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 decision option tree (#21560)

Arvin Xu11d0c0a5d2dc
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 084c47ec52b..154a667e3d5 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -830,8 +830,15 @@
"goalProcess.decision.summary.thisTask": "this task",
"goalProcess.decision.system": "Run environment",
"goalProcess.decision.viewRun": "Open task",
+ "goalProcess.decisions.chosen": "Chosen",
+ "goalProcess.decisions.effect.fail": "Fails the goal",
+ "goalProcess.decisions.effect.retire": "Retires the task",
+ "goalProcess.decisions.effect.retry": "Runs the task again",
"goalProcess.decisions.empty": "No decision has been asked on this goal yet.",
+ "goalProcess.decisions.openNode": "Open this decision",
"goalProcess.decisions.pending": "Awaiting decision",
+ "goalProcess.decisions.raisedBy": "Raised by",
+ "goalProcess.decisions.recommended": "Recommended",
"goalProcess.decisions.title": "Decisions",
"goalProcess.deliverables.empty": "Nothing delivered yet. Documents, generated files and linked resources a task persists show up here — anything left only on a local path does not.",
"goalProcess.deliverables.from": "From “{{title}}”",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index adf88fc796b..7fd25fc2924 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -830,8 +830,15 @@
"goalProcess.decision.summary.thisTask": "这项任务",
"goalProcess.decision.system": "运行环境",
"goalProcess.decision.viewRun": "查看任务",
+ "goalProcess.decisions.chosen": "已选",
+ "goalProcess.decisions.effect.fail": "目标失败",
+ "goalProcess.decisions.effect.retire": "退役这项任务",
+ "goalProcess.decisions.effect.retry": "再跑一遍这项任务",
"goalProcess.decisions.empty": "这个目标还没有需要决策的事项。",
+ "goalProcess.decisions.openNode": "查看这条决策",
"goalProcess.decisions.pending": "待决策",
+ "goalProcess.decisions.raisedBy": "由此触发",
+ "goalProcess.decisions.recommended": "推荐",
"goalProcess.decisions.title": "决策",
"goalProcess.deliverables.empty": "还没有交付物。任务写入产品的文档、生成的文件和关联资源会出现在这里——只留在本地路径上的产物不会。",
"goalProcess.deliverables.from": "来自「{{title}}」",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index a1761724890..4a84315cb59 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2905,6 +2905,13 @@ export default {
'goalProcess.decisions.title': 'Decisions',
'goalProcess.decisions.empty': 'No decision has been asked on this goal yet.',
'goalProcess.decisions.pending': 'Awaiting decision',
+ 'goalProcess.decisions.chosen': 'Chosen',
+ 'goalProcess.decisions.openNode': 'Open this decision',
+ 'goalProcess.decisions.recommended': 'Recommended',
+ 'goalProcess.decisions.raisedBy': 'Raised by',
+ 'goalProcess.decisions.effect.fail': 'Fails the goal',
+ 'goalProcess.decisions.effect.retire': 'Retires the task',
+ 'goalProcess.decisions.effect.retry': 'Runs the task again',
'goalProcess.findings.title': 'Findings',
'goalProcess.findings.empty': 'No findings yet.',
'goalProcess.findings.answers': 'Answers “{{title}}”',
diff --git a/src/features/AgentGoals/ProcessControl/DecisionGraph.test.tsx b/src/features/AgentGoals/ProcessControl/DecisionGraph.test.tsx
new file mode 100644
index 00000000000..c0f07df3e95
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/DecisionGraph.test.tsx
@@ -0,0 +1,88 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen, within } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import DecisionGraph from './DecisionGraph';
+import type { DecisionGraphModel } from './decisionGraphModel';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const options: DecisionGraphModel['options'] = [
+ { id: 'retry', label: 'Retry work', recommended: true, state: 'dim' },
+ {
+ description: 'Gives the task up',
+ effect: 'retire',
+ id: 'retire',
+ label: 'Retire work',
+ recommended: false,
+ state: 'chosen',
+ },
+];
+
+const effectLabel = { fail: 'F', retire: 'Retires the task', retry: 'R' };
+
+describe('DecisionGraph', () => {
+ it('draws the picked option, its effect and the note on the result card', () => {
+ render(
+ <DecisionGraph
+ result={{ effectLabel, header: <span>Dana</span> }}
+ root={{ question: 'Retry or retire?' }}
+ model={{
+ options,
+ result: { actor: 'user', effect: 'retire', from: 'option', note: 'not worth it' },
+ }}
+ />,
+ );
+
+ expect(screen.getByText('Retry or retire?')).toBeTruthy();
+ expect(screen.getByText('goalProcess.decisions.chosen')).toBeTruthy();
+ expect(screen.getByText('goalProcess.decisions.recommended')).toBeTruthy();
+ expect(screen.getByText('Gives the task up')).toBeTruthy();
+ expect(screen.getByText('Dana')).toBeTruthy();
+ expect(screen.getByText('Retires the task')).toBeTruthy();
+ expect(screen.getByText('not worth it')).toBeTruthy();
+ });
+
+ it('names what raised the question and opens it', () => {
+ const onOpen = vi.fn();
+ render(
+ <DecisionGraph
+ model={{ options }}
+ root={{
+ context: { onOpen, title: 'Draft the rollout plan' },
+ detail: 'Three attempts failed',
+ question: 'q',
+ }}
+ />,
+ );
+
+ fireEvent.click(screen.getByText('Draft the rollout plan'));
+
+ expect(onOpen).toHaveBeenCalledTimes(1);
+ expect(screen.getByText('goalProcess.decisions.raisedBy')).toBeTruthy();
+ expect(screen.getByText('Three attempts failed')).toBeTruthy();
+ // With context to show, the root card does not repeat the question.
+ expect(screen.queryByText('q')).toBeNull();
+ });
+
+ it('shows no result card while the question is open', () => {
+ render(
+ <DecisionGraph
+ model={{ options: options.map((option) => ({ ...option, state: 'open' as const })) }}
+ result={{ effectLabel, header: <span>Dana</span> }}
+ root={{ question: 'q' }}
+ />,
+ );
+
+ expect(screen.queryByText('Dana')).toBeNull();
+ expect(
+ within(screen.getByText('Retry work').closest('div')!.parentElement!).queryByText(
+ 'goalProcess.decisions.chosen',
+ ),
+ ).toBeNull();
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/DecisionGraph.tsx b/src/features/AgentGoals/ProcessControl/DecisionGraph.tsx
new file mode 100644
index 00000000000..557e380fa5d
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/DecisionGraph.tsx
@@ -0,0 +1,401 @@
+'use client';
+
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar as vars } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import {
+ Archive,
+ Check,
+ CircleX,
+ GitBranch,
+ type LucideIcon,
+ RotateCcw,
+ Sparkles,
+} from 'lucide-react';
+import { memo, type ReactNode, useCallback, useLayoutEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ connectorPath,
+ type DecisionEffect,
+ type DecisionGraphModel,
+ type Point,
+} from './decisionGraphModel';
+
+/**
+ * One decision drawn as a graph, left to right: what raised it → the options it
+ * offered → where the answer went. The picked path is drawn solid in the accent
+ * colour and everything passed over recedes, so a settled call reads as a route
+ * through the options rather than a list of them.
+ *
+ * Lines are drawn from where the cards actually sit (cards wrap with their
+ * text), so the container is measured and redrawn when it resizes.
+ */
+
+const styles = stylex.create({
+ card: {
+ backgroundColor: vars.colorBgContainer,
+ borderColor: vars.colorBorderSecondary,
+ borderRadius: vars.borderRadius,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ paddingBlock: 10,
+ paddingInline: 12,
+ position: 'relative',
+ zIndex: 1,
+ },
+ cardChosen: {
+ backgroundColor: vars.colorSuccessBg,
+ borderColor: vars.colorSuccessBorder,
+ },
+ cardDim: {
+ opacity: 0.5,
+ },
+ cardResult: {
+ boxShadow: vars.boxShadowTertiary,
+ },
+ cardRoot: {
+ backgroundColor: vars.colorBgContainerSecondary,
+ },
+ chip: {
+ alignItems: 'center',
+ backgroundColor: vars.colorFillTertiary,
+ borderRadius: vars.borderRadiusSM,
+ color: vars.colorTextSecondary,
+ display: 'flex',
+ flexShrink: 0,
+ height: 24,
+ justifyContent: 'center',
+ width: 24,
+ },
+ chipError: {
+ backgroundColor: vars.colorErrorBg,
+ color: vars.colorError,
+ },
+ chipInfo: {
+ backgroundColor: vars.colorInfoBg,
+ color: vars.colorInfo,
+ },
+ link: {
+ backgroundColor: 'transparent',
+ borderWidth: 0,
+ color: vars.colorText,
+ cursor: 'pointer',
+ padding: 0,
+ textAlign: 'start',
+ textDecorationLine: {
+ ':hover': 'underline',
+ 'default': 'none',
+ },
+ },
+ lines: {
+ height: '100%',
+ left: 0,
+ overflow: 'visible',
+ pointerEvents: 'none',
+ position: 'absolute',
+ top: 0,
+ width: '100%',
+ },
+ marker: {
+ alignItems: 'center',
+ borderColor: vars.colorBorder,
+ borderRadius: '50%',
+ borderStyle: 'solid',
+ borderWidth: 1.5,
+ boxSizing: 'border-box',
+ display: 'flex',
+ flexShrink: 0,
+ height: 16,
+ justifyContent: 'center',
+ marginBlockStart: 2,
+ width: 16,
+ },
+ markerChosen: {
+ backgroundColor: vars.colorSuccess,
+ borderColor: vars.colorSuccess,
+ color: vars.colorTextLightSolid,
+ },
+ srOnly: {
+ borderWidth: 0,
+ height: 1,
+ margin: -1,
+ overflow: 'hidden',
+ padding: 0,
+ position: 'absolute',
+ whiteSpace: 'nowrap',
+ width: 1,
+ },
+ wrap: {
+ columnGap: 48,
+ display: 'flex',
+ marginBlockStart: 4,
+ paddingBlock: 4,
+ position: 'relative',
+ },
+});
+
+const EFFECT_ICON: Record<DecisionEffect, LucideIcon> = {
+ fail: CircleX,
+ retire: Archive,
+ retry: RotateCcw,
+};
+
+interface Line {
+ active: boolean;
+ d: string;
+ from: Point;
+ key: string;
+ to: Point;
+}
+
+export interface DecisionGraphRoot {
+ /** What the question is about, e.g. the task that hit the gate. */
+ context?: { onOpen?: () => void; title: string };
+ /** The reason the question was asked. */
+ detail?: string;
+ /** Shown as the card's lead when nothing else says what this is about. */
+ question: string;
+}
+
+export interface DecisionGraphResultView {
+ /** Localized effect line, e.g. "Runs the task again". */
+ effectLabel?: Record<DecisionEffect, string>;
+ /** Who and when: the decider and the time. */
+ header: ReactNode;
+}
+
+interface DecisionGraphProps {
+ model: DecisionGraphModel;
+ result?: DecisionGraphResultView;
+ root: DecisionGraphRoot;
+}
+
+const DecisionGraph = memo<DecisionGraphProps>(({ model, result, root }) => {
+ const { t } = useTranslation('chat');
+ const wrapRef = useRef<HTMLDivElement>(null);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const resultRef = useRef<HTMLDivElement>(null);
+ const optionRefs = useRef<(HTMLDivElement | null)[]>([]);
+ const [lines, setLines] = useState<Line[]>([]);
+
+ const chosenIndex = model.options.findIndex((option) => option.state === 'chosen');
+
+ const measure = useCallback(() => {
+ const wrap = wrapRef.current;
+ const rootEl = rootRef.current;
+ if (!wrap || !rootEl) return;
+ const box = wrap.getBoundingClientRect();
+ const right = (el: HTMLElement) => {
+ const r = el.getBoundingClientRect();
+ return { x: r.right - box.left, y: r.top + r.height / 2 - box.top };
+ };
+ const left = (el: HTMLElement) => {
+ const r = el.getBoundingClientRect();
+ return { x: r.left - box.left, y: r.top + r.height / 2 - box.top };
+ };
+
+ const next: Line[] = [];
+ model.options.forEach((option, index) => {
+ const el = optionRefs.current[index];
+ if (!el) return;
+ const from = right(rootEl);
+ const to = left(el);
+ next.push({
+ active: option.state === 'chosen',
+ d: connectorPath(from, to),
+ from,
+ key: `root-${option.id}`,
+ to,
+ });
+ });
+ const resultEl = resultRef.current;
+ if (model.result && resultEl) {
+ const source = model.result.from === 'option' ? optionRefs.current[chosenIndex] : rootEl;
+ if (source) {
+ const from = right(source);
+ const to = left(resultEl);
+ next.push({ active: true, d: connectorPath(from, to), from, key: 'result', to });
+ }
+ }
+ setLines(next);
+ }, [chosenIndex, model]);
+
+ useLayoutEffect(() => {
+ measure();
+ const wrap = wrapRef.current;
+ if (!wrap || typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(wrap);
+ return () => observer.disconnect();
+ }, [measure]);
+
+ const hasContext = !!root.context || !!root.detail;
+
+ return (
+ <div ref={wrapRef} {...stylex.props(styles.wrap)}>
+ <svg aria-hidden {...stylex.props(styles.lines)}>
+ {/* Passed-over routes first, so the picked path always draws on top. */}
+ {[...lines]
+ .sort((x, y) => Number(x.active) - Number(y.active))
+ .map((line) => (
+ <g key={line.key}>
+ <path
+ d={line.d}
+ fill={'none'}
+ strokeDasharray={line.active ? undefined : '3 4'}
+ strokeLinecap={'round'}
+ strokeWidth={line.active ? 1.5 : 1}
+ style={{
+ stroke: line.active ? 'var(--lobe-color-success)' : 'var(--lobe-color-border)',
+ }}
+ />
+ {line.active &&
+ [line.from, line.to].map((point, index) => (
+ <circle
+ cx={point.x}
+ cy={point.y}
+ key={index}
+ r={3}
+ style={{ fill: 'var(--lobe-color-success)' }}
+ />
+ ))}
+ </g>
+ ))}
+ </svg>
+
+ <Flexbox flex={'0 1 26%'} justify={'center'} style={{ minWidth: 140 }}>
+ <div ref={rootRef} {...stylex.props(styles.card, styles.cardRoot)}>
+ <Flexbox horizontal align={'flex-start'} gap={10}>
+ <span {...stylex.props(styles.chip)}>
+ <Icon icon={GitBranch} size={14} />
+ </span>
+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>
+ {hasContext ? (
+ <>
+ {root.context && (
+ <Flexbox gap={2}>
+ <Text fontSize={12} style={{ color: 'var(--lobe-color-text-tertiary)' }}>
+ {t('goalProcess.decisions.raisedBy')}
+ </Text>
+ {root.context.onOpen ? (
+ <button
+ type={'button'}
+ {...stylex.props(styles.link)}
+ onClick={root.context.onOpen}
+ >
+ <Text style={{ wordBreak: 'break-word' }} weight={500}>
+ {root.context.title}
+ </Text>
+ </button>
+ ) : (
+ <Text style={{ wordBreak: 'break-word' }} weight={500}>
+ {root.context.title}
+ </Text>
+ )}
+ </Flexbox>
+ )}
+ {root.detail && (
+ <Text fontSize={13} style={{ wordBreak: 'break-word' }} type={'secondary'}>
+ {root.detail}
+ </Text>
+ )}
+ </>
+ ) : (
+ <Text style={{ wordBreak: 'break-word' }} weight={500}>
+ {root.question}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ </div>
+ </Flexbox>
+
+ <Flexbox flex={1} gap={8} justify={'center'} style={{ minWidth: 0 }}>
+ {model.options.map((option, index) => {
+ const chosen = option.state === 'chosen';
+ return (
+ <div
+ key={option.id}
+ ref={(el) => {
+ optionRefs.current[index] = el;
+ }}
+ {...stylex.props(
+ styles.card,
+ chosen && styles.cardChosen,
+ option.state === 'dim' && styles.cardDim,
+ )}
+ >
+ <Flexbox horizontal align={'flex-start'} gap={10}>
+ {/* A radio that fills in when picked: the state reads before the label does. */}
+ <span {...stylex.props(styles.marker, chosen && styles.markerChosen)}>
+ {chosen && <Icon icon={Check} size={10} style={{ strokeWidth: 3 }} />}
+ </span>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ rowGap: 2 }} wrap={'wrap'}>
+ <Text style={{ wordBreak: 'break-word' }} weight={chosen ? 600 : 500}>
+ {option.label}
+ </Text>
+ {option.recommended && (
+ <Flexbox horizontal align={'center'} gap={3} style={{ flex: 'none' }}>
+ <Icon color={vars.colorTextTertiary} icon={Sparkles} size={12} />
+ <Text fontSize={12} style={{ color: 'var(--lobe-color-text-tertiary)' }}>
+ {t('goalProcess.decisions.recommended')}
+ </Text>
+ </Flexbox>
+ )}
+ {chosen && (
+ <span {...stylex.props(styles.srOnly)}>
+ {t('goalProcess.decisions.chosen')}
+ </span>
+ )}
+ </Flexbox>
+ {option.description && (
+ <Text fontSize={13} style={{ wordBreak: 'break-word' }} type={'secondary'}>
+ {option.description}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ </div>
+ );
+ })}
+ </Flexbox>
+
+ {model.result && result && (
+ <Flexbox flex={'0 1 26%'} justify={'center'} style={{ minWidth: 140 }}>
+ <div ref={resultRef} {...stylex.props(styles.card, styles.cardResult)}>
+ <Flexbox gap={8}>
+ {result.header}
+ {model.result.effect && result.effectLabel && (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <span
+ {...stylex.props(
+ styles.chip,
+ model.result.effect === 'retry' && styles.chipInfo,
+ model.result.effect === 'fail' && styles.chipError,
+ )}
+ >
+ <Icon icon={EFFECT_ICON[model.result.effect]} size={14} />
+ </span>
+ <Text style={{ wordBreak: 'break-word' }} weight={600}>
+ {result.effectLabel[model.result.effect]}
+ </Text>
+ </Flexbox>
+ )}
+ {model.result.note && (
+ <Text fontSize={13} style={{ wordBreak: 'break-word' }} type={'secondary'}>
+ {model.result.note}
+ </Text>
+ )}
+ </Flexbox>
+ </div>
+ </Flexbox>
+ )}
+ </div>
+ );
+});
+
+DecisionGraph.displayName = 'GoalDecisionGraph';
+
+export default DecisionGraph;
diff --git a/src/features/AgentGoals/ProcessControl/Decisions.tsx b/src/features/AgentGoals/ProcessControl/Decisions.tsx
index 615566660ed..002e5358e8c 100644
--- a/src/features/AgentGoals/ProcessControl/Decisions.tsx
+++ b/src/features/AgentGoals/ProcessControl/Decisions.tsx
@@ -1,14 +1,16 @@
'use client';
-import { cssVar, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { ActionIcon, cssVar, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
import { cssVar as vars } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
-import { ArrowRight } from 'lucide-react';
-import { memo } from 'react';
+import { ArrowRight, ArrowUpRight, ChevronRight } from 'lucide-react';
+import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useActivityTime } from '@/hooks/useActivityTime';
+import DecisionGraph from './DecisionGraph';
+import { buildDecisionGraph } from './decisionGraphModel';
import { buildDecisionRows, type DecisionRow } from './decisionList';
import { AgentActor, UserActor } from './GoalActors';
import type { GoalGraphView } from './goalGraphViewModel';
@@ -18,10 +20,12 @@ import { useDecisionCopy } from './GoalResultFollowUps';
* Every call this goal stopped to ask, and who answered it — the trace behind
* "why did it go this way". Open questions lead, then settled ones newest
* first, each with the answer picked, any guidance written with it, and the
- * person or agent who gave it.
+ * person or agent who gave it. A row opens into a graph of the decision (see
+ * `DecisionGraph`): what raised it, the options it offered, where the answer
+ * went. Open questions start opened.
*
- * Answering still happens where the question is raised (the frontier); a row
- * only opens the node it was asked on.
+ * Answering still happens where the question is raised (the frontier); the
+ * arrow on a row opens the node it was asked on.
*/
const styles = stylex.create({
@@ -30,25 +34,37 @@ const styles = stylex.create({
borderBlockStartStyle: 'solid',
borderBlockStartWidth: 1,
},
+ arrow: {
+ color: vars.colorTextQuaternary,
+ flexShrink: 0,
+ transitionDuration: '0.2s',
+ transitionProperty: 'transform',
+ },
+ arrowOpen: {
+ transform: 'rotate(90deg)',
+ },
row: {
- backgroundColor: {
- ':hover': vars.colorFillQuaternary,
- 'default': 'transparent',
- },
- borderRadius: vars.borderRadiusSM,
+ paddingBlock: 10,
+ paddingInline: 8,
+ },
+ toggle: {
+ alignItems: 'center',
+ backgroundColor: 'transparent',
borderWidth: 0,
cursor: 'pointer',
+ display: 'flex',
+ flexGrow: 1,
+ gap: 6,
+ minWidth: 0,
outlineColor: vars.colorPrimary,
- outlineOffset: -2,
+ outlineOffset: 2,
outlineStyle: {
':focus-visible': 'solid',
'default': 'none',
},
outlineWidth: 2,
- paddingBlock: 10,
- paddingInline: 8,
+ padding: 0,
textAlign: 'start',
- width: '100%',
},
});
@@ -74,10 +90,15 @@ const Decider = memo<{ row: DecisionRow }>(({ row }) => {
Decider.displayName = 'GoalDecisionDecider';
-const DecisionTime = memo<{ at: Date }>(({ at }) => {
+const DecisionTime = memo<{ at: Date; compact?: boolean }>(({ at, compact }) => {
const { text, title } = useActivityTime(at);
return (
- <Text fontSize={12} style={TIME_STYLE} title={title} type={'secondary'}>
+ <Text
+ fontSize={12}
+ style={compact ? { flex: 'none' } : TIME_STYLE}
+ title={title}
+ type={'secondary'}
+ >
{text}
</Text>
);
@@ -85,6 +106,111 @@ const DecisionTime = memo<{ at: Date }>(({ at }) => {
DecisionTime.displayName = 'GoalDecisionTime';
+const DecisionRowView = memo<{
+ copy: ReturnType<ReturnType<typeof useDecisionCopy>>;
+ divided: boolean;
+ onSelect: (nodeId: string) => void;
+ row: DecisionRow;
+ /** The task whose gate this is, when the question was raised by one. */
+ subject?: { id: string; title: string };
+}>(({ copy, divided, onSelect, row, subject }) => {
+ const { t } = useTranslation('chat');
+ const [open, setOpen] = useState(row.actor === 'pending');
+ const { decision } = row;
+
+ return (
+ <Flexbox gap={6} {...stylex.props(styles.row, divided && styles.divided)}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <button
+ aria-expanded={open}
+ type={'button'}
+ {...stylex.props(styles.toggle)}
+ onClick={() => setOpen(!open)}
+ >
+ <Icon
+ icon={ChevronRight}
+ size={14}
+ {...stylex.props(styles.arrow, open && styles.arrowOpen)}
+ />
+ <Text ellipsis style={{ flex: 1, minWidth: 0 }} weight={500}>
+ {copy.question}
+ </Text>
+ </button>
+ <Decider row={row} />
+ <DecisionTime at={row.resolvedAt ?? decision.createdAt} />
+ <ActionIcon
+ aria-label={t('goalProcess.decisions.openNode')}
+ icon={ArrowUpRight}
+ size={'small'}
+ title={t('goalProcess.decisions.openNode')}
+ onClick={() => onSelect(decision.nodeId)}
+ />
+ </Flexbox>
+ {open ? (
+ <DecisionGraph
+ model={buildDecisionGraph(row, copy.options)}
+ result={{
+ effectLabel: {
+ fail: t('goalProcess.decisions.effect.fail'),
+ retire: t('goalProcess.decisions.effect.retire'),
+ retry: t('goalProcess.decisions.effect.retry'),
+ },
+ header: (
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ <Decider row={row} />
+ <DecisionTime compact at={row.resolvedAt ?? decision.createdAt} />
+ </Flexbox>
+ ),
+ }}
+ root={{
+ ...(subject
+ ? { context: { onOpen: () => onSelect(subject.id), title: subject.title } }
+ : {}),
+ ...(copy.detail ? { detail: copy.detail } : {}),
+ question: copy.question,
+ }}
+ />
+ ) : (
+ <>
+ {copy.detail && (
+ <Text
+ fontSize={13}
+ style={{ paddingInlineStart: 20, wordBreak: 'break-word' }}
+ type={'secondary'}
+ >
+ {copy.detail}
+ </Text>
+ )}
+ {copy.choice && (
+ <Flexbox horizontal align={'flex-start'} gap={6} style={{ paddingInlineStart: 20 }}>
+ <Icon
+ color={cssVar.colorPrimary}
+ icon={ArrowRight}
+ size={14}
+ style={{ flex: 'none', marginBlockStart: 3 }}
+ />
+ <Text style={{ wordBreak: 'break-word' }} weight={500}>
+ {copy.choice}
+ </Text>
+ </Flexbox>
+ )}
+ {row.note && (
+ <Text
+ fontSize={13}
+ style={{ paddingInlineStart: 40, wordBreak: 'break-word' }}
+ type={'secondary'}
+ >
+ {row.note}
+ </Text>
+ )}
+ </>
+ )}
+ </Flexbox>
+ );
+});
+
+DecisionRowView.displayName = 'GoalDecisionRowView';
+
const Decisions = memo<{ graph: GoalGraphView; onSelect: (nodeId: string) => void }>(
({ graph, onSelect }) => {
const { t } = useTranslation('chat');
@@ -101,51 +227,17 @@ const Decisions = memo<{ graph: GoalGraphView; onSelect: (nodeId: string) => voi
return (
<Flexbox gap={0}>
{rows.map((row, index) => {
- const copy = copyOf(row);
+ const subjectId = graph.byId[row.decision.nodeId]?.gateSubjectId;
+ const subjectNode = subjectId ? graph.byId[subjectId]?.node : undefined;
return (
- <button
+ <DecisionRowView
+ copy={copyOf(row)}
+ divided={index > 0}
key={row.decision.id}
- type={'button'}
- {...stylex.props(styles.row, index > 0 && styles.divided)}
- onClick={() => onSelect(row.decision.nodeId)}
- >
- <Flexbox gap={6}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Text ellipsis style={{ flex: 1, minWidth: 0 }} weight={500}>
- {copy.question}
- </Text>
- <Decider row={row} />
- <DecisionTime at={row.resolvedAt ?? row.decision.createdAt} />
- </Flexbox>
- {copy.detail && (
- <Text fontSize={13} style={{ wordBreak: 'break-word' }} type={'secondary'}>
- {copy.detail}
- </Text>
- )}
- {copy.choice && (
- <Flexbox horizontal align={'flex-start'} gap={6}>
- <Icon
- color={cssVar.colorPrimary}
- icon={ArrowRight}
- size={14}
- style={{ flex: 'none', marginBlockStart: 3 }}
- />
- <Text style={{ wordBreak: 'break-word' }} weight={500}>
- {copy.choice}
- </Text>
- </Flexbox>
- )}
- {row.note && (
- <Text
- fontSize={13}
- style={{ paddingInlineStart: 20, wordBreak: 'break-word' }}
- type={'secondary'}
- >
- {row.note}
- </Text>
- )}
- </Flexbox>
- </button>
+ row={row}
+ subject={subjectNode ? { id: subjectNode.id, title: subjectNode.title } : undefined}
+ onSelect={onSelect}
+ />
);
})}
</Flexbox>
diff --git a/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx b/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx
index d5d4f0524f4..df8c26112da 100644
--- a/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx
+++ b/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx
@@ -89,7 +89,14 @@ export const useDecisionCopy = (graph: GoalGraphView) => {
return (view: UserDecisionView) => {
const { decision } = view;
const kind = coordinatorGateKind(decision);
- if (!kind) return { choice: view.choice, question: view.question };
+ const optionsOf = (labelOf: (id: string) => string | undefined) =>
+ (decision.options ?? []).map((option) => ({
+ ...(option.description ? { description: option.description } : {}),
+ id: option.id,
+ label: labelOf(option.id) ?? option.label,
+ }));
+ if (!kind)
+ return { choice: view.choice, options: optionsOf(() => undefined), question: view.question };
const subjectId = graph.byId[decision.nodeId]?.gateSubjectId;
const subject = subjectId ? graph.byId[subjectId]?.node.title : undefined;
@@ -101,6 +108,10 @@ export const useDecisionCopy = (graph: GoalGraphView) => {
return {
choice,
detail: localizedCoordinatorReason(rawReason, t as any),
+ options: optionsOf((id) => {
+ const key = gateOptionLabelKey({ id }, kind);
+ return key ? t(key as any) : undefined;
+ }),
question: subject
? `${t(gateTitleKey(kind) as any)} · ${subject}`
: t(gateTitleKey(kind) as any),
diff --git a/src/features/AgentGoals/ProcessControl/decisionGraphModel.test.ts b/src/features/AgentGoals/ProcessControl/decisionGraphModel.test.ts
new file mode 100644
index 00000000000..c186a3cfef6
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/decisionGraphModel.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildDecisionGraph, connectorPath, effectOfOption } from './decisionGraphModel';
+import type { DecisionRow } from './decisionList';
+
+const row = (extra: Record<string, unknown>, rowExtra: Record<string, unknown> = {}) =>
+ ({
+ actor: 'user',
+ decision: {
+ options: [
+ { id: 'retry', label: 'Retry' },
+ { id: 'retire', label: 'Retire' },
+ { effect: 'retry', id: 'custom', label: 'Try it my way' },
+ ],
+ recommendedOptionId: 'retry',
+ resolvedOptionId: 'retire',
+ ...extra,
+ },
+ question: 'q',
+ ...rowExtra,
+ }) as unknown as DecisionRow;
+
+const labels = [
+ { id: 'retry', label: 'Retry' },
+ { id: 'retire', label: 'Retire' },
+ { id: 'custom', label: 'Try it my way' },
+];
+
+describe('buildDecisionGraph', () => {
+ it('marks the picked option, dims the rest and sends the result out of the picked one', () => {
+ const model = buildDecisionGraph(row({}, { note: 'not worth it' }), labels);
+
+ expect(model.options.map((option) => option.state)).toEqual(['dim', 'chosen', 'dim']);
+ expect(model.options[0].recommended).toBe(true);
+ expect(model.result).toEqual({
+ actor: 'user',
+ effect: 'retire',
+ from: 'option',
+ note: 'not worth it',
+ });
+ });
+
+ it('reads an effect from the option itself, then from the coordinator ids', () => {
+ expect(effectOfOption({ effect: 'retry', id: 'custom' })).toBe('retry');
+ expect(effectOfOption({ id: 'fail' })).toBe('fail');
+ expect(effectOfOption({ id: 'something-else' })).toBeUndefined();
+ });
+
+ it('leaves every option open and draws no result while the question waits', () => {
+ const model = buildDecisionGraph(row({ resolvedOptionId: null }, { actor: 'pending' }), labels);
+
+ expect(model.options.every((option) => option.state === 'open')).toBe(true);
+ expect(model.result).toBeUndefined();
+ });
+
+ it('hangs the result off the question when the answer was written out', () => {
+ const model = buildDecisionGraph(row({ resolvedOptionId: 'gone' }, { note: 'words' }), labels);
+
+ expect(model.options.every((option) => option.state === 'open')).toBe(true);
+ expect(model.result).toMatchObject({ from: 'root', note: 'words' });
+ });
+
+ it('shows the written answer when the question was answered in free text', () => {
+ const model = buildDecisionGraph(
+ row({ resolvedOptionId: 'answer' }, { choice: 'ship it on Friday' }),
+ [...labels, { id: 'answer', label: 'Answer with my note' }],
+ );
+
+ expect(model.options.find((option) => option.state === 'chosen')?.id).toBe('answer');
+ expect(model.result).toMatchObject({ from: 'option', note: 'ship it on Friday' });
+ });
+
+ it('keeps who settled it on the result', () => {
+ expect(buildDecisionGraph(row({}, { actor: 'agent' }), labels).result?.actor).toBe('agent');
+ });
+});
+
+describe('connectorPath', () => {
+ it('curves horizontally from one edge to the next', () => {
+ expect(connectorPath({ x: 0, y: 10 }, { x: 100, y: 50 })).toBe('M 0 10 C 50 10, 50 50, 100 50');
+ });
+
+ it('keeps a minimum reach on tight gaps', () => {
+ expect(connectorPath({ x: 0, y: 0 }, { x: 10, y: 0 })).toBe('M 0 0 C 24 0, -14 0, 10 0');
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/decisionGraphModel.ts b/src/features/AgentGoals/ProcessControl/decisionGraphModel.ts
new file mode 100644
index 00000000000..9dcc03a527d
--- /dev/null
+++ b/src/features/AgentGoals/ProcessControl/decisionGraphModel.ts
@@ -0,0 +1,101 @@
+import { GOAL_CLARIFICATION_OPTION } from '@lobechat/const/goal';
+import type { GoalDecisionOption } from '@lobechat/types';
+
+import type { DecisionActor, DecisionRow } from './decisionList';
+
+/**
+ * The shape of one decision drawn as a graph: what raised it, the options it
+ * offered, and — once settled — where the answer went. Pure data; labels and
+ * layout belong to the view.
+ */
+
+/** What picking an option does to the work that raised the question. */
+export type DecisionEffect = 'fail' | 'retire' | 'retry';
+
+export interface DecisionGraphOption {
+ description?: string;
+ effect?: DecisionEffect;
+ id: string;
+ label: string;
+ recommended: boolean;
+ /** `chosen` is the picked path, `dim` an option passed over, `open` one still on the table. */
+ state: 'chosen' | 'dim' | 'open';
+}
+
+export interface DecisionGraphResult {
+ actor: Exclude<DecisionActor, 'pending'>;
+ effect?: DecisionEffect;
+ /** Where the line into the result comes from: the picked option, or the question when the answer was written out. */
+ from: 'option' | 'root';
+ note?: string;
+}
+
+export interface DecisionGraphModel {
+ options: DecisionGraphOption[];
+ result?: DecisionGraphResult;
+}
+
+const COORDINATOR_EFFECTS = new Set<string>(['fail', 'retire', 'retry']);
+
+export const effectOfOption = (
+ option: Pick<GoalDecisionOption, 'effect' | 'id'>,
+): DecisionEffect | undefined =>
+ option.effect ?? (COORDINATOR_EFFECTS.has(option.id) ? (option.id as DecisionEffect) : undefined);
+
+/**
+ * `labels` are the options as the reader should see them (already localized,
+ * same order as the stored ones); stored ids and effects decide everything else.
+ */
+export const buildDecisionGraph = (
+ row: DecisionRow,
+ labels: { description?: string; id: string; label: string }[],
+): DecisionGraphModel => {
+ const { decision } = row;
+ const stored = new Map((decision.options ?? []).map((option) => [option.id, option]));
+ const settled = row.actor !== 'pending';
+ const chosenId = settled ? decision.resolvedOptionId : undefined;
+ const hasChosen = !!chosenId && labels.some((option) => option.id === chosenId);
+
+ const options = labels.map((option): DecisionGraphOption => {
+ const effect = stored.has(option.id) ? effectOfOption(stored.get(option.id)!) : undefined;
+ return {
+ ...(option.description ? { description: option.description } : {}),
+ ...(effect ? { effect } : {}),
+ id: option.id,
+ label: option.label,
+ recommended: option.id === decision.recommendedOptionId,
+ state: !hasChosen ? 'open' : option.id === chosenId ? 'chosen' : 'dim',
+ };
+ });
+
+ if (!settled || row.actor === 'pending') return { options };
+
+ const chosen = options.find((option) => option.state === 'chosen');
+ const effect = chosen?.effect;
+ // The free-text option carries no wording of its own, so the words are the
+ // answer itself: `buildDecisionRows` keeps them on `choice` instead of the
+ // `note` written next to a picked option. The graph has to show them either
+ // way, or expanding the decision would hide what the person actually said.
+ const answered = decision.resolvedOptionId === GOAL_CLARIFICATION_OPTION.answer;
+ const written = row.note ?? (answered || !chosen ? row.choice : undefined);
+ return {
+ options,
+ result: {
+ actor: row.actor,
+ ...(effect ? { effect } : {}),
+ from: chosen ? 'option' : 'root',
+ ...(written ? { note: written } : {}),
+ },
+ };
+};
+
+export interface Point {
+ x: number;
+ y: number;
+}
+
+/** A horizontal S-curve between two node edges, the way the exploration map joins its nodes. */
+export const connectorPath = (from: Point, to: Point): string => {
+ const reach = Math.max(24, (to.x - from.x) / 2);
+ return `M ${from.x} ${from.y} C ${from.x + reach} ${from.y}, ${to.x - reach} ${to.y}, ${to.x} ${to.y}`;
+};