让智能体使用你用 definePrimitive 构建的组件,无论它们在哪里渲染。

你用 definePrimitive 构建的组件会和页面上的每个 Select、Dialog 一起出现在智能体的快照里。添加一个 agent 键,指明智能体可以调用它的哪些方法。

这个键只需在组件里写一次。任何渲染这个组件的人都会得到它:一个从 npm 安装你的评分组件的应用,创建桥接层、渲染 <Rating>,它的智能体就能打分,不用编写任何工具或 schema。

ui-sdk 的组件也使用同一个键。Checkbox 有 agent: { actions: ["setChecked"] }。你可以在本页末尾再找到几个例子。

试一试

这个评分组件有 agent: { actions: ["rate"] }。按 Read the page 看看智能体看到的内容,再按 Ask for 4 stars,发送智能体会发的那一步。

import * as React from "react"
import { StarIcon } from "lucide-react"
import { createChange, definePrimitive } from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { createAgent } from "@ui-sdk/react/agent"

const rating = definePrimitive({
  name: "rating",
  options: { defaultValue: "number" },
  state: (options: { defaultValue?: number }) => ({
    value: options.defaultValue ?? 0,
  }),
  api: (context) => {
    const change = createChange(context)
    return {
      rate: (value: number, event?: Event) =>
        change("value", value, { reason: "item-press", event }),
    }
  },
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "group" }) }),
    star: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        type: "button",
        "aria-pressed": String(Number(part.key) <= state.value),
        "data-filled": Number(part.key) <= state.value ? "" : undefined,
      }),
      press: ({ api, key }, event) => api.rate(Number(key), event),
    }),
  }),
  agent: { actions: ["rate"] },
})

const parts = createParts(rating, { root: "div", star: "button" })
const Rating = parts.Root
const RatingStar = parts.Star

const agent = createAgent()

function Example() {
  const [output, setOutput] = React.useState("")
  const show = (value: unknown) => setOutput(JSON.stringify(value, null, 2))

  return (
    <div data-slot="stack">
      <Rating aria-label="Your rating">
        {Array.from({ length: 5 }, (_, index) => (
          <RatingStar
            key={index}
            value={String(index + 1)}
            aria-label={`${index + 1} ${index === 0 ? "star" : "stars"}`}
          >
            <StarIcon aria-hidden="true" />
          </RatingStar>
        ))}
      </Rating>
      <div data-slot="row">
        <button
          type="button"
          onClick={() =>
            show(
              agent.snapshot().filter((entry) => entry.component === "rating")
            )
          }
        >
          Read the page
        </button>
        <button
          type="button"
          data-variant="solid"
          onClick={async () =>
            show(
              await agent.act({
                steps: [{ ref: "Your rating", action: "rate", args: [4] }],
              })
            )
          }
        >
          Ask for 4 stars
        </button>
      </div>
      {output && (
        <pre role="status" data-slot="log">
          {output}
        </pre>
      )}
    </div>
  )
}

export { Example }

添加 Agent 键

这是评分组件的原语(primitive)。它的 API 只有一个方法 rate:

rating.ts
const rating = definePrimitive({
  name: "rating",
  options: { defaultValue: "number" },
  state: (options: { defaultValue?: number }) => ({
    value: options.defaultValue ?? 0,
  }),
  api: (context) => {
    const change = createChange(context)
    return {
      rate: (value: number, event?: Event) =>
        change("value", value, { reason: "item-press", event }),
    }
  },
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "group" }) }),
  }),
  agent: { actions: ["rate"] },
})

actions 列出智能体可以调用的 API 方法。把 agent 放在 api 后面。

然后在渲染评分组件的地方给它一个名称:

<Rating aria-label="Your rating">

这个名称就是评分组件在快照里的 label,步骤也可以把它当作 ref。评分组件是一个 group,而 group 不会从内部的文本取得名称,所以它需要 aria-label,或者用 aria-labelledby 指向一个可见的标签。屏幕阅读器播报的也是同一个名称。

有了键和名称,快照就会列出 rate:

[
  {
    "ref": "c1",
    "component": "rating",
    "actions": ["rate"],
    "label": "Your rating",
    "value": 0
  }
]

智能体可以用这个方法接收的参数调用它:

await agent.act({ steps: [{ ref: "Your rating", action: "rate", args: [4] }] })

这一步返回 ok: true 以及它改了什么:评分组件的 value 现在是 4。

变更会经过 createChange,所以应用的 onValueChange 会看到 details.source === "agent",并能像其他变更一样取消它。权限介绍了这一点。

选择智能体能调用什么

只有 actions 里的方法会被提供。你的 API 其余部分,比如 keydown 处理函数或游走焦点(roving focus)辅助函数,仍然是你组件私有的,步骤如果指定它们会被拒绝:

rating c1 takes no keydown now. It takes: rate.

如果 actions 指定了你的 API 里没有的方法,开发构建会给出警告,所以拼写错误会立刻暴露。

没有这个键

没有 agent 键时,桥接层会从方法名猜测:set 后跟一个大写字母,比如 setValue,以及 open、toggle 或 clear 这样的动词。

用 createPopup 构建的 popover 会由此得到 setOpen:

api: (context) => createPopup(context, { preset: popoverPreset }),

它没有 agent 键,智能体也可以打开它:

{
  "ref": "c1",
  "component": "share",
  "actions": ["setOpen", "press"],
  "label": "Share",
  "open": false
}

