← 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.tsx712 lines · View on GitHub
import {
	ComponentPropsWithoutRef,
	FocusEvent,
	KeyboardEvent,
	ReactNode,
	useEffect,
	useId,
	useLayoutEffect,
	useRef,
	useState,
} from 'react';

import { Select } from '../Select/Select';
import { AgentTreeCard } from './AgentTreeCard';
import { AgentTreeDetails } from './AgentTreeDetails';
import { AgentTreeLight } from './AgentTreeLight';
import { AgentTreeMessage } from './AgentTreeMessage';
import {
	AgentTreeAgent,
	AgentTreeHandoff,
	AgentTreeLabelStrings,
	AgentTreeProject,
	AgentTreeSteer,
	defaultFormatCost,
	defaultFormatDuration,
	defaultLabelStrings,
	depthOf,
	fill,
	prefersReducedMotion,
	walk,
} from './agent-tree-utils';

import './agent-tree.css';

export type {
	AgentTreeAgent,
	AgentTreeHandoff,
	AgentTreeLabelStrings,
	AgentTreeProject,
	AgentTreeStatus,
	AgentTreeSteer,
	AgentTreeTool,
} from './agent-tree-utils';

export interface AgentTreeProps extends ComponentPropsWithoutRef<'section'> {
	/**
	 * Additional class names.
	 */
	className?: string;
	/**
	 * Formats every cost. Defaults to dollars, for example "$0.42".
	 */
	formatCost?: (amount: number) => string;
	/**
	 * Formats how long an agent ran. Defaults to "2m 05s".
	 */
	formatDuration?: (milliseconds: number) => string;
	/**
	 * Work handed from one agent to another. Each new id runs a light along the
	 * connectors; the handoffs there on first render do not run.
	 */
	handoffs?: AgentTreeHandoff[];
	/**
	 * The name of the view, top left. A project switcher takes its place when
	 * `projects` is set.
	 */
	heading?: string;
	/**
	 * Slide the AI gradient around the border of the working agents and along
	 * the connectors between them, as the animated Panel does. Off for reduced
	 * motion.
	 */
	isAnimated?: boolean;
	/**
	 * Translatable strings: statuses, buttons, details and announcements.
	 */
	labelStrings?: AgentTreeLabelStrings;
	/**
	 * Called on a click or Enter on a card. The card also opens its details.
	 */
	onAgentSelect?: (agent: AgentTreeAgent) => void;
	/**
	 * Called when a handoff reaches its receiver: when the light arrives, or
	 * at once for reduced motion. This is the moment to change the agents' data:
	 * the receiver starts working and the sender stops, so the border and the
	 * connector turn AI gradient as the work lands, not before.
	 */
	onHandoffArrive?: (handoff: AgentTreeHandoff) => void;
	/**
	 * Called when another project is chosen in the switcher.
	 */
	onProjectChange?: (id: string) => void;
	/**
	 * Called with what the person tells an agent from its details: pause,
	 * resume, stop, retry, a message, or approve or decline when it needs them.
	 * Without it the details have no steering row.
	 */
	onSteer?: (
		agent: AgentTreeAgent,
		action: AgentTreeSteer,
		message?: string,
	) => void;
	/**
	 * Id of the project shown. Pass its agents as `root`.
	 */
	project?: string;
	/**
	 * Projects to switch between, in a switcher top left.
	 */
	projects?: AgentTreeProject[];
	/**
	 * The lead, with its sub-agents as `children` and their helpers as theirs.
	 */
	root: AgentTreeAgent;
}

interface Link {
	d: string;
	dot: [number, number];
	id: string;
	// Both ends are working: the connector is the AI gradient.
	isActive: boolean;
}

interface Pulse {
	handoff: AgentTreeHandoff;
	hops: { back: boolean; id: string }[];
	key: string;
	to: string;
}

// Geometry of the connectors, in SVG user units: the radius of a rounded
// corner and of the hollow dot where a connector leaves its parent.
const CORNER = 8;
const DOT_RADIUS = 3;
// Line width in SVG user units (the CSS `--pds-border-width-default`).
const LINE_WIDTH = 1;

