Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

7.6 KB
Raw Blame
'use client';

/**
 * assistant-ui's tool-group element: the collapsible that wraps a run of
 * consecutive tool calls behind a single "N tool calls" trigger.
 *
 * Vendored from the assistant-ui `tool-group` / `elements-tool-group`
 * registry items (https://r.assistant-ui.com/styles/base-nova/tool-group.json,
 * .../elements-tool-group.json — `elements/tool-group.aui.tsx` upstream).
 * Changes from upstream:
 * - `cn` import path and Radix collapsible from `../ui/collapsible` (this
 *   app's, not shadcn's).
 * - `data-variant="outline-solid"` default (this app's Tailwind v4 token set
 *   renames the `outline` utility).
 * - `ToolGroupTrigger` takes an optional `label` prop that replaces the
 *   default "N tool calls" text (used by `ActivityGroup` for a mixed
 *   reasoning + tool run) and renders a shimmer duplicate of the label while
 *   `active`, matching `tool-fallback`'s running-label treatment.
 * - The default "N tool calls" text is translated through `useT()`
 *   (`chat.tools.callOne` / `chat.tools.callOther`).
 */
import { cn } from '@/components/assistant-ui/lib/utils';
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/assistant-ui/ui/collapsible';
import { useT } from '@/lib/i18n/I18nContext';
import { useScrollLock } from '@assistant-ui/react';
import { cva, type VariantProps } from 'class-variance-authority';
import { ChevronDownIcon, LoaderIcon } from 'lucide-react';
import { useCallback, useRef, useState } from 'react';

const ANIMATION_DURATION = 200;

const toolGroupVariants = cva('aui-tool-group-root group/tool-group w-full', {
  variants: {
    variant: {
      outline: 'rounded-lg border py-3',
      ghost: '',
      muted: 'border-muted-foreground/30 bg-muted/30 rounded-lg border py-3',
    },
  },
  defaultVariants: { variant: 'outline' },
});

export type ToolGroupRootProps = Omit<
  React.ComponentProps<typeof Collapsible>,
  'open' | 'onOpenChange'
> &
  VariantProps<typeof toolGroupVariants> & {
    open?: boolean;
    onOpenChange?: (open: boolean) => void;
    defaultOpen?: boolean;
  };

function ToolGroupRoot({
  className,
  variant,
  open: controlledOpen,
  onOpenChange: controlledOnOpenChange,
  defaultOpen = false,
  children,
  ...props
}: ToolGroupRootProps) {
  const collapsibleRef = useRef<HTMLDivElement>(null);
  const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
  const lockScroll = useScrollLock(collapsibleRef, ANIMATION_DURATION);

  const isControlled = controlledOpen !== undefined;
  const isOpen = isControlled ? controlledOpen : uncontrolledOpen;

  const handleOpenChange = useCallback(
    (open: boolean) => {
      lockScroll();
      if (!isControlled) {
        setUncontrolledOpen(open);
      }
      controlledOnOpenChange?.(open);
    },
    [lockScroll, isControlled, controlledOnOpenChange]
  );

  return (
    <Collapsible
      ref={collapsibleRef}
      data-slot="tool-group-root"
      data-variant={variant ?? 'outline-solid'}
      open={isOpen}
      onOpenChange={handleOpenChange}
      className={cn(toolGroupVariants({ variant }), 'group/tool-group-root', className)}
      style={{ '--animation-duration': `${ANIMATION_DURATION}ms` } as React.CSSProperties}
      {...props}>
      {children}
    </Collapsible>
  );
}

