← All proposals

Context: AgentTree

A tree of agent cards: the lead on top, its sub-agents side by side below, their helpers under them, joined by thin connectors.

Net-new componentOpen in Storybook

proposals/AgentTree/AgentTree.stories.tsx238 lines · View on GitHub
import { useEffect, useRef, useState } from 'react';

import { Button } from '@pantheon-systems/pds-toolkit-react';
import { Meta, StoryObj } from '@storybook/react-vite';

import { AgentTree, AgentTreeAgent, AgentTreeSteer } from './AgentTree';
import {
	applyHandoff,
	HANDOFFS,
	makeAllStates,
	makeContextWarning,
	makeCrew,
	update,
} from './agent-tree-story-shared';

import './agent-tree-story.css';

const meta: Meta<typeof AgentTree> = {
	tags: ['new-pattern', 'in-progress'],
	title: 'Component Proposals/Agent Tree',
	component: AgentTree,
	parameters: {
		layout: 'padded',
		docs: {
			description: {
				component:
					'**New pattern:** not in PDS v2 today. A lead agent and its sub-agents as one live tree of cards, so every agent stays on screen for the whole run. Each card shows the status, what the agent does now, its context window, its tools and the last thing it was handed. A card opens its details, with steering. A handoff runs as a light along the connectors. First build from a reference, not ready for review.',
			},
		},
	},
	argTypes: {
		className: { table: { category: 'Base attributes' } },
		formatCost: { table: { category: 'Content' } },
		formatDuration: { table: { category: 'Content' } },
		handoffs: { control: 'object', table: { category: 'Content' } },
		heading: { control: 'text', table: { category: 'Content' } },
		isAnimated: {
			control: 'boolean',
			table: { category: 'Component configuration' },
		},
		labelStrings: { control: 'object', table: { category: 'Content' } },
		onAgentSelect: { table: { category: 'Functions' } },
		onHandoffArrive: { table: { category: 'Functions' } },
		onProjectChange: { table: { category: 'Functions' } },
		onSteer: { table: { category: 'Functions' } },
		project: { control: 'text', table: { category: 'Content' } },
		projects: { control: 'object', table: { category: 'Content' } },
		root: { control: 'object', table: { category: 'Content' } },
	},
	args: { heading: 'Checkout fix', isAnimated: true, root: makeCrew() },
};

export default meta;
type Story = StoryObj<typeof AgentTree>;

// The consumer owns what steering does, so the story keeps the tree in state
// and moves the agent to its new status.
const nextStatus: Partial<Record<AgentTreeSteer, AgentTreeAgent['status']>> = {
	approve: 'active',
	decline: 'idle',
	pause: 'paused',
	resume: 'active',
	retry: 'active',
	stop: 'idle',
};

// `withHandoffs` adds buttons for the scripted run: each handoff's light runs,
// and when it arrives the receiver starts working and the sender stops. "Next
// handoff" plays one; "Play demo" plays the whole run, each handoff starting a
// moment after the last one has landed.
const PAUSE_BEFORE_FIRST = 600;
const PAUSE_BETWEEN = 1100;

