From be8b5b414655dd142f198b6e0e88cac5afb9d42d Mon Sep 17 00:00:00 2001 From: Forge Date: Tue, 17 Nov 2026 18:33:42 +0800 Subject: [PATCH 01/21] feat(core): agent run and governance kit, generative UI catalog to 24 blocks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - core: Reasoning, ThinkingIndicator, ToolCall(Group), Question, Approval, CitedAnswer, PromptQueue, RunControls, AttachmentList, AgentWelcome, AgentPlan, AgentTrail, ChangeLedger, AgentCheckpoints, AutonomySelector, AgentInbox, RunningNow, AwaySummary, ContextUsage, TraceWaterfall, AgentTree, AgentLanes; MessageActions gains versions, edit and feedback reasons; AgentParts renders reasoning and tool calls with them - AgentPanel, ChoiceCard, ConfirmCard and RunProgress move from the agent package to core - agent: catalog grows from 8 to 24 blocks (record, list, timeline, compare, flow, progress, funnel, form, questions, confirm, plan, actions…); ui accepts a component list and the prompt lines are generated from the catalog Co-Authored-By: Claude Opus 5.5 --- agent/package.json | 4 +- agent/src/catalog/blocks.ts | 12 +- agent/src/catalog/render.tsx | 83 ++-- agent/src/catalog/schema.ts | 167 +++++++- agent/src/catalog/widgets.tsx | 380 ++++++++++++++++++ agent/src/forge-agent.tsx | 3 +- agent/src/index.ts | 7 +- agent/src/interact.tsx | 145 ------- agent/src/server/index.ts | 34 +- agent/test/blocks.test.ts | 27 +- agent/test/server.test.ts | 12 + core/package.json | 2 +- core/scripts/check-package.mjs | 11 +- core/scripts/package-api-snapshot.mjs | 119 +++++- .../ui/agent/agent-conversation.tsx | 83 ++-- .../components/ui/agent/agent-governance.tsx | 227 +++++++++++ .../src/components/ui/agent/agent-observe.tsx | 314 +++++++++++++++ core/src/components/ui/agent/agent-ops.tsx | 230 +++++++++++ .../src/components/ui/agent/agent-panel.tsx | 12 +- core/src/components/ui/agent/agent-parts.tsx | 98 ++--- core/src/components/ui/agent/agent-run.tsx | 262 ++++++++++++ core/src/components/ui/agent/agent-utils.ts | 44 ++ .../src/components/ui/agent/agent-welcome.tsx | 55 +++ core/src/components/ui/agent/approval.tsx | 192 +++++++++ core/src/components/ui/agent/cited-answer.tsx | 123 ++++++ .../components/ui/agent/composer-parts.tsx | 198 +++++++++ core/src/components/ui/agent/index.ts | 36 ++ core/src/components/ui/agent/question.tsx | 217 ++++++++++ core/src/components/ui/agent/thinking.tsx | 158 ++++++++ core/src/components/ui/agent/tool-call.tsx | 165 ++++++++ core/src/components/ui/index.ts | 96 +++++ core/src/styles/tokens.css | 10 + core/test/agent-conversation.test.tsx | 12 +- core/test/agent-kit.test.tsx | 197 +++++++++ src/app/api/agent/route.ts | 5 +- 35 files changed, 3421 insertions(+), 319 deletions(-) create mode 100644 agent/src/catalog/widgets.tsx delete mode 100644 agent/src/interact.tsx create mode 100644 core/src/components/ui/agent/agent-governance.tsx create mode 100644 core/src/components/ui/agent/agent-observe.tsx create mode 100644 core/src/components/ui/agent/agent-ops.tsx rename agent/src/panel.tsx => core/src/components/ui/agent/agent-panel.tsx (92%) create mode 100644 core/src/components/ui/agent/agent-run.tsx create mode 100644 core/src/components/ui/agent/agent-utils.ts create mode 100644 core/src/components/ui/agent/agent-welcome.tsx create mode 100644 core/src/components/ui/agent/approval.tsx create mode 100644 core/src/components/ui/agent/cited-answer.tsx create mode 100644 core/src/components/ui/agent/composer-parts.tsx create mode 100644 core/src/components/ui/agent/question.tsx create mode 100644 core/src/components/ui/agent/thinking.tsx create mode 100644 core/src/components/ui/agent/tool-call.tsx create mode 100644 core/test/agent-kit.test.tsx diff --git a/agent/package.json b/agent/package.json index 7b8df161..aa5a880c 100644 --- a/agent/package.json +++ b/agent/package.json @@ -1,6 +1,6 @@ { "name": "@forge-ui-official/agent", - "version": "0.4.0", + "version": "0.5.0", "description": "Forge Agent — an embeddable AI agent that understands your product, calls its tools and answers with Forge components", "license": "MIT", "private": false, @@ -37,7 +37,7 @@ "prepublishOnly": "pnpm build && pnpm typecheck && pnpm test" }, "peerDependencies": { - "@forge-ui-official/core": ">=0.8.3", + "@forge-ui-official/core": ">=0.9.0", "react": ">=19", "react-dom": ">=19" }, diff --git a/agent/src/catalog/blocks.ts b/agent/src/catalog/blocks.ts index c81a534f..41baa44f 100644 --- a/agent/src/catalog/blocks.ts +++ b/agent/src/catalog/blocks.ts @@ -1,19 +1,11 @@ -import { uiSchemas, type UiToolName } from "./schema"; +import { BLOCK_OF, uiSchemas, uiToolNames, type UiToolName } from "./schema"; /** * The model writes components inside its answer as fenced blocks (```forge:cards + JSON), so a whole * answer, components included, comes from one model step. Splitting the text turns each block into * a component; plain code fences become code or a copyable command. */ -export const BLOCK_NAMES: Record = { - "forge:cards": "show_cards", - "forge:steps": "show_steps", - "forge:table": "show_table", - "forge:metrics": "show_metrics", - "forge:chart": "show_chart", - "forge:choices": "show_choices", - "forge:followups": "suggest_followups", -}; +export const BLOCK_NAMES: Record = Object.fromEntries(uiToolNames.map(name => [BLOCK_OF[name], name])); export type Segment = | { kind: "text"; text: string } diff --git a/agent/src/catalog/render.tsx b/agent/src/catalog/render.tsx index 4b90851b..c25c0be4 100644 --- a/agent/src/catalog/render.tsx +++ b/agent/src/catalog/render.tsx @@ -1,10 +1,10 @@ "use client"; import { useEffect, useRef, useState, type ReactNode } from "react"; -import { BarChart, DataTable, PromptSuggestions, SmoothLineChart, StatCard, type ColumnDef } from "@forge-ui-official/core"; +import { ChoiceCard, DataTable, PromptSuggestions, StatCard, type ColumnDef } from "@forge-ui-official/core"; import { CheckCircleLinear, CopyLinear } from "@forge-ui-official/core/icons"; -import { ChoiceCard } from "../interact"; import { uiSchemas, type UiSpec, type UiToolName } from "./schema"; +import { Actions, Callout, Changes, Chart, Compare, Confirm, Flow, Form, Funnel, Images, ListBlock, Plan, Progress, Questions, RecordCard, Tags, Timeline } from "./widgets"; type Row = Record; @@ -147,20 +147,6 @@ function Metrics({ items }: UiSpec<"show_metrics">) { ); } -function Chart({ title, type, labels, series }: UiSpec<"show_chart">) { - return ( -
- {title &&

{title}

} -
- {type === "bar" - ? ({ label, value: series[0]?.data[index] ?? 0 }))} ariaLabel={title} /> - : ({ label: item.label, data: item.data }))} ariaLabel={title} />} -
-
{labels[0]}{labels[labels.length - 1]}
-
- ); -} - function Steps({ title, steps }: UiSpec<"show_steps">) { return (
@@ -206,6 +192,8 @@ function groundCards(spec: UiSpec<"show_cards">, sources: Sources): UiSpec<"show function numbersOf(name: UiToolName, spec: unknown): (string | number)[] { if (name === "show_metrics") return (spec as UiSpec<"show_metrics">).items.map(item => item.value.replace(/[^0-9.\-]/g, "")).filter(Boolean); if (name === "show_chart") return (spec as UiSpec<"show_chart">).series.flatMap(item => item.data); + if (name === "show_progress") return (spec as UiSpec<"show_progress">).items.map(item => item.value); + if (name === "show_funnel") return (spec as UiSpec<"show_funnel">).stages.map(stage => stage.value); if (name === "show_table") { const table = spec as UiSpec<"show_table">; const numeric = table.columns.filter(column => column.numeric).map(column => column.key); @@ -214,15 +202,33 @@ function numbersOf(name: UiToolName, spec: unknown): (string | number)[] { return []; } +// Links and images must be this site's pages or appear in a tool result. +function ground(name: UiToolName, data: unknown, sources: Sources): unknown { + const href = (value?: string) => (value && (value.startsWith("/") || sources.has(value)) ? value : undefined); + switch (name) { + case "show_cards": return groundCards(data as UiSpec<"show_cards">, sources); + case "show_record": { const spec = data as UiSpec<"show_record">; return { ...spec, href: href(spec.href) }; } + case "show_list": { const spec = data as UiSpec<"show_list">; return { ...spec, items: spec.items.map(item => ({ ...item, href: href(item.href) })) }; } + case "show_actions": { const spec = data as UiSpec<"show_actions">; return { ...spec, items: spec.items.map(item => ({ ...item, href: href(item.href) })).filter(item => item.href || item.ask) }; } + case "show_images": { + const spec = data as UiSpec<"show_images">; + const items = spec.items.filter(item => sources.has(item.src)); + return items.length ? { items } : undefined; + } + default: return data; + } +} + /** * Renders one catalog tool call. Inputs are validated again here, so a part replayed from storage or a - * malformed call shows nothing rather than a broken component. Numbers in tables, metrics and charts - * must come from tool results in the same answer; otherwise a note replaces the figure. + * malformed call shows nothing rather than a broken component. Numbers in tables, metrics, charts, + * progress and funnels must come from tool results in the same answer; otherwise a note replaces them. */ export function renderCatalog(name: UiToolName, input: unknown, onAsk: (question: string) => void, sources: Sources, answer?: string): ReactNode { const parsed = uiSchemas[name].safeParse(input); if (!parsed.success) return null; - const data = name === "show_cards" ? groundCards(parsed.data as UiSpec<"show_cards">, sources) : parsed.data; + const data = ground(name, parsed.data, sources); + if (data === undefined) return null; if (numbersOf(name, data).some(value => !sources.has(value))) { return

这组数字没能和查询结果核对上,已省略。

; } @@ -231,23 +237,38 @@ export function renderCatalog(name: UiToolName, input: unknown, onAsk: (question } function catalogContent(name: UiToolName, data: unknown, onAsk: (question: string) => void, answer?: string): ReactNode { - const parsed = { data }; switch (name) { - case "show_cards": return )} />; + case "show_cards": return )} />; case "show_code": { - const spec = parsed.data as UiSpec<"show_code">; - return ; + const code = data as UiSpec<"show_code">; + return ; } - case "show_table": return )} />; - case "show_metrics": return )} />; - case "show_chart": return )} />; - case "show_steps": return )} />; + case "show_steps": return )} />; + case "show_callout": return )} />; + case "show_record": return )} />; + case "show_list": return )} />; + case "show_timeline": return )} />; + case "show_tags": return )} />; + case "show_compare": return )} />; + case "show_changes": return )} />; + case "show_flow": return )} />; + case "show_images": return )} />; + case "show_table": return
)} />; + case "show_metrics": return )} />; + case "show_chart": return )} />; + case "show_progress": return )} />; + case "show_funnel": return )} />; case "show_choices": { // A pick is sent as the user's next message; once answered the card shows the answer. - const spec = parsed.data as UiSpec<"show_choices">; - const options = spec.options.map(option => ({ id: option.label, ...option })); - return { if ("optionId" in picked) onAsk(picked.optionId); }} />; + const choices = data as UiSpec<"show_choices">; + const options = choices.options.map(option => ({ id: option.label, ...option })); + return { if ("optionId" in picked) onAsk(picked.optionId); }} />; } - case "suggest_followups": return ).questions} onSelect={onAsk} />; + case "show_questions": return )} answer={answer} onAsk={onAsk} />; + case "show_form": return
)} answer={answer} onAsk={onAsk} />; + case "show_confirm": return )} answer={answer} onAsk={onAsk} />; + case "show_plan": return )} answer={answer} onAsk={onAsk} />; + case "show_actions": return )} onAsk={onAsk} />; + case "suggest_followups": return ).questions} onSelect={onAsk} />; } } diff --git a/agent/src/catalog/schema.ts b/agent/src/catalog/schema.ts index bff045cf..37142439 100644 --- a/agent/src/catalog/schema.ts +++ b/agent/src/catalog/schema.ts @@ -4,8 +4,10 @@ import { z } from "zod"; // before anything renders, and the client draws them with Forge components. const text = (max: number) => z.string().trim().min(1).max(max); +const tone = z.enum(["info", "success", "warning", "danger"]); export const uiSchemas = { + /* ── Display ── */ show_cards: z.object({ title: text(60).optional(), items: z.array(z.object({ @@ -22,6 +24,51 @@ export const uiSchemas = { filename: text(80).optional(), code: z.string().min(1).max(6000), }), + show_steps: z.object({ + title: text(60).optional(), + steps: z.array(z.object({ title: text(80), detail: text(400).optional(), code: z.string().max(2000).optional() })).min(1).max(10), + }), + show_callout: z.object({ + tone, + title: text(60).optional(), + text: text(400), + }), + show_record: z.object({ + title: text(60), + subtitle: text(80).optional(), + status: text(20).optional(), + fields: z.array(z.object({ label: text(20), value: text(120) })).min(1).max(12), + href: z.string().max(300).optional(), + }), + show_list: z.object({ + title: text(60).optional(), + items: z.array(z.object({ title: text(80), description: text(160).optional(), meta: text(30).optional(), tag: text(20).optional(), href: z.string().max(300).optional() })).min(1).max(12), + }), + show_timeline: z.object({ + title: text(60).optional(), + events: z.array(z.object({ time: text(30), title: text(80), detail: text(200).optional(), tone: tone.optional() })).min(1).max(12), + }), + show_tags: z.object({ + title: text(60).optional(), + tags: z.array(text(24)).min(1).max(20), + }), + show_compare: z.object({ + title: text(60).optional(), + items: z.array(z.object({ title: text(40), tag: text(20).optional(), points: z.array(text(80)).min(1).max(6), recommended: z.boolean().optional() })).min(2).max(4), + }), + show_changes: z.object({ + title: text(60).optional(), + fields: z.array(z.object({ label: text(30), before: z.string().max(120), after: z.string().max(120) })).min(1).max(12), + }), + show_flow: z.object({ + title: text(60).optional(), + nodes: z.array(z.object({ id: text(20), label: text(40), kind: z.enum(["start", "step", "decision", "end"]).optional() })).min(2).max(12), + edges: z.array(z.object({ from: text(20), to: text(20), label: text(20).optional() })).max(16), + }), + show_images: z.object({ + items: z.array(z.object({ src: z.string().max(300), caption: text(60).optional() })).min(1).max(8), + }), + /* ── Data ── */ show_table: z.object({ title: text(60).optional(), columns: z.array(z.object({ key: text(40), header: text(30), numeric: z.boolean().optional() })).min(1).max(8), @@ -37,18 +84,58 @@ export const uiSchemas = { }), show_chart: z.object({ title: text(60).optional(), - type: z.enum(["line", "bar"]), + type: z.enum(["line", "area", "bar", "hbar", "donut"]), labels: z.array(text(20)).min(2).max(60), series: z.array(z.object({ label: text(30), data: z.array(z.number()) })).min(1).max(4), }), - show_steps: z.object({ + show_progress: z.object({ title: text(60).optional(), - steps: z.array(z.object({ title: text(80), detail: text(400).optional(), code: z.string().max(2000).optional() })).min(1).max(10), + items: z.array(z.object({ label: text(30), value: z.number().min(0).max(100), note: text(40).optional() })).min(1).max(8), + }), + show_funnel: z.object({ + title: text(60).optional(), + stages: z.array(z.object({ label: text(20), value: z.number().min(0) })).min(2).max(8), }), + /* ── Asking and acting ── */ show_choices: z.object({ title: text(80), options: z.array(z.object({ label: text(60), description: text(120).optional() })).min(2).max(8), }), + show_questions: z.object({ + questions: z.array(z.object({ + title: text(80), + options: z.array(z.object({ label: text(60), description: text(120).optional() })).max(8), + multiple: z.boolean().optional(), + allowText: z.boolean().optional(), + })).min(1).max(4), + }), + show_form: z.object({ + title: text(60), + submitLabel: text(12).optional(), + fields: z.array(z.object({ + name: text(30), + label: text(30), + type: z.enum(["text", "textarea", "number", "date", "select", "multiselect", "switch"]), + options: z.array(text(40)).max(12).optional(), + required: z.boolean().optional(), + placeholder: text(60).optional(), + default: z.union([z.string().max(200), z.number(), z.boolean(), z.array(z.string().max(40))]).optional(), + })).min(1).max(10), + }), + show_confirm: z.object({ + title: text(80), + description: text(300).optional(), + risk: z.enum(["low", "medium", "high"]).optional(), + fields: z.array(z.object({ label: text(30), before: z.string().max(120).optional(), after: z.string().max(120) })).max(10).optional(), + confirmLabel: text(12).optional(), + }), + show_plan: z.object({ + title: text(60).optional(), + steps: z.array(z.object({ title: text(80), detail: text(200).optional() })).min(2).max(10), + }), + show_actions: z.object({ + items: z.array(z.object({ label: text(20), ask: text(80).optional(), href: z.string().max(300).optional(), primary: z.boolean().optional() })).min(1).max(4), + }), suggest_followups: z.object({ questions: z.array(text(40)).min(1).max(4), }), @@ -58,3 +145,77 @@ export type UiToolName = keyof typeof uiSchemas; export type UiSpec = z.infer<(typeof uiSchemas)[Name]>; export const uiToolNames = Object.keys(uiSchemas) as UiToolName[]; + +/** The fenced block name the model writes for each component: ```forge:table … ```. */ +export const BLOCK_OF: Record = { + show_cards: "forge:cards", + show_code: "forge:code", + show_steps: "forge:steps", + show_callout: "forge:callout", + show_record: "forge:record", + show_list: "forge:list", + show_timeline: "forge:timeline", + show_tags: "forge:tags", + show_compare: "forge:compare", + show_changes: "forge:changes", + show_flow: "forge:flow", + show_images: "forge:images", + show_table: "forge:table", + show_metrics: "forge:metrics", + show_chart: "forge:chart", + show_progress: "forge:progress", + show_funnel: "forge:funnel", + show_choices: "forge:choices", + show_questions: "forge:questions", + show_form: "forge:form", + show_confirm: "forge:confirm", + show_plan: "forge:plan", + show_actions: "forge:actions", + suggest_followups: "forge:followups", +}; + +/** One line per component for the system prompt: shape first, then when to use it. */ +export const BLOCK_GUIDE: Record = { + show_cards: `卡片:{"title"?, "items": [{"title", "description"?, "tag"?, "href"?, "preview"?, "code"?, "image"?}]},最多 8 项。preview 是能嵌入预览的站内页面路径,会显示成缩略图;code 是一行可复制的命令。`, + show_code: `代码:{"filename"?, "code"}。一般代码用普通 Markdown 代码块即可,要给文件名时用它。`, + show_steps: `步骤:{"title"?, "steps": [{"title", "detail"?, "code"?}]},教用户怎么做时用。`, + show_callout: `提示框:{"tone": "info"|"success"|"warning"|"danger", "title"?, "text"},只用于真正要提醒的一件事。`, + show_record: `单条记录:{"title", "subtitle"?, "status"?, "fields": [{"label", "value"}], "href"?},展示一个订单、账号、合同等的详情。`, + show_list: `列表:{"title"?, "items": [{"title", "description"?, "meta"?, "tag"?, "href"?}]},多条记录的摘要。`, + show_timeline: `时间线:{"title"?, "events": [{"time", "title", "detail"?, "tone"?}]},按时间排的经过、日志、进度。`, + show_tags: `标签:{"title"?, "tags": [...]}`, + show_compare: `方案对比:{"title"?, "items": [{"title", "tag"?, "points": [...], "recommended"?}]},2 到 4 个方案并排比较。`, + show_changes: `改动前后:{"title"?, "fields": [{"label", "before", "after"}]},说明改了什么。`, + show_flow: `流程图:{"title"?, "nodes": [{"id", "label", "kind"?: "start"|"step"|"decision"|"end"}], "edges": [{"from", "to", "label"?}]},讲审批流、业务流程时用。`, + show_images: `图片:{"items": [{"src", "caption"?}]},src 只用工具结果里的图片地址。`, + show_table: `表格:{"title"?, "columns": [{"key", "header", "numeric"?}], "rows": [{列 key: 值}]}`, + show_metrics: `指标:{"items": [{"label", "value", "change"?, "direction"?: "up"|"down"}]}`, + show_chart: `图表:{"title"?, "type": "line"|"area"|"bar"|"hbar"|"donut", "labels": [...], "series": [{"label", "data": [数字]}]}。趋势用 line/area,比较用 bar,排名用 hbar,占比用 donut(只取第一组数据)。`, + show_progress: `进度:{"title"?, "items": [{"label", "value": 0 到 100, "note"?}]},完成率、额度用量。`, + show_funnel: `漏斗:{"title"?, "stages": [{"label", "value"}]},转化各环节的数量。`, + show_choices: `让用户选:{"title", "options": [{"label", "description"?}]},2 到 8 项。要用户在几个明确方案里挑一个时用,用户点选后会作为下一条消息发来;问开放问题时直接用文字问。`, + show_questions: `一次问几件事:{"questions": [{"title", "options": [{"label", "description"?}], "multiple"?, "allowText"?}]},最多 4 题;缺好几项信息才能继续时用,答案会作为下一条消息发来。`, + show_form: `表单:{"title", "submitLabel"?, "fields": [{"name", "label", "type": "text"|"textarea"|"number"|"date"|"select"|"multiselect"|"switch", "options"?, "required"?, "placeholder"?, "default"?}]},让用户填一组结构化信息(例如新建记录);提交内容会作为下一条消息发来。`, + show_confirm: `请用户确认:{"title", "description"?, "risk"?: "low"|"medium"|"high", "fields"?: [{"label", "before"?, "after"}], "confirmLabel"?},在你要执行改动前用;用户的确认或取消会作为下一条消息发来。`, + show_plan: `执行计划:{"title"?, "steps": [{"title", "detail"?}]},多步任务开始前给用户看,用户可以增删改步骤,确认后计划会作为下一条消息发来。`, + show_actions: `操作按钮:{"items": [{"label", "ask"?, "href"?, "primary"?}]},最多 4 个;ask 是点了之后发出的消息,href 是要打开的链接。`, + suggest_followups: `后续问题:{"questions": [1 到 4 个短问题]},放在回答最后,正文里不要再列一遍。`, +}; + +/** The prompt lines for the enabled components. */ +export function catalogGuide(names: readonly UiToolName[] = uiToolNames) { + return names.map(name => ` - ${BLOCK_OF[name]} ${BLOCK_GUIDE[name]}`).join("\n"); +} + +// One worked example keeps the fence format exact; the first enabled component that has one is used. +const EXAMPLES: Partial> = { + show_cards: `{"items": [{"title": "订单列表", "tag": "页面", "description": "搜索、筛选、分页都已接好", "href": "/orders"}]}`, + show_table: `{"columns": [{"key": "name", "header": "客户"}, {"key": "amount", "header": "金额", "numeric": true}], "rows": [{"name": "华东分公司", "amount": 1280}]}`, + show_confirm: `{"title": "把张三的角色改为管理员", "risk": "medium", "fields": [{"label": "角色", "before": "成员", "after": "管理员"}]}`, +}; + +/** The prompt's example line for the enabled components, or nothing. */ +export function catalogExample(names: readonly UiToolName[]) { + const name = names.find(item => EXAMPLES[item]); + return name ? `- 例:\n\`\`\`${BLOCK_OF[name]}\n${EXAMPLES[name]}\n\`\`\`\n` : ""; +} diff --git a/agent/src/catalog/widgets.tsx b/agent/src/catalog/widgets.tsx new file mode 100644 index 00000000..6c1eda5a --- /dev/null +++ b/agent/src/catalog/widgets.tsx @@ -0,0 +1,380 @@ +"use client"; + +import { useState, type ReactNode } from "react"; +import { + AgentPlan, + Approval, + BarChart, + BarHorizontalChart, + Button, + DonutChart, + ProgressBar, + Question, + SmoothLineChart, + cn, + type PlanStep, +} from "@forge-ui-official/core"; +import { AltArrowRightLinear, CheckCircleLinear, DangerTriangleLinear, InfoCircleLinear } from "@forge-ui-official/core/icons"; +import type { UiSpec } from "./schema"; + +/** Components the model writes into its answer, beyond cards, tables and metrics (see render.tsx). */ + +const frame = "flex min-w-0 flex-col gap-2 rounded-xl border border-fg-grey-200 bg-background p-3"; +const Title = ({ children }: { children?: ReactNode }) => (children ?