function ToolGroupTrigger({
  count,
  label: labelOverride,
  active = false,
  className,
  ...props
}: React.ComponentProps<typeof CollapsibleTrigger> & {
  count: number;
  /** Replaces the default "N tool calls" text, e.g. for a mixed reasoning group. */
  label?: string;
  active?: boolean;
}) {
  const { t } = useT();
  const label =
    labelOverride ??
    t(count === 1 ? 'chat.tools.callOne' : 'chat.tools.callOther').replace(
      '{count}',
      String(count)
    );

  return (
    <CollapsibleTrigger
      data-slot="tool-group-trigger"
      className={cn(
        'aui-tool-group-trigger group/trigger flex origin-left items-center gap-2 text-sm transition-[color,scale] active:scale-[0.98]',
        'group-data-[variant=ghost]/tool-group-root:text-muted-foreground group-data-[variant=ghost]/tool-group-root:hover:text-foreground group-data-[variant=ghost]/tool-group-root:py-1.5',
        'group-data-[variant=outline]/tool-group-root:w-full group-data-[variant=outline]/tool-group-root:px-4',
        'group-data-[variant=muted]/tool-group-root:w-full group-data-[variant=muted]/tool-group-root:px-4',
        className
      )}
      {...props}>
      {active && (
        <LoaderIcon
          data-slot="tool-group-trigger-loader"
          className="aui-tool-group-trigger-loader size-3 shrink-0 animate-spin [animation-duration:0.6s]"
        />
      )}
      <span
        data-slot="tool-group-trigger-label"
        className={cn(
          'aui-tool-group-trigger-label-wrapper relative inline-block text-start leading-none font-medium',
          'group-data-[variant=ghost]/tool-group-root:font-normal',
          'group-data-[variant=outline]/tool-group-root:grow',
          'group-data-[variant=muted]/tool-group-root:grow'
        )}>
        <span className="text-xs">{label}</span>
        {active && (
          <span
            aria-hidden
            data-slot="tool-group-trigger-shimmer"
            className="aui-tool-group-trigger-shimmer shimmer pointer-events-none absolute inset-0 text-xs motion-reduce:animate-none">
            {label}
          </span>
        )}
      </span>
      <ChevronDownIcon
        data-slot="tool-group-trigger-chevron"
        className={cn(
          'aui-tool-group-trigger-chevron size-3 shrink-0',
          'transition-transform duration-(--animation-duration) ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none',
          '-rotate-90',
          'group-data-open/trigger:rotate-0',
          'group-data-panel-open/trigger:rotate-0'
        )}
      />
    </CollapsibleTrigger>
  );
}

function ToolGroupContent({
  className,
  children,
  ...props
}: React.ComponentProps<typeof CollapsibleContent>) {
  return (
    <CollapsibleContent
      data-slot="tool-group-content"
      className={cn(
        'aui-tool-group-content relative overflow-hidden text-sm outline-hidden',
        'group/collapsible-content ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:animate-none',
        'data-closed:animate-collapsible-up',
        'data-open:animate-collapsible-down',
        'data-closed:fill-mode-forwards',
        'data-closed:pointer-events-none',
        '[--tw-duration:var(--animation-duration)]',
        className
      )}
      {...props}>
      <div
        className={cn(
          'mt-2 flex flex-col gap-2',
          'group-data-[variant=ghost]/tool-group-root:mt-1 group-data-[variant=ghost]/tool-group-root:gap-1',
          'group-data-[variant=outline]/tool-group-root:mt-3 group-data-[variant=outline]/tool-group-root:border-t group-data-[variant=outline]/tool-group-root:px-4 group-data-[variant=outline]/tool-group-root:pt-3',
          'group-data-[variant=muted]/tool-group-root:mt-3 group-data-[variant=muted]/tool-group-root:border-t group-data-[variant=muted]/tool-group-root:px-4 group-data-[variant=muted]/tool-group-root:pt-3',
          '[&>*]:animate-in [&>*]:fade-in-0 [&>*]:blur-in-[2px] [&>*]:slide-in-from-top-1 [&>*]:animation-duration-(--animation-duration) *:ease-[cubic-bezier(0.32,0.72,0,1)]',
          'motion-reduce:*:animate-none',
          '[&>*:nth-child(2)]:[animation-delay:40ms]',
          '[&>*:nth-child(3)]:[animation-delay:80ms]',
          '[&>*:nth-child(4)]:[animation-delay:120ms]',
          '[&>*:nth-child(n+5)]:[animation-delay:160ms]'
        )}>
        {children}
      </div>
    </CollapsibleContent>
  );
}

export { ToolGroupRoot, ToolGroupTrigger, ToolGroupContent };