Task
Un paso plegable con estado, para mostrar qué hizo un agente y qué archivos tocó.
Instalación
Copia y pega el siguiente código en tu proyecto.
1'use client';23import { AnimatePresence, motion, useReducedMotion, type Variants } from 'motion/react';4import * as React from 'react';5import { cn } from '../lib/cn';6import {7 ARRIVE,8 AUTO_HEIGHT,9 Arrivals,10 STATUS_IN,11 useArrival,12 useAutoHeight,13 useChanged,14} from '../lib/arrival';15import { collapse, springs, still } from '../lib/motion';16import { useControllableState } from '../lib/use-controllable-state';1718const INSTANT_COLLAPSE: Variants = {19 closed: { height: 0, opacity: 0, transition: still },20 open: { height: 'auto', opacity: 1, transition: still },21};2223type IconProps = React.SVGProps<SVGSVGElement> & {24 size?: number | string;25};2627function ChevronDownIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {28 return (29 <svg30 xmlns="http://www.w3.org/2000/svg"31 width={size}32 height={size}33 viewBox="0 0 24 24"34 fill="none"35 stroke="currentColor"36 strokeWidth={strokeWidth}37 strokeLinecap="round"38 strokeLinejoin="round"39 aria-hidden="true"40 {...props}41 >42 <path d="m6 9 6 6 6-6" />43 </svg>44 );45}4647function CheckIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {48 return (49 <svg50 xmlns="http://www.w3.org/2000/svg"51 width={size}52 height={size}53 viewBox="0 0 24 24"54 fill="none"55 stroke="currentColor"56 strokeWidth={strokeWidth}57 strokeLinecap="round"58 strokeLinejoin="round"59 aria-hidden="true"60 {...props}61 >62 <path d="M20 6 9 17l-5-5" />63 </svg>64 );65}6667function LoaderIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {68 return (69 <svg70 xmlns="http://www.w3.org/2000/svg"71 width={size}72 height={size}73 viewBox="0 0 24 24"74 fill="none"75 stroke="currentColor"76 strokeWidth={strokeWidth}77 strokeLinecap="round"78 strokeLinejoin="round"79 aria-hidden="true"80 {...props}81 >82 <path d="M12 3a9 9 0 1 0 9 9" />83 </svg>84 );85}8687function AlertIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {88 return (89 <svg90 xmlns="http://www.w3.org/2000/svg"91 width={size}92 height={size}93 viewBox="0 0 24 24"94 fill="none"95 stroke="currentColor"96 strokeWidth={strokeWidth}97 strokeLinecap="round"98 strokeLinejoin="round"99 aria-hidden="true"100 {...props}101 >102 <circle cx="12" cy="12" r="9" />103 <path d="M12 8v4" />104 <path d="M12 16h.01" />105 </svg>106 );107}108109function DotIcon({ size = 24, ...props }: IconProps) {110 return (111 <svg112 xmlns="http://www.w3.org/2000/svg"113 width={size}114 height={size}115 viewBox="0 0 24 24"116 fill="currentColor"117 aria-hidden="true"118 {...props}119 >120 <circle cx="12" cy="12" r="4" />121 </svg>122 );123}124125type TaskStatus = 'pending' | 'active' | 'complete' | 'error';126127type TaskStatusLabels = Record<TaskStatus, string>;128129const DEFAULT_STATUS_LABELS: TaskStatusLabels = {130 pending: 'Pending',131 active: 'In progress',132 complete: 'Completed',133 error: 'Failed',134};135136interface TaskContextValue {137 open: boolean;138 setOpen: (open: boolean) => void;139 id: string;140}141142const TaskContext = React.createContext<TaskContextValue | null>(null);143144const useTaskContext = (): TaskContextValue => {145 const context = React.use(TaskContext);146 if (!context) {147 throw new Error('Task components must be used within Task');148 }149 return context;150};151152interface TaskProps extends React.HTMLAttributes<HTMLDivElement> {153 defaultOpen?: boolean;154 open?: boolean;155 onOpenChange?: (open: boolean) => void;156}157158interface TaskTriggerProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {159 title: string;160 status?: TaskStatus;161 statusLabels?: Partial<TaskStatusLabels>;162}163164type TaskContentProps = React.HTMLAttributes<HTMLDivElement>;165type TaskItemProps = React.HTMLAttributes<HTMLDivElement>;166type TaskFileProps = React.HTMLAttributes<HTMLSpanElement>;167168const STATUS_ICON: Record<TaskStatus, React.ComponentType<IconProps>> = {169 pending: DotIcon,170 active: LoaderIcon,171 complete: CheckIcon,172 error: AlertIcon,173};174175const STATUS_TONE: Record<TaskStatus, string> = {176 pending: 'text-muted-foreground',177 active: 'text-foreground',178 complete: 'text-success-text',179 error: 'text-destructive-text',180};181182const TaskRoot = ({183 className,184 defaultOpen = true,185 open: controlledOpen,186 onOpenChange,187 children,188 ref,189 ...props190}: TaskProps & { ref?: React.Ref<HTMLDivElement> }) => {191 const [open, setOpen] = useControllableState({192 value: controlledOpen,193 defaultValue: defaultOpen,194 onChange: onOpenChange,195 });196 const id = React.useId();197198 const value = React.useMemo<TaskContextValue>(() => ({ open, setOpen, id }), [open, setOpen, id]);199200 return (201 <TaskContext value={value}>202 <div203 ref={ref}204 data-state={open ? 'open' : 'closed'}205 className={cn('w-full', className)}206 {...props}207 >208 {children}209 </div>210 </TaskContext>211 );212};213214TaskRoot.displayName = 'Task';215216const TaskTrigger = ({217 className,218 title,219 status = 'complete',220 statusLabels,221 children,222 onClick,223 ref,224 ...props225}: TaskTriggerProps & { ref?: React.Ref<HTMLButtonElement> }) => {226 const { open, setOpen, id } = useTaskContext();227 const shouldReduceMotion = useReducedMotion();228 const StatusIcon = STATUS_ICON[status];229 const statusChanged = useChanged(status);230 const statusLabel = statusLabels?.[status] ?? DEFAULT_STATUS_LABELS[status];231232 return (233 <button234 ref={ref}235 type="button"236 id={`${id}-trigger`}237 aria-expanded={open}238 aria-controls={open ? `${id}-content` : undefined}239 onClick={(event) => {240 setOpen(!open);241 onClick?.(event);242 }}243 className={cn(244 'text-muted-foreground hover:text-foreground focus-visible:ring-ring -my-0.5 flex min-h-6 w-full items-center gap-2 rounded-md text-sm transition-colors focus-visible:ring-2 focus-visible:outline-none pointer-coarse:-my-2 pointer-coarse:min-h-9',245 className,246 )}247 {...props}248 >249 <span250 key={status}251 aria-hidden="true"252 className={cn(253 'flex shrink-0',254 STATUS_TONE[status],255 status === 'active' ? 'motion-safe:animate-spin' : statusChanged && STATUS_IN,256 )}257 >258 <StatusIcon size={14} />259 </span>260 <span className="min-w-0 flex-1 truncate text-start">261 {children ?? title}262 <span className="sr-only">{`, ${statusLabel}`}</span>263 </span>264 <motion.span265 aria-hidden="true"266 className="flex shrink-0"267 animate={shouldReduceMotion ? undefined : { rotate: open ? 180 : 0 }}268 transition={springs.snappy}269 >270 <ChevronDownIcon size={14} />271 </motion.span>272 </button>273 );274};275276TaskTrigger.displayName = 'TaskTrigger';277278const TaskContent = ({279 className,280 children,281 ref,282 ...props283}: TaskContentProps & { ref?: React.Ref<HTMLDivElement> }) => {284 const { open, id } = useTaskContext();285 const shouldReduceMotion = useReducedMotion();286287 const [growRef, growStyle] = useAutoHeight();288289 return (290 <AnimatePresence initial={false}>291 {open && (292 <motion.div293 ref={ref}294 id={`${id}-content`}295 role="region"296 aria-labelledby={`${id}-trigger`}297 variants={shouldReduceMotion ? INSTANT_COLLAPSE : collapse}298 initial="closed"299 animate="open"300 exit="closed"301 className="overflow-hidden"302 >303 <div style={growStyle} className={AUTO_HEIGHT}>304 <div ref={growRef} className="flow-root">305 <Arrivals>306 <div307 className={cn(308 'border-border text-muted-foreground ms-[6px] mt-2 flex flex-col gap-2 border-s ps-4 pt-1 pb-1 text-sm',309 className,310 )}311 {...props}312 >313 {children}314 </div>315 </Arrivals>316 </div>317 </div>318 </motion.div>319 )}320 </AnimatePresence>321 );322};323324TaskContent.displayName = 'TaskContent';325326const TaskItem = ({327 className,328 ref,329 ...props330}: TaskItemProps & { ref?: React.Ref<HTMLDivElement> }) => {331 const arrived = useArrival();332 return (333 <div334 ref={ref}335 className={cn(336 'flex origin-left flex-wrap items-center gap-1.5 leading-relaxed',337 arrived && ARRIVE,338 className,339 )}340 {...props}341 />342 );343};344345TaskItem.displayName = 'TaskItem';346347const TaskFile = ({348 className,349 ref,350 ...props351}: TaskFileProps & { ref?: React.Ref<HTMLSpanElement> }) => {352 return (353 <span354 ref={ref}355 className={cn(356 'bg-secondary text-foreground inline-flex items-center gap-1 rounded-sm px-1.5 py-0.5 font-mono text-xs [&>svg]:size-3 [&>svg]:shrink-0',357 className,358 )}359 {...props}360 />361 );362};363364TaskFile.displayName = 'TaskFile';365366const Task = Object.assign(TaskRoot, {367 Trigger: TaskTrigger,368 Content: TaskContent,369 Item: TaskItem,370 File: TaskFile,371});372373export { Task };374export type {375 TaskContentProps,376 TaskFileProps,377 TaskItemProps,378 TaskProps,379 TaskStatus,380 TaskStatusLabels,381 TaskTriggerProps,382};
Actualiza las rutas de importación para que coincidan con la estructura de tu proyecto.
Anatomía
1import { Task } from '@/ai/task';
1<Task defaultOpen>2 <Task.Trigger title="Recorrí el registro de componentes" status="complete" />3 <Task.Content>4 <Task.Item>Leí 58 componentes en dos familias</Task.Item>5 <Task.Item>6 Relacioné el pedido con <Task.File>button.tsx</Task.File>7 </Task.Item>8 </Task.Content>9</Task>
Una tarea arranca abierta, porque lo interesante de la corrida de un agente suele ser el paso en el que está. Pon
defaultOpen={false} en las que ya terminaron.Composición
Usa la siguiente composición para construir un
Task:Task├── Task.Trigger└── Task.Content└── Task.Item└── Task.File
Estados
status define el icono y su color: pending espera, active gira, complete tilda y error marca el problema. Apilá varias tareas y la corrida entera se lee de un vistazo.Writingprompt-input.tsx
2 errors in the generated registry
1'use client';23import { Task } from '@/ai/task';45export function Statuses() {6 return (7 <div className="flex w-full max-w-md flex-col gap-4">8 <Task defaultOpen={false}>9 <Task.Trigger title="Read the docs" status="complete" />10 <Task.Content>11 <Task.Item>Fetched 12 pages from llms.txt</Task.Item>12 </Task.Content>13 </Task>14 <Task defaultOpen>15 <Task.Trigger title="Generating the component" status="active" />16 <Task.Content>17 <Task.Item>18 Writing19 <Task.File>prompt-input.tsx</Task.File>20 </Task.Item>21 </Task.Content>22 </Task>23 <Task defaultOpen={false}>24 <Task.Trigger title="Run the test suite" status="pending" />25 <Task.Content>26 <Task.Item>Waiting for the previous step</Task.Item>27 </Task.Content>28 </Task>29 <Task defaultOpen>30 <Task.Trigger title="Type check" status="error" />31 <Task.Content>32 <Task.Item>2 errors in the generated registry</Task.Item>33 </Task.Content>34 </Task>35 </div>36 );37}
Referencia de API
Task
| Prop | Type | Default | Description |
|---|---|---|---|
defaultOpen | boolean | true | Estado abierto cuando no se controla |
open | boolean | - | Estado abierto controlado |
onOpenChange | (open: boolean) => void | - | Se llama al cambiar el estado |
className | string | - | Clases CSS adicionales |
Task.Trigger
| Prop | Type | Default | Description |
|---|---|---|---|
title | string | - | Etiqueta del paso |
status | 'pending' | 'active' | 'complete' | 'error' | 'complete' | Icono y color del indicador |
statusLabels | Partial<Record<status, string>> | Pending, In progress, Completed, Failed | Estado que leen los lectores de pantalla después del título |
children | ReactNode | - | Reemplaza el título si se pasa |
className | string | - | Clases CSS adicionales |
Task.Content
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Clases CSS adicionales |
Task.Item
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Clases CSS adicionales |
Task.File
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Clases CSS adicionales |
¿Encontraste algo que mejorar?
¿Notaste un error, tipografía o detalle faltante en esta página? Ayúdanos a mejorar la documentación abriendo un issue en GitHub.