diff --git a/.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.i18n.yaml index 511e290621..e0b3e158eb 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.i18n.yaml @@ -9,8 +9,8 @@ en: edefff7cd986a509 zh: a270839fa86976a2 /agent-note-guided-plugin-installation/decision: - en: 5448b9f8aaa9a569 - zh: 9024c5328c5da3bd + en: ca0224ae08a4b383 + zh: 780603ca24487949 /agent-note-guided-plugin-installation/alternatives-considered: en: be64b541f4d81e7c zh: 8600531c08ab4288 diff --git a/.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.md b/.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.md index 40cbf6179b..aa62340f84 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.md +++ b/.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.md @@ -14,7 +14,7 @@ The install dialog put a spec straight into `pnpm add` and showed pnpm's termina **A failed or cancelled installation restores the profile files.** `installBundle` snapshots `package.json` and `pnpm-lock.yaml` before pnpm runs and puts them back when pnpm fails, when the run is cancelled, or when the package pnpm added declares no bundle patch. This reverses, for installations only, the [manager's decision](2026-09-14-current-profile-plugin-management.md) to retain partial changes: an installation that did not produce a usable bundle must not leave a dependency the page cannot show. Removals keep that decision. Downloaded files can stay under `node_modules` and the pnpm store. -**A failed run is classified where the facts are.** `classifyInstallFailure` reads how the run ended and what pnpm printed — its `ERR_PNPM_*` codes and Node's errno names — into `packageResult.kind`. A run the manager terminated is classified `timeout` whatever exit status the signal left behind, so installation restores the files and removal reports failure instead of reading it as a success ([run bounds](../../../../packages/boot/plugin-manager/README.md)). The client shows the kind as one line and folds pnpm's output behind the details. Parsing the log is confined to this one function with a fixture-driven test. +**A failed run is classified where the facts are.** `classifyInstallFailure` reads how the run ended and what pnpm printed — its `ERR_PNPM_*` codes and Node's errno names — into `packageResult.kind`. A run the manager terminated is classified `timeout` whatever exit status the signal left behind, so installation restores the files and removal reports failure instead of reading it as a success ([run bounds](../../../../packages/boot/plugin-manager/README.md)). The client shows the kind as one line and folds pnpm's output behind the details, which also name the complete log and a failure that stopped before pnpm ran ([details](../bug-fix/2026-10-28-plugin-install-failure-diagnostics.md)). Parsing the log is confined to this one function with a fixture-driven test. **GitHub connection failures have a short budget before installation.** The Host runs a read-only `git ls-remote` check with the profile's Git and proxy configuration and a default `githubConnectionTimeoutMs` of 5000 ms. Credential helpers and prompts are disabled for this check, so authentication cannot consume the connection budget. Only network failures and timeouts prevent pnpm from starting; pnpm still owns authentication, HTTPS-to-SSH fallback, ref resolution and the full installation. The budget does not limit downloads or builds. The existing failure kind and `failedAt: 'spec-host'` let the Client show a connection error or timeout and offer a domestic registry for a replacement package spec. Cancellation and manager disposal terminate the check and its descendants before settling. diff --git a/.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.zh.md b/.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.zh.md index c53c138059..09c2c2e572 100644 --- a/.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-15-guided-plugin-installation.zh.md @@ -14,7 +14,7 @@ Status: implemented **失败或被取消的安装恢复 profile 文件。** `installBundle` 在 pnpm 运行前快照 `package.json` 与 `pnpm-lock.yaml`,在 pnpm 失败、运行被取消、或 pnpm 装入的包没有声明组合包 patch 时把它们放回去。这只针对安装反转了[管理器的决定](2026-09-14-current-profile-plugin-management.zh.md)中"保留部分改动"的部分:没有产出可用组合包的安装,不能留下一个页面无法显示的依赖。删除仍沿用那个决定。已下载文件可能留在 `node_modules` 与 pnpm 缓存中。 -**失败在事实所在处分类。** `classifyInstallFailure` 依据运行的结束方式和 pnpm 的输出——它的 `ERR_PNPM_*` 码和 Node 的 errno 名——给出 `packageResult.kind`。被管理器终止的运行,不论信号留下什么退出状态都归类为 `timeout`,因此安装会还原文件,删除则报告失败而不会读成成功([运行上界](../../../../packages/boot/plugin-manager/README.zh.md))。客户端把 kind 显示成一句话,把 pnpm 输出折叠进详情。对日志的解析只存在于这一个函数,用夹具驱动的测试钉住。 +**失败在事实所在处分类。** `classifyInstallFailure` 依据运行的结束方式和 pnpm 的输出——它的 `ERR_PNPM_*` 码和 Node 的 errno 名——给出 `packageResult.kind`。被管理器终止的运行,不论信号留下什么退出状态都归类为 `timeout`,因此安装会还原文件,删除则报告失败而不会读成成功([运行上界](../../../../packages/boot/plugin-manager/README.zh.md))。客户端把 kind 显示成一句话,把 pnpm 输出折叠进详情;详情还会指出完整日志,以及尚未运行 pnpm 就停下的一次失败([详情](../bug-fix/2026-10-28-plugin-install-failure-diagnostics.zh.md))。对日志的解析只存在于这一个函数,用夹具驱动的测试钉住。 **GitHub 连接失败在安装前有单独的短时限。** 宿主通过只读的 `git ls-remote` 检查连接,沿用 profile 的 Git 与代理配置,`githubConnectionTimeoutMs` 默认为 5000 毫秒。这次检查禁用凭据助手和认证提示,避免认证过程占用连接预算。只有网络失败与超时会阻止 pnpm 启动;认证、HTTPS 到 SSH 的回退、ref 解析及完整安装仍由 pnpm 负责。时限不约束下载或构建。已有的失败类型与 `failedAt: 'spec-host'` 让客户端显示连接失败或超时,并提供国内镜像供用户输入另一个包名。取消安装或销毁管理器会先终止检查及其子进程,再结束操作。 diff --git a/.agents/notes/implemented/architecture/2026-10-21-context-menu-contributions.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-21-context-menu-contributions.i18n.yaml new file mode 100644 index 0000000000..458cbcc733 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-21-context-menu-contributions.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-21-context-menu-contributions.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-21-context-menu-contributions.md +/agent-note-context-menu-contributions: + en: 380bed76b1989558 + zh: ecbb5c15933431f6 +/agent-note-context-menu-contributions/problem: + en: baf7f6e331fd9f03 + zh: 8a45faaad34e6b0c +/agent-note-context-menu-contributions/decision: + en: f04341778de57140 + zh: 12147060ea28feb1 +/agent-note-context-menu-contributions/alternatives-considered: + en: 1fc419cf3a0642d3 + zh: f774e64679bed2ab +/agent-note-context-menu-contributions/consequences: + en: 7a55e405714d598f + zh: d7ff74ace672bf22 diff --git a/.agents/notes/implemented/architecture/2026-10-21-context-menu-contributions.md b/.agents/notes/implemented/architecture/2026-10-21-context-menu-contributions.md new file mode 100644 index 0000000000..da02632cf2 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-21-context-menu-contributions.md @@ -0,0 +1,29 @@ +# Agent Note: Context menu contributions + +Status: implemented + +English | [中文](2026-10-21-context-menu-contributions.zh.md) + +## Problem + +Session and tab menus already accept React Slot entries. Reusing only those entries would require external plugins to supply React components and would leave action discovery, target capture, and cancellation coupled to each trigger. + +## Decision + +[Context menus](../../../../packages/client/ui-context-menu/README.md) own typed target families, contribution resolution, and callback lifetime. Feature plugins register actions through the same service available to external Client plugins. Plain presentation fields let a renderer consume resolved actions without loading contributed React components. Existing Session and tab Slots remain in feature-owned adapters, preserving those extension positions. + +[File actions](../../../../packages/client/ui-file-actions/README.md) own original-content transfer separately from menus and image components. Saving retains original encoding; clipboard interoperability may require PNG conversion. A browser download supplies no local path, so reveal requires a verified Host file or the destination returned by a native save. + +The menu plugin contributes `useContextMenu` through the existing Slot root binding. Its ordinary `getTriggerProps` factory centralizes DOM gestures while business owners still provide captured targets. Plain children receive props or existing delegates; a separate React Context or utility package would duplicate the established lifetime and injection mechanism. + +## Alternatives considered + +**React Slots alone.** They preserve arbitrary visual content but cannot supply a presentation-independent action model. They remain available for existing component contributions. + +**A central switch over built-in target kinds.** It would make each new plugin-owned target require changes to the menu implementation. Declaration merging and registered providers instead keep target-specific behavior with its owner. + +**Native menus first.** It would duplicate the existing keyboard, placement, and dismissal implementation while excluding component-only legacy entries. The shared Web renderer serves Desktop too; another renderer can consume the plain action view independently. + +## Consequences + +An opening captures its target and contribution set. Dismissal cancels metadata work; unloading withdraws that provider's actions. Selected actions own execution and must recheck mutable resources. Legacy React entries are absent from plain-data resolution, so native rendering cannot assume complete parity. These lifetimes are covered by registry tests; browser scenarios cover unchanged selection, original bytes, and nested-overlay dismissal. diff --git a/.agents/notes/implemented/architecture/2026-10-21-context-menu-contributions.zh.md b/.agents/notes/implemented/architecture/2026-10-21-context-menu-contributions.zh.md new file mode 100644 index 0000000000..cb0b3c5f3c --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-21-context-menu-contributions.zh.md @@ -0,0 +1,29 @@ +# Agent Note: 右键菜单贡献 + +Status: implemented + +[English](2026-10-21-context-menu-contributions.md) | 中文 + +## 问题 + +Session 和标签页菜单已经支持 React Slot 条目。仅复用这些条目会要求外部插件提供 React 组件,并使动作发现、目标捕获和取消逻辑继续耦合到各个触发位置。 + +## 决策 + +[右键菜单](../../../../packages/client/ui-context-menu/README.zh.md)负责类型化目标类别、贡献解析和回调生命周期。功能插件通过与外部 Client 插件相同的服务注册动作。纯数据展示字段让渲染器无需加载贡献方的 React 组件即可消费已解析动作。现有 Session 和标签页 Slot 保留在各功能所属的适配器中,从而保留这些扩展位置。 + +[文件动作](../../../../packages/client/ui-file-actions/README.zh.md)独立于菜单和图片组件负责原始内容传输。保存保留原始编码;剪贴板互操作可能需要转换为 PNG。浏览器下载不提供本机路径,因此在文件夹显示要求已验证的 Host 文件,或原生保存返回的目标路径。 + +菜单插件通过现有 Slot root 绑定贡献 `useContextMenu`。普通函数 `getTriggerProps` 统一处理 DOM 手势,业务所有者继续提供捕获的目标。普通子组件通过 props 或现有 delegate 接收能力;独立 React Context 或工具包会重复已有生命周期与注入机制。 + +## 考虑过的替代方案 + +**仅使用 React Slot。** 它们支持任意视觉内容,但无法提供独立于展示方式的动作模型。现有组件贡献仍可使用它们。 + +**在中心位置按内置目标类型分支。** 这种方式会使每个新增的插件目标都要求修改菜单实现。声明合并与注册式提供方让目标特有行为保留在其所属插件。 + +**优先实现原生菜单。** 这会重复已有的键盘、定位和关闭实现,同时无法容纳仅提供组件的旧条目。Desktop 同样使用共享 Web 渲染器;其他渲染器可以独立消费纯数据动作视图。 + +## 影响 + +打开菜单时捕获目标和贡献集合。关闭取消元数据任务;插件卸载撤回该提供方的动作。已选动作自行负责执行,并须重新检查可变资源。旧 React 条目不参与纯数据解析,因此原生渲染不能假定功能完全一致。注册表测试覆盖这些生命周期;浏览器场景覆盖选择不变、原始字节以及嵌套浮层关闭。 diff --git a/.agents/notes/implemented/bug-fix/2026-10-28-forge-git-session-permissions.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-10-28-forge-git-session-permissions.i18n.yaml new file mode 100644 index 0000000000..99a0eb8afa --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-28-forge-git-session-permissions.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-28-forge-git-session-permissions.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-10-28-forge-git-session-permissions.md +/agent-note-session-permissions-for-forge-git-queries: + en: a06c42342d1f0bad + zh: 88b063883336cb0b +/agent-note-session-permissions-for-forge-git-queries/problem: + en: ee1e5ba8190a9419 + zh: 88d6c35a3a400eb0 +/agent-note-session-permissions-for-forge-git-queries/decision: + en: 77d7706b2577e552 + zh: a4538a19656d5945 +/agent-note-session-permissions-for-forge-git-queries/alternatives-considered: + en: 69f0bbbc412a546f + zh: 9527e87b5adfc7c3 +/agent-note-session-permissions-for-forge-git-queries/consequences: + en: acf5249a959ac14c + zh: 268fc51ec3278dcb diff --git a/.agents/notes/implemented/bug-fix/2026-10-28-forge-git-session-permissions.md b/.agents/notes/implemented/bug-fix/2026-10-28-forge-git-session-permissions.md new file mode 100644 index 0000000000..fd753156d0 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-28-forge-git-session-permissions.md @@ -0,0 +1,31 @@ +# Agent Note: Session permissions for Forge Git queries + +Status: implemented + +English | [中文](2026-10-28-forge-git-session-permissions.zh.md) + +## Problem + +The [Forge panel](../feature/2026-10-09-forge-panel.md) forces read-only confinement even when a Session grants full access. On hosts without a usable sandbox, its checkout and local changes remain unavailable while the Session's shell works. Background queries also reach repository-configured executable helpers through working-tree comparisons. + +## Decision + +Git inspection uses the Session's resolved sandbox mode and subprocess provider. Full access requires no sandbox backend; confined modes retain their enforcement and never retry unconfined. The Session remains the authority for filesystem permissions, including workspace-write access. Query commands do not request repository mutations. + +Local patches and statistics apply command-local Git configuration to disable clean/process filters without changing user configuration. Environment entries preserve subsection names containing equals signs. Existing hook, fsmonitor, external-diff, textconv, optional-lock, and lazy-fetch restrictions remain; submodule queries show commit changes without scanning internal dirty files. Configuration read failure stops the comparison; the changes view reports the filter configuration failure separately from oversized diffs and offers a retry. These restrictions follow the informational-diff approach in Codex while retaining DSH's execution-world and cancellation ownership. + +## Alternatives considered + +**Force read-only for every query.** This makes an explicitly unconfined Session depend on an unavailable backend. Using the Session mode keeps tool and panel permission behavior consistent. + +**Retry without confinement after failure.** This would silently grant authority that a restricted Session does not have. + +**Run configured content converters.** They can execute programs and write files during automatic refresh. Disabling them trades converted-content equivalence for predictable query behavior. + +## Consequences + +Operating-system write protection follows the Session mode rather than a separate panel policy. With clean/process filters disabled, comparisons still apply Git's built-in newline, ident, and encoding conversions: materialized LFS and other filtered files can appear changed even when ordinary Git considers them clean. Pointer-only checkouts compare normally. Uncommitted submodule contents are omitted. The original Forge note remains active for panel ownership and worktree lifecycle; this note supersedes only its unconditional read-only policy. + +Filter overrides require Git 2.31 or newer; older Git can ignore them and execute configured helpers under Session permissions. Enumeration and diff run in separate processes, so a concurrently added driver can escape the overrides. These restrictions limit incidental helper execution; the Session sandbox determines the permissions of every process that runs. + +Real-repository tests cover permission modes, unavailable confinement, unchanged index/configuration, configured helper markers, submodule commits, filtered bytes, and failed filter enumeration. The Web replay covers permission changes through the picker and the resulting checkout and local-change view. diff --git a/.agents/notes/implemented/bug-fix/2026-10-28-forge-git-session-permissions.zh.md b/.agents/notes/implemented/bug-fix/2026-10-28-forge-git-session-permissions.zh.md new file mode 100644 index 0000000000..49ad8f7be5 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-28-forge-git-session-permissions.zh.md @@ -0,0 +1,31 @@ +# Agent Note: Forge Git 查询的 Session 权限 + +Status: implemented + +[English](2026-10-28-forge-git-session-permissions.md) | 中文 + +## 问题 + +[Forge 面板](../feature/2026-10-09-forge-panel.zh.md)即使在 Session 授予完全权限时也强制使用只读沙箱。在没有可用沙箱的主机上,Session 的 shell 可以工作,检出信息与本地变更却持续不可用。后台查询还会通过工作区比较执行仓库配置的辅助程序。 + +## 决策 + +Git 检查使用 Session 解析出的沙箱模式与子进程提供方。完全权限无需沙箱后端;受限模式保留强制约束,绝不以无沙箱方式重试。Session 统一决定文件系统权限,包括工作区写入权限。查询命令不请求修改仓库。 + +本地补丁与统计应用命令级 Git 配置以禁用 clean/process filter,不修改用户配置。环境项保留包含等号的子节名称。现有钩子、fsmonitor、外部 diff、textconv、可选锁与延迟获取限制继续生效;子模块查询展示提交变化,不扫描内部脏文件。配置读取失败时停止比较;变更视图区分过滤器配置失败与 diff 过大,并提供重试。这些限制参考 Codex 的信息展示型 diff,同时保留 DSH 对执行环境与取消过程的管理。 + +## 考虑过的替代方案 + +**所有查询强制只读。** 这让已明确取消限制的 Session 依赖不可用的后端。使用 Session 模式使工具与面板的权限行为一致。 + +**失败后无沙箱重试。** 这会静默授予受限 Session 原本没有的权限。 + +**运行已配置的内容转换器。** 它们可能在自动刷新时执行程序并写入文件。禁用它们以放弃转换后内容等价性为代价,换取可预测的查询行为。 + +## 后果 + +操作系统的写入保护跟随 Session 模式,而非独立的面板策略。禁用 clean/process filter 后,比较仍应用 Git 内置的换行、ident 与编码转换:已物化的 LFS 文件及其他过滤文件可能显示为变更,即使普通 Git 认为它们未变。仅保留指针的检出可正常比较。子模块内部未提交内容不显示。原 Forge 记录仍保留面板所有权与工作树生命周期的决策;本记录仅替代其无条件只读策略。 + +过滤器覆盖需要 Git 2.31 或更新版本;旧 Git 可能忽略覆盖,按 Session 权限执行已配置的辅助程序。枚举与 diff 在独立进程中执行,因此并发新增的驱动可能绕过覆盖。这些限制减少附带的辅助程序执行;所有实际运行进程的权限由 Session 沙箱决定。 + +真实仓库测试覆盖权限模式、沙箱不可用、索引与配置不变、辅助程序标记、子模块提交、过滤文件字节和过滤器枚举失败。Web 回放覆盖通过选择器切换权限及相应的检出信息与本地变更视图。 diff --git a/.agents/notes/implemented/bug-fix/2026-10-28-plugin-install-failure-diagnostics.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-10-28-plugin-install-failure-diagnostics.i18n.yaml new file mode 100644 index 0000000000..aaf821df79 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-28-plugin-install-failure-diagnostics.i18n.yaml @@ -0,0 +1,25 @@ +# Bilingual-pair consistency record for 2026-10-28-plugin-install-failure-diagnostics.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-10-28-plugin-install-failure-diagnostics.md +/agent-note-install-failures-keep-their-diagnostics-in-the-dialog: + en: dc13db49685fee98 + zh: 65896465ceaba16a +/agent-note-install-failures-keep-their-diagnostics-in-the-dialog/problem: + en: 34c85dbc0fdaeeaf + zh: b11042edb1eb8e3b +/agent-note-install-failures-keep-their-diagnostics-in-the-dialog/decision: + en: fa3f10f9d7502077 + zh: c6b83153a0f5e324 +/agent-note-install-failures-keep-their-diagnostics-in-the-dialog/alternatives-considered: + en: 2616d060183a7a74 + zh: 15179fd42ea2b6dc +/agent-note-install-failures-keep-their-diagnostics-in-the-dialog/consequences: + en: 246d2a60f856c631 + zh: d7a552af3ad32b6f +/agent-note-install-failures-keep-their-diagnostics-in-the-dialog/related: + en: e0709383c16148e9 + zh: 00765408d0ad25f1 +/agent-note-install-failures-keep-their-diagnostics-in-the-dialog/testing: + en: 336df2ffde183519 + zh: 86e62a8a052c1f91 diff --git a/.agents/notes/implemented/bug-fix/2026-10-28-plugin-install-failure-diagnostics.md b/.agents/notes/implemented/bug-fix/2026-10-28-plugin-install-failure-diagnostics.md new file mode 100644 index 0000000000..89712bf9f7 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-28-plugin-install-failure-diagnostics.md @@ -0,0 +1,47 @@ +# Agent Note: Install failures keep their diagnostics in the dialog + +Status: implemented + +English | [中文](2026-10-28-plugin-install-failure-diagnostics.zh.md) + +## Problem + +A failed plugin installation could show the generic sentence "Something went wrong during the install; the details say what" while its expanded details showed only "No output". The dialog rendered the live install-log stream and the failure kind, and the two Host diagnostics that explain such a failure never entered that stream. A pnpm run that printed nothing had its diagnostic (`result.shortMessage`, or `pnpm failed` as the fallback) written to the complete log and the returned result but never streamed, so the dialog's terminal stayed empty. The GitHub connection check that stops an installation before pnpm runs kept its captured output only in `packageResult.output`. The Client also ignored the settled result's `packageResult.logPath` and `stage`, so a failure with recorded diagnostics offered no path to the complete log and could not say that a finished installation failed while the bundle was being activated. + +## Decision + +**The install-log stream carries the Host diagnostic of every run the dialog shows.** A pnpm run that fails without printing anything streams the diagnostic the Host records for it, so the complete log and the dialog show the same text. The GitHub connection check reports the `git … ls-remote` command line it ran, with the user information of an http(s) repository URL removed; when its network failure or timeout stops the installation, `installBundle` emits that command, the captured output, and the failure's exit status as the installation's only install-log run under the caller's request id. A check failure the installation survives streams nothing. A timed-out check's Git returned no exit status, so that run settles without one; the returned result records the coerced status 1, because `PackageResult.exitCode` is a number, and `PackageResult.timedOut` states that the status is the one the failure is read as. The command line itself stays module-local: `installBundle` strips it off the plain `PackageResult` it returns, so no second wire field appears. + +**The failed screen keeps what the settled result reports, not only the live stream.** `InstallState` holds the settled `packageResult.logPath` — the run that settled the dialog, on the Host's filesystem — and the details name it as the complete log. `InstallState['failure'].stage` and `ChangeResult.enabled` add the sentence that the installation finished and enabling the bundle failed, only when that change did ask to enable it; an install that left activation to **Enable now** never claims it failed enabling. Details on a settled screen without a streamed run say the dialog received no terminal output, never that the run printed none, and a running install makes no such claim. The generic sentence names the failed install command, except when the failed step is applying an enabled bundle, where the enabling sentence stands alone. The answer and the log travel over separate transports, so a run whose first chunk arrives after the answer is kept in the settled dialog as a settled run rather than dropped or shown as running. + +No wire type, public export, or config key is added: `ChangeResult.packageResult.logPath`, `ChangeResult.stage`, `ChangeResult.enabled`, and `packageResult.timedOut` already carry these facts to every consumer. The check's command line is a module-local `GithubConnectionFailure` in `github-connection.ts`. + +## Alternatives considered + +**Have the Client synthesize a terminal run from `packageResult.output`.** Rejected: the install-log stream would stay incomplete for every other reader, including the agent tool and the complete Host log, and the dialog would carry two notions of a run — one streamed, one rebuilt from the result. + +**Render `packageResult.output` as a separate Host-diagnostic block.** Rejected: it duplicates the terminal surface with a second styling and copy path, and the failing check's command line would still be missing. + +**Add a failure-stage field to `ChangeResult`.** Rejected: `stage` already names installation and activation, and only activation needed its own sentence; a second stage vocabulary would make every consumer learn two fields for one fact. + +**Keep the generic sentence and rely on the details.** Rejected: the empty details panel this fixes was exactly what the sentence pointed at, so the sentence must not promise diagnostics the dialog does not show. + +**Report the check's coerced exit code in the streamed run too.** Rejected: the stream describes what the process did, and a Git the deadline killed returned no status; the result keeps the coerced status only because its exit code is a number, which the JSDoc states. + +## Consequences + +- A failed installation always offers something to act on: a pnpm diagnostic for a silent failure, the failing Git command and its output for a GitHub connection failure, the complete log of the settled run, and a sentence naming the failed step when an enabled installation could not be applied. +- The generic sentence becomes "The install command failed; the details say why" in every dictionary; the details' no-run note says the dialog received no terminal output. +- A GitHub connection failure reports `timedOut` and returns the coerced exit status 1, while its streamed run settles without an exit code; the displayed command line omits URL user information, and no `argv` field joins the Remote answer. +- The details' log path covers the run that settled the dialog and is a Host path, so earlier registry attempts and a remote browser may not reach it. +- No new configuration, wire field, or public package export. + +## Related + +[Guided plugin installation](../architecture/2026-09-15-guided-plugin-installation.md) owns the install dialog's screens, the pre-install spec check, and the failure classification; this note extends its failed screen and install-log stream. + +## Testing + +- `packages/boot/plugin-manager/tests/operations.spec.ts` pins the no-output diagnostic stream; `github-connection.spec.ts` pins the recorded command line without URL user information and the timeout state, including the coerced status in the result; `manager.spec.ts` pins the single streamed check run under the request id, its absent exit code on timeout, that the returned `packageResult` carries no command line, and that a check failure pnpm may resolve streams nothing. +- `packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts` pins the settled log path, stage and enablement fact, the run kept when its first chunk arrives after the answer, and the reset on retry; `components.client.spec.tsx` pins the enabling sentence (only for an install that asked to enable), the complete-log line, and the settled no-output sentence. +- `apps/web/tests/plugin-install-github.e2e.ts` expands the details of a real GitHub connection failure and finds the Git command, its output, and the log path; `apps/web/tests/plugin-install-silent-failure.e2e.ts` fails a real installation through a package manager that prints nothing and finds the run's command line, its diagnostic, and the complete log in the details. diff --git a/.agents/notes/implemented/bug-fix/2026-10-28-plugin-install-failure-diagnostics.zh.md b/.agents/notes/implemented/bug-fix/2026-10-28-plugin-install-failure-diagnostics.zh.md new file mode 100644 index 0000000000..5c8220ed13 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-28-plugin-install-failure-diagnostics.zh.md @@ -0,0 +1,47 @@ +# Agent Note: Install failures keep their diagnostics in the dialog + +Status: implemented + +[English](2026-10-28-plugin-install-failure-diagnostics.md) | 中文 + +## Problem + +一次插件安装失败时,界面可能显示通用的“安装过程中出错,原因见安装详情”,而展开后的详情只有“无输出”。对话框渲染的是实时的 install-log 流和失败 kind,而解释这类失败的 Host 诊断从未进入该流。打印了空输出的 pnpm 运行,其诊断(`result.shortMessage`,缺省为 `pnpm failed`)只写进完整日志和返回结果,从未被流式发送,因此对话框的终端一直是空的。在 pnpm 运行前就中止安装的 GitHub 连接检查,其捕获的输出只留在 `packageResult.output` 里。客户端同时也忽略了已结束结果中的 `packageResult.logPath` 和 `stage`,所以即使诊断已被记录,失败界面也没有指向完整日志的入口,也无法说明安装其实已经完成、失败发生在启用 bundle 时。 + +## Decision + +**install-log 流携带对话框所展示的每一次运行的 Host 诊断。** 没有打印任何内容就失败的 pnpm 运行,会把 Host 为其记录的那条诊断流式发送出来,于是完整日志和对话框显示同样的文本。GitHub 连接检查会报告它实际执行的 `git … ls-remote` 命令行,并去掉 http(s) 仓库 URL 中的用户信息;当它的网络失败或超时中止安装时,`installBundle` 把该命令、捕获的输出和这次失败的退出状态作为该次安装唯一的 install-log 运行、以调用方的 request id 发出。安装仍能继续进行的检查失败不发送任何内容。超时的检查里 Git 没有返回退出状态,所以该运行不带退出码结束;返回结果记录强制填入的状态 1,因为 `PackageResult.exitCode` 是数字,而 `PackageResult.timedOut` 说明该状态只是失败被读取成的状态。命令行本身仍只在模块内:`installBundle` 在返回的普通 `PackageResult` 上剥掉它,因此不会多出 wire 字段。 + +**失败界面保留已结束结果所报告的内容,而不只是实时流。** `InstallState` 持有已结束的 `packageResult.logPath`——结束对话框的那次运行,位于 Host 文件系统——详情把它标为完整日志。`InstallState['failure'].stage` 与 `ChangeResult.enabled` 补充一句话:安装已完成,启用 bundle 时失败;只有当这次变更确实要求启用时才出现,把启用留给**立即启用**的安装不会声称启用失败。已结束界面里没有任何流式运行的详情会说明对话框没有收到终端输出,而不会断言运行本身没有输出;安装进行中也不会这样说。通用提示句点明失败的是安装命令,但失败步骤是应用已启用的 bundle 时,只使用启用阶段的那句话。安装应答与日志走不同传输,因此首个 chunk 晚于应答到达的运行会作为已结束的运行保留在已结束的对话框里,既不会被丢弃,也不会显示成运行中。 + +不新增 wire 类型、公开导出或配置键:`ChangeResult.packageResult.logPath`、`ChangeResult.stage`、`ChangeResult.enabled` 和 `packageResult.timedOut` 本来就把这些事实带给每个消费方。检查的命令行是 `github-connection.ts` 内模块级的 `GithubConnectionFailure`。 + +## Alternatives considered + +**让客户端从 `packageResult.output` 合成一次终端运行。** 否决:对其他读取方(agent 工具和完整的 Host 日志)来说 install-log 流仍然不完整,而且对话框会出现两种“运行”的概念——一种来自流,一种从结果重建。 + +**把 `packageResult.output` 渲染成单独的 Host 诊断块。** 否决:它会以第二套样式和文案路径重复终端界面,而且失败检查的命令行仍然缺失。 + +**给 `ChangeResult` 新增失败阶段字段。** 否决:`stage` 已经区分安装和启用,而且只有启用需要自己的提示句;第二套阶段词汇会让每个消费方为一个事实学两个字段。 + +**保留通用提示句、只依赖详情。** 否决:这次要修的正是被该提示句指向的空详情面板,因此提示句不能承诺对话框并不显示的诊断。 + +**在流式运行里也报告检查被强制的退出码。** 否决:流描述的是进程实际做了什么,而被期限终止的 Git 没有返回任何状态;结果保留强制状态只是因为它的退出码字段是数字,JSDoc 已写明这一点。 + +## Consequences + +- 安装失败后总有可行动的信息:静默失败时的 pnpm 诊断、GitHub 连接失败时出错的 Git 命令及其输出、结束对话框那次运行的完整日志,以及已启用的安装在应用阶段失败时点名失败步骤的一句话。 +- 通用提示句在所有词典中变为“安装命令失败,原因见安装详情”;详情里的无运行提示改为说明对话框没有收到终端输出。 +- GitHub 连接失败会报告 `timedOut` 并返回强制状态 1,而它的流式运行不带退出码结束;展示的命令行去掉 URL 用户信息,Remote 应答里也不会多出 `argv` 字段。 +- 详情里的日志路径只覆盖结束对话框的那次运行,且是 Host 路径,因此更早的换源尝试与远端浏览器可能都够不到它。 +- 不新增配置、wire 字段或公开包导出。 + +## Related + +[Guided plugin installation](../architecture/2026-09-15-guided-plugin-installation.zh.md) 拥有安装对话框的各个界面、安装前的 spec 检查和失败分类;本记录扩展了它的失败界面和 install-log 流。 + +## Testing + +- `packages/boot/plugin-manager/tests/operations.spec.ts` 钉住无输出诊断的流式发送;`github-connection.spec.ts` 钉住去掉 URL 用户信息的记录命令行与超时状态(含结果里的强制状态);`manager.spec.ts` 钉住以 request id 发送的唯一检查运行、超时下缺失的退出码、返回的 `packageResult` 不含命令行,以及 pnpm 可能自行解决的检查失败不发送任何运行。 +- `packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts` 钉住已结束的日志路径、stage 与启用事实、首个 chunk 晚于应答到达时保留的运行,以及重试时的重置;`components.client.spec.tsx` 钉住启用阶段的提示句(只对要求启用的安装)、完整日志行,以及已结束界面的无输出提示句。 +- `apps/web/tests/plugin-install-github.e2e.ts` 展开一次真实 GitHub 连接失败的详情,找到 Git 命令、它的输出和日志路径;`apps/web/tests/plugin-install-silent-failure.e2e.ts` 让一次真实安装通过不打印任何内容的包管理器失败,并在详情中找到该运行的命令行、诊断和完整日志。 diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml index 6f3f674ec6..53d2b74f3a 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml @@ -9,8 +9,8 @@ en: 344bcc7e9825bbc8 zh: c1d0f4b54f5b3786 /agent-note-change-request-panel-and-worktree-sessions/decision: - en: 0b159e4e33409515 - zh: 2bf1eafd644f2d26 + en: 6a0dc836205863ba + zh: 3d4feb0385953dda /agent-note-change-request-panel-and-worktree-sessions/deferred: en: 32ef8af85f4d2f66 zh: b82b67f94346399e @@ -18,5 +18,5 @@ en: e471e16b6b6450ca zh: 5fbc9242edc8d112 /agent-note-change-request-panel-and-worktree-sessions/consequences: - en: 97976f073b9f65e0 - zh: 95be3f7f375b0876 + en: 81790c448f0a7d3b + zh: ec63ccb2ad315ff8 diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md index 7792f8caf9..1285ba6cdf 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md @@ -12,7 +12,7 @@ English | [中文](2026-10-09-forge-panel.zh.md) [`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.md) is a two-face package. Its Host half, the `forgePanel` Remote, assembles everything the panel shows for one Session into one streamed state; the forge registry and the binding service keep only their domain operations. Its Client half is a right-sidebar tab, a Session header button that shows or hides it, a New Session option, a creation card above the composer, a toast, and the [Session list icons and hover card section](2026-10-20-forge-session-list.md). Every surface calls a bound item a change request, the forge registry's term, whatever its code host calls it. The [forge bundle](../../../../packages/experimental/forge-bundle/README.md) ships the panel, the forge registry, the GitHub provider, the bindings, and an isolated worktree service as one default-disabled Plugins page entry. -The Remote inspects the checkout through the Session's subprocess provider under the Session's read-only sandbox policy, so it reads what the Session's commands see and cannot write. Inspection reads the top-level, Git, and common Git directories, the branch or the abbreviated HEAD commit, the upstream, the remotes, and the size of the branch's changes against its fork point. It runs when a Session is followed, after each `working-directory/change`, `tool/result`, and `sandbox/mode` event, and on refresh, one at a time with one trailing rerun. +The Remote inspects the checkout through the Session's subprocess provider under its [resolved permissions and query restrictions](../bug-fix/2026-10-28-forge-git-session-permissions.md), so it reads what the Session's commands see. Inspection reads the top-level, Git, and common Git directories, the branch or the abbreviated HEAD commit, the upstream, the remotes, and the size of the branch's changes against its fork point. It runs when a Session is followed, after each `working-directory/change`, `tool/result`, and `sandbox/mode` event, and on refresh, one at a time with one trailing rerun. Status polling follows panel subscriptions: a Session's bindings are watched only while one of its surfaces is mounted, and the registry stops polling change requests nobody watches. Each card keeps the last snapshot a poll returned, so a transient failure keeps the title and number visible. A Session's only open change request starts expanded, and with several every card starts collapsed; the user's first toggle replaces this default. @@ -24,7 +24,7 @@ The worktree a Session works in can be removed outside it. Each inspection check The panel does not move a Session between existing worktrees. Removing a change request appends a `dismiss` record, and its toast offers Undo through `track`. -The panel also shows the changes behind a Session's work in a changes view, a resource tab type of this package. The Remote parses every diff on the Host into files and hunks, so the browser draws them without a patch parser, and bounds each read with `maxDiffBytes` and `maxUntrackedFiles`. Local changes come from confined `git diff` in the Session's execution world, in a scope the user picks: the branch against its fork point by default, or the uncommitted, unstaged, or staged changes; untracked files are read through the Session's filesystem and shown as new files. A change request's changes come from its code host at the head of the binding's latest status, through two provider reads the forge seam gained, `diff` and `fileText`. The Host keeps the patch it read last for each change request, keyed by the head commit and base branch and bounded by `maxCachedDiffBytes`, so reopening, refreshing, and navigating at the same head download nothing again; a host or provider that refuses an answer over its size limit reports the forge failure `too-large`, and the view then offers the change request's web page instead of a retry. Unchanged lines between hunks expand from the file's new side, which is the working tree, the index, or the head commit, and only while that text still matches the hunks. Each inspection also sizes the branch's changes for a local changes card, shown while no open change request carries the checked-out branch; its Create change request sends the Session a user message, so the Agent creates the change request with its own tools and the binding follows from `gh pr create` as for any other. +The panel also shows the changes behind a Session's work in a changes view, a resource tab type of this package. The Remote parses every diff on the Host into files and hunks, so the browser draws them without a patch parser, and bounds each read with `maxDiffBytes` and `maxUntrackedFiles`. Local changes come from `git diff` using the Session's permissions and execution world, in a scope the user picks: the branch against its fork point by default, or the uncommitted, unstaged, or staged changes; untracked files are read through the Session's filesystem and shown as new files. A change request's changes come from its code host at the head of the binding's latest status, through two provider reads the forge seam gained, `diff` and `fileText`. The Host keeps the patch it read last for each change request, keyed by the head commit and base branch and bounded by `maxCachedDiffBytes`, so reopening, refreshing, and navigating at the same head download nothing again; a host or provider that refuses an answer over its size limit reports the forge failure `too-large`, and the view then offers the change request's web page instead of a retry. Unchanged lines between hunks expand from the file's new side, which is the working tree, the index, or the head commit, and only while that text still matches the hunks. Each inspection also sizes the branch's changes for a local changes card, shown while no open change request carries the checked-out branch; its Create change request sends the Session a user message, so the Agent creates the change request with its own tools and the binding follows from `gh pr create` as for any other. Review comments capture the file, side, range, complete hunk, and reviewed head when the user selects code. Agent references enter the existing composer quote mechanism, so the user controls batching and the sent message records exactly what the model receives. GitHub writes belong to the optional forge provider operation: preflight checks the current head, the write addresses that commit, and an ambiguous outcome blocks another write until the user reconciles it. Review drafts and inline records belong to a browser tab occurrence, not to the Session log or a GitHub pending review. Switching Sessions retains that occurrence; closing it discards the local state and rejects late write completions. Published GitHub comments remain external records. @@ -89,4 +89,4 @@ The changes view offers no scope for one commit or for the last turn yet; both w ## Consequences -The panel shows current status only while it is open; checks that finish while nothing is mounted produce no notification. Changes made outside the Session appear after Refresh or the next tool result. Every inspection spawns up to eleven short Git processes in the Session's execution world with one remote, and two more for each further remote it tries for a fork point. A worktree exists only for a Session that requested it before its first step, and a failed or cancelled attempt can leave its branch or checkout behind. A message that enters while the Agent runs a turn or other maintenance gets no hold, so its worktree is created within the first turn and a removed worktree is not checked. While a message waits, the Agent stays idle in maintenance: the composer offers no stop, and callers waiting for the Agent to become idle wait as well. Restoring loses changes that were never committed. A base branch that requires a merge queue cannot merge from the panel. With Git Worktrees also enabled, two independent worktree services exist; the model's tool never sees the panel's service. A local or change request diff over `maxDiffBytes`, or one the host refuses, shows no files. Expanding unchanged lines of a change request reads each file from the code host once. +The panel shows current status only while it is open; checks that finish while nothing is mounted produce no notification. Changes made outside the Session appear after Refresh or the next tool result. Every inspection spawns up to twelve short Git processes in the Session's execution world with one remote, and two more for each further remote it tries for a fork point. A worktree exists only for a Session that requested it before its first step, and a failed or cancelled attempt can leave its branch or checkout behind. A message that enters while the Agent runs a turn or other maintenance gets no hold, so its worktree is created within the first turn and a removed worktree is not checked. While a message waits, the Agent stays idle in maintenance: the composer offers no stop, and callers waiting for the Agent to become idle wait as well. Restoring loses changes that were never committed. A base branch that requires a merge queue cannot merge from the panel. With Git Worktrees also enabled, two independent worktree services exist; the model's tool never sees the panel's service. A local or change request diff over `maxDiffBytes`, or one the host refuses, shows no files. Expanding unchanged lines of a change request reads each file from the code host once. diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md index ea7847b96e..432f2b10a8 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md @@ -12,7 +12,7 @@ Status: implemented [`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.zh.md) 是一个双端包。宿主端的 `forgePanel` Remote 把面板为一个 Session 展示的全部内容组装成一条流式状态;forge 注册表与绑定服务只保留各自的领域操作。客户端包括一个右侧边栏标签页、一个显示或隐藏它的 Session 标题栏按钮、一个新会话选项、一张位于输入框上方的创建卡片、一个 toast,以及[会话列表中的图标与悬浮卡片部分](2026-10-20-forge-session-list.zh.md)。所有界面都把已绑定的条目称为变更请求(forge 注册表的术语),不随代码托管平台的叫法变化。[forge 套件](../../../../packages/experimental/forge-bundle/README.zh.md)把面板、forge 注册表、GitHub 提供方、绑定服务与一个隔离的 worktree 服务作为插件页中默认禁用的一个条目发布。 -Remote 通过 Session 的子进程提供方、在 Session 的只读沙箱策略下检查检出,因此它读到的与 Session 命令看到的相同,且无法写入。检查读取顶层目录、Git 目录与公共 Git 目录、分支或缩写的 HEAD 提交、上游与远端,以及分支相对于其分叉点的变更规模。它在 Session 被关注时、每个 `working-directory/change`、`tool/result` 与 `sandbox/mode` 事件之后以及刷新时运行,一次只运行一个,最多再追加一次。 +Remote 通过 Session 的子进程提供方,按其[解析出的权限与查询限制](../bug-fix/2026-10-28-forge-git-session-permissions.zh.md)检查检出,因此它读到的与 Session 命令看到的相同。检查读取顶层目录、Git 目录与公共 Git 目录、分支或缩写的 HEAD 提交、上游与远端,以及分支相对于其分叉点的变更规模。它在 Session 被关注时、每个 `working-directory/change`、`tool/result` 与 `sandbox/mode` 事件之后以及刷新时运行,一次只运行一个,最多再追加一次。 状态轮询跟随面板订阅:只有该 Session 的某个界面挂载时才监听其绑定,注册表停止轮询无人监听的变更请求。每张卡片保留最近一次轮询得到的快照,因此短暂的失败不会让标题与编号消失。Session 只有一个打开的变更请求时,它的卡片默认展开;有多个时全部折叠;用户第一次展开或收起卡片后,以用户的选择为准。 @@ -24,7 +24,7 @@ Session 所在的 worktree 可能在 Session 之外被删除。每次检查都 面板不在现有 worktree 之间移动 Session。移除变更请求会追加一条 `dismiss` 记录,它的 toast 通过 `track` 提供“撤销”。 -面板还通过变更视图展示 Session 工作背后的变更;变更视图是本包的一个资源标签页类型。Remote 在宿主上把每个 diff 解析成文件与 hunk,因此浏览器无需补丁解析器即可绘制,每次读取都受 `maxDiffBytes` 与 `maxUntrackedFiles` 约束。本地变更来自 Session 执行环境中受限的 `git diff`,范围由用户选择:默认是分支相对于分叉点的变更,也可以是未提交、未暂存或已暂存的变更;未跟踪文件经 Session 的文件系统读取,显示为新文件。变更请求的变更来自代码托管平台,取自绑定最新状态中的 head,经 forge seam 新增的两个提供方读取操作 `diff` 与 `fileText` 获得。Host 为每个变更请求保留最近读到的补丁,按 head 提交与目标分支区分,总量受 `maxCachedDiffBytes` 约束,因此在同一 head 下重新打开、刷新与导航都不会再次下载;托管平台或提供方因结果超过其大小上限而拒绝时报告 forge 失败 `too-large`,视图随之提供变更请求的网页而不是重试。hunk 之间未变更的行从文件的新版本展开,即工作树、暂存区或 head 提交,并且只在该文本仍与 hunk 吻合时展开。每次检查还会为变更卡片统计分支的变更规模;没有打开中的变更请求以当前检出分支为源分支时才显示该卡片。卡片上的“创建变更请求”向 Session 发送一条用户消息,由 Agent 用自己的工具创建变更请求,绑定像其他变更请求一样来自 `gh pr create`。 +面板还通过变更视图展示 Session 工作背后的变更;变更视图是本包的一个资源标签页类型。Remote 在宿主上把每个 diff 解析成文件与 hunk,因此浏览器无需补丁解析器即可绘制,每次读取都受 `maxDiffBytes` 与 `maxUntrackedFiles` 约束。本地变更来自使用 Session 权限与执行环境的 `git diff`,范围由用户选择:默认是分支相对于分叉点的变更,也可以是未提交、未暂存或已暂存的变更;未跟踪文件经 Session 的文件系统读取,显示为新文件。变更请求的变更来自代码托管平台,取自绑定最新状态中的 head,经 forge seam 新增的两个提供方读取操作 `diff` 与 `fileText` 获得。Host 为每个变更请求保留最近读到的补丁,按 head 提交与目标分支区分,总量受 `maxCachedDiffBytes` 约束,因此在同一 head 下重新打开、刷新与导航都不会再次下载;托管平台或提供方因结果超过其大小上限而拒绝时报告 forge 失败 `too-large`,视图随之提供变更请求的网页而不是重试。hunk 之间未变更的行从文件的新版本展开,即工作树、暂存区或 head 提交,并且只在该文本仍与 hunk 吻合时展开。每次检查还会为变更卡片统计分支的变更规模;没有打开中的变更请求以当前检出分支为源分支时才显示该卡片。卡片上的“创建变更请求”向 Session 发送一条用户消息,由 Agent 用自己的工具创建变更请求,绑定像其他变更请求一样来自 `gh pr create`。 评审评论在用户选择代码时固定文件、侧、行范围、完整 hunk 与所评审的 head。Agent 引用进入既有输入框引用机制,由用户决定批量发送,发送后的消息记录模型实际收到的内容。GitHub 写入属于 forge 提供方的可选操作:预检核对当前 head,写入明确指向该提交;结果不明时阻止再次写入,直到用户核对。评审草稿与行内记录归浏览器页签实例所有,不进入 Session 日志,也不创建 GitHub 待提交评审。切换 Session 保留该实例;关闭时丢弃本地状态并拒绝迟到的写入结果。已发布的 GitHub 评论仍保留在外部平台。 @@ -89,4 +89,4 @@ Session 所在的 worktree 可能在 Session 之外被删除。每次检查都 ## Consequences -面板只在打开时显示当前状态;没有任何界面挂载时检查结束不会有通知。Session 之外的改动要等到刷新或下一个工具结果才会出现。只有一个远端时,每次检查最多在 Session 的执行环境中启动十一个短暂的 Git 进程;为寻找分叉点每多尝试一个远端,就多启动两个。只有在第一步之前提出请求的 Session 才会有 worktree,失败或被取消的尝试可能留下它的分支或检出。Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留,因此它的 worktree 在第一轮之内创建,已删除的 worktree 也不会被检查。消息等待期间,Agent 以空闲状态处于维护任务中:输入框不提供停止,等待 Agent 空闲的调用方也会一并等待。恢复会丢失从未提交的修改。要求合并队列的基准分支无法从面板合并。同时启用 Git Worktrees 时会存在两个互不影响的 worktree 服务;模型的工具看不到面板的服务。本地或变更请求的 diff 超过 `maxDiffBytes`,或被托管平台拒绝时,不显示任何文件。展开变更请求中未变更的行时,每个文件只从托管平台读取一次。 +面板只在打开时显示当前状态;没有任何界面挂载时检查结束不会有通知。Session 之外的改动要等到刷新或下一个工具结果才会出现。只有一个远端时,每次检查最多在 Session 的执行环境中启动十二个短暂的 Git 进程;为寻找分叉点每多尝试一个远端,就多启动两个。只有在第一步之前提出请求的 Session 才会有 worktree,失败或被取消的尝试可能留下它的分支或检出。Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留,因此它的 worktree 在第一轮之内创建,已删除的 worktree 也不会被检查。消息等待期间,Agent 以空闲状态处于维护任务中:输入框不提供停止,等待 Agent 空闲的调用方也会一并等待。恢复会丢失从未提交的修改。要求合并队列的基准分支无法从面板合并。同时启用 Git Worktrees 时会存在两个互不影响的 worktree 服务;模型的工具看不到面板的服务。本地或变更请求的 diff 超过 `maxDiffBytes`,或被托管平台拒绝时,不显示任何文件。展开变更请求中未变更的行时,每个文件只从托管平台读取一次。 diff --git a/.agents/skills/record-browser-gif/SKILL.md b/.agents/skills/record-browser-gif/SKILL.md index a16f8294e9..1fa60fcb4f 100644 --- a/.agents/skills/record-browser-gif/SKILL.md +++ b/.agents/skills/record-browser-gif/SKILL.md @@ -1,6 +1,6 @@ --- name: record-browser-gif -description: Record browser or Web UI interaction demos as optimized GIFs using the available browser-control workflow, optional Playwright Videos for higher capture frame rates, and deterministic encoding, then attach the GIF to a pull request with `gh --attach`, falling back to a dedicated assets branch where attach cannot apply. Use when asked to make, record, or generate a GIF that demonstrates a browser workflow, and for every pull request that changes product-user-visible GUI behavior, which MUST include a GIF recorded from the pull request's real server and model flow. +description: Record browser or Web UI interaction demos as optimized GIFs using the available browser-control workflow, optional Playwright Videos for higher capture frame rates, and deterministic encoding, then attach the GIF to a pull request with `gh --attach`; publication requires gh v2.99.0 or later, and a GIF over 5 MiB is split into parts. Use when asked to make, record, or generate a GIF that demonstrates a browser workflow, and for every pull request that changes product-user-visible GUI behavior, which MUST include a GIF recorded from the pull request's real server and model flow. --- # Record Browser GIF @@ -17,8 +17,8 @@ The recording itself is part of the evidence: use a real server booted from that ## Keep recording separate from publication -- Recording produces local video or screenshots and one `.gif` artifact only; it never mutates remote state. -- Publication — attaching the GIF to a pull request body with `gh --attach`, or pushing it to an assets branch and embedding its URL where attach cannot apply — is the separate final step, performed only when the task includes attaching the GIF to a pull request. It never touches the pull request's own branch. +- Recording produces local video or screenshots; encoding produces one `.gif` artifact, or its [numbered parts](#attach-with-gh) when it exceeds the 5 MiB limit. Neither mutates remote state. +- Publication — attaching the GIF to a pull request body with `gh --attach` — is the separate final step, performed only when the task includes attaching the GIF to a pull request. It never commits to any branch. - Preserve the requested recording conditions. A real-server or real-API demo must not use fixture queries, mock transports, synthetic event injection, or test-only hooks. If credentials or the server are unavailable, report that limitation instead of substituting a fixture. - Never read or expose credential values. Use the application's normal configuration path and a benign demonstration prompt. @@ -117,13 +117,15 @@ Encoder maintenance: run `python3 -m unittest discover -s "$GIF_SKILL_DIR/script Perform this step only when the task includes attaching the GIF to a pull request. -Never commit a GIF to the pull request's own branch or any branch that merges into a long-lived branch: binary media committed there bloats the repository history for every future clone. Prefer `gh --attach`, which uploads the GIF to GitHub and rewrites the body reference in one command, so no branch carries the media. +Never commit a GIF to the pull request's own branch or any other branch: every default clone and full-history fetch of the repository downloads media committed to any branch. Publish only with `gh --attach`, which uploads the GIF to GitHub and rewrites the body reference in one command, so no branch carries the media. ### Attach with gh -`gh --attach` requires `gh` v2.99.0 or later (`gh --version`), a repository on github.com — GitHub Enterprise Server is not supported — write access to the repository, and a GIF at or below 10 MB. Confirm the verified artifact fits that limit; when it does not, shrink it with `--max-width`, then `--colors` or `--fps`, before attaching. +Before attaching, check `gh --version`. `gh --attach` requires `gh` v2.99.0 or later, a repository on github.com — GitHub Enterprise Server is not supported — and write access to the repository. When `gh` is older than v2.99.0, stop and tell the developer to upgrade `gh` to v2.99.0 or later; keep the verified GIF for the retry, and do not install or upgrade `gh` without authorization. When any other requirement is unmet or the attach fails — authentication, write access, a repository outside github.com, or an upload error — stop and report it to the developer. Never publish the GIF any other way. -Write the GIF into the body file as an ordinary local-path reference, using the same path passed to `--attach`; `gh` rewrites the reference in place to the uploaded URL, keeping its position and alt text: +Publish GIFs at or below 5 MiB, the encoder's default `--max-bytes`. When the encoder rejects the output for size, shrink it with `--max-width`, then `--colors` or `--fps`. When the GIF still exceeds 5 MiB at readable text quality, split it instead: encode consecutive, non-overlapping intervals of the same evidence run into numbered parts that each pass the encoder's size check — `--start` and `--end` over the one video, or consecutive screenshot subsets selected with `--pattern` — and verify every part as an artifact. Beside each embed, state its position (such as `2/3`) and its source interval or frames. + +Write each GIF into the body file as an ordinary local-path reference, using the same path passed to `--attach`; `gh` rewrites each reference in place to its uploaded URL, keeping its position and alt text, so the order of references in the body sets the display order of split parts: ```markdown ![]() @@ -138,35 +140,8 @@ gh pr create --body-file --attach # new pull re gh pr edit --body-file --attach # existing pull request ``` -`--attach` is repeatable but refuses the same file twice. A GIF the body does not reference is appended at the end, where alt text set on the flag (`--attach '#'`) applies; a rewritten reference keeps the body's alt text. After attaching, re-read the demonstrated live head and require it to remain at that recorded commit. Re-read the live body and confirm the reference now points at the uploaded URL, render the body through GitHub's Markdown API and confirm the expected ``, and fetch the uploaded URL once to confirm `200` and `image/gif`. +`--attach` is repeatable but refuses the same file twice. Publish split parts in one `gh pr create` or `gh pr edit` with one `--attach` per part, so a single pair of live-head checks covers every part. A GIF the body does not reference is appended at the end, where alt text set on the flag (`--attach '#'`) applies; a rewritten reference keeps the body's alt text. After attaching, re-read the demonstrated live head and require it to remain at that recorded commit. Re-read the live body and confirm the reference now points at the uploaded URL, render the body through GitHub's Markdown API and confirm the expected ``, and fetch the uploaded URL once to confirm `200` and `image/gif`. -### Fall back to an assets branch +### Existing assets branches -Use the assets-branch workflow only when `gh --attach` cannot apply: the GIF still exceeds 10 MB, `gh` is older than v2.99.0, or the repository is not on github.com. GIFs then live on a dedicated orphan assets branch — a branch with no parent commit and nothing but media — and one assets branch serves a whole pull request series (named `-assets`; list existing ones with `git ls-remote --heads origin '*assets*'`). - -Before either workflow below pushes, verify that the assets branch contains media only and that the staged GIF's checksum matches the verified local artifact. - -For an existing assets branch, work in a shallow single-branch scratch clone so the publication cannot touch your working tree: - -```sh -git clone --branch --single-branch --depth 1 /tmp/assets-checkout -cp /absolute/path/to/demo.gif /tmp/assets-checkout/.gif -cd /tmp/assets-checkout -git add .gif -git commit -m "assets: gif (#)" -git push origin -``` - -For a new series, make a fresh shallow scratch clone (`git clone --depth 1 /tmp/assets-checkout`), create the orphan branch with `git switch --orphan `, then add the GIF, commit, and push the same way. - -After pushing, use authenticated GitHub API or raw requests to confirm the remote path, byte size, checksum, `200` response, and `image/gif` content type. An anonymous `404` does not disprove a private-repository asset; authenticate the verification instead. This proves the repository-member review path, not public availability. - -Immediately before editing the pull-request body, re-read the demonstrated pull request's live head and compare it with the commit recorded next to the GIF. Stop and re-record when it moved. After the edit, re-read the demonstrated live head and require it to remain at that recorded commit. Separately, render the body through GitHub's Markdown API and confirm that the expected `` is present. - -Embed the GIF in the pull request body with the raw blob URL; the `?raw=true` suffix is required, because the plain blob URL renders GitHub's file page instead of the image: - -```markdown -![](https://github.com///blob//.gif?raw=true) -``` - -Never delete or rewrite an assets branch, and never force-push it: merged pull request bodies reference its URLs forever. Append new commits only. +Earlier pull request bodies embed GIFs from orphan `*-assets` branches in this repository. Never add to, delete, rewrite, or force-push them: merged pull request bodies reference their URLs. diff --git a/.github/workflows/build-exe-for-python-sdk.yml b/.github/workflows/build-exe-for-python-sdk.yml index 6bcdbee5ac..35f5a33df1 100644 --- a/.github/workflows/build-exe-for-python-sdk.yml +++ b/.github/workflows/build-exe-for-python-sdk.yml @@ -337,7 +337,8 @@ jobs: smoke_python="$venv/bin/python" "$smoke_python" -m pip install \ "dist-python/$SDK_WHEEL" \ - "dist-python/$RUNTIME_WHEEL" + "dist-python/$RUNTIME_WHEEL" \ + 'pytest>=8.0' echo "python=$smoke_python" >> "$GITHUB_OUTPUT" - name: Install local SDK and runtime wheels into a clean venv (Windows) @@ -351,7 +352,7 @@ jobs: $venv = (& python -c 'import tempfile; print(tempfile.mkdtemp(prefix="dsh-sdk-smoke-"))').Trim() python -m venv $venv $smokePython = Join-Path $venv 'Scripts\python.exe' - & $smokePython -m pip install "dist-python/$env:SDK_WHEEL" "dist-python/$env:RUNTIME_WHEEL" + & $smokePython -m pip install "dist-python/$env:SDK_WHEEL" "dist-python/$env:RUNTIME_WHEEL" 'pytest>=8.0' if ($LASTEXITCODE -ne 0) { throw "Wheel installation failed with exit code $LASTEXITCODE" } "python=$smokePython" >> $env:GITHUB_OUTPUT @@ -382,6 +383,19 @@ jobs: Pop-Location } + - name: Run installed-wheel native command tests (POSIX) + if: runner.os != 'Windows' + run: >- + "${{ steps.smoke-venv-posix.outputs.python }}" -I + "$GITHUB_WORKSPACE/python/sdk/tests/run_installed_commands.py" + + - name: Run installed-wheel native command tests (Windows) + if: runner.os == 'Windows' + shell: pwsh + run: | + & "${{ steps.smoke-venv-windows.outputs.python }}" -I "$env:GITHUB_WORKSPACE\python\sdk\tests\run_installed_commands.py" + if ($LASTEXITCODE -ne 0) { throw "Installed-wheel native command tests failed with exit code $LASTEXITCODE" } + - name: Preflight installed-wheel real API test (POSIX) if: >- inputs.ci diff --git a/.github/workflows/cua-helper-package.yml b/.github/workflows/cua-helper-package.yml new file mode 100644 index 0000000000..20ecb7526f --- /dev/null +++ b/.github/workflows/cua-helper-package.yml @@ -0,0 +1,83 @@ +name: Package CUA helper · macOS + +on: + workflow_dispatch: + inputs: + source_ref: + description: '同仓库可信源码分支或 dsh-v* tag' + type: string + default: master + required: true + preset: + description: '机器上的签名配置' + type: choice + options: [test, production] + default: test + required: true + workflow_call: + inputs: + source_ref: + type: string + required: true + preset: + type: string + default: production + outputs: + artifact: + description: '包含两个架构的已签名、公证 helper 归档' + value: ${{ jobs.package.outputs.artifact }} + +permissions: + contents: read + +# Desktop uses the same keychain search list and optional system proxy transaction. +concurrency: + group: macos-desktop-package + cancel-in-progress: false + +jobs: + package: + runs-on: [self-hosted, macOS, ARM64, dsh-mac-package-trial] + timeout-minutes: 60 + outputs: + artifact: ${{ steps.artifact.outputs.name }} + env: + DSH_PACKAGING_PRESET: ${{ inputs.preset }} + DSH_TELEMETRY_DISABLED: '1' + PACKAGE_SOURCE_REF: ${{ inputs.source_ref }} + steps: + - uses: actions/checkout@v7.0.1 + with: + ref: ${{ inputs.source_ref }} + persist-credentials: false + clean: true + - name: Validate source selection + run: | + node -e 'const cp=require("node:child_process"); const fs=require("node:fs"); const ref=process.env.PACKAGE_SOURCE_REF; + if(ref.startsWith("refs/pull/") || /^[a-f0-9]{40}$/i.test(ref)) throw Error("Select a trusted repository branch or release tag"); + const tag=ref.replace(/^refs\/tags\//, ""); + if(tag.startsWith("dsh-v") && tag!=="dsh-v"+JSON.parse(fs.readFileSync("package.json","utf8")).version) throw Error("Release tag must match product version"); + if(!["test","production"].includes(process.env.DSH_PACKAGING_PRESET)) throw Error("Invalid preset");' + - uses: pnpm/action-setup@v5.0.0 + with: + dest: ${{ runner.temp }}/setup-pnpm-cua-${{ github.run_id }}-${{ github.run_attempt }} + - uses: actions/setup-node@v7.0.0 + with: + node-version: '24' + package-manager-cache: false + - name: Install locked dependencies + run: pnpm install --frozen-lockfile + - name: Build and verify notarized applications + run: | + mkdir -p dist + pnpm exec tsx scripts/cua-helper/package.ts --out dist/cua-helper + - name: Name retained artifact + id: artifact + run: echo "name=cua-helper-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" >> "$GITHUB_OUTPUT" + - uses: actions/upload-artifact@v7.0.1 + with: + name: ${{ steps.artifact.outputs.name }} + path: dist/cua-helper/* + if-no-files-found: error + compression-level: 0 + retention-days: 14 diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index c30d75af0d..eb7e3a5eef 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -8,6 +8,16 @@ name: Release publish (dsh) on: workflow_dispatch: inputs: + cua_run_id: + description: '已有 CUA 打包 run ID:留空重新打包;填写时复用同一源码和版本的已验证产物' + type: string + required: false + default: '' + cua_run_attempt: + description: 'CUA 打包 attempt:仅与 run ID 一起使用;留空选择最新一次,不回退到更早的成功构建' + type: string + required: false + default: '' skip-tag-check: description: Skip release tag validation for the selected ref; other publication checks still apply. type: boolean @@ -22,9 +32,23 @@ env: DSH_TELEMETRY_DISABLED: '1' jobs: + cua-helper: + if: (startsWith(github.ref, 'refs/tags/dsh-v') || inputs.skip-tag-check) && inputs.cua_run_id == '' && inputs.cua_run_attempt == '' + uses: ./.github/workflows/cua-helper-package.yml + with: + source_ref: ${{ github.ref }} + preset: production + pack: name: Pack npm tarballs + needs: cua-helper + if: >- + ${{ !cancelled() && (needs.cua-helper.result == 'success' + || (needs.cua-helper.result == 'skipped' && (inputs.cua_run_id != '' || inputs.cua_run_attempt != ''))) }} runs-on: ubuntu-24.04 + permissions: + contents: read + actions: read steps: # Complete history: the release scripts read tags. - uses: actions/checkout@v7.0.1 @@ -63,9 +87,49 @@ jobs: RELEASE_PUBLISH: 'true' run: pnpm run release:verify --family dsh ${{ inputs.skip-tag-check && '--skip-tag-check' || '' }} + - name: Select retained CUA helper + if: inputs.cua_run_id != '' || inputs.cua_run_attempt != '' + id: retained-cua + env: + GH_TOKEN: ${{ github.token }} + run: pnpm exec tsx scripts/cua-helper/select-artifact.ts + + - name: Download retained CUA helper + if: inputs.cua_run_id != '' || inputs.cua_run_attempt != '' + uses: actions/download-artifact@v8.0.1 + with: + artifact-ids: ${{ steps.retained-cua.outputs.artifact-id }} + run-id: ${{ inputs.cua_run_id }} + github-token: ${{ github.token }} + path: dist/cua-helper + - name: Build run: pnpm run build:official --serial + - name: Download freshly built CUA helper + if: inputs.cua_run_id == '' && inputs.cua_run_attempt == '' + uses: actions/download-artifact@v8.0.1 + with: + name: ${{ needs.cua-helper.outputs.artifact }} + path: dist/cua-helper + + - name: Stage verified native helper applications + run: | + mkdir dist/cua-helper/extracted + tar -xzf dist/cua-helper/cua-helper.tgz -C dist/cua-helper/extracted + pnpm exec tsx scripts/cua-helper/stage.ts --from dist/cua-helper/extracted + + - name: Record CUA source and publication retry instructions + env: + CUA_RUN_ID: ${{ inputs.cua_run_id || github.run_id }} + CUA_RUN_ATTEMPT: ${{ steps.retained-cua.outputs.attempt || github.run_attempt }} + run: | + { + printf 'CUA helper: run `%s`, attempt `%s`.\n\n' "$CUA_RUN_ID" "$CUA_RUN_ATTEMPT" + printf '%s\n\n' 'npm 部分发布失败时,只重跑 Publish to npm job,复用原 dsh-npm-tarballs;不要重跑全部 job。' + printf '若需新建发布运行,填写 `cua_run_id=%s`、`cua_run_attempt=%s`,并使用相同源码 commit 和版本。\n' "$CUA_RUN_ID" "$CUA_RUN_ATTEMPT" + } >> "$GITHUB_STEP_SUMMARY" + - name: Pack release tarballs run: pnpm run release:pack --family dsh --out dist/npm diff --git a/.github/workflows/windows-package.yml b/.github/workflows/windows-package.yml index cbb4fd2642..29229605de 100644 --- a/.github/workflows/windows-package.yml +++ b/.github/workflows/windows-package.yml @@ -53,11 +53,6 @@ on: type: string default: '' required: false - build_root: - description: '独立构建根目录:填写绝对路径,每次任务创建独立源码副本;留空使用 runner 工作区' - type: string - default: '' - required: false permissions: contents: read @@ -82,7 +77,6 @@ jobs: PACKAGE_TEST_RELEASE_ID: ${{ inputs.test_release_id }} PACKAGE_SIGNING: ${{ inputs.signing }} PACKAGE_CACHE_NAMESPACE: ${{ inputs.cache_namespace }} - PACKAGE_BUILD_ROOT: ${{ inputs.build_root }} PACKAGE_WINDOWS_COMPRESSION_LEVEL: ${{ inputs.compression_level }} steps: - name: Reset packaging checkout @@ -106,7 +100,7 @@ jobs: run: | $helpers = Join-Path $env:RUNNER_TEMP "packaging-helpers-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" New-Item -ItemType Directory -Path $helpers -ErrorAction Stop | Out-Null - foreach ($name in @('windows-packaging-priority.ps1', 'windows-build-workspace.mjs')) { + foreach ($name in @('windows-packaging-priority.ps1')) { Copy-Item -LiteralPath (Join-Path 'apps/desktop/scripts' $name) -Destination $helpers -ErrorAction Stop } "PACKAGE_CI_HELPERS=$helpers" >> $env:GITHUB_ENV @@ -140,17 +134,6 @@ jobs: - uses: actions/setup-node@v7.0.0 with: node-version: '24' - - name: Select packaging workspace - id: build_workspace - env: - PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} - run: | - if (!$env:PACKAGE_BUILD_ROOT) { - "directory=$env:GITHUB_WORKSPACE" >> $env:GITHUB_OUTPUT - } else { - node "$env:PACKAGE_CI_HELPERS/windows-build-workspace.mjs" - exit $LASTEXITCODE - } - name: Configure persistent pnpm store # PNPM_HOME belongs to this run; keep downloaded packages outside its temporary directory. env: @@ -167,7 +150,6 @@ jobs: "DSH_DESKTOP_PACKAGE_CACHE_DIR=$env:DSH_DESKTOP_PACKAGE_CACHE_DIR" >> $env:GITHUB_ENV "PNPM_CONFIG_STORE_DIR=$storeRoot" >> $env:GITHUB_ENV - name: Install locked dependencies - working-directory: ${{ steps.build_workspace.outputs.directory }} run: | & "$env:PACKAGE_CI_HELPERS/windows-packaging-priority.ps1" -BestEffort node -e "const os=require('node:os'); console.log(JSON.stringify({node:process.version,availableParallelism:os.availableParallelism(),logicalCpus:os.cpus().length,totalMemoryBytes:os.totalmem(),freeMemoryBytes:os.freemem()}))" @@ -178,12 +160,10 @@ jobs: exit $LASTEXITCODE - name: Validate preset and resolve build version id: settings - working-directory: ${{ steps.build_workspace.outputs.directory }} env: PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} run: node apps/desktop/scripts/prepare-windows-ci.mjs - name: Check packaging configuration and toolchain - working-directory: ${{ steps.build_workspace.outputs.directory }} env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} run: | @@ -192,23 +172,16 @@ jobs: pnpm @packageArgs exit $LASTEXITCODE - name: Build installer and verify packaged runtime - working-directory: ${{ steps.build_workspace.outputs.directory }} env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} - PACKAGE_BUILD_TEMP: ${{ steps.build_workspace.outputs.temporaryDirectory }} run: | & "$env:PACKAGE_CI_HELPERS/windows-packaging-priority.ps1" -BestEffort - if ($env:PACKAGE_BUILD_TEMP) { - $env:TEMP = $env:PACKAGE_BUILD_TEMP - $env:TMP = $env:PACKAGE_BUILD_TEMP - } $packageArgs = @('run', 'package:desktop:win:x64', '--build-version', $env:PACKAGE_VERSION) if ($env:PACKAGE_SIGNING -eq 'unsigned') { $packageArgs += '--unsigned' } pnpm @packageArgs exit $LASTEXITCODE - name: Retain complete package outside the checkout id: retained - working-directory: ${{ steps.build_workspace.outputs.directory }} env: PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} PACKAGE_VERSION: ${{ steps.settings.outputs.version }} @@ -219,7 +192,7 @@ jobs: with: name: windows-package-logs-${{ github.run_id }}-${{ github.run_attempt }} include-hidden-files: true - path: ${{ steps.build_workspace.outputs.directory || github.workspace }}/apps/desktop/.desktop-build/packaging-runs/ + path: ${{ github.workspace }}/apps/desktop/.desktop-build/packaging-runs/ if-no-files-found: warn retention-days: 14 - name: Retain verified unsigned installer @@ -242,8 +215,3 @@ jobs: path: ${{ steps.retained.outputs.directory }}/* if-no-files-found: error retention-days: 14 - - name: Remove isolated packaging workspace - if: success() && inputs.build_root != '' - env: - PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} - run: node "$env:PACKAGE_CI_HELPERS/windows-build-workspace.mjs" --remove diff --git a/.gitignore b/.gitignore index 3cb86ce87d..4d52487a06 100644 --- a/.gitignore +++ b/.gitignore @@ -47,3 +47,6 @@ worktrees/ .agents/worktrees/ .typert-*/ native/system/test/bin/ + +# Generated company-signed CUA release record. +/packages/experimental/cua-macos/cua-helper.json diff --git a/apps/cli/package.json b/apps/cli/package.json index a77b89b9f2..463f4f1b9e 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -107,7 +107,6 @@ "@deepseek-ai/dsh-experimental-liveshare": "workspace:*", "@deepseek-ai/dsh-experimental-session-search": "workspace:*", "@deepseek-ai/dsh-experimental-tool-worktree": "workspace:*", - "@deepseek-ai/dsh-cua-bundle": "workspace:*", "@deepseek-ai/dsh-experimental-plugin-market-bundle": "workspace:*", "@deepseek-ai/dsh-personalized-recommendations": "workspace:*", "@deepseek-ai/dsh-experimental-forge-bundle": "workspace:*" diff --git a/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts b/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts new file mode 100644 index 0000000000..480ffe2032 --- /dev/null +++ b/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts @@ -0,0 +1,162 @@ +/** + * Keyless comparison of actual SDK and Desktop/Web step-admitted tool sets. + * Keep intentional differences in tool-parity.ts; unused exceptions fail. + * Team mode is excluded while its known composition mismatch is tracked in #7172. + * SDK minimal, Creator-only tools, graphical context and optional runtime payloads + * are outside this fixed standard/PTC, top-level-session comparison. + */ +import { createServer } from 'node:http' +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { execa } from 'execa' +import { z } from 'zod' +import { DeepSeekHarness } from '@deepseek-ai/dsh-sdk-client' +import { expect, it, type TestContext } from 'vitest' +import { profileEnvironment } from './fixtures/profile-environment.ts' +import { messagesResponse } from './fixtures/messages-response.ts' +import { assertToolParity, type ToolMode } from './tool-parity.ts' + +const repo = fileURLToPath(new URL('../../../../../', import.meta.url)) +const observer = new URL('./fixtures/tool-parity.mjs', import.meta.url).href +const probe = new URL('./fixtures/parity-probe.mjs', import.meta.url).href +const inventorySchema = z.object({ names: z.array(z.string()).min(1), hmr: z.boolean() }) +type Inventory = z.infer + +async function fixture(test: TestContext) { + const root = await mkdtemp(join(tmpdir(), 'sdk-desktop-tools-')) + const requests: { tools: { name: string }[] }[] = [] + const server = createServer((request, response) => { + let body = '' + request.setEncoding('utf8') + request.on('data', (chunk: string) => { body += chunk }) + request.on('end', () => { + requests.push(JSON.parse(body) as { tools: { name: string }[] }) + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.end(messagesResponse({ type: 'text', text: 'tools inspected' }, 'end_turn')) + }) + }) + test.onTestFinished(async () => { + try { + await new Promise((resolve, reject) => server.close((error) => { + if (error === undefined) resolve() + else reject(error) + })) + } + finally { await rm(root, { recursive: true, force: true }) } + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('model fixture has no TCP address') + const env = profileEnvironment(root, `http://127.0.0.1:${address.port}`) + + async function collect(side: 'sdk' | 'desktop', mode: ToolMode, mutations: object[] = []): Promise { + const cwd = await mkdtemp(join(root, `${side}-${mode}-`)) + const output = join(cwd, 'tools.json') + const patch = join(cwd, 'observer.patch.yml') + await writeFile(patch, JSON.stringify([ + { id: 'session-title-llm', disabled: true }, + { insert: [{ id: 'tool-parity-observer', name: observer, + config: { output, cwd, ...(side === 'desktop' ? { preset: mode } : {}) } }] }, + ...mutations, + ])) + const before = requests.length + let inventory: Inventory + if (side === 'sdk') { + const harness = new DeepSeekHarness({ + cwd, processCwd: cwd, dshHome: join(cwd, 'home'), env, model: 'deepseek-v4-pro', + patches: [...mode === 'ptc' ? [join(repo, 'apps/cli/config/examples/ptc.yml')] : [], patch], + }) + const abort = (): void => { void harness.close() } + test.signal.addEventListener('abort', abort, { once: true }) + try { + const result = await harness.session('tool-parity').run('Inspect tools') + expect(result.finalResponse).toBe('tools inspected') + inventory = inventorySchema.parse(JSON.parse(await readFile(output, 'utf8'))) + } finally { + await harness.close() + test.signal.removeEventListener('abort', abort) + } + expect(inventory.hmr).toBe(false) + } else { + const child = execa(process.execPath, [join(repo, 'apps/cli/lib/bin.js'), '--profile', 'web', + '--patch', patch, '--host', '127.0.0.1', '--port', '0', '--no-open'], { + cwd, env: { ...env, DSH_HOME: join(cwd, 'home') }, extendEnv: false, + ipc: true, stdin: 'ignore', reject: false, cancelSignal: test.signal, forceKillAfterDelay: 10_000, + }) + let stdout = '' + let stderr = '' + const ready = Promise.withResolvers() + child.stdout.on('data', (chunk: Buffer) => { + stdout += chunk.toString() + if (stdout.includes('dsh web: http://')) ready.resolve(true) + }) + child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() }) + void child.then((result) => { ready.reject(new Error(`Web exited: ${result.exitCode}\n${stderr}`)) }) + try { + await ready.promise + const reply = child.getOneMessage() + await child.sendMessage('collect-tool-parity') + const message = z.object({ result: inventorySchema.optional(), error: z.string().optional() }).parse(await reply) + if (message.error !== undefined) throw new Error(message.error) + inventory = inventorySchema.parse(message.result) + } catch (error) { + throw new Error(`Web collection failed\n${stdout}\n${stderr}`, { cause: error }) + } finally { + // Ask the CLI to drain on Windows too, where an OS signal kills immediately. + const watchdog = setTimeout(() => { child.kill('SIGKILL') }, 10_000) + try { + try { await child.sendMessage('stop-tool-parity') } + catch (_closedChannel: unknown) { + // A closed IPC channel cannot request graceful shutdown; fall back to the OS signal. + child.kill('SIGTERM') + } + const result = await child + expect(result.exitCode, result.stderr).toBe(0) + expect(result.signal, result.stderr).toBeUndefined() + } finally { clearTimeout(watchdog) } + } + expect(inventory.hmr).toBe(true) + } + expect(requests.length).toBeGreaterThan(before) + const presented = requests[before]!.tools.map(tool => tool.name).sort() + if (mode === 'ptc') expect(presented).toEqual(['run_code']) + else expect(presented).toEqual(inventory.names) + return inventory + } + return collect +} + +it.for(['standard', 'ptc'] as const)('compares the shipped %s tool sets and permits explicit opt-out', async (mode, test) => { + const collect = await fixture(test) + const sdk = await collect('sdk', mode) + const desktop = await collect('desktop', mode) + assertToolParity(mode, sdk.names, desktop.names) + expect(sdk.names).toContain('plugin_manager') + const optOut = await collect('sdk', mode, [{ id: 'tool-plugin-manager', disabled: true }]) + expect(optOut.names).not.toContain('plugin_manager') + expect(() => { assertToolParity(mode, optOut.names, desktop.names) }).toThrow( + mode === 'ptc' ? 'Stale exceptions: sdk:plugin_manager' : 'Missing from SDK: plugin_manager') +}) + +it.for(['standard', 'ptc'] as const)('detects missing shared tools in %s', async (mode, test) => { + const collect = await fixture(test) + const desktop = await collect('desktop', mode) + for (const [id, tool] of [['present', 'present'], ['tool-ask-user', 'ask_user_question'], ['tool-schedule', 'schedule_create']]) { + const missing = await collect('sdk', mode, [{ id, disabled: true }]) + expect(() => { assertToolParity(mode, missing.names, desktop.names) }).toThrow(new RegExp(`Missing from SDK:.*${tool}`)) + } +}) + +it.for(['standard', 'ptc'] as const)('detects one-sided additions in %s', async (mode, test) => { + const collect = await fixture(test) + const sdk = await collect('sdk', mode) + const desktop = await collect('desktop', mode) + const addition = [{ insert: [{ id: 'parity-probe', name: probe }] }] + const desktopExtra = await collect('desktop', mode, addition) + expect(() => { assertToolParity(mode, sdk.names, desktopExtra.names) }).toThrow('Missing from SDK: parity_probe') + const sdkExtra = await collect('sdk', mode, addition) + expect(() => { assertToolParity(mode, sdkExtra.names, desktop.names) }).toThrow('Only in SDK: parity_probe') + assertToolParity(mode, sdkExtra.names, desktopExtra.names) +}) diff --git a/apps/cli/tests/profiles/sdk/fixtures/parity-probe.mjs b/apps/cli/tests/profiles/sdk/fixtures/parity-probe.mjs new file mode 100644 index 0000000000..03596ae9bc --- /dev/null +++ b/apps/cli/tests/profiles/sdk/fixtures/parity-probe.mjs @@ -0,0 +1,12 @@ +/** A real extra registration used to detect one-sided profile additions. */ +import { defineTool } from '@deepseek-ai/dsh-tools' + +export const inject = ['tools'] + +export function apply(ctx) { + ctx.tools.register(defineTool({ + name: 'parity_probe', description: 'Test profile addition.', parameters: {}, + output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] }, + async execute() { return 'probe' }, + })) +} diff --git a/apps/cli/tests/profiles/sdk/fixtures/profile-environment.ts b/apps/cli/tests/profiles/sdk/fixtures/profile-environment.ts new file mode 100644 index 0000000000..c520b3c0ff --- /dev/null +++ b/apps/cli/tests/profiles/sdk/fixtures/profile-environment.ts @@ -0,0 +1,15 @@ +import { join } from 'node:path' +import { clearAmbientProxyEnv } from '../../../../../../scripts/test-proxy-environment.ts' + +/** Isolate SDK profile processes from ambient profile, runtime and Node loader settings. */ +export function profileEnvironment(root: string, baseUrl: string): NodeJS.ProcessEnv { + const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('DSH_'))) + Object.assign(env, { + DSH_PERMISSION_MODE: 'danger-full-access', DSH_TELEMETRY_DISABLED: '1', + DSH_AGENTS_HOME: join(root, 'agents'), DSH_PRIMARY_RUNTIME: '', + DEEPSEEK_API_KEY: 'keyless-profile-test', DEEPSEEK_BASE_URL: baseUrl, + NODE_OPTIONS: '', NODE_PATH: '', + }) + clearAmbientProxyEnv(env) + return env +} diff --git a/apps/cli/tests/profiles/sdk/fixtures/tool-parity.mjs b/apps/cli/tests/profiles/sdk/fixtures/tool-parity.mjs new file mode 100644 index 0000000000..69e1fbde57 --- /dev/null +++ b/apps/cli/tests/profiles/sdk/fixtures/tool-parity.mjs @@ -0,0 +1,54 @@ +/** Observe step-admitted capabilities without changing either shipped tool executor. */ +import { writeFile } from 'node:fs/promises' +import { createUserMessage } from '@deepseek-ai/dsh-llm' + +export const inject = ['tools', 'agents', 'loader'] + +export function apply(ctx, config) { + let observed + ctx.on('system-prompt/assemble', async (_assembly, context, next) => { + if (context.toolSet !== undefined) { + observed = { + names: ctx.tools.definitions(context.scope, context.toolSet).map(tool => tool.name).sort(), + hmr: ctx.get('hmr') !== undefined, + } + await writeFile(config.output, JSON.stringify(observed)) + } + return next() + }) + if (config.preset === undefined) return + const receive = message => { + if (message === 'stop-tool-parity') { + // Run the CLI shutdown handler: Windows OS signals terminate before its cleanup. + process.emit('SIGTERM') + return + } + if (message !== 'collect-tool-parity') return + void collect().then( + result => process.send({ result }), + error => process.send({ error: String(error.stack ?? error) }), + ) + } + ctx.effect(() => { + process.on('message', receive) + return () => process.off('message', receive) + }) + async function collect() { + await ctx.loader.await() + const presets = ctx.get('agentPresets') + if (presets === undefined) throw new Error('Web tool parity requires the shipped presets') + const handle = await ctx.agents.create({ + sessionId: 'tool-parity', cwd: config.cwd, + agentOptions: { provider: 'deepseek-official', model: 'deepseek-v4-pro' }, + setup: scope => presets.mount(scope, config.preset).then(() => undefined), + }) + try { + handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Inspect tools' }], source: { kind: 'user' } })) + await handle.agent.whenIdle() + if (observed === undefined) throw new Error('Web did not assemble a model step') + return observed + } finally { + await handle.dispose() + } + } +} diff --git a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts index 6f8add8c49..bee0a10775 100644 --- a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts +++ b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts @@ -174,7 +174,7 @@ describe('Python SDK dsh profile keyless smoke', () => { expect(modelRequests[0]?.output_config).toEqual({ effort: 'max' }) expect(modelRequests[0]?.max_tokens).toBe(1234) const expectedTools = ['read', 'write', 'edit', 'web_fetch', 'web_search', 'subagent', 'subagent_fork', - 'present', 'ask_user_question', 'schedule_create', 'schedule_delete', 'schedule_list', 'schedule_update'] + 'present', 'ask_user_question', 'schedule_create', 'schedule_delete', 'schedule_list', 'schedule_update', 'plugin_manager'] const requestText = JSON.stringify(modelRequests[0]) if (ptc) { expect(toolNames).toEqual(['run_code']) diff --git a/apps/cli/tests/profiles/sdk/plugin-manager.expected.e2e.ts b/apps/cli/tests/profiles/sdk/plugin-manager.expected.e2e.ts new file mode 100644 index 0000000000..e27881ded0 --- /dev/null +++ b/apps/cli/tests/profiles/sdk/plugin-manager.expected.e2e.ts @@ -0,0 +1,176 @@ +/** SDK plugin management persists changes while the live stdio process keeps its original composition. */ +import { createServer } from 'node:http' +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { DeepSeekHarness } from '@deepseek-ai/dsh-sdk-client' +import { expect, it } from 'vitest' +import { z } from 'zod' +import { profileEnvironment } from './fixtures/profile-environment.ts' +import { messagesResponse } from './fixtures/messages-response.ts' + +it.for(['standard', 'ptc'] as const)('keeps %s plugin changes pending until the SDK runtime restarts', async (mode, test) => { + const root = await mkdtemp(join(tmpdir(), 'sdk-plugin-manager-')) + const requests: Record[] = [] + let phase: 'list' | 'set' | 'done' = 'list' + let changedAt = 0 + let fixtureError: unknown + const listPage = z.object({ + entries: z.array(z.object({ entryId: z.string(), moduleName: z.string() })), nextOffset: z.number().nullable(), + }) + const server = createServer((request, response) => { + let body = '' + request.setEncoding('utf8') + request.on('data', (chunk: string) => { body += chunk }) + request.on('end', () => { + let args: Record | undefined + try { + const current = JSON.parse(body) as Record + requests.push(current) + if (requests.length === 1) args = { action: 'list_plugins', limit: 100 } + else if (phase === 'list') { + const messages = current.messages as { content: { type: string; content?: { text: string }[] }[] }[] + const result = messages.flatMap(message => message.content).findLast(block => block.type === 'tool_result') + const page = listPage.parse(JSON.parse(result!.content![0]!.text)) + const row = page.entries.find(entry => entry.moduleName === '@deepseek-ai/dsh-tool-web') + if (row !== undefined) { + args = { action: 'set_plugin', target: row.entryId, enabled: false } + phase = 'set' + } else if (page.nextOffset !== null) args = { action: 'list_plugins', offset: page.nextOffset, limit: 100 } + else throw new Error('SDK plugin inventory omitted tool-web') + } else if (phase === 'set') { + changedAt = requests.length - 1 + phase = 'done' + } + } catch (error) { fixtureError = error } + const call = mode === 'ptc' + ? { type: 'tool_use', id: `manage-${requests.length}`, name: 'run_code', input: { + code: `return await tools.plugin_manager(${JSON.stringify(args)});`, description: 'Disable web tools after restart', + } } + : { type: 'tool_use', id: `manage-${requests.length}`, name: 'plugin_manager', input: args } + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.end(messagesResponse(args !== undefined ? call : { type: 'text', text: 'done' }, + args !== undefined ? 'tool_use' : 'end_turn')) + }) + }) + test.onTestFinished(async () => { + try { + await new Promise((resolve, reject) => server.close((error) => { + if (error === undefined) resolve() + else reject(error) + })) + } + finally { await rm(root, { recursive: true, force: true }) } + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('model fixture has no TCP address') + const env = profileEnvironment(root, `http://127.0.0.1:${address.port}`) + const options = { + cwd: root, processCwd: root, dshHome: join(root, 'home'), env, model: 'deepseek-v4-pro', + patches: mode === 'ptc' ? [fileURLToPath(new URL('../../../config/examples/ptc.yml', import.meta.url))] : [], + } + async function run(restarted: boolean): Promise { + const harness = new DeepSeekHarness(options) + const abort = (): void => { void harness.close() } + test.signal.addEventListener('abort', abort, { once: true }) + try { + const session = harness.session(restarted ? 'restarted' : 'original') + expect((await session.run('Disable web tools after restart')).finalResponse).toBe('done') + if (!restarted) { + expect((await session.run('Continue on the same connection')).finalResponse).toBe('done') + } + } finally { + await harness.close() + test.signal.removeEventListener('abort', abort) + } + } + const advertises = (request: Record, name: string): boolean => mode === 'ptc' + ? JSON.stringify(request.system).includes(`${name}:`) + : (request.tools as { name: string }[]).some(tool => tool.name === name) + await run(false) + expect(fixtureError).toBeUndefined() + expect(changedAt).toBeGreaterThan(0) + expect(advertises(requests[0]!, 'plugin_manager')).toBe(true) + expect(JSON.stringify(requests[changedAt]!.messages)).toContain('restart-required') + expect(JSON.stringify(requests[changedAt]!.messages)).toContain('no-hmr') + expect(JSON.stringify(requests[changedAt]!.messages)).toContain('restart DSH') + expect(advertises(requests.at(-1)!, 'web_fetch')).toBe(true) + const saved = await readFile(join(root, 'home/profiles/sdk/cordis.patch.yml'), 'utf8') + expect(saved).toContain('tool-web') + expect(saved).toContain('disabled: true') + await run(true) + expect(advertises(requests.at(-1)!, 'web_fetch')).toBe(false) + expect(advertises(requests.at(-1)!, 'plugin_manager')).toBe(true) +}) + +it.for(['unavailable', 'approved', 'missing-pnpm'] as const)('reports the %s plugin-management prerequisite', async (scenario, test) => { + const root = await mkdtemp(join(tmpdir(), 'sdk-plugin-prerequisite-')) + const requests: Record[] = [] + let fixtureError: unknown + const server = createServer((request, response) => { + let body = '' + request.setEncoding('utf8') + request.on('data', (chunk: string) => { body += chunk }) + request.on('end', () => { + try { requests.push(JSON.parse(body) as Record) } + catch (error) { fixtureError = error } + const args = scenario === 'missing-pnpm' + ? { action: 'install_bundle', target: '@deepseek-ai/dsh-subagent-codex' } + : { action: 'list_plugins', limit: 1 } + const call = { type: 'tool_use', id: 'prerequisite', name: 'plugin_manager', input: args } + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.end(messagesResponse(requests.length === 1 ? call : { type: 'text', text: 'done' }, + requests.length === 1 ? 'tool_use' : 'end_turn')) + }) + }) + test.onTestFinished(async () => { + try { await new Promise((resolve, reject) => server.close((error) => { if (error) reject(error); else resolve() })) } + finally { await rm(root, { recursive: true, force: true }) } + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('model fixture has no TCP address') + const env = profileEnvironment(root, `http://127.0.0.1:${address.port}`) + env.DSH_PERMISSION_MODE = scenario === 'missing-pnpm' ? 'danger-full-access' : 'workspace-write' + if (scenario === 'missing-pnpm') { + for (const key of Object.keys(env)) if (key.toLowerCase() === 'path') Reflect.deleteProperty(env, key) + env.PATH = root + } + const harness = new DeepSeekHarness({ cwd: root, processCwd: root, dshHome: join(root, 'home'), + env, model: 'deepseek-v4-pro', approvalRequests: scenario === 'approved' }) + let approvals = 0 + const abort = (): void => { void harness.close() } + test.signal.addEventListener('abort', abort, { once: true }) + try { + harness.client.start() + harness.client.onRequest(async (method) => { + expect(method).toBe('approval/request') + approvals++ + return { outcome: 'allowed-once' } + }) + expect((await harness.run('Check plugin prerequisites')).finalResponse).toBe('done') + expect(fixtureError).toBeUndefined() + const result = JSON.stringify(requests.at(-1)?.messages) + if (scenario === 'unavailable') expect(result).toContain('unavailable') + else if (scenario === 'missing-pnpm') { + const messages = requests.at(-1)!.messages as { content: { type: string; content?: { text: string }[] }[] }[] + const toolResult = messages.flatMap(message => message.content).findLast(block => block.type === 'tool_result') + const failure = z.object({ + changed: z.literal(false), application: z.literal('failed'), + packageResult: z.object({ exitCode: z.number(), output: z.string().min(1) }), + error: z.object({ code: z.literal('operation-error'), diagnostic: z.string().min(1) }), + }).parse(JSON.parse(toolResult!.content![0]!.text)) + // cmd.exe reports 1 for a missing command; POSIX spawn reports 127. + expect(failure.packageResult.exitCode).toBe(process.platform === 'win32' ? 1 : 127) + expect(failure.error.diagnostic).toContain('pnpm') + expect(failure.packageResult.output).toContain(failure.error.diagnostic) + } else { expect(approvals).toBe(1); expect(result).toContain('entries') } + const manifest = JSON.parse(await readFile(join(root, 'home/profiles/sdk/package.json'), 'utf8')) as { dependencies: object } + expect(Object.keys(manifest.dependencies ?? {})).toEqual([]) + } finally { + await harness.close() + test.signal.removeEventListener('abort', abort) + } +}) diff --git a/apps/cli/tests/profiles/sdk/schedule-resume.e2e.ts b/apps/cli/tests/profiles/sdk/schedule-resume.e2e.ts index f3efcf6dd1..d031001f95 100644 --- a/apps/cli/tests/profiles/sdk/schedule-resume.e2e.ts +++ b/apps/cli/tests/profiles/sdk/schedule-resume.e2e.ts @@ -56,7 +56,7 @@ it('delivers an overdue reminder with the SDK route and lets the client resume t model: 'deepseek-v4-pro', maxTokens: 5678, initializeTimeoutMs: 30_000, env: { ...env, DSH_TEST_SCHEDULE_NOW: String(Date.parse('2030-01-01T00:00:00Z')) } }) clients.push(first) - expect((await first.session('saved').run('Set a reminder')).finalResponse).toBe('ready') + expect(await first.session('saved').run('Set a reminder')).toMatchObject({ finalResponse: 'ready' }) expect(requests).toHaveLength(2) await first.close() restarting = true @@ -68,5 +68,5 @@ it('delivers an overdue reminder with the SDK route and lets the client resume t await vi.waitFor(() => { expect(restored).toHaveLength(1) }, { timeout: 30_000 }) expect(restored[0]).toMatchObject({ model: 'deepseek-v4-flash', max_tokens: 1234 }) const session = await second.resumeSession('saved') - expect((await session.run('Continue after the reminder')).finalResponse).toBe('ready') + expect(await session.run('Continue after the reminder')).toMatchObject({ finalResponse: 'ready' }) }) diff --git a/apps/cli/tests/profiles/sdk/tool-parity.spec.ts b/apps/cli/tests/profiles/sdk/tool-parity.spec.ts new file mode 100644 index 0000000000..7e3e5a8585 --- /dev/null +++ b/apps/cli/tests/profiles/sdk/tool-parity.spec.ts @@ -0,0 +1,26 @@ +/** Diagnostics and exact exception consumption for cross-profile tool comparison. */ +import { expect, it } from 'vitest' +import { assertToolParity } from './tool-parity.ts' + +it('accepts an exact directional exception and rejects it after the profiles converge', () => { + const exceptions = [{ tool: 'desktop_only', side: 'desktop' as const, reason: 'Requires a graphical client.' }] + expect(() => { assertToolParity('standard', ['read'], ['read', 'desktop_only'], exceptions) }).not.toThrow() + expect(() => { assertToolParity('standard', ['read'], ['read'], exceptions) }).toThrow('Stale exceptions: desktop:desktop_only') + expect(() => { assertToolParity('standard', ['read', 'desktop_only'], ['read'], exceptions) }).toThrow('Only in SDK: desktop_only') +}) + +it('reports unexpected differences in both directions without hiding shared additions', () => { + expect(() => { assertToolParity('standard', ['read', 'new_shared'], ['new_shared', 'read'], []) }).not.toThrow() + expect(() => { assertToolParity('ptc', ['read', 'sdk_extra'], ['read', 'present'], []) }).toThrow( + 'Missing from SDK: present\nOnly in SDK: sdk_extra', + ) +}) + +it('rejects empty observations, undocumented exceptions and duplicate exceptions', () => { + expect(() => { assertToolParity('standard', [], [], []) }).toThrow('Empty tool inventory') + expect(() => { assertToolParity('standard', ['read'], ['read'], [ + { tool: 'extra', side: 'sdk', reason: ' ' }, + ]) }).toThrow('requires a reason') + const exception = { tool: 'extra', side: 'sdk' as const, reason: 'Intentional.' } + expect(() => { assertToolParity('standard', ['read', 'extra'], ['read'], [exception, exception]) }).toThrow('Stale exceptions: sdk:extra') +}) diff --git a/apps/cli/tests/profiles/sdk/tool-parity.ts b/apps/cli/tests/profiles/sdk/tool-parity.ts new file mode 100644 index 0000000000..fce089fc02 --- /dev/null +++ b/apps/cli/tests/profiles/sdk/tool-parity.ts @@ -0,0 +1,53 @@ +/** Exact, directional exceptions to the shipped SDK/Desktop capability comparison. */ +export type ToolMode = 'standard' | 'ptc' + +interface Exception { + tool: string + side: 'sdk' | 'desktop' + reason: string +} + +/** Intentional product differences; obsolete entries fail alongside undeclared differences. */ +export const toolParityExceptions: Record = { + standard: [{ tool: 'list_subagent_models', side: 'desktop', + reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' }], + ptc: [ + { tool: 'list_subagent_models', side: 'desktop', + reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' }, + { tool: 'plugin_manager', side: 'sdk', + reason: 'SDK PTC changes are persisted for restart without replacing active bindings because HMR is disabled; Desktop PTC excludes management in its HMR-enabled preset.' }, + { tool: 'workflow', side: 'sdk', + reason: 'The SDK PTC overlay changes only the executor so existing base workflow callers keep working; Desktop PTC uses run_code orchestration and omits the separate workflow surface.' }, + ], +} + +/** + * Compare actual step-admitted sets, rejecting both drift and unused exceptions. + * @param mode - matching SDK executor and Desktop preset. + * @param sdk - SDK capability names. + * @param desktop - Desktop capability names. + * @param exceptions - exact one-sided product differences with their rationale. + */ +export function assertToolParity( + mode: ToolMode, sdk: readonly string[], desktop: readonly string[], + exceptions = toolParityExceptions[mode], +): void { + if (sdk.length === 0 || desktop.length === 0) throw new Error(`Empty tool inventory: ${mode}`) + const only = { + sdk: new Set(sdk.filter(name => !desktop.includes(name))), + desktop: new Set(desktop.filter(name => !sdk.includes(name))), + } + const stale: string[] = [] + for (const exception of exceptions) { + if (!exception.reason.trim()) throw new Error(`Tool exception requires a reason: ${exception.tool}`) + if (!only[exception.side].delete(exception.tool)) stale.push(`${exception.side}:${exception.tool}`) + } + if (only.sdk.size || only.desktop.size || stale.length) { + throw new Error([ + `SDK/Desktop tool mismatch: ${mode}`, + `Missing from SDK: ${[...only.desktop].sort().join(', ') || '(none)'}`, + `Only in SDK: ${[...only.sdk].sort().join(', ') || '(none)'}`, + `Stale exceptions: ${stale.sort().join(', ') || '(none)'}`, + ].join('\n')) + } +} diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index e7fced6b8e..3dfceaccd1 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -15,8 +15,8 @@ en: 127ea90553cb6af7 zh: 7b1c5aec8558c684 /deepseek-harness-desktop/application-overview: - en: b57525e17b9638ab - zh: 274fe8344f7c2202 + en: 1667e3d6ffddea4a + zh: 4661a42b9ef4f673 /deepseek-harness-desktop/terminal-command: en: 5f2d25a1d8472647 zh: 2acb5c5d7d1917e2 @@ -66,8 +66,8 @@ en: 182a9c6705213e13 zh: 681762f83490f4c6 /deepseek-harness-desktop/updates/local-updater-qualification: - en: 68ec2f8bd5763ea6 - zh: 23b932dfe8503602 + en: db5e898140a73d53 + zh: 80a9d58c74b4bb24 /deepseek-harness-desktop/low-level-development-overrides: en: 8264b135871e8978 zh: 0939aafb1b2961fc diff --git a/apps/desktop/README.md b/apps/desktop/README.md index f961a72a92..fe24b24568 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -53,7 +53,7 @@ A server-expired account credential returns to Welcome when no official API key Desktop microphone access is restricted to audio requests from the primary `dsh-app://app` frame. macOS uses system microphone authorization, a packaged usage description, and `com.apple.security.device.audio-input` in the main application and Helper signatures. -Press F12 (Fn+F12 on media-key keyboards), Command+Option+I on macOS, or Ctrl+Shift+I on Windows to toggle DevTools for the focused application page, including in packaged builds. These native shortcuts use hidden application-menu items. Update overlays and packaged embedded browser guests disable DevTools. +Press F12 (Fn+F12 on media-key keyboards), Command+Option+I on macOS, or Ctrl+Shift+I on Windows to toggle DevTools for the focused application page, including in packaged builds. The application menu shows a localized “Developer tools” command in a separate group before Hide and Quit (before Exit on Windows). Windows exposes it in the titlebar application popup; its hidden native application menu registers the shortcuts. macOS and Linux keep a hidden F12 shortcut alias in their application menus. Update overlays and packaged embedded browser guests disable DevTools. @@ -353,6 +353,8 @@ The command builds the Desktop shell and runs its coordinator with real Electron The downloaded bytes are inert, and the installation call is recorded rather than executed. The test substitutes browser opening and clipboard writing to avoid external navigation and clipboard changes. It does not boot the full product workspace, qualify a real installer or restart, verify publisher signatures, or exercise differential updates or macOS. Stalled policy requests, feed requests, and payload transfers exercise real deadlines and recovery. The actual ordinary dialog verifies isolated preload loading, card geometry, an unfiltered parent page, cancellation, task-warning choices, and explicit installation approval; account-row component tests provide separate evidence. The [local qualification decision](../../.agents/notes/implemented/testing/2026-09-10-desktop-local-updater-qualification.md) and [verification record](tests/README.md) preserve these limits; production release requirements remain unchanged. +Native original-file operations accept only the trusted application frame. Completion returns the destination path to that frame; revealing it uses the existing Host path-opening API without a separate reveal IPC or saved-file history. Downloads use Chromium’s URL download and native save-dialog APIs; `DSH_DESKTOP_FILE_DOWNLOAD_TIMEOUT_MS` bounds startup until Chromium creates the download (300000 ms); the native save dialog has no application deadline. Clipboard-only remote image reads omit credentials, validate every redirect, reject the application Host and its loopback aliases, stop on main-frame navigation, and use `DSH_DESKTOP_IMAGE_READ_TIMEOUT_MS` (30000 ms) and `DSH_DESKTOP_IMAGE_READ_MAX_BYTES` (67108864 bytes). Image copying uses the renderer Clipboard API after PNG conversion. Other reachable HTTP(S) destinations follow deployment network isolation. [File actions](../../packages/client/ui-file-actions/README.md) defines saving and clipboard behavior. + ## Low-level development overrides diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index a7500d5d28..933e329ce1 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -53,7 +53,7 @@ Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 桌面麦克风访问仅允许主 `dsh-app://app` 页面发起的音频请求。macOS 使用系统麦克风授权、随包用途说明,以及主应用与 Helper 签名中的 `com.apple.security.device.audio-input` 权限。 -按 F12(多媒体功能键键盘上为 Fn+F12)、macOS 的 Command+Option+I 或 Windows 的 Ctrl+Shift+I,可切换当前获得焦点的应用页面的 DevTools,打包版本同样支持。这些原生快捷键通过隐藏的应用菜单项注册。更新遮罩和打包版本的内嵌浏览器禁用 DevTools。 +按 F12(多媒体功能键键盘上为 Fn+F12)、macOS 的 Command+Option+I 或 Windows 的 Ctrl+Shift+I,可切换当前获得焦点的应用页面的 DevTools,打包版本同样支持。应用菜单在隐藏和退出命令之前的独立分组中显示本地化的“开发者工具”命令。Windows 在标题栏的应用弹出菜单中显示开关,通过隐藏的原生应用菜单注册快捷键;macOS 和 Linux 的应用菜单保留隐藏的 F12 快捷键别名。更新遮罩和打包版本的内嵌浏览器禁用 DevTools。 @@ -353,6 +353,8 @@ node apps/desktop/node_modules/pnpm/bin/pnpm.mjs --dir apps/desktop run test:upd 下载内容是不可执行的测试字节,安装调用仅记录而不执行。测试替换浏览器打开与剪贴板写入,避免外部导航和剪贴板修改。它不启动完整产品工作区,不验证真实安装器或重启,不验证发布者签名,也不覆盖差分更新或 macOS。停滞的策略请求、清单请求和负载传输会执行真实截止时间及恢复。真实常规弹窗验证隔离预加载、卡片尺寸、未施加模糊的父页面、取消、任务警告选项与显式安装批准;账户行组件测试另行提供证据。[本地验证决策](../../.agents/notes/implemented/testing/2026-09-10-desktop-local-updater-qualification.zh.md)和[验证记录](tests/README.zh.md)保留这些限制;生产发布要求保持不变。 +原生原始文件操作仅接受可信应用页面。完成后向该页面返回目标路径;显示位置复用现有 Host 路径打开 API,不提供独立 reveal IPC,也不保留已保存文件历史。下载使用 Chromium URL 下载和原生保存对话框 API;`DSH_DESKTOP_FILE_DOWNLOAD_TIMEOUT_MS` 限定 Chromium 创建下载前的启动期限(300000 毫秒),不限制原生保存对话框的停留时间。仅剪贴板使用的远程图片读取不携带凭据,逐次校验重定向,拒绝应用 Host 及其回环别名,在主框架导航时终止,并使用 `DSH_DESKTOP_IMAGE_READ_TIMEOUT_MS`(30000 毫秒)与 `DSH_DESKTOP_IMAGE_READ_MAX_BYTES`(67108864 字节)。图片复制在转换为 PNG 后使用渲染进程的 Clipboard API。其他可达的 HTTP(S) 目标遵循部署侧网络隔离。[文件操作](../../packages/client/ui-file-actions/README.zh.md) 定义保存和剪贴板行为。 + ## 底层开发覆盖项 diff --git a/apps/desktop/config/publishing/macos/production.json.example b/apps/desktop/config/publishing/macos/production.json.example new file mode 100644 index 0000000000..cb7f67a0a4 --- /dev/null +++ b/apps/desktop/config/publishing/macos/production.json.example @@ -0,0 +1,13 @@ +{ + "bucket": "replace-with-bucket-1250000000", + "origin": "https://download.deepseek.com", + "credentialsFile": "/absolute/path/to/packaging/secrets/cos-production.json", + "macOS": { + "signingIdentity": "REPLACE_WITH_DEVELOPER_ID_APPLICATION_IDENTITY", + "teamId": "XXXXXXXXXX" + }, + "githubApp": { + "clientId": "REPLACE_WITH_GITHUB_APP_CLIENT_ID", + "privateKeyFile": "/absolute/path/to/packaging/publishing/keys/desktop-release-tagger.pem" + } +} diff --git a/apps/desktop/config/publishing/macos/test.json.example b/apps/desktop/config/publishing/macos/test.json.example new file mode 100644 index 0000000000..6981a88c6b --- /dev/null +++ b/apps/desktop/config/publishing/macos/test.json.example @@ -0,0 +1,9 @@ +{ + "bucket": "replace-with-bucket-1250000000", + "origin": "https://download-test.example.com", + "credentialsFile": "/absolute/path/to/packaging/secrets/cos-test.json", + "macOS": { + "signingIdentity": "REPLACE_WITH_DEVELOPER_ID_APPLICATION_IDENTITY", + "teamId": "XXXXXXXXXX" + } +} diff --git a/apps/desktop/config/publishing/windows/production.json.example b/apps/desktop/config/publishing/windows/production.json.example new file mode 100644 index 0000000000..9a2a743227 --- /dev/null +++ b/apps/desktop/config/publishing/windows/production.json.example @@ -0,0 +1,12 @@ +{ + "bucket": "replace-with-bucket-1250000000", + "origin": "https://download.deepseek.com", + "credentialsFile": "C:/absolute/path/to/packaging/secrets/cos-production.json", + "windows": { + "certificateThumbprint": "0000000000000000000000000000000000000000" + }, + "githubApp": { + "clientId": "REPLACE_WITH_GITHUB_APP_CLIENT_ID", + "privateKeyFile": "C:/absolute/path/to/packaging/publishing/keys/desktop-release-tagger.pem" + } +} diff --git a/apps/desktop/config/publishing/windows/test.json.example b/apps/desktop/config/publishing/windows/test.json.example new file mode 100644 index 0000000000..cf3e1a40a1 --- /dev/null +++ b/apps/desktop/config/publishing/windows/test.json.example @@ -0,0 +1,8 @@ +{ + "bucket": "replace-with-bucket-1250000000", + "origin": "https://download-test.example.com", + "credentialsFile": "C:/absolute/path/to/packaging/secrets/cos-test.json", + "windows": { + "certificateThumbprint": "0000000000000000000000000000000000000000" + } +} diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 081a90ead3..40bdfefe27 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -88,6 +88,7 @@ "@deepseek-ai/dsh-plugin-manager": "workspace:*", "zod": "4.4.3", "@deepseek-ai/dsh-util-file-drag": "workspace:*", + "@deepseek-ai/dsh-client-ui-file-actions": "workspace:*", "tencentcloud-sdk-nodejs-teo": "4.1.330" } } diff --git a/apps/desktop/packaging/README.i18n.yaml b/apps/desktop/packaging/README.i18n.yaml index b98c3d075f..c39bb71bc3 100644 --- a/apps/desktop/packaging/README.i18n.yaml +++ b/apps/desktop/packaging/README.i18n.yaml @@ -24,11 +24,11 @@ en: 5b4f0f80a117f202 zh: ff05be196c181087 /desktop-packaging/windows-actions-packaging: - en: 9dd2227f2878519e - zh: cd95dd6efd48298f + en: 253e17998951931c + zh: b582b377391d2ec2 /desktop-packaging/macos-self-hosted-packaging: - en: ee628e830d849ae9 - zh: 44313f5fb842f042 + en: f4cc5209bdaeefba + zh: 1db959d1ed345fcc /desktop-packaging/unsigned-windows-test-installer: en: f429bc0c280e2dfa zh: 4adbcc9e906bdf80 diff --git a/apps/desktop/packaging/README.md b/apps/desktop/packaging/README.md index 83a0e5a77b..28aa9ff9c7 100644 --- a/apps/desktop/packaging/README.md +++ b/apps/desktop/packaging/README.md @@ -115,11 +115,9 @@ Select the workflow in Actions, choose the source branch, preset, signing mode a Open the completed run in Actions and download its Artifacts. `windows-x64-signed---` and `windows-x64-unsigned---` contain the corresponding EXE; `windows-package-logs--` contains packaging diagnostics. The upload steps are `Retain verified signed installer`, `Retain verified unsigned installer`, and `Retain packaging diagnostics`; their step durations and timestamped logs show upload time. These artifacts are not a Release or download-site publication. -For path-sensitive Windows build measurements, `build_root` optionally selects an absolute directory outside existing Git checkouts. Each run clones the validated source commit into a new `windows-package--/source` directory; ignored files and previous build outputs are not copied. Only the packaging process uses a sibling run-owned `temp` directory through `TEMP` and `TMP`; Actions steps and post-job hooks retain their original temporary directories. Dependency and signing caches retain their existing locations. Successful runs remove only their owned checkout after artifact uploads, retrying transient filesystem failures up to three times with 100 ms increasing delays; persistent cleanup errors fail the Job and may leave a partially removed directory. Failed builds retain their checkout for inspection. Leave the input empty to build in the original Actions checkout. Include checkout creation and cleanup in the complete Job timing. - For cache measurements, `cache_namespace` selects a retained subdirectory for both dependency stores and upstream downloads; leave it empty for normal shared caches. Use a new name for a cold sample and repeat that name for warm samples. Names contain 1–64 lowercase letters, digits or hyphens, start with a letter or digit, and cannot be Windows device names. This does not reset the separate signature cache or OS file cache; report those states and Job start-to-completion time alongside phase timings and artifact size. Before dependency installation, the workflow records the Node version, available CPU parallelism, logical CPU count, and total/free memory. -The dependency-install and packaging steps normalize their own shell to normal CPU, I/O and memory priority before launching children. Priority and isolated-workspace helpers are copied from the exact workflow commit into a run-specific temporary directory, independently of the selected product source. Missing helpers stop CI setup; unavailable priority adjustment emits a warning and marks scheduling unsuitable for performance comparison, but does not stop packaging. This does not modify the runner task or other processes. Version, preset and retained-artifact adapters remain tied to product source and its formats. +The dependency-install and packaging steps normalize their own shell to normal CPU, I/O and memory priority before launching children. The priority helper is copied from the exact workflow commit into a run-specific temporary directory, independently of the selected product source. A missing helper stops CI setup; unavailable priority adjustment emits a warning and marks scheduling unsuitable for performance comparison, but does not stop packaging. This does not modify the runner task or other processes. Version, preset and retained-artifact adapters remain tied to product source and its formats. Installer uploads store the already-compressed release files without ZIP recompression; this preserves installer bytes and signatures. Diagnostic uploads retain their ordinary compression. @@ -129,13 +127,12 @@ Installer uploads store the already-compressed release files without ZIP recompr The [Apple Silicon workflow](../../../.github/workflows/macos-package.yml) and [Intel workflow](../../../.github/workflows/macos-intel-package.yml) produce separate arm64 and x64 packages on the Apple Silicon runner labeled `dsh-mac-package-trial`. Both share one concurrency group. The Intel workflow checks Rosetta execution before dependency installation; its selected source must include the target-aware macOS CI adapter. Both select `test` or `production` and use the existing signing, notarization and packaged-runtime checks. Successful DMG/ZIP files and diagnostic logs are retained for 14 days without publishing a release. Installer uploads disable redundant ZIP compression. The operator must verify a complete Actions run and installation on the target architecture before release qualification. The `compression_level` dropdown defaults to `3` and also offers `7`; it overrides the machine preset for this run and affects only ZIP and automatic-update downloads, not DMG. -All three platform forms put source, environment, update channel, version mode, manual version, test release ID and compression level first, with matching defaults. macOS notarization and Windows signing, cache measurement and isolated-workspace options follow these common fields. +All three platform forms put source, environment, update channel, version mode, manual version, test release ID and compression level first, with matching defaults. macOS notarization and Windows signing and cache measurement options follow these common fields. Run `node apps/desktop/scripts/setup-macos-packaging.mjs "$HOME/dsh-ci"` to prepare private `runner/`, `packaging/{presets,secrets,certificates}` and `cache/macos-signatures` directories without overwriting existing files; append `--check` to inspect them. Fill the [preset](../config/macos-packaging/test.env.example) and [signing](../config/macos-packaging/macos-signing.env.example) templates outside the checkout. Set secret and certificate files to mode `0600`. `DSH_PACKAGING_CONFIG_DIR` selects the absolute `packaging` directory and `DSH_PACKAGING_PRESET` selects its preset; missing files fail without falling back to `.env.macos`. Signed and preparation-only Mac builds read `secrets/macos-signing.env`; relative credential paths resolve beside that file. Public presets reject signing credentials, and signing files cannot override public settings. Local unsigned Mac builds retain their configuration-free behavior. Run `bash apps/desktop/scripts/start-macos-packaging-runner.sh "$HOME/dsh-ci/runner" "$HOME/dsh-ci/packaging" --check` to check the host tools and configuration files. The script selects the active Xcode and its macOS SDK together and compiles a small linker probe. After registration, omit `--check` to run in the foreground with a cleared inherited environment and prevent idle sleep while the runner is alive. Stop it with Ctrl-C before installing the service below. The runner owns its `_work` checkout, separate from daily development. The account can read its signing files, so run only trusted code. The existing notarization proxy restoration rules apply; after forced termination, inspect retained recovery records before another build. New setup templates set `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` to the absolute `cache/macos-signatures` directory outside checkout. For existing installations, rerun setup and add that field to each preset; existing files are preserved. This retains signatures across clean checkouts; cache verification and limits are described under [macOS signing](#macos-release-signing). - ZIP compression uses the same configured level with or without notarization; the App is assembled once, then DMG and ZIP are built separately so the ZIP setting does not change DMG compression. The `skip_notarization` workflow option defaults to `false`; the equivalent CLI flag is `--skip-notarization`. It retains Developer ID signing, DMG signature verification and packaged-runtime verification, but omits Apple notarization and stapling and does not require Apple notarization credentials. DMG/ZIP filenames carry `-unnotarized`, are stored under `.desktop-build/targets//unnotarized-artifacts/`, and are uploaded with an `unnotarized-debug` label. These artifacts are for internal debugging only: Gatekeeper may block downloaded copies, and they are not qualified for distribution or update publishing. No release completion record is written. The flag rejects unsigned, Windows and preparation-only builds. Install the user service from the checkout as the same account that registered the runner, without `sudo`: diff --git a/apps/desktop/packaging/README.zh.md b/apps/desktop/packaging/README.zh.md index 3868508c9e..2e87933826 100644 --- a/apps/desktop/packaging/README.zh.md +++ b/apps/desktop/packaging/README.zh.md @@ -115,11 +115,9 @@ runner 的受监督启动和恢复见 [Windows runner 机器准备](../windows-s 在 Actions 打开完成的运行并下载 Artifacts。`windows-x64-signed---` 与 `windows-x64-unsigned---` 包含对应 EXE;`windows-package-logs--` 包含打包诊断。上传步骤名为 `Retain verified signed installer`、`Retain verified unsigned installer` 和 `Retain packaging diagnostics`;步骤耗时与带时间戳的日志显示上传用时。这些产物不等于发布 Release 或下载站内容。 -测量 Windows 构建路径对性能的影响时,可用 `build_root` 指定现有 Git checkout 之外的绝对目录。每轮任务将已验证的源码提交克隆到新的 `windows-package--/source` 目录;不会复制忽略文件或此前的构建输出。仅打包进程通过 `TEMP` 和 `TMP` 使用同轮所属的同级 `temp` 目录;Actions 步骤及 Job 后置钩子保留原临时目录。依赖缓存和签名缓存沿用原有位置。成功任务在产物上传后仅删除本轮所属的 checkout,临时文件系统错误最多重试三次,等待时间按 100 ms 递增;持续清理失败会使 Job 失败,并可能留下部分删除的目录。构建失败时保留 checkout 供检查。输入留空时使用原 Actions checkout。完整 Job 耗时须包含 checkout 创建和清理。 - 测量缓存时,`cache_namespace` 为两个依赖 store 和上游下载选择保留的子目录;留空使用正常共享缓存。新名称用于冷缓存采样,再次使用同名用于热缓存采样。名称由 1–64 个小写字母、数字或连字符组成,以字母或数字开头,且不能为 Windows 设备名。这不会重置独立的签名缓存或操作系统文件缓存;应将其状态、Job 开始至完成的总耗时与阶段耗时和产物体积一并报告。workflow 在依赖安装前记录 Node 版本、可用 CPU 并行数、逻辑 CPU 数及总内存和空闲内存。 -依赖安装和打包步骤在启动子进程前,将自身 shell 的 CPU、I/O 和内存优先级调整为普通值。优先级及独立构建目录辅助脚本从 workflow 的精确提交复制到本轮临时目录,与选中的产品源码分离。缺失辅助脚本会终止 CI 准备;无法调整优先级时明确告警并标记调度条件不适合性能对比,但继续打包。这不会修改 runner 任务或其他进程。版本、preset 和产物留存适配器仍跟随产品源码及其格式。 +依赖安装和打包步骤在启动子进程前,将自身 shell 的 CPU、I/O 和内存优先级调整为普通值。优先级辅助脚本从 workflow 的精确提交复制到本轮临时目录,与选中的产品源码分离。缺失辅助脚本会终止 CI 准备;无法调整优先级时明确告警并标记调度条件不适合性能对比,但继续打包。这不会修改 runner 任务或其他进程。版本、preset 和产物留存适配器仍跟随产品源码及其格式。 安装器上传直接存储已经压缩的发布文件,不再进行 ZIP 二次压缩;安装器字节和签名保持不变。诊断日志上传保留通常的压缩方式。 @@ -129,13 +127,12 @@ runner 的受监督启动和恢复见 [Windows runner 机器准备](../windows-s [Apple Silicon 工作流](../../../.github/workflows/macos-package.yml)与 [Intel 工作流](../../../.github/workflows/macos-intel-package.yml)在带有 `dsh-mac-package-trial` 标签的 Apple Silicon runner 上分别生成 arm64 和 x64 安装包,两者共用一个并发组。Intel 工作流在安装依赖前检查 Rosetta 能否执行;所选源码必须包含按目标架构校验的 macOS CI 适配脚本。两者均选择 `test` 或 `production`,并复用现有签名、公证和打包运行时检查。成功的 DMG/ZIP 与诊断日志保留 14 天,不发布 release;安装包上传关闭重复 ZIP 压缩。操作人员须验收完整 Actions 运行及目标架构上的安装,才能确认可交付。`compression_level` 下拉选项默认为 `3`,也可选择 `7`;本次运行以该选项覆盖机器预设,只影响 ZIP 和自动升级下载,不影响 DMG。 -三个平台的表单均依次展示源码、环境、升级通道、版本模式、手动版本号、测试 release ID 和压缩等级,默认值一致。macOS 公证选项和 Windows 签名、缓存测量、独立构建目录选项位于公共字段之后。 +三个平台的表单均依次展示源码、环境、升级通道、版本模式、手动版本号、测试 release ID 和压缩等级,默认值一致。macOS 公证选项和 Windows 签名、缓存测量选项位于公共字段之后。 运行 `node apps/desktop/scripts/setup-macos-packaging.mjs "$HOME/dsh-ci"` 创建私有 `runner/`、`packaging/{presets,secrets,certificates}` 和 `cache/macos-signatures` 目录,不覆盖已有文件;追加 `--check` 仅检查。在 checkout 外填写 [preset](../config/macos-packaging/test.env.example) 和[签名](../config/macos-packaging/macos-signing.env.example)模板,将秘密和证书文件权限设为 `0600`。`DSH_PACKAGING_CONFIG_DIR` 指定 `packaging` 的绝对目录,`DSH_PACKAGING_PRESET` 选择其中的 preset;缺少文件立即失败,不回退到 `.env.macos`。Mac 签名和仅准备构建读取 `secrets/macos-signing.env`,相对凭据路径以该文件所在目录为基准。公开 preset 拒绝签名凭据,签名文件不能覆盖公开配置。本地未签名 Mac 构建保留无需配置的行为。 运行 `bash apps/desktop/scripts/start-macos-packaging-runner.sh "$HOME/dsh-ci/runner" "$HOME/dsh-ci/packaging" --check` 检查宿主工具和配置文件。脚本同时选择当前 Xcode 及其 macOS SDK,并编译小型链接探针。注册后省略 `--check`,清理继承环境并在前台启动 runner,存活期间阻止空闲睡眠。安装下方服务前,先用 Ctrl-C 停止。runner 拥有 `_work` 下的源码目录,与日常开发分开。该账户可读取签名文件,因此只执行可信代码。沿用现有公证代理恢复规则;强制终止后,先检查保留的恢复记录再构建。新建模板将 `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` 设为 checkout 外 `cache/macos-signatures` 的绝对路径。已有部署重新运行 setup 后,在各 preset 中补上该字段;已有文件保持不变。这样可跨干净检出保留签名;缓存验证和容量限制见 [macOS 签名](#macos-release-signing)。 - 无论是否公证,ZIP 都使用同一压缩配置;App 只组装一次,再分别生成 DMG 和 ZIP,确保 ZIP 设置不改变 DMG 压缩。工作流选项 `skip_notarization` 默认为 `false`;对应 CLI 参数是 `--skip-notarization`。该模式保留 Developer ID 签名、DMG 签名验证和打包运行时验证,跳过 Apple 公证和 stapling,不要求 Apple 公证凭据。DMG/ZIP 文件名带 `-unnotarized`,存放于 `.desktop-build/targets//unnotarized-artifacts/`,上传产物标为 `unnotarized-debug`。这些产物仅供内部调试:Gatekeeper 可能阻止下载副本运行,不能视为可分发包或用于更新发布。该模式不写入发布完成记录,不能与未签名、Windows 或仅准备构建组合。 在 checkout 中,以注册 runner 的同一账户安装用户服务,不使用 `sudo`: diff --git a/apps/desktop/publishing/ci/README.i18n.yaml b/apps/desktop/publishing/ci/README.i18n.yaml index d6940d4d14..14ef478ed7 100644 --- a/apps/desktop/publishing/ci/README.i18n.yaml +++ b/apps/desktop/publishing/ci/README.i18n.yaml @@ -21,14 +21,14 @@ en: 0478d8e35f9a3d55 zh: 0aa3fd828bc02691 /desktop-ci-publication/machine-setup: - en: 6e7b928af17f4377 - zh: 7c559078306df3fd + en: 0f43f2e193e95043 + zh: 1c1efb062c06f7b8 /desktop-ci-publication/package-and-publish: en: f7c12d343891e547 zh: da596ee1366c2046 /desktop-ci-publication/recovery-and-records: - en: 2e1e6b16d0d6bd41 - zh: 6ff4ad5a8f1f57b4 + en: b62a7484929f9941 + zh: c9dd06c77098e6ef /desktop-ci-publication/restore-a-channel: en: d82e2ccf70cce397 zh: d93dcb77cc4b463e diff --git a/apps/desktop/publishing/ci/README.md b/apps/desktop/publishing/ci/README.md index 02f1e1b6af..5009bf87e7 100644 --- a/apps/desktop/publishing/ci/README.md +++ b/apps/desktop/publishing/ci/README.md @@ -54,7 +54,9 @@ For a queued job, compare the job page's requested labels with **Settings → Ac Keep `DSH_PACKAGING_CONFIG_DIR` pointed at the existing machine packaging directory. Completed attempts are copied to its sibling `releases///`; `DSH_DESKTOP_RELEASES_DIR` overrides that root with an absolute path. The inventory includes installers, update archives, blockmaps, completion metadata and a credential-free manifest. Debug packages are retained but cannot publish. Copies are checked before the attempt directory becomes visible, and an existing attempt cannot be replaced. GitHub retains the same file inventory for 14 days. Local files remain until an operator removes them; do not delete an attempt while it is being verified or published. -Create `publishing/test.json` and, when authorized, `publishing/production.json` below the configuration directory. Each declares `bucket`, HTTPS `origin` without a path, and an absolute `credentialsFile`. The credential file contains only `secretId` and `secretKey`. macOS also requires `macOS.signingIdentity` and `macOS.teamId`; Windows requires `windows.certificateThumbprint`. Production requires the exact origin `https://download.deepseek.com` and `githubApp.clientId` plus an absolute `githubApp.privateKeyFile`. These files stay outside Git. The uploader supports permanent COS credentials, not STS session credentials. Administrators must keep test and production buckets unversioned (neither enabled nor suspended). Publication assumes this deployment prerequisite and does not call `GetBucketVersioning` or require its permission. Immutable binary PUTs retain `x-cos-forbid-overwrite`; their protection depends on administrators maintaining the bucket configuration. +Start from the [macOS test](../../config/publishing/macos/test.json.example), [macOS production](../../config/publishing/macos/production.json.example), [Windows test](../../config/publishing/windows/test.json.example), or [Windows production](../../config/publishing/windows/production.json.example) template. Create the `publishing/` directory and copy the selected file to `publishing/.json` below `DSH_PACKAGING_CONFIG_DIR`. Replace the example bucket, test origin, absolute paths, macOS signing identity and team ID or Windows certificate thumbprint, and production App client ID with the machine settings; keep the fixed production origin. Templates contain no credentials and do not grant COS, GitHub, or signing permissions. Store referenced secrets outside Git with access restricted to the publishing account. macOS uses the same configuration for arm64 and x64; the retained package determines the target. + +Each configuration declares `bucket`, HTTPS `origin` without a path, and an absolute `credentialsFile`. The credential file contains only `secretId` and `secretKey`. macOS also requires `macOS.signingIdentity` and `macOS.teamId`; Windows requires `windows.certificateThumbprint`. Production requires the exact origin `https://download.deepseek.com` and `githubApp.clientId` plus an absolute `githubApp.privateKeyFile`. The uploader supports permanent COS credentials, not STS session credentials. Administrators must keep test and production buckets unversioned (neither enabled nor suspended). Publication assumes this deployment prerequisite and does not call `GetBucketVersioning` or require its permission. Immutable binary PUTs retain `x-cos-forbid-overwrite`; their protection depends on administrators maintaining the bucket configuration. Set the repository variable `DESKTOP_PUBLISH_RUNNERS` to a JSON mapping of registered runner names to unique labels and targets, for example `{"mini":{"label":"dsh-mini-publish","target":["mac-arm64","mac-x64"]}}`. Assign that label to exactly that runner. A target may be a single name or a nonempty list; the Mac entry above authorizes both packaging workflows on the same machine. Windows uses target `win-x64`. The retained target must match the selected packaging workflow. The routing job checks the original successful job, and the publisher checks its own runner name against the recorded name. Machines need no shared filesystem or LAN connection to each other. @@ -82,7 +84,7 @@ After resolving a failure, re-run the failed publishing job to keep its prepared The sibling `upload-records/` directory retains an operation identity, newline-delimited events and terminal result. Feed-write intents retain both previous and requested YAML. Failures record their stage, safe error classification and diagnostic; COS failures also identify `GetObject` or `PutObject`, plus a validated HTTP status and request ID when available. Access-denied reports name the permission to inspect. Raw provider responses and credentials are excluded. Audit initialization becomes visible only after its files are complete; abandoned `.initializing-*` directories are not scanned for completed publication. Writes and readback are recorded before proceeding; missing terminal results mean interruption, not success. Actions also keeps its operation record as a diagnostic artifact for 30 days. These local records are not tamper-proof. COS readback verifies storage bytes, not public CDN behavior; public download acceptance is separate. -If the feed completed but tagging failed, the result is `published-tag-pending` and the job fails visibly. On retry, durable feed-completion evidence permits only tag recovery, even if a later release has advanced the channel. It never re-publishes old YAML. An existing conflicting tag requires administrator investigation and is never moved automatically. +If the feed completed but tagging failed, the result is `published-tag-pending` and the job fails visibly. On retry, durable feed-completion evidence permits only tag recovery, even if a later release has advanced the channel. It never re-publishes old YAML. An existing conflicting tag requires administrator investigation and is never moved automatically. A rejected tag creation retains its HTTP status and validated GitHub request ID; a follow-up lookup does not replace that failure with a missing-tag error. A repository-rule rejection directs the operator to the matching rulesets without logging the raw response. Normal publication and manual restoration acquire the same local channel lock. A crash can leave a lock directory under the sibling `publish-locks/`; verify no writer is running before manually removing it. A runner label alone does not coordinate writers on other machines. Keep one publishing machine per channel and preserve its records when migrating. diff --git a/apps/desktop/publishing/ci/README.zh.md b/apps/desktop/publishing/ci/README.zh.md index 3a635b5116..151032eed9 100644 --- a/apps/desktop/publishing/ci/README.zh.md +++ b/apps/desktop/publishing/ci/README.zh.md @@ -54,7 +54,9 @@ job 排队时,先对照 job 页面请求的标签与 **Settings → Actions 保持 `DSH_PACKAGING_CONFIG_DIR` 指向现有机器打包目录。完成的构建复制到其同级 `releases///`;`DSH_DESKTOP_RELEASES_DIR` 可用绝对路径覆盖该根目录。文件清单包含安装包、更新归档、blockmap、完成记录和不含凭据的 manifest。调试包会留存,但不能发布。复制内容通过校验后才开放 attempt 目录,已有 attempt 不能被替换。GitHub 保留相同文件清单 14 天。本地文件保留到操作员删除;校验或发布期间不要删除对应 attempt。 -在配置目录下创建 `publishing/test.json`,获得授权后再创建 `publishing/production.json`。每份配置声明 `bucket`、不带路径的 HTTPS `origin` 和绝对路径 `credentialsFile`。凭据文件只包含 `secretId` 和 `secretKey`。macOS 还需 `macOS.signingIdentity` 和 `macOS.teamId`;Windows 需要 `windows.certificateThumbprint`。production 必须使用 origin `https://download.deepseek.com`,并提供 `githubApp.clientId` 和绝对路径 `githubApp.privateKeyFile`。这些文件不进入 Git。上传器支持长期 COS 凭据,不支持 STS 会话凭据。管理员必须维持 test 和 production bucket 未启用版本控制(不能是已启用或已暂停状态)。发布流程以此为部署前提,不调用 `GetBucketVersioning`,也不要求该权限。二进制 PUT 仍携带 `x-cos-forbid-overwrite`;防覆盖保证依赖管理员维持桶配置。 +从 [macOS test](../../config/publishing/macos/test.json.example)、[macOS production](../../config/publishing/macos/production.json.example)、[Windows test](../../config/publishing/windows/test.json.example) 或 [Windows production](../../config/publishing/windows/production.json.example) 模板开始,创建 `publishing/` 目录,将所选文件复制到 `DSH_PACKAGING_CONFIG_DIR` 下的 `publishing/.json`。用机器实际配置替换示例 bucket、test origin、绝对路径、macOS 签名身份和 Team ID 或 Windows 证书指纹,以及 production App client ID;保留固定的 production origin。模板不含凭据,也不授予 COS、GitHub 或签名权限。引用的秘密文件保存在 Git 之外,只允许发布账户访问。macOS 的 arm64 和 x64 共用配置,目标由留存包决定。 + +每份配置声明 `bucket`、不带路径的 HTTPS `origin` 和绝对路径 `credentialsFile`。凭据文件只包含 `secretId` 和 `secretKey`。macOS 还需 `macOS.signingIdentity` 和 `macOS.teamId`;Windows 需要 `windows.certificateThumbprint`。production 必须使用 origin `https://download.deepseek.com`,并提供 `githubApp.clientId` 和绝对路径 `githubApp.privateKeyFile`。上传器支持长期 COS 凭据,不支持 STS 会话凭据。管理员必须维持 test 和 production bucket 未启用版本控制(不能是已启用或已暂停状态)。发布流程以此为部署前提,不调用 `GetBucketVersioning`,也不要求该权限。二进制 PUT 仍携带 `x-cos-forbid-overwrite`;防覆盖保证依赖管理员维持桶配置。 将仓库变量 `DESKTOP_PUBLISH_RUNNERS` 配置为已注册 runner 名称到唯一标签和目标的 JSON 映射,例如 `{"mini":{"label":"dsh-mini-publish","target":["mac-arm64","mac-x64"]}}`。该标签只能分配给这台 runner。目标可为单个名称或非空列表;上述 Mac 条目允许同一台机器处理两种架构的打包工作流。Windows 使用目标 `win-x64`。留存包的目标必须与所选打包工作流一致。路由 job 检查原构建成功的 job,发布器再检查自身 runner 名称与记录一致。机器之间不需要共享文件系统或局域网连接。 @@ -82,7 +84,7 @@ Environment 审批限制此工作流,不限制同一机器账户运行的任 同级 `upload-records/` 目录保留操作标识、逐行事件和最终结果。频道写入意图同时记录先前和目标 YAML。失败记录阶段、安全错误分类与诊断;COS 失败还标明 `GetObject` 或 `PutObject`,并在可用时记录经过校验的 HTTP 状态码和 request ID。访问拒绝提示会指出需检查的权限。不保存原始服务响应或凭据。审计初始化在文件完整后才可见;遗留的 `.initializing-*` 目录不参与已完成发布的扫描。写入和回读在继续操作前落盘;没有最终结果代表中断,不代表成功。Actions 还将操作记录保存为诊断 artifact,保留 30 天。这些本地记录不防篡改。COS 回读验证存储字节,不代表公开 CDN 行为;公开下载需单独验收。 -频道更新完成但 tag 失败时,结果为 `published-tag-pending`,job 明确失败。重试时,已落盘的频道完成证据只允许恢复 tag,即使后来发布已推进频道,也不会重新发布旧 YAML。已有冲突 tag 需要管理员调查,不会自动移动。 +频道更新完成但 tag 失败时,结果为 `published-tag-pending`,job 明确失败。重试时,已落盘的频道完成证据只允许恢复 tag,即使后来发布已推进频道,也不会重新发布旧 YAML。已有冲突 tag 需要管理员调查,不会自动移动。tag 创建被拒绝时保留其 HTTP 状态及经过校验的 GitHub request ID,后续查询不会用 tag 不存在的错误替换创建失败。仓库规则拒绝会提示操作人员检查匹配的 ruleset,不记录原始响应。 正常发布和手动恢复获取同一把本地频道锁。崩溃可能在同级 `publish-locks/` 下留下锁目录;手动删除前确认没有写入任务运行。runner 标签本身不能协调其他机器的写入。每个频道保持单一发布机器,迁移时保留记录。 diff --git a/apps/desktop/scripts/desktop-publish-tag.ts b/apps/desktop/scripts/desktop-publish-tag.ts index f47cc698a6..de60c03e84 100644 --- a/apps/desktop/scripts/desktop-publish-tag.ts +++ b/apps/desktop/scripts/desktop-publish-tag.ts @@ -40,8 +40,32 @@ export async function publishDesktopTag( body: JSON.stringify({ ref: `refs/tags/${tag}`, sha: commit }), redirect: 'error', signal: AbortSignal.timeout(30_000), }) if (response.status === 201) { await matches(response); return 'created' } - // A parallel platform release may have created the same version tag after our first read. - if (response.status === 422) { await response.body?.cancel(); await matches(await get()); return 'present' } + const requestId = response.headers.get('x-github-request-id') + const identity = requestId !== null && /^[A-Fa-f0-9:]{1,128}$/u.test(requestId) ? `; GitHub request ${requestId}` : '' + const failure = `desktop tag: creation failed (HTTP ${response.status}${identity})` + // A 422 can reject repository rules as well as report a concurrent tag creation. + if (response.status === 422) { + let detail: unknown + try { detail = await response.json() } catch (error) { + // Non-JSON error responses still retain the original HTTP status and request ID. + } + const rulesRejected = typeof detail === 'object' && detail !== null && 'message' in detail + && typeof detail.message === 'string' && detail.message.startsWith('Repository rule violations found') + const guidance = rulesRejected ? 'repository rules rejected tag creation; inspect the matching tag rulesets' + : 'inspect repository rule insights and App permissions before retrying' + let reconciled: Response + try { reconciled = await get() } catch (cause) { + throw new Error(`${failure}; follow-up tag lookup failed; ${guidance}`, { cause }) + } + if (!reconciled.ok) { + await reconciled.body?.cancel() + throw new Error(`${failure}; follow-up tag lookup returned HTTP ${reconciled.status}; ${guidance}`) + } + try { await matches(reconciled) } catch (cause) { + throw new Error(`${failure}; follow-up tag verification failed; inspect the existing tag before retrying`, { cause }) + } + return 'present' + } await response.body?.cancel() - throw new Error(`desktop tag: creation failed (HTTP ${response.status}); reconcile the tag before retrying`) + throw new Error(`${failure}; reconcile the tag before retrying`) } diff --git a/apps/desktop/scripts/windows-build-workspace.d.mts b/apps/desktop/scripts/windows-build-workspace.d.mts deleted file mode 100644 index 92f3a3c704..0000000000 --- a/apps/desktop/scripts/windows-build-workspace.d.mts +++ /dev/null @@ -1,19 +0,0 @@ -/** Identity of a Windows packaging run and its independent build root. */ -export interface WindowsBuildWorkspaceOptions { - sourceDirectory: string - buildRoot: string - runId: string - runAttempt: string - sourceSha: string -} -/** - * Clone the clean selected commit into a new run-owned directory. - * @param options - Original checkout and Actions run identity. - * @returns Checkout and temporary directory owned by this run. - */ -export function prepareWindowsBuildWorkspace(options: WindowsBuildWorkspaceOptions): { directory: string; temporaryDirectory: string } -/** - * Remove the directory only when its ownership record matches the run. - * @param options - Original checkout and Actions run identity. - */ -export function removeWindowsBuildWorkspace(options: WindowsBuildWorkspaceOptions): void diff --git a/apps/desktop/scripts/windows-build-workspace.mjs b/apps/desktop/scripts/windows-build-workspace.mjs deleted file mode 100644 index 977dda6618..0000000000 --- a/apps/desktop/scripts/windows-build-workspace.mjs +++ /dev/null @@ -1,96 +0,0 @@ -/** Create and remove a run-owned checkout for Windows packaging. */ -import { execFileSync } from 'node:child_process' -import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { dirname, isAbsolute, join, parse, resolve } from 'node:path' -import { pathToFileURL } from 'node:url' - -function assertUnlinkedAncestors(directory) { - for (let current = directory; ; current = dirname(current)) { - if (existsSync(current) && lstatSync(current).isSymbolicLink()) { - throw new Error('Packaging workspace ancestors must not be links') - } - if (dirname(current) === current) break - } -} - -function locations(options) { - const { buildRoot, runId, runAttempt, sourceSha } = options - if (!buildRoot || !isAbsolute(buildRoot) || /[\r\n\0]/.test(buildRoot)) { - throw new Error('Packaging build root must be a nonempty absolute directory') - } - const root = resolve(buildRoot) - if (root === parse(root).root) throw new Error('Packaging build root must not be a volume root') - if (!/^[1-9]\d*$/.test(runId) || !/^[1-9]\d*$/.test(runAttempt) || !/^[a-f0-9]{40}$/.test(sourceSha)) { - throw new Error('Packaging workspace requires a run identity and exact commit') - } - assertUnlinkedAncestors(root) - for (let current = root; ; current = dirname(current)) { - if (existsSync(join(current, '.git'))) throw new Error('Packaging build root must be outside existing Git checkouts') - if (dirname(current) === current) break - } - const owner = join(root, `windows-package-${runId}-${runAttempt}`) - assertUnlinkedAncestors(owner) - return { root, owner, directory: join(owner, 'source'), temporaryDirectory: join(owner, 'temp') } -} - -function git(directory, args) { - return execFileSync('git', args, { cwd: directory, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim() -} - -function ownership(options, paths) { - return JSON.stringify({ version: 1, root: paths.root, source: resolve(options.sourceDirectory), runId: options.runId, runAttempt: options.runAttempt, sourceSha: options.sourceSha }) -} - -/** - * Clone the validated commit into a new run-owned checkout; failures retain diagnostics. - * @param {{sourceDirectory: string, buildRoot: string, runId: string, runAttempt: string, sourceSha: string}} options - Source and run identity. - * @returns {{directory: string, temporaryDirectory: string}} Checkout and temporary directory owned by this run. - */ -export function prepareWindowsBuildWorkspace(options) { - const paths = locations(options) - if (git(options.sourceDirectory, ['rev-parse', 'HEAD']) !== options.sourceSha || git(options.sourceDirectory, ['status', '--porcelain'])) { - throw new Error('Packaging source must be clean and match the selected commit') - } - mkdirSync(paths.root, { recursive: true }) - mkdirSync(paths.owner) - writeFileSync(join(paths.owner, 'owner.json'), ownership(options, paths), { flag: 'wx' }) - mkdirSync(paths.temporaryDirectory) - git(paths.owner, ['clone', '--no-hardlinks', '--no-checkout', resolve(options.sourceDirectory), paths.directory]) - git(paths.directory, ['checkout', '--detach', options.sourceSha]) - if (git(paths.directory, ['rev-parse', 'HEAD']) !== options.sourceSha || git(paths.directory, ['status', '--porcelain'])) { - throw new Error('Isolated packaging checkout does not match the selected commit') - } - return { directory: paths.directory, temporaryDirectory: paths.temporaryDirectory } -} - -/** - * Remove only the matching run-owned directory after successful artifact upload. - * Transient filesystem failures retry up to three times; persistent failures propagate. - * @param {{sourceDirectory: string, buildRoot: string, runId: string, runAttempt: string, sourceSha: string}} options - Original source and run identity. - * @returns {void} - */ -export function removeWindowsBuildWorkspace(options) { - const paths = locations(options) - const marker = join(paths.owner, 'owner.json') - const stat = lstatSync(marker) - if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 8192 || readFileSync(marker, 'utf8') !== ownership(options, paths)) { - throw new Error('Packaging workspace ownership does not match this run') - } - rmSync(paths.owner, { recursive: true, maxRetries: 3, retryDelay: 100 }) -} - -if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { - const options = { - sourceDirectory: process.env.GITHUB_WORKSPACE ?? '', - buildRoot: process.env.PACKAGE_BUILD_ROOT ?? '', - runId: process.env.GITHUB_RUN_ID ?? '', - runAttempt: process.env.GITHUB_RUN_ATTEMPT ?? '', - sourceSha: process.env.PACKAGE_SOURCE_SHA ?? '', - } - if (process.argv[2] === '--remove') removeWindowsBuildWorkspace(options) - else { - if (process.argv.length !== 2 || !process.env.GITHUB_OUTPUT) throw new Error('Expected Actions output file and no arguments') - const result = prepareWindowsBuildWorkspace(options) - appendFileSync(process.env.GITHUB_OUTPUT, `directory=${result.directory}\ntemporaryDirectory=${result.temporaryDirectory}\n`) - } -} diff --git a/apps/desktop/src/file-actions.ts b/apps/desktop/src/file-actions.ts new file mode 100644 index 0000000000..45c4a25fc1 --- /dev/null +++ b/apps/desktop/src/file-actions.ts @@ -0,0 +1,192 @@ +/** Trusted-window Chromium downloads and clipboard fallback reads. */ +import { app, ipcMain, session } from 'electron' +import type { BrowserWindow, IpcMainInvokeEvent } from 'electron' +import { closeSync, openSync, rmSync } from 'node:fs' +import { extname, join } from 'node:path' +import { resolveDragFileName } from '@deepseek-ai/dsh-util-file-drag' +import { randomUUID } from 'node:crypto' +import type { FileSaveResult } from '@deepseek-ai/dsh-client-ui-file-actions/types' +import { DESKTOP_IPC } from './ipc.ts' +import { resolveDurationMs } from './duration-env.ts' + +/** @param value - untrusted IPC input. @returns captured URL and destination policy. */ +function saveRequest(value: unknown): { url: URL; name?: string; mediaType?: string; mode: 'download' | 'saveAs' } { + if (typeof value !== 'object' || value === null + || !('url' in value) || typeof value.url !== 'string' + || ('name' in value && typeof value.name !== 'string') + || ('mediaType' in value && typeof value.mediaType !== 'string') + || !('mode' in value) || (value.mode !== 'download' && value.mode !== 'saveAs')) throw new Error('Invalid file save request') + const url = new URL(value.url) + if (!['https:', 'http:', 'blob:', 'data:'].includes(url.protocol) || url.username || url.password) throw new Error('Unsupported file source') + return { url, mode: value.mode, + ...'name' in value ? { name: value.name as string } : {}, + ...'mediaType' in value ? { mediaType: value.mediaType as string } : {}, + } +} + +/** + * Install trusted-window original-file operations. + * @param assertOwner - rejects shell pages, subframes, and unowned windows. + * @param hostUrl - current application Host excluded from image reads. + */ +export function installFileActions( + assertOwner: (event: IpcMainInvokeEvent) => BrowserWindow, hostUrl: () => string | undefined = () => undefined, +): void { + const timeoutMs = resolveDurationMs(process.env, 'DSH_DESKTOP_IMAGE_READ_TIMEOUT_MS', 30_000) + const maxBytes = Number(process.env.DSH_DESKTOP_IMAGE_READ_MAX_BYTES ?? 64 * 1024 * 1024) + if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new Error('DSH_DESKTOP_IMAGE_READ_MAX_BYTES must be a positive integer') + const pending = new Map + finish: (result: FileSaveResult | Error) => void + started: () => void + item?: Electron.DownloadItem + }>() + session.defaultSession.on('will-download', (_event, item, contents) => { + const url = item.getURLChain()[0] + if (url === undefined || !new URL(url).hash.startsWith('#dsh-download=')) return + const entry = pending.get(url) + if (entry === undefined || entry.owner.webContents !== contents) { item.cancel(); return } + entry.started() + entry.item = item + let reserved: string | undefined + try { + assertOwner(entry.event) + const name = resolveDragFileName({ + name: entry.request.name ?? item.getFilename(), + mediaType: item.getMimeType() || entry.request.mediaType || '', + }) + let destination = join(app.getPath('downloads'), name) + if (entry.request.mode === 'saveAs') { + item.setSaveDialogOptions({ defaultPath: destination, properties: ['showOverwriteConfirmation', 'createDirectory'] }) + } else { + const extension = extname(destination) + const stem = destination.slice(0, destination.length - extension.length) + for (let index = 0; ; index++) { + destination = index === 0 ? `${stem}${extension}` : `${stem} (${index})${extension}` + try { closeSync(openSync(destination, 'wx')); break } + catch (error) { + if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'EEXIST') continue + throw error + } + } + reserved = destination + item.setSavePath(destination) + } + item.once('done', (_event, state) => { + try { + if (state !== 'completed') { + if (reserved !== undefined) rmSync(reserved, { force: true }) + entry.finish(state === 'cancelled' ? { status: 'cancelled' } : new Error('File download interrupted')) + return + } + if (!pending.has(url)) return + assertOwner(entry.event) + entry.finish({ status: 'saved', path: item.getSavePath() }) + } catch (error) { entry.finish(error instanceof Error ? error : new Error('File download unavailable')) } + }) + } catch (error) { + item.cancel() + try { if (reserved !== undefined) rmSync(reserved, { force: true }) } + catch (cleanupError) { + entry.finish(new AggregateError([error, cleanupError], 'File download failed and its partial file could not be removed')) + return + } + entry.finish(error instanceof Error ? error : new Error('File download unavailable')) + } + }) + const downloadTimeoutMs = resolveDurationMs(process.env, 'DSH_DESKTOP_FILE_DOWNLOAD_TIMEOUT_MS', 300_000) + ipcMain.handle(DESKTOP_IPC.fileSave, (event, value: unknown): Promise => { + const owner = assertOwner(event) + const request = saveRequest(value) + // Fragments do not change the fetched resource; each native request has its own completion identity. + request.url.hash = `dsh-download=${randomUUID()}` + const url = request.url.href + return new Promise((resolve, reject) => { + const contents = owner.webContents + const finish = (result: FileSaveResult | Error): void => { + if (!pending.delete(url)) return + clearTimeout(timer) + owner.removeListener('closed', cancel) + contents.removeListener('did-start-navigation', navigate) + if (result instanceof Error) reject(result) + else resolve(result) + } + const cancel = (): void => { + const item = pending.get(url)?.item + finish({ status: 'cancelled' }) + item?.cancel() + } + const navigate = (_event: Electron.Event, _url: string, inPlace: boolean, mainFrame: boolean): void => { + if (mainFrame && !inPlace) cancel() + } + const timer = setTimeout(() => { + const item = pending.get(url)?.item + finish(new Error('File download timed out')) + item?.cancel() + }, downloadTimeoutMs) + pending.set(url, { event, owner, request, finish, started: () => { clearTimeout(timer) } }) + owner.once('closed', cancel) + contents.on('did-start-navigation', navigate) + try { contents.downloadURL(url) } + catch (error) { finish(error instanceof Error ? error : new Error('File download unavailable')) } + }) + }) + ipcMain.handle(DESKTOP_IPC.clipboardImageRead, async (event, value: unknown) => { + const owner = assertOwner(event) + if (typeof value !== 'string') throw new Error('Invalid image URL') + const checkedUrl = (value: string): URL => { + const url = new URL(value) + const host = hostUrl() + const application = host === undefined ? undefined : new URL(host) + if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password + || application !== undefined && url.port === application.port + && (url.hostname === application.hostname || ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) { + throw new Error('Invalid image URL') + } + return url + } + let url = checkedUrl(value) + const contents = owner.webContents + const lifetime = new AbortController() + const abort = (): void => { lifetime.abort() } + owner.once('closed', abort) + const navigate = (_event: Electron.Event, _url: string, inPlace: boolean, mainFrame: boolean): void => { + if (mainFrame && !inPlace) abort() + } + contents.on('did-start-navigation', navigate) + try { + const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(timeoutMs)]) + let response: Response + for (let redirects = 0; ; redirects++) { + response = await fetch(url, { signal, redirect: 'manual', credentials: 'omit', referrerPolicy: 'no-referrer' }) + if (![301, 302, 303, 307, 308].includes(response.status)) break + await response.body?.cancel() + const location = response.headers.get('location') + if (redirects >= 20 || location === null) throw new Error('Invalid image redirect') + url = checkedUrl(new URL(location, url).href) + } + if (!response.ok) throw new Error('Original image unavailable') + const reader = response.body?.getReader() + if (reader === undefined) throw new Error('Original image unavailable') + const chunks: Uint8Array[] = [] + let size = 0 + try { + for (;;) { + const chunk = await reader.read() + if (chunk.done) break + size += chunk.value.byteLength + if (size > maxBytes) throw new Error('Original image exceeds the download limit') + chunks.push(chunk.value) + } + } finally { await reader.cancel(); reader.releaseLock() } + assertOwner(event) + lifetime.signal.throwIfAborted() + return { bytes: new Uint8Array(Buffer.concat(chunks)), mediaType: response.headers.get('content-type') ?? '' } + } finally { + owner.removeListener('closed', abort) + contents.removeListener('did-start-navigation', navigate) + } + }) +} diff --git a/apps/desktop/src/ipc.ts b/apps/desktop/src/ipc.ts index e62a84f0a1..a3c5f5d935 100644 --- a/apps/desktop/src/ipc.ts +++ b/apps/desktop/src/ipc.ts @@ -1,3 +1,4 @@ +import type { DesktopFileActions } from '@deepseek-ai/dsh-client-ui-file-actions/types' /** Typed preload operations exposed only by the Electron shell. */ import type { DesktopKeyboardApi, DesktopShortcutsApi } from '@deepseek-ai/dsh-client-shortcuts/protocol' @@ -7,6 +8,8 @@ import type { DesktopFileDrag } from '@deepseek-ai/dsh-util-file-drag' /** IPC channel names kept private to the desktop application bundle. */ export const DESKTOP_IPC = { + fileSave: 'dsh-desktop:file-save', + clipboardImageRead: 'dsh-desktop:clipboard-image-read', shortcutsInput: 'dsh-desktop:shortcuts-input', shortcutsCloseWindow: 'dsh-desktop:shortcuts-close-window', shortcutsGet: 'dsh-desktop:shortcuts-get', @@ -76,6 +79,7 @@ export interface DesktopUpdatePresentation { /** Product documents cannot supply update versions, package URLs, or installation authorization. */ export interface DshDesktopProductApi { + readonly fileActions: DesktopFileActions readonly protocolVersion: 1 readonly browser: DesktopBrowserBridge readonly fileDrag: DesktopFileDrag diff --git a/apps/desktop/src/locale.ts b/apps/desktop/src/locale.ts index 74a1f19941..f5d30b82ba 100644 --- a/apps/desktop/src/locale.ts +++ b/apps/desktop/src/locale.ts @@ -104,6 +104,7 @@ export const en = { welcomeContinueFailed: 'Could not open the workspace. Please try again.', checkUpdatesMenu: 'Check for Updates…', reloadPageMenu: 'Reload Page', + toggleDevToolsMenu: 'Developer tools', restartAppHostMenu: 'Restart App and Host', updateCheckFailedTitle: 'Update Check Failed', updateCheckFailed: 'Could not check for updates. Please try again later.', @@ -283,6 +284,7 @@ export const zh = { welcomeContinueFailed: '无法打开工作区,请重试。', checkUpdatesMenu: '检查更新…', reloadPageMenu: '刷新页面', + toggleDevToolsMenu: '开发者工具', restartAppHostMenu: '重启应用与 Host', updateCheckFailedTitle: '更新检查失败', updateCheckFailed: '检查更新失败,请稍后重试。', @@ -460,6 +462,7 @@ export const ja = { welcomeContinueFailed: 'ワークスペースを開けませんでした。もう一度お試しください。', checkUpdatesMenu: 'アップデートを確認…', reloadPageMenu: 'ページを再読み込み', + toggleDevToolsMenu: '開発者ツール', restartAppHostMenu: 'アプリとホストを再起動', updateCheckFailedTitle: 'アップデートの確認に失敗しました', updateCheckFailed: 'アップデートを確認できませんでした。後でもう一度お試しください。', @@ -637,6 +640,7 @@ export const es = { welcomeContinueFailed: 'No se pudo abrir el espacio de trabajo. Por favor inténtalo de nuevo.', checkUpdatesMenu: 'Buscar actualizaciones...', reloadPageMenu: 'Recargar página', + toggleDevToolsMenu: 'Herramientas de desarrollo', restartAppHostMenu: 'Reiniciar la aplicación y el host', updateCheckFailedTitle: 'Error en la comprobación de actualización', updateCheckFailed: 'No se pudo buscar actualizaciones. Inténtelo de nuevo más tarde.', @@ -814,6 +818,7 @@ export const fr = { welcomeContinueFailed: "Impossible d'ouvrir l'espace de travail. Veuillez réessayer.", checkUpdatesMenu: 'Vérifiez les mises à jour…', reloadPageMenu: 'Recharger la page', + toggleDevToolsMenu: 'Outils de développement', restartAppHostMenu: "Redémarrez l'application et l'hôte", updateCheckFailedTitle: 'Échec de la vérification de la mise à jour', updateCheckFailed: 'Impossible de vérifier les mises à jour. Veuillez réessayer plus tard.', @@ -991,6 +996,7 @@ export const de = { welcomeContinueFailed: 'Der Arbeitsbereich konnte nicht geöffnet werden. Bitte versuchen Sie es erneut.', checkUpdatesMenu: 'Nach Updates suchen…', reloadPageMenu: 'Seite neu laden', + toggleDevToolsMenu: 'Entwicklertools', restartAppHostMenu: 'Anwendung und Host neu starten', updateCheckFailedTitle: 'Update-Überprüfung fehlgeschlagen', updateCheckFailed: 'Es konnte nicht nach Updates gesucht werden. Bitte versuchen Sie es später noch einmal.', @@ -1168,6 +1174,7 @@ export const ru = { welcomeContinueFailed: 'Не удалось открыть рабочую область. Пожалуйста, попробуйте еще раз.', checkUpdatesMenu: 'Проверить наличие обновлений…', reloadPageMenu: 'Обновить страницу', + toggleDevToolsMenu: 'Инструменты разработчика', restartAppHostMenu: 'Перезапустите приложение и хост.', updateCheckFailedTitle: 'Проверка обновления не удалась', updateCheckFailed: 'Не удалось проверить наличие обновлений. Пожалуйста, повторите попытку позже.', @@ -1345,6 +1352,7 @@ export const pt = { welcomeContinueFailed: 'Não foi possível abrir o espaço de trabalho. Por favor, tente novamente.', checkUpdatesMenu: 'Verifique se há atualizações…', reloadPageMenu: 'Recarregar página', + toggleDevToolsMenu: 'Ferramentas do desenvolvedor', restartAppHostMenu: 'Reinicie o aplicativo e o host', updateCheckFailedTitle: 'Falha na verificação de atualização', updateCheckFailed: 'Não foi possível verificar se há atualizações. Por favor, tente novamente mais tarde.', diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 4770fe83bf..d8d0e30c4c 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -1,3 +1,4 @@ +import { installFileActions } from './file-actions.ts' import type { ProductEventMap, ProductEvent } from '@deepseek-ai/dsh-client-product-analytics/types' import { WINDOWS_TITLEBAR_HEIGHT } from './windows-layout.ts' /** Electron shell: desktop project ownership, custom protocol, windows, and lifecycle. */ @@ -826,6 +827,7 @@ async function main(): Promise { || !event.senderFrame.url.startsWith('dsh-app://app/')) throw new Error('Rejected Platform command') return owner } + installFileActions(assertMainApplication, () => hostUrl) ipcMain.on(PLATFORM_IPC.bootstrap, (event) => { try { event.returnValue = platformView.bootstrap(event) } catch { event.returnValue = null } @@ -1058,8 +1060,8 @@ async function main(): Promise { { label: currentDesktopLocale().messages.checkUpdatesMenu, click: () => { void openUpdatePrompt(true) } }, ...process.platform === 'darwin' || process.platform === 'win32' ? [{ label: currentDesktopLocale().messages.cliCommandMenu, click: () => { void commandManager.show() } }] : [], + { type: 'separator' }, ...development ? [ - { type: 'separator' as const }, { label: currentDesktopLocale().messages.reloadPageMenu, role: 'reload' as const }, { label: currentDesktopLocale().messages.restartAppHostMenu, click: () => { if (quitting) return @@ -1067,20 +1069,23 @@ async function main(): Promise { quitWithoutConfirmation() } }, ] : [], + { role: 'toggleDevTools', label: currentDesktopLocale().messages.toggleDevToolsMenu }, { type: 'separator' }, ...hideCommands, { role: 'quit', ...(darwin ? { label: currentDesktopLocale().messages.quitApplication } : process.platform === 'win32' ? { label: currentDesktopLocale().messages.exitApplication } : {}) }, ] - const devToolsItems: MenuItemConstructorOptions[] = [ + const devToolsF12Shortcut: MenuItemConstructorOptions = { role: 'toggleDevTools', visible: false, accelerator: 'F12' } + const windowsDevToolsShortcuts: MenuItemConstructorOptions[] = [ { role: 'toggleDevTools', visible: false }, - { role: 'toggleDevTools', visible: false, accelerator: 'F12' }, + devToolsF12Shortcut, ] const refreshApplicationMenu = (): void => { - Menu.setApplicationMenu(Menu.buildFromTemplate(process.platform === 'win32' ? devToolsItems : [{ - label: darwin ? app.name : currentDesktopLocale().messages.application, - submenu: [...applicationItems(), ...devToolsItems], - }, ...platformMenus()])) + Menu.setApplicationMenu(Menu.buildFromTemplate(process.platform === 'win32' + ? windowsDevToolsShortcuts : [{ + label: darwin ? app.name : currentDesktopLocale().messages.application, + submenu: [...applicationItems(), devToolsF12Shortcut], + }, ...platformMenus()])) tray?.relabel() } refreshApplicationMenu() diff --git a/apps/desktop/src/preload-app.ts b/apps/desktop/src/preload-app.ts index c9937a301e..26266b4f1c 100644 --- a/apps/desktop/src/preload-app.ts +++ b/apps/desktop/src/preload-app.ts @@ -1,3 +1,4 @@ +import type { FileSaveResult } from '@deepseek-ai/dsh-client-ui-file-actions/types' /** Origin-scoped boot, native directory selection, host paths of picked files, and update presentation with native confirmation actions. */ import type { DesktopShortcutInput, ShortcutConfigSnapshot, ShortcutSaveResult } from '@deepseek-ai/dsh-client-shortcuts/protocol' @@ -14,6 +15,11 @@ import type { FileDragHandle } from '@deepseek-ai/dsh-util-file-drag' function createProductApi(): DshDesktopProductApi { return { protocolVersion: 1, + fileActions: { + save: request => ipcRenderer.invoke(DESKTOP_IPC.fileSave, request) as Promise, + readClipboardImage: url => ipcRenderer.invoke(DESKTOP_IPC.clipboardImageRead, url) as + Promise<{ bytes: Uint8Array; mediaType: string }>, + }, browser: createDesktopBrowserBridge(), fileDrag: { prepare: (source, requestId) => ipcRenderer.invoke(DESKTOP_IPC.fileDragPrepare, source, requestId) as diff --git a/apps/desktop/tests/cua-optional-package.spec.ts b/apps/desktop/tests/cua-optional-package.spec.ts index a6b42cdcfd..85ef15f0ee 100644 --- a/apps/desktop/tests/cua-optional-package.spec.ts +++ b/apps/desktop/tests/cua-optional-package.spec.ts @@ -1,4 +1,4 @@ -/** Cold pnpm requests exercise shipped CUA dependency/platform metadata with inert package contents. */ +/** Cold pnpm requests exercise on-demand CUA dependency/platform metadata with inert package contents. */ import { createHash } from 'node:crypto' import { createServer } from 'node:http' import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' @@ -37,14 +37,14 @@ it('fetches the macOS optional tarball only for Darwin, with an empty cache for const cli = await readManifest('apps/cli') const bundle = await readManifest('packages/experimental/cua-bundle') const native = await readManifest('packages/experimental/cua-macos') - expect(cli.dependencies).toHaveProperty(bundleName) + expect(cli.dependencies).not.toHaveProperty(bundleName) expect(bundle.dependencies).not.toHaveProperty(providerName) expect(bundle.optionalDependencies).toEqual({ [providerName]: 'workspace:*' }) expect(native.os).toEqual(['darwin']) const version = '1.0.0' const bundleDependencies = Object.fromEntries(Object.keys(bundle.dependencies as Record).map(name => [name, version])) const manifests = [ - { name: cli.name, version, dependencies: { [bundleName]: version } }, + { name: cli.name, version }, { name: bundleName, version, dependencies: bundleDependencies, optionalDependencies: { [providerName]: version } }, ...Object.keys(bundleDependencies).map(name => ({ name, version })), { name: providerName, version, os: native.os, files: native.files }, @@ -102,13 +102,13 @@ it('fetches the macOS optional tarball only for Darwin, with an empty cache for await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve) }) const address = server.address() if (!address || typeof address === 'string') throw new Error('fixture registry has no TCP address') - for (const target of ['darwin', 'win32', 'linux', 'linux-unrestricted']) { + for (const target of ['darwin-base', 'darwin', 'win32', 'linux', 'linux-unrestricted']) { unrestricted = target === 'linux-unrestricted' const project = join(root, target) await mkdir(project) - await writeFile(join(project, 'package.json'), JSON.stringify({ private: true, dependencies: { [String(cli.name)]: version } })) + await writeFile(join(project, 'package.json'), JSON.stringify({ private: true, dependencies: { [target === 'darwin-base' ? String(cli.name) : bundleName]: version } })) await writeFile(join(project, 'pnpm-workspace.yaml'), [ - 'autoInstallPeers: false', 'supportedArchitectures:', ` os: [${unrestricted ? 'linux' : target}]`, + 'autoInstallPeers: false', 'supportedArchitectures:', ` os: [${unrestricted ? 'linux' : target === 'darwin-base' ? 'darwin' : target}]`, ' cpu: [arm64]', 'minimumReleaseAge: 0', '', ].join('\n')) requests.length = 0 @@ -117,8 +117,8 @@ it('fetches the macOS optional tarball only for Darwin, with an empty cache for `--config.registry=http://127.0.0.1:${address.port}/`, `--config.store-dir=${join(project, 'store')}`, `--config.cache-dir=${join(project, 'cache')}`, `--config.state-dir=${join(project, 'state')}`, ], project) - expect(requests).toContain(`/${bundleName}.tgz`) - expect(requests).toContain('/@deepseek-ai/dsh-cua.tgz') + expect(requests.includes(`/${bundleName}.tgz`)).toBe(target !== 'darwin-base') + expect(requests.includes('/@deepseek-ai/dsh-cua.tgz')).toBe(target !== 'darwin-base') expect(requests.includes(`/${providerName}.tgz`), `${target}: ${JSON.stringify(requests)}\n${output}`) .toBe(target === 'darwin' || unrestricted) } diff --git a/apps/desktop/tests/desktop-publish-tag.spec.ts b/apps/desktop/tests/desktop-publish-tag.spec.ts index 7a13daba54..06894f7504 100644 --- a/apps/desktop/tests/desktop-publish-tag.spec.ts +++ b/apps/desktop/tests/desktop-publish-tag.spec.ts @@ -3,13 +3,13 @@ import { publishDesktopTag } from '../scripts/desktop-publish-tag.ts' const commit = 'a'.repeat(40) const tag = (sha = commit) => ({ object: { type: 'commit', sha } }) -function transport(replies: Array<{ status: number; body?: object }>) { +function transport(replies: Array<{ status: number; body?: object; rawBody?: string; headers?: Record }>) { const calls: Array<{ url: string; init: RequestInit | undefined }> = [] const request: typeof fetch = async (url, init) => { calls.push({ url: typeof url === 'string' ? url : url instanceof URL ? url.href : url.url, init }) const reply = replies.shift() if (!reply) throw new Error('unexpected HTTP request') - return new Response(JSON.stringify(reply.body ?? {}), { status: reply.status }) + return new Response(reply.rawBody ?? JSON.stringify(reply.body ?? {}), { status: reply.status, headers: reply.headers ?? {} }) } return { calls, request } } @@ -57,3 +57,36 @@ it('explains an existing annotated tag without replacing it', async () => { await expect(publishDesktopTag('owner/repo', '1.2.3', commit, 'fixture-token', http.request)).rejects.toThrow(/not a lightweight commit tag/u) expect(http.calls).toHaveLength(1) }) + +it('keeps the creation status and safe rule diagnostic when no competing tag exists', async () => { + const http = transport([{ status: 404 }, { status: 422, + headers: { 'x-github-request-id': 'ABCD:1234' }, + body: { message: 'Repository rule violations found for refs/tags/desktop-v1.2.3', errors: ['secret-value'] } }, { status: 404 }]) + const failure = publishDesktopTag('owner/repo', '1.2.3', commit, 'fixture-token', http.request) + await expect(failure).rejects.toThrow('creation failed (HTTP 422; GitHub request ABCD:1234); follow-up tag lookup returned HTTP 404; repository rules rejected') + await expect(failure).rejects.not.toThrow('secret-value') + expect(http.calls.map(call => call.init?.method ?? 'GET')).toEqual(['GET', 'POST', 'GET']) +}) + +it('does not echo arbitrary GitHub response text or unrecognized request IDs', async () => { + const http = transport([{ status: 404 }, { status: 422, + headers: { 'x-github-request-id': 'fixture-token' }, body: { message: 'fixture-token' } }, { status: 403 }]) + const failure = publishDesktopTag('owner/repo', '1.2.3', commit, 'fixture-token', http.request) + await expect(failure).rejects.toThrow('creation failed (HTTP 422); follow-up tag lookup returned HTTP 403') + await expect(failure).rejects.not.toThrow('fixture-token') +}) + +it('still rejects a competing tag on a different commit', async () => { + const http = transport([{ status: 404 }, { status: 422 }, { status: 200, body: tag('b'.repeat(40)) }]) + await expect(publishDesktopTag('owner/repo', '1.2.3', commit, 'fixture-token', http.request)).rejects.toThrow('creation failed (HTTP 422)') +}) + +it('retains creation context for a non-JSON rejection', async () => { + const http = transport([{ status: 404 }, { status: 422, rawBody: 'not JSON', headers: { 'x-github-request-id': 'ABCD:1234' } }, { status: 404 }]) + await expect(publishDesktopTag('owner/repo', '1.2.3', commit, 'fixture-token', http.request)).rejects.toThrow('creation failed (HTTP 422; GitHub request ABCD:1234)') +}) + +it('retains creation context when the follow-up request fails', async () => { + const http = transport([{ status: 404 }, { status: 422, headers: { 'x-github-request-id': 'ABCD:1234' } }]) + await expect(publishDesktopTag('owner/repo', '1.2.3', commit, 'fixture-token', http.request)).rejects.toThrow('creation failed (HTTP 422; GitHub request ABCD:1234); follow-up tag lookup failed') +}) diff --git a/apps/desktop/tests/desktop-publish-templates.spec.ts b/apps/desktop/tests/desktop-publish-templates.spec.ts new file mode 100644 index 0000000000..0ead9a11ab --- /dev/null +++ b/apps/desktop/tests/desktop-publish-templates.spec.ts @@ -0,0 +1,35 @@ +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join, posix, win32 } from 'node:path' +import { fileURLToPath } from 'node:url' +import { expect, it } from 'vitest' +import { readDesktopPublishConfig, type DesktopPublishConfig } from '../scripts/desktop-publish-config.ts' + +for (const platform of ['macos', 'windows'] as const) { + for (const preset of ['test', 'production'] as const) { + it(`accepts the ${platform} ${preset} template after machine paths are supplied`, async () => { + const path = fileURLToPath(new URL(`../config/publishing/${platform}/${preset}.json.example`, import.meta.url)) + const template = JSON.parse(await readFile(path, 'utf8')) as DesktopPublishConfig + const paths = platform === 'windows' ? win32 : posix + expect(paths.isAbsolute(template.credentialsFile)).toBe(true) + expect(template[platform === 'macos' ? 'macOS' : 'windows']).toBeDefined() + expect(Object.hasOwn(template, 'secretId')).toBe(false) + expect(Object.hasOwn(template, 'secretKey')).toBe(false) + if (preset === 'production') expect(paths.isAbsolute(template.githubApp?.privateKeyFile ?? '')).toBe(true) + const root = await mkdtemp(join(tmpdir(), 'publish-template-')) + try { + await mkdir(join(root, 'publishing')) + // The parser uses the current host's path syntax; examples retain their target platform's paths. + const config = { ...template, credentialsFile: join(root, 'absent-credentials.json'), + ...(template.githubApp ? { githubApp: { ...template.githubApp, privateKeyFile: join(root, 'absent-key.pem') } } : {}) } + const output = join(root, 'publishing', `${preset}.json`) + await writeFile(output, JSON.stringify(config)) + await expect(readDesktopPublishConfig(root, preset)).resolves.toEqual(config) + await writeFile(output, JSON.stringify({ ...config, bucket: undefined })) + const failure = readDesktopPublishConfig(root, preset) + await expect(failure).rejects.toHaveProperty('name', 'ZodError') + await expect(failure).rejects.toHaveProperty('issues.0.path', ['bucket']) + } finally { await rm(root, { recursive: true, force: true }) } + }) + } +} diff --git a/apps/desktop/tests/expected/application-menu-en-US.json b/apps/desktop/tests/expected/application-menu-en-US.json index 4e3c981919..71b281c6b2 100644 --- a/apps/desktop/tests/expected/application-menu-en-US.json +++ b/apps/desktop/tests/expected/application-menu-en-US.json @@ -1,10 +1,27 @@ [ + { + "label": "About DeepSeek Harness", + "role": "about" + }, + { + "type": "separator" + }, { "label": "Check for Updates…" }, { "label": "Manage dsh Command…" }, + { + "type": "separator" + }, + { + "role": "toggleDevTools", + "label": "Developer tools" + }, + { + "type": "separator" + }, { "role": "hide", "label": "Hide DeepSeek Harness" @@ -17,6 +34,9 @@ "role": "unhide", "label": "Show All" }, + { + "type": "separator" + }, { "role": "quit", "label": "Quit DeepSeek Harness" diff --git a/apps/desktop/tests/expected/application-menu-zh-CN.json b/apps/desktop/tests/expected/application-menu-zh-CN.json index f39b2d88ae..472aa48a8e 100644 --- a/apps/desktop/tests/expected/application-menu-zh-CN.json +++ b/apps/desktop/tests/expected/application-menu-zh-CN.json @@ -1,10 +1,27 @@ [ + { + "label": "关于 DeepSeek Harness", + "role": "about" + }, + { + "type": "separator" + }, { "label": "检查更新…" }, { "label": "管理 dsh 命令…" }, + { + "type": "separator" + }, + { + "role": "toggleDevTools", + "label": "开发者工具" + }, + { + "type": "separator" + }, { "role": "hide", "label": "隐藏 DeepSeek Harness" @@ -17,6 +34,9 @@ "role": "unhide", "label": "显示全部" }, + { + "type": "separator" + }, { "role": "quit", "label": "退出 DeepSeek Harness" diff --git a/apps/desktop/tests/file-actions.spec.ts b/apps/desktop/tests/file-actions.spec.ts new file mode 100644 index 0000000000..972f64e7ee --- /dev/null +++ b/apps/desktop/tests/file-actions.spec.ts @@ -0,0 +1,213 @@ +/** Native original-byte saves and window-scoped IPC ownership. */ +import { EventEmitter } from 'node:events' +import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { IpcMainInvokeEvent } from 'electron' +import { afterEach, expect, it, vi } from 'vitest' +import { installFileActions } from '../src/file-actions.ts' +import { DESKTOP_IPC } from '../src/ipc.ts' + +const electron = vi.hoisted(() => ({ + app: { getPath: vi.fn() }, ipcMain: { handle: vi.fn() }, session: { defaultSession: { on: vi.fn() } }, +})) +vi.mock('electron', () => electron) +const roots: string[] = [] +const owners: EventEmitter[] = [] +afterEach(async () => { + for (const owner of owners.splice(0)) owner.emit('closed') + vi.useRealTimers(); vi.unstubAllEnvs() + await Promise.all(roots.splice(0).map(path => rm(path, { recursive: true, force: true }))); vi.clearAllMocks(); vi.unstubAllGlobals() +}) +async function directory() { const path = await mkdtemp(join(tmpdir(), 'dsh-file-actions-')); roots.push(path); return path } + +function harness(root: string) { + const owner = Object.assign(new EventEmitter(), { + webContents: Object.assign(new EventEmitter(), { downloadURL: vi.fn<(url: string) => void>() }), isDestroyed: () => false, + }) + owners.push(owner) + const assertOwner = vi.fn(() => owner as never) + electron.app.getPath.mockReturnValue(root) + installFileActions(assertOwner) + const event = {} as IpcMainInvokeEvent + const invoke = async (channel: string, value: unknown): Promise => { + const handler = electron.ipcMain.handle.mock.calls.find(([name]) => name === channel)?.[1] as + (event: IpcMainInvokeEvent, value: unknown) => Promise + return handler(event, value) + } + const item = (mime = 'image/gif', url = owner.webContents.downloadURL.mock.lastCall![0]) => { + let destination = '' + const download = Object.assign(new EventEmitter(), { + getURLChain: () => [url], + getFilename: () => 'original.gif', getMimeType: () => mime, getSavePath: () => destination, + setSavePath: vi.fn((path: string) => { destination = path }), + setSaveDialogOptions: vi.fn(), cancel: vi.fn(), + }) + const willDownload = electron.session.defaultSession.on.mock.calls[0]![1] as + (event: object, item: object, contents: object) => void + willDownload({}, download, owner.webContents) + return download + } + const save = async (mode: 'download' | 'saveAs' = 'download') => { + const pending = invoke(DESKTOP_IPC.fileSave, { url: 'https://images.example/original.gif', name: 'image.gif', mode }) + const download = item() + if (mode === 'download') await writeFile(download.getSavePath(), new Uint8Array([0, 128, 255])) + download.emit('done', {}, 'completed') + return pending + } + return { owner, assertOwner, invoke, item, save } +} + +it('returns the completed destination and releases download listeners', async () => { + const root = await directory(), f = harness(root) + await expect(f.save()).resolves.toEqual({ status: 'saved', path: join(root, 'image.gif') }) + expect(f.owner.listenerCount('closed')).toBe(0) + expect(f.owner.webContents.listenerCount('did-start-navigation')).toBe(0) +}) + +it.each(['file:///private/data', 'dsh-app://app/api/private', 'javascript:alert(1)'])('rejects unsupported URL %s', async (url) => { + const root = await directory(), f = harness(root) + await expect(f.invoke(DESKTOP_IPC.fileSave, { url, mode: 'download' })).rejects.toThrow('Unsupported') + expect(await readdir(root)).toEqual([]) +}) + +it('retains original downloads and reserves distinct paths until Chromium finishes', async () => { + const root = await directory(), f = harness(root) + await writeFile(join(root, 'image.gif'), 'previous') + await f.save() + expect(await readFile(join(root, 'image.gif'), 'utf8')).toBe('previous') + expect(await readFile(join(root, 'image (1).gif'))).toEqual(Buffer.from([0, 128, 255])) +}) + +it.each(['cancelled', 'interrupted'] as const)('reports native %s without a completed path', async (state) => { + const root = await directory(), f = harness(root) + const pending = f.invoke(DESKTOP_IPC.fileSave, { url: 'https://images.example/a', name: 'wrong.png', mode: 'download' }) + const download = f.item('image/webp') + expect(download.setSavePath).toHaveBeenCalledWith(join(root, 'wrong.webp')) + download.emit('done', {}, state) + if (state === 'cancelled') await expect(pending).resolves.toEqual({ status: 'cancelled' }) + else await expect(pending).rejects.toThrow('interrupted') + expect(await readdir(root)).toEqual([]) +}) + +it('uses the native save dialog and waits for completion before reporting success', async () => { + const root = await directory(), f = harness(root) + const pending = f.invoke(DESKTOP_IPC.fileSave, { url: 'https://images.example/a', name: 'photo.png', mode: 'saveAs' }) + const download = f.item('image/jpeg') + expect(download.setSavePath).not.toHaveBeenCalled() + expect(download.setSaveDialogOptions).toHaveBeenCalledWith({ defaultPath: join(root, 'photo.jpg'), properties: ['showOverwriteConfirmation', 'createDirectory'] }) + download.emit('done', {}, 'cancelled') + await expect(pending).resolves.toEqual({ status: 'cancelled' }) + f.assertOwner.mockImplementation(() => { throw new Error('Rejected owner') }) + await expect(f.invoke(DESKTOP_IPC.fileSave, {})).rejects.toThrow('Rejected owner') +}) + +it('cancels pending downloads when the owning document changes', async () => { + const f = harness(await directory()) + const pending = f.invoke(DESKTOP_IPC.fileSave, { url: 'https://images.example/a', mode: 'download' }) + const download = f.item() + f.owner.webContents.emit('did-start-navigation', {}, 'dsh-app://app/', false, true) + await expect(pending).resolves.toEqual({ status: 'cancelled' }) + expect(download.cancel).toHaveBeenCalledOnce() + download.emit('done', {}, 'cancelled') + expect(f.owner.listenerCount('closed')).toBe(0) +}) + +it('matches overlapping downloads of the same source to their captured requests', async () => { + const root = await directory(), f = harness(root) + const first = f.invoke(DESKTOP_IPC.fileSave, { url: 'https://images.example/a', name: 'first.gif', mode: 'download' }) + const firstUrl = f.owner.webContents.downloadURL.mock.lastCall![0] + const second = f.invoke(DESKTOP_IPC.fileSave, { url: 'https://images.example/a', name: 'second.gif', mode: 'saveAs' }) + const secondItem = f.item() + const firstItem = f.item('image/gif', firstUrl) + expect(firstItem.setSavePath).toHaveBeenCalledWith(join(root, 'first.gif')) + expect(secondItem.setSaveDialogOptions.mock.lastCall?.[0]).toMatchObject({ defaultPath: join(root, 'second.gif') }) + secondItem.emit('done', {}, 'cancelled') + firstItem.emit('done', {}, 'completed') + await expect(first).resolves.toMatchObject({ status: 'saved' }) + await expect(second).resolves.toEqual({ status: 'cancelled' }) +}) + +it('retires timed-out downloads and cancels items arriving after their window closes', async () => { + vi.useFakeTimers(); vi.stubEnv('DSH_DESKTOP_FILE_DOWNLOAD_TIMEOUT_MS', '1000') + const root = await directory(), f = harness(root) + const pending = f.invoke(DESKTOP_IPC.fileSave, { url: 'https://images.example/a', mode: 'download' }) + const rejected = expect(pending).rejects.toThrow('timed out') + await vi.advanceTimersByTimeAsync(1000) + await rejected + const download = f.item() + expect(download.cancel).toHaveBeenCalledOnce() + download.emit('done', {}, 'cancelled') + expect(await readdir(root)).toEqual([]) + expect(f.owner.listenerCount('closed')).toBe(0) + expect(f.owner.webContents.listenerCount('did-start-navigation')).toBe(0) + + const late = f.invoke(DESKTOP_IPC.fileSave, { url: 'https://images.example/a', mode: 'download' }) + f.owner.emit('closed') + await expect(late).resolves.toEqual({ status: 'cancelled' }) + const stale = f.item() + expect(stale.cancel).toHaveBeenCalledOnce() + expect(stale.setSavePath).not.toHaveBeenCalled() +}) + +it('allows the native save dialog to remain open beyond the download startup deadline', async () => { + vi.useFakeTimers(); vi.stubEnv('DSH_DESKTOP_FILE_DOWNLOAD_TIMEOUT_MS', '1000') + const f = harness(await directory()) + const pending = f.invoke(DESKTOP_IPC.fileSave, { url: 'https://images.example/a', mode: 'saveAs' }) + const download = f.item() + await vi.advanceTimersByTimeAsync(2000) + expect(download.cancel).not.toHaveBeenCalled() + download.emit('done', {}, 'completed') + await expect(pending).resolves.toMatchObject({ status: 'saved' }) +}) + +it('reports a synchronous Chromium launch failure and releases pending listeners', async () => { + const f = harness(await directory()) + f.owner.webContents.downloadURL.mockImplementation(() => { throw new Error('Download unavailable') }) + await expect(f.invoke(DESKTOP_IPC.fileSave, { url: 'https://images.example/a', mode: 'download' })).rejects.toThrow('Download unavailable') + expect(f.owner.listenerCount('closed')).toBe(0) + expect(f.owner.webContents.listenerCount('did-start-navigation')).toBe(0) +}) + +it('aborts original-image reads on window navigation and releases lifecycle listeners', async () => { + const f = harness(await directory()) + let signal!: AbortSignal + vi.stubGlobal('fetch', vi.fn((_url: URL, options: RequestInit) => new Promise((_resolve, reject) => { + signal = options.signal! + signal.addEventListener('abort', () => { reject(new DOMException('Aborted', 'AbortError')) }, { once: true }) + }))) + const reading = f.invoke(DESKTOP_IPC.clipboardImageRead, 'https://images.example/original.gif') + f.owner.webContents.emit('did-start-navigation', {}, 'dsh-app://app/', false, true) + await expect(reading).rejects.toThrow('Aborted') + expect(signal.aborted).toBe(true) + expect(f.owner.listenerCount('closed')).toBe(0) + expect(f.owner.webContents.listenerCount('did-start-navigation')).toBe(0) +}) + +it('preserves pending downloads across iframe and same-document navigation', async () => { + const root = await directory(), f = harness(root) + const pending = f.invoke(DESKTOP_IPC.fileSave, { url: 'https://images.example/a', mode: 'saveAs' }) + const download = f.item() + f.owner.webContents.emit('did-start-navigation', {}, 'https://example.org', false, false) + f.owner.webContents.emit('did-start-navigation', {}, 'dsh-app://app/#tab', true, true) + download.setSavePath(join(root, 'chosen.gif')) + download.emit('done', {}, 'completed') + await expect(pending).resolves.toEqual({ status: 'saved', path: join(root, 'chosen.gif') }) + expect(download.cancel).not.toHaveBeenCalled() +}) + +it('rejects redirects to the application Host', async () => { + const root = await directory() + const owner = Object.assign(new EventEmitter(), { + webContents: Object.assign(new EventEmitter(), { downloadURL: vi.fn<(url: string) => void>() }), isDestroyed: () => false, + }) + installFileActions(() => owner as never, () => 'http://127.0.0.1:19321') + const handler = (name: string) => electron.ipcMain.handle.mock.calls.find(([channel]) => channel === name)![1] as + (event: IpcMainInvokeEvent, value: unknown) => Promise + const fetchImage = vi.fn(async () => new Response(null, { status: 302, headers: { location: 'http://localhost:19321/api/private' } })) + vi.stubGlobal('fetch', fetchImage) + const event = {} as IpcMainInvokeEvent + await expect(handler(DESKTOP_IPC.clipboardImageRead)(event, 'https://images.example/photo')).rejects.toThrow('Invalid image URL') + expect(fetchImage).toHaveBeenCalledOnce() + expect(await readdir(root)).toEqual([]) +}) diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index 20325642a2..3b1e63e00c 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -317,6 +317,7 @@ vi.mock('electron', () => ({ }, Menu: { setApplicationMenu: harness.menu.setApplicationMenu, buildFromTemplate: harness.menu }, session: { defaultSession: { + on: vi.fn(), setPermissionCheckHandler: vi.fn(), setPermissionRequestHandler: vi.fn(), webRequest: { onBeforeSendHeaders: harness.socketHeaders }, } }, protocol: { registerSchemesAsPrivileged: vi.fn(), handle: harness.protocolHandle }, @@ -549,12 +550,49 @@ describe('desktop main startup', () => { expect((await handler(new Request('dsh-app://unknown/update-dialog.html'))).status).toBe(404) }) - it('installs hidden native DevTools shortcuts in the macOS application menu', async () => { - vi.stubGlobal('process', { ...process, platform: 'darwin' }) + it.each(([ + ['darwin', 'en'], ['darwin', 'zh-CN'], ['win32', 'en'], ['win32', 'zh-CN'], ['linux', 'en'], ['linux', 'zh-CN'], + ] as const).flatMap(([platform, locale]) => [ + [platform, locale, true] as const, [platform, locale, false] as const, + ]))('groups localized DevTools before quit on %s (%s, packaged=%s)', async (platform, locale, packaged) => { + vi.stubGlobal('process', { ...process, platform }) + harness.app.isPackaged = packaged + vi.spyOn(harness.app, 'getPreferredSystemLanguages').mockReturnValue([locale]) await readyForUpdate() - expect(applicationMenuItems().slice(-2)).toEqual([ - { role: 'toggleDevTools', visible: false }, - { role: 'toggleDevTools', visible: false, accelerator: 'F12' }, + const messages = locale === 'en' ? en : zh + const menu = applicationMenuItems() + const visible = menu.filter(item => item.visible !== false) + expect(visible.map(item => item.role === 'quit' ? 'quit' : item.label ?? item.type)).toEqual([ + messages.aboutMenu, 'separator', messages.checkUpdatesMenu, + ...platform === 'linux' ? [] : [messages.cliCommandMenu], + 'separator', ...packaged ? [] : [messages.reloadPageMenu, messages.restartAppHostMenu], + messages.toggleDevToolsMenu, 'separator', + ...platform === 'darwin' ? [messages.hideApplication, messages.hideOtherApplications, messages.showAllApplications, 'separator'] : [], + 'quit', + ]) + expect(visible.filter(item => item.role === 'toggleDevTools')).toEqual([ + { role: 'toggleDevTools', label: messages.toggleDevToolsMenu }, + ]) + if (platform === 'win32') { + expect(harness.menu.mock.calls[0]![0]).toEqual([ + { role: 'toggleDevTools', visible: false }, + { role: 'toggleDevTools', visible: false, accelerator: 'F12' }, + ]) + expect(menu.every(item => item.visible !== false)).toBe(true) + } else { + expect(menu.filter(item => item.visible === false)).toEqual([ + { role: 'toggleDevTools', visible: false, accelerator: 'F12' }, + ]) + } + const sender = harness.windows[0]!.webContents + const nextLocale = locale === 'en' ? 'zh' : 'en' + harness.ipcOn.mock.calls.find(([channel]) => channel === DESKTOP_IPC.localeChanged)![1]( + { sender, senderFrame: sender.mainFrame }, nextLocale, + ) + const refreshed = platform === 'win32' ? applicationMenuItems() + : harness.menu.mock.lastCall![0][0]!.submenu as MenuItemConstructorOptions[] + expect(refreshed.filter(item => item.role === 'toggleDevTools' && item.visible !== false)).toEqual([ + { role: 'toggleDevTools', label: nextLocale === 'en' ? en.toggleDevToolsMenu : zh.toggleDevToolsMenu }, ]) expect(harness.windows[0]!.options).toMatchObject({ webPreferences: { devTools: true } }) }) @@ -1030,7 +1068,7 @@ describe('desktop main startup', () => { expect(() => handler(event, 'application', NaN, 34)).toThrow('invalid popup request') const application = handler(event, 'application', 48, 34) expect(harness.menu.buildFromTemplate.mock.lastCall![0].map(item => item.label ?? item.type)).toEqual([ - '关于 DeepSeek Harness', 'separator', '检查更新…', '管理 dsh 命令…', 'separator', '退出', + '关于 DeepSeek Harness', 'separator', '检查更新…', '管理 dsh 命令…', 'separator', zh.toggleDevToolsMenu, 'separator', '退出', ]) expect(harness.popup.mock.lastCall![0]).toMatchObject({ window, x: 48, y: 34 }) expect(harness.popup.mock.lastCall![0].callback).toBeTypeOf('function') @@ -1067,8 +1105,8 @@ describe('desktop main startup', () => { : ['Application', 'editMenu']) const application = template[0]!.submenu as MenuItemConstructorOptions[] expect(application.filter(item => item.visible !== false).map(describeItem)).toEqual(platform === 'darwin' - ? ['about', 'separator', en.checkUpdatesMenu, en.cliCommandMenu, 'separator', 'hide', 'hideOthers', 'unhide', 'separator', 'quit'] - : ['about', 'separator', en.checkUpdatesMenu, 'separator', 'quit']) + ? ['about', 'separator', en.checkUpdatesMenu, en.cliCommandMenu, 'separator', 'toggleDevTools', 'separator', 'hide', 'hideOthers', 'unhide', 'separator', 'quit'] + : ['about', 'separator', en.checkUpdatesMenu, 'separator', 'toggleDevTools', 'separator', 'quit']) expect(harness.menu.setApplicationMenu).toHaveBeenCalledOnce() }) @@ -1081,10 +1119,7 @@ describe('desktop main startup', () => { try { await import('../src/main.ts') await harness.preparing.promise - const commands = applicationMenuItems().filter(item => - item.role === 'hide' || item.role === 'hideOthers' || item.role === 'unhide' || item.role === 'quit' - || item.label === en.checkUpdatesMenu || item.label === zh.checkUpdatesMenu - || item.label === en.cliCommandMenu || item.label === zh.cliCommandMenu) + const commands = applicationMenuItems().filter(item => item.visible !== false) await expect(JSON.stringify(commands, null, 2) + '\n') .toMatchFileSnapshot(`./expected/application-menu-${locale}.json`) expect(harness.app.name).toBe('@deepseek-ai/dsh-desktop') diff --git a/apps/desktop/tests/preload-app.spec.ts b/apps/desktop/tests/preload-app.spec.ts index af9a9f226a..8001ae6fc2 100644 --- a/apps/desktop/tests/preload-app.spec.ts +++ b/apps/desktop/tests/preload-app.spec.ts @@ -38,6 +38,19 @@ it('exposes onboarding size activation to the application document', async () => expect(electron.ipcRenderer.send.mock.calls).toEqual([[DESKTOP_IPC.onboardingActive, true], [DESKTOP_IPC.onboardingActive, false]]) }) +it('routes original-file requests through the trusted application bridge', async () => { + vi.stubGlobal('location', new URL('dsh-app://app/')) + await import('../src/preload-app.ts') + const api = electron.contextBridge.exposeInMainWorld.mock.calls.find(([name]) => name === 'dshDesktop')?.[1] as DshDesktopProductApi + const request = { url: 'https://images.example/original.gif', name: 'image.gif', mode: 'download' as const } + await api.fileActions.save(request) + await api.fileActions.readClipboardImage('https://images.example/original.gif') + expect(electron.ipcRenderer.invoke.mock.calls).toEqual([ + [DESKTOP_IPC.fileSave, request], + [DESKTOP_IPC.clipboardImageRead, 'https://images.example/original.gif'], + ]) +}) + it('limits product documents to update status and a native confirmation action', async () => { vi.stubGlobal('location', new URL('dsh-app://app/index.html')) await import('../src/preload-app.ts') diff --git a/apps/desktop/tests/welcome-startup.spec.ts b/apps/desktop/tests/welcome-startup.spec.ts index 7915248243..4ae8743e2e 100644 --- a/apps/desktop/tests/welcome-startup.spec.ts +++ b/apps/desktop/tests/welcome-startup.spec.ts @@ -87,6 +87,7 @@ vi.mock('electron', () => ({ net: { fetch: vi.fn() }, nativeTheme: state.nativeTheme, session: { defaultSession: { + on: vi.fn(), setPermissionCheckHandler: vi.fn(), setPermissionRequestHandler: vi.fn(), webRequest: { onBeforeSendHeaders: vi.fn() }, } }, protocol: { registerSchemesAsPrivileged: vi.fn(), handle: vi.fn() }, diff --git a/apps/desktop/tsconfig.client.json b/apps/desktop/tsconfig.client.json index 3de33f06dd..eb17ebe087 100644 --- a/apps/desktop/tsconfig.client.json +++ b/apps/desktop/tsconfig.client.json @@ -18,6 +18,9 @@ }, { "path": "../../packages/client/product-analytics/tsconfig.client.json" + }, + { + "path": "../../packages/client/ui-file-actions" } ] } diff --git a/apps/desktop/tsconfig.host.json b/apps/desktop/tsconfig.host.json index 44992641d5..7078ac8198 100644 --- a/apps/desktop/tsconfig.host.json +++ b/apps/desktop/tsconfig.host.json @@ -40,6 +40,9 @@ }, { "path": "../../packages/util/file-drag" + }, + { + "path": "../../packages/client/ui-file-actions" } ], "exclude": [ diff --git a/apps/web/tests/client-plugin-live.e2e.ts b/apps/web/tests/client-plugin-live.e2e.ts index ecd46f5f5c..72a389f9c8 100644 --- a/apps/web/tests/client-plugin-live.e2e.ts +++ b/apps/web/tests/client-plugin-live.e2e.ts @@ -26,7 +26,7 @@ async function openInventory(page: Page, url: string) { return dialog } -it('places dynamic Session menu rows by order among the shipped ones and removes them with their fiber', async () => { +it('keeps ordered legacy Session menu rows before Archive and removes them with their fiber', async () => { const scaffold = await launchWebScaffold({ extraInstallAnchors: [join(FIXTURE, 'package.json')] }) onTestFinished(() => scaffold.close()) const workspace = await scaffold.ctx.workspaceRegistry.create(scaffold.workspaceCwd) @@ -46,12 +46,13 @@ it('places dynamic Session menu rows by order among the shipped ones and removes const trailing = row.locator('[data-session-trailing]') const observations: { stage: string; icons: string[]; time: boolean; pinned: boolean; actions: boolean }[] = [] - const observe = async (stage: string, iconsVisible: boolean, actionsVisible: boolean, target = row): Promise => { + const observe = async (stage: string, iconsVisible: boolean, actionsVisible: boolean, target = row, + timeVisible = iconsVisible): Promise => { const icons = target.locator('[data-session-trailing]') const actions = target.getByRole('button', { name: `Session actions for ${SESSION_TITLE}` }) const time = target.locator('[class*="time"]') await expect.poll(() => icons.first().isVisible()).toBe(iconsVisible) - await expect.poll(() => time.isVisible()).toBe(iconsVisible) + await expect.poll(() => time.isVisible()).toBe(timeVisible) await expect.poll(() => actions.isVisible()).toBe(actionsVisible) observations.push({ stage, @@ -94,14 +95,16 @@ it('places dynamic Session menu rows by order among the shipped ones and removes await observe('menu-open', false, true) const menu = page.getByRole('menu') await menu.waitFor() - expect(await menu.getByRole('separator').count()).toBe(1) + expect(await menu.getByRole('separator').count()).toBe(3) + const exportRow = menu.getByRole('menuitem', { name: 'Export session', exact: true }) + expect(await exportRow.locator('..').getByRole('separator').isVisible()).toBe(true) await compareOrRefreshGolden( SESSION_ACTION_EXPECTED, await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd), webSnapshotMode(), ) - await menu.getByRole('menuitem', { name: 'Export session' }).press('Enter') + await exportRow.press('Enter') await expect.poll(() => menu.count()).toBe(0) expect(await page.evaluate(() => ({ action: document.documentElement.dataset.sessionAction, @@ -138,18 +141,18 @@ it('places dynamic Session menu rows by order among the shipped ones and removes const touchTrigger = touchRow.getByRole('button', { name: `Session actions for ${SESSION_TITLE}` }) await touchTrigger.waitFor() expect(await touchPage.evaluate(() => matchMedia('(hover: hover)').matches)).toBe(false) - await observe('touch', true, true, touchRow) + await observe('touch', true, true, touchRow, false) expect(await touchRow.getByRole('button', { name: 'Archive session', exact: true }).isVisible()).toBe(false) expect(await touchRow.getByRole('button', { name: 'Pin session', exact: true }).isVisible()).toBe(false) await touchTrigger.tap() await touchPage.getByRole('menu').waitFor() - await observe('touch-menu-open', true, true, touchRow) + await observe('touch-menu-open', true, true, touchRow, false) await touchPage.keyboard.press('Escape') - await observe('touch-menu-closed', true, true, touchRow) + await observe('touch-menu-closed', true, true, touchRow, false) await touchTrigger.tap() await touchPage.getByRole('menuitem', { name: 'Pin session', exact: true }).tap() - await touchRow.getByRole('img', { name: 'Pinned', exact: true }).waitFor() - await observe('touch-pinned', true, true, touchRow) + await touchRow.getByRole('button', { name: 'Unpin session', exact: true }).waitFor() + await observe('touch-pinned', true, true, touchRow, false) const touchBounds = await touchRow.evaluate((element) => { const title = element.querySelector('[class*="title"]')!.getBoundingClientRect() const resting = element.querySelector('[class*="rowResting"]')!.getBoundingClientRect() @@ -173,7 +176,7 @@ it('places dynamic Session menu rows by order among the shipped ones and removes expect(await row.evaluate(element => element === document.activeElement)).toBe(true) await observe('clicked-archived-row', true, false) await scaffold.ctx.workspaceRegistry.unarchiveSession(sessionId) - await observe('touch-unarchived', true, true, touchRow) + await observe('touch-unarchived', true, true, touchRow, false) expect(touchConsole.pageErrors).toEqual([]) } finally { await touchPage.close() @@ -193,13 +196,13 @@ it('places dynamic Session menu rows by order among the shipped ones and removes await row.hover() await trigger.click() await menu.waitFor() - const remainingNames = ['Pin session', 'Rename', 'Fork session', 'Archive session', 'Copy Session ID'] + const remainingNames = ['Pin session', 'Rename', 'Fork session', 'Copy Session ID', 'Archive session'] const remainingItems = menu.getByRole('menuitem') expect(await remainingItems.count()).toBe(remainingNames.length) for (const [index, name] of remainingNames.entries()) { expect(await remainingItems.nth(index).and(menu.getByRole('menuitem', { name, exact: true })).count()).toBe(1) } - expect(await menu.getByRole('separator').count()).toBe(0) + expect(await menu.getByRole('separator').count()).toBe(2) await page.context().grantPermissions(['clipboard-read', 'clipboard-write']) await menu.getByRole('menuitem', { name: 'Copy Session ID', exact: true }).click() await expect.poll(() => menu.count()).toBe(0) diff --git a/apps/web/tests/context-menus.e2e.ts b/apps/web/tests/context-menus.e2e.ts new file mode 100644 index 0000000000..9e350ec6d4 --- /dev/null +++ b/apps/web/tests/context-menus.e2e.ts @@ -0,0 +1,386 @@ +/** Context gestures against built plugins, seeded Sessions, and original files. */ +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { chromium, type Browser, type Locator, type Page } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed, vi } from 'vitest' +import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' +import { createAssistantMessage, createUserMessage } from '@deepseek-ai/dsh-llm' +import { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-title' +import { launchWebScaffold, seedSession, watchConsole, type WebScaffold } from './scaffold.ts' +import { saveFailureShot } from './support.ts' + +const GIF = Buffer.from('R0lGODdhMAAgAIEAAEtu5gAAAAAAAAAAACwAAAAAMAAgAEAIQQABCBxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjyBDihxJsqTJkyhTqlzJsqXLlzBjypxJs6bNmQEBADs=', 'base64') +async function menuLabels(menu: Locator): Promise { + return menu.getByRole('menuitem').evaluateAll(items => items.map((item) => { + const copy = item.cloneNode(true) as HTMLElement + for (const decoration of copy.querySelectorAll('[aria-hidden="true"]')) decoration.remove() + return copy.textContent ?? '' + })) +} +function fixture(title: string): string { + const session = Session.create(SessionId('context-menus-source')) + session.append('turn/start', { turn: 1 }) + const user = session.append('user/message', createUserMessage({ content: [{ type: 'text', text: 'Show the output.' }], source: { kind: 'user' } }), { surfaceOp: 'append' }) + session.append('session/title', { title, messageSeqs: [user.seq], source: { kind: 'fallback' } }) + session.append('step/start', { turn: 1, step: 1 }) + session.append('assistant/message', { stream: [], turn: 1, step: 1, message: createAssistantMessage({ + content: [{ type: 'text', text: '[First file](first.txt#L2) [Second file](second.txt) [Website](https://example.com/path?q=1#fragment)\n\n![Original](original.gif) ![Remote](https://images.example/original.gif)\n\nCONTEXT_MENU_READY' }], + source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, + }) }, { surfaceOp: 'append' }) + session.append('step/end', { turn: 1, step: 1 }) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + return [JSON.stringify({ type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', createdAt: 0, cwd: '{{cwd}}', isSeeded: false, delegationDepth: 0 }), + ...session.snapshotEvents().map(event => JSON.stringify({ ...event, time: 1_000 + event.seq * 1_000 })), ''].join('\n') +} + +describe.each(['MacIntel', 'Win32', 'Linux x86_64'])('web context menus on %s', (platform) => { + let scaffold: WebScaffold, browser: Browser, page: Page + let tripwire: ReturnType + beforeAll(async () => { + scaffold = await launchWebScaffold({ openInAppEnvironment: createLaunchEnvironmentSnapshot([{ source: 'process', values: { SSH_CONNECTION: '10.0.0.2 55000 10.0.0.9 22' } }]) }) + await mkdir(join(scaffold.workspaceCwd, 'folder')) + await scaffold.ctx.workspaceRegistry.create(join(scaffold.workspaceCwd, 'folder'), 'Menu workspace') + await writeFile(join(scaffold.workspaceCwd, 'first.txt'), 'FIRST\nSECOND\nTHIRD\n') + await writeFile(join(scaffold.workspaceCwd, 'second.txt'), 'SECOND FILE\n') + await writeFile(join(scaffold.workspaceCwd, 'original.gif'), GIF) + await seedSession(scaffold, fixture('Menu foreground'), 'context-menu-first') + await seedSession(scaffold, fixture('Menu background'), 'context-menu-other') + browser = await chromium.launch() + const context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: 'en-US', timezoneId: 'Asia/Shanghai' }) + await context.addInitScript((value) => { Object.defineProperty(navigator, 'platform', { value }) }, platform) + page = await context.newPage() + await page.setViewportSize({ width: 1291, height: 768 }) + tripwire = watchConsole(page) + await page.route('https://images.example/original.gif', route => route.fulfill({ body: GIF, contentType: 'image/gif', headers: { 'access-control-allow-origin': '*' } })) + await page.context().grantPermissions(['clipboard-read', 'clipboard-write']) + await page.goto(scaffold.authenticatedUrl) + await page.locator('[data-row-key^="workspace:"]').filter({ hasText: 'Ungrouped' }).click() + await page.locator('[data-row-key="session:context-menu-other"]').click() + await page.locator('[data-row-key="session:context-menu-other"]').getByText('Menu background', { exact: true }).waitFor() + await page.locator('[data-row-key="session:context-menu-first"]').click() + await page.getByText('CONTEXT_MENU_READY', { exact: true }).waitFor() + }) + afterAll(async () => { await browser?.close(); await scaffold?.close() }) + + it('shares Session entries without selecting the background Session, and dismisses at viewport edges', async () => { + onTestFailed(() => saveFailureShot(page, 'context-menus-session')) + const background = page.locator('[data-row-key="session:context-menu-other"]') + await background.click({ button: 'right' }) + const menu = page.getByRole('menu') + await menu.getByRole('menuitem', { name: /Copy.*[Ii][Dd]/ }).waitFor() + const names = await menuLabels(menu) + expect(names.slice(0, 5)).toEqual(['Pin session', 'Rename', 'Fork session', 'Copy Session ID', 'Show in folder']) + expect(names.at(-1)).toBe('Archive session') + expect(await menu.getByRole('menuitem').evaluateAll(rows => rows.every(row => row.querySelector('svg[data-icon]')))).toBe(true) + expect(await menu.getByRole('separator').count()).toBe(2) + expect(await menu.getByRole('menuitem', { name: 'Archive session', exact: true }).evaluate(row => + getComputedStyle(row.parentElement!.parentElement!).borderTopWidth)).toBe('0px') + const alignedSeparators = async () => { + const bounds = await menu.evaluate((node) => { + const row = node.querySelector('[role="menuitem"]')! + const rect = row.getBoundingClientRect() + const style = getComputedStyle(row) + return { + left: rect.left + Number.parseFloat(style.paddingLeft), + right: rect.right - Number.parseFloat(style.paddingRight), + lines: [...node.querySelectorAll('[role="separator"]')].map((line) => { + const rect = line.getBoundingClientRect() + return { left: rect.left, right: rect.right } + }), + } + }) + for (const line of bounds.lines) { + expect(line.left).toBeCloseTo(bounds.left, 1) + expect(line.right).toBeCloseTo(bounds.right, 1) + } + } + await alignedSeparators() + await expect(names.join('\n') + '\n').toMatchFileSnapshot(join(import.meta.dirname, 'expected/context-menus/session.txt')) + expect(names.some(name => name.includes('Rename'))).toBe(true) + expect(await background.getAttribute('aria-selected')).toBe('false') + await page.keyboard.press('Escape') + await background.getByRole('button', { name: /actions/i }).click() + await menu.getByRole('menuitem', { name: /Copy.*[Ii][Dd]/ }).waitFor() + expect(await menuLabels(menu)).toEqual(names) + await alignedSeparators() + await background.getByRole('button', { name: /actions/i }).click() + expect(await menu.count()).toBe(0) + expect(await background.getAttribute('aria-selected')).toBe('false') + }) + + it('updates an open Session menu from another window’s shortcut preferences and still renames the captured row', async () => { + onTestFailed(() => saveFailureShot(page, 'context-menus-live-shortcuts')) + const other = await page.context().newPage() + const key = 'dsh.keybindings.v1' + const original = await page.evaluate(key => localStorage.getItem(key), key) + try { + await other.goto(scaffold.authenticatedUrl) + await other.getByRole('button', { name: 'Search sessions', exact: true }).waitFor() + const background = page.locator('[data-row-key="session:context-menu-other"]') + await background.click({ button: 'right' }) + const item = page.getByRole('menuitem', { name: 'Rename', exact: true }) + await item.waitFor() + const popup = await page.getByRole('menu').elementHandle() + const initial = await item.getAttribute('aria-keyshortcuts') + await other.evaluate((key) => { + localStorage.setItem(key, JSON.stringify({ schemaVersion: 2, profiles: { + 'web:macos': { 'session.rename': { code: 'Comma', modifiers: ['primary', 'shift'] } }, + 'web:windows': { 'session.rename': { code: 'Comma', modifiers: ['primary', 'shift'] } }, + 'web:linux': { 'session.rename': { code: 'Comma', modifiers: ['primary', 'shift'] } }, + } })) + }, key) + await expect.poll(() => item.getAttribute('aria-keyshortcuts')).toBe(platform === 'MacIntel' ? 'Shift+Meta+,' : 'Control+Shift+,') + expect(await item.getAttribute('aria-keyshortcuts')).not.toBe(initial) + expect(await popup!.evaluate(element => element.isConnected)).toBe(true) + expect(await background.getAttribute('aria-selected')).toBe('false') + await item.click() + const rename = page.getByRole('dialog', { name: 'Rename session', exact: true }) + expect(await rename.getByLabel('Session name').inputValue()).toBe('Menu background') + await rename.getByRole('button', { name: 'Cancel', exact: true }).click() + expect(await background.getAttribute('aria-selected')).toBe('false') + await background.click({ button: 'right' }) + await item.waitFor() + await other.evaluate((key) => { + localStorage.setItem(key, JSON.stringify({ schemaVersion: 2, profiles: { + 'web:macos': { 'session.rename': null }, 'web:windows': { 'session.rename': null }, 'web:linux': { 'session.rename': null }, + } })) + }, key) + await expect.poll(() => item.getAttribute('aria-keyshortcuts')).toBeNull() + await other.evaluate(({ key, original }) => { + if (original === null) localStorage.removeItem(key) + else localStorage.setItem(key, original) + }, { key, original }) + await expect.poll(() => item.getAttribute('aria-keyshortcuts')).toBe(initial) + await page.keyboard.press('Escape') + } finally { + const cancel = page.getByRole('dialog', { name: 'Rename session', exact: true }).getByRole('button', { name: 'Cancel', exact: true }) + if (await cancel.isVisible()) await cancel.click() + await page.keyboard.press('Escape') + await other.evaluate(({ key, original }) => { + if (original === null) localStorage.removeItem(key) + else localStorage.setItem(key, original) + }, { key, original }) + await other.close() + } + }) + + it('shares Workspace menus and keeps folder gestures independent from expansion', async () => { + onTestFailed(() => saveFailureShot(page, 'context-menus-workspace')) + const workspace = page.locator('[data-row-key^="workspace:"]').filter({ hasText: 'Menu workspace' }) + const expanded = await workspace.getAttribute('aria-expanded') + await workspace.click({ button: 'right' }) + const menu = page.getByRole('menu') + await menu.getByRole('menuitem', { name: 'Rename', exact: true }).waitFor() + const names = await menuLabels(menu) + expect(names).toEqual(['Rename', 'Show in folder', 'Delete workspace']) + expect(await menu.locator('svg[data-icon]').count()).toBe(3) + expect(await workspace.getAttribute('aria-expanded')).toBe(expanded) + await page.keyboard.press('Escape') + await workspace.getByRole('button', { name: /actions/i }).click() + await menu.getByRole('menuitem', { name: 'Rename', exact: true }).waitFor() + expect(await menuLabels(menu)).toEqual(names) + await menu.getByRole('menuitem', { name: 'Rename', exact: true }).click() + await page.getByRole('dialog').waitFor() + await page.getByRole('button', { name: 'Cancel', exact: true }).click() + await workspace.click({ button: 'right' }) + await menu.getByRole('menuitem', { name: 'Delete workspace', exact: true }).click() + await page.getByRole('dialog', { name: 'Delete workspace', exact: true }).waitFor() + await page.getByRole('button', { name: 'Cancel', exact: true }).click() + await page.locator('[data-sidebar-right-expand]').click() + await page.locator('[data-sidebar-right-guide-entry="files"]').click() + await page.locator('[data-files-state="tree"]').waitFor() + const folder = page.locator('[data-files-entry="directory"]').filter({ hasText: 'folder' }).getByRole('button').first() + await folder.click({ button: 'right' }) + await menu.getByRole('menuitem', { name: 'Copy folder path', exact: true }).waitFor() + expect(await menuLabels(menu)).toEqual(['Show in folder', 'Copy folder path']) + expect(await folder.getAttribute('aria-expanded')).toBe('false') + await menu.getByRole('menuitem', { name: 'Copy folder path', exact: true }).click() + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(join(scaffold.workspaceCwd, 'folder')) + await page.getByText('Copied', { exact: true }).waitFor() + await expect(names.join('\n') + '\n').toMatchFileSnapshot(join(import.meta.dirname, 'expected/context-menus/workspace.txt')) + }) + + it('prepares complete menus, anchors above the frame inset, and treats repeated gestures as separate occurrences', async () => { + onTestFailed(() => saveFailureShot(page, 'context-menus-gestures')) + const file = page.getByRole('button', { name: 'First file', exact: true }) + await file.focus() + await page.keyboard.press('Shift+F10') + await page.getByRole('menuitem', { name: 'Copy file path', exact: true }).waitFor() + await page.keyboard.press('End') + expect(await page.getByRole('menuitem', { name: 'Save as…', exact: true }).count()).toBe(0) + expect(await page.getByRole('menuitem', { name: 'Download', exact: true }).evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('ArrowUp') + expect(await page.getByRole('menuitem', { name: 'Copy file path', exact: true }).evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Enter') + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(join(scaffold.workspaceCwd, 'first.txt')) + expect(await file.evaluate(element => element === document.activeElement)).toBe(true) + await page.evaluate(() => { + document.documentElement.style.setProperty('--dsh-frame-overlay-top', '100px') + const frames: number[] = [] + const observer = new MutationObserver(() => { + for (const menu of document.querySelectorAll('[role="menu"]')) frames.push(menu.querySelectorAll('[role="menuitem"]').length) + }) + observer.observe(document.body, { subtree: true, childList: true }) + Object.assign(window, { menuObservation: { frames, observer } }) + }) + const header = page.locator('[data-session-title]').first() + const target = await header.count() > 0 ? header : page.getByText('Menu foreground', { exact: true }).last() + const box = (await target.boundingBox())! + const point = { x: box.x + box.width / 2, y: box.y + box.height / 2 } + await page.mouse.click(point.x, point.y, { button: 'right' }) + await page.getByRole('menuitem', { name: /Copy.*[Ii][Dd]/ }).waitFor() + expect((await page.getByRole('menu').boundingBox())!.y).toBeLessThan(100) + await page.mouse.click(point.x + 1, point.y, { button: 'right' }) + expect(await page.getByRole('menu').count()).toBe(0) + await file.click({ button: 'right' }) + await page.getByRole('menuitem', { name: 'Copy file path', exact: true }).waitFor() + const previous = await page.getByRole('menu').elementHandle() + await page.getByRole('link', { name: 'Website', exact: true }).click({ button: 'right' }) + await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).waitFor() + expect(await previous!.evaluate(element => element.isConnected)).toBe(false) + await page.keyboard.press('Escape') + const counts = await page.evaluate(() => { + const observed = (window as Window & { menuObservation?: { frames: number[]; observer: MutationObserver } }).menuObservation + if (observed === undefined) throw new Error('Menu observer not installed') + observed.observer.disconnect() + document.documentElement.style.removeProperty('--dsh-frame-overlay-top') + return observed.frames + }) + expect(counts.length).toBeGreaterThan(0) + expect(counts.every(count => count > 0)).toBe(true) + }) + + it('preserves file line navigation, URL text, image format, and existing tab close actions', async () => { + onTestFailed(() => saveFailureShot(page, 'context-menus-content')) + const file = page.getByRole('button', { name: 'First file', exact: true }) + await file.click({ button: 'right' }) + await page.getByRole('menuitem', { name: 'Download', exact: true }).waitFor() + expect(await page.getByRole('menuitem', { name: 'Save as…', exact: true }).count()).toBe(0) + const fileDownloadPromise = page.waitForEvent('download') + await page.getByRole('menuitem', { name: 'Download', exact: true }).click() + const fileDownload = await fileDownloadPromise + expect(fileDownload.suggestedFilename()).toBe('first.txt') + expect(await readFile(await fileDownload.path(), 'utf8')).toBe('FIRST\nSECOND\nTHIRD\n') + const started = page.getByRole('alert').filter({ hasText: 'Download started' }) + await started.waitFor() + expect(await started.getByRole('button', { name: /Show in/ }).count()).toBe(0) + await file.click({ button: 'right' }) + await page.getByRole('menuitem', { name: 'Open in sidebar', exact: true }).click() + await page.locator('[data-document-preview]').getByText('SECOND', { exact: true }).waitFor() + await page.getByRole('link', { name: 'Website', exact: true }).click({ button: 'right' }) + await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).click() + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe('https://example.com/path?q=1#fragment') + await page.getByRole('img', { name: 'Original', exact: true }).click({ button: 'right' }) + await page.getByRole('menuitem', { name: 'Download', exact: true }).waitFor() + await expect((await menuLabels(page.getByRole('menu'))).join('\n') + '\n') + .toMatchFileSnapshot(join(import.meta.dirname, 'expected/context-menus/image.txt')) + expect(await page.getByRole('menuitem', { name: 'Show in folder', exact: true }).count()).toBe(1) + const downloadPromise = page.waitForEvent('download') + await page.getByRole('menuitem', { name: 'Download', exact: true }).click() + const download = await downloadPromise + expect(download.suggestedFilename().endsWith('.gif')).toBe(true) + await page.getByRole('alert').filter({ hasText: 'Download started' }).waitFor() + const path = await download.path() + expect(path).not.toBeNull() + if (path === null) throw new Error('Browser download unavailable') + expect(await readFile(path)).toEqual(GIF) + await page.getByRole('img', { name: 'Original', exact: true }).click({ button: 'right' }) + await page.getByRole('menuitem', { name: 'Copy image', exact: true }).click() + await page.getByText('Copied', { exact: true }).waitFor() + expect(await page.evaluate(async () => (await navigator.clipboard.read()).some(item => item.types.includes('image/png')))).toBe(true) + await page.getByRole('img', { name: 'Remote', exact: true }).click({ button: 'right' }) + expect(await page.getByRole('menuitem', { name: 'Show in folder', exact: true }).isDisabled()).toBe(true) + const remoteDownloadPromise = page.waitForEvent('download') + await page.getByRole('menuitem', { name: 'Download', exact: true }).click() + const remoteDownload = await remoteDownloadPromise + expect(await readFile((await remoteDownload.path()))).toEqual(GIF) + await page.getByRole('img', { name: 'Remote', exact: true }).click({ button: 'right' }) + await page.getByRole('menuitem', { name: 'Copy image', exact: true }).click() + await page.getByText('Copied', { exact: true }).waitFor() + expect(await page.evaluate(async () => (await navigator.clipboard.read()).some(item => item.types.includes('image/png')))).toBe(true) + await page.getByRole('button', { name: 'Second file', exact: true }).click() + await page.locator('[data-document-preview]').getByText('SECOND FILE', { exact: true }).waitFor() + const firstTab = page.locator('[role="tab"]').filter({ hasText: 'first.txt' }).first() + await firstTab.click({ button: 'right' }) + await page.getByRole('menuitem', { name: 'Close', exact: true }).waitFor() + expect(await page.getByRole('menuitem', { name: 'Close', exact: true }).locator('svg[data-icon]').count()).toBe(1) + await page.getByRole('menuitem', { name: 'Close', exact: true }).click() + expect(await firstTab.count()).toBe(0) + expect(await page.locator('[data-document-preview]').getByText('SECOND FILE', { exact: true }).count()).toBe(1) + expect(tripwire.pageErrors).toEqual([]) + }) + it('keeps original preview open when dismissing its menu and fits both themes at the viewport edge', async () => { + onTestFailed(() => saveFailureShot(page, 'context-menus-preview')) + await page.getByRole('button', { name: 'View full image: Original', exact: true }).click() + const preview = page.getByRole('dialog') + await preview.waitFor() + for (const colorScheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme }) + await preview.getByRole('img').evaluate(element => element.dispatchEvent(new MouseEvent('contextmenu', { clientX: 1270, clientY: 735, bubbles: true }))) + const menu = page.getByRole('menu') + await menu.getByRole('menuitem', { name: 'Copy image', exact: true }).waitFor() + expect(await menu.getByRole('menuitem').evaluateAll(rows => rows.every(row => row.querySelector('svg[data-icon]')))).toBe(true) + const box = await menu.boundingBox() + expect(box).not.toBeNull() + expect(box!.x).toBeGreaterThan(1000) + expect(box!.y).toBeGreaterThan(500) + expect(box!.x + box!.width).toBeLessThanOrEqual(1291) + expect(box!.y + box!.height).toBeLessThanOrEqual(768) + await saveFailureShot(page, `context-menus-${colorScheme}`) + await page.keyboard.press('Escape') + expect(await menu.count()).toBe(0) + expect(await preview.count()).toBe(1) + } + await page.keyboard.press('Escape') + expect(await preview.count()).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + }) + + it('offers completed Desktop destinations as toast text actions without enabling remote-image menu reveal', async () => { + const native = await browser.newPage({ viewport: { width: 1291, height: 768 }, locale: 'en-US' }) + const opened = vi.spyOn(scaffold.ctx.sessionController, 'openWorkspacePath').mockResolvedValue({ opened: true }) + try { + const destinations = { download: join(scaffold.workspaceCwd, 'downloaded.gif'), saveAs: join(scaffold.workspaceCwd, 'saved.txt') } + await native.addInitScript(({ platform, destinations }) => { + Object.defineProperty(navigator, 'platform', { value: platform }) + Object.defineProperty(globalThis, 'dshDesktop', { value: { protocolVersion: 1, fileActions: { + save: async ({ mode }: { mode: 'download' | 'saveAs' }) => ({ status: 'saved', path: destinations[mode] }), + } } }) + }, { platform, destinations }) + await native.route('https://images.example/original.gif', route => route.fulfill({ body: GIF, contentType: 'image/gif' })) + await native.goto(scaffold.authenticatedUrl) + await native.evaluate((platform) => { + document.documentElement.dataset.platform = platform === 'MacIntel' ? 'darwin' : platform === 'Win32' ? 'win32' : 'linux' + }, platform) + const group = native.locator('[data-row-key^="workspace:"]').filter({ hasText: 'Ungrouped' }) + if (await group.getAttribute('aria-expanded') !== 'true') await group.click() + await native.locator('[data-row-key="session:context-menu-first"]').click() + await native.getByText('CONTEXT_MENU_READY', { exact: true }).waitFor() + for (const [mode, label, text, theme] of [ + ['download', 'Download', 'Download complete', 'light'], + ['saveAs', 'Save as…', 'Saved', 'dark'], + ] as const) { + await native.emulateMedia({ colorScheme: theme }) + const trigger = mode === 'download' + ? native.getByRole('img', { name: 'Remote', exact: true }) + : native.getByRole('button', { name: 'First file', exact: true }) + await trigger.click({ button: 'right' }) + await native.getByRole('menuitem', { name: label, exact: true }).click() + const notice = native.getByRole('alert').filter({ hasText: text }) + const action = notice.getByRole('button', { name: platform === 'MacIntel' ? 'Show in Finder' : 'Show in folder', exact: true }) + await action.click() + await notice.waitFor({ state: 'hidden' }) + await expect.poll(() => opened.mock.calls.at(-1)?.[0]).toEqual({ path: destinations[mode], action: 'reveal' }) + } + expect(opened).toHaveBeenCalledTimes(2) + await native.getByRole('img', { name: 'Remote', exact: true }).click({ button: 'right' }) + const reveal = native.getByRole('menuitem', { name: 'Show in folder', exact: true }) + await reveal.waitFor() + expect(await reveal.isDisabled()).toBe(true) + } finally { + await native.close() + opened.mockRestore() + } + }) +}) diff --git a/apps/web/tests/cua-optin.e2e.ts b/apps/web/tests/cua-optin.e2e.ts index a9ddcde869..c5900519c6 100644 --- a/apps/web/tests/cua-optin.e2e.ts +++ b/apps/web/tests/cua-optin.e2e.ts @@ -63,9 +63,9 @@ it.skipIf(process.platform !== 'darwin').each([ const dialog = page.getByRole('dialog', { name: '添加插件', exact: true }) await dialog.getByRole('textbox', { name: '包名或地址', exact: true }).fill('@deepseek-ai/dsh-cua-bundle') await dialog.getByRole('button', { name: '安装', exact: true }).click() - const ready = page.getByRole('dialog', { name: '插件已随 DSH 提供', exact: true }) + const ready = page.getByRole('dialog', { name: '已安装', exact: true }) await ready.waitFor() - expect(await ready.getByText('无需下载,启用即可使用', { exact: true }).count()).toBe(1) + expect(await ready.getByText('无需下载,启用即可使用', { exact: true }).count()).toBe(0) return ready.getByRole('button', { name: '立即启用', exact: true }) } const enableNow = await offerCua() @@ -199,8 +199,7 @@ it.skipIf(process.platform !== 'darwin').each([ const program = 'globalThis.counter = (globalThis.counter ?? 0) + 1' expect((await runtime.run(runtime.resolve({ program, bindings: [], stateOwner: owner }))).value).toBe(1) await toggle.click() - await toggle.waitFor({ state: 'hidden' }) - await card.waitFor({ state: 'hidden' }) + await toggle.and(page.locator('[aria-checked="false"]')).waitFor({ state: 'visible' }) expect(scaffold.ctx.get('computerUse')).toBeUndefined() expect(runtimeFiber() === persistentRuntimeFiber).toBe(true) expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault) @@ -211,7 +210,7 @@ it.skipIf(process.platform !== 'darwin').each([ } expect((await runtime.run(runtime.resolve({ program, bindings: [], stateOwner: owner }))).value).toBe(2) expect(await readFile(settingsPath, 'utf8')).toBe(saved) - await (await offerCua()).click() + await toggle.click() await toggle.and(page.locator('[aria-checked="true"]')).waitFor({ state: 'visible' }) await setup.waitFor() expect(await setup.getByText('Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) @@ -249,9 +248,8 @@ it.skipIf(process.platform !== 'darwin').each([ expect.objectContaining({ id: 'agent-preset-registry', config: { default: 'standard', selectedDefault: 'ptc' } }), ])) await toggle.click() - await toggle.waitFor({ state: 'hidden' }) - await card.waitFor({ state: 'hidden' }) - await (await offerCua()).click() + await toggle.and(page.locator('[aria-checked="false"]')).waitFor({ state: 'visible' }) + await toggle.click() await toggle.and(page.locator('[aria-checked="true"]')).waitFor({ state: 'visible' }) await setup.waitFor() expect(await setup.getByText('Computer Use 插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1) diff --git a/apps/web/tests/default-model.e2e.ts b/apps/web/tests/default-model.e2e.ts index 9625333287..fa6c518add 100644 --- a/apps/web/tests/default-model.e2e.ts +++ b/apps/web/tests/default-model.e2e.ts @@ -563,7 +563,7 @@ describe('web e2e: the composer model switch is the default for later sessions', for (const palette of headingPalettes) { expect(palette.headingFills, `${palette.platform}, dark=${String(palette.dark)}`) .toEqual(['rgba(0, 0, 0, 0)']) - expect(palette.menuFill).toBe(palette.dark ? 'rgba(67, 69, 74, 0.45)' : 'rgba(248, 249, 250, 0.58)') + expect(palette.menuFill).toBe(palette.dark ? 'rgba(48, 49, 54, 0.64)' : 'rgba(252, 253, 254, 0.7)') expect(palette.searchBorder).toBe('rgba(0, 0, 0, 0)') expect(palette.positions).toEqual(['sticky']) expect(palette.headingRadii).toEqual([palette.platform === 'darwin' ? '0px' : palette.optionRadius]) diff --git a/apps/web/tests/document-preview.e2e.ts b/apps/web/tests/document-preview.e2e.ts index 79a5ed4bdb..a3d2eb21e6 100644 --- a/apps/web/tests/document-preview.e2e.ts +++ b/apps/web/tests/document-preview.e2e.ts @@ -714,7 +714,7 @@ else process.exit(1); const initialFilesClose = await filesTab.locator('[data-dockkit-tab-close]').count() expect(initialFilesClose).toBe(1) await filesTab.click({ button: 'right' }) - expect(await page.locator('[data-dockkit-tab-menu]:visible').count()).toBe(1) + await page.locator('[data-context-menu][role="menu"]').waitFor() await page.keyboard.press('Escape') await addTab.waitFor({ state: 'visible' }) const initialAdd = await addTab.count() diff --git a/apps/web/tests/expected/client-plugin-live/session-actions.expected.md b/apps/web/tests/expected/client-plugin-live/session-actions.expected.md index 51df861f77..93f241e0fc 100644 --- a/apps/web/tests/expected/client-plugin-live/session-actions.expected.md +++ b/apps/web/tests/expected/client-plugin-live/session-actions.expected.md @@ -2,8 +2,10 @@ - menuitem "Pin session" - menuitem "Rename" - menuitem "Fork session" - - menuitem "Archive session" + - separator - menuitem "Copy Session ID" - separator - menuitem "Export session" - menuitem "Copy session ID" + - separator + - menuitem "Archive session" diff --git a/apps/web/tests/expected/client-plugin-live/session-trailing.expected.json b/apps/web/tests/expected/client-plugin-live/session-trailing.expected.json index 8b5c4cb664..83f9ecd3fb 100644 --- a/apps/web/tests/expected/client-plugin-live/session-trailing.expected.json +++ b/apps/web/tests/expected/client-plugin-live/session-trailing.expected.json @@ -86,7 +86,7 @@ "Fixture badge", "Fixture section" ], - "time": true, + "time": false, "pinned": false, "actions": true }, @@ -96,7 +96,7 @@ "Fixture badge", "Fixture section" ], - "time": true, + "time": false, "pinned": false, "actions": true }, @@ -106,7 +106,7 @@ "Fixture badge", "Fixture section" ], - "time": true, + "time": false, "pinned": false, "actions": true }, @@ -116,8 +116,8 @@ "Fixture badge", "Fixture section" ], - "time": true, - "pinned": true, + "time": false, + "pinned": false, "actions": true }, { @@ -136,7 +136,7 @@ "Fixture badge", "Fixture section" ], - "time": true, + "time": false, "pinned": false, "actions": true } diff --git a/apps/web/tests/expected/context-menus/image.txt b/apps/web/tests/expected/context-menus/image.txt new file mode 100644 index 0000000000..a8090be657 --- /dev/null +++ b/apps/web/tests/expected/context-menus/image.txt @@ -0,0 +1,3 @@ +Copy image +Download +Show in folder diff --git a/apps/web/tests/expected/context-menus/session.txt b/apps/web/tests/expected/context-menus/session.txt new file mode 100644 index 0000000000..5468d20e51 --- /dev/null +++ b/apps/web/tests/expected/context-menus/session.txt @@ -0,0 +1,6 @@ +Pin session +Rename +Fork session +Copy Session ID +Show in folder +Archive session diff --git a/apps/web/tests/expected/context-menus/workspace.txt b/apps/web/tests/expected/context-menus/workspace.txt new file mode 100644 index 0000000000..93c401728b --- /dev/null +++ b/apps/web/tests/expected/context-menus/workspace.txt @@ -0,0 +1,3 @@ +Rename +Show in folder +Delete workspace diff --git a/apps/web/tests/expected/forge-panel/branch-details.expected.md b/apps/web/tests/expected/forge-panel/branch-details.expected.md new file mode 100644 index 0000000000..8c348d423a --- /dev/null +++ b/apps/web/tests/expected/forge-panel/branch-details.expected.md @@ -0,0 +1 @@ +- 'tooltip "Current branch: feature/a-long-current-branch-name-for-mobile-review"' diff --git a/apps/web/tests/expected/forge-panel/changes-view.expected.md b/apps/web/tests/expected/forge-panel/changes-view.expected.md index 1a6db5161e..b6c825a833 100644 --- a/apps/web/tests/expected/forge-panel/changes-view.expected.md +++ b/apps/web/tests/expected/forge-panel/changes-view.expected.md @@ -8,65 +8,64 @@ - button "全部折叠" - button "左右对比" [pressed] - button "自动换行" [pressed] -- button "收起 panel.ts" [expanded] -- 'button "复制路径: src/panel.ts"': src/panel.ts -- text: +2 −2 -- button "panel.ts 的更多操作" -- button "选择第 L1 行": "1" -- text: export const n1 = 1 -- button "选择第 R1 行": "1" -- text: export const n1 = 1 -- button "选择第 L2 行": "2" -- text: export const n2 = 2 -- button "选择第 R2 行": "2" -- text: export const n2 = 'two' -- button "选择第 L3 行": "3" -- text: export const n3 = 3 -- button "选择第 R3 行": "3" -- text: export const n3 = 3 -- button "选择第 L4 行": "4" -- text: export const n4 = 4 -- button "选择第 R4 行": "4" -- text: export const n4 = 4 -- button "选择第 L5 行": "5" -- text: export const n5 = 5 -- button "选择第 R5 行": "5" -- text: export const n5 = 5 -- button "6 行未变更" -- button "选择第 L12 行": "12" -- text: export const n12 = 12 -- button "选择第 R12 行": "12" -- text: export const n12 = 12 -- button "选择第 L13 行": "13" -- text: export const n13 = 13 -- button "选择第 R13 行": "13" -- text: export const n13 = 13 -- button "选择第 L14 行": "14" -- text: export const n14 = 14 -- button "选择第 R14 行": "14" -- text: export const n14 = 14 -- button "选择第 L15 行": "15" -- text: export const n15 = 15 -- button "选择第 R15 行": "15" -- text: export const n15 = 'fifteen' -- button "选择第 L16 行": "16" -- text: export const n16 = 16 -- button "选择第 R16 行": "16" -- text: export const n16 = 16 -- button "选择第 L17 行": "17" -- text: export const n17 = 17 -- button "选择第 R17 行": "17" -- text: export const n17 = 17 -- button "选择第 L18 行": "18" -- text: export const n18 = 18 -- button "选择第 R18 行": "18" -- text: export const n18 = 18 -- button "其余未变更的行" -- button "收起 panel.md" [expanded] -- 'button "复制路径: docs/panel.md"': docs/panel.md -- text: 新文件 +2 −0 -- button "panel.md 的更多操作" -- button "选择第 R1 行": "1" -- text: "+ # Panel" -- button "选择第 R2 行": "2" -- text: + Shows the change requests of a Session. +- region "全部 2 个文件": + - button "收起 panel.ts" [expanded] + - text: src/panel.ts +2 −2 + - button "panel.ts 的更多操作" + - button "选择第 L1 行": "1" + - text: export const n1 = 1 + - button "选择第 R1 行": "1" + - text: export const n1 = 1 + - button "选择第 L2 行": "2" + - text: export const n2 = 2 + - button "选择第 R2 行": "2" + - text: export const n2 = 'two' + - button "选择第 L3 行": "3" + - text: export const n3 = 3 + - button "选择第 R3 行": "3" + - text: export const n3 = 3 + - button "选择第 L4 行": "4" + - text: export const n4 = 4 + - button "选择第 R4 行": "4" + - text: export const n4 = 4 + - button "选择第 L5 行": "5" + - text: export const n5 = 5 + - button "选择第 R5 行": "5" + - text: export const n5 = 5 + - button "6 行未变更" + - button "选择第 L12 行": "12" + - text: export const n12 = 12 + - button "选择第 R12 行": "12" + - text: export const n12 = 12 + - button "选择第 L13 行": "13" + - text: export const n13 = 13 + - button "选择第 R13 行": "13" + - text: export const n13 = 13 + - button "选择第 L14 行": "14" + - text: export const n14 = 14 + - button "选择第 R14 行": "14" + - text: export const n14 = 14 + - button "选择第 L15 行": "15" + - text: export const n15 = 15 + - button "选择第 R15 行": "15" + - text: export const n15 = 'fifteen' + - button "选择第 L16 行": "16" + - text: export const n16 = 16 + - button "选择第 R16 行": "16" + - text: export const n16 = 16 + - button "选择第 L17 行": "17" + - text: export const n17 = 17 + - button "选择第 R17 行": "17" + - text: export const n17 = 17 + - button "选择第 L18 行": "18" + - text: export const n18 = 18 + - button "选择第 R18 行": "18" + - text: export const n18 = 18 + - button "其余未变更的行" + - button "收起 panel.md" [expanded] + - text: docs/panel.md 新文件 +2 −0 + - button "panel.md 的更多操作" + - button "选择第 R1 行": "1" + - text: "+ # Panel" + - button "选择第 R2 行": "2" + - text: + Shows the change requests of a Session. diff --git a/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md b/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md index f1231bbb8f..5873dec5ae 100644 --- a/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md +++ b/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md @@ -8,69 +8,68 @@ - button "全部折叠" - button "左右对比" [pressed] - button "自动换行" [pressed] -- button "文件树" [expanded] [pressed] -- button "收起 panel.ts" [expanded] -- 'button "复制路径: src/panel.ts"': src/panel.ts -- text: +2 −2 -- button "panel.ts 的更多操作" -- button "选择第 L1 行": "1" -- text: export const n1 = 1 -- button "选择第 R1 行": "1" -- text: export const n1 = 1 -- button "选择第 L2 行": "2" -- text: export const n2 = 2 -- button "选择第 R2 行": "2" -- text: export const n2 = 'two' -- button "选择第 L3 行": "3" -- text: export const n3 = 3 -- button "选择第 R3 行": "3" -- text: export const n3 = 3 -- button "选择第 L4 行": "4" -- text: export const n4 = 4 -- button "选择第 R4 行": "4" -- text: export const n4 = 4 -- button "选择第 L5 行": "5" -- text: export const n5 = 5 -- button "选择第 R5 行": "5" -- text: export const n5 = 5 -- button "6 行未变更" -- button "选择第 L12 行": "12" -- text: export const n12 = 12 -- button "选择第 R12 行": "12" -- text: export const n12 = 12 -- button "选择第 L13 行": "13" -- text: export const n13 = 13 -- button "选择第 R13 行": "13" -- text: export const n13 = 13 -- button "选择第 L14 行": "14" -- text: export const n14 = 14 -- button "选择第 R14 行": "14" -- text: export const n14 = 14 -- button "选择第 L15 行": "15" -- text: export const n15 = 15 -- button "选择第 R15 行": "15" -- text: export const n15 = 'fifteen' -- button "选择第 L16 行": "16" -- text: export const n16 = 16 -- button "选择第 R16 行": "16" -- text: export const n16 = 16 -- button "选择第 L17 行": "17" -- text: export const n17 = 17 -- button "选择第 R17 行": "17" -- text: export const n17 = 17 -- button "选择第 L18 行": "18" -- text: export const n18 = 18 -- button "选择第 R18 行": "18" -- text: export const n18 = 18 -- button "其余未变更的行" -- button "收起 panel.md" [expanded] -- 'button "复制路径: docs/panel.md"': docs/panel.md -- text: 新文件 +2 −0 -- button "panel.md 的更多操作" -- button "选择第 R1 行": "1" -- text: "+ # Panel" -- button "选择第 R2 行": "2" -- text: + Shows the change requests of a Session. +- button "将文件树移到右侧" [expanded] +- region "全部 2 个文件": + - button "收起 panel.ts" [expanded] + - text: src/panel.ts +2 −2 + - button "panel.ts 的更多操作" + - button "选择第 L1 行": "1" + - text: export const n1 = 1 + - button "选择第 R1 行": "1" + - text: export const n1 = 1 + - button "选择第 L2 行": "2" + - text: export const n2 = 2 + - button "选择第 R2 行": "2" + - text: export const n2 = 'two' + - button "选择第 L3 行": "3" + - text: export const n3 = 3 + - button "选择第 R3 行": "3" + - text: export const n3 = 3 + - button "选择第 L4 行": "4" + - text: export const n4 = 4 + - button "选择第 R4 行": "4" + - text: export const n4 = 4 + - button "选择第 L5 行": "5" + - text: export const n5 = 5 + - button "选择第 R5 行": "5" + - text: export const n5 = 5 + - button "6 行未变更" + - button "选择第 L12 行": "12" + - text: export const n12 = 12 + - button "选择第 R12 行": "12" + - text: export const n12 = 12 + - button "选择第 L13 行": "13" + - text: export const n13 = 13 + - button "选择第 R13 行": "13" + - text: export const n13 = 13 + - button "选择第 L14 行": "14" + - text: export const n14 = 14 + - button "选择第 R14 行": "14" + - text: export const n14 = 14 + - button "选择第 L15 行": "15" + - text: export const n15 = 15 + - button "选择第 R15 行": "15" + - text: export const n15 = 'fifteen' + - button "选择第 L16 行": "16" + - text: export const n16 = 16 + - button "选择第 R16 行": "16" + - text: export const n16 = 16 + - button "选择第 L17 行": "17" + - text: export const n17 = 17 + - button "选择第 R17 行": "17" + - text: export const n17 = 17 + - button "选择第 L18 行": "18" + - text: export const n18 = 18 + - button "选择第 R18 行": "18" + - text: export const n18 = 18 + - button "其余未变更的行" + - button "收起 panel.md" [expanded] + - text: docs/panel.md 新文件 +2 −0 + - button "panel.md 的更多操作" + - button "选择第 R1 行": "1" + - text: "+ # Panel" + - button "选择第 R2 行": "2" + - text: + Shows the change requests of a Session. - separator "调整文件树宽度" - navigation "全部 2 个文件": - textbox "筛选文件…": src diff --git a/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md b/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md new file mode 100644 index 0000000000..eef3d4c6df --- /dev/null +++ b/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md @@ -0,0 +1,11 @@ +- text: 与 origin/main 比较,包含未提交的修改 +- button "创建变更请求" +- button "分支" +- button "全部 0 个文件" [disabled] +- button "刷新变更" +- button "全部展开" [disabled] +- button "左右对比" [pressed] +- button "自动换行" [pressed] +- status: + - text: 无法完整读取 Git 过滤器配置,尚未执行比较。请检查 Git 配置和读取上限后重试 + - button "重试" diff --git a/apps/web/tests/expected/forge-panel/full-access.expected.md b/apps/web/tests/expected/forge-panel/full-access.expected.md new file mode 100644 index 0000000000..3f45ecb592 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/full-access.expected.md @@ -0,0 +1,4 @@ +- button "本地变更" +- text: HEAD → origin/main +- button "查看本会话的变更:1 个文件,新增 1 行,删除 0 行": +1 −0 1 个文件 +- button "创建变更请求" diff --git a/apps/web/tests/expected/forge-panel/local-card.expected.md b/apps/web/tests/expected/forge-panel/local-card.expected.md new file mode 100644 index 0000000000..24058934d3 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/local-card.expected.md @@ -0,0 +1,4 @@ +- button "Local changes" +- text: HEAD → origin/main +- 'button "View the changes of this Session: 60 files, 60 lines added, 0 lines deleted"': +60 −0 60 files +- button "Create change request" diff --git a/apps/web/tests/expected/forge-panel/panel.expected.md b/apps/web/tests/expected/forge-panel/panel.expected.md index 3450262cd7..f71db0bd64 100644 --- a/apps/web/tests/expected/forge-panel/panel.expected.md +++ b/apps/web/tests/expected/forge-panel/panel.expected.md @@ -12,6 +12,6 @@ - button "复制变更请求链接" - 'button "从本会话移除 #7"' - 'button "收起 #7" [expanded]' - - button "检查 1 项失败 · 1 项通过" + - button "检查 已加载 1 项检查,仍有更多" - text: 评审 等待评审 · 1 条未解决讨论 合并 无冲突 - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 diff --git a/apps/web/tests/expected/forge-panel/reference.expected.md b/apps/web/tests/expected/forge-panel/reference.expected.md index cc5f2e87f6..4a34c8f7c9 100644 --- a/apps/web/tests/expected/forge-panel/reference.expected.md +++ b/apps/web/tests/expected/forge-panel/reference.expected.md @@ -7,6 +7,6 @@ - button "复制变更请求链接" - 'button "从本会话移除 #7"' - 'button "收起 #7" [expanded]' - - button "检查 1 项失败 · 1 项通过" + - button "检查 已加载 1 项检查,仍有更多" - text: 评审 等待评审 · 1 条未解决讨论 合并 无冲突 - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 diff --git a/apps/web/tests/expected/forge-panel/review-guide.expected.md b/apps/web/tests/expected/forge-panel/review-guide.expected.md new file mode 100644 index 0000000000..a56f8cd077 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-guide.expected.md @@ -0,0 +1 @@ +- button "代码审查和变更 查看代码变更与本会话的变更请求" diff --git a/apps/web/tests/expected/forge-panel/review-summary-required.expected.md b/apps/web/tests/expected/forge-panel/review-summary-required.expected.md new file mode 100644 index 0000000000..3e384b28e1 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-summary-required.expected.md @@ -0,0 +1,14 @@ +- dialog "提交评审": + - heading "提交评审" [level=2] + - button "关闭" + - text: 待提交评论(1) + - textbox "评审总结…" + - status: 请求更改时,请填写评审总结 + - radio "评论" + - text: 评论 + - radio "批准" + - text: 批准 + - radio "请求更改" [checked] + - text: 请求更改 + - button "取消" + - button "提交评审" [disabled] diff --git a/apps/web/tests/expected/forge-panel/submit-review.expected.md b/apps/web/tests/expected/forge-panel/submit-review.expected.md index c06de70320..0687f7ba99 100644 --- a/apps/web/tests/expected/forge-panel/submit-review.expected.md +++ b/apps/web/tests/expected/forge-panel/submit-review.expected.md @@ -3,6 +3,7 @@ - button "关闭" - text: 待提交评论(1) - textbox "评审总结…": 需要补充边界检查 + - status: 请求更改时,请填写评审总结 - radio "评论" - text: 评论 - radio "批准" diff --git a/apps/web/tests/expected/forge-panel/worktree-option.expected.md b/apps/web/tests/expected/forge-panel/worktree-option.expected.md new file mode 100644 index 0000000000..c9a85b8723 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/worktree-option.expected.md @@ -0,0 +1,3 @@ +- button "当前分支:main": main +- checkbox "新建工作树" +- text: 新建工作树 diff --git a/apps/web/tests/expected/markdown-colon-file-links.md b/apps/web/tests/expected/markdown-colon-file-links.md new file mode 100644 index 0000000000..fe7031c9f0 --- /dev/null +++ b/apps/web/tests/expected/markdown-colon-file-links.md @@ -0,0 +1,21 @@ +- paragraph: + - button "Relative colon:24–30" + - text: · + - button "Absolute colon:30" + - text: · + - button "Fragment:12" + - text: · + - button "Column:24:5" + - text: · + - button "Zero line" + - text: · + - button "Reversed range" + - text: · + - link "Bare URL": + - /url: index.ts:24 + - text: · Blocked script · + - link "Development server": + - /url: localhost:3000 + - text: · + - link "Mail": + - /url: mailto:10086 diff --git a/apps/web/tests/expected/menu-material/materials.expected.json b/apps/web/tests/expected/menu-material/materials.expected.json index 301564bef3..b0abc51804 100644 --- a/apps/web/tests/expected/menu-material/materials.expected.json +++ b/apps/web/tests/expected/menu-material/materials.expected.json @@ -1,24 +1,24 @@ { "web-light": { - "fill": "rgba(248, 249, 250, 0.58)", + "fill": "rgba(252, 253, 254, 0.7)", "blur": "blur(40px) saturate(1.5)", "radius": "16px", "shadow": "rgba(0, 0, 0, 0.04) 0px 0px 0px 0.5px, rgba(0, 0, 0, 0.04) 0px 3px 8px 0px, rgba(0, 0, 0, 0.05) 0px 0px 20px 0px" }, "web-dark": { - "fill": "rgba(67, 69, 74, 0.45)", + "fill": "rgba(48, 49, 54, 0.64)", "blur": "blur(40px) saturate(1.5)", "radius": "16px", "shadow": "rgba(255, 255, 255, 0.16) 0px 0px 0px 0.5px, rgba(0, 0, 0, 0.04) 0px 3px 8px 0px, rgba(0, 0, 0, 0.05) 0px 0px 20px 0px" }, "darwin-light": { - "fill": "rgba(248, 249, 250, 0.58)", + "fill": "rgba(252, 253, 254, 0.7)", "blur": "blur(40px) saturate(1.5)", "radius": "16px", "shadow": "rgba(0, 0, 0, 0.04) 0px 0px 0px 0.5px, rgba(0, 0, 0, 0.04) 0px 3px 8px 0px, rgba(0, 0, 0, 0.05) 0px 0px 20px 0px" }, "darwin-dark": { - "fill": "rgba(67, 69, 74, 0.45)", + "fill": "rgba(48, 49, 54, 0.64)", "blur": "blur(40px) saturate(1.5)", "radius": "16px", "shadow": "rgba(255, 255, 255, 0.16) 0px 0px 0px 0.5px, rgba(0, 0, 0, 0.04) 0px 3px 8px 0px, rgba(0, 0, 0, 0.05) 0px 0px 20px 0px" diff --git a/apps/web/tests/expected/menu-material/session-menu.expected.md b/apps/web/tests/expected/menu-material/session-menu.expected.md index ebb1786386..c7c535b9e4 100644 --- a/apps/web/tests/expected/menu-material/session-menu.expected.md +++ b/apps/web/tests/expected/menu-material/session-menu.expected.md @@ -2,5 +2,7 @@ - menuitem "Pin session" - menuitem "Rename" - menuitem "Fork session" - - menuitem "Archive session" + - separator - menuitem "Copy Session ID" + - separator + - menuitem "Archive session" diff --git a/apps/web/tests/expected/plugin-install-registry/installed.expected.md b/apps/web/tests/expected/plugin-install-registry/installed.expected.md index 2ddc96e196..d198049eca 100644 --- a/apps/web/tests/expected/plugin-install-registry/installed.expected.md +++ b/apps/web/tests/expected/plugin-install-registry/installed.expected.md @@ -15,4 +15,5 @@ - text: 已完成 $ pnpm add mirrored-package - button "复制" - text: Installed from the registry pnpm names + - paragraph: 完整日志:{{cwd}}/.dsh-home/profiles/scaffold/.plugin-manager/logs/operation-{{suffix}}/pnpm.log - button "立即启用" diff --git a/apps/web/tests/expected/plugin-install-silent-failure/failed.expected.md b/apps/web/tests/expected/plugin-install-silent-failure/failed.expected.md new file mode 100644 index 0000000000..61630bd8b2 --- /dev/null +++ b/apps/web/tests/expected/plugin-install-silent-failure/failed.expected.md @@ -0,0 +1,14 @@ +- dialog "插件安装失败": + - button "返回编辑": 编辑 + - button "关闭" + - alert: 插件安装失败 + - paragraph: 安装命令失败,原因见安装详情 + - paragraph: silent-package + - paragraph: 版本 1.0.0 + - button "收起安装详情" [expanded] + - button "重试" + - paragraph: 安装位置:{{cwd}}/.dsh-home/profiles/scaffold + - text: 失败 $ pnpm add silent-package 退出码 1 + - button "复制" + - text: "Command failed with exit code 1: {{node}} add silent-package" + - paragraph: 完整日志:{{cwd}}/.dsh-home/profiles/scaffold/.plugin-manager/logs/operation-{{suffix}}/pnpm.log diff --git a/apps/web/tests/expected/plugin-manager/header-natural-motion.expected.md b/apps/web/tests/expected/plugin-manager/header-natural-motion.expected.md index 6deb4441c6..648b1e5f3b 100644 --- a/apps/web/tests/expected/plugin-manager/header-natural-motion.expected.md +++ b/apps/web/tests/expected/plugin-manager/header-natural-motion.expected.md @@ -7,4 +7,4 @@ - Tabs / 600px: resting title 28, actions 97, tabs 96; pinned actions 17, tabs 16, bar 66; stable range, reversible coordinates, same controls. - Tabs / 470px: resting title 28, actions 97, tabs 96; pinned actions 17, tabs 16, bar 66; stable range, reversible coordinates, same controls. - Tabs / 390px: resting title 28, actions 97, tabs 96; pinned actions 17, tabs 16, bar 66; stable range, reversible coordinates, same controls. -- Tabs / 334px: resting title 28, actions 146, tabs 96; pinned actions 66, tabs 16, bar 114; stable range, reversible coordinates, same controls. +- Tabs / 320px: resting title 28, actions 146, tabs 96; pinned actions 66, tabs 16, bar 114; stable range, reversible coordinates, same controls. diff --git a/apps/web/tests/expected/shortcuts-panels/tab-menu.expected.md b/apps/web/tests/expected/shortcuts-panels/tab-menu.expected.md index c8ab6426ab..16362fff3a 100644 --- a/apps/web/tests/expected/shortcuts-panels/tab-menu.expected.md +++ b/apps/web/tests/expected/shortcuts-panels/tab-menu.expected.md @@ -1,2 +1,3 @@ - menu: - menuitem "Close" + - menuitem "Close Other Tabs" [disabled] diff --git a/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md b/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md index ebb1786386..6724e2373d 100644 --- a/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md +++ b/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md @@ -2,5 +2,8 @@ - menuitem "Pin session" - menuitem "Rename" - menuitem "Fork session" - - menuitem "Archive session" + - separator - menuitem "Copy Session ID" + - menuitem "Show in Finder" + - separator + - menuitem "Archive session" diff --git a/apps/web/tests/expected/sidebar-drawer.expected.md b/apps/web/tests/expected/sidebar-drawer.expected.md index 466c2d6ccf..fafb1402b2 100644 --- a/apps/web/tests/expected/sidebar-drawer.expected.md +++ b/apps/web/tests/expected/sidebar-drawer.expected.md @@ -16,7 +16,9 @@ folded landscape: 951px frame splits at 475.5px without a resize handle; unfoldi fold transitions: sidebar controls follow the divider in both directions; reduced motion changes width without animation drawer mask: opacity transitions from 0 to 1 on open and 1 to 0 on close reduced motion: drawer and mask settle without transitions -touch selected Session: More remains visible; archive and pin stay in its menu; pin marker retained +Web header: only the sidebar opener remains, with 48px leading clearance +below 768px: plugin and automation pages use 20px insets; Web view tabs align at 20px, while Desktop and wider Web tabs retain 28px +touch selected Session: More remains visible; update time is hidden; pinned rows offer Unpin before More with Workspace action spacing touch Workspace: actions appear only while expanded, including after folding the focused row fine pointer: folded Workspace actions remain available on hover fine pointer: selected Session actions stay hidden until hover, including at 390px diff --git a/apps/web/tests/fixtures/markdown-colon-file-links/session.v3.jsonl b/apps/web/tests/fixtures/markdown-colon-file-links/session.v3.jsonl new file mode 100644 index 0000000000..7ef9426138 --- /dev/null +++ b/apps/web/tests/fixtures/markdown-colon-file-links/session.v3.jsonl @@ -0,0 +1,10 @@ +{"version":3,"isSeeded":false,"createdAt":0,"cwd":"{{cwd}}","delegationDepth":0,"type":"session","id":"{{session:1}}"} +{"type":"turn/start","data":{"turn":1}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt"},"id":"{{message:1}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Link src/example.txt using relative :24-30, absolute :30, and relative #L12 destinations, plus line/column and invalid locations, localhost:3000, index.ts:24, mailto:10086, and a blocked script link."}],"source":{"kind":"user","rpcId":"{{rpc:1}}"},"role":"user","id":"{{message:2}}"},"surfaceOp":"append"} +{"type":"session/title","data":{"title":"Colon file references","messageSeqs":[3],"source":{"kind":"fallback"}}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}","messagePrefix":["{{messagePrefix}}"]},"reason":"initial"}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"[Relative colon:24–30](src/example.txt:24-30) · [Absolute colon:30]({{cwd}}/src/example.txt:30) · [Fragment:12](src/example.txt#L12) · [Column:24:5](src/example.txt:24:5) · [Zero line](src/example.txt:0) · [Reversed range](src/example.txt:30-24) · [Bare URL](index.ts:24) · [Blocked script](javascript:alert) · [Development server](localhost:3000) · [Mail](mailto:10086)"}],"source":{"provider":"deepseek-official","model":"deepseek-v4-flash","kind":"model"},"id":"{{message:3}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["[Relative colon:24–30](src/example.txt:24-30) · [Absolute colon:30]({{cwd}}/src/example.txt:30) · [Fragment:12](src/example.txt#L12) · [Column:24:5](src/example.txt:24:5) · [Zero line](src/example.txt:0) · [Reversed range](src/example.txt:30-24) · [Bare URL](index.ts:24) · [Blocked script](javascript:alert) · [Development server](localhost:3000) · [Mail](mailto:10086)"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"[Relative colon:24–30](src/example.txt:24-30) · [Absolute colon:30]({{cwd}}/src/example.txt:30) · [Fragment:12](src/example.txt#L12) · [Column:24:5](src/example.txt:24:5) · [Zero line](src/example.txt:0) · [Reversed range](src/example.txt:30-24) · [Bare URL](index.ts:24) · [Blocked script](javascript:alert) · [Development server](localhost:3000) · [Mail](mailto:10086)"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":1}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/apps/web/tests/fixtures/plugins/fixture-live-client/client.js b/apps/web/tests/fixtures/plugins/fixture-live-client/client.js index 1c884c568f..db9eab44b9 100644 --- a/apps/web/tests/fixtures/plugins/fixture-live-client/client.js +++ b/apps/web/tests/fixtures/plugins/fixture-live-client/client.js @@ -101,8 +101,7 @@ window.__ModuleLoader__.load({ } }) ctx.slots.inject('sidebar.workspaces.session.menu.item', function* () { - // The shipped rows end at Session ID (450); these follow as one group, - // opened by the export row's hairline. + // Legacy rows form their own ordered group before the built-in Archive action. yield registerSessionAction('fixture.export-session', 500, 'exportSession', true) yield registerSessionAction('fixture.copy-session-id', 600, 'copySessionId', false) }) diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 739c2d6ebd..6be6b70c39 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -113,10 +113,10 @@ if (args[0] === 'auth' && args[1] === 'status') { } if (args[0] === 'api' && args[1] === 'graphql') { const query = args.find(arg => arg.startsWith('query=')).slice('query='.length) - const check = (name, conclusion, completedAt) => ({ - __typename: 'CheckRun', name, status: 'COMPLETED', conclusion, + const check = (name, conclusion, completedAt, databaseId = 101) => ({ + __typename: 'CheckRun', id: 'check-' + databaseId, name, status: 'COMPLETED', conclusion, databaseId, detailsUrl: 'https://github.com/octo/demo/actions/runs/1', startedAt: '2026-10-09T00:00:00Z', completedAt, - checkSuite: { workflowRun: { workflow: { name: 'CI' } } }, + checkSuite: { app: { id: 'github-actions' }, workflowRun: { event: 'pull_request', workflow: { id: 'ci', name: 'CI' } } }, }) const pulls = { 7: { @@ -124,9 +124,9 @@ if (args[0] === 'api' && args[1] === 'graphql') { updatedAt: '2026-10-09T00:00:00Z', closedAt: null, author: { login: 'octo' }, headRefName: 'feat', headRefOid: 'a'.repeat(40), baseRefName: 'main', additions: 128, deletions: 14, mergeable: 'MERGEABLE', mergeStateStatus: 'BLOCKED', reviewDecision: 'REVIEW_REQUIRED', reviewThreads: { nodes: [{ isResolved: false }] }, - commits: { nodes: [{ commit: { statusCheckRollup: { state: 'FAILURE', contexts: { - pageInfo: { hasNextPage: false }, - nodes: [check('lint', 'SUCCESS', '2026-10-09T00:00:42Z'), check('test', 'FAILURE', '2026-10-09T00:02:07Z')], + commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-7', state: 'FAILURE', contexts: { + pageInfo: { hasNextPage: true, endCursor: 'checks-100' }, + nodes: Array.from({ length: 100 }, (_, i) => check('lint', 'FAILURE', '2026-10-08T00:00:42Z', i + 1)), } } } }] }, }, 9: { @@ -134,11 +134,18 @@ if (args[0] === 'api' && args[1] === 'graphql') { isDraft: !state.ready, updatedAt: '2026-10-09T00:00:00Z', closedAt: state.mergedAt, author: { login: 'octo' }, headRefName: 'feat/merge', headRefOid: state.head ?? 'b'.repeat(40), baseRefName: 'main', additions: 30, deletions: 2, mergeable: 'MERGEABLE', mergeStateStatus: state.ready ? 'CLEAN' : 'BLOCKED', reviewDecision: 'APPROVED', reviewThreads: { nodes: [] }, - commits: { nodes: [{ commit: { statusCheckRollup: { state: 'SUCCESS', contexts: { - pageInfo: { hasNextPage: false }, nodes: [check('lint', 'SUCCESS', '2026-10-09T00:00:42Z')], + commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-9', state: 'SUCCESS', contexts: { + pageInfo: { hasNextPage: false, endCursor: null }, nodes: [check('lint', 'SUCCESS', '2026-10-09T00:00:42Z')], } } } }] }, }, } + if (query.includes('node(id: $id)')) { + process.stdout.write(JSON.stringify({ data: { node: { contexts: { + pageInfo: { hasNextPage: false, endCursor: null }, + nodes: [check('lint', 'SUCCESS', '2026-10-09T00:00:42Z'), check('test', 'FAILURE', '2026-10-09T00:02:07Z')], + } } } })) + process.exit(0) + } const settings = { squashMergeAllowed: true, mergeCommitAllowed: true, rebaseMergeAllowed: true, viewerPermission: 'WRITE', viewerDefaultMergeMethod: 'SQUASH', } @@ -217,9 +224,12 @@ interface PanelLaunch { * Launch the bundle against a GitHub checkout of `main` and `release` and open the New Session screen of that workspace. * @param failureShot - name of the screenshot saved when the test fails. * @param scenario - normal conversation, a restoration follow-up, or a numbered PR lookup. + * @param options - desktop transport, checkout branch, browser input, sandbox runner availability, and diff output limit. * @returns the scaffold, page, and checkout. */ -async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' | 'reference' = 'normal', desktop?: 'darwin' | 'win32'): Promise { +async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' | 'reference' = 'normal', + options: { desktop?: 'darwin' | 'win32'; branch?: string; hasTouch?: boolean; missingSandbox?: boolean; maxDiffBytes?: number } = {}): Promise { + const { desktop } = options const resources: { scaffold?: WebScaffold; browser?: Browser } = {} const root = await mkdtemp(join(tmpdir(), 'dsh-forge-panel-')) onTestFinished(async () => { @@ -237,7 +247,9 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' const panelText = `${Array.from({ length: 20 }, (_, index) => panelLine(index + 1, 'new')).join('\n')}\n` await writeFile(join(root, 'contents.json'), JSON.stringify({ [`src/panel.ts@${HEAD7}`]: panelText })) const overlay = join(root, 'forge.patch.yml') - await writeFile(overlay, `- id: forge-github\n config: ${JSON.stringify({ ghCommand: gh })}\n`) + await writeFile(overlay, `- id: forge-github\n config: ${JSON.stringify({ ghCommand: gh })}\n` + + (options.maxDiffBytes === undefined ? '' : `- id: forge-panel\n config: ${JSON.stringify({ maxDiffBytes: options.maxDiffBytes })}\n`) + + (options.missingSandbox ? `- id: sandbox\n config: ${JSON.stringify({ runnerCommand: [join(root, 'missing-sandbox')], runnerFailureSignatures: ['sandbox startup failed'] })}\n` : '')) const override = join(root, 'replay.override.json') // The borrowed scenario records one model call, so index 1 appends the reply to the follow-up. if (scenario === 'follow-up') await writeFile(override, JSON.stringify({ patches: [{ at: 1, entry: { kind: 'chunks', chunks: textReply(FOLLOW_UP_REPLY) } }] })) @@ -275,6 +287,7 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' await git(project, 'remote', 'add', 'origin', 'https://github.com/octo/demo.git') await git(project, 'branch', 'release') await git(project, 'commit', '--quiet', '--allow-empty', '-m', 'main only') + if (options.branch !== undefined) await git(project, 'checkout', '--quiet', '-b', options.branch) if (scenario === 'reference') { // The model's confined command must own the CLI double's writable call log. const modelBin = join(project, '.fixture-bin') @@ -285,7 +298,8 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' const browser = await chromium.launch() resources.browser = browser - const page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE, timezoneId: 'Asia/Shanghai' }) + const page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE, timezoneId: 'Asia/Shanghai', + hasTouch: options.hasTouch ?? false }) if (desktop !== undefined) { // Only Electron's keyboard transport is substituted; the product registry and menus remain real. await page.addInitScript(({ device, config }) => { @@ -338,7 +352,7 @@ async function requestReleaseWorktree(failureShot: string, followUp = false): Pr const { page } = launched const option = page.locator('[data-forge-worktree]') await option.waitFor({ timeout: 20_000 }) - await option.getByRole('checkbox', { name: '工作树', exact: true }).check() + await option.getByRole('checkbox', { name: '新建工作树', exact: true }).check() await option.getByRole('button', { name: '基于 main', exact: true }).click() await page.getByRole('menuitem', { name: 'release', exact: true }).click() await option.getByRole('button', { name: '基于 release', exact: true }).waitFor() @@ -366,6 +380,68 @@ function worktreeRecords(events: readonly SessionEvent[]): unknown[] { }) } +it.skipIf(MODE === 'record')('reads local Git with full access when the sandbox runner cannot start', async () => { + const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-permissions', 'normal', { missingSandbox: true }) + await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + await writeFile(join(project, 'README.md'), 'demo\nchanged\n') + const { settled } = await sendPrompt(page, scaffold) + const sessionId = await settled + await page.getByText('LIGHTHOUSE', { exact: true }).waitFor() + await page.locator('[data-forge-header]').click() + const panel = page.locator('[data-forge-panel]') + await panel.getByText('无法读取 Git 信息', { exact: true }).waitFor({ timeout: 20_000 }) + + const permission = page.locator('button[aria-label^="访问模式"]').first() + await permission.click() + await page.getByRole('menuitem', { name: '完全权限', exact: true }).click() + const confirmation = page.getByRole('dialog', { name: '确认启用完全权限?' }) + await confirmation.getByRole('checkbox', { name: '我已了解风险,并愿意继续' }).check() + await confirmation.getByRole('button', { name: '启用完全权限' }).click() + const local = page.locator('[data-forge-local]') + await local.getByRole('button', { name: '查看本会话的变更:1 个文件,新增 1 行,删除 0 行', exact: true }).waitFor({ timeout: 20_000 }) + await compareOrRefreshGolden(join(EXPECTED, 'full-access.expected.md'), await captureStableAria(page, '[data-forge-local]', scaffold.workspaceCwd), MODE) + await local.getByRole('button', { name: '查看本会话的变更:1 个文件,新增 1 行,删除 0 行', exact: true }).click() + await page.locator('[data-forge-diff-file="README.md"]').getByText('changed', { exact: true }).waitFor() + + await permission.click() + await page.getByRole('menuitem', { name: '工作区内修改', exact: true }).click() + if (!await panel.isVisible()) await page.locator('[data-forge-header]').click() + await panel.getByText('无法读取 Git 信息', { exact: true }).waitFor({ timeout: 20_000 }) + await expect.poll(async () => (await readPersistedEvents(scaffold, sessionId)) + .filter(event => event.type === 'sandbox/mode').map(event => event.data.mode).slice(-2)) + .toEqual(['danger-full-access', 'workspace-write']) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + +it.skipIf(MODE === 'record')('reports incomplete filter configuration and retries after it is corrected', async () => { + const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-filter-config', 'normal', { maxDiffBytes: 512 }) + await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + await writeFile(join(project, 'README.md'), 'demo\nchanged\n') + const { settled } = await sendPrompt(page, scaffold) + await settled + await page.getByText('LIGHTHOUSE', { exact: true }).waitFor() + await page.locator('[data-forge-header]').click() + const openChanges = page.locator('[data-forge-local]').getByRole('button', { name: '查看本会话的变更:1 个文件,新增 1 行,删除 0 行', exact: true }) + await openChanges.waitFor({ timeout: 20_000 }) + const key = `filter.${'long'.repeat(200)}.clean` + await git(project, 'config', key, 'cat') + await openChanges.click() + const changes = page.locator('[data-forge-changes="local"]') + await changes.getByText('无法完整读取 Git 过滤器配置,尚未执行比较。请检查 Git 配置和读取上限后重试', { exact: true }).waitFor() + await compareOrRefreshGolden(join(EXPECTED, 'filter-config-failed.expected.md'), + await captureStableAria(page, '[data-forge-changes="local"]', scaffold.workspaceCwd), MODE) + + await git(project, 'config', '--unset', key) + await changes.getByRole('button', { name: '重试', exact: true }).click() + await changes.locator('[data-forge-diff-file="README.md"]').getByText('changed', { exact: true }).waitFor() + expect(await changes.getByRole('status').count()).toBe(0) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + it.skipIf(MODE === 'record')('automatically shows a numbered PR when gh JSON omits its URL', async () => { const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-numbered-reference', 'reference') const { settled } = await sendPrompt(page, scaffold) @@ -437,6 +513,11 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me const row = page.locator(`[data-row-key="session:${sessionId}"]`) await row.getByRole('img', { name: '在自己的工作树中', exact: true }).waitFor({ timeout: 20_000 }) await row.getByRole('img', { name: '变更请求状态:需要处理 · 检查失败', exact: true }).waitFor({ timeout: 20_000 }) + // A fresh page cannot retain the previous browser source's status values. + await page.goto('about:blank') + await expect.poll(() => scaffold.ctx.storageDomain.get('forge_panel_change_requests')).toBeUndefined() + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await row.getByRole('img', { name: '变更请求状态:需要处理 · 检查失败', exact: true }).waitFor({ timeout: 20_000 }) await row.hover() const rowHover = page.locator('[data-forge-session-hover]') await rowHover.getByText('#7 Add the pull request panel', { exact: true }).waitFor({ timeout: 20_000 }) @@ -462,10 +543,14 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me // The random branch suffix can read as a duration, so the branch is replaced before the capture normalizes durations. await compareOrRefreshGolden(join(EXPECTED, 'panel.expected.md'), await captureStableAria(page, '[data-forge-panel]', scaffold.workspaceCwd, { replacements: [[branch, 'dsh-{{worktree}}']] }), MODE) + const beforeChecks = (await readFile(join(root, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[]) + expect(beforeChecks.some(args => args.includes('id=rollup-7'))).toBe(false) const checksRow = change.getByRole('button', { name: /^检查/ }) await checksRow.click() const checks = page.getByRole('menu') await expect.poll(() => checks.getByRole('menuitem').allTextContents()).toEqual([expect.stringMatching(/^test/), expect.stringMatching(/^lint/)]) + const afterChecks = (await readFile(join(root, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[]) + expect(afterChecks.filter(args => args.includes('id=rollup-7'))).toHaveLength(1) await page.keyboard.press('Escape') await checks.waitFor({ state: 'detached' }) expect(await checksRow.getAttribute('aria-expanded')).toBe('false') @@ -621,7 +706,12 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an const session = scaffold.ctx.sessions.get(sessionId) if (session === undefined) throw new Error('The Session must stay loaded') const header = page.locator('[data-forge-header]') - await header.click() + await page.getByRole('button', { name: '打开右侧边栏', exact: true }).click() + const guide = page.locator('[data-sidebar-right-guide]') + await guide.getByRole('button', { name: /^代码审查和变更/ }).waitFor() + await compareOrRefreshGolden(join(EXPECTED, 'review-guide.expected.md'), + await captureStableAria(page, '[data-sidebar-right-guide-entry="forge-panel"]', scaffold.workspaceCwd), MODE) + await guide.getByRole('button', { name: /^代码审查和变更/ }).click() // The New Session screen inspected the checkout before these changes, which came from outside the Session. await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click() const card = page.locator('[data-forge-local]') @@ -636,9 +726,9 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await local.locator('[data-forge-diff-file="notes.md"]').getByText('新文件 · 未提交', { exact: true }).waitFor() const readme = local.locator('[data-forge-diff-file="README.md"]') await page.context().grantPermissions(['clipboard-read', 'clipboard-write']) - await readme.getByRole('button', { name: '复制路径: README.md', exact: true }).click() - await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe('README.md') await page.evaluate(() => navigator.clipboard.writeText('unchanged')) + await readme.locator('[data-forge-file-label]').click() + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe('unchanged') await readme.locator('[data-forge-path-spacer]').click() await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe('unchanged') await readme.getByRole('button', { name: '6 行未变更', exact: true }).click() @@ -702,6 +792,13 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await page.getByRole('button', { name: '全屏', exact: true }).click() await view.getByRole('navigation').getByRole('button', { name: 'src/panel.ts', exact: true }).waitFor() const fileTree = view.getByRole('navigation') + const treeIsLeft = async () => { + const tree = await fileTree.boundingBox() + const diff = await view.locator('[data-forge-changes-scroll]').boundingBox() + if (tree === null || diff === null) throw new Error('Tree and diff must be visible') + return tree.x < diff.x + } + expect(await treeIsLeft()).toBe(true) const directoryName = await fileTree.getByText('src', { exact: true }).boundingBox() const fileName = await fileTree.getByText('panel.ts', { exact: true }).boundingBox() if (directoryName === null || fileName === null) throw new Error('Tree entries must be visible') @@ -709,13 +806,26 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await fileTree.getByRole('textbox', { name: '筛选文件…' }).fill('src') await fileTree.getByRole('textbox', { name: '筛选文件…' }).fill('') await fileTree.getByRole('button', { name: 'src', exact: true }).click() - await view.getByRole('button', { name: '文件树', exact: true }).click() + await view.getByRole('button', { name: /^(将文件树移到右侧|隐藏文件树|在左侧显示文件树)$/ }).click() + expect(await treeIsLeft()).toBe(false) + expect(await fileTree.getByRole('button', { name: 'src', exact: true }).getAttribute('aria-expanded')).toBe('false') + await page.setViewportSize({ width: 390, height: 844 }) expect(await fileTree.isVisible()).toBe(false) - await view.getByRole('button', { name: '文件树', exact: true }).click() + expect(await view.getByRole('button', { name: /^(将文件树移到右侧|隐藏文件树|在左侧显示文件树)$/ }).isVisible()).toBe(false) + await view.getByRole('button', { name: '全部 2 个文件', exact: true }).click() + await page.getByRole('menu').getByRole('textbox', { name: '筛选文件…' }).waitFor() + await page.keyboard.press('Escape') + await page.setViewportSize({ width: 1680, height: 1000 }) + expect(await treeIsLeft()).toBe(false) + await view.getByRole('button', { name: /^(将文件树移到右侧|隐藏文件树|在左侧显示文件树)$/ }).click() + expect(await fileTree.isVisible()).toBe(false) + await view.getByRole('button', { name: /^(将文件树移到右侧|隐藏文件树|在左侧显示文件树)$/ }).click() + expect(await treeIsLeft()).toBe(true) expect(await fileTree.getByRole('button', { name: 'src', exact: true }).getAttribute('aria-expanded')).toBe('false') await fileTree.getByRole('textbox', { name: '筛选文件…' }).fill('src') - await view.getByRole('button', { name: '文件树', exact: true }).click() - await view.getByRole('button', { name: '文件树', exact: true }).click() + await view.getByRole('button', { name: /^(将文件树移到右侧|隐藏文件树|在左侧显示文件树)$/ }).click() + await view.getByRole('button', { name: /^(将文件树移到右侧|隐藏文件树|在左侧显示文件树)$/ }).click() + await view.getByRole('button', { name: /^(将文件树移到右侧|隐藏文件树|在左侧显示文件树)$/ }).click() expect(await fileTree.getByRole('textbox', { name: '筛选文件…' }).inputValue()).toBe('src') await compareOrRefreshGolden(join(EXPECTED, 'file-tree-toggle.expected.md'), await captureStableAria(page, '[data-forge-changes="change"]', scaffold.workspaceCwd), MODE) @@ -727,7 +837,7 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an if (handle === null) throw new Error('Tree resize handle must be visible') await page.mouse.move(handle.x + handle.width / 2, handle.y + 100) await page.mouse.down() - await page.mouse.move(handle.x - 80, handle.y + 100, { steps: 5 }) + await page.mouse.move(handle.x + 80, handle.y + 100, { steps: 5 }) await page.mouse.up() expect(Number(await resizeTree.getAttribute('aria-valuenow'))).toBeGreaterThan(originalWidth) await resizeTree.press('Home') @@ -736,11 +846,25 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an const treeBounds = await fileTree.boundingBox() if (searchBounds === null || treeBounds === null) throw new Error('Tree search must be visible') expect(searchBounds.x + searchBounds.width).toBeLessThanOrEqual(treeBounds.x + treeBounds.width) - await resizeTree.press('ArrowLeft') + await resizeTree.press('ArrowRight') const resizedWidth = await resizeTree.getAttribute('aria-valuenow') - await view.getByRole('button', { name: '文件树', exact: true }).click() - await view.getByRole('button', { name: '文件树', exact: true }).click() + await view.getByRole('button', { name: /^(将文件树移到右侧|隐藏文件树|在左侧显示文件树)$/ }).click() + expect(await treeIsLeft()).toBe(false) expect(await resizeTree.getAttribute('aria-valuenow')).toBe(resizedWidth) + await resizeTree.press('ArrowLeft') + expect(Number(await resizeTree.getAttribute('aria-valuenow'))).toBe(Number(resizedWidth) + 20) + await resizeTree.press('ArrowRight') + const rightHandle = await resizeTree.boundingBox() + if (rightHandle === null) throw new Error('Right tree resize handle must be visible') + await page.mouse.move(rightHandle.x + rightHandle.width / 2, rightHandle.y + 100) + await page.mouse.down() + await page.mouse.move(rightHandle.x - 80, rightHandle.y + 100, { steps: 5 }) + await page.mouse.up() + expect(Number(await resizeTree.getAttribute('aria-valuenow'))).toBeGreaterThan(Number(resizedWidth)) + const rightWidth = await resizeTree.getAttribute('aria-valuenow') + await view.getByRole('button', { name: /^(将文件树移到右侧|隐藏文件树|在左侧显示文件树)$/ }).click() + await view.getByRole('button', { name: /^(将文件树移到右侧|隐藏文件树|在左侧显示文件树)$/ }).click() + expect(await resizeTree.getAttribute('aria-valuenow')).toBe(rightWidth) for (const side of ['old', 'new'] as const) { const firstLine = await panelFile.locator(`[data-review-code][data-${side}-line="2"]`).boundingBox() const lastLine = await panelFile.locator(`[data-review-code][data-${side}-line="4"]`).boundingBox() @@ -800,8 +924,12 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await page.keyboard.press('Escape') expect(await reviewDialog.count()).toBe(0) await view.getByRole('button', { name: '提交评审 (1)', exact: true }).click() - await reviewDialog.getByRole('textbox', { name: '评审总结…', exact: true }).fill('需要补充边界检查') await reviewDialog.getByRole('radio', { name: '请求更改', exact: true }).check() + await reviewDialog.getByText('请求更改时,请填写评审总结', { exact: true }).waitFor() + expect(await reviewDialog.getByRole('button', { name: '提交评审', exact: true }).isDisabled()).toBe(true) + await compareOrRefreshGolden(join(EXPECTED, 'review-summary-required.expected.md'), + await captureStableAria(page, '[role="dialog"][aria-label="提交评审"]', scaffold.workspaceCwd), MODE) + await reviewDialog.getByRole('textbox', { name: '评审总结…', exact: true }).fill('需要补充边界检查') await compareOrRefreshGolden(join(EXPECTED, 'submit-review.expected.md'), await captureStableAria(page, '[role="dialog"][aria-label="提交评审"]', scaffold.workspaceCwd), MODE) await reviewDialog.getByRole('button', { name: '提交评审', exact: true }).click() @@ -815,14 +943,15 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await panelFile.getByRole('button', { name: '6 行未变更', exact: true }).click() await panelFile.getByText('export const n6 = 6', { exact: true }).first().waitFor({ timeout: 20_000 }) await panelFile.getByRole('button', { name: '2 行未变更', exact: true }).waitFor() - await panelFile.getByRole('button', { name: '复制路径: src/panel.ts', exact: true }).click() + await panelFile.getByRole('button', { name: 'panel.ts 的更多操作', exact: true }).click() + await page.getByRole('menuitem', { name: '复制路径', exact: true }).click() await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe('src/panel.ts') const docsFile = view.locator('[data-forge-diff-file="docs/panel.md"]') await docsFile.getByRole('button', { name: '收起 panel.md', exact: true }).click() await page.setViewportSize({ width: 1280, height: 500 }) const scrollport = view.locator('[data-forge-changes-scroll]') await scrollport.evaluate((element) => { element.scrollTop = 100; element.dispatchEvent(new Event('scroll')) }) - await panelFile.getByRole('button', { name: '复制路径: src/panel.ts', exact: true }).click() + await panelFile.locator('[data-forge-file-label]').click() const position = await scrollport.evaluate(element => element.scrollTop) expect(position).toBeGreaterThan(0) const originalFile = await panelFile.elementHandle() @@ -870,8 +999,300 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an }) +it.skipIf(MODE === 'record')('retains a wrapped code line and tree width across tab and Session switches', async () => { + const { page, scaffold, root, tripwire } = await launchPanel('web-e2e-forge-reading-position') + const paths = ['src/before-0.ts', 'src/before-1.ts', 'src/before-2.ts', 'src/server.ts', 'src/after.ts'] + const patch = paths.map(path => [ + `diff --git a/${path} b/${path}`, 'index 1111111..2222222 100644', `--- a/${path}`, `+++ b/${path}`, + '@@ -1,650 +1,650 @@', '-const oldValue = true;', '+const newValue = true;', + ...Array.from({ length: 649 }, (_, index) => ` const value_${index + 2} = "${'x'.repeat(24 + (index + 2) % 70)}";`), '', + ].join('\n')).join('\n') + await writeFile(join(root, 'pr-7.diff'), patch) + const { settled } = await sendPrompt(page, scaffold) + const sessionId = await settled + const session = scaffold.ctx.sessions.get(sessionId) + if (session === undefined) throw new Error('Session must stay loaded') + scaffold.ctx.forgeSession.track(session, PULL) + // Keep the file tree and the Session sidebar visible together on every platform. + await page.setViewportSize({ width: 2400, height: 700 }) + await page.locator('[data-forge-header]').click() + await page.locator(`[data-forge-change="${PULL}"]`).getByRole('button', { name: /查看 #7 的变更/ }).click() + const view = page.locator('[data-forge-changes="change"]') + const scroll = view.locator('[data-forge-changes-scroll]') + const file = view.locator('[data-forge-diff-file="src/server.ts"]') + const code = file.locator('[data-review-code][data-new-line="300"]') + const separator = view.getByRole('separator', { name: '调整文件树宽度', exact: true }) + const beforeFile = view.locator('[data-forge-diff-file="src/before-0.ts"]') + // ResizeObserver runs between rendering frames, including when an ancestor becomes hidden. + const layout = () => page.evaluate(() => new Promise((resolve) => { + requestAnimationFrame(() => { requestAnimationFrame(() => { resolve() }) }) + })) + const reading = () => file.evaluate((element) => { + const viewport = element.closest('[data-forge-changes-scroll]')! + const top = Math.max(viewport.getBoundingClientRect().top, element.firstElementChild!.getBoundingClientRect().bottom) + const line = [...element.querySelectorAll('[data-review-code][data-new-line]')] + .find(row => row.getBoundingClientRect().bottom > top + 1)! + return { path: element.getAttribute('data-forge-diff-file'), line: line.dataset.newLine, + offset: line.getBoundingClientRect().top - top, scrollTop: viewport.scrollTop } + }) + await code.waitFor() + for (const width of [240, 320]) { + if (width === 320) { + for (let step = 0; step < 4; step += 1) await separator.press('ArrowRight') + await beforeFile.getByRole('button', { name: '收起 before-0.ts', exact: true }).click() + } + await layout() + await code.evaluate((element) => { + const viewport = element.closest('[data-forge-changes-scroll]')! + const header = element.closest('[data-forge-diff-file]')!.firstElementChild! + const top = viewport.getBoundingClientRect().top + header.getBoundingClientRect().height + viewport.scrollTop += element.getBoundingClientRect().top - top + 7 + }) + await layout() + const position = await reading() + expect(position.line).toBe('300') + expect(position.offset).toBe(-7) + for (const destination of ['tab', 'session', 'tab', 'session']) { + if (destination === 'tab') await page.getByRole('tab').filter({ hasText: '变更请求' }).click() + else await page.getByRole('button', { name: '新建会话', exact: true }).last().click() + await expect.poll(() => view.isVisible()).toBe(false) + await layout() + expect(await scroll.evaluate(element => element.clientWidth)).toBe(0) + if (destination === 'tab') await page.getByRole('tab').filter({ hasText: '#7 的变更' }).click() + else await page.locator(`[data-row-key="session:${sessionId}"]`).click() + await view.waitFor() + await layout() + expect(await separator.getAttribute('aria-valuenow')).toBe(String(width)) + expect(await reading()).toEqual(position) + expect(await beforeFile.getAttribute('data-expanded')).toBe(width === 240 ? '' : null) + } + } + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + +it.skipIf(MODE === 'record')('uses horizontal arrows to navigate files while preserving vertical scrolling and comment editing', async () => { + const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-file-keys') + await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + for (const path of ['a.txt', 'b.txt', 'c.txt']) { + await writeFile(join(project, path), Array.from({ length: path === 'c.txt' ? 1 : 80 }, (_, line) => `line ${line + 1}\n`).join('')) + } + const { settled } = await sendPrompt(page, scaffold) + await settled + await page.locator('[data-forge-header]').click() + await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click() + await page.locator('[data-forge-local]').getByRole('button', { name: /查看本会话的变更:3 个文件/ }).click() + const view = page.locator('[data-forge-changes="local"]') + const scroll = view.getByRole('region', { name: '全部 3 个文件', exact: true }) + await scroll.waitFor() + await page.getByRole('button', { name: '全屏', exact: true }).click() + await page.setViewportSize({ width: 1280, height: 500 }) + const tree = view.getByRole('navigation') + const a = view.locator('[data-forge-diff-file="a.txt"]') + const b = view.locator('[data-forge-diff-file="b.txt"]') + const c = view.locator('[data-forge-diff-file="c.txt"]') + await b.getByRole('button', { name: '收起 b.txt', exact: true }).click() + await scroll.evaluate((element) => { element.scrollTop = 0 }) + await scroll.focus() + await page.keyboard.press('ArrowLeft') + expect(await scroll.evaluate(element => element.scrollTop)).toBe(0) + expect(await scroll.evaluate(element => getComputedStyle(element).outlineStyle)).toBe('none') + await page.keyboard.press('ArrowDown') + await expect.poll(() => scroll.evaluate(element => element.scrollTop)).toBeGreaterThan(0) + await scroll.evaluate((element) => { element.scrollTop = 0 }) + await page.keyboard.press('ArrowRight') + await expect.poll(() => tree.getByRole('button', { name: 'b.txt', exact: true }).getAttribute('aria-current')).toBe('true') + expect(await b.getAttribute('data-expanded')).toBe('') + expect(await scroll.evaluate(element => document.activeElement === element)).toBe(true) + await page.keyboard.press('ArrowRight') + await expect.poll(() => tree.getByRole('button', { name: 'c.txt', exact: true }).getAttribute('aria-current')).toBe('true') + const lastPosition = await scroll.evaluate(element => element.scrollTop) + const lastBox = await c.boundingBox(), viewport = await scroll.boundingBox() + if (lastBox === null || viewport === null) throw new Error('The last file and scroll viewport must be rendered') + expect(lastBox.y).toBeGreaterThan(viewport.y) + expect(lastBox.y).toBeLessThan(viewport.y + viewport.height) + await page.keyboard.press('ArrowRight') + expect(await scroll.evaluate(element => element.scrollTop)).toBe(lastPosition) + await page.keyboard.press('ArrowLeft') + await expect.poll(() => tree.getByRole('button', { name: 'b.txt', exact: true }).getAttribute('aria-current')).toBe('true') + await page.keyboard.press('ArrowLeft') + await expect.poll(() => tree.getByRole('button', { name: 'a.txt', exact: true }).getAttribute('aria-current')).toBe('true') + await b.evaluate((element) => { + const viewport = element.closest('[data-forge-changes-scroll]')! + viewport.scrollTop += element.getBoundingClientRect().top - viewport.getBoundingClientRect().top + 100 + }) + await page.keyboard.press('ArrowRight') + await expect.poll(() => tree.getByRole('button', { name: 'c.txt', exact: true }).getAttribute('aria-current')).toBe('true') + await tree.getByRole('button', { name: 'a.txt', exact: true }).click() + await a.getByRole('button', { name: '选择第 R1 行', exact: true }).click() + await a.getByRole('button', { name: '添加评论', exact: true }).click() + const input = a.getByRole('textbox', { name: '留下评论…', exact: true }) + await input.fill('keep editing') + await input.press('ArrowLeft') + expect(await input.evaluate(element => (element as HTMLTextAreaElement).selectionStart)).toBe(11) + await input.press('ArrowRight') + expect(await input.inputValue()).toBe('keep editing') + expect(await tree.getByRole('button', { name: 'a.txt', exact: true }).getAttribute('aria-current')).toBe('true') + expect(await input.evaluate(element => document.activeElement === element)).toBe(true) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + +it.skipIf(MODE === 'record')('keeps localized status columns separate and long file lists inside one vertical scroller', async () => { + const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-layout') + await page.locator('[data-forge-current-branch]').waitFor() + await compareOrRefreshGolden(join(EXPECTED, 'worktree-option.expected.md'), + await captureStableAria(page, '[data-forge-worktree]', scaffold.workspaceCwd), MODE) + await page.getByRole('button', { name: '收起侧边栏', exact: true }).click() + await page.setViewportSize({ width: 390, height: 844 }) + await expect.poll(() => page.locator('[data-forge-worktree]') + .evaluate(element => element.getBoundingClientRect().right)).toBeLessThanOrEqual(390) + await page.setViewportSize({ width: 1680, height: 1000 }) + await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + await mkdir(join(project, 'src')) + await Promise.all(Array.from({ length: 60 }, (_, index) => writeFile(join(project, 'src', `file-${index}.ts`), `export const value = ${index}\n`))) + const { settled } = await sendPrompt(page, scaffold) + const session = scaffold.ctx.sessions.get(await settled) + if (session === undefined) throw new Error('The Session must stay loaded') + scaffold.ctx.forgeSession.track(session, PULL) + await page.locator('[data-forge-header]').click() + const panel = page.locator('[data-forge-panel]') + await panel.getByRole('button', { name: '刷新状态', exact: true }).click() + const local = panel.locator('[data-forge-local]') + await local.locator('button[aria-expanded]').click() + await expect.poll(() => local.locator('li').count(), { timeout: 20_000 }).toBe(60) + for (const width of [1280, 390]) { + await page.setViewportSize({ width, height: 700 }) + const outerScrollers = await panel.evaluate((element) => { + const scrollers: string[] = [] + for (let ancestor = element.parentElement; ancestor !== null; ancestor = ancestor.parentElement) { + if (/auto|scroll/.test(getComputedStyle(ancestor).overflowY) && ancestor.scrollHeight > ancestor.clientHeight + 1) { + scrollers.push(ancestor.className) + } + } + return scrollers + }) + expect(outerScrollers).toEqual([]) + expect(await panel.evaluate(element => element.scrollHeight > element.clientHeight)).toBe(true) + await local.locator('li').last().scrollIntoViewIfNeeded() + expect(await local.locator('li').last().isVisible()).toBe(true) + } + await local.locator('button[aria-expanded]').click() + const change = panel.locator(`[data-forge-change="${PULL}"]`) + for (const [locale, labels] of [ + ['zh', ['检查', '评审', '合并', '变更']], + ['en', ['Checks', 'Review', 'Merge', 'Changes']], + ['de', ['Prüfungen', 'Review', 'Zusammenführen', 'Änderungen']], + ] as const) { + await scaffold.ctx.settings.update('locale', { preference: locale }) + await change.getByText(labels[0], { exact: true }).waitFor() + if (locale === 'en') { + await compareOrRefreshGolden(join(EXPECTED, 'local-card.expected.md'), + await captureStableAria(page, '[data-forge-local]', scaffold.workspaceCwd), MODE) + } + for (const width of [1280, 390]) { + await page.setViewportSize({ width, height: 700 }) + await expect.poll(() => change.evaluate(element => element.getBoundingClientRect().right)).toBeLessThanOrEqual(width) + await change.getByText(labels[3], { exact: true }).hover() + for (const label of labels) { + const geometry = await change.getByText(label, { exact: true }).evaluate((element) => { + const value = element.nextElementSibling + if (value === null) throw new Error('Status label must have a value') + const range = document.createRange() + range.selectNodeContents(element) + const name = range.getBoundingClientRect() + const content = value.getBoundingClientRect() + const row = element.parentElement! + const icon = element.previousElementSibling! + const rowRect = row.getBoundingClientRect() + return { + gap: content.left - name.right, + iconInset: icon.getBoundingClientRect().left - rowRect.left, + rowInset: rowRect.left - row.closest('[data-forge-change]')!.getBoundingClientRect().left, + labelWidth: element.getBoundingClientRect().width, + valueOffset: content.left - rowRect.left, + right: content.right, + width: document.documentElement.clientWidth, + } + }) + expect(geometry.gap).toBeGreaterThanOrEqual(8) + expect(geometry.iconInset).toBe(8) + expect(geometry.rowInset).toBeGreaterThanOrEqual(6) + expect(geometry.rowInset).toBeLessThanOrEqual(7) + if (locale === 'zh') { + expect(geometry.labelWidth).toBe(32) + expect(geometry.valueOffset).toBe(76) + } + expect(geometry.right).toBeLessThanOrEqual(geometry.width) + } + } + } + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + +it.skipIf(MODE === 'record')('keeps long branch details accessible by touch and keyboard across the hero row breakpoints', async () => { + const branch = 'feature/a-long-current-branch-name-for-mobile-review' + const { page, scaffold, tripwire } = await launchPanel('web-e2e-forge-branch-details', 'normal', { branch, hasTouch: true }) + const option = page.locator('[data-forge-worktree]') + const chip = option.locator('[data-forge-current-branch]') + await chip.waitFor() + await page.getByRole('button', { name: '收起侧边栏', exact: true }).click() + for (const [locale, label] of [['zh', `当前分支:${branch}`], ['en', `Current branch: ${branch}`], ['de', `Aktueller Branch: ${branch}`]] as const) { + await scaffold.ctx.settings.update('locale', { preference: locale }) + await option.getByRole('button', { name: label, exact: true }).waitFor() + for (const width of [390, 600, 601, 700, 1280]) { + await page.setViewportSize({ width, height: 844 }) + await chip.scrollIntoViewIfNeeded() + await expect.poll(() => option.evaluate((element) => { + const row = element.closest('[class*="heroWorkspaceRow"]')! + const ancestors: Element[] = [] + for (let node: Element | null = row; node !== null; node = node.parentElement) ancestors.push(node) + return { + fits: element.getBoundingClientRect().right <= innerWidth, + overflow: ancestors.filter(node => node.scrollWidth > node.clientWidth + 1).map(node => node.className), + } + })).toEqual({ fits: true, overflow: [] }) + } + } + await scaffold.ctx.settings.update('locale', { preference: 'en' }) + await option.getByRole('button', { name: `Current branch: ${branch}`, exact: true }).waitFor() + await page.setViewportSize({ width: 390, height: 844 }) + expect(await chip.locator('span').evaluate(element => element.scrollWidth > element.clientWidth)).toBe(true) + const tooltip = page.getByRole('tooltip', { exact: true, name: `Current branch: ${branch}` }) + await chip.tap() + await tooltip.waitFor() + await compareOrRefreshGolden(join(EXPECTED, 'branch-details.expected.md'), await tooltip.ariaSnapshot(), MODE) + await chip.tap() + await tooltip.waitFor({ state: 'hidden' }) + await chip.tap() + await tooltip.waitFor() + await page.locator('[class*="heroWorkspaceRow"]').tap({ position: { x: 1, y: 1 } }) + await tooltip.waitFor({ state: 'hidden' }) + await chip.focus() + await page.keyboard.press('Tab') + await page.keyboard.press('Shift+Tab') + await tooltip.waitFor() + await page.keyboard.press('Escape') + await tooltip.waitFor({ state: 'hidden' }) + await page.keyboard.press('Enter') + await tooltip.waitFor() + await page.keyboard.press('Escape') + await tooltip.waitFor({ state: 'hidden' }) + expect(await option.getByRole('checkbox').isChecked()).toBe(false) + expect(await page.getByRole('menu').count()).toBe(0) + await scaffold.ctx.settings.update('locale', { preference: 'zh' }) + await option.getByRole('checkbox', { name: '新建工作树', exact: true }).waitFor() + const { settled } = await sendPrompt(page, scaffold) + await settled + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + it.skipIf(MODE === 'record').each(['darwin', 'win32'] as const)('closes diff menus when the %s desktop shortcut deactivates a retained tab', async (platform) => { - const { page, scaffold, project, tripwire } = await launchPanel(`web-e2e-forge-menu-${platform}`, 'normal', platform) + const { page, scaffold, project, tripwire } = await launchPanel(`web-e2e-forge-menu-${platform}`, 'normal', { desktop: platform }) await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD') await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') await writeFile(join(project, 'README.md'), 'review this change\n') @@ -881,7 +1302,7 @@ it.skipIf(MODE === 'record').each(['darwin', 'win32'] as const)('closes diff men await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click() await page.locator('[data-forge-local]').getByRole('button', { name: /查看本会话的变更:1 个文件/ }).click() const view = page.locator('[data-forge-changes="local"]') - await view.getByRole('button', { name: '复制路径: README.md', exact: true }).waitFor() + await view.locator('[data-forge-diff-file="README.md"]').waitFor() for (const name of ['分支', '全部 1 个文件', 'README.md 的更多操作']) { await view.getByRole('button', { name, exact: true }).click() await page.getByRole('menu').waitFor() diff --git a/apps/web/tests/hover-input.e2e.ts b/apps/web/tests/hover-input.e2e.ts index ccba69a0c7..8ec5679df0 100644 --- a/apps/web/tests/hover-input.e2e.ts +++ b/apps/web/tests/hover-input.e2e.ts @@ -103,7 +103,7 @@ it.each([false, true])('keeps workspace and archived search actions reachable wi await activate(actions) await archive.waitFor() } - for (const key of ['ArrowDown', 'Tab']) { + for (const key of ['ArrowDown', 'Home']) { await page.keyboard.press(key) expect(await page.locator('html').getAttribute('data-input-modality')).toBe('keyboard') expect(await page.getByRole('menu').evaluate(menu => menu.contains(document.activeElement))).toBe(true) diff --git a/apps/web/tests/markdown-file-links.e2e.ts b/apps/web/tests/markdown-file-links.e2e.ts index 62b83dfafb..6161bf048e 100644 --- a/apps/web/tests/markdown-file-links.e2e.ts +++ b/apps/web/tests/markdown-file-links.e2e.ts @@ -2,7 +2,7 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises' import { basename, join } from 'node:path' import { fileURLToPath } from 'node:url' -import { chromium, type Browser, type Page } from 'playwright' +import { chromium, type Browser, type Locator, type Page } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import { ToolCallId, createAssistantMessage, createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm' import { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session' @@ -17,6 +17,13 @@ import { expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './supp const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/markdown-file-links', import.meta.url)) const MODE = webSnapshotMode() +/** A restored preview resolves its Host path after the document's load event. */ +async function reloadPreview(page: Page, column: Locator, absolutePath: string): Promise { + await page.reload({ waitUntil: 'load' }) + await column.getByText(absolutePath, { exact: true }).waitFor() + expect(await column.locator('[data-textpreview-path]').textContent()).toBe(absolutePath) +} + /** Build live test input with a parent-path link and a read result naming the same Host file. */ function parentPathFixture(path: string): string { const session = Session.create(SessionId('parent-file-links-source')) @@ -156,6 +163,54 @@ describe('web e2e: Markdown file links', () => { await assertFixtureInventory(SNAPSHOT_DIR, ['session.v3.jsonl', 'links.expected.md', 'preview.expected.md']) }) + it('replays colon line suffixes as locations and shares tabs with fragment links', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-colon-file-links')) + const fixture = new URL('./fixtures/markdown-colon-file-links/session.v3.jsonl', import.meta.url) + const id = await seedSession(scaffold, await readFile(fixture, 'utf8'), 'colon-file-links') + await page.reload({ waitUntil: 'load' }) + const workspace = page.getByRole('treeitem').first() + await workspace.waitFor() + if (await workspace.getAttribute('aria-expanded') !== 'true') await workspace.click() + await page.locator(`[data-row-key="session:${id}"]`).click() + + const relative = page.getByRole('button', { name: 'Relative colon:24–30', exact: true }) + await relative.waitFor() + expect(await page.getByRole('button', { name: 'Development server', exact: true }).count()).toBe(0) + expect(await page.getByRole('link', { name: 'Development server', exact: true }).getAttribute('href')).toBe('localhost:3000') + expect(await page.getByRole('link', { name: 'Bare URL', exact: true }).getAttribute('href')).toBe('index.ts:24') + expect(await page.getByRole('link', { name: 'Blocked script', exact: true }).count()).toBe(0) + expect(await page.getByRole('button', { name: 'Blocked script', exact: true }).count()).toBe(0) + expect(await page.getByRole('link', { name: 'Mail', exact: true }).getAttribute('href')).toBe('mailto:10086') + await compareOrRefreshGolden( + fileURLToPath(new URL('./expected/markdown-colon-file-links.md', import.meta.url)), + await relative.locator('..').ariaSnapshot(), MODE, + ) + const column = page.locator('[data-rightbar-col]') + for (const label of ['Zero line', 'Reversed range']) { + await page.getByRole('button', { name: label, exact: true }).click() + await expect.poll(() => column.locator('[data-textpreview-path]').textContent()) + .toBe(join(scaffold.workspaceCwd, 'src/example.txt')) + await expect.poll(() => column.locator('[data-textpreview-line="1"]').textContent()).toBe('source line 1\n') + expect(await column.locator('[data-dockkit-tab-title]').allTextContents()).toEqual(['example.txt']) + } + for (const [label, line] of [['Relative colon:24–30', 24], ['Absolute colon:30', 30], ['Column:24:5', 24], ['Fragment:12', 12]] as const) { + const link = page.getByRole('button', { name: label, exact: true }) + await link.focus() + await link.press('Enter') + await expect.poll(() => column.locator(`[data-textpreview-target="${line}"]`).textContent()) + .toBe(`source line ${line}\n`) + await expect.poll(() => column.locator('[data-textpreview-path]').textContent()) + .toBe(join(scaffold.workspaceCwd, 'src/example.txt')) + expect(await column.locator('[data-dockkit-tab-title]').allTextContents()).toEqual(['example.txt']) + } + await reloadPreview(page, column, join(scaffold.workspaceCwd, 'src/example.txt')) + await relative.click() + await expect.poll(() => column.locator('[data-textpreview-target="24"]').textContent()).toBe('source line 24\n') + expect(await column.locator('[data-dockkit-tab-title]').allTextContents()).toEqual(['example.txt']) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) + it('opens parent-path prose and read-card links while retaining each address across reload', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-parent-file-links')) // Return through the parent into this owned temp root; no shared parent file is created. @@ -186,8 +241,7 @@ describe('web e2e: Markdown file links', () => { await expect.poll(() => column.locator('[data-textpreview-target="30"]').textContent()).toBe('parent line 30\n') expect(await tabs.allTextContents()).toEqual(['parent.txt']) - await page.reload({ waitUntil: 'load' }) - await expect.poll(() => column.locator('[data-textpreview-path]').textContent()).toBe(join(scaffold.workspaceCwd, 'parent.txt')) + await reloadPreview(page, column, join(scaffold.workspaceCwd, 'parent.txt')) await expect.poll(stored).toContain(address) await source.click() await expect.poll(() => column.locator('[data-textpreview-target="24"]').textContent()).toBe('parent line 24\n') diff --git a/apps/web/tests/markdown-image-refresh.e2e.ts b/apps/web/tests/markdown-image-refresh.e2e.ts index bade81cd1e..2a9dc421a3 100644 --- a/apps/web/tests/markdown-image-refresh.e2e.ts +++ b/apps/web/tests/markdown-image-refresh.e2e.ts @@ -1,9 +1,10 @@ // A rewritten local image file shows its current bytes in a newly rendered Markdown image. -import { writeFile } from 'node:fs/promises' +import { readFile, writeFile } from 'node:fs/promises' import { join } from 'node:path' import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import { createMessage, createUserMessage } from '@deepseek-ai/dsh-llm' import { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-session-title' @@ -50,7 +51,11 @@ describe('web e2e: rewritten Markdown image files', () => { let tripwire: ReturnType beforeAll(async () => { - scaffold = await launchWebScaffold({}) + scaffold = await launchWebScaffold({ + openInAppEnvironment: createLaunchEnvironmentSnapshot([ + { source: 'process', values: { SSH_CONNECTION: '10.0.0.2 55000 10.0.0.9 22' } }, + ]), + }) await writeFile(join(scaffold.workspaceCwd, 'chart.svg'), chart(120, 'red')) await seedSession(scaffold, chartFixture('First chart'), 'markdown-image-refresh-first', undefined, { createdAt: WEB_FIXTURE_TIME - 120_000 }) @@ -81,6 +86,14 @@ describe('web e2e: rewritten Markdown image files', () => { await page.getByRole('treeitem').nth(1).click() await page.getByText('Second chart', { exact: true }).last().waitFor() await expect.poll(width, { timeout: 10_000 }).toBe(240) + await page.getByRole('img', { name: ALT }).click({ button: 'right' }) + const action = page.getByRole('menuitem', { name: 'Download', exact: true }) + await action.waitFor() + const [download] = await Promise.all([page.waitForEvent('download'), action.click()]) + expect(download.suggestedFilename()).toBe('chart.svg') + const path = await download.path() + if (path === null) throw new Error('Browser download unavailable') + expect(await readFile(path, 'utf8')).toBe(chart(240, 'blue')) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) }, 60_000) diff --git a/apps/web/tests/menu-material.e2e.ts b/apps/web/tests/menu-material.e2e.ts index 9f96ba008a..4f65a889a8 100644 --- a/apps/web/tests/menu-material.e2e.ts +++ b/apps/web/tests/menu-material.e2e.ts @@ -3,6 +3,7 @@ import { readFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' import { join } from 'node:path' import { chromium, type Locator } from 'playwright' +import sharp from 'sharp' import { expect, it, onTestFinished } from 'vitest' import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, seedSession, webSnapshotMode } from './scaffold.ts' @@ -48,13 +49,13 @@ it('shares menu transparency and blur across palettes and follows native menu bo }) expect(overlayFill).toBe(platform === 'darwin' ? dark ? 'rgba(48, 49, 54, 0.94)' : 'rgba(248, 249, 250, 0.94)' - : dark ? 'rgba(67, 69, 74, 0.45)' : 'rgba(248, 249, 250, 0.58)') + : dark ? 'rgba(48, 49, 54, 0.64)' : 'rgba(252, 253, 254, 0.7)') await account.click() const menu = page.getByRole('menu').filter({ has: page.getByRole('menuitem', { name: 'Settings', exact: true }) }) await menu.waitFor() const appearance = await material(menu) expect(appearance).toMatchObject({ - fill: dark ? 'rgba(67, 69, 74, 0.45)' : 'rgba(248, 249, 250, 0.58)', + fill: dark ? 'rgba(48, 49, 54, 0.64)' : 'rgba(252, 253, 254, 0.7)', blur: 'blur(40px) saturate(1.5)', }) expect(appearance.shadow).toContain(`${dark ? 'rgba(255, 255, 255, 0.16)' : 'rgba(0, 0, 0, 0.04)'} 0px 0px 0px 0.5px`) @@ -109,4 +110,57 @@ it('shares menu transparency and blur across palettes and follows native menu bo await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd), webSnapshotMode()) await page.keyboard.press('Escape') await expect.poll(() => page.locator('[data-menu-backing]').count()).toBe(0) + + await action.locator('xpath=ancestor::*[@role="treeitem"][1]').click({ button: 'right' }) + await sessionMenu.waitFor() + const popup = page.locator('[data-context-menu]') + const stripes = await page.evaluateHandle(() => { + const element = document.createElement('div') + element.style.cssText = 'position:fixed;inset:0;z-index:1099;pointer-events:none;background:repeating-linear-gradient(90deg,#000 0 4px,#fff 4px 8px)' + document.body.appendChild(element) + return element + }) + try { + // Hide text while preserving layout so pixel contrast measures only the material. + await popup.evaluate((node) => { + for (const child of node.children) { + if (child instanceof HTMLElement && child.getAttribute('aria-hidden') !== 'true') child.style.visibility = 'hidden' + } + }) + const box = (await popup.boundingBox())! + const clip = { x: Math.floor(box.x + box.width / 2 - 32), y: Math.floor(box.y + box.height / 2 - 16), width: 64, height: 32 } + for (const phase of ['enter', 'dismiss', 'replace']) { + await popup.evaluate((node, phase) => { + node.removeAttribute('data-menu-phase') + void (node as HTMLElement).offsetWidth + node.setAttribute('data-menu-phase', phase) + for (const animation of node.getAnimations({ subtree: true })) { + animation.pause() + animation.currentTime = Number(animation.effect!.getComputedTiming().duration) / 2 + } + }, phase) + const stats = await sharp(await page.screenshot({ clip })).stats() + // During a fade the unpainted fraction exposes stripes; a working blur still + // removes substantially more contrast than opacity without backdrop sampling. + expect(stats.channels[0]!.stdev, phase).toBeLessThan(90) + } + await popup.evaluate((node) => { + node.setAttribute('data-menu-phase', 'enter') + for (const animation of node.getAnimations({ subtree: true })) animation.finish() + }) + const settled = await sharp(await page.screenshot({ clip })).stats() + expect(settled.channels[0]!.stdev).toBeLessThan(3) + await popup.evaluate((node) => { + node.style.opacity = '0.999' + // The negative control measures backdrop isolation independently of the theme's fill alpha. + const material = node.querySelector(':scope > [aria-hidden="true"]')! + material.style.backgroundColor = 'transparent' + }) + const isolated = await sharp(await page.screenshot({ clip })).stats() + expect(isolated.channels[0]!.stdev).toBeGreaterThan(90) + } finally { + await stripes.evaluate((node) => { node.remove() }) + await stripes.dispose() + await page.keyboard.press('Escape') + } }) diff --git a/apps/web/tests/plugin-install-github.e2e.ts b/apps/web/tests/plugin-install-github.e2e.ts index a11f2b942b..7fc4ece9fd 100644 --- a/apps/web/tests/plugin-install-github.e2e.ts +++ b/apps/web/tests/plugin-install-github.e2e.ts @@ -1,6 +1,8 @@ // Real Git reaches a controlled proxy failure or stall; the browser // offers a mirror for a replacement spec, or another way once the install -// already asks the mirror, without retrying the failed address. +// already asks the mirror, without retrying the failed address. Without a +// configured fallback registry the same failure keeps the plain failed +// screen, whose details name the check's own Git run and complete log. import { once } from 'node:events' import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises' import { createServer, type Socket } from 'node:net' @@ -121,3 +123,66 @@ it.each(['network', 'timeout'] as const)('offers a mirror after a GitHub %s, the expect(connections).toBeGreaterThan(checked) expect(tripwire.pageErrors).toEqual([]) }) + +it("shows the failed check's Git run and complete log in the installation details when no mirror is offered", async () => { + const scratch = await mkdtemp(join(tmpdir(), 'dsh-install-github-details-')) + onTestFinished(() => rm(scratch, { recursive: true, force: true })) + const sockets = new Set() + const proxy = createServer((socket) => { + sockets.add(socket) + socket.on('error', () => {}) + socket.once('close', () => { sockets.delete(socket) }) + socket.once('data', () => socket.destroy()) + }) + onTestFinished(async () => { + for (const socket of sockets) socket.destroy() + await new Promise((resolve, reject) => { proxy.close((error) => { if (error) reject(error); else resolve() }) }) + }) + proxy.listen(0, '127.0.0.1') + await once(proxy, 'listening') + const address = proxy.address() + if (address === null || typeof address === 'string') throw new Error('proxy did not bind a TCP port') + const gitConfig = join(scratch, 'git.config') + await writeFile(gitConfig, `[http "https://github.com/"]\n proxy = http://127.0.0.1:${String(address.port)}\n`) + // Without a configured fallback registry the Host has no mirror to offer, so the failure keeps the + // plain failed screen whose details name the check's own run. + const overlay = join(scratch, 'cordis.patch.yml') + await writeFile(overlay, '- id: ui-plugin-manager\n config: { registryProbeEnabled: false }\n- id: plugin-manager\n config: { fallbackRegistries: [] }\n') + const scaffold = await launchWebScaffold({ + profile: { packages: [], packageManager: { command: process.execPath, args: [], env: { GIT_CONFIG_GLOBAL: gitConfig, GIT_CONFIG_NOSYSTEM: '1' } } }, + extraOverlayPath: overlay, + }) + onTestFinished(() => scaffold.close()) + const browser = await chromium.launch() + onTestFinished(() => browser.close()) + const profile = join(scaffold.harnessHome, 'profiles', 'scaffold') + const attempts = join(profile, '.attempts') + await writeFile(join(profile, 'config'), 'console.log("https://registry.npmjs.org/")\n') + await writeFile(attempts, '') + await writeFile(join(profile, 'add'), ` + const fs = require('node:fs'); + fs.appendFileSync('.attempts', JSON.stringify(process.argv) + '\\n'); + process.exitCode = 1; + `) + const page = await browser.newPage({ viewport: { width: 1280, height: 800 }, locale: ZH_BROWSER_LOCALE }) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl) + await page.waitForSelector('[class*="frame"]') + if (await page.getByRole('dialog', { name: '设置' }).count() > 0) await page.keyboard.press('Escape') + await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() + await page.getByRole('button', { name: '添加插件', exact: true }).click() + const spec = 'https://github.com/example/dsh-plugin.git' + let dialog = page.getByRole('dialog', { name: '添加插件', exact: true }) + await dialog.getByRole('textbox', { name: '包名或地址' }).fill(spec) + await dialog.getByRole('button', { name: '安装', exact: true }).click() + dialog = page.getByRole('dialog', { name: '插件安装失败', exact: true }) + await dialog.waitFor() + expect(await dialog.getByText('无法连接 github.com', { exact: false }).count()).toBe(1) + // The details carry the failed check's own Git run and the complete log, not an empty terminal. + await dialog.getByRole('button', { name: '查看安装详情', exact: true }).click() + await dialog.getByText(/git -c credential\.helper= ls-remote -- https:\/\/github\.com\/example\/dsh-plugin\.git HEAD/).waitFor() + await dialog.getByText(/fatal: unable to access/).waitFor() + expect(await dialog.getByText(/^完整日志:.*github-connection-.*git\.log$/).count()).toBe(1) + expect(await readFile(attempts, 'utf8')).toBe('') + expect(tripwire.pageErrors).toEqual([]) +}) diff --git a/apps/web/tests/plugin-install-registry.e2e.ts b/apps/web/tests/plugin-install-registry.e2e.ts index 5a29cceada..70d8f47520 100644 --- a/apps/web/tests/plugin-install-registry.e2e.ts +++ b/apps/web/tests/plugin-install-registry.e2e.ts @@ -124,6 +124,7 @@ it.each(['https://registry.npmjs.org/', MIRROR])('selects the fastest responding const installed = (await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)) .split(process.execPath).join('{{node}}') .split(scaffold.harnessHome).join('{{harnessHome}}') + .replace(/operation-[A-Za-z0-9]+/g, 'operation-{{suffix}}') await compareOrRefreshGolden(fileURLToPath(new URL('./expected/plugin-install-registry/installed.expected.md', import.meta.url)), installed, webSnapshotMode()) // The dialog opened again starts from the registry picked for the last install. await dialog.getByRole('button', { name: '立即启用', exact: true }).click() diff --git a/apps/web/tests/plugin-install-silent-failure.e2e.ts b/apps/web/tests/plugin-install-silent-failure.e2e.ts new file mode 100644 index 0000000000..4a487c24fe --- /dev/null +++ b/apps/web/tests/plugin-install-silent-failure.e2e.ts @@ -0,0 +1,59 @@ +// A real Host/Remote/browser composition with a controllable package-manager process: +// pnpm fails without printing anything, and the dialog still shows what failed and where +// the complete log lives instead of a generic sentence over an empty details panel. +import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium } from 'playwright' +import { expect, it } from 'vitest' +import { launchWebScaffold, captureStableAria, compareOrRefreshGolden, webSnapshotMode, watchConsole, type WebScaffold } from './scaffold.ts' +import { ZH_BROWSER_LOCALE } from './support.ts' + +it('reports a failed install whose pnpm printed nothing with its command line, output, and log file', async () => { + const scratch = await mkdtemp(join(tmpdir(), 'dsh-install-silent-')) + const overlay = join(scratch, 'cordis.patch.yml') + await writeFile(overlay, `- id: plugin-manager\n config: ${JSON.stringify({ pnpmCommand: process.execPath })}\n`) + let scaffold: WebScaffold | undefined + try { + scaffold = await launchWebScaffold({ profile: { packages: [] }, extraOverlayPath: overlay }) + const browser = await chromium.launch() + try { + const profile = join(scaffold.harnessHome, 'profiles', 'scaffold') + // Node stands in for pnpm: `view` answers the check, and `add` exits unsuccessfully without printing + // anything, the way a silent or early-crashing package manager leaves a failed run with no terminal output. + await writeFile(join(profile, 'view'), 'console.log(JSON.stringify({ name: "silent-package", version: "1.0.0", dsh: { bundle: { patch: "./cordis.patch.yml" } } }))\n') + await writeFile(join(profile, 'add'), 'process.exitCode = 1\n') + const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, locale: ZH_BROWSER_LOCALE }) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl) + await page.waitForSelector('[class*="frame"]') + if (await page.getByRole('dialog', { name: '设置' }).count() > 0) await page.keyboard.press('Escape') + await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() + await page.getByRole('button', { name: '添加插件', exact: true }).click() + const dialog = page.getByRole('dialog') + await dialog.getByRole('textbox').fill('silent-package') + await dialog.getByRole('button', { name: '安装', exact: true }).click() + const failure = page.getByRole('dialog', { name: '插件安装失败', exact: true }) + await failure.waitFor({ timeout: 20_000 }) + // The sentence names the failed stage; the details carry the Host's own record of the run. + await failure.getByText('安装命令失败,原因见安装详情', { exact: true }).waitFor() + await failure.getByRole('button', { name: '查看安装详情', exact: true }).click() + await failure.getByText('pnpm add silent-package', { exact: true }).waitFor() + await failure.getByText(/Command failed with exit code 1:/).waitFor() + expect(await failure.getByText(/^完整日志:.*pnpm\.log$/).count()).toBe(1) + expect(await readFile(join(profile, 'package.json'), 'utf8')).not.toContain('silent-package') + const snapshot = (await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)) + .split(process.execPath).join('{{node}}') + .split(scaffold.harnessHome).join('{{harnessHome}}') + .replace(/operation-[A-Za-z0-9]+/g, 'operation-{{suffix}}') + await compareOrRefreshGolden( + fileURLToPath(new URL('./expected/plugin-install-silent-failure/failed.expected.md', import.meta.url)), snapshot, webSnapshotMode(), + ) + expect(tripwire.pageErrors).toEqual([]) + } finally { await browser.close() } + } finally { + await scaffold?.close() + await rm(scratch, { recursive: true, force: true }) + } +}) diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index 61ce911f8c..7963b22779 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -269,7 +269,7 @@ describe('web e2e: plugin manager', () => { await add.focus() for (const [width, icons, narrowTabs, wraps] of [ [1280, false, false, false], [544, true, false, false], - [414, true, true, false], [334, true, true, true], [244, true, true, true], + [390, true, true, false], [320, true, true, true], [244, true, true, true], ] as const) { await probe.setViewportSize({ width, height: 480 }) await body.evaluate((element) => { element.scrollTop = 180 }) @@ -856,7 +856,10 @@ describe('web e2e: plugin manager', () => { .toBe(bundles.filter(bundle => bundle.name !== '@deepseek-ai/dsh-experimental-terminal-bundle' && bundle.name !== '@deepseek-ai/dsh-experimental-liveshare' && bundle.official && (bundle.listedByDefault !== false || bundle.enabled || bundle.installed)).length) - for (const name of ['@deepseek-ai/dsh-cua-bundle', '@deepseek-ai/dsh-experimental-session-search', '@deepseek-ai/dsh-experimental-ralph-bundle']) { + expect(bundles.find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle')) + .toMatchObject({ enabled: false, optional: false, availability: 'missing', listedByDefault: false }) + expect(await panel.locator('[data-plugin-package="@deepseek-ai/dsh-cua-bundle"]').count()).toBe(0) + for (const name of ['@deepseek-ai/dsh-experimental-session-search', '@deepseek-ai/dsh-experimental-ralph-bundle']) { expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === name)) .toMatchObject({ enabled: false, optional: true, availability: 'installation', listedByDefault: false }) expect(await panel.locator(`[data-plugin-package="${name}"]`).count()).toBe(0) diff --git a/apps/web/tests/plugin-sticky-motion.e2e.ts b/apps/web/tests/plugin-sticky-motion.e2e.ts index d9a549c35f..86fecc4656 100644 --- a/apps/web/tests/plugin-sticky-motion.e2e.ts +++ b/apps/web/tests/plugin-sticky-motion.e2e.ts @@ -83,8 +83,8 @@ it('preserves both header layouts and follows the scroll position without changi await page.locator('[data-plugin-bar][data-natural]').waitFor() await page.evaluate(() => document.fonts.ready) // Without tabs, whether the actions fit beside the title at 470px depends on the platform font, - // so that width is pinned only with tabs. At 334px the tabs and actions wrap onto separate rows. - for (const width of hasTabs ? [1280, 600, 470, 390, 334] : [1280, 600, 390]) { + // so that width is pinned only with tabs. At 320px the tabs and actions wrap onto separate rows. + for (const width of hasTabs ? [1280, 600, 470, 390, 320] : [1280, 600, 390]) { await page.setViewportSize({ width, height: 480 }) await scrollTo(page, 0) const resting = await reference(page, false) @@ -95,7 +95,7 @@ it('preserves both header layouts and follows the scroll position without changi expect(initial.tabs).toEqual(resting.tabs) if (hasTabs && width <= 600) { const tabs = initial.tabs! - if (width === 334) { + if (width === 320) { expect(initial.toolbar.y).toBeGreaterThanOrEqual(tabs.y + tabs.height) } else { expect(initial.toolbar.x).toBeGreaterThanOrEqual(tabs.x + tabs.width) diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index 13d03475ff..3cf7695139 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -694,6 +694,7 @@ async function toggleOptionalBundles(page: Page): Promise { }) } return { + cua: bundles.filter(entry => entry.name === '@deepseek-ai/dsh-cua-bundle'), optional: bundles.filter(entry => entry.optional).map(entry => ({ name: entry.name, enabled: entry.enabled, availability: entry.availability, error: entry.error ?? null, title: typeof entry.meta?.title, icon: typeof entry.meta?.icon, metaError: entry.meta?.error ?? null, @@ -705,20 +706,16 @@ async function toggleOptionalBundles(page: Page): Promise { }) expect(result.optional.map(entry => entry.name).sort()).toEqual([...OPTIONAL_BUNDLES].sort()) expect(result.optional.filter(entry => entry.enabled || entry.availability !== 'installation')).toEqual([]) - expect(result.optional.filter(entry => entry.error !== null)).toEqual([ - expect.objectContaining({ name: '@deepseek-ai/dsh-cua-bundle', error: { code: 'unsupported-platform' } }), - ]) + expect(result.optional.filter(entry => entry.error !== null)).toEqual([]) + expect(result.cua).toHaveLength(1) + expect(result.cua[0]).toMatchObject({ name: '@deepseek-ai/dsh-cua-bundle', optional: false, + availability: 'missing', error: { code: 'unsupported-platform' } }) // Metadata resolves through the Worker's Node internal modules: every optional bundle shows its title and icon. expect(result.optional.filter(entry => entry.metaError !== null || entry.title !== 'object' || entry.icon !== 'string')).toEqual([]) expect(result.inventoryErrors).toEqual([]) console.info(`preview boot: optional bundle toggles ${JSON.stringify(result.toggles.map(({ name, enable, disable, error }) => ({ name, enable, disable, error })))}`) - expect(result.toggles.find(toggle => toggle.name === '@deepseek-ai/dsh-cua-bundle')).toMatchObject({ - enable: 'failed', disable: 'applied', error: { code: 'unsupported-platform' }, - changed: 0, inactive: [], restored: true, - }) - // The packed worker composition excludes LiveShare from its generic toggles; plugin-manager.e2e.ts - // covers that bundle's enable/disable path in the ordinary Web scaffold. - const supported = result.toggles.filter(toggle => toggle.name !== '@deepseek-ai/dsh-cua-bundle') + expect(result.toggles.find(toggle => toggle.name === '@deepseek-ai/dsh-cua-bundle')).toBeUndefined() + const supported = result.toggles expect(supported.filter(toggle => toggle.enable !== 'applied' || toggle.disable !== 'applied') .map(({ name, enable, disable }) => ({ name, enable, disable }))).toEqual([]) // Each bundle changes Loader rows, every enabled row it changes runs, and switching it off restores the prior rows. diff --git a/apps/web/tests/shortcuts-panels.e2e.ts b/apps/web/tests/shortcuts-panels.e2e.ts index 2036dad448..601221e96d 100644 --- a/apps/web/tests/shortcuts-panels.e2e.ts +++ b/apps/web/tests/shortcuts-panels.e2e.ts @@ -127,10 +127,16 @@ describe.skipIf(process.platform === 'win32')('Web sidebar shortcuts', () => { const terminalEntry = panel.locator('[data-sidebar-right-guide-entry="terminal"]') const shellMenu = terminalEntry.getByRole('button', { name: 'Choose shell', exact: true }) - const titleBounds = await terminalEntry.getByText('New terminal', { exact: true }).boundingBox() - const arrowBounds = await shellMenu.boundingBox() - expect(arrowBounds!.x).toBeGreaterThanOrEqual(titleBounds!.x + titleBounds!.width) - expect(arrowBounds!.x - titleBounds!.x - titleBounds!.width).toBeLessThan(8) + // Sample both rectangles in one layout instead of crossing the panel's transition frames. + await expect.poll(() => terminalEntry.evaluate((entry) => { + const title = [...entry.querySelectorAll('span[aria-hidden="true"]')].find(element => element.textContent === 'New terminal') + const arrow = entry.querySelector('button[aria-label="Choose shell"]') + if (title === undefined || arrow === null) return null + const titleBounds = title.getBoundingClientRect() + const arrowBounds = arrow.getBoundingClientRect() + const gap = arrowBounds.left - titleBounds.right + return { ordered: gap >= 0, adjacent: gap < 8 } + })).toEqual({ ordered: true, adjacent: true }) await shellMenu.click() await page.getByRole('menu').waitFor() expect(await panel.locator('[data-sidebar-terminal]').count()).toBe(0) @@ -254,12 +260,12 @@ describe.skipIf(process.platform === 'win32')('Web sidebar shortcuts', () => { await menuTab.click({ button: 'right' }) await page.getByRole('menu').waitFor() expect(await page.getByRole('tooltip').count()).toBe(0) - expect(await page.getByRole('menuitem').getAttribute('aria-keyshortcuts')).toBeNull() + expect(await page.getByRole('menuitem', { name: 'Close', exact: true }).getAttribute('aria-keyshortcuts')).toBe(aria) if (attempt === 0) { await compareOrRefreshGolden(join(expected, 'tab-menu.expected.md'), - await captureStableAria(page, '[data-dockkit-tab-menu]', scaffold.workspaceCwd), mode) + await captureStableAria(page, '[data-context-menu][role="menu"]', scaffold.workspaceCwd), mode) } else { - await page.getByRole('menuitem').focus() + await page.getByRole('menuitem', { name: 'Close', exact: true }).focus() } await page.keyboard.press('Escape') await page.getByRole('menu').waitFor({ state: 'detached' }) diff --git a/apps/web/tests/sidebar-alignment.e2e.ts b/apps/web/tests/sidebar-alignment.e2e.ts index 6ea3f3dedb..82afdd29f2 100644 --- a/apps/web/tests/sidebar-alignment.e2e.ts +++ b/apps/web/tests/sidebar-alignment.e2e.ts @@ -553,6 +553,11 @@ describe('web e2e: sidebar search alignment and row action targets', () => { expect(tooltipBox.x + tooltipBox.width).toBe(anchorBox.x + anchorBox.width) await page.mouse.move(1000, 400) await tooltip.waitFor({ state: 'detached' }) + if (kind === 'session') { + expect(await menuButton.evaluate(element => element === document.activeElement)).toBe(true) + expect(await tooltipAnchor.isVisible()).toBe(true) + } + await page.mouse.click(1000, 400) expect(await tooltipAnchor.isVisible()).toBe(false) expect(await page.getByRole('tooltip').count()).toBe(0) expect(tripwire.pageErrors).toEqual([]) diff --git a/apps/web/tests/sidebar-drawer.e2e.ts b/apps/web/tests/sidebar-drawer.e2e.ts index 89721edacc..99b5c3fd43 100644 --- a/apps/web/tests/sidebar-drawer.e2e.ts +++ b/apps/web/tests/sidebar-drawer.e2e.ts @@ -236,6 +236,9 @@ it('overlays the conversation and closes after navigation without losing its sid const opener = page.getByRole('button', { name: 'Open sidebar', exact: true }) await opener.waitFor() const frame = page.locator('[data-sidebar-drawer]') + expect(await page.locator('[data-shell-leading]').getByRole('button').count()).toBe(1) + expect(await frame.evaluate(el => getComputedStyle(el).getPropertyValue('--dsh-frame-leading-clearance').trim())) + .toBe('48px') await expect.poll(() => frame.getAttribute('data-sidebar-collapsed')).toBe('true') const sidebar = page.locator('[data-slot="sidebar"]') const original = await sidebar.elementHandle() @@ -271,6 +274,33 @@ it('overlays the conversation and closes after navigation without losing its sid await assertMaskFade(frame, 1, 0) await drawer.waitFor({ state: 'hidden' }) await page.getByRole('navigation', { name: 'Session hierarchy' }).getByText('Drawer navigation', { exact: true }).waitFor() + const chatTab = page.getByRole('tab', { name: 'Chat', exact: true }) + const tabInset = () => chatTab.evaluate((tab) => { + const label = document.createRange() + label.selectNodeContents(tab) + return label.getBoundingClientRect().left - tab.closest('header')!.getBoundingClientRect().left + }) + expect(await tabInset()).toBeCloseTo(20, 1) + // Restore CSS-probe markers in the same synchronous task, before rendering. + const desktopInsets = await chatTab.evaluate((tab) => { + const root = document.documentElement + try { + return ['darwin', 'win32'].map((platform) => { + root.dataset.platform = platform + const label = document.createRange() + label.selectNodeContents(tab) + return label.getBoundingClientRect().left - tab.closest('header')!.getBoundingClientRect().left + }) + } finally { + delete root.dataset.platform + } + }) + for (const inset of desktopInsets) expect(inset).toBeCloseTo(28, 1) + await page.setViewportSize({ width: 768, height: 844 }) + await frame.waitFor({ state: 'detached' }) + expect(await tabInset()).toBeCloseTo(28, 1) + await page.setViewportSize({ width: 390, height: 844 }) + await frame.waitFor() await opener.click() const selectedRow = drawer.getByRole('treeitem', { selected: true }) const more = selectedRow.getByRole('button', { name: 'Session actions for Drawer navigation', exact: true }) @@ -283,14 +313,52 @@ it('overlays the conversation and closes after navigation without losing its sid await menu.getByRole('menuitem', { name: 'Archive session', exact: true }).waitFor() await menu.getByRole('menuitem', { name: 'Pin session', exact: true }).tap() await menu.waitFor({ state: 'hidden' }) - await selectedRow.getByLabel('Pinned', { exact: true }).waitFor() + const unpin = selectedRow.getByRole('button', { name: 'Unpin session', exact: true }) + await expect.poll(() => selectedRow.getByLabel('Pinned', { exact: true }).count()).toBe(1) + expect(await unpin.isVisible()).toBe(true) + const timestamp = selectedRow.getByText(/^(?:now|\d+min)$/, { exact: true }) + expect(await timestamp.count()).toBe(1) + expect(await timestamp.textContent()).toMatch(/^(?:now|\d+min)$/) + expect(await timestamp.isVisible()).toBe(false) + const unpinBox = (await unpin.boundingBox())! + const moreBox = (await more.boundingBox())! + const folderMoreBox = (await workspaceButtons.nth(0).boundingBox())! + const folderNewBox = (await workspaceButtons.nth(1).boundingBox())! + expect(moreBox.x - unpinBox.x).toBeCloseTo(folderNewBox.x - folderMoreBox.x, 1) + await unpin.tap() + await expect.poll(() => selectedRow.getByLabel('Pinned', { exact: true }).count()).toBe(0) + expect(await drawer.isVisible()).toBe(true) + await more.tap() + await menu.getByRole('menuitem', { name: 'Pin session', exact: true }).tap() + await menu.waitFor({ state: 'hidden' }) + await unpin.waitFor() await more.tap() await menu.getByRole('menuitem', { name: 'Unpin session', exact: true }).tap() await menu.waitFor({ state: 'hidden' }) await expect.poll(() => selectedRow.getByLabel('Pinned', { exact: true }).count()).toBe(0) await drawer.getByRole('button', { name: 'Plugins', exact: true }).tap() await drawer.waitFor({ state: 'hidden' }) - await page.locator('[data-plugin-panel]').waitFor() + const pluginPanel = page.locator('[data-plugin-panel]') + await pluginPanel.waitFor() + for (const width of [390, 767, 768]) { + await page.setViewportSize({ width, height: 844 }) + expect(await pluginPanel.evaluate(el => Number.parseFloat(getComputedStyle(el).paddingLeft))) + .toBeCloseTo(width < 768 ? 20 : width * 0.04, 1) + } + await page.setViewportSize({ width: 390, height: 844 }) + await frame.waitFor() + await opener.click() + await drawer.getByRole('button', { name: 'Automation tasks', exact: true }).tap() + await drawer.waitFor({ state: 'hidden' }) + const tasksContent = page.getByTestId('task-manager-page').locator('[class*="pageContent"]') + await tasksContent.waitFor() + for (const width of [390, 767, 768]) { + await page.setViewportSize({ width, height: 844 }) + expect(await tasksContent.evaluate(el => Number.parseFloat(getComputedStyle(el).paddingLeft))) + .toBeCloseTo(width < 768 ? 20 : width * 0.04, 1) + } + await page.setViewportSize({ width: 390, height: 844 }) + await frame.waitFor() await opener.click() await drawer.waitFor() await page.touchscreen.tap(370, 420) @@ -526,7 +594,9 @@ it('overlays the conversation and closes after navigation without losing its sid 'fold transitions: sidebar controls follow the divider in both directions; reduced motion changes width without animation', 'drawer mask: opacity transitions from 0 to 1 on open and 1 to 0 on close', 'reduced motion: drawer and mask settle without transitions', - 'touch selected Session: More remains visible; archive and pin stay in its menu; pin marker retained', + 'Web header: only the sidebar opener remains, with 48px leading clearance', + 'below 768px: plugin and automation pages use 20px insets; Web view tabs align at 20px, while Desktop and wider Web tabs retain 28px', + 'touch selected Session: More remains visible; update time is hidden; pinned rows offer Unpin before More with Workspace action spacing', 'touch Workspace: actions appear only while expanded, including after folding the focused row', 'fine pointer: folded Workspace actions remain available on hover', 'fine pointer: selected Session actions stay hidden until hover, including at 390px', diff --git a/apps/web/tests/sidebar-right.e2e.ts b/apps/web/tests/sidebar-right.e2e.ts index 307e1adf12..4e5be429ce 100644 --- a/apps/web/tests/sidebar-right.e2e.ts +++ b/apps/web/tests/sidebar-right.e2e.ts @@ -1128,8 +1128,28 @@ describe('web e2e: shipped right Sidebar', () => { expect(await column.locator('[data-dockkit-tab-close]').count()).toBe(0) expect(await column.locator('[data-dockkit-tab-quiet]').count()).toBe(1) await column.locator('[data-dockkit-tab]').first().click({ button: 'right' }) - expect(await page.locator('[data-dockkit-tab-menu]').isVisible()).toBe(false) + // Wait for prepared content, rather than passing before the opening delay. + const emptyMenu = page.locator('[data-context-menu][role="menu"]') + await emptyMenu.waitFor({ state: 'attached' }) + expect(await emptyMenu.evaluate(node => getComputedStyle(node).display)).toBe('none') + expect(await emptyMenu.isVisible()).toBe(false) expect(await page.getByRole('menu').count()).toBe(0) + expect(await column.locator('[data-dockkit-tab]').first().evaluate(node => node.contains(document.activeElement))).toBe(true) + const backingSize = await page.locator('[data-menu-backing]').evaluate((node) => { + const root = document.documentElement + const platform = root.getAttribute('data-platform') + root.setAttribute('data-platform', 'darwin') + try { + const { width, height } = node.getBoundingClientRect() + return { width, height } + } finally { + if (platform === null) root.removeAttribute('data-platform') + else root.setAttribute('data-platform', platform) + } + }) + expect(backingSize).toEqual({ width: 0, height: 0 }) + await page.keyboard.press('Escape') + await emptyMenu.waitFor({ state: 'detached' }) // Any other tab standing alone closes together with the column. Open the // sample file, close the guide (an ordinary close with two tabs), then @@ -1231,13 +1251,10 @@ describe('web e2e: shipped right Sidebar', () => { // is the secondary press. expect(await column.locator('[data-dockkit-tab-more]').count()).toBe(0) await column.locator('[data-dockkit-tab]').filter({ hasText: 'Start' }).click({ button: 'right' }) - const menu = page.locator('[data-dockkit-tab-menu]') + const menu = page.locator('[data-context-menu][role="menu"]') await expect.poll(async () => await menu.count()).toBe(1) - // The kit's one item; the extension seat is declared and rendered, and - // with no registrant it contributes nothing, which is what "declared, not - // speculative" looks like from the outside. - await expect.poll(async () => await menu.getByRole('menuitem').allInnerTexts()).toEqual(['Close']) + await expect.poll(() => menu.ariaSnapshot()).toBe('- menu:\n - menuitem "Close"\n - menuitem "Close Other Tabs"') // The menu hangs below the strip that clips its overflow. Its pixels are // its own: a hit test at its centre lands on it, not on whatever the // strip would have shown through a clipped box. diff --git a/apps/web/tests/workspace-management.e2e.ts b/apps/web/tests/workspace-management.e2e.ts index ba6cb7cbe3..096c159be4 100644 --- a/apps/web/tests/workspace-management.e2e.ts +++ b/apps/web/tests/workspace-management.e2e.ts @@ -567,7 +567,10 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo const consoleWatch = watchConsole(hoverPage) await hoverPage.goto(scaffold.authenticatedUrl) const row = await seededSessionRow(hoverPage) + await row.click() + await hoverPage.getByText('DONE', { exact: true }).waitFor() const title = row.locator('[class*="title"]') + await expect.poll(() => title.innerText()).not.toBe('Untitled') const card = hoverPage.getByRole('button', { name: `Copy: ${await title.innerText()}` }) const tooltip = hoverPage.getByRole('tooltip') const observations: { stage: string; details: boolean; tooltips: string[] }[] = [] @@ -575,6 +578,7 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo observations.push({ stage, details: await card.count() > 0, tooltips: await tooltip.allTextContents() }) } const clockStart = Date.now() + await hoverPage.getByRole('button', { name: 'Account menu', exact: true }).hover() await hoverPage.clock.install({ time: clockStart }) await hoverPage.clock.pauseAt(clockStart + 1000) await title.hover() @@ -612,9 +616,11 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo const menu = row.getByRole('button', { name: /^Session actions for / }) await menu.click() + await hoverPage.clock.runFor(1000) await hoverPage.getByRole('menu').waitFor() expect(await card.count()).toBe(0) await hoverPage.keyboard.press('Escape') + await hoverPage.clock.runFor(1000) await hoverPage.getByRole('menu').waitFor({ state: 'detached' }) await title.hover() await hoverPage.clock.runFor(1600) @@ -821,8 +827,10 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo await item.hover() await page.waitForTimeout(POINTER_HOLD_MS) expect(await page.getByRole('menuitem', { name: 'Rename' }).count()).toBe(1) - // Pointer-leave dismissal still applies once the pointer genuinely leaves. + // Context menus stay open across pointer departure and dismiss on an outside press. await page.getByRole('button', { name: 'Account menu', exact: true }).hover() + expect(await item.isVisible()).toBe(true) + await page.locator('[data-row-key]').first().click() await expect.poll(() => page.getByRole('menuitem', { name: 'Rename' }).count(), { timeout: 5_000 }).toBe(0) expect(tripwire.pageErrors).toEqual([]) }, 60_000) @@ -862,9 +870,8 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) acknowledgeReloadConnectionLoss(tripwire, warningStart) await expect.poll(() => page.getByText('Workspaces', { exact: true }).count(), { timeout: 15_000 }).toBe(1) - // Initial Workspace reconnection can focus the composer after the tree renders. - // Finish that navigation before the next test opens a path editor. - await page.locator('[role="treeitem"][aria-selected="true"]').waitFor({ timeout: 15_000 }) + // The last Session can leave the new-session page with no selected row. + // Wait for composer focus so reconnection cannot steal the next editor's focus. await expect.poll( () => page.locator('[data-composer-input][contenteditable="true"]') .evaluate(element => element === document.activeElement), diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index c653301218..75efc1547d 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -27,6 +27,7 @@ "tests/creation-recommendations.e2e.ts", "tests/plugin-recommendations.e2e.ts", "tests/japanese-plugin-metadata.e2e.ts", + "tests/context-menus.e2e.ts", "tests/additional-locales.e2e.ts", "tests/rich-text-quotes.e2e.ts", "tests/hover-input.e2e.ts", @@ -114,6 +115,7 @@ "tests/plugin-hmr-lifecycle.e2e.ts", "tests/plugin-install-registry.e2e.ts", "tests/plugin-install-github.e2e.ts", + "tests/plugin-install-silent-failure.e2e.ts", "tests/client-plugin-live.e2e.ts", "tests/icon-skin.e2e.ts", "tests/draft-initialization.e2e.ts", diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 39ebd5cd9c..d1766b9e80 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -74,4 +74,4 @@ Hunt these in any doc; [dsh-doc](../.agents/skills/dsh-doc/SKILL.md) runs this l ## Repository references -Use relative Markdown links for current files and tags or PR numbers for historical references. `verify-md-links` checks local targets. [Reference validation](../scripts/verify-repository-references.ts) rejects actual commit identifiers and disallowed organization URLs in maintained files. +Use relative Markdown links for current files and tags or PR numbers for historical references. `verify-md-links` checks local targets. [Reference validation](../scripts/verify-repository-references.ts) rejects commit identifiers containing a hexadecimal letter and disallowed organization URLs in maintained files. Decimal-only tokens are ignored to avoid collisions with numeric data, even when they identify commits. diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 69805a5895..f9140a3c2d 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: 6dfe441b758583b2 - zh: fb28de0533f07432 + en: 5e42f2392f0457d6 + zh: a694691c079e36fb diff --git a/docs/capability-seams.md b/docs/capability-seams.md index e42fc5d08e..faf80ef4fa 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -663,7 +663,7 @@ flowchart LR | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | Owns browser authentication and shared HTTP request dispatch; API adapters register endpoints and streams. | | `ctx.forge` | `seam` | [`experimental-forge`](../packages/experimental/forge) | [`experimental-forge-github`](../packages/experimental/forge-github) | [`experimental-forge-session`](../packages/experimental/forge-session), [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | Providers map remote and change request URLs, look up change requests by head branch, and read status in batches; watchers of one change request share one polling loop. | | `ctx.forgeSession` | `service` | [`experimental-forge-session`](../packages/experimental/forge-session) | - | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | A Session projection derives bindings from shell results and binding records and publishes their URLs without status to clients; push results trigger head-branch discovery, and Session watchers poll bound change requests through the forge registry. | -| `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | Streams one panel state per followed Session: a read-only Git inspection in the Session sandbox, the recognized code host and its sign-in, and the bound change requests with polled status. | +| `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | Streams one panel state per followed Session: Git inspection using Session permissions, the recognized code host and its sign-in, and the bound change requests with polled status. | | `ctx.worktrees` | `seam` | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | - | Explicit experimental creation from a pinned local commit. Existing write permissions govern checkout and shared Git metadata; the working-directory service owns the resulting Session directory. | | `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-working-directory`](../packages/session/tool-working-directory), [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server) | - | One Session projection owns the effective execution directory. The filesystem validates changes; user context reports them while original metadata and write grants stay fixed. | | `ctx.mcpResources` | `seam` | [`mcp-resources`](../packages/mcp/mcp-resources) | [`mcp-client`](../packages/mcp/mcp-client) | [`mcp-resources`](../packages/mcp/mcp-resources) | - | Connection-owned providers serve shared resource tools in the calling agent scope. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index f434835133..5156a43822 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -665,7 +665,7 @@ flowchart LR | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | 负责浏览器认证与共享 HTTP 请求分发;API 适配器注册端点和流。 | | `ctx.forge` | `seam` | [`experimental-forge`](../packages/experimental/forge) | [`experimental-forge-github`](../packages/experimental/forge-github) | [`experimental-forge-session`](../packages/experimental/forge-session), [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | 提供方映射远端与变更请求 URL、按 head 分支查找变更请求并批量读取状态;同一变更请求的监听方共享一个轮询循环。 | | `ctx.forgeSession` | `service` | [`experimental-forge-session`](../packages/experimental/forge-session) | - | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | Session 投影从 shell 结果与绑定记录派生绑定,并把不含状态的 URL 发布给客户端;推送结果触发按 head 分支的发现,Session 监听方通过 forge 注册表轮询已绑定的变更请求。 | -| `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | 为每个被跟随的 Session 推送一份面板状态:在 Session 沙箱中进行的只读 Git 检查、识别出的代码托管平台及其登录状态,以及带轮询状态的已绑定变更请求。 | +| `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | 为每个被跟随的 Session 推送一份面板状态:使用 Session 权限进行的 Git 检查、识别出的代码托管平台及其登录状态,以及带轮询状态的已绑定变更请求。 | | `ctx.worktrees` | `seam` | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | - | 显式实验组合从固定的本地提交创建工作树。检出目录与共享 Git 元数据受现有写权限约束;工作目录服务拥有创建后的 Session 目录。 | | `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-working-directory`](../packages/session/tool-working-directory), [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server) | - | 一个 Session 投影拥有有效执行目录。文件系统验证变更,用户上下文报告目录信息,原始元数据与写入授权保持不变。 | | `ctx.mcpResources` | `seam` | [`mcp-resources`](../packages/mcp/mcp-resources) | [`mcp-client`](../packages/mcp/mcp-client) | [`mcp-resources`](../packages/mcp/mcp-resources) | - | 连接所有者提供的操作在调用 agent 的作用域内服务于共享资源工具。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index ffca5309b4..3d52397d77 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1126,7 +1126,7 @@ export type Config = CuaConfig ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:230`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:232`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1160,7 +1160,7 @@ export interface Config { hosts?: string[] /** Deadline in milliseconds for one `gh` invocation. */ timeoutMs?: number - /** Maximum captured bytes per `gh` output stream. */ + /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ maxOutputBytes?: number } ``` @@ -4832,6 +4832,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) | | `@deepseek-ai/dsh-client-ui-chat` | — | [`packages/client/ui-chat/src/index.ts`](../packages/client/ui-chat/src/index.ts) | | `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-context-menu` | — | [`packages/client/ui-context-menu/src/index.ts`](../packages/client/ui-context-menu/src/index.ts) | | `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) | | `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) | | `@deepseek-ai/dsh-client-ui-creation-recommendations` | — | [`packages/experimental/client-ui-creation-recommendations/src/index.ts`](../packages/experimental/client-ui-creation-recommendations/src/index.ts) | @@ -4839,6 +4840,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-directory-picker-browse` | — | [`packages/client/ui-directory-picker-browse/src/index.ts`](../packages/client/ui-directory-picker-browse/src/index.ts) | | `@deepseek-ai/dsh-client-ui-directory-picker-native` | — | [`packages/client/ui-directory-picker-native/src/index.ts`](../packages/client/ui-directory-picker-native/src/index.ts) | | `@deepseek-ai/dsh-client-ui-entry-customization` | — | [`packages/client/ui-entry-customization/src/index.ts`](../packages/client/ui-entry-customization/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-file-actions` | — | [`packages/client/ui-file-actions/src/index.ts`](../packages/client/ui-file-actions/src/index.ts) | | `@deepseek-ai/dsh-client-ui-file-drag` | — | [`packages/client/ui-file-drag/src/index.ts`](../packages/client/ui-file-drag/src/index.ts) | | `@deepseek-ai/dsh-client-ui-goal` | — | [`packages/client/ui-goal/src/index.ts`](../packages/client/ui-goal/src/index.ts) | | `@deepseek-ai/dsh-client-ui-input-trigger` | — | [`packages/client/ui-input-trigger/src/index.ts`](../packages/client/ui-input-trigger/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index e826fc10e1..9cb8434451 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1128,7 +1128,7 @@ export type Config = CuaConfig ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:230`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:232`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1162,7 +1162,7 @@ export interface Config { hosts?: string[] /** Deadline in milliseconds for one `gh` invocation. */ timeoutMs?: number - /** Maximum captured bytes per `gh` output stream. */ + /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ maxOutputBytes?: number } ``` @@ -4834,6 +4834,7 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) | | `@deepseek-ai/dsh-client-ui-chat` | — | [`packages/client/ui-chat/src/index.ts`](../packages/client/ui-chat/src/index.ts) | | `@deepseek-ai/dsh-client-ui-commands` | — | [`packages/client/ui-commands/src/index.ts`](../packages/client/ui-commands/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-context-menu` | — | [`packages/client/ui-context-menu/src/index.ts`](../packages/client/ui-context-menu/src/index.ts) | | `@deepseek-ai/dsh-client-ui-conversation` | — | [`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts) | | `@deepseek-ai/dsh-client-ui-cordis` | — | [`packages/extensions/ui-cordis/src/index.ts`](../packages/extensions/ui-cordis/src/index.ts) | | `@deepseek-ai/dsh-client-ui-creation-recommendations` | — | [`packages/experimental/client-ui-creation-recommendations/src/index.ts`](../packages/experimental/client-ui-creation-recommendations/src/index.ts) | @@ -4841,6 +4842,7 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-directory-picker-browse` | — | [`packages/client/ui-directory-picker-browse/src/index.ts`](../packages/client/ui-directory-picker-browse/src/index.ts) | | `@deepseek-ai/dsh-client-ui-directory-picker-native` | — | [`packages/client/ui-directory-picker-native/src/index.ts`](../packages/client/ui-directory-picker-native/src/index.ts) | | `@deepseek-ai/dsh-client-ui-entry-customization` | — | [`packages/client/ui-entry-customization/src/index.ts`](../packages/client/ui-entry-customization/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-file-actions` | — | [`packages/client/ui-file-actions/src/index.ts`](../packages/client/ui-file-actions/src/index.ts) | | `@deepseek-ai/dsh-client-ui-file-drag` | — | [`packages/client/ui-file-drag/src/index.ts`](../packages/client/ui-file-drag/src/index.ts) | | `@deepseek-ai/dsh-client-ui-goal` | — | [`packages/client/ui-goal/src/index.ts`](../packages/client/ui-goal/src/index.ts) | | `@deepseek-ai/dsh-client-ui-input-trigger` | — | [`packages/client/ui-input-trigger/src/index.ts`](../packages/client/ui-input-trigger/src/index.ts) | diff --git a/docs/cordis-api/context.md b/docs/cordis-api/context.md index 320b23de1c..453f607768 100644 --- a/docs/cordis-api/context.md +++ b/docs/cordis-api/context.md @@ -110,7 +110,7 @@ The root context of the application (every child context shares it). @experiment ```ts cordis-catalog /** Base URL used to resolve relative plugin/module specifiers, if the runtime sets one. */ -baseUrl?: string +baseUrl?: string | undefined ``` Base URL used to resolve relative plugin/module specifiers, if the runtime sets one. diff --git a/docs/cordis-api/context.zh.md b/docs/cordis-api/context.zh.md index b97fe51eb8..a5c7e36b4b 100644 --- a/docs/cordis-api/context.zh.md +++ b/docs/cordis-api/context.zh.md @@ -112,7 +112,7 @@ root: this ```ts cordis-catalog /** Base URL used to resolve relative plugin/module specifiers, if the runtime sets one. */ -baseUrl?: string +baseUrl?: string | undefined ``` 用于解析相对插件/模块说明符的基础 URL,前提是运行时设置了该值。 diff --git a/docs/cordis-api/events.i18n.yaml b/docs/cordis-api/events.i18n.yaml index 68421a5f2c..f423afad17 100644 --- a/docs/cordis-api/events.i18n.yaml +++ b/docs/cordis-api/events.i18n.yaml @@ -9,29 +9,29 @@ en: 9d809e3de33dd783 zh: b965aee4a65c6c1a /events/ctx-parallel-name-args: - en: e583c71acb606915 - zh: 0560679b20f8d7f0 + en: 9c0a63f484e33428 + zh: 09ee4c26931324af /events/ctx-emit-name-args: - en: ff6f4023b66f8164 - zh: af16d24d663a7eb7 + en: b41bd01cf219cbd6 + zh: 2e9660a05dc07cfc /events/ctx-serial-name-args: - en: c431c0e3ac72e854 - zh: c43b7d899ea8161c + en: 46708104f4d6a034 + zh: f1b7fcb92a5b05c0 /events/ctx-bail-name-args: - en: 85b8b2178c3e3c33 - zh: ad8af3e0743e231c + en: 6577e113d5b8ce40 + zh: b925f8070cf387f7 /events/ctx-waterfall-name-args: - en: 3b32d0511b7da48b - zh: e0ac62e59d8e2152 + en: 105fda32f60c7cea + zh: c67e6c6051c9a1af /events/ctx-on-name-listener-options: - en: 74a1fe55f4a47ec8 - zh: 87d37038af3bab0e + en: ec7c7e8a8b15d460 + zh: 79eba67c31873b0b /events/ctx-once-name-listener-options: - en: 64802f0580705984 - zh: 3f6ce2d7ce1e760d + en: 27143e45f63622dd + zh: 095f804dfa47ad37 /events/eventoptions: - en: 937453f689836c80 - zh: ebf0cc0f28127245 + en: 14ed1031e4a7abee + zh: 2380e2f73f8931af /events/dispatchmode: - en: 1c8548fb249ed794 - zh: 86b92a28f39b2a12 + en: 1081bbd7aa27baf8 + zh: cc4434892b0bb93f diff --git a/docs/cordis-api/events.md b/docs/cordis-api/events.md index 8b8eb2358e..1916532331 100644 --- a/docs/cordis-api/events.md +++ b/docs/cordis-api/events.md @@ -26,7 +26,7 @@ Dispatch an event, running all listeners concurrently. **Returns** a promise resolving once every listener has settled. -[Source](../../vendor/cordis/src/events.ts#L44) +[Source](../../vendor/cordis/src/events.ts#L43) ### ctx.emit(name, ...args) @@ -46,7 +46,7 @@ Dispatch an event synchronously, ignoring listener return values. - `name` — the event name. - `args` — arguments passed to every listener. -[Source](../../vendor/cordis/src/events.ts#L53) +[Source](../../vendor/cordis/src/events.ts#L52) ### ctx.serial(name, ...args) @@ -69,7 +69,7 @@ Dispatch an event, awaiting listeners in order until one bails. **Returns** the first bail value (non-null, non-false, non-undefined), if any. -[Source](../../vendor/cordis/src/events.ts#L63) +[Source](../../vendor/cordis/src/events.ts#L62) ### ctx.bail(name, ...args) @@ -92,7 +92,7 @@ Dispatch an event, calling listeners in order until one bails. **Returns** the first bail value (non-null, non-false, non-undefined), if any. -[Source](../../vendor/cordis/src/events.ts#L73) +[Source](../../vendor/cordis/src/events.ts#L72) ### ctx.waterfall(name, ...args) @@ -120,7 +120,7 @@ Each listener wraps the rest of the chain: calling `next()` invokes the next lis **Returns** the outermost listener's return value. -[Source](../../vendor/cordis/src/events.ts#L86) +[Source](../../vendor/cordis/src/events.ts#L85) ### ctx.on(name, listener, options?) @@ -144,7 +144,7 @@ Register an event listener owned by the current fiber. **Returns** a disposer removing the listener; `true` if it was still registered. -[Source](../../vendor/cordis/src/events.ts#L97) +[Source](../../vendor/cordis/src/events.ts#L96) ### ctx.once(name, listener, options?) @@ -168,7 +168,7 @@ Same as `on()`, but the listener disposes itself after its first call. **Returns** a disposer removing the listener; `true` if it was still registered. -[Source](../../vendor/cordis/src/events.ts#L106) +[Source](../../vendor/cordis/src/events.ts#L105) ## EventOptions @@ -184,7 +184,7 @@ interface EventOptions { } ``` -[Source](../../vendor/cordis/src/events.ts#L112) +[Source](../../vendor/cordis/src/events.ts#L111) ## DispatchMode @@ -204,4 +204,4 @@ Event dispatch strategy used by the event service. type DispatchMode = 'emit' | 'parallel' | 'serial' | 'bail' | 'waterfall' ``` -[Source](../../vendor/cordis/src/events.ts#L32) +[Source](../../vendor/cordis/src/events.ts#L31) diff --git a/docs/cordis-api/events.zh.md b/docs/cordis-api/events.zh.md index 60b0580496..b66a1fc4d3 100644 --- a/docs/cordis-api/events.zh.md +++ b/docs/cordis-api/events.zh.md @@ -28,7 +28,7 @@ parallel(thisArg: NoInfer>, name: K, **返回值**:一个 Promise,在所有监听器均已完成后兑现。 -[源码](../../vendor/cordis/src/events.ts#L44) +[源码](../../vendor/cordis/src/events.ts#L43) ### ctx.emit(name, ...args) @@ -48,7 +48,7 @@ emit(thisArg: NoInfer>, name: K, ... - `name`:事件名称。 - `args`:传递给每个监听器的参数。 -[源码](../../vendor/cordis/src/events.ts#L53) +[源码](../../vendor/cordis/src/events.ts#L52) ### ctx.serial(name, ...args) @@ -71,7 +71,7 @@ serial(thisArg: NoInfer>, name: K, . **返回值**:第一个提前终止值(非 null、非 false 且非 undefined);如果没有,则不返回此类值。 -[源码](../../vendor/cordis/src/events.ts#L63) +[源码](../../vendor/cordis/src/events.ts#L62) ### ctx.bail(name, ...args) @@ -94,7 +94,7 @@ bail(thisArg: NoInfer>, name: K, ... **返回值**:第一个提前终止值(非 null、非 false 且非 undefined);如果没有,则不返回此类值。 -[源码](../../vendor/cordis/src/events.ts#L73) +[源码](../../vendor/cordis/src/events.ts#L72) ### ctx.waterfall(name, ...args) @@ -122,7 +122,7 @@ waterfall(thisArg: NoInfer>, name: K **返回值**:最外层监听器的返回值。 -[源码](../../vendor/cordis/src/events.ts#L86) +[源码](../../vendor/cordis/src/events.ts#L85) ### ctx.on(name, listener, options?) @@ -146,7 +146,7 @@ on(name: K, listener: Events[K], options?: boolean | Eve **返回值**:一个用于移除监听器的资源释放函数;如果调用该函数时监听器仍处于注册状态,则返回 `true`。 -[源码](../../vendor/cordis/src/events.ts#L97) +[源码](../../vendor/cordis/src/events.ts#L96) ### ctx.once(name, listener, options?) @@ -170,7 +170,7 @@ once(name: K, listener: Events[K], options?: boolean | E **返回值**:一个用于移除监听器的资源释放函数;如果调用该函数时监听器仍处于注册状态,则返回 `true`。 -[源码](../../vendor/cordis/src/events.ts#L106) +[源码](../../vendor/cordis/src/events.ts#L105) ## EventOptions @@ -186,7 +186,7 @@ interface EventOptions { } ``` -[源码](../../vendor/cordis/src/events.ts#L112) +[源码](../../vendor/cordis/src/events.ts#L111) ## DispatchMode @@ -206,4 +206,4 @@ interface EventOptions { type DispatchMode = 'emit' | 'parallel' | 'serial' | 'bail' | 'waterfall' ``` -[源码](../../vendor/cordis/src/events.ts#L32) +[源码](../../vendor/cordis/src/events.ts#L31) diff --git a/docs/cordis-api/fiber.i18n.yaml b/docs/cordis-api/fiber.i18n.yaml index 042af3ba02..aeba613660 100644 --- a/docs/cordis-api/fiber.i18n.yaml +++ b/docs/cordis-api/fiber.i18n.yaml @@ -9,14 +9,14 @@ en: b5b3510f4b6dd13a zh: a0c70471b6d779b5 /fiber/ctx-effect-execute-label: - en: ef3418fd5ffbe86d - zh: c98935435da8bc7e + en: 38bab93cf931eec1 + zh: 50fed09622da4926 /fiber/ctx-fiber: en: a10e38bf26b4ecfe zh: 7c91817984c95c99 /fiber/the-fiber-class: - en: 0e0fcb134ed44957 - zh: 326f4232aa0e65d1 + en: 31ca1205552db9ef + zh: 5fa2e5b9a7396576 /fiber/the-fiber-class/fiber-uid: en: 2f0eb3658bb8497e zh: 65d3c17ca8bd4f95 @@ -24,50 +24,53 @@ en: 1b527d85759324f9 zh: 54aa40db2705b95c /fiber/the-fiber-class/fiber-config: - en: 1efe137a7ef0e599 - zh: bb4b9818fb48f4e9 + en: 73b05dc38761b681 + zh: d663668f3e8fd33f /fiber/the-fiber-class/fiber-state: - en: 999ad29dfc29661b - zh: 20245d11c338e3f1 + en: eda419fecddc4dc8 + zh: 1a1b90f405cf3cbc /fiber/the-fiber-class/fiber-dispose: - en: 29e304d183eb9104 - zh: 9ac5023f518e06c4 -/fiber/the-fiber-class/fiber-store: - en: c4185e5d051136a2 - zh: 5714d9e4f5461ca3 + en: 43f4ad79a728a492 + zh: 71b216695d0afb22 +/fiber/the-fiber-class/fiber-committed: + en: 0485c9d782bf90da + zh: 74304cd05e9c0796 +/fiber/the-fiber-class/fiber-provisions: + en: 1cf8235d0ca54124 + zh: 3d2e39064853165f /fiber/the-fiber-class/fiber-inertia: en: 2a3b1d3bc37bf986 zh: 83bd257ee685d38b /fiber/the-fiber-class/fiber-name: - en: e5c2ecca13167a32 - zh: 284a461f0f1cd35b + en: cdc0677ce1d83361 + zh: a58305521a0626de /fiber/the-fiber-class/fiber-assertactive: - en: cceb503899634d09 - zh: a8381af1a23436f3 + en: 0c3e8008ff2d69e2 + zh: 7b454626d3e3a3b6 /fiber/the-fiber-class/fiber-effect-execute-label: - en: 55dcfacf295bbcf2 - zh: 6e3ec27bb8da5a3d + en: 0e905aa798ce3830 + zh: bbd0b0c537097d37 /fiber/the-fiber-class/fiber-geteffects: - en: 4d739a9c186fd9c2 - zh: f80fd3b87e79b004 + en: 729a1000bda8ee36 + zh: 5bfc19df3addab80 /fiber/the-fiber-class/fiber-rawconfig: - en: 898aab51825bd8c3 - zh: b9ab6339574002df + en: 80d4007e42bd8b47 + zh: 14c11dc09c6402ce /fiber/the-fiber-class/fiber-effectiveconfig: - en: 93ac680251e7023f - zh: 8ea7d7de5db39b8e + en: 8e9fcdcf458c8bde + zh: 36d21cafbf4f0198 /fiber/the-fiber-class/fiber-resolveconfig-config: - en: d7319852e2a1c3a9 - zh: 3300fac049227006 + en: f8a9ca27b288bd4c + zh: 03ce360b5200fbdb /fiber/the-fiber-class/fiber-await: - en: c9a6544cacdbc28e - zh: 636bf93efad95bc9 + en: 3f228c1861466386 + zh: 43b3f3acfc3d314b /fiber/the-fiber-class/fiber-restart: - en: 6ffc1baba98d689f - zh: 7e13bc92225c7e0a + en: 152116f669f52e95 + zh: 11d3cd941ce32d88 /fiber/the-fiber-class/fiber-update-config-nosave: - en: 5c176a6e67073e92 - zh: ee07edc8dbf7c1f3 + en: a4f711258eb70e47 + zh: fff4d880d820de10 /fiber/effect: en: 007d5b214e8a8610 zh: d74c26fbb1b8aeb6 diff --git a/docs/cordis-api/fiber.md b/docs/cordis-api/fiber.md index e85cc7b3e6..3bfc3a00e9 100644 --- a/docs/cordis-api/fiber.md +++ b/docs/cordis-api/fiber.md @@ -34,7 +34,7 @@ Register a cleanup-aware effect on this fiber. **Returns** a disposer that tears the effect down and settles once done. -[Source](../../vendor/cordis/src/fiber.ts#L415) +[Source](../../vendor/cordis/src/fiber.ts#L421) ### ctx.fiber @@ -51,7 +51,7 @@ The fiber (plugin runtime instance) that owns this context. Runtime instance of one plugin application. -A fiber tracks dependency state, validated config, lifecycle effects, and cleanup for the plugin context returned by `ctx.plugin()`. +A fiber tracks dependency state, raw and effective config, lifecycle effects, and cleanup for the plugin context returned by `ctx.plugin()`. [Source](../../vendor/cordis/src/fiber.ts#L184) @@ -80,11 +80,11 @@ The context this fiber's plugin runs in (extends the parent context). ### fiber.config ```ts cordis-catalog -/** The validated plugin config (updated by `update()`); read through {@link effectiveConfig}. */ +/** Raw plugin input retained for the next activation. */ public config: any ``` -The validated plugin config (updated by `update()`); read through effectiveConfig. +Raw plugin input retained for the next activation. [Source](../../vendor/cordis/src/fiber.ts#L190) @@ -97,7 +97,7 @@ public state Current lifecycle state; transitions emit `internal/status`. -[Source](../../vendor/cordis/src/fiber.ts#L194) +[Source](../../vendor/cordis/src/fiber.ts#L192) ### fiber.dispose @@ -108,16 +108,27 @@ public readonly dispose: () => Promise Dispose this fiber: unload the plugin, then settle once cleanup finished. -[Source](../../vendor/cordis/src/fiber.ts#L196) +[Source](../../vendor/cordis/src/fiber.ts#L194) -### fiber.store +### fiber.committed ```ts cordis-catalog -/** Snapshot of required service implementations while loaded; `undefined` otherwise. */ -public store: Dict | undefined +/** Required implementations retained through dependent teardown. */ +public committed: Readonly> | undefined ``` -Snapshot of required service implementations while loaded; `undefined` otherwise. +Required implementations retained through dependent teardown. + +[Source](../../vendor/cordis/src/fiber.ts#L196) + +### fiber.provisions + +```ts cordis-catalog +/** Service implementations owned by this fiber, including isolated provisions. */ +public readonly provisions: Set +``` + +Service implementations owned by this fiber, including isolated provisions. [Source](../../vendor/cordis/src/fiber.ts#L198) @@ -141,7 +152,7 @@ get name() The plugin's display name, inherited from the nearest named ancestor, else `'root'`. -[Source](../../vendor/cordis/src/fiber.ts#L336) +[Source](../../vendor/cordis/src/fiber.ts#L342) ### fiber.assertActive() @@ -159,7 +170,7 @@ Throw if the fiber has already been disposed. **Returns** nothing when the fiber is still active. -[Source](../../vendor/cordis/src/fiber.ts#L351) +[Source](../../vendor/cordis/src/fiber.ts#L357) ### fiber.effect(execute, label?) @@ -190,7 +201,7 @@ Register a cleanup-aware effect on this fiber. **Returns** a disposer that tears the effect down and settles once done. -[Source](../../vendor/cordis/src/fiber.ts#L415) +[Source](../../vendor/cordis/src/fiber.ts#L421) ### fiber.getEffects() @@ -207,7 +218,7 @@ Return metadata for currently registered effects. **Returns** one `EffectMeta` tree per labeled live effect. -[Source](../../vendor/cordis/src/fiber.ts#L568) +[Source](../../vendor/cordis/src/fiber.ts#L574) ### fiber.rawConfig @@ -218,21 +229,22 @@ get rawConfig(): unknown Raw input retained for the next activation, without evaluating expressions or validating it. -[Source](../../vendor/cordis/src/fiber.ts#L642) +[Source](../../vendor/cordis/src/fiber.ts#L649) ### fiber.effectiveConfig ```ts cordis-catalog /** - * The config object published by the existing activation/update lifecycle, without cloning or re-parsing. - * It is undefined before the first resolution and remains readable after unload; callers requiring a live instance check `state`. + * The object passed to plugin activation or the latest successful update that retained the instance. + * Candidate resolution does not publish it; volatile updates retain its references. + * Undefined before activation and readable after unload; callers requiring a live instance check `state`. */ get effectiveConfig(): unknown ``` -The config object published by the existing activation/update lifecycle, without cloning or re-parsing. It is undefined before the first resolution and remains readable after unload; callers requiring a live instance check `state`. +The object passed to plugin activation or the latest successful update that retained the instance. Candidate resolution does not publish it; volatile updates retain its references. Undefined before activation and readable after unload; callers requiring a live instance check `state`. -[Source](../../vendor/cordis/src/fiber.ts#L655) +[Source](../../vendor/cordis/src/fiber.ts#L664) ### fiber.resolveConfig(config) @@ -254,7 +266,7 @@ Evaluate and validate a candidate using this fiber's `internal/config` hooks and **Returns** The candidate's resolved config, retaining the schema's result identity. -[Source](../../vendor/cordis/src/fiber.ts#L667) +[Source](../../vendor/cordis/src/fiber.ts#L676) ### fiber.await() @@ -272,7 +284,7 @@ Wait for current lifecycle work and rethrow startup errors. **Returns** this fiber, once it has settled into a stable state. -[Source](../../vendor/cordis/src/fiber.ts#L731) +[Source](../../vendor/cordis/src/fiber.ts#L754) ### fiber.restart() @@ -290,35 +302,29 @@ Dispose and immediately reload this plugin with its current config. **Returns** a promise resolving once the reload settled. -[Source](../../vendor/cordis/src/fiber.ts#L745) +[Source](../../vendor/cordis/src/fiber.ts#L768) ### fiber.update(config, noSave?) ```ts cordis-catalog /** - * Validate and apply new config, then restart the plugin. - * - * Runs the `internal/update` waterfall first, so update hooks (and HMR) - * can veto or replace the restart. - * - * @param config — the new raw config; validated before anything restarts. - * @param noSave — hint for persistence hooks not to write the change back. - * @returns nothing; the restart runs behind the `internal/update` waterfall. - * @throws {ValidationError} when the new config fails validation. + * Resolve a candidate, retain its raw config and apply it through the update waterfall. + * @param config Raw config; pending fibers defer resolution until activation. + * @param noSave Suppress the persistence notification when true. + * @returns The awaited update/restart result, or undefined when a synchronous listener handles it. + * @throws {ValidationError} when an active fiber's candidate is invalid. */ -update(config: any, noSave = false) +update(config: any, noSave = false): Awaitable ``` -Validate and apply new config, then restart the plugin. +Resolve a candidate, retain its raw config and apply it through the update waterfall. -Runs the `internal/update` waterfall first, so update hooks (and HMR) can veto or replace the restart. +- `config` — Raw config; pending fibers defer resolution until activation. +- `noSave` — Suppress the persistence notification when true. -- `config` — the new raw config; validated before anything restarts. -- `noSave` — hint for persistence hooks not to write the change back. +**Returns** The awaited update/restart result, or undefined when a synchronous listener handles it. -**Returns** nothing; the restart runs behind the `internal/update` waterfall. - -[Source](../../vendor/cordis/src/fiber.ts#L764) +[Source](../../vendor/cordis/src/fiber.ts#L783) ## Effect diff --git a/docs/cordis-api/fiber.zh.md b/docs/cordis-api/fiber.zh.md index d529013e73..88d253452d 100644 --- a/docs/cordis-api/fiber.zh.md +++ b/docs/cordis-api/fiber.zh.md @@ -36,7 +36,7 @@ effect(execute: () => Effect, label?: string): AsyncDisposable> **返回**一个用于撤销该作用的清理函数,并在清理完成后结算。 -[源码](../../vendor/cordis/src/fiber.ts#L415) +[源码](../../vendor/cordis/src/fiber.ts#L421) ### ctx.fiber @@ -53,7 +53,7 @@ fiber: Fiber 单次插件应用的运行时实例。 -fiber 会跟踪 `ctx.plugin()` 返回的插件上下文所对应的依赖状态、经过校验的配置、生命周期作用和清理操作。 +fiber 会跟踪 `ctx.plugin()` 返回的插件上下文所对应的依赖状态、原始配置与有效配置、生命周期作用和清理操作。 [源码](../../vendor/cordis/src/fiber.ts#L184) @@ -82,11 +82,11 @@ public readonly ctx: Context ### fiber.config ```ts cordis-catalog -/** The validated plugin config (updated by `update()`); read through {@link effectiveConfig}. */ +/** Raw plugin input retained for the next activation. */ public config: any ``` -经过校验的插件配置(由 `update()` 更新);通过 `effectiveConfig` 读取。 +为下次激活保留的原始插件输入。 [源码](../../vendor/cordis/src/fiber.ts#L190) @@ -99,7 +99,7 @@ public state 当前生命周期状态;状态转换会发出 `internal/status`。 -[源码](../../vendor/cordis/src/fiber.ts#L194) +[源码](../../vendor/cordis/src/fiber.ts#L192) ### fiber.dispose @@ -110,16 +110,27 @@ public readonly dispose: () => Promise dispose 此 fiber:卸载插件,并在清理完成后结算。 -[源码](../../vendor/cordis/src/fiber.ts#L196) +[源码](../../vendor/cordis/src/fiber.ts#L194) -### fiber.store +### fiber.committed ```ts cordis-catalog -/** Snapshot of required service implementations while loaded; `undefined` otherwise. */ -public store: Dict | undefined +/** Required implementations retained through dependent teardown. */ +public committed: Readonly> | undefined ``` -加载期间所需服务实现的快照;其他情况下为 `undefined`。 +在依赖方清理完成前保留的所需服务实现。 + +[源码](../../vendor/cordis/src/fiber.ts#L196) + +### fiber.provisions + +```ts cordis-catalog +/** Service implementations owned by this fiber, including isolated provisions. */ +public readonly provisions: Set +``` + +此 fiber 拥有的服务实现,包括隔离域中的服务。 [源码](../../vendor/cordis/src/fiber.ts#L198) @@ -143,7 +154,7 @@ get name() 插件的显示名称,继承自最近的具名祖先;如果不存在,则为 `'root'`。 -[源码](../../vendor/cordis/src/fiber.ts#L336) +[源码](../../vendor/cordis/src/fiber.ts#L342) ### fiber.assertActive() @@ -161,7 +172,7 @@ assertActive() **返回**:fiber 仍处于活动状态时不返回任何内容。 -[源码](../../vendor/cordis/src/fiber.ts#L351) +[源码](../../vendor/cordis/src/fiber.ts#L357) ### fiber.effect(execute, label?) @@ -192,7 +203,7 @@ effect(execute: () => Effect, label?: string): AsyncDisposable> **返回**一个用于撤销该作用的清理函数,并在清理完成后结算。 -[源码](../../vendor/cordis/src/fiber.ts#L415) +[源码](../../vendor/cordis/src/fiber.ts#L421) ### fiber.getEffects() @@ -209,7 +220,7 @@ getEffects() **返回**:每个带标签的活动作用对应一棵 `EffectMeta` 树。 -[源码](../../vendor/cordis/src/fiber.ts#L568) +[源码](../../vendor/cordis/src/fiber.ts#L574) ### fiber.rawConfig @@ -218,23 +229,25 @@ getEffects() get rawConfig(): unknown ``` + 保留供下次激活使用的原始输入,不执行表达式求值或验证。 -[源码](../../vendor/cordis/src/fiber.ts#L642) +[源码](../../vendor/cordis/src/fiber.ts#L649) ### fiber.effectiveConfig ```ts cordis-catalog /** - * The config object published by the existing activation/update lifecycle, without cloning or re-parsing. - * It is undefined before the first resolution and remains readable after unload; callers requiring a live instance check `state`. + * The object passed to plugin activation or the latest successful update that retained the instance. + * Candidate resolution does not publish it; volatile updates retain its references. + * Undefined before activation and readable after unload; callers requiring a live instance check `state`. */ get effectiveConfig(): unknown ``` -既有激活/更新生命周期发布的配置对象,不克隆或重新解析。首次解析前为 undefined,卸载后仍可读取;需要运行实例的调用方应检查 `state`。 +传给插件激活过程或最近一次成功保留实例的更新的对象。候选配置求值不发布结果;volatile 更新保留其中的引用。激活前为 undefined,卸载后仍可读取;需要运行中实例的调用方还应检查 `state`。 -[源码](../../vendor/cordis/src/fiber.ts#L655) +[源码](../../vendor/cordis/src/fiber.ts#L664) ### fiber.resolveConfig(config) @@ -250,13 +263,14 @@ get effectiveConfig(): unknown resolveConfig(config: unknown): unknown ``` + 通过此 fiber 的 `internal/config` 钩子和运行时 schema 对候选值求值并验证。此操作不发布结果、不替换原始输入,也不提交运行中的 volatile 引用。钩子访问的注入服务必须已经可用。 - `config`:原始候选输入。 **返回**候选配置的解析结果,保留 schema 返回对象的身份。 -[源码](../../vendor/cordis/src/fiber.ts#L667) +[源码](../../vendor/cordis/src/fiber.ts#L676) ### fiber.await() @@ -274,7 +288,7 @@ async await() **返回**:进入稳定状态后的此 fiber。 -[源码](../../vendor/cordis/src/fiber.ts#L731) +[源码](../../vendor/cordis/src/fiber.ts#L754) ### fiber.restart() @@ -292,35 +306,29 @@ dispose 此插件,并立即使用其当前配置重新加载。 **返回**一个在重新加载完成后兑现的 promise。 -[源码](../../vendor/cordis/src/fiber.ts#L745) +[源码](../../vendor/cordis/src/fiber.ts#L768) ### fiber.update(config, noSave?) ```ts cordis-catalog /** - * Validate and apply new config, then restart the plugin. - * - * Runs the `internal/update` waterfall first, so update hooks (and HMR) - * can veto or replace the restart. - * - * @param config — the new raw config; validated before anything restarts. - * @param noSave — hint for persistence hooks not to write the change back. - * @returns nothing; the restart runs behind the `internal/update` waterfall. - * @throws {ValidationError} when the new config fails validation. + * Resolve a candidate, retain its raw config and apply it through the update waterfall. + * @param config Raw config; pending fibers defer resolution until activation. + * @param noSave Suppress the persistence notification when true. + * @returns The awaited update/restart result, or undefined when a synchronous listener handles it. + * @throws {ValidationError} when an active fiber's candidate is invalid. */ -update(config: any, noSave = false) +update(config: any, noSave = false): Awaitable ``` -校验并应用新配置,然后重新启动插件。 +求值候选配置,保留原始输入,并通过更新 waterfall 应用结果。 -首先运行 `internal/update` waterfall(瀑布式事件),因此更新钩子(以及 HMR(热模块替换))可以否决或取代重新启动操作。 +- `config` — 原始配置;pending fiber 将求值推迟到激活时。 +- `noSave` — 为 true 时不发出持久化通知。 -- `config`:新的原始配置;在任何内容重新启动前进行校验。 -- `noSave`:提示持久化钩子不要写回此变更。 +**返回** 可等待的更新或重启结果;同步监听器处理更新时为 undefined。 -**返回**无返回值;重启由 `internal/update` waterfall 执行。 - -[源码](../../vendor/cordis/src/fiber.ts#L764) +[源码](../../vendor/cordis/src/fiber.ts#L783) ## Effect diff --git a/docs/cordis-api/inherited.md b/docs/cordis-api/inherited.md index cc62683cb5..c414eaedd5 100644 --- a/docs/cordis-api/inherited.md +++ b/docs/cordis-api/inherited.md @@ -21,15 +21,16 @@ This file is GENERATED from source (`scripts/gen-cordis-catalog.ts`) and verifie ## Inherited events (cordis core + loader/hmr/timer) -- `internal/plugin` — A plugin fiber was created. ([`vendor/cordis/src/events.ts:331`](../../vendor/cordis/src/events.ts)) -- `internal/status` — A fiber changed lifecycle state. ([`vendor/cordis/src/events.ts:333`](../../vendor/cordis/src/events.ts)) -- `internal/service` — Interception hook for a service binding (no core producer). ([`vendor/cordis/src/events.ts:341`](../../vendor/cordis/src/events.ts)) -- `internal/update` — Waterfall: a fiber config update is being applied. ([`vendor/cordis/src/events.ts:343`](../../vendor/cordis/src/events.ts)) -- `internal/config` — Waterfall: a fiber config is being resolved before validation. ([`vendor/cordis/src/events.ts:339`](../../vendor/cordis/src/events.ts)) -- `internal/get` — Waterfall: a service is being read from the store. ([`vendor/cordis/src/events.ts:345`](../../vendor/cordis/src/events.ts)) -- `internal/set` — Waterfall: a service is being written to the store. ([`vendor/cordis/src/events.ts:347`](../../vendor/cordis/src/events.ts)) -- `internal/listener` — A listener was registered. ([`vendor/cordis/src/events.ts:349`](../../vendor/cordis/src/events.ts)) -- `internal/dispatch` — An event is being dispatched to listeners. ([`vendor/cordis/src/events.ts:351`](../../vendor/cordis/src/events.ts)) +- `internal/plugin` — A plugin fiber was created. ([`vendor/cordis/src/events.ts:337`](../../vendor/cordis/src/events.ts)) +- `internal/status` — A fiber changed lifecycle state. ([`vendor/cordis/src/events.ts:339`](../../vendor/cordis/src/events.ts)) +- `internal/service` — A service binding was refreshed in the matching isolation scope. ([`vendor/cordis/src/events.ts:341`](../../vendor/cordis/src/events.ts)) +- `internal/update` — Waterfall: apply resolved config; omitting next() keeps the current instance. ([`vendor/cordis/src/events.ts:348`](../../vendor/cordis/src/events.ts)) +- `internal/commit` — Persist raw config from a programmatic update unless noSave is set. ([`vendor/cordis/src/events.ts:355`](../../vendor/cordis/src/events.ts)) +- `internal/config` — Waterfall: resolve a candidate after injections are active without publishing it. ([`vendor/cordis/src/events.ts:362`](../../vendor/cordis/src/events.ts)) +- `internal/get` — Waterfall: a service is being read from the store. ([`vendor/cordis/src/events.ts:364`](../../vendor/cordis/src/events.ts)) +- `internal/set` — Waterfall: a service is being written to the store. ([`vendor/cordis/src/events.ts:366`](../../vendor/cordis/src/events.ts)) +- `internal/listener` — A listener was registered. ([`vendor/cordis/src/events.ts:368`](../../vendor/cordis/src/events.ts)) +- `internal/dispatch` — An event is being dispatched to listeners. ([`vendor/cordis/src/events.ts:370`](../../vendor/cordis/src/events.ts)) - `exit` — The process is exiting on a signal. ([`vendor/loader/src/index.ts:25`](../../vendor/loader/src/index.ts)) - `loader/config-update` — The loader config tree changed. ([`vendor/loader/src/index.ts:26`](../../vendor/loader/src/index.ts)) - `loader/entry-init` — A config entry is being initialized. ([`vendor/loader/src/index.ts:27`](../../vendor/loader/src/index.ts)) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 5c24b55d2a..1f2dc0b047 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -14,7 +14,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team` | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team` | | `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | @@ -51,7 +51,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:67`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:77`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | | `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:59`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes` | +| `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes`, `server` | | `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | @@ -59,11 +59,11 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:75`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | -| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:427`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:433`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:440`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:419`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | -| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:447`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:432`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:438`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:445`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:424`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | +| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:452`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | | `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:168`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` | | `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:484`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | | `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:74`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | @@ -104,15 +104,16 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | Event string | Dispatchers | Listeners | | --- | --- | --- | | `agent/request` | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic) | -| `connection/reset` | `gateway` (`emit`) | - | +| `connection/reset` | `gateway` (`emit`) | `terminal-controller`, `ui-settings` | | `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | | `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) | | `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), `modules` | | `internal/service` | - | `client-ui-forge`, `gateway` | -| `internal/status` | - | [`agent`](../packages/core/agent), `inspector`, `translator`, [`web`](../packages/web/web) | -| `internal/update` | - | [`app-boot`](../packages/boot/app-boot) | +| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `translator`, [`web`](../packages/web/web) | | `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text` | +| `locale/change` | `locale` (`emit`) | `locale` | | `slots/changed` | `ui-renderer` (`emit`) | - | +| `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-theme` | Maintenance mode: generated: Cordis event declarations and producer/listener edges are resolved from the repository TypeScript Program. diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 4faa80eb3a..13c54dd8e3 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -16,7 +16,7 @@ | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | | `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team` | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team` | | `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | @@ -53,7 +53,7 @@ | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:67`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:77`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | | `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:59`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes` | +| `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes`, `server` | | `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | | `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | @@ -61,11 +61,11 @@ | `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` | | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:75`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) | | `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:48`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` | -| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:427`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:433`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:440`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | -| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:419`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | -| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:447`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:432`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:438`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:445`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | +| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:424`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | +| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:452`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | | `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:168`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` | | `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:484`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | | `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:74`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | @@ -106,15 +106,16 @@ | Event string | Dispatchers | Listeners | | --- | --- | --- | | `agent/request` | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic) | -| `connection/reset` | `gateway` (`emit`) | - | +| `connection/reset` | `gateway` (`emit`) | `terminal-controller`, `ui-settings` | | `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) | | `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) | | `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), `modules` | | `internal/service` | - | `client-ui-forge`, `gateway` | -| `internal/status` | - | [`agent`](../packages/core/agent), `inspector`, `translator`, [`web`](../packages/web/web) | -| `internal/update` | - | [`app-boot`](../packages/boot/app-boot) | +| `internal/status` | - | [`agent`](../packages/core/agent), `claude-code-mods`, `inspector`, `translator`, [`web`](../packages/web/web) | | `loader/volatile-update` | - | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text` | +| `locale/change` | `locale` (`emit`) | `locale` | | `slots/changed` | `ui-renderer` (`emit`) | - | +| `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-theme` | Maintenance mode: generated: Cordis event declarations and producer/listener edges are resolved from the repository TypeScript Program. diff --git a/docs/module-graph.md b/docs/module-graph.md index eedf1ce2df..840655de04 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -166,12 +166,14 @@ flowchart TD pkg_client_ui_chat["client-ui-chat"] pkg_client_ui_cli_account["client-ui-cli-account"] pkg_client_ui_commands["client-ui-commands"] + pkg_client_ui_context_menu["client-ui-context-menu"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_deliverables["client-ui-deliverables"] pkg_client_ui_directory_picker_browse["client-ui-directory-picker-browse"] pkg_client_ui_directory_picker_native["client-ui-directory-picker-native"] pkg_client_ui_dockkit["client-ui-dockkit"] pkg_client_ui_entry_customization["client-ui-entry-customization"] + pkg_client_ui_file_actions["client-ui-file-actions"] pkg_client_ui_file_drag["client-ui-file-drag"] pkg_client_ui_goal["client-ui-goal"] pkg_client_ui_input_trigger["client-ui-input-trigger"] @@ -1425,6 +1427,7 @@ flowchart TD pkg_tool_ralph --> pkg_system_prompt pkg_tool_ralph --> pkg_tools pkg_tool_ralph --> pkg_workflow + pkg_sdk_protocol --> pkg_commands pkg_sdk_protocol --> pkg_llm pkg_sdk_protocol --> pkg_session pkg_sdk_protocol --> pkg_subagent @@ -1469,6 +1472,7 @@ flowchart TD pkg_client_test_runtime --> pkg_client_modules pkg_client_test_runtime --> pkg_client_store pkg_client_test_runtime --> pkg_client_ui_chat + pkg_client_test_runtime --> pkg_client_ui_context_menu pkg_client_test_runtime --> pkg_client_ui_conversation pkg_client_test_runtime --> pkg_client_ui_renderer pkg_client_test_runtime --> pkg_client_ui_session @@ -1491,6 +1495,8 @@ flowchart TD pkg_tool_schedule --> pkg_tools pkg_sdk_jsonrpc_server --> pkg_agent pkg_sdk_jsonrpc_server --> pkg_attachment + pkg_sdk_jsonrpc_server --> pkg_commands + pkg_sdk_jsonrpc_server --> pkg_goal pkg_sdk_jsonrpc_server --> pkg_llm pkg_sdk_jsonrpc_server --> pkg_llm_deepseek_api_key pkg_sdk_jsonrpc_server --> pkg_schedule @@ -1554,12 +1560,14 @@ flowchart TD | [`client-ui-chat`](../packages/client/ui-chat) | `client` | — | | [`client-ui-cli-account`](../packages/client/ui-cli-account) | `client` | — | | [`client-ui-commands`](../packages/client/ui-commands) | `client` | — | +| [`client-ui-context-menu`](../packages/client/ui-context-menu) | `client` | — | | [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | — | | [`client-ui-deliverables`](../packages/client/ui-deliverables) | `client` | — | | [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse) | `client` | — | | [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native) | `client` | — | | [`client-ui-dockkit`](../packages/client/ui-dockkit) | `client` | — | | [`client-ui-entry-customization`](../packages/client/ui-entry-customization) | `client` | — | +| [`client-ui-file-actions`](../packages/client/ui-file-actions) | `client` | — | | [`client-ui-file-drag`](../packages/client/ui-file-drag) | `client` | — | | [`client-ui-goal`](../packages/client/ui-goal) | `client` | — | | [`client-ui-input-trigger`](../packages/client/ui-input-trigger) | `client` | — | @@ -1869,13 +1877,13 @@ flowchart TD | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | -| [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | | [`experimental-tool-agent-team`](../packages/experimental/tool-agent-team) | `experimental` | [`agent`](../packages/core/agent), [`experimental-agent-team`](../packages/experimental/agent-team), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`api-session-controller`](../packages/api/session-controller), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-time`](../packages/util/time), [`workspace`](../packages/workspace/workspace) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | -| [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | +| [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-context-menu`](../packages/client/ui-context-menu), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`tool-schedule`](../packages/schedule/tool-schedule) | `schedule` | [`llm`](../packages/llm/llm), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | -| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | +| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 3881b23ca1..20fc92635c 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -168,12 +168,14 @@ flowchart TD pkg_client_ui_chat["client-ui-chat"] pkg_client_ui_cli_account["client-ui-cli-account"] pkg_client_ui_commands["client-ui-commands"] + pkg_client_ui_context_menu["client-ui-context-menu"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_deliverables["client-ui-deliverables"] pkg_client_ui_directory_picker_browse["client-ui-directory-picker-browse"] pkg_client_ui_directory_picker_native["client-ui-directory-picker-native"] pkg_client_ui_dockkit["client-ui-dockkit"] pkg_client_ui_entry_customization["client-ui-entry-customization"] + pkg_client_ui_file_actions["client-ui-file-actions"] pkg_client_ui_file_drag["client-ui-file-drag"] pkg_client_ui_goal["client-ui-goal"] pkg_client_ui_input_trigger["client-ui-input-trigger"] @@ -1427,6 +1429,7 @@ flowchart TD pkg_tool_ralph --> pkg_system_prompt pkg_tool_ralph --> pkg_tools pkg_tool_ralph --> pkg_workflow + pkg_sdk_protocol --> pkg_commands pkg_sdk_protocol --> pkg_llm pkg_sdk_protocol --> pkg_session pkg_sdk_protocol --> pkg_subagent @@ -1471,6 +1474,7 @@ flowchart TD pkg_client_test_runtime --> pkg_client_modules pkg_client_test_runtime --> pkg_client_store pkg_client_test_runtime --> pkg_client_ui_chat + pkg_client_test_runtime --> pkg_client_ui_context_menu pkg_client_test_runtime --> pkg_client_ui_conversation pkg_client_test_runtime --> pkg_client_ui_renderer pkg_client_test_runtime --> pkg_client_ui_session @@ -1493,6 +1497,8 @@ flowchart TD pkg_tool_schedule --> pkg_tools pkg_sdk_jsonrpc_server --> pkg_agent pkg_sdk_jsonrpc_server --> pkg_attachment + pkg_sdk_jsonrpc_server --> pkg_commands + pkg_sdk_jsonrpc_server --> pkg_goal pkg_sdk_jsonrpc_server --> pkg_llm pkg_sdk_jsonrpc_server --> pkg_llm_deepseek_api_key pkg_sdk_jsonrpc_server --> pkg_schedule @@ -1556,12 +1562,14 @@ flowchart TD | [`client-ui-chat`](../packages/client/ui-chat) | `client` | — | | [`client-ui-cli-account`](../packages/client/ui-cli-account) | `client` | — | | [`client-ui-commands`](../packages/client/ui-commands) | `client` | — | +| [`client-ui-context-menu`](../packages/client/ui-context-menu) | `client` | — | | [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | — | | [`client-ui-deliverables`](../packages/client/ui-deliverables) | `client` | — | | [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse) | `client` | — | | [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native) | `client` | — | | [`client-ui-dockkit`](../packages/client/ui-dockkit) | `client` | — | | [`client-ui-entry-customization`](../packages/client/ui-entry-customization) | `client` | — | +| [`client-ui-file-actions`](../packages/client/ui-file-actions) | `client` | — | | [`client-ui-file-drag`](../packages/client/ui-file-drag) | `client` | — | | [`client-ui-goal`](../packages/client/ui-goal) | `client` | — | | [`client-ui-input-trigger`](../packages/client/ui-input-trigger) | `client` | — | @@ -1871,13 +1879,13 @@ flowchart TD | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | -| [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | | [`experimental-tool-agent-team`](../packages/experimental/tool-agent-team) | `experimental` | [`agent`](../packages/core/agent), [`experimental-agent-team`](../packages/experimental/agent-team), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`api-session-controller`](../packages/api/session-controller), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-time`](../packages/util/time), [`workspace`](../packages/workspace/workspace) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | -| [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | +| [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-context-menu`](../packages/client/ui-context-menu), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`tool-schedule`](../packages/schedule/tool-schedule) | `schedule` | [`llm`](../packages/llm/llm), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | -| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | +| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/rescope.i18n.yaml b/docs/rescope.i18n.yaml index f6ace06890..f418069ce3 100644 --- a/docs/rescope.i18n.yaml +++ b/docs/rescope.i18n.yaml @@ -6,8 +6,8 @@ en: c8aa4d3384ea1306 zh: 5aa030587d5b634d /vendored-package-rescope/name-mapping: - en: cc0f91dc4bb82605 - zh: 81d5031752c6ea74 + en: 239fa7993825ac62 + zh: df35fa9f5ef42a05 /vendored-package-rescope/what-the-rename-does-not-touch: en: 9bb7d09f8cccf695 zh: 2a8f3f60ae5116f3 diff --git a/docs/rescope.md b/docs/rescope.md index 2e25989742..85917bbfce 100644 --- a/docs/rescope.md +++ b/docs/rescope.md @@ -8,13 +8,13 @@ The Cordis framework and its foundation libraries are vendored under [`vendor/`] | Directory | Upstream name | Published name | Upstream version | Role | |---|---|---|---|---| -| `vendor/cordis/` | `cordis` | `@deepseek-ai/cordis` | 4.0.0-rc.7 | Framework core: `Context`, `Service`, `Fiber`, events | +| `vendor/cordis/` | `cordis` | `@deepseek-ai/cordis` | 4.0.0-rc.11 | Framework core: `Context`, `Service`, `Fiber`, events | | `vendor/cosmokit/` | `cosmokit` | `@deepseek-ai/cosmokit` | 1.8.1 | Shared utilities the framework and Schemastery build on | | `vendor/schemastery/` | `schemastery` | `@deepseek-ai/schemastery` | 3.18.0 | Config schemas (`Schema`) behind every plugin's `Config` | | `vendor/loader/` | `@cordisjs/plugin-loader` | `@deepseek-ai/cordis-plugin-loader` | 1.0.0-rc.5 | `cordis.yml` loading, plugin resolution, repository cache | | `vendor/include/` | `@cordisjs/plugin-include` | `@deepseek-ai/cordis-plugin-include` | 1.0.4 | Config includes and patch overlays | | `vendor/group/` | `@cordisjs/plugin-group` | `@deepseek-ai/cordis-plugin-group` | 1.0.0 | Nested plugin groups | -| `vendor/timer/` | `@cordisjs/plugin-timer` | `@deepseek-ai/cordis-plugin-timer` | 1.1.2 | Disposal-aware timers on `ctx` | +| `vendor/timer/` | `@cordisjs/plugin-timer` | `@deepseek-ai/cordis-plugin-timer` | 1.1.4 | Disposal-aware timers on `ctx` | | `vendor/hmr/` | `@cordisjs/plugin-hmr` | `@deepseek-ai/cordis-plugin-hmr` | 1.0.15 | Hot module replacement for plugins and config | | `vendor/logger-console/` | `@cordisjs/plugin-logger-console` | `@deepseek-ai/cordis-plugin-logger-console` | 1.0.0 | Console logger exporter | diff --git a/docs/rescope.zh.md b/docs/rescope.zh.md index 7b888ede0c..8d13ed539b 100644 --- a/docs/rescope.zh.md +++ b/docs/rescope.zh.md @@ -8,13 +8,13 @@ Cordis 框架及其基础库以源码形式 vendored 在 [`vendor/`](../vendor/R | 目录 | 上游名 | 发布名 | 上游版本 | 角色 | |---|---|---|---|---| -| `vendor/cordis/` | `cordis` | `@deepseek-ai/cordis` | 4.0.0-rc.7 | 框架核心:`Context`、`Service`、`Fiber`、事件 | +| `vendor/cordis/` | `cordis` | `@deepseek-ai/cordis` | 4.0.0-rc.11 | 框架核心:`Context`、`Service`、`Fiber`、事件 | | `vendor/cosmokit/` | `cosmokit` | `@deepseek-ai/cosmokit` | 1.8.1 | 框架与 Schemastery 共用的基础工具 | | `vendor/schemastery/` | `schemastery` | `@deepseek-ai/schemastery` | 3.18.0 | 配置 schema(`Schema`),每个插件的 `Config` 都基于它 | | `vendor/loader/` | `@cordisjs/plugin-loader` | `@deepseek-ai/cordis-plugin-loader` | 1.0.0-rc.5 | `cordis.yml` 装载、插件解析、repository 缓存 | | `vendor/include/` | `@cordisjs/plugin-include` | `@deepseek-ai/cordis-plugin-include` | 1.0.4 | 配置包含与 patch 叠加 | | `vendor/group/` | `@cordisjs/plugin-group` | `@deepseek-ai/cordis-plugin-group` | 1.0.0 | 嵌套插件分组 | -| `vendor/timer/` | `@cordisjs/plugin-timer` | `@deepseek-ai/cordis-plugin-timer` | 1.1.2 | `ctx` 上随 disposal 回收的定时器 | +| `vendor/timer/` | `@cordisjs/plugin-timer` | `@deepseek-ai/cordis-plugin-timer` | 1.1.4 | `ctx` 上随 disposal 回收的定时器 | | `vendor/hmr/` | `@cordisjs/plugin-hmr` | `@deepseek-ai/cordis-plugin-hmr` | 1.0.15 | 插件与配置的热替换 | | `vendor/logger-console/` | `@cordisjs/plugin-logger-console` | `@deepseek-ai/cordis-plugin-logger-console` | 1.0.0 | 控制台日志导出 | diff --git a/docs/subsystems/boot.i18n.yaml b/docs/subsystems/boot.i18n.yaml index 7754efcc03..a1b1b47591 100644 --- a/docs/subsystems/boot.i18n.yaml +++ b/docs/subsystems/boot.i18n.yaml @@ -6,8 +6,8 @@ en: 962b4398c9052959 zh: 14471c340a9f6e60 /profile-management/management-records: - en: 8813788cd8a86903 - zh: 3c30cb180fc1a33d + en: 2cf6a1f62dcc1de6 + zh: b6d519b60f6f5c79 /profile-management/market-records: en: 3dfc62d837d61b9b zh: ec223be315f3dc62 diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index 157ef5da64..48b9b179e0 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -18,7 +18,7 @@ The [boot package group](../../packages/boot/README.md) owns launcher-provided p `PluginRegistries` carries the configured first registry, `null` for the one pnpm's own configuration names, the fallbacks asked after it, and `resolved`, the URL pnpm's own configuration names or `null` while unread. `InspectOptions.registry` names the registry a lookup asks first. -`ChangeResult.changed` reports a disk edit independently of `application`: `applied`, `restart-required`, `overridden` or `failed`. Optional `error` carries a localizable code and external diagnostic. `packageResult` records the pnpm exit code, bounded output, truncation flag and complete diagnostic log path, plus `timedOut` when the manager terminated a run that stopped printing. A terminated run is classified `timeout` whatever exit status the signal left behind, so installation and removal report failure instead of success and no further registry is asked. `pendingBuilds` lists undecided packages across the profile; `approvedBuilds` records the names granted permission by this operation; `registries` lists the registries an installation asked, in order; `bundle` and `version` name the package a finished installation added and its manifest version; `failedAt` says whether the last failed run could not reach the registry it asked or the host a git or tarball spec is fetched from. +`ChangeResult.changed` reports a disk edit independently of `application`: `applied`, `restart-required`, `overridden` or `failed`. Optional `error` carries a localizable code and external diagnostic. `packageResult` records the run's exit status, bounded output, truncation flag and complete diagnostic log path, plus `timedOut` when the manager terminated a run that stopped printing or the GitHub connection check hit its deadline; a terminated run records the coerced status 1 because its process returned none. A terminated run is classified `timeout` whatever exit status the signal left behind, so installation and removal report failure instead of success and no further registry is asked. `pendingBuilds` lists undecided packages across the profile; `approvedBuilds` records the names granted permission by this operation; `registries` lists the registries an installation asked, in order; `bundle` and `version` name the package a finished installation added and its manifest version; `failedAt` says whether the last failed run could not reach the registry it asked or the host a git or tarball spec is fetched from. ## Market records @@ -297,7 +297,8 @@ Manage profile files and apply their declared reload lifecycle. /** * Install a package using the same pnpm implementation as dsh plugin. GitHub * repositories get a connection check bounded by githubConnectionTimeoutMs before pnpm starts; - * only network failures or timeouts stop installation, while pnpm owns authentication and transport fallback. An + * only network failures or timeouts stop installation, and a stop streams the check's diagnostic + * as the installation's install-log run under its request id, while pnpm owns authentication and transport fallback. An * HTTP(S) Git URL on another host is installed over SSH instead when access probes bounded by gitTransportTimeoutMs * find that only SSH can read it. A run * that fails, is cancelled, or adds a package without a bundle patch restores @@ -532,11 +533,11 @@ Source: [`packages/boot/plugin-manager/src/types.ts`](../../packages/boot/plugin #### `plugin-manager/install-log` — emit -One chunk of a pnpm run's output, streamed as the run produces it. +One chunk of an installation run's output, streamed as the run produces it. ```ts cordis-catalog /** - * One chunk of a pnpm run's output, streamed as the run produces it. + * One chunk of an installation run's output, streamed as the run produces it. * @mode emit * @param chunk - the chunk and the run it belongs to. */ diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index 1e5f78cf0e..d80c05fb53 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -18,7 +18,7 @@ `PluginRegistries` 携带配置的第一个注册表(`null` 即 pnpm 自身配置指定的那个)、随后依次询问的备选注册表,以及 `resolved`——pnpm 自身配置指向的 URL,未读到时为 `null`。`InspectOptions.registry` 指定一次查询首先询问的注册表。 -`ChangeResult.changed` 报告磁盘修改,独立于 `application`:`applied`、`restart-required`、`overridden` 或 `failed`。可选的 `error` 包含可本地化的错误码和外部诊断。`packageResult` 记录 pnpm 退出码、有界输出、截断标志及完整诊断日志路径;当管理器终止了一个停止打印的运行,还记录 `timedOut`。被终止的运行不论信号留下什么退出状态都归类为 `timeout`,因此安装与删除都报告失败而非成功,也不会再询问下一个注册表。`pendingBuilds` 列出整个 profile 尚未决定的包;`approvedBuilds` 记录本次操作授予权限的包名;`registries` 按顺序列出一次安装问过的注册表;`bundle` 与 `version` 给出完成的安装新增的包及其清单版本;`failedAt` 说明最后一次失败的运行连不上的是所问的注册表,还是 git 或 tarball spec 自身拉取的主机。 +`ChangeResult.changed` 报告磁盘修改,独立于 `application`:`applied`、`restart-required`、`overridden` 或 `failed`。可选的 `error` 包含可本地化的错误码和外部诊断。`packageResult` 记录运行的退出状态、有界输出、截断标志及完整诊断日志路径;当管理器终止了一个停止打印的运行,或 GitHub 连接检查到达期限,还记录 `timedOut`;被终止的运行记录强制填入的状态 1,因为它的进程没有返回任何状态。被终止的运行不论信号留下什么退出状态都归类为 `timeout`,因此安装与删除都报告失败而非成功,也不会再询问下一个注册表。`pendingBuilds` 列出整个 profile 尚未决定的包;`approvedBuilds` 记录本次操作授予权限的包名;`registries` 按顺序列出一次安装问过的注册表;`bundle` 与 `version` 给出完成的安装新增的包及其清单版本;`failedAt` 说明最后一次失败的运行连不上的是所问的注册表,还是 git 或 tarball spec 自身拉取的主机。 ## 市场记录 @@ -297,7 +297,8 @@ Manage profile files and apply their declared reload lifecycle. /** * Install a package using the same pnpm implementation as dsh plugin. GitHub * repositories get a connection check bounded by githubConnectionTimeoutMs before pnpm starts; - * only network failures or timeouts stop installation, while pnpm owns authentication and transport fallback. An + * only network failures or timeouts stop installation, and a stop streams the check's diagnostic + * as the installation's install-log run under its request id, while pnpm owns authentication and transport fallback. An * HTTP(S) Git URL on another host is installed over SSH instead when access probes bounded by gitTransportTimeoutMs * find that only SSH can read it. A run * that fails, is cancelled, or adds a package without a bundle patch restores @@ -532,11 +533,11 @@ Source: [`packages/boot/plugin-manager/src/types.ts`](../../packages/boot/plugin #### `plugin-manager/install-log` — emit -One chunk of a pnpm run's output, streamed as the run produces it. +One chunk of an installation run's output, streamed as the run produces it. ```ts cordis-catalog /** - * One chunk of a pnpm run's output, streamed as the run produces it. + * One chunk of an installation run's output, streamed as the run produces it. * @mode emit * @param chunk - the chunk and the run it belongs to. */ diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index 67331f49f0..2a3cdf2087 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -58,6 +58,8 @@ interface ForgeProvider { refs: readonly ChangeRequestRef[], signal: AbortSignal, ): Promise> + /** Read all checks for one change request on demand; omission declares that only the polling preview is available. */ + fetchChecks?(ref: ChangeRequestRef, signal: AbortSignal): Promise /** Find open change requests whose head is `branch` in `repository`, excluding the default branch and forks. */ findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise /** Report whether the provider can reach `host` with current credentials. */ @@ -768,6 +770,15 @@ async markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * Read complete check details independently of periodic polling. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the detail view. + * @returns a complete snapshot or the provider's failure; unsupported providers return unavailable. + * @throws on cancellation, provider disposal, or expiry of this read's own `fetchTimeoutMs` deadline. + */ +async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** * Read the changes of a change request as its host computes them. * @param ref - change request served by a registered provider. @@ -840,7 +851,7 @@ Source: [`packages/experimental/forge/src/index.ts`](../../packages/experimental ### `ctx.forgePanel` — `ForgePanelController` -Serves the forge panel. Following a Session inspects the checkout of its current directory read-only in the Session's execution world, recognizes the code host of the upstream remote or `origin`, probes sign-in for that host, and polls the Session's bound change requests through `ctx.forge` until the last follower of that Session leaves. A worktree request makes the panel create a branch and checkout through an optional `ctx.worktrees` and enter it while the Session's first message waits in the inbox, or at the first step proposal of a message no wait took. After a failed or stopped attempt the message keeps waiting for another attempt or for the request to be withdrawn. A message also waits while the worktree the Session works in is gone, until that worktree is checked out again or left for the source checkout. Changes to a Session's checkout run as Agent maintenance, so a message that arrives meanwhile waits for them. +Serves the forge panel. Following a Session inspects the checkout of its current directory using the Session's permissions and execution world, recognizes the code host of the upstream remote or `origin`, probes sign-in for that host, and polls the Session's bound change requests through `ctx.forge` until the last follower of that Session leaves. A worktree request makes the panel create a branch and checkout through an optional `ctx.worktrees` and enter it while the Session's first message waits in the inbox, or at the first step proposal of a message no wait took. After a failed or stopped attempt the message keeps waiting for another attempt or for the request to be withdrawn. A message also waits while the worktree the Session works in is gone, until that worktree is checked out again or left for the source checkout. Changes to a Session's checkout run as Agent maintenance, so a message that arrives meanwhile waits for them. ```ts cordis-catalog /** @@ -904,13 +915,14 @@ Serves the forge panel. Following a Session inspects the checkout of its current /** * Read the changes one scope covers in the checkout of the Session's - * current directory, with Git confined to the Session's read-only sandbox. + * current directory, with Git using the Session's sandbox policy. * @param session - Session whose checkout is read. * @param scope - which changes to read. * @param signal - request cancellation. * @returns the files, the base of the `branch` scope, and the untracked files left out. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/no-fork-point` for the `branch` - * scope of a checkout without one; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. + * scope of a checkout without one; `forgePanel/filter-config-failed` when filter configuration cannot be read + * completely, before any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise @@ -927,6 +939,18 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise +/** + * Load complete checks for the change request whose list the user opened. + * @param session - Session retaining the visible binding. + * @param url - binding URL. + * @param headSha - commit displayed by the card; a different head rejects the result. + * @param signal - cancellation when the list closes. + * @returns the complete snapshot at the displayed head. + * @throws `forgePanel/not-bound` for an invisible binding, `forgePanel/stale-head` for a moved head, + * or `forgePanel/checks-failed` when the provider cannot complete the read. + */ +@Remote async changeRequestChecks(session: Session, url: string, headSha: string, signal: AbortSignal): Promise + /** * Read the changes of a change request of a Session as its code host * computes them, at the head commit of its latest status. A patch already diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 2d726ca39d..5c78d7bb02 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -58,6 +58,8 @@ interface ForgeProvider { refs: readonly ChangeRequestRef[], signal: AbortSignal, ): Promise> + /** Read all checks for one change request on demand; omission declares that only the polling preview is available. */ + fetchChecks?(ref: ChangeRequestRef, signal: AbortSignal): Promise /** Find open change requests whose head is `branch` in `repository`, excluding the default branch and forks. */ findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise /** Report whether the provider can reach `host` with current credentials. */ @@ -768,6 +770,15 @@ async markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * Read complete check details independently of periodic polling. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the detail view. + * @returns a complete snapshot or the provider's failure; unsupported providers return unavailable. + * @throws on cancellation, provider disposal, or expiry of this read's own `fetchTimeoutMs` deadline. + */ +async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** * Read the changes of a change request as its host computes them. * @param ref - change request served by a registered provider. @@ -840,7 +851,7 @@ Source: [`packages/experimental/forge/src/index.ts`](../../packages/experimental ### `ctx.forgePanel` — `ForgePanelController` -Serves the forge panel. Following a Session inspects the checkout of its current directory read-only in the Session's execution world, recognizes the code host of the upstream remote or `origin`, probes sign-in for that host, and polls the Session's bound change requests through `ctx.forge` until the last follower of that Session leaves. A worktree request makes the panel create a branch and checkout through an optional `ctx.worktrees` and enter it while the Session's first message waits in the inbox, or at the first step proposal of a message no wait took. After a failed or stopped attempt the message keeps waiting for another attempt or for the request to be withdrawn. A message also waits while the worktree the Session works in is gone, until that worktree is checked out again or left for the source checkout. Changes to a Session's checkout run as Agent maintenance, so a message that arrives meanwhile waits for them. +Serves the forge panel. Following a Session inspects the checkout of its current directory using the Session's permissions and execution world, recognizes the code host of the upstream remote or `origin`, probes sign-in for that host, and polls the Session's bound change requests through `ctx.forge` until the last follower of that Session leaves. A worktree request makes the panel create a branch and checkout through an optional `ctx.worktrees` and enter it while the Session's first message waits in the inbox, or at the first step proposal of a message no wait took. After a failed or stopped attempt the message keeps waiting for another attempt or for the request to be withdrawn. A message also waits while the worktree the Session works in is gone, until that worktree is checked out again or left for the source checkout. Changes to a Session's checkout run as Agent maintenance, so a message that arrives meanwhile waits for them. ```ts cordis-catalog /** @@ -904,13 +915,14 @@ Serves the forge panel. Following a Session inspects the checkout of its current /** * Read the changes one scope covers in the checkout of the Session's - * current directory, with Git confined to the Session's read-only sandbox. + * current directory, with Git using the Session's sandbox policy. * @param session - Session whose checkout is read. * @param scope - which changes to read. * @param signal - request cancellation. * @returns the files, the base of the `branch` scope, and the untracked files left out. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/no-fork-point` for the `branch` - * scope of a checkout without one; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. + * scope of a checkout without one; `forgePanel/filter-config-failed` when filter configuration cannot be read + * completely, before any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise @@ -927,6 +939,18 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise +/** + * Load complete checks for the change request whose list the user opened. + * @param session - Session retaining the visible binding. + * @param url - binding URL. + * @param headSha - commit displayed by the card; a different head rejects the result. + * @param signal - cancellation when the list closes. + * @returns the complete snapshot at the displayed head. + * @throws `forgePanel/not-bound` for an invisible binding, `forgePanel/stale-head` for a moved head, + * or `forgePanel/checks-failed` when the provider cannot complete the read. + */ +@Remote async changeRequestChecks(session: Session, url: string, headSha: string, signal: AbortSignal): Promise + /** * Read the changes of a change request of a Session as its code host * computes them, at the head commit of its latest status. A patch already diff --git a/docs/subsystems/slots.i18n.yaml b/docs/subsystems/slots.i18n.yaml index 17ae54903e..0a2bb60f40 100644 --- a/docs/subsystems/slots.i18n.yaml +++ b/docs/subsystems/slots.i18n.yaml @@ -9,8 +9,8 @@ en: f2d2c0d3b8f14ec7 zh: 441ed13ff3f81d2a /web-client-slots/cardinality-and-scope: - en: 5b0ada069239576b - zh: 84e1e6b253d1461e + en: cd17e3e0ff6e62ff + zh: 6e0db2cb16c41b73 /web-client-slots/component-inputs: en: 9cb70abb2e39b958 zh: cd4b6f1705d90e17 diff --git a/docs/subsystems/slots.md b/docs/subsystems/slots.md index d64184dbc0..fe8589f685 100644 --- a/docs/subsystems/slots.md +++ b/docs/subsystems/slots.md @@ -65,6 +65,8 @@ The slot declaration fixes two independent axes. `priority` is a shadowing rank for `single`, `list`, and `keyed` cells and an election order for `chain`. Lower values run or render first. Ordinary additive contributions should choose a fresh list `id` or keyed `key`; intentionally reusing a shipped cell replaces its presentation. +The [context-menu plugin](../../packages/client/ui-context-menu/README.md) contributes `useContextMenu` through `provideRoot`; every scope receives the same plugin-owned trigger factory. Its prop and retained handlers retire when the provider unloads. Its root-scoped keyed `contextMenu.icon` Slot renders business-owned icons from action metadata. + ## Component inputs A registered component receives inputs assembled at its binding site. Components derive these types rather than copying their members. diff --git a/docs/subsystems/slots.zh.md b/docs/subsystems/slots.zh.md index db7509aefe..288b4b85f1 100644 --- a/docs/subsystems/slots.zh.md +++ b/docs/subsystems/slots.zh.md @@ -67,6 +67,8 @@ Slot 声明固定两个相互独立的维度。 +[右键菜单插件](../../packages/client/ui-context-menu/README.zh.md) 通过 `provideRoot` 贡献 `useContextMenu`;每个作用域接收同一个由插件拥有的触发器工厂。提供方卸载时,注入属性与保留的处理器一并失效。其根作用域 keyed Slot `contextMenu.icon` 根据操作元数据渲染业务方提供的图标。 + ## 组件输入 注册组件会在 binding 位置收到组装后的输入。组件应从这些类型推导 props,不要重新抄写成员。 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/context-menu-services/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/context-menu-services/guide.i18n.yaml new file mode 100644 index 0000000000..8249edf3c4 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/context-menu-services/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.2/context-menu-services/guide.md +/: + en: b0a44570cee3ac45 + zh: f68438befed14c6e +/context-menu-services-in-custom-client-compositions: + en: b2018bf0250be579 + zh: 1d8a243d09f4128f +/context-menu-services-in-custom-client-compositions/change: + en: 3eaef415166d076f + zh: 4040390d2572fc47 +/context-menu-services-in-custom-client-compositions/migration: + en: ebffe957534ac31b + zh: a33d2782f5ad0f5d diff --git a/docs/upgrade-guide/v0.2.1-rc.2/context-menu-services/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/context-menu-services/guide.md new file mode 100644 index 0000000000..082e1da33f --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/context-menu-services/guide.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "Custom Client compositions must provide the context-menu and file-action services required by GUI plugins." +--- + +# Context menu services in custom Client compositions + +English | [中文](guide.zh.md) + +## Change + +GUI plugins now inject `contextMenus` to open shared object menus. The open-in-app plugin also injects `fileActions`, `sidebarRight`, `sidebarRightTabs`, and `remote.workspaceFiles`. Custom compositions that mount these GUI plugins without the new services cannot activate them. The shipped Web application bundle includes the providers; existing Session and tab menu Slot names remain available. + +## Migration + +1. In the package manifest that owns a custom composition, add dependencies on `@deepseek-ai/dsh-client-ui-context-menu` and `@deepseek-ai/dsh-client-ui-file-actions` at the same Harness version. +2. Add both package names as plugin rows in the custom Client composition alongside the existing locale, slots, shortcuts, sidebar, and workspace-file providers. The default `@deepseek-ai/dsh-web-app` bundle already contains these rows. +3. Rename `ctx.menus` to `ctx.contextMenus` and `MenuTargetMap` to `ContextMenuTargetMap`; neither old name has an alias. Mount the menu plugin so its `ctx.slots.provideRoot` contribution supplies `useContextMenu` to every Slot. Components call the hook once and spread `getTriggerProps(target, handlers?)` onto each element, including elements created in loops. See the [menu reference](../../../../packages/client/ui-context-menu/README.md) for handler composition and external action registration. +4. Rebuild and launch the custom profile. Confirm that GUI plugins activate, right-clicking a background Session preserves selection, and existing Session/tab Slot contributions still appear. +5. Custom Slot hosts must remove their declarations of `sidebar.workspaces.session.menu.item` and `sidebar.right.tab.menu.item`; the workspace and right-sidebar adapters now own these under `contextMenu.content`. Session rows retain the `[open, setOpen]` hook context, and tab rows receive `{ tab, dismiss }` within the clicked Session’s provider. A custom host replacing these adapters must declare the same children and supply those owners itself. Dockkit embedders using `getTabTriggerProps` own the popup and dismissal; `renderTabMenuItems` is used only by the kit popup. Supply reactive `tabMenuOpen` to suppress close-button tooltips while a custom menu prepares or remains open. + +6. Built-in Session menu items are data contributions. The legacy React Slot retains external entries together before Archive; Slot priority no longer shadows built-in actions. Use `ctx.contextMenus.register` for new actions and optional `commandId` to display an existing command’s current binding. Keep captured-target execution in `run`; no command dispatch is added. +7. Menu contributions use `icon?: ReactNode`; replace `symbol` with a glyph element and wrap icon URLs in ``. Obtain `useContextMenu` at each actual Slot entry. Plain children receive `getTriggerProps` or bound `contextMenuProps`; ToolRow uses `fileContextMenuProps` and `urlContextMenuProps`. Remove menu fields from Chat flow/node owners. The assistant entry supplies an ordinary file adapter to `forClosing()`, while Markdown adapts its target type at `MarkdownDelegateProvider.getTriggerProps`. Keep Session identity and gesture-time path resolution in the business registration. Remove imports of `contextMenuTrigger` and `menuPoint`; their independent utility package is removed. Do not add gesture exports to ui-primitives. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/context-menu-services/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/context-menu-services/guide.zh.md new file mode 100644 index 0000000000..9281f9bee1 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/context-menu-services/guide.zh.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "自定义 Client 组合必须提供 GUI 插件所需的右键菜单与文件动作服务。" +--- + +# 自定义 Client 组合中的右键菜单服务 + +[English](guide.md) | 中文 + +## 变更 + +GUI 插件现在注入 `contextMenus` 以打开共享对象菜单。open-in-app 插件还注入 `fileActions`、`sidebarRight`、`sidebarRightTabs` 和 `remote.workspaceFiles`。自定义组合若挂载这些 GUI 插件却没有新服务,将无法激活它们。随附 Web 应用 bundle(插件包)已包含提供方;现有 Session 和标签页菜单 Slot 名称仍可使用。 + +## 迁移 + +1. 在自定义组合所属的包清单中,添加与 Harness 版本一致的 `@deepseek-ai/dsh-client-ui-context-menu` 和 `@deepseek-ai/dsh-client-ui-file-actions` 依赖。 +2. 在自定义 Client 组合中将两个包名添加为插件行,与已有 locale、slots、shortcuts、侧栏和工作区文件提供方并列。默认 `@deepseek-ai/dsh-web-app` bundle 已包含这些行。 +3. 将 `ctx.menus` 改为 `ctx.contextMenus`,将 `MenuTargetMap` 改为 `ContextMenuTargetMap`,旧名均无兼容别名。挂载菜单插件,由其 `ctx.slots.provideRoot` 贡献向每个 Slot 提供 `useContextMenu`。组件调用一次 hook,将 `getTriggerProps(target, handlers?)` 展开到每个元素,包括循环生成的元素。处理器组合和外部动作注册见[菜单参考](../../../../packages/client/ui-context-menu/README.zh.md)。 +4. 重新构建并启动自定义 profile(配置档)。确认 GUI 插件正常激活、右键后台 Session 不改变选择,且现有 Session/标签页 Slot 贡献仍然显示。 +5. 自定义 Slot 宿主应移除对 `sidebar.workspaces.session.menu.item` 和 `sidebar.right.tab.menu.item` 的声明;现在由工作区和右侧栏适配器在 `contextMenu.content` 下拥有它们。会话行继续接收 `[open, setOpen]` hook context,标签行在所点击会话的 provider 内接收 `{ tab, dismiss }`。替换这些适配器的自定义宿主须自行声明相同的子 Slot 并提供这些 owner。使用 `getTabTriggerProps` 的 Dockkit 嵌入方负责弹窗和关闭,`renderTabMenuItems` 仅供组件自身的弹窗使用。通过响应式 `tabMenuOpen` 在自定义菜单准备或显示时禁用关闭按钮的 Tooltip。 + +6. 内置 Session 菜单项改为数据贡献。旧 React Slot 将外部条目集中显示在归档之前,Slot priority 不再覆盖内置动作。新增动作用 `ctx.contextMenus.register`,可通过 `commandId` 展示已有命令的当前绑定。针对捕获目标的执行仍放在 `run`,不增加命令调度。 +7. 菜单贡献使用 `icon?: ReactNode`:将 `symbol` 改为图标元素,并用 `` 包装图标 URL。在每个实际 Slot 入口获取 `useContextMenu`。普通子组件接收 `getTriggerProps` 或绑定后的 `contextMenuProps`;ToolRow 使用 `fileContextMenuProps` 和 `urlContextMenuProps`。删除 Chat 消息流和节点 owner 的菜单字段。助手入口向 `forClosing()` 传入普通文件适配函数,Markdown 则在 `MarkdownDelegateProvider.getTriggerProps` 处适配目标类型。业务注册保留 Session 归属和触发时路径解析。删除 `contextMenuTrigger` 和 `menuPoint` 导入,其独立工具包已删除。不要向 ui-primitives 增加手势导出。 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.i18n.yaml index 7e4e4247a2..f8584a6842 100644 --- a/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.i18n.yaml @@ -12,5 +12,5 @@ en: 1552866718133b10 zh: 1c760c5c2d5cfc0b /authorize-the-computer-use-helper/migration: - en: 2a28385e24468734 - zh: 725c1856a604bc0c + en: a79e5995415ff456 + zh: 6f818a092e53af2c diff --git a/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.md b/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.md index 9e57c7c569..c913488785 100644 --- a/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.md +++ b/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.md @@ -13,7 +13,7 @@ macOS Computer Use runs as `DSH Computer Use.app`, launched through LaunchServic ## Migration -1. Restart DSH after upgrading the Computer Use package. In the Computer Use plugin page, grant Accessibility and Screen Recording access to `DSH Computer Use.app` when macOS requests it. +1. Computer Use now installs on demand. In **Plugins → Add plugin**, install `@deepseek-ai/dsh-cua-bundle` and enable it; profiles that previously selected the shipped copy need this installation. Restart DSH if requested. In the Computer Use plugin page, grant Accessibility and Screen Recording access to `DSH Computer Use.app` when macOS requests it. 2. Remove an obsolete `helperPath` override or `DSH_CUA_HELPER` value to use automatic preparation. For a custom build, point it to the executable at `DSH Computer Use.app/Contents/MacOS/dsh-cua-native` inside the complete application bundle. 3. Confirm that the permission page identifies `DSH Computer Use.app` and both permissions are allowed before resuming native application tasks. Target-application consent remains required. 4. If a terminal or Desktop launcher was granted these permissions only for Computer Use, revoke those obsolete grants in System Settings. Authorizing the helper does not revoke other applications’ existing permissions; programs the model runs still follow their launcher’s system permissions and the DSH sandbox policy. diff --git a/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.zh.md index a6c3a2f634..f25a4b805d 100644 --- a/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.zh.md +++ b/docs/upgrade-guide/v0.2.1-rc.3/computer-use-helper-permissions/guide.zh.md @@ -13,7 +13,7 @@ macOS Computer Use 通过 LaunchServices 以 `DSH Computer Use.app` 运行。终 ## 迁移 -1. 升级 Computer Use 包后重启 DSH。在 Computer Use 插件页按 macOS 提示,给 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。 +1. Computer Use 改为按需安装。在“插件 → 添加插件”中安装 `@deepseek-ai/dsh-cua-bundle` 并启用;此前选中过内置副本的 profile 也需完成这次安装。按提示重启 DSH。在 Computer Use 插件页按 macOS 提示,给 `DSH Computer Use.app` 授予辅助功能和屏幕录制权限。 2. 删除过时的 `helperPath` 覆盖配置或 `DSH_CUA_HELPER` 值,使用自动准备。使用自定义构建时,将其指向完整应用包内的 `DSH Computer Use.app/Contents/MacOS/dsh-cua-native` 可执行文件。 3. 恢复原生应用任务前,确认权限页显示 `DSH Computer Use.app`,且两项权限均已允许。具体目标应用仍需另行许可。 4. 若终端或 Desktop 启动器的这两项权限只用于 Computer Use,可在系统设置中撤销这些旧授权。给 helper 授权不会撤销其他应用已有的权限;模型运行的程序仍遵循启动器的系统权限和 DSH 沙箱策略。 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/web-file-downloads/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.3/web-file-downloads/guide.i18n.yaml new file mode 100644 index 0000000000..881f6d61d6 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/web-file-downloads/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.3/web-file-downloads/guide.md +/: + en: 25674d6a93c97ca5 + zh: ac1563eccab1b284 +/file-downloads-on-web: + en: d8fac1a37dede04d + zh: 8f132360f0553b64 +/file-downloads-on-web/change: + en: d76c6132a5e5fc9d + zh: 691b2264a37a526f +/file-downloads-on-web/migration: + en: a4365e73ae4e2de4 + zh: 8988bc1703fc5b8d diff --git a/docs/upgrade-guide/v0.2.1-rc.3/web-file-downloads/guide.md b/docs/upgrade-guide/v0.2.1-rc.3/web-file-downloads/guide.md new file mode 100644 index 0000000000..dcc26609ac --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/web-file-downloads/guide.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "Custom file-action menus must offer save-as only on Desktop and browser downloads on Web." +--- + +# File downloads on Web + +English | [中文](guide.zh.md) + +## Change + +The Web file-action service no longer offers save-as through a browser file picker. `canSaveAs` is always false on Web, and `save(source, 'saveAs')` rejects before reading the source. Built-in Web file and image menus offer Download and omit Save as. Desktop still offers both actions; successful saves return the absolute destination `path` instead of an opaque file ID. + +## Migration + +1. Custom Client menus should include Save as only when `ctx.fileActions.canSaveAs` is true. +2. On Web, call `ctx.fileActions.save(source, 'download')`. The browser handles the original content and suggested filename; a `requested` result means download started, not completed. Do not report a saved local path. +3. Replace `savedFile(url)` and `reveal(id)` calls with an action on the completed `saved` result, using its `path` with `session.openWorkspacePath`. Keep original-file context-menu reveal independent of saved destinations. +4. Verify that Web file and image menus expose Download without Save as, including browsers that support `showSaveFilePicker`. Verify that Desktop image menus retain both actions. See the [file-action reference](../../../../packages/client/ui-file-actions/README.md) for save results and feedback ownership. diff --git a/docs/upgrade-guide/v0.2.1-rc.3/web-file-downloads/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.3/web-file-downloads/guide.zh.md new file mode 100644 index 0000000000..d9e232845a --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/web-file-downloads/guide.zh.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "自定义文件动作菜单应仅在 Desktop 提供另存为,在 Web 使用浏览器下载。" +--- + +# Web 文件下载 + +[English](guide.md) | 中文 + +## 变更 + +Web 文件动作服务不再通过浏览器文件选择器提供另存为。Web 的 `canSaveAs` 始终为 false,`save(source, 'saveAs')` 会在读取来源前拒绝。内置 Web 文件和图片菜单提供「下载」,不显示「另存为」。Desktop 仍提供两种操作;保存成功后返回目标绝对路径 `path`,不再返回不透明文件 ID。 + +## 迁移 + +1. 自定义 Client 菜单仅在 `ctx.fileActions.canSaveAs` 为 true 时添加「另存为」。 +2. Web 端调用 `ctx.fileActions.save(source, 'download')`。浏览器处理原始内容和建议文件名;`requested` 结果仅表示下载已开始,不代表完成。不要报告本机保存路径。 +3. 将 `savedFile(url)` 和 `reveal(id)` 调用替换为完成后 `saved` 结果上的操作,使用其中的 `path` 调用 `session.openWorkspacePath`。原文件右键定位应独立于保存目标。 +4. 验证 Web 文件和图片菜单只有「下载」而没有「另存为」,包括支持 `showSaveFilePicker` 的浏览器;验证 Desktop 图片菜单保留两种操作。保存结果与提示的归属参见[文件动作参考](../../../../packages/client/ui-file-actions/README.zh.md)。 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/context-menu-target/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/context-menu-target/guide.i18n.yaml new file mode 100644 index 0000000000..74990defdf --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/context-menu-target/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.2/context-menu-target/guide.md +/: + en: 6c606440532dfae0 + zh: 9308d72d451e12c7 +/context-menu-types-and-icons: + en: d1237d3842936881 + zh: b32fcacf82bed5f1 +/context-menu-types-and-icons/change: + en: 35faa7bd1cff539f + zh: 0dc2515e0025e3d8 +/context-menu-types-and-icons/migration: + en: e15e76d8d6a95f35 + zh: 4bf2dec8d764e5ae diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/context-menu-target/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/context-menu-target/guide.md new file mode 100644 index 0000000000..0f33207f01 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/context-menu-target/guide.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "Client plugins must use the prefixed context menu types and hooks and register keyed icon components." +--- + +# Context menu types and icons + +English | [中文](guide.zh.md) + +## Change + +The `@deepseek-ai/dsh-client-ui-context-menu/client` export `MenuTarget` is renamed to `ContextMenuTarget`, matching `ContextMenuTargetMap`. The old name has no compatibility alias. Target fields and runtime behavior are unchanged. Workspace and sidebar injections rename `menuTarget` / `useMenuTarget` to `contextMenuTarget` / `useContextMenuTarget`. Action icons accept `{ key, src? }` instead of React nodes and render through the keyed `contextMenu.icon` Slot. + +## Migration + +1. Replace `MenuTarget` imports and type references with `ContextMenuTarget`. +2. Rename injected `menuTarget` sources and `useMenuTarget` consumers to `contextMenuTarget` and `useContextMenuTarget`. +3. Replace action icon elements with `{ key: 'my-plugin.action' }`; carry a captured image URL in `src` when needed. Register the icon component under that key through `ctx.slots.inject('contextMenu.icon', ...)` and `ctx.slots.register()`. See the [menu package](../../../../packages/client/ui-context-menu/README.md#use-this-package). +4. Rebuild custom Client plugins, confirm that type checks pass, and open their menus to verify icon rendering and plugin-unload cleanup. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/context-menu-target/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/context-menu-target/guide.zh.md new file mode 100644 index 0000000000..e6bcb0cd2c --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/context-menu-target/guide.zh.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "Client 插件须使用带前缀的右键菜单类型和 hook,并注册 keyed 图标组件。" +--- + +# 右键菜单类型和图标 + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-client-ui-context-menu/client` 导出的 `MenuTarget` 更名为 `ContextMenuTarget`,与 `ContextMenuTargetMap` 保持一致。旧名不保留兼容别名,目标字段和运行时行为不变。工作区与侧栏注入的 `menuTarget` / `useMenuTarget` 改为 `contextMenuTarget` / `useContextMenuTarget`。操作图标改用 `{ key, src? }`,通过 keyed Slot `contextMenu.icon` 渲染,不再接收 React 节点。 + +## 迁移 + +1. 将 `MenuTarget` 导入及类型引用替换为 `ContextMenuTarget`。 +2. 将注入源 `menuTarget` 和消费者 `useMenuTarget` 分别改为 `contextMenuTarget`、`useContextMenuTarget`。 +3. 将操作图标元素替换为 `{ key: 'my-plugin.action' }`,需要时通过 `src` 携带已捕获的图片 URL。通过 `ctx.slots.inject('contextMenu.icon', ...)` 和 `ctx.slots.register()` 在该 key 下注册图标组件,参见[菜单包](../../../../packages/client/ui-context-menu/README.zh.md#use-this-package)。 +4. 重新构建自定义 Client 插件,确认类型检查通过,并打开菜单验证图标渲染和插件卸载后的清理。 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/forge-git-permissions/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/forge-git-permissions/guide.i18n.yaml new file mode 100644 index 0000000000..dc8f886672 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/forge-git-permissions/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.2/forge-git-permissions/guide.md +/: + en: 670467a1e1ef4871 + zh: a5c49c32981a3d50 +/forge-git-query-permissions-and-content-conversion: + en: 622fa28fae275249 + zh: 75888856615bcfd3 +/forge-git-query-permissions-and-content-conversion/change: + en: d8f544395f65b663 + zh: f785a6d6f9a696b6 +/forge-git-query-permissions-and-content-conversion/migration: + en: db9ae3d66f6bb1e7 + zh: 315bfde302564a7c diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/forge-git-permissions/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/forge-git-permissions/guide.md new file mode 100644 index 0000000000..76ac171810 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/forge-git-permissions/guide.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: "Forge Git queries use Session permissions and disable configured diff helpers." +--- +# Forge Git query permissions and content conversion + +English | [中文](guide.zh.md) + +## Change + +Forge Git queries use the Session's sandbox mode instead of forcing `read-only`. `danger-full-access` works without a sandbox backend; `workspace-write` permits writes within its configured roots. A confined mode still refuses execution when its backend is unavailable. + +On Git 2.31 or newer, local diffs and statistics disable enumerated clean/process filters for each command. Git's built-in newline, ident, and encoding conversions still apply. Materialized LFS files and other filtered files can appear changed when ordinary Git considers them clean. The panel does not request LFS downloads. Older Git or concurrently added filters can still execute helpers under Session permissions. Submodule commit changes remain visible, but internal uncommitted changes are omitted. + +Filter configuration read failures, including truncated output, report `forgePanel/filter-config-failed` before any comparison and offer a retry. They are separate from `forgePanel/diff-too-large`. + +## Migration + +1. Keep a Session in `read-only` when its Git queries require operating-system-enforced write protection. Use the existing permission picker to select the intended Session mode; no configuration keys change. +2. For repositories that require content conversion or submodule working-tree inspection, use an explicit Git command under the intended Session permissions to inspect those changes. The panel's local comparison bypasses clean/process filters on supported Git versions. +3. On a host without a sandbox backend, select Full access and refresh the Forge panel. Its checkout and ordinary local changes should load; switching to a confined mode must still report the unavailable backend. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/forge-git-permissions/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/forge-git-permissions/guide.zh.md new file mode 100644 index 0000000000..07c4770bf3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/forge-git-permissions/guide.zh.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: "Forge Git 查询使用 Session 权限并禁用已配置的 diff 辅助程序。" +--- +# Forge Git 查询权限与内容转换 + +[English](guide.md) | 中文 + +## 变更 + +Forge Git 查询使用 Session 的沙箱模式,不再强制 `read-only`。`danger-full-access` 无需沙箱后端;`workspace-write` 允许在其配置的根目录内写入。受限模式的后端不可用时仍拒绝执行。 + +在 Git 2.31 或更新版本中,本地 diff 与统计仅对每次命令禁用已枚举的 clean/process filter。Git 内置的换行、ident 与编码转换仍然生效。已物化的 LFS 文件及其他过滤文件可能显示为变更,即使普通 Git 认为它们未变。面板不请求下载 LFS 对象。旧 Git 或并发新增的过滤器仍可能按 Session 权限执行辅助程序。子模块提交变化仍可见,但内部未提交修改不显示。 + +过滤器配置读取失败(包括输出被截断)时,在任何比较之前报告 `forgePanel/filter-config-failed` 并提供重试,与 `forgePanel/diff-too-large` 区分。 + +## 迁移 + +1. 如果 Git 查询需要操作系统强制禁止写入,请将 Session 保持为 `read-only`。通过现有权限选择器选择所需的 Session 模式;配置键没有变化。 +2. 对于需要内容转换或检查子模块工作区的仓库,请在所需的 Session 权限下显式运行 Git 命令检查这些变化。面板的本地比较在受支持的 Git 版本中绕过 clean/process filter。 +3. 在没有沙箱后端的主机上选择“完全权限”,然后刷新 Forge 面板。检出信息和普通本地变更应可加载;切回受限模式后仍须报告后端不可用。 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.i18n.yaml new file mode 100644 index 0000000000..69f284f402 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.md +/: + en: 695ee5740865d684 + zh: 83cb4df5ecf20a99 +/sdk-run-accepts-native-commands: + en: 54f8a31426f4758c + zh: 283820d3f187092e +/sdk-run-accepts-native-commands/change: + en: 478742169aa04c50 + zh: 3324d99f4206d1fc +/sdk-run-accepts-native-commands/migration: + en: 0298fc31efa6466c + zh: ab99db4beaa86a14 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.md new file mode 100644 index 0000000000..deb605d80e --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.md @@ -0,0 +1,24 @@ +--- +kind: upgrade-guide +description: "SDK run recognizes native commands and returns RunResult after its input completes." +--- + +# SDK run accepts native commands + +English | [中文](guide.zh.md) + +## Change + +Python and TypeScript `run()` accept strings and content-block arrays through the existing entry and always return `RunResult`. Supported native commands are recognized by their definition identities and effective registered names. English and Chinese aliases follow renamed definitions; unrelated exact-name replacements remain ordinary input. See the [supported command rules](../../../../packages/sdk/server/README.md#command-input). + +`final_response` / `finalResponse` contains the final assistant text, or an empty string when the activity emits none. State-only commands return the native handler's result text. `finish_reason` / `finishReason` reports the terminal outcome. Every result retains its Session id, root events and Session-tree notifications. State-only commands finish without waiting for a model turn; `/plan ` waits for its admitted activity, including native review and any approved continuation. Goal creation and resume wait across automatic rounds until the goal stops and its closing activity ends. Low-level strict command calls still return `CommandExecution` after the native handler settles. + +Content-block arrays no longer bypass native routing. A recognized command requires one text block and optional encoded raster images; native handlers enforce image admission. `/plan off` with an image fails without changing plan state. Empty arrays and blank-only input reject before Session creation; image-only input remains accepted. Identity rejection by the strict endpoint retains its initialized Session without executing a handler or submitting a prompt. + +## Migration + +1. Keep the existing `result.final_response` / `result.finalResponse` access for prompts and commands. Inspect `finish_reason` / `finishReason` for failure; command ids and native outcomes remain in `command/run` and `command/done` events. Save the result's Session id to continue or restore it. +2. Keep the user-question callback alive for plan review. State-changing command failures appear in `RunResult`; routing, malformed protocol data and transport failures still raise or reject. A timeout or observer failure does not roll back runtime work. +3. For literal queued input, use Python `client.session_prompt(session_id, blocks)` or TypeScript `client.prompt(sessionId, blocks)`, and manage its subsequent activity. Runtime skill recognition still applies. +4. Custom `session/query` clients send `{ sessionId, contentBlocks }`. Command responses acknowledge the native handler; the matching `session.query.completed` notification carries the final input outcome. Preserve notification order and subscribe before sending. +5. Filter empty input before calling `run()`. Use an image-capable model and the existing `run([text_block, image_block])` form for images. Python malformed native command responses raise `SdkProtocolError`, preserving their validation cause; generic caller-selected response models retain their validation behavior. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.zh.md new file mode 100644 index 0000000000..3af3c36ed3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/sdk-run-commands/guide.zh.md @@ -0,0 +1,24 @@ +--- +kind: upgrade-guide +description: "SDK run 识别原生命令,并在本次输入完成后返回 RunResult。" +--- + +# SDK run 接受原生命令 + +[English](guide.md) | 中文 + +## 变更 + +Python 和 TypeScript 的 `run()` 通过原有入口接受字符串和内容块数组,始终返回 `RunResult`。受支持原生命令按定义身份和实际注册名识别。中英文别名跟随重命名的定义;无关的同名替代命令仍作为普通输入。见[支持的命令规则](../../../../packages/sdk/server/README.zh.md#command-input)。 + +`final_response` / `finalResponse` 包含最终助手文本;活动未输出助手文本时为空字符串。仅改变状态的命令返回原生 handler 的结果文本。`finish_reason` / `finishReason` 表示结束结果。每份结果都保留 Session id、根会话事件和会话树通知。仅改变状态的命令无需等待模型 turn;`/plan ` 等待其提交的活动,包括原生审阅及获批后的后续执行。目标创建和恢复跨越自动轮次等待,直到目标停止及最后的活动结束。底层严格命令调用仍在原生 handler 完成后返回 `CommandExecution`。 + +内容块数组不再绕过原生命令路由。已识别命令要求一个文本块及可选的编码位图;原生 handler 执行图片准入。`/plan off` 带图片会失败且不改变计划状态。空数组和纯空白输入在创建 Session 前拒绝;纯图片输入仍然接受。严格端点拒绝命令身份时保留已经初始化的 Session,不执行 handler 或提交提示词。 + +## 迁移 + +1. 普通提示词和命令均继续使用 `result.final_response` / `result.finalResponse`。通过 `finish_reason` / `finishReason` 检查失败;命令 id 和原生结果保留在 `command/run` 与 `command/done` 事件中。保存结果的 Session id,以便继续或恢复会话。 +2. 计划审阅期间保持用户问题回调可用。状态变更命令的失败体现在 `RunResult` 中;路由、协议数据格式和传输失败仍抛出或拒绝。超时或观察回调失败不会回滚运行时工作。 +3. 需要按原文排队输入时,使用 Python `client.session_prompt(session_id, blocks)` 或 TypeScript `client.prompt(sessionId, blocks)`,并管理后续活动。运行时技能识别仍然适用。 +4. 自定义 `session/query` 客户端发送 `{ sessionId, contentBlocks }`。命令响应确认原生 handler 完成;对应的 `session.query.completed` 通知携带本次输入的最终结果。保持通知顺序,并在发送前订阅。 +5. 调用 `run()` 前过滤空输入。图片使用支持图片的模型及原有 `run([text_block, image_block])` 形式。Python 对格式错误的原生命令响应抛出 `SdkProtocolError`,保留校验原因;调用者自行选择的通用响应模型保留原有校验行为。 diff --git a/docs/user/guide/python-sdk.i18n.yaml b/docs/user/guide/python-sdk.i18n.yaml index f911334f40..db2d757606 100644 --- a/docs/user/guide/python-sdk.i18n.yaml +++ b/docs/user/guide/python-sdk.i18n.yaml @@ -12,8 +12,8 @@ en: c2b15716ea155625 zh: 0879be26f0afc452 /get-started-with-the-python-sdk/run-the-checked-in-example: - en: 74e1866caf573e6a - zh: 7f034b6f81decf9d + en: 23d04cd9dcb6a530 + zh: e7a9471b9493b888 /get-started-with-the-python-sdk/use-the-sdk-in-your-program: en: d1e350be0ba38196 zh: 893220ee7b12b12f @@ -24,5 +24,5 @@ en: 450d54b6e9e38469 zh: f0dc06a08c073571 /get-started-with-the-python-sdk/understand-the-minimal-profile: - en: 8ed0bfd3cc9cc967 - zh: a52dab4cb3dd09ea + en: ea2a6521cff50517 + zh: 3769760a5e40af8d diff --git a/docs/user/guide/python-sdk.md b/docs/user/guide/python-sdk.md index 438598c378..38f6a2a531 100644 --- a/docs/user/guide/python-sdk.md +++ b/docs/user/guide/python-sdk.md @@ -91,7 +91,7 @@ python python/sdk/examples/minimal.py ` ::: -The script prints the final assistant response. The selected home receives the generated `sdk-minimal` profile, installed plugins, and uncompressed JSONL session logs under `sessions/`. The example and SDK never silently read `~/.dsh`. +The script prints the final assistant response or the command result supplied by the selected profile. The selected home receives the generated `sdk-minimal` profile, installed plugins, and uncompressed JSONL session logs under `sessions/`. The example and SDK never silently read `~/.dsh`. ## Use the SDK in your program @@ -176,7 +176,7 @@ Pass `patches=("/absolute/path/to/editor.patch.yml",)` when constructing `DeepSe The profile's sole bundle inserts the complete tree over an empty root and does not include `dsh-base`; later base-profile tools therefore cannot appear implicitly. It contains the SDK protocol, one environment-configured DeepSeek adapter, local execution, and persistence, while text file tools, settings, managed credentials, OTel telemetry, Web tools, subagents, and local instruction discovery are absent. The [DeepSeek session-log contributor](../../../packages/session/session-log-deepseek/README.md) uploads unaccepted log events with DeepSeek requests by default, at most `maxBytes` (8 MiB) per request; set `session-log-deepseek.enabled: false` in a profile patch to disable it. It pins `danger-full-access`, so the platform-selected persistent shell can modify any path visible to the runtime; use a disposable checkout or container. -Image reading requires an image-capable route. Automatic compaction preserves the complete Session log; see the [bundle reference](../../../packages/bundle/sdk-minimal/README.md) for model and storage effects. SDK prompt text does not execute `/compact` or other slash commands. +Image reading requires an image-capable route. Automatic compaction preserves the complete Session log; see the [bundle reference](../../../packages/bundle/sdk-minimal/README.md) for model and storage effects. In this `sdk-minimal` composition, unsupported slash input remains ordinary prompt text. The installed wheel still packages the full `web` profile and frontend assets. Run `dsh web` against an explicit `DSH_HOME` when a Python SDK deployment also needs the browser application; `web` is a separate CLI application and cannot serve a Python SDK client. diff --git a/docs/user/guide/python-sdk.zh.md b/docs/user/guide/python-sdk.zh.md index b7a86e9860..cd321cfad6 100644 --- a/docs/user/guide/python-sdk.zh.md +++ b/docs/user/guide/python-sdk.zh.md @@ -91,7 +91,7 @@ python python/sdk/examples/minimal.py ` ::: -脚本会打印最终 assistant 响应。所选 home 会保存生成的 `sdk-minimal` profile、已安装插件,以及 `sessions/` 下的未压缩 JSONL 会话日志。示例与 SDK 绝不会静默读取 `~/.dsh`。 +脚本会打印最终 assistant 响应或所选 profile 提供的命令结果。所选 home 会保存生成的 `sdk-minimal` profile、已安装插件,以及 `sessions/` 下的未压缩 JSONL 会话日志。示例与 SDK 绝不会静默读取 `~/.dsh`。 ## 在程序中使用 SDK @@ -176,7 +176,7 @@ dsh plugin --profile sdk-minimal add file:C:/work/my-plugin-bundle 该 profile 的唯一组合包会在空根之上插入完整配置树,且不包含 `dsh-base`,因此基础 profile 以后新增的工具不会隐式出现。它包含 SDK 协议、一个由环境配置的 DeepSeek 适配器、本地执行与持久化;文本文件工具、settings、托管凭据、OTel 遥测、Web 工具、subagent、本地指令发现均不存在。[DeepSeek 会话日志贡献器](../../../packages/session/session-log-deepseek/README.zh.md)默认随 DeepSeek 请求上传未接受的日志事件,每次请求最多 `maxBytes`(8 MiB);在 profile patch 中设置 `session-log-deepseek.enabled: false` 可将其关闭。它固定使用 `danger-full-access`,因此按平台选择的持久 shell 可以修改运行时可见的任何路径;应使用一次性 checkout 或容器。 -图片读取需要支持图片输入的路由。自动压缩保留完整 Session 日志;模型与存储影响见[组合包参考](../../../packages/bundle/sdk-minimal/README.zh.md)。SDK 提示词文本不会执行 `/compact` 或其他斜杠命令。 +图片读取需要支持图片输入的路由。自动压缩保留完整 Session 日志;模型与存储影响见[组合包参考](../../../packages/bundle/sdk-minimal/README.zh.md)。在这个 `sdk-minimal` 组合中,不支持的斜杠输入保持为普通提示词文本。 已安装 wheel 仍会打包完整 `web` profile 与前端产物。如果 Python SDK 部署还需要浏览器应用,请针对显式 `DSH_HOME` 运行 `dsh web`;`web` 是独立 CLI 应用,不能为 Python SDK client 提供服务。 diff --git a/packages/api/gateway/src/client/remote-events.ts b/packages/api/gateway/src/client/remote-events.ts index eabda54e37..8e5b1c22ca 100644 --- a/packages/api/gateway/src/client/remote-events.ts +++ b/packages/api/gateway/src/client/remote-events.ts @@ -333,7 +333,7 @@ function invalidRemoteEventFrame(): never { } function privateEvents(ctx: Context): PrivateEventContext { - return ctx + return ctx.events } function toError(reason: unknown, message: string): Error { diff --git a/packages/api/gateway/tests/gateway.client.spec.ts b/packages/api/gateway/tests/gateway.client.spec.ts index a7e0ca2560..3807baee59 100644 --- a/packages/api/gateway/tests/gateway.client.spec.ts +++ b/packages/api/gateway/tests/gateway.client.spec.ts @@ -866,7 +866,7 @@ describe('Client Typert API', () => { const ctx = await bench(call) const agentCtx = ctx.extend({ fixtureId: 'agent-2' }) as FixtureContext ctx.typert.contexts.registerClient('fixture', { - identity: candidate => (candidate as Context & { fixtureId?: string }).fixtureId, + identity: candidate => 'fixtureId' in candidate ? (candidate as Context & { fixtureId?: string }).fixtureId : undefined, resolve: id => id === 'agent-2' ? agentCtx : undefined, }) const assembly = ctx.plugin(Object.assign( @@ -897,7 +897,7 @@ describe('Client Typert API', () => { const ctx = await bench(call) const agentCtx = ctx.extend({ fixtureId: 'agent-2' }) as FixtureContext ctx.typert.contexts.registerClient('fixture', { - identity: candidate => (candidate as Context & { fixtureId?: string }).fixtureId, + identity: candidate => 'fixtureId' in candidate ? (candidate as Context & { fixtureId?: string }).fixtureId : undefined, resolve: id => id === 'agent-2' ? agentCtx : undefined, }) const assembly = ctx.plugin(Object.assign( @@ -943,7 +943,7 @@ describe('Client Typert API', () => { const ctx = await bench(call) const agentCtx = ctx.extend({ fixtureId: 'agent-remounted' }) as FixtureContext ctx.typert.contexts.registerClient('fixture', { - identity: candidate => (candidate as Context & { fixtureId?: string }).fixtureId, + identity: candidate => 'fixtureId' in candidate ? (candidate as Context & { fixtureId?: string }).fixtureId : undefined, resolve: id => id === 'agent-remounted' ? agentCtx : undefined, }) const direct = directDescriptor() diff --git a/packages/api/gateway/tests/gateway.host.spec.ts b/packages/api/gateway/tests/gateway.host.spec.ts index 4272ee90bb..2931b3d159 100644 --- a/packages/api/gateway/tests/gateway.host.spec.ts +++ b/packages/api/gateway/tests/gateway.host.spec.ts @@ -75,14 +75,14 @@ class GoalService extends Service { return { agentId: agent.id, title: request.title, - scope: (this.ctx as MarkedContext).fixtureScope ?? 'root', + scope: 'fixtureScope' in this.ctx ? (this.ctx as MarkedContext).fixtureScope : 'root', } } @RemoteScope('gatewayFixture') rename(request: { readonly title: string }): unknown { this.calls.push('rename') - return { title: request.title, scope: (this.ctx as MarkedContext).fixtureScope ?? 'root' } + return { title: request.title, scope: 'fixtureScope' in this.ctx ? (this.ctx as MarkedContext).fixtureScope : 'root' } } @Remote diff --git a/packages/api/remotes/tests/built-lib.e2e.ts b/packages/api/remotes/tests/built-lib.e2e.ts index 2c22aff84f..07d0ef5618 100644 --- a/packages/api/remotes/tests/built-lib.e2e.ts +++ b/packages/api/remotes/tests/built-lib.e2e.ts @@ -184,7 +184,7 @@ describe.skipIf(!requiredArtifacts)('Goal Remote built LIB chain', () => { await client.plugin({ inject: plugin.inject, apply: plugin.apply }) } client.typert.contexts.registerClient('agent', { - identity: candidate => candidate.builtAgentId, + identity: candidate => 'builtAgentId' in candidate ? candidate.builtAgentId : undefined, }) const invalidResult = await client.remote.goals.create(rootAgent.id, { objective: 1 }) diff --git a/packages/boot/app-boot/src/index.ts b/packages/boot/app-boot/src/index.ts index acab24ebe4..b89eb3632a 100644 --- a/packages/boot/app-boot/src/index.ts +++ b/packages/boot/app-boot/src/index.ts @@ -340,9 +340,7 @@ async function recompose( diagnostic: failure.entry.fiber?.uid ? reloadDiagnostic(failure) : undefined, })) // Removed entries leave the Loader store before their async disposers finish. - const previousFibers = [...ctx.loader.entries()].flatMap(row => row.fiber === undefined ? [] : [{ - fiber: row.fiber, failed: row.fiber.state === FIBER_FAILED || row.fiber.state === FIBER_DISPOSED, - }]) + const previousFibers = [...ctx.loader.entries()].flatMap(row => row.fiber === undefined ? [] : [row.fiber]) const { patches: previous = [], ...includeConfig } = entry.options.config as Include.Config const current = withResolution ? ctx.get('pluginPackages')?.resolution : undefined // A plain-data resolution has no inputs to recompute from. @@ -386,12 +384,15 @@ async function recompose( const prepared = prepareProfilePatches(ctx, patches, parentURL, binName) applying = true const retried = [...new Set([...running, ...withResolution ? [...ctx.loader.entries()].filter(importFailed) : []])] + // Group.update replaces its data array and attempts every row it still lists, including failed imports. + const priorData = new Map(retried.map(row => [row, row.parent.data])) try { await entry.update({ config: { ...includeConfig, patches: prepared } }) } finally { - await resume(ctx, retried) + // Only rows whose Group did not update still need an explicit retry after the awaited update. + await resume(ctx, retried.filter(row => row.parent.data === priorData.get(row))) } - const results = await Promise.allSettled(previousFibers.map(({ fiber }) => fiber.await())) + await Promise.allSettled(previousFibers.map(fiber => fiber.await())) await ctx.loader.await() const failures = await inactiveEntries(ctx) const introduced = failures.filter((failure) => { @@ -403,9 +404,6 @@ async function recompose( return !previousFailures.some(previous => sameFailure(previous, failure)) }) if (introduced.length > 0) throw new Error(activationDiagnostic(binName, introduced, false).trimEnd()) - for (const [index, result] of results.entries()) { - if (result.status === 'rejected' && !previousFibers[index]?.failed) throw result.reason - } ctx.emit('app-boot/config-reload') return { warnings: failures.map(reloadDiagnostic) } } finally { @@ -1224,11 +1222,6 @@ export async function boot( try { ctx.baseUrl = pathToFileURL(dirname(absoluteConfigPath)).href + '/' ctx.provide('dshHomePath', dshHomePath) - // Fiber.update() discards the restart promise. Observe it before the - // waterfall returns; activation audits still report the failed fiber. - ctx.on('internal/update', (_config, _noSave, next: () => unknown) => { - void Promise.resolve(next()).catch((error: unknown) => { ctx.logger.error(error) }) - }, { global: true, prepend: true }) await ctx.plugin(Loader) await prepare?.(ctx) stage = 'plugin tree failed to load' diff --git a/packages/boot/app-boot/src/startup-diagnostics.ts b/packages/boot/app-boot/src/startup-diagnostics.ts index 7982ccc111..c9fe729935 100644 --- a/packages/boot/app-boot/src/startup-diagnostics.ts +++ b/packages/boot/app-boot/src/startup-diagnostics.ts @@ -90,7 +90,7 @@ export function captureStartupComposition(ctx: Context): StartupCompositionDiagn const impl = store[key] if (impl?.name !== service) continue providers.push({ - entry: impl.fiber.entry?.id ?? 'unknown', state: stateName(impl.fiber.state), + entry: impl.ctx.fiber.entry?.id ?? 'unknown', state: stateName(impl.ctx.fiber.state), visibility: key === scope ? 'same-scope' : 'other-scope', }) } diff --git a/packages/boot/app-boot/tests/user-patches.spec.ts b/packages/boot/app-boot/tests/user-patches.spec.ts index 63e0af5ea6..5b0257aac1 100644 --- a/packages/boot/app-boot/tests/user-patches.spec.ts +++ b/packages/boot/app-boot/tests/user-patches.spec.ts @@ -254,6 +254,11 @@ describe('Loader config interpolation', () => { await provider?.update({ config: { value: 'recovered' } }) await provider?.update({ disabled: false }) await ctx.loader.await() + // rc.11 keeps a failed fiber failed after its dependency recovers; recovery requires an explicit update. + const failed = reader?.fiber + if (failed === undefined) throw new Error('reader entry has no fiber') + await expect(failed.await()).rejects.toThrow('rejected provider') + await failed.update(failed.rawConfig, true) expect(ctx.get('readerResult')).toEqual({ value: 'recovered' }) } finally { await ctx.fiber.dispose() @@ -360,7 +365,7 @@ describe('profile reconciliation settlement', () => { onTestFinished(() => ctx.fiber.dispose()) const entry = [...ctx.loader.entries()].find(row => row.options.id === 'candidate') if (entry === undefined) throw new Error('candidate entry missing') - await entry.update({ config: { fail: true } }) + await expect(entry.update({ config: { fail: true } })).rejects.toThrow('candidate activation failed') await ctx.loader.await() await reconcileProfilePatches(ctx, [], NAME) expect([...ctx.loader.entries()].some(row => row.options.id === 'candidate')).toBe(false) @@ -379,7 +384,7 @@ describe('profile reconciliation settlement', () => { .rejects.toThrow('candidate activation failed') }) - it('reports an activation failure that settles while its entry is being removed', async () => { + it('logs a superseded activation failure without failing removal', async () => { const dir = tmp() const entered = Promise.withResolvers() const release = Promise.withResolvers() @@ -390,11 +395,19 @@ describe('profile reconciliation settlement', () => { }) onTestFinished(async () => { release.resolve(undefined); await ctx.fiber.dispose() }) const entry = [...ctx.loader.entries()].find(row => row.options.id === 'candidate')! - await entry.update({ config: { fail: true } }) + const updating = entry.update({ config: { fail: true } }) await entered.promise - const result = expect(reconcileProfilePatches(ctx, [], NAME)).rejects.toThrow('in-flight failure') + const stopped = Promise.withResolvers() + ctx.on('internal/plugin', (fiber) => { + if (fiber.uid === null && fiber.entry === entry) stopped.resolve(undefined) + }) + const removing = reconcileProfilePatches(ctx, [], NAME) + await stopped.promise release.resolve(undefined) - await result + await Promise.all([updating, removing]) + expect([...ctx.loader.entries()].some(row => row.options.id === 'candidate')).toBe(false) + expect(ctx.logger.buffer.some(message => message.type === 'error' + && message.args.some(value => String(value).includes('in-flight failure')))).toBe(true) }) it('waits for a removed plugin to release its resources', async () => { diff --git a/packages/boot/hmr/src/index.ts b/packages/boot/hmr/src/index.ts index 709524d741..36c16ba6ac 100644 --- a/packages/boot/hmr/src/index.ts +++ b/packages/boot/hmr/src/index.ts @@ -678,10 +678,12 @@ class Hmr extends Service { activated: Fiber[] = [], ) => { for (const [previousFiber, implementation] of replacements.getActiveImplementations(this.ctx, plugin, fibers)) { - const fiber = previousFiber.fiber.parent.registry.plugin(implementation, previousFiber.config, this.getOuterStack).ctx.fiber + const wrapper = previousFiber.fiber.parent.registry.plugin(implementation, previousFiber.config, this.getOuterStack) + const fiber = wrapper.ctx.fiber if (previousFiber.entry !== undefined) { fiber.entry = previousFiber.entry - previousFiber.entry.fiber = fiber + // Like Loader activation, store the registry wrapper; identity checks compare `.ctx.fiber`. + previousFiber.entry.fiber = wrapper } activated.push(fiber) } @@ -831,7 +833,7 @@ class Hmr extends Service { const owner = (fiber: Fiber): Entry | undefined => { for (let current = fiber; current.uid !== 0; current = current.parent.fiber) { const entry = current.entry - if (entry?.fiber === current && managed.has(entry) && affectedFibers.has(current)) return entry + if (entry?.fiber?.ctx.fiber === current && managed.has(entry) && affectedFibers.has(current)) return entry } return undefined } diff --git a/packages/boot/hmr/tests/coordination.spec.ts b/packages/boot/hmr/tests/coordination.spec.ts index b3660828e9..e0dceccb99 100644 --- a/packages/boot/hmr/tests/coordination.spec.ts +++ b/packages/boot/hmr/tests/coordination.spec.ts @@ -218,7 +218,7 @@ it('rebinds configuration handlers when its provider is reconfigured within a re }) await binding.await() await hmr.runExclusive(async () => { - provider.update({ root: [], ignored: [], debounce: 1 }) + await provider.update({ root: [], ignored: [], debounce: 1 }) await provider.await() await binding.await() }) diff --git a/packages/boot/plugin-manager/README.i18n.yaml b/packages/boot/plugin-manager/README.i18n.yaml index b40049c632..2b95a68b06 100644 --- a/packages/boot/plugin-manager/README.i18n.yaml +++ b/packages/boot/plugin-manager/README.i18n.yaml @@ -15,8 +15,8 @@ en: 87679c51aa3693f5 zh: 11684a48a5806afb /deepseek-ai-dsh-plugin-manager/use-this-package: - en: 4bda68030a6999e0 - zh: 5ae0b9825341c05e + en: ae0905aa47cc971d + zh: b22fc6e831fac136 /deepseek-ai-dsh-plugin-manager/use-this-package/version-compatibility-and-exemptions: en: 483285658e267dd5 zh: 846bec2daac59a96 diff --git a/packages/boot/plugin-manager/README.md b/packages/boot/plugin-manager/README.md index fd75a0d46a..a06788d42a 100644 --- a/packages/boot/plugin-manager/README.md +++ b/packages/boot/plugin-manager/README.md @@ -28,9 +28,9 @@ Manage the current profile's plugins without editing configuration by hand. Enab ## Use this package -Base-backed profiles provide the manager. In Web, the sidebar's **Plugins** page ([ui-plugin-manager](../../client/ui-plugin-manager/README.md)) manages the profile's bundles and their uniquely addressable rows; the Settings Plugin list stays read-only. Agent-preset rows remain read-only. The `plugin_manager` tool exposes the same operations and is enabled in the Standard and Creator presets. Other presets keep it disabled by default. Every tool action requires `danger-full-access` or approval for that call. Under lower sandbox modes, `ask` requests approval; `never`, rejection, cancellation, or an unavailable approval channel prevents execution. An approval leaves the session permission mode unchanged. Profile changes persist across sessions, and installed Host code executes in-process outside the workspace sandbox. Dependency build-script approval remains separate. +Base-backed profiles provide the manager. In Web, the sidebar's **Plugins** page ([ui-plugin-manager](../../client/ui-plugin-manager/README.md)) manages the profile's bundles and their uniquely addressable rows; the Settings Plugin list stays read-only. Agent-preset rows remain read-only. The `plugin_manager` tool exposes the same operations and is enabled in the Standard and Creator presets. Other Web presets keep it disabled by default. The full SDK profile enables it at profile scope in native/PTC mode; without HMR, saved changes return `restart-required` with `no-hmr` and apply after the runtime restarts. Every tool action requires `danger-full-access` or approval for that call. Under lower sandbox modes, `ask` requests approval; `never`, rejection, cancellation, or an unavailable approval channel prevents execution. An approval leaves the session permission mode unchanged. Profile changes persist across sessions, and installed Host code executes in-process outside the workspace sandbox. Dependency build-script approval remains separate. -For a deployment without agent presets, enable the tool in the profile patch. Preset-backed sessions use their preset’s `tool-plugin-manager` entry. +For a deployment without agent presets other than the full SDK profile, enable the tool in the profile patch. Package installation/removal requires pnpm on `PATH` or an explicit `pnpmCommand`; a launcher-provided package manager takes precedence. Preset-backed sessions use their preset’s `tool-plugin-manager` entry. ```yaml - id: tool-plugin-manager @@ -57,7 +57,7 @@ Official on-demand installs call the same `installBundle` operation as other bun `updateBundle(name, version, options)` replaces an updatable bundle with an exact newer version; an older version is refused. The target is first viewed over the same plan as `listVersions`, and a version that is missing, declares no bundle, or whose `engines.dsh` or DSH peers reject the running DSH stops the update at `step: 'check'` with the profile unchanged. With HMR the update removes the installed version, so its plugins stop, then installs `name@version` with `saveExact` and the current selection from the registry that answered. When that installation fails, is cancelled, or installs but cannot start, the target is removed if it stayed and the removed version is installed again from the registry it was installed from in this process, else over the configured plan as its removal asks, and reported as `restore`; a reinstallation that also fails leaves the package uninstalled. A removal or installation that rejects, for example on a lock timeout, is reported as that step's failure. Without HMR the target is installed over the running version and the result reports `restart-required`. `plugin-manager/update-state` announces `checking`, `removing`, `installing`, and `restoring` under the caller's `requestId`; the target's installation streams its logs and accepts `cancelInstall` under the same id, while the reinstallation carries none, so a cancellation cannot stop it. -`installBundle` checks GitHub repositories with `git ls-remote` before starting pnpm, using the profile directory and the installer's Git and proxy configuration. `githubConnectionTimeoutMs` defaults to 5000 ms and limits only this check, not package download or builds. The check disables credential helpers and prompts; only network failures and timeouts stop installation, reporting `failedAt: 'spec-host'` with the existing failure kind and diagnostic log. Authentication, repository lookup and other failures are left to pnpm, including its HTTPS-to-SSH fallback. Cancellation and manager disposal stop the check and its descendants. Registry packages, paths, tarballs and other Git hosts skip this check. A reachable repository can still fail during download or bundle validation. +`installBundle` checks GitHub repositories with `git ls-remote` before starting pnpm, using the profile directory and the installer's Git and proxy configuration. `githubConnectionTimeoutMs` defaults to 5000 ms and limits only this check, not package download or builds. The check disables credential helpers and prompts; only network failures and timeouts stop installation, reporting `failedAt: 'spec-host'` with the existing failure kind and diagnostic log. A stopped installation streams that failure under its `requestId` as the installation's only `plugin-manager/install-log` run, named by the `git ls-remote` command line with any URL user information removed; a timed-out check reports no exit code. The answer's `packageResult` stays a plain result, without the command line. Authentication, repository lookup and other failures are left to pnpm, including its HTTPS-to-SSH fallback. Cancellation and manager disposal stop the check and its descendants. Registry packages, paths, tarballs and other Git hosts skip this check. A reachable repository can still fail during download or bundle validation. An HTTP(S) Git URL on a host for which pnpm has no HTTPS-to-SSH fallback, that is, any host `hosted-git-info` does not know, such as a self-hosted GitLab, is probed with `git ls-remote` before pnpm starts. The probe uses the installer's Git configuration and credential helpers with Git's terminal and askpass prompts disabled; on POSIX it also has no controlling terminal, so SSH cannot prompt. When HTTP(S) cannot read the repository and `ssh://git@/` can, pnpm installs that SSH URL with the original fragment, and the profile records it. Otherwise the spec is installed unchanged. Each probe is bounded by `gitTransportTimeoutMs`, 5000 ms by default; cancellation and manager disposal stop it. URLs with credentials or a query skip the probe. @@ -65,7 +65,7 @@ Registries are asked in turn. The plan starts at `options.registry`, else the co The browser-safe `@deepseek-ai/dsh-plugin-manager/registry` entry exports `OFFICIAL_NPM_REGISTRY` and `NPMMIRROR_REGISTRY` for consumers that identify those public registries. -`installBundle` accepts a caller-generated `requestId`, under which `plugin-manager/install-log` streams each pnpm run's output and `plugin-manager/install-state` announces `installing`, `cancelling`, and `applying`; `installing` is announced once per registry asked, with the `attempt`'s registry, position, and the plan's length. The install asks the same plan as the lookup, from `options.registry`, running `pnpm add` with `--registry` and restoring the profile files between attempts; it moves on for the failures another registry can change and stops at any other, and at a failure whose error line names the host a git or tarball spec is fetched from, which no registry stands in for; `failedAt` says which of the two the last failed run could not reach. `cancelInstall(requestId)` stops the run and answers `cancelled` only after the Git check or pnpm exited and the files are back, `too-late` once the bundle is being applied, and `not-running` for any other id; the install call then reports `application: 'cancelled'`. A run that fails, is cancelled, or adds a package without a bundle patch restores `package.json` and `pnpm-lock.yaml` as they were; `packageResult.kind` classifies the last run from its exit and output, `registries` names every registry asked, `bundle` names the package a finished run added, and `version` its manifest version, which can differ from the version `inspect` read, for example when pnpm's `minimumReleaseAge` holds back a recent release. `listBundles` carries each bundle's one-liner (the package `description`), the rows its patch declares with their live entries, and the built-in rows it overrides; it lists the profile's own bundles, the bundles the installation supplies, and a selected name without a bundle patch as a `not-bundle` problem, while an unselected plain dependency is left out. A bundle the launcher's `OPTIONAL_BUNDLES` names is `optional`: shipped switched off for the person to turn on, never removable, and selected by no shipped template ([rationale](../../../.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md)). Every completed operation emits `plugin-manager/changed`; a patch generation applied outside the manager, by HMR's watcher after a CLI or hand edit, announces nothing, so the page learns of it on its next read. +`installBundle` accepts a caller-generated `requestId`, under which `plugin-manager/install-log` streams each pnpm run's output and `plugin-manager/install-state` announces `installing`, `cancelling`, and `applying`; a pnpm run that fails without printing streams the diagnostic its log carries, so the details panel is not left empty. `installing` is announced once per registry asked, with the `attempt`'s registry, position, and the plan's length. The install asks the same plan as the lookup, from `options.registry`, running `pnpm add` with `--registry` and restoring the profile files between attempts; it moves on for the failures another registry can change and stops at any other, and at a failure whose error line names the host a git or tarball spec is fetched from, which no registry stands in for; `failedAt` says which of the two the last failed run could not reach. `cancelInstall(requestId)` stops the run and answers `cancelled` only after the Git check or pnpm exited and the files are back, `too-late` once the bundle is being applied, and `not-running` for any other id; the install call then reports `application: 'cancelled'`. A run that fails, is cancelled, or adds a package without a bundle patch restores `package.json` and `pnpm-lock.yaml` as they were; `packageResult.kind` classifies the last run from its exit and output, `registries` names every registry asked, `bundle` names the package a finished run added, and `version` its manifest version, which can differ from the version `inspect` read, for example when pnpm's `minimumReleaseAge` holds back a recent release. `listBundles` carries each bundle's one-liner (the package `description`), the rows its patch declares with their live entries, and the built-in rows it overrides; it lists the profile's own bundles, the bundles the installation supplies, and a selected name without a bundle patch as a `not-bundle` problem, while an unselected plain dependency is left out. A bundle the launcher's `OPTIONAL_BUNDLES` names is `optional`: shipped switched off for the person to turn on, never removable, and selected by no shipped template ([rationale](../../../.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md)). Every completed operation emits `plugin-manager/changed`; a patch generation applied outside the manager, by HMR's watcher after a CLI or hand edit, announces nothing, so the page learns of it on its next read. `waitForInstall(requestId)` lets a client recover a lost response by waiting for the active installation, including its non-cancellable application phase. It returns the same outcome as the original call, or `null` if the request is not active. Completed results are not retained; `null` establishes neither success nor cancellation. diff --git a/packages/boot/plugin-manager/README.zh.md b/packages/boot/plugin-manager/README.zh.md index 46a95a412e..db1c756fae 100644 --- a/packages/boot/plugin-manager/README.zh.md +++ b/packages/boot/plugin-manager/README.zh.md @@ -28,9 +28,9 @@ kind: "package-reference" ## 使用本包 -基于 base 的 profile 提供管理服务。在 Web 中,侧边栏的**插件**页([ui-plugin-manager](../../client/ui-plugin-manager/README.zh.md))管理 profile 的组合包及其能唯一定位的行;设置页的插件列表保持只读。Agent 预设条目保持只读。`plugin_manager` 工具提供相同操作,在标准和 Creator 预设中启用。其他预设仍默认禁用。每个工具操作都要求 `danger-full-access` 或本次调用的批准。在较低沙箱模式下,`ask` 会请求审批;`never`、拒绝、取消或审批渠道不可用时均不执行。批准不改变会话的权限模式。profile 变更跨会话持久化,已安装的 Host 代码在宿主进程内运行,不受工作区沙箱限制。依赖构建脚本仍需单独批准。 +基于 base 的 profile 提供管理服务。在 Web 中,侧边栏的**插件**页([ui-plugin-manager](../../client/ui-plugin-manager/README.zh.md))管理 profile 的组合包及其能唯一定位的行;设置页的插件列表保持只读。Agent 预设条目保持只读。`plugin_manager` 工具提供相同操作,在标准和 Creator 预设中启用。其他 Web 预设仍默认禁用。完整 SDK profile 在 profile 作用域为 native/PTC 模式启用此工具;没有 HMR 时,保存的变更返回 `restart-required` 和 `no-hmr`,在运行时重启后应用。每个工具操作都要求 `danger-full-access` 或本次调用的批准。在较低沙箱模式下,`ask` 会请求审批;`never`、拒绝、取消或审批渠道不可用时均不执行。批准不改变会话的权限模式。profile 变更跨会话持久化,已安装的 Host 代码在宿主进程内运行,不受工作区沙箱限制。依赖构建脚本仍需单独批准。 -未使用 Agent 预设的部署在 profile patch 中启用工具;使用预设的会话由其预设中的 `tool-plugin-manager` 条目控制。 +除完整 SDK profile 外,未使用 Agent 预设的部署在 profile patch 中启用工具;安装/移除包要求 PATH 中有 pnpm,或显式配置 `pnpmCommand`,启动器提供的包管理器优先;使用预设的会话由其预设中的 `tool-plugin-manager` 条目控制。 ```yaml - id: tool-plugin-manager @@ -57,7 +57,7 @@ kind: "package-reference" `updateBundle(name, version, options)` 把可更新的组合包替换为一个更新的确切版本;更旧的版本会被拒绝。目标版本先按与 `listVersions` 相同的计划查询,版本不存在、未声明组合包,或其 `engines.dsh` 或 DSH peer 拒绝当前 DSH 时,更新停在 `step: 'check'`,profile 保持不变。有 HMR 时,更新先移除已安装版本,使其插件停止,再以 `saveExact` 和当前的选中状态从作答的注册表安装 `name@version`。该安装失败、被取消,或已安装但无法启动时,先移除仍留下的目标版本,再从本进程安装被移除版本所用的注册表重新安装它,没有记录时按配置的计划安装,与移除的做法一致,结果以 `restore` 报告;重新安装也失败时,包处于未安装状态。移除或安装被拒绝(例如锁等待超时)时,报告为该步骤失败。没有 HMR 时,目标版本直接安装在运行中的版本之上,结果报告 `restart-required`。`plugin-manager/update-state` 以调用方的 `requestId` 通告 `checking`、`removing`、`installing` 与 `restoring`;目标版本的安装以同一 id 流式输出日志并接受 `cancelInstall`,重新安装不带 id,因此取消无法中止它。 -`installBundle` 在启动 pnpm 前通过 `git ls-remote` 检查 GitHub 仓库,使用 profile 目录及安装器的 Git 与代理配置。`githubConnectionTimeoutMs` 默认为 5000 毫秒,只限制这次检查,不限制包下载或构建。检查禁用凭据助手和认证提示;只有网络失败与超时会停止安装,通过现有失败类型与诊断日志返回,并标记 `failedAt: 'spec-host'`。认证、仓库查找及其他失败继续交给 pnpm,包括其 HTTPS 到 SSH 的回退。取消安装或销毁管理器会停止检查及其子进程。注册表包、本地路径、压缩包和其他 Git 主机跳过此检查。仓库可达后,下载或组合包验证仍可能失败。 +`installBundle` 在启动 pnpm 前通过 `git ls-remote` 检查 GitHub 仓库,使用 profile 目录及安装器的 Git 与代理配置。`githubConnectionTimeoutMs` 默认为 5000 毫秒,只限制这次检查,不限制包下载或构建。检查禁用凭据助手和认证提示;只有网络失败与超时会停止安装,通过现有失败类型与诊断日志返回,并标记 `failedAt: 'spec-host'`。被停止的安装会以调用方的 `requestId` 把该失败转发为这次安装唯一的 `plugin-manager/install-log` 运行,其命令行是去掉 URL 用户信息的 `git ls-remote`;因超时结束的检查不报告退出码。应答中的 `packageResult` 仍是普通结果,不含该命令行。认证、仓库查找及其他失败继续交给 pnpm,包括其 HTTPS 到 SSH 的回退。取消安装或销毁管理器会停止检查及其子进程。注册表包、本地路径、压缩包和其他 Git 主机跳过此检查。仓库可达后,下载或组合包验证仍可能失败。 HTTP(S) Git URL 指向 pnpm 没有 HTTPS 到 SSH 回退的主机(即 `hosted-git-info` 不认识的任何主机,例如自托管 GitLab)时,在启动 pnpm 前通过 `git ls-remote` 探测。探测使用安装器的 Git 配置与凭据助手,并禁用 Git 的终端与 askpass 提示;在 POSIX 上探测也没有控制终端,因此 SSH 无法提示。HTTP(S) 无法读取仓库而 `ssh://git@/` 可以读取时,pnpm 以该 SSH URL 加上原片段安装,profile 也记录该 URL。否则按原 spec 安装。每次探测受 `gitTransportTimeoutMs` 限制,默认为 5000 毫秒;取消安装或销毁管理器会停止探测。带凭据或查询串的 URL 跳过探测。 @@ -65,7 +65,7 @@ HTTP(S) Git URL 指向 pnpm 没有 HTTPS 到 SSH 回退的主机(即 `hosted-g 可在浏览器使用的 `@deepseek-ai/dsh-plugin-manager/registry` 入口导出 `OFFICIAL_NPM_REGISTRY` 和 `NPMMIRROR_REGISTRY`,供消费方识别这两个公共注册表。 -`installBundle` 接受调用方生成的 `requestId`,`plugin-manager/install-log` 在其下流式转发每次 pnpm 运行的输出,`plugin-manager/install-state` 通告 `installing`、`cancelling` 与 `applying`;每问一个注册表通告一次 `installing`,`attempt` 带上这次的注册表、序号和计划长度。安装沿用查询的计划,从 `options.registry` 开始,以 `--registry` 运行 `pnpm add`,两次尝试之间恢复 profile 文件;换一个注册表能改变的失败才转问下一个,其他失败即停,错误行点名 git 或 tarball spec 自身拉取主机的失败也停,因为没有注册表能替代那台主机;`failedAt` 说明最后一次失败的运行连不上的是二者中的哪一个。`cancelInstall(requestId)` 停止运行,只在 Git 检查或 pnpm 退出且文件恢复后答复 `cancelled`,组合包已在应用时答复 `too-late`,其他 id 答复 `not-running`;安装调用随后报告 `application: 'cancelled'`。失败、被取消或装入了没有组合包 patch 的包的运行,会把 `package.json` 与 `pnpm-lock.yaml` 恢复原样;`packageResult.kind` 按退出方式与输出对最后一次运行分类,`registries` 列出问过的每个注册表,`bundle` 给出完成的运行新增的包,`version` 给出它的清单版本,它可能与 `inspect` 读到的版本不同,例如 pnpm 的 `minimumReleaseAge` 暂缓了最近的发布。`listBundles` 携带每个组合包的一句话简介(包的 `description`)、其 patch 声明的行及其存活条目,以及它覆盖的内置行;它列出 profile 自己的组合包、安装提供的组合包,以及被选中却没有组合包 patch 的名字(作为 `not-bundle` 问题),未选中的普通依赖不列出。启动器的 `OPTIONAL_BUNDLES` 点名的组合包是 `optional`:随安装提供、默认关闭、由用户开启,永不可卸载,也不被任何随附模板选中([理由](../../../.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md))。每个完成的操作都会发出 `plugin-manager/changed`;在管理器之外应用的一代 patch(HMR 监视到 CLI 或手工编辑后)不发通知,页面要到下一次读取才知道。 +`installBundle` 接受调用方生成的 `requestId`,`plugin-manager/install-log` 在其下流式转发每次 pnpm 运行的输出,`plugin-manager/install-state` 通告 `installing`、`cancelling` 与 `applying`;未打印任何输出就失败的 pnpm 运行转发其日志中的诊断,详情面板因而不会为空。每问一个注册表通告一次 `installing`,`attempt` 带上这次的注册表、序号和计划长度。安装沿用查询的计划,从 `options.registry` 开始,以 `--registry` 运行 `pnpm add`,两次尝试之间恢复 profile 文件;换一个注册表能改变的失败才转问下一个,其他失败即停,错误行点名 git 或 tarball spec 自身拉取主机的失败也停,因为没有注册表能替代那台主机;`failedAt` 说明最后一次失败的运行连不上的是二者中的哪一个。`cancelInstall(requestId)` 停止运行,只在 Git 检查或 pnpm 退出且文件恢复后答复 `cancelled`,组合包已在应用时答复 `too-late`,其他 id 答复 `not-running`;安装调用随后报告 `application: 'cancelled'`。失败、被取消或装入了没有组合包 patch 的包的运行,会把 `package.json` 与 `pnpm-lock.yaml` 恢复原样;`packageResult.kind` 按退出方式与输出对最后一次运行分类,`registries` 列出问过的每个注册表,`bundle` 给出完成的运行新增的包,`version` 给出它的清单版本,它可能与 `inspect` 读到的版本不同,例如 pnpm 的 `minimumReleaseAge` 暂缓了最近的发布。`listBundles` 携带每个组合包的一句话简介(包的 `description`)、其 patch 声明的行及其存活条目,以及它覆盖的内置行;它列出 profile 自己的组合包、安装提供的组合包,以及被选中却没有组合包 patch 的名字(作为 `not-bundle` 问题),未选中的普通依赖不列出。启动器的 `OPTIONAL_BUNDLES` 点名的组合包是 `optional`:随安装提供、默认关闭、由用户开启,永不可卸载,也不被任何随附模板选中([理由](../../../.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md))。每个完成的操作都会发出 `plugin-manager/changed`;在管理器之外应用的一代 patch(HMR 监视到 CLI 或手工编辑后)不发通知,页面要到下一次读取才知道。 `waitForInstall(requestId)` 让客户端在响应丢失后等待活动安装的结果,包括不可取消的应用阶段。它返回与原调用相同的结果,请求不在活动中时返回 `null`。已完成的结果不保留;`null` 不表示成功或已取消。 diff --git a/packages/boot/plugin-manager/src/github-connection.ts b/packages/boot/plugin-manager/src/github-connection.ts index 99b64fd73c..e2d349c734 100644 --- a/packages/boot/plugin-manager/src/github-connection.ts +++ b/packages/boot/plugin-manager/src/github-connection.ts @@ -4,9 +4,21 @@ import { join } from 'node:path' import { execa } from 'execa' import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess' import { classifyInstallFailure } from './install-failure.ts' -import type { ParsedInstallSpec } from './install-spec.ts' +import { HTTP_USER_INFO, type ParsedInstallSpec } from './install-spec.ts' import type { PackageResult } from './types.ts' +/** + * A failed check, with the Git command line the install dialog shows as the installation's only run. + * The returned result itself stays a plain {@link PackageResult}: the command line never joins the wire fields. + */ +export interface GithubConnectionFailure extends PackageResult { + /** + * The `git` command line the check ran, with the user information of an http(s) repository URL removed: + * `git -c credential.helper= ls-remote -- HEAD`. + */ + readonly argv: readonly string[] +} + /** Deadline, diagnostics and cancellation for one read-only GitHub check. */ export interface GithubConnectionOptions { timeoutMs: number @@ -23,11 +35,12 @@ export interface GithubConnectionOptions { * @param spec The parsed installation address; npm packages, local paths and other hosts are not checked. * @param dir The profile directory where installation runs. * @param options The connection deadline, output bound and operation cancellation. - * @returns A failed check with bounded output and a complete log at logPath, or undefined for a reachable repository or an unhandled spec. + * @returns A failed check carrying the command line it ran (without URL user information) and its bounded output, with a + * complete log at logPath, or undefined for a reachable repository or an unhandled spec. */ export async function checkGithubConnection( spec: ParsedInstallSpec, dir: string, options: GithubConnectionOptions, -): Promise { +): Promise { if (spec.kind !== 'git') return undefined const host = spec.host.toLowerCase().replace(/:.*$/, '') if (host !== 'github.com' && !host.endsWith('.github.com')) return undefined @@ -40,8 +53,12 @@ export async function checkGithubConnection( const logDir = await mkdtemp(join(logRoot, 'github-connection-')) const logPath = join(logDir, 'git.log') const log = await open(logPath, 'ax+', 0o600) + const argv = ['git', '-c', 'credential.helper=', 'ls-remote', '--', repository, 'HEAD'] as const + // The executed command keeps any credentials the spec names; the recorded one drops them before it is displayed. + const recordedArgv = argv.map(argument => argument.replace(HTTP_USER_INFO, '$1')) + const [command, ...args] = argv try { - const result = await execa('git', ['-c', 'credential.helper=', 'ls-remote', '--', repository, 'HEAD'], { + const result = await execa(command, args, { cwd: dir, env: { ...scrubbedParentEnv(), ...options.env, LC_ALL: 'C', GIT_TERMINAL_PROMPT: '0', @@ -58,9 +75,13 @@ export async function checkGithubConnection( const bytes = Buffer.alloc(Math.min(size, options.outputBytes)) await log.read(bytes, 0, bytes.length, size - bytes.length) const output = bytes.toString('utf8') + // `PackageResult.exitCode` is a status number, so a Git the deadline stopped records the status its failure is read + // as. The run streamed for the same failure reports no exit code, because that process ended without one. return { - exitCode: result.exitCode ?? (result.code === 'ENOENT' ? 127 : 1), output, truncated: size > options.outputBytes, logPath, + argv: recordedArgv, exitCode: result.exitCode ?? (result.code === 'ENOENT' ? 127 : 1), + output, truncated: size > options.outputBytes, logPath, kind: classifyInstallFailure({ log: output, timedOut: result.timedOut }), + ...result.timedOut ? { timedOut: true } : {}, } } finally { await log.close() diff --git a/packages/boot/plugin-manager/src/index.ts b/packages/boot/plugin-manager/src/index.ts index 271e6af0d3..ceb82aac47 100644 --- a/packages/boot/plugin-manager/src/index.ts +++ b/packages/boot/plugin-manager/src/index.ts @@ -36,7 +36,7 @@ import { attributeFailure, normalizeRegistry, NPMMIRROR_REGISTRY, registryPlan } import { flatten, writePluginEnabled } from './patch.ts' import { incompatiblePlugin, ManagementFailure } from './failure.ts' import { approveBuilds, recordPendingBuilds } from './build-approval.ts' -import { checkGithubConnection } from './github-connection.ts' +import { checkGithubConnection, type GithubConnectionFailure } from './github-connection.ts' import { chooseGitTransport, sshGitSpec } from './git-transport.ts' import { newerVersions, VERSION_FIELDS, VERSION_LIST_FIELDS, versionFacts } from './versions.ts' import type { @@ -522,6 +522,7 @@ export class PluginManager extends TypertRemoteService { catch (error) { platformError = managementError(error) } const error = platformError ?? targetError ?? (enabled ? { code: 'not-bundle' as const } : undefined) bundles.push({ name, official, availability: 'missing', ...catalogMeta, ...target, enabled, installed, optional, + ...offered.listedByDefault === undefined ? {} : { listedByDefault: offered.listedByDefault }, ...platformError?.code === 'unsupported-platform' ? { listedByDefault: false } : {}, removable: enabled, rows: [], overrides: [], ...error === undefined ? {} : { error } }) @@ -857,7 +858,8 @@ export class PluginManager extends TypertRemoteService { /** * Install a package using the same pnpm implementation as dsh plugin. GitHub * repositories get a connection check bounded by githubConnectionTimeoutMs before pnpm starts; - * only network failures or timeouts stop installation, while pnpm owns authentication and transport fallback. An + * only network failures or timeouts stop installation, and a stop streams the check's diagnostic + * as the installation's install-log run under its request id, while pnpm owns authentication and transport fallback. An * HTTP(S) Git URL on another host is installed over SSH instead when access probes bounded by gitTransportTimeoutMs * find that only SSH can read it. A run * that fails, is cancelled, or adds a package without a bundle patch restores @@ -901,13 +903,23 @@ export class PluginManager extends TypertRemoteService { timeoutMs: this.githubConnectionTimeoutMs, outputBytes: this.outputBytes, signal, ...env, }) this.packageOperations.add(connection) - let connectionFailure: PackageResult | undefined + let connectionFailure: GithubConnectionFailure | undefined try { connectionFailure = await connection } finally { this.packageOperations.delete(connection) } if (stopped()) throw new InstallCancelledError() if (connectionFailure?.kind === 'network' || connectionFailure?.kind === 'timeout') { - result.packageResult = connectionFailure + // The answer keeps a plain PackageResult; the check's command line is only streamed as the run below. + const { argv, ...packageResult } = connectionFailure + result.packageResult = packageResult result.failedAt = 'spec-host' + // pnpm never runs, so the check is the installation's only run: stream its failure into the install log. + // A timed-out Git reports no exit code of its own, unlike the result, which records the status it is read as. + if (requestId !== undefined) { + this.ownerContext.emit('plugin-manager/install-log', { + requestId, jobId: randomUUID(), argv, cwd: this.profile.dir, stream: 'stderr', + text: connectionFailure.output, exitCode: connectionFailure.timedOut === true ? null : connectionFailure.exitCode, + }) + } throw new Error(connectionFailure.output) } const transport = chooseGitTransport(parsed, this.profile.dir, { timeoutMs: this.gitTransportTimeoutMs, signal, ...env }) diff --git a/packages/boot/plugin-manager/src/install-spec.ts b/packages/boot/plugin-manager/src/install-spec.ts index 4b76f1925e..2fb6b64cca 100644 --- a/packages/boot/plugin-manager/src/install-spec.ts +++ b/packages/boot/plugin-manager/src/install-spec.ts @@ -94,7 +94,7 @@ export function parseInstallSpec(raw: string): ParsedInstallSpec { /** A recorded dependency value pnpm resolves outside a registry: a protocol other than a registry alias, or an scp-like git address. */ const NON_REGISTRY_VALUE = /^(?!(?:npm|jsr|workspace|catalog):)[a-z][a-z0-9+.-]*:|^[^@/:\s]+@[^:/\s]+:/i /** The user information of an http(s) URL, up to the last `@` before the path, which holds a password or access token when present. */ -const HTTP_USER_INFO = /^((?:git\+)?https?:\/\/)[^/]*@/i +export const HTTP_USER_INFO = /^((?:git\+)?https?:\/\/)[^/]*@/i /** * The spec `pnpm add` accepts for a dependency the profile manifest records. A git address, URL, or other diff --git a/packages/boot/plugin-manager/src/operations.ts b/packages/boot/plugin-manager/src/operations.ts index e7b761ad3c..d0ab1dccab 100644 --- a/packages/boot/plugin-manager/src/operations.ts +++ b/packages/boot/plugin-manager/src/operations.ts @@ -470,6 +470,8 @@ export async function runProfilePnpm( if (result.failed && output.length === 0) { const diagnostic = result.shortMessage ?? 'pnpm failed' await log.write(diagnostic) + // The run printed nothing, so this diagnostic is the whole of its captured output; stream it as such. + options.onOutput?.(diagnostic, 'stderr') truncated = Buffer.byteLength(diagnostic) > options.outputBytes output = Buffer.from(diagnostic).subarray(0, options.outputBytes) } diff --git a/packages/boot/plugin-manager/src/types.ts b/packages/boot/plugin-manager/src/types.ts index efef87b4dc..221607f1e8 100644 --- a/packages/boot/plugin-manager/src/types.ts +++ b/packages/boot/plugin-manager/src/types.ts @@ -139,13 +139,18 @@ export type PluginInstallFailureKind = /** Package operation completion, including Git checks and a retrieval path for unabridged diagnostics. */ export interface PackageResult { + /** The status the run is read as having ended with; a run the manager terminated records the coerced status 1. */ exitCode: number output: string truncated: boolean logPath: string /** Present when the run failed: what kind of failure its exit and output describe. */ kind?: PluginInstallFailureKind - /** The manager terminated the run after it printed nothing for its silence bound; `exitCode` still reports how it ended. */ + /** + * The run outlived its bound: the manager terminated it after it printed nothing for its silence bound, or the GitHub + * connection check hit its deadline. Such a run reports no exit status of its own, so `exitCode` records the status + * its failure is read as rather than a status the process returned. + */ timedOut?: boolean /** Present when a compatibility check refused the run: the packages the running DSH version rejects. */ incompatible?: IncompatiblePlugin[] @@ -344,19 +349,19 @@ export interface PluginInstallCancellation { readonly status: 'cancelled' | 'too-late' | 'not-running' } -/** One chunk of a pnpm run's output, as the run produces it. */ +/** One chunk of an installation run's output: a pnpm run, or the GitHub connection check that stopped it. */ export interface PluginInstallLogChunk { /** The installation the run belongs to, when its caller supplied a request id. */ readonly requestId?: PluginInstallRequestId /** The run the chunk belongs to. */ readonly jobId: string - /** The command line the run executes: pnpm's command name, then its arguments. */ + /** The command line the run executes: its command name, then its arguments. */ readonly argv: readonly string[] /** The directory the run executes in: the profile directory. */ readonly cwd: string readonly stream: 'stdout' | 'stderr' readonly text: string - /** Present on the run's last chunk: pnpm's exit code, null when it ended without one. */ + /** Present on the chunk that ends a run: its exit code, null when the run ended without one. */ readonly exitCode?: number | null } @@ -426,7 +431,7 @@ declare module '@deepseek-ai/cordis' { */ 'plugin-manager/changed'(change: PluginChange): void /** - * One chunk of a pnpm run's output, streamed as the run produces it. + * One chunk of an installation run's output, streamed as the run produces it. * @mode emit * @param chunk - the chunk and the run it belongs to. */ diff --git a/packages/boot/plugin-manager/tests/git-transport.spec.ts b/packages/boot/plugin-manager/tests/git-transport.spec.ts index 36d043b6b8..31fc22e6a0 100644 --- a/packages/boot/plugin-manager/tests/git-transport.spec.ts +++ b/packages/boot/plugin-manager/tests/git-transport.spec.ts @@ -26,7 +26,8 @@ const SSH_SPEC = `git+ssh://git@git.example/team/sub/plugin.git#${'a'.repeat(40) async function fixture() { const dir = await mkdtemp(join(tmpdir(), 'dsh-git-transport-')) - onTestFinished(() => rm(dir, { recursive: true, force: true })) + // Retry Windows directory-busy errors after awaited probe cleanup. + onTestFinished(() => rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })) const config = join(dir, 'git.config') await writeFile(config, '') const env = { GIT_CONFIG_GLOBAL: config, GIT_CONFIG_NOSYSTEM: '1' } diff --git a/packages/boot/plugin-manager/tests/github-connection.spec.ts b/packages/boot/plugin-manager/tests/github-connection.spec.ts index 33dd34e067..e87ac53b8c 100644 --- a/packages/boot/plugin-manager/tests/github-connection.spec.ts +++ b/packages/boot/plugin-manager/tests/github-connection.spec.ts @@ -43,6 +43,9 @@ async function fixture() { return { dir, config, controller, check, env } } +/** The exact command line a check runs for one repository URL. */ +const checkArgv = (repository: string): string[] => ['git', '-c', 'credential.helper=', 'ls-remote', '--', repository, 'HEAD'] + async function proxy(config: string, fail: boolean) { const sockets = new Set() const connected = Promise.withResolvers() @@ -93,7 +96,9 @@ it('reports an immediate transport failure without waiting for the deadline', as const transport = await proxy(config, true) const result = await check('https://github.com/acme/plugin.git') await transport.connected - expect(result).toMatchObject({ exitCode: 128, kind: 'network', truncated: false }) + expect(result).toMatchObject({ + exitCode: 128, kind: 'network', truncated: false, argv: checkArgv('https://github.com/acme/plugin.git'), + }) expect(await readFile(result!.logPath, 'utf8')).toBe(result!.output) await transport.disconnected expect(transport.sockets.size).toBe(0) @@ -106,6 +111,8 @@ it('ends a silent proxy connection and its Git child at the connection deadline' await transport.connected const result = await running expect(result?.kind).toBe('timeout') + // The result records the status the terminated Git is read as; only the streamed run reports no exit code. + expect(result).toMatchObject({ exitCode: 1, timedOut: true, argv: checkArgv('https://github.com/acme/plugin.git') }) expect(result!.output).toContain('connection to github.com timed out after 3000ms') await transport.disconnected expect(transport.sockets.size).toBe(0) @@ -128,12 +135,15 @@ it.each([undefined, 'Git could not start'])('retains a diagnostic when Git write const run = vi.spyOn(subprocess, 'execa').mockResolvedValue({ failed: true, shortMessage } as Awaited>) onTestFinished(() => { run.mockRestore() }) const result = await check('github:acme/plugin') - expect(result).toMatchObject({ exitCode: 1, kind: 'unknown', output: shortMessage ?? 'GitHub connection check failed' }) + expect(result).toMatchObject({ + exitCode: 1, kind: 'unknown', output: shortMessage ?? 'GitHub connection check failed', + argv: checkArgv('https://github.com/acme/plugin'), + }) expect(await readFile(result!.logPath, 'utf8')).toBe(result!.output) }) it('bounds returned diagnostics while retaining Git stderr in the operation log', async () => { - const { check } = await fixture() + const { check, dir } = await fixture() const run = vi.spyOn(subprocess, 'execa').mockImplementation((...args: unknown[]) => { const options = args[2] as { stderr: { file: string } } appendFileSync(options.stderr.file, '0123456789') @@ -141,10 +151,24 @@ it('bounds returned diagnostics while retaining Git stderr in the operation log' }) onTestFinished(() => { run.mockRestore() }) const result = await check('github:acme/plugin', 3000, 4) - expect(result).toMatchObject({ output: '6789', truncated: true }) + expect(result).toMatchObject({ output: '6789', truncated: true, argv: checkArgv('https://github.com/acme/plugin') }) + // The recorded command line is the one Git actually ran. + expect(run).toHaveBeenCalledWith('git', checkArgv('https://github.com/acme/plugin').slice(1), expect.objectContaining({ cwd: dir })) expect(await readFile(result!.logPath, 'utf8')).toBe('0123456789') }) +it('keeps URL user information out of the recorded command line', async () => { + const { check } = await fixture() + const run = vi.spyOn(subprocess, 'execa').mockResolvedValue({ + failed: true, exitCode: 128, shortMessage: 'fatal: unable to access the repository', + } as Awaited>) + onTestFinished(() => { run.mockRestore() }) + const result = await check('https://user:token@github.com/acme/plugin.git') + // Git runs the address as typed so its own credentials keep working, while the recorded line is safe to display. + expect(run).toHaveBeenCalledWith('git', checkArgv('https://user:token@github.com/acme/plugin.git').slice(1), expect.anything()) + expect(result?.argv).toEqual(checkArgv('https://github.com/acme/plugin.git')) +}) + it('reports a missing Git executable without classifying it as a network failure', async () => { const { check } = await fixture() const run = vi.spyOn(subprocess, 'execa').mockResolvedValue({ failed: true, code: 'ENOENT', shortMessage: 'spawn git ENOENT' } as Awaited>) diff --git a/packages/boot/plugin-manager/tests/manager.spec.ts b/packages/boot/plugin-manager/tests/manager.spec.ts index 0f8290a48d..207f34291f 100644 --- a/packages/boot/plugin-manager/tests/manager.spec.ts +++ b/packages/boot/plugin-manager/tests/manager.spec.ts @@ -127,24 +127,50 @@ it('allows supported bundle activation and permits deselecting an unsupported sa }) it.each(['network', 'timeout'] as const)('stops a GitHub %s before pnpm and attributes it to the repository', async (kind) => { - const { manager, dir, connection } = await fixture() + const { ctx, manager, dir, connection } = await fixture() + const chunks: PluginInstallLogChunk[] = [] + ctx.on('plugin-manager/install-log', (chunk) => { chunks.push(chunk) }) const before = readFileSync(join(dir, 'package.json'), 'utf8') - const failure = { exitCode: 1, output: 'GitHub check failed', truncated: false, logPath: join(dir, 'git.log'), kind } - connection.mockResolvedValue(failure) + const argv = ['git', '-c', 'credential.helper=', 'ls-remote', '--', 'https://github.com/acme/dsh-plugin.git', 'HEAD'] + const checked = { + argv, exitCode: 1, output: 'GitHub check failed', truncated: false, logPath: join(dir, 'git.log'), kind, + ...kind === 'timeout' ? { timedOut: true } : {}, + } + connection.mockResolvedValue(checked) const pnpm = vi.spyOn(operations, 'runProfilePnpm') onTestFinished(() => { pnpm.mockRestore() }) - expect(await manager.installBundle('https://github.com/acme/dsh-plugin.git')).toMatchObject({ - application: 'failed', changed: false, stage: 'install', failedAt: 'spec-host', packageResult: failure, + const requestId = '824103ec-bc45-489d-bb85-5b4fe0aefc78' as PluginInstallRequestId + const result = await manager.installBundle('https://github.com/acme/dsh-plugin.git', { requestId }) + expect(result).toMatchObject({ + application: 'failed', changed: false, stage: 'install', failedAt: 'spec-host', + packageResult: { exitCode: 1, output: 'GitHub check failed', truncated: false, logPath: join(dir, 'git.log'), kind }, }) + // The command line belongs to the streamed run only; the answer stays a plain package result. + expect(result.packageResult).not.toHaveProperty('argv') expect(pnpm).not.toHaveBeenCalled() expect(connection).toHaveBeenCalledWith(expect.objectContaining({ host: 'github.com' }), dir, expect.objectContaining({ timeoutMs: 5000 })) expect(readFileSync(join(dir, 'package.json'), 'utf8')).toBe(before) + // The check is the installation's only run, so its diagnostic reaches the details panel. A timed-out Git has no exit + // code of its own, so its chunk reports none instead of the status the timeout coerced. + expect(chunks).toEqual([{ + requestId, jobId: expect.any(String) as string, argv, cwd: dir, stream: 'stderr', text: 'GitHub check failed', + exitCode: kind === 'timeout' ? null : 1, + }]) + // Without a request id there is no installation to stream the failed check under. + chunks.length = 0 + expect(await manager.installBundle('https://github.com/acme/dsh-plugin.git')).toMatchObject({ failedAt: 'spec-host' }) + expect(chunks).toEqual([]) }) it('leaves non-network GitHub errors to pnpm and forwards profile Git environment and deadline', async () => { const env = { GIT_CONFIG_GLOBAL: '/application/git.config' } - const { manager, connection } = await fixture('live', false, undefined, { githubConnectionTimeoutMs: 8000 }, { command: 'pnpm', args: [], env }) - connection.mockResolvedValue({ exitCode: 128, output: 'fatal: Authentication failed', truncated: false, logPath: 'git.log', kind: 'unknown' }) + const { ctx, manager, connection } = await fixture('live', false, undefined, { githubConnectionTimeoutMs: 8000 }, { command: 'pnpm', args: [], env }) + const chunks: PluginInstallLogChunk[] = [] + ctx.on('plugin-manager/install-log', (chunk) => { chunks.push(chunk) }) + connection.mockResolvedValue({ + argv: ['git', '-c', 'credential.helper=', 'ls-remote', '--', 'https://github.com/acme/private-plugin', 'HEAD'], + exitCode: 128, output: 'fatal: Authentication failed', truncated: false, logPath: 'git.log', kind: 'unknown', + }) const failure = { exitCode: 1, output: 'pnpm owns authentication', truncated: false, logPath: 'pnpm.log', kind: 'unknown' as const } const pnpm = vi.spyOn(operations, 'runProfilePnpm').mockResolvedValue(failure) onTestFinished(() => { pnpm.mockRestore() }) @@ -154,6 +180,8 @@ it('leaves non-network GitHub errors to pnpm and forwards profile Git environmen expect(pnpm).toHaveBeenCalledOnce() expect(result.failedAt).toBeUndefined() expect(connection).toHaveBeenCalledWith(expect.anything(), expect.anything(), expect.objectContaining({ timeoutMs: 8000, env })) + // A check failure pnpm may resolve streams no run of its own. + expect(chunks.filter(chunk => chunk.argv[0] === 'git')).toEqual([]) }) it('cancels an active GitHub check before starting pnpm', async () => { @@ -162,7 +190,10 @@ it('cancels an active GitHub check before starting pnpm', async () => { connection.mockImplementation(async (_spec, _dir, options) => { entered.resolve(undefined) await new Promise((resolve) => { options.signal.addEventListener('abort', () => { resolve() }, { once: true }) }) - return { exitCode: 1, output: 'cancelled', truncated: false, logPath: 'git.log', kind: 'unknown' } + return { + argv: ['git', '-c', 'credential.helper=', 'ls-remote', '--', 'https://github.com/acme/dsh-plugin', 'HEAD'], + exitCode: 1, output: 'cancelled', truncated: false, logPath: 'git.log', kind: 'unknown', + } }) const pnpm = vi.spyOn(operations, 'runProfilePnpm') onTestFinished(() => { pnpm.mockRestore() }) @@ -244,7 +275,10 @@ it('disposal waits for an active GitHub check to stop', async () => { entered.resolve(undefined) await new Promise((resolve) => { options.signal.addEventListener('abort', () => { resolve() }, { once: true }) }) released.resolve(undefined) - return { exitCode: 1, output: 'cancelled', truncated: false, logPath: 'git.log', kind: 'unknown' } + return { + argv: ['git', '-c', 'credential.helper=', 'ls-remote', '--', 'https://github.com/acme/addon', 'HEAD'], + exitCode: 1, output: 'cancelled', truncated: false, logPath: 'git.log', kind: 'unknown', + } }) const pnpm = vi.spyOn(operations, 'runProfilePnpm') onTestFinished(() => { pnpm.mockRestore() }) @@ -1773,9 +1807,13 @@ it('lists absent Official entries offline without resolving their packages or co onTestFinished(() => { resolve.mockRestore(); registry.mockRestore() }) const bundles = await manager.listBundles() for (const entry of OFFICIAL_ON_DEMAND_CATALOG) { - expect(bundles.filter(bundle => bundle.name === entry.packageName)).toEqual([{ + expect(bundles.filter(bundle => bundle.name === entry.packageName)).toHaveLength(1) + expect(bundles.filter(bundle => bundle.name === entry.packageName)).toMatchObject([{ name: entry.packageName, official: true, availability: 'missing', enabled: false, installed: false, optional: false, removable: false, updatable: false, rows: [], overrides: [], meta: entry.meta, + ...entry.listedByDefault === undefined ? {} : { listedByDefault: entry.listedByDefault }, + ...entry.platforms !== undefined && !entry.platforms.includes(process.platform) + ? { listedByDefault: false, error: { code: 'unsupported-platform' } } : {}, installTarget: { spec: `${entry.packageName}@${getDshRuntimeVersion()}`, version: getDshRuntimeVersion() }, }]) expect(resolve.mock.calls.some(([name]) => name === entry.packageName)).toBe(false) diff --git a/packages/boot/plugin-manager/tests/operations.spec.ts b/packages/boot/plugin-manager/tests/operations.spec.ts index c54260d214..b6a87a6475 100644 --- a/packages/boot/plugin-manager/tests/operations.spec.ts +++ b/packages/boot/plugin-manager/tests/operations.spec.ts @@ -874,10 +874,16 @@ it.each([ ])('reports launch failures with a complete log: $code', async ({ code, shortMessage, expected }) => { const { context } = fixture() command.run.mockImplementationOnce(() => result(undefined, '', () => {}, { code, ...shortMessage === undefined ? {} : { shortMessage } })) - const outcome = await runProfilePnpm(context, ['root'], { execution: 'service', outputBytes: 4, signal: new AbortController().signal }) + const messages: string[] = [] + const outcome = await runProfilePnpm(context, ['root'], { + execution: 'service', outputBytes: 4, signal: new AbortController().signal, + onOutput: (text) => { messages.push(text) }, + }) expect(outcome.exitCode).toBe(expected) expect(outcome.truncated).toBe(true) expect(readFileSync(outcome.logPath, 'utf8')).toBe(shortMessage ?? 'pnpm failed') + // A run that printed nothing still streams the diagnostic its log carries. + expect(messages).toEqual([shortMessage ?? 'pnpm failed']) }) it('cancels and settles package output when the output consumer fails', async () => { diff --git a/packages/bundle/sdk-app/README.i18n.yaml b/packages/bundle/sdk-app/README.i18n.yaml index ed528810fc..623f6546a0 100644 --- a/packages/bundle/sdk-app/README.i18n.yaml +++ b/packages/bundle/sdk-app/README.i18n.yaml @@ -15,8 +15,8 @@ en: 4e53164159b5ce41 zh: 89582dc0294d0776 /deepseek-ai-dsh-sdk-app/use-this-package: - en: b9a0e01492ffe278 - zh: 7c6ffd1f9e9c0906 + en: 63aa871622cea3af + zh: 8f00a69640caadc5 /deepseek-ai-dsh-sdk-app/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 @@ -24,17 +24,17 @@ en: 4f88e647c6df4f42 zh: 2bd3e4b0bdfe9412 /deepseek-ai-dsh-sdk-app/model-experience/sdk-model-context/what-the-model-sees: - en: 0cce2b88aae3a0e5 - zh: fcb31314096ef15e + en: 6b46520441d75a00 + zh: 04851fd123960847 /deepseek-ai-dsh-sdk-app/model-experience/sdk-model-context/token-effect: - en: 0d4a38b2448396b3 - zh: e63408a146bf0100 + en: cef8efe97fe1ff16 + zh: c052ab3e6706efa6 /deepseek-ai-dsh-sdk-app/model-experience/sdk-model-context/kv-cache-effect: - en: 0503df0971e5f8d7 - zh: 18cae8c6e25cda04 + en: b1169743449b2272 + zh: 98d465d802bf55c1 /deepseek-ai-dsh-sdk-app/known-limitations-and-deferred-work: - en: 451497677de7e6b9 - zh: dcfdc671c38d54d4 + en: d1d4567b7d2b9d8d + zh: c1618617d1562d8b /deepseek-ai-dsh-sdk-app/known-limitations-and-deferred-work/dev-note: - en: e67f633dc6fe7773 - zh: e88aeb617ffb74ea + en: b9b4e27513ebba78 + zh: 51b123ac60ff28c6 diff --git a/packages/bundle/sdk-app/README.md b/packages/bundle/sdk-app/README.md index d1be289939..60d1db572e 100644 --- a/packages/bundle/sdk-app/README.md +++ b/packages/bundle/sdk-app/README.md @@ -35,6 +35,8 @@ The startup provider binds stdin EOF to the launcher's bounded successful shutdo The SDK uses the base `read`, `write`, and `edit` defaults. To add `str_replace_editor`, use the explicit insertion patch in the [base configuration guide](../base/README.md#use-this-package). The standalone `sdk-minimal` profile owns its separate tool selection. +The model can use [`plugin_manager`](../../boot/plugin-manager/README.md) in native and PTC modes. Every action, including listing, requires full access or approval for that call. The default workspace-write/ask policy needs a client approval responder: enable `approvalRequests` and handle `approval/request` through `harness.client.onRequest()`, or supply an approver in the composition. Without one, the operation is refused as unavailable. For Python package installation/removal, explicitly prepare Node and pnpm with `download_primary_runtime()` before starting the runtime; the packaged launcher then supplies them to plugin management without requiring system pnpm. Without a selected payload, package operations need `pnpm` on `PATH` or an explicit `plugin-manager.pnpmCommand`. See the [interactive approval example](../../../python/sdk/examples/manage_plugins.py). Saved profile changes report `restart-required` with `no-hmr`; the current runtime and its sessions retain their tools until the caller closes and starts the runtime again. Set `tool-plugin-manager.disabled: true` through a profile patch to hide this tool. The standalone `sdk-minimal` profile does not include it. + The Python runtime exposes explicitly downloaded authoring resources and Office sidecars to this profile. `DSH_PRIMARY_RUNTIME` overrides the authoring payload; an empty value disables its query. Office skills can use either resource independently. Profile patches can disable `skill-office` or replace its `assetRoot` independently of `workspace-dependencies`; filesystem skills with the same name take precedence. See the [runtime package](../../../python/sdk-runtime/README.md) for downloads and configuration. ----- @@ -46,15 +48,15 @@ The Python runtime exposes explicitly downloaded authoring resources and Office #### What the model sees -The profile inherits the base system prompt, including the `You are an AI agent powered by DeepSeek Harness.` identity, and adds the same model-interpolated coding persona as the Web and headless profiles. Each Session receives its current directory in required user-role context from [`dsh-working-directory`](../../session/working-directory/README.md). Default file tool schemas include `read`, `write`, and `edit`; they omit `str_replace_editor`. The model also receives `present`, `ask_user_question`, schedule tools, shared file-reference guidance, and time context. Child agents cannot use schedule tools. The [`time-context`](../../context/time-context/README.md) row accepts a fallback time zone. Skills use the configured resources described above. +The profile inherits the base system prompt, including the `You are an AI agent powered by DeepSeek Harness.` identity, and adds the same model-interpolated coding persona as the Web and headless profiles. Each Session receives its current directory in required user-role context from [`dsh-working-directory`](../../session/working-directory/README.md). Default file tool schemas include `read`, `write`, and `edit`; they omit `str_replace_editor`. The model also receives `present`, `ask_user_question`, `plugin_manager`, schedule tools, shared file-reference guidance, and time context. Child agents cannot use schedule tools. The [`time-context`](../../context/time-context/README.md) row accepts a fallback time zone. Skills use the configured resources described above. #### Token effect -The profile adds a coding-persona sentence, the mounted tool definitions and guidance, and logged runtime-context and time messages. +The profile adds a coding-persona sentence, the mounted tool definitions and guidance, and logged runtime-context and time messages. The `plugin_manager` description and parameter schema add input tokens even when an operation cannot be approved; an embedding that does not use plugin management can disable its row. #### KV Cache effect -The static prefix is stable for a fixed profile, provider, model, and tool roster. Runtime values append to logged user context. Profile changes take effect on the next process because the shipped SDK profile uses startup-only patches. +Enabling `plugin_manager` changes the tool-schema prefix from earlier SDK versions. The static prefix is stable for a fixed profile, provider, model, and tool roster. Runtime values append to logged user context. Profile changes take effect on the next process because the shipped SDK profile uses startup-only patches. ## Known Limitations and Deferred Work @@ -66,6 +68,7 @@ The static prefix is stable for a fixed profile, provider, model, and tool roste - **Schedules share the runtime lifetime** — delivery needs a running process and its persistent Session storage. - **A profile can omit the SDK server** — a custom profile selected by the TypeScript client must retain this bundle or another `dsh-sdk-jsonrpc-server` row; client initialization fails when no peer answers. - **User plugins can violate stdout purity** — profile and per-launch patches are trusted application composition. The shipped bundle writes no non-protocol stdout, but it cannot contain an arbitrary inserted plugin. +- **Plugin changes share a profile** — saved changes affect `/profiles/sdk` and other embeddings using that home on their next launch; use separate `dshHome` directories for independent compositions. The Python launcher uses Node/pnpm from its selected downloaded runtime; without that payload or an external pnpm, package operations fail. - **Configuration changes require restart** — the `sdk-app` bundle disables HMR in YAML so one stdio connection never observes a replacement server or Agent dependency. @@ -75,6 +78,6 @@ The static prefix is stable for a fixed profile, provider, model, and tool roste
Working context for maintainers — click to expand -None. +The [SDK/Desktop tool comparison](../../../apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts) runs without API credentials in `test:expected`, included in the required PR consumer job. It covers standard/PTC root sessions with Team disabled; Team parity is deferred to #7172. After building, run `CI=true pnpm run test:expected apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts`. Maintain exact, reasoned differences in the adjacent `tool-parity.ts`; resolved differences invalidate their exceptions. Existing SDK session snapshots and installed-runtime smokes independently check model output and packaging.
diff --git a/packages/bundle/sdk-app/README.zh.md b/packages/bundle/sdk-app/README.zh.md index 70523123d7..eee5f3522c 100644 --- a/packages/bundle/sdk-app/README.zh.md +++ b/packages/bundle/sdk-app/README.zh.md @@ -35,6 +35,8 @@ kind: "package-bundle" SDK 使用 base 默认提供的 `read`、`write` 和 `edit`。要添加 `str_replace_editor`,请使用 [base 配置指南](../base/README.zh.md#use-this-package)中的显式插入 patch。独立的 `sdk-minimal` profile 自行决定其工具选择。 +模型可以在 native 和 PTC 模式下使用 [`plugin_manager`](../../boot/plugin-manager/README.zh.md)。每个操作(包括列举)都要求完整权限或本次调用的批准。默认 workspace-write/ask 策略需要客户端审批应答方:启用 `approvalRequests`,并通过 `harness.client.onRequest()` 处理 `approval/request`,或在组合中提供审批器。没有应答方时,操作因 unavailable 被拒绝。Python 安装/移除包时,先显式调用 `download_primary_runtime()` 准备 Node 和 pnpm,再启动运行时;打包启动器会将它们提供给插件管理,无需系统 pnpm。未选择载荷时,包操作仍要求 `PATH` 中有 `pnpm`,或显式配置 `plugin-manager.pnpmCommand`。可运行的接入方式见[交互审批示例](../../../python/sdk/examples/manage_plugins.py)。保存的 profile 变更返回 `restart-required` 和 `no-hmr`;当前运行时及其会话保留原有工具,直到调用方关闭并重新启动运行时。通过 profile patch 设置 `tool-plugin-manager.disabled: true` 可隐藏此工具。独立的 `sdk-minimal` profile 不包含它。 + Python 运行时向本 profile 提供显式下载的创作资源和 Office sidecar。`DSH_PRIMARY_RUNTIME` 覆盖创作载荷;空值禁用其查询。Office skills 可独立使用任一种资源。Profile patch 可独立于 `workspace-dependencies` 禁用 `skill-office` 或替换其 `assetRoot`;同名文件系统 skills 优先。下载与配置见[运行时包](../../../python/sdk-runtime/README.zh.md)。 ----- @@ -46,15 +48,15 @@ Python 运行时向本 profile 提供显式下载的创作资源和 Office sidec #### 模型看到什么 -profile 继承 base 系统提示词,包括 `You are an AI agent powered by DeepSeek Harness.` 身份说明,并添加与 Web 和 headless profile 相同、按当前模型插值的 coding persona。每个 Session 通过 [`dsh-working-directory`](../../session/working-directory/README.zh.md) 提供的必需 user-role 上下文接收当前目录。默认文件工具 schema 包含 `read`、`write` 和 `edit`,不包含 `str_replace_editor`。模型还会收到 `present`、`ask_user_question`、定时任务工具、共用文件引用说明和时间上下文。子 agent 不能使用定时任务工具。[`time-context`](../../context/time-context/README.zh.md) 配置项接受回退时区。Skills 使用上述配置的资源。 +profile 继承 base 系统提示词,包括 `You are an AI agent powered by DeepSeek Harness.` 身份说明,并添加与 Web 和 headless profile 相同、按当前模型插值的 coding persona。每个 Session 通过 [`dsh-working-directory`](../../session/working-directory/README.zh.md) 提供的必需 user-role 上下文接收当前目录。默认文件工具 schema 包含 `read`、`write` 和 `edit`,不包含 `str_replace_editor`。模型还会收到 `present`、`ask_user_question`、`plugin_manager`、定时任务工具、共用文件引用说明和时间上下文。子 agent 不能使用定时任务工具。[`time-context`](../../context/time-context/README.zh.md) 配置项接受回退时区。Skills 使用上述配置的资源。 #### Token 影响 -此 profile 添加一句 coding persona、所挂载的工具定义与说明,以及记录在日志中的运行时上下文和时间消息。 +此 profile 添加一句 coding persona、所挂载的工具定义与说明,以及记录在日志中的运行时上下文和时间消息。 即使操作无法获批,`plugin_manager` 的描述和参数 schema 仍增加输入 token;不使用插件管理的嵌入方可禁用该条目。 #### KV Cache 影响 -对固定 profile、提供方、模型与工具清单,静态前缀保持稳定。运行时值追加到已记录的 user 上下文中。由于随附 SDK profile 使用仅启动时 patch,profile 变化会在下一个进程生效。 +启用 `plugin_manager` 会改变早期 SDK 版本的工具 schema 前缀。对固定 profile、提供方、模型与工具清单,静态前缀保持稳定。运行时值追加到已记录的 user 上下文中。由于随附 SDK profile 使用仅启动时 patch,profile 变化会在下一个进程生效。 ## 已知限制与延期工作 @@ -66,6 +68,7 @@ profile 继承 base 系统提示词,包括 `You are an AI agent powered by Dee - **定时任务依赖运行时生命周期**:投递需要运行中的进程及其持久化 Session 存储。 - **profile 可能省略 SDK server**:TypeScript client 选择的自定义 profile 必须保留本组合包或另一个 `dsh-sdk-jsonrpc-server` 配置项;没有 peer 响应时,client 初始化会失败。 - **用户插件可以破坏 stdout 纯净性**:profile 与逐次启动 patch 属于受信任应用组合。随附组合包不会向 stdout 写入非协议内容,但无法约束任意插入插件。 +- **插件变更共享 profile** — 保存的变更影响 `/profiles/sdk`,以及使用同一 home 的其他嵌入方的下次启动;独立组合应使用不同的 `dshHome` 目录。Python 启动器使用所选下载运行时中的 Node/pnpm;没有该载荷或外部 pnpm 时,包操作会失败。 - **配置变化需要重启**:`sdk-app` 组合包在 YAML 中禁用 HMR,因此一个 stdio 连接不会观察到 server 或 agent 依赖被替换。 @@ -75,6 +78,6 @@ profile 继承 base 系统提示词,包括 `You are an AI agent powered by Dee
维护者工作上下文——点击展开 -无。 +[SDK/Desktop 工具比较](../../../apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts) 在 `test:expected` 中无需 API 凭据运行,并纳入 PR 必需的 consumer 作业。检查覆盖关闭 Team 的 standard/PTC 主会话;Team 对齐暂由 #7172 跟踪。构建后运行 `CI=true pnpm run test:expected apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts`。在相邻的 `tool-parity.ts` 中维护精确、带理由的差异;差异消除后,对应例外会使检查失败。已有 SDK 会话快照和安装后运行时 smoke 分别检查模型输出和打包结果。
diff --git a/packages/bundle/sdk-app/cordis.patch.yml b/packages/bundle/sdk-app/cordis.patch.yml index afcbfd2c0d..15a5245ade 100644 --- a/packages/bundle/sdk-app/cordis.patch.yml +++ b/packages/bundle/sdk-app/cordis.patch.yml @@ -23,6 +23,9 @@ - id: hmr disabled: true +- id: tool-plugin-manager + disabled: false + # The packaged carrier supplies a default; DSH_PRIMARY_RUNTIME overrides it, # including an empty-string opt-out. Each row can be patched independently. - insert: diff --git a/packages/bundle/sdk-app/tests/sdk-app.spec.ts b/packages/bundle/sdk-app/tests/sdk-app.spec.ts index 2e040c2487..6ab9bd10ff 100644 --- a/packages/bundle/sdk-app/tests/sdk-app.spec.ts +++ b/packages/bundle/sdk-app/tests/sdk-app.spec.ts @@ -8,7 +8,7 @@ import { describe, expect, it } from 'vitest' import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' describe('dsh-sdk-app bundle', () => { - it('declares startup-gated JSON-RPC serving without overriding base HMR policy', () => { + it('enables plugin management while keeping JSON-RPC dependencies stable until restart', () => { const root = fileURLToPath(new URL('..', import.meta.url)) const manifest = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8')) as { dependencies?: Record @@ -21,6 +21,7 @@ describe('dsh-sdk-app bundle', () => { { schema: entryListSchema }, ) as Array<{ id?: string; disabled?: boolean; insert?: Array<{ id?: string; inject?: string[]; name?: string }> }> expect(patches.find(patch => patch.id === 'hmr')).toMatchObject({ disabled: true }) + expect(patches.find(patch => patch.id === 'tool-plugin-manager')).toMatchObject({ disabled: false }) expect(patches.find(patch => patch.id === 'session-title-llm')).toMatchObject({ disabled: true }) expect(patches.find(patch => patch.id === 'system-prompt')).toMatchObject({ config: { personaPrefix: 'You are a coding agent powered by the {{model}} model.' }, diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index c0ae7077d9..53d2b2971e 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -77,6 +77,10 @@ iconTimeoutMs: 10000 launchWatchMs: 1000 + - id: ui-file-actions + name: '@deepseek-ai/dsh-client-ui-file-actions' + - id: ui-context-menu + name: '@deepseek-ai/dsh-client-ui-context-menu' - id: ui-open-in-app name: '@deepseek-ai/dsh-client-ui-open-in-app' diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index 3a94c4aeda..9ecc295724 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -191,7 +191,9 @@ "@deepseek-ai/dsh-client-ui-settings-session-log": "workspace:*", "@deepseek-ai/dsh-harness-dev-context": "workspace:*", "@deepseek-ai/dsh-deliverable-file-references": "workspace:*", - "@deepseek-ai/dsh-client-ui-file-drag": "workspace:*" + "@deepseek-ai/dsh-client-ui-file-drag": "workspace:*", + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", + "@deepseek-ai/dsh-client-ui-file-actions": "workspace:*" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", diff --git a/packages/client/locale/tests/language-row.client.spec.tsx b/packages/client/locale/tests/language-row.client.spec.tsx index ecf23dd6e9..d94b2a195b 100644 --- a/packages/client/locale/tests/language-row.client.spec.tsx +++ b/packages/client/locale/tests/language-row.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' @@ -45,6 +46,7 @@ function mount(active = 'en') { usePanelInfo, useSessionRetainInfo: () => undefined, useResource, useWorkspaces: emptyWorkspaces(), ...allowAllAccess, + useContextMenu: contextMenuHook(), useStore: bindSnapshotSelector(store), actions: store.actions, t: (key: string) => key === 'language.title' ? 'Language' : key, diff --git a/packages/client/modules/src/client/entries.ts b/packages/client/modules/src/client/entries.ts index 587d3ffdd0..e33d0055f8 100644 --- a/packages/client/modules/src/client/entries.ts +++ b/packages/client/modules/src/client/entries.ts @@ -236,7 +236,8 @@ export class ClientEntries { } else if (entry.fiber === undefined) { await this.replace(entry, row.id, row.rev, generation) } else if (entry.fiber.state === FAILED) { - entry.fiber.update(entry.options.config) + // A retry with unchanged config is not a configuration change to persist. + await entry.fiber.update(entry.options.config, true) } } catch (error) { failures.push({ id: row.id, message: String(error) }) diff --git a/packages/client/tsdown.client.ts b/packages/client/tsdown.client.ts index ca7bbc4154..5f1cbd355e 100644 --- a/packages/client/tsdown.client.ts +++ b/packages/client/tsdown.client.ts @@ -82,7 +82,7 @@ function styleInjectionModule( * Everything else under @deepseek-ai/* is either a module-table entry * (external) or a leak the purity gate rejects. */ -export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|session|llm|tools|brand|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@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$)/ +export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|session|llm|tools|brand|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@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$)/ /** * Vendored framework libraries: rescoped into @deepseek-ai, so the gate below diff --git a/packages/client/ui-agent-preset/tests/create-plugin-menu-item.client.spec.tsx b/packages/client/ui-agent-preset/tests/create-plugin-menu-item.client.spec.tsx index 578234c898..83ea649c80 100644 --- a/packages/client/ui-agent-preset/tests/create-plugin-menu-item.client.spec.tsx +++ b/packages/client/ui-agent-preset/tests/create-plugin-menu-item.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import { useState, type ComponentProps } from 'react' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -30,6 +31,7 @@ function view(roster: Partial = {}, inMenu = false) { usePanelInfo: unusedHook, useSessions: unusedHook, useSessionStatus: unusedHook, useSessionRetainInfo: unusedHook, useWorkspaces: unusedHook, useResource: unusedHook, ...allowAllAccess, + useContextMenu: contextMenuHook(), load, startCreatorDraft, onDismiss, } function TestMenu() { diff --git a/packages/client/ui-agent-preset/tests/section.client.spec.tsx b/packages/client/ui-agent-preset/tests/section.client.spec.tsx index 1ea42a6af1..59f2bf5842 100644 --- a/packages/client/ui-agent-preset/tests/section.client.spec.tsx +++ b/packages/client/ui-agent-preset/tests/section.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' import { allowAllAccess, bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' @@ -24,6 +25,7 @@ function view(partial: Partial = {}, startCreatorDraft? usePanelInfo: unusedHook, useSessions: unusedHook, useSessionStatus: unusedHook, useSessionRetainInfo: unusedHook, useWorkspaces: unusedHook, useResource: unusedHook, ...allowAllAccess, + useContextMenu: contextMenuHook(), useAgentPresetSection: bindSnapshotSelector(store), useDeveloperTools: bindSnapshotSelector(developerTools), t: key => translations.get(key) ?? key } diff --git a/packages/client/ui-attachment/README.i18n.yaml b/packages/client/ui-attachment/README.i18n.yaml index 65b551434d..fe9e9182e5 100644 --- a/packages/client/ui-attachment/README.i18n.yaml +++ b/packages/client/ui-attachment/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-attachment/use-this-package: - en: df47b6abd789dcb5 - zh: 7e17c7f18631a572 + en: 02870b565a595b51 + zh: c31d02d76d78094b /deepseek-ai-dsh-client-ui-attachment/use-this-package/draft-attachments: en: 8246cb3c470e3fc5 zh: 7028cf466a832b99 @@ -30,8 +30,8 @@ en: 07204b7d538b7434 zh: 705cc6b0c9387cce /deepseek-ai-dsh-client-ui-attachment/further-exploration: - en: 733ac3e4df52d6e9 - zh: 98a6a8cac7d66645 + en: 661e8285abb71b5d + zh: 0c421325537cdcda /deepseek-ai-dsh-client-ui-attachment/model-experience: en: 25566605d7b38667 zh: 927d3ea272893296 diff --git a/packages/client/ui-attachment/README.md b/packages/client/ui-attachment/README.md index 29e7f3aba0..7b3158b50b 100644 --- a/packages/client/ui-attachment/README.md +++ b/packages/client/ui-attachment/README.md @@ -25,7 +25,7 @@ This package renders everything the conversation UI shows about attachments: one ## Use this package -Image drag actions and the composer’s original-file reader arrive through slot injection from [ui-file-drag](../ui-file-drag/README.md). The image gallery Factory also receives these actions through its declared inject face; custom Factory replacements must supply that face. +Image drag actions and the composer’s original-file reader arrive through slot injection from [ui-file-drag](../ui-file-drag/README.md). The image gallery Factory also receives these actions through its declared inject face; custom Factory replacements must supply that face. `MessageImage` and `ImageGallery` require the ordinary `getTriggerProps` factory; they bind each original image once and pass the same `contextMenuProps` to its thumbnail and lightbox. Mount this plugin alongside [`ui-conversation`](../ui-conversation/README.md) and [`ui-tool`](../ui-tool/README.md) when tool results need an image gallery. It waits for their slot declarations and registers its components into them. Users then see the mixed draft-attachment rail, DeepSeek Web file cards with upload controls, the drop overlay with its limits line, message images sized by count, the tool card's gallery, and the Escape/mask/close lightbox. @@ -82,6 +82,8 @@ Read these pages when the attachment surface is not enough. They move from the s ----- +Message images and original previews forward context gestures through the shared gallery to [ui-context-menu](../ui-context-menu/README.md). Original authorized URLs and MIME metadata remain independent from thumbnail presentation. + ## Model Experience diff --git a/packages/client/ui-attachment/README.zh.md b/packages/client/ui-attachment/README.zh.md index 80db6ae928..7391553fe2 100644 --- a/packages/client/ui-attachment/README.zh.md +++ b/packages/client/ui-attachment/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -图片拖放回调与输入框的原图读取回调通过 slot 注入从 [ui-file-drag](../ui-file-drag/README.zh.md) 获取。图片图库 Factory 也通过声明的注入接口接收回调;自定义 Factory 替换实现必须提供该接口。 +图片拖放回调与输入框的原图读取回调通过 slot 注入从 [ui-file-drag](../ui-file-drag/README.zh.md) 获取。图片图库 Factory 也通过声明的注入接口接收回调;自定义 Factory 替换实现必须提供该接口。 `MessageImage` 和 `ImageGallery` 必须接收普通 `getTriggerProps` 函数,每张原图绑定一次,将同一份 `contextMenuProps` 传给缩略图和灯箱。 与 [`ui-conversation`](../ui-conversation/README.zh.md) 一起挂载本插件,工具结果需要图片图库时也要挂载 [`ui-tool`](../ui-tool/README.zh.md)。插件等待这些 slot 的声明,并把组件注册进去。用户会看到混合草稿附件栏、带上传控件的 DeepSeek Web 文件卡、带限制说明的拖放遮罩、按数量定尺寸的消息图片、工具卡片图库,以及支持 Escape、遮罩和关闭按钮的灯箱。 @@ -82,6 +82,8 @@ Trajectory 附件行使用 48px 方形缩略图,完整缩放图片而不裁剪 ----- +消息图片和原图预览通过共享图片库将右键手势转发给 [ui-context-menu](../ui-context-menu/README.zh.md)。原始授权 URL 与 MIME 元数据独立于缩略图展示。 + ## 模型体验 diff --git a/packages/client/ui-attachment/package.json b/packages/client/ui-attachment/package.json index ed6496c2cf..2f5d2d5d93 100644 --- a/packages/client/ui-attachment/package.json +++ b/packages/client/ui-attachment/package.json @@ -35,7 +35,8 @@ "@deepseek-ai/dsh-client-ui-renderer", "@deepseek-ai/dsh-client-ui-trajectory", "@deepseek-ai/dsh-client-ui-tool", - "@deepseek-ai/dsh-client-ui-file-drag" + "@deepseek-ai/dsh-client-ui-file-drag", + "@deepseek-ai/dsh-client-ui-context-menu" ], "platform": "web" } @@ -60,7 +61,8 @@ "@deepseek-ai/dsh-client-ui-tool": "workspace:*", "clsx": "^2.0.0", "@deepseek-ai/dsh-client-ui-file-drag": "workspace:*", - "@deepseek-ai/dsh-util-file-drag": "workspace:*" + "@deepseek-ai/dsh-util-file-drag": "workspace:*", + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-attachment/src/MessageImage.tsx b/packages/client/ui-attachment/src/MessageImage.tsx index 5adcfb69a3..7afdb8b245 100644 --- a/packages/client/ui-attachment/src/MessageImage.tsx +++ b/packages/client/ui-attachment/src/MessageImage.tsx @@ -1,3 +1,4 @@ +import type { ContextMenuBindings } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { useCallback, useEffect, useMemo, useState } from 'react' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import { IconLoadingOutlineRegular, IconRefreshOutlineRegular, DraggableImage, ImageLightbox, type FileDragActions } from '@deepseek-ai/dsh-client-ui-primitives' @@ -67,12 +68,13 @@ function dimensionsOf(image: MessageImageSpec): { readonly width: number; readon * @param props.labels - resolved strings (tooltip, loading, retry, lightbox). * @returns the bounded thumbnail button, or the retry control on failure. */ -export function MessageImage({ image, load, variant, labels, fileDrag }: { +export function MessageImage({ image, load, variant, labels, fileDrag, getTriggerProps }: { image: MessageImageSpec load: ImageLoader variant: 'single' | 'tile' | 'thumbnail' fileDrag: FileDragActions labels: MessageImageLabels + getTriggerProps: ContextMenuBindings['getTriggerProps'] }) { const preview = 'preview' in image ? image.preview : undefined const attachment = 'attachment' in image ? image.attachment : undefined @@ -110,6 +112,9 @@ export function MessageImage({ image, load, variant, labels, fileDrag }: { const src = preview?.url ?? loaded const label = ('attachment' in image ? image.label : undefined) ?? preview?.name ?? attachment?.name ?? labels.image + const contextMenuProps = getTriggerProps(src === null ? undefined : { kind: 'image', value: { + url: src, name: label, ...(attachment === undefined ? {} : { mediaType: attachment.mediaType }), + } }) const loadingThumbnail = variant === 'thumbnail' && src === null if (error) return ( - {open && src !== null && } + {open && src !== null && } ) } /** Wrapping image group shared by user and assistant history: a lone image * renders large unless its owner requests compact tiles or contained list thumbnails. */ -export function ImageGallery({ images, load, align, compact = false, thumbnail = false, labels, fileDrag }: { +export function ImageGallery({ images, load, align, compact = false, thumbnail = false, labels, fileDrag, getTriggerProps }: { images: readonly MessageImageSpec[] load: ImageLoader align: 'start' | 'end' @@ -161,6 +168,7 @@ export function ImageGallery({ images, load, align, compact = false, thumbnail = thumbnail?: boolean fileDrag: FileDragActions labels: MessageImageLabels + getTriggerProps: ContextMenuBindings['getTriggerProps'] }) { if (images.length === 0) return null const variant = thumbnail ? 'thumbnail' : compact || images.length > 1 ? 'tile' : 'single' @@ -174,6 +182,7 @@ export function ImageGallery({ images, load, align, compact = false, thumbnail = variant={variant} fileDrag={fileDrag} labels={labels} + getTriggerProps={getTriggerProps} /> ))} diff --git a/packages/client/ui-attachment/src/client/MessageImages.tsx b/packages/client/ui-attachment/src/client/MessageImages.tsx index 0a95ddc66d..176940777f 100644 --- a/packages/client/ui-attachment/src/client/MessageImages.tsx +++ b/packages/client/ui-attachment/src/client/MessageImages.tsx @@ -12,11 +12,12 @@ type MessageImagesProps = MessageImagesOwnerProps & PropsRenderFactories * @param props - image sources, authorized loader, layout hints, optional labels, and Factory locale seat. * @returns the official gallery; no Session binding is needed by this component. */ -export function MessageImagesContent({ images, loadImage, align, compact = false, thumbnail = false, labels, t, fileDrag }: +export function MessageImagesContent({ images, loadImage, align, compact = false, thumbnail = false, labels, t, fileDrag, useContextMenu }: FactoryComponentPropsOf<'conversation.images.content'>) { + const { getTriggerProps } = useContextMenu() const resolved = useMemo(() => labels ?? messageImageLabels(t), [labels, t]) return + compact={compact} thumbnail={thumbnail} labels={resolved} fileDrag={fileDrag} getTriggerProps={getTriggerProps} /> } /** diff --git a/packages/client/ui-attachment/src/client/index.ts b/packages/client/ui-attachment/src/client/index.ts index 7ef44e1dd8..ef0f496a78 100644 --- a/packages/client/ui-attachment/src/client/index.ts +++ b/packages/client/ui-attachment/src/client/index.ts @@ -1,5 +1,7 @@ +import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Browser attachment plugin: composer entries and independently replaceable image galleries. */ import type { Context as ClientContext } from '@deepseek-ai/cordis' +import type { SlotFactoryMap } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-chat/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' @@ -9,6 +11,8 @@ import type {} from '@deepseek-ai/dsh-client-ui-file-drag/client' import { ComposerAttachments, type ComposerAttachmentsInjected } from './ComposerAttachments.tsx' import { MessageImages, MessageImagesContent } from './MessageImages.tsx' +type MessageImagesInjected = SlotFactoryMap['conversation.images.content']['inject'] + /** Slot registry required by the attachment presentation plugin. */ export const inject = ['slots', 'fileDrag'] @@ -19,7 +23,9 @@ export const inject = ['slots', 'fileDrag'] export function apply(ctx: ClientContext): void { ctx.slots.registerFactory({ name: 'conversation.images.content', scope: 'root', locale: 'conversation', - inject: () => ({ fileDrag: ctx.fileDrag.actions }), + inject: (): MessageImagesInjected => ({ + fileDrag: ctx.fileDrag.actions, + }), }, MessageImagesContent) ctx.slots.inject('conversation.input.attachments', () => ctx.slots.register({ name: 'conversation.input.attachments', diff --git a/packages/client/ui-attachment/tests/image-slot-isolation.client.spec.tsx b/packages/client/ui-attachment/tests/image-slot-isolation.client.spec.tsx index 09f0db62cb..98f3d923a3 100644 --- a/packages/client/ui-attachment/tests/image-slot-isolation.client.spec.tsx +++ b/packages/client/ui-attachment/tests/image-slot-isolation.client.spec.tsx @@ -1,6 +1,7 @@ // @vitest-environment jsdom /** Independent domain image positions with one shared official gallery Factory. */ import * as fileDragPlugin from '@deepseek-ai/dsh-client-ui-file-drag/client' +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import { act, cleanup, within } from '@testing-library/react' import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { AttachmentId } from '@deepseek-ai/dsh-attachment' @@ -29,6 +30,10 @@ async function bench() { runtime.slots.installLocale(locale) new UiConversation(runtime.ctx, runtime.sessions) await runtime.mount(fileDragPlugin) + runtime.ctx.provide('contextMenus', { open: vi.fn() } as never) + runtime.slots.provideRoot({ props: { + useContextMenu: contextMenuHook((target, point) => { runtime.ctx.contextMenus.open(target, point) }), + } }) await runtime.mount(attachmentPlugin) await runtime.sessions.add({ id: 'image-domains' }) const session = runtime.sessions.retainFor(runtime.ctx, SessionId('image-domains')) diff --git a/packages/client/ui-attachment/tests/message-image.client.spec.tsx b/packages/client/ui-attachment/tests/message-image.client.spec.tsx index dd6588f8bf..68cf23a7c8 100644 --- a/packages/client/ui-attachment/tests/message-image.client.spec.tsx +++ b/packages/client/ui-attachment/tests/message-image.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import { useState } from 'react' import type { PropsRenderFactories, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' @@ -39,7 +40,8 @@ describe('MessageImage', () => { const load = Object.assign(vi.fn(() => new Promise(() => {})), { peek: vi.fn(() => 'blob:seeded'), }) - const view = render() + const view = render() expect(view.queryByText('图片加载中…')).toBeNull() expect((view.getByAltText('history.png') as HTMLImageElement).src).toContain('blob:seeded') expect(load).toHaveBeenCalledWith(attachment) @@ -47,7 +49,8 @@ describe('MessageImage', () => { it('loads a Gateway-authorized URL, bounds the thumbnail, and clicks into the original', async () => { const load = vi.fn().mockResolvedValue('blob:history') - const view = render() + const view = render() const frame = view.getByRole('button', { name: 'history.png,点击查看原图' }) expect(frame.getAttribute('style')).toContain('width: 240px') expect(frame.getAttribute('style')).toContain('height: 120px') @@ -62,7 +65,8 @@ describe('MessageImage', () => { it('ignores a click while the thumbnail is still loading', () => { const load = vi.fn(() => new Promise(() => {})) - const view = render() + const view = render() const frame = view.getByRole('button', { name: 'history.png,点击查看原图' }) expect(view.getByText('图片加载中…')).toBeTruthy() fireEvent.click(frame) @@ -72,7 +76,8 @@ describe('MessageImage', () => { it('falls back to the image label for an unnamed attachment', async () => { const { name: _named, ...unnamed } = attachment const load = vi.fn().mockResolvedValue('blob:unnamed') - const view = render() + const view = render() await waitFor(() => { expect(view.getByAltText('图片')).toBeTruthy() }) expect(view.getByRole('button', { name: '图片,点击查看原图' })).toBeTruthy() }) @@ -82,7 +87,8 @@ describe('MessageImage', () => { .mockRejectedValueOnce(new Error('offline')) .mockRejectedValueOnce(new Error('still offline')) .mockResolvedValueOnce('blob:retry') - const view = render() + const view = render() const retry = await view.findByRole('button', { name: '图片加载失败,点击重试' }) fireEvent.click(retry) const retryAgain = await view.findByRole('button', { name: '图片加载失败,点击重试' }) @@ -94,7 +100,8 @@ describe('MessageImage', () => { it('clamps extreme aspect ratios and anchors the crop toward the informative edge', async () => { const load = vi.fn().mockResolvedValue('blob:ratio') const tall = render( - , + , ) const tallFrame = tall.getByRole('button', { name: 'history.png,点击查看原图' }) expect(tallFrame.getAttribute('style')).toContain('width: 60px') @@ -103,7 +110,8 @@ describe('MessageImage', () => { expect(tall.getByAltText('history.png').style.objectPosition).toBe('center top') tall.unmount() const wide = render( - , + , ) const wideFrame = wide.getByRole('button', { name: 'history.png,点击查看原图' }) expect(wideFrame.getAttribute('style')).toContain('width: 240px') @@ -112,7 +120,8 @@ describe('MessageImage', () => { expect(wide.getByAltText('history.png').style.objectPosition).toBe('left center') wide.unmount() const small = render( - , + , ) const smallFrame = small.getByRole('button', { name: 'history.png,点击查看原图' }) expect(smallFrame.getAttribute('style')).toContain('width: 100px') @@ -121,7 +130,8 @@ describe('MessageImage', () => { it('renders a tile at the fixed square without inline sizing', () => { const load = vi.fn(() => new Promise(() => {})) - const view = render() + const view = render() const frame = view.getByRole('button', { name: 'history.png,点击查看原图' }) expect(frame.getAttribute('data-variant')).toBe('tile') expect(frame.getAttribute('style')).toBeNull() @@ -129,7 +139,9 @@ describe('MessageImage', () => { it.each(['tile', 'thumbnail'] as const)('keeps the %s variant on the failed-load retry control', async (variant) => { const load = vi.fn().mockRejectedValue(new Error('offline')) - const view = render() + const view = render() const retry = await view.findByRole('button', { name: '图片加载失败,点击重试' }) expect(retry.getAttribute('data-variant')).toBe(variant) }) @@ -140,7 +152,8 @@ describe('MessageImage', () => { ] as const)('labels thumbnail status icons and retries a failed read in %s', async (_locale, statusLabels) => { const pending = Promise.withResolvers() const load = vi.fn().mockReturnValueOnce(pending.promise).mockResolvedValue('blob:retry') - const view = render() + const view = render() const loading = view.getByRole('button', { name: statusLabels.loading }) expect(loading.getAttribute('title')).toBe(statusLabels.loading) expect(loading.getAttribute('aria-busy')).toBe('true') @@ -164,7 +177,8 @@ describe('MessageImage', () => { it('uses the owner display name for an unnamed thumbnail and its original-image viewer', async () => { const { name: _name, ...unnamed } = attachment const load = vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValue('blob:thumbnail') - const view = render() + const view = render() fireEvent.click(await view.findByRole('button', { name: labels.loadFailed })) const image = await view.findByAltText('Image 2') expect(image.closest('button')?.getAttribute('data-variant')).toBe('thumbnail') @@ -182,13 +196,15 @@ describe('MessageImage', () => { it('ignores a load settling after unmount', async () => { let resolve: ((url: string) => void) | undefined const load = vi.fn(() => new Promise((r) => { resolve = r })) - const view = render() + const view = render() view.unmount() resolve?.('blob:late') await Promise.resolve() let reject: ((error: Error) => void) | undefined const failing = vi.fn(() => new Promise((_r, rej) => { reject = rej })) - const second = render() + const second = render() second.unmount() reject?.(new Error('late failure')) await Promise.resolve() @@ -199,7 +215,7 @@ describe('MessageImage preview arm', () => { it('displays a local preview immediately, without the loader, sized by its probed dimensions', () => { const load = vi.fn() const view = render( - { it('sizes an unprobed lone preview as a square crop and falls back to the image label', () => { const load = vi.fn() const view = render( - , + , ) const img = view.getByAltText('图片') as HTMLImageElement const frame = img.closest('button') as HTMLButtonElement @@ -227,7 +244,8 @@ describe('MessageImage preview arm', () => { it('opens the lightbox from a preview thumbnail', () => { const view = render( - '')} variant="tile" labels={labels} />, + '')} variant="tile" labels={labels} />, ) fireEvent.click(view.getByRole('button', { name: '图片,点击查看原图' })) expect(view.getByRole('dialog', { name: '原图预览' })).toBeTruthy() @@ -237,10 +255,11 @@ describe('MessageImage preview arm', () => { describe('ImageGallery', () => { it('renders nothing without images and an aligned wrapping group with them', async () => { const load = vi.fn().mockResolvedValue('blob:gallery') - const empty = render() + const empty = render() expect(empty.container.firstChild).toBeNull() const view = render( - { it('renders a lone image large and compact or grouped images as square tiles', () => { const load = vi.fn(() => new Promise(() => {})) - const lone = render() + const lone = render() expect(lone.container.querySelectorAll('[data-variant="single"]')).toHaveLength(1) lone.unmount() const compact = render( - , + , ) expect(compact.container.querySelectorAll('[data-variant="tile"]')).toHaveLength(1) compact.unmount() const several = render( - , + , ) expect(several.container.querySelectorAll('[data-variant="tile"]')).toHaveLength(3) }) @@ -277,6 +299,10 @@ describe('ImageGallery', () => { runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) runtime.ctx.provide('fileDrag', { actions: fileDrag, read: () => undefined }) + runtime.ctx.provide('contextMenus', { open: vi.fn() } as never) + runtime.slots.provideRoot({ props: { + useContextMenu: contextMenuHook((target, point) => { runtime.ctx.contextMenus.open(target, point) }), + } }) await runtime.mount(attachmentPlugin) const images = [{ preview: { url: 'blob:labels', name: 'preview.png' } }] const loadImage = vi.fn(async () => 'blob:unused') @@ -291,10 +317,14 @@ describe('ImageGallery', () => { }) const view = runtime.renderRoot() const image = view.getByAltText('preview.png') + fireEvent.contextMenu(image, { clientX: 7, clientY: 8 }) + expect(vi.spyOn(runtime.ctx.contextMenus, 'open')).toHaveBeenCalledWith({ kind: 'image', value: { url: 'blob:labels', name: 'preview.png' } }, { x: 7, y: 8 }) const frame = view.getByRole('button', { name: 'preview.png,点击查看原图' }) expect(frame.getAttribute('title')).toBe(labels.open) fireEvent.click(frame) expect(view.getByRole('dialog', { name: labels.lightbox.dialog })).toBeTruthy() + fireEvent.contextMenu(view.getByRole('dialog').querySelector('img')!, { clientX: 13, clientY: 14 }) + expect(vi.spyOn(runtime.ctx.contextMenus, 'open')).toHaveBeenLastCalledWith({ kind: 'image', value: { url: 'blob:labels', name: 'preview.png' } }, { x: 13, y: 14 }) fireEvent.click(view.getByRole('button', { name: labels.lightbox.close })) fireEvent.click(view.getByRole('button', { name: 'Default labels' })) const defaultFrame = view.getByRole('button', { name: 'preview.png, click to view original' }) @@ -318,6 +348,10 @@ describe('ImageGallery', () => { runtime.slots.installLocale(locale) await runtime.declare({ 'conversation.chat.message.images': { kind: 'single', scope: 'session' } }) runtime.ctx.provide('fileDrag', { actions: fileDrag, read: () => undefined }) + runtime.ctx.provide('contextMenus', { open: vi.fn() } as never) + runtime.slots.provideRoot({ props: { + useContextMenu: contextMenuHook((target, point) => { runtime.ctx.contextMenus.open(target, point) }), + } }) await runtime.mount(attachmentPlugin) await runtime.sessions.add({ id: 'message-images-test' }) const session = runtime.sessions.retainFor(runtime.ctx, SessionId('message-images-test')) @@ -330,6 +364,8 @@ describe('ImageGallery', () => { expect(view.getByRole('button', { name: 'history.png,点击查看原图' })).toBeTruthy() expect(container.querySelector('[data-align="end"]')).not.toBeNull() expect(loadImage).toHaveBeenCalledWith(attachment) + fireEvent.contextMenu(view.getByAltText('history.png'), { clientX: 9, clientY: 10 }) + expect(vi.spyOn(runtime.ctx.contextMenus, 'open')).toHaveBeenCalledWith({ kind: 'image', value: { url: 'blob:slot-image', name: 'history.png', mediaType: 'image/png' } }, { x: 9, y: 10 }) expect(view.getByRole('button', { name: 'history.png,点击查看原图' }).getAttribute('data-variant')).toBe('single') for (const [compact, thumbnail, variant] of [ [true, false, 'tile'], @@ -346,3 +382,16 @@ describe('ImageGallery', () => { }) const fileDrag = { prepare: vi.fn(async () => ({ start: () => true, release: () => {} })), reportFailure: vi.fn() } + +it('opens image menus from the thumbnail and lightbox using the original source', async () => { + const openImageMenu = vi.fn() + const view = render( 'blob:original')} + variant="single" labels={labels} />) + const image = await view.findByAltText('history.png') + fireEvent.contextMenu(image, { clientX: 18, clientY: 29 }) + expect(openImageMenu).toHaveBeenLastCalledWith({ kind: 'image', value: { url: 'blob:original', name: 'history.png', mediaType: attachment.mediaType } }, { x: 18, y: 29 }) + fireEvent.click(image) + fireEvent.contextMenu(view.getByRole('dialog').querySelector('img')!, { clientX: 31, clientY: 42 }) + expect(openImageMenu).toHaveBeenLastCalledWith({ kind: 'image', value: { url: 'blob:original', name: 'history.png', mediaType: attachment.mediaType } }, { x: 31, y: 42 }) +}) diff --git a/packages/client/ui-attachment/tests/plugin.client.spec.ts b/packages/client/ui-attachment/tests/plugin.client.spec.ts index a14099543e..706dc4531b 100644 --- a/packages/client/ui-attachment/tests/plugin.client.spec.ts +++ b/packages/client/ui-attachment/tests/plugin.client.spec.ts @@ -21,6 +21,7 @@ async function bench() { await ctx.fiber.dispose() }) ctx.provide('sessions', sessions) + ctx.provide('contextMenus', { open: vi.fn() } as never) ctx.provide('locale', new LocaleRuntime(ctx)) await ctx.plugin(SlotRegistry).await() ctx.slots.register({ @@ -33,11 +34,13 @@ async function bench() { 'tool.call.images': { kind: 'single', scope: 'session' }, }, } as never, () => null) - ctx.provide('fileDrag', { actions: fileDrag, read: () => undefined }) + const readFileDrag = vi.fn(() => undefined) + ctx.provide('fileDrag', { actions: fileDrag, read: readFileDrag }) + const register = vi.spyOn(ctx.slots, 'register') const registerFactory = vi.spyOn(ctx.slots, 'registerFactory') const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber.await() - return { ctx, fiber, registerFactory } + return { ctx, fiber, register, registerFactory, readFileDrag } } describe('attachment plugin', () => { @@ -46,7 +49,7 @@ describe('attachment plugin', () => { }) it('registers all entries and removes them with the plugin fiber', async () => { - const { ctx, fiber, registerFactory } = await bench() + const { ctx, fiber, register, registerFactory, readFileDrag } = await bench() expect(inject).toEqual(['slots', 'fileDrag']) expect(registerFactory.mock.calls[0]?.[0]).toMatchObject({ name: 'conversation.images.content', scope: 'root', locale: 'conversation', @@ -57,6 +60,10 @@ describe('attachment plugin', () => { expect(ctx.slots.entries('conversation.input.attachments')).toMatchObject([{ locale: 'conversation', component: ComposerAttachments, }]) + const composer = register.mock.calls.find(([options]) => options.name === 'conversation.input.attachments')! + const injectComposer = composer[0].inject as () => { readFileDrag: () => undefined } + injectComposer().readFileDrag() + expect(readFileDrag).toHaveBeenCalledOnce() for (const name of IMAGE_SLOTS) { expect(ctx.slots.entries(name)).toMatchObject([{ component: MessageImages, options: { priority: 100 } }]) } diff --git a/packages/client/ui-attachment/tsconfig.json b/packages/client/ui-attachment/tsconfig.json index 6d6e4792bc..853d6a70e2 100644 --- a/packages/client/ui-attachment/tsconfig.json +++ b/packages/client/ui-attachment/tsconfig.json @@ -43,6 +43,9 @@ }, { "path": "../../util/file-drag" + }, + { + "path": "../ui-context-menu" } ] } diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index f0c7f90fe8..ea9a48c09a 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -15,14 +15,14 @@ en: 41cd21266011d571 zh: 3172d1a2acbb27b7 /deepseek-ai-dsh-client-ui-chat/reference-previews: - en: 1333217883f84d52 - zh: 234a23bc2e793283 + en: 9386791a9e5efa00 + zh: 7cb9f3bbc42319d6 /deepseek-ai-dsh-client-ui-chat/hidden-chat-rows: en: cbf1f0a2205046a5 zh: 2e59d0815351349f /deepseek-ai-dsh-client-ui-chat/command-and-failure-rows: - en: 41dcd70e14ebe9cc - zh: ededead572b59037 + en: be90c24392fb021b + zh: 992b8745b385f9ab /deepseek-ai-dsh-client-ui-chat/turn-token-usage: en: cfdfe3d99d3f4e09 zh: 9330bad3d3f7a689 @@ -36,8 +36,8 @@ en: 3afad0b4c6bf9ce0 zh: d8179ba4ee9fcd61 /deepseek-ai-dsh-client-ui-chat/scroll-ownership: - en: 91e1f5f12ca51211 - zh: b92090966d58b82c + en: dd4e69828096c3a0 + zh: 2a9bc370f44efcd7 /deepseek-ai-dsh-client-ui-chat/model-experience: en: c17b4dd43a61c569 zh: f7414309810c3a08 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 97af0ab22b..99b01c5566 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -37,7 +37,7 @@ Image drag actions arrive through the image entry’s inject face from [ui-file- Sent generic-file attachments retain the draft's [file-card radius](../../../docs/ui-radius.md#radius-scale). -`ChatView` supplies file and HTTP(S) navigation through the existing `MarkdownDelegateProvider` around its node list, passing `requestOpenFile`, `openExternalLink`, and `fileImages` directly. Its file opener retains Chat's failure feedback and retry handling. Assistant Markdown file links open in the right Sidebar after the message settles, including references to unmodified files. Relative paths resolve in the viewed Session's workspace; absolute paths retain the same Session's filesystem access. `#L24` and `#L24-L30` navigate to the first specified line and reuse an existing file tab. Missing files show the preview's error state. +`ChatView` supplies file and HTTP(S) navigation through the existing `MarkdownDelegateProvider` around its node list, passing `requestOpenFile`, `openExternalLink`, and `fileImages` directly. Its file opener retains Chat's failure feedback and retry handling. Assistant Markdown file links open in the right Sidebar after the message settles, including references to unmodified files. Relative paths resolve in the viewed Session's workspace; absolute paths retain the same Session's filesystem access. [Supported Markdown line references](../ui-primitives/README.md#rendering-agent-output) navigate to the first specified line and reuse an existing file tab. Missing files show the preview's error state. Native message images use separate user and output positions. The `conversation.chat.user.content` Factory declares `conversation.chat.user.images`, which `UserContent` renders; the Assistant node registration declares `conversation.chat.message.images`, which `AssistantMarkdown` renders. Both receive image sources, the authorized `loadImage`, and layout options through explicit props. Their official `MessageImages` entries call the shared root-scoped `conversation.images.content` Factory. Each position can be replaced independently without duplicating the gallery implementation. @@ -63,6 +63,8 @@ When an Assistant attempt retires without a visible message, Chat hides its alre Generic command rows retain the ordinary command glyph in every lifecycle state; failure remains explicit through the row state and summary. Every terminal Turn failure renders its inline red-dot row; a quota failure's row states the neutral `message.failure.quota` copy instead of the provider message. The transient notice for a newly appended `QUOTA` or `ACCOUNT_QUOTA` comes from this package's frame-wide entry in `shell.overlay`, which outlives the Chat panel: it offers the one live notice to the `shell.quota-notice` chain and falls back to its own warning Toast, while an entry that claims the code replaces that fallback. Only Sessions this Client has bound and materialized publish; quota failures in Sessions it never opened do not. A newer notice replaces the current one unless a claiming entry retains it with `keepOpen()`: that call returns a release the caller owns and must run on unmount, any live hold keeps the claiming entry mounted and drops later notices, and releasing resumes later notices without replaying the dropped ones. The fallback Toast has no deferral of its own: while the Desktop account's opaque native Platform page covers the document, it still runs underneath and its display timer may elapse unseen, dismissing the notice itself, so only the persistent failure row remains. A release drops only its own hold, so one that runs after a dismissal or a newer hold leaves that newer hold intact. Dismissal and sign-out clear every hold, and dropped notices are not queued while their persistent failure rows still render. History replacement and pagination never publish a notice. Intermediate retries do not create a terminal row; output-token limits use the amber warning dot. A Turn that restart recovery closed as `interrupted` renders a localized stopped row stating that the DSH process exited mid-Turn, without a code chip, and its process summary reads Stopped. +Chat adapts Markdown targets at `MarkdownDelegateProvider.getTriggerProps`. The assistant-node Slot obtains `useContextMenu` directly and passes a file-path adapter to the optional mention service; intermediate flow and node owners carry no menu callbacks. Paths resolve against the originating Session’s current working directory when the gesture begins. Menus retain that captured path and line even if focus changes. Undeclared plugin links keep native behavior. + ----- @@ -184,6 +186,8 @@ The Chat view detects selection and context-menu gestures on business nodes mark `ctx.uiConversation.interactions` dispatches eligible gestures to plugin registrations and supplies their component to the Chat view. The action surface is absolutely positioned inside the existing Chat column, above the composer seat and its dock. Its wrapper preserves the component's outer stroke and shadow; components own internal scrolling. Scrolling the selection outside that visible region temporarily hides the surface; returning restores it. Chat owns viewport visibility, placement, outside pointer presses, Escape, new selections, source invalidation, and disposal; explicit dismissal preserves browser selection and layout changes do not reopen the surface. [Message quotes](../../session/message-quotes/README.md) owns quotation eligibility and insertion. +Markdown files, links, images, reference chips, and tool-file controls forward explicit right-click targets to [ui-context-menu](../ui-context-menu/README.md). File targets retain their working directory and line; ordinary link clicks retain the configured opening preference. + ## Model Experience diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 9dcd30137d..35231f8e5e 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -37,7 +37,7 @@ kind: "package-reference" 已发送的普通文件附件保留草稿中的[文件卡片圆角](../../../docs/ui-radius.zh.md#radius-scale)。 -`ChatView` 通过节点列表外围既有的 `MarkdownDelegateProvider` 提供文件及 HTTP(S) 导航,直接传入 `requestOpenFile`、`openExternalLink` 和 `fileImages`。文件打开动作保留 Chat 的失败反馈与重试处理。Assistant Markdown 文件链接在消息落定后可于右侧栏打开,包括未修改文件的引用。相对路径基于当前查看的 Session 工作区解析;绝对路径仍使用同一 Session 的文件系统访问。`#L24` 和 `#L24-L30` 定位到指定起始行,并复用现有文件标签。文件缺失时显示预览错误状态。 +`ChatView` 通过节点列表外围既有的 `MarkdownDelegateProvider` 提供文件及 HTTP(S) 导航,直接传入 `requestOpenFile`、`openExternalLink` 和 `fileImages`。文件打开动作保留 Chat 的失败反馈与重试处理。Assistant Markdown 文件链接在消息落定后可于右侧栏打开,包括未修改文件的引用。相对路径基于当前查看的 Session 工作区解析;绝对路径仍使用同一 Session 的文件系统访问。[支持的 Markdown 行号引用](../ui-primitives/README.zh.md#rendering-agent-output)定位到指定起始行,并复用现有文件标签。文件缺失时显示预览错误状态。 原生消息图片使用独立的用户与输出位置。`conversation.chat.user.content` Factory 声明 `conversation.chat.user.images`,由 `UserContent` 渲染;Assistant 节点注册声明 `conversation.chat.message.images`,由 `AssistantMarkdown` 渲染。两者通过显式 props 接收图片来源、授权 `loadImage` 和布局参数。官方 `MessageImages` 条目调用共享的 root 作用域 `conversation.images.content` Factory。每个位置均可独立替换,无需复制画廊实现。 @@ -63,6 +63,8 @@ Assistant 尝试结束且没有可见消息时,Chat 隐藏已发布的 Node, 通用指令行在所有生命周期状态中都保留普通指令图标;失败仍通过行状态与摘要表达。每个终止轮次都渲染自己的红点行;欠费失败的行使用中立的 `message.failure.quota` 文案,而不是提供方消息。新追加的 `QUOTA` 或 `ACCOUNT_QUOTA` 产生的瞬时提示来自本包注册在 `shell.overlay` 的全局条目,它不随 Chat 面板消失:该条目把唯一一条实时提示交给 `shell.quota-notice` 链,并在无人接管时回退到自己的警告 Toast,接管该错误码的条目会替换该回退。只有本 Client 已绑定并已物化的 Session 会发布提示;它从未打开的 Session 中的欠费不会发布。更新的提示会替换当前提示,除非认领条目用 `keepOpen()` 保持住当前提示:该调用返回一个由调用方持有、必须在卸载时调用的释放函数,只要存在保持,认领条目就继续挂载,后续提示被丢弃,释放后恢复后续提示但不重放已丢弃的提示。回退 Toast 自身没有延后策略:当 Desktop 账号的不透明原生 Platform 页盖住本页时,它仍会在下方运行,其显示计时器可能在不可见时走完并自行撤下提示,因此只留下持久化失败行。释放只移除自己的保持,因此它在关闭或更新的保持之后执行时不会影响更新的保持。关闭与退出登录会清空所有保持;被丢弃的提示不排队,其对应的持久化失败行仍会渲染。历史替换和分页不会发布提示。中间重试不会创建终止行;输出 token 上限使用琥珀色警告点。重启恢复以 `interrupted` 结束的轮次会渲染本地化的停止行,说明 DSH 进程在轮次中途退出,不显示代码标签,其过程摘要显示“已停止”。 +Chat 在 `MarkdownDelegateProvider.getTriggerProps` 接入处适配 Markdown 目标。助手节点 Slot 直接获取 `useContextMenu`,向可选的文件引用服务传入路径适配函数;消息流和节点中间层不再携带菜单回调。手势发生时按原始 Session 的当前工作目录解析路径,菜单保留捕获的路径和行号,不受焦点变化影响。未声明的插件链接保留原生行为。 + ----- @@ -184,6 +186,8 @@ Chat view 在标记了 `data-text-interaction-source` 的业务节点上检测 `ctx.uiConversation.interactions` 将有效手势分发给插件注册项,并把对应组件交给 Chat view。操作展示位置在已有 Chat 列内绝对定位,限制在 composer seat 及其 dock 上方。外层容器保留组件的外描边与阴影,内部滚动由组件负责。选区滚出该可见范围时暂时隐藏操作,滚回后恢复。Chat 负责视口可见性、定位、外部指针按下、Escape、新选区、来源失效与卸载清理;主动关闭保留浏览器选区,布局变化不会重新打开操作。[Message quotes](../../session/message-quotes/README.zh.md) 负责引用的接管条件和插入。 +Markdown 文件、链接、图片、引用 chip 和工具文件控件将明确的右键目标转发给 [ui-context-menu](../ui-context-menu/README.zh.md)。文件目标保留工作目录和行号;普通链接点击仍遵循配置的打开偏好。 + ## 模型体验 diff --git a/packages/client/ui-chat/package.json b/packages/client/ui-chat/package.json index 886912aa6c..c8a468b48c 100644 --- a/packages/client/ui-chat/package.json +++ b/packages/client/ui-chat/package.json @@ -42,7 +42,8 @@ "@deepseek-ai/dsh-client-ui-settings", "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-workspace", - "@deepseek-ai/dsh-client-ui-file-drag" + "@deepseek-ai/dsh-client-ui-file-drag", + "@deepseek-ai/dsh-client-ui-context-menu" ], "platform": "web" } @@ -97,7 +98,8 @@ "react-dom": "^18.2.0", "@deepseek-ai/dsh-settings": "workspace:*", "@deepseek-ai/dsh-client-product-analytics": "workspace:*", - "@deepseek-ai/dsh-client-ui-file-drag": "workspace:*" + "@deepseek-ai/dsh-client-ui-file-drag": "workspace:*", + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~" diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index fbabf95903..d3a6df8b96 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -1,3 +1,4 @@ +import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Register the Chat Conversation target, renderers, stats, and details surface. */ import type {} from '@deepseek-ai/dsh-client-ui-file-drag/client' import type {} from '@deepseek-ai/dsh-client-product-analytics/client' @@ -25,11 +26,12 @@ import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client' import type { ChatFlowDataInjected, ChatFlowInjected, ChatNodeInjected, ChatScrollPosition, ChatViewInjected, - QuotaNoticeInjected, QuotaNoticeState, TurnTailOwnerProps, + QuotaNoticeInjected, QuotaNoticeState, } from './contract/slots.ts' import type { ChatSnapshot } from './contract/snapshot.ts' import { EMPTY_CHAT_SNAPSHOT } from './contract/snapshot.ts' import { ApprovalCommand } from './chat/ApprovalCommand.tsx' +import { sessionFilePath } from './file-path.ts' import { ChatView } from './chat/ChatView.tsx' import { ChatFlow } from './chat/ChatFlow.tsx' import { registerChatNodeRenderers } from './chat/register-node-renderers.ts' @@ -253,7 +255,6 @@ export function apply(ctx: Context): void { fileDrag: ctx.fileDrag.actions, hooks: { presentation, interactionIds: ctx.uiConversation.interactions }, dispatchInteraction: gesture => ctx.uiConversation.interactions.dispatch(sessionId, gesture), - fileMentions: (owner: TurnTailOwnerProps) => ctx.get('chatFileMentions')?.forClosing(owner, sessionId), // Files open in the right Sidebar, not in a desktop application: the // content stays in the product, beside the conversation that produced // it. A relative path resolves from the Session's working directory @@ -276,6 +277,7 @@ export function apply(ctx: Context): void { else ctx.sidebarRight.openResource(url, { params: { line: options.line } }) await Promise.resolve() }, + resolveFilePath: sessionFilePath(ctx, sessionId), openExternalLink: (url) => { if (linkOpening.getSnapshot() === 'sidebar' && ctx.get('sidebarRightTabs')?.get('browser') !== undefined) { ctx.sidebarRight.openTab('browser', { params: { url } }) diff --git a/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx b/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx index 455f90f9a2..ad5963c093 100644 --- a/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx +++ b/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx @@ -1,16 +1,28 @@ import { memo, useCallback, useMemo } from 'react' import type { InjectFace, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' -import type { ChatNodeViewProps, PresentationInjected, TurnTailOwnerProps } from '../contract/slots.ts' +import type { ChatFileMentions, ChatNodeViewProps, PresentationInjected, TurnTailOwnerProps } from '../contract/slots.ts' import { AssistantMarkdown } from './AssistantMarkdown.tsx' -type AssistantNodeViewProps = ChatNodeViewProps<'assistant-step'> & InjectFace +/** Business readers owned by the assistant renderer's existing Slot registration. */ +export interface AssistantNodeInjected extends PresentationInjected { + /** Resolve against the live Session directory. @param path - Recorded path. @returns Host path. */ + resolveFilePath: (path: string) => string + /** Resolve closing-Turn mentions with the supplied ordinary file gesture callback. */ + fileMentions: (owner: TurnTailOwnerProps, getFileTriggerProps: NonNullable[2]>) => ReturnType +} + +type AssistantNodeViewProps = ChatNodeViewProps<'assistant-step'> & InjectFace & PropsRenderSlots<'conversation.chat.reasoning.body' | 'conversation.chat.message.images'> /** Streaming, settled, and interrupted Assistant states share one keyed renderer instance. */ export const AssistantNodeView = memo(function AssistantNodeView({ node, groupPart, useDisclosure, useGroupAction, useTurnData, turnProcess, openFile, loadImage, fileMentions, - usePresentation, renderSlot, t, + usePresentation, renderSlot, t, sessionId, useContextMenu, resolveFilePath, }: AssistantNodeViewProps) { + const { getTriggerProps } = useContextMenu() + const getFileTriggerProps = useCallback((path: string) => getTriggerProps(() => ({ + kind: 'file', value: { sessionId, path: resolveFilePath(path) }, + })), [getTriggerProps, sessionId, resolveFilePath]) const data = node.data const turn = node.location.kind === 'turn' || node.location.kind === 'step' ? node.location.turn @@ -22,8 +34,8 @@ export const AssistantNodeView = memo(function AssistantNodeView({ return { turn, seq: data.finalNode.seq, openFile } }, [data.finalNode, openFile, tail, turn]) const mentions = useMemo( - () => owner === undefined ? undefined : fileMentions(owner), - [fileMentions, owner], + () => owner === undefined ? undefined : fileMentions(owner, getFileTriggerProps), + [fileMentions, owner, getFileTriggerProps], ) const keepReplies = usePresentation(policy => policy.foldedReplies === 'all') // A kept reply row stays visible while the folded Turn hides its inline reasoning. diff --git a/packages/client/ui-chat/src/client/chat/ChatFlow.tsx b/packages/client/ui-chat/src/client/chat/ChatFlow.tsx index 86bcdaa542..d83a3043cc 100644 --- a/packages/client/ui-chat/src/client/chat/ChatFlow.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatFlow.tsx @@ -27,7 +27,7 @@ export const ChatFlow = memo(function ChatFlow({ entries, pendingInputs, lastInputTurn, deferCollapse, useSession, useChat, useChatNode, useChatNodeBottom, useChatNodeProcess, useChatGroup, usePresentation, useConnectionState, useStore, actions, renderSlot, renderFactorySlot, t, useGroupAction, useGroupHeaderAction, - cwd, openFile, inspectCall, forkAt, loadImage, fileMentions, + cwd, openFile, inspectCall, forkAt, loadImage, }: ChatFlowSlotProps) { const nodeStore = useChat(snapshot => snapshot.nodes) const running = useSession(snapshot => snapshot.running) @@ -47,7 +47,7 @@ export const ChatFlow = memo(function ChatFlow({ const seatProps = { nodeStore, useChatNode, useChatNodeBottom, useChatNodeProcess, usePresentation, useStore, actions, renderSlot, t, useGroupAction, deferCollapse, - cwd, openFile, inspectCall, forkAt, loadImage, fileMentions, + cwd, openFile, inspectCall, forkAt, loadImage, } const rows = entries.map((entry) => { switch (entry.kind) { diff --git a/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx b/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx index 6db2f75821..4efdb94142 100644 --- a/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx @@ -50,7 +50,7 @@ function turnOf(node: ChatNode | undefined): number | undefined { export const ChatNodeSeat = memo(function ChatNodeSeat({ nodeKey, groupPart, useChatNode, useChatNodeProcess, usePresentation, cwd, openFile, inspectCall, forkAt, - loadImage, fileMentions, useStore, actions, renderSlot, t, useChatNodeBottom, deferCollapse, useGroupAction, + loadImage, useStore, actions, renderSlot, t, useChatNodeBottom, deferCollapse, useGroupAction, }: ChatNodeSeatProps) { const bottom = useChatNodeBottom(nodeKey) const node = useChatNode(nodeKey) @@ -138,11 +138,10 @@ export const ChatNodeSeat = memo(function ChatNodeSeat({ inspectCall, forkAt, loadImage, - fileMentions, turnProcess, }, [ node, groupPart, cwd, openFile, inspectCall, forkAt, - loadImage, fileMentions, turnProcess, + loadImage, turnProcess, ]) if (routedNode === undefined || owner === null) return null // Runtime dispatch owns the correlation: every Node's discriminant is the diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index 703fe65449..e265ab635f 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx @@ -8,7 +8,7 @@ import type { import type { InboxState } from '@deepseek-ai/dsh-agent/types' import type { PendingSubmission } from '@deepseek-ai/dsh-api-session-controller/client' import { - Button, IconChevronDownOutlineRegular, MarkdownDelegateProvider, Modal, + Button, IconChevronDownOutlineRegular, MarkdownDelegateProvider, Modal, type MarkdownMenuTarget, } from '@deepseek-ai/dsh-client-ui-primitives' import { isAtOrOutside } from '../contract/group-tree.ts' import type { ChatFlowHookContext, ChatViewSlotProps, OpenFileOptions } from '../contract/slots.ts' @@ -60,9 +60,22 @@ const MOTION_TAIL_MS = 800 */ export function ChatView({ useSession, useChat, useConversation, useSessions, renderSlot, - sessionId, openFile, openExternalLink, loadOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, fileMentions, + sessionId, openFile, openExternalLink, resolveFilePath, useContextMenu, + loadOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, usePresentation, useProjection, useInteractionIds, dispatchInteraction, t, fileDrag, }: ChatViewSlotProps) { + const { getTriggerProps } = useContextMenu() + const getMarkdownTriggerProps = useCallback((target: MarkdownMenuTarget) => getTriggerProps(() => { + switch (target.kind) { + case 'file': return { kind: 'file', value: { sessionId, path: resolveFilePath(target.path), + ...(target.line === undefined ? {} : { line: target.line }) } } + case 'url': return { kind: 'url', value: { sessionId, url: target.url } } + case 'image': return { kind: 'image', value: { sessionId, url: target.url, + ...(target.name === undefined ? {} : { name: target.name }), + ...(target.mediaType === undefined ? {} : { mediaType: target.mediaType }), + ...(target.path === undefined ? {} : { path: resolveFilePath(target.path) }) } } + } + }), [getTriggerProps, resolveFilePath, sessionId]) const order = useChat(s => s.order) const groupedEntries = useConversation(snapshot => snapshot.views.grouped('chat')?.entries) const entries = useMemo(() => groupedEntries @@ -230,10 +243,15 @@ export function ChatView({ )} - + {renderSlot('conversation.chat.flow', { entries, pendingInputs, lastInputTurn, deferCollapse, - cwd, openFile: requestOpenFile, inspectCall, forkAt, loadImage, fileMentions, + cwd, openFile: requestOpenFile, inspectCall, forkAt, loadImage, }, { hookContext: flowContext })}
({ hooks: { presentation } }), + inject: (sessionId): AssistantNodeInjected => ({ + hooks: { presentation }, + resolveFilePath: sessionFilePath(ctx, sessionId), + fileMentions: (owner, getFileTriggerProps) => ctx.get('chatFileMentions')?.forClosing(owner, sessionId, getFileTriggerProps), + }), }, AssistantNodeView)) ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({ name: 'conversation.chat.node', diff --git a/packages/client/ui-chat/src/client/contract/slots.ts b/packages/client/ui-chat/src/client/contract/slots.ts index 96028b0ffd..9479bde696 100644 --- a/packages/client/ui-chat/src/client/contract/slots.ts +++ b/packages/client/ui-chat/src/client/contract/slots.ts @@ -17,7 +17,9 @@ import type { } from '@deepseek-ai/dsh-client-ui-slots' import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { ConnectionStateSource } from '@deepseek-ai/dsh-client-connection/client' -import type { MarkdownFileMentions, MarkdownLabels } from '@deepseek-ai/dsh-client-ui-primitives' +import type { FileDragActions, MarkdownFileMentions, MarkdownLabels } from '@deepseek-ai/dsh-client-ui-primitives' +import type { ContextMenuTriggerProps } from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type { ChatKey } from '../locale.ts' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' // Type-only: the Session-scope access Hook (`useAccess`) the Chat entries read. import type {} from '@deepseek-ai/dsh-client-ui-session/client' @@ -136,9 +138,12 @@ export interface ChatFileMentions { * Resolve prose links for one closing Turn. * @param owner - closing-Turn identity and file opener. * @param sessionId - viewed Session, including when history is inherited from a fork. + * @param getFileTriggerProps - ordinary gesture binding for a resolved file path. * @returns link resolver when available. */ - forClosing(owner: TurnTailOwnerProps, sessionId: SessionId): MarkdownFileMentions | undefined + forClosing( + owner: TurnTailOwnerProps, sessionId: SessionId, getFileTriggerProps?: (path: string) => ContextMenuTriggerProps, + ): MarkdownFileMentions | undefined } declare module '@deepseek-ai/cordis' { @@ -233,7 +238,6 @@ export interface ChatNodeOwnerProps { forkAt: (seq: number) => void /** Session-authorized image loader supplied by the Chat view. */ loadImage: MessageImageLoader - fileMentions: (owner: TurnTailOwnerProps) => MarkdownFileMentions | undefined /** Turn-process state when this Node belongs to a projected Turn. */ turnProcess?: TurnProcessOwnerProps | undefined } @@ -313,7 +317,9 @@ export interface PerformanceUsageInjected { /** Business callbacks injected into the Chat view. */ export interface ChatViewInjected { /** File preparation and failure callbacks owned by the file-drag plugin. */ - readonly fileDrag: import('@deepseek-ai/dsh-client-ui-primitives').FileDragActions + readonly fileDrag: FileDragActions + /** Resolve the reference against this Session and its current path base when the gesture begins. */ + resolveFilePath: (path: string) => string /** Dispatch one gesture to the Conversation plugin registry. */ dispatchInteraction: (gesture: TextInteractionGesture) => string | null hooks: { @@ -344,7 +350,6 @@ export interface ChatViewInjected { read: () => ChatScrollPosition | null } forkAt: (seq: number) => void - fileMentions: (owner: TurnTailOwnerProps) => MarkdownFileMentions | undefined } /** Session-owned node sources shared with the view, plus the flow's connection state. */ @@ -357,7 +362,7 @@ export type ChatFlowDataInjected = Pick & { /** Ordered rows and reconciled local echoes rendered inside one Chat viewport. */ export interface ChatFlowOwnerProps extends Pick { + 'cwd' | 'openFile' | 'inspectCall' | 'forkAt' | 'loadImage'> { readonly entries: readonly RenderEntry[] readonly pendingInputs: readonly (PendingSubmission | InboxState['next-step'][number])[] readonly lastInputTurn: number | undefined @@ -393,7 +398,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { /** Chat target, transcript node, statistics, and details copy. */ - chat: import('../locale.ts').ChatKey + chat: ChatKey } interface SlotFactoryMap { diff --git a/packages/client/ui-chat/src/client/file-path.ts b/packages/client/ui-chat/src/client/file-path.ts new file mode 100644 index 0000000000..9c23fdc21d --- /dev/null +++ b/packages/client/ui-chat/src/client/file-path.ts @@ -0,0 +1,19 @@ +/** Gesture-time path resolution for Chat-owned file references. */ +import type { Context } from '@deepseek-ai/cordis' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' +import type {} from '@deepseek-ai/dsh-api-session-controller/client' + +/** + * Bind path resolution to the originating Session without capturing its current directory. + * @param ctx - Chat plugin context. + * @param sessionId - Original Session identity. + * @returns Resolver using the live working directory, falling back to the workspace root. + */ +export function sessionFilePath(ctx: Context, sessionId: SessionId): (path: string) => string { + return (path) => { + const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + const current = ctx.sessions.binding(sessionId)?.session.projections.faceOf('workingDirectory').getSnapshot() as string | null | undefined + return resolveWorkspacePath(current ?? cwd, path) + } +} diff --git a/packages/client/ui-chat/src/client/index.ts b/packages/client/ui-chat/src/client/index.ts index e56a8e0a7a..c785329f0a 100644 --- a/packages/client/ui-chat/src/client/index.ts +++ b/packages/client/ui-chat/src/client/index.ts @@ -1,3 +1,4 @@ +import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Browser Chat target plugin. */ export { apply, inject } from './apply.ts' export type {} from './conversation-nodes/assistant.ts' diff --git a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx index 9687743249..8ee48b8f65 100644 --- a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx @@ -1,4 +1,6 @@ +import type { AssistantNodeInjected } from '../src/client/chat/AssistantNodeView.tsx' import { MessageId } from '@deepseek-ai/dsh-llm/brand' +import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' // @vitest-environment jsdom /** Chat inject factories exercised over independently mounted Conversation and Chat plugins. */ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -100,6 +102,8 @@ async function bench(initialSettings?: ChatSettings, withBrowserRegistry = true, const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) + runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) await runtime.root.declare({ 'main': { kind: 'keyed', scope: 'root' }, 'settings.general.item': { kind: 'list', scope: 'root' }, @@ -314,9 +318,15 @@ describe('Chat inject API', () => { it('resolves relative file paths against the Session\'s current working directory', async () => { const b = await bench() const { injected } = b.chatViewApi(b.rootReference) + vi.spyOn(b.runtime.ctx.contextMenus, 'open') await b.runtime.sessions.setProjection(ROOT, 'workingDirectory', '/proj/.agents/worktrees/w') await injected.openFile('src/a.ts') expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1/.agents/worktrees/w/src/a.ts') + expect(injected.resolveFilePath('src/a.ts')).toBe('/proj/.agents/worktrees/w/src/a.ts') + await b.runtime.sessions.setProjection(ROOT, 'workingDirectory', null) + expect(injected.resolveFilePath('file.ts')).toBe('/proj/file.ts') + await b.runtime.sessions.setProjection(ROOT, 'workingDirectory', '/proj/.agents/worktrees/w') + // A leading `./` names the same file, so the Sidebar reuses its tab. await injected.openFile('./src/a.ts') expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1/.agents/worktrees/w/src/a.ts') @@ -515,12 +525,16 @@ describe('Chat inject API', () => { expect(flow.injected.hooks.connectionState).toBe(b.runtime.ctx.get('connection')!.state) expect(flow.injected.hooks.presentation).toBe(injected.hooks.presentation) - expect(injected.fileMentions(owner)).toBeUndefined() + const entry = b.runtime.slots.entries('conversation.chat.node').find(entry => entry.options.key === 'assistant-step')! + const assistant = entry.inject!(ROOT as never) + const fileMentions = assistant.fileMentions as AssistantNodeInjected['fileMentions'] + const getFileTriggerProps = vi.fn(() => ({})) + expect(fileMentions(owner, getFileTriggerProps)).toBeUndefined() const mentions = { resolve: vi.fn() } as never const forClosing = vi.fn(() => mentions) b.runtime.ctx.provide('chatFileMentions', { forClosing } as never) - expect(injected.fileMentions(owner)).toBe(mentions) - expect(forClosing).toHaveBeenCalledWith(owner, ROOT) + expect(fileMentions(owner, getFileTriggerProps)).toBe(mentions) + expect(forClosing).toHaveBeenCalledWith(owner, ROOT, getFileTriggerProps) expect(injected.chatScroll.read()).toBeNull() const position = { anchorKey: 'node-1', anchorTop: 4, scrollTop: 12 } diff --git a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx index 066a441068..3e61dce8bf 100644 --- a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { describe, expect, it, onTestFinished, vi } from 'vitest' import { act, fireEvent, render } from '@testing-library/react' @@ -75,6 +76,8 @@ async function bench() { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) + runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) await runtime.root.declare({ 'main': { kind: 'keyed', scope: 'root' }, 'shell.overlay': { kind: 'list', scope: 'root' }, diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index 5f8de03ab8..2bc8286e93 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import type { ProcessGroupData } from '../src/client/contract/process-groups.ts' import type { InboxState } from '@deepseek-ai/dsh-agent/types' @@ -7,6 +8,7 @@ import type { GlobalStandardProps, PropsRenderFactories, PropsRenderSlots } from import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { useEffect, useMemo } from 'react' +import { useMarkdownDelegate, type MarkdownMenuTarget } from '@deepseek-ai/dsh-client-ui-primitives' import type { AssistantMessageNode, ChatFlowHookContext, ChatFlowOwnerProps, ChatFlowSlotProps, ChatNode, ChatNodeHookContext, ChatNodeOwnerProps, ChatSnapshot, UserBeforeOwnerProps, @@ -267,7 +269,7 @@ type ImageRenderer = (owner: MessageImagesOwnerProps) => React.ReactNode declare const userChainDispatch: PropsRenderSlots<'conversation.chat.user.before'>['renderSlotChain'] type UserChainRenderer = typeof userChainDispatch<'conversation.chat.user.before'> type UserChainState = { readonly renderer: UserChainRenderer | undefined } -type HarnessStandardProps = ChatViewSlotProps & PropsRenderFactories +type HarnessStandardProps = ChatViewSlotProps & PropsRenderFactories & Pick, 'fileMentions'> function isImageOwner(owner: object): owner is MessageImagesOwnerProps { return 'images' in owner && Array.isArray(owner.images) @@ -492,6 +494,7 @@ function makeHarness( const SessionProviderStub: ChatViewSlotProps['SessionProvider'] = ({ children }) => <>{children} const props: HarnessStandardProps = { fileDrag, + resolveFilePath: vi.fn((path: string) => path), renderFactorySlot, usePanelInfo: selector => selector({ activePanelId: null }), sessionId: SID, @@ -505,6 +508,7 @@ function makeHarness( useTrajectory: (() => { throw new Error('unused') }), useSessions: emptySessions(), useSessionRetainInfo: () => undefined, + useContextMenu: contextMenuHook(), useResource, useSessionStatus: bindSnapshotSelector( createSnapshotStore(new Map()), @@ -706,6 +710,41 @@ function formatRunDuration(ms: number, t: Parameters[1]): describe('Chat node rendering', () => { + it('adapts Markdown targets with the original Session and resolves file paths when each gesture begins', () => { + const h = makeHarness() + const opened = vi.fn() + let directory = '/workspace' + h.props.useContextMenu = contextMenuHook(opened) + h.props.resolveFilePath = path => `${directory}/${path}` + const targets: MarkdownMenuTarget[] = [ + { kind: 'file', path: 'src/a.ts', line: 24 }, + { kind: 'file', path: 'src/b.ts' }, + { kind: 'url', url: 'https://example.com/page' }, + { kind: 'image', url: 'blob:remote' }, + { kind: 'image', url: 'blob:local', path: 'image.svg', name: 'Image', mediaType: 'image/svg+xml' }, + ] + function References() { + const { getTriggerProps } = useMarkdownDelegate() + return <>{targets.map((target, index) => )} + } + const view = render( } />) + directory = '/workspace/moved' + for (const [index, target] of targets.entries()) { + const button = view.getByRole('button', { name: String(index) }) + button.getBoundingClientRect = () => new DOMRect(10, 20, 30, 40) + fireEvent.contextMenu(button, { clientX: 50, clientY: 60 }) + const { kind, ...value } = target + const expected = { kind, value: { + sessionId: SID, ...value, ...'path' in target ? { path: `${directory}/${target.path}` } : {}, + } } + expect(opened).toHaveBeenLastCalledWith(expected, { x: 50, y: 60 }) + fireEvent.keyDown(button, { key: 'F10', shiftKey: true }) + expect(opened).toHaveBeenLastCalledWith(expected, { x: 10, y: 60 }) + } + expect(opened).toHaveBeenCalledTimes(10) + expect(h.openFile).not.toHaveBeenCalled() + }) + it('opens Markdown references to unmodified files with line navigation', () => { const h = makeHarness({ nodes: [user(1, 'explain'), assistant(2, '[source](src/index.ts#L24-L30)', 1)], @@ -729,13 +768,18 @@ describe('Chat node rendering', () => { ], turnEnds: new Map([[1, 4]]), }) - h.props.fileMentions = owner => ({ + const opened = vi.fn() + let directory = '/workspace' + h.props.useContextMenu = contextMenuHook(opened) + h.props.resolveFilePath = path => `${directory}/${path}` + h.props.fileMentions = (owner, getFileTriggerProps) => ({ resolve: (value) => { if (value !== 'report.html') return undefined return { open: () => { void h.openFile(`for-seq-${String(owner.seq)}/site/report.html`) }, label: '打开 site/report.html', title: 'site/report.html', + contextMenuProps: getFileTriggerProps('site/report.html'), } }, }) @@ -746,6 +790,17 @@ describe('Chat node rendering', () => { expect(mentions).toHaveLength(1) const mention = view.getByRole('button', { name: '打开 site/report.html' }) expect(mention.getAttribute('title')).toBe('site/report.html') + fireEvent.contextMenu(mention, { clientX: 12, clientY: 34 }) + expect(opened).toHaveBeenLastCalledWith({ + kind: 'file', value: { sessionId: SID, path: '/workspace/site/report.html' }, + }, { x: 12, y: 34 }) + directory = '/workspace/moved' + fireEvent.keyDown(mention, { key: 'F10', shiftKey: true }) + expect(opened).toHaveBeenLastCalledWith({ + kind: 'file', value: { sessionId: SID, path: '/workspace/moved/site/report.html' }, + }, { x: 0, y: 0 }) + expect(opened).toHaveBeenCalledTimes(2) + expect(h.openFile).not.toHaveBeenCalled() fireEvent.click(mention) // The vocabulary was built from the closing message's own owner currency. expect(h.openFile).toHaveBeenCalledWith('for-seq-4/site/report.html') @@ -4699,3 +4754,21 @@ const fileDrag = { prepare: vi.fn(async () => ({ start: () => true, release: () it('formats Portuguese elapsed minutes with numeric units', () => { expect(formatRunDuration(90_000, key => pt[key])).toBe('1m 30s') }) + +it('does not infer menu targets from links or data attributes inside a plugin flow slot', () => { + const h = makeHarness() + const custom = vi.fn() + const view = render( <> + Plugin link + + + } />) + expect(fireEvent.contextMenu(view.getByRole('link', { name: 'Plugin link' }))).toBe(true) + expect(fireEvent.contextMenu(view.getByRole('button', { name: 'Undeclared file' }))).toBe(true) + fireEvent.contextMenu(view.getByRole('button', { name: 'Custom target' })) + expect(custom).toHaveBeenCalledOnce() + expect(h.props.resolveFilePath).not.toHaveBeenCalled() +}) diff --git a/packages/client/ui-chat/tests/config.host.spec.ts b/packages/client/ui-chat/tests/config.host.spec.ts index e3996ec43d..4cd8dd8651 100644 --- a/packages/client/ui-chat/tests/config.host.spec.ts +++ b/packages/client/ui-chat/tests/config.host.spec.ts @@ -57,15 +57,15 @@ describe('ui-chat Host settings', () => { it('validates folded replies and restores the saved choice', async () => { const ctx = new Context() const configuration = await liveConfig(ctx, { Config, apply }) - expect(plainConfig(configuration.fiber.config)).toMatchObject({ foldedReplies: 'all' }) + expect(plainConfig(configuration.fiber.effectiveConfig)).toMatchObject({ foldedReplies: 'all' }) await configuration.update({ foldedReplies: 'final' }) - const saved = plainConfig(configuration.fiber.config) + const saved = plainConfig(configuration.fiber.effectiveConfig) if (typeof saved !== 'object' || saved === null) throw new Error('expected saved configuration object') expect(saved).toMatchObject({ foldedReplies: 'final' }) await expect(configuration.update({ foldedReplies: 'none' })).rejects.toThrow() await configuration.fiber.dispose() const restored = await liveConfig(ctx, { Config, apply }, saved) - expect(plainConfig(restored.fiber.config)).toMatchObject({ foldedReplies: 'final' }) + expect(plainConfig(restored.fiber.effectiveConfig)).toMatchObject({ foldedReplies: 'final' }) await restored.fiber.dispose() }) diff --git a/packages/client/ui-chat/tests/context-menu.client.spec.tsx b/packages/client/ui-chat/tests/context-menu.client.spec.tsx new file mode 100644 index 0000000000..545538b18c --- /dev/null +++ b/packages/client/ui-chat/tests/context-menu.client.spec.tsx @@ -0,0 +1,29 @@ +// @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' +import { cleanup, fireEvent, render } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { MarkdownDelegateProvider, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives' + +afterEach(cleanup) + +it('leaves undeclared plugin links alone and binds only explicitly rendered Markdown targets', () => { + const open = vi.fn() + const custom = vi.fn() + const view = render( {}}> + Plugin link + + + ) + expect(fireEvent.contextMenu(view.getByRole('link', { name: 'Plugin link' }))).toBe(true) + expect(open).not.toHaveBeenCalled() + const file = view.getByRole('button', { name: 'File' }) + fireEvent.contextMenu(file, { clientX: 40, clientY: 50 }) + expect(open).toHaveBeenLastCalledWith({ kind: 'file', path: 'docs/file.ts', line: 42 }, { x: 40, y: 50 }) + file.getBoundingClientRect = () => new DOMRect(30, 40, 100, 20) + fireEvent.keyDown(file, { key: 'F10', shiftKey: true }) + expect(open).toHaveBeenLastCalledWith({ kind: 'file', path: 'docs/file.ts', line: 42 }, { x: 30, y: 60 }) + expect(document.activeElement).toBe(file) + fireEvent.contextMenu(view.getByRole('button', { name: 'Plugin target' }), { clientX: 70, clientY: 80 }) + expect(custom).toHaveBeenCalledExactlyOnceWith({ kind: 'pluginDocument', id: 'one' }, { x: 70, y: 80 }) + expect(open).toHaveBeenCalledTimes(2) +}) diff --git a/packages/client/ui-chat/tests/quota-notice.client.spec.tsx b/packages/client/ui-chat/tests/quota-notice.client.spec.tsx index c7f67f3505..5e0f5cd8e3 100644 --- a/packages/client/ui-chat/tests/quota-notice.client.spec.tsx +++ b/packages/client/ui-chat/tests/quota-notice.client.spec.tsx @@ -3,6 +3,7 @@ * that outlives the Chat panel, and history scrollback never does. */ // @vitest-environment jsdom +import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { afterEach, describe, expect, it } from 'vitest' import { act, screen } from '@testing-library/react' @@ -68,6 +69,8 @@ async function bench() { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) + runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) await runtime.declare({ 'shell.overlay': { kind: 'list', scope: 'root' }, 'conversation.approval.detail': { kind: 'single', scope: 'session' }, diff --git a/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx b/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx index f67f18eb92..ca6d67f0f3 100644 --- a/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx +++ b/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import { afterEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' @@ -50,6 +51,7 @@ function mount(mode: TranscriptViewMode = 'standard', dictionary: typeof en | ty useSessionRetainInfo: () => undefined, useResource, ...allowAllAccess, + useContextMenu: contextMenuHook(), useTranscriptView: bindSnapshotSelector(source), useCollapseTiming: bindSnapshotSelector(collapseTiming), useFoldedReplies: bindSnapshotSelector(foldedReplies), diff --git a/packages/client/ui-chat/tests/user-content.client.spec.tsx b/packages/client/ui-chat/tests/user-content.client.spec.tsx index 1a93864a41..38a786beee 100644 --- a/packages/client/ui-chat/tests/user-content.client.spec.tsx +++ b/packages/client/ui-chat/tests/user-content.client.spec.tsx @@ -1,3 +1,4 @@ +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' // @vitest-environment jsdom import { useState, type ReactNode } from 'react' import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' @@ -54,6 +55,7 @@ async function bench() { const openFile = vi.fn<(path: string) => void>() const openSkill = vi.fn<(name: string) => void>() await runtime.mount({ inject: ['slots'], apply: (ctx) => { + ctx.slots.provideRoot({ props: { useContextMenu: contextMenuHook() } }) const userText = new UserTextRegistry(ctx) for (const rule of [ sessionReferenceRule, fileReferenceRule, folderReferenceRule, skillReferenceRule, @@ -75,7 +77,7 @@ async function bench() { ctx.slots.register({ name: 'conversation.user.text.node', key: 'text' }, PlainUserText) ctx.slots.register({ name: 'conversation.user.text.node', key: 'session' }, SessionReference) ctx.slots.register({ name: 'conversation.user.text.node', key: 'file', locale: 'reference', - inject: () => ({ openFile }) }, FileReference) + inject: () => ({ openFile, resolveFilePath: path => path }) }, FileReference) ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder' }, FolderReference) ctx.slots.register({ name: 'conversation.user.text.node', key: 'skill', inject: () => ({ openSkill }) }, SkillReference) ctx.slots.inject('conversation.chat.user.images', () => ctx.slots.register({ name: 'conversation.chat.user.images' }, function ImageProbe(props) { diff --git a/packages/client/ui-chat/tsconfig.client.json b/packages/client/ui-chat/tsconfig.client.json index 42e4b6003c..4040aacd08 100644 --- a/packages/client/ui-chat/tsconfig.client.json +++ b/packages/client/ui-chat/tsconfig.client.json @@ -122,6 +122,9 @@ }, { "path": "../../core/tool-executor-ptc" + }, + { + "path": "../ui-context-menu" } ], "exclude": [ diff --git a/packages/client/ui-commands/README.i18n.yaml b/packages/client/ui-commands/README.i18n.yaml index eed1e982c7..c1b66eb439 100644 --- a/packages/client/ui-commands/README.i18n.yaml +++ b/packages/client/ui-commands/README.i18n.yaml @@ -27,8 +27,8 @@ en: 4feecdbec0c3f39e zh: 618944ecade8a3a2 /deepseek-ai-dsh-client-ui-commands/understand-the-implementation: - en: a44d56484412ac85 - zh: 6d6012485211908c + en: 99c9ca848b39d59e + zh: 24a5fa23e5b50797 /deepseek-ai-dsh-client-ui-commands/further-exploration: en: 409c04f534d23de7 zh: 165022d7a0a554eb diff --git a/packages/client/ui-commands/README.md b/packages/client/ui-commands/README.md index ef8781649e..709e6a13ff 100644 --- a/packages/client/ui-commands/README.md +++ b/packages/client/ui-commands/README.md @@ -55,7 +55,7 @@ Popup selection panels fill the composer overlay's width, matching the slash men
Implementation internals — click to expand -`src/client/contract.ts` defines contribution and decoration registration, plus `dismiss(name)`, which closes that command's open popups and confirmations: dismissal aborts pending option loads, prevents their late results from reopening the popup, and preserves composer drafts. `CommandDirectory` owns the per-session wire cache and resolves typed commands through `resolution.ts`; that module owns first-party identity matching and localized input spellings. `matchSpace` reads the ready cache synchronously, while `matchEnter` waits for readiness and rejects on warmup failure or cancellation. Forwarded catalog and connection events invalidate the cache. After a matched Host execution, this browser emits `command/executed`; other clients observe only the durable command events. `PopupSelectController` owns popup state, and `PopupSelectView` occupies the input overlay. `presentation.ts` owns row labels, icons, and sections; its helpers and the resolution helpers stay internal to the plugin. +`src/client/contract.ts` defines contribution and decoration registration, plus `dismiss(name)`, which closes that command's open popups and confirmations: dismissal aborts pending option loads, prevents their late results from reopening the popup, and preserves composer drafts. `CommandDirectory` owns the per-session wire cache and resolves typed commands through the shared [`dsh-commands/builtin`](../../interaction/commands/README.md) library. Client dictionaries reuse its English and Chinese tokens; `resolution.ts` selects the localized menu claim. `matchSpace` reads the ready cache synchronously, while `matchEnter` waits for readiness and rejects on warmup failure or cancellation. Forwarded catalog and connection events invalidate the cache. After a matched Host execution, this browser emits `command/executed`; other clients observe only the durable command events. `PopupSelectController` owns popup state, and `PopupSelectView` occupies the input overlay. `presentation.ts` owns row labels, icons, and sections; its helpers and the menu-claim helper stay internal to the plugin. Each command-directory fetch requires an existing retained Client Session and waits for its initial history open to succeed before sending `commands.list`. A temporary `commandCatalog` reference holds that Session until the fetch settles. An unretained Session or a failed open rejects without sending the RPC, so background catalog refreshes do not reopen closed Sessions. A reloaded draft that opens with a claimed command rebuilds the claim through the `matchClaim` hook, which awaits the same directory and answers only a `leadingInput` claim without invoking or executing anything. diff --git a/packages/client/ui-commands/README.zh.md b/packages/client/ui-commands/README.zh.md index 7ad5b4f9a1..2938f9c7d0 100644 --- a/packages/client/ui-commands/README.zh.md +++ b/packages/client/ui-commands/README.zh.md @@ -55,7 +55,7 @@ composer 携带图片或通用文件提交时,只有声明了 `input.attachmen
实现细节——点击展开 -`src/client/contract.ts` 定义贡献项和装饰的注册接口,以及 `dismiss(name)`:它关闭该命令已打开的弹窗与确认对话框,中止待完成的选项加载,阻止晚到结果重新打开弹窗,并保留 composer 草稿。`CommandDirectory` 负责会话级协议缓存,并通过 `resolution.ts` 解析输入命令;该模块负责内置命令标识匹配和本地化输入写法。`matchSpace` 同步读取就绪缓存,`matchEnter` 等待缓存就绪,预热失败或取消时拒绝。转发的目录和连接事件使缓存失效。宿主执行匹配的命令后,本浏览器发布 `command/executed`,其他客户端只观察持久命令事件。`PopupSelectController` 负责弹窗状态,`PopupSelectView` 占据输入浮层。`presentation.ts` 负责行标题、图标和分节,展示与解析辅助函数均留在插件内部。 +`src/client/contract.ts` 定义贡献项和装饰的注册接口,以及 `dismiss(name)`:它关闭该命令已打开的弹窗与确认对话框,中止待完成的选项加载,阻止晚到结果重新打开弹窗,并保留 composer 草稿。`CommandDirectory` 负责会话级协议缓存,并通过共享的 [`dsh-commands/builtin`](../../interaction/commands/README.zh.md) 库解析输入命令。Client 字典复用其中的中英文 token;`resolution.ts` 选择本地化的菜单输入写法。`matchSpace` 同步读取就绪缓存,`matchEnter` 等待缓存就绪,预热失败或取消时拒绝。转发的目录和连接事件使缓存失效。宿主执行匹配的命令后,本浏览器发布 `command/executed`,其他客户端只观察持久命令事件。`PopupSelectController` 负责弹窗状态,`PopupSelectView` 占据输入浮层。`presentation.ts` 负责行标题、图标和分节,展示与菜单输入辅助函数均留在插件内部。 每次命令目录拉取都要求客户端已持有该会话,并等待首次历史打开成功后才发送 `commands.list`。临时的 `commandCatalog` 引用持续持有会话,直到拉取结束。未被持有的会话或打开失败会直接拒绝,不发送 RPC,因此后台目录刷新不会重新打开已关闭的会话。刷新后以已认领命令开头的草稿经 `matchClaim` 钩子重建认领:它等待同一个目录就绪,只应答 `leadingInput` 认领,不调用也不执行任何东西。 diff --git a/packages/client/ui-commands/src/client/directory.ts b/packages/client/ui-commands/src/client/directory.ts index 524e0352b9..e0a15c54dc 100644 --- a/packages/client/ui-commands/src/client/directory.ts +++ b/packages/client/ui-commands/src/client/directory.ts @@ -7,7 +7,7 @@ */ import type { CommandDescriptor } from '@deepseek-ai/dsh-commands/types' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { resolveCommand } from './resolution.ts' +import { resolveCommand } from '@deepseek-ai/dsh-commands/builtin' export type { CommandDescriptor } from '@deepseek-ai/dsh-commands/types' diff --git a/packages/client/ui-commands/src/client/locales.ts b/packages/client/ui-commands/src/client/locales.ts index ae0517b5f4..a0c2f14012 100644 --- a/packages/client/ui-commands/src/client/locales.ts +++ b/packages/client/ui-commands/src/client/locales.ts @@ -5,6 +5,8 @@ * popupSelect shell's copy. */ +import { builtinCommandTokens } from '@deepseek-ai/dsh-commands/builtin' + /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { 'section.add': '添加', @@ -21,12 +23,12 @@ export const zh = { 'description.compact': '压缩以上对话内容', 'description.permission': '切换权限预设(沙箱模式与审批策略)', 'description.export': '将当前会话内容导出为 ZIP', - 'token.goal': '目标', - 'token.plan': '计划', - 'token.feedback': '反馈', - 'token.compact': '压缩', - 'token.permission': '权限', - 'token.export': '导出', + 'token.goal': builtinCommandTokens.zh.goal, + 'token.plan': builtinCommandTokens.zh.plan, + 'token.feedback': builtinCommandTokens.zh.feedback, + 'token.compact': builtinCommandTokens.zh.compact, + 'token.permission': builtinCommandTokens.zh.permission, + 'token.export': builtinCommandTokens.zh.export, 'search.placeholder': '搜索…', 'search.aria': '筛选选项', 'status.loading': '正在加载选项…', @@ -56,12 +58,12 @@ export const en = { 'description.compact': 'Compact older conversation history', 'description.permission': 'Switch the permission preset (sandbox mode + approval policy)', 'description.export': 'Download this Session log as a ZIP archive', - 'token.goal': 'goal', - 'token.plan': 'plan', - 'token.feedback': 'feedback', - 'token.compact': 'compact', - 'token.permission': 'permission', - 'token.export': 'export', + 'token.goal': builtinCommandTokens.en.goal, + 'token.plan': builtinCommandTokens.en.plan, + 'token.feedback': builtinCommandTokens.en.feedback, + 'token.compact': builtinCommandTokens.en.compact, + 'token.permission': builtinCommandTokens.en.permission, + 'token.export': builtinCommandTokens.en.export, 'search.placeholder': 'Search…', 'search.aria': 'Filter options', 'status.loading': 'Loading options…', diff --git a/packages/client/ui-commands/src/client/presentation.ts b/packages/client/ui-commands/src/client/presentation.ts index 32d03930b2..f5abacd2a4 100644 --- a/packages/client/ui-commands/src/client/presentation.ts +++ b/packages/client/ui-commands/src/client/presentation.ts @@ -9,8 +9,7 @@ import type { IconProps } from '@deepseek-ai/dsh-client-ui-primitives' import type { TranslateNS } from '@deepseek-ai/dsh-client-locale/client' import type { CommandDescriptor } from '@deepseek-ai/dsh-commands/types' import type { CommandKey } from './locales.ts' -import { builtinCommandName } from './resolution.ts' -import type { BuiltinCommandName } from './resolution.ts' +import { builtinCommandName, type BuiltinCommandName } from '@deepseek-ai/dsh-commands/builtin' /** The menu's two sections. */ export type MenuSection = 'add' | 'commands' diff --git a/packages/client/ui-commands/src/client/resolution.ts b/packages/client/ui-commands/src/client/resolution.ts index 7b4951cba3..1ee4af7473 100644 --- a/packages/client/ui-commands/src/client/resolution.ts +++ b/packages/client/ui-commands/src/client/resolution.ts @@ -1,29 +1,7 @@ /** Command identity and localized input spelling over the effective Host catalog. */ import type { CommandDescriptor } from '@deepseek-ai/dsh-commands/types' import type { TranslateNS } from '@deepseek-ai/dsh-client-locale/client' -import { en, zh } from './locales.ts' - -const BUILTINS = { - goal: '@deepseek-ai/dsh-command-goal', - plan: '@deepseek-ai/dsh-plan-mode', - feedback: '@deepseek-ai/dsh-command-feedback', - compact: '@deepseek-ai/dsh-command-compact', - permission: '@deepseek-ai/dsh-permission-presets', - export: '@deepseek-ai/dsh-session-log-export', -} as const - -/** Names whose first-party definitions have localized client presentation. */ -export type BuiltinCommandName = keyof typeof BUILTINS - -/** - * Identify a first-party definition without interpreting its display copy. - * @param descriptor - effective Host descriptor after scoped shadowing. - * @returns its first-party name, or undefined for another definition. - */ -export function builtinCommandName(descriptor: CommandDescriptor): BuiltinCommandName | undefined { - return (Object.keys(BUILTINS) as BuiltinCommandName[]) - .find(name => descriptor.definitionId === BUILTINS[name]) -} +import { builtinCommandName } from '@deepseek-ai/dsh-commands/builtin' /** * Select the input spelling for a menu-picked command. @@ -35,25 +13,3 @@ export function claimToken(descriptor: CommandDescriptor, t: TranslateNS<'comman const name = builtinCommandName(descriptor) return name === undefined ? descriptor.name : t(`token.${name}`) } - -const TOKEN_ALIASES = new Map( - (Object.keys(BUILTINS) as BuiltinCommandName[]).flatMap(name => - [zh[`token.${name}`], en[`token.${name}`]].map(token => [token, name] as const)), -) - -/** - * Resolve typed spelling against the current Session's effective definitions. - * @param token - typed name without its leading slash. - * @param descriptors - effective descriptors in the Session's ready catalog. - * @returns the matching descriptor; aliases never select an unrelated scoped override. - */ -export function resolveCommand( - token: string, - descriptors: readonly CommandDescriptor[], -): CommandDescriptor | undefined { - const exact = descriptors.find(descriptor => descriptor.name === token) - if (exact !== undefined) return exact - const name = TOKEN_ALIASES.get(token) - if (name === undefined) return undefined - return descriptors.find(descriptor => descriptor.definitionId === BUILTINS[name]) -} diff --git a/packages/client/ui-context-menu/README.i18n.yaml b/packages/client/ui-context-menu/README.i18n.yaml new file mode 100644 index 0000000000..1f54beccbb --- /dev/null +++ b/packages/client/ui-context-menu/README.i18n.yaml @@ -0,0 +1,40 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/client/ui-context-menu/README.md +/: + en: c7a386986f8aa0d7 + zh: a4bace64648d0a89 +/deepseek-ai-dsh-client-ui-context-menu: + en: f165f99dfbea7ed2 + zh: 0f2835e7726dd0f5 +/deepseek-ai-dsh-client-ui-context-menu/summary: + en: 7d22e21395a76909 + zh: e9f98068a4c5fde7 +/deepseek-ai-dsh-client-ui-context-menu/table-of-contents: + en: d152484eb41ac6b4 + zh: 725b47765ee8f30b +/deepseek-ai-dsh-client-ui-context-menu/use-this-package: + en: c84c65c7d24d51c3 + zh: 98c8f40a326a8f0b +/deepseek-ai-dsh-client-ui-context-menu/use-this-package/register-actions: + en: 11bea09005de2678 + zh: d56e25d2d93022aa +/deepseek-ai-dsh-client-ui-context-menu/understand-the-implementation: + en: 5b7717fad8457145 + zh: 19a06fca8060cf62 +/deepseek-ai-dsh-client-ui-context-menu/further-exploration: + en: 6d538e70a88f070b + zh: f90577fe9c8d1799 +/deepseek-ai-dsh-client-ui-context-menu/model-experience: + en: bb3787b3201a6724 + zh: e51cbb66f42a433d +/deepseek-ai-dsh-client-ui-context-menu/model-experience/kv-cache-effect: + en: e5fe67ca0631f67a + zh: b26e6107f2638589 +/deepseek-ai-dsh-client-ui-context-menu/known-limitations-and-deferred-work: + en: ac1e5554e7f3109f + zh: c2df38df3b9ea4f2 +/deepseek-ai-dsh-client-ui-context-menu/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: 6c5f9788c6536776 diff --git a/packages/client/ui-context-menu/README.md b/packages/client/ui-context-menu/README.md new file mode 100644 index 0000000000..dff6ea78cc --- /dev/null +++ b/packages/client/ui-context-menu/README.md @@ -0,0 +1,100 @@ +--- +description: "Add actions to right-click menus without importing a React component" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-context-menu + +English | [中文](README.zh.md) + +## Summary + +Add actions to right-click menus without importing a React component. Targets retain the clicked Session, Workspace, file, directory, URL, image, or pane even when selection changes. Contributions can discover metadata asynchronously and disappear safely when their plugin unloads. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +The Web application bundle mounts this Client plugin. External Client plugins declare the package in `dsh.client.inject`, import its `/client` types, and inject the `contextMenus` service. `resolutionTimeoutMs` bounds each provider’s preparation (1000ms by default); timed-out providers are aborted and omitted with visible failure feedback. + +The plugin injects `useContextMenu` into every Slot scope through `ctx.slots.provideRoot`. Call `const { getTriggerProps } = useContextMenu()` once in the component and spread `getTriggerProps(target, handlers?)` onto each trigger. The factory is an ordinary function and can run in loops. It handles right-click, Shift+F10, the ContextMenu key, viewport coordinates, and focus without scrolling. Existing handlers run first; `preventDefault()` keeps their ownership and prevents duplicate handling by composed or nested bindings. Repeated, composing, and unrelated key events remain untouched. Pass `undefined` to retain native behavior, or a target resolver to read business state when the gesture begins. The resolved object is captured before focus changes. Plain children receive event props or a factory through props or an existing delegate; no additional React Context is needed. Special editors and canvases can call `ctx.contextMenus.open()` directly. + +### Register actions + +Call `ctx.effect(() => ctx.contextMenus.register({ id, target, order, resolve }))` in the contributing plugin. `resolve` receives the captured target and its cancellation signal; return localized actions with stable IDs, optional icons, disabled state, submenus, and execution callbacks. Contributions sort by `order`, then ID. Duplicate contribution IDs within one target family fail registration; duplicate action paths reject that provider’s result. IDs are encoded by segment before publication. + +An action’s optional `commandId` associates it with an existing shortcut command. The overlay subscribes to `ctx.shortcuts.catalog`, including configured, removed, and reset bindings; nested and footer actions use the same presentation. This association never dispatches the command: selection invokes only the action’s captured `run` callback. The menu plugin requires the `shortcuts` service. + +A contribution can declare `observe(target)` sources for permissions, membership, or localized labels. Source updates re-resolve that contribution against the same captured target and replace its callbacks; outdated asynchronous preparations are cancelled. Dismissal and plugin unload release every subscription. + +Extend `ContextMenuTargetMap` through declaration merging on `@deepseek-ai/dsh-client-ui-context-menu/client` for a new target family; `ContextMenuTarget` derives the `{ kind, value }` union from that map. Open a target with `ctx.contextMenus.open(target, { x, y })`. Keep target values as immutable JSON-compatible identifiers and metadata. Execution callbacks capture that value; they must recheck mutable resources before acting. New registrations participate in the next opening. Unregistering removes visible actions and cancels pending metadata. + +`ctx.contextMenus.resolve(target)` gives a separate occurrence for another renderer. Subscribe to its immutable action views, select a published ID, and dispose it when its owner closes. Views contain presentation fields only. Callbacks remain in the registry and execute at most once. Dismissal and replacement cancel metadata, but an action already selected owns its own execution and cancellation. Rejected providers and actions produce a persistent overlay toast; an action’s localized `failureLabel` supplies operation-specific recovery guidance. + +`ctx.contextMenus.notify(text, success, action?)` can attach a localized text action through the shared Toast. The action provides `label`, `run`, and `failureLabel`; clicking dismisses the toast before execution, and rejection reports its failure label. A dismissed or replaced toast cannot execute its action again. + +Shared popups wait for every contribution to settle or time out before appearing. A repeated gesture within four CSS pixels closes the same target; a farther gesture replaces it with a separate fade. `ready` gives custom renderers the same preparation point. Structured action icons align within each divider group; component contributions retain their own layout. Normal dismissal retains the popup for 80ms, replacement for 10ms; opening waits at least 20ms and fades in over 40ms. Reduced motion suppresses the fade. + +Actions carry `icon?: { key: string; src?: string }`. Register the matching glyph component with `ctx.slots.inject('contextMenu.icon', () => ctx.slots.register({ name: 'contextMenu.icon', key: 'my-plugin.action' }, Icon))`. The overlay dispatches `renderSlot` by that key for ordinary, nested, and footer actions; the component receives the captured `icon` metadata, including an optional image URL. Registrations follow the contributing plugin and menu Slot declaration lifetimes. Action views contain no JSX nodes. + +The optional keyed `contextMenu.content` Slot hosts component contributions. Existing Session and tab Slot names remain owned by their feature adapters. Keyboard context keys and Shift+F10 use the focused trigger’s lower edge. `afterContent` places a data action after those rows; ordinary actions render before them. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The registry separates resolution and callback lifetimes from presentation. The shared overlay uses the existing Menu primitive for keyboard movement, focus return, dismissal, submenus, and viewport positioning. [Registry](src/client/registry.ts) owns cancellation and ordering; [target and action types](src/client/types.ts) own the public fields. + +
+ +----- + + +## Further Exploration + +- [Slots](../ui-slots/README.md) — component contributions. +- [File actions](../ui-file-actions/README.md) — original content transfer. +- [Open in app](../ui-open-in-app/README.md) — shipped resource actions. + +----- + + +## Model Experience + +None, as popup presentation and registration do not construct model input. + +#### KV Cache effect + +None; contributed feature actions own any subsequent model interaction. + +## Known Limitations and Deferred Work + + + +- The shipped renderer is the shared Web Menu, including inside Desktop. Native menu rendering is not supplied. +- Component-only legacy actions do not appear in the plain-data resolution API. +- Menus are window-local and transient; they are not persisted in Session data. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/client/ui-context-menu/README.zh.md b/packages/client/ui-context-menu/README.zh.md new file mode 100644 index 0000000000..78f154feae --- /dev/null +++ b/packages/client/ui-context-menu/README.zh.md @@ -0,0 +1,100 @@ +--- +description: "无需导入 React 组件即可向右键菜单添加操作" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-context-menu + +[English](README.md) | 中文 + +## 概述 + +无需导入 React 组件即可向右键菜单添加操作。即使选中项变化,目标仍保留被点击的会话、工作区、文件、文件夹、链接、图片或窗格。贡献项可以异步查询元数据,并在插件卸载时安全移除。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延后工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +Web 应用 bundle 挂载此客户端插件。外部客户端插件在 `dsh.client.inject` 声明本包,导入 `/client` 类型,并注入 `contextMenus` 服务。`resolutionTimeoutMs` 限制每个提供方的准备时长(默认 1000ms);超时后取消并忽略该提供方,显示失败提示。 + +插件通过 `ctx.slots.provideRoot` 向每个 Slot 作用域注入 `useContextMenu`。组件调用一次 `const { getTriggerProps } = useContextMenu()`,再将 `getTriggerProps(target, handlers?)` 展开到各个触发元素上。该工厂是普通函数,可以在循环中调用;它统一处理右键、Shift+F10、ContextMenu 键、视口坐标及无滚动聚焦。已有处理器先运行,`preventDefault()` 保留其处理权,并防止组合或嵌套绑定重复处理。重复、输入法组合及无关按键保持原状。传入 `undefined` 保留原生行为,也可传入目标解析函数,在手势开始时读取业务状态。解析后的对象会在焦点变化前捕获。普通子组件通过 props 或现有 delegate 接收事件 props 或工厂,无需额外 React Context。特殊编辑器和 Canvas 可直接调用 `ctx.contextMenus.open()`。 + +### 注册操作 + +在贡献插件中调用 `ctx.effect(() => ctx.contextMenus.register({ id, target, order, resolve }))`。`resolve` 接收捕获的目标和取消信号;返回本地化操作,包含稳定 ID、可选图标、禁用状态、子菜单和执行回调。贡献项先按 `order`、再按 ID 排序。同类目标的贡献 ID 重复会导致注册失败;操作路径重复会拒绝该提供方的结果。发布前会逐段编码 ID。 + +动作可通过可选 `commandId` 关联已有快捷键命令。浮层订阅 `ctx.shortcuts.catalog`,跟随已配置、移除和重置的绑定更新;子菜单和底部动作采用相同展示。此关联不会调度命令:选择菜单项只调用该动作捕获的 `run` 回调。菜单插件依赖 `shortcuts` 服务。 + +贡献可通过 `observe(target)` 声明权限、成员状态或本地化标签的数据源。数据源更新时,针对同一捕获目标重新解析该贡献并替换回调;过期的异步准备会被取消。关闭菜单和卸载插件都会释放所有订阅。 + +通过对 `@deepseek-ai/dsh-client-ui-context-menu/client` 的声明合并扩展 `ContextMenuTargetMap`,即可增加目标类别;`ContextMenuTarget` 从该映射派生 `{ kind, value }` 联合类型。通过 `ctx.contextMenus.open(target, { x, y })` 打开目标。目标值使用不可变、可 JSON 序列化的标识与元数据。执行回调捕获该值,并在操作前重新检查可变资源。新注册项在下次打开时生效。注销会移除可见操作并取消待处理的元数据查询。 + +`ctx.contextMenus.resolve(target)` 为其他渲染器提供独立菜单实例。订阅不可变操作视图,选择已发布的 ID,并在所属界面关闭时释放。视图仅包含展示字段。回调保留在注册表中,最多执行一次。关闭和替换菜单会取消元数据查询,已选中操作则自行管理执行与取消。提供方或操作拒绝时由持久的覆盖层提示;操作的本地化 `failureLabel` 提供具体的恢复建议。 + +`ctx.contextMenus.notify(text, success, action?)` 可通过共享 Toast 附加本地化文字操作。操作提供 `label`、`run` 和 `failureLabel`;点击后先关闭提示再执行,失败时显示对应文案。已关闭或被替换的提示不能再次执行其操作。 + +共享弹窗等待全部贡献项完成或超时后才显示。同一目标在四个 CSS 像素以内重复触发会关闭菜单;更远的触发以独立淡入淡出替换菜单。`ready` 向自定义渲染器提供同一个准备完成时点。结构化操作的图标按分隔线组对齐;组件贡献保留自己的布局。普通关闭保留弹窗 80ms,替换保留 10ms;打开至少等待 20ms,再用 40ms 淡入。减少动态效果偏好会禁用淡入淡出。 + +操作携带 `icon?: { key: string; src?: string }`。通过 `ctx.slots.inject('contextMenu.icon', () => ctx.slots.register({ name: 'contextMenu.icon', key: 'my-plugin.action' }, Icon))` 注册匹配的图标组件。覆盖层对普通项、子菜单和底部操作都按该 key 调用 `renderSlot`;组件接收已捕获的 `icon` 元数据,包括可选图片 URL。注册随贡献插件和菜单 Slot 声明的生命周期清理。操作视图不包含 JSX 节点。 + +可选的 keyed Slot `contextMenu.content` 承载组件贡献。现有会话和标签菜单 Slot 名称仍由各自功能适配器维护。键盘菜单键和 Shift+F10 使用焦点触发元素的下边缘定位。`afterContent` 将数据操作放在这些行之后;普通操作排在之前。 + +----- + + +## 理解实现 + +
+实现细节 — 点击展开 + +注册表将查询和回调生命周期与展示分离。共享覆盖层复用现有 Menu 原语,处理键盘移动、焦点返回、关闭、子菜单和视口定位。[注册表](src/client/registry.ts) 管理取消与排序;[目标和操作类型](src/client/types.ts) 定义公开字段。 + +
+ +----- + + +## 进一步探索 + +- [Slots](../ui-slots/README.zh.md) — 组件贡献。 +- [文件操作](../ui-file-actions/README.zh.md) — 原始内容传输。 +- [本地打开](../ui-open-in-app/README.zh.md) — 内置资源操作。 + +----- + + +## 模型体验 + +无,因为弹出菜单展示与注册不会构造模型输入。 + +#### KV 缓存影响 + +无;贡献操作所属功能负责后续可能产生的模型交互。 + +## 已知限制与延后工作 + + + +- 内置渲染器是共享 Web Menu,Desktop 也使用它;未提供原生菜单渲染器。 +- 仅有组件形式的旧操作不会出现在纯数据查询 API 中。 +- 菜单是窗口内的临时状态,不持久化到会话数据。 + + +### 开发备注 + +
+维护者工作背景 — 点击展开 + +无。 + +
diff --git a/packages/client/ui-context-menu/locale/de.json b/packages/client/ui-context-menu/locale/de.json new file mode 100644 index 0000000000..4b83ec446a --- /dev/null +++ b/packages/client/ui-context-menu/locale/de.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Kontextmenüs" + } +} diff --git a/packages/client/ui-context-menu/locale/en.json b/packages/client/ui-context-menu/locale/en.json new file mode 100644 index 0000000000..edcf35ac5e --- /dev/null +++ b/packages/client/ui-context-menu/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Context menus" + } +} diff --git a/packages/client/ui-context-menu/locale/es.json b/packages/client/ui-context-menu/locale/es.json new file mode 100644 index 0000000000..dda4ab5e04 --- /dev/null +++ b/packages/client/ui-context-menu/locale/es.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Menús contextuales" + } +} diff --git a/packages/client/ui-context-menu/locale/fr.json b/packages/client/ui-context-menu/locale/fr.json new file mode 100644 index 0000000000..6e41b74ead --- /dev/null +++ b/packages/client/ui-context-menu/locale/fr.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Menus contextuels" + } +} diff --git a/packages/client/ui-context-menu/locale/ja.json b/packages/client/ui-context-menu/locale/ja.json new file mode 100644 index 0000000000..7b98bda82b --- /dev/null +++ b/packages/client/ui-context-menu/locale/ja.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "コンテキストメニュー" + } +} diff --git a/packages/client/ui-context-menu/locale/pt.json b/packages/client/ui-context-menu/locale/pt.json new file mode 100644 index 0000000000..4a2c18368a --- /dev/null +++ b/packages/client/ui-context-menu/locale/pt.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Menus de contexto" + } +} diff --git a/packages/client/ui-context-menu/locale/ru.json b/packages/client/ui-context-menu/locale/ru.json new file mode 100644 index 0000000000..33b3ad67a4 --- /dev/null +++ b/packages/client/ui-context-menu/locale/ru.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Контекстные меню" + } +} diff --git a/packages/client/ui-context-menu/locale/zh.json b/packages/client/ui-context-menu/locale/zh.json new file mode 100644 index 0000000000..974fc94de9 --- /dev/null +++ b/packages/client/ui-context-menu/locale/zh.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "右键菜单" + } +} diff --git a/packages/client/ui-context-menu/package.json b/packages/client/ui-context-menu/package.json new file mode 100644 index 0000000000..6aacc8717f --- /dev/null +++ b/packages/client/ui-context-menu/package.json @@ -0,0 +1,70 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-context-menu", + "description": "Typed, plugin-extensible context menus with captured targets and shared Web presentation", + "version": "0.2.2-alpha.2", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/client/ui-context-menu" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" + }, + "dsh": { + "client": { + "inject": [ + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-layout", + "@deepseek-ai/dsh-client-shortcuts" + ], + "platform": "web" + } + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/schemastery": "workspace:~", + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-store": "workspace:*", + "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-layout": "workspace:*", + "@deepseek-ai/dsh-brand": "workspace:*", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-client-ui-dockkit": "workspace:*", + "@deepseek-ai/dsh-client-shortcuts": "workspace:*" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/client.js", + "lib/types/**/*.d.ts" + ] +} diff --git a/packages/client/ui-context-menu/src/client/View.tsx b/packages/client/ui-context-menu/src/client/View.tsx new file mode 100644 index 0000000000..58a9808f3a --- /dev/null +++ b/packages/client/ui-context-menu/src/client/View.tsx @@ -0,0 +1,60 @@ +/** Shared Web renderer for Client menu contributions. */ +import { Menu, Toast } from '@deepseek-ai/dsh-client-ui-primitives' +import type { MenuEntry } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsStore, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import type { Shortcuts, ShortcutCatalogEntry } from '@deepseek-ai/dsh-client-shortcuts/client' +import type { createMenuStore } from './store.ts' +import type { MenuActionView } from './types.ts' + +/** + * @param actions - plain presentation. + * @param catalog - effective user shortcuts. + * @param renderSlot - owner-authorized keyed icon renderer. + * @returns Existing Menu entries. + */ +export function menuEntries( + actions: readonly MenuActionView[], catalog: readonly ShortcutCatalogEntry[], + renderSlot: PropsRenderSlots<'contextMenu.icon'>['renderSlot'], +): MenuEntry[] { + return actions.flatMap((action) => { + const shortcut = catalog.find(entry => entry.id === action.commandId) + const item: MenuEntry = { id: action.id, label: action.label, + ...(shortcut === undefined ? {} : { shortcut }), + ...(action.disabled === undefined ? {} : { disabled: action.disabled }), + ...(action.danger === undefined ? {} : { danger: action.danger }), + ...(action.icon === undefined ? {} : { + icon: renderSlot('contextMenu.icon', { icon: action.icon }, { entryKey: action.icon.key }), + }), + ...(action.children === undefined ? {} : { submenu: menuEntries(action.children, catalog, renderSlot) }), + } + return action.separatorBefore ? [{ type: 'separator', id: `${action.id}:separator` }, item] : [item] + }) +} + +/** Shared overlay callbacks. */ +export interface MenuOverlayInjected { + hooks: { catalog: Shortcuts['catalog'] } + close: () => void + returnFocus?: () => HTMLElement | null + select: (id: string) => void +} +type Props = PropsStore> + & PropsRenderSlots<'contextMenu.content' | 'contextMenu.icon'> & InjectFace + +/** @param props - registered state, target-specific legacy rows, and actions. @returns one menu and persistent feedback. */ +export function MenuOverlay({ useStore, actions, renderSlot, close, select, returnFocus, useCatalog }: Props) { + const catalog = useCatalog(value => value) + const { target, point, items, notice, occurrence, closing, replacing } = useStore(s => s) + return <> + new DOMRect(point.x, point.y, 0, 0)} + items={menuEntries(items.filter(item => !item.afterContent), catalog, renderSlot)} + footer={menuEntries(items.filter(item => item.afterContent), catalog, renderSlot)} onClose={close} onSelect={select}> + {target !== null && renderSlot('contextMenu.content', { target, dismiss: close }, { entryKey: target.kind })} + + {notice !== null && { actions.notify(null) }} />} + +} diff --git a/packages/client/ui-context-menu/src/client/index.ts b/packages/client/ui-context-menu/src/client/index.ts new file mode 100644 index 0000000000..ac4fc288be --- /dev/null +++ b/packages/client/ui-context-menu/src/client/index.ts @@ -0,0 +1,155 @@ +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +/** Window-local menu capability and its Web overlay. */ +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-client-ui-layout/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import z from '@deepseek-ai/schemastery' +import { MENU_TRANSITION_MS } from '@deepseek-ai/dsh-client-ui-primitives' +import { menuTargetKey } from './target-key.ts' +import { MenuRegistry } from './registry.ts' +import { createMenuStore } from './store.ts' +import { dictionaries } from './locales.ts' +import { MenuOverlay } from './View.tsx' +import type { ContextMenus, MenuResolution, ContextMenuTarget, ContextMenuIcon, MenuPoint, UseContextMenu } from './types.ts' +import { createContextMenuBindings } from './trigger.ts' + +export type { ContextMenus, ContextMenuTarget, ContextMenuTargetMap, MenuPoint, MenuAction, MenuActionView, MenuContribution, MenuResolution } from './types.ts' +export type { ContextMenuBindings, ContextMenuTriggerProps, UseContextMenu } from './types.ts' +export type { ContextMenuIcon } from './types.ts' +export { createMenuStore } from './store.ts' + +declare module '@deepseek-ai/cordis' { + interface Context { /** Extensible context menus for explicit clicked objects. */ contextMenus: ContextMenus } +} +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface GlobalStandardProps { + /** Menu bindings for explicit objects, available in every Slot scope. */ + useContextMenu: UseContextMenu + } + interface SlotMap { + /** Business-owned glyph or image selected by the action's icon key. */ + 'contextMenu.icon': { kind: 'keyed'; scope: 'root'; inline: true; owner: { icon: ContextMenuIcon } } + /** Optional React rows for existing extension positions; data contributions need no renderer. */ + 'contextMenu.content': { kind: 'keyed'; scope: 'root'; owner: { target: ContextMenuTarget; dismiss: () => void } } + } + interface LocaleNamespaceMap { /** Menu operation feedback. */ contextMenu: 'failed' } +} + +/** Maximum time to prepare each contribution before omitting its pending actions. */ +export interface Config { resolutionTimeoutMs?: number } +/** Validated Client menu preparation budget. */ +export const Config: z = z.object({ resolutionTimeoutMs: z.natural().min(1).default(1000) }) + +/** Required overlay and localization services. */ +export const inject = ['slots', 'locale', 'shortcuts'] +/** @param ctx - plugin-owned Client context. @param config - validated preparation budget. */ +export function apply(ctx: Context, config: Config = Config({})): void { + ctx.effect(() => ctx.locale.register('contextMenu', dictionaries), 'context menu: locale') + const t = ctx.locale.bind('contextMenu') + const handle = createMenuStore() + const instance = handle.create() + const store: typeof handle = { ...handle, create: () => instance } + const targetSource = createSnapshotStore(null) + let sequence = 0 + let active: { resolution: MenuResolution; unsubscribe: () => void; target: ContextMenuTarget; point: MenuPoint } | undefined + let closeTimer: ReturnType | undefined + let openingTimer: ReturnType | undefined + let finishOpening: (() => void) | undefined + let returnFocus: HTMLElement | null = null + let disposed = false + const notify: ContextMenus['notify'] = (text, success = false, action) => { + if (disposed) return + const id = ++sequence + instance.actions.notify({ id, text, success, ...action === undefined ? {} : { action: { + label: action.label, + onClick: () => { + if (disposed || instance.getSnapshot().notice?.id !== id) return + instance.actions.notify(null) + try { void Promise.resolve(action.run()).catch(() => { notify(action.failureLabel) }) } + catch (_error) { notify(action.failureLabel) } + }, + } } }) + } + const registry = new MenuRegistry((message) => { notify(message ?? t('failed')) }, config.resolutionTimeoutMs) + const cancelOpening = (): void => { + clearTimeout(openingTimer); finishOpening?.(); finishOpening = undefined + active?.unsubscribe(); active?.resolution.dispose(); active = undefined + targetSource.set(null) + } + const dismiss = (replacing: boolean): void => { + cancelOpening() + clearTimeout(closeTimer) + if (instance.getSnapshot().target === null) return + instance.actions.exit(replacing) + closeTimer = setTimeout(() => { instance.actions.close() }, replacing ? MENU_TRANSITION_MS.replace : MENU_TRANSITION_MS.dismiss) + } + const close = (): void => { dismiss(false) } + const contextMenus: ContextMenus = { + active: targetSource, + register: input => registry.register(input), resolve: target => registry.resolve(target), notify, close, + open: (target, point) => { + const previous = active + if (previous !== undefined + && Math.hypot(previous.point.x - point.x, previous.point.y - point.y) <= 4 + && menuTargetKey(previous.target) === menuTargetKey(target)) { close(); return } + const focused = document.activeElement + if (!(focused instanceof Element) || focused.closest('[data-context-menu]') === null) { + returnFocus = focused instanceof HTMLElement ? focused : null + } + dismiss(true) + const resolution = registry.resolve(target) + targetSource.set(target) + let displayed = false + const publish = (): void => { if (displayed) instance.actions.items(resolution.source.getSnapshot()) } + const occurrence = { resolution, unsubscribe: resolution.source.subscribe(publish), target, point } + active = occurrence + const delay = new Promise((resolve) => { + finishOpening = resolve; openingTimer = setTimeout(resolve, MENU_TRANSITION_MS.prepare) + }) + void Promise.all([resolution.ready, delay]).then(() => { + if (active !== occurrence) return + clearTimeout(closeTimer) + instance.actions.open(target, point) + displayed = true + publish() + }) + }, + } + ctx.provide('contextMenus', contextMenus) + const bindings = createContextMenuBindings((target, point) => { contextMenus.open(target, point) }, () => !disposed) + ctx.slots.provideRoot({ props: { useContextMenu: () => bindings } }) + ctx.effect(() => { + const outside = (event: PointerEvent): void => { + if (event.button === 2 || (event.target instanceof Element && event.target.closest('[role="menu"], [data-context-menu-trigger]'))) return + close() + } + const context = (event: MouseEvent): void => { if (!event.defaultPrevented) close() } + const escape = (event: KeyboardEvent): void => { + if (active !== undefined && instance.getSnapshot().target === null && event.key === 'Escape') { + event.preventDefault(); event.stopImmediatePropagation(); close() + } + } + document.addEventListener('pointerdown', outside) + document.addEventListener('contextmenu', context) + window.addEventListener('keydown', escape, true) + return () => { + disposed = true; cancelOpening(); clearTimeout(closeTimer); registry.dispose(); instance.actions.close() + document.removeEventListener('pointerdown', outside) + document.removeEventListener('contextmenu', context) + window.removeEventListener('keydown', escape, true) + } + }, 'context menu: lifetime') + ctx.slots.inject('shell.overlay', () => ctx.slots.register({ + name: 'shell.overlay', id: 'context-menu', store, + children: { + 'contextMenu.content': { kind: 'keyed', scope: 'root' }, + 'contextMenu.icon': { kind: 'keyed', scope: 'root', inline: true }, + }, + inject: () => ({ hooks: { catalog: ctx.shortcuts.catalog }, close, returnFocus: () => returnFocus, select: (id: string) => { + const selected = active?.resolution + active?.unsubscribe(); active = undefined + targetSource.set(null); dismiss(false) + selected?.select(id); selected?.dispose() } }), + }, MenuOverlay)) +} diff --git a/packages/client/ui-context-menu/src/client/locales.ts b/packages/client/ui-context-menu/src/client/locales.ts new file mode 100644 index 0000000000..d8b33a422e --- /dev/null +++ b/packages/client/ui-context-menu/src/client/locales.ts @@ -0,0 +1,11 @@ +/** Context-menu operation feedback, separate from plugin display metadata. */ +export const dictionaries = { + zh: { failed: '操作失败,请重试' }, + en: { failed: 'Could not complete the action. Try again.' }, + ja: { failed: '操作に失敗しました。再試行してください。' }, + es: { failed: 'No se pudo completar la acción. Inténtelo de nuevo.' }, + fr: { failed: 'Impossible de terminer l’action. Réessayez.' }, + de: { failed: 'Die Aktion konnte nicht abgeschlossen werden. Versuchen Sie es erneut.' }, + ru: { failed: 'Не удалось выполнить действие. Повторите попытку.' }, + pt: { failed: 'Não foi possível concluir a ação. Tente novamente.' }, +} satisfies Record diff --git a/packages/client/ui-context-menu/src/client/registry.ts b/packages/client/ui-context-menu/src/client/registry.ts new file mode 100644 index 0000000000..3725bb9fed --- /dev/null +++ b/packages/client/ui-context-menu/src/client/registry.ts @@ -0,0 +1,160 @@ +/** Ordered menu resolution with cancellation and contribution-owned action lifetimes. */ +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { MenuAction, MenuActionView, MenuContribution, MenuResolution, ContextMenuTarget, ContextMenuTargetMap } from './types.ts' + +interface Provider { + readonly id: string + readonly order: number + readonly kind: keyof ContextMenuTargetMap + readonly lifetime: AbortController + observe(target: ContextMenuTarget): readonly ObservableSnapshot[] + resolve(target: ContextMenuTarget, signal: AbortSignal): readonly MenuAction[] | Promise +} + +/** React-free registry; each occurrence captures the providers registered at opening. */ +export class MenuRegistry { + private readonly providers = new Map() + private readonly occurrences = new Set<() => void>() + private disposed = false + constructor(private readonly failed: (message?: string) => void, private readonly timeoutMs?: number) {} + + /** + * Register actions for subsequent openings. + * @param input - provider definition. + * @returns removal of this contribution and its pending resolutions. + */ + register(input: MenuContribution): () => void { + if (this.disposed) throw new Error('Menu registry is disposed') + const key = `${encodeURIComponent(input.target)}/${encodeURIComponent(input.id)}` + if (this.providers.has(key)) throw new Error(`Duplicate menu contribution: ${key}`) + const provider: Provider = { + id: input.id, kind: input.target, order: input.order, lifetime: new AbortController(), + observe: target => input.observe?.(target.value as ContextMenuTargetMap[K]) ?? [], + resolve: (target, signal) => input.resolve(target.value as ContextMenuTargetMap[K], signal), + } + this.providers.set(key, provider) + return () => { + if (provider.lifetime.signal.aborted) return + this.providers.delete(key) + provider.lifetime.abort() + } + } + + /** + * Resolve an independently owned occurrence. + * @param target - captured clicked identity. + * @returns presentation, selection, and disposal. + */ + resolve(target: ContextMenuTarget): MenuResolution { + if (this.disposed) throw new Error('Menu registry is disposed') + const lifetime = new AbortController() + const source = createSnapshotStore([]) + const resolved = new Map() + const callbacks = new Map() + const providers = [...this.providers.values()].filter(p => p.kind === target.kind) + .sort((a, b) => a.order - b.order || a.id.localeCompare(b.id)) + const refresh = (): void => { + source.set(providers.flatMap(provider => + provider.lifetime.signal.aborted ? [] : resolved.get(provider) ?? [])) + } + const cleanup: (() => void)[] = [] + const dispose = (): void => { + if (lifetime.signal.aborted) return + lifetime.abort() + for (const detach of cleanup) detach() + callbacks.clear() + this.occurrences.delete(dispose) + } + this.occurrences.add(dispose) + const pending: Promise[] = [] + for (const provider of providers) { + let preparation: AbortController | undefined + let actionIds: string[] = [] + let preparing: Promise | undefined + const clear = (): void => { + for (const id of actionIds) callbacks.delete(id) + actionIds = [] + resolved.delete(provider) + refresh() + } + const prepare = (): void => { + preparation?.abort() + const deadline = new AbortController() + preparation = deadline + const signal = AbortSignal.any([lifetime.signal, provider.lifetime.signal, deadline.signal]) + const accept = (actions: readonly MenuAction[]): void => { + if (signal.aborted) return + const next = new Map() + const project = (action: MenuAction, parent: string): MenuActionView => { + const id = `${parent}/${encodeURIComponent(action.id)}` + if (next.has(id)) throw new Error(`Duplicate menu action: ${id}`) + next.set(id, action) + const { run: _run, failureLabel: _failureLabel, children, ...view } = action + return { ...view, id, ...(children === undefined ? {} : { children: children.map(child => project(child, id)) }) } + } + const views = actions.map(action => project(action, encodeURIComponent(provider.id))) + for (const id of actionIds) callbacks.delete(id) + for (const [id, action] of next) callbacks.set(id, { provider, action }) + actionIds = [...next.keys()] + resolved.set(provider, views) + refresh() + } + preparing = undefined + try { + const result = provider.resolve(target, signal) + if (result instanceof Promise) clear() + preparing = result instanceof Promise ? new Promise((settle) => { + const timer = this.timeoutMs === undefined ? undefined : setTimeout(() => { + deadline.abort(); this.failed() + }, this.timeoutMs) + const finish = (): void => { clearTimeout(timer); signal.removeEventListener('abort', finish); settle() } + signal.addEventListener('abort', finish, { once: true }) + void result.then(accept).catch(() => { if (!signal.aborted) this.failed() }).finally(finish) + }) : undefined + if (!(result instanceof Promise)) accept(result) + } catch (_error) { if (!signal.aborted) { clear(); this.failed() } } + } + const subscriptions: (() => void)[] = [] + const withdraw = (): void => { + preparation?.abort() + for (const detach of subscriptions.splice(0)) detach() + clear() + } + provider.lifetime.signal.addEventListener('abort', withdraw, { once: true }) + cleanup.push(() => { + provider.lifetime.signal.removeEventListener('abort', withdraw) + withdraw() + }) + try { + for (const input of provider.observe(target)) subscriptions.push(input.subscribe(prepare)) + prepare() + } catch (_error) { if (!lifetime.signal.aborted && !provider.lifetime.signal.aborted) this.failed() } + pending.push((async () => { + let current: Promise | undefined + do { current = preparing; await current } while (current !== preparing) + })()) + } + return { + source, dispose, ready: Promise.all(pending).then(() => {}), + select: (id) => { + const selected = callbacks.get(id) + if (lifetime.signal.aborted || selected === undefined || selected.provider.lifetime.signal.aborted + || selected.action.disabled || selected.action.children !== undefined) return + const run = selected.action.run + dispose() + try { void Promise.resolve(run?.()).catch(() => { this.failed(selected.action.failureLabel) }) } + catch (_error) { this.failed(selected.action.failureLabel) } + }, + } + } + + /** Cancel every occurrence and reject further registrations or resolutions. */ + dispose(): void { + if (this.disposed) return + this.disposed = true + for (const dispose of this.occurrences) dispose() + for (const provider of this.providers.values()) provider.lifetime.abort() + this.providers.clear() + } +} diff --git a/packages/client/ui-context-menu/src/client/store.ts b/packages/client/ui-context-menu/src/client/store.ts new file mode 100644 index 0000000000..8791201c91 --- /dev/null +++ b/packages/client/ui-context-menu/src/client/store.ts @@ -0,0 +1,41 @@ +/** Single-popup viewing state and feedback retained outside trigger components. */ +import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store' +import type { MenuActionView, MenuPoint, ContextMenuTarget } from './types.ts' + +interface Notice { id: number; text: string; success: boolean; action?: { label: string; onClick: () => void } } +interface MenuState { + occurrence: number + closing: boolean + replacing: boolean + target: ContextMenuTarget | null + point: MenuPoint + items: readonly MenuActionView[] + notice: Notice | null +} +type MenuActions = { + open(draft: MenuState, target: ContextMenuTarget, point: MenuPoint): void + items(draft: MenuState, items: readonly MenuActionView[]): void + exit(draft: MenuState, replacing: boolean): void + close(draft: MenuState): void + notify(draft: MenuState, notice: Notice | null): void +} + +/** + * Create the root popup store. + * @returns the presentation and its mutation actions. + */ +export function createMenuStore(): EngineStoreHandle { + return defineStore({ + init: () => ({ occurrence: 0, closing: false, replacing: false, target: null, point: { x: 0, y: 0 }, items: [], notice: null }), + actions: { + open(draft, target, point) { + draft.occurrence++; draft.closing = false; draft.replacing = false + draft.target = target; draft.point = point; draft.items = [] + }, + items(draft, items) { draft.items = items }, + exit(draft, replacing) { draft.closing = true; draft.replacing = replacing }, + close(draft) { draft.target = null; draft.items = [] }, + notify(draft, notice) { draft.notice = notice }, + }, + }) +} diff --git a/packages/client/ui-context-menu/src/client/target-key.ts b/packages/client/ui-context-menu/src/client/target-key.ts new file mode 100644 index 0000000000..4304d2d617 --- /dev/null +++ b/packages/client/ui-context-menu/src/client/target-key.ts @@ -0,0 +1,14 @@ +/** Stable equality for the JSON-compatible target vocabulary, independent of object insertion order. */ +import type { ContextMenuTarget } from './types.ts' + +/** + * Compare captured JSON targets independently of object key insertion order. + * @param target - captured immutable target. + * @returns canonical JSON identity. + */ +export function menuTargetKey(target: ContextMenuTarget): string { + return JSON.stringify(target, (_key: string, value: unknown): unknown => { + if (typeof value !== 'object' || value === null || Array.isArray(value)) return value + return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right))) + }) +} diff --git a/packages/client/ui-context-menu/src/client/trigger.ts b/packages/client/ui-context-menu/src/client/trigger.ts new file mode 100644 index 0000000000..04cd530e1a --- /dev/null +++ b/packages/client/ui-context-menu/src/client/trigger.ts @@ -0,0 +1,43 @@ +/** DOM gesture bindings owned by one menu plugin instance. */ +import type { SyntheticEvent } from 'react' +import type { ContextMenuTriggerProps, MenuPoint, ContextMenuTarget } from './types.ts' + +/** + * Create stable bindings for the plugin's injected hook. + * @param open - Open against the supplied captured target and viewport position. + * @param active - Whether the plugin still owns its service. + * @returns Ordinary trigger-prop factory; no React subscription or context is created. + */ +export function createContextMenuBindings( + open: (target: Target, point: MenuPoint) => void, active: () => boolean, +): { getTriggerProps: (target: Target | (() => Target) | undefined, handlers?: ContextMenuTriggerProps) => ContextMenuTriggerProps } { + return { + getTriggerProps(target, handlers = {}) { + if (target === undefined) return handlers + const show = (event: SyntheticEvent, x: number, y: number): void => { + if (event.defaultPrevented || !active()) return + const captured = typeof target === 'function' ? target() : target + event.preventDefault() + event.stopPropagation() + event.currentTarget.focus({ preventScroll: true }) + open(captured, { x, y }) + } + return { + ...handlers, + tabIndex: handlers.tabIndex ?? 0, + onContextMenu(event) { + handlers.onContextMenu?.(event) + const rect = event.clientX === 0 && event.clientY === 0 ? event.currentTarget.getBoundingClientRect() : undefined + show(event, rect?.left ?? event.clientX, rect?.bottom ?? event.clientY) + }, + onKeyDown(event) { + handlers.onKeyDown?.(event) + if (event.defaultPrevented || event.repeat || event.nativeEvent.isComposing || event.ctrlKey || event.altKey || event.metaKey + || !(event.key === 'ContextMenu' || event.key === 'F10' && event.shiftKey)) return + const rect = event.currentTarget.getBoundingClientRect() + show(event, rect.left, rect.bottom) + }, + } + }, + } +} diff --git a/packages/client/ui-context-menu/src/client/types.ts b/packages/client/ui-context-menu/src/client/types.ts new file mode 100644 index 0000000000..d32a788fb4 --- /dev/null +++ b/packages/client/ui-context-menu/src/client/types.ts @@ -0,0 +1,143 @@ +/** Client menu contributions and explicit gesture targets. */ +import type { ShortcutCommandId } from '@deepseek-ai/dsh-client-shortcuts/client' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { PaneId, TabRecord } from '@deepseek-ai/dsh-client-ui-dockkit' +import type { HTMLAttributes } from 'react' + +/** DOM handlers bound to an explicit object; existing handlers can prevent menu activation. */ +export type ContextMenuTriggerProps = Pick, 'onContextMenu' | 'onKeyDown' | 'tabIndex'> + +/** Functions supplied by the globally injected useContextMenu hook. */ +export interface ContextMenuBindings { + /** + * Bind an object or deferred business target to one element. This is an ordinary function, safe in loops. + * @param target - Object captured when the gesture runs; undefined retains native behavior. + * @param handlers - Existing handlers run first and can cancel with preventDefault(). + * @returns Combined pointer and keyboard handlers plus a keyboard focus stop. + */ + getTriggerProps: ( + target: ContextMenuTarget | (() => ContextMenuTarget) | undefined, handlers?: ContextMenuTriggerProps, + ) => ContextMenuTriggerProps +} + +/** Read menu gesture bindings owned by the current menu plugin lifetime. */ +export type UseContextMenu = () => ContextMenuBindings + +/** External plugins extend this map with their own target families. */ +export interface ContextMenuTargetMap { + session: { readonly sessionId: SessionId; readonly displayTitle: string } + file: { readonly sessionId: SessionId; readonly path: string; readonly line?: number; readonly paneId?: PaneId } + directory: { readonly sessionId: SessionId; readonly path: string } + url: { readonly sessionId: SessionId; readonly url: string } + image: { + readonly sessionId?: SessionId + readonly url: string + readonly name?: string + readonly mediaType?: string + readonly path?: string + } + tab: { readonly sessionId: SessionId; readonly paneId: PaneId; readonly tab: TabRecord } +} + +/** Captured target; changing selection never changes an open menu's target. */ +export type ContextMenuTarget = { + [K in keyof ContextMenuTargetMap]: { readonly kind: K; readonly value: ContextMenuTargetMap[K] } +}[keyof ContextMenuTargetMap] +/** Pointer position in CSS pixels; keyboard gestures use the trigger's bottom edge. */ +export interface MenuPoint { readonly x: number; readonly y: number } +/** Keyed icon renderer and optional image URL captured with the action. */ +export interface ContextMenuIcon { + readonly key: string + readonly src?: string +} +/** Client presentation fields; callbacks stay in the registry. */ +export interface MenuActionView { + readonly id: string + readonly label: string + /** Command identity for live shortcut display only; selection still invokes this action’s run callback. */ + readonly commandId?: ShortcutCommandId + readonly disabled?: boolean + readonly icon?: ContextMenuIcon + readonly danger?: boolean + readonly separatorBefore?: boolean + /** Render after legacy component contributions in the shared Web popup. */ + readonly afterContent?: boolean + readonly children?: readonly MenuActionView[] +} +/** A contribution can decline, return actions immediately, or resolve metadata asynchronously. */ +export interface MenuAction extends Omit { + readonly children?: readonly MenuAction[] + /** Localized operation and recovery guidance when execution rejects. */ + readonly failureLabel?: string + /** Execute against the captured target. Reject for a visible failure; cancellation resolves normally. */ + readonly run?: () => void | Promise +} +/** A namespaced contribution, ordered within its target family. */ +export interface MenuContribution { + readonly id: string + readonly target: K + readonly order: number + /** + * Reactive inputs that re-resolve actions for the same captured target. + * @param target - clicked object. + * @returns sources owned by the contributing feature; unsubscribed on dismissal or unload. + */ + observe?(target: ContextMenuTargetMap[K]): readonly ObservableSnapshot[] + /** + * @param target - clicked object. + * @param signal - aborted on dismissal, plugin unload, or a newer observed preparation. + * @returns available actions. + */ + resolve(target: ContextMenuTargetMap[K], signal: AbortSignal): readonly MenuAction[] | Promise +} +/** Independent menu occurrence used by custom renderers and embedded menus. */ +export interface MenuResolution { + /** Read a new immutable presentation after each provider settles, updates, or is withdrawn. */ + readonly source: ObservableSnapshot + /** Settles when all opening contributions have completed or been withdrawn. */ + readonly ready: Promise + /** + * Select once; disposed or removed contributions cannot execute. + * @param id - resolved action id. + */ + select(id: string): void + /** Cancel metadata queries and discard callbacks. */ + dispose(): void +} +/** Client capability used equally by built-in and external plugins. */ +export interface ContextMenus { + /** Captured target of the shared popup; null after dismissal. */ + readonly active: ObservableSnapshot + /** + * Register for subsequent openings; unloading withdraws actions and aborts their queries. Duplicate ids within a target fail. + * @param contribution - target provider. + * @returns unregister. + */ + register(contribution: MenuContribution): () => void + /** + * Open the single shared popup. + * @param target - captured object. + * @param point - viewport position. + */ + open(target: ContextMenuTarget, point: MenuPoint): void + /** + * Resolve an embedded menu without opening the shared popup. + * @param target - captured object. + * @returns owned occurrence. + */ + resolve(target: ContextMenuTarget): MenuResolution + /** Close the shared popup and cancel its metadata queries. */ + close(): void + /** + * Show localized feedback outside the originating surface. + * @param text - localized message. + * @param success - successful action. + * @param action - optional text action retained by this notice; rejects with localized failure feedback. + */ + notify(text: string, success?: boolean, action?: { + readonly label: string + readonly run: () => void | Promise + readonly failureLabel: string + }): void +} diff --git a/packages/client/ui-context-menu/src/index.ts b/packages/client/ui-context-menu/src/index.ts new file mode 100644 index 0000000000..77258040c7 --- /dev/null +++ b/packages/client/ui-context-menu/src/index.ts @@ -0,0 +1,4 @@ +/** Host Loader entry; menus belong to the Client. */ + +/** Register the browser plugin without Host behavior. */ +export function apply(): void {} diff --git a/packages/client/ui-context-menu/tests/overlay.client.spec.tsx b/packages/client/ui-context-menu/tests/overlay.client.spec.tsx new file mode 100644 index 0000000000..54194a811b --- /dev/null +++ b/packages/client/ui-context-menu/tests/overlay.client.spec.tsx @@ -0,0 +1,166 @@ +// @vitest-environment jsdom +import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import { bindSnapshotSelector, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import { MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' +import { ShortcutRegistry } from '../../shortcuts/src/client/registry.ts' +import type { ShortcutCommandId } from '@deepseek-ai/dsh-client-shortcuts/client' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { createMenuStore } from '../src/client/store.ts' +import { MenuOverlay } from '../src/client/View.tsx' +import { apply, inject } from '../src/client/index.ts' +import type { ContextMenuTarget } from '../src/client/types.ts' + +afterEach(() => { cleanup(); vi.useRealTimers() }) + +it('renders legacy Session actions before data contributions and restores More focus after dismissal', async () => { + const store = createMenuStore().create(), run = vi.fn() + const close = () => { store.actions.close() } + const useStore = bindSnapshotSelector(store) + const view = render(<> + + select([])} useStore={useStore} actions={store.actions} close={close} select={run} + renderSlot={(_key, owner: object) => { + const { target, dismiss } = owner as { target: ContextMenuTarget; dismiss: () => void } + return { + if (target.kind === 'session') run(target.value.sessionId) + dismiss() + }}>Export + }} /> + ) + const trigger = view.getByRole('button', { name: 'More' }) + trigger.focus(); fireEvent.click(trigger) + await waitFor(() =>{ expect(view.getByRole('menuitem', { name: 'Export' })).toBe(document.activeElement) }) + fireEvent.click(view.getByRole('menuitem', { name: 'Export' })) + await waitFor(() =>{ expect(document.activeElement).toBe(trigger) }) + expect(run).toHaveBeenCalledExactlyOnceWith('clicked') + expect(view.queryByRole('menu')).toBeNull() + fireEvent.click(trigger) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(view.queryByRole('menu')).toBeNull() + fireEvent.click(trigger) + fireEvent.pointerDown(document.body) + expect(view.queryByRole('menu')).toBeNull() +}) + +it('renders disabled, grouped and nested data actions and keeps feedback after menu dismissal', () => { + vi.useFakeTimers() + const store = createMenuStore().create(), select = vi.fn() + store.actions.open({ kind: 'session', value: { sessionId: SessionId('clicked'), displayTitle: 'Clicked' } }, { x: 20, y: 30 }) + store.actions.items([ + { id: 'plain', label: 'Open' }, + { id: 'blocked', label: 'Unavailable', disabled: true, danger: true, separatorBefore: true }, + { id: 'parent', label: 'Export', children: [{ id: 'child', label: 'Original' }, { id: 'other', label: 'Other', separatorBefore: true }] }, + { id: 'footer', label: 'Folder', afterContent: true }, + ]) + const view = render( select([])} useStore={bindSnapshotSelector(store)} actions={store.actions} + close={() => { store.actions.close() }} select={select} renderSlot={() => null} />) + expect(view.getByRole('menuitem', { name: 'Unavailable' }).hasAttribute('disabled')).toBe(true) + fireEvent.click(view.getByRole('menuitem', { name: 'Open' })) + expect(select).toHaveBeenCalledWith('plain') + fireEvent.click(view.getByRole('menuitem', { name: 'Export' })) + expect(view.getAllByRole('separator')).toHaveLength(2) + fireEvent.click(view.getByRole('menuitem', { name: 'Original' })) + expect(select).toHaveBeenCalledWith('child') + act(() => { store.actions.exit(true) }) + expect(document.querySelector('[data-menu-phase="replace"]')).not.toBeNull() + act(() => { store.actions.exit(false) }) + expect(document.querySelector('[data-menu-phase="dismiss"]')).not.toBeNull() + const reveal = vi.fn() + act(() => { store.actions.close(); store.actions.notify({ id: 1, text: 'Saved', success: true, + action: { label: 'Show in Finder', onClick: reveal } }) }) + expect(view.queryByRole('menu')).toBeNull() + expect(view.getByRole('alert').textContent).toBe('SavedShow in Finder') + fireEvent.click(view.getByRole('button', { name: 'Show in Finder' })) + expect(reveal).toHaveBeenCalledOnce() + act(() => { store.actions.notify({ id: 2, text: 'Copy failed', success: false }) }) + expect(view.getByRole('alert').textContent).toBe('Copy failed') + expect(view.queryByRole('button', { name: 'Show in Finder' })).toBeNull() + act(() => { vi.advanceTimersByTime(4000) }) + expect(view.queryByRole('alert')).toBeNull() +}) + +function PluginIcon({ icon }: PropsRuntime<'contextMenu.icon'>) { + return +} + +it('dispatches captured icon keys in rows, submenus and footers and retires renderer registrations on unload', async () => { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) } as never) + runtime.ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) + await runtime.root.declare({ 'shell.overlay': { kind: 'list', scope: 'root' } }, ({ renderSlot }) => + <>{renderSlot('shell.overlay', {})}) + const menuPlugin = await runtime.mount({ inject, apply }) + const run = vi.fn() + const contribution = await runtime.mount({ inject: ['contextMenus'], apply(ctx) { + ctx.effect(() => ctx.contextMenus.register({ id: 'icons', target: 'session', order: 0, resolve: () => [ + { id: 'row', label: 'Open', icon: { key: 'example.icon', src: '/captured.png' }, run }, + { id: 'parent', label: 'Export', children: [{ id: 'child', label: 'Original', icon: { key: 'example.icon' } }] }, + { id: 'footer', label: 'Footer', afterContent: true, icon: { key: 'example.icon' } }, + ] })) + } }) + const icons = await runtime.mount({ inject: ['slots'], apply(ctx) { + ctx.slots.inject('contextMenu.icon', function* () { + yield ctx.slots.register({ name: 'contextMenu.icon', key: 'example.icon' }, PluginIcon) + yield ctx.slots.register({ name: 'contextMenu.icon', key: 'example.unused' }, () => Unused icon) + }) + } }) + const view = runtime.renderRoot() + const open = () => { runtime.ctx.contextMenus.open({ kind: 'session', value: { + sessionId: SessionId('icons'), displayTitle: 'Icons', + } }, { x: 20, y: 30 }) } + act(open) + await waitFor(() => { expect(view.getAllByTestId('plugin-icon')).toHaveLength(2) }) + expect(view.getByRole('menuitem', { name: 'Open' }).querySelector('img')?.getAttribute('src')).toBe('/captured.png') + expect(view.queryByText('Unused icon')).toBeNull() + fireEvent.click(view.getByRole('menuitem', { name: 'Export' })) + expect(view.getByRole('menuitem', { name: 'Original' }).querySelector('img')).not.toBeNull() + await icons.dispose() + expect(view.queryAllByTestId('plugin-icon')).toHaveLength(0) + fireEvent.click(view.getByRole('menuitem', { name: 'Open' })) + expect(run).toHaveBeenCalledOnce() + await contribution.dispose() + await menuPlugin.dispose() + expect(runtime.slots.spec('contextMenu.icon')).toBeUndefined() +}) + +it('tracks configured shortcuts for nested and footer actions without invoking command dispatch', () => { + const shortcuts = new ShortcutRegistry('desktop', 'macos') + const commandId = 'session.rename' as ShortcutCommandId + const resolveCommand = vi.fn(() => ({ status: 'pass' as const })) + const remove = shortcuts.register({ id: commandId, label: () => 'Rename', aliases: [], + defaults: { 'desktop:macos': { code: 'KeyG', modifiers: ['primary', 'alt'] } }, + regions: ['page'], modals: [], resolve: resolveCommand }) + const store = createMenuStore().create() + store.actions.open({ kind: 'session', value: { sessionId: SessionId('captured'), displayTitle: 'Captured' } }, { x: 30, y: 40 }) + store.actions.items([ + { id: 'rename', label: 'Rename', commandId }, + { id: 'missing', label: 'Unknown command', commandId: 'absent' as ShortcutCommandId }, + { id: 'parent', label: 'Submenu', children: [{ id: 'nested', label: 'Nested', commandId }] }, + { id: 'footer', label: 'Footer', commandId, afterContent: true }, + ]) + const select = vi.fn() + const view = render( null} />) + const item = view.getByRole('menuitem', { name: 'Rename' }) + expect(item.getAttribute('aria-keyshortcuts')).toBe('Alt+Meta+G') + expect(view.getByRole('menuitem', { name: 'Unknown command' }).getAttribute('aria-keyshortcuts')).toBeNull() + act(() => { shortcuts.configure({ ...shortcuts.config.getSnapshot(), revision: 'custom' as never, + document: { schemaVersion: 2, profiles: { 'desktop:macos': { 'session.rename': { code: 'KeyR', modifiers: ['primary', 'shift'] } } } } }) }) + expect(item.getAttribute('aria-keyshortcuts')).toBe('Shift+Meta+R') + expect(view.getByRole('menuitem', { name: 'Footer' }).getAttribute('aria-keyshortcuts')).toBe('Shift+Meta+R') + fireEvent.click(view.getByRole('menuitem', { name: 'Submenu' })) + expect(view.getByRole('menuitem', { name: 'Nested' }).getAttribute('aria-keyshortcuts')).toBe('Shift+Meta+R') + act(() => { shortcuts.configure({ ...shortcuts.config.getSnapshot(), revision: 'unbound' as never, + document: { schemaVersion: 2, profiles: { 'desktop:macos': { 'session.rename': null } } } }) }) + expect(item.getAttribute('aria-keyshortcuts')).toBeNull() + expect(item.querySelector('kbd')).toBeNull() + act(remove) + expect(item.getAttribute('aria-keyshortcuts')).toBeNull() + fireEvent.click(item) + expect(select).toHaveBeenCalledWith('rename') + expect(resolveCommand).not.toHaveBeenCalled() +}) diff --git a/packages/client/ui-context-menu/tests/plugin.client.spec.ts b/packages/client/ui-context-menu/tests/plugin.client.spec.ts new file mode 100644 index 0000000000..afd3d97350 --- /dev/null +++ b/packages/client/ui-context-menu/tests/plugin.client.spec.ts @@ -0,0 +1,197 @@ +// @vitest-environment jsdom +import type { MenuAction } from '../src/client/types.ts' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { Context } from '@deepseek-ai/cordis' +import { afterEach, expect, it, vi } from 'vitest' +import type { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { MenuOverlayInjected } from '../src/client/View.tsx' +import { apply, inject } from '../src/client/index.ts' +import { apply as hostApply } from '../src/index.ts' +import type { createMenuStore } from '../src/client/store.ts' + +afterEach(() => { vi.useRealTimers() }) + +declare module '@deepseek-ai/dsh-client-ui-context-menu/client' { + interface ContextMenuTargetMap { pluginDocument: { readonly id: string } } +} + +it('lets an external contribution open another menu and withdraws its actions when its fiber unloads', async () => { + const ctx = new Context() + ctx.provide('shortcuts', { catalog: createSnapshotStore([]) } as never) + let overlay!: MenuOverlayInjected + let store!: ReturnType['create']> + ctx.provide('slots', { provideRoot: () => () => {}, + inject: (_name: string, register: Parameters[1]) => ctx.effect(register), + register: (entry: { inject: () => MenuOverlayInjected; store: ReturnType }) => { + overlay = entry.inject(); store = entry.store.create(); return () => {} + }, + } as never) + ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) + const menuFiber = ctx.plugin({ inject, apply }) + await menuFiber.await() + expect(hostApply).not.toThrow() + const run = vi.fn() + const contribution = ctx.plugin({ inject: ['contextMenus'], apply: (plugin: Context) => { + plugin.effect(() => plugin.contextMenus.register({ + target: 'pluginDocument', id: 'example.document', order: 0, + resolve: ({ id }) => [{ id: 'inspect', label: id, run: () => { + run(id) + plugin.contextMenus.open({ kind: 'pluginDocument', value: { id: 'next' } }, { x: 3, y: 4 }) + } }], + })) + } }) + await contribution.await() + try { + ctx.contextMenus.open({ kind: 'pluginDocument', value: { id: 'clicked' } }, { x: 1, y: 2 }) + await vi.waitFor(() => { expect(store.getSnapshot().items.length).toBeGreaterThan(0) }) + overlay.select('example.document/inspect') + expect(run).toHaveBeenCalledExactlyOnceWith('clicked') + expect(ctx.contextMenus.active.getSnapshot()).toEqual({ kind: 'pluginDocument', value: { id: 'next' } }) + const occurrence = ctx.contextMenus.resolve({ kind: 'pluginDocument', value: { id: 'retained' } }) + expect(occurrence.source.getSnapshot().map(action => action.label)).toEqual(['retained']) + await contribution.dispose() + expect(occurrence.source.getSnapshot()).toEqual([]) + occurrence.select('example.document/inspect') + expect(run).toHaveBeenCalledOnce() + occurrence.dispose() + ctx.contextMenus.notify('Saved', true) + expect(store.getSnapshot().notice).toMatchObject({ text: 'Saved', success: true }) + ctx.contextMenus.notify('Unavailable') + expect(store.getSnapshot().notice).toMatchObject({ text: 'Unavailable', success: false }) + const reveal = vi.fn(async () => {}) + ctx.contextMenus.notify('Saved', true, { label: 'Show in folder', run: reveal, failureLabel: 'Reveal failed' }) + const previousAction = store.getSnapshot().notice!.action! + expect(previousAction.label).toBe('Show in folder') + previousAction.onClick() + previousAction.onClick() + expect(reveal).toHaveBeenCalledOnce() + expect(store.getSnapshot().notice).toBeNull() + ctx.contextMenus.notify('Saved again', true, { label: 'Show in folder', run: reveal, failureLabel: 'Reveal failed' }) + const replaced = store.getSnapshot().notice!.action! + ctx.contextMenus.notify('New notice') + replaced.onClick() + expect(reveal).toHaveBeenCalledOnce() + for (const fail of [() => { throw new Error('denied') }, async () => { throw new Error('offline') }]) { + ctx.contextMenus.notify('Saved', true, { label: 'Show in folder', run: fail, failureLabel: 'Reveal failed' }) + store.getSnapshot().notice!.action!.onClick() + await vi.waitFor(() => { expect(store.getSnapshot().notice).toMatchObject({ text: 'Reveal failed', success: false }) }) + } + const removeFailure = ctx.contextMenus.register({ target: 'pluginDocument', id: 'failure', order: 0, + resolve: () => { throw new Error('Metadata unavailable') } }) + ctx.contextMenus.open({ kind: 'pluginDocument', value: { id: 'failed' } }, { x: 0, y: 0 }) + expect(store.getSnapshot().notice?.text).toBe('failed') + removeFailure() + const removeAction = ctx.contextMenus.register({ target: 'pluginDocument', id: 'action', order: 0, + resolve: () => [{ id: 'copy', label: 'Copy', failureLabel: 'Copy failed', run: () => { throw new Error('Denied') } }] }) + ctx.contextMenus.open({ kind: 'pluginDocument', value: { id: 'failed-action' } }, { x: 0, y: 0 }) + overlay.select('action/copy') + expect(store.getSnapshot().notice?.text).toBe('Copy failed') + removeAction() + } finally { await contribution.dispose(); await menuFiber.dispose() } +}) + +it('waits for metadata, toggles nearby repeated gestures, replaces occurrences, and cancels pending openings', async () => { + vi.useFakeTimers() + const ctx = new Context() + ctx.provide('shortcuts', { catalog: createSnapshotStore([]) } as never) + let store!: ReturnType['create']> + ctx.provide('slots', { provideRoot: () => () => {}, + inject: (_name: string, register: Parameters[1]) => ctx.effect(register), + register: (entry: { store: ReturnType }) => { store = entry.store.create(); return () => {} }, + } as never) + ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) + const fiber = ctx.plugin({ inject, apply }) + await fiber.await() + let finish!: (actions: readonly MenuAction[]) => void + ctx.contextMenus.register({ target: 'pluginDocument', id: 'slow', order: 0, + resolve: () => new Promise((resolve) => { finish = resolve }) }) + const target = { kind: 'pluginDocument' as const, value: { id: 'file' } } + try { + ctx.contextMenus.open(target, { x: 20, y: 30 }) + await vi.advanceTimersByTimeAsync(100) + expect(store.getSnapshot().target).toBeNull() + finish([{ id: 'open', label: 'Open' }]) + await vi.advanceTimersByTimeAsync(0) + expect(store.getSnapshot().items.map(item => item.label)).toEqual(['Open']) + const first = store.getSnapshot().occurrence + ctx.contextMenus.open(target, { x: 22, y: 31 }) + expect(ctx.contextMenus.active.getSnapshot()).toBeNull() + expect(store.getSnapshot().closing).toBe(true) + await vi.advanceTimersByTimeAsync(80) + expect(store.getSnapshot().target).toBeNull() + ctx.contextMenus.open(target, { x: 80, y: 30 }) + finish([{ id: 'second', label: 'Second' }]) + await vi.advanceTimersByTimeAsync(40) + expect(store.getSnapshot().occurrence).toBe(first + 1) + ctx.contextMenus.open(target, { x: 180, y: 30 }) + expect(store.getSnapshot().replacing).toBe(true) + document.body.dispatchEvent(new Event('pointerdown', { bubbles: true })) + finish([{ id: 'late', label: 'Late' }]) + await vi.advanceTimersByTimeAsync(100) + expect(store.getSnapshot().target).toBeNull() + ctx.contextMenus.open(target, { x: 20, y: 30 }) + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })) + finish([{ id: 'escape', label: 'Escape' }]) + await vi.advanceTimersByTimeAsync(100) + expect(store.getSnapshot().target).toBeNull() + } finally { await fiber.dispose() } +}) + +it('keeps trigger focus through replacement and ignores non-dismissal events and late feedback', async () => { + vi.useFakeTimers() + const ctx = new Context() + ctx.provide('shortcuts', { catalog: createSnapshotStore([]) } as never) + let overlay!: MenuOverlayInjected + ctx.provide('slots', { provideRoot: () => () => {}, + inject: (_name: string, register: Parameters[1]) => ctx.effect(register), + register: (entry: { inject: () => MenuOverlayInjected }) => { overlay = entry.inject(); return () => {} }, + } as never) + ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) + const fiber = ctx.plugin({ inject, apply }) + await fiber.await() + const notify = ctx.contextMenus.notify.bind(ctx.contextMenus) + ctx.contextMenus.register({ target: 'pluginDocument', id: 'plain', order: 0, resolve: () => [{ id: 'copy', label: 'Copy' }] }) + const trigger = document.createElement('button'), menu = document.createElement('button') + menu.setAttribute('data-context-menu', '') + menu.setAttribute('role', 'menu') + document.body.append(trigger, menu) + try { + trigger.focus() + ctx.contextMenus.open({ kind: 'pluginDocument', value: { id: 'first' } }, { x: 10, y: 10 }) + await vi.advanceTimersByTimeAsync(40) + expect(overlay.returnFocus?.()).toBe(trigger) + menu.focus() + ctx.contextMenus.open({ kind: 'pluginDocument', value: { id: 'second' } }, { x: 80, y: 80 }) + await vi.advanceTimersByTimeAsync(40) + expect(overlay.returnFocus?.()).toBe(trigger) + menu.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, button: 2 })) + menu.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, button: 0 })) + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown' })) + expect(ctx.contextMenus.active.getSnapshot()).not.toBeNull() + document.dispatchEvent(new MouseEvent('contextmenu', { cancelable: true })) + expect(ctx.contextMenus.active.getSnapshot()).toBeNull() + const handled = new MouseEvent('contextmenu', { cancelable: true }); handled.preventDefault() + document.dispatchEvent(handled) + document.dispatchEvent(new Event('pointerdown')) + expect(ctx.contextMenus.active.getSnapshot()).toBeNull() + const active = vi.spyOn(document, 'activeElement', 'get').mockReturnValue(null) + ctx.contextMenus.open({ kind: 'pluginDocument', value: { id: 'third' } }, { x: 80, y: 80 }) + active.mockRestore() + expect(overlay.returnFocus?.()).toBeNull() + } finally { trigger.remove(); menu.remove(); await fiber.dispose() } + notify('late') +}) + +it('leaves unbound keyboard gestures native', async () => { + const ctx = new Context() + ctx.provide('shortcuts', { catalog: createSnapshotStore([]) } as never) + ctx.provide('slots', { provideRoot: () => () => {}, inject: () => () => {} } as never) + ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) + const fiber = ctx.plugin({ inject, apply }) + await fiber.await() + try { + const event = new KeyboardEvent('keydown', { key: 'ContextMenu', bubbles: true, cancelable: true }) + document.dispatchEvent(event) + expect(event.defaultPrevented).toBe(false) + } finally { await fiber.dispose() } +}) diff --git a/packages/client/ui-context-menu/tests/registry.client.spec.ts b/packages/client/ui-context-menu/tests/registry.client.spec.ts new file mode 100644 index 0000000000..c533f3b49d --- /dev/null +++ b/packages/client/ui-context-menu/tests/registry.client.spec.ts @@ -0,0 +1,218 @@ +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { describe, expect, it, vi } from 'vitest' +import { MenuRegistry } from '../src/client/registry.ts' +import type { MenuAction } from '@deepseek-ai/dsh-client-ui-context-menu/client' + +declare module '@deepseek-ai/dsh-client-ui-context-menu/client' { + interface ContextMenuTargetMap { extension: { readonly id: string } } +} +const target = { kind: 'extension' as const, value: { id: 'clicked' } } + +function deferred() { + let resolve!: (value: T) => void + let reject!: (error: Error) => void + const promise = new Promise((yes, no) => { resolve = yes; reject = no }) + return { promise, resolve, reject } +} + +describe('menu contribution lifecycle', () => { + it('orders independently resolved contributions and executes the captured target once', async () => { + const failure = vi.fn(), run = vi.fn() + const registry = new MenuRegistry(failure) + const waiting = deferred() + registry.register({ id: 'later', target: 'extension', order: 20, resolve: () => waiting.promise }) + registry.register({ id: 'first', target: 'extension', order: 10, resolve: ({ id }) => [{ id: 'open', label: id, run: () => { run(id) } }] }) + const menu = registry.resolve(target) + expect(menu.source.getSnapshot().map(x => x.id)).toEqual(['first/open']) + waiting.resolve([{ id: 'open', label: 'Later' }]); await waiting.promise + expect(menu.source.getSnapshot().map(x => x.id)).toEqual(['first/open', 'later/open']) + expect(JSON.parse(JSON.stringify(menu.source.getSnapshot()))).toEqual(menu.source.getSnapshot()) + menu.select('first/open'); menu.select('first/open') + expect(run).toHaveBeenCalledExactlyOnceWith('clicked') + expect(failure).not.toHaveBeenCalled() + registry.dispose() + }) + + it.each(['menu', 'provider', 'registry'] as const)('aborts pending metadata when its %s retires', async (retire) => { + const failure = vi.fn(), run = vi.fn() + const registry = new MenuRegistry(failure) + const waiting = deferred() + let signal!: AbortSignal + const remove = registry.register({ id: 'slow', target: 'extension', order: 0, resolve: (_target, lifetime) => { signal = lifetime; return waiting.promise } }) + const menu = registry.resolve(target) + if (retire === 'menu') menu.dispose() + if (retire === 'provider') remove() + if (retire === 'registry') registry.dispose() + expect(signal.aborted).toBe(true) + waiting.resolve([{ id: 'late', label: 'Late', run }]); await waiting.promise + expect(menu.source.getSnapshot()).toEqual([]) + menu.select('slow/late') + expect(run).not.toHaveBeenCalled() + expect(failure).not.toHaveBeenCalled() + menu.dispose(); remove(); registry.dispose() + }) + + it('withdraws resolved actions on unload and takes new contributions on the next opening', () => { + const registry = new MenuRegistry(vi.fn()), run = vi.fn() + const remove = registry.register({ id: 'old', target: 'extension', order: 0, resolve: () => [{ id: 'a', label: 'A', run }] }) + const first = registry.resolve(target) + remove(); remove() + expect(first.source.getSnapshot()).toEqual([]) + first.select('old/a'); expect(run).not.toHaveBeenCalled() + registry.register({ id: 'new', target: 'extension', order: 0, resolve: () => [{ id: 'b', label: 'B' }] }) + expect(first.source.getSnapshot()).toEqual([]) + const next = registry.resolve(target) + expect(next.source.getSnapshot()[0]?.id).toBe('new/b') + first.dispose(); next.dispose(); registry.dispose() + expect(() => registry.resolve(target)).toThrow('disposed') + }) + + it('contains provider failure and rejects duplicate contributions without corrupting other actions', async () => { + const failed = vi.fn(), run = vi.fn(), registry = new MenuRegistry(failed) + const definition = { id: 'good', target: 'extension' as const, order: 0, resolve: () => [{ id: 'a', label: 'A', run }] } + registry.register(definition) + expect(() => registry.register(definition)).toThrow('Duplicate menu contribution') + registry.register({ id: 'bad', target: 'extension', order: 1, resolve: () => [{ id: 'a', label: 'A' }, { id: 'a', label: 'B' }] }) + registry.register({ id: 'rejected', target: 'extension', order: 2, resolve: () => Promise.reject(new Error('unavailable')) }) + const menu = registry.resolve(target) + await Promise.resolve(); await Promise.resolve() + expect(failed).toHaveBeenCalledTimes(2) + expect(menu.source.getSnapshot().map(x => x.id)).toEqual(['good/a']) + menu.select('bad/a'); expect(run).not.toHaveBeenCalled() + menu.select('good/a'); expect(run).toHaveBeenCalledOnce() + registry.dispose() + }) + + it('ignores disabled, submenu and unknown selections and reports an action rejection', async () => { + const failed = vi.fn(), run = vi.fn(), registry = new MenuRegistry(failed) + registry.register({ id: 'actions', target: 'extension', order: 0, resolve: () => [ + { id: 'disabled', label: 'Disabled', disabled: true, run }, + { id: 'parent', label: 'Parent', children: [{ id: 'child', label: 'Child', run: () => Promise.reject(new Error('failed')) }], run }, + ] }) + const menu = registry.resolve(target) + menu.select('missing'); menu.select('actions/disabled'); menu.select('actions/parent') + expect(run).not.toHaveBeenCalled() + menu.select('actions/parent/child'); await Promise.resolve(); await Promise.resolve() + expect(failed).toHaveBeenCalledOnce() + registry.dispose() + }) + + it('orders equal-priority providers by identity and contains synchronous action failures', () => { + const failed = vi.fn(), registry = new MenuRegistry(failed) + registry.register({ id: 'z', target: 'extension', order: 1, resolve: () => [{ id: 'none', label: 'No action' }] }) + registry.register({ id: 'a', target: 'extension', order: 1, resolve: () => [{ id: 'throw', label: 'Fail', + failureLabel: 'Could not copy. Try again.', run: () => { throw new Error('clipboard denied') } }] }) + const first = registry.resolve(target) + expect(first.source.getSnapshot().map(item => item.id)).toEqual(['a/throw', 'z/none']) + first.select('a/throw') + expect(failed).toHaveBeenCalledWith('Could not copy. Try again.') + const second = registry.resolve(target) + second.select('z/none') + registry.dispose() + expect(() => registry.register({ id: 'late', target: 'extension', order: 0, resolve: () => [] })).toThrow('disposed') + }) + + it('does not report cancelled metadata failures, including unload during resolution', async () => { + const failed = vi.fn(), registry = new MenuRegistry(failed) + let remove = () => {} + remove = registry.register({ id: 'self-removing', target: 'extension', order: 0, resolve: () => { + remove(); throw new Error('owner unloaded') + } }) + const waiting = deferred() + registry.register({ id: 'late-rejection', target: 'extension', order: 1, resolve: () => waiting.promise }) + const menu = registry.resolve(target) + menu.dispose() + waiting.reject(new Error('cancelled')) + await Promise.resolve(); await Promise.resolve() + expect(failed).not.toHaveBeenCalled() + registry.dispose() + }) +}) + +it('omits a provider that misses its deadline and ignores its late result', async () => { + vi.useFakeTimers() + const failed = vi.fn(), registry = new MenuRegistry(failed, 50) + const waiting = deferred() + let signal!: AbortSignal + registry.register({ id: 'slow', target: 'extension', order: 0, resolve: (_target, value) => { signal = value; return waiting.promise } }) + registry.register({ id: 'ready', target: 'extension', order: 1, resolve: () => [{ id: 'copy', label: 'Copy' }] }) + const menu = registry.resolve(target) + try { + await vi.advanceTimersByTimeAsync(50) + await menu.ready + expect(signal.aborted).toBe(true) + expect(menu.source.getSnapshot().map(item => item.label)).toEqual(['Copy']) + expect(failed).toHaveBeenCalledOnce() + waiting.resolve([{ id: 'late', label: 'Late' }]) + await waiting.promise + expect(menu.source.getSnapshot().map(item => item.label)).toEqual(['Copy']) + } finally { registry.dispose(); vi.useRealTimers() } +}) + +it('replaces observed actions and callbacks, cancels older preparation, and releases every subscription', async () => { + const input = createSnapshotStore(0) + const original = input.subscribe.bind(input) + const subscribe = vi.spyOn(input, 'subscribe') + const detach = vi.fn() + subscribe.mockImplementation((listener) => { + const off = original(listener) + return () => { detach(); off() } + }) + const failed = vi.fn(), registry = new MenuRegistry(failed), run = vi.fn() + const old = deferred(), current = deferred() + const signals: AbortSignal[] = [] + const resolve = vi.fn((_target: { id: string }, signal: AbortSignal) => { + signals.push(signal) + return input.getSnapshot() === 0 ? old.promise : current.promise + }) + const remove = registry.register({ id: 'live', target: 'extension', order: 0, observe: () => [input], resolve }) + const menu = registry.resolve(target) + try { + input.set(1) + expect(signals[0]?.aborted).toBe(true) + old.resolve([{ id: 'old', label: 'Old', run }]) + await old.promise + expect(menu.source.getSnapshot()).toEqual([]) + current.resolve([{ id: 'new', label: 'New', run }]) + await menu.ready + expect(menu.source.getSnapshot().map(item => item.id)).toEqual(['live/new']) + menu.select('live/old') + expect(run).not.toHaveBeenCalled() + remove() + expect(detach).toHaveBeenCalledOnce() + expect(menu.source.getSnapshot()).toEqual([]) + input.set(2) + expect(resolve).toHaveBeenCalledTimes(2) + expect(signals.every(signal => signal.aborted)).toBe(true) + expect(failed).not.toHaveBeenCalled() + } finally { menu.dispose(); registry.dispose() } + expect(detach).toHaveBeenCalledOnce() +}) + +it('withdraws invalid reactive updates and contains observation failure without retaining stale callbacks', () => { + const input = createSnapshotStore(false), failed = vi.fn(), run = vi.fn() + const registry = new MenuRegistry(failed) + registry.register({ id: 'live', target: 'extension', order: 0, observe: () => [input], resolve: () => { + if (input.getSnapshot()) throw new Error('No access') + return [{ id: 'run', label: 'Run', run }] + } }) + registry.register({ id: 'broken', target: 'extension', order: 1, observe: () => { throw new Error('Unavailable') }, resolve: () => [] }) + const menu = registry.resolve(target) + input.set(true) + expect(menu.source.getSnapshot()).toEqual([]) + menu.select('live/run') + expect(run).not.toHaveBeenCalled() + expect(failed).toHaveBeenCalledTimes(2) + menu.dispose(); registry.dispose() +}) + +it('does not report an observation failure after its provider unloads', () => { + const failed = vi.fn(), registry = new MenuRegistry(failed) + let remove = () => {} + remove = registry.register({ id: 'removed', target: 'extension', order: 0, + observe: () => { remove(); throw new Error('Unloaded') }, resolve: () => [] }) + const menu = registry.resolve(target) + expect(menu.source.getSnapshot()).toEqual([]) + expect(failed).not.toHaveBeenCalled() + menu.dispose(); registry.dispose() +}) diff --git a/packages/client/ui-context-menu/tests/target-key.client.spec.ts b/packages/client/ui-context-menu/tests/target-key.client.spec.ts new file mode 100644 index 0000000000..0f6830f205 --- /dev/null +++ b/packages/client/ui-context-menu/tests/target-key.client.spec.ts @@ -0,0 +1,14 @@ +import { expect, it } from 'vitest' +import { menuTargetKey } from '../src/client/target-key.ts' +import type { ContextMenuTarget } from '../src/client/types.ts' + +declare module '@deepseek-ai/dsh-client-ui-context-menu/client' { + interface ContextMenuTargetMap { nested: { id: string; data: { a: number; b: readonly (string | null)[] } } } +} + +it('compares JSON targets independently of object key insertion order while preserving arrays', () => { + const first: ContextMenuTarget = { kind: 'nested', value: { id: 'a', data: { a: 1, b: ['x', null] } } } + const second: ContextMenuTarget = { value: { data: { b: ['x', null], a: 1 }, id: 'a' }, kind: 'nested' } + expect(menuTargetKey(first)).toBe(menuTargetKey(second)) + expect(menuTargetKey(first)).not.toBe(menuTargetKey({ kind: 'nested', value: { id: 'a', data: { a: 1, b: [null, 'x'] } } })) +}) diff --git a/packages/client/ui-context-menu/tests/trigger.client.spec.tsx b/packages/client/ui-context-menu/tests/trigger.client.spec.tsx new file mode 100644 index 0000000000..d83a906a3b --- /dev/null +++ b/packages/client/ui-context-menu/tests/trigger.client.spec.tsx @@ -0,0 +1,100 @@ +// @vitest-environment jsdom +import { act, cleanup, createEvent, fireEvent, render } from '@testing-library/react' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import { createPortal } from 'react-dom' +import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { apply, inject } from '../src/client/index.ts' +import { createContextMenuBindings } from '../src/client/trigger.ts' +import type { ContextMenuTriggerProps, ContextMenuTarget } from '../src/client/types.ts' + +afterEach(cleanup) +const target = (id: string): ContextMenuTarget => ({ kind: 'session', value: { sessionId: SessionId(id), displayTitle: id } }) + +it('binds targets in loops, captures deferred identity before focus changes it, and composes existing handlers', () => { + const open = vi.fn(), previous = vi.fn(), clicked = vi.fn() + let selected = 'first' + const { getTriggerProps } = createContextMenuBindings(open, () => true) + const view = render(<> + {['one', 'two'].map(id => )} + + ) + for (const id of ['one', 'two']) { + fireEvent.contextMenu(view.getByRole('button', { name: id }), { clientX: 12, clientY: 23 }) + expect(open).toHaveBeenLastCalledWith(target(id), { x: 12, y: 23 }) + } + expect(previous).toHaveBeenCalledTimes(2) + const button = view.getByRole('button', { name: 'Captured' }) + button.getBoundingClientRect = () => new DOMRect(30, 40, 50, 20) + const focus = vi.spyOn(button, 'focus') + fireEvent.keyDown(button, { key: 'F10', shiftKey: true }) + expect(open).toHaveBeenLastCalledWith(target('first'), { x: 30, y: 60 }) + expect(focus).toHaveBeenCalledWith({ preventScroll: true }) + expect(button.tabIndex).toBe(-1) + expect(clicked).not.toHaveBeenCalled() + fireEvent.contextMenu(button) + expect(open).toHaveBeenLastCalledWith(target('changed'), { x: 30, y: 60 }) +}) + +it('honors prevented and nested gestures, portals, repeats, composition, and missing targets', () => { + const open = vi.fn(), outer = vi.fn(), existing = vi.fn() + const bindings = createContextMenuBindings(open, () => true) + const parent = createContextMenuBindings(outer, () => true) + const inner = bindings.getTriggerProps(target('inner')) + const composed = bindings.getTriggerProps(target('second'), inner) + const view = render(
+ + + + {createPortal(, document.body)} +
) + const button = view.getByRole('button', { name: 'Inner' }) + fireEvent.contextMenu(button, { clientX: 1, clientY: 2 }) + fireEvent.keyDown(button, { key: 'ContextMenu' }) + expect(open).toHaveBeenCalledTimes(2) + expect(open).toHaveBeenLastCalledWith(target('inner'), { x: 0, y: 0 }) + fireEvent.contextMenu(view.getByRole('button', { name: 'Blocked' })) + fireEvent.keyDown(view.getByRole('button', { name: 'Blocked' }), { key: 'ContextMenu' }) + for (const extra of [{ repeat: true }, { isComposing: true }, { ctrlKey: true }, { altKey: true }, { metaKey: true }, { key: 'Enter' }]) { + fireEvent.keyDown(button, { key: 'ContextMenu', ...extra }) + } + const prevented = createEvent.contextMenu(button) + prevented.preventDefault(); fireEvent(button, prevented) + expect(open).toHaveBeenCalledTimes(2) + fireEvent.contextMenu(view.getByRole('button', { name: 'Portal' }), { clientX: 4, clientY: 5 }) + expect(open).toHaveBeenCalledTimes(3) + expect(outer).not.toHaveBeenCalled() + fireEvent.keyDown(view.getByRole('button', { name: 'Native' }), { key: 'a' }) + expect(existing).toHaveBeenCalledOnce() +}) + +it('injects the hook through the root Slot and withdraws both its prop and retained handlers on unload', async () => { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) } as never) + runtime.ctx.provide('locale', { register: () => () => {}, bind: () => (key: string) => key } as never) + let retained: ContextMenuTriggerProps = {} + let received = false + await runtime.root.declare({}, ({ useContextMenu }) => { + received = typeof useContextMenu === 'function' + if (!received) return null + retained = useContextMenu().getTriggerProps(target('injected')) + return + }) + const plugin = await runtime.mount({ inject, apply }) + const view = runtime.renderRoot() + expect(received).toBe(true) + act(() => { fireEvent.contextMenu(view.getByRole('button')) }) + expect(runtime.ctx.contextMenus.active.getSnapshot()).toEqual(target('injected')) + const source = runtime.ctx.contextMenus.active + await plugin.dispose() + expect(received).toBe(false) + expect(source.getSnapshot()).toBeNull() + const detached = render() + expect(fireEvent.contextMenu(detached.getByRole('button'))).toBe(true) + expect(fireEvent.keyDown(detached.getByRole('button'), { key: 'ContextMenu' })).toBe(true) + expect(source.getSnapshot()).toBeNull() +}) diff --git a/packages/client/ui-context-menu/tsconfig.json b/packages/client/ui-context-menu/tsconfig.json new file mode 100644 index 0000000000..e12f61a4c8 --- /dev/null +++ b/packages/client/ui-context-menu/tsconfig.json @@ -0,0 +1,45 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../core/session" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../ui-slots" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-dockkit" + }, + { + "path": "../ui-layout" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../shortcuts/tsconfig.client.json" + } + ] +} diff --git a/packages/client/ui-context-menu/tsdown.config.ts b/packages/client/ui-context-menu/tsdown.config.ts new file mode 100644 index 0000000000..7aa03cebc1 --- /dev/null +++ b/packages/client/ui-context-menu/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 8f74c9dfc6..0f945d3708 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,11 +21,11 @@ en: cc4dafd1aae02468 zh: be6b67724b7ac4a3 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 08cf047cee6419bd - zh: 1f464f059753eacb + en: 9b596b668979544a + zh: 159f24dfc8715c92 /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: - en: bb1244310f5c0382 - zh: 824b84077432b559 + en: 59cd63057dfb6eeb + zh: b2e2c86e810b7bb8 /deepseek-ai-dsh-client-ui-conversation/model-experience: en: e0a05b73ba3e4318 zh: dc85ab8433bb4456 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 1fdfca0f3c..2002f10c1b 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -68,6 +68,8 @@ The existing semantic `DraftSnapshot` retains quote text and clipboard-coordinat ## Shell and standard props +Below 768px, Web view tabs align with the header's 20px left inset. Desktop and wider Web windows retain the additional 8px tab inset. + The shared image slot props keep display choices separate from durable references: `thumbnail` requests a contained attachment-list thumbnail, while `compact` requests a cropped gallery tile. An optional per-image `label` supplies the accessible display name; loading and cache identity still use the original attachment reference. `MessageImagesContentInput` adds optional complete `MessageImageLabels` for the root-scoped `conversation.images.content` Factory. Message, tool, and Factory inputs carry the view's authorized `loadImage` callback explicitly; loading and URL caching remain with the resource owner. [ui-attachment](../ui-attachment/README.md) provides this Factory and owns rendering and the lightbox. The composer uses a minimum 16px draft font on coarse-pointer devices to avoid focus-triggered browser zoom; larger font preferences still apply. @@ -182,6 +184,8 @@ The selector must be a pure function of the owner currency. Its non-null return `conversation.input.activity` hosts one control between the model selector and Send. Its `onActiveChange` callback expands that control across the toolbar and hides ordinary accessory controls and the context meter while preserving the editor and submit action. Closing the activity restores those controls with context details closed. The empty hero dock remains collapsed when it has no content. The occupant releases expansion on unmount and owns any activity-specific feedback. +Session title context gestures use the shared [context menu](../ui-context-menu/README.md) with the clicked breadcrumb’s Session. The reusable image gallery receives `getTriggerProps` from its Factory’s injected `useContextMenu` hook. + ## Model Experience diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index dd01ddf45b..b1d1c5fbd3 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -68,6 +68,8 @@ Queue 预览启用空白折叠和文档边缘 trim,保留 emoji,并使用 CS ## Shell 与标准 props +宽度小于 768px 时,Web 的 View 标签与页头的 20px 左内边距对齐。桌面客户端和较宽的 Web 窗口保留标签额外的 8px 左内边距。 + 共享图片插槽属性将展示选择与持久化引用分开:`thumbnail` 请求完整缩放的附件列表缩略图,`compact` 请求裁剪的图片方块。每张图片可通过可选的 `label` 提供无障碍展示名称;加载和缓存标识仍使用原始附件引用。`MessageImagesContentInput` 为 root 作用域的 `conversation.images.content` Factory 增加可选的完整 `MessageImageLabels`。消息、工具及 Factory 输入显式携带视图提供的授权 `loadImage` 回调;读取和 URL 缓存仍由资源所有者负责。[ui-attachment](../ui-attachment/README.zh.md) 提供该 Factory,负责渲染与灯箱。 在粗指针设备上,composer 的草稿字号至少为 16px,以避免获得焦点时浏览器自动放大;更大的字号偏好仍然生效。 @@ -182,6 +184,8 @@ selector 必须是 owner currency 的纯函数。非 null 返回值作为 `match `conversation.input.activity` 在模型选择器与发送按钮之间承载一个控件。其 `onActiveChange` 回调将控件展开至整条工具栏并隐藏普通辅助控件和上下文用量按钮,同时保留编辑器与提交按钮。关闭活动后恢复这些控件,上下文详情保持关闭。首页输入框下方没有内容时,该区域保持收起。占用者在卸载时释放展开状态,并拥有活动专属反馈。 +会话标题右键使用共享[右键菜单](../ui-context-menu/README.zh.md),目标是被点击面包屑所属会话。可复用图片库从其 Factory 注入的 `useContextMenu` hook 获取 `getTriggerProps`。 + ## 模型体验 diff --git a/packages/client/ui-conversation/package.json b/packages/client/ui-conversation/package.json index d2924b00e3..f168e7f6c8 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -36,7 +36,8 @@ "@deepseek-ai/dsh-client-ui-renderer", "@deepseek-ai/dsh-client-ui-session", "@deepseek-ai/dsh-client-ui-settings", - "@deepseek-ai/dsh-client-ui-workspace" + "@deepseek-ai/dsh-client-ui-workspace", + "@deepseek-ai/dsh-client-ui-context-menu" ], "platform": "web" } @@ -97,7 +98,8 @@ "@deepseek-ai/dsh-settings": "workspace:*", "@deepseek-ai/dsh-client-shortcuts": "workspace:*", "@deepseek-ai/dsh-client-product-analytics": "workspace:*", - "@deepseek-ai/dsh-message-quotes": "workspace:*" + "@deepseek-ai/dsh-message-quotes": "workspace:*", + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index b3c0d3bcd0..3328e1e5da 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -1,3 +1,4 @@ +import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Registers the target-neutral Conversation assembly, shell, input, and docks. */ import type {} from '@deepseek-ai/dsh-client-product-analytics/client' import type { Context } from '@deepseek-ai/cordis' diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index caec4849b4..369f562a7b 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -475,6 +475,7 @@ export interface ConversationViewActionsOwnerProps { /** Business callbacks injected into the strict Session header. */ export interface ConversationSessionHeaderInjected { + /** Open the clicked title's actions. */ /** Package-owned View roster source bound only for the Conversation header. */ readonly hooks: { readonly conversationViews: ObservableSnapshot diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index d4f06accc5..7a39200c30 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -1,3 +1,4 @@ +import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Browser Conversation assemble core, React adapter, shell, input, and text projection plugin. */ export type {} from './user-text/session-reference-rule.ts' diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css index ac6cb69f70..bf1a1e8d02 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.module.css @@ -224,6 +224,12 @@ padding-left: 8px; } +@media (max-width: 767px) { + :global(html:not([data-platform])) .tabs { + padding-left: 0; + } +} + .viewTabs { display: flex; flex-wrap: wrap; diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx index deaddcf769..14602cbca0 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationSession.tsx @@ -107,8 +107,9 @@ function equalBreadcrumbs(left: readonly Breadcrumb[], right: readonly Breadcrum */ export function ConversationSessionHeader({ sessionId, hideChrome, useSessions, useConversationViews, useStore, - renderSlot, open, selectView, setPinned, t, useEntryPins, useEntryActions, + renderSlot, open, useContextMenu, selectView, setPinned, t, useEntryPins, useEntryActions, }: ConversationSessionHeaderProps) { + const { getTriggerProps } = useContextMenu() const tabs = useConversationViews(value => value) const selectedId = useStore(s => s.view) const active = resolveActiveView(tabs, selectedId) @@ -176,7 +177,7 @@ export function ConversationSessionHeader({ ...last ? {} : { openTitle: () => { open(summary.id) } }, } return ( - + {index > 0 && /} {lineage ? summary.subagent diff --git a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx index 523fcffaae..d968bdc4d8 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { render, cleanup } from '@testing-library/react' import { $getRoot, $isTextNode, PASTE_COMMAND } from 'lexical' import { createUserTextFixture } from './user-text-component-fixture.client.tsx' @@ -103,6 +104,8 @@ async function bench(renderQuote = false) { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) + runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) await runtime.root.declare({ 'main': { kind: 'keyed', scope: 'root' }, 'quote-probe': { kind: 'single', scope: 'session' }, diff --git a/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx b/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx index a7b0bfdbdf..154d31ec9f 100644 --- a/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { describe, expect, it, vi } from 'vitest' import { SlotTestRuntime, stubConfigForm, usePinnedBrowserLanguages, @@ -25,6 +26,8 @@ async function bench(options: { declareConversation?: boolean } = {}) { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) + runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) if (options.declareConversation !== false) { await runtime.root.declare({ 'main': { kind: 'keyed', scope: 'root' }, diff --git a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx index e4c2a2c037..c8e96efdbc 100644 --- a/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx +++ b/packages/client/ui-conversation/tests/assembly-surfaces.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { apply as applyMenus, inject as injectMenus } from '@deepseek-ai/dsh-client-ui-context-menu/client' /** Conversation assembly acceptance independent of Tool presentation. */ import './control-row-dom.ts' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -86,6 +87,8 @@ async function bench(opts?: { blank?: boolean }) { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) + runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) await runtime.sessions.add({ id: SID, summary: { title: 'S', displayTitle: 'S', cwd: '/proj' }, @@ -109,6 +112,8 @@ describe('resident composer', () => { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) + runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) await runtime.root.declare(LAYOUT_CHILDREN, AppRoot) await runtime.mount({ inject: [...inject], apply }) runtime.slots.register({ name: 'conversation.hero.workspace' }, WorkspaceProbe) @@ -136,6 +141,8 @@ describe('resident composer', () => { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) + runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) await runtime.workspaces.update((draft) => { draft.items = [{ workspaceId: 'w1', title: 'Proj', path: '/proj', sessionIds: [SID] }] as never }) @@ -203,6 +210,8 @@ describe('prompt rejection through the assembled composer', () => { const locale = new LocaleRuntime(runtime.ctx) runtime.ctx.provide('locale', locale) runtime.slots.installLocale(locale) + runtime.ctx.provide('shortcuts', { catalog: createSnapshotStore([]) }) + await runtime.mount({ inject: [...injectMenus], apply: applyMenus }) const prompt = vi.fn(async () => ({ ok: false, error: new RemoteError('session/agent-busy', 'prompt rejected before acceptance', { reason: 'busy' }), diff --git a/packages/client/ui-conversation/tests/enter-behavior-row.client.spec.tsx b/packages/client/ui-conversation/tests/enter-behavior-row.client.spec.tsx index f4b80c891c..3106eeb495 100644 --- a/packages/client/ui-conversation/tests/enter-behavior-row.client.spec.tsx +++ b/packages/client/ui-conversation/tests/enter-behavior-row.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' @@ -47,6 +48,7 @@ function mount() { useResource, useWorkspaces: emptyWorkspaces(), ...allowAllAccess, + useContextMenu: contextMenuHook(), useBusyEnter: bindSnapshotSelector(policy.busyEnter), setBusyEnter, t: makeTranslate(en), diff --git a/packages/client/ui-conversation/tests/header-styles.client.spec.ts b/packages/client/ui-conversation/tests/header-styles.client.spec.ts index aa9a983654..4be70c648d 100644 --- a/packages/client/ui-conversation/tests/header-styles.client.spec.ts +++ b/packages/client/ui-conversation/tests/header-styles.client.spec.ts @@ -5,6 +5,12 @@ import { describe, expect, it } from 'vitest' const css = readFileSync(new URL('../src/client/skeleton/ConversationRoot.module.css', import.meta.url), 'utf8') describe('conversation header geometry', () => { + it('removes the extra tab inset only in narrow Web windows', () => { + const narrow = /@media \(max-width: 767px\) \{([\s\S]*?)\n\}/.exec(css)?.[1] + expect(narrow).toContain(':global(html:not([data-platform])) .tabs') + expect(narrow).toContain('padding-left: 0') + }) + it('keeps the single-line header at the shared 76px height', () => { expect(css.match(/\.header\s*\{([^}]*)\}/)?.[1]).toContain('min-height: 76px') expect(css.match(/\.viewTabs\s*\{([^}]*)\}/)?.[1]).toContain('min-height: 25px') diff --git a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx index a657abf806..da4c7dc61b 100644 --- a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' // InputBar behavior over the editor + submit-machine wiring: Enter-send // semantics (IME guard, Shift newline, busy Enter policy, Ctrl/Meta steering, // repeat suppression), running semantics (input stays free; continuable @@ -195,6 +196,7 @@ function bench(over?: BenchOptions) { items: [], archivedSessionIds: [], pinnedSessionIds: [], state: 'idle', phase: 'ready', error: null, })), ...allowAllAccess, + useContextMenu: contextMenuHook(), useAccess: endpoint => !(over?.deniedEndpoints ?? []).includes(endpoint), useProjection: ((key: string, selector?: (v: unknown) => unknown) => (selector ?? (v => v))(key === 'plan' diff --git a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx index 6a18cede9a..517848498a 100644 --- a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' /** * Impact-matrix projection tests (row by row): what each * phase projects onto the InputBar — enter routing, visuals (command chip / @@ -67,6 +68,7 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled baselinesReady: true, recentWorkspaceId: undefined, })), ...allowAllAccess, + useContextMenu: contextMenuHook(), useProjection: (() => undefined), useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), useInput: bindSnapshotSelector(shell.state), diff --git a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx index 380097b5d1..2129c605d2 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' /** * Scenario-chain integration (scenarios A/C/D/H/I): the real per-session * InputTriggerController pipeline over a real session scope (Client Sessions over @@ -169,6 +170,7 @@ async function scopedBench(register?: (inputTriggers: InputTriggerService) => vo baselinesReady: true, recentWorkspaceId: undefined, })), ...allowAllAccess, + useContextMenu: contextMenuHook(), useProjection: (() => undefined), useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), useInput: bindSnapshotSelector(shell.state), diff --git a/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx index 4583814093..44878bbc18 100644 --- a/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx +++ b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' /** * QueueDock rendering and operations: authoritative rows, inline editing, * collapse state, removal, QueueDock Steer, failure notices, and live retirement. @@ -118,6 +119,7 @@ function kitFor(snapshot: SessionSnapshot, injected: Partial ), useWorkspaces: (() => { throw new Error('unused') }) as never, ...allowAllAccess, + useContextMenu: contextMenuHook(), useProjection: (() => undefined) as never, useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())), useChat: (() => { throw new Error('unused') }) as QueueDockProps['useChat'], diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index 2f7a1fd979..5f07662274 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import type { GlobalStandardProps, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createContext, useContext, type ReactNode } from 'react' @@ -235,7 +236,7 @@ function mount( useTrajectory={useTrajectory} useSessions={props.useSessions} usePanelInfo={props.usePanelInfo} - useResource={useResource} + useContextMenu={contextMenuHook()} useResource={useResource} useSessionStatus={useSessionStatus} useSessionRetainInfo={() => undefined} useWorkspaces={props.useWorkspaces} @@ -265,7 +266,7 @@ function mount( useTrajectory={useTrajectory} useSessions={props.useSessions} usePanelInfo={props.usePanelInfo} - useResource={useResource} + useContextMenu={contextMenuHook()} useResource={useResource} useSessionStatus={useSessionStatus} useSessionRetainInfo={() => undefined} useWorkspaces={props.useWorkspaces} @@ -289,7 +290,7 @@ function mount( children} - useResource={useResource} + useContextMenu={contextMenuHook()} useResource={useResource} useSession={useSession} useConversation={useConversation} useSessions={props.useSessions} @@ -353,6 +354,7 @@ function mount( useTrajectory, useSessions: bindSnapshotSelector(sessions), usePanelInfo: selector => selector({ activePanelId: null }), + useContextMenu: contextMenuHook(), useResource, useSessionStatus, useSessionRetainInfo: () => undefined, @@ -386,6 +388,7 @@ function mount( useSessions: bindSnapshotSelector(sessions), useSessionStatus, useSessionRetainInfo: () => undefined, + useContextMenu: contextMenuHook(), useResource, useWorkspaces: bindSnapshotSelector(workspaces), ...allowAllAccess, diff --git a/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx b/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx index f4970b398d..c5383f3091 100644 --- a/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx +++ b/packages/client/ui-conversation/tests/user-text-component-fixture.client.tsx @@ -2,7 +2,7 @@ import { Context } from '@deepseek-ai/cordis' import { createElement, type ComponentProps, type ReactNode } from 'react' import { onTestFinished } from 'vitest' -import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { bindSnapshotSelector, contextMenuHook, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import type { UserTextInput, UserTextNodeOwnerProps } from '../src/client/contract/slots.ts' import type { UserTextNode } from '../src/client/contract/user-text.ts' @@ -62,7 +62,7 @@ export function createUserTextFixture(actions: UserTextFixtureActions = {}): (in case 'secret': return createElement(SecretText, { ...owner, t } as ComponentProps) case 'text': return createElement(PlainUserText, owner as ComponentProps) case 'session': return createElement(SessionReference, owner as ComponentProps) - case 'file': return createElement(FileReference, { ...owner, openFile, t } as ComponentProps) + case 'file': return createElement(FileReference, { ...owner, openFile, t, useContextMenu: contextMenuHook(), resolveFilePath: (path: string) => path } as ComponentProps) case 'folder': return createElement(FolderReference, owner as ComponentProps) case 'skill': return createElement(SkillReference, { ...owner, openSkill } as ComponentProps) case 'command': return createElement(GoalCommandReference, owner as ComponentProps) diff --git a/packages/client/ui-conversation/tsconfig.client.json b/packages/client/ui-conversation/tsconfig.client.json index 0339eebbe6..0187cf5d72 100644 --- a/packages/client/ui-conversation/tsconfig.client.json +++ b/packages/client/ui-conversation/tsconfig.client.json @@ -104,6 +104,9 @@ }, { "path": "../product-analytics/tsconfig.client.json" + }, + { + "path": "../ui-context-menu" } ], "exclude": [ diff --git a/packages/client/ui-deliverables/README.i18n.yaml b/packages/client/ui-deliverables/README.i18n.yaml index ff6839eee5..675bcff105 100644 --- a/packages/client/ui-deliverables/README.i18n.yaml +++ b/packages/client/ui-deliverables/README.i18n.yaml @@ -33,8 +33,8 @@ en: 7ee5ee783902662c zh: fdf2c244fb22b8ab /deepseek-ai-dsh-client-ui-deliverables/further-exploration: - en: 476b59e8671db982 - zh: b3d0495a03e8940a + en: 98eda99fafcb04b9 + zh: e6a21254c0383f48 /deepseek-ai-dsh-client-ui-deliverables/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 diff --git a/packages/client/ui-deliverables/README.md b/packages/client/ui-deliverables/README.md index 6727c12776..0632574d83 100644 --- a/packages/client/ui-deliverables/README.md +++ b/packages/client/ui-deliverables/README.md @@ -86,6 +86,8 @@ Read these pages when the deliverables surface is not enough. They move from the ----- +Delivery cards and known inline file mentions expose a [context menu](../ui-context-menu/README.md) for their declared Session file, preserving the original path and optional line. + ## Model Experience diff --git a/packages/client/ui-deliverables/README.zh.md b/packages/client/ui-deliverables/README.zh.md index 45484627dd..2951888e72 100644 --- a/packages/client/ui-deliverables/README.zh.md +++ b/packages/client/ui-deliverables/README.zh.md @@ -86,6 +86,8 @@ Node 半部提供经过身份验证的原生文件打开;共用指导由[模 ----- +交付卡片和已知行内文件引用为其声明的会话文件提供[右键菜单](../ui-context-menu/README.zh.md),保留原始路径和可选行号。 + ## 模型体验 diff --git a/packages/client/ui-deliverables/package.json b/packages/client/ui-deliverables/package.json index e64e93ae83..4172b1f4c2 100644 --- a/packages/client/ui-deliverables/package.json +++ b/packages/client/ui-deliverables/package.json @@ -37,7 +37,8 @@ "@deepseek-ai/dsh-client-ui-renderer", "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-tool", - "@deepseek-ai/dsh-client-ui-settings" + "@deepseek-ai/dsh-client-ui-settings", + "@deepseek-ai/dsh-client-ui-context-menu" ], "platform": "web" } @@ -80,7 +81,8 @@ "@deepseek-ai/dsh-fs-local": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-sandbox-policy": "workspace:*", - "@deepseek-ai/dsh-client-ui-settings": "workspace:*" + "@deepseek-ai/dsh-client-ui-settings": "workspace:*", + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-deliverables/src/client/Deliverables.tsx b/packages/client/ui-deliverables/src/client/Deliverables.tsx index 544e7a82b2..89cfa24afa 100644 --- a/packages/client/ui-deliverables/src/client/Deliverables.tsx +++ b/packages/client/ui-deliverables/src/client/Deliverables.tsx @@ -66,11 +66,12 @@ export function DeliverablesTail(props: PropsRuntime<'conversation.chat.turnTail * @returns the closing turn's file rows. */ export function Deliverables({ - matched, openFile, t, sessionId, useSessions, openPresented, openChangesReview, usePresentedOpen, usePresentedHost, + matched, openFile, useContextMenu, t, sessionId, useSessions, openPresented, openChangesReview, usePresentedOpen, usePresentedHost, useChangesDiff, loadChangesDiff, useChangesSummary, reloadPresentedHost, loadChangesSummary, useShowCodeDiff, renderSlot, }: Pick & { matched: DeliverablesMatch -} & PropsLocale & Pick & Pick & InjectFace & PropsRenderSlots<'deliverables.file.actions'>) { +} & PropsLocale & Pick & Pick & InjectFace & PropsRenderSlots<'deliverables.file.actions'>) { + const { getTriggerProps } = useContextMenu() const [expanded, setExpanded] = useState(false) const showCodeDiff = useShowCodeDiff(value => value) const cwd = useSessions(state => state.byId[sessionId]?.cwd) @@ -109,6 +110,7 @@ export function Deliverables({ phase={states[presentedFileUrl(sessionId, file.seq, file.index)]} host={host === 'error' ? null : host} t={t} onPreview={() => { openFile(file.path) }} + contextMenuProps={getTriggerProps({ kind: 'file', value: { sessionId, path: file.path } })} actions={renderSlot('deliverables.file.actions', { actionUrl: presentedFileUrl(sessionId, file.seq, file.index), available: host !== null && host !== 'error' && host.available, diff --git a/packages/client/ui-deliverables/src/client/PresentedFileCard.tsx b/packages/client/ui-deliverables/src/client/PresentedFileCard.tsx index b40bfa40a0..6e71d25d15 100644 --- a/packages/client/ui-deliverables/src/client/PresentedFileCard.tsx +++ b/packages/client/ui-deliverables/src/client/PresentedFileCard.tsx @@ -1,3 +1,4 @@ +import type { ContextMenuTriggerProps } from '@deepseek-ai/dsh-client-ui-context-menu/client' /** File identity, Sidebar preview, and contributed native actions for one delivery. */ import type { ReactNode } from 'react' import { resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' @@ -19,12 +20,13 @@ function cardDescription(description: string | undefined, fallback: string): str * @param props - durable file metadata, Sidebar preview, Host capabilities, gesture status, and localized copy. * @returns the file card and its anchored action menu. */ -export function PresentedFileCard({ file, cwd, phase, host, onPreview, actions, t }: { +export function PresentedFileCard({ file, cwd, phase, host, onPreview, contextMenuProps, actions, t }: { file: PresentedPath cwd: string | undefined phase: PresentedOpenPhase | undefined host: PresentedHost | null onPreview: () => void + contextMenuProps: ContextMenuTriggerProps actions: ReactNode } & PropsLocale) { const reveal = host?.fileManager ?? 'directory' @@ -36,7 +38,8 @@ export function PresentedFileCard({ file, cwd, phase, host, onPreview, actions, : reveal === 'directory' && phase === 'revealError' ? 'presented.directoryError' : `presented.${phase}`) return
) + fireEvent.contextMenu(trigger.getByRole('button'), { clientX: 41, clientY: 52 }) + trigger.unmount() + expect(vi.spyOn(ctx.contextMenus, 'open')).toHaveBeenLastCalledWith({ kind: 'file', value: { sessionId: 'child-session', path: 'out/report.docx' } }, { x: 41, y: 52 }) mention?.open() } } @@ -1014,6 +1025,8 @@ describe('presented files', () => { const props = openProps() props.openPresented.mockResolvedValue({ kind: 'opened' }) const view = render() + fireEvent.contextMenu(view.getByRole('button', { name: 'Preview report-0.docx in sidebar' }), { clientX: 18, clientY: 29 }) + expect(props.openMenu).toHaveBeenCalledWith({ kind: 'file', value: { sessionId: 'child-session', path: 'report-0.docx' } }, { x: 18, y: 29 }) expect(view.container.querySelectorAll('[data-presented-file]')).toHaveLength(4) const expand = view.getByRole('button', { name: 'Show all 8 delivered files' }) expect(expand.getAttribute('aria-expanded')).toBe('false') diff --git a/packages/client/ui-deliverables/tests/presented-file-card.client.spec.tsx b/packages/client/ui-deliverables/tests/presented-file-card.client.spec.tsx index 192fb447de..0b009d5915 100644 --- a/packages/client/ui-deliverables/tests/presented-file-card.client.spec.tsx +++ b/packages/client/ui-deliverables/tests/presented-file-card.client.spec.tsx @@ -2,20 +2,25 @@ /** Explicit file actions preserve their destination, availability, and independent failure state. */ import { cleanup, fireEvent, render } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { contextMenuHook, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { PresentedFileCard } from '../src/client/PresentedFileCard.tsx' import { en, zh } from '../src/client/locales.ts' afterEach(cleanup) -const props = () => ({ - cwd: undefined, - file: { path: 'out/report.pdf', description: 'Final report', seq: 4, index: 1 }, - host: { name: 'remote-desktop', available: true, fileManager: 'finder' as const }, - phase: undefined, - onPreview: vi.fn(), - actions: , - t: makeTranslate(en), -}) +const props = () => { + const onMenu = vi.fn() + return { + cwd: undefined, + file: { path: 'out/report.pdf', description: 'Final report', seq: 4, index: 1 }, + host: { name: 'remote-desktop', available: true, fileManager: 'finder' as const }, + phase: undefined, + onPreview: vi.fn(), + onMenu, contextMenuProps: contextMenuHook((_target, point) => { onMenu(point) })() + .getTriggerProps({ kind: 'image', value: { url: 'unused' } }), + actions: , + t: makeTranslate(en), + } +} it('localizes reveal failures and restores the description when progress clears', () => { const p = props() const view = render() @@ -66,6 +71,8 @@ it('renders the supplied action independently from the card preview', () => { fireEvent.click(view.getByRole('button', { name: 'Native file action' })) expect(native).toHaveBeenCalledOnce() expect(p.onPreview).not.toHaveBeenCalled() + fireEvent.contextMenu(view.getByRole('button', { name: 'Preview out/report.pdf in sidebar' }), { clientX: 26, clientY: 37 }) + expect(p.onMenu).toHaveBeenCalledWith({ x: 26, y: 37 }) fireEvent.click(view.getByRole('button', { name: 'Preview out/report.pdf in sidebar' })) expect(p.onPreview).toHaveBeenCalledOnce() }) diff --git a/packages/client/ui-deliverables/tsconfig.client.json b/packages/client/ui-deliverables/tsconfig.client.json index 4fe248edd6..bd78605122 100644 --- a/packages/client/ui-deliverables/tsconfig.client.json +++ b/packages/client/ui-deliverables/tsconfig.client.json @@ -68,6 +68,9 @@ }, { "path": "../../util/workspace-path" + }, + { + "path": "../ui-context-menu" } ] } diff --git a/packages/client/ui-dockkit/src/components/DockSurface.tsx b/packages/client/ui-dockkit/src/components/DockSurface.tsx index 846a4b75e8..36ec07ca0b 100644 --- a/packages/client/ui-dockkit/src/components/DockSurface.tsx +++ b/packages/client/ui-dockkit/src/components/DockSurface.tsx @@ -9,9 +9,9 @@ * drop target changes nothing. */ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' -import type { ReactNode } from 'react' +import type { ReactNode, HTMLAttributes } from 'react' import type { DockIntents, DockLabels, TabMenuExtras, TabRenderer } from '../contract/adapter.ts' -import type { LayoutState, PaneId, SplitId, TabId } from '../contract/types.ts' +import type { LayoutState, PaneId, SplitId, TabId, TabRecord } from '../contract/types.ts' import { clampSizes, FLOAT_DEFAULT_SIZE, MIN_PANE_FRACTION } from '../engine/constraints.ts' import { getSplit, topRightPaneId } from '../engine/tree.ts' import type { DropTarget, HalvesFit } from '../engine/geometry.ts' @@ -63,7 +63,11 @@ export interface DockSurfaceProps { * slot, and nothing outside that embedder is expected to supply it. */ readonly renderTabTitle?: TabRenderer - /** Extra items for a tab's context menu; omit for the kit's own item only. */ + /** Whether the embedder popup is preparing or visible; suppresses tab tooltips. */ + readonly tabMenuOpen?: boolean | undefined + /** Override the kit popup; the embedder owns rendering and dismissal. */ + readonly getTabTriggerProps?: ((tab: TabRecord, paneId: PaneId, handlers?: Pick, 'onContextMenu' | 'onKeyDown' | 'tabIndex'>) => Pick, 'onContextMenu' | 'onKeyDown' | 'tabIndex'>) | undefined + /** Extra rows for the kit popup; ignored when getTabTriggerProps is supplied. */ readonly renderTabMenuItems?: TabMenuExtras /** * Surface-wide controls, drawn at the far end of the top-right pane's tab @@ -169,7 +173,8 @@ function sameSizes(a: readonly number[], b: readonly number[]): boolean { /** The split tree and the gestures over it. */ function Surface({ - state, canSplit, canAddTab, canCloseTab, intents, labels, renderTab, renderTabTitle, renderTabMenuItems, chrome, onRoom, + state, canSplit, canAddTab, canCloseTab, intents, labels, renderTab, renderTabTitle, renderTabMenuItems, + getTabTriggerProps, tabMenuOpen, chrome, onRoom, draw, dropZones = 'edges', minPaneFraction = MIN_PANE_FRACTION, hideSplitWhenBlocked = false, }: DockSurfaceProps & { readonly draw: (callbacks: PaneCallbacks, preview: SizePreview | undefined) => ReactNode }): ReactNode { @@ -291,6 +296,7 @@ function Surface({ renderTab, renderTabTitle, renderTabMenuItems, + getTabTriggerProps, tabMenuOpen, chromePaneId: topRightPaneId(state), chrome, } diff --git a/packages/client/ui-dockkit/src/components/TabPanel.tsx b/packages/client/ui-dockkit/src/components/TabPanel.tsx index df0e39bdb4..a7d2e721ea 100644 --- a/packages/client/ui-dockkit/src/components/TabPanel.tsx +++ b/packages/client/ui-dockkit/src/components/TabPanel.tsx @@ -22,6 +22,7 @@ * `canAddTab` allows), the pane's split control, and the embedder's chrome keep * their width and their place at the strip's end. */ +import type { KeyboardEvent } from 'react' import { Fragment, useLayoutEffect, useRef, useState } from 'react' import type { ReactNode, RefObject } from 'react' import clsx from 'clsx' @@ -303,6 +304,13 @@ export function TabStrip({ state, pane, callbacks, offsets }: TabStripProps): Re // A pane's lone unclosable chip is a label, not a choice: there is // no other tab to select against and nothing to do to it. const quiet = !closable && pane.tabs.length === 1 + const onKeyDown = (event: KeyboardEvent) => { + if (event.target !== event.currentTarget) return + if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.nativeEvent.isComposing) return + const next = chipToFocus(event.key, pane.tabs, tabId) + if (next !== undefined) { event.preventDefault(); focusChip(next); return } + if (selects(event.key)) { event.preventDefault(); activate(tabId) } + } return ( {(index > 0 || stripIndex === index) && ( @@ -350,30 +358,18 @@ export function TabStrip({ state, pane, callbacks, offsets }: TabStripProps): Re event.stopPropagation() activate(tabId) }} - onKeyDown={(event) => { - // Keys on the chip's nested close control are that control's. - if (event.target !== event.currentTarget) return - if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.nativeEvent.isComposing) return - const next = chipToFocus(event.key, pane.tabs, tabId) - if (next !== undefined) { - event.preventDefault() - focusChip(next) - return - } - if (selects(event.key)) { - event.preventDefault() - activate(tabId) - } - }} - onContextMenu={(event) => { - event.preventDefault() - const anchor = event.currentTarget - setMenu(current => current?.tabId === tabId ? undefined : { tabId, anchor }) + {...callbacks.getTabTriggerProps?.(tab, pane.id, { onKeyDown, tabIndex: selected ? 0 : -1 }) ?? { + onKeyDown, + onContextMenu: (event) => { + event.preventDefault(); event.stopPropagation() + const anchor = event.currentTarget + setMenu(current => current?.tabId === tabId ? undefined : { tabId, anchor }) + }, }} > {callbacks.renderTabTitle?.(tab) ?? tab.title} {closable && ( - +
) : null} diff --git a/packages/client/ui-plugin-manager/src/client/locales.ts b/packages/client/ui-plugin-manager/src/client/locales.ts index 98bcf3ac3e..6b31b7ffa8 100644 --- a/packages/client/ui-plugin-manager/src/client/locales.ts +++ b/packages/client/ui-plugin-manager/src/client/locales.ts @@ -215,11 +215,13 @@ export const zh = { installEnableNow: '立即启用', installDetailsShow: '查看安装详情', installDetailsHide: '收起安装详情', + installDetailsNoOutput: '本次安装详情没有收到终端输出', installVersion: '版本 {version}', installSubjectPath: '本地目录', installSubjectGit: 'Git 仓库', installSubjectTarball: '压缩包', installLocation: '安装位置:{dir}', + installLogPath: '完整日志:{path}', installRetry: '重试', installChangeRegistry: '更换安装源', installAttempt: '{previous} 不可用,正在改用 {registry} 重试(第 {index} 个源,共 {total} 个)', @@ -236,7 +238,8 @@ export const zh = { installFailureIntegrity: '下载的安装包校验失败', installFailureTimeout: '安装超时', installFailurePnpmMissing: '没有找到 pnpm,无法安装', - installFailureGeneric: '安装过程中出错,原因见安装详情', + installFailureGeneric: '安装命令失败,原因见安装详情', + installFailedEnabling: '安装已完成,失败发生在启用插件时', terminalCommandLine: '命令第 {n} 行', terminalRunning: '运行中', terminalFailed: '失败', @@ -510,11 +513,13 @@ export const en = { installEnableNow: 'Enable now', installDetailsShow: 'Show install details', installDetailsHide: 'Hide install details', + installDetailsNoOutput: 'No terminal output from this install reached the details', installVersion: 'Version {version}', installSubjectPath: 'Local directory', installSubjectGit: 'Git repository', installSubjectTarball: 'Tarball', installLocation: 'Installs into {dir}', + installLogPath: 'Full log: {path}', installRetry: 'Retry', installChangeRegistry: 'Change registry', installAttempt: '{previous} could not serve the package; retrying through {registry} (registry {index} of {total})', @@ -531,7 +536,8 @@ export const en = { installFailureIntegrity: 'The downloaded package failed its integrity check', installFailureTimeout: 'The install timed out', installFailurePnpmMissing: 'pnpm was not found, so nothing can be installed', - installFailureGeneric: 'Something went wrong during the install; the details say what', + installFailureGeneric: 'The install command failed; the details say why', + installFailedEnabling: 'The install finished; enabling the plugin is what failed', terminalCommandLine: 'Command line {n}', terminalRunning: 'Running', terminalFailed: 'Failed', @@ -803,11 +809,13 @@ export const ja = { 'installEnableNow': '今すぐ有効化', 'installDetailsShow': 'インストール詳細を表示', 'installDetailsHide': 'インストール詳細を隠す', + 'installDetailsNoOutput': 'このインストールのターミナル出力は詳細に届きませんでした', 'installVersion': 'バージョン {version}', 'installSubjectPath': 'ローカルディレクトリ', 'installSubjectGit': 'Gitリポジトリ', 'installSubjectTarball': 'Tarball', 'installLocation': '{dir} にインストール', + 'installLogPath': 'ログ全体: {path}', 'installRetry': '再試行', 'installChangeRegistry': 'レジストリを変更', 'installAttempt': '{previous} ではパッケージを提供できませんでした。{registry} 経由で再試行しています(レジストリ {index}/{total})', @@ -824,7 +832,8 @@ export const ja = { 'installFailureIntegrity': 'ダウンロードしたパッケージの整合性チェックに失敗しました', 'installFailureTimeout': 'インストールがタイムアウトしました', 'installFailurePnpmMissing': 'pnpmが見つからないため、インストールできません', - 'installFailureGeneric': 'インストール中に問題が発生しました。詳細をご確認ください', + 'installFailureGeneric': 'インストールコマンドに失敗しました。詳細をご確認ください', + 'installFailedEnabling': 'インストールは完了しており、失敗したのはプラグインの有効化です', 'terminalCommandLine': 'コマンドライン {n}', 'terminalRunning': '実行中', 'terminalFailed': '失敗', @@ -1095,11 +1104,13 @@ export const es = { installEnableNow: 'Habilitar ahora', installDetailsShow: 'Mostrar detalles de instalación', installDetailsHide: 'Ocultar detalles de instalación', + installDetailsNoOutput: 'La salida de terminal de esta instalación no llegó a los detalles', installVersion: 'Versión {version}', installSubjectPath: 'directorio local', installSubjectGit: 'repositorio git', installSubjectTarball: 'bola de tar', installLocation: 'Se instala en {dir}', + installLogPath: 'Registro completo: {path}', installRetry: 'Reintentar', installChangeRegistry: 'Cambiar registro', installAttempt: '{previous} no pudo entregar el paquete; reintentando a través de {registry} (registro {index} de {total})', @@ -1116,7 +1127,8 @@ export const es = { installFailureIntegrity: 'El paquete descargado no pasó la verificación de integridad', installFailureTimeout: 'La instalación expiró', installFailurePnpmMissing: 'No se encontró pnpm, por lo que no se puede instalar nada.', - installFailureGeneric: 'Algo salió mal durante la instalación; los detalles dicen lo que', + installFailureGeneric: 'El comando de instalación falló; los detalles dicen por qué', + installFailedEnabling: 'La instalación finalizó; lo que falló fue la activación del complemento', terminalCommandLine: 'Línea de comando {n}', terminalRunning: 'corriendo', terminalFailed: 'Fallido', @@ -1387,11 +1399,13 @@ export const fr = { installEnableNow: 'Activer maintenant', installDetailsShow: "Afficher les détails de l'installation", installDetailsHide: "Masquer les détails de l'installation", + installDetailsNoOutput: "Aucune sortie de terminal de cette installation n'est parvenue aux détails", installVersion: 'Version {version}', installSubjectPath: 'Annuaire local', installSubjectGit: 'Dépôt Git', installSubjectTarball: 'Tarball', installLocation: "S'installe dans {dir}", + installLogPath: 'Journal complet : {path}', installRetry: 'Réessayer', installChangeRegistry: 'Changer de registre', installAttempt: "{previous} n'a pas pu servir le package ; nouvelle tentative via {registry} (registre {index} de {total})", @@ -1408,7 +1422,8 @@ export const fr = { installFailureIntegrity: "Le package téléchargé a échoué à sa vérification d'intégrité", installFailureTimeout: "L'installation a expiré", installFailurePnpmMissing: "pnpm n'a pas été trouvé, donc rien ne peut être installé", - installFailureGeneric: "Quelque chose s'est mal passé lors de l'installation ; les détails disent quoi", + installFailureGeneric: "La commande d'installation a échoué ; les détails expliquent pourquoi", + installFailedEnabling: "L'installation est terminée ; c'est l'activation du plugin qui a échoué", terminalCommandLine: 'Ligne de commande {n}', terminalRunning: 'Courir', terminalFailed: 'Échec', @@ -1679,11 +1694,13 @@ export const de = { installEnableNow: 'Jetzt aktivieren', installDetailsShow: 'Installationsdetails anzeigen', installDetailsHide: 'Installationsdetails ausblenden', + installDetailsNoOutput: 'Die Terminalausgabe dieser Installation hat die Details nicht erreicht', installVersion: 'Version {version}', installSubjectPath: 'Lokales Verzeichnis', installSubjectGit: 'Git-Repository', installSubjectTarball: 'Tarball', installLocation: 'Wird in {dir} installiert', + installLogPath: 'Vollständiges Protokoll: {path}', installRetry: 'Erneut versuchen', installChangeRegistry: 'Registrierung ändern', installAttempt: '{previous} konnte das Paket nicht bereitstellen; erneuter Versuch über {registry} (Registrierung {index} von {total})', @@ -1700,7 +1717,8 @@ export const de = { installFailureIntegrity: 'Das heruntergeladene Paket hat die Integritätsprüfung nicht bestanden', installFailureTimeout: 'Bei der Installation ist eine Zeitüberschreitung aufgetreten', installFailurePnpmMissing: 'pnpm wurde nicht gefunden, daher kann nichts installiert werden', - installFailureGeneric: 'Bei der Installation ist ein Fehler aufgetreten. Die Details sagen was', + installFailureGeneric: 'Der Installationsbefehl ist fehlgeschlagen. Die Details sagen warum', + installFailedEnabling: 'Die Installation wurde abgeschlossen; das Aktivieren des Plugins ist fehlgeschlagen', terminalCommandLine: 'Befehlszeile {n}', terminalRunning: 'Laufen', terminalFailed: 'Fehlgeschlagen', @@ -1971,11 +1989,13 @@ export const ru = { installEnableNow: 'Включить сейчас', installDetailsShow: 'Показать детали установки', installDetailsHide: 'Скрыть сведения об установке', + installDetailsNoOutput: 'Вывод терминала этой установки не дошёл до подробностей', installVersion: 'Версия {version}', installSubjectPath: 'Локальный каталог', installSubjectGit: 'Git-репозиторий', installSubjectTarball: 'Тарбол', installLocation: 'Устанавливается в {dir}', + installLogPath: 'Полный журнал: {path}', installRetry: 'Повторить', installChangeRegistry: 'Изменить реестр', installAttempt: '{previous} не смог обслужить пакет; повторная попытка через {registry} (реестр {index} из {total})', @@ -1992,7 +2012,8 @@ export const ru = { installFailureIntegrity: 'Загруженный пакет не прошел проверку целостности.', installFailureTimeout: 'Время установки истекло', installFailurePnpmMissing: 'pnpm не найден, поэтому ничего установить невозможно', - installFailureGeneric: 'Во время установки что-то пошло не так; детали говорят о чем', + installFailureGeneric: 'Команда установки завершилась ошибкой; детали объясняют причину', + installFailedEnabling: 'Установка завершена; ошибка возникла при включении плагина', terminalCommandLine: 'Командная строка {n}', terminalRunning: 'Бег', terminalFailed: 'Не удалось', @@ -2263,11 +2284,13 @@ export const pt = { installEnableNow: 'Ativar agora', installDetailsShow: 'Mostrar detalhes da instalação', installDetailsHide: 'Ocultar detalhes de instalação', + installDetailsNoOutput: 'A saída de terminal desta instalação não chegou aos detalhes', installVersion: 'Versão {version}', installSubjectPath: 'Diretório local', installSubjectGit: 'Repositório Git', installSubjectTarball: 'Tarball', installLocation: 'Instala em {dir}', + installLogPath: 'Registro completo: {path}', installRetry: 'Tentar novamente', installChangeRegistry: 'Alterar registro', installAttempt: '{previous} não pôde entregar o pacote; tentando novamente através de {registry} (registro {index} de {total})', @@ -2284,7 +2307,8 @@ export const pt = { installFailureIntegrity: 'O pacote baixado falhou na verificação de integridade', installFailureTimeout: 'A instalação expirou', installFailurePnpmMissing: 'pnpm não foi encontrado, então nada pode ser instalado', - installFailureGeneric: 'Algo deu errado durante a instalação; os detalhes dizem o que', + installFailureGeneric: 'O comando de instalação falhou; os detalhes explicam por que', + installFailedEnabling: 'A instalação foi concluída; a falha ocorreu ao ativar o plugin', terminalCommandLine: 'Linha de comando {n}', terminalRunning: 'Correndo', terminalFailed: 'Falha', diff --git a/packages/client/ui-plugin-manager/src/client/manager-store.ts b/packages/client/ui-plugin-manager/src/client/manager-store.ts index b4b982ebf5..2ca4f1cdb6 100644 --- a/packages/client/ui-plugin-manager/src/client/manager-store.ts +++ b/packages/client/ui-plugin-manager/src/client/manager-store.ts @@ -139,7 +139,7 @@ export type InstallSubject = Extract { return { reason: error?.diagnostic ?? '', ...error === undefined ? {} : { code: error.code }, ...error?.incompatible === undefined ? {} : { incompatible: error.incompatible }, ...kind === undefined ? {} : { kind }, + stage, + ...enabled === undefined ? {} : { enabled }, ...failedAt === undefined ? {} : { failedAt }, ...pendingBuilds === undefined || pendingBuilds.length === 0 ? {} : { pendingBuilds }, } @@ -588,7 +599,7 @@ export function sortPackages(packages: readonly PackageView[]): PackageView[] { const IDLE_INSTALL: InstallState = { open: false, spec: '', registries: null, registry: OFFICIAL_REGISTRY, registryOpen: false, registryError: false, attempts: null, - phase: 'idle', inputError: null, subject: null, runs: [], detailsOpen: false, + phase: 'idle', inputError: null, subject: null, runs: [], detailsOpen: false, logPath: null, installed: null, installedVersion: null, restartRequired: false, failure: null, approvedBuilds: [], enabling: false, } @@ -997,8 +1008,9 @@ export class PluginManagerController { } /** - * Fold a chunk belonging to this installation into its pnpm command. - * A final chunk may arrive after the install answer and still updates an existing run. + * Fold a chunk belonging to this installation into its run. The install answer and the log travel over + * separate transports, so the run that ended the installation can arrive after its answer: a settled + * dialog keeps that run too, with the outcome's exit code when the chunk carries none of its own. * @param chunk - the chunk the Host forwarded. */ appendLog(chunk: PluginInstallLogChunk): void { @@ -1009,10 +1021,14 @@ export class PluginManagerController { this.installProgress({ requestId: install.requestId, phase: 'installing' }) } const index = install.runs.findIndex(run => run.jobId === chunk.jobId) - if (index === -1 && !isInstallPending(install.phase)) return const settled = chunk.exitCode === undefined ? {} : { exitCode: chunk.exitCode } + const settledRun = install.phase === 'failed' || install.phase === 'done' + if (index === -1 && !isInstallPending(install.phase) && !settledRun) return const runs = index === -1 - ? [...install.runs, { jobId: chunk.jobId, command: chunk.argv.join(' '), cwd: chunk.cwd, output: chunk.text, ...settled }] + ? [...install.runs, { + jobId: chunk.jobId, command: chunk.argv.join(' '), cwd: chunk.cwd, output: chunk.text, + ...settledRun && chunk.exitCode === undefined ? { exitCode: null } : settled, + }] : install.runs.map((run, at) => at === index ? { ...run, output: run.output + chunk.text, ...settled } : run) this.patchInstall({ runs }) } @@ -1164,12 +1180,21 @@ export class PluginManagerController { const install = state.install const spec = install.spec.trim() if (install.phase === 'checking' || isInstallPending(install.phase) || spec === '') return + const listed = state.packages.find(pkg => pkg.name === spec) + let catalogSubject = install.subject?.selection === undefined || install.subject.spec !== spec ? undefined : install.subject + if (listed?.availability === 'missing' && listed.installTarget !== undefined + && listed.error === undefined && catalogSubject === undefined) { + const target = listed.installTarget + const local = target.spec.startsWith('link:') + catalogSubject = { + status: 'accepted', kind: local ? 'path' : 'registry', name: listed.name, version: target.version, bundle: true, + spec: target.spec, registry: null, ...local ? {} : { saveExact: true }, + } + } if (this.ctx.get('productAnalytics')?.enabled) { this.analyticsAttempt = { input: sanitizeInstallInput(spec), started: Date.now() } this.ctx.get('productAnalytics')?.track('plugin_install_click', { input_value: sanitizeInstallInput(spec) }) } - const listed = state.packages.find(pkg => pkg.name === spec) - const catalogSubject = install.subject?.selection === undefined || install.subject.spec !== spec ? undefined : install.subject if (listed?.availability === 'installation' && listed.optional && listed.listedByDefault === false && !listed.enabled && listed.error === undefined && listed.readOnlyReason === undefined) { this.abortInspect() @@ -1199,7 +1224,7 @@ export class PluginManagerController { this.inspectAbort = controller this.patchInstall({ phase: 'checking', inputError: null, subject: catalogSubject ?? null, runs: [], detailsOpen: false, attempts: null, registryOpen: false, - installed: null, installedVersion: null, restartRequired: false, failure: null, approvedBuilds: [], + installed: null, installedVersion: null, restartRequired: false, failure: null, approvedBuilds: [], logPath: null, }) const read = this.registryRead if (read !== undefined && choice === read.choice && read.done !== undefined) { @@ -1242,7 +1267,10 @@ export class PluginManagerController { const requestId = randomUUID() as PluginInstallRequestId const request: InstallRequest = { requestId, acknowledged: false, replyLost: false, recovering: false } this.request = request - this.patchInstall({ phase: 'starting', requestId, subject, runs: [], attempts: null, failure: null, installed: null, installedVersion: null, approvedBuilds: [] }) + this.patchInstall({ + phase: 'starting', requestId, subject, runs: [], attempts: null, failure: null, installed: null, installedVersion: null, + approvedBuilds: [], logPath: null, + }) // The Host announces `plugin-manager/changed` while the run is still on // the wire, and every such event reads again; those reads must not cancel // the run's settlement. @@ -1298,7 +1326,8 @@ export class PluginManagerController { const packages = result.packageResult this.patchInstall({ phase: 'failed', runs: settledRuns(runs, packages?.exitCode ?? null), - failure: failureOf(result.error, packages?.kind, result.pendingBuilds, result.failedAt), + failure: failureOf(result.error, packages?.kind, result.pendingBuilds, result.failedAt, result.stage, result.enabled), + logPath: result.packageResult?.logPath ?? null, ...asked, }) } else { @@ -1308,6 +1337,7 @@ export class PluginManagerController { installedVersion: result.version ?? null, restartRequired: result.application === 'restart-required', ...result.restartReason === undefined ? {} : { restartReason: result.restartReason }, + logPath: result.packageResult?.logPath ?? null, approvedBuilds: result.approvedBuilds ?? [], ...asked, }) diff --git a/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx b/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx index 2a6f019ad4..9069ce355b 100644 --- a/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx +++ b/packages/client/ui-plugin-manager/tests/browser-plugin.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import assert from 'node:assert/strict' import { Context, Service } from '@deepseek-ai/cordis' import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' @@ -253,7 +254,7 @@ describe('ui-plugin-manager browser plugin', () => { const unread = () => { throw new Error('The sidebar icon must not read application state') } const glyph = render() + useWorkspaces={unread} useContextMenu={contextMenuHook()} useResource={unread} {...allowAllAccess} />) expect(glyph.container.querySelector('svg')?.getAttribute('width')).toBe('18') expect(icon.options).toMatchObject({ id: PANEL_ID, order: 0 }) expect(icon.locale).toBe(NS) diff --git a/packages/client/ui-plugin-manager/tests/components.client.spec.tsx b/packages/client/ui-plugin-manager/tests/components.client.spec.tsx index 1cb3a73e15..adacb15d71 100644 --- a/packages/client/ui-plugin-manager/tests/components.client.spec.tsx +++ b/packages/client/ui-plugin-manager/tests/components.client.spec.tsx @@ -1,4 +1,5 @@ // @vitest-environment jsdom +import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import type { ConfigPageForm } from '../src/client/slot-contract.ts' import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' @@ -70,7 +71,7 @@ const MIRROR_OPTION = `${en.registryNpmmirror} registry.npmmirror.com` const IDLE_INSTALL: InstallState = { open: false, spec: '', registries: null, registry: { kind: 'offered', registry: null }, registryOpen: false, registryError: false, attempts: null, - phase: 'idle', inputError: null, subject: null, runs: [], detailsOpen: false, + phase: 'idle', inputError: null, subject: null, runs: [], detailsOpen: false, logPath: null, installed: null, installedVersion: null, restartRequired: false, failure: null, approvedBuilds: [], enabling: false, } @@ -159,6 +160,7 @@ function renderTab( useSessionRetainInfo: unusedStandardHook, useResource: unusedStandardHook, ...allowAllAccess, + useContextMenu: contextMenuHook(), } const navigation = createNavigationStore().create() const props: PluginManagerPageProps = { @@ -1856,9 +1858,9 @@ describe('PluginManagerPage', () => { expect(screen.queryByText('line 8')).toBeNull() fireEvent.click(screen.getByRole('button', { name: en.terminalExpandAria.replace('{n}', '3') })) expect(screen.getByText('line 8')).toBeTruthy() - // Before the first chunk there is no location to name. + // Before the first chunk there is no location to name, and a running install claims no output yet. set({ install: { ...IDLE_INSTALL, open: true, spec: 'dsh-x', phase: 'running', subject, detailsOpen: true } }) - expect(screen.getByText(en.terminalNoOutput)).toBeTruthy() + expect(screen.queryByText(en.installDetailsNoOutput)).toBeNull() // Cancel and the back control each ask the Host to stop the run; the close control asks too, and closes once the Host confirms. fireEvent.click(screen.getByRole('button', { name: en.installCancel })) fireEvent.click(screen.getByRole('button', { name: en.installCancelAndEdit })) @@ -2060,6 +2062,35 @@ describe('PluginManagerPage', () => { expect(screen.getByText(en.installSubjectTarball)).toBeTruthy() }) + it('names an enable-stage failure and points the details at the complete Host log', () => { + const subject = { spec: 'dsh-x', status: 'accepted', kind: 'registry', name: 'dsh-x', bundle: true, registry: null } as const + const logPath = '/home/u/.dsh/profiles/web/plugin-manager/runs/install.log' + const enabling: InstallState = { + ...IDLE_INSTALL, open: true, spec: 'dsh-x', phase: 'failed', subject, detailsOpen: true, logPath, + failure: { reason: 'activation refused', stage: 'enable', enabled: true }, + } + const { set } = renderTab({ install: enabling }) + // The enabled bundle could not be applied, so the screen separates the finished install from the failure. + expect(screen.getByText(en.installFailedEnabling)).toBeTruthy() + // No terminal chunk reached the dialog; the details say what the dialog received, not what the run printed. + expect(screen.getByText(en.installDetailsNoOutput)).toBeTruthy() + // They still point at the Host's complete log for the run that settled the dialog. + expect(screen.getByText(en.installLogPath.replace('{path}', logPath))).toBeTruthy() + // A failure of the install itself names no finished install. + set({ install: { ...enabling, failure: { reason: 'activation refused', stage: 'install', enabled: true } } }) + expect(screen.queryByText(en.installFailedEnabling)).toBeNull() + // An install that never asked to enable the bundle cannot have failed enabling it. + set({ install: { ...enabling, failure: { reason: 'activation refused', stage: 'enable', enabled: false } } }) + expect(screen.queryByText(en.installFailedEnabling)).toBeNull() + // Without a reason the sentence is the only line: it names the step instead of the install command it finished. + set({ install: { ...enabling, failure: { reason: '', stage: 'enable', enabled: true } } }) + expect(screen.getAllByText(en.installFailedEnabling)).toHaveLength(1) + expect(screen.queryByText(en.installFailureGeneric)).toBeNull() + // Without a settled run's log the details offer no path. + set({ install: { ...enabling, logPath: null } }) + expect(screen.queryByText(en.installLogPath.replace('{path}', logPath))).toBeNull() + }) + it.each(['network', 'timeout'] as const)('shows GitHub recovery only after a %s failure and returns to package input', (kind) => { const subject = { spec: 'github:a/b', status: 'accepted', kind: 'git', bundle: null, registry: null, host: 'github.com' } as const const failed: InstallState = { diff --git a/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts b/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts index 47dc13c330..67b95bded7 100644 --- a/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts +++ b/packages/client/ui-plugin-manager/tests/manager-store.client.spec.ts @@ -48,9 +48,11 @@ const INSPECTED = { status: 'accepted' as const, kind: 'registry' as const, name const APPLIED: ChangeResult = { changed: true, application: 'applied', stage: 'enable', target: 'dsh-better-sidebar' } /** A change the Host could not apply, with the refusal it names. */ -function failed(error?: ManagementError, packageResult?: ChangeResult['packageResult']): ChangeResult { +function failed( + error?: ManagementError, packageResult?: ChangeResult['packageResult'], facts: Pick = { stage: 'install' }, +): ChangeResult { return { - changed: false, application: 'failed', stage: 'enable', target: 'dsh-better-sidebar', + changed: false, application: 'failed', target: 'dsh-better-sidebar', ...facts, ...error === undefined ? {} : { error }, ...packageResult === undefined ? {} : { packageResult }, } } @@ -655,13 +657,14 @@ describe('PluginManagerController', () => { gate.resolve(ok({ ...APPLIED, bundle: 'dsh-new', version: '1.0.0' })) await vi.waitFor(() => { expect(state().install.phase).toBe('done') }) expect(state().install).toMatchObject({ installed: 'dsh-new', installedVersion: '1.0.0', restartRequired: false, detailsOpen: true }) - // The finished install settled its run; a trailing last chunk still lands - // on it, while a chunk for a run the dialog never saw is dropped. + // The answer and the log travel over separate transports: the settled dialog keeps a trailing chunk of a + // known run, and a run whose first chunk arrived after the answer settles with the outcome, not as running. controller.appendLog({ requestId, jobId: 'j1', argv, cwd: '/p', stream: 'stdout', text: '', exitCode: 0 }) - controller.appendLog({ requestId, jobId: 'j3', argv, cwd: '/p', stream: 'stdout', text: 'stray' }) + controller.appendLog({ requestId, jobId: 'j3', argv, cwd: '/p', stream: 'stdout', text: 'late diagnostic' }) expect(state().install.runs).toEqual([ { jobId: 'j1', command: 'pnpm add dsh-new', cwd: '/p', output: 'Progress\nDone\n', exitCode: 0 }, { jobId: 'j2', command: 'pnpm remove lib', cwd: '/p', output: '- lib\n', exitCode: 0 }, + { jobId: 'j3', command: 'pnpm add dsh-new', cwd: '/p', output: 'late diagnostic', exitCode: null }, ]) await vi.waitFor(() => { expect(plugins.listBundles).toHaveBeenCalledTimes(2) }) // Cancelling from the finished screen does nothing, nor does the Host's late progress; a new spec after it starts over. @@ -815,7 +818,7 @@ describe('PluginManagerController', () => { face.editInstallSpec('dsh-x') face.runInstall() await vi.waitFor(() => { expect(state().install.phase).toBe('failed') }) - expect(state().install.failure).toEqual({ reason: 'ERR', code: 'operation-error', kind: 'network' }) + expect(state().install.failure).toEqual({ reason: 'ERR', code: 'operation-error', kind: 'network', stage: 'install' }) face.cancelInstall() expect(state().install).toMatchObject({ open: true, phase: 'idle', spec: 'dsh-x', failure: null, subject: null }) }) @@ -1227,7 +1230,7 @@ describe('PluginManagerController', () => { pendingBuilds: ['native'], })) await vi.waitFor(() => { expect(state().install.phase).toBe('failed') }) - expect(state().install.failure).toEqual({ reason: 'ERR_PNPM_IGNORED_BUILDS', code: 'operation-error', kind: 'build-blocked', pendingBuilds: ['native'] }) + expect(state().install.failure).toEqual({ reason: 'ERR_PNPM_IGNORED_BUILDS', code: 'operation-error', kind: 'build-blocked', pendingBuilds: ['native'], stage: 'install' }) // The retry keeps the subject the check produced and carries the approved names under a new request id. face.approveBuildsAndRetry() const second = await started() @@ -1301,7 +1304,7 @@ describe('PluginManagerController', () => { answer(ok(failed({ code: 'operation-error', diagnostic: 'ERR_PNPM' }, { exitCode: 1, output: 'ERR_PNPM', truncated: false, logPath: '/l', kind: 'network' }))) await vi.waitFor(() => { expect(state().install.phase).toBe('failed') }) expect(state().install.runs).toEqual([]) - expect(state().install.failure).toEqual({ reason: 'ERR_PNPM', code: 'operation-error', kind: 'network' }) + expect(state().install.failure).toEqual({ reason: 'ERR_PNPM', code: 'operation-error', kind: 'network', stage: 'install' }) expect(state().install.subject).toEqual({ spec: 'x', ...INSPECTED }) // A lost answer cannot establish whether the Host stopped the process. await installing() @@ -1329,23 +1332,80 @@ describe('PluginManagerController', () => { { jobId: 'j', command: 'pnpm add x', cwd: '/p', output: 'partial', exitCode: 0 }, { jobId: 'k', command: 'pnpm add x', cwd: '/p', output: 'open', exitCode: null }, ]) - expect(state().install.failure).toEqual({ reason: '', code: 'not-bundle' }) + expect(state().install.failure).toEqual({ reason: '', code: 'not-bundle', stage: 'install' }) // An incompatibility keeps the packages it names. await installing() answer(ok(failed({ code: 'incompatible-version', incompatible: [INCOMPATIBLE] }))) await vi.waitFor(() => { expect(state().install.phase).toBe('failed') }) - expect(state().install.failure).toEqual({ reason: '', code: 'incompatible-version', incompatible: [INCOMPATIBLE] }) + expect(state().install.failure).toEqual({ reason: '', code: 'incompatible-version', incompatible: [INCOMPATIBLE], stage: 'install' }) // A failure the Host does not explain has neither code nor words. await installing() answer(ok(failed())) await vi.waitFor(() => { expect(state().install.phase).toBe('failed') }) - expect(state().install.failure).toEqual({ reason: '' }) + expect(state().install.failure).toEqual({ reason: '', stage: 'install' }) expect(plugins.installBundle).toHaveBeenCalledTimes(6) // Editing the spec after a failure starts over too. face.editInstallSpec('y') expect(state().install).toMatchObject({ phase: 'idle', spec: 'y', runs: [], failure: null }) }) + it('keeps the run whose first chunk arrives after the failed answer', async () => { + const { face, state, controller } = bench({ + installBundle: vi.fn().mockResolvedValueOnce(ok(failed( + { code: 'operation-error', diagnostic: 'offline' }, + { exitCode: 1, output: 'fatal: unable to access', truncated: false, logPath: '/l', kind: 'network' }, + ))), + }) + face.openInstall() + face.editInstallSpec('https://github.com/a/b.git') + face.runInstall() + await vi.waitFor(() => { expect(state().install.phase).toBe('failed') }) + const requestId = state().install.requestId as PluginInstallRequestId + expect(state().install.runs).toEqual([]) + // The check's only chunk can arrive after the answer; the settled dialog still shows it and its log. + const argv = ['git', '-c', 'credential.helper=', 'ls-remote', '--', 'https://github.com/a/b.git', 'HEAD'] + controller.appendLog({ requestId, jobId: 'g1', argv, cwd: '/p', stream: 'stderr', text: 'fatal: unable to access', exitCode: 1 }) + expect(state().install.runs).toEqual([ + { jobId: 'g1', command: argv.join(' '), cwd: '/p', output: 'fatal: unable to access', exitCode: 1 }, + ]) + // A chunk of another installation still is not this dialog's. + controller.appendLog({ requestId: 'other' as PluginInstallRequestId, jobId: 'g2', argv, cwd: '/p', stream: 'stderr', text: 'stray', exitCode: 1 }) + expect(state().install.runs).toHaveLength(1) + }) + + it('keeps the step a failed install reached and the complete Host log it settled with', async () => { + const retry = deferred>>() + const failedLog = '/var/log/dsh/plugin-manager/install-failed.log' + const doneLog = '/var/log/dsh/plugin-manager/install-done.log' + const { face, state, plugins, started } = bench({ + installBundle: vi.fn() + .mockResolvedValueOnce(ok(failed( + { code: 'operation-error', diagnostic: 'activation refused' }, + { exitCode: 0, output: 'installed', truncated: false, logPath: failedLog }, + { stage: 'enable', enabled: true }, + ))) + .mockReturnValueOnce(retry.promise), + }) + face.openInstall() + face.editInstallSpec('dsh-x') + face.runInstall() + await vi.waitFor(() => { expect(state().install.phase).toBe('failed') }) + // The Host laid the failure at activation, and the details keep the run's complete log. + expect(state().install.failure).toEqual({ reason: 'activation refused', code: 'operation-error', stage: 'enable', enabled: true }) + expect(state().install.logPath).toBe(failedLog) + // Retrying forgets the settled run's log until the next answer names its own. + face.runInstall() + await started() + expect(state().install.logPath).toBeNull() + retry.resolve(ok({ + ...APPLIED, bundle: 'dsh-x', + packageResult: { exitCode: 0, output: '', truncated: false, logPath: doneLog }, + })) + await vi.waitFor(() => { expect(state().install.phase).toBe('done') }) + expect(state().install.logPath).toBe(doneLog) + expect(plugins.installBundle).toHaveBeenCalledTimes(2) + }) + it('drops every late settlement after disposal', async () => { const enableGate = deferred>>() const installGate = deferred>>() @@ -1919,6 +1979,23 @@ const CATALOG: BundleInfo = { installTarget: { spec: '@deepseek-ai/dsh-subagent-codex@2.0.0', version: '2.0.0' }, } +it.each(['registry', 'source'] as const)('installs a typed default-hidden Official name using its %s target', async (mode) => { + const name = '@deepseek-ai/dsh-cua-bundle' + const spec = mode === 'source' ? 'link:/workspace/cua-bundle' : `${name}@2.0.0` + const entry = { ...CATALOG, name, listedByDefault: false, installTarget: { spec, version: '2.0.0' } } + const { controller, plugins, face, state } = bench({ listBundles: vi.fn().mockResolvedValue(ok([entry])) }) + await controller.load() + face.openInstall() + face.editInstallSpec(name) + face.runInstall() + await vi.waitFor(() => { expect(plugins.installBundle).toHaveBeenCalledOnce() }) + expect(plugins.inspect).not.toHaveBeenCalled() + expect(state().install.subject?.selection).toBeUndefined() + expect(plugins.installBundle).toHaveBeenCalledWith(spec, { + enabled: false, ...mode === 'registry' ? { saveExact: true } : {}, requestId: state().install.requestId, registry: null, + }) +}) + it('installs an absent Official entry directly at the host target and enables it through the normal installer', async () => { const { controller, plugins, face, state } = bench({ listBundles: vi.fn().mockResolvedValue(ok([CATALOG])) }) await controller.load() diff --git a/packages/client/ui-plugin-manager/tests/touch-styles.client.spec.ts b/packages/client/ui-plugin-manager/tests/touch-styles.client.spec.ts index 79cd0229f9..f3e637dd54 100644 --- a/packages/client/ui-plugin-manager/tests/touch-styles.client.spec.ts +++ b/packages/client/ui-plugin-manager/tests/touch-styles.client.spec.ts @@ -59,6 +59,11 @@ function ruleBody(selector: string): string { } describe('plugin page touch rules', () => { + it('uses the compact page inset below 768px', () => { + const narrow = /@media \(max-width: 767px\) \{([\s\S]*?)\n\}/.exec(rules)?.[1] + expect(narrow).toContain('--plugin-page-inset: 20px') + }) + it('fences every hover affordance behind a hover-capable pointer', () => { // Unguarded, the browser keeps `:hover` on the tapped element until the next tap // elsewhere: a card or menu row stays painted as if the pointer were still on it. diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index c25fde68e8..8bb6988406 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-primitives/use-this-package: - en: beec1ea02d0adc12 - zh: 9a0fc5e0e4d78722 + en: ead6be55c7c9d7cf + zh: 125ad36db7328551 /deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog: en: 289fe5c01b026e81 zh: 5680066a8443fba9 @@ -24,14 +24,14 @@ en: f13b4ba09521d300 zh: a6093993d8fd0cdb /deepseek-ai-dsh-client-ui-primitives/use-this-package/rendering-agent-output: - en: 32d4557c4429e00d - zh: 293a6fef712f7502 + en: 3271871a42bd52c8 + zh: 89b7a9f03018454d /deepseek-ai-dsh-client-ui-primitives/use-this-package/localizing-copy: - en: a943603b74080ef5 - zh: 43f7a0188aff271b + en: 81e58c7b342baf3c + zh: 6cd47b16124b215c /deepseek-ai-dsh-client-ui-primitives/understand-the-implementation: - en: d223f2e301758b0f - zh: 5d1bc5a5e5431dbf + en: 6fbd9df222b41e09 + zh: 3bdb4a6b9b6bff9e /deepseek-ai-dsh-client-ui-primitives/understand-the-implementation/source-map: en: fd510d34404eb090 zh: d05b0890db929ae6 @@ -45,8 +45,8 @@ en: 45f4cd1ef96bb6d2 zh: f264d25b780ad1dc /deepseek-ai-dsh-client-ui-primitives/further-exploration: - en: abbbdbc9a7540743 - zh: cf5bbeaedb3696d0 + en: daa908e173136285 + zh: 5f8492ce8a4c4e48 /deepseek-ai-dsh-client-ui-primitives/model-experience: en: 3120df665299c634 zh: 1d9f365d091d0d2a diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index c0145d1a7b..4e538ecaeb 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -25,7 +25,7 @@ Use `dsh-client-ui-primitives` to build web-client controls and render agent out ## Use this package -`Toast` uses the theme’s toast background and label colors in both light and dark modes. `Menu` data rows and `MenuItemButton` component rows accept owner-provided effective shortcuts and align their keys at the trailing edge as muted text without a background, including submenus. Menus hide these hints when the primary pointer is coarse (`pointer: coarse`) and [keyboard navigation](#input-modality) is inactive. Keyboard navigation reveals them until the next pointer press; keyboard bindings remain active. `ShortcutKeys` defaults to unboxed keys for menu and inline hints. Its `tooltip` variant uses lighter keycaps over the dark bubble and groups plus-separated combinations into one filled block. `Tooltip.shortcutKeys` vertically centers keycaps beside optional localized action text, or shows only keys when the label is empty. The optional `className` supplies owner interaction styles. `Modal` uses the frame’s shared overlay inset, with a minimum 24px viewport margin. Its mask leaves the Windows caption unpainted while the full-viewport layer blocks background clicks. `Modal` and the settings shell share top-layer Escape and Tab handling through `useModalLayer`, restoring the previous focus on close. A dialog that remains mounted restores focus left inside its closed layer, preserving focus already moved elsewhere. `closeTopModal(document)` requests the foreground modal’s current close action; newer menus or unregistered dialogs block dismissal of the modal behind them. Components use `isBehindModal` to avoid moving focus behind a nested dialog. Menus consume their local Escape before modal dismissal. `observeComposition` supplies the same composition-end and legacy IME guard to local modal and recording handlers; callers dispose its document listeners with their interaction lifetime. +`Toast` uses the theme’s toast background and label colors in both light and dark modes. `Menu` data rows and `MenuItemButton` component rows accept owner-provided effective shortcuts and align their keys at the trailing edge as muted text without a background, including submenus. Menu row separators align with the horizontal content edges of their rows. Menus hide these hints when the primary pointer is coarse (`pointer: coarse`) and [keyboard navigation](#input-modality) is inactive. Keyboard navigation reveals them until the next pointer press; keyboard bindings remain active. `ShortcutKeys` defaults to unboxed keys for menu and inline hints. Its `tooltip` variant uses lighter keycaps over the dark bubble and groups plus-separated combinations into one filled block. `Tooltip.shortcutKeys` vertically centers keycaps beside optional localized action text, or shows only keys when the label is empty. The optional `className` supplies owner interaction styles. `Modal` uses the frame’s shared overlay inset, with a minimum 24px viewport margin. Its mask leaves the Windows caption unpainted while the full-viewport layer blocks background clicks. `Modal` and the settings shell share top-layer Escape and Tab handling through `useModalLayer`, restoring the previous focus on close. A dialog that remains mounted restores focus left inside its closed layer, preserving focus already moved elsewhere. `closeTopModal(document)` requests the foreground modal’s current close action; newer menus or unregistered dialogs block dismissal of the modal behind them. Components use `isBehindModal` to avoid moving focus behind a nested dialog. Menus consume their local Escape before modal dismissal. `observeComposition` supplies the same composition-end and legacy IME guard to local modal and recording handlers; callers dispose its document listeners with their interaction lifetime. `isMobileDevice()` identifies iOS and Android phones and tablets for automatic text-input focus and keyboard dismissal. It recognizes `Android`, `iPhone`, `iPad`, or `iPod` in the UA, and iPads reporting `MacIntel` with more than one touch point. Other devices, including Windows touchscreen computers, return false regardless of window width. The function caches its first result for all callers in the page; component remounts reuse that result, and reloading the page reads the browser environment again. Identified mobile devices require explicit text-input focus. Browser modes or custom UAs that conceal the mobile platform can prevent identification; unrecognized UAs return false. A desktop UA alone cannot distinguish Android tablets from Linux computers. @@ -110,7 +110,9 @@ An open hover card closes immediately when an ancestor of its anchor becomes ine The pure Markdown helper `formatQuoteText` normalizes CRLF and CR line endings, then prefixes each line with `> `. -The nearest `MarkdownDelegateProvider` supplies optional `openExternalLink` and `openFile` navigation callbacks. Nested providers replace the enclosing capabilities, and callback changes reach already-rendered links without rebuilding Markdown. Its `openFile` makes local Markdown links clickable after settlement. Absolute and workspace-relative paths support percent escapes and `#L24` / `#L24-L30` fragments; ranges open at their first line. A destination with a backslash and no URL scheme (a drive letter is not one) is a Windows path when it has no `/` or has a backslash before a letter or digit. Such a path keeps every backslash, including one before punctuation, and still decodes character references, so `D:\repo\.github` is not read as an escaped `.`. Literal `?` and `#` in filenames must be percent-encoded. The tooltip uses the decoded path and supplies the accessible name when the label is empty. The callback receives the decoded path and optional line, while the renderer preserves the label and displays a file icon. Without a callback, local links remain text. URL schemes, queries, unsupported fragments, and malformed destinations never reach the file opener. +The nearest `MarkdownDelegateProvider` supplies optional `openExternalLink` and `openFile` navigation callbacks. Nested providers replace the enclosing capabilities, and callback changes reach already-rendered links without rebuilding Markdown. Its `openFile` makes local Markdown links clickable after settlement. Paths support percent escapes, `#L24` / `#L24-L30` fragments, and `:24` / `:24-30` / `:24:5` suffixes. Ranges open at their first line; columns are consumed but not selected. Fragments disable suffix parsing. Zero, unsafe integers, descending ranges, and unsupported fragments open the file without selecting a line. Literal `?`, `#`, and numeric colon suffixes in filenames must be percent-encoded. A destination with a backslash and no URL scheme (a drive letter is not one) is a Windows path when it has no `/` or has a backslash before a letter or digit. Such a path keeps every backslash, including one before punctuation, and still decodes character references, so `D:\repo\.github` is not read as an escaped `.`. The tooltip uses the decoded path and supplies the accessible name when the label is empty. The callback receives that path and optional line; the label and file icon remain visible. Without a callback, local links remain text. Queries, malformed escapes, and control characters never reach the file opener. + +Explicit `./`, `../`, slash/backslash-rooted paths (including UNC), and Windows drive paths such as `C:/work/file.ts` take precedence over URL parsing. Otherwise, destinations accepted by the absolute URL parser remain URLs: `index.ts:24`, `Makefile:12`, and `localhost:3000` are links, without adding a protocol or testing whether they can open. Use `./index.ts:24` for a file reference. Other destinations are paths. Authored links reject `javascript:`, `vbscript:`, `data:`, and `blob:`; other parseable protocols retain native navigation. HTTP(S) links retain delegated navigation and modified-click behavior. No click-time failure notice is added. `MarkdownText` renders untrusted GFM and TeX math, blocks unsafe links and images, and can turn resolved file mentions into explicit controls. Strikethrough requires `~~`; a single `~`, as in `10~20`, stays literal. A bare URL ends before non-ASCII punctuation or symbols, such as `。` or `,`, so CJK prose that follows it stays outside the link. A surrounding `MarkdownDelegateProvider` receives sanitized HTTP(S) URLs from ordinary clicks; modified clicks and links outside a provider retain native external-anchor behavior. `omitHtml` renders raw HTML as nothing instead of literal text, for documents written for HTML renderers. When the owner passes a `pathImages` vocabulary, image destinations that are local media paths rewrite to displayable URLs on settled renders only (the same streaming gate as file mentions); without a vocabulary, local destinations remain inert alt text. Rewritten images accept HTTP(S), data, blob, and the Desktop `dsh-app://app/api/file`, `dsh-app://app/api/plugin-market/detail-file`, and `dsh-app://app/api/plugin-manager/detail-file` routes; authored Desktop URLs remain inert. A load or decode failure replaces the image with its authored alt text, or the original destination when alt is empty; `fileImages` additionally supplies a localized failure prefix. Changing the image source permits a fresh load. Each mounted image appends a `load` query parameter to a resolved Host `api/file` URL, because browsers reuse a same-URL image within one document despite `no-store`; a newly rendered image of an overwritten file therefore loads its current bytes, and every remount requests the file again; the Host file route redirects that request to a cacheable URL for the current file version. While a reply streams, it freezes completed blocks, advances a top-level open fence by completed lines, and highlights that fence from saved Shiki grammar state. Completed token lines enter fixed-size React groups, so later chunks reconcile only the growing group; an unchanged fence retains that DOM when the final full parse resolves cross-document syntax. `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, and `WebBlock` render the matching tool-result intent with copy controls, overflow handling, and ANSI processing where applicable. `JsonTree` and `JsonBlock` inspect JSON values read-only, while `UserTextRun` renders uninterpreted text and `ReferenceChip` renders business-resolved labels. An explicit `onActivate` makes a chip a keyboard-accessible button; repeated pointer clicks and an existing text selection do not activate it, while keyboard activation remains available. Labels inherit their host’s wrapping policy. Recognition and JSON transforms belong to [ui-conversation](../ui-conversation/README.md#sent-user-text). @@ -130,6 +132,8 @@ The nearest `MarkdownDelegateProvider` supplies optional `openExternalLink` and The atoms cannot read the application locale, so every piece of user-facing copy arrives through required label props. `HoverCard`, `TerminalBlock`, `JsonTree`, `CodeBlock`, `MarkdownText`, `JsonBlock`, `ConnectionIndicator`, `Modal`, `DiffBlock`, `ReadBlock`, `SearchBlock`, `WebBlock`, and `ZoomControls` accept complete localized labels. The package owns no language fallback; omission fails typechecking, and each feature maps its typed `t` seat into the primitive's label interface. +`Menu.contextual` positions from the pointer without the frame inset and closes on a right-click inside the popup. Contextual popups with no rendered `role="menuitem"` rows stay hidden, including when legacy Slots return no content. Structured `items` reserve an icon column per divider group; `footer` and each submenu calculate their own groups. A contextual `footer` with a leading separator uses that line instead of adding a second border. Opaque `children` retain their own layout; a legacy Slot after data rows keeps its declared leading separator. `exiting` retains an inert popup for its fade; `returnFocus` restores the original control after asynchronous preparation. `MenuSurface.phase` fades the material, direct content, and macOS backing separately so the material keeps blurring the page. `MENU_TRANSITION_MS` supplies both CSS timing and the popup lifecycle timers. Ordinary dropdowns retain their existing timing. + ----- @@ -137,7 +141,7 @@ The atoms cannot read the application locale, so every piece of user-facing copy `Button` uses H36/R12 for `md` and H28/R8 for `sm`, including outlined controls. The `outline` variant preserves a transparent 0.5px layout border and paints its stroke with an inset shadow. The stroke reads ui-theme's DPR-aware `--dsh-hairline-width`, with a 0.5px fallback outside the theme. Feature classes customize its color through `--dsh-button-outline-color` and preserve the border width, transparent border color, and box-shadow. Menus and cards follow the [shared radius rules](../../../docs/web-styling.md#corner-radii-and-settings-cards); feature classes preserve control geometry. -Portalled menus close when their anchor becomes inert or hidden; their owner’s retained content stays mounted. +Portalled menus close when their anchor becomes inert or hidden; contextual menus use the original control supplied by `returnFocus`. While open, a contextual menu adds its ID to that control's `aria-controls` and restores the previous value on close. Their owner’s retained content stays mounted. `Menu.listClassName` styles the menu card independently of the anchor wrapper, including in portal mode. Leading icons use the `--dsw-alias-menu-icon` color; destructive icons retain their error color. @@ -202,6 +206,8 @@ These pages place the atoms in the client stack and the design system. `QuotePreview` shares the compact quote excerpt and clipped-only inline HoverCard between composers and sent messages. The popover sizes to its text up to 300px and stays within the viewport. Both surfaces display the exact text; editable drafts may supply a localized whole-quote removal action. Quotes opt into the nearest `HoverCardGroup` for exclusive preview display. The primitive performs no recognition or navigation. +`MarkdownDelegate.getTriggerProps` receives explicit file, URL, or original-image targets and returns gesture props. File paths and line numbers are carried by callbacks. File mentions can supply `contextMenuProps`; `ImageLightbox.contextMenuProps` delegates the original image gesture. An image menu owns Escape and Tab while it holds focus, returning to the preview before closing it. + ## Model Experience diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index f6cf20362a..5e0262cdc2 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -25,7 +25,7 @@ kind: "package-library" ## 使用本包 -`Toast` 在浅色和深色模式下均使用主题的系统提示背景与文字颜色。`Menu` 数据条目与 `MenuItemButton` 组件条目接收功能 owner 提供的有效快捷键,并在末端以无背景的浅灰色文字对齐显示,子菜单也采用同一呈现。主指针为粗指针(`pointer: coarse`)且未使用[键盘导航](#input-modality)时,菜单隐藏这些提示。键盘导航会显示提示,直到下一次指针按下;快捷键绑定始终生效。`ShortcutKeys` 默认以无方块的按键文字显示菜单和行内提示。`tooltip` 变体在深色气泡上使用稍浅的键帽,以加号连接的组合则共用一个填充色块。`Tooltip.shortcutKeys` 将键帽与可选的本地化操作文本垂直居中排列,标签为空时只显示按键。可选的 `className` 供调用方设置交互状态样式。`Modal` 使用框架共享的浮层起点,视口边距至少为 24px。其遮罩不绘制 Windows 顶栏区域,覆盖整个视口的模态层仍阻挡背景点击。`Modal` 与设置外壳通过 `useModalLayer` 共用顶层 Esc 和 Tab 处理,关闭时恢复先前焦点。关闭后保留在 DOM 中的弹窗仅恢复仍停留于内部的焦点,不覆盖已经移到其他位置的焦点。`closeTopModal(document)` 请求前台弹窗当前的关闭操作;上层菜单或未注册的对话框会阻止关闭其后方弹窗。组件通过 `isBehindModal` 避免将焦点移到嵌套弹窗后方。菜单先消费自己的 Esc,再由模态层处理关闭。 `observeComposition` 为局部弹层和录键处理提供相同的 composition-end 与旧版 IME 保护;调用方随交互生命周期释放其 document 监听。 +`Toast` 在浅色和深色模式下均使用主题的系统提示背景与文字颜色。`Menu` 数据条目与 `MenuItemButton` 组件条目接收功能 owner 提供的有效快捷键,并在末端以无背景的浅灰色文字对齐显示,子菜单也采用同一呈现。菜单行的分割线与该行内容区的左右边缘对齐。主指针为粗指针(`pointer: coarse`)且未使用[键盘导航](#input-modality)时,菜单隐藏这些提示。键盘导航会显示提示,直到下一次指针按下;快捷键绑定始终生效。`ShortcutKeys` 默认以无方块的按键文字显示菜单和行内提示。`tooltip` 变体在深色气泡上使用稍浅的键帽,以加号连接的组合则共用一个填充色块。`Tooltip.shortcutKeys` 将键帽与可选的本地化操作文本垂直居中排列,标签为空时只显示按键。可选的 `className` 供调用方设置交互状态样式。`Modal` 使用框架共享的浮层起点,视口边距至少为 24px。其遮罩不绘制 Windows 顶栏区域,覆盖整个视口的模态层仍阻挡背景点击。`Modal` 与设置外壳通过 `useModalLayer` 共用顶层 Esc 和 Tab 处理,关闭时恢复先前焦点。关闭后保留在 DOM 中的弹窗仅恢复仍停留于内部的焦点,不覆盖已经移到其他位置的焦点。`closeTopModal(document)` 请求前台弹窗当前的关闭操作;上层菜单或未注册的对话框会阻止关闭其后方弹窗。组件通过 `isBehindModal` 避免将焦点移到嵌套弹窗后方。菜单先消费自己的 Esc,再由模态层处理关闭。 `observeComposition` 为局部弹层和录键处理提供相同的 composition-end 与旧版 IME 保护;调用方随交互生命周期释放其 document 监听。 `isMobileDevice()` 识别 iOS 和 Android 手机及平板,供自动聚焦和收起键盘使用。它识别 UA 中的 `Android`、`iPhone`、`iPad` 或 `iPod`,以及报告 `MacIntel` 且触摸点数大于一的 iPad。其他设备(包括 Windows 触屏电脑)返回 false,不受窗口宽度影响。函数缓存首次判断结果,供页面内的所有调用方共享;组件重新挂载会复用该结果,重新加载页面时会再次读取浏览器环境。识别出的移动设备需要用户主动聚焦文本输入框。隐藏移动平台信息的浏览器模式或自定义 UA 可能导致识别失败;未识别的 UA 返回 false。仅凭桌面 UA 无法区分 Android 平板与 Linux 电脑。 @@ -110,7 +110,9 @@ kind: "package-library" 纯 Markdown 工具 `formatQuoteText` 规范化 CRLF 和 CR 换行符,再为每行添加 `> ` 前缀。 -最近的 `MarkdownDelegateProvider` 提供可选的 `openExternalLink` 和 `openFile` 导航回调。嵌套 Provider 替换外层能力,回调变化无需重新构建 Markdown 即可到达已渲染链接。其 `openFile` 使本地 Markdown 链接在落定后可点击。绝对路径和工作区相对路径支持百分号转义以及 `#L24` / `#L24-L30` 片段;范围定位到起始行。含反斜杠且无 URL 协议(盘符不算 URL 协议)的目标,若不含 `/`,或在字母或数字前有反斜杠,即为 Windows 路径。此类路径保留所有反斜杠(包括标点前的反斜杠),仍会解码字符引用,因此 `D:\repo\.github` 不会被读作转义的 `.`。文件名中的字面 `?` 和 `#` 必须百分号编码。悬停提示使用解码后的路径,并在标签为空时提供可访问名称。回调接收解码后的路径和可选行号,渲染器保留标签并显示文件图标。不传回调时,本地链接仍为文本。URL 协议、查询串、不支持的片段及格式错误的目标不会传给文件打开器。 +最近的 `MarkdownDelegateProvider` 提供可选的 `openExternalLink` 和 `openFile` 导航回调。嵌套 Provider 替换外层能力,回调变化无需重新构建 Markdown 即可到达已渲染链接。其 `openFile` 使本地 Markdown 链接在落定后可点击。路径支持百分号转义、`#L24` / `#L24-L30` 片段或 `:24` / `:24-30` / `:24:5` 后缀。范围定位到起始行;列号会被移除但不参与定位。有片段时不解析后缀。零、超出安全整数范围的值、倒序范围及不支持的片段只打开文件,不指定行号。文件名中的字面 `?`、`#` 和数字冒号后缀必须百分号编码。含反斜杠且无 URL 协议(盘符不算 URL 协议)的目标,若不含 `/`,或在字母或数字前有反斜杠,即为 Windows 路径。此类路径保留所有反斜杠(包括标点前的反斜杠),仍会解码字符引用,因此 `D:\repo\.github` 不会被读作转义的 `.`。悬停提示使用解码后的路径,并在标签为空时提供可访问名称。回调接收该路径和可选行号;标签与文件图标保留。不传回调时,本地链接仍为文本。查询串、格式错误的转义和控制字符不会传给文件打开器。 + +明确的 `./`、`../`、斜杠或反斜杠开头的路径(包括 UNC),以及 `C:/work/file.ts` 这样的 Windows 盘符路径优先于 URL 解析。其余目标若能被绝对 URL 解析器接受,就保留为 URL:`index.ts:24`、`Makefile:12` 和 `localhost:3000` 均为链接,不补协议,也不预先检查能否打开。文件引用使用 `./index.ts:24`。其他目标视为路径。正文链接禁止 `javascript:`、`vbscript:`、`data:` 和 `blob:`;其余可解析的协议保留原生导航。HTTP(S) 链接保留委托导航和修饰键点击行为。不添加点击后的失败提示。 `MarkdownText` 渲染不可信的 GFM 与 TeX 公式、阻止不安全的链接与图片,并可把已解析的文件提及转换为显式控件。删除线需要 `~~`;单个 `~`(如 `10~20`)保持字面文本。裸 URL 在非 ASCII 标点或符号(如 `。`、`,`)前结束,紧随其后的中文正文不会并入链接。外层 `MarkdownDelegateProvider` 会接收普通点击产生的已净化 HTTP(S) URL;带修饰键的点击和 Provider 外的链接保留原生外部 anchor 行为。`omitHtml` 不渲染原始 HTML,而不是将其显示为原样文本,用于为 HTML 渲染器编写的文档。当 owner 传入 `pathImages` 词表时,本地媒体路径的图片目标只在落定渲染阶段重写为可展示 URL(与 file mentions 相同的流式门);不传词表时本地目标保持惰性 alt 文本。重写后的图片支持 HTTP(S)、data、blob 及桌面端 `dsh-app://app/api/file`、`dsh-app://app/api/plugin-market/detail-file` 与 `dsh-app://app/api/plugin-manager/detail-file` 路由;正文直接书写的桌面端 URL 仍保持惰性。加载或解码失败后,图片替换为作者的 alt 文本;alt 为空时显示原始目标路径;`fileImages` 还提供本地化的失败提示前缀。图片源变化后可重新加载。每个挂载的图片会为解析得到的 Host `api/file` 地址追加 `load` 查询参数,因为浏览器在同一文档内会无视 `no-store` 复用相同 URL 的图片;因此覆盖后的文件在新渲染的图片中会加载当前内容,每次重新挂载都会重新请求该文件;Host 文件路由会把该请求重定向到当前文件版本的可缓存地址。回复流式输出时,它冻结已完成的块、按已完成行推进顶层未闭合 fence,并从保存的 Shiki grammar state 为该 fence 增量高亮。已完成的 token 行进入固定大小的 React 分组,后续分片只 reconcile 正在增长的分组;最终全量解析解决跨文档语法时,未变化的 fence 会保留该 DOM。`TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock` 与 `WebBlock` 把对应的工具结果意图渲染为带复制控件、溢出处理及适用时 ANSI 处理的卡片。`JsonTree` 与 `JsonBlock` 以只读方式检查 JSON 值;`UserTextRun` 渲染不做解析的文本,`ReferenceChip` 渲染业务已解析的标签。显式传入 `onActivate` 后,胶囊成为可由键盘操作的按钮;重复指针点击和已有文本选区不触发激活,键盘激活仍然可用。标签继承所属容器的换行规则。识别和 JSON 变换由 [ui-conversation](../ui-conversation/README.zh.md#sent-user-text) 负责。 @@ -130,6 +132,8 @@ kind: "package-library" 这些原子组件无法读取应用 locale,因此每段面向用户的文案都必须通过 label prop 提供。`HoverCard`、`TerminalBlock`、`JsonTree`、`CodeBlock`、`MarkdownText`、`JsonBlock`、`ConnectionIndicator`、`Modal`、`DiffBlock`、`ReadBlock`、`SearchBlock`、`WebBlock` 与 `ZoomControls` 接收完整的本地化 label。本包不拥有语言回退;遗漏会导致类型检查失败,各功能会把带类型的 `t` 席位映射到 primitive 的 label 接口。 +`Menu.contextual` 从指针位置定位而不避让顶部栏,并在弹窗内右键时关闭。右键弹窗没有实际渲染的 `role="menuitem"` 行时保持隐藏,包括旧 Slot 返回空内容的情况。结构化 `items` 按分隔线组预留图标栏;`footer` 与各子菜单独立计算分组。右键菜单的 `footer` 以分隔线开头时,直接使用该线,不再叠加边框。不透明的 `children` 保留原有布局;数据行后方的旧 Slot 保留其声明的首条分隔线。`exiting` 在淡出期间保留不可交互的弹窗;`returnFocus` 在异步准备后恢复原控件焦点。`MenuSurface.phase` 分别对材质层、直接内容和 macOS 背景淡入淡出,让材质层继续模糊页面。`MENU_TRANSITION_MS` 同时提供 CSS 动画与弹窗生命周期计时。普通下拉菜单保留原有时序。 + ----- @@ -137,7 +141,7 @@ kind: "package-library" `Button` 的 `md` 使用 H36/R12,`sm` 使用 H28/R8,包含描边控件。`outline` 变体保留 0.5px 透明边框用于布局,并通过内阴影绘制描边。描边宽度读取 ui-theme 随设备像素比更新的 `--dsh-hairline-width`,未安装主题时回退到 0.5px。功能样式通过 `--dsh-button-outline-color` 定制描边颜色,并保留边框宽度、透明边框颜色和 box-shadow。菜单与卡片遵循[共享圆角规则](../../../docs/web-styling.zh.md#corner-radii-and-settings-cards);功能样式保留控件几何。 -锚点变为 inert 或隐藏时,portal 菜单会关闭,其所属区域保留的内容继续挂载。 +锚点变为 inert 或隐藏时,portal 菜单会关闭;右键菜单使用 `returnFocus` 提供的原始控件。右键菜单打开期间会将自身 ID 加入该控件的 `aria-controls`,关闭时恢复原值。其所属区域保留的内容继续挂载。 `Menu.listClassName` 独立控制菜单卡片样式,不影响入口容器,也适用于 portal 模式。前置图标使用 `--dsw-alias-menu-icon` 文本色;破坏性操作图标保留错误色。 @@ -202,6 +206,8 @@ kind: "package-library" `QuotePreview` 在 composer 与已发送消息之间共享紧凑 quote 摘录和仅截断时显示的行内 HoverCard。原文弹层按文本内容确定宽度,最大为 300px,并限制在视口内。两处均展示原文;可编辑草稿可以提供本地化的整条 quote 删除操作。quote 加入最近的 `HoverCardGroup`,使原文弹层互斥显示。该 primitive 不负责识别或导航。 +`MarkdownDelegate.getTriggerProps` 接收明确的文件、链接或原图目标并返回手势 props。文件路径与行号通过回调传递。文件引用可提供 `contextMenuProps`;`ImageLightbox.contextMenuProps` 转发原图手势。图片菜单持有焦点时负责 Escape 与 Tab,先返回预览再关闭预览。 + ## 模型体验 diff --git a/packages/client/ui-primitives/src/ImageLightbox.tsx b/packages/client/ui-primitives/src/ImageLightbox.tsx index 1cb3fe4a8c..36deb6d2cf 100644 --- a/packages/client/ui-primitives/src/ImageLightbox.tsx +++ b/packages/client/ui-primitives/src/ImageLightbox.tsx @@ -1,3 +1,4 @@ +import type { HTMLAttributes } from 'react' import { useEffect, useRef } from 'react' import { createPortal } from 'react-dom' import { IconCloseOutlineRegular } from './icons/index.tsx' @@ -21,14 +22,16 @@ export interface ImageLightboxLabels { * @param props.src - the original image URL. * @param props.alt - the image's alt text. * @param props.labels - dialog and close-control strings. + * @param props.contextMenuProps - optional original-image gesture bindings. * @param props.onClose - dismiss callback owned by the opener. * @returns the modal preview dialog. */ -export function ImageLightbox({ src, alt, labels, onClose }: { +export function ImageLightbox({ src, alt, labels, onClose, contextMenuProps }: { src: string alt: string labels: ImageLightboxLabels onClose: () => void + contextMenuProps?: Pick, 'onContextMenu' | 'onKeyDown' | 'tabIndex'> | undefined }) { const closeRef = useRef(null) const restoreRef = useRef(null) @@ -37,6 +40,8 @@ export function ImageLightbox({ src, alt, labels, onClose }: { restoreRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null closeRef.current?.focus() const onKeyDown = (event: globalThis.KeyboardEvent): void => { + // A portaled image menu owns Escape and Tab until it returns focus. + if (event.defaultPrevented || document.activeElement?.closest('[role="menu"]')) return if (event.key === 'Escape') { event.stopPropagation(); onClose() } if (event.key === 'Tab') { event.preventDefault(); closeRef.current?.focus() } } @@ -56,7 +61,7 @@ export function ImageLightbox({ src, alt, labels, onClose }: { >