🤯 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(goal): review every acceptance of a goal from its result page (#20270)
Arvin Xuf749df916454
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex ee6dd4fd6d8..bbdc257ad94 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -747,6 +747,11 @@ export class GoalService {* against — never the judgment. A reader could see that a task finished and* still have no idea whether it held up, which is the gap that made the page* feel unverifiable.+ *+ * Each level's tally rides along so the page can show its standing without+ * opening it. That tally is counted from the same check union the level+ * expands to (so a summary row can never contradict its own list), and it is+ * one batched read, never one per acceptance — this runs on every graph poll.*/private collectAcceptances = async (graph: GoalGraphSnapshot,@@ -762,11 +767,18 @@ export class GoalService {taskNodes.map((node) => node.taskId),);+ // An acceptance with no round yet is absent from the tally map, not zero —+ // keep "no round" and "judged nothing" apart on the page.+ const tallies = await this.acceptanceService.getCheckTalliesByAcceptances(+ rows.map((row) => row.id),+ );+const result: Record<string, GoalNodeAcceptance> = {};for (const row of rows) {const nodeId = nodeByTaskId.get(row.subjectId);if (!nodeId) continue;- result[nodeId] = { id: row.id, status: row.status };+ const checks = tallies.get(row.id);+ result[nodeId] = { id: row.id, status: row.status, ...(checks ? { checks } : {}) };}return Object.keys(result).length > 0 ? result : undefined;};diff --git a/apps/server/src/services/verify/__tests__/acceptanceTallies.test.ts b/apps/server/src/services/verify/__tests__/acceptanceTallies.test.tsnew file mode 100644index 00000000000..b16d5c0b146--- /dev/null+++ b/apps/server/src/services/verify/__tests__/acceptanceTallies.test.ts@@ -0,0 +1,135 @@+// @vitest-environment node+import { randomUUID } from 'node:crypto';++import type { LobeChatDatabase } from '@lobechat/database';+import { acceptances, users, verifyCheckResults, verifyRuns } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { AcceptanceService } from '../acceptanceService';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = `acceptance-tallies-${randomUUID()}`;+const otherUserId = `acceptance-tallies-other-${randomUUID()}`;++const planItem = (id: string) => ({+ id,+ index: 0,+ onFail: 'manual' as const,+ required: true,+ title: id,+ verifierConfig: {},+ verifierType: 'llm' as const,+});++const seedAcceptance = async (owner = userId) => {+ const [row] = await serverDB+ .insert(acceptances)+ .values({ subjectId: randomUUID(), subjectType: 'standalone', userId: owner })+ .returning();+ return row.id;+};++const seedRound = async (+ acceptanceId: string,+ roundIndex: number,+ plan: string[],+ results: [checkItemId: string, verdict: 'passed' | 'failed' | 'uncertain'][],+ owner = userId,+) => {+ const [run] = await serverDB+ .insert(verifyRuns)+ .values({+ acceptanceId,+ plan: plan.map(planItem),+ roundIndex,+ title: `round ${roundIndex}`,+ userId: owner,+ })+ .returning();++ if (results.length > 0)+ await serverDB.insert(verifyCheckResults).values(+ results.map(([checkItemId, verdict]) => ({+ checkItemId,+ // `uncertain` is a verdict, not a run status; the union reads the+ // verdict first, so the status only has to be a legal value.+ status: verdict === 'uncertain' ? ('running' as const) : verdict,+ userId: owner,+ verdict,+ verifierType: 'llm' as const,+ verifyRunId: run.id,+ })),+ );++ return run.id;+};++const talliesOf = (ids: string[]) =>+ new AcceptanceService(serverDB, userId).getCheckTalliesByAcceptances(ids);++beforeAll(async () => {+ await serverDB+ .insert(users)+ .values([{ id: userId }, { id: otherUserId }])+ .onConflictDoNothing();+});++afterAll(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+});++describe('AcceptanceService.getCheckTalliesByAcceptances', () => {+ it('tallies a repaired acceptance by its union, not by the repair round alone', async () => {+ const acceptanceId = await seedAcceptance();+ await seedRound(+ acceptanceId,+ 1,+ ['c1', 'c2'],+ [+ ['c1', 'passed'],+ ['c2', 'failed'],+ ],+ );+ // The repair round re-runs only the check it was asked to fix; c1 is+ // carried forward. Counting this round's own rows would report one passed+ // beside a list that expands to two.+ await seedRound(acceptanceId, 2, ['c1', 'c2'], [['c2', 'passed']]);++ const tallies = await talliesOf([acceptanceId]);++ expect(tallies.get(acceptanceId)).toEqual({ failed: 0, passed: 2, total: 2, unjudged: 0 });+ });++ it('leaves an acceptance with no round out of the map — absent is not zero', async () => {+ const withRun = await seedAcceptance();+ const withoutRun = await seedAcceptance();+ await seedRound(withRun, 1, ['c1'], [['c1', 'passed']]);++ const tallies = await talliesOf([withRun, withoutRun]);++ expect(tallies.has(withoutRun)).toBe(false);+ expect(tallies.get(withRun)).toEqual({ failed: 0, passed: 1, total: 1, unjudged: 0 });+ });++ it('counts a round that judged nothing as its planned checks, unjudged', async () => {+ const acceptanceId = await seedAcceptance();+ await seedRound(acceptanceId, 1, ['c1', 'c2'], []);++ const tallies = await talliesOf([acceptanceId]);++ // The level expands to two checks, so it says two — not nothing.+ expect(tallies.get(acceptanceId)).toEqual({ failed: 0, passed: 0, total: 2, unjudged: 2 });+ });++ it('never reads another user’s acceptances', async () => {+ const theirs = await seedAcceptance(otherUserId);+ await seedRound(theirs, 1, ['c1'], [['c1', 'passed']], otherUserId);++ const tallies = await talliesOf([theirs]);++ expect(tallies.size).toBe(0);+ });+});diff --git a/apps/server/src/services/verify/__tests__/acceptanceUnion.test.ts b/apps/server/src/services/verify/__tests__/acceptanceUnion.test.tsindex 6e9ed4a3f15..642e57ca6b0 100644--- a/apps/server/src/services/verify/__tests__/acceptanceUnion.test.ts+++ b/apps/server/src/services/verify/__tests__/acceptanceUnion.test.ts@@ -8,6 +8,7 @@ import {AcceptanceService,buildAcceptanceCheckUnion,buildCheckReviewOverlay,+ tallyCheckUnion,} from '../acceptanceService';// Union/grouping checks never execute tasks; keep that external runtime out of this suite.@@ -408,3 +409,41 @@ describe('buildAcceptanceCheckUnion', () => {expect(rows[0].category).toBe('未读区');});});++describe('tallyCheckUnion', () => {+ it('splits a union into passed / failed / unjudged', () => {+ const union = buildAcceptanceCheckUnion([+ {+ results: [result('c1', 'passed'), result('c2', 'failed'), result('c3', 'uncertain')],+ run: run('r1', 1, [planItem('c1'), planItem('c2'), planItem('c3'), planItem('c4')]),+ },+ ]);++ // c4 was planned and never ran: it is still a row of the union, so it counts.+ expect(tallyCheckUnion(union)).toEqual({ failed: 1, passed: 1, total: 4, unjudged: 2 });+ });++ it('counts a repaired acceptance by its union, not by the repair round alone', () => {+ // Round 1 judged both checks; round 2 was asked to fix c2, re-ran only that+ // one and carried c1 forward. Counting round 2's own result rows would put+ // "1 passed" on a row that expands to c1 AND c2.+ const union = buildAcceptanceCheckUnion([+ {+ results: [result('c1', 'passed'), result('c2', 'failed')],+ run: run('r1', 1, [planItem('c1'), planItem('c2')]),+ },+ { results: [result('c2', 'passed')], run: run('r2', 2, [planItem('c1'), planItem('c2')]) },+ ]);++ expect(tallyCheckUnion(union)).toEqual({ failed: 0, passed: 2, total: 2, unjudged: 0 });+ });++ it('counts a check re-run across rounds once', () => {+ const union = buildAcceptanceCheckUnion([+ { results: [result('c1', 'failed')], run: run('r1', 1, [planItem('c1')]) },+ { results: [result('c1', 'passed')], run: run('r2', 2, [planItem('c1')]) },+ ]);++ expect(tallyCheckUnion(union)).toEqual({ failed: 0, passed: 1, total: 1, unjudged: 0 });+ });+});diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.tsindex 3fceda9c534..eebf1610072 100644--- a/apps/server/src/services/verify/acceptanceService.ts+++ b/apps/server/src/services/verify/acceptanceService.ts@@ -12,6 +12,7 @@ import type {VerifyAgentPlanConfig,VerifyCheckDecisionDetail,VerifyCheckItem,+ VerifyCheckTally,VerifyRunDecisionDetail,VerifySurface,} from '@lobechat/types';@@ -279,6 +280,30 @@ export const buildAcceptanceCheckUnion = (return [...grouped.values(), ...[...rows.values()].filter((row) => !grouped.has(row.id))];};+/**+ * The union's own three-way split, counted — the number a summary can show+ * without opening the list.+ *+ * It counts UNION ROWS, not one round's result rows. A repair round re-runs the+ * check it was asked to fix and carries the rest forward, so the current round's+ * rows are a subset of the union: counting them would print "1 passed" beside a+ * list that expands to the repaired check plus everything it carried, and the+ * two readings of one acceptance would contradict each other.+ */+export const tallyCheckUnion = (checks: AcceptanceCheckRow[]): VerifyCheckTally => {+ let failed = 0;+ let passed = 0;+ let unjudged = 0;+ for (const check of checks) {+ if (check.state === 'passed') passed++;+ else if (check.state === 'failed') failed++;+ // `uncertain` and `not_executed` are both "planned, never judged" — the same+ // split the acceptance's criteria list draws.+ else unjudged++;+ }+ return { failed, passed, total: checks.length, unjudged };+};+// ============================================// User review overlay — the per-check human verdict layered onto the union.// An accept or ignore is sticky across rounds; a reject binds to the round it@@ -1466,4 +1491,50 @@ export class AcceptanceService {]);return { evidence, reports, results, runs };};++ /**+ * The union tally of several acceptances at once, counted from the SAME check+ * union each acceptance page renders (`tallyCheckUnion` over+ * `buildAcceptanceCheckUnion`), so a summary row and the list it expands to+ * can never disagree about what a round chain judged.+ *+ * Batched on purpose: a surface that summarises many acceptances runs on a+ * poll, so this is two statements regardless of how many it covers. An+ * acceptance with no round at all is ABSENT from the map — a caller must not+ * read "absent" as "nothing passed".+ */+ getCheckTalliesByAcceptances = async (+ acceptanceIds: string[],+ ): Promise<Map<string, VerifyCheckTally>> => {+ const ids = [...new Set(acceptanceIds.filter(Boolean))];+ const tallies = new Map<string, VerifyCheckTally>();+ if (ids.length === 0) return tallies;++ const runs = await this.runModel.listByAcceptances(ids);+ const results = await this.resultModel.listByRuns(runs.map((run) => run.id));++ const resultsByRun = new Map<string, VerifyCheckResultItem[]>();+ for (const result of results) {+ if (!result.verifyRunId) continue;+ const bucket = resultsByRun.get(result.verifyRunId) ?? [];+ bucket.push(result);+ resultsByRun.set(result.verifyRunId, bucket);+ }++ const runsByAcceptance = new Map<string, VerifyRunItem[]>();+ for (const run of runs) {+ if (!run.acceptanceId) continue;+ const bucket = runsByAcceptance.get(run.acceptanceId) ?? [];+ bucket.push(run);+ runsByAcceptance.set(run.acceptanceId, bucket);+ }++ for (const [acceptanceId, acceptanceRuns] of runsByAcceptance) {+ const checks = buildAcceptanceCheckUnion(+ acceptanceRuns.map((run) => ({ results: resultsByRun.get(run.id) ?? [], run })),+ );+ tallies.set(acceptanceId, tallyCheckUnion(checks));+ }+ return tallies;+ };}diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 9c9ec8b1f7a..79c7df6afa7 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -582,6 +582,34 @@"goalProcess.acceptance.rejected": "Rejected","goalProcess.acceptance.repairing": "Repairing","goalProcess.acceptance.verifying": "Verifying",+ "goalProcess.acceptanceHierarchy.accept": "Accept",+ "goalProcess.acceptanceHierarchy.acceptAll": "Accept all",+ "goalProcess.acceptanceHierarchy.acceptAllConfirm": "{{count}} acceptances will be accepted in one go. Each keeps its own result — this only records your sign-off.",+ "goalProcess.acceptanceHierarchy.acceptAllDone": "Accepted {{count}} acceptances",+ "goalProcess.acceptanceHierarchy.acceptAllPartial": "Accepted {{accepted}} · {{failed}} could not be signed off and were left as they were",+ "goalProcess.acceptanceHierarchy.acceptAllTitle": "Accept every waiting acceptance?",+ "goalProcess.acceptanceHierarchy.acceptError": "Could not save the sign-off. Try again.",+ "goalProcess.acceptanceHierarchy.accepted": "Accepted “{{title}}”",+ "goalProcess.acceptanceHierarchy.checksError": "Failed to load this acceptance’s checks",+ "goalProcess.acceptanceHierarchy.collapseAll": "Collapse all",+ "goalProcess.acceptanceHierarchy.criterion.failed": "Failed",+ "goalProcess.acceptanceHierarchy.criterion.passed": "Passed",+ "goalProcess.acceptanceHierarchy.criterion.unjudged": "Undecided",+ "goalProcess.acceptanceHierarchy.error": "Failed to load the acceptance levels, so no level’s standing can be read.",+ "goalProcess.acceptanceHierarchy.expandAll": "Expand all",+ "goalProcess.acceptanceHierarchy.group": "Related acceptances",+ "goalProcess.acceptanceHierarchy.level.awaitingSignOff": "Awaiting your sign-off",+ "goalProcess.acceptanceHierarchy.level.closed": "Closed",+ "goalProcess.acceptanceHierarchy.level.inProgress": "In progress",+ "goalProcess.acceptanceHierarchy.level.rejected": "Sent back",+ "goalProcess.acceptanceHierarchy.level.signedOff": "Signed off",+ "goalProcess.acceptanceHierarchy.level.unavailable": "No acceptance",+ "goalProcess.acceptanceHierarchy.noChecks": "This acceptance has no checks yet",+ "goalProcess.acceptanceHierarchy.retry": "Reload",+ "goalProcess.acceptanceHierarchy.tally.failed": "{{count}} failed",+ "goalProcess.acceptanceHierarchy.tally.passed": "{{count}} passed",+ "goalProcess.acceptanceHierarchy.tally.unjudged": "{{count}} undecided",+ "goalProcess.acceptanceHierarchy.taskNotDispatched": "This task has not been dispatched, so it has no acceptance yet.","goalProcess.activity.empty": "No activity yet","goalProcess.activity.finding": "Recorded finding: {{title}}","goalProcess.activity.title": "Activity",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 7418890615b..1da772abd02 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -582,6 +582,34 @@"goalProcess.acceptance.rejected": "验收未通过","goalProcess.acceptance.repairing": "修复中","goalProcess.acceptance.verifying": "验收中",+ "goalProcess.acceptanceHierarchy.accept": "验收通过",+ "goalProcess.acceptanceHierarchy.acceptAll": "全部验收通过",+ "goalProcess.acceptanceHierarchy.acceptAllConfirm": "将一次性验收通过 {{count}} 个验收。每个验收保留自身结果,这里只记录你的签署。",+ "goalProcess.acceptanceHierarchy.acceptAllDone": "已验收通过 {{count}} 个验收",+ "goalProcess.acceptanceHierarchy.acceptAllPartial": "已验收通过 {{accepted}} 个 · {{failed}} 个无法签署,已保持原状",+ "goalProcess.acceptanceHierarchy.acceptAllTitle": "全部验收通过?",+ "goalProcess.acceptanceHierarchy.acceptError": "验收未能保存,请重试。",+ "goalProcess.acceptanceHierarchy.accepted": "已验收通过「{{title}}」",+ "goalProcess.acceptanceHierarchy.checksError": "这个验收的检查项加载失败",+ "goalProcess.acceptanceHierarchy.collapseAll": "全部收起",+ "goalProcess.acceptanceHierarchy.criterion.failed": "未通过",+ "goalProcess.acceptanceHierarchy.criterion.passed": "已通过",+ "goalProcess.acceptanceHierarchy.criterion.unjudged": "未判定",+ "goalProcess.acceptanceHierarchy.error": "验收层级加载失败,无法判断各层级的判定状态。",+ "goalProcess.acceptanceHierarchy.expandAll": "全部展开",+ "goalProcess.acceptanceHierarchy.group": "关联验收",+ "goalProcess.acceptanceHierarchy.level.awaitingSignOff": "等你验收",+ "goalProcess.acceptanceHierarchy.level.closed": "已关闭",+ "goalProcess.acceptanceHierarchy.level.inProgress": "进行中",+ "goalProcess.acceptanceHierarchy.level.rejected": "已打回",+ "goalProcess.acceptanceHierarchy.level.signedOff": "你已验收",+ "goalProcess.acceptanceHierarchy.level.unavailable": "没有验收",+ "goalProcess.acceptanceHierarchy.noChecks": "这个验收还没有检查项",+ "goalProcess.acceptanceHierarchy.retry": "重新加载",+ "goalProcess.acceptanceHierarchy.tally.failed": "{{count}} 项未通过",+ "goalProcess.acceptanceHierarchy.tally.passed": "{{count}} 项通过",+ "goalProcess.acceptanceHierarchy.tally.unjudged": "{{count}} 项未判定",+ "goalProcess.acceptanceHierarchy.taskNotDispatched": "这个任务还没有被派发,因此还没有验收。","goalProcess.activity.empty": "暂无活动","goalProcess.activity.finding": "沉淀结论:{{title}}","goalProcess.activity.title": "活动",diff --git a/packages/database/src/models/__tests__/verifyRun.test.ts b/packages/database/src/models/__tests__/verifyRun.test.tsindex 66b14d363cc..4129b0939b4 100644--- a/packages/database/src/models/__tests__/verifyRun.test.ts+++ b/packages/database/src/models/__tests__/verifyRun.test.ts@@ -1,4 +1,6 @@// @vitest-environment node+import { randomUUID } from 'node:crypto';+import { eq, sql } from 'drizzle-orm';import { beforeEach, describe, expect, it } from 'vitest';@@ -383,3 +385,60 @@ describe('VerifyRunModel.foldIntoRound', () => {await expect(model().foldIntoRound(chained.id, draft.id)).rejects.toThrow('detached');});});++describe('VerifyRunModel.listByAcceptances', () => {+ const item = (id: string) => ({+ id,+ index: 0,+ onFail: 'manual' as const,+ required: true,+ title: id,+ verifierConfig: {},+ verifierType: 'llm' as const,+ });++ const buildAcceptance = async (owner = userId) => {+ const [row] = await serverDB+ .insert(acceptances)+ .values({ subjectId: randomUUID(), subjectType: 'standalone', userId: owner })+ .returning();+ return row.id;+ };++ it('returns the rounds of several acceptances in one read', async () => {+ const first = await buildAcceptance();+ const second = await buildAcceptance();+ const model = new VerifyRunModel(serverDB, userId);+ await model.create({ acceptanceId: first, plan: [item('c1')], roundIndex: 1, title: 'a1' });+ await model.create({ acceptanceId: first, plan: [item('c1')], roundIndex: 2, title: 'a2' });+ await model.create({ acceptanceId: second, plan: [item('c1')], roundIndex: 1, title: 'b1' });++ const runs = await model.listByAcceptances([first, second]);++ expect(runs.map((run) => `${run.acceptanceId}#${run.roundIndex}`).sort()).toEqual(+ [`${first}#1`, `${first}#2`, `${second}#1`].sort(),+ );+ });++ it('returns nothing for an empty id list', async () => {+ const model = new VerifyRunModel(serverDB, userId);++ expect(await model.listByAcceptances([])).toEqual([]);+ });++ it('never reads another user’s rounds', async () => {+ const mine = await buildAcceptance();+ const theirs = await buildAcceptance(otherUserId);+ const theirsRun = await new VerifyRunModel(serverDB, otherUserId).create({+ acceptanceId: theirs,+ plan: [item('c1')],+ roundIndex: 1,+ title: 'theirs',+ });++ const runs = await new VerifyRunModel(serverDB, userId).listByAcceptances([mine, theirs]);++ expect(runs.some((run) => run.id === theirsRun.id)).toBe(false);+ expect(runs.every((run) => run.acceptanceId === mine)).toBe(true);+ });+});diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.tsindex 895af643367..3c58b5b5a06 100644--- a/packages/database/src/models/verifyRun.ts+++ b/packages/database/src/models/verifyRun.ts@@ -288,6 +288,25 @@ export class VerifyRunModel {);};+ /**+ * Every round of several acceptances at once, in round order — the batched+ * form of `listByAcceptance`.+ *+ * Feeds a surface that summarises many acceptances on a poll: one statement+ * regardless of how many it covers. A caller wanting each acceptance's+ * standing counts it from the check union (`AcceptanceService`), so the+ * summary and the list it expands to read the same rows.+ */+ listByAcceptances = async (acceptanceIds: string[]): Promise<VerifyRunItem[]> => {+ const ids = [...new Set(acceptanceIds.filter(Boolean))];+ if (ids.length === 0) return [];++ return this.db.query.verifyRuns.findMany({+ orderBy: [asc(verifyRuns.roundIndex)],+ where: and(inArray(verifyRuns.acceptanceId, ids), this.ownership()),+ });+ };+/** Every round chained onto an acceptance aggregate, in round order. */listByAcceptance = async (acceptanceId: string): Promise<VerifyRunItem[]> => {return this.db.query.verifyRuns.findMany({diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 1099b674d4d..e3f11c013f7 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2035,6 +2035,38 @@ export default {'goalDetail.taskStatus': 'Execution status','goalDetail.unnamedRun': 'Untitled run','goalDetail.viewPlan': 'View execution plan',+ 'goalProcess.acceptanceHierarchy.accept': 'Accept',+ 'goalProcess.acceptanceHierarchy.acceptAll': 'Accept all',+ 'goalProcess.acceptanceHierarchy.acceptAllConfirm':+ '{{count}} acceptances will be accepted in one go. Each keeps its own result — this only records your sign-off.',+ 'goalProcess.acceptanceHierarchy.acceptAllDone': 'Accepted {{count}} acceptances',+ 'goalProcess.acceptanceHierarchy.acceptAllPartial':+ 'Accepted {{accepted}} · {{failed}} could not be signed off and were left as they were',+ 'goalProcess.acceptanceHierarchy.acceptAllTitle': 'Accept every waiting acceptance?',+ 'goalProcess.acceptanceHierarchy.acceptError': 'Could not save the sign-off. Try again.',+ 'goalProcess.acceptanceHierarchy.accepted': 'Accepted “{{title}}”',+ 'goalProcess.acceptanceHierarchy.checksError': 'Failed to load this acceptance’s checks',+ 'goalProcess.acceptanceHierarchy.collapseAll': 'Collapse all',+ 'goalProcess.acceptanceHierarchy.criterion.failed': 'Failed',+ 'goalProcess.acceptanceHierarchy.criterion.passed': 'Passed',+ 'goalProcess.acceptanceHierarchy.criterion.unjudged': 'Undecided',+ 'goalProcess.acceptanceHierarchy.error':+ 'Failed to load the acceptance levels, so no level’s standing can be read.',+ 'goalProcess.acceptanceHierarchy.expandAll': 'Expand all',+ 'goalProcess.acceptanceHierarchy.group': 'Related acceptances',+ 'goalProcess.acceptanceHierarchy.level.awaitingSignOff': 'Awaiting your sign-off',+ 'goalProcess.acceptanceHierarchy.level.closed': 'Closed',+ 'goalProcess.acceptanceHierarchy.level.inProgress': 'In progress',+ 'goalProcess.acceptanceHierarchy.level.rejected': 'Sent back',+ 'goalProcess.acceptanceHierarchy.level.signedOff': 'Signed off',+ 'goalProcess.acceptanceHierarchy.level.unavailable': 'No acceptance',+ 'goalProcess.acceptanceHierarchy.noChecks': 'This acceptance has no checks yet',+ 'goalProcess.acceptanceHierarchy.retry': 'Reload',+ 'goalProcess.acceptanceHierarchy.tally.failed': '{{count}} failed',+ 'goalProcess.acceptanceHierarchy.tally.passed': '{{count}} passed',+ 'goalProcess.acceptanceHierarchy.tally.unjudged': '{{count}} undecided',+ 'goalProcess.acceptanceHierarchy.taskNotDispatched':+ 'This task has not been dispatched, so it has no acceptance yet.','goalProcess.frontier.title': 'Current tasks','goalProcess.northStar.emptyHint': 'No measurable target declared yet','goalProcess.northStar.met': 'Met',diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex 263cb4302ab..3b1620c3a6e 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -1,6 +1,6 @@import type { GoalReportDispatch, GoalReportState } from './goalReport';import type { InitialGoalOverviewContext } from './stepContext';-import type { AcceptanceStatus } from './verify';+import type { AcceptanceStatus, VerifyCheckTally } from './verify';import type { WorkType } from './work';// ============================================@@ -548,6 +548,13 @@ export interface GoalGraphWorkVersionDisplay {/** Where a task node's own verification stands, for a reader scanning the goal. */export interface GoalNodeAcceptance {+ /**+ * The acceptance's current round, counted. Read in the same batched pass as+ * the rows themselves so a surface can show each level's standing without+ * opening it; absent when the acceptance has no round yet, which is not the+ * same as a round that judged nothing.+ */+ checks?: VerifyCheckTally;id: string;status: AcceptanceStatus;}diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.tsindex 94a971f9907..d1e6cfe26eb 100644--- a/packages/types/src/verify.ts+++ b/packages/types/src/verify.ts@@ -775,6 +775,25 @@ export interface VerifyCheckResultMetadata {visualization?: VerifyVisualizationManifest;}+/**+ * How one round's checks came out, counted — what a surface shows as+ * "3 passed · 1 undecided" without reading the checks themselves.+ *+ * Deliberately the same three-way split the acceptance's criteria list uses+ * (`CriterionOutcomeState`): a check with no verdict falls back to its status,+ * and everything else is undecided. Two surfaces reading the same round must+ * not be able to disagree about it.+ */+export interface VerifyCheckTally {+ /** Judged failed — a failed verdict, or a failed status where no verdict landed. */+ failed: number;+ /** Judged passed — a passed verdict, or a passed status where no verdict landed. */+ passed: number;+ total: number;+ /** Planned but never judged: neither passed nor failed. */+ unjudged: number;+}+/*** Immutable snapshot of one check item, frozen into `agent_operations.verify_plan`* when the plan is confirmed. The resolved content (title / verifierConfig) isdiff --git a/src/features/Acceptance/CriterionList/index.ts b/src/features/Acceptance/CriterionList/index.tsindex 030be206df5..91abce00585 100644--- a/src/features/Acceptance/CriterionList/index.ts+++ b/src/features/Acceptance/CriterionList/index.ts@@ -5,4 +5,5 @@ export {CriterionRequiredChip,CriterionRow,type CriterionRowProps,+ rowKeyDownHandler,} from './CriterionRow';diff --git a/src/features/Acceptance/Viewer/useAcceptanceBundle.ts b/src/features/Acceptance/Viewer/useAcceptanceBundle.tsindex 1d5289c16a3..e0d618788de 100644--- a/src/features/Acceptance/Viewer/useAcceptanceBundle.ts+++ b/src/features/Acceptance/Viewer/useAcceptanceBundle.ts@@ -11,7 +11,18 @@ const ACCEPTANCE_BUNDLE_SWR_CONFIG = {revalidateOnReconnect: true,} as const;-export const useAcceptanceBundle = (acceptanceId: string | null) => {+/**+ * The acceptance bundle, revalidating on focus/reconnect as a live decision+ * surface.+ *+ * `poll: false` is for a surface that reads a bundle only as a DETAIL view —+ * the goal result page opens one per task row — where the live 5s poll would+ * run one interval per opened row. Such a surface keeps focus/reconnect+ * revalidation (returning to the tab still refreshes) and leaves the always-on+ * polling to the acceptance page itself.+ */+export const useAcceptanceBundle = (acceptanceId: string | null, options?: { poll?: boolean }) => {+ const poll = options?.poll ?? true;const swr = useClientDataSWR(acceptanceId ? verifyKeys.acceptanceBundle(acceptanceId) : null,() => verifyService.getAcceptanceBundle(acceptanceId!),@@ -20,10 +31,11 @@ export const useAcceptanceBundle = (acceptanceId: string | null) => {const status = swr.data?.acceptance.status;useEffect(() => {+ if (!poll) return;if (!status || !LIVE_ACCEPTANCE_STATUSES.has(status)) return;const timer = setInterval(() => void swr.mutate(), 5000);return () => clearInterval(timer);- }, [status, swr.mutate]);+ }, [poll, status, swr.mutate]);return swr;};diff --git a/src/features/Acceptance/index.ts b/src/features/Acceptance/index.tsindex bef7cf6dcea..e1baa03724a 100644--- a/src/features/Acceptance/index.ts+++ b/src/features/Acceptance/index.ts@@ -7,6 +7,7 @@ export {type CriterionRowProps,openCriterionEditModal,type OpenCriterionEditModalProps,+ rowKeyDownHandler,} from './CriterionList';export {useAcceptanceBundle,diff --git a/src/features/AgentGoals/ProcessControl/GoalAcceptanceHierarchy.tsx b/src/features/AgentGoals/ProcessControl/GoalAcceptanceHierarchy.tsxnew file mode 100644index 00000000000..363a89c42ea--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/GoalAcceptanceHierarchy.tsx@@ -0,0 +1,502 @@+'use client';++import type { VerifyCheckTally } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import { ActionIcon, Button, Skeleton, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import {+ BadgeCheck,+ CheckCheck,+ CheckCircle2,+ ChevronDown,+ ChevronRight,+ ChevronsDownUp,+ ChevronsUpDown,+ CircleDot,+ CircleSlash,+ CircleX,+ RotateCcw,+} from 'lucide-react';+import { memo, type ReactNode, useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import {+ type AcceptanceCheck,+ checkDisplayTitle,+ checkHeadMeta,+ CriterionRow,+ rowKeyDownHandler,+ useAcceptanceBundle,+} from '@/features/Acceptance';+import { useChatStore } from '@/store/chat';++import type { AcceptanceLevelState, AcceptanceTree } from './goalAcceptanceTree';+import { GroupLabel } from './GoalResultFollowUps';+import { useAcceptanceSignOff } from './useAcceptanceSignOff';++const styles = createStaticStyles(({ css }) => ({+ /* One row per level. The row itself is the expand target (the acceptance+ page's own criterion-row grammar), so the level's title, its sign-off, its+ count and the chevron are all inside one clickable band. */+ row: css`+ display: flex;+ gap: 10px;+ align-items: center;++ width: 100%;+ min-height: 38px;+ padding-block: 8px;+ padding-inline: 12px 6px;++ &:not(:last-child) {+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ }++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }++ /* The sign-off appears under the pointer, the way the acceptance page's own+ per-group accept does: a permanently visible button on every waiting row+ turns the list into a column of buttons and begs a misclick. */+ &:hover .acc-hierarchy-action {+ opacity: 1;+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -2px;+ }+ `,+ rowToggle: css`+ cursor: pointer;++ display: flex;+ flex: 1;+ gap: 10px;+ align-items: center;++ min-width: 0;+ padding: 0;+ border: none;++ color: inherit;+ text-align: start;++ background: none;+ `,+ /* Hover-revealed, and held visible while its own request is in flight: a+ spinner that disappears the moment the pointer leaves reads as "nothing+ happened". */+ levelAction: css`+ flex: none;+ opacity: 0;+ transition: opacity 0.15s;++ &:focus-within,+ &[data-pending='true'] {+ opacity: 1;+ }+ `,+ /* The task's position in the Goal graph, the same handle the process view+ refers to it by — quiet, but a step above the faintest tone so a row can+ still be read back and pointed at. */+ seq: css`+ flex: none;+ min-width: 22px;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ /* Sized to its own text, so what follows it — the sign-off — sits directly+ after the title rather than out at the row's trailing edge. It still gives+ way (truncating) when the title is the long thing on the row. */+ title: css`+ overflow: hidden;+ flex: 0 1 auto;++ min-width: 0;++ font-size: 14px;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ /* Everything after the sign-off is right-aligned: the count is the row's own+ trailing meta, not a neighbour of the title. */+ spacer: css`+ flex: 1 1 0;+ min-width: 0;+ `,+ /* A level with nothing produced yet drops one step of text colour. A failed+ level keeps full weight: a failure is a result, an absence is not. */+ titleQuiet: css`+ color: ${cssVar.colorTextSecondary};+ `,+ meta: css`+ flex: none;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ /* Check rows keep the acceptance page's own list grammar, so opening a level+ and opening the acceptance read as the same list.++ The offset is exactly the level row's icon column — its 16px mark plus the+ 10px gap — so a check's mark lines up under the level's `#N`. The nesting+ reads from the sequence and the mark, not from a second indent. */+ nestedList: css`+ margin-block-end: 4px;+ margin-inline-start: 26px;+ `,+ /* "Nothing verified this" replaces a check list, so it starts on the same+ column as the checks' own marks — not a second indent. */+ empty: css`+ padding-block: 10px;+ padding-inline: 38px 12px;+ font-size: 13px;+ color: ${cssVar.colorTextTertiary};+ `,+ error: css`+ padding-block: 10px;+ padding-inline: 14px;+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorErrorBg};+ `,+}));++/** A level's own state, as a glyph. Never derived from the levels beneath it. */+const LEVEL_GLYPH: Record<AcceptanceLevelState, typeof CircleDot> = {+ awaitingSignOff: CheckCircle2,+ closed: CircleSlash,+ inProgress: CircleDot,+ rejected: CircleX,+ signedOff: BadgeCheck,+ unavailable: CircleSlash,+};++const levelColor = (state: AcceptanceLevelState) =>+ state === 'awaitingSignOff'+ ? cssVar.colorSuccess+ : state === 'signedOff'+ ? cssVar.colorPrimary+ : state === 'rejected'+ ? cssVar.colorError+ : state === 'inProgress'+ ? cssVar.colorInfo+ : cssVar.colorTextTertiary;++const LEVEL_LABEL_KEY: Record<AcceptanceLevelState, string> = {+ awaitingSignOff: 'goalProcess.acceptanceHierarchy.level.awaitingSignOff',+ closed: 'goalProcess.acceptanceHierarchy.level.closed',+ inProgress: 'goalProcess.acceptanceHierarchy.level.inProgress',+ rejected: 'goalProcess.acceptanceHierarchy.level.rejected',+ signedOff: 'goalProcess.acceptanceHierarchy.level.signedOff',+ unavailable: 'goalProcess.acceptanceHierarchy.level.unavailable',+};++/** Counts read as words, never as a raw `3/4` fraction. */+const useTallyText = () => {+ const { t } = useTranslation('chat');+ return useCallback(+ (checks?: VerifyCheckTally) => {+ if (!checks) return undefined;+ const parts = [+ checks.passed > 0 &&+ t('goalProcess.acceptanceHierarchy.tally.passed', { count: checks.passed }),+ checks.unjudged > 0 &&+ t('goalProcess.acceptanceHierarchy.tally.unjudged', { count: checks.unjudged }),+ checks.failed > 0 &&+ t('goalProcess.acceptanceHierarchy.tally.failed', { count: checks.failed }),+ ].filter(Boolean);+ return parts.length > 0 ? parts.join(' · ') : undefined;+ },+ [t],+ );+};++interface LevelRowProps {+ /** Trailing level-scoped control — the one-click sign-off, when it applies. */+ action?: ReactNode;+ chevron: typeof ChevronRight;+ dim?: boolean;+ meta?: string;+ onToggle: () => void;+ /** The task's position in the Goal graph, so a row can be pointed at. */+ seq?: string;+ state: AcceptanceLevelState;+ title: string;+}++const LevelRow = memo<LevelRowProps>(+ ({ action, chevron, dim, meta, onToggle, seq, state, title }) => {+ const { t } = useTranslation('chat');+ return (+ <div className={cx(styles.row, 'acc-hierarchy-row')}>+ <div+ aria-expanded={chevron === ChevronDown}+ className={styles.rowToggle}+ role={'button'}+ tabIndex={0}+ onClick={onToggle}+ onKeyDown={rowKeyDownHandler(onToggle)}+ >+ <Icon+ aria-label={t(LEVEL_LABEL_KEY[state] as any)}+ color={levelColor(state)}+ icon={LEVEL_GLYPH[state]}+ size={16}+ style={{ flex: 'none' }}+ />+ {seq && <span className={styles.seq}>{seq}</span>}+ <span className={cx(styles.title, dim && styles.titleQuiet)}>{title}</span>+ {action}+ <span className={styles.spacer} />+ {meta && <span className={styles.meta}>{meta}</span>}+ <Icon+ color={cssVar.colorTextQuaternary}+ icon={chevron}+ size={15}+ style={{ flex: 'none' }}+ />+ </div>+ </div>+ );+ },+);+LevelRow.displayName = 'AcceptanceLevelRow';++/**+ * The checks a task's acceptance was judged on, read when the level is opened.+ *+ * Loaded on demand on purpose: the hierarchy's counts come from the graph+ * snapshot, so opening one level costs one bundle instead of the page fetching+ * every task's checks up front.+ *+ * No live poll here. This is a detail view inside a summary, and "expand all"+ * mounts one of these per task — the acceptance page's 5s poll would become one+ * interval per opened row. The tallies stay current because they ride the graph+ * poll, and the surface still revalidates on focus/reconnect.+ */+const TaskChecks = memo<{ acceptanceId: string; onOpenCheck: (checkId: string) => void }>(+ ({ acceptanceId, onOpenCheck }) => {+ const { t } = useTranslation(['chat', 'verify']);+ const { data, error, isLoading, mutate } = useAcceptanceBundle(acceptanceId, { poll: false });+ const checks = data?.checks ?? [];++ if (isLoading && !data)+ return (+ <Flexbox className={styles.nestedList} gap={8} paddingBlock={10} paddingInline={12}>+ {[0, 1, 2].map((index) => (+ <Skeleton height={14} key={index} radius={4} width={`${40 + index * 12}%`} />+ ))}+ </Flexbox>+ );++ // A failed read must not read as "this acceptance has no checks".+ if (error)+ return (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.error}+ gap={8}+ justify={'space-between'}+ >+ <Text fontSize={12} style={{ flex: 1 }} type={'danger'}>+ {t('goalProcess.acceptanceHierarchy.checksError')}+ </Text>+ <Button+ icon={<Icon icon={RotateCcw} />}+ size={'small'}+ type={'text'}+ onClick={() => void mutate()}+ >+ {t('goalProcess.acceptanceHierarchy.retry')}+ </Button>+ </Flexbox>+ );++ if (checks.length === 0)+ return <div className={styles.empty}>{t('goalProcess.acceptanceHierarchy.noChecks')}</div>;++ return (+ /* Flat, indented rows — the same grammar as the level rows above. An+ outlined card here put its rounded top corner flush under the level+ row's own separator, so the two lines read as one broken edge. */+ <div className={styles.nestedList}>+ {checks.map((check: AcceptanceCheck) => {+ const meta = checkHeadMeta(check);+ return (+ <CriterionRow+ icon={<Icon color={meta.color} icon={meta.icon} size={16} style={{ flex: 'none' }} />}+ key={check.id}+ seq={check.seq}+ title={checkDisplayTitle(+ check.title,+ t('acceptance.checks.holisticTitle', { ns: 'verify' }),+ )}+ onOpen={() => onOpenCheck(check.id)}+ />+ );+ })}+ </div>+ );+ },+);+TaskChecks.displayName = 'AcceptanceTaskChecks';++export interface GoalAcceptanceHierarchyProps {+ /**+ * Whether the viewer may sign off. The page reads it from the goal-level+ * acceptance's bundle, which is the only permission the graph does not carry;+ * the tasks belong to the same goal and workspace, so they answer the same.+ */+ canReview: boolean;+ goalId: string;+ tree: AcceptanceTree;+}++/**+ * The per-task acceptance group of the result page's 验收标准 section: one row+ * per task that holds an acceptance of its own, each with its OWN tally,+ * opening in place to the checks it was judged on.+ *+ * Every row and every tally rides on the goal graph snapshot the page has+ * already loaded, so this renders with the page instead of adding a second+ * loading state beside it.+ *+ * Sign-off is offered at the two granularities the reader works at, and both+ * act on the level's OWN acceptance — never on a level derived from it:+ *+ * - a waiting row signs itself off under the pointer, and+ * - the group signs off every waiting row in one action.+ *+ * Two things this deliberately does NOT do:+ *+ * - It does not restate the goal-level acceptance. That is the criteria list+ * above, under its own group label, with per-check evidence and reasons; a+ * tally row here would state the same result twice. Signed off from here,+ * the goal-level acceptance would also be a second home for the page's own+ * decision strip — so the group action stops at the task rows it lists.+ * - It does not count a level the server did not count. A task with no round+ * yet shows no tally rather than a row of zeroes.+ */+const GoalAcceptanceHierarchy = memo<GoalAcceptanceHierarchyProps>(+ ({ canReview, goalId, tree }) => {+ const { t } = useTranslation('chat');+ const openAcceptanceCheck = useChatStore((state) => state.openAcceptanceCheck);+ const tallyText = useTallyText();+ const [expanded, setExpanded] = useState<Set<string>>(() => new Set());+ const { acceptAll, acceptLevel, awaiting, pendingKey } = useAcceptanceSignOff(+ goalId,+ tree.tasks,+ );++ const toggle = useCallback((key: string) => {+ setExpanded((previous) => {+ const next = new Set(previous);+ if (next.has(key)) next.delete(key);+ else next.add(key);+ return next;+ });+ }, []);++ const taskKeys = useMemo(() => tree.tasks.map((level) => level.key), [tree]);+ const allExpanded = taskKeys.length > 0 && taskKeys.every((key) => expanded.has(key));++ // No task holds an acceptance: the criteria list already carries the goal's+ // own result, so this group is absent rather than an empty heading.+ if (tree.tasks.length === 0) return null;++ const groupActions =+ (canReview && awaiting.length > 0) || taskKeys.length > 1 ? (+ <Flexbox horizontal align={'center'} gap={4}>+ {canReview && awaiting.length > 0 && (+ <Button+ icon={<Icon icon={CheckCheck} />}+ size={'small'}+ type={'text'}+ onClick={acceptAll}+ >+ {t('goalProcess.acceptanceHierarchy.acceptAll')}+ </Button>+ )}+ {taskKeys.length > 1 && (+ <ActionIcon+ icon={allExpanded ? ChevronsDownUp : ChevronsUpDown}+ size={'small'}+ aria-label={t(+ allExpanded+ ? 'goalProcess.acceptanceHierarchy.collapseAll'+ : 'goalProcess.acceptanceHierarchy.expandAll',+ )}+ title={t(+ allExpanded+ ? 'goalProcess.acceptanceHierarchy.collapseAll'+ : 'goalProcess.acceptanceHierarchy.expandAll',+ )}+ onClick={() => setExpanded(allExpanded ? new Set() : new Set(taskKeys))}+ />+ )}+ </Flexbox>+ ) : undefined;++ return (+ <Flexbox gap={8}>+ <GroupLabel extra={groupActions}>{t('goalProcess.acceptanceHierarchy.group')}</GroupLabel>+ <Flexbox>+ {tree.tasks.map((level) => (+ <Flexbox key={level.key}>+ <LevelRow+ chevron={expanded.has(level.key) ? ChevronDown : ChevronRight}+ dim={level.state === 'unavailable'}+ meta={tallyText(level.checks)}+ seq={level.node.seq ? `#${level.node.seq}` : undefined}+ state={level.state}+ title={level.node.node.title}+ action={+ canReview && level.state === 'awaitingSignOff' && level.acceptanceId ? (+ <span+ className={cx(styles.levelAction, 'acc-hierarchy-action')}+ data-pending={pendingKey === level.key || undefined}+ >+ <Button+ disabled={pendingKey !== null && pendingKey !== level.key}+ icon={<Icon icon={BadgeCheck} />}+ loading={pendingKey === level.key}+ size={'small'}+ type={'text'}+ // The sign-off sits inside the row's own expand target;+ // acting on it must not also fold the level.+ onClick={(event) => {+ event.stopPropagation();+ void acceptLevel(level);+ }}+ >+ {t('goalProcess.acceptanceHierarchy.accept')}+ </Button>+ </span>+ ) : undefined+ }+ onToggle={() => toggle(level.key)}+ />+ {expanded.has(level.key) &&+ (level.acceptanceId ? (+ <TaskChecks+ acceptanceId={level.acceptanceId}+ onOpenCheck={(checkId) => openAcceptanceCheck(level.acceptanceId!, checkId)}+ />+ ) : (+ <div className={styles.empty}>+ {t('goalProcess.acceptanceHierarchy.taskNotDispatched')}+ </div>+ ))}+ </Flexbox>+ ))}+ </Flexbox>+ </Flexbox>+ );+ },+);++GoalAcceptanceHierarchy.displayName = 'GoalAcceptanceHierarchy';++export default GoalAcceptanceHierarchy;diff --git a/src/features/AgentGoals/ProcessControl/GoalCriteriaResults.tsx b/src/features/AgentGoals/ProcessControl/GoalCriteriaResults.tsxindex a7e86b65f18..4a14adeeb0c 100644--- a/src/features/AgentGoals/ProcessControl/GoalCriteriaResults.tsx+++ b/src/features/AgentGoals/ProcessControl/GoalCriteriaResults.tsx@@ -11,7 +11,7 @@ import {FileText,Paperclip,} from 'lucide-react';-import { useState } from 'react';+import { type ReactNode, useState } from 'react';import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';@@ -249,6 +249,8 @@ const CriterionRow = ({ index, outcome }: { index: number; outcome: CriterionOut};interface GoalCriteriaResultsProps {+ /** The per-task acceptance group, rendered as this section's continuation. */+ children?: ReactNode;/** The acceptance or criteria read failed: its outcomes are not a result. */error?: unknown;loading: boolean;@@ -256,7 +258,13 @@ interface GoalCriteriaResultsProps {outcomes: CriterionOutcome[];}-const GoalCriteriaResults = ({ error, loading, onRetry, outcomes }: GoalCriteriaResultsProps) => {+const GoalCriteriaResults = ({+ children,+ error,+ loading,+ onRetry,+ outcomes,+}: GoalCriteriaResultsProps) => {const { t } = useTranslation('chat');const met = outcomes.filter((outcome) => outcome.state === 'passed').length;@@ -293,6 +301,7 @@ const GoalCriteriaResults = ({ error, loading, onRetry, outcomes }: GoalCriteria))}</Flexbox>)}+ {children}</Flexbox>);};diff --git a/src/features/AgentGoals/ProcessControl/GoalResult.tsx b/src/features/AgentGoals/ProcessControl/GoalResult.tsxindex a6de1f7a7fc..4765e4597e8 100644--- a/src/features/AgentGoals/ProcessControl/GoalResult.tsx+++ b/src/features/AgentGoals/ProcessControl/GoalResult.tsx@@ -2,7 +2,7 @@import { Flexbox, Markdown } from '@lobehub/ui';import { Divider, Skeleton } from '@lobehub/ui/base-ui';-import { useRef } from 'react';+import { useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { useEntityMarkdown } from '@/features/EntityLink';@@ -10,7 +10,9 @@ import { useClientDataSWR } from '@/libs/swr';import { portalKeys } from '@/libs/swr/keys';import { documentService } from '@/services/document';+import GoalAcceptanceHierarchy from './GoalAcceptanceHierarchy';import { pickFinalDeliverable } from './goalAcceptanceReport';+import { buildAcceptanceTree } from './goalAcceptanceTree';import GoalCriteriaResults from './GoalCriteriaResults';import type { GoalGraphView } from './goalGraphViewModel';import { GoalDecisionsMade, GoalUnfinished, useContinueFromResult } from './GoalResultFollowUps';@@ -74,6 +76,7 @@ const GoalResult = ({ graph, onSelect }: GoalResultProps) => {const deliverable = pickFinalDeliverable(graph.artifacts, acceptanceNodeId);const data = useGoalResultData(graph);const continueFromResult = useContinueFromResult(graph, data.outcomes);+ const acceptanceTree = useMemo(() => buildAcceptanceTree(graph), [graph]);return (<div ref={rootRef}>@@ -106,7 +109,15 @@ const GoalResult = ({ graph, onSelect }: GoalResultProps) => {loading={data.isLoading}outcomes={data.outcomes}onRetry={data.retry}- />+ >+ {/* The goal's own acceptance IS the criteria list above; every task's+ acceptance follows it as the second group of the same section. */}+ <GoalAcceptanceHierarchy+ canReview={data.canReview}+ goalId={graph.goal.id}+ tree={acceptanceTree}+ />+ </GoalCriteriaResults></div></Flexbox><Divider style={{ marginBlock: 24 }} />diff --git a/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx b/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsxindex e6244dddd24..242b1e2e650 100644--- a/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx+++ b/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx@@ -59,6 +59,16 @@ export const SectionTitle = ({ children, extra }: { children: ReactNode; extra?:</Flexbox>);+/** A group inside a section — one step below `SectionTitle`, same row grammar. */+export const GroupLabel = ({ children, extra }: { children: ReactNode; extra?: ReactNode }) => (+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Text fontSize={13} type={'secondary'} weight={600}>+ {children}+ </Text>+ {extra}+ </Flexbox>+);+const DecisionTime = ({ at }: { at: Date }) => {const { text, title } = useActivityTime(at);return (diff --git a/src/features/AgentGoals/ProcessControl/goalAcceptanceTree.test.ts b/src/features/AgentGoals/ProcessControl/goalAcceptanceTree.test.tsnew file mode 100644index 00000000000..ce9256b5294--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/goalAcceptanceTree.test.ts@@ -0,0 +1,139 @@+import { GOAL_ACCEPTANCE_TASK_TITLE, GOAL_REPORT_TASK_TITLE } from '@lobechat/const/goal';+import { describe, expect, it } from 'vitest';++import { buildAcceptanceTree, hasAcceptanceTree } from './goalAcceptanceTree';+import type { GoalGraphView, GoalNodeView } from './goalGraphViewModel';+import { countGoalTasks } from './goalResultState';++const REPORT_NODE_ID = 'node-report';++const acceptanceNode = (+ id: string,+ status: string,+ {+ // `null` is the explicit "no acceptance"; the default fires only for+ // `undefined`, so it cannot be used to express it.+ acceptance = { id: `acc-${id}`, status } as GoalNodeView['acceptance'],+ title = id,+ }: { acceptance?: GoalNodeView['acceptance'] | null; title?: string } = {},+): GoalNodeView =>+ ({+ acceptance: acceptance ?? undefined,+ node: { id, kind: 'task', status: 'resolved', title },+ }) as unknown as GoalNodeView;++const graph = (nodes: GoalNodeView[]): GoalGraphView =>+ ({+ byId: Object.fromEntries(nodes.map((view) => [view.node.id, view])),+ goal: { config: { report: { nodeId: REPORT_NODE_ID } }, status: 'achieved' },+ nodes,+ }) as unknown as GoalGraphView;++const goalLevel = (status: string) =>+ acceptanceNode('node-goal-acceptance', status, {+ title: GOAL_ACCEPTANCE_TASK_TITLE,+ });++const reportTask = () =>+ acceptanceNode(REPORT_NODE_ID, 'accepted', { title: GOAL_REPORT_TASK_TITLE });++describe('buildAcceptanceTree', () => {+ it('把目标级验收放在任务级验收之上', () => {+ const tree = buildAcceptanceTree(+ graph([+ acceptanceNode('t1', 'accepted'),+ acceptanceNode('t2', 'delivered'),+ goalLevel('delivered'),+ reportTask(),+ ]),+ );++ expect(tree.goal?.key).toBe('node-goal-acceptance');+ expect(tree.goal?.state).toBe('awaitingSignOff');+ expect(tree.tasks.map((level) => level.key)).toEqual(['t1', 't2']);+ });++ it('只列工作任务:验收任务与总结任务不属于层级里的任务级', () => {+ const view = graph([+ acceptanceNode('t1', 'accepted'),+ acceptanceNode('t2', 'accepted'),+ goalLevel('accepted'),+ reportTask(),+ ]);++ // 与页面别处统计任务规模的口径一致 —— 两处不能各数各的。+ expect(buildAcceptanceTree(view).tasks).toHaveLength(countGoalTasks(view));+ });++ it('状态映射:已交付/出错等决策,已通过即已验收', () => {+ const tree = buildAcceptanceTree(+ graph([+ acceptanceNode('delivered', 'delivered'),+ acceptanceNode('errored', 'errored'),+ acceptanceNode('accepted', 'accepted'),+ acceptanceNode('rejected', 'rejected'),+ acceptanceNode('verifying', 'verifying'),+ acceptanceNode('pending', 'pending'),+ acceptanceNode('closed', 'closed'),+ ]),+ );++ expect(tree.tasks.map((level) => level.state)).toEqual([+ 'awaitingSignOff',+ 'awaitingSignOff',+ 'signedOff',+ 'rejected',+ 'inProgress',+ 'inProgress',+ 'closed',+ ]);+ });++ it('未派发的任务读作「没有验收」,而不是通过', () => {+ const tree = buildAcceptanceTree(+ graph([+ acceptanceNode('t1', 'accepted'),+ acceptanceNode('never-ran', 'pending', { acceptance: null }),+ ]),+ );++ const undispatched = tree.tasks.find((level) => level.key === 'never-ran');+ expect(undispatched?.state).toBe('unavailable');+ expect(undispatched?.acceptanceId).toBeUndefined();+ });++ it('回归:目标级状态取它自己的验收状态,不由子项推导', () => {+ // 子任务被打了回,但目标级验收还没被判定 —— 层级顶部必须仍然是+ // 「等你验收」,不能因为下面有失败就自己变红。+ const tree = buildAcceptanceTree(+ graph([acceptanceNode('t1', 'rejected'), goalLevel('delivered')]),+ );++ expect(tree.goal?.state).toBe('awaitingSignOff');+ });++ it('回归:没有验收就没有层级,不用空树冒充满足条件的树', () => {+ const tree = buildAcceptanceTree(+ graph([acceptanceNode('never-ran', 'pending', { acceptance: null })]),+ );++ expect(tree.goal).toBeUndefined();+ expect(hasAcceptanceTree(tree)).toBe(true);+ expect(hasAcceptanceTree(buildAcceptanceTree(graph([])))).toBe(false);+ });++ it('带上当前轮的计数,没有轮次的验收不带', () => {+ const withChecks = acceptanceNode('t1', 'delivered', {+ acceptance: {+ checks: { failed: 1, passed: 3, total: 4, unjudged: 0 },+ id: 'acc-t1',+ status: 'delivered',+ } as GoalNodeView['acceptance'],+ });++ const tree = buildAcceptanceTree(graph([withChecks, acceptanceNode('t2', 'pending')]));++ expect(tree.tasks[0].checks).toEqual({ failed: 1, passed: 3, total: 4, unjudged: 0 });+ expect(tree.tasks[1].checks).toBeUndefined();+ });+});diff --git a/src/features/AgentGoals/ProcessControl/goalAcceptanceTree.ts b/src/features/AgentGoals/ProcessControl/goalAcceptanceTree.tsnew file mode 100644index 00000000000..e22a28beaa6--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/goalAcceptanceTree.ts@@ -0,0 +1,107 @@+import type { AcceptanceStatus, VerifyCheckTally } from '@lobechat/types';++import { isGoalAcceptanceTask } from './coordinatorCopy';+import type { GoalGraphView, GoalNodeView } from './goalGraphViewModel';+import { findGoalAcceptanceView, isGoalReportTaskView } from './goalResultState';++/**+ * Where a level in the acceptance hierarchy stands.+ *+ * A level's state is always its OWN acceptance status — never a roll-up of the+ * levels under it. The goal-level acceptance and a task's acceptance are+ * independent judgments, so deriving one from the other would state a rule the+ * product never decided and let the tree contradict the page header above it.+ */+export type AcceptanceLevelState =+ 'awaitingSignOff' | 'closed' | 'inProgress' | 'rejected' | 'signedOff' | 'unavailable';++/**+ * The acceptance lifecycle, folded onto what a reviewer needs to do about it.+ *+ * `delivered` and `errored` land together on purpose: a settled round and an+ * inconclusive one both wait on the owner, and the decision strip the tree sits+ * above treats them the same way.+ */+const LEVEL_STATE_BY_STATUS: Record<AcceptanceStatus, AcceptanceLevelState> = {+ accepted: 'signedOff',+ closed: 'closed',+ delivered: 'awaitingSignOff',+ errored: 'awaitingSignOff',+ pending: 'inProgress',+ planned: 'inProgress',+ rejected: 'rejected',+ repairing: 'inProgress',+ verifying: 'inProgress',+};++export interface AcceptanceLevel {+ /** The acceptance behind this level; absent when the node has none yet. */+ acceptanceId?: string;+ /** The acceptance's current round, counted. Absent when it has no round yet. */+ checks?: VerifyCheckTally;+ /** Stable key for expansion state — the node id. */+ key: string;+ node: GoalNodeView;+ state: AcceptanceLevelState;+}++export interface AcceptanceTree {+ /**+ * The goal-level acceptance — the one sign-off acts on. Absent until the+ * terminal acceptance task exists.+ */+ goal?: AcceptanceLevel;+ /**+ * The work tasks' own acceptances, in the order the graph numbers its tasks.+ * A task that was never dispatched has no acceptance and still appears, as+ * `unavailable` — "nothing verified this" must not read as "this passed".+ */+ tasks: AcceptanceLevel[];+}++const levelOf = (view: GoalNodeView, key: string): AcceptanceLevel => {+ const { acceptance } = view;+ if (!acceptance) return { key, node: view, state: 'unavailable' };++ return {+ acceptanceId: acceptance.id,+ ...(acceptance.checks ? { checks: acceptance.checks } : {}),+ key,+ node: view,+ state: LEVEL_STATE_BY_STATUS[acceptance.status] ?? 'inProgress',+ };+};++/**+ * The Goal's acceptances as one hierarchy: the goal-level acceptance over the+ * acceptances of the tasks that were dispatched to serve it.+ *+ * The relation already exists in the graph — the terminal Goal-acceptance task+ * and the work tasks are nodes of the same graph — so this only reads it out.+ * Every level is generated from what the graph snapshot already carries; no+ * level is inferred from another level's result.+ */+export const buildAcceptanceTree = (graph: GoalGraphView): AcceptanceTree => {+ const goalView = findGoalAcceptanceView(graph);+ const taskViews = graph.nodes.filter(+ (view) =>+ view.node.kind === 'task' &&+ !isGoalAcceptanceTask(view) &&+ !isGoalReportTaskView(graph, view),+ );++ return {+ ...(goalView ? { goal: levelOf(goalView, goalView.node.id) } : {}),+ tasks: taskViews.map((view) => levelOf(view, view.node.id)),+ };+};++/**+ * Whether the tree has anything to draw.+ *+ * Counts the levels the page can name, not their verdicts: a goal whose+ * acceptance exists but has not run yet has a hierarchy worth showing — every+ * level simply reads as still in progress.+ */+export const hasAcceptanceTree = (tree: AcceptanceTree): boolean =>+ Boolean(tree.goal) || tree.tasks.length > 0;diff --git a/src/features/AgentGoals/ProcessControl/useAcceptanceSignOff.test.ts b/src/features/AgentGoals/ProcessControl/useAcceptanceSignOff.test.tsnew file mode 100644index 00000000000..f79b7c920bc--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/useAcceptanceSignOff.test.ts@@ -0,0 +1,184 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { AcceptanceLevel } from './goalAcceptanceTree';+import type { GoalNodeView } from './goalGraphViewModel';+import { useAcceptanceSignOff } from './useAcceptanceSignOff';++const mocks = vi.hoisted(() => ({+ acceptDelivery: vi.fn(),+ confirmModal: vi.fn(),+ refreshGoalGraph: vi.fn(),+ toastError: vi.fn(),+ toastSuccess: vi.fn(),+ toastWarning: vi.fn(),+ updateAcceptanceStatusBatch: vi.fn(),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: Record<string, unknown>) => {+ if (!options) return key;+ return `${key}::${Object.entries(options)+ .map(([name, value]) => `${name}=${value}`)+ .join(',')}`;+ },+ }),+}));++vi.mock('@lobehub/ui/base-ui', () => ({+ confirmModal: (...args: unknown[]) => mocks.confirmModal(...args),+ toast: {+ error: (...args: unknown[]) => mocks.toastError(...args),+ success: (...args: unknown[]) => mocks.toastSuccess(...args),+ warning: (...args: unknown[]) => mocks.toastWarning(...args),+ },+}));++vi.mock('@/services/verify', () => ({+ verifyService: {+ acceptDelivery: (...args: unknown[]) => mocks.acceptDelivery(...args),+ updateAcceptanceStatusBatch: (...args: unknown[]) => mocks.updateAcceptanceStatusBatch(...args),+ },+}));++vi.mock('@/store/goal', () => ({+ useGoalStore: (selector: (state: Record<string, unknown>) => unknown) =>+ selector({ refreshGoalGraph: mocks.refreshGoalGraph }),+}));++const level = (+ title: string,+ state: AcceptanceLevel['state'],+ extra: { acceptanceId?: string } = {},+): AcceptanceLevel =>+ ({+ ...(extra.acceptanceId ? { acceptanceId: extra.acceptanceId } : {}),+ key: title,+ node: { node: { id: title, title } } as unknown as GoalNodeView,+ state,+ }) as AcceptanceLevel;++const waiting = level('CF Sandbox', 'awaitingSignOff', { acceptanceId: 'acc-wait' });+const alsoWaiting = level('JSON contract', 'awaitingSignOff', { acceptanceId: 'acc-wait-2' });+const done = level('Tables', 'signedOff', { acceptanceId: 'acc-done' });+const running = level('Router', 'inProgress', { acceptanceId: 'acc-live' });+const unDispatched = level('Later', 'unavailable');++const sweepConfig = () => mocks.confirmModal.mock.calls[0][0] as { onOk: () => Promise<void> };++describe('useAcceptanceSignOff', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.acceptDelivery.mockResolvedValue(undefined);+ mocks.updateAcceptanceStatusBatch.mockResolvedValue({ failedIds: [], updated: 0 });+ });++ it('lists only the levels waiting on the owner', () => {+ const { result } = renderHook(() =>+ useAcceptanceSignOff('goal-1', [waiting, done, running, unDispatched, alsoWaiting]),+ );++ expect(result.current.awaiting).toEqual([waiting, alsoWaiting]);+ });++ it('signs off the level it is given and refreshes the graph', async () => {+ const { result } = renderHook(() => useAcceptanceSignOff('goal-1', [waiting]));++ await act(() => result.current.acceptLevel(waiting));++ expect(mocks.acceptDelivery).toHaveBeenCalledWith('acc-wait');+ expect(mocks.toastSuccess).toHaveBeenCalledWith(+ expect.objectContaining({ title: expect.stringContaining('CF Sandbox') }),+ );+ expect(mocks.refreshGoalGraph).toHaveBeenCalledWith('goal-1');+ expect(result.current.pendingKey).toBeNull();+ });++ it('reports a failed sign-off and keeps the level as it was', async () => {+ mocks.acceptDelivery.mockRejectedValueOnce(new Error('nope'));+ const { result } = renderHook(() => useAcceptanceSignOff('goal-1', [waiting]));++ await act(() => result.current.acceptLevel(waiting));++ expect(mocks.toastSuccess).not.toHaveBeenCalled();+ expect(mocks.toastError).toHaveBeenCalledWith('goalProcess.acceptanceHierarchy.acceptError');+ expect(mocks.refreshGoalGraph).not.toHaveBeenCalled();+ expect(result.current.pendingKey).toBeNull();+ });++ it('sweeps every waiting level through the batch endpoint after a confirmation', async () => {+ mocks.updateAcceptanceStatusBatch.mockResolvedValue({ failedIds: [], updated: 2 });+ const { result } = renderHook(() =>+ useAcceptanceSignOff('goal-1', [waiting, done, alsoWaiting]),+ );++ act(() => result.current.acceptAll());+ expect(mocks.updateAcceptanceStatusBatch).not.toHaveBeenCalled();++ await act(() => sweepConfig().onOk());++ // Only the levels the owner can actually sign off — never a decided or live one.+ expect(mocks.updateAcceptanceStatusBatch).toHaveBeenCalledWith(+ ['acc-wait', 'acc-wait-2'],+ 'accepted',+ );+ // A clean sweep reports once, on the success channel.+ expect(mocks.toastSuccess).toHaveBeenCalledTimes(1);+ expect(mocks.toastSuccess).toHaveBeenCalledWith(+ expect.objectContaining({ title: expect.stringContaining('count=2') }),+ );+ expect(mocks.toastWarning).not.toHaveBeenCalled();+ expect(mocks.refreshGoalGraph).toHaveBeenCalledWith('goal-1');+ });++ it('reports a partial sweep in ONE toast, naming both halves', async () => {+ mocks.updateAcceptanceStatusBatch.mockResolvedValue({ failedIds: ['acc-wait'], updated: 1 });+ const { result } = renderHook(() => useAcceptanceSignOff('goal-1', [waiting, alsoWaiting]));++ act(() => result.current.acceptAll());+ await act(() => sweepConfig().onOk());++ // One action, one report: a single toast carries what landed AND what did not.+ expect(mocks.toastWarning).toHaveBeenCalledTimes(1);+ expect(mocks.toastWarning).toHaveBeenCalledWith(+ expect.objectContaining({+ title: expect.stringContaining('accepted=1,failed=1'),+ }),+ );+ expect(mocks.toastSuccess).not.toHaveBeenCalled();+ expect(mocks.toastError).not.toHaveBeenCalled();+ });++ it('never opens a sweep when nothing is waiting', () => {+ const { result } = renderHook(() => useAcceptanceSignOff('goal-1', [done, running]));++ act(() => result.current.acceptAll());++ expect(mocks.confirmModal).not.toHaveBeenCalled();+ expect(mocks.updateAcceptanceStatusBatch).not.toHaveBeenCalled();+ });++ it('keeps the other rows usable while one sign-off is in flight', async () => {+ let release = () => {};+ mocks.acceptDelivery.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ release = resolve;+ }),+ );+ const { result } = renderHook(() => useAcceptanceSignOff('goal-1', [waiting]));++ let pending: Promise<void> | undefined;+ act(() => {+ pending = result.current.acceptLevel(waiting);+ });+ await waitFor(() => expect(result.current.pendingKey).toBe(waiting.key));++ await act(async () => {+ release();+ await pending;+ });+ expect(result.current.pendingKey).toBeNull();+ });+});diff --git a/src/features/AgentGoals/ProcessControl/useAcceptanceSignOff.ts b/src/features/AgentGoals/ProcessControl/useAcceptanceSignOff.tsnew file mode 100644index 00000000000..e1ad4861965--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/useAcceptanceSignOff.ts@@ -0,0 +1,108 @@+import { confirmModal, toast } from '@lobehub/ui/base-ui';+import { useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { verifyService } from '@/services/verify';+import { useGoalStore } from '@/store/goal';++import type { AcceptanceLevel } from './goalAcceptanceTree';++/** Only a level the server can decide is one the owner can sign off. */+const isAcceptable = (level: AcceptanceLevel) =>+ level.state === 'awaitingSignOff' && Boolean(level.acceptanceId);++export interface AcceptanceSignOff {+ acceptAll: () => void;+ acceptLevel: (level: AcceptanceLevel) => Promise<void>;+ /** The waiting levels a sweep would sign off, in the order the tree lists them. */+ awaiting: AcceptanceLevel[];+ /** The level whose own sign-off is in flight, so only that row spins. */+ pendingKey: string | null;+}++/**+ * Sign-off for the acceptance hierarchy: one level at a time, or every waiting+ * level in one sweep.+ *+ * Both act on each level's OWN acceptance. A sweep is N independent decisions+ * taken together — never a verdict computed from the levels beneath, and never+ * the goal-level acceptance, which the page signs off in its own decision strip.+ */+export const useAcceptanceSignOff = (+ goalId: string,+ tasks: AcceptanceLevel[],+): AcceptanceSignOff => {+ const { t } = useTranslation('chat');+ const refreshGoalGraph = useGoalStore((state) => state.refreshGoalGraph);+ const [pendingKey, setPendingKey] = useState<string | null>(null);++ const acceptLevel = useCallback(+ async (level: AcceptanceLevel) => {+ if (!level.acceptanceId) return;+ setPendingKey(level.key);+ try {+ await verifyService.acceptDelivery(level.acceptanceId);+ toast.success({+ placement: 'top',+ title: t('goalProcess.acceptanceHierarchy.accepted', { title: level.node.node.title }),+ });+ await refreshGoalGraph(goalId);+ } catch (cause) {+ console.error('[goal:acceptance-sign-off]', cause);+ toast.error(t('goalProcess.acceptanceHierarchy.acceptError'));+ } finally {+ setPendingKey(null);+ }+ },+ [goalId, refreshGoalGraph, t],+ );++ const awaiting = useMemo(() => tasks.filter(isAcceptable), [tasks]);++ const acceptAll = useCallback(() => {+ const ids = awaiting.map((level) => level.acceptanceId!);+ if (ids.length === 0) return;++ // Sweeping several deliveries at once is worth confirming. The server+ // reports per row what landed rather than voiding the rest when one of them+ // cannot be decided, so the confirmation is about the size of the decision,+ // not about guarding against a partial failure.+ confirmModal({+ cancelText: t('goalProcess.result.signOff.cancel'),+ content: t('goalProcess.acceptanceHierarchy.acceptAllConfirm', { count: ids.length }),+ okText: t('goalProcess.acceptanceHierarchy.acceptAll'),+ title: t('goalProcess.acceptanceHierarchy.acceptAllTitle'),+ onOk: async () => {+ try {+ const { failedIds, updated } = await verifyService.updateAcceptanceStatusBatch(+ ids,+ 'accepted',+ );+ // One sweep is one report, however it went: a partial outcome says+ // both halves in a single toast. Two toasts for one action read as two+ // separate events, and the second one's duration decides how long the+ // first stays legible.+ if (failedIds.length > 0)+ toast.warning({+ placement: 'top',+ title: t('goalProcess.acceptanceHierarchy.acceptAllPartial', {+ accepted: updated,+ failed: failedIds.length,+ }),+ });+ else if (updated > 0)+ toast.success({+ placement: 'top',+ title: t('goalProcess.acceptanceHierarchy.acceptAllDone', { count: updated }),+ });+ await refreshGoalGraph(goalId);+ } catch (cause) {+ console.error('[goal:acceptance-sign-off:sweep]', cause);+ toast.error(t('goalProcess.acceptanceHierarchy.acceptError'));+ }+ },+ });+ }, [awaiting, goalId, refreshGoalGraph, t]);++ return { acceptAll, acceptLevel, awaiting, pendingKey };+};