Compare commits
35 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
ef5be0408c | |
|
|
6bbca59f8d | |
|
|
066935d125 | |
|
|
8ca3b77aed | |
|
|
a163b7fd32 | |
|
|
59c6e6e2f5 | |
|
|
2020a6ebc3 | |
|
|
a388edf343 | |
|
|
eec1b3f1a6 | |
|
|
348f774669 | |
|
|
268f4c427c | |
|
|
e49b514685 | |
|
|
4d071ffa66 | |
|
|
54d8099004 | |
|
|
a0366b91cc | |
|
|
0acf291002 | |
|
|
8f2572ffa9 | |
|
|
7d1b3af497 | |
|
|
3e077eb71c | |
|
|
1d1a1a2162 | |
|
|
5b58f8c0f3 | |
|
|
858485bfcc | |
|
|
3fa55c72c3 | |
|
|
f5da78063a | |
|
|
3262d20b6f | |
|
|
418139e5a2 | |
|
|
bafa057457 | |
|
|
3135e80085 | |
|
|
9c0ee58021 | |
|
|
fa18351a16 | |
|
|
36785ffa08 | |
|
|
f57a74cd8b | |
|
|
f87055b75b | |
|
|
7774d6fc28 | |
|
|
5c80061f08 |
58
CHANGELOG.md
58
CHANGELOG.md
|
|
@ -1,8 +1,54 @@
|
|||
# Changelog
|
||||
|
||||
## 1.3.0 — 2026-11-28
|
||||
|
||||
- 新增左侧 AI 回复气泡(柔灰底色、左下对话尾角,适配浅色 / 深色 / 毛玻璃主题),多段回复合并在同一个气泡内、无段间横线,内部代码块自动提亮底色。
|
||||
- 思考与工具过程框移至 AI 回复气泡下方,与 AI 气泡共用最大宽度 `90%`(窄屏 `92%`);收起时呈现贴合胶囊,展开时保留内部滚动上限与顶部分割线;流式波次使用稳定 key,避免实时折叠重挂载。
|
||||
- 操作栏(复制 / 赞踩 / 分叉 / 指标 / 时间)移至气泡与过程框外侧最下方,移除已完成过程框标题上重复的「用时」展示。
|
||||
- 修复窄宽下回答操作栏与 `TurnMetrics` 指标胶囊挤压折行变形、以及指标浮卡在窄屏下冲出右侧边界的问题。
|
||||
- 验证:`tsc --noEmit`、`vitest run`(34 个文件 / 258 个用例)、`tsdown` 构建通过。
|
||||
|
||||
## 1.2.0 — 2026-11-28
|
||||
|
||||
- 阅读视图改为直接接管「对话」页签:在 `conversation.view` 里以 `id: 'chat'`、`priority: -10` 遮蔽官方 ChatView,并隐藏官方那条页签账本行(只清空其 View `id`,不删除条目、不提前释放子槽与 store),插件卸载时原样恢复;三次方重注册在遮蔽期间会被自动重新隐藏。
|
||||
- 回答段补回官方行契约:每个回答 `<article>` 带 `data-chat-flow-kind="assistant-step"`、按段唯一的 `data-chat-flow-key`、`data-chat-node-key` 与 `data-chat-turn`,修复 dsh-btw 旁问选中回答文字时找不到消息行、菜单不弹的问题。官方 `[data-text-interaction-surface]` 正文小工具条仍未镜像(btw 的正文小按钮不出现,旁问菜单已可用)。
|
||||
- 修正接管期间官方对话重注册导致 `conversation.chat.flow` 子槽与 `chatStore` 句柄泄漏、重注册抛 "already declared" 的问题。
|
||||
- 验证:`pnpm build`、`pnpm typecheck`、`pnpm test`(34 个文件 / 241 个用例)通过。
|
||||
|
||||
## 1.1.0 — 2026-11-27
|
||||
|
||||
- 恢复 1.0.4 删除的阅读视图源码(`src/client/**` 组件、样式、Markdown/KaTeX 渲染、官方槽位镜像、文本变换服务、逐字动效、时间轴、产物卡、MCP 交互卡片、设置节)与对应的纯逻辑测试。
|
||||
- 阅读视图不再注册「阅读」页签:改为在 `conversation.view` 里以 `id: 'chat'`、`priority: -10` 接管内置「对话」页签的正文区域。页头、输入框、审批区、外层滚动画布仍走官方。
|
||||
- 回答段补回官方行契约:`AssistantNode` 的每个回答 `<article>` 现在带 `data-chat-flow-kind="assistant-step"`、`data-chat-flow-key`(按段唯一)、`data-chat-node-key` 与 `data-chat-turn`,修复 dsh-btw 旁问选中回答文字时找不到消息行、菜单不弹的问题;`data-chat-anchor-key` 仍不发布,回退隐藏继续由 `rewind-cut.ts` 负责。官方 `[data-text-interaction-surface]` 小工具条尚未镜像(btw 的正文小按钮仍不出现)。
|
||||
- 因为列表槽的页签清单读的是原始注册账本(不是渲染胜者),新增 `chat-view-seat.ts`:注册后把官方 ChatView 条目的 View `id` 暂时清空,让页签投影只看到本插件那一项;插件卸载时恢复。官方条目本身始终留在账本里,`conversation.chat.flow` 子槽与 `chatStore` 仍由官方 disposer 释放;ui-chat 遮蔽期间重注册会被自动重新隐藏(有专项用例)。
|
||||
- 未恢复宿主 `/better-display/reveal` 与 `/better-display/metrics` 路由;「在访达/资源管理器中定位」会走官方父目录打开的回退路径。
|
||||
- 验证:`pnpm build`、`pnpm typecheck`、`pnpm test`(33 个文件 / 237 个用例)通过。
|
||||
|
||||
## 1.0.4 — 2026-11-22
|
||||
|
||||
- 彻底移除旧的阅读视图及其全部残留:删除阅读页组件/样式/文本变换/官方槽位/入场策略等 `src/client/**` 源码,删除 reader/reveal/metrics 宿主路由与 `flags.json` 开关,删除 `DESIGN.md`、阅读相关 `docs/` 与随包许可证;设置页只保留审批快捷键录制。
|
||||
- `src/host.ts` 只保留「新建空白会话默认自动审查」,不再注册任何 HTTP 路由。
|
||||
|
||||
## 1.0.3 — 2026-11-14
|
||||
|
||||
- 开发侧:`npm run typecheck` 转绿(无运行时行为变化)。设置节的 locale 命名空间键统一为 `better-chat`;`DEFAULT_BINDINGS.always` 可空导致展开后键可选,改用非空的 `DEFAULT_ALWAYS`;新增 `host-modules.d.ts` 与 `host-augment.d.ts`,为宿主自带的客户端包(`dsh-api-remotes` / `dsh-api-session-controller` / `dsh-client-connection` 等)补声明,并声明 `remote` / `sessions` 服务与 `connection/reset` 事件。
|
||||
|
||||
## 1.0.2 — 2026-11-14
|
||||
|
||||
|
||||
- 修复 host 插件在干净 profile 里激活失败(`1 entry did not activate`):`apply()` 先读 `ctx.permissionPresets` 再判断,而 Cordis 对未在 `inject` 声明的服务读取会直接抛 `cannot get property "permissionPresets" without inject`,于是 `else` 里的 `ctx.inject` 兜底永远走不到。现在统一用 `ctx.inject(['permissionPresets', 'agents'], …)` 挂载自动审查监听,服务缺失时插件照常激活,服务就绪后再挂载;reveal / metrics 路由不受影响。
|
||||
- 新增 `tests/host-activation.test.ts`:用真实 Cordis `Context` 在只提供 `webServer` 的干净环境加载 host 入口,断言 fiber 为 `ACTIVE`,并验证服务就绪后空白会话仍会被切到 `auto`。
|
||||
|
||||
## 1.0.1 — 2026-11-13
|
||||
|
||||
- 恢复并完善「默认打开模式为自动审查(`auto`)」功能:
|
||||
- 宿主侧(`src/host.ts`)监听 `agent/created` 与 `permission-presets/catalog-changed`,当 `@deepseek-ai/dsh-experimental-auto-review` 已启用时,对新建空白顶层会话直接设为 `auto`;
|
||||
- 客户端(`src/client/chat/permission-policy.ts`)适配 DSH 0.2.2 `ClientSessions`(`list.getSnapshot()` / `scopes`)与 `{ currentValue }` 权限投影结构,首次见到空白顶层会话时自动切到 `/permission auto`;
|
||||
- 已处理会话 id 持久化到 `localStorage`(`dsh.better-chat.permission-handled.v1`),且跳过非空白历史会话(`blank === false`)、子代理会话与已手动执行过 `/permission` 的会话,刷新或重启不会覆盖用户手动切换的权限。
|
||||
|
||||
## 1.0.0 — 2026-11-12
|
||||
|
||||
首个可用版本。单个插件同时提供阅读视图(合并自 dsh-better-display 0.3.12)与聊天增强:
|
||||
首个可用版本。单个插件同时提供阅读视图与聊天增强:
|
||||
|
||||
- 审批卡键帽提示,以及 Enter / Ctrl+Enter(Mac 为 Cmd+Enter)/ Esc 路由;可在 Better Chat 设置里自定义绑定、清除「始终允许」或恢复默认;
|
||||
- 权限 UI 移除「完全权限」选项,不改写已有会话的权限;
|
||||
|
|
@ -13,16 +59,16 @@
|
|||
|
||||
## 0.4.4 — 2026-11-12
|
||||
|
||||
- 删除设置里的 `generative-mcpapps` 技能检测/安装块(对用户无用):同时移除客户端探测、宿主 `/better-display/skill-status` 路由、技能扫描实现、随包 `skills/generative-mcpapps` 技能包,以及对应的文案与测试。阅读页仍会渲染模型自己写出的 `mcp-app` 代码块,只是不再检测/引导安装该技能。
|
||||
- 删除设置里的 `generative-mcpapps` 技能检测/安装块(对用户无用):同时移除客户端探测、宿主技能状态路由、技能扫描实现、随包 `skills/generative-mcpapps` 技能包,以及对应的文案与测试。阅读页仍会渲染模型自己写出的 `mcp-app` 代码块,只是不再检测/引导安装该技能。
|
||||
|
||||
## 0.4.3 — 2026-11-12
|
||||
|
||||
- 修复设置项标题在「Better Display / Better Chat」之间来回变的问题:合并后的插件此前复用了独立 dsh-better-display 的设置节 id(`better-display`)与 locale 命名空间(`better-display`),两个插件同时安装时后注册的会覆盖前者,标题随加载顺序翻转。现在改用独立的 `better-chat` 节 id 与 locale 命名空间,互不覆盖。
|
||||
- 注意:README 已写明更新时必须同时从 profile 移除独立的 dsh-better-display,否则会同时出现两个设置节(以及两套阅读页注册)。
|
||||
- 修复设置项标题在旧名称 / Better Chat 之间来回变的问题:合并后的插件此前复用了旧独立插件的设置节 id 与 locale 命名空间,两个插件同时安装时后注册的会覆盖前者,标题随加载顺序翻转。现在改用独立的 `better-chat` 节 id 与 locale 命名空间,互不覆盖。
|
||||
- 注意:README 已写明更新时必须同时从 profile 移除独立的旧阅读视图插件,否则会同时出现两个设置节(以及两套阅读页注册)。
|
||||
|
||||
## 0.4.2 — 2026-11-12
|
||||
|
||||
- 设置页的 **Better Display** 选项栏改名为 **Better Chat**(中英文案同步)。
|
||||
- 设置页的旧选项栏改名为 **Better Chat**(中英文案同步)。
|
||||
- 审批快捷键可自定义并写入插件配置(持久化键 `dsh.better-chat.v1`):允许(单次)/始终允许/拒绝三行,点键帽后按新组合键即可录制;基础键固定为 Enter(允许类)与 Esc(拒绝),修饰键自由,支持清除「始终允许」和恢复默认。冲突、缺少修饰键、用错基础键都会在设置页提示并拒绝保存。
|
||||
- 审批卡上的键帽提示与按键判定都读取实时配置:保存后卡片提示立即重建,无需重启 DSH。
|
||||
|
||||
|
|
@ -34,7 +80,7 @@
|
|||
|
||||
## 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`);目标
|
||||
|
|
|
|||
112
DESIGN.md
112
DESIGN.md
|
|
@ -1,112 +0,0 @@
|
|||
# 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.
|
||||
103
README.en.md
103
README.en.md
|
|
@ -1,8 +1,8 @@
|
|||
# dsh-better-chat
|
||||
|
||||
Chat enhancements for DeepSeek Harness. v1.0.0 merges the **dsh-better-display
|
||||
reading view** in: one plugin and one Web client artifact provide the reader tab
|
||||
plus the approval / permission / plugin-store improvements.
|
||||
Chat enhancements for DeepSeek Harness: Enter-to-approve / Esc-to-reject on approval cards, permission UI, plugin-store update button, and default auto-review for fresh blank sessions.
|
||||
|
||||
> The old reading view was fully removed in 1.0.4. This plugin no longer ships a Reading tab, nor that view's source, design docs or license.
|
||||
|
||||
## Install
|
||||
|
||||
|
|
@ -16,96 +16,11 @@ From this repository (pin a commit):
|
|||
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.
|
||||
The compiled `lib/` is committed, so installation needs no build step. Fully restart DSH afterwards.
|
||||
|
||||
> If the standalone **dsh-better-display** is installed, remove it while updating
|
||||
> this plugin: the reading view is now part of this package, and installing both
|
||||
> registers two reader views and two settings sections (their titles overwrite
|
||||
> each other).
|
||||
## Features
|
||||
|
||||
## 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 Chat** settings: preview deliverables in the right sidebar, frosted
|
||||
glass (off by default), auto-fold the process (on by default), and approval-card
|
||||
shortcuts.
|
||||
- Upstream design notes, extension points and runbooks live in [`docs/`](docs/).
|
||||
|
||||
## Feature 2: Enter approves, Esc rejects on approval cards (v0.1.0; hints in v0.4.1, customization in v0.4.2)
|
||||
|
||||
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, the configured key
|
||||
clicks "Allow once" (never "Always allow" by default) and Esc clicks "Reject".
|
||||
3. **Key hint**: the action row shows keycaps for the current bindings (default
|
||||
`Enter Allow once · Ctrl+Enter Always allow · Esc Reject`), using the card's
|
||||
real button labels. It disappears once answered, is not focusable and is not
|
||||
clickable. macOS shows Cmd instead of Ctrl.
|
||||
4. **Ctrl+Enter / Cmd+Enter = Always allow**, only when the card has the third
|
||||
button. The official card ignores modified keys, so this chord is handled here
|
||||
even while focus is inside the card. It never fires while typing in an input.
|
||||
5. **Customizable shortcuts**: Settings → Better Chat → Approval card shortcuts.
|
||||
Click a keycap and press the new combination. Allow-type actions stay on Enter,
|
||||
reject stays on Esc; modifiers are free. You can clear "Always allow" or
|
||||
restore defaults. Bindings persist under `dsh.better-chat.v1` and the card hint
|
||||
updates immediately — no restart needed.
|
||||
|
||||
It never intercepts while typing, for a plain Enter/Esc when focus is inside the
|
||||
card, for modifier sets that do not match the current binding, on auto-repeat,
|
||||
during IME composition, when Enter lands on another button or link, or when the
|
||||
card is 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
|
||||
# Windows: pnpm's default isolated linker overflows on rolldown's native
|
||||
# binding symlink; use the hoisted layout.
|
||||
pnpm install --config.node-linker=hoisted
|
||||
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/).
|
||||
- **Approval shortcuts**: Enter approves, Esc rejects on approval cards; customize bindings, clear "always allow" or restore defaults in Settings → Better Chat.
|
||||
- **Permission UI**: removes the "Full access" option; never rewrites existing session permissions.
|
||||
- **Default auto-review**: fresh blank top-level sessions switch to `auto` (requires `@deepseek-ai/dsh-experimental-auto-review`); reloads/restarts never override a user's manual switch.
|
||||
- **Plugin-store update**: adds an "Update" button to the plugin store.
|
||||
|
|
|
|||
94
README.md
94
README.md
|
|
@ -1,7 +1,8 @@
|
|||
# dsh-better-chat
|
||||
|
||||
DSH 聊天增强插件。v1.0.0 把 **dsh-better-display 的阅读视图**合并进来:一个插件、
|
||||
一个 Web 客户端产物,同时提供「阅读页」与「审批 / 权限 / 商店」增强。
|
||||
DSH 聊天增强插件:审批卡回车批准 / Esc 拒绝、权限 UI、插件商店更新、新建空白会话默认切到「自动审查」,对话页正文使用阅读视图的渲染(逐字动效、过程折叠、时间轴、产物卡、MCP 交互卡片等)。
|
||||
|
||||
> 1.1.0 起不再有单独的「阅读」页签:阅读视图直接接管内置「对话」页签的正文区域。页头、输入框、审批、滚动画布仍由官方提供。
|
||||
|
||||
## 安装
|
||||
|
||||
|
|
@ -17,87 +18,10 @@ dsh plugin --profile desktop add git+https://git.qyhhh.top/DeepsSeekHarness/dsh-
|
|||
|
||||
编译好的 `lib/` 已提交,安装时不需要构建。装完彻底重启 DSH。
|
||||
|
||||
> 如果之前装过独立的 **dsh-better-display**,请在更新本插件的同时把它从 profile
|
||||
> 移除:阅读视图已经并入本插件,两个都装会同时注册两套阅读页与设置节(设置项标题
|
||||
> 也会互相覆盖)。
|
||||
## 功能
|
||||
|
||||
## 功能一:阅读视图(合并自 dsh-better-display 0.3.12)
|
||||
|
||||
给对话加一个 **阅读** 页签:执行时能看到步骤、思考与进度;整轮成功结束后把过程
|
||||
收起来,留下最终回答。原版「对话 / 轨迹」、输入框、模型选择、工具和审批都还在。
|
||||
|
||||
- 阅读列保留宿主 ChatView 的 `data-chat-flow` 钩子,依赖该标记显示输入框的第三方
|
||||
皮肤不会把阅读页当成仅检视视图。
|
||||
- 最终回答里的 ````mcp-app` 代码块会挂成交互卡片(`<iframe sandbox="allow-scripts allow-forms">`)。
|
||||
- 设置里的 **Better Chat**:产物右侧预览、半透明毛玻璃(默认关)、过程自动折叠
|
||||
(默认开)、审批卡快捷键。
|
||||
- 上游的设计说明、扩展点文档与开发 runbook 一并保留在 [`docs/`](docs/)。
|
||||
|
||||
## 功能二:审批卡片的回车批准 / Esc 拒绝(v0.1.0,v0.4.1 加提示,v0.4.2 快捷键可配置)
|
||||
|
||||
DSH 官方审批卡本身支持 Enter 批准、Esc 拒绝,但前提是焦点先落在卡内。本插件补上:
|
||||
|
||||
1. **自动送入焦点**:审批卡出现时,若没有正在别处输入,把焦点送进卡片详情区。
|
||||
2. **全局兜底路由**:焦点不在卡内时,在 document 捕获阶段接住配置的快捷键 —— 默认
|
||||
回车点「允许(单次)」(不会误触「始终允许」),Esc 点「拒绝」。
|
||||
3. **键盘提示**:操作行左侧显示当前绑定的键帽提示(默认
|
||||
`Enter 允许(单次) · Ctrl+Enter 始终允许 · Esc 拒绝`),文案取卡片按钮的实际文字,
|
||||
卡片作答后自动消失;只做说明,不占焦点、不可点击。Mac 上 Ctrl 显示为 Cmd。
|
||||
4. **Ctrl+Enter / Cmd+Enter = 始终允许**:仅当卡片有第三个按钮时生效。官方卡片对带
|
||||
修饰键的按键不作答,所以这条即使在卡片内也由本插件处理;正在输入控件里打字时
|
||||
不拦截。
|
||||
5. **快捷键可自定义**:设置 → Better Chat → 审批卡快捷键,点键帽后按下新组合键。
|
||||
允许类动作固定在 Enter 上、拒绝固定在 Esc 上,修饰键自由;可清除「始终允许」或
|
||||
恢复默认。配置持久化在 `dsh.better-chat.v1`,保存后卡片提示立即更新,无需重启。
|
||||
|
||||
防误触:正在输入控件里打字、裸 Enter/Esc 且焦点已在卡内、与当前绑定不符的修饰键、
|
||||
长按连发、输入法组词、回车落在别的按钮或链接上、卡片已作答或按钮禁用时,都不拦截。
|
||||
|
||||
## 功能三:权限 UI(v0.2.0,v0.3.1 收紧)
|
||||
|
||||
- 去掉「完全权限 / Full access」选项:`/permission` 弹出菜单、composer 权限菜单与
|
||||
通用设置的默认权限下拉里都会被摘除。只动界面,手动输入命令仍可达。
|
||||
- 不覆盖已有会话权限:页面加载、刷新、插件重载都不会遍历会话改权限;默认权限交给
|
||||
宿主的新建会话流程。
|
||||
|
||||
## 功能四:插件商店「更新」按钮(v0.3.0)
|
||||
|
||||
从自定义索引装的插件在发现页只有「有新版本」标签。本功能补一个「更新到 x.y.z」
|
||||
按钮:数据与动作都走宿主自己的 `remote.pluginMarket` / `remote.pluginManager`,
|
||||
按索引给出的精确 spec 覆盖安装,不模拟点击。远程服务由子插件单独 inject,未启用
|
||||
实验性插件索引时静默关闭。
|
||||
|
||||
## 开发
|
||||
|
||||
```sh
|
||||
# Windows:pnpm 默认 isolated linker 建 rolldown 原生符号链接会栈溢出,用 hoisted
|
||||
pnpm install --config.node-linker=hoisted
|
||||
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 / 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/)。
|
||||
- **对话页阅读式渲染**:回答逐字动效、思考卡片、过程自动折叠与一行汇总、时间轴与每轮指标、产物快捷操作(打开/定位/复制)、MCP 交互卡片、CJK 加粗与公式排版,以及「设置 → Better Chat」里的打开方式、毛玻璃、自动折叠开关。
|
||||
- **审批快捷键**:审批卡上回车批准、Esc 拒绝;可在「设置 → Better Chat」里自定义绑定、清除「始终允许」或恢复默认。
|
||||
- **权限 UI**:权限选择里移除「完全权限」;不改写已有会话的权限。
|
||||
- **默认自动审查**:新建空白顶层会话自动切到 `auto`(需启用 `@deepseek-ai/dsh-experimental-auto-review`);刷新/重启不会覆盖用户手动切换。
|
||||
- **插件商店更新**:为插件商店提供「更新」按钮。
|
||||
|
|
|
|||
|
|
@ -1,17 +1,6 @@
|
|||
# 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.
|
||||
The MIT license in this repository covers the plugin code.
|
||||
|
||||
## dshx client build adapter
|
||||
|
||||
|
|
@ -19,68 +8,4 @@ range widened to the 0.2.2 line, and the build toolchain below.
|
|||
`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.
|
||||
`tools/harness/packages/client/web/src/platform.ts` (dsh-v0.2.2-rc.2).
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ Revisions:
|
|||
|
||||
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.
|
||||
Copy answer and copy message read the original blocks (`originalAnswerText` for the answer). Since 1.1.0 the reader occupies the built-in 对话 View, so a registered transformer also changes what the user reads in the transcript; remove the plugin to get the stock ChatView back. The seam never runs inside tool results or user bubbles.
|
||||
|
||||
Fold still uses the original block list and the public turn boundary.
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,18 @@
|
|||
|
||||
`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`。阅读页自己呈现模型重试和进行中的过程行,所以这两处官方视图变化不改阅读布局。后续仍需维护的自有展示逻辑和升级边界见下文。
|
||||
|
||||
## 1.1.0 的挂载位置
|
||||
|
||||
阅读视图不再注册单独的 View 页签。它复用内置 View id `chat`,以 `priority: -10` 在 `conversation.view`(list 槽)里遮蔽官方 ChatView,因此「对话」页签的正文区域由 Reader 绘制,页头、输入框、审批区和 `[data-conversation-scroll]` 滚动画布仍是官方实现。
|
||||
|
||||
`conversation.view` 的页签清单读的是原始注册账本,不是渲染胜者;只做遮蔽会出现两个「对话」页签。`src/client/chat-view-seat.ts` 不删除官方行(删行会让官方 disposer 提前返回,`conversation.chat.flow` 子槽和 `chatStore` 句柄就漏了),只把官方条目的 View `id` 暂时清空——页签投影唯一读取的字段;插件卸载时还原。官方行、子槽、store 与 disposer 全程归官方所有。若 ui-chat 在遮蔽期间重注册 ChatView,订阅会把新行重新隐藏。若未来宿主不再允许修改 `entry.options`,隐藏会退化为 no-op:正文仍由 Reader 渲染,最多多出一个重复页签。
|
||||
|
||||
下文的“阅读页”均指接管后的「对话」正文。`entry.tsx`(打开会话时强制切到阅读页)已停用,源码仅作参考。
|
||||
|
||||
## 回答行的官方 DOM 契约
|
||||
|
||||
官方 ChatView 给每条 assistant-step 行发 `data-chat-flow-kind="assistant-step"`、`data-chat-flow-key`、`data-chat-node-key`、`data-chat-turn`。阅读页原来只给用户气泡发了 `data-chat-flow-kind`,回答段没有,依赖这套标记的第三方插件(如 dsh-btw 的选中文字旁问)会在阅读页里找不到消息行。`AssistantNode` 现在给每个回答段 `<article>` 补发这四个属性:`data-chat-flow-key` 按段加 `#<partStart>` 保持唯一;`data-chat-anchor-key` 仍不发布,避免与阅读页自己的 `rewind-cut.ts` 双重隐藏。官方 `[data-text-interaction-surface]` 文本工具条仍未镜像。
|
||||
|
||||
## 一个具体例子
|
||||
|
||||
一条回答的持久化 `messageId` 进入 `OfficialActions`,随后进入 Reader 自己的回答操作插槽。里面的反馈组件、状态注入和弹窗控制器来自当前已加载的官方反馈插件。点击按钮后,由官方控制器打开原来的官方弹窗;Reader 不实现反馈请求、类别或状态管理。
|
||||
|
|
|
|||
|
|
@ -1,82 +0,0 @@
|
|||
openapi: 3.0.3
|
||||
info:
|
||||
title: dsh-better-chat
|
||||
version: 1.0.0
|
||||
description: >
|
||||
Exact routes registered by apply() in src/host.ts.
|
||||
POST /better-display/reveal is createRevealHandler in src/reveal.ts.
|
||||
GET /better-display/metrics returns metricsPayload().
|
||||
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.
|
||||
components:
|
||||
schemas:
|
||||
ErrorBody:
|
||||
type: object
|
||||
required: [ok, error]
|
||||
additionalProperties: false
|
||||
properties:
|
||||
ok:
|
||||
type: boolean
|
||||
enum: [false]
|
||||
error:
|
||||
type: string
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
# 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.
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
{
|
||||
"readerEnabled": true
|
||||
}
|
||||
2008
lib/client.js
2008
lib/client.js
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
344
lib/host.js
344
lib/host.js
|
|
@ -1,38 +1,5 @@
|
|||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, posix, resolve, win32 } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { spawn } from "node:child_process";
|
||||
// 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",
|
||||
|
|
@ -134,247 +101,80 @@ function createLogger(options = {}) {
|
|||
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_METRICS = "/better-display/metrics";
|
||||
const ROUTE_HITS = [ROUTE_REVEAL, 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/host.ts
|
||||
const name = "dsh-better-chat";
|
||||
const inject = ["webServer"];
|
||||
const inject = [];
|
||||
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 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;
|
||||
const AUTO_REVIEW_PRESET = "auto";
|
||||
/**
|
||||
* 判断宿主会话是否为「尚未开始对话、且用户未手动改过权限」的新建空白顶层会话。
|
||||
* - 排除子代理会话(`origin === 'subagent'`)与 fork/seed 会话;
|
||||
* - 排除已开始轮次或已有用户消息的会话;
|
||||
* - 排除用户已显式执行过 `/permission` 命令的会话。
|
||||
*/
|
||||
function isFreshAutoEligibleSession(session) {
|
||||
if (!session || typeof session !== "object") return false;
|
||||
const header = session.header;
|
||||
if (header?.origin === "subagent") return false;
|
||||
if (header?.isSeeded === true) return false;
|
||||
if (typeof session.inheritedEventCount === "number" && session.inheritedEventCount > 0) return false;
|
||||
if (typeof session.snapshotEvents === "function") try {
|
||||
const events = session.snapshotEvents();
|
||||
for (const event of events) if (event?.type === "turn/start" || event?.type === "user/message" || event?.type === "session/end-seed" || event?.type === "command/run" && event?.data?.name === "permission") return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
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 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();
|
||||
disposeMetrics();
|
||||
};
|
||||
}, "dsh-better-chat: reveal and metrics routes");
|
||||
return true;
|
||||
}
|
||||
export { apply, inject, name };
|
||||
function applyHostAutoReview(permissionPresets, session, handled) {
|
||||
if (!permissionPresets || !session) return false;
|
||||
const id = typeof session.id === "string" ? session.id : typeof session.header?.id === "string" ? session.header.id : void 0;
|
||||
if (id && handled.has(id)) return false;
|
||||
if (!isFreshAutoEligibleSession(session)) {
|
||||
if (id) handled.add(id);
|
||||
return false;
|
||||
}
|
||||
const names = permissionPresets.names;
|
||||
if (!Array.isArray(names) || !names.includes(AUTO_REVIEW_PRESET)) return false;
|
||||
if (id) handled.add(id);
|
||||
try {
|
||||
if (permissionPresets.current?.(session) === AUTO_REVIEW_PRESET) return false;
|
||||
permissionPresets.set?.(session, AUTO_REVIEW_PRESET);
|
||||
return true;
|
||||
} catch (err) {
|
||||
log.info("auto review preset switch skipped", {
|
||||
sessionId: id ?? "",
|
||||
error: err instanceof Error ? err.message : String(err)
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function mountAutoReviewListeners(targetCtx) {
|
||||
const handled = /* @__PURE__ */ new Set();
|
||||
const scanAll = () => {
|
||||
const presets = targetCtx.permissionPresets;
|
||||
const list = targetCtx.agents?.list?.() ?? [];
|
||||
for (const agent of list) if (agent?.session) applyHostAutoReview(presets, agent.session, handled);
|
||||
};
|
||||
targetCtx.effect?.(() => {
|
||||
const offCreated = targetCtx.on?.("agent/created", ({ agent }) => {
|
||||
if (agent?.session) applyHostAutoReview(targetCtx.permissionPresets, agent.session, handled);
|
||||
});
|
||||
const offCatalog = targetCtx.on?.("permission-presets/catalog-changed", () => {
|
||||
scanAll();
|
||||
});
|
||||
scanAll();
|
||||
return () => {
|
||||
if (typeof offCreated === "function") offCreated();
|
||||
if (typeof offCatalog === "function") offCatalog();
|
||||
};
|
||||
}, "dsh-better-chat: default auto-review preset for new sessions");
|
||||
}
|
||||
function apply(ctx) {
|
||||
log.info("[dsh-better-chat] loaded");
|
||||
const anyCtx = ctx;
|
||||
if (typeof anyCtx.inject === "function") anyCtx.inject(["permissionPresets", "agents"], (childCtx) => {
|
||||
mountAutoReviewListeners(childCtx);
|
||||
});
|
||||
}
|
||||
export { apply, applyHostAutoReview, inject, isFreshAutoEligibleSession, name };
|
||||
|
|
|
|||
|
|
@ -1,24 +0,0 @@
|
|||
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.
|
||||
10
package.json
10
package.json
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "dsh-better-chat",
|
||||
"version": "1.0.0",
|
||||
"description": "DSH 聊天增强插件:审批回车批准 / Esc 拒绝、权限 UI、插件商店更新,以及 reading view(合并自 dsh-better-display)",
|
||||
"version": "1.3.0",
|
||||
"description": "DSH 聊天增强插件:审批回车批准 / Esc 拒绝、权限 UI、插件商店更新、默认自动审查。",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"main": "lib/host.js",
|
||||
|
|
@ -82,13 +82,10 @@
|
|||
"tests",
|
||||
"docs",
|
||||
"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",
|
||||
|
|
@ -100,7 +97,6 @@
|
|||
"dsh-plugin",
|
||||
"conversation",
|
||||
"approval",
|
||||
"permission",
|
||||
"reading"
|
||||
"permission"
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
import { Fragment, memo } from 'react';
|
||||
import { 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 { Blocks } 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 { OfficialAssistantBody } from './OfficialContent.js';
|
||||
import { ProcessFragment } from './motion.js';
|
||||
import { assistantSegments, hasVisibleBody, isEarlierNarration } from './projection.js';
|
||||
import type { TurnBoundary } from './projection.js';
|
||||
import type { BlockRenderProps, ReaderProps } from './types.js';
|
||||
import { answerRowAttrs } from './chat-seat.js';
|
||||
import css from './Reader.module.css';
|
||||
|
||||
function isNode<K extends ChatNodeKind>(node: ChatConversationViewNode, kind: K): node is ChatNode<K> {
|
||||
|
|
@ -19,9 +19,8 @@ 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 & {
|
||||
export const AssistantNode = memo(function AssistantNode({ useChat, nodeKey, boundary, processOpen = false, pinned = false, folded = false, partStart, 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;
|
||||
|
|
@ -30,43 +29,23 @@ export const AssistantNode = memo(function AssistantNode({ useChat, nodeKey, bou
|
|||
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}>
|
||||
<ReasoningCard step={data.step}>
|
||||
<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>;
|
||||
return <article className={css.answer} key={part.start} data-reader-body data-reader-anchor data-reader-key={nodeKey} data-reader-source-start={part.start}
|
||||
{...answerRowAttrs(nodeKey, part.start, data.turn)}
|
||||
data-answer-status={data.status} data-answer-phase={isFinalAnswer ? 'body' : 'process'}>
|
||||
<OfficialAssistantBody {...render} node={node} blocks={part.blocks} {...bodyProps} />
|
||||
</article>;
|
||||
})}</>;
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,20 +1,18 @@
|
|||
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 type { AssistantBlock, MessageImagesOwnerProps, MessageImageLoader, 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 { MotionMarkdown } 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
|
||||
|
|
@ -30,9 +28,9 @@ export class BlockBoundary extends Component<{ children: ReactNode }, { failed:
|
|||
}
|
||||
}
|
||||
|
||||
export const ImageBlock = memo(function ImageBlock({ attachment, loadImage }: {
|
||||
attachment: ImageAttachmentRef; loadImage: BlockRenderProps['loadImage'];
|
||||
}) {
|
||||
type ImageBlockProps = { attachment: ImageAttachmentRef; label?: string; loadImage: MessageImageLoader };
|
||||
|
||||
export const ImageBlock = memo(function ImageBlock({ attachment, label = attachment.name, loadImage }: ImageBlockProps) {
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
const [error, setError] = useState(false);
|
||||
|
|
@ -41,39 +39,45 @@ export const ImageBlock = memo(function ImageBlock({ attachment, loadImage }: {
|
|||
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 => {
|
||||
// Await the canonical URL. The host may revoke a cached submission preview.
|
||||
void Promise.resolve().then(() => 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);
|
||||
setUrl(result);
|
||||
}).catch(() => { clearTimeout(timeout); if (active) setError(true); });
|
||||
return () => { active = false; clearTimeout(timeout); if (owned) URL.revokeObjectURL(owned); };
|
||||
}, [attachment.attachmentId, attempt, loadImage]);
|
||||
return () => { active = false; clearTimeout(timeout); };
|
||||
}, [attachment, 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} />
|
||||
{!error && url && <button ref={opener} type="button" className={css.imageOpen} aria-label={`放大图片${label ? `:${label}` : ''}`} onClick={() => dialog.current?.showModal()}>
|
||||
<img src={url} alt={label ?? '会话图片'} 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>}
|
||||
{label && <figcaption>{label}</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 ?? '会话图片'} />}
|
||||
{url && <img src={url} alt={label ?? '会话图片'} />}
|
||||
</dialog>
|
||||
</figure>;
|
||||
});
|
||||
|
||||
/** The host's user content factory omits its images when no gallery occupies the slot. */
|
||||
export function UserImageFallback({ images, loadImage }: MessageImagesOwnerProps) {
|
||||
return <div className={css.userImages}>
|
||||
{images.map((image, index) => 'attachment' in image
|
||||
? <ImageBlock key={index} attachment={image.attachment} label={image.label} loadImage={loadImage} />
|
||||
: <img key={index} className={css.pendingImage} src={image.preview.url} alt={image.preview.name ?? '发送的图片'} />)}
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function contentBlocks(content: UserMessageNode['content']): AssistantBlock[] {
|
||||
return content.map(block => {
|
||||
if (block.type === 'text') return { kind: 'text', text: block.text };
|
||||
|
|
@ -127,7 +131,7 @@ function ReasoningStream({ blockKey, text, streaming, holdFormatting, startedAt,
|
|||
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} />
|
||||
<MotionMarkdown text={presentation.text} streaming={streaming} enabled={liveText && presentation.reveal} revision={presentation.revision} variant="compact" />
|
||||
</div>;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { createContext, Fragment, 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 { arrangeTurnWaves, collapseRows, containsNewUser, flowRows, FOLD_TIMING, retiringKeys } from './fold-choreography.js';
|
||||
import type { FlowBucket, FlowRow, FoldPhase } from './fold-choreography.js';
|
||||
import { Disclosure } from './motion.js';
|
||||
import { FoldSummaryText } from './LiveFold.js';
|
||||
import { DiffStat } from './DiffPanel.js';
|
||||
|
|
@ -12,6 +12,7 @@ import { StreamMotionContext } from './streaming.js';
|
|||
import css from './Reader.module.css';
|
||||
import { useSummaryLane } from './StickyLane.js';
|
||||
|
||||
const FLOW_CELLS = ':scope > [data-flow-key], :scope > [data-reader-answer-bubble] > [data-flow-key], :scope > [data-reader-process-frame] > [data-reader-process-scroll] > [data-flow-key]';
|
||||
const FlowSnapshot = createContext<ChatSnapshot | null>(null);
|
||||
/** Public projection only. Descendants cannot leak live data through a frozen frame. */
|
||||
export const useFlowChat: ReaderProps['useChat'] = selector => {
|
||||
|
|
@ -33,16 +34,17 @@ function Summary({ item, open, onChange, motion }: {
|
|||
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} />} />
|
||||
<Disclosure open={open} onChange={onChange} buttonRef={button} ariaLabel={`执行记录,${item.summary}`}
|
||||
label={open ? <FoldSummaryText summary={item.summary} motion={motion} />
|
||||
: <span title={item.summary}>查看 {item.steps.length} 条执行记录</span>} />
|
||||
<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;
|
||||
function FlowCell({ hidden, instant, motion, rowKey, children, summary = false, process }: {
|
||||
hidden: boolean; instant: boolean; motion: boolean; rowKey: string; children: ReactNode; summary?: boolean; process?: boolean;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useSummaryLane(ref, summary);
|
||||
|
|
@ -94,25 +96,81 @@ function FlowCell({ hidden, instant, motion, rowKey, children, summary = false }
|
|||
// 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}
|
||||
return <div ref={ref} className={css.flowCell} data-flow-key={rowKey} data-flow-summary={summary || undefined} data-flow-process={process || 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 }: {
|
||||
function ProcessScroll({ children, live, hidden }: { children: ReactNode; live: boolean; hidden: boolean }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const following = useRef(true);
|
||||
const lastWrittenTop = useRef<number | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const port = ref.current;
|
||||
if (!port || !live) return;
|
||||
const follow = () => {
|
||||
const selection = document.getSelection();
|
||||
if (!following.current || (selection && !selection.isCollapsed && selection.rangeCount
|
||||
&& selection.getRangeAt(0).intersectsNode(port))) return;
|
||||
const end = Math.max(0, port.scrollHeight - port.clientHeight);
|
||||
if (Math.abs(port.scrollTop - end) <= 1) return;
|
||||
port.scrollTop = end;
|
||||
lastWrittenTop.current = port.scrollTop;
|
||||
};
|
||||
const resize = new ResizeObserver(follow);
|
||||
const observeRows = () => {
|
||||
resize.disconnect();
|
||||
resize.observe(port);
|
||||
for (const child of port.children) resize.observe(child);
|
||||
follow();
|
||||
};
|
||||
const rows = new MutationObserver(observeRows);
|
||||
rows.observe(port, { childList: true });
|
||||
observeRows();
|
||||
return () => {
|
||||
rows.disconnect();
|
||||
resize.disconnect();
|
||||
};
|
||||
}, [live]);
|
||||
return <div ref={ref} className={css.processScroll} data-reader-process-scroll hidden={hidden} tabIndex={0} role="region" aria-label="执行过程"
|
||||
onScroll={event => {
|
||||
const port = event.currentTarget;
|
||||
if (event.target !== port) return;
|
||||
const written = lastWrittenTop.current;
|
||||
lastWrittenTop.current = null;
|
||||
if (written !== null && Math.abs(written - port.scrollTop) <= 1) return;
|
||||
following.current = port.scrollHeight - port.clientHeight - port.scrollTop <= 2;
|
||||
}}
|
||||
onWheel={event => {
|
||||
const port = event.currentTarget;
|
||||
if (event.deltaY < 0 && port.scrollTop > 0) following.current = false;
|
||||
}}>
|
||||
{children}
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpenChange, processOpen, running, renderStep, id, status }: {
|
||||
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;
|
||||
processOpen: boolean; running: boolean; renderStep: (step: LiveStep, folded: boolean) => ReactNode; id: string; status?: ReactNode;
|
||||
}) {
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const [collapsedFrames, setCollapsedFrames] = useState<ReadonlySet<string>>(() => new Set());
|
||||
useEffect(() => {
|
||||
if (!processOpen) setCollapsedFrames(current => current.size ? new Set() : current);
|
||||
}, [processOpen]);
|
||||
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)) {
|
||||
const shownKeys = state.shown !== frame ? new Set(state.shown.items.map(item => item.key)) : undefined;
|
||||
const outputArrived = shownKeys !== undefined && frame.items.some(item =>
|
||||
item.kind === 'open' && item.step.kind === 'body' && !shownKeys.has(item.key));
|
||||
// Publish new prose with its folded process rather than buffering the first words.
|
||||
// Render-time adjustment prevents even one paint of the stale layout.
|
||||
if ((bypass || outputArrived || 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);
|
||||
|
|
@ -131,7 +189,7 @@ export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpen
|
|||
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]')) {
|
||||
for (const cell of el.querySelectorAll<HTMLElement>(FLOW_CELLS)) {
|
||||
const key = cell.dataset.flowKey!;
|
||||
const isHeader = cell.dataset.flowSummary && !state.beforeKeys.has(key);
|
||||
if (!retiring.has(key) && !isHeader) continue;
|
||||
|
|
@ -206,7 +264,8 @@ export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpen
|
|||
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!))
|
||||
const animations = Array.from(el.querySelectorAll<HTMLElement>(FLOW_CELLS))
|
||||
.filter(child => !child.hidden && !state.beforeKeys.has(child.dataset.flowKey!))
|
||||
.map(child => child.animate([
|
||||
{ height: '0px', opacity: 0 },
|
||||
{ height: `${child.getBoundingClientRect().height}px`, opacity: 1 },
|
||||
|
|
@ -220,18 +279,84 @@ export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpen
|
|||
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);
|
||||
type FlowCellEntry = { row: FlowRow; key: string; hidden: boolean; process: boolean; bucket: FlowBucket };
|
||||
const cells: FlowCellEntry[] = rows.map(row => {
|
||||
if (row.kind === 'summary') return { row, key: row.key, hidden: false, process: true, bucket: 'process' };
|
||||
if (row.step.kind === 'user') return { row, key: row.key, hidden: false, process: false, bucket: 'user' };
|
||||
if (row.step.kind === 'body') {
|
||||
const hidden = blocked && state.phase !== 'collapse' && !state.beforeKeys.has(row.key);
|
||||
return { row, key: row.key, hidden, process: false, bucket: 'body' };
|
||||
}
|
||||
const node = row.step.kind === 'other' ? source.snapshot.nodes.get(row.step.nodeKey) : undefined;
|
||||
const trigger = !!status && node?.kind === 'turn-trigger';
|
||||
const isProcess = row.step.kind === 'reasoning' || row.step.kind === 'tool' || trigger
|
||||
|| (row.step.kind === 'other' && row.step.process === true && node?.kind !== 'turn-trigger');
|
||||
const hidden = (isProcess && !processOpen)
|
||||
|| (trigger && !processOpen)
|
||||
|| (!!row.foldKey && (!processOpen || !open[row.foldKey]))
|
||||
|| (blocked && state.phase !== 'collapse' && !state.beforeKeys.has(row.key));
|
||||
return { row, key: row.key, hidden, process: isProcess, bucket: isProcess ? 'process' : 'other' };
|
||||
});
|
||||
const waves = arrangeTurnWaves(cells);
|
||||
let statusWaveIndex = -1;
|
||||
if (status) {
|
||||
for (let i = waves.length - 1; i >= 0; i--) {
|
||||
if (!waves[i]!.user && waves[i]!.process.length > 0) { statusWaveIndex = i; break; }
|
||||
}
|
||||
if (statusWaveIndex < 0) {
|
||||
for (let i = waves.length - 1; i >= 0; i--) {
|
||||
if (!waves[i]!.user) { statusWaveIndex = i; break; }
|
||||
}
|
||||
}
|
||||
if (statusWaveIndex < 0) {
|
||||
waves.push({ key: 'process-status', body: [], other: [], process: [] });
|
||||
statusWaveIndex = waves.length - 1;
|
||||
}
|
||||
}
|
||||
const renderCell = ({ row, hidden, process }: { row: FlowRow; hidden: boolean; process: boolean }) => {
|
||||
if (row.kind === 'summary') return <FlowCell key={row.key} rowKey={row.key} hidden={false} instant motion={motion} summary process={process}>
|
||||
<Summary item={row.item} open={processOpen && !!open[row.key]} onChange={value => onOpenChange(row.key, value)} motion={motion && state.phase !== 'collapse'} />
|
||||
</FlowCell>;
|
||||
return <FlowCell key={row.key} rowKey={row.key} hidden={hidden} instant={state.phase !== 'idle'} motion={motion} process={process}>
|
||||
{renderStep(row.step, !!row.foldKey)}
|
||||
</FlowCell>;
|
||||
};
|
||||
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>;
|
||||
{waves.map((wave, index) => {
|
||||
if (wave.user) return renderCell(wave.user);
|
||||
const hasStatus = index === statusWaveIndex && !!status;
|
||||
const hasProcessRows = wave.process.length > 0;
|
||||
const showProcessFrame = hasStatus || (processOpen && hasProcessRows);
|
||||
const hasLocalToggle = !hasStatus && !running && hasProcessRows && !wave.process.some(({ row }) => row.kind === 'summary');
|
||||
const localCollapsed = hasLocalToggle && collapsedFrames.has(wave.key);
|
||||
const hasVisibleProcessContent = wave.process.some(cell => !cell.hidden);
|
||||
const scrollHidden = localCollapsed || (!processOpen && !wave.process.some(cell => cell.row.kind === 'summary')) || !hasVisibleProcessContent;
|
||||
const frameCollapsed = scrollHidden;
|
||||
return <Fragment key={`wave:${wave.key}`}>
|
||||
{wave.body.length > 0 && <div className={css.answerBubble} data-reader-answer-bubble>
|
||||
{wave.body.map(cell => renderCell(cell))}
|
||||
</div>}
|
||||
{wave.other.map(cell => renderCell(cell))}
|
||||
{showProcessFrame && <div className={css.processViewport} data-reader-process-frame data-reader-frame-collapsed={frameCollapsed || undefined}>
|
||||
{hasStatus && <div className={css.turnStickyLanes} data-flow-process>{status}</div>}
|
||||
{hasLocalToggle && <div className={css.processFrameToggle}>
|
||||
<Disclosure open={!localCollapsed} ariaLabel="这段执行记录" onChange={nextOpen => {
|
||||
setCollapsedFrames(current => {
|
||||
const next = new Set(current);
|
||||
if (nextOpen) next.delete(wave.key);
|
||||
else next.add(wave.key);
|
||||
return next;
|
||||
});
|
||||
}} label={localCollapsed ? `查看 ${wave.process.length} 条执行记录` : '收起执行记录'} />
|
||||
</div>}
|
||||
<ProcessScroll hidden={scrollHidden} live={running && visible && state.phase === 'idle' && index === waves.length - 1
|
||||
&& wave.process.some(({ row, hidden }) => !hidden && row.kind === 'step' && !row.foldKey)}>
|
||||
{wave.process.map(cell => renderCell(cell))}
|
||||
</ProcessScroll>
|
||||
</div>}
|
||||
</Fragment>;
|
||||
})}
|
||||
</div>
|
||||
</StreamMotionContext.Provider>
|
||||
|
|
|
|||
|
|
@ -1,25 +1,20 @@
|
|||
import { useRef } from 'react';
|
||||
import type { RefObject } 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;
|
||||
export function ClosedProcessSummary({ steps, open, onChange, controls, buttonRef }: {
|
||||
steps: readonly LiveStep[]; open: boolean; onChange: (value: boolean) => void; controls: string; buttonRef?: RefObject<HTMLButtonElement>;
|
||||
}) {
|
||||
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>
|
||||
return <div className={`${css.closedProcessSummary} ${css.summaryRow}`} data-reader-closed-summary={summary}>
|
||||
<Disclosure open={open} onChange={onChange} controls={controls} buttonRef={buttonRef} ariaLabel="本轮过程详情"
|
||||
label={<FoldSummaryText summary={summary} motion={false} />} />
|
||||
<DiffStat steps={steps} label={summary} />
|
||||
</div>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ const useToolDisclosure: UseDisclosure = () => {
|
|||
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;
|
||||
const home = useSyncExternalStore(official.officialHostHome.subscribe, official.officialHostHome.getSnapshot);
|
||||
return <div data-reader-tool-official>
|
||||
{(official.renderSlot as (key: string, owner: object, options: object) => ReactNode)(OFFICIAL_SEATS.tools, {
|
||||
callId: block.callId, toolName,
|
||||
|
|
|
|||
|
|
@ -12,12 +12,14 @@
|
|||
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)));
|
||||
--reader-ai-max-width: 90%;
|
||||
/* 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));
|
||||
}
|
||||
:global([data-conversation-tabs] > button[data-better-chat-duplicate-tab]) { display: none !important; }
|
||||
.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. */
|
||||
|
|
@ -50,11 +52,34 @@
|
|||
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; }
|
||||
/* The host row needs the full axis. The fallback renders its bubble, images
|
||||
and actions as separate children of the same slot outlet. */
|
||||
.userCluster > [data-slot] > :not(.user, .userImages, .userActions) { 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: min(100%, 360px); min-width: 0; }
|
||||
.userImages .imageFigure { align-self: flex-end; width: 100%; }
|
||||
.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: 18px 18px 6px 18px; 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; }
|
||||
.answerBubble {
|
||||
align-self: flex-start;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
width: fit-content;
|
||||
max-width: var(--reader-ai-max-width);
|
||||
min-width: 0;
|
||||
padding: 10px 16px;
|
||||
box-sizing: border-box;
|
||||
border-radius: 18px 18px 18px 6px;
|
||||
background: var(--dsw-alias-bg-module-platform);
|
||||
border: 1px solid var(--dsw-alias-border-l1);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.answerBubble:not(:has(> .flowCell:not([hidden]))) { display: none; }
|
||||
.answerBubble > .flowCell > .flowCellInner { padding-bottom: 0; }
|
||||
.answerBubble :global(.md-code-block) {
|
||||
background: var(--dsw-alias-bg-base);
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
}
|
||||
.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; }
|
||||
|
|
@ -133,22 +158,19 @@
|
|||
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); }
|
||||
/* The inline disclosure supplies the spacing between narration blocks. */
|
||||
.processSeamRow { display: flex; align-items: center; }
|
||||
.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); }
|
||||
.toolActivity { color: var(--dsw-alias-label-secondary); }
|
||||
.toolActivity, .processCard {
|
||||
min-width: 0;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
border-radius: 12px;
|
||||
background: var(--dsw-alias-bg-module-platform);
|
||||
}
|
||||
.processCard { padding: 8px 12px; }
|
||||
.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; }
|
||||
|
|
@ -348,67 +370,17 @@
|
|||
@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; }
|
||||
|
|
@ -469,10 +441,11 @@
|
|||
.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); }
|
||||
.answerActions { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; margin: -4px 0 0 -6px; min-height: 28px; max-width: calc(100% + 6px); min-width: 0; }
|
||||
.userActions { display: flex; flex-wrap: wrap; align-items: center; align-self: flex-end; justify-content: flex-end; width: fit-content; max-width: 100%; gap: 4px 8px; min-height: 28px; }
|
||||
.answerActions > .meta:empty, .userActions > .meta:empty { display: none; }
|
||||
.messageClock { flex: none; font-size: 13px; line-height: 24px; color: var(--dsw-alias-label-tertiary); white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||||
.iconButton { flex: none; 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; }
|
||||
|
|
@ -520,11 +493,9 @@
|
|||
.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; }
|
||||
/* Keep each label and count together when a longer digest needs another line. */
|
||||
.foldSummary { display: inline-flex; align-items: baseline; flex-wrap: wrap; min-width: 0; }
|
||||
.foldSummaryPart { display: inline-flex; align-items: baseline; white-space: nowrap; 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; }
|
||||
|
|
@ -551,18 +522,82 @@
|
|||
[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; } }
|
||||
@media (max-width: 600px) { .root { padding-inline: 20px; --reader-ai-max-width: 92%; } .column { gap: 18px; } .toolbar { font-size: 11px; } }
|
||||
@container (max-width: 480px) { .choreographedFlow { --reader-ai-max-width: 92%; } }
|
||||
|
||||
/* Measured flow owns geometry; steps never change React parents when folded. */
|
||||
.choreographedFlow { display: flex; flex-direction: column; min-width: 0; overflow-anchor: none; }
|
||||
.choreographedFlow { display: flex; flex-direction: column; gap: 10px; 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; }
|
||||
.processViewport {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-self: flex-start;
|
||||
width: 100%;
|
||||
max-width: var(--reader-ai-max-width);
|
||||
min-width: 0;
|
||||
max-height: min(320px, 45vh);
|
||||
margin-bottom: 0;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
border-radius: 14px;
|
||||
background: var(--dsw-alias-bg-module-platform);
|
||||
}
|
||||
.processScroll {
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
overscroll-behavior-y: contain;
|
||||
padding: 0 8px;
|
||||
}
|
||||
.processViewport:not([data-reader-frame-collapsed]) > .processScroll:not([hidden]) {
|
||||
border-top: 1px solid var(--dsw-alias-border-l1);
|
||||
}
|
||||
.processScroll:not(:has(> .flowCell:not([hidden]))),
|
||||
.processViewport:not(:has(> .turnStickyLanes, > .processFrameToggle, .flowCell:not([hidden]))) { display: none; }
|
||||
.processScroll > .flowCell > .flowCellInner:not(:empty) { padding: 4px 0; }
|
||||
.processScroll:focus-visible { outline: 2px solid var(--dsw-alias-state-business-primary); outline-offset: -2px; }
|
||||
.processViewport > .turnStickyLanes { position: static; flex: none; padding: 4px 10px; }
|
||||
.root[data-reader-glass] .processViewport {
|
||||
background: color-mix(in srgb, var(--dsw-alias-bg-module-platform, rgba(128, 128, 128, .12)) 35%, transparent);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
.processViewport[data-reader-frame-collapsed] {
|
||||
width: fit-content;
|
||||
max-height: none;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--dsw-alias-border-l1);
|
||||
background: color-mix(in srgb, var(--dsw-alias-bg-module-platform) 75%, transparent);
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.processViewport[data-reader-frame-collapsed]:hover {
|
||||
border-color: var(--dsw-alias-border-l2);
|
||||
background: var(--dsw-alias-bg-module-platform);
|
||||
}
|
||||
.processViewport:has(.diffOverlayRow) {
|
||||
width: 100%;
|
||||
border-radius: 14px;
|
||||
}
|
||||
.processFrameToggle { flex: none; padding: 4px 10px; }
|
||||
.processViewport[data-reader-frame-collapsed] > .processFrameToggle,
|
||||
.processViewport[data-reader-frame-collapsed] > .turnStickyLanes { padding: 2px 10px; }
|
||||
.processViewport[data-reader-frame-collapsed] .disclosureButton {
|
||||
font-size: calc(13px + var(--dsh-content-font-delta, 0px));
|
||||
line-height: calc(22px + var(--dsh-content-font-delta, 0px));
|
||||
}
|
||||
.processViewport[data-reader-frame-collapsed] > .turnStickyLanes > .turnProcessSticky {
|
||||
min-height: 0;
|
||||
border: 0;
|
||||
}
|
||||
.flowCell[data-flow-process] :is(.reasonCard, .toolActivity, .processCard, .toolDetails, :global([data-turn-trigger])) {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
}
|
||||
.flowCell[data-flow-process] .processCard { padding: 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
|
||||
|
|
@ -590,22 +625,46 @@
|
|||
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; }
|
||||
.turnStickyLanes .turnProcessSticky { position: static; top: auto; z-index: auto; }
|
||||
.turnProcessSticky:has(> .closedProcessSummary) {
|
||||
width: 100%;
|
||||
gap: 8px;
|
||||
box-shadow: none;
|
||||
}
|
||||
.turnProcessSticky:has(> .closedProcessSummary) > .disclosure { flex: 0 0 auto; }
|
||||
.closedProcessSummary.summaryRow { flex: 1 1 auto; flex-wrap: nowrap; }
|
||||
.closedProcessSummary.summaryRow:has(> .diffOverlayRow) { flex-wrap: wrap; }
|
||||
/* 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; }
|
||||
.flowCell[data-flow-summary] { 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)); }
|
||||
.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]:not([data-flow-process]) > .flowCellInner { padding-bottom: 0; }
|
||||
.processScroll > .flowCell[data-flow-summary][data-flow-process] { position: sticky; top: 0; min-height: 0; padding-block: 0; box-shadow: none; background: var(--dsw-alias-bg-module-platform); }
|
||||
.processScroll > .flowCell[data-flow-summary][data-flow-process] > .flowCellInner { padding: 0; }
|
||||
.processViewport:not(:has(> .processScroll > .flowCell:not([hidden], [data-flow-summary]))) .flowCell[data-flow-summary][data-flow-process] { background: transparent; }
|
||||
.root[data-reader-glass] .flowCell[data-flow-summary][data-flow-process] { border-left: 0; padding-left: 0; }
|
||||
.flowCell[data-flow-summary] .disclosureButton, .closedProcessSummary .disclosureButton { width: auto; max-width: 100%; }
|
||||
.flowCell[data-flow-summary] .foldSummary, .closedProcessSummary .foldSummary { min-width: 0; }
|
||||
.disclosureButton:has([data-reader-fold-summary]),
|
||||
.turnProcessSticky > .disclosure > .disclosureButton {
|
||||
margin-left: 0;
|
||||
padding-inline: 12px;
|
||||
max-width: 100%;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
border-radius: var(--dsw-radius-xl, 22px);
|
||||
background: color-mix(in srgb, var(--dsw-alias-label-primary) 8%, transparent);
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
.disclosureButton:has([data-reader-fold-summary]):hover,
|
||||
.turnProcessSticky > .disclosure > .disclosureButton:hover {
|
||||
background: color-mix(in srgb, var(--dsw-alias-label-primary) 13%, transparent);
|
||||
}
|
||||
.turnProcessSticky > .disclosure { flex: 1 1 auto; min-width: 0; }
|
||||
.disclosureButton { width: max-content; max-width: calc(100% + 6px); }
|
||||
.statusText { flex: 0 1 auto; }
|
||||
|
|
@ -620,8 +679,7 @@
|
|||
.turnStickyLanes,
|
||||
.turnProcessSticky,
|
||||
.liveFoldContainer,
|
||||
.flowCell[data-flow-summary],
|
||||
.closedProcessSummary {
|
||||
.flowCell[data-flow-summary] {
|
||||
background-color: Canvas;
|
||||
background-image: var(--reader-lane-plate);
|
||||
background-repeat: no-repeat;
|
||||
|
|
@ -667,8 +725,7 @@
|
|||
}
|
||||
/* 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 {
|
||||
.root[data-reader-glass] .flowCell[data-flow-summary] {
|
||||
box-shadow: none;
|
||||
position: static;
|
||||
z-index: auto;
|
||||
|
|
@ -679,18 +736,41 @@
|
|||
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 */
|
||||
.turnStickyLanes[data-flow-process] { background: transparent; }
|
||||
.turnStickyLanes[data-flow-process] .turnProcessSticky { width: 100%; background: transparent; box-shadow: none; }
|
||||
.turnStickyLanes[data-flow-process] .disclosureButton,
|
||||
.flowCell[data-flow-process][data-flow-summary] .disclosureButton {
|
||||
border: 0;
|
||||
border-radius: 7px;
|
||||
background: transparent;
|
||||
backdrop-filter: none;
|
||||
}
|
||||
.turnStickyLanes[data-flow-process] .disclosureButton:hover,
|
||||
.flowCell[data-flow-process][data-flow-summary] .disclosureButton:hover {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
}
|
||||
:is(.processSeamRow, .processFrameToggle, .turnStickyLanes[data-flow-process], .flowCell[data-flow-process][data-flow-summary]) .disclosureButton {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
min-height: 0;
|
||||
font-size: var(--dsh-content-font-size, 14px);
|
||||
line-height: calc(24px + var(--dsh-content-font-delta, 0px));
|
||||
}
|
||||
/* User & AI bubbles become sleek translucent frosted pills 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);
|
||||
}
|
||||
.root[data-reader-glass] .answerBubble {
|
||||
background: color-mix(in srgb, var(--dsw-alias-bg-module-platform, rgba(128,128,128,.12)) 55%, transparent);
|
||||
backdrop-filter: blur(12px);
|
||||
border: 1px solid color-mix(in srgb, var(--dsw-alias-border-l1, rgba(128,128,128,.3)) 45%, 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 {
|
||||
.root[data-reader-glass] :is(.reasonCard, .toolActivity, .processCard) {
|
||||
background: transparent;
|
||||
border-color: color-mix(in srgb, var(--dsw-alias-border-l1, rgba(128,128,128,.35)) 65%, transparent);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,10 +5,10 @@ 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 { BlockBoundary, Blocks, contentBlocks, CopyAnswer, UserMessageActions } from './Blocks.js';
|
||||
import { AssistantNode } from './AssistantNode.js';
|
||||
import { ToolActivity, ToolMedia } from './ToolActivity.js';
|
||||
import { OfficialNode, OfficialTail } from './OfficialContent.js';
|
||||
import { OfficialActions, 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';
|
||||
|
|
@ -23,7 +23,7 @@ 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 { 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';
|
||||
|
|
@ -168,7 +168,7 @@ const ProcessNode = memo(function ProcessNode({ useChat, t, nodeKey, open, motio
|
|||
}
|
||||
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>;
|
||||
return content && <ProcessFragment open={open} motion={motion} onRead={onRead} returnFocusTo={returnFocusTo} nodeKey={nodeKey} framed><div className={css.processCard}>{content}</div></ProcessFragment>;
|
||||
});
|
||||
|
||||
const MainNode = memo(function MainNode({ useChat, nodeKey, boundary, pinned, processOpen: _processOpen = false, ...render }: SeatProps) {
|
||||
|
|
@ -277,11 +277,7 @@ function subagentCount(snapshot: { nodes: { get(key: string): ChatConversationVi
|
|||
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 === 'closed') return '执行过程';
|
||||
if (turn?.status !== 'open') return '执行过程';
|
||||
if (pending !== undefined) return '等待你的操作';
|
||||
const current = turn.steps.at(-1)?.data.get('assistant-step');
|
||||
|
|
@ -499,8 +495,9 @@ const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys,
|
|||
() => '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;
|
||||
const processSteps = useMemo(() => steps.filter(step => step.kind !== 'user' && step.kind !== 'body'), [steps]);
|
||||
const showClosedSummary = boundary.status === 'closed' && hasProcess && processSteps.length > 0;
|
||||
const showStatusLane = hasProcess && !isAwaitingModel && !showClosedSummary;
|
||||
// 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 =>
|
||||
|
|
@ -509,12 +506,6 @@ const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys,
|
|||
? 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.
|
||||
|
|
@ -540,8 +531,8 @@ const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys,
|
|||
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]);
|
||||
officialHostHome: props.officialHostHome, openView: props.openView,
|
||||
}), [props.renderSlot, props.renderSlotChain, props.officialImageLoader, props.officialFileMentions, props.officialPreviewFile, props.officialHostHome, 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(() => ({
|
||||
|
|
@ -564,7 +555,7 @@ const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys,
|
|||
const shared = {
|
||||
useChat: useFlowChat,
|
||||
renderSlotChain: props.renderSlotChain,
|
||||
loadImage: props.loadImage,
|
||||
loadImage: props.officialImageLoader,
|
||||
fillComposer: props.fillComposer,
|
||||
openFile: props.openFile,
|
||||
revealFile: props.revealFile,
|
||||
|
|
@ -585,12 +576,32 @@ const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys,
|
|||
const stoppedWithoutAnswer = (boundary.reason === 'interrupted' || boundary.reason === 'aborted') && !hasAnswerProse;
|
||||
const showTerminalNotice = terminal && !hasTurnError
|
||||
&& (stoppedWithoutAnswer || (boundary.reason !== 'interrupted' && boundary.reason !== 'aborted'));
|
||||
const finalBodyInfo = useMemo(() => {
|
||||
let lastUserIndex = -1;
|
||||
for (let i = steps.length - 1; i >= 0; i--) {
|
||||
if (steps[i]?.kind === 'user') { lastUserIndex = i; break; }
|
||||
}
|
||||
const waveBodySteps = steps
|
||||
.slice(lastUserIndex + 1)
|
||||
.filter((step): step is Extract<LiveStep, { kind: 'body' }> => step.kind === 'body');
|
||||
const lastBodyStep = waveBodySteps.at(-1);
|
||||
const lastNode = lastBodyStep ? nodes.get(lastBodyStep.nodeKey) : undefined;
|
||||
const finalData = lastNode && isNode(lastNode, 'assistant-step') ? lastNode.data : undefined;
|
||||
const copyBlocks = waveBodySteps.flatMap(step => step.blocks);
|
||||
return { finalData, copyBlocks };
|
||||
}, [steps, nodes]);
|
||||
const answerFork = useMemo(() => {
|
||||
const anchor = forkAnchorSeq([finalBodyInfo.finalData?.finalNode, { seq: forkSeq }]);
|
||||
return props.forkAt && anchor !== undefined ? () => props.forkAt!(anchor) : undefined;
|
||||
}, [finalBodyInfo.finalData?.finalNode, forkSeq, props.forkAt]);
|
||||
const showAnswerActions = boundary.status === 'closed'
|
||||
&& finalBodyInfo.finalData !== undefined
|
||||
&& finalBodyInfo.finalData.status !== 'running';
|
||||
const showStopped = finalBodyInfo.finalData?.status === 'interrupted';
|
||||
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)} />
|
||||
<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} />
|
||||
</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} />
|
||||
|
|
@ -605,23 +616,25 @@ const TurnGroup = memo(function TurnGroup({ group, motion, autoFold, pinnedKeys,
|
|||
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}
|
||||
running={sessionRunning && boundary.status === 'open' && !holdingSelection}
|
||||
status={(showStatusLane || showClosedSummary) && <StickyLane kind="status" className={css.turnProcessSticky}>
|
||||
{showStatusLane && <Disclosure open={expanded} onChange={setExpanded} controls={flowId} buttonRef={processButton}
|
||||
label={<GroupStatus group={group} useChat={props.useChat} pending={interaction} motion={motion} />} />}
|
||||
{showClosedSummary && <ClosedProcessSummary open={expanded} onChange={setExpanded} controls={flowId} buttonRef={processButton}
|
||||
steps={processSteps} />}
|
||||
</StickyLane>}
|
||||
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>}
|
||||
{showStopped && <span className={css.stopped}>已停止</span>}
|
||||
{showDeliverablesRow(boundary.status, deliverables) && <DeliverablesRow deliverables={deliverables} openFile={props.openFile} revealFile={props.revealFile} openMode={openMode} />}
|
||||
{showAnswerActions && <CopyAnswer blocks={finalBodyInfo.copyBlocks} onFork={answerFork} metrics={metrics}
|
||||
extraActions={<OfficialActions official={official} messageId={finalBodyInfo.finalData?.finalNode?.messageId} />} />}
|
||||
{boundary.status === 'closed' && <BlockBoundary><OfficialTail official={official} owner={tailOwner} produced={deliverables} /></BlockBoundary>}
|
||||
{showTerminalNotice && <div className={css.notice} data-reader-terminal>{terminal}</div>}
|
||||
</section>;
|
||||
|
|
|
|||
|
|
@ -1,306 +1,12 @@
|
|||
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">
|
||||
export function ReasoningCard({ children, step }: { children: ReactNode; step: number }) {
|
||||
return <div className={css.reasonCard} data-reader-reasoning-card>
|
||||
<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 className={css.reasonText} data-reader-reasoning-text>{children}</div>
|
||||
</div>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -60,17 +60,6 @@ export function publishLaneHeight(el: HTMLElement, property: string, scoped: Lan
|
|||
};
|
||||
}
|
||||
|
||||
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(() => {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
.container {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
gap: 4px 2px;
|
||||
position: relative;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
font-size: 13px;
|
||||
line-height: 24px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
|
|
@ -11,13 +14,19 @@
|
|||
.pillButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex: none;
|
||||
gap: 5px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 12px;
|
||||
height: 24px;
|
||||
padding: 0 8px;
|
||||
box-sizing: border-box;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--dsw-alias-border-l1);
|
||||
background: var(--dsw-alias-bg-module-platform);
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
transition: all 140ms ease;
|
||||
|
|
@ -33,16 +42,18 @@
|
|||
.timeButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex: none;
|
||||
gap: 4px;
|
||||
height: 28px;
|
||||
padding: 6px 8px;
|
||||
padding: 0 8px;
|
||||
box-sizing: border-box;
|
||||
border: none;
|
||||
border-radius: 28px;
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 13px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 24px;
|
||||
line-height: 20px;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
|
|
@ -64,7 +75,9 @@
|
|||
position: absolute;
|
||||
bottom: calc(100% + 8px);
|
||||
left: 0;
|
||||
width: 260px;
|
||||
width: min(260px, calc(100cqw - 24px), calc(100vw - 32px));
|
||||
max-width: calc(100vw - 32px);
|
||||
box-sizing: border-box;
|
||||
padding: 12px 14px;
|
||||
border-radius: 10px;
|
||||
background: var(--dsw-alias-bg-base);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { memo, useEffect, useRef, useState } from 'react';
|
||||
import { memo, useEffect, useLayoutEffect, 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';
|
||||
|
|
@ -26,6 +26,32 @@ export const TurnMetrics = memo(function TurnMetrics({
|
|||
}: TurnMetricsProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const containerRef = useRef<HTMLSpanElement>(null);
|
||||
const popRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!open) return;
|
||||
const clampPopover = () => {
|
||||
const container = containerRef.current;
|
||||
const pop = popRef.current;
|
||||
if (!container || !pop) return;
|
||||
pop.style.left = '0px';
|
||||
const host = container.closest<HTMLElement>('[data-dsh-better-display]') ?? container.closest<HTMLElement>('[data-conversation-scroll]');
|
||||
const bounds = host?.getBoundingClientRect() ?? { left: 0, right: window.innerWidth };
|
||||
const popRect = pop.getBoundingClientRect();
|
||||
const pad = 12;
|
||||
let shift = 0;
|
||||
if (popRect.right > bounds.right - pad) {
|
||||
shift = (bounds.right - pad) - popRect.right;
|
||||
}
|
||||
if (popRect.left + shift < bounds.left + pad) {
|
||||
shift = (bounds.left + pad) - popRect.left;
|
||||
}
|
||||
pop.style.left = `${Math.round(shift)}px`;
|
||||
};
|
||||
clampPopover();
|
||||
window.addEventListener('resize', clampPopover);
|
||||
return () => window.removeEventListener('resize', clampPopover);
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
|
@ -92,7 +118,7 @@ export const TurnMetrics = memo(function TurnMetrics({
|
|||
)}
|
||||
|
||||
{open && (
|
||||
<div className={css.metricsPop} role="dialog" aria-label="本轮概况">
|
||||
<div ref={popRef} className={css.metricsPop} role="dialog" aria-label="本轮概况">
|
||||
<div className={css.popHeader}>
|
||||
<span>本轮性能与用量概况</span>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -8,3 +8,24 @@ export function chatSeatProps(kind: ChatSeatKind, key: string): Record<string, s
|
|||
'data-chat-flow-kind': kind,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Official ChatView's row contract for one assistant answer part.
|
||||
*
|
||||
* `data-chat-flow-kind="assistant-step"` is the marker plugins such as
|
||||
* dsh-btw rely on to recognise "this selection is part of a model answer";
|
||||
* without it they walk up from the selection, find no message row, and bail.
|
||||
* The flow key stays unique per rendered part so row lookups do not merge
|
||||
* separate paragraphs. `data-chat-anchor-key` is deliberately absent: the
|
||||
* reader performs its own rewind hiding (`rewind-cut.ts`) and publishing the
|
||||
* official anchor on every part would let a DOM-level rewind plugin hide only
|
||||
* part of a turn.
|
||||
*/
|
||||
export function answerRowAttrs(nodeKey: string, partStart: number, turn: number | undefined): Record<string, string> {
|
||||
return {
|
||||
'data-chat-flow-kind': 'assistant-step',
|
||||
'data-chat-flow-key': `${nodeKey}#${partStart}`,
|
||||
'data-chat-node-key': nodeKey,
|
||||
...(turn === undefined ? {} : { 'data-chat-turn': String(turn) }),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,162 @@
|
|||
/**
|
||||
* Chat-view tab ownership for the reader-in-chat layout.
|
||||
*
|
||||
* The reader used to live in its own "阅读" View tab. It now occupies the
|
||||
* built-in "对话" View id instead, so the transcript area draws the reader
|
||||
* while the composer, header, approvals, and scroll port stay official.
|
||||
*
|
||||
* `conversation.view` is a list Slot: a registration with the same `id` at a
|
||||
* lower priority wins the cell for rendering. The tab row, however, is derived
|
||||
* from the raw entry ledger (`slots.entries`), and normally skips entries whose
|
||||
* `id` is undefined. Shadowing alone would therefore show two "对话" tabs.
|
||||
*
|
||||
* The preferred way to hide the official row is to clear only its View `id`:
|
||||
* the row, its children, store, and disposer stay entirely official, so the
|
||||
* official disposer still releases `conversation.chat.flow` and the Chat store
|
||||
* if ui-chat tears down while we shadow it. Removing the row would leak those
|
||||
* and make the next ui-chat registration throw "slot is already declared".
|
||||
*
|
||||
* If the host still paints both tabs, the header fallback hides the extra
|
||||
* button without editing the registration ledger.
|
||||
*
|
||||
* A subscription re-hides a ChatView row that ui-chat re-registers while the
|
||||
* plugin stays mounted. Every visibility change bumps the ledger version with
|
||||
* a throwaway probe registration (never selected) so View subscribers such as
|
||||
* the header recompute their tab list.
|
||||
*/
|
||||
import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
|
||||
export const CHAT_VIEW_ID = 'chat';
|
||||
|
||||
/** Lower than the official ChatView registration (priority 0) so it shadows. */
|
||||
export const CHAT_VIEW_PRIORITY = -10;
|
||||
|
||||
const PROBE_ID = 'dsh-better-chat:chat-view-ledger-probe';
|
||||
const CHAT_TAB_LIST = '[data-conversation-tabs][role="tablist"]';
|
||||
const DUPLICATE_TAB = 'data-better-chat-duplicate-tab';
|
||||
|
||||
/** Keep the outer header usable if the host still paints both chat registrations. */
|
||||
export function hideDuplicateChatTabs(doc: Document): () => void {
|
||||
const sync = () => {
|
||||
for (const list of doc.querySelectorAll(CHAT_TAB_LIST)) {
|
||||
let seenChat = false;
|
||||
for (const tab of list.querySelectorAll<HTMLButtonElement>(':scope > button[role="tab"]')) {
|
||||
const label = tab.textContent?.trim() ?? '';
|
||||
const isChat = label === '对话' || label === '對話' || label === 'Chat';
|
||||
tab.toggleAttribute(DUPLICATE_TAB, isChat && seenChat);
|
||||
if (isChat) seenChat = true;
|
||||
}
|
||||
}
|
||||
};
|
||||
const observer = new MutationObserver(records => {
|
||||
if (records.some(record => {
|
||||
const target = record.target instanceof Element ? record.target : record.target.parentElement;
|
||||
return target?.closest(CHAT_TAB_LIST) || Array.from(record.addedNodes).some(node =>
|
||||
node instanceof Element && (node.matches(CHAT_TAB_LIST) || node.querySelector(CHAT_TAB_LIST)));
|
||||
})) sync();
|
||||
});
|
||||
observer.observe(doc.documentElement, { childList: true, characterData: true, subtree: true });
|
||||
sync();
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
for (const tab of doc.querySelectorAll(`[${DUPLICATE_TAB}]`)) tab.removeAttribute(DUPLICATE_TAB);
|
||||
};
|
||||
}
|
||||
|
||||
/** The registry operations this seat needs; documented public surface. */
|
||||
export interface ViewLedger {
|
||||
entries(name: string): readonly StoredEntry[];
|
||||
register(options: {
|
||||
name: string;
|
||||
id: string;
|
||||
priority?: number;
|
||||
order?: number;
|
||||
label?: () => string;
|
||||
}, component: unknown): () => void;
|
||||
subscribe(name: string, listener: () => void): () => void;
|
||||
}
|
||||
|
||||
/** One active retirement per View ledger (`ctx.slots` is a single shared object). */
|
||||
const ACTIVE = new WeakMap<ViewLedger, () => void>();
|
||||
|
||||
/**
|
||||
* Hide the official ChatView row from the View tab projection by clearing its
|
||||
* View `id`; the row itself stays live and keeps its official disposer.
|
||||
* @param ledger - Slot registry surfaced through `ctx.slots`.
|
||||
* @returns idempotent restore for plugin teardown.
|
||||
*/
|
||||
export function retireHostedChatView(ledger: ViewLedger): () => void {
|
||||
if (ACTIVE.has(ledger)) return () => {};
|
||||
const hidden = new Set<StoredEntry>();
|
||||
let live = true;
|
||||
let notifying = false;
|
||||
|
||||
// Splicing ids does not bump the slot version, so View subscribers would
|
||||
// keep a stale tab list. A throwaway registration both notifies and is gone
|
||||
// before paint: its id is never the selected View.
|
||||
const notify = (): void => {
|
||||
if (notifying) return;
|
||||
notifying = true;
|
||||
try {
|
||||
const dispose = ledger.register({
|
||||
name: 'conversation.view',
|
||||
id: PROBE_ID,
|
||||
priority: CHAT_VIEW_PRIORITY,
|
||||
order: 0,
|
||||
label: () => '',
|
||||
}, () => null);
|
||||
dispose();
|
||||
} finally {
|
||||
notifying = false;
|
||||
}
|
||||
};
|
||||
|
||||
const hide = (): void => {
|
||||
let changed = false;
|
||||
for (const entry of ledger.entries('conversation.view')) {
|
||||
if (entry.options.id !== CHAT_VIEW_ID) continue;
|
||||
if ((entry.options.priority ?? 0) === CHAT_VIEW_PRIORITY) continue;
|
||||
if (hidden.has(entry)) continue;
|
||||
try {
|
||||
entry.options.id = undefined;
|
||||
} catch {
|
||||
// The header fallback handles immutable entry options.
|
||||
}
|
||||
if (entry.options.id === undefined) {
|
||||
hidden.add(entry);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) notify();
|
||||
};
|
||||
|
||||
// Registration-time callback; a later ui-chat registration also lands here.
|
||||
const unsubscribe = ledger.subscribe('conversation.view', () => {
|
||||
if (live) hide();
|
||||
});
|
||||
hide();
|
||||
|
||||
const restore = (): void => {
|
||||
if (!live) return;
|
||||
live = false;
|
||||
unsubscribe();
|
||||
ACTIVE.delete(ledger);
|
||||
let changed = false;
|
||||
const present = new Set(ledger.entries('conversation.view'));
|
||||
for (const entry of hidden) {
|
||||
if (!present.has(entry)) continue;
|
||||
try {
|
||||
entry.options.id = CHAT_VIEW_ID;
|
||||
changed = true;
|
||||
} catch {
|
||||
// Frozen options are already the host's own limitation.
|
||||
}
|
||||
}
|
||||
|
||||
hidden.clear();
|
||||
if (changed) notify();
|
||||
};
|
||||
ACTIVE.set(ledger, restore);
|
||||
return restore;
|
||||
}
|
||||
|
|
@ -32,9 +32,12 @@ export interface KeyEventLike {
|
|||
altKey?: boolean
|
||||
}
|
||||
|
||||
/** 「始终允许」的默认键帽;单列出来,展开时不会沾上 `null` 带来的可选键。 */
|
||||
export const DEFAULT_ALWAYS: ApprovalBinding = { key: 'Enter', primary: true, shift: false, alt: false }
|
||||
|
||||
export const DEFAULT_BINDINGS: ApprovalBindings = {
|
||||
allow: { key: 'Enter', primary: false, shift: false, alt: false },
|
||||
always: { key: 'Enter', primary: true, shift: false, alt: false },
|
||||
always: DEFAULT_ALWAYS,
|
||||
reject: { key: 'Escape', primary: false, shift: false, alt: false },
|
||||
}
|
||||
|
||||
|
|
@ -112,18 +115,20 @@ export function normalizeBindings(value: unknown): ApprovalBindings {
|
|||
const rejectRaw = normalizeBinding(record.reject)
|
||||
const allow = allowRaw && allowRaw.key === 'Enter' ? allowRaw : { ...DEFAULT_BINDINGS.allow }
|
||||
const reject = rejectRaw && rejectRaw.key === 'Escape' ? rejectRaw : { ...DEFAULT_BINDINGS.reject }
|
||||
const alwaysRaw = 'always' in record ? record.always : DEFAULT_BINDINGS.always
|
||||
const alwaysRaw = 'always' in record ? record.always : DEFAULT_ALWAYS
|
||||
const alwaysParsed = alwaysRaw === null ? null : normalizeBinding(alwaysRaw)
|
||||
const always = alwaysParsed && alwaysParsed.key === 'Enter'
|
||||
? alwaysParsed
|
||||
: (alwaysRaw === null ? null : { ...DEFAULT_BINDINGS.always })
|
||||
const always: ApprovalBinding | null = alwaysRaw === null
|
||||
? null
|
||||
: alwaysParsed && alwaysParsed.key === 'Enter'
|
||||
? alwaysParsed
|
||||
: { ...DEFAULT_ALWAYS }
|
||||
|
||||
const out: ApprovalBindings = { allow, always, reject }
|
||||
// 冲突(或「始终允许」没修饰键)时把 allow/always 一起回落到默认,
|
||||
// 避免一个按键命中两个动作;默认值本身互不冲突。
|
||||
if (out.always && (!hasModifier(out.always) || bindingsEqual(out.allow, out.always))) {
|
||||
out.allow = { ...DEFAULT_BINDINGS.allow }
|
||||
out.always = { ...DEFAULT_BINDINGS.always }
|
||||
out.always = { ...DEFAULT_ALWAYS }
|
||||
}
|
||||
if (out.always && bindingsEqual(out.reject, out.always)) {
|
||||
out.reject = { ...DEFAULT_BINDINGS.reject }
|
||||
|
|
|
|||
|
|
@ -1,14 +1,19 @@
|
|||
/**
|
||||
* 功能二:权限 UI —— 去掉「完全权限」选项,不改已有会话权限。
|
||||
* 功能二:权限策略 —— 去掉「完全权限」选项,新会话默认「自动审查」。
|
||||
*
|
||||
* 会话权限有四个预设值:read-only(仅可查看)、workspace-write(工作区内
|
||||
* 修改)、danger-full-access(完全权限)、auto(自动审查,EXP)。「自动
|
||||
* 审查」由实验层提供,开启后才出现在当前会话的选择器里;通用设置不提供
|
||||
* auto,新会话默认值里也选不到它。
|
||||
* 审查」由实验层 @deepseek-ai/dsh-experimental-auto-review 提供,开启后才
|
||||
* 出现在当前会话的选择器里;通用设置不提供 auto,新会话默认值里也选不到它。
|
||||
*
|
||||
* 本功能只做一件事:界面移除完全权限。它**不再**在页面加载、刷新或插件
|
||||
* 重载时遍历已有会话改权限:默认权限属于宿主的新建会话流程,本插件没有
|
||||
* 可靠的新建扩展点,因此不拿轮询去补偿。
|
||||
* 本模块做两件事:
|
||||
* 1. 界面移除「完全权限」:观察 DOM,把选择器/菜单/设置下拉里标签为「完全
|
||||
* 权限 / Full access」的选项摘掉。只动界面,手动输入命令仍可达。
|
||||
* 2. 新建/空白会话默认「自动审查」:首次见到空白顶层会话且其权限不是 auto
|
||||
* 时,通过宿主命令通道 `/permission auto` 切过去。已处理过的会话 id 会
|
||||
* 持久化在 localStorage(`dsh.better-chat.permission-handled.v1`),且已
|
||||
* 有对话内容的会话(`blank === false`)和子代理会话不会被改写;用户手
|
||||
* 动切回只读/工作区修改后,刷新或重载也不会被覆盖。
|
||||
*/
|
||||
|
||||
/** 完全权限的预设机器值。 */
|
||||
|
|
@ -17,6 +22,9 @@ export const FULL_ACCESS_PRESET = 'danger-full-access'
|
|||
export const AUTO_REVIEW_PRESET = 'auto'
|
||||
/** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */
|
||||
export const FULL_ACCESS_LABELS = ['完全权限', 'Full access']
|
||||
/** 已处理会话 id 的浏览器持久化键,避免刷新后覆盖用户手动改过的权限。 */
|
||||
export const HANDLED_STORAGE_KEY = 'dsh.better-chat.permission-handled.v1'
|
||||
const MAX_HANDLED_IDS = 500
|
||||
|
||||
/** 纯判定:一段选项文字是否就是「完全权限」选项(标签打头,或恰好相等)。 */
|
||||
export function isFullAccessLabel(text: unknown): boolean {
|
||||
|
|
@ -30,13 +38,16 @@ export function shouldAutoSwitch(preset: string | undefined | null, alreadyHandl
|
|||
return preset !== undefined && preset !== null && preset !== AUTO_REVIEW_PRESET && !alreadyHandled
|
||||
}
|
||||
|
||||
interface LiveSession {
|
||||
export interface LiveSession {
|
||||
id: string
|
||||
live: unknown
|
||||
live: any
|
||||
}
|
||||
|
||||
/**
|
||||
* 防御式枚举宿主的 live 会话:优先 keys()+binding(),退回 list()。
|
||||
* 防御式枚举宿主的 live 会话:
|
||||
* 1. `keys() + binding()`(测试桩或旧形状)
|
||||
* 2. DSH 0.2.2 `ClientSessions`:`scopes` Map 与 `list.getSnapshot()`(`ids` / `byId`)配合 `binding(id)`
|
||||
* 3. `list()` 函数回退
|
||||
* 服务形状对不上时安静返回空数组,绝不抛错。
|
||||
*/
|
||||
export function liveSessions(sessions: any): LiveSession[] {
|
||||
|
|
@ -50,6 +61,30 @@ export function liveSessions(sessions: any): LiveSession[] {
|
|||
}
|
||||
return out
|
||||
}
|
||||
if (typeof sessions.binding === 'function' || sessions.scopes instanceof Map) {
|
||||
const seen = new Set<string>()
|
||||
const addCandidate = (id: unknown) => {
|
||||
if (typeof id !== 'string' || !id || seen.has(id)) return
|
||||
const live =
|
||||
(typeof sessions.binding === 'function' ? sessions.binding(id)?.session : undefined) ??
|
||||
(sessions.scopes instanceof Map ? sessions.scopes.get(id)?.binding?.session : undefined)
|
||||
if (live) {
|
||||
seen.add(id)
|
||||
out.push({ id, live })
|
||||
}
|
||||
}
|
||||
if (sessions.scopes instanceof Map) {
|
||||
for (const id of sessions.scopes.keys()) addCandidate(id)
|
||||
}
|
||||
const listSnap = typeof sessions.list?.getSnapshot === 'function' ? sessions.list.getSnapshot() : undefined
|
||||
if (Array.isArray(listSnap?.ids)) {
|
||||
for (const id of listSnap.ids) addCandidate(id)
|
||||
}
|
||||
if (listSnap?.byId && typeof listSnap.byId === 'object') {
|
||||
for (const id of Object.keys(listSnap.byId)) addCandidate(id)
|
||||
}
|
||||
if (out.length > 0 || typeof sessions.list !== 'function') 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 })
|
||||
|
|
@ -61,15 +96,71 @@ export function liveSessions(sessions: any): LiveSession[] {
|
|||
return out
|
||||
}
|
||||
|
||||
/** 读会话当前的权限预设值(投影不可用时返回 undefined)。 */
|
||||
/**
|
||||
* 读会话当前的权限预设值(投影不可用时返回 undefined)。
|
||||
* 兼容 DSH 0.2.2 的 `{ currentValue: string }` 投影视图与直接返回字符串的测试桩。
|
||||
*/
|
||||
export function currentPreset(live: any): string | undefined {
|
||||
try {
|
||||
return live?.projections?.faceOf('permissions')?.getSnapshot?.()
|
||||
const snap = live?.projections?.faceOf?.('permissions')?.getSnapshot?.()
|
||||
if (typeof snap === 'string') return snap
|
||||
if (snap && typeof snap === 'object' && typeof (snap as { currentValue?: unknown }).currentValue === 'string') {
|
||||
return (snap as { currentValue: string }).currentValue
|
||||
}
|
||||
return undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定会话是否允许执行首次默认自动审查切换:
|
||||
* - 已有对话内容的会话(`blank === false`)不改;
|
||||
* - 子代理会话(`origin === 'subagent'`)不改;
|
||||
* - 其余空白新建会话(以及未提供 blank 元数据的轻量测试桩)允许首次切换。
|
||||
*/
|
||||
export function isAutoSwitchEligible(id: string, live: any, sessions?: any): boolean {
|
||||
try {
|
||||
if (live?.getSnapshot?.()?.blank === false) return false
|
||||
const summary = sessions?.list?.getSnapshot?.()?.byId?.[id]
|
||||
if (summary?.blank === false) return false
|
||||
if (summary?.origin === 'subagent') return false
|
||||
} catch {
|
||||
// 忽略元数据读取异常
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function loadHandledIds(doc: Document): Set<string> {
|
||||
const set = new Set<string>()
|
||||
try {
|
||||
const storage = (doc as any)?.defaultView?.localStorage
|
||||
const raw = storage?.getItem?.(HANDLED_STORAGE_KEY)
|
||||
if (typeof raw === 'string' && raw) {
|
||||
const parsed = JSON.parse(raw)
|
||||
if (Array.isArray(parsed)) {
|
||||
for (const item of parsed) {
|
||||
if (typeof item === 'string' && item) set.add(item)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// localStorage 不可用时仅在内存保存
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
function saveHandledIds(doc: Document, set: Set<string>): void {
|
||||
try {
|
||||
const storage = (doc as any)?.defaultView?.localStorage
|
||||
if (!storage?.setItem) return
|
||||
const items = [...set].slice(-MAX_HANDLED_IDS)
|
||||
storage.setItem(HANDLED_STORAGE_KEY, JSON.stringify(items))
|
||||
} catch {
|
||||
// 忽略写入异常
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把「完全权限」选项从当前文档里摘掉:原生 select 的 option、弹出
|
||||
* 选择器(role=listbox)与菜单(role=menu)里的 option/menuitem。
|
||||
|
|
@ -93,25 +184,34 @@ export function pruneFullAccess(doc: Document): number {
|
|||
}
|
||||
|
||||
export interface PolicyTimers {
|
||||
setInterval?: (fn: () => void, ms: number) => number
|
||||
clearInterval?: (id: number) => void
|
||||
setTimeout: (fn: () => void, ms: number) => number
|
||||
clearTimeout: (id: number) => void
|
||||
}
|
||||
|
||||
const defaultTimers: Required<PolicyTimers> = {
|
||||
setInterval: (fn, ms) => setInterval(fn, ms) as unknown as number,
|
||||
clearInterval: (id) => clearInterval(id),
|
||||
setTimeout: (fn, ms) => setTimeout(fn, ms) as unknown as number,
|
||||
clearTimeout: (id) => clearTimeout(id),
|
||||
}
|
||||
|
||||
/**
|
||||
* 安装权限 UI 策略:只观察 DOM、摘掉「完全权限」选项。
|
||||
* 不接收 getSessions,也不启动任何会话轮询。
|
||||
* 安装权限策略:
|
||||
* 1. 观察 DOM、摘掉「完全权限」选项;
|
||||
* 2. 观察/轮询空白新建会话,首次见到时自动切到 `auto`(自动审查)。
|
||||
* @returns 卸载函数
|
||||
*/
|
||||
export function installPermissionPolicy(
|
||||
doc: Document,
|
||||
_getSessions?: unknown,
|
||||
timers: PolicyTimers = {
|
||||
setTimeout: (fn, ms) => setTimeout(fn, ms) as unknown as number,
|
||||
clearTimeout: (id) => clearTimeout(id),
|
||||
},
|
||||
getSessions?: () => any,
|
||||
timers: PolicyTimers = defaultTimers,
|
||||
): () => void {
|
||||
let disposed = false
|
||||
let scanTimer = 0
|
||||
const setTimerInterval = timers.setInterval ?? defaultTimers.setInterval
|
||||
const clearTimerInterval = timers.clearInterval ?? defaultTimers.clearInterval
|
||||
const scheduleScan = (): void => {
|
||||
if (disposed || scanTimer) return
|
||||
scanTimer = timers.setTimeout(() => {
|
||||
|
|
@ -123,9 +223,100 @@ export function installPermissionPolicy(
|
|||
if (doc.body) observer.observe(doc.body, { childList: true, subtree: true })
|
||||
pruneFullAccess(doc)
|
||||
|
||||
const handled = loadHandledIds(doc)
|
||||
const inFlight = new Set<string>()
|
||||
const projectionUnsubs = new Map<string, () => void>()
|
||||
let listUnsub: (() => void) | undefined
|
||||
|
||||
const markHandled = (id: string): void => {
|
||||
if (!handled.has(id)) {
|
||||
handled.add(id)
|
||||
saveHandledIds(doc, handled)
|
||||
}
|
||||
const unsub = projectionUnsubs.get(id)
|
||||
if (unsub) {
|
||||
projectionUnsubs.delete(id)
|
||||
try { unsub() } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
const watchProjection = (id: string, live: any): void => {
|
||||
if (projectionUnsubs.has(id) || handled.has(id)) return
|
||||
const face = live?.projections?.faceOf?.('permissions')
|
||||
if (typeof face?.subscribe !== 'function') return
|
||||
try {
|
||||
const unsub = face.subscribe(() => {
|
||||
if (!disposed) void tick()
|
||||
})
|
||||
if (typeof unsub === 'function') projectionUnsubs.set(id, unsub)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
const tick = async (): Promise<void> => {
|
||||
if (disposed || typeof getSessions !== 'function') return
|
||||
let sessions: any
|
||||
try {
|
||||
sessions = getSessions()
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
if (!listUnsub && typeof sessions?.list?.subscribe === 'function') {
|
||||
try {
|
||||
listUnsub = sessions.list.subscribe(() => {
|
||||
if (!disposed) void tick()
|
||||
})
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
for (const { id, live } of liveSessions(sessions)) {
|
||||
if (handled.has(id) || inFlight.has(id)) continue
|
||||
if (!isAutoSwitchEligible(id, live, sessions)) {
|
||||
markHandled(id)
|
||||
continue
|
||||
}
|
||||
const preset = currentPreset(live)
|
||||
if (!shouldAutoSwitch(preset, handled.has(id))) {
|
||||
if (preset !== undefined && preset !== null) {
|
||||
markHandled(id)
|
||||
} else {
|
||||
watchProjection(id, live)
|
||||
}
|
||||
continue
|
||||
}
|
||||
markHandled(id)
|
||||
if (typeof live?.command !== 'function') continue
|
||||
inFlight.add(id)
|
||||
try {
|
||||
const result = await live.command(`/permission ${AUTO_REVIEW_PRESET}`)
|
||||
if (!result?.ok) {
|
||||
console.info('[dsh-better-chat] auto review not applied for session', id, result?.error?.code ?? '')
|
||||
}
|
||||
} catch {
|
||||
console.info('[dsh-better-chat] auto review switch failed for session', id)
|
||||
} finally {
|
||||
inFlight.delete(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const intervalId = typeof getSessions === 'function' ? setTimerInterval(() => { void tick() }, 2500) : 0
|
||||
if (typeof getSessions === 'function') void tick()
|
||||
|
||||
return () => {
|
||||
disposed = true
|
||||
observer.disconnect()
|
||||
if (scanTimer) timers.clearTimeout(scanTimer)
|
||||
if (intervalId) clearTimerInterval(intervalId)
|
||||
if (listUnsub) {
|
||||
try { listUnsub() } catch { /* ignore */ }
|
||||
listUnsub = undefined
|
||||
}
|
||||
for (const unsub of projectionUnsubs.values()) {
|
||||
try { unsub() } catch { /* ignore */ }
|
||||
}
|
||||
projectionUnsubs.clear()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,7 +24,59 @@ 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 type FlowBucket = 'body' | 'process' | 'user' | 'other';
|
||||
export interface FlowWave<T> {
|
||||
key: string;
|
||||
body: T[];
|
||||
other: T[];
|
||||
process: T[];
|
||||
user?: T;
|
||||
}
|
||||
|
||||
/** Keep process cells together, including rows temporarily hidden by a fold. */
|
||||
export function groupProcessRows<T extends { process: boolean }>(rows: readonly T[]): T[][] {
|
||||
const groups: T[][] = [];
|
||||
for (const row of rows) {
|
||||
const previous = groups.at(-1);
|
||||
if (row.process && previous?.[0]?.process) previous.push(row);
|
||||
else groups.push([row]);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
/**
|
||||
* Partition a turn's flow cells into waves around mid-turn user/steering
|
||||
* messages. Inside each wave, assistant reply segments merge into one reply
|
||||
* bubble on top while thinking, tools and records collect into a single
|
||||
* process frame beneath it.
|
||||
*/
|
||||
export function arrangeTurnWaves<T extends { key: string; bucket: FlowBucket }>(rows: readonly T[]): FlowWave<T>[] {
|
||||
const waves: FlowWave<T>[] = [];
|
||||
let current: FlowWave<T> | null = null;
|
||||
let anchor = 'initial';
|
||||
const ensure = (): FlowWave<T> => {
|
||||
if (!current) {
|
||||
current = { key: anchor, body: [], other: [], process: [] };
|
||||
waves.push(current);
|
||||
}
|
||||
return current;
|
||||
};
|
||||
for (const row of rows) {
|
||||
if (row.bucket === 'user') {
|
||||
waves.push({ key: row.key, body: [], other: [], process: [], user: row });
|
||||
current = null;
|
||||
anchor = `after:${row.key}`;
|
||||
continue;
|
||||
}
|
||||
const wave = ensure();
|
||||
if (row.bucket === 'body') wave.body.push(row);
|
||||
else if (row.bucket === 'process') wave.process.push(row);
|
||||
else wave.other.push(row);
|
||||
}
|
||||
return waves;
|
||||
}
|
||||
|
||||
/** Each step keeps its React key when its fold 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 }))]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,35 @@
|
|||
/**
|
||||
* Structural faces for the host services this client plugin injects but whose
|
||||
* packages are not published (see host-modules.d.ts). Kept deliberately small:
|
||||
* only the members this plugin actually calls are typed, and the session face
|
||||
* stays `any` because the host session facade is not part of the public API.
|
||||
*/
|
||||
import '@deepseek-ai/cordis';
|
||||
|
||||
export interface RemoteSessionFace {
|
||||
openWorkspacePath: (arg: { path: string }) => Promise<{ ok: boolean; error?: { message: string } }>;
|
||||
}
|
||||
|
||||
export interface RemoteFace {
|
||||
/** Host projection store handed to the official reader host seat. */
|
||||
$host: { home?: string };
|
||||
session?: RemoteSessionFace;
|
||||
}
|
||||
|
||||
export interface SessionsFace {
|
||||
binding: (sessionId: string) => { session?: any } | undefined;
|
||||
list: { getSnapshot: () => { byId: Record<string, { cwd?: string } | undefined> } };
|
||||
}
|
||||
|
||||
declare module '@deepseek-ai/cordis' {
|
||||
interface Context {
|
||||
/** Injected as `remote` (see the client entry's `inject` array). */
|
||||
remote: RemoteFace;
|
||||
/** Injected as `sessions`. */
|
||||
sessions: SessionsFace;
|
||||
}
|
||||
|
||||
interface Events {
|
||||
'connection/reset': () => void;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
/**
|
||||
* Host-side client packages that the desktop build ships inside its own
|
||||
* bundle but does not publish as installable dependencies. The plugin imports
|
||||
* them only for their declaration-merging side effects (services and events on
|
||||
* the Cordis context), so an empty ambient module is enough to keep the
|
||||
* imports resolvable in this repository.
|
||||
*/
|
||||
declare module '@deepseek-ai/dsh-api-remotes/client' {}
|
||||
declare module '@deepseek-ai/dsh-api-session-controller/client' {}
|
||||
declare module '@deepseek-ai/dsh-client-connection/client' {}
|
||||
declare module '@deepseek-ai/dsh-session-turn-outline/types' {}
|
||||
declare module '@deepseek-ai/dsh-agent/types' {}
|
||||
|
|
@ -37,8 +37,8 @@ export function apply(ctx: Context): void {
|
|||
ctx.effect(() => installApprovalKeys(document, getBindings), 'dsh-better-chat: approval key routing')
|
||||
ctx.effect(() => installKeyHints(document, { getBindings }), 'dsh-better-chat: approval key hints')
|
||||
ctx.effect(
|
||||
() => installPermissionPolicy(document),
|
||||
'dsh-better-chat: permission policy (no full access)',
|
||||
() => installPermissionPolicy(document, () => (ctx as { sessions?: unknown }).sessions),
|
||||
'dsh-better-chat: permission policy (no full access, auto review by default)',
|
||||
)
|
||||
try {
|
||||
ctx.plugin(storeUpdatePlugin as any)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
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 { assistantSegments, hasVisibleBody, isProcessRecord } from './projection.js';
|
||||
import type { TurnBoundary } from './projection.js';
|
||||
import type { ReaderFlowEntry, ToolActivityEntry } from './tool-activity.js';
|
||||
|
||||
|
|
@ -9,7 +9,7 @@ export type LiveStep =
|
|||
| { 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 };
|
||||
| { kind: 'other'; key: string; nodeKey: string; process?: boolean };
|
||||
|
||||
export type LiveTurnItem =
|
||||
| { kind: 'user'; key: string; step: Extract<LiveStep, { kind: 'user' }> }
|
||||
|
|
@ -99,7 +99,7 @@ export function segmentLiveTurn(
|
|||
continue;
|
||||
}
|
||||
const node = get(entry.nodeKey);
|
||||
if (!node || node.visibility === 'hidden' || node.kind === 'turn-tail') continue;
|
||||
if (!node || node.visibility === 'hidden' || (node.kind === 'turn-tail' || node.kind === 'turn-process')) continue;
|
||||
if (node.kind === 'user' || node.kind === 'steering') {
|
||||
steps.push({ kind: 'user', key: entry.key, nodeKey: entry.nodeKey });
|
||||
continue;
|
||||
|
|
@ -108,80 +108,53 @@ export function segmentLiveTurn(
|
|||
steps.push(...stepsFromAssistant(entry.nodeKey, node.data as AssistantChatData, toolsByCallId, consumed));
|
||||
continue;
|
||||
}
|
||||
steps.push({ kind: 'other', key: entry.key, nodeKey: entry.nodeKey });
|
||||
steps.push({ kind: 'other', key: entry.key, nodeKey: entry.nodeKey, process: node.kind === 'turn-trigger' || isProcessRecord(node) });
|
||||
}
|
||||
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');
|
||||
function isLiveProcess(step: LiveStep): boolean {
|
||||
return step.kind === 'reasoning' || step.kind === 'tool' || (step.kind === 'other' && step.process === true);
|
||||
}
|
||||
|
||||
/**
|
||||
* One live chain: narration stays visible, while every earlier reasoning/tool
|
||||
* run collapses into its own box at its original position.
|
||||
*/
|
||||
/** Fold the preceding process at visible output or a newer reasoning step. */
|
||||
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[] = [];
|
||||
const show = (step: LiveStep) => items.push({ kind: 'open', key: step.key, step });
|
||||
const flush = () => {
|
||||
const lastReasoning = live ? segment.findLastIndex(step => step.kind === 'reasoning') : -1;
|
||||
let run: LiveStep[] = [];
|
||||
const finishRun = (fold: boolean) => {
|
||||
if (fold && run.length) {
|
||||
items.push({ kind: 'fold', key: `live-fold:${run[0]!.key}`, steps: run, summary: foldSummary(run) });
|
||||
} else {
|
||||
run.forEach(show);
|
||||
}
|
||||
run = [];
|
||||
};
|
||||
for (const [index, step] of segment.entries()) {
|
||||
if (live && isLiveProcess(step)) {
|
||||
if (index === lastReasoning) finishRun(true);
|
||||
run.push(step);
|
||||
} else {
|
||||
finishRun(live && (step.kind === 'body' || index < lastReasoning));
|
||||
show(step);
|
||||
}
|
||||
}
|
||||
finishRun(false);
|
||||
segment = [];
|
||||
};
|
||||
for (const step of steps) {
|
||||
if (step.kind === 'user') {
|
||||
segments.push(segment); segments.push([step]); segment = [];
|
||||
flush();
|
||||
items.push({ kind: 'user', key: step.key, step });
|
||||
} 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();
|
||||
}
|
||||
flush();
|
||||
return items;
|
||||
}
|
||||
|
||||
|
|
@ -194,12 +167,14 @@ export function presentLiveTurn(steps: readonly LiveStep[], boundary: TurnBounda
|
|||
* 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 type ProcessSeam = { summary: string; count: number };
|
||||
|
||||
export function planProcessSeams(
|
||||
steps: readonly LiveStep[],
|
||||
liveItems: readonly LiveTurnItem[],
|
||||
expanded: boolean,
|
||||
): { before: Map<string, string>; after: Set<string> } {
|
||||
const before = new Map<string, string>();
|
||||
): { before: Map<string, ProcessSeam>; after: Set<string> } {
|
||||
const before = new Map<string, ProcessSeam>();
|
||||
const after = new Set<string>();
|
||||
if (expanded) return { before, after };
|
||||
const liveFolded = new Set(
|
||||
|
|
@ -213,7 +188,7 @@ export function planProcessSeams(
|
|||
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));
|
||||
before.set(step.key, { summary: foldSummary(folded), count: folded.length });
|
||||
after.add(previousBody.key);
|
||||
}
|
||||
previousBody = step;
|
||||
|
|
|
|||
|
|
@ -302,3 +302,82 @@
|
|||
text-decoration: underline var(--dsw-alias-state-business-primary);
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
/* Compact variant: secondary text sizing, uniform bold headings, tight block
|
||||
spacing — the same shape as the official MarkdownText `variant="compact"`. */
|
||||
.compact {
|
||||
max-width: 100%;
|
||||
font-size: var(--dsh-content-font-size-secondary, 13px);
|
||||
line-height: calc(20px + var(--dsh-content-font-delta-secondary, 0px));
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
.compact :is(h1, h2, h3, h4, h5, h6) {
|
||||
margin: 8px 0 4px;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.compact :is(p, ul, ol, blockquote) {
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
.compact li:not(:first-child) {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.compact li > p {
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
.compact li::marker {
|
||||
line-height: inherit;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.compact blockquote {
|
||||
padding-left: 8px;
|
||||
}
|
||||
|
||||
.compact hr {
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.compact a,
|
||||
.compact .fileMention {
|
||||
font-weight: inherit;
|
||||
color: inherit;
|
||||
text-decoration: underline dotted;
|
||||
}
|
||||
|
||||
.compact :not(pre) > code {
|
||||
display: inline;
|
||||
font: inherit;
|
||||
font-family: var(--ds-font-family-code);
|
||||
font-size: 1em !important;
|
||||
border-radius: var(--dsw-radius-xs);
|
||||
padding: 0 3px;
|
||||
box-decoration-break: clone;
|
||||
}
|
||||
|
||||
.compact :global(.md-code-block) {
|
||||
margin: 4px 0;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.compact pre,
|
||||
.compact pre :is(code, span) {
|
||||
color: inherit !important;
|
||||
}
|
||||
|
||||
.markdown.compact .tableScroll {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
margin: 4px 0;
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
.markdown.compact .tableScroll > table {
|
||||
z-index: auto;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -167,7 +167,7 @@ class StreamingRenderer {
|
|||
* 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 }: {
|
||||
export const MarkdownText = memo(function MarkdownText({ text, streaming = false, codeLabels, fileMentions, pathImages, renderText, renderAtom, variant = 'body' }: {
|
||||
text: string
|
||||
streaming?: boolean
|
||||
codeLabels?: MarkdownCodeLabels | undefined
|
||||
|
|
@ -175,6 +175,8 @@ export const MarkdownText = memo(function MarkdownText({ text, streaming = false
|
|||
pathImages?: MarkdownPathImages | undefined
|
||||
renderText?: MarkdownRenderContext['renderText']
|
||||
renderAtom?: MarkdownRenderContext['renderAtom']
|
||||
/** `compact` is the secondary-text/short-block shape used for reasoning bodies. */
|
||||
variant?: 'body' | 'compact'
|
||||
}) {
|
||||
const streamRef = useRef<StreamingRenderer | null>(null)
|
||||
const streamImagesRef = useRef(pathImages)
|
||||
|
|
@ -191,5 +193,5 @@ export const MarkdownText = memo(function MarkdownText({ text, streaming = false
|
|||
}
|
||||
return streamRef.current.render(text)
|
||||
}, [text, streaming, codeLabels, fileMentions, pathImages, renderText, renderAtom])
|
||||
return <div className={css.markdown}>{children}</div>
|
||||
return <div className={variant === 'compact' ? `${css.markdown} ${css.compact}` : css.markdown}>{children}</div>
|
||||
})
|
||||
|
|
|
|||
|
|
@ -452,14 +452,19 @@ export function useReadingScroll(root: RefObject<HTMLElement>, motion: boolean):
|
|||
}
|
||||
if (!bottom) { following.current = false; setDetached(true); }
|
||||
};
|
||||
const fromProcess = (event: Event) => event.target instanceof Element
|
||||
&& event.target.closest('[data-reader-process-scroll]');
|
||||
const onWheel = (event: WheelEvent) => {
|
||||
if (fromProcess(event)) return;
|
||||
cancelAnimationFrame(followFrame); followFrame = 0; lastWrittenTop = null;
|
||||
if (event.deltaY < 0) { following.current = false; setDetached(true); pinned.current = false; scheduleCapture(); }
|
||||
};
|
||||
const onTouch = () => {
|
||||
const onTouch = (event: TouchEvent) => {
|
||||
if (fromProcess(event)) return;
|
||||
cancelAnimationFrame(followFrame); followFrame = 0; lastWrittenTop = null;
|
||||
};
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (fromProcess(event)) return;
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -69,7 +69,12 @@ export function hasProcessContent(node: ChatConversationViewNode | undefined, _b
|
|||
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'
|
||||
return node.kind === 'turn-process' || isProcessRecord(node);
|
||||
}
|
||||
|
||||
export function isProcessRecord(node: ChatConversationViewNode | undefined): boolean {
|
||||
if (!node || node.visibility === 'hidden') return false;
|
||||
return node.kind === 'context' || node.kind === 'model-retry' || node.kind === 'system-prompt'
|
||||
|| node.kind === 'command' || node.kind === 'manual-compaction' || node.kind === 'compaction';
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import type { Context } from '@deepseek-ai/cordis';
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store';
|
||||
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';
|
||||
|
|
@ -12,7 +13,8 @@ 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 { CHAT_VIEW_ID, CHAT_VIEW_PRIORITY, hideDuplicateChatTabs, retireHostedChatView, type ViewLedger } from './chat-view-seat.js';
|
||||
import { UserImageFallback } from './Blocks.js';
|
||||
import { installBetterDisplaySettings } from './settings.js';
|
||||
import type { ChatPrefs } from './chat/bindings-store.js';
|
||||
import { fillComposerDom } from './mcp-app.js';
|
||||
|
|
@ -71,18 +73,35 @@ export function apply(ctx: Context, options: { chatPrefs?: ChatPrefs } = {}): vo
|
|||
const restoreTextTransform = installTextTransformRegistry(textTransform);
|
||||
ctx.provide(TEXT_TRANSFORM_SERVICE, textTransform);
|
||||
ctx.effect(() => restoreTextTransform);
|
||||
const officialHostHome = createSnapshotStore<string | undefined>(undefined);
|
||||
ctx.effect(() => {
|
||||
// A retiring tool card can still render after this Cordis context closes.
|
||||
// React reads the store only, while the active plugin refreshes its value.
|
||||
const updateHome = () => officialHostHome.set(ctx.remote.$host?.home);
|
||||
updateHome();
|
||||
return ctx.on('connection/reset', updateHome);
|
||||
}, 'better-chat: host home snapshot');
|
||||
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, options.chatPrefs);
|
||||
ctx.slots.inject('conversation.chat.user.images', () => ctx.slots.register({
|
||||
name: 'conversation.chat.user.images',
|
||||
priority: 1000,
|
||||
}, UserImageFallback));
|
||||
|
||||
ctx.slots.inject('conversation.chat.node', function* () {
|
||||
yield retireHostedChatView(ctx.slots as unknown as ViewLedger);
|
||||
// Occupies the built-in 对话 View: the transcript area draws the reader,
|
||||
// the official composer/header/scroll port stay untouched.
|
||||
yield ctx.slots.register({
|
||||
name: 'conversation.view',
|
||||
id: 'reader',
|
||||
order: -5,
|
||||
label: () => '阅读',
|
||||
id: CHAT_VIEW_ID,
|
||||
priority: CHAT_VIEW_PRIORITY,
|
||||
order: 0,
|
||||
label: () => '对话',
|
||||
locale: 'chat',
|
||||
children: {
|
||||
'dsh-better-display.block': { kind: 'chain', scope: 'session' },
|
||||
|
|
@ -90,6 +109,7 @@ export function apply(ctx: Context, options: { chatPrefs?: ChatPrefs } = {}): vo
|
|||
},
|
||||
store,
|
||||
inject: (sessionId: SessionId): ReaderInjected => {
|
||||
const uiConversation = ctx.uiConversation;
|
||||
const session = () => {
|
||||
const current = ctx.sessions.binding(sessionId)?.session;
|
||||
if (!current) throw new Error('阅读页对应的会话已关闭。');
|
||||
|
|
@ -98,8 +118,8 @@ export function apply(ctx: Context, options: { chatPrefs?: ChatPrefs } = {}): vo
|
|||
return {
|
||||
openPrefs: prefs,
|
||||
officialImageLoader: Object.assign(
|
||||
(attachment: ImageAttachmentRef) => ctx.uiConversation.imageUrl(sessionId, attachment),
|
||||
{ peek: (attachment: ImageAttachmentRef) => ctx.uiConversation.peekImageUrl(sessionId, attachment) },
|
||||
(attachment: ImageAttachmentRef) => uiConversation.imageUrl(sessionId, attachment),
|
||||
{ peek: (attachment: ImageAttachmentRef) => uiConversation.peekImageUrl(sessionId, attachment) },
|
||||
),
|
||||
officialFileMentions: owner => ctx.get('chatFileMentions')?.forClosing(owner, sessionId),
|
||||
officialPreviewFile: path => {
|
||||
|
|
@ -108,16 +128,8 @@ export function apply(ctx: Context, options: { chatPrefs?: ChatPrefs } = {}): vo
|
|||
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),
|
||||
},
|
||||
officialHostHome,
|
||||
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;
|
||||
|
|
@ -233,7 +245,7 @@ export function apply(ctx: Context, options: { chatPrefs?: ChatPrefs } = {}): vo
|
|||
};
|
||||
},
|
||||
}, Reader);
|
||||
yield hideDuplicateChatTabs(document);
|
||||
yield installOfficialSlots(ctx);
|
||||
yield installReaderEntry(ctx);
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,6 +15,6 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
|
|||
'settings.section': { kind: 'list'; scope: 'root'; owner: SettingsSectionOwnerProps };
|
||||
}
|
||||
interface LocaleNamespaceMap {
|
||||
'better-display': SettingsCopyKey;
|
||||
'better-chat': SettingsCopyKey;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment';
|
||||
import type { AssistantBlock, MessageImageLoader } from '@deepseek-ai/dsh-client-ui-conversation/client';
|
||||
import type { MarkdownFileMentions } from '@deepseek-ai/dsh-client-ui-primitives';
|
||||
import type { PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
|
|
@ -44,7 +43,6 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
|
|||
|
||||
export interface ReaderInjected {
|
||||
loadOlder: () => Promise<void>;
|
||||
loadImage: (attachment: ImageAttachmentRef) => Promise<{ data: Uint8Array; mediaType: string }>;
|
||||
/**
|
||||
* Writes text into this session's composer draft via the sanctioned
|
||||
* conversation input face, with a DOM fallback. Returns true when the
|
||||
|
|
@ -56,7 +54,7 @@ export interface ReaderInjected {
|
|||
officialImageLoader: MessageImageLoader;
|
||||
officialFileMentions: (owner: TurnTailOwnerProps) => MarkdownFileMentions | undefined;
|
||||
officialPreviewFile: (path: string) => void;
|
||||
officialHost: { getSnapshot: () => { home?: string }; subscribe: (listener: () => void) => () => void };
|
||||
officialHostHome: { getSnapshot: () => string | undefined; subscribe: (listener: () => void) => () => void };
|
||||
/** Root-scoped Better Display prefs (`dsh.reader.v1`), shared with Settings. */
|
||||
openPrefs?: {
|
||||
getSnapshot: () => {
|
||||
|
|
@ -86,8 +84,9 @@ export type ReaderProps = PropsRuntime<'conversation.view'>
|
|||
& PropsRenderSlots<'dsh-better-display.block' | OfficialSeat>
|
||||
& PropsStore<ReturnType<typeof createReaderStore>>
|
||||
& ReaderInjected;
|
||||
export type BlockRenderProps = Pick<ReaderProps, 'renderSlotChain' | 'loadImage' | 'fillComposer'> & {
|
||||
official?: Pick<ReaderProps, 'renderSlot' | 'renderSlotChain' | 'officialImageLoader' | 'officialFileMentions' | 'officialPreviewFile' | 'officialHost' | 'openView'>;
|
||||
export type BlockRenderProps = Pick<ReaderProps, 'renderSlotChain' | 'fillComposer'> & {
|
||||
loadImage: MessageImageLoader;
|
||||
official?: Pick<ReaderProps, 'renderSlot' | 'renderSlotChain' | 'officialImageLoader' | 'officialFileMentions' | 'officialPreviewFile' | 'officialHostHome' | 'openView'>;
|
||||
cwd?: string;
|
||||
openFile?: (path: string, options?: OpenFileOptions) => Promise<void> | void;
|
||||
revealFile?: (path: string) => Promise<void> | void;
|
||||
|
|
|
|||
|
|
@ -67,8 +67,8 @@ export function MotionPlainText({ text, enabled, revision }: { text: string; ena
|
|||
}
|
||||
|
||||
/** Native DSH Markdown semantics with a stable text-leaf animation hook. */
|
||||
export function MotionMarkdown({ text, streaming, enabled, revision, fileMentions }: {
|
||||
text: string; streaming: boolean; enabled: boolean; revision: number; fileMentions?: MarkdownFileMentions;
|
||||
export function MotionMarkdown({ text, streaming, enabled, revision, fileMentions, variant = 'body' }: {
|
||||
text: string; streaming: boolean; enabled: boolean; revision: number; fileMentions?: MarkdownFileMentions; variant?: 'body' | 'compact';
|
||||
}) {
|
||||
const timeline = useRef<WordTimeline>();
|
||||
timeline.current ??= new WordTimeline();
|
||||
|
|
@ -87,6 +87,6 @@ export function MotionMarkdown({ text, streaming, enabled, revision, fileMention
|
|||
return current.hasLiveText ? <MotionAtom born={current.bornAt(offset)} generation={current.generation} offset={offset}>{children}</MotionAtom> : children;
|
||||
}, []);
|
||||
return <WordScope.Provider value={scope}>
|
||||
<MarkdownText text={text} streaming={streaming} codeLabels={CODE_LABELS} fileMentions={fileMentions} pathImages={readerPathImages} renderText={renderText} renderAtom={renderAtom} />
|
||||
<MarkdownText text={text} streaming={streaming} codeLabels={CODE_LABELS} fileMentions={fileMentions} pathImages={readerPathImages} renderText={renderText} renderAtom={renderAtom} variant={variant} />
|
||||
</WordScope.Provider>;
|
||||
}
|
||||
|
|
|
|||
175
src/host.ts
175
src/host.ts
|
|
@ -1,87 +1,110 @@
|
|||
import type { IncomingMessage, ServerResponse } from 'node:http';
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
import { loadFlags, type Flags } from './flags.js';
|
||||
import { createLogger, requestIdOf } from './log.js';
|
||||
import { metricsPayload, recordRouteDuration, recordRouteHit, ROUTE_METRICS, ROUTE_REVEAL } from './metrics.js';
|
||||
import { createRevealHandler, revealRoots } from './reveal.js';
|
||||
|
||||
declare module '@deepseek-ai/cordis' {
|
||||
interface Context {
|
||||
webServer?: {
|
||||
register: (route: {
|
||||
kind: 'exact' | 'prefix';
|
||||
path: string;
|
||||
handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
|
||||
}) => () => void;
|
||||
};
|
||||
}
|
||||
}
|
||||
import { createLogger } from './log.js';
|
||||
|
||||
export const name = 'dsh-better-chat';
|
||||
export const inject = ['webServer'];
|
||||
export const inject: string[] = [];
|
||||
|
||||
const log = createLogger({ base: { plugin: name } });
|
||||
|
||||
function writeJson(res: ServerResponse, status: number, body: unknown): void {
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.statusCode = status;
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
const AUTO_REVIEW_PRESET = 'auto';
|
||||
|
||||
function beginRequest(req: IncomingMessage, res: ServerResponse, route: string): string {
|
||||
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;
|
||||
}
|
||||
|
||||
export function apply(ctx: Context, options?: { readonly flags?: Flags }): void {
|
||||
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;
|
||||
/**
|
||||
* 判断宿主会话是否为「尚未开始对话、且用户未手动改过权限」的新建空白顶层会话。
|
||||
* - 排除子代理会话(`origin === 'subagent'`)与 fork/seed 会话;
|
||||
* - 排除已开始轮次或已有用户消息的会话;
|
||||
* - 排除用户已显式执行过 `/permission` 命令的会话。
|
||||
*/
|
||||
export function isFreshAutoEligibleSession(session: any): boolean {
|
||||
if (!session || typeof session !== 'object') return false;
|
||||
const header = session.header;
|
||||
if (header?.origin === 'subagent') return false;
|
||||
if (header?.isSeeded === true) return false;
|
||||
if (typeof session.inheritedEventCount === 'number' && session.inheritedEventCount > 0) return false;
|
||||
if (typeof session.snapshotEvents === 'function') {
|
||||
try {
|
||||
const events = session.snapshotEvents() as Array<{ type?: string; data?: { name?: string } }>;
|
||||
for (const event of events) {
|
||||
if (
|
||||
event?.type === 'turn/start'
|
||||
|| event?.type === 'user/message'
|
||||
|| event?.type === 'session/end-seed'
|
||||
|| (event?.type === 'command/run' && event?.data?.name === 'permission')
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
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 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();
|
||||
disposeMetrics();
|
||||
};
|
||||
}, 'dsh-better-chat: reveal and metrics routes');
|
||||
export function applyHostAutoReview(permissionPresets: any, session: any, handled: Set<string>): boolean {
|
||||
if (!permissionPresets || !session) return false;
|
||||
const id: string | undefined = typeof session.id === 'string'
|
||||
? session.id
|
||||
: typeof session.header?.id === 'string'
|
||||
? session.header.id
|
||||
: undefined;
|
||||
if (id && handled.has(id)) return false;
|
||||
if (!isFreshAutoEligibleSession(session)) {
|
||||
if (id) handled.add(id);
|
||||
return false;
|
||||
}
|
||||
const names: unknown = permissionPresets.names;
|
||||
if (!Array.isArray(names) || !names.includes(AUTO_REVIEW_PRESET)) {
|
||||
// 实验层 auto-review 尚未就绪:暂不记入 handled,待 catalog-changed 时再切。
|
||||
return false;
|
||||
}
|
||||
if (id) handled.add(id);
|
||||
try {
|
||||
if (permissionPresets.current?.(session) === AUTO_REVIEW_PRESET) return false;
|
||||
permissionPresets.set?.(session, AUTO_REVIEW_PRESET);
|
||||
return true;
|
||||
} catch (err) {
|
||||
log.info('auto review preset switch skipped', {
|
||||
sessionId: id ?? '',
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function mountAutoReviewListeners(targetCtx: any): void {
|
||||
const handled = new Set<string>();
|
||||
const scanAll = (): void => {
|
||||
const presets = targetCtx.permissionPresets;
|
||||
const list = targetCtx.agents?.list?.() ?? [];
|
||||
for (const agent of list) {
|
||||
if (agent?.session) applyHostAutoReview(presets, agent.session, handled);
|
||||
}
|
||||
};
|
||||
targetCtx.effect?.(() => {
|
||||
const offCreated = targetCtx.on?.('agent/created', ({ agent }: { agent?: { session?: unknown } }) => {
|
||||
if (agent?.session) applyHostAutoReview(targetCtx.permissionPresets, agent.session, handled);
|
||||
});
|
||||
const offCatalog = targetCtx.on?.('permission-presets/catalog-changed', () => {
|
||||
scanAll();
|
||||
});
|
||||
scanAll();
|
||||
return () => {
|
||||
if (typeof offCreated === 'function') offCreated();
|
||||
if (typeof offCatalog === 'function') offCatalog();
|
||||
};
|
||||
}, 'dsh-better-chat: default auto-review preset for new sessions');
|
||||
}
|
||||
|
||||
export function apply(ctx: Context): void {
|
||||
log.info('[dsh-better-chat] loaded');
|
||||
|
||||
// Cordis throws when a service is read before it is declared in inject, so never
|
||||
// probe services on the context directly: a scoped ctx.inject mounts the listeners
|
||||
// once both services exist and skips cleanly otherwise (plain object contexts too).
|
||||
const anyCtx = ctx as any;
|
||||
if (typeof anyCtx.inject === 'function') {
|
||||
anyCtx.inject(['permissionPresets', 'agents'], (childCtx: any) => {
|
||||
mountAutoReviewListeners(childCtx);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,64 +0,0 @@
|
|||
import React, { useSyncExternalStore } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import type { ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client';
|
||||
import { Reader } from '../src/client/Reader.js';
|
||||
import { createReaderStore } from '../src/client/store.js';
|
||||
import type { ReaderProps } from '../src/client/types.js';
|
||||
|
||||
// Real Reader and real root/session stores; only conversation data is synthetic.
|
||||
const store = createReaderStore();
|
||||
const prefs = store.create();
|
||||
const session = store.create('auto-fold-fixture');
|
||||
const nodes = new Map();
|
||||
const turns = new Map();
|
||||
for (const [number, closed] of [[1, true], [2, false]] as const) {
|
||||
const turn = {
|
||||
turn: number, status: closed ? 'closed' : 'open',
|
||||
start: { seq: number * 10, time: 1 },
|
||||
end: closed ? { time: 1001, data: { reason: { kind: 'completed' } } } : undefined,
|
||||
data: new Map(closed ? [['turn-tail', { closing: { step: 1 } }]] : []),
|
||||
steps: [] as any[],
|
||||
};
|
||||
for (let step = 0; step < 2; step++) {
|
||||
const key = `turn-${number}-step-${step}`;
|
||||
const data = { turn: number, step, status: closed || step === 0 ? 'settled' : 'running', time: 1,
|
||||
blocks: [
|
||||
{ kind: 'reasoning', text: closed ? `已完成思考 ${step}` : `进行中思考 ${step}` },
|
||||
{ kind: 'text', text: closed && step === 1 ? '最终回答始终保留' : `过程说明 ${number}-${step}` },
|
||||
],
|
||||
};
|
||||
const location = { step, start: { seq: number * 10 + step }, data: new Map([['assistant-step', data]]) };
|
||||
turn.steps.push(location);
|
||||
nodes.set(key, { key, kind: 'assistant-step', visibility: 'visible', anchorSeq: number * 10 + step,
|
||||
location: { kind: 'step', turn, step: location }, data });
|
||||
}
|
||||
turns.set(number, turn);
|
||||
}
|
||||
const chat = { order: [...nodes.keys()], nodes, timeline: { turns } } as unknown as ChatSnapshot;
|
||||
const sessionSnapshot = { running: true, openState: 'ready', pendingSubmissions: [], hasMore: false, loadingOlder: false };
|
||||
const sessionsSnapshot = { byId: { 'auto-fold-fixture': { cwd: '/fixture' } } };
|
||||
const pending = new Map();
|
||||
const host = { home: '/fixture' };
|
||||
const useReaderStore: ReaderProps['useStore'] = selector => selector(useSyncExternalStore(session.subscribe, session.getSnapshot));
|
||||
const props = {
|
||||
sessionId: 'auto-fold-fixture', useChat: selector => selector(chat),
|
||||
useSession: selector => selector(sessionSnapshot), useSessions: selector => selector(sessionsSnapshot),
|
||||
useSessionStatus: selector => selector(new Map([['auto-fold-fixture', { running: true, pendingInteraction: pending.get('auto-fold-fixture'), completionUnread: false }]])),
|
||||
useStore: useReaderStore, actions: session.actions, openPrefs: prefs,
|
||||
t: key => key, renderSlot: (_name, _owner, options) => options?.fallback ?? null,
|
||||
renderSlotChain: (_name, _owner, options) => options?.fallback ?? null,
|
||||
loadImage: async () => ({ data: new Uint8Array(), mediaType: 'image/png' }),
|
||||
officialImageLoader: Object.assign(async () => null, { peek: () => null }),
|
||||
officialFileMentions: () => undefined, officialPreviewFile: () => {},
|
||||
officialHost: { getSnapshot: () => host, subscribe: () => () => {} },
|
||||
fillComposer: () => true, openFile: () => {}, loadOlder: async () => {}, openView: () => {},
|
||||
} as ReaderProps;
|
||||
|
||||
Object.assign(window, { autoFoldFixture: {
|
||||
// Exercise Settings' root preference path without recreating the Reader.
|
||||
preference: (value: boolean) => prefs.actions.setAutoFold(value),
|
||||
state: () => session.getSnapshot(),
|
||||
} });
|
||||
createRoot(document.getElementById('app')!).render(
|
||||
<div data-conversation-scroll style={{ height: '100vh', overflow: 'auto' }}><Reader {...props} /></div>,
|
||||
);
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
import React, { useMemo, useRef, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import type { ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client';
|
||||
import { ChoreographedFlow } from '../src/client/ChoreographedFlow.js';
|
||||
import { ClosedProcessSummary } from '../src/client/ClosedProcessSummary.js';
|
||||
import { ProcessFragment } from '../src/client/motion.js';
|
||||
import { presentLiveTurn } from '../src/client/live-turn.js';
|
||||
import type { LiveStep } from '../src/client/live-turn.js';
|
||||
function Fixture() {
|
||||
const [open,setOpen]=useState(false);const button=useRef<HTMLButtonElement>(null);
|
||||
const steps=useMemo(()=>Array.from({length:500},(_,i):LiveStep=>({kind:'reasoning',key:`r${i}`,nodeKey:`r${i}`,step:i,start:0,blocks:[]})),[]);
|
||||
const frame=useMemo(()=>({items:presentLiveTurn(steps,{status:'closed',reason:'completed',closingStep:501,latestStep:501}),snapshot:{} as ChatSnapshot}),[steps]);
|
||||
return <main style={{padding:30}}><h1>完成后 500 条过程记录:实际组件回归</h1>
|
||||
<button ref={button} onClick={()=>setOpen(v=>!v)}>切换过程展开</button>
|
||||
<ClosedProcessSummary steps={steps} open={open} onChange={setOpen} controls="closed-flow"/>
|
||||
<ChoreographedFlow id="closed-flow" frame={frame} motion enabled={false} urgent={false} processOpen={open} open={{}} onOpenChange={()=>{}}
|
||||
renderStep={step=><ProcessFragment open={open} motion onRead={()=>{}} returnFocusTo={button} nodeKey={step.key}><p>过程内容 {step.key}</p></ProcessFragment>}/>
|
||||
<article data-final-answer>最终回答必须紧随统计,不能隔着 8000px 空白;展开、收起以后仍应如此。</article></main>;
|
||||
}
|
||||
createRoot(document.getElementById('app')!).render(<Fixture/>);
|
||||
|
|
@ -1,191 +0,0 @@
|
|||
import React, { useSyncExternalStore } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import type { ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client';
|
||||
import { Reader } from '../src/client/Reader.js';
|
||||
import { createReaderStore } from '../src/client/store.js';
|
||||
import type { ReaderProps } from '../src/client/types.js';
|
||||
|
||||
/**
|
||||
* Real Reader + real root/session stores; only conversation data is synthetic.
|
||||
*
|
||||
* This fixture isolates the "process report narration" bug: an assistant step
|
||||
* that carries a long non-reasoning text block (正文) between thinking steps used
|
||||
* to be classified as process content and folded away. Contract under test:
|
||||
* body text is always visible; folds may only hold reasoning / tool / other
|
||||
* process records.
|
||||
*
|
||||
* Turn layout:
|
||||
* 1 closed/completed : step0 = reasoning + 正文A + tool-call ; step1 = reasoning + 最终回答B
|
||||
* 2 open : step0 = reasoning + 进行中汇报正文C ; step1 = reasoning (latest)
|
||||
* 3 closed/error : step0 = reasoning + 失败轮正文D
|
||||
* 4 closed/interrupted: step0 = reasoning + 中断轮正文E
|
||||
*/
|
||||
const BODY_A = '过程汇报正文A';
|
||||
const REASON_A = '历史思考:先查简报素材';
|
||||
const FINAL_B = '最终回答B';
|
||||
const REASON_B = '第二次思考:整理结论';
|
||||
const TOOL_SUMMARY = '读取 简报素材.txt';
|
||||
const BODY_C = '进行中汇报正文C';
|
||||
const REASON_C0 = '第一轮思考';
|
||||
const REASON_C1 = '第二轮思考';
|
||||
const BODY_D = '失败轮正文D';
|
||||
const REASON_D = '报错前的思考';
|
||||
const BODY_E = '中断轮正文E';
|
||||
const REASON_E = '中断前的思考';
|
||||
// Turn 5 exercises the segmented-report case: two adjacent narration paragraphs
|
||||
// (with folded reasoning between them) plus a final answer, all with long text.
|
||||
const BODY_F = '第一段汇报:已完成需求梳理,确认改造点集中在投影层与阅读渲染层。这一步整理的是已经核实的事实,不包括猜测。\n\n第二段汇报:接下来核对折叠链边界,并验证正文在收起状态下仍然可见,同时保持思维链与工具行可以展开。';
|
||||
const REASON_F0 = '汇报前的思考';
|
||||
const BODY_G = '补充汇报:折叠只保留思维链与工具调用,正文块保持原位。';
|
||||
const REASON_G = '补充说明前的思考';
|
||||
const REASON_H = '收尾思考';
|
||||
const FINAL_H = '最终回答H';
|
||||
const TOOL_CALL_ID = 'call-read-1';
|
||||
const TOOL_ARGS = '{"path":"/fixture/工作区/简报素材.txt"}';
|
||||
|
||||
const store = createReaderStore();
|
||||
const prefs = store.create();
|
||||
const session = store.create('commentary-fixture');
|
||||
|
||||
type Turn = {
|
||||
turn: number; status: 'open' | 'closed';
|
||||
start: { seq: number; time: number };
|
||||
end?: { time: number; data: { reason: { kind: string } } };
|
||||
data: Map<string, any>;
|
||||
steps: any[];
|
||||
};
|
||||
const nodes = new Map<string, any>();
|
||||
const turns = new Map<number, Turn>();
|
||||
|
||||
function newTurn(turn: number, status: 'open' | 'closed', seq: number, reason?: string): Turn {
|
||||
const value: Turn = {
|
||||
turn, status, start: { seq, time: 1 },
|
||||
end: status === 'closed' ? { time: 1001, data: { reason: { kind: reason ?? 'completed' } } } : undefined,
|
||||
data: new Map<string, any>(),
|
||||
steps: [],
|
||||
};
|
||||
turns.set(turn, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
function addStep(turnNumber: number, step: number, seq: number, status: string, blocks: any[]): any {
|
||||
const turn = turns.get(turnNumber)!;
|
||||
const data = { turn: turnNumber, step, status, time: 1, blocks };
|
||||
const location = { step, start: { seq }, data: new Map([['assistant-step', data]]) };
|
||||
turn.steps.push(location);
|
||||
nodes.set(`turn-${turnNumber}-step-${step}`, {
|
||||
key: `turn-${turnNumber}-step-${step}`, kind: 'assistant-step', visibility: 'visible',
|
||||
anchorSeq: seq, location: { kind: 'step', turn, step: location }, data,
|
||||
});
|
||||
return location;
|
||||
}
|
||||
|
||||
function addToolCallNode(turnNumber: number, key: string, seq: number, location: any, callId: string, argsRaw: string): void {
|
||||
const turn = turns.get(turnNumber)!;
|
||||
const root = {
|
||||
kind: 'tool-result', seq, time: 1, callId,
|
||||
call: { name: 'read', argsRaw }, callTime: 1,
|
||||
content: [{ kind: 'text', text: '简报素材的摘录内容' }], isError: false, subCalls: [],
|
||||
};
|
||||
nodes.set(key, {
|
||||
key, kind: 'tool-call', visibility: 'visible', anchorSeq: seq,
|
||||
location: { kind: 'step', turn, step: location }, data: { root },
|
||||
});
|
||||
}
|
||||
|
||||
// --- turn 1: completed; narration sits between reasoning and the final answer.
|
||||
const turn1 = newTurn(1, 'closed', 100);
|
||||
turn1.data.set('turn-tail', { closing: { step: 1 } });
|
||||
const t1s0 = addStep(1, 0, 101, 'settled', [
|
||||
{ kind: 'reasoning', text: REASON_A },
|
||||
{ kind: 'text', text: BODY_A },
|
||||
{ kind: 'tool-call', callId: TOOL_CALL_ID, name: 'read', argsRaw: TOOL_ARGS },
|
||||
]);
|
||||
addToolCallNode(1, 'turn-1-tool-call-1', 102, t1s0, TOOL_CALL_ID, TOOL_ARGS);
|
||||
addStep(1, 1, 103, 'settled', [
|
||||
{ kind: 'reasoning', text: REASON_B },
|
||||
{ kind: 'text', text: FINAL_B },
|
||||
]);
|
||||
|
||||
// --- turn 2: open; second reasoning arrives after a process report.
|
||||
const turn2 = newTurn(2, 'open', 200);
|
||||
addStep(2, 0, 201, 'settled', [
|
||||
{ kind: 'reasoning', text: REASON_C0 },
|
||||
{ kind: 'text', text: BODY_C },
|
||||
]);
|
||||
addStep(2, 1, 202, 'running', [
|
||||
{ kind: 'reasoning', text: REASON_C1 },
|
||||
]);
|
||||
|
||||
// --- turn 3: failed turn; nothing may fold.
|
||||
newTurn(3, 'closed', 300, 'error');
|
||||
addStep(3, 0, 301, 'settled', [
|
||||
{ kind: 'reasoning', text: REASON_D },
|
||||
{ kind: 'text', text: BODY_D },
|
||||
]);
|
||||
|
||||
// --- turn 4: interrupted turn; nothing may fold.
|
||||
newTurn(4, 'closed', 400, 'interrupted');
|
||||
addStep(4, 0, 401, 'settled', [
|
||||
{ kind: 'reasoning', text: REASON_E },
|
||||
{ kind: 'text', text: BODY_E },
|
||||
]);
|
||||
|
||||
// --- turn 5: completed turn whose report is split into two narration paragraphs
|
||||
// with folded reasoning between them; the rail must bridge them after collapsing.
|
||||
const turn5 = newTurn(5, 'closed', 500);
|
||||
turn5.data.set('turn-tail', { closing: { step: 2 } });
|
||||
addStep(5, 0, 501, 'settled', [
|
||||
{ kind: 'reasoning', text: REASON_F0 },
|
||||
{ kind: 'text', text: BODY_F },
|
||||
]);
|
||||
addStep(5, 1, 502, 'settled', [
|
||||
{ kind: 'reasoning', text: REASON_G },
|
||||
{ kind: 'text', text: BODY_G },
|
||||
]);
|
||||
addStep(5, 2, 503, 'settled', [
|
||||
{ kind: 'reasoning', text: REASON_H },
|
||||
{ kind: 'text', text: FINAL_H },
|
||||
]);
|
||||
|
||||
const chat = {
|
||||
order: [
|
||||
'turn-1-step-0', 'turn-1-tool-call-1', 'turn-1-step-1',
|
||||
'turn-2-step-0', 'turn-2-step-1',
|
||||
'turn-3-step-0', 'turn-4-step-0',
|
||||
'turn-5-step-0', 'turn-5-step-1', 'turn-5-step-2',
|
||||
],
|
||||
nodes,
|
||||
timeline: { turns },
|
||||
} as unknown as ChatSnapshot;
|
||||
const sessionSnapshot = { running: true, openState: 'ready', pendingSubmissions: [], hasMore: false, loadingOlder: false };
|
||||
const sessionsSnapshot = { byId: { 'commentary-fixture': { cwd: '/fixture' } } };
|
||||
const pending = new Map();
|
||||
const host = { home: '/fixture' };
|
||||
const useReaderStore: ReaderProps['useStore'] = selector => selector(useSyncExternalStore(session.subscribe, session.getSnapshot));
|
||||
const props = {
|
||||
sessionId: 'commentary-fixture', useChat: selector => selector(chat),
|
||||
useSession: selector => selector(sessionSnapshot), useSessions: selector => selector(sessionsSnapshot),
|
||||
useSessionStatus: selector => selector(new Map([['commentary-fixture', { running: true, pendingInteraction: pending.get('commentary-fixture'), completionUnread: false }]])),
|
||||
useStore: useReaderStore, actions: session.actions, openPrefs: prefs,
|
||||
t: key => key, renderSlot: (_name: string, _owner: any, options: any) => options?.fallback ?? null,
|
||||
renderSlotChain: (_name: string, _owner: any, options: any) => options?.fallback ?? null,
|
||||
loadImage: async () => ({ data: new Uint8Array(), mediaType: 'image/png' }),
|
||||
officialImageLoader: Object.assign(async () => null, { peek: () => null }),
|
||||
officialFileMentions: () => undefined, officialPreviewFile: () => {},
|
||||
officialHost: { getSnapshot: () => host, subscribe: () => () => {} },
|
||||
fillComposer: () => true, openFile: () => {}, loadOlder: async () => {}, openView: () => {},
|
||||
} as unknown as ReaderProps;
|
||||
|
||||
Object.assign(window, {
|
||||
commentaryFixture: {
|
||||
// Exercise the same root preference the Settings panel uses.
|
||||
preference: (value: boolean) => prefs.actions.setAutoFold(value),
|
||||
state: () => session.getSnapshot(),
|
||||
text: { BODY_A, REASON_A, FINAL_B, REASON_B, TOOL_SUMMARY, BODY_C, REASON_C0, REASON_C1, BODY_D, REASON_D, BODY_E, REASON_E, BODY_F, REASON_F0, BODY_G, REASON_G, REASON_H, FINAL_H, TOOL_CALL_ID },
|
||||
},
|
||||
});
|
||||
|
||||
createRoot(document.getElementById('app')!).render(
|
||||
<div data-conversation-scroll style={{ height: '100vh', overflow: 'auto' }}><Reader {...props} /></div>,
|
||||
);
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
import React, { useMemo, useRef, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import type { ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client';
|
||||
import { ChoreographedFlow, useFlowChat } from '../src/client/ChoreographedFlow.js';
|
||||
import { presentLiveTurn } from '../src/client/live-turn.js';
|
||||
import type { LiveStep } from '../src/client/live-turn.js';
|
||||
import { Disclosure, StatusText, useMotionAllowed, useReadingScroll } from '../src/client/motion.js';
|
||||
import { ReasoningCard } from '../src/client/ReasoningCard.js';
|
||||
import { StreamMotionContext, useStreamingText } from '../src/client/streaming.js';
|
||||
import css from '../src/client/Reader.module.css';
|
||||
|
||||
const sample = '旧内容保持原位,先完成连续收拢,再确认数字,最后继续输出。This is a real component regression fixture, not a replacement animation. ';
|
||||
function Text({ step }: { step: LiveStep }) {
|
||||
const node = useFlowChat(s => 'nodeKey' in step ? s.nodes.get(step.nodeKey) : undefined);
|
||||
const source = (node?.data as { text?: string })?.text ?? '';
|
||||
const text = useStreamingText(source, true, { startedAt: 0, interrupted: false, selected: false });
|
||||
if (step.kind === 'reasoning') return <ReasoningCard step={step.step} active motion selected={false} onRead={() => {}}>
|
||||
<div data-test-text={step.key} style={{ whiteSpace: 'pre-wrap' }}>{text.text}</div>
|
||||
</ReasoningCard>;
|
||||
return <div data-reader-anchor style={{ padding: '10px 0' }} data-test-text={step.key}>{step.kind === 'body' ? sample : '工具 · 读取源文件,等待下一个步骤'}</div>;
|
||||
}
|
||||
function Demo() {
|
||||
const [n, setN] = useState(1);
|
||||
const [tail, setTail] = useState(0);
|
||||
const [auto, setAuto] = useState(true);
|
||||
const [motionSetting, setMotion] = useState(true);
|
||||
const motion = useMotionAllowed(motionSetting);
|
||||
const [urgent, setUrgent] = useState(false);
|
||||
const [expanded, setExpanded] = useState(true);
|
||||
const [open, setOpen] = useState<Record<string, boolean>>({});
|
||||
const root = useRef<HTMLDivElement>(null); const button=useRef<HTMLButtonElement>(null);
|
||||
useReadingScroll(root, motion);
|
||||
const frame = useMemo(() => {
|
||||
const steps: LiveStep[] = [];
|
||||
const nodes = new Map();
|
||||
for (let i=1; i<=n; i++) {
|
||||
steps.push({ kind: 'reasoning', key: `r${i}`, nodeKey:`r${i}`, start:0, blocks:[], step:i });
|
||||
nodes.set(`r${i}`, { data: { text: sample.repeat(i===n && n>1 ? 3 + tail : 5) } });
|
||||
if (i<n || n===1) {
|
||||
steps.push({kind:'body',key:`b${i}`,nodeKey:`b${i}`,start:1,blocks:[],step:i});
|
||||
steps.push({kind:'other',key:`t${i}`,nodeKey:`t${i}`});
|
||||
}
|
||||
}
|
||||
return {items:presentLiveTurn(steps,{status:'open'},auto),snapshot:{nodes:{get:(key:string)=>nodes.get(key)}} as unknown as ChatSnapshot};
|
||||
}, [n,tail,auto]);
|
||||
(window as any).fixture = { next:()=>setN(v=>v+1), burst:()=>{setN(v=>v+1); setTimeout(()=>setN(v=>v+2),100); setTimeout(()=>setTail(v=>v+2),180);}, stop:()=>setUrgent(true), reduce:()=>setMotion(false), reset:()=>{setN(1);setTail(0);setUrgent(false);setOpen({});setMotion(true);setAuto(true);} };
|
||||
return <><nav style={{padding:12,display:'flex',gap:12,flexWrap:'wrap'}}>
|
||||
<b>转场验收 · 真实组件 / 模拟数据</b>
|
||||
<button onClick={()=>(window as any).fixture.next()}>下一步</button>
|
||||
<button onClick={()=>(window as any).fixture.burst()}>突发三步</button>
|
||||
<button onClick={()=>(window as any).fixture.stop()}>停止</button>
|
||||
<button onClick={()=>(window as any).fixture.reset()}>重置</button>
|
||||
<button onClick={()=>setMotion(v=>!v)}>动效{motion?'开':'关'}</button>
|
||||
</nav><div data-conversation-scroll style={{height:'calc(100vh - 70px)',overflow:'auto'}}>
|
||||
<StreamMotionContext.Provider value={{enabled:motion,activatedAt:Date.now()}}>
|
||||
<div ref={root} className={css.root} data-motion={motion?'on':'off'}><div className={css.column} data-chat-flow="">
|
||||
<div className={css.toolbar}><button className={css.textButton} onClick={()=>setAuto(v=>!v)}>自动折叠{auto?'开':'关'}</button></div>
|
||||
<div className={css.turnProcessSticky}><Disclosure open={expanded} onChange={setExpanded} buttonRef={button} label={<StatusText text="正在处理" motion={motion}/>} /></div>
|
||||
<ChoreographedFlow id="fixture-flow" frame={frame} motion={motion} enabled={auto} urgent={urgent} processOpen={expanded}
|
||||
open={open} onOpenChange={(key,value)=>setOpen(s=>({...s,[key]:value}))} renderStep={step=><Text step={step}/>} />
|
||||
<div data-test-footer style={{height:72}}>输入区位置参照 · 后台数据不会被修改</div>
|
||||
</div></div></StreamMotionContext.Provider>
|
||||
</div></>;
|
||||
}
|
||||
createRoot(document.getElementById('app')!).render(<Demo />);
|
||||
|
|
@ -1,153 +0,0 @@
|
|||
/** Test-only imports resolve to the selected Harness; none enter client.js. */
|
||||
import { Context } from '@deepseek-ai/cordis';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { memo, useState } from 'react';
|
||||
import { SlotRegistry } from '@fixture/registry';
|
||||
import { createSlotRenderer } from '@fixture/renderer';
|
||||
import { apply as applyFeedback } from '@fixture/feedback';
|
||||
import { ReadRow } from '@fixture/read-row';
|
||||
import { readImageToolview } from '@fixture/read-image-row';
|
||||
import { en as conversationEn } from '@fixture/tool-locale';
|
||||
import { officialChildren, installOfficialSlots, OFFICIAL_SEATS } from '../src/client/official-slots.js';
|
||||
import { OfficialActions, OfficialTool } from '../src/client/OfficialContent.js';
|
||||
import { DeliverablesTail } from '@fixture/deliverables';
|
||||
import { zh as deliverablesZh, en as deliverablesEn } from '@fixture/deliverables-locale';
|
||||
import { FileRouteAction } from '@fixture/open-in-app-action';
|
||||
import { zh as openInAppZh, en as openInAppEn } from '@fixture/open-in-app-locale';
|
||||
import { CopyAnswer } from '../src/client/Blocks.js';
|
||||
import { MotionMarkdown } from '../src/client/word-motion.js';
|
||||
import css from '../src/client/Reader.module.css';
|
||||
|
||||
const rootContext = new Context();
|
||||
await rootContext.plugin(SlotRegistry);
|
||||
await rootContext.plugin({ name: 'bridge-fixture', inject: ['slots'], async apply(ctx: Context) {
|
||||
const slots = ctx.slots as any;
|
||||
slots.install(createSlotRenderer());
|
||||
const observations: any = { opens: [], requests: [], mounts: 0, subscriptions: 0 };
|
||||
const source = <T,>(initial: T) => {
|
||||
let value = initial;
|
||||
const listeners = new Set<() => void>();
|
||||
return { getSnapshot: () => value, subscribe: (fn: () => void) => {
|
||||
listeners.add(fn); observations.subscriptions++;
|
||||
return () => { if (listeners.delete(fn)) observations.subscriptions--; };
|
||||
}, set(next: T) { value = next; for (const fn of [...listeners]) fn(); } };
|
||||
};
|
||||
const localeSource = source({ revision: 0 });
|
||||
let language = 'zh';
|
||||
const dictionaries: Record<string, any> = { deliverables: { zh: deliverablesZh, en: deliverablesEn }, 'open-in-app': { zh: openInAppZh, en: openInAppEn }, conversation: { zh: conversationEn, en: conversationEn } };
|
||||
const locale = {
|
||||
...localeSource,
|
||||
register(ns: string, dictionary: any) { dictionaries[ns] = dictionary; return () => { delete dictionaries[ns]; }; },
|
||||
bind(ns: string) { return (key: string, values?: Record<string, any>) => {
|
||||
let text = dictionaries[ns]?.[language]?.[key] ?? dictionaries[ns]?.en?.[key] ?? key;
|
||||
for (const [name, value] of Object.entries(values ?? {})) text = text.replaceAll(`{${name}}`, String(value));
|
||||
return text;
|
||||
}; },
|
||||
};
|
||||
ctx.provide('locale', locale);
|
||||
slots.installLocale(locale);
|
||||
const messageItems = new Map();
|
||||
ctx.provide('remote', {
|
||||
messageFeedback: {
|
||||
async list(request: any) { observations.requests.push(['list', request]); return { ok: true, value: { ok: true, value: { items: [...messageItems.values()] } } }; },
|
||||
async put(request: any) {
|
||||
observations.requests.push(['put', request]);
|
||||
const item = { messageId: request.messageId, rating: request.rating, version: (messageItems.get(request.messageId)?.version ?? 0) + 1, ...request.entry };
|
||||
messageItems.set(request.messageId, item);
|
||||
return { ok: true, value: { ok: true, value: item } };
|
||||
},
|
||||
async delete(request: any) { observations.requests.push(['delete', request]); messageItems.delete(request.messageId); return { ok: true, value: { ok: true, value: { item: null } } }; },
|
||||
},
|
||||
sessionFeedback: { record: async () => { throw new Error('Unexpected session feedback'); } },
|
||||
});
|
||||
const binding = { key: 'session-a', ctx: new Context(), hooks: {}, keyedHooks: {}, props: { sessionId: 'session-a' } };
|
||||
const current = source(binding);
|
||||
slots.installScope('session', { current, bindingSource: (target: any) => source(target === binding.key ? binding : undefined), renderArea: (_b: any, props: any) => props.children });
|
||||
const toolBlock = {
|
||||
kind: 'tool-result', callId: 'read-1', call: { name: 'read', args: { file_path: '/fixture/sample.ts', offset: 12 }, argsRaw: '{"file_path":"/fixture/sample.ts","offset":12}' },
|
||||
content: [{ type: 'text', text: '<path>/fixture/sample.ts</path>\n<type>file</type>\n<content>\n12: export const value = 1;\n</content>' }], isError: false, subCalls: [], time: 100, callTime: 10,
|
||||
meta: { path: '/fixture/sample.ts', offset: 12, totalLines: 20, lines: [{ number: 12, text: 'export const value = 1;' }], lang: 'typescript' },
|
||||
};
|
||||
const host = source({ home: '/fixture' });
|
||||
const loadImage = Object.assign(async () => '/pixel.png', { peek: () => '/pixel.png' });
|
||||
const blockProps = { loadImage: async () => ({ data: new Uint8Array(), mediaType: 'image/png' }), fillComposer: () => true, cwd: '/fixture', openFile: (path: string, options?: any) => observations.opens.push({ path, options }) };
|
||||
let stopReader = () => {};
|
||||
let stopMirror = () => {};
|
||||
slots.register({ name: 'root', children: {
|
||||
'conversation.chat.assistant-actions': { kind: 'list', scope: 'session' },
|
||||
'tool.call.toolview': { kind: 'keyed', scope: 'session' },
|
||||
'conversation.chat.turnTail': { kind: 'list', scope: 'session' },
|
||||
'conversation.chat.node': { kind: 'keyed', scope: 'session', inject: { hooks: { turnData: (_s: any, value: any) => () => value } } },
|
||||
'conversation.chat.message.images': { kind: 'single', scope: 'session' },
|
||||
'conversation.chat.user.images': { kind: 'single', scope: 'session' },
|
||||
'conversation.input.overlay': { kind: 'list', scope: 'session' },
|
||||
'fixture.reader': { kind: 'single', scope: 'session' },
|
||||
} }, ({ SessionProvider, renderSlot }: any) => <SessionProvider>
|
||||
{renderSlot('fixture.reader', {}, { fallback: <div data-unmounted>Reader unloaded</div> })}
|
||||
{renderSlot('conversation.input.overlay', {})}
|
||||
</SessionProvider>);
|
||||
await ctx.plugin({ name: 'fixture-official-feedback', inject: ['slots', 'remote', 'locale'], apply: applyFeedback });
|
||||
slots.register({ name: 'tool.call.toolview', key: 'read', locale: 'conversation' }, ReadRow);
|
||||
readImageToolview.apply(ctx);
|
||||
slots.provideRoot({ hooks: { sessions: source({ byId: { 'session-a': { cwd: '/fixture' } } }) } });
|
||||
const artifact = { path: '/fixture/report.pdf', description: '演示报告', seq: 42, index: 0 };
|
||||
const presentedOpen = source({});
|
||||
const presentedHost = source({ available: true, fileManager: 'finder' });
|
||||
const changesDiff = source({});
|
||||
const changesSummary = source({});
|
||||
const showCodeDiff = source(false);
|
||||
slots.register({ name: 'conversation.chat.turnTail', id: '@deepseek-ai/dsh-client-ui-deliverables', locale: 'deliverables',
|
||||
children: { 'deliverables.file.actions': { kind: 'list', scope: 'session' } },
|
||||
inject: () => ({ hooks: { changesDiff, showCodeDiff, presentedOpen, presentedHost, changesSummary },
|
||||
loadChangesDiff: async () => {}, reloadPresentedHost: async () => {}, loadChangesSummary: async () => {},
|
||||
openPresented: async (...args: any[]) => { observations.opens.push(['presented', ...args]); },
|
||||
openChanged: async () => {}, openChangesReview: () => {},
|
||||
}),
|
||||
}, DeliverablesTail);
|
||||
slots.register({ name: 'deliverables.file.actions', id: 'open-in-app', locale: 'open-in-app' }, FileRouteAction);
|
||||
let liveDetail = source('initial');
|
||||
const storeHandle = { create: () => {
|
||||
observations.mounts++;
|
||||
const value = source(0);
|
||||
return { ...value, actions: { increment: () => value.set(value.getSnapshot() + 1) }, clearPersisted() {} };
|
||||
} };
|
||||
slots.register({ name: 'conversation.chat.node', key: 'future-widget', store: storeHandle,
|
||||
children: { 'future.detail': { kind: 'single', scope: 'session' } },
|
||||
inject: (sessionId: string, actions: any) => ({ hooks: { detail: liveDetail }, injectedSession: sessionId, increment: actions.increment }),
|
||||
}, memo(function FutureWidget({ useStore, useDetail, useTurnData, injectedSession, increment, renderSlot }: any) {
|
||||
const value = useStore((n: number) => n);
|
||||
const detail = useDetail((s: string) => s);
|
||||
const context = useTurnData();
|
||||
return <div data-memo-widget><button onClick={increment}>Count {value}</button><span>{injectedSession} / {detail} / {context}</span>{renderSlot('future.detail', {})}</div>;
|
||||
}));
|
||||
slots.register({ name: 'future.detail' }, memo(() => <span data-nested>nested official child</span>));
|
||||
|
||||
function ReaderFixture({ renderSlot, renderSlotChain }: any) {
|
||||
const official = { renderSlot, renderSlotChain, officialHost: host, officialImageLoader: loadImage, officialFileMentions: () => undefined, officialPreviewFile: blockProps.openFile, openView: (...args: any[]) => observations.opens.push(args) };
|
||||
const [text, setText] = useState('本地图片:\n\n\n\n普通正文 **加粗** 与 `sample.ts`。');
|
||||
return <main className={css.root} data-dsh-better-display="official-fixture"><div className={css.column} data-chat-flow="">
|
||||
<article className={css.answer} data-reader-answer>
|
||||
<MotionMarkdown text={text} streaming={false} enabled={false} revision={0} />
|
||||
<CopyAnswer blocks={[{ kind: 'text', text }]} extraActions={<OfficialActions official={official} messageId={'message-1' as any} />} />
|
||||
</article>
|
||||
<div data-reader-tool><OfficialTool {...blockProps} official={official} renderSlotChain={renderSlotChain} block={toolBlock as any} toolName="read" fallback={<span>fallback</span>} /></div>
|
||||
{renderSlot(OFFICIAL_SEATS.tail, { turn: { data: new Map([['deliverables', { changes: null, presented: [artifact] }]]) }, seq: 43, openFile: blockProps.openFile, readerProducedPaths: ['/fixture/sample.ts'] })}
|
||||
{renderSlot(OFFICIAL_SEATS.nodes, {}, { entryKey: 'future-widget', hookContext: 'turn-context' })}
|
||||
<button onClick={() => setText(text + '\n\n继续输出。')}>Append text</button>
|
||||
</div></main>;
|
||||
}
|
||||
function mountReader() {
|
||||
stopReader = slots.register({ name: 'fixture.reader', children: officialChildren(slots) }, ReaderFixture);
|
||||
stopMirror = installOfficialSlots(ctx);
|
||||
}
|
||||
mountReader();
|
||||
const root = createRoot(document.getElementById('app')!);
|
||||
root.render(slots.renderSlot('root', {}));
|
||||
(window as any).fixture = {
|
||||
observations, update: () => liveDetail.set('updated'),
|
||||
language: () => { language = 'en'; localeSource.set({ revision: 1 }); },
|
||||
addAction: () => slots.register({ name: 'conversation.chat.assistant-actions', id: 'future-action', order: 20 }, memo(() => <button>Future official action</button>)),
|
||||
unmount: () => { stopMirror(); stopReader(); }, mount: mountReader,
|
||||
};
|
||||
|
||||
} });
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
import React, { useMemo, useRef, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import type { ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client';
|
||||
import { StickyLane } from '../src/client/StickyLane.js';
|
||||
import { ChoreographedFlow } from '../src/client/ChoreographedFlow.js';
|
||||
import { ClosedProcessSummary } from '../src/client/ClosedProcessSummary.js';
|
||||
import { Disclosure, StatusText } from '../src/client/motion.js';
|
||||
import { presentLiveTurn } from '../src/client/live-turn.js';
|
||||
import type { LiveStep } from '../src/client/live-turn.js';
|
||||
import css from '../src/client/Reader.module.css';
|
||||
const steps:LiveStep[]=[...Array.from({length:6},(_,i):LiveStep=>({kind:'reasoning',key:`r${i}`,nodeKey:`r${i}`,step:i,start:0,blocks:[]})),{kind:'body',key:'body',nodeKey:'body',step:6,start:0,blocks:[]},{kind:'other',key:'extra',nodeKey:'extra'},{kind:'reasoning',key:'latest',nodeKey:'latest',step:7,start:0,blocks:[]},{kind:'body',key:'answer',nodeKey:'answer',step:7,start:0,blocks:[]}];
|
||||
function Fixture(){
|
||||
const [expanded,setExpanded]=useState(true),[open,setOpen]=useState<Record<string,boolean>>({}),[closed,setClosed]=useState(false);const button=useRef<HTMLButtonElement>(null);
|
||||
const frame=useMemo(()=>({items:presentLiveTurn(steps,{status:'open',reason:null,latestStep:7,closingStep:null}),snapshot:{} as ChatSnapshot}),[]);
|
||||
return <><button onClick={()=>setClosed(v=>!v)}>切换完成状态</button><div data-conversation-scroll style={{height:'calc(100vh - 32px)',overflow:'auto'}}><div className={css.root} data-dsh-better-display="fixture"><div className={css.column} data-chat-flow="">
|
||||
<StickyLane kind="toolbar" className={css.toolbar}><button className={css.textButton}>自动折叠开</button></StickyLane>
|
||||
<section className={css.turn} data-reader-turn="1"><div style={{height:240,background:'#eef2ff',alignSelf:'flex-end',width:'65%'}}>用户消息:滚动抵达顶部才吸顶。</div>
|
||||
<StickyLane kind="status" className={css.turnProcessSticky}><Disclosure open={expanded} onChange={setExpanded} buttonRef={button} label={<StatusText text="正在使用工具" motion={false}/>} /></StickyLane>
|
||||
{closed?<><ClosedProcessSummary steps={steps.slice(0,-1)} open={expanded} onChange={setExpanded} controls="body"/><div id="body" style={{height:1600}}>最终回答占位,验证完成后统计仍然吸顶。</div></>:<ChoreographedFlow id="flow" frame={frame} motion={false} enabled={false} urgent={false} processOpen={expanded} open={open} onOpenChange={(k,v)=>{setExpanded(true);setOpen(x=>({...x,[k]:v}));}} renderStep={s=>s.key==='answer'?<div style={{height:1600}}>当前输出保持完整,统计不应被推出视野。</div>:expanded?<div style={{height:s.key==='latest'?300:100}}>过程 {s.key}</div>:null}/>}
|
||||
</section><div style={{height:180}}>下一轮之前</div></div></div></div></>;
|
||||
}
|
||||
createRoot(document.getElementById('app')!).render(<Fixture/>);
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
import React, { useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { WaitingStatus } from '../src/client/WaitingStatus.js';
|
||||
import { waitingAnchor } from '../src/client/waiting-clock.js';
|
||||
function Fixture() {
|
||||
const [inputs,setInputs]=useState([{key:'u1',kind:'user',data:{time:Date.now()-300000}}]);
|
||||
const [renders,setRenders]=useState(0);
|
||||
const anchor=waitingAnchor(inputs.map(x=>x.key),key=>inputs.find(x=>x.key===key));
|
||||
return <main style={{padding:30}}><h1>等待计时回归:真实组件、模拟输入</h1>
|
||||
<button onClick={()=>setInputs(x=>[...x,{key:`s${x.length}`,kind:'steering',data:{time:Date.now()}}])}>追加 steering</button>
|
||||
<button onClick={()=>setRenders(x=>x+1)}>普通输出更新</button><span>更新次数 {renders}</span>
|
||||
<WaitingStatus anchor={anchor} label="深度求索中..."/></main>;
|
||||
}
|
||||
createRoot(document.getElementById('app')!).render(<Fixture/>);
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { test } from 'vitest';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
/** Maid-atelier / phoebe-atelier hide rule, reduced to the :has() predicate. */
|
||||
const SKIN_HIDE = '[data-conversation-scroll]:not(:has([data-chat-flow])) > [data-composer-seat]';
|
||||
|
||||
interface AttrNode {
|
||||
attrs: Record<string, string>;
|
||||
children: AttrNode[];
|
||||
}
|
||||
|
||||
function hasAttr(node: AttrNode, name: string): boolean {
|
||||
if (Object.hasOwn(node.attrs, name)) return true;
|
||||
return node.children.some(child => hasAttr(child, name));
|
||||
}
|
||||
|
||||
/** True when the skin rule would set the seat to display:none. */
|
||||
function skinHidesComposerSeat(scroll: AttrNode): boolean {
|
||||
return !hasAttr(scroll, 'data-chat-flow');
|
||||
}
|
||||
|
||||
function readerColumn(hook: boolean): AttrNode {
|
||||
return {
|
||||
attrs: hook ? { 'data-chat-flow': '' } : {},
|
||||
children: [{ attrs: { 'data-reader-turn': '1' }, children: [] }],
|
||||
};
|
||||
}
|
||||
|
||||
test('Reader source keeps the native ChatView chat-flow hook on its column', () => {
|
||||
const source = readFileSync(resolve(root, 'src/client/Reader.tsx'), 'utf8');
|
||||
const column = source.match(/<div className=\{css\.column\}[^>]*>/);
|
||||
assert.ok(column, 'Reader still renders css.column');
|
||||
assert.match(column[0], /data-chat-flow=""/);
|
||||
});
|
||||
|
||||
test('committed client bundle publishes data-chat-flow for git installs', () => {
|
||||
const client = readFileSync(resolve(root, 'lib/client.js'), 'utf8');
|
||||
assert.match(client, /"data-chat-flow":\s*""/);
|
||||
});
|
||||
|
||||
test('Reader exposes rewind chat seats and pending steering markers', () => {
|
||||
const source = readFileSync(resolve(root, 'src/client/Reader.tsx'), 'utf8');
|
||||
const seat = readFileSync(resolve(root, 'src/client/chat-seat.ts'), 'utf8');
|
||||
assert.match(seat, /data-chat-anchor-key/);
|
||||
assert.match(seat, /data-chat-flow-key/);
|
||||
assert.match(seat, /data-chat-node-key/);
|
||||
assert.match(source, /data-pending-steering/);
|
||||
assert.match(source, /data-pending-attachment-count/);
|
||||
const client = readFileSync(resolve(root, 'lib/client.js'), 'utf8');
|
||||
assert.match(client, /data-chat-anchor-key/);
|
||||
assert.match(client, /data-pending-steering/);
|
||||
});
|
||||
|
||||
test('skin empty-state hide stays off when Reader mounts inside the scrollport', () => {
|
||||
const inspectOnly: AttrNode = {
|
||||
attrs: { 'data-conversation-scroll': '' },
|
||||
children: [
|
||||
{ attrs: { 'data-reader-turn': '1' }, children: [] },
|
||||
{ attrs: { 'data-composer-seat': '' }, children: [] },
|
||||
],
|
||||
};
|
||||
const withReader: AttrNode = {
|
||||
attrs: { 'data-conversation-scroll': '' },
|
||||
children: [readerColumn(true), { attrs: { 'data-composer-seat': '' }, children: [] }],
|
||||
};
|
||||
assert.equal(skinHidesComposerSeat(inspectOnly), true, SKIN_HIDE);
|
||||
assert.equal(skinHidesComposerSeat(withReader), false, SKIN_HIDE);
|
||||
assert.equal(skinHidesComposerSeat({
|
||||
attrs: { 'data-conversation-scroll': '' },
|
||||
children: [readerColumn(false), { attrs: { 'data-composer-seat': '' }, children: [] }],
|
||||
}), true);
|
||||
});
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { test } from 'vitest';
|
||||
import { answerRowAttrs, chatSeatProps } from '../src/client/chat-seat.js';
|
||||
|
||||
test('answer rows publish the official assistant-step marker dsh-btw looks for', () => {
|
||||
const attrs = answerRowAttrs('assistant-step:turn-1:0', 2, 1);
|
||||
assert.equal(attrs['data-chat-flow-kind'], 'assistant-step');
|
||||
assert.equal(attrs['data-chat-node-key'], 'assistant-step:turn-1:0');
|
||||
assert.equal(attrs['data-chat-flow-key'], 'assistant-step:turn-1:0#2', 'flow keys stay unique per rendered part');
|
||||
assert.equal(attrs['data-chat-turn'], '1');
|
||||
});
|
||||
|
||||
test('answer rows do not publish the official rewind anchor', () => {
|
||||
const attrs = answerRowAttrs('assistant-step:turn-2:1', 0, 2);
|
||||
assert.equal('data-chat-anchor-key' in attrs, false, 'rewind hiding stays owned by rewind-cut.ts');
|
||||
assert.equal(attrs['data-chat-flow-kind'], 'assistant-step');
|
||||
});
|
||||
|
||||
test('user bubbles keep their existing official seat attributes', () => {
|
||||
const attrs = chatSeatProps('user', 'user:turn-1');
|
||||
assert.deepEqual(attrs, {
|
||||
'data-chat-anchor-key': 'user:turn-1',
|
||||
'data-chat-flow-key': 'user:turn-1',
|
||||
'data-chat-node-key': 'user:turn-1',
|
||||
'data-chat-flow-kind': 'user',
|
||||
});
|
||||
});
|
||||
|
||||
test('the answer article actually carries the row attributes', async () => {
|
||||
const source = await readFile(new URL('../src/client/AssistantNode.tsx', import.meta.url), 'utf8');
|
||||
const article = source.match(/<article className=\{css\.answer\}[\s\S]*?>/u)?.[0] ?? '';
|
||||
assert.match(article, /\{\.\.\.answerRowAttrs\(nodeKey, part\.start, data\.turn\)\}/u);
|
||||
assert.match(article, /data-reader-body/u, 'reader attributes must stay');
|
||||
assert.match(article, /data-reader-key=\{nodeKey\}/u);
|
||||
});
|
||||
|
|
@ -0,0 +1,228 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { test, vi } from 'vitest';
|
||||
import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import { SlotCore } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import { CHAT_VIEW_ID, CHAT_VIEW_PRIORITY, hideDuplicateChatTabs, retireHostedChatView, type ViewLedger } from '../src/client/chat-view-seat.js';
|
||||
|
||||
const CHAT_FLOW = 'conversation.chat.flow';
|
||||
|
||||
/** The projection `viewTabs()` uses: raw ledger rows, skipping entries without an id. */
|
||||
const tabIds = (core: SlotCore): string[] => core.entries('conversation.view')
|
||||
.flatMap(entry => entry.options.id === undefined ? [] : [entry.options.id]);
|
||||
|
||||
const chatIds = (core: SlotCore): string[] => core.entries('conversation.view')
|
||||
.flatMap(entry => entry.options.id === CHAT_VIEW_ID ? [entry.options.id] : []);
|
||||
|
||||
const ledgerOf = (core: SlotCore): ViewLedger => ({
|
||||
entries: key => core.entries(key) as readonly StoredEntry[],
|
||||
register: (options, component) => core.register(options as never, component),
|
||||
subscribe: (key, listener) => core.subscribe(key, listener),
|
||||
});
|
||||
|
||||
function viewsSlot(core: SlotCore): void {
|
||||
core.register({ name: 'root', children: {
|
||||
'conversation.view': { kind: 'list', scope: 'session' },
|
||||
} }, () => null);
|
||||
}
|
||||
|
||||
/** Simulates the official ChatView entry: a child declaration and a store seat. */
|
||||
function registerChatView(core: SlotCore, component: () => null) {
|
||||
return core.register({
|
||||
name: 'conversation.view',
|
||||
id: CHAT_VIEW_ID,
|
||||
order: 0,
|
||||
children: { [CHAT_FLOW]: { kind: 'single', scope: 'session' } },
|
||||
store: {} as never,
|
||||
}, component);
|
||||
}
|
||||
|
||||
function viewEntry(id: string, priority: number | undefined, component: unknown): StoredEntry {
|
||||
return { component, options: { id, ...(priority === undefined ? {} : { priority }) } } as StoredEntry;
|
||||
}
|
||||
|
||||
/** A row whose `options.id` setter is a no-op, as on hosts that ignore the primary hide. */
|
||||
function stubbornEntry(component: unknown): StoredEntry {
|
||||
const options = {} as StoredEntry['options'];
|
||||
Object.defineProperty(options, 'id', { get: () => CHAT_VIEW_ID, set: () => {}, enumerable: true, configurable: true });
|
||||
return { component, options } as StoredEntry;
|
||||
}
|
||||
|
||||
function fakeLedger(rows: readonly StoredEntry[], copyArrays = false): ViewLedger {
|
||||
const listeners = new Set<() => void>();
|
||||
return {
|
||||
entries: () => copyArrays ? [...rows] : rows,
|
||||
register: () => () => {},
|
||||
subscribe: (_name, listener) => {
|
||||
listeners.add(listener);
|
||||
return () => { listeners.delete(listener); };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('shadowing keeps the official row live and removes only its tab', () => {
|
||||
const core = new SlotCore();
|
||||
viewsSlot(core);
|
||||
const OfficialChatView = () => null;
|
||||
const ReaderSeat = () => null;
|
||||
const disposeOfficial = registerChatView(core, OfficialChatView);
|
||||
const disposeReader = core.register({
|
||||
name: 'conversation.view',
|
||||
id: CHAT_VIEW_ID,
|
||||
priority: CHAT_VIEW_PRIORITY,
|
||||
order: 0,
|
||||
}, ReaderSeat);
|
||||
|
||||
const ledger = ledgerOf(core);
|
||||
const restore = retireHostedChatView(ledger);
|
||||
|
||||
// One 对话 tab; the reader wins the render seat.
|
||||
assert.deepEqual(tabIds(core), [CHAT_VIEW_ID]);
|
||||
assert.equal(core.entries('conversation.view').filter(entry => entry.component === OfficialChatView).length, 1);
|
||||
assert.equal(core.entriesOfSlot('conversation.view').filter(entry => entry.options.id === CHAT_VIEW_ID)[0].component, ReaderSeat);
|
||||
// The official row still owns its child declaration.
|
||||
assert.equal(core.spec(CHAT_FLOW)?.kind, 'single');
|
||||
|
||||
const before = core.entries('conversation.view').indexOf(
|
||||
core.entries('conversation.view').find(entry => entry.component === OfficialChatView)!,
|
||||
);
|
||||
restore();
|
||||
const after = core.entries('conversation.view').indexOf(
|
||||
core.entries('conversation.view').find(entry => entry.component === OfficialChatView)!,
|
||||
);
|
||||
assert.equal(after, before, 'restore must keep the official row in place');
|
||||
assert.equal(core.entries('conversation.view').find(entry => entry.component === OfficialChatView)?.options.id, CHAT_VIEW_ID);
|
||||
|
||||
disposeReader();
|
||||
disposeOfficial();
|
||||
});
|
||||
|
||||
/** Slot subscriptions flush on a microtask; settle a couple of turns. */
|
||||
const settle = async (): Promise<void> => {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 0));
|
||||
};
|
||||
|
||||
test('official teardown while hidden still releases child slots and allows re-registration', async () => {
|
||||
const core = new SlotCore();
|
||||
viewsSlot(core);
|
||||
const OfficialChatView = () => null;
|
||||
const disposeOfficial = registerChatView(core, OfficialChatView);
|
||||
const disposeReader = core.register({
|
||||
name: 'conversation.view',
|
||||
id: CHAT_VIEW_ID,
|
||||
priority: CHAT_VIEW_PRIORITY,
|
||||
order: 0,
|
||||
}, () => null);
|
||||
const ledger = ledgerOf(core);
|
||||
const restore = retireHostedChatView(ledger);
|
||||
|
||||
// ui-chat unloads while the reader shadows it. The official disposer must
|
||||
// still release its declared child (the old splice made it early-return).
|
||||
disposeOfficial();
|
||||
assert.equal(core.spec(CHAT_FLOW), undefined);
|
||||
|
||||
// ui-chat registers again (HMR): no "already declared" and the seat re-hides it.
|
||||
const Again = () => null;
|
||||
assert.doesNotThrow(() => { registerChatView(core, Again); });
|
||||
assert.equal(core.spec(CHAT_FLOW)?.kind, 'single');
|
||||
await settle();
|
||||
assert.deepEqual(tabIds(core), [CHAT_VIEW_ID], 'a re-registered ChatView row must be hidden again');
|
||||
assert.equal(core.entries('conversation.view').filter(entry => entry.component === Again).length, 1);
|
||||
|
||||
restore();
|
||||
assert.equal(core.entries('conversation.view').find(entry => entry.component === Again)?.options.id, CHAT_VIEW_ID);
|
||||
disposeReader();
|
||||
});
|
||||
|
||||
test('repeat retirement and restore are idempotent', () => {
|
||||
const core = new SlotCore();
|
||||
viewsSlot(core);
|
||||
const OfficialChatView = () => null;
|
||||
const disposeOfficial = registerChatView(core, OfficialChatView);
|
||||
const disposeReader = core.register({
|
||||
name: 'conversation.view',
|
||||
id: CHAT_VIEW_ID,
|
||||
priority: CHAT_VIEW_PRIORITY,
|
||||
order: 0,
|
||||
}, () => null);
|
||||
|
||||
const ledger = ledgerOf(core);
|
||||
const first = retireHostedChatView(ledger);
|
||||
const second = retireHostedChatView(ledger);
|
||||
|
||||
first();
|
||||
assert.equal(core.entries('conversation.view').find(entry => entry.component === OfficialChatView)?.options.id, CHAT_VIEW_ID);
|
||||
first();
|
||||
second();
|
||||
assert.equal(core.entries('conversation.view').filter(entry => entry.component === OfficialChatView).length, 1);
|
||||
assert.deepEqual(tabIds(core), [CHAT_VIEW_ID, CHAT_VIEW_ID]);
|
||||
|
||||
disposeReader();
|
||||
disposeOfficial();
|
||||
});
|
||||
|
||||
test('entries that cannot be hidden remain owned by the host', () => {
|
||||
const rows = Object.freeze([stubbornEntry('official'), viewEntry(CHAT_VIEW_ID, CHAT_VIEW_PRIORITY, 'reader')]);
|
||||
for (const copyArrays of [false, true]) {
|
||||
const restore = retireHostedChatView(fakeLedger(rows, copyArrays));
|
||||
assert.equal(rows[0]?.options.id, CHAT_VIEW_ID);
|
||||
assert.equal(rows.length, 2);
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('the header hides only repeated chat tabs and removes its marks on teardown', () => {
|
||||
const tab = (textContent: string) => ({
|
||||
textContent, hidden: false,
|
||||
toggleAttribute(_name: string, hidden: boolean) { this.hidden = hidden; },
|
||||
removeAttribute() { this.hidden = false; },
|
||||
});
|
||||
const first = tab('对话');
|
||||
const duplicate = tab('Chat');
|
||||
const gallery = tab('画廊');
|
||||
const another = tab('对话');
|
||||
const doc = {
|
||||
documentElement: {},
|
||||
querySelectorAll: (selector: string) => selector.startsWith('[data-conversation-tabs]')
|
||||
? [{ querySelectorAll: () => [first, duplicate, gallery] }, { querySelectorAll: () => [another] }]
|
||||
: [duplicate],
|
||||
} as unknown as Document;
|
||||
vi.stubGlobal('MutationObserver', class { observe() {} disconnect() {} });
|
||||
try {
|
||||
const restore = hideDuplicateChatTabs(doc);
|
||||
assert.deepEqual([first.hidden, duplicate.hidden, gallery.hidden, another.hidden], [false, true, false, false]);
|
||||
restore();
|
||||
assert.equal(duplicate.hidden, false);
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
test('visibility changes notify View subscribers', async () => {
|
||||
const core = new SlotCore();
|
||||
viewsSlot(core);
|
||||
const disposeOfficial = registerChatView(core, () => null);
|
||||
const disposeReader = core.register({
|
||||
name: 'conversation.view',
|
||||
id: CHAT_VIEW_ID,
|
||||
priority: CHAT_VIEW_PRIORITY,
|
||||
order: 0,
|
||||
}, () => null);
|
||||
|
||||
const seen: string[][] = [];
|
||||
const unsubscribe = core.subscribe('conversation.view', () => { seen.push(tabIds(core)); });
|
||||
|
||||
const ledger = ledgerOf(core);
|
||||
const restore = retireHostedChatView(ledger);
|
||||
await settle();
|
||||
assert.equal(seen.at(-1)?.filter(id => id === CHAT_VIEW_ID).length, 1, 'subscribers must see one 对话 tab');
|
||||
|
||||
restore();
|
||||
await settle();
|
||||
assert.equal(seen.at(-1)?.filter(id => id === CHAT_VIEW_ID).length, 2, 'restore must show the official tab again');
|
||||
|
||||
unsubscribe();
|
||||
disposeReader();
|
||||
disposeOfficial();
|
||||
});
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
import { test } from 'vitest'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import vm from 'node:vm'
|
||||
|
||||
test('lib/client.js registers the merged package factory with the module loader', () => {
|
||||
const code = readFileSync(new URL('../../lib/client.js', import.meta.url), 'utf8')
|
||||
assert.ok(!/^export /m.test(code), 'loader file must not contain ESM export syntax')
|
||||
|
||||
let registered: any
|
||||
const window = {
|
||||
__ModuleLoader__: {
|
||||
load: (entry: any) => { registered = entry },
|
||||
},
|
||||
}
|
||||
vm.runInNewContext(code, {
|
||||
window,
|
||||
document: undefined,
|
||||
console,
|
||||
setInterval,
|
||||
clearInterval,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
})
|
||||
assert.ok(registered, 'expected a __ModuleLoader__.load call')
|
||||
assert.equal(registered.id, 'dsh-better-chat')
|
||||
assert.equal(typeof registered.factory, 'function', 'factory must be a function')
|
||||
|
||||
// 合并后:一个 client 产物同时带阅读视图与聊天增强。
|
||||
assert.match(code, /data-approval-key/, 'approval card routing must be bundled')
|
||||
assert.match(code, /data-better-chat-update/, 'store update buttons must be bundled')
|
||||
assert.match(code, /conversation\.view/, 'reader view slot registration must be bundled')
|
||||
|
||||
// 只允许共享模块表里的 require,避免打包进第二份 React/Cordis。
|
||||
const requires = [...code.matchAll(/require\("([^"]+)"\)/g)].map((match) => match[1])
|
||||
const allowed = new Set([
|
||||
'react',
|
||||
'react/jsx-runtime',
|
||||
'react-dom',
|
||||
'react-dom/client',
|
||||
'@deepseek-ai/cordis',
|
||||
'zod',
|
||||
'@tanstack/react-virtual',
|
||||
'@deepseek-ai/dsh-client-store',
|
||||
'@deepseek-ai/dsh-client-ui-slots',
|
||||
'@deepseek-ai/dsh-client-ui-primitives',
|
||||
'@deepseek-ai/dsh-client-ui-dockkit',
|
||||
])
|
||||
for (const id of requires) assert.ok(allowed.has(id), `unexpected runtime require: ${id}`)
|
||||
})
|
||||
|
|
@ -4,13 +4,16 @@ import { test } from 'vitest'
|
|||
import {
|
||||
AUTO_REVIEW_PRESET,
|
||||
FULL_ACCESS_PRESET,
|
||||
HANDLED_STORAGE_KEY,
|
||||
currentPreset,
|
||||
installPermissionPolicy,
|
||||
isAutoSwitchEligible,
|
||||
isFullAccessLabel,
|
||||
liveSessions,
|
||||
pruneFullAccess,
|
||||
shouldAutoSwitch,
|
||||
} from '../../src/client/chat/permission-policy.ts'
|
||||
import { apply as applyHost, applyHostAutoReview, isFreshAutoEligibleSession } from '../../src/host.ts'
|
||||
|
||||
;(globalThis as any).MutationObserver = class { observe() {} disconnect() {} }
|
||||
|
||||
|
|
@ -57,10 +60,26 @@ test('pruneFullAccess removes full-access from selects, listboxes and menus', ()
|
|||
assert.deepEqual(items.map((o) => o.removed), [false, true, true, false])
|
||||
})
|
||||
|
||||
test('liveSessions: keys+binding, list fallback, hostile shapes', () => {
|
||||
test('liveSessions: keys+binding, ClientSessions list.getSnapshot/scopes, list() fallback, hostile shapes', () => {
|
||||
const live = { sessionId: 's1' }
|
||||
const viaKeys = liveSessions({ keys: () => ['s1', 's2'], binding: (id: string) => (id === 's1' ? { session: live } : undefined) })
|
||||
assert.deepEqual(viaKeys.map((x) => x.id), ['s1'])
|
||||
|
||||
const live2 = { sessionId: 's2' }
|
||||
const viaClientSessions = liveSessions({
|
||||
list: { getSnapshot: () => ({ ids: ['s1', 's2'], byId: { s1: { id: 's1' }, s2: { id: 's2' } } }) },
|
||||
binding: (id: string) => (id === 's2' ? { session: live2 } : undefined),
|
||||
})
|
||||
assert.deepEqual(viaClientSessions.map((x) => x.id), ['s2'])
|
||||
|
||||
const scopes = new Map([['s3', { binding: { session: { sessionId: 's3' } } }]])
|
||||
const viaScopes = liveSessions({
|
||||
scopes,
|
||||
list: { getSnapshot: () => ({ ids: [], byId: {} }) },
|
||||
binding: (id: string) => scopes.get(id)?.binding,
|
||||
})
|
||||
assert.deepEqual(viaScopes.map((x) => x.id), ['s3'])
|
||||
|
||||
const viaList = liveSessions({ list: () => [{ sessionId: 'a' }, { nope: 1 }] })
|
||||
assert.deepEqual(viaList.map((x) => x.id), ['a'])
|
||||
assert.deepEqual(liveSessions({ keys: () => { throw new Error('x') } }), [])
|
||||
|
|
@ -68,9 +87,11 @@ test('liveSessions: keys+binding, list fallback, hostile shapes', () => {
|
|||
assert.deepEqual(liveSessions(42), [])
|
||||
})
|
||||
|
||||
test('currentPreset reads the permissions projection defensively', () => {
|
||||
const live = { projections: { faceOf: (n: string) => (n === 'permissions' ? { getSnapshot: () => 'workspace-write' } : undefined) } }
|
||||
assert.equal(currentPreset(live), 'workspace-write')
|
||||
test('currentPreset reads both string and { currentValue } permissions projections defensively', () => {
|
||||
const strLive = { projections: { faceOf: (n: string) => (n === 'permissions' ? { getSnapshot: () => 'workspace-write' } : undefined) } }
|
||||
assert.equal(currentPreset(strLive), 'workspace-write')
|
||||
const objLive = { projections: { faceOf: (n: string) => (n === 'permissions' ? { getSnapshot: () => ({ currentValue: 'auto' }) } : undefined) } }
|
||||
assert.equal(currentPreset(objLive), 'auto')
|
||||
assert.equal(currentPreset({}), undefined)
|
||||
assert.equal(currentPreset({ projections: { faceOf: () => { throw new Error('x') } } }), undefined)
|
||||
})
|
||||
|
|
@ -88,23 +109,173 @@ function fakeTimers() {
|
|||
}
|
||||
}
|
||||
|
||||
test('policy: page load and refresh never change existing session permissions', async () => {
|
||||
const timers = fakeTimers()
|
||||
function fakeLive(preset: string | { currentValue: string }, fail = false, blank?: boolean) {
|
||||
const calls: string[] = []
|
||||
const live = { projections: { faceOf: () => ({ getSnapshot: () => 'read-only' }) }, command: async (text: string) => { calls.push(text); return { ok: true } } }
|
||||
const sessions = { keys: () => ['s1'], binding: () => ({ session: live }) }
|
||||
return {
|
||||
calls,
|
||||
...(blank === undefined ? {} : { getSnapshot: () => ({ blank }) }),
|
||||
projections: { faceOf: () => ({ getSnapshot: () => preset }) },
|
||||
async command(text: string) {
|
||||
calls.push(text)
|
||||
if (fail) return { ok: false, error: { code: 'unavailable' } }
|
||||
return { ok: true, value: { matched: true } }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function fakeStorage() {
|
||||
const map = new Map<string, string>()
|
||||
return {
|
||||
getItem: (k: string) => map.get(k) ?? null,
|
||||
setItem: (k: string, v: string) => { map.set(k, v) },
|
||||
}
|
||||
}
|
||||
|
||||
test('policy: first sight of a new blank session switches it to auto once', async () => {
|
||||
const timers = fakeTimers()
|
||||
const live = fakeLive({ currentValue: 'workspace-write' }, false, true)
|
||||
const sessions = {
|
||||
list: { getSnapshot: () => ({ ids: ['s1'], byId: { s1: { id: 's1', blank: true } } }) },
|
||||
binding: (id: string) => (id === 's1' ? { session: live } : undefined),
|
||||
}
|
||||
const doc = { body: {}, querySelectorAll: () => [] }
|
||||
const dispose = installPermissionPolicy(doc as any, () => sessions, timers as any)
|
||||
await timers.runIntervals()
|
||||
await timers.runIntervals()
|
||||
assert.deepEqual(calls, [], '已有只读会话不能被自动切到 auto')
|
||||
assert.deepEqual(live.calls, ['/permission auto'])
|
||||
dispose()
|
||||
assert.equal(timers.size, 0)
|
||||
})
|
||||
|
||||
// A second mount (the page reload path) must not touch it either.
|
||||
test('policy: already-auto sessions are left alone; failures are not retried', async () => {
|
||||
const timers = fakeTimers()
|
||||
const autoLive = fakeLive('auto')
|
||||
const failLive = fakeLive('read-only', true)
|
||||
const sessions = {
|
||||
keys: () => ['a', 'b'],
|
||||
binding: (id: string) => ({ session: id === 'a' ? autoLive : failLive }),
|
||||
}
|
||||
const doc = { body: {}, querySelectorAll: () => [] }
|
||||
const dispose = installPermissionPolicy(doc as any, () => sessions, timers as any)
|
||||
await timers.runIntervals()
|
||||
await timers.runIntervals()
|
||||
assert.deepEqual(autoLive.calls, [])
|
||||
assert.deepEqual(failLive.calls, ['/permission auto'])
|
||||
dispose()
|
||||
})
|
||||
|
||||
test('policy: existing non-blank sessions and refreshed handled sessions are never overwritten', async () => {
|
||||
const localStorage = fakeStorage()
|
||||
const doc = { body: {}, defaultView: { localStorage }, querySelectorAll: () => [] }
|
||||
|
||||
// 1) An existing conversation (blank: false) is never switched on load.
|
||||
const existingLive = fakeLive({ currentValue: 'read-only' }, false, false)
|
||||
// 2) A brand-new blank session is switched once on first sight.
|
||||
let blankPreset = 'workspace-write'
|
||||
const blankCalls: string[] = []
|
||||
const blankLive = {
|
||||
getSnapshot: () => ({ blank: true }),
|
||||
projections: { faceOf: () => ({ getSnapshot: () => ({ currentValue: blankPreset }) }) },
|
||||
async command(text: string) {
|
||||
blankCalls.push(text)
|
||||
blankPreset = 'auto'
|
||||
return { ok: true, value: { matched: true } }
|
||||
},
|
||||
}
|
||||
const sessions = {
|
||||
list: {
|
||||
getSnapshot: () => ({
|
||||
ids: ['existing-1', 'blank-1'],
|
||||
byId: {
|
||||
'existing-1': { id: 'existing-1', blank: false },
|
||||
'blank-1': { id: 'blank-1', blank: true },
|
||||
},
|
||||
}),
|
||||
},
|
||||
binding: (id: string) => {
|
||||
if (id === 'existing-1') return { session: existingLive }
|
||||
if (id === 'blank-1') return { session: blankLive }
|
||||
return undefined
|
||||
},
|
||||
}
|
||||
|
||||
const timers1 = fakeTimers()
|
||||
const dispose1 = installPermissionPolicy(doc as any, () => sessions, timers1 as any)
|
||||
await timers1.runIntervals()
|
||||
assert.deepEqual(existingLive.calls, [], '已有对话(blank=false)不得被自动切到 auto')
|
||||
assert.deepEqual(blankCalls, ['/permission auto'], '新建空白会话首次见到时应切到 auto')
|
||||
dispose1()
|
||||
|
||||
// User manually switches blank-1 to read-only, then reloads the page (second mount).
|
||||
blankPreset = 'read-only'
|
||||
assert.ok(localStorage.getItem(HANDLED_STORAGE_KEY)?.includes('blank-1'))
|
||||
const timers2 = fakeTimers()
|
||||
const dispose2 = installPermissionPolicy(doc as any, () => sessions, timers2 as any)
|
||||
await timers2.runIntervals()
|
||||
assert.deepEqual(calls, [], '刷新后再次挂载也不能改权限')
|
||||
assert.deepEqual(blankCalls, ['/permission auto'], '刷新后不得覆盖用户手动改过的会话权限')
|
||||
assert.equal(isAutoSwitchEligible('sub-1', {}, { list: { getSnapshot: () => ({ byId: { 'sub-1': { origin: 'subagent' } } }) } }), false)
|
||||
dispose2()
|
||||
})
|
||||
|
||||
test('host auto-review default: switches fresh blank sessions and skips used/subagent/manual sessions', () => {
|
||||
assert.equal(isFreshAutoEligibleSession({ header: { id: 's1' }, snapshotEvents: () => [{ type: 'permission/preset', data: { preset: 'workspace-write' } }] }), true)
|
||||
assert.equal(isFreshAutoEligibleSession({ header: { id: 's2', origin: 'subagent' }, snapshotEvents: () => [] }), false)
|
||||
assert.equal(isFreshAutoEligibleSession({ header: { id: 's3', isSeeded: true }, snapshotEvents: () => [] }), false)
|
||||
assert.equal(isFreshAutoEligibleSession({ header: { id: 's4' }, snapshotEvents: () => [{ type: 'turn/start' }] }), false)
|
||||
assert.equal(isFreshAutoEligibleSession({ header: { id: 's5' }, snapshotEvents: () => [{ type: 'command/run', data: { name: 'permission' } }] }), false)
|
||||
|
||||
const setCalls: Array<[string, string]> = []
|
||||
let catalogNames = ['read-only', 'workspace-write']
|
||||
let currentPresetVal = 'workspace-write'
|
||||
const listeners = new Map<string, (payload?: any) => void>()
|
||||
const session1 = {
|
||||
id: 'fresh-1',
|
||||
header: { id: 'fresh-1' },
|
||||
snapshotEvents: () => [{ type: 'permission/preset', data: { preset: 'workspace-write' } }],
|
||||
}
|
||||
const permissionPresets = {
|
||||
get names() { return catalogNames },
|
||||
current: () => currentPresetVal,
|
||||
set: (s: any, name: string) => {
|
||||
setCalls.push([s.id, name])
|
||||
currentPresetVal = name
|
||||
},
|
||||
}
|
||||
const agents = { list: () => [{ session: session1 }] }
|
||||
|
||||
// Cordis 只在 inject 声明的服务可用时才把带服务的上下文交给回调;这里同步调用
|
||||
// 即可复现实机行为。直接读 ctx.permissionPresets 会在真实 Context 上抛
|
||||
// `cannot get property "permissionPresets" without inject`。
|
||||
const ctxStub: any = {
|
||||
permissionPresets,
|
||||
agents,
|
||||
effect(run: () => void) { run() },
|
||||
on(event: string, fn: (payload?: any) => void) {
|
||||
listeners.set(event, fn)
|
||||
return () => { listeners.delete(event) }
|
||||
},
|
||||
inject(_deps: string[], callback: (child: any) => void) { callback(ctxStub) },
|
||||
}
|
||||
applyHost(ctxStub, { flags: { readerEnabled: false } })
|
||||
|
||||
// Before 'auto' is registered in permissionPresets.names, nothing is switched yet.
|
||||
assert.deepEqual(setCalls, [])
|
||||
|
||||
// Once auto-review registers 'auto' and emits catalog-changed, fresh-1 is switched to 'auto'.
|
||||
catalogNames = ['read-only', 'workspace-write', 'auto']
|
||||
listeners.get('permission-presets/catalog-changed')?.()
|
||||
assert.deepEqual(setCalls, [['fresh-1', 'auto']])
|
||||
|
||||
// User later switches fresh-1 to read-only; another catalog-changed or agent/created does not overwrite it.
|
||||
currentPresetVal = 'read-only'
|
||||
listeners.get('permission-presets/catalog-changed')?.()
|
||||
assert.deepEqual(setCalls, [['fresh-1', 'auto']])
|
||||
|
||||
// A new agent/created with a fresh session is switched immediately.
|
||||
const session2 = { id: 'fresh-2', header: { id: 'fresh-2' }, snapshotEvents: () => [] }
|
||||
listeners.get('agent/created')?.({ agent: { session: session2 } })
|
||||
assert.deepEqual(setCalls, [['fresh-1', 'auto'], ['fresh-2', 'auto']])
|
||||
|
||||
// Direct helper coverage when already auto.
|
||||
assert.equal(applyHostAutoReview(permissionPresets, session2, new Set()), false)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,31 +0,0 @@
|
|||
<!doctype html>
|
||||
<meta charset="utf-8">
|
||||
<title>Reader chat-flow hook vs maid-atelier composer hide</title>
|
||||
<style>
|
||||
[data-conversation-scroll] { display: flex; flex-direction: column; min-height: 120px; }
|
||||
[data-composer-seat] { display: flex; min-height: 28px; }
|
||||
/* Exact maid-atelier / phoebe-atelier empty-state hide (issue #10). */
|
||||
[data-phase="active"]
|
||||
[data-conversation-scroll]:not(:has([data-chat-flow]))
|
||||
> [data-composer-seat] { display: none; }
|
||||
</style>
|
||||
<body>
|
||||
<section id="inspect" data-phase="active">
|
||||
<div data-conversation-scroll>
|
||||
<div data-dsh-better-display="fixture"><section data-reader-turn="1">turn</section></div>
|
||||
<div data-composer-seat id="inspect-seat">composer</div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="reader" data-phase="active">
|
||||
<div data-conversation-scroll>
|
||||
<div data-dsh-better-display="0.1.1">
|
||||
<div data-chat-flow=""><section data-reader-turn="1">turn</section></div>
|
||||
</div>
|
||||
<div data-composer-seat id="reader-seat">composer</div>
|
||||
</div>
|
||||
</section>
|
||||
<script>
|
||||
document.body.dataset.inspectDisplay = getComputedStyle(document.getElementById('inspect-seat')).display;
|
||||
document.body.dataset.readerDisplay = getComputedStyle(document.getElementById('reader-seat')).display;
|
||||
</script>
|
||||
</body>
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
import { useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { StickyLane, usePublishedHeight } from '../../src/client/StickyLane.js';
|
||||
|
||||
function Measured({ id, property, height }: { id: string; property: string; height: number }) {
|
||||
const ref = usePublishedHeight(property);
|
||||
return <div ref={ref} id={id} style={{ height }}>{id}</div>;
|
||||
}
|
||||
|
||||
function SummaryReader({ id, height, show }: { id: string; height: number; show: boolean }) {
|
||||
return <div data-dsh-better-display={id} id={`root-${id}`}>
|
||||
<section data-reader-turn="1" id={`turn-${id}`}>
|
||||
{show && <Measured id={`row-${id}`} property="--reader-summary-height" height={height} />}
|
||||
</section>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function App() {
|
||||
const [height, setHeight] = useState(52);
|
||||
const [show, setShow] = useState(true);
|
||||
return <>
|
||||
<button id="grow" type="button" onClick={() => setHeight(86)}>grow</button>
|
||||
<button id="drop" type="button" onClick={() => setShow(false)}>drop</button>
|
||||
<SummaryReader id="a" height={height} show={show} />
|
||||
<SummaryReader id="b" height={52} show />
|
||||
<div data-dsh-better-display="short" id="root-short">
|
||||
<section data-reader-turn="1" id="turn-short">
|
||||
<Measured id="row-short" property="--reader-status-height" height={38} />
|
||||
</section>
|
||||
</div>
|
||||
<div data-dsh-better-display="toolbar" id="root-toolbar">
|
||||
<StickyLane kind="toolbar" className="toolbarProbe">
|
||||
<button id="toolbar-button" type="button" style={{ height: 12, padding: 0, border: 0 }}>开</button>
|
||||
</StickyLane>
|
||||
</div>
|
||||
<div data-dsh-better-display="status" id="root-status">
|
||||
<section data-reader-turn="1" id="turn-status">
|
||||
<StickyLane kind="status" className="statusProbe">
|
||||
<span style={{ display: 'block', height: 12 }}>用时</span>
|
||||
</StickyLane>
|
||||
</section>
|
||||
</div>
|
||||
</>;
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('app')!).render(<App />);
|
||||
|
|
@ -1,234 +0,0 @@
|
|||
import { Context } from '@deepseek-ai/cordis';
|
||||
import * as React from 'react';
|
||||
import * as Primitives from '@deepseek-ai/dsh-client-ui-primitives';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { flushSync } from 'react-dom';
|
||||
import { SlotRegistry } from '@fixture/registry';
|
||||
import { createSlotRenderer } from '@fixture/renderer';
|
||||
import { Reader } from '../../src/client/Reader.js';
|
||||
import { createReaderStore } from '../../src/client/store.js';
|
||||
import { installOfficialSlots, officialChildren, OFFICIAL_SEATS } from '../../src/client/official-slots.js';
|
||||
import type { ReaderProps } from '../../src/client/types.js';
|
||||
|
||||
// Real Reader, registry, scope binding and slot renderer. Only session data is synthetic.
|
||||
function equal(actual: unknown, expected: unknown) {
|
||||
if (!Object.is(actual, expected)) throw new Error(`Expected ${String(expected)}, got ${String(actual)}`);
|
||||
}
|
||||
const assert = {
|
||||
equal,
|
||||
ok(value: unknown) { equal(Boolean(value), true); },
|
||||
deepEqual(actual: unknown, expected: unknown) { equal(JSON.stringify(actual), JSON.stringify(expected)); },
|
||||
};
|
||||
async function verify() {
|
||||
const root = new Context();
|
||||
await root.plugin(SlotRegistry);
|
||||
let run = async () => {};
|
||||
await root.plugin({ name: 'reader-user-test', inject: ['slots'], async apply(ctx: Context) {
|
||||
const slots = ctx.slots as any;
|
||||
slots.install(createSlotRenderer());
|
||||
const source = <T,>(value: T) => ({ getSnapshot: () => value, subscribe: () => () => {} });
|
||||
const binding = { key: 'session-users', ctx: new Context(), hooks: {}, keyedHooks: {}, props: { sessionId: 'session-users' } };
|
||||
slots.installScope('session', {
|
||||
current: source(binding), bindingSource: () => source(binding), renderArea: (_: unknown, props: any) => props.children,
|
||||
});
|
||||
slots.installLocale({ ...source({}), bind: () => (key: string) => key });
|
||||
const turn = { turn: 1, status: 'closed', start: { seq: 1, time: 1 },
|
||||
end: { time: 2, data: { reason: { kind: 'completed' } } }, data: new Map(), steps: [] };
|
||||
const nodes = new Map(['user', 'steering', 'hidden'].map((kind, index) => {
|
||||
const key = `${kind}-key`;
|
||||
return [key, { key, kind: kind === 'hidden' ? 'user' : kind, anchorSeq: index + 1,
|
||||
visibility: kind === 'hidden' ? 'hidden' : 'visible', location: { kind: 'turn', turn },
|
||||
data: { seq: index + 1, time: 1, content: [{ type: 'text', text: `${kind} content` }] } }];
|
||||
}));
|
||||
const chat = { order: [...nodes.keys()], nodes, timeline: { turns: new Map([[1, turn]]) } };
|
||||
const session = { running: false, openState: 'ready', pendingSubmissions: [], hasMore: false, loadingOlder: false };
|
||||
const store = createReaderStore().create('session-users');
|
||||
const props = {
|
||||
sessionId: 'session-users', useChat: (select: any) => select(chat),
|
||||
useSession: (select: any) => select(session), useSessions: (select: any) => select({ byId: { 'session-users': { cwd: '/fixture' } } }),
|
||||
useSessionStatus: (select: any) => select(new Map()), useStore: (select: any) => select(store.getSnapshot()), actions: store.actions,
|
||||
t: (key: string) => key, loadImage: async () => ({ data: new Uint8Array(), mediaType: 'image/png' }),
|
||||
officialImageLoader: Object.assign(async () => null, { peek: () => null }),
|
||||
officialFileMentions: () => undefined, officialPreviewFile: () => {},
|
||||
officialHost: source({ home: '/fixture' }), fillComposer: () => true,
|
||||
openFile: () => {}, loadOlder: async () => {}, openView: () => {},
|
||||
};
|
||||
slots.register({ name: 'root', children: {
|
||||
'conversation.chat.node': { kind: 'keyed', scope: 'session', inject: { hooks: {
|
||||
turnData: (_: unknown, context: any) => () => context.turnData,
|
||||
disclosure: (_: unknown, context: any) => () => context.disclosureReset,
|
||||
} } },
|
||||
'fixture.reader': { kind: 'single', scope: 'session' },
|
||||
} }, ({ SessionProvider, renderSlot }: any) => <SessionProvider>{renderSlot('fixture.reader', {})}</SessionProvider>);
|
||||
slots.register({ name: 'fixture.reader', children: { ...officialChildren(slots), 'dsh-better-display.block': { kind: 'chain', scope: 'session' } } }, ({ renderSlot, renderSlotChain }: any) =>
|
||||
<Reader {...{ ...props, renderSlot, renderSlotChain } as ReaderProps} />);
|
||||
const stopMirror = installOfficialSlots(ctx);
|
||||
run = async () => {
|
||||
const container = document.getElementById('app')!;
|
||||
const reactRoot = createRoot(container);
|
||||
const render = () => {
|
||||
flushSync(() => reactRoot.render(slots.renderSlot('root', {})));
|
||||
return container.innerHTML;
|
||||
};
|
||||
const count = (html: string, text: string) => html.split(text).length - 1;
|
||||
const assertSeats = (html: string) => {
|
||||
for (const kind of ['user', 'steering']) {
|
||||
assert.equal(count(html, `data-reader-key="${kind}-key"`), 1);
|
||||
assert.equal(count(html, `data-chat-anchor-key="${kind}-key"`), 1);
|
||||
assert.equal(count(html, `data-chat-flow-key="${kind}-key"`), 1);
|
||||
assert.equal(count(html, `data-chat-node-key="${kind}-key"`), 1);
|
||||
assert.equal(count(html, `data-chat-flow-kind="${kind}"`), 1);
|
||||
}
|
||||
assert.equal(count(html, 'data-reader-anchor="true"'), 2);
|
||||
assert.ok(!html.includes('hidden content'));
|
||||
};
|
||||
|
||||
// The real renderSlot returns an outlet element for an unoccupied key.
|
||||
let html = render();
|
||||
assertSeats(html);
|
||||
assert.equal(count(html, 'user content'), 1);
|
||||
assert.equal(count(html, 'steering content'), 1);
|
||||
assert.ok(html.includes('补充消息'));
|
||||
const seen: any[] = [];
|
||||
const official = ({ node, sessionId, injectedSession, useTurnData, useDisclosure }: any) => {
|
||||
assert.equal(sessionId, 'session-users');
|
||||
assert.equal(injectedSession, 'session-users');
|
||||
assert.equal(useTurnData(), turn.data);
|
||||
assert.equal(useDisclosure().getSnapshot(), 0);
|
||||
assert.equal(node, nodes.get(node.key));
|
||||
seen.push(node.kind);
|
||||
return <div data-official-user={node.kind}>{node.data.content[0].text}<button>Official recall</button></div>;
|
||||
};
|
||||
const removeUser = slots.register({ name: 'conversation.chat.node', key: 'user',
|
||||
inject: (sessionId: string) => ({ injectedSession: sessionId }), locale: 'chat' }, official);
|
||||
const removeSteering = slots.register({ name: 'conversation.chat.node', key: 'steering',
|
||||
inject: (sessionId: string) => ({ injectedSession: sessionId }), locale: 'chat' }, official);
|
||||
const removeAssistant = slots.register({ name: 'conversation.chat.node', key: 'assistant-step' }, () => <span>Duplicate assistant</span>);
|
||||
await new Promise(resolve => queueMicrotask(resolve));
|
||||
assert.deepEqual(slots.entriesOfSlot(OFFICIAL_SEATS.nodes).map((entry: any) => entry.options.key).sort(), ['steering', 'user']);
|
||||
html = render();
|
||||
assertSeats(html);
|
||||
assert.equal(count(html, 'Official recall'), 2);
|
||||
assert.equal(count(html, 'user content'), 1);
|
||||
assert.equal(count(html, 'steering content'), 1);
|
||||
assert.deepEqual(seen, ['user', 'steering']);
|
||||
|
||||
// A winner intentionally returning null must keep its row hidden.
|
||||
const removeWinner = slots.register({ name: 'conversation.chat.node', key: 'user', priority: -1 }, () => null);
|
||||
await new Promise(resolve => queueMicrotask(resolve));
|
||||
html = render();
|
||||
assertSeats(html);
|
||||
assert.equal(count(html, 'user content'), 0);
|
||||
assert.equal(count(html, 'Official recall'), 1);
|
||||
removeWinner();
|
||||
await new Promise(resolve => queueMicrotask(resolve));
|
||||
assert.equal(count(render(), 'Official recall'), 2);
|
||||
removeUser(); removeSteering(); removeAssistant();
|
||||
await new Promise(resolve => queueMicrotask(resolve));
|
||||
html = render();
|
||||
assertSeats(html);
|
||||
assert.equal(count(html, 'user content'), 1);
|
||||
assert.equal(count(html, 'steering content'), 1);
|
||||
assert.equal(count(html, 'Official recall'), 0);
|
||||
|
||||
// A priority below the official assistant renderer is a replacement.
|
||||
// Reader keeps the reasoning card and hands only the body blocks over.
|
||||
const assistant = {
|
||||
key: 'assistant-key', kind: 'assistant-step', anchorSeq: 4, visibility: 'visible',
|
||||
location: { kind: 'turn', turn },
|
||||
data: {
|
||||
status: 'settled', turn: 1, step: 0, time: 3,
|
||||
blocks: [
|
||||
{ kind: 'reasoning', text: 'think privately' },
|
||||
{ kind: 'text', text: '<div id="vcp-root">card face</div>' },
|
||||
],
|
||||
},
|
||||
};
|
||||
// Reader memoizes on the order array and the nodes map. A real host
|
||||
// publishes new references; this fixture has to do the same.
|
||||
chat.nodes = new Map(chat.nodes);
|
||||
chat.nodes.set('assistant-key', assistant);
|
||||
chat.order = [...chat.order, 'assistant-key'];
|
||||
store.actions.setExpanded('turn:1:closed:completed', true);
|
||||
html = render();
|
||||
assert.equal(count(html, 'data-foreign-assistant'), 0);
|
||||
assert.ok(html.includes('vcp-root'));
|
||||
assert.ok(html.includes('think privately'));
|
||||
const calls: Array<{ groupPart: unknown; kinds: string[]; text: string }> = [];
|
||||
const Foreign = (props: { groupPart?: unknown; node?: { data?: { blocks?: Array<{ kind: string; text?: string }> } } }) => {
|
||||
const blocks = props.node?.data?.blocks ?? [];
|
||||
calls.push({
|
||||
groupPart: props.groupPart,
|
||||
kinds: blocks.map(block => block.kind),
|
||||
text: blocks.map(block => block.text ?? '').join('\n'),
|
||||
});
|
||||
const body = blocks.filter(block => block.kind === 'text').map(block => block.text ?? '').join('\n');
|
||||
return <div data-foreign-assistant>{body}</div>;
|
||||
};
|
||||
const removeOfficialAssistant = slots.register({ name: 'conversation.chat.node', key: 'assistant-step' }, () => <span>Official assistant</span>);
|
||||
const removeForeign = slots.register({ name: 'conversation.chat.node', key: 'assistant-step', priority: -10 }, Foreign);
|
||||
await new Promise(resolve => queueMicrotask(resolve));
|
||||
assert.ok(slots.entriesOfSlot(OFFICIAL_SEATS.nodes).some((entry: { options: { key?: string; priority?: number } }) => entry.options.key === 'assistant-step' && entry.options.priority === -10));
|
||||
html = render();
|
||||
const answer = container.querySelector('[data-reader-body]');
|
||||
assert.ok(answer);
|
||||
assert.equal(answer!.querySelectorAll('[data-foreign-assistant]').length, 1);
|
||||
assert.ok(answer!.textContent?.includes('<div id="vcp-root">card face</div>'));
|
||||
assert.equal(answer!.querySelectorAll('pre').length, 0);
|
||||
assert.equal(count(html, 'Official assistant'), 0);
|
||||
assert.ok(calls.some(call => call.groupPart === 'response' && call.kinds.join(',') === 'text' && call.text.includes('vcp-root')));
|
||||
assert.ok(calls.every(call => !call.kinds.includes('reasoning')));
|
||||
const reasoning = container.querySelector('[data-reader-text-kind="reasoning"]');
|
||||
assert.ok(reasoning);
|
||||
assert.ok(reasoning!.textContent?.includes('think privately'));
|
||||
assert.equal(reasoning!.querySelectorAll('[data-foreign-assistant]').length, 0);
|
||||
removeForeign();
|
||||
removeOfficialAssistant();
|
||||
await new Promise(resolve => queueMicrotask(resolve));
|
||||
html = render();
|
||||
assert.equal(count(html, 'data-foreign-assistant'), 0);
|
||||
assert.ok(html.includes('vcp-root'));
|
||||
assert.ok(html.includes('think privately'));
|
||||
chat.nodes = new Map(chat.nodes);
|
||||
chat.nodes.delete('assistant-key');
|
||||
chat.order = chat.order.filter((key: string) => key !== 'assistant-key');
|
||||
store.actions.setExpanded('turn:1:closed:completed', false);
|
||||
|
||||
const module = Reflect.get(window, 'easyrewriteModule');
|
||||
if (module) {
|
||||
const plugin = module.factory((name: string) => {
|
||||
if (name === 'react') return React;
|
||||
if (name === '@deepseek-ai/dsh-client-ui-primitives') return Primitives;
|
||||
throw new Error(`Unexpected easyrewrite dependency: ${name}`);
|
||||
});
|
||||
const disposers: Array<() => void> = [];
|
||||
plugin.apply({
|
||||
effect: (effect: () => () => void) => disposers.push(effect()),
|
||||
slots: {
|
||||
inject: (key: string, effect: () => () => void) => key === 'conversation.chat.node' ? effect() : () => {},
|
||||
register: (options: object, component: unknown) => slots.register(options, component),
|
||||
},
|
||||
sessions: { list: source({ current: 'session-users' }), scope: () => ({ get: () => undefined }) },
|
||||
workspaces: {},
|
||||
});
|
||||
await new Promise(resolve => queueMicrotask(resolve));
|
||||
html = render();
|
||||
assertSeats(html);
|
||||
assert.equal(count(html, 'data-dsh-easyrewrite="user"'), 1);
|
||||
assert.equal(count(html, 'data-dsh-easyrewrite="recall-key"'), 1);
|
||||
assert.equal(count(html, 'user content'), 1);
|
||||
assert.equal(count(html, 'steering content'), 1);
|
||||
const recall = container.querySelector<HTMLButtonElement>('[data-dsh-easyrewrite="recall-key"]');
|
||||
assert.ok(recall);
|
||||
flushSync(() => recall!.click());
|
||||
assert.equal(container.querySelectorAll('[data-dsh-easyrewrite="confirm-capsule"]').length, 1);
|
||||
for (const dispose of disposers) dispose();
|
||||
}
|
||||
stopMirror();
|
||||
reactRoot.unmount();
|
||||
Object.assign(window, { readerUserResult: 'passed' });
|
||||
};
|
||||
} });
|
||||
await run();
|
||||
}
|
||||
verify().catch(error => { console.error(error); Object.assign(window, { readerUserResult: `${error.stack}\n${document.getElementById('app')?.innerHTML}` }); });
|
||||
|
|
@ -1,80 +0,0 @@
|
|||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Reader theme overlap</title>
|
||||
<link rel="stylesheet" href="/Reader.module.css">
|
||||
<link rel="stylesheet" href="/MarkdownText.module.css">
|
||||
<style>
|
||||
:root {
|
||||
--dsh-content-font-size: 24px;
|
||||
--dsh-content-font-delta: 10px;
|
||||
--dsw-alias-bg-base: transparent;
|
||||
--dsw-alias-bg-layer-1: #102040;
|
||||
--dsw-alias-label-primary: #f5f7fa;
|
||||
--dsw-alias-label-secondary: #c5cad3;
|
||||
--dsw-alias-label-tertiary: #9aa3af;
|
||||
--dsw-font-family: ui-sans-serif, sans-serif;
|
||||
--dsw-font-markdown-h2: 700 29px/38px var(--dsw-font-family);
|
||||
--dsw-font-markdown-base: 24px/34px var(--dsw-font-family);
|
||||
}
|
||||
body { margin: 0; background: #ff00aa; }
|
||||
.scroll { height: 280px; overflow: auto; background: #ff00aa; }
|
||||
.spacer { height: 900px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="scroll" id="scroll">
|
||||
<div class="root" data-dsh-better-display="fixture">
|
||||
<div class="column" data-chat-flow="">
|
||||
<div class="toolbar" data-reader-lane="toolbar"><button class="textButton">自动折叠开</button></div>
|
||||
<section class="turn" data-reader-turn="1">
|
||||
<div class="turnStickyRegion">
|
||||
<div class="turnStickyLanes">
|
||||
<div class="turnProcessSticky" data-reader-lane="status">
|
||||
<button class="disclosureButton" type="button"><span class="statusText">用时 64 分 24 秒</span></button>
|
||||
</div>
|
||||
<div class="closedProcessSummary" id="summary" data-reader-closed-summary>
|
||||
<div class="summaryRow">
|
||||
<button class="disclosureButton" type="button"><span class="foldSummary">思考×79 · 输出×15 · 工具×79 · 记录×3</span></button>
|
||||
<span class="diffStatRoot"><button class="diffStatButton" type="button"><span class="diffAdded">+751</span><span class="diffRemoved">-63</span></button></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="answer">
|
||||
<div class="markdown">
|
||||
<h2 id="heading">核心对比 (2024/25 赛季, Deloitte 统一口径)</h2>
|
||||
<p class="spacer">回答正文在标题下面继续,用来把标题滚进吸顶带。</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="turn" data-reader-turn="2">
|
||||
<div class="turnProcessSticky" id="flow-status" data-reader-lane="flow-status">
|
||||
<button class="disclosureButton" type="button"><span class="statusText">用时 64 分 24 秒,字号放大后这一行变高</span></button>
|
||||
</div>
|
||||
<div class="flowCell" id="flow-summary" data-flow-summary>
|
||||
<button class="disclosureButton" type="button"><span class="foldSummary">思考×79 · 输出×15 · 工具×79 · 记录×3</span></button>
|
||||
</div>
|
||||
<div class="spacer"></div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
const root = document.querySelector('[data-dsh-better-display]');
|
||||
const turn = document.querySelector('[data-reader-turn="2"]');
|
||||
const toolbar = document.querySelector('.toolbar');
|
||||
const flowStatus = document.querySelector('#flow-status');
|
||||
const flowSummary = document.querySelector('#flow-summary');
|
||||
const publish = () => {
|
||||
root.style.setProperty('--reader-toolbar-height', `${Math.ceil(toolbar.getBoundingClientRect().height)}px`);
|
||||
turn.style.setProperty('--reader-status-height', `${Math.ceil(flowStatus.getBoundingClientRect().height)}px`);
|
||||
turn.style.setProperty('--reader-summary-height', `${Math.ceil(flowSummary.getBoundingClientRect().height)}px`);
|
||||
};
|
||||
publish();
|
||||
for (const el of [toolbar, flowStatus, flowSummary]) new ResizeObserver(publish).observe(el);
|
||||
window.__themeOverlapReady = true;
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,244 +0,0 @@
|
|||
import { Context } from '@deepseek-ai/cordis';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { flushSync } from 'react-dom';
|
||||
import { SlotRegistry } from '@fixture/registry';
|
||||
import { createSlotRenderer } from '@fixture/renderer';
|
||||
import { UserMessageNodeView } from '@fixture/user-message';
|
||||
import { UserContent } from '@fixture/user-content';
|
||||
import { Reader } from '../../src/client/Reader.js';
|
||||
import { createReaderStore } from '../../src/client/store.js';
|
||||
import { OFFICIAL_SEATS, OFFICIAL_SLOTS, installOfficialSlots, officialChildren } from '../../src/client/official-slots.js';
|
||||
import type { ReaderProps } from '../../src/client/types.js';
|
||||
|
||||
// Real Reader, real slot seats, and the host's user/steering renderer.
|
||||
// Session text is the only synthetic part. Width is measured after layout.
|
||||
|
||||
const CASES = [
|
||||
{ name: 'short', width: 748, axis: '', text: '升级插件' },
|
||||
{ name: 'thirty', width: 748, axis: '', text: '测'.repeat(30) },
|
||||
{ name: 'long', width: 748, axis: '', text: '测'.repeat(80) },
|
||||
{ name: 'narrow', width: 480, axis: '', text: '测'.repeat(30) },
|
||||
{ name: 'wide-axis', width: 1000, axis: '1000px', text: '测'.repeat(80) },
|
||||
] as const;
|
||||
|
||||
function turnOf() {
|
||||
return {
|
||||
turn: 1, status: 'closed' as const, start: { seq: 1, time: 1 },
|
||||
end: { time: 2, data: { reason: { kind: 'completed' } } }, data: new Map(), steps: [],
|
||||
};
|
||||
}
|
||||
|
||||
function messageNode(kind: 'user' | 'steering', text: string) {
|
||||
const turn = turnOf();
|
||||
return {
|
||||
key: `${kind}-key`, kind, anchorSeq: kind === 'user' ? 1 : 2, visibility: 'visible' as const,
|
||||
location: { kind: 'turn' as const, turn },
|
||||
data: { seq: kind === 'user' ? 1 : 2, time: 1, content: [{ type: 'text', text }] },
|
||||
};
|
||||
}
|
||||
|
||||
function readerProps(text: string, renderSlot: ReaderProps['renderSlot'], renderSlotChain: ReaderProps['renderSlotChain']): ReaderProps {
|
||||
const turn = turnOf();
|
||||
const user = messageNode('user', text);
|
||||
const steering = messageNode('steering', text);
|
||||
user.location = { kind: 'turn', turn };
|
||||
steering.location = { kind: 'turn', turn };
|
||||
const nodes = new Map([[user.key, user], [steering.key, steering]]);
|
||||
const chat = { order: [user.key, steering.key], nodes, timeline: { turns: new Map([[1, turn]]) } };
|
||||
const session = {
|
||||
running: false, openState: 'ready', hasMore: false, loadingOlder: false,
|
||||
pendingSubmissions: [{ requestId: `pending-${text.length}`, text, time: 1, placement: 'transcript' }],
|
||||
};
|
||||
const store = createReaderStore().create(`session-${text.length}`);
|
||||
store.actions.setMotion(false);
|
||||
const source = <T,>(value: T) => ({ getSnapshot: () => value, subscribe: () => () => {} });
|
||||
return {
|
||||
sessionId: `session-${text.length}`,
|
||||
useChat: (select: (snapshot: typeof chat) => unknown) => select(chat),
|
||||
useSession: (select: (snapshot: typeof session) => unknown) => select(session),
|
||||
useSessions: (select: (snapshot: { byId: Record<string, { cwd: string }> }) => unknown) => select({ byId: { [`session-${text.length}`]: { cwd: '/fixture' } } }),
|
||||
useSessionStatus: (select: (snapshot: Map<string, unknown>) => unknown) => select(new Map()),
|
||||
useStore: (select: (snapshot: ReturnType<typeof store.getSnapshot>) => unknown) => select(store.getSnapshot()),
|
||||
actions: store.actions,
|
||||
t: (key: string) => key,
|
||||
loadImage: async () => ({ data: new Uint8Array(), mediaType: 'image/png' }),
|
||||
officialImageLoader: Object.assign(async () => null, { peek: () => null }),
|
||||
officialFileMentions: () => undefined,
|
||||
officialPreviewFile: () => {},
|
||||
officialHost: source({ home: '/fixture' }),
|
||||
fillComposer: () => true,
|
||||
openFile: () => {},
|
||||
loadOlder: async () => {},
|
||||
openView: () => {},
|
||||
renderSlot,
|
||||
renderSlotChain,
|
||||
} as ReaderProps;
|
||||
}
|
||||
|
||||
function NativeColumn({ renderSlot, kind, text }: {
|
||||
renderSlot: ReaderProps['renderSlot'];
|
||||
kind: 'user' | 'steering';
|
||||
text: string;
|
||||
}) {
|
||||
const node = messageNode(kind, text);
|
||||
const owner = {
|
||||
cwd: '/fixture', openFile: () => {}, forkAt: () => {},
|
||||
inspectCall: () => {}, loadImage: async () => null,
|
||||
fileMentions: () => undefined, node,
|
||||
};
|
||||
return (
|
||||
<div data-native={kind} style={{ width: '100%', maxWidth: 'var(--dsh-chat-content-width, 748px)', display: 'flex', flexDirection: 'column' }}>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
{renderSlot(OFFICIAL_SLOTS.nodes, owner, {
|
||||
entryKey: kind,
|
||||
hookContext: {
|
||||
turnData: node.location.turn.data,
|
||||
disclosureReset: { getSnapshot: () => 0, subscribe: () => () => {}, set: () => {} },
|
||||
useGroupAction: () => ({ current: null }),
|
||||
},
|
||||
fallback: null,
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function paddedTextBox(scope: ParentNode | null): Element | null {
|
||||
if (!scope) return null;
|
||||
const walker = document.createTreeWalker(scope, NodeFilter.SHOW_TEXT);
|
||||
let node: Node | null;
|
||||
while ((node = walker.nextNode())) {
|
||||
if (!node.textContent?.trim()) continue;
|
||||
const parent = node.parentElement;
|
||||
if (!parent || parent.closest('button')) continue;
|
||||
let element: HTMLElement | null = parent;
|
||||
while (element && element !== scope) {
|
||||
if (parseFloat(getComputedStyle(element).paddingTop) > 0) return element;
|
||||
element = element.parentElement;
|
||||
}
|
||||
return parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function boxOf(root: ParentNode | null, kind: 'user' | 'steering' | 'pending') {
|
||||
const scope = kind === 'pending'
|
||||
? root?.querySelector('[data-reader-pending-submission]')
|
||||
: root?.querySelector(`[data-reader-key="${kind}-key"]`);
|
||||
return paddedTextBox(scope ?? null);
|
||||
}
|
||||
|
||||
function nativeBox(frame: ParentNode, kind: 'user' | 'steering') {
|
||||
return paddedTextBox(frame.querySelector(`[data-native="${kind}"]`));
|
||||
}
|
||||
|
||||
function measure(element: Element | null) {
|
||||
if (!element) return { w: 0, h: 0, font: '', line: '' };
|
||||
const style = getComputedStyle(element);
|
||||
const rect = element.getBoundingClientRect();
|
||||
return {
|
||||
w: Math.round(rect.width * 10) / 10,
|
||||
h: Math.round(rect.height * 10) / 10,
|
||||
font: style.fontSize,
|
||||
line: style.lineHeight,
|
||||
};
|
||||
}
|
||||
|
||||
async function verify() {
|
||||
const root = new Context();
|
||||
await root.plugin(SlotRegistry);
|
||||
let run = async () => {};
|
||||
await root.plugin({ name: 'reader-bubble-width', inject: ['slots'], async apply(ctx: Context) {
|
||||
const slots = ctx.slots as any;
|
||||
slots.install(createSlotRenderer());
|
||||
const source = <T,>(value: T) => ({ getSnapshot: () => value, subscribe: () => () => {} });
|
||||
const binding = { key: 'session-width', ctx: new Context(), hooks: {}, keyedHooks: {}, props: { sessionId: 'session-width' } };
|
||||
slots.installScope('session', {
|
||||
current: source(binding), bindingSource: () => source(binding), renderArea: (_: unknown, props: { children?: unknown }) => props.children,
|
||||
});
|
||||
slots.installLocale({ ...source({}), bind: () => (key: string) => key });
|
||||
const HostUser = (props: Record<string, unknown>) => (
|
||||
<UserMessageNodeView
|
||||
{...props as never}
|
||||
t={(props.t as ((key: string) => string) | undefined) ?? ((key: string) => key)}
|
||||
openFile={(props.openFile as (() => void) | undefined) ?? (() => {})}
|
||||
/>
|
||||
);
|
||||
slots.register({ name: 'root', children: {
|
||||
'conversation.chat.node': { kind: 'keyed', scope: 'session', inject: { hooks: {
|
||||
turnData: (_: unknown, context: { turnData?: unknown }) => () => context.turnData,
|
||||
disclosure: (_: unknown, context: { disclosureReset?: { getSnapshot(): number } }) => () => context.disclosureReset,
|
||||
groupAction: (_: unknown, context: { useGroupAction?: unknown }) => context.useGroupAction,
|
||||
} } },
|
||||
'conversation.chat.message.images': { kind: 'single', scope: 'session' },
|
||||
'fixture.reader': { kind: 'single', scope: 'session' },
|
||||
} }, ({ SessionProvider, renderSlot }: any) => (
|
||||
<SessionProvider>
|
||||
{renderSlot('fixture.reader', {})}
|
||||
{CASES.map(item => (
|
||||
<section key={`native-${item.name}`} data-native-case={item.name} style={{ width: item.width, ['--dsh-chat-content-width' as string]: item.axis || undefined }}>
|
||||
<NativeColumn renderSlot={renderSlot} kind="user" text={item.text} />
|
||||
<NativeColumn renderSlot={renderSlot} kind="steering" text={item.text} />
|
||||
</section>
|
||||
))}
|
||||
</SessionProvider>
|
||||
));
|
||||
slots.register({ name: 'fixture.reader', children: {
|
||||
...officialChildren(slots),
|
||||
'dsh-better-display.block': { kind: 'chain', scope: 'session' },
|
||||
} }, ({ renderSlot, renderSlotChain }: any) => (
|
||||
<>
|
||||
{CASES.map(item => (
|
||||
<section key={item.name} data-case={item.name} style={{ width: item.width, ['--dsh-chat-content-width' as string]: item.axis || undefined }}>
|
||||
<div data-reader-mount>
|
||||
<Reader {...readerProps(item.text, renderSlot, renderSlotChain)} />
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</>
|
||||
));
|
||||
slots.registerFactory({
|
||||
name: 'conversation.chat.user.content', scope: 'session', locale: 'chat',
|
||||
children: { 'conversation.chat.user.images': { kind: 'single', scope: 'session' } },
|
||||
}, UserContent);
|
||||
slots.registerFactory({
|
||||
name: 'conversation.user.text', scope: 'session', locale: 'chat',
|
||||
}, ({ text }: { text: string }) => <>{text}</>);
|
||||
slots.register({ name: 'conversation.chat.node', key: 'user', locale: 'chat' }, HostUser);
|
||||
slots.register({ name: 'conversation.chat.node', key: 'steering', locale: 'chat' }, HostUser);
|
||||
const stopMirror = installOfficialSlots(ctx);
|
||||
run = async () => {
|
||||
await new Promise(resolve => queueMicrotask(resolve));
|
||||
const container = document.getElementById('app')!;
|
||||
const reactRoot = createRoot(container);
|
||||
flushSync(() => reactRoot.render(slots.renderSlot('root', {})));
|
||||
for (const reader of container.querySelectorAll<HTMLElement>('[data-dsh-better-display]')) reader.style.padding = '0';
|
||||
await new Promise(resolve => requestAnimationFrame(() => resolve(undefined)));
|
||||
const readerSlot = container.querySelector('[data-reader-key="user-key"] [data-slot]')?.getAttribute('data-slot') ?? '';
|
||||
const nativeSlot = container.querySelector('[data-native="user"] [data-slot]')?.getAttribute('data-slot') ?? '';
|
||||
const rows = CASES.map(item => {
|
||||
const frame = container.querySelector(`[data-case="${item.name}"]`);
|
||||
const nativeFrame = container.querySelector(`[data-native-case="${item.name}"]`);
|
||||
const mount = frame?.querySelector('[data-reader-mount]') ?? null;
|
||||
const user = measure(boxOf(mount, 'user'));
|
||||
const steering = measure(boxOf(mount, 'steering'));
|
||||
const pending = measure(boxOf(mount, 'pending'));
|
||||
const nativeUser = measure(nativeFrame ? nativeBox(nativeFrame, 'user') : null);
|
||||
const nativeSteering = measure(nativeFrame ? nativeBox(nativeFrame, 'steering') : null);
|
||||
return {
|
||||
name: item.name,
|
||||
user, steering, pending, nativeUser, nativeSteering,
|
||||
readerHtml: mount?.querySelector('[data-reader-key="user-key"]')?.innerHTML.slice(0, 400) ?? '',
|
||||
};
|
||||
});
|
||||
stopMirror();
|
||||
Object.assign(window, { readerBubbleResult: { readerSlot, nativeSlot, expectedReaderSlot: OFFICIAL_SEATS.nodes, expectedNativeSlot: OFFICIAL_SLOTS.nodes, rows } });
|
||||
};
|
||||
} });
|
||||
await run();
|
||||
}
|
||||
|
||||
verify().catch(error => {
|
||||
console.error(error);
|
||||
Object.assign(window, { readerBubbleResult: { error: `${error instanceof Error ? error.stack : String(error)}\n${document.getElementById('app')?.innerHTML.slice(0, 2000)}` } });
|
||||
});
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { test } from 'vitest';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { apply } from '../src/host.js';
|
||||
import { defaultFlags, loadFlags } from '../src/flags.js';
|
||||
|
||||
test('readerEnabled defaults to true', () => {
|
||||
assert.equal(defaultFlags.readerEnabled, true);
|
||||
const file = JSON.parse(readFileSync(fileURLToPath(new URL('../flags.json', import.meta.url)), 'utf8')) as { readerEnabled: boolean };
|
||||
assert.equal(file.readerEnabled, true);
|
||||
assert.equal(loadFlags().readerEnabled, true);
|
||||
assert.equal(loadFlags({ readerEnabled: false }).readerEnabled, false);
|
||||
const dir = mkdtempSync(join(tmpdir(), 'bd-flags-'));
|
||||
try {
|
||||
const broken = join(dir, 'flags.json');
|
||||
writeFileSync(broken, '{ "readerEnabled": "yes" }');
|
||||
assert.equal(loadFlags(broken).readerEnabled, true);
|
||||
assert.equal(loadFlags(join(dir, 'missing.json')).readerEnabled, true);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('apply skips route registration when readerEnabled is false', () => {
|
||||
let registered = 0;
|
||||
let effects = 0;
|
||||
apply({
|
||||
webServer: {
|
||||
register() {
|
||||
registered += 1;
|
||||
return () => undefined;
|
||||
},
|
||||
},
|
||||
effect(run: () => void) {
|
||||
effects += 1;
|
||||
run();
|
||||
},
|
||||
} as never, { flags: { readerEnabled: false } });
|
||||
assert.equal(registered, 0);
|
||||
assert.equal(effects, 0);
|
||||
assert.doesNotThrow(() => apply({} as never, { flags: { readerEnabled: true } }));
|
||||
});
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { test } from 'vitest';
|
||||
import assert from 'node:assert/strict';
|
||||
import { collapseRows, containsNewUser, flowRows, FOLD_TIMING, retiringKeys } from '../src/client/fold-choreography.js';
|
||||
import { arrangeTurnWaves, collapseRows, containsNewUser, flowRows, FOLD_TIMING, groupProcessRows, retiringKeys } from '../src/client/fold-choreography.js';
|
||||
import { presentLiveTurn } from '../src/client/live-turn.js';
|
||||
import type { LiveStep } from '../src/client/live-turn.js';
|
||||
const reasoning = (n: number): LiveStep => ({ kind: 'reasoning', key: `r${n}`, nodeKey: `n${n}`, start: 0, blocks: [], step: n });
|
||||
|
|
@ -38,13 +38,13 @@ test('repeat fold retires only displayed open rows, retaining the same summary i
|
|||
test('narration never enters a fold cell, so choreography never retires it', () => {
|
||||
const before = presentLiveTurn([reasoning(1)], open);
|
||||
const withNarration = presentLiveTurn([reasoning(1), body], open);
|
||||
assert.deepEqual(retiringKeys(before, withNarration, {}), []);
|
||||
assert.deepEqual(flowRows(withNarration).map(row => row.key), ['r1', 'b1']);
|
||||
assert.deepEqual(retiringKeys(before, withNarration, {}), ['r1']);
|
||||
assert.deepEqual(flowRows(withNarration).map(row => row.key), ['live-fold:r1', 'r1', 'b1']);
|
||||
|
||||
const after = presentLiveTurn([reasoning(1), body, tool, reasoning(2)], open);
|
||||
assert.equal(after.some(item => item.kind === 'fold' && item.steps.some(step => step.kind === 'body')), false);
|
||||
// The prior reasoning run folds (r1 retires), but narration itself never does.
|
||||
assert.deepEqual(retiringKeys(withNarration, after, {}), ['r1']);
|
||||
// The first run is already folded, and the next tool was never visible.
|
||||
assert.deepEqual(retiringKeys(withNarration, after, {}), []);
|
||||
assert.ok(!retiringKeys(withNarration, after, {}).includes('b1'));
|
||||
});
|
||||
test('user admission bypasses buffered choreography and preserves source ordering', () => {
|
||||
|
|
@ -76,3 +76,49 @@ test('every phase has a bounded budget and a watchdog strictly beyond it', () =>
|
|||
assert.ok(budget + FOLD_TIMING.watchdogSlack < 1000, phase + ' must not read as a stall');
|
||||
}
|
||||
});
|
||||
|
||||
test('one scroll box joins process rows across hidden members and ends before the answer', () => {
|
||||
const groups = groupProcessRows([
|
||||
{ key: 'summary', process: true, hidden: false },
|
||||
{ key: 'folded-record', process: true, hidden: true },
|
||||
{ key: 'thought', process: true, hidden: false },
|
||||
{ key: 'tool', process: true, hidden: false },
|
||||
{ key: 'answer', process: false, hidden: false },
|
||||
{ key: 'next-thought', process: true, hidden: false },
|
||||
]);
|
||||
assert.deepEqual(groups.map(group => group.map(row => row.key)), [
|
||||
['summary', 'folded-record', 'thought', 'tool'], ['answer'], ['next-thought'],
|
||||
]);
|
||||
});
|
||||
|
||||
test('arrangeTurnWaves merges multi-segment AI replies on top and collects process below, splitting at steering', () => {
|
||||
const waves = arrangeTurnWaves([
|
||||
{ key: 'r1', bucket: 'process' },
|
||||
{ key: 'b1', bucket: 'body' },
|
||||
{ key: 't1', bucket: 'process' },
|
||||
{ key: 'b2', bucket: 'body' },
|
||||
{ key: 'steer', bucket: 'user' },
|
||||
{ key: 'r2', bucket: 'process' },
|
||||
{ key: 'b3', bucket: 'body' },
|
||||
{ key: 'err', bucket: 'other' },
|
||||
]);
|
||||
assert.equal(waves.length, 3);
|
||||
assert.equal(waves[0]?.key, 'initial');
|
||||
assert.deepEqual(waves[0]?.body.map(r => r.key), ['b1', 'b2']);
|
||||
assert.deepEqual(waves[0]?.process.map(r => r.key), ['r1', 't1']);
|
||||
assert.equal(waves[1]?.user?.key, 'steer');
|
||||
assert.equal(waves[2]?.key, 'after:steer');
|
||||
assert.deepEqual(waves[2]?.body.map(r => r.key), ['b3']);
|
||||
assert.deepEqual(waves[2]?.other.map(r => r.key), ['err']);
|
||||
assert.deepEqual(waves[2]?.process.map(r => r.key), ['r2']);
|
||||
});
|
||||
|
||||
test('arrangeTurnWaves keeps wave key stable when a live-fold summary is inserted ahead of earlier steps', () => {
|
||||
const before = arrangeTurnWaves([{ key: 'r1', bucket: 'process' }]);
|
||||
const after = arrangeTurnWaves([
|
||||
{ key: 'live-fold:r1', bucket: 'process' },
|
||||
{ key: 'r1', bucket: 'process' },
|
||||
{ key: 'b1', bucket: 'body' },
|
||||
]);
|
||||
assert.equal(before[0]?.key, after[0]?.key);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,137 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { test } from 'vitest';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const css = readFileSync(resolve(root, 'src/client/Reader.module.css'), 'utf8');
|
||||
const bundle = readFileSync(resolve(root, 'lib/client.js'), 'utf8');
|
||||
|
||||
/**
|
||||
* Host ConversationRoot owns the footer band: `.composerSeat` is `position:
|
||||
* sticky; bottom: 0; z-index: 7`, its own markdown code banner is 6 and the
|
||||
* floating controls are 8. A scrolling reader clamps every turn-level sticky
|
||||
* lane down into that band (the lane stops at its containing block's bottom,
|
||||
* which passes behind the input card), so a lane at 7 or above paints the
|
||||
* reader's own opaque plate over the composer. Everything the reader pins
|
||||
* inside the transcript therefore has to stay strictly below 7.
|
||||
*/
|
||||
const HOST_FOOTER_Z = 7;
|
||||
|
||||
/** Lanes a scroll can clamp into the footer band. */
|
||||
const CLAMPED_LANES = [
|
||||
'.turnStickyLanes',
|
||||
'.turnProcessSticky',
|
||||
'.liveFoldContainer',
|
||||
'.flowCell[data-flow-summary]',
|
||||
'.closedProcessSummary',
|
||||
];
|
||||
|
||||
/** The one lane allowed at 7: it pins to the scrollport's first lane and can never reach the band. */
|
||||
const TOP_LANE = '.toolbar';
|
||||
|
||||
function mergedDeclarations(source: string, selector: string, { hashed = false } = {}): Map<string, string> {
|
||||
const declarations = new Map<string, string>();
|
||||
const body = source.replace(/\/\*[\s\S]*?\*\//g, '');
|
||||
const rule = /([^{}]+)\{([^{}]*)\}/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = rule.exec(body)) !== null) {
|
||||
const selectors = match[1]!.split(',').map(part => part.trim());
|
||||
const wanted = hashed
|
||||
? selectors.some(part => part.endsWith(selector) || part.endsWith(selector.replace(/^\./, '')))
|
||||
: selectors.includes(selector);
|
||||
if (!wanted) continue;
|
||||
for (const declaration of match[2]!.split(';')) {
|
||||
const separator = declaration.indexOf(':');
|
||||
if (separator < 0) continue;
|
||||
const property = declaration.slice(0, separator).trim();
|
||||
const value = declaration.slice(separator + 1).trim();
|
||||
if (property) declarations.set(property, value);
|
||||
}
|
||||
}
|
||||
return declarations;
|
||||
}
|
||||
|
||||
/** Minified CSS inside the committed bundle keeps the hashed prefix on each class. */
|
||||
function bundledDeclarations(className: string): Map<string, string> {
|
||||
const declarations = new Map<string, string>();
|
||||
const rule = new RegExp(`(?:^|[.,}])[.#]?[\\w-]*${className}\\{([^{}]*)\\}`, 'g');
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = rule.exec(bundle)) !== null) {
|
||||
for (const declaration of match[1]!.split(';')) {
|
||||
const separator = declaration.indexOf(':');
|
||||
if (separator < 0) continue;
|
||||
declarations.set(declaration.slice(0, separator).trim(), declaration.slice(separator + 1).trim());
|
||||
}
|
||||
}
|
||||
return declarations;
|
||||
}
|
||||
|
||||
test('clamped reader lanes stay strictly below the host footer band', () => {
|
||||
for (const lane of CLAMPED_LANES) {
|
||||
const declarations = mergedDeclarations(css, lane);
|
||||
const zIndex = declarations.get('z-index');
|
||||
assert.ok(zIndex, `${lane} still declares its lane z-index`);
|
||||
assert.ok(
|
||||
Number(zIndex) < HOST_FOOTER_Z,
|
||||
`${lane} must stay below the host composer seat (z-index ${HOST_FOOTER_Z}), got ${zIndex}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('the top toolbar lane stays at 7 and pins to the scrollport top', () => {
|
||||
const declarations = mergedDeclarations(css, TOP_LANE);
|
||||
assert.equal(declarations.get('z-index'), String(HOST_FOOTER_Z));
|
||||
assert.equal(declarations.get('top'), '0');
|
||||
});
|
||||
|
||||
test('official code block banners stay beneath Reader sticky lanes', () => {
|
||||
const blockZ = Number(mergedDeclarations(css, '.root :global(.md-code-block)').get('z-index'));
|
||||
const summaryZ = Number(mergedDeclarations(css, '.flowCell[data-flow-summary]').get('z-index'));
|
||||
assert.ok(Number.isFinite(blockZ), 'Reader scopes official markdown code blocks into a stacking context');
|
||||
assert.ok(blockZ < summaryZ, `code block banner context (${blockZ}) must stay below the summary lane (${summaryZ})`);
|
||||
});
|
||||
|
||||
test('the live status lane pins below the toolbar lane instead of over it', () => {
|
||||
const declarations = mergedDeclarations(css, '.turnProcessSticky');
|
||||
assert.match(
|
||||
declarations.get('top') ?? '',
|
||||
/var\(--reader-toolbar-height/,
|
||||
'the status lane shares the measured lane below the toolbar',
|
||||
);
|
||||
});
|
||||
|
||||
test('the closed summary lane shares that same measured lane', () => {
|
||||
const declarations = mergedDeclarations(css, '.flowCell[data-flow-summary]');
|
||||
assert.match(declarations.get('top') ?? '', /var\(--reader-toolbar-height/);
|
||||
});
|
||||
|
||||
test('skin mode does not reintroduce a lane above the footer band', () => {
|
||||
for (const lane of CLAMPED_LANES) {
|
||||
const zIndex = mergedDeclarations(css, `.root[data-reader-glass] ${lane}`).get('z-index');
|
||||
if (zIndex === undefined || zIndex === 'auto') continue;
|
||||
assert.ok(
|
||||
Number(zIndex) < HOST_FOOTER_Z,
|
||||
`glass override for ${lane} must not lift above ${HOST_FOOTER_Z}, got ${zIndex}`,
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
mergedDeclarations(css, '.root[data-reader-glass] .toolbar').get('z-index'),
|
||||
undefined,
|
||||
'the toolbar keeps its single ladder value in both modes',
|
||||
);
|
||||
});
|
||||
|
||||
test('the committed client bundle carries the same lane ladder', () => {
|
||||
for (const lane of ['turnProcessSticky', 'liveFoldContainer']) {
|
||||
const bundled = bundledDeclarations(lane);
|
||||
const zIndex = bundled.get('z-index');
|
||||
assert.ok(zIndex, `${lane} is present in the built bundle`);
|
||||
assert.ok(
|
||||
Number(zIndex) < HOST_FOOTER_Z,
|
||||
`${lane} in lib/client.js must stay below ${HOST_FOOTER_Z}, got ${zIndex}`,
|
||||
);
|
||||
}
|
||||
assert.equal(bundledDeclarations('toolbar').get('z-index'), String(HOST_FOOTER_Z));
|
||||
});
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { test } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import * as host from '../src/host.js'
|
||||
|
||||
/**
|
||||
* Regression: dsh-better-chat 1.0.1 read `ctx.permissionPresets` before declaring
|
||||
* it in `inject`. Cordis throws `cannot get property "permissionPresets" without
|
||||
* inject` on that read, so a clean profile (§ only provides webServer) failed the
|
||||
* host activation with "1 entry did not activate". The plugin must activate and
|
||||
* leave the auto-review wiring to a scoped `ctx.inject` callback.
|
||||
*/
|
||||
function createContext(services: Record<string, unknown>): Context {
|
||||
const ctx = new Context()
|
||||
for (const [name, value] of Object.entries(services)) {
|
||||
ctx.provide(name as never)
|
||||
ctx.set(name as never, value as never)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
test('host plugin activates when permissionPresets/agents are absent', async () => {
|
||||
const ctx = createContext({ webServer: { register: () => () => undefined } })
|
||||
const fiber = ctx.plugin(host as never)
|
||||
await fiber
|
||||
assert.equal(fiber.state, 2, 'fiber should be ACTIVE, not FAILED/PENDING')
|
||||
})
|
||||
|
||||
test('host plugin wires the auto-review default through inject', async () => {
|
||||
const setCalls: Array<[string, string]> = []
|
||||
const ctx = createContext({
|
||||
webServer: { register: () => () => undefined },
|
||||
permissionPresets: {
|
||||
names: ['read-only', 'auto'],
|
||||
current: () => 'workspace-write',
|
||||
set: (session: { id: string }, name: string) => setCalls.push([session.id, name]),
|
||||
},
|
||||
agents: {
|
||||
list: () => [{
|
||||
session: { id: 'fresh-1', header: { id: 'fresh-1' }, snapshotEvents: () => [] },
|
||||
}],
|
||||
},
|
||||
})
|
||||
const fiber = ctx.plugin(host as never)
|
||||
await fiber
|
||||
assert.equal(fiber.state, 2)
|
||||
await new Promise(resolve => setTimeout(resolve, 50))
|
||||
assert.deepEqual(setCalls, [['fresh-1', 'auto']], 'blank top-level session should default to auto review')
|
||||
})
|
||||
|
|
@ -24,7 +24,7 @@ function user(id: string): LiveStep {
|
|||
return { kind: 'user', key: id, nodeKey: id };
|
||||
}
|
||||
function other(id: string): LiveStep {
|
||||
return { kind: 'other', key: id, nodeKey: id };
|
||||
return { kind: 'other', key: id, nodeKey: id, process: true };
|
||||
}
|
||||
|
||||
function kinds(items: ReturnType<typeof presentLiveTurn>) {
|
||||
|
|
@ -33,7 +33,7 @@ function kinds(items: ReturnType<typeof presentLiveTurn>) {
|
|||
|
||||
test('narration is never folded; earlier process runs collapse even across narration', () => {
|
||||
const beforeSecondReasoning = presentLiveTurn([reasoning('1'), body('2')], open);
|
||||
assert.deepEqual(kinds(beforeSecondReasoning), [['open', '1'], ['open', '2']]);
|
||||
assert.deepEqual(kinds(beforeSecondReasoning), [['fold', '思考×1', ['1']], ['open', '2']]);
|
||||
|
||||
// The first reasoning run folds in place before the narration; the narration
|
||||
// itself stays open, and the latest reasoning stays open.
|
||||
|
|
@ -123,23 +123,23 @@ test('presentLiveTurn keeps one fold box per foldable run and never hides narrat
|
|||
test('mid-turn user insert resets the chain; narration stays open across the reset', () => {
|
||||
const before = presentLiveTurn([reasoning('1'), body('2'), tool('3'), user('insert'), body('4'), tool('5')], open);
|
||||
assert.deepEqual(kinds(before), [
|
||||
['open', '1'], ['open', '2'], ['open', '3'],
|
||||
['fold', '思考×1', ['1']], ['open', '2'], ['open', '3'],
|
||||
['user', 'insert'],
|
||||
['open', '4'], ['open', '5'],
|
||||
]);
|
||||
|
||||
const after = presentLiveTurn([reasoning('1'), body('2'), tool('3'), user('insert'), body('4'), tool('5'), reasoning('6')], open);
|
||||
assert.deepEqual(kinds(after), [
|
||||
['open', '1'], ['open', '2'], ['open', '3'],
|
||||
['fold', '思考×1', ['1']], ['open', '2'], ['open', '3'],
|
||||
['user', 'insert'],
|
||||
['open', '4'],
|
||||
['fold', '工具×1', ['5']],
|
||||
['open', '6'],
|
||||
]);
|
||||
const folds = after.filter(item => item.kind === 'fold');
|
||||
assert.equal(folds.length, 1);
|
||||
if (folds[0]?.kind !== 'fold') throw new Error('missing insert fold');
|
||||
assert.ok(!folds[0].steps.some(step => ['1', '2', '3', '4', 'insert'].includes(step.key)));
|
||||
assert.equal(folds.length, 2);
|
||||
if (folds[1]?.kind !== 'fold') throw new Error('missing insert fold');
|
||||
assert.ok(!folds[1].steps.some(step => ['1', '2', '3', '4', 'insert'].includes(step.key)));
|
||||
});
|
||||
|
||||
test('every prior process run folds in its own place; narration stays open between runs', () => {
|
||||
|
|
@ -232,7 +232,7 @@ test('steering in the flow is a chain reset, same as a mid-turn user message', (
|
|||
const flow = readerFlow({ key: 'turn:1', turn: 1, keys: ['a', 'steer', 'b'] }, undefined, key => nodes.get(key));
|
||||
const items = presentLiveTurn(segmentLiveTurn(flow, key => nodes.get(key)), open);
|
||||
assert.deepEqual(kinds(items), [
|
||||
['open', 'a:reasoning:0'], ['open', 'a:body:1'],
|
||||
['fold', '思考×1', ['a:reasoning:0']], ['open', 'a:body:1'],
|
||||
['user', 'steer'],
|
||||
['open', 'b:reasoning:0'],
|
||||
]);
|
||||
|
|
@ -280,10 +280,18 @@ test('closed turn keeps the seam between narration blocks and the previous body
|
|||
assert.equal(live.some(item => item.kind === 'fold'), false);
|
||||
|
||||
const seams = planProcessSeams(steps, live, false);
|
||||
assert.equal(seams.before.get('body2'), '思考×2 · 工具×3 · 记录×1');
|
||||
assert.deepEqual(seams.before.get('body2'), { summary: '思考×2 · 工具×3 · 记录×1', count: 6 });
|
||||
assert.equal(seams.after.has('body1'), true);
|
||||
|
||||
const expanded = planProcessSeams(steps, live, true);
|
||||
assert.equal(expanded.before.size, 0);
|
||||
assert.equal(expanded.after.size, 0);
|
||||
});
|
||||
|
||||
test('the first output folds even a record-only process; subsequent work stays visible', () => {
|
||||
const records = [other('context1'), other('context2')];
|
||||
assert.deepEqual(kinds(presentLiveTurn(records, open)), [['open', 'context1'], ['open', 'context2']]);
|
||||
assert.deepEqual(kinds(presentLiveTurn([...records, body('text'), tool('new-tool')], open)), [
|
||||
['fold', '记录×2', ['context1', 'context2']], ['open', 'text'], ['open', 'new-tool'],
|
||||
]);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,99 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { IncomingMessage, ServerResponse } from 'node:http';
|
||||
import { Socket } from 'node:net';
|
||||
import { test } from 'vitest';
|
||||
import { createLogger, redact, REDACTED, requestIdOf } from '../src/log.js';
|
||||
import { apply } from '../src/host.js';
|
||||
import { ROUTE_REVEAL } from '../src/metrics.js';
|
||||
|
||||
const SECRET = 's3cr3t-token-value';
|
||||
|
||||
test('logger redacts authorization headers, tokens, and secret-looking query values', () => {
|
||||
const lines: string[] = [];
|
||||
const logger = createLogger({ write: line => lines.push(line), clock: () => new Date('2026-10-20T00:00:00.000Z') });
|
||||
logger.info('http request', {
|
||||
headers: {
|
||||
authorization: `Bearer ${SECRET}`,
|
||||
'x-api-key': SECRET,
|
||||
'x-request-id': 'req-1',
|
||||
accept: 'application/json',
|
||||
},
|
||||
url: `/better-display/reveal?cwd=/work&token=${SECRET}&api_key=${SECRET}&password=${SECRET}`,
|
||||
token: SECRET,
|
||||
access_token: SECRET,
|
||||
});
|
||||
const record = JSON.parse(lines[0] ?? '{}') as {
|
||||
level: string;
|
||||
msg: string;
|
||||
time: string;
|
||||
headers: { authorization: string; 'x-api-key': string; 'x-request-id': string; accept: string };
|
||||
url: string;
|
||||
token: string;
|
||||
access_token: string;
|
||||
};
|
||||
const text = lines.join('\n');
|
||||
assert.equal(record.level, 'info');
|
||||
assert.equal(record.msg, 'http request');
|
||||
assert.equal(record.time, '2026-10-20T00:00:00.000Z');
|
||||
assert.equal(record.headers.authorization, REDACTED);
|
||||
assert.equal(record.headers['x-api-key'], REDACTED);
|
||||
assert.equal(record.token, REDACTED);
|
||||
assert.equal(record.access_token, REDACTED);
|
||||
assert.equal(record.headers['x-request-id'], 'req-1');
|
||||
assert.equal(record.headers.accept, 'application/json');
|
||||
assert.match(record.url, /cwd=\/work/);
|
||||
assert.match(record.url, /token=\[REDACTED\]/);
|
||||
assert.match(record.url, /api_key=\[REDACTED\]/);
|
||||
assert.match(record.url, /password=\[REDACTED\]/);
|
||||
assert.equal(text.includes(SECRET), false);
|
||||
assert.deepEqual(redact({ authorization: `Bearer ${SECRET}`, accept: 'application/json' }), {
|
||||
authorization: REDACTED,
|
||||
accept: 'application/json',
|
||||
});
|
||||
});
|
||||
|
||||
test('request ids keep a safe X-Request-ID and replace anything else', () => {
|
||||
const kept = requestIdOf({ headers: { 'x-request-id': 'req.trace_1:part-a' } } as IncomingMessage);
|
||||
assert.equal(kept, 'req.trace_1:part-a');
|
||||
const firstOfMany = requestIdOf({ headers: { 'x-request-id': ['batch-7', 'batch-8'] } } as IncomingMessage);
|
||||
assert.equal(firstOfMany, 'batch-7');
|
||||
const generated = requestIdOf({ headers: { 'x-request-id': 'bad id\ninjected' } } as IncomingMessage);
|
||||
assert.notEqual(generated, 'bad id\ninjected');
|
||||
assert.match(generated, /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
|
||||
assert.match(requestIdOf({ headers: {} } as IncomingMessage), /^[0-9a-f-]{36}$/);
|
||||
});
|
||||
|
||||
test('reveal handler logs the request id and does not log the secret query', () => {
|
||||
const lines: string[] = [];
|
||||
const original = console.log;
|
||||
console.log = (line?: unknown) => { lines.push(String(line)); };
|
||||
try {
|
||||
const routes: { path: string; handler: (req: IncomingMessage, res: ServerResponse) => void }[] = [];
|
||||
apply({
|
||||
webServer: {
|
||||
register(route: { path: string; handler: (req: IncomingMessage, res: ServerResponse) => void }) {
|
||||
routes.push(route);
|
||||
return () => undefined;
|
||||
},
|
||||
},
|
||||
effect(run: () => void) { run(); },
|
||||
} as never, { flags: { readerEnabled: true } });
|
||||
const reveal = routes.find(route => route.path === ROUTE_REVEAL);
|
||||
assert.ok(reveal);
|
||||
const req = new IncomingMessage(new Socket());
|
||||
req.method = 'GET';
|
||||
req.url = `${ROUTE_REVEAL}?cwd=/work&token=${SECRET}`;
|
||||
req.headers = { authorization: `Bearer ${SECRET}`, 'x-request-id': 'req-reveal-1' };
|
||||
const res = new ServerResponse(req);
|
||||
res.end = (() => res) as ServerResponse['end'];
|
||||
reveal.handler(req, res);
|
||||
assert.equal(res.statusCode, 405);
|
||||
assert.equal(res.getHeader('X-Request-ID'), 'req-reveal-1');
|
||||
const text = lines.join('\n');
|
||||
assert.match(text, /\[dsh-better-chat\] loaded/);
|
||||
assert.match(text, /req-reveal-1/);
|
||||
assert.equal(text.includes(SECRET), false);
|
||||
} finally {
|
||||
console.log = original;
|
||||
}
|
||||
});
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { IncomingMessage, ServerResponse } from 'node:http';
|
||||
import { Socket } from 'node:net';
|
||||
import { test } from 'vitest';
|
||||
import { apply } from '../src/host.js';
|
||||
import { metricsPayload, recordRouteDuration, recordRouteHit, ROUTE_METRICS, ROUTE_REVEAL } from '../src/metrics.js';
|
||||
|
||||
test('route hit counter increments', () => {
|
||||
const before = metricsPayload();
|
||||
const hitsBefore = before.counters.dsh_better_display_route_hits_total[ROUTE_REVEAL] ?? 0;
|
||||
const totalBefore = before.timingsMs[ROUTE_REVEAL]?.totalMs ?? 0;
|
||||
const next = recordRouteHit(ROUTE_REVEAL);
|
||||
recordRouteDuration(ROUTE_REVEAL, 12.4);
|
||||
const after = metricsPayload();
|
||||
assert.equal(next, hitsBefore + 1);
|
||||
assert.equal(after.counters.dsh_better_display_route_hits_total[ROUTE_REVEAL], hitsBefore + 1);
|
||||
assert.equal(after.timingsMs[ROUTE_REVEAL]?.totalMs, totalBefore + 12);
|
||||
assert.ok((after.timingsMs[ROUTE_REVEAL]?.maxMs ?? 0) >= 12);
|
||||
});
|
||||
|
||||
test('GET /better-display/metrics returns the incremented route counter', () => {
|
||||
const routes: { path: string; handler: (req: IncomingMessage, res: ServerResponse) => void }[] = [];
|
||||
apply({
|
||||
webServer: {
|
||||
register(route: { path: string; handler: (req: IncomingMessage, res: ServerResponse) => void }) {
|
||||
routes.push(route);
|
||||
return () => undefined;
|
||||
},
|
||||
},
|
||||
effect(run: () => void) { run(); },
|
||||
} as never, { flags: { readerEnabled: true } });
|
||||
assert.deepEqual(routes.map(route => route.path).sort(), [ROUTE_METRICS, ROUTE_REVEAL].sort());
|
||||
const metrics = routes.find(route => route.path === ROUTE_METRICS);
|
||||
assert.ok(metrics);
|
||||
const before = metricsPayload().counters.dsh_better_display_route_hits_total[ROUTE_METRICS] ?? 0;
|
||||
const req = new IncomingMessage(new Socket());
|
||||
req.method = 'GET';
|
||||
req.url = ROUTE_METRICS;
|
||||
req.headers = { 'x-request-id': 'req-metrics-1' };
|
||||
const res = new ServerResponse(req);
|
||||
let body = '';
|
||||
res.end = ((chunk?: string) => {
|
||||
body = chunk ?? '';
|
||||
return res;
|
||||
}) as ServerResponse['end'];
|
||||
metrics.handler(req, res);
|
||||
assert.equal(res.statusCode, 200);
|
||||
assert.equal(res.getHeader('content-type'), 'application/json');
|
||||
assert.equal(res.getHeader('X-Request-ID'), 'req-metrics-1');
|
||||
const parsed = JSON.parse(body) as { counters: { dsh_better_display_route_hits_total: Record<string, number> } };
|
||||
assert.equal(parsed.counters.dsh_better_display_route_hits_total[ROUTE_METRICS], before + 1);
|
||||
});
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const read = (path: string) => readFileSync(new URL(path, import.meta.url), 'utf8');
|
||||
|
||||
describe('pinned selection', () => {
|
||||
it('covers every Reader body marker, so final formatting keeps a live selection', () => {
|
||||
const reader = [read('../src/client/Reader.tsx'), read('../src/client/AssistantNode.tsx')].join('\n');
|
||||
const motion = read('../src/client/motion.tsx');
|
||||
const selector = /usePinnedSelection\([^)]*selector = '([^']+)'/.exec(motion)?.[1] ?? '';
|
||||
const markers = ['data-reader-answer', 'data-reader-body'].filter(marker => new RegExp(`<article[^>]*\\b${marker}\\b`).test(reader));
|
||||
expect(markers.length).toBeGreaterThan(0);
|
||||
for (const marker of markers) expect(selector).toContain(`[${marker}]`);
|
||||
expect(selector).toContain('[data-reader-process]');
|
||||
});
|
||||
});
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { test } from 'vitest';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { hostComposerUsable, READER_COMPOSER_RESTORE } from '../src/client/composer-seat.js';
|
||||
import { ReaderEntryPolicy, readerEntryRequested } from '../src/client/entry-policy.js';
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
/** Specificity tuple [ids, attributes-and-pseudos, elements] for the two selectors this fix compares. */
|
||||
function specificity(selector: string): [number, number, number] {
|
||||
const expanded = selector.replace(/:has\(([^)]*)\)/g, ' $1 ');
|
||||
const ids = expanded.match(/#[\w-]+/g)?.length ?? 0;
|
||||
const attrs = expanded.match(/\[[^\]]+\]/g)?.length ?? 0;
|
||||
const without = expanded.replace(/\[[^\]]+\]/g, ' ').replace(/:[^\s#.[]+/g, ' ').replace(/#[\w-]+/g, ' ');
|
||||
const elements = without.match(/[a-zA-Z][\w-]*/g)?.length ?? 0;
|
||||
return [ids, attrs, elements];
|
||||
}
|
||||
|
||||
const SKIN_HIDE = 'body[data-dsh-claude-style][data-dsh-claude-composer-active] [data-dsh-claude-composer-hidden] [data-composer-seat]';
|
||||
|
||||
test('a new session lands on reader and the host composer stays usable there', () => {
|
||||
const policy = new ReaderEntryPolicy(false);
|
||||
assert.equal(policy.select(null), 'reader');
|
||||
assert.equal(policy.select(undefined), 'reader');
|
||||
assert.equal(hostComposerUsable({ skinHidesSeat: false, readerMounted: true }), true);
|
||||
assert.equal(hostComposerUsable({ skinHidesSeat: true, readerMounted: true }), true);
|
||||
});
|
||||
|
||||
test('?reader=1 still enters reading once and does not cover the composer', () => {
|
||||
assert.equal(readerEntryRequested('?reader=1'), true);
|
||||
let consumed = 0;
|
||||
const policy = new ReaderEntryPolicy(true, () => { consumed++; });
|
||||
assert.equal(policy.select('chat'), 'reader');
|
||||
assert.equal(consumed, 1);
|
||||
assert.equal(policy.select('chat'), null);
|
||||
assert.equal(hostComposerUsable({ skinHidesSeat: true, readerMounted: true }), true);
|
||||
});
|
||||
|
||||
test('leaving the reader tab does not keep forcing the composer visible', () => {
|
||||
const policy = new ReaderEntryPolicy(false);
|
||||
assert.equal(policy.select('chat'), null);
|
||||
assert.equal(policy.select('trajectory'), null);
|
||||
assert.equal(policy.select('reader'), null);
|
||||
assert.equal(hostComposerUsable({ skinHidesSeat: true, readerMounted: false }), false);
|
||||
assert.equal(hostComposerUsable({ skinHidesSeat: false, readerMounted: false }), true);
|
||||
});
|
||||
|
||||
test('the reader stylesheet outranks the skin hide and the bundle ships it', () => {
|
||||
const css = readFileSync(resolve(root, 'src/client/Reader.module.css'), 'utf8');
|
||||
const reader = readFileSync(resolve(root, 'src/client/Reader.tsx'), 'utf8');
|
||||
assert.match(reader, /data-dsh-better-display=/);
|
||||
assert.match(css, new RegExp(`:global\\(${READER_COMPOSER_RESTORE.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\)`));
|
||||
assert.match(css, /display:\s*flex\s*!important/);
|
||||
const ours = specificity(READER_COMPOSER_RESTORE);
|
||||
const skin = specificity(SKIN_HIDE);
|
||||
assert.ok(ours[0] > skin[0] || ours[1] > skin[1] || (ours[1] === skin[1] && ours[2] > skin[2]), `${ours} should beat ${skin}`);
|
||||
const client = readFileSync(resolve(root, 'lib/client.js'), 'utf8');
|
||||
assert.match(client, /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\}/);
|
||||
});
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { resolve } from 'node:path';
|
||||
import { test } from 'vitest';
|
||||
import { externalClientBundle } from '../tools/client-build.js';
|
||||
|
||||
// Exercise the actual build plugin so options cannot drift from production.
|
||||
async function readerCss(): Promise<string> {
|
||||
const configs = externalClientBundle('dsh-better-chat', [], { clientEntry: 'src/client/index.tsx' });
|
||||
const client = configs.find(config => config.name === 'dsh-better-chat/client');
|
||||
const plugin = client?.plugins.find(plugin => plugin.name === 'dshx-css-modules');
|
||||
assert.ok(plugin);
|
||||
const source = await plugin.load.call({ addWatchFile() {} }, `\0dshx-css-module:${resolve('src/client/Reader.module.css')}.mjs`);
|
||||
const literal = /^const css = (.+);$/m.exec(source)?.[1];
|
||||
assert.ok(literal, 'the build emits an inline CSS string');
|
||||
const css: unknown = JSON.parse(literal);
|
||||
assert.equal(typeof css, 'string');
|
||||
if (typeof css !== 'string') throw new Error('Expected CSS text');
|
||||
return css;
|
||||
}
|
||||
|
||||
test('built Reader CSS retains Chromium blur and the older Safari fallback', async () => {
|
||||
const css = await readerCss();
|
||||
assert.match(css, /(?<![\w-])backdrop-filter:blur\(12px\)/);
|
||||
assert.match(css, /-webkit-backdrop-filter:blur\(12px\)/);
|
||||
const prefixed = [...css.matchAll(/-webkit-backdrop-filter:([^;}]+)/g)].map(match => match[1]);
|
||||
const standard = [...css.matchAll(/(?<![\w-])backdrop-filter:([^;}]+)/g)].map(match => match[1]);
|
||||
assert.deepEqual(standard, prefixed, 'every Safari fallback also has a working standard declaration');
|
||||
});
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { test } from 'vitest';
|
||||
|
||||
/**
|
||||
* The reader-in-chat wiring is mostly declarative (slot id, priority, child
|
||||
* seats, hidden official row), so the cheap regression guard is reading the
|
||||
* entry modules. Executable ledger behaviour lives in `chat-view-seat.test.ts`;
|
||||
* this file guards the two files' agreed contract.
|
||||
*/
|
||||
const source = await readFile(new URL('../src/client/reader-plugin.tsx', import.meta.url), 'utf8');
|
||||
const seat = await readFile(new URL('../src/client/chat-view-seat.ts', import.meta.url), 'utf8');
|
||||
const reader = await readFile(new URL('../src/client/Reader.tsx', import.meta.url), 'utf8');
|
||||
const flow = await readFile(new URL('../src/client/ChoreographedFlow.tsx', import.meta.url), 'utf8');
|
||||
const official = await readFile(new URL('../src/client/OfficialContent.tsx', import.meta.url), 'utf8');
|
||||
const blocks = await readFile(new URL('../src/client/Blocks.tsx', import.meta.url), 'utf8');
|
||||
const readerCss = await readFile(new URL('../src/client/Reader.module.css', import.meta.url), 'utf8');
|
||||
const turnMetricsCss = await readFile(new URL('../src/client/TurnMetrics.module.css', import.meta.url), 'utf8');
|
||||
const markdown = await readFile(new URL('../src/client/markdown/MarkdownText.tsx', import.meta.url), 'utf8');
|
||||
|
||||
test('the reader occupies the built-in 对话 View at a shadowing priority', () => {
|
||||
assert.match(source, /name: 'conversation\.view'/u);
|
||||
assert.match(source, /id: CHAT_VIEW_ID/u);
|
||||
assert.match(source, /priority: CHAT_VIEW_PRIORITY/u);
|
||||
assert.match(source, /label: \(\) => '对话'/u);
|
||||
assert.doesNotMatch(source, /id: 'reader'/u, 'the old 阅读 tab must not come back');
|
||||
assert.doesNotMatch(source, /installReaderEntry/u, 'no forced View switch on open');
|
||||
});
|
||||
|
||||
test('the official ChatView row stays live; only its tab id is hidden', () => {
|
||||
assert.match(source, /retireHostedChatView/u);
|
||||
assert.match(source, /yield retireHostedChatView\(/u);
|
||||
assert.match(source, /yield installOfficialSlots\(ctx\)/u);
|
||||
assert.match(seat, /entry\.options\.id = undefined/u);
|
||||
assert.doesNotMatch(seat, /rows\.splice/u);
|
||||
assert.match(source, /yield hideDuplicateChatTabs\(document\)/u);
|
||||
assert.match(readerCss, /data-better-chat-duplicate-tab[^}]+display: none/u);
|
||||
assert.match(seat, /ACTIVE\.set\(ledger, restore\)/u);
|
||||
});
|
||||
|
||||
test('the reader bubble and actions stay right-aligned under the user message', () => {
|
||||
assert.match(readerCss, /\.userCluster > \[data-slot\] > :not\(\.user, \.userImages, \.userActions\)/u);
|
||||
assert.match(readerCss, /\.userActions \{[^}]*align-self: flex-end;[^}]*width: fit-content/u);
|
||||
assert.doesNotMatch(readerCss, /\.userCluster > \[data-slot\] > \*/u);
|
||||
});
|
||||
|
||||
test('reasoning bodies render through compact Markdown', () => {
|
||||
assert.match(blocks, /data-reader-text-kind="reasoning"/u);
|
||||
assert.match(blocks, /variant="compact"/u);
|
||||
assert.match(markdown, /variant\?: 'body' \| 'compact'/u);
|
||||
});
|
||||
|
||||
test('the optional user-image slot has a low-priority renderer', () => {
|
||||
assert.match(source, /name: 'conversation\.chat\.user\.images',\s*priority: 1000,[\s\S]*?UserImageFallback/u);
|
||||
assert.match(blocks, /loadImage=\{loadImage\}/u);
|
||||
assert.match(blocks, /src=\{image\.preview\.url\}/u);
|
||||
});
|
||||
|
||||
test('short thoughts, tools and folded process summaries keep visible cards', () => {
|
||||
assert.doesNotMatch(readerCss, /\.reasonCard\[data-overflow=false\][^{}]*\{[^}]*background:\s*transparent/u);
|
||||
assert.match(readerCss, /\.toolActivity, \.processCard \{[^}]*border:/u);
|
||||
assert.match(readerCss, /\.disclosureButton:has\(\[data-reader-fold-summary\]\)[^{}]*\{[^}]*border:/u);
|
||||
});
|
||||
|
||||
test('completed process summary drops duplicate turn duration and keeps one status lane', () => {
|
||||
assert.match(reader, /<StickyLane kind="status"[^>]*>[\s\S]*?<GroupStatus[\s\S]*?<ClosedProcessSummary[\s\S]*?<\/StickyLane>/u);
|
||||
assert.match(reader, /if \(turn\?\.status === 'closed'\) return '执行过程';/u);
|
||||
assert.match(reader, /const showStatusLane = hasProcess && !isAwaitingModel && !showClosedSummary;/u);
|
||||
assert.match(readerCss, /\.closedProcessSummary\.summaryRow \{[^}]*flex-wrap: nowrap/u);
|
||||
});
|
||||
|
||||
test('process summary wraps between labels and keeps the last counter visible', () => {
|
||||
const rules = [...readerCss.matchAll(/^\.foldSummary \{([^}]*)\}/gmu)].map(match => match[1]);
|
||||
assert.equal(rules.length, 1);
|
||||
assert.match(rules[0] ?? '', /flex-wrap: wrap/u);
|
||||
assert.doesNotMatch(rules[0] ?? '', /overflow: hidden|text-overflow/u);
|
||||
assert.match(readerCss, /\.foldSummaryPart \{[^}]*white-space: nowrap/u);
|
||||
});
|
||||
|
||||
test('tool rendering reads a snapshot that survives the plugin context', () => {
|
||||
assert.match(source, /const officialHostHome = createSnapshotStore<string \| undefined>\(undefined\)/u);
|
||||
assert.match(source, /ctx\.on\('connection\/reset', updateHome\)/u);
|
||||
assert.doesNotMatch(source, /getSnapshot:\s*\(\)\s*=>\s*ctx\.remote/u);
|
||||
assert.match(official, /useSyncExternalStore\(official\.officialHostHome\.subscribe, official\.officialHostHome\.getSnapshot\)/u);
|
||||
});
|
||||
|
||||
test('live summaries and visible work share a bounded process frame beneath the merged AI bubble', () => {
|
||||
assert.match(flow, /row\.kind === 'summary'\) return \{ row, key: row\.key, hidden: false, process: true, bucket: 'process' \}/u);
|
||||
assert.match(flow, /arrangeTurnWaves\(cells\)/u);
|
||||
assert.match(flow, /data-reader-answer-bubble[\s\S]*?data-reader-process-frame/u);
|
||||
assert.match(readerCss, /\.answerBubble \{[^}]*max-width: var\(--reader-ai-max-width\)/u);
|
||||
assert.match(readerCss, /\.processViewport \{[^}]*max-width: var\(--reader-ai-max-width\)[^}]*max-height: min\(320px, 45vh\)/u);
|
||||
assert.match(readerCss, /\.processScroll \{[^}]*overflow: auto/u);
|
||||
assert.match(reader, /const expanded = !autoFold \|\| holdingSelection \|\| processExpanded\(expansionChoice, boundary\)/u);
|
||||
});
|
||||
|
||||
test('all Reader attachment previews delegate the full reference to the host loader', () => {
|
||||
assert.match(reader, /loadImage: props\.officialImageLoader/u);
|
||||
assert.match(source, /uiConversation\.imageUrl\(sessionId, attachment\)/u);
|
||||
assert.match(blocks, /loadImage\(attachment\)/u);
|
||||
assert.doesNotMatch(source, /readAttachment\(attachment\.attachmentId\)/u);
|
||||
});
|
||||
|
||||
test('the status lane joins the visible process frame below the reply bubble and actions sit outside the bubble', () => {
|
||||
assert.match(reader, /status=\{\(showStatusLane \|\| showClosedSummary\) && <StickyLane/u);
|
||||
assert.match(reader, /<CopyAnswer blocks=\{finalBodyInfo\.copyBlocks\}/u);
|
||||
assert.match(flow, /data-reader-process-frame[^>]*>[\s\S]*?\{hasStatus && <div className=\{css\.turnStickyLanes\} data-flow-process>\{status\}<\/div>\}[\s\S]*?<ProcessScroll hidden=\{scrollHidden\}/u);
|
||||
assert.match(flow, /className=\{css\.processScroll\} data-reader-process-scroll/u);
|
||||
assert.match(readerCss, /\[data-flow-process\]\[data-flow-summary\] \.disclosureButton \{[^}]*border: 0/u);
|
||||
});
|
||||
|
||||
test('answer actions and turn metric pills stay intact when the chat column narrows', () => {
|
||||
assert.match(readerCss, /\.answerActions \{[^}]*flex-wrap: wrap;/u);
|
||||
assert.match(readerCss, /\.iconButton \{[^}]*flex: none;/u);
|
||||
assert.match(readerCss, /\.messageClock \{[^}]*flex: none;[^}]*white-space: nowrap;/u);
|
||||
assert.match(turnMetricsCss, /\.container \{[^}]*flex-wrap: wrap;[^}]*max-width: 100%;/u);
|
||||
assert.match(turnMetricsCss, /\.pillButton \{[^}]*flex: none;[^}]*height: 24px;[^}]*white-space: nowrap;/u);
|
||||
assert.match(turnMetricsCss, /\.timeButton \{[^}]*flex: none;[^}]*height: 28px;[^}]*white-space: nowrap;/u);
|
||||
assert.match(turnMetricsCss, /\.metricsPop \{[^}]*width: min\(260px,/u);
|
||||
});
|
||||
|
|
@ -1,91 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { createServer } from 'node:http';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
import { homedir, tmpdir } from 'node:os';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { test } from 'vitest';
|
||||
|
||||
// Needs the Harness source tree and a local pinned Chromium; CI (which builds the
|
||||
// release) has neither browser runtime, so the test skips there instead of failing.
|
||||
const harnessPointer = join(homedir(), '.config/dshx/harness');
|
||||
const harness = process.env.DSHX_HARNESS?.trim()
|
||||
|| (existsSync(harnessPointer) ? readFileSync(harnessPointer, 'utf8').trim() : '');
|
||||
const browserRuntime = join(homedir(), '.codex/playwright-runtime/runtime.mjs');
|
||||
const skip = !harness ? 'DSH Harness source not available'
|
||||
: !existsSync(browserRuntime) ? 'pinned Chromium runtime not available' : false;
|
||||
|
||||
test('official user output stays inside the cluster that carries the host width', () => {
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
const source = readFileSync(join(root, 'src/client/Reader.tsx'), 'utf8');
|
||||
const css = readFileSync(join(root, 'src/client/Reader.module.css'), 'utf8');
|
||||
assert.match(source, /className=\{css\.userCluster\}[^>]*data-reader-key=\{nodeKey\}[^>]*>\{rendered\}/);
|
||||
assert.match(css, /\.userCluster\s*\{[^}]*width:\s*100%/);
|
||||
assert.match(css, /\.userCluster > \[data-slot\] > \* \{[^}]*width:\s*100%/);
|
||||
assert.doesNotMatch(css, /\[data-slot="conversation\.chat\.node"\]/);
|
||||
});
|
||||
|
||||
test('headless Reader users retain official renderers, anchors and empty-key fallback', { skip, timeout: 15_000 }, async () => {
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
const require = createRequire(join(root, 'package.json'));
|
||||
const { build } = createRequire(require.resolve('tsx'))('esbuild');
|
||||
const webRequire = createRequire(join(harness, 'packages/client/web/package.json'));
|
||||
const out = mkdtempSync(join(tmpdir(), 'reader-official-users-'));
|
||||
try {
|
||||
const { launchPinnedChromium } = await import(pathToFileURL(browserRuntime).href);
|
||||
await build({
|
||||
entryPoints: [join(root, 'tests/fixtures/reader-official-users.tsx')],
|
||||
outfile: join(out, 'fixture.js'), bundle: true, platform: 'browser', format: 'esm', jsx: 'automatic',
|
||||
alias: {
|
||||
'@fixture/registry': join(harness, 'packages/client/ui-renderer/src/client/registry.ts'),
|
||||
'@fixture/renderer': join(harness, 'packages/client/ui-renderer/src/client/scoped-slots.tsx'),
|
||||
'@deepseek-ai/dsh-client-ui-primitives': join(harness, 'packages/client/ui-primitives/src/index.ts'),
|
||||
'@deepseek-ai/dsh-client-ui-slots': join(harness, 'packages/client/ui-slots/src/index.ts'),
|
||||
// The published store lib leaves zustand/immer to the host; the source
|
||||
// package resolves them from the Harness workspace.
|
||||
'@deepseek-ai/dsh-client-store': join(harness, 'packages/client/store/src/index.ts'),
|
||||
react: dirname(require.resolve('react/package.json')),
|
||||
'react-dom': dirname(webRequire.resolve('react-dom/package.json')),
|
||||
},
|
||||
loader: { '.css': 'empty', '.woff2': 'empty', '.woff': 'empty', '.ttf': 'empty', '.svg': 'empty' },
|
||||
logLevel: 'silent',
|
||||
});
|
||||
const server = createServer((request, response) => {
|
||||
if (request.url === '/easyrewrite.js' && process.env.DSH_EASYREWRITE_CLIENT) {
|
||||
response.setHeader('Content-Type', 'text/javascript');
|
||||
response.end(readFileSync(process.env.DSH_EASYREWRITE_CLIENT));
|
||||
} else if (request.url === '/fixture.js') {
|
||||
response.setHeader('Content-Type', 'text/javascript');
|
||||
response.end(readFileSync(join(out, 'fixture.js')));
|
||||
} else {
|
||||
response.setHeader('Content-Type', 'text/html');
|
||||
const easyrewrite = process.env.DSH_EASYREWRITE_CLIENT
|
||||
? '<script>window.__ModuleLoader__={load:m=>window.easyrewriteModule=m}</script><script src="/easyrewrite.js"></script>' : '';
|
||||
response.end(`<!doctype html><div id="app"></div>${easyrewrite}<script type="module" src="/fixture.js"></script>`);
|
||||
}
|
||||
});
|
||||
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
let browser;
|
||||
try {
|
||||
browser = await launchPinnedChromium();
|
||||
const page = await browser.newPage();
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', (error: Error) => errors.push(String(error)));
|
||||
page.on('console', (message: { type(): string; text(): string }) => {
|
||||
if (message.type() === 'error') errors.push(message.text());
|
||||
});
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address === 'object');
|
||||
await page.goto(`http://127.0.0.1:${address.port}`);
|
||||
await page.waitForFunction(() => 'readerUserResult' in window, undefined, { timeout: 10000 });
|
||||
assert.equal(await page.evaluate(() => Reflect.get(window, 'readerUserResult')), 'passed');
|
||||
assert.deepEqual(errors, []);
|
||||
} finally {
|
||||
await browser?.close();
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
}
|
||||
} finally {
|
||||
rmSync(out, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
|
@ -1,377 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { createServer } from 'node:http';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { homedir, tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { inflateSync } from 'node:zlib';
|
||||
import { test } from 'vitest';
|
||||
|
||||
const browserRuntime = join(homedir(), '.codex/playwright-runtime/runtime.mjs');
|
||||
const skip = existsSync(browserRuntime) ? false : 'pinned Chromium runtime not available';
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
const shots = '/tmp/issue-66-sticky-lanes';
|
||||
|
||||
function paeth(left: number, up: number, upLeft: number) {
|
||||
const estimate = left + up - upLeft;
|
||||
const leftDistance = Math.abs(estimate - left);
|
||||
const upDistance = Math.abs(estimate - up);
|
||||
const diagonal = Math.abs(estimate - upLeft);
|
||||
if (leftDistance <= upDistance && leftDistance <= diagonal) return left;
|
||||
if (upDistance <= diagonal) return up;
|
||||
return upLeft;
|
||||
}
|
||||
|
||||
function pngPixel(buffer: Buffer, x: number, y: number) {
|
||||
let offset = 8;
|
||||
const chunks: Buffer[] = [];
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
let colorType = 0;
|
||||
while (offset < buffer.length) {
|
||||
const length = buffer.readUInt32BE(offset);
|
||||
const type = buffer.toString('ascii', offset + 4, offset + 8);
|
||||
const data = buffer.subarray(offset + 8, offset + 8 + length);
|
||||
if (type === 'IHDR') {
|
||||
width = data.readUInt32BE(0);
|
||||
height = data.readUInt32BE(4);
|
||||
colorType = data[9] ?? 0;
|
||||
} else if (type === 'IDAT') chunks.push(data);
|
||||
else if (type === 'IEND') break;
|
||||
offset += 12 + length;
|
||||
}
|
||||
const bytesPerPixel = colorType === 6 ? 4 : 3;
|
||||
const raw = inflateSync(Buffer.concat(chunks));
|
||||
const stride = width * bytesPerPixel;
|
||||
let source = 0;
|
||||
let previous = Buffer.alloc(stride);
|
||||
const rows: Buffer[] = [];
|
||||
for (let rowIndex = 0; rowIndex < height; rowIndex += 1) {
|
||||
const filter = raw[source] ?? 0;
|
||||
source += 1;
|
||||
const row = Buffer.alloc(stride);
|
||||
for (let index = 0; index < stride; index += 1) {
|
||||
const value = raw[source] ?? 0;
|
||||
source += 1;
|
||||
const left = index >= bytesPerPixel ? row[index - bytesPerPixel] ?? 0 : 0;
|
||||
const up = previous[index] ?? 0;
|
||||
const upLeft = index >= bytesPerPixel ? previous[index - bytesPerPixel] ?? 0 : 0;
|
||||
let decoded = value;
|
||||
if (filter === 1) decoded = value + left;
|
||||
else if (filter === 2) decoded = value + up;
|
||||
else if (filter === 3) decoded = value + Math.floor((left + up) / 2);
|
||||
else if (filter === 4) decoded = value + paeth(left, up, upLeft);
|
||||
else if (filter !== 0) throw new Error(`unsupported png filter ${filter}`);
|
||||
row[index] = decoded & 255;
|
||||
}
|
||||
rows.push(row);
|
||||
previous = row;
|
||||
}
|
||||
const pixel = rows[y];
|
||||
const start = x * bytesPerPixel;
|
||||
return [pixel?.[start] ?? 0, pixel?.[start + 1] ?? 0, pixel?.[start + 2] ?? 0];
|
||||
}
|
||||
|
||||
function dist(a: number[], b: number[]) {
|
||||
return Math.hypot(a[0]! - b[0]!, a[1]! - b[1]!, a[2]! - b[2]!);
|
||||
}
|
||||
|
||||
type Rgb = [number, number, number];
|
||||
|
||||
function laneHtml(cssName: string, options: {
|
||||
scheme: 'dark' | 'light';
|
||||
base: string;
|
||||
layer: string;
|
||||
label: string;
|
||||
delta: number;
|
||||
fontSize: number;
|
||||
glass?: boolean;
|
||||
}) {
|
||||
const glass = options.glass ? ' data-reader-glass=""' : '';
|
||||
return `<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<link rel="stylesheet" href="/${cssName}">
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: ${options.scheme};
|
||||
--dsh-content-font-size: ${options.fontSize}px;
|
||||
--dsh-content-font-delta: ${options.delta}px;
|
||||
--dsw-alias-bg-base: ${options.base};
|
||||
--dsw-alias-bg-layer-1: ${options.layer};
|
||||
--dsw-alias-label-primary: ${options.label};
|
||||
--dsw-alias-label-secondary: ${options.label};
|
||||
--dsw-alias-label-tertiary: ${options.label};
|
||||
--dsw-font-family: ui-sans-serif, sans-serif;
|
||||
}
|
||||
html, body { margin: 0; background: #ff00aa; color-scheme: ${options.scheme}; }
|
||||
.scroll { height: 280px; overflow: auto; background: #ff00aa; }
|
||||
#heading { margin: 0; background: #00e5ff; color: #ff4ad2; font: 700 48px/52px sans-serif; }
|
||||
#canvas-probe { position: fixed; right: 8px; bottom: 8px; width: 12px; height: 12px; background: Canvas; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="canvas-probe"></div>
|
||||
<div class="scroll" id="scroll">
|
||||
<div class="root"${glass} data-dsh-better-display="fixture">
|
||||
<div class="column" data-chat-flow="">
|
||||
<div class="toolbar" data-reader-lane="toolbar"><button class="textButton" type="button">自动折叠开</button></div>
|
||||
<section class="turn" data-reader-turn="1">
|
||||
<div class="turnStickyRegion">
|
||||
<div class="turnStickyLanes">
|
||||
<div class="turnProcessSticky" data-reader-lane="status">
|
||||
<button class="disclosureButton" type="button"><span class="statusText">用时 64 分 24 秒</span></button>
|
||||
</div>
|
||||
<div class="closedProcessSummary" id="summary">
|
||||
<div class="summaryRow">
|
||||
<button class="disclosureButton" type="button"><span class="foldSummary">思考×79 · 输出×15</span></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="answer">
|
||||
<h2 id="heading">核心对比核心对比核心对比核心对比</h2>
|
||||
<div style="height:900px"></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>window.__ready = true;</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
async function listen(files: Map<string, Buffer | string>) {
|
||||
const server = createServer((request, response) => {
|
||||
const body = files.get(request.url ?? '/');
|
||||
if (body === undefined) { response.statusCode = 404; response.end(); return; }
|
||||
response.setHeader('Content-Type', request.url?.endsWith('.css') ? 'text/css' : request.url?.endsWith('.js') ? 'text/javascript' : 'text/html');
|
||||
response.end(body);
|
||||
});
|
||||
await new Promise<void>(resolveListen => server.listen(0, '127.0.0.1', resolveListen));
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address === 'object');
|
||||
return {
|
||||
port: address.port,
|
||||
close: () => new Promise<void>(resolveClose => server.close(() => resolveClose())),
|
||||
};
|
||||
}
|
||||
|
||||
async function sample(page: { screenshot(options: { clip: { x: number; y: number; width: number; height: number }; scale: 'css' }): Promise<Buffer> }, x: number, y: number): Promise<Rgb> {
|
||||
const shot = await page.screenshot({ clip: { x: Math.round(x), y: Math.round(y), width: 1, height: 1 }, scale: 'css' });
|
||||
const [red, green, blue] = pngPixel(shot, 0, 0);
|
||||
return [red, green, blue];
|
||||
}
|
||||
|
||||
test('transparent and faded theme tokens keep lane pixels on the page surface', { skip, timeout: 30_000 }, async () => {
|
||||
const css = readFileSync(join(root, 'src/client/Reader.module.css'));
|
||||
const files = new Map<string, Buffer | string>([['/reader.css', css]]);
|
||||
const cases = [
|
||||
{ name: 'dark-22-clear', scheme: 'dark' as const, base: 'transparent', layer: 'transparent', label: '#f5f7fa', delta: 8, fontSize: 22, limit: 16 },
|
||||
{ name: 'light-22-clear', scheme: 'light' as const, base: 'transparent', layer: 'transparent', label: '#141414', delta: 8, fontSize: 22, limit: 16 },
|
||||
{ name: 'dark-22-fade', scheme: 'dark' as const, base: 'rgb(255 255 255 / 10%)', layer: 'rgb(255 255 255 / 10%)', label: '#f5f7fa', delta: 8, fontSize: 22, limit: 100 },
|
||||
{ name: 'light-22-fade', scheme: 'light' as const, base: 'rgb(255 255 255 / 10%)', layer: 'rgb(255 255 255 / 10%)', label: '#141414', delta: 8, fontSize: 22, limit: 100 },
|
||||
{ name: 'floor-12', scheme: 'dark' as const, base: 'transparent', layer: 'transparent', label: '#f5f7fa', delta: -2, fontSize: 12, limit: 16 },
|
||||
];
|
||||
for (const item of cases) files.set(`/${item.name}.html`, laneHtml('reader.css', item));
|
||||
const server = await listen(files);
|
||||
const { launchPinnedChromium } = await import(pathToFileURL(browserRuntime).href);
|
||||
const browser = await launchPinnedChromium();
|
||||
mkdirSync(shots, { recursive: true });
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1000, height: 360 }, deviceScaleFactor: 1 });
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', (error: Error) => errors.push(String(error)));
|
||||
for (const item of cases) {
|
||||
await page.goto(`http://127.0.0.1:${server.port}/${item.name}.html`);
|
||||
await page.waitForFunction(() => Reflect.get(window, '__ready') === true);
|
||||
const box = await page.evaluate(() => {
|
||||
const rect = (selector: string) => {
|
||||
const itemRect = document.querySelector(selector)!.getBoundingClientRect();
|
||||
return { top: itemRect.top, right: itemRect.right, bottom: itemRect.bottom, left: itemRect.left, height: itemRect.height };
|
||||
};
|
||||
return { toolbar: rect('.toolbar'), status: rect('[data-reader-lane="status"]'), summary: rect('#summary'), probe: rect('#canvas-probe') };
|
||||
});
|
||||
if (item.fontSize === 12) {
|
||||
assert.ok(box.toolbar.height >= 40, `${item.name} toolbar ${box.toolbar.height}px is under the 40px floor`);
|
||||
assert.ok(box.status.height >= 40, `${item.name} status ${box.status.height}px is under the 40px floor`);
|
||||
} else {
|
||||
assert.ok(box.status.height > 44, `${item.name} status ${box.status.height}px did not grow with the 22px content font`);
|
||||
}
|
||||
await page.evaluate(() => {
|
||||
const scroll = document.querySelector<HTMLElement>('#scroll')!;
|
||||
const summary = document.querySelector('#summary')!.getBoundingClientRect();
|
||||
const heading = document.querySelector('#heading')!.getBoundingClientRect();
|
||||
scroll.scrollTop += heading.top - summary.top;
|
||||
});
|
||||
const points = await page.evaluate(() => {
|
||||
const summary = document.querySelector('#summary')!.getBoundingClientRect();
|
||||
const status = document.querySelector('[data-reader-lane="status"]')!.getBoundingClientRect();
|
||||
const probe = document.querySelector('#canvas-probe')!.getBoundingClientRect();
|
||||
return {
|
||||
summary: { x: summary.left + 10, y: summary.top + 2 },
|
||||
status: { x: status.right - 12, y: status.top + 2 },
|
||||
probe: { x: probe.left + 2, y: probe.top + 2 },
|
||||
};
|
||||
});
|
||||
const canvas = await sample(page, points.probe.x, points.probe.y);
|
||||
const summary = await sample(page, points.summary.x, points.summary.y);
|
||||
const status = await sample(page, points.status.x, points.status.y);
|
||||
const text = item.scheme === 'dark' ? [245, 247, 250] : [20, 20, 20];
|
||||
const glyph: Rgb = [255, 74, 210];
|
||||
const wash: Rgb = [0, 229, 255];
|
||||
const pageTone: Rgb = [255, 0, 170];
|
||||
await page.screenshot({ path: join(shots, `${item.name}.png`) });
|
||||
for (const [place, pixel] of [['summary', summary], ['status', status]] as const) {
|
||||
const message = `${item.name} ${place} pixel ${pixel.join(',')} canvas ${canvas.join(',')} text ${text.join(',')}`;
|
||||
assert.ok(dist(pixel, canvas) <= item.limit, message);
|
||||
assert.ok(dist(pixel, canvas) + 40 < dist(pixel, text), message);
|
||||
assert.ok(dist(pixel, glyph) > 80, message);
|
||||
assert.ok(dist(pixel, wash) > 80, message);
|
||||
assert.ok(dist(pixel, pageTone) > 80, message);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
} finally {
|
||||
await browser.close();
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('stock and glass lanes stay pixel-identical to origin/main', { skip, timeout: 30_000 }, async () => {
|
||||
const headCss = readFileSync(join(root, 'src/client/Reader.module.css'));
|
||||
const mainCss = execFileSync('git', ['show', 'origin/main:src/client/Reader.module.css'], { cwd: root });
|
||||
const files = new Map<string, Buffer | string>([
|
||||
['/head.css', headCss],
|
||||
['/main.css', mainCss],
|
||||
['/stock-head.html', laneHtml('head.css', { scheme: 'light', base: '#223344', layer: '#aabbcc', label: '#f5f7fa', delta: 0, fontSize: 14 })],
|
||||
['/stock-main.html', laneHtml('main.css', { scheme: 'light', base: '#223344', layer: '#aabbcc', label: '#f5f7fa', delta: 0, fontSize: 14 })],
|
||||
['/glass-head.html', laneHtml('head.css', { scheme: 'light', base: '#223344', layer: '#aabbcc', label: '#f5f7fa', delta: 0, fontSize: 14, glass: true })],
|
||||
['/glass-main.html', laneHtml('main.css', { scheme: 'light', base: '#223344', layer: '#aabbcc', label: '#f5f7fa', delta: 0, fontSize: 14, glass: true })],
|
||||
]);
|
||||
const server = await listen(files);
|
||||
const { launchPinnedChromium } = await import(pathToFileURL(browserRuntime).href);
|
||||
const browser = await launchPinnedChromium();
|
||||
mkdirSync(shots, { recursive: true });
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1000, height: 360 }, deviceScaleFactor: 1 });
|
||||
const read = async (path: string) => {
|
||||
await page.goto(`http://127.0.0.1:${server.port}${path}`);
|
||||
await page.waitForFunction(() => Reflect.get(window, '__ready') === true);
|
||||
const points = await page.evaluate(() => {
|
||||
const summary = document.querySelector('#summary')!.getBoundingClientRect();
|
||||
const toolbar = document.querySelector('.toolbar')!.getBoundingClientRect();
|
||||
return {
|
||||
lane: { x: summary.left + 12, y: summary.top + 2 },
|
||||
gap: { x: summary.left + 12, y: summary.top - 4 },
|
||||
toolbar: { x: toolbar.left + 8, y: toolbar.top + 4 },
|
||||
};
|
||||
});
|
||||
return {
|
||||
lane: await sample(page, points.lane.x, points.lane.y),
|
||||
gap: await sample(page, points.gap.x, points.gap.y),
|
||||
toolbar: await sample(page, points.toolbar.x, points.toolbar.y),
|
||||
};
|
||||
};
|
||||
const stockHead = await read('/stock-head.html');
|
||||
await page.screenshot({ path: join(shots, 'stock-head.png') });
|
||||
const stockMain = await read('/stock-main.html');
|
||||
await page.screenshot({ path: join(shots, 'stock-main.png') });
|
||||
const glassHead = await read('/glass-head.html');
|
||||
await page.screenshot({ path: join(shots, 'glass-head.png') });
|
||||
const glassMain = await read('/glass-main.html');
|
||||
await page.screenshot({ path: join(shots, 'glass-main.png') });
|
||||
for (const place of ['lane', 'gap', 'toolbar'] as const) {
|
||||
assert.ok(dist(stockHead[place], stockMain[place]) <= 2, `stock ${place} head ${stockHead[place].join(',')} main ${stockMain[place].join(',')}`);
|
||||
assert.ok(dist(stockHead[place], [34, 51, 68]) <= 2, `stock ${place} left the opaque token: ${stockHead[place].join(',')}`);
|
||||
assert.ok(dist(glassHead[place], glassMain[place]) <= 8, `glass ${place} head ${glassHead[place].join(',')} main ${glassMain[place].join(',')}`);
|
||||
assert.ok(dist(glassHead[place], [255, 0, 170]) <= 12, `glass ${place} painted a plate: ${glassHead[place].join(',')}`);
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
await server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('each Reader root owns its lane height and the floor is 40px', { skip, timeout: 30_000 }, async () => {
|
||||
const harnessPointer = join(homedir(), '.config/dshx/harness');
|
||||
const harness = process.env.DSHX_HARNESS?.trim()
|
||||
|| (existsSync(harnessPointer) ? readFileSync(harnessPointer, 'utf8').trim() : '');
|
||||
assert.ok(harness, 'DSH Harness source not available');
|
||||
const require = createRequire(join(root, 'package.json'));
|
||||
const { build } = createRequire(require.resolve('tsx'))('esbuild');
|
||||
const webRequire = createRequire(join(harness, 'packages/client/web/package.json'));
|
||||
const out = mkdtempSync(join(tmpdir(), 'reader-lane-owners-'));
|
||||
try {
|
||||
await build({
|
||||
entryPoints: [join(root, 'tests/fixtures/reader-lane-owners.tsx')],
|
||||
outfile: join(out, 'fixture.js'),
|
||||
bundle: true,
|
||||
platform: 'browser',
|
||||
format: 'esm',
|
||||
jsx: 'automatic',
|
||||
alias: {
|
||||
react: dirnameOf(require.resolve('react/package.json')),
|
||||
'react-dom': dirnameOf(webRequire.resolve('react-dom/package.json')),
|
||||
},
|
||||
logLevel: 'silent',
|
||||
});
|
||||
const server = await listen(new Map<string, Buffer | string>([
|
||||
['/fixture.js', readFileSync(join(out, 'fixture.js'))],
|
||||
['/', '<!doctype html><div id="app"></div><script type="module" src="/fixture.js"></script>'],
|
||||
]));
|
||||
const { launchPinnedChromium } = await import(pathToFileURL(browserRuntime).href);
|
||||
const browser = await launchPinnedChromium();
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 800, height: 600 }, deviceScaleFactor: 1 });
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', (error: Error) => errors.push(String(error)));
|
||||
await page.goto(`http://127.0.0.1:${server.port}/`);
|
||||
await page.waitForSelector('#row-a');
|
||||
await page.click('#grow');
|
||||
await page.waitForFunction(() => {
|
||||
const row = document.querySelector('#row-a');
|
||||
return !!row && row.getBoundingClientRect().height >= 86;
|
||||
});
|
||||
await page.evaluate(() => new Promise(resolveFrame => requestAnimationFrame(() => requestAnimationFrame(resolveFrame))));
|
||||
const grown = await page.evaluate(() => ({
|
||||
published: document.querySelector<HTMLElement>('#turn-a')!.style.getPropertyValue('--reader-summary-height'),
|
||||
actual: document.querySelector('#row-a')!.getBoundingClientRect().height,
|
||||
other: document.querySelector<HTMLElement>('#turn-b')!.style.getPropertyValue('--reader-summary-height'),
|
||||
short: document.querySelector<HTMLElement>('#turn-short')!.style.getPropertyValue('--reader-status-height'),
|
||||
toolbar: Number.parseFloat(document.querySelector<HTMLElement>('#root-toolbar')!.style.getPropertyValue('--reader-toolbar-height')),
|
||||
status: Number.parseFloat(document.querySelector<HTMLElement>('#turn-status')!.style.getPropertyValue('--reader-status-height')),
|
||||
}));
|
||||
assert.equal(grown.actual, 86, `row a measured ${grown.actual}`);
|
||||
assert.equal(grown.published, '86px', `reader A kept a stale lane height ${grown.published} for an 86px row`);
|
||||
assert.equal(grown.other, '52px', `reader B lane height changed to ${grown.other}`);
|
||||
assert.equal(grown.short, '40px', `38px row published ${grown.short}`);
|
||||
assert.ok(grown.toolbar >= 40, `toolbar lane published ${grown.toolbar}`);
|
||||
assert.ok(grown.status >= 40, `status lane published ${grown.status}`);
|
||||
await page.click('#drop');
|
||||
await page.waitForFunction(() => document.querySelector('#row-a') === null);
|
||||
await page.evaluate(() => new Promise(resolveFrame => requestAnimationFrame(() => requestAnimationFrame(resolveFrame))));
|
||||
const dropped = await page.evaluate(() => ({
|
||||
published: document.querySelector<HTMLElement>('#turn-a')!.style.getPropertyValue('--reader-summary-height'),
|
||||
other: document.querySelector<HTMLElement>('#turn-b')!.style.getPropertyValue('--reader-summary-height'),
|
||||
}));
|
||||
assert.equal(dropped.published, '', `unmounted reader A left ${dropped.published}`);
|
||||
assert.equal(dropped.other, '52px', `unmounting reader A cleared reader B (${dropped.other})`);
|
||||
assert.deepEqual(errors, []);
|
||||
await page.screenshot({ path: join(shots, 'two-roots.png') });
|
||||
} finally {
|
||||
await browser.close();
|
||||
await server.close();
|
||||
}
|
||||
} finally {
|
||||
rmSync(out, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function dirnameOf(file: string) {
|
||||
return file.slice(0, file.lastIndexOf('/'));
|
||||
}
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { test } from 'vitest';
|
||||
import { externalClientBundle } from '../tools/client-build.js';
|
||||
|
||||
const css = readFileSync(resolve('src/client/Reader.module.css'), 'utf8');
|
||||
|
||||
test('sticky lanes follow the host font delta and measured row heights', () => {
|
||||
assert.match(css, /--reader-lane-block:\s*max\(40px,\s*calc\(40px \+ var\(--dsh-content-font-delta, 0px\)\)\)/);
|
||||
assert.match(css, /font-size:\s*calc\(14px \+ var\(--dsh-content-font-delta, 0px\)\)/);
|
||||
assert.match(css, /line-height:\s*calc\(24px \+ var\(--dsh-content-font-delta, 0px\)\)/);
|
||||
assert.match(
|
||||
css,
|
||||
/\.flowCell\[data-flow-summary\], \.closedProcessSummary \{[^}]*top:\s*calc\(var\(--reader-toolbar-height, var\(--reader-lane-block, 40px\)\) \+ var\(--reader-status-height, var\(--reader-lane-block, 40px\)\)\)/,
|
||||
);
|
||||
assert.match(css, /--reader-code-summary-height:\s*var\(--reader-summary-height, var\(--reader-lane-block, 40px\)\)/);
|
||||
assert.doesNotMatch(css, /--reader-sticky-lane/);
|
||||
});
|
||||
|
||||
test('a transparent canvas still masks the lane with the surface token', () => {
|
||||
assert.match(css, /--reader-lane-plate:\s*linear-gradient\(var\(--dsw-alias-bg-base\)/);
|
||||
assert.match(css, /linear-gradient\(var\(--dsw-alias-bg-layer-1, transparent\)/);
|
||||
assert.doesNotMatch(css, /--reader-lane-plate:[^;]*label-primary/);
|
||||
assert.doesNotMatch(css, /--reader-lane-plate:[^;]*color-mix/);
|
||||
assert.match(css, /background-color:\s*Canvas/);
|
||||
assert.match(css, /background-image:\s*var\(--reader-lane-plate\)/);
|
||||
assert.match(css, /\.turnProcessSticky \{ box-shadow:[^;]*\bCanvas\b/);
|
||||
assert.doesNotMatch(css, /\.turnProcessSticky \{ box-shadow:[^;]*label-primary/);
|
||||
assert.match(css, /\.closedProcessSummary \{ box-shadow:[^;]*\bCanvas\b/);
|
||||
assert.match(css, /\.flowCell\[data-flow-summary\] \{ box-shadow:[^;]*\bCanvas\b/);
|
||||
assert.match(css, /\.root\[data-reader-glass\] \.turnProcessSticky/);
|
||||
const glass = css.slice(css.indexOf('Skin mode is opt-in'));
|
||||
assert.match(glass, /background:\s*transparent/);
|
||||
assert.doesNotMatch(glass, /background-color:\s*Canvas/);
|
||||
});
|
||||
|
||||
test('built Reader CSS keeps the lane plate and the measured summary offset', async () => {
|
||||
const configs = externalClientBundle('dsh-better-chat', [], { clientEntry: 'src/client/index.tsx' });
|
||||
const client = configs.find(config => config.name === 'dsh-better-chat/client');
|
||||
const plugin = client?.plugins.find(entry => entry.name === 'dshx-css-modules');
|
||||
assert.ok(plugin);
|
||||
const source = await plugin.load.call({ addWatchFile() {} }, `\0dshx-css-module:${resolve('src/client/Reader.module.css')}.mjs`);
|
||||
const literal = /^const css = (.+);$/m.exec(source)?.[1];
|
||||
assert.ok(literal);
|
||||
const built: unknown = JSON.parse(literal);
|
||||
assert.equal(typeof built, 'string');
|
||||
if (typeof built !== 'string') return;
|
||||
assert.match(built, /--reader-lane-block:max\(40px, calc\(40px \+ var\(--dsh-content-font-delta,0px\)\)\)/);
|
||||
assert.match(built, /--dsw-alias-bg-layer-1,transparent/);
|
||||
assert.match(built, /background-color:canvas/);
|
||||
assert.doesNotMatch(built, /--reader-lane-plate:[^;]*label-primary/);
|
||||
assert.match(built, /var\(--reader-toolbar-height,var\(--reader-lane-block,40px\)\) \+ var\(--reader-status-height,var\(--reader-lane-block,40px\)\)/);
|
||||
});
|
||||
|
|
@ -1,151 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { createServer } from 'node:http';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { inflateSync } from 'node:zlib';
|
||||
import { test } from 'vitest';
|
||||
|
||||
const browserRuntime = join(homedir(), '.codex/playwright-runtime/runtime.mjs');
|
||||
const skip = existsSync(browserRuntime) ? false : 'pinned Chromium runtime not available';
|
||||
|
||||
function paeth(left: number, up: number, upLeft: number) {
|
||||
const estimate = left + up - upLeft;
|
||||
const leftDistance = Math.abs(estimate - left);
|
||||
const upDistance = Math.abs(estimate - up);
|
||||
const diagonal = Math.abs(estimate - upLeft);
|
||||
if (leftDistance <= upDistance && leftDistance <= diagonal) return left;
|
||||
if (upDistance <= diagonal) return up;
|
||||
return upLeft;
|
||||
}
|
||||
|
||||
function pngPixel(buffer: Buffer, x: number, y: number) {
|
||||
let offset = 8;
|
||||
const chunks: Buffer[] = [];
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
let colorType = 0;
|
||||
while (offset < buffer.length) {
|
||||
const length = buffer.readUInt32BE(offset);
|
||||
const type = buffer.toString('ascii', offset + 4, offset + 8);
|
||||
const data = buffer.subarray(offset + 8, offset + 8 + length);
|
||||
if (type === 'IHDR') {
|
||||
width = data.readUInt32BE(0);
|
||||
height = data.readUInt32BE(4);
|
||||
colorType = data[9] ?? 0;
|
||||
} else if (type === 'IDAT') chunks.push(data);
|
||||
else if (type === 'IEND') break;
|
||||
offset += 12 + length;
|
||||
}
|
||||
const bytesPerPixel = colorType === 6 ? 4 : 3;
|
||||
const raw = inflateSync(Buffer.concat(chunks));
|
||||
const stride = width * bytesPerPixel;
|
||||
let source = 0;
|
||||
let previous = Buffer.alloc(stride);
|
||||
const rows: Buffer[] = [];
|
||||
for (let rowIndex = 0; rowIndex < height; rowIndex += 1) {
|
||||
const filter = raw[source] ?? 0;
|
||||
source += 1;
|
||||
const row = Buffer.alloc(stride);
|
||||
for (let index = 0; index < stride; index += 1) {
|
||||
const value = raw[source] ?? 0;
|
||||
source += 1;
|
||||
const left = index >= bytesPerPixel ? row[index - bytesPerPixel] ?? 0 : 0;
|
||||
const up = previous[index] ?? 0;
|
||||
const upLeft = index >= bytesPerPixel ? previous[index - bytesPerPixel] ?? 0 : 0;
|
||||
let decoded = value;
|
||||
if (filter === 1) decoded = value + left;
|
||||
else if (filter === 2) decoded = value + up;
|
||||
else if (filter === 3) decoded = value + Math.floor((left + up) / 2);
|
||||
else if (filter === 4) decoded = value + paeth(left, up, upLeft);
|
||||
else if (filter !== 0) throw new Error(`unsupported png filter ${filter}`);
|
||||
row[index] = decoded & 255;
|
||||
}
|
||||
rows.push(row);
|
||||
previous = row;
|
||||
}
|
||||
const pixel = rows[y];
|
||||
const start = x * bytesPerPixel;
|
||||
return [pixel?.[start] ?? 0, pixel?.[start + 1] ?? 0, pixel?.[start + 2] ?? 0];
|
||||
}
|
||||
|
||||
test('enlarged theme tokens do not let the answer heading share a lane', { skip, timeout: 15_000 }, async () => {
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
const files = new Map([
|
||||
['/Reader.module.css', readFileSync(join(root, 'src/client/Reader.module.css'))],
|
||||
['/MarkdownText.module.css', readFileSync(join(root, 'src/client/markdown/MarkdownText.module.css'))],
|
||||
['/', readFileSync(join(root, 'tests/fixtures/reader-theme-overlap.html'))],
|
||||
]);
|
||||
const server = createServer((request, response) => {
|
||||
const body = files.get(request.url ?? '/');
|
||||
if (!body) { response.statusCode = 404; response.end(); return; }
|
||||
response.setHeader('Content-Type', request.url?.endsWith('.css') ? 'text/css' : 'text/html');
|
||||
response.end(body);
|
||||
});
|
||||
await new Promise<void>(resolveListen => server.listen(0, '127.0.0.1', resolveListen));
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address === 'object');
|
||||
const { launchPinnedChromium } = await import(pathToFileURL(browserRuntime).href);
|
||||
const browser = await launchPinnedChromium();
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1000, height: 320 }, deviceScaleFactor: 1 });
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', (error: Error) => errors.push(String(error)));
|
||||
await page.goto(`http://127.0.0.1:${address.port}/`);
|
||||
await page.waitForFunction(() => Reflect.get(window, '__themeOverlapReady') === true);
|
||||
const atRest = await page.evaluate(() => {
|
||||
const box = (selector: string) => {
|
||||
const rect = document.querySelector(selector)!.getBoundingClientRect();
|
||||
return { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left };
|
||||
};
|
||||
const overlaps = (a: { top: number; right: number; bottom: number; left: number }, b: typeof a) =>
|
||||
a.left < b.right - 1 && a.right > b.left + 1 && a.top < b.bottom - 1 && a.bottom > b.top + 1;
|
||||
const status = box('[data-reader-lane="status"]');
|
||||
const summary = box('#summary');
|
||||
const heading = box('#heading');
|
||||
return {
|
||||
statusOverlapsSummary: overlaps(status, summary),
|
||||
headingOverlapsSummary: overlaps(heading, summary),
|
||||
headingBelowSummary: heading.top >= summary.bottom - 1,
|
||||
};
|
||||
});
|
||||
assert.equal(atRest.statusOverlapsSummary, false);
|
||||
assert.equal(atRest.headingOverlapsSummary, false);
|
||||
assert.equal(atRest.headingBelowSummary, true);
|
||||
|
||||
await page.evaluate(() => {
|
||||
const scroll = document.querySelector<HTMLElement>('#scroll')!;
|
||||
const summary = document.querySelector('#summary')!.getBoundingClientRect();
|
||||
const heading = document.querySelector('#heading')!.getBoundingClientRect();
|
||||
scroll.scrollTop += heading.top - summary.top + 8;
|
||||
});
|
||||
const sample = await page.evaluate(() => {
|
||||
const summary = document.querySelector('#summary')!.getBoundingClientRect();
|
||||
const diff = document.querySelector('#summary .diffStatRoot')!.getBoundingClientRect();
|
||||
return { x: Math.max(summary.left + 8, diff.left - 24), y: summary.top + 2 };
|
||||
});
|
||||
const shot = await page.screenshot({
|
||||
clip: { x: sample.x, y: sample.y, width: 1, height: 1 },
|
||||
scale: 'css',
|
||||
});
|
||||
const [red, green, blue] = pngPixel(shot, 0, 0);
|
||||
assert.ok(Math.abs(red - 16) < 12 && Math.abs(green - 32) < 12 && Math.abs(blue - 64) < 12, `lane plate pixel was ${red},${green},${blue}`);
|
||||
|
||||
await page.evaluate(() => {
|
||||
const scroll = document.querySelector<HTMLElement>('#scroll')!;
|
||||
scroll.scrollTop = scroll.scrollHeight;
|
||||
});
|
||||
const stuck = await page.evaluate(() => {
|
||||
const status = document.querySelector('#flow-status')!.getBoundingClientRect();
|
||||
const summary = document.querySelector('#flow-summary')!.getBoundingClientRect();
|
||||
return { statusBottom: status.bottom, summaryTop: summary.top, statusHeight: status.height };
|
||||
});
|
||||
assert.ok(stuck.statusHeight > 40, `expected the enlarged status row to exceed 40px, got ${stuck.statusHeight}`);
|
||||
assert.ok(stuck.summaryTop >= stuck.statusBottom - 1, `summary top ${stuck.summaryTop} overlaps status bottom ${stuck.statusBottom}`);
|
||||
assert.deepEqual(errors, []);
|
||||
} finally {
|
||||
await browser.close();
|
||||
await new Promise<void>(resolveClose => server.close(() => resolveClose()));
|
||||
}
|
||||
});
|
||||
|
|
@ -1,138 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { createServer } from 'node:http';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
import { homedir, tmpdir } from 'node:os';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { transform } from 'lightningcss';
|
||||
import { test } from 'vitest';
|
||||
import { OFFICIAL_SEATS, OFFICIAL_SLOTS } from '../src/client/official-slots.js';
|
||||
|
||||
// Width is a layout fact of the real Reader and the host user/steering renderer.
|
||||
// This skips in CI, which has no pinned Chromium and no Harness tree.
|
||||
const harnessPointer = join(homedir(), '.config/dshx/harness');
|
||||
const harness = process.env.DSHX_HARNESS?.trim()
|
||||
|| (existsSync(harnessPointer) ? readFileSync(harnessPointer, 'utf8').trim() : '');
|
||||
const browserRuntime = join(homedir(), '.codex/playwright-runtime/runtime.mjs');
|
||||
const skip = !harness ? 'DSH Harness source not available'
|
||||
: !existsSync(browserRuntime) ? 'pinned Chromium runtime not available' : false;
|
||||
|
||||
interface Box { w: number; h: number; font: string; line: string }
|
||||
interface Row {
|
||||
name: string;
|
||||
user: Box; steering: Box; pending: Box;
|
||||
nativeUser: Box; nativeSteering: Box;
|
||||
readerHtml: string;
|
||||
}
|
||||
interface BubbleResult {
|
||||
error?: string;
|
||||
readerSlot?: string;
|
||||
nativeSlot?: string;
|
||||
rows?: Row[];
|
||||
}
|
||||
|
||||
test('reader user and steering bubbles match the host column cap', { skip, timeout: 120_000 }, async () => {
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
const require = createRequire(join(root, 'package.json'));
|
||||
const { build } = createRequire(require.resolve('tsx'))('esbuild');
|
||||
const webRequire = createRequire(join(harness, 'packages/client/web/package.json'));
|
||||
const out = mkdtempSync(join(tmpdir(), 'reader-user-bubble-'));
|
||||
const cssParts: string[] = [];
|
||||
try {
|
||||
const { launchPinnedChromium } = await import(pathToFileURL(browserRuntime).href);
|
||||
await build({
|
||||
entryPoints: [join(root, 'tests/fixtures/reader-user-bubble.tsx')],
|
||||
outfile: join(out, 'fixture.js'), bundle: true, platform: 'browser', format: 'esm', jsx: 'automatic',
|
||||
alias: {
|
||||
'@fixture/registry': join(harness, 'packages/client/ui-renderer/src/client/registry.ts'),
|
||||
'@fixture/renderer': join(harness, 'packages/client/ui-renderer/src/client/scoped-slots.tsx'),
|
||||
'@fixture/user-message': join(harness, 'packages/client/ui-chat/src/client/chat/MessageItem.tsx'),
|
||||
'@fixture/user-content': join(harness, 'packages/client/ui-chat/src/client/chat/UserContent.tsx'),
|
||||
'@deepseek-ai/dsh-client-ui-primitives': join(harness, 'packages/client/ui-primitives/src/index.ts'),
|
||||
'@deepseek-ai/dsh-client-ui-slots': join(harness, 'packages/client/ui-slots/src/index.ts'),
|
||||
'@deepseek-ai/dsh-client-store': join(harness, 'packages/client/store/src/index.ts'),
|
||||
react: dirname(require.resolve('react/package.json')),
|
||||
'react-dom': dirname(webRequire.resolve('react-dom/package.json')),
|
||||
},
|
||||
loader: { '.woff2': 'empty', '.woff': 'empty', '.ttf': 'empty', '.png': 'empty', '.jpg': 'empty', '.webp': 'empty' },
|
||||
plugins: [{
|
||||
name: 'css-modules',
|
||||
setup(build: { onLoad: Function; onEnd: Function }) {
|
||||
build.onLoad({ filter: /\.module\.css$/ }, (args: { path: string }) => {
|
||||
const result = transform({ filename: args.path, code: readFileSync(args.path), cssModules: { pattern: 't[hash]_[local]' } });
|
||||
const mapping: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(result.exports ?? {})) mapping[key] = value.name;
|
||||
cssParts.push(Buffer.from(result.code).toString('utf8'));
|
||||
return { contents: `export default ${JSON.stringify(mapping)};`, loader: 'js' };
|
||||
});
|
||||
build.onLoad({ filter: /\.css$/ }, (args: { path: string }) => {
|
||||
cssParts.push(readFileSync(args.path, 'utf8'));
|
||||
return { contents: 'export default {};', loader: 'js' };
|
||||
});
|
||||
build.onLoad({ filter: /\.svg$/ }, () => ({ contents: 'export default function Svg(){return null}', loader: 'js' }));
|
||||
build.onEnd(() => { writeFileSync(join(out, 'fixture.css'), cssParts.join('\n')); });
|
||||
},
|
||||
}],
|
||||
logLevel: 'silent',
|
||||
});
|
||||
const server = createServer((request, response) => {
|
||||
if (request.url === '/fixture.js') {
|
||||
response.setHeader('Content-Type', 'text/javascript');
|
||||
response.end(readFileSync(join(out, 'fixture.js')));
|
||||
} else if (request.url === '/fixture.css') {
|
||||
response.setHeader('Content-Type', 'text/css');
|
||||
response.end(readFileSync(join(out, 'fixture.css')));
|
||||
} else {
|
||||
response.setHeader('Content-Type', 'text/html');
|
||||
response.end('<!doctype html><meta charset="utf-8"><link rel="stylesheet" href="/fixture.css"><style>html,body{margin:0;font-family:"PingFang SC","Hiragino Sans GB",sans-serif}</style><div id="app"></div><script type="module" src="/fixture.js"></script>');
|
||||
}
|
||||
});
|
||||
await new Promise<void>(resolveListen => server.listen(0, '127.0.0.1', resolveListen));
|
||||
let browser;
|
||||
try {
|
||||
browser = await launchPinnedChromium();
|
||||
const page = await browser.newPage({ viewport: { width: 1400, height: 900 } });
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', (error: Error) => errors.push(String(error)));
|
||||
page.on('console', (message: { type(): string; text(): string }) => {
|
||||
if (message.type() === 'error') errors.push(message.text());
|
||||
});
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address === 'object');
|
||||
await page.goto(`http://127.0.0.1:${address.port}`);
|
||||
await page.waitForFunction(() => 'readerBubbleResult' in window, undefined, { timeout: 20000 });
|
||||
const result = await page.evaluate(() => Reflect.get(window, 'readerBubbleResult')) as BubbleResult;
|
||||
assert.equal(result.error, undefined, result.error);
|
||||
assert.deepEqual(errors, []);
|
||||
assert.equal(result.readerSlot, OFFICIAL_SEATS.nodes);
|
||||
assert.equal(result.nativeSlot, OFFICIAL_SLOTS.nodes);
|
||||
assert.notEqual(result.readerSlot, 'conversation.chat.node');
|
||||
for (const row of result.rows ?? []) {
|
||||
assert.equal(row.user.w, row.nativeUser.w, `${row.name} user width ${row.user.w} != ${row.nativeUser.w} ${row.readerHtml}`);
|
||||
assert.equal(row.user.h, row.nativeUser.h, `${row.name} user height`);
|
||||
assert.equal(row.steering.w, row.nativeSteering.w, `${row.name} steering width`);
|
||||
assert.equal(row.steering.h, row.nativeSteering.h, `${row.name} steering height`);
|
||||
assert.equal(row.pending.w, row.nativeUser.w, `${row.name} pending width`);
|
||||
assert.equal(row.pending.h, row.nativeUser.h, `${row.name} pending height`);
|
||||
assert.equal(row.pending.font, '14px', `${row.name} pending font`);
|
||||
assert.equal(row.pending.line, '22px', `${row.name} pending line`);
|
||||
assert.equal(row.nativeUser.font, '14px', `${row.name} native font`);
|
||||
assert.equal(row.nativeUser.line, '22px', `${row.name} native line`);
|
||||
}
|
||||
const byName = Object.fromEntries((result.rows ?? []).map(row => [row.name, row]));
|
||||
assert.ok(byName.short.user.h < 50, 'a four-glyph message stays on one line');
|
||||
assert.ok(byName.short.user.w < 160, 'a four-glyph message stays content-sized');
|
||||
assert.ok(byName.thirty.user.h < 50, 'thirty glyphs fit on one line at the default column');
|
||||
assert.ok(Math.abs(byName.long.user.w - 748 * 0.702) < 1, 'the default cap follows 748 * 0.702');
|
||||
assert.ok(byName['wide-axis'].user.w > 540, 'a wider content axis is not stuck at 525px');
|
||||
assert.ok(Math.abs(byName.narrow.user.w - 480 * 0.82) < 1, 'a narrow column uses 82% of the column');
|
||||
assert.ok(byName.short.steering.h < 50, 'a short steering message stays on one line');
|
||||
} finally {
|
||||
await browser?.close();
|
||||
await new Promise<void>(resolveClose => server.close(() => resolveClose()));
|
||||
}
|
||||
} finally {
|
||||
rmSync(out, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
|
@ -1,229 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { test } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { runInNewContext } from 'node:vm';
|
||||
import ts from 'typescript';
|
||||
|
||||
const source = readFileSync(new URL('../src/client/motion.tsx', import.meta.url), 'utf8');
|
||||
const retiring = source.slice(source.indexOf('export function RetiringContent('), source.indexOf('// DOM-only behavior:'));
|
||||
const compiled = ts.transpileModule(`const EASING = 'cubic-bezier(.22,1,.36,1)';\n${retiring}`, {
|
||||
fileName: 'retiring.tsx',
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX },
|
||||
}).outputText;
|
||||
|
||||
// Drive the component's real effect with deterministic hooks and a compositor
|
||||
// that never finishes unless the test explicitly sends onfinish.
|
||||
function mount(options?: { containsFocus?: boolean; hidden?: boolean }) {
|
||||
let cursor = 0;
|
||||
let enabled = true;
|
||||
const hooks: unknown[] = [];
|
||||
const effects = new Map<number, { deps: unknown[]; cleanup?: () => void }>();
|
||||
let pending: Array<{ index: number; run: () => (() => void) | void; deps: unknown[] }> = [];
|
||||
let timerId = 0;
|
||||
const timers = new Map<number, { run: () => void; duration: number }>();
|
||||
const animations: Array<{ onfinish?: () => void; cancelled: number }> = [];
|
||||
const cutFocus = { id: 'focus-cut' };
|
||||
const outside = { id: 'outside' };
|
||||
const listeners = new Set<() => void>();
|
||||
const column = {
|
||||
id: 'reader-column',
|
||||
tabIndex: -1,
|
||||
focus() { page.active = column; },
|
||||
};
|
||||
const page = {
|
||||
hidden: options?.hidden ?? false,
|
||||
active: (options?.containsFocus ? cutFocus : null) as { id: string } | null,
|
||||
};
|
||||
const element = {
|
||||
contains: (node: unknown) => node === cutFocus,
|
||||
closest: (selector: string) => selector === '[data-chat-flow]' ? column : null,
|
||||
parentElement: null,
|
||||
getBoundingClientRect: () => ({ height: 64 }),
|
||||
animate: (_frames: unknown, options: { duration: number; fill: string }) => {
|
||||
assert.equal(options.duration, 220);
|
||||
assert.equal(options.fill, 'both');
|
||||
const animation = { cancelled: 0, cancel() { this.cancelled++; } };
|
||||
animations.push(animation);
|
||||
return animation;
|
||||
},
|
||||
};
|
||||
const effect = (run: () => (() => void) | void, deps: unknown[]) => {
|
||||
const index = cursor++;
|
||||
const previous = effects.get(index);
|
||||
if (!previous || deps.some((value, at) => value !== previous.deps[at])) pending.push({ index, run, deps });
|
||||
};
|
||||
const exports: { RetiringContent?: (props: { visible: boolean; children: string }) => unknown } = {};
|
||||
runInNewContext(compiled, {
|
||||
exports,
|
||||
require: createRequire(import.meta.url),
|
||||
css: { retiringContent: 'retiring' },
|
||||
StreamMotionContext: {},
|
||||
HTMLElement: globalThis.HTMLElement,
|
||||
Element: globalThis.Element,
|
||||
document: {
|
||||
get activeElement() { return page.active; },
|
||||
get hidden() { return page.hidden; },
|
||||
addEventListener: (type: string, listener: () => void) => { if (type === 'visibilitychange') listeners.add(listener); },
|
||||
removeEventListener: (type: string, listener: () => void) => { if (type === 'visibilitychange') listeners.delete(listener); },
|
||||
},
|
||||
window: {
|
||||
setTimeout: (run: () => void, duration: number) => { timers.set(++timerId, { run, duration }); return timerId; },
|
||||
clearTimeout: (id: number) => { timers.delete(id); },
|
||||
},
|
||||
useContext: () => ({ enabled }),
|
||||
useRef: (initial: unknown) => {
|
||||
const index = cursor++;
|
||||
if (!(index in hooks)) hooks[index] = { current: initial };
|
||||
return hooks[index];
|
||||
},
|
||||
useState: (initial: unknown) => {
|
||||
const index = cursor++;
|
||||
if (!(index in hooks)) hooks[index] = initial;
|
||||
return [hooks[index], (value: unknown) => { hooks[index] = value; }];
|
||||
},
|
||||
useLayoutEffect: effect,
|
||||
useEffect: effect,
|
||||
});
|
||||
assert.equal(typeof exports.RetiringContent, 'function');
|
||||
type Rendered = { ref: { current: unknown }; props: { onBlur: (event: unknown) => void } };
|
||||
let last: Rendered | null = null;
|
||||
const render = (visible: boolean) => {
|
||||
cursor = 0;
|
||||
pending = [];
|
||||
const result = exports.RetiringContent!({ visible, children: 'narration' }) as Rendered | null;
|
||||
last = result;
|
||||
if (result) result.ref.current = element;
|
||||
for (const { index, run, deps } of pending) {
|
||||
effects.get(index)?.cleanup?.();
|
||||
effects.set(index, { deps, cleanup: run() ?? undefined });
|
||||
}
|
||||
return result;
|
||||
};
|
||||
render(true);
|
||||
return {
|
||||
render, timers, animations, listeners,
|
||||
focusId: () => page.active?.id ?? '',
|
||||
// Move focus out of the cut the way a real blur reports it.
|
||||
blur: () => {
|
||||
page.active = outside;
|
||||
last?.props.onBlur({ currentTarget: element, relatedTarget: outside });
|
||||
},
|
||||
hide: () => {
|
||||
page.hidden = true;
|
||||
for (const listener of [...listeners]) listener();
|
||||
},
|
||||
disableMotion: () => { enabled = false; },
|
||||
unmount: () => { for (const effect of effects.values()) effect.cleanup?.(); },
|
||||
deadline: () => {
|
||||
const [id, timer] = [...timers][0] ?? [];
|
||||
assert.ok(timer, 'retiring animation must have a deadline');
|
||||
assert.equal(timer.duration, 460);
|
||||
timers.delete(id);
|
||||
timer.run();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('retiring narration unmounts on its deadline when onfinish never fires', () => {
|
||||
const view = mount();
|
||||
assert.ok(view.render(false));
|
||||
view.deadline();
|
||||
assert.equal(view.animations[0].cancelled, 1);
|
||||
assert.equal(view.render(false), null);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
test('normal finish settles once and removes the deadline on cleanup', () => {
|
||||
const view = mount();
|
||||
view.render(false);
|
||||
view.animations[0].onfinish?.();
|
||||
view.animations[0].onfinish?.();
|
||||
assert.equal(view.animations[0].cancelled, 1);
|
||||
assert.equal(view.render(false), null);
|
||||
view.unmount();
|
||||
assert.equal(view.timers.size, 0);
|
||||
});
|
||||
|
||||
test('visibility reversal and unmount cancel the deadline and release animation fill', () => {
|
||||
const view = mount();
|
||||
view.render(false);
|
||||
const staleFinish = view.animations[0].onfinish;
|
||||
assert.ok(view.render(true));
|
||||
assert.equal(view.timers.size, 0);
|
||||
assert.equal(view.animations[0].cancelled, 1);
|
||||
staleFinish?.();
|
||||
assert.ok(view.render(true));
|
||||
view.render(false);
|
||||
view.unmount();
|
||||
assert.equal(view.timers.size, 0);
|
||||
assert.equal(view.animations[1].cancelled, 1);
|
||||
});
|
||||
|
||||
test('disabled motion retires immediately without an animation or timer', () => {
|
||||
const view = mount();
|
||||
view.disableMotion();
|
||||
view.render(false);
|
||||
assert.equal(view.render(false), null);
|
||||
assert.equal(view.animations.length, 0);
|
||||
assert.equal(view.timers.size, 0);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
test('reduced motion moves focus out of cut content before it unmounts', () => {
|
||||
const reduced = mount({ containsFocus: true });
|
||||
reduced.disableMotion();
|
||||
reduced.render(false);
|
||||
assert.equal(reduced.render(false), null);
|
||||
assert.equal(reduced.focusId(), 'reader-column');
|
||||
assert.equal(reduced.animations.length, 0);
|
||||
reduced.unmount();
|
||||
|
||||
const hidden = mount({ containsFocus: true, hidden: true });
|
||||
hidden.render(false);
|
||||
assert.equal(hidden.render(false), null);
|
||||
assert.equal(hidden.focusId(), 'reader-column');
|
||||
assert.equal(hidden.animations.length, 0);
|
||||
hidden.unmount();
|
||||
|
||||
// The animated path still defers while focus is inside the cut.
|
||||
const playing = mount({ containsFocus: true });
|
||||
assert.ok(playing.render(false));
|
||||
assert.equal(playing.focusId(), 'focus-cut');
|
||||
assert.equal(playing.animations.length, 0);
|
||||
playing.unmount();
|
||||
});
|
||||
|
||||
test('a page hidden while focus defers the collapse retires at once and keeps focus', () => {
|
||||
const view = mount({ containsFocus: true });
|
||||
assert.ok(view.render(false));
|
||||
// The focus-held state re-runs the effect; it must keep waiting, not animate.
|
||||
assert.ok(view.render(false));
|
||||
assert.equal(view.focusId(), 'focus-cut');
|
||||
assert.equal(view.animations.length, 0);
|
||||
assert.equal(view.listeners.size, 1, 'the focus-held path still listens for a hidden page');
|
||||
view.hide();
|
||||
assert.equal(view.render(false), null);
|
||||
assert.equal(view.focusId(), 'reader-column');
|
||||
assert.equal(view.animations.length, 0);
|
||||
assert.equal(view.timers.size, 0);
|
||||
view.unmount();
|
||||
assert.equal(view.listeners.size, 0);
|
||||
});
|
||||
|
||||
test('focus leaving the cut still plays the collapse, bounded by its deadline', () => {
|
||||
const view = mount({ containsFocus: true });
|
||||
view.render(false);
|
||||
view.render(false);
|
||||
assert.equal(view.animations.length, 0);
|
||||
view.blur();
|
||||
assert.ok(view.render(false));
|
||||
assert.equal(view.animations.length, 1);
|
||||
assert.equal(view.listeners.size, 1);
|
||||
view.deadline();
|
||||
assert.equal(view.render(false), null);
|
||||
assert.equal(view.focusId(), 'outside');
|
||||
view.unmount();
|
||||
assert.equal(view.listeners.size, 0);
|
||||
assert.equal(view.timers.size, 0);
|
||||
});
|
||||
|
|
@ -1,128 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { test } from 'vitest';
|
||||
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
|
||||
import { IncomingMessage, ServerResponse } from 'node:http';
|
||||
import { Socket } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
import { createRevealHandler, resolveRevealPath, revealPath, revealRoots } from '../src/reveal.js';
|
||||
import { isAbsoluteWorkspacePath } from '../src/workspace-path.js';
|
||||
import { dirname } from '../src/client/deliverables.js';
|
||||
|
||||
test('absolute parent predicate accepts POSIX, drive and UNC roots only', () => {
|
||||
for (const path of ['/', '/repo', 'C:\\', 'C:/', 'D:\\5- AI\\docs', '\\\\server\\share']) {
|
||||
assert.equal(isAbsoluteWorkspacePath(path), true, path);
|
||||
}
|
||||
for (const path of ['', '.', 'docs', './docs', '../docs', 'C:', 'C:docs', '\\docs']) {
|
||||
assert.equal(isAbsoluteWorkspacePath(path), false, path);
|
||||
}
|
||||
assert.equal(dirname('/a.txt'), '/');
|
||||
assert.equal(dirname('C:\\a.txt'), 'C:\\');
|
||||
assert.equal(dirname('C:/a.txt'), 'C:/');
|
||||
assert.equal(isAbsoluteWorkspacePath(dirname('docs/a.txt')), false);
|
||||
});
|
||||
|
||||
async function workspace(t: { onTestFinished: (cleanup: () => Promise<void>) => void }) {
|
||||
const root = await mkdtemp(join(tmpdir(), 'bd-reveal-'));
|
||||
t.onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
await mkdir(join(root, 'docs'));
|
||||
await writeFile(join(root, 'docs', 'report.md'), 'report');
|
||||
return root;
|
||||
}
|
||||
|
||||
test('relative resolution uses an existing full path, rejects missing and ambiguous matches', async t => {
|
||||
const root = await workspace(t);
|
||||
const other = await workspace(t);
|
||||
assert.equal(resolveRevealPath('docs/report.md', [root]), join(root, 'docs', 'report.md'));
|
||||
assert.equal(resolveRevealPath('docs/report.md', ['/missing-root', root, root]), join(root, 'docs', 'report.md'));
|
||||
assert.throws(() => resolveRevealPath('docs/missing.md', [root]), /not found/);
|
||||
assert.throws(() => resolveRevealPath('docs/report.md', []), /not found/);
|
||||
assert.throws(() => resolveRevealPath('docs/report.md', [root, other]), /ambiguous/);
|
||||
assert.equal(resolveRevealPath('/absolute/file', []), '/absolute/file');
|
||||
});
|
||||
|
||||
test('relative resolution preserves Windows drive and UNC spelling', () => {
|
||||
const exists = (path: string) => ['D:\\5- AI\\docs\\report.md', '\\\\server\\share\\docs\\report.md'].includes(path);
|
||||
assert.equal(resolveRevealPath('docs/report.md', ['D:\\5- AI'], exists), 'D:\\5- AI\\docs\\report.md');
|
||||
assert.equal(resolveRevealPath('docs/report.md', ['\\\\server\\share'], exists), '\\\\server\\share\\docs\\report.md');
|
||||
assert.throws(() => resolveRevealPath('C:report.md', ['D:\\5- AI'], exists), /not workspace-relative/);
|
||||
assert.throws(() => resolveRevealPath('\\report.md', ['D:\\5- AI'], exists), /not workspace-relative/);
|
||||
});
|
||||
|
||||
function context(services: Record<string, unknown>): Context {
|
||||
return { get: (name: string) => services[name] } as unknown as Context;
|
||||
}
|
||||
|
||||
test('host roots use only the target live session or its registered workspace', async () => {
|
||||
const ctx = context({
|
||||
sessions: { get: (id: string) => id === 'target' ? { header: { cwd: '/target' } } : undefined },
|
||||
workspaceRegistry: { list: () => [
|
||||
{ path: '/other', sessionIds: ['other'] },
|
||||
{ path: '/cold', sessionIds: ['cold'] },
|
||||
] },
|
||||
});
|
||||
assert.deepEqual(await revealRoots(ctx, 'target'), ['/target']);
|
||||
assert.deepEqual(await revealRoots(ctx, 'cold'), ['/cold']);
|
||||
assert.deepEqual(await revealRoots(ctx, 'unknown'), []);
|
||||
assert.deepEqual(await revealRoots(ctx, undefined), ['/other', '/cold']);
|
||||
});
|
||||
|
||||
test('cold session roots are read without projections and the observation is disposed', async () => {
|
||||
let disposed = false;
|
||||
const ctx = context({ sessionQuery: {
|
||||
observeSession: async (id: string, options: unknown) => {
|
||||
assert.equal(id, 'cold');
|
||||
assert.deepEqual(options, { projectionMode: 'none' });
|
||||
return { header: { cwd: '/cold' }, [Symbol.dispose]: () => { disposed = true; } };
|
||||
},
|
||||
} });
|
||||
assert.deepEqual(await revealRoots(ctx, 'cold'), ['/cold']);
|
||||
assert.equal(disposed, true);
|
||||
});
|
||||
|
||||
async function request(handler: ReturnType<typeof createRevealHandler>, body: string, method = 'POST') {
|
||||
const req = new IncomingMessage(new Socket());
|
||||
req.method = method;
|
||||
const res = new ServerResponse(req);
|
||||
const response = new Promise<{ status: number; body: string }>(resolve => {
|
||||
res.end = (chunk: string) => {
|
||||
resolve({ status: res.statusCode, body: chunk ?? '' });
|
||||
return res;
|
||||
};
|
||||
});
|
||||
handler(req, res);
|
||||
req.emit('data', body);
|
||||
req.emit('end');
|
||||
return response;
|
||||
}
|
||||
|
||||
test('reveal route resolves a session-relative request and never opens a missing path', async t => {
|
||||
const root = await workspace(t);
|
||||
const opened: string[] = [];
|
||||
const handler = createRevealHandler({
|
||||
roots: async sessionId => { assert.equal(sessionId, 'target'); return [root]; },
|
||||
reveal: path => { opened.push(path); },
|
||||
});
|
||||
assert.deepEqual(await request(handler, JSON.stringify({ path: 'docs/report.md', sessionId: 'target' })), {
|
||||
status: 200, body: '{"ok":true}',
|
||||
});
|
||||
assert.equal((await request(handler, JSON.stringify({ path: 'docs/missing.md', sessionId: 'target' }))).status, 400);
|
||||
assert.deepEqual(opened, [join(root, 'docs', 'report.md')]);
|
||||
assert.equal((await request(handler, '{}')).status, 400);
|
||||
assert.equal((await request(handler, 'invalid')).status, 400);
|
||||
assert.equal((await request(handler, '', 'GET')).status, 405);
|
||||
});
|
||||
|
||||
test('absolute requests bypass root lookup and Explorer receives a quoted verbatim selection', async () => {
|
||||
const path = 'D:\\5- AI\\docs\\report.md';
|
||||
const calls: unknown[] = [];
|
||||
const handler = createRevealHandler({
|
||||
roots: async () => { throw new Error('absolute requests do not need roots'); },
|
||||
reveal: target => revealPath(target, 'win32', (...args) => { calls.push(args); }),
|
||||
});
|
||||
assert.equal((await request(handler, JSON.stringify({ path }))).status, 200);
|
||||
assert.deepEqual(calls, [['explorer.exe', ['/select,"D:\\5- AI\\docs\\report.md"'], {
|
||||
detached: true, stdio: 'ignore', windowsVerbatimArguments: true,
|
||||
}]]);
|
||||
});
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { test } from 'vitest';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import semver from 'semver';
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8')) as {
|
||||
name: string;
|
||||
main: string;
|
||||
scripts?: { prepare?: string };
|
||||
exports: Record<string, { default?: string } | string>;
|
||||
files: string[];
|
||||
dsh: { bundle?: { patch?: string }; client?: { inject?: string[] } };
|
||||
peerDependencies: Record<string, string>;
|
||||
};
|
||||
|
||||
const HARNESS_PEER = '>=0.2.1-rc.1 <0.2.3';
|
||||
|
||||
test('Harness peer range accepts the 0.2.2 line and rejects the 0.2.0 series', () => {
|
||||
const peers = Object.entries(pkg.peerDependencies).filter(([name]) => name.startsWith('@deepseek-ai/dsh-'));
|
||||
assert.ok(peers.length >= 10);
|
||||
for (const [name, range] of peers) {
|
||||
assert.equal(range, HARNESS_PEER, name);
|
||||
assert.equal(semver.satisfies('0.2.2-rc.2', range, { includePrerelease: true }), true, name);
|
||||
assert.equal(semver.satisfies('0.2.1-rc.5', range, { includePrerelease: true }), true, name);
|
||||
assert.equal(semver.satisfies('0.2.1', range, { includePrerelease: true }), true, name);
|
||||
assert.equal(semver.satisfies('0.2.1-alpha.1', range, { includePrerelease: true }), false, name);
|
||||
assert.equal(semver.satisfies('0.2.0-rc.2', range, { includePrerelease: true }), false, name);
|
||||
assert.equal(semver.satisfies('0.2.0', range, { includePrerelease: true }), false, name);
|
||||
assert.equal(semver.satisfies('0.1.7-rc.2', range, { includePrerelease: true }), false, name);
|
||||
}
|
||||
const manifest = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8')) as { engines?: { dsh?: string } };
|
||||
assert.equal(manifest.engines?.dsh, HARNESS_PEER);
|
||||
});
|
||||
|
||||
test('declares dsh.bundle.patch so official add joins the profile layer stack', () => {
|
||||
assert.equal(pkg.dsh.bundle?.patch, './cordis.patch.yml');
|
||||
assert.equal(existsSync(resolve(root, 'cordis.patch.yml')), true);
|
||||
const patch = readFileSync(resolve(root, 'cordis.patch.yml'), 'utf8');
|
||||
assert.match(patch, /id: dsh-better-chat/);
|
||||
assert.match(patch, /name: dsh-better-chat/);
|
||||
assert.equal(pkg.files.includes('cordis.patch.yml'), true);
|
||||
});
|
||||
|
||||
test('commits one merged client bundle and one host entry', () => {
|
||||
assert.equal(pkg.scripts?.prepare, undefined);
|
||||
assert.equal(pkg.name, 'dsh-better-chat');
|
||||
assert.equal(pkg.main, 'lib/host.js');
|
||||
const client = pkg.exports['./client'];
|
||||
assert.equal(typeof client === 'object' && client !== null ? client.default : client, './lib/client.js');
|
||||
assert.equal(existsSync(resolve(root, 'lib/host.js')), true);
|
||||
assert.equal(existsSync(resolve(root, 'lib/client.js')), true);
|
||||
|
||||
const clientJs = readFileSync(resolve(root, 'lib/client.js'), 'utf8');
|
||||
assert.match(clientJs, /window\.__ModuleLoader__\.load/);
|
||||
assert.match(clientJs, /id:\s*"dsh-better-chat"/);
|
||||
// reading view (merged from dsh-better-display)
|
||||
assert.match(clientJs, /conversation\.view/);
|
||||
assert.match(clientJs, /data-reader-glass/);
|
||||
assert.match(clientJs, /foldIntensity/);
|
||||
// chat enhancements (dsh-better-chat)
|
||||
assert.match(clientJs, /data-approval-key/);
|
||||
assert.match(clientJs, /data-better-chat-update/);
|
||||
assert.match(clientJs, /Full access/);
|
||||
});
|
||||
|
||||
test('compiled host entry loads in Node without a TypeScript loader', async () => {
|
||||
// Dynamic import rather than a child process: the desktop sandbox forbids
|
||||
// spawning children with piped stdio.
|
||||
const plugin = await import(new URL('../lib/host.js', import.meta.url).href) as {
|
||||
name?: string;
|
||||
apply?: unknown;
|
||||
};
|
||||
assert.equal(plugin.name, 'dsh-better-chat');
|
||||
assert.equal(typeof plugin.apply, 'function');
|
||||
});
|
||||
|
||||
test('README documents the official install one-liner', () => {
|
||||
for (const name of ['README.md', 'README.en.md']) {
|
||||
const text = readFileSync(resolve(root, name), 'utf8');
|
||||
assert.match(text, /dsh plugin --profile desktop add dsh-better-chat/);
|
||||
assert.doesNotMatch(text, /activate-new-client/);
|
||||
assert.doesNotMatch(text, /my-plugins/);
|
||||
}
|
||||
});
|
||||
|
|
@ -1,75 +0,0 @@
|
|||
import assert from 'node:assert/strict';
|
||||
import { test } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { ensureStyles } from '../src/client/styles.js';
|
||||
|
||||
test('ensureStyles tolerates module evaluation without a document', () => {
|
||||
ensureStyles();
|
||||
});
|
||||
|
||||
test('ensureStyles restores removed plugin CSS and remains idempotent', t => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(globalThis, 'document');
|
||||
t.onTestFinished(() => {
|
||||
if (descriptor) Object.defineProperty(globalThis, 'document', descriptor);
|
||||
else Reflect.deleteProperty(globalThis, 'document');
|
||||
});
|
||||
const reader = { dataset: { plugin: 'dsh-better-display', pluginCss: 'dsh-better-display/Reader.module.css' }, textContent: '.reader{height:auto}' };
|
||||
const fold = { dataset: { plugin: 'dsh-better-display', pluginCss: 'dsh-better-display/Fold.module.css' }, textContent: '.fold{overflow:hidden}' };
|
||||
const foreign = { dataset: { plugin: 'other', pluginCss: 'other/Fold.module.css' }, textContent: '.other{}' };
|
||||
const tags = [reader, fold, foreign];
|
||||
const document = {
|
||||
querySelectorAll: (selector: string) => {
|
||||
assert.equal(selector, 'style[data-plugin="dsh-better-display"][data-plugin-css]');
|
||||
return tags.filter(tag => tag.dataset.plugin === 'dsh-better-display');
|
||||
},
|
||||
createElement: (name: string) => { assert.equal(name, 'style'); return { dataset: {}, textContent: '' }; },
|
||||
head: { appendChild: (tag: typeof reader) => { tags.push(tag); } },
|
||||
};
|
||||
Object.defineProperty(globalThis, 'document', { configurable: true, value: document });
|
||||
ensureStyles();
|
||||
assert.equal(tags.length, 3);
|
||||
tags.splice(0, 2);
|
||||
ensureStyles();
|
||||
assert.deepEqual(tags, [foreign, reader, fold]);
|
||||
ensureStyles();
|
||||
assert.equal(tags.length, 3);
|
||||
tags[1].textContent = '.reader{height:100px}';
|
||||
ensureStyles();
|
||||
tags.splice(1, 1);
|
||||
ensureStyles();
|
||||
assert.equal(tags.find(tag => tag.dataset.pluginCss === reader.dataset.pluginCss)?.textContent, '.reader{height:100px}');
|
||||
});
|
||||
|
||||
test('CSS is cached after module injection and restored before mount layout effects', () => {
|
||||
const index = readFileSync(new URL('../src/client/reader-plugin.tsx', import.meta.url), 'utf8');
|
||||
const reader = readFileSync(new URL('../src/client/Reader.tsx', import.meta.url), 'utf8');
|
||||
assert.match(index, /\nensureStyles\(\);/);
|
||||
// Whitespace-tolerant: the source is formatted by the project's own toolchain,
|
||||
// which may break the effect body onto its own line.
|
||||
assert.match(reader, /useInsertionEffect\(\(\) => \{[\s\S]{0,40}?ensureStyles\(\);[\s\S]{0,20}?\}, \[\]\)/);
|
||||
});
|
||||
|
||||
test('user cluster fills the column so the host cap resolves once', () => {
|
||||
const css = readFileSync(new URL('../src/client/Reader.module.css', import.meta.url), 'utf8');
|
||||
const cluster = css.match(/\.userCluster\s*\{[^}]*\}/)?.[0] ?? '';
|
||||
assert.match(cluster, /width:\s*100%/);
|
||||
assert.match(cluster, /max-width:\s*100%/);
|
||||
assert.doesNotMatch(cluster, /0\.702/);
|
||||
assert.doesNotMatch(cluster, /525px/);
|
||||
assert.doesNotMatch(css, /525px/);
|
||||
// A direct-child cap misses the display:contents slot. The host row is the
|
||||
// slot's child; capping that grandchild would replace .userStack's own 82%.
|
||||
assert.doesNotMatch(css, /\.userCluster\s*>\s*\*/);
|
||||
assert.doesNotMatch(css, /\[data-slot="conversation\.chat\.node"\]/);
|
||||
assert.match(css, /\.userCluster > \[data-slot\] > \* \{[^}]*align-self:\s*stretch/);
|
||||
assert.match(css, /\.userCluster > \[data-slot\] > \* \{[^}]*width:\s*100%/);
|
||||
assert.doesNotMatch(css, /\.userCluster > \[data-slot\] > \* > \*/);
|
||||
const user = css.match(/\.user\s*\{[^}]*\}/)?.[0] ?? '';
|
||||
assert.match(user, /max-width:\s*min\(calc\(var\(--dsh-chat-content-width,\s*748px\)\s*\*\s*0\.702\),\s*82%\)/);
|
||||
assert.match(user, /font-size:\s*var\(--dsh-content-font-size,\s*14px\)/);
|
||||
assert.match(user, /line-height:\s*calc\(22px \+ var\(--dsh-content-font-delta,\s*0px\)\)/);
|
||||
assert.match(user, /font-weight:\s*400/);
|
||||
assert.match(user, /white-space:\s*pre-wrap/);
|
||||
assert.match(user, /border-radius:\s*var\(--dsw-radius-xl,\s*22px\)/);
|
||||
assert.doesNotMatch(css, /\.user\s*\{\s*max-width:\s*90%/);
|
||||
});
|
||||
|
|
@ -1,113 +0,0 @@
|
|||
import { test } from 'vitest';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { PreparingToolCall, RunningToolCall, ToolResultNode } from '@deepseek-ai/dsh-client-ui-conversation/client';
|
||||
import { activityPhase, activitySummary } from '../src/client/tool-activity.ts';
|
||||
import type { ToolDraft } from '../src/client/tool-activity.ts';
|
||||
|
||||
function draft(name: string, argsRaw: string): ToolDraft {
|
||||
return { kind: 'tool-call', callId: 'terminal-preview', name, argsRaw };
|
||||
}
|
||||
|
||||
test('terminal drafts expose a pending placeholder state until a command field appears', () => {
|
||||
for (const name of ['bash', 'pwsh']) {
|
||||
const early = activitySummary({ draft: draft(name, '{"comman') });
|
||||
assert.equal(early.category, 'terminal');
|
||||
assert.equal(early.argsState, 'partial');
|
||||
assert.equal(early.command, undefined);
|
||||
|
||||
const partial = activitySummary({ draft: draft(name, '{"command":"Get-C') });
|
||||
assert.equal(partial.argsState, 'partial');
|
||||
assert.equal(partial.command, 'Get-C');
|
||||
}
|
||||
});
|
||||
|
||||
test('complete Bash and PowerShell arguments remain available in full', () => {
|
||||
for (const name of ['bash', 'pwsh']) {
|
||||
const values = {
|
||||
command: name === 'pwsh' ? 'Get-ChildItem -Force' : 'printf "ready\\n"',
|
||||
workdir: '/work/project',
|
||||
description: 'List project files',
|
||||
timeout_ms: 4000,
|
||||
};
|
||||
const model = activitySummary({ draft: draft(name, JSON.stringify(values)) });
|
||||
assert.equal(model.argsState, 'complete');
|
||||
assert.equal(model.command, values.command);
|
||||
assert.deepEqual(model.args, values);
|
||||
}
|
||||
});
|
||||
|
||||
test('partial escaped and multiline commands keep their authored text', () => {
|
||||
const argsRaw = '{"command":"printf \\"first\\nsecond';
|
||||
const model = activitySummary({ draft: draft('bash', argsRaw) });
|
||||
assert.equal(model.argsState, 'partial');
|
||||
assert.equal(model.command, 'printf "first\nsecond');
|
||||
|
||||
const multiline = 'printf "first line\\nsecond line"\necho 你好';
|
||||
const complete = activitySummary({ draft: draft('bash', JSON.stringify({ command: multiline, workdir: '/tmp' })) });
|
||||
assert.equal(complete.command, multiline);
|
||||
assert.equal(complete.args.workdir, '/tmp');
|
||||
});
|
||||
|
||||
test('complete empty and non-command arguments are not mistaken for partial commands', () => {
|
||||
const empty = activitySummary({ draft: draft('bash', '{}') });
|
||||
assert.equal(empty.argsState, 'complete');
|
||||
assert.deepEqual(empty.args, {});
|
||||
assert.equal(empty.command, undefined);
|
||||
|
||||
const read = activitySummary({ draft: draft('read', '{"path":"/tmp/readme.md"}') });
|
||||
assert.equal(read.argsState, 'complete');
|
||||
assert.equal(read.category, 'read');
|
||||
assert.equal(read.command, undefined);
|
||||
assert.equal(read.args.path, '/tmp/readme.md');
|
||||
});
|
||||
|
||||
test('the activity lifecycle distinguishes draft, dispatched call, and result', () => {
|
||||
const argsRaw = '{"command":"echo ready"}';
|
||||
const pending = draft('bash', argsRaw);
|
||||
const running: RunningToolCall = {
|
||||
phase: 'start', callId: pending.callId, name: pending.name, turn: 1, step: 0, time: 1000, argsRaw, subCalls: [],
|
||||
};
|
||||
const result: ToolResultNode = {
|
||||
kind: 'tool-result', seq: 2, time: 2000, callId: pending.callId,
|
||||
call: { name: pending.name, argsRaw }, callTime: 1000,
|
||||
content: [{ type: 'text', text: 'ready\n[exit code: 0]' }], isError: false, meta: { exitCode: 0 }, subCalls: [],
|
||||
};
|
||||
assert.equal(activityPhase({ draft: pending }), 'preparing');
|
||||
assert.equal(activityPhase({ block: running }), 'running');
|
||||
assert.equal(activityPhase({ block: result }), 'succeeded');
|
||||
});
|
||||
|
||||
test('a canonical preparing call remains preparing until dispatch', () => {
|
||||
for (const name of ['bash', 'pwsh']) {
|
||||
const block: PreparingToolCall = {
|
||||
phase: 'preparing', callId: 'preparing-head', name, turn: 1, step: 0, time: 1000, subCalls: [],
|
||||
};
|
||||
assert.equal(activityPhase({ block }), 'preparing');
|
||||
assert.equal(activityPhase({ block }, true), 'interrupted');
|
||||
const model = activitySummary({ block });
|
||||
assert.equal(model.name, name);
|
||||
assert.equal(model.argsState, 'partial');
|
||||
assert.equal(model.raw, '');
|
||||
assert.equal(model.command, undefined);
|
||||
}
|
||||
});
|
||||
|
||||
test('a canonical preparing head retains progressively generated draft arguments', () => {
|
||||
for (const name of ['bash', 'pwsh']) {
|
||||
const block: PreparingToolCall = {
|
||||
phase: 'preparing', callId: 'preparing-head', name, turn: 1, step: 0, time: 1000, subCalls: [],
|
||||
};
|
||||
for (const raw of ['{"comman', '{"command":"echo ready']) {
|
||||
const pending = { ...draft(name, raw), callId: block.callId };
|
||||
const model = activitySummary({ block, draft: pending });
|
||||
assert.equal(model.raw, raw);
|
||||
assert.equal(model.argsState, 'partial');
|
||||
assert.equal(model.command, raw === '{"comman' ? undefined : 'echo ready');
|
||||
}
|
||||
const dispatched: RunningToolCall = { ...block, phase: 'start', argsRaw: '{"command":"echo sent"}' };
|
||||
const model = activitySummary({ block: dispatched, draft: draft(name, '{"command":"stale') });
|
||||
assert.equal(activityPhase({ block: dispatched }), 'running');
|
||||
assert.equal(model.command, 'echo sent');
|
||||
assert.equal(model.argsState, 'complete');
|
||||
}
|
||||
});
|
||||
|
|
@ -2,10 +2,8 @@ import { defineConfig } from 'vitest/config'
|
|||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
// tests/*.test.ts is the reading-view suite (upstream dsh-better-display);
|
||||
// tests/chat/*.test.ts covers the chat enhancements carried over from
|
||||
// dsh-better-chat. Workers use threads because the desktop sandbox forbids
|
||||
// spawning child processes with piped stdio.
|
||||
// Chat suites live under tests/chat/*.test.ts. Workers use threads because
|
||||
// the desktop sandbox forbids spawning child processes with piped stdio.
|
||||
include: ['tests/**/*.test.ts'],
|
||||
pool: 'threads',
|
||||
environment: 'node',
|
||||
|
|
|
|||
Loading…
Reference in New Issue