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): make the exploration map legend a node-kind filter (#19078)

Arvin Xu164b11d7e9a2
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 1ac4656aff6..b82c29f236c 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -560,6 +560,8 @@
"goalProcess.gate.title.recoverTask": "Decide what happens to the failed task",
"goalProcess.graph.exitFullscreen": "Exit fullscreen",
"goalProcess.graph.fullscreen": "Fullscreen",
+ "goalProcess.graph.legend.hide": "Hide this kind on the map",
+ "goalProcess.graph.legend.show": "Show this kind on the map",
"goalProcess.graph.title": "Exploration map",
"goalProcess.graph.view.all": "Full map",
"goalProcess.graph.view.stage": "Current stage",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 07459f4e673..ee313272c93 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -560,6 +560,8 @@
"goalProcess.gate.title.recoverTask": "决定失败任务的去向",
"goalProcess.graph.exitFullscreen": "退出全屏",
"goalProcess.graph.fullscreen": "全屏",
+ "goalProcess.graph.legend.hide": "在图中隐藏这类节点",
+ "goalProcess.graph.legend.show": "在图中显示这类节点",
"goalProcess.graph.title": "探索图",
"goalProcess.graph.view.all": "全图",
"goalProcess.graph.view.stage": "当前阶段",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 18c2cef594e..e6a80615fe4 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1910,6 +1910,8 @@ export default {
'goalProcess.graph.view.all': 'Full map',
'goalProcess.graph.fullscreen': 'Fullscreen',
'goalProcess.graph.exitFullscreen': 'Exit fullscreen',
+ 'goalProcess.graph.legend.hide': 'Hide this kind on the map',
+ 'goalProcess.graph.legend.show': 'Show this kind on the map',
'goalProcess.edge.investigates': 'investigates',
'goalProcess.edge.produces': 'produces',
'goalProcess.edge.supports': 'supports',
diff --git a/src/features/AgentGoals/ProcessControl/Graph/index.tsx b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
index 94ac5b0c88b..c6160ec8994 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/index.tsx
+++ b/src/features/AgentGoals/ProcessControl/Graph/index.tsx
@@ -2,7 +2,7 @@
import '@xyflow/react/dist/style.css';
-import type { GoalGraphEdge, GoalGraphNode } from '@lobechat/types';
+import type { GoalGraphEdge, GoalGraphNode, GoalNodeKind } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import { ActionIcon, Segmented, Text } from '@lobehub/ui/base-ui';
import {
@@ -30,13 +30,15 @@ import { chatPortalSelectors } from '@/store/chat/selectors';
import type { GoalGraphView, GoalNodeView } from '../goalGraphViewModel';
import { KindDot } from '../shared';
import GraphNodeView, { GhostNodeView, type GraphNodeData } from './GraphNode';
-import { layoutGraph, NODE_WIDTH } from './layout';
+import { hideKinds, layoutGraph, NODE_WIDTH } from './layout';
/**
* The exploration map. Two views: 当前阶段 (what got the goal here plus what the
* next advance unlocks) and 全图. Edges carry their relation as a label so the
- * map reads without a legend; fullscreen is a real overlay, not a taller box,
- * and carries its own right-hand portal panel so node drill-down keeps working.
+ * map reads without a legend; the legend itself is a kind filter — click 任务
+ * or 结论 off and the map relayouts around what remains. Fullscreen is a real
+ * overlay, not a taller box, and carries its own right-hand portal panel so
+ * node drill-down keeps working.
*/
const styles = createStaticStyles(({ css }) => ({
@@ -88,6 +90,23 @@ const styles = createStaticStyles(({ css }) => ({
font-size: 12px;
color: ${cssVar.colorTextTertiary};
`,
+ legendItem: css`
+ cursor: pointer;
+ user-select: none;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ }
+ `,
+ /* A hidden kind stays in the legend as a dimmed toggle — the way back must
+ be exactly where the way in was. */
+ legendOff: css`
+ opacity: 0.35;
+
+ &:hover {
+ opacity: 0.65;
+ }
+ `,
/* Fullscreen chrome floats over the canvas in two corner cards instead of a
full-width bar, so a node panned to the top edge is never hidden behind an
opaque header strip. */
@@ -240,107 +259,138 @@ const GHOST_HEIGHT = 88;
const Canvas = memo<
Pick<GraphProps, 'graph' | 'onSelect' | 'planning' | 'selectedId'> & {
className: string;
+ hiddenKinds: ReadonlySet<GoalNodeKind>;
interactive: boolean;
/** Bump to refit after the frame around the canvas changes size. */
refitKey?: boolean;
view: GraphViewMode;
}
->(({ className, graph, interactive, onSelect, planning, refitKey, selectedId, view }) => {
- const { fitView } = useReactFlow();
- const subtitleOf = useSubtitle();
- const edgeLabel = useEdgeLabel();
-
- const visibleIds = useMemo(
- () => (view === 'all' ? new Set(graph.nodes.map((item) => item.node.id)) : stageNodeIds(graph)),
- [graph, view],
- );
- const positions = useMemo(() => {
- const nodes: GoalGraphNode[] = graph.nodes
- .filter((item) => visibleIds.has(item.node.id))
- .map((item) => item.node);
- const edges = graph.edges.filter(
- (edge) => visibleIds.has(edge.sourceNodeId) && visibleIds.has(edge.targetNodeId),
+>(
+ ({
+ className,
+ graph,
+ hiddenKinds,
+ interactive,
+ onSelect,
+ planning,
+ refitKey,
+ selectedId,
+ view,
+ }) => {
+ const { fitView } = useReactFlow();
+ const subtitleOf = useSubtitle();
+ const edgeLabel = useEdgeLabel();
+
+ const baseIds = useMemo(
+ () =>
+ view === 'all' ? new Set(graph.nodes.map((item) => item.node.id)) : stageNodeIds(graph),
+ [graph, view],
);
- return layoutGraph(nodes, edges);
- }, [graph, visibleIds]);
-
- const ghosts = useMemo(() => {
- if (!planning) return [];
- const problem = graph.nodes.find((item) => item.node.kind === 'problem');
- const box = problem ? positions[problem.node.id] : undefined;
- const centerX = box ? box.x + box.width / 2 : 0;
- const y = box ? box.y + box.height + GHOST_RANK_GAP : 0;
- const width = NODE_WIDTH.task;
- const total = width * GHOST_COUNT + GHOST_GAP * (GHOST_COUNT - 1);
- return Array.from({ length: GHOST_COUNT }, (_, i) => ({
- id: `goal-ghost-${i}`,
- sourceId: problem && box ? problem.node.id : undefined,
- x: centerX - total / 2 + i * (width + GHOST_GAP),
- y,
- }));
- }, [planning, graph, positions]);
-
- // Inline, the canvas hugs its content: a two-node graph in a fixed 560px
- // frame is mostly empty margin, and `fitView` then shrinks the nodes to
- // fill it. Sizing the frame from the layout keeps small graphs at natural
- // node scale; 560px stays the ceiling so large graphs still zoom out.
- const inlineHeight = useMemo(() => {
- const boxes = Object.values(positions);
- if (boxes.length === 0 && ghosts.length === 0) return 216;
- const top = Math.min(...boxes.map((box) => box.y), ...ghosts.map((ghost) => ghost.y));
- const bottom = Math.max(
- ...boxes.map((box) => box.y + box.height),
- ...ghosts.map((ghost) => ghost.y + GHOST_HEIGHT),
+ const { bridges, visibleIds } = useMemo(
+ () =>
+ hideKinds(
+ graph.nodes.filter((item) => baseIds.has(item.node.id)).map((item) => item.node),
+ graph.edges,
+ hiddenKinds,
+ ),
+ [graph, baseIds, hiddenKinds],
);
- return Math.min(560, Math.max(216, bottom - top + 72));
- }, [positions, ghosts]);
-
- const ghostFlowNodes: FlowNode[] = useMemo(
- () =>
- ghosts.map((ghost) => ({
- data: {},
- draggable: false,
- id: ghost.id,
- position: { x: ghost.x, y: ghost.y },
- selectable: false,
- type: 'goalGhost',
- width: NODE_WIDTH.task,
- })),
- [ghosts],
- );
-
- const flowNodes: FlowNode[] = useMemo(
- () =>
- graph.nodes
+ const positions = useMemo(() => {
+ const nodes: GoalGraphNode[] = graph.nodes
.filter((item) => visibleIds.has(item.node.id))
- .map((item) => {
- const box = positions[item.node.id];
- const isGate = item.node.kind === 'decision' && item.node.status === 'waiting';
- const data: GraphNodeData = {
- // Not started and still blocked — it is context, not the story.
- dim: item.node.status === 'proposed' && item.blockers.length > 0,
- isGate,
- running: item.node.status === 'active' && !item.isStale,
- selected: selectedId === item.node.id,
- stale: item.isStale,
- subtitle: subtitleOf(item),
- view: item,
- };
- return {
- data,
- draggable: false,
- id: item.node.id,
- position: { x: box?.x ?? 0, y: box?.y ?? 0 },
- type: 'goalNode',
- width: NODE_WIDTH[item.node.kind],
- } satisfies FlowNode;
- }),
- [graph, visibleIds, positions, selectedId, subtitleOf],
- );
+ .map((item) => item.node);
+ const edges = [
+ ...graph.edges.filter(
+ (edge) => visibleIds.has(edge.sourceNodeId) && visibleIds.has(edge.targetNodeId),
+ ),
+ // Bridges rank like the chain they replace, keeping survivors at depth.
+ ...bridges.map((bridge) => ({ ...bridge, kind: 'leads_to' as const })),
+ ];
+ return layoutGraph(nodes, edges);
+ }, [graph, visibleIds, bridges]);
+
+ const ghosts = useMemo(() => {
+ if (!planning) return [];
+ const problem = graph.nodes.find((item) => item.node.kind === 'problem');
+ const box = problem ? positions[problem.node.id] : undefined;
+ const centerX = box ? box.x + box.width / 2 : 0;
+ const y = box ? box.y + box.height + GHOST_RANK_GAP : 0;
+ const width = NODE_WIDTH.task;
+ const total = width * GHOST_COUNT + GHOST_GAP * (GHOST_COUNT - 1);
+ return Array.from({ length: GHOST_COUNT }, (_, i) => ({
+ id: `goal-ghost-${i}`,
+ sourceId: problem && box ? problem.node.id : undefined,
+ x: centerX - total / 2 + i * (width + GHOST_GAP),
+ y,
+ }));
+ }, [planning, graph, positions]);
+
+ // Inline, the canvas hugs its content: a two-node graph in a fixed 560px
+ // frame is mostly empty margin, and `fitView` then shrinks the nodes to
+ // fill it. Sizing the frame from the layout keeps small graphs at natural
+ // node scale; 560px stays the ceiling so large graphs still zoom out.
+ const inlineHeight = useMemo(() => {
+ const boxes = Object.values(positions);
+ if (boxes.length === 0 && ghosts.length === 0) return 216;
+ const top = Math.min(...boxes.map((box) => box.y), ...ghosts.map((ghost) => ghost.y));
+ const bottom = Math.max(
+ ...boxes.map((box) => box.y + box.height),
+ ...ghosts.map((ghost) => ghost.y + GHOST_HEIGHT),
+ );
+ return Math.min(560, Math.max(216, bottom - top + 72));
+ }, [positions, ghosts]);
+
+ const ghostFlowNodes: FlowNode[] = useMemo(
+ () =>
+ ghosts.map((ghost) => ({
+ data: {},
+ draggable: false,
+ id: ghost.id,
+ position: { x: ghost.x, y: ghost.y },
+ selectable: false,
+ type: 'goalGhost',
+ width: NODE_WIDTH.task,
+ })),
+ [ghosts],
+ );
- const flowEdges: FlowEdge[] = useMemo(
- () =>
- graph.edges
+ const flowNodes: FlowNode[] = useMemo(
+ () =>
+ graph.nodes
+ .filter((item) => visibleIds.has(item.node.id))
+ .map((item) => {
+ const box = positions[item.node.id];
+ const isGate = item.node.kind === 'decision' && item.node.status === 'waiting';
+ const data: GraphNodeData = {
+ // Not started and still blocked — it is context, not the story.
+ dim: item.node.status === 'proposed' && item.blockers.length > 0,
+ isGate,
+ running: item.node.status === 'active' && !item.isStale,
+ selected: selectedId === item.node.id,
+ stale: item.isStale,
+ subtitle: subtitleOf(item),
+ view: item,
+ };
+ return {
+ data,
+ draggable: false,
+ id: item.node.id,
+ position: { x: box?.x ?? 0, y: box?.y ?? 0 },
+ type: 'goalNode',
+ width: NODE_WIDTH[item.node.kind],
+ } satisfies FlowNode;
+ }),
+ [graph, visibleIds, positions, selectedId, subtitleOf],
+ );
+
+ const flowEdges: FlowEdge[] = useMemo(() => {
+ const marker = {
+ color: cssVar.colorBorder,
+ height: 12,
+ type: MarkerType.ArrowClosed,
+ width: 12,
+ };
+ const direct = graph.edges
.filter((edge) => visibleIds.has(edge.sourceNodeId) && visibleIds.has(edge.targetNodeId))
.map((edge) => {
const [source, target] = orient(edge);
@@ -350,102 +400,113 @@ const Canvas = memo<
id: edge.id,
label: edgeLabel(edge.kind),
labelShowBg: true,
- markerEnd: {
- color: cssVar.colorBorder,
- height: 12,
- type: MarkerType.ArrowClosed,
- width: 12,
- },
+ markerEnd: marker,
source,
target,
type: 'default',
} satisfies FlowEdge;
- }),
- [graph, visibleIds, selectedId, edgeLabel],
- );
-
- const ghostFlowEdges: FlowEdge[] = useMemo(
- () =>
- ghosts
- .filter((ghost) => ghost.sourceId)
- .map((ghost) => ({
- animated: true,
- id: `${ghost.id}-edge`,
- source: ghost.sourceId!,
- target: ghost.id,
+ });
+ // A bridge stands in for a chain through hidden nodes: dashed like other
+ // indirect relations, and unlabeled — any word would claim a relation the
+ // hidden hop may not have.
+ const bridged = bridges.map((bridge) => {
+ const hot = selectedId === bridge.sourceNodeId || selectedId === bridge.targetNodeId;
+ return {
+ className: cx('goal-dep', hot && 'goal-hot'),
+ id: `bridge:${bridge.sourceNodeId}:${bridge.targetNodeId}`,
+ markerEnd: marker,
+ source: bridge.sourceNodeId,
+ target: bridge.targetNodeId,
type: 'default',
- })),
- [ghosts],
- );
-
- const allNodes = useMemo(() => [...flowNodes, ...ghostFlowNodes], [flowNodes, ghostFlowNodes]);
- const allEdges = useMemo(() => [...flowEdges, ...ghostFlowEdges], [flowEdges, ghostFlowEdges]);
-
- useEffect(() => {
- const timer = setTimeout(
- () => fitView({ duration: 200, maxZoom: 1, minZoom: 0.6, padding: 0.12 }),
- 30,
- );
- return () => clearTimeout(timer);
- }, [view, allNodes.length, fitView]);
-
- // The portal panel borrows width from the canvas; wait out its slide
- // animation before refitting, or the fit is computed mid-transition.
- useEffect(() => {
- if (refitKey === undefined) return;
- const timer = setTimeout(
- () => fitView({ duration: 200, maxZoom: 1, minZoom: 0.6, padding: 0.12 }),
- 280,
+ } satisfies FlowEdge;
+ });
+ return [...direct, ...bridged];
+ }, [graph, visibleIds, bridges, selectedId, edgeLabel]);
+
+ const ghostFlowEdges: FlowEdge[] = useMemo(
+ () =>
+ ghosts
+ .filter((ghost) => ghost.sourceId)
+ .map((ghost) => ({
+ animated: true,
+ id: `${ghost.id}-edge`,
+ source: ghost.sourceId!,
+ target: ghost.id,
+ type: 'default',
+ })),
+ [ghosts],
);
- return () => clearTimeout(timer);
- }, [refitKey, fitView]);
- return (
- <div className={className} style={interactive ? undefined : { height: inlineHeight }}>
- {/* Inline, the map is a picture: it settles on `fitView` and stays
+ const allNodes = useMemo(() => [...flowNodes, ...ghostFlowNodes], [flowNodes, ghostFlowNodes]);
+ const allEdges = useMemo(() => [...flowEdges, ...ghostFlowEdges], [flowEdges, ghostFlowEdges]);
+
+ useEffect(() => {
+ const timer = setTimeout(
+ () => fitView({ duration: 200, maxZoom: 1, minZoom: 0.6, padding: 0.12 }),
+ 30,
+ );
+ return () => clearTimeout(timer);
+ }, [view, allNodes.length, hiddenKinds, fitView]);
+
+ // The portal panel borrows width from the canvas; wait out its slide
+ // animation before refitting, or the fit is computed mid-transition.
+ useEffect(() => {
+ if (refitKey === undefined) return;
+ const timer = setTimeout(
+ () => fitView({ duration: 200, maxZoom: 1, minZoom: 0.6, padding: 0.12 }),
+ 280,
+ );
+ return () => clearTimeout(timer);
+ }, [refitKey, fitView]);
+
+ return (
+ <div className={className} style={interactive ? undefined : { height: inlineHeight }}>
+ {/* Inline, the map is a picture: it settles on `fitView` and stays
there. Panning or zooming it inside a scrolling page moves the graph
under the cursor while the page moves too, and leaves no way back to
the framing the layout chose. Fullscreen is where it is navigable. */}
- <ReactFlow
- fitView
- edges={allEdges}
- maxZoom={interactive ? 1.5 : 1}
- minZoom={0.3}
- nodeTypes={nodeTypes}
- nodes={allNodes}
- nodesConnectable={false}
- nodesDraggable={false}
- panOnDrag={interactive}
- // Fullscreen reads like Figma on a trackpad: two-finger scroll pans
- // and pinch (ctrl+wheel) zooms. Wheel-to-zoom is off — on a mouse,
- // zooming stays on pinch/double-click and the +/- controls.
- panOnScroll={interactive}
- preventScrolling={interactive}
- proOptions={{ hideAttribution: true }}
- zoomOnDoubleClick={interactive}
- zoomOnPinch={interactive}
- zoomOnScroll={false}
- onNodeClick={(_, node) => {
- if (node.type !== 'goalGhost') onSelect(node.id);
- }}
- >
- <Background
- color={cssVar.colorBorderSecondary}
- gap={18}
- size={1}
- variant={BackgroundVariant.Dots}
- />
- {interactive && <Controls position={'bottom-right'} showInteractive={false} />}
- </ReactFlow>
- </div>
- );
-});
+ <ReactFlow
+ fitView
+ edges={allEdges}
+ maxZoom={interactive ? 1.5 : 1}
+ minZoom={0.3}
+ nodeTypes={nodeTypes}
+ nodes={allNodes}
+ nodesConnectable={false}
+ nodesDraggable={false}
+ panOnDrag={interactive}
+ // Fullscreen reads like Figma on a trackpad: two-finger scroll pans
+ // and pinch (ctrl+wheel) zooms. Wheel-to-zoom is off — on a mouse,
+ // zooming stays on pinch/double-click and the +/- controls.
+ panOnScroll={interactive}
+ preventScrolling={interactive}
+ proOptions={{ hideAttribution: true }}
+ zoomOnDoubleClick={interactive}
+ zoomOnPinch={interactive}
+ zoomOnScroll={false}
+ onNodeClick={(_, node) => {
+ if (node.type !== 'goalGhost') onSelect(node.id);
+ }}
+ >
+ <Background
+ color={cssVar.colorBorderSecondary}
+ gap={18}
+ size={1}
+ variant={BackgroundVariant.Dots}
+ />
+ {interactive && <Controls position={'bottom-right'} showInteractive={false} />}
+ </ReactFlow>
+ </div>
+ );
+ },
+);
Canvas.displayName = 'GoalGraphCanvas';
const Graph = memo<GraphProps>(({ fullscreen, onFullscreenChange, ...props }) => {
const { t } = useTranslation('chat');
const [view, setView] = useState<GraphViewMode>('stage');
+ const [hiddenKinds, setHiddenKinds] = useState<ReadonlySet<GoalNodeKind>>(() => new Set());
const showPortal = useChatStore(chatPortalSelectors.showPortal);
const currentViewType = useChatStore(chatPortalSelectors.currentViewType);
const clearPortalStack = useChatStore((s) => s.clearPortalStack);
@@ -453,6 +514,15 @@ const Graph = memo<GraphProps>(({ fullscreen, onFullscreenChange, ...props }) =>
// size when it moves between the page and the fullscreen overlay.
const { maxWidth, minWidth, updateWidth, width } = usePortalPanelWidth(currentViewType, 'goal');
+ const toggleKind = useCallback((kind: GoalNodeKind) => {
+ setHiddenKinds((prev) => {
+ const next = new Set(prev);
+ if (next.has(kind)) next.delete(kind);
+ else next.add(kind);
+ return next;
+ });
+ }, []);
+
const titleAndViews = (
<>
<Text fontSize={16} weight={600}>
@@ -471,12 +541,24 @@ const Graph = memo<GraphProps>(({ fullscreen, onFullscreenChange, ...props }) =>
);
const legend = (
<Flexbox horizontal align={'center'} className={styles.legend} gap={10}>
- {(['problem', 'task', 'finding', 'decision'] as const).map((kind) => (
- <Flexbox horizontal align={'center'} gap={4} key={kind}>
- <KindDot kind={kind} />
- <span>{t(`goalProcess.kind.${kind}` as const)}</span>
- </Flexbox>
- ))}
+ {(['problem', 'task', 'finding', 'decision'] as const).map((kind) => {
+ const off = hiddenKinds.has(kind);
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={cx(styles.legendItem, off && styles.legendOff)}
+ gap={4}
+ key={kind}
+ role={'button'}
+ title={t(off ? 'goalProcess.graph.legend.show' : 'goalProcess.graph.legend.hide')}
+ onClick={() => toggleKind(kind)}
+ >
+ <KindDot kind={kind} />
+ <span>{t(`goalProcess.kind.${kind}` as const)}</span>
+ </Flexbox>
+ );
+ })}
</Flexbox>
);
const toggle = (
@@ -497,6 +579,7 @@ const Graph = memo<GraphProps>(({ fullscreen, onFullscreenChange, ...props }) =>
{...props}
interactive
className={cx(styles.canvas, styles.full)}
+ hiddenKinds={hiddenKinds}
refitKey={showPortal}
view={view}
/>
@@ -539,7 +622,13 @@ const Graph = memo<GraphProps>(({ fullscreen, onFullscreenChange, ...props }) =>
</Flexbox>
</Flexbox>
<ReactFlowProvider>
- <Canvas {...props} className={styles.canvas} interactive={false} view={view} />
+ <Canvas
+ {...props}
+ className={styles.canvas}
+ hiddenKinds={hiddenKinds}
+ interactive={false}
+ view={view}
+ />
</ReactFlowProvider>
</Flexbox>
);
diff --git a/src/features/AgentGoals/ProcessControl/Graph/layout.test.ts b/src/features/AgentGoals/ProcessControl/Graph/layout.test.ts
index 80994f09a63..b85d1729967 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/layout.test.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/layout.test.ts
@@ -1,7 +1,7 @@
import type { GoalGraphEdge, GoalGraphNode } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { layoutGraph } from './layout';
+import { hideKinds, layoutGraph } from './layout';
const node = (id: string, kind: GoalGraphNode['kind'] = 'task'): GoalGraphNode => ({
confidence: null,
@@ -78,3 +78,69 @@ describe('layoutGraph', () => {
expect(Object.keys(boxes)).toHaveLength(2);
});
});
+
+describe('hideKinds', () => {
+ const chain = {
+ edges: [edge('p1', 'w1', 'decomposes'), edge('w1', 'f1', 'produces')],
+ nodes: [node('p1', 'problem'), node('w1'), node('f1', 'finding')],
+ };
+
+ it('keeps everything and bridges nothing when no kind is hidden', () => {
+ const { bridges, visibleIds } = hideKinds(chain.nodes, chain.edges, new Set());
+
+ expect([...visibleIds].sort()).toEqual(['f1', 'p1', 'w1']);
+ expect(bridges).toEqual([]);
+ });
+
+ it('bridges the problem to the finding when the task between them is hidden', () => {
+ const { bridges, visibleIds } = hideKinds(chain.nodes, chain.edges, new Set(['task']));
+
+ expect(visibleIds.has('w1')).toBe(false);
+ expect(bridges).toEqual([{ sourceNodeId: 'p1', targetNodeId: 'f1' }]);
+ });
+
+ it('keeps a bridged finding ranked below the problem', () => {
+ const { bridges, visibleIds } = hideKinds(chain.nodes, chain.edges, new Set(['task']));
+ const boxes = layoutGraph(
+ chain.nodes.filter((n) => visibleIds.has(n.id)),
+ bridges.map((bridge) => ({ ...bridge, kind: 'leads_to' as const })),
+ );
+
+ expect(boxes.f1.y).toBeGreaterThan(boxes.p1.y);
+ });
+
+ it('bridges through consecutive hidden hops', () => {
+ const { bridges } = hideKinds(
+ [node('p1', 'problem'), node('w1'), node('w2'), node('f1', 'finding')],
+ [edge('p1', 'w1', 'decomposes'), edge('w1', 'w2', 'leads_to'), edge('w2', 'f1', 'produces')],
+ new Set(['task']),
+ );
+
+ expect(bridges).toEqual([{ sourceNodeId: 'p1', targetNodeId: 'f1' }]);
+ });
+
+ it('does not add a bridge that duplicates a surviving direct edge', () => {
+ const { bridges } = hideKinds(
+ [node('p1', 'problem'), node('w1'), node('f1', 'finding')],
+ [edge('p1', 'w1', 'decomposes'), edge('w1', 'f1', 'produces'), edge('p1', 'f1', 'leads_to')],
+ new Set(['task']),
+ );
+
+ expect(bridges).toEqual([]);
+ });
+
+ it('survives a cycle among hidden nodes', () => {
+ const { bridges } = hideKinds(
+ [node('p1', 'problem'), node('w1'), node('w2'), node('f1', 'finding')],
+ [
+ edge('p1', 'w1', 'decomposes'),
+ edge('w1', 'w2', 'leads_to'),
+ edge('w2', 'w1', 'leads_to'),
+ edge('w2', 'f1', 'produces'),
+ ],
+ new Set(['task']),
+ );
+
+ expect(bridges).toEqual([{ sourceNodeId: 'p1', targetNodeId: 'f1' }]);
+ });
+});
diff --git a/src/features/AgentGoals/ProcessControl/Graph/layout.ts b/src/features/AgentGoals/ProcessControl/Graph/layout.ts
index 93e433a44b5..1621a0faf94 100644
--- a/src/features/AgentGoals/ProcessControl/Graph/layout.ts
+++ b/src/features/AgentGoals/ProcessControl/Graph/layout.ts
@@ -1,4 +1,4 @@
-import type { GoalGraphEdge, GoalGraphNode } from '@lobechat/types';
+import type { GoalGraphEdge, GoalGraphNode, GoalNodeKind } from '@lobechat/types';
/**
* Layered DAG layout for the exploration graph.
@@ -15,12 +15,15 @@ export const NODE_HEIGHT = { decision: 76, finding: 76, problem: 76, task: 112 }
const RANK_GAP = 56;
const COLUMN_GAP = 32;
+/** The fields layout actually reads — lets callers pass synthetic bridge edges. */
+export type LayoutEdge = Pick<GoalGraphEdge, 'kind' | 'sourceNodeId' | 'targetNodeId'>;
+
/**
* Which way an edge points on screen. `supports` / `contradicts` link a finding
* back to the problem it answers, so they are drawn but never rank a node —
* using them would fight the produce chain that put the finding there.
*/
-const rankDirection = (edge: GoalGraphEdge): [string, string] | undefined => {
+const rankDirection = (edge: LayoutEdge): [string, string] | undefined => {
switch (edge.kind) {
case 'decomposes':
case 'investigates':
@@ -45,9 +48,67 @@ export interface LayoutBox {
y: number;
}
+/** A synthetic edge standing in for a ranked chain that runs through hidden nodes. */
+export interface GraphBridge {
+ sourceNodeId: string;
+ targetNodeId: string;
+}
+
+/**
+ * Drop every node of a hidden kind, bridging the ranked chains that ran
+ * through them (problem → hidden task → finding reads problem → finding), so
+ * the survivors keep their depth instead of collapsing into one orphan row.
+ */
+export const hideKinds = (
+ nodes: GoalGraphNode[],
+ edges: LayoutEdge[],
+ hidden: ReadonlySet<GoalNodeKind>,
+): { bridges: GraphBridge[]; visibleIds: Set<string> } => {
+ const visibleIds = new Set<string>();
+ const hiddenIds = new Set<string>();
+ for (const node of nodes) (hidden.has(node.kind) ? hiddenIds : visibleIds).add(node.id);
+
+ const bridges: GraphBridge[] = [];
+ if (hiddenIds.size === 0) return { bridges, visibleIds };
+
+ const out = new Map<string, string[]>();
+ // A bridge that mirrors a surviving direct edge would draw twice — seed the
+ // dedupe set with the ranked pairs that stay on the map.
+ const seen = new Set<string>();
+ for (const edge of edges) {
+ const link = rankDirection(edge);
+ if (!link) continue;
+ const inScope = (id: string) => visibleIds.has(id) || hiddenIds.has(id);
+ if (!inScope(link[0]) || !inScope(link[1])) continue;
+ out.set(link[0], [...(out.get(link[0]) ?? []), link[1]]);
+ if (visibleIds.has(link[0]) && visibleIds.has(link[1])) seen.add(`${link[0]}→${link[1]}`);
+ }
+
+ for (const start of visibleIds) {
+ const stack = (out.get(start) ?? []).filter((id) => hiddenIds.has(id));
+ const visited = new Set(stack);
+ while (stack.length > 0) {
+ const current = stack.pop()!;
+ for (const next of out.get(current) ?? []) {
+ if (visibleIds.has(next)) {
+ const key = `${start}→${next}`;
+ if (next !== start && !seen.has(key)) {
+ seen.add(key);
+ bridges.push({ sourceNodeId: start, targetNodeId: next });
+ }
+ } else if (!visited.has(next)) {
+ visited.add(next);
+ stack.push(next);
+ }
+ }
+ }
+ }
+ return { bridges, visibleIds };
+};
+
export const layoutGraph = (
nodes: GoalGraphNode[],
- edges: GoalGraphEdge[],
+ edges: LayoutEdge[],
): Record<string, LayoutBox> => {
const index = new Map(nodes.map((node, i) => [node.id, i]));
const links = edges.map(rankDirection).filter((link): link is [string, string] => {