{children}

: null); +const Answered = ({ children }: { children: ReactNode }) => ( +

{children}

+); +const safeHref = (href?: string) => (href && (/^\/(?!\/)/.test(href) || /^https:\/\//.test(href)) ? href : undefined); + +/* ── Display ── */ + +const TONE = { + info: { icon: InfoCircleLinear, style: "border-fg-blue-200 bg-fg-blue-50 text-fg-blue-800" }, + success: { icon: CheckCircleLinear, style: "border-fg-green-200 bg-fg-green-50 text-fg-green-700" }, + warning: { icon: DangerTriangleLinear, style: "border-fg-yellow-300 bg-fg-yellow-50 text-fg-yellow-900" }, + danger: { icon: DangerTriangleLinear, style: "border-fg-red-200 bg-fg-red-50 text-fg-red-700" }, +} as const; + +export function Callout({ tone, title, text }: UiSpec<"show_callout">) { + const { icon: Icon, style } = TONE[tone]; + return ( +
+ +
{title && {title}}{text}
+
+ ); +} + +export function RecordCard({ title, subtitle, status, fields, href }: UiSpec<"show_record">) { + const link = safeHref(href); + return ( +
+
+
+ {title} + {subtitle && {subtitle}} +
+ {status && {status}} +
+
+ {fields.map(field => ( +
{field.label}
{field.value}
+ ))} +
+ {link && 查看详情} +
+ ); +} + +export function ListBlock({ title, items }: UiSpec<"show_list">) { + return ( +
+ {title} +
    + {items.map(item => { + const link = safeHref(item.href); + const body = ( + <> + + {item.title} + {item.description && {item.description}} + + {item.tag && {item.tag}} + {item.meta && {item.meta}} + + ); + return
  • {link ? {body} :
    {body}
    }
  • ; + })} +
+
+ ); +} + +const DOT = { info: "bg-accent", success: "bg-fg-green-500", warning: "bg-fg-yellow-500", danger: "bg-fg-red" } as const; + +export function Timeline({ title, events }: UiSpec<"show_timeline">) { + return ( +
+ {title} +
    + {events.map((event, index) => ( +
  1. + {index < events.length - 1 &&
  2. + ))} +
+
+ ); +} + +export function Tags({ title, tags }: UiSpec<"show_tags">) { + return ( +
+ {title} +
{tags.map(tag => {tag})}
+
+ ); +} + +export function Compare({ title, items }: UiSpec<"show_compare">) { + return ( +
+ {title} +
+ {items.map(item => ( +
+
+ {item.title} + {item.recommended && 推荐} + {item.tag && !item.recommended && {item.tag}} +
+
    {item.points.map(point =>
  • ·{point}
  • )}
+
+ ))} +
+
+ ); +} + +export function Changes({ title, fields }: UiSpec<"show_changes">) { + return ( +
+ {title} +
+ {fields.map(field => ( +
+
{field.label}
+
{field.before || "空"} → {field.after || "空"}
+
+ ))} +
+
+ ); +} + +export function Flow({ title, nodes, edges }: UiSpec<"show_flow">) { + const byId = new Map(nodes.map(node => [node.id, node])); + return ( +
+ {title} +
    + {nodes.map(node => { + const out = edges.filter(edge => edge.from === node.id && byId.has(edge.to)); + const decision = node.kind === "decision"; + return ( +
  1. + {node.label} + {out.map(edge => ( + + ↓{edge.label && {edge.label}}到「{byId.get(edge.to)?.label}」 + + ))} +
  2. + ); + })} +
+
+ ); +} + +export function Images({ items }: UiSpec<"show_images">) { + return ( +
1 ? "grid-cols-2" : "grid-cols-1")}> + {items.map(item => ( +
+ {/* eslint-disable-next-line @next/next/no-img-element -- the package does not depend on Next.js */} + {item.caption { event.currentTarget.parentElement!.hidden = true; }} className="aspect-[4/3] w-full rounded-lg border border-fg-grey-200 object-cover" /> + {item.caption &&
{item.caption}
} +
+ ))} +
+ ); +} + +/* ── Data ── */ + +export function Chart({ title, type, labels, series }: UiSpec<"show_chart">) { + const first = series[0]?.data ?? []; + const points = labels.map((label, index) => ({ label, value: first[index] ?? 0 })); + return ( +
+ {title} + {type === "donut" ? ( +
+ +
    {points.map(point =>
  • {point.label}{point.value}
  • )}
+
+ ) : type === "hbar" ? ( + + ) : ( + <> +
+ {type === "bar" + ? + : ({ label: item.label, data: item.data, fillArea: type === "area" }))} ariaLabel={title} />} +
+
{labels[0]}{labels[labels.length - 1]}
+ {series.length > 1 &&
{series.map(item => {item.label})}
} + + )} +
+ ); +} + +export function Progress({ title, items }: UiSpec<"show_progress">) { + return ( +
+ {title} + {items.map(item => ( +
+
{item.label}{item.note && {item.note}}{item.value}%
+ = 90 ? "red" : "blue"} /> +
+ ))} +
+ ); +} + +export function Funnel({ title, stages }: UiSpec<"show_funnel">) { + const top = Math.max(1, stages[0]?.value ?? 1); + return ( +
+ {title} + {stages.map((stage, index) => ( +
+
+ {stage.label} + {stage.value} + {index > 0 && {stages[index - 1].value ? `${Math.round((stage.value / stages[index - 1].value) * 100)}%` : "—"}} +
+
+
+ ))} +
+ ); +} + +/* ── Asking and acting: what the user does goes back as their next message ── */ + +export function Questions({ questions, answer, onAsk }: UiSpec<"show_questions"> & { answer?: string; onAsk: (text: string) => void }) { + if (answer) return {answer}; + const items = questions.map((question, index) => ({ id: String(index), title: question.title, multiple: question.multiple, allowText: question.allowText, options: question.options.map(option => ({ id: option.label, ...option })) })); + return ( + onAsk(items.map(item => `${item.title}:${[...(answers[item.id]?.optionIds ?? []), answers[item.id]?.text?.trim()].filter(Boolean).join("、") || "不限"}`).join(";"))} + /> + ); +} + +type FieldValue = string | number | boolean | string[]; + +export function Form({ title, submitLabel, fields, answer, onAsk }: UiSpec<"show_form"> & { answer?: string; onAsk: (text: string) => void }) { + const [values, setValues] = useState>(() => Object.fromEntries(fields.map(field => [field.name, field.default ?? (field.type === "switch" ? false : field.type === "multiselect" ? [] : "")]))); + if (answer) return {answer}; + const set = (name: string, value: FieldValue) => setValues(current => ({ ...current, [name]: value })); + const missing = fields.filter(field => field.required && (values[field.name] === "" || (Array.isArray(values[field.name]) && !(values[field.name] as string[]).length))); + const input = "w-full min-w-0 rounded-lg border border-fg-grey-200 bg-background px-2.5 py-1.5 text-[13px] text-fg-black outline-none placeholder:text-fg-grey-500 focus:border-accent"; + const describe = (value: FieldValue) => (Array.isArray(value) ? value.join("、") : typeof value === "boolean" ? (value ? "是" : "否") : String(value)); + return ( + { + event.preventDefault(); + if (missing.length) return; + onAsk(`提交「${title}」:${fields.filter(field => describe(values[field.name]) !== "").map(field => `${field.label}:${describe(values[field.name])}`).join(";")}`); + }} + > + {title} + {fields.map(field => { + const id = `forge-form-${field.name}`; + const value = values[field.name]; + return ( +
+ + {field.type === "textarea" ?