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): group anchor rail and a tighter result page (#20248)

Arvin Xua564091cdf92
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index bf40f0df38f..82f5dd443b2 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -839,7 +839,9 @@
"goalProcess.result.gate.error": "Could not save the decision. Try again.",
"goalProcess.result.gate.prompt": "Check which criteria were not met below, then retry or end the Goal.",
"goalProcess.result.gate.revising": "You chose to retry. The Agent is revising the result; it will be accepted again when done.",
- "goalProcess.result.requirement": "Original requirement",
+ "goalProcess.result.nav.document": "Final document",
+ "goalProcess.result.nav.label": "Jump to section",
+ "goalProcess.result.nav.overview": "Overview",
"goalProcess.result.scale.cost": "Spent {{cost}}",
"goalProcess.result.scale.criteria": "{{met}}/{{total}} criteria met",
"goalProcess.result.scale.duration": "Took {{duration}}",
@@ -862,11 +864,6 @@
"goalProcess.result.signOff.requestChanges": "Request changes",
"goalProcess.result.signOff.stopped": "The Goal stopped before it was done — this is what it left behind. Pick it up from here.",
"goalProcess.result.signOff.unavailable": "There is no Goal-level acceptance to sign off.",
- "goalProcess.result.status.awaitingDecision": "Acceptance not passed · your call",
- "goalProcess.result.status.awaitingSignOff": "Achieved · awaiting your sign-off",
- "goalProcess.result.status.partial": "Not achieved · partial result",
- "goalProcess.result.status.revising": "Revising",
- "goalProcess.result.status.signedOff": "Signed off",
"goalProcess.result.story.chapterMissing": "This chapter is no longer in the report — it may have been rewritten.",
"goalProcess.result.story.detourKind.dead_end": "Dead end",
"goalProcess.result.story.detourKind.retry": "Retried",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index bb77e0938b6..d66bfe97135 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -839,7 +839,9 @@
"goalProcess.result.gate.error": "决定没有保存成功,请重试。",
"goalProcess.result.gate.prompt": "先看下方哪些标准没有达成,再决定重试还是结束目标。",
"goalProcess.result.gate.revising": "你选择了重试,Agent 正在修改,改完后会重新验收。",
- "goalProcess.result.requirement": "原始要求",
+ "goalProcess.result.nav.document": "交付文档",
+ "goalProcess.result.nav.label": "页面导航",
+ "goalProcess.result.nav.overview": "概览",
"goalProcess.result.scale.cost": "花费 {{cost}}",
"goalProcess.result.scale.criteria": "标准达成 {{met}}/{{total}}",
"goalProcess.result.scale.duration": "用时 {{duration}}",
@@ -862,11 +864,6 @@
"goalProcess.result.signOff.requestChanges": "提出修改",
"goalProcess.result.signOff.stopped": "目标没有完成就停止了,这里是它留下的成果,可以从这里接着做。",
"goalProcess.result.signOff.unavailable": "没有可签收的整体验收。",
- "goalProcess.result.status.awaitingDecision": "验收未通过 · 等你决定",
- "goalProcess.result.status.awaitingSignOff": "已达成 · 等你验收",
- "goalProcess.result.status.partial": "未达成 · 部分成果",
- "goalProcess.result.status.revising": "修改中",
- "goalProcess.result.status.signedOff": "已签收",
"goalProcess.result.story.chapterMissing": "报告里已经没有这一章,可能被重新整理过。",
"goalProcess.result.story.detourKind.dead_end": "死路",
"goalProcess.result.story.detourKind.retry": "重试",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 7a13e2c0ef0..1c72bfc16c8 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2186,7 +2186,9 @@ export default {
'Check which criteria were not met below, then retry or end the Goal.',
'goalProcess.result.gate.revising':
'You chose to retry. The Agent is revising the result; it will be accepted again when done.',
- 'goalProcess.result.requirement': 'Original requirement',
+ 'goalProcess.result.nav.document': 'Final document',
+ 'goalProcess.result.nav.label': 'Jump to section',
+ 'goalProcess.result.nav.overview': 'Overview',
'goalProcess.result.scale.cost': 'Spent {{cost}}',
'goalProcess.result.scale.criteria': '{{met}}/{{total}} criteria met',
'goalProcess.result.scale.duration': 'Took {{duration}}',
@@ -2215,11 +2217,6 @@ export default {
'goalProcess.result.signOff.stopped':
'The Goal stopped before it was done — this is what it left behind. Pick it up from here.',
'goalProcess.result.signOff.unavailable': 'There is no Goal-level acceptance to sign off.',
- 'goalProcess.result.status.awaitingDecision': 'Acceptance not passed · your call',
- 'goalProcess.result.status.awaitingSignOff': 'Achieved · awaiting your sign-off',
- 'goalProcess.result.status.partial': 'Not achieved · partial result',
- 'goalProcess.result.status.revising': 'Revising',
- 'goalProcess.result.status.signedOff': 'Signed off',
'goalProcess.result.unfinished.abandoned': 'Dropped tasks',
'goalProcess.result.unfinished.continue': 'Continue from this result',
'goalProcess.result.unfinished.empty': 'Nothing is left open.',
diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsx
index 6a57e399e42..e6edf1b6675 100644
--- a/src/features/AgentGoals/GoalDetailPage.tsx
+++ b/src/features/AgentGoals/GoalDetailPage.tsx
@@ -235,14 +235,15 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {
)}
</Flexbox>
)}
+ {/* North-star strip reads with the requirement document — the
+ measured clauses ARE half of the acceptance contract — and
+ leads it rather than trailing it (review feedback, r3). It
+ stays below the execution metrics, so it is never squeezed
+ between the title and those numbers. */}
+ <NorthStarMetrics canEdit={canEdit} goalId={goalId} />
{goal.requirement && (
<GoalRequirement goalId={goal.id} requirement={goal.requirement} />
)}
- {/* North-star strip beside the requirement document: the measured
- clauses ARE half of the acceptance contract, so they read
- with it — not squeezed between the title and the execution
- metrics (review feedback, r1). */}
- <NorthStarMetrics canEdit={canEdit} goalId={goalId} />
</Flexbox>
<ProcessControl
diff --git a/src/features/AgentGoals/ProcessControl/GoalCriteriaResults.tsx b/src/features/AgentGoals/ProcessControl/GoalCriteriaResults.tsx
index 0dbe3ce03d3..a7e86b65f18 100644
--- a/src/features/AgentGoals/ProcessControl/GoalCriteriaResults.tsx
+++ b/src/features/AgentGoals/ProcessControl/GoalCriteriaResults.tsx
@@ -23,10 +23,10 @@ import type { CriterionOutcome, CriterionOutcomeState, EvidenceLike } from './go
/**
* 验收标准 × 结果 — each criterion the Goal was accepted against, next to what
- * the latest acceptance round found: met or not, one line of what the evidence
- * showed, and why when it was not. A row opens into its evidence — screenshots,
- * written evidence, the documents it cites — in place, without framing the
- * content in another card.
+ * the latest acceptance round found: met or not, and why when it was not. A row
+ * opens into its evidence — screenshots, written evidence, the documents it
+ * cites — in place, without framing the content in another card. The round's own
+ * write-up for a met criterion belongs to the acceptance, not to this summary.
*/
const styles = createStaticStyles(({ css }) => ({
@@ -179,7 +179,7 @@ const EvidenceItem = ({ item }: { item: EvidenceLike }) => {
const CriterionRow = ({ index, outcome }: { index: number; outcome: CriterionOutcome }) => {
const { t } = useTranslation('chat');
const [open, setOpen] = useState(false);
- const { criterion, evidence, reason, state, summary } = outcome;
+ const { criterion, evidence, reason, state } = outcome;
const openable = evidence.length > 0;
const color = STATE_COLOR[state];
@@ -208,11 +208,6 @@ const CriterionRow = ({ index, outcome }: { index: number; outcome: CriterionOut
{t(`goalProcess.result.criteria.state.${state}`)}
</Text>
</Flexbox>
- {summary && (
- <Text fontSize={13} style={{ wordBreak: 'break-word' }} type={'secondary'}>
- {summary}
- </Text>
- )}
{state === 'failed' && reason && (
<Text className={styles.reason} fontSize={13} style={{ wordBreak: 'break-word' }}>
{reason}
diff --git a/src/features/AgentGoals/ProcessControl/GoalResult.tsx b/src/features/AgentGoals/ProcessControl/GoalResult.tsx
index 2ea92291828..a6de1f7a7fc 100644
--- a/src/features/AgentGoals/ProcessControl/GoalResult.tsx
+++ b/src/features/AgentGoals/ProcessControl/GoalResult.tsx
@@ -2,6 +2,8 @@
import { Flexbox, Markdown } from '@lobehub/ui';
import { Divider, Skeleton } from '@lobehub/ui/base-ui';
+import { useRef } from 'react';
+import { useTranslation } from 'react-i18next';
import { useEntityMarkdown } from '@/features/EntityLink';
import { useClientDataSWR } from '@/libs/swr';
@@ -14,6 +16,8 @@ import type { GoalGraphView } from './goalGraphViewModel';
import { GoalDecisionsMade, GoalUnfinished, useContinueFromResult } from './GoalResultFollowUps';
import GoalResultHeader from './GoalResultHeader';
import { findFinalAcceptanceView } from './goalResultState';
+import ResultAnchorRail from './ResultAnchorRail';
+import { anchorProps } from './resultAnchors';
import ResultDeliverables from './ResultDeliverables';
import ResultTrail from './ResultTrail';
import { useGoalResultData } from './useGoalResultData';
@@ -21,14 +25,16 @@ import { useGoalResultData } from './useGoalResultData';
/**
* 结果交付 — what a finished Goal hands over, on its own tab.
*
- * Layered for a reviewer who reads top-down: the first screen says where the
- * result stands, what was asked, how big the run was, and carries the sign-off.
- * Every deliverable follows in one place, with a reader to page through them.
- * Then each acceptance criterion against what the latest acceptance round
- * found, the decisions the owner made along the way, and what is still open.
- * The document the work wrote follows, read like a page rather than a card,
- * and under it the trail of how that result was reached. How the Goal ran
- * (tasks, map, activity) lives on the 执行过程 tab.
+ * Layered for a reviewer who reads top-down: the first screen is the Goal's own
+ * headline, the document the work wrote leads the page as the delivery itself,
+ * and the deliverables plus each acceptance criterion (against what the latest
+ * acceptance round found) follow as the evidence behind it. Under them the trail
+ * of how that result was reached. What the owner shaped along the way and what is
+ * still open closes the page — history reads after the delivery, not before it.
+ * How the Goal ran (tasks, map, activity) lives on the 执行过程 tab.
+ *
+ * A rail of ticks beside the scrollbar names those sections on hover and jumps
+ * to them on click — see `ResultAnchorRail`.
*/
const FinalDocument = ({ documentId }: { documentId: string }) => {
@@ -62,39 +68,66 @@ interface GoalResultProps {
}
const GoalResult = ({ graph, onSelect }: GoalResultProps) => {
+ const { t } = useTranslation('chat');
+ const rootRef = useRef<HTMLDivElement>(null);
const acceptanceNodeId = findFinalAcceptanceView(graph)?.node.id ?? '';
const deliverable = pickFinalDeliverable(graph.artifacts, acceptanceNodeId);
const data = useGoalResultData(graph);
const continueFromResult = useContinueFromResult(graph, data.outcomes);
return (
- <Flexbox gap={8}>
- <Flexbox gap={32}>
- <GoalResultHeader data={data} graph={graph} onContinue={continueFromResult} />
- <ResultDeliverables
- graph={graph}
- loading={data.isLoading}
- outcomes={data.outcomes}
- primaryResourceId={deliverable?.documentId}
- />
- <GoalCriteriaResults
- error={data.error}
- loading={data.isLoading}
- outcomes={data.outcomes}
- onRetry={data.retry}
- />
- <GoalDecisionsMade graph={graph} />
- <GoalUnfinished graph={graph} outcomes={data.outcomes} onContinue={continueFromResult} />
+ <div ref={rootRef}>
+ <ResultAnchorRail rootRef={rootRef} />
+ <Flexbox gap={8}>
+ <div {...anchorProps('overview', t('goalProcess.result.nav.overview'))}>
+ <GoalResultHeader data={data} graph={graph} />
+ </div>
+ {deliverable && (
+ <div
+ {...anchorProps('document', t('goalProcess.result.nav.document'))}
+ style={{ paddingBlockStart: 16 }}
+ >
+ <FinalDocument documentId={deliverable.documentId} />
+ </div>
+ )}
+ <Divider style={{ marginBlock: 24 }} />
+ <Flexbox gap={32}>
+ <div {...anchorProps('deliverables', t('goalProcess.deliverables.title'))}>
+ <ResultDeliverables
+ graph={graph}
+ loading={data.isLoading}
+ outcomes={data.outcomes}
+ primaryResourceId={deliverable?.documentId}
+ />
+ </div>
+ <div {...anchorProps('criteria', t('goalProcess.result.criteria.title'))}>
+ <GoalCriteriaResults
+ error={data.error}
+ loading={data.isLoading}
+ outcomes={data.outcomes}
+ onRetry={data.retry}
+ />
+ </div>
+ </Flexbox>
+ <Divider style={{ marginBlock: 24 }} />
+ <div {...anchorProps('trail', t('goalProcess.result.trail.title'))}>
+ <ResultTrail documentId={deliverable?.documentId} graph={graph} onSelect={onSelect} />
+ </div>
+ <Divider style={{ marginBlock: 24 }} />
+ <Flexbox gap={32}>
+ <div {...anchorProps('decisions', t('goalProcess.result.decisions.title'))}>
+ <GoalDecisionsMade graph={graph} />
+ </div>
+ <div {...anchorProps('unfinished', t('goalProcess.result.unfinished.title'))}>
+ <GoalUnfinished
+ graph={graph}
+ outcomes={data.outcomes}
+ onContinue={continueFromResult}
+ />
+ </div>
+ </Flexbox>
</Flexbox>
- <Divider style={{ marginBlock: 24 }} />
- {deliverable && (
- <>
- <FinalDocument documentId={deliverable.documentId} />
- <Divider style={{ marginBlock: 24 }} />
- </>
- )}
- <ResultTrail documentId={deliverable?.documentId} graph={graph} onSelect={onSelect} />
- </Flexbox>
+ </div>
);
};
diff --git a/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx b/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx
index 93ddecbe73b..0c1d0206ed2 100644
--- a/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx
+++ b/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx
@@ -1,50 +1,30 @@
'use client';
import type { GoalGraphDecision } from '@lobechat/types';
-import { Flexbox, Icon, Markdown, Tooltip } from '@lobehub/ui';
-import { Button, confirmModal, Text, TextArea, toast } from '@lobehub/ui/base-ui';
+import { Flexbox, Tooltip } from '@lobehub/ui';
+import { Button, Text, TextArea, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import {
- ArrowRight,
- BadgeCheck,
- CircleAlert,
- CircleCheck,
- CircleX,
- RefreshCw,
- Undo2,
-} from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
-import AsyncError from '@/components/AsyncError';
-import CollapsibleContent from '@/components/CollapsibleContent';
import { usePermission } from '@/hooks/usePermission';
-import { verifyService } from '@/services/verify';
import { useGoalStore } from '@/store/goal';
-import { formatSpan, formatUsd } from '../goalPresentation';
import { coordinatorGateReason, coordinatorReasonCopy } from './coordinatorCopy';
import { useGateOptionLabel } from './Frontier';
import type { GoalGraphView } from './goalGraphViewModel';
import {
- countGoalTasks,
deriveGoalResultStatus,
- deriveSignOffState,
findGoalAcceptanceGate,
findOpenChangeRequest,
- type GoalAcceptanceGate,
- type GoalResultStatus,
- type GoalSignOffState,
} from './goalResultState';
-import { openRequestChangesModal } from './RequestChangesModal';
import type { GoalResultData } from './useGoalResultData';
/**
- * The first screen of a finished Goal: where it stands, the one-line result
- * (only when the wrap-up report wrote one), what was asked, how big the run
- * was, and the one action it waits on — signing off the delivery. Sign-off is
- * the Goal-level acceptance's own accept / reject, so the acceptance page and
- * this strip can never disagree.
+ * The first screen of a finished Goal: the one-line result the wrap-up report
+ * wrote, and — only when the Goal-level acceptance left the coordinator a gate
+ * to resolve — the decision it is waiting on. Signing a delivery off belongs to
+ * the acceptance itself, so this page does not carry a second copy of it.
*/
const styles = createStaticStyles(({ css }) => ({
@@ -56,138 +36,6 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-const STATUS_ICON: Record<GoalResultStatus, typeof CircleCheck> = {
- awaitingDecision: CircleX,
- awaitingSignOff: CircleCheck,
- partial: CircleAlert,
- revising: RefreshCw,
- signedOff: BadgeCheck,
-};
-
-const STATUS_COLOR: Record<GoalResultStatus, string> = {
- awaitingDecision: cssVar.colorError,
- awaitingSignOff: cssVar.colorSuccess,
- partial: cssVar.colorWarning,
- revising: cssVar.colorInfo,
- signedOff: cssVar.colorPrimary,
-};
-
-const SIGN_OFF_TEXT: Record<GoalSignOffState, string> = {
- accepted: 'goalProcess.result.signOff.accepted',
- changesRequested: 'goalProcess.result.signOff.changesRequested',
- open: 'goalProcess.result.signOff.prompt',
- stopped: 'goalProcess.result.signOff.stopped',
- unavailable: 'goalProcess.result.signOff.unavailable',
-};
-
-interface SignOffStripProps {
- data: GoalResultData;
- gate?: GoalAcceptanceGate['kind'];
- goalId: string;
- goalStatus: string;
- onContinue: () => void;
- partial: boolean;
-}
-
-const SignOffStrip = ({
- data,
- gate,
- goalId,
- goalStatus,
- onContinue,
- partial,
-}: SignOffStripProps) => {
- const { t } = useTranslation('chat');
- const refreshGoalGraph = useGoalStore((s) => s.refreshGoalGraph);
- const { acceptanceId, acceptanceStatus, canReview, mutateAcceptance, outcomes } = data;
- const state = deriveSignOffState(acceptanceStatus, goalStatus, gate);
- const unmet = outcomes.filter((outcome) => outcome.state !== 'passed').length;
-
- const settle = async (action: () => Promise<unknown>) => {
- try {
- await action();
- await Promise.all([mutateAcceptance(), refreshGoalGraph(goalId)]);
- return true;
- } catch (error) {
- console.error('[goal:sign-off]', error);
- toast.error(t('goalProcess.result.signOff.error'));
- return false;
- }
- };
-
- const accept = () =>
- confirmModal({
- cancelText: t('goalProcess.result.signOff.cancel'),
- content:
- unmet > 0
- ? `${t('goalProcess.result.signOff.acceptConfirm.content')} ${t(
- 'goalProcess.result.signOff.acceptConfirm.unmet',
- { count: unmet },
- )}`
- : t('goalProcess.result.signOff.acceptConfirm.content'),
- okText: t('goalProcess.result.signOff.accept'),
- onOk: async () => {
- await settle(() => verifyService.acceptDelivery(acceptanceId!));
- },
- title: t('goalProcess.result.signOff.acceptConfirm.title'),
- });
-
- const requestChanges = () =>
- openRequestChangesModal({
- onConfirm: async (comment) => {
- const sent = await settle(() => verifyService.rejectDelivery(acceptanceId!, comment));
- if (sent) toast.success(t('goalProcess.result.signOff.changes.sent'));
- return sent;
- },
- });
-
- const actionable = state === 'open' && !!acceptanceId && canReview;
-
- // Without the bundle the page cannot tell whether a sign-off is possible;
- // say so and offer a retry rather than silently dropping the actions.
- if (data.error && state === 'open')
- return (
- <Flexbox className={styles.strip} data-sign-off-state={'error'}>
- <AsyncError error={data.error} variant={'inline'} onRetry={data.retry} />
- </Flexbox>
- );
-
- return (
- <Flexbox
- horizontal
- align={'center'}
- className={styles.strip}
- data-sign-off-state={state}
- gap={12}
- justify={'space-between'}
- wrap={'wrap'}
- >
- <Text style={{ flex: 1, minWidth: 200 }} type={state === 'open' ? undefined : 'secondary'}>
- {t(SIGN_OFF_TEXT[state] as any)}
- </Text>
- <Flexbox horizontal gap={8}>
- {actionable && (
- <>
- <Button icon={Undo2} onClick={requestChanges}>
- {t('goalProcess.result.signOff.requestChanges')}
- </Button>
- <Button icon={CircleCheck} type={'primary'} onClick={accept}>
- {t('goalProcess.result.signOff.accept')}
- </Button>
- </>
- )}
- {/* A stopped Goal has nothing further to sign; its way forward is to
- pick the work up again. */}
- {!actionable && partial && (
- <Button icon={ArrowRight} onClick={onContinue}>
- {t('goalProcess.result.unfinished.continue')}
- </Button>
- )}
- </Flexbox>
- </Flexbox>
- );
-};
-
interface DecisionStripProps {
decision: GoalGraphDecision;
goalId: string;
@@ -266,14 +114,11 @@ const DecisionStrip = ({ decision, goalId, onDecided }: DecisionStripProps) => {
interface GoalResultHeaderProps {
data: GoalResultData;
graph: GoalGraphView;
- onContinue: () => void;
}
-const GoalResultHeader = ({ data, graph, onContinue }: GoalResultHeaderProps) => {
- const { t } = useTranslation('chat');
+const GoalResultHeader = ({ data, graph }: GoalResultHeaderProps) => {
const { goal } = graph;
const { outcomes } = data;
- const met = outcomes.filter((outcome) => outcome.state === 'passed').length;
const gate = findGoalAcceptanceGate(graph);
const changeRequest = findOpenChangeRequest(graph);
const status = deriveGoalResultStatus({
@@ -285,81 +130,19 @@ const GoalResultHeader = ({ data, graph, onContinue }: GoalResultHeaderProps) =>
});
const headline = graph.report?.latest?.metadata.headline;
- const scale = [
- outcomes.length > 0 && t('goalProcess.result.scale.criteria', { met, total: outcomes.length }),
- t('goalProcess.result.scale.tasks', { count: countGoalTasks(graph) }),
- goal.startedAt &&
- t('goalProcess.result.scale.duration', {
- duration: formatSpan(
- (goal.completedAt ?? goal.updatedAt).getTime() - goal.startedAt.getTime(),
- ),
- }),
- graph.spend && t('goalProcess.result.scale.cost', { cost: formatUsd(graph.spend.totalCost) }),
- ].filter(Boolean);
-
return (
<Flexbox data-goal-result-status={status} gap={14}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Icon color={STATUS_COLOR[status]} icon={STATUS_ICON[status]} size={18} />
- <Text fontSize={14} style={{ color: STATUS_COLOR[status] }} weight={600}>
- {t(`goalProcess.result.status.${status}`)}
- </Text>
- </Flexbox>
{headline && (
<Text fontSize={20} style={{ lineHeight: 1.4 }} weight={600}>
{headline}
</Text>
)}
- {goal.requirement && (
- <Flexbox gap={4}>
- <Text fontSize={12} type={'secondary'} weight={500}>
- {t('goalProcess.result.requirement')}
- </Text>
- <CollapsibleContent maxHeight={120}>
- <Markdown fontSize={14} variant={'chat'}>
- {goal.requirement}
- </Markdown>
- </CollapsibleContent>
- </Flexbox>
- )}
- <Text fontSize={13} type={'secondary'}>
- {scale.join(' · ')}
- </Text>
- {status === 'awaitingDecision' && gate?.kind === 'pending' ? (
+ {status === 'awaitingDecision' && gate?.kind === 'pending' && (
<DecisionStrip
decision={gate.decision}
goalId={goal.id}
onDecided={data.mutateAcceptance}
/>
- ) : status === 'revising' ? (
- // Nothing to sign while the rework runs: the strip says what the Agent
- // is answering to instead of offering accept / request changes again.
- <Flexbox className={styles.strip} data-sign-off-state={'revising'} gap={6}>
- <Text type={'secondary'}>
- {t(
- changeRequest
- ? 'goalProcess.result.changes.revising'
- : 'goalProcess.result.gate.revising',
- )}
- </Text>
- {changeRequest?.comment && (
- <Flexbox data-goal-change-request gap={2}>
- <Text fontSize={12} type={'secondary'} weight={500}>
- {t('goalProcess.result.changes.comment')}
- </Text>
- <Text style={{ whiteSpace: 'pre-wrap' }}>{changeRequest.comment}</Text>
- </Flexbox>
- )}
- </Flexbox>
- ) : (
- <SignOffStrip
- data={data}
- gate={gate?.kind}
- goalId={goal.id}
- goalStatus={goal.status}
- partial={status === 'partial'}
- onContinue={onContinue}
- />
)}
</Flexbox>
);
diff --git a/src/features/AgentGoals/ProcessControl/ResultAnchorRail.tsx b/src/features/AgentGoals/ProcessControl/ResultAnchorRail.tsx
new file mode 100644
index 00000000000..6f2eb4946ec
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/ResultAnchorRail.tsx
@@ -0,0 +1,182 @@
+'use client';
+
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { type RefObject } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { MIN_RAIL_ANCHORS } from './resultAnchors';
+import { RAIL_ROW, RAIL_TOP, useResultAnchorRail } from './useResultAnchorRail';
+
+/**
+ * A scroll rail for the long 结果交付 page. At rest it is a column of ticks in
+ * the page's right padding — one per section, shorter ones for the deliverable
+ * groups inside 交付物 — with the section being read highlighted. Hovering it,
+ * or tabbing to it, opens the section names; clicking one scrolls there.
+ *
+ * What it knows about the page comes from useResultAnchorRail; this file is the
+ * column that draws it.
+ */
+
+const styles = createStaticStyles(({ css }) => ({
+ host: css`
+ position: sticky;
+ z-index: 10;
+ inset-block-start: ${RAIL_TOP}px;
+ height: 0;
+ `,
+ item: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 10px;
+ align-items: center;
+ justify-content: flex-end;
+
+ width: 100%;
+
+ /* Fixed, not a minimum: a row that grows taller when the labels open slides
+ every tick below it out from under the pointer between hover and click. */
+ height: ${RAIL_ROW}px;
+ padding: 0;
+ border: none;
+
+ color: ${cssVar.colorTextTertiary};
+ text-align: end;
+
+ background: none;
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimary};
+ outline-offset: 2px;
+ }
+ `,
+ itemActive: css`
+ color: ${cssVar.colorText};
+ `,
+ label: css`
+ overflow: hidden;
+ display: none;
+ flex: 1;
+
+ max-width: 240px;
+
+ font-size: 12px;
+
+ /* Matches the row height, so opening the labels changes nothing vertically. */
+ line-height: ${RAIL_ROW}px;
+ text-align: start;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ labelChild: css`
+ padding-inline-start: 12px;
+ `,
+ rail: css`
+ position: absolute;
+ inset-block-start: 0;
+ inset-inline-end: -16px;
+
+ overflow: hidden auto;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-end;
+
+ max-height: calc(100vh - ${RAIL_TOP * 2}px);
+ padding-block: 6px;
+
+ /* The end padding must not change when the labels open: the ticks are
+ anchored to this edge, and a tick that moves out from under the pointer
+ between hover and click is a click that goes nowhere. */
+ padding-inline: 2px 8px;
+ border: 1px solid transparent;
+ border-radius: ${cssVar.borderRadiusLG};
+
+ transition:
+ background 0.15s ${cssVar.motionEaseOut},
+ box-shadow 0.15s ${cssVar.motionEaseOut};
+
+ /* Hover, or keyboard focus: a click leaves focus behind, and an open panel
+ that outlives the gesture would cover the page it just navigated. */
+ &:hover,
+ &:has(:focus-visible) {
+ padding-inline-start: 12px;
+ border-color: ${cssVar.colorBorderSecondary};
+ background: ${cssVar.colorBgElevated};
+ box-shadow: ${cssVar.boxShadowSecondary};
+
+ .result-anchor-label {
+ display: block;
+ }
+ }
+ `,
+ tick: css`
+ flex: none;
+
+ width: 12px;
+ height: 2px;
+ border-radius: 1px;
+
+ background: ${cssVar.colorFill};
+ `,
+ tickActive: css`
+ background: ${cssVar.colorText};
+ `,
+ tickChild: css`
+ width: 7px;
+ `,
+}));
+
+interface ResultAnchorRailProps {
+ rootRef: RefObject<HTMLElement | null>;
+}
+
+const ResultAnchorRail = ({ rootRef }: ResultAnchorRailProps) => {
+ const { t } = useTranslation('chat');
+ const { active, anchors, edge, hostRef, jumpTo } = useResultAnchorRail({ rootRef });
+
+ if (anchors.length < MIN_RAIL_ANCHORS) return null;
+
+ return (
+ <div className={styles.host} ref={hostRef}>
+ <nav
+ aria-label={t('goalProcess.result.nav.label')}
+ className={styles.rail}
+ data-testid={'goal-result-anchor-rail'}
+ style={{ insetInlineEnd: edge }}
+ >
+ {anchors.map((anchor, index) => {
+ const isActive = index === active;
+ return (
+ <button
+ aria-current={isActive ? 'location' : undefined}
+ aria-label={anchor.label}
+ className={cx(styles.item, isActive && styles.itemActive)}
+ key={anchor.id}
+ type={'button'}
+ onClick={() => jumpTo(anchor.id)}
+ >
+ <span
+ className={cx(
+ 'result-anchor-label',
+ styles.label,
+ anchor.level === 1 && styles.labelChild,
+ )}
+ >
+ {anchor.label}
+ </span>
+ <span
+ className={cx(
+ styles.tick,
+ anchor.level === 1 && styles.tickChild,
+ isActive && styles.tickActive,
+ )}
+ />
+ </button>
+ );
+ })}
+ </nav>
+ </div>
+ );
+};
+
+export default ResultAnchorRail;
diff --git a/src/features/AgentGoals/ProcessControl/ResultDeliverables.tsx b/src/features/AgentGoals/ProcessControl/ResultDeliverables.tsx
index f8df1df47f1..9836a39daba 100644
--- a/src/features/AgentGoals/ProcessControl/ResultDeliverables.tsx
+++ b/src/features/AgentGoals/ProcessControl/ResultDeliverables.tsx
@@ -1,18 +1,15 @@
'use client';
-import { Center, Flexbox, Icon, Markdown } from '@lobehub/ui';
+import { Center, Flexbox, Icon } from '@lobehub/ui';
import { ActionIcon, Button, Input, Segmented, Skeleton, Tag, Text } from '@lobehub/ui/base-ui';
-import { createStaticStyles, cssVar } from 'antd-style';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
import { ArrowRight, PackageOpen, SearchIcon, SearchX, X } from 'lucide-react';
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useEntityMarkdown } from '@/features/EntityLink';
import { useActivityTime } from '@/hooks/useActivityTime';
-import { useClientDataSWR } from '@/libs/swr';
-import { portalKeys } from '@/libs/swr/keys';
-import { documentService } from '@/services/document';
+import { coordinatorNodeTitleKey } from './coordinatorCopy';
import {
buildDeliverables,
type DeliverableItem,
@@ -23,67 +20,36 @@ import {
MANY_DELIVERABLES,
} from './deliverableList';
import DeliverableReader from './DeliverableReader';
+import { openTargetOf, useOpenGoalArtifact } from './Deliverables';
import { CitationMark, deliverableIconOf, deliverableTitleOf } from './deliverableVisuals';
import type { GoalGraphView } from './goalGraphViewModel';
import { SectionTitle } from './GoalResultFollowUps';
import type { CriterionOutcome } from './goalResultState';
+import { anchorProps } from './resultAnchors';
/**
* 交付物 on the 结果交付 tab — everything the Goal persisted, in one place.
*
- * The main deliverable (the document the work wrote) leads as a card with the
- * start of its text; every other artifact is a row naming the task that
- * produced it, when, and whether acceptance evidence cites it. A long list
+ * One row per artifact, naming the task that produced it, when, and whether
+ * acceptance evidence cites it; the main deliverable leads, tagged, and every
+ * other one follows. The main deliverable's own text is not previewed here:
+ * it is the document 交付文档 reads in full further down the page. A long list
* grows the tools a long list needs — grouping by task, a type filter and
- * search — and a short one stays a plain list. Any row, or 逐一查看, opens the
- * full-screen reader to page through them in order.
+ * search — and a short one stays a plain list. A row opens where the artifact
+ * lives: a document in the side panel, a file or link at its own target.
*/
const styles = createStaticStyles(({ css }) => ({
card: css`
overflow: hidden;
- border: 1px solid ${cssVar.colorBorderSecondary};
border-radius: ${cssVar.borderRadiusLG};
background: ${cssVar.colorBgContainer};
`,
- excerpt: css`
- pointer-events: none;
- overflow: hidden;
- max-height: 148px;
-
- mask-image: linear-gradient(to bottom, #000 55%, transparent);
- `,
groupTitle: css`
padding-block: 12px 4px;
padding-inline: 12px;
`,
- primary: css`
- cursor: pointer;
-
- display: flex;
- flex-direction: column;
- gap: 12px;
-
- width: 100%;
- padding: 16px;
- border: none;
-
- text-align: start;
-
- background: none;
-
- &:hover {
- background: ${cssVar.colorFillQuaternary};
- }
-
- &:focus-visible {
- outline: 2px solid ${cssVar.colorPrimary};
- outline-offset: -2px;
- }
- `,
row: css`
- cursor: pointer;
-
display: flex;
gap: 12px;
align-items: center;
@@ -96,6 +62,9 @@ const styles = createStaticStyles(({ css }) => ({
text-align: start;
background: none;
+ `,
+ rowOpenable: css`
+ cursor: pointer;
&:hover {
background: ${cssVar.colorFillQuaternary};
@@ -126,95 +95,36 @@ const ProducerAndTime = ({ item }: { item: DeliverableItem }) => {
const DeliverableRow = ({ item, onOpen }: { item: DeliverableItem; onOpen: () => void }) => {
const { t } = useTranslation('chat');
+ // A row that goes nowhere stays inert rather than faking an affordance it
+ // cannot honour — see `openTargetOf`.
+ const openable = !!openTargetOf(item.artifact);
+
return (
- <button
- className={styles.row}
+ <Flexbox
+ horizontal
+ align={'center'}
+ as={openable ? 'button' : 'div'}
+ className={cx(styles.row, openable && styles.rowOpenable)}
data-testid={'goal-deliverable-row'}
- type={'button'}
- onClick={onOpen}
+ gap={12}
+ {...(openable ? { onClick: onOpen, type: 'button' as const } : {})}
>
<Icon color={cssVar.colorTextSecondary} icon={deliverableIconOf(item.artifact)} size={18} />
<Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
- <Text ellipsis weight={500}>
- {deliverableTitleOf(item.artifact, t('goalProcess.deliverables.untitled'))}
- </Text>
- <ProducerAndTime item={item} />
- </Flexbox>
- <CitationMark item={item} />
- </button>
- );
-};
-
-const PrimaryExcerpt = ({ documentId }: { documentId: string }) => {
- // The card is a preview, not a reader: `aria-hidden` rows keep the inline
- // entity chips (no raw URLs) but take no click of their own.
- const markdownProps = useEntityMarkdown();
- const { data: document, isLoading } = useClientDataSWR(
- portalKeys.documentHeader(documentId),
- () => documentService.getDocumentById(documentId),
- );
- if (isLoading)
- return (
- <Flexbox gap={8}>
- <Skeleton height={14} radius={4} />
- <Skeleton height={14} radius={4} width={'80%'} />
- <Skeleton height={14} radius={4} width={'60%'} />
- </Flexbox>
- );
- // The card already names the document; its own leading H1 would repeat it.
- const excerpt = document?.content?.replace(/^\s*#\s[^\n]*\n+/, '');
- if (!excerpt) return null;
- return (
- <div aria-hidden className={styles.excerpt}>
- <Markdown fontSize={13} variant={'chat'} {...markdownProps}>
- {excerpt}
- </Markdown>
- </div>
- );
-};
-
-const PrimaryCard = ({
- item,
- loading,
- onOpen,
-}: {
- item: DeliverableItem;
- loading: boolean;
- onOpen: () => void;
-}) => {
- const { t } = useTranslation('chat');
- const { text, title } = useActivityTime(item.artifact.createdAt);
- return (
- <div className={styles.card}>
- <button
- className={styles.primary}
- data-testid={'goal-deliverable-primary'}
- type={'button'}
- onClick={onOpen}
- >
<Flexbox horizontal align={'center'} gap={8}>
- <Tag color={'blue'}>{t('goalProcess.result.deliverables.primary')}</Tag>
- <Text ellipsis fontSize={15} weight={600}>
+ <Text ellipsis weight={500}>
{deliverableTitleOf(item.artifact, t('goalProcess.deliverables.untitled'))}
</Text>
+ {item.primary && (
+ <Tag color={'blue'} size={'small'}>
+ {t('goalProcess.result.deliverables.primary')}
+ </Tag>
+ )}
</Flexbox>
- {item.artifact.resourceId && <PrimaryExcerpt documentId={item.artifact.resourceId} />}
- <Text fontSize={12} title={title} type={'secondary'}>
- {[
- item.producerTitle &&
- t('goalProcess.result.deliverables.producedBy', { title: item.producerTitle }),
- text,
- loading
- ? undefined
- : item.citedBy.length > 0
- ? t('goalProcess.result.deliverables.citedCount', { count: item.citedBy.length })
- : t('goalProcess.result.deliverables.uncited'),
- ]
- .filter(Boolean)
- .join(' · ')}
- </Text>
- </button>
- </div>
+ <ProducerAndTime item={item} />
+ </Flexbox>
+ <CitationMark item={item} />
+ </Flexbox>
);
};
@@ -265,6 +175,7 @@ const ResultDeliverables = ({
const [readerIndex, setReaderIndex] = useState<number>();
const [type, setType] = useState<DeliverableType | 'all'>('all');
const [query, setQuery] = useState('');
+ const open = useOpenGoalArtifact();
const items = useMemo(
() =>
@@ -272,24 +183,29 @@ const ResultDeliverables = ({
artifacts: graph.artifacts,
outcomes,
primaryResourceId,
- titleOf: (nodeId) => graph.byId[nodeId]?.node.title,
+ // The coordinator's own nodes carry fixed English titles (the terminal
+ // acceptance Task among them); name them as the rest of the goal view
+ // does, since these titles also label the rail's group ticks.
+ titleOf: (nodeId) => {
+ const view = graph.byId[nodeId];
+ if (!view) return undefined;
+ const key = coordinatorNodeTitleKey(view);
+ return key ? t(key as any) : view.node.title;
+ },
}),
- [graph.artifacts, graph.byId, outcomes, primaryResourceId],
+ [graph.artifacts, graph.byId, outcomes, primaryResourceId, t],
);
- const primary = items[0]?.primary ? items[0] : undefined;
- const rest = primary ? items.slice(1) : items;
- const many = rest.length >= MANY_DELIVERABLES;
- const visible = many ? filterDeliverables(rest, { query, type }) : rest;
+ const many = items.length >= MANY_DELIVERABLES;
+ const visible = many ? filterDeliverables(items, { query, type }) : items;
const groups = many ? groupDeliverables(visible) : [{ items: visible }];
- const counts = deliverableTypeCounts(rest);
- const open = (item: DeliverableItem) => setReaderIndex(items.indexOf(item));
+ const counts = deliverableTypeCounts(items);
const title = (
<SectionTitle
extra={
items.length > 0 && (
- <Button icon={ArrowRight} size={'small'} onClick={() => setReaderIndex(0)}>
+ <Button icon={ArrowRight} size={'small'} type={'text'} onClick={() => setReaderIndex(0)}>
{t('goalProcess.result.deliverables.viewAll', { count: items.length })}
</Button>
)
@@ -312,7 +228,6 @@ const ResultDeliverables = ({
return (
<Flexbox data-testid={'goal-result-deliverables'} gap={12}>
{title}
- {primary && <PrimaryCard item={primary} loading={loading} onOpen={() => open(primary)} />}
{many && (
<Flexbox horizontal align={'center'} gap={12} wrap={'wrap'}>
<Segmented
@@ -320,7 +235,7 @@ const ResultDeliverables = ({
value={type}
options={[
{
- label: `${t('goalProcess.result.deliverables.filter.all')} ${rest.length}`,
+ label: `${t('goalProcess.result.deliverables.filter.all')} ${items.length}`,
value: 'all',
},
...TYPE_ORDER.filter((key) => counts.has(key)).map((key) => ({
@@ -355,57 +270,61 @@ const ResultDeliverables = ({
{loading ? (
<LoadingRows />
) : visible.length === 0 ? (
- rest.length > 0 && (
- <Center
- className={styles.card}
- data-testid={'goal-deliverables-no-match'}
- gap={8}
- padding={24}
+ <Center
+ className={styles.card}
+ data-testid={'goal-deliverables-no-match'}
+ gap={8}
+ padding={24}
+ >
+ <Icon color={cssVar.colorTextQuaternary} icon={SearchX} size={24} />
+ <Text weight={500}>
+ {query.trim()
+ ? t('goalProcess.result.deliverables.noMatch', { query: query.trim() })
+ : t('goalProcess.result.deliverables.noMatchType')}
+ </Text>
+ <Button
+ size={'small'}
+ type={'text'}
+ onClick={() => {
+ setQuery('');
+ setType('all');
+ }}
>
- <Icon color={cssVar.colorTextQuaternary} icon={SearchX} size={24} />
- <Text weight={500}>
- {query.trim()
- ? t('goalProcess.result.deliverables.noMatch', { query: query.trim() })
- : t('goalProcess.result.deliverables.noMatchType')}
- </Text>
- <Button
- size={'small'}
- type={'text'}
- onClick={() => {
- setQuery('');
- setType('all');
- }}
- >
- {t('goalProcess.result.deliverables.clearFilter')}
- </Button>
- </Center>
- )
+ {t('goalProcess.result.deliverables.clearFilter')}
+ </Button>
+ </Center>
) : (
- rest.length > 0 && (
- <Flexbox className={styles.card} paddingBlock={4}>
- {groups.map((group) => (
- <Flexbox key={group.nodeId ?? 'rest'}>
- {groups.length > 1 && (
- <Text
- className={styles.groupTitle}
- data-testid={'goal-deliverables-group'}
- fontSize={12}
- type={'secondary'}
- >
- {`${group.title ?? t('goalProcess.result.deliverables.otherTasks')} · ${group.items.length}`}
- </Text>
- )}
- {group.items.map((item) => (
- <DeliverableRow
- item={item}
- key={item.artifact.workVersionId}
- onOpen={() => open(item)}
- />
+ <Flexbox className={styles.card} paddingBlock={4}>
+ {groups.map((group) => (
+ <Flexbox
+ key={group.nodeId ?? 'rest'}
+ {...(groups.length > 1 &&
+ anchorProps(
+ `deliverables:${group.nodeId ?? 'rest'}`,
+ group.title ?? t('goalProcess.result.deliverables.otherTasks'),
+ 1,
))}
- </Flexbox>
- ))}
- </Flexbox>
- )
+ >
+ {groups.length > 1 && (
+ <Text
+ className={styles.groupTitle}
+ data-testid={'goal-deliverables-group'}
+ fontSize={12}
+ type={'secondary'}
+ >
+ {`${group.title ?? t('goalProcess.result.deliverables.otherTasks')} · ${group.items.length}`}
+ </Text>
+ )}
+ {group.items.map((item) => (
+ <DeliverableRow
+ item={item}
+ key={item.artifact.workVersionId}
+ onOpen={() => open(item.artifact)}
+ />
+ ))}
+ </Flexbox>
+ ))}
+ </Flexbox>
)}
{readerIndex !== undefined && (
<DeliverableReader
diff --git a/src/features/AgentGoals/ProcessControl/resultAnchors.test.ts b/src/features/AgentGoals/ProcessControl/resultAnchors.test.ts
new file mode 100644
index 00000000000..a52cab6953f
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/resultAnchors.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ anchorProps,
+ JUMP_MARGIN,
+ jumpScrollTop,
+ pickActiveAnchor,
+ READING_LINE,
+ sameAnchors,
+} from './resultAnchors';
+
+describe('pickActiveAnchor', () => {
+ it('returns -1 when the page has no anchors', () => {
+ expect(pickActiveAnchor([], READING_LINE, false)).toBe(-1);
+ });
+
+ it('keeps the first anchor active before any has reached the reading line', () => {
+ expect(pickActiveAnchor([200, 600, 1200], READING_LINE, false)).toBe(0);
+ });
+
+ it('picks the last anchor whose top has passed the reading line', () => {
+ expect(pickActiveAnchor([-900, -300, 80, 700], 100, false)).toBe(2);
+ });
+
+ it('picks the last anchor at the bottom of the page even if it starts lower', () => {
+ expect(pickActiveAnchor([-900, -300, 80, 700], 100, true)).toBe(3);
+ });
+});
+
+describe('jumpScrollTop', () => {
+ it('leaves the section it jumped to at the jump margin', () => {
+ expect(jumpScrollTop(400, 200, 4000)).toBe(400 + 200 - JUMP_MARGIN);
+ });
+
+ it('never scrolls past either end of the range', () => {
+ expect(jumpScrollTop(10, 0, 4000)).toBe(0);
+ expect(jumpScrollTop(5000, 0, 1000)).toBe(1000);
+ expect(jumpScrollTop(100, 0, 0)).toBe(0);
+ });
+});
+
+describe('a jump lands on the section that was clicked', () => {
+ // The reading line must reach a section that sits at the jump margin, or a
+ // section only a few rows high (验收标准 with a single criterion) hands the
+ // highlight to the section after it — the r1 defect.
+ it('keeps the short section the reader clicked on active', () => {
+ expect(READING_LINE).toBeGreaterThanOrEqual(JUMP_MARGIN);
+
+ const sectionHeight = 40;
+ const landedTops = [JUMP_MARGIN, JUMP_MARGIN + sectionHeight, JUMP_MARGIN + 900];
+ expect(pickActiveAnchor(landedTops, READING_LINE, false)).toBe(0);
+ });
+});
+
+describe('sameAnchors', () => {
+ it('compares ids and labels in order', () => {
+ const anchors = [{ id: 'a', label: 'A', level: 0 as const }];
+ expect(sameAnchors(anchors, [{ id: 'a', label: 'A', level: 0 }])).toBe(true);
+ expect(sameAnchors(anchors, [{ id: 'a', label: 'B', level: 0 }])).toBe(false);
+ expect(sameAnchors(anchors, [])).toBe(false);
+ });
+});
+
+describe('anchorProps', () => {
+ it('marks a section with its id, label and level', () => {
+ expect(anchorProps('trail', 'Exploration', 1)).toEqual({
+ 'data-result-anchor': 'trail',
+ 'data-result-anchor-label': 'Exploration',
+ 'data-result-anchor-level': 1,
+ });
+ });
+
+ it('marks a plain section as level 0', () => {
+ expect(anchorProps('overview', 'Overview')['data-result-anchor-level']).toBe(0);
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/resultAnchors.ts b/src/features/AgentGoals/ProcessControl/resultAnchors.ts
new file mode 100644
index 00000000000..f0022efc3ac
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/resultAnchors.ts
@@ -0,0 +1,65 @@
+/**
+ * Anchors on the 结果交付 page. Sections mark themselves with these data
+ * attributes; the rail reads them from the DOM, so a section that renders
+ * nothing — or a deliverable group a filter hides — drops out on its own.
+ */
+
+export const ANCHOR_ATTR = 'data-result-anchor';
+export const ANCHOR_LABEL_ATTR = 'data-result-anchor-label';
+export const ANCHOR_LEVEL_ATTR = 'data-result-anchor-level';
+
+/** Below this many anchors the page is short enough to scroll by hand. */
+export const MIN_RAIL_ANCHORS = 3;
+
+/**
+ * Where a section counts as being read: this far below the scroller's top edge.
+ *
+ * Kept small on purpose. A section only a few rows high (验收标准 with one
+ * criterion, 探索过程 when the work left no trail) never reaches further down,
+ * so a deeper line would credit the section *after* the one the reader is on.
+ */
+export const READING_LINE = 24;
+
+/** Space left above a section the reader jumped to, so its title clears the edge. */
+export const JUMP_MARGIN = 16;
+
+export interface ResultAnchor {
+ id: string;
+ label: string;
+ /** 0 for a page section, 1 for a group inside one. */
+ level: 0 | 1;
+}
+
+export const anchorProps = (id: string, label: string, level: 0 | 1 = 0) => ({
+ [ANCHOR_ATTR]: id,
+ [ANCHOR_LABEL_ATTR]: label,
+ [ANCHOR_LEVEL_ATTR]: level,
+});
+
+export const sameAnchors = (a: ResultAnchor[], b: ResultAnchor[]) =>
+ a.length === b.length &&
+ a.every((anchor, i) => anchor.id === b[i].id && anchor.label === b[i].label);
+
+/**
+ * The anchor being read: the last one whose top has passed the reading line,
+ * measured against the scroller's viewport. At the bottom of the page the last
+ * anchor wins even if it starts lower, so a short closing section can still be
+ * highlighted. Returns -1 when there is nothing to mark.
+ */
+export const pickActiveAnchor = (tops: number[], readingLine: number, atBottom: boolean) => {
+ if (tops.length === 0) return -1;
+ if (atBottom) return tops.length - 1;
+ let active = 0;
+ for (const [i, top] of tops.entries()) {
+ if (top <= readingLine) active = i;
+ else break;
+ }
+ return active;
+};
+
+/**
+ * Where to scroll so a section's top lands `JUMP_MARGIN` below the scroller's
+ * top edge, never past either end of the scroll range.
+ */
+export const jumpScrollTop = (sectionTop: number, scrollTop: number, maxScrollTop: number) =>
+ Math.min(Math.max(0, scrollTop + sectionTop - JUMP_MARGIN), Math.max(0, maxScrollTop));
diff --git a/src/features/AgentGoals/ProcessControl/useResultAnchorRail.test.ts b/src/features/AgentGoals/ProcessControl/useResultAnchorRail.test.ts
new file mode 100644
index 00000000000..3431542779e
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/useResultAnchorRail.test.ts
@@ -0,0 +1,88 @@
+import { renderHook, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useResultAnchorRail } from './useResultAnchorRail';
+
+const scrollTo = vi.fn();
+
+const setReducedMotion = (reduce: boolean) => {
+ vi.stubGlobal('matchMedia', (query: string) => ({
+ addEventListener: vi.fn(),
+ matches: reduce && query.includes('prefers-reduced-motion'),
+ media: query,
+ onchange: null,
+ removeEventListener: vi.fn(),
+ }));
+};
+
+/** A scrolling page with one section per label, plus the root the rail scans. */
+const buildPage = (labels: string[]) => {
+ const scroller = document.createElement('div');
+ scroller.style.overflowY = 'auto';
+ const root = document.createElement('div');
+ scroller.append(root);
+ document.body.append(scroller);
+ for (const label of labels) {
+ const section = document.createElement('div');
+ section.setAttribute('data-result-anchor', `section-${label}`);
+ section.setAttribute('data-result-anchor-label', label);
+ section.setAttribute('data-result-anchor-level', '0');
+ root.append(section);
+ }
+ return { root, scroller };
+};
+
+beforeEach(() => {
+ // The rail marks sections that render something, and jsdom has no layout.
+ Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
+ configurable: true,
+ get: () => 40,
+ });
+ Element.prototype.scrollTo = scrollTo as never;
+ setReducedMotion(false);
+});
+
+afterEach(() => {
+ scrollTo.mockClear();
+ vi.unstubAllGlobals();
+ document.body.innerHTML = '';
+});
+
+describe('useResultAnchorRail', () => {
+ it('keeps up with a label rewritten in place, with no child added or removed', async () => {
+ const { root } = buildPage(['Alpha', 'Bravo', 'Charlie']);
+ const { result } = renderHook(() => useResultAnchorRail({ rootRef: { current: root } }));
+ await waitFor(() => expect(result.current.anchors).toHaveLength(3));
+ expect(result.current.anchors[1].label).toBe('Bravo');
+
+ // What a language switch does: the attribute on the section that is already
+ // there gets rewritten. The child list never changes, so a rail that only
+ // watched childList would keep the previous language on every tick.
+ root
+ .querySelector('[data-result-anchor="section-Bravo"]')!
+ .setAttribute('data-result-anchor-label', '布拉沃');
+
+ await waitFor(() => expect(result.current.anchors[1].label).toBe('布拉沃'));
+ });
+
+ it('jumps without animation when the reader asked for reduced motion', async () => {
+ setReducedMotion(true);
+ const { root } = buildPage(['Alpha', 'Bravo', 'Charlie']);
+ const { result } = renderHook(() => useResultAnchorRail({ rootRef: { current: root } }));
+ await waitFor(() => expect(result.current.anchors).toHaveLength(3));
+
+ result.current.jumpTo('section-Charlie');
+
+ expect(scrollTo).toHaveBeenCalledWith(expect.objectContaining({ behavior: 'auto' }));
+ });
+
+ it('keeps the animated jump when motion is welcome', async () => {
+ const { root } = buildPage(['Alpha', 'Bravo', 'Charlie']);
+ const { result } = renderHook(() => useResultAnchorRail({ rootRef: { current: root } }));
+ await waitFor(() => expect(result.current.anchors).toHaveLength(3));
+
+ result.current.jumpTo('section-Charlie');
+
+ expect(scrollTo).toHaveBeenCalledWith(expect.objectContaining({ behavior: 'smooth' }));
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/useResultAnchorRail.ts b/src/features/AgentGoals/ProcessControl/useResultAnchorRail.ts
new file mode 100644
index 00000000000..de32022b2f1
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/useResultAnchorRail.ts
@@ -0,0 +1,164 @@
+'use client';
+
+import { type RefObject, useEffect, useRef, useState } from 'react';
+
+import {
+ ANCHOR_ATTR,
+ ANCHOR_LABEL_ATTR,
+ ANCHOR_LEVEL_ATTR,
+ JUMP_MARGIN,
+ pickActiveAnchor,
+ READING_LINE,
+ type ResultAnchor,
+ sameAnchors,
+} from './resultAnchors';
+
+/** How far below the scroller's top edge the rail pins itself. */
+export const RAIL_TOP = 96;
+
+/**
+ * The rail belongs to the page's right edge, not to the column the sections are
+ * laid out in. At rest the ticks sit this far inside the scroller's right edge,
+ * and never closer than RAIL_EDGE_MIN to the column's own edge — so a narrowed
+ * column (the document panel open) keeps them outside the text, and a wide one
+ * puts them against the page instead of inside the container.
+ */
+export const RAIL_MARGIN = 16;
+export const RAIL_EDGE_MIN = 8;
+
+/**
+ * One row per section, and the line-height the labels take inside it. Both use
+ * this number: the row must stay exactly as tall with the labels open as with
+ * them closed, or every tick below the pointer slides out from under it between
+ * hover and click. Wide enough that the names do not read as a solid block.
+ */
+export const RAIL_ROW = 22;
+
+const scrollParentOf = (element: HTMLElement): HTMLElement | null => {
+ for (let node = element.parentElement; node; node = node.parentElement) {
+ const { overflowY } = getComputedStyle(node);
+ if (overflowY === 'auto' || overflowY === 'scroll') return node;
+ }
+ return null;
+};
+
+const anchorElement = (root: HTMLElement, id: string) =>
+ root.querySelector<HTMLElement>(`[${ANCHOR_ATTR}="${CSS.escape(id)}"]`);
+
+const readAnchors = (root: HTMLElement): ResultAnchor[] =>
+ [...root.querySelectorAll<HTMLElement>(`[${ANCHOR_ATTR}]`)]
+ // A section that renders nothing leaves an empty wrapper behind.
+ .filter((element) => element.offsetHeight > 0)
+ .map((element) => ({
+ id: element.getAttribute(ANCHOR_ATTR)!,
+ label: element.getAttribute(ANCHOR_LABEL_ATTR) ?? '',
+ level: element.getAttribute(ANCHOR_LEVEL_ATTR) === '1' ? 1 : 0,
+ }));
+
+interface UseResultAnchorRailOptions {
+ rootRef: RefObject<HTMLElement | null>;
+}
+
+/**
+ * Everything the rail knows: which sections the page is showing, which one the
+ * reader is on, where the page's right edge is, and how to jump to a section. It
+ * reads all of that from the DOM, so it needs no knowledge of which sections a
+ * given Goal renders and it follows the page as filters and acceptance data
+ * change underneath it.
+ */
+export const useResultAnchorRail = ({ rootRef }: UseResultAnchorRailOptions) => {
+ const hostRef = useRef<HTMLDivElement>(null);
+ const [anchors, setAnchors] = useState<ResultAnchor[]>([]);
+ const [active, setActive] = useState(0);
+ const [edge, setEdge] = useState(-RAIL_MARGIN);
+
+ // Sections load and filters change after mount; re-read on DOM changes.
+ useEffect(() => {
+ const root = rootRef.current;
+ if (!root) return;
+ let frame = 0;
+ const scan = () => {
+ cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(() => {
+ const next = readAnchors(root);
+ setAnchors((prev) => (sameAnchors(prev, next) ? prev : next));
+ });
+ };
+ scan();
+ const observer = new MutationObserver(scan);
+ // Section titles are the tick labels, and a language switch rewrites those
+ // attributes in place — nothing is added or removed — so watch them too, or
+ // the rail keeps the previous language until some unrelated child appears.
+ observer.observe(root, {
+ attributeFilter: [ANCHOR_ATTR, ANCHOR_LABEL_ATTR],
+ attributes: true,
+ childList: true,
+ subtree: true,
+ });
+ return () => {
+ observer.disconnect();
+ cancelAnimationFrame(frame);
+ };
+ }, [rootRef]);
+
+ useEffect(() => {
+ const root = rootRef.current;
+ const scroller = root && scrollParentOf(root);
+ if (!root || !scroller || anchors.length === 0) return;
+ let frame = 0;
+ const update = () => {
+ cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(() => {
+ const readingLine = scroller.getBoundingClientRect().top + READING_LINE;
+ const tops = anchors.map(
+ (anchor) =>
+ anchorElement(root, anchor.id)?.getBoundingClientRect().top ?? Number.POSITIVE_INFINITY,
+ );
+ const atBottom = scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 2;
+ setActive(Math.max(0, pickActiveAnchor(tops, readingLine, atBottom)));
+
+ // Measure where the page's right edge actually is rather than assuming
+ // it: the document panel and the window both narrow the column under us.
+ const host = hostRef.current;
+ if (host) {
+ const gap = scroller.getBoundingClientRect().right - host.getBoundingClientRect().right;
+ setEdge(Math.min(-RAIL_EDGE_MIN, RAIL_MARGIN - gap));
+ }
+ });
+ };
+ update();
+ scroller.addEventListener('scroll', update, { passive: true });
+ window.addEventListener('resize', update);
+ const resizeObserver = new ResizeObserver(update);
+ resizeObserver.observe(scroller);
+ return () => {
+ scroller.removeEventListener('scroll', update);
+ window.removeEventListener('resize', update);
+ resizeObserver.disconnect();
+ cancelAnimationFrame(frame);
+ };
+ }, [anchors, rootRef]);
+
+ const jumpTo = (id: string) => {
+ const root = rootRef.current;
+ const scroller = root && scrollParentOf(root);
+ const section = root && anchorElement(root, id);
+ if (!scroller || !section) return;
+ // The jump already moves the reader; the animation is the decoration on top
+ // of it, so it is the part that goes when the reader asked for less motion.
+ const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ const sectionTop =
+ section.getBoundingClientRect().top -
+ scroller.getBoundingClientRect().top +
+ scroller.scrollTop;
+ scroller.scrollTo({
+ behavior: reduceMotion ? 'auto' : 'smooth',
+ top: Math.min(
+ Math.max(0, sectionTop - JUMP_MARGIN),
+ Math.max(0, scroller.scrollHeight - scroller.clientHeight),
+ ),
+ });
+ };
+
+ return { active, anchors, edge, hostRef, jumpTo };
+};