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(goal): review the delivery report before signing off a goal (#21773)

Arvin Xu0ce8daa996c8
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 99f7f2775ca..749019b4c6a 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1196,10 +1196,9 @@
"goalProcess.signOff.accepted": "Signed off",
"goalProcess.signOff.description": "Goal-level acceptance passed. Your sign-off closes the goal.",
"goalProcess.signOff.islandSubtitle": "is done and waiting for your sign-off",
- "goalProcess.signOff.notePlaceholder": "What should change? The Agent reworks the delivery with this.",
- "goalProcess.signOff.question": "Do you accept what this goal delivered?",
+ "goalProcess.signOff.islandSummary": "Goal-level acceptance passed. Read the delivery report, then sign off or request changes.",
+ "goalProcess.signOff.openReport": "View details",
"goalProcess.signOff.requestChanges": "Request changes",
- "goalProcess.signOff.requestChangesEffect": "Send it back to the Agent. Say what to change in the notes.",
"goalProcess.signOff.sentBack": "Sent back for changes",
"goalProcess.stalled.description": "Last heartbeat {{duration}}. The next advance restarts this attempt — it does not count as a failure.",
"goalProcess.start": "Start",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 6a863216c92..4c5592a5868 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1196,10 +1196,9 @@
"goalProcess.signOff.accepted": "已签收",
"goalProcess.signOff.description": "目标验收已通过,你签收后目标正式结束。",
"goalProcess.signOff.islandSubtitle": "已完成,等你签收",
- "goalProcess.signOff.notePlaceholder": "要改什么?Agent 会按这里的说明返工",
- "goalProcess.signOff.question": "这个目标的交付你认可吗?",
+ "goalProcess.signOff.islandSummary": "目标验收已通过。先看交付报告,再决定签收或提出修改。",
+ "goalProcess.signOff.openReport": "查看详情",
"goalProcess.signOff.requestChanges": "提出修改",
- "goalProcess.signOff.requestChangesEffect": "退回给 Agent 重做,在补充说明里写要改什么",
"goalProcess.signOff.sentBack": "已退回修改",
"goalProcess.stalled.description": "上次心跳在 {{duration}}。下一次推进会重开这次尝试,不计失败次数。",
"goalProcess.start": "启动",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index c7a6e793e9e..7a601f0e736 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2666,15 +2666,13 @@ export default {
'goalProcess.decision.effect.releaseBatch':
'Release the next wave on the current recipe. Each later wave goes to the main Agent, which releases it or brings it back to you.',
'goalProcess.signOff.islandSubtitle': 'is done and waiting for your sign-off',
- 'goalProcess.signOff.question': 'Do you accept what this goal delivered?',
+ 'goalProcess.signOff.islandSummary':
+ 'Goal-level acceptance passed. Read the delivery report, then sign off or request changes.',
+ 'goalProcess.signOff.openReport': 'View details',
'goalProcess.signOff.description': 'Goal-level acceptance passed. Your sign-off closes the goal.',
'goalProcess.signOff.accept': 'Sign off',
'goalProcess.signOff.acceptEffect': 'Close the goal as delivered.',
'goalProcess.signOff.requestChanges': 'Request changes',
- 'goalProcess.signOff.requestChangesEffect':
- 'Send it back to the Agent. Say what to change in the notes.',
- 'goalProcess.signOff.notePlaceholder':
- 'What should change? The Agent reworks the delivery with this.',
'goalProcess.signOff.accepted': 'Signed off',
'goalProcess.signOff.sentBack': 'Sent back for changes',
'goalProcess.gate.title.agentQuestion': "Answer the main Agent's question",
diff --git a/src/features/AgentGoals/ProcessControl/FinalDocument.tsx b/src/features/AgentGoals/ProcessControl/FinalDocument.tsx
new file mode 100644
index 00000000000..070d31f575c
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/FinalDocument.tsx
@@ -0,0 +1,33 @@
+'use client';
+
+import { Flexbox, Markdown, Skeleton } from '@lobehub/ui';
+
+import { useEntityMarkdown } from '@/features/EntityLink';
+import { useDocumentStore } from '@/store/document';
+
+/** The document the Goal's work wrote, read in full as the delivery itself. */
+const FinalDocument = ({ documentId }: { documentId: string }) => {
+ // The graph carries only the document id; its content is read for the page.
+ const markdownProps = useEntityMarkdown();
+ const useFetchDocumentDetail = useDocumentStore((s) => s.useFetchDocumentDetail);
+ const { data: document, isHydrated, isLoading } = useFetchDocumentDetail(documentId);
+
+ if (isLoading && !isHydrated) return null;
+ if (isLoading)
+ return (
+ <Flexbox gap={10}>
+ <Skeleton height={24} radius={4} width={'40%'} />
+ <Skeleton height={14} radius={4} />
+ <Skeleton height={14} radius={4} />
+ <Skeleton height={14} radius={4} width={'70%'} />
+ </Flexbox>
+ );
+
+ return (
+ <Markdown variant={'chat'} {...markdownProps}>
+ {document?.content ?? ''}
+ </Markdown>
+ );
+};
+
+export default FinalDocument;
diff --git a/src/features/AgentGoals/ProcessControl/GoalResult.tsx b/src/features/AgentGoals/ProcessControl/GoalResult.tsx
index 6dbe2a2b106..86632d6c043 100644
--- a/src/features/AgentGoals/ProcessControl/GoalResult.tsx
+++ b/src/features/AgentGoals/ProcessControl/GoalResult.tsx
@@ -1,12 +1,10 @@
'use client';
-import { Divider, Flexbox, Markdown, Skeleton } from '@lobehub/ui';
+import { Divider, Flexbox } from '@lobehub/ui';
import { useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
-import { useEntityMarkdown } from '@/features/EntityLink';
-import { useDocumentStore } from '@/store/document';
-
+import FinalDocument from './FinalDocument';
import GoalAcceptanceHierarchy from './GoalAcceptanceHierarchy';
import { pickFinalDeliverable } from './goalAcceptanceReport';
import { buildAcceptanceTree } from './goalAcceptanceTree';
@@ -38,30 +36,6 @@ import { useGoalResultData } from './useGoalResultData';
* to them on click — see `ResultAnchorRail`.
*/
-const FinalDocument = ({ documentId }: { documentId: string }) => {
- // The graph carries only the document id; its content is read for the page.
- const markdownProps = useEntityMarkdown();
- const useFetchDocumentDetail = useDocumentStore((s) => s.useFetchDocumentDetail);
- const { data: document, isHydrated, isLoading } = useFetchDocumentDetail(documentId);
-
- if (isLoading && !isHydrated) return null;
- if (isLoading)
- return (
- <Flexbox gap={10}>
- <Skeleton height={24} radius={4} width={'40%'} />
- <Skeleton height={14} radius={4} />
- <Skeleton height={14} radius={4} />
- <Skeleton height={14} radius={4} width={'70%'} />
- </Flexbox>
- );
-
- return (
- <Markdown variant={'chat'} {...markdownProps}>
- {document?.content ?? ''}
- </Markdown>
- );
-};
-
interface GoalResultProps {
graph: GoalGraphView;
onSelect: (nodeId: string) => void;
diff --git a/src/features/AgentGoals/SignOffReport/SignOffDigest.tsx b/src/features/AgentGoals/SignOffReport/SignOffDigest.tsx
new file mode 100644
index 00000000000..b5645642d23
--- /dev/null
+++ b/src/features/AgentGoals/SignOffReport/SignOffDigest.tsx
@@ -0,0 +1,103 @@
+'use client';
+
+import { Flexbox, Icon, Skeleton, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { CircleCheck, CircleDashed, CircleX } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ buildGoalGraphView,
+ type GoalGraphView,
+} from '@/features/AgentGoals/ProcessControl/goalGraphViewModel';
+import {
+ type CriterionOutcomeState,
+ goalResultHeadline,
+} from '@/features/AgentGoals/ProcessControl/goalResultState';
+import { useGoalResultData } from '@/features/AgentGoals/ProcessControl/useGoalResultData';
+import { goalSelectors, useGoalStore } from '@/store/goal';
+
+const STATE_ICON: Record<CriterionOutcomeState, typeof CircleCheck> = {
+ failed: CircleX,
+ passed: CircleCheck,
+ unjudged: CircleDashed,
+};
+
+const styles = stylex.create({
+ criteria: {
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ borderBlockStartStyle: 'solid',
+ borderBlockStartWidth: 1,
+ paddingBlockStart: 8,
+ },
+ failed: { color: cssVar.colorError },
+ passed: { color: cssVar.colorSuccess },
+ unjudged: { color: cssVar.colorTextQuaternary },
+});
+
+/**
+ * What a finished goal delivered, small enough for the island: the result
+ * headline the wrap-up wrote and each criterion against the goal-level
+ * acceptance. The owner reads it where they are; the full report — HTML page,
+ * document, evidence — is one 「查看详情」 away.
+ */
+const SignOffDigest = ({ goalId }: { goalId: string }) => {
+ const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);
+ useFetchGoalGraph(goalId);
+ const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
+ const graph = useMemo(() => (snapshot ? buildGoalGraphView(snapshot) : undefined), [snapshot]);
+
+ if (!graph)
+ return (
+ <Flexbox gap={8}>
+ <Skeleton height={18} radius={4} width={'70%'} />
+ <Skeleton height={14} radius={4} />
+ <Skeleton height={14} radius={4} width={'60%'} />
+ </Flexbox>
+ );
+
+ return <DigestBody graph={graph} />;
+};
+
+const DigestBody = ({ graph }: { graph: GoalGraphView }) => {
+ const { t } = useTranslation('chat');
+ const { isLoading, outcomes } = useGoalResultData(graph);
+ const headline = goalResultHeadline(graph);
+ const met = outcomes.filter((outcome) => outcome.state === 'passed').length;
+
+ return (
+ <Flexbox gap={8}>
+ {headline ? (
+ <Text style={{ lineHeight: 1.5 }} weight={500}>
+ {headline}
+ </Text>
+ ) : (
+ <Text type={'secondary'}>{t('goalProcess.signOff.islandSummary')}</Text>
+ )}
+ {isLoading ? (
+ <Skeleton height={14} radius={4} width={'60%'} />
+ ) : (
+ outcomes.length > 0 && (
+ <Flexbox gap={4} {...stylex.props(styles.criteria)}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('goalProcess.result.scale.criteria', { met, total: outcomes.length })}
+ </Text>
+ {outcomes.map(({ criterion, state }) => (
+ <Flexbox horizontal align={'center'} gap={6} key={criterion.id}>
+ <span {...stylex.props(styles[state])}>
+ <Icon icon={STATE_ICON[state]} size={14} />
+ </span>
+ <Text ellipsis fontSize={13}>
+ {criterion.title}
+ </Text>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ )
+ )}
+ </Flexbox>
+ );
+};
+
+export default SignOffDigest;
diff --git a/src/features/AgentGoals/SignOffReport/SignOffReport.tsx b/src/features/AgentGoals/SignOffReport/SignOffReport.tsx
new file mode 100644
index 00000000000..3e1ebf682c6
--- /dev/null
+++ b/src/features/AgentGoals/SignOffReport/SignOffReport.tsx
@@ -0,0 +1,210 @@
+'use client';
+
+import { ActionIcon, Button, Flexbox, Skeleton, Text, useModalContext } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ArrowUpRight, X } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { GoalDecisionAsker } from '@/features/AgentGoals/GoalDecision';
+import FinalDocument from '@/features/AgentGoals/ProcessControl/FinalDocument';
+import { pickFinalDeliverable } from '@/features/AgentGoals/ProcessControl/goalAcceptanceReport';
+import GoalCriteriaResults from '@/features/AgentGoals/ProcessControl/GoalCriteriaResults';
+import { buildGoalGraphView } from '@/features/AgentGoals/ProcessControl/goalGraphViewModel';
+import GoalReportPage from '@/features/AgentGoals/ProcessControl/GoalReportPage';
+import {
+ findFinalAcceptanceView,
+ goalReportPageId,
+ goalResultHeadline,
+} from '@/features/AgentGoals/ProcessControl/goalResultState';
+import { openRequestChangesModal } from '@/features/AgentGoals/ProcessControl/RequestChangesModal';
+import { useGoalResultData } from '@/features/AgentGoals/ProcessControl/useGoalResultData';
+import { goalSelectors, useGoalStore } from '@/store/goal';
+
+import { useGoalSignOff } from './useGoalSignOff';
+
+const styles = stylex.create({
+ // The same action band as the gate report: one tinted strip the decision
+ // lives in, apart from the report it decides on.
+ footer: {
+ alignItems: 'center',
+ backgroundColor: `color-mix(in srgb, ${cssVar.colorBgElevated} 92%, ${cssVar.colorFillSecondary})`,
+ borderBlockStartColor: cssVar.colorBorder,
+ borderBlockStartStyle: 'solid',
+ borderBlockStartWidth: 1,
+ display: 'flex',
+ gap: 12,
+ paddingBlock: 12,
+ paddingInline: 24,
+ },
+ frame: {
+ display: 'flex',
+ flexDirection: 'column',
+ maxHeight: '84vh',
+ overflow: 'hidden',
+ },
+ header: {
+ alignItems: 'center',
+ borderBlockEndColor: cssVar.colorBorder,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ display: 'flex',
+ gap: 8,
+ paddingBlock: 12,
+ paddingInline: 24,
+ },
+ // Sized by its content and shrunk to the frame's max height: a zero basis
+ // in a column with no definite height collapses the report to nothing.
+ scroll: {
+ flexBasis: 'auto',
+ flexGrow: 1,
+ flexShrink: 1,
+ minHeight: 0,
+ overflowY: 'auto',
+ paddingBlock: 24,
+ paddingInline: 24,
+ },
+ title: {
+ fontSize: cssVar.fontSizeHeading4,
+ fontWeight: 600,
+ lineHeight: 1.4,
+ margin: 0,
+ },
+});
+
+export interface GoalSignOffReportProps {
+ acceptanceId: string;
+ agentId?: string | null;
+ goalId: string;
+ goalTitle: string;
+ /** The sign-off landed either way; re-read whatever listed it. */
+ onDecided?: () => Promise<unknown> | void;
+ /** Leave for the goal page — the modal host sits outside the router. */
+ onOpenGoal?: () => void;
+}
+
+/**
+ * A finished Goal's delivery, read before it is signed off: the headline and
+ * HTML report the wrap-up wrote, the document the work produced, and each
+ * criterion against what the goal-level acceptance found. The decision sits in
+ * the band under it, so nobody signs a delivery they have not been shown.
+ */
+const GoalSignOffReport = ({
+ acceptanceId,
+ agentId,
+ goalId,
+ goalTitle,
+ onDecided,
+ onOpenGoal,
+}: GoalSignOffReportProps) => {
+ const { t } = useTranslation('chat');
+ const { close } = useModalContext();
+
+ const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);
+ useFetchGoalGraph(goalId);
+ const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));
+ const graph = useMemo(() => (snapshot ? buildGoalGraphView(snapshot) : undefined), [snapshot]);
+
+ const { accept, pending, requestChanges } = useGoalSignOff({
+ acceptanceId,
+ onClose: close,
+ onDecided,
+ });
+
+ return (
+ <div {...stylex.props(styles.frame)}>
+ <div {...stylex.props(styles.header)}>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <GoalDecisionAsker
+ agentId={agentId}
+ category={'judgment'}
+ subtitle={t('goalProcess.signOff.islandSubtitle')}
+ />
+ </div>
+ {onOpenGoal && (
+ <ActionIcon
+ icon={ArrowUpRight}
+ size={'small'}
+ title={t('goalProcess.clarify.openGoal')}
+ onClick={() => {
+ close();
+ onOpenGoal();
+ }}
+ />
+ )}
+ <ActionIcon icon={X} size={'small'} title={t('close', { ns: 'common' })} onClick={close} />
+ </div>
+ <div {...stylex.props(styles.scroll)}>
+ <Flexbox gap={24}>
+ <Flexbox gap={8}>
+ <h3 {...stylex.props(styles.title)}>{goalTitle}</h3>
+ <Text type={'secondary'}>{t('goalProcess.result.signOff.prompt')}</Text>
+ </Flexbox>
+ {graph ? (
+ <DeliveryBody graph={graph} />
+ ) : (
+ <Flexbox gap={10}>
+ <Skeleton height={24} radius={4} width={'40%'} />
+ <Skeleton height={320} radius={8} />
+ <Skeleton height={14} radius={4} />
+ <Skeleton height={14} radius={4} width={'70%'} />
+ </Flexbox>
+ )}
+ </Flexbox>
+ </div>
+ <div {...stylex.props(styles.footer)}>
+ <Text style={{ flex: 1, minWidth: 0 }} type={'secondary'}>
+ {t('goalProcess.signOff.description')}
+ </Text>
+ <Button
+ disabled={!!pending}
+ loading={pending === 'changes'}
+ onClick={() => openRequestChangesModal({ onConfirm: requestChanges })}
+ >
+ {t('goalProcess.signOff.requestChanges')}
+ </Button>
+ <Button
+ disabled={!!pending}
+ loading={pending === 'accept'}
+ title={t('goalProcess.signOff.acceptEffect')}
+ type={'primary'}
+ onClick={accept}
+ >
+ {t('goalProcess.signOff.accept')}
+ </Button>
+ </div>
+ </div>
+ );
+};
+
+const DeliveryBody = ({ graph }: { graph: NonNullable<ReturnType<typeof buildGoalGraphView>> }) => {
+ const data = useGoalResultData(graph);
+ const headline = goalResultHeadline(graph);
+ const reportPageId = goalReportPageId(graph);
+ const deliverable = pickFinalDeliverable(
+ graph.artifacts,
+ findFinalAcceptanceView(graph)?.node.id ?? '',
+ );
+
+ return (
+ <>
+ {headline && (
+ <Text fontSize={18} style={{ lineHeight: 1.4 }} weight={600}>
+ {headline}
+ </Text>
+ )}
+ {reportPageId && <GoalReportPage documentId={reportPageId} />}
+ {deliverable && <FinalDocument documentId={deliverable.documentId} />}
+ <GoalCriteriaResults
+ acceptanceId={data.acceptanceId}
+ error={data.error}
+ loading={data.isLoading}
+ outcomes={data.outcomes}
+ onRetry={data.retry}
+ />
+ </>
+ );
+};
+
+export default GoalSignOffReport;
diff --git a/src/features/AgentGoals/SignOffReport/index.tsx b/src/features/AgentGoals/SignOffReport/index.tsx
new file mode 100644
index 00000000000..4c18fc30355
--- /dev/null
+++ b/src/features/AgentGoals/SignOffReport/index.tsx
@@ -0,0 +1,20 @@
+'use client';
+
+import { createModal } from '@lobehub/ui';
+
+import GoalSignOffReport, { type GoalSignOffReportProps } from './SignOffReport';
+
+/**
+ * Open a finished Goal's delivery for sign-off where the owner already is —
+ * the same report-then-decide dialog a batch release gate opens, so a goal is
+ * never closed from a bare yes/no.
+ */
+export const openGoalSignOffModal = (props: GoalSignOffReportProps) =>
+ createModal({
+ content: <GoalSignOffReport {...props} />,
+ footer: null,
+ maskClosable: true,
+ // The report draws its own frame — header, scrolling body, action band.
+ styles: { content: { overflow: 'hidden', padding: 0 }, header: { display: 'none' } },
+ width: 'min(94vw, 960px)',
+ });
diff --git a/src/features/AgentGoals/SignOffReport/useGoalSignOff.test.ts b/src/features/AgentGoals/SignOffReport/useGoalSignOff.test.ts
new file mode 100644
index 00000000000..f4838951163
--- /dev/null
+++ b/src/features/AgentGoals/SignOffReport/useGoalSignOff.test.ts
@@ -0,0 +1,67 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { verifyService } from '@/services/verify';
+
+import { useGoalSignOff } from './useGoalSignOff';
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@lobehub/ui', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
+vi.mock('@/services/verify', () => ({
+ verifyService: { acceptDelivery: vi.fn(), rejectDelivery: vi.fn() },
+}));
+
+describe('useGoalSignOff', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('accepts the delivery, then closes the report and re-reads the lists', async () => {
+ const onClose = vi.fn();
+ const onDecided = vi.fn();
+ const { result } = renderHook(() =>
+ useGoalSignOff({ acceptanceId: 'acc-1', onClose, onDecided }),
+ );
+
+ await act(async () => {
+ expect(await result.current.accept()).toBe(true);
+ });
+
+ expect(verifyService.acceptDelivery).toHaveBeenCalledWith('acc-1', undefined);
+ expect(verifyService.rejectDelivery).not.toHaveBeenCalled();
+ expect(onClose).toHaveBeenCalledOnce();
+ expect(onDecided).toHaveBeenCalledOnce();
+ });
+
+ it('sends the delivery back with the feedback and dispatches the rework', async () => {
+ const onClose = vi.fn();
+ const { result } = renderHook(() => useGoalSignOff({ acceptanceId: 'acc-1', onClose }));
+
+ await act(async () => {
+ expect(await result.current.requestChanges('fix the chart')).toBe(true);
+ });
+
+ expect(verifyService.rejectDelivery).toHaveBeenCalledWith('acc-1', 'fix the chart', {
+ dispatch: true,
+ });
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+
+ it('keeps the report open when the sign-off fails', async () => {
+ vi.mocked(verifyService.acceptDelivery).mockRejectedValueOnce(new Error('boom'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const onClose = vi.fn();
+ const onDecided = vi.fn();
+ const { result } = renderHook(() =>
+ useGoalSignOff({ acceptanceId: 'acc-1', onClose, onDecided }),
+ );
+
+ await act(async () => {
+ expect(await result.current.accept()).toBe(false);
+ });
+
+ expect(onClose).not.toHaveBeenCalled();
+ expect(onDecided).not.toHaveBeenCalled();
+ expect(result.current.pending).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentGoals/SignOffReport/useGoalSignOff.ts b/src/features/AgentGoals/SignOffReport/useGoalSignOff.ts
new file mode 100644
index 00000000000..8f762920b61
--- /dev/null
+++ b/src/features/AgentGoals/SignOffReport/useGoalSignOff.ts
@@ -0,0 +1,52 @@
+import { toast } from '@lobehub/ui';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { verifyService } from '@/services/verify';
+
+export type SignOffPending = 'accept' | 'changes';
+
+interface UseGoalSignOffOptions {
+ acceptanceId: string;
+ /** Runs once the decision landed, before `onDecided` re-reads the lists. */
+ onClose: () => void;
+ onDecided?: () => Promise<unknown> | void;
+}
+
+/**
+ * Settle a goal's sign-off from its delivery report: accept it, or send it back
+ * with the owner's feedback for the next round. A failure keeps the report open
+ * and says so; a change request then keeps its draft (`requestChanges` → false).
+ */
+export const useGoalSignOff = ({ acceptanceId, onClose, onDecided }: UseGoalSignOffOptions) => {
+ const { t } = useTranslation('chat');
+ const [pending, setPending] = useState<SignOffPending>();
+
+ const settle = async (kind: SignOffPending, comment?: string): Promise<boolean> => {
+ setPending(kind);
+ try {
+ if (kind === 'accept') await verifyService.acceptDelivery(acceptanceId, comment);
+ else await verifyService.rejectDelivery(acceptanceId, comment, { dispatch: true });
+ } catch (error) {
+ console.error('[goal:sign-off-report]', error);
+ toast.error(t('goalProcess.result.signOff.error'));
+ return false;
+ } finally {
+ setPending(undefined);
+ }
+ toast.success({
+ placement: 'top',
+ title:
+ kind === 'accept' ? t('goalProcess.signOff.accepted') : t('goalProcess.signOff.sentBack'),
+ });
+ onClose();
+ await onDecided?.();
+ return true;
+ };
+
+ return {
+ accept: () => settle('accept'),
+ pending,
+ requestChanges: (comment: string) => settle('changes', comment),
+ };
+};
diff --git a/src/features/GlobalApprovalNotification/GoalDecisionCard.tsx b/src/features/GlobalApprovalNotification/GoalDecisionCard.tsx
index 06bdaaebd90..0dac488db79 100644
--- a/src/features/GlobalApprovalNotification/GoalDecisionCard.tsx
+++ b/src/features/GlobalApprovalNotification/GoalDecisionCard.tsx
@@ -1,8 +1,8 @@
'use client';
-import { ActionIcon, Button, toast } from '@lobehub/ui';
+import { ActionIcon, Button } from '@lobehub/ui';
import { ArrowUpRight, ChevronUp } from 'lucide-react';
-import { useCallback, useMemo, useState } from 'react';
+import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { openGateReportModal } from '@/features/Acceptance/Viewer/Gate';
@@ -16,15 +16,13 @@ import {
coordinatorGateReason,
localizedCoordinatorReason,
} from '@/features/AgentGoals/ProcessControl/coordinatorCopy';
-import ClarificationQuestions, {
- type ClarificationAnswer,
-} from '@/features/ClarificationQuestions';
+import { openGoalSignOffModal } from '@/features/AgentGoals/SignOffReport';
+import SignOffDigest from '@/features/AgentGoals/SignOffReport/SignOffDigest';
+import { useGoalSignOff } from '@/features/AgentGoals/SignOffReport/useGoalSignOff';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
-import { mutate } from '@/libs/swr';
-import { goalKeys } from '@/libs/swr/keys';
-import { verifyService } from '@/services/verify';
import { useGoalStore } from '@/store/goal';
+import { refreshGoalAsks } from './refreshGoalAsks';
import { styles } from './styles';
import type { IslandGoalItem } from './usePendingGoalDecisions';
@@ -35,8 +33,6 @@ interface GoalDecisionCardProps {
onDismiss?: () => void;
}
-const SIGN_OFF = { accept: 'signOff', requestChanges: 'requestChanges' } as const;
-
/**
* A goal gate or a goal sign-off in the island: the same question the goal
* page asks, answerable from wherever the user is. The goal's own title leads,
@@ -70,65 +66,35 @@ const GoalDecisionCard = ({ item, onCollapse, onDismiss }: GoalDecisionCardProps
reviewAcceptanceId &&
openGateReportModal({
acceptanceId: reviewAcceptanceId,
- onDecided: () => {
- void mutate(goalKeys.pendingForIsland());
- void mutate((key) => Array.isArray(key) && key[0] === 'brief:list');
- },
+ onDecided: () => void refreshGoalAsks(goal.id),
});
const openGoal = () =>
navigate(goal.agentId ? `/agent/${goal.agentId}/goal/${goal.id}` : `/goal/${goal.id}`);
- const signOffQuestions = useMemo(
- () => [
- {
- description: t('goalProcess.signOff.description'),
- header: '',
- id: 'signOff',
- options: [
- {
- description: t('goalProcess.signOff.acceptEffect'),
- id: SIGN_OFF.accept,
- label: t('goalProcess.signOff.accept'),
- recommended: true,
- },
- {
- description: t('goalProcess.signOff.requestChangesEffect'),
- id: SIGN_OFF.requestChanges,
- label: t('goalProcess.signOff.requestChanges'),
- },
- ],
- question: t('goalProcess.signOff.question'),
- },
- ],
- [t],
- );
-
- const signOff = useCallback(
- async (answers: ClarificationAnswer[]) => {
- if (item.type !== 'signOff') return;
- const [answer] = answers;
- if (!answer) return;
- // Words with no pick are a change request: that is the only answer that
- // needs them.
- const accept = answer.type === 'option' && answer.optionId === SIGN_OFF.accept;
- const comment = (answer.type === 'option' ? answer.note : answer.text)?.trim() || undefined;
- if (accept) await verifyService.acceptDelivery(item.signOff.acceptanceId, comment);
- else
- await verifyService.rejectDelivery(item.signOff.acceptanceId, comment, { dispatch: true });
- toast.success({
- placement: 'top',
- title: accept ? t('goalProcess.signOff.accepted') : t('goalProcess.signOff.sentBack'),
- });
+ // A sign-off closes the goal, so it is decided over the delivery itself —
+ // the report opens first, never a bare yes/no from wherever the user is.
+ const openSignOff = () =>
+ item.type === 'signOff' &&
+ openGoalSignOffModal({
+ acceptanceId: item.signOff.acceptanceId,
+ agentId: item.signOff.agentId,
+ goalId: item.signOff.goalId,
+ goalTitle: item.signOff.goalTitle,
// The inbox carries the same sign-off; it is settled on the server with
// the acceptance, so re-read it there too.
- await Promise.all([
- mutate(goalKeys.pendingForIsland()),
- mutate((key) => Array.isArray(key) && key[0] === 'brief:list'),
- ]);
- },
- [item, t],
- );
+ onDecided: () => refreshGoalAsks(item.signOff.goalId),
+ onOpenGoal: openGoal,
+ });
+
+ // The digest says what was delivered, so a sign-off the owner agrees with
+ // needs no detour; asking for changes goes through the full report, where
+ // the feedback is written.
+ const { accept, pending } = useGoalSignOff({
+ acceptanceId: item.type === 'signOff' ? item.signOff.acceptanceId : '',
+ onClose: () => {},
+ onDecided: () => refreshGoalAsks(goal.id),
+ });
return (
<div data-pending-hotkey-scope className={styles.card}>
@@ -196,15 +162,7 @@ const GoalDecisionCard = ({ item, onCollapse, onDismiss }: GoalDecisionCardProps
}
/>
) : (
- <ClarificationQuestions
- actionsPortalTarget={actionsPortalTarget}
- draftKey={`goal-sign-off:${item.signOff.acceptanceId}`}
- key={item.signOff.acceptanceId}
- questions={signOffQuestions}
- submitLabel={t('goalProcess.decision.submit')}
- supplementPlaceholder={t('goalProcess.signOff.notePlaceholder')}
- onSubmit={signOff}
- />
+ <SignOffDigest goalId={item.signOff.goalId} key={item.signOff.goalId} />
)}
</div>
@@ -220,10 +178,30 @@ const GoalDecisionCard = ({ item, onCollapse, onDismiss }: GoalDecisionCardProps
</Button>
)}
<div className={styles.goalActionsSlot} ref={setActionsPortalTarget} />
- {reviewAcceptanceId && (
- <Button size="small" type="primary" onClick={openReview}>
- {t('goalProcess.gate.openReview')}
- </Button>
+ {/* One primary per card: a sign-off commits from its digest, a held
+ release is reviewed in its report — never both on one card. */}
+ {item.type === 'signOff' ? (
+ <>
+ <Button disabled={!!pending} size="small" onClick={openSignOff}>
+ {t('goalProcess.signOff.openReport')}
+ </Button>
+ <Button
+ disabled={!!pending}
+ loading={pending === 'accept'}
+ size="small"
+ title={t('goalProcess.signOff.acceptEffect')}
+ type="primary"
+ onClick={accept}
+ >
+ {t('goalProcess.signOff.accept')}
+ </Button>
+ </>
+ ) : (
+ reviewAcceptanceId && (
+ <Button size="small" type="primary" onClick={openReview}>
+ {t('goalProcess.gate.openReview')}
+ </Button>
+ )
)}
</div>
</div>
diff --git a/src/features/GlobalApprovalNotification/refreshGoalAsks.test.ts b/src/features/GlobalApprovalNotification/refreshGoalAsks.test.ts
new file mode 100644
index 00000000000..c359f1da6a4
--- /dev/null
+++ b/src/features/GlobalApprovalNotification/refreshGoalAsks.test.ts
@@ -0,0 +1,34 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { revalidateReplica } from '@/libs/replica';
+import { mutate } from '@/libs/swr';
+import { goalKeys } from '@/libs/swr/keys';
+import { briefListResource } from '@/store/brief/slices/list/projection';
+import { goalGraphResource } from '@/store/goal/projection';
+
+import { refreshGoalAsks } from './refreshGoalAsks';
+
+vi.mock('@/libs/replica', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ revalidateReplica: vi.fn(),
+}));
+vi.mock('@/libs/swr', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ mutate: vi.fn(),
+}));
+
+describe('refreshGoalAsks', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('re-reads the island, the Home inbox replica and the goal graph', async () => {
+ await refreshGoalAsks('goal-1');
+
+ expect(mutate).toHaveBeenCalledWith(goalKeys.pendingForIsland());
+ // The inbox is a replica: a `brief:list` SWR prefix match never reached it,
+ // so an answered sign-off stayed listed there until a reload.
+ expect(revalidateReplica).toHaveBeenCalledWith(briefListResource);
+ expect(revalidateReplica).toHaveBeenCalledWith(goalGraphResource, 'goal-1');
+ });
+});
diff --git a/src/features/GlobalApprovalNotification/refreshGoalAsks.ts b/src/features/GlobalApprovalNotification/refreshGoalAsks.ts
new file mode 100644
index 00000000000..24f85e76fe1
--- /dev/null
+++ b/src/features/GlobalApprovalNotification/refreshGoalAsks.ts
@@ -0,0 +1,18 @@
+import { revalidateReplica } from '@/libs/replica';
+import { mutate } from '@/libs/swr';
+import { goalKeys } from '@/libs/swr/keys';
+import { briefListResource } from '@/store/brief/slices/list/projection';
+import { goalGraphResource } from '@/store/goal/projection';
+
+/**
+ * Re-read everything that asks a goal question the owner just answered: the
+ * island, the Home inbox (which carries the same gate or sign-off as a brief)
+ * and the goal's own graph. The inbox and the graph are replicas, so they are
+ * revalidated through their resources — an SWR key prefix no longer reaches them.
+ */
+export const refreshGoalAsks = (goalId: string) =>
+ Promise.all([
+ mutate(goalKeys.pendingForIsland()),
+ revalidateReplica(briefListResource),
+ revalidateReplica(goalGraphResource, goalId),
+ ]);