"use client" /** * Leo generation lifecycle — the one contract every "Leo is creating this" * surface follows, whether it is a table row, a card, a chart, or a form. * * inited ──▶ thinking ──▶ completed * * - `inited` Leo was asked. The placeholder appears and Leo's mark plays its * one-shot "invited" gesture. No data, no skeleton yet. * - `thinking` Leo is working. Brand-tinted skeleton, shimmering status, the * mark's working loop. * - `completed` Leo is done: a check with "Leo is done", held briefly. Then the placeholder * leaves and the real data appears (`delivered`). * * The state is owned by the consumer (it comes from the stream / mutation). * `useLeoGeneration` is the default owner for demos and for simple * request/response flows. */ import * as React from "react" import type { LeoIconMotionState } from "../components/ui/leo-icon" export type LeoGenerationState = "inited" | "thinking" | "completed" export const LEO_GENERATION_LABEL: Record = { inited: "Leo is getting started…", thinking: "Leo is thinking…", completed: "Leo is done", } /** Leo mark gesture for each lifecycle state. `inited` plays on mount. */ export const LEO_GENERATION_ICON_STATE: Record = { inited: "invited", thinking: "working", completed: "answered", } export interface UseLeoGenerationOptions { /** How long `inited` holds before thinking begins. Default 1200ms. */ initedMs?: number /** How long the lone check holds before the placeholder leaves. Default 900ms. */ doneMs?: number /** How long `thinking` runs when using `run()`. Default 3000ms. */ thinkingMs?: number } export function useLeoGeneration({ initedMs = 1200, thinkingMs = 3000, doneMs = 900 }: UseLeoGenerationOptions = {}) { const [delivered, setDelivered] = React.useState(false) const [stopped, setStopped] = React.useState(false) const [state, setState] = React.useState(null) const timers = React.useRef([]) const clear = React.useCallback(() => { timers.current.forEach(t => window.clearTimeout(t)) timers.current = [] }, []) React.useEffect(() => clear, [clear]) const set = React.useCallback( (next: LeoGenerationState | null) => { clear() setDelivered(false) setStopped(false) setState(next) }, [clear], ) /** Plays inited → thinking → completed on timers. */ const run = React.useCallback(() => { clear() setDelivered(false) setStopped(false) setState("inited") timers.current = [ window.setTimeout(() => setState("thinking"), initedMs), window.setTimeout(() => setState("completed"), initedMs + thinkingMs), window.setTimeout(() => { setState(null) setDelivered(true) }, initedMs + thinkingMs + doneMs), ] }, [clear, initedMs, thinkingMs, doneMs]) return { /** `null` when Leo is not generating. */ state, isActive: state !== null, /** True once a `run()` has finished: the placeholder is gone, show the data. */ delivered, set, run, /** True after `stop()`; cleared by the next `run()` or `set()`. */ stopped, /** Cancels an in-flight generation. Nothing is delivered. */ stop: React.useCallback(() => { clear() setState(null) setDelivered(false) setStopped(true) }, [clear]), reset: React.useCallback(() => set(null), [set]), } } // ─── Parent / child ────────────────────────────────────────────────────────── /** * One parent generation that creates several children (a dashboard that is * three charts, a table that gains five rows). Each child runs the same * lifecycle; the parent's state is derived from them. * * Parent state while running: * any child thinking → `thinking` * else any child waiting/inited → `inited` * else (all remaining completed)→ `completed` * When every child is delivered or stopped, the run ends: `parent.state` is * `null` and `parent.delivered` is true. * * Stopping the parent stops every child that has not been delivered yet. * Stopping a child leaves its siblings running. */ export interface LeoChildStatus { id: string /** `null` while waiting its turn, and again after delivery or a stop. */ state: LeoGenerationState | null delivered: boolean stopped: boolean /** Waiting to start (run in progress, this child not begun). */ pending: boolean } export interface UseLeoGenerationGroupOptions extends UseLeoGenerationOptions { /** Delay between one child starting and the next. Default 900ms. */ staggerMs?: number } export function useLeoGenerationGroup( childIds: readonly string[], { initedMs = 1200, thinkingMs = 3000, doneMs = 900, staggerMs = 900 }: UseLeoGenerationGroupOptions = {}, ) { type Row = Omit const blank = (): Record => Object.fromEntries(childIds.map(id => [id, { state: null, delivered: false, stopped: false, pending: false }])) const [rows, setRows] = React.useState>(blank) const [running, setRunning] = React.useState(false) const timers = React.useRef>({}) const clearChild = React.useCallback((id: string) => { ;(timers.current[id] ?? []).forEach(t => window.clearTimeout(t)) timers.current[id] = [] }, []) const clearAll = React.useCallback(() => { Object.keys(timers.current).forEach(clearChild) }, [clearChild]) React.useEffect(() => clearAll, [clearAll]) const patch = React.useCallback((id: string, p: Partial) => { setRows(r => (r[id] ? { ...r, [id]: { ...r[id], ...p } } : r)) }, []) // The run ends once nothing is waiting, active, or holding a check. React.useEffect(() => { if (!running) return const settled = childIds.every(id => { const r = rows[id] return !r || r.delivered || r.stopped }) if (settled) setRunning(false) }, [rows, running, childIds]) const run = React.useCallback(() => { clearAll() setRunning(true) setRows( Object.fromEntries( childIds.map(id => [id, { state: null, delivered: false, stopped: false, pending: true }]), ), ) childIds.forEach((id, i) => { const t0 = i * staggerMs timers.current[id] = [ window.setTimeout(() => patch(id, { state: "inited", pending: false }), t0), window.setTimeout(() => patch(id, { state: "thinking" }), t0 + initedMs), window.setTimeout(() => patch(id, { state: "completed" }), t0 + initedMs + thinkingMs), window.setTimeout( () => patch(id, { state: null, delivered: true }), t0 + initedMs + thinkingMs + doneMs, ), ] }) }, [childIds, clearAll, patch, staggerMs, initedMs, thinkingMs, doneMs]) const stopChild = React.useCallback( (id: string) => { clearChild(id) setRows(r => { const cur = r[id] if (!cur || cur.delivered) return r return { ...r, [id]: { ...cur, state: null, pending: false, stopped: true } } }) }, [clearChild], ) const stop = React.useCallback(() => { clearAll() setRows(r => Object.fromEntries( Object.entries(r).map(([id, row]) => [ id, row.delivered ? row : { ...row, state: null, pending: false, stopped: true }, ]), ), ) }, [clearAll]) const children: LeoChildStatus[] = childIds.map(id => ({ id, ...(rows[id] ?? blank()[id]) })) const active = children.filter(c => !c.delivered && !c.stopped) const parentState: LeoGenerationState | null = !running ? null : active.some(c => c.state === "thinking") ? "thinking" : active.some(c => c.state === "inited" || c.pending) ? "inited" : active.length ? "completed" : null return { parent: { state: parentState, /** A run finished with at least one child delivered. */ delivered: !running && children.some(c => c.delivered), running, stopped: !running && children.some(c => c.stopped), }, children, run, stop, stopChild, } }