/**
 * AgentTree UI component. A lead agent and its sub-agents as one live tree of
 * cards, so every agent stays on screen for the whole run. Wide containers
 * lay the sub-agents out side by side; narrow ones indent every level.
 */
export const AgentTree = ({
	className,
	formatCost = defaultFormatCost,
	formatDuration = defaultFormatDuration,
	handoffs = [],
	heading,
	isAnimated = false,
	labelStrings = defaultLabelStrings,
	onAgentSelect,
	onHandoffArrive,
	onProjectChange,
	onSteer,
	project,
	projects,
	root,
	...props
}: AgentTreeProps) => {
	const baseClass = 'pds-agent-tree';
	const uid = useId();
	const boxRef = useRef<HTMLDivElement>(null);
	const probeRef = useRef<HTMLSpanElement>(null);
	const nodes = useRef(new Map<string, HTMLDivElement>());
	const items = useRef(new Map<string, HTMLDivElement>());

	const all = walk(root);
	const kids = root.children ?? [];
	const parentOf = new Map<string, string>();
	all.forEach((agent) =>
		(agent.children ?? []).forEach((child) => parentOf.set(child.id, agent.id)),
	);
	const nameOf = (id: string) => all.find((agent) => agent.id === id)?.name;

	/* ----- Wide or narrow ----- */
	const [layout, setLayout] = useState<'narrow' | 'wide'>('wide');
	const isWide = layout === 'wide';

	/* ----- The connectors, measured from the cards ----- */
	const [links, setLinks] = useState<Link[]>([]);
	const [size, setSize] = useState({ h: 0, w: 0 });
	const drawn = useRef('');

	const measure = () => {
		const box = boxRef.current;
		if (!box) return;
		const outer = box.getBoundingClientRect();
		const scale = box.offsetWidth ? outer.width / box.offsetWidth : 1;
		const at = (el: Element) => {
			const r = el.getBoundingClientRect();
			return {
				h: r.height / scale,
				w: r.width / scale,
				x: (r.left - outer.left) / scale,
				y: (r.top - outer.top) / scale,
			};
		};
		// Connectors leave from under the avatar and enter beside it.
		const avatarCenter = (node: HTMLElement) => {
			const a = at(node.querySelector(`.${baseClass}__avatar`) ?? node);
			return { x: a.x + a.w / 2, y: a.y + a.h / 2 };
		};

		const next: Link[] = [];
		const row = box.querySelector(`:scope > .${baseClass}__level`);
		const rowTop = row ? at(row).y : null;

		const visit = (agent: AgentTreeAgent, depth: number) => {
			const parentEl = nodes.current.get(agent.id);
			for (const child of agent.children ?? []) {
				const childEl = nodes.current.get(child.id);
				if (parentEl && childEl) {
					const p = at(parentEl);
					const q = at(childEl);
					const id = `${agent.id}>${child.id}`;
					const active = agent.status === 'active' && child.status === 'active';
					if (isWide && depth === 0) {
						// Down from the lead, along a bar, and into each card, both
						// bends rounded.
						const x1 = p.x + p.w / 2;
						const y1 = p.y + p.h;
						const x2 = q.x + q.w / 2;
						const y2 = q.y;
						const mid = Math.round(y1 + ((rowTop ?? y2) - y1) / 2);
						const dx = x2 - x1;
						const sign = Math.sign(dx);
						const r = Math.max(
							0,
							Math.min(CORNER, Math.abs(dx) / 2, (y2 - mid) / 2),
						);
						const r1 = Math.max(
							0,
							Math.min(CORNER, Math.abs(dx) / 2 - r, (mid - y1) / 2),
						);
						const d =
							Math.abs(dx) < 12
								? `M${x1} ${y1}V${y2}`
								: `M${x1} ${y1}V${mid - r1}Q${x1} ${mid} ${x1 + sign * r1} ${mid}H${x2 - sign * r}Q${x2} ${mid} ${x2} ${mid + r}V${y2}`;
						next.push({ d, dot: [x1, y1], id, isActive: active });
					} else {
						// Hanging below: down from under the parent's avatar, then into
						// the side of the card.
						const x1 = avatarCenter(parentEl).x;
						const y1 = p.y + p.h;
						const x2 = q.x;
						const y2 = avatarCenter(childEl).y;
						const r = Math.max(
							0,
							Math.min(CORNER, (x2 - x1) / 2, (y2 - y1) / 2),
						);
						const d =
							x2 - x1 < 2
								? `M${x1} ${y1}V${q.y}`
								: `M${x1} ${y1}V${y2 - r}Q${x1} ${y2} ${x1 + r} ${y2}H${x2}`;
						next.push({ d, dot: [x1, y1], id, isActive: active });
					}
				}
				visit(child, depth + 1);
			}
		};
		visit(root, 0);

		const ends = [...nodes.current.values()].map(at);
		const w = Math.ceil(
			Math.max(box.clientWidth, ...ends.map((e) => e.x + e.w)),
		);
		const h = Math.ceil(
			Math.max(box.clientHeight, ...ends.map((e) => e.y + e.h)),
		);
		const key = JSON.stringify([next, w, h]);
		if (key === drawn.current) return;
		drawn.current = key;
		setLinks(next);
		setSize({ h, w });
	};
	// The observer and the effects below always call the latest measure.
	const latest = useRef(measure);
	latest.current = measure;
	const rootRef = useRef(root);
	rootRef.current = root;

	useLayoutEffect(() => latest.current());
	useLayoutEffect(() => {
		const box = boxRef.current;
		if (!box) return;
		const observer = new ResizeObserver(() => {
			// The card, the indent and the gap are measured from a hidden probe,
			// so the tokens stay the one source of the sizes.
			const probe = probeRef.current;
			const [card, indent, gap] = probe
				? ([...probe.children] as HTMLElement[]).map((el) => el.offsetWidth)
				: [0, 0, 0];
			const level = rootRef.current.children ?? [];
			const needed =
				level.reduce(
					(sum, child) => sum + card + indent * Math.max(1, depthOf(child)),
					0,
				) +
				Math.max(0, level.length - 1) * gap;
			setLayout(!card || box.offsetWidth >= needed ? 'wide' : 'narrow');
			latest.current();
		});
		observer.observe(box);
		document.fonts?.ready.then(() => latest.current());
		// The cards scale in when they mount, and a scaled card reports shifted
		// positions, so the connectors are measured again once an animation ends.
		const measureAgain = () => latest.current();
		box.addEventListener('animationend', measureAgain);
		return () => {
			observer.disconnect();
			box.removeEventListener('animationend', measureAgain);
		};
	}, []);

	/* ----- Handoffs: a light along the connectors, up to where the two meet, then down ----- */
	const seen = useRef<Set<string> | null>(null);
	const shownProject = useRef(project);
	const [pulses, setPulses] = useState<Pulse[]>([]);
	const [arrivals, setArrivals] = useState<Record<string, number>>({});
	const [announcement, setAnnouncement] = useState('');

	useEffect(() => {
		// A new project starts clean: what was handed before it shows does not
		// run again.
		if (!seen.current || shownProject.current !== project) {
			shownProject.current = project;
			seen.current = new Set(handoffs.map((h) => h.id));
			setPulses([]);
			setArrivals({});
			return;
		}
		const fresh = handoffs.filter((h) => !seen.current?.has(h.id));
		if (!fresh.length) return;
		fresh.forEach((h) => seen.current?.add(h.id));

		const chain = (id: string) => {
			const list = [id];
			for (let p = parentOf.get(id); p; p = parentOf.get(p)) list.push(p);
			return list;
		};
		const added: Pulse[] = [];
		for (const h of fresh) {
			if (!nameOf(h.from) || !nameOf(h.to)) continue;
			const up = chain(h.from);
			const down = chain(h.to);
			const meet = up.find((id) => down.includes(id)) ?? root.id;
			const hops: Pulse['hops'] = [];
			for (let i = 0; up[i] !== meet; i++) {
				hops.push({ back: true, id: `${up[i + 1]}>${up[i]}` });
			}
			const downPath = down.slice(0, down.indexOf(meet)).reverse();
			let from = meet;
			for (const id of downPath) {
				hops.push({ back: false, id: `${from}>${id}` });
				from = id;
			}
			added.push({ handoff: h, hops, key: h.id, to: h.to });
		}
		const last = fresh[fresh.length - 1];
		setAnnouncement(
			fill(
				last.label
					? labelStrings.handoffSaidWithLabel
					: labelStrings.handoffSaid,
				{
					from: nameOf(last.from),
					label: last.label,
					to: nameOf(last.to),
				},
			),
		);
		if (prefersReducedMotion()) {
			// No light to wait for: the handoff has arrived.
			added.forEach((pulse) => onHandoffArrive?.(pulse.handoff));
			return;
		}
		setPulses((list) => [...list, ...added]);
		// Only a new handoff list or project starts a run.
	}, [handoffs, project]);

	const arrived = (pulse: Pulse) => {
		setArrivals((current) => ({
			...current,
			[pulse.to]: (current[pulse.to] ?? 0) + 1,
		}));
		onHandoffArrive?.(pulse.handoff);
	};
	const finished = (pulse: Pulse) =>
		setPulses((list) => list.filter((p) => p.key !== pulse.key));

	/* ----- Details: a click on a card opens what else there is to know, inside it ----- */
	const [openId, setOpenId] = useState<string | null>(null);
	const [messageId, setMessageId] = useState<string | null>(null);
	const messageTrigger = useRef<HTMLElement | null>(null);
	const messageAgent = messageId
		? all.find((agent) => agent.id === messageId)
		: undefined;

	const pick = (agent: AgentTreeAgent) => {
		onAgentSelect?.(agent);
		setOpenId((current) => (current === agent.id ? null : agent.id));
	};
	const close = () => {
		const id = openId;
		setOpenId(null);
		if (id) items.current.get(id)?.focus();
	};
	useEffect(() => {
		setOpenId(null);
		setMessageId(null);
	}, [project]);

	/* ----- Keyboard: one tab stop; the arrows walk the cards like a tree ----- */
	const [focusId, setFocusId] = useState(root.id);
	const current = all.some((agent) => agent.id === focusId) ? focusId : root.id;
	const goTo = (id: string | undefined) => {
		if (!id) return;
		setFocusId(id);
		items.current.get(id)?.focus();
	};
	const onKey = (
		event: KeyboardEvent<HTMLDivElement>,
		agent: AgentTreeAgent,
	) => {
		if (event.target !== event.currentTarget) return;
		const index = all.findIndex((a) => a.id === agent.id);
		if (event.key === 'ArrowDown') goTo(all[index + 1]?.id);
		else if (event.key === 'ArrowUp') goTo(all[index - 1]?.id);
		else if (event.key === 'ArrowRight') goTo(agent.children?.[0]?.id);
		else if (event.key === 'ArrowLeft') goTo(parentOf.get(agent.id));
		else if (event.key === 'Home') goTo(all[0].id);
		else if (event.key === 'End') goTo(all[all.length - 1].id);
		else if (event.key === 'Enter' || event.key === ' ') pick(agent);
		else if (event.key === 'Escape' && openId) close();
		else return;
		event.preventDefault();
	};

	/* ----- Steering announcements ----- */
	const steer = (
		agent: AgentTreeAgent,
		action: AgentTreeSteer,
		message?: string,
	) => {
		onSteer?.(agent, action, message);
		const said: Record<AgentTreeSteer, string> = {
			approve: labelStrings.saidApprove,
			decline: labelStrings.saidDecline,
			message: labelStrings.saidMessage,
			pause: labelStrings.saidPause,
			resume: labelStrings.saidResume,
			retry: labelStrings.saidRetry,
			stop: labelStrings.saidStop,
		};
		setAnnouncement(fill(said[action], { message, name: agent.name }));
	};

	/* ----- One agent, and the ones hanging under it ----- */
	const card = (
		agent: AgentTreeAgent,
		depth: number,
		position: number,
		setSize: number,
	) => (
		<AgentTreeCard
			agent={agent}
			arrival={arrivals[agent.id]}
			depth={depth}
			formatDuration={formatDuration}
			isAnimated={isAnimated}
			detailsId={`${uid}-${agent.id}-details`}
			isCurrent={agent.id === current}
			isOpen={openId === agent.id}
			labelStrings={labelStrings}
			onFocus={(event: FocusEvent<HTMLDivElement>) => {
				if (event.target === event.currentTarget) setFocusId(agent.id);
			}}
			onKeyDown={(event) => onKey(event, agent)}
			onPick={() => pick(agent)}
			position={position}
			ref={(el) => {
				if (el) nodes.current.set(agent.id, el);
				else nodes.current.delete(agent.id);
			}}
			setSize={setSize}
			summaryRef={(el) => {
				if (el) items.current.set(agent.id, el);
				else items.current.delete(agent.id);
			}}
		>
			{openId === agent.id && (
				<AgentTreeDetails
					agent={agent}
					formatCost={formatCost}
					formatDuration={formatDuration}
					id={`${uid}-${agent.id}-details`}
					labelStrings={labelStrings}
					onClose={close}
					onMessage={(event) => {
						messageTrigger.current = event.currentTarget;
						setMessageId((current) => (current === agent.id ? null : agent.id));
					}}
					onSteer={onSteer ? (action) => steer(agent, action) : undefined}
				/>
			)}
		</AgentTreeCard>
	);
	const hang = (
		agent: AgentTreeAgent,
		depth: number,
		position: number,
		setSize: number,
	): ReactNode => (
		<div
			className={`${baseClass}__hang`}
			data-depth={depth === 1 ? Math.max(1, depthOf(agent)) : undefined}
			key={agent.id}
		>
			{card(agent, depth, position, setSize)}
			{!!agent.children?.length && (
				<div className={`${baseClass}__below`}>
					{agent.children.map((child, i) =>
						hang(child, depth + 1, i + 1, agent.children?.length ?? 1),
					)}
				</div>
			)}
		</div>
	);

	const byLink = new Map(links.map((link) => [link.id, link]));
	// Connectors that leave the same point share one dot; it is the gradient if
	// any of them is.
	const dots = new Map<string, { at: [number, number]; isActive: boolean }>();
	for (const link of links) {
		const key = link.dot.join(',');
		dots.set(key, {
			at: link.dot,
			isActive: (dots.get(key)?.isActive ?? false) || link.isActive,
		});
	}

	// The connectors between two working agents are an AI-gradient background
	// seen through this mask, because an SVG stroke cannot take a CSS gradient
	// token. The gradient is the token, not a copy of its colors.
	const maskSvg =
		`<svg xmlns='http://www.w3.org/2000/svg' width='${size.w}' height='${size.h}'>` +
		links
			.filter((link) => link.isActive)
			.map(
				(link) =>
					`<path d='${link.d}' fill='none' stroke='black' stroke-linecap='round' stroke-width='${LINE_WIDTH}'/>`,
			)
			.join('') +
		[...dots.values()]
			.filter((dot) => dot.isActive)
			.map(
				(dot) =>
					`<circle cx='${dot.at[0]}' cy='${dot.at[1]}' r='${DOT_RADIUS}' fill='none' stroke='black' stroke-width='${LINE_WIDTH}'/>`,
			)
			.join('') +
		'</svg>';
	const linesMask = `url("data:image/svg+xml,${encodeURIComponent(maskSvg)}")`;

	const projectOptions = (projects ?? []).map((p) => {
		const meta = p.needsYou
			? fill(labelStrings.projectNeedsYou, { count: p.needsYou })
			: p.working
				? fill(labelStrings.projectWorking, { count: p.working })
				: null;
		return { label: meta ? `${p.name} · ${meta}` : p.name, value: p.id };
	});

	return (
		<section
			aria-label={heading}
			className={[baseClass, className].filter(Boolean).join(' ')}
			data-animated={isAnimated ? '' : undefined}
			data-layout={layout}
			{...props}
		>
			{projects?.length ? (
				<header className={`${baseClass}__bar`}>
					<Select
						className={`${baseClass}__projects`}
						id={`${uid}-project`}
						label={labelStrings.projects}
						onOptionSelect={(option) => onProjectChange?.(option.value)}
						options={projectOptions}
						value={project ?? projects[0].id}
						variant='bare'
					/>
				</header>
			) : null}

			<div
				aria-label={heading ?? labelStrings.agent}
				className={`${baseClass}__tree`}
				ref={boxRef}
				role='tree'
			>
				<span
					aria-hidden='true'
					className={`${baseClass}__probe`}
					ref={probeRef}
				>
					<span className={`${baseClass}__probe-card`} />
					<span className={`${baseClass}__probe-indent`} />
					<span className={`${baseClass}__probe-gap`} />
				</span>
				<svg
					aria-hidden='true'
					className={`${baseClass}__links`}
					height={size.h}
					width={size.w}
				>
					{links.map((link) => (
						<path
							className={`${baseClass}__link`}
							d={link.d}
							key={`${project ?? ''}:${link.id}`}
							pathLength={1}
						/>
					))}
					{[...dots].map(([key, dot]) => (
						<circle
							className={`${baseClass}__ring`}
							cx={dot.at[0]}
							cy={dot.at[1]}
							key={key}
							r={DOT_RADIUS}
						/>
					))}
				</svg>
				<div
					aria-hidden='true'
					className={`${baseClass}__lines`}
					key={`lines-${project ?? ''}`}
					style={{
						height: size.h,
						maskImage: linesMask,
						WebkitMaskImage: linesMask,
						width: size.w,
					}}
				/>
				<svg
					aria-hidden='true'
					className={`${baseClass}__links`}
					height={size.h}
					width={size.w}
				>
					{pulses.map((pulse) => (
						<AgentTreeLight
							hops={pulse.hops.map((hop) => ({
								back: hop.back,
								d: byLink.get(hop.id)?.d,
							}))}
							key={pulse.key}
							onArrive={() => arrived(pulse)}
							onDone={() => finished(pulse)}
						/>
					))}
				</svg>
				<svg
					aria-hidden='true'
					className={`${baseClass}__links ${baseClass}__dots`}
					height={size.h}
					width={size.w}
				>
					{[...dots].map(([key, dot]) => (
						<circle
							className={`${baseClass}__dot`}
							cx={dot.at[0]}
							cy={dot.at[1]}
							key={key}
							r={DOT_RADIUS - LINE_WIDTH / 2}
						/>
					))}
				</svg>

				<div className={`${baseClass}__root`} key={`root-${project ?? ''}`}>
					{card(root, 0, 1, 1)}
				</div>
				{kids.length > 0 && (
					<div className={`${baseClass}__level`} key={`level-${project ?? ''}`}>
						{kids.map((kid, i) => hang(kid, 1, i + 1, kids.length))}
					</div>
				)}
			</div>

			{messageAgent && (
				<AgentTreeMessage
					agent={messageAgent}
					id={`${uid}-message`}
					key={messageAgent.id}
					labelStrings={labelStrings}
					onClose={(returnFocus) => {
						setMessageId(null);
						if (returnFocus) messageTrigger.current?.focus();
					}}
					onSend={(text) => steer(messageAgent, 'message', text)}
					triggerRef={messageTrigger}
				/>
			)}

			<div aria-live='polite' className='visually-hidden'>
				{announcement}
			</div>
		</section>
	);
};