fix(web): trim unused user text features and cover rendering

This commit is contained in:
imccyu committed 2026-10-11 02:03:27 +08:00
1 parent a46d5b143f
commit ed629da5da
41 files changed
+365 -692

No files matched your search

@@ -24,14 +24,14 @@
en: fe4eeb8e8b664e89
zh: 12ca0841b31e5550
/agent-note-linear-user-text-transforms-facts-dependencies-and-business-node-rendering/decision/reference-reuse-and-determinism:
en: 4d654ad1f0045060
zh: 9fe36047370b3fc1
en: d921bef12061c36d
zh: 314a496441525a85
/agent-note-linear-user-text-transforms-facts-dependencies-and-business-node-rendering/decision/facts-and-display-props:
en: 070761de46ce492a
zh: 8013b575f40b6ea7
en: ba3e871455bea24b
zh: fe558d53cf1e5bb2
/agent-note-linear-user-text-transforms-facts-dependencies-and-business-node-rendering/decision/rendering-and-interaction-ownership:
en: 928254237025d31a
zh: d7288468104226fc
en: eee69956dfcde909
zh: 53a12448ee47a5a2
/agent-note-linear-user-text-transforms-facts-dependencies-and-business-node-rendering/decision/publication-and-failure:
en: c1577c8ddfa447bc
zh: 9233dab4e8eb4b3b
@@ -39,8 +39,8 @@
en: dc106896de5ccb57
zh: 224d2db274d2df84
/agent-note-linear-user-text-transforms-facts-dependencies-and-business-node-rendering/verification-requirements:
en: de75b3dbcb42056f
zh: 3b02843d14909a46
en: c107fdcbeb5f56eb
zh: 278bf123f99af38b
/agent-note-linear-user-text-transforms-facts-dependencies-and-business-node-rendering/alternatives-considered:
en: fa52b4ce828182ff
zh: 311d37b799b67b04
@@ -67,7 +67,7 @@ The document's data-layer evaluation instance owns its cache. The registry creat
### Reference reuse and determinism
Input arrays, nodes, and Facts are readonly. Rules must not `splice` input in place, mutate node payloads, or use retained references to modify later results. Unchanged input nodes remain shared; entirely unchanged results retain the array reference instead of using full deep copies for isolation.
Input arrays, nodes, and Facts use readonly TypeScript types; the runner borrows values without freezing or copying them. Rules must not `splice` input in place, mutate node payloads, or use retained references to modify later results. Unchanged input nodes remain shared; entirely unchanged results retain the array reference instead of using full deep copies for isolation.
The runner retains its previous output internally to align recomputed results. When new business nodes are equivalent to old nodes in ID, original-text range, and JSON data, the old objects can be reused; when all result elements are identical, the old array is reused. Comparison occurs only in stages that need recomputation, with a reference-equality fast path first, rather than serializing the whole pipeline on every refresh.
@@ -81,9 +81,9 @@ Each node has `{ id, start, end, data }`. `id` is the business type and the node
Nodes and Facts contain no functions, ReactNode, service handles, DOM, observables, Date, or Map. `UserTextDataMap` and `UserTextFacts` are extensible declarations on the public `/client` entry point, and internal types reference those same declarations; business declaration merging must survive in published type files. Type constraints and unit tests ensure JSON compatibility, without repeatedly serializing and validating entire trees of trusted same-process input.
Callers supply business Facts; the runner does not query global state for them. Skills use confirmed names, session references use associated labels, commands use actual execution ranges, and attachments use explicit ranges and resource references. Ordinary file paths can be recognized from text alone; an attachment display name is not a file path and must not be used to guess an attachmentId.
Callers supply business Facts; the runner does not query global state for them. Skills use confirmed names, session references use associated labels, commands use actual execution ranges. Ordinary file paths can be recognized from text alone; an attachment display name is not a file path and must not be used to guess an attachmentId.
`stripEmoji`, `collapseWhitespace`, and `trimWhitespace` each control one text-display transform and are disabled by default. Each rule reads only its own switch and uses the preceding stage's display result. Emoji handling uses complete graphemes; whitespace collapsing continues across consecutive Text segments but not business nodes; trimming affects only the document's two ends without removing normal spaces between references. Built-in rules use ordinary `order` values to place these transforms after existing reference recognition, preserving characters and identity within references; there is no additional category priority.
`collapseWhitespace` and `trimWhitespace` each control one text-display transform and are disabled by default. Each rule reads only its own switch and uses the preceding stage's display result. Whitespace collapsing continues across consecutive Text segments but not business nodes; trimming affects only the document's two ends without removing normal spaces between references. Built-in rules use ordinary `order` values to place these transforms after existing reference recognition, preserving characters and identity within references; there is no additional category priority.
`interactive` and CSS `ellipsis` are React Props, not Facts. Ellipsis neither removes original text nor limits the number of input characters. The queue enables whitespace collapsing and trimming through Facts and ellipsis through display Props; message bodies and Goal retain full display. Callers retain no `previewOf`, 200-character pre-truncation, or concatenated unknown-block placeholders; nontext attachments continue through the existing attachment display.
@@ -91,11 +91,11 @@ Reference summaries obtain display data from `UserContentData.referenceLabels`,
### Rendering and interaction ownership
`conversation.user.text` is a session-scoped Factory that independently owns the session/keyed `conversation.user.text.node`. UserText traverses final nodes in order and selects each renderer by node ID, without centralized skill, file, or attachment rendering branches. Default entries use `priority: 100`; external businesses override the corresponding keys through the existing Slot mechanism.
`conversation.user.text` is a session-scoped Factory that independently owns the session/keyed `conversation.user.text.node`. UserText traverses final nodes in order and selects each renderer by node ID, without centralized skill or file rendering branches. Default entries use `priority: 100`; external businesses override the corresponding keys through the existing Slot mechanism.
`ui-conversation` provides `text` and session labels; `ui-skill` provides skills; `ui-reference` provides ordinary file and directory references; `ui-attachment` provides explicit attachment references; `ui-goal` provides Goal command markers. Each business's own Slot registration declares its action dependencies. Parsed data carries no callbacks, and parent layouts do not forward node-specific actions.
`ui-conversation` provides `text` and session labels; `ui-skill` provides skills; `ui-reference` provides ordinary file and directory references; `ui-goal` provides Goal command markers. Each business's own Slot registration declares its action dependencies. Parsed data carries no callbacks, and parent layouts do not forward node-specific actions.
The display layer passes the `interactive` Prop and original-text fragment `raw` to node renderers; these are ordinary data, not execution capabilities. Reference actions may appear only when `interactive` is true. Queues, submission echoes, and pending incoming input remain nonclickable; sessions, directories, and commands remain labels by default. File attachments retain their name and size presentation, and image reads occur in the display layer upon user action through the existing Session authorization cache.
The display layer passes the `interactive` Prop and original-text fragment `raw` to node renderers; these are ordinary data, not execution capabilities. Reference actions may appear only when `interactive` is true. Queues, submission echoes, and pending incoming input remain nonclickable; sessions, directories, and commands remain labels by default. Native attachments remain outside the text pipeline: file cards retain their name and size, and image galleries use the existing Session-authorized loader.
The file-reference business handles file-navigation failures rather than returning them to the Chat action aggregator. A local Modal provides retry and close actions; synchronous navigation adds neither request sequence numbers nor fictitious aborts. Document previews still handle file-read errors, and Sidebar retains its existing public location semantics. Existing Assistant Markdown feedback and component responsibilities remain separate.
@@ -118,8 +118,8 @@ UserContent retains attachments, the body container, unknown content, and refere
- Changes to unread Facts fields do not execute a stage; reading an absent field allows its later appearance to trigger recomputation; conditional read dependencies can be added or removed.
- When a stage's Facts change but its output remains equivalent, old node and array references are reused and unrelated downstream stages do not execute; later stages that directly depend on other changed fields still execute.
- Original-text changes run the entire pipeline; incremental results match a newly created evaluation instance with the same input.
- Frozen-input tests detect in-place array or payload mutation; node output is ordered, fully covers the original text without overlaps, and survives a JSON round-trip.
- Only `order/id` determines sequence; transform unit tests cover ordinary registration order for built-in display transforms, independent switches, whitespace across adjacent segments, document-edge trimming, emoji graphemes, and reference atomicity.
- Readonly type assertions cover arrays and payloads; node output is ordered, fully covers the original text without overlaps, and survives a JSON round-trip.
- Only `order/id` determines sequence; transform unit tests cover ordinary registration order for built-in display transforms, independent switches, whitespace across adjacent segments, document-edge trimming, emoji preservation, and reference atomicity.
- Text processing executes no UI actions; Slot-injected actions do not make previews clickable; registration and unloading leak no evaluation state or subscriptions.
## Alternatives considered
@@ -67,7 +67,7 @@ Facts 更新时,只将实际读取了变化字段的阶段标记为失效。
### 引用复用与确定性
输入数组、节点和 Facts 均只读。禁止原地 `splice` 输入、修改节点 payload 或通过保留引用写入后续结果。不变的输入节点继续复用;结果完全不变时保留数组引用,不以全量深拷贝作为隔离方法。
输入数组、节点和 Facts 使用 TypeScript readonly 类型;运行器借用这些值,不冻结或复制它们。禁止原地 `splice` 输入、修改节点 payload 或通过保留引用写入后续结果。不变的输入节点继续复用;结果完全不变时保留数组引用,不以全量深拷贝作为隔离方法。
运行器内部保存上一轮输出,用于对齐重算结果。业务产生的新节点与旧节点在 ID、原文范围及 JSON 数据上等价时,可以复用旧对象;全部结果元素相同时复用旧数组。比较只发生在需要重算的阶段,先使用引用相等的快速路径,不在每次刷新时序列化整条流水线。
@@ -81,9 +81,9 @@ Facts 更新时,只将实际读取了变化字段的阶段标记为失效。
节点和 Facts 不包含函数、ReactNode、服务句柄、DOM、observable、Date 或 Map。`UserTextDataMap` 与 `UserTextFacts` 是公开 `/client` 入口上的可扩展声明实体,内部类型引用同一实体;业务声明合并必须保留在发布的类型文件中。JSON 兼容性由类型约束与单测保证,可信同进程输入不逐次做整树序列化校验。
业务 Facts 由调用者提供,不是运行器自行查询的全局状态:skill 使用已确认的名字,会话引用使用关联标签,命令使用真实执行范围,附件使用明确范围和资源引用。普通文件路径可以只依据文本识别;附件显示名不等于文件路径,不据此猜 attachmentId。
业务 Facts 由调用者提供,不是运行器自行查询的全局状态:skill 使用已确认的名字,会话引用使用关联标签,命令使用真实执行范围。普通文件路径可以只依据文本识别;附件显示名不等于文件路径,不据此猜 attachmentId。
`stripEmoji`、`collapseWhitespace`、`trimWhitespace` 分别控制三个文本显示变换,缺省均不启用。每条规则只读取自己的开关并使用前一层的显示结果;emoji 按完整字素处理,空白折叠跨连续 Text 分段延续但不跨业务节点,trim 只处理整份文档两端而不删除引用之间的正常空格。内置规则用普通 `order` 值将这些加工安排在既有引用识别之后,保留引用内部字符和身份;不存在额外的类别优先级。
`collapseWhitespace` 与 `trimWhitespace` 分别控制两个文本显示变换,缺省均不启用。每条规则只读取自己的开关并使用前一层的显示结果;空白折叠跨连续 Text 分段延续但不跨业务节点,trim 只处理整份文档两端而不删除引用之间的正常空格。内置规则用普通 `order` 值将这些加工安排在既有引用识别之后,保留引用内部字符和身份;不存在额外的类别优先级。
`interactive` 和 CSS `ellipsis` 由 React Props 传递,不属于 Facts。省略不删除原文或限制传入字符数。队列用 Facts 启用空白折叠与 trim,用显示 Props 启用省略;消息正文与 Goal 保持完整展示。调用者不再保留 `previewOf`、200 字符预截断或未知块占位拼接,非文本附件继续走既有附件展示。
@@ -91,11 +91,11 @@ Facts 更新时,只将实际读取了变化字段的阶段标记为失效。
### 渲染与交互所有权
`conversation.user.text` 是 session 作用域 Factory,独立拥有 session/keyed 的 `conversation.user.text.node`。UserText 顺序遍历最终节点,以节点 ID 选择 renderer,不包含 skill、file 或 attachment 的集中渲染分支。默认条目使用 `priority: 100`,外部业务按既有 Slot 机制覆盖对应 key。
`conversation.user.text` 是 session 作用域 Factory,独立拥有 session/keyed 的 `conversation.user.text.node`。UserText 顺序遍历最终节点,以节点 ID 选择 renderer,不包含 skill 或 file 的集中渲染分支。默认条目使用 `priority: 100`,外部业务按既有 Slot 机制覆盖对应 key。
`text` 和会话标签由 `ui-conversation` 提供,skill 由 `ui-skill` 提供,普通文件及目录引用由 `ui-reference` 提供,明确附件引用由 `ui-attachment` 提供,Goal 命令标记由 `ui-goal` 提供。业务自己的 Slot 注册声明操作依赖;解析数据不携带回调,上层布局不转交这些节点专用动作。
`text` 和会话标签由 `ui-conversation` 提供,skill 由 `ui-skill` 提供,普通文件及目录引用由 `ui-reference` 提供,Goal 命令标记由 `ui-goal` 提供。业务自己的 Slot 注册声明操作依赖;解析数据不携带回调,上层布局不转交这些节点专用动作。
显示侧将 `interactive` Prop 连同原文片段 `raw` 传给节点 renderer;这些都是普通数据,不是执行能力。只有 `interactive` 为 true 时允许显示引用操作。队列、提交回显及待接收输入保持不可点击;会话、目录和命令默认仍为标签。文件附件保持名称和大小呈现,图片读取在显示层按用户操作发生,继续使用既有 Session 授权缓存。
显示侧将 `interactive` Prop 连同原文片段 `raw` 传给节点 renderer;这些都是普通数据,不是执行能力。只有 `interactive` 为 true 时允许显示引用操作。队列、提交回显及待接收输入保持不可点击;会话、目录和命令默认仍为标签。原生附件不进入文本流水线:文件卡片保留名称和大小,图片画廊使用既有 Session 授权 loader。
文件导航失败由文件引用业务处理,不回到 Chat 动作聚合层。局部 Modal 提供重试和关闭;同步导航不增加请求序号或虚构 abort。文件读取错误仍由文档预览处理,Sidebar 继续使用现有公共定位语义。Assistant Markdown 的既有反馈与组件分工独立保留。
@@ -118,8 +118,8 @@ UserContent 保留附件、正文容器、未知内容和引用摘要,消息
- 未读取的 Facts 字段变化不会执行该阶段;读取缺失字段后,该字段出现能够触发重算;条件读取关系可以增加或撤销。
- 某阶段读到的 Facts 变化但输出等价时,旧节点和数组引用得到复用,无关下游不执行;直接依赖其他变化字段的后续阶段仍然执行。
- 原文变更完整执行流水线;增量结果与相同输入下的新建求值实例结果一致。
- 冻结输入的测试能发现数组或 payload 原地修改;节点输出有序、完整覆盖原文、无重叠并可作 JSON round-trip。
- 顺序仅由 `order/id` 决定;内置显示变换的普通注册顺序、独立开关、相邻分段空白、文档边缘 trim、emoji 字素和引用原子性均由变换单测覆盖。
- 只读类型断言覆盖数组和 payload;节点输出有序、完整覆盖原文、无重叠并可作 JSON round-trip。
- 顺序仅由 `order/id` 决定;内置显示变换的普通注册顺序、独立开关、相邻分段空白、文档边缘 trim、emoji 保留和引用原子性均由变换单测覆盖。
- 文本处理不执行 UI 操作;preview 不因 Slot 注入了操作能力而变成可点击;注册与卸载不泄漏求值状态或订阅。
## 备选方案
@@ -1,5 +0,0 @@
.loading {
display: flex;
justify-content: center;
padding-block: 24px;
}
@@ -1,84 +0,0 @@
/** Inline attachment labels; image reads start only after activation and reuse the Session-owned cache. */
import { useCallback, useEffect, useState } from 'react'
import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
import type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
import { Button, ImageLightbox, Modal, ReferenceChip, StateDot, fileSizeText } from '@deepseek-ai/dsh-client-ui-primitives'
import type { ImageLoader } from '../MessageImage.tsx'
import type { NS } from './locales.ts'
import type {} from './user-text-rules.ts'
import css from './AttachmentReference.module.css'
/** Image loading is authorized by this reference's Session, independently of its text host. */
export interface AttachmentReferenceInjected {
readonly loadImage: ImageLoader
}
type AttachmentReferenceProps = UserTextNodeProps<'attachment'>
& InjectFace<AttachmentReferenceInjected> & PropsLocale<typeof NS>
/**
* Keep file attachments read-only and open image previews only after an interactive activation.
* @param props - explicit attachment node, interaction policy, authorized loader, and locale seat.
* @returns an inline reference; image loading and preview dialogs render through body portals.
*/
export function AttachmentReference({ node, raw, interactive, loadImage, t }: AttachmentReferenceProps) {
const { attachment } = node.data
const [previewId, setPreviewId] = useState<ImageAttachmentRef['attachmentId'] | null>(null)
const close = useCallback(() => { setPreviewId(null) }, [])
if (attachment.type === 'file') {
return <ReferenceChip appearance="file" title={raw} label={t('file.label', {
name: attachment.ref.name, size: fileSizeText(attachment.ref.bytes),
})} />
}
const label = attachment.ref.name ?? t('image.label')
return <>
<ReferenceChip appearance="file" label={label} title={raw}
{...interactive ? { onActivate: () => { setPreviewId(attachment.ref.attachmentId) } } : {}} />
{interactive && previewId === attachment.ref.attachmentId && <ImageReferencePreview
key={attachment.ref.attachmentId}
attachment={attachment.ref} label={label} loadImage={loadImage} t={t} onClose={close}
/>}
</>
}
type ImagePreviewState = { readonly status: 'loading' | 'failed' } | { readonly status: 'open'; readonly url: string }
type ImageReferencePreviewProps = Pick<AttachmentReferenceProps, 'loadImage' | 't'> & {
readonly attachment: ImageAttachmentRef
readonly label: string
readonly onClose: () => void
}
/** Mounted only by a user gesture; closing ignores pending settlement without aborting the shared read. */
function ImageReferencePreview({ attachment, label, loadImage, t, onClose }: ImageReferencePreviewProps) {
const [preview, setPreview] = useState<ImagePreviewState>({ status: 'loading' })
const [attempt, setAttempt] = useState(0)
useEffect(() => {
let live = true
const cached = loadImage.peek?.(attachment)
setPreview(cached === undefined ? { status: 'loading' } : { status: 'open', url: cached })
void loadImage(attachment).then(
(url) => { if (live) setPreview({ status: 'open', url }) },
() => { if (live) setPreview({ status: 'failed' }) },
)
return () => { live = false }
}, [attachment, loadImage, attempt])
if (preview.status === 'open') {
return <ImageLightbox src={preview.url} alt={label} onClose={onClose}
labels={{ dialog: t('image.preview'), close: t('image.closePreview') }} />
}
return <Modal open onClose={onClose} title={t('image.preview')} closeLabel={t('close')}
footer={<>
<Button variant="outline" onClick={onClose}>{t('close')}</Button>
{preview.status === 'failed' && <Button variant="primary" onClick={() => { setAttempt(value => value + 1) }}>
{t('retry')}
</Button>}
</>}
>
{preview.status === 'failed'
? <p role="alert">{t('image.failed', { name: label })}</p>
: <span className={css.loading} role="status" aria-label={t('image.loading')}><StateDot state="ongoing" /></span>}
</Modal>
}
@@ -1,38 +1,21 @@
/** Browser attachment plugin: composer, image galleries, and explicit inline attachment references. */
/** Browser attachment plugin: composer entries and independently replaceable image galleries. */
import type { Context as ClientContext } from '@deepseek-ai/cordis'
import type {} from '@deepseek-ai/dsh-client-ui-chat/client'
import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
import type {} from '@deepseek-ai/dsh-client-locale/client'
import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
import type {} from '@deepseek-ai/dsh-client-ui-tool/client'
import type {} from '@deepseek-ai/dsh-client-ui-trajectory/client'
import { ComposerAttachments } from './ComposerAttachments.tsx'
import { AttachmentReference, type AttachmentReferenceInjected } from './AttachmentReference.tsx'
import { attachmentReferenceRule } from './user-text-rules.ts'
export type {} from './user-text-rules.ts'
import { en, NS, zh } from './locales.ts'
import { MessageImages, MessageImagesContent } from './MessageImages.tsx'
/** Slot assembly, pure text rules, Session image loading, and attachment-owned copy. */
export const inject = ['slots', 'uiConversation', 'locale']
/** Slot registry required by the attachment presentation plugin. */
export const inject = ['slots']
/**
* Register attachment presentation and the explicit-range user-text provider.
* @param ctx - client plugin context with Session-authorized image loading.
* Register composer attachments and the shared gallery with its domain adapters.
* @param ctx - client plugin context with the Slot registry.
*/
export function apply(ctx: ClientContext): void {
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-attachment: dictionaries')
ctx.effect(() => ctx.uiConversation.userText.register(attachmentReferenceRule), 'ui-attachment: text rule')
ctx.slots.inject('conversation.user.text.node', () => ctx.slots.register({
name: 'conversation.user.text.node', key: 'attachment', priority: 100, locale: NS,
inject: (sessionId: UserTextNodeProps<'attachment'>['sessionId']): AttachmentReferenceInjected => ({
loadImage: Object.assign(
(attachment: ImageAttachmentRef) => ctx.uiConversation.imageUrl(sessionId, attachment),
{ peek: (attachment: ImageAttachmentRef) => ctx.uiConversation.peekImageUrl(sessionId, attachment) },
),
}),
}, AttachmentReference))
ctx.slots.registerFactory({
name: 'conversation.images.content', scope: 'root', locale: 'conversation',
}, MessageImagesContent)
@@ -41,20 +24,15 @@ export function apply(ctx: ClientContext): void {
locale: 'conversation',
}, ComposerAttachments))
ctx.slots.inject('conversation.chat.message.images', () => ctx.slots.register({
name: 'conversation.chat.message.images',
priority: 100,
name: 'conversation.chat.message.images', priority: 100,
}, MessageImages))
ctx.slots.inject('conversation.chat.user.images', () => ctx.slots.register({
name: 'conversation.chat.user.images',
priority: 100,
name: 'conversation.chat.user.images', priority: 100,
}, MessageImages))
ctx.slots.inject('conversation.trajectory.images', () => ctx.slots.register({
name: 'conversation.trajectory.images',
priority: 100,
name: 'conversation.trajectory.images', priority: 100,
}, MessageImages))
// Tool image entries reuse the same gallery Factory.
ctx.slots.inject('tool.call.images', () => ctx.slots.register({
name: 'tool.call.images',
priority: 100,
name: 'tool.call.images', priority: 100,
}, MessageImages))
}
@@ -1,38 +0,0 @@
/** Localized copy for explicit inline attachment references and their image preview. */
import type {} from '@deepseek-ai/dsh-client-ui-slots'
/** Namespace owned by attachment reference renderers. */
export const NS = 'attachment'
/** Simplified Chinese attachment-reference copy. */
export const zh = {
'file.label': '{name} · {size}',
'image.label': '图片',
'image.loading': '正在加载图片',
'image.failed': '无法加载“{name}”,请重试或关闭此提示',
'image.preview': '图片预览',
'image.closePreview': '关闭图片预览',
'close': '关闭',
'retry': '重试',
} satisfies Record<string, string>
/** Keys required by both attachment dictionaries. */
export type AttachmentKey = keyof typeof zh
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface LocaleNamespaceMap {
attachment: AttachmentKey
}
}
/** English attachment-reference copy. */
export const en = {
'file.label': '{name} · {size}',
'image.label': 'Image',
'image.loading': 'Loading image',
'image.failed': 'Couldn’t load “{name}”. Try again or close this message.',
'image.preview': 'Image preview',
'image.closePreview': 'Close image preview',
'close': 'Close',
'retry': 'Retry',
} satisfies Record<AttachmentKey, string>
@@ -1,84 +0,0 @@
/** Pure attachment references use only caller-confirmed ranges and durable identities. */
import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
import type { UserTextNode, UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client'
/** A durable attachment identity, never a path inferred from its display name. */
export type UserTextAttachment =
| { readonly type: 'image'; readonly ref: ImageAttachmentRef }
| { readonly type: 'file'; readonly ref: FileAttachmentRef }
declare module '@deepseek-ai/dsh-client-ui-conversation/client' {
interface UserTextDataMap {
attachment: { readonly attachment: UserTextAttachment }
}
interface UserTextFacts {
readonly attachments: readonly {
readonly start: number
readonly end: number
readonly attachment: UserTextAttachment
}[]
}
}
function appendText(nodes: UserTextNode[], segment: UserTextNode<'text'>, start: number, end: number): void {
if (start < end) {
nodes.push({
id: 'text', start, end,
data: { text: segment.data.text.slice(start - segment.start, end - segment.start) },
})
}
}
/**
* Read explicit attachment facts only when Text remains; never infer references from names.
* Invalid or overlapping fact ranges throw; valid ranges outside a single Text segment stay unclaimed.
*/
export const attachmentReferenceRule: UserTextRule<'attachment'> = {
id: 'attachment',
order: 15,
transform(segments, context) {
const lastSegment = segments.at(-1)
if (!lastSegment || !segments.some(segment => segment.id === 'text')) return segments
const attachments = context.read('attachments')
if (!attachments?.length) return segments
const end = lastSegment.end
for (const range of attachments) {
if (!Number.isInteger(range.start) || !Number.isInteger(range.end)
|| range.start < 0 || range.end <= range.start || range.end > end) {
throw new RangeError(`invalid attachment range [${range.start}, ${range.end}); expected a nonempty UTF-16 range within [0, ${end})`)
}
}
const ranges = [...attachments].sort((left, right) => left.start - right.start)
let previousEnd = 0
for (const range of ranges) {
if (range.start < previousEnd) {
throw new RangeError(`overlapping attachment range [${range.start}, ${range.end})`)
}
previousEnd = range.end
}
const nodes: UserTextNode[] = []
let changed = false
let rangeIndex = 0
for (const segment of segments) {
if (segment.id !== 'text') {
nodes.push(segment)
continue
}
let cursor = segment.start
for (let range = ranges[rangeIndex]; range && range.start < segment.end; range = ranges[++rangeIndex]) {
if (range.start < segment.start || range.end > segment.end) continue
appendText(nodes, segment, cursor, range.start)
nodes.push({ id: 'attachment', start: range.start, end: range.end, data: { attachment: range.attachment } })
cursor = range.end
}
if (cursor === segment.start) {
nodes.push(segment)
} else {
changed = true
appendText(nodes, segment, cursor, segment.end)
}
}
return changed ? nodes : segments
},
}
@@ -1,95 +0,0 @@
// @vitest-environment jsdom
import { act, cleanup, fireEvent, render } from '@testing-library/react'
import type { ComponentProps } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { AttachmentId, type ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { AttachmentReference } from '../src/client/AttachmentReference.tsx'
import { en } from '../src/client/locales.ts'
afterEach(cleanup)
const image: ImageAttachmentRef = {
attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`),
mediaType: 'image/png', bytes: 68, width: 1, height: 1, name: 'photo.png',
}
type Props = ComponentProps<typeof AttachmentReference>
function props(loadImage: Props['loadImage'], attachment: ImageAttachmentRef = image): Props {
return {
node: { id: 'attachment', start: 0, end: 6, data: { attachment: { type: 'image', ref: attachment } } },
raw: '@photo', interactive: true, loadImage, t: makeTranslate(en),
} as Props
}
describe('AttachmentReference', () => {
it('keeps files and non-interactive images read-only without starting image reads', () => {
const loadImage = vi.fn(() => Promise.resolve('blob:unused'))
const input = props(loadImage)
const view = render(<AttachmentReference {...input} interactive={false} />)
expect(view.getByText('photo.png').getAttribute('title')).toBe('@photo')
expect(view.queryByRole('button')).toBeNull()
view.rerender(<AttachmentReference {...input} node={{
id: 'attachment', start: 0, end: 6,
data: { attachment: { type: 'file', ref: {
attachmentId: image.attachmentId, name: 'notes.txt', bytes: 42,
} } },
}} />)
expect(view.getByText('notes.txt · 42B')).toBeTruthy()
expect(view.queryByRole('button')).toBeNull()
expect(loadImage).not.toHaveBeenCalled()
})
it('loads only after activation and closes the resolved preview', async () => {
const pending = Promise.withResolvers<string>()
const loadImage = vi.fn(() => pending.promise)
const view = render(<AttachmentReference {...props(loadImage)} />)
expect(loadImage).not.toHaveBeenCalled()
fireEvent.click(view.getByRole('button', { name: 'photo.png' }))
expect(view.getByRole('status', { name: 'Loading image' })).toBeTruthy()
expect(loadImage).toHaveBeenCalledWith(image)
await act(async () => { pending.resolve('blob:photo') })
expect(view.getByAltText('photo.png').getAttribute('src')).toBe('blob:photo')
fireEvent.click(view.getByRole('button', { name: 'Close image preview' }))
expect(view.queryByRole('dialog')).toBeNull()
})
it('shows a cached unnamed image while its authorized read settles', async () => {
const { name: _name, ...unnamed } = image
const pending = Promise.withResolvers<string>()
const loadImage = Object.assign(vi.fn(() => pending.promise), { peek: vi.fn(() => 'blob:cached') })
const view = render(<AttachmentReference {...props(loadImage, unnamed)} />)
fireEvent.click(view.getByRole('button', { name: 'Image' }))
expect(view.getByAltText('Image').getAttribute('src')).toBe('blob:cached')
expect(loadImage.peek).toHaveBeenCalledWith(unnamed)
await act(async () => { pending.resolve('blob:fresh') })
expect(view.getByAltText('Image').getAttribute('src')).toBe('blob:fresh')
})
it('contains failed image reads and retries through the same authorized loader', async () => {
const loadImage = Object.assign(vi.fn()
.mockRejectedValueOnce(new Error('offline'))
.mockResolvedValueOnce('blob:retry'), { peek: () => undefined })
const view = render(<AttachmentReference {...props(loadImage)} />)
fireEvent.click(view.getByRole('button', { name: 'photo.png' }))
expect((await view.findByRole('alert')).textContent).toBe('Couldn’t load “photo.png”. Try again or close this message.')
fireEvent.click(view.getByRole('button', { name: 'Retry' }))
expect((await view.findByAltText('photo.png')).getAttribute('src')).toBe('blob:retry')
expect(loadImage).toHaveBeenCalledTimes(2)
})
it.each(['resolve', 'reject'] as const)('ignores a closed read that later %ss without reopening its dialog', async (outcome) => {
const pending = Promise.withResolvers<string>()
const view = render(<AttachmentReference {...props(() => pending.promise)} />)
fireEvent.click(view.getByRole('button', { name: 'photo.png' }))
fireEvent.click(view.getAllByRole('button', { name: 'Close' }).at(-1)!)
expect(view.queryByRole('dialog')).toBeNull()
await act(async () => {
if (outcome === 'resolve') pending.resolve('blob:late')
else pending.reject(new Error('late failure'))
})
expect(view.queryByRole('dialog')).toBeNull()
expect(view.getByRole('button', { name: 'photo.png' })).toBeTruthy()
})
})
@@ -1,5 +1,7 @@
// @vitest-environment jsdom
import { useState } from 'react'
import type { PropsRenderFactories, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react'
import { AttachmentId } from '@deepseek-ai/dsh-attachment'
@@ -266,6 +268,44 @@ describe('ImageGallery', () => {
expect(several.container.querySelectorAll('[data-variant="tile"]')).toHaveLength(3)
})
it('uses complete Factory labels unchanged and restores defaults without remounting the image', async () => {
const runtime = await SlotTestRuntime.create()
onTestFinished(() => runtime.dispose())
const locale = new LocaleRuntime(runtime.ctx)
locale.register('conversation', { en, zh })
locale.setLocale('en')
runtime.ctx.provide('locale', locale)
runtime.slots.installLocale(locale)
await runtime.mount(attachmentPlugin)
const images = [{ preview: { url: 'blob:labels', name: 'preview.png' } }]
const loadImage = vi.fn(async () => 'blob:unused')
await runtime.root.declare({}, ({ renderFactorySlot }: PropsRuntime<'root'> & PropsRenderFactories) => {
const [custom, setCustom] = useState(true)
return <>
<button onClick={() => { setCustom(false) }}>Default labels</button>
{renderFactorySlot('conversation.images.content', {
images, loadImage, align: 'start', ...(custom ? { labels } : {}),
})}
</>
})
const view = runtime.renderRoot()
const image = view.getByAltText('preview.png')
const frame = view.getByRole('button', { name: 'preview.png,点击查看原图' })
expect(frame.getAttribute('title')).toBe(labels.open)
fireEvent.click(frame)
expect(view.getByRole('dialog', { name: labels.lightbox.dialog })).toBeTruthy()
fireEvent.click(view.getByRole('button', { name: labels.lightbox.close }))
fireEvent.click(view.getByRole('button', { name: 'Default labels' }))
const defaultFrame = view.getByRole('button', { name: 'preview.png, click to view original' })
expect(defaultFrame).toBe(frame)
expect(view.getByAltText('preview.png')).toBe(image)
expect(defaultFrame.getAttribute('title')).toBe('View original')
fireEvent.click(defaultFrame)
expect(view.getByRole('dialog', { name: 'Original image preview' })).toBeTruthy()
fireEvent.click(view.getByRole('button', { name: 'Close original image preview' }))
expect(loadImage).not.toHaveBeenCalled()
})
it('renders the conversation slot entry with translated labels', async () => {
const runtime = await SlotTestRuntime.create()
onTestFinished(() => runtime.dispose())
@@ -3,15 +3,16 @@ import { describe, expect, it, onTestFinished, vi } from 'vitest'
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
import { TestSessions } from '@deepseek-ai/dsh-client-test-runtime'
import { UiConversation } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/assembly.ts'
import { AttachmentId } from '@deepseek-ai/dsh-attachment'
import { SessionId } from '@deepseek-ai/dsh-session/types'
import { AttachmentReference, type AttachmentReferenceInjected } from '../src/client/AttachmentReference.tsx'
import { apply as applyHost } from '../src/index.ts'
import { apply, inject } from '../src/client/index.ts'
import { ComposerAttachments } from '../src/client/ComposerAttachments.tsx'
import { MessageImages, MessageImagesContent } from '../src/client/MessageImages.tsx'
const IMAGE_SLOTS = [
'conversation.chat.message.images', 'conversation.chat.user.images',
'conversation.trajectory.images', 'tool.call.images',
] as const
async function bench() {
const ctx = new Context()
const sessions = new TestSessions(async (action) => { await action() }, ctx)
@@ -21,12 +22,10 @@ async function bench() {
})
ctx.provide('sessions', sessions)
ctx.provide('locale', new LocaleRuntime(ctx))
new UiConversation(ctx, sessions)
await ctx.plugin(SlotRegistry).await()
ctx.slots.register({
name: 'root',
children: {
'conversation.user.text.node': { kind: 'keyed', scope: 'session' },
'conversation.input.attachments': { kind: 'single', scope: 'session-maybe' },
'conversation.chat.message.images': { kind: 'single', scope: 'session' },
'conversation.chat.user.images': { kind: 'single', scope: 'session' },
@@ -45,58 +44,22 @@ describe('attachment plugin', () => {
expect(() => { applyHost() }).not.toThrow()
})
it('binds image reads and cache peeks to the reference Session', async () => {
const { ctx } = await bench()
const attachment = { attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), mediaType: 'image/png' as const, bytes: 68, width: 1, height: 1 }
const imageUrl = vi.spyOn(ctx.uiConversation, 'imageUrl').mockResolvedValue('blob:loaded')
const peekImageUrl = vi.spyOn(ctx.uiConversation, 'peekImageUrl').mockReturnValue('blob:cached')
const entry = ctx.slots.entries('conversation.user.text.node')[0]!
const factory = entry.inject as NonNullable<typeof entry.inject> & ((id: SessionId) => AttachmentReferenceInjected)
const first = factory(SessionId('first'))
const second = factory(SessionId('second'))
expect(first.loadImage.peek?.(attachment)).toBe('blob:cached')
await expect(first.loadImage(attachment)).resolves.toBe('blob:loaded')
await expect(second.loadImage(attachment)).resolves.toBe('blob:loaded')
expect(peekImageUrl).toHaveBeenCalledWith('first', attachment)
expect(imageUrl.mock.calls).toEqual([['first', attachment], ['second', attachment]])
})
it('registers all entries and removes them with the plugin fiber', async () => {
const { ctx, fiber, registerFactory } = await bench()
expect(inject).toEqual(['slots', 'uiConversation', 'locale'])
expect(ctx.slots.entries('conversation.user.text.node')).toMatchObject([{
options: { key: 'attachment' }, component: AttachmentReference,
}])
expect(ctx.slots.entries('conversation.user.text.node')[0]?.inject).toBeTypeOf('function')
expect(ctx.uiConversation.userText.entries().map(rule => rule.id)).toEqual(['attachment'])
expect(inject).toEqual(['slots'])
expect(registerFactory).toHaveBeenCalledWith({
name: 'conversation.images.content', scope: 'root', locale: 'conversation',
}, MessageImagesContent)
expect(ctx.slots.snapshot('factory:conversation.images.content')).toHaveLength(1)
expect(ctx.slots.entries('conversation.input.attachments')).toMatchObject([{
locale: 'conversation',
component: ComposerAttachments,
locale: 'conversation', component: ComposerAttachments,
}])
expect(ctx.slots.entries('conversation.chat.message.images')).toMatchObject([{
component: MessageImages,
}])
expect(ctx.slots.entries('conversation.chat.user.images')).toMatchObject([{ component: MessageImages, options: { priority: 100 } }])
expect(ctx.slots.entries('conversation.trajectory.images')).toMatchObject([{
component: MessageImages,
}])
expect(ctx.slots.entries('tool.call.images')).toMatchObject([{
component: MessageImages,
}])
for (const name of IMAGE_SLOTS) {
expect(ctx.slots.entries(name)).toMatchObject([{ component: MessageImages, options: { priority: 100 } }])
}
await fiber.dispose()
expect(ctx.slots.entries('conversation.user.text.node')).toHaveLength(0)
expect(ctx.uiConversation.userText.entries()).toHaveLength(0)
expect(ctx.slots.entries('conversation.input.attachments')).toHaveLength(0)
expect(ctx.slots.entries('conversation.chat.message.images')).toHaveLength(0)
expect(ctx.slots.entries('conversation.chat.user.images')).toHaveLength(0)
expect(ctx.slots.entries('conversation.trajectory.images')).toHaveLength(0)
expect(ctx.slots.entries('tool.call.images')).toHaveLength(0)
for (const name of IMAGE_SLOTS) expect(ctx.slots.entries(name)).toHaveLength(0)
expect(ctx.slots.snapshot('factory:conversation.images.content')).toHaveLength(0)
})
})
@@ -1,121 +0,0 @@
import { Context } from '@deepseek-ai/cordis'
import { UserTextRegistry } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/user-text-registry.ts'
import { AttachmentId } from '@deepseek-ai/dsh-attachment'
import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
import { describe, expect, it, onTestFinished, vi } from 'vitest'
import type { UserTextNode, UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client'
import { attachmentReferenceRule } from '../src/client/user-text-rules.ts'
declare module '@deepseek-ai/dsh-client-ui-conversation/client' {
interface UserTextDataMap {
'test.attachment.blocker': { readonly label: string }
}
}
function setup(rules: readonly UserTextRule[] = [attachmentReferenceRule]) {
const ctx = new Context()
onTestFinished(async () => { await ctx.fiber.dispose() })
const registry = new UserTextRegistry(ctx)
for (const rule of rules) registry.register(rule)
return registry.createEvaluator()
}
describe('attachmentReferenceRule', () => {
it('does not read attachment facts when an earlier rule leaves no Text', () => {
const read = vi.fn()
const transform = vi.fn<UserTextRule['transform']>((segments, context) => attachmentReferenceRule.transform(segments, {
read: (key) => { read(key); return context.read(key) },
}))
const blocker: UserTextNode<'test.attachment.blocker'> = {
id: 'test.attachment.blocker', start: 0, end: 5, data: { label: 'claimed' },
}
const evaluate = setup([
{ id: 'test.attachment.blocker', order: 0, transform: () => [blocker] },
{ ...attachmentReferenceRule, transform },
])
const before = evaluate({ text: 'image', facts: {} })
expect(before).toEqual([blocker])
expect(evaluate({ text: 'image', facts: { attachments: [] } })).toBe(before)
expect(read).not.toHaveBeenCalled()
expect(transform).toHaveBeenCalledOnce()
})
it('rejects invalid and overlapping fact ranges with its rule ID and cause', () => {
const evaluate = setup()
const attachment = { type: 'file' as const, ref: { attachmentId: AttachmentId('file'), name: 'a', bytes: 1 } }
for (const ranges of [
[{ start: -1, end: 1 }], [{ start: 0, end: 0 }], [{ start: 0, end: 5 }],
[{ start: 0.5, end: 1 }], [{ start: 0, end: Infinity }],
[{ start: 0, end: 3 }, { start: 2, end: 4 }],
]) {
let failure: unknown
try {
evaluate({ text: 'abcd', facts: { attachments: ranges.map(range => ({ ...range, attachment })) } })
} catch (error) { failure = error }
expect(failure).toHaveProperty('ruleId', 'attachment')
expect(failure).toHaveProperty('cause', expect.any(RangeError))
}
})
it('preserves earlier business nodes and claims only fact ranges inside remaining Text', () => {
const blocker: UserTextNode<'test.attachment.blocker'> = {
id: 'test.attachment.blocker', start: 1, end: 4, data: { label: 'claimed' },
}
const evaluate = setup([
{
id: 'test.attachment.blocker', order: 0,
transform: () => [
{ id: 'text', start: 0, end: 1, data: { text: 'a' } }, blocker,
{ id: 'text', start: 4, end: 6, data: { text: 'ef' } },
],
},
attachmentReferenceRule,
])
const attachment = { type: 'file' as const, ref: { attachmentId: AttachmentId('file'), name: 'a', bytes: 1 } }
const nodes = evaluate({
text: 'abcdef', facts: { attachments: [{ start: 1, end: 4, attachment }, { start: 4, end: 6, attachment }] },
})
expect(nodes[1]).toBe(blocker)
expect(nodes.filter(node => node.id === 'attachment').map(node => [node.start, node.end])).toEqual([[4, 6]])
const crossing = evaluate({ text: 'abcdef', facts: { attachments: [{ start: 0, end: 5, attachment }] } })
expect(crossing[1]).toBe(blocker)
expect(crossing.filter(node => node.id === 'attachment')).toEqual([])
})
it('carries only explicitly located image and file references as JSON', () => {
const evaluate = setup()
const image: ImageAttachmentRef = {
attachmentId: AttachmentId('image-id'), mediaType: 'image/png', bytes: 13,
width: 10, height: 20, name: 'photo.png', originalDimensions: { width: 100, height: 200 },
}
const file: FileAttachmentRef = { attachmentId: AttachmentId('file-id'), name: 'report.pdf', bytes: 42 }
const imageAttachment = Object.freeze({ type: 'image' as const, ref: Object.freeze(image) })
const fileAttachment = Object.freeze({ type: 'file' as const, ref: Object.freeze(file) })
const input = Object.freeze({
text: '🙂 image file',
facts: Object.freeze({ attachments: Object.freeze([
Object.freeze({ start: 3, end: 8, attachment: imageAttachment }),
Object.freeze({ start: 9, end: 13, attachment: fileAttachment }),
]) }),
})
const matches = evaluate(input).filter(node => node.id === 'attachment')
expect(attachmentReferenceRule.id).toBe('attachment')
expect(matches).toEqual([
{ id: 'attachment', start: 3, end: 8, data: { attachment: imageAttachment } },
{ id: 'attachment', start: 9, end: 13, data: { attachment: fileAttachment } },
])
expect(JSON.parse(JSON.stringify(matches))).toEqual(matches)
})
it('never treats a display name as a path or infers a second same-name reference', () => {
const evaluate = setup()
const text = '@report.pdf and @report.pdf'
const ref: FileAttachmentRef = { attachmentId: AttachmentId('chosen-file'), name: 'report.pdf', bytes: 5 }
expect(evaluate({ text, facts: {} }).filter(node => node.id === 'attachment')).toEqual([])
expect(evaluate({ text, facts: { attachments: [] } }).filter(node => node.id === 'attachment')).toEqual([])
const start = text.lastIndexOf('@report.pdf')
expect(evaluate({
text, facts: { attachments: [{ start, end: text.length, attachment: { type: 'file', ref } }] },
}).filter(node => node.id === 'attachment')).toEqual([{ id: 'attachment', start, end: text.length, data: { attachment: { type: 'file', ref } } }])
})
})
@@ -16,7 +16,7 @@ import type { UserTextInjected } from '@deepseek-ai/dsh-client-ui-conversation/c
import { UserTextRegistry } from '../../ui-conversation/src/client/conversation/user-text-registry.ts'
import { UserText, PlainUserText, SessionReference } from '../../ui-conversation/src/client/user-text/UserText.tsx'
import { sessionReferenceRule } from '../../ui-conversation/src/client/user-text/session-reference-rule.ts'
import { collapseWhitespaceRule, stripEmojiRule, trimWhitespaceRule } from '../../ui-conversation/src/client/user-text/display-rules.ts'
import { collapseWhitespaceRule, trimWhitespaceRule } from '../../ui-conversation/src/client/user-text/display-rules.ts'
import { fileReferenceRule, folderReferenceRule } from '../../ui-reference/src/client/user-text-rules.ts'
import { FileReference, FolderReference } from '../../ui-reference/src/client/FileReference.tsx'
import { en as referenceEn, zh as referenceZh } from '../../ui-reference/src/client/locales.ts'
@@ -57,7 +57,7 @@ async function bench() {
const userText = new UserTextRegistry(ctx)
for (const rule of [
sessionReferenceRule, fileReferenceRule, folderReferenceRule, skillReferenceRule,
stripEmojiRule, collapseWhitespaceRule, trimWhitespaceRule,
collapseWhitespaceRule, trimWhitespaceRule,
]) {
userText.register(rule)
}
@@ -12,14 +12,17 @@
en: bac0bf0d7330f3b1
zh: 84a895f4b26d8490
/deepseek-ai-dsh-client-ui-conversation/table-of-contents:
en: 9c1c4905952fea5e
zh: d1506dd6fc1018d1
en: eef4f18c3972ccc4
zh: 6be65c6ac84ce497
/deepseek-ai-dsh-client-ui-conversation/conversation-assembly:
en: 1d2a3a7f98c2cc9b
zh: f895dd5e9f91e0a9
en: 6aefa09bb22fdf81
zh: 0641c4196437cf53
/deepseek-ai-dsh-client-ui-conversation/sent-user-text:
en: 96bdc17762697cb8
zh: 91554a16df23f850
/deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props:
en: 0ff4669e7d9e9235
zh: ec69fae087f04660
en: ddabf2f192114e62
zh: 31370ed6d5149409
/deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries:
en: bb1244310f5c0382
zh: 824b84077432b559
+11 -1
View File
@@ -16,6 +16,7 @@ Desktop product events use the optional [product analytics service](../product-a
## Table of Contents
- [Conversation assembly](#conversation-assembly)
- [Sent user text](#sent-user-text)
- [Shell and standard props](#shell-and-standard-props)
- [Temporary composer entries](#temporary-composer-entries)
- [Model Experience](#model-experience)
@@ -49,6 +50,15 @@ Group registration rejects a missing View target. Removing an already registered
Target packages declaration-merge their snapshot and Location data maps, then register with `ctx.uiConversation.events.register(...)` and `ctx.uiConversation.views.register(...)`. A target reads its Session-owned source with `ctx.uiConversation.binding(binding).target(targetId)`. Registrations are Cordis effects and their returned disposers remove the contribution from the same registry. The shared request inspection serves every target: `ctx.uiConversation.inspectSystemPrompt(previous, event)` interprets system messages and positional replacements as immutable loaded-surface state. It selects the last nonempty surviving system node in surface order, retains only surviving replacement positions for chained rewrites, and withholds the prompt after an unindexed older endpoint until prepend replay supplies its order. Target-owned Definitions retain historical cards independently. `ctx.uiConversation.inspectRequestPrompt(previous, header, system)` classifies request changes against that effective prompt; ordinary messages and stream chunks require no system-state work.
<a id="sent-user-text"></a>
## Sent user text
`UiConversation.userText` registers synchronous JSON transforms ordered by `order` and stable ID. Each caller owns an evaluator; `Context.read(key)` tracks the Facts fields that invalidate its cached stages. Inputs and outputs use readonly types without runtime freezing. Rules preserve original UTF-16 coverage and existing business nodes. See the [UserText types](src/client/contract/user-text.ts) and [design decision](../../../.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.md).
Businesses extend `UserTextDataMap` and `UserTextFacts` on this package's `/client` entry, register a transform through `ctx.uiConversation.userText`, and contribute their renderer to `conversation.user.text.node`. The session-scoped `conversation.user.text` Factory owns this inline keyed Slot. Node registrations supply their own actions; `interactive` controls activation and `ellipsis` controls CSS presentation. Missing renderers display the original fragment; transform failures retain the complete original text and report the rule error.
Queue previews enable whitespace collapsing and document-edge trimming, retain emoji, and use CSS ellipsis without truncating the input. Editing and copying retain the original text; native attachments use their separate presentation.
<a id="shell-and-standard-props"></a>
## Shell and standard props
@@ -84,7 +94,7 @@ Active transcripts in the main occurrence expose content-width drag handles in t
The width-handle indicator follows the pointer only during a captured drag; ordinary hover leaves its position unchanged.
The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's text and semantic references are persisted by the per-Session Conversation store. QueueDock reads `next-turn` from the Session `inbox` projection, including cold recovered messages, and excludes only requestIds still owned by local transcript submissions. Other queued rows retain their normal display and actions. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text in the ui-primitives `InlineEditor`, so line breaks survive re-editing. Durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start.
The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's text and semantic references are persisted by the per-Session Conversation store. QueueDock reads `next-turn` from the Session `inbox` projection, including cold recovered messages, and excludes only requestIds still owned by local transcript submissions. Other queued rows retain their normal display and actions. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews use the [UserText Factory](#sent-user-text) (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text in the ui-primitives `InlineEditor`, so line breaks survive re-editing. Durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start.
Plain Enter uses the configured delivery mode, exactly Ctrl+Enter or Cmd+Enter uses its complement, and Shift+Enter inserts a line break. Enter with Alt, AltGraph, both Ctrl and Cmd, or Shift plus Ctrl/Cmd leaves the draft and command menu unchanged and keeps the DOM event available to application shortcuts. The Conversation plugin registers the fixed send, newline, complementary-delivery, command-menu, and reference-menu rows and reserves their bindings until it unloads.
+11 -1
View File
@@ -16,6 +16,7 @@ kind: "package-reference"
## 目录
- [Conversation 组装](#conversation-assembly)
- [已发送用户文本](#sent-user-text)
- [Shell 与标准 props](#shell-and-standard-props)
- [临时 composer entry](#temporary-composer-entries)
- [模型体验](#model-experience)
@@ -49,6 +50,15 @@ Group 注册时缺少 View 目标会报错。已注册的 View Definition 被移
target package 通过 declaration merge 扩展 snapshot 与 Location data map,再调用 `ctx.uiConversation.events.register(...)` 和 `ctx.uiConversation.views.register(...)`。target 通过 `ctx.uiConversation.binding(binding).target(targetId)` 读取其 Session-owned source。注册属于 Cordis effect,返回的 disposer 从同一个 registry 移除 contribution。共享的请求检查服务于每个 target:`ctx.uiConversation.inspectSystemPrompt(previous, event)` 将系统消息与位置替换解释为不可变的已加载 surface 状态。它按 surface 顺序选择最后一个非空的存活系统节点,为连续重写只保留存活的替换位置;遇到未建立索引的更早端点后,提示词保持不可用,直到向前补页回放提供其顺序。target 自有的 Definition 独立保留历史卡片。`ctx.uiConversation.inspectRequestPrompt(previous, header, system)` 根据该有效提示词分类请求变更;普通消息与流式分片无需处理系统状态。
<a id="sent-user-text"></a>
## 已发送用户文本
`UiConversation.userText` 注册同步 JSON 变换,按 `order` 和稳定 ID 排序。每个调用者独立拥有求值器;`Context.read(key)` 跟踪使阶段缓存失效的 Facts 字段。输入和输出使用 readonly 类型,不在运行时冻结。规则保留原始 UTF-16 覆盖范围及已有业务节点。详见 [UserText 类型](src/client/contract/user-text.ts)与[设计决策](../../../.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.zh.md)。
业务扩展本包 `/client` 入口的 `UserTextDataMap` 和 `UserTextFacts`,通过 `ctx.uiConversation.userText` 注册变换,并向 `conversation.user.text.node` 贡献 renderer。Session 作用域的 `conversation.user.text` Factory 拥有这个行内 keyed Slot。节点注册自行提供动作;`interactive` 控制激活,`ellipsis` 控制 CSS 展示。缺少 renderer 时显示原文片段;变换失败时保留完整原文并报告规则错误。
Queue 预览启用空白折叠和文档边缘 trim,保留 emoji,并使用 CSS 省略而不截断输入。编辑和复制保留原文;原生附件使用独立的展示路径。
<a id="shell-and-standard-props"></a>
## Shell 与标准 props
@@ -84,7 +94,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染
宽度拖拽条的指示线只在已捕获指针的拖拽期间跟随指针,普通悬停不改变其位置。
常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿文字和引用语义字段由逐 Session Conversation store 持久化。QueueDock 从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息,仅排除仍由本地 transcript 提交承接的 requestId。其他排队行保留正常展示和操作。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态在 ui-primitives 的 `InlineEditor` 中展示字面发送文本,因此重新编辑不会丢失换行。持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。
常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿文字和引用语义字段由逐 Session Conversation store 持久化。QueueDock 从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息,仅排除仍由本地 transcript 提交承接的 requestId。其他排队行保留正常展示和操作。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览使用 [UserText Factory](#sent-user-text)(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态在 ui-primitives 的 `InlineEditor` 中展示字面发送文本,因此重新编辑不会丢失换行。持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。
普通 Enter 使用已配置的投递模式,严格的 Ctrl+Enter 或 Cmd+Enter 使用互补模式,Shift+Enter 插入换行。带 Alt、AltGraph、同时带 Ctrl 与 Cmd,或 Shift 与 Ctrl/Cmd 的 Enter 保持草稿和指令菜单不变,并将 DOM 事件留给应用快捷键。Conversation 插件注册发送、换行、互补投递、命令菜单和引用菜单的固定条目,并在卸载前保留这些键位。
@@ -16,7 +16,7 @@ import type { ShortcutCommandId, ShortcutFixedCommand } from '@deepseek-ai/dsh-c
import { UiConversation } from './conversation/assembly.ts'
import { UserText, PlainUserText, SessionReference } from './user-text/UserText.tsx'
import { sessionReferenceRule } from './user-text/session-reference-rule.ts'
import { collapseWhitespaceRule, stripEmojiRule, trimWhitespaceRule } from './user-text/display-rules.ts'
import { collapseWhitespaceRule, trimWhitespaceRule } from './user-text/display-rules.ts'
import type { ViewTab } from './contract/views.ts'
import type {
ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected,
@@ -160,7 +160,6 @@ export function apply(ctx: Context, config: Config = Config({})): void {
const workspaceNavigation = ctx.get('uiWorkspace') as unknown as WorkspaceNavigation
const uiConversation = new UiConversation(ctx, sessions)
uiConversation.userText.register(sessionReferenceRule)
uiConversation.userText.register(stripEmojiRule)
uiConversation.userText.register(collapseWhitespaceRule)
uiConversation.userText.register(trimWhitespaceRule)
slots.registerFactory({
@@ -46,7 +46,7 @@ export interface UserTextRule<Id extends string = string> {
* May split or merge adjacent Text nodes, update their `data.display`, and create business nodes using this rule's ID.
* Text `data.text` always retains its original substring; display transforms compose from `display ?? text`.
* Must not mutate inputs or consume or rewrite existing business nodes.
* @param segments - complete, frozen upstream nodes in original UTF-16 coordinates.
* @param segments - complete, readonly upstream nodes in original UTF-16 coordinates.
* @param context - synchronous facts reader; reads replace this stage's previous dependencies.
* @returns full ordered source coverage; new business nodes stay within one input Text segment.
* Preserve unchanged input objects and return the input array when nothing changes.
@@ -59,6 +59,6 @@ export interface UserTextRule<Id extends string = string> {
* Reentrant calls throw. A failed stage throws an Error carrying ruleId and cause, never partial output;
* its failure and reads are cached until its definition, upstream input, text or a read field changes.
* @param input - original text and immutable JSON facts; fields are compared with Object.is.
* @returns frozen nodes covering the text, or [] for empty text; equivalent results retain identities.
* @returns readonly nodes covering the text, or [] for empty text; equivalent results retain identities.
*/
export type UserTextEvaluator = (input: UserTextDocumentInput) => readonly UserTextNode[]
@@ -26,11 +26,10 @@ interface Stage {
/** Internal cache owned by one evaluator; no registry or React lifetime is retained here. */
export class UserTextDocument {
private text: string | undefined
private initial: readonly UserTextNode[] = Object.freeze([])
private initial: readonly UserTextNode[] = []
private rules: readonly UserTextRule[] | undefined
private readonly stages = new Map<string, Stage>()
private readonly readers = new Map<FactKey, Set<Stage>>()
private readonly frozen = new WeakSet<object>()
private evaluating = false
/**
@@ -71,7 +70,6 @@ export class UserTextDocument {
this.initial = input.text.length === 0 ? [] : [
{ id: 'text', start: 0, end: input.text.length, data: { text: input.text } },
]
this.freeze(this.initial)
}
if (this.rules !== rules) {
const ids = new Set(rules.map(rule => rule.id))
@@ -94,14 +92,14 @@ export class UserTextDocument {
private run(stage: Stage, definition: UserTextRule, segments: readonly UserTextNode[], input: UserTextDocumentInput): void {
const reads = new Map<FactKey, unknown>()
let active = true
const context: UserTextTransformContext = Object.freeze({
const context: UserTextTransformContext = {
read: <K extends FactKey>(key: K): UserTextFacts[K] | undefined => {
if (!active) throw new Error('user-text transform context is closed; read is synchronous only')
const value = input.facts[key]
reads.set(key, value)
return value
},
})
}
stage.definition = definition
stage.input = segments
stage.dirty = false
@@ -114,9 +112,7 @@ export class UserTextDocument {
active = false
}
validateOutput(input.text, definition.id, segments, output)
const aligned = alignNodes(output, stage.output, segments)
this.freeze(aligned)
stage.output = aligned
stage.output = alignNodes(output, stage.output, segments)
} catch (cause) {
stage.error = new UserTextTransformError(definition.id, cause)
} finally {
@@ -139,13 +135,6 @@ export class UserTextDocument {
readers.add(stage)
}
}
private freeze(value: unknown): void {
if (value === null || typeof value !== 'object' || this.frozen.has(value)) return
for (const child of Object.values(value)) this.freeze(child)
Object.freeze(value)
this.frozen.add(value)
}
}
function assertSynchronousOutput(output: unknown): void {
@@ -5,7 +5,7 @@ import { UserTextDocument } from './user-text-document.ts'
/** Observable rule revision with no retained documents or document subscriptions. */
export class UserTextRegistry extends ConversationDefinitionRegistry<UserTextRule> {
private rules: readonly UserTextRule[] = Object.freeze([])
private rules: readonly UserTextRule[] = []
private revision = 0
/**
@@ -19,7 +19,7 @@ export class UserTextRegistry extends ConversationDefinitionRegistry<UserTextRul
if (!Number.isFinite(rule.order)) throw new Error(`user-text rule "${rule.id}" order must be finite`)
return this.registerDefinition(
rule.id,
Object.freeze(rule),
rule,
`user-text rule "${rule.id}" is already registered`,
`uiConversation.userText.register(${JSON.stringify(rule.id)})`,
)
@@ -43,8 +43,8 @@ export class UserTextRegistry extends ConversationDefinitionRegistry<UserTextRul
}
protected override refresh(): void {
this.rules = Object.freeze([...this.definitions.values()].sort((a, b) =>
a.order - b.order || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)))
this.rules = [...this.definitions.values()].sort((a, b) =>
a.order - b.order || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
this.revision++
super.refresh()
}
@@ -17,8 +17,6 @@ export interface UserTextFacts {
readonly collapseWhitespace: boolean
/** Remove display whitespace only at the document's outer edges, without crossing business nodes. */
readonly trimWhitespace: boolean
/** Remove complete emoji graphemes from ordinary display text. */
readonly stripEmoji: boolean
}
export type {
@@ -6,36 +6,6 @@ function withDisplay(node: UserTextNode<'text'>, display: string): UserTextNode<
return { ...node, data: { ...node.data, display } }
}
function mapTextDisplay(
segments: readonly UserTextNode[], transform: (display: string) => string,
): readonly UserTextNode[] {
let result: UserTextNode[] | undefined
for (const [index, node] of segments.entries()) {
const updated = node.id === 'text' ? withDisplay(node, transform(node.data.display ?? node.data.text)) : node
if (updated !== node) result ??= segments.slice(0, index)
result?.push(updated)
}
return result ?? segments
}
/** Remove whole emoji graphemes only when `stripEmoji` is true; ordinary letters and digits are preserved. */
export const stripEmojiRule: UserTextRule<'text.strip-emoji'> = {
id: 'text.strip-emoji',
order: 1000,
transform(segments, context) {
if (!context.read('stripEmoji')) return segments
const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' })
const emoji = /[\p{Extended_Pictographic}\p{Regional_Indicator}\p{Emoji_Presentation}]|^[0-9#*]\ufe0f?\u20e3/u
return mapTextDisplay(segments, (display) => {
let result = ''
for (const { segment } of segmenter.segment(display)) {
if (!emoji.test(segment)) result += segment
}
return result
})
},
}
/** Collapse whitespace across adjacent Text displays when enabled; business nodes separate runs. */
export const collapseWhitespaceRule: UserTextRule<'text.collapse-whitespace'> = {
id: 'text.collapse-whitespace',
@@ -9,7 +9,7 @@ import type { UserTextNode } from '../src/client/contract/user-text.ts'
import { UserTextRegistry } from '../src/client/conversation/user-text-registry.ts'
import { UserText, PlainUserText, SessionReference } from '../src/client/user-text/UserText.tsx'
import { sessionReferenceRule } from '../src/client/user-text/session-reference-rule.ts'
import { collapseWhitespaceRule, stripEmojiRule, trimWhitespaceRule } from '../src/client/user-text/display-rules.ts'
import { collapseWhitespaceRule, trimWhitespaceRule } from '../src/client/user-text/display-rules.ts'
import { skillReferenceRule } from '../../ui-skill/src/client/user-text-rules.ts'
import { SkillReference } from '../../ui-skill/src/client/SkillReference.tsx'
import { fileReferenceRule, folderReferenceRule } from '../../ui-reference/src/client/user-text-rules.ts'
@@ -38,7 +38,7 @@ export function createUserTextFixture(actions: UserTextFixtureActions = {}): (in
const registry = new UserTextRegistry(ctx)
for (const rule of [
sessionReferenceRule, skillReferenceRule, fileReferenceRule, folderReferenceRule,
goalCommandReferenceRule, stripEmojiRule, collapseWhitespaceRule, trimWhitespaceRule,
goalCommandReferenceRule, collapseWhitespaceRule, trimWhitespaceRule,
]) registry.register(rule)
const useUserTextRevision = bindSnapshotSelector({
getSnapshot: () => registry.getSnapshot(),
@@ -5,11 +5,11 @@ import type {
} from '@deepseek-ai/dsh-client-ui-conversation/client'
import { UserTextRegistry } from '../src/client/conversation/user-text-registry.ts'
import {
collapseWhitespaceRule, stripEmojiRule, trimWhitespaceRule,
collapseWhitespaceRule, trimWhitespaceRule,
} from '../src/client/user-text/display-rules.ts'
import { sessionReferenceRule } from '../src/client/user-text/session-reference-rule.ts'
const displayRules = [trimWhitespaceRule, collapseWhitespaceRule, stripEmojiRule]
const displayRules = [trimWhitespaceRule, collapseWhitespaceRule]
function track(rule: UserTextRule) {
return vi.fn((segments: readonly UserTextNode[], context: UserTextTransformContext) => rule.transform(segments, context))
@@ -33,8 +33,6 @@ function assertSource(text: string, nodes: readonly UserTextNode[]): void {
expect(node.start).toBe(cursor)
expect(node.end).toBeGreaterThan(cursor)
if (node.id === 'text') expect(node.data.text).toBe(text.slice(node.start, node.end))
expect(Object.isFrozen(node)).toBe(true)
expect(Object.isFrozen(node.data)).toBe(true)
cursor = node.end
}
expect(cursor).toBe(text.length)
@@ -59,7 +57,6 @@ describe('user-text display facts', () => {
it('declares independent boolean facts and an optional display string without new node kinds', () => {
expectTypeOf<UserTextFacts['collapseWhitespace']>().toEqualTypeOf<boolean>()
expectTypeOf<UserTextFacts['trimWhitespace']>().toEqualTypeOf<boolean>()
expectTypeOf<UserTextFacts['stripEmoji']>().toEqualTypeOf<boolean>()
expectTypeOf<UserTextFacts>().not.toHaveProperty('ellipsis')
expectTypeOf<UserTextFacts>().not.toHaveProperty('interactive')
expectTypeOf<UserTextFacts['sessionLabels']>().toEqualTypeOf<readonly string[]>()
@@ -76,13 +73,12 @@ describe('user-text display facts', () => {
expect(evaluate({ text, facts: {} })).toBe(nodes)
expect(nodes).toEqual([{ id: 'text', start: 0, end: text.length, data: { text } }])
expect(evaluate({ text: '', facts: {} })).toBe(first.mock.lastCall?.[0])
expect(evaluate({ text: '', facts: { stripEmoji: true, collapseWhitespace: true, trimWhitespace: true } })).toEqual([])
expect(evaluate({ text: '', facts: { collapseWhitespace: true, trimWhitespace: true } })).toEqual([])
})
it.each([
['collapseWhitespace', collapseWhitespaceRule, ' \t甲\r\n乙\u00a0 ', ' 甲 乙 '],
['trimWhitespace', trimWhitespaceRule, ' \t甲\r\n乙\u00a0 ', '甲\r\n乙'],
['stripEmoji', stripEmojiRule, ' 甲🙂乙 ', ' 甲乙 '],
] as const)('reads only %s, recomputes missing-to-true and restores the source when withdrawn', (flag, rule, text, display) => {
const reads: (keyof UserTextFacts)[] = []
const transform = vi.fn((segments: readonly UserTextNode[], context: UserTextTransformContext) => rule.transform(segments, {
@@ -116,22 +112,22 @@ describe('user-text display facts', () => {
})
it('orders default display rules after the existing reference rule and preserves its atoms', () => {
expect([stripEmojiRule.order, collapseWhitespaceRule.order, trimWhitespaceRule.order]).toEqual([1000, 1010, 1020])
expect(sessionReferenceRule.order).toBeLessThan(stripEmojiRule.order)
expect([collapseWhitespaceRule.order, trimWhitespaceRule.order]).toEqual([1010, 1020])
expect(sessionReferenceRule.order).toBeLessThan(collapseWhitespaceRule.order)
const content = track(sessionReferenceRule)
const registry = setup([...displayRules, { ...sessionReferenceRule, transform: content }])
const evaluate = registry.createEvaluator()
const wire = '@[🧑‍🚀 引用](dsh-session:abc)'
const text = ` \t🙂甲\n ${wire} \r\n乙🇨🇳 \t`
const original = evaluate({ text, facts: {} })
const nodes = evaluate({ text, facts: { stripEmoji: true, collapseWhitespace: true, trimWhitespace: true } })
expect(visible(nodes)).toBe('甲 [session] 乙')
const nodes = evaluate({ text, facts: { collapseWhitespace: true, trimWhitespace: true } })
expect(visible(nodes)).toBe('🙂甲 [session] 乙🇨🇳')
expect(nodes[1]).toBe(original[1])
expect(nodes[1]).toEqual({ id: 'session', start: text.indexOf(wire), end: text.indexOf(wire) + wire.length,
data: { label: '🧑‍🚀 引用' } })
expect(content).toHaveBeenCalledOnce()
assertSource(text, nodes)
expect(registry.createEvaluator()({ text, facts: { stripEmoji: true, collapseWhitespace: true, trimWhitespace: true } })).toEqual(nodes)
expect(registry.createEvaluator()({ text, facts: { collapseWhitespace: true, trimWhitespace: true } })).toEqual(nodes)
})
it('allows a display rule to run before reference matching when its ordinary order is lower', () => {
@@ -141,21 +137,21 @@ describe('user-text display facts', () => {
observed.push(visible(segments))
return sessionReferenceRule.transform(segments, context)
} },
{ ...stripEmojiRule, order: -1 },
{ ...collapseWhitespaceRule, order: -1 },
])
const text = '@[🙂ref](dsh-session:x)'
const input = { text, facts: { stripEmoji: true } }
const text = '@[two words](dsh-session:x)'
const input = { text, facts: { collapseWhitespace: true } }
const nodes = registry.createEvaluator()(input)
expect(observed).toEqual(['@[ref](dsh-session:x)'])
expect(nodes).toEqual([{ id: 'session', start: 0, end: text.length, data: { label: '🙂ref' } }])
expect(observed).toEqual(['@[two words](dsh-session:x)'])
expect(nodes).toEqual([{ id: 'session', start: 0, end: text.length, data: { label: 'two words' } }])
assertSource(text, nodes)
})
it('allows custom transforms between and after the default display orders', () => {
it('allows custom transforms before and after the default display orders', () => {
const observed: string[] = []
const registry = setup([
...displayRules,
{ id: 'custom.between', order: 1005, transform: (segments) => {
{ id: 'custom.before', order: 1005, transform: (segments) => {
observed.push(visible(segments))
return segments.map(node => node.id === 'text'
? { ...node, data: { ...node.data, display: `${node.data.display ?? node.data.text}\t乙 ` } } : node)
@@ -166,51 +162,50 @@ describe('user-text display facts', () => {
} },
])
const text = ' 🙂 甲 '
const facts = { stripEmoji: true, collapseWhitespace: true, trimWhitespace: true }
const facts = { collapseWhitespace: true, trimWhitespace: true }
const nodes = registry.createEvaluator()({ text, facts })
expect(observed).toEqual([' 甲 ', '甲 乙'])
expect(visible(nodes)).toBe('甲 乙')
expect(observed).toEqual([' 🙂 甲 ', '🙂 甲 乙'])
expect(visible(nodes)).toBe('🙂 甲 乙')
assertSource(text, nodes)
})
it('applies strip, collapse and document trim to the preceding display value in ordinary order', () => {
it('composes whitespace transforms without removing emoji', () => {
const evaluate = setup().createEvaluator()
const text = ' \t🙂 \n甲 👨‍👩‍👧‍👦\t 乙🇨🇳 \t'
const facts = { stripEmoji: true, collapseWhitespace: true, trimWhitespace: true }
expect(visible(evaluate({ text, facts }))).toBe('甲 乙')
expect(visible(evaluate({ text, facts: { ...facts, stripEmoji: false } }))).toBe('🙂 甲 👨‍👩‍👧‍👦 乙🇨🇳')
expect(visible(evaluate({ text, facts: { ...facts, collapseWhitespace: false } }))).toBe('甲 \t 乙')
expect(visible(evaluate({ text, facts: { ...facts, trimWhitespace: false } }))).toBe(' 甲 乙 ')
const facts = { collapseWhitespace: true, trimWhitespace: true }
expect(visible(evaluate({ text, facts }))).toBe('🙂 甲 👨‍👩‍👧‍👦 乙🇨🇳')
expect(visible(evaluate({ text, facts: { trimWhitespace: true } }))).toBe(text.trim())
expect(visible(evaluate({ text, facts: { collapseWhitespace: true } }))).toBe(' 🙂 甲 👨‍👩‍👧‍👦 乙🇨🇳 ')
expect(visible(evaluate({ text, facts: {} }))).toBe(text)
})
it.each([
{ parts: ['a ', ' \nb'], expected: 'a b' },
{ parts: ['a ', '😀', ' b'], expected: 'a b' },
{ parts: ['a ', '😀', '\t', '😀', ' b'], expected: 'a b' },
{ parts: ['a ', '\t', ' b'], expected: 'a b' },
{ parts: ['a ', '\n', '\t', ' ', ' b'], expected: 'a b' },
{ parts: ['\t', '\n', 'a'], expected: ' a' },
{ parts: ['a ', '\n', '😀'], expected: 'a ' },
{ parts: ['a', '😀', 'b'], expected: 'ab' },
{ parts: ['a ', '\n', '\t'], expected: 'a ' },
{ parts: ['a', '😀', 'b'], expected: 'a😀b' },
])('collapses contiguous display whitespace across adjacent Text nodes: $parts', ({ parts, expected }) => {
const registry = setup([splitText(parts), stripEmojiRule, collapseWhitespaceRule])
const registry = setup([splitText(parts), collapseWhitespaceRule])
const evaluate = registry.createEvaluator()
const text = parts.join('')
const original = evaluate({ text, facts: { stripEmoji: true } })
const nodes = evaluate({ text, facts: { stripEmoji: true, collapseWhitespace: true } })
const original = evaluate({ text, facts: {} })
const nodes = evaluate({ text, facts: { collapseWhitespace: true } })
expect(visible(nodes)).toBe(expected)
expect(nodes).toHaveLength(parts.length)
if (parts[0]?.startsWith('a')) expect(nodes[0]).toBe(original[0])
expect(evaluate({ text, facts: { stripEmoji: true } })).toBe(original)
expect(evaluate({ text, facts: {} })).toBe(original)
assertSource(text, nodes)
})
it('resets whitespace collapsing at each atomic reference and keeps spaces on both sides', () => {
const parts = ['a ', '@[😀 ref](dsh-session:x)', ' ', ' \nb ', '@[tail](dsh-session:y)', ' ', '\tc']
const registry = setup([splitText(parts), sessionReferenceRule, stripEmojiRule, collapseWhitespaceRule])
const registry = setup([splitText(parts), sessionReferenceRule, collapseWhitespaceRule])
const evaluate = registry.createEvaluator()
const text = parts.join('')
const original = evaluate({ text, facts: { stripEmoji: true } })
const nodes = evaluate({ text, facts: { stripEmoji: true, collapseWhitespace: true } })
const original = evaluate({ text, facts: {} })
const nodes = evaluate({ text, facts: { collapseWhitespace: true } })
expect(visible(nodes)).toBe('a [session] b [session] c')
expect(nodes).toHaveLength(original.length)
expect(nodes[0]).toBe(original[0])
@@ -221,15 +216,15 @@ describe('user-text display facts', () => {
})
it.each([
{ parts: [' \t', '🙂', '\n ', '甲 ', ' 乙', ' \t', '🙂', '\n '], expected: '甲 乙' },
{ parts: [' \t', '🙂', '\n '], expected: '' },
{ parts: [' \t', '\t', '\n ', '甲 ', ' 乙', ' \t', '\t', '\n '], expected: '甲 乙' },
{ parts: [' \t', '\t', '\n '], expected: '' },
{ parts: ['甲 ', ' 乙'], expected: '甲 乙' },
])('trims only document edges across empty text displays: $parts', ({ parts, expected }) => {
const registry = setup([splitText(parts), stripEmojiRule, trimWhitespaceRule])
const registry = setup([splitText(parts), trimWhitespaceRule])
const text = parts.join('')
const evaluate = registry.createEvaluator()
const original = evaluate({ text, facts: { stripEmoji: true } })
const nodes = evaluate({ text, facts: { stripEmoji: true, trimWhitespace: true } })
const original = evaluate({ text, facts: {} })
const nodes = evaluate({ text, facts: { trimWhitespace: true } })
expect(visible(nodes)).toBe(expected)
expect(nodes).toHaveLength(parts.length)
for (let index = 0; index < parts.length; index++) {
@@ -239,38 +234,24 @@ describe('user-text display facts', () => {
})
it.each([
[' \n🙂@[a](dsh-session:x) \t @[b](dsh-session:y)🙂 \t', '[session] \t [session]'],
[' \n@[a](dsh-session:x) \t @[b](dsh-session:y) \t', '[session] \t [session]'],
['@[a](dsh-session:x) \t 甲 \n @[b](dsh-session:y)', '[session] \t 甲 \n [session]'],
['@[a](dsh-session:x) \t 甲 \n', '[session] \t 甲'],
[' \t 甲 \n @[b](dsh-session:y)', '甲 \n [session]'],
])('does not trim through visible business nodes or remove reference spacing: %s', (text, expected) => {
const registry = setup([sessionReferenceRule, stripEmojiRule, trimWhitespaceRule])
const nodes = registry.createEvaluator()({ text, facts: { stripEmoji: true, trimWhitespace: true } })
const registry = setup([sessionReferenceRule, trimWhitespaceRule])
const nodes = registry.createEvaluator()({ text, facts: { trimWhitespace: true } })
expect(visible(nodes)).toBe(expected)
assertSource(text, nodes)
})
it('removes whole emoji graphemes without losing Han, ASCII numbers, combining text or joiners in ordinary text', () => {
const text = '甲0 123 #* e\u0301 क्‍ष 👨‍👩‍👧‍👦👍🏽🇨🇳🇺🇳1️⃣2⃣#️⃣*️⃣🏳️‍🌈❤️🧑🏾‍🚀乙'
const nodes = setup().createEvaluator()({ text, facts: { stripEmoji: true } })
expect(visible(nodes)).toBe('甲0 123 #* e\u0301 क्‍ष 乙')
assertSource(text, nodes)
})
it('does not classify enclosing-keycap marks on Han or letters as emoji sequences', () => {
const text = '甲\u20e3 e\u20e3 123 7\ufe0f 1️⃣'
const nodes = setup().createEvaluator()({ text, facts: { stripEmoji: true } })
expect(visible(nodes)).toBe('甲\u20e3 e\u20e3 123 7\ufe0f ')
assertSource(text, nodes)
})
it('preserves input identities when enabled transforms have no visible change', () => {
const first = vi.fn((segments: readonly UserTextNode[]) => segments)
const registry = setup([{ id: 'test.observe', order: 0, transform: first }, ...displayRules])
const evaluate = registry.createEvaluator()
const text = '甲 乙123'
const original = evaluate({ text, facts: {} })
expect(evaluate({ text, facts: { stripEmoji: true, collapseWhitespace: true, trimWhitespace: true } })).toBe(original)
expect(evaluate({ text, facts: { collapseWhitespace: true, trimWhitespace: true } })).toBe(original)
expect(original).toBe(first.mock.lastCall?.[0])
})
@@ -28,6 +28,7 @@ declare module '@deepseek-ai/dsh-client-ui-conversation/client' {
interface UserTextFacts {
readonly testEnabled: boolean
readonly testLabel: string
readonly testNested: NonNullable<AnnotationData['nested']>
readonly testOther: number
readonly skillNames: readonly string[]
}
@@ -477,21 +478,30 @@ describe('UserTextRegistry linear transforms', () => {
expect(() => registry.createEvaluator()({ text: 'abc', facts: {} })).toThrow(/test\.z/)
})
it.each(['array', 'node', 'payload'] as const)('freezes %s input against mutation', (target) => {
it('keeps nodes readonly in types without freezing borrowed payloads', () => {
expectTypeOf<Parameters<UserTextRule['transform']>[0]>().toEqualTypeOf<readonly UserTextNode[]>()
expectTypeOf<UserTextNode<'text'>>().toEqualTypeOf<Readonly<UserTextNode<'text'>>>()
expectTypeOf<UserTextNode<'text'>['data']>().toEqualTypeOf<{ readonly text: string; readonly display?: string }>()
expectTypeOf<NonNullable<AnnotationData['nested']>['values']>().toEqualTypeOf<readonly (string | number | boolean | null)[]>()
const { registry } = setup()
registry.register({
id: 'test.a', order: 0,
transform: (segments) => {
expect(Object.isFrozen(segments)).toBe(true)
expect(Object.isFrozen(segments[0])).toBe(true)
expect(Object.isFrozen(segments[0]?.data)).toBe(true)
if (target === 'array') Object.assign(segments, { 0: plain('bad') })
else if (target === 'node') Object.assign(segments[0]!, { end: 2 })
else Object.assign(segments[0]!.data, { text: 'bad' })
return segments
const nested = { values: ['borrowed'] }
const definition: UserTextRule = {
id: 'test.annotation', order: 0,
transform: (_segments, context) => {
const value = context.read('testNested')
if (value === undefined) throw new Error('Missing test payload')
return [{ id: 'test.annotation', start: 0, end: 1, data: { label: 'x', nested: value } }]
},
})
expect(() => registry.createEvaluator()({ text: 'abc', facts: Object.freeze({}) })).toThrow(/test\.a/)
}
registry.register(definition)
const nodes = registry.createEvaluator()({ text: 'x', facts: { testNested: nested } })
if (nodes[0]?.id !== 'test.annotation') throw new Error('Missing annotation')
expect(nodes[0].data.nested).toBe(nested)
expect(Object.isFrozen(definition)).toBe(false)
expect(Object.isFrozen(nodes)).toBe(false)
expect(Object.isFrozen(nodes[0])).toBe(false)
expect(Object.isFrozen(nested)).toBe(false)
expect(Object.isFrozen(nested.values)).toBe(false)
})
it('closes escaped read contexts after both success and failure', () => {
+2 -2
View File
@@ -18,8 +18,8 @@
en: 4f6e6353d793a0de
zh: cde6e470f7dd9057
/deepseek-ai-dsh-client-ui-goal/use-this-package/the-command-input-bubble:
en: 05c5db0eb58dffef
zh: 54e7bea0b810b1b8
en: 05f0360b6c6dd3e9
zh: d14c3f15dc4cea5b
/deepseek-ai-dsh-client-ui-goal/use-this-package/failures:
en: 097bbdd748dc17e5
zh: 867d341d046ba609
+1 -1
View File
@@ -29,7 +29,7 @@ Mount this plugin alongside `ui-conversation` and the goal domain package; the s
### The command-input bubble
Each durable `/goal` run projects as a right-aligned user-style bubble labeled `Command input` (or `指令输入`), rendered before the generic command result row; the leading `/goal` token renders as a command reference chip in the code face through ui-primitives `projectUserText`, and the objective stays plain body text. It carries no timestamp, copy, or branch actions, and reloading reconstructs it from the run.
Each durable `/goal` run projects as a right-aligned user-style bubble labeled `Command input` (or `指令输入`), rendered before the generic command result row; the leading `/goal` token renders as a command reference chip in the code face through the shared `conversation.user.text` Factory and the Goal-owned `command` renderer, using the executed token range in `facts.commands`, and the objective stays plain body text. It carries no timestamp, copy, or branch actions, and reloading reconstructs it from the run.
### Failures
+1 -1
View File
@@ -29,7 +29,7 @@ Web GUI 的 goal 界面同时显示持久 goal 状态及当前的进程本地激
### 指令输入气泡
每条持久的 `/goal` 运行都投影为一个右对齐的用户样式气泡,标签为 `Command input`(或 `指令输入`),渲染在通用命令结果行之前;开头的 `/goal` token 经 ui-primitives 的 `projectUserText` 以等宽代码字体渲染为指令引用 chip,目标文本保持正文字体。它不含时间戳、复制或分支操作,重新加载时会依据运行记录重建。
每条持久的 `/goal` 运行都投影为一个右对齐的用户样式气泡,标签为 `Command input`(或 `指令输入`),渲染在通用命令结果行之前;开头的 `/goal` token 经共享的 `conversation.user.text` Factory 与 Goal 自有的 `command` renderer,使用 `facts.commands` 中的实际执行 token 范围, 以等宽代码字体渲染为指令引用 chip,目标文本保持正文字体。它不含时间戳、复制或分支操作,重新加载时会依据运行记录重建。
### 失败
@@ -3,6 +3,8 @@ import type { PropsLocale, PropsRenderFactories, PropsRuntime } from '@deepseek-
import { GOAL_COMMAND, type GoalCommandInputData } from './goal-command-input.ts'
import css from './GoalCommandInputView.module.css'
const GOAL_COMMANDS = [{ start: 0, end: GOAL_COMMAND.length + 1, name: GOAL_COMMAND }] as const
type GoalCommandInputViewProps =
PropsRuntime<'conversation.chat.node', 'command-input'>
& PropsLocale<'goal'>
@@ -18,7 +20,6 @@ export const GoalCommandInputView = memo(function GoalCommandInputView({
node, t, renderFactorySlot,
}: GoalCommandInputViewProps) {
const data: GoalCommandInputData = node.data
const commands = [{ start: 0, end: GOAL_COMMAND.length + 1, name: GOAL_COMMAND }]
return (
<div
className={css.row}
@@ -30,7 +31,7 @@ export const GoalCommandInputView = memo(function GoalCommandInputView({
<div className={css.bubble}>
{renderFactorySlot('conversation.user.text', {
text: data.text,
facts: { commands },
facts: { commands: GOAL_COMMANDS },
interactive: false,
})}
</div>
@@ -24,10 +24,11 @@ import { zh } from '../src/client/locales.ts'
afterEach(cleanup)
function textFactories(): PropsRenderFactories['renderFactorySlot'] {
function textFactories(onInput?: (input: UserTextInput) => void): PropsRenderFactories['renderFactorySlot'] {
const renderText = createUserTextFixture()
return (name, input) => {
if (name !== 'conversation.user.text') throw new Error(`Unexpected Goal Factory: ${name}`)
onInput?.(input as UserTextInput)
return renderText(input as UserTextInput)
}
}
@@ -149,6 +150,21 @@ describe('goal command input projection', () => {
expect(chips.map(chip => [chip.getAttribute('data-ref-chip'), chip.textContent])).toEqual([['command', '/goal']])
})
it('keeps command facts stable when the input row rerenders', () => {
const commands: UserTextInput['facts']['commands'][] = []
const props = {
node: { key: 'goal-command-input:stable', data: { commandId: 'command-goal', text: '/goal ship it', time: 1 } },
t: makeTranslate(zh, commonZh),
renderFactorySlot: textFactories((input) => { commands.push(input.facts.commands) }),
} as Parameters<typeof GoalCommandInputView>[0]
const view = render(<GoalCommandInputView {...props} />)
view.rerender(<GoalCommandInputView {...props} node={{ ...props.node }} />)
expect(commands).toHaveLength(2)
expect(commands[0]).toEqual([{ start: 0, end: 5, name: 'goal' }])
expect(commands[1]).toBe(commands[0])
expect(view.getByRole('group', { name: '指令输入' }).textContent).toBe('/goal ship it')
})
it('renders a bare /goal as one command chip and nothing else', () => {
const t = makeTranslate(zh, commonZh)
const props = {
@@ -18,14 +18,14 @@
en: 7bae72c97d0449f5
zh: 4589ecc2b216edc5
/deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog:
en: eb1d57b0d5851435
zh: 2789bf9b1e478905
en: 2afd547980f6f009
zh: bc0ab804bdf2d296
/deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons:
en: f0e54915b896af5a
zh: 2047520fd321be90
/deepseek-ai-dsh-client-ui-primitives/use-this-package/rendering-agent-output:
en: 4a1a61bb2d64fe4c
zh: 1b0097fff440c2ef
en: 12fe9d9b1410edef
zh: f2dfdc01170d7cce
/deepseek-ai-dsh-client-ui-primitives/use-this-package/localizing-copy:
en: 4aef65dea11de083
zh: abc22cd7c65cdf38
+2 -1
View File
@@ -66,6 +66,7 @@ Check this table before writing a control in a feature package. A plugin cannot
| `SettingsFormModel`, `settingsNumberField`, `settingsTextField` | The staged-edit model behind such a page over a settings scope: drafts are staged and written on save, a field is overridden by its presence in the user layer, and a save that did not land keeps its drafts. |
| `JsonTree`, `JsonBlock` | Read-only JSON inspection. |
| `MarkdownText`, `MarkdownDelegateProvider`, `CodeBlock` | Untrusted GFM with TeX math, owner-delegated HTTP(S) navigation, and highlighted code. `CodeBlock` accepts opt-in `lineNumbers`; copied source excludes the gutter, and `contentRef` exposes its stable source wrapper to an owner that uses it as a scrollport. Set `showHeader={false}` when the owner supplies its own language and copy toolbar. |
| `UserTextRun`, `ReferenceChip` | Uninterpreted inline text and business-resolved reference labels or activation buttons. |
| `CommandText` | Selectable command or argument text; only horizontal overflow adds a named keyboard focus target. |
| `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, `WebBlock` | The agent-output card matching each tool-result intent. |
| `icons/*`, `FishLogo`, `BrandWordmark`, `ReferenceIconRegular`/`ReferenceIconMedium`, `LinkIconRegular`/`LinkIconMedium` | Glyphs and brand marks. The thinking glyph keeps an inset orbit within its 16px view box. Use `LinkIconMedium` for 14px clickable-link categories and known-site marks. |
@@ -96,7 +97,7 @@ The catalog above lists what each export is for; this section covers the behavio
The nearest `MarkdownDelegateProvider` supplies optional `openExternalLink` and `openFile` navigation callbacks. Nested providers replace the enclosing capabilities, and callback changes reach already-rendered links without rebuilding Markdown. Its `openFile` makes local Markdown links clickable after settlement. Absolute and workspace-relative paths support percent escapes and `#L24` / `#L24-L30` fragments; ranges open at their first line. Literal `?` and `#` in filenames must be percent-encoded. The tooltip uses the decoded path and supplies the accessible name when the label is empty. The callback receives the decoded path and optional line, while the renderer preserves the label and displays a file icon. Without a callback, local links remain text. URL schemes, queries, unsupported fragments, and malformed destinations never reach the file opener.
`MarkdownText` renders untrusted GFM and TeX math, blocks unsafe links and images, and can turn resolved file mentions into explicit controls. A surrounding `MarkdownDelegateProvider` receives sanitized HTTP(S) URLs from ordinary clicks; modified clicks and links outside a provider retain native external-anchor behavior. When the owner passes a `pathImages` vocabulary, image destinations that are local media paths rewrite to displayable URLs on settled renders only (the same streaming gate as file mentions); without a vocabulary, local destinations remain inert alt text. Rewritten images accept HTTP(S), data, blob, and the Desktop `dsh-app://app/api/file` route; authored Desktop URLs remain inert. A load or decode failure replaces the image with its authored alt text, or the original destination when alt is empty; `fileImages` additionally supplies a localized failure prefix. Changing the image source permits a fresh load. While a reply streams, it freezes completed blocks, advances a top-level open fence by completed lines, and highlights that fence from saved Shiki grammar state. Completed token lines enter fixed-size React groups, so later chunks reconcile only the growing group; an unchanged fence retains that DOM when the final full parse resolves cross-document syntax. `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, and `WebBlock` render the matching tool-result intent with copy controls, overflow handling, and ANSI processing where applicable. `JsonTree` and `JsonBlock` inspect JSON values read-only, while `projectUserText` projects sent user text into inline plain runs and reference chips for the message bubble and queue rows. Reference labels inherit the consumer’s wrapping policy: long names wrap within a bubble, while queue previews retain their single-line layout. When supplied with `UserTextReferences`, file and skill references become keyboard-accessible preview buttons using the same hover and focus styling as prose file links; the first pointer click can open a preview, while subsequent clicks and existing text selections retain native selection handling. Keyboard activation opens previews even when text is selected.
`MarkdownText` renders untrusted GFM and TeX math, blocks unsafe links and images, and can turn resolved file mentions into explicit controls. A surrounding `MarkdownDelegateProvider` receives sanitized HTTP(S) URLs from ordinary clicks; modified clicks and links outside a provider retain native external-anchor behavior. When the owner passes a `pathImages` vocabulary, image destinations that are local media paths rewrite to displayable URLs on settled renders only (the same streaming gate as file mentions); without a vocabulary, local destinations remain inert alt text. Rewritten images accept HTTP(S), data, blob, and the Desktop `dsh-app://app/api/file` route; authored Desktop URLs remain inert. A load or decode failure replaces the image with its authored alt text, or the original destination when alt is empty; `fileImages` additionally supplies a localized failure prefix. Changing the image source permits a fresh load. While a reply streams, it freezes completed blocks, advances a top-level open fence by completed lines, and highlights that fence from saved Shiki grammar state. Completed token lines enter fixed-size React groups, so later chunks reconcile only the growing group; an unchanged fence retains that DOM when the final full parse resolves cross-document syntax. `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, and `WebBlock` render the matching tool-result intent with copy controls, overflow handling, and ANSI processing where applicable. `JsonTree` and `JsonBlock` inspect JSON values read-only, while `UserTextRun` renders uninterpreted text and `ReferenceChip` renders business-resolved labels. An explicit `onActivate` makes a chip a keyboard-accessible button; repeated pointer clicks and an existing text selection do not activate it, while keyboard activation remains available. Labels inherit their host’s wrapping policy. Recognition and JSON transforms belong to [ui-conversation](../ui-conversation/README.md#sent-user-text).
`MarkdownText` defaults to `variant="body"`. Use `variant="compact"` for secondary content: its 13px text and 20px line height follow the content-size setting, all heading levels use the same size with weight 600, and paragraphs and lists use tighter spacing. Text, links, and code keep the tertiary color; dotted underlines distinguish links. Code headers scroll with their blocks. Tables and math stay enabled at the surrounding text size and scroll horizontally within the available width. Both variants share the parser and streaming cache.
+2 -1
View File
@@ -66,6 +66,7 @@ kind: "package-library"
| `SettingsFormModel`、`settingsNumberField`、`settingsTextField` | 这类页面背后基于设置 scope 的暂存编辑模型:草稿先暂存、保存时写入,字段是否被覆盖看用户层是否含有它,未落地的保存保留草稿。 |
| `JsonTree`、`JsonBlock` | 只读 JSON 查看。 |
| `MarkdownText`、`MarkdownDelegateProvider`、`CodeBlock` | 不可信 GFM 与 TeX 数学、owner 委托的 HTTP(S) 导航,以及高亮代码。`CodeBlock` 可通过 `lineNumbers` 开启行号;复制的源码不含行号栏,`contentRef` 则向需要把稳定源码包装节点用作滚动区的 owner 提供该节点。调用方提供自己的语言与复制工具栏时,设置 `showHeader={false}`。 |
| `UserTextRun`、`ReferenceChip` | 不做解析的行内文本,以及业务已解析的引用标签或激活按钮。 |
| `CommandText` | 可选中的命令或参数文本;仅横向溢出时添加具名的键盘聚焦目标。 |
| `TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock`、`WebBlock` | 与各类工具结果意图对应的 agent 输出卡片。 |
| `icons/*`、`FishLogo`、`BrandWordmark`、`ReferenceIconRegular`/`ReferenceIconMedium`、`LinkIconRegular`/`LinkIconMedium` | 字形与品牌标识。思考图标的轨道在 16px 视口内保留内边距。`LinkIconMedium` 用于 14px 的可点击链接分类及已知站点标记。 |
@@ -96,7 +97,7 @@ kind: "package-library"
最近的 `MarkdownDelegateProvider` 提供可选的 `openExternalLink` 和 `openFile` 导航回调。嵌套 Provider 替换外层能力,回调变化无需重新构建 Markdown 即可到达已渲染链接。其 `openFile` 使本地 Markdown 链接在落定后可点击。绝对路径和工作区相对路径支持百分号转义以及 `#L24` / `#L24-L30` 片段;范围定位到起始行。文件名中的字面 `?` 和 `#` 必须百分号编码。悬停提示使用解码后的路径,并在标签为空时提供可访问名称。回调接收解码后的路径和可选行号,渲染器保留标签并显示文件图标。不传回调时,本地链接仍为文本。URL 协议、查询串、不支持的片段及格式错误的目标不会传给文件打开器。
`MarkdownText` 渲染不可信的 GFM 与 TeX 公式、阻止不安全的链接与图片,并可把已解析的文件提及转换为显式控件。外层 `MarkdownDelegateProvider` 会接收普通点击产生的已净化 HTTP(S) URL;带修饰键的点击和 Provider 外的链接保留原生外部 anchor 行为。当 owner 传入 `pathImages` 词表时,本地媒体路径的图片目标只在落定渲染阶段重写为可展示 URL(与 file mentions 相同的流式门);不传词表时本地目标保持惰性 alt 文本。重写后的图片支持 HTTP(S)、data、blob 及桌面端 `dsh-app://app/api/file` 路由;正文直接书写的桌面端 URL 仍保持惰性。加载或解码失败后,图片替换为作者的 alt 文本;alt 为空时显示原始目标路径;`fileImages` 还提供本地化的失败提示前缀。图片源变化后可重新加载。回复流式输出时,它冻结已完成的块、按已完成行推进顶层未闭合 fence,并从保存的 Shiki grammar state 为该 fence 增量高亮。已完成的 token 行进入固定大小的 React 分组,后续分片只 reconcile 正在增长的分组;最终全量解析解决跨文档语法时,未变化的 fence 会保留该 DOM。`TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock` 与 `WebBlock` 把对应的工具结果意图渲染为带复制控件、溢出处理及适用时 ANSI 处理的卡片。`JsonTree` 与 `JsonBlock` 以只读方式检查 JSON 值;`projectUserText` 把已发送的用户文本投影为行内普通文本段与引用 chip,供消息气泡和排队行使用。引用名称继承调用方的换行规则:长名称在气泡内换行,排队预览保持单行布局。传入 `UserTextReferences` 时,文件和 skill 引用成为支持键盘操作的预览按钮,复用正文文件链接的悬停和聚焦样式;第一次指针点击可以打开预览,后续点击和已有选区保留原生选择行为。键盘激活在存在选区时仍可打开预览。
`MarkdownText` 渲染不可信的 GFM 与 TeX 公式、阻止不安全的链接与图片,并可把已解析的文件提及转换为显式控件。外层 `MarkdownDelegateProvider` 会接收普通点击产生的已净化 HTTP(S) URL;带修饰键的点击和 Provider 外的链接保留原生外部 anchor 行为。当 owner 传入 `pathImages` 词表时,本地媒体路径的图片目标只在落定渲染阶段重写为可展示 URL(与 file mentions 相同的流式门);不传词表时本地目标保持惰性 alt 文本。重写后的图片支持 HTTP(S)、data、blob 及桌面端 `dsh-app://app/api/file` 路由;正文直接书写的桌面端 URL 仍保持惰性。加载或解码失败后,图片替换为作者的 alt 文本;alt 为空时显示原始目标路径;`fileImages` 还提供本地化的失败提示前缀。图片源变化后可重新加载。回复流式输出时,它冻结已完成的块、按已完成行推进顶层未闭合 fence,并从保存的 Shiki grammar state 为该 fence 增量高亮。已完成的 token 行进入固定大小的 React 分组,后续分片只 reconcile 正在增长的分组;最终全量解析解决跨文档语法时,未变化的 fence 会保留该 DOM。`TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock` 与 `WebBlock` 把对应的工具结果意图渲染为带复制控件、溢出处理及适用时 ANSI 处理的卡片。`JsonTree` 与 `JsonBlock` 以只读方式检查 JSON 值;`UserTextRun` 渲染不做解析的文本,`ReferenceChip` 渲染业务已解析的标签。显式传入 `onActivate` 后,胶囊成为可由键盘操作的按钮;重复指针点击和已有文本选区不触发激活,键盘激活仍然可用。标签继承所属容器的换行规则。识别和 JSON 变换由 [ui-conversation](../ui-conversation/README.zh.md#sent-user-text) 负责。
`MarkdownText` 默认为 `variant="body"`。次级内容使用 `variant="compact"`:其 13px 字号与 20px 行高跟随内容字号设置,各级标题保持同一字号并使用 600 字重,段落与列表采用更紧凑的间距。正文、链接和代码均保持 tertiary 颜色,以点状下划线区分链接。代码标题栏随代码块滚动。表格和公式仍然启用,使用周围文字的字号,并在可用宽度内横向滚动。两个变体共享解析器与流式缓存。
@@ -30,8 +30,8 @@
en: 6c77da1e946f72e1
zh: b7b8e1e1d4f5a102
/deepseek-ai-dsh-client-ui-reference/understand-the-implementation/serialization:
en: dce929ccd4f0e349
zh: e68bc0f79e184057
en: c338427c3fc3a663
zh: 3daebd32b2196efa
/deepseek-ai-dsh-client-ui-reference/further-exploration:
en: 157b1bcf84b5c11b
zh: 6b7e4f3326b19036
+2
View File
@@ -59,6 +59,8 @@ Candidate requests require an existing retained Client Session and share one tem
File picks preserve the natural text defined by the shared `@path` grammar as the hidden serialized and clipboard form. Session picks use the canonical `@[label](dsh-session:…)` mention; serialization never reconstructs identity from the visible title.
The plugin also registers file and folder transforms with [UserText](../ui-conversation/README.md#sent-user-text) and owns their `conversation.user.text.node` renderers. Matching uses remaining Text segments without file discovery. Interactive file nodes receive a Session-bound `openFile` injection; navigation failures keep the reference visible and offer a local retry/close dialog. Folder nodes remain labels.
</details>
-----
@@ -59,6 +59,8 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话
文件选择把共享 `@path` 语法所定义的自然文本保留为隐藏的序列化与剪贴板形式。会话选择使用规范的 `@[label](dsh-session:…)` mention;序列化永远不会根据可见标题重建身份。
插件还向 [UserText](../ui-conversation/README.zh.md#sent-user-text) 注册文件和目录变换,并拥有它们的 `conversation.user.text.node` renderer。匹配使用剩余 Text 分段,不执行文件发现。可交互的文件节点通过 Injection 接收绑定 Session 的 `openFile`;导航失败时保留引用,提供局部重试/关闭对话框。目录节点仍为标签。
</details>
-----
@@ -0,0 +1,123 @@
// @vitest-environment jsdom
import { useState, type ReactNode } from 'react'
import { act, cleanup, fireEvent } from '@testing-library/react'
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime'
import type { PropsRenderFactories, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface SlotMap {
'spec.inline.single': { kind: 'single'; scope: 'root'; inline: true }
'spec.inline.keyed': { kind: 'keyed'; scope: 'root'; inline: true }
'spec.inline.list': { kind: 'list'; scope: 'root'; inline: true }
'spec.inline.chain': { kind: 'chain'; scope: 'root'; inline: true; owner: { enabled: boolean } }
'spec.inline.child': { kind: 'single'; scope: 'root'; inline: true }
'spec.inline.block': { kind: 'single'; scope: 'root' }
}
interface SlotFactoryMap {
'spec.inline.factory': {
scope: 'root'
children: { 'spec.inline.child': { kind: 'single'; scope: 'root'; inline: true } }
}
}
}
afterEach(cleanup)
async function setup() {
const runtime = await SlotTestRuntime.create()
onTestFinished(() => runtime.dispose())
return runtime
}
function Crashed(): never {
throw new Error('inline entry failed')
}
describe('inline Slot anchors', () => {
it('keeps inline anchors and exhausted cells as spans while ordinary Slots remain divs', async () => {
const runtime = await setup()
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
onTestFinished(() => { error.mockRestore() })
await runtime.root.declare({
'spec.inline.single': { kind: 'single', scope: 'root', inline: true },
'spec.inline.keyed': { kind: 'keyed', scope: 'root', inline: true },
'spec.inline.list': { kind: 'list', scope: 'root', inline: true },
'spec.inline.block': { kind: 'single', scope: 'root' },
}, ({ renderSlot }) => <>
{renderSlot('spec.inline.single', {})}
{renderSlot('spec.inline.keyed', {}, { entryKey: 'failed' })}
{renderSlot('spec.inline.list', {})}
{renderSlot('spec.inline.block', {}, { fallback: <span>Ordinary fallback</span> })}
</>)
runtime.slots.register({ name: 'spec.inline.single' }, Crashed)
runtime.slots.register({ name: 'spec.inline.keyed', key: 'failed' }, Crashed)
runtime.slots.register({ name: 'spec.inline.list', id: 'failed' }, Crashed)
const view = runtime.renderRoot()
await act(async () => {})
for (const name of ['spec.inline.single', 'spec.inline.keyed', 'spec.inline.list'] as const) {
const anchor = view.container.querySelector(`[data-slot="${name}"]`)
expect(anchor?.tagName).toBe('SPAN')
expect(anchor?.querySelector('[data-slot-error]')?.tagName).toBe('SPAN')
expect(runtime.slots.entries(name)).toHaveLength(1)
}
expect(view.container.querySelector('[data-slot="spec.inline.block"]')?.tagName).toBe('DIV')
expect(view.getByText('Ordinary fallback')).toBeTruthy()
})
it('uses span overlay fallbacks and span error boundaries for inline chains', async () => {
const runtime = await setup()
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
onTestFinished(() => { error.mockRestore() })
await runtime.root.declare({
'spec.inline.chain': { kind: 'chain', scope: 'root', inline: true },
}, ({ renderSlotChain }) => {
const [enabled, setEnabled] = useState(false)
return <>
<button onClick={() => { setEnabled(true) }}>Enable</button>
{renderSlotChain('spec.inline.chain', { enabled }, {
fallback: <span>Fallback</span>, overlay: true, fallbackOnly: !enabled,
})}
</>
})
runtime.slots.register({ name: 'spec.inline.chain', select: ({ enabled }) => enabled ? {} : null }, Crashed)
const view = runtime.renderRoot()
const fallback = view.container.querySelector<HTMLElement>('[data-chain-overlay-fallback]')!
expect(fallback.tagName).toBe('SPAN')
expect(fallback.style.display).toBe('contents')
fireEvent.click(view.getByRole('button', { name: 'Enable' }))
expect(view.container.querySelector('[data-chain-overlay-fallback]')).toBe(fallback)
expect(fallback.style.display).toBe('none')
expect(view.container.querySelector('[data-slot-error="spec.inline.chain"]')?.tagName).toBe('SPAN')
})
it('retains the inline child anchor after its Factory declaration is disposed', async () => {
const runtime = await setup()
let retained: ReactNode = null
const dispose = runtime.slots.registerFactory({
name: 'spec.inline.factory', scope: 'root',
children: { 'spec.inline.child': { kind: 'single', scope: 'root', inline: true } },
}, ({ renderSlot }) => {
retained = renderSlot('spec.inline.child', {}, { fallback: <span>Child fallback</span> })
return retained
})
runtime.slots.register({ name: 'spec.inline.child' }, () => <span>Child</span>)
await runtime.root.declare({}, ({ renderFactorySlot }: PropsRuntime<'root'> & PropsRenderFactories) => {
const [hold, setHold] = useState(false)
return <>
<button onClick={() => { setHold(true) }}>Retain child</button>
{hold ? retained : renderFactorySlot('spec.inline.factory', {})}
</>
})
const view = runtime.renderRoot()
expect(view.getByText('Child')).toBeTruthy()
fireEvent.click(view.getByRole('button', { name: 'Retain child' }))
const anchor = view.container.querySelector('[data-slot="spec.inline.child"]')!
expect(anchor.tagName).toBe('SPAN')
await act(async () => { dispose() })
expect(view.container.querySelector('[data-slot="spec.inline.child"]')).toBe(anchor)
expect(anchor.textContent).toBe('')
expect(view.queryByText('Child fallback')).toBeNull()
expect(runtime.slots.entries('spec.inline.child')).toHaveLength(0)
})
})
+2 -2
View File
@@ -30,8 +30,8 @@
en: 1a02a85859f851c7
zh: 03bd48b83c4a287c
/deepseek-ai-dsh-client-ui-skill/understand-the-implementation/registration:
en: 1965ad3169b7fd97
zh: efc23c44ad1d2765
en: 6e01df075135fb40
zh: 24037d36b732191f
/deepseek-ai-dsh-client-ui-skill/further-exploration:
en: 54198f095d0cc569
zh: 4eba4413e159967b
+2
View File
@@ -59,6 +59,8 @@ Each catalog fetch requires an existing retained Client Session and waits for it
The `/client` exports are the plugin body (`apply`/`inject`) only; the source object is internal to the registration effect. The tool row registers the `skill` wire name in ui-tool's keyed `tool.call.toolview` slot.
For sent text, the plugin registers a UserText transform that reads caller-confirmed `skillNames` and owns the `skill` entry in `conversation.user.text.node`. The renderer receives `openSkill` from its own Session-bound injection and delegates to this source’s preview operation, not to Chat owner props. Non-interactive previews remain labels. [UserText](../ui-conversation/README.md#sent-user-text) owns evaluation and node dispatch.
</details>
-----
+2
View File
@@ -59,6 +59,8 @@ source 不实现任何裁决钩子,也没有引用 codec:pick 落下字面
`/client` 导出接口只有插件主体(`apply`/`inject`);source 对象是注册 effect 的内部实现。工具行把 `skill` wire 名称注册进 ui-tool 的 keyed `tool.call.toolview` slot。
对于已发送文本,插件注册读取调用方已确认 `skillNames` 的 UserText 变换,并拥有 `conversation.user.text.node` 中的 `skill` 条目。renderer 从自身绑定 Session 的 Injection 接收 `openSkill`,委托本 source 的预览操作,而非 Chat owner props。不可交互的预览仍为标签。[UserText](../ui-conversation/README.zh.md#sent-user-text) 拥有求值与节点分发。
</details>
-----
@@ -1710,12 +1710,11 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
'useProjection: UseProjection',
'useTrajectory: UseTrajectory',
],
keyDomain: 'fixed by the owner\'s key table { [Id in UserTextId]: { node: UserTextNode<Id> } }, already taken: attachment, command, file, folder, session, skill, text',
keyDomain: 'fixed by the owner\'s key table { [Id in UserTextId]: { node: UserTextNode<Id> } }, already taken: command, file, folder, session, skill, text',
hookContext: '',
slotInject: '',
declaredBy: 'factory \'conversation.user.text\' (client-ui-conversation), so it exists while that definition is registered',
occupants: [
'client-ui-attachment AttachmentReference key \'attachment\'',
'client-ui-conversation PlainUserText key \'text\'',
'client-ui-conversation SessionReference key \'session\'',
'client-ui-goal GoalCommandReference key \'command\'',