fix(action-cards): read card blocks with the Chat client's Markdown grammar

- The Host finds action-card blocks with mdast-util-from-markdown plus the
  GFM and math extensions the Chat client uses for settled answers, so a
  block offers a card exactly when the client dispatches it to the card
  layer. Only text with an opening fence that can start the card language
  is parsed.
- The card block layer shows a settled block whose content is not JSON as
  plain code instead of hiding it.
- Sessions recorded with propose_action calls show their tool row again.
- Add the upgrade guide for the removed tool, the ignored
  queuedMessageLimit field and the callId to cardId rename.
- Update package READMEs, package descriptions and generated catalogs.
This commit is contained in:
ZiyaZhang committed 2026-11-15 23:02:13 -08:00
1 parent 945d00378c
commit 0ee96fac04
25 files changed
+383 -137

No files matched your search

@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/action-card-blocks/guide.md
/:
en: 956388e1727f0148
zh: b7204e9d2f3879e4
/action-cards-come-from-blocks-in-answers:
en: f1c8039bfd4951a4
zh: 9ef5eff3846f3b75
/action-cards-come-from-blocks-in-answers/change:
en: ffb4bc0019343849
zh: f40c350dec4b0342
/action-cards-come-from-blocks-in-answers/migration:
en: 56d3fd71dc496cdb
zh: 058a5bd80d8a2a18
@@ -0,0 +1,27 @@
---
kind: upgrade-guide
description: "Personalized recommendations cards come from action-card blocks in answers; the propose_action tool, the action-cards queuedMessageLimit field and the callId card field are gone."
---
# Action cards come from blocks in answers
English | [中文](guide.zh.md)
## Change
The experimental Personalized recommendations bundle offered its cards through the `propose_action` tool. The model now ends its final answer with a fenced `action-card` block holding the same `action`, `title`, `brief` and `details`, and `@deepseek-ai/dsh-action-cards` reads the card from the logged answer. The tool is no longer declared, and the service has no `queuedMessageLimit` configuration field: a value left under `id: action-cards` in a profile's `cordis.patch.yml` is ignored.
For plugins that register a card kind or call the service:
- `ActionCardKind` no longer takes `skill` or `invitation`; the kind's skill tells the model how to write the block and how to invite the user.
- `ActionCardProposal`, `ActionCardDecision`, `ctx.actionCards.act()` and the `actionCards` Remote name cards by `cardId` (type `ActionCardId`) instead of `callId`, and new `plugin:action-cards/decision` records carry `cardId`.
- The package no longer exports `Config` or `ActionCardError`.
Sessions recorded with `propose_action` keep their cards and decisions. This affects users who changed `queuedMessageLimit` and plugins that register card kinds; the shipped bundle needs no change.
## Migration
1. Remove `queuedMessageLimit` from the `id: action-cards` entry of the profile's `cordis.patch.yml`, and remove the entry when nothing else remains in it.
2. In a plugin that registers a card kind, drop `skill` and `invitation` from `ctx.actionCards.register()`, and change its skill to ask for one `action-card` block at the end of the final answer, with the invitation sentence before it, as [`official-plugins.md`](../../../../packages/experimental/plugin-recommendations/skills/official-plugins.md) does.
3. Rename `callId` to `cardId` where the plugin reads proposals or decisions, records decisions or calls `act()`.
4. Ask a question that a kind's skill answers with a card; the migration works when the card appears below the answer and the process area shows no `propose_action` call.
@@ -0,0 +1,27 @@
---
kind: upgrade-guide
description: "个性化推荐的卡片改由回答里的 action-card 代码块提出;propose_action 工具、action-cards 的 queuedMessageLimit 字段和卡片的 callId 字段都已移除。"
---
# 操作卡片改由回答里的代码块提出
[English](guide.md) | 中文
## 变更
实验性的个性化推荐 Bundle 过去通过 `propose_action` 工具提出卡片。现在模型在最终回答末尾写一个围栏代码块,语言为 `action-card`,内容仍是 `action`、`title`、`brief` 与 `details`,`@deepseek-ai/dsh-action-cards` 从日志里的回答读出卡片。该工具不再声明,服务也不再有 `queuedMessageLimit` 配置字段:profile 的 `cordis.patch.yml` 里 `id: action-cards` 下留下的值会被忽略。
对注册卡片种类或调用该服务的插件:
- `ActionCardKind` 不再接受 `skill` 与 `invitation`;由种类自己的 Skill 告诉模型怎样写代码块、怎样邀请用户。
- `ActionCardProposal`、`ActionCardDecision`、`ctx.actionCards.act()` 与 `actionCards` Remote 用 `cardId`(类型 `ActionCardId`)指代卡片,不再用 `callId`;新写入的 `plugin:action-cards/decision` 记录带 `cardId`。
- 本包不再导出 `Config` 与 `ActionCardError`。
用 `propose_action` 录下的会话,卡片和决定照常保留。受影响的是改过 `queuedMessageLimit` 的用户和注册卡片种类的插件;随产品提供的 Bundle 无需改动。
## 迁移
1. 从 profile 的 `cordis.patch.yml` 里 `id: action-cards` 条目中删除 `queuedMessageLimit`;条目里不再有其他内容时,删除整个条目。
2. 在注册卡片种类的插件里,从 `ctx.actionCards.register()` 中去掉 `skill` 与 `invitation`,并把它的 Skill 改为要求在最终回答末尾写一个 `action-card` 代码块、邀请句写在代码块之前,做法同 [`official-plugins.md`](../../../../packages/experimental/plugin-recommendations/skills/official-plugins.md)。
3. 插件读取提议或决定、记录决定或调用 `act()` 的地方,把 `callId` 改为 `cardId`。
4. 提一个某个种类的 Skill 会以卡片回应的问题;卡片出现在回答下方、过程区没有 `propose_action` 调用,即迁移完成。
@@ -21,11 +21,11 @@
en: ec2c7e23b17e2d3e
zh: f6e104e7ce68c3ac
/deepseek-ai-dsh-action-cards/use-this-package/card-rules:
en: 731ba1f68d4e5a7e
zh: 10ac451f7d9419ed
en: e6912640f032199c
zh: 8919028df76bbd6c
/deepseek-ai-dsh-action-cards/understand-the-implementation:
en: 93c3d90a1c5d4d6b
zh: a1f7a22c8f152a60
en: b01320593b9dba18
zh: de02fb30999de490
/deepseek-ai-dsh-action-cards/further-exploration:
en: b5d6fde7329f67a7
zh: db2839d22fc577c4
@@ -60,8 +60,8 @@
en: 58785543e2428dba
zh: 4b082f77b3b2f482
/deepseek-ai-dsh-action-cards/known-limitations-and-deferred-work:
en: 79e8caf3f067a13d
zh: 600c814e4a0297db
en: b9ef6e3e0ecff6f9
zh: d8c7041b141641d7
/deepseek-ai-dsh-action-cards/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: bd8a8936229e035e
+5 -5
View File
@@ -33,8 +33,8 @@ A kind package injects `actionCards` and calls `ctx.actionCards.register(kind)`
### Card rules
- A card is a fenced block whose language is `action-card` and whose content is one JSON object with `action`, `title`, `brief` and an object `details`. The first such block of a turn that parses becomes the card, named by the id of the assistant message that holds it. Later blocks of that turn, blocks in reasoning, blocks in an interrupted answer, blocks with a blank title or brief, and every block of a subagent Session create no card, and nothing reports this to the model.
- Admission does not check the kind: a card whose action no kind registered, or whose `details` fail the kind schema, still appears, and every action on it except Not now is refused as unavailable.
- A card is a fenced block whose language is `action-card` and whose content is one JSON object with `action`, `title`, `brief` and an object `details`. Blocks count at any depth, such as inside a list item or block quote, exactly where the Chat client renders them as `action-card` blocks. The first such block of a turn that parses becomes the card, named by the id of the assistant message that holds it. Later blocks of that turn, blocks in reasoning, blocks in an interrupted answer, blocks with a blank title or brief, and every block of a subagent Session create no card, and nothing reports this to the model.
- Admission does not check the kind: a card whose action no kind registered, or whose `details` fail the kind schema, still appears, replaces every unstarted earlier card, and refuses every action except Not now as unavailable.
- Sessions recorded before cards moved into answers keep their cards: a successful `propose_action` call still becomes a card named by its call id, and decision records that name the card `callId` are still read.
- A newer card of any kind replaces every unstarted earlier card. Replacement is derived from the log and never recorded.
- Events a forked Session inherits create no cards.
@@ -49,7 +49,7 @@ A kind package injects `actionCards` and calls `ctx.actionCards.register(kind)`
<details>
<summary>Implementation internals — click to expand</summary>
The package default-exports the `actionCards` Remote service and registers no tool. The logged answer is the durable proposal: the `actionCards` Session projection (state version 3) reads the text blocks of each `assistant/message` with [`src/fence.ts`](src/fence.ts), which finds top-level fenced blocks by the CommonMark rules and matches their language the way the Chat client dispatches fences, and admits the first valid block of the turn. It also pairs each `propose_action` call of an older Session with its successful result, records decisions from `plugin:action-cards/decision`, and keeps unreported decisions until a status notice whose `through` covers them enters the log. The header's `origin` marks a subagent Session, whose projection admits nothing. Its Client view `{ proposals, decisions }` is excluded from Session summaries.
The package default-exports the `actionCards` Remote service and registers no tool. The logged answer is the durable proposal: the `actionCards` Session projection (state version 3) reads the text blocks of each `assistant/message` with [`src/fence.ts`](src/fence.ts), which parses each text that has an opening fence able to start the `action-card` language with the GFM and math grammar of the Chat client's settled answers (`mdast-util-from-markdown` and its extensions) and keeps the code blocks the client dispatches to that language, and admits the first valid block of the turn. It also pairs each `propose_action` call of an older Session with its successful result, records decisions from `plugin:action-cards/decision`, and keeps unreported decisions until a status notice whose `through` covers them enters the log. The header's `origin` marks a subagent Session, whose projection admits nothing. Its Client view `{ proposals, decisions }` is excluded from Session summaries.
The Remote `act(sessionId, cardId, verb, payload?)` checks the owner, the live root and the card; Not now continues without a registered kind, while other verbs need the kind, the verb and Remote access. It then shares one operation per card. The kind's `reconcile` runs first and the live root is checked again; a dismissed or replaced card then settles unchanged, Not now is recorded, a writing verb is refused in a read-only Session, and every other verb goes to the kind handler under the Agent's initiator. `record()` also accepts an action whose kind has unregistered, because Cordis disposes a plugin's effects concurrently and an unloading kind still records the outcome of work it started. An `agent/pre-step` listener adds the status notice after later listeners prepared the step.
@@ -114,8 +114,8 @@ The notice is appended after the request's other new context and never rewrites
<a id="known-limitations-and-deferred-work"></a>
- The model learns nothing about a block that creates no card: a malformed block, a second block of the turn or a subagent's block shows nothing, while the answer may already invite the user to the card.
- Only top-level blocks are read; a block inside a list or block quote creates no card, though the browser half still hides it.
- The model learns nothing about a block that creates no card, while the answer may already invite the user to the card. The browser half shows a settled block whose content is not JSON as plain code; a block that parses but lacks a field, a second block of the turn and a subagent's block stay hidden.
- A card that fails its kind schema or names no registered kind still replaces an unstarted earlier card, which then offers no action.
- Cards are offered in the main conversation only. A subagent Session, including a Creator child's, admits no card, because only a live root can act on one.
- Only one card is offered per turn across all kinds. A later card of any kind replaces every unstarted earlier card, so a second kind's card replaces an unstarted card of the first.
- Refusal reasons of user actions are plain strings by design: the service defines `closing`, `not-live-root`, `unknown`, `unavailable`, `access-denied` and `read-only`, each kind adds its own, and a browser body names the reasons it knows and treats others as unavailable.
@@ -33,8 +33,8 @@ kind: "package-reference"
### 卡片规则
- 卡片是语言为 `action-card` 的围栏代码块,内容是一个 JSON 对象,包含 `action`、`title`、`brief` 和对象类型的 `details`。一轮中第一个能解析的这种代码块成为卡片,以所在助手消息的 id 作为卡片 id。同一轮之后的代码块、思考内容里的代码块、被打断的回答里的代码块、标题或说明为空的代码块,以及 subagent 会话里的所有代码块都不会产生卡片,也不会告知模型。
- 收下卡片时不检查种类:动作没有种类注册、或 `details` 未通过种类校验的卡片照样出现,除“暂不需要”外的操作一律以 unavailable 拒绝。
- 卡片是语言为 `action-card` 的围栏代码块,内容是一个 JSON 对象,包含 `action`、`title`、`brief` 和对象类型的 `details`。代码块在任意层级都算,例如列表项或引用块中,与 Chat 客户端把它当作 `action-card` 代码块渲染的位置完全一致。一轮中第一个能解析的这种代码块成为卡片,以所在助手消息的 id 作为卡片 id。同一轮之后的代码块、思考内容里的代码块、被打断的回答里的代码块、标题或说明为空的代码块,以及 subagent 会话里的所有代码块都不会产生卡片,也不会告知模型。
- 收下卡片时不检查种类:动作没有种类注册、或 `details` 未通过种类校验的卡片照样出现,并替换此前所有尚未开始的卡片,除“暂不需要”外的操作一律以 unavailable 拒绝。
- 卡片改为写在回答里之前录下的会话,卡片照常保留:成功的 `propose_action` 调用仍成为卡片,以调用 id 作为卡片 id;用 `callId` 指代卡片的旧决定记录也照常读取。
- 任何种类的新卡片都会替换此前所有尚未开始的卡片。替换从日志推导,从不单独记录。
- fork 出的会话从父会话继承的事件不会产生卡片。
@@ -49,7 +49,7 @@ kind: "package-reference"
<details>
<summary>实现细节——点击展开</summary>
本包默认导出 `actionCards` Remote 服务,不注册任何工具。日志里的回答就是持久的提议:`actionCards` 会话投影(状态版本 3)用 [`src/fence.ts`](src/fence.ts) 读取每条 `assistant/message` 的文字块,按 CommonMark 规则找出顶层围栏代码块,并按 Chat 客户端分派代码块的方式匹配语言,收下本轮第一个合格的代码块。投影还把旧会话里每个 `propose_action` 调用与其成功结果配对,从 `plugin:action-cards/decision` 读取决定,并保留尚未报告的决定,直到 `through` 覆盖它们的状态通知写入日志。会话头的 `origin` 标出 subagent 会话,其投影不收任何卡片。投影的客户端视图 `{ proposals, decisions }` 不进入会话摘要。
本包默认导出 `actionCards` Remote 服务,不注册任何工具。日志里的回答就是持久的提议:`actionCards` 会话投影(状态版本 3)用 [`src/fence.ts`](src/fence.ts) 读取每条 `assistant/message` 的文字块:含有可能以 `action-card` 语言开头的围栏起始行的文字按 Chat 客户端回答落定后的 GFM 与数学语法解析(`mdast-util-from-markdown` 及其扩展),保留客户端分派到该语言的代码块,收下本轮第一个合格的代码块。投影还把旧会话里每个 `propose_action` 调用与其成功结果配对,从 `plugin:action-cards/decision` 读取决定,并保留尚未报告的决定,直到 `through` 覆盖它们的状态通知写入日志。会话头的 `origin` 标出 subagent 会话,其投影不收任何卡片。投影的客户端视图 `{ proposals, decisions }` 不进入会话摘要。
Remote `act(sessionId, cardId, verb, payload?)` 先检查服务所有者、在线根 Agent 和卡片;“暂不需要”在种类未注册时也继续处理,其他操作还需要种类、操作和 Remote 权限。然后同一张卡片共用一次处理。种类的 `reconcile` 先运行,之后再次检查在线根 Agent;已忽略或已替换的卡片原样返回,“暂不需要”被记录,写入类操作在只读会话中被拒绝,其余操作在该 Agent 的发起方作用域内交给种类处理器。`record()` 也接受种类已注销的动作,因为 Cordis 并发释放插件的各个 effect,卸载中的种类仍要记录已开始工作的结果。一个 `agent/pre-step` 监听器在后续监听器准备好本步之后追加状态通知。
@@ -114,8 +114,8 @@ Latest status of action cards from user actions and background work. These are s
<a id="known-limitations-and-deferred-work"></a>
- 代码块没有产生卡片时模型不会知道:格式错误的代码块、同一轮的第二个代码块或 subagent 的代码块都不显示任何东西,而回答里可能已经邀请用户点卡片。
- 只读取顶层代码块;列表或引用块里的代码块不会产生卡片,但浏览器端仍会把它隐藏。
- 代码块没有产生卡片时模型不会知道,而回答里可能已经邀请用户点卡片。浏览器端会把回答落定后内容不是 JSON 的代码块按普通代码显示;能解析但缺字段的代码块、同一轮的第二个代码块和 subagent 的代码块仍然隐藏。
- 未通过种类校验或动作没有注册的卡片仍会替换此前尚未开始的卡片,被替换的卡片不再提供任何操作。
- 卡片只在主对话中提供。subagent 会话(包括 Creator 子 Agent 的会话)不收任何卡片,因为只有在线的根 Agent 才能对卡片进行操作。
- 所有种类合计每轮只展示一张卡片。任何种类的新卡片都会替换此前所有尚未开始的卡片,因此第二个种类的卡片会替换第一个种类尚未开始的卡片。
- 用户操作的拒绝原因有意设计为普通字符串:服务定义 `closing`、`not-live-root`、`unknown`、`unavailable`、`access-denied` 和 `read-only`,各种类可以添加自己的原因,浏览器端正文为已知原因显示文案,其余按 unavailable 处理。
@@ -52,10 +52,16 @@
"@deepseek-ai/dsh-session-projection": "workspace:*",
"@deepseek-ai/dsh-api-remote-access": "workspace:*",
"@deepseek-ai/dsh-sandbox-policy": "workspace:*",
"@deepseek-ai/dsh-util-values": "workspace:*"
"@deepseek-ai/dsh-util-values": "workspace:*",
"@types/mdast": "^4.0.4"
},
"dependencies": {
"@deepseek-ai/dsh-brand": "workspace:*",
"mdast-util-from-markdown": "^2.1.0",
"mdast-util-gfm": "^3.1.0",
"mdast-util-math": "^3.0.0",
"micromark-extension-gfm": "^3.0.0",
"micromark-extension-math": "^3.1.0",
"zod": "4.6.6"
},
"files": [
+28 -48
View File
@@ -1,61 +1,41 @@
/** Find the fenced blocks of answer text that offer action cards. */
/** Find the `action-card` blocks of answer text with the Markdown grammar the Chat client renders settled answers with. */
import type { Nodes } from 'mdast'
import { fromMarkdown } from 'mdast-util-from-markdown'
import { gfmFromMarkdown } from 'mdast-util-gfm'
import { mathFromMarkdown } from 'mdast-util-math'
import { gfm } from 'micromark-extension-gfm'
import { math } from 'micromark-extension-math'
import type { ActionCardFence } from './types.ts'
/** Language of a block that offers a card, matched after lowercasing, as the Chat client dispatches fences. */
/** Language of a block that offers a card, compared as the Chat client dispatches fences. */
export const ACTION_CARD_FENCE: ActionCardFence = 'action-card'
const OPENING = /^( {0,3})(`{3,}|~{3,})(.*)$/u
const CANDIDATE = new RegExp(ACTION_CARD_FENCE, 'iu')
/**
* Three backticks or tildes, then spaces or tabs, then a first info-string character that can decode to the card
* language: `a`, `A`, or the `&` of a character reference. Text without this opening holds no card block.
*/
const CARD_FENCE_OPENING = /(?:`{3}|~{3})[\t ]*[a&]/iu
/** An open fence: its closing line, its content indentation and, for a card block, the content read so far. */
interface OpenFence {
readonly closing: RegExp
readonly outdent: RegExp
readonly content: string[] | undefined
}
/** Lowercased leading letters, digits, `_` and `-` of an info string's first word. */
function languageOf(info: string): string {
return info.trim().replace(/[^\w-][\s\S]*$/u, '').toLowerCase()
}
/** The fence a line opens, or undefined when the line opens none. */
function opened(line: string): OpenFence | undefined {
const opening = OPENING.exec(line)
if (opening === null) return undefined
const indent = String(opening[1])
const marker = String(opening[2])
const info = String(opening[3])
if (marker.startsWith('`') && info.includes('`')) return undefined
return {
closing: new RegExp(`^ {0,3}${marker.charAt(0)}{${String(marker.length)},}[ \\t]*$`, 'u'),
outdent: new RegExp(`^ {0,${String(indent.length)}}`, 'u'),
content: languageOf(info) === ACTION_CARD_FENCE ? [] : undefined,
}
/** Append, in document order, the content of every non-empty code block at any depth whose language is the card language. */
function collect(node: Nodes, found: string[]): string[] {
const language = /^[\w-]+/u.exec(node.type === 'code' ? node.lang ?? '' : '')?.[0].toLowerCase()
if (node.type === 'code' && node.value !== '' && language === ACTION_CARD_FENCE) found.push(node.value)
if ('children' in node) for (const child of node.children) collect(child, found)
return found
}
/**
* Contents of the top-level fenced code blocks whose language is {@link ACTION_CARD_FENCE}, in text order.
* A fence opens with at least three backticks or tildes indented by at most three spaces, and closes at a line of the
* same character at least as long, or at the end of the text; content lines lose up to the opening's indentation.
* Fences inside lists or block quotes are not read.
* Contents of the fenced code blocks whose language is {@link ACTION_CARD_FENCE}, at any depth and in text order.
* The text is parsed with the GFM and math grammar of the Chat client's settled answers, so a block counts exactly when
* the client dispatches it to the card language: the leading letters, digits, `_` and `-` of the info string's first
* word after escapes and character references are decoded, compared case-insensitively. An empty block offers nothing.
* @param text - one text block of an assistant message.
* @returns the blocks' contents.
*/
export function actionCardFences(text: string): string[] {
const found: string[] = []
if (!CANDIDATE.test(text)) return found
let fence: OpenFence | undefined
for (const line of text.split(/\r?\n/u)) {
if (fence === undefined) {
fence = opened(line)
} else if (fence.closing.test(line)) {
if (fence.content !== undefined) found.push(fence.content.join('\n'))
fence = undefined
} else {
fence.content?.push(line.replace(fence.outdent, ''))
}
}
if (fence?.content !== undefined) found.push(fence.content.join('\n'))
return found
if (!CARD_FENCE_OPENING.test(text)) return []
return collect(fromMarkdown(text, {
extensions: [gfm({ singleTilde: false }), math()],
mdastExtensions: [gfmFromMarkdown(), mathFromMarkdown()],
}), [])
}
@@ -1,26 +1,35 @@
import { expect, it } from 'vitest'
import { actionCardFences } from '../src/fence.ts'
it('reads top-level action-card fences of either marker in text order, matching the language as the Chat client does', () => {
expect(actionCardFences('Answer.\n\n```action-card\n{"a":1}\n```\n')).toEqual(['{"a":1}'])
expect(actionCardFences('x\n~~~~ Action-Card extra words\n{"b":2}\n~~~~\nafter')).toEqual(['{"b":2}'])
expect(actionCardFences('```action-card{"c":3}\n{"c":3}\n```')).toEqual(['{"c":3}'])
expect(actionCardFences('```action-card\r\n{"d":4}\r\n```')).toEqual(['{"d":4}'])
const card = '{"a":1}'
it('reads action-card blocks of either marker in text order, decoding and matching the language as the Chat client does', () => {
expect(actionCardFences(`Answer.\n\n\`\`\`action-card\n${card}\n\`\`\`\n`)).toEqual([card])
expect(actionCardFences(`x\n~~~~ Action-Card extra words\n${card}\n~~~~\nafter`)).toEqual([card])
expect(actionCardFences(`\`\`\`action-card{"c":3}\n${card}\n\`\`\``)).toEqual([card])
expect(actionCardFences(`\`\`\`action-card\r\n${card}\r\n\`\`\``)).toEqual([card])
expect(actionCardFences('```action-card\n1\n```\ntext\n```action-card\n2\n```')).toEqual(['1', '2'])
expect(actionCardFences(`text\n\`\`\`action-card\n${card}`)).toEqual([card])
expect(actionCardFences(`\`\`\`action\\-card\n${card}\n\`\`\``)).toEqual([card])
expect(actionCardFences(`\`\`\`&#97;ction&#x2D;card\n${card}\n\`\`\``)).toEqual([card])
})
it('removes the opening indentation from content and runs an unclosed fence to the end of the text', () => {
expect(actionCardFences(' ```action-card\n {"a":1}\n {"b":2}\n ```')).toEqual(['{"a":1}\n {"b":2}'])
expect(actionCardFences('text\n```action-card\n{"open":true}')).toEqual(['{"open":true}'])
expect(actionCardFences('````action-card\n{"a":1}\n```\n````')).toEqual(['{"a":1}\n```'])
it('reads blocks nested in lists and block quotes, as the client renders them there too', () => {
expect(actionCardFences(`- item\n\n \`\`\`action-card\n ${card}\n \`\`\``)).toEqual([card])
expect(actionCardFences(`1. step\n \`\`\`action-card\n ${card}\n \`\`\``)).toEqual([card])
expect(actionCardFences(`- \`\`\`action-card\n ${card}\n \`\`\``)).toEqual([card])
expect(actionCardFences(`> \`\`\`action-card\n> ${card}\n> \`\`\``)).toEqual([card])
})
it('skips other languages, fences nested in another fence, indented code and backtick info strings', () => {
it('skips text the client does not render as a card block: other languages, empty blocks, HTML, indented code and nested fences', () => {
expect(actionCardFences('No card here.')).toEqual([])
expect(actionCardFences('action-card mentioned in prose only')).toEqual([])
expect(actionCardFences('action-card mentioned in prose, with an unlabeled block\n\n```\n{}\n```')).toEqual([])
expect(actionCardFences('```json\n{"action-card":true}\n```')).toEqual([])
expect(actionCardFences('```action-cards\n{}\n```')).toEqual([])
expect(actionCardFences('````md\n```action-card\n{"e":5}\n```\n````')).toEqual([])
expect(actionCardFences(' ```action-card\n {"f":6}\n ```')).toEqual([])
expect(actionCardFences('```action-card `x`\n{"g":7}\n```')).toEqual([])
expect(actionCardFences('```+action-card\n{}\n```')).toEqual([])
expect(actionCardFences('```action-card\n```')).toEqual([])
expect(actionCardFences(`<details>\n\`\`\`action-card\n${card}\n\`\`\`\n</details>`)).toEqual([])
expect(actionCardFences(` \`\`\`action-card\n ${card}\n \`\`\``)).toEqual([])
expect(actionCardFences(`\`\`\`\`md\n\`\`\`action-card\n${card}\n\`\`\`\n\`\`\`\``)).toEqual([])
expect(actionCardFences(`$$\n\`\`\`action-card\n${card}\n\`\`\`\n$$`)).toEqual([])
})
@@ -3,14 +3,14 @@
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/experimental/client-ui-action-cards/README.md
/:
en: 04e5b09d504b9c6d
zh: c477c03d68f696b4
en: b2ec6581c8910419
zh: d7131e343a702002
/deepseek-ai-dsh-client-ui-action-cards:
en: c36a554629f96f79
zh: 0ea837da87938e52
/deepseek-ai-dsh-client-ui-action-cards/summary:
en: edc6004ecea2e04d
zh: 7e66a631dc34791a
en: 191f5c437c721c58
zh: a2e2163a9d89d01a
/deepseek-ai-dsh-client-ui-action-cards/table-of-contents:
en: d152484eb41ac6b4
zh: b00dddf4c88f0a45
@@ -21,17 +21,17 @@
en: 9ec9f9f8f3165d3e
zh: 2d8154ec2fe0c9ab
/deepseek-ai-dsh-client-ui-action-cards/understand-the-implementation:
en: d81dd6582b58b34a
zh: 998196ebff842199
en: e518b1d72b7d6d8c
zh: ce22303653bb9c0d
/deepseek-ai-dsh-client-ui-action-cards/further-exploration:
en: 8a8fd260a90c34c2
zh: 5d3859326521d5b7
en: 538e6b8c9380c6d7
zh: a1723a10e78e3e8a
/deepseek-ai-dsh-client-ui-action-cards/model-experience:
en: f80a4b656c108f22
zh: a3e30f46fa7136ac
en: 85119b58566a0324
zh: 6405e0db54d066ac
/deepseek-ai-dsh-client-ui-action-cards/model-experience/kv-cache-effect:
en: 238b07582e981a18
zh: f026e4cfac22d8e7
en: 63c083d8bccf899e
zh: 510e586c377066bf
/deepseek-ai-dsh-client-ui-action-cards/known-limitations-and-deferred-work:
en: df94821940e4e2b8
zh: 490441ab06b153c9
@@ -1,5 +1,5 @@
---
description: "Browser half of optional action cards: the card frame below completed answers, the body registry that experiment packages fill, and the hiding of the action-card blocks that offer them."
description: "Browser half of optional action cards: the card frame below completed answers, the body registry that experiment packages fill, the layer for the action-card blocks that offer them, and the process row of older propose_action calls."
kind: "package-reference"
---
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
Users see an optional action card below a completed answer: its title, a brief that folds when long, and the controls of the experiment that proposed it. The answer's `action-card` block that offers the card never shows. A card whose experiment provides no controls in this browser offers only Not now. Showing, expanding and folding cards make no model request.
Users see an optional action card below a completed answer: its title, a brief that folds when long, and the controls of the experiment that proposed it. The answer's `action-card` block that offers the card stays hidden unless its content is not JSON. In Sessions recorded before cards moved into answers, the process area shows the proposal as one row with the card title and whether the call was accepted; a refused call expands to its reason. A card whose experiment provides no controls in this browser offers only Not now. Showing, expanding and folding cards make no model request.
## Table of Contents
@@ -41,14 +41,15 @@ A kind's browser plugin injects `actionCards` and registers its body inside its
One `conversation.chat.turnTail` entry reads the `actionCards` Session projection and shows the card admitted in its Turn after that Turn has ended with a final answer; a Turn that ends without answer text shows no card, and should several cards share a Turn, the lowest card id is shown. The frame sets `data-action-card` to the card id and names its region by the card title. Folding counts a wide grapheme, such as a Chinese character, as two Latin-letter widths and folds after about 260; it never measures layout or alters the full text.
A `conversation.chat.markdown.fence` layer keyed `action-card` renders nothing, so every such block in the Chat flow is hidden: in answers, reasoning and compaction summaries, including blocks the Host does not admit. The plugin provides the body registry at its top level, then mounts the generated `actionCards` Remote and registers its dictionaries and slot entries for the same lifetime.
A `conversation.chat.markdown.fence` layer keyed `action-card` renders nothing while the answer streams and once the block's content parses as JSON, so such blocks stay hidden wherever the Chat flow renders Markdown: in answers, reasoning and compaction summaries, including blocks the Host does not admit. A settled block whose content is not JSON offers no card and renders as plain code. A `tool.call.toolview` entry keyed `propose_action` renders the process row of older Sessions' calls from the recorded call arguments and result. The plugin provides the body registry at its top level, then mounts the generated `actionCards` Remote and registers its dictionaries and slot entries for the same lifetime.
| Source | Contents |
|---|---|
| [`src/client/mount.ts`](src/client/mount.ts) | Registry, Remote, dictionaries and slot entries |
| [`src/client/Card.tsx`](src/client/Card.tsx) | Turn tail, frame, fold, fallback body and hidden block |
| [`src/client/Card.tsx`](src/client/Card.tsx) | Turn tail, frame, fold, fallback body and block layer |
| [`src/client/ProposeRow.tsx`](src/client/ProposeRow.tsx) | Process row of older Sessions' calls |
| [`src/client/registry.ts`](src/client/registry.ts) | Body registry and body props |
| [`tests/`](tests/) | Placement, frame, fallback and registration tests |
| [`tests/`](tests/) | Placement, frame, fallback, block, row and registration tests |
</details>
@@ -57,18 +58,18 @@ A `conversation.chat.markdown.fence` layer keyed `action-card` renders nothing,
<a id="further-exploration"></a>
## Further Exploration
- [Action cards](../action-cards/README.md) — the tool, card state and user actions behind the frame.
- [Action cards](../action-cards/README.md) — the card blocks, card state and user actions behind the frame.
- [Personalized page cards](../client-ui-creation-recommendations/README.md) and [recommendation cards](../client-ui-plugin-recommendations/README.md) — the shipped card bodies.
- [Slots](../../client/ui-slots/README.md) — Turn tail and Markdown fence layer registration.
- [Slots](../../client/ui-slots/README.md) — Turn tail, Markdown fence layer and tool row registration.
<a id="model-experience"></a>
## Model Experience
Indirectly, through the Host card service: card actions reach it as Remote calls, and it owns the logged tool, decisions and status notice.
Indirectly, through the Host card service: card actions reach it as Remote calls, and it owns the card proposals read from answers, decisions and status notice.
#### KV Cache effect
Rendering cards and hiding their blocks does not change any model request.
Rendering cards, their blocks and process rows does not change any model request.
## Known Limitations and Deferred Work
@@ -1,5 +1,5 @@
---
description: "可选操作卡片的浏览器端:已完成回答下方的卡片框架、供各实验包填入的正文注册表,以及隐藏提供卡片的 action-card 代码块。"
description: "可选操作卡片的浏览器端:已完成回答下方的卡片框架、供各实验包填入的正文注册表、提供卡片的 action-card 代码块的显示层,以及旧版 propose_action 调用的过程行。"
kind: "package-reference"
---
@@ -9,7 +9,7 @@ kind: "package-reference"
## 概述
用户在已完成的回答下方看到一张可选操作卡片:标题、过长时会折叠的说明,以及提议该卡片的实验所提供的控件。回答里提供卡片的 `action-card` 代码块不会显示。如果实验在当前浏览器中没有提供控件,卡片只提供“暂不需要”。展示、展开和折叠卡片都不会发起模型请求。
用户在已完成的回答下方看到一张可选操作卡片:标题、过长时会折叠的说明,以及提议该卡片的实验所提供的控件。回答里提供卡片的 `action-card` 代码块保持隐藏,除非其内容不是 JSON。在卡片改为写在回答里之前录下的会话中,过程区把提议显示为一行,带卡片标题和调用是否被接受;被拒绝的调用可以展开查看原因。如果实验在当前浏览器中没有提供控件,卡片只提供“暂不需要”。展示、展开和折叠卡片都不会发起模型请求。
## 目录
@@ -41,14 +41,15 @@ kind: "package-reference"
一个 `conversation.chat.turnTail` 条目读取 `actionCards` 会话投影,在某一轮以最终回答结束后展示该轮接受的卡片;没有回答文本就结束的轮次不显示卡片,若同一轮有多张卡片,显示卡片 id 最小的一张。框架把 `data-action-card` 设为卡片 id,并以卡片标题命名所在区域。折叠时,宽字素(如汉字)按两个拉丁字母宽度计算,约 260 个单位后折叠;折叠不测量布局,也不改动完整文本。
一个以 `action-card` 为键的 `conversation.chat.markdown.fence` 层不渲染任何内容,因此 Chat 流中所有这类代码块都被隐藏:包括回答、思考内容和压缩摘要中的代码块,以及 Host 没有收下的代码块。插件在顶层提供正文注册表,然后挂载生成的 `actionCards` Remote,并在同一生命周期内注册词典和插槽条目。
一个以 `action-card` 为键的 `conversation.chat.markdown.fence` 层在回答流式输出期间、以及代码块内容能解析为 JSON 时不渲染任何内容,因此 Chat 流中凡是渲染 Markdown 的地方,这类代码块都被隐藏:包括回答、思考内容和压缩摘要中的代码块,以及 Host 没有收下的代码块。回答落定后内容不是 JSON 的代码块不会产生卡片,按普通代码显示。一个以 `propose_action` 为键的 `tool.call.toolview` 条目,根据记录的调用参数和结果渲染旧会话中该调用的过程行。插件在顶层提供正文注册表,然后挂载生成的 `actionCards` Remote,并在同一生命周期内注册词典和插槽条目。
| 源码 | 内容 |
|---|---|
| [`src/client/mount.ts`](src/client/mount.ts) | 注册表、Remote、词典与插槽条目 |
| [`src/client/Card.tsx`](src/client/Card.tsx) | 轮次尾部、框架、折叠、兜底正文与隐藏代码块 |
| [`src/client/Card.tsx`](src/client/Card.tsx) | 轮次尾部、框架、折叠、兜底正文与代码块显示层 |
| [`src/client/ProposeRow.tsx`](src/client/ProposeRow.tsx) | 旧会话中调用的过程行 |
| [`src/client/registry.ts`](src/client/registry.ts) | 正文注册表与正文属性 |
| [`tests/`](tests/) | 位置、框架、兜底与注册测试 |
| [`tests/`](tests/) | 位置、框架、兜底、代码块、过程行与注册测试 |
</details>
@@ -57,18 +58,18 @@ kind: "package-reference"
<a id="further-exploration"></a>
## 延伸阅读
- [操作卡片](../action-cards/README.zh.md) — 框架背后的工具、卡片状态与用户操作。
- [操作卡片](../action-cards/README.zh.md) — 框架背后的卡片代码块、卡片状态与用户操作。
- [个性化页面卡片](../client-ui-creation-recommendations/README.zh.md)和[推荐卡片](../client-ui-plugin-recommendations/README.zh.md) — 随产品提供的卡片正文。
- [插槽](../../client/ui-slots/README.zh.md) — 轮次尾部与 Markdown 代码块层的注册。
- [插槽](../../client/ui-slots/README.zh.md) — 轮次尾部、Markdown 代码块层与工具行的注册。
<a id="model-experience"></a>
## 模型体验
间接影响来自 Host 卡片服务:卡片操作以 Remote 调用到达该服务,由它负责记录在日志中的工具、决定和状态通知。
间接影响来自 Host 卡片服务:卡片操作以 Remote 调用到达该服务,由它负责从回答中读出的卡片提议、决定和状态通知。
#### KV Cache 影响
渲染卡片和隐藏代码块不会改变任何模型请求。
渲染卡片、代码块和过程行不会改变任何模型请求。
## 已知限制与后续工作
@@ -8,7 +8,7 @@
"types": "lib/types/index.d.ts",
"license": "MIT",
"name": "@deepseek-ai/dsh-client-ui-action-cards",
"description": "Action cards below completed answers: the shared card frame, kind bodies and the compact tool row",
"description": "Action cards below completed answers: the shared card frame, kind bodies, the layer for the answer blocks that offer them, and the tool row of older Sessions",
"repository": {
"type": "git",
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
@@ -35,7 +35,8 @@
"@deepseek-ai/dsh-client-locale",
"@deepseek-ai/dsh-client-ui-conversation",
"@deepseek-ai/dsh-client-ui-chat",
"@deepseek-ai/dsh-client-ui-session"
"@deepseek-ai/dsh-client-ui-session",
"@deepseek-ai/dsh-client-ui-tool"
]
}
},
@@ -54,6 +55,7 @@
"@deepseek-ai/dsh-client-ui-session": "workspace:*",
"@deepseek-ai/dsh-client-ui-slots": "workspace:*",
"@deepseek-ai/dsh-client-ui-primitives": "workspace:*",
"@deepseek-ai/dsh-client-ui-tool": "workspace:*",
"react": "^18.2.0",
"@deepseek-ai/dsh-action-cards": "workspace:*",
"@deepseek-ai/dsh-typert-protocol": "workspace:*",
@@ -1,7 +1,7 @@
/** The card frame below a completed answer (title, folded brief, the kind's body or a dismiss-only fallback) and the hidden card block. */
/** The card frame below a completed answer (title, folded brief, the kind's body or a dismiss-only fallback) and the card block layer. */
import { useCallback, useId, useMemo, useState, type ReactNode } from 'react'
import { Button } from '@deepseek-ai/dsh-client-ui-primitives'
import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, Translate } from '@deepseek-ai/dsh-client-ui-slots'
import type { HocShare, HostObservable, InjectFace, PropsLocale, PropsRuntime, SlotMap, Translate } from '@deepseek-ai/dsh-client-ui-slots'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type {
ActionCardDecision, ActionCardFence, ActionCardFields, ActionCardId, ActionCardProposal, ActionCardResult, ActionCardView,
@@ -79,14 +79,27 @@ function decisionOf(view: ActionCardView | undefined, cardId: string): ActionCar
}
/** Language of the answer blocks that offer cards; the Host reads each card from its block. */
export const CARD_FENCE: ActionCardFence = 'action-card'
export const ACTION_CARD_FENCE: ActionCardFence = 'action-card'
/** Props of the card block layer: the fence and the plain code block it can show instead. */
type CardBlockProps = PropsRuntime<'conversation.chat.markdown.fence'> & HocShare<SlotMap['conversation.chat.markdown.fence']>
/** Whether model-written block content is JSON. */
function parses(code: string): boolean {
try { JSON.parse(code) }
catch { return false } // Text that is not JSON offers no card.
return true
}
/**
* Hide an `action-card` block wherever the Chat flow renders Markdown: its card appears below the turn's final answer.
* @returns nothing, so the block's JSON is never shown.
* Show an `action-card` block wherever the Chat flow renders Markdown. While the answer streams and once its content
* parses as JSON, the block renders nothing: a card it offers appears below the turn's final answer. A settled block
* that is not JSON offers no card, so it shows as plain code.
* @param props - the fence and the plain code block.
* @returns nothing, or the plain code block.
*/
export function HiddenCardBlock(): null {
return null
export function CardBlock({ code, streaming, children }: CardBlockProps): ReactNode {
return streaming || parses(code) ? null : children
}
/**
@@ -0,0 +1,6 @@
/** The card title stays readable beside the call state. */
.summary { margin-left: 8px; display: flex; align-items: center; gap: 8px; min-width: 0; color: inherit; font-size: 12px; }
.summary > :first-child { flex-shrink: 0; }
.title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.reason { margin: 8px 0; padding: 12px; border-radius: var(--dsw-radius-lg); background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-secondary); white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; }
.inspect { align-self: flex-start; border: none; padding: 4px 0; background: transparent; color: var(--dsw-alias-link); font: inherit; font-size: 12px; cursor: pointer; }
@@ -0,0 +1,43 @@
/** One-line process row for a `propose_action` call: the card title and whether the card was shown. */
import { useState } from 'react'
import { DisclosureRow, IconAppsAddOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'
import type { ToolCallViewProps } from '@deepseek-ai/dsh-client-ui-tool/client'
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
import css from './ProposeRow.module.css'
type ProposeRowProps = ToolCallViewProps & PropsLocale<'actionCards'>
/** Call states with row copy; a preparing call has no complete arguments yet. */
type RowState = 'preparing' | 'running' | 'ok' | 'error' | 'stopped'
function stateOf(props: ProposeRowProps): RowState {
if (props.phase === 'preparing') return 'preparing'
if (props.phase === 'start') return 'running'
if (props.block.error?.code === 'interrupted') return 'stopped'
return props.block.isError ? 'error' : 'ok'
}
/**
* Render a `propose_action` call from its recorded arguments and result. Only a refused call expands, to show
* why no card followed the answer.
* @param props - tool call and localized status copy.
* @returns the status row.
*/
export function ProposeRow(props: ProposeRowProps) {
const { block, inspect, t } = props
const [expanded, setExpanded] = useState(false)
const state = stateOf(props)
const title = block.args.text('title') ?? ''
const reason = props.phase === 'result' && props.block.isError
? props.block.content.flatMap(item => item.type === 'text' ? [item.text] : []).join('\n')
: ''
return <div data-tool="propose_action" data-state={state}>
<DisclosureRow title={t('row.title')} icon={<IconAppsAddOutlineRegular size={14} />} running={state === 'preparing' || state === 'running'}
open={expanded && reason !== ''} expandable={reason !== ''} expandOnRowClick keepContentWhenOpen
onToggle={() => { setExpanded(value => !value) }}
collapsedContent={<span className={css.summary}><span>{t(`row.${state}`)}</span><span className={css.title}>{title}</span></span>}>
<pre className={css.reason}>{reason}</pre>
{inspect && <button type="button" className={css.inspect} onClick={inspect}>{t('row.inspect')}</button>}
</DisclosureRow>
</div>
}
@@ -1,66 +1,82 @@
/** English card frame and fallback copy. */
/** English card frame, fallback and tool-row copy. */
export const en = {
expandBrief: 'Show more', collapseBrief: 'Show less',
dismiss: 'Not now', dismissed: 'Dismissed', replaced: 'Replaced',
unavailable: 'This action is unavailable. Check the plugin in Plugins.',
transport: 'Could not confirm the result. Reconnect and check the card before retrying.',
'row.title': 'Action card', 'row.preparing': 'Preparing a card', 'row.running': 'Proposing',
'row.ok': 'Proposed', 'row.error': 'Not shown', 'row.stopped': 'Interrupted', 'row.inspect': 'Inspect call',
}
/** Keys shared by every dictionary. */
export type ActionCardKey = keyof typeof en
/** Chinese card frame and fallback copy. */
/** Chinese card frame, fallback and tool-row copy. */
export const zh: Record<ActionCardKey, string> = {
expandBrief: '展开', collapseBrief: '收起',
dismiss: '暂不需要', dismissed: '已忽略', replaced: '已替换',
unavailable: '暂时无法执行,请到插件页面查看',
transport: '暂时无法确认结果,请重新连接并查看卡片状态后再重试',
'row.title': '操作卡片', 'row.preparing': '正在准备卡片', 'row.running': '正在提议',
'row.ok': '已提议', 'row.error': '未显示', 'row.stopped': '已中断', 'row.inspect': '查看调用',
}
/** Japanese card frame and fallback copy. */
/** Japanese card frame, fallback and tool-row copy. */
export const ja: Record<ActionCardKey, string> = {
expandBrief: 'すべて表示', collapseBrief: '折りたたむ',
dismiss: '今はしない', dismissed: '却下済み', replaced: '置き換え済み',
unavailable: 'この操作は利用できません。プラグイン画面でプラグインを確認してください。',
transport: '結果を確認できませんでした。再接続してカードを確認してから再試行してください。',
'row.title': 'アクションカード', 'row.preparing': 'カードを準備中', 'row.running': '提案中',
'row.ok': '提案済み', 'row.error': '表示されませんでした', 'row.stopped': '中断されました', 'row.inspect': '呼び出しを確認',
}
/** Spanish card frame and fallback copy. */
/** Spanish card frame, fallback and tool-row copy. */
export const es: Record<ActionCardKey, string> = {
expandBrief: 'Mostrar más', collapseBrief: 'Mostrar menos',
dismiss: 'Ahora no', dismissed: 'Descartado', replaced: 'Reemplazado',
unavailable: 'Esta acción no está disponible. Revisa el complemento en Complementos.',
transport: 'No se pudo confirmar el resultado. Vuelve a conectarte y revisa la tarjeta antes de reintentar.',
'row.title': 'Tarjeta de acción', 'row.preparing': 'Preparando una tarjeta', 'row.running': 'Proponiendo',
'row.ok': 'Propuesto', 'row.error': 'No se mostró', 'row.stopped': 'Interrumpido', 'row.inspect': 'Inspeccionar llamada',
}
/** French card frame and fallback copy. */
/** French card frame, fallback and tool-row copy. */
export const fr: Record<ActionCardKey, string> = {
expandBrief: 'Afficher plus', collapseBrief: 'Afficher moins',
dismiss: 'Pas maintenant', dismissed: 'Ignoré', replaced: 'Remplacé',
unavailable: "Cette action n'est pas disponible. Vérifiez le plugin dans Plugins.",
transport: 'Impossible de confirmer le résultat. Reconnectez-vous et vérifiez la carte avant de réessayer.',
'row.title': "Carte d'action", 'row.preparing': "Préparation d'une carte", 'row.running': 'Proposition en cours',
'row.ok': 'Proposé', 'row.error': 'Non affiché', 'row.stopped': 'Interrompu', 'row.inspect': "Inspecter l'appel",
}
/** German card frame and fallback copy. */
/** German card frame, fallback and tool-row copy. */
export const de: Record<ActionCardKey, string> = {
expandBrief: 'Mehr anzeigen', collapseBrief: 'Weniger anzeigen',
dismiss: 'Nicht jetzt', dismissed: 'Verworfen', replaced: 'Ersetzt',
unavailable: 'Diese Aktion ist nicht verfügbar. Prüfen Sie das Plugin unter Plugins.',
transport: 'Das Ergebnis konnte nicht bestätigt werden. Verbinden Sie sich erneut und prüfen Sie die Karte, bevor Sie es erneut versuchen.',
'row.title': 'Aktionskarte', 'row.preparing': 'Karte wird vorbereitet', 'row.running': 'Wird vorgeschlagen',
'row.ok': 'Vorgeschlagen', 'row.error': 'Nicht angezeigt', 'row.stopped': 'Unterbrochen', 'row.inspect': 'Aufruf prüfen',
}
/** Russian card frame and fallback copy. */
/** Russian card frame, fallback and tool-row copy. */
export const ru: Record<ActionCardKey, string> = {
expandBrief: 'Показать больше', collapseBrief: 'Показать меньше',
dismiss: 'Не сейчас', dismissed: 'Отклонено', replaced: 'Заменено',
unavailable: 'Это действие недоступно. Проверьте плагин в разделе «Плагины».',
transport: 'Не удалось подтвердить результат. Переподключитесь и проверьте карточку перед повторной попыткой.',
'row.title': 'Карточка действия', 'row.preparing': 'Подготовка карточки', 'row.running': 'Предлагается',
'row.ok': 'Предложено', 'row.error': 'Не показано', 'row.stopped': 'Прервано', 'row.inspect': 'Проверить вызов',
}
/** Portuguese card frame and fallback copy. */
/** Portuguese card frame, fallback and tool-row copy. */
export const pt: Record<ActionCardKey, string> = {
expandBrief: 'Mostrar mais', collapseBrief: 'Mostrar menos',
dismiss: 'Agora não', dismissed: 'Dispensado', replaced: 'Substituído',
unavailable: 'Esta ação não está disponível. Verifique o plug-in em Plug-ins.',
transport: 'Não foi possível confirmar o resultado. Reconecte-se e verifique o cartão antes de tentar novamente.',
'row.title': 'Cartão de ação', 'row.preparing': 'Preparando um cartão', 'row.running': 'Propondo',
'row.ok': 'Proposto', 'row.error': 'Não exibido', 'row.stopped': 'Interrompido', 'row.inspect': 'Inspecionar chamada',
}
@@ -1,4 +1,4 @@
/** Register the card frame, the hidden answer block, their copy and the body registry. */
/** Register the card frame, the answer block layer, the tool row of older Sessions, their copy and the body registry. */
import type { Context } from '@deepseek-ai/cordis'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type {} from '@deepseek-ai/dsh-api-remotes/client'
@@ -6,9 +6,11 @@ import type {} from '@deepseek-ai/dsh-client-locale/client'
import type {} from '@deepseek-ai/dsh-client-ui-session/client'
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
import type {} from '@deepseek-ai/dsh-client-ui-chat/client'
import type {} from '@deepseek-ai/dsh-client-ui-tool/client'
import type {} from '@deepseek-ai/dsh-action-cards/remote'
import type { TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol'
import { ActionCardTail, CARD_FENCE, HiddenCardBlock, type TailInjected } from './Card.tsx'
import { ACTION_CARD_FENCE, ActionCardTail, CardBlock, type TailInjected } from './Card.tsx'
import { ProposeRow } from './ProposeRow.tsx'
import { ActionCardRegistry } from './registry.ts'
import { de, en, es, fr, ja, pt, ru, zh, type ActionCardKey } from './locales.ts'
@@ -57,6 +59,10 @@ function registerUi(ctx: Context, registry: ActionCardRegistry): void {
}),
}, ActionCardTail))
ctx.slots.inject('conversation.chat.markdown.fence', () => ctx.slots.register(
{ name: 'conversation.chat.markdown.fence', key: CARD_FENCE, id: '@deepseek-ai/dsh-client-ui-action-cards/block' }, HiddenCardBlock,
{ name: 'conversation.chat.markdown.fence', key: ACTION_CARD_FENCE, id: '@deepseek-ai/dsh-client-ui-action-cards/block' }, CardBlock,
))
// Sessions recorded before cards moved into answers offered them through `propose_action` calls.
ctx.slots.inject('tool.call.toolview', () => ctx.slots.register(
{ name: 'tool.call.toolview', key: 'propose_action', locale: 'actionCards' }, ProposeRow,
))
}
@@ -9,7 +9,8 @@ import type { ActionCardId } from '@deepseek-ai/dsh-action-cards/types'
import { expect, it, onTestFinished, vi } from 'vitest'
import { mountActionCards, inject } from '../src/client/mount.ts'
import { apply as hostApply } from '../src/index.ts'
import { HiddenCardBlock, type TailInjected } from '../src/client/Card.tsx'
import { CardBlock, type TailInjected } from '../src/client/Card.tsx'
import { ProposeRow } from '../src/client/ProposeRow.tsx'
const apply = (ctx: Context) => mountActionCards(ctx, { package: '@deepseek-ai/dsh-action-cards', descriptors: [] })
const Body = () => null
@@ -23,6 +24,7 @@ it('binds actions to the displayed session, serves registered bodies and removes
slots.register({ name: 'root', children: {
'conversation.chat.turnTail': { kind: 'list', scope: 'session' },
'conversation.chat.markdown.fence': { kind: 'hoc', scope: 'session' },
'tool.call.toolview': { kind: 'keyed', scope: 'session' },
} }, (_props: { renderSlot?: unknown }) => null)
const act = vi.fn().mockResolvedValue({ ok: true, value: { status: 'accepted' } })
const unmount = vi.fn(async () => {})
@@ -32,9 +34,8 @@ it('binds actions to the displayed session, serves registered bodies and removes
ctx.provide('locale', locale)
const fiber = await ctx.plugin({ inject, apply })
const entry = slots.entries('conversation.chat.turnTail')[0]!
expect(slots.entries('conversation.chat.markdown.fence').map(item => [item.options.key, item.component]))
.toEqual([['action-card', HiddenCardBlock]])
expect(HiddenCardBlock()).toBeNull()
expect(slots.entries('conversation.chat.markdown.fence').map(item => [item.options.key, item.component])).toEqual([['action-card', CardBlock]])
expect(slots.entries('tool.call.toolview').map(item => [item.options.key, item.component])).toEqual([['propose_action', ProposeRow]])
const resolve = entry.inject as NonNullable<typeof entry.inject> & ((sessionId: SessionId) => TailInjected)
const bound = resolve(brandString<SessionId>('session-one'))
expect(bound.sessionId).toBe('session-one')
@@ -68,6 +69,7 @@ it('binds actions to the displayed session, serves registered bodies and removes
expect(unmount).toHaveBeenCalledOnce()
expect(slots.entries('conversation.chat.turnTail')).toHaveLength(0)
expect(slots.entries('conversation.chat.markdown.fence')).toHaveLength(0)
expect(slots.entries('tool.call.toolview')).toHaveLength(0)
expect(ctx.get('actionCards')).toBeUndefined()
vi.spyOn(locale, 'register').mockImplementation(() => { throw new Error('registration failed') })
const failed = ctx.plugin({ inject, apply })
@@ -6,7 +6,7 @@ import { brandString } from '@deepseek-ai/dsh-brand'
import type { ActionCardId } from '@deepseek-ai/dsh-action-cards/types'
import { type SessionId, SessionSeq } from '@deepseek-ai/dsh-session/types'
import type { ActionCardDecision, ActionCardResult, ActionCardView } from '@deepseek-ai/dsh-action-cards/types'
import { ActionCard, ActionCardTail, FoldedText } from '../src/client/Card.tsx'
import { ActionCard, ActionCardTail, CardBlock, FoldedText } from '../src/client/Card.tsx'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { en, zh } from '../src/client/locales.ts'
import type { ActionCardBodyProps, RegisteredBody } from '../src/client/registry.ts'
@@ -140,3 +140,16 @@ it('only offers expansion for omitted text and preserves the full brief without
expect(screen.queryByRole('button', { name: zh.expandBrief })).toBeNull()
expect(paragraph.textContent).toBe(prefix)
})
it('hides an action-card block while the answer streams and once it parses, and shows a settled block that is not JSON', () => {
type BlockProps = ComponentProps<typeof CardBlock>
const block = (code: string, streaming: boolean) =>
render(<CardBlock {...{ lang: 'action-card', code, streaming } as BlockProps}><pre data-testid="code" /></CardBlock>)
for (const [code, streaming] of [['{"action":"a"}', false], ['{"act', true]] as const) {
block(code, streaming)
expect(screen.queryByTestId('code')).toBeNull()
cleanup()
}
block('{"act', false)
expect(screen.getByTestId('code')).toBeTruthy()
})
@@ -0,0 +1,55 @@
// @vitest-environment jsdom
/** The process row reads the card title from the recorded arguments and expands only a refused call. */
import { cleanup, fireEvent, render } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import type { StartedToolCall, ToolResultNode } from '@deepseek-ai/dsh-client-ui-chat/client'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { PartialArguments } from '@deepseek-ai/dsh-util-values'
import { ProposeRow } from '../src/client/ProposeRow.tsx'
import { en } from '../src/client/locales.ts'
afterEach(cleanup)
type Props = Parameters<typeof ProposeRow>[0]
const argsRaw = JSON.stringify({ action: 'test_action', title: 'Counter', brief: 'Keep count.', details: {} })
const running: StartedToolCall = { phase: 'start', args: PartialArguments.fromText(argsRaw), callId: 'c', name: 'propose_action', argsRaw, turn: 1, step: 1, time: 1, subCalls: [] }
const settled: ToolResultNode = { kind: 'tool-result', seq: 2, time: 2, callId: 'c', name: 'propose_action', args: PartialArguments.fromText(argsRaw),
call: { name: 'propose_action', argsRaw }, callTime: 1, content: [{ type: 'text', text: 'Card shown below your answer. Do not restate it. Invite the user.' }], isError: false, subCalls: [] }
function props(block: Props['block'], inspect?: () => void): Props {
return { ...('kind' in block ? { phase: 'result' as const, block } : { phase: block.phase, block }),
callId: 'c', toolName: 'propose_action', openFile: vi.fn(), inspect, t: makeTranslate(en) } as Props
}
it('shows a proposed card on one line without exposing the model-facing result', () => {
const view = render(<ProposeRow {...props(settled)} />)
expect(view.container.querySelector('[data-tool="propose_action"]')?.getAttribute('data-state')).toBe('ok')
expect(view.getByText('Proposed')).toBeTruthy()
expect(view.getByText('Counter')).toBeTruthy()
expect(view.queryByRole('button')).toBeNull()
expect(view.container.textContent).not.toContain('Card shown below your answer. Do not restate it. Invite the user.')
})
it('explains a refused call and offers call inspection', () => {
const inspect = vi.fn()
const view = render(<ProposeRow {...props({ ...settled, isError: true,
content: [{ type: 'text', text: 'Error: Load skill test-skill first, then call propose_action.' }, { type: 'reasoning', text: 'hidden' }] }, inspect)} />)
expect(view.getByText('Not shown')).toBeTruthy()
const row = view.getByRole('button')
fireEvent.click(row)
expect(view.container.querySelector('pre')?.textContent).toBe('Error: Load skill test-skill first, then call propose_action.')
fireEvent.click(view.getByRole('button', { name: 'Inspect call' }))
expect(inspect).toHaveBeenCalledOnce()
fireEvent.click(row)
expect(row.getAttribute('aria-expanded')).toBe('false')
})
it.each([
['preparing', { phase: 'preparing', args: PartialArguments.EMPTY, callId: 'c', name: 'propose_action', turn: 1, step: 1, time: 1, subCalls: [] }, 'Preparing a card'],
['running', running, 'Proposing'],
['stopped', { ...settled, isError: true, content: [], error: { name: 'Interrupted', code: 'interrupted' } }, 'Interrupted'],
] as const)('renders the %s call stage without claiming a card', (state, block, label) => {
const view = render(<ProposeRow {...props(block)} />)
expect(view.container.querySelector('[data-tool="propose_action"]')?.getAttribute('data-state')).toBe(state)
expect(view.getAllByText(label).length).toBeGreaterThan(0)
expect(view.queryByText('Proposed')).toBeNull()
expect(view.queryByRole('button')).toBeNull()
})
@@ -17,6 +17,7 @@
{ "path": "../../client/ui-session" },
{ "path": "../../client/ui-slots" },
{ "path": "../../client/ui-primitives" },
{ "path": "../../client/ui-tool" },
{ "path": "../../core/session" },
{ "path": "../action-cards" },
{ "path": "../../typert/protocol" },
@@ -483,7 +483,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
'client-ui-chat MathFenceLayer id \'@deepseek-ai/dsh-client-ui-chat/fence/math\' key \'math\'',
'client-ui-chat DiffFenceLayer id \'@deepseek-ai/dsh-client-ui-chat/fence/diff\' key \'diff\'',
'client-ui-chat DiffFenceLayer id \'@deepseek-ai/dsh-client-ui-chat/fence/diff\' key \'patch\'',
'client-ui-action-cards HiddenCardBlock id \'@deepseek-ai/dsh-client-ui-action-cards/block\'',
'client-ui-action-cards CardBlock id \'@deepseek-ai/dsh-client-ui-action-cards/block\'',
],
replaceRisk: 'wraps-owner-content',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.markdown.fence\', () => ctx.slots.register(\n { name: \'conversation.chat.markdown.fence\', id: \'my-layer\', order: 100 },\n ({ children }) => React.createElement(\'div\', null, children),\n ))\n },\n}',
@@ -6234,7 +6234,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
'useAccess: (action: RemoteEndpoint) => boolean',
'useTrajectory: UseTrajectory',
],
keyDomain: 'open: any string the owner dispatches (no compile-time key set), already taken: apply_patch, ask_user_question, bash, cordis_define, cordis_inspect, cordis_inspect_list, cordis_inspect_query, cordis_inspect_self, cordis_run, cordis_stop, cordis_undefine, create_goal, edit, get_goal, glob, grep, interrupt_agent, job_kill, job_list, job_output, list_agents, list_subagent_models, lsp, office_convert, office_recalculate, office_render, present, ralph, read, read_image, schedule_create, schedule_delete, schedule_edit, schedule_list, schedule_update, schedule_view, send_message, session_event_read, session_event_search, session_event_trace, session_search, session_trace, skill, spawn_teammate, subagent, subagent_fork, team_task_create, team_task_get, team_task_list, team_task_update, terminal_close, terminal_list, terminal_open, terminal_read, terminal_signal, timeline_tasks, todo_write, update_goal, wait_agent, web_fetch, web_search, workflow, write',
keyDomain: 'open: any string the owner dispatches (no compile-time key set), already taken: apply_patch, ask_user_question, bash, cordis_define, cordis_inspect, cordis_inspect_list, cordis_inspect_query, cordis_inspect_self, cordis_run, cordis_stop, cordis_undefine, create_goal, edit, get_goal, glob, grep, interrupt_agent, job_kill, job_list, job_output, list_agents, list_subagent_models, lsp, office_convert, office_recalculate, office_render, present, propose_action, ralph, read, read_image, schedule_create, schedule_delete, schedule_edit, schedule_list, schedule_update, schedule_view, send_message, session_event_read, session_event_search, session_event_trace, session_search, session_trace, skill, spawn_teammate, subagent, subagent_fork, team_task_create, team_task_get, team_task_list, team_task_update, terminal_close, terminal_list, terminal_open, terminal_read, terminal_signal, timeline_tasks, todo_write, update_goal, wait_agent, web_fetch, web_search, workflow, write',
hookContext: '',
slotInject: '',
declaredBy: 'an entry in \'conversation.chat.node\' (client-ui-tool), so it exists while that entry is mounted',
@@ -6297,6 +6297,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
'client-ui-tool TodoRow key \'todo_write\'',
'client-ui-tool WebRow key \'web_search\'',
'client-ui-tool WebRow key \'web_fetch\'',
'client-ui-action-cards ProposeRow key \'propose_action\'',
'timeline TaskCard key \'timeline_tasks\'',
'client-ui-cordis CordisDefineRow key \'cordis_define\'',
'client-ui-cordis CordisRunRow key \'cordis_run\'',
@@ -195,7 +195,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo
| Package | Config | Description |
|---|---|---|
| `@deepseek-ai/dsh-action-cards` | no | Optional action cards below answers: card state, user actions and status notices |
| `@deepseek-ai/dsh-client-ui-action-cards` | no | Action cards below completed answers: the shared card frame, kind bodies and the compact tool row |
| `@deepseek-ai/dsh-client-ui-action-cards` | no | Action cards below completed answers: the shared card frame, kind bodies, the layer for the answer blocks that offer them, and the tool row of older Sessions |
| `@deepseek-ai/dsh-client-ui-creation-recommendations` | no | Body of the personalized page card: location choice, creation progress, Undo and Restore |
| `@deepseek-ai/dsh-client-ui-plugin-recommendations` | no | Official plugin card body with catalog text and enabling |
| `@deepseek-ai/dsh-creation-recommendations` | no | Create persistent removable interface plugins from explicit conversation needs |
+21
View File
@@ -8839,6 +8839,21 @@ importers:
'@deepseek-ai/dsh-brand':
specifier: workspace:*
version: link:../../util/brand
mdast-util-from-markdown:
specifier: ^2.1.0
version: 2.1.0([email protected])
mdast-util-gfm:
specifier: ^3.1.0
version: 3.1.0([email protected])
mdast-util-math:
specifier: ^3.0.0
version: 3.0.0([email protected])
micromark-extension-gfm:
specifier: ^3.0.0
version: 3.0.0
micromark-extension-math:
specifier: ^3.1.0
version: 3.1.0
zod:
specifier: 4.6.6
version: 4.6.6
@@ -8876,6 +8891,9 @@ importers:
'@deepseek-ai/dsh-util-values':
specifier: workspace:*
version: link:../../util/values
'@types/mdast':
specifier: ^4.0.4
version: 4.0.4
packages/experimental/api-speech-to-text:
dependencies:
@@ -9418,6 +9436,9 @@ importers:
'@deepseek-ai/dsh-client-ui-slots':
specifier: workspace:*
version: link:../../client/ui-slots
'@deepseek-ai/dsh-client-ui-tool':
specifier: workspace:*
version: link:../../client/ui-tool
'@deepseek-ai/dsh-session':
specifier: workspace:*
version: link:../../core/session