const Interactive = ({
	withHandoffs = false,
	...args
}: React.ComponentProps<typeof AgentTree> & { withHandoffs?: boolean }) => {
	const [root, setRoot] = useState(args.root);
	const [count, setCount] = useState(0);
	const [run, setRun] = useState(0);
	const [isPlaying, setIsPlaying] = useState(false);
	const playing = useRef(false);
	const timer = useRef<number | undefined>(undefined);

	const stop = () => {
		playing.current = false;
		setIsPlaying(false);
		window.clearTimeout(timer.current);
	};
	const reset = () => {
		stop();
		setCount(0);
		setRoot(args.root);
		setRun((n) => n + 1);
	};
	const play = () => {
		// Pressed at the end: start again from the beginning.
		if (count >= HANDOFFS.length) {
			setCount(0);
			setRoot(args.root);
			setRun((n) => n + 1);
		}
		playing.current = true;
		setIsPlaying(true);
		timer.current = window.setTimeout(
			() => setCount((n) => n + 1),
			PAUSE_BEFORE_FIRST,
		);
	};
	// Stop the timer if the story goes away.
	useEffect(() => () => window.clearTimeout(timer.current), []);

	const onArrive = (handoffId: string) => {
		setRoot((r) => applyHandoff(r, handoffId));
		if (!playing.current) return;
		if (handoffId === HANDOFFS[HANDOFFS.length - 1].id) {
			playing.current = false;
			setIsPlaying(false);
			return;
		}
		timer.current = window.setTimeout(
			() => setCount((n) => n + 1),
			PAUSE_BETWEEN,
		);
	};

	return (
		<div className='agent-tree-story'>
			{withHandoffs && (
				<div className='agent-tree-story__toolbar'>
					<Button
						label={isPlaying ? 'Stop demo' : 'Play demo'}
						onClick={isPlaying ? stop : play}
						size='xs'
						variant='primary'
					/>
					<Button
						disabled={isPlaying || count >= HANDOFFS.length}
						label={`Next handoff (${count}/${HANDOFFS.length})`}
						onClick={() => setCount((n) => n + 1)}
						size='xs'
						variant='secondary'
					/>
					<Button
						disabled={count === 0 && !isPlaying}
						label='Reset'
						onClick={reset}
						size='xs'
						variant='secondary'
					/>
				</div>
			)}
			<AgentTree
				{...args}
				handoffs={withHandoffs ? HANDOFFS.slice(0, count) : undefined}
				key={run}
				onHandoffArrive={(handoff) => onArrive(handoff.id)}
				onSteer={(agent, action, message) => {
					const status = nextStatus[action];
					setRoot((r) =>
						update(r, agent.id, {
							...(status ? { status } : {}),
							...(message ? { last: { from: 'You', text: message } } : {}),
						}),
					);
				}}
				root={root}
			/>
		</div>
	);
};

export const Default: Story = {
	render: (args) => <Interactive {...args} withHandoffs />,
};

export const AllStatuses: Story = {
	args: { heading: 'Every status', root: makeAllStates() },
	render: (args) => <Interactive {...args} />,
};

export const ContextWarning: Story = {
	args: { heading: 'Context windows', root: makeContextWarning() },
	render: (args) => <Interactive {...args} />,
};

export const NarrowContainer: Story = {
	name: 'Narrow container (drawer width)',
	render: (args) => (
		<div className='agent-tree-story__narrow'>
			<Interactive {...args} withHandoffs />
		</div>
	),
};

const ProjectsStory = (args: React.ComponentProps<typeof AgentTree>) => {
	const [project, setProject] = useState('checkout');
	const crews: Record<string, AgentTreeAgent> = {
		checkout: makeCrew(),
		search: { ...makeAllStates(), name: 'Search lead' },
	};
	return (
		<Interactive
			{...args}
			key={project}
			withHandoffs={project === 'checkout'}
			onProjectChange={setProject}
			project={project}
			projects={[
				{ id: 'checkout', name: 'Checkout fix', needsYou: 1 },
				{ id: 'search', name: 'Search relevance', working: 2 },
				{ id: 'billing', name: 'Billing export' },
			]}
			root={crews[project] ?? crews.checkout}
		/>
	);
};

export const WithProjects: Story = {
	render: (args) => <ProjectsStory {...args} />,
};

export const LeadOnly: Story = {
	args: {
		heading: 'Checkout fix',
		root: {
			activity: 'Planning the work',
			context: 0.1,
			contextLimit: 200000,
			id: 'lead',
			model: 'Zappy',
			name: 'Release lead',
			status: 'active',
		},
	},
	render: (args) => <Interactive {...args} />,
};