feat: merge dsh-better-display reading view into dsh-better-chat

One package, one Web client artifact (id dsh-better-chat) now ships both the reader view and the chat enhancements (approval Enter/Esc, permission UI, plugin-store update button).

- vendor dsh-better-display 0.3.12 sources, docs, skills and tests; host entry is src/host.ts, client entry src/client/index.tsx -> reader-plugin.tsx
- switch the build to tsdown with the dshx 0.9.7 client bundle adapter vendored under tools/; target platform table pinned to dsh-v0.2.2-rc.2
- keep Safari -webkit-backdrop-filter in the built reader CSS
- port chat tests to vitest (tests/chat); re-baseline the upstream reader suite on the merged layout
- bump to 0.4.0 and document the merge, provenance and toolchain
This commit is contained in:
QQ 2026-11-12 21:54:14 +08:00
parent e3b27d98f8
commit 1b3bb75a0f
184 changed files with 78599 additions and 1043 deletions

2
.gitignore vendored
View File

@ -1,3 +1,5 @@
node_modules/
*.log
.DS_Store
.pnpm-store/
.build-spike/

View File

@ -1,5 +1,16 @@
# Changelog
## 0.4.0 — 2026-11-12
- 合并 **dsh-better-display 0.3.12** 的阅读视图:源码、样式、文档、技能包、设置页与
上游测试全部并入本仓库。单包、单 Web 客户端产物(id `dsh-better-chat`),一个插件
同时提供阅读页和聊天增强。
- 构建切换到 tsdown + dshx 0.9.7 的客户端打包适配器(`tools/client-build.js`);目标
DSH 平台模块表固定为随仓库的 dsh-v0.2.2-rc.2 副本,可用 `DSHX_HARNESS` 覆盖。
- 阅读视图 CSS 构建固定 Safari 15.4 targets,保留 `-webkit-backdrop-filter` 回退。
- 聊天增强保持不变:审批回车批准 / Esc 拒绝、权限 UI(移除完全权限)、插件商店
「更新」按钮。测试迁到 vitest(`tests/chat/`),阅读视图上游套件按新包结构重新基线。
## 0.3.1 — 2026-11-12
- 权限策略只保留「界面移除完全权限」:删除页面加载/刷新/插件重载时遍历已有会话并执行 `/permission auto` 的行为。已有会话的只读、工作区修改、完全权限选择不再被插件覆盖;默认值交给宿主的新建会话流程。新增回归测试覆盖两次挂载均无权限命令。

112
DESIGN.md Normal file
View File

@ -0,0 +1,112 @@
# Display contract
## Purpose
Keep native DeepSeek Harness process information readable while separating the final answer after a successful turn. The reading view is a presentation of the public session projection, never a second Agent pipeline.
## Content fidelity
- Preserve literal reasoning text, whitespace, source order and block identity. An opt-in display transformer may paint different glyphs; it does not change the stored block. With no transformer installed, the painted text stays literal.
- Do not infer reasoning from wording, parse private provider logs, rewrite prompts or alter model settings.
- Preserve native context sources, tool types, summaries, filenames, details and results.
- Preserve the native conversation, input, model selector and approval system.
- Leave nontext and unknown content available through native renderers or a safe fallback.
## Lifecycle
During a turn, show its real process in chronological order. Starting body output, preparing tool input, finishing one tool, or entering another step is not whole-turn completion.
Only a successful public turn-close boundary folds process, leaving the final answer in place. Failures, interruptions, unknown terminal states and approval requests remain visible. A live text selection defers folding until the selection is released. A historical turn can always be reopened.
## Narration is never folded (2026-10-20)
Assistant narration — the body segments a step emits between reasoning and tool calls, including text, images and future block kinds — is display content, not process detail. It is ordinary body prose, never annotation chrome. It is always rendered in source order:
- Collapsing process hides reasoning cards, tool calls, context rows and other process records; it never hides, truncates or dims narration.
- Expanding process inserts those records back between the narration segments exactly where they occurred. Narration does not move, duplicate or become an answer card.
- Narration uses the normal body typography and keeps no left rule of its own. When collapsed process sat between two narration blocks, a compact process-chain summary (1px rail on the shared `--reader-rail` edge + `思考×N · 工具×K` label + chevron, 12px tertiary) occupies the gap; it counts only the rows folded between those blocks and expands them in place when clicked. If a live-fold cell already contains every one of those rows, the seam is omitted. Omitting it does not mark the previous narration with `data-reader-seam-after`, so that body keeps its bottom spacing.
- A step that carries body blocks no longer advertises process content on that basis; only literal reasoning does.
- Fold summaries count thinking, tools and records; narration is not counted as `输出×N` and never appears inside a fold box.
- During a live turn, a later reasoning step collapses every earlier reasoning/tool run in its own position, even across narration blocks; the latest thinking and everything after it stay open, and narration itself is never folded or moved.
- Auto-fold off, failure, interruption, unknown terminals and selection protection keep their existing behavior.
While a turn is still open, a later reasoning step may collapse each earlier reasoning/tool run into its own disclosure at that run's source position. Narration stays outside those disclosures. Body or tool alone never triggers that live fold. A mid-turn user insert or steering message resets the chain, so reasoning after the insert does not fold steps before it. This is presentation-only and does not change the successful-turn final-answer fold. The live-fold cell is the only summary of a run it covers; the between-narration seam is not a second copy of that cell.
## Long reasoning
A neutral card bounds the transcript without replacing it. The viewport mask is 28px. Follow advances by two actual line heights every 840ms, with a 500ms transform using `cubic-bezier(.22,1,.36,1)`; clamp only at the current real end. Never accelerate through a burst, clone the transcript or loop old text.
Expanding changes viewport size and preserves position and follow state. Wheel, touch, viewport focus or selection pause following. The explicit follow control resumes only when no text is selected. Completed history stays static. The full source text remains available.
## Text and status motion
Assign reveal times from source positions before rendering Markdown. Only newly appended text receives opacity/blur motion; existing paragraphs, page surfaces and text color do not animate. Unicode graphemes and punctuation keep their source order. Media and custom blocks do not enter the text queue.
Busy labels use a 2-second glyph-only shimmer and a short state swap. Initial, busy and elapsed labels all use the native font at 14px/24px, weight 400. The disclosure arrow sits 6px from the current label; no longest-state spacer. Elapsed time and attention states do not shimmer.
## Sticky reading lanes (2026-09-16)
Keep the existing in-flow positions. The auto-fold control receives a full-column, 40px-minimum lane from initial render, native page background and seamless spacing, without divider lines or replacement shadows (user preference). The status retains its source position and shares the top lane's left side only when it reaches the scrollport top. The original summary row (never a duplicate) sticks below the greater measured toolbar/status height. Expanded and collapsed live summaries remain discoverable; completed summaries obey the same sticky offset. Scope is the current flow/turn, so subsequent turns replace earlier statistics rather than displaying unrelated counts forever.
Taste checkpoint: native reading chrome, not floating badges; one column, no new card family, no shadows or rounded background tiles; existing typography. Active responsive-interaction binding: real ResizeObserver lane geometry → StickyLane + CSS offsets → verify desktop/320px, wrapped statistics, no overlap, and return to original position on reverse scroll. Preserve prior measured fold choreography and zero-height empty wrappers.
## Reading and accessibility
Manual reading, selection and keyboard access take precedence over automatic following. Reduced-motion preferences, disabled motion and background views settle to the received content. Errors stay local to their block. Do not turn user interaction into a permanent lock that prevents successful-turn folding.
## Extensions and safety
Trusted plugins may register `dsh-better-display.block`. Native content remains the fallback. Generative MCP Apps (SEP-1865 / `io.modelcontextprotocol/ui`) are supported via an isolated, sandboxed iframe (`sandbox="allow-scripts allow-forms"`, strictly without `allow-same-origin`) communicating via bidirectional JSON-RPC `postMessage` (`ui/initialize`, `ui/resize`, `ui/update-model-context`, `ui/submit`).
### Block chain owner
`renderSlotChain('dsh-better-display.block', owner)` passes the session block plus the display inputs the Reader already has. The original fields stay `block`, `streaming`, and `source`. These are added and may be omitted by an older caller:
| Field | Meaning |
| --- | --- |
| `presentation.startedAt` | Assistant step time, when the Reader has one. |
| `presentation.interrupted` | This step was interrupted. |
| `presentation.liveText` | This block may run the live reveal. |
| `holdFormatting` | A text selection is holding Markdown formatting in place. |
| `liveText` | Same boolean as `presentation.liveText`. |
A registrant that only reads `block`, `streaming`, and `source` keeps working. Replacing the chain still means that registrant draws the block. The fallback Reader keeps reveal, follow-scroll, and fold. The full shape and a copy-paste plugin are in [docs/extension-points.md](docs/extension-points.md).
### Display text transform
Service name: `dsh-better-display.text-transform`. Another client plugin lists that name in `inject` and registers a transformer. Kinds are `reasoning` (the thinking card) and `body` (assistant Markdown, and tool prose that uses the same reader). The request is `{ text, streaming, blockKey, kind, source }`. `read` may return a string, `{ text, final }`, or `undefined` to keep the source. `subscribe` tells the reader that a later batch changed what `read` will return.
No registrant means the reader never calls `read` and never subscribes. Painted text, reveal, and fold stay as they are.
The transformer is display-only. It must not write the session, the transcript, or the block object. Copy answer and copy message read the original blocks. Fold still follows the public turn boundary and the original block list.
`final: false` keeps the live reveal open, including after the model has stopped while a batch is still out. A transformer that returns `final: !streaming` leaves the reveal flag unchanged.
Each displayed string has its own `transformRevision`. That counter is not the reveal clock. The reveal continues when the new display string extends the previous one, so a translated batch that only appends does not replay the fade from the first character. A string that does not extend the previous one settles in place instead of typing again from empty. Plugins that want the fade to continue should return a string that starts with the previous display string. Do not use `transformRevision` as a React key or as the word-timeline revision.
Register during plugin apply, before the reading view paints. A transformer registered mid-turn is picked up on the next reader render.
## Host DOM hooks
Reader replaces ChatView's message list, not the native conversation chrome. The enclosing `[data-conversation-scroll]` and sticky `[data-composer-seat]` stay host-owned. ChatView marks its column with `data-chat-flow=""`. Third-party skins (maid-atelier, phoebe-atelier, and others) treat a scrollport without that hook as inspect-only and hide the composer. Reader keeps the same empty `data-chat-flow` attribute on its column so those skins still see an interactive conversation. Turns stay on `[data-reader-turn]`; Reader does not emit native `[data-chat-flow-kind]` rows.
## Fold choreography contract (2026-09-16)
Single-agent implementation; preserve existing type, colors, source order and one-column reading layout. The memory cue is causality, not ornament: shrink → count → pause → continue. No bouncing capsule, scale-squashed text or parallel entrance spectacle.
| Active reference | Decision | Target | Verification |
| --- | --- | --- | --- |
| motion-language | One attention owner; bounded coalescing instead of replaying every arrival | ChoreographedFlow | fast/slow/burst frame samples |
| motion-contract | Preserve step parents/keys until shrink completes; freeze a materialized public snapshot | fold-choreography + ChoreographedFlow | DOM identity, intermediate heights, ordered phases |
| responsive-interaction | Controls stay usable; labels receive available width, not an arbitrary narrow box | Reader.module.css | wide/narrow/200% text checks |
| typography-system | Keep native 14/24 status type; full short labels; wrap exceptional long labels | StatusText CSS | actual range vs container bounds |
Motion id: `fold-choreography`. Trigger: newly received reasoning folds a previously visible chain. Historical mount is static. Native WAAPI animates measured layout height for 320ms (deliberate layout exception needed for real flow continuity), then counters roll for 160ms, then 80ms stillness, then 180ms content reveal. New data coalesces into one latest frame; it never restarts the active shrink. Newly released text uses the existing grapheme-safe bounded catch-up buffer. Counter values belong to committed presentation frames, not the transport clock.
A selected passage, new user message, approval, error, stop, reduced motion or hidden page bypasses the waiting queue. Manual fold controls remain interruptible. Only the reader scroll coordinator writes the outer scroll position; during measured size animation it tracks geometry rather than layering another scroll easing. Authoritative session data is never rewritten.
Rollback baseline: `.delivery/before-choreography-20260916.tgz` plus original commit `56a87bb2531e5ccb9db5d4c8a347c2f91d7e449a`; existing uncommitted fixes are included in the archive. Changed surface: existing client only, no Host restart or core edits.
## Verification
Use unit coverage for projection, lifecycle, source-ordered streaming, graphemes, Markdown and two-line stepping. Verify live Host manifest, served bundle, native process details, literal reasoning, motion, successful folding, reopening, narrow layouts and reduced motion separately. Keep private session evidence outside this repository.

91
README.en.md Normal file
View File

@ -0,0 +1,91 @@
# dsh-better-chat
Chat enhancements for DeepSeek Harness. Since v0.4.0 the **dsh-better-display
reading view** is merged in: one plugin and one Web client artifact provide the
reader tab plus the approval / permission / plugin-store improvements.
## Install
```sh
dsh plugin --profile desktop add dsh-better-chat
```
From this repository (pin a commit):
```sh
dsh plugin --profile desktop add git+https://git.qyhhh.top/DeepsSeekHarness/dsh-better-chat.git#<commit>
```
The compiled `lib/` is committed, so installation needs no build step. Fully
restart DSH afterwards.
## Feature 1: reading view (merged from dsh-better-display 0.3.12)
Adds a **阅读 / Reading** tab to the conversation: while a turn runs you see the
steps, reasoning and progress; on success the process collapses and the final
answer stays. The native conversation / trajectory views, composer, model picker,
tools and approvals remain.
- The reader column keeps the host ChatView `data-chat-flow` hook, so third-party
skins that hang the composer off that marker still show it.
- ````mcp-app` code blocks in the final answer render as interactive cards inside
`<iframe sandbox="allow-scripts allow-forms">`.
- **Better Display** settings: preview deliverables in the right sidebar, frosted
glass (off by default), auto-fold the process (on by default), and detect
whether the `generative-mcpapps` skill is installed in the host skill roots.
- Upstream design notes, extension points and runbooks live in [`docs/`](docs/).
## Feature 2: Enter approves, Esc rejects on approval cards (v0.1.0)
DSH's approval card handles Enter / Esc itself, but only when focus is already
inside the card. This plugin adds:
1. **Auto-focus**: when an approval appears and the user is not typing elsewhere,
focus moves into the card's detail region.
2. **Document-level routing**: with focus outside the card, Enter clicks
"Allow once" (never "Always allow") and Esc clicks "Reject".
It never intercepts while typing, when focus is inside the card, with modifier
keys / auto-repeat / IME composition, when Enter lands on another button or link,
or when the card is already answered.
## Feature 3: permission UI (v0.2.0, tightened in v0.3.1)
- Removes the "Full access / 完全权限" option from the `/permission` popup, the
composer permission menu and the settings default-permission dropdown.
UI-only: the slash command still works.
- Never rewrites existing session permissions on page load, reload or plugin
remount; the default is left to the host's new-session flow.
## Feature 4: plugin-store update button (v0.3.0)
Plugins installed from custom indexes only get an "update available" badge. This
feature adds an "Update to x.y.z" button that calls the host's own
`remote.pluginMarket` / `remote.pluginManager` to overwrite-install the exact
spec from the index. The remote services are injected by a child plugin, so the
feature silently disables itself when the experimental plugin index is off.
## Development
```sh
pnpm install
pnpm build # tsdown
pnpm test # vitest
```
- **Single artifact**: `lib/host.js` is the host entry and `lib/client.js` is the
only Web client artifact, registered as `dsh-better-chat`. The reader view and
the chat enhancements meet in `src/client/index.tsx`.
- **Toolchain**: [`tools/client-build.js`](tools/client-build.js) is the dshx
0.9.7 client bundle adapter (MIT, see third-party notices); the target DSH
platform module table is pinned in
`tools/harness/packages/client/web/src/platform.ts` (from dsh-v0.2.2-rc.2).
Set `DSHX_HARNESS` to build against another Harness checkout.
- **Tests**: `tests/chat/` covers the chat enhancements; `tests/*.test.ts` is the
upstream reading-view suite, re-baselined on the merged package layout.
## License
MIT. The reading-view source and docs come from
[dsh-better-display](https://github.com/aa2246740/dsh-better-display) (MIT); see
[`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md) and [`licenses/`](licenses/).

125
README.md
View File

@ -1,70 +1,89 @@
# dsh-better-chat
DSH 聊天增强插件。
DSH 聊天增强插件。v0.4.0 起把 **dsh-better-display 的阅读视图**合并进来:一个插件、
一个 Web 客户端产物,同时提供「阅读页」与「审批 / 权限 / 商店」增强。
## 功能一:审批时回车批准、Esc 拒绝(v0.1.0)
## 安装
DSH 官方审批卡(`@deepseek-ai/dsh-client-ui-approval`)本身就支持
Enter 批准、Esc 拒绝,但前提是**焦点先落在审批卡里**。审批弹出时焦点
通常还在对话区,回车按下去没有反应,得先拿鼠标点一下卡片。
本插件补上这一段,不改官方逻辑:
1. **自动送入焦点**:审批卡出现时,如果你没有正在别处输入,就把焦点
送进卡片的详情区,官方的回车/Esc 立即生效。
2. **全局兜底路由**:焦点不在卡片内时(比如点了别处又想作答),在
document 捕获阶段接住回车/Esc,点击卡片上的按钮。回车永远点
「允许(单次)」,不会误触「始终允许」;Esc 点「拒绝」。
防误触(与官方卡片内部规则对齐):
- 正在任何输入框/编辑区打字时不拦截;
- 焦点已在卡片内时完全交给官方处理,不重复作答;
- 带 Ctrl/Meta/Alt/Shift、长按连发、输入法组词中不拦截;
- 回车落在某个按钮/链接上时,保留那个按钮自己的行为;
- 卡片已作答或按钮禁用时不动作。
已知边界:焦点停在另一个面板的输入框里时(例如设置页搜索框),为防
误触不会抢焦点、也不会路由按键,需要先点一下审批卡——与原生行为一致。
## 安装(DSH 桌面端)
```
```sh
dsh plugin --profile desktop add dsh-better-chat
```
完全重启 DSH 后生效。本地验证:`npm test`(判定逻辑单元测试)。
从本仓库安装(钉住提交):
## 真机验收点
```sh
dsh plugin --profile desktop add git+https://git.qyhhh.top/DeepsSeekHarness/dsh-better-chat.git#<commit>
```
- 触发一次工具审批:不点鼠标,直接按回车应批准(单次)、Esc 应拒绝;
- 审批等待时在输入框打字,回车应照常发送/换行,不被劫持;
- 审批等待时点开别处按钮,回车应执行那个按钮而不是批准。
编译好的 `lib/` 已提交,安装时不需要构建。装完彻底重启 DSH。
## 功能二:权限 UI(v0.2.0,v0.3.1 收紧)
## 功能一:阅读视图(合并自 dsh-better-display 0.3.12)
- **去掉「完全权限」选项**:权限选择器(`/permission` 弹出菜单、composer
权限菜单)和通用设置的默认权限下拉里,标签为「完全权限 / Full access」
的选项会被摘除。只动界面:手动输入 `/permission danger-full-access`
命令仍可达,那是宿主行为。
- **不覆盖已有会话权限**:插件不再在页面加载、刷新或重载时遍历会话改
权限。已有会话的只读/工作区/完全权限选择完全由用户与宿主决定;默认
自动审查只属于宿主自己的新建会话流程,本插件没有可靠的新建扩展点,
因此不拿轮询补偿。需要自动审查时,请在宿主的权限选择器里显式选择。
给对话加一个 **阅读** 页签:执行时能看到步骤、思考与进度;整轮成功结束后把过程
收起来,留下最终回答。原版「对话 / 轨迹」、输入框、模型选择、工具和审批都还在。
真机验收点(功能二):
- 阅读列保留宿主 ChatView 的 `data-chat-flow` 钩子,依赖该标记显示输入框的第三方
皮肤不会把阅读页当成仅检视视图。
- 最终回答里的 ````mcp-app` 代码块会挂成交互卡片(`<iframe sandbox="allow-scripts allow-forms">`)。
- 设置里的 **Better Display**:产物右侧预览、半透明毛玻璃(默认关)、过程自动折叠
(默认开),并检测 `generative-mcpapps` 技能是否已装进宿主技能目录。
- 上游的设计说明、扩展点文档与开发 runbook 一并保留在 [`docs/`](docs/)。
1. 打开权限选择器 → 没有「完全权限」一项;设置里的默认权限下拉同样没有。
2. 手动把某个会话切到「仅可查看」→ 刷新、重连、插件重载后仍是「仅可查看」。
3. 新建会话的默认权限由宿主/用户选择决定,插件不替用户改写。
## 功能二:审批卡片的回车批准 / Esc 拒绝(v0.1.0)
## 功能三:插件商店「更新」按钮(v0.3.0)
DSH 官方审批卡本身支持 Enter 批准、Esc 拒绝,但前提是焦点先落在卡内。本插件补上:
DSH 只给官方插件原地更新;从自定义索引装的插件在发现页只有「有新版本」标签、没有按钮,只能手动卸载重装。本功能在发现页给每个「有新版本」的条目补一个「更新到 x.y.z」按钮:
1. **自动送入焦点**:审批卡出现时,若没有正在别处输入,把焦点送进卡片详情区。
2. **全局兜底路由**:焦点不在卡内时,在 document 捕获阶段接住回车 / Esc —— 回车
永远点「允许(单次)」(不会误触「始终允许」),Esc 点「拒绝」。
- 数据与动作都走宿主自己的远程服务:`remote.pluginMarket` 查各索引的安装状态与每版的精确安装 spec,`remote.pluginManager.installBundle` 按 spec 覆盖安装——与官方安装流程同一套接口,不模拟点击、不动官方状态。覆盖安装经实测可直接把已装旧版换成新版。
- 点击先弹确认框(插件名、旧版 → 新版),完成后按钮显示「已更新,重启 DSH 后生效」;失败显示「更新失败,点此重试」并把宿主错误打到控制台。
- 远程服务由一个子插件单独声明 inject 取用,主插件保持 inject 为空;未启用实验性「自定义插件索引」时子插件不生效,本功能静默关闭,审批与权限功能不受影响。
- 更新后需重启 DSH 才加载新版(与官方流程一致)。插件数据在 `$DSH_HOME` 的边车文件里,覆盖安装不影响。
防误触:正在输入控件里打字、焦点已在卡内、带修饰键 / 长按连发 / 输入法组词、
回车落在别的按钮或链接上、卡片已作答或按钮禁用时,都不拦截。
顺带修复(v0.3.0):v0.2.x 里权限策略的定时器默认值把浏览器原生 `setInterval` 等函数摘出来当普通对象方法调用,Chrome 下抛 `TypeError: Illegal invocation`,会让独立安装的客户端条目激活失败(DSH 报 “entry did not activate”、整页白屏)。已改为箭头函数包裹调用,本功能的定时器同样处理。
## 功能三:权限 UI(v0.2.0,v0.3.1 收紧)
- 去掉「完全权限 / Full access」选项:`/permission` 弹出菜单、composer 权限菜单与
通用设置的默认权限下拉里都会被摘除。只动界面,手动输入命令仍可达。
- 不覆盖已有会话权限:页面加载、刷新、插件重载都不会遍历会话改权限;默认权限交给
宿主的新建会话流程。
## 功能四:插件商店「更新」按钮(v0.3.0)
从自定义索引装的插件在发现页只有「有新版本」标签。本功能补一个「更新到 x.y.z」
按钮:数据与动作都走宿主自己的 `remote.pluginMarket` / `remote.pluginManager`,
按索引给出的精确 spec 覆盖安装,不模拟点击。远程服务由子插件单独 inject,未启用
实验性插件索引时静默关闭。
## 开发
```sh
pnpm install
pnpm build # tsdown
pnpm test # vitest
```
- **单产物**:`lib/host.js` 是宿主入口,`lib/client.js` 是唯一的 Web 客户端产物,
注册 id `dsh-better-chat`。阅读视图与聊天增强在 `src/client/index.tsx` 里合流。
- **构建工具链**:[`tools/client-build.js`](tools/client-build.js) 是 dshx 0.9.7 的
客户端打包适配器(MIT,见第三方声明);目标 DSH 的平台模块表固定为
`tools/harness/packages/client/web/src/platform.ts`(随仓库,来源 dsh-v0.2.2-rc.2)。
设置 `DSHX_HARNESS` 可改为构建到别的 Harness 版本。
- **测试**:`tests/chat/` 覆盖聊天增强;`tests/*.test.ts` 是随阅读视图一并继承的
上游套件(已按合并后的包结构重新基线)。
## 目录
```text
src/host.ts 宿主入口(reveal / skill-status / metrics 路由)
src/client/index.tsx 合并后的客户端入口
src/client/reader-plugin.tsx 阅读视图入口(原 dsh-better-display client)
src/client/chat/ 审批键盘、权限 UI、商店更新
tools/ dshx 客户端构建适配器 + 目标平台表
tests/ 聊天增强 + 阅读视图测试
```
## 许可与来源
本仓库 MIT。阅读视图源码与文档来自 [dsh-better-display](https://github.com/aa2246740/dsh-better-display)
(MIT),版权与许可全文见 [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md) 与
[`licenses/`](licenses/)。

86
THIRD_PARTY_NOTICES.md Normal file
View File

@ -0,0 +1,86 @@
# Third-party notices
The MIT license in this repository covers original plugin code. It does not
replace third-party licenses or the Transitions.dev recipe terms below.
## dsh-better-display source (reading view)
The reading view (`src/client/**`, `src/host.ts`, `docs/`, `skills/`, `DESIGN.md`
and the `tests/*.test.ts` suite) derives from **dsh-better-display 0.3.12** by
aa2246740 (<https://github.com/aa2246740/dsh-better-display>, MIT). The upstream
license text is preserved in [`licenses/dsh-better-display-LICENSE`](licenses/dsh-better-display-LICENSE).
Local changes: merged entry points (`src/client/index.tsx` and
`src/client/reader-plugin.tsx`), package name/id `dsh-better-chat`, DSH target
range widened to the 0.2.2 line, and the build toolchain below.
## dshx client build adapter
`tools/client-build.js`, `tools/core-boundary.js` and
`tools/internal/client-cordis-inject.js` come from the dshx devkit
(`dsh-external-plugin-devkit` 0.9.7, MIT, <https://github.com/liyown/dshx>).
Local changes: the target Harness platform table defaults to the vendored copy in
`tools/harness/packages/client/web/src/platform.ts` (dsh-v0.2.2-rc.2), and the
CSS transform pins Safari 15.4 targets so the reader's `-webkit-backdrop-filter`
fallback survives minification.
## Transitions.dev product-use terms
The three free recipes used in this DSH-specific display are Streaming text,
Thinking states and Reasoning stream, by Jakub Antalik / Transitions.dev.
They are incorporated into the actual conversation UI, not redistributed as a
standalone effects collection, template pack or component kit. No Pro assets,
website fonts, stock images, demo transcript or upstream CLI are included.
The upstream [Terms & License](https://transitions.dev/terms.html), last updated
July 2026 and checked on 2026-08-28, permit use, modification and shipment of
accessible recipes within personal or commercial products. They prohibit
republishing the collection or a substantial part as a competing effects
library, template pack or component kit. The upstream MIT license applies to
its tooling, **not** to the transition recipes. Retain this notice and consult
the upstream terms when redistributing or adapting the corresponding motion
portions of `Reader.module.css`, `motion.tsx` and `word-timeline.ts`.
## DeepSeek Harness native process presentation
`src/client/native` copies the native context rows, form-specific context bodies, reference icon and pure tool summary model. `upstream.json` records the source commit and each original hash. The only adaptations are public type imports, relative ESM suffixes and a local icon path. The MIT license below covers these files. No Host, model, SDK, Agent or tool execution source is included or modified.
## DeepSeek Harness Markdown renderer
`src/client/markdown` derives from DeepSeek Harness commit `b150a551b8d465e31e418e1b2eaf5e79bbb7d28e`. Changes add source-offset hooks for text leaves, literal HTML, inline code and atomic code-block entry, and keep source-offset keys on finalization. Native CodeBlock is reused through the public package API without changing its content renderer. Original file hashes are recorded in `upstream.json`.
MIT License
Copyright (c) 2026 DeepSeek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## Transitions.dev Streaming text
Motion recipe: https://github.com/Jakubantalik/transitions.dev/blob/ef497bb64867ce569689730198fc66f49db56317/cli/free/streaming-text.md
Author: Jakub Antalik. The public free recipe is presented for copying into projects. Opacity 0 to 1, blur 1px to 0, 350ms, 60ms gap and cubic-bezier(0.22,1,0.36,1) are used here. The live adapter animates only appended words rather than replaying existing paragraphs. No protected recipes were retrieved and no license for the entire upstream repository is asserted.
## Transitions.dev Thinking states
Author: Jakub Antalik. Source: the public [Thinking states recipe](https://github.com/Jakubantalik/transitions.dev/blob/ef497bb64867ce569689730198fc66f49db56317/cli/free/thinking-states.md). The scoped implementation retains its glyph-only `::before` sweep (2 seconds, 400% background), 150ms state transition, 50ms entry gap, 8px travel and 2px blur. DSH semantic colors replace fixed colors; real Host events replace the demo's timed state carousel. Hidden visual copies are excluded from accessibility, and interrupted/off/reduced/background states settle to the current label.
## Transitions.dev Reasoning stream
Author: Jakub Antalik. Source: the public [Reasoning stream recipe](https://github.com/Jakubantalik/transitions.dev/blob/ef497bb64867ce569689730198fc66f49db56317/cli/free/reasoning-stream.md). This adaptation retains the 28px viewport mask, 840ms cadence, 500ms cubic-bezier(0.22,1,0.36,1) CSS transform and fixed two-line steps, clamped only at the real transcript's current end. One real text tree replaces the demo's cloned loop. Body and tool phases do not prematurely stop the current step's motion; manual reading receives the painted offset through native scrolling, preserving selection and keyboard access. Bursts never increase the step distance. Reduced motion and closed historical turns remain static.

407
client.js
View File

@ -1,407 +0,0 @@
/**
* dsh-better-chat 客户端:让审批卡片的回车 / Esc 不再挑焦点。
*
* 背景(DSH 0.2.2-rc.1 的 @deepseek-ai/dsh-client-ui-approval):
* 官方审批卡自带键盘处理 —— Enter 批准(单次)、Esc 拒绝 —— 但它的
* keydown 挂在卡片根节点上,且要求焦点先落在卡片内。审批弹出时焦点
* 往往还在对话区/页面主体上,按回车毫无反应,必须先点一下卡片。
*
* 本模块补两件事,不改官方任何逻辑:
* 1. 审批卡出现时,若用户没有正在别处输入,把焦点送进卡片的详情区
* ([data-approval-scroll],本身 tabIndex=0),官方处理立即生效。
* 2. 焦点不在卡片内时兜底路由:在 document 捕获阶段监听 keydown,
* 满足全部防误触条件时,点击卡片操作行里的按钮 —— 顺序由官方渲染
* 固定为 [拒绝, 允许(单次), 始终允许?],回车点「允许(单次)」,
* 永远不会误触「始终允许」;Esc 点「拒绝」。
*
* 防误触(与官方卡片内部规则对齐):
* - 正在任何输入控件(input/textarea/select/contenteditable)里打字 → 不管
* - 焦点已在卡片内 → 官方处理,绝不重复作答
* - 带 Ctrl/Meta/Alt/Shift、长按连发、输入法组词中 → 不管
* - 回车落在某个按钮/链接上 → 保留那个按钮自己的回车行为
* - 卡片已作答(aria-busy=true)或按钮禁用 → 不管
*/
const CARD_SELECTOR = '[data-approval-key]'
const SCROLL_SELECTOR = '[data-approval-scroll]'
const EDITABLE_SELECTOR = 'input, textarea, select, [contenteditable="true"], [contenteditable=""]'
/** 卡片操作行的按钮:详情滚动区之外的全部按钮,顺序 [拒绝, 允许, 始终允许?]。 */
export function actionButtons(card) {
return [...card.querySelectorAll('button')].filter((b) => !b.closest(SCROLL_SELECTOR))
}
/** 找当前可作答的审批卡(DOM 顺序第一张未作答、按钮齐全的卡)。 */
export function findPendingCard(doc) {
for (const card of doc.querySelectorAll(CARD_SELECTOR)) {
if (card.getAttribute('aria-busy') === 'true') continue
const buttons = actionButtons(card)
if (buttons.length >= 2 && !buttons[0].disabled && !buttons[1].disabled) return card
}
return null
}
/**
* 纯判定:这次 keydown 是否应该路由到审批卡。
* @returns {'allow'|'reject'|null}
*/
export function decideKeyAction(input) {
const { key, ctrlKey, metaKey, altKey, shiftKey, repeat, isComposing, keyCode, defaultPrevented, target, activeElement, card } = input
if (!card) return null
if (defaultPrevented) return null
if (key !== 'Enter' && key !== 'Escape') return null
if (ctrlKey || metaKey || altKey || shiftKey) return null
if (repeat || isComposing || keyCode === 229) return null
if (activeElement && card.contains(activeElement)) return null // 焦点在卡内:官方处理
if (target && typeof target.closest === 'function') {
if (target.closest(EDITABLE_SELECTOR) !== null) return null // 正在别处输入
if (key === 'Enter' && target.closest('button, a[href], [role="button"]') !== null) return null
}
return key === 'Enter' ? 'allow' : 'reject'
}
/** 纯判定:审批卡出现时是否应该把焦点送进详情区。 */
export function shouldAutoFocus(activeElement, card) {
if (!activeElement) return true
if (activeElement === card.ownerDocument?.body) return true
if (card.contains(activeElement)) return false // 已经在卡里
if (typeof activeElement.closest === 'function' && activeElement.closest(EDITABLE_SELECTOR) !== null) return false // 正在别处输入
return true
}
function install(doc) {
const focusedCards = new WeakSet()
const tryAutoFocus = () => {
const card = findPendingCard(doc)
if (!card || focusedCards.has(card)) return
focusedCards.add(card)
if (!shouldAutoFocus(doc.activeElement, card)) return
const region = card.querySelector(SCROLL_SELECTOR)
if (region && typeof region.focus === 'function') region.focus()
}
const observer = new MutationObserver(tryAutoFocus)
observer.observe(doc.documentElement, { childList: true, subtree: true })
tryAutoFocus()
const onKeyDown = (event) => {
const card = findPendingCard(doc)
const action = decideKeyAction({
key: event.key,
ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey,
repeat: event.repeat, isComposing: event.isComposing, keyCode: event.keyCode,
defaultPrevented: event.defaultPrevented,
target: event.target, activeElement: doc.activeElement, card,
})
if (!action) return
const buttons = actionButtons(card)
const button = action === 'allow' ? buttons[1] : buttons[0]
if (!button || button.disabled) return
event.preventDefault()
event.stopPropagation()
button.click()
}
doc.addEventListener('keydown', onKeyDown, true)
return () => {
observer.disconnect()
doc.removeEventListener('keydown', onKeyDown, true)
}
}
/**
* 功能二:权限 UI —— 去掉「完全权限」选项,不改已有会话权限。
*
* 背景(DSH 0.2.2-rc.1 的权限预设,@deepseek-ai/dsh-client-ui-permission-presets):
* 会话权限有四个预设值:read-only(仅可查看)、workspace-write(工作区内
* 修改)、danger-full-access(完全权限)、auto(自动审查,EXP)。「自动
* 审查」由实验层 @deepseek-ai/dsh-experimental-auto-review 提供:开启该层
* 后才出现在当前会话的选择器里;通用设置不提供 auto,新会话默认值里
* 也选不到它。宿主切换预设的通道是会话对象的 command(`/permission <值>`),
* 带参命令直接生效、不弹风险确认。
*
* 本功能只做一件事:界面移除完全权限。它**不再**在页面加载、刷新或
* 插件重载时遍历已有会话改权限:那会把用户明确选择的只读/工作区权限
* 覆盖成 auto,而且 handled 只在内存里,刷新后会再次执行。默认权限
* 属于宿主的新建会话流程;本插件没有可靠的新建扩展点,因此不拿轮询
* 去补偿,用户仍可在宿主提供的权限选择器里自行选择自动审查。
*/
/** 完全权限的预设机器值。 */
export const FULL_ACCESS_PRESET = 'danger-full-access'
/** 自动审查的预设机器值。 */
export const AUTO_REVIEW_PRESET = 'auto'
/** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */
export const FULL_ACCESS_LABELS = ['完全权限', 'Full access']
/** 纯判定:一段选项文字是否就是「完全权限」选项(标签打头,或恰好相等)。 */
export function isFullAccessLabel(text) {
if (typeof text !== 'string') return false
const t = text.trim()
return FULL_ACCESS_LABELS.some((label) => t === label || t.startsWith(label))
}
/** 纯判定:这个会话现在是否应该被切到自动审查。 */
export function shouldAutoSwitch(preset, alreadyHandled) {
return preset !== undefined && preset !== null && preset !== AUTO_REVIEW_PRESET && !alreadyHandled
}
/**
* 防御式枚举宿主的 live 会话:优先 keys()+binding(),退回 list()。
* 服务形状对不上时安静返回空数组,绝不抛错。
*/
export function liveSessions(sessions) {
const out = []
if (!sessions || typeof sessions !== 'object') return out
try {
if (typeof sessions.keys === 'function' && typeof sessions.binding === 'function') {
for (const id of sessions.keys()) {
const live = sessions.binding(id)?.session
if (live) out.push({ id, live })
}
return out
}
if (typeof sessions.list === 'function') {
for (const s of sessions.list() ?? []) {
if (s && s.sessionId) out.push({ id: s.sessionId, live: s })
}
}
} catch { /* 服务形状不同:放弃枚举 */ }
return out
}
/** 读会话当前的权限预设值(投影不可用时返回 undefined)。 */
export function currentPreset(live) {
try {
return live?.projections?.faceOf('permissions')?.getSnapshot?.()
} catch {
return undefined
}
}
/**
* 把「完全权限」选项从当前文档里摘掉:原生 select 的 option、弹出
* 选择器(role=listbox)与菜单(role=menu)里的 option/menuitem。
* @returns 摘掉的个数
*/
export function pruneFullAccess(doc) {
let removed = 0
for (const opt of doc.querySelectorAll('option')) {
if (isFullAccessLabel(opt.textContent)) { opt.remove(); removed++ }
}
for (const item of doc.querySelectorAll('[role="listbox"] [role="option"], [role="menu"] [role="menuitem"]')) {
if (isFullAccessLabel(item.textContent)) { item.remove(); removed++ }
}
return removed
}
/**
* 安装权限 UI 策略:只观察 DOM、摘掉「完全权限」选项。
*
* 不接收 `getSessions`,也不启动任何会话轮询:页面加载、刷新和插件重载
* 都不得改变已有会话的权限。新建会话的默认值由宿主自己的新建流程决定。
* @returns 卸载函数
*/
export function installPermissionPolicy(doc, _getSessions, timers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) }) {
let disposed = false
let scanTimer = 0
const scheduleScan = () => {
if (disposed || scanTimer) return
scanTimer = timers.setTimeout(() => {
scanTimer = 0
if (!disposed) pruneFullAccess(doc)
}, 120)
}
const observer = new MutationObserver(scheduleScan)
if (doc.body) observer.observe(doc.body, { childList: true, subtree: true })
pruneFullAccess(doc)
return () => {
disposed = true
observer.disconnect()
if (scanTimer) timers.clearTimeout(scanTimer)
}
}
/* ------------------------------------------------------------------ *
* 功能三:插件商店「更新」按钮。
*
* DSH 只给官方插件原地更新;从自定义索引装的插件在发现页只有
* 「有新版本」标签、没有按钮,只能手动卸载重装。这里补一个真按钮:
* 数据与动作都走宿主自己的远程服务——pluginMarket 查索引和安装
* 状态,pluginManager.installBundle 按索引给出的精确 spec 覆盖
* 安装——与官方安装流程同一套接口,不模拟点击、不动官方状态。
* 覆盖安装在探针实测中可直接把已装旧版换成新版(changed/applied)。
*
* 服务经子插件声明 inject 取用:主插件保持 inject 为空,审批与
* 权限功能不依赖这些服务;未启用实验性插件索引时子插件不生效,
* 本功能静默关闭。
* ------------------------------------------------------------------ */
export const UPDATE_LABELS = ['有新版本', 'Update available']
/** 索引条目的本地化标题在当前语言下的文本(与发现页行内展示一致)。 */
export function localizedTitle(title, lang) {
if (typeof title === 'string') return title
if (!title || typeof title !== 'object') return ''
const chain = [lang, lang && lang.split('-')[0], 'zh-CN', 'en']
for (const key of chain) {
if (key && typeof title[key] === 'string' && title[key]) return title[key]
}
const values = Object.values(title)
return typeof values[0] === 'string' ? values[0] : ''
}
/** 从各索引的搜索结果里挑出「有新版本」的条目,整理成可执行的更新计划。 */
export function pickUpdates(searchResults, lang) {
const updates = []
for (const result of searchResults ?? []) {
const entries = result?.value?.entries ?? result?.entries ?? []
for (const entry of entries) {
if (entry?.installation?.status !== 'update-available') continue
const versions = entry.versions ?? []
const version = versions.find((v) => v.version === entry.defaultVersion) ?? versions[0]
const spec = version?.install?.spec
if (!entry.name || !version?.version || !spec) continue
updates.push({
name: entry.name,
title: localizedTitle(entry.title, lang) || entry.name,
installedVersion: entry.installation.installedVersion ?? '',
version: version.version,
spec,
registry: version.install.registry,
})
}
}
return updates
}
/** 执行一次更新:按索引 spec 覆盖安装,宿主结果信封原样返回。 */
export async function runUpdate(remote, update, makeRequestId) {
const requestId = makeRequestId ? makeRequestId() : 'better-chat-update-' + Date.now()
return remote.pluginManager.installBundle(update.spec, {
enabled: true,
requestId,
...(update.registry ? { registry: update.registry } : {}),
})
}
/**
* 发现页里某个插件的行:状态标签本身是个按钮,从它向上找第一个
* 同时包含插件标题、且文本总量还像一行的祖先。
*/
export function findUpdateRow(doc, title) {
for (const el of doc.querySelectorAll('button')) {
if (!UPDATE_LABELS.includes(el.textContent?.trim())) continue
let node = el
for (let depth = 0; depth < 6 && node; depth++) {
node = node.parentElement
if (node && node.textContent?.includes(title) && node.textContent.length < 600) return node
}
}
return null
}
/** 更新按钮的点击处理:确认 → 调宿主覆盖安装 → 按结果改按钮文案。 */
export function makeUpdateClickHandler(doc, getRemote, update, button) {
return async (event) => {
event?.preventDefault?.()
event?.stopPropagation?.()
const view = doc.defaultView
const ask = view?.confirm ?? globalThis.confirm
const message = '更新「' + update.title + '」' + (update.installedVersion ? ' ' + update.installedVersion : '') + ' → ' + update.version + '?\n会直接覆盖安装新版,插件数据保留。'
if (ask && !ask.call(view ?? globalThis, message)) return
button.disabled = true
button.textContent = '更新中…'
try {
const result = await runUpdate(getRemote(), update, () => globalThis.crypto?.randomUUID?.() ?? undefined)
if (result?.value?.application === 'applied') {
button.textContent = '已更新,重启 DSH 后生效'
} else {
console.error('[dsh-better-chat] update failed for', update.name, result?.value?.error ?? result)
button.disabled = false
button.textContent = '更新失败,点此重试'
}
} catch (error) {
console.error('[dsh-better-chat] update failed for', update.name, error)
button.disabled = false
button.textContent = '更新失败,点此重试'
}
}
}
/** 发现页增强:轮询索引状态,把「更新」按钮挂到有新版本的行上。 */
export function installStoreUpdateButtons(doc, getRemote, timers = { setInterval: (fn, ms) => setInterval(fn, ms), clearInterval: (id) => clearInterval(id) }) {
let disposed = false
let updates = []
const decorate = () => {
for (const update of updates) {
const row = findUpdateRow(doc, update.title)
if (!row || row.querySelector('[data-better-chat-update]')) continue
const button = doc.createElement('button')
button.type = 'button'
button.setAttribute('data-better-chat-update', update.name)
button.textContent = '更新到 ' + update.version
button.style.cssText = 'flex:none;margin-left:8px;padding:2px 10px;border:1px solid #7f7f7f55;border-radius:999px;background:transparent;color:inherit;font-size:12px;cursor:pointer'
button.addEventListener('click', makeUpdateClickHandler(doc, getRemote, update, button))
row.appendChild(button)
}
}
const refresh = async () => {
try {
const remote = getRemote()
if (!remote?.pluginMarket || !remote?.pluginManager) return
const indexes = await remote.pluginMarket.listIndexes()
const urls = (indexes?.value ?? indexes ?? []).map((entry) => entry?.url).filter(Boolean)
const results = []
for (const url of urls) {
results.push(await remote.pluginMarket.search(url, { sort: { kind: 'index' }, offset: 0, limit: 100 }))
}
if (disposed) return
updates = pickUpdates(results, doc.documentElement?.lang || 'zh-CN')
decorate()
} catch {
// 索引服务不可用(未启用实验性插件索引等):静默关闭本功能。
}
}
const observer = new MutationObserver(() => decorate())
observer.observe(doc.documentElement, { childList: true, subtree: true })
const timer = timers.setInterval(() => { void refresh() }, 30000)
void refresh()
return () => {
disposed = true
observer.disconnect()
timers.clearInterval(timer)
}
}
/** 商店更新子插件:单独声明远程服务 inject,与主功能互相隔离。 */
const storeUpdatePlugin = {
name: 'dsh-better-chat-store-update',
inject: ['remote', 'remote.pluginMarket', 'remote.pluginManager'],
apply(childCtx) {
childCtx.effect(
() => installStoreUpdateButtons(document, () => childCtx.remote),
'dsh-better-chat: store update buttons',
)
},
}
/** 本插件不硬依赖任何客户端服务(sessions 服务是可选增强,缺了只是不自动切)。 */
export const inject = []
/** 插件主体:挂载两组增强,卸载时完整摘除。 */
export function apply(ctx) {
ctx.effect(() => install(document), 'dsh-better-chat: approval enter/esc routing')
ctx.effect(
() => installPermissionPolicy(document),
'dsh-better-chat: permission policy (no full access)',
)
try {
ctx.plugin(storeUpdatePlugin)
} catch {
// 子插件挂不上(旧宿主等)不影响主功能。
}
}

View File

@ -1,9 +1,9 @@
# dsh-better-chat bundle patch
#
# One insert row loads the package: the host entry is a no-op stub, the
# actual feature lives in the web client (./client export, see the `dsh`
# manifest in package.json).
# One insert row loads the package: the host entry registers the reader's
# reveal/skill-status/metrics routes, and the web client (./client export,
# see the `dsh` manifest in package.json) registers the reader view plus the
# chat enhancements (approval keys, permission UI, store update buttons).
- insert:
- id: dsh-better-chat
name: 'dsh-better-chat'
config: {}
name: dsh-better-chat

View File

@ -0,0 +1,9 @@
# Dependency update policy
Wait 7 days before merging a version bump.
`renovate.json` sets `minimumReleaseAge` to `7 days`. Renovate must not treat a release as ready until that age has passed. `.github/dependabot.yml` only schedules weekly npm checks. A weekly pull request is not permission to merge a version on the day it was published. The same 7 day wait applies before merging those bumps.
Do not merge a version bump the day it is published, even when CI is green. A lockfile change that only repeats a version which is already 7 days old can merge with the bump it belongs to. It does not skip the wait, and it does not start a new one.
This policy does not point at a Dependabot or Renovate pull request. Open one only when the bot actually does.

208
docs/extension-points.md Normal file
View File

@ -0,0 +1,208 @@
# Extension points
Two seams. Both are display-only. Neither one writes the session, the transcript, or the fold input.
## `dsh-better-display.text-transform`
Cordis service, provided by this plugin's client when it applies. Another client plugin lists the name in `inject` and registers a transformer. With no registrant, the reader does not call `read` and does not subscribe.
Kinds:
| Kind | What it paints |
| --- | --- |
| `reasoning` | The thinking card (`ReadingReasoning`), before `useStreamingText`. |
| `body` | Assistant Markdown, and tool prose that uses the same reader (`ReadingMarkdown`). User bubbles are not passed through. |
Request:
```ts
interface DisplayTextRequest {
text: string;
streaming: boolean;
blockKey: string;
kind: 'reasoning' | 'body';
source?: 'assistant' | 'user' | 'tool';
}
```
`blockKey` identifies one mounted block. It changes when that block unmounts. It is not a session message id.
`read` runs on each paint and returns one of:
- `{ text, final }`
- a string, which is treated as `{ text, final: !streaming }`
- `undefined`, which keeps the source text
`final: false` keeps the live reveal open. That includes the moment after the model has stopped while a translation batch is still outstanding. Return `final: !streaming` to leave the reveal flag as it is today.
`subscribe(listener)` is how an async batch tells the reader to call `read` again. It may be invoked once per kind, so it must keep every listener. Skip it for a pure sync transform.
Revisions:
- `transformRevision` increments when the displayed string or `final` changes. It is not the reveal clock. Do not pass it to the word timeline, and do not use it as a React key. Doing either one settles or remounts the paragraph and the fade starts over.
- The reveal continues when the new display string starts with the previous display string. Already shown characters keep their birth time. Only the new tail fades in.
- A string that does not extend the previous one is a replacement. The reader shows that string in place. It does not clear the card and type from the first character.
Register during `apply`, before the reading view paints. A transformer added mid-turn is picked up on the next reader render, and that first switch mounts the reveal on the current string.
Copy answer and copy message read the original blocks (`originalAnswerText` for the answer). The native 对话 view is untouched, because this seam only runs inside the reader.
Fold still uses the original block list and the public turn boundary.
A foreign `assistant-step` renderer receives original text. That is a `conversation.chat.node` replacement whose priority is below the official renderer. Reader hands it the segment's original blocks and does not run this transform on that path. Reader markdown, including this transform, is only the fallback when the foreign renderer returns null. Reasoning stays on the reading card either way.
Import the types from `dsh-better-display/client`:
```ts
import type { DisplayTextRequest, TextTransformRegistry } from 'dsh-better-display/client';
import { TEXT_TRANSFORM_SERVICE } from 'dsh-better-display/client';
```
`createTextTransformRegistry()` builds a private registry for a unit test. A plugin that wants the reader to paint its text must register on the service the reader provides, not on a registry it constructed itself.
### Reasoning DOM marker
The reader fallback's reasoning text root (`[data-reader-text-kind="reasoning"]`) exposes `data-reader-reasoning-block-key`. Its value is the same opaque `blockKey` sent in that block's reasoning `DisplayTextRequest`. The marker is present with or without a reasoning transformer, including when a transformer returns `undefined` to keep the original text. It stays stable while that block remains mounted, including streaming growth and display-text changes; do not parse it or persist it as a session identifier.
A `ReasoningCard` can group multiple reasoning blocks. For a per-card original/translated toggle, collect **all descendant** `[data-reader-reasoning-block-key]` values and apply the display override to those exact keys through the text-transform registry. Do not assume one key per card, infer ownership from card/block order, or match original or translated text: distinct blocks may have identical text. Treat the values as opaque identifiers, not CSS selector fragments.
This marker only associates the existing reasoning display roots with transform requests. It does not change text, rendering identity, source blocks, transcript records, or the native conversation view. A foreign block-chain renderer replaces the fallback and is not guaranteed to provide this marker.
### Minimal translation-shaped plugin
This one only uppercases. A real translator keeps the same `read` / `subscribe` shape, stores each batch on `blockKey`, and returns a string that extends the previous display string when it wants the fade to continue. It leaves `source === 'tool'` alone unless tool prose should change too.
`src/client/index.ts`:
```ts
import type { Context } from '@deepseek-ai/cordis';
export const name = 'upper-reasoning-client';
export const inject = ['dsh-better-display.text-transform'];
interface Request {
text: string;
streaming: boolean;
blockKey: string;
kind: 'reasoning' | 'body';
source?: 'assistant' | 'user' | 'tool';
}
export function apply(ctx: Context): () => void {
const seam = ctx.get('dsh-better-display.text-transform') as {
register(kind: 'reasoning' | 'body' | readonly ('reasoning' | 'body')[], transformer: {
read(request: Request): { text: string; final: boolean } | undefined;
}): () => void;
} | undefined;
if (!seam) return () => {};
return seam.register(['reasoning', 'body'], {
read(request) {
if (request.source === 'tool') return undefined;
return { text: request.text.toUpperCase(), final: !request.streaming };
},
});
}
```
`package.json`:
```json
{
"name": "dsh-upper-reasoning",
"private": true,
"type": "module",
"dsh": { "client": { "platform": "web" }, "bundle": { "patch": "./cordis.patch.yml" } }
}
```
`cordis.patch.yml`:
```yaml
- insert:
- id: dsh-upper-reasoning
name: dsh-upper-reasoning
```
Install this plugin and the local `dsh-better-display` checkout into the same web profile, reopen the Web Host, and reload. The published npm package does not have this seam until a release that includes it.
ASCII letters in the thinking card and the final answer render in upper case. Chinese is unchanged by Unicode case, so ask the model to reason in English if you need a visible difference. The fade still grows at the end of the string while the turn streams. Copy answer pastes the original casing. The 对话 tab still shows the original casing. A successful turn still folds the process and leaves the answer.
An async batch looks like this:
```ts
const cache = new Map<string, { text: string; final: boolean }>();
const listeners = new Set<() => void>();
seam.register(['reasoning', 'body'], {
read(request) {
if (request.source === 'tool') return undefined;
return cache.get(request.blockKey) ?? { text: request.text, final: !request.streaming };
},
subscribe(listener) {
listeners.add(listener);
return () => { listeners.delete(listener); };
},
});
function publish(blockKey: string, text: string, final: boolean) {
cache.set(blockKey, { text, final });
for (const listener of listeners) listener();
}
```
`publish` after each batch. Extend the previous cached string when the fade should continue.
### 接官方思考翻译(`cotTranslation`)
官方「思考过程机器翻译」组合包(`@deepseek-ai/dsh-experimental-cot-translation-bundle`)把译文注册在 `conversation.chat.reasoning.body` 插槽上,而阅读页用自己的卡片渲染思考,那个插槽不会渲染——装了翻译包,在阅读页看起来像没翻译。用这条缝接它:
```ts
const cot = ctx.get('cotTranslation') as {
limits(signal: AbortSignal): Promise<{
maxTextChars: number;
preferences: { provider: string; targetLanguage: string };
}>;
translate(
request: { text: string; targetLanguage: string; provider?: string },
signal: AbortSignal,
): Promise<string>;
} | undefined;
```
先调 `limits()` 拿目标语言与单次上限(这一步不发送文本),再按 `maxTextChars` 切出**已完成**段落逐段 `translate()`。四个容易踩的点:
- `read` 必须同步:返回缓存或 `undefined`(保留原文),把请求排进 `queueMicrotask`,完成后用 `subscribe` 通知重绘;
- 流式中的末段不发,否则会把半句话送去翻译;
- 结果按 `blockKey` 缓存,源文本变长时只请求新增段落;
- 失败返回 `undefined`,阅读页保留原文;不要抛错,也不要写回 block。
组合包没挂载时 `ctx.get('cotTranslation')` 返回 `undefined`,此时直接返回 `undefined` 即可,界面与未安装插件完全一致。
完整可运行版本(分片、缓存、失败回退、卸载中止)见 [`examples/cot-translation-reader/`](../examples/cot-translation-reader/)。
## `dsh-better-display.block`
Chain slot, `scope: 'session'`. The reader calls `renderSlotChain` once per block. The first selector that returns non-null draws the block. All-null renders the reader fallback, which is the path that keeps reveal, follow-scroll, and fold.
Owner:
```ts
interface ReaderBlockOwner {
block: AssistantBlock;
streaming: boolean;
source: 'assistant' | 'user' | 'tool';
presentation?: {
startedAt?: number;
interrupted?: boolean;
liveText?: boolean;
};
holdFormatting?: boolean;
liveText?: boolean;
}
```
`presentation`, `holdFormatting`, and `liveText` are what the reader already computed. They used to stop at the fallback. A plugin that replaces the chain can read them. A plugin that only reads `block`, `streaming`, and `source` does not need to change.
Selectors stay pure. Logging the owner from a selector is a temporary check, not the contract.
Replacing the chain drops the reader fallback for that block, including the text transform above. A translation plugin that wants the reader's motion should use the text-transform service and leave this chain alone.

View File

@ -0,0 +1,110 @@
# 官方能力接入说明
`0.3.0` 在阅读布局上接入官方内容和控件。当前验收目标是 Harness `0.2.1-rc.5`(`dsh-v0.2.1-rc.5`,`b830ec950faba0a46dda564be3e2d854afed94f1`)。`conversation.chat.turnTail` 仍是 `list`。`conversation.message.images` 已拆成 `conversation.chat.message.images` 与 `conversation.chat.user.images`,Reader 分别镜像这两条 single/session 槽。`ChatNodeOwnerProps` 不再带 `openSkill` / `renderMessageImages`;`conversation.chat.node` 的 `hookContext` 需要 `useGroupAction`。`schedule-created` 和 `schedule_update` 继续走已有镜像座位,Reader 不另写这两张卡片。图标仍使用 `*Regular` 名称。开发者消息里的工具增减行用官方标题和计数,本地 Markdown 图片接受 Desktop 文件路由 `dsh-app://app/api/file`。阅读页自己呈现模型重试和进行中的过程行,所以这两处官方视图变化不改阅读布局。后续仍需维护的自有展示逻辑和升级边界见下文。
## 一个具体例子
一条回答的持久化 `messageId` 进入 `OfficialActions`,随后进入 Reader 自己的回答操作插槽。里面的反馈组件、状态注入和弹窗控制器来自当前已加载的官方反馈插件。点击按钮后,由官方控制器打开原来的官方弹窗;Reader 不实现反馈请求、类别或状态管理。
工具详情同理:传递 `callId`、原始 `block`、工作目录、Host home、图片加载器、带行号的文件打开操作和轨迹入口,再由官方工具组件呈现。原来只取函数组件、手工传四个参数并模拟点击展开的路径已经移除。
## 代码归属
| 模块 | 负责什么 |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `official-slots.tsx` | 用公开注册表 API 将官方注册信息映射到 Reader 的独立插槽;保留注入、locale、store、selector 和子插槽。监听贡献增删,逐条挂载和释放。 |
| `OfficialContent.tsx` | 将回答身份、工具、节点和产物上下文传给官方控件。这里只组合,不处理业务请求。 |
| `Reader.tsx`、`ToolActivity.tsx` | 原有阅读布局、过程组织、摘要和交互。工具详情里的控件采用官方形式。 |
| `platform-media.ts` | RC2 的本地媒体 URL 约定;读取授权仍由 Host 文件 API 负责。 |
| `compat/harness-rc2.json` | 已验收的官方接口、被自有展示覆盖的实现和注册清单基线。 |
## 为什么有插槽映射
RC2 的一个子插槽只能有一个声明者,只有声明它的组件能获得相应 `renderSlot` 权限。Reader 不能把官方插槽再声明一次,也不能从 `ctx.slots` 任意渲染子插槽。
本适配用 `spec`、`entriesOfSlot`、`register`、`inject`、`subscribe` 建立 Reader 自己的名字空间,交给同一个官方渲染器运行。组件声明的子插槽名称在一层薄包装中转换,其余属性原样传递。没有私有源码导入,没有修改官方注册对象或官方 DOM,没有复制官方渲染器。现有控件保持组件和注入身份;增加别的控件不会重挂它们。
这仍是 RC2 的受限适配方案。若官方将来提供可直接组合的共享渲染入口,应优先替换这层映射。
## 这版覆盖的能力
| 能力 | 处理方式 |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 回答操作、反馈 | 官方 `conversation.chat.assistant-actions`,使用持久化 messageId;中断的临时片段不伪造身份。 |
| 工具详情 | 官方 `tool.call.toolview`,包括 memo、注入状态、翻译和递归子插槽;未注册的工具保留原有结果预览。 |
| 显式 `present` 产物 | 官方 turnTail 中的文件卡片和菜单,保留官方状态和打开操作。 |
| 已修改文件快捷操作 | 保持原 Reader 的复制、定位和打开模式;仅从 Reader 的官方 tail 展示参数中排除重复的 produced chips,不改变官方源数据。未知匹配结构原样呈现。 |
| 文件行号和正文文件链接 | 保留工具传来的行号;正文优先采用官方 file-mention 服务,现有路径匹配作为补充。 |
| 本地 Markdown 图片 | 和 RC2 相同的同源文件 API,加载失败保留替代文本,危险协议不直接渲染。 |
| 用户与 steering 消息 | 镜像 `conversation.chat.node` 的 keyed renderer,保留 `sessionId`、turn hook 和 Reader 跳转属性;未注册对应 key 时通过插槽 `fallback` 呈现 Reader 气泡。renderer 主动返回 `null` 时不补画气泡。 |
| 回答正文上的第三方替换渲染器 | 只镜像 priority 低于官方 `assistant-step`(priority 0)的注册。正文段交给该渲染器,`groupPart` 为 `response`,blocks 只有这一段。思考、折叠、动效和回答外框仍由 Reader 绘制。没有这类注册时正文仍走 Reader Markdown。 |
| 命令、新节点类型 | 接入官方节点渲染及其子插槽;无可用渲染器时保留记录并提供“在对话中查看”。 |
阅读布局、折叠、逐字动效、阅读速度、默认设置保持现版。移除了未被使用的全局 `body.dataset.readerFolding` 写入。
## 验证与升级
在选定 Harness 运行时上执行:
```sh
node scripts/link-harness-dependencies.mjs "$DSHX_HARNESS"
npm run build
npm test
npm run test:official
npm run test:auto-fold
```
`test:official` 使用测试目标里的真实官方 SlotRegistry、React renderer、反馈插件、ReadRow 和 Deliverables,只有远程业务服务使用内存替身。测试私有源码仅用于验证,不进入交付 bundle。浏览器验证使用本机固定的 Codex Playwright runtime,不附着用户会话。
`test:auto-fold` 使用真实 Reader 和独立的全局、会话 store,验证关闭后阅读再开启、此前步骤、设置同步、文本选择及连续切换;分别覆盖普通动画和减少动态效果。
`build` 先检查兼容基线。Harness 版本、敏感接口、尚未收敛的官方实现或相关注册清单改变时,构建明确要求审查。审查差异并通过功能与视觉测试后,才可运行 `check-harness-compat.mjs --record` 记录新基线。记录本身不构成兼容证明。
## rewind 座位兼容
Reader 的 user 与 steering 行会同时发布 `data-chat-anchor-key`、`data-chat-flow-key`、`data-chat-node-key` 和 `data-chat-flow-kind`,这些属性是 rewind 用来定位 durable 回退操作的官方 chat 座位契约。排队中的 inbox steering 也会渲染为 `data-pending-steering` 行,并按非文本内容块数量发布附件计数;本地 pending submission 与已落 durable 节点通过 source.rpcId 去重。
座位属性只解决「回退按钮出现在哪一行」,不解决「回退之后屏幕上还剩什么」。`dsh-rewind-plugin` 是 DOM 层实现:它从命令节点算出被遮蔽的 anchor seq,再对每个带 `data-chat-anchor-key` 的元素设 `display:none`。Reader 自渲染转录(turn 区块、answer、工具行),除 user/steering 外不发这个属性,所以 DOM 隐藏只够遮住气泡,被撤回的回答、工具行和 `/rewind` 命令行本身仍留在屏幕上——回退看起来只是被记录成一条命令,而不是把对话滚回发送该消息之前。
因此 Reader 自己执行同一份契约,见 `src/client/rewind-cut.ts`:从命令名属于 `{'rewind-plugin', 'rewind'}`(插件注册的命令 id 是前者,会话日志记录的是后者)且 `outcome.kind === 'success'` 的命令节点取 `outcome.sourceEventSeq`(替换型标记的日志 seq)与 `args` 里的 `@<seq>` 目标,合成闭区间 `[target, marker]`,落在区间内的 chat 行(含命令行自身)一律不渲染。三个要点:
- 回退的替换型标记 `user/message` 不是 append 事件,因此**不会**成为 chat 节点;命令节点的 `outcome.sourceEventSeq` 是客户端唯一的遮蔽信号。不要解析 `outcome.text`。
- 区间按「真正重叠/相接才合并」处理,不做 `[min,max]` 塌缩,否则两次回退之间的新内容会被一并吞掉。目标消息自身也在区间内:回退恢复的是发送该消息**之前**的状态。
- 行位置不是整数:官方 ChatView 会把合成行锚定在真实 seq 的分数偏移上(`CHAT_SYNTHETIC_SEQ_OFFSETS`:`turn-process` 在 `controlAnchorSeq - 0.1`、`turn-tail` 在 `seq + 0.1`、被中断的回答在 `seq - 0.9`)。判定用这个真实位置(`anchorSeqOf` 接受有限非负数),区间是闭区间 `[target, marker]`,**不要**放到下一个整数。下一回合的 `turn-process` 就锚在 `startSeq - 0.1`,落在 `[marker, marker + 1)` 里。
- `preview` 和 `__candidates` 不产生区间,哪怕 outcome 带了 marker。目标晚于 marker 的命令也不产生区间。失败或尚未成功的命令不产生区间,所以流式输出、重连、单纯重绘都不会被当成回退。
- 合成行故意锚在所属 turn 的事件区间之外。只有该 turn 的内容行全部落入区间(或已被宿主标成 hidden)时,才撤掉它的 `turn-process` 和 `turn-tail`。目标之前、同一 turn 里的用户消息和回答留着,过程摘要也留着。
最后一条也是订阅面:回退只是就地更新既有 command 节点,`snapshot.order` 与 `snapshot.nodes` 的引用都不变,针对其一的 selector 永不触发。Reader 因此订阅 `visibleChatSignature`(可见 key 拼成的字符串),让 chat hook 的 `Object.is` 比较能够发现变化。被撤回的行随即进入 `RetiringTurns`(`src/client/motion.tsx`)的退场通道:它按原索引保留该 turn,用 220ms 的 height/opacity 收起动画播完再卸载,行下方的内容是滑上去而不是瞬移。
纯图片目标现在也能撤回:这条路径只依赖命令节点的 seq,不再依赖插件对消息文本的匹配。收起动画在减少动态效果或页面隐藏时直接落到回退后的内容。`tests/rewind-cut.test.ts` 固定了上述规则、Reader 的接线和「流式 / 重绘 / 重连不误伤」;`tests/reader-official-users.test.ts` 仍覆盖座位与 easyrewrite 集成。
`dsh-easyrewrite@2.6.0` 在 `conversation.chat.node` 注册 `key: 'user', priority: -1` 的 `UserBubbleView`;撤回按钮是该组件内的 `data-dsh-easyrewrite="recall-key"`。chat 座位属性本身不会创建这个按钮,Reader 还需镜像此注册。它的快捷键使用 `data-chat-flow-kind="user"`,待定撤回的后续行隐藏使用 `data-chat-flow` 和 `data-chat-anchor-key`。
`tests/reader-official-users.test.ts` 在固定的 headless Chromium 中运行真实 Reader 与官方 registry/renderer,覆盖 user/steering 镜像、唯一气泡与锚点、session/turn 注入、替换、卸载、空 key 回退和 renderer 主动隐藏。可将已下载的 npm 包传入,额外验证 easyrewrite 的真实气泡、撤回按钮和点击后的确认胶囊:
```sh
DSH_EASYREWRITE_CLIENT=/path/to/package/lib/client.js \
node --import tsx/esm --test tests/reader-official-users.test.ts
```
该 fixture 不执行撤回提交。完整验收仍需在独立测试会话中打开 Reader,确认每条 user 消息只有一个气泡与撤回按钮;点击撤回并确认后检查输入框回填、取消恢复、发送后的真实历史回退,再切换到原对话检查一致性。另需用 steering 消息和历史跳转检查补充消息与锚点。
## 第三方 assistant-step 替换渲染器
Reader 自己画 `assistant-step`。思考卡片、过程折叠、逐字动效和回答栏留在阅读页,所以官方 priority 0 的 `AssistantNodeView` 不会再挂进阅读座位。挂进去的话,正文会被官方组件整段换掉。
Keyed 槽位里 priority 更小的注册胜出。priority 小于 0 的 `assistant-step` 注册就是在替换官方渲染器。`dsh-raw-html-v2@0.8.0` 用 priority `-10` 注册 `VcpSlotGuard`,遍历 `node.data.blocks`,把 text 块切成 Markdown 和 `<div id="vcp-root">` 卡片。阅读页只镜像这种替换,座位仍是 `dsh-better-display.official.nodes/conversation.chat.node`。`tool-call`、`turn-tail`、`turn-process` 继续不镜像。
每个正文段单独交给胜出的替换渲染器。传过去的 node 保留原来的身份、`status` 和 `step`,`data.blocks` 只有这一段的正文块,并带 `groupPart: 'response'`,和宿主把思考与回答拆开的方式一致。思考段仍走阅读页的 `ReasoningCard`。折叠、吸顶、复制和回答外框也不交给替换渲染器。
没有这类注册时,`renderSlot` 的 fallback 仍是阅读页自己的 Markdown。替换渲染器返回 `null` 时不补画第二份正文。它卸下之后,下一次 reconcile 回到 Markdown。
这里不解析某一种卡片协议,也不改会话数据。原始 HTML、代码围栏和流式切段仍由那个插件自己的渲染器处理。阅读页保证的是:这个渲染器能在回答正文里运行。启用替换渲染器时,正文不再走阅读页的逐字动效;思考和折叠动效保持不变。替换渲染器若自己再画一份「已中断」,会和阅读页的「已停止」叠在一起,这是该渲染器的展示,不另做裁剪。
`tests/official-slots.test.ts` 锁定「priority 低于 0 才镜像,官方 priority 与 tool-call 不镜像」。`tests/fixtures/reader-official-users.tsx` 在真实 Reader 里渲染一条带思考和 `<div id="vcp-root">` 的 assistant-step:替换渲染器收到 `groupPart: 'response'` 和正文块,思考文本留在 `data-reader-text-kind="reasoning"`,回答栏里不再出现 Markdown 代码块。
## 后续仍需完成
Markdown 定制仍保留逐字动效和 MCP 展示钩子,官方公共组件还没有对应的注入接口。上下文行、部分过程展示和工具摘要也仍有自有实现。本分支先建立官方能力的完整运行路径,后续按视觉基线逐模块收敛这些副本,并拆分 Reader 的阅读策略与动画执行。不能据此承诺所有未来版本零维护。上面的 assistant-step 替换渲染器是已承诺的共存方式;除此之外不承诺任意第三方插件的视觉兼容。
已有客户端通过 HMR 更新时,无需新增 Host 或改写会话数据;应先核对实际安装来源、构建产物和同页行为。正式版本保留 Git 标签及发布包,便于按版本安装和回退。

147
docs/openapi.yaml Normal file
View File

@ -0,0 +1,147 @@
openapi: 3.0.3
info:
title: dsh-better-display
version: 0.3.9
description: >
Exact routes registered by apply() in src/dsh-better-display.ts.
POST /better-display/reveal is createRevealHandler in src/reveal.ts.
GET /better-display/skill-status returns toPublicSkillStatus.
The host webServer mounts these paths. The handlers do not read an
Authorization header or any other credential.
servers:
- url: /
description: DeepSeek Harness host after this plugin has loaded.
paths:
/better-display/reveal:
post:
operationId: revealInFileManager
summary: Reveal a workspace file in the OS file manager
description: >
Any method other than POST returns 405 with an empty body and no
Content-Type. The JSON body is read to completion, then parsed.
An absolute path is used as-is and does not call the workspace root
lookup. A relative path must resolve to exactly one existing file
under the session cwd or the matching workspace registry roots.
Drive-relative and root-relative Windows paths are rejected.
On success the host spawns open -R, explorer.exe /select, or xdg-open.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [path]
properties:
path:
type: string
description: Trimmed. Empty or whitespace-only is 400.
sessionId:
type: string
description: Optional. Used only when path is not absolute.
examples:
relative:
value:
path: docs/report.md
sessionId: target
responses:
'200':
description: The file manager was spawned. Body is JSON.
content:
application/json:
schema:
type: object
required: [ok]
additionalProperties: false
properties:
ok:
type: boolean
enum: [true]
'400':
description: >
JSON.parse failed, path was empty, the path was not
workspace-relative, no root contained the file, or more than one
root contained it. error is String(err), so it includes the
Error prefix.
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorBody'
'405':
description: req.method was not POST. Empty body. Content-Type is not set.
/better-display/skill-status:
get:
operationId: getGenerativeMcpappsSkillStatus
summary: Public generative-mcpapps install status
description: >
Any method other than GET returns 405 with an empty body and no
Content-Type. The optional cwd query selects which project roots are
scanned. The JSON body is toPublicSkillStatus, which always replaces
roots with the two conventional relative paths and drops packPath
and any host home absolute path.
parameters:
- in: query
name: cwd
required: false
schema:
type: string
description: Project directory passed to scanGenerativeMcpappsStatus. Omitted when the settings probe has no session cwd.
responses:
'200':
description: Public skill status. This body has no ok field.
content:
application/json:
schema:
$ref: '#/components/schemas/PublicSkillStatus'
'405':
description: req.method was not GET. Empty body. Content-Type is not set.
'500':
description: scanGenerativeMcpappsStatus threw. error is String(err).
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorBody'
components:
schemas:
ErrorBody:
type: object
required: [ok, error]
additionalProperties: false
properties:
ok:
type: boolean
enum: [false]
error:
type: string
PublicSkillRoot:
type: object
required: [source, path]
additionalProperties: false
properties:
source:
type: string
enum: [conventional]
path:
type: string
enum: ['.dsh/skills', '.agents/skills']
PublicSkillStatus:
type: object
required: [name, installed, via, roots]
additionalProperties: false
properties:
name:
type: string
enum: [generative-mcpapps]
installed:
type: boolean
via:
type: string
nullable: true
enum: ['skills.list', 'skill-root', null]
description: skills.list when the host skills registry lists the skill, skill-root when a scanned root has it, otherwise null.
roots:
type: array
minItems: 2
maxItems: 2
items:
$ref: '#/components/schemas/PublicSkillRoot'
description: Always .dsh/skills then .agents/skills, source conventional. Not the scanned absolute roots.

View File

@ -0,0 +1,39 @@
# Blank reader, missing stylesheet, stuck fold
These three show up in CHANGELOG as real failures. There is no dashboard to open. Look at the host page and the versions below.
## Blank reader
0.3.8 (#60) re-injects the plugin stylesheet when a session switch clears it, because that clear left a blank page. `ensureStyles` in `src/client/styles.ts` remembers `style[data-plugin="dsh-better-display"][data-plugin-css]` and puts a missing tag back on `document.head`. The client entry calls it while the module loads (`src/client/index.tsx`), and `Reader` calls it again from `useInsertionEffect` before paint.
A page that never becomes the reading view is a different failure. 0.3.1 threw while booting because `conversation.chat.turnTail` had become a list slot, and the host stayed on “Failed to load plugins”. 0.3.7 shipped a host entry that imported `./skill-roots.ts`; the host died with `ERR_MODULE_NOT_FOUND` while the market still showed the plugin installed. 0.3.8 stops externalising those relative host imports. Reinstalling the broken 0.3.7 build does not fix that.
Check, in order:
1. Reopen the Web Host and reload. The bundle is read at boot.
2. If the host says “Failed to load plugins”, read that error. Do not toggle auto-fold. A slot mismatch or `ERR_MODULE_NOT_FOUND ./skill-roots.ts` means the installed build never reached `Reader`.
3. In the document, look for `style[data-plugin="dsh-better-display"]`. If the reading column is mounted and those tags are missing, the stylesheet was cleared before `ensureStyles` had stored it. Reload so the client entry runs again.
## Missing stylesheet
The same 0.3.8 note (#60) is the stylesheet case: the session switch removes the plugin style tags, the reading column is still there, and it paints without the reader sheet. `ensureStyles` can only restore tags it has already seen. If `document.head` has no `data-plugin-css` node for this plugin and the in-memory map is empty, there is nothing to put back until the entry runs again.
Confirm the host did not mount the plugin twice. A hand-written `cordis.patch.yml` insert plus `dsh plugin add` loads two copies. Reload after a single install. Do not add a second stylesheet link.
## Stuck fold
0.2.0: the fold choreography advanced only on animation promises and rendered frames. A cancelled animation rejects, and a hidden tab delivers no frames. The machine stayed in a non-idle phase, the frame source stayed on the shown snapshot, and the text reveal paused, so the turn looked stuck until the view remounted. Each phase now has a wall-clock deadline. In `src/client/fold-choreography.ts`, `watchdogSlack` is 240ms added to the phase duration (`collapse` 320, `count` 160, `settle` 80, `reveal` 180). `ChoreographedFlow` fires that deadline with `setTimeout` and moves the phase even when `onfinish` never runs.
The same release gave disclosures a deadline. `fill: 'both'` pins the opening keyframe, so a Web Animation that never reaches `onfinish` left the row at zero height and zero opacity. A click looked like nothing happened. Later deadlines in `motion.tsx` and `ReasoningCard.tsx` use the same 240ms slack on top of the animation length.
0.3.5: a finished expand animation has to release back to the row’s natural height. Content that changed after expanding left blank space or clipped steps until refresh. The collapse animation stays until React removes the content, so it does not flash for one frame.
0.3.8 (#60) adds a timeout fallback for retiring content animations so they complete instead of holding the row.
0.3.0: turning auto-fold off, opening process detail, then turning it on again used to leave the process expanded. Turning it on restores the auto-fold rules. Text selection protection and a later manual expand still win. The switch is on the reading toolbar and in Settings. The root store key is `dsh.reader.v1`; `foldIntensity` 0 is off, 1 is the default fold, 2 folds process runs into a digest and does not fold prose.
Check, in order:
1. Settings shows auto-fold on. Off means thinking and tools stay expanded. That is not a stuck animation.
2. Wait out the phase plus 240ms. A row still at zero height after that should have been settled by the deadline. Reload the reading view once. The pre-0.2.0 recovery was a remount, and a deadline that did not run is the bug to report.
3. Say whether the tab was in the background and whether `prefers-reduced-motion` is set. Do not restyle `Reader` to force the row open.

3
flags.json Normal file
View File

@ -0,0 +1,3 @@
{
"readerEnabled": true
}

View File

@ -1,13 +0,0 @@
/**
* dsh-better-chat — DSH 聊天增强插件。
*
* 宿主侧入口只是占位(让 bundle 能被加载);功能都在 Web 客户端
* (client.js,见 package.json 的 exports / dsh 清单):
* 功能一 = 审批卡片的回车批准 / Esc 拒绝(自动送入焦点 + 全局兜底路由)。
*/
/** Plugin identity for cordis.yml rows. */
export const name = 'dsh-better-chat'
/** Plugin body: nothing host-side yet; the client half does the work. */
export function apply(ctx) {}

File diff suppressed because one or more lines are too long

1
lib/client.js.map Normal file

File diff suppressed because one or more lines are too long

570
lib/host.js Normal file
View File

@ -0,0 +1,570 @@
import { existsSync, readFileSync } from "node:fs";
import { dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
import { fileURLToPath } from "node:url";
import { randomUUID } from "node:crypto";
import { spawn } from "node:child_process";
import { access, readdir } from "node:fs/promises";
import { homedir } from "node:os";
// src/flags.ts
const defaultFlags = { readerEnabled: true };
function locateFlags(start = dirname(fileURLToPath(import.meta.url))) {
let dir = start;
for (let depth = 0; depth < 6; depth += 1) {
const candidate = resolve(dir, "flags.json");
if (existsSync(candidate)) return candidate;
const parent = dirname(dir);
if (parent === dir) return void 0;
dir = parent;
}
}
function normalize(value) {
const record = value !== null && typeof value === "object" ? value : {};
return { readerEnabled: typeof record.readerEnabled === "boolean" ? record.readerEnabled : defaultFlags.readerEnabled };
}
function loadFlags(source) {
if (source !== void 0 && typeof source !== "string") return normalize(source);
try {
const path = typeof source === "string" ? source : locateFlags();
if (path === void 0 || !existsSync(path)) return { ...defaultFlags };
return normalize(JSON.parse(readFileSync(path, "utf8")));
} catch {
return { ...defaultFlags };
}
}
// src/log.ts
const REDACTED = "[REDACTED]";
const REQUEST_ID_HEADER = "x-request-id";
const REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,200}$/;
const SECRET_KEYS = /* @__PURE__ */ new Set([
"authorization",
"proxyauthorization",
"cookie",
"setcookie",
"token",
"accesstoken",
"refreshtoken",
"idtoken",
"apikey",
"apisecret",
"secret",
"clientsecret",
"password",
"passwd",
"credential",
"credentials",
"signature",
"sig",
"jwt",
"bearer",
"privatekey",
"xapikey",
"xauthtoken",
"xaccesstoken",
"auth"
]);
function normalizeKey(key) {
return key.toLowerCase().replace(/[^a-z0-9]/g, "");
}
function isSecretKey(key) {
const normalized = normalizeKey(key);
if (SECRET_KEYS.has(normalized)) return true;
if (normalized === "requestid" || normalized === "xrequestid") return false;
return /(?:^|[^a-z])(?:token|secret|password|api[-_]?key)$/i.test(key);
}
function redactString(value) {
return value.replace(/([?&#])([^&#=]+)=([^&#]*)/g, (match, sep, rawKey) => {
let key;
try {
key = decodeURIComponent(rawKey.replace(/\+/g, " "));
} catch {
key = rawKey;
}
return isSecretKey(key) ? `${sep}${rawKey}=${REDACTED}` : match;
}).replace(/\b(Bearer|Basic)\s+\S+/gi, `$1 ${REDACTED}`).replace(/\b((?:access[_-]?token|refresh[_-]?token|id[_-]?token|api[_-]?key|client[_-]?secret|password|passwd|authorization|token|secret))(\s*[:=]\s*)([^\s&]+)/gi, `$1$2${REDACTED}`);
}
function redact(value) {
return redactValue(void 0, value, 0, /* @__PURE__ */ new WeakSet());
}
function redactValue(key, value, depth, seen) {
if (key !== void 0 && isSecretKey(key)) return REDACTED;
if (depth > 8) return REDACTED;
if (typeof value === "string") return redactString(value);
if (typeof value === "number" || typeof value === "boolean" || value === null || value === void 0) return value;
if (typeof value !== "object") return REDACTED;
if (value instanceof Date) return value.toISOString();
if (value instanceof Error) return redactValue(void 0, {
name: value.name,
message: value.message
}, depth + 1, seen);
if (seen.has(value)) return REDACTED;
seen.add(value);
if (Array.isArray(value)) return value.map((item) => redactValue(void 0, item, depth + 1, seen));
const output = {};
for (const [childKey, childValue] of Object.entries(value)) output[childKey] = redactValue(childKey, childValue, depth + 1, seen);
return output;
}
function createLogger(options = {}) {
const write = options.write ?? ((line) => {
console.log(line);
});
const clock = options.clock ?? (() => /* @__PURE__ */ new Date());
const emit = (level, msg, fields) => {
const details = redact({
...options.base,
...fields
});
const record = {
...details !== null && typeof details === "object" ? details : {},
time: clock().toISOString(),
level,
msg: redactString(msg)
};
try {
write(JSON.stringify(record));
} catch {
write(JSON.stringify({
time: record.time,
level,
msg: record.msg,
error: "log record was not serializable"
}));
}
};
return {
info: (msg, fields) => emit("info", msg, fields),
warn: (msg, fields) => emit("warn", msg, fields),
error: (msg, fields) => emit("error", msg, fields)
};
}
function requestIdOf(req) {
const raw = req.headers[REQUEST_ID_HEADER];
const value = Array.isArray(raw) ? raw[0] : raw;
if (typeof value === "string" && REQUEST_ID_PATTERN.test(value)) return value;
return randomUUID();
}
// src/metrics.ts
const ROUTE_REVEAL = "/better-display/reveal";
const ROUTE_SKILL_STATUS = "/better-display/skill-status";
const ROUTE_METRICS = "/better-display/metrics";
const ROUTE_HITS = [
ROUTE_REVEAL,
ROUTE_SKILL_STATUS,
ROUTE_METRICS
];
const hits = new Map(ROUTE_HITS.map((route) => [route, 0]));
const timings = new Map(ROUTE_HITS.map((route) => [route, {
count: 0,
totalMs: 0,
maxMs: 0
}]));
function snapshotHits() {
return Object.fromEntries(hits);
}
function snapshotTimings() {
return Object.fromEntries([...timings].map(([route, timing]) => [route, { ...timing }]));
}
function recordRouteHit(route) {
const next = (hits.get(route) ?? 0) + 1;
hits.set(route, next);
return next;
}
function recordRouteDuration(route, elapsedMs) {
const ms = Number.isFinite(elapsedMs) && elapsedMs > 0 ? Math.round(elapsedMs) : 0;
const current = timings.get(route) ?? {
count: 0,
totalMs: 0,
maxMs: 0
};
const next = {
count: current.count + 1,
totalMs: current.totalMs + ms,
maxMs: Math.max(current.maxMs, ms)
};
timings.set(route, next);
return next;
}
function metricsPayload() {
return {
counters: { dsh_better_display_route_hits_total: snapshotHits() },
timingsMs: snapshotTimings()
};
}
// src/workspace-path.ts
/** Absolute paths accepted by both POSIX and Windows hosts. */
function isAbsoluteWorkspacePath(path) {
return /^(?:\/|[A-Za-z]:[/\\]|\\\\)/.test(path);
}
// \0@oxc-project+runtime@0.158.0/helpers/esm/usingCtx.js
function _usingCtx() {
var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
var n = Error();
return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
}, e = {}, n = [];
function using(r, e) {
if (null != e) {
if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
if ("function" != typeof o) throw new TypeError("Object is not disposable.");
t && (o = function o() {
try {
t.call(e);
} catch (r) {
return Promise.reject(r);
}
}), n.push({
v: e,
d: o,
a: r
});
} else r && n.push({
d: e,
a: r
});
return e;
}
return {
e,
u: using.bind(null, !1),
a: using.bind(null, !0),
d: function d() {
var o, t = this.e, s = 0;
function next() {
for (; o = n.pop();) try {
if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
if (o.d) {
var r = o.d.call(o.v);
if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
} else s |= 1;
} catch (r) {
return err(r);
}
if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
if (t !== e) throw t;
}
function err(n) {
return t = t !== e ? new r(n, t) : n, next();
}
return next();
}
};
}
// src/reveal.ts
async function revealRoots(ctx, sessionId) {
if (sessionId !== void 0) {
const cwd = (ctx.get?.("sessions"))?.get(sessionId)?.header.cwd;
if (cwd) return [cwd];
const query = ctx.get?.("sessionQuery");
if (query) try {
var _usingCtx$1 = _usingCtx();
const observation = _usingCtx$1.u(await query.observeSession(sessionId, { projectionMode: "none" }));
if (observation.header.cwd) return [observation.header.cwd];
} catch (_) {
_usingCtx$1.e = _;
} finally {
_usingCtx$1.d();
}
}
return ((ctx.get?.("workspaceRegistry"))?.list() ?? []).filter((workspace) => sessionId === void 0 || workspace.sessionIds.includes(sessionId)).map((workspace) => workspace.path);
}
function resolveRevealPath(path, roots, exists = existsSync) {
if (isAbsoluteWorkspacePath(path)) return path;
if (/^[A-Za-z]:|^\\/.test(path)) throw new Error("Path is not workspace-relative");
const matches = /* @__PURE__ */ new Set();
for (const root of roots) {
if (!isAbsoluteWorkspacePath(root)) continue;
const candidate = (/^[A-Za-z]:[/\\]|^\\\\/.test(root) ? win32 : posix).resolve(root, path);
if (exists(candidate)) matches.add(candidate);
}
if (matches.size !== 1) throw new Error(matches.size === 0 ? "Workspace path not found" : "Workspace path is ambiguous");
return [...matches][0];
}
function revealPath(path, platform = process.platform, spawnProcess = spawn) {
const options = {
detached: true,
stdio: "ignore"
};
if (platform === "darwin") spawnProcess("open", ["-R", path], options);
else if (platform === "win32") spawnProcess("explorer.exe", [`/select,"${path}"`], {
...options,
windowsVerbatimArguments: true
});
else spawnProcess("xdg-open", [path], options);
}
function createRevealHandler({ roots, reveal = revealPath }) {
return (req, res) => {
if (req.method !== "POST") {
res.statusCode = 405;
res.end();
return;
}
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", async () => {
res.setHeader("Content-Type", "application/json");
try {
const data = JSON.parse(body);
const path = typeof data === "object" && data !== null && "path" in data && typeof data.path === "string" ? data.path.trim() : "";
if (!path) throw new Error("Empty path");
const sessionId = typeof data === "object" && data !== null && "sessionId" in data && typeof data.sessionId === "string" ? data.sessionId : void 0;
reveal(resolveRevealPath(path, isAbsoluteWorkspacePath(path) ? [] : await roots(sessionId)));
res.statusCode = 200;
res.end(JSON.stringify({ ok: true }));
} catch (err) {
res.statusCode = 400;
res.end(JSON.stringify({
ok: false,
error: String(err)
}));
}
});
};
}
// src/skill-status.ts
/** Shared generative-mcpapps identity. Plugin-tree presence is not installation. */
const GENERATIVE_MCPAPPS_SKILL = "generative-mcpapps";
/** Conventional relative roots only. Never expand $HOME or dump host `root.path`. */
const CONVENTIONAL_SKILL_ROOTS = [".dsh/skills", ".agents/skills"];
function skillNameMatches(name) {
return typeof name === "string" && name === "generative-mcpapps";
}
function skillListIncludes(entries) {
return Array.isArray(entries) && entries.some((entry) => skillNameMatches(entry?.name));
}
/** Directory bundle `name/SKILL.md` or flat `name.md` at a scanned root. */
function skillRootEntryMatches(entryName) {
return entryName === "generative-mcpapps" || entryName === `generative-mcpapps.md`;
}
function skillsFromListResult(result) {
if (Array.isArray(result)) return result;
if (result === null || typeof result !== "object") return [];
const record = result;
if (record.ok === false) return [];
if (Array.isArray(record.skills)) return record.skills;
if (record.value && typeof record.value === "object") {
const value = record.value;
if (Array.isArray(value.skills)) return value.skills;
if (Array.isArray(record.value)) return record.value;
}
return [];
}
function publicSkillRoots() {
return CONVENTIONAL_SKILL_ROOTS.map((path) => ({
source: "conventional",
path
}));
}
/**
* Strip host home / pack absolutes before anything user-facing (HTTP or Settings).
* Detection still uses the raw scan; this is the public face.
*/
function toPublicSkillStatus(status) {
return {
name: status.name,
installed: status.installed,
via: status.via,
roots: publicSkillRoots()
};
}
// src/skill-roots.ts
function expandHomePath(path, home = homedir()) {
if (path === "~") return home;
if (path.startsWith("~/") || path.startsWith("~\\")) return join(home, path.slice(2));
return path;
}
/** `$DSH_HOME` or `~/.dsh`, matching official `resolveDshHome`. */
function resolveDshHome(env = process.env, home = homedir()) {
const fromEnv = env.DSH_HOME;
const selected = fromEnv !== void 0 && fromEnv.trim().length > 0 ? fromEnv : join(home, ".dsh");
return resolve(expandHomePath(selected, home));
}
/** `$DSH_AGENTS_HOME` or `~/.agents`. */
function resolveAgentsHome(env = process.env, home = homedir()) {
const fromEnv = env.DSH_AGENTS_HOME;
const selected = fromEnv !== void 0 && fromEnv.trim().length > 0 ? fromEnv : join(home, ".agents");
return resolve(expandHomePath(selected, home));
}
function userSkillRoots(env = process.env, home = homedir()) {
return [{
source: "user-dsh",
path: join(resolveDshHome(env, home), "skills")
}, {
source: "user-agents",
path: join(resolveAgentsHome(env, home), "skills")
}];
}
function projectSkillRoots(projectRoot) {
return [{
source: "project-dsh",
path: join(projectRoot, ".dsh", "skills")
}, {
source: "project-agents",
path: join(projectRoot, ".agents", "skills")
}];
}
async function findProjectRoot(cwd) {
let current = resolve(cwd);
while (true) {
if (existsSync(join(current, ".git"))) return current;
const parent = dirname(current);
if (parent === current) return resolve(cwd);
current = parent;
}
}
async function rootHasGenerativeMcpapps(rootPath) {
let entries;
try {
entries = await readdir(rootPath, { withFileTypes: true });
} catch {
return false;
}
for (const entry of entries) {
if (entry.name === ".system") continue;
if (!skillRootEntryMatches(entry.name)) continue;
if (entry.isDirectory()) try {
await access(join(rootPath, entry.name, "SKILL.md"));
return true;
} catch {
continue;
}
if (entry.isFile()) return true;
}
return false;
}
/** Resolve the plugin-shipped pack. This path is never treated as a skill root. */
function pluginSkillPackPath(moduleUrl = import.meta.url) {
const here = dirname(fileURLToPath(moduleUrl));
return [
join(here, "../skills", GENERATIVE_MCPAPPS_SKILL),
join(here, "../../skills", GENERATIVE_MCPAPPS_SKILL),
join(here, "skills", GENERATIVE_MCPAPPS_SKILL)
].find((path) => existsSync(join(path, "SKILL.md")));
}
async function scanGenerativeMcpappsStatus(options = {}) {
const roots = [...userSkillRoots(options.env ?? process.env, options.home ?? homedir())];
const cwd = typeof options.cwd === "string" && options.cwd.trim().length > 0 ? isAbsolute(options.cwd) ? options.cwd : resolve(options.cwd) : void 0;
if (cwd !== void 0) roots.unshift(...projectSkillRoots(await findProjectRoot(cwd)));
const inspected = [];
let rootHit = false;
for (const root of roots) {
const present = await rootHasGenerativeMcpapps(root.path);
inspected.push({
...root,
present
});
if (present) rootHit = true;
}
let via = null;
let listHit = false;
if (options.listSkills) try {
listHit = skillListIncludes(await options.listSkills());
if (listHit) via = "skills.list";
} catch {}
if (!listHit && rootHit) via = "skill-root";
const packPath = options.packPath ?? pluginSkillPackPath();
return {
name: GENERATIVE_MCPAPPS_SKILL,
installed: listHit || rootHit,
via,
roots: inspected,
...packPath !== void 0 ? { packPath } : {}
};
}
// src/host.ts
const name = "dsh-better-chat";
const inject = ["webServer"];
const log = createLogger({ base: { plugin: name } });
function writeJson(res, status, body) {
res.setHeader("Content-Type", "application/json");
res.statusCode = status;
res.end(JSON.stringify(body));
}
function skillLister(ctx) {
const skills = ctx.get?.("skills");
if (typeof skills?.list !== "function") return void 0;
return async () => skillsFromListResult(await skills.list({}));
}
function beginRequest(req, res, route) {
const requestId = requestIdOf(req);
res.setHeader("X-Request-ID", requestId);
recordRouteHit(route);
const started = performance.now();
res.on("finish", () => {
recordRouteDuration(route, performance.now() - started);
});
log.info("http request", {
requestId,
route,
method: req.method ?? "",
url: req.url ?? "",
headers: req.headers
});
return requestId;
}
function apply(ctx, options) {
const flags = options?.flags ?? loadFlags();
log.info("[dsh-better-chat] loaded", { readerEnabled: flags.readerEnabled });
if (!flags.readerEnabled) {
log.info("route registration skipped", { readerEnabled: false });
return;
}
if (ctx.webServer) ctx.effect(() => {
const reveal = createRevealHandler({ roots: (sessionId) => revealRoots(ctx, sessionId) });
const disposeReveal = ctx.webServer.register({
kind: "exact",
path: ROUTE_REVEAL,
handler: (req, res) => {
beginRequest(req, res, ROUTE_REVEAL);
reveal(req, res);
}
});
const disposeSkill = ctx.webServer.register({
kind: "exact",
path: ROUTE_SKILL_STATUS,
handler: async (req, res) => {
const requestId = beginRequest(req, res, ROUTE_SKILL_STATUS);
if (req.method !== "GET") {
res.statusCode = 405;
res.end();
return;
}
try {
writeJson(res, 200, toPublicSkillStatus(await scanGenerativeMcpappsStatus({
cwd: new URL(req.url ?? "", "http://127.0.0.1").searchParams.get("cwd") ?? void 0,
listSkills: skillLister(ctx)
})));
} catch (err) {
log.error("skill-status failed", {
requestId,
error: err instanceof Error ? err.message : String(err)
});
writeJson(res, 500, {
ok: false,
error: String(err)
});
}
}
});
const disposeMetrics = ctx.webServer.register({
kind: "exact",
path: ROUTE_METRICS,
handler: (req, res) => {
beginRequest(req, res, ROUTE_METRICS);
if (req.method !== "GET") {
res.statusCode = 405;
res.end();
return;
}
writeJson(res, 200, metricsPayload());
}
});
return () => {
disposeReveal();
disposeSkill();
disposeMetrics();
};
}, "dsh-better-chat: reveal, skill-status, and metrics routes");
}
export { apply, inject, name };

View File

@ -0,0 +1,24 @@
MIT License
Copyright (c) 2026 dsh-better-display contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Third-party material retains its original license and terms as identified in
THIRD_PARTY_NOTICES.md. This license does not relicense that material.

View File

@ -1,11 +1,12 @@
{
"name": "dsh-better-chat",
"version": "0.3.1",
"description": "DSH 聊天增强插件:审批卡片全局回车批准 / Esc 拒绝",
"version": "0.4.0",
"description": "DSH 聊天增强插件:审批回车批准 / Esc 拒绝、权限 UI、插件商店更新,以及 reading view(合并自 dsh-better-display)",
"type": "module",
"main": "index.js",
"license": "MIT",
"main": "lib/host.js",
"exports": {
".": "./index.js",
".": "./lib/host.js",
"./client": "./lib/client.js",
"./cordis.patch.yml": "./cordis.patch.yml",
"./package.json": "./package.json"
@ -16,12 +17,91 @@
},
"client": {
"platform": "web",
"inject": []
"inject": [
"@deepseek-ai/dsh-api-session-controller",
"@deepseek-ai/dsh-client-ui-chat",
"@deepseek-ai/dsh-client-ui-conversation",
"@deepseek-ai/dsh-client-ui-renderer",
"@deepseek-ai/dsh-client-ui-session"
]
}
},
"scripts": {
"test": "node --test tests/approval-keys.test.mjs tests/permission-policy.test.mjs tests/client-loader.test.mjs tests/store-update.test.mjs",
"build": "node scripts/build-client.mjs"
"build": "tsdown",
"test": "vitest run",
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"license": "MIT"
"dependencies": {
"@deepseek-ai/dsh-util-workspace-path": "0.2.1-rc.5",
"clsx": "^2.0.0",
"katex": "^0.19.1",
"mdast-util-from-markdown": "^2.0.3",
"mdast-util-gfm": "^3.1.0",
"mdast-util-math": "^3.0.0",
"micromark-core-commonmark": "^2.0.3",
"micromark-extension-gfm": "^3.0.0",
"micromark-extension-math": "^3.1.0",
"micromark-factory-space": "^2.0.1",
"micromark-util-character": "^2.1.1",
"micromark-util-classify-character": "^2.0.1",
"micromark-util-sanitize-uri": "^2.0.1",
"micromark-util-symbol": "^2.0.1",
"micromark-util-types": "^2.0.2"
},
"peerDependencies": {
"@deepseek-ai/cordis": ">=4.0.4 <5",
"@deepseek-ai/dsh-attachment": ">=0.2.1-rc.1 <0.2.3",
"@deepseek-ai/dsh-client-store": ">=0.2.1-rc.1 <0.2.3",
"@deepseek-ai/dsh-client-ui-chat": ">=0.2.1-rc.1 <0.2.3",
"@deepseek-ai/dsh-client-ui-conversation": ">=0.2.1-rc.1 <0.2.3",
"@deepseek-ai/dsh-client-ui-primitives": ">=0.2.1-rc.1 <0.2.3",
"@deepseek-ai/dsh-client-ui-renderer": ">=0.2.1-rc.1 <0.2.3",
"@deepseek-ai/dsh-client-ui-session": ">=0.2.1-rc.1 <0.2.3",
"@deepseek-ai/dsh-client-ui-slots": ">=0.2.1-rc.1 <0.2.3",
"@deepseek-ai/dsh-client-ui-tool": ">=0.2.1-rc.1 <0.2.3",
"@deepseek-ai/dsh-session": ">=0.2.1-rc.1 <0.2.3",
"@deepseek-ai/dsh-util-workspace-path": ">=0.2.1-rc.1 <0.2.3",
"react": "^18.2.0"
},
"devDependencies": {
"@types/node": "^22.20.0",
"@types/react": "~18.3.1",
"lightningcss": "^1.33.0",
"semver": "^7.7.2",
"tsdown": "^0.23.2",
"typescript": "^6.0.3",
"vitest": "^5.0.5"
},
"engines": {
"node": "^22.19.0 || >=24.0.0",
"dsh": ">=0.2.1-rc.1 <0.2.3"
},
"files": [
"lib",
"src",
"tests",
"docs",
"skills",
"cordis.patch.yml",
"flags.json",
"README.md",
"README.en.md",
"CHANGELOG.md",
"DESIGN.md",
"THIRD_PARTY_NOTICES.md",
"licenses",
"tsconfig.json",
"tsdown.config.ts",
"vitest.config.ts",
"tools"
],
"keywords": [
"deepseek-harness",
"dsh",
"dsh-plugin",
"conversation",
"approval",
"permission",
"reading"
]
}

2146
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,47 +0,0 @@
// Build lib/client.js (the file the host's client module loader fetches)
// from client.js (the ESM source of truth).
//
// Why: the loader fetches a package's client as a CLASSIC script and expects
// it to register a factory via window.__ModuleLoader__.load({ id, factory }).
// A raw ESM file registers nothing (its `export` syntax never runs), which is
// the v0.2.0 standalone-load failure. client.js stays ESM for the QQ-dsh
// bundle's direct import and for the unit tests; this script mechanically
// strips the export keywords and wraps the result in the registration IIFE.
// It fails loudly if the source grows an export shape it cannot map.
import { readFileSync, writeFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
const source = readFileSync(join(root, 'client.js'), 'utf8')
const exported = []
const body = source.replace(/^export (async function|function|const) ([A-Za-z_$][\w$]*)/gm, (match, kind, name) => {
exported.push(name)
return kind + ' ' + name
})
if (/^export /m.test(body)) throw new Error('unmapped export syntax remains in client.js')
for (const required of ['inject', 'apply']) {
if (!exported.includes(required)) throw new Error('client.js no longer exports ' + required)
}
const header = [
"'use strict'",
'/* Generated by scripts/build-client.mjs from client.js - do not edit by hand.',
' The host client module loader fetches this file as a classic script and',
' expects window.__ModuleLoader__.load({ id, factory }) registration. */',
';(function () {',
'',
].join('\n')
const footer = [
'',
' var plugin = { name: "dsh-better-chat", inject: inject, apply: apply }',
' if (typeof window !== "undefined" && window.__ModuleLoader__ && typeof window.__ModuleLoader__.load === "function") {',
' window.__ModuleLoader__.load({ id: "dsh-better-chat", factory: function () { return plugin } })',
' }',
'})()',
'',
].join('\n')
writeFileSync(join(root, 'lib', 'client.js'), header + body + footer)
console.log('built lib/client.js from client.js; exports mapped:', exported.join(', '))

View File

@ -0,0 +1,47 @@
---
name: generative-mcpapps
description: "Render interactive HTML/JS widgets, product UI mockups, and clickable prototypes inside the chat (MCP Apps / SEP-1865). Use whenever the user asks to see, preview, compare, or interact with a design (mockup, prototype, 画出来看看): data visualizations, calculators, stateful forms, config wizards, or any UI richer than plain Markdown."
---
# Generative MCP Apps
Create self-contained interactive HTML/JS widgets, UI mockups, and clickable prototypes in chat. This is an Agent Skill with YAML metadata and Markdown instructions; it has no Gemini-specific syntax or model requirement.
## Select the delivery surface
- In DSH with Better Display enabled, emit an `mcp-app` fenced code block. The reading view renders it in an iframe with `sandbox="allow-scripts allow-forms"`.
- In another harness, use only its available, documented UI tool and actual input schema. The Better Display fence and message aliases below are not a universal MCP Apps transport.
- If no inline renderer is available, save a standalone HTML artifact and explain how to open it. Do not claim that a plain code block was rendered.
The harness must discover this skill before automatic selection can work. Keep the whole `generative-mcpapps/` folder together, including references and examples, in a skill directory supported by that harness. Merely placing it inside a plugin repository does not prove that the current agent has loaded it.
## Build the widget
1. Choose local interaction (tabs, filters, calculations) or an explicit submission back to chat. For Better Display, submission fills the composer; the user still sends the message. It does not execute tools or commands automatically.
2. Inline critical CSS and JavaScript. Use semantic theme variables with readable fallbacks, a transparent body, and layouts that fit widths from 320px to 1200px. Avoid `100vh` and `min-h-screen`: Better Display measures content height and clamps it to 60–2400px.
3. Read [HTML boilerplate and theme tokens](references/html_boilerplate.md) when assembling a card. Read [Better Display host messages](references/sep1865_protocol.md) only when using host communication. The latter documents this plugin's implementation, not a full MCP Apps specification.
4. For a selectable local-state example, inspect [interactive_quiz.html](examples/interactive_quiz.html). Adapt its content and controls to the user's request.
## Deliver in Better Display
Output the complete HTML document directly in the answer:
````markdown
```mcp-app title="交互原型"
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>交互原型</title>
</head>
<body>
<!-- Include the widget's inline styles, content, and script here. -->
</body>
</html>
```
````
## Verify the result
Check the complete document, narrow-width layout, readable theme contrast, and the requested interaction. For a submission widget, verify that the chosen data reaches the chat composer; distinguish that from a sent message or completed agent action. A local-only widget needs no host submission. Report only the rendering and interaction actually observed in the available harness.

View File

@ -0,0 +1,153 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>双盲方案盲选评测器</title>
<style>
:root {
--app-bg: var(--background, #ffffff);
--card-bg: var(--card, #f8fafc);
--border-color: var(--border, #e2e8f0);
--text-main: var(--foreground, #0f172a);
--text-muted: var(--muted-foreground, #64748b);
--primary-color: var(--primary, #2563eb);
--primary-text: var(--primary-foreground, #ffffff);
--hover-bg: rgba(148, 163, 184, 0.12);
}
@media (prefers-color-scheme: dark) {
:root {
--app-bg: var(--background, #0f172a);
--card-bg: var(--card, #1e293b);
--border-color: var(--border, #334155);
--text-main: var(--foreground, #f8fafc);
--text-muted: var(--muted-foreground, #94a3b8);
}
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: transparent;
color: var(--text-main);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
padding: 12px;
}
.quiz-card {
background: var(--card-bg);
border: 1px solid var(--border-color);
border-radius: 12px;
padding: 16px;
max-width: 680px;
margin: 0 auto;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
border-bottom: 1px solid var(--border-color);
padding-bottom: 8px;
}
.title { font-size: 15px; font-weight: 600; }
.badge {
font-size: 11px;
padding: 2px 8px;
border-radius: 9999px;
background: var(--hover-bg);
color: var(--text-muted);
}
.prompt {
font-size: 13px;
color: var(--text-muted);
margin-bottom: 14px;
line-height: 1.4;
}
.options { display: flex; flex-direction: column; gap: 8px; margin-bottom: 14px; }
.option-btn {
text-align: left;
background: transparent;
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 10px 14px;
color: var(--text-main);
font-size: 13px;
cursor: pointer;
line-height: 1.4;
transition: all 0.15s ease;
}
.option-btn:hover { background: var(--hover-bg); }
.option-btn.selected {
border-color: var(--primary-color);
background: var(--hover-bg);
font-weight: 500;
}
.footer {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 10px;
}
.submit-btn {
background: var(--primary-color);
color: var(--primary-text);
border: none;
border-radius: 6px;
padding: 7px 16px;
font-size: 13px;
cursor: pointer;
}
.submit-btn:disabled { opacity: 0.5; cursor: not-allowed; }
</style>
</head>
<body>
<div class="quiz-card">
<div class="header">
<span class="title">⚡ 架构方案盲选评测</span>
<span class="badge" id="step-indicator">第 1/2 题</span>
</div>
<p class="prompt" id="question-text">
【场景】:订单超时自动关单,选 Redis 过期监听还是延迟消息队列?
</p>
<div class="options" id="options-container">
<button class="option-btn" onclick="selectOption('A')">A: 选 Redis 监听,轻量便捷无需额外运维</button>
<button class="option-btn" onclick="selectOption('B')">B: 坚决选延迟消息队列,Redis 监听会静默丢事件</button>
</div>
<div class="footer">
<span style="font-size: 12px; color: var(--text-muted);" id="status-text">请选择最符合你直觉的方案</span>
<button class="submit-btn" id="submit-btn" disabled onclick="submitChoice()">确认选择并提交</button>
</div>
</div>
<script>
let currentSelection = null;
function selectOption(key) {
currentSelection = key;
document.querySelectorAll('.option-btn').forEach((btn, idx) => {
btn.classList.toggle('selected', (idx === 0 && key === 'A') || (idx === 1 && key === 'B'));
});
document.getElementById('submit-btn').disabled = false;
}
function submitChoice() {
if (!currentSelection) return;
document.getElementById('status-text').innerText = "已发送到聊天输入框,请确认并发送。";
document.getElementById('submit-btn').disabled = true;
// 通过 Better Display 适配器将选择填入聊天输入框
window.parent.postMessage({
jsonrpc: "2.0",
id: "eval-" + Date.now(),
method: "ui/submit",
params: {
task: "architecture_quiz_completed",
choice: currentSelection,
desc: currentSelection === 'A' ? 'Redis 监听' : '延迟消息队列'
}
}, "*");
}
</script>
</body>
</html>

View File

@ -0,0 +1,122 @@
# HTML Boilerplate & Theme Tokens Reference
This document provides self-contained HTML/CSS templates optimized for MCP Apps iframes across dark and light modes.
---
## 1. Universal Theme Tokens Mapping
Host applications inject different CSS variables into iframes. Use this resilient CSS custom properties cascade to guarantee proper contrast regardless of the host:
```css
:root {
/* Surface & Background */
--app-bg: var(--background, #ffffff);
--card-bg: var(--card, #f8fafc);
--border-color: var(--border, #e2e8f0);
/* Typography */
--text-main: var(--foreground, #0f172a);
--text-muted: var(--muted-foreground, #64748b);
/* Accents & States */
--primary-color: var(--primary, #2563eb);
--primary-text: var(--primary-foreground, #ffffff);
--hover-bg: rgba(148, 163, 184, 0.12);
}
@media (prefers-color-scheme: dark) {
:root {
--app-bg: var(--background, #0f172a);
--card-bg: var(--card, #1e293b);
--border-color: var(--border, #334155);
--text-main: var(--foreground, #f8fafc);
--text-muted: var(--muted-foreground, #94a3b8);
}
}
```
---
## 2. Standard Responsive Card Template
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
/* Insert Theme Tokens here */
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: transparent;
color: var(--text-main);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
padding: 12px;
}
.mcp-card {
background: var(--card-bg);
border: 1px solid var(--border-color);
border-radius: 12px;
padding: 16px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
max-width: 720px;
margin: 0 auto;
}
.mcp-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}
.mcp-title {
font-size: 15px;
font-weight: 600;
color: var(--text-main);
}
.mcp-badge {
font-size: 11px;
padding: 2px 8px;
border-radius: 9999px;
background: var(--hover-bg);
color: var(--text-muted);
}
.btn-primary {
background: var(--primary-color);
color: var(--primary-text);
border: none;
border-radius: 6px;
padding: 8px 14px;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: opacity 0.15s ease;
}
.btn-primary:hover { opacity: 0.9; }
</style>
</head>
<body>
<div class="mcp-card">
<div class="mcp-header">
<h3 class="mcp-title" id="widget-title">交互组件标题</h3>
<span class="mcp-badge" id="widget-badge">Interactive</span>
</div>
<div id="widget-content">
<!-- 动态正文内容 -->
</div>
</div>
<script>
function notifyHost(action, payload) {
window.parent.postMessage({
jsonrpc: "2.0",
id: "action-" + Date.now(),
method: "ui/submit",
params: { action, payload }
}, "*");
}
</script>
</body>
</html>
```

View File

@ -0,0 +1,54 @@
# Better Display host messages
This documents the adapter in `src/client/McpAppFrame.tsx`, not the full SEP-1865 specification. Use these messages for Better Display's `mcp-app` iframe. Other hosts require their own documented transport and capabilities.
## Initialization and theme
The iframe can send `ui/initialize` with a JSON-RPC request ID. Better Display responds with `result.protocolVersion` and `result.hostContext`, including `theme`, `locale`, and `styles.variables`.
For compatibility, Better Display also sends an initial `ui/initialize` notification with those theme fields in `params`. Later theme changes arrive as `ui/notifications/host-context-changed`. The plugin injects a theme and height helper into HTML documents.
When handling parent messages, verify the source:
```javascript
window.addEventListener("message", (event) => {
if (event.source !== window.parent) return;
const msg = event.data;
if (!msg || msg.jsonrpc !== "2.0") return;
const context = msg.result?.hostContext || msg.params;
if (context?.theme) {
document.documentElement.dataset.theme = context.theme;
}
});
```
The sandbox has an opaque origin, so messages to the parent use `"*"`. The host checks that incoming messages originate from this iframe's content window.
## Submit a choice to the composer
```javascript
window.parent.postMessage({
jsonrpc: "2.0",
id: "choice-" + Date.now(),
method: "ui/submit",
params: { task: "quiz_completed", choice: "B", desc: "Selected option B" }
}, "*");
```
The host displays a receipt and fills the chat composer with a prompt derived from the parameters. The user must send it. `ui/update-model-context` is handled as the same composer action in this adapter; do not assume a silent model-context update. These submit handlers do not send a JSON-RPC success response, so do not wait indefinitely for one.
There is no `tools/call` handler in this adapter. Use submission for a requested follow-up instead of claiming that a click executed a tool.
## Readiness and sizing
`ui/ready` and `ui/notifications/initialized` mark the iframe ready. The injected ResizeObserver normally handles height automatically. A widget may also send:
```javascript
window.parent.postMessage({
jsonrpc: "2.0",
method: "ui/resize",
params: { height: document.body.scrollHeight }
}, "*");
```
The host accepts positive finite heights and clamps them to 60–2400px. No `ui/updateState` handler is provided by this adapter.

View File

@ -0,0 +1,72 @@
import { Fragment, memo } from 'react';
import type { RefObject } from 'react';
import type { ChatConversationViewNode, ChatNode, ChatNodeKind } from '@deepseek-ai/dsh-client-ui-chat/client';
import { Blocks, CopyAnswer } from './Blocks.js';
import { ReasoningCard } from './ReasoningCard.js';
import { OfficialActions, OfficialAssistantBody } from './OfficialContent.js';
import { Disclosure, ProcessFragment } from './motion.js';
import { FoldSummaryText } from './LiveFold.js';
import { assistantSegments, forkAnchorSeq, hasVisibleBody, isEarlierNarration } from './projection.js';
import type { TurnBoundary } from './projection.js';
import type { BlockRenderProps, ReaderProps } from './types.js';
import css from './Reader.module.css';
function isNode<K extends ChatNodeKind>(node: ChatConversationViewNode, kind: K): node is ChatNode<K> {
return node.kind === kind;
}
type SeatProps = BlockRenderProps & Pick<ReaderProps, 'useChat' | 'sessionId'> & {
nodeKey: string; boundary: TurnBoundary; pinned?: boolean; processOpen?: boolean;
};
export const AssistantNode = memo(function AssistantNode({ useChat, nodeKey, boundary, processOpen = false, pinned = false, folded = false, partStart, seamSummary, seamAfter = false, motion, onRead, returnFocusTo, ...render }: SeatProps & {
motion: boolean; onRead: () => void; returnFocusTo: RefObject<HTMLButtonElement>; partStart?: number; folded?: boolean;
seamSummary?: string; seamAfter?: boolean;
}) {
const node = useChat(snapshot => snapshot.nodes.get(nodeKey));
if (!node || node.visibility === 'hidden' || !isNode(node, 'assistant-step')) return null;
const data = node.data;
const parts = assistantSegments(data.blocks);
const earlier = isEarlierNarration(data, boundary);
const hasToolCalls = data.blocks.some(block => block.kind === 'tool-call');
const isProcessStep = earlier || folded || hasToolCalls || (boundary.latestStep > 0 && data.step < boundary.latestStep);
const body = data.blocks.filter(block => block.kind !== 'reasoning' && block.kind !== 'tool-call');
const visible = partStart === undefined ? parts : parts.filter(part => part.start === partStart);
const bodyProps = { streaming: data.status === 'running', holdFormatting: pinned, startedAt: data.time, interrupted: data.status === 'interrupted', liveText: true as const };
return <>{visible.map(part => {
const index = parts.findIndex(item => item.start === part.start);
const last = index === parts.length - 1;
if (part.kind === 'reasoning') return <ProcessFragment key={part.start} open={processOpen} motion={motion} onRead={onRead} returnFocusTo={returnFocusTo} nodeKey={nodeKey} framed>
<ReasoningCard step={data.step} active={processOpen && boundary.status === 'open' && data.step === boundary.latestStep} motion={motion} selected={pinned} onRead={onRead}>
<Blocks {...render} blocks={part.blocks} streaming={data.status === 'running' && last && data.blocks.at(-1)?.kind === 'reasoning'}
holdFormatting={pinned} startedAt={data.time} interrupted={data.status === 'interrupted'} liveText />
</ReasoningCard>
</ProcessFragment>;
if (!hasVisibleBody(part.blocks)) return null;
// Narration stays body prose and never enters a disclosure. The seam in
// the gap summarises folded process between two body blocks. A foreign
// assistant-step renderer receives these original blocks; Reader markdown,
// including the text transform, is only the fallback.
const isFinalAnswer = !isProcessStep;
return <Fragment key={part.start}>
{seamSummary && <div className={css.processSeamRow} data-reader-process-seam data-reader-process-seam-summary={seamSummary}>
<Disclosure open={false} onChange={() => onRead()} ariaLabel="被折叠的过程"
label={<FoldSummaryText summary={seamSummary} motion={false} />} />
</div>}
<article className={css.answer} data-reader-body data-reader-anchor data-reader-key={nodeKey} data-reader-source-start={part.start}
data-reader-seam-after={seamAfter || undefined} data-answer-status={data.status} data-answer-phase={isFinalAnswer ? 'body' : 'process'}>
<OfficialAssistantBody {...render} node={node} blocks={part.blocks} {...bodyProps} />
{isFinalAnswer && last && data.status === 'interrupted' && <span className={css.stopped}>已停止</span>}
{isFinalAnswer && last && data.status !== 'running' && boundary.status === 'closed' && (
<CopyAnswer blocks={body} onFork={(() => {
// The fork anchor must be the durable closing message seq (same as
// the official turn-tail branch). AssistantChatData carries no seq
// of its own; passing it would fork the whole session instead.
const anchor = forkAnchorSeq([data.finalNode, { seq: render.forkSeq }]);
return render.forkAt && anchor !== undefined ? () => render.forkAt!(anchor) : undefined;
})()} metrics={render.metrics} extraActions={<OfficialActions official={render.official} messageId={data.finalNode?.messageId} />} />
)}
</article>
</Fragment>;
})}</>;
});

252
src/client/Blocks.tsx Normal file
View File

@ -0,0 +1,252 @@
import { Component, Fragment, memo, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
import type { AssistantBlock, UserMessageNode } from '@deepseek-ai/dsh-client-ui-conversation/client';
import { JsonBlock, MarkdownText, writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives';
import { ComposerFillContext, McpAppFrame } from './McpAppFrame.js';
import { formatMessageClock } from './message-chrome.js';
import { markdownLabels, truncatedJsonLabel } from './primitive-labels.js';
import type { BlockRenderProps, ReaderBlockOwner } from './types.js';
import { useStreamingText } from './streaming.js';
import { MotionMarkdown, MotionPlainText } from './word-motion.js';
import { activeTextTransform, displayStreaming, originalAnswerText, readerBlockOwner, useDisplayText } from './text-transform.js';
import type { TextTransformRegistry } from './text-transform.js';
import css from './Reader.module.css';
const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
export class BlockBoundary extends Component<{ children: ReactNode }, { failed: boolean; detail: string }> {
state = { failed: false, detail: '' };
// Temporary diagnostic: surface the reason inline so a recurrence is reportable
// without a console. Remove once the reported block crash is identified.
static getDerivedStateFromError(error: unknown) {
const err = error as { message?: unknown } | undefined;
return { failed: true, detail: String(err?.message ?? error).slice(0, 160) };
}
render() {
return this.state.failed
? <div className={css.notice}>此内容暂时无法在阅读页显示;原对话中的记录未受影响。<span data-reader-block-error style={{ opacity: .65 }}>({this.state.detail})</span></div>
: this.props.children;
}
}
export const ImageBlock = memo(function ImageBlock({ attachment, loadImage }: {
attachment: ImageAttachmentRef; loadImage: BlockRenderProps['loadImage'];
}) {
const [attempt, setAttempt] = useState(0);
const [url, setUrl] = useState<string | null>(null);
const [error, setError] = useState(false);
const [decoded, setDecoded] = useState(false);
const dialog = useRef<HTMLDialogElement>(null);
const opener = useRef<HTMLButtonElement>(null);
useEffect(() => {
let active = true;
let owned: string | null = null;
const timeout = setTimeout(() => { if (active) { setError(true); active = false; } }, 20000);
setError(false); setDecoded(false); setUrl(null);
void loadImage(attachment).then(result => {
if (!active) return;
clearTimeout(timeout);
if (!IMAGE_TYPES.has(result.mediaType)) throw new Error('Unsupported image media type');
const bytes = Uint8Array.from(result.data);
owned = URL.createObjectURL(new Blob([bytes.buffer], { type: result.mediaType }));
setUrl(owned);
}).catch(() => { clearTimeout(timeout); if (active) setError(true); });
return () => { active = false; clearTimeout(timeout); if (owned) URL.revokeObjectURL(owned); };
}, [attachment.attachmentId, attempt, loadImage]);
const width = Number.isFinite(attachment.width) && attachment.width > 0 ? attachment.width : 4;
const height = Number.isFinite(attachment.height) && attachment.height > 0 ? attachment.height : 3;
return <figure className={css.imageFigure} data-reader-image data-image-state={error ? 'error' : decoded ? 'ready' : 'loading'}>
<div className={css.imageFrame} style={{ aspectRatio: `${width} / ${height}` }}>
{!error && url && <button ref={opener} type="button" className={css.imageOpen} aria-label={`放大图片${attachment.name ? `:${attachment.name}` : ''}`} onClick={() => dialog.current?.showModal()}>
<img src={url} alt={attachment.name ?? '会话图片'} width={width} height={height} onLoad={() => setDecoded(true)} onError={() => setError(true)} data-ready={decoded} />
</button>}
{(!decoded || error) && <div className={css.imagePlaceholder}>
<span>{error ? '图片未能加载' : '正在加载图片'}</span>
{error && <button type="button" className={css.textButton} onClick={() => setAttempt(value => value + 1)}>重试</button>}
</div>}
</div>
{attachment.name && <figcaption>{attachment.name}</figcaption>}
<dialog ref={dialog} className={css.imageDialog} aria-label="图片预览" onClose={() => opener.current?.focus()} onClick={event => { if (event.target === dialog.current) dialog.current?.close(); }}>
<button type="button" autoFocus className={css.dialogClose} aria-label="关闭图片预览" onClick={() => dialog.current?.close()}>×</button>
{url && <img src={url} alt={attachment.name ?? '会话图片'} />}
</dialog>
</figure>;
});
export function contentBlocks(content: UserMessageNode['content']): AssistantBlock[] {
return content.map(block => {
if (block.type === 'text') return { kind: 'text', text: block.text };
if (block.type === 'image') return { kind: 'image', attachment: block.attachment };
return { kind: 'other', block };
});
}
type TextPresentation = { startedAt?: number; interrupted?: boolean; liveText?: boolean };
type MarkdownStreamProps = {
text: string;
streaming: boolean;
holdFormatting: boolean;
kind?: 'body' | 'reasoning';
fileMentions?: BlockRenderProps['fileMentions'];
transformed?: boolean;
} & TextPresentation;
function MarkdownStream({ text, streaming, holdFormatting, startedAt, interrupted = false, liveText = false, kind = 'body', fileMentions, transformed = false }: MarkdownStreamProps) {
const root = useRef<HTMLDivElement>(null);
const presentation = useStreamingText(text, streaming, { startedAt, interrupted: interrupted || !liveText, selected: holdFormatting });
// Native Markdown changes block keys for its full final parse. Keep the last
// committed mode while this answer is selected, then finish formatting on
// deselection. Business status and the source text still update normally.
const committedMode = useRef(streaming);
const effectiveMode = holdFormatting ? committedMode.current : presentation.formatStreaming;
useLayoutEffect(() => { committedMode.current = effectiveMode; }, [effectiveMode]);
return <div ref={root} className={css.readingText} data-reader-text data-reader-text-kind={kind} data-received-length={text.length} data-shown-length={presentation.text.length}
data-presentation-pending={presentation.pending || undefined} data-motion-style="opacity-blur" data-ud-motion="reader-text-arrival" data-ud-motion-type="reveal" data-ud-motion-no-flash="true"
data-text-transform={transformed ? (streaming ? 'live' : 'final') : undefined}>
<MotionMarkdown text={presentation.text} streaming={effectiveMode} enabled={liveText && presentation.reveal && effectiveMode} revision={presentation.revision} fileMentions={fileMentions} />
</div>;
}
function TransformedMarkdown({ registry, blockKey, source, text, streaming, ...props }: MarkdownStreamProps & { registry: TextTransformRegistry; blockKey: string; source: ReaderBlockOwner['source'] }) {
const shown = useDisplayText(registry, { text, streaming, blockKey, kind: 'body', source });
return <MarkdownStream {...props} text={shown.text} streaming={displayStreaming(streaming, shown, true)} transformed />;
}
function ReadingMarkdown({ blockKey, source, ...props }: MarkdownStreamProps & { blockKey: string; source: ReaderBlockOwner['source'] }) {
const registry = activeTextTransform();
if (registry?.has('body')) return <TransformedMarkdown registry={registry} blockKey={blockKey} source={source} {...props} />;
return <MarkdownStream {...props} />;
}
type ReasoningStreamProps = { blockKey: string; text: string; streaming: boolean; holdFormatting: boolean; transformed?: boolean } & TextPresentation;
function ReasoningStream({ blockKey, text, streaming, holdFormatting, startedAt, interrupted = false, liveText = false, transformed = false }: ReasoningStreamProps) {
const presentation = useStreamingText(text, streaming, { startedAt, interrupted: interrupted || !liveText, selected: holdFormatting });
return <div className={css.readingText} data-reader-text data-reader-text-kind="reasoning" data-reader-reasoning-block-key={blockKey} data-received-length={text.length} data-shown-length={presentation.text.length}
data-presentation-pending={presentation.pending || undefined} data-motion-style="opacity-blur" data-ud-motion="reader-text-arrival" data-ud-motion-type="reveal" data-ud-motion-no-flash="true"
data-text-transform={transformed ? (streaming ? 'live' : 'final') : undefined}>
<MotionPlainText text={presentation.text} enabled={liveText && presentation.reveal} revision={presentation.revision} />
</div>;
}
function TransformedReasoning({ registry, blockKey, source, text, streaming, ...props }: ReasoningStreamProps & { registry: TextTransformRegistry; blockKey: string; source: ReaderBlockOwner['source'] }) {
const shown = useDisplayText(registry, { text, streaming, blockKey, kind: 'reasoning', source });
return <ReasoningStream {...props} blockKey={blockKey} text={shown.text} streaming={displayStreaming(streaming, shown, true)} transformed />;
}
function ReadingReasoning({ blockKey, source, ...props }: ReasoningStreamProps & { blockKey: string; source: ReaderBlockOwner['source'] }) {
const registry = activeTextTransform();
if (registry?.has('reasoning')) return <TransformedReasoning registry={registry} blockKey={blockKey} source={source} {...props} />;
return <ReasoningStream {...props} blockKey={blockKey} />;
}
function fallback(block: AssistantBlock, streaming: boolean, source: ReaderBlockOwner['source'], loadImage: BlockRenderProps['loadImage'], fillComposer: BlockRenderProps['fillComposer'], holdFormatting: boolean, presentation: TextPresentation, blockKey: string, fileMentions?: BlockRenderProps['fileMentions']): ReactNode {
switch (block.kind) {
case 'text': return source === 'user' ? <MarkdownText text={block.text} labels={markdownLabels} /> : <ReadingMarkdown text={block.text} streaming={streaming} holdFormatting={holdFormatting} {...presentation} fileMentions={fileMentions} blockKey={blockKey} source={source} />;
case 'image': return <ImageBlock attachment={block.attachment} loadImage={loadImage} />;
case 'reasoning': return <ReadingReasoning text={block.text} streaming={streaming} holdFormatting={holdFormatting} {...presentation} blockKey={blockKey} source={source} />;
case 'tool-call': return <JsonBlock label={`工具参数 · ${block.name}`} payload={block.argsRaw} truncatedLabel={truncatedJsonLabel} />;
case 'other': {
const raw = block.block;
if (raw && typeof raw === 'object') {
const item = raw as Record<string, unknown>;
if ((item.type === 'mcp-app' || item.type === 'mcpapp' || item.type === 'ui') && typeof item.html === 'string') {
return <McpAppFrame html={item.html} title={typeof item.title === 'string' ? item.title : undefined} fillComposer={fillComposer} />;
}
}
return <div className={css.unknown}>
<p>此内容类型尚未接入阅读页,原始内容已保留。</p>
<JsonBlock label="查看原始内容" payload={block.block} truncatedLabel={truncatedJsonLabel} />
</div>;
}
}
}
export const Blocks = memo(function Blocks({ blocks, streaming = false, source = 'assistant', holdFormatting = false, startedAt, interrupted, liveText, renderSlotChain, loadImage, fillComposer, fileMentions }: BlockRenderProps & TextPresentation & {
blocks: readonly AssistantBlock[]; streaming?: boolean; source?: ReaderBlockOwner['source']; holdFormatting?: boolean;
}) {
const reactId = useId();
return <ComposerFillContext.Provider value={fillComposer}>
<div className={css.blocks} data-streaming={streaming || undefined}>
{blocks.map((block, index) => <BlockBoundary key={block.kind === 'image' ? `image:${block.attachment.attachmentId}:${index}` : `${index}:${block.kind}`}>
<Fragment>{renderSlotChain('dsh-better-display.block', readerBlockOwner(block, streaming, source, { startedAt, interrupted, liveText }, holdFormatting), { fallback: fallback(block, streaming, source, loadImage, fillComposer, holdFormatting, { startedAt, interrupted, liveText }, `${reactId}:${index}:${block.kind}`, fileMentions) })}</Fragment>
</BlockBoundary>)}
</div>
</ComposerFillContext.Provider>;
});
import { TurnMetrics } from './TurnMetrics.js';
function CopyGlyph() {
return <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><rect x="5" y="5" width="8" height="8" rx="1.5" /><path d="M3 10H2.8A.8.8 0 0 1 2 9.2V2.8a.8.8 0 0 1 .8-.8h6.4a.8.8 0 0 1 .8.8V3" /></svg>;
}
function useCopyReceipt() {
const [receipt, setReceipt] = useState('');
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => () => { if (timer.current) clearTimeout(timer.current); }, []);
const copy = async (text: string) => {
const accepted = await writeClipboard(text);
setReceipt(accepted ? '已复制' : '未能复制,请手动选择文字');
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(() => setReceipt(''), 2000);
};
return { receipt, copy };
}
function MessageClock({ time }: { time: number }) {
return <time className={css.messageClock} dateTime={new Date(time).toISOString()}>{formatMessageClock(time)}</time>;
}
export function CopyAnswer({ blocks, onFork, metrics, extraActions }: { blocks: readonly AssistantBlock[]; onFork?: () => void; metrics?: BlockRenderProps['metrics']; extraActions?: ReactNode }) {
const { receipt, copy } = useCopyReceipt();
// Session text. A display transformer does not write these blocks.
const text = originalAnswerText(blocks);
const endedAt = metrics?.endedAt;
const hasMetrics = metrics !== undefined && (metrics.usage !== undefined || metrics.runMs !== undefined || endedAt !== undefined);
if (!text.trim() && !onFork && !hasMetrics) return null;
return <div className={css.answerActions}>
{text.trim() !== '' && (
<button type="button" className={css.iconButton} aria-label="复制回答" title="复制回答" onClick={() => { void copy(text); }}>
<CopyGlyph />
</button>
)}
{extraActions}
{onFork && (
<button
type="button"
className={css.iconButton}
aria-label="以此处为基础创建分叉会话"
title="以此处为基础创建分叉会话 (Fork)"
onClick={onFork}
>
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.2">
<circle cx="4.5" cy="3.5" r="1.8" />
<circle cx="4.5" cy="12.5" r="1.8" />
<circle cx="11.5" cy="5.5" r="1.8" />
<path d="M4.5 5.5v5M4.5 8c2.5 0 4.5-1 7-2.5" strokeLinecap="round" />
</svg>
</button>
)}
{metrics && <TurnMetrics usage={metrics.usage} runMs={metrics.runMs} tokensPerSecond={metrics.tokensPerSecond} ttftMs={metrics.ttftMs} />}
{endedAt !== undefined && <MessageClock time={endedAt} />}
<span role="status" className={css.meta}>{receipt}</span>
</div>;
}
export function UserMessageActions({ text, time }: { text: string; time?: number }) {
const { receipt, copy } = useCopyReceipt();
const hasText = text.trim() !== '';
if (!hasText && time === undefined) return null;
return <div className={css.userActions}>
{time !== undefined && <MessageClock time={time} />}
{hasText && (
<button type="button" className={css.iconButton} aria-label="复制消息" title="复制消息" onClick={() => { void copy(text); }}>
<CopyGlyph />
</button>
)}
<span role="status" className={css.meta}>{receipt}</span>
</div>;
}

View File

@ -0,0 +1,239 @@
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import type { ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client';
import type { ReaderProps } from './types.js';
import type { LiveStep, LiveTurnItem } from './live-turn.js';
import { collapseRows, containsNewUser, flowRows, FOLD_TIMING, retiringKeys } from './fold-choreography.js';
import type { FoldPhase } from './fold-choreography.js';
import { Disclosure } from './motion.js';
import { FoldSummaryText } from './LiveFold.js';
import { DiffStat } from './DiffPanel.js';
import { StreamMotionContext } from './streaming.js';
import css from './Reader.module.css';
import { useSummaryLane } from './StickyLane.js';
const FlowSnapshot = createContext<ChatSnapshot | null>(null);
/** Public projection only. Descendants cannot leak live data through a frozen frame. */
export const useFlowChat: ReaderProps['useChat'] = selector => {
const snapshot = useContext(FlowSnapshot);
if (!snapshot) throw new Error('Flow snapshot provider missing');
return selector(snapshot);
};
export type PresentationFrame = { items: readonly LiveTurnItem[]; snapshot: ChatSnapshot };
type Transaction = {
phase: FoldPhase; shown: PresentationFrame; target: PresentationFrame;
retiring: readonly string[]; beforeKeys: ReadonlySet<string>;
};
const idle = (frame: PresentationFrame): Transaction => ({ phase: 'idle', shown: frame, target: frame, retiring: [], beforeKeys: new Set() });
function Summary({ item, open, onChange, motion }: {
item: Extract<LiveTurnItem, { kind: 'fold' }>; open: boolean; onChange: (open: boolean) => void; motion: boolean;
}) {
const button = useRef<HTMLButtonElement>(null);
return <div data-reader-live-fold data-expanded={open} data-reader-live-fold-summary={item.summary}>
<div className={css.summaryRow}>
<Disclosure open={open} onChange={onChange} buttonRef={button} ariaLabel="此前步骤"
label={<FoldSummaryText summary={item.summary} motion={motion} />} />
<DiffStat steps={item.steps} label={item.summary} />
</div>
</div>;
}
/** Manual disclosure shares the measured-size path; children survive until finish. */
function FlowCell({ hidden, instant, motion, rowKey, children, summary = false }: {
hidden: boolean; instant: boolean; motion: boolean; rowKey: string; children: ReactNode; summary?: boolean;
}) {
const ref = useRef<HTMLDivElement>(null);
useSummaryLane(ref, summary);
const [present, setPresent] = useState(!hidden);
const previous = useRef(hidden);
if (!hidden && !present) setPresent(true);
useLayoutEffect(() => {
const el = ref.current;
const changed = previous.current !== hidden;
previous.current = hidden;
if (!el) return;
if (!changed || instant || !motion) { setPresent(!hidden); return; }
const height = el.scrollHeight;
const animation = el.animate([
{ height: `${hidden ? height : 0}px`, opacity: hidden ? 1 : 0 },
{ height: `${hidden ? 0 : height}px`, opacity: hidden ? 0 : 1 },
], { duration: 220, easing: 'cubic-bezier(.4,0,.2,1)', fill: 'both' });
el.dispatchEvent(new CustomEvent('reader-layout-start', { bubbles: true }));
let released = false;
const release = () => { if (!released) { released = true; el.dispatchEvent(new CustomEvent('reader-layout-end', { bubbles: true })); } };
// Do NOT cancel here. `fill: 'both'` is what currently holds the cell at its
// collapsed size; cancelling on finish drops that fill before React has
// committed the removal, so the cell snaps back to full height for one frame
// — the flash before it disappears. The state change alone retires it; the
// cleanup below cancels the animation once that has actually rendered.
let settled = false;
const settle = () => {
if (settled) return;
settled = true;
// Expanding retires nothing: the fill only pins the measured height. Drop it
// now — if the cell's content later shrinks, the stale fill would hold the
// empty space open. Collapsing still keeps the fill until React commits
// the removal (see the comment above), then the cleanup cancels it.
if (!hidden) animation.cancel();
setPresent(!hidden);
release();
};
animation.onfinish = settle;
// \`fill: 'both'\` pins the opening keyframe for the whole run, so if this
// animation never advances the cell stays at height 0 and opacity 0: the row is
// in the DOM but reads as "clicked it and nothing happened". A cancelled
// animation, or one inside a subtree the compositor skips, never fires
// onfinish. Fall back to the state change on a deadline; the cleanup then
// cancels the animation and drops the fill.
const deadline = window.setTimeout(settle, 220 + 240);
return () => { window.clearTimeout(deadline); animation.cancel(); release(); };
// `present` is a dependency so that committing it re-runs this effect: the
// cleanup then cancels the finished animation *after* the removal has been
// applied, which is the only moment the fill can be dropped safely. Without
// it the animation was never cancelled at all and every folded cell kept one.
}, [hidden, instant, motion, present]);
return <div ref={ref} className={css.flowCell} data-flow-key={rowKey} data-flow-summary={summary || undefined}
hidden={hidden && !present} aria-hidden={hidden || undefined} {...(hidden ? { inert: '' } : {})}>
{present && <div className={css.flowCellInner}>{children}</div>}
</div>;
}
export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpenChange, processOpen, renderStep, id }: {
frame: PresentationFrame; motion: boolean; enabled: boolean; urgent: boolean;
open: Readonly<Record<string, boolean>>; onOpenChange: (key: string, value: boolean) => void;
processOpen: boolean; renderStep: (step: LiveStep, folded: boolean) => ReactNode; id: string;
}) {
const root = useRef<HTMLDivElement>(null);
const stream = useContext(StreamMotionContext);
const latest = useRef(frame); latest.current = frame;
const [visible, setVisible] = useState(() => !document.hidden);
const [state, setState] = useState<Transaction>(() => idle(frame));
const bypass = !motion || !enabled || urgent || !visible || !processOpen || (state.phase !== 'idle' && Object.values(open).some(Boolean));
// Render-time adjustment prevents even one paint of the new authoritative layout.
if ((bypass || containsNewUser(state.shown.items, frame.items)) && (state.phase !== 'idle' || state.shown !== frame)) {
setState(idle(frame));
} else if (state.phase === 'idle' && state.shown !== frame) {
const retiring = retiringKeys(state.shown.items, frame.items, open);
setState(retiring.length ? { ...state, phase: 'collapse', target: frame, retiring,
beforeKeys: new Set(flowRows(state.shown.items).map(row => row.key)) } : idle(frame));
}
useEffect(() => {
const update = () => setVisible(!document.hidden);
document.addEventListener('visibilitychange', update);
return () => document.removeEventListener('visibilitychange', update);
}, []);
useLayoutEffect(() => {
if (state.phase !== 'collapse') return;
const el = root.current;
if (!el) return;
const retiring = new Set(state.retiring);
const animations: Animation[] = [];
el.dispatchEvent(new CustomEvent('reader-layout-start', { bubbles: true }));
for (const cell of el.querySelectorAll<HTMLElement>(':scope > [data-flow-key]')) {
const key = cell.dataset.flowKey!;
const isHeader = cell.dataset.flowSummary && !state.beforeKeys.has(key);
if (!retiring.has(key) && !isHeader) continue;
const height = cell.getBoundingClientRect().height;
animations.push(cell.animate(isHeader ? [
{ height: '0px', opacity: 0 }, { height: `${height}px`, opacity: 1 },
] : [
{ height: `${height}px`, opacity: 1 },
{ height: `${height * .5}px`, opacity: .85, offset: .5 },
{ height: '0px', opacity: 0 },
], { duration: FOLD_TIMING.collapse, easing: 'cubic-bezier(.4,0,.2,1)', fill: 'both' }));
}
let cancelled = false;
// Coalesce everything received during shrink, once. No animation restarts.
// Idempotent and phase-checked: the promise and the deadline race, and
// whichever arrives first wins while the other becomes a no-op.
let advanced = false;
const advance = () => {
if (cancelled || advanced) return;
advanced = true;
setState(current => current.phase === 'collapse' ? { ...current, phase: 'count', target: latest.current } : current);
};
// `finished` rejects when an animation is cancelled and can stay pending when a
// compositor never runs it to completion, so the promise alone cannot be the only
// way out of this phase. Without a deadline a stalled phase would hold the frame
// source at `shown` and keep the reveal paused, which reads as a frozen turn
// until the view remounts.
const deadline = window.setTimeout(advance, FOLD_TIMING.collapse + FOLD_TIMING.watchdogSlack);
Promise.all(animations.map(animation => animation.finished)).then(advance, advance);
return () => {
cancelled = true;
window.clearTimeout(deadline);
animations.forEach(animation => animation.cancel());
el.dispatchEvent(new CustomEvent('reader-layout-end', { bubbles: true }));
};
}, [state.phase]);
useEffect(() => {
if (state.phase !== 'count' && state.phase !== 'settle' && state.phase !== 'reveal') return;
const phase = state.phase;
let done = false;
const finish = () => {
if (done) return;
done = true;
setState(current => {
if (current.phase !== phase) return current;
if (phase === 'count') return { ...current, phase: 'settle' };
if (phase === 'settle') return { ...current, phase: 'reveal' };
return idle(current.target);
});
};
// Count visible presentation time, not a timer that can expire before a
// busy browser paints. Each attention phase must get actual rendered frames.
let elapsed = 0;
let previous: number | undefined;
let raf = 0;
const tick = (now: number) => {
if (previous !== undefined) elapsed += Math.min(40, now - previous);
previous = now;
if (elapsed < FOLD_TIMING[phase]) { raf = requestAnimationFrame(tick); return; }
finish();
};
raf = requestAnimationFrame(tick);
// A hidden tab gets no frames at all, so the frame counter above would never
// reach its budget and the phase would hold forever. The wall-clock deadline
// advances it anyway; a non-idle phase is what freezes the turn.
const deadline = window.setTimeout(finish, FOLD_TIMING[phase] + FOLD_TIMING.watchdogSlack);
return () => { window.clearTimeout(deadline); cancelAnimationFrame(raf); };
}, [state.phase]);
useLayoutEffect(() => {
if (state.phase !== 'reveal' || !root.current) return;
const el = root.current;
el.dispatchEvent(new CustomEvent('reader-layout-start', { bubbles: true }));
// Opacity alone still inserts the new layout in one frame. Open real space
// first; text stays paused until this entry finishes, then catches up.
const animations = Array.from(el.children).filter(child => !(child as HTMLElement).hidden && !state.beforeKeys.has((child as HTMLElement).dataset.flowKey!))
.map(child => child.animate([
{ height: '0px', opacity: 0 },
{ height: `${child.getBoundingClientRect().height}px`, opacity: 1 },
], { duration: FOLD_TIMING.reveal, easing: 'cubic-bezier(.4,0,.2,1)', fill: 'both' }));
return () => {
animations.forEach(animation => animation.cancel());
el.dispatchEvent(new CustomEvent('reader-layout-end', { bubbles: true }));
};
}, [state.phase]);
const blocked = state.phase === 'collapse' || state.phase === 'count' || state.phase === 'settle';
const source = state.phase === 'idle' || state.phase === 'collapse' ? state.shown : state.target;
const rows = state.phase === 'collapse' ? collapseRows(state.shown.items, state.target.items) : flowRows(source.items);
return <FlowSnapshot.Provider value={source.snapshot}>
<StreamMotionContext.Provider value={{ ...stream, paused: state.phase !== 'idle', resumed: state.phase === 'reveal' }}>
<div id={id} ref={root} className={css.choreographedFlow} data-reader-flow data-reader-transition={state.phase} data-ud-motion="fold-choreography">
{rows.map(row => {
if (row.kind === 'summary') return <FlowCell key={row.key} rowKey={row.key} hidden={false} instant motion={motion} summary>
<Summary item={row.item} open={processOpen && !!open[row.key]} onChange={value => onOpenChange(row.key, value)} motion={motion && state.phase !== 'collapse'} />
</FlowCell>;
const hidden = !!row.foldKey && (!processOpen || !open[row.foldKey]) || (blocked && state.phase !== 'collapse' && !state.beforeKeys.has(row.key));
// Keep retiring child props unchanged until it has actually shrunk.
return <FlowCell key={row.key} rowKey={row.key} hidden={hidden} instant={state.phase !== 'idle'} motion={motion}>
{renderStep(row.step, !!row.foldKey)}
</FlowCell>;
})}
</div>
</StreamMotionContext.Provider>
</FlowSnapshot.Provider>;
}

View File

@ -0,0 +1,25 @@
import { useRef } from 'react';
import css from './Reader.module.css';
import { Disclosure } from './motion.js';
import { FoldSummaryText } from './LiveFold.js';
import { foldSummary } from './live-turn.js';
import { DiffStat } from './DiffPanel.js';
import { usePublishedHeight } from './StickyLane.js';
import type { LiveStep } from './live-turn.js';
/** Keep process counts discoverable after the live-fold presentation retires. */
export function ClosedProcessSummary({ steps, open, onChange, controls }: {
steps: readonly LiveStep[]; open: boolean; onChange: (value: boolean) => void; controls: string;
}) {
const button = useRef<HTMLButtonElement>(null);
const lane = usePublishedHeight('--reader-summary-height');
if (!steps.length) return null;
const summary = foldSummary(steps);
return <div ref={lane} className={css.closedProcessSummary} data-reader-closed-summary={summary}>
<div className={css.summaryRow}>
<Disclosure open={open} onChange={onChange} controls={controls} buttonRef={button} ariaLabel="本轮过程详情"
label={<FoldSummaryText summary={summary} motion={false} />} />
<DiffStat steps={steps} label={summary} />
</div>
</div>;
}

124
src/client/DiffPanel.tsx Normal file
View File

@ -0,0 +1,124 @@
import { useLayoutEffect, useMemo, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import { DiffBlock, diffTotals } from '@deepseek-ai/dsh-client-ui-primitives';
import css from './Reader.module.css';
import { diffBlockLabels } from './primitive-labels.js';
import { FOLD_TIMING } from './fold-choreography.js';
import { foldDiffHunks } from './tool-activity.js';
import type { LiveStep } from './live-turn.js';
/**
* Reveals and withdraws its child by animating real height, in the plugin's own
* motion language. Height is the animated property rather than transform because
* the panel pushes the transcript down and the reading scroll measures that
* growth; the curve and duration are the fold choreography's, so this reads as
* the same gesture as opening a digest.
*
* Closing animates too: the child stays mounted until the shrink finishes, which
* is why the owner keeps it alive on an `open` flag instead of unmounting it.
*/
function MorphPanel({ open, children, onSettled, onClosed }: {
open: boolean; children: ReactNode; onSettled?: (element: HTMLElement) => void; onClosed: () => void;
}) {
const ref = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const element = ref.current;
if (!element) return;
element.dispatchEvent(new CustomEvent('reader-layout-start', { bubbles: true }));
let released = false;
const release = () => { if (!released) { released = true; element.dispatchEvent(new CustomEvent('reader-layout-end', { bubbles: true })); } };
if (typeof element.animate !== 'function') { release(); if (!open) onClosed(); return; }
const height = element.scrollHeight;
const frames = open
? [{ height: '0px', opacity: 0, transform: 'translateY(-6px)' },
{ height: `${height}px`, opacity: 1, transform: 'translateY(0)' }]
: [{ height: `${height}px`, opacity: 1 },
{ height: '0px', opacity: 0 }];
const animation = element.animate(frames, {
duration: FOLD_TIMING.reveal + FOLD_TIMING.settle,
easing: 'cubic-bezier(.4,0,.2,1)',
});
let settled = false;
const settle = () => {
if (settled) return;
settled = true;
release();
if (open) {
element.style.height = 'auto';
element.style.overflow = 'visible';
onSettled?.(element);
} else {
onClosed();
}
};
animation.onfinish = settle;
const deadline = window.setTimeout(settle, FOLD_TIMING.reveal + FOLD_TIMING.settle + 240);
return () => { window.clearTimeout(deadline); animation.cancel(); release(); };
}, [open]);
return <div ref={ref} className={css.diffOverlay}>{children}</div>;
}
/**
* Keeps a newly opened panel on screen.
*
* Opening grows the row downward, so a badge near the fold reveals its card below
* the viewport and the reader has to chase it. The scroll container is not known
* here, so the nearest scrollable ancestor is found and the card's head is brought
* to the top of it — the same thing a jump-to-anchor does.
*/
function revealPanel(element: HTMLElement): void {
let port: HTMLElement | null = element.parentElement;
while (port && port.scrollHeight <= port.clientHeight + 1) port = port.parentElement;
if (!port) { element.scrollIntoView({ block: 'nearest' }); return; }
const gap = element.getBoundingClientRect().top - port.getBoundingClientRect().top;
// Already fully visible: leave the scroll alone rather than jumping on every open.
if (gap >= 0 && element.getBoundingClientRect().bottom <= port.getBoundingClientRect().bottom) return;
port.scrollTop += gap - 8;
}
/**
* Line counts for everything a folded run of steps changed.
*
* A run that touched no files renders nothing, so an ordinary process digest is
* unchanged. Clicking the counts opens the same diff surface the official tool
* row uses — one file at a time, red removed / green added, expandable.
*/
export function DiffStat({ steps, label }: { steps: readonly LiveStep[]; label: string }) {
const hunks = useMemo(() => foldDiffHunks(steps), [steps]);
const [open, setOpen] = useState(false);
const [visible, setVisible] = useState(false);
const totals = useMemo(() => diffTotals(hunks), [hunks]);
const [active, setActive] = useState(0);
if (!hunks.length) return null;
const current = hunks[Math.min(active, hunks.length - 1)]!;
return <>
<span className={css.diffStatRoot}>
<button type="button" className={css.diffStatButton} aria-expanded={open}
aria-label={`${label} · 改动 ${totals.added} 行,删除 ${totals.removed} 行`}
onClick={event => {
event.stopPropagation();
if (open) { setOpen(false); return; }
setVisible(true);
setOpen(true);
}}>
<span className={css.diffCaret} aria-hidden>{open ? '\u25be' : '\u25b8'}</span>
{totals.added > 0 && <span className={css.diffAdded}>+{totals.added}</span>}
{totals.removed > 0 && <span className={css.diffRemoved}>-{totals.removed}</span>}
</button>
</span>
{visible && <div className={css.diffOverlayRow}>
<MorphPanel open={open} onSettled={revealPanel} onClosed={() => setVisible(false)}>
{hunks.length > 1 && <div className={css.diffTabs}>
{hunks.map((hunk, index) => <button key={`${hunk.path}:${index}`} type="button"
className={css.diffTab} data-active={index === active || undefined}
onClick={() => setActive(index)} title={hunk.path}>
{hunk.path.split(/[/\\]+/).filter(Boolean).slice(-1)[0] ?? hunk.path}
</button>)}
</div>}
<div className={css.diffScrollArea}>
<DiffBlock diffs={[current]} maxLines={36} labels={diffBlockLabels} />
</div>
</MorphPanel>
</div>}
</>;
}

43
src/client/LiveFold.tsx Normal file
View File

@ -0,0 +1,43 @@
import { useLayoutEffect, useMemo, useRef, useState } from 'react';
import { FOLD_TIMING } from './fold-choreography.js';
import css from './Reader.module.css';
/** Values are presentation commits, never live network counters. */
export function SubtleNumberRoll({ value, motion }: { value: number; motion: boolean }) {
const [outgoing, setOutgoing] = useState<number | null>(null);
const previous = useRef(value);
useLayoutEffect(() => {
if (value === previous.current) return;
const old = previous.current;
previous.current = value;
if (!motion) { setOutgoing(null); return; }
setOutgoing(old);
const timer = window.setTimeout(() => setOutgoing(null), FOLD_TIMING.count);
return () => window.clearTimeout(timer);
}, [value, motion]);
return <span className={css.numberRollRoot} aria-hidden="true">
<span className={css.numberRollSizer}>{value}</span>
{outgoing !== null && <span key={`out-${outgoing}`} className={`${css.numberRollDigit} ${css.numberRollExit}`}>{outgoing}</span>}
<span key={`cur-${value}`} className={`${css.numberRollDigit} ${outgoing !== null ? css.numberRollEnter : ''}`}>{value}</span>
</span>;
}
export function FoldSummaryText({ summary, motion }: { summary: string; motion: boolean }) {
const parts = useMemo(() => {
const regex = /([^\d]+)(\d+)/g;
const result: { text: string; number?: number }[] = [];
let end = 0;
for (const match of summary.matchAll(regex)) {
result.push({ text: match[1]!, number: Number(match[2]) });
end = match.index! + match[0].length;
}
if (end < summary.length) result.push({ text: summary.slice(end) });
return result;
}, [summary]);
return <span className={css.foldSummary} data-reader-fold-summary={summary} aria-label={summary}>
{parts.map(part => <span key={part.text} className={css.foldSummaryPart}>
<span>{part.text}</span>
{part.number !== undefined && <SubtleNumberRoll value={part.number} motion={motion} />}
</span>)}
</span>;
}

View File

@ -0,0 +1,210 @@
.card {
position: relative;
margin: 16px 0;
border-radius: 14px;
border: 1px solid var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.08));
background: var(--dsw-alias-bg-module-platform, transparent);
transition: border-color 0.2s cubic-bezier(0.22, 1, 0.36, 1), box-shadow 0.2s cubic-bezier(0.22, 1, 0.36, 1);
overflow: hidden;
}
.card:hover {
border-color: var(--dsw-alias-border-l1, rgba(0, 0, 0, 0.16));
box-shadow: 0 2px 10px -2px rgba(0, 0, 0, 0.04);
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
height: 36px;
padding: 0 14px;
border-bottom: 1px solid var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.06));
background: var(--dsw-alias-interactive-bg-hover, rgba(0, 0, 0, 0.015));
user-select: none;
}
.titleArea {
display: flex;
align-items: center;
gap: 7px;
min-width: 0;
}
.icon {
flex-shrink: 0;
color: var(--dsw-alias-label-tertiary, #94a3b8);
display: flex;
align-items: center;
justify-content: center;
}
.title {
font-size: 12px;
font-weight: 500;
color: var(--dsw-alias-label-secondary, #64748b);
letter-spacing: -0.01em;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.actions {
display: flex;
align-items: center;
gap: 4px;
}
.iconBtn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
border: none;
background: transparent;
color: var(--dsw-alias-label-tertiary, #94a3b8);
border-radius: 6px;
cursor: pointer;
padding: 0;
transition: all 0.15s ease;
}
.iconBtn:hover {
background: var(--dsw-alias-interactive-bg-hover, rgba(0, 0, 0, 0.06));
color: var(--dsw-alias-label-primary, #0f172a);
}
.iconBtn:focus-visible {
outline: 2px solid var(--dsw-alias-state-business-primary, #2563eb);
outline-offset: 1px;
}
.iframeWrapper {
width: 100%;
position: relative;
background: transparent;
transition: height 0.25s cubic-bezier(0.22, 1, 0.36, 1);
}
.iframe {
width: 100%;
height: 100%;
border: none;
display: block;
background: transparent;
}
.receipt {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 6px 12px;
padding: 8px 14px;
background: var(--dsw-alias-interactive-bg-hover, rgba(34, 197, 94, 0.05));
border-top: 1px solid var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.06));
font-size: 12px;
line-height: 18px;
color: var(--dsw-alias-label-primary, #0f172a);
animation: slideUp 0.2s cubic-bezier(0.22, 1, 0.36, 1);
}
.receiptPrompt {
flex: 1 1 100%;
font-size: 12px;
line-height: 18px;
color: var(--dsw-alias-label-secondary, #64748b);
background: var(--dsw-alias-bg-base, rgba(0, 0, 0, 0.03));
border: 1px solid var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.06));
border-radius: 6px;
padding: 6px 10px;
user-select: text;
cursor: text;
overflow-wrap: anywhere;
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(4px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.receiptSummary {
display: flex;
align-items: center;
gap: 6px;
color: var(--dsw-alias-state-business-primary, #16a34a);
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.receiptHint {
display: flex;
align-items: center;
gap: 6px;
}
.sendKbd {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 11px;
color: var(--dsw-alias-label-tertiary, #94a3b8);
background: var(--dsw-alias-bg-base, rgba(0, 0, 0, 0.04));
border: 1px solid var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.08));
padding: 2px 8px;
border-radius: 5px;
cursor: pointer;
font-family: inherit;
transition: all 0.15s ease;
}
.sendKbd:hover {
background: var(--dsw-alias-interactive-bg-hover, rgba(0, 0, 0, 0.08));
color: var(--dsw-alias-label-primary, #0f172a);
}
.sendKbd:focus-visible {
outline: 2px solid var(--dsw-alias-state-business-primary, #2563eb);
outline-offset: 1px;
}
.streamingPlaceholder {
margin: 16px 0;
padding: 16px 18px;
border-radius: 14px;
border: 1px dashed var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.12));
background: var(--dsw-alias-interactive-bg-hover, rgba(0, 0, 0, 0.015));
color: var(--dsw-alias-label-secondary, #64748b);
font-size: 13px;
display: flex;
align-items: center;
gap: 10px;
}
.pulseDot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--dsw-alias-state-business-primary, #2563eb);
animation: pulse 1.5s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% {
opacity: 0.35;
transform: scale(0.9);
}
50% {
opacity: 1;
transform: scale(1.15);
}
}

309
src/client/McpAppFrame.tsx Normal file
View File

@ -0,0 +1,309 @@
import { createContext, memo, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from 'react';
import {
getHostTheme,
getCssTokens,
extractHtmlTitle,
ensureHtmlDocument,
formatReceiptPrompt,
fillComposerDom,
} from './mcp-app.js';
import css from './McpAppFrame.module.css';
/**
* Composer fill channel shared by every McpAppFrame in one Reader tree.
* Provided by Blocks from the session-scoped Reader face (sanctioned
* conversation input API); absent outside a Reader, where the DOM fallback
* applies. React context avoids threading the callback through the whole
* markdown pipeline (MarkdownText -> render context -> code fence).
*/
export type ComposerFill = (text: string) => boolean;
export const ComposerFillContext = createContext<ComposerFill | undefined>(undefined);
export function useComposerFill(): ComposerFill | undefined {
return useContext(ComposerFillContext);
}
export interface McpAppFrameProps {
html: string;
title?: string;
initialHeight?: number;
/** Session-scoped composer writer; falls back to context, then DOM. */
fillComposer?: ComposerFill;
}
export const McpAppFrame = memo(function McpAppFrame({
html,
title: initialTitle,
initialHeight = 240,
fillComposer: fillComposerProp,
}: McpAppFrameProps) {
const fillComposerFromContext = useComposerFill();
const writeComposer = useMemo<ComposerFill>(
() => fillComposerProp ?? fillComposerFromContext ?? fillComposerDom,
[fillComposerProp, fillComposerFromContext],
);
const iframeRef = useRef<HTMLIFrameElement>(null);
const lastParamsRef = useRef<Record<string, unknown>>({});
const [height, setHeight] = useState(() => Math.max(60, Math.min(2400, initialHeight)));
const [receipt, setReceipt] = useState<string | null>(null);
const [lastPrompt, setLastPrompt] = useState<string | null>(null);
const [reloadNonce, setReloadNonce] = useState(0);
const frameId = useId();
const title = useMemo(() => {
return initialTitle || extractHtmlTitle(html) || '交互式 MCP App';
}, [initialTitle, html]);
// Capture the host theme ONCE for the initial srcDoc. Live theme switches
// are delivered via postMessage (broadcastTheme), so the srcDoc identity
// stays stable and the iframe never reloads (which would wipe user state
// such as checked boxes or selected tabs).
const [initialTheme] = useState(getHostTheme);
const preparedHtml = useMemo(() => ensureHtmlDocument(html, initialTheme), [html, initialTheme]);
const fillComposer = useCallback((params: Record<string, unknown>) => {
const prompt = formatReceiptPrompt(params, title);
setLastPrompt(prompt);
try {
if (writeComposer(prompt)) return true;
// Composer refused: leave the prompt visible in the receipt bar and
// stash a clipboard copy as a fallback.
try {
void navigator.clipboard?.writeText(prompt);
} catch {
// Clipboard unavailable; the visible receipt text remains copyable.
}
} catch {
// Ignore DOM query errors in non-browser environments
}
return false;
}, [title, writeComposer]);
const handleUserSubmit = useCallback((params: Record<string, unknown>) => {
lastParamsRef.current = params;
let summary: string;
if (typeof params.choice === 'string') {
const desc = typeof params.desc === 'string' ? ` (${params.desc})` : '';
summary = `选择: ${params.choice}${desc}`;
} else if (typeof params.action === 'string') {
summary = `操作: ${params.action}${params.payload ? ` (${JSON.stringify(params.payload)})` : ''}`;
} else if (typeof params.selectedVariant === 'string') {
summary = `方案: ${params.selectedVariant}`;
} else {
summary = JSON.stringify(params);
}
setReceipt(summary);
// Populate DSH composer with natural prompt and trigger React input state
fillComposer(params);
}, [fillComposer]);
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
const iframe = iframeRef.current;
if (!iframe || event.source !== iframe.contentWindow) return;
const data = event.data;
if (!data || typeof data !== 'object') return;
// Protocol SEP-1865 JSON-RPC 2.0
const currentTheme = getHostTheme();
const cssTokens = getCssTokens(currentTheme);
// 1. ui/initialize (View -> Host)
if (data.method === 'ui/initialize') {
const response = {
jsonrpc: '2.0',
id: data.id,
result: {
protocolVersion: '2026-01-26',
hostContext: {
theme: currentTheme,
locale: 'zh-CN',
styles: {
variables: cssTokens,
},
},
},
};
iframe.contentWindow?.postMessage(response, '*');
return;
}
// ui/ready is a notification. The frame has no ready flag to flip.
if (data.method === 'ui/ready' || data.method === 'ui/notifications/initialized') return;
// ui/resize
if (data.method === 'ui/resize' && data.params?.height) {
const h = Number(data.params.height);
if (Number.isFinite(h) && h > 0) {
setHeight(Math.max(60, Math.min(2400, Math.round(h))));
}
return;
}
// ui/submit or ui/update-model-context
if (data.method === 'ui/submit' || data.method === 'ui/update-model-context') {
const params = (data.params as Record<string, unknown>) || {};
handleUserSubmit(params);
return;
}
};
window.addEventListener('message', handleMessage);
// Broadcast live theme changes to running iframe
const broadcastTheme = () => {
const newTheme = getHostTheme();
const tokens = getCssTokens(newTheme);
iframeRef.current?.contentWindow?.postMessage({
jsonrpc: '2.0',
method: 'ui/notifications/host-context-changed',
params: {
theme: newTheme,
styles: { variables: tokens },
},
}, '*');
};
let observer: MutationObserver | null = null;
if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
observer = new MutationObserver(broadcastTheme);
if (document.body) {
observer.observe(document.body, { attributes: true, attributeFilter: ['data-ds-dark-theme', 'class', 'style', 'data-theme'] });
}
if (document.documentElement) {
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'class', 'style'] });
}
}
const media = typeof window !== 'undefined' && window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;
media?.addEventListener?.('change', broadcastTheme);
return () => {
window.removeEventListener('message', handleMessage);
observer?.disconnect();
media?.removeEventListener?.('change', broadcastTheme);
};
}, [handleUserSubmit]);
const handleFrameLoad = useCallback(() => {
const iframe = iframeRef.current;
if (!iframe) return;
// Proactive Host -> View initialize notification for boilerplate compatibility
const currentTheme = getHostTheme();
const cssTokens = getCssTokens(currentTheme);
iframe.contentWindow?.postMessage({
jsonrpc: '2.0',
method: 'ui/initialize',
params: {
theme: currentTheme,
locale: 'zh-CN',
styles: {
variables: cssTokens,
},
},
}, '*');
}, []);
const handleReload = useCallback(() => {
setReloadNonce(n => n + 1);
setReceipt(null);
}, []);
return (
<div className={css.card} data-mcp-app-card data-testid="mcp-app-card">
<div className={css.header}>
<div className={css.titleArea}>
<span className={css.icon} aria-hidden="true">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<rect width="18" height="18" x="3" y="3" rx="2" />
<path d="M3 9h18" />
<path d="M9 21V9" />
</svg>
</span>
<span className={css.title} title={title}>{title}</span>
</div>
<div className={css.actions}>
<button
type="button"
className={css.iconBtn}
onClick={handleReload}
title="重置组件状态"
aria-label="重置组件状态"
>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
<path d="M3 3v5h5" />
<path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16" />
<path d="M16 16h5v5" />
</svg>
</button>
</div>
</div>
<div className={css.iframeWrapper} style={{ height: `${height}px` }}>
<iframe
key={`${frameId}-${reloadNonce}`}
ref={iframeRef}
className={css.iframe}
title={title}
srcDoc={preparedHtml}
sandbox="allow-scripts allow-forms"
referrerPolicy="no-referrer"
onLoad={handleFrameLoad}
/>
</div>
{receipt && (
<div className={css.receipt} data-testid="mcp-app-receipt">
<span className={css.receiptSummary}>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<polyline points="20 6 9 17 4 12" />
</svg>
<span>已就绪:{receipt}</span>
</span>
{lastPrompt && (
<div className={css.receiptPrompt} title={lastPrompt}>
{lastPrompt}
</div>
)}
<div className={css.receiptHint}>
<button
type="button"
className={css.sendKbd}
title="把这条结果重新填入输入框,然后回车发送"
onClick={() => {
fillComposer(lastParamsRef.current);
}}
>
<span>填入输入框</span>
<kbd>↵</kbd>
</button>
</div>
</div>
)}
</div>
);
});
/**
* Markdown code-fence mount point: picks the session composer writer from
* React context (provided by Blocks) without changing the markdown
* pipeline's signatures.
*/
export function McpAppCodeBlock({ html, title, initialHeight }: {
html: string; title?: string; initialHeight?: number;
}) {
const fillComposer = useComposerFill();
return <McpAppFrame html={html} title={title} initialHeight={initialHeight} fillComposer={fillComposer} />;
}
export function StreamingMcpAppPlaceholder({ title }: { title?: string }) {
return (
<div className={css.streamingPlaceholder}>
<span className={css.pulseDot} aria-hidden="true" />
<span>正在生成交互组件{title ? `(${title})` : ''}...</span>
</div>
);
}

View File

@ -0,0 +1,108 @@
import { useCallback, useState, useSyncExternalStore, type ReactNode } from 'react';
import type { AssistantActionOwnerProps, ChatConversationViewNode, ChatNode, ChatNodeOwnerProps, TurnTailOwnerProps, UseDisclosure } from '@deepseek-ai/dsh-client-ui-chat/client';
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store';
import type { AssistantBlock, ToolCallBlock } from '@deepseek-ai/dsh-client-ui-conversation/client';
type MessageId = AssistantActionOwnerProps['messageId'];
import { OFFICIAL_SEATS, readerGroupAction } from './official-slots.js';
import type { BlockRenderProps } from './types.js';
import { chatSeatProps } from './chat-seat.js';
import { Blocks } from './Blocks.js';
export function OfficialActions({ official, messageId }: Pick<BlockRenderProps, 'official'> & { messageId?: MessageId }) {
if (!official || !messageId) return null;
return <span data-reader-official-actions style={{ display: 'contents' }}>
{official.renderSlot(OFFICIAL_SEATS.actions, { messageId })}
</span>;
}
/** Each atomic Tool view owns its disclosure state through this stable Hook prop. */
const useToolDisclosure: UseDisclosure = () => {
const [expanded, setExpanded] = useState(false);
const toggle = useCallback(() => setExpanded(previous => !previous), []);
return { expanded, setExpanded, toggle };
};
export function OfficialTool({ official, block, toolName, cwd, openFile, fallback }: BlockRenderProps & {
official: NonNullable<BlockRenderProps['official']>; block: ToolCallBlock; toolName: string; fallback: ReactNode;
}) {
const home = useSyncExternalStore(official.officialHost.subscribe, official.officialHost.getSnapshot).home;
return <div data-reader-tool-official>
{(official.renderSlot as (key: string, owner: object, options: object) => ReactNode)(OFFICIAL_SEATS.tools, {
callId: block.callId, toolName,
phase: 'kind' in block ? 'result' : block.phase, block, cwd, home,
openFile: openFile ?? (() => {}),
loadImage: official.officialImageLoader,
useDisclosure: useToolDisclosure,
inspect: () => official.openView('trajectory', block.callId),
}, { entryKey: toolName, hookContext: { callId: block.callId, assistant: undefined }, fallback })}
</div>;
}
function chatNodeOwner(render: BlockRenderProps, official: NonNullable<BlockRenderProps['official']>): ChatNodeOwnerProps {
return {
cwd: render.cwd,
openFile: render.openFile ?? (() => {}),
forkAt: render.forkAt ?? (() => {}),
inspectCall: callId => official.openView('trajectory', callId),
loadImage: official.officialImageLoader,
fileMentions: official.officialFileMentions,
};
}
function nodeHookContext(turnData: unknown, disclosureReset: ReturnType<typeof createSnapshotStore<number>>) {
return { turnData, disclosureReset, useGroupAction: readerGroupAction };
}
export function OfficialNode({ node, fallback, ...render }: BlockRenderProps & { node: ChatConversationViewNode; fallback: ReactNode }) {
const official = render.official;
const [disclosureReset] = useState(() => createSnapshotStore(0));
if (!official) return fallback;
const turn = node.location.kind === 'turn' || node.location.kind === 'step' ? node.location.turn : undefined;
// The runtime node domain is open; the public SlotMap enumerates the known kinds.
const renderNode = official.renderSlot as unknown as (key: string, owner: object, options: object) => ReactNode;
return <div data-reader-official-node={node.kind} {...(node.kind === 'user' || node.kind === 'steering' ? chatSeatProps(node.kind, node.key) : {})}>
{renderNode(OFFICIAL_SEATS.nodes, { ...chatNodeOwner(render, official), node }, { entryKey: node.kind, hookContext: nodeHookContext(turn?.data, disclosureReset), fallback })}
</div>;
}
type AssistantBodyProps = BlockRenderProps & {
node: ChatNode<'assistant-step'>;
blocks: readonly AssistantBlock[];
streaming?: boolean;
holdFormatting?: boolean;
startedAt?: number;
interrupted?: boolean;
liveText?: boolean;
};
/**
* Body of one assistant segment. A mirrored assistant-step replacement draws
* it; Reader markdown is the fallback when no replacement is registered.
* The caller keeps reasoning blocks on the reading card.
*/
export function OfficialAssistantBody({
node, blocks, streaming = false, holdFormatting = false, startedAt, interrupted = false, liveText = false, ...render
}: AssistantBodyProps) {
const official = render.official;
const [disclosureReset] = useState(() => createSnapshotStore(0));
const fallback = <Blocks {...render} blocks={blocks} streaming={streaming} holdFormatting={holdFormatting} startedAt={startedAt} interrupted={interrupted} liveText={liveText} />;
if (!official) return fallback;
const turn = node.location.kind === 'turn' || node.location.kind === 'step' ? node.location.turn : undefined;
const sameBlocks = blocks.length === node.data.blocks.length && blocks.every((block, index) => block === node.data.blocks[index]);
const view = sameBlocks ? node : { ...node, data: { ...node.data, blocks } };
const renderNode = official.renderSlot as unknown as (key: string, owner: object, options: object) => ReactNode;
// groupPart matches the host split: response skips reasoning. The block
// slice is what a replacement that ignores groupPart actually receives.
return renderNode(OFFICIAL_SEATS.nodes, { ...chatNodeOwner(render, official), node: view, groupPart: 'response' }, {
entryKey: 'assistant-step',
hookContext: nodeHookContext(turn?.data, disclosureReset),
fallback,
});
}
export function OfficialTail({ official, owner, produced }: Pick<BlockRenderProps, 'official'> & { owner?: TurnTailOwnerProps; produced: readonly string[] }) {
const tailOwner = owner && official ? { ...owner, openFile: official.officialPreviewFile, readerProducedPaths: produced } : undefined;
return official && tailOwner ? <div data-reader-official-tail style={{ display: 'contents' }}>
{official.renderSlot(OFFICIAL_SEATS.tail, tailOwner)}
</div> : null;
}

View File

@ -0,0 +1,765 @@
.root {
color: var(--dsw-alias-label-primary);
font-family: inherit;
font-size: 16px;
line-height: 28px;
padding: 16px calc(var(--dsh-composer-side-clearance, 16px) + 16px) 24px;
min-width: 0;
flex: 0 0 auto;
overflow-anchor: auto;
container-type: inline-size;
/* 40px at the host's default 14px content size. A smaller content size
must not shrink the lane under that floor. Positive font delta still
grows it, or the next sticky band lands on the previous one. */
--reader-lane-block: max(40px, calc(40px + var(--dsh-content-font-delta, 0px)));
/* Wallpaper themes clear --dsw-alias-bg-base, or leave it only partly
opaque. The token and the inner surface paint above Canvas, the page
surface colour (it follows color-scheme). An opaque stock token covers
that underlay, so the stock theme does not change. */
--reader-lane-plate: linear-gradient(var(--dsw-alias-bg-base), var(--dsw-alias-bg-base)), linear-gradient(var(--dsw-alias-bg-layer-1, transparent), var(--dsw-alias-bg-layer-1, transparent));
}
.column { max-width: var(--dsh-chat-content-width, 748px); width: 100%; margin: 0 auto; display: flex; flex-direction: column; gap: 22px; min-width: 0; }
/* The column is only a programmatic focus-restore target (tabIndex -1), never a
Tab stop, so it must not draw a ring around the whole transcript. */
.column:focus, .column:focus-visible { outline: none; }
.toolbar { position: sticky; top: 0; display: flex; justify-content: flex-end; align-items: center; gap: 6px; min-height: 32px; padding: 0; color: var(--dsw-alias-label-tertiary); font-size: 12px; background: var(--dsw-alias-bg-base); backdrop-filter: blur(12px); }
/* 吸顶带第二车道:左「正在处理」+ 右「自动折叠」共享同一条 40px 水平基线。
top / z-index 由下方 measured-flow 段统一定义:这一道永远钉在工具栏车道
之下、且永远低于宿主输入卡(composerSeat z-index 7)。 */
.turnProcessSticky { position: sticky; background: var(--dsw-alias-bg-base); backdrop-filter: blur(12px); min-height: 32px; display: flex; align-items: center; }
.turnProcessSticky .disclosureButton { min-height: 32px; }
/* 第二车道:折叠胶囊吸附在第一车道正下方,互不重叠 */
.textButton, .historyButton, .iconButton, .jump, .disclosureButton, .imageOpen, .dialogClose { font: inherit; cursor: pointer; }
.textButton { border: 0; background: transparent; color: var(--dsw-alias-label-secondary); padding: 2px 6px; border-radius: 6px; white-space: nowrap; }
.textButton:hover, .iconButton:hover, .disclosureButton:hover { background: var(--dsw-alias-interactive-bg-hover); }
.root button:focus-visible, .root summary:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary); outline-offset: 3px; }
.turn { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
/* Keep pinned process lanes inside the process/answer block, before turn-tail UI. */
.turnStickyRegion { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
.turnStickyLanes { position: sticky; top: var(--reader-toolbar-height, var(--reader-lane-block, 40px)); z-index: 6; display: flex; flex-direction: column; min-width: 0; }
/* Every turn renders through its own retiring lane, so the sibling rule has to
reach one level in: the margin still lands between two consecutive turns. */
.turn + .turn, .retiringContent + .retiringContent > .turn { margin-top: 12px; }
/* Host .userStack caps itself with min(axis * 0.702, 82%). In the native column
that percentage resolves against a .userRow stretched across the column. The
slot outlet is display:contents, so the host row is this cluster's flex item.
Naming the official slot here misses the mirrored seat
(dsh-better-display.official.nodes/…), the row shrink-wraps to the text, and
the same 82% is applied again. The cluster fills the column. The direct child
of its own slot — the host row, not a nested image slot — stretches with it.
The host .userStack is left alone. Pending bubbles are not that row, so they
carry the same cap themselves. */
.userCluster { display: flex; flex-direction: column; align-self: stretch; align-items: flex-end; width: 100%; max-width: 100%; gap: 8px; min-width: 0; margin-bottom: 4px; }
.userCluster > [data-slot] > * { align-self: stretch; width: 100%; max-width: 100%; min-width: 0; box-sizing: border-box; }
.userImages { display: flex; flex-direction: column; align-items: flex-end; align-self: flex-end; width: fit-content; max-width: 100%; min-width: 0; }
.userImages .imageFigure { align-self: flex-end; }
.user { align-self: flex-end; width: fit-content; max-width: min(calc(var(--dsh-chat-content-width, 748px) * 0.702), 82%); margin-left: auto; padding: 10px 16px; border-radius: var(--dsw-radius-xl, 22px); background: var(--dsw-specific-bubble); color: var(--dsw-alias-label-primary); font-size: var(--dsh-content-font-size, 14px); line-height: calc(22px + var(--dsh-content-font-delta, 0px)); font-weight: 400; white-space: pre-wrap; overflow-wrap: anywhere; word-break: break-word; box-sizing: border-box; }
.user .blocks { gap: 10px; }
.answer { display: flex; flex-direction: column; min-width: 0; overflow-wrap: anywhere; }
.readingText { min-width: 0; }
.reasonPlain { white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; color: inherit; }
.readingText button { min-width: 24px; min-height: 24px; }
.streamWord { display: inline-block; }
.streamInlineWord { display: inline; }
.streamWord, .streamInlineWord, .streamAtom { opacity: 1; filter: none; }
.streamAtom { min-width: 0; }
@media (prefers-reduced-motion: reduce) { .streamWord, .streamInlineWord, .streamAtom { opacity: 1 !important; filter: none !important; } }
.retiringContent { min-width: 0; }
.retiringContent[data-reader-retiring=retiring] { overflow: hidden; }
.mainFlow, .blocks { display: flex; flex-direction: column; gap: 16px; min-width: 0; }
.mainFlow:empty, .blocks:empty { display: none; }
.blocks > :first-child { margin-top: 0; }
.blocks > :last-child { margin-bottom: 0; }
.blocks :global(.md-table-wide) { max-width: 100%; }
.disclosure { min-width: 0; }
.disclosureButton { display: inline-flex; align-items: center; gap: 6px; max-width: 100%; min-height: 32px; border: 0; background: transparent; border-radius: 7px; color: var(--dsw-alias-label-tertiary); font-size: calc(14px + var(--dsh-content-font-delta, 0px)); line-height: calc(24px + var(--dsh-content-font-delta, 0px)); font-weight: 400; padding: 4px 6px; margin-left: -6px; text-align: left; }
.disclosure[data-reader-status-only] { display: flex; align-items: center; min-height: 32px; }
.statusText { display: inline-flex; min-width: 0; max-width: 100%; font-size: calc(14px + var(--dsh-content-font-delta, 0px)); line-height: calc(24px + var(--dsh-content-font-delta, 0px)); font-weight: 400; color: var(--dsw-alias-label-secondary); }
.srOnly { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
/* Transitions.dev — Thinking states, supplied by the user. Native DSH colors;
the hidden sizer shares this font and the short phases share a left edge. */
.think {
--think-swap: 150ms;
--think-gap: 50ms;
--think-distance: 8px;
--think-blur: 2px;
--think-shimmer: 2000ms;
--think-base: var(--dsw-alias-label-secondary);
--think-highlight: var(--dsw-alias-label-primary);
--think-ease: ease-in-out;
position: relative; display: inline-block; max-width: 100%; text-align: left;
}
.thinkSizer { display: block; visibility: hidden; white-space: nowrap; }
.thinkText {
position: absolute; top: 0; left: 0; right: 0; display: block;
color: var(--think-base); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
transform: translateY(0); filter: blur(0); opacity: 1;
transition: transform var(--think-swap) var(--think-ease), filter var(--think-swap) var(--think-ease), opacity var(--think-swap) var(--think-ease);
}
.think[data-reader-status-phase=running] .thinkText[data-reader-status-copy=current] { transition-delay: var(--think-gap); }
.think:not([data-reader-status-phase=idle]) .thinkText { will-change: transform, filter, opacity; }
@supports (background-clip: text) or (-webkit-background-clip: text) {
.think[data-active=true] .thinkText::before {
content: attr(data-text); position: absolute; inset: 0; pointer-events: none;
background-image: linear-gradient(90deg, transparent 0%, transparent 40%, var(--think-highlight) 50%, transparent 60%, transparent 100%);
background-size: 400% 100%; background-repeat: no-repeat;
-webkit-background-clip: text; background-clip: text;
color: transparent; -webkit-text-fill-color: transparent;
animation: thinkShimmer var(--think-shimmer) linear infinite;
}
}
@keyframes thinkShimmer { 0% { background-position: 100% 0; } 100% { background-position: 0% 0; } }
.thinkText.isExit { transform: translateY(calc(var(--think-distance) * -1)); filter: blur(var(--think-blur)); opacity: 0; }
.thinkText.isEnterStart { transition: none; transform: translateY(var(--think-distance)); filter: blur(var(--think-blur)); opacity: 0; }
[data-motion=off] .thinkText { transition: none !important; transform: none !important; filter: none !important; opacity: 1 !important; }
[data-motion=off] .thinkText[data-reader-status-copy=outgoing] { display: none !important; }
[data-motion=off] .thinkText::before { display: none !important; }
@media (prefers-reduced-motion: reduce), (forced-colors: active) {
.thinkText { transition: none !important; transform: none !important; filter: none !important; opacity: 1 !important; }
.thinkText[data-reader-status-copy=outgoing] { display: none !important; }
.thinkText::before { display: none !important; }
}
.processMeta { display: grid; grid-template-rows: 0fr; opacity: 0; transition: grid-template-rows 260ms cubic-bezier(.22,1,.36,1), opacity 160ms ease-out; }
.processMeta[data-open=true] { grid-template-rows: 1fr; opacity: 1; }
.processMetaInner { min-height: 0; overflow: hidden; }
.processMetaLine { display: flex; align-items: baseline; flex-wrap: wrap; gap: 8px; padding: 8px 0 0 16px; color: var(--dsw-alias-label-secondary); font-size: 12px; line-height: 20px; font-variant-numeric: tabular-nums; }
.processMetaLine .meta { color: inherit; }
.chevron { flex: none; stroke: currentColor; fill: none; stroke-width: 1.4; stroke-linecap: round; stroke-linejoin: round; transition: transform 260ms cubic-bezier(.22,1,.36,1); }
.chevron[data-open=true] { transform: rotate(90deg); }
.disclosureBody { overflow: hidden; height: 0; transform-origin: top center; will-change: height, opacity, transform; }
/* One rail geometry for every nested lane. These three rules used to sit at
6px / 24px / 6px with 1px, 1px and 2px rails, so the vertical guides stepped
in and out down the page. They now share --reader-rail: same left edge, same
rail width, same gutter, so a column of nested rows reads as one line. */
.processContents { display: flow-root; border-left: 1px solid var(--dsw-alias-border-l2); padding: 3px 0 2px var(--reader-gutter, 16px); margin: 0 0 0 var(--reader-rail, 6px); color: var(--dsw-alias-label-secondary); font-size: 14px; line-height: 24px; }
.processContents > :last-child { margin-bottom: 0; }
/* Narration stays ordinary body text (the `.answer` typography) and carries no
left rule of its own. When collapsed reasoning/tool rows sat between two
narration blocks, the gap carries a compact folded-process summary in the
process-chain language: a 1px left rail plus the familiar `思考×N · 工具×K`
label with its chevron. The preceding narration cell drops its outer bottom
gap so the seam row owns exactly that space. */
.processSeamRow {
display: flex; align-items: center; min-height: 40px;
margin-left: var(--reader-rail, 6px); padding-left: var(--reader-gutter, 16px);
border-left: 1px solid var(--dsw-alias-border-l2); box-sizing: border-box;
}
.processSeamRow > .disclosure { display: flex; align-items: center; min-height: 24px; }
.processSeamRow .disclosureButton { min-height: 24px; padding-block: 2px; font-size: 12px; line-height: 20px; color: var(--dsw-alias-label-tertiary); }
.flowCell:has(> .flowCellInner > [data-reader-seam-after]) > .flowCellInner { padding-bottom: 0; }
.processFrame { min-width: 0; }
.toolActivity { min-width: 0; color: var(--dsw-alias-label-secondary); }
.nativeToolRow { min-width: 0; }
.rowSeparator { flex: none; width: 2px; height: 2px; margin: 0 8px; border-radius: 1px; background: var(--dsw-alias-label-caption); }
.nativeToolSummary { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--dsw-alias-label-tertiary); font-size: 14px; line-height: 24px; }
.nativeToolRow:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary); outline-offset: 3px; border-radius: 4px; }
.toolHeading { display: grid; grid-template-columns: 20px minmax(0, 1fr) auto; align-items: start; gap: 10px; width: 100%; padding: 10px 14px 4px; border: 0; background: transparent; color: inherit; font: inherit; text-align: left; cursor: pointer; border-radius: 11px; }
.toolHeading:hover { background: var(--dsw-alias-interactive-bg-hover); }
.toolHeading:focus-visible { outline-offset: -3px !important; }
.toolGlyph { display: flex; align-items: center; justify-content: center; height: 22px; color: var(--dsw-alias-label-secondary); }
.toolHeadingCopy { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
.toolTitle { font-size: 13px; line-height: 22px; font-weight: 500; overflow-wrap: anywhere; }
.toolTarget { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; overflow-wrap: anywhere; color: var(--dsw-alias-label-secondary); font-size: 12px; line-height: 19px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
.toolHeadingState { display: flex; align-items: center; gap: 7px; min-height: 22px; color: var(--dsw-alias-label-secondary); }
/* Line counts of the file a tool changed, matching the official tool row:
additions read as growth, deletions as loss. Zero sides stay hidden. */
.diffStat { flex: none; display: inline-flex; gap: 6px; margin-left: 8px; font-size: 11px; line-height: 18px;
font-variant-numeric: tabular-nums; font-feature-settings: "tnum"; white-space: nowrap; }
.diffAdded { color: var(--dsw-alias-state-success-primary, #2f9e63); }
.diffRemoved { color: var(--dsw-alias-state-error-primary, #d1483c); }
/* A digest row is [label][counts]; the counts are pushed to the right edge so
every row's numbers line up in one column instead of drifting with the label. */
.summaryRow { display: flex; align-items: center; gap: 8px; min-width: 0; max-width: 100%; flex-wrap: wrap; }
.summaryRow > .diffStatRoot { flex: none; margin-left: auto; }
.summaryRow > :first-child { min-width: 0; }
.diffStatRoot { position: relative; flex: none; }
/* Transparent at rest like the path and count chips beside it; the outline and
surface appear on hover or keyboard focus, so the row reads as text until the
pointer says otherwise. */
.diffStatButton { display: inline-flex; gap: 6px; align-items: center; padding: 2px 8px; cursor: pointer;
font: inherit; font-size: 11px; line-height: 16px; font-variant-numeric: tabular-nums;
font-feature-settings: "tnum"; color: var(--dsw-alias-label-secondary);
background: transparent; border: 1px solid transparent; border-radius: 6px;
transition: background 120ms ease, border-color 120ms ease; }
.diffStatButton:hover, .diffStatButton:focus-visible,
.diffStatButton[aria-expanded="true"] {
background: var(--dsw-alias-bg-module-platform, rgba(127, 127, 127, .1));
border-color: var(--dsw-alias-border-l2, rgba(127, 127, 127, .28)); }
.diffStatButton:focus-visible { outline: none; }
.diffStatButton[aria-expanded="true"] .diffCaret { opacity: 1; }
/* The diff overlay spans the full column width below the summary row, never overflowing. */
.diffOverlayRow {
flex: 1 1 100%;
width: 100%;
max-width: 100%;
min-width: 0;
margin-top: 6px;
box-sizing: border-box;
}
.diffOverlay {
display: flex;
flex-direction: column;
width: 100%;
max-width: 100%;
min-width: 0;
box-sizing: border-box;
overflow: hidden;
border-radius: 10px;
background: var(--dsw-alias-bg-module-platform, rgba(127, 127, 127, .08));
border: 1px solid var(--dsw-alias-border-l2, rgba(128, 128, 128, .22));
padding: 8px;
}
.diffTabs {
display: flex;
flex-wrap: nowrap;
overflow-x: auto;
gap: 6px;
padding-bottom: 6px;
margin-bottom: 4px;
max-width: 100%;
scrollbar-width: thin;
}
.diffTab {
flex: none;
max-width: 220px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 3px 10px;
cursor: pointer;
font: inherit;
font-size: 11px;
line-height: 16px;
color: var(--dsw-alias-label-secondary);
background: var(--dsw-alias-bg-base, rgba(255, 255, 255, .8));
border: 1px solid var(--dsw-alias-border-l2, rgba(128, 128, 128, .2));
border-radius: 6px;
transition: all 120ms ease;
}
.diffTab:hover {
background: var(--dsw-alias-interactive-bg-hover);
color: var(--dsw-alias-label-primary);
}
.diffTab[data-active] {
color: var(--dsw-alias-label-primary);
border-color: var(--dsw-alias-state-business-primary, #1e90ff);
background: var(--dsw-alias-bg-base);
font-weight: 500;
}
.diffScrollArea {
max-height: 420px;
overflow-y: auto;
overflow-x: auto;
overscroll-behavior: contain;
-webkit-overflow-scrolling: touch;
border-radius: 8px;
border: 1px solid var(--dsw-alias-border-l2, rgba(128, 128, 128, .15));
background: var(--dsw-alias-markdown-code-block, rgba(0, 0, 0, .04));
}
.diffScrollArea :global([data-diff]) {
margin: 0 !important;
background: transparent !important;
border-radius: 0 !important;
}
.diffCaret { flex: none; width: 10px; opacity: .6; font-size: 10px; }
.diffPath { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
direction: rtl; text-align: left; }
.diffStat { flex: none; display: inline-flex; gap: 6px; font-size: 11px; font-variant-numeric: tabular-nums; }
.diffHunkBody { display: flex; flex-direction: column; gap: 4px; padding: 2px 7px 7px 25px; }
.diffLines { margin: 0; padding: 6px 8px; overflow-x: auto; border-radius: 6px; font-size: 11px; line-height: 1.55;
font-family: var(--dsw-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace); white-space: pre; }
.diffLines[data-side=removed] { background: color-mix(in srgb, #d1483c 12%, transparent); }
.diffLines[data-side=added] { background: color-mix(in srgb, #2f9e63 12%, transparent); }
.diffLineRemoved, .diffLineAdded { display: block; }
.diffLineRemoved { color: var(--dsw-alias-state-error-primary, #d1483c); }
.diffLineAdded { color: var(--dsw-alias-state-success-primary, #2f9e63); }
.diffEmpty { margin: 0; padding: 2px 0; font-size: 11px; color: var(--dsw-alias-label-secondary); }
/* A step still waiting on its result breathes: the command body itself carries a
travelling highlight, and a live counter says how long it has been running, so
a slow call reads as working rather than as frozen. Both stop on their own when
the result lands, because the running phase disappears with it. */
.nativeToolSummary[data-running] {
background-image: linear-gradient(90deg,
currentColor 0%, currentColor 35%,
color-mix(in srgb, currentColor 35%, transparent) 50%,
currentColor 65%, currentColor 100%);
/* Keep the travelling band outside the text at both loop endpoints. A single
tile covers the row throughout, so wrapping cannot start a second sweep. */
background-size: 300% 100%;
background-repeat: no-repeat;
background-position: 100% 0;
-webkit-background-clip: text; background-clip: text;
-webkit-text-fill-color: transparent;
animation: readerStepShimmer 1.6s linear infinite;
}
@keyframes readerStepShimmer { to { background-position: 0% 0; } }
/* The duration stays on a step that ran long, so a slow command keeps its number;
a fast one shows nothing once it returns. */
.toolElapsed[data-slow] { opacity: 1; font-weight: 500;
color: var(--dsw-alias-state-warning-primary, #d8862c); }
.toolElapsed { flex: none; margin-left: 8px; font-size: 11px; line-height: 18px; opacity: .72;
font-variant-numeric: tabular-nums; font-feature-settings: "tnum"; white-space: nowrap; }
[data-motion=off] .nativeToolSummary[data-running] { animation: none !important;
background-image: none; -webkit-text-fill-color: currentColor; }
@media (prefers-reduced-motion: reduce) {
.nativeToolSummary[data-running] { animation: none !important; background-image: none;
-webkit-text-fill-color: currentColor; }
}
.toolState { flex: none; font-size: 11px; line-height: 18px; white-space: nowrap; margin-left: 8px; }
.toolState[data-phase=preparing], .toolState[data-phase=running] { color: var(--dsw-alias-state-business-primary); }
/* The step that is still running gets a living edge: a breathing dot whose halo
expands and fades. Same palette as the turn-status shimmer, no new component. */
.toolState[data-phase=preparing]::before, .toolState[data-phase=running]::before {
content: ''; display: inline-block; width: 6px; height: 6px; margin-right: 6px;
border-radius: 50%; vertical-align: middle; background: currentColor;
animation: readerRunningGlow 1.4s ease-in-out infinite;
}
@keyframes readerRunningGlow {
0% { box-shadow: 0 0 0 0 color-mix(in srgb, currentColor 60%, transparent); opacity: 1; }
70% { box-shadow: 0 0 0 7px transparent; opacity: .7; }
100% { box-shadow: 0 0 0 0 transparent; opacity: 1; }
}
[data-motion=off] .toolState[data-phase=preparing]::before, [data-motion=off] .toolState[data-phase=running]::before { animation: none !important; }
@media (prefers-reduced-motion: reduce) { .toolState[data-phase=preparing]::before, .toolState[data-phase=running]::before { animation: none !important; } }
.toolState[data-phase=failed] { color: var(--dsw-alias-state-error-primary); }
.toolState[data-phase=interrupted] { color: inherit; opacity: .7; }
.toolLedger { display: flex; align-items: baseline; flex-wrap: wrap; gap: 4px 12px; padding: 10px 14px 0; color: var(--dsw-alias-label-secondary); font-size: 11px; line-height: 18px; font-variant-numeric: tabular-nums; }
.toolEngine { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
.toolDetails { margin: 6px 0 0 22px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 8px; min-width: 0; overflow: hidden; }
.toolTabs { display: flex; align-items: center; gap: 15px; padding: 0 14px; }
.toolTabs > button { background: transparent; border: 0; border-bottom: 2px solid transparent; padding: 10px 1px 8px; font: inherit; font-size: 12px; line-height: 20px; color: var(--dsw-alias-label-secondary); cursor: pointer; }
.toolTabs > button[aria-selected=true] { color: var(--dsw-alias-label-primary); border-bottom-color: var(--dsw-alias-state-business-primary); }
.toolPanel { padding: 12px 14px 14px; display: flex; flex-direction: column; gap: 12px; min-width: 0; font-size: 13px; line-height: 22px; }
.toolPanel:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary); outline-offset: -3px; }
.toolDetailNote { margin: 0 0 9px; font-size: 12px; line-height: 20px; color: var(--dsw-alias-label-secondary); }
.toolRawLabel { margin: 0; color: var(--dsw-alias-label-secondary); font-size: 12px; font-weight: 500; }
.toolRaw { margin: 0; max-height: 400px; padding: 12px; overflow: auto; border-radius: 8px; background: var(--dsw-alias-bg-module-platform); color: var(--dsw-alias-label-primary); font: 12px/20px ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; overflow-wrap: anywhere; }
.systemPrompt { margin: 0; max-height: 320px; padding: 12px; overflow: auto; border-radius: 8px; background: var(--dsw-alias-bg-module-platform); color: var(--dsw-alias-label-primary); font: 12px/20px ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; overflow-wrap: anywhere; }
.commandInput { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
.toolReceipt .blocks, .toolDocument .blocks { font-size: 13px; line-height: 22px; }
.toolChildren { margin: 0 14px 12px var(--reader-rail, 6px); padding-left: var(--reader-gutter, 16px); border-left: 1px solid var(--dsw-alias-border-l2); display: flex; flex-direction: column; gap: 9px; }
@container (max-width: 420px) { .toolHeading { gap: 7px; padding: 11px 10px 6px; grid-template-columns: 16px minmax(0, 1fr) auto; } .toolHeadingState { gap: 4px; } .toolLedger { padding-left: 33px; padding-right: 10px; } .toolPanel { padding: 10px; } /* .toolChildren keeps the shared rail here too: a different left edge under a
narrow container is what made nested rows read as misplaced lines. */ }
@media (pointer: coarse) { .toolTabs > button { min-height: 44px; } }
/* Transitions.dev — Reasoning stream (user-supplied). Transform the one real
transcript; hand the painted offset to native scrolling for manual reading. */
.reasonCard {
--reason-preview-height: 224px;
--reason-hold: 840ms;
--reason-step: 500ms;
--reason-lines: 2;
--reason-fade: 28px;
--reason-ease: cubic-bezier(0.22, 1, 0.36, 1);
position: relative;
min-width: 0;
overflow: hidden;
border: 1px solid var(--dsw-alias-border-l2);
border-radius: 12px;
background: var(--dsw-alias-bg-module-platform);
scroll-margin-block: 16px calc(var(--dsh-composer-height, 152px) + 16px);
}
.reasonHeading { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; padding: 10px 16px 0; color: var(--dsw-alias-label-secondary); font-size: 12px; line-height: 20px; font-variant-numeric: tabular-nums; }
.reasonCard[data-overflow=false][data-expanded=false] { border-color: transparent; border-radius: 0; background: transparent; }
.reasonCard[data-overflow=false][data-expanded=false] .reasonHeading { padding: 0; }
.reasonCard[data-overflow=false][data-expanded=false] .reasonText { padding: 4px 0 0 22px; }
.reasonLabel { font-weight: 500; }
.reasonViewport {
position: relative;
max-height: var(--reason-preview-height);
overflow: auto;
scroll-behavior: auto;
overflow-anchor: none;
overscroll-behavior-y: contain;
scrollbar-width: thin;
scrollbar-color: var(--dsw-alias-border-l1) transparent;
}
.reasonCard[data-expanded=true] .reasonViewport { max-height: min(60vh, 560px, var(--reason-reading-height, 560px)); }
.reasonViewport[data-edges=both], .reasonCard[data-following=true][data-overflow=true] .reasonViewport {
-webkit-mask-image: linear-gradient(transparent 0, black var(--reason-fade), black calc(100% - var(--reason-fade)), transparent 100%);
mask-image: linear-gradient(transparent 0, black var(--reason-fade), black calc(100% - var(--reason-fade)), transparent 100%);
}
.reasonViewport[data-edges=top] {
-webkit-mask-image: linear-gradient(transparent 0, black var(--reason-fade), black 100%);
mask-image: linear-gradient(transparent 0, black var(--reason-fade), black 100%);
}
.reasonViewport[data-edges=bottom] {
-webkit-mask-image: linear-gradient(black 0, black calc(100% - var(--reason-fade)), transparent 100%);
mask-image: linear-gradient(black 0, black calc(100% - var(--reason-fade)), transparent 100%);
}
.reasonCard[data-expanded=true] .reasonViewport { -webkit-mask-image: none; mask-image: none; }
.reasonViewport:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary); outline-offset: -3px; }
.reasonTrack { position: relative; transform: translateY(0); }
.reasonCard[data-following=true] .reasonTrack { will-change: transform; }
.reasonText { padding: 8px 16px 16px; font-size: 14px; line-height: 24px; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; }
.reasonText .readingText > div { font-size: inherit; line-height: inherit; color: inherit; }
.reasonFooter { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 2px 10px 8px; font-size: 12px; line-height: 20px; color: var(--dsw-alias-label-secondary); }
.reasonAction { display: inline-flex; justify-content: center; align-items: center; gap: 5px; min-height: 28px; padding: 4px 6px; border: 0; border-radius: 6px; background: transparent; color: inherit; font: inherit; cursor: pointer; white-space: nowrap; }
.reasonAction:hover { background: var(--dsw-alias-interactive-bg-hover); }
.reasonAction:disabled { cursor: default; opacity: .65; }
.reasonAction svg { flex: none; fill: none; stroke: currentColor; stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }
.reasonCaption { padding-left: 6px; }
@container (max-width: 480px) { .reasonCard { --reason-preview-height: 192px; } }
@media (pointer: coarse) { .reasonAction { min-height: 44px; } }
@media (prefers-reduced-motion: reduce) { .reasonTrack { transition: none !important; transform: none !important; will-change: auto !important; } }
@media (forced-colors: active) { .reasonViewport { -webkit-mask-image: none !important; mask-image: none !important; } }
.processItem, .tool { margin: 0 0 18px; min-width: 0; }
.processLabel { display: flex; align-items: baseline; gap: 12px; margin: 0 0 6px; color: var(--dsw-alias-label-tertiary); font-size: 12px; line-height: 20px; }
.processFootnote { color: var(--dsw-alias-label-tertiary); margin: 14px 0 0; font-size: 12px; line-height: 20px; }
.detail { font-size: 13px; line-height: 22px; color: var(--dsw-alias-label-secondary); }
.detail > summary { cursor: pointer; padding: 3px 0; }
.detail[open] > summary { margin-bottom: 8px; }
.tool > .tool { margin: 10px 0 0 12px; }
.meta { font-size: 12px; line-height: 20px; color: var(--dsw-alias-label-tertiary); }
.stopped { align-self: flex-start; border-radius: 6px; padding: 0 6px; background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-tertiary); font-size: 11px; line-height: 18px; margin-top: 12px; }
.compactionRow { display: flex; flex-direction: column; align-items: center; margin: 16px 0; width: 100%; box-sizing: border-box; }
.compactionLine { display: flex; align-items: center; justify-content: center; gap: 12px; width: 100%; color: var(--dsw-alias-label-tertiary); font-size: 11px; line-height: 18px; user-select: none; }
.compactionLine::before, .compactionLine::after { content: ''; flex: 1; height: 1px; background: var(--dsw-alias-border-l1); opacity: .7; }
/* The divider arrives rather than simply appearing: the rule sweeps out from the
middle, the pill settles in, and its dial turns once. Same idiom (and the same
motion gates) as the rest of the reader's transitions. */
.compactionRow > .compactionLine { animation: compactionLineIn 520ms cubic-bezier(.4,0,.2,1) both; }
.compactionRow > .compactionLine > .compactionPill { animation: compactionPillIn 420ms 120ms cubic-bezier(.34,1.4,.64,1) both; }
.compactionRow > .compactionLine .compactionIcon { animation: compactionDial 900ms 200ms cubic-bezier(.4,0,.2,1) both; }
@keyframes compactionLineIn {
from { opacity: 0; transform: scaleX(.6); }
to { opacity: 1; transform: scaleX(1); }
}
@keyframes compactionPillIn {
from { opacity: 0; transform: translateY(-6px) scale(.94); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes compactionDial {
from { transform: rotate(-140deg); opacity: 0; }
to { transform: rotate(0deg); opacity: .7; }
}
[data-motion=off] .compactionRow > .compactionLine,
[data-motion=off] .compactionRow > .compactionLine > .compactionPill,
[data-motion=off] .compactionRow > .compactionLine .compactionIcon { animation: none !important; }
@media (prefers-reduced-motion: reduce) {
.compactionRow > .compactionLine,
.compactionRow > .compactionLine > .compactionPill,
.compactionRow > .compactionLine .compactionIcon { animation: none !important; }
}
.compactionPill { display: inline-flex; align-items: center; gap: 6px; padding: 2px 10px; border-radius: 12px; background: var(--dsw-alias-bg-module-platform); border: 1px solid var(--dsw-alias-border-l1); color: var(--dsw-alias-label-tertiary); font-size: 11px; line-height: 18px; font-family: inherit; }
.compactionButton { cursor: pointer; transition: color 140ms ease, border-color 140ms ease, background-color 140ms ease; }
.compactionButton:hover { color: var(--dsw-alias-label-primary); border-color: var(--dsw-alias-border-l2); background: var(--dsw-alias-interactive-bg-hover); }
.compactionIcon { width: 12px; height: 12px; flex: none; opacity: .7; }
.compactionToggle { font-size: 10px; opacity: .8; margin-left: 2px; }
.compactionSummaryBox { margin-top: 10px; width: 100%; max-width: 680px; padding: 12px 16px; border-radius: 8px; background: var(--dsw-alias-bg-module-platform); border: 1px solid var(--dsw-alias-border-l2); font-size: 12px; line-height: 20px; color: var(--dsw-alias-label-secondary); box-sizing: border-box; }
.compactionSummaryHeader { font-size: 11px; font-weight: 500; color: var(--dsw-alias-label-tertiary); margin-bottom: 8px; padding-bottom: 4px; border-bottom: 1px dashed var(--dsw-alias-border-l1); }
.notice, .error, .attention { border-radius: 10px; padding: 12px 14px; font-size: 13px; line-height: 20px; overflow-wrap: anywhere; }
.notice { background: var(--dsw-alias-bg-module-platform); color: var(--dsw-alias-label-secondary); border: 1px solid var(--dsw-alias-border-l2); }
.error { display: flex; align-items: flex-start; gap: 10px; background: rgba(239, 68, 68, 0.06); border: 1px solid rgba(239, 68, 68, 0.22); color: var(--dsw-alias-label-primary); }
.errorIcon { width: 16px; height: 16px; flex: none; margin-top: 2px; color: #ef4444; }
.errorCopy { flex: 1; min-width: 0; }
.errorTitle { display: flex; align-items: center; gap: 8px; color: #dc2626; font-weight: 500; margin-bottom: 2px; }
.errorMessage { margin: 0; color: var(--dsw-alias-label-secondary); font-size: 12px; line-height: 18px; word-break: break-word; }
.errorCode { font-size: 11px; padding: 1px 5px; border-radius: 4px; background: rgba(239, 68, 68, 0.12); color: #dc2626; font-family: inherit; }
.attention { display: flex; flex-direction: column; gap: 3px; border: 1px solid var(--dsw-alias-state-business-primary); color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-base); }
.attention span { color: var(--dsw-alias-label-secondary); }
.unknown { background: var(--dsw-alias-bg-module-platform); border: 1px solid var(--dsw-alias-border-l2); border-radius: 10px; padding: 12px 14px; font-size: 13px; line-height: 22px; }
.unknown p { margin: 0 0 6px; }
.historyButton { align-self: center; background: transparent; border: 1px solid var(--dsw-alias-border-l2); border-radius: 8px; padding: 4px 12px; font-size: 12px; color: var(--dsw-alias-label-secondary); }
.historyButton:disabled { opacity: .55; cursor: default; }
.empty { padding: 40px 0; color: var(--dsw-alias-label-tertiary); text-align: center; }
.answerActions { display: flex; align-items: center; gap: 8px; margin: 13px 0 0 -6px; min-height: 28px; }
.userActions { display: flex; align-items: center; gap: 8px; min-height: 28px; }
.messageClock { font-size: 13px; line-height: 24px; color: var(--dsw-alias-label-tertiary); white-space: nowrap; font-variant-numeric: tabular-nums; }
.iconButton { display: inline-flex; align-items: center; justify-content: center; border: 0; border-radius: 6px; padding: 6px; background: transparent; color: var(--dsw-alias-label-tertiary); }
.iconButton svg { fill: none; stroke: currentColor; stroke-width: 1.2; stroke-linecap: round; stroke-linejoin: round; }
.imageFigure { margin: 0; max-width: 100%; width: min(100%, 360px); box-sizing: border-box; align-self: flex-start; }
.imageFrame { position: relative; border-radius: 12px; background: var(--dsw-alias-bg-module-platform); border: 1px solid var(--dsw-alias-border-l2); overflow: hidden; max-height: 440px; min-height: 96px; max-width: 100%; box-sizing: border-box; }
.imageOpen { border: 0; padding: 0; position: absolute; inset: 0; background: transparent; display: flex; width: 100%; height: 100%; }
.imageOpen img { display: block; width: 100%; height: 100%; object-fit: contain; opacity: 0; transition: opacity 200ms cubic-bezier(.4,0,.2,1); }
.imageOpen img[data-ready=true] { opacity: 1; }
.pendingImage { display: block; width: 100%; height: 100%; max-width: 100%; object-fit: contain; }
.imagePlaceholder { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 8px; color: var(--dsw-alias-label-tertiary); font-size: 13px; pointer-events: none; }
.imagePlaceholder button { pointer-events: auto; }
.imageFigure figcaption { color: var(--dsw-alias-label-tertiary); font-size: 12px; line-height: 20px; margin-top: 6px; overflow-wrap: anywhere; }
.imageDialog { border: 1px solid var(--dsw-alias-border-l2); padding: 38px 20px 20px; border-radius: 16px; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); max-width: 90vw; max-height: 90vh; }
.imageDialog::backdrop { background: var(--dsw-alias-bg-mask-photo); }
.imageDialog img { max-width: 82vw; max-height: 75vh; display: block; object-fit: contain; }
.dialogClose { position: absolute; right: 8px; top: 4px; border: 0; background: transparent; color: inherit; width: 32px; height: 32px; border-radius: 8px; font-size: 24px; }
.jumpDock { position: sticky; bottom: calc(var(--dsh-composer-height, 152px) + 16px); height: 0; z-index: 8; display: flex; justify-content: flex-end; pointer-events: none; }
.deliverablesRoot { display: grid; grid-template-columns: max-content minmax(0, 1fr); align-items: start; column-gap: 10px; margin-top: 14px; font-size: 13px; line-height: 22px; }
.deliverablesLabel { grid-column: 1; grid-row: 1; color: var(--dsw-alias-label-tertiary); font-size: 12px; padding-top: 2px; font-weight: 500; }
.deliverablesLane { grid-column: 2; grid-row: 1; min-width: 0; }
.deliverablesRow { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; }
.deliverableChip { box-sizing: border-box; display: inline-flex; align-items: center; border: 1px solid var(--dsw-alias-border-l2); border-radius: 6px; background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-secondary); font-size: 12px; line-height: 20px; transition: border-color 160ms ease, background-color 160ms ease, color 160ms ease; overflow: hidden; }
.deliverableChip:hover { border-color: var(--dsw-alias-border-l3); background: var(--dsw-alias-bg-module-platform); box-shadow: 0 1px 4px var(--dsw-alias-border-l1); }
.deliverableChip[data-status=opened] { border-color: #10b981; background: rgba(16, 185, 129, 0.12); color: #059669; }
.chipMain { display: inline-flex; align-items: center; gap: 5px; max-width: 220px; padding: 3px 6px 3px 8px; border: none; background: transparent; color: inherit; font: inherit; cursor: pointer; text-align: left; }
.chipMain:hover { color: var(--dsw-alias-label-primary); }
.deliverableIcon, .statusIcon { width: 13px; height: 13px; flex: none; opacity: .8; }
.statusIcon { color: #10b981; }
.deliverableName { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chipActions { display: inline-flex; align-items: center; gap: 2px; padding-right: 4px; border-left: 1px solid transparent; opacity: .65; transition: opacity 150ms ease, border-left-color 150ms ease; }
.deliverableChip:hover .chipActions { opacity: 1; border-left-color: var(--dsw-alias-border-l2); }
.chipActionBtn { display: inline-flex; align-items: center; justify-content: center; width: 20px; height: 20px; padding: 0; border: none; border-radius: 4px; background: transparent; color: var(--dsw-alias-label-tertiary); cursor: pointer; transition: color 120ms ease, background-color 120ms ease; }
.chipActionBtn:hover { color: var(--dsw-alias-label-primary); background: var(--dsw-alias-interactive-bg-hover); }
.actionIcon { width: 12px; height: 12px; }
.deliverablesMore { font-size: 12px; color: var(--dsw-alias-label-tertiary); white-space: nowrap; }
.deliverablesShowFolder { border: 1px solid transparent; background: transparent; color: var(--dsw-alias-label-tertiary); font: inherit; font-size: 12px; cursor: pointer; padding: 2px 7px; border-radius: 5px; display: inline-flex; align-items: center; gap: 4px; transition: all 150ms ease; }
.deliverablesShowFolder:hover { color: var(--dsw-alias-state-business-primary); background: var(--dsw-alias-interactive-bg-hover); border-color: var(--dsw-alias-border-l2); }
.deliverablesShowFolder[data-status=opened] { color: #10b981; border-color: rgba(16, 185, 129, 0.3); background: rgba(16, 185, 129, 0.08); }
.morphCluster { display: flex; flex-direction: column; width: 100%; min-width: 0; }
.morphDrawer { overflow: hidden; height: 0; transform-origin: top center; will-change: height, opacity, transform; }
.liveFoldImpact { animation: liveFoldElastic 180ms cubic-bezier(0.2, 0, 0, 1) both; }
@keyframes liveFoldElastic { 0% { transform: scale(1); } 50% { transform: scale(1.015); } 100% { transform: scale(1); } }
.liveFoldContainer { position: sticky; top: calc(var(--reader-toolbar-height, var(--reader-lane-block, 40px)) + var(--reader-status-height, var(--reader-lane-block, 40px)) + var(--reader-summary-height, var(--reader-lane-block, 40px))); z-index: 4; background: var(--dsw-alias-bg-base); backdrop-filter: blur(12px); padding: 4px 0; margin-bottom: 6px; animation: liveFoldPulse 320ms cubic-bezier(0.16, 1, 0.3, 1) both; transform-origin: left center; will-change: transform, opacity; }
@keyframes liveFoldPulse { 0% { transform: translateY(-4px) scale(0.98); opacity: 0.8; } 50% { transform: translateY(0) scale(1.02); opacity: 1; } 100% { transform: translateY(0) scale(1); opacity: 1; } }
[data-motion=off] .liveFoldContainer { animation: none !important; }
@media (prefers-reduced-motion: reduce) { .liveFoldContainer { animation: none !important; } }
.priorFoldDrawer { display: flex; flex-direction: column; gap: 14px; min-width: 0; width: 100%; }
.jump { margin-top: -34px; flex: none; width: 34px; height: 34px; display: flex; justify-content: center; align-items: center; padding: 0; border: 0; border-radius: 100px; color: var(--dsw-alias-label-primary); background: var(--dsw-alias-button-floating-fill, var(--dsw-alias-bg-base)); box-shadow: var(--dsw-elevation-panel, 0 2px 8px var(--dsw-alias-border-l1)); pointer-events: auto; }
.jump:hover { background: var(--dsw-alias-button-floating-hover, var(--dsw-alias-interactive-bg-hover)); }
/* The digest is a single line. nowrap on the parent does not stop the parts
from wrapping, so each part is pinned too and the run clips with an ellipsis
when the column is narrow. */
.foldSummary { display: inline-flex; align-items: baseline; white-space: nowrap !important; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
.foldSummaryPart { display: inline-flex; align-items: baseline; white-space: nowrap !important; flex: none; }
.numberRollRoot { display: inline-flex; position: relative; overflow: hidden; vertical-align: baseline; line-height: inherit; font-variant-numeric: tabular-nums; font-feature-settings: "tnum"; white-space: nowrap !important; flex-shrink: 0; min-width: 1.45em; justify-content: center; text-align: center; }
.numberRollSizer { visibility: hidden; user-select: none; pointer-events: none; line-height: inherit; white-space: nowrap; }
.numberRollDigit { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; line-height: inherit; white-space: nowrap; }
.numberRollExit { animation: numberRollOut 240ms cubic-bezier(0.16, 1, 0.3, 1) forwards; }
.numberRollEnter { animation: numberRollIn 240ms cubic-bezier(0.16, 1, 0.3, 1) forwards; }
@keyframes numberRollOut { from { transform: translateY(0); opacity: 1; } to { transform: translateY(-100%); opacity: 0; } }
@keyframes numberRollIn { from { transform: translateY(100%); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
[data-motion=off] .chevron, [data-motion=off] .imageOpen img, [data-motion=off] .processMeta, [data-motion=off] .numberRollDigit { transition: none !important; animation: none !important; }
@media (prefers-reduced-motion: reduce) { .chevron, .imageOpen img, .processMeta, .numberRollDigit { transition: none !important; animation: none !important; } }
.turnStatus { align-self: flex-start; flex: none; display: inline-flex; align-items: center; height: 26px; font-size: 14px; line-height: 22px; white-space: nowrap; margin: 4px 0 12px; padding: 0 4px; }
.turnStatusLabel { font-weight: 500; background: linear-gradient(90deg, var(--dsw-static-deepseek-500, #4d6bfe) 0%, var(--dsw-static-deepseek-500, #4d6bfe) 40%, var(--dsw-static-deepseek-200, #a8c7fa) 50%, var(--dsw-static-deepseek-500, #4d6bfe) 60%, var(--dsw-static-deepseek-500, #4d6bfe) 100%); background-position: 100% 0; background-size: 250% 100%; background-clip: text; color: transparent; -webkit-background-clip: text; -webkit-text-fill-color: transparent; animation: dsh-turn-status-shimmer 1.8s linear infinite; }
/* The status line and its clock sit on one row, so a wait is timed right where the
reader is looking; the bar fills toward ten seconds and then holds while the
readout keeps counting and the badge appears. */
.waitClock { display: inline-flex; align-items: center; flex: none; margin-left: 8px; }
.waitSeconds { font-size: 13px; font-weight: 400; font-variant-numeric: tabular-nums;
font-feature-settings: "tnum"; color: var(--dsw-alias-label-caption, #86909c); }
.waitOvertime { margin-left: 8px; padding: 0 6px; font-size: 11px; line-height: 16px; border-radius: 5px;
color: var(--dsw-alias-state-warning-primary, #d8862c);
background: color-mix(in srgb, var(--dsw-alias-state-warning-primary, #d8862c) 16%, transparent); }
.turnStatusClock { margin-left: 8px; font-size: 13px; font-weight: 400; font-variant-numeric: tabular-nums; font-feature-settings: "tnum"; color: var(--dsw-alias-label-caption, #86868b); -webkit-text-fill-color: var(--dsw-alias-label-caption, #86868b); }
@keyframes dsh-turn-status-shimmer { to { background-position: 0 0; } }
[data-motion=off] .turnStatusLabel { animation: none !important; color: var(--dsw-static-deepseek-500, #4d6bfe) !important; -webkit-text-fill-color: var(--dsw-static-deepseek-500, #4d6bfe) !important; }
@media (prefers-reduced-motion: reduce) { .turnStatusLabel { animation: none !important; color: var(--dsw-static-deepseek-500, #4d6bfe) !important; -webkit-text-fill-color: var(--dsw-static-deepseek-500, #4d6bfe) !important; } }
@media (pointer: coarse) { .disclosureButton { min-height: 44px; } }
@media (max-width: 600px) { .root { padding-inline: 20px; } .column { gap: 18px; } .toolbar { font-size: 11px; } }
/* Measured flow owns geometry; steps never change React parents when folded. */
.choreographedFlow { display: flex; flex-direction: column; min-width: 0; overflow-anchor: none; }
.flowCell { min-width: 0; overflow: clip; display: flow-root; }
.flowCell[hidden] { display: none; }
.flowCellInner { display: flex; flex-direction: column; min-width: 0; padding-bottom: 16px; }
/* A null-rendered ProcessFragment must contribute no cumulative row spacing. */
.flowCellInner:empty { padding-bottom: 0; }
.choreographedFlow[data-reader-transition=collapse] .flowCell * { animation-play-state: paused !important; }
.numberRollExit, .numberRollEnter { animation-duration: 160ms; }
.foldSummary { display: inline-flex; align-items: baseline; flex-wrap: nowrap !important; white-space: nowrap !important; }
/* A flex item's intrinsic width must include its real label and chevron.
The previous shrink-to-fit + max-width chain clipped even four CJK glyphs. */
/* Footer precedence (host ConversationRoot): the sticky composer seat owns
z-index 7, its own sticky code banner is 6 and the floating controls are 8.
Every reader lane a scroll can clamp down into the footer band must stay
strictly below 7, otherwise the reader paints its own opaque plate over the
input card. Only the top toolbar lane may use 7: it pins to the scrollport's
first lane and its containing block always ends above the seat, so it can
never reach the band, and 7 keeps it above the host's code-block banners. */
.toolbar { width: 100%; max-width: 100%; align-self: stretch; box-sizing: border-box; min-height: var(--reader-lane-block, 40px); z-index: 7; border-bottom: 0; backdrop-filter: none; }
/* Every sticky lane used to pin to the SAME top: the status row, the folded
summary row and the live-fold container all sat at
max(toolbar-height, status-height) with z-index 6. Three siblings competing
for one slot paint over each other in scroll order, which is what "展开以后
内容被盖住、看不见" was: the disclosure opened, and the row that followed
pinned straight on top of it. Give each lane its own band instead, stacked
from the measured top: status first, then the summary, then the fold body. */
.turnProcessSticky { box-sizing: border-box; width: calc(100% - var(--reader-control-width, 148px)); top: var(--reader-toolbar-height, var(--reader-lane-block, 40px)); min-height: var(--reader-lane-block, 40px); padding-right: 0; z-index: 6; border-bottom: 1px solid transparent; background-clip: padding-box; backdrop-filter: none; }
/* A pinned lane's in-flow gap stays visible as an uncovered scrollport strip
while the lane itself paints opaque. Cast each plate upward over its strip
(the .turn 14px gap / the prior cell's 16px flowCellInner padding) so the
lanes read as one band instead of solid plates with notches between them.
The status lane reserves --reader-control-width on its right for the
toolbar's control group, which leaves the same kind of strip there; paint
it too. The toolbar is z-index 7, above the lane's 6, so its buttons still
render on top of the extension. */
.turnProcessSticky { box-shadow: 0 -14px 0 var(--dsw-alias-bg-base), var(--reader-control-width, 148px) 0 0 var(--dsw-alias-bg-base), 0 -14px 0 var(--dsw-alias-bg-layer-1, transparent), var(--reader-control-width, 148px) 0 0 var(--dsw-alias-bg-layer-1, transparent), 0 -14px 0 Canvas, var(--reader-control-width, 148px) 0 0 Canvas; }
.turnStickyLanes .turnProcessSticky, .turnStickyLanes .closedProcessSummary { position: static; top: auto; z-index: auto; }
/* The same summary row stays in flow until it reaches the measured top lane. */
.flowCell[data-flow-summary], .closedProcessSummary { position: sticky; top: calc(var(--reader-toolbar-height, var(--reader-lane-block, 40px)) + var(--reader-status-height, var(--reader-lane-block, 40px))); z-index: 5; overflow: visible; box-sizing: border-box; min-height: var(--reader-lane-block, 40px); padding-block: 4px; background: var(--dsw-alias-bg-base); border-bottom: 0; }
/* Keep the official CodeBlock banner's internal z-index inside its wrapper so Reader lanes stay above it. */
.root :global(.md-code-block) { z-index: 0; }
/* Keep native code actions below the pinned Reader lanes. */
.turnStickyRegion:has(> .turnStickyLanes > .closedProcessSummary), .turnStickyRegion:has(.flowCell[data-flow-summary]) { --reader-code-summary-height: var(--reader-summary-height, var(--reader-lane-block, 40px)); }
.root :global(.md-code-block > :has(+ [data-code-block-content])) { top: calc(max(var(--reader-toolbar-height, 40px), var(--reader-status-height, 0px)) + var(--reader-status-height, 0px) + var(--reader-code-summary-height, 0px)); }
.flowCell[data-flow-summary] { box-shadow: 0 -16px 0 var(--dsw-alias-bg-base), 0 -16px 0 var(--dsw-alias-bg-layer-1, transparent), 0 -16px 0 Canvas; }
.closedProcessSummary { box-shadow: 0 -14px 0 var(--dsw-alias-bg-base), 0 -14px 0 var(--dsw-alias-bg-layer-1, transparent), 0 -14px 0 Canvas; }
.foldControl { display: inline-flex; align-items: center; gap: 0; padding: 2px; border-radius: 8px; background: var(--dsw-alias-bg-module-platform); }
.foldStop { border: 0; background: transparent; color: var(--dsw-alias-label-secondary); padding: 2px 8px; border-radius: 6px; white-space: nowrap; font: inherit; font-size: 12px; line-height: 18px; cursor: pointer; }
.foldStop[data-on] { background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); }
.flowCell[data-flow-summary] > .flowCellInner { padding-bottom: 0; }
.flowCell[data-flow-summary] .disclosureButton, .closedProcessSummary .disclosureButton { width: auto; max-width: 100%; }
.flowCell[data-flow-summary] .foldSummary, .closedProcessSummary .foldSummary { min-width: 0; }
.turnProcessSticky > .disclosure { flex: 1 1 auto; min-width: 0; }
.disclosureButton { width: max-content; max-width: calc(100% + 6px); }
.statusText { flex: 0 1 auto; }
.think { width: max-content; min-width: 0; }
.thinkSizer { white-space: normal; overflow-wrap: anywhere; }
.thinkText { white-space: normal; overflow-wrap: anywhere; overflow: visible; text-overflow: clip; }
/* Theme layers sit on an opaque page surface. A cleared token, or one at
10% opacity, composites over Canvas instead of the text colour, and the
heading underneath cannot show through. */
.toolbar,
.turnStickyLanes,
.turnProcessSticky,
.liveFoldContainer,
.flowCell[data-flow-summary],
.closedProcessSummary {
background-color: Canvas;
background-image: var(--reader-lane-plate);
background-repeat: no-repeat;
}
/* Skin mode is opt-in, and it has one job: some readers run a skinned host
(wallpaper / theme), and the reader's own opaque rows hide that skin. On =
every surface the reader paints becomes a thin token-derived wash and the
decorative chrome (border, 16px radius, floating shadow) is dropped, so the
skin stays visible across the whole reading view. Off keeps the pre-#14 /
current-main opaque chrome. */
.root[data-reader-glass] .toolbar,
.root[data-reader-glass] .turnProcessSticky,
.root[data-reader-glass] .liveFoldContainer {
background: transparent;
backdrop-filter: blur(16px);
border: 0;
border-radius: 0;
box-shadow: none;
}
/* Keep the skin visible between controls without changing the sticky lanes. */
.root[data-reader-glass] .toolbar,
.root[data-reader-glass] .turnProcessSticky {
backdrop-filter: none;
}
.root[data-reader-glass] .toolbar {
pointer-events: none;
}
.root[data-reader-glass] .toolbar > .textButton,
.root[data-reader-glass] .turnProcessSticky .disclosureButton {
pointer-events: auto;
padding: 2px 10px;
border-radius: 999px;
background: color-mix(in srgb, var(--dsw-alias-bg-layer-1, rgba(255, 255, 255, .7)) 80%, transparent);
backdrop-filter: blur(12px);
}
.root[data-reader-glass] .turnProcessSticky .disclosureButton {
margin-left: 0;
max-width: 100%;
}
.root[data-reader-glass] .toolbar > .textButton:hover,
.root[data-reader-glass] .turnProcessSticky .disclosureButton:hover {
background: var(--dsw-alias-interactive-bg-hover);
}
/* The z-index ladder is mode-independent: skin mode only drops the plate, so
a glass reader keeps exactly the same footer precedence as an opaque one. */
.root[data-reader-glass] .flowCell[data-flow-summary],
.root[data-reader-glass] .closedProcessSummary {
box-shadow: none;
position: static;
z-index: auto;
min-height: 32px;
padding-block: 2px;
background: transparent;
border-left: 2px solid color-mix(in srgb, var(--dsw-alias-border-l2, rgba(128,128,128,.35)) 80%, transparent);
padding-left: 10px;
border-radius: 0;
}
.root[data-reader-glass] .turnStickyLanes { display: contents; position: static; top: auto; z-index: auto; }
.root[data-reader-glass] .turnStickyRegion { --reader-code-summary-height: 0px; }
.root[data-reader-glass] .turnStickyLanes .turnProcessSticky { position: sticky; top: var(--reader-toolbar-height, var(--reader-lane-block, 40px)); z-index: 6; }
/* User bubble becomes a sleek translucent frosted pill in skin mode */
.root[data-reader-glass] .user {
background: color-mix(in srgb, var(--dsw-specific-bubble, rgba(0,0,0,.08)) 25%, transparent);
backdrop-filter: blur(12px);
border: 1px solid color-mix(in srgb, var(--dsw-alias-border-l1, rgba(128,128,128,.3)) 30%, transparent);
}
/* Skin mode paints no plates of the reader's own: cards, panels and frames go
fully transparent so the skin behind them stays visible. */
.root[data-reader-glass] .reasonCard {
background: transparent;
border-color: color-mix(in srgb, var(--dsw-alias-border-l1, rgba(128,128,128,.35)) 65%, transparent);
}
.root[data-reader-glass] .toolDetails,
.root[data-reader-glass] .notice,
.root[data-reader-glass] .unknown,
.root[data-reader-glass] .toolRaw,
.root[data-reader-glass] .systemPrompt,
.root[data-reader-glass] .compactionSummaryBox,
.root[data-reader-glass] .attention,
.root[data-reader-glass] .imageFrame,
.root[data-reader-glass] .imageDialog {
background: transparent;
}
/* Diff overlay in skin mode */
.root[data-reader-glass] .diffOverlay {
background: color-mix(in srgb, var(--dsw-alias-bg-module-platform, rgba(127,127,127,.1)) 20%, transparent);
backdrop-filter: blur(16px);
}
.root[data-reader-glass] .diffScrollArea {
background: transparent;
}
.root[data-reader-glass] .diffTab {
background: color-mix(in srgb, var(--dsw-alias-bg-base, rgba(255,255,255,.8)) 25%, transparent);
}
.root[data-reader-glass] .diffTab[data-active] {
background: color-mix(in srgb, var(--dsw-alias-bg-base, rgba(255,255,255,1)) 45%, transparent);
}
/* Code blocks translucent in skin mode */
.root[data-reader-glass] :global(.md-code-block),
.root[data-reader-glass] :global([data-diff]) {
background: color-mix(in srgb, var(--dsw-alias-markdown-code-block, rgba(0,0,0,.06)) 25%, transparent) !important;
border: 1px solid color-mix(in srgb, var(--dsw-alias-border-l1, rgba(128,128,128,.2)) 30%, transparent);
backdrop-filter: blur(12px);
}
/* The fold control rides a sticky row: it must not paint a plate of its own. */
.root[data-reader-glass] .foldControl {
background: color-mix(in srgb, var(--dsw-alias-bg-module-platform, rgba(127,127,127,.1)) 25%, transparent);
border: 1px solid color-mix(in srgb, var(--dsw-alias-border-l2, rgba(128,128,128,.2)) 30%, transparent);
}
.root[data-reader-glass] .foldStop[data-on] {
background: color-mix(in srgb, var(--dsw-alias-bg-base, rgba(255,255,255,1)) 35%, transparent);
}
.root[data-reader-glass] .compactionPill,
.root[data-reader-glass] .deliverableChip,
.root[data-reader-glass] .toolState,
.root[data-reader-glass] .diffStatButton {
background: transparent;
border-color: transparent;
}
.root[data-reader-glass] .compactionPill:hover,
.root[data-reader-glass] .compactionPill:focus-visible,
.root[data-reader-glass] .deliverableChip:hover,
.root[data-reader-glass] .deliverableChip:focus-within,
.root[data-reader-glass] .toolState:hover,
.root[data-reader-glass] .diffStatButton:hover,
.root[data-reader-glass] .diffStatButton:focus-visible,
.root[data-reader-glass] .diffStatButton[aria-expanded="true"] {
background: var(--dsw-alias-bg-module-platform, rgba(127, 127, 127, .1));
border-color: var(--dsw-alias-border-l2, rgba(127, 127, 127, .28));
}
/* Host rc.5 keeps [data-composer-seat] mounted on every conversation tab and
pins it to the scrollport. dsh-claude-style 0.19.x hides that seat whenever
the first tab is not 对话 (`display: none !important` under
[data-dsh-claude-composer-hidden]). This rule wins only while the reader
root is mounted, so opening on 阅读 can type immediately. Switching to
轨迹 unmounts the reader and the skin's rule applies again. The seat's own
display is flex. Keep this selector in sync with READER_COMPOSER_RESTORE. */
:global(html body[data-dsh-claude-style][data-dsh-claude-composer-active] [data-dsh-claude-composer-hidden]:has([data-dsh-better-display]) [data-composer-seat]) {
display: flex !important;
}

912
src/client/Reader.tsx Normal file
View File

@ -0,0 +1,912 @@
import type {} from '@deepseek-ai/dsh-session-turn-outline/types';
import type {} from '@deepseek-ai/dsh-agent/types';
import { Fragment, memo, useCallback, useEffect, useId, useInsertionEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import type { ReactNode, RefObject } from 'react';
import type { ChatConversationViewNode, ChatNode, ChatNodeKind, ChatNodeOwnerProps } from '@deepseek-ai/dsh-client-ui-chat/client';
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store';
import { JsonBlock, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives';
import { BlockBoundary, Blocks, contentBlocks, UserMessageActions } from './Blocks.js';
import { AssistantNode } from './AssistantNode.js';
import { ToolActivity, ToolMedia } from './ToolActivity.js';
import { OfficialNode, OfficialTail } from './OfficialContent.js';
import { OFFICIAL_SEATS, readerGroupAction } from './official-slots.js';
import { preparingLabel, readerFlow } from './tool-activity.js';
import { Disclosure, ProcessFragment, RetiringTurns, StatusText, useMotionAllowed, usePinnedSelection, useReadingScroll } from './motion.js';
import { StreamMotionContext } from './streaming.js';
import { boundaryOf, forkAnchorSeq, groupNodes, hasProcessContent, processChoiceKey, processExpanded, terminalLabel } from './projection.js';
import { basename, createProducedFileMentions, dirname, getTurnDeliverables, showDeliverablesRow } from './deliverables.js';
import { deliverableOpenModeOf, type DeliverableOpenMode } from './open-file.js';
import { asReadonlyArray, pendingSubmissionImages, type PendingSubmissionEcho } from './pending-submission.js';
import { WaitingStatus } from './WaitingStatus.js';
import { handsBackToModel, waitingAnchor } from './waiting-clock.js';
import { ContextInjectionRow } from './native/ContextInjectionRow.js';
import { TimelineRail } from './TimelineRail.js';
import { landTurn, scrollerOf } from './conversation-scroll.js';
import { mergeTimelineItems, type TimelineItem } from './timeline.js';
import { planProcessSeams, presentLiveTurn, segmentLiveTurn } from './live-turn.js';
import type { LiveStep } from './live-turn.js';
import { frostedGlassOf } from './fold-intensity.js';
import { ChoreographedFlow, useFlowChat } from './ChoreographedFlow.js';
import { ClosedProcessSummary } from './ClosedProcessSummary.js';
import { ReaderLaneScope, StickyLane } from './StickyLane.js';
import type { ReaderGroup, TurnBoundary } from './projection.js';
import type { BlockRenderProps, ReaderProps } from './types.js';
import css from './Reader.module.css';
import { markdownLabels, truncatedJsonLabel } from './primitive-labels.js';
import { chatSeatProps } from './chat-seat.js';
import { visibleChatKeys, visibleChatSignature } from './rewind-cut.js';
import { ensureStyles } from './styles.js';
function isNode<K extends ChatNodeKind>(node: ChatConversationViewNode, kind: K): node is ChatNode<K> {
return node.kind === kind;
}
function observedInputIds(order: readonly string[], getNode: (key: string) => ChatConversationViewNode | undefined): Set<string> {
const ids = new Set<string>();
for (const key of order) {
const node = getNode(key);
if (!node || (node.kind !== 'user' && node.kind !== 'steering' && node.kind !== 'turn-trigger')) continue;
const source = (node.data as { source?: { kind?: string; rpcId?: unknown } }).source;
if (source?.kind === 'user' && typeof source.rpcId === 'string') ids.add(source.rpcId);
}
return ids;
}
function inboxText(item: { content?: readonly unknown[] }): string {
return (item.content ?? []).filter((block): block is { type: 'text'; text: string } => {
return typeof block === 'object' && block !== null && (block as { type?: unknown }).type === 'text' && typeof (block as { text?: unknown }).text === 'string';
}).map(block => block.text).join('');
}
function inboxAttachmentCount(item: { content?: readonly unknown[] }): number {
return (item.content ?? []).filter(block => typeof block === 'object' && block !== null && (block as { type?: unknown }).type !== 'text').length;
}
function cleanErrorMessage(raw: string | undefined): string {
if (!raw) return '模型服务暂时无响应或连接中断,请稍后重试。';
let str = raw.trim();
if (str.includes('"error"') || str.startsWith('{')) {
try {
const idx = str.indexOf('{');
const parsed = JSON.parse(str.slice(idx));
const msg = parsed?.error?.message || parsed?.message || parsed?.error;
if (typeof msg === 'string') str = msg;
} catch {
// keep
}
}
return str;
}
type SeatProps = BlockRenderProps & Pick<ReaderProps, 'useChat' | 'sessionId'> & {
nodeKey: string; boundary: TurnBoundary; pinned?: boolean; processOpen?: boolean;
};
const CompactionDivider = memo(function CompactionDivider({ data }: {
data: { summary?: string | null; shadowedItemCount?: number | null; shadowedTokenCount?: number | null } | null;
}) {
const [open, setOpen] = useState(false);
if (!data) return null;
const hasSummary = typeof data.summary === 'string' && data.summary.trim().length > 0;
const items = data.shadowedItemCount;
const tokens = data.shadowedTokenCount;
let label = '已压缩历史上下文';
if (items && tokens) {
const kTokens = tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : String(tokens);
label = `已压缩 ${items} 条上下文 · 释放约 ${kTokens} tokens`;
} else if (items) {
label = `已压缩 ${items} 条上下文`;
} else if (tokens) {
const kTokens = tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : String(tokens);
label = `已压缩上下文 · 释放约 ${kTokens} tokens`;
}
return (
<div className={css.compactionRow} data-reader-compaction>
<div className={css.compactionLine}>
{hasSummary ? (
<button
type="button"
className={`${css.compactionPill} ${css.compactionButton}`}
onClick={() => setOpen(v => !v)}
aria-expanded={open}
title={open ? '收起历史记忆摘要' : '展开查看此节点提炼的记忆摘要'}
>
<svg className={css.compactionIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<path d="M8 2a6 6 0 1 0 0 12A6 6 0 0 0 8 2z" strokeWidth="1.2" />
<path d="M8 5v3.2l2 1.8" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
<span>{label}</span>
<span className={css.compactionToggle}>{open ? '收起备忘' : '查看备忘'}</span>
</button>
) : (
<span className={css.compactionPill}>
<svg className={css.compactionIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<path d="M8 2a6 6 0 1 0 0 12A6 6 0 0 0 8 2z" strokeWidth="1.2" />
<path d="M8 5v3.2l2 1.8" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
<span>{label}</span>
</span>
)}
</div>
{open && hasSummary && (
<div className={css.compactionSummaryBox} data-reader-anchor>
<div className={css.compactionSummaryHeader}>前期对话要点备忘</div>
<MarkdownText text={data.summary!} labels={markdownLabels} />
</div>
)}
</div>
);
});
const ProcessNode = memo(function ProcessNode({ useChat, t, nodeKey, open, motion, onRead, returnFocusTo }: Pick<ReaderProps, 'useChat' | 't'> & {
nodeKey: string; open: boolean; motion: boolean; onRead: () => void; returnFocusTo: RefObject<HTMLButtonElement>;
}) {
const node = useChat(snapshot => snapshot.nodes.get(nodeKey));
if (!node || node.visibility === 'hidden') return null;
let content: ReactNode = null;
if (isNode(node, 'context')) content = <ContextInjectionRow {...node.data} t={t} />;
else if (isNode(node, 'system-prompt')) content = <details className={css.detail}><summary>系统提示词</summary><pre className={css.systemPrompt}>{node.data.text}</pre></details>;
else if (isNode(node, 'model-retry')) content = <JsonBlock label="模型重试记录" payload={node.data.attempts} truncatedLabel={truncatedJsonLabel} />;
else if (isNode(node, 'manual-compaction')) {
if (node.data.command.outcome?.kind === 'error') {
content = <div className={css.error} role="alert">
<svg className={css.errorIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<circle cx="8" cy="8" r="6.5" strokeWidth="1.2" />
<path d="M8 5v3.5M8 11.2h.01" strokeWidth="1.5" strokeLinecap="round" />
</svg>
<div className={css.errorCopy}>
<div className={css.errorTitle}><strong>上下文压缩未成功</strong></div>
<p className={css.errorMessage}>{node.data.command.outcome.text}</p>
</div>
</div>;
} else {
content = node.data.compaction ? <CompactionDivider data={node.data.compaction} /> : null;
}
}
else if (isNode(node, 'compaction')) content = <CompactionDivider data={node.data} />;
else if (isNode(node, 'command')) content = <JsonBlock label="命令记录" payload={node.data} truncatedLabel={truncatedJsonLabel} />;
return content && <ProcessFragment open={open} motion={motion} onRead={onRead} returnFocusTo={returnFocusTo} nodeKey={nodeKey} framed>{content}</ProcessFragment>;
});
const MainNode = memo(function MainNode({ useChat, nodeKey, boundary, pinned, processOpen: _processOpen = false, ...render }: SeatProps) {
const node = useChat(snapshot => snapshot.nodes.get(nodeKey));
const [disclosureReset] = useState(() => createSnapshotStore(0));
if (!node || node.visibility === 'hidden') return null;
if (isNode(node, 'user') || isNode(node, 'steering')) {
const blocks = contentBlocks(node.data.content);
const imageBlocks = blocks.filter(b => b.kind === 'image');
const otherBlocks = blocks.filter(b => b.kind !== 'image');
const text = otherBlocks.filter((block): block is Extract<typeof block, { kind: 'text' }> => block.kind === 'text').map(block => block.text).join('\n\n');
const time = node.data.time;
const fallback = <>
{node.kind === 'steering' && <p className={css.meta}>补充消息</p>}
{imageBlocks.length > 0 && <div className={css.userImages}>
<Blocks {...render} blocks={imageBlocks} source="user" />
</div>}
{otherBlocks.length > 0 && <div className={css.user}>
<Blocks {...render} blocks={otherBlocks} source="user" />
</div>}
<UserMessageActions text={text} time={time} />
</>;
const official = render.official;
let rendered: ReactNode = fallback;
if (official) {
const turn = node.location.kind === 'turn' || node.location.kind === 'step' ? node.location.turn : undefined;
const owner: ChatNodeOwnerProps & Pick<ReaderProps, 'sessionId'> = {
cwd: render.cwd,
openFile: render.openFile ?? (() => {}),
forkAt: render.forkAt ?? (() => {}),
inspectCall: callId => official.openView('trajectory', callId),
loadImage: official.officialImageLoader,
fileMentions: official.officialFileMentions,
sessionId: render.sessionId,
};
const options = { hookContext: { turnData: turn?.data, disclosureReset, useGroupAction: readerGroupAction }, fallback };
rendered = node.kind === 'user'
? official.renderSlot(OFFICIAL_SEATS.nodes, { ...owner, node }, { ...options, entryKey: 'user' })
: official.renderSlot(OFFICIAL_SEATS.nodes, { ...owner, node }, { ...options, entryKey: 'steering' });
}
return <div className={css.userCluster} data-reader-anchor data-reader-key={nodeKey} {...chatSeatProps(node.kind, nodeKey)}>{rendered}</div>;
}
if (isNode(node, 'assistant-step')) return null;
if (isNode(node, 'tool-call')) return <ToolMedia {...render} block={node.data.root} />;
if (isNode(node, 'turn-error')) return <div className={css.error} role="alert" data-reader-anchor>
<svg className={css.errorIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<circle cx="8" cy="8" r="6.5" strokeWidth="1.2" />
<path d="M8 5v3.5M8 11.2h.01" strokeWidth="1.5" strokeLinecap="round" />
</svg>
<div className={css.errorCopy}>
<div className={css.errorTitle}>
<strong>本轮运行失败</strong>
{node.data.code && <code className={css.errorCode}>{node.data.code}</code>}
</div>
<p className={css.errorMessage}>{cleanErrorMessage(node.data.message)}</p>
</div>
</div>;
if (isNode(node, 'turn-max-tokens')) return <div className={css.notice}>已到达输出长度限制,回答尚未完整。</div>;
if (isNode(node, 'model-retry')) return node.data.current.retryState === 'scheduled'
? <div className={css.notice} role="status">模型请求未成功,正在等待重试。详情保留在执行过程中。</div> : null;
if (isNode(node, 'command') && render.official) return <OfficialNode {...render} node={node} fallback={<JsonBlock label="命令记录" payload={node.data} truncatedLabel={truncatedJsonLabel} />} />;
if (isNode(node, 'command')) {
if (node.data.outcome?.kind === 'error') return <div className={css.error} role="alert">
<svg className={css.errorIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<circle cx="8" cy="8" r="6.5" strokeWidth="1.2" />
<path d="M8 5v3.5M8 11.2h.01" strokeWidth="1.5" strokeLinecap="round" />
</svg>
<div className={css.errorCopy}>
<div className={css.errorTitle}><strong>命令执行未成功</strong></div>
<p className={css.errorMessage}>{node.data.outcome.text ?? node.data.name ?? '查看原对话中的命令记录'}</p>
</div>
</div>;
return node.data.outcome?.text ? <MarkdownText text={node.data.outcome.text} labels={markdownLabels} /> : null;
}
if (isNode(node, 'manual-compaction') || isNode(node, 'compaction')) return null;
if (node.kind === 'context' || node.kind === 'turn-tail' || node.kind === 'system-prompt' || node.kind === 'turn-process') return null;
// No 'command-input' branch: that string is not a chat node kind in any released
// host (it appears nowhere in the installed packages), so a slash command arrives
// as 'command' above and is rendered there. Keeping the branch only made the file
// look like it handled a case that cannot occur.
return <OfficialNode {...render} node={node} fallback={<div className={css.unknown} data-reader-anchor>
<p>此记录类型暂未接入阅读页:{node.kind}</p>
{render.official && <button type="button" className={css.textButton} onClick={() => render.official!.openView('chat', node.key)}>在对话中查看</button>}
<JsonBlock label="查看原始记录" payload={node.data} truncatedLabel={truncatedJsonLabel} />
</div>} />;
});
/**
* Sub-agents this turn dispatched, read from the host's own Turn-process row.
*
* The host already derives this from the dispatch tree (`subagentCount` on
* `TurnProcessChatData`), so counting calls here would only risk disagreeing with
* it. The row is otherwise hidden by the reader, which is why this is the one place
* its counters are read.
*/
function subagentCount(snapshot: { nodes: { get(key: string): ChatConversationViewNode | undefined } }, keys: readonly string[]): number {
for (const key of keys) {
const node = snapshot.nodes.get(key);
if (!node || node.kind !== 'turn-process') continue;
const value = (node.data as { subagentCount?: unknown }).subagentCount;
if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value;
}
return 0;
}
function GroupStatus({ group, useChat, pending, motion }: Pick<ReaderProps, 'useChat'> & { group: ReaderGroup; motion: boolean; pending: { kind?: string } | undefined }) {
const text = useChat(snapshot => {
const turn = group.turn === null ? undefined : snapshot.timeline.turns.get(group.turn);
if (turn?.status === 'closed') {
if (turn.end?.data.reason.kind !== 'completed') return '执行过程';
const elapsed = turn.start && turn.end ? Math.max(0, Math.round((turn.end.time - turn.start.time) / 1000)) : null;
return elapsed === null ? '执行过程' : elapsed < 60 ? `用时 ${elapsed} 秒` : `用时 ${Math.floor(elapsed / 60)} 分 ${elapsed % 60} 秒`;
}
if (turn?.status !== 'open') return '执行过程';
if (pending !== undefined) return '等待你的操作';
const current = turn.steps.at(-1)?.data.get('assistant-step');
const last = current?.blocks.at(-1);
if (current?.status === 'running' && last?.kind === 'tool-call') {
const spawned = subagentCount(snapshot, group.keys);
return spawned ? `${preparingLabel(last.name)}·${spawned} 个子代理` : preparingLabel(last.name);
}
for (let index = group.keys.length - 1; index >= 0; index--) {
const node = snapshot.nodes.get(group.keys[index]);
if (!node) continue;
if (isNode(node, 'tool-call') && !('kind' in node.data.root)) return '正在使用工具';
if (isNode(node, 'assistant-step') && node.data.status === 'running') {
const last = node.data.blocks.at(-1);
return last?.kind === 'reasoning' ? '正在思考' : last?.kind === 'text' ? '正在输出' : '正在准备回复';
}
}
return '正在处理';
});
const busy = useChat(snapshot => group.turn !== null && snapshot.timeline.turns.get(group.turn)?.status === 'open' && pending === undefined);
return <StatusText text={text} motion={motion} shimmer={busy} />;
}
const DeliverableChip = memo(function DeliverableChip({ path, openFile, revealFile, openMode }: {
path: string;
openFile?: (path: string) => Promise<void> | void;
revealFile?: (path: string) => Promise<void> | void;
openMode: DeliverableOpenMode;
}) {
const [status, setStatus] = useState<'idle' | 'opened' | 'copied' | 'revealed'>('idle');
const timer = useRef<ReturnType<typeof setTimeout>>();
const flash = (next: 'opened' | 'copied' | 'revealed') => {
setStatus(next);
clearTimeout(timer.current);
timer.current = setTimeout(() => setStatus('idle'), 1600);
};
const onOpen = (event: React.MouseEvent) => {
event.stopPropagation();
try {
openFile?.(path);
flash('opened');
} catch {
// fallback
}
};
const onReveal = (event: React.MouseEvent) => {
event.stopPropagation();
try {
if (revealFile) {
revealFile(path);
} else {
openFile?.(dirname(path));
}
flash('revealed');
} catch {
// fallback
}
};
const onCopy = (event: React.MouseEvent) => {
event.stopPropagation();
try {
void navigator.clipboard?.writeText(path);
flash('copied');
} catch {
// fallback
}
};
const name = basename(path);
const folder = dirname(path);
return (
<div className={css.deliverableChip} data-status={status} title={path}>
<button
type="button"
className={css.chipMain}
onClick={onOpen}
onDoubleClick={onOpen}
aria-label={openMode === 'sidebar' ? `在内置面板中打开 ${path}` : `用系统应用打开 ${path}`}
>
{status === 'opened' ? (
<svg className={css.statusIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<path d="M3.5 8.5l3 3 6-7" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
</svg>
) : (
<svg className={css.deliverableIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<path d="M4 2.5h5l3 3V13.5H4V2.5z" strokeWidth="1.2" strokeLinejoin="round" />
<path d="M9 2.5v3h3" strokeWidth="1.2" strokeLinejoin="round" />
</svg>
)}
<span className={css.deliverableName}>
{status === 'opened' ? (openMode === 'sidebar' ? '已在面板打开' : '已在外部打开') : name}
</span>
</button>
<div className={css.chipActions} aria-label="文件操作">
<button
type="button"
className={css.chipActionBtn}
title={`在访达中定位所在目录 (${folder})`}
aria-label="在访达中显示所在目录"
onClick={onReveal}
>
{status === 'revealed' ? (
<svg className={css.actionIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<path d="M3.5 8.5l3 3 6-7" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
</svg>
) : (
<svg className={css.actionIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<path d="M2 4.5h4l1.5 2H14v6.5H2V4.5z" strokeWidth="1.2" strokeLinejoin="round" />
</svg>
)}
</button>
<button
type="button"
className={css.chipActionBtn}
title="复制相对路径"
aria-label="复制相对路径"
onClick={onCopy}
>
{status === 'copied' ? (
<svg className={css.actionIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<path d="M3.5 8.5l3 3 6-7" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
</svg>
) : (
<svg className={css.actionIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<rect x="5.5" y="5.5" width="8" height="8" rx="1.5" strokeWidth="1.2" />
<path d="M4 10.5H3a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v1" strokeWidth="1.2" strokeLinecap="round" />
</svg>
)}
</button>
</div>
</div>
);
});
function DeliverablesRow({ deliverables, openFile, revealFile, openMode }: {
deliverables: readonly string[];
openFile?: (path: string) => Promise<void> | void;
revealFile?: (path: string) => Promise<void> | void;
openMode: DeliverableOpenMode;
}) {
const [folderStatus, setFolderStatus] = useState<'idle' | 'opened'>('idle');
const onOpenWorkspace = () => {
try {
openFile?.('.');
setFolderStatus('opened');
setTimeout(() => setFolderStatus('idle'), 1600);
} catch {
// ignore
}
};
return (
<div className={css.deliverablesRoot} data-reader-deliverables>
<span className={css.deliverablesLabel}>产物</span>
<div className={css.deliverablesLane}>
<div className={css.deliverablesRow}>
{deliverables.slice(0, 8).map(path => (
<DeliverableChip key={path} path={path} openFile={openFile} revealFile={revealFile} openMode={openMode} />
))}
{deliverables.length > 8 && (
<span className={css.deliverablesMore}>
+ {deliverables.length - 8} 个文件
</span>
)}
{deliverables.length > 1 && (
<button
type="button"
className={css.deliverablesShowFolder}
data-status={folderStatus}
onClick={onOpenWorkspace}
title="在访达中打开整个工作区目录"
>
{folderStatus === 'opened' && (
<svg className={css.statusIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<path d="M3.5 8.5l3 3 6-7" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
</svg>
)}
<span>{folderStatus === 'opened' ? '已打开访达' : '在文件夹中显示'}</span>
</button>
)}
</div>
</div>
</div>
);
}
const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys, selectedProcessKeys, isAwaitingModel = false, ...props }: ReaderProps & { group: ReaderGroup; motion: boolean; autoFold: boolean; pinnedKeys: readonly string[]; selectedProcessKeys: readonly string[]; isAwaitingModel?: boolean }) {
const snapshot = props.useChat(snapshot => snapshot);
const nodes = snapshot.nodes;
const turn = group.turn === null ? undefined : snapshot.timeline.turns.get(group.turn);
const interaction = props.useSessionStatus(snapshot => snapshot.get(props.sessionId)?.pendingInteraction);
const sessionRunning = props.useSession(snapshot => snapshot.running);
const boundary = useMemo(() => boundaryOf(turn), [turn]);
const choiceKey = processChoiceKey(group.key, boundary);
const expansionChoice = props.useStore(state => state.expanded[choiceKey]);
const flowId = useId();
const processButton = useRef<HTMLButtonElement>(null);
const setExpanded = useCallback((value: boolean) => props.actions.setExpanded(choiceKey, value), [props.actions, choiceKey]);
const pinProcess = useCallback(() => setExpanded(true), [setExpanded]);
const firstKind = props.useChat(snapshot => snapshot.nodes.get(group.keys[0])?.kind);
const startsWithUser = firstKind === 'user';
const mainKeys = startsWithUser ? group.keys.slice(1) : group.keys;
const flow = useMemo(() => readerFlow({ ...group, keys: mainKeys }, turn, key => nodes.get(key), snapshot.order), [nodes, group, mainKeys, turn, snapshot.order]);
const steps = useMemo(() => segmentLiveTurn(flow, key => nodes.get(key)), [flow, nodes]);
const liveItems = useMemo(() => presentLiveTurn(steps, boundary, autoFold), [steps, boundary, autoFold]);
const openMode = deliverableOpenModeOf(useSyncExternalStore(
props.openPrefs?.subscribe ?? ((fn: () => void) => { void fn; return () => {}; }),
() => props.openPrefs?.getSnapshot()?.deliverableOpenMode,
() => 'external',
));
const hasProcess = flow.some(item => item.kind === 'tool' || hasProcessContent(nodes.get(item.nodeKey), boundary));
const showStatusLane = hasProcess && !isAwaitingModel;
const showClosedSummary = boundary.status === 'closed' && hasProcess && autoFold;
// Only a real, still-active text selection delays folding. Merely clicking,
// focusing or scrolling the live card does not create a permanent override.
const holdingSelection = selectedProcessKeys.some(key =>
flow.some(item => item.key === key)
|| liveItems.some(item => item.kind === 'fold'
? item.key === key || item.steps.some(step => step.key === key || ('nodeKey' in step && step.nodeKey === key))
: item.key === key || ('nodeKey' in item.step && item.step.nodeKey === key)));
const expanded = !autoFold || holdingSelection || processExpanded(expansionChoice, boundary);
// Seam between narration blocks. Skip a run a live-fold cell already
// covers, and do not drop the previous body's bottom spacing.
const seamPlan = useMemo(
() => planProcessSeams(steps, liveItems, expanded),
[steps, liveItems, expanded],
);
const [foldOpenByKey, setFoldOpenByKey] = useState<Record<string, boolean>>({});
useLayoutEffect(() => {
// Restoring automatic folding also releases live "prior steps" disclosures.
if (autoFold) setFoldOpenByKey(current => Object.keys(current).length ? {} : current);
}, [autoFold]);
const deliverables = useMemo(() => getTurnDeliverables(turn, flow), [turn, flow]);
const tailData = useMemo(() => {
for (const key of group.keys) {
const n = nodes.get(key);
if (n && isNode(n, 'turn-tail')) return n.data;
}
return undefined;
}, [group.keys, nodes]);
const tailOwner = useMemo(() => turn && tailData ? {
turn, seq: tailData.closing?.finalNode.seq ?? tailData.seq, openFile: props.openFile,
} : undefined, [turn, tailData, props.openFile]);
const fileMentions = useMemo(() => {
const official = tailOwner ? props.officialFileMentions(tailOwner) : undefined;
const reader = deliverables.length > 0 ? createProducedFileMentions(deliverables, props.openFile) : undefined;
return official || reader ? { resolve: (value: string) => official?.resolve(value) ?? reader?.resolve(value) } : undefined;
}, [tailOwner, props.officialFileMentions, deliverables, props.openFile]);
const official = useMemo(() => ({
renderSlot: props.renderSlot, renderSlotChain: props.renderSlotChain,
officialImageLoader: props.officialImageLoader, officialFileMentions: props.officialFileMentions,
officialPreviewFile: props.officialPreviewFile,
officialHost: props.officialHost, openView: props.openView,
}), [props.renderSlot, props.renderSlotChain, props.officialImageLoader, props.officialFileMentions, props.officialPreviewFile, props.officialHost, props.openView]);
const cwd = props.useSessions(state => state.byId[props.sessionId]?.cwd);
const runMs = turn?.start && turn?.end ? Math.max(0, turn.end.time - turn.start.time) : undefined;
const metrics = useMemo(() => ({
usage: tailData?.tokenUsage,
runMs,
tokensPerSecond: (tailData as { tokensPerSecond?: number } | undefined)?.tokensPerSecond,
ttftMs: (tailData as { ttftMs?: number } | undefined)?.ttftMs,
endedAt: tailData?.closing?.time ?? turn?.end?.time,
}), [tailData, runMs, turn?.end?.time]);
const forkSeq = forkAnchorSeq([tailData?.closing?.finalNode]);
const presentation = useMemo(() => {
// ChatNodeStore exposes live keyed readers. Materialize this turn instead of
// retaining a live get() function and mistakenly calling it a frozen frame.
const captured = new Map(group.keys.flatMap(key => {
const node = nodes.get(key); return node ? [[key, node] as const] : [];
}));
return { items: holdingSelection ? presentLiveTurn(steps, boundary, false) : liveItems,
snapshot: { ...snapshot, nodes: { ...nodes, get: (key: string) => captured.get(key), values: () => [...captured.values()] } } };
}, [snapshot, nodes, group, steps, boundary, liveItems, holdingSelection]);
const shared = {
useChat: useFlowChat,
renderSlotChain: props.renderSlotChain,
loadImage: props.loadImage,
fillComposer: props.fillComposer,
openFile: props.openFile,
revealFile: props.revealFile,
forkAt: props.forkAt,
forkSeq,
fileMentions,
metrics,
official,
sessionId: props.sessionId,
cwd,
};
const terminal = terminalLabel(boundary.reason);
const hasTurnError = flow.some(item => item.kind === 'node' && nodes.get(item.nodeKey)?.kind === 'turn-error');
// A stopped turn normally stays quiet, but a stopped turn that produced no
// prose at all reads as if its answer vanished into the process fold. Say so.
const hasAnswerProse = steps.some(step => step.kind === 'body'
&& step.blocks.some(block => block.kind === 'text' && block.text.trim() !== ''));
const stoppedWithoutAnswer = (boundary.reason === 'interrupted' || boundary.reason === 'aborted') && !hasAnswerProse;
const showTerminalNotice = terminal && !hasTurnError
&& (stoppedWithoutAnswer || (boundary.reason !== 'interrupted' && boundary.reason !== 'aborted'));
const renderStep = (step: LiveStep, folded: boolean) => {
const processOpen = folded || expanded;
if (step.kind === 'reasoning' || step.kind === 'body') return <BlockBoundary>
<AssistantNode {...shared} boundary={boundary} nodeKey={step.nodeKey} partStart={step.start} pinned={pinnedKeys.includes(step.nodeKey)} processOpen={processOpen} folded={folded} motion={motion} onRead={pinProcess} returnFocusTo={processButton}
seamSummary={step.kind === 'body' ? seamPlan.before.get(step.key) : undefined}
seamAfter={step.kind === 'body' && seamPlan.after.has(step.key)} />
</BlockBoundary>;
if (step.kind === 'tool') return <BlockBoundary><ProcessFragment open={processOpen} motion={motion} onRead={pinProcess} returnFocusTo={processButton} nodeKey={step.key} framed>
<ToolActivity {...shared} entry={step.entry} motion={motion} turnClosed={boundary.status === 'closed'} onRead={pinProcess} />
{step.entry.block && <ToolMedia {...shared} block={step.entry.block} />}
</ProcessFragment></BlockBoundary>;
if (step.kind === 'user') return <BlockBoundary><MainNode {...shared} boundary={boundary} nodeKey={step.nodeKey} /></BlockBoundary>;
return <Fragment>
<BlockBoundary><ProcessNode useChat={useFlowChat} t={props.t} nodeKey={step.nodeKey} open={processOpen} motion={motion} onRead={pinProcess} returnFocusTo={processButton} /></BlockBoundary>
<BlockBoundary><MainNode {...shared} boundary={boundary} nodeKey={step.nodeKey} pinned={pinnedKeys.includes(step.nodeKey)} processOpen={processOpen} /></BlockBoundary>
</Fragment>;
};
return <section className={css.turn} data-reader-turn={group.turn ?? 'unresolved'} data-reader-turn-state={boundary.status} data-reader-turn-result={boundary.reason ?? undefined}>
{startsWithUser && <BlockBoundary><MainNode {...shared} useChat={props.useChat} boundary={boundary} nodeKey={group.keys[0]} /></BlockBoundary>}
<div className={css.turnStickyRegion} data-reader-sticky-region>
{(showStatusLane || showClosedSummary) && <div className={css.turnStickyLanes}>
{showStatusLane && <StickyLane kind="status" className={css.turnProcessSticky}>
<Disclosure open={expanded} onChange={setExpanded} controls={flowId} buttonRef={processButton}
label={<GroupStatus group={group} useChat={props.useChat} pending={interaction} motion={motion} />} />
</StickyLane>}
{showClosedSummary && <ClosedProcessSummary open={expanded} onChange={setExpanded} controls={flowId}
steps={steps.filter(step => step.kind !== 'user' && step.kind !== 'body')} />}
</div>}
<ChoreographedFlow id={flowId} frame={presentation} motion={motion} enabled={autoFold && boundary.status === 'open' && !holdingSelection}
urgent={hasTurnError || interaction !== undefined || !sessionRunning} open={foldOpenByKey} processOpen={expanded}
onOpenChange={(key, value) => { pinProcess(); setFoldOpenByKey(current => ({ ...current, [key]: value })); }} renderStep={renderStep} />
</div>
{/* 状态指示永远排在流程之后:AI 的响应永远出现在最新消息(含补充消息)的下方 */}
{!hasProcess && boundary.status === 'open' && !isAwaitingModel && <div className={css.disclosure} data-reader-status-only>
<GroupStatus group={group} useChat={props.useChat} pending={interaction} motion={motion} />
</div>}
{showDeliverablesRow(boundary.status, deliverables) && <DeliverablesRow deliverables={deliverables} openFile={props.openFile} revealFile={props.revealFile} openMode={openMode} />}
{boundary.status === 'closed' && <BlockBoundary><OfficialTail official={official} owner={tailOwner} produced={deliverables} /></BlockBoundary>}
{showTerminalNotice && <div className={css.notice} data-reader-terminal>{terminal}</div>}
</section>;
});
export function Reader(props: ReaderProps) {
useInsertionEffect(() => { ensureStyles(); }, []);
const root = useRef<HTMLDivElement>(null);
const activatedAt = useRef(Date.now());
const order = props.useChat(snapshot => snapshot.order);
const nodes = props.useChat(snapshot => snapshot.nodes);
// A rewind upserts the command row in place, so order and nodes keep their identity.
const rewindSignature = props.useChat(snapshot => visibleChatSignature(snapshot));
const renderKeys = useMemo(() => visibleChatKeys({ order, nodes }), [order, nodes, rewindSignature]);
const timeline = props.useChat(snapshot => snapshot.timeline);
const running = props.useSession(snapshot => snapshot.running);
const pending = props.useSessionStatus(snapshot => snapshot.get(props.sessionId)?.pendingInteraction);
const openError = props.useSession(snapshot => snapshot.openError);
const loading = props.useSession(snapshot => snapshot.openState === 'loading');
const hasMore = props.useSession(snapshot => snapshot.hasMore);
const loadingOlder = props.useSession(snapshot => snapshot.loadingOlder);
const pendingSubmissions = props.useSession(snapshot => snapshot.pendingSubmissions);
const pendingList = asReadonlyArray<PendingSubmissionEcho>(pendingSubmissions);
const inbox = props.useProjection?.('inbox');
type PendingInboxItem = { source?: { kind?: string; rpcId?: unknown }; content?: readonly unknown[] };
const inboxSteering = asReadonlyArray<PendingInboxItem>(inbox?.['next-step']).filter(item => item.source?.kind === 'user');
const observed = useMemo(() => observedInputIds(order, key => nodes.get(key)), [order, nodes]);
const visibleSubmissions = useMemo(() => pendingList.filter(sub => sub.placement !== 'queued' && !observed.has(sub.requestId)), [pendingList, observed]);
const pendingInputs = useMemo(() => {
const local = new Map<string, PendingSubmissionEcho>(visibleSubmissions.map(sub => [sub.requestId, sub]));
const localIds = new Set(pendingList.filter(sub => sub.placement !== 'queued').map(sub => sub.requestId));
const rows: Array<PendingSubmissionEcho | (typeof inboxSteering)[number]> = [];
for (const item of inboxSteering) {
const rpcId = typeof item.source?.rpcId === 'string' ? item.source.rpcId : undefined;
if (!rpcId) { rows.push(item); continue; }
const submission = local.get(rpcId);
if (submission) { local.delete(rpcId); rows.push(submission); }
else if (!localIds.has(rpcId)) rows.push(item);
}
rows.push(...local.values());
return rows;
}, [inboxSteering, pendingList, visibleSubmissions]);
const waitAnchor = waitingAnchor(renderKeys, key => nodes.get(key), pendingList);
const motionPreference = props.useStore(state => state.motion);
const motion = useMotionAllowed(motionPreference);
const prefsSnap = useSyncExternalStore(
props.openPrefs?.subscribe ?? ((fn: () => void) => { void fn; return () => {}; }),
() => props.openPrefs?.getSnapshot?.(),
() => undefined,
);
const storeAutoFold = props.useStore(state => state.autoFold);
const autoFold = prefsSnap?.autoFold ?? (prefsSnap?.foldIntensity !== undefined ? prefsSnap.foldIntensity !== 0 : undefined) ?? storeAutoFold ?? true;
const previousAutoFold = useRef(autoFold);
useLayoutEffect(() => {
const restored = autoFold && !previousAutoFold.current;
previousAutoFold.current = autoFold;
// Watch the effective preference so toolbar and Settings changes behave alike.
// Reading while folding is off must not pin completed process content forever.
if (restored) props.actions.resetExpanded();
}, [autoFold, props.actions]);
const frostedGlass = frostedGlassOf(prefsSnap);
const streamMotion = useMemo(() => ({ enabled: motion, activatedAt: activatedAt.current }), [motion]);
const groups = useMemo(() => groupNodes(renderKeys, key => nodes.get(key)), [renderKeys, nodes, timeline]);
const isAwaitingModel = useMemo(() => {
// 状态机铁律:「深度求索中」与「正在处理/思考」永远互斥。
// 1. 仅空闲发送(!running)的本地回显窗口:用户按下回车第 0 毫秒立即反馈。
// 忙碌时的 queued/steering 回显不算等待——模型本来就在工作。
if (!running && pendingList.length > 0) return true;
const lastKey = renderKeys.at(-1);
const lastNode = lastKey ? nodes.get(lastKey) : undefined;
if (!lastKey || !lastNode) return false;
// 2. 模型已经产出内容:等待结束,计时器必须立刻消失。
// 「产出」= assistant-step 已带 block(正文/思维链/工具调用都算)。
if (lastNode.kind === 'assistant-step') {
const data = lastNode.data as { status?: string; blocks?: unknown[] };
const blocks = data.blocks ?? [];
// 空 block 且仍在跑 = 请求已发出、模型还没吐字,正是要计时的那一刻。
return blocks.length === 0 && data.status === 'running';
}
// 3. 球在模型脚下:用户刚发言,或工具已返回、上下文已注入、命令已执行。
// 这些时刻模型随时可能卡住,正是要计时的地方;工具执行期间不计时,
// 因为那时忙的是工具而不是模型。
// handsBackToModel 内部按 chat 层 kind 判定,并区分「工具已返回」与
// 「工具仍在跑」——后者不算等待。
const modelOwesResponse = handsBackToModel(lastNode);
if (!modelOwesResponse) return false;
// 轮次已结束就没什么可等的。
const lastGroup = groups.at(-1);
const turn = lastGroup?.turn === null || lastGroup?.turn === undefined ? undefined : timeline.turns.get(lastGroup.turn);
return turn?.status !== 'closed';
}, [running, pendingList, renderKeys, nodes, groups, timeline]);
const scroll = useReadingScroll(root, motion);
const pinnedKeys = usePinnedSelection(root);
const selectedProcessKeys = usePinnedSelection(root, '[data-reader-process]');
const [historyError, setHistoryError] = useState(false);
// 1. Navigation items from Chat snapshot
const turnNavigationItems = props.useChat(snapshot => snapshot.navigation?.items ? snapshot.navigation.items() : undefined);
// 2. Whole-log turn outline projection
const turnOutline = props.useProjection?.('turnOutline');
// 3. Track turns with deliverables
const turnsWithDeliverables = useMemo(() => {
const set = new Set<number>();
for (const [turnNum, loc] of timeline.turns) {
const deliv = (loc.data as { get(key: string): unknown } | undefined)?.get('deliverables') as { produced?: unknown[] } | undefined;
if (Array.isArray(deliv?.produced) && deliv.produced.length > 0) {
set.add(turnNum);
}
}
return set;
}, [timeline]);
// 4. Merged timeline items for the rail
const timelineItems = useMemo(
() => mergeTimelineItems(turnNavigationItems, turnOutline, turnsWithDeliverables),
[turnNavigationItems, turnOutline, turnsWithDeliverables],
);
// 5. Active & busy turn tracking
const [activeTurn, setActiveTurn] = useState<number | null>(null);
const [busyTurn, setBusyTurn] = useState<number | null>(null);
// Scroll spy to update activeTurn
useEffect(() => {
const el = root.current;
if (!el) return;
const scroller = el.closest('[data-conversation-scroll]') ?? el;
let ticking = false;
const updateActive = () => {
if (ticking) return;
ticking = true;
requestAnimationFrame(() => {
ticking = false;
const line = (scroller instanceof HTMLElement ? scroller.clientHeight : window.innerHeight) * 0.35;
const turnRows = el.querySelectorAll<HTMLElement>('[data-reader-turn]:not([data-reader-turn="unresolved"])');
let current: number | null = null;
for (const row of turnRows) {
const rect = row.getBoundingClientRect();
if (rect.top <= line) {
const num = Number(row.dataset.readerTurn);
if (Number.isSafeInteger(num)) current = num;
} else {
break;
}
}
if (current !== null) {
setActiveTurn(current);
} else if (turnRows.length > 0) {
const first = Number(turnRows[0].dataset.readerTurn);
if (Number.isSafeInteger(first)) setActiveTurn(first);
}
});
};
scroller.addEventListener('scroll', updateActive, { passive: true });
updateActive();
return () => scroller.removeEventListener('scroll', updateActive);
}, [groups]);
// Navigation handler (supports loaded jump & unloaded loadThrough).
// Land on the conversation scroller only — scrollIntoView also moves
// ancestor boxes and can lift the sticky composer after a top→bottom jump.
const onNavigateTurn = useCallback(async (item: TimelineItem) => {
const el = root.current;
if (!el) return;
const port = scrollerOf(el);
const reveal = (turn: number) => {
const targetRow = el.querySelector<HTMLElement>(`[data-reader-turn="${turn}"]`);
if (!targetRow) return;
const last = timelineItems.at(-1);
if (last !== undefined && last.turn === turn) {
scroll.jump();
} else {
scroll.release();
landTurn(targetRow, port);
}
setActiveTurn(turn);
};
if (item.anchor.kind === 'loaded') {
reveal(item.turn);
return;
}
setBusyTurn(item.turn);
try {
if (props.loadThrough) {
await props.loadThrough(item.anchor.seq);
} else {
await props.loadOlder();
}
setTimeout(() => { reveal(item.turn); }, 50);
} finally {
setBusyTurn(null);
}
}, [props.loadThrough, props.loadOlder, scroll.jump, scroll.release, timelineItems]);
const lastKey = renderKeys.at(-1);
const lastNode = lastKey ? nodes.get(lastKey) : undefined;
const lastSubmissionId = pendingList.length ? pendingList[pendingList.length - 1].requestId : null;
const lastOrderKeyRef = useRef<string | undefined>(lastKey);
const lastSubmissionRef = useRef<string | null>(lastSubmissionId);
useLayoutEffect(() => {
const appendedUser = lastKey !== lastOrderKeyRef.current && (lastNode?.kind === 'user' || lastNode?.kind === 'steering');
const appendedSubmission = lastSubmissionId !== null && lastSubmissionId !== lastSubmissionRef.current;
lastOrderKeyRef.current = lastKey;
lastSubmissionRef.current = lastSubmissionId;
if (appendedUser || appendedSubmission) {
scroll.jump();
}
}, [lastKey, lastNode?.kind, lastSubmissionId, scroll]);
// ChatView publishes data-chat-flow="" on its column. Skins treat a
// scrollport without that hook as inspect-only and hide [data-composer-seat].
// dsh-claude-style 0.19.x also hides the host seat whenever the first tab
// is not 对话. Reader.module.css restores that seat only while this root
// (data-dsh-better-display) is mounted.
return <StreamMotionContext.Provider value={streamMotion}><ReaderLaneScope><div ref={root} className={css.root} data-reader-build="0.3.4" data-dsh-better-display="0.3.4" data-reader-wait-clock-version="input-v1" data-reader-wait-start={waitAnchor.time ?? undefined} data-motion={motion ? 'on' : 'off'} data-reader-glass={frostedGlass || undefined} data-reader-auto-fold={autoFold ? 'on' : 'off'}>
<TimelineRail items={timelineItems} activeTurn={activeTurn} busyTurn={busyTurn} onNavigate={onNavigateTurn} />
<div className={css.column} data-chat-flow="" tabIndex={-1}>
<StickyLane kind="toolbar" className={css.toolbar}>
<button
type="button"
className={css.textButton}
aria-pressed={autoFold}
onClick={() => {
props.actions.setAutoFold(!autoFold);
props.openPrefs?.actions?.setAutoFold?.(!autoFold);
}}
title="新思考产生时,是否自动将此前步骤收拢为一行汇总。关闭后完整保留原始过程与流式输出。"
>
{`自动折叠${autoFold ? '开' : '关'}`}
</button>
</StickyLane>
{hasMore && <button type="button" className={css.historyButton} disabled={loadingOlder} onClick={async () => {
setHistoryError(false);
try { await props.loadOlder(); } catch { setHistoryError(true); }
}}>{loadingOlder ? '正在加载更早记录' : '加载更早记录'}</button>}
{historyError && <div className={css.notice}>历史记录加载失败,可再次尝试;现有内容未改变。</div>}
{openError && <div className={css.error} role="alert">会话暂时无法读取:{openError.message}</div>}
{loading && groups.length === 0 && <p className={css.empty} role="status">正在读取会话…</p>}
<RetiringTurns groups={groups} render={group => <TurnGroup {...props} group={group} motion={motion} autoFold={autoFold} pinnedKeys={pinnedKeys} selectedProcessKeys={selectedProcessKeys} isAwaitingModel={isAwaitingModel && group.key === groups.at(-1)?.key} />} />
{pendingInputs.map((item, index) => {
const submission = 'requestId' in item ? item : undefined;
const text = submission?.text ?? inboxText(item as PendingInboxItem);
const images = submission ? pendingSubmissionImages(submission) : [];
const attachmentCount = submission ? images.length : inboxAttachmentCount(item as PendingInboxItem);
const requestId = submission?.requestId ?? `inbox-${index}`;
return (
<div key={requestId} className={css.userCluster} data-reader-pending-submission data-pending-steering={submission ? undefined : ''} data-pending-attachment-count={attachmentCount}>
{images.length > 0 && (
<div className={css.userImages}>
{images.map((item, idx) => (
<figure key={idx} className={css.imageFigure}>
<div className={css.imageFrame} style={{ aspectRatio: `${item.width || 4} / ${item.height || 3}` }}>
<img src={item.previewUrl} alt={item.name ?? '发送的图片'} className={css.pendingImage} />
</div>
</figure>
))}
</div>
)}
{text ? (
<div className={css.user}>
<div className={css.blocks}>{text}</div>
</div>
) : null}
<UserMessageActions text={text} time={submission?.time} />
</div>
);
})}
{isAwaitingModel && <WaitingStatus anchor={waitAnchor} label={props.t ? props.t('chat.deepDiving') : '深度求索中...'} />}
{pending !== undefined && <div className={css.attention} role="alert" data-reader-attention>
<strong>{pending.kind === 'question' ? '需要你回答一个问题' : '需要你的确认'}</strong>
<span>请在下方原生操作区处理。此提示不会收进执行过程。</span>
</div>}
{scroll.detached && <div className={css.jumpDock}><button type="button" className={css.jump} aria-label="回到底部" title="回到底部" onClick={scroll.jump}>
<svg viewBox="0 0 14 14" width="14" height="14" aria-hidden="true"><path d="M3 5.5 7 9.5 11 5.5" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg>
</button></div>}
</div>
</div></ReaderLaneScope></StreamMotionContext.Provider>;
}

View File

@ -0,0 +1,306 @@
import { useCallback, useContext, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
import { StreamMotionContext } from './streaming.js';
import type { ReactNode } from 'react';
import { REASON_CHASE_HOLD, REASON_HOLD, REASON_LINES, REASON_STEP, reasoningTarget } from './reasoning-follow.js';
import css from './Reader.module.css';
const EASING = 'cubic-bezier(.22,1,.36,1)';
/** One real transcript: reference transform while following, native scroll while reading. */
export function ReasoningCard({ children, step, active, motion, selected, onRead }: {
children: ReactNode; step: number; active: boolean; motion: boolean; selected: boolean; onRead: () => void;
}) {
const viewport = useRef<HTMLDivElement>(null);
const track = useRef<HTMLDivElement>(null);
const content = useRef<HTMLDivElement>(null);
const controls = useId();
const [expanded, setExpanded] = useState(false);
const [following, setFollowing] = useState(true);
const [overflow, setOverflow] = useState(false);
const [edges, setEdges] = useState('none');
const lastHeight = useRef(0);
const resize = useRef<Animation | null>(null);
const previousExpanded = useRef(expanded);
const stopFollow = useRef<() => void>(() => {});
const { paused = false } = useContext(StreamMotionContext);
const allowed = following && active && motion && !selected && !paused;
const pause = useCallback(() => {
stopFollow.current();
setFollowing(false);
onRead();
}, [onRead]);
useLayoutEffect(() => {
// The parent's selection observer can suspend this card before its own
// listener runs. Clearing a selection must not silently resume following.
if (!selected) return;
stopFollow.current();
setFollowing(false);
}, [selected]);
useLayoutEffect(() => {
if (!expanded) return;
const port = viewport.current;
const host = port?.closest<HTMLElement>('[data-conversation-scroll]');
if (!port || !host) return;
const fit = () => {
// Public DSH layout variable, updated by the native composer's observer.
// Leave room for the permanent identity, footer and reading margin.
const composer = parseFloat(getComputedStyle(host).getPropertyValue('--dsh-composer-height')) || 152;
const heading = port.parentElement?.querySelector<HTMLElement>('[data-reader-reasoning-heading]')?.offsetHeight || 30;
const footer = port.parentElement?.querySelector<HTMLElement>('[data-ud-check=reasoning-controls]')?.offsetHeight || 38;
const available = Math.max(120, host.clientHeight - composer - heading - footer - 32);
port.style.setProperty('--reason-reading-height', `${available}px`);
};
fit();
const observer = new ResizeObserver(fit); observer.observe(host);
return () => { observer.disconnect(); };
}, [expanded]);
useLayoutEffect(() => {
const port = viewport.current;
const text = content.current;
const scrollTrack = track.current;
if (!port || !text || !scrollTrack) return;
let frame = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
let nextAt = performance.now() + REASON_HOLD;
let alive = true;
let automatic = false;
let lastPainted = port.scrollTop;
let targetOffset = lastPainted;
const tail = () => Math.max(0, text.offsetHeight - port.clientHeight);
const clamp = (value: number) => Math.max(0, Math.min(tail(), value));
const paintedOffset = () => {
if (!automatic) return port.scrollTop;
const transform = getComputedStyle(scrollTrack).transform;
// Reduced-motion CSS may win before React receives the media change.
// Retain the last painted position rather than snapping back to the top.
return clamp(transform === 'none' ? lastPainted : port.scrollTop - new DOMMatrixReadOnly(transform).m42);
};
const hasSelection = () => {
const selection = document.getSelection();
return !!selection && !selection.isCollapsed && !!selection.anchorNode && text.contains(selection.anchorNode);
};
const cancel = () => {
cancelAnimationFrame(frame); frame = 0;
clearTimeout(timer); timer = undefined;
delete port.dataset.reasoningMoving;
};
const manual = () => {
if (!automatic) return;
const top = paintedOffset();
automatic = false;
scrollTrack.style.transition = 'none';
scrollTrack.style.transform = 'none';
// Set both in the same layout effect/event, before a frame can paint.
// The first wheel gesture must already have a native scrollable viewport.
port.style.overflow = 'auto';
port.scrollTop = top;
lastPainted = port.scrollTop;
port.dataset.reasoningMode = 'manual';
};
const follow = () => {
if (automatic) return;
targetOffset = lastPainted = clamp(port.scrollTop);
scrollTrack.style.transition = 'none';
scrollTrack.style.transform = `translateY(-${lastPainted}px)`;
port.scrollTop = 0;
port.style.overflow = 'hidden';
automatic = true;
port.dataset.reasoningMode = 'transform';
};
const measure = (recordHeight = true) => {
const previewHeight = parseFloat(getComputedStyle(port).getPropertyValue('--reason-preview-height'));
setOverflow(text.offsetHeight > previewHeight + 1);
lastPainted = paintedOffset();
const top = lastPainted > 1;
const bottom = tail() - lastPainted > 1;
const next = top ? bottom ? 'both' : 'top' : bottom ? 'bottom' : 'none';
setEdges(value => value === next ? value : next);
if (recordHeight && !resize.current) lastHeight.current = port.clientHeight;
};
stopFollow.current = () => { cancel(); manual(); measure(false); };
const canFollow = () => allowed && alive && !document.hidden && !hasSelection();
const schedule = () => {
if (!canFollow() || frame || timer !== undefined) return;
follow();
if (tail() - paintedOffset() < 1) return;
timer = setTimeout(start, Math.max(0, nextAt - performance.now()));
};
const start = () => {
timer = undefined;
if (!canFollow()) return;
const from = paintedOffset();
const lineHeight = parseFloat(getComputedStyle(text).lineHeight) || 24;
// How much unpainted text is waiting. A fast model pushes this far past the
// reference step, and chasing it is what keeps the scroll continuous.
const backlogLines = Math.max(0, (tail() - from) / lineHeight);
const target = reasoningTarget(from, text.offsetHeight, port.clientHeight, lineHeight, backlogLines);
if (target - from < 1) return;
const began = performance.now();
// Still behind after this step: take the next one almost immediately instead
// of holding the reading beat, so motion tracks the text rather than stalling.
nextAt = began + (backlogLines > REASON_LINES ? REASON_CHASE_HOLD : REASON_HOLD);
targetOffset = target;
// The supplied recipe: commit the start pose, then transition the track.
// No per-frame scrollTop writes and no catch-up across unread lines.
scrollTrack.style.transition = 'none';
scrollTrack.style.transform = `translateY(-${from}px)`;
void scrollTrack.offsetHeight;
scrollTrack.style.transition = 'transform var(--reason-step) var(--reason-ease)';
scrollTrack.style.transform = `translateY(-${target}px)`;
port.dataset.reasoningMoving = 'true';
port.dataset.reasoningFrom = String(from);
port.dataset.reasoningTarget = String(target);
port.dataset.reasoningBegan = String(began);
const tick = (now: number) => {
frame = 0;
if (!canFollow()) { cancel(); manual(); return; }
// Observe the browser's actual CSS interpolation for masks and handoff.
measure();
if (now - began < REASON_STEP || Math.abs(lastPainted - target) > .05) frame = requestAnimationFrame(tick);
else { delete port.dataset.reasoningMoving; schedule(); }
};
frame = requestAnimationFrame(tick);
};
const onScroll = () => {
measure();
// Focus/keyboard-induced native scroll wins even while the track moves.
if (automatic && port.scrollTop > 1) pause();
};
const onWheel = (event: WheelEvent) => {
if (!event.deltaY) return;
// The compositor picks a wheel scroller before handlers run. A clipped
// transform viewport would otherwise lose this first gesture or scroll
// the conversation. Consume only this handoff; later wheels stay native.
const handoff = automatic && event.cancelable;
if (handoff) event.preventDefault();
const unit = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? parseFloat(getComputedStyle(text).lineHeight) || 24
: event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? port.clientHeight : 1;
pause();
if (handoff) { port.scrollTop = clamp(port.scrollTop + event.deltaY * unit); measure(); }
};
const onSelection = () => { if (hasSelection()) pause(); };
const onVisibility = () => {
cancel(); manual();
nextAt = performance.now() + REASON_HOLD;
if (!document.hidden) schedule();
};
const observer = new ResizeObserver(() => {
if (automatic && targetOffset > tail() + 1) {
cancel(); manual();
nextAt = performance.now() + REASON_HOLD;
}
measure(); schedule();
});
observer.observe(text); observer.observe(port);
port.addEventListener('scroll', onScroll, { passive: true });
port.addEventListener('wheel', onWheel, { passive: false });
document.addEventListener('selectionchange', onSelection);
document.addEventListener('visibilitychange', onVisibility);
// Keep the previous layout height until the resize effect can sample it.
measure(false); schedule();
return () => {
alive = false; cancel(); manual(); observer.disconnect();
port.removeEventListener('scroll', onScroll); port.removeEventListener('wheel', onWheel);
document.removeEventListener('selectionchange', onSelection);
document.removeEventListener('visibilitychange', onVisibility);
stopFollow.current = () => {};
};
}, [allowed, pause]);
useLayoutEffect(() => {
const port = viewport.current;
if (!port) return;
const changed = expanded !== previousExpanded.current;
previousExpanded.current = expanded;
const from = resize.current ? port.clientHeight : lastHeight.current;
resize.current?.cancel(); resize.current = null;
port.style.maxHeight = ''; port.style.height = '';
const target = port.clientHeight;
// Explicit reading adjusts only the conversation, never the outer app.
// The card is also a reader anchor so resizing cannot pin a later answer
// in place at the expense of this card's visible heading.
if (changed && !selected) {
const card = port.parentElement;
const host = port.closest<HTMLElement>('[data-conversation-scroll]');
if (card && host) {
const composer = parseFloat(getComputedStyle(host).getPropertyValue('--dsh-composer-height')) || 152;
const region = host.getBoundingClientRect();
const box = card.getBoundingClientRect();
const top = region.top + 16;
const bottom = region.bottom - composer - 16;
const delta = box.top < top ? box.top - top : box.bottom > bottom ? Math.min(box.bottom - bottom, box.top - top) : 0;
if (Math.abs(delta) > 1) host.scrollTo({ top: Math.max(0, host.scrollTop + delta), behavior: motion ? 'smooth' : 'instant' });
}
}
if (!changed || !motion || from < 1 || Math.abs(target - from) < 1) {
lastHeight.current = target;
return;
}
// max-height otherwise clamps the very first collapse frame to the new cap.
port.style.maxHeight = 'none';
const animation = port.animate([{ height: `${from}px` }, { height: `${target}px` }], { duration: 300, easing: EASING, fill: 'both' });
resize.current = animation;
const restore = () => {
// `max-height` was cleared so the first frame could exceed the old cap; it has
// to come back even if the animation never reports finishing, or the card keeps
// the inline styles the animation was driving.
port.style.maxHeight = ''; port.style.height = '';
lastHeight.current = port.clientHeight;
};
let settled = false;
const settle = () => {
if (settled) return;
settled = true;
if (resize.current === animation) resize.current = null;
animation.cancel();
restore();
};
animation.onfinish = settle;
// `fill: 'both'` holds whichever keyframe the animation stopped on, so a run that
// never finishes — cancelled by a re-run, unmounted, or skipped by the compositor —
// would leave the card at the previous height with its inline styles still
// overridden. Restore on a deadline too.
const deadline = window.setTimeout(settle, 300 + 240);
return () => { window.clearTimeout(deadline); };
}, [expanded, motion, selected]);
useEffect(() => () => resize.current?.cancel(), []);
const toggleReading = () => {
// Resize the same transcript without changing follow intent or position.
// Wheel, selection and viewport focus still explicitly pause following.
onRead();
setExpanded(value => !value);
};
return <div className={css.reasonCard} data-reader-reasoning-card data-reader-anchor data-expanded={expanded} data-following={allowed} data-overflow={overflow} data-ud-motion="reader-reasoning-size">
<div className={css.reasonHeading} data-reader-reasoning-heading data-ud-check="reasoning-identity">
<span className={css.reasonLabel} data-reader-reasoning-label>思考</span>
<span>步骤 {step}</span>
</div>
<div ref={viewport} id={controls} className={css.reasonViewport} data-reader-reasoning-scroll data-edges={edges}
data-ud-motion="reader-reasoning-scroll" role="region" aria-label={`步骤 ${step} 的思考${overflow ? ',可滚动阅读' : ''}`}
tabIndex={overflow ? 0 : undefined} onPointerDown={pause} onFocus={pause}>
<div ref={track} className={css.reasonTrack} data-reader-reasoning-track>
<div ref={content} className={css.reasonText} data-reader-reasoning-text>{children}</div>
</div>
</div>
{(overflow || expanded) && <div className={css.reasonFooter} data-ud-check="reasoning-controls">
{active && motion ? <button type="button" className={css.reasonAction} disabled={selected} aria-controls={controls}
aria-label={following ? '暂停自动跟随思考' : '继续跟随最新思考'}
title={selected ? '取消文字选择后可继续跟随' : undefined}
onClick={() => { if (following) pause(); else { onRead(); setFollowing(true); } }}>
<svg width="12" height="12" viewBox="0 0 16 16" aria-hidden="true">{following ? <path d="M5.5 4v8m5-8v8" /> : <path d="M8 3v10m-4-4 4 4 4-4" />}</svg>
{following ? '暂停跟随' : '跟随最新'}
</button> : <span className={css.reasonCaption}>{expanded ? '手动阅读' : '可滚动阅读'}</span>}
<button type="button" className={css.reasonAction} aria-expanded={expanded} aria-controls={controls}
aria-label={expanded ? '收起完整思考' : '展开阅读完整思考'} onClick={toggleReading}>
{expanded ? '收起' : '展开阅读'}
<svg width="12" height="12" viewBox="0 0 16 16" aria-hidden="true">{expanded ? <path d="m4 10 4-4 4 4" /> : <path d="m4 6 4 4 4-4" />}</svg>
</button>
</div>}
</div>;
}

View File

@ -0,0 +1,184 @@
.section {
display: flex;
flex-direction: column;
gap: 28px;
width: 100%;
max-width: 720px;
}
.row {
display: flex;
align-items: center;
gap: 8px;
padding: 16px 0;
border-bottom: 0.5px solid var(--dsw-alias-border-l2);
}
.rowText {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 4px;
padding-right: 24px;
}
.title {
font-size: 14px;
font-weight: 400;
line-height: 22px;
color: var(--dsw-alias-label-primary);
}
.desc {
font-size: 12px;
font-weight: 400;
line-height: 18px;
color: var(--dsw-alias-label-tertiary);
}
.switch {
flex: none;
width: 40px;
height: 24px;
padding: 0;
border: none;
border-radius: 12px;
background: var(--dsw-alias-bg-module-platform);
position: relative;
cursor: pointer;
}
.switch::after {
content: '';
position: absolute;
top: 3px;
left: 3px;
width: 18px;
height: 18px;
border-radius: 50%;
background: var(--dsw-alias-label-primary);
transition: transform 160ms ease;
}
.switch[data-on]::after {
transform: translateX(16px);
}
.switch[data-on] {
background: var(--dsw-alias-state-business-primary);
}
.block {
display: flex;
flex-direction: column;
gap: 10px;
}
.status {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 13px;
line-height: 20px;
color: var(--dsw-alias-label-secondary);
}
.badge {
display: inline-flex;
align-items: center;
height: 22px;
padding: 0 8px;
border-radius: 11px;
background: var(--dsw-alias-bg-module-platform);
color: var(--dsw-alias-label-secondary);
font-size: 12px;
}
.badge[data-ok] {
background: rgba(16, 185, 129, 0.14);
color: #059669;
}
.pre {
margin: 0;
padding: 10px 12px;
border-radius: 8px;
background: var(--dsw-alias-bg-module-platform);
color: var(--dsw-alias-label-secondary);
font-size: 12px;
line-height: 18px;
overflow-wrap: anywhere;
white-space: pre-wrap;
}
.roots {
margin: 0;
padding-left: 18px;
color: var(--dsw-alias-label-tertiary);
font-size: 12px;
line-height: 18px;
}
.actions {
display: flex;
gap: 8px;
}
.button {
height: 32px;
padding: 0 12px;
border: 0.5px solid var(--dsw-alias-border-l2);
border-radius: 8px;
background: var(--dsw-alias-bg-module-platform);
color: var(--dsw-alias-label-primary);
font: inherit;
font-size: 13px;
cursor: pointer;
}
.button:hover {
background: var(--dsw-alias-interactive-bg-hover);
}
.button:disabled {
opacity: 0.6;
cursor: default;
}
.segment {
display: flex;
width: 100%;
margin-top: 8px;
padding: 2px;
border-radius: 10px;
background: var(--dsw-alias-bg-module-platform);
gap: 2px;
}
.segmentStop {
flex: 1 1 0;
min-width: 0;
height: 32px;
padding: 0 8px;
border: 0;
border-radius: 8px;
background: transparent;
color: var(--dsw-alias-label-secondary);
font: inherit;
font-size: 12px;
line-height: 18px;
cursor: pointer;
}
.segmentStop[data-on] {
background: var(--dsw-alias-bg-base);
color: var(--dsw-alias-label-primary);
box-shadow: 0 0 0 0.5px var(--dsw-alias-border-l2);
}
.slider {
width: 100%;
margin: 10px 0 0;
accent-color: var(--dsw-alias-state-business-primary);
}

View File

@ -0,0 +1,169 @@
import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';
import { frostedGlassOf, type FoldIntensity } from './fold-intensity.js';
import { deliverableOpenModeOf, type DeliverableOpenMode } from './open-file.js';
import { settingsCopyFor, type SettingsCopy, type SettingsCopyKey } from './settings-copy.js';
import { CONVENTIONAL_SKILL_ROOTS, detectGenerativeMcpappsSkill, shortestInstallCommand, type SkillStatusProbe, type SkillStatusSnapshot } from './skill-status.js';
import css from './SettingsSection.module.css';
export interface ReaderPrefsSnapshot {
deliverableOpenMode?: DeliverableOpenMode;
frostedGlass?: boolean;
foldIntensity?: FoldIntensity;
autoFold?: boolean;
processOnly?: boolean;
}
export interface OpenPrefs {
getSnapshot: () => ReaderPrefsSnapshot;
subscribe: (fn: () => void) => () => void;
actions: {
setDeliverableOpenMode: (value: DeliverableOpenMode) => void;
setFrostedGlass: (value: boolean) => void;
setFoldIntensity?: (value: FoldIntensity) => void;
setAutoFold?: (value: boolean) => void;
};
}
export interface BetterDisplaySettingsInjected {
prefs: OpenPrefs;
copy?: SettingsCopy;
languageTag?: string;
checkSkill: SkillStatusProbe;
}
type SettingsProps = BetterDisplaySettingsInjected & {
/** Official settings.section owner share; unused here. */
close?: () => void;
t?: (key: SettingsCopyKey) => string;
};
function text(props: SettingsProps, copy: SettingsCopy, key: keyof SettingsCopy): string {
if (typeof props.t === 'function') {
try {
const value = props.t(key);
if (typeof value === 'string' && value.length > 0 && value !== key) return value;
} catch {
// Fall through to the bundled dictionaries.
}
}
return copy[key];
}
export function SettingsSection(props: SettingsProps) {
const copy = props.copy ?? settingsCopyFor(props.languageTag);
const snap = useSyncExternalStore(
props.prefs.subscribe,
() => props.prefs.getSnapshot() ?? ({} as ReaderPrefsSnapshot),
() => ({} as ReaderPrefsSnapshot),
);
const mode = deliverableOpenModeOf(snap.deliverableOpenMode);
const glass = frostedGlassOf(snap);
const autoFold = snap.autoFold !== false && snap.foldIntensity !== 0;
const setMode = (value: DeliverableOpenMode) => {
props.prefs.actions.setDeliverableOpenMode(value);
};
const on = mode === 'sidebar';
const [skill, setSkill] = useState<SkillStatusSnapshot | undefined>();
const [checking, setChecking] = useState(false);
const recheck = useCallback(async () => {
setChecking(true);
try {
setSkill(await detectGenerativeMcpappsSkill(props.checkSkill));
} catch {
setSkill({
name: 'generative-mcpapps',
installed: false,
via: null,
roots: [],
hostReached: false,
});
} finally {
setChecking(false);
}
}, [props.checkSkill]);
useEffect(() => { void recheck(); }, [recheck]);
return (
<div className={css.section} data-better-display-settings>
<div className={css.row}>
<div className={css.rowText}>
<div className={css.title}>{text(props, copy, 'openTitle')}</div>
<div className={css.desc}>{text(props, copy, 'openDescription')}</div>
</div>
<button
type="button"
role="switch"
aria-checked={on}
className={css.switch}
data-on={on || undefined}
data-better-display-open-mode={mode}
onClick={() => { setMode(on ? 'external' : 'sidebar'); }}
/>
</div>
<div className={css.row}>
<div className={css.rowText}>
<div className={css.title}>{text(props, copy, 'glassTitle')}</div>
<div className={css.desc}>{text(props, copy, 'glassDescription')}</div>
</div>
<button
type="button"
role="switch"
aria-checked={glass}
className={css.switch}
data-on={glass || undefined}
data-better-display-glass={glass ? 'on' : 'off'}
onClick={() => { props.prefs.actions.setFrostedGlass(!glass); }}
/>
</div>
<div className={css.row}>
<div className={css.rowText}>
<div className={css.title}>{text(props, copy, 'foldTitle')}</div>
<div className={css.desc}>{text(props, copy, 'foldDescription')}</div>
</div>
<button
type="button"
role="switch"
aria-checked={autoFold}
className={css.switch}
data-on={autoFold || undefined}
data-better-display-auto-fold={autoFold ? 'on' : 'off'}
onClick={() => {
props.prefs.actions.setAutoFold?.(!autoFold);
props.prefs.actions.setFoldIntensity?.(!autoFold ? 1 : 0);
}}
/>
</div>
<section className={css.block} data-better-display-skill={skill?.installed ? 'installed' : 'missing'}>
<div className={css.title}>{text(props, copy, 'skillTitle')}</div>
<div className={css.status}>
<span className={css.badge} data-ok={skill?.installed || undefined}>
{skill?.installed ? text(props, copy, 'skillInstalled') : text(props, copy, 'skillMissing')}
</span>
</div>
<p className={css.desc}>{text(props, copy, 'skillPurpose')}</p>
<p className={css.desc}>{text(props, copy, 'skillPluginNote')}</p>
{skill && !skill.installed ? (
<>
<p className={css.desc}>{skill.hostReached ? text(props, copy, 'skillInstall') : text(props, copy, 'skillUnavailable')}</p>
<pre className={css.pre}>{shortestInstallCommand()}</pre>
<ul className={css.roots} data-better-display-skill-roots>
{CONVENTIONAL_SKILL_ROOTS.map(root => (
<li key={root}>{root}</li>
))}
</ul>
</>
) : null}
<div className={css.actions}>
<button type="button" className={css.button} disabled={checking} onClick={() => { void recheck(); }}>
{checking ? text(props, copy, 'skillChecking') : text(props, copy, 'skillRecheck')}
</button>
</div>
</section>
</div>
);
}

113
src/client/StickyLane.tsx Normal file
View File

@ -0,0 +1,113 @@
import { createContext, useContext, useLayoutEffect, useRef } from 'react';
import type { ReactNode } from 'react';
const MIN_LANE_PX = 40;
type LaneOwners = Map<string, HTMLElement>;
const LaneOwnerContext = createContext<LaneOwners | null>(null);
const ownersByRoot = new WeakMap<HTMLElement, LaneOwners>();
/** One map per Reader, so two roots that both contain turn 1 do not share a writer. */
export function ReaderLaneScope({ children }: { children: ReactNode }) {
const owners = useRef<LaneOwners>(new Map());
useLayoutEffect(() => {
const map = owners.current;
return () => { map.clear(); };
}, []);
return <LaneOwnerContext.Provider value={owners.current}>{children}</LaneOwnerContext.Provider>;
}
function laneScope(el: HTMLElement) {
return el.closest<HTMLElement>('[data-reader-turn]') ?? el.closest<HTMLElement>('[data-dsh-better-display]');
}
function ownersFor(el: HTMLElement, scoped: LaneOwners | null) {
if (scoped) return scoped;
const root = el.closest<HTMLElement>('[data-dsh-better-display]') ?? el;
let owners = ownersByRoot.get(root);
if (!owners) {
owners = new Map();
ownersByRoot.set(root, owners);
}
return owners;
}
function publishedLanePx(el: HTMLElement) {
return Math.max(MIN_LANE_PX, Math.ceil(el.getBoundingClientRect().height));
}
/** One writer per turn inside a single Reader. A retiring summary cannot clear the lane that replaced it. */
export function publishLaneHeight(el: HTMLElement, property: string, scoped: LaneOwners | null = null) {
const scope = laneScope(el);
if (!scope) return () => {};
const owners = ownersFor(el, scoped);
const root = el.closest<HTMLElement>('[data-dsh-better-display]');
const key = `${property}\0${scope.getAttribute('data-reader-turn') ?? 'root'}`;
const update = () => {
if (owners.get(key) !== el) return;
scope.style.setProperty(property, `${publishedLanePx(el)}px`);
};
owners.set(key, el);
update();
const observer = new ResizeObserver(update);
observer.observe(el);
return () => {
observer.disconnect();
if (owners.get(key) !== el) return;
owners.delete(key);
scope.style.removeProperty(property);
if (!scoped && root && owners.size === 0) ownersByRoot.delete(root);
};
}
export function usePublishedHeight(property: string) {
const owners = useContext(LaneOwnerContext);
const ref = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
return publishLaneHeight(el, property, owners);
}, [owners, property]);
return ref;
}
export function useSummaryLane(ref: { readonly current: HTMLElement | null }, active: boolean) {
const owners = useContext(LaneOwnerContext);
useLayoutEffect(() => {
const el = ref.current;
if (!active || !el) return;
return publishLaneHeight(el, '--reader-summary-height', owners);
}, [active, owners, ref]);
}
/** Publish real lane geometry; wrapped labels must not collide with statistics. */
export function StickyLane({ kind, className, children }: { kind: 'toolbar' | 'status'; className: string; children: ReactNode }) {
const ref = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const el = ref.current;
const scope = el?.closest<HTMLElement>(kind === 'toolbar' ? '[data-dsh-better-display]' : '[data-reader-turn]');
if (!el || !scope) return;
const property = kind === 'toolbar' ? '--reader-toolbar-height' : '--reader-status-height';
const update = () => {
scope.style.setProperty(property, `${Math.max(MIN_LANE_PX, el.getBoundingClientRect().height)}px`);
if (kind !== 'toolbar') return;
// The status lane is sized as calc(100% - --reader-control-width), so this
// must reserve the WHOLE control group. Measuring only the first button
// left every later control painted over by the status lane.
const controls = el.querySelectorAll('button');
let width = 80;
if (controls.length > 0) {
const first = controls[0]!.getBoundingClientRect();
const last = controls[controls.length - 1]!.getBoundingClientRect();
width = last.right - first.left;
}
scope.style.setProperty('--reader-control-width', `${width + 28}px`);
};
update();
const observer = new ResizeObserver(update);
observer.observe(el);
if (kind === 'toolbar') for (const control of el.querySelectorAll('button')) observer.observe(control);
return () => { observer.disconnect(); scope.style.removeProperty(property); if (kind === 'toolbar') scope.style.removeProperty('--reader-control-width'); };
}, [kind]);
return <div ref={ref} className={className} data-reader-lane={kind} data-ud-check={kind === 'toolbar' ? 'reader-toolbar' : undefined}>{children}</div>;
}

View File

@ -0,0 +1,170 @@
/* Zero-height sticky slot: floats over the transcript right gutter */
.slot {
position: sticky;
top: 0;
z-index: 10;
height: 0;
pointer-events: none;
}
.frame {
--turn-rail-band: calc(
var(--dsh-conversation-viewport-height, 100dvh) - var(--dsh-composer-height, 152px)
);
--turn-preview-height: 100px;
position: absolute;
top: calc(var(--turn-rail-band) / 2);
/* .root is the containing block (container-type creates layout containment)
and already reserves the right gutter via its own padding, so a small
positive inset keeps the rail inside the gutter, clear of the text. */
right: 6px;
width: 26px;
height: min(
var(--turn-natural-height),
max(0px, calc(var(--turn-rail-band) - 64px)),
420px
);
cursor: pointer;
pointer-events: auto;
transform: translateY(-50%);
transition: height 220ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.scroller {
position: absolute;
inset: 0;
overflow-y: auto;
overscroll-behavior: contain;
scrollbar-width: none;
}
.scroller::-webkit-scrollbar {
display: none;
}
.fadeTop {
mask-image: linear-gradient(to bottom, transparent 0, #000 24px, #000 100%);
-webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 24px, #000 100%);
}
.fadeBottom {
mask-image: linear-gradient(to bottom, #000 0, #000 calc(100% - 24px), transparent 100%);
-webkit-mask-image: linear-gradient(to bottom, #000 0, #000 calc(100% - 24px), transparent 100%);
}
.fadeTop.fadeBottom {
mask-image: linear-gradient(to bottom, transparent 0, #000 24px, #000 calc(100% - 24px), transparent 100%);
-webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 24px, #000 calc(100% - 24px), transparent 100%);
}
.marks {
position: relative;
height: var(--turn-natural-height);
}
.markPosition {
position: absolute;
top: calc(var(--turn-natural-position) + var(--turn-rail-inset));
right: 0;
left: 0;
height: 12px;
transform: translateY(-50%);
transition: top 220ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.mark {
position: absolute;
inset: 0 0 0 auto;
width: 24px;
padding: 0;
border: 0;
background: transparent;
cursor: pointer;
pointer-events: none;
display: flex;
align-items: center;
justify-content: flex-end;
}
.tick {
border-radius: 2px;
flex: none;
transition: width 100ms cubic-bezier(0.16, 1, 0.3, 1),
height 100ms cubic-bezier(0.16, 1, 0.3, 1),
opacity 100ms ease,
background-color 140ms ease;
}
.markBusy .tick {
animation: markBusyPulse 1s ease-in-out infinite alternate;
}
@keyframes markBusyPulse {
from { width: 8px; opacity: 0.4; }
to { width: 18px; opacity: 1; }
}
.preview {
position: absolute;
top: clamp(
0px,
calc(
var(--turn-natural-position) + var(--turn-rail-inset)
- var(--turn-scroll-top, 0px) - var(--turn-preview-height) / 2
),
calc(100% - var(--turn-preview-height))
);
right: calc(100% + 10px);
box-sizing: border-box;
width: min(280px, calc(100cqw - 120px));
max-height: var(--turn-preview-height);
overflow: hidden;
padding: 10px 12px;
border: 1px solid var(--dsw-alias-border-l2);
border-radius: 10px;
color: var(--dsw-alias-label-primary);
background: var(--dsw-alias-bg-base);
box-shadow: 0 4px 18px rgba(0, 0, 0, 0.12);
backdrop-filter: blur(12px);
pointer-events: none;
animation: previewFadeIn 120ms ease-out;
transition: top 140ms cubic-bezier(0.2, 0.8, 0.2, 1);
z-index: 40;
}
@keyframes previewFadeIn {
from { opacity: 0; transform: translateX(4px); }
to { opacity: 1; transform: translateX(0); }
}
.previewPrompt {
font-size: 12px;
line-height: 18px;
font-weight: 500;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-word;
}
.previewResponse {
margin-top: 4px;
color: var(--dsw-alias-label-tertiary);
font-size: 11px;
line-height: 16px;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-word;
}
@media (max-width: 960px) {
.slot {
display: none !important;
}
}

262
src/client/TimelineRail.tsx Normal file
View File

@ -0,0 +1,262 @@
import {
memo, useEffect, useId, useRef, useState,
type CSSProperties, type MouseEvent, type PointerEvent,
} from 'react';
import type { TimelineItem } from './timeline.js';
import css from './TimelineRail.module.css';
interface TimelineRailProps {
items: readonly TimelineItem[];
activeTurn: number | null;
busyTurn?: number | null;
onNavigate: (item: TimelineItem) => void;
}
const TURN_SPACING_PX = 12;
const RAIL_INSET_PX = 6;
const FADE_PX = 24;
type TurnPositionStyle = CSSProperties & {
readonly '--turn-natural-position': string;
};
type TurnFrameStyle = CSSProperties & {
readonly '--turn-natural-height': string;
readonly '--turn-rail-inset': string;
readonly '--turn-scroll-top': string;
};
function itemPosition(index: number): TurnPositionStyle {
return { '--turn-natural-position': `${index * TURN_SPACING_PX}px` };
}
function frameStyle(count: number, scrollTop: number): TurnFrameStyle {
return {
'--turn-natural-height': `${(count - 1) * TURN_SPACING_PX + 2 * RAIL_INSET_PX}px`,
'--turn-rail-inset': `${RAIL_INSET_PX}px`,
'--turn-scroll-top': `${scrollTop}px`,
};
}
function itemIndexAtPointer(
items: readonly TimelineItem[],
frame: HTMLElement,
scrollTop: number,
clientY: number,
): number {
const rect = frame.getBoundingClientRect();
const offset = clientY - rect.top + scrollTop - RAIL_INSET_PX;
return Math.max(0, Math.min(items.length - 1, Math.round(offset / TURN_SPACING_PX)));
}
interface RailScrollState {
readonly top: number;
readonly canScrollUp: boolean;
readonly canScrollDown: boolean;
}
const RAIL_AT_REST: RailScrollState = { top: 0, canScrollUp: false, canScrollDown: false };
function railScrollState(scroller: HTMLElement): RailScrollState {
const top = scroller.scrollTop;
return {
top,
canScrollUp: top > 1,
canScrollDown: top < scroller.scrollHeight - scroller.clientHeight - 1,
};
}
export const TimelineRail = memo(function TimelineRail({
items,
activeTurn,
busyTurn,
onNavigate,
}: TimelineRailProps) {
const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
const [scrollState, setScrollState] = useState<RailScrollState>(RAIL_AT_REST);
const scrollerRef = useRef<HTMLDivElement | null>(null);
const pointerInsideRef = useRef(false);
const previewId = useId();
const syncScrollState = () => {
const scroller = scrollerRef.current;
if (!scroller) return;
const next = railScrollState(scroller);
setScrollState(cur => (cur.top === next.top && cur.canScrollUp === next.canScrollUp && cur.canScrollDown === next.canScrollDown ? cur : next));
};
useEffect(() => {
const scroller = scrollerRef.current;
if (!scroller || typeof ResizeObserver === 'undefined') return;
const observer = new ResizeObserver(syncScrollState);
observer.observe(scroller);
return () => observer.disconnect();
}, []);
useEffect(syncScrollState, [items.length]);
// Keep active mark visible
useEffect(() => {
const scroller = scrollerRef.current;
const index = items.findIndex(item => item.turn === activeTurn);
if (!scroller || index < 0 || pointerInsideRef.current) return;
const markTop = index * TURN_SPACING_PX + RAIL_INSET_PX;
const viewTop = scroller.scrollTop;
const viewHeight = scroller.clientHeight;
if (viewHeight <= 0 || (markTop >= viewTop + FADE_PX && markTop <= viewTop + viewHeight - FADE_PX)) return;
const target = Math.max(0, markTop - viewHeight / 2);
if (typeof scroller.scrollTo === 'function') {
scroller.scrollTo({ top: target, behavior: 'smooth' });
} else {
scroller.scrollTop = target;
}
syncScrollState();
}, [activeTurn, items]);
if (items.length < 2) return null;
const preview = hoveredIndex !== null && hoveredIndex >= 0 ? items[hoveredIndex] : undefined;
const previewPosition = hoveredIndex !== null && hoveredIndex >= 0 ? itemPosition(hoveredIndex) : undefined;
const onPointerMove = (event: PointerEvent<HTMLElement>) => {
const scroller = scrollerRef.current;
const scrollTop = scroller?.scrollTop ?? 0;
const idx = itemIndexAtPointer(items, event.currentTarget, scrollTop, event.clientY);
setHoveredIndex(idx);
};
const onPointerLeave = () => {
pointerInsideRef.current = false;
setHoveredIndex(null);
};
const navigateAtPointer = (event: MouseEvent<HTMLElement>) => {
const scroller = scrollerRef.current;
const scrollTop = scroller?.scrollTop ?? 0;
const idx = itemIndexAtPointer(items, event.currentTarget, scrollTop, event.clientY);
const item = items[idx];
if (item !== undefined) onNavigate(item);
};
const fadeClasses = [css.scroller];
if (scrollState.canScrollUp) fadeClasses.push(css.fadeTop);
if (scrollState.canScrollDown) fadeClasses.push(css.fadeBottom);
return (
<div className={css.slot}>
<nav
className={css.frame}
style={frameStyle(items.length, scrollState.top)}
aria-label="轮次导航时间轴"
onClick={navigateAtPointer}
onPointerMove={onPointerMove}
onPointerEnter={() => { pointerInsideRef.current = true; }}
onPointerLeave={onPointerLeave}
onMouseDown={event => { event.preventDefault(); }}
>
<div
ref={scrollerRef}
className={fadeClasses.join(' ')}
onScroll={syncScrollState}
>
<div className={css.marks}>
{items.map((item, index) => {
const isBusy = busyTurn === item.turn;
const isActive = activeTurn === item.turn;
const isUnloaded = item.anchor.kind === 'unloaded';
// Wave calculation: peak at cursor, smoothly tapering off in width and height
let width = isUnloaded ? 6 : 8;
let height = 2;
let opacity = isUnloaded ? 0.3 : 0.45;
let background = 'var(--dsw-alias-label-tertiary)';
if (hoveredIndex !== null) {
const diff = Math.abs(index - hoveredIndex);
if (diff === 0) {
// Cursor peak (最长最高)
width = 26;
height = 2.8;
opacity = 1.0;
background = 'var(--dsw-alias-label-primary)';
} else if (diff === 1) {
// 旁边第 1 阶 (次长次高)
width = 18;
height = 2.2;
opacity = 0.8;
background = 'var(--dsw-alias-label-primary)';
} else if (diff === 2) {
// 旁边第 2 阶 (继续变矮变短)
width = 13;
height = 1.8;
opacity = 0.6;
background = 'var(--dsw-alias-label-secondary)';
} else if (diff === 3) {
// 旁边第 3 阶 (平缓过渡)
width = 9;
height = 1.6;
opacity = 0.45;
background = 'var(--dsw-alias-label-tertiary)';
} else {
// 远离光标的基线
width = 8;
height = 2;
opacity = 0.35;
background = 'var(--dsw-alias-label-tertiary)';
}
} else if (isActive) {
width = 20;
height = 2.4;
opacity = 0.95;
background = 'var(--dsw-alias-label-primary)';
}
const tickStyle: CSSProperties = {
width: `${width}px`,
height: `${height}px`,
opacity,
backgroundColor: background,
};
const markClasses = [css.mark];
if (isBusy) markClasses.push(css.markBusy);
return (
<div key={item.turn} className={css.markPosition} style={itemPosition(index)}>
<button
type="button"
className={markClasses.join(' ')}
aria-label={`第 ${item.turn + 1} 轮`}
aria-current={isActive ? 'true' : undefined}
aria-busy={isBusy ? 'true' : undefined}
aria-describedby={hoveredIndex === index ? previewId : undefined}
onMouseDown={event => { event.preventDefault(); }}
onClick={(e) => {
e.stopPropagation();
onNavigate(item);
}}
onFocus={() => setHoveredIndex(index)}
onBlur={() => setHoveredIndex(null)}
>
<span className={css.tick} style={tickStyle} />
</button>
</div>
);
})}
</div>
</div>
{preview !== undefined && previewPosition !== undefined && (
<div id={previewId} role="tooltip" className={css.preview} style={previewPosition}>
<div className={css.previewPrompt}>
{preview.prompt || `第 ${preview.turn + 1} 轮`}
</div>
{preview.response !== '' && (
<div className={css.previewResponse}>{preview.response}</div>
)}
</div>
)}
</nav>
</div>
);
});

278
src/client/ToolActivity.tsx Normal file
View File

@ -0,0 +1,278 @@
import { memo, useEffect, useId, useMemo, useRef, useState } from 'react';
import type { ToolCallBlock, ToolResultNode } from '@deepseek-ai/dsh-client-ui-conversation/client';
import type { DiffHunk, ReadBlockLine, SearchFileGroup } from '@deepseek-ai/dsh-client-ui-primitives';
import { DiffBlock, DisclosureRow, JsonTree, ReadBlock, SearchBlock, TerminalBlock, WebBlock,
IconApiOutlineRegular, IconBrowseOutlineRegular, IconEditOutlineRegular, IconSearchOutlineRegular, IconSkillOutlineRegular, IconSparkleRegular } from '@deepseek-ai/dsh-client-ui-primitives';
import { Blocks, contentBlocks } from './Blocks.js';
import { OfficialTool } from './OfficialContent.js';
import { ProcessFragment } from './motion.js';
import { activityPhase, activitySummary, callDiffHunks, diffTotals, executionFacts, forgetCallClock, objectValue, runningClockBase } from './tool-activity.js';
import type { ToolActivityEntry, ToolCategory, ToolPhase } from './tool-activity.js';
import type { BlockRenderProps } from './types.js';
import { classifyTool, toolRowModel, VARIANT_TITLES } from './native/tool-call-model.js';
import { McpAppFrame, StreamingMcpAppPlaceholder } from './McpAppFrame.js';
import { diffBlockLabels, jsonTreeLabels, readBlockLabels, searchBlockLabels, terminalBlockLabels, webBlockLabels } from './primitive-labels.js';
import css from './Reader.module.css';
const LABEL: Record<ToolPhase, string> = { preparing: '输入生成中', running: '执行中', returned: '已返回', succeeded: '已完成', failed: '失败', interrupted: '已中断' };
const ICONS = { write: IconEditOutlineRegular, read: IconBrowseOutlineRegular, terminal: IconApiOutlineRegular, search: IconSearchOutlineRegular, web: IconSearchOutlineRegular, code: IconApiOutlineRegular, other: IconSparkleRegular } satisfies Record<ToolCategory, unknown>;
const number = new Intl.NumberFormat('zh-CN');
const preparingTerminalLabels = { ...terminalBlockLabels, running: '正在生成命令' };
const language = (path: string | undefined) => path?.split('.').at(-1);
const duration = (ms: number) => ms < 1000 ? `${Math.round(ms)} 毫秒` : `${(ms / 1000).toFixed(ms < 10000 ? 1 : 0)} 秒`;
function generatedInput(content: string, target: string | undefined, preparing: boolean) {
const lines = content.split('\n').map((text, index) => ({ number: index + 1, text }));
const visible = preparing ? lines.slice(-12) : lines.slice(0, 1600);
return <div data-reader-tool-file><p className={css.toolDetailNote}>{preparing ? '正在生成的输入 · 尚未执行 · 末尾 12 行' : '工具输入中的文件内容'}{!preparing && lines.length > visible.length ? ' · 预览前 1,600 行,完整内容在原始数据中' : ''}</p>
<ReadBlock label={target ?? '文件内容'} lang={language(target)} lines={visible} totalLines={lines.length} maxLines={16} labels={readBlockLabels} />
</div>;
}
function InputView({ model, phase, fillComposer }: { model: ReturnType<typeof activitySummary>; phase: ToolPhase; fillComposer: BlockRenderProps['fillComposer'] }) {
const preparing = phase === 'preparing';
const inProgress = preparing || phase === 'running';
if ((model.name === 'render_ui' || model.name === 'show_widget') && typeof model.args?.html === 'string') {
return preparing
? <StreamingMcpAppPlaceholder title={typeof model.args.title === 'string' ? (model.args.title as string) : undefined} />
: <McpAppFrame html={model.args.html as string} title={typeof model.args.title === 'string' ? (model.args.title as string) : undefined} fillComposer={fillComposer} />;
}
if (model.content) return generatedInput(model.content, model.target, preparing);
if (model.command) return <div data-reader-tool-terminal><p className={css.toolDetailNote}>{preparing ? '正在生成命令 · 尚未执行' : '提交的命令'}</p><TerminalBlock command={model.command} cwd={model.cwd} running={inProgress} labels={preparing ? preparingTerminalLabels : terminalBlockLabels} /></div>;
if (model.category === 'terminal' && preparing && model.argsState === 'partial') return <p className={css.toolDetailNote} data-reader-tool-command-pending>命令仍在生成,收到可识别的命令文本后会显示预览。</p>;
return <JsonTree data={model.args} label={preparing ? '已收到的输入字段' : '工具输入'} labels={jsonTreeLabels} />;
}
function readLines(value: unknown): ReadBlockLine[] | null {
if (!Array.isArray(value)) return null;
const lines: ReadBlockLine[] = [];
for (const item of value) {
const row = objectValue(item);
if (typeof row?.number !== 'number' || !Number.isInteger(row.number) || typeof row.text !== 'string') return null;
lines.push({ number: row.number, text: row.text });
}
return lines;
}
/** A step past this reads as slow rather than merely in progress. */
const SLOW_TOOL_MS = 10_000;
function diffHunks(value: unknown): DiffHunk[] | null {
if (!Array.isArray(value) || value.length === 0) return null;
const diffs: DiffHunk[] = [];
for (const item of value) {
const row = objectValue(item);
if (typeof row?.path !== 'string' || (row.oldText !== null && typeof row.oldText !== 'string') || typeof row.newText !== 'string') return null;
diffs.push({ path: row.path, oldText: row.oldText, newText: row.newText });
}
return diffs;
}
function searchFiles(value: unknown): SearchFileGroup[] | null {
if (!Array.isArray(value)) return null;
const files: SearchFileGroup[] = [];
for (const item of value) {
const row = objectValue(item);
if (typeof row?.path !== 'string' || !Array.isArray(row.matches)) return null;
const matches: { lineNumber: number; line: string }[] = [];
for (const itemMatch of row.matches) {
const match = objectValue(itemMatch);
if (typeof match?.lineNumber !== 'number' || !Number.isInteger(match.lineNumber) || typeof match.line !== 'string') return null;
matches.push({ lineNumber: match.lineNumber, line: match.line });
}
files.push({ path: row.path, matches });
}
return files;
}
function ResultView(props: BlockRenderProps & { entry: ToolActivityEntry; model: ReturnType<typeof activitySummary>; phase: ToolPhase }) {
const { official, entry, model } = props;
const fallback = <ResultFallback {...props} />;
if (!official || !entry.block || model.name === 'render_ui' || model.name === 'show_widget') return fallback;
return <OfficialTool {...props} official={official} block={entry.block} toolName={model.name} cwd={props.cwd ?? model.cwd} fallback={fallback} />;
}
function ResultFallback({ entry, model, phase, ...render }: BlockRenderProps & { entry: ToolActivityEntry; model: ReturnType<typeof activitySummary>; phase: ToolPhase }) {
if ((model.name === 'render_ui' || model.name === 'show_widget') && typeof model.args?.html === 'string') {
return <McpAppFrame html={model.args.html as string} title={typeof model.args.title === 'string' ? (model.args.title as string) : undefined} fillComposer={render.fillComposer} />;
}
const block = entry.block;
if (!block || !('kind' in block)) return <>
<p className={css.toolDetailNote}>{phase === 'interrupted' ? '已中断,没有工具结果。已生成的输入仍可查看。' : phase === 'preparing' ? '模型正在生成工具输入,工具还未开始执行。' : '工具已开始执行,正在等待结果。'}</p>
<InputView model={model} phase={phase} fillComposer={render.fillComposer} />
</>;
const meta = objectValue(block.meta);
const text = block.content.filter(item => item.type === 'text').map(item => item.text).join('\n');
if (phase === 'interrupted') return <><p className={css.toolDetailNote}>工具已取消,未正常完成。输入和原始返回记录仍可查看。</p><InputView model={model} phase={phase} fillComposer={render.fillComposer} /><pre className={css.toolRaw}>{text}</pre></>;
if (model.category === 'terminal') {
const facts = executionFacts(block);
const output = text.replace(/\n\[(?:exit code: \d+|killed by signal: [^\]\n]+)\]$/, '');
return <div data-reader-tool-terminal><TerminalBlock command={model.command ?? model.name} cwd={model.cwd}
output={output} exitCode={facts.exitCode} signal={facts.signal} maxLines={18} labels={terminalBlockLabels} /></div>;
}
const lines = readLines(meta?.lines);
if (model.category === 'read' && typeof meta?.path === 'string' && typeof meta.totalLines === 'number' && lines) return <div data-reader-tool-file><ReadBlock label={meta.path} lang={typeof meta.lang === 'string' ? meta.lang : undefined} lines={lines} totalLines={meta.totalLines} maxLines={18} labels={readBlockLabels} /></div>;
// The host's own hunks when it sent them; otherwise derive them from the call's
// arguments, which is also what the official row does while a write is pending.
// Both the counts and this card read the same source, so they cannot disagree.
const diffs = diffHunks(meta?.diffs) ?? callDiffHunks(block, model.args, model.name);
if (diffs.length) return <div data-reader-tool-diff><DiffBlock diffs={diffs} maxLines={18} labels={diffBlockLabels} /></div>;
if (model.category === 'search' && typeof meta?.total === 'number' && typeof meta.truncated === 'boolean') {
if (meta.shape === 'paths' && Array.isArray(meta.paths) && meta.paths.every((path): path is string => typeof path === 'string')) return <div data-reader-tool-search><SearchBlock kind="paths" paths={meta.paths} total={meta.total} truncated={meta.truncated} maxLines={18} labels={searchBlockLabels} /></div>;
const files = searchFiles(meta.files);
if (meta.shape === 'matches' && files) return <div data-reader-tool-search><SearchBlock kind="matches" files={files} total={meta.total} truncated={meta.truncated} maxLines={18} labels={searchBlockLabels} /></div>;
}
if (model.category === 'web' && typeof meta?.truncated === 'boolean') {
if (model.name === 'web_fetch' && typeof meta.url === 'string' && typeof meta.statusCode === 'number') return <div data-reader-tool-web><WebBlock kind="fetch" url={meta.url} statusCode={meta.statusCode} truncated={meta.truncated} labels={webBlockLabels} /></div>;
if (model.name === 'web_search' && Array.isArray(meta.sources)) {
const sources = meta.sources.flatMap(source => {
const item = objectValue(source);
return typeof item?.url === 'string' ? [{ url: item.url, ...(typeof item.title === 'string' ? { title: item.title } : {}), ...(typeof item.snippet === 'string' ? { snippet: item.snippet } : {}), ...(typeof item.publishedAt === 'string' ? { publishedAt: item.publishedAt } : {}) }] : [];
});
if (sources.length === meta.sources.length) return <div data-reader-tool-web><WebBlock kind="search" sources={sources} answer={typeof meta.answer === 'string' ? meta.answer : undefined} truncated={meta.truncated} labels={webBlockLabels} /></div>;
}
}
// A trace/export may omit wire presentation. Keep the generated input clearly
// labelled; it is not proof of an applied diff or a successful file mutation.
if (model.category === 'write' && model.content && !block.isError) return <>
<p className={css.toolDetailNote}>文件工具已返回。以下为提交的内容;完整返回记录可在「原始数据」查看。</p>
{generatedInput(model.content, model.target, false)}
</>;
const content: ToolResultNode['content'] = block.content;
// A code interpreter's product is its result, not prose. Without this branch
// the output fell through to the generic document path below, which emits it
// as reader answer text — so a run_code card sat in the transcript outside
// every fold, the exact block the reader wanted to be able to close.
if (model.category === 'code') {
const output = content.filter(item => item.type === 'text').map(item => item.text).join('\n');
const facts = executionFacts(block);
if (output.trim()) return <div data-reader-tool-code>
<TerminalBlock command={model.command ?? model.name} cwd={model.cwd} output={output}
exitCode={facts.exitCode} signal={facts.signal} maxLines={18} labels={terminalBlockLabels} />
</div>;
return <p className={css.toolDetailNote}>代码已执行,没有可展示的输出。</p>;
}
if (content.some(item => item.type === 'text')) return <div className={css.toolDocument}><Blocks {...render} blocks={contentBlocks(content).filter(item => item.kind === 'text')} source="tool" /></div>;
if (content.length) return <p className={css.toolDetailNote}>图片或扩展内容已在对话中单独展示。</p>;
return <p className={css.toolDetailNote}>工具没有返回可展示的内容。</p>;
}
/** One occurrence, keyed by call id all the way from generation to result. */
export const ToolActivity = memo(function ToolActivityView({ entry, motion, turnClosed, onRead, depth = 0, ...render }: BlockRenderProps & {
entry: ToolActivityEntry; motion: boolean; turnClosed: boolean; onRead: () => void; depth?: number;
}) {
const [open, setOpen] = useState(false);
const [tab, setTab] = useState<'result' | 'input' | 'raw'>('result');
const control = useRef<HTMLElement | null>(null);
const panel = useRef<HTMLDivElement>(null);
const [selected, setSelected] = useState(false);
const detailId = useId();
const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);
const model = useMemo(() => activitySummary(entry), [entry.block, entry.draft]);
const phase = activityPhase(entry, turnClosed);
const heldPreview = useRef({ entry, model, phase });
if (!selected) heldPreview.current = { entry, model, phase };
const preview = heldPreview.current;
useEffect(() => {
const track = () => {
const selection = document.getSelection();
setSelected(!!selection && !selection.isCollapsed && !!selection.anchorNode && !!panel.current?.contains(selection.anchorNode));
};
document.addEventListener('selectionchange', track);
return () => document.removeEventListener('selectionchange', track);
}, []);
const facts = executionFacts(entry.block);
const Icon = model.name === 'skill' ? IconSkillOutlineRegular : ICONS[model.category];
const block = entry.block;
const native = block ? toolRowModel(model.name, block) : null;
const skillName = typeof model.args?.name === 'string' ? model.args.name.split('\n')[0] : model.raw.split('\n')[0];
const rowTitle = model.name === 'skill' ? 'Skill' : native?.title ?? VARIANT_TITLES[classifyTool(model.name)];
const rowSummary = phase === 'interrupted' ? '已停止 · 调用记录保留' : model.name === 'skill' ? skillName : native?.errorSummary ?? native?.summary
?? (classifyTool(model.name) === 'others' ? `${model.name} · ${model.target ?? model.title}` : model.target ?? model.title);
// Files that changed get the same +/- line counts the official tool row shows,
// read straight from the diff the host attached to the result.
const diff = useMemo(() => diffTotals(block, model.args, model.name), [block, model.args, model.name]);
// The changed lines ride in the row's own expansion, the way the official tool
// row shows them — one disclosure, not a second floating widget.
const showState = phase === 'preparing' || phase === 'running' || phase === 'failed' || phase === 'interrupted';
const running = phase === 'preparing' || phase === 'running';
// A step that has not returned yet counts its own seconds, so a long command
// reads as progress rather than as a stall. The clock counts from the call's
// stamped start — a session event time, not the moment this view mounted —
// so switching conversations and back keeps it running instead of resetting
// it to zero, and it disappears the moment the result arrives.
const [liveMs, setLiveMs] = useState<number | null>(null);
useEffect(() => {
if (!running) { forgetCallClock(entry.callId); setLiveMs(null); return; }
const base = runningClockBase(entry.callId, block);
const tick = () => setLiveMs(Math.max(0, Date.now() - base));
tick();
const timer = setInterval(tick, 200);
return () => clearInterval(timer);
}, [running, block, entry.callId]);
const elapsed = block && 'kind' in block && block.callTime != null ? Math.max(0, block.time - block.callTime) : null;
// A step that ran long keeps showing how long it took after it returns: the
// number is the point of the readout. A fast step shows nothing once it is done.
const shownMs = liveMs ?? (elapsed !== null && elapsed >= SLOW_TOOL_MS ? elapsed : null);
const rawResult = useMemo(() => {
const value = preview.entry.block;
return value && 'kind' in value ? JSON.stringify({ content: value.content, isError: value.isError, meta: value.meta }, null, 2) : '';
}, [preview.entry.block]);
const tabs = [['result', phase === 'preparing' ? '生成预览' : '结果'], ['input', '输入'], ['raw', '原始数据']] as const;
const activate = (index: number) => { const item = tabs[(index + tabs.length) % tabs.length]!; setTab(item[0]); tabRefs.current[(index + tabs.length) % tabs.length]?.focus(); };
if (depth > 6) return <p className={css.meta}>更深的嵌套调用可在原对话查看。</p>;
return <div ref={element => { control.current = element?.querySelector<HTMLElement>('[data-disclosure-row]') ?? null; }} className={css.toolActivity} data-reader-tool-call={entry.callId} data-tool-phase={phase} data-tool-args-length={model.raw.length} data-tool-category={model.category} data-expanded={open} data-ud-check="reader-tool-activity">
<DisclosureRow icon={<Icon size={14} />} title={rowTitle} open={open} expandable expandOnRowClick keepContentWhenOpen
onToggle={() => { onRead(); setOpen(value => !value); }} rowClassName={css.nativeToolRow}
collapsedContent={<><span className={css.rowSeparator} aria-hidden /><span className={css.nativeToolSummary} title={rowSummary} data-reader-tool-summary
{...(running ? { 'data-running': '' } : {})}>{rowSummary}</span>
{shownMs !== null && <span className={css.toolElapsed} data-reader-tool-elapsed
{...(shownMs >= SLOW_TOOL_MS ? { 'data-slow': '' } : {})}>
{(shownMs / 1000).toFixed(shownMs < 10000 ? 1 : 0)}s</span>}
{diff && <span className={css.diffStat} data-reader-diff-stat>
{diff.added > 0 && <span className={css.diffAdded}>+{number.format(diff.added)}</span>}
{diff.removed > 0 && <span className={css.diffRemoved}>-{number.format(diff.removed)}</span>}
</span>}
{showState && <span className={css.toolState} data-phase={phase}>{LABEL[phase]}</span>}</>} />
<ProcessFragment open={open} motion={motion} onRead={onRead} returnFocusTo={control} nodeKey={`${entry.key}:detail`} framed>
<div id={detailId} className={css.toolDetails}>
<div className={css.toolLedger} aria-live="off">
<span>工具 · <span className={css.toolEngine}>{model.name}</span></span>
<span data-reader-tool-progress>{phase === 'preparing' ? `已接收 ${number.format(model.raw.length)} 字符输入` : phase === 'running' ? '已提交 · 等待工具返回' : phase === 'interrupted' ? '已停止 · 输入记录保留' : elapsed !== null ? `执行 ${duration(elapsed)}` : '结果已记录'}</span>
{facts.exitCode !== undefined && <span>退出码 {facts.exitCode}</span>}
{facts.signal && <span>信号 {facts.signal}</span>}
</div>
<div className={css.toolTabs} role="tablist" aria-label={`${model.title}的执行数据`} onKeyDown={event => {
const index = tabs.findIndex(item => item[0] === tab);
if (event.key === 'ArrowRight' || event.key === 'ArrowLeft') { event.preventDefault(); activate(index + (event.key === 'ArrowRight' ? 1 : -1)); }
else if (event.key === 'Home' || event.key === 'End') { event.preventDefault(); activate(event.key === 'Home' ? 0 : tabs.length - 1); }
}}>{tabs.map(([id, title], index) => <button key={id} ref={element => { tabRefs.current[index] = element; }} type="button" role="tab" id={`${detailId}-${id}`} aria-selected={tab === id} aria-controls={`${detailId}-panel`} tabIndex={tab === id ? 0 : -1} onClick={() => setTab(id)}>{title}</button>)}</div>
<div ref={panel} id={`${detailId}-panel`} className={css.toolPanel} role="tabpanel" aria-labelledby={`${detailId}-${tab}`} tabIndex={0}>
{selected && <p className={css.toolDetailNote}>为保留选区,预览暂停更新;当前状态见卡片标题。</p>}
{tab === 'result' && <ResultView {...render} {...preview} />}
{tab === 'input' && <><InputView model={preview.model} phase={preview.phase} fillComposer={render.fillComposer} /><details className={css.detail}><summary>全部输入字段</summary><JsonTree data={preview.model.args} label="输入字段" labels={jsonTreeLabels} /></details></>}
{tab === 'raw' && <><p className={css.toolDetailNote}>完整记录 · 只读 · 不执行其中的代码</p><h4 className={css.toolRawLabel}>工具输入</h4><pre className={css.toolRaw}>{preview.model.raw || '输入尚未到达'}</pre>{rawResult && <><h4 className={css.toolRawLabel}>工具结果</h4><pre className={css.toolRaw}>{rawResult}</pre></>}</>}
</div>
</div>
</ProcessFragment>
{!!block?.subCalls.length && <div className={css.toolChildren} aria-label="子调用">{block.subCalls.map((child, index) => <ToolActivity key={child.callId} {...render}
entry={{ kind: 'tool', key: `reader-tool:${child.callId}`, callId: child.callId, step: entry.step, order: index, block: child }}
motion={motion} turnClosed={turnClosed} onRead={onRead} depth={depth + 1} />)}</div>}
</div>;
}, (previous, next) => previous.entry.callId === next.entry.callId && previous.entry.block === next.entry.block
&& previous.entry.draft === next.entry.draft && previous.entry.step === next.entry.step
&& previous.motion === next.motion && previous.turnClosed === next.turnClosed && previous.depth === next.depth
&& previous.onRead === next.onRead && previous.renderSlotChain === next.renderSlotChain && previous.loadImage === next.loadImage && previous.fillComposer === next.fillComposer
&& previous.official === next.official && previous.cwd === next.cwd && previous.openFile === next.openFile);
/** Rich media (images, MCP widgets) rendered outside the folded tool ledger. */
export function ToolMedia({ block, depth = 0, ...render }: BlockRenderProps & { block: ToolCallBlock; depth?: number }) {
if (depth > 6) return null;
const settled = 'kind' in block;
const visible = settled ? contentBlocks(block.content).filter(item => item.kind === 'image' || item.kind === 'other') : [];
return <>
{visible.length > 0 && <Blocks {...render} blocks={visible} source="tool" />}
{block.subCalls.map(child => <ToolMedia key={child.callId} {...render} block={child} depth={depth + 1} />)}
</>;
}

View File

@ -0,0 +1,139 @@
.container {
display: inline-flex;
align-items: center;
gap: 2px;
position: relative;
font-size: 13px;
line-height: 24px;
color: var(--dsw-alias-label-tertiary);
}
.pillButton {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 2px 8px;
border-radius: 12px;
border: 1px solid var(--dsw-alias-border-l1);
background: var(--dsw-alias-bg-module-platform);
color: var(--dsw-alias-label-tertiary);
font-size: 11px;
cursor: pointer;
outline: none;
transition: all 140ms ease;
font-family: inherit;
}
.pillButton:hover, .pillButton[data-active=true] {
color: var(--dsw-alias-label-primary);
border-color: var(--dsw-alias-border-l2);
background: var(--dsw-alias-interactive-bg-hover);
}
.timeButton {
display: inline-flex;
align-items: center;
gap: 4px;
height: 28px;
padding: 6px 8px;
border: none;
border-radius: 28px;
background: transparent;
color: var(--dsw-alias-label-tertiary);
font-size: 13px;
font-variant-numeric: tabular-nums;
line-height: 24px;
white-space: nowrap;
cursor: pointer;
font-family: inherit;
}
.timeButton:hover, .timeButton[data-active=true] {
background: var(--dsw-alias-interactive-bg-hover);
color: var(--dsw-alias-label-secondary);
}
.pillIcon {
width: 12px;
height: 12px;
flex: none;
opacity: .8;
}
.metricsPop {
position: absolute;
bottom: calc(100% + 8px);
left: 0;
width: 260px;
padding: 12px 14px;
border-radius: 10px;
background: var(--dsw-alias-bg-base);
border: 1px solid var(--dsw-alias-border-l2);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.14);
backdrop-filter: blur(10px);
z-index: 50;
display: flex;
flex-direction: column;
gap: 8px;
text-align: left;
animation: popIn 140ms ease-out;
}
@keyframes popIn {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
}
.popHeader {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 12px;
font-weight: 600;
color: var(--dsw-alias-label-primary);
padding-bottom: 6px;
border-bottom: 1px solid var(--dsw-alias-border-l1);
}
.popSection {
display: flex;
flex-direction: column;
gap: 4px;
}
.popSectionTitle {
font-size: 10px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .5px;
color: var(--dsw-alias-label-tertiary);
margin-top: 2px;
}
.popGrid {
display: grid;
grid-template-columns: 1fr auto;
gap: 3px 12px;
font-size: 11px;
line-height: 18px;
}
.popLabel {
color: var(--dsw-alias-label-secondary);
}
.popValue {
color: var(--dsw-alias-label-primary);
font-variant-numeric: tabular-nums;
font-weight: 500;
text-align: right;
}
.popBadge {
font-size: 10px;
padding: 0 4px;
border-radius: 3px;
background: var(--dsw-alias-border-l1);
color: var(--dsw-alias-label-secondary);
margin-left: 4px;
}

160
src/client/TurnMetrics.tsx Normal file
View File

@ -0,0 +1,160 @@
import { memo, useEffect, useRef, useState } from 'react';
import type { TurnTailChatData } from '@deepseek-ai/dsh-client-ui-chat/client';
import { formatRanFor, formatRunDuration } from './message-chrome.js';
import css from './TurnMetrics.module.css';
type TurnTokenUsage = NonNullable<TurnTailChatData['tokenUsage']>;
export interface TurnMetricsProps {
usage?: TurnTokenUsage;
runMs?: number;
tokensPerSecond?: number;
ttftMs?: number;
}
function formatTokens(count: number): string {
if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(2)}M tok`;
if (count >= 1000) return `${(count / 1000).toFixed(1)}k tok`;
return `${count} tok`;
}
export const TurnMetrics = memo(function TurnMetrics({
usage,
runMs,
tokensPerSecond,
ttftMs,
}: TurnMetricsProps) {
const [open, setOpen] = useState(false);
const containerRef = useRef<HTMLSpanElement>(null);
useEffect(() => {
if (!open) return;
const onClickOutside = (e: MouseEvent) => {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setOpen(false);
}
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') setOpen(false);
};
document.addEventListener('pointerdown', onClickOutside);
document.addEventListener('keydown', onKeyDown);
return () => {
document.removeEventListener('pointerdown', onClickOutside);
document.removeEventListener('keydown', onKeyDown);
};
}, [open]);
const totalTokens = usage?.totalTokens;
const hasTiming = typeof runMs === 'number' && runMs > 0;
const hasTokens = typeof totalTokens === 'number' && totalTokens > 0;
if (!hasTiming && !hasTokens) return null;
const cacheHitPercent = usage && usage.cacheReadTokens && usage.totalTokens > usage.outputTokens
? Math.round((usage.cacheReadTokens / (usage.totalTokens - usage.outputTokens)) * 100)
: null;
return (
<span ref={containerRef} className={css.container}>
{hasTokens && typeof totalTokens === 'number' && (
<button
type="button"
className={css.pillButton}
data-active={open}
onClick={() => setOpen(v => !v)}
aria-expanded={open}
title="查看本轮 Token 消耗"
>
<svg className={css.pillIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<ellipse cx="8" cy="4.2" rx="5" ry="2.2" strokeWidth="1.2" />
<path d="M3 4.2v7.6c0 1.2 2.2 2.2 5 2.2s5-1 5-2.2V4.2" strokeWidth="1.2" />
<path d="M3 8c0 1.2 2.2 2.2 5 2.2s5-1 5-2.2" strokeWidth="1.2" />
</svg>
<span>用量 {formatTokens(totalTokens)}</span>
</button>
)}
{hasTiming && typeof runMs === 'number' && (
<button
type="button"
className={css.timeButton}
data-active={open}
onClick={() => setOpen(v => !v)}
aria-expanded={open}
aria-label={formatRanFor(runMs)}
title="查看本轮用时和速度"
>
<svg className={css.pillIcon} viewBox="0 0 16 16" fill="none" stroke="currentColor">
<circle cx="8" cy="8" r="6.5" strokeWidth="1.2" />
<path d="M8 4.5v3.8l2.5 1.5" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
<span>{formatRanFor(runMs)}</span>
</button>
)}
{open && (
<div className={css.metricsPop} role="dialog" aria-label="本轮概况">
<div className={css.popHeader}>
<span>本轮性能与用量概况</span>
</div>
{hasTiming && typeof runMs === 'number' && (
<div className={css.popSection}>
<div className={css.popSectionTitle}>耗时与生成速度</div>
<div className={css.popGrid}>
<span className={css.popLabel}>总用时</span>
<span className={css.popValue}>{formatRunDuration(runMs)}</span>
{typeof tokensPerSecond === 'number' && tokensPerSecond > 0 && (
<>
<span className={css.popLabel}>生成吞吐 (TPS)</span>
<span className={css.popValue}>{tokensPerSecond.toFixed(1)} tok/s</span>
</>
)}
{typeof ttftMs === 'number' && ttftMs > 0 && (
<>
<span className={css.popLabel}>首字延迟 (TTFT)</span>
<span className={css.popValue}>{(ttftMs / 1000).toFixed(2)}s</span>
</>
)}
</div>
</div>
)}
{hasTokens && usage && (
<div className={css.popSection}>
<div className={css.popSectionTitle}>Token 消耗分解</div>
<div className={css.popGrid}>
<span className={css.popLabel}>总消耗</span>
<span className={css.popValue}>{usage.totalTokens.toLocaleString()} tok</span>
<span className={css.popLabel}>
输入
{cacheHitPercent !== null && (
<span className={css.popBadge}>命中 {cacheHitPercent}%</span>
)}
</span>
<span className={css.popValue}>{(usage.totalTokens - usage.outputTokens).toLocaleString()} tok</span>
{typeof usage.cacheReadTokens === 'number' && usage.cacheReadTokens > 0 && (
<>
<span className={css.popLabel}>缓存读取</span>
<span className={css.popValue}>{usage.cacheReadTokens.toLocaleString()} tok</span>
</>
)}
<span className={css.popLabel}>
输出
{typeof usage.reasoningTokens === 'number' && usage.reasoningTokens > 0 && (
<span className={css.popBadge}>思考 {usage.reasoningTokens.toLocaleString()}</span>
)}
</span>
<span className={css.popValue}>{usage.outputTokens?.toLocaleString() ?? 0} tok</span>
</div>
</div>
)}
</div>
)}
</span>
);
});

33
src/client/WaitClock.tsx Normal file
View File

@ -0,0 +1,33 @@
import { useEffect, useState } from 'react';
import { formatRunDuration } from './message-chrome.js';
import css from './Reader.module.css';
/** Past this, a wait stops being a pause and reads as the model not answering. */
export const WAIT_OVERTIME_MS = 10_000;
/**
* How long the model has been given the turn, counted in plain seconds.
*
* Just the number and, past ten seconds, a「暂未响应」badge — no bar, because the
* question the reader has is「how long has this been hanging」, not「how far
* along」: there is no known total to be a fraction of.
*
* The clock restarts whenever the anchor changes, so each wait is timed from the
* event that started it rather than from the beginning of the turn.
*/
export function WaitClock({ startTime }: { startTime: number | null }) {
const [mountedAt] = useState(() => Date.now());
const [now, setNow] = useState(() => Date.now());
const anchor = startTime ?? mountedAt;
useEffect(() => {
const id = setInterval(() => setNow(Date.now()), 250);
return () => clearInterval(id);
}, []);
const waited = Math.max(0, now - anchor);
const overtime = waited >= WAIT_OVERTIME_MS;
return <span className={css.waitClock} data-reader-wait-clock
{...(overtime ? { 'data-overtime': '' } : {})}>
<span className={css.waitSeconds}>{formatRunDuration(waited)}</span>
{overtime && <span className={css.waitOvertime} data-reader-wait-badge>暂未响应</span>}
</span>;
}

View File

@ -0,0 +1,13 @@
import { WaitClock } from './WaitClock.js';
import type { WaitingAnchor } from './waiting-clock.js';
import css from './Reader.module.css';
export function WaitingStatus({ anchor, label }: { anchor: WaitingAnchor; label: string }) {
// A new input gets its own clock even if the waiting indicator stays mounted;
// the readout itself is shared with the group status so the two never disagree.
return <div className={css.turnStatus} role="status" aria-live="polite" data-reader-turn-status
data-reader-wait-start={anchor.time ?? ''}>
<span className={css.turnStatusLabel}>{label}</span>
<WaitClock key={anchor.key} startTime={anchor.time} />
</div>;
}

10
src/client/chat-seat.ts Normal file
View File

@ -0,0 +1,10 @@
export type ChatSeatKind = 'user' | 'steering';
export function chatSeatProps(kind: ChatSeatKind, key: string): Record<string, string> {
return {
'data-chat-anchor-key': key,
'data-chat-flow-key': key,
'data-chat-node-key': key,
'data-chat-flow-kind': kind,
};
}

View File

@ -0,0 +1,123 @@
/**
* 功能一:审批卡片的回车批准 / Esc 拒绝(自动送入焦点 + 全局兜底路由)。
*
* 背景(@deepseek-ai/dsh-client-ui-approval):官方审批卡自带键盘处理
* —— Enter 批准(单次)、Esc 拒绝 —— 但 keydown 挂在卡片根节点上,且
* 要求焦点先落在卡片内。审批弹出时焦点往往还在对话区,按回车毫无反应。
*
* 本模块补两件事,不改官方任何逻辑:
* 1. 审批卡出现时,若用户没有正在别处输入,把焦点送进卡片详情区。
* 2. 焦点不在卡片内时兜底路由:document 捕获阶段拦 keydown,点击卡片
* 操作行里的按钮 —— 回车点「允许(单次)」,Esc 点「拒绝」。
*/
const CARD_SELECTOR = '[data-approval-key]'
const SCROLL_SELECTOR = '[data-approval-scroll]'
const EDITABLE_SELECTOR = 'input, textarea, select, [contenteditable="true"], [contenteditable=""]'
export interface KeyActionInput {
key: string
ctrlKey?: boolean
metaKey?: boolean
altKey?: boolean
shiftKey?: boolean
repeat?: boolean
isComposing?: boolean
keyCode?: number
defaultPrevented?: boolean
target?: Element | null
activeElement?: Element | null
card?: Element | null
}
/** 卡片操作行的按钮:详情滚动区之外的全部按钮,顺序 [拒绝, 允许, 始终允许?]。 */
export function actionButtons(card: Element): HTMLButtonElement[] {
return [...card.querySelectorAll('button')].filter(
(button) => !button.closest(SCROLL_SELECTOR),
) as HTMLButtonElement[]
}
/** 找当前可作答的审批卡(DOM 顺序第一张未作答、按钮齐全的卡)。 */
export function findPendingCard(doc: Document): Element | null {
for (const card of doc.querySelectorAll(CARD_SELECTOR)) {
if (card.getAttribute('aria-busy') === 'true') continue
const buttons = actionButtons(card)
if (buttons.length >= 2 && !buttons[0].disabled && !buttons[1].disabled) return card
}
return null
}
/**
* 纯判定:这次 keydown 是否应该路由到审批卡。
* @returns 'allow' | 'reject' | null
*/
export function decideKeyAction(input: KeyActionInput): 'allow' | 'reject' | null {
const {
key, ctrlKey, metaKey, altKey, shiftKey, repeat, isComposing,
keyCode, defaultPrevented, target, activeElement, card,
} = input
if (!card) return null
if (defaultPrevented) return null
if (key !== 'Enter' && key !== 'Escape') return null
if (ctrlKey || metaKey || altKey || shiftKey) return null
if (repeat || isComposing || keyCode === 229) return null
if (activeElement && card.contains(activeElement)) return null // 焦点在卡内:官方处理
if (target && typeof target.closest === 'function') {
if (target.closest(EDITABLE_SELECTOR) !== null) return null // 正在别处输入
if (key === 'Enter' && target.closest('button, a[href], [role="button"]') !== null) return null
}
return key === 'Enter' ? 'allow' : 'reject'
}
/** 纯判定:审批卡出现时是否应该把焦点送进详情区。 */
export function shouldAutoFocus(activeElement: Element | null | undefined, card: Element): boolean {
if (!activeElement) return true
if (activeElement === card.ownerDocument?.body) return true
if (card.contains(activeElement)) return false // 已经在卡里
if (typeof activeElement.closest === 'function' && activeElement.closest(EDITABLE_SELECTOR) !== null) {
return false // 正在别处输入
}
return true
}
/** 安装审批键盘增强,返回卸载函数。 */
export function install(doc: Document): () => void {
const focusedCards = new WeakSet<Element>()
const tryAutoFocus = (): void => {
const card = findPendingCard(doc)
if (!card || focusedCards.has(card)) return
focusedCards.add(card)
if (!shouldAutoFocus(doc.activeElement, card)) return
const region = card.querySelector(SCROLL_SELECTOR)
if (region && typeof (region as HTMLElement).focus === 'function') (region as HTMLElement).focus()
}
const observer = new MutationObserver(tryAutoFocus)
observer.observe(doc.documentElement, { childList: true, subtree: true })
tryAutoFocus()
const onKeyDown = (event: KeyboardEvent): void => {
const card = findPendingCard(doc)
const action = decideKeyAction({
key: event.key,
ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey,
repeat: event.repeat, isComposing: event.isComposing, keyCode: event.keyCode,
defaultPrevented: event.defaultPrevented,
target: event.target as Element | null, activeElement: doc.activeElement, card,
})
if (!action || !card) return
const buttons = actionButtons(card)
const button = action === 'allow' ? buttons[1] : buttons[0]
if (!button || button.disabled) return
event.preventDefault()
event.stopPropagation()
button.click()
}
doc.addEventListener('keydown', onKeyDown, true)
return () => {
observer.disconnect()
doc.removeEventListener('keydown', onKeyDown, true)
}
}

View File

@ -0,0 +1,131 @@
/**
* 功能二:权限 UI —— 去掉「完全权限」选项,不改已有会话权限。
*
* 会话权限有四个预设值:read-only(仅可查看)、workspace-write(工作区内
* 修改)、danger-full-access(完全权限)、auto(自动审查,EXP)。「自动
* 审查」由实验层提供,开启后才出现在当前会话的选择器里;通用设置不提供
* auto,新会话默认值里也选不到它。
*
* 本功能只做一件事:界面移除完全权限。它**不再**在页面加载、刷新或插件
* 重载时遍历已有会话改权限:默认权限属于宿主的新建会话流程,本插件没有
* 可靠的新建扩展点,因此不拿轮询去补偿。
*/
/** 完全权限的预设机器值。 */
export const FULL_ACCESS_PRESET = 'danger-full-access'
/** 自动审查的预设机器值。 */
export const AUTO_REVIEW_PRESET = 'auto'
/** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */
export const FULL_ACCESS_LABELS = ['完全权限', 'Full access']
/** 纯判定:一段选项文字是否就是「完全权限」选项(标签打头,或恰好相等)。 */
export function isFullAccessLabel(text: unknown): boolean {
if (typeof text !== 'string') return false
const trimmed = text.trim()
return FULL_ACCESS_LABELS.some((label) => trimmed === label || trimmed.startsWith(label))
}
/** 纯判定:这个会话现在是否应该被切到自动审查。 */
export function shouldAutoSwitch(preset: string | undefined | null, alreadyHandled: boolean): boolean {
return preset !== undefined && preset !== null && preset !== AUTO_REVIEW_PRESET && !alreadyHandled
}
interface LiveSession {
id: string
live: unknown
}
/**
* 防御式枚举宿主的 live 会话:优先 keys()+binding(),退回 list()。
* 服务形状对不上时安静返回空数组,绝不抛错。
*/
export function liveSessions(sessions: any): LiveSession[] {
const out: LiveSession[] = []
if (!sessions || typeof sessions !== 'object') return out
try {
if (typeof sessions.keys === 'function' && typeof sessions.binding === 'function') {
for (const id of sessions.keys()) {
const live = sessions.binding(id)?.session
if (live) out.push({ id, live })
}
return out
}
if (typeof sessions.list === 'function') {
for (const session of (sessions.list() ?? []) as any[]) {
if (session && session.sessionId) out.push({ id: session.sessionId, live: session })
}
}
} catch {
// 服务形状不同:放弃枚举
}
return out
}
/** 读会话当前的权限预设值(投影不可用时返回 undefined)。 */
export function currentPreset(live: any): string | undefined {
try {
return live?.projections?.faceOf('permissions')?.getSnapshot?.()
} catch {
return undefined
}
}
/**
* 把「完全权限」选项从当前文档里摘掉:原生 select 的 option、弹出
* 选择器(role=listbox)与菜单(role=menu)里的 option/menuitem。
* @returns 摘掉的个数
*/
export function pruneFullAccess(doc: Document): number {
let removed = 0
for (const option of doc.querySelectorAll('option')) {
if (isFullAccessLabel(option.textContent)) {
option.remove()
removed++
}
}
for (const item of doc.querySelectorAll('[role="listbox"] [role="option"], [role="menu"] [role="menuitem"]')) {
if (isFullAccessLabel(item.textContent)) {
item.remove()
removed++
}
}
return removed
}
export interface PolicyTimers {
setTimeout: (fn: () => void, ms: number) => number
clearTimeout: (id: number) => void
}
/**
* 安装权限 UI 策略:只观察 DOM、摘掉「完全权限」选项。
* 不接收 getSessions,也不启动任何会话轮询。
* @returns 卸载函数
*/
export function installPermissionPolicy(
doc: Document,
_getSessions?: unknown,
timers: PolicyTimers = {
setTimeout: (fn, ms) => setTimeout(fn, ms) as unknown as number,
clearTimeout: (id) => clearTimeout(id),
},
): () => void {
let disposed = false
let scanTimer = 0
const scheduleScan = (): void => {
if (disposed || scanTimer) return
scanTimer = timers.setTimeout(() => {
scanTimer = 0
if (!disposed) pruneFullAccess(doc)
}, 120)
}
const observer = new MutationObserver(scheduleScan)
if (doc.body) observer.observe(doc.body, { childList: true, subtree: true })
pruneFullAccess(doc)
return () => {
disposed = true
observer.disconnect()
if (scanTimer) timers.clearTimeout(scanTimer)
}
}

View File

@ -0,0 +1,190 @@
/**
* 功能三:插件商店「更新」按钮。
*
* DSH 只给官方插件原地更新;从自定义索引装的插件在发现页只有「有新版本」
* 标签、没有按钮。这里补一个真按钮:数据与动作都走宿主自己的远程服务
* ——pluginMarket 查索引和安装状态,pluginManager.installBundle 按索引
* 给出的精确 spec 覆盖安装——与官方安装流程同一套接口,不模拟点击、
* 不动官方状态。
*
* 服务经子插件声明 inject 取用:主插件保持自己的 inject,商店功能不
* 依赖这些服务;未启用实验性插件索引时子插件不生效,本功能静默关闭。
*/
const UPDATE_LABELS = ['有新版本', 'Update available']
export interface StoreUpdate {
name: string
title: string
installedVersion: string
version: string
spec: string
registry?: string
}
/** 索引条目的本地化标题在当前语言下的文本(与发现页行内展示一致)。 */
export function localizedTitle(title: unknown, lang: string): string {
if (typeof title === 'string') return title
if (!title || typeof title !== 'object') return ''
const record = title as Record<string, unknown>
const chain = [lang, lang && lang.split('-')[0], 'zh-CN', 'en']
for (const key of chain) {
if (key && typeof record[key] === 'string' && record[key]) return record[key] as string
}
const values = Object.values(record)
return typeof values[0] === 'string' ? (values[0] as string) : ''
}
/** 从各索引的搜索结果里挑出「有新版本」的条目,整理成可执行的更新计划。 */
export function pickUpdates(searchResults: any[], lang: string): StoreUpdate[] {
const updates: StoreUpdate[] = []
for (const result of searchResults ?? []) {
const entries = result?.value?.entries ?? result?.entries ?? []
for (const entry of entries as any[]) {
if (entry?.installation?.status !== 'update-available') continue
const versions = entry.versions ?? []
const version = versions.find((candidate: any) => candidate.version === entry.defaultVersion) ?? versions[0]
const spec = version?.install?.spec
if (!entry.name || !version?.version || !spec) continue
updates.push({
name: entry.name,
title: localizedTitle(entry.title, lang) || entry.name,
installedVersion: entry.installation.installedVersion ?? '',
version: version.version,
spec,
registry: version.install.registry,
})
}
}
return updates
}
/** 执行一次更新:按索引 spec 覆盖安装,宿主结果信封原样返回。 */
export async function runUpdate(remote: any, update: StoreUpdate, makeRequestId?: () => string | undefined): Promise<any> {
const requestId = makeRequestId ? makeRequestId() : 'better-chat-update-' + Date.now()
return remote.pluginManager.installBundle(update.spec, {
enabled: true,
requestId,
...(update.registry ? { registry: update.registry } : {}),
})
}
/**
* 发现页里某个插件的行:状态标签本身是个按钮,从它向上找第一个
* 同时包含插件标题、且文本总量还像一行的祖先。
*/
export function findUpdateRow(doc: Document, title: string): Element | null {
for (const element of doc.querySelectorAll('button')) {
if (!UPDATE_LABELS.includes(element.textContent?.trim() ?? '')) continue
let node: Element | null = element
for (let depth = 0; depth < 6 && node; depth++) {
node = node.parentElement
if (node && node.textContent?.includes(title) && node.textContent.length < 600) return node
}
}
return null
}
/** 更新按钮的点击处理:确认 → 调宿主覆盖安装 → 按结果改按钮文案。 */
export function makeUpdateClickHandler(
doc: Document,
getRemote: () => any,
update: StoreUpdate,
button: HTMLButtonElement,
): (event?: Event) => Promise<void> {
return async (event?: Event): Promise<void> => {
event?.preventDefault?.()
event?.stopPropagation?.()
const view = doc.defaultView as (Window & typeof globalThis) | null
const ask = view?.confirm ?? (globalThis as any).confirm
const message = '更新「' + update.title + '」'
+ (update.installedVersion ? ' ' + update.installedVersion : '')
+ ' → ' + update.version + '?\n会直接覆盖安装新版,插件数据保留。'
if (ask && !ask.call(view ?? globalThis, message)) return
button.disabled = true
button.textContent = '更新中…'
try {
const result = await runUpdate(getRemote(), update, () => (globalThis as any).crypto?.randomUUID?.() ?? undefined)
if (result?.value?.application === 'applied') {
button.textContent = '已更新,重启 DSH 后生效'
} else {
console.error('[dsh-better-chat] update failed for', update.name, result?.value?.error ?? result)
button.disabled = false
button.textContent = '更新失败,点此重试'
}
} catch (error) {
console.error('[dsh-better-chat] update failed for', update.name, error)
button.disabled = false
button.textContent = '更新失败,点此重试'
}
}
}
export interface StoreTimers {
setInterval: (fn: () => void, ms: number) => number
clearInterval: (id: number) => void
}
/** 发现页增强:轮询索引状态,把「更新」按钮挂到有新版本的行上。 */
export function installStoreUpdateButtons(
doc: Document,
getRemote: () => any,
timers: StoreTimers = {
setInterval: (fn, ms) => setInterval(fn, ms) as unknown as number,
clearInterval: (id) => clearInterval(id),
},
): () => void {
let disposed = false
let updates: StoreUpdate[] = []
const decorate = (): void => {
for (const update of updates) {
const row = findUpdateRow(doc, update.title)
if (!row || row.querySelector('[data-better-chat-update]')) continue
const button = doc.createElement('button')
button.type = 'button'
button.setAttribute('data-better-chat-update', update.name)
button.textContent = '更新到 ' + update.version
button.style.cssText = 'flex:none;margin-left:8px;padding:2px 10px;border:1px solid #7f7f7f55;border-radius:999px;background:transparent;color:inherit;font-size:12px;cursor:pointer'
button.addEventListener('click', makeUpdateClickHandler(doc, getRemote, update, button))
row.appendChild(button)
}
}
const refresh = async (): Promise<void> => {
try {
const remote = getRemote()
if (!remote?.pluginMarket || !remote?.pluginManager) return
const indexes = await remote.pluginMarket.listIndexes()
const urls = (indexes?.value ?? indexes ?? []).map((entry: any) => entry?.url).filter(Boolean)
const results: any[] = []
for (const url of urls) {
results.push(await remote.pluginMarket.search(url, { sort: { kind: 'index' }, offset: 0, limit: 100 }))
}
if (disposed) return
updates = pickUpdates(results, doc.documentElement?.lang || 'zh-CN')
decorate()
} catch {
// 索引服务不可用(未启用实验性插件索引等):静默关闭本功能。
}
}
const observer = new MutationObserver(() => decorate())
observer.observe(doc.documentElement, { childList: true, subtree: true })
const timer = timers.setInterval(() => { void refresh() }, 30000)
void refresh()
return () => {
disposed = true
observer.disconnect()
timers.clearInterval(timer)
}
}
/** 商店更新子插件:单独声明远程服务 inject,与主功能互相隔离。 */
export const storeUpdatePlugin = {
name: 'dsh-better-chat-store-update',
inject: ['remote', 'remote.pluginMarket', 'remote.pluginManager'],
apply(childCtx: any): void {
childCtx.effect(
() => installStoreUpdateButtons(document, () => childCtx.remote),
'dsh-better-chat: store update buttons',
)
},
}

View File

@ -0,0 +1,28 @@
/**
* Whether the host composer seat stays usable for the view that is on screen.
*
* Harness 0.2.1-rc.5 always mounts `[data-composer-seat]` beside the active
* conversation view (`ConversationContent`). `dsh-claude-style` 0.19.x then
* sets `data-dsh-claude-composer-hidden` on that conversation root whenever
* the first tab (对话 / `chat`) is not selected, and hides the seat with
* `display: none !important`. Reader is the only view this package mounts, so
* the restore rule in `Reader.module.css` matches only while 阅读 is showing.
* 轨迹 and other tabs keep the skin's own choice.
*/
export function hostComposerUsable(input: {
/** The skin has marked this conversation root hidden. */
skinHidesSeat: boolean;
/** The reader root is mounted. The host renders only the active view. */
readerMounted: boolean;
}): boolean {
if (!input.skinHidesSeat) return true;
return input.readerMounted;
}
/**
* Beats the skin rule
* `body[data-dsh-claude-style][data-dsh-claude-composer-active] [data-dsh-claude-composer-hidden] [data-composer-seat]`
* and only while `[data-dsh-better-display]` is under that root.
*/
export const READER_COMPOSER_RESTORE =
'html body[data-dsh-claude-style][data-dsh-claude-composer-active] [data-dsh-claude-composer-hidden]:has([data-dsh-better-display]) [data-composer-seat]';

View File

@ -0,0 +1,28 @@
/**
* Conversation-column scroll helpers. Official ChatView lands Turns by writing
* the enclosing `[data-conversation-scroll]` box; `Element.scrollIntoView`
* also walks ancestor scrollers and can lift the sticky composer off the
* bottom of the viewport (rail jump to top, then to bottom).
*/
/** Reading-line offset used by ui-chat ChatView.landOnRow. */
export const READING_LINE_OFFSET_PX = 24;
/** Active column host when present; otherwise the view-local scroller. */
export function scrollerOf(from: HTMLElement): HTMLElement {
return from.closest('[data-conversation-scroll]') ?? from;
}
/** Row position in scrollport coordinates (viewport-independent). */
export function flowTop(row: HTMLElement, scrollport: HTMLElement): number {
return row.getBoundingClientRect().top - scrollport.getBoundingClientRect().top;
}
/**
* Place `row` on the conversation scroller only. Never calls scrollIntoView.
* @param row - a rendered `[data-reader-turn]` row.
* @param scrollport - `scrollerOf` of the reader root.
*/
export function landTurn(row: HTMLElement, scrollport: HTMLElement, offsetPx = READING_LINE_OFFSET_PX): void {
scrollport.scrollTop += flowTop(row, scrollport) - offsetPx;
}

123
src/client/deliverables.ts Normal file
View File

@ -0,0 +1,123 @@
import type { TurnLocation } from '@deepseek-ai/dsh-client-ui-conversation/client';
import type { MarkdownFileMentions } from '@deepseek-ai/dsh-client-ui-primitives';
import type { ReaderFlowEntry } from './tool-activity.js';
import { inputFields, stringValue, toolIdentity } from './tool-activity.js';
interface ProducedEntry {
readonly seq?: number;
readonly path: string;
}
interface DeliverablesData {
readonly produced: readonly ProducedEntry[];
}
/** Extract standard filename without directory components. */
export function basename(path: string): string {
const normalized = path.replace(/[/\\]+$/, '');
const at = Math.max(normalized.lastIndexOf('/'), normalized.lastIndexOf('\\'));
return at === -1 ? normalized : normalized.slice(at + 1);
}
/** Extract parent directory of a path (or '.' if top-level). */
export function dirname(path: string): string {
const normalized = path.replace(/[/\\]+$/, '');
const at = Math.max(normalized.lastIndexOf('/'), normalized.lastIndexOf('\\'));
if (at === 0 || (at === 2 && /^[A-Za-z]:/.test(normalized))) return normalized.slice(0, at + 1);
return at === -1 ? '.' : normalized.slice(0, at) || '.';
}
/**
* The produced-files chip row waits for turn close. Live writes still
* accumulate, but the row must not interrupt an in-progress process.
*/
export function showDeliverablesRow(status: 'open' | 'closed' | 'unknown', paths: readonly string[]): boolean {
return status === 'closed' && paths.length > 0
}
/**
* Extract all unique file paths produced/modified in one turn.
* Respects official deliverables data when available, and falls back to
* inspecting successful write/edit tool invocations in the turn flow.
*/
export function getTurnDeliverables(turn: TurnLocation | undefined, flow?: readonly ReaderFlowEntry[]): readonly string[] {
const paths: string[] = [];
const seen = new Set<string>();
// 1. Check official deliverables turn data from @deepseek-ai/dsh-client-ui-deliverables
const deliverables = (turn?.data as { get(key: string): unknown } | undefined)?.get('deliverables') as DeliverablesData | undefined;
if (deliverables?.produced && Array.isArray(deliverables.produced)) {
for (const item of deliverables.produced) {
if (typeof item?.path === 'string' && item.path.trim().length > 0) {
const clean = item.path.trim();
if (!seen.has(clean)) {
seen.add(clean);
paths.push(clean);
}
}
}
}
if (paths.length > 0) return paths;
// 2. Fallback: inspect successful file modification tool calls in the flow
if (flow) {
for (const item of flow) {
if (item.kind !== 'tool' || !item.block) continue;
// Skip failed tool results
if ('isError' in item.block && item.block.isError) continue;
const { name, raw } = toolIdentity(item);
const toolName = name !== '工具调用' ? name : ((item.block as unknown as { name?: string }).name || (item.block as unknown as { call?: { name?: string } }).call?.name);
const toolRaw = raw || ((item.block as unknown as { argsRaw?: string }).argsRaw || (item.block as unknown as { call?: { argsRaw?: string } }).call?.argsRaw || '');
if (toolName === 'write' || toolName === 'edit' || toolName === 'apply_patch') {
const args = inputFields(toolRaw);
const target = stringValue(args, 'file_path', 'path', 'filename', 'filePath');
if (target && !seen.has(target)) {
seen.add(target);
paths.push(target);
}
} else if (toolName === 'str_replace_editor') {
const args = inputFields(toolRaw);
const cmd = stringValue(args, 'command');
if (cmd === 'create' || cmd === 'str_replace' || cmd === 'insert') {
const target = stringValue(args, 'path');
if (target && !seen.has(target)) {
seen.add(target);
paths.push(target);
}
}
}
}
}
return paths;
}
/** The single produced path whose basename is exactly value, or undefined. */
function onlyPathWithBasename(paths: readonly string[], value: string): string | undefined {
const matches = paths.filter(path => basename(path) === value);
return matches.length === 1 ? matches[0] : undefined;
}
/**
* File-mention resolver: converts inline-code tokens matching produced paths
* into clickable file references that open the corresponding file on the host.
*/
export function createProducedFileMentions(
paths: readonly string[],
openFile: (path: string) => void,
): MarkdownFileMentions {
return {
resolve(value: string) {
if (!value || value.includes('\n')) return undefined;
const clean = value.trim();
const path = paths.includes(clean) ? clean : onlyPathWithBasename(paths, clean);
if (path === undefined) return undefined;
return {
open: () => { openFile(path); },
label: `打开 ${path}`,
title: path,
};
},
};
}

View File

@ -0,0 +1,20 @@
/** Select the reading view on entry, without fighting a later explicit tab choice. */
export class ReaderEntryPolicy {
private entered = false;
constructor(private readonly requested: boolean, private readonly consumeRequest: () => void = () => {}) {}
select(view: string | null | undefined): 'reader' | null {
const requested = !this.entered && this.requested;
if (!this.entered) {
this.entered = true;
if (this.requested) this.consumeRequest();
}
return (requested || view == null) && view !== 'reader' ? 'reader' : null;
}
}
export function readerEntryRequested(search: string): boolean {
const value = new URLSearchParams(search).get('reader');
return value === '1' || /^0\.1\.0-trial\.\d+$/.test(value ?? '');
}

40
src/client/entry.tsx Normal file
View File

@ -0,0 +1,40 @@
import { useLayoutEffect } from 'react';
import type { Context } from '@deepseek-ai/cordis';
import type { ConversationStore } from '@deepseek-ai/dsh-client-ui-conversation/client';
import type { PropsRuntime, PropsStore, StoreDecl } from '@deepseek-ai/dsh-client-ui-slots';
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client';
import { ReaderEntryPolicy, readerEntryRequested } from './entry-policy.js';
function isConversationStore(store: StoreDecl | undefined): store is ConversationStore {
return typeof store === 'object' && store !== null
&& store.spec.persist === 'dsh.conversation'
&& typeof store.spec.actions.setView === 'function';
}
type EntryProps = PropsRuntime<'conversation.input.dock'> & PropsStore<ConversationStore> & { policy: ReaderEntryPolicy };
function ReaderEntry({ useStore, actions, policy }: EntryProps) {
const view = useStore(state => state.view);
useLayoutEffect(() => {
const next = policy.select(view);
if (next) actions.setView(next);
}, [view, actions, policy]);
return null;
}
/** Reuse the native store handle; its framework-owned instance preserves drafts. */
export function installReaderEntry(ctx: Context): () => void {
const native = ctx.slots.entriesOfSlot('conversation.session')[0]?.store;
if (!isConversationStore(native)) throw new Error('DSH Reader cannot bind the native conversation view store.');
const policy = new ReaderEntryPolicy(readerEntryRequested(location.search), () => {
const url = new URL(location.href);
url.searchParams.delete('reader');
history.replaceState(history.state, '', `${url.pathname}${url.search}${url.hash}`);
});
return ctx.slots.register({
name: 'conversation.input.dock',
id: 'dsh-better-display-entry',
store: native,
inject: () => ({ policy }),
}, ReaderEntry);
}

View File

@ -0,0 +1,55 @@
import type { LiveStep, LiveTurnItem } from './live-turn.js';
/** Presentation clock, not model/network time. */
export const FOLD_TIMING = {
collapse: 320,
count: 160,
settle: 80,
reveal: 180,
/**
* Slack added to every phase deadline before the watchdog forces the next phase.
*
* The choreography advances on animation promises and rendered frames. Both are
* best-effort: a cancelled animation *rejects* and a compositor that never
* finishes one leaves its promise pending, while a backgrounded tab stops
* delivering frames. Without a deadline the machine would sit in a non-idle
* phase forever, and a non-idle phase freezes both the frame source and the text
* reveal, so the turn would look stuck until a remount. This is the liveness
* guarantee that does not depend on any of them.
*/
watchdogSlack: 240,
} as const;
export type FoldPhase = 'idle' | 'collapse' | 'count' | 'settle' | 'reveal';
export type FlowRow =
| { kind: 'summary'; key: string; item: Extract<LiveTurnItem, { kind: 'fold' }> }
| { kind: 'step'; key: string; step: LiveStep; foldKey?: string };
/** A step always has the same parent and React key, even when its membership changes. */
export function flowRows(items: readonly LiveTurnItem[]): FlowRow[] {
return items.flatMap((item): FlowRow[] => item.kind === 'fold'
? [{ kind: 'summary', key: item.key, item }, ...item.steps.map(step => ({ kind: 'step' as const, key: step.key, step, foldKey: item.key }))]
: [{ kind: 'step', key: item.key, step: item.step }]);
}
export function retiringKeys(before: readonly LiveTurnItem[], after: readonly LiveTurnItem[], open: Readonly<Record<string, boolean>>): string[] {
const folded = new Set(flowRows(after).filter(row => row.kind === 'step' && row.foldKey && !open[row.foldKey]).map(row => row.key));
return flowRows(before).filter(row => row.kind === 'step' && !row.foldKey && folded.has(row.key)).map(row => row.key);
}
/** Insert only new summary slots. Never admit incoming content during shrink. */
export function collapseRows(before: readonly LiveTurnItem[], target: readonly LiveTurnItem[]): FlowRow[] {
const rows = flowRows(before);
const headers = new Set(rows.filter(row => row.kind === 'summary').map(row => row.key));
for (const item of target) {
if (item.kind !== 'fold' || headers.has(item.key)) continue;
const members = new Set(item.steps.map(step => step.key));
const at = rows.findIndex(row => members.has(row.key));
if (at >= 0) rows.splice(at, 0, { kind: 'summary', key: item.key, item: { ...item, summary: item.summary.replace(/\d+/g, '0') } });
}
return rows;
}
export function containsNewUser(before: readonly LiveTurnItem[], after: readonly LiveTurnItem[]): boolean {
const users = new Set(before.filter(item => item.kind === 'user').map(item => item.key));
return after.some(item => item.kind === 'user' && !users.has(item.key));
}

View File

@ -0,0 +1,28 @@
/** Three-stop fold intensity persisted on `dsh.reader.v1`. Default is standard. */
export type FoldIntensity = 0 | 1 | 2;
export const FOLD_INTENSITY_DEFAULT: FoldIntensity = 1;
/** Level 0: nothing auto-folds. Level 1: current-main choreography. Level 2: process summaries. */
export function foldIntensityOf(state: unknown): FoldIntensity {
const rec = state && typeof state === 'object' ? state as Record<string, unknown> : {};
if (rec.foldIntensity === 0 || rec.foldIntensity === 1 || rec.foldIntensity === 2) return rec.foldIntensity;
if (rec.processOnly === true) return 2;
if (rec.autoFold === false) return 0;
return FOLD_INTENSITY_DEFAULT;
}
export function frostedGlassOf(state: unknown): boolean {
if (state && typeof state === 'object' && 'frostedGlass' in state) {
return (state as { frostedGlass?: unknown }).frostedGlass === true;
}
return state === true;
}
export function autoFoldFromIntensity(intensity: FoldIntensity): boolean {
return intensity !== 0;
}
export function processOnlyFromIntensity(intensity: FoldIntensity): boolean {
return intensity === 2;
}

45
src/client/index.tsx Normal file
View File

@ -0,0 +1,45 @@
/**
* dsh-better-chat 客户端入口(合并后)。
*
* 两个半场共用一个 client 产物:
* - 阅读视图(原 dsh-better-display):reader-plugin.tsx 及其整棵 React 源码树;
* - 聊天增强(原 dsh-better-chat):审批键盘、权限 UI、商店更新按钮。
*
* 入口必须导出一个静态字符串 inject 数组(宿主 Cordis 服务注入),
* 并在这里统一 apply。
*/
import type { Context } from '@deepseek-ai/cordis'
import { install as installApprovalKeys } from './chat/approval-keys.js'
import { installPermissionPolicy } from './chat/permission-policy.js'
import { storeUpdatePlugin } from './chat/store-update.js'
import { apply as applyReader, name as readerName } from './reader-plugin.js'
export const name = 'dsh-better-chat'
/** 阅读视图所需的宿主客户端服务;聊天增强不额外依赖服务。 */
export const inject = [
'slots',
'sessions',
'conversation',
'uiConversation',
'remote',
'remote.session',
]
export function apply(ctx: Context): void {
// 聊天增强:纯 DOM 观察,不依赖任何宿主服务。
ctx.effect(() => installApprovalKeys(document), 'dsh-better-chat: approval enter/esc routing')
ctx.effect(
() => installPermissionPolicy(document),
'dsh-better-chat: permission policy (no full access)',
)
try {
ctx.plugin(storeUpdatePlugin as any)
} catch {
// 子插件挂不上(旧宿主等)不影响主功能。
}
// 阅读视图:注册 slots、设置页与文本变换服务。
applyReader(ctx)
void readerName
}

229
src/client/live-turn.ts Normal file
View File

@ -0,0 +1,229 @@
import type { AssistantChatData, ChatConversationViewNode } from '@deepseek-ai/dsh-client-ui-chat/client';
import type { AssistantBlock } from '@deepseek-ai/dsh-client-ui-conversation/client';
import { assistantSegments, hasVisibleBody } from './projection.js';
import type { TurnBoundary } from './projection.js';
import type { ReaderFlowEntry, ToolActivityEntry } from './tool-activity.js';
export type LiveStep =
| { kind: 'reasoning'; key: string; nodeKey: string; start: number; blocks: AssistantBlock[]; step: number }
| { kind: 'body'; key: string; nodeKey: string; start: number; blocks: AssistantBlock[]; step: number }
| { kind: 'tool'; key: string; entry: ToolActivityEntry }
| { kind: 'user'; key: string; nodeKey: string }
| { kind: 'other'; key: string; nodeKey: string };
export type LiveTurnItem =
| { kind: 'user'; key: string; step: Extract<LiveStep, { kind: 'user' }> }
| { kind: 'fold'; key: string; steps: readonly LiveStep[]; summary: string }
| { kind: 'open'; key: string; step: LiveStep };
export function liveFoldEnabled(boundary: TurnBoundary): boolean {
return boundary.status === 'open';
}
export function foldSummary(steps: readonly LiveStep[]): string {
let reasoning = 0;
let body = 0;
let tool = 0;
let extra = 0;
for (const step of steps) {
if (step.kind === 'reasoning') reasoning += 1;
else if (step.kind === 'body') body += 1;
else if (step.kind === 'tool') tool += 1;
else if (step.kind !== 'user') extra += 1;
}
const parts: string[] = [];
if (reasoning) parts.push(`思考×${reasoning}`);
if (body) parts.push(`输出×${body}`);
if (tool) parts.push(`工具×${tool}`);
if (extra) parts.push(`记录×${extra}`);
return parts.join(' · ') || '此前步骤';
}
function skipReasoning(part: { kind: string; blocks: AssistantBlock[] }): boolean {
return part.kind === 'reasoning' && !part.blocks.some(block => block.kind === 'reasoning' && block.text.trim() !== '');
}
function skipBody(part: { kind: string; blocks: AssistantBlock[] }): boolean {
return part.kind === 'body' && !hasVisibleBody(part.blocks);
}
function stepsFromAssistant(
nodeKey: string,
data: AssistantChatData,
toolsByCallId: Map<string, ToolActivityEntry>,
consumed: Set<string>,
): LiveStep[] {
const marks: { at: number; step: LiveStep }[] = [];
for (const part of assistantSegments(data.blocks)) {
if (skipReasoning(part) || skipBody(part)) continue;
marks.push({
at: part.start,
step: {
kind: part.kind,
key: `${nodeKey}:${part.kind}:${part.start}`,
nodeKey,
start: part.start,
blocks: part.blocks,
step: data.step,
},
});
}
data.blocks.forEach((block, index) => {
if (block.kind !== 'tool-call' || !block.callId) return;
const tool = toolsByCallId.get(block.callId);
if (!tool || consumed.has(tool.callId)) return;
consumed.add(tool.callId);
marks.push({ at: index, step: { kind: 'tool', key: tool.key, entry: tool } });
});
marks.sort((left, right) => left.at - right.at || left.step.key.localeCompare(right.step.key));
return marks.map(mark => mark.step);
}
/** Expand readerFlow into source-ordered live steps using existing block boundaries. */
export function segmentLiveTurn(
flow: readonly ReaderFlowEntry[],
get: (key: string) => ChatConversationViewNode | undefined,
): LiveStep[] {
const steps: LiveStep[] = [];
const consumed = new Set<string>();
const toolsByCallId = new Map<string, ToolActivityEntry>();
for (const entry of flow) {
if (entry.kind === 'tool') toolsByCallId.set(entry.callId, entry);
}
for (const entry of flow) {
if (entry.kind === 'tool') {
if (!consumed.has(entry.callId)) {
steps.push({ kind: 'tool', key: entry.key, entry });
consumed.add(entry.callId);
}
continue;
}
const node = get(entry.nodeKey);
if (!node || node.visibility === 'hidden' || node.kind === 'turn-tail') continue;
if (node.kind === 'user' || node.kind === 'steering') {
steps.push({ kind: 'user', key: entry.key, nodeKey: entry.nodeKey });
continue;
}
if (node.kind === 'assistant-step') {
steps.push(...stepsFromAssistant(entry.nodeKey, node.data as AssistantChatData, toolsByCallId, consumed));
continue;
}
steps.push({ kind: 'other', key: entry.key, nodeKey: entry.nodeKey });
}
return steps;
}
/** Only a run that contains real thinking/tool work is worth folding. */
function foldableRun(run: readonly LiveStep[]): boolean {
return run.some(step => step.kind === 'reasoning' || step.kind === 'tool');
}
/**
* One live chain: narration stays visible, while every earlier reasoning/tool
* run collapses into its own box at its original position.
*/
export function presentLiveTurn(steps: readonly LiveStep[], boundary: TurnBoundary, autoFold = true): LiveTurnItem[] {
const live = autoFold && liveFoldEnabled(boundary);
const items: LiveTurnItem[] = [];
const open = (step: LiveStep) => items.push({ kind: 'open', key: step.key, step });
const fold = (run: readonly LiveStep[]) => {
if (!run.length) return;
if (live && foldableRun(run)) {
items.push({ kind: 'fold', key: `live-fold:${run[0]!.key}`, steps: run, summary: foldSummary(run) });
} else {
for (const step of run) open(step);
}
};
let run: LiveStep[] = [];
const flush = () => { fold(run); run = []; };
// A user insert resets the chain: steps before it are never folded by
// reasoning after it. Split into user-delimited segments and walk each one.
const segments: LiveStep[][] = [];
let segment: LiveStep[] = [];
for (const step of steps) {
if (step.kind === 'user') {
segments.push(segment); segments.push([step]); segment = [];
} else {
segment.push(step);
}
}
segments.push(segment);
for (const part of segments) {
if (!part.length) continue;
const first = part[0]!;
if (part.length === 1 && first.kind === 'user') {
items.push({ kind: 'user', key: first.key, step: first });
continue;
}
if (!live) {
for (const step of part) open(step);
continue;
}
// Narration is never folded. Once a later reasoning step exists, every
// reasoning/tool run before it folds at its own position, so the latest
// thinking and everything after it stay open while earlier steps collapse —
// even across narration blocks, which the reader still renders in place.
const lastReasoning = part.findLastIndex(step => step.kind === 'reasoning');
if (lastReasoning <= 0) {
for (const step of part) open(step);
continue;
}
for (let index = 0; index < part.length; index++) {
const step = part[index]!;
if (index < lastReasoning) {
if (step.kind === 'body') { flush(); open(step); }
else run.push(step);
} else {
if (index === lastReasoning) flush();
open(step);
}
}
flush();
}
return items;
}
/**
* Summaries for collapsed process that sits between two narration blocks.
*
* A live-fold cell already shows that summary while the turn is open. Drawing
* the seam as well repeats the same counts, so a run whose every step is
* already inside a fold cell contributes neither a seam nor `after`. `after`
* is what marks the previous body with `data-reader-seam-after` and drops its
* bottom padding; skipping the seam must leave that spacing alone.
*/
export function planProcessSeams(
steps: readonly LiveStep[],
liveItems: readonly LiveTurnItem[],
expanded: boolean,
): { before: Map<string, string>; after: Set<string> } {
const before = new Map<string, string>();
const after = new Set<string>();
if (expanded) return { before, after };
const liveFolded = new Set(
liveItems.flatMap(item => item.kind === 'fold' ? item.steps.map(step => step.key) : []),
);
let previousBody: Extract<LiveStep, { kind: 'body' }> | undefined;
let process: LiveStep[] = [];
for (const step of steps) {
if (step.kind === 'body') {
const folded = process.filter(item => item.kind !== 'user');
const coveredByLiveFold = folded.length > 0 && folded.every(item => liveFolded.has(item.key));
if (!coveredByLiveFold && previousBody
&& folded.some(item => item.kind === 'reasoning' || item.kind === 'tool' || item.kind === 'other')) {
before.set(step.key, foldSummary(folded));
after.add(previousBody.key);
}
previousBody = step;
process = [];
} else if (step.kind === 'user') {
previousBody = undefined;
process = [];
} else {
process.push(step);
}
}
return { before, after };
}

View File

@ -0,0 +1,304 @@
/* Visual baseline: deepsuite `@deepseek/md` markdown.css, adapted to CSS
Modules. Cite pills, header anchors, and thinking-small variants are
intentionally absent (no matching DOM). Token names match that sheet. */
.markdown {
min-width: 0;
overflow-wrap: anywhere;
font: var(--dsw-font-markdown-base);
color: var(--dsw-alias-label-primary);
}
.markdown strong {
font-weight: 600;
}
.markdown h1 {
font: var(--dsw-font-markdown-h1);
margin: 32px 0 16px;
}
.markdown h2 {
font: var(--dsw-font-markdown-h2);
margin: 32px 0 16px;
}
.markdown h3 {
font: var(--dsw-font-markdown-h3);
margin: 32px 0 16px;
}
.markdown h4 {
font: var(--dsw-font-markdown-h4);
margin: 16px 0;
}
.markdown :where(h5, h6) {
font: var(--dsw-font-markdown-base-strong);
margin: 16px 0;
}
.markdown :where(h1, h2, h3, h4, h5, h6) strong {
font-weight: inherit;
}
.markdown p {
margin: 16px 0;
}
/* Tighten h4–h6 against a following list (design: 8px gap). */
.markdown :where(h4, h5, h6) + :where(ul, ol) {
margin-top: 8px;
}
.markdown :where(h4, h5, h6):has(+ :where(ul, ol)) {
margin-bottom: 8px;
}
.markdown a {
/* deepsuite markdown.css uses brand-text (blue in newDesign); this sheet
keeps design-platform brand-text as near-black, so links use the blue
business-primary alias instead. */
color: var(--dsw-alias-state-business-primary);
transition: box-shadow var(--ds-transition-duration) var(--ds-ease-in-out);
position: relative;
text-decoration: none;
/* Transparent hit-area padding; literal zero-alpha only (no painted color). */
border-left: 3px solid rgb(255 255 255 / 0);
border-right: 3px solid rgb(255 255 255 / 0);
border-top: 2px solid rgb(255 255 255 / 0);
border-bottom: 2px solid rgb(255 255 255 / 0);
margin-left: -3px;
margin-right: -3px;
}
.markdown a:hover,
.markdown a:focus {
outline: none;
text-decoration: underline var(--dsw-alias-state-business-primary);
}
.markdown a:focus-visible {
box-shadow: 0 0 0 2px var(--dsw-alias-state-business-primary);
}
.markdown :where(ul, ol) {
margin: 16px 0;
padding-left: 18px;
}
.markdown li:not(:first-child) {
margin-top: 6px;
}
.markdown li > :where(ul, ol) {
margin-top: 4px;
}
.markdown li::marker {
line-height: 28px;
color: var(--dsw-alias-label-secondary);
}
/* Nested ol under ul/ol: markers inside (models sometimes emit this shape). */
.markdown :where(ul, ol) ol {
list-style-position: inside;
padding-left: 0;
}
.markdown :where(ul, ol) ol li p {
display: inline;
}
.markdown li > p {
margin: 8px 0;
}
.markdown li > *:first-child {
margin-top: 0;
}
/* Keep list-nested code-block vertical margins (design: +4px vs other last children). */
.markdown li > *:last-child:not(:global(.md-code-block)) {
margin-bottom: 0;
}
.markdown hr {
display: block;
border: none;
height: 1px;
margin: 32px 0;
background: var(--dsw-alias-border-l2);
}
.markdown blockquote {
border-left: 2px solid var(--dsw-alias-label-caption);
margin: 16px 0 0;
padding-left: 14px;
}
.markdown pre {
margin: 16px 0;
font-family: var(--ds-font-family-code);
overflow: auto;
}
.markdown :not(pre) > code {
display: inline-flex;
align-items: center;
box-sizing: border-box;
font: var(--dsw-font-markdown-code);
font-family: var(--ds-font-family-code);
font-size: 0.875em !important;
background-color: var(--dsw-alias-markdown-inline-code);
border-radius: 6px;
padding: 0 5px;
}
.markdown :where(h1, h2, h3, h4, h5, h6) code {
font: inherit;
font-family: var(--ds-font-family-code);
}
.markdown :global(.katex-display) {
max-width: 100%;
overflow-x: auto;
overflow-y: hidden;
}
.markdown input[type='checkbox'] {
margin: 0 8px 0 0;
accent-color: var(--dsw-alias-label-secondary);
}
.tableScroll {
max-width: 100%;
overflow-x: auto;
overscroll-behavior-x: contain;
}
/* Wide tables reveal their horizontal bar on hover (or keyboard focus)
instead of keeping it painted. Chromium never repaints state-conditioned
scrollbar STYLES (neither hover-conditioned `::-webkit-scrollbar*` rules
nor a :hover `scrollbar-color` change reaches the painted bar), so the
toggle is `overflow-x` itself — a layout change repaints reliably. The
resting padding matches the themed bar's height, so on an overflowing
table the appearing bar exactly replaces it and nothing below shifts.
Wheel and trackpad scrolling need the pointer over the table, which is
already the hover that re-enables `auto`. */
.tableScroll:global(.md-table-wide) {
overflow-x: hidden;
padding-bottom: var(--dsh-scrollbar-width, 8px);
}
.tableScroll:global(.md-table-wide):hover,
.tableScroll:global(.md-table-wide):focus-visible {
overflow-x: auto;
padding-bottom: 0;
}
/* Chromium keyboard-focuses scrollable containers by default; the ring uses
the sheet's link focus color. */
.tableScroll:focus-visible {
outline: none;
box-shadow: 0 0 0 2px var(--dsw-alias-state-business-primary);
}
/* Many-column tables (the renderer's `md-table-wide` hook) keep their
natural width and scroll inside the wrapper; a hosting layout may widen
the wrapper through the hook (deepsuite chat TableWrapper parity). */
.tableScroll table {
border-collapse: collapse;
width: max-content;
max-width: max-content;
}
/* Tables under four columns, and any table inside a blockquote, fill the
column instead: cells wrap down to their minimum readable width, and the
wrapper's scroll only remains for the below-floor case (deepsuite chat
parity: `.wrapper:not(:has(th:nth-child(4), td:nth-child(4)))`). */
.tableFill table {
width: 100%;
max-width: none;
}
.tableScroll th {
text-align: start;
padding: 10px 16px;
border-bottom: 1px solid var(--dsw-alias-border-l3);
border-top: none;
font: var(--dsw-font-markdown-table-head);
max-width: 320px;
max-width: min(30vw, 320px);
min-width: 100px;
}
.tableScroll td {
padding: 10px 16px;
border-bottom: 1px solid var(--dsw-alias-border-l2);
font: var(--dsw-font-markdown-table);
max-width: 320px;
max-width: min(30vw, 320px);
min-width: 100px;
}
.tableScroll th:first-child,
.tableScroll td:first-child {
padding-left: 0;
}
.tableScroll td:last-child {
padding-right: 0;
}
.tableScroll table code {
font-size: 13px;
}
.markdown > *:first-child,
.markdown p:first-child {
margin-top: 0 !important;
}
.markdown > *:last-child,
.markdown p:last-child {
margin-bottom: 0 !important;
}
.imageAlt {
color: var(--dsw-alias-label-tertiary);
font-style: italic;
}
.image {
display: block;
width: auto;
max-width: 100%;
height: auto;
margin: 0;
border-radius: 8px;
background: var(--dsw-alias-bg-base);
object-fit: contain;
}
/* Inline file mention: the same link language this sheet gives anchors (and
thereby URL-promoted inline code) — link-blue at rest, underline only on
hover/focus. An underline at rest reads badly inside the code chip, where
it collides with monospace descenders and the pill background. */
.fileMention {
margin: 0;
padding: 0;
border: none;
background: none;
font: inherit;
color: var(--dsw-alias-state-business-primary);
text-decoration: none;
cursor: pointer;
}
.fileMention:hover,
.fileMention:focus {
outline: none;
text-decoration: underline var(--dsw-alias-state-business-primary);
text-underline-offset: 3px;
}

View File

@ -0,0 +1,195 @@
// Adapted from DeepSeek Harness b150a551b8d465e31e418e1b2eaf5e79bbb7d28e (MIT). See THIRD_PARTY_NOTICES.md.
/**
* Untrusted assistant-Markdown renderer over the direct mdast pipeline:
* `parse.ts` grammars, the incremental streaming parser, and `render.tsx`.
* While a message streams, all but the trailing two blocks freeze as cached
* React elements and only the source tail behind them re-parses per chunk,
* so per-chunk work tracks the tail size instead of the whole reply. Frozen
* blocks keep their source-offset keys when they cross the freeze boundary,
* so React reconciles instead of remounting. Known deviation while
* streaming: a reference-style link or footnote whose definition sits on the
* other side of the freeze boundary renders literally until the settled
* full parse self-heals it.
*/
import { memo, useMemo, useRef } from 'react'
import type { ReactNode } from 'react'
import type { MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives'
import { IncrementalMarkdownParser } from './incremental.js'
import { parseGfm, parseGfmWithMath } from './parse.js'
import {
collectReferenceTargets, createReferenceTargets, renderBlocks, renderFootnoteSection,
wrapBlockChildren,
} from './render.js'
import type { MarkdownCodeLabels, MarkdownFileMentions, MarkdownRenderContext, ReferenceTargets } from './render.js'
// KaTeX CSS is supplied once by the shared DSH UI-primitives client bundle.
import css from './MarkdownText.module.css'
export type { MarkdownCodeLabels, MarkdownFileMentions } from './render.js'
/** One settled full render: parse with math, resolve references, append the footnote section. */
function renderSettled(
text: string,
codeLabels: MarkdownCodeLabels | undefined,
fileMentions: MarkdownFileMentions | undefined,
pathImages: MarkdownPathImages | undefined,
renderText: MarkdownRenderContext['renderText'],
renderAtom: MarkdownRenderContext['renderAtom'],
): ReactNode[] {
const root = parseGfmWithMath(text)
const targets = createReferenceTargets()
collectReferenceTargets(root.children, targets)
const context: MarkdownRenderContext = {
renderText,
renderAtom,
streaming: false,
codeLabels,
fileMentions,
pathImages,
targets,
footnoteOrder: [],
footnoteCounts: new Map(),
}
const blocks = wrapBlockChildren(
renderBlocks(root.children.map((node, index) => ({ node, key: node.position?.start.offset ?? -(index + 1) })), context),
false,
)
const section = renderFootnoteSection(context)
return section === null ? blocks : [...blocks, '\n', section]
}
/**
* Streaming render state for one growing message: the incremental parser,
* the frozen blocks' cached elements, and the reference/footnote state their
* rendering consumed (footnote numbering assigned to frozen references is
* final, so the tail continues from a copy of it each frame).
*/
class StreamingRenderer {
private readonly parser = new IncrementalMarkdownParser(parseGfm)
private generation = -1
private frozenCount = 0
private frozenElements: ReactNode[] = []
private frozenTargets: ReferenceTargets = createReferenceTargets()
private frozenFootnoteOrder: string[] = []
private frozenFootnoteCounts = new Map<string, number>()
private lastText: string | null = null
private lastRendered: ReactNode[] = []
/** @param codeLabels - Fence copy labels baked into cached elements; the owner replaces the renderer when they change. */
constructor(private readonly codeLabels: MarkdownCodeLabels | undefined, private readonly renderText: MarkdownRenderContext['renderText'], private readonly renderAtom: MarkdownRenderContext['renderAtom'], private readonly pathImages: MarkdownPathImages | undefined) {}
/**
* Render the current accumulated text. Idempotent per text value, so React
* may re-execute the calling render freely.
* @param text - The full accumulated markdown source.
* @returns Frozen elements, re-rendered tail, and the footnote section.
*/
render(text: string): ReactNode[] {
if (text === this.lastText) return this.lastRendered
const { frozen, tail, generation } = this.parser.update(text)
if (generation !== this.generation) {
this.generation = generation
this.frozenCount = 0
this.frozenElements = []
this.frozenTargets = createReferenceTargets()
this.frozenFootnoteOrder = []
this.frozenFootnoteCounts = new Map()
}
const newlyFrozen = frozen.slice(this.frozenCount)
collectReferenceTargets(newlyFrozen.map(block => block.node), this.frozenTargets)
// Targets visible this frame: everything frozen so far plus the current
// tail parse — a newly frozen block's references resolved against the
// same parse tree its definitions came from.
const frameTargets: ReferenceTargets = {
definitions: new Map(this.frozenTargets.definitions),
footnotes: new Map(this.frozenTargets.footnotes),
}
collectReferenceTargets(tail.map(block => block.node), frameTargets)
if (newlyFrozen.length > 0) {
const frozenContext: MarkdownRenderContext = {
renderText: this.renderText,
renderAtom: this.renderAtom,
streaming: true,
codeLabels: this.codeLabels,
fileMentions: undefined,
pathImages: this.pathImages,
targets: frameTargets,
footnoteOrder: this.frozenFootnoteOrder,
footnoteCounts: this.frozenFootnoteCounts,
}
// Separator newlines are cached alongside the elements so the
// assembled children match the settled pipeline's block wrapping.
const batch = [...this.frozenElements]
for (const element of renderBlocks(newlyFrozen, frozenContext)) {
if (batch.length > 0) batch.push('\n')
batch.push(element)
}
this.frozenElements = batch
this.frozenCount = frozen.length
}
const tailContext: MarkdownRenderContext = {
renderText: this.renderText,
renderAtom: this.renderAtom,
streaming: true,
codeLabels: this.codeLabels,
fileMentions: undefined,
pathImages: this.pathImages,
targets: frameTargets,
footnoteOrder: [...this.frozenFootnoteOrder],
footnoteCounts: new Map(this.frozenFootnoteCounts),
}
const children = [...this.frozenElements]
for (const element of renderBlocks(tail, tailContext)) {
if (children.length > 0) children.push('\n')
children.push(element)
}
const section = renderFootnoteSection(tailContext)
if (section !== null) children.push('\n', section)
this.lastText = text
this.lastRendered = children
return this.lastRendered
}
}
/**
* Render untrusted assistant-authored Markdown as semantic React elements.
* @param props - Markdown source text preserved by the session projection;
* `streaming` renders fences and TeX plain (highlighting and KaTeX land on
* the finalize swap) and parses incrementally across chunks; `codeLabels`
* forwards localized copy-button labels to fence CodeBlocks — pass a
* reference-stable object (memoized per locale revision), because a new
* identity discards the streaming render cache mid-message. `fileMentions`
* links inline-code tokens its resolver recognizes as real files; this is
* the single streaming gate — it applies to settled renders only, because a
* streaming message's vocabulary is not final and frozen cached elements
* must not bake in handlers that could go stale.
* @returns A GFM document with TeX math rendered through KaTeX; raw HTML,
* relative links, and unsafe protocols are disabled, while absolute HTTP(S)
* images render directly.
*/
export const MarkdownText = memo(function MarkdownText({ text, streaming = false, codeLabels, fileMentions, pathImages, renderText, renderAtom }: {
text: string
streaming?: boolean
codeLabels?: MarkdownCodeLabels | undefined
fileMentions?: MarkdownFileMentions | undefined
pathImages?: MarkdownPathImages | undefined
renderText?: MarkdownRenderContext['renderText']
renderAtom?: MarkdownRenderContext['renderAtom']
}) {
const streamRef = useRef<StreamingRenderer | null>(null)
const streamImagesRef = useRef(pathImages)
const streamLabelsRef = useRef<MarkdownCodeLabels | undefined>(codeLabels)
const children = useMemo(() => {
if (!streaming) {
streamRef.current = null
return renderSettled(text, codeLabels, fileMentions, pathImages, renderText, renderAtom)
}
if (streamRef.current === null || streamLabelsRef.current !== codeLabels || streamImagesRef.current !== pathImages) {
streamRef.current = new StreamingRenderer(codeLabels, renderText, renderAtom, pathImages)
streamLabelsRef.current = codeLabels
streamImagesRef.current = pathImages
}
return streamRef.current.render(text)
}, [text, streaming, codeLabels, fileMentions, pathImages, renderText, renderAtom])
return <div className={css.markdown}>{children}</div>
})

View File

@ -0,0 +1,84 @@
// Adapted from DeepSeek Harness b150a551b8d465e31e418e1b2eaf5e79bbb7d28e (MIT). See THIRD_PARTY_NOTICES.md.
/** Let asterisk strong emphasis close after punctuation when CJK prose continues without whitespace. */
import { attention } from 'micromark-core-commonmark'
import { unicodePunctuation } from 'micromark-util-character'
import { classifyCharacter } from 'micromark-util-classify-character'
import { codes, constants } from 'micromark-util-symbol'
import type { Construct, Extension, State, Tokenizer } from 'micromark-util-types'
const cjkCharacter = new RegExp([
'\\p{Script_Extensions=Han}',
'\\p{Script_Extensions=Hiragana}',
'\\p{Script_Extensions=Katakana}',
'\\p{Script_Extensions=Hangul}',
'\\p{Script_Extensions=Bopomofo}',
].join('|'), 'u')
function isCjkCharacter(code: number | null): boolean {
return code !== null && code >= 0 && cjkCharacter.test(String.fromCodePoint(code))
}
const tokenizeCjkFriendlyAttention: Tokenizer = function (effects, ok, nok) {
const configuredAttentionMarkers = this.parser.constructs.attentionMarkers.null
if (configuredAttentionMarkers === undefined) {
throw new Error('micromark CommonMark attention markers are unavailable')
}
const attentionMarkers = configuredAttentionMarkers
const previous = this.previous
const before = classifyCharacter(previous)
let marker: number | null = codes.eof
return start
function start(code: number | null): State | undefined {
/* v8 ignore next -- this text construct is dispatched only for an asterisk. */
if (code !== codes.asterisk) return nok(code)
marker = code
effects.enter('attentionSequence')
return inside(code)
}
function inside(code: number | null): State | undefined {
if (code === marker) {
effects.consume(code)
return inside
}
const token = effects.exit('attentionSequence')
const after = classifyCharacter(code)
const open = !after || (after === constants.characterGroupPunctuation && Boolean(before))
|| attentionMarkers.includes(code)
const commonMarkClose = !before
|| (before === constants.characterGroupPunctuation && Boolean(after))
|| attentionMarkers.includes(previous)
const markerCount = token.end.offset - token.start.offset
const cjkStrongClose = markerCount >= 2
&& unicodePunctuation(previous)
&& isCjkCharacter(code)
const close = commonMarkClose || cjkStrongClose
token._open = open
token._close = close
return ok(code)
}
}
const cjkFriendlyAttention: Construct = {
name: 'cjkFriendlyAttention',
resolveAll: attention.resolveAll,
tokenize: tokenizeCjkFriendlyAttention,
}
const cjkFriendlyStrongExtension: Extension = {
text: { [codes.asterisk]: cjkFriendlyAttention },
}
/**
* Extend CommonMark asterisk strong emphasis for punctuation-delimited CJK
* prose, as a micromark syntax extension for `fromMarkdown`.
* @returns The micromark syntax extension.
*/
export function cjkFriendlyStrong(): Extension {
return cjkFriendlyStrongExtension
}

View File

@ -0,0 +1,131 @@
// Adapted from DeepSeek Harness b150a551b8d465e31e418e1b2eaf5e79bbb7d28e (MIT). See THIRD_PARTY_NOTICES.md.
/**
* Incremental block-level markdown parsing for an append-only text stream.
*
* Re-parsing the whole accumulated document on every streaming chunk is
* quadratic in the final reply length. CommonMark block parsing is line-based
* and appended text can only reshape the parse frontier — the last top-level
* block (a paragraph becoming a setext heading or a table, a list continuing
* after a blank line, an unclosed fence swallowing lines) — so earlier blocks
* are final. This parser therefore freezes all but the trailing
* {@link UNSTABLE_TAIL_BLOCKS} blocks and re-parses only the source tail
* behind them: each source region is parsed O(1) times over the stream
* instead of once per chunk.
*
* The freeze boundary comes from the parser's own `position` offsets, never
* from custom source scanning. The cut sits at the *end offset* of the last
* frozen block (not the next block's start): a following block's start offset
* excludes up to three spaces of insignificant leading indentation, which is
* harmless to drop, but cutting at the previous end also keeps the
* inter-block blank lines in the tail so the sliced source stays verbatim.
*
* Known deviation, shared with any prefix-freeze scheme: micromark resolves
* reference-style links and footnotes document-wide at parse time, so a
* reference whose definition lands on the other side of the freeze boundary
* renders literally until the settled full parse self-heals it.
*/
import type { Root, RootContent } from 'mdast'
/**
* Trailing blocks kept unstable. Appended text reshapes at most the last
* block; the second-to-last is retained as safety margin so a freeze decision
* never has to reason about the parse frontier.
*/
const UNSTABLE_TAIL_BLOCKS = 2
/** A top-level mdast block plus a render key that is stable across chunks. */
export interface PositionedBlock {
/** The parsed block. Positions inside it are relative to its parse slice. */
readonly node: RootContent
/**
* The block's start offset in the full source text. Stable from the frame
* a block first appears through freezing, so React reconciles rather than
* remounts when a block crosses the freeze boundary.
*/
readonly key: number
}
/** One {@link IncrementalMarkdownParser.update} result. */
export interface IncrementalBlocks {
/** Blocks that can no longer change; grows monotonically per generation. */
readonly frozen: readonly PositionedBlock[]
/** The re-parsed unstable tail (at most {@link UNSTABLE_TAIL_BLOCKS} blocks plus growth). */
readonly tail: readonly PositionedBlock[]
/** Bumped whenever non-append input discards the frozen prefix; callers drop caches keyed on it. */
readonly generation: number
}
/**
* A block's render key: its absolute source start offset. A position-less
* node (a grammar is free to omit positions) falls back to a negative
* list-index key — unique within one update's tail, which is the only place
* the fallback can occur: freezing requires the cut block's position, so a
* position-less parse keeps every block in the tail (real grammars always
* stamp positions and never take this path).
*/
function blockKey(node: RootContent, base: number, index: number): number {
const offset = node.position?.start.offset
return offset === undefined ? -(index + 1) : base + offset
}
/**
* Append-only incremental parser over a caller-supplied grammar. One instance
* accumulates one streaming document; non-append input resets it.
*/
export class IncrementalMarkdownParser {
private prevText = ''
private tailStart = 0
private frozen: PositionedBlock[] = []
private generation = 0
private cached: IncrementalBlocks | null = null
/** @param parse - Grammar shared with whatever renders the blocks, so boundaries agree. */
constructor(private readonly parse: (text: string) => Root) {}
/**
* Fold the current accumulated text and return the frozen/tail split.
* Idempotent for identical input (the previous result is returned as-is),
* so callers may invoke it from render paths that re-execute.
* @param text - The full accumulated markdown source.
* @returns Frozen and tail blocks with stream-stable render keys.
*/
update(text: string): IncrementalBlocks {
if (this.cached !== null && text === this.prevText) return this.cached
// Deliberate O(prefix) memcmp per update: sound divergence detection has
// to verify the whole retained prefix, and startsWith compares bytes two
// orders of magnitude faster than parsing them — the cost this class
// exists to remove. Passing append/reset deltas instead would push
// append bookkeeping across the session-projection update boundary for a check
// that stays sub-millisecond at realistic reply sizes.
if (!text.startsWith(this.prevText)) {
this.prevText = ''
this.tailStart = 0
this.frozen = []
this.generation += 1
}
this.prevText = text
const base = this.tailStart
const blocks = this.parse(text.slice(base)).children
let firstUnstable = Math.max(0, blocks.length - UNSTABLE_TAIL_BLOCKS)
if (firstUnstable > 0) {
const cutEnd = blocks[firstUnstable - 1]?.position?.end.offset
if (cutEnd === undefined) {
// A grammar that omits positions leaves nothing to cut at; keep the
// whole parse in the tail rather than guessing a boundary.
firstUnstable = 0
} else {
for (const node of blocks.slice(0, firstUnstable)) {
this.frozen.push({ node, key: blockKey(node, base, this.frozen.length) })
}
this.tailStart = base + cutEnd
}
}
const tail = blocks.slice(firstUnstable).map((node, index) => ({
node,
key: blockKey(node, base, index),
}))
this.cached = { frozen: [...this.frozen], tail, generation: this.generation }
return this.cached
}
}

View File

@ -0,0 +1,91 @@
// Adapted from DeepSeek Harness b150a551b8d465e31e418e1b2eaf5e79bbb7d28e (MIT). See THIRD_PARTY_NOTICES.md.
/**
* TeX-to-React via KaTeX, replicating the rehype-katex pipeline this renderer
* replaced: the same three-arm error chain (strict render, `strict: 'ignore'`
* retry, error span) and a DOM-identical element tree, so settled math keeps
* its exact markup. KaTeX emits an HTML string; the browser's own HTML parser
* (`DOMParser`, applying the spec's SVG/MathML foreign-content attribute
* adjustments KaTeX output relies on) turns it into a tree this module maps
* onto React elements — KaTeX output is a static span/MathML/SVG vocabulary
* with no raw user HTML, the same trust shiki's tree gets in CodeBlock.
*
* React 18 has no MathML support, so the `.katex-mathml` subtree's elements
* land in the HTML namespace — exactly as they did under the replaced
* hast-util-to-jsx-runtime pipeline. The visual arm is the `.katex-html`
* span tree; the MathML arm serves assistive technology, which reads it by
* tag name regardless of namespace.
*/
import { createElement } from 'react'
import type { CSSProperties, ReactNode } from 'react'
import katex from 'katex'
/**
* Convert one inline `style` attribute string into React's style object.
* KaTeX emits only plain kebab-case declarations (no custom properties and no
* nameless declarations), so camel-casing the property is the whole mapping.
*/
function styleObject(css: string): CSSProperties {
const style: Record<string, string> = {}
for (const declaration of css.split(';')) {
const colon = declaration.indexOf(':')
if (colon === -1) continue
const name = declaration.slice(0, colon).trim()
const key = name.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase())
style[key] = declaration.slice(colon + 1).trim()
}
return style
}
/** Map one parsed DOM node onto a React element (text nodes pass through). */
function domToReact(node: ChildNode, key: number): ReactNode {
if (node.nodeType === Node.TEXT_NODE) return node.textContent
/* v8 ignore next 2 -- KaTeX output holds only elements and text; other
node kinds cannot appear in its serialized vocabulary. */
if (node.nodeType !== Node.ELEMENT_NODE) return null
const element = node as Element
const props: Record<string, unknown> = { key }
for (const attribute of element.attributes) {
if (attribute.name === 'class') props['className'] = attribute.value
else if (attribute.name === 'style') props['style'] = styleObject(attribute.value)
else props[attribute.name] = attribute.value
}
const children = [...element.childNodes].map(domToReact)
return children.length === 0
? createElement(element.localName, props)
: createElement(element.localName, props, ...children)
}
/**
* Render TeX source to React elements through KaTeX.
* @param value - The TeX source (math node value; fenced `math` blocks append
* their trailing newline to match the replaced pipeline's text extraction).
* @param displayMode - Display (block) versus inline rendering.
* @returns KaTeX's element tree, or the error span when the source does not
* parse (colored with KaTeX's stock `errorColor`, matching rehype-katex).
*/
export function renderTexToReact(value: string, displayMode: boolean): ReactNode {
let html: string
try {
html = katex.renderToString(value, { displayMode, throwOnError: true })
} catch (error) {
try {
html = katex.renderToString(value, { displayMode, strict: 'ignore', throwOnError: false })
} catch {
// KaTeX renders ParseErrors itself under throwOnError: false; only its
// internal errors reach here, so mirror rehype-katex's manual span.
/* v8 ignore next 8 */
return (
<span
className="katex-error"
style={{ color: '#cc0000' }}
title={String(error)}
>
{value}
</span>
)
}
}
const parsed = new DOMParser().parseFromString(html, 'text/html')
return [...parsed.body.childNodes].map(domToReact)
}

View File

@ -0,0 +1,350 @@
// Adapted from DeepSeek Harness b150a551b8d465e31e418e1b2eaf5e79bbb7d28e (MIT). See THIRD_PARTY_NOTICES.md.
/** Extend upstream dollar-only math syntax with TeX delimiters while reusing its token vocabulary. */
import { factorySpace } from 'micromark-factory-space'
import type {} from 'micromark-extension-math'
import { markdownLineEnding } from 'micromark-util-character'
import { codes, constants, types } from 'micromark-util-symbol'
import type { Construct, Extension, Previous, State, Tokenizer } from 'micromark-util-types'
// oxlint-disable typescript/no-this-alias -- micromark binds tokenizer context only on the outer callback.
const previousBackslash: Previous = function (code) {
if (code !== codes.backslash) return true
const tail = this.events.at(-1)
/* v8 ignore next -- a previous code necessarily has a preceding event. */
if (tail === undefined) return false
return tail[1].type === types.characterEscape
}
const tokenizeBackslashMathText: Tokenizer = function (effects, ok, nok) {
return start
function start(code: number | null): State | undefined {
/* v8 ignore next -- the text construct is dispatched only for a backslash. */
if (code !== codes.backslash) return nok(code)
effects.enter('mathText')
effects.enter('mathTextSequence')
effects.consume(code)
return open
}
function open(code: number | null): State | undefined {
if (code !== codes.leftParenthesis) return nok(code)
effects.consume(code)
effects.exit('mathTextSequence')
return between
}
function between(code: number | null): State | undefined {
if (code === codes.eof) return nok(code)
if (code === codes.backslash) {
return effects.attempt({ partial: true, tokenize: tokenizeClose }, close, afterCloseAttempt)(code)
}
if (markdownLineEnding(code)) {
effects.enter(types.lineEnding)
effects.consume(code)
effects.exit(types.lineEnding)
return between
}
return dataStart(code)
}
function afterCloseAttempt(code: number | null): State | undefined {
return effects.check({ partial: true, tokenize: tokenizeOpen }, nok, dataStart)(code)
}
function dataStart(code: number | null): State | undefined {
effects.enter('mathTextData')
effects.consume(code)
return code === codes.backslash ? afterDataBackslash : data
}
function afterDataBackslash(code: number | null): State | undefined {
if (code === codes.backslash) {
effects.consume(code)
return data
}
return data(code)
}
function data(code: number | null): State | undefined {
if (code === codes.eof || code === codes.backslash || markdownLineEnding(code)) {
effects.exit('mathTextData')
return between(code)
}
effects.consume(code)
return data
}
function close(code: number | null): State | undefined {
effects.exit('mathText')
return ok(code)
}
function tokenizeClose(closeEffects: Parameters<Tokenizer>[0], closeOk: State, closeNok: State): State {
return slash
function slash(code: number | null): State | undefined {
/* v8 ignore next -- this partial construct is attempted only at a backslash. */
if (code !== codes.backslash) return closeNok(code)
closeEffects.enter('mathTextSequence')
closeEffects.consume(code)
return parenthesis
}
function parenthesis(code: number | null): State | undefined {
if (code !== codes.rightParenthesis) return closeNok(code)
closeEffects.consume(code)
closeEffects.exit('mathTextSequence')
return closeOk
}
}
function tokenizeOpen(openEffects: Parameters<Tokenizer>[0], openOk: State, openNok: State): State {
return slash
function slash(code: number | null): State | undefined {
/* v8 ignore next -- the opening check follows a failed close attempt at a backslash. */
if (code !== codes.backslash) return openNok(code)
openEffects.enter(types.chunkString)
openEffects.consume(code)
return parenthesis
}
function parenthesis(code: number | null): State | undefined {
if (code !== codes.leftParenthesis) return openNok(code)
openEffects.consume(code)
openEffects.exit(types.chunkString)
return openOk
}
}
}
function createMathFlow(marker: number, openMarker: number, closeMarker: number, multiline: boolean): Construct {
const tokenize: Tokenizer = function (effects, ok, nok) {
const self = this
let oddBackslashRun = false
const tail = self.events.at(-1)
const initialSize = tail?.[1].type === types.linePrefix
? tail[2].sliceSerialize(tail[1], true).length
: 0
return start
function start(code: number | null): State | undefined {
/* v8 ignore next -- the flow construct is dispatched only for its marker. */
if (code !== marker) return nok(code)
effects.enter('mathFlow')
effects.enter('mathFlowFence')
effects.enter('mathFlowFenceSequence')
effects.consume(code)
return open
}
function open(code: number | null): State | undefined {
if (code !== openMarker) return nok(code)
effects.consume(code)
effects.exit('mathFlowFenceSequence')
effects.exit('mathFlowFence')
return marker === codes.dollarSign ? afterDollarOpen : content
}
function afterDollarOpen(code: number | null): State | undefined {
return code === codes.dollarSign ? nok(code) : content(code)
}
function content(code: number | null): State | undefined {
if (code === codes.eof) return nok(code)
if (code === marker && (marker !== codes.dollarSign || !oddBackslashRun)) {
return effects.attempt(
{ partial: true, tokenize: tokenizeClosingFence },
closed,
afterClosingFenceAttempt,
)(code)
}
if (markdownLineEnding(code)) {
return multiline
? effects.attempt(nonLazyContinuation, afterContinuation, nok)(code)
: nok(code)
}
return valueStart(code)
}
function afterClosingFenceAttempt(code: number | null): State | undefined {
return marker === codes.backslash
? effects.check({ partial: true, tokenize: tokenizeOpeningFence }, nok, markerValueStart)(code)
: markerValueStart(code)
}
function afterContinuation(code: number | null): State | undefined {
return effects.attempt(
{ partial: true, tokenize: tokenizeClosingFence },
closed,
initialSize
? factorySpace(effects, content, types.linePrefix, initialSize + 1)
: content,
)(code)
}
function valueStart(code: number | null): State | undefined {
effects.enter('mathFlowValue')
oddBackslashRun = code === codes.backslash
effects.consume(code)
return value
}
function markerValueStart(code: number | null): State | undefined {
effects.enter('mathFlowValue')
oddBackslashRun = false
effects.consume(code)
return valueAfterMarker
}
function valueAfterMarker(code: number | null): State | undefined {
if (code === marker) {
effects.consume(code)
return value
}
return value(code)
}
function value(code: number | null): State | undefined {
if (code === codes.eof || code === marker || markdownLineEnding(code)) {
effects.exit('mathFlowValue')
return content(code)
}
oddBackslashRun = code === codes.backslash ? !oddBackslashRun : false
effects.consume(code)
return value
}
function closed(code: number | null): State | undefined {
effects.exit('mathFlow')
return ok(code)
}
function tokenizeClosingFence(
closeEffects: Parameters<Tokenizer>[0],
closeOk: State,
closeNok: State,
): State {
return factorySpace(closeEffects, sequenceStart, types.linePrefix, constants.tabSize)
function sequenceStart(code: number | null): State | undefined {
if (code !== marker) return closeNok(code)
closeEffects.enter('mathFlowFence')
closeEffects.enter('mathFlowFenceSequence')
closeEffects.consume(code)
return sequenceEnd
}
function sequenceEnd(code: number | null): State | undefined {
if (code !== closeMarker) return closeNok(code)
closeEffects.consume(code)
closeEffects.exit('mathFlowFenceSequence')
return factorySpace(closeEffects, after, types.whitespace)
}
function after(code: number | null): State | undefined {
if (code !== codes.eof && !markdownLineEnding(code)) return closeNok(code)
closeEffects.exit('mathFlowFence')
return closeOk(code)
}
}
function tokenizeOpeningFence(
openEffects: Parameters<Tokenizer>[0],
openOk: State,
openNok: State,
): State {
return sequenceStart
function sequenceStart(code: number | null): State | undefined {
/* v8 ignore next -- the opening check follows a failed close attempt at the marker. */
if (code !== marker) return openNok(code)
openEffects.enter(types.chunkString)
openEffects.consume(code)
return sequenceEnd
}
function sequenceEnd(code: number | null): State | undefined {
if (code !== openMarker) return openNok(code)
openEffects.consume(code)
openEffects.exit(types.chunkString)
return openOk
}
}
}
return {
concrete: true,
name: marker === codes.dollarSign ? 'sameLineDollarMathFlow' : 'backslashMathFlow',
tokenize,
}
}
const tokenizeNonLazyContinuation: Tokenizer = function (effects, ok, nok) {
const self = this
return start
function start(code: number | null): State | undefined {
/* v8 ignore next -- continuation constructs are attempted only after a line ending. */
if (code === codes.eof) return ok(code)
/* v8 ignore next -- continuation constructs are attempted only after a line ending. */
if (!markdownLineEnding(code)) return nok(code)
effects.enter(types.lineEnding)
effects.consume(code)
effects.exit(types.lineEnding)
return lineStart
}
function lineStart(code: number | null): State | undefined {
return self.parser.lazy[self.now().line] ? nok(code) : ok(code)
}
}
const nonLazyContinuation: Construct = {
partial: true,
tokenize: tokenizeNonLazyContinuation,
}
const backslashMathText: Construct = {
name: 'backslashMathText',
previous: previousBackslash,
tokenize: tokenizeBackslashMathText,
}
const backslashMathFlow = createMathFlow(
codes.backslash,
codes.leftSquareBracket,
codes.rightSquareBracket,
true,
)
const sameLineDollarMathFlow = createMathFlow(
codes.dollarSign,
codes.dollarSign,
codes.dollarSign,
false,
)
const backslashMath: Extension = {
flow: {
[codes.backslash]: backslashMathFlow,
[codes.dollarSign]: sameLineDollarMathFlow,
},
text: { [codes.backslash]: backslashMathText },
}
/**
* TeX backslash delimiters and same-line display-dollar blocks as a micromark
* syntax extension reusing `micromark-extension-math`'s token vocabulary; the
* caller must also register `math()` on the same parse so the emitted tokens
* compile to standard math nodes.
* @returns The micromark syntax extension.
*/
export function mathCompatibility(): Extension {
return backslashMath
}

View File

@ -0,0 +1,45 @@
// Adapted from DeepSeek Harness b150a551b8d465e31e418e1b2eaf5e79bbb7d28e (MIT). See THIRD_PARTY_NOTICES.md.
/**
* The markdown renderer's two mdast grammars, one per rendering arm. Each
* arm is internally consistent — the incremental tail parses, the one-shot
* parses, and the plain-text projection of a given grammar always agree on
* where blocks start and end — and the settled grammar is the streaming one
* plus the math extensions, so the arms differ only where TeX delimiters
* begin a math construct (a `$$` block is a paragraph while streaming and a
* math block once settled, by design).
*/
import type { Root } from 'mdast'
import { fromMarkdown } from 'mdast-util-from-markdown'
import { gfmFromMarkdown } from 'mdast-util-gfm'
import { mathFromMarkdown } from 'mdast-util-math'
import { gfm } from 'micromark-extension-gfm'
import { math } from 'micromark-extension-math'
import { cjkFriendlyStrong } from './cjkFriendlyStrong.js'
import { mathCompatibility } from './mathCompatibility.js'
/**
* Parse GFM markdown (the streaming arm's grammar: no math, so incomplete
* TeX never flashes KaTeX errors mid-stream).
* @param text - Markdown source.
* @returns The mdast root.
*/
export function parseGfm(text: string): Root {
return fromMarkdown(text, {
extensions: [gfm(), cjkFriendlyStrong()],
mdastExtensions: [gfmFromMarkdown()],
})
}
/**
* Parse GFM markdown plus TeX math with the compatibility delimiters
* (the settled arm's grammar).
* @param text - Markdown source.
* @returns The mdast root.
*/
export function parseGfmWithMath(text: string): Root {
return fromMarkdown(text, {
extensions: [gfm(), cjkFriendlyStrong(), mathCompatibility(), math()],
mdastExtensions: [gfmFromMarkdown(), mathFromMarkdown()],
})
}

View File

@ -0,0 +1,647 @@
// Adapted from DeepSeek Harness b150a551b8d465e31e418e1b2eaf5e79bbb7d28e (MIT). See THIRD_PARTY_NOTICES.md.
/**
* Direct mdast→React markdown renderer. Replaces the react-markdown /
* remark-rehype pipeline with one switch over parsed nodes so streaming can
* cache frozen blocks as React elements; the rendered DOM is pinned
* byte-for-byte by `tests/fixtures/markdown-dom` and must not drift.
*
* Untrusted-output policy (unchanged from the replaced pipeline): link and
* image destinations pass a protocol allowlist, images additionally require
* absolute HTTP(S), raw HTML renders as literal text (no HTML enters the
* DOM), and KaTeX runs without trusted commands. Fragment-anchor URLs fail
* the allowlist, so footnote references and back-references render as plain
* text rather than in-page links.
*
* Merge-extensible node unions fall through the documented default (render
* nothing) rather than ending in assertNever: grammars registered elsewhere
* may add node types this renderer has no mapping for.
*/
import { Fragment, createElement, useState } from 'react'
import type { Key, ReactNode } from 'react'
import clsx from 'clsx'
import type * as Md from 'mdast'
import type {} from 'mdast-util-math'
import { normalizeUri } from 'micromark-util-sanitize-uri'
import { CodeBlock } from '@deepseek-ai/dsh-client-ui-primitives'
import { renderTexToReact } from './katex.js'
import { McpAppCodeBlock, StreamingMcpAppPlaceholder } from '../McpAppFrame.js'
import { isMcpAppCodeBlock, extractMcpAppTitle, extractMcpAppHeight } from '../mcp-app.js'
import type { MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives'
import type { PositionedBlock } from './incremental.js'
import css from './MarkdownText.module.css'
/** Copy-button labels forwarded to fence CodeBlocks (this package is cordis-free, so copy arrives via props). */
export interface MarkdownCodeLabels {
/** Copy-button idle label. */
copyLabel?: string | undefined
/** Copy-button label during the post-copy confirmation window. */
copiedLabel?: string | undefined
}
function sanitizeUrl(url: string): string {
try {
switch (new URL(url).protocol) {
case 'http:':
case 'https:':
case 'mailto:':
return url
default:
return ''
}
} catch {
// Relative and otherwise unparsable destinations are disallowed alongside
// disallowed protocols; new URL() has no other failure mode for strings.
return ''
}
}
function remoteImageUrl(url: string): string | undefined {
try {
const protocol = new URL(url).protocol
return protocol === 'http:' || protocol === 'https:' ? url : undefined
} catch {
// Same single failure mode as above: not an absolute URL.
return undefined
}
}
/** Link/image reference targets collected from a document (first definition per identifier wins, as in CommonMark). */
export interface ReferenceTargets {
/** Link/image definitions keyed by upper-cased identifier. */
definitions: Map<string, Md.Definition>
/** Footnote definitions keyed by upper-cased identifier. */
footnotes: Map<string, Md.FootnoteDefinition>
}
/**
* Create an empty {@link ReferenceTargets}.
* @returns Fresh empty maps.
*/
export function createReferenceTargets(): ReferenceTargets {
return { definitions: new Map(), footnotes: new Map() }
}
/**
* Record every definition and footnote definition under `nodes` into
* `targets`, depth-first, keeping the first definition per identifier.
* @param nodes - Subtrees to walk (top-level blocks or any nested children).
* @param targets - Accumulator, typically shared across incremental segments.
*/
export function collectReferenceTargets(
nodes: readonly Md.RootContent[],
targets: ReferenceTargets,
): void {
for (const node of nodes) {
if (node.type === 'definition') {
const id = node.identifier.toUpperCase()
if (!targets.definitions.has(id)) targets.definitions.set(id, node)
} else if (node.type === 'footnoteDefinition') {
const id = node.identifier.toUpperCase()
if (!targets.footnotes.has(id)) targets.footnotes.set(id, node)
}
if ('children' in node) collectReferenceTargets(node.children, targets)
}
}
/**
* File-mention affordance for inline code: the owner resolves an authored
* token to the file it names, using its own vocabulary of real files — the
* renderer never guesses at what looks like a path.
*/
export interface MarkdownFileMentions {
/**
* Resolve one inline-code token.
* @param value - The authored token, exactly as written.
* @returns The opener with its accessible label and full-path title, or
* undefined when the token names no known file — it then stays inert code.
*/
resolve(value: string): { open: () => void; label: string; title: string } | undefined
}
/**
* One render pass's state: immutable options and targets plus the footnote
* numbering accumulated in document order while references render.
*/
export interface MarkdownRenderContext {
/** Reader addition: optional semantic text-leaf renderer with an absolute source offset. */
readonly renderText?: (value: string, offset: number, inline?: boolean) => ReactNode
/** Reader addition: keep atomic code content behind the source-order gate. */
readonly renderAtom?: (children: ReactNode, offset: number) => ReactNode
readonly sourceOffset?: number
/** Streaming arm: fences render plain and TeX stays literal. */
readonly streaming: boolean
/** Localized fence copy-button labels. */
readonly codeLabels: MarkdownCodeLabels | undefined
/** Inside a blockquote's children: tables there always fill the quote's width. */
readonly inBlockquote?: boolean
/** Inline-code file mentions; absent wherever no opener vocabulary exists. */
readonly fileMentions: MarkdownFileMentions | undefined
readonly pathImages?: MarkdownPathImages
/** Inside an anchor's children: interactive mentions must not nest there. */
readonly inLink?: boolean
/** Reference targets visible to this pass. */
readonly targets: ReferenceTargets
/** Footnote identifiers in first-reference order; a footnote's number is its 1-based index here. */
readonly footnoteOrder: string[]
/** References rendered per identifier; drives the section's back-reference count. */
readonly footnoteCounts: Map<string, number>
}
/**
* Render top-level blocks. Nodes that render nothing (definitions, unmapped
* types) are dropped rather than kept as null placeholders, matching the
* replaced pipeline's child lists so separator newlines land identically.
* @param blocks - Blocks with their stream-stable render keys.
* @param context - The pass state; footnote numbering mutates in document order.
* @returns One React node per rendered block.
*/
export function renderBlocks(
blocks: readonly PositionedBlock[],
context: MarkdownRenderContext,
): ReactNode[] {
return blocks
.map(block => renderNode(block.node, block.key, {
...context,
sourceOffset: block.key - (block.node.position?.start.offset ?? block.key),
}))
.filter(element => element !== null)
}
/**
* Interleave the newline text nodes the replaced pipeline emitted between
* block-level children. They are invisible between elements but coalesce
* into adjacent literal raw-HTML text, where the DOM parity fixtures pin
* them.
* @param elements - Rendered block children with empty renders already dropped.
* @param edges - Also emit the leading and trailing newline (hast's loose wrap).
* @returns The interleaved children.
*/
export function wrapBlockChildren(elements: readonly ReactNode[], edges: boolean): ReactNode[] {
const wrapped: ReactNode[] = []
for (const element of elements) {
if (edges || wrapped.length > 0) wrapped.push('\n')
wrapped.push(element)
}
if (edges && elements.length > 0) wrapped.push('\n')
return wrapped
}
/**
* A block child rendered for a parent that must tell paragraphs apart from
* other blocks (list items unwrap them when tight; footnote bodies receive
* their back-references inside the trailing paragraph).
*/
type BlockEntry = { paragraph: ReactNode[] } | { element: ReactNode }
/** Render container children into {@link BlockEntry} values, dropping empty renders. */
function renderBlockEntries(
blocks: readonly Md.RootContent[],
context: MarkdownRenderContext,
): BlockEntry[] {
const entries: BlockEntry[] = []
for (const [index, block] of blocks.entries()) {
if (block.type === 'paragraph') {
entries.push({ paragraph: renderChildren(block.children, context) })
} else {
const element = renderNode(block, index, context)
if (element !== null) entries.push({ element })
}
}
return entries
}
function renderChildren(
nodes: readonly Md.RootContent[],
context: MarkdownRenderContext,
): ReactNode[] {
return nodes.map((node, index) => renderNode(node, index, context))
}
function renderNode(node: Md.RootContent, key: Key, context: MarkdownRenderContext): ReactNode {
switch (node.type) {
case 'text':
return context.renderText ? context.renderText(node.value, (context.sourceOffset ?? 0) + (node.position?.start.offset ?? 0)) : node.value
case 'paragraph':
return <p key={key}>{renderChildren(node.children, context)}</p>
case 'heading':
return createElement(`h${node.depth}`, { key }, ...renderChildren(node.children, context))
case 'blockquote':
return (
<blockquote key={key}>
{wrapBlockChildren(
renderChildren(node.children, { ...context, inBlockquote: true }).filter(child => child !== null),
true,
)}
</blockquote>
)
case 'thematicBreak':
return <hr key={key} />
case 'break':
// The replaced pipeline emitted a newline text node after each <br>.
return <Fragment key={key}><br />{'\n'}</Fragment>
case 'strong':
return <strong key={key}>{renderChildren(node.children, context)}</strong>
case 'emphasis':
return <em key={key}>{renderChildren(node.children, context)}</em>
case 'delete':
return <del key={key}>{renderChildren(node.children, context)}</del>
case 'inlineCode': {
// Parity with mdast-util-to-hast: inline code renders line endings as spaces.
const value = node.value.replace(/\r?\n|\r/g, ' ')
// Native code chips are inline-flex. Keep a single inline formatting
// context so motion spans do not become flex items or drop code spaces.
const content = context.renderText ? <span>{context.renderText(value, (context.sourceOffset ?? 0) + (node.position?.start.offset ?? 0), true)}</span> : value
// An inline-code token that is entirely an absolute HTTP(S) URL keeps
// its code chrome and gains the same safe external anchor as a link;
// commands, partial URLs, and other schemes stay inert. The value is
// authored text, not a parsed destination, so no normalizeUri: port,
// path, and query render unchanged.
const href = inlineCodeHttpUrl(value)
if (href !== undefined) return <code key={key}>{renderSafeLink(href, [content], 'link')}</code>
// A token the owner's file-mention vocabulary recognizes opens that
// file; the resolver, not this renderer, decides what names a file.
// Inside an anchor the token stays inert — a button cannot nest there.
const mention = context.inLink === true ? undefined : context.fileMentions?.resolve(value)
if (mention !== undefined) {
return (
<code key={key}>
<button
type="button"
className={css.fileMention}
title={mention.title}
aria-label={mention.label}
onClick={mention.open}
>
{content}
</button>
</code>
)
}
return <code key={key}>{content}</code>
}
case 'html':
// No HTML parser enters the pipeline: raw HTML stays literal text.
return context.renderText ? context.renderText(node.value, (context.sourceOffset ?? 0) + (node.position?.start.offset ?? 0)) : node.value
case 'code': {
const code = renderCode(node, key, context)
return context.renderAtom ? <Fragment key={key}>{context.renderAtom(code, (context.sourceOffset ?? 0) + (node.position?.start.offset ?? 0))}</Fragment> : code
}
case 'math':
return <Fragment key={key}>{renderTexToReact(node.value, true)}</Fragment>
case 'inlineMath':
return <Fragment key={key}>{renderTexToReact(node.value, false)}</Fragment>
case 'list':
return renderList(node, key, context)
case 'listItem':
// Reachable only in hand-built trees: the grammar emits items inside lists.
return renderListItem(node, listItemLoose(node), key, context)
case 'table':
return renderTable(node, key, context)
case 'link':
return renderAnchor(node.url, renderChildren(node.children, { ...context, inLink: true }), key)
case 'linkReference':
return renderLinkReference(node, key, context)
case 'image':
return renderImage(node.url, node.alt ?? '', key, context)
case 'imageReference':
return renderImageReference(node, key, context)
case 'footnoteReference':
return renderFootnoteReference(node, key, context)
case 'definition':
case 'footnoteDefinition':
// Targets render elsewhere: definitions resolve references in place;
// footnote bodies render in the trailing section.
return null
default:
// Documented default for the merge-extensible union: node types without
// a mapping (tableRow/tableCell outside a table, frontmatter, future
// grammar contributions) render nothing.
return null
}
}
function renderCode(node: Md.Code, key: Key, context: MarkdownRenderContext): ReactNode {
const language = node.lang ?? undefined
if (node.value === '') {
// Parity: the replaced pipeline kept the stock <pre> for an empty fence.
return (
<pre key={key}>
<code className={language === undefined ? undefined : `language-${language}`} />
</pre>
)
}
// The replaced pipeline recovered the grammar id from the hast class with
// /language-([\w-]+)/, which truncates at the first non-word character.
const lang = language === undefined ? undefined : /^[\w-]+/.exec(language)?.[0]
if (isMcpAppCodeBlock(node.lang, node.meta, node.value)) {
const title = extractMcpAppTitle(node.meta, node.value)
const initialHeight = extractMcpAppHeight(node.meta)
if (context.streaming) {
return <StreamingMcpAppPlaceholder key={key} title={title} />
}
return <McpAppCodeBlock key={key} html={node.value} title={title} initialHeight={initialHeight} />
}
if (!context.streaming && lang === 'math') {
// ```math fences render as display TeX once settled (rehype-katex parity);
// its text extraction saw the code block's trailing newline.
return <Fragment key={key}>{renderTexToReact(`${node.value}\n`, true)}</Fragment>
}
return (
<CodeBlock
key={key}
// The replaced hast pipeline appended one synthetic newline that
// CodeBlock's display trim removes; feeding the bare value would make
// that trim eat a REAL trailing blank line inside the fence instead.
code={`${node.value}\n`}
lang={context.streaming ? undefined : lang}
copyLabel={context.codeLabels?.copyLabel ?? '复制代码'}
copiedLabel={context.codeLabels?.copiedLabel ?? '已复制'}
/>
)
}
/** A list is loose when it or any of its items is spread; every item then keeps its paragraphs. */
function listLoose(list: Md.List): boolean {
return (list.spread ?? false) || list.children.some(listItemLoose)
}
function listItemLoose(item: Md.ListItem): boolean {
return item.spread ?? item.children.length > 1
}
function renderList(node: Md.List, key: Key, context: MarkdownRenderContext): ReactNode {
const loose = listLoose(node)
const properties: { start?: number; className?: string } = {}
if (typeof node.start === 'number' && node.start !== 1) properties.start = node.start
if (node.children.some(item => typeof item.checked === 'boolean')) {
properties.className = 'contains-task-list'
}
return createElement(
node.ordered === true ? 'ol' : 'ul',
{ key, ...properties },
...node.children.map((item, index) => renderListItem(item, loose, index, context)),
)
}
function renderListItem(
item: Md.ListItem,
loose: boolean,
key: Key,
context: MarkdownRenderContext,
): ReactNode {
const entries = renderBlockEntries(item.children, context)
const task = typeof item.checked === 'boolean'
if (task) {
const checkbox = <input key="task-checkbox" type="checkbox" checked={item.checked === true} disabled />
const head = entries[0]
if (head !== undefined && 'paragraph' in head) {
head.paragraph = head.paragraph.length > 0 ? [checkbox, ' ', ...head.paragraph] : [checkbox]
} else {
entries.unshift({ paragraph: [checkbox] })
}
}
// Newline placement and tight-paragraph unwrapping mirror
// mdast-util-to-hast's list-item handler: a newline before every child
// except a tight leading paragraph, and after a trailing non-paragraph
// (or any trailing child when loose).
const parts: ReactNode[] = []
for (const [index, entry] of entries.entries()) {
const isParagraph = 'paragraph' in entry
if (loose || index !== 0 || !isParagraph) parts.push('\n')
if (!isParagraph) parts.push(entry.element)
else if (loose) parts.push(<p key={`p-${index}`}>{entry.paragraph}</p>)
else parts.push(<Fragment key={`p-${index}`}>{entry.paragraph}</Fragment>)
}
const tail = entries[entries.length - 1]
if (tail !== undefined && (loose || !('paragraph' in tail))) parts.push('\n')
return (
<li key={key} className={task ? 'task-list-item' : undefined}>
{parts}
</li>
)
}
function renderTable(node: Md.Table, key: Key, context: MarkdownRenderContext): ReactNode {
const align = node.align ?? null
const [headRow, ...bodyRows] = node.children
const columns = align === null ? headRow?.children.length ?? 0 : align.length
// Four or more columns read as a comparison matrix: the block keeps the
// table at natural width and exposes the stable `md-table-wide` hook so a
// hosting layout (the chat transcript) can widen it past the message
// column. Narrower tables — and any table inside a blockquote — fill the
// column and wrap instead (deepsuite chat TableWrapper parity).
const wide = columns >= 4 && context.inBlockquote !== true
return (
// Wide tables rest with overflow-x hidden (the hover-revealed bar in
// MarkdownText.module.css), which drops Chromium's implicit scroller
// focusability — the explicit tabindex keeps them keyboard-reachable,
// and :focus-visible restores scrolling.
<div
key={key}
className={clsx(css.tableScroll, wide ? 'md-table-wide' : css.tableFill)}
tabIndex={wide ? 0 : undefined}
>
<table>
{headRow !== undefined && <thead>{renderTableRow(headRow, 'th', align, 0, context)}</thead>}
{bodyRows.length > 0 && (
<tbody>
{bodyRows.map((row, index) => renderTableRow(row, 'td', align, index + 1, context))}
</tbody>
)}
</table>
</div>
)
}
function renderTableRow(
row: Md.TableRow,
cellTag: 'th' | 'td',
align: readonly Md.AlignType[] | null,
key: Key,
context: MarkdownRenderContext,
): ReactNode {
// With column alignment present, every row renders exactly one cell per
// column, padding or truncating the row (mdast-util-to-hast parity).
const length = align === null ? row.children.length : align.length
const cells: ReactNode[] = []
for (let index = 0; index < length; index++) {
const cell = row.children[index]
const alignValue = align?.[index]
cells.push(createElement(
cellTag,
// hast-util-to-jsx-runtime's default tableCellAlignToStyle turned the
// deprecated align attribute into an inline style; keep that DOM.
{ key: index, style: alignValue == null ? undefined : { textAlign: alignValue } },
...(cell === undefined ? [] : renderChildren(cell.children, context)),
))
}
return <tr key={key}>{cells}</tr>
}
/** Anchor over an already-authored href: allowlisted or unwrapped, external links get the safe attributes. */
function renderSafeLink(href: string, children: ReactNode[], key: Key): ReactNode {
const safeHref = sanitizeUrl(href)
if (safeHref === '') return <Fragment key={key}>{children}</Fragment>
const external = ['http:', 'https:'].includes(new URL(safeHref).protocol)
return (
<a
key={key}
href={safeHref}
{...(external ? { target: '_blank', rel: 'noopener noreferrer' } : {})}
>
{children}
</a>
)
}
/** Anchor over a parsed markdown destination, which hast normalized before the allowlist saw it. */
function renderAnchor(url: string, children: ReactNode[], key: Key): ReactNode {
return renderSafeLink(normalizeUri(url), children, key)
}
/**
* The complete inline-code value when it is exactly an absolute HTTP(S) URL
* (no surrounding whitespace); anything else stays inert code.
*/
function inlineCodeHttpUrl(value: string): string | undefined {
if (value.trim() !== value) return undefined
try {
const protocol = new URL(value).protocol
return protocol === 'http:' || protocol === 'https:' ? value : undefined
} catch {
// Not an absolute URL at all — the only way new URL() rejects a string.
return undefined
}
}
function renderImage(url: string, alt: string, key: Key, context: MarkdownRenderContext): ReactNode {
// RC2 semantics, including the revalidation of a trusted vocabulary result.
const remote = remoteImageUrl(sanitizeUrl(normalizeUri(url)))
const rewritten = remote === undefined ? context.pathImages?.resolve(url) : undefined
let imageSrc = remote
if (rewritten !== undefined) {
try {
const parsed = new URL(rewritten)
if (['http:', 'https:', 'blob:', 'data:'].includes(parsed.protocol) || rewritten.startsWith('dsh-app://app/api/file?')) imageSrc = rewritten
} catch { /* A vocabulary result must be an absolute URL. */ }
}
if (imageSrc === undefined) {
return <span key={key} className={css.imageAlt}>{alt}</span>
}
return <MarkdownImage key={`${key}:${imageSrc}`} src={imageSrc} alt={alt} destination={url} />
}
function MarkdownImage({ src, alt, destination }: { src: string; alt: string; destination: string }): ReactNode {
const [failed, setFailed] = useState(false)
if (failed) return <span className={css.imageAlt}>{alt || destination}</span>
return (
<img
className={css.image}
src={src}
alt={alt}
onError={() => { setFailed(true) }}
loading="lazy"
decoding="async"
referrerPolicy="no-referrer"
/>
)
}
/** The bracketed source text a reference reverts to when its definition is missing. */
function referenceSuffix(node: Md.LinkReference | Md.ImageReference): string {
if (node.referenceType === 'collapsed') return '][]'
if (node.referenceType === 'full') return `][${node.label ?? node.identifier}]`
return ']'
}
function renderLinkReference(
node: Md.LinkReference,
key: Key,
context: MarkdownRenderContext,
): ReactNode {
const definition = context.targets.definitions.get(node.identifier.toUpperCase())
if (definition === undefined) {
// The grammar only emits references whose definitions exist somewhere in
// the same parse, but incremental segments and hand-built trees may still
// present unresolved ones: revert to the bracketed source text — which is
// not an anchor, so mentions inside it stay live.
return <Fragment key={key}>{'['}{renderChildren(node.children, context)}{referenceSuffix(node)}</Fragment>
}
return renderAnchor(definition.url, renderChildren(node.children, { ...context, inLink: true }), key)
}
function renderImageReference(
node: Md.ImageReference,
key: Key,
context: MarkdownRenderContext,
): ReactNode {
const definition = context.targets.definitions.get(node.identifier.toUpperCase())
if (definition === undefined) return `![${node.alt ?? ''}${referenceSuffix(node)}`
return renderImage(definition.url, node.alt ?? '', key, context)
}
function renderFootnoteReference(
node: Md.FootnoteReference,
key: Key,
context: MarkdownRenderContext,
): ReactNode {
const id = node.identifier.toUpperCase()
const seen = context.footnoteCounts.get(id)
if (seen === undefined) context.footnoteOrder.push(id)
context.footnoteCounts.set(id, (seen ?? 0) + 1)
// The in-page anchor fails the protocol allowlist, so only the numbered
// superscript renders (matching the replaced pipeline's unwrapped link).
return <sup key={key}>{String(context.footnoteOrder.indexOf(id) + 1)}</sup>
}
/**
* Render the trailing footnote section for every footnote referenced during
* the pass, in first-reference order, with one plain-text back-reference
* marker per rendered reference.
* @param context - The pass state after all blocks rendered.
* @returns The section, or null when no referenced footnote has a definition.
*/
export function renderFootnoteSection(context: MarkdownRenderContext): ReactNode | null {
const items: ReactNode[] = []
for (const id of context.footnoteOrder) {
const definition = context.targets.footnotes.get(id)
if (definition === undefined) continue
const count = context.footnoteCounts.get(id) ?? 0
const backrefs: ReactNode[] = []
for (let reference = 1; reference <= count; reference++) {
if (backrefs.length > 0) backrefs.push(' ')
backrefs.push('↩')
if (reference > 1) backrefs.push(<sup key={`re-${reference}`}>{String(reference)}</sup>)
}
const entries = renderBlockEntries(definition.children, context)
const tail = entries[entries.length - 1]
const body: ReactNode[] = entries.map((entry, index) => (
'paragraph' in entry
? (
<p key={`p-${index}`}>
{entry.paragraph}
{entry === tail && <>{' '}{backrefs}</>}
</p>
)
: entry.element
))
// Without a trailing paragraph the back-references join the block list
// itself (and pick up the wrap newlines), as in the replaced pipeline.
if (tail === undefined || !('paragraph' in tail)) body.push(...backrefs)
items.push(
<li key={id} id={`user-content-fn-${normalizeUri(id.toLowerCase())}`}>
{wrapBlockChildren(body, true)}
</li>,
)
}
if (items.length === 0) return null
return (
<section key="footnotes" data-footnotes className="footnotes">
<h2 id="footnote-label" className="sr-only">Footnotes</h2>
<ol>{items}</ol>
</section>
)
}

View File

@ -0,0 +1,14 @@
{
"repository": "https://github.com/deepseek-ai/deepseek-harness",
"commit": "b150a551b8d465e31e418e1b2eaf5e79bbb7d28e",
"sha256BeforeAdaptation": {
"MarkdownText.tsx": "b0ce4cf0986cadf624436136186b16f108ed2365aec0350b195f02dae036017a",
"MarkdownText.module.css": "e226e878c45037b1cf537e4361f59e052ef979321593be3369bd31200d0342bc",
"render.tsx": "d4fefca41ab709526933e47144a01df14bd3d5619558cd6ed35b663d1640d779",
"parse.ts": "6be57559995c4e717d6d704207eb2fec86db9714c2a4bcc5b0c3f6648c8990f0",
"incremental.ts": "2975a332ac74b931a7cb489e2eea28469aa3d9596328d5a474d41379b6c7b640",
"cjkFriendlyStrong.ts": "bc4adf3183f7d0feea17e3a176e7c4b1db5bdddc29e7fc87261f627ff8a39b53",
"mathCompatibility.ts": "5f8cec86fd613fd2f67510e22b0a9d661f4173b3d49fb13fef71b25f4abb652b",
"katex.tsx": "8227e04d29333d2568021ed012143237b457852bce25d82cf394d72b941e74a5"
}
}

323
src/client/mcp-app.ts Normal file
View File

@ -0,0 +1,323 @@
/**
* Core pure functions for SEP-1865 / MCP Apps integration.
* Free of CSS module imports so it can be cleanly tested in Node test environments.
*/
export function getHostTheme(): 'dark' | 'light' {
if (typeof document === 'undefined') return 'light';
if (document.body?.hasAttribute('data-ds-dark-theme')) return 'dark';
const colorScheme = document.documentElement?.style.colorScheme;
if (colorScheme === 'dark' || colorScheme === 'light') return colorScheme;
const dataTheme = document.documentElement?.getAttribute('data-theme') || document.body?.getAttribute('data-theme');
if (dataTheme === 'dark' || dataTheme === 'light') return dataTheme;
if (document.body?.classList.contains('dark') || document.documentElement?.classList.contains('dark')) return 'dark';
return typeof window !== 'undefined' && window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
export function getCssTokens(theme: 'dark' | 'light'): Record<string, string> {
const isDark = theme === 'dark';
return {
'--background': isDark ? '#0f172a' : '#ffffff',
'--card': isDark ? '#1e293b' : '#f8fafc',
'--foreground': isDark ? '#f8fafc' : '#0f172a',
'--muted-foreground': isDark ? '#94a3b8' : '#64748b',
'--primary': '#2563eb',
'--primary-foreground': '#ffffff',
'--border': isDark ? '#334155' : '#e2e8f0',
'--hover': isDark ? 'rgba(148, 163, 184, 0.15)' : 'rgba(148, 163, 184, 0.12)',
};
}
/**
* Extracts a title from the HTML document's <title> tag.
*/
export function extractHtmlTitle(html: string): string | undefined {
const match = /<title[^>]*>([^<]+)<\/title>/i.exec(html);
return match?.[1]?.trim();
}
/**
* Normalizes user/model generated HTML to ensure a valid HTML5 structure
* and embeds a dynamic theme listener so dark/light mode switches take effect immediately.
*/
export function ensureHtmlDocument(rawHtml: string, initialTheme: 'dark' | 'light' = 'light'): string {
const isDark = initialTheme === 'dark';
const trimmed = rawHtml.trim();
const themeScript = `<script>
(function() {
function applyTheme(theme) {
if (!theme) return;
document.documentElement.setAttribute('data-theme', theme);
document.documentElement.style.colorScheme = theme;
if (theme === 'dark') {
document.documentElement.classList.add('dark');
if (document.body) document.body.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
if (document.body) document.body.classList.remove('dark');
}
}
applyTheme(${JSON.stringify(initialTheme)});
// Precise content-bottom measurement to avoid scrollHeight latching to iframe outer height
function reportHeight() {
var body = document.body;
if (!body) return;
var children = body.children;
var maxBottom = 0;
for (var i = 0; i < children.length; i++) {
var el = children[i];
if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE' || el.tagName === 'LINK') continue;
var style = window.getComputedStyle(el);
if (style.display === 'none' || style.position === 'fixed') continue;
var marginBottom = parseFloat(style.marginBottom) || 0;
var bottom = el.offsetTop + el.offsetHeight + marginBottom;
if (bottom > maxBottom) maxBottom = bottom;
}
var bodyStyle = window.getComputedStyle(body);
var bodyPaddingBottom = parseFloat(bodyStyle.paddingBottom) || 0;
var h = maxBottom > 0 ? Math.ceil(maxBottom + bodyPaddingBottom) : body.scrollHeight;
if (h > 40) {
window.parent.postMessage({
jsonrpc: '2.0',
method: 'ui/resize',
params: { height: h }
}, '*');
}
}
if (typeof ResizeObserver !== 'undefined') {
var ro = new ResizeObserver(function() {
reportHeight();
});
if (document.body) {
ro.observe(document.body);
} else {
document.addEventListener('DOMContentLoaded', function() {
if (document.body) ro.observe(document.body);
});
}
}
window.addEventListener('load', reportHeight);
setTimeout(reportHeight, 50);
setTimeout(reportHeight, 250);
setTimeout(reportHeight, 600);
window.addEventListener('message', function(e) {
var msg = e.data;
if (!msg || typeof msg !== 'object') return;
var theme = (msg.params && msg.params.theme) || (msg.result && msg.result.hostContext && msg.result.hostContext.theme);
if (theme) applyTheme(theme);
});
})();
</script>`;
if (/^<!DOCTYPE/i.test(trimmed) || /<html[\s>]/i.test(trimmed)) {
if (/<head[\s>]/i.test(trimmed)) {
return trimmed.replace(/<head([^>]*)>/i, `<head$1>\n ${themeScript}`);
}
return trimmed;
}
return `<!DOCTYPE html>
<html lang="zh-CN" data-theme="${initialTheme}" class="${isDark ? 'dark' : ''}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
${themeScript}
<style>
:root {
--background: #ffffff;
--card: #f8fafc;
--border: #e2e8f0;
--foreground: #0f172a;
--muted-foreground: #64748b;
--primary: #2563eb;
--primary-foreground: #ffffff;
}
:root[data-theme='dark'], html.dark {
--background: #0f172a;
--card: #1e293b;
--border: #334155;
--foreground: #f8fafc;
--muted-foreground: #94a3b8;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme='light']) {
--background: #0f172a;
--card: #1e293b;
--border: #334155;
--foreground: #f8fafc;
--muted-foreground: #94a3b8;
}
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: transparent;
color: var(--foreground);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
padding: 12px;
}
</style>
</head>
<body class="${isDark ? 'dark' : ''}">
${trimmed}
</body>
</html>`;
}
/**
* Determines whether a markdown code block represents an MCP App.
*/
export function isMcpAppCodeBlock(lang: string | null | undefined, meta: string | null | undefined, value: string): boolean {
const l = (lang ?? '').toLowerCase().trim();
const m = (meta ?? '').toLowerCase().trim();
if (l === 'mcp-app' || l === 'mcpapp' || l === 'mcp-ui' || l === 'mcp' || l.startsWith('mcp-app:') || l === 'html:mcp-app' || l === 'html:mcp') {
return true;
}
if (m.includes('mcp-app') || m.includes('mcpapp') || m.includes('sep-1865') || m.includes('mcp-ui')) {
return true;
}
if (l === 'html' && (value.includes('ui/submit') || value.includes('ui/initialize') || value.includes('SEP-1865') || value.includes('mcp-app'))) {
return true;
}
return false;
}
/**
* Extracts a title from code block meta or HTML content.
*/
export function extractMcpAppTitle(meta: string | null | undefined, value: string): string | undefined {
if (meta) {
const titleMatch = /title=["']([^"']+)["']/i.exec(meta) || /title=([^\s]+)/i.exec(meta);
if (titleMatch?.[1]) return titleMatch[1];
}
const htmlTitle = extractHtmlTitle(value);
if (htmlTitle) return htmlTitle;
return undefined;
}
/**
* Extracts an explicit height budget from code block meta (e.g. height=600 or height="500px").
*/
export function extractMcpAppHeight(meta: string | null | undefined): number | undefined {
if (!meta) return undefined;
const match = /height=["']?(\d+)(?:px)?["']?/i.exec(meta);
if (match?.[1]) {
const n = parseInt(match[1], 10);
if (Number.isFinite(n) && n >= 100 && n <= 3000) return n;
}
return undefined;
}
/**
* Formats a user-submitted MCP App event into a concise, natural language conversational prompt.
* Avoids raw multiline JSON and excessive whitespace.
*/
export function formatReceiptPrompt(params: Record<string, unknown>, title?: string): string {
// If user selected a choice/variant (e.g. quiz or blind test)
if (typeof params.choice === 'string') {
const desc = typeof params.desc === 'string' ? `(${params.desc})` : '';
const componentName = title ? `「${title}」` : '组件';
return `我在${componentName}中选择了:${params.choice}${desc}。请根据我的选择继续。`;
}
if (typeof params.selectedVariant === 'string') {
const score = typeof params.score === 'number' ? `,得分:${params.score}` : '';
return `我在方案评测中选择了:${params.selectedVariant}${score}。请根据该方案继续分析。`;
}
if (typeof params.action === 'string') {
const payloadStr = params.payload ? (typeof params.payload === 'string' ? params.payload : JSON.stringify(params.payload)) : '';
return `[${title ?? '组件操作'}] 已完成 ${params.action}${payloadStr ? `: ${payloadStr}` : ''}`;
}
// Generic single field
const keys = Object.keys(params);
if (keys.length === 1 && typeof params[keys[0]] === 'string') {
return `[${title ?? '组件回执'}] ${keys[0]}: ${params[keys[0]]}`;
}
return `[${title ?? '组件回执'}] ${JSON.stringify(params)}`;
}
/**
* Finds the DSH composer textarea. The page can contain multiple (hidden)
* textareas, so prefer a visible, enabled one carrying the input-bar
* `data-phase` marker; fall back to the tallest visible, then any enabled.
*/
export function findComposerTextarea(doc?: Document): HTMLTextAreaElement | null {
const d = doc ?? (typeof document !== 'undefined' ? document : undefined);
if (!d) return null;
const areas = Array.from(d.querySelectorAll('textarea'));
if (areas.length === 0) return null;
const visible = areas.filter((el) => !el.disabled && (el as HTMLElement).offsetParent !== null);
const pool = visible.length > 0 ? visible : areas.filter((el) => !el.disabled);
const candidates = pool.length > 0 ? pool : areas;
const phased = candidates.find((el) => el.hasAttribute('data-phase'));
if (phased) return phased;
let best = candidates[0];
for (const el of candidates) {
if (((el as HTMLElement).offsetHeight || 0) > ((best as HTMLElement).offsetHeight || 0)) best = el;
}
return best;
}
/**
* DOM fallback for composer fill: types into the Lexical contenteditable
* surface (`[data-composer-input]`) via execCommand insertText so the editor
* adopts the change as a genuine user edit. Returns true when accepted.
*/
export function fillComposerDom(text: string, doc?: Document): boolean {
const d = doc ?? (typeof document !== 'undefined' ? document : undefined);
if (!d) return false;
try {
const surfaces = Array.from(d.querySelectorAll('[data-composer-input]'));
const editable = surfaces.find(
(el) => el.getAttribute('contenteditable') === 'true'
) as HTMLElement | undefined;
const target = editable ?? (surfaces[0] as HTMLElement | undefined);
if (!target) return false;
target.focus();
if (typeof d.execCommand === 'function') {
try {
if (d.execCommand('insertText', false, text)) return true;
} catch {
// Fall through to the selection-based path below.
}
}
const selection = d.getSelection?.();
if (selection) {
selection.selectAllChildren(target);
if (typeof d.execCommand === 'function') {
try {
if (d.execCommand('insertText', false, text)) return true;
} catch {
// No further DOM path; the caller falls back to clipboard.
}
}
}
} catch {
// Non-browser environment or DOM denial.
}
return false;
}
/**
* Updates a React-controlled textarea and properly notifies React's valueTracker
* so the backdrop and input state immediately reflect the text.
*/
export function setReactInputValue(textarea: HTMLTextAreaElement, value: string): void {
try {
const nativeSetter = Object.getOwnPropertyDescriptor(
window.HTMLTextAreaElement.prototype,
'value'
)?.set;
if (nativeSetter) {
nativeSetter.call(textarea, value);
} else {
textarea.value = value;
}
textarea.dispatchEvent(new Event('input', { bubbles: true }));
textarea.focus();
} catch {
textarea.value = value;
}
}

View File

@ -0,0 +1,47 @@
/** Local clock and run-duration labels for reader message chrome. */
function pad2(n: number): string {
return String(n).padStart(2, '0')
}
/**
* Elapsed wall time, matching official Chat `duration.minutes` / `duration.seconds`.
* @param ms - Elapsed milliseconds (negatives clamp to zero).
*/
export function formatRunDuration(ms: number): string {
const total = Math.max(0, Math.floor(ms / 1000))
const minutes = Math.floor(total / 60)
const seconds = total % 60
return minutes > 0 ? `${minutes}分${pad2(seconds)}秒` : `${seconds}秒`
}
/**
* Settled-turn duration pill, matching official `message.ranFor`.
* @param ms - Elapsed milliseconds.
*/
export function formatRanFor(ms: number): string {
return `用时 ${formatRunDuration(ms)}`
}
/**
* Compact local timestamp. Same calendar day → `HH:mm`; earlier this year →
* `M月D日 HH:mm`; other years → `YYYY年M月D日 HH:mm`.
* @param time - Unix epoch ms from the source session event.
* @param now - Reference instant for the day/year cut.
*/
export function formatMessageClock(time: number, now: number = Date.now()): string {
const d = new Date(time)
const n = new Date(now)
const clock = `${pad2(d.getHours())}:${pad2(d.getMinutes())}`
if (
d.getFullYear() === n.getFullYear()
&& d.getMonth() === n.getMonth()
&& d.getDate() === n.getDate()
) {
return clock
}
if (d.getFullYear() === n.getFullYear()) {
return `${d.getMonth() + 1}月${d.getDate()}日 ${clock}`
}
return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日 ${clock}`
}

545
src/client/motion.tsx Normal file
View File

@ -0,0 +1,545 @@
import { useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react';
import type { ReactNode, RefObject } from 'react';
import css from './Reader.module.css';
import { StreamMotionContext } from './streaming.js';
import { reconcileTurnSlots, type TurnSlot } from './turn-slots.js';
const EASING = 'cubic-bezier(.22,1,.36,1)';
export function useMotionAllowed(enabled: boolean): boolean {
const [reduced, setReduced] = useState(() => window.matchMedia('(prefers-reduced-motion: reduce)').matches);
useEffect(() => {
const query = window.matchMedia('(prefers-reduced-motion: reduce)');
const change = () => setReduced(query.matches);
query.addEventListener('change', change);
return () => query.removeEventListener('change', change);
}, []);
return enabled && !reduced;
}
export function usePinnedSelection(root: RefObject<HTMLElement>, selector = '[data-reader-answer], [data-reader-body], [data-reader-process]'): readonly string[] {
const [keys, setKeys] = useState<readonly string[]>([]);
useEffect(() => {
const update = () => {
const selection = document.getSelection();
const range = selection && !selection.isCollapsed && selection.rangeCount ? selection.getRangeAt(0) : null;
const next = range && root.current
? [...new Set(Array.from(root.current.querySelectorAll<HTMLElement>(selector))
.filter(element => range.intersectsNode(element))
.map(element => element.dataset.readerKey ?? element.dataset.readerProcessKey!).filter(Boolean))]
: [];
setKeys(previous => previous.length === next.length && previous.every((key, index) => key === next[index]) ? previous : next);
};
document.addEventListener('selectionchange', update);
return () => document.removeEventListener('selectionchange', update);
}, [root, selector]);
return keys;
}
export function StatusText({ text, motion, shimmer = false }: { text: string; motion: boolean; shimmer?: boolean }) {
const ref = useRef<HTMLSpanElement>(null);
const [visible, setVisible] = useState(() => !document.hidden);
const [forcedColors, setForcedColors] = useState(() => window.matchMedia('(forced-colors: active)').matches);
const allowed = motion && visible && !forcedColors;
const [frame, setFrame] = useState<{
text: string; id: number; phase: 'idle' | 'start' | 'running';
outgoing: { text: string; id: number } | null;
}>({ text, id: 0, phase: 'idle', outgoing: null });
// Adjust before commit, so a new label cannot paint once before its entry state.
// Reuse the previous incoming key: a rapid change exits from its current pose.
if (frame.text !== text) setFrame({
text, id: frame.id + 1, phase: allowed ? 'start' : 'idle',
outgoing: allowed ? { text: frame.text, id: frame.id } : null,
});
useEffect(() => {
const update = () => setVisible(!document.hidden);
const query = window.matchMedia('(forced-colors: active)');
const colors = () => setForcedColors(query.matches);
document.addEventListener('visibilitychange', update);
query.addEventListener('change', colors);
return () => { document.removeEventListener('visibilitychange', update); query.removeEventListener('change', colors); };
}, []);
useLayoutEffect(() => {
const id = frame.id;
const settle = () => setFrame(current => current.id === id && current.outgoing
? { ...current, phase: 'idle', outgoing: null } : current);
if (!allowed) { settle(); return; }
if (!frame.outgoing || !ref.current) return;
// Commit the supplied .is-enter-start pose before releasing CSS transitions.
ref.current.getBoundingClientRect();
let timer = 0;
const tick = requestAnimationFrame(() => {
setFrame(current => current.id === id ? { ...current, phase: 'running' } : current);
timer = window.setTimeout(settle, 200); // 150ms swap + 50ms incoming gap.
});
return () => { cancelAnimationFrame(tick); window.clearTimeout(timer); };
}, [frame.id, allowed]);
const active = shimmer && allowed;
const swapping = allowed && frame.outgoing !== null;
return <span className={css.statusText} data-reader-status data-reader-busy={shimmer} data-ud-check="reader-status">
<span className={css.think} aria-hidden="true" data-active={active} data-reader-status-phase={swapping ? frame.phase : 'idle'} data-ud-motion="reader-thinking-state">
<span className={css.thinkSizer}>{text}</span>
{swapping && <span key={frame.outgoing!.id} className={`${css.thinkText} ${frame.phase === 'running' ? css.isExit : ''}`}
data-reader-status-copy="outgoing" data-text={frame.outgoing!.text}>{frame.outgoing!.text}</span>}
<span key={frame.id} ref={ref} className={`${css.thinkText} ${swapping && frame.phase === 'start' ? css.isEnterStart : ''}`}
data-reader-status-copy="current" data-reader-shimmer={active || undefined} data-text={text}>{text}</span>
</span>
<span className={css.srOnly} role="status" aria-live="polite" aria-atomic="true">{text}</span>
</span>;
}
export function Disclosure({ open, onChange, label, controls, buttonRef, ariaLabel }: {
open: boolean; onChange: (value: boolean) => void; label: ReactNode;
controls?: string; buttonRef?: RefObject<HTMLButtonElement>;
ariaLabel?: string;
}) {
const name = ariaLabel ?? '思考与过程';
return <div className={css.disclosure} data-reader-disclosure data-expanded={open}>
<button ref={buttonRef} type="button" className={css.disclosureButton} aria-label={`${open ? '收起' : '展开'}${name}`} aria-expanded={open} {...(controls ? { 'aria-controls': controls } : {})} onClick={() => onChange(!open)}>
{label}
<svg className={css.chevron} data-open={open} viewBox="0 0 16 16" width="12" height="12" aria-hidden="true"><path d="m6 4 4 4-4 4" /></svg>
</button>
</div>;
}
/** Supplemental details stay in source order beside their own narration. */
export function ProcessFragment({ open, motion, onRead, returnFocusTo, nodeKey, children, framed = false }: {
open: boolean; motion: boolean; onRead: () => void; nodeKey: string;
returnFocusTo: RefObject<HTMLElement>; children: ReactNode; framed?: boolean;
}) {
const body = useRef<HTMLDivElement>(null);
const running = useRef<Animation | null>(null);
const previous = useRef(open);
const [present, setPresent] = useState(open);
useLayoutEffect(() => {
const element = body.current;
if (!element) return;
const from = running.current ? element.getBoundingClientRect().height : previous.current ? element.scrollHeight : 0;
running.current?.cancel();
running.current = null;
const changed = previous.current !== open;
previous.current = open;
if (open) setPresent(true);
if (!open && element.contains(document.activeElement)) returnFocusTo.current?.focus();
element.style.height = open ? 'auto' : '0px';
const target = open ? element.scrollHeight : 0;
if (!motion || !changed || Math.abs(from - target) < 1) {
setPresent(open);
return;
}
const animation = element.animate(
from > target
? [
{ offset: 0, height: `${from}px`, opacity: 1, transform: 'scaleY(1) translateY(0)' },
{ offset: 0.32, height: `${Math.round(from * 0.92)}px`, opacity: 0.35, transform: 'scaleY(0.96) translateY(-2px)' },
{ offset: 1, height: `${target}px`, opacity: 0, transform: 'scaleY(0.68) translateY(-8px)' },
]
: [
{ offset: 0, height: `${from}px`, opacity: 0, transform: 'scaleY(0.8) translateY(6px)' },
{ offset: 0.3, height: `${Math.round(target * 0.4)}px`, opacity: 0.4, transform: 'scaleY(0.92) translateY(3px)' },
{ offset: 1, height: `${target}px`, opacity: 1, transform: 'scaleY(1) translateY(0)' },
],
{ duration: 380, easing: 'cubic-bezier(0.16, 1, 0.3, 1)', fill: 'both' },
);
running.current = animation;
let settled = false;
const settle = () => {
if (settled) return;
settled = true;
if (running.current === animation) running.current = null;
animation.cancel();
setPresent(open);
};
animation.onfinish = settle;
// `fill: 'both'\` pins the opening keyframe (height 0, opacity 0), so while this
// animation runs the body is *invisible* no matter what the element's style says.
// An animation that never finishes — cancelled by a re-run, an unmount, or a
// compositor that drops it — would then leave the row looking like it refused to
// open, which is exactly the reported symptom. Cancel is only safe once the
// state change has been committed, so the deadline does both.
const deadline = window.setTimeout(settle, 380 + 240);
return () => {
window.clearTimeout(deadline);
running.current?.cancel();
};
}, [open, motion, returnFocusTo]);
if (!open && !present) return null;
return <div ref={body} className={css.disclosureBody} data-reader-process data-reader-process-key={nodeKey} data-ud-motion="reader-process-size"
aria-hidden={!open} onPointerDown={() => { if (open) onRead(); }} onFocusCapture={() => { if (open) onRead(); }} {...(!open ? { inert: '' } : {})}>
<div className={framed ? css.processFrame : css.processContents}>{children}</div>
</div>;
}
/** Retire only narration that was actually visible; historical rows stay folded. */
export function RetiringContent({ visible, children, onRetired }: { visible: boolean; children: ReactNode; onRetired?: () => void }) {
const { enabled } = useContext(StreamMotionContext);
const root = useRef<HTMLDivElement>(null);
const animation = useRef<Animation | null>(null);
const [present, setPresent] = useState(visible);
const [focusHeld, setFocusHeld] = useState(false);
// Held in a ref so a caller passing an inline closure does not restart the
// collapse every render, and so the settle path always sees the latest one.
const retired = useRef(onRetired);
retired.current = onRetired;
useLayoutEffect(() => {
const element = root.current;
if (visible) {
animation.current?.cancel(); animation.current = null;
setPresent(true);
return;
}
if (!element) return;
// Reduced motion and a hidden page settle immediately. Focus may defer a
// collapse that will actually play; it must not pin a reduced-motion rewind.
// Move it to a surviving turn or the reading column first, or the browser
// drops it on the document when this subtree unmounts.
let retiredNow = false;
const retireNow = () => {
if (retiredNow) return;
retiredNow = true;
animation.current?.cancel(); animation.current = null;
focusSurvivesRetire(element);
setPresent(false); retired.current?.();
};
if (!enabled || document.hidden) { retireNow(); return; }
// The retiring-content harness stubs document without addEventListener.
const canListen = typeof document.addEventListener === 'function';
const holdsFocus = element.contains(document.activeElement);
if (holdsFocus || focusHeld) {
if (holdsFocus) setFocusHeld(true);
// Focus defers only a collapse that will play. `document.hidden` is not
// state, so a page hidden while focus waits must retire from here.
const onHiddenWhileHeld = () => { if (document.hidden) retireNow(); };
if (canListen) document.addEventListener('visibilitychange', onHiddenWhileHeld);
return () => { if (canListen) document.removeEventListener('visibilitychange', onHiddenWhileHeld); };
}
const from = element.getBoundingClientRect().height;
animation.current?.cancel(); animation.current = null;
if (from < 1) { setPresent(false); retired.current?.(); return; }
const next = element.animate([{ height: `${from}px`, opacity: 1 }, { height: '0px', opacity: 0 }], { duration: 220, easing: EASING, fill: 'both' });
animation.current = next;
let settled = false;
const settle = () => {
if (settled || animation.current !== next) return;
settled = true;
animation.current = null; next.cancel(); setPresent(false); retired.current?.();
};
next.onfinish = settle;
// #60: a stalled WAAPI finish must not leave the row mounted.
const deadline = window.setTimeout(settle, 220 + 240);
const onHide = () => { if (document.hidden) settle(); };
if (canListen) document.addEventListener('visibilitychange', onHide);
return () => {
window.clearTimeout(deadline);
if (canListen) document.removeEventListener('visibilitychange', onHide);
if (animation.current === next) animation.current = null;
next.cancel();
};
}, [visible, enabled, focusHeld]);
useEffect(() => () => animation.current?.cancel(), []);
if (!visible && !present) return null;
return <div ref={root} className={css.retiringContent} data-reader-retiring={visible ? 'visible' : 'retiring'} data-ud-motion="reader-progress-retire"
onBlur={event => { if (!event.currentTarget.contains(event.relatedTarget)) setFocusHeld(false); }}>
{children}
</div>;
}
/**
* Keeps a departing turn mounted for the length of its own collapse.
*
* A rewind removes turns from the visible order, and unmounting them outright
* snapped the transcript: every withdrawn row disappeared in one frame with
* nothing to scroll. Instead each departing turn is retained, rendered with
* `visible={false}` so it animates to zero height, and released only once the
* collapse has settled — so the reader watches the rows fold away and the rows
* below glide up into their place.
*
* Live slots follow the incoming group order, so older history stays above the
* tail. A collapsing turn stays next to the live neighbour that preceded it;
* appending it would jump it to the bottom for the length of the animation.
* Retention is bounded by the animation itself: `onRetired`
* drops the slot, so a departing turn lives for one collapse and no longer —
* and a key that comes back later is re-added as a live slot.
*/
export function RetiringTurns<T extends { readonly key: string }>({ groups, render }: {
groups: readonly T[];
render: (group: T) => ReactNode;
}) {
const [slots, setSlots] = useState<readonly TurnSlot<T>[]>(() =>
groups.map((group) => ({ group, live: true })),
);
// Reconcile after every commit rather than during render: a key that left the
// order becomes `live: false` and keeps its index, which is what lets the
// collapse play in place instead of jumping the turn to the bottom.
useLayoutEffect(() => {
setSlots(current => reconcileTurnSlots(current, groups));
}, [groups]);
return (
<>
{slots.map((slot) => (
<RetiringContent
key={slot.group.key}
visible={slot.live}
onRetired={() => setSlots((current) => current.filter((candidate) =>
candidate.live || candidate.group.key !== slot.group.key))}
>
{render(slot.group)}
</RetiringContent>
))}
</>
);
}
/** A turn that is still on screen, not one this commit is about to unmount. */
function survivingTurn(node: Element): HTMLElement | null {
if (!(node instanceof HTMLElement) || node.dataset.readerRetiring === 'retiring') return null;
const turn = node.hasAttribute('data-reader-turn') ? node : node.querySelector<HTMLElement>('[data-reader-turn]');
if (turn === null) return null;
const retiring = turn.closest('[data-reader-retiring]');
if (retiring instanceof HTMLElement && retiring.dataset.readerRetiring === 'retiring') return null;
return turn;
}
/**
* Where focus goes when cut content is removed without an animation.
* Prefer the nearest turn that is still live. Otherwise the reading column
* (or the host scrollport) so focus does not fall through to the document.
*/
function retireFocusTarget(element: HTMLElement): HTMLElement | null {
const parent = element.parentElement;
if (parent) {
const siblings = [...parent.children];
const index = siblings.indexOf(element);
for (let cursor = index - 1; cursor >= 0; cursor--) {
const turn = survivingTurn(siblings[cursor]!);
if (turn) return turn;
}
for (let cursor = index + 1; cursor < siblings.length; cursor++) {
const turn = survivingTurn(siblings[cursor]!);
if (turn) return turn;
}
}
const column = element.closest<HTMLElement>('[data-chat-flow]');
if (column && !element.contains(column)) return column;
const scroll = element.closest<HTMLElement>('[data-conversation-scroll]');
if (scroll && !element.contains(scroll)) return scroll;
return null;
}
/** Move focus out of `element` before it unmounts. A no-op when focus is elsewhere. */
function focusSurvivesRetire(element: HTMLElement): void {
const active = document.activeElement;
if (active === null || !element.contains(active)) return;
const target = retireFocusTarget(element);
if (target === null || element.contains(target)) return;
if (target.tabIndex < 0) target.tabIndex = -1;
target.focus({ preventScroll: true });
}
// DOM-only behavior: the native Session remains the sole source of business data.
export function useReadingScroll(root: RefObject<HTMLElement>, motion: boolean): {
detached: boolean;
jump: () => void;
/** Stop tail-follow so a rail landing is not pulled back to the live bottom. */
release: () => void;
} {
const port = useRef<HTMLElement | null>(null);
const following = useRef(true);
// Tracked separately from `following`: only an explicit reader action clears
// this, so a fold-induced scroll clamp cannot permanently drop the tail.
const pinned = useRef(true);
const anchor = useRef<{ element: HTMLElement; docTop: number } | null>(null);
const cancelFollow = useRef<() => void>(() => {});
const [detached, setDetached] = useState(false);
useLayoutEffect(() => {
const content = root.current;
if (!content) return;
const scroll = content.closest<HTMLElement>('[data-conversation-scroll]') ?? content;
port.current = scroll;
// Browser scroll anchoring moves the viewport on its own as the transcript
// grows, which reads as the page freezing mid-follow.
const previousOverflowAnchor = scroll.style.overflowAnchor;
scroll.style.overflowAnchor = 'none';
let followFrame = 0;
let lastFrameAt = 0;
let layoutDepth = 0;
let lastWrittenTop: number | null = null;
const layoutStart = () => {
layoutDepth++;
cancelAnimationFrame(followFrame); followFrame = 0;
capture();
};
const layoutEnd = () => {
layoutDepth = Math.max(0, layoutDepth - 1);
if (!layoutDepth && following.current && !followFrame) {
lastFrameAt = performance.now(); followFrame = requestAnimationFrame(follow);
}
};
cancelFollow.current = () => {
cancelAnimationFrame(followFrame);
followFrame = 0;
lastWrittenTop = null;
};
const selected = () => {
const selection = document.getSelection();
return selection && !selection.isCollapsed && selection.anchorNode && content.contains(selection.anchorNode);
};
// Only a focused text field suspends tail-follow. Clicking a fold control
// inside the reader also moves document.activeElement into `content`, and
// treating that as "user is busy" froze following for the rest of the turn.
const editingText = () => {
const active = document.activeElement;
if (!(active instanceof HTMLElement)) return false;
// The composer lives outside this subtree: focusing it must never stop
// the transcript from following.
if (!content.contains(active)) return false;
return active.isContentEditable || active.tagName === 'TEXTAREA' || active.tagName === 'INPUT';
};
const capture = () => {
const top = scroll.getBoundingClientRect().top;
const candidates = content.querySelectorAll<HTMLElement>('[data-reader-anchor]');
let candidate: HTMLElement | null = null;
for (let index = 0; index < candidates.length; index++) {
const element = candidates[index];
if (element.getBoundingClientRect().bottom > top + 8) { candidate = element; break; }
}
// Record the anchor in DOCUMENT space, never viewport space. The viewport
// offset also changes whenever the reader scrolls, so comparing it back
// turned a plain scroll into an "anchor correction" that yanked the
// viewport back to wherever the anchor had last been captured.
anchor.current = candidate
? { element: candidate, docTop: candidate.getBoundingClientRect().top + scroll.scrollTop }
: null;
};
// Anchor capture is only consumed while detached; coalesce DOM scans to one per frame.
let captureFrame = 0;
const scheduleCapture = () => {
if (captureFrame) return;
captureFrame = requestAnimationFrame(() => { captureFrame = 0; capture(); });
};
const atBottom = () => scroll.scrollHeight - scroll.scrollTop - scroll.clientHeight < 25;
// Intent to stay pinned to the bottom, tracked independently of the scroll
// position. A fold collapse shrinks the transcript and the browser clamps
// scrollTop, producing a scroll event indistinguishable from the reader
// scrolling up; without this the reader silently detached exactly when the
// turn's last content arrived, and the page stopped following.
pinned.current = true;
const onScroll = () => {
// While a follow animation is actively driving scroll, do not cancel following midway.
if (followFrame !== 0 || layoutDepth > 0) return;
// Our easing frames must not be mistaken for a user leaving the bottom.
if (lastWrittenTop !== null && Math.abs(scroll.scrollTop - lastWrittenTop) < 1) return;
// Bind the follow intent to the position observed HERE. Every scroll that
// reaches this point is the viewport moving under someone else's hand: a
// wheel, a drag, a key, or the browser clamping the offset after a shrink.
//
// The previous form inferred detaching from a strictly upward delta against
// lastWrittenTop, which left two holes. That baseline is nulled by
// cancelFollow/onWheel/onTouch/onKey, and the guard above already returned
// for any scroll whose delta is under 1px — so a reader parked mid-transcript
// by a scrollbar drag stayed following === true AND pinned === true. The next
// content growth then took the re-attach branch and yanked the viewport to
// the bottom, discarding what they were reading. Reading the position
// directly needs no baseline: a fold's clamp lands at the very bottom and
// still keeps following, while any other offset detaches.
const bottom = atBottom();
pinned.current = bottom;
if (!bottom) { cancelAnimationFrame(followFrame); followFrame = 0; scheduleCapture(); }
if (!following.current) {
// Only an explicit return to the bottom resumes following.
if (bottom) { following.current = true; setDetached(false); }
return;
}
if (!bottom) { following.current = false; setDetached(true); }
};
const onWheel = (event: WheelEvent) => {
cancelAnimationFrame(followFrame); followFrame = 0; lastWrittenTop = null;
if (event.deltaY < 0) { following.current = false; setDetached(true); pinned.current = false; scheduleCapture(); }
};
const onTouch = () => {
cancelAnimationFrame(followFrame); followFrame = 0; lastWrittenTop = null;
};
const onKey = (event: KeyboardEvent) => {
if (event.target instanceof HTMLElement && event.target.closest('textarea,input,[contenteditable=true]')) return;
if (['PageUp', 'Home', 'ArrowUp'].includes(event.key)) {
cancelAnimationFrame(followFrame); followFrame = 0; lastWrittenTop = null;
following.current = false; setDetached(true); pinned.current = false; scheduleCapture();
}
};
const writeTop = (top: number) => { scroll.scrollTop = top; lastWrittenTop = scroll.scrollTop; };
const follow = (now: number) => {
followFrame = 0;
if (!following.current || selected() || editingText()) return;
if (layoutDepth > 0) return;
const gap = scroll.scrollHeight - scroll.clientHeight - scroll.scrollTop;
const delta = Math.min(48, Math.max(1, now - lastFrameAt));
lastFrameAt = now;
if (!motion || Math.abs(gap) < 1.5) { writeTop(scroll.scrollHeight); capture(); return; }
writeTop(scroll.scrollTop + gap * (1 - Math.exp(-delta / 52)));
followFrame = requestAnimationFrame(follow);
};
const firstFrame = requestAnimationFrame(() => {
if (following.current && !selected()) writeTop(scroll.scrollHeight);
capture();
});
let lastHeight = content.scrollHeight;
const observer = new ResizeObserver(() => {
if (selected()) return;
const height = scroll.scrollHeight;
const grew = height > lastHeight + 1;
lastHeight = height;
// Growth while the reader intends to be at the bottom re-attaches the
// tail. This is the self-healing path for the clamp case above and is
// also what keeps the viewport moving when a turn ends.
if (grew && pinned.current && !editingText()) { following.current = true; setDetached(false); }
if (following.current && !editingText()) {
// Height is already animated: no second, lagging scroll easing.
if (!motion || layoutDepth > 0) writeTop(scroll.scrollHeight);
else if (!followFrame) { lastFrameAt = performance.now(); followFrame = requestAnimationFrame(follow); }
} else if (!following.current && anchor.current?.element.isConnected) {
// Only a real layout change above the anchor needs compensation. A reader
// scroll moves the viewport offset but not the document offset, so this
// stays silent while the reader is scrolling and cannot snap back.
const delta = anchor.current.element.getBoundingClientRect().top + scroll.scrollTop - anchor.current.docTop;
if (Math.abs(delta) > .5) writeTop(scroll.scrollTop + delta);
}
capture();
});
observer.observe(content);
if (scroll !== content) observer.observe(scroll);
content.addEventListener('reader-layout-start', layoutStart);
content.addEventListener('reader-layout-end', layoutEnd);
scroll.addEventListener('scroll', onScroll, { passive: true });
scroll.addEventListener('wheel', onWheel, { passive: true });
scroll.addEventListener('touchstart', onTouch, { passive: true });
scroll.addEventListener('touchmove', onTouch, { passive: true });
scroll.addEventListener('keydown', onKey);
return () => {
cancelAnimationFrame(firstFrame); cancelAnimationFrame(followFrame); cancelAnimationFrame(captureFrame); observer.disconnect();
content.removeEventListener('reader-layout-start', layoutStart);
content.removeEventListener('reader-layout-end', layoutEnd);
scroll.style.overflowAnchor = previousOverflowAnchor;
scroll.removeEventListener('scroll', onScroll); scroll.removeEventListener('wheel', onWheel);
scroll.removeEventListener('touchstart', onTouch); scroll.removeEventListener('touchmove', onTouch);
scroll.removeEventListener('keydown', onKey);
};
}, [root, motion]);
const jump = useCallback(() => {
cancelFollow.current();
anchor.current = null;
following.current = true;
pinned.current = true;
setDetached(false);
if (port.current) {
port.current.scrollTop = port.current.scrollHeight;
}
}, []);
const release = useCallback(() => {
cancelFollow.current();
following.current = false;
pinned.current = false;
anchor.current = null;
setDetached(true);
}, []);
return { detached, jump, release };
}

View File

@ -0,0 +1,161 @@
/* Expanded context bodies: one code-block surface shared by every form, so the
disclosure keeps the Figma 10:2482 geometry whichever form renders inside. */
.text {
margin: 0;
color: var(--dsw-alias-label-secondary);
font: inherit;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
/* Source fields beneath the text: dimmer than the content they describe. */
.fields {
display: flex;
flex-direction: column;
gap: 2px;
margin: 8px 0 0;
padding-top: 8px;
border-top: 1px solid var(--dsw-alias-line-secondary);
}
.field {
display: flex;
gap: 8px;
min-width: 0;
}
.fieldKey {
flex: none;
min-width: 96px;
color: var(--dsw-alias-label-caption);
}
.fieldValue {
flex: 1 1 auto;
min-width: 0;
margin: 0;
color: var(--dsw-alias-label-tertiary);
overflow-wrap: anywhere;
}
/* instructions: the reconciled files, above their text. */
.files {
display: flex;
flex-wrap: wrap;
gap: 4px 12px;
margin: 0 0 8px;
padding: 0;
list-style: none;
}
.file {
display: flex;
align-items: baseline;
gap: 6px;
min-width: 0;
}
.filePath {
color: var(--dsw-alias-label-secondary);
overflow-wrap: anywhere;
}
.fileAction {
color: var(--dsw-alias-label-caption);
}
/* catalog: a replacement notice above one row per published entry. */
.catalogNotice {
margin: 0 0 6px;
color: var(--dsw-alias-label-caption);
}
.entries {
display: flex;
flex-direction: column;
gap: 4px;
margin: 0;
padding: 0;
list-style: none;
}
.entry {
display: flex;
gap: 8px;
min-width: 0;
}
.entryName {
flex: none;
color: var(--dsw-alias-label-secondary);
}
.entryDescription {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
color: var(--dsw-alias-label-tertiary);
text-overflow: ellipsis;
white-space: nowrap;
}
/* snapshot: one titled block per contributing subsystem. */
.sections {
display: flex;
flex-direction: column;
gap: 8px;
margin: 0;
}
.section {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.sectionName {
color: var(--dsw-alias-label-caption);
}
.sectionText {
margin: 0;
color: var(--dsw-alias-label-secondary);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
/* relay: who sent this, above what they said. */
.relaySender {
margin: 0 0 6px;
color: var(--dsw-alias-label-caption);
overflow-wrap: anywhere;
}
/* recall: one row per source session, with how much of it survived. */
.recalls {
display: flex;
flex-direction: column;
gap: 2px;
margin: 0 0 8px;
padding: 0;
list-style: none;
}
.recall {
display: flex;
gap: 8px;
min-width: 0;
}
.recallLabel {
color: var(--dsw-alias-label-secondary);
overflow-wrap: anywhere;
}
.recallCounts {
flex: none;
color: var(--dsw-alias-label-caption);
}

View File

@ -0,0 +1,591 @@
// Expanded bodies for the context disclosure, one per durable context form.
// The producer declares the form; this module only chooses a presentation for
// it. Every form falls back to OpaqueBody, which is the documented default for
// an absent, unknown, or malformed form — a resumed or foreign log must render
// even when this UI version has never seen its producer.
import type { ReactNode } from 'react'
import type { ContextMessageNode, KnownContextForm } from '@deepseek-ai/dsh-client-ui-conversation/client'
import { JsonBlock } from '@deepseek-ai/dsh-client-ui-primitives'
import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
import css from './ContextBody.module.css'
/** Model-facing text stays bounded at the disclosure, not at the producer. */
const MAX_CHARS = 20_000
/** Rows a list body materializes before summarizing the remainder. */
const MAX_ENTRIES = 200
type Translate = TranslateNS<'chat'>
/** One durable source narrowed to the readable-record shape; null for anything else. */
function asRecord(value: unknown): Record<string, unknown> | null {
return typeof value === 'object' && value !== null && !Array.isArray(value)
? value as Record<string, unknown>
: null
}
/** One run of the model-facing content: adjacent text, or one unknown block. */
type ContentRun = { text: string } | { block: unknown }
/**
* The content blocks as runs, IN THE ORDER the model received them.
*
* Adjacent text blocks join with no separator, matching how provider adapters
* flatten them — inserting a line break would show the reader a line the model
* never saw. An unknown block breaks the run and keeps its own fallback rather
* than being hoisted past the text around it or vanishing; the block union is
* merge-extensible, so a foreign log may interleave shapes this build does not
* know.
*/
function contentRuns(content: ContextMessageNode['content']): ContentRun[] {
const runs: ContentRun[] = []
for (const block of content) {
if (block.type !== 'text') {
runs.push({ block })
continue
}
const last = runs[runs.length - 1]
if (last !== undefined && 'text' in last) last.text += block.text
else runs.push({ text: block.text })
}
return runs
}
/** Only the blocks this UI version does not know, for bodies that replace the text. */
function unknownBlocks(content: ContextMessageNode['content']): unknown[] {
return contentRuns(content).flatMap(run => 'block' in run ? [run.block] : [])
}
/** The model-facing text, truncated to the display bound. */
function boundedText(text: string, t: Translate): string {
return text.length > MAX_CHARS
? `${text.slice(0, MAX_CHARS)}\n${t('json.truncated', { total: text.length })}`
: text
}
/**
* One source field rendered as a value row; nested shapes stay compact JSON.
* Bounded on its own, because source fields are as unbounded as the text: an unknown
* producer may record an arbitrarily large string or array.
*/
function fieldValue(value: unknown, t: Translate): string {
const text = typeof value === 'string'
? value
: typeof value === 'number' || typeof value === 'boolean' ? String(value) : JSON.stringify(value)
return boundedText(text, t)
}
/**
* Source fields as a key/value list. `kind` is always omitted because the
* row header already names the producer. `form` is omitted only when a
* dedicated body rendered for it — then the presentation the reader is looking
* at IS that value. On the opaque fallback the declaration is kept, because
* that is the one place a form this version cannot present would otherwise
* disappear from the UI entirely.
*/
function SourceFields({ source, formRendered, t }: {
source: unknown
formRendered: boolean
t: Translate
}): ReactNode {
const record = asRecord(source)
if (record === null) return null
const hidden = formRendered ? ['kind', 'form'] : ['kind']
const rows = Object.entries(record).filter(([key]) => !hidden.includes(key))
if (rows.length === 0) return null
return (
<dl className={css.fields} data-context-fields>
{rows.map(([key, value]) => (
<div key={key} className={css.field}>
<dt className={css.fieldKey}>{key}</dt>
<dd className={css.fieldValue}>{fieldValue(value, t)}</dd>
</div>
))}
</dl>
)
}
/**
* Content blocks this UI version does not know, kept visible rather than
* dropped: the block union is merge-extensible, so a newer or foreign log may
* carry a shape this build has no presentation for.
* @param props - The unrecognized blocks and the locale seat.
* @returns One generic JSON block per unknown entry.
*/
function UnknownBlocks({ blocks, t }: { blocks: readonly unknown[]; t: Translate }): ReactNode {
return (
<>
{blocks.map((block, index) => (
<JsonBlock
key={index}
label={t('message.unknownBlock')}
payload={block}
truncatedLabel={total => t('json.truncated', { total })}
/>
))}
</>
)
}
/**
* The model-facing content of one context, shared by every form that shows it:
* the text with its real line breaks, then any block this UI version does not
* know, which keeps its own fallback rather than vanishing.
* @param props - Durable content and the locale seat.
* @returns The content blocks as the model received them.
*/
function ModelFacingContent({ content, t }: {
content: ContextMessageNode['content']
t: Translate
}): ReactNode {
return (
<>
{contentRuns(content).map((run, index) => ('text' in run
? run.text !== '' && (
<pre key={index} className={css.text} data-context-text>{boundedText(run.text, t)}</pre>
)
: (
<JsonBlock
key={index}
label={t('message.unknownBlock')}
payload={run.block}
truncatedLabel={total => t('json.truncated', { total })}
/>
)))}
</>
)
}
/**
* Default presentation: the model-facing text as text, with its real line
* breaks, and the remaining source fields beneath it. This is what every form
* this UI version does not recognize renders as.
* @param props - Durable content, its source, and the locale seat.
* @returns The opaque context body.
*/
export function OpaqueBody({ content, source, t }: {
content: ContextMessageNode['content']
source: unknown
t: Translate
}): ReactNode {
return (
<>
<ModelFacingContent content={content} t={t} />
<SourceFields source={source} formRendered={false} t={t} />
</>
)
}
/** One reconciled instruction file, as the durable source records it. */
interface InstructionChange {
action: 'set' | 'replace' | 'remove'
path: string
digest?: string
}
/**
* Instruction changes read off the source, or null when the record is not a
* usable instruction list.
*
* The read is all-or-nothing: silently dropping one unreadable entry would show
* a confident, incomplete file list for a log this version cannot fully read.
* Paths are deduplicated in first-seen order, matching how the header label is
* derived from the same array.
*/
function instructionChanges(source: unknown): InstructionChange[] | null {
const record = asRecord(source)
const list = record === null ? undefined : record['changes']
if (!Array.isArray(list)) return null
const changes: InstructionChange[] = []
const seen = new Set<string>()
for (const entry of list as readonly unknown[]) {
const change = asRecord(entry)
if (change === null) return null
const path = change['path']
if (typeof path !== 'string' || path === '') return null
const action = change['action']
// The action decides which word the row shows, so an unrecognized one is
// not a readable change — it would be presented as loaded or updated.
if (action !== 'set' && action !== 'replace' && action !== 'remove') return null
const digest = change['digest']
if (seen.has(path)) continue
seen.add(path)
changes.push({ action, path, ...typeof digest === 'string' ? { digest } : {} })
}
return changes.length === 0 ? null : changes
}
/**
* Locale key for one reconciled file. The baseline loads a file; a later delta
* distinguishes a newly reconciled path from a rewritten one, which `set` and
* `replace` already separate at the producer.
* @param action - the durable change action.
* @param baseline - whether this context is the startup/resume baseline.
* @returns the key naming what happened to that file.
*/
function instructionAction(
action: InstructionChange['action'],
baseline: boolean,
): 'message.context.instructions.removed' | 'message.context.instructions.loaded'
| 'message.context.instructions.added' | 'message.context.instructions.updated' {
if (action === 'remove') return 'message.context.instructions.removed'
if (baseline) return 'message.context.instructions.loaded'
return action === 'set' ? 'message.context.instructions.added' : 'message.context.instructions.updated'
}
/**
* `instructions` form: the files this context reconciled, then their text.
*
* The text keeps its `<system-reminder>` framing verbatim — the framing is part
* of what the model read, so hiding it would misreport the request.
* @param props - Durable content, its source, and the locale seat.
* @returns The instructions context body, or the opaque body when the change
* list is unreadable.
*/
export function InstructionsBody({ content, source, t }: {
content: ContextMessageNode['content']
source: unknown
t: Translate
}): ReactNode {
const changes = instructionChanges(source)
if (changes === null) return <OpaqueBody content={content} source={source} t={t} />
const baseline = asRecord(source)?.['baseline'] === true
return (
<>
<ul className={css.files} data-context-files>
{changes.map(change => (
<li key={change.path} className={css.file} title={change.digest}>
<span className={css.filePath}>{change.path}</span>
<span className={css.fileAction}>
{t(instructionAction(change.action, baseline))}
</span>
</li>
))}
</ul>
<ModelFacingContent content={content} t={t} />
</>
)
}
/** One catalog entry, as the durable source records it. */
interface CatalogEntry {
name: string
description: string
}
/**
* Catalog entries read off the source, or null when the record is not a usable
* catalog. All-or-nothing for the same reason as the instruction list: this body
* replaces the model-facing text, so a partial list would hide the only complete
* account of what the model read.
*/
function catalogEntries(source: unknown): CatalogEntry[] | null {
const record = asRecord(source)
const list = record === null ? undefined : record['entries']
if (!Array.isArray(list)) return null
const entries: CatalogEntry[] = []
for (const item of list as readonly unknown[]) {
const entry = asRecord(item)
if (entry === null) return null
const name = entry['name']
const description = entry['description']
if (typeof name !== 'string' || name === '' || typeof description !== 'string') return null
entries.push({ name, description })
}
// An empty list is a real catalog: a replacement with no entries retires
// every earlier name. Only an unreadable shape falls back.
return entries
}
/**
* `catalog` form: the published entries as a list, read from the source rather
* than re-parsed out of the model-facing prose.
*
* A catalog whose source carries no usable entries falls through to the opaque
* body, so an older or hand-edited log still shows its text.
* @param props - Durable content, its source, and the locale seat.
* @returns The catalog context body, or the opaque body when the entry list is
* unreadable.
*/
export function CatalogBody({ content, source, t }: {
content: ContextMessageNode['content']
source: unknown
t: Translate
}): ReactNode {
const entries = catalogEntries(source)
if (entries === null) return <OpaqueBody content={content} source={source} t={t} />
const update = asRecord(source)?.['update'] === true
// Entry count is unbounded (a provider may publish any number of skills), and
// the scrollport bounds height, not node count — so the list bounds itself.
const shown = entries.slice(0, MAX_ENTRIES)
const rest = unknownBlocks(content)
return (
<>
{update && <p className={css.catalogNotice} data-context-catalog-update>{t('message.context.catalog.replaced')}</p>}
<ul className={css.entries} data-context-entries>
{shown.map((entry, index) => (
// Index key: a hand-edited or foreign log may repeat a name, and a
// duplicate React key would drop a row the model did see.
<li key={index} className={css.entry}>
<code className={css.entryName}>{entry.name}</code>
<span className={css.entryDescription}>{entry.description}</span>
</li>
))}
</ul>
{shown.length < entries.length && (
<p className={css.catalogNotice} data-context-entries-truncated>
{t('message.context.catalog.more', { count: entries.length - shown.length })}
</p>
)}
{/* The block union is merge-extensible: a catalog message carrying an
unknown block still shows it rather than dropping model-visible content. */}
<UnknownBlocks blocks={rest} t={t} />
</>
)
}
/** One named contribution to a runtime snapshot, as the durable source records it. */
interface SnapshotSection {
name: string
text: string
}
/** Snapshot sections read off the source, or null when the record is unusable. */
function snapshotSections(source: unknown): SnapshotSection[] | null {
const record = asRecord(source)
const list = record === null ? undefined : record['sections']
if (!Array.isArray(list)) return null
const sections: SnapshotSection[] = []
for (const item of list as readonly unknown[]) {
const section = asRecord(item)
if (section === null) return null
const name = section['name']
const text = section['text']
if (typeof name !== 'string' || name === '' || typeof text !== 'string') return null
sections.push({ name, text })
}
return sections.length === 0 ? null : sections
}
/**
* `snapshot` form: the named contributions this snapshot assembled, in order.
*
* The sections are the same bytes the model read, split at the boundaries the
* producer assembled them on, so a reader sees which subsystem contributed
* which state instead of one undifferentiated wall.
*
* One sentence of the model-facing text is NOT in any section: the producer's
* framing line declaring that this snapshot supersedes earlier ones. Unlike the
* `<system-reminder>` wrapper an instruction context carries — which wraps
* content and cannot be separated from it — that line states the form's own
* semantics, so the body states them as a caption instead of reprinting the
* joined prose beside the sections it was split from.
* @param props - Durable content, its source, and the locale seat.
* @returns The snapshot context body, or the opaque body when unreadable.
*/
export function SnapshotBody({ content, source, t }: {
content: ContextMessageNode['content']
source: unknown
t: Translate
}): ReactNode {
const sections = snapshotSections(source)
/* v8 ignore next -- contextBody reads the sections before choosing this body. */
if (sections === null) return <OpaqueBody content={content} source={source} t={t} />
return (
<>
<p className={css.catalogNotice} data-context-snapshot-supersedes>
{t('message.context.snapshot.supersedes')}
</p>
<dl className={css.sections} data-context-sections>
{sections.map((section, index) => (
<div key={index} className={css.section}>
<dt className={css.sectionName}>{section.name}</dt>
<dd className={css.sectionText}>{boundedText(section.text, t)}</dd>
</div>
))}
</dl>
</>
)
}
/**
* `notice` form: what just happened, with the model-facing text beneath it.
*
* The one-line account also rides the collapsed row ({@link contextBody}), so a
* notice is usually readable without expanding at all.
* @param props - Durable content, its source, and the locale seat.
* @returns The notice context body.
*/
export function NoticeBody({ content, t }: {
content: ContextMessageNode['content']
source: unknown
t: Translate
}): ReactNode {
return <ModelFacingContent content={content} t={t} />
}
/**
* `relay` form: which agent sent this, then what it said.
*
* The sender is an opaque session id; it is shown as a field rather than a
* label, because this client cannot resolve it to a title.
* @param props - Durable content, its source, and the locale seat.
* @returns The relay context body.
*/
export function RelayBody({ content, source, t }: {
content: ContextMessageNode['content']
source: unknown
t: Translate
}): ReactNode {
const sender = relaySender(source)
/* v8 ignore next -- contextBody resolves the sender before choosing this body. */
if (sender === null) return <OpaqueBody content={content} source={source} t={t} />
return (
<>
<p className={css.relaySender} data-context-relay-sender>
{t('message.context.relay.from', { session: sender })}
</p>
<ModelFacingContent content={content} t={t} />
</>
)
}
/** The sending agent's session id, or null when the record does not name one. */
function relaySender(source: unknown): string | null {
const sender = asRecord(source)?.['senderSessionId']
return typeof sender === 'string' && sender !== '' ? sender : null
}
/** One recalled session, as the durable source records it. */
interface RecalledSession {
label: string
retained: number
omitted: number
truncated: boolean
}
/** Recalled sessions read off the source, or null when the record is unusable. */
function recalledSessions(source: unknown): RecalledSession[] | null {
const record = asRecord(source)
const list = record === null ? undefined : record['references']
if (!Array.isArray(list)) return null
const sessions: RecalledSession[] = []
for (const item of list as readonly unknown[]) {
const reference = asRecord(item)
if (reference === null) return null
const label = reference['label']
const retained = reference['retainedMessages']
const omitted = reference['omittedMessages']
const truncated = reference['truncated']
// Completeness is the fact this card exists to report, so a reference that
// cannot state it is not a readable recall — showing the label alone would
// present a confident card over unknown loss.
if (typeof label !== 'string' || label === ''
|| typeof retained !== 'number' || typeof omitted !== 'number'
|| typeof truncated !== 'boolean') return null
sessions.push({ label, retained, omitted, truncated })
}
return sessions.length === 0 ? null : sessions
}
/**
* `recall` form: which sessions this material came from and how much of each
* survived the read, then the material itself.
*
* Completeness is the fact a reader needs first: recalled context is bounded on
* the way in, so a card that hid the omitted count would overstate what the
* model received.
* @param props - Durable content, its source, and the locale seat.
* @returns The recall context body, or the opaque body when unreadable.
*/
export function RecallBody({ content, source, t }: {
content: ContextMessageNode['content']
source: unknown
t: Translate
}): ReactNode {
const sessions = recalledSessions(source)
if (sessions === null) return <OpaqueBody content={content} source={source} t={t} />
return (
<>
<ul className={css.recalls} data-context-recalls>
{sessions.map((session, index) => (
<li key={index} className={css.recall}>
<span className={css.recallLabel}>{session.label}</span>
<span className={css.recallCounts}>
{t('message.context.recall.counts', {
retained: session.retained,
omitted: session.omitted,
})}
</span>
{session.truncated && (
<span className={css.recallCounts}>{t('message.context.recall.truncated')}</span>
)}
</li>
))}
</ul>
<ModelFacingContent content={content} t={t} />
</>
)
}
/** The one-line account a `notice` puts on its collapsed row, when it records one. */
function noticeSummary(source: unknown): string | null {
const summary = asRecord(source)?.['summary']
return typeof summary === 'string' && summary !== '' ? summary : null
}
/**
* Choose the body for one context node.
*
* Returns the form the body actually rendered as, which is not always the
* declared one: a declared form whose fields are unreadable falls back to
* opaque, and the caller labels the row with what it really shows.
* `summary` is the collapsed row's one-line account, which only a `notice`
* records: its whole point is being readable without expanding.
* @param form - the producer-declared form projected onto the node.
* @param props - durable content, its source, and the locale seat.
* @returns the rendered form (null for opaque), its collapsed summary, and its body.
*/
export function contextBody(
form: ContextMessageNode['form'],
props: { content: ContextMessageNode['content']; source: unknown; t: Translate },
): { rendered: KnownContextForm | null; summary: string | null; body: ReactNode } {
const opaque = { rendered: null, summary: null, body: <OpaqueBody {...props} /> }
switch (form) {
case 'instructions':
return instructionChanges(props.source) === null
? opaque
: { rendered: 'instructions', summary: null, body: <InstructionsBody {...props} /> }
case 'catalog':
return catalogEntries(props.source) === null
? opaque
: { rendered: 'catalog', summary: null, body: <CatalogBody {...props} /> }
case 'snapshot':
return snapshotSections(props.source) === null
? opaque
: { rendered: 'snapshot', summary: null, body: <SnapshotBody {...props} /> }
case 'notice': {
const summary = noticeSummary(props.source)
return summary === null
? opaque
: { rendered: 'notice', summary, body: <NoticeBody {...props} /> }
}
case 'relay':
return relaySender(props.source) === null
? opaque
: { rendered: 'relay', summary: null, body: <RelayBody {...props} /> }
case 'recall':
return recalledSessions(props.source) === null
? opaque
: { rendered: 'recall', summary: null, body: <RecallBody {...props} /> }
case null:
return opaque
/* v8 ignore next 4 -- closed-union backstop; the compiler rejects a new
KnownContextForm here rather than letting it degrade to opaque silently. */
default: {
const unreachable: never = form
throw new Error(`unreachable context form: ${String(unreachable)}`)
}
}
}

View File

@ -0,0 +1,66 @@
/* Figma 10:2482: 24px Tool calls header, 4px gap, 141px code block cap. */
.root {
min-width: 0;
}
.root[data-open] {
padding-bottom: 4px;
}
.chevron {
color: var(--dsw-alias-label-secondary);
}
/* Separator and producer name beside the role title: ToolRow's summary geometry,
so the two disclosure rows keep one 24px rhythm and one separator shape. */
.sep {
flex: none;
width: 2px;
height: 2px;
margin: 0 8px;
border-radius: 1px;
background: var(--dsw-alias-label-caption);
}
.source {
flex: none;
min-width: 0;
overflow: hidden;
color: var(--dsw-alias-label-tertiary);
font-size: 14px;
line-height: 24px;
text-overflow: ellipsis;
white-space: nowrap;
}
/* A notice's one-line account: the reason it rarely needs expanding. */
.summary {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
color: var(--dsw-alias-label-tertiary);
font-size: 14px;
line-height: 24px;
text-overflow: ellipsis;
white-space: nowrap;
}
.body {
box-sizing: border-box;
width: calc(100% - 22px);
max-height: 141px;
margin: 4px 0 0 22px;
overflow: auto;
padding: 10px 16px 12px 12px;
border: none;
border-radius: 8px;
background: var(--dsw-alias-markdown-code-block);
color: var(--dsw-alias-label-tertiary);
/* Figma 10:2482 code text: the form bodies inherit it from the scrollport. */
font: 400 11px/16px var(--ds-font-family-code);
}
.toolChanges {
white-space: nowrap;
}

View File

@ -0,0 +1,106 @@
import { useState } from 'react'
import type { ContextMessageNode } from '@deepseek-ai/dsh-client-ui-conversation/client'
import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
import { DisclosureRow, IconBrowseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'
import { ReferenceIcon } from './ReferenceIcon.js'
import { contextBody } from './ContextBody.js'
import { toolUpdateRows } from './tool-update.js'
import css from './ContextInjectionRow.module.css'
/** Props for the logged non-user message presentation. */
export interface ContextInjectionRowProps {
content: ContextMessageNode['content']
source: ContextMessageNode['source']
/**
* Role and producer name projected from the durable source.
*
* Host generations disagree on the field name: newer builds project
* `provenance`, the 0.1.6-alpha generations project `producer`. Both are
* optional here and resolved below, so the row renders on either host instead
* of throwing on `undefined.role` and degrading its whole block boundary.
*/
provenance?: ContextMessageNode['producer'] | null
/** Alpha-generation spelling of {@link provenance}. */
producer?: ContextMessageNode['producer'] | null
/** Producer-declared information form; null renders the opaque body. */
form: ContextMessageNode['form']
/** The owning view's locale seat, passed down as a plain prop. */
t: TranslateNS<'chat'>
}
/**
* Render logged context with the Tool calls disclosure chrome from Figma.
*
* The header names the role the context plays and, beside it, the producer the
* durable source identifies, so a reader can tell an injected skill catalog
* from a workspace instruction file or a recalled session without expanding.
* The expanded body follows the producer-declared form; an absent or unknown
* form renders the opaque body.
* @param props - Durable content, its projected producer role/name and form, and the locale seat.
* @returns A collapsed context row with a bounded, form-specific body.
*/
export function ContextInjectionRow({ content, source, provenance, producer, form, t }: ContextInjectionRowProps) {
const [open, setOpen] = useState(false)
// Two host generations, one component. A row whose projection is absent
// entirely still renders: the marker falls back to a plain injection.
const view = provenance ?? producer ?? { role: 'inject' as const, label: null }
// Resolved rather than declared: a form whose fields are unreadable renders
// the opaque body, and the marker must say what the row actually shows.
const { rendered, summary, body } = contextBody(form, { content, source, t })
const tools = toolUpdateRows(content)
const toolSummary = tools === null || tools.single !== null ? null
: tools.added.length > 0 && tools.removed.length > 0
? t('message.toolsChanged', { added: tools.added.length, removed: tools.removed.length })
: tools.added.length > 0
? t('message.toolsAddedCount', { count: tools.added.length })
: t('message.toolsRemovedCount', { count: tools.removed.length })
return (
<DisclosureRow
className={css.root}
icon={view.role === 'recall' && tools === null
? <span data-context-recall-icon><ReferenceIcon kind="session" /></span>
: <IconBrowseOutlineRegular size={14} />}
chevronClassName={css.chevron}
title={tools?.single !== undefined && tools.single !== null
? t(tools.single.type === 'tool-addition' ? 'message.toolAdded' : 'message.toolRemoved', { name: tools.single.toolName })
: tools !== null
? t('message.toolsUpdated')
: t(view.role === 'recall' ? 'message.contextRecall' : 'message.contextInjection')}
collapsedContent={toolSummary !== null ? (
<>
<span className={css.sep} aria-hidden />
<span className={css.summary}>{toolSummary}</span>
</>
) : tools !== null || view.label === null ? undefined : (
/* ToolRow's separator shape: an aria-hidden dot, so the accessible name
stays the two readable parts and the two disclosure rows expose one
name shape. A source that names no producer drops the dot with it. */
<>
<span className={css.sep} aria-hidden />
<span className={css.source} data-context-source>{view.label}</span>
{summary !== null && (
<>
<span className={css.sep} aria-hidden />
<span className={css.summary} data-context-summary>{summary}</span>
</>
)}
</>
)}
keepContentWhenOpen
open={open && tools?.single == null}
expandable={tools?.single == null}
expandOnRowClick
onToggle={() => { setOpen(value => !value) }}
>
<div className={css.body} data-context-injection-body data-context-form={rendered ?? undefined}>
{tools === null ? body : (
<div className={css.toolChanges}>
{tools.added.length > 0 && <div>{t('message.toolsAdded', { names: tools.added.join(', ') })}</div>}
{tools.removed.length > 0 && <div>{t('message.toolsRemoved', { names: tools.removed.join(', ') })}</div>}
</div>
)}
</div>
</DisclosureRow>
)
}

View File

@ -0,0 +1,35 @@
import type { ReactNode } from 'react'
import {
IconBrowseOutlineRegular, IconFolderCloseRegular,
} from '@deepseek-ai/dsh-client-ui-primitives'
/** Reference domains with distinct composer and transcript glyphs. */
export type ReferenceIconKind = 'session' | 'file' | 'folder'
/** Props shared by inline reference glyphs. */
export interface ReferenceIconProps {
kind: ReferenceIconKind
size?: number
className?: string | undefined
}
/**
* Render the icon that identifies one inline reference domain.
* @param props - Reference kind, optional size, and optional CSS class.
* @returns The corresponding current-color SVG glyph.
*/
export function ReferenceIcon({ kind, size = 16, className }: ReferenceIconProps): ReactNode {
switch (kind) {
case 'session':
return (
<svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" aria-hidden>
<path
d="M8 0.597656C3.91296 0.597656 0.599716 3.91103 0.599609 7.99805C0.599609 9.13171 0.854567 10.2079 1.31152 11.1699L1.59277 11.7607L2.77441 11.1992L2.49414 10.6084L2.36035 10.3076C2.06865 9.59612 1.90723 8.81645 1.90723 7.99805C1.90733 4.63362 4.63554 1.90625 8 1.90625C11.3644 1.90635 14.0917 4.63368 14.0918 7.99805C14.0918 11.3625 11.3644 14.0907 8 14.0908C7.311 14.0908 6.80642 14.0414 6.35938 13.918C5.919 13.7963 5.50105 13.5929 5.00098 13.2441C4.26805 12.7329 3.21756 12.5526 2.35156 13.0996L2.33789 13.1084L2.32422 13.1182L1.74805 13.5234L2.18164 14.8184L3.05957 14.2002C3.37505 14.0068 3.84248 14.0319 4.25195 14.3174C4.84447 14.7307 5.39718 15.009 6.01172 15.1787C6.61963 15.3465 7.25579 15.3984 8 15.3984C12.087 15.3983 15.4004 12.0851 15.4004 7.99805C15.4003 3.9111 12.087 0.59776 8 0.597656ZM4.56836 8.50977V9.80371H8.12402V8.50977H4.56836ZM4.56836 7.30078H11.4619V6.00684H4.56836V7.30078Z"
fill="currentColor"
/>
</svg>
)
case 'file': return <IconBrowseOutlineRegular size={size} className={className} />
case 'folder': return <IconFolderCloseRegular size={size} className={className} />
}
}

View File

@ -0,0 +1,248 @@
/**
* Pure row-model derivation for tool summary rows: variant classification,
* one-line summary, expanded-body text, and flattened result output from the
* frozen call slice. Input material comes from the call ARGUMENTS; output and
* error material from the settled result node. A call whose render intent is
* a terminal card gets its expanded body from the views instead, through
* `terminalCardModel` in terminal-card-model.ts.
*/
// The block union's defining home is runtime (fold-product types); this
// contract only forwards it (type-definition authority stays with the layer
// that produces the values).
import { abbreviateHomePath } from '@deepseek-ai/dsh-util-workspace-path'
import type { ToolCallBlock, ToolResultNode } from '@deepseek-ai/dsh-client-ui-conversation/client'
export type { ToolCallBlock } from '@deepseek-ai/dsh-client-ui-conversation/client'
/** Tool-call row variants selected by the generic atomic renderer. */
export type ToolRowVariant = 'search' | 'read' | 'bash' | 'write' | 'edit' | 'code' | 'others'
/** Row state semantic; colors self-supplied via StateDot (design gives none). */
export type ToolRowState = 'running' | 'ok' | 'error' | 'stopped'
/** Figma row titles per variant (design literals, not translatable copy). */
export const VARIANT_TITLES: Record<ToolRowVariant, string> = {
search: 'Search', read: 'Read', bash: 'Bash',
write: 'Write', edit: 'Edit', code: 'Code', others: 'Tool call',
}
/**
* Known tool name -> variant.
*
* `cordis_define` is deliberately absent: ui-cordis registers a keyed
* `tool.call.toolview` entry for it, and a keyed hit REPLACES the generic row
* (this table is only reached through GenericToolCard, the dispatch fallback in
* ToolCallTree). An entry here would be unreachable, and a second title for the
* same call would be a second answer to a question the card already owns.
*/
const TOOL_VARIANTS: Record<string, ToolRowVariant> = {
bash: 'bash',
// The PowerShell twin is a shell tool: the bash row family (icon, colors)
// with its own title from TOOL_TITLES, not the generic `others` row.
pwsh: 'bash',
read: 'read',
web_fetch: 'read',
web_search: 'search',
grep: 'search',
glob: 'search',
write: 'write',
edit: 'edit',
run_code: 'code',
cordis_package_inspect: 'read',
cordis_runtime_inspect: 'read',
// The three run-control verbs take one package id and produce a receipt, so
// the generic row is the decided intent, not an unclassified default: there is
// no program to show (that is `cordis_define`'s card) and no file to open. The
// id lands in the summary slot, and the titles below name the act.
cordis_run: 'others',
cordis_stop: 'others',
cordis_undefine: 'others',
}
/** Tool-owned titles that refine a generic row variant without replacing it. */
const TOOL_TITLES: Record<string, string> = {
cordis_package_inspect: 'Inspect',
cordis_runtime_inspect: 'Inspect',
cordis_run: 'Run Cordis Plugin',
cordis_stop: 'Stop Cordis Plugin',
cordis_undefine: 'Remove Cordis Plugin',
pwsh: 'Pwsh',
}
/**
* Classify a tool name into its row variant.
* @param toolName - wire tool name.
* @returns matching variant, others when unknown.
*/
export function classifyTool(toolName: string): ToolRowVariant {
return TOOL_VARIANTS[toolName] ?? 'others'
}
/** Everything ToolRow needs, derived once from the frozen slice. */
export interface ToolRowModel {
variant: ToolRowVariant
title: string
summary: string
/**
* Filesystem path from args (`path` / `file_path`) when the row is a file
* tool; absent for URL reads and non-file tools. The chat view resolves
* relative values against the session cwd before opening.
*/
filePath: string | undefined
/** Expanded-body input text (pretty args); null = no input section. */
body: string | null
/** Flattened result text ({@link resultText}); null while running or when the result carries no text. */
output: string | null
/** First line of the result text on an error row; null for every other state. */
errorSummary: string | null
state: ToolRowState
}
/**
* Flatten a settled result's content blocks to display text: text blocks
* verbatim, other block shapes as pretty JSON. Empty content on a failed call
* falls back to the structured error's `name: code` line.
* @param node - the settled result node.
* @returns the flattened result text (may be empty).
*/
export function resultText(node: ToolResultNode): string {
const parts: string[] = []
for (const block of node.content) {
if (block.type === 'text') parts.push(block.text)
else parts.push(JSON.stringify(block, null, 2))
}
if (parts.length === 0 && node.error !== undefined) {
parts.push(`${node.error.name}: ${node.error.code}`)
}
return parts.join('\n')
}
function parseArgs(argsRaw: string): unknown {
try {
return JSON.parse(argsRaw)
} catch {
// Non-JSON args (mid-stream truncation): summary/body fall back to the raw string.
return undefined
}
}
function firstLine(text: string): string {
const nl = text.indexOf('\n')
return nl === -1 ? text : text.slice(0, nl)
}
function pickString(args: Record<string, unknown>, keys: readonly string[]): string | undefined {
for (const key of keys) {
const v = args[key]
if (typeof v === 'string' && v !== '') return v
}
return undefined
}
/** Summary key preference per variant (args-derived; result-derived summaries are a ledger item). */
const SUMMARY_KEYS: Record<ToolRowVariant, readonly string[]> = {
bash: ['description', 'command'],
read: ['path', 'file_path', 'url'],
search: ['query', 'pattern', 'url'],
write: ['path', 'file_path'],
edit: ['path', 'file_path'],
code: ['description'],
others: [],
}
/**
* Strip the workspace root from a workspace-rooted absolute path (display only).
* @param text - the path to shorten.
* @param cwd - session workspace root; absent or empty leaves the path unchanged.
* @returns the path relative to the workspace root, or unchanged when it is not rooted there.
*/
export function relativizeToCwd(text: string, cwd: string | undefined): string {
if (cwd === undefined || cwd === '') return text
const root = cwd.replace(/[/\\]+$/, '')
if (text.startsWith(`${root}/`) || text.startsWith(`${root}\\`)) return text.slice(root.length + 1)
return text
}
function deriveSummary(variant: ToolRowVariant, argsRaw: string): string {
const parsed = parseArgs(argsRaw)
if (typeof parsed !== 'object' || parsed === null) return firstLine(argsRaw)
const args = parsed as Record<string, unknown>
if (variant === 'search' && Array.isArray(args.queries)) {
const queries = args.queries.filter((query): query is string => typeof query === 'string' && query !== '')
if (queries.length > 0) return queries.map(firstLine).join(', ')
}
const picked = pickString(args, SUMMARY_KEYS[variant])
if (picked !== undefined) return firstLine(picked)
for (const v of Object.values(args)) {
if (typeof v === 'string' && v !== '') return firstLine(v)
}
return firstLine(argsRaw)
}
/** Path keys only — never `url` (web_fetch lands on the read variant). */
const FILE_PATH_KEYS = ['path', 'file_path'] as const
/** File-tool variants whose summary may be an openable workspace path. */
const FILE_PATH_VARIANTS: ReadonlySet<ToolRowVariant> = new Set(['read', 'write', 'edit'])
function deriveFilePath(variant: ToolRowVariant, argsRaw: string): string | undefined {
if (!FILE_PATH_VARIANTS.has(variant)) return undefined
const parsed = parseArgs(argsRaw)
if (typeof parsed !== 'object' || parsed === null) return undefined
const picked = pickString(parsed as Record<string, unknown>, FILE_PATH_KEYS)
return picked === undefined ? undefined : firstLine(picked)
}
function deriveBody(variant: ToolRowVariant, argsRaw: string): string | null {
if (argsRaw === '') return null
const parsed = parseArgs(argsRaw)
if (parsed === undefined) return argsRaw
// The code row's expanded body IS the program (monospace via the row's
// variant styling), not the args JSON envelope around it.
if (variant === 'code' && typeof parsed === 'object' && parsed !== null) {
const code = (parsed as Record<string, unknown>).code
if (typeof code === 'string' && code !== '') return code
}
return JSON.stringify(parsed, null, 2)
}
/**
* Derive the full row model from a frozen call slice.
* @param toolName - wire tool name (dispatch-supplied; survives windowless results).
* @param block - RunningToolCall or ToolResultNode off the snapshot caches.
* @param cwd - session workspace root; workspace-rooted path summaries display relative to it.
* @param home - host account home; a leftover POSIX home path displays as `~`.
* @returns the row model.
*/
export function toolRowModel(toolName: string, block: ToolCallBlock, cwd?: string, home?: string): ToolRowModel {
const variant = classifyTool(toolName)
const done = 'kind' in block
const argsRaw = (done ? block.call?.argsRaw : ('argsRaw' in block ? block.argsRaw : '')) ?? ''
const state: ToolRowState = !done ? 'running'
: block.error?.code === 'interrupted' ? 'stopped'
: block.isError ? 'error' : 'ok'
const base = argsRaw === ''
? block.callId
: abbreviateHomePath(relativizeToCwd(deriveSummary(variant, argsRaw), cwd), home)
const toolTitle = TOOL_TITLES[toolName]
// Others keeps the static "Tool call" title (figma literal); the real tool
// name rides the mutable summary slot unless the tool owns a specific title.
const summary = variant === 'others' && toolName !== '' && toolTitle === undefined
? `${toolName} · ${base}`
: base
// The empty string is "no text" for both derived result fields: a settled
// call with blank content has nothing to expand, and a blank first line
// would erase the collapsed error row's summary slot.
const output = done ? (resultText(block) || null) : null
const errorSummary = state === 'error' && output !== null ? firstLine(output) : null
return {
variant,
title: toolTitle ?? VARIANT_TITLES[variant],
summary,
filePath: deriveFilePath(variant, argsRaw),
body: deriveBody(variant, argsRaw),
output,
errorSummary,
state,
}
}

View File

@ -0,0 +1,32 @@
/** One developer tool-change block the 0.1.7-rc.2 context row names in place. */
export interface ToolChangeBlock {
type: 'tool-addition' | 'tool-removal'
toolName: string
}
/** Names collected from a context whose every block is a tool change. */
export interface ToolUpdateRows {
added: readonly string[]
removed: readonly string[]
/** The only block, when the row is a single add or removal. */
single: ToolChangeBlock | null
}
/**
* Classify a context as the rc.2 tool-update row.
* Mixed or empty content stays on the generic injection presentation.
* @param content - durable context blocks.
* @returns collected names, or null when any block is not a tool change.
*/
export function toolUpdateRows(content: readonly { readonly type: string; readonly toolName?: string }[]): ToolUpdateRows | null {
if (content.length === 0) return null
const rows: ToolChangeBlock[] = []
for (const block of content) {
if (block.type !== 'tool-addition' && block.type !== 'tool-removal') return null
if (typeof block.toolName !== 'string') return null
rows.push({ type: block.type, toolName: block.toolName })
}
const added = rows.flatMap(row => row.type === 'tool-addition' ? [row.toolName] : [])
const removed = rows.flatMap(row => row.type === 'tool-removal' ? [row.toolName] : [])
return { added, removed, single: rows.length === 1 ? rows[0]! : null }
}

View File

@ -0,0 +1,41 @@
{
"repository": "DeepSeek Harness",
"commit": "b150a551b8d465e31e418e1b2eaf5e79bbb7d28e",
"adaptations": [
"Public type import in place of private type-only path",
"ESM .js import suffixes",
"Local ReferenceIcon location"
],
"files": [
{
"source": "packages/client/ui-conversation/src/client/chat/ContextInjectionRow.tsx",
"output": "ContextInjectionRow.tsx",
"sha256": "afb41e6285f2abaf0eb6a1f843dbc135c8480bd48848beed1f94e395ac0f68c8"
},
{
"source": "packages/client/ui-conversation/src/client/chat/ContextInjectionRow.module.css",
"output": "ContextInjectionRow.module.css",
"sha256": "af61636789223d2476ec818a76d795bc7c13ca1a433f834d78702a825bd000de"
},
{
"source": "packages/client/ui-conversation/src/client/chat/ContextBody.tsx",
"output": "ContextBody.tsx",
"sha256": "94f41356d59bdcdae7225f3cb8cd9b0c0b1a32d24153d82512bfba7c40443cc8"
},
{
"source": "packages/client/ui-conversation/src/client/chat/ContextBody.module.css",
"output": "ContextBody.module.css",
"sha256": "b3838bf9cf38af53b31fd6333b4766ad063024d9a59cd636a38e3e0e07d7bf61"
},
{
"source": "packages/client/ui-conversation/src/client/reference/ReferenceIcon.tsx",
"output": "ReferenceIcon.tsx",
"sha256": "6315cb1ceafa830cd9e38ce296ddf5791ab93562e4f5a7bdbda1ef9ac6f7ed57"
},
{
"source": "packages/client/ui-tool/src/client/tool/models/tool-call-model.ts",
"output": "tool-call-model.ts",
"sha256": "02536cb0be80168351857083d0f0b71554216cd3195bad8016b1e4bb567acc7f"
}
]
}

View File

@ -0,0 +1,263 @@
import { createElement, memo, useEffect, useLayoutEffect, useMemo, useRef, type ComponentType, type ReactNode, type RefObject } from 'react';
import type { Context } from '@deepseek-ai/cordis';
import type { UseGroupAction } from '@deepseek-ai/dsh-client-ui-chat/client';
import type { SlotEntryDef, SlotMap, SlotSpec, StoredEntry } from '@deepseek-ai/dsh-client-ui-slots';
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client';
/**
* RC2 composition adapter. Only public registry operations are used. We lend
* registrations a Reader-owned seat, not a second implementation of their UI.
* The platform still binds injection, hooks, locale, stores and boundaries.
* Original entries, declarations and components are never changed.
*
* Child seats have unique names because RC2 declarations have one owner. The
* sole component wrapper translates those names before delegating to the
* framework-provided renderSlot. It does not implement a slot renderer.
*/
export const OFFICIAL_SLOTS = {
actions: 'conversation.chat.assistant-actions',
tools: 'tool.call.toolview',
tail: 'conversation.chat.turnTail',
nodes: 'conversation.chat.node',
messageImages: 'conversation.chat.message.images',
userImages: 'conversation.chat.user.images',
} as const;
export type OfficialFamily = keyof typeof OFFICIAL_SLOTS;
export const OFFICIAL_SEATS = {
actions: 'dsh-better-display.official.actions/conversation.chat.assistant-actions',
tools: 'dsh-better-display.official.tools/tool.call.toolview',
tail: 'dsh-better-display.official.tail/conversation.chat.turnTail',
nodes: 'dsh-better-display.official.nodes/conversation.chat.node',
messageImages: 'dsh-better-display.official.messageImages/conversation.chat.message.images',
userImages: 'dsh-better-display.official.userImages/conversation.chat.user.images',
} as const;
export type OfficialSeat = typeof OFFICIAL_SEATS[OfficialFamily];
export const officialSeat = (family: OfficialFamily, source: string = OFFICIAL_SLOTS[family]) =>
`dsh-better-display.official.${family}/${source}`;
type Spec = SlotSpec<SlotEntryDef>;
type Render = (key: string, owner: object, options?: object) => ReactNode;
type RenderProps = { renderSlot: Render; renderSlotChain?: Render } & Record<string, unknown>;
type Registration = StoredEntry['options'] & Omit<StoredEntry, 'options' | 'component'> & { name: string };
/** The documented, type-erased registry inspection/registration boundary. */
export interface CompositionRegistry {
spec(key: string): Spec | undefined;
entriesOfSlot(key: string): readonly StoredEntry[];
subscribe(key: string, listener: () => void): () => void;
inject(key: string, effect: () => () => void): () => void;
register(options: Registration, component: unknown): () => void;
}
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface SlotMap {
'dsh-better-display.official.actions/conversation.chat.assistant-actions': SlotMap['conversation.chat.assistant-actions'];
'dsh-better-display.official.tools/tool.call.toolview': SlotMap['tool.call.toolview'];
'dsh-better-display.official.tail/conversation.chat.turnTail': SlotMap['conversation.chat.turnTail'];
'dsh-better-display.official.nodes/conversation.chat.node': SlotMap['conversation.chat.node'];
'dsh-better-display.official.messageImages/conversation.chat.message.images': SlotMap['conversation.chat.message.images'];
'dsh-better-display.official.userImages/conversation.chat.user.images': SlotMap['conversation.chat.user.images'];
}
}
/**
* Searchable hide for official nodes drawn outside the Chat flow viewport.
* The flow's own `useGroupAction` is not in scope here; this keeps the same
* `hidden="until-found"` contract so browser find can still reveal the row.
*/
export function useReaderGroupAction(hidden: boolean, reveal: () => void): RefObject<HTMLDivElement> {
const ref = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const element = ref.current;
if (element === null) return;
if (hidden && element.contains(element.ownerDocument.activeElement)) {
reveal();
return;
}
if (hidden) element.setAttribute('hidden', 'until-found');
else element.removeAttribute('hidden');
}, [hidden, reveal]);
useEffect(() => {
const element = ref.current;
if (element === null) return;
element.addEventListener('beforematch', reveal);
return () => { element.removeEventListener('beforematch', reveal); };
}, [reveal]);
return ref;
}
export const readerGroupAction: UseGroupAction = useReaderGroupAction;
// Reader draws these rows itself. Everything else, including future kinds, is
// mirrored so the official renderer still runs inside the reading view.
// 'user' and 'steering' stay mirrored (message-recall buttons and the like).
// 'assistant-step' is special: the official renderer is priority 0 and Reader
// keeps that presentation. A strictly lower priority is a keyed-slot
// replacement (lowest priority renders) and is mirrored for body content.
const READER_OWNED_NODES = new Set(['tool-call', 'turn-tail', 'turn-process']);
/** Official `AssistantNodeView` registers at priority 0. Lower wins. */
export const OFFICIAL_ASSISTANT_PRIORITY = 0;
/**
* Mirror a chat-node registration into the Reader seat.
* Assistant replacements are the entries that would actually replace the
* official renderer on the host. The official priority itself stays out, so
* Reader keeps its own answer markdown until a plugin opts in.
*/
export function acceptMirroredChatNode(entry: StoredEntry): boolean {
const key = entry.options.key ?? '';
if (key === 'assistant-step') return (entry.options.priority ?? OFFICIAL_ASSISTANT_PRIORITY) < OFFICIAL_ASSISTANT_PRIORITY;
return !READER_OWNED_NODES.has(key);
}
const EXPECTED: Record<OfficialFamily, Spec> = {
actions: { kind: 'list', scope: 'session' },
tools: { kind: 'keyed', scope: 'session' },
tail: { kind: 'list', scope: 'session' },
nodes: { kind: 'keyed', scope: 'session' },
messageImages: { kind: 'single', scope: 'session' },
userImages: { kind: 'single', scope: 'session' },
};
/**
* Reader already presents produced paths with its copy/reveal actions. RC2's
* official tail additionally owns explicit `present` artifacts. Leave those
* cards, actions and state intact, and omit only the duplicate produced chips.
* This changes a presentation prop, never the source match or session data.
* Unrecognized shapes pass through intact for safe forward degradation.
*/
export function readerTailMatch(value: unknown, displayedPaths?: readonly string[]): unknown {
if (!value || typeof value !== 'object') return value;
const match = value as Record<string, unknown>;
const displayed = new Set(displayedPaths ?? []);
return displayed.size > 0 && Array.isArray(match.produced) && Array.isArray(match.presented)
? { ...match, produced: match.produced.filter(path => !displayed.has(path)) }
: value;
}
function tailPresentation(component: unknown) {
const Original = component as ComponentType<Record<string, unknown>>;
return memo(function ReaderTailPresentation(props: Record<string, unknown>) {
const matched = useMemo(() => readerTailMatch(props.matched, props.readerProducedPaths as readonly string[] | undefined), [props.matched, props.readerProducedPaths]);
return createElement(Original, { ...props, matched });
});
}
export function officialChildren(slots: Pick<CompositionRegistry, 'spec'>): { [K in OfficialSeat]: SlotSpec<SlotMap[K]> } {
return Object.fromEntries(Object.entries(OFFICIAL_SLOTS).map(([name, source]) => {
const family = name as OfficialFamily;
const spec = slots.spec(source);
if (spec && (spec.kind !== EXPECTED[family].kind || spec.scope !== EXPECTED[family].scope)) {
throw new Error(`Official slot contract changed: ${source} (${spec.kind}/${spec.scope})`);
}
// In particular, retain conversation.chat.node's contextual turn-data hook.
return [officialSeat(family), spec ?? EXPECTED[family]];
})) as { [K in OfficialSeat]: SlotSpec<SlotMap[K]> };
}
function translatedComponent(entry: StoredEntry, names: ReadonlyMap<string, string>) {
if (names.size === 0) return entry.component;
const Original = entry.component as ComponentType<Record<string, unknown>>;
return memo(function OfficialSlotChildren(props: RenderProps) {
const renders = useMemo(() => {
const translate = (render: Render | undefined): Render => (key, owner, options) => {
const seat = names.get(key);
if (!seat || !render) throw new Error(`Undeclared official child slot: ${key}`);
return render(seat, owner, options);
};
return {
renderSlot: translate(props.renderSlot),
...(props.renderSlotChain ? { renderSlotChain: translate(props.renderSlotChain) } : {}),
};
}, [props.renderSlot, props.renderSlotChain]);
return createElement(Original, { ...props, ...renders });
});
}
/**
* Mirror one elected contribution set incrementally. Unrelated additions do not
* remount existing cards or recreate their subscriptions. A source unload/HMR
* disposes the corresponding subtree and closures before its replacement.
*/
export function mirrorOfficialSlot(
slots: CompositionRegistry,
source: string,
target: string,
namespace: string,
accept: (entry: StoredEntry) => boolean = () => true,
): () => void {
const mounted = new Map<StoredEntry, () => void>();
let stopped = false;
const reconcile = () => {
if (stopped) return;
const entries = slots.entriesOfSlot(source).filter(accept);
const wanted = new Set(entries);
for (const [entry, dispose] of mounted) {
if (wanted.has(entry)) continue;
dispose();
mounted.delete(entry);
}
for (const entry of entries) {
if (mounted.has(entry)) continue;
const names = new Map(Object.keys(entry.children ?? {}).map(key => [key, `${namespace}/${key}`]));
const children = Object.fromEntries([...names].map(([key, seat]) => [seat, entry.children![key]]));
const disposers: (() => void)[] = [];
const dispose = () => { for (const stop of disposers.splice(0).reverse()) stop(); };
try {
const { component: _component, options, children: _children, ...metadata } = entry;
const presentation = source === OFFICIAL_SLOTS.tail && entry.locale === 'deliverables'
? { ...entry, component: tailPresentation(entry.component) }
: entry;
disposers.push(slots.register({
...options, ...metadata, name: target,
...(names.size ? { children } : {}),
registrant: `dsh-better-display → ${entry.registrant ?? source}`,
}, translatedComponent(presentation, names)));
for (const [key, seat] of names) {
disposers.push(mirrorOfficialSlot(slots, key, seat, namespace));
}
mounted.set(entry, dispose);
} catch (error) {
dispose();
throw error;
}
}
};
const unsubscribe = slots.subscribe(source, reconcile);
const dispose = () => {
stopped = true;
unsubscribe();
for (const stop of [...mounted.values()].reverse()) stop();
mounted.clear();
};
try { reconcile(); } catch (error) { dispose(); throw error; }
return dispose;
}
export function installOfficialSlots(ctx: Context): () => void {
// The SlotMap overloads are for statically declared keys. Aliases are a
// runtime composition, using exactly the public erased metadata contract.
const slots = ctx.slots as unknown as CompositionRegistry;
const disposers: (() => void)[] = [];
try {
for (const [name, source] of Object.entries(OFFICIAL_SLOTS)) {
const family = name as OfficialFamily;
disposers.push(slots.inject(source, () => {
const spec = slots.spec(source)!;
const target = officialSeat(family);
const declared = slots.spec(target);
if (spec.kind !== declared?.kind || spec.scope !== declared.scope) {
throw new Error(`Official slot contract changed: ${source}`);
}
return mirrorOfficialSlot(slots, source, target, `dsh-better-display.official.${family}`,
family === 'nodes' ? acceptMirroredChatNode : undefined);
}));
}
} catch (error) {
for (const stop of disposers.reverse()) stop();
throw error;
}
return () => { for (const stop of disposers.splice(0).reverse()) stop(); };
}
export type OfficialSlotKey = typeof OFFICIAL_SLOTS[OfficialFamily] & keyof SlotMap;

88
src/client/open-file.ts Normal file
View File

@ -0,0 +1,88 @@
import { isAbsoluteWorkspacePath } from '../workspace-path.js';
export type DeliverableOpenMode = 'external' | 'sidebar';
export interface OpenModeSnapshot {
getSnapshot: () => { deliverableOpenMode?: DeliverableOpenMode };
subscribe?: (fn: () => void) => () => void;
}
export function deliverableOpenModeOf(value: unknown): DeliverableOpenMode {
return value === 'sidebar' ? 'sidebar' : 'external';
}
export function modeFromSnapshot(store: OpenModeSnapshot | undefined): DeliverableOpenMode {
try {
return deliverableOpenModeOf(store?.getSnapshot()?.deliverableOpenMode);
} catch {
return 'external';
}
}
/** Workspace-folder affordances stay on the OS opener, not the Sidebar switch. */
export function isFolderOpenPath(path: string): boolean {
return path === '.' || path === '';
}
function encodeSegment(segment: string): string {
return encodeURIComponent(segment).replace(/%3A/gi, ':');
}
function encodePath(path: string): string {
return path.split('/').map(encodeSegment).join('/');
}
/**
* Session-scoped `dsh-resource://file/session/<id>/…` address.
* Matches official `fileAddressFor` / `sessionFileAddress` (0.1.5).
*/
export function fileAddressFor(sessionId: string, cwd: string | undefined, path: string): string {
const normalized = path.replace(/\\/g, '/');
const address = (relative: string): string => {
const cleaned = relative.replace(/\\/g, '/').replace(/^(?:\.\/)+/, '');
return `dsh-resource://file/session/${encodeSegment(sessionId)}/${encodePath(cleaned)}`;
};
if (!isAbsoluteWorkspacePath(normalized)) return address(normalized);
const root = cwd === undefined ? '' : cwd.replace(/\\/g, '/').replace(/\/+$/, '');
if (root !== '' && normalized === root) return address('');
if (root !== '' && normalized.startsWith(`${root}/`)) return address(normalized.slice(root.length + 1));
return address(normalized);
}
export function resolveOpenWorkspacePath(
cwd: string | undefined,
path: string,
resolveWorkspacePath: (cwd: string | undefined, path: string) => string,
): string {
return isFolderOpenPath(path) ? (cwd ?? '.') : resolveWorkspacePath(cwd, path);
}
export async function openDeliverableFile(args: {
path: string;
mode: DeliverableOpenMode;
sessionId: string;
cwd: string | undefined;
resolveWorkspacePath: (cwd: string | undefined, path: string) => string;
openExternal: (absolutePath: string) => Promise<void>;
openSidebar?: (address: string) => void;
fileAddressFor?: (sessionId: string, cwd: string | undefined, path: string) => string;
warn?: (message: string, extra?: unknown) => void;
}): Promise<'sidebar' | 'external'> {
const targetPath = resolveOpenWorkspacePath(args.cwd, args.path, args.resolveWorkspacePath);
const useSidebar = args.mode === 'sidebar' && !isFolderOpenPath(args.path);
if (useSidebar) {
if (typeof args.openSidebar !== 'function') {
args.warn?.('[dsh-better-display] sidebarRight.openResource is not available; falling back to system app');
} else {
try {
const address = (args.fileAddressFor ?? fileAddressFor)(args.sessionId, args.cwd, args.path);
args.openSidebar(address);
return 'sidebar';
} catch (error) {
args.warn?.('[dsh-better-display] sidebar open failed; falling back to system app', error);
}
}
}
await args.openExternal(targetPath);
return 'external';
}

View File

@ -0,0 +1,49 @@
/** Official PendingSubmission.images is optional at runtime; text-only sends omit it. */
export interface PendingSubmissionImage {
readonly previewUrl: string;
readonly width?: number;
readonly height?: number;
readonly name?: string;
}
export interface PendingSubmissionLike {
readonly images?: readonly PendingSubmissionImage[] | null;
readonly attachments?: readonly {
readonly type?: string;
readonly value?: PendingSubmissionImage;
}[] | null;
}
export interface PendingSubmissionEcho extends PendingSubmissionLike {
readonly requestId: string;
readonly text?: string;
readonly time?: number;
readonly placement?: string;
}
export function asReadonlyArray<T>(value: unknown): readonly T[] {
return Array.isArray(value) ? value as readonly T[] : [];
}
function isImage(value: unknown): value is PendingSubmissionImage {
return value !== null && typeof value === 'object' && typeof (value as PendingSubmissionImage).previewUrl === 'string';
}
/**
* Safe image list for conversation.view pending echoes.
* Official 0.1.5 uses `images`; older hosts used `attachments`.
* Either field may be missing — never read `.length` on undefined.
*/
export function pendingSubmissionImages(submission: PendingSubmissionLike | null | undefined): readonly PendingSubmissionImage[] {
if (submission == null) return [];
if (Array.isArray(submission.images)) return submission.images.filter(isImage);
if (Array.isArray(submission.attachments)) {
const images: PendingSubmissionImage[] = [];
for (const item of submission.attachments) {
if (item?.type === 'image' && isImage(item.value)) images.push(item.value);
}
return images;
}
return [];
}

View File

@ -0,0 +1,17 @@
/** Web or Desktop file route. Authorization stays Host-side. */
export function localPathMediaUrl(protocol: string, origin: string, value: string): string | undefined {
if (!value.startsWith('/') || value.startsWith('//')) return undefined;
if (protocol === 'http:' || protocol === 'https:') {
return `${origin}/api/file?path=${encodeURIComponent(value)}`;
}
// Official fileMediaUrl accepts the Desktop application base dsh-app://app/.
if (protocol === 'dsh-app:' && origin === 'dsh-app://app') {
return `dsh-app://app/api/file?path=${encodeURIComponent(value)}`;
}
return undefined;
}
export const readerPathImages = {
resolve: (value: string) => typeof window === 'undefined' ? undefined
: localPathMediaUrl(window.location.protocol, window.location.origin, value),
};

View File

@ -0,0 +1,55 @@
import type {
DiffBlockLabels,
JsonTreeLabels,
MarkdownLabels,
ReadBlockLabels,
SearchBlockLabels,
TerminalBlockLabels,
WebBlockLabels,
} from '@deepseek-ai/dsh-client-ui-primitives';
export const markdownLabels: MarkdownLabels = {
code: { copyLabel: '复制', copiedLabel: '已复制' },
footnotes: '脚注',
};
export const readBlockLabels: ReadBlockLabels = {
codeLabel: '代码', wrapLabel: '自动换行', unwrapLabel: '不换行',
window: (shown, total) => `显示 ${shown} / ${total} 行`,
copy: '复制', copied: '已复制', collapseAria: '收起文件内容',
expandAria: hidden => `展开其余 ${hidden} 行`, collapse: '收起', expand: hidden => `展开其余 ${hidden} 行`,
};
export const terminalBlockLabels: TerminalBlockLabels = {
commandLine: line => `命令第 ${line} 行`,
signal: signal => `信号 ${signal}`, exitCode: code => `退出码 ${code}`, noExitCode: '无退出码',
running: '执行中', failed: '失败', done: '已完成', copy: '复制', copied: '已复制',
noOutput: '没有输出', collapseAria: '收起命令输出', collapse: '收起',
expandAria: hidden => `展开其余 ${hidden} 行`, expand: hidden => `展开其余 ${hidden} 行`,
};
export const diffBlockLabels: DiffBlockLabels = {
codeLabel: '代码', wrapLabel: '自动换行', unwrapLabel: '不换行',
copy: '复制', copied: '已复制', collapseAria: '收起差异', collapse: '收起',
expandAria: hidden => `展开其余 ${hidden} 行`, expand: hidden => `展开其余 ${hidden} 行`,
};
export const searchBlockLabels: SearchBlockLabels = {
pathsSummary: (shown, total, truncated) => `${shown} / ${total} 个路径${truncated ? '(结果已截断)' : ''}`,
matchesSummary: (shown, total, files, truncated) => `${shown} / ${total} 处匹配 · ${files} 个文件${truncated ? '(结果已截断)' : ''}`,
copy: '复制', copied: '已复制', noResults: '没有结果', collapseAria: '收起搜索结果', collapse: '收起',
expandAria: hidden => `展开其余 ${hidden} 行`, expand: hidden => `展开其余 ${hidden} 行`,
};
export const webBlockLabels: WebBlockLabels = {
noResults: '没有结果', sourcesTruncated: '来源已截断', http: 'HTTP', contentTruncated: '内容已截断',
markdown: markdownLabels,
};
export const jsonTreeLabels: JsonTreeLabels = {
copyValue: '复制值', copyJson: '复制 JSON', copyPath: '复制路径', copyPrettyJson: '复制格式化 JSON',
copyCompactJson: '复制紧凑 JSON', copied: '已复制', copyFailed: '复制失败', collapseNode: '收起节点',
expandNode: '展开节点', copyButtonTitle: action => action,
};
export const truncatedJsonLabel = (total: number): string => `内容过长,已截断(共 ${total} 个字符)`;

130
src/client/projection.ts Normal file
View File

@ -0,0 +1,130 @@
import type { AssistantBlock, ToolCallBlock, TurnLocation } from '@deepseek-ai/dsh-client-ui-conversation/client';
import type { AssistantChatData, ChatConversationViewNode } from '@deepseek-ai/dsh-client-ui-chat/client';
import { activityPhase } from './tool-activity.js';
export interface ReaderGroup { key: string; turn: number | null; keys: readonly string[] }
export interface TurnBoundary { status: 'open' | 'closed' | 'unknown'; reason: string | null; latestStep: number; closingStep: number | null }
// Run on structural publication, not on each text delta. Node seats subscribe by key.
export function groupNodes(order: readonly string[], get: (key: string) => ChatConversationViewNode | undefined): ReaderGroup[] {
const groups: ReaderGroup[] = [];
const seenTurns = new Set<number>();
for (const key of order) {
const node = get(key);
if (!node || node.visibility === 'hidden') continue;
const turn = node.location.kind === 'step' || node.location.kind === 'turn' ? node.location.turn.turn : null;
const previous = groups.at(-1);
if (turn !== null && previous?.turn === turn) {
(previous.keys as string[]).push(key);
} else {
groups.push({ key: turn === null ? `node:${key}` : seenTurns.has(turn) ? `turn:${turn}:${key}` : `turn:${turn}`, turn, keys: [key] });
if (turn !== null) seenTurns.add(turn);
}
}
return groups;
}
export function boundaryOf(turn: TurnLocation | undefined): TurnBoundary {
return {
status: turn?.status ?? 'unknown',
reason: turn?.end?.data.reason.kind ?? null,
latestStep: turn?.steps.at(-1)?.step ?? -1,
closingStep: turn?.data.get('turn-tail')?.closing?.step ?? null,
};
}
/**
* A settled body step before the closing step of a successful turn.
*
* This is presentation classification only. Narration is never process content
* and never folds. The flag only marks body text that is no longer the turn's
* final answer, so copy and fork stay on that final answer.
*/
export function isEarlierNarration(data: AssistantChatData, boundary: TurnBoundary): boolean {
// New body text, a tool call, or a settled step is not a completed turn.
if (data.status !== 'settled' || boundary.status !== 'closed' || boundary.reason !== 'completed') return false;
if (data.blocks.some(block => block.kind === 'image' || block.kind === 'other')) return false;
return boundary.closingStep !== null && data.step < boundary.closingStep;
}
export function processExpanded(choice: boolean | undefined, boundary: TurnBoundary): boolean {
return choice ?? !(boundary.status === 'closed' && boundary.reason === 'completed');
}
/** Reading while running must not pin the process open after completion. */
export function processChoiceKey(groupKey: string, boundary: TurnBoundary): string {
return `${groupKey}:${boundary.status}:${boundary.reason ?? 'pending'}`;
}
/**
* A body-only assistant step is not a thinking/process disclosure.
*
* Narration (text/image/other blocks) is always visible, so it never counts as
* foldable process content; only literal reasoning does. Tool calls arrive as
* their own flow entries and are checked separately by the reader.
*/
export function hasProcessContent(node: ChatConversationViewNode | undefined, _boundary: TurnBoundary): boolean {
if (!node || node.visibility === 'hidden') return false;
if (node.kind === 'assistant-step') {
const data = node.data as AssistantChatData;
return data.blocks.some(block => block.kind === 'reasoning' && block.text.trim() !== '');
}
return node.kind === 'context' || node.kind === 'model-retry' || node.kind === 'system-prompt' || node.kind === 'turn-process'
|| node.kind === 'command' || node.kind === 'manual-compaction' || node.kind === 'compaction';
}
export function hasVisibleBody(blocks: readonly AssistantBlock[]): boolean {
return blocks.some(block => block.kind === 'image' || block.kind === 'other' || (block.kind === 'text' && block.text.trim() !== ''));
}
/** Keep native block order. In particular, never lift a later Think above text. */
export function assistantSegments(blocks: readonly AssistantBlock[]): { kind: 'reasoning' | 'body'; start: number; blocks: AssistantBlock[] }[] {
const segments: ReturnType<typeof assistantSegments> = [];
let previous: ReturnType<typeof assistantSegments>[number] | undefined;
blocks.forEach((block, index) => {
if (block.kind === 'tool-call') { previous = undefined; return; }
const kind = block.kind === 'reasoning' ? 'reasoning' : 'body';
if (previous?.kind === kind) previous.blocks.push(block);
else {
previous = { kind, start: index, blocks: [block] };
segments.push(previous);
}
});
return segments;
}
export function toolFailed(block: ToolCallBlock): boolean {
return activityPhase({ block }) === 'failed';
}
export function toolName(block: ToolCallBlock): string {
return 'kind' in block ? block.call?.name ?? '工具调用' : block.name;
}
export function terminalLabel(reason: string | null): string | null {
switch (reason) {
case 'completed': return null;
case 'aborted': case 'interrupted': return '本轮已停止,已生成的内容仍保留。';
case 'blocked': return '本轮需要处理阻塞事项;请查看原对话与下方操作区。';
case 'max-tokens': return '输出达到本轮长度限制,内容可能尚未完整。';
case 'error': return '本轮未完成;错误信息保留在下方。';
case null: return null;
default: return `本轮结束状态:${reason}。请在原对话中核对完整记录。`;
}
}
/**
* Extract the first usable fork anchor seq from candidate message nodes.
* Only the durable closing message seq cuts the intended turn prefix: an
* absent anchor must surface as undefined (never as 0 or NaN), because the
* host treats a missing atSeq as a whole-session fork.
*/
export function forkAnchorSeq(
candidates: ReadonlyArray<{ seq?: unknown } | null | undefined>,
): number | undefined {
for (const candidate of candidates) {
const seq = candidate?.seq;
if (typeof seq === 'number' && Number.isFinite(seq)) return seq;
}
return undefined;
}

View File

@ -0,0 +1,238 @@
import type { Context } from '@deepseek-ai/cordis';
import type {} from '@deepseek-ai/dsh-api-remotes/client';
import type {} from '@deepseek-ai/dsh-api-session-controller/client';
import type {} from '@deepseek-ai/dsh-client-connection/client';
import type { SessionId } from '@deepseek-ai/dsh-session/types';
import { resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path';
import * as workspacePathPkg from '@deepseek-ai/dsh-util-workspace-path';
import { dirname } from './deliverables.js';
import { isAbsoluteWorkspacePath } from '../workspace-path.js';
import { ensureStyles } from './styles.js';
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client';
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client';
import { Reader } from './Reader.js';
import { createReaderStore } from './store.js';
import { installReaderEntry } from './entry.js';
import { installBetterDisplaySettings } from './settings.js';
import { fillComposerDom } from './mcp-app.js';
import { fileAddressFor, modeFromSnapshot, openDeliverableFile } from './open-file.js';
import type { ReaderInjected } from './types.js';
import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
import { installOfficialSlots, officialChildren, type CompositionRegistry } from './official-slots.js';
import { TEXT_TRANSFORM_SERVICE, createTextTransformRegistry, installTextTransformRegistry } from './text-transform.js';
/** Structural face of the sanctioned per-session composer writer. */
interface ComposerShell {
setDraft: (text: string) => void;
}
interface ConversationFace {
input?: { shell?: (id: SessionId) => ComposerShell };
}
interface SidebarRightFace {
openResource?: (address: string, options?: { params?: { line?: number } }) => void;
}
const officialFileAddressFor = (workspacePathPkg as {
fileAddressFor?: typeof fileAddressFor;
}).fileAddressFor;
async function openWorkspacePath(
ctx: Context,
path: string,
): Promise<void> {
const remote = ctx.remote as unknown as { session?: { openWorkspacePath: (arg: { path: string }) => Promise<{ ok: boolean; error?: { message: string } }> } } | undefined;
const remoteSession = remote?.session
?? (ctx.get?.('remote.session') as unknown as { openWorkspacePath: (arg: { path: string }) => Promise<{ ok: boolean; error?: { message: string } }> } | undefined)
?? ((ctx.get?.('remote') as unknown as { session?: { openWorkspacePath: (arg: { path: string }) => Promise<{ ok: boolean; error?: { message: string } }> } })?.session);
if (remoteSession?.openWorkspacePath) {
const result = await remoteSession.openWorkspacePath({ path });
if (!result?.ok) {
console.warn('[dsh-better-display] openWorkspacePath failed:', result?.error?.message);
}
} else {
console.warn('[dsh-better-display] remote.session is not available');
}
}
export type { ReaderBlockOwner, ReaderBlockPresentation } from './types.js';
export type { DisplayCursor, DisplayText, DisplayTextKind, DisplayTextRequest, DisplayTextTransformer, TextTransformRegistry } from './text-transform.js';
export { McpAppFrame } from './McpAppFrame.js';
export { TEXT_TRANSFORM_SERVICE, createTextTransformRegistry, originalAnswerText } from './text-transform.js';
export const name = 'dsh-better-display-client';
export const inject = ['slots', 'sessions', 'conversation', 'uiConversation', 'remote', 'remote.session'];
// All CSS imports have injected their nodes before this module's body runs.
ensureStyles();
export function apply(ctx: Context): void {
const textTransform = createTextTransformRegistry();
const restoreTextTransform = installTextTransformRegistry(textTransform);
ctx.provide(TEXT_TRANSFORM_SERVICE, textTransform);
ctx.effect(() => restoreTextTransform);
const store = createReaderStore();
// conversation.view is session-scoped, so session persist keys are
// `dsh.reader.v1.<sessionId>`. One root instance keeps glass, fold
// intensity, and open-mode on the unsuffixed `dsh.reader.v1` key.
const prefs = store.create();
installBetterDisplaySettings(ctx, prefs);
ctx.slots.inject('conversation.chat.node', function* () {
yield ctx.slots.register({
name: 'conversation.view',
id: 'reader',
order: -5,
label: () => '阅读',
locale: 'chat',
children: {
'dsh-better-display.block': { kind: 'chain', scope: 'session' },
...officialChildren(ctx.slots as unknown as CompositionRegistry),
},
store,
inject: (sessionId: SessionId): ReaderInjected => {
const session = () => {
const current = ctx.sessions.binding(sessionId)?.session;
if (!current) throw new Error('阅读页对应的会话已关闭。');
return current;
};
return {
openPrefs: prefs,
officialImageLoader: Object.assign(
(attachment: ImageAttachmentRef) => ctx.uiConversation.imageUrl(sessionId, attachment),
{ peek: (attachment: ImageAttachmentRef) => ctx.uiConversation.peekImageUrl(sessionId, attachment) },
),
officialFileMentions: owner => ctx.get('chatFileMentions')?.forClosing(owner, sessionId),
officialPreviewFile: path => {
const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd;
const sidebar = ctx.get('sidebarRight') as SidebarRightFace | undefined;
if (!sidebar?.openResource) throw new Error('文件预览面板不可用。');
sidebar.openResource((officialFileAddressFor ?? fileAddressFor)(sessionId, cwd, path));
},
officialHost: {
getSnapshot: () => ctx.remote.$host,
subscribe: listener => ctx.on('connection/reset', listener),
},
loadOlder: async () => { await session().loadOlder(); },
loadImage: async attachment => {
const receipt = await session().readAttachment(attachment.attachmentId);
if (!receipt.ok) throw new Error(receipt.error.message);
return { data: Uint8Array.from(receipt.value.data), mediaType: receipt.value.attachment.mediaType };
},
openFile: async (path, options) => {
try {
const cwd = ctx.sessions?.list?.getSnapshot?.()?.byId[sessionId]?.cwd;
const sidebar = (
ctx.get?.('sidebarRight')
?? (ctx as unknown as { sidebarRight?: SidebarRightFace }).sidebarRight
) as SidebarRightFace | undefined;
await openDeliverableFile({
path,
mode: modeFromSnapshot(prefs),
sessionId,
cwd,
resolveWorkspacePath,
openExternal: async (absolutePath) => { await openWorkspacePath(ctx, absolutePath); },
openSidebar: typeof sidebar?.openResource === 'function'
? (address) => { sidebar.openResource!(address, options?.line === undefined ? undefined : { params: { line: options.line } }); }
: undefined,
fileAddressFor: officialFileAddressFor ?? fileAddressFor,
warn: (message, extra) => { console.warn(message, extra); },
});
} catch (error) {
console.warn('[dsh-better-display] openFile error:', error);
}
},
revealFile: async (path: string) => {
try {
const cwd = ctx.sessions?.list?.getSnapshot?.()?.byId[sessionId]?.cwd;
const targetPath = resolveWorkspacePath(cwd, path);
// 1. Try dedicated host endpoint for native file highlighting (open -R / explorer /select)
try {
const res = await fetch('/better-display/reveal', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: targetPath, sessionId }),
});
if (res.ok) {
const data = await res.json();
if (data.ok) return;
}
} catch {
// Server endpoint not yet available, fallback to directory open
}
// 2. Fallback to official opener with parent directory
const parentDir = dirname(targetPath);
if (!isAbsoluteWorkspacePath(parentDir)) {
console.warn('[dsh-better-display] reveal failed; refusing to open a relative parent:', targetPath);
return;
}
const remote = ctx.remote as unknown as { session?: { openWorkspacePath: (arg: { path: string }) => Promise<{ ok: boolean; error?: { message: string } }> } } | undefined;
const remoteSession = remote?.session
?? (ctx.get?.('remote.session') as unknown as { openWorkspacePath: (arg: { path: string }) => Promise<{ ok: boolean; error?: { message: string } }> } | undefined);
if (remoteSession?.openWorkspacePath) {
await remoteSession.openWorkspacePath({ path: parentDir });
}
} catch (error) {
console.warn('[dsh-better-display] revealFile error:', error);
}
},
forkAt: (seq: number) => {
// A missing anchor would silently fork the whole session instead of
// the intended turn prefix, so refuse it loudly rather than guessing.
if (typeof seq !== 'number' || !Number.isFinite(seq)) {
console.warn('[dsh-better-display] fork refused: missing anchor seq');
return;
}
try {
const sessionsApi = ctx.sessions as unknown as {
fork: (arg: { sessionId: string; atSeq: number; increaseTitle: boolean }) => Promise<string>;
open: (sessionId: string) => void;
} | undefined;
if (sessionsApi?.fork) {
sessionsApi.fork({ sessionId, atSeq: seq, increaseTitle: true })
.then(childId => { sessionsApi.open?.(childId); })
.catch(err => { console.warn('[dsh-better-display] fork failed:', err); });
}
} catch (error) {
console.warn('[dsh-better-display] forkAt error:', error);
}
},
loadThrough: async (seq: unknown) => {
try {
const current = session() as unknown as { loadThrough?: (seq: unknown) => Promise<void> };
if (typeof current?.loadThrough === 'function') {
await current.loadThrough(seq);
} else {
await session().loadOlder();
}
} catch (error) {
console.warn('[dsh-better-display] loadThrough error:', error);
}
},
fillComposer: (text: string) => {
// Sanctioned path: the conversation input shell owns the Lexical
// editor, so setDraft lands in the draft store deterministically.
try {
const conversation = (ctx as unknown as { conversation?: ConversationFace }).conversation;
const shell = conversation?.input?.shell?.(sessionId);
if (shell && typeof shell.setDraft === 'function') {
shell.setDraft(text);
return true;
}
} catch {
// Fall through to the DOM path below.
}
try {
return fillComposerDom(text);
} catch {
return false;
}
},
};
},
}, Reader);
yield installOfficialSlots(ctx);
yield installReaderEntry(ctx);
});
}

View File

@ -0,0 +1,28 @@
/** Transitions.dev Reasoning stream, adapted to appended content, never a loop. */
export const REASON_HOLD = 840;
export const REASON_STEP = 500;
export const REASON_LINES = 2;
/** Ceiling on how much text one catch-up step may cover. */
export const REASON_MAX_LINES = 40;
/** Beat between catch-up steps, while the transcript is still well behind. */
export const REASON_CHASE_HOLD = 40;
export function reasoningTarget(
top: number,
contentHeight: number,
viewportHeight: number,
lineHeight: number,
backlogLines = 0,
): number {
const end = Math.max(0, contentHeight - viewportHeight);
const current = Math.min(end, Math.max(0, top));
// `backlogLines` is how far the newest text sits below what is painted. The
// reference step size is a reading pace: two lines, then a hold. That pace is
// far slower than a fast model writes, so the viewport used to crawl behind in
// fixed hops no matter how quickly the text arrived. Covering the backlog in
// one step keeps the newest line with the text instead; a model that writes at
// or below the reading pace still leaves the backlog at two lines, unchanged.
const lines = Math.max(REASON_LINES, Math.min(REASON_MAX_LINES, Math.ceil(backlogLines)));
return Math.min(end, current + Math.max(1, lineHeight) * lines);
}

340
src/client/rewind-cut.ts Normal file
View File

@ -0,0 +1,340 @@
/**
* Which chat rows a `/rewind` withdrew, expressed as a pure function of the
* chat snapshot.
*
* WHY THIS EXISTS. A rewind never deletes history: the host appends one
* replacement `user/message` marker whose `surfaceOp` shadows everything after
* the target, and the transcript must then read as it did *before* the target
* was sent. The official ChatView is a per-node renderer, so the rewind plugin
* (`dsh-rewind-plugin`) hides withdrawn rows by DOM: it computes the shadowed
* anchor seqs from the command node and sets `display:none` on every element
* carrying the official `data-chat-anchor-key` seat attribute.
*
* The Reader replaces ChatView's message list and renders its own row shapes
* (turn sections, answer articles, tool rows), so it does not republish that
* seat attribute on every row. DOM hiding therefore reaches only the user and
* steering bubbles, and every other withdrawn row — the answer, the tool rows,
* and the `/rewind` command row itself — stayed on screen. That is the reported
* defect: the command is recorded as a rewind row instead of the Reader rolling
* back to the state before the message was sent.
*
* The Reader decides visibility from React state, so it must apply the same
* contract itself instead of waiting for a third-party MutationObserver. The
* marker node is not admitted as a chat node (only append-origin surface events
* become nodes), so the command node's `outcome.sourceEventSeq` — the marker's
* log seq — plus the `@<seq>` target in its `args` are the only client-side
* signal for the shadowed range. This mirrors the plugin's own reader of that
* contract, and is pinned by `tests/rewind-cut.test.ts` so a plugin or host
* change cannot silently regress it.
*
* @module dsh-better-display/rewind-cut
*/
/** A chat-snapshot view node, read structurally (only the fields this module needs). */
export interface CutChatNode {
readonly key: string;
readonly kind?: string;
readonly anchorSeq?: number;
readonly visibility?: string;
readonly data?: unknown;
/**
* Where the host placed the node in the session's location index. Only the
* owning turn is read from it, and an absent or foreign location is fine.
*/
readonly location?: unknown;
}
/** The minimal chat-snapshot reader the cut logic needs. */
export interface CutChat {
readonly order: readonly string[];
readonly nodes: {
get(key: string): CutChatNode | undefined;
};
}
/** One closed shadow range `[start, end]` in surface/anchor seq space. */
export interface CutSpan {
readonly start: number;
readonly end: number;
}
function asRecord(value: unknown): Record<string, unknown> | undefined {
return typeof value === 'object' && value !== null && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function safeSeq(value: unknown): number | undefined {
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
}
/** The command payload of a `command` chat node, when it is structurally readable. */
function commandOf(node: CutChatNode): Record<string, unknown> | undefined {
if (node.kind !== 'command') return undefined;
return asRecord(node.data);
}
/**
* The engine names an executed rewind command node can carry. The plugin
* registers its command as `rewind-plugin` (`ENGINE_COMMANDS = new
* Set(['rewind-plugin', 'rewind'])` in dsh-rewind-plugin's
* `src/client/hidden.ts`), and that is the name the client projection actually
* publishes — the session log's `command/run.name` is not what the Reader sees.
* `rewind` stays accepted because older logs and the bili-side proxy record the
* shorter spelling.
*/
const REWIND_COMMANDS: ReadonlySet<string> = new Set(['rewind-plugin', 'rewind']);
/** True when a command payload is the rewind engine command, in either spelling. */
function isRewindCommand(command: Record<string, unknown>): boolean {
return typeof command.name === 'string' && REWIND_COMMANDS.has(command.name);
}
/**
* The render POSITION a row is anchored at: the view node's `anchorSeq`, else
* its payload seq.
*
* This is deliberately NOT integer-only. The host anchors synthetic rows at
* fractional offsets off a real seq (`CHAT_SYNTHETIC_SEQ_OFFSETS` in the
* official ChatView: `turn-process` at `controlAnchorSeq - 0.1`, `turn-tail` at
* `seq + 0.1`, an interrupted assistant step at `seq - 0.9`). An integer-only
* read made those rows invisible to the cut, so the last `turn-process` of a
* withdrawn turn survived on its own. Log seqs (marker, target) stay integer:
* see `safeSeq`.
*/
export function anchorSeqOf(node: CutChatNode): number | undefined {
const raw = node.anchorSeq ?? asRecord(node.data)?.seq;
return typeof raw === 'number' && Number.isFinite(raw) && raw >= 0 ? raw : undefined;
}
/**
* Extract the rewind target seq from a `/rewind` command's structured `args`
* (e.g. `@5 chat`, `preview @5 both`). Locale-independent: it never parses the
* host's human outcome copy.
*/
export function rewindTargetOfArgs(args: unknown): number | undefined {
if (typeof args !== 'string') return undefined;
const match = args.match(/@(\d+)/);
return match === null ? undefined : Number(match[1]);
}
/** True for the internal candidate-list probe (`/rewind __candidates`). */
function isCandidateCommand(command: Record<string, unknown>): boolean {
return typeof command.args === 'string' && command.args.includes('__candidates');
}
/** True for an impact preview (`/rewind preview @5 both`). */
function isPreviewCommand(command: Record<string, unknown>): boolean {
return typeof command.args === 'string' && command.args.includes('preview');
}
/**
* Merge overlapping or touching shadow ranges.
*
* Spans are kept SEPARATE unless they genuinely overlap: collapsing every cut
* to `[min target, max marker]` would hide a still-on-surface gap of new traffic
* between an earlier marker and a later target.
*/
export function coalesceCutSpans(spans: readonly CutSpan[]): CutSpan[] {
if (spans.length < 2) return [...spans];
const sorted = [...spans].sort((left, right) => left.start - right.start || left.end - right.end);
const merged: { start: number; end: number }[] = [];
for (const span of sorted) {
const last = merged.at(-1);
if (last !== undefined && span.start <= last.end) {
if (span.end > last.end) last.end = span.end;
continue;
}
merged.push({ start: span.start, end: span.end });
}
return merged;
}
/**
* True when a row anchored at `seq` falls inside one of the cut spans.
*
* A cut runs from the target seq through the marker's own log seq, inclusive
* (`target <= anchorSeq && anchorSeq <= marker`), the same comparison
* `dsh-rewind-plugin`'s `RewindVisibilityBuilder` uses. The upper bound stops
* at the marker. Extending it to the next integer hides the following turn's
* process row, which the host anchors at `startSeq - 0.1` and therefore in
* `[marker, marker + 1)`. Fractional anchors inside the closed range still
* match: `anchorSeqOf` keeps them. A process or tail row parked outside the
* range is handled by `summaryTurns`, not by widening the cut. Spans stay
* disjoint, so new traffic between two rewinds survives.
*/
export function cutContains(cuts: readonly CutSpan[], seq: number): boolean {
let low = 0;
let high = cuts.length - 1;
let found = -1;
while (low <= high) {
const middle = (low + high) >> 1;
const cut = cuts[middle];
if (cut === undefined) return false;
if (seq < cut.start) high = middle - 1;
else {
found = middle;
low = middle + 1;
}
}
const span = found < 0 ? undefined : cuts[found];
return span !== undefined && seq <= span.end;
}
/** The turn id a node belongs to (absent outside a turn). */
function turnIdOf(node: CutChatNode): unknown | undefined {
// The location's own `kind` varies (`turn` for a turn's synthetic rows,
// `step` for one of its messages); only the turn it carries matters here.
const turn = asRecord(asRecord(node.location)?.turn);
if (turn === undefined || !Object.hasOwn(turn, 'turn')) return undefined;
return turn.turn;
}
/**
* Node kinds that SUMMARIZE a turn instead of carrying its content, so the host
* anchors them at the turn's edges rather than at an event inside it.
*/
const TURN_SUMMARY_KINDS: ReadonlySet<string> = new Set(['turn-process', 'turn-tail']);
/**
* True for a rewind command row the transcript should not keep.
*
* Probes (`preview`, `__candidates`) exist only to feed the popover. An
* executed rewind — success plus a marker seq — is the command that performed
* the cut, and the plugin hides that row even when its anchor sits outside
* the numeric range. A failed or still-running command stays visible.
*/
function commandHidden(node: CutChatNode): boolean {
const command = commandOf(node);
if (command === undefined || !isRewindCommand(command)) return false;
if (isPreviewCommand(command) || isCandidateCommand(command)) return true;
const outcome = asRecord(command.outcome);
return outcome?.kind === 'success' && safeSeq(outcome.sourceEventSeq) !== undefined;
}
/** True when the row's own anchor falls in a cut, or the row is a rewind command to hide. */
function anchorWithdrawn(node: CutChatNode, cuts: readonly CutSpan[]): boolean {
if (commandHidden(node)) return true;
const seq = anchorSeqOf(node);
return seq !== undefined && cutContains(cuts, seq);
}
/**
* Turns whose process and tail rows must leave.
*
* The host opens a turn before its user message is logged and anchors
* `turn-process` at `controlAnchorSeq - 0.1`, below the first withdrawn
* event, and `turn-tail` at `turn.end.seq + 0.1`, which can sit past the
* marker. Containment therefore misses those two rows, and the transcript
* kept announcing `执行过程 / 本轮已停止,已生成的内容仍保留。`
*
* A summary leaves only when every content row of its turn is already
* withdrawn — the same rule as the plugin's `deriveTurnProcess`. One content
* row before the target (a mid-turn steering rewind) keeps the summary and
* that earlier message. A turn with no content rows is left alone.
*/
function summaryTurns(chat: CutChat, cuts: readonly CutSpan[]): Set<unknown> {
const stays = new Map<unknown, boolean>();
for (const key of chat.order) {
const node = chat.nodes.get(key);
if (node === undefined || TURN_SUMMARY_KINDS.has(node.kind ?? '')) continue;
const id = turnIdOf(node);
if (id === undefined) continue;
const visible = node.visibility !== 'hidden' && !anchorWithdrawn(node, cuts);
stays.set(id, (stays.get(id) ?? false) || visible);
}
const withdrawn = new Set<unknown>();
for (const [id, visible] of stays) if (!visible) withdrawn.add(id);
return withdrawn;
}
/** True when this row is a summary of a turn whose content is fully withdrawn. */
function summaryWithdrawn(node: CutChatNode, summaries: ReadonlySet<unknown>): boolean {
if (!TURN_SUMMARY_KINDS.has(node.kind ?? '')) return false;
const id = turnIdOf(node);
return id !== undefined && summaries.has(id);
}
/**
* The shadow ranges a session's executed rewinds produced, newest state last.
* An executed rewind cuts `[target, marker]` — the target itself is included,
* because a rewind restores the state *before* that message was sent (its text
* goes back to the composer).
*/
export function rewindCutSpans(chat: CutChat | undefined): CutSpan[] {
if (chat === undefined) return [];
const spans: CutSpan[] = [];
for (const key of chat.order) {
const node = chat.nodes.get(key);
if (node === undefined) continue;
const command = commandOf(node);
if (command === undefined || !isRewindCommand(command)) continue;
// Probes never open a span, even when a later host stamps them with a
// success marker. Matching them would roll the transcript back on preview.
if (isPreviewCommand(command) || isCandidateCommand(command)) continue;
const outcome = asRecord(command.outcome);
if (outcome?.kind !== 'success') continue;
const marker = safeSeq(outcome.sourceEventSeq);
if (marker === undefined) continue;
const target = rewindTargetOfArgs(command.args);
if (target === undefined || target > marker) continue;
spans.push({ start: target, end: marker });
}
return coalesceCutSpans(spans);
}
/**
* The anchor seqs the Reader must not render: every withdrawn message (the
* target, everything after it, and the unrendered marker), plus every `/rewind`
* row that exists only to feed the popover — the candidate-list probe and each
* impact preview. A SUCCESSFUL executed command row is covered by its own cut;
* a failed or unsettled one stays visible as an ordinary command record.
*/
export function hiddenRewindSeqs(chat: CutChat | undefined): Set<number> {
const hidden = new Set<number>();
if (chat === undefined) return hidden;
const cuts = rewindCutSpans(chat);
const summaries = summaryTurns(chat, cuts);
for (const key of chat.order) {
const node = chat.nodes.get(key);
if (node === undefined) continue;
if (!anchorWithdrawn(node, cuts) && !summaryWithdrawn(node, summaries)) continue;
const seq = anchorSeqOf(node);
if (seq !== undefined) hidden.add(seq);
}
return hidden;
}
/**
* The chat keys the Reader should render, in snapshot order: withdrawn rows and
* rows the host itself marked hidden are dropped, everything else keeps its
* position. Returns the snapshot's own `order` array when nothing is filtered,
* so React selectors see a stable reference.
*/
export function visibleChatKeys(chat: CutChat): readonly string[] {
const cuts = rewindCutSpans(chat);
const summaries = summaryTurns(chat, cuts);
const visible: string[] = [];
for (const key of chat.order) {
const node = chat.nodes.get(key);
if (node === undefined) continue;
if (node.visibility === 'hidden') continue;
if (anchorWithdrawn(node, cuts) || summaryWithdrawn(node, summaries)) continue;
visible.push(key);
}
return visible.length === chat.order.length ? chat.order : visible;
}
/**
* A comparable signal for the visible row set, built for
* `useSyncExternalStore`-style subscription: the host re-runs a chat selector
* on every publish and compares the RESULT by `Object.is`, and a rewind
* publishes an in-place upsert of an existing command row. The snapshot's
* `order` array and node store are therefore both reference-stable across a
* rewind, so a selector on them never re-renders; a string does change exactly
* when the visible set does. Never return the array itself from a selector —
* a fresh array fails the `Object.is` check on every publish.
*/
export function visibleChatSignature(chat: CutChat): string {
return visibleChatKeys(chat).join('\u0000');
}

View File

@ -0,0 +1,74 @@
export type SettingsCopyKey =
| 'nav'
| 'openTitle'
| 'openDescription'
| 'glassTitle'
| 'glassDescription'
| 'foldTitle'
| 'foldDescription'
| 'foldNone'
| 'foldStandard'
| 'foldSummary'
| 'skillTitle'
| 'skillInstalled'
| 'skillMissing'
| 'skillPurpose'
| 'skillPluginNote'
| 'skillInstall'
| 'skillRecheck'
| 'skillChecking'
| 'skillUnavailable';
export type SettingsCopy = Record<SettingsCopyKey, string>;
export const en: SettingsCopy = {
nav: 'Better Display',
openTitle: 'Open deliverables in built-in panel',
openDescription: 'Off by default: chips and inline file mentions open in the system app. Turn this on to preview them in the right Sidebar, matching official chat. Reveal and folder actions still use the system file manager.',
glassTitle: 'Translucent frosted glass',
glassDescription: 'Off by default: reading chrome stays opaque, matching the current Host look. Turn this on to let wallpaper and skins show through the panel; path and count chips stay clear until hover or focus.',
foldTitle: 'Auto-fold process',
foldDescription: 'Default on: collapses earlier steps when new thoughts appear. Turn off to keep all thinking and tools expanded in full.',
foldNone: 'Off',
foldStandard: 'On',
foldSummary: 'Summary',
skillTitle: 'generative-mcpapps skill',
skillInstalled: 'Installed',
skillMissing: 'Not detected',
skillPurpose: 'This install is for model auto-selection of MCP Apps. Reader already renders mcp-app fences when the model emits them.',
skillPluginNote: 'Shipping the pack inside this plugin repository does not install it into the harness skill catalog.',
skillInstall: 'Copy the whole generative-mcpapps folder (including references and examples) into .dsh/skills or .agents/skills — in your home or the project, you choose — then Re-check. There is no one-click install that works on every host.',
skillRecheck: 'Re-check',
skillChecking: 'Checking…',
skillUnavailable: 'Could not query the host skill catalog. Copy into .dsh/skills or .agents/skills (home or project), then Re-check.',
};
export const zh: SettingsCopy = {
nav: 'Better Display',
openTitle: '在内置面板中打开产物',
openDescription: '默认关闭:产物芯片和正文中的文件提及会用系统应用打开。打开后与官方对话一致,在右侧栏预览。访达 / 资源管理器中的显示与打开所在文件夹不受此开关控制。',
glassTitle: '半透明毛玻璃',
glassDescription: '默认关闭:阅读栏保持不透明,和现在的 Host 观感一致。打开后透出宿主壁纸与皮肤;路径、行数等标签静止时透明,悬停或聚焦才显出轮廓。',
foldTitle: '自动折叠过程',
foldDescription: '默认开启:新思考产生时自动折叠此前步骤。关闭后全程展开,完整保留原始思考与工具流。',
foldNone: '关闭',
foldStandard: '开启',
foldSummary: '摘要',
skillTitle: 'generative-mcpapps 技能',
skillInstalled: '已安装',
skillMissing: '未检测到',
skillPurpose: '这项安装是为了让模型自动选用 MCP Apps。阅读页在模型写出 mcp-app 代码块时已经会渲染,不依赖该技能是否装进宿主。',
skillPluginNote: '技能包只出现在本插件仓库里,并不等于当前 Agent 已经加载它。',
skillInstall: '把完整的 generative-mcpapps 文件夹(含 references 与 examples)复制到 .dsh/skills 或 .agents/skills(家目录或项目目录,由你选),然后重新检测。没有在所有宿主上都可用的一键安装。',
skillRecheck: '重新检测',
skillChecking: '正在检测…',
skillUnavailable: '无法查询宿主技能目录。请复制到 .dsh/skills 或 .agents/skills(家目录或项目),再重新检测。',
};
export function settingsLanguage(tag: string | undefined): 'zh' | 'en' {
return (tag ?? '').toLowerCase().startsWith('zh') ? 'zh' : 'en';
}
export function settingsCopyFor(tag: string | undefined): SettingsCopy {
return settingsLanguage(tag) === 'zh' ? zh : en;
}

View File

@ -0,0 +1,20 @@
/**
* Community-plugin SlotMap merge for Settings pages.
* Official plugins import `@deepseek-ai/dsh-client-ui-settings/client` instead.
* Shape matches that package's `settings.section` (list / root / close).
*/
import type { SettingsCopyKey } from './settings-copy.js';
export interface SettingsSectionOwnerProps {
/** Close the settings panel (the shell owns the open state). */
close: () => void;
}
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface SlotMap {
'settings.section': { kind: 'list'; scope: 'root'; owner: SettingsSectionOwnerProps };
}
interface LocaleNamespaceMap {
'better-display': SettingsCopyKey;
}
}

73
src/client/settings.tsx Normal file
View File

@ -0,0 +1,73 @@
import type { Context } from '@deepseek-ai/cordis';
import type {} from './settings-slots.js';
import { settingsCopyFor, zh, en } from './settings-copy.js';
import { SettingsSection, type BetterDisplaySettingsInjected, type OpenPrefs } from './SettingsSection.js';
import { firstSessionId, skillsFromListResult, type SkillStatusProbe } from './skill-status.js';
import type { HostSkillStatus } from '../skill-status.js';
interface LocaleFace {
register?: (ns: string, dicts: { zh: unknown; en: unknown }) => () => void;
bind?: (ns: string) => (key: string) => string;
getSnapshot?: () => { locale?: string; language?: string };
}
interface RemoteSkillsFace {
list?: (arg: { sessionId: string }, signal?: AbortSignal) => Promise<unknown>;
}
function languageTag(ctx: Context): string | undefined {
const locale = (ctx.get?.('locale') ?? (ctx as unknown as { locale?: LocaleFace }).locale) as LocaleFace | undefined;
const snap = locale?.getSnapshot?.();
return snap?.locale ?? snap?.language
?? (typeof document !== 'undefined' ? document.documentElement.lang : undefined)
?? (typeof navigator !== 'undefined' ? navigator.language : undefined);
}
function createSkillProbe(ctx: Context): SkillStatusProbe {
return {
fetchHostStatus: async () => {
const sessions = ctx.sessions as { list?: { getSnapshot?: () => { byId?: Record<string, { cwd?: string }> } } } | undefined;
const snap = sessions?.list?.getSnapshot?.();
const id = firstSessionId(snap);
const cwd = id && snap?.byId ? snap.byId[id]?.cwd : undefined;
const url = cwd
? `/better-display/skill-status?cwd=${encodeURIComponent(cwd)}`
: '/better-display/skill-status';
const res = await fetch(url);
if (!res.ok) return undefined;
return await res.json() as HostSkillStatus;
},
listRemoteSkills: async () => {
const remote = ctx.remote as unknown as { skills?: RemoteSkillsFace } | undefined;
const skills = remote?.skills
?? (ctx.get?.('remote.skills') as RemoteSkillsFace | undefined)
?? ((ctx.get?.('remote') as { skills?: RemoteSkillsFace } | undefined)?.skills);
const sessions = ctx.sessions as { list?: { getSnapshot?: () => { ids?: string[]; byId?: Record<string, unknown> } } } | undefined;
const sessionId = firstSessionId(sessions?.list?.getSnapshot?.());
if (!skills?.list || !sessionId) return undefined;
return skillsFromListResult(await skills.list({ sessionId }));
},
};
}
export function installBetterDisplaySettings(ctx: Context, prefs: OpenPrefs): void {
const locale = (ctx.get?.('locale') ?? (ctx as unknown as { locale?: LocaleFace }).locale) as LocaleFace | undefined;
if (locale?.register) {
ctx.effect(() => locale.register!('better-display', { zh, en }), 'dsh-better-display: settings copy');
}
const checkSkill = createSkillProbe(ctx);
const injected = (): BetterDisplaySettingsInjected => ({
prefs,
copy: settingsCopyFor(languageTag(ctx)),
languageTag: languageTag(ctx),
checkSkill,
});
ctx.slots.inject('settings.section', () => ctx.slots.register({
name: 'settings.section',
id: 'better-display',
order: 40,
label: () => locale?.bind?.('better-display')?.('nav') || settingsCopyFor(languageTag(ctx)).nav,
locale: locale?.bind ? 'better-display' : undefined,
inject: injected,
}, SettingsSection));
}

View File

@ -0,0 +1,78 @@
import {
CONVENTIONAL_SKILL_ROOTS,
GENERATIVE_MCPAPPS_SKILL,
SKILL_PACK_RELATIVE,
publicSkillRoots,
skillListIncludes,
skillsFromListResult,
toPublicSkillStatus,
type HostSkillStatus,
} from '../skill-status.js';
export {
CONVENTIONAL_SKILL_ROOTS,
GENERATIVE_MCPAPPS_SKILL,
SKILL_PACK_RELATIVE,
publicSkillRoots,
skillListIncludes,
skillsFromListResult,
toPublicSkillStatus,
};
export type { HostSkillStatus };
export interface SkillStatusSnapshot {
readonly name: typeof GENERATIVE_MCPAPPS_SKILL;
readonly installed: boolean;
readonly via: 'skills.list' | 'skill-root' | null;
readonly roots: HostSkillStatus['roots'];
readonly packPath?: string;
readonly hostReached: boolean;
}
export interface SkillStatusProbe {
listRemoteSkills?: () => Promise<readonly { readonly name?: string }[] | undefined>;
fetchHostStatus?: () => Promise<HostSkillStatus | undefined>;
}
export async function detectGenerativeMcpappsSkill(probe: SkillStatusProbe): Promise<SkillStatusSnapshot> {
let host: HostSkillStatus | undefined;
if (probe.fetchHostStatus) {
try {
host = await probe.fetchHostStatus();
} catch {
host = undefined;
}
}
let remoteHit = false;
if (probe.listRemoteSkills) {
try {
remoteHit = skillListIncludes(await probe.listRemoteSkills());
} catch {
remoteHit = false;
}
}
const installed = Boolean(host?.installed || remoteHit);
const via = remoteHit ? 'skills.list' : (host?.via ?? null);
const publicHost = host === undefined ? undefined : toPublicSkillStatus(host);
return {
name: GENERATIVE_MCPAPPS_SKILL,
installed,
via,
roots: publicHost?.roots ?? publicSkillRoots(),
hostReached: host !== undefined,
};
}
/** mkdir/cp using conventional relative roots only. Host paths are ignored. */
export function shortestInstallCommand(_status?: Pick<SkillStatusSnapshot, 'packPath' | 'roots'>): string {
const dest = CONVENTIONAL_SKILL_ROOTS[0];
return `mkdir -p ${dest} && cp -R ${SKILL_PACK_RELATIVE} ${dest}/`;
}
export function firstSessionId(list: { ids?: readonly string[]; byId?: Record<string, unknown> } | undefined): string | undefined {
if (list?.ids && list.ids.length > 0) return list.ids[0];
const keys = list?.byId ? Object.keys(list.byId) : [];
return keys[0];
}

70
src/client/store.ts Normal file
View File

@ -0,0 +1,70 @@
import { defineStore } from '@deepseek-ai/dsh-client-store';
import type { EngineStoreHandle } from '@deepseek-ai/dsh-client-store';
import {
FOLD_INTENSITY_DEFAULT,
autoFoldFromIntensity,
processOnlyFromIntensity,
type FoldIntensity,
} from './fold-intensity.js';
import type { DeliverableOpenMode } from './open-file.js';
export interface ReaderState {
expanded: Record<string, boolean>;
motion: boolean;
/** Derived from foldIntensity; kept so older persisted snapshots still read. */
autoFold: boolean;
/** Default stays the system app. `sidebar` is opt-in. */
deliverableOpenMode: DeliverableOpenMode;
/**
* 0 = no auto-fold, 1 = current-main fold-on-next-reasoning (default),
* 2 = process-summary mode from community PR #14.
*/
foldIntensity: FoldIntensity;
/** Translucent frosted chrome. Default off so opaque main chrome stays. */
frostedGlass: boolean;
/** Derived from foldIntensity === 2; kept for older #14 snapshots. */
processOnly: boolean;
}
type ReaderActions = {
setExpanded: (draft: ReaderState, key: string, value: boolean) => void;
resetExpanded: (draft: ReaderState) => void;
setMotion: (draft: ReaderState, value: boolean) => void;
setAutoFold: (draft: ReaderState, value: boolean) => void;
setDeliverableOpenMode: (draft: ReaderState, value: DeliverableOpenMode) => void;
setFoldIntensity: (draft: ReaderState, value: FoldIntensity) => void;
setFrostedGlass: (draft: ReaderState, value: boolean) => void;
};
function applyFoldIntensity(draft: ReaderState, value: FoldIntensity): void {
draft.foldIntensity = value;
draft.autoFold = autoFoldFromIntensity(value);
draft.processOnly = processOnlyFromIntensity(value);
}
export function createReaderStore(): EngineStoreHandle<ReaderState, ReaderActions> {
return defineStore({
init: (): ReaderState => ({
expanded: {},
motion: true,
autoFold: true,
deliverableOpenMode: 'external',
foldIntensity: FOLD_INTENSITY_DEFAULT,
frostedGlass: false,
processOnly: false,
}),
persist: 'dsh.reader.v1',
actions: {
setExpanded: (draft, key: string, value: boolean) => { draft.expanded[key] = value; },
resetExpanded: draft => { draft.expanded = {}; },
setMotion: (draft, value: boolean) => { draft.motion = value; },
setAutoFold: (draft, value: boolean) => {
applyFoldIntensity(draft, value
? (draft.foldIntensity === 2 ? 2 : 1)
: 0);
},
setDeliverableOpenMode: (draft, value: DeliverableOpenMode) => { draft.deliverableOpenMode = value; },
setFoldIntensity: (draft, value: FoldIntensity) => { applyFoldIntensity(draft, value); },
setFrostedGlass: (draft, value: boolean) => { draft.frostedGlass = value; },
},
});
}

136
src/client/stream-buffer.ts Normal file
View File

@ -0,0 +1,136 @@
/** Presentation only. The original session string remains the source of truth. */
// The reveal runs at the rate the source is actually producing (feed-forward)
// plus a proportional term that closes whatever backlog jitter left behind.
// A proportional-only controller drains exactly one window per window, so the
// display trails live output by catchUpMs forever — unreadable-but-smooth at
// 75 chars/s, permanently behind at 1000. The feed-forward term is what makes
// the pace adapt to the model instead of to a fixed constant.
export const STREAM_TIMING = {
catchUpMs: 520,
maxQueuedMs: 600,
finishMs: 96,
revealMs: 350,
minimumRate: 260,
/** Weight of the newest arrival sample in the smoothed source rate. */
rateWeight: 0.35,
/** A longer gap is a pause between runs, not a slow model: keep the estimate. */
rateGapMs: 250,
} as const;
const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
function atOrAfter(values: readonly number[], target: number): number {
let low = 0;
let high = values.length - 1;
while (low < high) {
const middle = (low + high) >>> 1;
if (values[middle]! < target) low = middle + 1;
else high = middle;
}
return low;
}
export class StreamBuffer {
target: string;
visible: string;
revision = 0;
private boundaries = [0];
private arrivals: { end: number; at: number }[] = [];
private lastAt: number | null = null;
private credit = 0;
private finishAt: number | null = null;
private rateEwma = 0;
private lastArrival: number | null = null;
constructor(initial = '') {
this.target = initial;
this.visible = initial;
this.segment(0);
}
get pending(): boolean { return this.visible.length < this.target.length; }
private segment(from: number): void {
const index = atOrAfter(this.boundaries, from);
this.boundaries.length = index;
for (const part of graphemes.segment(this.target.slice(from))) this.boundaries.push(from + part.index);
if (this.boundaries.at(-1) !== this.target.length) this.boundaries.push(this.target.length);
}
/** Non-append updates, cancellations and hidden/reduced views never replay. */
update(text: string, now: number, options: { immediate?: boolean; finished?: boolean } = {}): void {
if (options.immediate || !text.startsWith(this.target)) {
if (text !== this.target) this.revision++;
this.target = text;
this.flush();
this.boundaries = [0];
this.segment(0);
return;
}
if (text !== this.target) {
const wasPending = this.pending;
const grew = text.length - this.target.length;
const from = this.boundaries.at(-2) ?? 0;
this.observe(grew, now);
this.target = text;
// Re-segment the previous last cluster: an emoji/combining sequence can
// itself span transport chunks. Frozen source prefixes are not scanned.
this.segment(from);
this.arrivals.push({ end: text.length, at: now });
if (!wasPending) { this.lastAt = now; this.credit = 0; }
}
if (options.finished && this.finishAt === null) this.finishAt = now + STREAM_TIMING.finishMs;
if (!options.finished) this.finishAt = null;
if (this.target.length - this.visible.length > 8192) { this.revision++; this.flush(); }
}
/** Smoothed source rate, so one jittery transport chunk cannot set the pace. */
private observe(grew: number, now: number): void {
const previous = this.lastArrival;
this.lastArrival = now;
if (previous === null || grew <= 0) return;
const elapsed = now - previous;
if (elapsed <= 0 || elapsed > STREAM_TIMING.rateGapMs) return;
const sample = grew * 1000 / elapsed;
this.rateEwma = this.rateEwma === 0
? sample
: this.rateEwma * (1 - STREAM_TIMING.rateWeight) + sample * STREAM_TIMING.rateWeight;
}
flush(): void {
this.visible = this.target;
this.arrivals = [];
this.credit = 0;
this.lastAt = null;
this.lastArrival = null;
this.finishAt = null;
}
advance(now: number): boolean {
if (!this.pending) return false;
const before = this.visible.length;
const index = atOrAfter(this.boundaries, before);
const remaining = this.boundaries.length - index - 1;
const delta = Math.max(0, now - (this.lastAt ?? now));
this.lastAt = now;
const windowMs = this.finishAt === null ? STREAM_TIMING.catchUpMs : Math.max(16, Math.min(STREAM_TIMING.catchUpMs, this.finishAt - now));
// Feed-forward keeps pace with the source; the proportional term then drains
// whatever backlog is left, so lag decays instead of settling at one window.
const rate = Math.max(STREAM_TIMING.minimumRate, this.rateEwma + remaining * 1000 / windowMs);
this.credit += rate * delta / 1000;
const count = Math.floor(this.credit);
this.credit -= count;
let end = this.boundaries[Math.min(this.boundaries.length - 1, index + count)]!;
for (const item of this.arrivals) {
if (now - item.at < STREAM_TIMING.maxQueuedMs) break;
end = Math.max(end, this.boundaries[atOrAfter(this.boundaries, item.end)]!);
}
if (this.finishAt !== null && now >= this.finishAt) end = this.target.length;
// Never expose half of a surrogate pair while the source can still grow.
if (end && /[\uD800-\uDBFF]/.test(this.target[end - 1]!) && this.finishAt === null) end--;
end = Math.max(before, end);
this.visible = this.target.slice(0, end);
this.arrivals = this.arrivals.filter(item => item.end > end);
if (!this.pending) { this.credit = 0; this.lastAt = null; }
return end !== before;
}
}

70
src/client/streaming.tsx Normal file
View File

@ -0,0 +1,70 @@
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { StreamBuffer } from './stream-buffer.js';
import { WORD_MOTION } from './word-timeline.js';
export const StreamMotionContext = createContext<{ enabled: boolean; activatedAt: number; paused?: boolean; resumed?: boolean }>({ enabled: false, activatedAt: 0 });
export function useStreamingText(source: string, streaming: boolean, options: { startedAt?: number; interrupted: boolean; selected: boolean }) {
const { enabled, activatedAt, paused = false, resumed = false } = useContext(StreamMotionContext);
const fresh = resumed || (options.startedAt ?? 0) >= activatedAt;
const buffer = useRef<StreamBuffer>();
// Only newly mounted content after a fold uses the catch-up path. History and
// user-opened drawers stay immediate; already mounted prefixes never replay.
if (!buffer.current) buffer.current = new StreamBuffer(enabled && (streaming || resumed) && fresh ? '' : source);
const [display, setDisplay] = useState(() => ({ text: buffer.current!.visible, revision: 0 }));
const [finalizing, setFinalizing] = useState(streaming);
const frame = useRef(0);
const immediate = !enabled || options.interrupted || options.selected;
const publish = () => {
const current = buffer.current!;
setDisplay(previous => previous.text === current.visible && previous.revision === current.revision ? previous : { text: current.visible, revision: current.revision });
};
const handoff = useRef(resumed);
const presentationClock = useRef(performance.now());
useLayoutEffect(() => {
cancelAnimationFrame(frame.current);
const current = buffer.current!;
// While the choreography holds the reveal, keep the buffer absorbing the
// source instead of returning early: the target must never lag behind what
// arrived, or the text would keep catching up long after the fold settled.
// Dropping the frame loop is what pauses the reveal; the target still tracks.
if (paused && !immediate && !document.hidden) {
current.update(source, performance.now(), { immediate: false, finished: !streaming });
publish();
return;
}
let previous = performance.now();
current.update(source, handoff.current ? presentationClock.current : previous, { immediate: immediate || document.hidden, finished: !streaming && !resumed });
publish();
const tick = (now: number) => {
// A delayed browser frame must not dump the whole buffered response at
// first paint. Bound catch-up by visible frame time for this handoff only.
presentationClock.current += Math.min(32, Math.max(0, now - previous));
previous = now;
if (document.hidden) current.flush();
else current.advance(handoff.current ? presentationClock.current : now);
publish();
if (current.pending) frame.current = requestAnimationFrame(tick);
else handoff.current = false;
};
if (current.pending) frame.current = requestAnimationFrame(tick);
return () => cancelAnimationFrame(frame.current);
}, [source, streaming, immediate, paused, resumed]);
useEffect(() => {
const hidden = () => {
if (!document.hidden) return;
cancelAnimationFrame(frame.current);
buffer.current!.flush(); publish(); setFinalizing(false);
};
document.addEventListener('visibilitychange', hidden);
return () => document.removeEventListener('visibilitychange', hidden);
}, []);
const pending = display.text !== source;
useEffect(() => {
if (streaming || pending) { setFinalizing(true); return; }
if (immediate || document.hidden) { setFinalizing(false); return; }
const timer = setTimeout(() => setFinalizing(false), WORD_MOTION.duration + WORD_MOTION.maxDelay);
return () => clearTimeout(timer);
}, [streaming, pending, immediate]);
return { text: immediate ? source : display.text, pending: !immediate && pending, revision: display.revision, formatStreaming: streaming || (!immediate && (pending || finalizing)), reveal: enabled && !options.interrupted && !options.selected };
}

4
src/client/style.d.ts vendored Normal file
View File

@ -0,0 +1,4 @@
declare module '*.module.css' {
const classes: Record<string, string>;
export default classes;
}

22
src/client/styles.ts Normal file
View File

@ -0,0 +1,22 @@
const plugin = 'dsh-better-display';
const styles = new Map<string, string>();
/** Retain injected CSS across host cleanup and restore it before Reader paints. */
export function ensureStyles(): void {
if (typeof document === 'undefined') return;
const live = new Set<string>();
for (const tag of document.querySelectorAll<HTMLStyleElement>(`style[data-plugin="${plugin}"][data-plugin-css]`)) {
const id = tag.dataset.pluginCss;
if (id === undefined) continue;
styles.set(id, tag.textContent ?? '');
live.add(id);
}
for (const [id, text] of styles) {
if (live.has(id)) continue;
const tag = document.createElement('style');
tag.dataset.plugin = plugin;
tag.dataset.pluginCss = id;
tag.textContent = text;
document.head.appendChild(tag);
}
}

View File

@ -0,0 +1,265 @@
import { useEffect, useMemo, useState } from 'react';
import type { ReaderBlockOwner, ReaderBlockPresentation } from './types.js';
/**
* Cordis service name. Another client plugin lists this in `inject` and
* registers a transformer. The reading view paints the result. The session
* block, transcript, and fold inputs stay on the original text.
*/
export const TEXT_TRANSFORM_SERVICE = 'dsh-better-display.text-transform';
export type DisplayTextKind = 'reasoning' | 'body';
export interface DisplayTextRequest {
/** Original block text. Registrants must not write it back onto the block. */
text: string;
streaming: boolean;
/** Opaque id of this mounted block. Stable until the block unmounts. */
blockKey: string;
kind: DisplayTextKind;
/** Assistant body and reasoning are the usual targets. Tool prose uses `tool`. */
source?: ReaderBlockOwner['source'];
}
export interface DisplayText {
text: string;
/**
* True when this string is the settled display for the current source.
* False keeps the live reveal open, including after the model has stopped
* but a translation batch is still outstanding.
*/
final: boolean;
}
/**
* Sync `read` on every paint, plus `subscribe` when a later batch changes
* what `read` returns. `subscribe` may be called once per kind and must
* accept more than one listener.
*/
export interface DisplayTextTransformer {
read(request: DisplayTextRequest): DisplayText | string | undefined;
subscribe?(listener: () => void): () => void;
}
export interface DisplayCursor extends DisplayText {
/**
* Increments when the displayed string or its `final` bit changes.
* This is not the reveal clock. Passing it to the word timeline as the
* motion revision replays or snaps the paragraph.
*/
transformRevision: number;
/**
* Reveal identity. Stays put when the new string extends the previous
* display string, so an appended translation batch continues the fade.
* Increments only when the string is replaced, which settles the new
* text instead of typing it again from the first grapheme.
*/
motionRevision: number;
}
export interface TextTransformRegistry {
register(kind: DisplayTextKind | readonly DisplayTextKind[], transformer: DisplayTextTransformer): () => void;
has(kind: DisplayTextKind): boolean;
read(request: DisplayTextRequest): DisplayCursor;
subscribe(kind: DisplayTextKind, listener: () => void): () => void;
release(kind: DisplayTextKind, blockKey: string): void;
}
const KINDS = new Set<DisplayTextKind>(['reasoning', 'body']);
function isKind(value: string): value is DisplayTextKind {
return KINDS.has(value as DisplayTextKind);
}
function reportTransformError(error: unknown): void {
console.warn('[dsh-better-display] text transform failed; showing original text', error);
}
function passthrough(request: DisplayTextRequest): DisplayCursor {
return { text: request.text, final: !request.streaming, transformRevision: 0, motionRevision: 0 };
}
function normalize(value: DisplayText | string | undefined, request: DisplayTextRequest): DisplayText {
if (typeof value === 'string') return { text: value, final: !request.streaming };
if (!value || typeof value.text !== 'string') return { text: request.text, final: !request.streaming };
return { text: value.text, final: typeof value.final === 'boolean' ? value.final : !request.streaming };
}
/**
* Appends keep the motion revision. A replacement gets a new one so the
* timeline treats the swapped string as already settled.
*/
export function nextDisplayCursor(previous: DisplayCursor | undefined, display: DisplayText): DisplayCursor {
if (!previous) return { ...display, transformRevision: 0, motionRevision: 0 };
if (previous.text === display.text && previous.final === display.final) return previous;
const appended = display.text.startsWith(previous.text);
return {
text: display.text,
final: display.final,
transformRevision: previous.transformRevision + 1,
motionRevision: appended ? previous.motionRevision : previous.motionRevision + 1,
};
}
/**
* Streaming flag fed to the reveal. With no transformer this is the model's
* flag. A transformer that reports `final: !streaming` produces the same flag.
*/
export function displayStreaming(sourceStreaming: boolean, shown: Pick<DisplayCursor, 'final'>, active: boolean): boolean {
return active ? !shown.final : sourceStreaming;
}
/** No registry, or none for this kind: the source string, and no cursor write. */
export function readDisplayText(registry: TextTransformRegistry | undefined, request: DisplayTextRequest): DisplayCursor {
if (!registry?.has(request.kind)) return passthrough(request);
return registry.read(request);
}
interface StackEntry {
transformer: DisplayTextTransformer;
unsubscribe?: () => void;
}
class TextTransformRegistryImpl implements TextTransformRegistry {
private readonly stacks = new Map<DisplayTextKind, StackEntry[]>();
private readonly listeners = new Map<DisplayTextKind, Set<() => void>>();
private readonly cursors = new Map<string, DisplayCursor>();
register(kind: DisplayTextKind | readonly DisplayTextKind[], transformer: DisplayTextTransformer): () => void {
const requested = [...new Set(Array.isArray(kind) ? kind : [kind])];
for (const item of requested) {
if (!isKind(item)) throw new Error(`Unknown display text kind: ${String(item)}`);
}
const bound: { kind: DisplayTextKind; entry: StackEntry }[] = [];
for (const item of requested) {
const entry: StackEntry = { transformer };
try {
entry.unsubscribe = transformer.subscribe?.(() => { this.emit(item); });
} catch (error) {
reportTransformError(error);
}
const stack = this.stacks.get(item) ?? [];
stack.push(entry);
this.stacks.set(item, stack);
bound.push({ kind: item, entry });
this.emit(item);
}
return () => {
for (const { kind: item, entry } of bound) {
try { entry.unsubscribe?.(); } catch (error) { reportTransformError(error); }
const stack = this.stacks.get(item);
if (!stack) continue;
const next = stack.filter(candidate => candidate !== entry);
if (next.length > 0) this.stacks.set(item, next);
else this.stacks.delete(item);
this.emit(item);
}
};
}
has(kind: DisplayTextKind): boolean {
return (this.stacks.get(kind)?.length ?? 0) > 0;
}
read(request: DisplayTextRequest): DisplayCursor {
const transformer = this.stacks.get(request.kind)?.at(-1)?.transformer;
if (!transformer) return passthrough(request);
let display: DisplayText;
try {
display = normalize(transformer.read(request), request);
} catch (error) {
// A broken transformer must never hide the original text. Show it and
// ask again on the next text change or notify, so a recovered
// transformer takes over without a remount.
reportTransformError(error);
display = { text: request.text, final: !request.streaming };
}
const key = `${request.kind}\u0000${request.blockKey}`;
const next = nextDisplayCursor(this.cursors.get(key), display);
this.cursors.set(key, next);
return next;
}
subscribe(kind: DisplayTextKind, listener: () => void): () => void {
const set = this.listeners.get(kind) ?? new Set();
set.add(listener);
this.listeners.set(kind, set);
return () => { set.delete(listener); };
}
release(kind: DisplayTextKind, blockKey: string): void {
this.cursors.delete(`${kind}\u0000${blockKey}`);
}
private emit(kind: DisplayTextKind): void {
const set = this.listeners.get(kind);
if (!set) return;
for (const listener of [...set]) listener();
}
}
export function createTextTransformRegistry(): TextTransformRegistry {
return new TextTransformRegistryImpl();
}
let active: TextTransformRegistry | undefined;
/** Points the reading view at the registry this client plugin provides. */
export function installTextTransformRegistry(registry: TextTransformRegistry | undefined): () => void {
const previous = active;
active = registry;
return () => { active = previous; };
}
export function activeTextTransform(): TextTransformRegistry | undefined {
return active;
}
/**
* Subscribe while mounted. The reveal components call this only after
* `has(kind)`, so an empty registry adds no hook and no listener.
*/
export function useDisplayText(registry: TextTransformRegistry, request: DisplayTextRequest): DisplayCursor {
const [epoch, setEpoch] = useState(0);
const { text, streaming, blockKey, kind, source } = request;
useEffect(() => registry.subscribe(kind, () => { setEpoch(value => value + 1); }), [registry, kind]);
useEffect(() => () => { registry.release(kind, blockKey); }, [registry, kind, blockKey]);
return useMemo(
() => registry.read({ text, streaming, blockKey, kind, source }),
[registry, text, streaming, blockKey, kind, source, epoch],
);
}
/** Chain-slot owner. Extra fields are optional so older callers still type-check. */
export function readerBlockOwner(
block: ReaderBlockOwner['block'],
streaming: boolean,
source: ReaderBlockOwner['source'],
presentation: ReaderBlockPresentation,
holdFormatting: boolean,
): ReaderBlockOwner {
return {
block,
streaming,
source,
presentation: {
startedAt: presentation.startedAt,
interrupted: presentation.interrupted,
liveText: presentation.liveText,
},
holdFormatting,
liveText: presentation.liveText,
};
}
/** Copy actions read this. Display text never replaces it. */
export function originalAnswerText(blocks: readonly { readonly kind: string; readonly text?: string }[]): string {
return blocks.flatMap(block => block.kind === 'text' && typeof block.text === 'string' ? [block.text] : []).join('\n\n');
}
declare module '@deepseek-ai/cordis' {
interface Context {
/** Display-only reader text transforms. Present after this client plugin applies. */
'dsh-better-display.text-transform'?: TextTransformRegistry;
}
}

Some files were not shown because too many files have changed in this diff Show More