🤯 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): open north-star metrics in the side panel and chart them with @lobehub/charts (#21126)
Arvin Xu8c54630fb01d
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 0cc1ac7e5a3..1ded2590306 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -972,6 +972,18 @@"goalProcess.northStar.declare.title": "Declare metric","goalProcess.northStar.declare.titleLabel": "Display name (optional)","goalProcess.northStar.declare.titlePlaceholder": "e.g. Followers / Open security issues",+ "goalProcess.northStar.detail.history": "Observations ({{count}})",+ "goalProcess.northStar.detail.removed": "This metric is no longer declared on the goal",+ "goalProcess.northStar.detail.source.agent": "Recorded by agent",+ "goalProcess.northStar.detail.source.api": "Written via API",+ "goalProcess.northStar.detail.source.manual": "Recorded manually",+ "goalProcess.northStar.detail.source.probe": "Collected",+ "goalProcess.northStar.detail.target": "Target",+ "goalProcess.northStar.detail.title": "Metric",+ "goalProcess.northStar.detail.trend": "Trend",+ "goalProcess.northStar.detail.trendEmpty": "The trend appears after a second observation",+ "goalProcess.northStar.edit.submit": "Save",+ "goalProcess.northStar.edit.title": "Adjust target","goalProcess.northStar.emptyHint": "No measurable target declared yet","goalProcess.northStar.lastObserved": "Last observed {{time}}","goalProcess.northStar.met": "Met",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 6d30dff4d6e..ef329cc6f00 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -972,6 +972,18 @@"goalProcess.northStar.declare.title": "声明指标","goalProcess.northStar.declare.titleLabel": "显示名(可选)","goalProcess.northStar.declare.titlePlaceholder": "如 粉丝总数 / 未关闭安全 issue",+ "goalProcess.northStar.detail.history": "观测记录({{count}})",+ "goalProcess.northStar.detail.removed": "这个指标已从目标中移除",+ "goalProcess.northStar.detail.source.agent": "Agent 记录",+ "goalProcess.northStar.detail.source.api": "接口写入",+ "goalProcess.northStar.detail.source.manual": "手动记录",+ "goalProcess.northStar.detail.source.probe": "自动采集",+ "goalProcess.northStar.detail.target": "目标",+ "goalProcess.northStar.detail.title": "指标",+ "goalProcess.northStar.detail.trend": "趋势",+ "goalProcess.northStar.detail.trendEmpty": "再记录一次观测后显示趋势",+ "goalProcess.northStar.edit.submit": "保存",+ "goalProcess.northStar.edit.title": "调整目标","goalProcess.northStar.emptyHint": "尚未声明可衡量的目标","goalProcess.northStar.lastObserved": "最近观测 {{time}}","goalProcess.northStar.met": "已达标",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex c52f4fe7ad6..184b9c0f271 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2371,6 +2371,18 @@ export default {'goalProcess.northStar.record.valueLabel': 'Current value of {{key}}','goalProcess.northStar.record.submit': 'Record','goalProcess.northStar.record.failed': 'Failed to record the observation',+ 'goalProcess.northStar.detail.history': 'Observations ({{count}})',+ 'goalProcess.northStar.detail.removed': 'This metric is no longer declared on the goal',+ 'goalProcess.northStar.detail.source.agent': 'Recorded by agent',+ 'goalProcess.northStar.detail.source.api': 'Written via API',+ 'goalProcess.northStar.detail.source.manual': 'Recorded manually',+ 'goalProcess.northStar.detail.source.probe': 'Collected',+ 'goalProcess.northStar.detail.target': 'Target',+ 'goalProcess.northStar.detail.title': 'Metric',+ 'goalProcess.northStar.detail.trend': 'Trend',+ 'goalProcess.northStar.detail.trendEmpty': 'The trend appears after a second observation',+ 'goalProcess.northStar.edit.submit': 'Save',+ 'goalProcess.northStar.edit.title': 'Adjust target','goalProcess.frontier.add': 'Add task','goalProcess.frontier.needsYou': '{{count}} need you','goalProcess.frontier.advanceable': '{{count}} can advance',diff --git a/src/features/AgentGoals/GoalDetailPage.test.tsx b/src/features/AgentGoals/GoalDetailPage.test.tsxindex 8d69619e47f..28ab80c5881 100644--- a/src/features/AgentGoals/GoalDetailPage.test.tsx+++ b/src/features/AgentGoals/GoalDetailPage.test.tsx@@ -23,7 +23,7 @@ vi.mock('@/store/goal', () => ({: {},id: 'goal_1',projectId: null,- requirement: null,+ requirement: 'Reach 1,100 followers',status: 'review',title: 'Ship it',},@@ -106,8 +106,8 @@ vi.mock('./GoalChat', () => ({}));vi.mock('./GoalDetailActions', () => ({ default: () => null }));vi.mock('./GoalHeaderMetrics', () => ({ default: () => null }));-vi.mock('./GoalRequirement', () => ({ default: () => null }));-vi.mock('./NorthStarMetrics', () => ({ default: () => null }));+vi.mock('./GoalRequirement', () => ({ default: () => <div data-testid="goal-requirement" /> }));+vi.mock('./NorthStarMetrics', () => ({ default: () => <div data-testid="goal-north-star" /> }));// The result page's composer lives inside ProcessControl; the page owns where// its message goes, so the stub only exposes the hand-off.vi.mock('./ProcessControl', () => ({@@ -146,6 +146,19 @@ describe('GoalDetailPage', () => {mocks.showPortal = false;});+ // The measured numbers are what executing the requirement has observed, so+ // they read below it as its outcome.+ it('renders the north-star metrics below the requirement', () => {+ render(<GoalDetailPage goalId={'goal_1'} />);++ expect(+ screen+ .getByTestId('goal-requirement')+ .compareDocumentPosition(screen.getByTestId('goal-north-star')) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ });+// On the agent-less route the task workspace owns the portal host, but the// supervision record has no other home: the supervising agent's avatar must// still open it, and must name it as the supervision record to open.diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsxindex 9ff00a6d086..e099cee9c15 100644--- a/src/features/AgentGoals/GoalDetailPage.tsx+++ b/src/features/AgentGoals/GoalDetailPage.tsx@@ -284,15 +284,13 @@ 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 follows the requirement it measures: the+ numbers are what executing that requirement has observed so+ far, so they read as its outcome, below it. */}+ <NorthStarMetrics canEdit={canEdit} goalId={goalId} /></Flexbox><ProcessControldiff --git a/src/features/AgentGoals/NorthStarMetrics/DeclareMetricModal.tsx b/src/features/AgentGoals/NorthStarMetrics/DeclareMetricModal.tsxindex 8e94542759e..bc187cba3f4 100644--- a/src/features/AgentGoals/NorthStarMetrics/DeclareMetricModal.tsx+++ b/src/features/AgentGoals/NorthStarMetrics/DeclareMetricModal.tsx@@ -1,6 +1,6 @@'use client';-import type { GoalMetricComparison } from '@lobechat/types';+import type { GoalMetricComparison, GoalMetricCriterion } from '@lobechat/types';import { Flexbox } from '@lobehub/ui';import {Button,@@ -22,110 +22,122 @@ import { useGoalStore } from '@/store/goal';* Declare one measured acceptance clause: "this series must reach this* number". The key doubles as the series name the probe / manual observations* write to, so declaring is enough — the first observation creates the series.+ * Given an existing clause it edits that clause in place: the declare merges+ * by key, so the key stays locked and only the name, condition and target move.*/-const DeclareMetricContent = memo<{ goalId: string }>(({ goalId }) => {- const { t } = useTranslation('chat');- const { close } = useModalContext();- const declareGoalMetric = useGoalStore((s) => s.declareGoalMetric);+const DeclareMetricContent = memo<{ goalId: string; initial?: GoalMetricCriterion }>(+ ({ goalId, initial }) => {+ const { t } = useTranslation('chat');+ const { close } = useModalContext();+ const declareGoalMetric = useGoalStore((s) => s.declareGoalMetric);- const [key, setKey] = useState('');- const [title, setTitle] = useState('');- const [op, setOp] = useState<GoalMetricComparison>('gte');- const [target, setTarget] = useState('');- const [busy, setBusy] = useState(false);+ const [key, setKey] = useState(initial?.key ?? '');+ const [title, setTitle] = useState(initial?.title ?? '');+ const [op, setOp] = useState<GoalMetricComparison>(initial?.op ?? 'gte');+ const [target, setTarget] = useState(initial ? String(initial.target) : '');+ const [busy, setBusy] = useState(false);- const submit = async () => {- const trimmedKey = key.trim();- const parsedTarget = Number(target);- if (!trimmedKey || !Number.isFinite(parsedTarget) || busy) return;- setBusy(true);- try {- await declareGoalMetric(goalId, {- key: trimmedKey,- op,- target: parsedTarget,- title: title.trim() || undefined,- });- close();- } catch (error) {- // Keep the form open — a silent close would be indistinguishable from success.- console.error('[NorthStar] failed to declare metric:', error);- toast.error(t('goalProcess.northStar.declare.failed'));- } finally {- setBusy(false);- }- };+ const submit = async () => {+ const trimmedKey = key.trim();+ const parsedTarget = Number(target);+ if (!trimmedKey || !Number.isFinite(parsedTarget) || busy) return;+ setBusy(true);+ try {+ await declareGoalMetric(goalId, {+ key: trimmedKey,+ op,+ target: parsedTarget,+ title: title.trim() || undefined,+ });+ close();+ } catch (error) {+ // Keep the form open — a silent close would be indistinguishable from success.+ console.error('[NorthStar] failed to declare metric:', error);+ toast.error(t('goalProcess.northStar.declare.failed'));+ } finally {+ setBusy(false);+ }+ };- return (- <Flexbox gap={16} paddingBlock={'4px 8px'}>- <Flexbox gap={6}>- <Text fontSize={13} weight={500}>- {t('goalProcess.northStar.declare.keyLabel')}- </Text>- <Input- autoFocus- placeholder={t('goalProcess.northStar.declare.keyPlaceholder')}- value={key}- onChange={(e) => setKey(e.target.value)}- />- </Flexbox>- <Flexbox gap={6}>- <Text fontSize={13} weight={500}>- {t('goalProcess.northStar.declare.titleLabel')}- </Text>- <Input- placeholder={t('goalProcess.northStar.declare.titlePlaceholder')}- value={title}- onChange={(e) => setTitle(e.target.value)}- />- </Flexbox>- <Flexbox horizontal gap={12}>- <Flexbox flex={1} gap={6}>+ return (+ <Flexbox gap={16} paddingBlock={'4px 8px'}>+ <Flexbox gap={6}><Text fontSize={13} weight={500}>- {t('goalProcess.northStar.declare.opLabel')}+ {t('goalProcess.northStar.declare.keyLabel')}</Text>- <Select- value={op}- options={(['gte', 'lte', 'gt', 'lt', 'eq'] as const).map((value) => ({- label: t(`goalProcess.northStar.op.${value}` as const),- value,- }))}- onChange={(value) => setOp(value as GoalMetricComparison)}+ <Input+ autoFocus={!initial}+ disabled={!!initial}+ placeholder={t('goalProcess.northStar.declare.keyPlaceholder')}+ value={key}+ onChange={(e) => setKey(e.target.value)}/></Flexbox>- <Flexbox flex={1} gap={6}>+ <Flexbox gap={6}><Text fontSize={13} weight={500}>- {t('goalProcess.northStar.declare.targetLabel')}+ {t('goalProcess.northStar.declare.titleLabel')}</Text><Input- placeholder={'10000'}- value={target}- onChange={(e) => setTarget(e.target.value)}- onPressEnter={() => void submit()}+ placeholder={t('goalProcess.northStar.declare.titlePlaceholder')}+ value={title}+ onChange={(e) => setTitle(e.target.value)}/></Flexbox>+ <Flexbox horizontal gap={12}>+ <Flexbox flex={1} gap={6}>+ <Text fontSize={13} weight={500}>+ {t('goalProcess.northStar.declare.opLabel')}+ </Text>+ <Select+ value={op}+ options={(['gte', 'lte', 'gt', 'lt', 'eq'] as const).map((value) => ({+ label: t(`goalProcess.northStar.op.${value}` as const),+ value,+ }))}+ onChange={(value) => setOp(value as GoalMetricComparison)}+ />+ </Flexbox>+ <Flexbox flex={1} gap={6}>+ <Text fontSize={13} weight={500}>+ {t('goalProcess.northStar.declare.targetLabel')}+ </Text>+ <Input+ placeholder={'10000'}+ value={target}+ onChange={(e) => setTarget(e.target.value)}+ onPressEnter={() => void submit()}+ />+ </Flexbox>+ </Flexbox>+ <Flexbox horizontal justify={'flex-end'}>+ <Button+ disabled={!key.trim() || !Number.isFinite(Number(target)) || target.trim() === ''}+ loading={busy}+ type={'primary'}+ onClick={() => void submit()}+ >+ {initial+ ? t('goalProcess.northStar.edit.submit')+ : t('goalProcess.northStar.declare.submit')}+ </Button>+ </Flexbox></Flexbox>- <Flexbox horizontal justify={'flex-end'}>- <Button- disabled={!key.trim() || !Number.isFinite(Number(target)) || target.trim() === ''}- loading={busy}- type={'primary'}- onClick={() => void submit()}- >- {t('goalProcess.northStar.declare.submit')}- </Button>- </Flexbox>- </Flexbox>- );-});+ );+ },+);DeclareMetricContent.displayName = 'DeclareMetricContent';-export const openDeclareMetricModal = (goalId: string): ModalInstance =>+export const openDeclareMetricModal = (+ goalId: string,+ initial?: GoalMetricCriterion,+): ModalInstance =>createModal({- content: <DeclareMetricContent goalId={goalId} />,+ content: <DeclareMetricContent goalId={goalId} initial={initial} />,footer: null,maskClosable: true,- title: t('goalProcess.northStar.declare.title', { ns: 'chat' }),+ title: initial+ ? t('goalProcess.northStar.edit.title', { ns: 'chat' })+ : t('goalProcess.northStar.declare.title', { ns: 'chat' }),width: 'min(90%, 480px)',});diff --git a/src/features/AgentGoals/NorthStarMetrics/MetBadge.tsx b/src/features/AgentGoals/NorthStarMetrics/MetBadge.tsxnew file mode 100644index 00000000000..b06756397fd--- /dev/null+++ b/src/features/AgentGoals/NorthStarMetrics/MetBadge.tsx@@ -0,0 +1,32 @@+'use client';++import { cssVar, Flexbox, Icon, Text } from '@lobehub/ui';+import { Check } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++/**+ * "Met" beside a metric's name: a quiet check and word in the success color.+ * A filled tag outweighed the number it qualifies.+ */+const MetBadge = memo(() => {+ const { t } = useTranslation('chat');++ return (+ <Flexbox+ horizontal+ align={'center'}+ gap={3}+ style={{ color: cssVar.colorSuccess, flex: 'none' }}+ >+ <Icon icon={Check} size={12} />+ <Text fontSize={12} style={{ color: 'inherit' }}>+ {t('goalProcess.northStar.met')}+ </Text>+ </Flexbox>+ );+});++MetBadge.displayName = 'NorthStarMetBadge';++export default MetBadge;diff --git a/src/features/AgentGoals/NorthStarMetrics/Sparkline.tsx b/src/features/AgentGoals/NorthStarMetrics/Sparkline.tsxdeleted file mode 100644index 9c4e6cc7d80..00000000000--- a/src/features/AgentGoals/NorthStarMetrics/Sparkline.tsx+++ /dev/null@@ -1,38 +0,0 @@-'use client';--import { cssVar } from '@lobehub/ui';-import { memo } from 'react';--/**- * Trend-only miniature: no axes, no labels — the card's number carries the- * value, this carries the shape of the climb.- */-const Sparkline = memo<{ met?: boolean; values: number[] }>(({ met, values }) => {- const width = 84;- const height = 22;- if (values.length < 2) return null;-- const min = Math.min(...values);- const max = Math.max(...values);- const span = Math.max(1e-9, max - min);- const sx = (index: number) => (index / (values.length - 1)) * (width - 2) + 1;- const sy = (value: number) => height - 2 - ((value - min) / span) * (height - 4);- const d = values- .map((value, index) => `${index === 0 ? 'M' : 'L'} ${sx(index)} ${sy(value)}`)- .join(' ');-- return (- <svg aria-hidden height={height} width={width}>- <path- d={d}- fill={'none'}- stroke={met ? cssVar.colorSuccess : cssVar.colorInfo}- strokeWidth={1.5}- />- </svg>- );-});--Sparkline.displayName = 'NorthStarSparkline';--export default Sparkline;diff --git a/src/features/AgentGoals/NorthStarMetrics/cardKeyboard.test.ts b/src/features/AgentGoals/NorthStarMetrics/cardKeyboard.test.tsnew file mode 100644index 00000000000..e9e1759948a--- /dev/null+++ b/src/features/AgentGoals/NorthStarMetrics/cardKeyboard.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it, vi } from 'vitest';++import { handleCardKeyDown } from './cardKeyboard';++const card = {} as EventTarget;+const keyEvent = (key: string, target: EventTarget = card) => ({+ currentTarget: card as any,+ key,+ preventDefault: vi.fn(),+ target: target as any,+});++describe('handleCardKeyDown', () => {+ it('opens the detail on Enter or Space on the card itself', () => {+ for (const key of ['Enter', ' ']) {+ const open = vi.fn();+ const event = keyEvent(key);+ handleCardKeyDown(event, open);+ expect(open).toHaveBeenCalledOnce();+ expect(event.preventDefault).toHaveBeenCalled();+ }+ });++ it('ignores other keys', () => {+ const open = vi.fn();+ handleCardKeyDown(keyEvent('Tab'), open);+ expect(open).not.toHaveBeenCalled();+ });++ // Regression: Enter on the nested record button bubbled to the card, which+ // prevented the button's own click and opened the detail instead.+ it('leaves keys pressed on a nested control to that control', () => {+ const open = vi.fn();+ const event = keyEvent('Enter', {} as EventTarget);+ handleCardKeyDown(event, open);+ expect(open).not.toHaveBeenCalled();+ expect(event.preventDefault).not.toHaveBeenCalled();+ });+});diff --git a/src/features/AgentGoals/NorthStarMetrics/cardKeyboard.ts b/src/features/AgentGoals/NorthStarMetrics/cardKeyboard.tsnew file mode 100644index 00000000000..11952336d0e--- /dev/null+++ b/src/features/AgentGoals/NorthStarMetrics/cardKeyboard.ts@@ -0,0 +1,17 @@+import type { KeyboardEvent } from 'react';++/**+ * Enter / Space on the focused card opens its detail, as a click would. Keys+ * pressed on a control nested in the card (its record button) bubble here too;+ * those belong to that control, so they are left alone.+ */+export const handleCardKeyDown = (+ event: Pick<KeyboardEvent, 'currentTarget' | 'key' | 'preventDefault' | 'target'>,+ open: () => void,+) => {+ if (event.target !== event.currentTarget) return;+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault();+ open();+ }+};diff --git a/src/features/AgentGoals/NorthStarMetrics/index.tsx b/src/features/AgentGoals/NorthStarMetrics/index.tsxindex 888b8cc7c2a..2722ac986fd 100644--- a/src/features/AgentGoals/NorthStarMetrics/index.tsx+++ b/src/features/AgentGoals/NorthStarMetrics/index.tsx@@ -1,5 +1,6 @@'use client';+import { SparkAreaChart } from '@lobehub/charts';import {Button,createStaticStyles,@@ -7,22 +8,25 @@ import {Flexbox,Icon,Skeleton,- Tag,Text,Tooltip,+ useTheme,} from '@lobehub/ui';import dayjs from 'dayjs';-import { Check, Plus, Target } from 'lucide-react';+import { Plus, Target } from 'lucide-react';import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';+import { useChatStore } from '@/store/chat';+import { PortalViewType } from '@/store/chat/slices/portal/initialState';import { goalSelectors, useGoalStore } from '@/store/goal';+import { handleCardKeyDown } from './cardKeyboard';import { openDeclareMetricModal } from './DeclareMetricModal';+import MetBadge from './MetBadge';import { buildNorthStarCards, formatMetricValue, type NorthStarCard } from './northStar';import { openRecordObservationModal } from './RecordObservationModal';-import Sparkline from './Sparkline';/*** The goal's north-star strip: how far the *world* is from the declared@@ -30,7 +34,8 @@ import Sparkline from './Sparkline';* which only say what the run cost. Clauses come from* `config.acceptance.metrics` — the same numbers the coordinator's measured* gate reads — so the strip and the acceptance verdict can never disagree- * about what is being tracked.+ * about what is being tracked. A card opens its clause's detail in the+ * right-hand Portal: the full trend, the observation history and the actions.*/const styles = createStaticStyles(({ css }) => ({@@ -39,30 +44,53 @@ const styles = createStaticStyles(({ css }) => ({min-width: 236px;max-width: 340px;- padding-block: 10px;- padding-inline: 14px;+ padding-block: 12px;+ padding-inline: 16px;border: 1px solid ${cssVar.colorBorderSecondary};border-radius: ${cssVar.borderRadiusLG};background: ${cssVar.colorBgContainer};++ transition: border-color 0.2s;++ &:hover {+ border-color: ${cssVar.colorBorder};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimaryBorder};+ outline-offset: 1px;+ }`,metValue: css`color: ${cssVar.colorSuccess};`,+ /*+ * The chart has no dashed-series option. It names each series path after its+ * category, so the target reference line is styled from here: a dashed stroke+ * with no area under it.+ */+ spark: css`+ & path[name='target'] {+ stroke-dasharray: 3 3;+ }++ & path.recharts-area-area[name='target'] {+ fill: none;+ }+ `,stale: css`color: ${cssVar.colorWarning};`,- track: css`- overflow: hidden;- height: 4px;- border-radius: 2px;- background: ${cssVar.colorFillSecondary};- `,}));const MetricCard = memo<{ canEdit: boolean; card: NorthStarCard; goalId: string }>(({ canEdit, card, goalId }) => {const { t } = useTranslation('chat');+ const pushPortalView = useChatStore((s) => s.pushPortalView);+ const openDetail = () =>+ pushPortalView({ goalId, metricKey: card.key, type: PortalViewType.GoalNorthStar });+ const theme = useTheme();const freshness =card.latestAt == null@@ -70,27 +98,38 @@ const MetricCard = memo<{ canEdit: boolean; card: NorthStarCard; goalId: string: t('goalProcess.northStar.lastObserved', { time: dayjs(card.latestAt).fromNow() });return (- <Flexbox className={styles.card} gap={6}>+ <Flexbox+ className={styles.card}+ gap={6}+ role={'button'}+ style={{ cursor: 'pointer' }}+ tabIndex={0}+ onClick={openDetail}+ onKeyDown={(event) => handleCardKeyDown(event, openDetail)}+ ><Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>- <Text ellipsis fontSize={12} type={'secondary'}>- {card.label}- </Text>+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>+ <Text ellipsis fontSize={13} weight={600}>+ {card.label}+ </Text>+ {card.met && <MetBadge />}+ </Flexbox><Flexbox horizontal align={'center'} gap={4}>- {card.met && (- <Tag color={'success'} size={'small'}>- <Icon icon={Check} size={11} /> {t('goalProcess.northStar.met')}- </Tag>- )}{/* Recording stays available after the target is met: the worldcan regress, and a card whose only refresh path disappearedwould stay falsely met forever. */}{canEdit && (<Tooltip title={t('goalProcess.northStar.record.title')}><Button+ aria-label={t('goalProcess.northStar.record.title')}icon={<Icon icon={Plus} size={13} />}size={'small'}type={'text'}- onClick={() => openRecordObservationModal(goalId, card.key, card.label)}+ onClick={(event) => {+ // Recording from the card must not also open the detail.+ event.stopPropagation();+ openRecordObservationModal(goalId, card.key, card.label);+ }}/></Tooltip>)}@@ -106,18 +145,22 @@ const MetricCard = memo<{ canEdit: boolean; card: NorthStarCard; goalId: string{card.unit ? ` ${card.unit}` : ''}</Text></Flexbox>- <Sparkline met={card.met} values={card.trend} />+ {card.trend.length > 1 && (+ <SparkAreaChart+ autoMinValue+ categories={['value', 'target']}+ className={styles.spark}+ // The chart ids its SVG gradient by the color string, so it needs a+ // literal theme color: a `var(--…)` id breaks the `url(#…)` fill.+ colors={[card.met ? theme.colorSuccess : theme.colorInfo, theme.colorTextQuaternary]}+ data={card.trend.map((value, index) => ({ index, target: card.target, value }))}+ height={24}+ index={'index'}+ showGradient={false}+ width={84}+ />+ )}</Flexbox>- <div className={styles.track}>- <div- style={{- background: card.met ? cssVar.colorSuccess : cssVar.colorInfo,- borderRadius: 2,- height: '100%',- width: `${card.percent}%`,- }}- />- </div><Text className={card.stale ? styles.stale : ''} fontSize={11} type={'secondary'}>{freshness}{card.stale ? ` · ${t('goalProcess.northStar.staleWarning')}` : ''}@@ -198,6 +241,7 @@ const NorthStarMetrics = memo<NorthStarMetricsProps>(({ canEdit, goalId }) => {{canEdit && (<Tooltip title={t('goalProcess.northStar.declare.title')}><Button+ aria-label={t('goalProcess.northStar.declare.title')}icon={<Icon icon={Plus} size={14} />}style={{ alignSelf: 'center' }}type={'text'}diff --git a/src/features/AgentGoals/NorthStarMetrics/northStar.test.ts b/src/features/AgentGoals/NorthStarMetrics/northStar.test.tsindex 84add94eeba..31c4ce95f87 100644--- a/src/features/AgentGoals/NorthStarMetrics/northStar.test.ts+++ b/src/features/AgentGoals/NorthStarMetrics/northStar.test.ts@@ -2,7 +2,14 @@ import { describe, expect, it } from 'vitest';import type { MetricSeriesWithPoints } from '@/services/metric';-import { buildNorthStarCards, formatMetricValue, NORTH_STAR_STALE_AFTER_MS } from './northStar';+import {+ buildNorthStarCards,+ buildNorthStarChartRows,+ buildObservationRows,+ deltaTone,+ formatMetricValue,+ NORTH_STAR_STALE_AFTER_MS,+} from './northStar';const NOW = Date.parse('2026-09-06T12:00:00Z');@@ -144,3 +151,70 @@ describe('formatMetricValue', () => {expect(formatMetricValue(null)).toBe('—');});});++describe('buildObservationRows', () => {+ it('lists observations newest first with the change from the one before', () => {+ const { points } = series('followers', [1000, 1040, 1080, 1120]);++ expect(buildObservationRows(points).map(({ delta, value }) => ({ delta, value }))).toEqual([+ { delta: 40, value: 1120 },+ { delta: 40, value: 1080 },+ { delta: 40, value: 1040 },+ { delta: null, value: 1000 },+ ]);+ });++ it('attaches each finished task to the first observation after it', () => {+ const { points } = series('followers', [1000, 1040, 1080]);+ const at = (index: number, offsetMs: number) =>+ new Date(points[index].observedAt.getTime() + offsetMs);+ const tasks = [+ { id: 'n_before', resolvedAt: at(0, -1000), title: 'Before the window' },+ { id: 'n_batch1', resolvedAt: at(1, -10_000), title: 'Batch 1' },+ { id: 'n_batch2', resolvedAt: at(2, 0), title: 'Batch 2' },+ { id: 'n_later', resolvedAt: at(2, 1000), title: 'Not measured yet' },+ ];++ expect(+ buildObservationRows(points, tasks).map((row) => row.tasks.map((task) => task.id)),+ ).toEqual([['n_batch2'], ['n_batch1'], ['n_before']]);+ });++ it('returns nothing for a series never measured', () => {+ expect(buildObservationRows([])).toEqual([]);+ });+});++describe('buildNorthStarChartRows', () => {+ it('pairs every observation with the flat target line', () => {+ const { points } = series('followers', [1000, 1080]);++ expect(buildNorthStarChartRows(points, 1100, (date) => date.toISOString())).toEqual([+ { target: 1100, time: points[0].observedAt.toISOString(), value: 1000 },+ { target: 1100, time: points[1].observedAt.toISOString(), value: 1080 },+ ]);+ });+});++describe('deltaTone', () => {+ it('reads an increase as progress on a count-up clause', () => {+ expect(deltaTone('gte', 1080, 40, 1100)).toBe('good');+ expect(deltaTone('gt', 1040, -40, 1100)).toBe('bad');+ });++ it('reads a decrease as progress on a lower-is-better clause', () => {+ // 未关闭 issue 112 → 目标 0:少了 12 个是进展,多了 5 个是倒退。+ expect(deltaTone('lte', 100, -12, 0)).toBe('good');+ expect(deltaTone('lt', 105, 5, 0)).toBe('bad');+ });++ it('judges an eq clause by whether the value moved toward the target', () => {+ expect(deltaTone('eq', 95, -5, 90)).toBe('good');+ expect(deltaTone('eq', 80, -15, 90)).toBe('bad');+ expect(deltaTone('eq', 85, -10, 90)).toBe('neutral');+ });++ it('stays neutral when nothing changed', () => {+ expect(deltaTone('gte', 1000, 0, 1100)).toBe('neutral');+ });+});diff --git a/src/features/AgentGoals/NorthStarMetrics/northStar.ts b/src/features/AgentGoals/NorthStarMetrics/northStar.tsindex c566bb7df7c..27c820e2aa9 100644--- a/src/features/AgentGoals/NorthStarMetrics/northStar.ts+++ b/src/features/AgentGoals/NorthStarMetrics/northStar.ts@@ -1,10 +1,12 @@import {type GoalMetricComparison,type GoalMetricCriterion,+ type MetricActorType,+ type MetricPointSourceType,toMetricScale,} from '@lobechat/types';-import type { MetricSeriesWithPoints } from '@/services/metric';+import type { MetricSeriesPoint, MetricSeriesWithPoints } from '@/services/metric';/*** View model of one north-star card: a declared acceptance clause joined with@@ -141,3 +143,83 @@ export const formatMetricValue = (value: number | null): string => {if (Number.isInteger(value)) return value.toLocaleString('en-US');return String(value);};++/** A goal task, as the observation history needs it. */+export interface NorthStarTaskRef {+ id: string;+ resolvedAt: Date;+ title: string;+}++/** One observation in the detail panel's history, newest first. */+export interface NorthStarObservationRow {+ actorType?: MetricActorType;+ /** Change from the observation before it; null for the first one in the window. */+ delta: number | null;+ observedAt: Date;+ sourceType?: MetricPointSourceType;+ /**+ * Tasks that finished since the observation before this one — the work this+ * number is the first measurement after.+ */+ tasks: NorthStarTaskRef[];+ value: number;+}++export const buildObservationRows = (+ points: MetricSeriesPoint[],+ tasks: NorthStarTaskRef[] = [],+): NorthStarObservationRow[] =>+ points+ .map((point, index) => {+ const previous = points[index - 1]?.observedAt.getTime() ?? -Infinity;+ const at = point.observedAt.getTime();+ return {+ actorType: point.actorType,+ delta: index === 0 ? null : point.value - points[index - 1].value,+ observedAt: point.observedAt,+ sourceType: point.sourceType,+ tasks: tasks+ .filter((task) => {+ const resolved = task.resolvedAt.getTime();+ return resolved > previous && resolved <= at;+ })+ .sort((a, b) => b.resolvedAt.getTime() - a.resolvedAt.getTime()),+ value: point.value,+ };+ })+ .reverse();++/**+ * Rows for the detail chart: the observed series plus the target as a flat+ * reference line, so the gap reads off the chart instead of the legend.+ */+export const buildNorthStarChartRows = (+ points: { observedAt: Date; value: number }[],+ target: number,+ formatTime: (date: Date) => string,+): { target: number; time: string; value: number }[] =>+ points.map((point) => ({ target, time: formatTime(point.observedAt), value: point.value }));++export type DeltaTone = 'bad' | 'good' | 'neutral';++/**+ * Whether one observation's change is progress, read by the clause's own+ * direction: on a lower-is-better clause (`lte` / `lt`) a drop is progress, and+ * on `eq` progress is closing the distance to the target from the value before.+ */+export const deltaTone = (+ op: GoalMetricComparison,+ value: number,+ delta: number,+ target: number,+): DeltaTone => {+ if (delta === 0) return 'neutral';+ if (op === 'eq') {+ const before = Math.abs(value - delta - target);+ const after = Math.abs(value - target);+ return after === before ? 'neutral' : after < before ? 'good' : 'bad';+ }+ const lowerIsBetter = op === 'lte' || op === 'lt';+ return delta < 0 === lowerIsBetter ? 'good' : 'bad';+};diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.tsindex ed7c94badfc..290507127b2 100644--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts@@ -19,7 +19,6 @@ import {hasReviewableResult,isRunningNode,isTroubledTaskNode,- opensOnResultSurface,scopeGraphView,} from './goalGraphViewModel';@@ -871,57 +870,6 @@ describe('hasReviewableResult', () => {});});-describe('opensOnResultSurface', () => {- it('opens a healthy running task on the result surface to watch the live run', () => {- const view = buildGoalGraphView(- snapshot({- events: [event('w1', 'activated', 110)],- nodes: [node('w1', { status: 'active', taskId: 'task-1', updatedAt: at(115) })],- }),- NOW,- );-- expect(opensOnResultSurface(view.byId.w1)).toBe(true);- });-- it('opens a settled task on the result surface', () => {- const view = buildGoalGraphView(- snapshot({- events: [event('w1', 'activated', 100), event('w1', 'resolved', 110)],- nodes: [- node('w1', {- resolvedAt: at(110),- status: 'resolved',- taskId: 'task-1',- updatedAt: at(110),- }),- ],- }),- NOW,- );-- expect(opensOnResultSurface(view.byId.w1)).toBe(true);- });-- it('keeps undispatched and stale tasks on the original task detail', () => {- const proposed = buildGoalGraphView(- snapshot({ nodes: [node('w1', { status: 'proposed', taskId: 'task-1' })] }),- NOW,- );- const stale = buildGoalGraphView(- snapshot({- events: [event('w1', 'activated', 30)],- nodes: [node('w1', { status: 'active', taskId: 'task-1', updatedAt: at(0) })],- }),- NOW,- );-- expect(opensOnResultSurface(proposed.byId.w1)).toBe(false);- expect(stale.byId.w1.isStale).toBe(true);- expect(opensOnResultSurface(stale.byId.w1)).toBe(false);- });-});-describe('experiment navigation', () => {it('keeps historical branching separate from dependencies and excludes terminal acceptance', () => {const view = buildGoalGraphView(diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.tsindex 03d3659282a..ad7d3a36b5e 100644--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts@@ -186,19 +186,6 @@ export const hasReviewableResult = (view: GoalNodeView): boolean => {return view.node.status === 'resolved' || view.isVerifying;};-/**- * Whether clicking a Task node opens its result surface rather than the- * original Task detail. A delivery to read opens there, and so does a healthy- * run in flight: the result panel shows the live run as it happens, and the- * same panel turns into the report once the run settles — one place to watch- * and then read. Troubled Tasks still open the original Task detail.- */-export const opensOnResultSurface = (view: GoalNodeView): boolean => {- if (view.node.kind !== 'task') return false;- if (isTroubledTaskNode(view)) return false;- return hasReviewableResult(view) || isRunningNode(view);-};-/*** Whether a node reads as "running" on the map — the animated ring, the chip* and the elapsed clock all hang off this.diff --git a/src/features/AgentGoals/ProcessControl/useGoalProcessActions.test.ts b/src/features/AgentGoals/ProcessControl/useGoalProcessActions.test.tsnew file mode 100644index 00000000000..4aaf6546578--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/useGoalProcessActions.test.ts@@ -0,0 +1,85 @@+import type { GoalGraphNode, GoalGraphSnapshot } from '@lobechat/types';+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { buildGoalGraphView } from './goalGraphViewModel';+import { useGoalNodeSelect } from './useGoalProcessActions';++const portal = vi.hoisted(() => ({+ openGoalNode: vi.fn(),+ openTaskDetail: vi.fn(),+ openTaskResult: vi.fn(),+}));++vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (s: typeof portal) => unknown) => selector(portal),+}));++const T0 = new Date('2026-10-18T00:00:00Z');++const node = (id: string, overrides: Partial<GoalGraphNode> = {}): GoalGraphNode => ({+ confidence: null,+ createdAt: T0,+ createdByAgentId: null,+ createdByUserId: null,+ description: null,+ goalId: 'goal-1',+ id,+ kind: 'task',+ priority: 0,+ resolvedAt: null,+ status: 'proposed',+ taskId: null,+ title: id,+ updatedAt: T0,+ ...overrides,+});++const graphOf = (nodes: GoalGraphNode[]) =>+ buildGoalGraphView({+ decisions: [],+ edges: [],+ events: [],+ goal: { config: {}, id: 'goal-1', status: 'running', title: 'Goal' },+ nodes,+ workVersions: [],+ } as unknown as GoalGraphSnapshot);++describe('useGoalNodeSelect', () => {+ beforeEach(() => {+ portal.openGoalNode.mockClear();+ portal.openTaskDetail.mockClear();+ portal.openTaskResult.mockClear();+ });++ // Regression: a settled or running Task opened its result surface, but a+ // Task link is read as "show me the Task" — the original Task detail.+ it('opens the original Task detail for a settled or running Task', () => {+ const graph = graphOf([+ node('done', { resolvedAt: T0, status: 'resolved', taskId: 'task-done' }),+ node('running', { status: 'active', taskId: 'task-running', updatedAt: new Date() }),+ ]);+ const { result } = renderHook(() => useGoalNodeSelect('goal-1', graph));++ result.current('done');+ result.current('running');++ expect(portal.openTaskDetail.mock.calls).toEqual([['task-done'], ['task-running']]);+ expect(portal.openTaskResult).not.toHaveBeenCalled();+ expect(portal.openGoalNode).not.toHaveBeenCalled();+ });++ it('opens the drill-down for a node with no Task behind it', () => {+ const graph = graphOf([node('finding', { kind: 'finding' }), node('draft')]);+ const { result } = renderHook(() => useGoalNodeSelect('goal-1', graph));++ result.current('finding');+ result.current('draft');++ expect(portal.openGoalNode.mock.calls).toEqual([+ ['goal-1', 'finding'],+ ['goal-1', 'draft'],+ ]);+ expect(portal.openTaskDetail).not.toHaveBeenCalled();+ });+});diff --git a/src/features/AgentGoals/ProcessControl/useGoalProcessActions.ts b/src/features/AgentGoals/ProcessControl/useGoalProcessActions.tsindex 49aee77b568..98430c6e33c 100644--- a/src/features/AgentGoals/ProcessControl/useGoalProcessActions.ts+++ b/src/features/AgentGoals/ProcessControl/useGoalProcessActions.ts@@ -1,4 +1,3 @@-import { experimentOwner } from '@lobechat/utils/goalGraph';import { useCallback, useMemo } from 'react';import { goalService } from '@/services/goal';@@ -7,18 +6,17 @@ import { useGoalStore } from '@/store/goal';import { isExperiment } from '../Experiments/model';import type { FrontierActions } from './Frontier';-import { type GoalGraphView, opensOnResultSurface } from './goalGraphViewModel';+import { type GoalGraphView } from './goalGraphViewModel';/*** Where a click on a goal graph node lands, shared by every host of the- * process-control sections (goal page, conversation portal). A Task with a- * delivery to read, or a healthy run in flight, lands on its result surface —- * the live run while it works, the report once it settles. A Task waiting or in- * trouble opens the original Task detail, where configuration and failure- * context live. Everything else opens the node drill-down.+ * process-control sections (goal page, conversation portal) and every link to+ * a node. A node with a Task behind it shows the original Task detail —+ * configuration, runs and deliveries all live there — so a Task link never+ * lands on a node drill-down or a partial view of the Task. Everything else+ * opens the node drill-down.*/export const useGoalNodeSelect = (goalId: string, graph?: GoalGraphView) => {- const openTaskResult = useChatStore((s) => s.openTaskResult);const openTaskDetail = useChatStore((s) => s.openTaskDetail);const openGoalNode = useChatStore((s) => s.openGoalNode);@@ -30,15 +28,9 @@ export const useGoalNodeSelect = (goalId: string, graph?: GoalGraphView) => {openGoalNode(goalId, nodeId);return;}- if (- graph &&- experimentOwner({ nodes: graph.nodes.map((item) => item.node), edges: graph.edges }, nodeId)- )- openTaskDetail(taskId);- else if (view && opensOnResultSurface(view)) openTaskResult(taskId);- else openTaskDetail(taskId);+ openTaskDetail(taskId);},- [goalId, graph, openGoalNode, openTaskDetail, openTaskResult],+ [goalId, graph, openGoalNode, openTaskDetail],);};diff --git a/src/features/Portal/GoalNode/Body.tsx b/src/features/Portal/GoalNode/Body.tsxindex a0597b60ddc..28a945b9119 100644--- a/src/features/Portal/GoalNode/Body.tsx+++ b/src/features/Portal/GoalNode/Body.tsx@@ -31,7 +31,10 @@ import {findBatchPlan,} from '@/features/AgentGoals/ProcessControl/Graph/batchModel';import { KindDot } from '@/features/AgentGoals/ProcessControl/shared';-import { useFrontierActions } from '@/features/AgentGoals/ProcessControl/useGoalProcessActions';+import {+ useFrontierActions,+ useGoalNodeSelect,+} from '@/features/AgentGoals/ProcessControl/useGoalProcessActions';import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';import { goalSelectors, useGoalStore } from '@/store/goal';@@ -151,7 +154,6 @@ const Body = memo(() => {const { t } = useTranslation('chat');const view = useChatStore(chatPortalSelectors.goalNodeView);const openTaskDetail = useChatStore((s) => s.openTaskDetail);- const openGoalNode = useChatStore((s) => s.openGoalNode);const { decide } = useFrontierActions(view?.goalId ?? '');// Fetched here, not assumed from the goal page: the drill-down also opens// from the conversation portal, where nothing else holds the snapshot.@@ -160,6 +162,9 @@ const Body = memo(() => {const snapshot = useGoalStore(goalSelectors.goalGraph(view?.goalId ?? ''));const graph = useMemo(() => (snapshot ? buildGoalGraphView(snapshot) : undefined), [snapshot]);+ // Linked nodes land where a click on the map would: a Task shows the Task+ // itself, anything else its drill-down.+ const openNode = useGoalNodeSelect(view?.goalId ?? '', graph);if (!view || !graph || !snapshot) return null;const nodeView = graph.byId[view.nodeId];@@ -208,7 +213,7 @@ const Body = memo(() => {graph={graph}model={batchGate.model}round={batchGate.round}- onOpenNode={(nodeId) => openGoalNode(view.goalId, nodeId)}+ onOpenNode={(nodeId) => openNode(nodeId)}/>)}@@ -257,7 +262,7 @@ const Body = memo(() => {key={finding.id}text={finding.title}view={findingView}- onClick={() => openGoalNode(view.goalId, finding.id)}+ onClick={() => openNode(finding.id)}/>);})}@@ -270,7 +275,7 @@ const Body = memo(() => {<NodeLinkRowtext={nodeView.producedBy.title}view={graph.byId[nodeView.producedBy.id]}- onClick={() => openGoalNode(view.goalId, nodeView.producedBy!.id)}+ onClick={() => openNode(nodeView.producedBy!.id)}/></Section>)}@@ -286,7 +291,7 @@ const Body = memo(() => {key={blocker.id}text={blocker.title}view={blockerView}- onClick={() => openGoalNode(view.goalId, blocker.id)}+ onClick={() => openNode(blocker.id)}/>);})}diff --git a/src/features/Portal/GoalNorthStar/Body.tsx b/src/features/Portal/GoalNorthStar/Body.tsxnew file mode 100644index 00000000000..d03dddf5807--- /dev/null+++ b/src/features/Portal/GoalNorthStar/Body.tsx@@ -0,0 +1,310 @@+'use client';++import { LineChart } from '@lobehub/charts';+import {+ Button,+ createStaticStyles,+ cssVar,+ Flexbox,+ Icon,+ Skeleton,+ Text,+ useTheme,+} from '@lobehub/ui';+import dayjs from 'dayjs';+import { ListChecks } from 'lucide-react';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import MetBadge from '@/features/AgentGoals/NorthStarMetrics/MetBadge';+import {+ buildNorthStarChartRows,+ buildObservationRows,+ type DeltaTone,+ deltaTone,+ formatMetricValue,+ type NorthStarObservationRow,+} from '@/features/AgentGoals/NorthStarMetrics/northStar';+import { useGoalNodeSelect } from '@/features/AgentGoals/ProcessControl/useGoalProcessActions';+import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';++import { useNorthStarCard } from './useNorthStarCard';++/**+ * Detail of one north-star clause: where the number stands against its+ * target, how it got there, and the actions that move it — recording a new+ * observation or adjusting the clause itself.+ */++const styles = createStaticStyles(({ css }) => ({+ mono: css`+ font-family: ${cssVar.fontFamilyCode};+ font-variant-numeric: tabular-nums;+ `,+ /* The chart names each series path after its category; dash the target line. */+ chart: css`+ & path[name='target'] {+ stroke-dasharray: 4 4;+ }+ `,+ row: css`+ padding-block: 8px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ &:last-child {+ border-block-end: none;+ }+ `,+ task: css`+ overflow: hidden;+ min-width: 0;+ max-width: 100%;+ `,+ taskCell: css`+ overflow: hidden;+ min-width: 0;+ `,+ taskTitle: css`+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ time: css`+ flex: none;+ width: 72px;+ `,+ value: css`+ flex: none;+ min-width: 96px;+ `,+ section: css`+ font-size: 12px;+ font-weight: 600;+ color: ${cssVar.colorTextSecondary};+ `,+}));++const DAY_MS = 24 * 60 * 60 * 1000;++/** Axis labels at the granularity the series actually spans. */+const timeFormat = (points: { observedAt: Date }[]) => {+ const span =+ points.length > 1 ? points.at(-1)!.observedAt.getTime() - points[0].observedAt.getTime() : 0;+ return span >= DAY_MS ? 'MM-DD HH:mm' : 'HH:mm:ss';+};++const formatDelta = (delta: number) =>+ `${delta > 0 ? '+' : delta < 0 ? '−' : '±'}${formatMetricValue(Math.abs(delta))}`;++/** At most this many task links per observation; the rest are counted. */+const TASKS_PER_ROW = 1;++/** Who put the number there, for an observation no finished task explains. */+const observationSource = (row: NorthStarObservationRow): 'agent' | 'api' | 'manual' | 'probe' =>+ row.actorType === 'agent' ? 'agent' : (row.sourceType ?? 'manual');++const DELTA_COLOR: Record<DeltaTone, string> = {+ bad: cssVar.colorError,+ good: cssVar.colorSuccess,+ neutral: cssVar.colorTextTertiary,+};++const NorthStarDetail = memo<{ goalId: string; metricKey: string }>(({ goalId, metricKey }) => {+ const { t } = useTranslation('chat');+ const theme = useTheme();+ const { card, criterion, error, graph, isLoading, loaded, points, retry, tasks } =+ useNorthStarCard(goalId, metricKey);++ const chartRows = useMemo(+ () =>+ card+ ? buildNorthStarChartRows(points, card.target, (date) =>+ dayjs(date).format(timeFormat(points)),+ )+ : [],+ [card, points],+ );+ // A task link shows the Task itself, as a click on the map would.+ const openNode = useGoalNodeSelect(goalId, graph);+ const history = useMemo(() => buildObservationRows(points, tasks), [points, tasks]);++ if (!loaded || isLoading)+ return (+ <Flexbox gap={16} padding={16}>+ <Skeleton height={96} />+ <Skeleton height={200} />+ </Flexbox>+ );++ if (!criterion || !card)+ return (+ <Flexbox padding={16}>+ <Text type={'secondary'}>{t('goalProcess.northStar.detail.removed')}</Text>+ </Flexbox>+ );++ if (error && points.length === 0)+ return (+ <Flexbox padding={16}>+ <AsyncError error={error} variant={'metric'} onRetry={retry} />+ </Flexbox>+ );++ const accent = card.met ? cssVar.colorSuccess : cssVar.colorInfo;+ const unit = card.unit ? ` ${card.unit}` : '';+ // Literal theme colors: the chart ids its SVG gradients by the color string.+ const chartColors = [card.met ? theme.colorSuccess : theme.colorInfo, theme.colorTextQuaternary];++ return (+ <Flexbox gap={24} padding={16}>+ <Flexbox gap={10}>+ <Flexbox horizontal align={'center'} justify={'space-between'}>+ <Flexbox horizontal align={'baseline'} gap={8}>+ <Text fontSize={28} style={{ color: card.met ? accent : undefined }} weight={700}>+ {formatMetricValue(card.current)}+ </Text>+ <Text type={'secondary'}>+ {t(`goalProcess.northStar.op.${card.op}` as const)} {formatMetricValue(card.target)}+ {unit}+ </Text>+ {card.met && <MetBadge />}+ </Flexbox>+ </Flexbox>+ <Text+ fontSize={12}+ style={card.stale ? { color: cssVar.colorWarning } : undefined}+ type={'secondary'}+ >+ {card.latestAt == null+ ? t('goalProcess.northStar.unmeasured')+ : t('goalProcess.northStar.lastObserved', { time: dayjs(card.latestAt).fromNow() })}+ {card.stale ? ` · ${t('goalProcess.northStar.staleWarning')}` : ''}+ </Text>+ </Flexbox>++ <Flexbox gap={8}>+ <Text className={styles.section}>{t('goalProcess.northStar.detail.trend')}</Text>+ {chartRows.length < 2 ? (+ <Text fontSize={12} type={'secondary'}>+ {t('goalProcess.northStar.detail.trendEmpty')}+ </Text>+ ) : (+ <LineChart+ autoMinValue+ categories={['value', 'target']}+ className={styles.chart}+ colors={chartColors}+ data={chartRows}+ height={200}+ index={'time'}+ startEndOnly={chartRows.length > 8}+ valueFormatter={formatMetricValue}+ yAxisWidth={56}+ customCategories={{+ target: t('goalProcess.northStar.detail.target'),+ value: card.label,+ }}+ />+ )}+ </Flexbox>++ <Flexbox gap={4}>+ <Text className={styles.section}>+ {t('goalProcess.northStar.detail.history', { count: history.length })}+ </Text>+ {history.length === 0 ? (+ <Text fontSize={12} type={'secondary'}>+ {t('goalProcess.northStar.unmeasured')}+ </Text>+ ) : (+ <Flexbox>+ {history.map((row) => (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.row}+ gap={12}+ key={row.observedAt.getTime()}+ >+ <Text+ className={styles.time}+ fontSize={12}+ title={dayjs(row.observedAt).format('YYYY-MM-DD HH:mm:ss')}+ type={'secondary'}+ >+ {dayjs(row.observedAt).fromNow()}+ </Text>+ <Flexbox horizontal align={'baseline'} className={styles.value} gap={6}>+ <Text className={styles.mono} weight={500}>+ {formatMetricValue(row.value)}+ </Text>+ {row.delta != null && (+ <Text+ className={styles.mono}+ fontSize={12}+ style={{+ color: DELTA_COLOR[deltaTone(card.op, row.value, row.delta, card.target)],+ }}+ >+ {formatDelta(row.delta)}+ </Text>+ )}+ </Flexbox>+ <Flexbox+ horizontal+ align={'center'}+ className={styles.taskCell}+ flex={1}+ gap={6}+ justify={'flex-end'}+ >+ {row.tasks.length > 0 ? (+ <>+ {row.tasks.slice(0, TASKS_PER_ROW).map((task) => (+ <Button+ className={styles.task}+ icon={<Icon icon={ListChecks} size={12} />}+ key={task.id}+ size={'small'}+ title={task.title}+ type={'text'}+ onClick={() => openNode(task.id)}+ >+ <span className={styles.taskTitle}>{task.title}</span>+ </Button>+ ))}+ {row.tasks.length > TASKS_PER_ROW && (+ <Text fontSize={12} type={'secondary'}>+ +{row.tasks.length - TASKS_PER_ROW}+ </Text>+ )}+ </>+ ) : (+ <Text fontSize={12} type={'secondary'}>+ {t(`goalProcess.northStar.detail.source.${observationSource(row)}` as const)}+ </Text>+ )}+ </Flexbox>+ </Flexbox>+ ))}+ </Flexbox>+ )}+ </Flexbox>+ </Flexbox>+ );+});++NorthStarDetail.displayName = 'GoalNorthStarDetail';++const Body = memo(() => {+ const view = useChatStore(chatPortalSelectors.goalNorthStarView);+ if (!view) return null;++ return <NorthStarDetail goalId={view.goalId} key={view.metricKey} metricKey={view.metricKey} />;+});++Body.displayName = 'GoalNorthStarBody';++export default Body;diff --git a/src/features/Portal/GoalNorthStar/Title.tsx b/src/features/Portal/GoalNorthStar/Title.tsxnew file mode 100644index 00000000000..751e4ae9a79--- /dev/null+++ b/src/features/Portal/GoalNorthStar/Title.tsx@@ -0,0 +1,28 @@+import { Text } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';+import { goalSelectors, useGoalStore } from '@/store/goal';++const Title = memo(() => {+ const { t } = useTranslation('chat');+ const view = useChatStore(chatPortalSelectors.goalNorthStarView);+ const criterion = useGoalStore((s) =>+ view+ ? goalSelectors+ .goalGraph(view.goalId)(s)+ ?.goal.config?.acceptance?.metrics?.find((item) => item.key === view.metricKey)+ : undefined,+ );+ if (!view) return null;++ return (+ <Text style={{ fontSize: 14 }} weight={500}>+ {criterion?.title || view.metricKey || t('goalProcess.northStar.detail.title')}+ </Text>+ );+});++export default Title;diff --git a/src/features/Portal/GoalNorthStar/index.ts b/src/features/Portal/GoalNorthStar/index.tsnew file mode 100644index 00000000000..0d1303db800--- /dev/null+++ b/src/features/Portal/GoalNorthStar/index.ts@@ -0,0 +1,6 @@+import { type PortalImpl } from '../type';+import Body from './Body';+import Title from './Title';+import { useGoalNorthStarMoreMenu } from './useMoreMenu';++export const GoalNorthStar: PortalImpl = { Body, Title, useMoreMenu: useGoalNorthStarMoreMenu };diff --git a/src/features/Portal/GoalNorthStar/useMoreMenu.tsx b/src/features/Portal/GoalNorthStar/useMoreMenu.tsxnew file mode 100644index 00000000000..258586fe70f--- /dev/null+++ b/src/features/Portal/GoalNorthStar/useMoreMenu.tsx@@ -0,0 +1,57 @@+import { Icon } from '@lobehub/ui';+import { Pencil, Plus } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { openDeclareMetricModal } from '@/features/AgentGoals/NorthStarMetrics/DeclareMetricModal';+import { openRecordObservationModal } from '@/features/AgentGoals/NorthStarMetrics/RecordObservationModal';+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';+import { usePermission } from '@/hooks/usePermission';+import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';+import { goalSelectors, useGoalStore } from '@/store/goal';++export const useGoalNorthStarMoreMenu = (): PortalMoreMenuConfig | undefined => {+ const { t } = useTranslation('chat');+ const view = useChatStore(chatPortalSelectors.goalNorthStarView);+ const { allowed: canEdit } = usePermission('create_content');+ const [refreshGoalGraph, refreshGoalMetricSeries] = useGoalStore((s) => [+ s.refreshGoalGraph,+ s.refreshGoalMetricSeries,+ ]);+ const criterion = useGoalStore((s) =>+ view+ ? goalSelectors+ .goalGraph(view.goalId)(s)+ ?.goal.config?.acceptance?.metrics?.find((item) => item.key === view.metricKey)+ : undefined,+ );++ if (!view) return;+ const { goalId } = view;++ return {+ // The clause's actions sit beside its title, out of the reading flow of+ // the number, the trend and the history.+ extraItems:+ canEdit && criterion+ ? [+ {+ icon: <Icon icon={Plus} />,+ key: 'record',+ label: t('goalProcess.northStar.record.title'),+ onClick: () =>+ openRecordObservationModal(goalId, criterion.key, criterion.title || criterion.key),+ },+ {+ icon: <Icon icon={Pencil} />,+ key: 'edit',+ label: t('goalProcess.northStar.edit.title'),+ onClick: () => openDeclareMetricModal(goalId, criterion),+ },+ ]+ : undefined,+ // A clause lives in its goal's config and its numbers in the goal's metric+ // series, so refreshing re-reads both.+ refresh: () => Promise.all([refreshGoalGraph(goalId), refreshGoalMetricSeries(goalId)]),+ };+};diff --git a/src/features/Portal/GoalNorthStar/useNorthStarCard.ts b/src/features/Portal/GoalNorthStar/useNorthStarCard.tsnew file mode 100644index 00000000000..873dcd82191--- /dev/null+++ b/src/features/Portal/GoalNorthStar/useNorthStarCard.ts@@ -0,0 +1,58 @@+import { useMemo } from 'react';++import {+ buildNorthStarCards,+ type NorthStarCard,+ type NorthStarTaskRef,+} from '@/features/AgentGoals/NorthStarMetrics/northStar';+import { buildGoalGraphView } from '@/features/AgentGoals/ProcessControl/goalGraphViewModel';+import { goalSelectors, useGoalStore } from '@/store/goal';++/**+ * One declared clause of a goal joined with its measured series — the same+ * derivation the goal page's card renders, so the panel and the card it was+ * opened from can never disagree about the number.+ */+export const useNorthStarCard = (goalId: string, metricKey: string) => {+ const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));+ const useFetchGoalMetricSeries = useGoalStore((s) => s.useFetchGoalMetricSeries);+ const series = useGoalStore(goalSelectors.goalMetricSeries(goalId));++ const criterion = snapshot?.goal.config?.acceptance?.metrics?.find(+ (item) => item.key === metricKey,+ );+ const { error, isLoading, mutate } = useFetchGoalMetricSeries(criterion ? goalId : undefined);+ const matched = series?.find((item) => item.key === metricKey);++ const card = useMemo<NorthStarCard | undefined>(+ () => (criterion ? buildNorthStarCards([criterion], series ?? [])[0] : undefined),+ [criterion, series],+ );++ // Finished task nodes, so each observation can name the work it measures.+ const nodes = snapshot?.nodes;+ const tasks = useMemo<NorthStarTaskRef[]>(+ () =>+ (nodes ?? []).flatMap((node) =>+ node.kind === 'task' && node.status === 'resolved' && node.resolvedAt+ ? [{ id: node.id, resolvedAt: new Date(node.resolvedAt), title: node.title }]+ : [],+ ),+ [nodes],+ );++ // The graph view routes a task link the way the map does (see `useGoalNodeSelect`).+ const graph = useMemo(() => (snapshot ? buildGoalGraphView(snapshot) : undefined), [snapshot]);++ return {+ card,+ criterion,+ error,+ graph,+ isLoading: !series && isLoading,+ loaded: !!snapshot,+ points: matched?.points ?? [],+ retry: () => void mutate(),+ tasks,+ };+};diff --git a/src/features/Portal/portalWidth.test.ts b/src/features/Portal/portalWidth.test.tsindex 1fd8fd3a05b..b5bd1692ad4 100644--- a/src/features/Portal/portalWidth.test.ts+++ b/src/features/Portal/portalWidth.test.ts@@ -27,6 +27,7 @@ describe('getPortalViewMinWidth', () => {PortalViewType.Goal,PortalViewType.GoalMetric,PortalViewType.GoalNode,+ PortalViewType.GoalNorthStar,PortalViewType.TaskDetail,PortalViewType.TaskResult,PortalViewType.Thread,diff --git a/src/features/Portal/portalWidth.ts b/src/features/Portal/portalWidth.tsindex b200b386816..1062d47b7c5 100644--- a/src/features/Portal/portalWidth.ts+++ b/src/features/Portal/portalWidth.ts@@ -37,6 +37,7 @@ const VIEW_MIN_WIDTH: PortalWidths = {[PortalViewType.Goal]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.GoalMetric]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.GoalNode]: CHAT_PORTAL_TOOL_UI_WIDTH,+ [PortalViewType.GoalNorthStar]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.GoalReport]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.GoalReportChapter]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.TaskDetail]: CHAT_PORTAL_TOOL_UI_WIDTH,diff --git a/src/features/Portal/router.tsx b/src/features/Portal/router.tsxindex c3deae1a76d..da522ecdc59 100644--- a/src/features/Portal/router.tsx+++ b/src/features/Portal/router.tsx@@ -18,6 +18,7 @@ import { FilePreview } from './FilePreview';import { Goal } from './Goal';import { GoalMetric } from './GoalMetric';import { GoalNode } from './GoalNode';+import { GoalNorthStar } from './GoalNorthStar';import { GoalReport, GoalReportChapter } from './GoalReport';import { GroupThread } from './GroupThread';import { HomeBody, HomeTitle } from './Home';@@ -52,6 +53,7 @@ const VIEW_COMPONENTS: Record<PortalViewType, PortalImpl> = {[PortalViewType.Goal]: Goal,[PortalViewType.GoalMetric]: GoalMetric,[PortalViewType.GoalNode]: GoalNode,+ [PortalViewType.GoalNorthStar]: GoalNorthStar,[PortalViewType.GoalReport]: GoalReport,[PortalViewType.GoalReportChapter]: GoalReportChapter,[PortalViewType.LocalFile]: LocalFile,diff --git a/src/services/metric.ts b/src/services/metric.tsindex 1b78c1c36c6..a426bb39d83 100644--- a/src/services/metric.ts+++ b/src/services/metric.ts@@ -1,7 +1,20 @@-import type { MetricKind, MetricSubjectType } from '@lobechat/types';+import type {+ MetricActorType,+ MetricKind,+ MetricPointSourceType,+ MetricSubjectType,+} from '@lobechat/types';import { lambdaClient } from '@/libs/trpc/client';+/** One observation; who recorded it and how is optional for persisted older reads. */+export interface MetricSeriesPoint {+ actorType?: MetricActorType;+ observedAt: Date;+ sourceType?: MetricPointSourceType;+ value: number;+}+/*** One chartable series of a subject — the shape the north-star strip consumes.* `firstPoint` is the series' true first observation, carried separately@@ -14,7 +27,7 @@ export interface MetricSeriesWithPoints {id: string;key: string;kind: MetricKind;- points: { observedAt: Date; value: number }[];+ points: MetricSeriesPoint[];title?: string | null;unit?: string | null;}@@ -51,7 +64,9 @@ class MetricService {key: item.key,kind: item.kind,points: item.points.map((point) => ({+ actorType: point.actorType,observedAt: new Date(point.observedAt),+ sourceType: point.sourceType,value: Number(point.value),})),title: item.title,diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.tsindex b1036d5d57b..8a4c87a4f0d 100644--- a/src/store/chat/slices/portal/initialState.ts+++ b/src/store/chat/slices/portal/initialState.ts@@ -20,6 +20,7 @@ export enum PortalViewType {Goal = 'goal',GoalMetric = 'goalMetric',GoalNode = 'goalNode',+ GoalNorthStar = 'goalNorthStar',GoalReport = 'goalReport',GoalReportChapter = 'goalReportChapter',GroupThread = 'groupThread',@@ -93,6 +94,8 @@ export type PortalViewData =| { goalId: string; type: PortalViewType.Goal }| { goalId: string; metric: GoalMetricKind; type: PortalViewType.GoalMetric }| { goalId: string; nodeId: string; type: PortalViewType.GoalNode }+ /** One declared north-star clause of a goal, keyed by its metric series key. */+ | { goalId: string; metricKey: string; type: PortalViewType.GoalNorthStar }| { goalId: string; type: PortalViewType.GoalReport }| { chapterIndex: number; goalId: string; type: PortalViewType.GoalReportChapter }| { acceptanceId: string; type: PortalViewType.Acceptance }diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.tsindex 4d153940bb7..e32d3bc1671 100644--- a/src/store/chat/slices/portal/selectors.ts+++ b/src/store/chat/slices/portal/selectors.ts@@ -276,6 +276,7 @@ const goalPortalId = (s: ChatStoreState): string | undefined =>getViewData(s, PortalViewType.Goal)?.goalId;const goalNodeView = (s: ChatStoreState) => getViewData(s, PortalViewType.GoalNode);const goalMetricView = (s: ChatStoreState) => getViewData(s, PortalViewType.GoalMetric);+const goalNorthStarView = (s: ChatStoreState) => getViewData(s, PortalViewType.GoalNorthStar);const goalReportView = (s: ChatStoreState) => getViewData(s, PortalViewType.GoalReport);const goalReportChapterView = (s: ChatStoreState) =>getViewData(s, PortalViewType.GoalReportChapter);@@ -363,6 +364,7 @@ export const chatPortalSelectors = {// Goal drill-down datagoalMetricView,+ goalNorthStarView,dashboardWidgetView,goalNodeView,goalPortalId,