UI 扩展
宿主拥有应用外壳、导航与聊天骨架。插件通过四种方式扩展它:把 Compose 内容挂到插槽、用工具结果渲染器渲染工具结果、声明插件页面与输入框动作,以及写入自定义消息卡片。所有插件 UI 都是用共享 design 模块构建的 Compose;没有声明式 UI 语言、没有资源、也没有自定义 Activity。
UI 声明与兼容性
UI 扩展需要清单中的 ui 块:
"ui": { "apiLevel": 3 }| 检查 | 规则 | 失败时 |
|---|---|---|
ui.apiLevel | 必须在 1..HOST_UI_API_LEVEL(3)范围内;当前 SDK 为级别 3 | 安装时警告;插件的 Compose UI 被停用,插件仍会加载 |
ui.kotlin | 存在时必须匹配宿主 Kotlin 主/次版本(例如 "2.4") | 插件 UI 被停用 |
ui.compose | 存在时必须与宿主 Compose 运行时版本完全一致,而非 BOM 版本 | 插件 UI 被停用 |
UI 被停用时,插槽绑定、页面、输入框动作与工具结果渲染器都不渲染;工具、技能、提示词与钩子仍照常工作。除非确有理由,否则不要写 ui.kotlin 与 ui.compose。
插槽
插槽是宿主卡片内一块有名字的内容区域。ui(host) 返回 PluginUiContributions,其绑定把 Compose 内容挂到插槽 id 上。
public object SlotIds {
public const val TOOL_CARD_PREFIX: String = "tool.card.content:"
public const val CHAT_MESSAGE_PREFIX: String = "chat.message:"
public fun toolCard(toolName: String): String
public fun chatMessage(customType: String): String
public fun matches(slotId: String): Boolean
}| 插槽 id | 渲染位置 | 状态 |
|---|---|---|
tool.card.content:<toolName> | 该工具调用卡片的内容区 | ToolCardSlotState |
chat.message:<customType> | 该类型自定义消息卡片的内容区 | CustomMessageSlotState |
public interface SlotBinding {
public val slotId: String
public val priority: Int
public val content: SlotContent
}
public fun slotBinding(slotId: String, priority: Int = 0, content: SlotContent): SlotBinding
public interface SlotContent {
@Composable
public fun render(state: SlotState)
}
public fun composeSlot(render: @Composable (SlotState) -> Unit): SlotContent每个插槽只渲染一个绑定:priority 最高者胜出,同优先级按插件注册顺序。没有可渲染绑定时,宿主回落到默认视图。
插槽状态类型:
public interface SlotState
public data object NoSlotState : SlotState
public interface ToolCardSlotState : SlotState {
public val callId: String
public val toolName: String
public val args: JsonObject
public val result: PluginToolResult?
}
public interface CustomMessageSlotState : SlotState {
public val messageId: String
public val customType: String
public val payload: JsonObject
}示例:为插件自己的工具渲染卡片。
override fun ui(host: PluginHost): PluginUiContributions = object : PluginUiContributions {
override val bindings = listOf(
slotBinding(
slotId = SlotIds.toolCard("sync_files"),
content = composeSlot { state ->
val card = state as? ToolCardSlotState ?: return@composeSlot
SyncCard(
args = card.args,
result = card.result,
onOpen = { host.ui().openPage("sync") },
)
},
),
)
override val pages = listOf(syncPage(host))
}工具结果渲染器
插槽只匹配一个精确工具名。工具结果渲染器可以按来源、服务器、精确名称或名称前缀匹配,用来渲染 MCP 工具、内置工具或一族插件工具的结果。
public value class ToolResultSource private constructor(public val wire: String) {
public companion object {
public val PLUGIN: ToolResultSource
public val MCP: ToolResultSource
public val BUILTIN: ToolResultSource
}
}
public interface ToolResultMatch {
public val source: ToolResultSource?
public val server: String?
public val tool: String?
public val toolPrefix: String?
public fun matches(source: ToolResultSource, server: String?, tool: String): Boolean
public fun specificity(): Int
}
public fun toolResultMatch(
source: ToolResultSource? = null,
server: String? = null,
tool: String? = null,
toolPrefix: String? = null,
): ToolResultMatch
public interface ToolResultRendererContributor {
public val toolResultRenderers: List<ToolResultRenderer>
}
public interface ToolResultRenderer {
public val id: String
public val priority: Int
public val match: ToolResultMatch
@Composable public fun content(state: ToolResultState)
}
public fun toolResultRenderer(
id: String,
match: ToolResultMatch,
priority: Int = 0,
content: @Composable (ToolResultState) -> Unit,
): ToolResultRenderer
public interface ToolResultState {
public val callId: String
public val toolName: String
public val source: ToolResultSource
public val server: String?
public val arguments: JsonObject
public val result: PluginToolResult?
public val structuredContent: JsonElement?
}让 ui() 的返回值实现 ToolResultRendererContributor 来返回渲染器列表:
override fun ui(host: PluginHost): PluginUiContributions =
object : PluginUiContributions, ToolResultRendererContributor {
override val bindings = emptyList<SlotBinding>()
override val toolResultRenderers = listOf(
toolResultRenderer(
id = "route-card",
match = toolResultMatch(
source = ToolResultSource.MCP,
server = "maps",
toolPrefix = "route_",
),
) { state ->
val structured = state.structuredContent as? JsonObject
RouteCard(
summary = structured?.get("summary")?.jsonPrimitive?.contentOrNull
?: state.result?.text.orEmpty(),
)
},
)
}匹配规则:
source:PLUGIN、MCP或BUILTIN;省略表示任意来源。server:用户在 MCP 设置中配置的服务器名。tool:精确工具名;toolPrefix:名称前缀。二者可以组合。- 一个结果只用一个渲染器:先比
priority,再比匹配的具体程度,最后比注册顺序。 - 没有匹配的渲染器、插件已停用或 UI 不兼容时,宿主使用默认工具卡片。渲染器内不要抛异常或
require。
ToolResultState 字段:callId 与 toolName 标识调用;通过 tool_execute 调用的 MCP 工具会被还原为真实 MCP 工具身份。structuredContent 是宿主持久化的结构化负载(上限 256 KiB),重新打开会话后仍可用;它不会进入模型上下文。展示数据请用它,而不要把 JSON 塞进 details。
插件页面
插件页面是插件自己的完整 Compose 屏幕。页面声明为 PluginUiContributions.pages:
public interface PluginPage {
public val id: String
public val title: LocalizedText
public val icon: IconRef?
@Composable public fun content()
}
public fun pluginPage(
id: String,
title: LocalizedText,
icon: IconRef? = null,
content: @Composable () -> Unit,
): PluginPage
public interface PluginUiContributions {
public val bindings: List<SlotBinding>
public val pages: List<PluginPage> get() = emptyList()
public val composerActions: List<ComposerAction> get() = emptyList()
public companion object {
public val None: PluginUiContributions
}
}
public interface ComposerAction {
public val id: String
public val label: LocalizedText
public val icon: IconRef?
}
public fun composerAction(id: String, label: LocalizedText, icon: IconRef? = null): ComposerAction页面 id 为 ^[a-z][a-z0-9_.-]*$。插件只能打开自己的页面。
打开与关闭页面:
host.ui().openPage("home")
host.ui().openPageWithArguments(
pageId = "detail",
arguments = buildJsonObject { put("id", "42") },
newTask = false,
)
host.ui().closePage(buildJsonObject { put("saved", true) })| 调用 | 行为 |
|---|---|
openPage(pageId) | 把页面压入当前导航栈 |
openPageWithArguments(..., newTask = false) | 带 JSON 参数压入当前导航栈 |
openPageWithArguments(..., newTask = true) | 在宿主代理的专用窗口中打开,适合扫码、拍照或长流程 |
openPageSheet(pageId, arguments) | 以底部面板形式浮在聊天之上;内容相同,不压入导航栈 |
closePage(result?) | 关闭页面或面板,可返回 JSON 结果 |
页面上下文:
public interface PluginPageContext {
public val pageId: String
public val arguments: JsonObject
public val presentation: PluginPagePresentation
}
public value class PluginPagePresentation private constructor(public val wire: String) {
public companion object {
public val PAGE: PluginPagePresentation
public val SHEET: PluginPagePresentation
}
}
public val LocalPluginPageContext: ProvidableCompositionLocal<PluginPageContext?>在页面内容中读取 host.ui().pageContext() 或 LocalPluginPageContext.current;在插件页面之外二者均为 null。检查 presentation 区分面板与页面。同一时间只允许一个插件页面面板;面板内可以使用 DdSheet,关闭时先关最上层。
页面示例:
private fun syncPage(host: PluginHost) = pluginPage(
id = "sync",
title = localizedText("Sync", "同步"),
icon = assetIcon("asset:icon.png"),
) {
val colors = soraColors()
var status by remember { mutableStateOf<SyncStatus?>(null) }
var busy by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
status = loadStatus()
}
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(
start = DdSpacing.Xl,
end = DdSpacing.Xl,
top = DdSpacing.Md,
bottom = DdSpacing.Xxl,
),
verticalArrangement = Arrangement.spacedBy(DdSpacing.Lg),
) {
DdGroupCard {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = DdSpacing.Card, vertical = DdSpacing.Sm),
) {
DdStatusRow(
label = host.text(localizedText("Service", "服务")),
value = if (status?.connected == true) "Connected" else "Not connected",
tone = if (status?.connected == true) DdStatusTone.SUCCESS else DdStatusTone.NEUTRAL,
busy = busy,
)
}
}
if (status?.error != null) {
DdNoticeBar(
text = status.error,
tone = DdNoticeTone.DANGER,
actionLabel = "Retry",
onAction = { /* rerun the failed action */ },
)
}
DdPrimaryButton(
text = "Sync now",
onClick = { /* start sync */ },
enabled = !busy,
)
}
}页面行为:
- 页面可以调用所有已声明的宿主服务。优先使用
host.ui()的确认/输入/选择器,而不是 Material 对话框。 host.ui().openPage只接受插件自己的页面 id;在工具或非页面上下文中需要专用窗口时,使用components().startActivity(pluginActivityOptions(...))。- 页面状态放在 Compose 中;必须跨进程存活的状态写入
host.settings()或host.dataDir下的文件。不要把密钥写进普通文件;使用host.secrets()。 - 页面操作改变了工具、技能或页面后,调用
host.requestContributionsRefresh();忙碌会话会在本轮结束后更新。 - 页面离开后,宿主会取消页面协程(
LaunchedEffect)。长时间任务应挂在host.scope上。 - 不要自绘标题栏:宿主会在页面上方渲染 64dp 顶栏。
输入框动作
composerAction(id, label, icon?) 在聊天输入框添加一个快捷动作。点击后打开与该动作 id 匹配的插件页面,没有匹配时打开第一个页面。它适合一两个高价值入口,不要把每个工具都镜像到 UI 里。
自定义消息卡片
用 customType 向会话写入卡片;卡片通过 chat.message:<customType> 渲染:
host.chat().sendMessage(
sessionId = call.sessionId,
text = "Sync finished",
options = chatMessageOptions(
triggerTurn = false,
display = chatDisplay(
customType = "sync.card",
payload = buildJsonObject {
put("title", "Sync finished")
put("files", 12)
},
text = "Sync finished, 12 files",
),
),
)也可以只用 postCustomMessage(...) 写入卡片。卡片会持久化到会话并在重新打开后恢复;工具运行期间投递的卡片会内联渲染在该轮中。投递选项与 ChatSendResult 见 运行时 API。
交互与选择器
host.ui() 提供宿主风格的对话框与系统选择器。它们需要前台页面或聊天上下文;在后台调用可能返回 null 或 false。
| 方法 | 返回值 | 说明 |
|---|---|---|
confirm(uiConfirmRequest(title, message?, confirmLabel?, cancelLabel?, destructive)) | Boolean | 确认对话框;destructive 使用危险色 |
prompt(uiPromptRequest(title, message?, initial, placeholder?, multiline)) | String? | 文本输入;取消返回 null |
choose(uiChooseRequest(title, options, message?)) | String? | 单选列表;返回选中项的 UiChoice.id |
pickDate(uiDatePickRequest(initialMs?, minMs?, maxMs?)) | Long? | 日期选择器 |
pickTime(uiTimePickRequest(initialHour?, initialMinute?, is24Hour)) | Int? | 时间选择器,返回 hour * 60 + minute |
pickFiles(uiFilePickRequest(mimeTypes, multiple, maxCount)) | List<PluginPickedFile> | 系统文件选择器;取消返回空列表 |
pickImage(uiImagePickRequest(source = UiImageSource.GALLERY/CAMERA, frontCamera)) | PluginPickedFile? | 相册或相机 |
scanQr() | String? | 扫码并返回文本 |
pickDirectory() | String? | 选择目录 |
snackbar(message, actionLabel?, action?) | — | 页内轻提示,可带一个动作 |
shareFiles(paths, mimeType?) | — | 分享插件可读的文件 |
openUrl(url) / share(shareRequest(...)) / toast(message) | — | 打开链接、分享文本、轻量 Toast |
isDark | Boolean | 当前主题是否为深色 |
PluginPickedFile 包含 path、uri、name、sizeBytes 与 mimeType。相机与麦克风权限由宿主统一申请:在清单 permissions 中声明 camera / microphone,并声明 ui 能力。
val picked = host.ui().pickImage(uiImagePickRequest(source = UiImageSource.CAMERA))
val note = host.ui().prompt(uiPromptRequest(title = "Note", placeholder = "Optional")) ?: return
host.ui().snackbar("Imported", actionLabel = "View") { host.ui().openPage("sync") }设计体系
插件 UI 使用 io.github.sadami3066.sora.design(制品 design 1.1.0),与应用相同的组件。plugin-api 已通过 api() 携带它,因此模板不声明显式依赖;官方插件会用 compileOnly("io.github.sadami3066.sora:design:1.1.0") 显式固定版本。
组件
| 组件 | 用途 |
|---|---|
DdGroupCard | 圆角分组卡片(20dp 圆角,行间发丝线) |
DdListRow | 卡片内的列表行:标题、副标题、值、图标、箭头、尾部内容 |
DdSectionLabel | 分组标签 |
DdPrimaryButton | 主操作按钮(强调色填充,一屏最多一个) |
DdTextAction | 次要操作的文字按钮 |
DdTextField / DdTextArea | 单行与多行输入 |
DdSwitch / DdChip / DdSegmented | 开关、筛选标签、分段控件 |
DdSheet + DdSheetHeader | 底部面板与标题 |
DdDialog | 居中对话框 |
DdMenu / DdMenuItem | 下拉菜单 |
DdEmptyState / DdLoadingBlock / DdSpinner | 空状态、加载块与进度指示 |
DdProgressBar / DdSlider | 确定/不确定进度与连续值 |
DdHairline / DdRowDivider | 分隔线 |
DdStatusRow + DdStatusTone | 状态摘要行:NEUTRAL、ACCENT、SUCCESS、WARNING、DANGER |
DdNoticeBar + DdNoticeTone | 内联提示:INFO、SUCCESS、WARNING、DANGER,可带动作 |
DdMarkdown | Markdown 渲染,支持链接、图片与代码复制 |
DdHtmlText / DdHtmlBlocks / DdWebView | 受限 HTML 与内嵌网页 |
DdImage / DdRemoteImage / DdImageViewer | 本地、远程与全屏图片 |
DdPullToRefresh | 下拉刷新容器 |
DdSnackbarHost | 页内轻提示宿主 |
DdFileRow / DdInfoTooltip / DdExpandToggle | 文件行、内联说明、展开/收起 |
DdSwipeRow + DdSwipeAction | 列表行滑动操作 |
DdDatePicker / DdTimePicker | 日期与时间选择面板 |
DdSearchField / DdDropdown / DdAvatar / DdIconBox / DdTypingDots | 搜索、下拉、头像、图标容器、输入中指示 |
DdPageScaffold | 宿主页面使用的页面骨架 |
DdTheme / SoraTheme / soraColors() | 调色板与颜色访问 |
DdType / DdSpacing / DdShapes / DdMotion / DdIcons | 字阶、间距、形状、动效、图标 |
颜色、字体、间距
val colors = soraColors() // SoraColors
colors.ink; colors.inkSecondary; colors.inkTertiary
colors.paper; colors.surface; colors.raised
colors.accent; colors.accentSoft; colors.onAccent
colors.danger; colors.success; colors.warning
colors.hairline; colors.wash; colors.composer; colors.scrim使用 DdType 字阶而不是原始字号:wordmark、display、pageTitle、heading、body、bodySmall、label、button。使用 DdSpacing 而不是硬编码 dp:ScreenHorizontal(24)、Section(20)、Card 与 RowHorizontal(18)、Xl(20)、Xxl(24)、Lg(16)、Md(12)、Sm(8)、Xs(4)、Xxs(2)。
设计体系是共享语言,不是建议:不要硬编码颜色或字号,也不要直接使用 Material 3 的 Card/Button/Switch/OutlinedTextField——它们与应用其余部分风格不一致。
布局指南
插件页面自身就是滚动容器。宿主已经提供 64dp 顶栏,因此页面从内容开始,而不是从标题开始。
- 页面内边距:水平
DdSpacing.Xl(20dp)、顶部DdSpacing.Md(12dp)、底部DdSpacing.Xxl(24dp);分组之间用Arrangement.spacedBy(DdSpacing.Lg)。 DdGroupCard只绘制卡片表面:卡片内的自定义内容需要Modifier.fillMaxWidth().padding(horizontal = DdSpacing.Card)(18dp),避免文字贴边。DdListRow已通过LocalDdRowHorizontalPadding自带该内边距,DdNoticeBar也有自己的内边距——不要重复包裹。- 一屏一个视觉重心:先状态卡片,再操作,最后细节。
DdPrimaryButton最多一个;次要操作使用文字按钮或菜单。 - 刷新时状态必须稳定:保留旧值可见,只把受影响的行标记为
busy;不要把整页清空成加载态。 - 错误就近内联展示(危险色
DdNoticeBar加「重试」动作),不要只用 Toast。空状态与加载状态使用DdEmptyState与DdLoadingBlock。
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(
start = DdSpacing.Xl,
end = DdSpacing.Xl,
top = DdSpacing.Md,
bottom = DdSpacing.Xxl,
),
verticalArrangement = Arrangement.spacedBy(DdSpacing.Lg),
) {
StatusCard(host, status)
if (status.error != null) {
DdNoticeBar(status.error, tone = DdNoticeTone.DANGER, actionLabel = "Retry") { retry() }
}
DdProgressBar(progress = if (busy) percent else null)
}卡片最佳实践
- 工具卡片回答三个问题:执行了什么、结果如何、用户接下来能做什么。第一行给结论,原始输出收进展开区。
- 用
DdGroupCard、DdListRow、DdStatusRow搭建卡片;错误用DdNoticeBar,文件用DdFileRow。 - 高度克制:卡片存在于对话中。展示摘要加少量行,其余用
DdExpandToggle展开;不要嵌套可滚动容器。 - 媒体:用
host.images().load(url, maxEdgePx)加载远程图片,用DdRemoteImage渲染;全屏用DdImageViewer。图片只留在宿主内存与私有缓存中——绝不把卡片图片写入共享存储。 - 交互:点击卡片主体可以打开页面面板;显式操作放在文字按钮上。绝不能让工具结果必须靠用户点击才能完成。
- 不要把能力只做在 UI 里:智能体必须仍能通过工具完成同一件事。UI 是给人用的可选路径,不是自动化的门槛。
- 动效:使用
DdMotion数值并尊重LocalDdMotionEnabled;只动透明度与缩放,不引起布局跳动。 - 文案:写给用户,而不是开发者。中英成对,避免 CLI 名称、文件路径与原始版本号;确实必要的信息放进
DdInfoTooltip。图标使用DdIcons,不要用 emoji。
