Agent Run
Animated brand-neutral AI agent run — a Thinking status and short plan, tool calls whose spinners close into checks while a timer counts real seconds, then a markdown answer with citations and a code block that streams in irregular token bursts. Light/dark themes.
Source
components/kuchi/agent-run.tsx
1"use client";23import { type CSSProperties, useMemo } from "react";4import { Easing, random, useCurrentFrame, useVideoConfig } from "remotion";56export type AgentRunTheme = "light" | "dark";78export type AgentRunIcon =9 | "chart"10 | "database"11 | "search"12 | "book"13 | "globe"14 | "terminal"15 | "file";1617export interface AgentRunStep {18 name: string;19 detail?: string;20 duration: number;21 icon?: AgentRunIcon;22 sources?: readonly string[];23}2425export interface AgentRunScript {26 title?: string;27 prompt: string;28 plan?: readonly string[];29 steps?: readonly AgentRunStep[];30 answer: string;31}3233export interface AgentRunProps {34 run?: AgentRunScript;35 theme?: AgentRunTheme;36 accentColor?: string;37 compression?: number;38 seed?: number;39 speed?: number;40 className?: string;41}4243export interface AgentRunOptions {44 seed?: number;45 compression?: number;46 width?: number;47 height?: number;48}4950export interface AgentRunPlayback {51 fps?: number;52 speed?: number;53}5455export const defaultAgentRun: AgentRunScript = {56 title: "Checkout conversion drop",57 prompt: "Why did checkout conversion drop last week?",58 plan: [59 "Compare the checkout funnel with the week before",60 "Break the drop down by browser and step",61 "Check what shipped and what the error logs say",62 ],63 steps: [64 {65 icon: "chart",66 name: "Query analytics",67 detail: "checkout funnel, last 7 days vs prior 7",68 duration: 1.4,69 },70 {71 icon: "database",72 name: "Run SQL",73 detail: "conversion by browser and step",74 duration: 2.3,75 },76 {77 icon: "search",78 name: "Search logs",79 detail: "Apple Pay errors on Safari",80 duration: 1.1,81 },82 {83 icon: "book",84 name: "Read 12 sources",85 duration: 3.2,86 sources: [87 "Checkout funnel",88 "Browser report",89 "Release 4.12",90 "PR #2186",91 "webkit.org",92 "developer.mozilla.org",93 "Payments runbook",94 "Error log",95 "Incident notes",96 "Apple Pay guide",97 "Support tickets",98 "Status page",99 ],100 },101 ],102 answer: [103 "## Apple Pay broke on Safari in release 4.12",104 "",105 "Checkout conversion fell from 3.4% to 2.7% last week, a 21% drop [1]. All of it comes from the payment step on Safari, 41% of checkouts [2].",106 "",107 "- Safari conversion halved, from 3.5% to 1.8%",108 "- Chrome and Firefox held steady at 3.3%",109 '- 4.12 moved the card form into an iframe without `allow="payment"` [3]',110 "",111 "```tsx",112 "<iframe",113 " src={cardFormUrl}",114 ' allow="payment"',115 "/>",116 "```",117 "",118 "**Fix:** add the attribute and ship 4.12.1 today.",119 ].join("\n"),120};121122export const agentRunDefaults: Required<Omit<AgentRunProps, "className">> = {123 run: defaultAgentRun,124 theme: "light",125 accentColor: "#2563eb",126 compression: 3,127 seed: 1,128 speed: 1,129};130131const PANEL_IN = 14;132const PANEL_RISE = 14;133const BUBBLE_AT = 4;134const BUBBLE_IN = 10;135const BUBBLE_RISE = 8;136const RUN_START = 16;137const STATUS_IN = 6;138const THINK_LEAD = 14;139const THINK_TAIL = 8;140const SWAP = 8;141const SWAP_RISE = 4;142const TOOL_GAP = 5;143const TOOL_MIN = 12;144const TOOL_MAX = 120;145const ANSWER_GAP = 8;146const ROW_IN = 8;147const ROW_FADE = 6;148const LABEL_DELAY = 2;149const LABEL_FADE = 6;150const SPIN = 12;151const ARC = 0.28;152const RESOLVE = 8;153const CHECK_FROM = 3;154const CHECK_TO = 10;155const CHIP_LEAD = 4;156const CHIP_SPAN = 0.7;157const FADE = 5;158const MORPH = 8;159const POP = 8;160const CODE_OPEN = 8;161const LINE_GROW = 5;162const SCROLL = 24;163const SCROLL_LEAD = 16;164const SETTLE = 16;165const HOLD = 45;166const SHIMMER_PERIOD = 30;167const SHIMMER_BAND = 3;168const SHIMMER_BASE = 0.45;169const DOT_BACK = 1.7;170const CITE_BACK = 2;171const CHIP_BACK = 1.7;172const MIN_COMPRESSION = 0.25;173const MAX_COMPRESSION = 20;174175const SIZE_WEIGHTS = [8, 16, 22, 22, 17, 15];176const GAP_WEIGHTS = [42, 33, 16, 9];177const PAUSE_CHANCE = 0.06;178const PAUSE_MIN = 4;179const PAUSE_SPREAD = 4;180const BLOCK_MIN = 2;181const BLOCK_SPREAD = 3;182183const REF_HEIGHT = 720;184const PANEL_W = 800;185const MARGIN_X = 40;186const MARGIN_Y = 40;187const MIN_PANEL_H = 360;188const MAX_PANEL_H = 960;189const HEADER_H = 48;190const PAD_X = 32;191const PAD_TOP = 24;192const SAFE = 40;193const COLUMN = PANEL_W - 2 * PAD_X;194const MEASURE = 680;195const BODY_SIZE = 16;196const BODY_LINE = 26;197const BUBBLE_SIZE = 16;198const BUBBLE_LINE = 24;199const BUBBLE_PAD_Y = 10;200const BUBBLE_PAD_X = 16;201const BUBBLE_WIDTH = 520;202const BUBBLE_GAP = 22;203const STATUS_H = 22;204const STATUS_GAP = 10;205const PLAN_SIZE = 15;206const PLAN_LINE = 24;207const PLAN_GAP = 4;208const PLAN_INDENT = 36;209const PLAN_WIDTH = 640;210const PLAN_AFTER = 20;211const ROW_H = 40;212const CHIPS_H = 34;213const TOOLS_AFTER = 24;214const ITEM_INDENT = 22;215const ITEM_GAP = 4;216const BLOCK_GAP = 12;217const HEADING_GAP = 8;218const CODE_GAP = 14;219const CODE_SIZE = 14;220const CODE_LINE = 22;221const CODE_HEAD = 34;222const CODE_PAD = 10;223const CHIP_SIZE = 12.5;224const CHIP_GAP = 6;225const CHIP_MAX = 6;226const CHIP_ROOM = COLUMN - 2 - 40 - 14;227const CIRCLE = 2 * Math.PI * 10;228const CHECK_LENGTH = 6 * Math.SQRT2;229230const HEADINGS: Record<1 | 2, { size: number; line: number }> = {231 1: { size: 22, line: 32 },232 2: { size: 20, line: 30 },233};234235const SANS =236 'Inter, "Geist", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';237const MONO =238 '"JetBrains Mono", "Geist Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace';239240const EXPO = Easing.bezier(0.16, 1, 0.3, 1);241242const finite = (value: number | undefined, fallback: number) =>243 typeof value === "number" && Number.isFinite(value) ? value : fallback;244const clamp = (value: number, min: number, max: number) =>245 Math.min(max, Math.max(min, value));246const progress = (value: number) =>247 Number.isNaN(value) ? 0 : clamp(value, 0, 1);248const round = (value: number) => Math.round(value * 1000) / 1000;249const expo = (value: number) => EXPO(progress(value));250const easeOut = (value: number) => 1 - (1 - progress(value)) ** 3;251const smoothstep = (value: number) => {252 const t = progress(value);253 return t * t * (3 - 2 * t);254};255const backOut = (value: number, overshoot: number) => {256 const t = progress(value) - 1;257 return 1 + (overshoot + 1) * t ** 3 + overshoot * t ** 2;258};259const rateOf = (speed: number | undefined) =>260 Math.max(0, finite(speed, agentRunDefaults.speed));261const seedOf = (seed: number | undefined) =>262 finite(seed, agentRunDefaults.seed);263const compressionOf = (compression: number | undefined) =>264 clamp(265 finite(compression, agentRunDefaults.compression),266 MIN_COMPRESSION,267 MAX_COMPRESSION,268 );269270export function formatAgentRunSeconds(seconds: number) {271 const value = Math.max(0, finite(seconds, 0));272 if (value < 60) return `${value.toFixed(1)}s`;273 const minutes = Math.floor(value / 60);274 const rest = Math.floor(value - minutes * 60);275 return `${minutes}m ${String(rest).padStart(2, "0")}s`;276}277278const isLetter = (code: number) =>279 (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code >= 192;280const isDigit = (code: number) => code >= 48 && code <= 57;281282export function tokenizeAgentRun(text: string): number[] {283 const ends: number[] = [];284 let index = 0;285 while (index < text.length) {286 if (text[index] === "\n") {287 index += 1;288 ends.push(index);289 continue;290 }291 while (292 index < text.length &&293 (text[index] === " " || text[index] === "\t")294 ) {295 index += 1;296 }297 if (index < text.length && text[index] !== "\n") {298 const code = text.charCodeAt(index);299 if (isLetter(code)) {300 while (index < text.length && isLetter(text.charCodeAt(index))) {301 index += 1;302 }303 } else if (isDigit(code)) {304 const stop = Math.min(text.length, index + 3);305 while (index < stop && isDigit(text.charCodeAt(index))) {306 index += 1;307 }308 } else {309 index += 1;310 }311 }312 ends.push(index);313 }314 return ends;315}316317export interface AgentRunChunk {318 index: number;319 at: number;320 start: number;321 end: number;322 tokens: number;323 block: boolean;324}325326function pick(weights: readonly number[], value: number) {327 const total = weights.reduce((sum, weight) => sum + weight, 0);328 let cursor = value * total;329 for (const [index, weight] of weights.entries()) {330 if (cursor < weight) return index;331 cursor -= weight;332 }333 return weights.length - 1;334}335336export function getAgentRunChunks(337 text: string,338 seed = agentRunDefaults.seed,339 stream = "answer",340): AgentRunChunk[] {341 const ends = tokenizeAgentRun(text);342 const startOf = (token: number) => (token > 0 ? ends[token - 1] : 0);343 const isNewline = (token: number) =>344 token < ends.length && text[startOf(token)] === "\n";345 const key = `agent-run-${seedOf(seed)}-${stream}`;346 const chunks: AgentRunChunk[] = [];347 let token = 0;348 let at = 0;349 let block = false;350 while (token < ends.length) {351 const index = chunks.length;352 const size = pick(SIZE_WEIGHTS, random(`${key}-size-${index}`)) + 1;353 let stop = Math.min(ends.length, token + size);354 let cut = false;355 for (let cursor = token; cursor < stop; cursor++) {356 if (isNewline(cursor) && isNewline(cursor + 1)) {357 stop = cursor + 2;358 cut = true;359 break;360 }361 }362 if (!cut && isNewline(stop - 1) && isNewline(stop)) {363 stop += 1;364 cut = true;365 }366 while (cut && isNewline(stop)) stop += 1;367 if (index > 0) {368 at += pick(GAP_WEIGHTS, random(`${key}-gap-${index}`)) + 1;369 if (random(`${key}-pause-${index}`) < PAUSE_CHANCE) {370 const hold = random(`${key}-hold-${index}`) * PAUSE_SPREAD;371 at += PAUSE_MIN + Math.floor(hold);372 }373 if (block) {374 const extra = random(`${key}-block-${index}`) * BLOCK_SPREAD;375 at += BLOCK_MIN + Math.floor(extra);376 }377 }378 chunks.push({379 index,380 at,381 start: startOf(token),382 end: ends[stop - 1],383 tokens: stop - token,384 block,385 });386 block = cut;387 token = stop;388 }389 return chunks;390}391392function lastArrival(chunks: readonly AgentRunChunk[]) {393 return chunks.length > 0 ? chunks[chunks.length - 1].at : 0;394}395396function chunkIndexAt(chunks: readonly AgentRunChunk[], offset: number) {397 let low = 0;398 let high = chunks.length - 1;399 let found = chunks.length;400 while (low <= high) {401 const middle = (low + high) >> 1;402 if (chunks[middle].end > offset) {403 found = middle;404 high = middle - 1;405 } else {406 low = middle + 1;407 }408 }409 return found;410}411412export function getAgentRunArrival(413 chunks: readonly AgentRunChunk[],414 offset: number,415) {416 const index = chunkIndexAt(chunks, offset);417 return index < chunks.length ? chunks[index].at : Number.POSITIVE_INFINITY;418}419420export function getAgentRunReveal(421 chunks: readonly AgentRunChunk[],422 local: number,423) {424 let low = 0;425 let high = chunks.length - 1;426 let revealed = 0;427 while (low <= high) {428 const middle = (low + high) >> 1;429 if (chunks[middle].at <= local) {430 revealed = chunks[middle].end;431 low = middle + 1;432 } else {433 high = middle - 1;434 }435 }436 return revealed;437}438439export type AgentRunInlineKind = "text" | "bold" | "code" | "cite";440441export interface AgentRunInline {442 kind: AgentRunInlineKind;443 text: string;444 raw: number;445 end: number;446}447448export interface AgentRunCodeLine {449 text: string;450 raw: number;451}452453export type AgentRunBlock =454 | {455 kind: "heading";456 level: 1 | 2;457 raw: number;458 body: number;459 end: number;460 inline: AgentRunInline[];461 }462 | { kind: "paragraph"; raw: number; end: number; inline: AgentRunInline[] }463 | {464 kind: "item";465 raw: number;466 body: number;467 end: number;468 inline: AgentRunInline[];469 }470 | {471 kind: "code";472 raw: number;473 open: number;474 end: number;475 lang: string;476 langRaw: number;477 lines: AgentRunCodeLine[];478 };479480function parseInline(source: string, base: number): AgentRunInline[] {481 const out: AgentRunInline[] = [];482 let text = "";483 let textStart = 0;484 const flush = (at: number) => {485 if (text.length > 0) {486 out.push({ kind: "text", text, raw: base + textStart, end: base + at });487 }488 text = "";489 };490 let index = 0;491 while (index < source.length) {492 if (source.startsWith("**", index)) {493 const close = source.indexOf("**", index + 2);494 if (close > index + 2) {495 flush(index);496 out.push({497 kind: "bold",498 text: source.slice(index + 2, close),499 raw: base + index + 2,500 end: base + close + 2,501 });502 index = close + 2;503 textStart = index;504 continue;505 }506 }507 if (source[index] === "`") {508 const close = source.indexOf("`", index + 1);509 if (close > index + 1) {510 flush(index);511 out.push({512 kind: "code",513 text: source.slice(index + 1, close),514 raw: base + index + 1,515 end: base + close + 1,516 });517 index = close + 1;518 textStart = index;519 continue;520 }521 }522 if (source[index] === "[") {523 const match = /^\[(\d{1,3})\]/.exec(source.slice(index));524 if (match) {525 flush(index);526 out.push({527 kind: "cite",528 text: match[1],529 raw: base + index,530 end: base + index + match[0].length,531 });532 index += match[0].length;533 textStart = index;534 continue;535 }536 }537 if (text.length === 0) textStart = index;538 text += source[index];539 index += 1;540 }541 flush(index);542 return out;543}544545const HEADING_LINE = /^(#{1,3})[ \t]+(.*)$/;546const ITEM_LINE = /^[-*][ \t]+(.*)$/;547548function isStructural(line: string) {549 return (550 line.startsWith("```") || HEADING_LINE.test(line) || ITEM_LINE.test(line)551 );552}553554export function parseAgentRunMarkdown(markdown: string): AgentRunBlock[] {555 const lines: AgentRunCodeLine[] = [];556 let offset = 0;557 for (const text of markdown.split("\n")) {558 lines.push({ text, raw: offset });559 offset += text.length + 1;560 }561 const blocks: AgentRunBlock[] = [];562 let index = 0;563 while (index < lines.length) {564 const line = lines[index];565 if (line.text.trim() === "") {566 index += 1;567 continue;568 }569 if (line.text.startsWith("```")) {570 const rest = line.text.slice(3);571 const body: AgentRunCodeLine[] = [];572 let cursor = index + 1;573 while (cursor < lines.length && !lines[cursor].text.startsWith("```")) {574 body.push(lines[cursor]);575 cursor += 1;576 }577 const closed = cursor < lines.length;578 const last = closed ? lines[cursor] : (body[body.length - 1] ?? line);579 blocks.push({580 kind: "code",581 raw: line.raw,582 open: line.raw + 3,583 end: last.raw + last.text.length,584 lang: rest.trim(),585 langRaw: line.raw + 3 + (rest.length - rest.trimStart().length),586 lines: body,587 });588 index = closed ? cursor + 1 : cursor;589 continue;590 }591 const heading = HEADING_LINE.exec(line.text);592 if (heading) {593 const body = line.raw + line.text.length - heading[2].length;594 blocks.push({595 kind: "heading",596 level: heading[1].length === 1 ? 1 : 2,597 raw: line.raw,598 body,599 end: line.raw + line.text.length,600 inline: parseInline(heading[2], body),601 });602 index += 1;603 continue;604 }605 const item = ITEM_LINE.exec(line.text);606 if (item) {607 const body = line.raw + line.text.length - item[1].length;608 blocks.push({609 kind: "item",610 raw: line.raw,611 body,612 end: line.raw + line.text.length,613 inline: parseInline(item[1], body),614 });615 index += 1;616 continue;617 }618 let cursor = index;619 while (620 cursor < lines.length &&621 lines[cursor].text.trim() !== "" &&622 (cursor === index || !isStructural(lines[cursor].text))623 ) {624 cursor += 1;625 }626 const last = lines[cursor - 1];627 const end = last.raw + last.text.length;628 const source = markdown.slice(line.raw, end).replace(/\n/g, " ");629 blocks.push({630 kind: "paragraph",631 raw: line.raw,632 end,633 inline: parseInline(source, line.raw),634 });635 index = cursor;636 }637 return blocks;638}639640const NARROW = " .,:;'!|iljI`";641const THIN = "ftr()[]{}/\\-";642const SYMBOL = "<>=+~#$&→";643const WIDE = "mw…";644const WIDEST = "MW@%—";645646function charWidth(char: string) {647 if (NARROW.includes(char)) return 0.3;648 if (THIN.includes(char)) return 0.44;649 if (WIDEST.includes(char)) return 1;650 if (WIDE.includes(char)) return 0.9;651 if (SYMBOL.includes(char)) return 0.68;652 if (char >= "0" && char <= "9") return 0.66;653 if (char >= "A" && char <= "Z") return 0.74;654 return 0.62;655}656657export function estimateAgentRunWidth(658 text: string,659 size: number,660 mono = false,661) {662 let em = 0;663 for (const char of text) em += mono ? 0.6 : charWidth(char);664 return em * size;665}666667export type AgentRunPieceKind =668 | AgentRunInlineKind669 | "punct"670 | "string"671 | "comment";672673export interface AgentRunPiece {674 kind: AgentRunPieceKind;675 text: string;676 raw: number;677 end: number;678}679680export interface AgentRunTextLine {681 y: number;682 height: number;683 raw: number;684 pieces: AgentRunPiece[];685}686687function pieceWidth(piece: AgentRunPiece, size: number) {688 if (piece.kind === "cite") {689 return 20 + 7 * Math.max(0, piece.text.length - 1);690 }691 if (piece.kind === "code") {692 return estimateAgentRunWidth(piece.text, size * 0.875, true) + 10;693 }694 return estimateAgentRunWidth(piece.text, size);695}696697interface Atom {698 pieces: AgentRunPiece[];699 width: number;700 space: boolean;701}702703function atomsOf(inline: readonly AgentRunInline[], size: number): Atom[] {704 const atoms: Atom[] = [];705 let word: AgentRunPiece[] = [];706 let wordWidth = 0;707 const add = (piece: AgentRunPiece) => {708 word.push(piece);709 wordWidth += pieceWidth(piece, size);710 };711 const close = () => {712 if (word.length > 0) {713 atoms.push({ pieces: word, width: wordWidth, space: false });714 }715 word = [];716 wordWidth = 0;717 };718 for (const segment of inline) {719 if (segment.kind === "cite" || segment.kind === "code") {720 add({ ...segment });721 continue;722 }723 let index = 0;724 while (index < segment.text.length) {725 const space = segment.text[index] === " ";726 let stop = index;727 while (728 stop < segment.text.length &&729 (segment.text[stop] === " ") === space730 ) {731 stop += 1;732 }733 const piece: AgentRunPiece = {734 kind: segment.kind,735 text: segment.text.slice(index, stop),736 raw: segment.raw + index,737 end: segment.raw + stop,738 };739 if (space) {740 close();741 atoms.push({742 pieces: [piece],743 width: pieceWidth(piece, size),744 space: true,745 });746 } else {747 add(piece);748 }749 index = stop;750 }751 }752 close();753 return atoms;754}755756function mergePieces(pieces: readonly AgentRunPiece[]) {757 const merged: AgentRunPiece[] = [];758 for (const piece of pieces) {759 const last = merged.at(-1);760 const text = piece.kind === "text" || piece.kind === "bold";761 if (text && last?.kind === piece.kind && last.end === piece.raw) {762 merged[merged.length - 1] = {763 ...last,764 text: last.text + piece.text,765 end: piece.end,766 };767 } else {768 merged.push({ ...piece });769 }770 }771 return merged;772}773774export function wrapAgentRunInline(775 inline: readonly AgentRunInline[],776 size: number,777 maxWidth: number,778): AgentRunPiece[][] {779 const lines: AgentRunPiece[][] = [];780 let line: AgentRunPiece[] = [];781 let width = 0;782 let pending: Atom | undefined;783 for (const atom of atomsOf(inline, size)) {784 if (atom.space) {785 if (line.length > 0) pending = atom;786 continue;787 }788 const gap = pending ? pending.width : 0;789 if (line.length > 0 && width + gap + atom.width > maxWidth) {790 lines.push(line);791 line = [...atom.pieces];792 width = atom.width;793 } else {794 if (pending && line.length > 0) {795 line.push(...pending.pieces);796 width += gap;797 }798 line.push(...atom.pieces);799 width += atom.width;800 }801 pending = undefined;802 }803 if (line.length > 0) lines.push(line);804 return lines.map(mergePieces);805}806807function plainInline(text: string, raw: number): AgentRunInline[] {808 return text.length > 0809 ? [{ kind: "text", text, raw, end: raw + text.length }]810 : [];811}812813function textLines(814 pieces: AgentRunPiece[][],815 lineHeight: number,816 raw: number,817): AgentRunTextLine[] {818 if (pieces.length === 0) {819 return [{ y: 0, height: lineHeight, raw, pieces: [] }];820 }821 return pieces.map((line, index) => ({822 y: index * lineHeight,823 height: lineHeight,824 raw: line[0]?.raw ?? raw,825 pieces: line,826 }));827}828829const PUNCT = "<>{}()[]/=;,.:+-*&|!?";830831export function getAgentRunCodePieces(line: AgentRunCodeLine): AgentRunPiece[] {832 const pieces: AgentRunPiece[] = [];833 const push = (kind: AgentRunPieceKind, from: number, to: number) => {834 if (to <= from) return;835 const last = pieces.at(-1);836 if (last?.kind === kind && last.end === line.raw + from) {837 pieces[pieces.length - 1] = {838 ...last,839 text: last.text + line.text.slice(from, to),840 end: line.raw + to,841 };842 return;843 }844 pieces.push({845 kind,846 text: line.text.slice(from, to),847 raw: line.raw + from,848 end: line.raw + to,849 });850 };851 let index = 0;852 while (index < line.text.length) {853 const char = line.text[index];854 if (line.text.startsWith("//", index)) {855 push("comment", index, line.text.length);856 break;857 }858 if (char === '"' || char === "'" || char === "`") {859 const close = line.text.indexOf(char, index + 1);860 const stop = close === -1 ? line.text.length : close + 1;861 push("string", index, stop);862 index = stop;863 continue;864 }865 if (PUNCT.includes(char)) {866 push("punct", index, index + 1);867 index += 1;868 continue;869 }870 push("text", index, index + 1);871 index += 1;872 }873 return pieces;874}875876export function getAgentRunFrame(width?: number, height?: number) {877 const frameWidth = Math.max(1, finite(width, 1280));878 const frameHeight = Math.max(1, finite(height, 720));879 const scale = Math.min(880 frameHeight / REF_HEIGHT,881 frameWidth / (PANEL_W + 2 * MARGIN_X),882 );883 const panelHeight = clamp(884 frameHeight / scale - 2 * MARGIN_Y,885 MIN_PANEL_H,886 MAX_PANEL_H,887 );888 return {889 width: frameWidth,890 height: frameHeight,891 unit: round(scale),892 panelWidth: PANEL_W,893 panelHeight: round(panelHeight),894 viewport: round(panelHeight - HEADER_H - 2),895 };896}897898export type AgentRunFrame = ReturnType<typeof getAgentRunFrame>;899900export interface AgentRunSegment {901 kind: "think" | "gap" | "tool" | "answer";902 from: number;903 to: number;904 realFrom: number;905 real: number;906}907908export interface AgentRunToolSpan {909 index: number;910 start: number;911 end: number;912 span: number;913 duration: number;914 realStart: number;915}916917function planTextOf(run: AgentRunScript) {918 return (run.plan ?? []).join("\n");919}920921export function getAgentRunTimeline(922 run: AgentRunScript = defaultAgentRun,923 options: AgentRunOptions = {},924) {925 const seed = seedOf(options.seed);926 const compression = compressionOf(options.compression);927 const perFrame = compression / 30;928 const planText = planTextOf(run);929 const planChunks =930 planText.length > 0 ? getAgentRunChunks(planText, seed, "plan") : [];931 const planStart = RUN_START + THINK_LEAD;932 const planEnd = planStart + lastArrival(planChunks);933 const thinkEnd = planEnd + THINK_TAIL;934 const segments: AgentRunSegment[] = [];935 let real = 0;936 const push = (937 kind: AgentRunSegment["kind"],938 from: number,939 to: number,940 seconds: number,941 ) => {942 segments.push({ kind, from, to, realFrom: real, real: seconds });943 real += seconds;944 };945 push("think", RUN_START, thinkEnd, (thinkEnd - RUN_START) * perFrame);946 const thinkSeconds = real;947 const tools: AgentRunToolSpan[] = [];948 let cursor = thinkEnd;949 for (const [index, step] of (run.steps ?? []).entries()) {950 push("gap", cursor, cursor + TOOL_GAP, TOOL_GAP * perFrame);951 cursor += TOOL_GAP;952 const duration = Math.max(0, finite(step.duration, 0));953 const span = clamp(Math.round(duration / perFrame), TOOL_MIN, TOOL_MAX);954 const realStart = real;955 push("tool", cursor, cursor + span, duration);956 tools.push({957 index,958 start: cursor,959 end: cursor + span,960 span,961 duration,962 realStart,963 });964 cursor += span;965 }966 push("gap", cursor, cursor + ANSWER_GAP, ANSWER_GAP * perFrame);967 const answerStart = cursor + ANSWER_GAP;968 const answerChunks = getAgentRunChunks(run.answer, seed, "answer");969 const answerEnd = answerStart + lastArrival(answerChunks);970 push("answer", answerStart, answerEnd, (answerEnd - answerStart) * perFrame);971 return {972 compression,973 runStart: RUN_START,974 planStart,975 planEnd,976 thinkEnd,977 thinkSeconds,978 tools,979 answerStart,980 answerEnd,981 runEnd: answerEnd,982 settled: answerEnd + SETTLE,983 realTotal: real,984 segments,985 planChunks,986 answerChunks,987 };988}989990export type AgentRunTimeline = ReturnType<typeof getAgentRunTimeline>;991992export const agentRunLength = getAgentRunTimeline().settled;993994export function getAgentRunDuration(995 run: AgentRunScript = defaultAgentRun,996 options: AgentRunOptions & Pick<AgentRunPlayback, "speed"> = {},997) {998 const rate = rateOf(options.speed);999 if (rate === 0) return HOLD;1000 const { settled } = getAgentRunTimeline(run, options);1001 return Math.ceil(round(settled / rate)) + HOLD;1002}10031004export function getAgentRunTime(1005 frame: number,1006 playback: AgentRunPlayback = {},1007) {1008 const fps = Math.max(1, finite(playback.fps, 30));1009 return Math.max(0, finite(frame, 0)) * (30 / fps) * rateOf(playback.speed);1010}10111012export function getAgentRunElapsed(time: number, timeline: AgentRunTimeline) {1013 if (!(time > timeline.runStart)) return 0;1014 for (const segment of timeline.segments) {1015 if (segment.to > segment.from && time < segment.to) {1016 const share = (time - segment.from) / (segment.to - segment.from);1017 return segment.realFrom + share * segment.real;1018 }1019 }1020 return timeline.realTotal;1021}10221023export interface AgentRunChipLayout {1024 label: string;1025 icon: "globe" | "file";1026}10271028export interface AgentRunRowLayout {1029 index: number;1030 y: number;1031 height: number;1032 divider: boolean;1033 icon: AgentRunIcon;1034 name: string;1035 detail: string;1036 duration: string;1037 chips: AgentRunChipLayout[];1038 more: number;1039}10401041export interface AgentRunPlanItemLayout {1042 index: number;1043 y: number;1044 raw: number;1045 lines: AgentRunTextLine[];1046}10471048export interface AgentRunPlanSection {1049 y: number;1050 height: number;1051 items: AgentRunPlanItemLayout[];1052}10531054export interface AgentRunToolsSection {1055 y: number;1056 height: number;1057 rows: AgentRunRowLayout[];1058}10591060export type AgentRunBlockLayout =1061 | {1062 kind: "heading";1063 index: number;1064 y: number;1065 height: number;1066 level: 1 | 2;1067 raw: number;1068 end: number;1069 mark: string;1070 markWidth: number;1071 lines: AgentRunTextLine[];1072 }1073 | {1074 kind: "paragraph" | "item";1075 index: number;1076 y: number;1077 height: number;1078 raw: number;1079 lines: AgentRunTextLine[];1080 }1081 | {1082 kind: "code";1083 index: number;1084 y: number;1085 height: number;1086 raw: number;1087 open: number;1088 lang: string;1089 langRaw: number;1090 lines: AgentRunTextLine[];1091 };10921093const DOMAIN = /^[a-z0-9-]+(\.[a-z0-9-]+)+(\/\S*)?$/i;10941095function chipWidth(label: string) {1096 return 7 + 12 + 5 + estimateAgentRunWidth(label, CHIP_SIZE) + 9 + 2;1097}10981099function moreWidth(count: number) {1100 return 9 + estimateAgentRunWidth(`+${count}`, CHIP_SIZE) + 9 + 2;1101}11021103export function fitAgentRunChips(sources: readonly string[]) {1104 const chips: AgentRunChipLayout[] = [];1105 let used = 0;1106 for (const [index, label] of sources.entries()) {1107 if (chips.length >= CHIP_MAX) break;1108 const width = chipWidth(label) + (chips.length > 0 ? CHIP_GAP : 0);1109 const rest = sources.length - index - 1;1110 const reserve = rest > 0 ? CHIP_GAP + moreWidth(rest) : 0;1111 if (used + width + reserve > CHIP_ROOM) break;1112 chips.push({ label, icon: DOMAIN.test(label) ? "globe" : "file" });1113 used += width;1114 }1115 return { chips, more: sources.length - chips.length };1116}11171118const lineText = (line: readonly AgentRunPiece[]) =>1119 line.map((piece) => piece.text).join("");11201121function blockGap(1122 previous: AgentRunBlock["kind"] | undefined,1123 next: AgentRunBlock["kind"],1124) {1125 if (previous === undefined) return 0;1126 if (previous === "item" && next === "item") return ITEM_GAP;1127 if (previous === "code" || next === "code") return CODE_GAP;1128 if (previous === "heading") return HEADING_GAP;1129 return BLOCK_GAP;1130}11311132export function getAgentRunLayout(run: AgentRunScript = defaultAgentRun) {1133 let y = PAD_TOP;1134 const prompt = plainInline(run.prompt, 0);1135 const wrappedPrompt = wrapAgentRunInline(prompt, BUBBLE_SIZE, BUBBLE_WIDTH);1136 const promptLines = wrappedPrompt.map(lineText);1137 const bubble = {1138 y,1139 height: Math.max(1, promptLines.length) * BUBBLE_LINE + 2 * BUBBLE_PAD_Y,1140 lines: promptLines,1141 };1142 y += bubble.height + BUBBLE_GAP;1143 const status = { y, height: STATUS_H };1144 y += STATUS_H;1145 let plan: AgentRunPlanSection | null = null;1146 const planLines = run.plan ?? [];1147 if (planLines.length > 0) {1148 y += STATUS_GAP;1149 const items: AgentRunPlanItemLayout[] = [];1150 let cursor = 0;1151 let raw = 0;1152 for (const [index, text] of planLines.entries()) {1153 if (index > 0) cursor += PLAN_GAP;1154 const inline = plainInline(text, raw);1155 const wrapped = wrapAgentRunInline(inline, PLAN_SIZE, PLAN_WIDTH);1156 const lines = textLines(wrapped, PLAN_LINE, raw);1157 items.push({ index, y: cursor, raw, lines });1158 cursor += lines.length * PLAN_LINE;1159 raw += text.length + 1;1160 }1161 plan = { y, height: cursor, items };1162 y += cursor;1163 }1164 let tools: AgentRunToolsSection | null = null;1165 const steps = run.steps ?? [];1166 if (steps.length > 0) {1167 y += PLAN_AFTER;1168 const rows: AgentRunRowLayout[] = [];1169 let cursor = 0;1170 for (const [index, step] of steps.entries()) {1171 const sources = step.sources ?? [];1172 const fit = fitAgentRunChips(sources);1173 const height =1174 ROW_H + (index > 0 ? 1 : 0) + (sources.length > 0 ? CHIPS_H : 0);1175 rows.push({1176 index,1177 y: cursor,1178 height,1179 divider: index > 0,1180 icon: step.icon ?? (sources.length > 0 ? "book" : "terminal"),1181 name: step.name,1182 detail: step.detail ?? "",1183 duration: formatAgentRunSeconds(finite(step.duration, 0)),1184 chips: fit.chips,1185 more: fit.more,1186 });1187 cursor += height;1188 }1189 tools = { y, height: cursor + 2, rows };1190 y += cursor + 2;1191 }1192 const parsed = parseAgentRunMarkdown(run.answer);1193 const blocks: AgentRunBlockLayout[] = [];1194 if (parsed.length > 0) y += tools ? TOOLS_AFTER : PLAN_AFTER;1195 let previous: AgentRunBlock["kind"] | undefined;1196 for (const [index, block] of parsed.entries()) {1197 y += blockGap(previous, block.kind);1198 previous = block.kind;1199 if (block.kind === "heading") {1200 const spec = HEADINGS[block.level];1201 const wrapped = wrapAgentRunInline(block.inline, spec.size, MEASURE);1202 const lines = textLines(wrapped, spec.line, block.body);1203 const mark = run.answer.slice(block.raw, block.body);1204 blocks.push({1205 kind: "heading",1206 index,1207 y,1208 height: lines.length * spec.line,1209 level: block.level,1210 raw: block.raw,1211 end: block.end,1212 mark,1213 markWidth: round(estimateAgentRunWidth(mark, BODY_SIZE)),1214 lines,1215 });1216 y += lines.length * spec.line;1217 continue;1218 }1219 if (block.kind === "code") {1220 const lines = block.lines.map((line, row) => ({1221 y: row * CODE_LINE,1222 height: CODE_LINE,1223 raw: line.raw,1224 pieces: getAgentRunCodePieces(line),1225 }));1226 const height = CODE_HEAD + 2 * CODE_PAD + lines.length * CODE_LINE;1227 blocks.push({1228 kind: "code",1229 index,1230 y,1231 height,1232 raw: block.raw,1233 open: block.open,1234 lang: block.lang,1235 langRaw: block.langRaw,1236 lines,1237 });1238 y += height;1239 continue;1240 }1241 const width = block.kind === "item" ? MEASURE - ITEM_INDENT : MEASURE;1242 const body = block.kind === "item" ? block.body : block.raw;1243 const wrapped = wrapAgentRunInline(block.inline, BODY_SIZE, width);1244 const lines = textLines(wrapped, BODY_LINE, body);1245 blocks.push({1246 kind: block.kind,1247 index,1248 y,1249 height: lines.length * BODY_LINE,1250 raw: block.raw,1251 lines,1252 });1253 y += lines.length * BODY_LINE;1254 }1255 return { bubble, status, plan, tools, blocks, height: y };1256}12571258export type AgentRunLayout = ReturnType<typeof getAgentRunLayout>;12591260export interface AgentRunScrollStep {1261 at: number;1262 delta: number;1263}12641265export function getAgentRunGrowth(1266 layout: AgentRunLayout,1267 timeline: AgentRunTimeline,1268) {1269 const events: { at: number; bottom: number }[] = [1270 { at: BUBBLE_AT, bottom: layout.bubble.y + layout.bubble.height },1271 { at: RUN_START, bottom: layout.status.y + layout.status.height },1272 ];1273 const { plan, tools } = layout;1274 if (plan) {1275 for (const item of plan.items) {1276 for (const line of item.lines) {1277 const at = getAgentRunArrival(timeline.planChunks, line.raw);1278 events.push({1279 at: timeline.planStart + at,1280 bottom: plan.y + item.y + line.y + line.height,1281 });1282 }1283 }1284 }1285 if (tools) {1286 for (const row of tools.rows) {1287 const span = timeline.tools[row.index];1288 events.push({ at: span.start, bottom: tools.y + row.y + row.height + 2 });1289 }1290 }1291 const arrival = (offset: number) =>1292 timeline.answerStart + getAgentRunArrival(timeline.answerChunks, offset);1293 for (const block of layout.blocks) {1294 if (block.kind === "code") {1295 events.push({1296 at: arrival(block.open - 1),1297 bottom: block.y + CODE_HEAD + 2 * CODE_PAD,1298 });1299 for (const line of block.lines) {1300 events.push({1301 at: arrival(line.raw),1302 bottom: block.y + CODE_HEAD + 2 * CODE_PAD + line.y + line.height,1303 });1304 }1305 continue;1306 }1307 for (const [row, line] of block.lines.entries()) {1308 const start = row === 0 ? block.raw : line.raw;1309 events.push({1310 at: arrival(start),1311 bottom: block.y + line.y + line.height,1312 });1313 }1314 }1315 return events1316 .filter((event) => Number.isFinite(event.at))1317 .sort((a, b) => a.at - b.at);1318}13191320export function getAgentRunScrollSteps(1321 layout: AgentRunLayout,1322 timeline: AgentRunTimeline,1323 viewport: number,1324): AgentRunScrollStep[] {1325 const steps: AgentRunScrollStep[] = [];1326 let target = 0;1327 for (const event of getAgentRunGrowth(layout, timeline)) {1328 const next = Math.max(target, event.bottom + SAFE - viewport);1329 if (next > target) {1330 steps.push({ at: event.at, delta: round(next - target) });1331 }1332 target = next;1333 }1334 return steps;1335}13361337export function getAgentRunScroll(1338 time: number,1339 steps: readonly AgentRunScrollStep[],1340) {1341 let total = 0;1342 for (const step of steps) {1343 const since = time - step.at + SCROLL_LEAD;1344 if (since <= 0) break;1345 total += step.delta * smoothstep(since / SCROLL);1346 }1347 return total;1348}13491350export function getAgentRunModel(1351 run: AgentRunScript = defaultAgentRun,1352 options: AgentRunOptions = {},1353) {1354 const stage = getAgentRunFrame(options.width, options.height);1355 const timeline = getAgentRunTimeline(run, options);1356 const layout = getAgentRunLayout(run);1357 const scroll = getAgentRunScrollSteps(layout, timeline, stage.viewport);1358 return { run, stage, timeline, layout, scroll };1359}13601361export type AgentRunModel = ReturnType<typeof getAgentRunModel>;13621363export interface AgentRunSpinnerState {1364 angle: number;1365 arc: number;1366 done: number;1367 check: number;1368 resolved: boolean;1369}13701371export function getAgentRunSpinner(1372 time: number,1373 start: number,1374 end: number,1375): AgentRunSpinnerState {1376 const spinning = clamp(time - start, 0, Math.max(0, end - start));1377 const since = time - end;1378 const settle = progress(since / RESOLVE);1379 const coast = SPIN * RESOLVE * (settle - (settle * settle) / 2);1380 return {1381 angle: round(spinning * SPIN + coast - 90),1382 arc: round(ARC + (1 - ARC) * expo(since / RESOLVE)),1383 done: round(smoothstep(since / RESOLVE)),1384 check: round(easeOut((since - CHECK_FROM) / (CHECK_TO - CHECK_FROM))),1385 resolved: since >= 0,1386 };1387}13881389export function getAgentRunShimmer(time: number, length: number) {1390 const cycle = (time - RUN_START) / SHIMMER_PERIOD;1391 const phase = cycle - Math.floor(cycle);1392 const center = -SHIMMER_BAND + phase * (length + 2 * SHIMMER_BAND);1393 return Array.from({ length }, (_, index) => {1394 const distance = Math.abs(index + 0.5 - center) / SHIMMER_BAND;1395 const band = distance < 1 ? (1 - distance * distance) ** 2 : 0;1396 return round(SHIMMER_BASE + (1 - SHIMMER_BASE) * band);1397 });1398}13991400export interface AgentRunFragment {1401 text: string;1402 opacity: number;1403}14041405export interface AgentRunSpan {1406 kind: AgentRunPieceKind;1407 fragments: AgentRunFragment[];1408 opacity: number;1409 scale: number;1410}14111412export interface AgentRunLineState {1413 key: string;1414 y: number;1415 height: number;1416 spans: AgentRunSpan[];1417}14181419const fadeOf = (since: number) => round(easeOut((since + 1) / FADE));14201421function spansOf(1422 pieces: readonly AgentRunPiece[],1423 chunks: readonly AgentRunChunk[],1424 local: number,1425 revealed: number,1426): AgentRunSpan[] {1427 const spans: AgentRunSpan[] = [];1428 for (const piece of pieces) {1429 if (piece.kind === "cite") {1430 if (revealed < piece.end) continue;1431 const since = local - getAgentRunArrival(chunks, piece.end - 1);1432 spans.push({1433 kind: "cite",1434 fragments: [{ text: piece.text, opacity: 1 }],1435 opacity: round(easeOut((since + 1) / 4)),1436 scale: round(0.6 + 0.4 * backOut((since + 1) / POP, CITE_BACK)),1437 });1438 continue;1439 }1440 const visible = clamp(revealed - piece.raw, 0, piece.text.length);1441 if (visible === 0) continue;1442 const fragments: AgentRunFragment[] = [];1443 let offset = 0;1444 while (offset < visible) {1445 const index = chunkIndexAt(chunks, piece.raw + offset);1446 const chunk = chunks[index];1447 const stop = chunk ? Math.min(visible, chunk.end - piece.raw) : visible;1448 const opacity = chunk ? fadeOf(local - chunk.at) : 1;1449 const text = piece.text.slice(offset, stop);1450 const last = fragments.at(-1);1451 if (last?.opacity === 1 && opacity === 1) {1452 fragments[fragments.length - 1] = { text: last.text + text, opacity };1453 } else {1454 fragments.push({ text, opacity });1455 }1456 offset = Math.max(stop, offset + 1);1457 }1458 spans.push({ kind: piece.kind, fragments, opacity: 1, scale: 1 });1459 }1460 return spans;1461}14621463export type AgentRunBlockState =1464 | {1465 kind: "heading";1466 key: string;1467 y: number;1468 level: 1 | 2;1469 styled: boolean;1470 morph: number;1471 mark: string;1472 markWidth: number;1473 lines: AgentRunLineState[];1474 }1475 | { kind: "paragraph"; key: string; y: number; lines: AgentRunLineState[] }1476 | {1477 kind: "item";1478 key: string;1479 y: number;1480 dot: number;1481 dotOpacity: number;1482 lines: AgentRunLineState[];1483 }1484 | {1485 kind: "code";1486 key: string;1487 y: number;1488 height: number;1489 opacity: number;1490 lang: string;1491 lines: AgentRunLineState[];1492 };14931494function blockState(1495 block: AgentRunBlockLayout,1496 text: string,1497 chunks: readonly AgentRunChunk[],1498 local: number,1499 revealed: number,1500): AgentRunBlockState | null {1501 const key = `block-${block.index}`;1502 const lineStates = (from: number) => {1503 const lines: AgentRunLineState[] = [];1504 for (const [row, line] of block.lines.entries()) {1505 if (revealed <= (row === 0 ? from : line.raw)) break;1506 lines.push({1507 key: `${key}-line-${row}`,1508 y: line.y,1509 height: line.height,1510 spans: spansOf(line.pieces, chunks, local, revealed),1511 });1512 }1513 return lines;1514 };1515 if (block.kind === "code") {1516 if (revealed < block.open) return null;1517 const since = local - getAgentRunArrival(chunks, block.open - 1);1518 let height = expo((since + 1) / CODE_OPEN) * (CODE_HEAD + 2 * CODE_PAD);1519 const lines: AgentRunLineState[] = [];1520 for (const [row, line] of block.lines.entries()) {1521 if (revealed <= line.raw) break;1522 const grown = local - getAgentRunArrival(chunks, line.raw);1523 height += expo((grown + 1) / LINE_GROW) * CODE_LINE;1524 lines.push({1525 key: `${key}-line-${row}`,1526 y: line.y,1527 height: line.height,1528 spans: spansOf(line.pieces, chunks, local, revealed),1529 });1530 }1531 const langShown = clamp(revealed - block.langRaw, 0, block.lang.length);1532 return {1533 kind: "code",1534 key,1535 y: block.y,1536 height: round(height),1537 opacity: round(easeOut((since + 1) / 4)),1538 lang: block.lang.slice(0, langShown),1539 lines,1540 };1541 }1542 if (revealed <= block.raw) return null;1543 if (block.kind === "heading") {1544 const complete =1545 revealed > block.end ||1546 (block.end >= text.length && revealed >= block.end);1547 const completeAt = getAgentRunArrival(1548 chunks,1549 Math.min(block.end, text.length - 1),1550 );1551 const morph = complete ? round(expo((local - completeAt) / MORPH)) : 0;1552 const markShown = clamp(revealed - block.raw, 0, block.mark.length);1553 return {1554 kind: "heading",1555 key,1556 y: block.y,1557 level: block.level,1558 styled: complete,1559 morph,1560 mark: block.mark.slice(0, markShown),1561 markWidth: block.markWidth,1562 lines: lineStates(block.raw),1563 };1564 }1565 if (block.kind === "item") {1566 const since = local - getAgentRunArrival(chunks, block.raw);1567 return {1568 kind: "item",1569 key,1570 y: block.y,1571 dot: round(backOut((since + 1) / POP, DOT_BACK)),1572 dotOpacity: round(easeOut((since + 1) / 3)),1573 lines: lineStates(block.raw),1574 };1575 }1576 return { kind: "paragraph", key, y: block.y, lines: lineStates(block.raw) };1577}15781579export interface AgentRunPlanItemState {1580 key: string;1581 index: number;1582 y: number;1583 numberOpacity: number;1584 lines: AgentRunLineState[];1585}15861587function planState(1588 plan: AgentRunPlanSection,1589 chunks: readonly AgentRunChunk[],1590 local: number,1591) {1592 const revealed = getAgentRunReveal(chunks, local);1593 const items: AgentRunPlanItemState[] = [];1594 let rule = 0;1595 for (const item of plan.items) {1596 if (revealed <= item.raw) break;1597 const lines: AgentRunLineState[] = [];1598 for (const [row, line] of item.lines.entries()) {1599 if (revealed <= (row === 0 ? item.raw : line.raw)) break;1600 const since = local - getAgentRunArrival(chunks, line.raw);1601 const grown = line.height * expo((since + 1) / LINE_GROW);1602 rule = Math.max(rule, item.y + line.y + grown);1603 lines.push({1604 key: `plan-${item.index}-line-${row}`,1605 y: line.y,1606 height: line.height,1607 spans: spansOf(line.pieces, chunks, local, revealed),1608 });1609 }1610 const numbered = local - getAgentRunArrival(chunks, item.raw);1611 items.push({1612 key: `plan-${item.index}`,1613 index: item.index,1614 y: item.y,1615 numberOpacity: fadeOf(numbered),1616 lines,1617 });1618 }1619 return { y: plan.y, rule: round(rule), items };1620}16211622function chipPops(count: number, since: number, span: number) {1623 const spread = Math.max(0, CHIP_SPAN * span - CHIP_LEAD);1624 const step = count > 1 ? spread / (count - 1) : 0;1625 return Array.from({ length: count }, (_, index) => {1626 const age = since - CHIP_LEAD - index * step;1627 return {1628 visible: age >= 0,1629 opacity: round(easeOut((age + 1) / 4)),1630 scale: round(0.8 + 0.2 * backOut((age + 1) / POP, CHIP_BACK)),1631 };1632 });1633}16341635function toolsState(1636 tools: AgentRunToolsSection,1637 timeline: AgentRunTimeline,1638 time: number,1639) {1640 let height = 2;1641 const rows = tools.rows1642 .filter((row) => time >= timeline.tools[row.index].start)1643 .map((row) => {1644 const span = timeline.tools[row.index];1645 const since = time - span.start;1646 const open = expo(since / ROW_IN);1647 height += row.height * open;1648 const pops = chipPops(1649 row.chips.length + (row.more > 0 ? 1 : 0),1650 since,1651 span.span,1652 );1653 const more = pops[row.chips.length];1654 return {1655 key: `tool-${row.index}`,1656 index: row.index,1657 y: row.y,1658 height: round(row.height * open),1659 divider: row.divider,1660 icon: row.icon,1661 name: row.name,1662 detail: row.detail,1663 duration: row.duration,1664 content: round(easeOut((since - 1) / ROW_FADE)),1665 spinner: getAgentRunSpinner(time, span.start, span.end),1666 label: round(easeOut((time - span.end - LABEL_DELAY) / LABEL_FADE)),1667 chips: row.chips.map((chip, index) => ({ ...chip, ...pops[index] })),1668 more: row.more > 0 && more ? { count: row.more, ...more } : null,1669 sources: row.chips.length + row.more > 0,1670 };1671 });1672 return { y: tools.y, height: round(height), rows };1673}16741675export function getAgentRunState(1676 frame: number,1677 model: AgentRunModel = getAgentRunModel(),1678 playback: AgentRunPlayback = {},1679) {1680 const time = getAgentRunTime(frame, playback);1681 const { run, stage, timeline, layout } = model;1682 const elapsed = getAgentRunElapsed(time, timeline);1683 const planLocal = time - timeline.planStart;1684 const answerLocal = time - timeline.answerStart;1685 const answerRevealed = getAgentRunReveal(timeline.answerChunks, answerLocal);1686 const running = time - RUN_START;1687 const swap =1688 time >= timeline.thinkEnd ? expo((time - timeline.thinkEnd) / SWAP) : 0;1689 const thinking = "Thinking";1690 const blocks: AgentRunBlockState[] = [];1691 for (const block of layout.blocks) {1692 const next = blockState(1693 block,1694 run.answer,1695 timeline.answerChunks,1696 answerLocal,1697 answerRevealed,1698 );1699 if (next) blocks.push(next);1700 }1701 return {1702 time,1703 elapsed,1704 scroll: round(getAgentRunScroll(time, model.scroll)),1705 panel: {1706 width: stage.panelWidth,1707 height: stage.panelHeight,1708 viewport: stage.viewport,1709 unit: stage.unit,1710 opacity: round(easeOut((time + 1) / PANEL_IN)),1711 lift: round(PANEL_RISE * (1 - expo(time / PANEL_IN))),1712 },1713 header: {1714 title: run.title ?? "",1715 label: formatAgentRunSeconds(elapsed),1716 opacity: round(easeOut((running + 1) / STATUS_IN)),1717 spinner: getAgentRunSpinner(time, RUN_START, timeline.runEnd),1718 done: time >= timeline.runEnd,1719 },1720 bubble: {1721 y: layout.bubble.y,1722 height: layout.bubble.height,1723 lines: layout.bubble.lines,1724 opacity: round(easeOut((time - BUBBLE_AT + 1) / BUBBLE_IN)),1725 lift: round(BUBBLE_RISE * (1 - expo((time - BUBBLE_AT) / BUBBLE_IN))),1726 },1727 status: {1728 y: layout.status.y,1729 visible: running >= 0,1730 opacity: round(easeOut((running + 1) / STATUS_IN)),1731 thinking,1732 shimmer: getAgentRunShimmer(time, thinking.length),1733 thought: `Thought for ${Math.max(1, Math.round(timeline.thinkSeconds))}s`,1734 swap: round(swap),1735 lift: round(SWAP_RISE * (1 - swap)),1736 },1737 plan: layout.plan1738 ? planState(layout.plan, timeline.planChunks, planLocal)1739 : null,1740 tools: layout.tools ? toolsState(layout.tools, timeline, time) : null,1741 blocks,1742 revealed: {1743 plan: getAgentRunReveal(timeline.planChunks, planLocal),1744 answer: answerRevealed,1745 },1746 };1747}17481749export type AgentRunState = ReturnType<typeof getAgentRunState>;17501751interface AgentRunSurface {1752 panel: string;1753 border: string;1754 divider: string;1755 fg: string;1756 muted: string;1757 subtle: string;1758 surface: string;1759 surfaceBorder: string;1760 code: string;1761 track: string;1762 shadow: string;1763}17641765export interface AgentRunPalette extends AgentRunSurface {1766 accent: string;1767 accentTint: string;1768 accentText: string;1769}17701771export const AGENT_RUN_THEMES: Record<AgentRunTheme, AgentRunSurface> = {1772 light: {1773 panel: "#ffffff",1774 border: "#e4e4e0",1775 divider: "#ededea",1776 fg: "#1c1c1a",1777 muted: "#63635e",1778 subtle: "#9a9a94",1779 surface: "#f3f3f1",1780 surfaceBorder: "#e7e7e3",1781 code: "#f8f8f6",1782 track: "#e3e3df",1783 shadow: "0 1px 2px rgba(28, 28, 26, 0.06)",1784 },1785 dark: {1786 panel: "#161616",1787 border: "#2b2b2a",1788 divider: "#232322",1789 fg: "#ececea",1790 muted: "#a2a29d",1791 subtle: "#6d6d68",1792 surface: "#212120",1793 surfaceBorder: "#2e2e2d",1794 code: "#1c1c1b",1795 track: "#343433",1796 shadow: "0 1px 2px rgba(0, 0, 0, 0.5)",1797 },1798};17991800export function getAgentRunPalette(1801 theme = agentRunDefaults.theme,1802 accentColor = agentRunDefaults.accentColor,1803): AgentRunPalette {1804 const dark = theme === "dark";1805 const tint = dark ? 22 : 12;1806 return {1807 ...AGENT_RUN_THEMES[dark ? "dark" : "light"],1808 accent: accentColor,1809 accentTint: `color-mix(in srgb, ${accentColor} ${tint}%, transparent)`,1810 accentText: dark1811 ? `color-mix(in srgb, ${accentColor} 62%, #ffffff)`1812 : accentColor,1813 };1814}18151816type IconNode =1817 | { tag: "path"; d: string }1818 | { tag: "circle"; cx: number; cy: number; r: number }1819 | { tag: "ellipse"; cx: number; cy: number; rx: number; ry: number }1820 | {1821 tag: "rect";1822 x: number;1823 y: number;1824 width: number;1825 height: number;1826 rx: number;1827 };18281829type IconName = AgentRunIcon | "copy";18301831const ICONS: Record<IconName, readonly IconNode[]> = {1832 chart: [1833 { tag: "path", d: "M3 3v16a2 2 0 0 0 2 2h16" },1834 { tag: "path", d: "M18 17V9" },1835 { tag: "path", d: "M13 17V5" },1836 { tag: "path", d: "M8 17v-3" },1837 ],1838 database: [1839 { tag: "ellipse", cx: 12, cy: 5, rx: 9, ry: 3 },1840 { tag: "path", d: "M3 5V19A9 3 0 0 0 21 19V5" },1841 { tag: "path", d: "M3 12A9 3 0 0 0 21 12" },1842 ],1843 search: [1844 { tag: "path", d: "m21 21-4.34-4.34" },1845 { tag: "circle", cx: 11, cy: 11, r: 8 },1846 ],1847 book: [1848 { tag: "path", d: "M12 7v14" },1849 {1850 tag: "path",1851 d: "M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",1852 },1853 ],1854 globe: [1855 { tag: "circle", cx: 12, cy: 12, r: 10 },1856 { tag: "path", d: "M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20" },1857 { tag: "path", d: "M2 12h20" },1858 ],1859 terminal: [1860 { tag: "path", d: "M12 19h8" },1861 { tag: "path", d: "m4 17 6-6-6-6" },1862 ],1863 file: [1864 {1865 tag: "path",1866 d: "M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",1867 },1868 { tag: "path", d: "M14 2v5a1 1 0 0 0 1 1h5" },1869 { tag: "path", d: "M10 9H8" },1870 { tag: "path", d: "M16 13H8" },1871 { tag: "path", d: "M16 17H8" },1872 ],1873 copy: [1874 { tag: "rect", x: 8, y: 8, width: 14, height: 14, rx: 2 },1875 {1876 tag: "path",1877 d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",1878 },1879 ],1880};18811882function Icon({1883 name,1884 size,1885 color,1886}: {1887 name: IconName;1888 size: number;1889 color: string;1890}) {1891 return (1892 <svg1893 width={size}1894 height={size}1895 viewBox="0 0 24 24"1896 fill="none"1897 stroke={color}1898 strokeWidth={2}1899 strokeLinecap="round"1900 strokeLinejoin="round"1901 style={{ display: "block", flexShrink: 0 }}1902 >1903 {ICONS[name].map((node, index) => {1904 if (node.tag === "path") return <path key={index} d={node.d} />;1905 if (node.tag === "circle") {1906 return <circle key={index} cx={node.cx} cy={node.cy} r={node.r} />;1907 }1908 if (node.tag === "ellipse") {1909 return (1910 <ellipse1911 key={index}1912 cx={node.cx}1913 cy={node.cy}1914 rx={node.rx}1915 ry={node.ry}1916 />1917 );1918 }1919 return (1920 <rect1921 key={index}1922 x={node.x}1923 y={node.y}1924 width={node.width}1925 height={node.height}1926 rx={node.rx}1927 />1928 );1929 })}1930 </svg>1931 );1932}19331934function Spinner({1935 state,1936 size,1937 palette,1938}: {1939 state: AgentRunSpinnerState;1940 size: number;1941 palette: AgentRunPalette;1942}) {1943 const active = 1 - state.done;1944 return (1945 <svg1946 width={size}1947 height={size}1948 viewBox="0 0 24 24"1949 fill="none"1950 strokeWidth={2}1951 strokeLinecap="round"1952 strokeLinejoin="round"1953 style={{ display: "block", flexShrink: 0 }}1954 >1955 <circle cx={12} cy={12} r={10} stroke={palette.track} opacity={active} />1956 <circle1957 cx={12}1958 cy={12}1959 r={10}1960 stroke={palette.accent}1961 opacity={active}1962 strokeDasharray={`${round(state.arc * CIRCLE)} ${round(CIRCLE)}`}1963 transform={`rotate(${state.angle} 12 12)`}1964 />1965 <circle1966 cx={12}1967 cy={12}1968 r={10}1969 stroke={palette.muted}1970 opacity={state.done}1971 />1972 <path1973 d="m9 12 2 2 4-4"1974 stroke={palette.muted}1975 strokeDasharray={round(CHECK_LENGTH)}1976 strokeDashoffset={round(CHECK_LENGTH * (1 - state.check))}1977 opacity={state.check > 0 ? 1 : 0}1978 />1979 </svg>1980 );1981}19821983function spanStyle(1984 span: AgentRunSpan,1985 palette: AgentRunPalette,1986): CSSProperties {1987 if (span.kind === "bold") return { fontWeight: 600 };1988 if (span.kind === "code") {1989 return {1990 fontFamily: MONO,1991 fontSize: "0.875em",1992 padding: "1px 5px",1993 borderRadius: 5,1994 background: palette.surface,1995 border: `1px solid ${palette.surfaceBorder}`,1996 };1997 }1998 if (span.kind === "cite") {1999 return {2000 display: "inline-flex",2001 alignItems: "center",2002 justifyContent: "center",2003 minWidth: 18,2004 height: 18,2005 padding: "0 5px",2006 marginLeft: 2,2007 borderRadius: 9,2008 boxSizing: "border-box",2009 background: palette.accentTint,2010 color: palette.accentText,2011 fontSize: 11.5,2012 fontWeight: 600,2013 lineHeight: "18px",2014 fontVariantNumeric: "tabular-nums",2015 verticalAlign: "middle",2016 opacity: span.opacity,2017 transform: `scale(${span.scale})`,2018 };2019 }2020 if (span.kind === "punct" || span.kind === "comment") {2021 return { color: palette.subtle };2022 }2023 if (span.kind === "string") return { color: palette.muted };2024 return {};2025}20262027function renderSpans(spans: readonly AgentRunSpan[], palette: AgentRunPalette) {2028 return spans.map((span, index) => (2029 <span key={index} style={spanStyle(span, palette)}>2030 {span.fragments.map((fragment, part) => (2031 <span2032 key={part}2033 style={2034 fragment.opacity < 1 ? { opacity: fragment.opacity } : undefined2035 }2036 >2037 {fragment.text}2038 </span>2039 ))}2040 </span>2041 ));2042}20432044function AnswerBlock({2045 block,2046 palette,2047}: {2048 block: AgentRunBlockState;2049 palette: AgentRunPalette;2050}) {2051 if (block.kind === "code") {2052 return (2053 <div2054 style={{2055 position: "absolute",2056 top: block.y,2057 left: 0,2058 width: COLUMN,2059 height: block.height,2060 opacity: block.opacity,2061 overflow: "hidden",2062 boxSizing: "border-box",2063 border: `1px solid ${palette.surfaceBorder}`,2064 borderRadius: 10,2065 background: palette.code,2066 }}2067 >2068 <div2069 style={{2070 height: CODE_HEAD,2071 boxSizing: "border-box",2072 display: "flex",2073 alignItems: "center",2074 justifyContent: "space-between",2075 padding: "0 12px 0 16px",2076 borderBottom: `1px solid ${palette.divider}`,2077 fontFamily: MONO,2078 fontSize: 12.5,2079 color: palette.muted,2080 }}2081 >2082 <span>{block.lang}</span>2083 <Icon name="copy" size={14} color={palette.subtle} />2084 </div>2085 {block.lines.map((line) => (2086 <div2087 key={line.key}2088 style={{2089 position: "absolute",2090 top: CODE_HEAD + CODE_PAD - 1 + line.y,2091 left: 16,2092 height: line.height,2093 lineHeight: `${line.height}px`,2094 fontFamily: MONO,2095 fontSize: CODE_SIZE,2096 whiteSpace: "pre",2097 color: palette.fg,2098 }}2099 >2100 {renderSpans(line.spans, palette)}2101 </div>2102 ))}2103 </div>2104 );2105 }2106 if (block.kind === "heading") {2107 const spec = HEADINGS[block.level];2108 const from = BODY_SIZE / spec.size;2109 const scale = block.styled ? from + (1 - from) * block.morph : 1;2110 return (2111 <div>2112 {block.lines.map((line, index) => (2113 <div2114 key={line.key}2115 style={{2116 position: "absolute",2117 top: block.y + line.y,2118 left: 0,2119 height: line.height,2120 display: "flex",2121 alignItems: "center",2122 whiteSpace: "pre",2123 }}2124 >2125 {index === 0 && block.mark.length > 0 && block.morph < 1 ? (2126 <span2127 style={{2128 maxWidth: block.markWidth * (1 - block.morph),2129 overflow: "hidden",2130 flexShrink: 0,2131 opacity: 1 - block.morph,2132 fontSize: BODY_SIZE,2133 color: palette.subtle,2134 }}2135 >2136 {block.mark}2137 </span>2138 ) : null}2139 <span2140 style={{2141 fontSize: block.styled ? spec.size : BODY_SIZE,2142 fontWeight: Math.round(400 + 200 * block.morph),2143 lineHeight: 1.25,2144 transform: `scale(${round(scale)})`,2145 transformOrigin: "0 50%",2146 }}2147 >2148 {renderSpans(line.spans, palette)}2149 </span>2150 </div>2151 ))}2152 </div>2153 );2154 }2155 const indent = block.kind === "item" ? ITEM_INDENT : 0;2156 return (2157 <div>2158 {block.kind === "item" ? (2159 <div2160 style={{2161 position: "absolute",2162 top: block.y + BODY_LINE / 2 - 3,2163 left: 5,2164 width: 6,2165 height: 6,2166 borderRadius: 3,2167 background: palette.fg,2168 opacity: block.dotOpacity,2169 transform: `scale(${block.dot})`,2170 }}2171 />2172 ) : null}2173 {block.lines.map((line) => (2174 <div2175 key={line.key}2176 style={{2177 position: "absolute",2178 top: block.y + line.y,2179 left: indent,2180 height: line.height,2181 lineHeight: `${line.height}px`,2182 whiteSpace: "pre",2183 }}2184 >2185 {renderSpans(line.spans, palette)}2186 </div>2187 ))}2188 </div>2189 );2190}21912192function Header({2193 header,2194 palette,2195}: {2196 header: AgentRunState["header"];2197 palette: AgentRunPalette;2198}) {2199 return (2200 <div2201 style={{2202 height: HEADER_H,2203 boxSizing: "border-box",2204 display: "flex",2205 alignItems: "center",2206 justifyContent: "space-between",2207 gap: 16,2208 padding: `0 ${PAD_X}px`,2209 borderBottom: `1px solid ${palette.divider}`,2210 }}2211 >2212 <span2213 style={{2214 minWidth: 0,2215 fontSize: 14,2216 fontWeight: 500,2217 whiteSpace: "nowrap",2218 overflow: "hidden",2219 textOverflow: "ellipsis",2220 }}2221 >2222 {header.title}2223 </span>2224 <div2225 style={{2226 display: "flex",2227 alignItems: "center",2228 gap: 7,2229 flexShrink: 0,2230 opacity: header.opacity,2231 }}2232 >2233 <Spinner state={header.spinner} size={14} palette={palette} />2234 <span2235 style={{2236 minWidth: 38,2237 fontSize: 13,2238 color: palette.muted,2239 fontVariantNumeric: "tabular-nums",2240 textAlign: "right",2241 }}2242 >2243 {header.label}2244 </span>2245 </div>2246 </div>2247 );2248}22492250function Bubble({2251 bubble,2252 palette,2253}: {2254 bubble: AgentRunState["bubble"];2255 palette: AgentRunPalette;2256}) {2257 return (2258 <div2259 style={{2260 position: "absolute",2261 top: bubble.y,2262 right: 0,2263 padding: `${BUBBLE_PAD_Y}px ${BUBBLE_PAD_X}px`,2264 borderRadius: 18,2265 background: palette.surface,2266 fontSize: BUBBLE_SIZE,2267 lineHeight: `${BUBBLE_LINE}px`,2268 whiteSpace: "pre",2269 opacity: bubble.opacity,2270 transform: `translateY(${bubble.lift}px)`,2271 }}2272 >2273 {bubble.lines.map((line, index) => (2274 <div key={index}>{line}</div>2275 ))}2276 </div>2277 );2278}22792280function Status({2281 status,2282 palette,2283}: {2284 status: AgentRunState["status"];2285 palette: AgentRunPalette;2286}) {2287 if (!status.visible) return null;2288 return (2289 <div2290 style={{2291 position: "absolute",2292 top: status.y,2293 left: 0,2294 width: COLUMN,2295 height: STATUS_H,2296 fontSize: 15,2297 fontWeight: 500,2298 lineHeight: `${STATUS_H}px`,2299 whiteSpace: "pre",2300 opacity: status.opacity,2301 }}2302 >2303 {status.swap < 1 ? (2304 <span2305 style={{2306 position: "absolute",2307 top: 0,2308 left: 0,2309 opacity: 1 - status.swap,2310 }}2311 >2312 {status.shimmer.map((level, index) => (2313 <span key={index} style={{ opacity: level }}>2314 {status.thinking[index]}2315 </span>2316 ))}2317 </span>2318 ) : null}2319 {status.swap > 0 ? (2320 <span2321 style={{2322 position: "absolute",2323 top: 0,2324 left: 0,2325 color: palette.muted,2326 opacity: status.swap,2327 transform: `translateY(${status.lift}px)`,2328 }}2329 >2330 {status.thought}2331 </span>2332 ) : null}2333 </div>2334 );2335}23362337function Plan({2338 plan,2339 palette,2340}: {2341 plan: NonNullable<AgentRunState["plan"]>;2342 palette: AgentRunPalette;2343}) {2344 return (2345 <div2346 style={{2347 position: "absolute",2348 top: plan.y,2349 left: 0,2350 width: COLUMN,2351 fontSize: PLAN_SIZE,2352 color: palette.muted,2353 }}2354 >2355 <div2356 style={{2357 position: "absolute",2358 top: 0,2359 left: 0,2360 width: 2,2361 height: plan.rule,2362 borderRadius: 1,2363 background: palette.track,2364 }}2365 />2366 {plan.items.map((item) => (2367 <div key={item.key}>2368 <span2369 style={{2370 position: "absolute",2371 top: item.y,2372 left: 14,2373 lineHeight: `${PLAN_LINE}px`,2374 color: palette.subtle,2375 fontVariantNumeric: "tabular-nums",2376 opacity: item.numberOpacity,2377 }}2378 >2379 {`${item.index + 1}.`}2380 </span>2381 {item.lines.map((line) => (2382 <div2383 key={line.key}2384 style={{2385 position: "absolute",2386 top: item.y + line.y,2387 left: PLAN_INDENT,2388 height: line.height,2389 lineHeight: `${line.height}px`,2390 whiteSpace: "pre",2391 }}2392 >2393 {renderSpans(line.spans, palette)}2394 </div>2395 ))}2396 </div>2397 ))}2398 </div>2399 );2400}24012402function chipStyle(2403 palette: AgentRunPalette,2404 pop: { opacity: number; scale: number },2405 padding: string,2406): CSSProperties {2407 return {2408 display: "inline-flex",2409 alignItems: "center",2410 gap: 5,2411 height: 24,2412 boxSizing: "border-box",2413 padding,2414 borderRadius: 7,2415 border: `1px solid ${palette.surfaceBorder}`,2416 background: palette.surface,2417 fontSize: CHIP_SIZE,2418 color: palette.muted,2419 fontVariantNumeric: "tabular-nums",2420 whiteSpace: "nowrap",2421 opacity: pop.opacity,2422 transform: `scale(${pop.scale})`,2423 };2424}24252426type AgentRunRowState = NonNullable<AgentRunState["tools"]>["rows"][number];24272428function ToolRow({2429 row,2430 palette,2431}: {2432 row: AgentRunRowState;2433 palette: AgentRunPalette;2434}) {2435 const chips = row.chips.filter((chip) => chip.visible);2436 return (2437 <div2438 style={{2439 position: "absolute",2440 top: row.y,2441 left: 0,2442 right: 0,2443 height: row.height,2444 overflow: "hidden",2445 boxSizing: "border-box",2446 borderTop: row.divider ? `1px solid ${palette.divider}` : undefined,2447 }}2448 >2449 <div2450 style={{2451 height: ROW_H,2452 display: "flex",2453 alignItems: "center",2454 gap: 10,2455 padding: "0 14px",2456 opacity: row.content,2457 }}2458 >2459 <Icon name={row.icon} size={16} color={palette.muted} />2460 <span2461 style={{2462 flexShrink: 0,2463 fontSize: 15,2464 fontWeight: 500,2465 whiteSpace: "nowrap",2466 }}2467 >2468 {row.name}2469 </span>2470 <span2471 style={{2472 flex: 1,2473 minWidth: 0,2474 fontSize: 15,2475 color: palette.muted,2476 whiteSpace: "nowrap",2477 overflow: "hidden",2478 textOverflow: "ellipsis",2479 }}2480 >2481 {row.detail}2482 </span>2483 <span2484 style={{2485 fontSize: 13,2486 color: palette.muted,2487 fontVariantNumeric: "tabular-nums",2488 opacity: row.label,2489 }}2490 >2491 {row.duration}2492 </span>2493 <Spinner state={row.spinner} size={16} palette={palette} />2494 </div>2495 {row.sources ? (2496 <div2497 style={{2498 display: "flex",2499 gap: CHIP_GAP,2500 height: CHIPS_H,2501 padding: "0 14px 0 40px",2502 opacity: row.content,2503 }}2504 >2505 {chips.map((chip, index) => (2506 <span2507 key={`${index}-${chip.label}`}2508 style={chipStyle(palette, chip, "0 9px 0 7px")}2509 >2510 <Icon name={chip.icon} size={12} color={palette.subtle} />2511 {chip.label}2512 </span>2513 ))}2514 {row.more?.visible ? (2515 <span style={chipStyle(palette, row.more, "0 9px")}>2516 {`+${row.more.count}`}2517 </span>2518 ) : null}2519 </div>2520 ) : null}2521 </div>2522 );2523}25242525function Tools({2526 tools,2527 palette,2528}: {2529 tools: NonNullable<AgentRunState["tools"]>;2530 palette: AgentRunPalette;2531}) {2532 if (tools.rows.length === 0) return null;2533 return (2534 <div2535 style={{2536 position: "absolute",2537 top: tools.y,2538 left: 0,2539 width: COLUMN,2540 height: tools.height,2541 boxSizing: "border-box",2542 overflow: "hidden",2543 border: `1px solid ${palette.surfaceBorder}`,2544 borderRadius: 12,2545 }}2546 >2547 {tools.rows.map((row) => (2548 <ToolRow key={row.key} row={row} palette={palette} />2549 ))}2550 </div>2551 );2552}25532554export function AgentRun({2555 run = agentRunDefaults.run,2556 theme = agentRunDefaults.theme,2557 accentColor = agentRunDefaults.accentColor,2558 compression = agentRunDefaults.compression,2559 seed = agentRunDefaults.seed,2560 speed = agentRunDefaults.speed,2561 className,2562}: AgentRunProps) {2563 const frame = useCurrentFrame();2564 const { width, height, fps } = useVideoConfig();2565 const model = useMemo(2566 () => getAgentRunModel(run, { seed, compression, width, height }),2567 [run, seed, compression, width, height],2568 );2569 const state = getAgentRunState(frame, model, { fps, speed });2570 const palette = getAgentRunPalette(theme, accentColor);2571 const { panel } = state;25722573 return (2574 <div className={className} style={{ position: "absolute", inset: 0 }}>2575 <div2576 style={{2577 position: "absolute",2578 left: "50%",2579 top: "50%",2580 width: panel.width,2581 height: panel.height,2582 translate: "-50% -50%",2583 scale: `${panel.unit}`,2584 }}2585 >2586 <div2587 style={{2588 position: "relative",2589 width: "100%",2590 height: "100%",2591 boxSizing: "border-box",2592 overflow: "hidden",2593 opacity: panel.opacity,2594 transform: `translateY(${panel.lift}px)`,2595 background: palette.panel,2596 border: `1px solid ${palette.border}`,2597 borderRadius: 18,2598 boxShadow: palette.shadow,2599 color: palette.fg,2600 fontFamily: SANS,2601 fontSize: BODY_SIZE,2602 WebkitFontSmoothing: "antialiased",2603 }}2604 >2605 <Header header={state.header} palette={palette} />2606 <div2607 style={{2608 position: "relative",2609 height: panel.viewport,2610 overflow: "hidden",2611 }}2612 >2613 <div2614 style={{2615 position: "absolute",2616 top: 0,2617 left: PAD_X,2618 width: COLUMN,2619 transform: `translateY(${-state.scroll}px)`,2620 }}2621 >2622 <Bubble bubble={state.bubble} palette={palette} />2623 <Status status={state.status} palette={palette} />2624 {state.plan ? <Plan plan={state.plan} palette={palette} /> : null}2625 {state.tools ? (2626 <Tools tools={state.tools} palette={palette} />2627 ) : null}2628 {state.blocks.map((block) => (2629 <AnswerBlock key={block.key} block={block} palette={palette} />2630 ))}2631 </div>2632 </div>2633 </div>2634 </div>2635 </div>2636 );2637}