桥接层猜不出 rate。没有这个键时,评分组件会显示 "actions": [],而请求 rate 的步骤会得到:

rating c1 takes no rate now. It takes: nothing.

列出你的动作,组件就能准确说明自己能做什么,无论它的方法叫什么名字。

参数

步骤的 args 会成为方法的参数。这个看板有两个动作。moveCard 接收一张卡片和一个列,addCard 接收一个标题:

board.ts
const columns = ["todo", "doing", "done"]

const board = definePrimitive({
  name: "board",
  state: () => ({
    value: { "Fix login": "todo", "Write docs": "doing" } as Record<
      string,
      string
    >,
  }),
  api: (context) => {
    const change = createChange(context)
    const cards = () => context.store.get().value
    return {
      moveCard: (card: string, column: string) => {
        if (!columns.includes(column)) {
          throw new Error(
            `No column "${column}". Columns: ${columns.join(", ")}.`
          )
        }
        return change(
          "value",
          { ...cards(), [card]: column },
          { reason: "drag" }
        )
      },
      addCard: (card: string) =>
        change("value", { ...cards(), [card]: "todo" }, { reason: "input" }),
    }
  },
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "group" }) }),
  }),
  agent: { actions: ["moveCard", "addCard"] },
})

智能体可以在同一次调用里移动一张卡片并添加另一张:

await agent.act({
  steps: [
    { ref: "Sprint board", action: "moveCard", args: ["Fix login", "done"] },
    { ref: "Sprint board", action: "addCard", args: ["Write tests"] },
  ],
})

桥接层不检查你自己方法的参数,所以请自行检查,就像 moveCard 检查列那样。方法抛出错误时,这一步会带着你的消息失败,后面的步骤不会运行:

No column "shipped". Columns: todo, doing, done.

动作也可以返回 promise。桥接层不会等待它兑现,所以这一步的结果是 "pending"。如果 promise 在这一步结束前被拒绝,这一步会带着它的消息失败。

列表

当组件的值始终是它的某个项时,比如尺寸选择器,添加 closed: true:

agent: { actions: ["setValue"], closed: true },

智能体可以用选项的标签或值来指定它。如果指定的内容不存在,这一步会带着真实的选项被拒绝,这样它就能重试:

No item "XL" in Size (c1). Its items: Small, Medium, Large.

桥接层从你状态的 items 读取这些项。如果它们放在别处,就用 items 返回它们:

agent: { actions: ["setValue"], items: (api) => api.allItems() },

items 会读取你的 API,这就是 agent 要放在 api 后面的原因。放在它前面时,TypeScript 会报告 allItems 不存在。

快照会把项和组件列在一起:页面上已有的项,或者数据里不超过 10 个时的全部项。列表更长时,快照给出 more,即项的数量,由 query({ within }) 返回它们。有了 items 函数,任何动作都能这样工作,不只是 setValue,所以步进器的 goTo 也能显示它的步骤。

项背后的内容

Tabs 和手风琴会把其他组件藏在它们关闭的项后面。添加 reveals: true 后,在页面上找不到组件的步骤会查看这些项背后,用 setValue 逐个打开它们;当组件持有一个打开项列表时,则用 open。带有 setPage 且状态里有 pageCount 的组件会逐页查找;只有 setOpen 的组件会在关闭时被打开:

agent: { actions: ["setValue"], closed: true, reveals: true },

对于一个停在 Account 步骤的设置流程,针对 "Card number" 的步骤会选中 Billing 步骤,并在那里填写字段。如果指定的字段不属于任何步骤,步骤会得到其他步骤包含的内容:

No component "Coupon" on the page. Its labels: Setup, Email. Behind what is closed: Billing: Card number, Postal code. Team: Invite.

只在需要时显示

shown 决定智能体现在能不能看到这个组件。比如字段的外层容器只需在有错误时显示,因为它的输入框已经带有标签:

agent: { shown: (state) => state.errors.length > 0 },

秘密值

对于智能体不该读取的值,比如 PIN,添加 secret: true。智能体仍然可以填写它,快照会显示 "[redacted]" 而不是这个值:

agent: { actions: ["setValue", "clear"], secret: true },

如果要改为隐藏某一个字段,应用可以用 data-agent-secret 标记它。见权限。

ui-sdk 的组件里

下面是几个 ui-sdk 组件的 agent 键,写法与 @ui-sdk/core 里一致:

组件agent
Checkbox{ actions: ["setChecked"] }
Number Input{ actions: ["setValue", "increment", "decrement"] }
Select{ actions: ["setOpen", "setValue", "clear", "setQuery"], closed: true }
Tabs{ actions: ["setValue"], closed: true, reveals: true }
Accordion{ actions: ["setValue", "open", "close", "toggle", "openAll", "closeAll"], closed: true, reveals: true }
OTP Input{ actions: ["setValue", "clear"], secret: true }
Field{ shown: (state) => !!state.errors.length }

API 参考

键类型说明
actionsstring[]智能体可以调用的 API 方法。没有它时,使用名字像变更的方法,比如 setValue。
closedboolean值始终是这些项之一,所以指定其他项的步骤会被拒绝。
items(api) => unknown以数据形式给出的项,当它们不是状态的 items 时使用。
revealsboolean关闭的项、页面或关闭的面板会隐藏其他组件。找不到组件的步骤会查看它们背后。
shown(state) => boolean智能体现在是否能看到这个组件。
secretboolean已填写的值在快照、步骤结果和 observe 里都读作 "[redacted]"。

agent 键是实验性的。