Compare commits
18 Commits
fix/permis
...
main
| Author | SHA1 | Date |
|---|---|---|
|
|
418139e5a2 | |
|
|
bafa057457 | |
|
|
3135e80085 | |
|
|
9c0ee58021 | |
|
|
fa18351a16 | |
|
|
36785ffa08 | |
|
|
f57a74cd8b | |
|
|
f87055b75b | |
|
|
7774d6fc28 | |
|
|
5c80061f08 | |
|
|
010a3d4e8b | |
|
|
eeac9d7e2a | |
|
|
3168c2a341 | |
|
|
6ed202f029 | |
|
|
a4844006a6 | |
|
|
f50d36874d | |
|
|
1b3bb75a0f | |
|
|
e3b27d98f8 |
|
|
@ -1,3 +1,7 @@
|
||||||
node_modules/
|
node_modules/
|
||||||
*.log
|
*.log
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
.pnpm-store/
|
||||||
|
.build-spike/
|
||||||
|
.preview/
|
||||||
|
dsh-image-gen/
|
||||||
|
|
|
||||||
65
CHANGELOG.md
65
CHANGELOG.md
|
|
@ -1,5 +1,70 @@
|
||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 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
|
||||||
|
|
||||||
|
首个可用版本。单个插件同时提供阅读视图与聊天增强:
|
||||||
|
|
||||||
|
- 审批卡键帽提示,以及 Enter / Ctrl+Enter(Mac 为 Cmd+Enter)/ Esc 路由;可在 Better Chat 设置里自定义绑定、清除「始终允许」或恢复默认;
|
||||||
|
- 权限 UI 移除「完全权限」选项,不改写已有会话的权限;
|
||||||
|
- 插件商店「更新」按钮;
|
||||||
|
- 设置节改名 Better Chat,并使用独立的 locale 命名空间与节 id,不再与独立 display 插件互相覆盖;
|
||||||
|
- 移除无用的 generative-mcpapps 技能检测块及其宿主路由、扫描实现与随包技能;
|
||||||
|
- 构建为 tsdown + 随仓库的 dshx 0.9.7 客户端适配器,目标平台表固定 dsh-v0.2.2-rc.2。
|
||||||
|
|
||||||
|
## 0.4.4 — 2026-11-12
|
||||||
|
|
||||||
|
- 删除设置里的 `generative-mcpapps` 技能检测/安装块(对用户无用):同时移除客户端探测、宿主技能状态路由、技能扫描实现、随包 `skills/generative-mcpapps` 技能包,以及对应的文案与测试。阅读页仍会渲染模型自己写出的 `mcp-app` 代码块,只是不再检测/引导安装该技能。
|
||||||
|
|
||||||
|
## 0.4.3 — 2026-11-12
|
||||||
|
|
||||||
|
- 修复设置项标题在旧名称 / Better Chat 之间来回变的问题:合并后的插件此前复用了旧独立插件的设置节 id 与 locale 命名空间,两个插件同时安装时后注册的会覆盖前者,标题随加载顺序翻转。现在改用独立的 `better-chat` 节 id 与 locale 命名空间,互不覆盖。
|
||||||
|
- 注意:README 已写明更新时必须同时从 profile 移除独立的旧阅读视图插件,否则会同时出现两个设置节(以及两套阅读页注册)。
|
||||||
|
|
||||||
|
## 0.4.2 — 2026-11-12
|
||||||
|
|
||||||
|
- 设置页的旧选项栏改名为 **Better Chat**(中英文案同步)。
|
||||||
|
- 审批快捷键可自定义并写入插件配置(持久化键 `dsh.better-chat.v1`):允许(单次)/始终允许/拒绝三行,点键帽后按新组合键即可录制;基础键固定为 Enter(允许类)与 Esc(拒绝),修饰键自由,支持清除「始终允许」和恢复默认。冲突、缺少修饰键、用错基础键都会在设置页提示并拒绝保存。
|
||||||
|
- 审批卡上的键帽提示与按键判定都读取实时配置:保存后卡片提示立即重建,无需重启 DSH。
|
||||||
|
|
||||||
|
## 0.4.1 — 2026-11-12
|
||||||
|
|
||||||
|
- 审批卡新增键盘提示(方案 A):操作行左侧显示 `Enter 允许(单次) · Ctrl+Enter 始终允许 · Esc 拒绝` 的键帽提示,文案直接取卡片按钮的实际文字;卡片作答后立即移除,React 重渲染后自动重建。鼠标不可点、不参与焦点,纯说明。
|
||||||
|
- 新增 **Ctrl+Enter / Cmd+Enter = 始终允许**(仅当卡片有第三个按钮时生效)。官方卡片原本对带修饰键的按键不作答,所以这条即使在卡片内(自动送入焦点后)也由本插件处理;正在输入控件里打字时不拦截。Mac 上提示显示 Cmd+Enter。
|
||||||
|
- 新增 `tests/chat/key-hint.test.ts`(提示分段、平台键、插入/移除),并补充 Ctrl/Cmd+Enter 的判定测试。
|
||||||
|
|
||||||
|
## 0.4.0 — 2026-11-12
|
||||||
|
|
||||||
|
- 合并旧阅读视图插件的阅读视图:源码、样式、文档、技能包、设置页与
|
||||||
|
上游测试全部并入本仓库。单包、单 Web 客户端产物(id `dsh-better-chat`),一个插件
|
||||||
|
同时提供阅读页和聊天增强。
|
||||||
|
- 构建切换到 tsdown + dshx 0.9.7 的客户端打包适配器(`tools/client-build.js`);目标
|
||||||
|
DSH 平台模块表固定为随仓库的 dsh-v0.2.2-rc.2 副本,可用 `DSHX_HARNESS` 覆盖。
|
||||||
|
- 阅读视图 CSS 构建固定 Safari 15.4 targets,保留 `-webkit-backdrop-filter` 回退。
|
||||||
|
- 聊天增强保持不变:审批回车批准 / Esc 拒绝、权限 UI(移除完全权限)、插件商店
|
||||||
|
「更新」按钮。测试迁到 vitest(`tests/chat/`),阅读视图上游套件按新包结构重新基线。
|
||||||
|
|
||||||
## 0.3.1 — 2026-11-12
|
## 0.3.1 — 2026-11-12
|
||||||
|
|
||||||
- 权限策略只保留「界面移除完全权限」:删除页面加载/刷新/插件重载时遍历已有会话并执行 `/permission auto` 的行为。已有会话的只读、工作区修改、完全权限选择不再被插件覆盖;默认值交给宿主的新建会话流程。新增回归测试覆盖两次挂载均无权限命令。
|
- 权限策略只保留「界面移除完全权限」:删除页面加载/刷新/插件重载时遍历已有会话并执行 `/permission auto` 的行为。已有会话的只读、工作区修改、完全权限选择不再被插件覆盖;默认值交给宿主的新建会话流程。新增回归测试覆盖两次挂载均无权限命令。
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,26 @@
|
||||||
|
# dsh-better-chat
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
```sh
|
||||||
|
dsh plugin --profile desktop add dsh-better-chat
|
||||||
|
```
|
||||||
|
|
||||||
|
From this repository (pin a commit):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
dsh plugin --profile desktop add git+https://git.qyhhh.top/DeepsSeekHarness/dsh-better-chat.git#<commit>
|
||||||
|
```
|
||||||
|
|
||||||
|
The compiled `lib/` is committed, so installation needs no build step. Fully restart DSH afterwards.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **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.
|
||||||
72
README.md
72
README.md
|
|
@ -1,70 +1,26 @@
|
||||||
# dsh-better-chat
|
# dsh-better-chat
|
||||||
|
|
||||||
DSH 聊天增强插件。
|
DSH 聊天增强插件:审批卡回车批准 / Esc 拒绝、权限 UI、插件商店更新,以及新建空白会话默认切到「自动审查」。
|
||||||
|
|
||||||
## 功能一:审批时回车批准、Esc 拒绝(v0.1.0)
|
> 旧的阅读视图已于 1.0.4 彻底移除,本插件不再提供「阅读」页签,也不再包含其源码、设计文档或许可证。
|
||||||
|
|
||||||
DSH 官方审批卡(`@deepseek-ai/dsh-client-ui-approval`)本身就支持
|
## 安装
|
||||||
Enter 批准、Esc 拒绝,但前提是**焦点先落在审批卡里**。审批弹出时焦点
|
|
||||||
通常还在对话区,回车按下去没有反应,得先拿鼠标点一下卡片。
|
|
||||||
|
|
||||||
本插件补上这一段,不改官方逻辑:
|
```sh
|
||||||
|
|
||||||
1. **自动送入焦点**:审批卡出现时,如果你没有正在别处输入,就把焦点
|
|
||||||
送进卡片的详情区,官方的回车/Esc 立即生效。
|
|
||||||
2. **全局兜底路由**:焦点不在卡片内时(比如点了别处又想作答),在
|
|
||||||
document 捕获阶段接住回车/Esc,点击卡片上的按钮。回车永远点
|
|
||||||
「允许(单次)」,不会误触「始终允许」;Esc 点「拒绝」。
|
|
||||||
|
|
||||||
防误触(与官方卡片内部规则对齐):
|
|
||||||
|
|
||||||
- 正在任何输入框/编辑区打字时不拦截;
|
|
||||||
- 焦点已在卡片内时完全交给官方处理,不重复作答;
|
|
||||||
- 带 Ctrl/Meta/Alt/Shift、长按连发、输入法组词中不拦截;
|
|
||||||
- 回车落在某个按钮/链接上时,保留那个按钮自己的行为;
|
|
||||||
- 卡片已作答或按钮禁用时不动作。
|
|
||||||
|
|
||||||
已知边界:焦点停在另一个面板的输入框里时(例如设置页搜索框),为防
|
|
||||||
误触不会抢焦点、也不会路由按键,需要先点一下审批卡——与原生行为一致。
|
|
||||||
|
|
||||||
## 安装(DSH 桌面端)
|
|
||||||
|
|
||||||
```
|
|
||||||
dsh plugin --profile desktop add dsh-better-chat
|
dsh plugin --profile desktop add dsh-better-chat
|
||||||
```
|
```
|
||||||
|
|
||||||
完全重启 DSH 后生效。本地验证:`npm test`(判定逻辑单元测试)。
|
从本仓库安装(钉住提交):
|
||||||
|
|
||||||
## 真机验收点
|
```sh
|
||||||
|
dsh plugin --profile desktop add git+https://git.qyhhh.top/DeepsSeekHarness/dsh-better-chat.git#<commit>
|
||||||
|
```
|
||||||
|
|
||||||
- 触发一次工具审批:不点鼠标,直接按回车应批准(单次)、Esc 应拒绝;
|
编译好的 `lib/` 已提交,安装时不需要构建。装完彻底重启 DSH。
|
||||||
- 审批等待时在输入框打字,回车应照常发送/换行,不被劫持;
|
|
||||||
- 审批等待时点开别处按钮,回车应执行那个按钮而不是批准。
|
|
||||||
|
|
||||||
## 功能二:权限 UI(v0.2.0,v0.3.1 收紧)
|
## 功能
|
||||||
|
|
||||||
- **去掉「完全权限」选项**:权限选择器(`/permission` 弹出菜单、composer
|
- **审批快捷键**:审批卡上回车批准、Esc 拒绝;可在「设置 → Better Chat」里自定义绑定、清除「始终允许」或恢复默认。
|
||||||
权限菜单)和通用设置的默认权限下拉里,标签为「完全权限 / Full access」
|
- **权限 UI**:权限选择里移除「完全权限」;不改写已有会话的权限。
|
||||||
的选项会被摘除。只动界面:手动输入 `/permission danger-full-access`
|
- **默认自动审查**:新建空白顶层会话自动切到 `auto`(需启用 `@deepseek-ai/dsh-experimental-auto-review`);刷新/重启不会覆盖用户手动切换。
|
||||||
命令仍可达,那是宿主行为。
|
- **插件商店更新**:为插件商店提供「更新」按钮。
|
||||||
- **不覆盖已有会话权限**:插件不再在页面加载、刷新或重载时遍历会话改
|
|
||||||
权限。已有会话的只读/工作区/完全权限选择完全由用户与宿主决定;默认
|
|
||||||
自动审查只属于宿主自己的新建会话流程,本插件没有可靠的新建扩展点,
|
|
||||||
因此不拿轮询补偿。需要自动审查时,请在宿主的权限选择器里显式选择。
|
|
||||||
|
|
||||||
真机验收点(功能二):
|
|
||||||
|
|
||||||
1. 打开权限选择器 → 没有「完全权限」一项;设置里的默认权限下拉同样没有。
|
|
||||||
2. 手动把某个会话切到「仅可查看」→ 刷新、重连、插件重载后仍是「仅可查看」。
|
|
||||||
3. 新建会话的默认权限由宿主/用户选择决定,插件不替用户改写。
|
|
||||||
|
|
||||||
## 功能三:插件商店「更新」按钮(v0.3.0)
|
|
||||||
|
|
||||||
DSH 只给官方插件原地更新;从自定义索引装的插件在发现页只有「有新版本」标签、没有按钮,只能手动卸载重装。本功能在发现页给每个「有新版本」的条目补一个「更新到 x.y.z」按钮:
|
|
||||||
|
|
||||||
- 数据与动作都走宿主自己的远程服务:`remote.pluginMarket` 查各索引的安装状态与每版的精确安装 spec,`remote.pluginManager.installBundle` 按 spec 覆盖安装——与官方安装流程同一套接口,不模拟点击、不动官方状态。覆盖安装经实测可直接把已装旧版换成新版。
|
|
||||||
- 点击先弹确认框(插件名、旧版 → 新版),完成后按钮显示「已更新,重启 DSH 后生效」;失败显示「更新失败,点此重试」并把宿主错误打到控制台。
|
|
||||||
- 远程服务由一个子插件单独声明 inject 取用,主插件保持 inject 为空;未启用实验性「自定义插件索引」时子插件不生效,本功能静默关闭,审批与权限功能不受影响。
|
|
||||||
- 更新后需重启 DSH 才加载新版(与官方流程一致)。插件数据在 `$DSH_HOME` 的边车文件里,覆盖安装不影响。
|
|
||||||
|
|
||||||
顺带修复(v0.3.0):v0.2.x 里权限策略的定时器默认值把浏览器原生 `setInterval` 等函数摘出来当普通对象方法调用,Chrome 下抛 `TypeError: Illegal invocation`,会让独立安装的客户端条目激活失败(DSH 报 “entry did not activate”、整页白屏)。已改为箭头函数包裹调用,本功能的定时器同样处理。
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Third-party notices
|
||||||
|
|
||||||
|
The MIT license in this repository covers the plugin code.
|
||||||
|
|
||||||
|
## dshx client build adapter
|
||||||
|
|
||||||
|
`tools/client-build.js`, `tools/core-boundary.js` and
|
||||||
|
`tools/internal/client-cordis-inject.js` come from the dshx devkit
|
||||||
|
(`dsh-external-plugin-devkit` 0.9.7, MIT, <https://github.com/liyown/dshx>).
|
||||||
|
Local changes: the target Harness platform table defaults to the vendored copy in
|
||||||
|
`tools/harness/packages/client/web/src/platform.ts` (dsh-v0.2.2-rc.2).
|
||||||
407
client.js
407
client.js
|
|
@ -1,407 +0,0 @@
|
||||||
/**
|
|
||||||
* dsh-better-chat 客户端:让审批卡片的回车 / Esc 不再挑焦点。
|
|
||||||
*
|
|
||||||
* 背景(DSH 0.2.2-rc.1 的 @deepseek-ai/dsh-client-ui-approval):
|
|
||||||
* 官方审批卡自带键盘处理 —— Enter 批准(单次)、Esc 拒绝 —— 但它的
|
|
||||||
* keydown 挂在卡片根节点上,且要求焦点先落在卡片内。审批弹出时焦点
|
|
||||||
* 往往还在对话区/页面主体上,按回车毫无反应,必须先点一下卡片。
|
|
||||||
*
|
|
||||||
* 本模块补两件事,不改官方任何逻辑:
|
|
||||||
* 1. 审批卡出现时,若用户没有正在别处输入,把焦点送进卡片的详情区
|
|
||||||
* ([data-approval-scroll],本身 tabIndex=0),官方处理立即生效。
|
|
||||||
* 2. 焦点不在卡片内时兜底路由:在 document 捕获阶段监听 keydown,
|
|
||||||
* 满足全部防误触条件时,点击卡片操作行里的按钮 —— 顺序由官方渲染
|
|
||||||
* 固定为 [拒绝, 允许(单次), 始终允许?],回车点「允许(单次)」,
|
|
||||||
* 永远不会误触「始终允许」;Esc 点「拒绝」。
|
|
||||||
*
|
|
||||||
* 防误触(与官方卡片内部规则对齐):
|
|
||||||
* - 正在任何输入控件(input/textarea/select/contenteditable)里打字 → 不管
|
|
||||||
* - 焦点已在卡片内 → 官方处理,绝不重复作答
|
|
||||||
* - 带 Ctrl/Meta/Alt/Shift、长按连发、输入法组词中 → 不管
|
|
||||||
* - 回车落在某个按钮/链接上 → 保留那个按钮自己的回车行为
|
|
||||||
* - 卡片已作答(aria-busy=true)或按钮禁用 → 不管
|
|
||||||
*/
|
|
||||||
|
|
||||||
const CARD_SELECTOR = '[data-approval-key]'
|
|
||||||
const SCROLL_SELECTOR = '[data-approval-scroll]'
|
|
||||||
const EDITABLE_SELECTOR = 'input, textarea, select, [contenteditable="true"], [contenteditable=""]'
|
|
||||||
|
|
||||||
/** 卡片操作行的按钮:详情滚动区之外的全部按钮,顺序 [拒绝, 允许, 始终允许?]。 */
|
|
||||||
export function actionButtons(card) {
|
|
||||||
return [...card.querySelectorAll('button')].filter((b) => !b.closest(SCROLL_SELECTOR))
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 找当前可作答的审批卡(DOM 顺序第一张未作答、按钮齐全的卡)。 */
|
|
||||||
export function findPendingCard(doc) {
|
|
||||||
for (const card of doc.querySelectorAll(CARD_SELECTOR)) {
|
|
||||||
if (card.getAttribute('aria-busy') === 'true') continue
|
|
||||||
const buttons = actionButtons(card)
|
|
||||||
if (buttons.length >= 2 && !buttons[0].disabled && !buttons[1].disabled) return card
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 纯判定:这次 keydown 是否应该路由到审批卡。
|
|
||||||
* @returns {'allow'|'reject'|null}
|
|
||||||
*/
|
|
||||||
export function decideKeyAction(input) {
|
|
||||||
const { key, ctrlKey, metaKey, altKey, shiftKey, repeat, isComposing, keyCode, defaultPrevented, target, activeElement, card } = input
|
|
||||||
if (!card) return null
|
|
||||||
if (defaultPrevented) return null
|
|
||||||
if (key !== 'Enter' && key !== 'Escape') return null
|
|
||||||
if (ctrlKey || metaKey || altKey || shiftKey) return null
|
|
||||||
if (repeat || isComposing || keyCode === 229) return null
|
|
||||||
if (activeElement && card.contains(activeElement)) return null // 焦点在卡内:官方处理
|
|
||||||
if (target && typeof target.closest === 'function') {
|
|
||||||
if (target.closest(EDITABLE_SELECTOR) !== null) return null // 正在别处输入
|
|
||||||
if (key === 'Enter' && target.closest('button, a[href], [role="button"]') !== null) return null
|
|
||||||
}
|
|
||||||
return key === 'Enter' ? 'allow' : 'reject'
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 纯判定:审批卡出现时是否应该把焦点送进详情区。 */
|
|
||||||
export function shouldAutoFocus(activeElement, card) {
|
|
||||||
if (!activeElement) return true
|
|
||||||
if (activeElement === card.ownerDocument?.body) return true
|
|
||||||
if (card.contains(activeElement)) return false // 已经在卡里
|
|
||||||
if (typeof activeElement.closest === 'function' && activeElement.closest(EDITABLE_SELECTOR) !== null) return false // 正在别处输入
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
function install(doc) {
|
|
||||||
const focusedCards = new WeakSet()
|
|
||||||
|
|
||||||
const tryAutoFocus = () => {
|
|
||||||
const card = findPendingCard(doc)
|
|
||||||
if (!card || focusedCards.has(card)) return
|
|
||||||
focusedCards.add(card)
|
|
||||||
if (!shouldAutoFocus(doc.activeElement, card)) return
|
|
||||||
const region = card.querySelector(SCROLL_SELECTOR)
|
|
||||||
if (region && typeof region.focus === 'function') region.focus()
|
|
||||||
}
|
|
||||||
|
|
||||||
const observer = new MutationObserver(tryAutoFocus)
|
|
||||||
observer.observe(doc.documentElement, { childList: true, subtree: true })
|
|
||||||
tryAutoFocus()
|
|
||||||
|
|
||||||
const onKeyDown = (event) => {
|
|
||||||
const card = findPendingCard(doc)
|
|
||||||
const action = decideKeyAction({
|
|
||||||
key: event.key,
|
|
||||||
ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey,
|
|
||||||
repeat: event.repeat, isComposing: event.isComposing, keyCode: event.keyCode,
|
|
||||||
defaultPrevented: event.defaultPrevented,
|
|
||||||
target: event.target, activeElement: doc.activeElement, card,
|
|
||||||
})
|
|
||||||
if (!action) return
|
|
||||||
const buttons = actionButtons(card)
|
|
||||||
const button = action === 'allow' ? buttons[1] : buttons[0]
|
|
||||||
if (!button || button.disabled) return
|
|
||||||
event.preventDefault()
|
|
||||||
event.stopPropagation()
|
|
||||||
button.click()
|
|
||||||
}
|
|
||||||
doc.addEventListener('keydown', onKeyDown, true)
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
observer.disconnect()
|
|
||||||
doc.removeEventListener('keydown', onKeyDown, true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 功能二:权限 UI —— 去掉「完全权限」选项,不改已有会话权限。
|
|
||||||
*
|
|
||||||
* 背景(DSH 0.2.2-rc.1 的权限预设,@deepseek-ai/dsh-client-ui-permission-presets):
|
|
||||||
* 会话权限有四个预设值:read-only(仅可查看)、workspace-write(工作区内
|
|
||||||
* 修改)、danger-full-access(完全权限)、auto(自动审查,EXP)。「自动
|
|
||||||
* 审查」由实验层 @deepseek-ai/dsh-experimental-auto-review 提供:开启该层
|
|
||||||
* 后才出现在当前会话的选择器里;通用设置不提供 auto,新会话默认值里
|
|
||||||
* 也选不到它。宿主切换预设的通道是会话对象的 command(`/permission <值>`),
|
|
||||||
* 带参命令直接生效、不弹风险确认。
|
|
||||||
*
|
|
||||||
* 本功能只做一件事:界面移除完全权限。它**不再**在页面加载、刷新或
|
|
||||||
* 插件重载时遍历已有会话改权限:那会把用户明确选择的只读/工作区权限
|
|
||||||
* 覆盖成 auto,而且 handled 只在内存里,刷新后会再次执行。默认权限
|
|
||||||
* 属于宿主的新建会话流程;本插件没有可靠的新建扩展点,因此不拿轮询
|
|
||||||
* 去补偿,用户仍可在宿主提供的权限选择器里自行选择自动审查。
|
|
||||||
*/
|
|
||||||
|
|
||||||
/** 完全权限的预设机器值。 */
|
|
||||||
export const FULL_ACCESS_PRESET = 'danger-full-access'
|
|
||||||
/** 自动审查的预设机器值。 */
|
|
||||||
export const AUTO_REVIEW_PRESET = 'auto'
|
|
||||||
/** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */
|
|
||||||
export const FULL_ACCESS_LABELS = ['完全权限', 'Full access']
|
|
||||||
|
|
||||||
/** 纯判定:一段选项文字是否就是「完全权限」选项(标签打头,或恰好相等)。 */
|
|
||||||
export function isFullAccessLabel(text) {
|
|
||||||
if (typeof text !== 'string') return false
|
|
||||||
const t = text.trim()
|
|
||||||
return FULL_ACCESS_LABELS.some((label) => t === label || t.startsWith(label))
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 纯判定:这个会话现在是否应该被切到自动审查。 */
|
|
||||||
export function shouldAutoSwitch(preset, alreadyHandled) {
|
|
||||||
return preset !== undefined && preset !== null && preset !== AUTO_REVIEW_PRESET && !alreadyHandled
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 防御式枚举宿主的 live 会话:优先 keys()+binding(),退回 list()。
|
|
||||||
* 服务形状对不上时安静返回空数组,绝不抛错。
|
|
||||||
*/
|
|
||||||
export function liveSessions(sessions) {
|
|
||||||
const out = []
|
|
||||||
if (!sessions || typeof sessions !== 'object') return out
|
|
||||||
try {
|
|
||||||
if (typeof sessions.keys === 'function' && typeof sessions.binding === 'function') {
|
|
||||||
for (const id of sessions.keys()) {
|
|
||||||
const live = sessions.binding(id)?.session
|
|
||||||
if (live) out.push({ id, live })
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
if (typeof sessions.list === 'function') {
|
|
||||||
for (const s of sessions.list() ?? []) {
|
|
||||||
if (s && s.sessionId) out.push({ id: s.sessionId, live: s })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch { /* 服务形状不同:放弃枚举 */ }
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 读会话当前的权限预设值(投影不可用时返回 undefined)。 */
|
|
||||||
export function currentPreset(live) {
|
|
||||||
try {
|
|
||||||
return live?.projections?.faceOf('permissions')?.getSnapshot?.()
|
|
||||||
} catch {
|
|
||||||
return undefined
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 把「完全权限」选项从当前文档里摘掉:原生 select 的 option、弹出
|
|
||||||
* 选择器(role=listbox)与菜单(role=menu)里的 option/menuitem。
|
|
||||||
* @returns 摘掉的个数
|
|
||||||
*/
|
|
||||||
export function pruneFullAccess(doc) {
|
|
||||||
let removed = 0
|
|
||||||
for (const opt of doc.querySelectorAll('option')) {
|
|
||||||
if (isFullAccessLabel(opt.textContent)) { opt.remove(); removed++ }
|
|
||||||
}
|
|
||||||
for (const item of doc.querySelectorAll('[role="listbox"] [role="option"], [role="menu"] [role="menuitem"]')) {
|
|
||||||
if (isFullAccessLabel(item.textContent)) { item.remove(); removed++ }
|
|
||||||
}
|
|
||||||
return removed
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 安装权限 UI 策略:只观察 DOM、摘掉「完全权限」选项。
|
|
||||||
*
|
|
||||||
* 不接收 `getSessions`,也不启动任何会话轮询:页面加载、刷新和插件重载
|
|
||||||
* 都不得改变已有会话的权限。新建会话的默认值由宿主自己的新建流程决定。
|
|
||||||
* @returns 卸载函数
|
|
||||||
*/
|
|
||||||
export function installPermissionPolicy(doc, _getSessions, timers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) }) {
|
|
||||||
let disposed = false
|
|
||||||
let scanTimer = 0
|
|
||||||
const scheduleScan = () => {
|
|
||||||
if (disposed || scanTimer) return
|
|
||||||
scanTimer = timers.setTimeout(() => {
|
|
||||||
scanTimer = 0
|
|
||||||
if (!disposed) pruneFullAccess(doc)
|
|
||||||
}, 120)
|
|
||||||
}
|
|
||||||
const observer = new MutationObserver(scheduleScan)
|
|
||||||
if (doc.body) observer.observe(doc.body, { childList: true, subtree: true })
|
|
||||||
pruneFullAccess(doc)
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
disposed = true
|
|
||||||
observer.disconnect()
|
|
||||||
if (scanTimer) timers.clearTimeout(scanTimer)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ *
|
|
||||||
* 功能三:插件商店「更新」按钮。
|
|
||||||
*
|
|
||||||
* DSH 只给官方插件原地更新;从自定义索引装的插件在发现页只有
|
|
||||||
* 「有新版本」标签、没有按钮,只能手动卸载重装。这里补一个真按钮:
|
|
||||||
* 数据与动作都走宿主自己的远程服务——pluginMarket 查索引和安装
|
|
||||||
* 状态,pluginManager.installBundle 按索引给出的精确 spec 覆盖
|
|
||||||
* 安装——与官方安装流程同一套接口,不模拟点击、不动官方状态。
|
|
||||||
* 覆盖安装在探针实测中可直接把已装旧版换成新版(changed/applied)。
|
|
||||||
*
|
|
||||||
* 服务经子插件声明 inject 取用:主插件保持 inject 为空,审批与
|
|
||||||
* 权限功能不依赖这些服务;未启用实验性插件索引时子插件不生效,
|
|
||||||
* 本功能静默关闭。
|
|
||||||
* ------------------------------------------------------------------ */
|
|
||||||
|
|
||||||
export const UPDATE_LABELS = ['有新版本', 'Update available']
|
|
||||||
|
|
||||||
/** 索引条目的本地化标题在当前语言下的文本(与发现页行内展示一致)。 */
|
|
||||||
export function localizedTitle(title, lang) {
|
|
||||||
if (typeof title === 'string') return title
|
|
||||||
if (!title || typeof title !== 'object') return ''
|
|
||||||
const chain = [lang, lang && lang.split('-')[0], 'zh-CN', 'en']
|
|
||||||
for (const key of chain) {
|
|
||||||
if (key && typeof title[key] === 'string' && title[key]) return title[key]
|
|
||||||
}
|
|
||||||
const values = Object.values(title)
|
|
||||||
return typeof values[0] === 'string' ? values[0] : ''
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 从各索引的搜索结果里挑出「有新版本」的条目,整理成可执行的更新计划。 */
|
|
||||||
export function pickUpdates(searchResults, lang) {
|
|
||||||
const updates = []
|
|
||||||
for (const result of searchResults ?? []) {
|
|
||||||
const entries = result?.value?.entries ?? result?.entries ?? []
|
|
||||||
for (const entry of entries) {
|
|
||||||
if (entry?.installation?.status !== 'update-available') continue
|
|
||||||
const versions = entry.versions ?? []
|
|
||||||
const version = versions.find((v) => v.version === entry.defaultVersion) ?? versions[0]
|
|
||||||
const spec = version?.install?.spec
|
|
||||||
if (!entry.name || !version?.version || !spec) continue
|
|
||||||
updates.push({
|
|
||||||
name: entry.name,
|
|
||||||
title: localizedTitle(entry.title, lang) || entry.name,
|
|
||||||
installedVersion: entry.installation.installedVersion ?? '',
|
|
||||||
version: version.version,
|
|
||||||
spec,
|
|
||||||
registry: version.install.registry,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return updates
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 执行一次更新:按索引 spec 覆盖安装,宿主结果信封原样返回。 */
|
|
||||||
export async function runUpdate(remote, update, makeRequestId) {
|
|
||||||
const requestId = makeRequestId ? makeRequestId() : 'better-chat-update-' + Date.now()
|
|
||||||
return remote.pluginManager.installBundle(update.spec, {
|
|
||||||
enabled: true,
|
|
||||||
requestId,
|
|
||||||
...(update.registry ? { registry: update.registry } : {}),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发现页里某个插件的行:状态标签本身是个按钮,从它向上找第一个
|
|
||||||
* 同时包含插件标题、且文本总量还像一行的祖先。
|
|
||||||
*/
|
|
||||||
export function findUpdateRow(doc, title) {
|
|
||||||
for (const el of doc.querySelectorAll('button')) {
|
|
||||||
if (!UPDATE_LABELS.includes(el.textContent?.trim())) continue
|
|
||||||
let node = el
|
|
||||||
for (let depth = 0; depth < 6 && node; depth++) {
|
|
||||||
node = node.parentElement
|
|
||||||
if (node && node.textContent?.includes(title) && node.textContent.length < 600) return node
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 更新按钮的点击处理:确认 → 调宿主覆盖安装 → 按结果改按钮文案。 */
|
|
||||||
export function makeUpdateClickHandler(doc, getRemote, update, button) {
|
|
||||||
return async (event) => {
|
|
||||||
event?.preventDefault?.()
|
|
||||||
event?.stopPropagation?.()
|
|
||||||
const view = doc.defaultView
|
|
||||||
const ask = view?.confirm ?? globalThis.confirm
|
|
||||||
const message = '更新「' + update.title + '」' + (update.installedVersion ? ' ' + update.installedVersion : '') + ' → ' + update.version + '?\n会直接覆盖安装新版,插件数据保留。'
|
|
||||||
if (ask && !ask.call(view ?? globalThis, message)) return
|
|
||||||
button.disabled = true
|
|
||||||
button.textContent = '更新中…'
|
|
||||||
try {
|
|
||||||
const result = await runUpdate(getRemote(), update, () => globalThis.crypto?.randomUUID?.() ?? undefined)
|
|
||||||
if (result?.value?.application === 'applied') {
|
|
||||||
button.textContent = '已更新,重启 DSH 后生效'
|
|
||||||
} else {
|
|
||||||
console.error('[dsh-better-chat] update failed for', update.name, result?.value?.error ?? result)
|
|
||||||
button.disabled = false
|
|
||||||
button.textContent = '更新失败,点此重试'
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[dsh-better-chat] update failed for', update.name, error)
|
|
||||||
button.disabled = false
|
|
||||||
button.textContent = '更新失败,点此重试'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 发现页增强:轮询索引状态,把「更新」按钮挂到有新版本的行上。 */
|
|
||||||
export function installStoreUpdateButtons(doc, getRemote, timers = { setInterval: (fn, ms) => setInterval(fn, ms), clearInterval: (id) => clearInterval(id) }) {
|
|
||||||
let disposed = false
|
|
||||||
let updates = []
|
|
||||||
const decorate = () => {
|
|
||||||
for (const update of updates) {
|
|
||||||
const row = findUpdateRow(doc, update.title)
|
|
||||||
if (!row || row.querySelector('[data-better-chat-update]')) continue
|
|
||||||
const button = doc.createElement('button')
|
|
||||||
button.type = 'button'
|
|
||||||
button.setAttribute('data-better-chat-update', update.name)
|
|
||||||
button.textContent = '更新到 ' + update.version
|
|
||||||
button.style.cssText = 'flex:none;margin-left:8px;padding:2px 10px;border:1px solid #7f7f7f55;border-radius:999px;background:transparent;color:inherit;font-size:12px;cursor:pointer'
|
|
||||||
button.addEventListener('click', makeUpdateClickHandler(doc, getRemote, update, button))
|
|
||||||
row.appendChild(button)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const refresh = async () => {
|
|
||||||
try {
|
|
||||||
const remote = getRemote()
|
|
||||||
if (!remote?.pluginMarket || !remote?.pluginManager) return
|
|
||||||
const indexes = await remote.pluginMarket.listIndexes()
|
|
||||||
const urls = (indexes?.value ?? indexes ?? []).map((entry) => entry?.url).filter(Boolean)
|
|
||||||
const results = []
|
|
||||||
for (const url of urls) {
|
|
||||||
results.push(await remote.pluginMarket.search(url, { sort: { kind: 'index' }, offset: 0, limit: 100 }))
|
|
||||||
}
|
|
||||||
if (disposed) return
|
|
||||||
updates = pickUpdates(results, doc.documentElement?.lang || 'zh-CN')
|
|
||||||
decorate()
|
|
||||||
} catch {
|
|
||||||
// 索引服务不可用(未启用实验性插件索引等):静默关闭本功能。
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const observer = new MutationObserver(() => decorate())
|
|
||||||
observer.observe(doc.documentElement, { childList: true, subtree: true })
|
|
||||||
const timer = timers.setInterval(() => { void refresh() }, 30000)
|
|
||||||
void refresh()
|
|
||||||
return () => {
|
|
||||||
disposed = true
|
|
||||||
observer.disconnect()
|
|
||||||
timers.clearInterval(timer)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 商店更新子插件:单独声明远程服务 inject,与主功能互相隔离。 */
|
|
||||||
const storeUpdatePlugin = {
|
|
||||||
name: 'dsh-better-chat-store-update',
|
|
||||||
inject: ['remote', 'remote.pluginMarket', 'remote.pluginManager'],
|
|
||||||
apply(childCtx) {
|
|
||||||
childCtx.effect(
|
|
||||||
() => installStoreUpdateButtons(document, () => childCtx.remote),
|
|
||||||
'dsh-better-chat: store update buttons',
|
|
||||||
)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 本插件不硬依赖任何客户端服务(sessions 服务是可选增强,缺了只是不自动切)。 */
|
|
||||||
export const inject = []
|
|
||||||
|
|
||||||
/** 插件主体:挂载两组增强,卸载时完整摘除。 */
|
|
||||||
export function apply(ctx) {
|
|
||||||
ctx.effect(() => install(document), 'dsh-better-chat: approval enter/esc routing')
|
|
||||||
ctx.effect(
|
|
||||||
() => installPermissionPolicy(document),
|
|
||||||
'dsh-better-chat: permission policy (no full access)',
|
|
||||||
)
|
|
||||||
try {
|
|
||||||
ctx.plugin(storeUpdatePlugin)
|
|
||||||
} catch {
|
|
||||||
// 子插件挂不上(旧宿主等)不影响主功能。
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,9 +1,9 @@
|
||||||
# dsh-better-chat bundle patch
|
# dsh-better-chat bundle patch
|
||||||
#
|
#
|
||||||
# One insert row loads the package: the host entry is a no-op stub, the
|
# One insert row loads the package: the host entry registers the reader's
|
||||||
# actual feature lives in the web client (./client export, see the `dsh`
|
# reveal/skill-status/metrics routes, and the web client (./client export,
|
||||||
# manifest in package.json).
|
# see the `dsh` manifest in package.json) registers the reader view plus the
|
||||||
|
# chat enhancements (approval keys, permission UI, store update buttons).
|
||||||
- insert:
|
- insert:
|
||||||
- id: dsh-better-chat
|
- id: dsh-better-chat
|
||||||
name: 'dsh-better-chat'
|
name: dsh-better-chat
|
||||||
config: {}
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
# Dependency update policy
|
||||||
|
|
||||||
|
Wait 7 days before merging a version bump.
|
||||||
|
|
||||||
|
`renovate.json` sets `minimumReleaseAge` to `7 days`. Renovate must not treat a release as ready until that age has passed. `.github/dependabot.yml` only schedules weekly npm checks. A weekly pull request is not permission to merge a version on the day it was published. The same 7 day wait applies before merging those bumps.
|
||||||
|
|
||||||
|
Do not merge a version bump the day it is published, even when CI is green. A lockfile change that only repeats a version which is already 7 days old can merge with the bump it belongs to. It does not skip the wait, and it does not start a new one.
|
||||||
|
|
||||||
|
This policy does not point at a Dependabot or Renovate pull request. Open one only when the bot actually does.
|
||||||
13
index.js
13
index.js
|
|
@ -1,13 +0,0 @@
|
||||||
/**
|
|
||||||
* dsh-better-chat — DSH 聊天增强插件。
|
|
||||||
*
|
|
||||||
* 宿主侧入口只是占位(让 bundle 能被加载);功能都在 Web 客户端
|
|
||||||
* (client.js,见 package.json 的 exports / dsh 清单):
|
|
||||||
* 功能一 = 审批卡片的回车批准 / Esc 拒绝(自动送入焦点 + 全局兜底路由)。
|
|
||||||
*/
|
|
||||||
|
|
||||||
/** Plugin identity for cordis.yml rows. */
|
|
||||||
export const name = 'dsh-better-chat'
|
|
||||||
|
|
||||||
/** Plugin body: nothing host-side yet; the client half does the work. */
|
|
||||||
export function apply(ctx) {}
|
|
||||||
1558
lib/client.js
1558
lib/client.js
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,180 @@
|
||||||
|
// src/log.ts
|
||||||
|
const REDACTED = "[REDACTED]";
|
||||||
|
const SECRET_KEYS = /* @__PURE__ */ new Set([
|
||||||
|
"authorization",
|
||||||
|
"proxyauthorization",
|
||||||
|
"cookie",
|
||||||
|
"setcookie",
|
||||||
|
"token",
|
||||||
|
"accesstoken",
|
||||||
|
"refreshtoken",
|
||||||
|
"idtoken",
|
||||||
|
"apikey",
|
||||||
|
"apisecret",
|
||||||
|
"secret",
|
||||||
|
"clientsecret",
|
||||||
|
"password",
|
||||||
|
"passwd",
|
||||||
|
"credential",
|
||||||
|
"credentials",
|
||||||
|
"signature",
|
||||||
|
"sig",
|
||||||
|
"jwt",
|
||||||
|
"bearer",
|
||||||
|
"privatekey",
|
||||||
|
"xapikey",
|
||||||
|
"xauthtoken",
|
||||||
|
"xaccesstoken",
|
||||||
|
"auth"
|
||||||
|
]);
|
||||||
|
function normalizeKey(key) {
|
||||||
|
return key.toLowerCase().replace(/[^a-z0-9]/g, "");
|
||||||
|
}
|
||||||
|
function isSecretKey(key) {
|
||||||
|
const normalized = normalizeKey(key);
|
||||||
|
if (SECRET_KEYS.has(normalized)) return true;
|
||||||
|
if (normalized === "requestid" || normalized === "xrequestid") return false;
|
||||||
|
return /(?:^|[^a-z])(?:token|secret|password|api[-_]?key)$/i.test(key);
|
||||||
|
}
|
||||||
|
function redactString(value) {
|
||||||
|
return value.replace(/([?&#])([^&#=]+)=([^&#]*)/g, (match, sep, rawKey) => {
|
||||||
|
let key;
|
||||||
|
try {
|
||||||
|
key = decodeURIComponent(rawKey.replace(/\+/g, " "));
|
||||||
|
} catch {
|
||||||
|
key = rawKey;
|
||||||
|
}
|
||||||
|
return isSecretKey(key) ? `${sep}${rawKey}=${REDACTED}` : match;
|
||||||
|
}).replace(/\b(Bearer|Basic)\s+\S+/gi, `$1 ${REDACTED}`).replace(/\b((?:access[_-]?token|refresh[_-]?token|id[_-]?token|api[_-]?key|client[_-]?secret|password|passwd|authorization|token|secret))(\s*[:=]\s*)([^\s&]+)/gi, `$1$2${REDACTED}`);
|
||||||
|
}
|
||||||
|
function redact(value) {
|
||||||
|
return redactValue(void 0, value, 0, /* @__PURE__ */ new WeakSet());
|
||||||
|
}
|
||||||
|
function redactValue(key, value, depth, seen) {
|
||||||
|
if (key !== void 0 && isSecretKey(key)) return REDACTED;
|
||||||
|
if (depth > 8) return REDACTED;
|
||||||
|
if (typeof value === "string") return redactString(value);
|
||||||
|
if (typeof value === "number" || typeof value === "boolean" || value === null || value === void 0) return value;
|
||||||
|
if (typeof value !== "object") return REDACTED;
|
||||||
|
if (value instanceof Date) return value.toISOString();
|
||||||
|
if (value instanceof Error) return redactValue(void 0, {
|
||||||
|
name: value.name,
|
||||||
|
message: value.message
|
||||||
|
}, depth + 1, seen);
|
||||||
|
if (seen.has(value)) return REDACTED;
|
||||||
|
seen.add(value);
|
||||||
|
if (Array.isArray(value)) return value.map((item) => redactValue(void 0, item, depth + 1, seen));
|
||||||
|
const output = {};
|
||||||
|
for (const [childKey, childValue] of Object.entries(value)) output[childKey] = redactValue(childKey, childValue, depth + 1, seen);
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
function createLogger(options = {}) {
|
||||||
|
const write = options.write ?? ((line) => {
|
||||||
|
console.log(line);
|
||||||
|
});
|
||||||
|
const clock = options.clock ?? (() => /* @__PURE__ */ new Date());
|
||||||
|
const emit = (level, msg, fields) => {
|
||||||
|
const details = redact({
|
||||||
|
...options.base,
|
||||||
|
...fields
|
||||||
|
});
|
||||||
|
const record = {
|
||||||
|
...details !== null && typeof details === "object" ? details : {},
|
||||||
|
time: clock().toISOString(),
|
||||||
|
level,
|
||||||
|
msg: redactString(msg)
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
write(JSON.stringify(record));
|
||||||
|
} catch {
|
||||||
|
write(JSON.stringify({
|
||||||
|
time: record.time,
|
||||||
|
level,
|
||||||
|
msg: record.msg,
|
||||||
|
error: "log record was not serializable"
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
info: (msg, fields) => emit("info", msg, fields),
|
||||||
|
warn: (msg, fields) => emit("warn", msg, fields),
|
||||||
|
error: (msg, fields) => emit("error", msg, fields)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// src/host.ts
|
||||||
|
const name = "dsh-better-chat";
|
||||||
|
const inject = [];
|
||||||
|
const log = createLogger({ base: { plugin: name } });
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
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 };
|
||||||
91
package.json
91
package.json
|
|
@ -1,11 +1,12 @@
|
||||||
{
|
{
|
||||||
"name": "dsh-better-chat",
|
"name": "dsh-better-chat",
|
||||||
"version": "0.3.1",
|
"version": "1.0.4",
|
||||||
"description": "DSH 聊天增强插件:审批卡片全局回车批准 / Esc 拒绝",
|
"description": "DSH 聊天增强插件:审批回车批准 / Esc 拒绝、权限 UI、插件商店更新、默认自动审查。",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "index.js",
|
"license": "MIT",
|
||||||
|
"main": "lib/host.js",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./index.js",
|
".": "./lib/host.js",
|
||||||
"./client": "./lib/client.js",
|
"./client": "./lib/client.js",
|
||||||
"./cordis.patch.yml": "./cordis.patch.yml",
|
"./cordis.patch.yml": "./cordis.patch.yml",
|
||||||
"./package.json": "./package.json"
|
"./package.json": "./package.json"
|
||||||
|
|
@ -16,12 +17,86 @@
|
||||||
},
|
},
|
||||||
"client": {
|
"client": {
|
||||||
"platform": "web",
|
"platform": "web",
|
||||||
"inject": []
|
"inject": [
|
||||||
|
"@deepseek-ai/dsh-api-session-controller",
|
||||||
|
"@deepseek-ai/dsh-client-ui-chat",
|
||||||
|
"@deepseek-ai/dsh-client-ui-conversation",
|
||||||
|
"@deepseek-ai/dsh-client-ui-renderer",
|
||||||
|
"@deepseek-ai/dsh-client-ui-session"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "node --test tests/approval-keys.test.mjs tests/permission-policy.test.mjs tests/client-loader.test.mjs tests/store-update.test.mjs",
|
"build": "tsdown",
|
||||||
"build": "node scripts/build-client.mjs"
|
"test": "vitest run",
|
||||||
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||||
},
|
},
|
||||||
"license": "MIT"
|
"dependencies": {
|
||||||
|
"@deepseek-ai/dsh-util-workspace-path": "0.2.1-rc.5",
|
||||||
|
"clsx": "^2.0.0",
|
||||||
|
"katex": "^0.19.1",
|
||||||
|
"mdast-util-from-markdown": "^2.0.3",
|
||||||
|
"mdast-util-gfm": "^3.1.0",
|
||||||
|
"mdast-util-math": "^3.0.0",
|
||||||
|
"micromark-core-commonmark": "^2.0.3",
|
||||||
|
"micromark-extension-gfm": "^3.0.0",
|
||||||
|
"micromark-extension-math": "^3.1.0",
|
||||||
|
"micromark-factory-space": "^2.0.1",
|
||||||
|
"micromark-util-character": "^2.1.1",
|
||||||
|
"micromark-util-classify-character": "^2.0.1",
|
||||||
|
"micromark-util-sanitize-uri": "^2.0.1",
|
||||||
|
"micromark-util-symbol": "^2.0.1",
|
||||||
|
"micromark-util-types": "^2.0.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@deepseek-ai/cordis": ">=4.0.4 <5",
|
||||||
|
"@deepseek-ai/dsh-attachment": ">=0.2.1-rc.1 <0.2.3",
|
||||||
|
"@deepseek-ai/dsh-client-store": ">=0.2.1-rc.1 <0.2.3",
|
||||||
|
"@deepseek-ai/dsh-client-ui-chat": ">=0.2.1-rc.1 <0.2.3",
|
||||||
|
"@deepseek-ai/dsh-client-ui-conversation": ">=0.2.1-rc.1 <0.2.3",
|
||||||
|
"@deepseek-ai/dsh-client-ui-primitives": ">=0.2.1-rc.1 <0.2.3",
|
||||||
|
"@deepseek-ai/dsh-client-ui-renderer": ">=0.2.1-rc.1 <0.2.3",
|
||||||
|
"@deepseek-ai/dsh-client-ui-session": ">=0.2.1-rc.1 <0.2.3",
|
||||||
|
"@deepseek-ai/dsh-client-ui-slots": ">=0.2.1-rc.1 <0.2.3",
|
||||||
|
"@deepseek-ai/dsh-client-ui-tool": ">=0.2.1-rc.1 <0.2.3",
|
||||||
|
"@deepseek-ai/dsh-session": ">=0.2.1-rc.1 <0.2.3",
|
||||||
|
"@deepseek-ai/dsh-util-workspace-path": ">=0.2.1-rc.1 <0.2.3",
|
||||||
|
"react": "^18.2.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.20.0",
|
||||||
|
"@types/react": "~18.3.1",
|
||||||
|
"lightningcss": "^1.33.0",
|
||||||
|
"semver": "^7.7.2",
|
||||||
|
"tsdown": "^0.23.2",
|
||||||
|
"typescript": "^6.0.3",
|
||||||
|
"vitest": "^5.0.5"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^22.19.0 || >=24.0.0",
|
||||||
|
"dsh": ">=0.2.1-rc.1 <0.2.3"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"lib",
|
||||||
|
"src",
|
||||||
|
"tests",
|
||||||
|
"docs",
|
||||||
|
"cordis.patch.yml",
|
||||||
|
"README.md",
|
||||||
|
"README.en.md",
|
||||||
|
"CHANGELOG.md",
|
||||||
|
"THIRD_PARTY_NOTICES.md",
|
||||||
|
"tsconfig.json",
|
||||||
|
"tsdown.config.ts",
|
||||||
|
"vitest.config.ts",
|
||||||
|
"tools"
|
||||||
|
],
|
||||||
|
"keywords": [
|
||||||
|
"deepseek-harness",
|
||||||
|
"dsh",
|
||||||
|
"dsh-plugin",
|
||||||
|
"conversation",
|
||||||
|
"approval",
|
||||||
|
"permission"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -1,47 +0,0 @@
|
||||||
// Build lib/client.js (the file the host's client module loader fetches)
|
|
||||||
// from client.js (the ESM source of truth).
|
|
||||||
//
|
|
||||||
// Why: the loader fetches a package's client as a CLASSIC script and expects
|
|
||||||
// it to register a factory via window.__ModuleLoader__.load({ id, factory }).
|
|
||||||
// A raw ESM file registers nothing (its `export` syntax never runs), which is
|
|
||||||
// the v0.2.0 standalone-load failure. client.js stays ESM for the QQ-dsh
|
|
||||||
// bundle's direct import and for the unit tests; this script mechanically
|
|
||||||
// strips the export keywords and wraps the result in the registration IIFE.
|
|
||||||
// It fails loudly if the source grows an export shape it cannot map.
|
|
||||||
import { readFileSync, writeFileSync } from 'node:fs'
|
|
||||||
import { dirname, join } from 'node:path'
|
|
||||||
import { fileURLToPath } from 'node:url'
|
|
||||||
|
|
||||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
|
||||||
const source = readFileSync(join(root, 'client.js'), 'utf8')
|
|
||||||
|
|
||||||
const exported = []
|
|
||||||
const body = source.replace(/^export (async function|function|const) ([A-Za-z_$][\w$]*)/gm, (match, kind, name) => {
|
|
||||||
exported.push(name)
|
|
||||||
return kind + ' ' + name
|
|
||||||
})
|
|
||||||
if (/^export /m.test(body)) throw new Error('unmapped export syntax remains in client.js')
|
|
||||||
for (const required of ['inject', 'apply']) {
|
|
||||||
if (!exported.includes(required)) throw new Error('client.js no longer exports ' + required)
|
|
||||||
}
|
|
||||||
|
|
||||||
const header = [
|
|
||||||
"'use strict'",
|
|
||||||
'/* Generated by scripts/build-client.mjs from client.js - do not edit by hand.',
|
|
||||||
' The host client module loader fetches this file as a classic script and',
|
|
||||||
' expects window.__ModuleLoader__.load({ id, factory }) registration. */',
|
|
||||||
';(function () {',
|
|
||||||
'',
|
|
||||||
].join('\n')
|
|
||||||
const footer = [
|
|
||||||
'',
|
|
||||||
' var plugin = { name: "dsh-better-chat", inject: inject, apply: apply }',
|
|
||||||
' if (typeof window !== "undefined" && window.__ModuleLoader__ && typeof window.__ModuleLoader__.load === "function") {',
|
|
||||||
' window.__ModuleLoader__.load({ id: "dsh-better-chat", factory: function () { return plugin } })',
|
|
||||||
' }',
|
|
||||||
'})()',
|
|
||||||
'',
|
|
||||||
].join('\n')
|
|
||||||
|
|
||||||
writeFileSync(join(root, 'lib', 'client.js'), header + body + footer)
|
|
||||||
console.log('built lib/client.js from client.js; exports mapped:', exported.join(', '))
|
|
||||||
|
|
@ -0,0 +1,177 @@
|
||||||
|
.section {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 28px;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 720px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 16px 0;
|
||||||
|
border-bottom: 0.5px solid var(--dsw-alias-border-l2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rowText {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
padding-right: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title {
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 400;
|
||||||
|
line-height: 22px;
|
||||||
|
color: var(--dsw-alias-label-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.desc {
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 400;
|
||||||
|
line-height: 18px;
|
||||||
|
color: var(--dsw-alias-label-tertiary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.switch {
|
||||||
|
flex: none;
|
||||||
|
width: 40px;
|
||||||
|
height: 24px;
|
||||||
|
padding: 0;
|
||||||
|
border: none;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--dsw-alias-bg-module-platform);
|
||||||
|
position: relative;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.switch::after {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
top: 3px;
|
||||||
|
left: 3px;
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--dsw-alias-label-primary);
|
||||||
|
transition: transform 160ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.switch[data-on]::after {
|
||||||
|
transform: translateX(16px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.switch[data-on] {
|
||||||
|
background: var(--dsw-alias-state-business-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.block {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button {
|
||||||
|
height: 32px;
|
||||||
|
padding: 0 12px;
|
||||||
|
border: 0.5px solid var(--dsw-alias-border-l2);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--dsw-alias-bg-module-platform);
|
||||||
|
color: var(--dsw-alias-label-primary);
|
||||||
|
font: inherit;
|
||||||
|
font-size: 13px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.button:hover {
|
||||||
|
background: var(--dsw-alias-interactive-bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.button:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
.segment {
|
||||||
|
display: flex;
|
||||||
|
width: 100%;
|
||||||
|
margin-top: 8px;
|
||||||
|
padding: 2px;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--dsw-alias-bg-module-platform);
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.segmentStop {
|
||||||
|
flex: 1 1 0;
|
||||||
|
min-width: 0;
|
||||||
|
height: 32px;
|
||||||
|
padding: 0 8px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--dsw-alias-label-secondary);
|
||||||
|
font: inherit;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 18px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.segmentStop[data-on] {
|
||||||
|
background: var(--dsw-alias-bg-base);
|
||||||
|
color: var(--dsw-alias-label-primary);
|
||||||
|
box-shadow: 0 0 0 0.5px var(--dsw-alias-border-l2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.slider {
|
||||||
|
width: 100%;
|
||||||
|
margin: 10px 0 0;
|
||||||
|
accent-color: var(--dsw-alias-state-business-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.keyActions {
|
||||||
|
flex: none;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.keyButton {
|
||||||
|
min-width: 96px;
|
||||||
|
height: 32px;
|
||||||
|
padding: 0 12px;
|
||||||
|
border: 0.5px solid var(--dsw-alias-border-l2);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--dsw-alias-bg-base);
|
||||||
|
color: var(--dsw-alias-label-primary);
|
||||||
|
font-family: var(--ds-font-family-code, ui-monospace, SFMono-Regular, Consolas, monospace);
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 20px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.keyButton:hover {
|
||||||
|
border-color: var(--dsw-alias-border-l3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.keyButton[data-recording] {
|
||||||
|
border-color: var(--dsw-alias-state-business-primary);
|
||||||
|
color: var(--dsw-alias-state-business-primary);
|
||||||
|
background: var(--dsw-alias-bg-module-platform);
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--dsw-alias-state-error-primary, #d1483c);
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 18px;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,154 @@
|
||||||
|
import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';
|
||||||
|
import {
|
||||||
|
BINDINGS_CHANGED_EVENT,
|
||||||
|
bindingKeycap,
|
||||||
|
normalizeBindings,
|
||||||
|
validateBinding,
|
||||||
|
type ApprovalAction,
|
||||||
|
type ApprovalBinding,
|
||||||
|
} from './chat/bindings.js';
|
||||||
|
import type { ChatPrefs } from './chat/bindings-store.js';
|
||||||
|
import { settingsCopyFor, type SettingsCopy, type SettingsCopyKey } from './settings-copy.js';
|
||||||
|
import css from './SettingsSection.module.css';
|
||||||
|
|
||||||
|
export interface BetterChatSettingsInjected {
|
||||||
|
chat?: ChatPrefs;
|
||||||
|
copy?: SettingsCopy;
|
||||||
|
languageTag?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
type SettingsProps = BetterChatSettingsInjected & {
|
||||||
|
/** Official settings.section owner share; unused here. */
|
||||||
|
close?: () => void;
|
||||||
|
t?: (key: SettingsCopyKey) => string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function text(props: SettingsProps, copy: SettingsCopy, key: keyof SettingsCopy): string {
|
||||||
|
if (typeof props.t === 'function') {
|
||||||
|
try {
|
||||||
|
const value = props.t(key);
|
||||||
|
if (typeof value === 'string' && value.length > 0 && value !== key) return value;
|
||||||
|
} catch {
|
||||||
|
// Fall through to the bundled dictionaries.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return copy[key];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SettingsSection(props: SettingsProps) {
|
||||||
|
const copy = props.copy ?? settingsCopyFor(props.languageTag);
|
||||||
|
|
||||||
|
// 审批快捷键:读插件配置,保存后派发事件让卡片提示立即重建。
|
||||||
|
const chat = props.chat;
|
||||||
|
const chatSnap = useSyncExternalStore(
|
||||||
|
chat?.subscribe ?? (() => () => {}),
|
||||||
|
() => chat?.getSnapshot() ?? ({ bindings: undefined } as never),
|
||||||
|
() => ({ bindings: undefined } as never),
|
||||||
|
);
|
||||||
|
const bindings = normalizeBindings(chatSnap);
|
||||||
|
const mac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform);
|
||||||
|
const [recording, setRecording] = useState<ApprovalAction | null>(null);
|
||||||
|
const [keyError, setKeyError] = useState<string | undefined>();
|
||||||
|
|
||||||
|
const announceBindings = useCallback(() => {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
|
window.dispatchEvent(new CustomEvent(BINDINGS_CHANGED_EVENT));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!recording || !chat) return;
|
||||||
|
const onKey = (event: KeyboardEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
if (event.key === 'Escape' && recording !== 'reject'
|
||||||
|
&& !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
|
||||||
|
setRecording(null);
|
||||||
|
setKeyError(undefined);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const key = event.key === 'Enter' ? 'Enter' : event.key === 'Escape' ? 'Escape' : undefined;
|
||||||
|
if (!key) {
|
||||||
|
setKeyError(copy.shortcutErrorKey);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const binding: ApprovalBinding = {
|
||||||
|
key,
|
||||||
|
primary: event.ctrlKey || event.metaKey,
|
||||||
|
shift: event.shiftKey,
|
||||||
|
alt: event.altKey,
|
||||||
|
};
|
||||||
|
const verdict = validateBinding(recording, binding, bindings);
|
||||||
|
if (verdict === 'key') { setKeyError(copy.shortcutErrorKey); return; }
|
||||||
|
if (verdict === 'modifier') { setKeyError(copy.shortcutErrorModifier); return; }
|
||||||
|
if (verdict === 'conflict') { setKeyError(copy.shortcutErrorConflict); return; }
|
||||||
|
chat.actions.setApprovalBinding(recording, binding);
|
||||||
|
announceBindings();
|
||||||
|
setRecording(null);
|
||||||
|
setKeyError(undefined);
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', onKey, true);
|
||||||
|
return () => window.removeEventListener('keydown', onKey, true);
|
||||||
|
}, [recording, chat, chatSnap, copy, bindings, announceBindings]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={css.section} data-better-chat-settings>
|
||||||
|
{chat ? (
|
||||||
|
<section className={css.block} data-better-chat-shortcuts>
|
||||||
|
<div className={css.title}>{text(props, copy, 'shortcutTitle')}</div>
|
||||||
|
<p className={css.desc}>{text(props, copy, 'shortcutDescription')}</p>
|
||||||
|
{([
|
||||||
|
['allow', 'shortcutAllow', bindings.allow],
|
||||||
|
['always', 'shortcutAlways', bindings.always],
|
||||||
|
['reject', 'shortcutReject', bindings.reject],
|
||||||
|
] as const).map(([action, title, binding]) => (
|
||||||
|
<div className={css.row} key={action}>
|
||||||
|
<div className={css.rowText}>
|
||||||
|
<div className={css.title}>{text(props, copy, title)}</div>
|
||||||
|
</div>
|
||||||
|
<div className={css.keyActions}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={css.keyButton}
|
||||||
|
data-recording={recording === action || undefined}
|
||||||
|
onClick={() => { setKeyError(undefined); setRecording(action); }}
|
||||||
|
>
|
||||||
|
{recording === action
|
||||||
|
? text(props, copy, 'shortcutRecording')
|
||||||
|
: binding ? bindingKeycap(binding, mac) : text(props, copy, 'shortcutDisabled')}
|
||||||
|
</button>
|
||||||
|
{action === 'always' && binding ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={css.button}
|
||||||
|
onClick={() => {
|
||||||
|
chat.actions.setApprovalBinding('always', null);
|
||||||
|
announceBindings();
|
||||||
|
setKeyError(undefined);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{text(props, copy, 'shortcutDisable')}
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{keyError ? <p className={css.error} data-better-chat-key-error>{keyError}</p> : null}
|
||||||
|
<div className={css.actions}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={css.button}
|
||||||
|
onClick={() => {
|
||||||
|
chat.actions.resetApprovalBindings();
|
||||||
|
announceBindings();
|
||||||
|
setRecording(null);
|
||||||
|
setKeyError(undefined);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{text(props, copy, 'shortcutReset')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,165 @@
|
||||||
|
/**
|
||||||
|
* 功能一:审批卡片的回车批准 / Esc 拒绝(自动送入焦点 + 全局兜底路由)。
|
||||||
|
*
|
||||||
|
* 背景(@deepseek-ai/dsh-client-ui-approval):官方审批卡自带键盘处理
|
||||||
|
* —— Enter 批准(单次)、Esc 拒绝 —— 但 keydown 挂在卡片根节点上,且
|
||||||
|
* 要求焦点先落在卡片内。审批弹出时焦点往往还在对话区,按回车毫无反应。
|
||||||
|
*
|
||||||
|
* 本模块补两件事,不改官方任何逻辑:
|
||||||
|
* 1. 审批卡出现时,若用户没有正在别处输入,把焦点送进卡片详情区。
|
||||||
|
* 2. 焦点不在卡片内时兜底路由:document 捕获阶段拦 keydown,点击卡片
|
||||||
|
* 操作行里的按钮 —— 回车点「允许(单次)」,Esc 点「拒绝」。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const CARD_SELECTOR = '[data-approval-key]'
|
||||||
|
const SCROLL_SELECTOR = '[data-approval-scroll]'
|
||||||
|
const EDITABLE_SELECTOR = 'input, textarea, select, [contenteditable="true"], [contenteditable=""]'
|
||||||
|
|
||||||
|
import {
|
||||||
|
DEFAULT_BINDINGS,
|
||||||
|
bindingMatches,
|
||||||
|
isPlainBinding,
|
||||||
|
type ApprovalAction,
|
||||||
|
type ApprovalBinding,
|
||||||
|
type ApprovalBindings,
|
||||||
|
} from './bindings.js'
|
||||||
|
|
||||||
|
export interface KeyActionInput {
|
||||||
|
key: string
|
||||||
|
ctrlKey?: boolean
|
||||||
|
metaKey?: boolean
|
||||||
|
altKey?: boolean
|
||||||
|
shiftKey?: boolean
|
||||||
|
repeat?: boolean
|
||||||
|
isComposing?: boolean
|
||||||
|
keyCode?: number
|
||||||
|
defaultPrevented?: boolean
|
||||||
|
target?: Element | null
|
||||||
|
activeElement?: Element | null
|
||||||
|
card?: Element | null
|
||||||
|
/** 卡片是否有可用的「始终允许」按钮(第三个操作按钮)。 */
|
||||||
|
hasAlways?: boolean
|
||||||
|
/** 当前快捷键绑定;缺省使用 DEFAULT_BINDINGS。 */
|
||||||
|
bindings?: ApprovalBindings
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 卡片操作行的按钮:详情滚动区之外的全部按钮,顺序 [拒绝, 允许, 始终允许?]。 */
|
||||||
|
export function actionButtons(card: Element): HTMLButtonElement[] {
|
||||||
|
return [...card.querySelectorAll('button')].filter(
|
||||||
|
(button) => !button.closest(SCROLL_SELECTOR),
|
||||||
|
) as HTMLButtonElement[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 找当前可作答的审批卡(DOM 顺序第一张未作答、按钮齐全的卡)。 */
|
||||||
|
export function findPendingCard(doc: Document): Element | null {
|
||||||
|
for (const card of doc.querySelectorAll(CARD_SELECTOR)) {
|
||||||
|
if (card.getAttribute('aria-busy') === 'true') continue
|
||||||
|
const buttons = actionButtons(card)
|
||||||
|
if (buttons.length >= 2 && !buttons[0].disabled && !buttons[1].disabled) return card
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 纯判定:这次 keydown 是否应该路由到审批卡。
|
||||||
|
*
|
||||||
|
* 默认绑定:Enter → 允许(单次)、Ctrl/Cmd+Enter → 始终允许、Esc → 拒绝;
|
||||||
|
* 绑定可由设置页改写(见 bindings.ts),基础键固定 Enter/Escape,只调修饰键。
|
||||||
|
* 官方卡片本身对带修饰键的按键不作答,所以带修饰键的绑定即使在卡内也由
|
||||||
|
* 本插件处理;裸 Enter/Esc 在卡内交给官方。
|
||||||
|
*
|
||||||
|
* @returns 'allow' | 'reject' | 'always' | null
|
||||||
|
*/
|
||||||
|
export function decideKeyAction(input: KeyActionInput): 'allow' | 'reject' | 'always' | null {
|
||||||
|
const {
|
||||||
|
repeat, isComposing, keyCode, defaultPrevented, target, activeElement, card, hasAlways,
|
||||||
|
} = input
|
||||||
|
if (!card) return null
|
||||||
|
if (defaultPrevented) return null
|
||||||
|
if (repeat || isComposing || keyCode === 229) return null
|
||||||
|
// 正在输入控件里打字时一律不拦截(含卡片内的输入框)。
|
||||||
|
if (target && typeof target.closest === 'function' && target.closest(EDITABLE_SELECTOR) !== null) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
const bindings = input.bindings ?? DEFAULT_BINDINGS
|
||||||
|
const candidates: Array<[ApprovalAction, ApprovalBinding | null]> = [
|
||||||
|
['allow', bindings.allow],
|
||||||
|
['always', hasAlways ? bindings.always : null],
|
||||||
|
['reject', bindings.reject],
|
||||||
|
]
|
||||||
|
|
||||||
|
for (const [action, binding] of candidates) {
|
||||||
|
if (!binding || !bindingMatches(binding, input)) continue
|
||||||
|
if (isPlainBinding(binding)) {
|
||||||
|
// 裸键在卡内交给官方;Enter 落在别的按钮/链接上时保留它自己的行为。
|
||||||
|
if (activeElement && card.contains(activeElement)) return null
|
||||||
|
if (binding.key === 'Enter' && target && typeof target.closest === 'function'
|
||||||
|
&& target.closest('button, a[href], [role="button"]') !== null) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return action
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 纯判定:审批卡出现时是否应该把焦点送进详情区。 */
|
||||||
|
export function shouldAutoFocus(activeElement: Element | null | undefined, card: Element): boolean {
|
||||||
|
if (!activeElement) return true
|
||||||
|
if (activeElement === card.ownerDocument?.body) return true
|
||||||
|
if (card.contains(activeElement)) return false // 已经在卡里
|
||||||
|
if (typeof activeElement.closest === 'function' && activeElement.closest(EDITABLE_SELECTOR) !== null) {
|
||||||
|
return false // 正在别处输入
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 安装审批键盘增强,返回卸载函数。 */
|
||||||
|
export function install(doc: Document, getBindings?: () => ApprovalBindings): () => void {
|
||||||
|
const focusedCards = new WeakSet<Element>()
|
||||||
|
|
||||||
|
const tryAutoFocus = (): void => {
|
||||||
|
const card = findPendingCard(doc)
|
||||||
|
if (!card || focusedCards.has(card)) return
|
||||||
|
focusedCards.add(card)
|
||||||
|
if (!shouldAutoFocus(doc.activeElement, card)) return
|
||||||
|
const region = card.querySelector(SCROLL_SELECTOR)
|
||||||
|
if (region && typeof (region as HTMLElement).focus === 'function') (region as HTMLElement).focus()
|
||||||
|
}
|
||||||
|
|
||||||
|
const observer = new MutationObserver(tryAutoFocus)
|
||||||
|
observer.observe(doc.documentElement, { childList: true, subtree: true })
|
||||||
|
tryAutoFocus()
|
||||||
|
|
||||||
|
const onKeyDown = (event: KeyboardEvent): void => {
|
||||||
|
const card = findPendingCard(doc)
|
||||||
|
if (!card) return
|
||||||
|
const buttons = actionButtons(card)
|
||||||
|
const hasAlways = buttons.length >= 3 && !buttons[2].disabled
|
||||||
|
const action = decideKeyAction({
|
||||||
|
key: event.key,
|
||||||
|
ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey,
|
||||||
|
repeat: event.repeat, isComposing: event.isComposing, keyCode: event.keyCode,
|
||||||
|
defaultPrevented: event.defaultPrevented,
|
||||||
|
target: event.target as Element | null, activeElement: doc.activeElement, card, hasAlways,
|
||||||
|
bindings: getBindings?.() ?? DEFAULT_BINDINGS,
|
||||||
|
})
|
||||||
|
if (!action) return
|
||||||
|
const button = action === 'allow'
|
||||||
|
? buttons[1]
|
||||||
|
: action === 'always'
|
||||||
|
? buttons[2]
|
||||||
|
: buttons[0]
|
||||||
|
if (!button || button.disabled) return
|
||||||
|
event.preventDefault()
|
||||||
|
event.stopPropagation()
|
||||||
|
button.click()
|
||||||
|
}
|
||||||
|
doc.addEventListener('keydown', onKeyDown, true)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
observer.disconnect()
|
||||||
|
doc.removeEventListener('keydown', onKeyDown, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
/**
|
||||||
|
* 聊天增强的持久化设置:审批卡快捷键。存储键 `dsh.better-chat.v1`,由宿主
|
||||||
|
* 客户端 store 的 persist 机制写入配置,重启后仍在。
|
||||||
|
*/
|
||||||
|
import { defineStore } from '@deepseek-ai/dsh-client-store'
|
||||||
|
import type { EngineStoreHandle } from '@deepseek-ai/dsh-client-store'
|
||||||
|
import {
|
||||||
|
normalizeBindings,
|
||||||
|
type ApprovalAction,
|
||||||
|
type ApprovalBinding,
|
||||||
|
type ApprovalBindings,
|
||||||
|
} from './bindings.js'
|
||||||
|
|
||||||
|
export interface ChatState {
|
||||||
|
bindings: ApprovalBindings
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ChatActionsDecl = {
|
||||||
|
setApprovalBinding: (draft: ChatState, action: ApprovalAction, binding: ApprovalBinding | null) => void
|
||||||
|
resetApprovalBindings: (draft: ChatState) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatPrefs {
|
||||||
|
getSnapshot: () => ChatState
|
||||||
|
subscribe: (fn: () => void) => () => void
|
||||||
|
actions: {
|
||||||
|
setApprovalBinding: (action: ApprovalAction, binding: ApprovalBinding | null) => void
|
||||||
|
resetApprovalBindings: () => void
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CHAT_PREFS_KEY = 'dsh.better-chat.v1'
|
||||||
|
|
||||||
|
export function createChatStore(): EngineStoreHandle<ChatState, ChatActionsDecl> {
|
||||||
|
return defineStore({
|
||||||
|
init: (): ChatState => ({ bindings: normalizeBindings(undefined) }),
|
||||||
|
persist: CHAT_PREFS_KEY,
|
||||||
|
actions: {
|
||||||
|
setApprovalBinding: (draft, action: ApprovalAction, binding: ApprovalBinding | null) => {
|
||||||
|
draft.bindings = normalizeBindings({ ...draft.bindings, [action]: binding })
|
||||||
|
},
|
||||||
|
resetApprovalBindings: (draft) => {
|
||||||
|
draft.bindings = normalizeBindings(undefined)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从设置实例读取当前绑定;旧快照/非法值自动回落默认。 */
|
||||||
|
export function currentBindings(prefs: ChatPrefs | undefined): ApprovalBindings {
|
||||||
|
try {
|
||||||
|
return normalizeBindings(prefs?.getSnapshot())
|
||||||
|
} catch {
|
||||||
|
return normalizeBindings(undefined)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,165 @@
|
||||||
|
/**
|
||||||
|
* 审批卡快捷键模型:默认 Enter 允许(单次)、Ctrl+Enter 始终允许、Esc 拒绝。
|
||||||
|
*
|
||||||
|
* 允许自定义:允许/始终允许固定在 Enter 上、拒绝固定在 Esc 上,只让修饰键可调,
|
||||||
|
* 避免把普通字母键变成全局快捷键。`primary` 表示 Windows/Linux 的 Ctrl、macOS 的
|
||||||
|
* Cmd —— 判定时 Ctrl 或 Meta 任一按下即算命中,展示时按平台显示 Ctrl/Cmd。
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type ApprovalAction = 'allow' | 'always' | 'reject'
|
||||||
|
export type ApprovalBaseKey = 'Enter' | 'Escape'
|
||||||
|
|
||||||
|
export interface ApprovalBinding {
|
||||||
|
key: ApprovalBaseKey
|
||||||
|
/** Ctrl(Windows/Linux)或 Cmd(macOS)。 */
|
||||||
|
primary: boolean
|
||||||
|
shift: boolean
|
||||||
|
alt: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApprovalBindings {
|
||||||
|
allow: ApprovalBinding
|
||||||
|
/** null = 不绑定「始终允许」。 */
|
||||||
|
always: ApprovalBinding | null
|
||||||
|
reject: ApprovalBinding
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface KeyEventLike {
|
||||||
|
key: string
|
||||||
|
ctrlKey?: boolean
|
||||||
|
metaKey?: boolean
|
||||||
|
shiftKey?: boolean
|
||||||
|
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: DEFAULT_ALWAYS,
|
||||||
|
reject: { key: 'Escape', primary: false, shift: false, alt: false },
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 设置页保存快捷键后派发的窗口事件;提示与判定都靠实时 getter,无需重启。 */
|
||||||
|
export const BINDINGS_CHANGED_EVENT = 'better-chat:bindings-changed'
|
||||||
|
|
||||||
|
/** 每个动作允许的基础键:允许类只能用 Enter,拒绝只能用 Esc。 */
|
||||||
|
export function baseKeyFor(action: ApprovalAction): ApprovalBaseKey {
|
||||||
|
return action === 'reject' ? 'Escape' : 'Enter'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 展示用键帽文案,例如 Enter / Ctrl+Enter / Shift+Alt+Enter / Esc。 */
|
||||||
|
export function bindingKeycap(binding: ApprovalBinding, mac: boolean): string {
|
||||||
|
const parts: string[] = []
|
||||||
|
if (binding.primary) parts.push(mac ? 'Cmd' : 'Ctrl')
|
||||||
|
if (binding.shift) parts.push('Shift')
|
||||||
|
if (binding.alt) parts.push('Alt')
|
||||||
|
parts.push(binding.key === 'Escape' ? 'Esc' : binding.key)
|
||||||
|
return parts.join('+')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 纯判定:按键事件是否命中这条绑定(修饰键必须完全一致)。 */
|
||||||
|
export function bindingMatches(binding: ApprovalBinding, event: KeyEventLike): boolean {
|
||||||
|
const primary = Boolean(event.ctrlKey) || Boolean(event.metaKey)
|
||||||
|
return event.key === binding.key
|
||||||
|
&& primary === binding.primary
|
||||||
|
&& Boolean(event.shiftKey) === binding.shift
|
||||||
|
&& Boolean(event.altKey) === binding.alt
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 是否是不带任何修饰键的裸键(Enter / Esc)。 */
|
||||||
|
export function isPlainBinding(binding: ApprovalBinding | null | undefined): boolean {
|
||||||
|
return Boolean(binding) && !binding!.primary && !binding!.shift && !binding!.alt
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 两条绑定是否相同。 */
|
||||||
|
export function bindingsEqual(
|
||||||
|
left: ApprovalBinding | null | undefined,
|
||||||
|
right: ApprovalBinding | null | undefined,
|
||||||
|
): boolean {
|
||||||
|
if (!left || !right) return left === right
|
||||||
|
return left.key === right.key
|
||||||
|
&& left.primary === right.primary
|
||||||
|
&& left.shift === right.shift
|
||||||
|
&& left.alt === right.alt
|
||||||
|
}
|
||||||
|
|
||||||
|
function booleanOrFalse(value: unknown): boolean {
|
||||||
|
return value === true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 校验并收敛一条绑定;形状不对时返回 undefined。 */
|
||||||
|
export function normalizeBinding(value: unknown): ApprovalBinding | undefined {
|
||||||
|
if (!value || typeof value !== 'object') return undefined
|
||||||
|
const record = value as Record<string, unknown>
|
||||||
|
if (record.key !== 'Enter' && record.key !== 'Escape') return undefined
|
||||||
|
return {
|
||||||
|
key: record.key,
|
||||||
|
primary: booleanOrFalse(record.primary),
|
||||||
|
shift: booleanOrFalse(record.shift),
|
||||||
|
alt: booleanOrFalse(record.alt),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把持久化快照收敛成合法绑定;`{ bindings: ... }` 或内层对象都接受。
|
||||||
|
* 缺失/非法/冲突的项回落到默认值,保证任何旧快照都能用。
|
||||||
|
*/
|
||||||
|
export function normalizeBindings(value: unknown): ApprovalBindings {
|
||||||
|
const inner = value && typeof value === 'object' && 'bindings' in (value as Record<string, unknown>)
|
||||||
|
? (value as Record<string, unknown>).bindings
|
||||||
|
: value
|
||||||
|
const record = inner && typeof inner === 'object' ? inner as Record<string, unknown> : {}
|
||||||
|
const allowRaw = normalizeBinding(record.allow)
|
||||||
|
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_ALWAYS
|
||||||
|
const alwaysParsed = alwaysRaw === null ? null : normalizeBinding(alwaysRaw)
|
||||||
|
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_ALWAYS }
|
||||||
|
}
|
||||||
|
if (out.always && bindingsEqual(out.reject, out.always)) {
|
||||||
|
out.reject = { ...DEFAULT_BINDINGS.reject }
|
||||||
|
}
|
||||||
|
if (bindingsEqual(out.allow, out.reject)) {
|
||||||
|
out.allow = { ...DEFAULT_BINDINGS.allow }
|
||||||
|
out.reject = { ...DEFAULT_BINDINGS.reject }
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasModifier(binding: ApprovalBinding): boolean {
|
||||||
|
return binding.primary || binding.shift || binding.alt
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BindingVerdict = 'ok' | 'key' | 'modifier' | 'conflict'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存前的校验:基础键是否匹配动作、始终允许是否有修饰键、是否与其他动作冲突。
|
||||||
|
*/
|
||||||
|
export function validateBinding(
|
||||||
|
action: ApprovalAction,
|
||||||
|
binding: ApprovalBinding,
|
||||||
|
current: ApprovalBindings,
|
||||||
|
): BindingVerdict {
|
||||||
|
if (binding.key !== baseKeyFor(action)) return 'key'
|
||||||
|
if (action === 'always' && !hasModifier(binding)) return 'modifier'
|
||||||
|
const others: ApprovalBinding[] = []
|
||||||
|
if (action !== 'allow') others.push(current.allow)
|
||||||
|
if (action !== 'always' && current.always) others.push(current.always)
|
||||||
|
if (action !== 'reject') others.push(current.reject)
|
||||||
|
if (others.some((other) => bindingsEqual(other, binding))) return 'conflict'
|
||||||
|
return 'ok'
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,199 @@
|
||||||
|
/**
|
||||||
|
* 审批卡键盘提示:在操作行左侧显示「Enter 允许(单次) · Ctrl+Enter
|
||||||
|
* 始终允许 · Esc 拒绝」的键帽提示,文案直接取卡片按钮的实际文字。
|
||||||
|
*
|
||||||
|
* 提示只是说明,不参与点击:pointer-events: none、aria-hidden,且只挂在
|
||||||
|
* 卡片操作行里(详情滚动区之外)。React 重渲染把提示冲掉时,MutationObserver
|
||||||
|
* 会按按钮文案的签名重新挂回去;卡片作答后(aria-busy)立即移除。
|
||||||
|
*/
|
||||||
|
import { actionButtons } from './approval-keys.js'
|
||||||
|
import {
|
||||||
|
BINDINGS_CHANGED_EVENT,
|
||||||
|
DEFAULT_BINDINGS,
|
||||||
|
bindingKeycap,
|
||||||
|
type ApprovalBindings,
|
||||||
|
} from './bindings.js'
|
||||||
|
|
||||||
|
export const HINT_ATTR = 'data-better-chat-keyhint'
|
||||||
|
const CARD_SELECTOR = '[data-approval-key]'
|
||||||
|
const SEPARATOR = '·'
|
||||||
|
|
||||||
|
export interface HintPart {
|
||||||
|
key: string
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HintLabels {
|
||||||
|
allow?: string
|
||||||
|
always?: string
|
||||||
|
reject?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 纯判定:当前平台是否用 Cmd 代替 Ctrl(只影响提示文案)。 */
|
||||||
|
export function isMacPlatform(platform: string | undefined | null): boolean {
|
||||||
|
return typeof platform === 'string' && /Mac|iPhone|iPad|iPod/.test(platform)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 纯函数:根据卡片上实际存在的按钮文案与当前绑定,生成提示的分段。
|
||||||
|
* 「始终允许」被关掉(binding 为 null)时就不显示这一段。
|
||||||
|
*/
|
||||||
|
export function hintParts(
|
||||||
|
labels: HintLabels,
|
||||||
|
mac: boolean,
|
||||||
|
bindings: ApprovalBindings = DEFAULT_BINDINGS,
|
||||||
|
): HintPart[] {
|
||||||
|
const parts: HintPart[] = []
|
||||||
|
if (labels.allow) parts.push({ key: bindingKeycap(bindings.allow, mac), label: labels.allow })
|
||||||
|
// Use the word "Cmd" instead of the ⌘ glyph: the glyph falls back to a CJK
|
||||||
|
// character under some font stacks, while "Cmd" is always legible.
|
||||||
|
if (labels.always && bindings.always) {
|
||||||
|
parts.push({ key: bindingKeycap(bindings.always, mac), label: labels.always })
|
||||||
|
}
|
||||||
|
if (labels.reject) parts.push({ key: bindingKeycap(bindings.reject, mac), label: labels.reject })
|
||||||
|
return parts
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 纯函数:提示内容的签名,用于判断是否需要重建。 */
|
||||||
|
export function hintSignature(parts: readonly HintPart[]): string {
|
||||||
|
return parts.map((part) => `${part.key}=${part.label}`).join('|')
|
||||||
|
}
|
||||||
|
|
||||||
|
const HINT_CSS = [
|
||||||
|
'margin-right:auto',
|
||||||
|
'display:inline-flex',
|
||||||
|
'flex-wrap:wrap',
|
||||||
|
'align-items:center',
|
||||||
|
'gap:6px',
|
||||||
|
'font-size:12px',
|
||||||
|
'line-height:18px',
|
||||||
|
'color:var(--dsw-alias-label-tertiary,#8b919b)',
|
||||||
|
'user-select:none',
|
||||||
|
'pointer-events:none',
|
||||||
|
].join(';')
|
||||||
|
|
||||||
|
const KEYCAP_CSS = [
|
||||||
|
'display:inline-flex',
|
||||||
|
'align-items:center',
|
||||||
|
'justify-content:center',
|
||||||
|
'height:18px',
|
||||||
|
'padding:0 5px',
|
||||||
|
'border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.35))',
|
||||||
|
'border-bottom-width:2px',
|
||||||
|
'border-radius:5px',
|
||||||
|
'background:var(--dsw-alias-bg-module-platform,rgba(127,127,127,.08))',
|
||||||
|
'font-family:var(--ds-font-family-code,ui-monospace,SFMono-Regular,Consolas,monospace)',
|
||||||
|
'font-size:11px',
|
||||||
|
'line-height:1',
|
||||||
|
'letter-spacing:.2px',
|
||||||
|
].join(';')
|
||||||
|
|
||||||
|
const PAIR_CSS = 'display:inline-flex;align-items:center;gap:5px'
|
||||||
|
const SEPARATOR_CSS = 'opacity:.45;margin:0 2px'
|
||||||
|
|
||||||
|
function labelOf(button: HTMLButtonElement | undefined): string | undefined {
|
||||||
|
if (!button) return undefined
|
||||||
|
const text = button.textContent?.trim()
|
||||||
|
return text ? text : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildHint(doc: Document, parts: readonly HintPart[]): HTMLElement {
|
||||||
|
const hint = doc.createElement('div')
|
||||||
|
hint.setAttribute(HINT_ATTR, '')
|
||||||
|
hint.setAttribute('role', 'note')
|
||||||
|
hint.setAttribute('aria-hidden', 'true')
|
||||||
|
hint.style.cssText = HINT_CSS
|
||||||
|
parts.forEach((part, index) => {
|
||||||
|
if (index > 0) {
|
||||||
|
const separator = doc.createElement('span')
|
||||||
|
separator.textContent = SEPARATOR
|
||||||
|
separator.style.cssText = SEPARATOR_CSS
|
||||||
|
hint.append(separator)
|
||||||
|
}
|
||||||
|
const pair = doc.createElement('span')
|
||||||
|
pair.style.cssText = PAIR_CSS
|
||||||
|
const keycap = doc.createElement('span')
|
||||||
|
keycap.textContent = part.key
|
||||||
|
keycap.style.cssText = KEYCAP_CSS
|
||||||
|
const label = doc.createElement('span')
|
||||||
|
label.textContent = part.label
|
||||||
|
pair.append(keycap, label)
|
||||||
|
hint.append(pair)
|
||||||
|
})
|
||||||
|
return hint
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeHints(doc: Document): void {
|
||||||
|
for (const hint of doc.querySelectorAll(`[${HINT_ATTR}]`)) hint.remove()
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface KeyHintOptions {
|
||||||
|
/** 用于区分 Cmd/Ctrl;默认读 navigator.platform。 */
|
||||||
|
platform?: string | null
|
||||||
|
/** 当前绑定;设置页保存后会派发 BINDINGS_CHANGED_EVENT 触发重建。 */
|
||||||
|
getBindings?: () => ApprovalBindings
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 安装审批卡键盘提示,返回卸载函数。 */
|
||||||
|
export function installKeyHints(doc: Document, options: KeyHintOptions = {}): () => void {
|
||||||
|
const platform = options.platform ?? doc.defaultView?.navigator?.platform
|
||||||
|
const mac = isMacPlatform(platform)
|
||||||
|
const getBindings = options.getBindings ?? (() => DEFAULT_BINDINGS)
|
||||||
|
let disposed = false
|
||||||
|
|
||||||
|
const syncCard = (card: Element): void => {
|
||||||
|
const buttons = actionButtons(card)
|
||||||
|
const existing = card.querySelector(`[${HINT_ATTR}]`)
|
||||||
|
const answered = card.getAttribute('aria-busy') === 'true'
|
||||||
|
if (answered || buttons.length < 2 || buttons[0].disabled || buttons[1].disabled) {
|
||||||
|
existing?.remove()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const always = buttons.length >= 3 && !buttons[2].disabled ? buttons[2] : undefined
|
||||||
|
const parts = hintParts({
|
||||||
|
allow: labelOf(buttons[1]),
|
||||||
|
always: labelOf(always),
|
||||||
|
reject: labelOf(buttons[0]),
|
||||||
|
}, mac, getBindings())
|
||||||
|
if (parts.length === 0) {
|
||||||
|
existing?.remove()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const signature = hintSignature(parts)
|
||||||
|
if (existing && existing.getAttribute('data-signature') === signature) return
|
||||||
|
existing?.remove()
|
||||||
|
const row = buttons[0].parentElement
|
||||||
|
if (!row) return
|
||||||
|
const hint = buildHint(doc, parts)
|
||||||
|
hint.setAttribute('data-signature', signature)
|
||||||
|
row.insertBefore(hint, row.firstChild)
|
||||||
|
}
|
||||||
|
|
||||||
|
const sync = (): void => {
|
||||||
|
if (disposed) return
|
||||||
|
const cards = doc.querySelectorAll(CARD_SELECTOR)
|
||||||
|
if (cards.length === 0) {
|
||||||
|
removeHints(doc)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for (const card of cards) syncCard(card)
|
||||||
|
}
|
||||||
|
|
||||||
|
const observer = new MutationObserver(sync)
|
||||||
|
observer.observe(doc.documentElement, {
|
||||||
|
childList: true,
|
||||||
|
subtree: true,
|
||||||
|
attributes: true,
|
||||||
|
attributeFilter: ['aria-busy', 'disabled'],
|
||||||
|
})
|
||||||
|
const view = doc.defaultView
|
||||||
|
view?.addEventListener?.(BINDINGS_CHANGED_EVENT, sync)
|
||||||
|
sync()
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
disposed = true
|
||||||
|
observer.disconnect()
|
||||||
|
view?.removeEventListener?.(BINDINGS_CHANGED_EVENT, sync)
|
||||||
|
removeHints(doc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,322 @@
|
||||||
|
/**
|
||||||
|
* 功能二:权限策略 —— 去掉「完全权限」选项,新会话默认「自动审查」。
|
||||||
|
*
|
||||||
|
* 会话权限有四个预设值:read-only(仅可查看)、workspace-write(工作区内
|
||||||
|
* 修改)、danger-full-access(完全权限)、auto(自动审查,EXP)。「自动
|
||||||
|
* 审查」由实验层 @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`)和子代理会话不会被改写;用户手
|
||||||
|
* 动切回只读/工作区修改后,刷新或重载也不会被覆盖。
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** 完全权限的预设机器值。 */
|
||||||
|
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 {
|
||||||
|
if (typeof text !== 'string') return false
|
||||||
|
const trimmed = text.trim()
|
||||||
|
return FULL_ACCESS_LABELS.some((label) => trimmed === label || trimmed.startsWith(label))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 纯判定:这个会话现在是否应该被切到自动审查。 */
|
||||||
|
export function shouldAutoSwitch(preset: string | undefined | null, alreadyHandled: boolean): boolean {
|
||||||
|
return preset !== undefined && preset !== null && preset !== AUTO_REVIEW_PRESET && !alreadyHandled
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LiveSession {
|
||||||
|
id: string
|
||||||
|
live: any
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 防御式枚举宿主的 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[] {
|
||||||
|
const out: LiveSession[] = []
|
||||||
|
if (!sessions || typeof sessions !== 'object') return out
|
||||||
|
try {
|
||||||
|
if (typeof sessions.keys === 'function' && typeof sessions.binding === 'function') {
|
||||||
|
for (const id of sessions.keys()) {
|
||||||
|
const live = sessions.binding(id)?.session
|
||||||
|
if (live) out.push({ id, live })
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
if (typeof sessions.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 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 服务形状不同:放弃枚举
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读会话当前的权限预设值(投影不可用时返回 undefined)。
|
||||||
|
* 兼容 DSH 0.2.2 的 `{ currentValue: string }` 投影视图与直接返回字符串的测试桩。
|
||||||
|
*/
|
||||||
|
export function currentPreset(live: any): string | undefined {
|
||||||
|
try {
|
||||||
|
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。
|
||||||
|
* @returns 摘掉的个数
|
||||||
|
*/
|
||||||
|
export function pruneFullAccess(doc: Document): number {
|
||||||
|
let removed = 0
|
||||||
|
for (const option of doc.querySelectorAll('option')) {
|
||||||
|
if (isFullAccessLabel(option.textContent)) {
|
||||||
|
option.remove()
|
||||||
|
removed++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const item of doc.querySelectorAll('[role="listbox"] [role="option"], [role="menu"] [role="menuitem"]')) {
|
||||||
|
if (isFullAccessLabel(item.textContent)) {
|
||||||
|
item.remove()
|
||||||
|
removed++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return removed
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PolicyTimers {
|
||||||
|
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),
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 安装权限策略:
|
||||||
|
* 1. 观察 DOM、摘掉「完全权限」选项;
|
||||||
|
* 2. 观察/轮询空白新建会话,首次见到时自动切到 `auto`(自动审查)。
|
||||||
|
* @returns 卸载函数
|
||||||
|
*/
|
||||||
|
export function installPermissionPolicy(
|
||||||
|
doc: Document,
|
||||||
|
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(() => {
|
||||||
|
scanTimer = 0
|
||||||
|
if (!disposed) pruneFullAccess(doc)
|
||||||
|
}, 120)
|
||||||
|
}
|
||||||
|
const observer = new MutationObserver(scheduleScan)
|
||||||
|
if (doc.body) observer.observe(doc.body, { childList: true, subtree: true })
|
||||||
|
pruneFullAccess(doc)
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,190 @@
|
||||||
|
/**
|
||||||
|
* 功能三:插件商店「更新」按钮。
|
||||||
|
*
|
||||||
|
* DSH 只给官方插件原地更新;从自定义索引装的插件在发现页只有「有新版本」
|
||||||
|
* 标签、没有按钮。这里补一个真按钮:数据与动作都走宿主自己的远程服务
|
||||||
|
* ——pluginMarket 查索引和安装状态,pluginManager.installBundle 按索引
|
||||||
|
* 给出的精确 spec 覆盖安装——与官方安装流程同一套接口,不模拟点击、
|
||||||
|
* 不动官方状态。
|
||||||
|
*
|
||||||
|
* 服务经子插件声明 inject 取用:主插件保持自己的 inject,商店功能不
|
||||||
|
* 依赖这些服务;未启用实验性插件索引时子插件不生效,本功能静默关闭。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const UPDATE_LABELS = ['有新版本', 'Update available']
|
||||||
|
|
||||||
|
export interface StoreUpdate {
|
||||||
|
name: string
|
||||||
|
title: string
|
||||||
|
installedVersion: string
|
||||||
|
version: string
|
||||||
|
spec: string
|
||||||
|
registry?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 索引条目的本地化标题在当前语言下的文本(与发现页行内展示一致)。 */
|
||||||
|
export function localizedTitle(title: unknown, lang: string): string {
|
||||||
|
if (typeof title === 'string') return title
|
||||||
|
if (!title || typeof title !== 'object') return ''
|
||||||
|
const record = title as Record<string, unknown>
|
||||||
|
const chain = [lang, lang && lang.split('-')[0], 'zh-CN', 'en']
|
||||||
|
for (const key of chain) {
|
||||||
|
if (key && typeof record[key] === 'string' && record[key]) return record[key] as string
|
||||||
|
}
|
||||||
|
const values = Object.values(record)
|
||||||
|
return typeof values[0] === 'string' ? (values[0] as string) : ''
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 从各索引的搜索结果里挑出「有新版本」的条目,整理成可执行的更新计划。 */
|
||||||
|
export function pickUpdates(searchResults: any[], lang: string): StoreUpdate[] {
|
||||||
|
const updates: StoreUpdate[] = []
|
||||||
|
for (const result of searchResults ?? []) {
|
||||||
|
const entries = result?.value?.entries ?? result?.entries ?? []
|
||||||
|
for (const entry of entries as any[]) {
|
||||||
|
if (entry?.installation?.status !== 'update-available') continue
|
||||||
|
const versions = entry.versions ?? []
|
||||||
|
const version = versions.find((candidate: any) => candidate.version === entry.defaultVersion) ?? versions[0]
|
||||||
|
const spec = version?.install?.spec
|
||||||
|
if (!entry.name || !version?.version || !spec) continue
|
||||||
|
updates.push({
|
||||||
|
name: entry.name,
|
||||||
|
title: localizedTitle(entry.title, lang) || entry.name,
|
||||||
|
installedVersion: entry.installation.installedVersion ?? '',
|
||||||
|
version: version.version,
|
||||||
|
spec,
|
||||||
|
registry: version.install.registry,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return updates
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 执行一次更新:按索引 spec 覆盖安装,宿主结果信封原样返回。 */
|
||||||
|
export async function runUpdate(remote: any, update: StoreUpdate, makeRequestId?: () => string | undefined): Promise<any> {
|
||||||
|
const requestId = makeRequestId ? makeRequestId() : 'better-chat-update-' + Date.now()
|
||||||
|
return remote.pluginManager.installBundle(update.spec, {
|
||||||
|
enabled: true,
|
||||||
|
requestId,
|
||||||
|
...(update.registry ? { registry: update.registry } : {}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发现页里某个插件的行:状态标签本身是个按钮,从它向上找第一个
|
||||||
|
* 同时包含插件标题、且文本总量还像一行的祖先。
|
||||||
|
*/
|
||||||
|
export function findUpdateRow(doc: Document, title: string): Element | null {
|
||||||
|
for (const element of doc.querySelectorAll('button')) {
|
||||||
|
if (!UPDATE_LABELS.includes(element.textContent?.trim() ?? '')) continue
|
||||||
|
let node: Element | null = element
|
||||||
|
for (let depth = 0; depth < 6 && node; depth++) {
|
||||||
|
node = node.parentElement
|
||||||
|
if (node && node.textContent?.includes(title) && node.textContent.length < 600) return node
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 更新按钮的点击处理:确认 → 调宿主覆盖安装 → 按结果改按钮文案。 */
|
||||||
|
export function makeUpdateClickHandler(
|
||||||
|
doc: Document,
|
||||||
|
getRemote: () => any,
|
||||||
|
update: StoreUpdate,
|
||||||
|
button: HTMLButtonElement,
|
||||||
|
): (event?: Event) => Promise<void> {
|
||||||
|
return async (event?: Event): Promise<void> => {
|
||||||
|
event?.preventDefault?.()
|
||||||
|
event?.stopPropagation?.()
|
||||||
|
const view = doc.defaultView as (Window & typeof globalThis) | null
|
||||||
|
const ask = view?.confirm ?? (globalThis as any).confirm
|
||||||
|
const message = '更新「' + update.title + '」'
|
||||||
|
+ (update.installedVersion ? ' ' + update.installedVersion : '')
|
||||||
|
+ ' → ' + update.version + '?\n会直接覆盖安装新版,插件数据保留。'
|
||||||
|
if (ask && !ask.call(view ?? globalThis, message)) return
|
||||||
|
button.disabled = true
|
||||||
|
button.textContent = '更新中…'
|
||||||
|
try {
|
||||||
|
const result = await runUpdate(getRemote(), update, () => (globalThis as any).crypto?.randomUUID?.() ?? undefined)
|
||||||
|
if (result?.value?.application === 'applied') {
|
||||||
|
button.textContent = '已更新,重启 DSH 后生效'
|
||||||
|
} else {
|
||||||
|
console.error('[dsh-better-chat] update failed for', update.name, result?.value?.error ?? result)
|
||||||
|
button.disabled = false
|
||||||
|
button.textContent = '更新失败,点此重试'
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[dsh-better-chat] update failed for', update.name, error)
|
||||||
|
button.disabled = false
|
||||||
|
button.textContent = '更新失败,点此重试'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StoreTimers {
|
||||||
|
setInterval: (fn: () => void, ms: number) => number
|
||||||
|
clearInterval: (id: number) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 发现页增强:轮询索引状态,把「更新」按钮挂到有新版本的行上。 */
|
||||||
|
export function installStoreUpdateButtons(
|
||||||
|
doc: Document,
|
||||||
|
getRemote: () => any,
|
||||||
|
timers: StoreTimers = {
|
||||||
|
setInterval: (fn, ms) => setInterval(fn, ms) as unknown as number,
|
||||||
|
clearInterval: (id) => clearInterval(id),
|
||||||
|
},
|
||||||
|
): () => void {
|
||||||
|
let disposed = false
|
||||||
|
let updates: StoreUpdate[] = []
|
||||||
|
const decorate = (): void => {
|
||||||
|
for (const update of updates) {
|
||||||
|
const row = findUpdateRow(doc, update.title)
|
||||||
|
if (!row || row.querySelector('[data-better-chat-update]')) continue
|
||||||
|
const button = doc.createElement('button')
|
||||||
|
button.type = 'button'
|
||||||
|
button.setAttribute('data-better-chat-update', update.name)
|
||||||
|
button.textContent = '更新到 ' + update.version
|
||||||
|
button.style.cssText = 'flex:none;margin-left:8px;padding:2px 10px;border:1px solid #7f7f7f55;border-radius:999px;background:transparent;color:inherit;font-size:12px;cursor:pointer'
|
||||||
|
button.addEventListener('click', makeUpdateClickHandler(doc, getRemote, update, button))
|
||||||
|
row.appendChild(button)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const refresh = async (): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const remote = getRemote()
|
||||||
|
if (!remote?.pluginMarket || !remote?.pluginManager) return
|
||||||
|
const indexes = await remote.pluginMarket.listIndexes()
|
||||||
|
const urls = (indexes?.value ?? indexes ?? []).map((entry: any) => entry?.url).filter(Boolean)
|
||||||
|
const results: any[] = []
|
||||||
|
for (const url of urls) {
|
||||||
|
results.push(await remote.pluginMarket.search(url, { sort: { kind: 'index' }, offset: 0, limit: 100 }))
|
||||||
|
}
|
||||||
|
if (disposed) return
|
||||||
|
updates = pickUpdates(results, doc.documentElement?.lang || 'zh-CN')
|
||||||
|
decorate()
|
||||||
|
} catch {
|
||||||
|
// 索引服务不可用(未启用实验性插件索引等):静默关闭本功能。
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const observer = new MutationObserver(() => decorate())
|
||||||
|
observer.observe(doc.documentElement, { childList: true, subtree: true })
|
||||||
|
const timer = timers.setInterval(() => { void refresh() }, 30000)
|
||||||
|
void refresh()
|
||||||
|
return () => {
|
||||||
|
disposed = true
|
||||||
|
observer.disconnect()
|
||||||
|
timers.clearInterval(timer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 商店更新子插件:单独声明远程服务 inject,与主功能互相隔离。 */
|
||||||
|
export const storeUpdatePlugin = {
|
||||||
|
name: 'dsh-better-chat-store-update',
|
||||||
|
inject: ['remote', 'remote.pluginMarket', 'remote.pluginManager'],
|
||||||
|
apply(childCtx: any): void {
|
||||||
|
childCtx.effect(
|
||||||
|
() => installStoreUpdateButtons(document, () => childCtx.remote),
|
||||||
|
'dsh-better-chat: store update buttons',
|
||||||
|
)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
@ -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' {}
|
||||||
|
|
@ -0,0 +1,51 @@
|
||||||
|
/**
|
||||||
|
* dsh-better-chat 客户端入口。
|
||||||
|
*
|
||||||
|
* 聊天增强:审批键盘/提示、权限 UI、商店更新按钮。
|
||||||
|
* 旧的阅读视图已彻底移除,不再注册“阅读”页签、文本变换服务或相关样式/组件;
|
||||||
|
* 另保留 Better Chat 设置页(仅审批快捷键录制)。
|
||||||
|
*
|
||||||
|
* 入口必须导出一个静态字符串 inject 数组(宿主 Cordis 服务注入),
|
||||||
|
* 并在这里统一 apply。审批快捷键的配置存在 dsh.better-chat.v1。
|
||||||
|
*/
|
||||||
|
import type { Context } from '@deepseek-ai/cordis'
|
||||||
|
import { install as installApprovalKeys } from './chat/approval-keys.js'
|
||||||
|
import { createChatStore, currentBindings } from './chat/bindings-store.js'
|
||||||
|
import { installKeyHints } from './chat/key-hint.js'
|
||||||
|
import { installPermissionPolicy } from './chat/permission-policy.js'
|
||||||
|
import { storeUpdatePlugin } from './chat/store-update.js'
|
||||||
|
import { installBetterChatSettings } from './settings.js'
|
||||||
|
|
||||||
|
export const name = 'dsh-better-chat'
|
||||||
|
|
||||||
|
/** 聊天增强本身不额外依赖宿主服务;保留服务注入列表以兼容既有宿主。 */
|
||||||
|
export const inject = [
|
||||||
|
'slots',
|
||||||
|
'sessions',
|
||||||
|
'conversation',
|
||||||
|
'uiConversation',
|
||||||
|
'remote',
|
||||||
|
'remote.session',
|
||||||
|
]
|
||||||
|
|
||||||
|
export function apply(ctx: Context): void {
|
||||||
|
// 审批快捷键:持久化实例在 apply 里创建,避免模块级单例跨插件重载残留。
|
||||||
|
const chatPrefs = createChatStore().create()
|
||||||
|
const getBindings = () => currentBindings(chatPrefs)
|
||||||
|
|
||||||
|
// 聊天增强:纯 DOM 观察,不依赖任何宿主服务。
|
||||||
|
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, () => (ctx as { sessions?: unknown }).sessions),
|
||||||
|
'dsh-better-chat: permission policy (no full access, auto review by default)',
|
||||||
|
)
|
||||||
|
try {
|
||||||
|
ctx.plugin(storeUpdatePlugin as any)
|
||||||
|
} catch {
|
||||||
|
// 子插件挂不上(旧宿主等)不影响主功能。
|
||||||
|
}
|
||||||
|
|
||||||
|
// Better Chat 设置页:仅审批快捷键录制。
|
||||||
|
installBetterChatSettings(ctx, chatPrefs)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,83 @@
|
||||||
|
export type SettingsCopyKey =
|
||||||
|
| 'nav'
|
||||||
|
| 'openTitle'
|
||||||
|
| 'openDescription'
|
||||||
|
| 'glassTitle'
|
||||||
|
| 'glassDescription'
|
||||||
|
| 'foldTitle'
|
||||||
|
| 'foldDescription'
|
||||||
|
| 'foldNone'
|
||||||
|
| 'foldStandard'
|
||||||
|
| 'foldSummary'
|
||||||
|
| 'shortcutTitle'
|
||||||
|
| 'shortcutDescription'
|
||||||
|
| 'shortcutAllow'
|
||||||
|
| 'shortcutAlways'
|
||||||
|
| 'shortcutReject'
|
||||||
|
| 'shortcutRecording'
|
||||||
|
| 'shortcutDisabled'
|
||||||
|
| 'shortcutDisable'
|
||||||
|
| 'shortcutReset'
|
||||||
|
| 'shortcutErrorKey'
|
||||||
|
| 'shortcutErrorModifier'
|
||||||
|
| 'shortcutErrorConflict';
|
||||||
|
|
||||||
|
export type SettingsCopy = Record<SettingsCopyKey, string>;
|
||||||
|
|
||||||
|
export const en: SettingsCopy = {
|
||||||
|
nav: 'Better Chat',
|
||||||
|
openTitle: 'Open deliverables in built-in panel',
|
||||||
|
openDescription: 'Off by default: chips and inline file mentions open in the system app. Turn this on to preview them in the right Sidebar, matching official chat. Reveal and folder actions still use the system file manager.',
|
||||||
|
glassTitle: 'Translucent frosted glass',
|
||||||
|
glassDescription: 'Off by default: reading chrome stays opaque, matching the current Host look. Turn this on to let wallpaper and skins show through the panel; path and count chips stay clear until hover or focus.',
|
||||||
|
foldTitle: 'Auto-fold process',
|
||||||
|
foldDescription: 'Default on: collapses earlier steps when new thoughts appear. Turn off to keep all thinking and tools expanded in full.',
|
||||||
|
foldNone: 'Off',
|
||||||
|
foldStandard: 'On',
|
||||||
|
foldSummary: 'Summary',
|
||||||
|
shortcutTitle: 'Approval card shortcuts',
|
||||||
|
shortcutDescription: 'Click a keycap and press the new combination. Allow-type actions use Enter, reject uses Esc; modifiers are free. Esc alone cancels while recording. Stored in the plugin config.',
|
||||||
|
shortcutAllow: 'Allow once',
|
||||||
|
shortcutAlways: 'Always allow',
|
||||||
|
shortcutReject: 'Reject',
|
||||||
|
shortcutRecording: 'Press keys…',
|
||||||
|
shortcutDisabled: 'Not set',
|
||||||
|
shortcutDisable: 'Clear',
|
||||||
|
shortcutReset: 'Restore defaults',
|
||||||
|
shortcutErrorKey: 'Allow actions must use Enter; reject must use Esc.',
|
||||||
|
shortcutErrorModifier: 'Always allow needs at least one modifier key.',
|
||||||
|
shortcutErrorConflict: 'That combination is already used by another action.',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const zh: SettingsCopy = {
|
||||||
|
nav: 'Better Chat',
|
||||||
|
openTitle: '在内置面板中打开产物',
|
||||||
|
openDescription: '默认关闭:产物芯片和正文中的文件提及会用系统应用打开。打开后与官方对话一致,在右侧栏预览。访达 / 资源管理器中的显示与打开所在文件夹不受此开关控制。',
|
||||||
|
glassTitle: '半透明毛玻璃',
|
||||||
|
glassDescription: '默认关闭:阅读栏保持不透明,和现在的 Host 观感一致。打开后透出宿主壁纸与皮肤;路径、行数等标签静止时透明,悬停或聚焦才显出轮廓。',
|
||||||
|
foldTitle: '自动折叠过程',
|
||||||
|
foldDescription: '默认开启:新思考产生时自动折叠此前步骤。关闭后全程展开,完整保留原始思考与工具流。',
|
||||||
|
foldNone: '关闭',
|
||||||
|
foldStandard: '开启',
|
||||||
|
foldSummary: '摘要',
|
||||||
|
shortcutTitle: '审批卡快捷键',
|
||||||
|
shortcutDescription: '点键帽后按下新的组合键。允许类只能用 Enter,拒绝只能用 Esc,修饰键随意;录制时单独按 Esc 取消。保存在插件配置里,重启后仍在。',
|
||||||
|
shortcutAllow: '允许(单次)',
|
||||||
|
shortcutAlways: '始终允许',
|
||||||
|
shortcutReject: '拒绝',
|
||||||
|
shortcutRecording: '按下组合键…',
|
||||||
|
shortcutDisabled: '未设置',
|
||||||
|
shortcutDisable: '清除',
|
||||||
|
shortcutReset: '恢复默认',
|
||||||
|
shortcutErrorKey: '允许类动作只能用 Enter,拒绝只能用 Esc。',
|
||||||
|
shortcutErrorModifier: '「始终允许」至少需要一个修饰键(Ctrl/Shift/Alt)。',
|
||||||
|
shortcutErrorConflict: '这个组合键已经被另一个动作占用。',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function settingsLanguage(tag: string | undefined): 'zh' | 'en' {
|
||||||
|
return (tag ?? '').toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function settingsCopyFor(tag: string | undefined): SettingsCopy {
|
||||||
|
return settingsLanguage(tag) === 'zh' ? zh : en;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,43 @@
|
||||||
|
import type { Context } from '@deepseek-ai/cordis';
|
||||||
|
import { settingsCopyFor, zh, en } from './settings-copy.js';
|
||||||
|
import { SettingsSection, type BetterChatSettingsInjected } from './SettingsSection.js';
|
||||||
|
import type { ChatPrefs } from './chat/bindings-store.js';
|
||||||
|
|
||||||
|
interface LocaleFace {
|
||||||
|
register?: (ns: string, dicts: { zh: unknown; en: unknown }) => () => void;
|
||||||
|
bind?: (ns: string) => (key: string) => string;
|
||||||
|
getSnapshot?: () => { locale?: string; language?: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
function languageTag(ctx: Context): string | undefined {
|
||||||
|
const locale = (ctx.get?.('locale') ?? (ctx as unknown as { locale?: LocaleFace }).locale) as LocaleFace | undefined;
|
||||||
|
const snap = locale?.getSnapshot?.();
|
||||||
|
return snap?.locale ?? snap?.language
|
||||||
|
?? (typeof document !== 'undefined' ? document.documentElement.lang : undefined)
|
||||||
|
?? (typeof navigator !== 'undefined' ? navigator.language : undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Own locale namespace and settings-section id (chat-only, independent of any display plugin). */
|
||||||
|
const SETTINGS_LOCALE_NS = 'better-chat'
|
||||||
|
const SETTINGS_SECTION_ID = 'better-chat'
|
||||||
|
|
||||||
|
export function installBetterChatSettings(ctx: Context, chat?: ChatPrefs): void {
|
||||||
|
const locale = (ctx.get?.('locale') ?? (ctx as unknown as { locale?: LocaleFace }).locale) as LocaleFace | undefined;
|
||||||
|
if (locale?.register) {
|
||||||
|
ctx.effect(() => locale.register!(SETTINGS_LOCALE_NS, { zh, en }), 'dsh-better-chat: settings copy');
|
||||||
|
}
|
||||||
|
const injected = (): BetterChatSettingsInjected => ({
|
||||||
|
chat,
|
||||||
|
copy: settingsCopyFor(languageTag(ctx)),
|
||||||
|
languageTag: languageTag(ctx),
|
||||||
|
});
|
||||||
|
const slots = (ctx as unknown as { slots: { inject: (name: string, fn: () => unknown) => void; register: (spec: unknown, component: unknown) => unknown } }).slots;
|
||||||
|
slots.inject('settings.section', () => slots.register({
|
||||||
|
name: 'settings.section',
|
||||||
|
id: SETTINGS_SECTION_ID,
|
||||||
|
order: 40,
|
||||||
|
label: () => locale?.bind?.(SETTINGS_LOCALE_NS)?.('nav') || settingsCopyFor(languageTag(ctx)).nav,
|
||||||
|
locale: locale?.bind ? SETTINGS_LOCALE_NS : undefined,
|
||||||
|
inject: injected,
|
||||||
|
}, SettingsSection));
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
declare module '*.module.css' {
|
||||||
|
const classes: Record<string, string>;
|
||||||
|
export default classes;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,110 @@
|
||||||
|
import type { Context } from '@deepseek-ai/cordis';
|
||||||
|
import { createLogger } from './log.js';
|
||||||
|
|
||||||
|
export const name = 'dsh-better-chat';
|
||||||
|
export const inject: string[] = [];
|
||||||
|
|
||||||
|
const log = createLogger({ base: { plugin: name } });
|
||||||
|
|
||||||
|
const AUTO_REVIEW_PRESET = 'auto';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断宿主会话是否为「尚未开始对话、且用户未手动改过权限」的新建空白顶层会话。
|
||||||
|
* - 排除子代理会话(`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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,137 @@
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import type { IncomingMessage } from 'node:http';
|
||||||
|
|
||||||
|
export const REDACTED = '[REDACTED]';
|
||||||
|
|
||||||
|
const REQUEST_ID_HEADER = 'x-request-id';
|
||||||
|
const REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,200}$/;
|
||||||
|
|
||||||
|
const SECRET_KEYS = new Set([
|
||||||
|
'authorization',
|
||||||
|
'proxyauthorization',
|
||||||
|
'cookie',
|
||||||
|
'setcookie',
|
||||||
|
'token',
|
||||||
|
'accesstoken',
|
||||||
|
'refreshtoken',
|
||||||
|
'idtoken',
|
||||||
|
'apikey',
|
||||||
|
'apisecret',
|
||||||
|
'secret',
|
||||||
|
'clientsecret',
|
||||||
|
'password',
|
||||||
|
'passwd',
|
||||||
|
'credential',
|
||||||
|
'credentials',
|
||||||
|
'signature',
|
||||||
|
'sig',
|
||||||
|
'jwt',
|
||||||
|
'bearer',
|
||||||
|
'privatekey',
|
||||||
|
'xapikey',
|
||||||
|
'xauthtoken',
|
||||||
|
'xaccesstoken',
|
||||||
|
'auth',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export type LogFields = Record<string, unknown>;
|
||||||
|
|
||||||
|
export interface Logger {
|
||||||
|
info(msg: string, fields?: LogFields): void;
|
||||||
|
warn(msg: string, fields?: LogFields): void;
|
||||||
|
error(msg: string, fields?: LogFields): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoggerOptions {
|
||||||
|
readonly write?: (line: string) => void;
|
||||||
|
readonly base?: LogFields;
|
||||||
|
readonly clock?: () => Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeKey(key: string): string {
|
||||||
|
return key.toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSecretKey(key: string): boolean {
|
||||||
|
const normalized = normalizeKey(key);
|
||||||
|
if (SECRET_KEYS.has(normalized)) return true;
|
||||||
|
if (normalized === 'requestid' || normalized === 'xrequestid') return false;
|
||||||
|
return /(?:^|[^a-z])(?:token|secret|password|api[-_]?key)$/i.test(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
function redactString(value: string): string {
|
||||||
|
const query = value.replace(/([?&#])([^&#=]+)=([^&#]*)/g, (match, sep: string, rawKey: string) => {
|
||||||
|
let key: string;
|
||||||
|
try {
|
||||||
|
key = decodeURIComponent(rawKey.replace(/\+/g, ' '));
|
||||||
|
} catch {
|
||||||
|
key = rawKey;
|
||||||
|
}
|
||||||
|
return isSecretKey(key) ? `${sep}${rawKey}=${REDACTED}` : match;
|
||||||
|
});
|
||||||
|
return query
|
||||||
|
.replace(/\b(Bearer|Basic)\s+\S+/gi, `$1 ${REDACTED}`)
|
||||||
|
.replace(
|
||||||
|
/\b((?:access[_-]?token|refresh[_-]?token|id[_-]?token|api[_-]?key|client[_-]?secret|password|passwd|authorization|token|secret))(\s*[:=]\s*)([^\s&]+)/gi,
|
||||||
|
`$1$2${REDACTED}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function redact(value: unknown): unknown {
|
||||||
|
return redactValue(undefined, value, 0, new WeakSet());
|
||||||
|
}
|
||||||
|
|
||||||
|
function redactValue(key: string | undefined, value: unknown, depth: number, seen: WeakSet<object>): unknown {
|
||||||
|
if (key !== undefined && isSecretKey(key)) return REDACTED;
|
||||||
|
if (depth > 8) return REDACTED;
|
||||||
|
if (typeof value === 'string') return redactString(value);
|
||||||
|
if (typeof value === 'number' || typeof value === 'boolean' || value === null || value === undefined) return value;
|
||||||
|
if (typeof value !== 'object') return REDACTED;
|
||||||
|
if (value instanceof Date) return value.toISOString();
|
||||||
|
if (value instanceof Error) {
|
||||||
|
return redactValue(undefined, { name: value.name, message: value.message }, depth + 1, seen);
|
||||||
|
}
|
||||||
|
if (seen.has(value)) return REDACTED;
|
||||||
|
seen.add(value);
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.map(item => redactValue(undefined, item, depth + 1, seen));
|
||||||
|
}
|
||||||
|
const output: Record<string, unknown> = {};
|
||||||
|
for (const [childKey, childValue] of Object.entries(value)) {
|
||||||
|
output[childKey] = redactValue(childKey, childValue, depth + 1, seen);
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createLogger(options: LoggerOptions = {}): Logger {
|
||||||
|
const write = options.write ?? ((line: string) => {
|
||||||
|
console.log(line);
|
||||||
|
});
|
||||||
|
const clock = options.clock ?? (() => new Date());
|
||||||
|
const emit = (level: 'info' | 'warn' | 'error', msg: string, fields?: LogFields): void => {
|
||||||
|
const details = redact({ ...options.base, ...fields });
|
||||||
|
const record = {
|
||||||
|
...(details !== null && typeof details === 'object' ? details as LogFields : {}),
|
||||||
|
time: clock().toISOString(),
|
||||||
|
level,
|
||||||
|
msg: redactString(msg),
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
write(JSON.stringify(record));
|
||||||
|
} catch {
|
||||||
|
write(JSON.stringify({ time: record.time, level, msg: record.msg, error: 'log record was not serializable' }));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
info: (msg, fields) => emit('info', msg, fields),
|
||||||
|
warn: (msg, fields) => emit('warn', msg, fields),
|
||||||
|
error: (msg, fields) => emit('error', msg, fields),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requestIdOf(req: IncomingMessage): string {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
@ -1,107 +0,0 @@
|
||||||
// dsh-better-chat 审批快捷键:纯判定与按钮定位的单元测试(假 DOM,零依赖)。
|
|
||||||
import { test } from 'node:test'
|
|
||||||
import assert from 'node:assert/strict'
|
|
||||||
import { actionButtons, findPendingCard, decideKeyAction, shouldAutoFocus } from '../client.js'
|
|
||||||
|
|
||||||
// --- 极小假 DOM:只实现 client.js 用到的表面 ---
|
|
||||||
function matches(el, selector) {
|
|
||||||
return selector.split(',').some((part) => {
|
|
||||||
const s = part.trim()
|
|
||||||
if (s.startsWith('[')) {
|
|
||||||
const m = s.match(/^\[([a-zA-Z-]+)(?:="([^"]*)")?\]$/)
|
|
||||||
if (!m) return false
|
|
||||||
const v = el.attrs[m[1]]
|
|
||||||
return m[2] === undefined ? v !== undefined : v === m[2]
|
|
||||||
}
|
|
||||||
return el.tag === s
|
|
||||||
})
|
|
||||||
}
|
|
||||||
class El {
|
|
||||||
constructor(tag, attrs = {}, children = []) {
|
|
||||||
this.tag = tag; this.attrs = attrs; this.children = []; this.parent = null
|
|
||||||
this.disabled = false; this.clicks = 0; this.focused = 0; this.ownerDocument = null
|
|
||||||
for (const c of children) this.append(c)
|
|
||||||
}
|
|
||||||
append(c) { c.parent = this; this.children.push(c); return c }
|
|
||||||
getAttribute(n) { return this.attrs[n] ?? null }
|
|
||||||
closest(sel) { let e = this; while (e) { if (matches(e, sel)) return e; e = e.parent } return null }
|
|
||||||
contains(other) { let e = other; while (e) { if (e === this) return true; e = e.parent } return false }
|
|
||||||
querySelectorAll(sel) { const out = []; const walk = (e) => { for (const c of e.children) { if (matches(c, sel)) out.push(c); walk(c) } }; walk(this); return out }
|
|
||||||
querySelector(sel) { return this.querySelectorAll(sel)[0] ?? null }
|
|
||||||
click() { this.clicks++ }
|
|
||||||
focus() { this.focused++ }
|
|
||||||
}
|
|
||||||
function approvalCard({ busy = false, withAlways = false, detailButton = false } = {}) {
|
|
||||||
const scrollChildren = detailButton ? [new El('button')] : []
|
|
||||||
const card = new El('div', { 'data-approval-key': 'k1', ...(busy ? { 'aria-busy': 'true' } : {}) }, [
|
|
||||||
new El('div', { 'data-approval-scroll': '' }, scrollChildren),
|
|
||||||
new El('div', {}, [
|
|
||||||
new El('button'), // 拒绝
|
|
||||||
new El('button'), // 允许(单次)
|
|
||||||
...(withAlways ? [new El('button')] : []), // 始终允许
|
|
||||||
]),
|
|
||||||
])
|
|
||||||
return card
|
|
||||||
}
|
|
||||||
const baseInput = {
|
|
||||||
key: 'Enter', ctrlKey: false, metaKey: false, altKey: false, shiftKey: false,
|
|
||||||
repeat: false, isComposing: false, keyCode: 13, defaultPrevented: false,
|
|
||||||
target: new El('div'), activeElement: new El('body'), card: approvalCard(),
|
|
||||||
}
|
|
||||||
|
|
||||||
test('回车 → allow,Esc → reject(焦点不在卡内、非输入状态)', () => {
|
|
||||||
assert.equal(decideKeyAction(baseInput), 'allow')
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, key: 'Escape', keyCode: 27 }), 'reject')
|
|
||||||
})
|
|
||||||
test('没有待审批卡 → 不管', () => {
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, card: null }), null)
|
|
||||||
})
|
|
||||||
test('焦点已在卡内 → 交给官方处理', () => {
|
|
||||||
const card = approvalCard()
|
|
||||||
const inside = card.querySelector('[data-approval-scroll]')
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, card, activeElement: inside }), null)
|
|
||||||
})
|
|
||||||
test('正在输入控件里打字 → 不管(textarea / input / contenteditable)', () => {
|
|
||||||
for (const target of [new El('textarea'), new El('input'), new El('div', { contenteditable: 'true' })]) {
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, target }), null)
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, target, key: 'Escape', keyCode: 27 }), null)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
test('修饰键、连发、输入法组词、已被处理 → 不管', () => {
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, ctrlKey: true }), null)
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, shiftKey: true }), null)
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, repeat: true }), null)
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, isComposing: true }), null)
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, keyCode: 229 }), null)
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, defaultPrevented: true }), null)
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, key: 'a', keyCode: 65 }), null)
|
|
||||||
})
|
|
||||||
test('回车落在别的按钮上 → 保留按钮原生行为;Esc 不受此限', () => {
|
|
||||||
const btn = new El('button')
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, target: btn }), null)
|
|
||||||
assert.equal(decideKeyAction({ ...baseInput, target: btn, key: 'Escape', keyCode: 27 }), 'reject')
|
|
||||||
})
|
|
||||||
test('actionButtons:跳过详情区内的按钮,顺序为 [拒绝, 允许, 始终允许?]', () => {
|
|
||||||
const card = approvalCard({ withAlways: true, detailButton: true })
|
|
||||||
const buttons = actionButtons(card)
|
|
||||||
assert.equal(buttons.length, 3)
|
|
||||||
assert.equal(buttons.includes(card.querySelector('[data-approval-scroll]').children[0]), false)
|
|
||||||
})
|
|
||||||
test('findPendingCard:跳过已作答与按钮被禁用的卡', () => {
|
|
||||||
const doc = new El('div', {}, [approvalCard({ busy: true }), approvalCard()])
|
|
||||||
const found = findPendingCard(doc)
|
|
||||||
assert.ok(found)
|
|
||||||
assert.equal(found.getAttribute('aria-busy'), null)
|
|
||||||
const disabledCard = approvalCard(); actionButtons(disabledCard)[1].disabled = true
|
|
||||||
const doc2 = new El('div', {}, [disabledCard])
|
|
||||||
assert.equal(findPendingCard(doc2), null)
|
|
||||||
})
|
|
||||||
test('shouldAutoFocus:主体焦点可送入,别处输入不抢,已在卡内不重复', () => {
|
|
||||||
const card = approvalCard()
|
|
||||||
const doc = { body: new El('body') }; card.ownerDocument = doc
|
|
||||||
assert.equal(shouldAutoFocus(null, card), true)
|
|
||||||
assert.equal(shouldAutoFocus(doc.body, card), true)
|
|
||||||
assert.equal(shouldAutoFocus(new El('textarea'), card), false)
|
|
||||||
assert.equal(shouldAutoFocus(card.querySelector('[data-approval-scroll]'), card), false)
|
|
||||||
assert.equal(shouldAutoFocus(new El('div'), card), true)
|
|
||||||
})
|
|
||||||
|
|
@ -0,0 +1,153 @@
|
||||||
|
// dsh-better-chat 审批快捷键:纯判定与按钮定位的单元测试(假 DOM,零依赖)。
|
||||||
|
import { test } from 'vitest'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import {
|
||||||
|
actionButtons,
|
||||||
|
findPendingCard,
|
||||||
|
decideKeyAction,
|
||||||
|
shouldAutoFocus,
|
||||||
|
} from '../../src/client/chat/approval-keys.ts'
|
||||||
|
|
||||||
|
// --- 极小假 DOM:只实现模块用到的表面 ---
|
||||||
|
function matches(el: any, selector: string): boolean {
|
||||||
|
return selector.split(',').some((part) => {
|
||||||
|
const s = part.trim()
|
||||||
|
if (s.startsWith('[')) {
|
||||||
|
const m = s.match(/^\[([a-zA-Z-]+)(?:="([^"]*)")?\]$/)
|
||||||
|
if (!m) return false
|
||||||
|
const v = el.attrs[m[1]]
|
||||||
|
return m[2] === undefined ? v !== undefined : v === m[2]
|
||||||
|
}
|
||||||
|
return el.tag === s
|
||||||
|
})
|
||||||
|
}
|
||||||
|
class El {
|
||||||
|
tag: string
|
||||||
|
attrs: Record<string, string>
|
||||||
|
children: El[] = []
|
||||||
|
parent: El | null = null
|
||||||
|
disabled = false
|
||||||
|
clicks = 0
|
||||||
|
focused = 0
|
||||||
|
ownerDocument: any = null
|
||||||
|
constructor(tag: string, attrs: Record<string, string> = {}, children: El[] = []) {
|
||||||
|
this.tag = tag
|
||||||
|
this.attrs = attrs
|
||||||
|
for (const c of children) this.append(c)
|
||||||
|
}
|
||||||
|
append(c: El) { c.parent = this; this.children.push(c); return c }
|
||||||
|
getAttribute(n: string) { return this.attrs[n] ?? null }
|
||||||
|
closest(sel: string) { let e: El | null = this; while (e) { if (matches(e, sel)) return e; e = e.parent } return null }
|
||||||
|
contains(other: any) { let e = other; while (e) { if (e === this) return true; e = e.parent } return false }
|
||||||
|
querySelectorAll(sel: string) { const out: El[] = []; const walk = (e: El) => { for (const c of e.children) { if (matches(c, sel)) out.push(c); walk(c) } }; walk(this); return out }
|
||||||
|
querySelector(sel: string) { return this.querySelectorAll(sel)[0] ?? null }
|
||||||
|
click() { this.clicks++ }
|
||||||
|
focus() { this.focused++ }
|
||||||
|
}
|
||||||
|
function approvalCard({ busy = false, withAlways = false, detailButton = false } = {}): El {
|
||||||
|
const scrollChildren = detailButton ? [new El('button')] : []
|
||||||
|
return new El('div', { 'data-approval-key': 'k1', ...(busy ? { 'aria-busy': 'true' } : {}) }, [
|
||||||
|
new El('div', { 'data-approval-scroll': '' }, scrollChildren),
|
||||||
|
new El('div', {}, [
|
||||||
|
new El('button'), // 拒绝
|
||||||
|
new El('button'), // 允许(单次)
|
||||||
|
...(withAlways ? [new El('button')] : []), // 始终允许
|
||||||
|
]),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
const baseInput = {
|
||||||
|
key: 'Enter', ctrlKey: false, metaKey: false, altKey: false, shiftKey: false,
|
||||||
|
repeat: false, isComposing: false, keyCode: 13, defaultPrevented: false,
|
||||||
|
target: new El('div'), activeElement: new El('body'), card: approvalCard(),
|
||||||
|
} as any
|
||||||
|
|
||||||
|
test('回车 → allow,Esc → reject(焦点不在卡内、非输入状态)', () => {
|
||||||
|
assert.equal(decideKeyAction(baseInput), 'allow')
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, key: 'Escape', keyCode: 27 }), 'reject')
|
||||||
|
})
|
||||||
|
test('没有待审批卡 → 不管', () => {
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, card: null }), null)
|
||||||
|
})
|
||||||
|
test('焦点已在卡内 → 交给官方处理(Ctrl/Cmd+Enter 例外)', () => {
|
||||||
|
const card = approvalCard()
|
||||||
|
const inside = card.querySelector('[data-approval-scroll]')
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, card, activeElement: inside }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, card, activeElement: inside, ctrlKey: true, hasAlways: true }), 'always')
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, card, activeElement: inside, metaKey: true, hasAlways: true }), 'always')
|
||||||
|
})
|
||||||
|
test('正在输入控件里打字 → 不管(textarea / input / contenteditable)', () => {
|
||||||
|
for (const target of [new El('textarea'), new El('input'), new El('div', { contenteditable: 'true' })]) {
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, target }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, target, key: 'Escape', keyCode: 27 }), null)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
test('修饰键、连发、输入法组词、已被处理 → 不管(Ctrl/Cmd+Enter 始终允许是唯一例外)', () => {
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, ctrlKey: true }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, metaKey: true }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, ctrlKey: true, hasAlways: true }), 'always')
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, metaKey: true, hasAlways: true }), 'always')
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, ctrlKey: true, shiftKey: true, hasAlways: true }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, ctrlKey: true, altKey: true, hasAlways: true }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, shiftKey: true }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, repeat: true }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, repeat: true, hasAlways: true }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, isComposing: true }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, keyCode: 229 }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, defaultPrevented: true }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, key: 'a', keyCode: 65 }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, key: 'Escape', ctrlKey: true, hasAlways: true }), null)
|
||||||
|
})
|
||||||
|
test('Ctrl/Cmd+Enter 只在卡片确实有可用的「始终允许」按钮时成立', () => {
|
||||||
|
const withAlways = approvalCard({ withAlways: true })
|
||||||
|
const withoutAlways = approvalCard()
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, card: withAlways, ctrlKey: true, hasAlways: true }), 'always')
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, card: withoutAlways, ctrlKey: true }), null)
|
||||||
|
// 正在输入控件里打字时,带修饰键的组合键也不拦截。
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, target: new El('textarea'), ctrlKey: true, hasAlways: true }), null)
|
||||||
|
})
|
||||||
|
test('自定义绑定生效:Shift+Enter 允许、Alt+Esc 拒绝、Ctrl+Enter 不再允许', () => {
|
||||||
|
const bindings = {
|
||||||
|
allow: { key: 'Enter', primary: false, shift: true, alt: false },
|
||||||
|
always: null,
|
||||||
|
reject: { key: 'Escape', primary: false, shift: false, alt: true },
|
||||||
|
} as const
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, key: 'Enter', shiftKey: true, bindings }), 'allow')
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, key: 'Enter', ctrlKey: true, bindings }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, key: 'Escape', altKey: true, bindings }), 'reject')
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, key: 'Escape', bindings }), null)
|
||||||
|
// 带 Shift 的 Enter 属于「带修饰键」的绑定,即使焦点在卡内也由插件处理。
|
||||||
|
const card = approvalCard()
|
||||||
|
const inside = card.querySelector('[data-approval-scroll]')
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, card, activeElement: inside, key: 'Enter', shiftKey: true, bindings }), 'allow')
|
||||||
|
})
|
||||||
|
test('回车落在别的按钮上 → 保留按钮原生行为;Esc 不受此限', () => {
|
||||||
|
const btn = new El('button')
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, target: btn }), null)
|
||||||
|
assert.equal(decideKeyAction({ ...baseInput, target: btn, key: 'Escape', keyCode: 27 }), 'reject')
|
||||||
|
})
|
||||||
|
test('actionButtons:跳过详情区内的按钮,顺序为 [拒绝, 允许, 始终允许?]', () => {
|
||||||
|
const card = approvalCard({ withAlways: true, detailButton: true })
|
||||||
|
const buttons = actionButtons(card as any)
|
||||||
|
assert.equal(buttons.length, 3)
|
||||||
|
assert.equal(buttons.includes(card.querySelector('[data-approval-scroll]')!.children[0] as any), false)
|
||||||
|
})
|
||||||
|
test('findPendingCard:跳过已作答与按钮被禁用的卡', () => {
|
||||||
|
const doc = new El('div', {}, [approvalCard({ busy: true }), approvalCard()])
|
||||||
|
const found = findPendingCard(doc as any)
|
||||||
|
assert.ok(found)
|
||||||
|
assert.equal(found!.getAttribute('aria-busy'), null)
|
||||||
|
const disabledCard = approvalCard()
|
||||||
|
actionButtons(disabledCard as any)[1].disabled = true
|
||||||
|
const doc2 = new El('div', {}, [disabledCard])
|
||||||
|
assert.equal(findPendingCard(doc2 as any), null)
|
||||||
|
})
|
||||||
|
test('shouldAutoFocus:主体焦点可送入,别处输入不抢,已在卡内不重复', () => {
|
||||||
|
const card = approvalCard()
|
||||||
|
const doc: any = { body: new El('body') }
|
||||||
|
card.ownerDocument = doc
|
||||||
|
assert.equal(shouldAutoFocus(null, card as any), true)
|
||||||
|
assert.equal(shouldAutoFocus(doc.body, card as any), true)
|
||||||
|
assert.equal(shouldAutoFocus(new El('textarea') as any, card as any), false)
|
||||||
|
assert.equal(shouldAutoFocus(card.querySelector('[data-approval-scroll]') as any, card as any), false)
|
||||||
|
assert.equal(shouldAutoFocus(new El('div') as any, card as any), true)
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,87 @@
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { test } from 'vitest'
|
||||||
|
import {
|
||||||
|
DEFAULT_BINDINGS,
|
||||||
|
bindingKeycap,
|
||||||
|
bindingMatches,
|
||||||
|
bindingsEqual,
|
||||||
|
isPlainBinding,
|
||||||
|
normalizeBindings,
|
||||||
|
validateBinding,
|
||||||
|
type ApprovalBindings,
|
||||||
|
} from '../../src/client/chat/bindings.ts'
|
||||||
|
|
||||||
|
test('defaults: Enter allow, Ctrl+Enter always, Esc reject', () => {
|
||||||
|
assert.deepEqual(DEFAULT_BINDINGS.allow, { key: 'Enter', primary: false, shift: false, alt: false })
|
||||||
|
assert.deepEqual(DEFAULT_BINDINGS.always, { key: 'Enter', primary: true, shift: false, alt: false })
|
||||||
|
assert.deepEqual(DEFAULT_BINDINGS.reject, { key: 'Escape', primary: false, shift: false, alt: false })
|
||||||
|
assert.equal(bindingKeycap(DEFAULT_BINDINGS.allow, false), 'Enter')
|
||||||
|
assert.equal(bindingKeycap(DEFAULT_BINDINGS.always, false), 'Ctrl+Enter')
|
||||||
|
assert.equal(bindingKeycap(DEFAULT_BINDINGS.always, true), 'Cmd+Enter')
|
||||||
|
assert.equal(bindingKeycap(DEFAULT_BINDINGS.reject, false), 'Esc')
|
||||||
|
assert.equal(bindingKeycap({ key: 'Enter', primary: true, shift: true, alt: true }, false), 'Ctrl+Shift+Alt+Enter')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('bindingMatches requires an exact modifier set and treats Ctrl/Meta as primary', () => {
|
||||||
|
const always = DEFAULT_BINDINGS.always!
|
||||||
|
assert.equal(bindingMatches(always, { key: 'Enter', ctrlKey: true }), true)
|
||||||
|
assert.equal(bindingMatches(always, { key: 'Enter', metaKey: true }), true)
|
||||||
|
assert.equal(bindingMatches(always, { key: 'Enter' }), false)
|
||||||
|
assert.equal(bindingMatches(always, { key: 'Enter', ctrlKey: true, shiftKey: true }), false)
|
||||||
|
assert.equal(bindingMatches(DEFAULT_BINDINGS.allow, { key: 'Enter' }), true)
|
||||||
|
assert.equal(bindingMatches(DEFAULT_BINDINGS.allow, { key: 'Enter', altKey: true }), false)
|
||||||
|
assert.equal(isPlainBinding(DEFAULT_BINDINGS.allow), true)
|
||||||
|
assert.equal(isPlainBinding(DEFAULT_BINDINGS.always), false)
|
||||||
|
assert.equal(isPlainBinding(null), false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('normalizeBindings falls back for missing, invalid, conflicting or modifier-less values', () => {
|
||||||
|
assert.deepEqual(normalizeBindings(undefined), DEFAULT_BINDINGS)
|
||||||
|
const custom = normalizeBindings({
|
||||||
|
allow: { key: 'Escape', primary: false, shift: false, alt: false }, // 允许不能用 Esc
|
||||||
|
always: { key: 'Enter', primary: false, shift: false, alt: false }, // 没有修饰键
|
||||||
|
reject: { key: 'Escape', primary: true, shift: false, alt: false },
|
||||||
|
})
|
||||||
|
assert.equal(custom.allow.key, 'Enter')
|
||||||
|
assert.equal(custom.always?.primary, true)
|
||||||
|
assert.equal(custom.reject.primary, true)
|
||||||
|
|
||||||
|
const disabled = normalizeBindings({ ...DEFAULT_BINDINGS, always: null })
|
||||||
|
assert.equal(disabled.always, null)
|
||||||
|
|
||||||
|
const conflict = normalizeBindings({
|
||||||
|
allow: { key: 'Enter', primary: true, shift: false, alt: false },
|
||||||
|
always: { key: 'Enter', primary: true, shift: false, alt: false },
|
||||||
|
reject: { key: 'Escape', primary: false, shift: false, alt: false },
|
||||||
|
})
|
||||||
|
assert.equal(bindingsEqual(conflict.allow, conflict.always), false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('validateBinding: base key, modifier requirement, and conflicts', () => {
|
||||||
|
const current: ApprovalBindings = normalizeBindings(undefined)
|
||||||
|
assert.equal(validateBinding('allow', { key: 'Enter', primary: false, shift: true, alt: false }, current), 'ok')
|
||||||
|
assert.equal(validateBinding('reject', { key: 'Escape', primary: false, shift: false, alt: true }, current), 'ok')
|
||||||
|
assert.equal(validateBinding('allow', { key: 'Escape', primary: false, shift: false, alt: false }, current), 'key')
|
||||||
|
assert.equal(validateBinding('always', { key: 'Enter', primary: false, shift: false, alt: false }, current), 'modifier')
|
||||||
|
assert.equal(validateBinding('allow', current.allow, current), 'ok')
|
||||||
|
assert.equal(validateBinding('reject', current.reject, current), 'ok')
|
||||||
|
assert.equal(validateBinding('always', current.always!, current), 'ok')
|
||||||
|
|
||||||
|
const custom = normalizeBindings({
|
||||||
|
allow: { key: 'Enter', primary: false, shift: true, alt: false },
|
||||||
|
always: { key: 'Enter', primary: true, shift: false, alt: false },
|
||||||
|
reject: { key: 'Escape', primary: false, shift: false, alt: false },
|
||||||
|
})
|
||||||
|
assert.equal(validateBinding('always', custom.allow, custom), 'conflict')
|
||||||
|
assert.equal(validateBinding('allow', custom.always, custom), 'conflict')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('validateBinding accepts a shifted Enter as a custom allow binding without colliding', () => {
|
||||||
|
const current = normalizeBindings({
|
||||||
|
allow: { key: 'Enter', primary: false, shift: true, alt: false },
|
||||||
|
always: null,
|
||||||
|
reject: { key: 'Escape', primary: false, shift: false, alt: false },
|
||||||
|
})
|
||||||
|
assert.equal(validateBinding('reject', { key: 'Escape', primary: false, shift: true, alt: false }, current), 'ok')
|
||||||
|
assert.equal(validateBinding('allow', { key: 'Enter', primary: false, shift: true, alt: false }, current), 'ok')
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,173 @@
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { test } from 'vitest'
|
||||||
|
import {
|
||||||
|
HINT_ATTR,
|
||||||
|
hintParts,
|
||||||
|
hintSignature,
|
||||||
|
installKeyHints,
|
||||||
|
isMacPlatform,
|
||||||
|
} from '../../src/client/chat/key-hint.ts'
|
||||||
|
|
||||||
|
test('hintParts: Ctrl+Enter only appears when the always button exists', () => {
|
||||||
|
const withAlways = hintParts({ allow: '允许(单次)', always: '始终允许', reject: '拒绝' }, false)
|
||||||
|
assert.deepEqual(withAlways.map((part) => part.key), ['Enter', 'Ctrl+Enter', 'Esc'])
|
||||||
|
const mac = hintParts({ allow: '允许(单次)', always: '始终允许', reject: '拒绝' }, true)
|
||||||
|
assert.equal(mac[1]?.key, 'Cmd+Enter')
|
||||||
|
const withoutAlways = hintParts({ allow: '允许(单次)', reject: '拒绝' }, false)
|
||||||
|
assert.deepEqual(withoutAlways.map((part) => part.key), ['Enter', 'Esc'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('hintSignature changes with labels and platform keys', () => {
|
||||||
|
const a = hintParts({ allow: '允许', reject: '拒绝' }, false)
|
||||||
|
const b = hintParts({ allow: '允许', reject: '拒绝' }, false)
|
||||||
|
const c = hintParts({ allow: 'Allow', reject: 'Reject' }, false)
|
||||||
|
assert.equal(hintSignature(a), hintSignature(b))
|
||||||
|
assert.notEqual(hintSignature(a), hintSignature(c))
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isMacPlatform detects Apple platforms only', () => {
|
||||||
|
assert.equal(isMacPlatform('MacIntel'), true)
|
||||||
|
assert.equal(isMacPlatform('iPhone'), true)
|
||||||
|
assert.equal(isMacPlatform('Win32'), false)
|
||||||
|
assert.equal(isMacPlatform('Linux x86_64'), false)
|
||||||
|
assert.equal(isMacPlatform(undefined), false)
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- 极小假 DOM:只实现提示模块用到的表面 ---
|
||||||
|
function matches(el: any, selector: string): boolean {
|
||||||
|
return selector.split(',').some((part) => {
|
||||||
|
const s = part.trim()
|
||||||
|
if (s.startsWith('[')) {
|
||||||
|
const m = s.match(/^\[([a-zA-Z-]+)(?:="([^"]*)")?\]$/)
|
||||||
|
if (!m) return false
|
||||||
|
const value = el.attrs[m[1]]
|
||||||
|
return m[2] === undefined ? value !== undefined : value === m[2]
|
||||||
|
}
|
||||||
|
return el.tag === s
|
||||||
|
})
|
||||||
|
}
|
||||||
|
class FakeEl {
|
||||||
|
tag: string
|
||||||
|
attrs: Record<string, string> = {}
|
||||||
|
children: FakeEl[] = []
|
||||||
|
parent: FakeEl | null = null
|
||||||
|
style = { cssText: '' }
|
||||||
|
disabled = false
|
||||||
|
textContent = ''
|
||||||
|
get parentElement(): FakeEl | null { return this.parent }
|
||||||
|
constructor(tag: string) { this.tag = tag }
|
||||||
|
setAttribute(name: string, value: string) { this.attrs[name] = value }
|
||||||
|
getAttribute(name: string) { return this.attrs[name] ?? null }
|
||||||
|
append(...nodes: FakeEl[]) { for (const node of nodes) { node.parent = this; this.children.push(node) } return this }
|
||||||
|
insertBefore(node: FakeEl, ref: FakeEl | null) {
|
||||||
|
node.parent = this
|
||||||
|
const index = ref ? this.children.indexOf(ref) : -1
|
||||||
|
if (index < 0) this.children.unshift(node)
|
||||||
|
else this.children.splice(index, 0, node)
|
||||||
|
return node
|
||||||
|
}
|
||||||
|
remove() {
|
||||||
|
if (!this.parent) return
|
||||||
|
const index = this.parent.children.indexOf(this)
|
||||||
|
if (index >= 0) this.parent.children.splice(index, 1)
|
||||||
|
this.parent = null
|
||||||
|
}
|
||||||
|
closest(selector: string): FakeEl | null {
|
||||||
|
let current: FakeEl | null = this
|
||||||
|
while (current) {
|
||||||
|
if (matches(current, selector)) return current
|
||||||
|
current = current.parent
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
querySelectorAll(selector: string): FakeEl[] {
|
||||||
|
const out: FakeEl[] = []
|
||||||
|
const walk = (node: FakeEl) => {
|
||||||
|
for (const child of node.children) {
|
||||||
|
if (matches(child, selector)) out.push(child)
|
||||||
|
walk(child)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(this)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
querySelector(selector: string): FakeEl | null {
|
||||||
|
return this.querySelectorAll(selector)[0] ?? null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
class FakeDoc {
|
||||||
|
root = new FakeEl('div')
|
||||||
|
documentElement = this.root
|
||||||
|
defaultView = { navigator: { platform: 'Win32' } }
|
||||||
|
createElement(tag: string) { return new FakeEl(tag) }
|
||||||
|
querySelectorAll(selector: string) { return this.root.querySelectorAll(selector) }
|
||||||
|
}
|
||||||
|
|
||||||
|
let observerFire: (() => void) | null = null
|
||||||
|
;(globalThis as any).MutationObserver = class {
|
||||||
|
constructor(callback: () => void) { observerFire = callback }
|
||||||
|
observe() {}
|
||||||
|
disconnect() { observerFire = null }
|
||||||
|
}
|
||||||
|
|
||||||
|
function button(text: string): FakeEl {
|
||||||
|
const el = new FakeEl('button')
|
||||||
|
el.textContent = text
|
||||||
|
return el
|
||||||
|
}
|
||||||
|
|
||||||
|
function cardWithButtons(labels: string[]): { doc: FakeDoc; card: FakeEl; row: FakeEl } {
|
||||||
|
const doc = new FakeDoc()
|
||||||
|
const card = new FakeEl('div')
|
||||||
|
card.setAttribute('data-approval-key', 'k1')
|
||||||
|
const row = new FakeEl('div')
|
||||||
|
for (const label of labels) row.append(button(label))
|
||||||
|
card.append(row)
|
||||||
|
doc.root.append(card)
|
||||||
|
return { doc, card, row }
|
||||||
|
}
|
||||||
|
|
||||||
|
function textOf(node: FakeEl): string {
|
||||||
|
const own = node.textContent
|
||||||
|
return own + node.children.map(textOf).join('')
|
||||||
|
}
|
||||||
|
|
||||||
|
test('installKeyHints inserts the hint as the first child of the action row', () => {
|
||||||
|
const { doc, card, row } = cardWithButtons(['拒绝', '允许(单次)', '始终允许'])
|
||||||
|
const dispose = installKeyHints(doc as unknown as Document, { platform: 'Win32' })
|
||||||
|
const hint = card.querySelector(`[${HINT_ATTR}]`) as FakeEl | null
|
||||||
|
assert.ok(hint, 'hint must be inserted')
|
||||||
|
assert.equal(row.children[0], hint, 'hint sits before the buttons')
|
||||||
|
const text = textOf(hint)
|
||||||
|
for (const expected of ['Enter', '允许(单次)', 'Ctrl+Enter', '始终允许', 'Esc', '拒绝']) {
|
||||||
|
assert.ok(text.includes(expected), `hint should contain ${expected}; got ${text}`)
|
||||||
|
}
|
||||||
|
dispose()
|
||||||
|
assert.equal(card.querySelector(`[${HINT_ATTR}]`), null, 'dispose removes the hint')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('installKeyHints omits Ctrl+Enter when there is no always button', () => {
|
||||||
|
const { doc, card } = cardWithButtons(['拒绝', '允许'])
|
||||||
|
const dispose = installKeyHints(doc as unknown as Document, { platform: 'Win32' })
|
||||||
|
const hint = card.querySelector(`[${HINT_ATTR}]`) as FakeEl
|
||||||
|
assert.equal(textOf(hint).includes('Ctrl+Enter'), false)
|
||||||
|
dispose()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('installKeyHints uses Cmd on Apple platforms', () => {
|
||||||
|
const { doc, card } = cardWithButtons(['拒绝', '允许', '始终允许'])
|
||||||
|
const dispose = installKeyHints(doc as unknown as Document, { platform: 'MacIntel' })
|
||||||
|
const hint = card.querySelector(`[${HINT_ATTR}]`) as FakeEl
|
||||||
|
assert.ok(textOf(hint).includes('Cmd+Enter'))
|
||||||
|
dispose()
|
||||||
|
})
|
||||||
|
|
||||||
|
test('installKeyHints removes the hint once the card is answered', () => {
|
||||||
|
const { doc, card } = cardWithButtons(['拒绝', '允许', '始终允许'])
|
||||||
|
const dispose = installKeyHints(doc as unknown as Document, { platform: 'Win32' })
|
||||||
|
assert.ok(card.querySelector(`[${HINT_ATTR}]`))
|
||||||
|
card.setAttribute('aria-busy', 'true')
|
||||||
|
observerFire?.()
|
||||||
|
assert.equal(card.querySelector(`[${HINT_ATTR}]`), null)
|
||||||
|
dispose()
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,281 @@
|
||||||
|
// Feature 2 (permission policy) unit tests with a fake DOM + fake sessions.
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
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() {} }
|
||||||
|
|
||||||
|
test('preset machine values match the host catalog', () => {
|
||||||
|
assert.equal(FULL_ACCESS_PRESET, 'danger-full-access')
|
||||||
|
assert.equal(AUTO_REVIEW_PRESET, 'auto')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('isFullAccessLabel matches zh/en labels at the start only', () => {
|
||||||
|
assert.equal(isFullAccessLabel('完全权限'), true)
|
||||||
|
assert.equal(isFullAccessLabel('完全权限 让代理不受限制地执行'), true)
|
||||||
|
assert.equal(isFullAccessLabel('Full access'), true)
|
||||||
|
assert.equal(isFullAccessLabel('自动审查'), false)
|
||||||
|
assert.equal(isFullAccessLabel('仅可查看'), false)
|
||||||
|
assert.equal(isFullAccessLabel('工作区内修改'), false)
|
||||||
|
assert.equal(isFullAccessLabel(''), false)
|
||||||
|
assert.equal(isFullAccessLabel(null), false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('shouldAutoSwitch: only known non-auto presets, once', () => {
|
||||||
|
assert.equal(shouldAutoSwitch('workspace-write', false), true)
|
||||||
|
assert.equal(shouldAutoSwitch('danger-full-access', false), true)
|
||||||
|
assert.equal(shouldAutoSwitch('auto', false), false)
|
||||||
|
assert.equal(shouldAutoSwitch(undefined, false), false)
|
||||||
|
assert.equal(shouldAutoSwitch('workspace-write', true), false)
|
||||||
|
})
|
||||||
|
|
||||||
|
function fakeEl(text: string) {
|
||||||
|
return { textContent: text, removed: false, remove(this: any) { this.removed = true } }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('pruneFullAccess removes full-access from selects, listboxes and menus', () => {
|
||||||
|
const opts = [fakeEl('仅可查看'), fakeEl('完全权限'), fakeEl('工作区内修改')]
|
||||||
|
const items = [fakeEl('自动审查EXP'), fakeEl('完全权限'), fakeEl('Full access'), fakeEl('仅可查看')]
|
||||||
|
const doc = {
|
||||||
|
querySelectorAll(sel: string) {
|
||||||
|
if (sel === 'option') return opts
|
||||||
|
if (sel.includes('listbox')) return items
|
||||||
|
return []
|
||||||
|
},
|
||||||
|
}
|
||||||
|
assert.equal(pruneFullAccess(doc as any), 3)
|
||||||
|
assert.deepEqual(opts.map((o) => o.removed), [false, true, false])
|
||||||
|
assert.deepEqual(items.map((o) => o.removed), [false, true, true, false])
|
||||||
|
})
|
||||||
|
|
||||||
|
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') } }), [])
|
||||||
|
assert.deepEqual(liveSessions(undefined), [])
|
||||||
|
assert.deepEqual(liveSessions(42), [])
|
||||||
|
})
|
||||||
|
|
||||||
|
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)
|
||||||
|
})
|
||||||
|
|
||||||
|
function fakeTimers() {
|
||||||
|
const intervals = new Map<number, () => void>()
|
||||||
|
let next = 1
|
||||||
|
return {
|
||||||
|
setInterval(fn: () => void) { const id = next++; intervals.set(id, fn); return id },
|
||||||
|
clearInterval(id: number) { intervals.delete(id) },
|
||||||
|
setTimeout(fn: () => void) { fn(); return 0 },
|
||||||
|
clearTimeout() {},
|
||||||
|
async runIntervals() { for (const fn of [...intervals.values()]) await fn() },
|
||||||
|
get size() { return intervals.size },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fakeLive(preset: string | { currentValue: string }, fail = false, blank?: boolean) {
|
||||||
|
const calls: string[] = []
|
||||||
|
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(live.calls, ['/permission auto'])
|
||||||
|
dispose()
|
||||||
|
assert.equal(timers.size, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
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(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,8 +1,14 @@
|
||||||
import { test } from 'node:test'
|
import { test } from 'vitest'
|
||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import { localizedTitle, pickUpdates, runUpdate, findUpdateRow, makeUpdateClickHandler } from '../client.js'
|
import {
|
||||||
|
localizedTitle,
|
||||||
|
pickUpdates,
|
||||||
|
runUpdate,
|
||||||
|
findUpdateRow,
|
||||||
|
makeUpdateClickHandler,
|
||||||
|
} from '../../src/client/chat/store-update.ts'
|
||||||
|
|
||||||
const entry = (overrides = {}) => ({
|
const entry = (overrides: Record<string, unknown> = {}) => ({
|
||||||
name: 'dsh-better-chat',
|
name: 'dsh-better-chat',
|
||||||
title: { 'zh-CN': '聊天增强', en: 'Better Chat' },
|
title: { 'zh-CN': '聊天增强', en: 'Better Chat' },
|
||||||
defaultVersion: '0.3.0',
|
defaultVersion: '0.3.0',
|
||||||
|
|
@ -38,9 +44,9 @@ test('pickUpdates keeps only update-available entries with a spec', () => {
|
||||||
})
|
})
|
||||||
|
|
||||||
test('runUpdate calls installBundle with the spec and enabled flag', async () => {
|
test('runUpdate calls installBundle with the spec and enabled flag', async () => {
|
||||||
const calls = []
|
const calls: any[] = []
|
||||||
const remote = { pluginManager: { installBundle: async (spec, options) => { calls.push([spec, options]); return { ok: true, value: { application: 'applied' } } } } }
|
const remote = { pluginManager: { installBundle: async (spec: string, options: any) => { calls.push([spec, options]); return { ok: true, value: { application: 'applied' } } } } }
|
||||||
const update = { name: 'x', spec: 'git+https://example.test/x.git#abc', registry: 'https://registry.example' }
|
const update = { name: 'x', title: 'x', installedVersion: '', version: '1.0.0', spec: 'git+https://example.test/x.git#abc', registry: 'https://registry.example' }
|
||||||
const result = await runUpdate(remote, update, () => 'req-1')
|
const result = await runUpdate(remote, update, () => 'req-1')
|
||||||
assert.equal(result.value.application, 'applied')
|
assert.equal(result.value.application, 'applied')
|
||||||
assert.equal(calls[0][0], update.spec)
|
assert.equal(calls[0][0], update.spec)
|
||||||
|
|
@ -48,12 +54,12 @@ test('runUpdate calls installBundle with the spec and enabled flag', async () =>
|
||||||
})
|
})
|
||||||
|
|
||||||
function fakeRow() {
|
function fakeRow() {
|
||||||
const label = { textContent: ' 有新版本 ', parentElement: null }
|
const label: any = { textContent: ' 有新版本 ', parentElement: null }
|
||||||
const row = {
|
const row: any = {
|
||||||
textContent: '聊天增强 审批卡回车确认 0.3.0 · newbie',
|
textContent: '聊天增强 审批卡回车确认 0.3.0 · newbie',
|
||||||
children: [],
|
children: [],
|
||||||
querySelector: () => null,
|
querySelector: () => null,
|
||||||
appendChild(child) { this.children.push(child) },
|
appendChild(child: any) { this.children.push(child) },
|
||||||
}
|
}
|
||||||
label.parentElement = row
|
label.parentElement = row
|
||||||
return { label, row }
|
return { label, row }
|
||||||
|
|
@ -61,22 +67,22 @@ function fakeRow() {
|
||||||
|
|
||||||
test('findUpdateRow locates the row for a title from its status label', () => {
|
test('findUpdateRow locates the row for a title from its status label', () => {
|
||||||
const { label, row } = fakeRow()
|
const { label, row } = fakeRow()
|
||||||
const doc = { querySelectorAll: (selector) => (selector === 'button' ? [label] : []) }
|
const doc = { querySelectorAll: (selector: string) => (selector === 'button' ? [label] : []) }
|
||||||
assert.equal(findUpdateRow(doc, '聊天增强'), row)
|
assert.equal(findUpdateRow(doc as any, '聊天增强'), row)
|
||||||
assert.equal(findUpdateRow(doc, '不存在的插件'), null)
|
assert.equal(findUpdateRow(doc as any, '不存在的插件'), null)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('update click handler reports applied and failure states', async () => {
|
test('update click handler reports applied and failure states', async () => {
|
||||||
const button = { disabled: false, textContent: '更新到 0.3.0' }
|
const button: any = { disabled: false, textContent: '更新到 0.3.0' }
|
||||||
const doc = { defaultView: { confirm: () => true } }
|
const doc = { defaultView: { confirm: () => true } }
|
||||||
const update = { name: 'x', title: '聊天增强', installedVersion: '0.2.1', version: '0.3.0', spec: 'spec' }
|
const update = { name: 'x', title: '聊天增强', installedVersion: '0.2.1', version: '0.3.0', spec: 'spec' }
|
||||||
const okRemote = () => ({ pluginManager: { installBundle: async () => ({ ok: true, value: { application: 'applied' } }) } })
|
const okRemote = () => ({ pluginManager: { installBundle: async () => ({ ok: true, value: { application: 'applied' } }) } })
|
||||||
await makeUpdateClickHandler(doc, okRemote, update, button)({})
|
await makeUpdateClickHandler(doc as any, okRemote, update, button)({})
|
||||||
assert.equal(button.textContent, '已更新,重启 DSH 后生效')
|
assert.equal(button.textContent, '已更新,重启 DSH 后生效')
|
||||||
|
|
||||||
const button2 = { disabled: false, textContent: '更新到 0.3.0' }
|
const button2: any = { disabled: false, textContent: '更新到 0.3.0' }
|
||||||
const failRemote = () => ({ pluginManager: { installBundle: async () => ({ ok: true, value: { application: 'failed' } }) } })
|
const failRemote = () => ({ pluginManager: { installBundle: async () => ({ ok: true, value: { application: 'failed' } }) } })
|
||||||
await makeUpdateClickHandler(doc, failRemote, update, button2)({})
|
await makeUpdateClickHandler(doc as any, failRemote, update, button2)({})
|
||||||
assert.equal(button2.disabled, false)
|
assert.equal(button2.disabled, false)
|
||||||
assert.equal(button2.textContent, '更新失败,点此重试')
|
assert.equal(button2.textContent, '更新失败,点此重试')
|
||||||
})
|
})
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
import { test } from 'node:test'
|
|
||||||
import assert from 'node:assert/strict'
|
|
||||||
import { readFileSync } from 'node:fs'
|
|
||||||
import vm from 'node:vm'
|
|
||||||
|
|
||||||
test('lib/client.js registers the 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
|
|
||||||
const window = {
|
|
||||||
__ModuleLoader__: {
|
|
||||||
load: (entry) => { 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')
|
|
||||||
const plugin = registered.factory()
|
|
||||||
assert.equal(typeof plugin.apply, 'function')
|
|
||||||
assert.ok(Array.isArray(plugin.inject) && plugin.inject.length === 0, 'inject must be an empty array')
|
|
||||||
})
|
|
||||||
|
|
@ -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')
|
||||||
|
})
|
||||||
|
|
@ -1,122 +0,0 @@
|
||||||
// Feature 2 (permission policy) unit tests with a fake DOM + fake sessions.
|
|
||||||
import assert from 'node:assert/strict'
|
|
||||||
import { test } from 'node:test'
|
|
||||||
import {
|
|
||||||
AUTO_REVIEW_PRESET,
|
|
||||||
FULL_ACCESS_PRESET,
|
|
||||||
currentPreset,
|
|
||||||
installPermissionPolicy,
|
|
||||||
isFullAccessLabel,
|
|
||||||
liveSessions,
|
|
||||||
pruneFullAccess,
|
|
||||||
shouldAutoSwitch,
|
|
||||||
} from '../client.js'
|
|
||||||
|
|
||||||
globalThis.MutationObserver = class { observe() {} disconnect() {} }
|
|
||||||
|
|
||||||
test('preset machine values match the host catalog', () => {
|
|
||||||
assert.equal(FULL_ACCESS_PRESET, 'danger-full-access')
|
|
||||||
assert.equal(AUTO_REVIEW_PRESET, 'auto')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('isFullAccessLabel matches zh/en labels at the start only', () => {
|
|
||||||
assert.equal(isFullAccessLabel('完全权限'), true)
|
|
||||||
assert.equal(isFullAccessLabel('完全权限 让代理不受限制地执行'), true)
|
|
||||||
assert.equal(isFullAccessLabel('Full access'), true)
|
|
||||||
assert.equal(isFullAccessLabel('自动审查'), false)
|
|
||||||
assert.equal(isFullAccessLabel('仅可查看'), false)
|
|
||||||
assert.equal(isFullAccessLabel('工作区内修改'), false)
|
|
||||||
assert.equal(isFullAccessLabel(''), false)
|
|
||||||
assert.equal(isFullAccessLabel(null), false)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('shouldAutoSwitch: only known non-auto presets, once', () => {
|
|
||||||
assert.equal(shouldAutoSwitch('workspace-write', false), true)
|
|
||||||
assert.equal(shouldAutoSwitch('danger-full-access', false), true)
|
|
||||||
assert.equal(shouldAutoSwitch('auto', false), false)
|
|
||||||
assert.equal(shouldAutoSwitch(undefined, false), false)
|
|
||||||
assert.equal(shouldAutoSwitch('workspace-write', true), false)
|
|
||||||
})
|
|
||||||
|
|
||||||
function fakeEl(text) {
|
|
||||||
return { textContent: text, removed: false, remove() { this.removed = true } }
|
|
||||||
}
|
|
||||||
|
|
||||||
test('pruneFullAccess removes full-access from selects, listboxes and menus', () => {
|
|
||||||
const opts = [fakeEl('仅可查看'), fakeEl('完全权限'), fakeEl('工作区内修改')]
|
|
||||||
const items = [fakeEl('自动审查EXP'), fakeEl('完全权限'), fakeEl('Full access'), fakeEl('仅可查看')]
|
|
||||||
const doc = {
|
|
||||||
querySelectorAll(sel) {
|
|
||||||
if (sel === 'option') return opts
|
|
||||||
if (sel.includes('listbox')) return items
|
|
||||||
return []
|
|
||||||
},
|
|
||||||
}
|
|
||||||
assert.equal(pruneFullAccess(doc), 3)
|
|
||||||
assert.deepEqual(opts.map((o) => o.removed), [false, true, false])
|
|
||||||
assert.deepEqual(items.map((o) => o.removed), [false, true, true, false])
|
|
||||||
})
|
|
||||||
|
|
||||||
test('liveSessions: keys+binding, list fallback, hostile shapes', () => {
|
|
||||||
const live = { sessionId: 's1' }
|
|
||||||
const viaKeys = liveSessions({ keys: () => ['s1', 's2'], binding: (id) => (id === 's1' ? { session: live } : undefined) })
|
|
||||||
assert.deepEqual(viaKeys.map((x) => x.id), ['s1'])
|
|
||||||
const viaList = liveSessions({ list: () => [{ sessionId: 'a' }, { nope: 1 }] })
|
|
||||||
assert.deepEqual(viaList.map((x) => x.id), ['a'])
|
|
||||||
assert.deepEqual(liveSessions({ keys: () => { throw new Error('x') } }), [])
|
|
||||||
assert.deepEqual(liveSessions(undefined), [])
|
|
||||||
assert.deepEqual(liveSessions(42), [])
|
|
||||||
})
|
|
||||||
|
|
||||||
test('currentPreset reads the permissions projection defensively', () => {
|
|
||||||
const live = { projections: { faceOf: (n) => (n === 'permissions' ? { getSnapshot: () => 'workspace-write' } : undefined) } }
|
|
||||||
assert.equal(currentPreset(live), 'workspace-write')
|
|
||||||
assert.equal(currentPreset({}), undefined)
|
|
||||||
assert.equal(currentPreset({ projections: { faceOf: () => { throw new Error('x') } } }), undefined)
|
|
||||||
})
|
|
||||||
|
|
||||||
function fakeTimers() {
|
|
||||||
const intervals = new Map()
|
|
||||||
let next = 1
|
|
||||||
return {
|
|
||||||
setInterval(fn) { const id = next++; intervals.set(id, fn); return id },
|
|
||||||
clearInterval(id) { intervals.delete(id) },
|
|
||||||
setTimeout(fn) { fn(); return 0 },
|
|
||||||
clearTimeout() {},
|
|
||||||
async runIntervals() { for (const fn of [...intervals.values()]) await fn() },
|
|
||||||
get size() { return intervals.size },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function fakeLive(preset, fail = false) {
|
|
||||||
const calls = []
|
|
||||||
return {
|
|
||||||
calls,
|
|
||||||
projections: { faceOf: () => ({ getSnapshot: () => preset }) },
|
|
||||||
async command(text) {
|
|
||||||
calls.push(text)
|
|
||||||
if (fail) return { ok: false, error: { code: 'unavailable' } }
|
|
||||||
return { ok: true, value: { matched: true } }
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
test('policy: page load and refresh never change existing session permissions', async () => {
|
|
||||||
const timers = fakeTimers()
|
|
||||||
const live = fakeLive('read-only')
|
|
||||||
const sessions = { keys: () => ['s1'], binding: () => ({ session: live }) }
|
|
||||||
const doc = { body: {}, querySelectorAll: () => [] }
|
|
||||||
const dispose = installPermissionPolicy(doc, () => sessions, timers)
|
|
||||||
await timers.runIntervals()
|
|
||||||
await timers.runIntervals()
|
|
||||||
assert.deepEqual(live.calls, [], '已有只读会话不能被自动切到 auto')
|
|
||||||
dispose()
|
|
||||||
assert.equal(timers.size, 0)
|
|
||||||
|
|
||||||
// A second mount (the page reload path) must not touch it either.
|
|
||||||
const timers2 = fakeTimers()
|
|
||||||
const dispose2 = installPermissionPolicy(doc, () => sessions, timers2)
|
|
||||||
await timers2.runIntervals()
|
|
||||||
assert.deepEqual(live.calls, [], '刷新后再次挂载也不能改权限')
|
|
||||||
dispose2()
|
|
||||||
})
|
|
||||||
|
|
@ -0,0 +1,305 @@
|
||||||
|
import { assertPluginSource } from './core-boundary.js'
|
||||||
|
/**
|
||||||
|
* Target-aware browser bundle preset for out-of-tree dshx plugins.
|
||||||
|
*
|
||||||
|
* Pre-0.2.1 DeepSeek Harness `clientBundle(id)` resolved manifests only from
|
||||||
|
* two-level directories under `packages/`, while 0.2.1-rc.5
|
||||||
|
* `clientBundle(packageDir)` still depends on monorepo-internal `scripts/`
|
||||||
|
* helpers. This standalone adapter reads the package being built from its own
|
||||||
|
* directory and the shared module table from the target Harness checkout, while
|
||||||
|
* preserving lazy-CJS registration, shared module identities, CSS ownership,
|
||||||
|
* inlined image data URLs, and `DSH_CLIENT_*` build-value parity across Host
|
||||||
|
* and browser halves.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { existsSync, readFileSync } from 'node:fs'
|
||||||
|
import { readFile } from 'node:fs/promises'
|
||||||
|
import { createRequire, isBuiltin } from 'node:module'
|
||||||
|
import { basename, dirname, extname, isAbsolute, resolve, sep } from 'node:path'
|
||||||
|
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||||
|
import { transform } from 'lightningcss'
|
||||||
|
import { assertClientCordisInject } from './internal/client-cordis-inject.js'
|
||||||
|
|
||||||
|
function clientPlatformPath() {
|
||||||
|
const requested = process.env.DSHX_HARNESS?.trim()
|
||||||
|
// Vendored table: dsh-v0.2.2-rc.2 packages/client/web/src/platform.ts.
|
||||||
|
const fallback = resolve(dirname(fileURLToPath(import.meta.url)), 'harness/packages/client/web/src/platform.ts')
|
||||||
|
const path = requested ? resolve(requested, 'packages/client/web/src/platform.ts') : fallback
|
||||||
|
if (!existsSync(path)) {
|
||||||
|
throw new Error(`dshx client build: target Harness client platform table not found at ${path}`)
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
const {
|
||||||
|
PLATFORM_MODULES,
|
||||||
|
PRELOADED_CLIENT_EXTERNALS,
|
||||||
|
} = await import(pathToFileURL(clientPlatformPath()).href)
|
||||||
|
|
||||||
|
const CSS_MODULE_PREFIX = '\0dshx-css-module:'
|
||||||
|
const CSS_GLOBAL_PREFIX = '\0dshx-css-global:'
|
||||||
|
const CSS_INLINE_PREFIX = '\0dshx-css-inline:'
|
||||||
|
// Keep Safari 15.4-era -webkit- prefixes: the reader's glass surfaces rely on
|
||||||
|
// -webkit-backdrop-filter as the fallback for older WebKit.
|
||||||
|
const CSS_TARGETS = { safari: (15 << 16) | (4 << 8) }
|
||||||
|
const VIRTUAL_SUFFIX = '.mjs'
|
||||||
|
const INLINE_QUERY = '?inline'
|
||||||
|
const TYPES_MARKER = `${sep}lib${sep}types${sep}`
|
||||||
|
const IMAGE_MEDIA_TYPES = new Map([
|
||||||
|
['.svg', 'image/svg+xml'],
|
||||||
|
['.png', 'image/png'],
|
||||||
|
['.webp', 'image/webp'],
|
||||||
|
])
|
||||||
|
|
||||||
|
// Official packages/client/tsdown.client.ts INLINE_SAFE at dsh-v0.2.1-rc.5.
|
||||||
|
// Unchanged from dsh-v0.1.7-rc.2, including dsh-api-workspace-controller/default-workspace.
|
||||||
|
const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|session|llm|tools|brand|deque|output-retention|typert-protocol|util-crypto|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-spill-policy\/notice$)/
|
||||||
|
const VENDORED_LIBRARY = /^@deepseek-ai\/(cosmokit|schemastery)(\/|$)/
|
||||||
|
const GENERATED_REMOTE = /^@deepseek-ai\/dsh-[a-z0-9]+(?:-[a-z0-9]+)*\/remote$/
|
||||||
|
|
||||||
|
function packageManifest(packageRoot) {
|
||||||
|
const path = resolve(packageRoot, 'package.json')
|
||||||
|
if (!existsSync(path)) throw new Error(`dshx client build: package.json not found at ${path}`)
|
||||||
|
return JSON.parse(readFileSync(path, 'utf8'))
|
||||||
|
}
|
||||||
|
|
||||||
|
function clientDeclaration(id, manifest) {
|
||||||
|
if (manifest.name !== id) {
|
||||||
|
throw new Error(`dshx client build: config id ${JSON.stringify(id)} does not match package name ${JSON.stringify(manifest.name)}`)
|
||||||
|
}
|
||||||
|
const declaration = manifest.dsh?.client
|
||||||
|
if (declaration === undefined || typeof declaration !== 'object' || declaration === null) {
|
||||||
|
throw new Error(`dshx client build: ${id} must declare dsh.client`)
|
||||||
|
}
|
||||||
|
if (declaration.platform !== 'web') {
|
||||||
|
throw new Error(`dshx client build: ${id} dsh.client.platform must be "web"`)
|
||||||
|
}
|
||||||
|
if (declaration.external !== undefined && (
|
||||||
|
!Array.isArray(declaration.external)
|
||||||
|
|| declaration.external.some(value => typeof value !== 'string' || value.length === 0)
|
||||||
|
)) {
|
||||||
|
throw new Error(`dshx client build: ${id} dsh.client.external must be an array of non-empty strings`)
|
||||||
|
}
|
||||||
|
const external = declaration.external ?? []
|
||||||
|
const duplicate = external.find((value, index) => external.indexOf(value) !== index)
|
||||||
|
if (duplicate !== undefined) {
|
||||||
|
throw new Error(`dshx client build: ${id} dsh.client.external contains duplicate ${JSON.stringify(duplicate)}`)
|
||||||
|
}
|
||||||
|
const baseline = new Set([...PLATFORM_MODULES, ...PRELOADED_CLIENT_EXTERNALS])
|
||||||
|
const repeatedBaseline = external.find(value => baseline.has(value))
|
||||||
|
if (repeatedBaseline !== undefined) {
|
||||||
|
throw new Error(`dshx client build: ${id} dsh.client.external repeats implicit baseline module ${JSON.stringify(repeatedBaseline)}`)
|
||||||
|
}
|
||||||
|
if (external.includes(id) || external.includes(`${id}/client`)) {
|
||||||
|
throw new Error(`dshx client build: ${id} dsh.client.external must not request its own package row`)
|
||||||
|
}
|
||||||
|
return declaration
|
||||||
|
}
|
||||||
|
|
||||||
|
function clientBuildValueDefines(environment) {
|
||||||
|
const values = {}
|
||||||
|
for (const [name, value] of Object.entries(environment)) {
|
||||||
|
if (!name.startsWith('DSH_CLIENT_') || value === undefined) continue
|
||||||
|
values[`process.env.${name}`] = JSON.stringify(value)
|
||||||
|
}
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
function clientDefines(environment) {
|
||||||
|
const mode = environment.NODE_ENV ?? 'production'
|
||||||
|
return {
|
||||||
|
'process.env': '{}',
|
||||||
|
'process.env.NODE_ENV': JSON.stringify(mode),
|
||||||
|
'import.meta.env.MODE': JSON.stringify(mode),
|
||||||
|
'import.meta.env': JSON.stringify({ MODE: mode }),
|
||||||
|
...clientBuildValueDefines(environment),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeSpecifier(name) {
|
||||||
|
return name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||||
|
}
|
||||||
|
|
||||||
|
function packagePatterns(manifest) {
|
||||||
|
const names = new Set([
|
||||||
|
...Object.keys(manifest.dependencies ?? {}),
|
||||||
|
...Object.keys(manifest.peerDependencies ?? {}),
|
||||||
|
...Object.keys(manifest.optionalDependencies ?? {}),
|
||||||
|
])
|
||||||
|
return [...names].sort().map(name => new RegExp(`^${escapeSpecifier(name)}(/|$)`))
|
||||||
|
}
|
||||||
|
|
||||||
|
function matches(patterns, specifier) {
|
||||||
|
return patterns.some(pattern => pattern.test(specifier))
|
||||||
|
}
|
||||||
|
|
||||||
|
function styleModule(id, path, css, classMap) {
|
||||||
|
const tagId = `${id}/${basename(path)}`
|
||||||
|
const source = [
|
||||||
|
`const css = ${JSON.stringify(css)};`,
|
||||||
|
`const tagId = ${JSON.stringify(tagId)};`,
|
||||||
|
"if (typeof document !== 'undefined' && document.querySelector('style[data-plugin-css=' + JSON.stringify(tagId) + ']') === null) {",
|
||||||
|
" const tag = document.createElement('style');",
|
||||||
|
` tag.dataset.plugin = ${JSON.stringify(id)};`,
|
||||||
|
' tag.dataset.pluginCss = tagId;',
|
||||||
|
' tag.textContent = css;',
|
||||||
|
' document.head.appendChild(tag);',
|
||||||
|
'}',
|
||||||
|
]
|
||||||
|
source.push(classMap === undefined ? 'export {};' : `export default ${JSON.stringify(classMap)};`)
|
||||||
|
return source.join('\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
function assetPath(source, importer) {
|
||||||
|
if (importer === undefined) return source
|
||||||
|
if (!source.startsWith('.') && !isAbsolute(source)) return createRequire(importer).resolve(source)
|
||||||
|
const emitted = resolve(dirname(importer), source)
|
||||||
|
if (existsSync(emitted)) return emitted
|
||||||
|
const boundary = emitted.indexOf(TYPES_MARKER)
|
||||||
|
if (boundary < 0) return emitted
|
||||||
|
return resolve(emitted.slice(0, boundary), 'src', emitted.slice(boundary + TYPES_MARKER.length))
|
||||||
|
}
|
||||||
|
|
||||||
|
function cssPlugins(id, requested) {
|
||||||
|
return [{
|
||||||
|
name: 'dshx-client-bundle-purity',
|
||||||
|
resolveId(source) {
|
||||||
|
if (!source.startsWith('@deepseek-ai/')) return null
|
||||||
|
if (requested.has(source)) return null
|
||||||
|
if (VENDORED_LIBRARY.test(source) || INLINE_SAFE.test(source) || GENERATED_REMOTE.test(source)) return null
|
||||||
|
throw new Error(
|
||||||
|
`dshx client bundle purity: ${JSON.stringify(source)} is not a shared baseline or dsh.client.external request; `
|
||||||
|
+ 'use a Cordis service/slot, a type-only import, or declare the exact dynamic module request',
|
||||||
|
)
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
name: 'dshx-css-modules',
|
||||||
|
resolveId(source, importer) {
|
||||||
|
if (!source.endsWith('.module.css')) return null
|
||||||
|
return CSS_MODULE_PREFIX + assetPath(source, importer) + VIRTUAL_SUFFIX
|
||||||
|
},
|
||||||
|
async load(virtualId) {
|
||||||
|
if (!virtualId.startsWith(CSS_MODULE_PREFIX)) return null
|
||||||
|
const path = virtualId.slice(CSS_MODULE_PREFIX.length, -VIRTUAL_SUFFIX.length)
|
||||||
|
this.addWatchFile(path)
|
||||||
|
const source = await readFile(path)
|
||||||
|
const { code, exports: cssExports } = transform({
|
||||||
|
filename: path,
|
||||||
|
code: source,
|
||||||
|
cssModules: { pattern: '[hash]_[local]' },
|
||||||
|
targets: CSS_TARGETS,
|
||||||
|
minify: true,
|
||||||
|
})
|
||||||
|
const classMap = {}
|
||||||
|
for (const [local, value] of Object.entries(cssExports ?? {}).sort(([left], [right]) => left.localeCompare(right))) {
|
||||||
|
classMap[local] = value.name
|
||||||
|
}
|
||||||
|
return styleModule(id, path, code.toString(), classMap)
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
name: 'dshx-css-inline',
|
||||||
|
resolveId(source, importer) {
|
||||||
|
if (!source.endsWith(`.css${INLINE_QUERY}`)) return null
|
||||||
|
const stylesheet = source.slice(0, -INLINE_QUERY.length)
|
||||||
|
return CSS_INLINE_PREFIX + assetPath(stylesheet, importer) + VIRTUAL_SUFFIX
|
||||||
|
},
|
||||||
|
async load(virtualId) {
|
||||||
|
if (!virtualId.startsWith(CSS_INLINE_PREFIX)) return null
|
||||||
|
const path = virtualId.slice(CSS_INLINE_PREFIX.length, -VIRTUAL_SUFFIX.length)
|
||||||
|
this.addWatchFile(path)
|
||||||
|
const source = await readFile(path)
|
||||||
|
const { code } = transform({ filename: path, code: source, targets: CSS_TARGETS, minify: true })
|
||||||
|
return `export default ${JSON.stringify(code.toString())};`
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
name: 'dshx-css-global',
|
||||||
|
resolveId(source, importer) {
|
||||||
|
if (!source.endsWith('.css') || source.endsWith('.module.css')) return null
|
||||||
|
return CSS_GLOBAL_PREFIX + assetPath(source, importer) + VIRTUAL_SUFFIX
|
||||||
|
},
|
||||||
|
async load(virtualId) {
|
||||||
|
if (!virtualId.startsWith(CSS_GLOBAL_PREFIX)) return null
|
||||||
|
const path = virtualId.slice(CSS_GLOBAL_PREFIX.length, -VIRTUAL_SUFFIX.length)
|
||||||
|
this.addWatchFile(path)
|
||||||
|
const source = await readFile(path)
|
||||||
|
const { code } = transform({ filename: path, code: source, targets: CSS_TARGETS, minify: true })
|
||||||
|
return styleModule(id, path, code.toString())
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
name: 'dshx-image-inline',
|
||||||
|
resolveId(source, importer) {
|
||||||
|
if (importer === undefined || !IMAGE_MEDIA_TYPES.has(extname(source))) return null
|
||||||
|
return assetPath(source, importer)
|
||||||
|
},
|
||||||
|
async load(fileId) {
|
||||||
|
const mediaType = IMAGE_MEDIA_TYPES.get(extname(fileId))
|
||||||
|
if (mediaType === undefined) return null
|
||||||
|
this.addWatchFile(fileId)
|
||||||
|
const data = await readFile(fileId)
|
||||||
|
return `export default ${JSON.stringify(`data:${mediaType};base64,${data.toString('base64')}`)};`
|
||||||
|
},
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a Host half plus a target-Harness lazy-CJS browser half for one out-of-tree package.
|
||||||
|
*
|
||||||
|
* @param {string} id package name and browser graph id.
|
||||||
|
* @param {readonly string[]} libEntry tsc-emitted Host entries under lib/types.
|
||||||
|
* @param {{ packageRoot?: string, clientEntry?: string }} options build paths.
|
||||||
|
* @returns {object[]} tsdown configuration array.
|
||||||
|
*/
|
||||||
|
export function externalClientBundle(id, libEntry, options = {}) {
|
||||||
|
const packageRoot = resolve(options.packageRoot ?? process.cwd())
|
||||||
|
assertPluginSource(process.env.DSHX_HARNESS, packageRoot)
|
||||||
|
const manifest = packageManifest(packageRoot)
|
||||||
|
const declaration = clientDeclaration(id, manifest)
|
||||||
|
const clientEntry = options.clientEntry ?? 'src/client/index.ts'
|
||||||
|
assertClientCordisInject(packageRoot, clientEntry)
|
||||||
|
const requested = new Set([
|
||||||
|
...PLATFORM_MODULES,
|
||||||
|
...PRELOADED_CLIENT_EXTERNALS,
|
||||||
|
...(declaration.external ?? []),
|
||||||
|
])
|
||||||
|
const production = packagePatterns(manifest)
|
||||||
|
const plugins = cssPlugins(id, requested)
|
||||||
|
|
||||||
|
return [{
|
||||||
|
name: id,
|
||||||
|
entry: [...libEntry],
|
||||||
|
outDir: 'lib',
|
||||||
|
format: ['esm'],
|
||||||
|
platform: 'node',
|
||||||
|
target: 'es2024',
|
||||||
|
fixedExtension: false,
|
||||||
|
dts: false,
|
||||||
|
clean: false,
|
||||||
|
define: clientBuildValueDefines(process.env),
|
||||||
|
deps: {
|
||||||
|
neverBundle: specifier => matches(production, specifier),
|
||||||
|
alwaysBundle: specifier => !isBuiltin(specifier) && !matches(production, specifier),
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
name: `${id}/client`,
|
||||||
|
entry: { client: clientEntry },
|
||||||
|
outDir: 'lib',
|
||||||
|
format: 'cjs',
|
||||||
|
platform: 'browser',
|
||||||
|
target: 'es2024',
|
||||||
|
dts: false,
|
||||||
|
sourcemap: true,
|
||||||
|
clean: false,
|
||||||
|
deps: {
|
||||||
|
neverBundle: specifier => requested.has(specifier),
|
||||||
|
alwaysBundle: specifier => !requested.has(specifier),
|
||||||
|
},
|
||||||
|
define: clientDefines(process.env),
|
||||||
|
plugins,
|
||||||
|
outputOptions: {
|
||||||
|
entryFileNames: 'client.js',
|
||||||
|
banner: `window.__ModuleLoader__.load({ id: ${JSON.stringify(id)}, factory: (require) => {`,
|
||||||
|
footer: 'return module.exports; } });',
|
||||||
|
intro: 'var module = { exports: {} }; var exports = module.exports;',
|
||||||
|
},
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,151 @@
|
||||||
|
/** Plugin-only boundary. Reading public Host APIs is allowed; writing official
|
||||||
|
* source, copies, worktrees, installed packages or generated artifacts is not. */
|
||||||
|
import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
|
||||||
|
import { dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path'
|
||||||
|
|
||||||
|
export const CORE_SOURCE_IMMUTABLE = 'CORE_SOURCE_IMMUTABLE'
|
||||||
|
export const PLUGIN_ONLY_RULE = 'DSHX and Creator Mode+ develop external plugins only. Never edit, patch, replace or rebuild DeepSeek Harness official source, shipped presets, installed official packages or their generated artifacts, including copies and worktrees. A missing public API is a plugin capability gap: use another public extension point or report the gap. A plugin task, handoff document, automatic approval, takeover or --force never authorizes a Host patch. Keep all build output inside the plugin. Watched user cordis.patch.yml configuration is not a source-code patch.'
|
||||||
|
const deny = detail => `${CORE_SOURCE_IMMUTABLE}: ${detail}. Use a public plugin extension point; do not patch the Host or retry with force/approval.`
|
||||||
|
const under = (parent, child) => { const r = relative(parent, child); return r === '' || (r !== '..' && !r.startsWith(`..${sep}`) && !isAbsolute(r)) }
|
||||||
|
function manifest(dir) { try { return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) } catch { return undefined } }
|
||||||
|
|
||||||
|
/** Resolve existing components before ..; also protects a not-yet-created file. */
|
||||||
|
export function canonicalTarget(path, cwd = process.cwd()) {
|
||||||
|
const absolute = isAbsolute(path) ? path : `${cwd}${sep}${path}`
|
||||||
|
let current = parse(absolute).root
|
||||||
|
for (const part of absolute.slice(current.length).split(sep)) {
|
||||||
|
if (!part || part === '.') continue
|
||||||
|
if (part === '..') { current = dirname(current); continue }
|
||||||
|
current = join(current, part)
|
||||||
|
try { current = realpathSync.native(current) }
|
||||||
|
catch (error) { if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error }
|
||||||
|
}
|
||||||
|
return current
|
||||||
|
}
|
||||||
|
function isHarness(dir) {
|
||||||
|
return manifest(dir)?.name === '@deepseek-ai/dsh-root'
|
||||||
|
|| (existsSync(join(dir, 'apps/cli/src/bin.ts')) && existsSync(join(dir, 'packages')) && existsSync(join(dir, 'vendor')))
|
||||||
|
}
|
||||||
|
function inHarnessSource(path, root) {
|
||||||
|
if (!under(root, path)) return false
|
||||||
|
const rel = relative(root, path).split(sep)
|
||||||
|
// Official tree surfaces are protected; sibling, independent external
|
||||||
|
// plugin directories remain supported. Real targets are resolved first.
|
||||||
|
if (rel.length === 1 && (rel[0] === '' || !existsSync(path) || !lstatSync(path).isDirectory())) return true
|
||||||
|
return ['apps', 'packages', 'vendor', 'scripts', 'config', 'configs', 'src',
|
||||||
|
'docs', 'assets', 'patches', 'benchmarks', 'native', 'python', 'snapshots', 'website', '.git', '.agents', '.github'].includes(rel[0])
|
||||||
|
}
|
||||||
|
export function coreWriteReason(path, harnessRoot, cwd) {
|
||||||
|
const target = canonicalTarget(path, cwd)
|
||||||
|
if (harnessRoot && inHarnessSource(target, canonicalTarget(harnessRoot))) return deny(`protected Harness path ${target}`)
|
||||||
|
let cursor = target
|
||||||
|
while (true) {
|
||||||
|
const pkg = manifest(cursor)
|
||||||
|
if (typeof pkg?.name === 'string' && pkg.name.startsWith('@deepseek-ai/') && pkg.name !== '@deepseek-ai/dsh-root') return deny(`official package ${pkg.name}: ${target}`)
|
||||||
|
if (isHarness(cursor) && inHarnessSource(target, cursor)) return deny(`official checkout or worktree ${cursor}: ${target}`)
|
||||||
|
const parent = dirname(cursor)
|
||||||
|
if (parent === cursor) return undefined
|
||||||
|
cursor = parent
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export function assertPluginSource(harnessRoot, dir, entry) {
|
||||||
|
const reason = coreWriteReason(dir, harnessRoot)
|
||||||
|
if (reason) throw new Error(reason)
|
||||||
|
if (entry) {
|
||||||
|
const target = canonicalTarget(entry)
|
||||||
|
const denied = coreWriteReason(target, harnessRoot)
|
||||||
|
if (denied) throw new Error(denied)
|
||||||
|
if (!under(canonicalTarget(dir), target)) throw new Error(deny(`plugin entry escapes its source directory: ${entry}`))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const PATCH_TARGET = /^(?:\+\+\+|---)\s+(?:[ab]\/)?(?:packages|apps|vendor|scripts|config)\/|^\*\*\* (?:Update|Add|Delete) File:\s*(?:[ab]\/)?(?:packages|apps|vendor|scripts|config)\//m
|
||||||
|
const SKIP = new Set(['node_modules', 'lib', 'dist', 'out', 'coverage', 'tests', 'test', 'fixtures'])
|
||||||
|
/** Release gate for concrete Host patches and compiler writes; not a proof that
|
||||||
|
* arbitrary third-party programs are safe. Never executes plugin scripts. */
|
||||||
|
export function auditPluginSource(harnessRoot, dir) {
|
||||||
|
const findings = []
|
||||||
|
assertPluginSource(harnessRoot, dir)
|
||||||
|
let count = 0
|
||||||
|
function walk(folder) {
|
||||||
|
for (const entry of readdirSync(folder, { withFileTypes: true })) {
|
||||||
|
if (entry.name.startsWith('.') || SKIP.has(entry.name)) continue
|
||||||
|
if (++count > 10000) throw new Error(deny('plugin boundary inventory exceeds 10000 files'))
|
||||||
|
const path = join(folder, entry.name)
|
||||||
|
if (entry.isSymbolicLink()) {
|
||||||
|
const reason = coreWriteReason(path, harnessRoot)
|
||||||
|
if (reason) findings.push({ path, message: reason })
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (entry.isDirectory()) { walk(path); continue }
|
||||||
|
if (!entry.isFile() || lstatSync(path).size > 1024 * 1024) continue
|
||||||
|
if (/\.(patch|diff)$/.test(entry.name) && PATCH_TARGET.test(readFileSync(path, 'utf8'))) {
|
||||||
|
findings.push({ path, message: deny('plugin contains a patch targeting official Host files') })
|
||||||
|
}
|
||||||
|
if (/^tsconfig.*\.json$/.test(entry.name)) {
|
||||||
|
// Conservative JSONC extraction: relevant path strings only, no code.
|
||||||
|
const source = readFileSync(path, 'utf8')
|
||||||
|
for (const match of source.matchAll(/"(?:outDir|outFile|declarationDir|tsBuildInfoFile)"\s*:\s*"([^"\n]+)"/g)) {
|
||||||
|
const output = canonicalTarget(match[1], folder)
|
||||||
|
if (!under(canonicalTarget(dir), output)) findings.push({ path, message: deny(`TypeScript output escapes the plugin: ${match[1]}`) })
|
||||||
|
}
|
||||||
|
const refs = source.match(/"references"\s*:\s*\[([\s\S]*?)\]/)?.[1] ?? ''
|
||||||
|
for (const match of refs.matchAll(/"path"\s*:\s*"([^"\n]+)"/g)) {
|
||||||
|
const reason = coreWriteReason(match[1], harnessRoot, folder)
|
||||||
|
if (reason) findings.push({ path, message: deny(`TypeScript project reference can rebuild official source: ${match[1]}`) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(dir)
|
||||||
|
return findings
|
||||||
|
}
|
||||||
|
|
||||||
|
function readOnlyShell(command) {
|
||||||
|
if (/[;&|`$><\n]/.test(command)) return false
|
||||||
|
if (/^\s*(?:cat|head|tail|ls|pwd|stat|realpath|readlink|rg)\b/.test(command)) return !/--pre\b/.test(command)
|
||||||
|
return /^\s*git\s+(?:(?:-C\s+(?:"[^"]+"|'[^']+'|\S+)\s+))?(?:status|diff|show|log|ls-files|rev-parse)\b/.test(command)
|
||||||
|
&& !/--(?:ext-diff|textconv|output|exec-path)\b/.test(command)
|
||||||
|
}
|
||||||
|
export function creatorCoreMutationReason(exec, harnessRoot, policy) {
|
||||||
|
const args = exec?.arguments ?? {}, cwd = exec?.agent?.session?.header?.cwd ?? process.cwd()
|
||||||
|
if (['write', 'edit', 'write_file', 'edit_file', 'delete_file', 'move_file', 'copy_file'].includes(exec?.name)) {
|
||||||
|
for (const key of ['file_path', 'path', 'destination', 'source', 'target']) {
|
||||||
|
if (typeof args[key] === 'string') { const reason = coreWriteReason(args[key], harnessRoot, cwd); if (reason) return reason }
|
||||||
|
}
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
if (exec?.name === 'apply_patch') {
|
||||||
|
const patch = args.patch ?? args.input ?? ''
|
||||||
|
for (const match of patch.matchAll(/^\*\*\* (?:(?:Update|Add|Delete) File|Move to):\s*(.+)$/gm)) {
|
||||||
|
const reason = coreWriteReason(match[1], harnessRoot, cwd); if (reason) return reason
|
||||||
|
}
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
if (!['bash', 'terminal_open', 'terminal_send'].includes(exec?.name)) return undefined
|
||||||
|
const command = args.command ?? args.text ?? ''
|
||||||
|
if (readOnlyShell(command)) return undefined
|
||||||
|
if (args.sandbox_permissions === 'danger-full-access') return deny('unconfined shell execution cannot protect official source')
|
||||||
|
if (!policy || !['read-only', 'workspace-write', 'danger-full-access'].includes(policy.mode)) {
|
||||||
|
return `CREATOR_SANDBOX_UNAVAILABLE: cannot verify a confined shell policy${policy?.unavailableReason ? ` (${policy.unavailableReason})` : ''}. The command was not executed. Repair Creator Mode+ sandbox service wiring; this is not evidence of an official-source write.`
|
||||||
|
}
|
||||||
|
if (exec.name === 'bash' && policy.shellConfined === false) return deny('the active shell executor does not enforce the sandbox policy')
|
||||||
|
if (policy?.mode === 'danger-full-access') return deny('switch Creator shell to workspace-write so the Host sandbox confines build scripts')
|
||||||
|
if (policy?.mode === 'workspace-write' && harnessRoot && under(canonicalTarget(policy.workspaceRoot), canonicalTarget(harnessRoot))) return deny('the shell workspace contains the official Harness; use a plugin-only workspace')
|
||||||
|
const workdir = canonicalTarget(args.workdir ?? args.cwd ?? cwd, cwd)
|
||||||
|
const atCore = coreWriteReason(workdir, harnessRoot)
|
||||||
|
if (atCore) return atCore
|
||||||
|
if (/\b(?:install-host-seam|patch-host|host-patches)(?:[/.\s]|$)/.test(command)) return deny('Host patch installation is outside plugin development')
|
||||||
|
for (const match of command.matchAll(/\/(?:[^\s"'`()[\]{};,<>|]+)/g)) {
|
||||||
|
const reason = coreWriteReason(match[0], harnessRoot, workdir)
|
||||||
|
if (reason) return reason
|
||||||
|
}
|
||||||
|
// This catches direct shell/REPL targets and git -C. The Host sandbox remains
|
||||||
|
// responsible for code that assembles a path dynamically.
|
||||||
|
for (const match of command.matchAll(/"([^"\n]+)"|'([^'\n]+)'|([^\s;|&()<>]+)/g)) {
|
||||||
|
const token = match[1] ?? match[2] ?? match[3]
|
||||||
|
if (!token.includes('/') || token.includes('://')) continue
|
||||||
|
const reason = coreWriteReason(token.replace(/^[\w]+=/, ''), harnessRoot, workdir)
|
||||||
|
if (reason) return reason
|
||||||
|
}
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,22 @@
|
||||||
|
/**
|
||||||
|
* Shared browser platform modules. Seeding, bundling externals, and Vite
|
||||||
|
* aliases consume this list so their module identities cannot drift.
|
||||||
|
* @module @deepseek-ai/dsh-client-web/src/platform
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** The module specifiers the shell shares into the frozen module table. */
|
||||||
|
export const PLATFORM_MODULES = [
|
||||||
|
'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',
|
||||||
|
] as const
|
||||||
|
|
||||||
|
/** Client-bundle specifiers whose factories the parser preloads before the shell starts. */
|
||||||
|
export const PRELOADED_CLIENT_EXTERNALS = [
|
||||||
|
] as const
|
||||||
|
|
||||||
|
/** One platform module specifier (a seed-table key). */
|
||||||
|
export type PlatformModule = (typeof PLATFORM_MODULES)[number]
|
||||||
|
|
@ -0,0 +1,189 @@
|
||||||
|
/** Static guard for Cordis service reads in an external Web client entry. */
|
||||||
|
|
||||||
|
import { existsSync, readFileSync } from 'node:fs'
|
||||||
|
import { join, resolve } from 'node:path'
|
||||||
|
import ts from 'typescript'
|
||||||
|
|
||||||
|
// Context members and Cordis mixins are available without plugin service inject.
|
||||||
|
const CORE_CONTEXT_MEMBERS = new Set([
|
||||||
|
'accessor',
|
||||||
|
'baseUrl',
|
||||||
|
'bail',
|
||||||
|
'effect',
|
||||||
|
'emit',
|
||||||
|
'events',
|
||||||
|
'extend',
|
||||||
|
'fiber',
|
||||||
|
'get',
|
||||||
|
'inject',
|
||||||
|
'intercept',
|
||||||
|
'isolate',
|
||||||
|
'logger',
|
||||||
|
'mixin',
|
||||||
|
'on',
|
||||||
|
'once',
|
||||||
|
'parallel',
|
||||||
|
'plugin',
|
||||||
|
'provide',
|
||||||
|
'reflect',
|
||||||
|
'registry',
|
||||||
|
'root',
|
||||||
|
'runtime',
|
||||||
|
'serial',
|
||||||
|
'set',
|
||||||
|
'waterfall',
|
||||||
|
])
|
||||||
|
|
||||||
|
function unwrap(expression) {
|
||||||
|
let current = expression
|
||||||
|
while (ts.isAsExpression(current)
|
||||||
|
|| ts.isSatisfiesExpression(current)
|
||||||
|
|| ts.isParenthesizedExpression(current)
|
||||||
|
|| ts.isNonNullExpression(current)) {
|
||||||
|
current = current.expression
|
||||||
|
}
|
||||||
|
return current
|
||||||
|
}
|
||||||
|
|
||||||
|
function scriptKind(path) {
|
||||||
|
if (path.endsWith('.tsx')) return ts.ScriptKind.TSX
|
||||||
|
if (path.endsWith('.jsx')) return ts.ScriptKind.JSX
|
||||||
|
if (path.endsWith('.js') || path.endsWith('.mjs') || path.endsWith('.cjs')) return ts.ScriptKind.JS
|
||||||
|
return ts.ScriptKind.TS
|
||||||
|
}
|
||||||
|
|
||||||
|
function exportedInject(source) {
|
||||||
|
for (const statement of source.statements) {
|
||||||
|
if (!ts.isVariableStatement(statement)
|
||||||
|
|| !statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue
|
||||||
|
for (const declaration of statement.declarationList.declarations) {
|
||||||
|
if (!ts.isIdentifier(declaration.name) || declaration.name.text !== 'inject') continue
|
||||||
|
if (!declaration.initializer) return { declared: new Set(), static: false }
|
||||||
|
const initializer = unwrap(declaration.initializer)
|
||||||
|
if (!ts.isArrayLiteralExpression(initializer)) return { declared: new Set(), static: false }
|
||||||
|
const declared = new Set()
|
||||||
|
for (const element of initializer.elements) {
|
||||||
|
const value = unwrap(element)
|
||||||
|
if (!ts.isStringLiteralLike(value)) return { declared, static: false }
|
||||||
|
declared.add(value.text)
|
||||||
|
}
|
||||||
|
return { declared, static: true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { declared: new Set(), static: true }
|
||||||
|
}
|
||||||
|
|
||||||
|
function contextNames(source) {
|
||||||
|
const names = new Set()
|
||||||
|
for (const statement of source.statements) {
|
||||||
|
if (!ts.isFunctionDeclaration(statement)
|
||||||
|
|| statement.name?.text !== 'apply'
|
||||||
|
|| !statement.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword)) continue
|
||||||
|
const parameter = statement.parameters[0]
|
||||||
|
if (parameter && ts.isIdentifier(parameter.name)) names.add(parameter.name.text)
|
||||||
|
}
|
||||||
|
|
||||||
|
let changed = true
|
||||||
|
while (changed) {
|
||||||
|
changed = false
|
||||||
|
const visit = (node) => {
|
||||||
|
if (ts.isVariableDeclaration(node)
|
||||||
|
&& ts.isIdentifier(node.name)
|
||||||
|
&& node.initializer
|
||||||
|
&& ts.isIdentifier(unwrap(node.initializer))
|
||||||
|
&& names.has(unwrap(node.initializer).text)
|
||||||
|
&& !names.has(node.name.text)) {
|
||||||
|
names.add(node.name.text)
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
ts.forEachChild(node, visit)
|
||||||
|
}
|
||||||
|
visit(source)
|
||||||
|
}
|
||||||
|
return names
|
||||||
|
}
|
||||||
|
|
||||||
|
function propertyName(node) {
|
||||||
|
if (ts.isIdentifier(node) || ts.isStringLiteralLike(node)) return node.text
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compare direct Cordis service reads with the client entry's exported inject.
|
||||||
|
* @param {string} path absolute client source entry.
|
||||||
|
* @returns {{ path: string, declared: string[], accessed: string[], missing: string[], staticInject: boolean }}
|
||||||
|
*/
|
||||||
|
export function inspectClientCordisInject(path) {
|
||||||
|
const text = readFileSync(path, 'utf8')
|
||||||
|
const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, scriptKind(path))
|
||||||
|
const { declared, static: staticInject } = exportedInject(source)
|
||||||
|
const contexts = contextNames(source)
|
||||||
|
const accessed = new Set()
|
||||||
|
|
||||||
|
const visit = (node) => {
|
||||||
|
if (ts.isPropertyAccessExpression(node)
|
||||||
|
&& ts.isIdentifier(node.expression)
|
||||||
|
&& contexts.has(node.expression.text)
|
||||||
|
&& !CORE_CONTEXT_MEMBERS.has(node.name.text)) {
|
||||||
|
accessed.add(node.name.text)
|
||||||
|
}
|
||||||
|
if (ts.isElementAccessExpression(node)
|
||||||
|
&& ts.isIdentifier(node.expression)
|
||||||
|
&& contexts.has(node.expression.text)
|
||||||
|
&& node.argumentExpression) {
|
||||||
|
const name = propertyName(unwrap(node.argumentExpression))
|
||||||
|
if (name && !CORE_CONTEXT_MEMBERS.has(name)) accessed.add(name)
|
||||||
|
}
|
||||||
|
if (ts.isVariableDeclaration(node)
|
||||||
|
&& ts.isObjectBindingPattern(node.name)
|
||||||
|
&& node.initializer
|
||||||
|
&& ts.isIdentifier(unwrap(node.initializer))
|
||||||
|
&& contexts.has(unwrap(node.initializer).text)) {
|
||||||
|
for (const element of node.name.elements) {
|
||||||
|
const name = propertyName(element.propertyName ?? element.name)
|
||||||
|
if (name && !CORE_CONTEXT_MEMBERS.has(name)) accessed.add(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ts.forEachChild(node, visit)
|
||||||
|
}
|
||||||
|
visit(source)
|
||||||
|
|
||||||
|
const sorted = values => [...values].sort()
|
||||||
|
return {
|
||||||
|
path,
|
||||||
|
declared: sorted(declared),
|
||||||
|
accessed: sorted(accessed),
|
||||||
|
missing: sorted([...accessed].filter(name => !declared.has(name))),
|
||||||
|
staticInject,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve the source entry declared by the dshx client build adapter. */
|
||||||
|
export function resolveClientSource(pluginDir) {
|
||||||
|
const configPath = join(pluginDir, 'tsdown.config.ts')
|
||||||
|
if (existsSync(configPath)) {
|
||||||
|
const config = readFileSync(configPath, 'utf8')
|
||||||
|
const match = config.match(/\bclientEntry\s*:\s*(['"])([^'"]+)\1/u)
|
||||||
|
if (match) return { path: resolve(pluginDir, match[2]), declared: true }
|
||||||
|
}
|
||||||
|
for (const candidate of ['src/client/index.tsx', 'src/client/index.ts', 'src/client/index.jsx', 'src/client/index.js']) {
|
||||||
|
const path = join(pluginDir, candidate)
|
||||||
|
if (existsSync(path)) return { path, declared: false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fail a client build before emitting a bundle with undeclared service reads. */
|
||||||
|
export function assertClientCordisInject(packageRoot, clientEntry) {
|
||||||
|
const path = resolve(packageRoot, clientEntry)
|
||||||
|
if (!existsSync(path)) return
|
||||||
|
const result = inspectClientCordisInject(path)
|
||||||
|
if (!result.staticInject) {
|
||||||
|
throw new Error(`dshx client build: ${clientEntry} must export a static string-literal Cordis inject array`)
|
||||||
|
}
|
||||||
|
if (result.missing.length > 0) {
|
||||||
|
throw new Error(
|
||||||
|
`dshx client build: ${clientEntry} reads undeclared Cordis service ${JSON.stringify(result.missing[0])}; `
|
||||||
|
+ `add it to the entry-level export const inject (missing: ${result.missing.join(', ')}). `
|
||||||
|
+ 'package.json dsh.client.inject is package metadata and cannot satisfy Cordis services',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,18 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2024",
|
||||||
|
"module": "NodeNext",
|
||||||
|
"moduleResolution": "NodeNext",
|
||||||
|
"strict": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"declaration": true,
|
||||||
|
"declarationMap": true,
|
||||||
|
"sourceMap": true,
|
||||||
|
"rootDir": "src",
|
||||||
|
"outDir": "lib/types",
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"lib": ["ES2024", "DOM", "DOM.Iterable"],
|
||||||
|
"types": ["node", "react"]
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,83 @@
|
||||||
|
import { resolve } from 'node:path'
|
||||||
|
import type { TsdownPlugin, UserConfig } from 'tsdown'
|
||||||
|
import { externalClientBundle } from './tools/client-build.js'
|
||||||
|
|
||||||
|
// The vendored dshx adapter resolves the target Harness client platform table
|
||||||
|
// from tools/harness by default (a copy of dsh-v0.2.2-rc.2
|
||||||
|
// packages/client/web/src/platform.ts), so a clean checkout builds without a
|
||||||
|
// Harness source checkout. Set DSHX_HARNESS to build against another target.
|
||||||
|
const bundle = externalClientBundle('dsh-better-chat', ['src/host.ts'], {
|
||||||
|
clientEntry: 'src/client/index.tsx',
|
||||||
|
}) as UserConfig[]
|
||||||
|
|
||||||
|
const portableOutput: TsdownPlugin = {
|
||||||
|
name: 'dsh-better-chat-portable-output',
|
||||||
|
generateBundle(_options, output) {
|
||||||
|
const client = output['client.js']
|
||||||
|
if (client?.type !== 'chunk') this.error('client.js was not emitted')
|
||||||
|
const root = resolve('.').replaceAll('\\', '/').replace(/\/$/u, '')
|
||||||
|
client.code = client.code.replace(
|
||||||
|
/^([ \t]*\/\/(?:#region )? ?)\\0dshx-css-module:([^\r\n]*?)(\r?)$/gmu,
|
||||||
|
(_match, prefix: string, rawPath: string, ending: string) => {
|
||||||
|
let cssPath = rawPath.replaceAll('\\', '/')
|
||||||
|
const rootPrefix = `${root}/`
|
||||||
|
if (cssPath.startsWith(rootPrefix)) cssPath = cssPath.slice(rootPrefix.length)
|
||||||
|
return `${prefix}\\0dshx-css-module:${cssPath}${ending}`
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if (/^[ \t]*\/\/(?:#region )? ?\\0dshx-css-module:(?:\/|[A-Za-z]:[\\/])/mu.test(client.code)) {
|
||||||
|
this.error('client.js contains a non-portable CSS module path')
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Guard against the 0.3.7 regression class: the host entry must not ship a
|
||||||
|
* relative specifier that cannot resolve inside the published tarball.
|
||||||
|
*/
|
||||||
|
const hostPortableOutput: TsdownPlugin = {
|
||||||
|
name: 'dsh-better-chat-host-portable-output',
|
||||||
|
generateBundle(_options, output) {
|
||||||
|
for (const [fileName, chunk] of Object.entries(output)) {
|
||||||
|
if (chunk.type !== 'chunk') continue
|
||||||
|
const offenders = [
|
||||||
|
...chunk.code.matchAll(/from\s*["'](\.[^"']*\.ts)["']/g),
|
||||||
|
...chunk.code.matchAll(/from\s*["'](\.\.?\/[^"']*node_modules\/[^"']*)["']/g),
|
||||||
|
].map((match) => match[1])
|
||||||
|
if (offenders.length > 0) {
|
||||||
|
this.error(
|
||||||
|
`${fileName} contains relative specifiers that will not resolve in the published package: ` +
|
||||||
|
`${[...new Set(offenders)].join(', ')}. Relative imports must be bundled, not externalised.`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export default bundle.map((config) => {
|
||||||
|
if (config.name === 'dsh-better-chat') {
|
||||||
|
const { external: _external, ...hostConfig } = config
|
||||||
|
return {
|
||||||
|
...hostConfig,
|
||||||
|
plugins: [
|
||||||
|
...(Array.isArray(hostConfig.plugins)
|
||||||
|
? hostConfig.plugins
|
||||||
|
: hostConfig.plugins === undefined
|
||||||
|
? []
|
||||||
|
: [hostConfig.plugins]),
|
||||||
|
hostPortableOutput,
|
||||||
|
],
|
||||||
|
// `neverBundle: true` keeps bare npm specifiers external and bundles
|
||||||
|
// relative imports; see the adapter's documentation for the 0.3.7
|
||||||
|
// ERR_MODULE_NOT_FOUND regression this prevents.
|
||||||
|
deps: { ...hostConfig.deps, neverBundle: true },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (config.name !== 'dsh-better-chat/client') return config
|
||||||
|
const plugins = Array.isArray(config.plugins)
|
||||||
|
? config.plugins
|
||||||
|
: config.plugins === undefined
|
||||||
|
? []
|
||||||
|
: [config.plugins]
|
||||||
|
return { ...config, plugins: [...plugins, portableOutput] }
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
// 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