diff --git a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml index 8d8498f8bb..6f1e439bdf 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.i18n.yaml @@ -9,8 +9,8 @@ en: 44615a7a0939054e zh: b8efa721321ba0d7 /agent-note-creator-mode-installs-persistent-plugin-bundles/decision: - en: 38ecabc170c418c7 - zh: d380f53fa508328e + en: 013a2088d8f8c435 + zh: 5491ff817716696b /agent-note-creator-mode-installs-persistent-plugin-bundles/alternatives-considered: en: af527d8aabdfd59c zh: 34388da992d2ab56 diff --git a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md index 8fa2b574f6..f831e40520 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md +++ b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.md @@ -14,7 +14,7 @@ Creator mode enables the existing `plugin_manager` tool. Agents author packages The default Standard mode enables the same tool under the same profile condition and approval gate. Without it, Standard sessions did not install plugins directly and spent extra turns and tokens working around the missing tool; the change also moves Standard and Creator toward one capability set. A full-access Standard session can therefore install Host code without a separate prompt, as its shell already can. PTC and Minimal keep the tool disabled. -The model sees two read-only Cordis inspection tools. Generated-code define/run/stop/undefine and dynamic self-inspection tool APIs are absent. Existing runtime and Client consumers retain their services; historical session cards remain readable. This supersedes only the model-facing mutation workflow in the [self-referential toolset reference](../../../../packages/extensions/cordis-host-runner/README.md); its runtime ownership and sandbox rationale remain independently relevant. The [profile transaction decision](2026-09-14-current-profile-plugin-management.md) continues to govern locking, package installation, and partial failures. +Standard and Creator expose one read-only Cordis inspection tool, `cordis_inspect`. Omitting `query` discovers providers; supplying `query` reads one declared method. The shared entry keeps runtime discovery available in the default mode without duplicating tool descriptions. Generated-code define/run/stop/undefine and dynamic self-inspection tool APIs are absent. Existing runtime and Client consumers retain their services; historical session cards remain readable. This supersedes only the model-facing mutation workflow in the [self-referential toolset reference](../../../../packages/extensions/cordis-host-runner/README.md); its runtime ownership and sandbox rationale remain independently relevant. The [profile transaction decision](2026-09-14-current-profile-plugin-management.md) continues to govern locking, package installation, and partial failures. Visual creation requests default to an installed Client plugin rendered in the current Web page unless the user names another destination. The development skill supplies a minimal package and effect-owned Client registration. Discovery ends when the required APIs are known; a working first version is installed before optional visual refinement. Verification uses the connected page where available. Browser authentication or operating-system setup is not a prerequisite for plugin installation, and a mock preview cannot establish an in-app result. diff --git a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md index b5c0ad0cb2..b3b686385f 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-16-creator-persistent-plugin-management.zh.md @@ -14,7 +14,7 @@ agent 需要安装能力并在同一段对话中使用。生成代码工具在 默认的标准模式以相同的 profile 条件和审批门槛启用同一工具。缺少该工具时,标准模式会话不会直接安装插件,而要额外花费轮次和 token 绕过;此改动也让标准模式和创造模式朝同一能力集收敛。因此,完整权限的标准模式会话无需单独审批即可安装 Host 代码,与其 shell 已有的能力一致。PTC 和 Minimal 仍禁用该工具。 -模型可见两个只读 Cordis 检查工具,不再提供生成代码的 define/run/stop/undefine 和动态自省工具 API。现有运行时和 Client 消费者保留其服务;历史会话卡片仍然可读。这仅取代[自引用工具集参考](../../../../packages/extensions/cordis-host-runner/README.zh.md)中的模型侧变更流程;其运行时所有权和沙箱依据仍有独立价值。[profile 事务决策](2026-09-14-current-profile-plugin-management.zh.md)继续规定锁、包安装和部分失败行为。 +标准模式和创造模式提供一个只读 Cordis 检查工具 `cordis_inspect`。省略 `query` 以发现 provider;提供 `query` 以读取一个已声明的方法。共用此入口使默认模式能够进行运行时发现,同时避免重复的工具描述。不再提供生成代码的 define/run/stop/undefine 和动态自省工具 API。现有运行时和 Client 消费者保留其服务;历史会话卡片仍然可读。这仅取代[自引用工具集参考](../../../../packages/extensions/cordis-host-runner/README.zh.md)中的模型侧变更流程;其运行时所有权和沙箱依据仍有独立价值。[profile 事务决策](2026-09-14-current-profile-plugin-management.zh.md)继续规定锁、包安装和部分失败行为。 除非用户指定其他目标,视觉创建请求默认通过已安装的 Client 插件显示在当前 Web 页面。开发 skill 提供最小包和由 effect 管理的 Client 注册示例。已知所需 API 后结束探查,在可选视觉优化之前先安装能工作的初版。有条件时使用已连接页面验证。浏览器认证或操作系统设置不是安装插件的前提,mock 预览不能证明应用内结果。 diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml b/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml new file mode 100644 index 0000000000..a661424786 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-11-05-session-panel.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/feature/2026-11-05-session-panel.md +/agent-note-session-panel-in-the-chat-view-s-end-gutter: + en: 1dc9957a0c9336e0 + zh: 88d41c8490c2710c +/agent-note-session-panel-in-the-chat-view-s-end-gutter/problem: + en: c69d9843bc6f0b87 + zh: c31bb1b2b4d9b781 +/agent-note-session-panel-in-the-chat-view-s-end-gutter/decision: + en: c2ddf417ea56b626 + zh: 44c30091ade7e5bf +/agent-note-session-panel-in-the-chat-view-s-end-gutter/decision/docking-follows-the-transcript-gutter: + en: 8a97ac8ac0b40d0c + zh: d42fe9c23b9dcd79 +/agent-note-session-panel-in-the-chat-view-s-end-gutter/decision/sections-are-registrations-the-panel-draws-titles: + en: d6f85e07351ad90e + zh: f883a99c8ca98522 +/agent-note-session-panel-in-the-chat-view-s-end-gutter/decision/the-turn-rail-sits-at-the-start-edge: + en: 08e720a4ea75d4d6 + zh: 5e2e5b8452f67d36 +/agent-note-session-panel-in-the-chat-view-s-end-gutter/alternatives-considered: + en: 6adaf7a36da05668 + zh: c0ace7297995d764 +/agent-note-session-panel-in-the-chat-view-s-end-gutter/consequences: + en: 6c2f625c9c36ebd0 + zh: 0060e818dbf233ce diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.md b/.agents/notes/implemented/feature/2026-11-05-session-panel.md new file mode 100644 index 0000000000..7dbb92ce80 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.md @@ -0,0 +1,49 @@ +# Agent Note: Session panel in the Chat View's end gutter + +Status: implemented + +English | [中文](2026-11-05-session-panel.zh.md) + +## Problem + +Facts about the current Session — its project directory, the change requests it opened, and later its outputs — had no common home. Each owner added its own Session header button and, for anything larger than a menu, a right-sidebar tab: the forge change requests are one such tab. A sidebar tab takes width from the transcript while it shows, shows one tab at a time, and leaves the facts one click away from every message. The required surface is a summary the user can keep beside the conversation without covering it, that several plugins fill independently, that hides when there is no room, and that the user can show or hide from the Session header. + +## Decision + +[`dsh-client-ui-session-panel`](../../../../packages/client/ui-session-panel/README.md) adds a Session header toggle (`conversation.session.header.utilities`, order −10) and a floating panel that occupies `conversation.chat.aside`, a slot that [`ui-chat`](../../../../packages/client/ui-chat/README.md#scroll-ownership) renders in the Chat View beside the turn rail. The aside is a zero-height layer at the top of the Chat frame and, like the turn rail, is sticky inside the shared scrollport: the panel does not scroll with the transcript, inherits the scrollport's composer and viewport heights, and needs no seat in the Conversation shell. Views other than Chat show no panel. + +### Docking follows the transcript gutter + +The panel docks only while the gutter between the transcript column and the Chat frame's end edge can hold it (348px: 40px clear of the column and its width handle, a 300px minimum width, and an 8px margin). The gutter, not the viewport width, decides because the column width is adaptive and user-draggable and the right sidebar shares the frame: the same viewport can leave 75px or 600px. The Chat View owns the frame and the transcript column, so its aside layer publishes the gutter as the `--dsh-chat-aside-gutter` custom property, and the panel's stylesheet sizes the docked panel from it. + +Script still needs the decision, because docked and overlay differ in behavior and not only in size: the toggle reports `aria-expanded` truthfully and knows whether a press flips docking or opens the overlay, the overlay closes on Escape and on outside presses and returns focus, and an open overlay closes once the panel can dock. A CSS-only container query cannot tell an element outside the Chat View, or a listener, any of that. The stylesheet therefore computes the decision as well: each mounted panel renders a zero-height dock probe that is 1px wide from the gutter that holds the panel's minimum width and 0 below it, derived from the same metrics as the docked width, and the plugin observes only that probe. It hears the decision flip; observing the frame and the transcript column would call back on every frame of a streamed reply, because the column's height changes with its content, and on every step of a window resize. A Session has room to dock while any of its probes does, and a Session without a probe shows no Chat View. The toggle and the panel decide the presentation with the same pure function. While no Chat View shows the Session, as in the trajectory View, the toggle is unavailable and its tooltip asks for the Chat view; `ui-conversation` keeps View selection inside its shell, so the toggle does not switch Views itself. + +Docking follows one persisted preference shared by every Session and defaults to on. Without room, a press opens a transient overlay for that Session above the transcript; it never changes the preference, and it closes once its gutter can dock the panel or no Chat View shows the Session any longer, so it never reappears on its own. The panel state follows the reported gutter of the open overlay's Session. A panel withdraws its report when it unmounts or its Chat View moves to another Session, in a layout-effect cleanup kept apart from the gutter update, so a changed gutter never reads as an unmount. Hiding automatically and overlaying on request keeps the transcript uncovered without making the facts unreachable on laptop widths. + +### Sections are registrations; the panel draws titles + +Each section is one list registration with `id`, `order`, and a required `label`. The panel projects the live registrations into titles, draws each title, and renders the section body with `renderSlot(..., { only: id })`; a CSS `:has()` rule hides a section whose body rendered nothing, so a section opts out by rendering nothing and no effect reports visibility to the owner. Trailing title controls are a keyed slot addressed by the section `id`, and a section that several plugins share declares its own row slot, as the built-in Environment section does with `conversation.session.panel.environment.row`. Marks that must stay visible while the panel is hidden go in an indicator list over the toggle. + +Rows from every contributor share one look through the panel's stylesheet instead of a shared component: each contributor writes its row's markup and marks the parts, and the panel lays them out, so icon, text, and trailing areas align across packages. A shared row component would receive each contributor's icon, text, and controls as React nodes in props, which the client rules forbid, and a feature package cannot share its own row component with another feature package. + +### The turn rail sits at the start edge + +The turn rail sits at the scrollport's start edge with its marks, focus ring, and preview mirrored, leaving the end gutter to the docked panel; its 900px hiding rule guarantees room beside the start-side width handle. + +## Alternatives considered + +- **A seat in `conversation.content`.** Rejected: it made `ui-conversation` render the panel beside the width handles and outside the scrollport, have its width controls measure the gutter into a per-Session `ctx.uiConversation.layouts` source, and move the composer and viewport height variables from the scrollport to the content body so the seat could read them. The Conversation shell would carry geometry and variable placement for one feature, while chrome that must not scroll can sit sticky inside the scrollport as the turn rail does, and the Chat View already owns the column it would measure. +- **A right-sidebar tab.** It already exists for change requests, but it narrows the transcript while shown, shows one tab at a time, and the [UI guidance](../../../skills/dsh-client-ui-ux/SKILL.md#reuse-before-adding) reserves the sidebar for content opened on demand rather than a resident summary. +- **The dock kit's floating window.** `FloatLayer` windows are draggable, resizable, and positioned in viewport coordinates; a summary anchored to the transcript gutter needs none of that and would have to fight the window's own placement rules. +- **Viewport-width breakpoints.** The transcript width is adaptive and draggable and the right sidebar takes a variable track, so a viewport breakpoint either covers the transcript or hides the panel with room to spare. +- **CSS-only hiding with a click-time read.** A container query on the gutter can hide the docked panel, and the toggle could read the computed result when pressed, as the background-job trigger does. The toggle would still render without knowing whether the panel shows, so `aria-expanded` and its tooltip would be wrong whenever the preference says dock but the gutter is too narrow. +- **Squeezing the transcript to make room.** Docking on laptop widths by moving the transcript column aside changes the centered column, the composer, and both width handles; it remains a separate layout decision. +- **A Session-scoped standard hook for the gutter.** Adding a hook to every Session-scoped Slot would make every component fixture in the client restate it; the docking decision has two readers, the panel and the toggle, and both read it from the plugin's own state. + +## Consequences + +- With the default transcript width, which stops at 880px, the body must be 1576px wide to dock, so laptop widths use the overlay; the panel never covers the transcript unless the user opens it. +- Sections from independent plugins share one surface, ordering, and title style without depending on each other, and an occupied section id can be replaced by a higher-priority registration. +- `ui-chat` gained one slot and one custom property on its layer and observes nothing for them. Each mounted panel adds one `ResizeObserver` on its dock probe, which calls back only when the docking decision flips. `ui-conversation` caps the default transcript width at 880px. +- The panel shows only in Chat Views; elsewhere the toggle stays in the header, unavailable. Every Chat View occurrence renders the aside, so a Session shown in the main body and in an embedded Conversation at once shows its overlay in both. +- The turn rail's position changed for every user; its behavior and hiding rule did not. diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md b/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md new file mode 100644 index 0000000000..de8e0914a5 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md @@ -0,0 +1,49 @@ +# Agent Note: 停靠在 Chat 视图末端留白的会话面板 + +Status: implemented + +[English](2026-11-05-session-panel.md) | 中文 + +## Problem + +与当前会话相关的信息(项目目录、它开出的变更请求,以及之后的产物)没有统一的位置。各自的拥有者分别加会话标题栏按钮,内容一多就再开一个右侧栏标签页,forge 的变更请求就是这样一个标签页。侧栏标签页显示时占用正文宽度,一次只显示一个,而且每条消息之外都要多点一次才能看到。需要的界面是:可以放在对话旁边常驻而不遮挡正文;多个插件各自填充;没有空间时自动隐藏;用户可以从会话标题栏显示或隐藏。 + +## Decision + +[`dsh-client-ui-session-panel`](../../../../packages/client/ui-session-panel/README.zh.md) 新增一个会话标题栏开关(`conversation.session.header.utilities`,order −10)和一块悬浮面板,面板占用 `conversation.chat.aside`:这是 [`ui-chat`](../../../../packages/client/ui-chat/README.zh.md#scroll-ownership) 在 Chat 视图中、轮次轨道旁渲染的 slot。侧边层是 Chat 外框顶部的零高度图层,与轮次轨道一样在共享滚动容器内 sticky 定位:面板不随正文滚动,继承滚动容器的输入框区域与视口高度,也不需要 Conversation 外壳提供落位。Chat 以外的视图不显示面板。 + +### 停靠取决于正文留白 + +只有正文列到 Chat 外框末端边缘的留白放得下面板时才停靠(348px:与正文列及其宽度拖拽条保持 40px,最小宽度 300px,外加 8px 边距)。判断依据是留白而不是视口宽度,因为正文列宽度可自适应、可由用户拖拽,右侧栏也会占用框架宽度:同一个视口可能只剩 75px,也可能有 600px。Chat 视图持有外框和正文列,因此由它的侧边层把留白发布为自定义属性 `--dsh-chat-aside-gutter`,面板的样式表据此决定停靠宽度。 + +脚本仍然需要知道这个判断,因为停靠与浮层的差别不只在尺寸,还在行为:开关要如实报告 `aria-expanded`,也要知道按下后是切换停靠还是打开浮层;浮层在按 Esc 或在外部按下时关闭并归还焦点;面板可以停靠后,已打开的浮层要关闭。纯 CSS 的容器查询无法把这些告诉 Chat 视图之外的元素或事件监听器。因此样式表把判断也一并算出:每个已挂载的面板渲染一个零高度的停靠探针,它从放得下面板最小宽度的留白起宽 1px,更窄时宽度为 0,与停靠宽度出自同一组尺寸,插件只观察这个探针。这样插件只在判断翻转时收到通知;如果改为观察外框和正文列,流式回答的每一帧都会回调(正文列的高度随内容变化),窗口缩放的每一步也会回调。会话的任一探针有空间时该会话就可以停靠,没有探针的会话表示没有 Chat 视图在显示它。开关和面板用同一个纯函数决定呈现方式。没有 Chat 视图显示该会话时(例如在轨迹视图中),开关不可用,悬停提示请用户切到「对话」视图;`ui-conversation` 把视图选择留在其外壳内部,因此开关不自行切换视图。 + +停靠遵循所有会话共用的一个持久化偏好,默认开启。没有空间时,按下开关会为该会话在正文上方打开临时浮层;它从不改变偏好;该会话的留白可以停靠面板,或不再有 Chat 视图显示该会话时,浮层关闭,因此不会自己重新出现。面板状态跟随打开浮层的会话所上报的留白。面板卸载或其 Chat 视图换到另一个会话时撤回上报;撤回放在与留白更新分开的 layout effect 清理中,因此留白变化永远不会被当成卸载。自动隐藏加按需浮层,既保证正文不被遮挡,也让笔记本宽度下的信息依然可达。 + +### 分栏是注册项;面板绘制标题 + +每个分栏是一次 list 注册,带 `id`、`order` 和必填的 `label`。面板把实时注册投影成标题并逐个绘制,再用 `renderSlot(..., { only: id })` 渲染分栏正文;CSS `:has()` 规则隐藏正文没有渲染内容的分栏,因此分栏不渲染任何内容即可退出,不需要 effect 向拥有者上报可见性。标题尾部控件是以分栏 `id` 为键的 keyed slot;多个插件共用的分栏声明自己的行 slot,内置「环境」分栏就以 `conversation.session.panel.environment.row` 这样做。面板隐藏时也要可见的标记放进开关上的角标列表。 + +各贡献方的行通过面板的样式表共享同一外观,而不是共享组件:各贡献方自己写行的标记并标出各个部分,由面板统一排版,使不同包的图标、文字与尾部区域对齐。共享的行组件要把各贡献方的图标、文字和控件作为 React 节点从 props 传入,这是客户端规则禁止的;功能包之间也不能共享各自的行组件。 + +### 轮次轨道位于起始边 + +轮次轨道连同刻度、焦点环和预览位于滚动容器的起始边,末端留白留给停靠面板;它的 900px 隐藏规则保证旁边有足够空间容纳起始侧的宽度拖拽条。 + +## Alternatives considered + +- **落位在 `conversation.content`。** 已否决:这种做法让 `ui-conversation` 在宽度拖拽条旁、滚动容器之外渲染面板,由宽度控件把留白测量结果写入按会话划分的 `ctx.uiConversation.layouts` source,并把输入框区域与视口高度变量从滚动容器挪到正文容器上,使落位能读到它们。Conversation 外壳因此要为单个功能承担几何测量和变量位置;而不随滚动的界面元素可以像轮次轨道那样在滚动容器内 sticky 定位,要测量的正文列也本来就归 Chat 视图所有。 +- **右侧栏标签页。** 变更请求已有这种实现,但它显示时会压窄正文,一次只显示一个标签页,而且 [UI 指南](../../../skills/dsh-client-ui-ux/SKILL.md#reuse-before-adding)把侧栏留给按需打开的内容,而不是常驻摘要。 +- **dock kit 的悬浮窗。** `FloatLayer` 窗口可拖拽、可缩放、按视口坐标定位;锚定在正文留白的摘要用不上这些能力,还要对抗窗口自身的定位规则。 +- **按视口宽度断点。** 正文宽度自适应、可拖拽,右侧栏占用可变宽度,视口断点要么遮挡正文,要么在空间充足时也隐藏面板。 +- **纯 CSS 隐藏加点击时读取。** 对留白做容器查询可以隐藏停靠面板,开关在按下时读取计算结果,与后台任务按钮的做法相同。但开关渲染时仍不知道面板是否显示,偏好为停靠而留白不足时,`aria-expanded` 与提示文字都会出错。 +- **挤压正文腾出空间。** 在笔记本宽度下把正文列移开来停靠,会改变居中的正文列、composer 和两侧宽度拖拽条;这仍是另一项布局决策。 +- **会话作用域标准 hook。** 给每个会话作用域 Slot 增加一个留白 hook,会让客户端所有组件测试夹具都要补上它;停靠判断只有两个读取方,即面板和开关,两者都从插件自己的状态读取。 + +## Consequences + +- 默认正文宽度最多 880px,此时对话区要 1576px 宽才能停靠,因此笔记本宽度使用浮层;除非用户主动打开,面板不会遮挡正文。 +- 独立插件的分栏共享同一界面、排序和标题样式,彼此不依赖;已占用的分栏 id 可以被更高优先级的注册替换。 +- `ui-chat` 多了一个 slot,侧边层多了一个自定义属性,但不为它们观察任何尺寸。每个已挂载的面板在停靠探针上多一个 `ResizeObserver`,只在停靠判断翻转时回调。`ui-conversation` 把默认正文宽度上限定为 880px。 +- 面板只出现在 Chat 视图中;其他视图下开关仍在标题栏中,但不可用。每个 Chat 视图实例都会渲染侧边层,因此同一会话同时显示在主正文区和嵌入的对话中时,两处都会显示浮层。 +- 轮次轨道的位置对所有用户都变了;行为和隐藏规则不变。 diff --git a/apps/cli/README.i18n.yaml b/apps/cli/README.i18n.yaml index a035a44693..741c64c21d 100644 --- a/apps/cli/README.i18n.yaml +++ b/apps/cli/README.i18n.yaml @@ -12,8 +12,8 @@ en: cc03e6b75206661b zh: 99e41f4143198352 /deepseek-ai-dsh/profiles: - en: 523477a093beb0c2 - zh: f88ea21e5fbea969 + en: 85171337ac2fb2ff + zh: 705a4eef97d9b519 /deepseek-ai-dsh/optional-overlays: en: 3a40ddc44e55f79c zh: 8d3949132e1ef93c diff --git a/apps/cli/README.md b/apps/cli/README.md index 644eba2aa5..4a5dd73e04 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -34,7 +34,7 @@ dsh --help # the launcher's own help ## Profiles -A profile directory holds a `package.json` (out-of-tree plugin dependencies plus the profile manifest `dsh.profile` with its ordered `bundles` list) and a `cordis.patch.yml` (the user's own patch layer). `dsh-hmr`, when enabled in YAML, watches the profile manifest and both profile and home patch files, then recomposes all layers through one serialized reload. Without HMR, changes apply on restart. Edits arriving during watcher registration use the same nonfatal reload reporting as later edits. [Plugin Manager](../../packages/boot/plugin-manager/README.md) shares package operations and the profile write lock with `dsh plugin`; package updates retain disabled bundle selections. CLI package commands inherit authentication variables and terminal descriptors, including interactive build approval; service calls retain their scrubbed environment and captured diagnostics. +A profile directory holds a `package.json` (out-of-tree plugin dependencies plus the profile manifest `dsh.profile` with its ordered `bundles` list) and a `cordis.patch.yml` (the user's own patch layer). `dsh-hmr`, when enabled in YAML, watches the profile manifest, the profile and home patch files, and every `--patch` overlay file, then recomposes all layers through one serialized reload. Without HMR, changes apply on restart, except that a Config Editor save applies the current contents of every patch and overlay file. Edits arriving during watcher registration use the same nonfatal reload reporting as later edits. [Plugin Manager](../../packages/boot/plugin-manager/README.md) shares package operations and the profile write lock with `dsh plugin`; package updates retain disabled bundle selections. CLI package commands inherit authentication variables and terminal descriptors, including interactive build approval; service calls retain their scrubbed environment and captured diagnostics. Installation and profile startup enforce the declared `engines.dsh` range, or DSH peer ranges when it is absent, against the same runtime version shown by `dsh --version`. Incompatible plugins require an explicitly acknowledged exact-version exemption. The [plugin manager's compatibility reference](../../packages/boot/plugin-manager/README.md#version-compatibility-and-exemptions) documents `version-exemptions`, `allow-version`, `revoke-version`, persistence, and risks. diff --git a/apps/cli/README.zh.md b/apps/cli/README.zh.md index 318e12440f..5d0ce78b86 100644 --- a/apps/cli/README.zh.md +++ b/apps/cli/README.zh.md @@ -34,7 +34,7 @@ dsh --help # the launcher's own help ## Profile -profile 目录包含一个 `package.json`,其中记录树外插件依赖,以及 profile manifest(元数据清单)`dsh.profile`、其中按顺序排列的 `bundles` 列表;还包含一个 `cordis.patch.yml`,其中保存用户自己的 patch 层。在 YAML 中启用的 `dsh-hmr` 监视 profile manifest、profile 与 home 级 patch 文件,再通过统一串行重载重新组合所有层。未启用 HMR 时,更改在重启后生效。监听器注册期间发生的编辑与后续编辑使用相同的非致命重载错误报告。[插件管理器](../../packages/boot/plugin-manager/README.zh.md) 与 `dsh plugin` 共享包操作和 profile 写锁;更新依赖会保留已停用的组合包选择。CLI 包操作继承认证环境和终端描述符,支持交互式构建批准;service 调用保留清理后的环境并捕获诊断。 +profile 目录包含一个 `package.json`,其中记录树外插件依赖,以及 profile manifest(元数据清单)`dsh.profile`、其中按顺序排列的 `bundles` 列表;还包含一个 `cordis.patch.yml`,其中保存用户自己的 patch 层。在 YAML 中启用的 `dsh-hmr` 监视 profile manifest、profile 与 home 级 patch 文件以及每个 `--patch` overlay 文件,再通过统一串行重载重新组合所有层。未启用 HMR 时,更改在重启后生效;例外是 Config Editor 保存时会应用所有 patch 与 overlay 文件的当前内容。监听器注册期间发生的编辑与后续编辑使用相同的非致命重载错误报告。[插件管理器](../../packages/boot/plugin-manager/README.zh.md) 与 `dsh plugin` 共享包操作和 profile 写锁;更新依赖会保留已停用的组合包选择。CLI 包操作继承认证环境和终端描述符,支持交互式构建批准;service 调用保留清理后的环境并捕获诊断。 安装和 profile 启动会按声明的 `engines.dsh` 范围(未声明时按 DSH peer 范围),检查与 `dsh --version` 显示值相同的运行时版本。不兼容插件需要用户明确确认精确版本豁免。[插件管理器的兼容性参考](../../packages/boot/plugin-manager/README.zh.md#version-compatibility-and-exemptions)说明 `version-exemptions`、`allow-version`、`revoke-version`、持久化规则与风险。 diff --git a/apps/cli/reference/README.i18n.yaml b/apps/cli/reference/README.i18n.yaml index 2c33416553..93a4389770 100644 --- a/apps/cli/reference/README.i18n.yaml +++ b/apps/cli/reference/README.i18n.yaml @@ -21,8 +21,8 @@ en: 8d2cfff9bab7327f zh: 21515ab6e6798504 /dsh-cli-behavior-reference/web-profile: - en: 149c5571acd51baf - zh: 300e3c2425273a92 + en: afc6ddcd63f24664 + zh: ed11d2ad6d7a9852 /dsh-cli-behavior-reference/shared-deployment-behavior: en: f02219118dcec531 zh: fe2977628d7340da diff --git a/apps/cli/reference/README.md b/apps/cli/reference/README.md index dc84a267d8..ff5b1914ad 100644 --- a/apps/cli/reference/README.md +++ b/apps/cli/reference/README.md @@ -128,7 +128,7 @@ The production Web runner needs built package and frontend artifacts (`pnpm run Process shutdown gives the plugin tree up to five seconds to dispose. The first `SIGINT`/`SIGTERM` starts that graceful drain — `SIGTERM` is a supervisor's ordinary stop request and exits 0 on every surface, `SIGINT` reports 130; a second signal forces immediate exit. If one-shot normal completion is already stuck in disposal, the first `Ctrl+C` is the escalation and exits immediately instead of being swallowed. -The base-backed modes treat the invoking directory as the default workspace root, load applicable `AGENTS.md` or `CLAUDE.md` instructions with a 65,536-byte render budget for each instruction chain, and use an in-memory SQLite session content index. The standalone `sdk-minimal` profile uses the invoking directory as its sandbox-policy root and includes `read_image`, but omits text filesystem tools, instruction discovery, and SQLite. An enabled HMR plugin watches both `cordis.patch.yml` layers (profile and home) and reapplies valid edits transactionally; without HMR, the process applies them once. A one-shot surface exits through its bounded shutdown, which disposes any live watchers. +The base-backed modes treat the invoking directory as the default workspace root, load applicable `AGENTS.md` or `CLAUDE.md` instructions with a 65,536-byte render budget for each instruction chain, and use an in-memory SQLite session content index. The standalone `sdk-minimal` profile uses the invoking directory as its sandbox-policy root and includes `read_image`, but omits text filesystem tools, instruction discovery, and SQLite. An enabled HMR plugin watches both `cordis.patch.yml` layers (profile and home) and every `--patch` overlay file, and reapplies valid edits transactionally; without HMR, the process applies them once. A one-shot surface exits through its bounded shutdown, which disposes any live watchers. New sessions in base-backed profiles default to the `workspace-write` permission preset. Bash and filesystem mutations are restricted to the session workspace and platform temporary roots; reads and network access are not confined, while process visibility depends on the selected sandbox backend — bwrap runs commands in a private PID namespace that hides host processes, and Landlock and Seatbelt leave host process visibility unchanged. `DSH_PERMISSION_MODE` changes the process fallback. Stored General-settings permissions affect later Web sessions, not an already-open one. The standalone `sdk-minimal` tree instead pins `danger-full-access` and mounts no approval or permission-settings service. diff --git a/apps/cli/reference/README.zh.md b/apps/cli/reference/README.zh.md index 2de7755983..bc1e6ed8ac 100644 --- a/apps/cli/reference/README.zh.md +++ b/apps/cli/reference/README.zh.md @@ -128,7 +128,7 @@ dsh web --help 进程关闭时,插件树最多有 5 秒完成 dispose。首次收到 `SIGINT` 或 `SIGTERM` 时会开始优雅排空:`SIGTERM` 是监督进程发出的常规停止请求,在所有运行模式下都以 0 退出;`SIGINT` 则报告 130。第二次收到信号时会立即强制退出。如果一次性运行在正常结束时已经卡在 dispose 阶段,第一次按下 `Ctrl+C` 就会直接升级为强制退出,而不会被忽略。 -基于 base 的模式都将运行命令时所在的目录作为默认 workspace 根目录,以每条指令链 65,536 字节的渲染预算加载适用的 `AGENTS.md` 或 `CLAUDE.md` 指令,并使用内存 SQLite 会话内容索引。独立的 `sdk-minimal` profile 把运行命令时所在的目录作为沙箱策略根目录并包含 `read_image`,但省略文本文件系统工具、指令发现与 SQLite。启用的 HMR 插件会监视 profile 与 home 两个 `cordis.patch.yml` 配置层的有效变更,并以事务方式重新应用;未启用 HMR 时只应用一次。一次性运行模式通过有界关闭流程退出,该流程会 dispose 所有实时监视器。 +基于 base 的模式都将运行命令时所在的目录作为默认 workspace 根目录,以每条指令链 65,536 字节的渲染预算加载适用的 `AGENTS.md` 或 `CLAUDE.md` 指令,并使用内存 SQLite 会话内容索引。独立的 `sdk-minimal` profile 把运行命令时所在的目录作为沙箱策略根目录并包含 `read_image`,但省略文本文件系统工具、指令发现与 SQLite。启用的 HMR 插件会监视 profile 与 home 两个 `cordis.patch.yml` 配置层以及每个 `--patch` overlay 文件的有效变更,并以事务方式重新应用;未启用 HMR 时只应用一次。一次性运行模式通过有界关闭流程退出,该流程会 dispose 所有实时监视器。 基于 base 的 profile 中,新会话默认使用 `workspace-write` 权限预设。Bash 和文件系统修改仅限于会话 workspace 与平台临时根目录;读取和网络访问不受限制,进程可见性则取决于所选沙箱后端——bwrap 在私有 PID 命名空间中运行命令并隐藏宿主进程,Landlock 与 Seatbelt 保持宿主进程可见性不变。`DSH_PERMISSION_MODE` 更改进程后备值。General settings 中存储的权限影响后续 Web 会话,不改变已打开的会话。独立的 `sdk-minimal` 配置树则固定为 `danger-full-access`,且不挂载 approval 或权限 settings 服务。 diff --git a/apps/cli/src/profile-boot.ts b/apps/cli/src/profile-boot.ts index 2b1977deed..9ac6ffbe42 100644 --- a/apps/cli/src/profile-boot.ts +++ b/apps/cli/src/profile-boot.ts @@ -14,14 +14,12 @@ import { existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } import { dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { FiberState, type Context } from '@deepseek-ai/cordis' -import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include' import { boot, readProfilePatches, createRuntimeResolution, initProfile, installFailLoud, - loadOverlayPatches, loadProfile, reportSkippedBundles, PluginPackages, @@ -204,8 +202,8 @@ interface ComposedProfile { profile: Profile /** Immutable runtime resolution computed before any plugin imports. */ resolution: RuntimeResolution - /** Command-line overlay contents, frozen for this invocation. */ - overlays: PatchOptions[] + /** Absolute command-line overlay files, in argv order. */ + overlayPaths: string[] } /** @@ -231,8 +229,7 @@ async function composeProfile( if (resolvedProfile !== undefined) writeFileSync(join(profile.dir, PROFILE_ROOT_FILENAME), PROFILE_ROOT_CONFIG) const resolutionOptions = { installAnchor: resolvedProfile?.installAnchor ?? INSTALL_ANCHOR, profile } const resolution = await createRuntimeResolution(resolutionOptions) - const overlays = patchFiles.flatMap(file => loadOverlayPatches(NAME, resolve(file))) - return { profile, resolution, overlays } + return { profile, resolution, overlayPaths: patchFiles.map(file => resolve(file)) } } /** An application-owned profile and its independent installation fallback. */ @@ -331,7 +328,7 @@ export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Con installAnchor: options.resolvedProfile?.installAnchor ?? INSTALL_ANCHOR, startedBundles: composed.profile.layers.map(layer => layer.packageName), cwd: process.cwd(), home: resolveDshHome(), - overlays: composed.overlays, telemetryDisabledEnv: process.env.DSH_TELEMETRY_DISABLED, + overlayPaths: composed.overlayPaths, telemetryDisabledEnv: process.env.DSH_TELEMETRY_DISABLED, } const ctx = await boot(NAME, rootConfig, readProfilePatches(NAME, profileContext, composed.profile), async (hostCtx) => { app.current = hostCtx diff --git a/apps/cli/tests/built-bin.e2e.ts b/apps/cli/tests/built-bin.e2e.ts index acb6e4ab37..6150f1b30f 100644 --- a/apps/cli/tests/built-bin.e2e.ts +++ b/apps/cli/tests/built-bin.e2e.ts @@ -143,9 +143,7 @@ function createProfileLifecycleFixture(): ProfileLifecycleFixture { writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n') const linkTarget = join(profileDir, 'node_modules', 'dsh-lifecycle-bundle') mkdirSync(join(profileDir, 'node_modules'), { recursive: true }) - try { - rmSync(linkTarget, { recursive: true, force: true }) - } catch { /* fresh dir */ } + rmSync(linkTarget, { recursive: true, force: true }) // Copy-free: a package.json redirecting via a relative main is enough for require.resolve. mkdirSync(linkTarget, { recursive: true }) for (const file of ['package.json', 'cordis.patch.yml', 'plugin.mjs']) { diff --git a/apps/cli/tests/optional-bundle-transitions.e2e.ts b/apps/cli/tests/optional-bundle-transitions.e2e.ts index ac04460a79..d7e81f2c47 100644 --- a/apps/cli/tests/optional-bundle-transitions.e2e.ts +++ b/apps/cli/tests/optional-bundle-transitions.e2e.ts @@ -95,7 +95,7 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option const profile = app.loadProfileDirectory('bundle-test', directory, installAnchor) const profileContext: ProfileContext = { name: 'web', dir: directory, patchPath: profile.patchPath, installAnchor, cwd: workspace, home, - startedBundles: profile.layers.map(layer => layer.packageName), overlays: [], telemetryDisabledEnv: '1', + startedBundles: profile.layers.map(layer => layer.packageName), overlayPaths: [], telemetryDisabledEnv: '1', } const resolution = await app.createRuntimeResolution({ installAnchor, home, profile }) const listeners = new Set<() => void>() diff --git a/apps/cli/tests/profiles/cua-mcp/expected/tools.json b/apps/cli/tests/profiles/cua-mcp/expected/tools.json index 3dcb8da4dc..79ad346b20 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/tools.json +++ b/apps/cli/tests/profiles/cua-mcp/expected/tools.json @@ -17,7 +17,7 @@ { "name": "cua_run_code", "title": "Computer use program", - "description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, output overflow, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.", + "description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, output overflow, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.", "inputSchema": { "type": "object", "properties": { diff --git a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts index d3129c027b..e8efb9463f 100644 --- a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts @@ -1,5 +1,5 @@ -import { executeModelToolFixture } from '@deepseek-ai/dsh-tool-testkit' -import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { executeToolFixture, executeModelToolFixture } from '@deepseek-ai/dsh-tool-testkit' +import { mkdtemp, mkdir, readFile, realpath, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' @@ -152,6 +152,50 @@ async function backgroundPtcModeHarness(cwd: string): Promise { } describe('PTC mode typed values: keyless real-process contracts', () => { + it('returns formatted read content from inspect through the real outer run_code result', async () => { + workdir = await realpath(await mkdtemp(join(tmpdir(), 'dsh-ptc-inspect-read-'))) + const path = join(workdir, 'a.txt') + await writeFile(path, 'alpha\nbeta\n') + ctx = await typedPtcModeHarness() + await ctx.plugin(ToolFs) + + const formatted = `${path}\nfile\n\n1: alpha\n2: beta\n\n(End of file - total 2 lines)\n` + const native = await executeToolFixture(ctx, { + callId: brandString('inspect-read-reference'), name: 'read', + arguments: { file_path: path }, signal: testToolSignal, + }) + expect(native.isError).toBe(false) + expect(native.content).toEqual([{ type: 'text', text: formatted }]) + + const result = await runCode(ctx, `inspect(await tools.read({ file_path: ${JSON.stringify(path)} }));`) + expect(result.isError).toBe(false) + expect(result.content).toEqual([{ type: 'text', text: formatted + '\n' }]) + expect(result.value).toEqual({ + logs: [formatted + '\n'], sandbox: { mode: 'danger-full-access', denied: false }, + }) + }) + + it.each(['renderer', 'policy'])('keeps an empty %s output silent while preserving program data', async (source) => { + ctx = await typedPtcModeHarness() + ctx.tools.register(defineTool({ + name: 'silent_result', description: 'Return data without display text.', parameters: {}, + output: { + schema: { type: 'object', properties: { answer: { type: 'number', required: true } }, additionalProperties: false }, + render: () => source === 'renderer' ? [] : [{ type: 'text', text: 'original rendering' }], + }, + execute: async () => ({ answer: 42 }), + ...source === 'policy' ? { finalizeContent: () => [] } : {}, + })) + const result = await runCode(ctx, ` + const value = await tools.silent_result({}); + if (value.answer !== 42) throw new Error('program data changed'); + inspect(value); + `) + expect(result.isError).toBe(false) + expect(result.content).toEqual([{ type: 'text', text: '(run_code completed with no output)' }]) + expect(result.value).toEqual({ logs: [], sandbox: { mode: 'danger-full-access', denied: false } }) + }) + it('crosses a large intermediate value intact and exposes only typed tool failure fields', async () => { ctx = await typedPtcModeHarness() ctx.tools.register(defineTool({ @@ -305,15 +349,15 @@ describe('PTC mode typed values: keyless real-process contracts', () => { } as Agent const value = completion(await runCode(ctx, ` - const listed = await tools.cordis_inspect_list({}); + const listed = await tools.cordis_inspect({}); const provider = listed.providers.find(item => item.id === 'Tool'); - const inspected = await tools.cordis_inspect_query({ + const inspected = await tools.cordis_inspect({ query: { platform: provider.platform, provider: provider.id, method: provider.methods[0].name, - }); + } }); inspect(JSON.stringify({ provider: provider.id, names: inspected.data.tools.map(tool => tool.name) })); `, testToolSignal, agent)) - expect(value).toEqual({ provider: 'Tool', names: ['cordis_inspect_list', 'cordis_inspect_query'] }) + expect(value).toEqual({ provider: 'Tool', names: ['cordis_inspect'] }) }) }) diff --git a/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts b/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts index 480ffe2032..3faedc4a74 100644 --- a/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts +++ b/apps/cli/tests/profiles/sdk/desktop-tools.expected.e2e.ts @@ -2,7 +2,7 @@ * 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 + * SDK minimal, other presets, graphical context and optional runtime payloads * are outside this fixed standard/PTC, top-level-session comparison. */ import { createServer } from 'node:http' diff --git a/apps/cli/tests/profiles/sdk/tool-parity.ts b/apps/cli/tests/profiles/sdk/tool-parity.ts index fce089fc02..0b6299051e 100644 --- a/apps/cli/tests/profiles/sdk/tool-parity.ts +++ b/apps/cli/tests/profiles/sdk/tool-parity.ts @@ -9,8 +9,12 @@ interface Exception { /** 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.' }], + standard: [ + { tool: 'list_subagent_models', side: 'desktop', + reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' }, + { tool: 'cordis_inspect', side: 'desktop', + reason: 'Web exposes inspection of its Host and connected Client runtime; the SDK profile does not compose the Cordis inspection providers.' }, + ], ptc: [ { tool: 'list_subagent_models', side: 'desktop', reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' }, diff --git a/apps/cli/tests/resolved-profile-boot.spec.ts b/apps/cli/tests/resolved-profile-boot.spec.ts index b8415fb974..40630df491 100644 --- a/apps/cli/tests/resolved-profile-boot.spec.ts +++ b/apps/cli/tests/resolved-profile-boot.spec.ts @@ -2,7 +2,7 @@ import { lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { createRequire } from 'node:module' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { join, relative } from 'node:path' import { Context } from '@deepseek-ai/cordis' import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import { @@ -139,7 +139,7 @@ describe('runProfile with an application-owned profile', () => { try { const { shutdown } = await runProfile({ environment, profile: 'desktop', resolvedProfile: runtime, - patchFiles: [overlay], args: ['--port', '0', '--no-open'], + patchFiles: [relative(process.cwd(), overlay)], args: ['--port', '0', '--no-open'], }) expect(installProxyFromEnvironment).toHaveBeenCalledWith(environment, expect.any(Function)) const resolution = vi.mocked(createRuntimeResolution).mock.settledResults @@ -165,7 +165,9 @@ describe('runProfile with an application-owned profile', () => { ]) expect(rows.find(row => row.id === 'target')?.config).toEqual({ overlay: true, priority: 'overlay' }) expect(rows.find(row => row.id === 'session-telemetry-otel')?.disabled).toBe(true) - expect(ctx.profileContext).toMatchObject({ dir: home, patchPath: profilePatch, installAnchor: runtime.installAnchor }) + expect(ctx.profileContext).toMatchObject({ + dir: home, patchPath: profilePatch, installAnchor: runtime.installAnchor, overlayPaths: [overlay], + }) await shutdown.shutdown(0) expect(dispose).toHaveBeenCalledOnce() expect(disposeProxy).toHaveBeenCalledOnce() diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts index 0fb662568f..efdb68d158 100644 --- a/apps/cli/tests/web-agent-presets.e2e.ts +++ b/apps/cli/tests/web-agent-presets.e2e.ts @@ -221,7 +221,7 @@ async function bootWeb( bootCtx.provide('profileContext', { name: surface, dir: profileDir, patchPath: profile.patchPath, installAnchor: INSTALL_ANCHOR, home, cwd: home, startedBundles: profileBundles ?? ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app'], - overlays: [], telemetryDisabledEnv: '1' }) + overlayPaths: [], telemetryDisabledEnv: '1' }) await bootCtx.plugin(PluginPackages, { resolution }) bootCtx.provide('connection', { fetch: { register: () => () => {} }, @@ -351,7 +351,7 @@ describe('the shipped Web composition', () => { // excluded for the reason the TUI composition e2e excludes them — they // depend on ripgrep being present on the machine. expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([ - 'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode', + 'ask_user_question', 'bash', 'cordis_inspect', 'create_goal', 'edit', 'exit_plan_mode', 'get_goal', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'present', 'read', 'read_image', 'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view', 'send_message', 'skill', @@ -359,6 +359,18 @@ describe('the shipped Web composition', () => { 'workflow', 'working_directory', 'write', ]) expect(ctx.commands.find(handle.agent, 'goal')).toBeDefined() + for (const query of [undefined, { platform: 'host', provider: 'Config', method: 'listConfigs', input: { name: '@deepseek-ai/dsh-agent-loop' } }] as const) { + const inspected = await executeToolFixture(ctx, { + agent: handle.agent, callId: brandString(`standard-inspect-${query === undefined ? 'list' : 'query'}`), name: 'cordis_inspect', + arguments: query === undefined ? {} : { query }, signal: new AbortController().signal, + }) + expect(inspected.isError).toBe(false) + const text = inspected.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') + const value: unknown = JSON.parse(text) + const path = query === undefined ? 'providers' : 'data.entries' + const entry = query === undefined ? { platform: 'host', id: 'Config' } : { name: '@deepseek-ai/dsh-agent-loop' } + expect(value).toHaveProperty(path, expect.arrayContaining([expect.objectContaining(entry)])) + } } finally { await handle.dispose() } @@ -603,7 +615,7 @@ describe('the shipped Web composition', () => { try { const tools = toolNames(ctx, handle.agent) expect(tools).toEqual(expect.arrayContaining([ - 'cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager', + 'cordis_inspect', 'plugin_manager', ])) for (const removed of ['cordis_define', 'cordis_run', 'cordis_stop', 'cordis_undefine', 'cordis_inspect_self']) { expect(tools).not.toContain(removed) @@ -985,8 +997,7 @@ describe('the standard preset documentation skill', () => { expect((await testCtx.skills.get('dsh-doc', { cwd: root, scope: creator.agent }))?.path).toBe(definition.path) const schemas = testCtx.tools.schemas(standardAgent.agent) expect(schemas).toEqual(testCtx.tools.schemas(baseline.agent)) - expect(schemas.map(tool => tool.name)).not.toContain('cordis_inspect_list') - expect(schemas.map(tool => tool.name)).not.toContain('cordis_inspect_query') + expect(schemas.map(tool => tool.name)).toContain('cordis_inspect') for (const handle of [baseline, standardAgent]) { handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Reply ready.' }], source: { kind: 'user' } })) await handle.agent.whenIdle() @@ -1116,13 +1127,13 @@ describe('a user preset declared from the shipped cordis rows', () => { try { for (const handle of [shipped, copied]) { expect(toolNames(copyCtx, handle.agent)).toEqual(expect.arrayContaining([ - 'cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager', + 'cordis_inspect', 'plugin_manager', ])) } const signal = new AbortController().signal const listed = await executeToolFixture(copyCtx, { callId: brandString('copied-preset-inspect-list'), - name: 'cordis_inspect_list', + name: 'cordis_inspect', arguments: {}, signal, agent: copied.agent, @@ -1139,15 +1150,15 @@ describe('a user preset declared from the shipped cordis rows', () => { onTestFinished(() => { spills.mockRestore() }) const queried = await executeToolFixture(copyCtx, { callId: brandString('copied-preset-inspect-tools'), - name: 'cordis_inspect_query', - arguments: { platform: 'host', provider: 'Tool', method: 'listTools' }, + name: 'cordis_inspect', + arguments: { query: { platform: 'host', provider: 'Tool', method: 'listTools' } }, signal, agent: copied.agent, }) expect(queried.isError).toBe(false) // The tool catalog may exceed the inline budget; assert its complete stored text. const queriedText = spills.mock.calls.at(-1)?.[0].content ?? resultText(queried) - for (const toolName of ['bash', 'cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager']) { + for (const toolName of ['bash', 'cordis_inspect', 'plugin_manager']) { expect(queriedText).toContain(`"name": "${toolName}"`) } @@ -1158,8 +1169,8 @@ describe('a user preset declared from the shipped cordis rows', () => { const listConfigs = async (input: Record, callId: string): Promise => { const page = await executeToolFixture(copyCtx, { callId: brandString(callId), - name: 'cordis_inspect_query', - arguments: { platform: 'host', provider: 'Config', method: 'listConfigs', input }, + name: 'cordis_inspect', + arguments: { query: { platform: 'host', provider: 'Config', method: 'listConfigs', input } }, signal, agent: copied.agent, }) @@ -1177,8 +1188,8 @@ describe('a user preset declared from the shipped cordis rows', () => { expect(firstPage.nextOffset).toBe(5) const projected = await executeToolFixture(copyCtx, { callId: brandString('copied-preset-inspect-config'), - name: 'cordis_inspect_query', - arguments: { platform: 'host', provider: 'Config', method: 'listConfigs', input: { entry: toolsRow!.id } }, + name: 'cordis_inspect', + arguments: { query: { platform: 'host', provider: 'Config', method: 'listConfigs', input: { entry: toolsRow!.id } } }, signal, agent: copied.agent, }) diff --git a/apps/desktop/src/client/WelcomePage.tsx b/apps/desktop/src/client/WelcomePage.tsx index b367061732..6a63dc7249 100644 --- a/apps/desktop/src/client/WelcomePage.tsx +++ b/apps/desktop/src/client/WelcomePage.tsx @@ -142,14 +142,15 @@ export function Welcome({ api }: { api: WelcomeApi }) { if (cancelling || attemptRef.current === null) return setCancelling(true) const current = ++revision.current + let state: AccountView | undefined try { - const state = await api.cancelSignIn(attemptRef.current.id) - if (mounted.current && revision.current === current) showAccount(state) - } catch { + state = await api.cancelSignIn(attemptRef.current.id) + } catch (_cancelFailed) { // The current attempt remains visible so cancellation can be retried. } finally { if (mounted.current) setCancelling(false) } + if (state !== undefined && mounted.current && revision.current === current) showAccount(state) } async function copyLink() { const current = attemptRef.current diff --git a/apps/desktop/src/preload-platform-account.ts b/apps/desktop/src/preload-platform-account.ts index ac7e42f0ae..5733a7fa2c 100644 --- a/apps/desktop/src/preload-platform-account.ts +++ b/apps/desktop/src/preload-platform-account.ts @@ -15,17 +15,18 @@ if (process.isMainFrame && location.origin === allowedOrigin) { try { listener(value) } catch (error) { console.error('Platform locale listener failed', error) } } }) + let value: unknown try { - const value: unknown = ipcRenderer.sendSync(PLATFORM_IPC.bootstrap) - if (typeof value === 'object' && value !== null && 'token' in value && 'origin' in value - && typeof value.token === 'string' && value.token.length > 0 && value.origin === location.origin - && 'locale' in value && (value.locale === 'en_US' || value.locale === 'zh_CN')) { - token = value.token - locale = value.locale - } - } catch { + value = ipcRenderer.sendSync(PLATFORM_IPC.bootstrap) + } catch (_bootstrapFailed) { // Initialization failure retains embedded mode so Platform cannot use browser credentials. } + if (typeof value === 'object' && value !== null && 'token' in value && 'origin' in value + && typeof value.token === 'string' && value.token.length > 0 && value.origin === location.origin + && 'locale' in value && (value.locale === 'en_US' || value.locale === 'zh_CN')) { + token = value.token + locale = value.locale + } contextBridge.exposeInMainWorld('dsh', { protocolVersion: 1, displayMode: 'embedded', diff --git a/apps/web/tests/agent-preset-authoring.e2e.ts b/apps/web/tests/agent-preset-authoring.e2e.ts index 5ab43f206b..0727af2cab 100644 --- a/apps/web/tests/agent-preset-authoring.e2e.ts +++ b/apps/web/tests/agent-preset-authoring.e2e.ts @@ -43,6 +43,16 @@ describe('web e2e: preset roster guidance', () => { it('reads mode details and examples without changing the new-task default', async () => { onTestFailed(() => saveFailureShot(page, 'preset-roster-guide')) const settings = page.getByRole('dialog', { name: '设置' }) + for (const name of ['标准模式', '创造模式']) { + const sharedTrigger = settings.getByRole('button', { name: `模式说明: ${name}`, exact: true }) + await sharedTrigger.click() + const sharedGuide = page.getByRole('dialog', { name, exact: true }) + await sharedGuide.getByText(/只读运行时检查/).waitFor() + expect(await sharedGuide.innerText()).not.toContain('增加了运行时检查') + if (name === '创造模式') expect(await sharedGuide.innerText()).toContain('创造模式专注于定制 DSH') + await page.keyboard.press('Escape') + await sharedGuide.waitFor({ state: 'detached' }) + } const trigger = settings.getByRole('button', { name: '模式说明: PTC 模式', exact: true }) await trigger.click() const guide = page.getByRole('dialog', { name: 'PTC 模式', exact: true }) diff --git a/apps/web/tests/agent-preset-selection.e2e.ts b/apps/web/tests/agent-preset-selection.e2e.ts index 624a5e3f96..2a378530ab 100644 --- a/apps/web/tests/agent-preset-selection.e2e.ts +++ b/apps/web/tests/agent-preset-selection.e2e.ts @@ -486,7 +486,7 @@ it.each([false, true])('starts Creator from Plugins with Coding Tools=%s without expect(scaffold.ctx.sessionProjections.checkpoint(creator.session).agentPreset?.val).toBe('cordis') expect(scaffold.ctx.agentPresets.composedPreset(creator.ctx)).toBe('cordis') expect(scaffold.ctx.tools.schemas(creator).map(tool => tool.name)) - .toEqual(expect.arrayContaining(['cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager'])) + .toEqual(expect.arrayContaining(['cordis_inspect', 'plugin_manager'])) // The Session starts under Creator; a chip selection after the list updates records no switch. expect(creator.session.snapshotEvents().filter(event => event.type === 'agent-preset/selected')).toEqual([]) expect(creator.session.snapshotEvents().some(event => event.type === 'user/message' || event.type === 'turn/start')).toBe(false) diff --git a/apps/web/tests/chat-scroll-contract.e2e.ts b/apps/web/tests/chat-scroll-contract.e2e.ts index bd0090d841..499e6ec062 100644 --- a/apps/web/tests/chat-scroll-contract.e2e.ts +++ b/apps/web/tests/chat-scroll-contract.e2e.ts @@ -264,8 +264,8 @@ async function withScrollWorld( runFailure = error try { await saveFailureShot(world.page, options.failureShot) - } catch { - // Best-effort evidence must never prevent cleanup of the owned world. + } catch (_failureShotFailed) { + // A missing screenshot loses evidence only; cleanup of the owned world and the rethrown run failure still follow. } } let cleanupFailure: unknown @@ -1305,7 +1305,7 @@ describe('web e2e: long Chat scroll contract', () => { const top = viewport.top + element.clientTop return Math.max( Math.abs((railBox.top + railBox.bottom) / 2 - (top + composerBox.top) / 2), - Math.abs(viewport.left + element.clientLeft + element.clientWidth - railBox.right - 12), + Math.abs(railBox.left - viewport.left - element.clientLeft - 12), Math.abs(composerBox.top - buttonBox.bottom - 16), ) }), { timeout: 10_000 }).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) diff --git a/apps/web/tests/expected/agent-preset-selection/header.expected.md b/apps/web/tests/expected/agent-preset-selection/header.expected.md index 2b87066124..3b3e5e3f6e 100644 --- a/apps/web/tests/expected/agent-preset-selection/header.expected.md +++ b/apps/web/tests/expected/agent-preset-selection/header.expected.md @@ -1,5 +1,6 @@ - navigation "Session hierarchy": Seeded turn - text: Minimal mode - button "1 subagent" +- button "Session panel" - button "More actions" - button "Open right sidebar" diff --git a/apps/web/tests/expected/clickable-links-gallery/ui.expected.md b/apps/web/tests/expected/clickable-links-gallery/ui.expected.md index 50cd7bc896..aeecf7ad1c 100644 --- a/apps/web/tests/expected/clickable-links-gallery/ui.expected.md +++ b/apps/web/tests/expected/clickable-links-gallery/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Clickable links gallery + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/cordis-history/ui.expected.md b/apps/web/tests/expected/cordis-history/ui.expected.md index 32e5cba5bc..56eb15e136 100644 --- a/apps/web/tests/expected/cordis-history/ui.expected.md +++ b/apps/web/tests/expected/cordis-history/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Use only Cordis tools. First + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md b/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md index b0546d4998..c75151fd81 100644 --- a/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md +++ b/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md @@ -11,6 +11,7 @@ - banner: - navigation "Session hierarchy": Review deepseek-ai/deepseek-harness#314 - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/github-ready-review/conversation.expected.md b/apps/web/tests/expected/github-ready-review/conversation.expected.md index 9b10e08416..df6aabe092 100644 --- a/apps/web/tests/expected/github-ready-review/conversation.expected.md +++ b/apps/web/tests/expected/github-ready-review/conversation.expected.md @@ -11,6 +11,7 @@ - banner: - navigation "Session hierarchy": Review deepseek-ai/deepseek-harness#314 - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/goal-command-presentation/ui.expected.md b/apps/web/tests/expected/goal-command-presentation/ui.expected.md index ac468809d2..60dcaaa04a 100644 --- a/apps/web/tests/expected/goal-command-presentation/ui.expected.md +++ b/apps/web/tests/expected/goal-command-presentation/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": workspace - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md b/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md index 6eee07ead9..a8f1951ae4 100644 --- a/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md +++ b/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": CJK strong emphasis + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/markdown-images/ui.expected.md b/apps/web/tests/expected/markdown-images/ui.expected.md index 4923acd2e6..b3fbac6447 100644 --- a/apps/web/tests/expected/markdown-images/ui.expected.md +++ b/apps/web/tests/expected/markdown-images/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Markdown image policy + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md b/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md index d2d68c6021..403c938a2b 100644 --- a/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md +++ b/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Inline code links + - button "Session panel" - button "More actions" - tablist: - tab "Chat" [selected] diff --git a/apps/web/tests/expected/math-rendering/ui.expected.md b/apps/web/tests/expected/math-rendering/ui.expected.md index 82c51f246e..b31a0cb736 100644 --- a/apps/web/tests/expected/math-rendering/ui.expected.md +++ b/apps/web/tests/expected/math-rendering/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Math rendering + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/reference-composer/order.expected.md b/apps/web/tests/expected/reference-composer/order.expected.md index e13baba024..f2a467af85 100644 --- a/apps/web/tests/expected/reference-composer/order.expected.md +++ b/apps/web/tests/expected/reference-composer/order.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": Reference order target + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/schedule-recommendations-en.expected.md b/apps/web/tests/expected/schedule-recommendations-en.expected.md new file mode 100644 index 0000000000..57a00d021e --- /dev/null +++ b/apps/web/tests/expected/schedule-recommendations-en.expected.md @@ -0,0 +1,17 @@ +- region "Recommended": + - heading "Recommended" [level=2] + - list: + - listitem: + - button "Daily brief": Daily brief Recent changes in the workspace and what needs follow-up, with what to do first today. Weekdays at 9:00 + - listitem: + - button "Issue scan": Issue scan Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply. Weekdays at {{clock}} + - listitem: + - button "Plugin compatibility check": Plugin compatibility check When a new DSH version ships, check whether installed and self-made plugins need changes. Daily at {{clock}} + - listitem: + - button "Topic and paper tracking": Topic and paper tracking Search for news and new arXiv papers on chosen topics and list the key points. Daily at 9:00 + - listitem: + - button "Branch and worktree cleanup": Branch and worktree cleanup List local branches and worktrees whose pull requests merged or closed, and delete them after confirmation. Fridays at {{clock}} + - listitem: + - button "Weather and travel": Weather and travel Weather for today and the next three days, with a note when an umbrella or warmer clothes are needed. Daily at 7:30 + - listitem: + - button "Weekly workout plan": Weekly workout plan Plan next week's workouts around your goals and training days. Sundays at {{clock}} diff --git a/apps/web/tests/expected/schedule-recommendations-zh.expected.md b/apps/web/tests/expected/schedule-recommendations-zh.expected.md new file mode 100644 index 0000000000..68c90f0426 --- /dev/null +++ b/apps/web/tests/expected/schedule-recommendations-zh.expected.md @@ -0,0 +1,17 @@ +- region "推荐": + - heading "推荐" [level=2] + - list: + - listitem: + - button "每日简报": 每日简报 汇总工作区最近的变化和待跟进的事,列出今天先做什么。 工作日 9:00 + - listitem: + - button "Issue 扫描": Issue 扫描 把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。 工作日 {{clock}} + - listitem: + - button "插件兼容检查": 插件兼容检查 DSH 出新版本时,检查已装的插件和自己做的插件要不要改。 每天 {{clock}} + - listitem: + - button "主题和论文追踪": 主题和论文追踪 搜索关注主题的新消息和 arXiv 新论文,各列几条要点。 每天 9:00 + - listitem: + - button "分支和 worktree 清理": 分支和 worktree 清理 列出 PR 已合并或关闭的本地分支和 worktree,确认后再删。 周五 {{clock}} + - listitem: + - button "天气和出行": 天气和出行 今天和接下来三天的天气,要带伞或加衣时提一句。 每天 7:30 + - listitem: + - button "一周运动计划": 一周运动计划 按目标和每周能练的日子排好下周的运动计划。 周日 {{clock}} diff --git a/apps/web/tests/expected/sidebar-subagent-activity/compact-running.expected.md b/apps/web/tests/expected/sidebar-subagent-activity/compact-running.expected.md index 7a26f1bae7..6e56147a9a 100644 --- a/apps/web/tests/expected/sidebar-subagent-activity/compact-running.expected.md +++ b/apps/web/tests/expected/sidebar-subagent-activity/compact-running.expected.md @@ -2,6 +2,7 @@ - navigation "Session hierarchy": Delegate a background job. - button "1 subagent" - button "1 background job" + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md b/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md index 4c06982b08..c7a72552a8 100644 --- a/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md +++ b/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": /user-invoke-demo @"meeting notes-this-i - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/skill-user-invoke/ui.expected.md b/apps/web/tests/expected/skill-user-invoke/ui.expected.md index db8db2840a..d13ca7947f 100644 --- a/apps/web/tests/expected/skill-user-invoke/ui.expected.md +++ b/apps/web/tests/expected/skill-user-invoke/ui.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": /user-invoke-demo @"meeting notes-this-i - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/stats-paged-history/ui.expected.md b/apps/web/tests/expected/stats-paged-history/ui.expected.md index 26d522dbe9..adc9016dd1 100644 --- a/apps/web/tests/expected/stats-paged-history/ui.expected.md +++ b/apps/web/tests/expected/stats-paged-history/ui.expected.md @@ -1,5 +1,6 @@ - banner: - navigation "Session hierarchy": {{workspace}} + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/steer-all/mid-steer.expected.md b/apps/web/tests/expected/steer-all/mid-steer.expected.md index dd9afda70c..b917214246 100644 --- a/apps/web/tests/expected/steer-all/mid-steer.expected.md +++ b/apps/web/tests/expected/steer-all/mid-steer.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/steer-all/settled-expanded.expected.md b/apps/web/tests/expected/steer-all/settled-expanded.expected.md index 3977249952..65213117f6 100644 --- a/apps/web/tests/expected/steer-all/settled-expanded.expected.md +++ b/apps/web/tests/expected/steer-all/settled-expanded.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/expected/steer-all/settled.expected.md b/apps/web/tests/expected/steer-all/settled.expected.md index 903a4d6021..db22bb3b36 100644 --- a/apps/web/tests/expected/steer-all/settled.expected.md +++ b/apps/web/tests/expected/steer-all/settled.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Use the ask_user_question tool to - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index f84c79925a..909fd7fca2 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -2022,9 +2022,11 @@ it.skipIf(MODE === 'record')('reviews a change request by layer, hides test file const lens = view.getByRole('radiogroup', { name: '分层透镜', exact: true }) const tree = view.getByRole('navigation') await expect.poll(() => lens.getByRole('radio').allTextContents()).toEqual(['全部6', '接口1', '实现2', '测试3']) - // The lens spans the file tree with the filter field's insets, and its divider continues the tree's border. + // The lens spans the file tree with the filter field's insets, and its divider continues the tree's border. The radio group + // sits in the element that measures it, inside the toolbar cell above the tree. const [lensBox, fieldBox, cellBox, treeBox] = await Promise.all([ - lens.boundingBox(), tree.locator('input').locator('xpath=..').boundingBox(), lens.locator('xpath=..').boundingBox(), tree.locator('xpath=..').boundingBox(), + lens.boundingBox(), tree.locator('input').locator('xpath=..').boundingBox(), lens.locator('xpath=../..').boundingBox(), + tree.locator('xpath=..').boundingBox(), ]) if (lensBox === null || fieldBox === null || cellBox === null || treeBox === null) throw new Error('Lens and tree must be visible') expect([lensBox.x, lensBox.x + lensBox.width]).toEqual([fieldBox.x, fieldBox.x + fieldBox.width]) diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index 736ba7c228..d3528d9eec 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -450,10 +450,11 @@ export interface LaunchOptions { harnessHome?: string } -/** Dispose the booted tree and remove both owned temp roots, reporting every independent cleanup failure. */ -async function cleanupScaffoldWorld(ctx: Context, workspaceCwd: string, persistenceRoot: string): Promise { +/** Dispose the booted tree and remove the owned temp roots and overlay file, reporting every independent cleanup failure. */ +async function cleanupScaffoldWorld(ctx: Context, workspaceCwd: string, persistenceRoot: string, overlayPath: string): Promise { const failures: unknown[] = [] await Promise.resolve(ctx.fiber.dispose()).catch((error: unknown) => failures.push(error)) + await rm(overlayPath, { force: true }).catch((error: unknown) => failures.push(error)) await rm(workspaceCwd, { recursive: true, force: true }).catch((error: unknown) => failures.push(error)) await rm(persistenceRoot, { recursive: true, force: true }).catch((error: unknown) => failures.push(error)) return failures @@ -526,6 +527,8 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise layer.packageName), - overlays: processOverlays, telemetryDisabledEnv: undefined, + overlayPaths: [overlayPath], telemetryDisabledEnv: undefined, } // HMR gates file-driven reloads on application readiness, which the // launcher commits after boot; this direct harness is ready at once. @@ -975,7 +980,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise cleanupFailures.push(closeError)) } @@ -1051,7 +1056,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise { it('manages cross-Session tasks from the sidebar without activating their Sessions', async () => { const otherSessionId = brandString('schedule-manager-other-session') await seedSession(scaffold, await readFile(CATALOG_FIXTURE, 'utf8'), otherSessionId, 'standard') - const other = await scaffold.ctx.schedule.create({ prompt: 'Inspect the second workspace deployment', title: 'Second workspace deployment', timing: { kind: 'at', at: '2099-08-25T12:08:00.000Z' }, target: { kind: 'session', sessionId: otherSessionId } }, otherSessionId) + const other = await scaffold.ctx.schedule.create({ prompt: 'Inspect the second workspace deployment', title: 'Second workspace deployment', timing: { kind: 'at', at: '2099-08-25T12:08:00.000Z' }, target: { kind: 'session', sessionId: otherSessionId } }, CATALOG_SESSION_ID) await page.getByRole('button', { name: 'Automation tasks', exact: true }).click() const manager = page.getByTestId('task-manager-page') await manager.getByRole('heading', { name: 'Automation tasks', exact: true }).waitFor() const tasks = manager.getByRole('list', { name: 'Task catalog' }) await expect.poll(() => tasks.getByRole('listitem').count()).toBe(4) + const creatorMark = page.locator(`[data-row-key="session:${CATALOG_SESSION_ID}"] [data-session-schedule-mark]`) + await expect.poll(() => creatorMark.textContent()).toBe('3 automation tasks') expect(scaffold.ctx.agents.get(CATALOG_SESSION_ID)).toBeUndefined() expect(scaffold.ctx.agents.get(otherSessionId)).toBeUndefined() diff --git a/apps/web/tests/schedule-manual.e2e.ts b/apps/web/tests/schedule-manual.e2e.ts index 54d4cf50f6..abf438f7e8 100644 --- a/apps/web/tests/schedule-manual.e2e.ts +++ b/apps/web/tests/schedule-manual.e2e.ts @@ -1,9 +1,10 @@ /** Schedule creation, prompt prefill, and editing through the shipped Web composition. */ -import { chromium } from 'playwright' +import { fileURLToPath } from 'node:url' +import { chromium, type Locator } from 'playwright' import { expect, it } from 'vitest' import type { ScheduleTiming } from '@deepseek-ai/dsh-schedule/client' -import { launchWebScaffold, watchConsole } from './scaffold.ts' -import { writeComposerDraft } from './support.ts' +import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode } from './scaffold.ts' +import { revealNavigationDrawer, writeComposerDraft } from './support.ts' it.each([ { locale: 'en', panel: 'Automation tasks', create: 'New', menu: 'Choose a creation method', chat: 'Create in a session', @@ -48,6 +49,96 @@ it.each([ } }) +it.each([ + { locale: 'en', panel: 'Automation tasks', heading: 'Recommended', title: 'Daily brief', + prompt: 'Create an automation task named "Daily brief": every weekday at 9:00, review the last 24 hours of changes in the current workspace and list what needs my follow-up and what to do first today; when the workspace is a code repository, also cover new commits, pull requests awaiting my review, and failing CI.' }, + { locale: 'zh', panel: '自动化任务', heading: '推荐', title: '每日简报', + prompt: '创建一个名为「每日简报」的自动化任务:每个工作日 9:00 查看当前工作区过去 24 小时的变化,列出需要我跟进的事和今天先做的事;工作区是代码仓库时,也看新提交、待我评审的 PR 和失败的 CI。' }, +])('prefills a recommended task request from the empty task page in $locale', async (copy) => { + const scaffold = await launchWebScaffold({ firstUse: true }) + let browser: Awaited> | undefined + try { + browser = await chromium.launch() + const page = await browser.newPage({ viewport: { width: 1440, height: 960 }, locale: copy.locale }) + await page.addInitScript((locale) => { localStorage.setItem('dsh.locale', locale) }, copy.locale) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + const input = page.locator('[data-composer-input][contenteditable="true"]').first() + for (const draft of ['', 'Existing unsent draft']) { + await writeComposerDraft(page, input, draft) + await page.getByRole('button', { name: copy.panel, exact: true }).click() + const manager = page.getByTestId('task-manager-page') + const recommendations = manager.getByRole('region', { name: copy.heading, exact: true }) + const recommendation = recommendations.getByRole('button', { name: copy.title, exact: true }) + await recommendation.waitFor() + expect(await recommendations.getByRole('button').count()).toBe(7) + if (draft === '') { + expect(await recommendationColumns(recommendations)).toBe(2) + await compareOrRefreshGolden( + fileURLToPath(new URL(`./expected/schedule-recommendations-${copy.locale}.expected.md`, import.meta.url)), + await captureStableAria(page, '[data-testid="schedule-recommendations"]', scaffold.workspaceCwd), + webSnapshotMode(), + ) + } + await recommendation.click() + await manager.waitFor({ state: 'detached' }) + await input.getByText(copy.prompt, { exact: true }).waitFor() + expect(await input.evaluate(element => [...element.children].map(paragraph => paragraph.textContent).join('\n'))) + .toBe(draft === '' ? copy.prompt : `${draft}\n${copy.prompt}`) + const events = scaffold.ctx.agents.list().flatMap(agent => agent.session.snapshotEvents()) + expect(events.filter(event => event.type === 'user/message' || event.type === 'turn/start')).toEqual([]) + expect(await scaffold.ctx.schedule.catalog()).toEqual([]) + } + expect(tripwire.pageErrors).toEqual([]) + } finally { + try { await browser?.close() } finally { await scaffold.close() } + } +}) + +/** Number of grid tracks the recommendation list lays its tiles in. */ +async function recommendationColumns(recommendations: Locator): Promise { + return recommendations.getByRole('list').evaluate(list => getComputedStyle(list).gridTemplateColumns.split(' ').length) +} + +it.each([ + { locale: 'en', panel: 'Automation tasks', title: 'Daily brief' }, + { locale: 'de', panel: 'Automatisierungsaufgaben', title: 'Tagesüberblick' }, +] as const)('shows every recommendation title and description in full on phone and desktop widths in $locale', async (copy) => { + const scaffold = await launchWebScaffold({ firstUse: true }) + let browser: Awaited> | undefined + try { + browser = await chromium.launch() + // 680px puts the list just above the 600px column breakpoint, where each column is narrowest. + for (const { width, columns } of [{ width: 390, columns: 1 }, { width: 680, columns: 2 }, { width: 1440, columns: 2 }]) { + const phone = width < 600 + const page = await browser.newPage({ viewport: { width, height: 900 }, isMobile: phone, hasTouch: phone, locale: copy.locale }) + await page.addInitScript((locale) => { localStorage.setItem('dsh.locale', locale) }, copy.locale) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await revealNavigationDrawer(page, copy.locale) + await page.getByRole('button', { name: copy.panel, exact: true }).click() + const recommendations = page.getByTestId('schedule-recommendations') + await recommendations.getByRole('button', { name: copy.title, exact: true }).waitFor() + await page.evaluate(() => document.fonts.ready) + expect(await recommendationColumns(recommendations)).toBe(columns) + // The title carries the button's name and the first description reference is the description; neither clips. + expect(await recommendations.getByRole('button').evaluateAll(buttons => buttons.flatMap((button) => { + const name = button.getAttribute('aria-label')! + const title = [...button.querySelectorAll('span')].find(span => span.textContent === name)! + const description = document.getElementById(button.getAttribute('aria-describedby')!.split(' ')[0]!)! + return [ + ...title.scrollWidth > title.clientWidth ? [`title: ${name}`] : [], + ...description.scrollHeight > description.clientHeight ? [`description: ${name}`] : [], + ] + }))).toEqual([]) + expect(tripwire.pageErrors).toEqual([]) + await page.close() + } + } finally { + try { await browser?.close() } finally { await scaffold.close() } + } +}) + it('opens stored timing fields immediately without selecting another repeat option', async () => { const scaffold = await launchWebScaffold({ firstUse: true }) let browser: Awaited> | undefined diff --git a/apps/web/tests/session-panel-layout.e2e.ts b/apps/web/tests/session-panel-layout.e2e.ts new file mode 100644 index 0000000000..7d3186d0d4 --- /dev/null +++ b/apps/web/tests/session-panel-layout.e2e.ts @@ -0,0 +1,253 @@ +/** + * Session panel layout in the shipped Web composition. The panel's stylesheet + * decides whether the Chat View's end gutter holds the docked panel and tells + * the plugin through a 1px dock probe, and it lays out the rows that + * contributors mark. jsdom cannot evaluate that stylesheet, so this measures + * the probe, the panel, and the toggle around the docking boundary, and the + * working folder row without and with a directory context menu. + */ +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished } from 'vitest' +import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' +import type { SessionId } from '@deepseek-ai/dsh-session' +import { brandString } from '@deepseek-ai/dsh-brand' +import { launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts' +import { newEnglishPage, saveFailureShot } from './support.ts' + +const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v3.jsonl', import.meta.url)) +const MODE = webSnapshotMode() +const SEED_ID = brandString('session-panel-layout-web-e2e') +/** The default transcript width in a frame wide enough to dock. */ +const TRANSCRIPT = 880 +/** The gutter that holds the docked panel: 40px clear of the transcript, its 300px minimum width, and the 8px edge inset. */ +const DOCK_GUTTER = 348 + +/** What the layout says about docking: the gutter, the probe, the panel's presentation and insets, and the toggle. */ +function docking(page: Page) { + return page.evaluate(() => { + const layer = document.querySelector('[data-chat-aside]') + const column = document.querySelector('[data-chat-flow]') + const probe = document.querySelector('[data-session-panel-probe]') + const toggle = document.querySelector('[data-session-panel-toggle]') + if (layer === null || column === null || probe === null || toggle === null) { + throw new Error('aside layer, transcript column, dock probe, or panel toggle is missing') + } + const frame = layer.getBoundingClientRect() + const flow = column.getBoundingClientRect() + const panel = document.querySelector('[data-session-panel]') + const box = panel?.getBoundingClientRect() + return { + gutter: (frame.width - flow.width) / 2, + probe: probe.getBoundingClientRect().width, + presentation: panel?.dataset['sessionPanel'] ?? null, + expanded: toggle.getAttribute('aria-expanded'), + panel: box === undefined ? null : { width: box.width, clear: box.left - flow.right, edge: frame.right - box.right }, + } + }) +} + +/** Open the seeded Session through the sidebar and wait for the panel's dock probe. */ +async function openSeed(page: Page): Promise { + const session = page.locator(`[data-row-key="session:${SEED_ID}"]`) + await expect.poll(async () => { + if (await session.isVisible()) return true + const group = page.locator('[role="treeitem"][aria-expanded]').first() + if (await group.count() > 0 && await group.getAttribute('aria-expanded') === 'false') await group.click() + return session.isVisible() + }, { timeout: 15_000 }).toBe(true) + await session.click() + await page.locator('[data-session-panel-probe]').waitFor({ state: 'attached', timeout: 30_000 }) +} + +/** Wait until the panel shows this way (null: not at all) and its entrance has finished. */ +async function shows(page: Page, presentation: 'docked' | 'overlay' | null): Promise { + await expect.poll(async () => (await docking(page)).presentation, { timeout: 10_000 }).toBe(presentation) + if (presentation === null) return + await page.locator('[data-session-panel]').evaluate(async (element) => { + await Promise.all(element.getAnimations().map(animation => animation.finished)) + }) +} + +/** + * The working folder row as laid out: its line, how far the centers of its + * icon and menu columns sit from its edges, the room after its text, and what + * the pointer state shows. `menu` is null while the menu part renders nothing. + */ +function rowLayout(page: Page) { + return page.locator('[data-session-panel] [data-session-panel-project]').evaluate((element) => { + const box = element.getBoundingClientRect() + const icon = element.querySelector('[data-row-part="icon"]')!.getBoundingClientRect() + const content = element.querySelector('[data-row-part="content"]')! + const menu = element.querySelector('[data-row-part="menu"]')! + const column = menu.getBoundingClientRect() + const button = menu.querySelector('button')?.getBoundingClientRect() + return { + height: box.height, + iconCenter: icon.left + icon.width / 2 - box.left, + iconSize: [icon.width, icon.height], + clipped: getComputedStyle(content).textOverflow, + afterText: box.right - content.getBoundingClientRect().right, + menu: button === undefined + ? null + : { + center: box.right - (column.left + column.width / 2), + target: [button.width, button.height], + opacity: getComputedStyle(menu).opacity, + }, + hovered: element.matches(':hover'), + highlighted: getComputedStyle(element).backgroundColor !== 'rgba(0, 0, 0, 0)', + } + }) +} + +describe.skipIf(MODE === 'record')('web e2e: Session panel layout', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + /** Viewport width the application keeps outside the Chat frame. */ + let chrome = 0 + + /** Resize the window so the Chat View's end gutter is exactly `gutter`, and wait for the layout to follow. */ + async function setGutter(gutter: number): Promise { + await page.setViewportSize({ width: TRANSCRIPT + 2 * gutter + chrome, height: page.viewportSize()!.height }) + await expect.poll(async () => (await docking(page)).gutter, { timeout: 10_000 }).toBe(gutter) + } + + beforeAll(async () => { + scaffold = await launchWebScaffold() + await seedSession(scaffold, await readFile(FIXTURE, 'utf8'), SEED_ID) + browser = await chromium.launch() + page = await newEnglishPage(browser) + await page.emulateMedia({ reducedMotion: 'reduce' }) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + }, 120_000) + + /** Open the seeded Session and learn how much of the window lies outside the Chat frame. */ + async function openSession(): Promise { + if (chrome !== 0) return + await openSeed(page) + const frame = await page.locator('[data-chat-aside]').evaluate(element => element.getBoundingClientRect().width) + chrome = page.viewportSize()!.width - frame + } + + afterAll(async () => { + const failures: unknown[] = [] + try { await browser?.close() } catch (error) { failures.push(error) } + try { await scaffold?.close() } catch (error) { failures.push(error) } + if (failures.length > 0) throw new AggregateError(failures, 'Session panel layout teardown failed') + }) + + it('docks exactly from the gutter that holds the panel at its minimum width', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-session-panel-dock')) + await openSession() + expect(Number.isInteger(chrome)).toBe(true) + + await setGutter(DOCK_GUTTER - 1) + await shows(page, null) + expect(await docking(page)).toEqual({ gutter: DOCK_GUTTER - 1, probe: 0, presentation: null, expanded: 'false', panel: null }) + + // Half a pixel short, the probe is half a pixel wide and the panel stays hidden. + await setGutter(DOCK_GUTTER - 0.5) + expect(await docking(page)).toEqual({ gutter: DOCK_GUTTER - 0.5, probe: 0.5, presentation: null, expanded: 'false', panel: null }) + + await setGutter(DOCK_GUTTER) + await shows(page, 'docked') + expect(await docking(page)).toEqual({ + gutter: DOCK_GUTTER, probe: 1, presentation: 'docked', expanded: 'true', panel: { width: 300, clear: 40, edge: 8 }, + }) + + // A wider gutter widens the panel to its maximum at the same edge inset; the probe stays 1px. + await setGutter(DOCK_GUTTER + 100) + expect(await docking(page)).toEqual({ + gutter: DOCK_GUTTER + 100, probe: 1, presentation: 'docked', expanded: 'true', panel: { width: 360, clear: 80, edge: 8 }, + }) + + await setGutter(DOCK_GUTTER - 1) + await shows(page, null) + expect((await docking(page)).expanded).toBe('false') + expect(tripwire.pageErrors).toEqual([]) + }) + + it('floats narrower than it docks, at the same edge inset, and docks once the gutter holds it', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-session-panel-overlay')) + await openSession() + const toggle = page.locator('[data-session-panel-toggle]') + await setGutter(260) + await shows(page, null) + await toggle.click() + await shows(page, 'overlay') + const overlay = await docking(page) + expect(overlay).toMatchObject({ probe: 0, presentation: 'overlay', expanded: 'true', panel: { width: 280, edge: 8 } }) + // The overlay covers part of the transcript instead of keeping clear of it. + expect(overlay.panel?.clear).toBeLessThan(0) + + await page.keyboard.press('Escape') + await shows(page, null) + expect((await docking(page)).expanded).toBe('false') + + // An open overlay gives way to the docked panel when the window widens enough. + await toggle.click() + await shows(page, 'overlay') + await setGutter(DOCK_GUTTER) + await shows(page, 'docked') + expect(await docking(page)).toMatchObject({ probe: 1, expanded: 'true', panel: { width: 300, clear: 40, edge: 8 } }) + expect(tripwire.pageErrors).toEqual([]) + }) + + it('lays the working folder row out by its marks, with no room or highlight for a menu that renders nothing', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-session-panel-row')) + await openSession() + await setGutter(DOCK_GUTTER + 100) + await shows(page, 'docked') + const row = page.locator('[data-session-panel] [data-session-panel-project]') + await row.waitFor() + await page.mouse.move(5, 5) + // This composition registers no directory menu entries, so the shared More button renders nothing: + // the text runs to the row's 6px padding, and the row has nothing to highlight for. + const resting = { height: 28, iconCenter: 14, iconSize: [16, 16], clipped: 'ellipsis', afterText: 6, menu: null, highlighted: false } + expect(await rowLayout(page)).toEqual({ ...resting, hovered: false }) + await row.hover() + expect(await rowLayout(page)).toEqual({ ...resting, hovered: true }) + expect(tripwire.pageErrors).toEqual([]) + }) + + it('puts a rendered menu on the panel end column and shows it, with the row highlight, on hover', async () => { + // The directory context menu comes from Open In; SSH facts keep it from probing this runner's native applications. + const withMenu = await launchWebScaffold({ openInAppEnvironment: createLaunchEnvironmentSnapshot([ + { source: 'process', values: { SSH_CONNECTION: '10.0.0.2 55000 10.0.0.9 22' } }, + ]) }) + onTestFinished(() => withMenu.close()) + await seedSession(withMenu, await readFile(FIXTURE, 'utf8'), SEED_ID) + const other = await newEnglishPage(browser) + onTestFinished(() => other.close()) + onTestFailed(() => saveFailureShot(other, 'web-e2e-session-panel-row-menu')) + await other.emulateMedia({ reducedMotion: 'reduce' }) + const errors = watchConsole(other) + // Wide enough for the gutter to hold the docked panel. + await other.setViewportSize({ width: 2200, height: 1000 }) + await other.goto(withMenu.authenticatedUrl, { waitUntil: 'load' }) + await openSeed(other) + await shows(other, 'docked') + const row = other.locator('[data-session-panel] [data-session-panel-project]') + await row.locator('[data-row-part="menu"] button').waitFor({ state: 'attached' }) + await other.mouse.move(5, 5) + // The 16px menu column and the 8px gap before it follow the text; the 24px target reaches past the column. + const resting = { height: 28, iconCenter: 14, iconSize: [16, 16], clipped: 'ellipsis', afterText: 30 } + expect(await rowLayout(other)).toEqual({ + ...resting, menu: { center: 14, target: [24, 24], opacity: '0' }, hovered: false, highlighted: false, + }) + await row.hover() + await expect.poll(async () => (await rowLayout(other)).menu?.opacity).toBe('1') + expect(await rowLayout(other)).toEqual({ + ...resting, menu: { center: 14, target: [24, 24], opacity: '1' }, hovered: true, highlighted: true, + }) + await other.mouse.move(5, 5) + await expect.poll(async () => (await rowLayout(other)).highlighted).toBe(false) + expect(errors.pageErrors).toEqual([]) + }) +}) diff --git a/apps/web/tests/shipped-composition.e2e.ts b/apps/web/tests/shipped-composition.e2e.ts index 5ea8df6021..24f053d133 100644 --- a/apps/web/tests/shipped-composition.e2e.ts +++ b/apps/web/tests/shipped-composition.e2e.ts @@ -464,18 +464,14 @@ function assertLeanChildRecord(agent: Agent): void { } /** - * The catalog the shipped Web composition puts in front of the model, minus the - * ripgrep-dependent pair below. The absences are deliberate, not incidental - * gaps: the `cordis_*` toolset executes model-written JavaScript that no - * sandbox row confines, `mcp_*` servers spawn outside `ctx.shell`, and `ralph` - * runs unsupervised rounds whose completion is a worker self-report. - * `web_fetch` is present because it adds no network reach beyond the - * mounted shell tools. The composition - * Agent Note owns the rationale and its sources. + * The shipped Standard catalog, minus the ripgrep-dependent pair below. + * Runtime inspection is read-only. Generated-code execution tools, external + * MCP servers, and ralph are not enabled in this preset. */ const EXPECTED_TOOLS = [ 'ask_user_question', 'bash', + 'cordis_inspect', 'create_goal', 'edit', 'exit_plan_mode', diff --git a/apps/web/tests/sidebar-right.e2e.ts b/apps/web/tests/sidebar-right.e2e.ts index c1027b1d54..ea9784b904 100644 --- a/apps/web/tests/sidebar-right.e2e.ts +++ b/apps/web/tests/sidebar-right.e2e.ts @@ -496,6 +496,25 @@ describe('web e2e: shipped right Sidebar', () => { expect(await filesTab.locator('[data-dockkit-tab-close]').count()).toBe(1) const guideTab = column.locator('[data-dockkit-tab]').filter({ hasText: 'Start' }) expect(await guideTab.locator('[data-dockkit-tab-close]').count()).toBe(1) + // A pane shorter than the guide scrolls it from the compass to the last capsule. + const viewport = page.viewportSize() + if (viewport === null) throw new Error('expected a fixed viewport') + const guide = column.locator('[data-sidebar-right-guide]') + await page.setViewportSize({ width: viewport.width, height: 240 }) + try { + await expect.poll(async () => await guide.evaluate(node => node.scrollHeight > node.clientHeight)).toBe(true) + expect(await guide.evaluate(node => node.scrollTop)).toBe(0) + const lastEntry = guide.locator('[data-sidebar-right-guide-entry]').last() + await guide.evaluate((node) => { node.scrollTop = node.scrollHeight }) + expect(await guide.evaluate(node => node.scrollTop)).toBeGreaterThan(0) + expect(await lastEntry.evaluate((node) => { + const entry = node.getBoundingClientRect() + const pane = node.closest('[data-sidebar-right-guide]')?.getBoundingClientRect() + return pane !== undefined && entry.top >= pane.top && entry.bottom <= pane.bottom + })).toBe(true) + } finally { + await page.setViewportSize(viewport) + } // Back to the seeded shape the cases below start from. await guideTab.hover() await guideTab.locator('[data-dockkit-tab-close]').click() diff --git a/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md b/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md index 94a7638c3f..64585d3be8 100644 --- a/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md +++ b/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md @@ -1,6 +1,7 @@ - banner: - navigation "Session hierarchy": Stream one TypeScript fence for - text: Standard mode + - button "Session panel" - button "More actions" - button "Open right sidebar" - tablist: diff --git a/apps/web/tests/standard-dsh-doc.e2e.ts b/apps/web/tests/standard-dsh-doc.e2e.ts index 26d920ac98..fceee7d3c6 100644 --- a/apps/web/tests/standard-dsh-doc.e2e.ts +++ b/apps/web/tests/standard-dsh-doc.e2e.ts @@ -38,8 +38,7 @@ it('lists dsh-doc once without loading instructions or calling tools for an ordi expect(events.filter(event => event.type === 'user/message' && event.data.source.kind === 'skill-invocation')).toEqual([]) const names = scaffold.ctx.tools.schemas(agent).map(tool => tool.name) - expect(names).not.toContain('cordis_inspect_list') - expect(names).not.toContain('cordis_inspect_query') + expect(names).toContain('cordis_inspect') await page.getByText('READY', { exact: true }).waitFor() await assertFixtureInventory(dirname(FIXTURE), ['session.v4.jsonl']) } finally { diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index c78ef64f6e..0dd362e431 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -308,14 +308,14 @@ export function probeFreePort(): Promise { * @param page - browser page with the mounted sidebar. * @param locale - current UI language. */ -export async function revealNavigationDrawer(page: Page, locale: 'en' | 'zh' | 'ja'): Promise { +export async function revealNavigationDrawer(page: Page, locale: 'en' | 'zh' | 'ja' | 'de'): Promise { const drawer = await page.evaluate(() => window.innerWidth < 768 && !document.documentElement.hasAttribute('data-windows-titlebar')) await page.waitForFunction(expected => Boolean(document.querySelector('[data-sidebar-drawer]')) === expected, drawer) const closed = page.locator('[data-sidebar-drawer][data-sidebar-collapsed]') if (await closed.count() === 0) return await page.locator('[data-shell-leading]').getByRole('button', { - name: { en: 'Open sidebar', zh: '打开侧边栏', ja: 'サイドバーを開く' }[locale], exact: true, + name: { en: 'Open sidebar', zh: '打开侧边栏', ja: 'サイドバーを開く', de: 'Seitenleiste öffnen' }[locale], exact: true, }).click() await closed.waitFor({ state: 'detached' }) } @@ -419,8 +419,8 @@ export async function saveFailureShot(page: Page, name: string): Promise { mkdirSync(dir, { recursive: true }) try { await page.screenshot({ path: `${dir}/${name}.png`, fullPage: true }) - } catch { - // Best-effort evidence: a dead page/browser at failure time must not mask the real assertion error. + } catch (_screenshotFailed) { + // Screenshot evidence is optional: a dead page/browser at failure time must not mask the real assertion error. } } diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index bee2edcb35..ba45e4c45c 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -25,6 +25,7 @@ "exclude": [ "tests/home-whale.e2e.ts", "tests/sidebar-drawer.e2e.ts", + "tests/session-panel-layout.e2e.ts", "tests/creation-recommendations.e2e.ts", "tests/plugin-recommendations.e2e.ts", "tests/deepseek-chat-import.e2e.ts", diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 9e3247f2a2..8474aa872d 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -262,7 +262,7 @@ export interface Config { ## `@deepseek-ai/dsh-api-session-controller` - `inject`: `agentDefaultModel` · `agents` · `attachments` · `fileUploads` · `fs` · `llm` · `remoteAccess` · `sessions` · `sessionProjections` · `sessionQuery` · `typert` · `typertGateway` · `workspaceRegistry` -- `source`: [`packages/api/session-controller/src/index.ts:111`](../packages/api/session-controller/src/index.ts) +- `source`: [`packages/api/session-controller/src/index.ts:83`](../packages/api/session-controller/src/index.ts) ```ts config-catalog /** Session Controller deployment policy. */ @@ -2740,7 +2740,7 @@ export interface Config { - `inject`: `shell` · `approval` · `sessions` · `agents` · `sessionProjections` - `refs`: [`ApprovalPolicy`](subsystems/approval.md) · [`SandboxMode`](subsystems/sandbox.md) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/interaction/permission-presets/src/index.ts:154`](../packages/interaction/permission-presets/src/index.ts) +- `source`: [`packages/interaction/permission-presets/src/index.ts:161`](../packages/interaction/permission-presets/src/index.ts) ```ts config-catalog /** The {@link PermissionPresetService} config: preset table and composition default. */ @@ -5179,7 +5179,7 @@ export interface Config { ## `@deepseek-ai/dsh-working-directory` - `inject`: `fs` · `sessionProjections` · `systemPrompt` -- `source`: [`packages/session/working-directory/src/index.ts:70`](../packages/session/working-directory/src/index.ts) +- `source`: [`packages/session/working-directory/src/index.ts:64`](../packages/session/working-directory/src/index.ts) ```ts config-catalog /** Deployment default for Sessions without an original project directory. */ @@ -5271,6 +5271,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-schedule` | — | [`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts) | | `@deepseek-ai/dsh-client-ui-secret-mask` | — | [`packages/client/ui-secret-mask/src/index.ts`](../packages/client/ui-secret-mask/src/index.ts) | | `@deepseek-ai/dsh-client-ui-session` | — | [`packages/client/ui-session/src/index.ts`](../packages/client/ui-session/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-session-panel` | — | [`packages/client/ui-session-panel/src/index.ts`](../packages/client/ui-session-panel/src/index.ts) | | `@deepseek-ai/dsh-client-ui-session-status` | `remoteAccess` · `sessions` · `sessionPersistence` · `typert` | [`packages/client/ui-session-status/src/index.ts`](../packages/client/ui-session-status/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings` | — | [`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-agent-loop` | — | [`packages/client/ui-settings-agent-loop/src/index.ts`](../packages/client/ui-settings-agent-loop/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 9eb7f5ebd3..076f4d6f1b 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -264,7 +264,7 @@ export interface Config { ## `@deepseek-ai/dsh-api-session-controller` - `inject`: `agentDefaultModel` · `agents` · `attachments` · `fileUploads` · `fs` · `llm` · `remoteAccess` · `sessions` · `sessionProjections` · `sessionQuery` · `typert` · `typertGateway` · `workspaceRegistry` -- `source`: [`packages/api/session-controller/src/index.ts:111`](../packages/api/session-controller/src/index.ts) +- `source`: [`packages/api/session-controller/src/index.ts:83`](../packages/api/session-controller/src/index.ts) ```ts config-catalog /** Session Controller deployment policy. */ @@ -2742,7 +2742,7 @@ export interface Config { - `inject`: `shell` · `approval` · `sessions` · `agents` · `sessionProjections` - `refs`: [`ApprovalPolicy`](subsystems/approval.zh.md) · [`SandboxMode`](subsystems/sandbox.zh.md) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/interaction/permission-presets/src/index.ts:154`](../packages/interaction/permission-presets/src/index.ts) +- `source`: [`packages/interaction/permission-presets/src/index.ts:161`](../packages/interaction/permission-presets/src/index.ts) ```ts config-catalog /** The {@link PermissionPresetService} config: preset table and composition default. */ @@ -5181,7 +5181,7 @@ export interface Config { ## `@deepseek-ai/dsh-working-directory` - `inject`: `fs` · `sessionProjections` · `systemPrompt` -- `source`: [`packages/session/working-directory/src/index.ts:70`](../packages/session/working-directory/src/index.ts) +- `source`: [`packages/session/working-directory/src/index.ts:64`](../packages/session/working-directory/src/index.ts) ```ts config-catalog /** Deployment default for Sessions without an original project directory. */ @@ -5273,6 +5273,7 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-schedule` | — | [`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts) | | `@deepseek-ai/dsh-client-ui-secret-mask` | — | [`packages/client/ui-secret-mask/src/index.ts`](../packages/client/ui-secret-mask/src/index.ts) | | `@deepseek-ai/dsh-client-ui-session` | — | [`packages/client/ui-session/src/index.ts`](../packages/client/ui-session/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-session-panel` | — | [`packages/client/ui-session-panel/src/index.ts`](../packages/client/ui-session-panel/src/index.ts) | | `@deepseek-ai/dsh-client-ui-session-status` | `remoteAccess` · `sessions` · `sessionPersistence` · `typert` | [`packages/client/ui-session-status/src/index.ts`](../packages/client/ui-session-status/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings` | — | [`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts) | | `@deepseek-ai/dsh-client-ui-settings-agent-loop` | — | [`packages/client/ui-settings-agent-loop/src/index.ts`](../packages/client/ui-settings-agent-loop/src/index.ts) | diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 4a90de6eb9..0c63cd86ff 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -62,7 +62,7 @@ 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:77`](../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), [`timeline`](../packages/experimental/timeline) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | -| `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` | +| `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:62`](../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:455`](../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:461`](../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:468`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | @@ -104,7 +104,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `workflow/log` | `emit` | [`packages/workflow/workflow/src/index.ts:58`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/phase` | `emit` | [`packages/workflow/workflow/src/index.ts:51`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/start` | `emit` | [`packages/workflow/workflow/src/index.ts:43`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | - | -| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:32`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` | +| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:33`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` | | `workspace/session-activity` | `waterfall` | [`packages/workspace/workspace/src/index.ts:130`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`waterfall`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | | `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:157`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` | | `workspace/session-stop` | `parallel` | [`packages/workspace/workspace/src/index.ts:148`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index ed97c96e65..5b9dd3a373 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -64,7 +64,7 @@ | `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:77`](../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), [`timeline`](../packages/experimental/timeline) | | `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:46`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | - | -| `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` | +| `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:62`](../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:455`](../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:461`](../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:468`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | @@ -106,7 +106,7 @@ | `workflow/log` | `emit` | [`packages/workflow/workflow/src/index.ts:58`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/phase` | `emit` | [`packages/workflow/workflow/src/index.ts:51`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | | `workflow/start` | `emit` | [`packages/workflow/workflow/src/index.ts:43`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | - | -| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:32`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` | +| `working-directory/access` | `waterfall` | [`packages/session/working-directory/src/index.ts:33`](../packages/session/working-directory/src/index.ts) | [`working-directory`](../packages/session/working-directory) (`waterfall`) | `worktree` | | `workspace/session-activity` | `waterfall` | [`packages/workspace/workspace/src/index.ts:130`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`waterfall`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | | `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:157`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` | | `workspace/session-stop` | `parallel` | [`packages/workspace/workspace/src/index.ts:148`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | diff --git a/docs/module-graph.md b/docs/module-graph.md index 292ba9b6be..c1d4295469 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -199,6 +199,7 @@ flowchart TD pkg_client_ui_schedule["client-ui-schedule"] pkg_client_ui_secret_mask["client-ui-secret-mask"] pkg_client_ui_session["client-ui-session"] + pkg_client_ui_session_panel["client-ui-session-panel"] pkg_client_ui_session_status["client-ui-session-status"] pkg_client_ui_settings["client-ui-settings"] pkg_client_ui_settings_account["client-ui-settings-account"] @@ -1657,6 +1658,7 @@ flowchart TD | [`client-ui-schedule`](../packages/client/ui-schedule) | `client` | — | | [`client-ui-secret-mask`](../packages/client/ui-secret-mask) | `client` | — | | [`client-ui-session`](../packages/client/ui-session) | `client` | — | +| [`client-ui-session-panel`](../packages/client/ui-session-panel) | `client` | — | | [`client-ui-session-status`](../packages/client/ui-session-status) | `client` | — | | [`client-ui-settings`](../packages/client/ui-settings) | `client` | — | | [`client-ui-settings-account`](../packages/client/ui-settings-account) | `client` | — | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index dcb416582f..a179dbe473 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -201,6 +201,7 @@ flowchart TD pkg_client_ui_schedule["client-ui-schedule"] pkg_client_ui_secret_mask["client-ui-secret-mask"] pkg_client_ui_session["client-ui-session"] + pkg_client_ui_session_panel["client-ui-session-panel"] pkg_client_ui_session_status["client-ui-session-status"] pkg_client_ui_settings["client-ui-settings"] pkg_client_ui_settings_account["client-ui-settings-account"] @@ -1659,6 +1660,7 @@ flowchart TD | [`client-ui-schedule`](../packages/client/ui-schedule) | `client` | — | | [`client-ui-secret-mask`](../packages/client/ui-secret-mask) | `client` | — | | [`client-ui-session`](../packages/client/ui-session) | `client` | — | +| [`client-ui-session-panel`](../packages/client/ui-session-panel) | `client` | — | | [`client-ui-session-status`](../packages/client/ui-session-status) | `client` | — | | [`client-ui-settings`](../packages/client/ui-settings) | `client` | — | | [`client-ui-settings-account`](../packages/client/ui-settings-account) | `client` | — | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 567159cc50..dd5b4975d3 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -147,8 +147,8 @@ en: 19917bc5438e60af zh: 19917bc5438e60af /session-persistence-event-catalog/events/permission/permission-preset-log-only: - en: 5a38e50ed89e1a80 - zh: 5c4160ebfb3d661b + en: bf9ce12daf742e7f + zh: 78d8424f1493ca2c /session-persistence-event-catalog/events/plan: en: 4294f78d26ed985b zh: 4294f78d26ed985b @@ -300,8 +300,8 @@ en: e8dd0cebbb930eb7 zh: e8dd0cebbb930eb7 /session-persistence-event-catalog/events/working-directory/working-directory-change-log-only: - en: 27f0761cbdd6fe2f - zh: 33528f333498132d + en: bf12683fa0fe3dfa + zh: 79a678a53cee33b9 /session-persistence-event-catalog/events/workspace: en: 63ee1a85e4b59ae3 zh: 63ee1a85e4b59ae3 @@ -1497,8 +1497,8 @@ en: bef51e0442ebb903 zh: 240ebeb160533d8c /session-persistence-event-catalog/resolved-persistence-types/cwd: - en: 2809c921c6996791 - zh: 80b15177561766d7 + en: 166c1be5f6237f1b + zh: 5002d35a2ec5fb1e /session-persistence-event-catalog/resolved-persistence-types/decision-durationms-exitcode-handlerid: en: a99ac57bbec0370f zh: 9073329e324a66e0 @@ -1935,8 +1935,8 @@ en: c6e1e91281b3f9c2 zh: 33225e83b0bd8cff /session-persistence-event-catalog/resolved-persistence-types/kind-working-directory: - en: b28ca6b37f5a338d - zh: 4c4f2f05721b8b62 + en: a36b909ecbd38156 + zh: b02edb123e72fbb1 /session-persistence-event-catalog/resolved-persistence-types/max-tokens-messages-model-thinking: en: efe43158304eaf7b zh: 7a4b0d7f1a9f1c65 @@ -1959,8 +1959,8 @@ en: 88fd92dff7aa505f zh: b400712b3ef749aa /session-persistence-event-catalog/resolved-persistence-types/preset: - en: 9fbb222685c7310c - zh: 26e3032eae149f0a + en: 42a6a0b07a66ad45 + zh: eaecef11c5b3ac02 /session-persistence-event-catalog/resolved-persistence-types/reason-turn: en: b8d80b4b1e6441ad zh: d5c52e1bfe560297 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 9f4a88866f..05a768ee87 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -718,7 +718,7 @@ Source: [`packages/core/agent/src/types.ts:121`](../packages/core/agent/src/type 'permission/preset': { preset: string } ``` -Source: [`packages/interaction/permission-presets/src/index.ts:54`](../packages/interaction/permission-presets/src/index.ts) +Source: [`packages/interaction/permission-presets/src/index.ts:61`](../packages/interaction/permission-presets/src/index.ts) ### `plan/*` @@ -1329,7 +1329,7 @@ Source: [`packages/web/web-search-deepseek/src/provider.ts:90`](../packages/web/ } ``` -Source: [`packages/session/working-directory/src/index.ts:55`](../packages/session/working-directory/src/index.ts) +Source: [`packages/session/working-directory/src/index.ts:56`](../packages/session/working-directory/src/index.ts) ### `workspace/*` @@ -6216,7 +6216,7 @@ Sources: [`packages/compaction/compaction/src/types.ts:24`](../packages/compacti SHA-256: `da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582` -Sources: [`packages/session/working-directory/src/index.ts:55`](../packages/session/working-directory/src/index.ts) +Sources: [`packages/session/working-directory/src/index.ts:56`](../packages/session/working-directory/src/index.ts) | Property | Presence | Type | |---|---|---| @@ -7970,7 +7970,7 @@ Sources: [`packages/experimental/webhook/src/types.ts:75`](../packages/experimen SHA-256: `2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5` -Sources: [`packages/session/working-directory/src/index.ts:48`](../packages/session/working-directory/src/index.ts) +Sources: [`packages/session/working-directory/src/index.ts:49`](../packages/session/working-directory/src/index.ts) | Property | Presence | Type | |---|---|---| @@ -8081,7 +8081,7 @@ Sources: [`packages/interaction/user-approval/src/index.ts:41`](../packages/inte SHA-256: `8a9c990773f798eac10ca8878e6bcc531ee080bc589cac956730e462cc6a09ad` -Sources: [`packages/interaction/permission-presets/src/index.ts:54`](../packages/interaction/permission-presets/src/index.ts) +Sources: [`packages/interaction/permission-presets/src/index.ts:61`](../packages/interaction/permission-presets/src/index.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 4c7b08a2ae..56a7386e98 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -720,7 +720,7 @@ export type SessionEvent = { 'permission/preset': { preset: string } ``` -来源:[`packages/interaction/permission-presets/src/index.ts:54`](../packages/interaction/permission-presets/src/index.ts) +来源:[`packages/interaction/permission-presets/src/index.ts:61`](../packages/interaction/permission-presets/src/index.ts) ### `plan/*` @@ -1331,7 +1331,7 @@ export type SessionEvent = { } ``` -来源:[`packages/session/working-directory/src/index.ts:55`](../packages/session/working-directory/src/index.ts) +来源:[`packages/session/working-directory/src/index.ts:56`](../packages/session/working-directory/src/index.ts) ### `workspace/*` @@ -6218,7 +6218,7 @@ SHA-256: `3e4e7683b0192c9f0e6a75c59076108f017892cdb302a98032c2632fd79c356f` SHA-256: `da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582` -来源:[`packages/session/working-directory/src/index.ts:55`](../packages/session/working-directory/src/index.ts) +来源:[`packages/session/working-directory/src/index.ts:56`](../packages/session/working-directory/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7972,7 +7972,7 @@ SHA-256: `9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94` SHA-256: `2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5` -来源:[`packages/session/working-directory/src/index.ts:48`](../packages/session/working-directory/src/index.ts) +来源:[`packages/session/working-directory/src/index.ts:49`](../packages/session/working-directory/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8083,7 +8083,7 @@ SHA-256: `11f70b595aa76897fc4e25a352bfa718c659f44b799e5aa14e84e5a38fe72912` SHA-256: `8a9c990773f798eac10ca8878e6bcc531ee080bc589cac956730e462cc6a09ad` -来源:[`packages/interaction/permission-presets/src/index.ts:54`](../packages/interaction/permission-presets/src/index.ts) +来源:[`packages/interaction/permission-presets/src/index.ts:61`](../packages/interaction/permission-presets/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index a9fc203412..5ea9b9cb55 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -161,7 +161,7 @@ {"digest":"2142e391b9ccb60d487afcf373ce74db98d952f69e8289eddb352a7e16e996c5","names":[],"sources":[]}, {"digest":"2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0","names":["packages/team/agent-team/src/types.ts#TeamMessageSource"],"sources":["packages/team/agent-team/src/types.ts:121"]}, {"digest":"21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d","names":[],"sources":[]}, - {"digest":"2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5","names":[],"sources":["packages/session/working-directory/src/index.ts:48"]}, + {"digest":"2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5","names":[],"sources":["packages/session/working-directory/src/index.ts:49"]}, {"digest":"224aa11d4d5f88c450822d01b99e6ca5e3a9c7f26a5ede10bae33384a09ef4dc","names":[],"sources":[]}, {"digest":"234142ee4f996f38cc9fa3b8b3e3de29b03c9aefe5ebf6c224eddd564505aa85","names":[],"sources":[]}, {"digest":"237c004c73b6b288246816e0d7fde16e09c63a47aa3b1227383d7afe58666163","names":[],"sources":[]}, @@ -416,7 +416,7 @@ {"digest":"88a610b831be6d92612a464be5c7d0b88ec24d97bd299837bf74bf7672183c9a","names":[],"sources":["packages/llm/llm/src/types.ts:588"]}, {"digest":"8a046b52331959aa3394680d6acbe09b8a5447c6b61375f263445bfcef19b7f1","names":[],"sources":[]}, {"digest":"8a6e1ec9e8db346b0e02f027db73c07a94f067a26d40c1aef1abd09c47ce7ba0","names":[],"sources":[]}, - {"digest":"8a9c990773f798eac10ca8878e6bcc531ee080bc589cac956730e462cc6a09ad","names":[],"sources":["packages/interaction/permission-presets/src/index.ts:54"]}, + {"digest":"8a9c990773f798eac10ca8878e6bcc531ee080bc589cac956730e462cc6a09ad","names":[],"sources":["packages/interaction/permission-presets/src/index.ts:61"]}, {"digest":"8ad45ad053b4d89f8865c17cc9ff3b8748e86045f3f0fb816269a34af2619141","names":[],"sources":["packages/experimental/hook-protocol/src/types.ts:31"]}, {"digest":"8af841fc9b265ade3441caf9fe40dd24db24226befba48150e6d0eeccc1389c3","names":[],"sources":[]}, {"digest":"8bb8c3751a6ce64b61aba1ec7ae798c00a5803c4d868a0430873216c6569ed52","names":[],"sources":["packages/session/session-log-deepseek/src/types.ts:96"]}, @@ -608,7 +608,7 @@ {"digest":"d9196086e41e4dd5c2ce87f5c25529c8112a1731d258cf0728747d41a9ee3241","names":[],"sources":[]}, {"digest":"d9c462b9f62fdd3efc76a44b9524dc8781f6b91cd9c7e584b17d971defafebab","names":["packages/llm/llm/src/message.ts#ToolMessageSource"],"sources":["packages/llm/llm/src/message.ts:28"]}, {"digest":"d9edf1862e4471d6ad8a106a3f4160e0643874368707d50ecd8e27e5ee7a2567","names":[],"sources":[]}, - {"digest":"da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582","names":[],"sources":["packages/session/working-directory/src/index.ts:55"]}, + {"digest":"da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582","names":[],"sources":["packages/session/working-directory/src/index.ts:56"]}, {"digest":"dacf3d5f3e4ff619c1320e64a48dec5e7ecd7870bece65fbd449a0e63adfa521","names":[],"sources":[]}, {"digest":"db06ef35b27a38425046b2228fa6bce9582abe140d781d363137eb2f4d233a1c","names":[],"sources":[]}, {"digest":"db6c5246911d47a7969f6b4cb47c7d0dbbde75c402710b22ace3672fa97bebe0","names":[],"sources":[]}, diff --git a/docs/subsystems/extensions.md b/docs/subsystems/extensions.md index 3219d86c65..4d8e592487 100644 --- a/docs/subsystems/extensions.md +++ b/docs/subsystems/extensions.md @@ -16,7 +16,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.cordisInspect` — `CordisInspectRegistryService` -Registry and cross-page router behind the two model-facing inspect tools. +Registry and cross-page router behind the model-facing inspection tool. ```ts cordis-catalog /** diff --git a/docs/subsystems/extensions.zh.md b/docs/subsystems/extensions.zh.md index d4dfce9c2d..715653f19a 100644 --- a/docs/subsystems/extensions.zh.md +++ b/docs/subsystems/extensions.zh.md @@ -16,7 +16,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.cordisInspect` — `CordisInspectRegistryService` -Registry and cross-page router behind the two model-facing inspect tools. +Registry and cross-page router behind the model-facing inspection tool. ```ts cordis-catalog /** diff --git a/docs/subsystems/jobs.md b/docs/subsystems/jobs.md index d00c691db2..24b6749e73 100644 --- a/docs/subsystems/jobs.md +++ b/docs/subsystems/jobs.md @@ -404,6 +404,9 @@ Host service backing the generated `ctx.remote.job` namespace. * Stream the jobs one session can see — its own plus every unowned job — * as whole-set frames: one on open, then one after each coalesced burst of * lifecycle commits. The stream has no natural end; the carrier closes it. + * + * The Gateway names this call's Session resource from `request.sessionId` + * through the session controller's resolver; no explicit reader is needed. * @param request - the session whose visible set to mirror. * @param signal - cancellation owned by the Remote stream carrier. * @returns the roster frames. diff --git a/docs/subsystems/jobs.zh.md b/docs/subsystems/jobs.zh.md index c592c7d996..1b9b1a3169 100644 --- a/docs/subsystems/jobs.zh.md +++ b/docs/subsystems/jobs.zh.md @@ -404,6 +404,9 @@ Host service backing the generated `ctx.remote.job` namespace. * Stream the jobs one session can see — its own plus every unowned job — * as whole-set frames: one on open, then one after each coalesced burst of * lifecycle commits. The stream has no natural end; the carrier closes it. + * + * The Gateway names this call's Session resource from `request.sessionId` + * through the session controller's resolver; no explicit reader is needed. * @param request - the session whose visible set to mirror. * @param signal - cancellation owned by the Remote stream carrier. * @returns the roster frames. diff --git a/docs/subsystems/permission-presets.i18n.yaml b/docs/subsystems/permission-presets.i18n.yaml index d0461f52c8..61733c9732 100644 --- a/docs/subsystems/permission-presets.i18n.yaml +++ b/docs/subsystems/permission-presets.i18n.yaml @@ -15,5 +15,5 @@ en: 43a7b661b747091f zh: ee6b4f1ddb8cf6f2 /permission-presets/switching-and-the-permission-preset-event: - en: 71924a3f5f717704 - zh: 0a7ecbbf8d801a32 + en: 2f287db1b6649a86 + zh: 99dac792fc340097 diff --git a/docs/subsystems/permission-presets.md b/docs/subsystems/permission-presets.md index e5fa61c405..0d70aaa165 100644 --- a/docs/subsystems/permission-presets.md +++ b/docs/subsystems/permission-presets.md @@ -72,6 +72,8 @@ interface PresetOption { `set(session, name)` resolves the preset (unknown names throw), runs Auto admission when applicable, appends a log-only `permission/preset` event unless `name` is already the effective preset, then writes each knob through its own setter — `setSandboxMode` from [dsh-sandbox-policy](../../packages/sandbox/sandbox-policy) and `setApprovalPolicy` from [dsh-user-approval](../../packages/interaction/user-approval) — only when that knob's effective value changes. The selection event precedes the knob events in the same turn, and re-selecting the effective preset appends nothing. +The `permissionPresets/set` Remote (`setPreset`) is the write's Remote face: it switches one live Session through `set` and declares that Session as the `session` resource the Gateway decides, so access control runs before any preset is resolved. + `permission/preset` is durable, log-only user intent: it stays out of the model transcript (the knob events own the model-visible consequences through their consumers), and it exists so `current()` can preserve which preset the user chose when two presets share a bundle. The `permissions` projection folds that selection with both knob events and retains the `session/end-seed` boundary used to distinguish a restored empty seed from a fresh session; replay needs no catch-up state or raw-log rescan. A restored `auto` selection requires the live Auto registration before Agent publication. The complete event declaration is in the [persistence log event catalog](../persistence-catalog.md); the method signatures are in the generated [service catalog](#ctxpermissionpresets--permissionpresetservice). @@ -95,6 +97,25 @@ Owns the deployment's configured permission presets, the fixed Auto integration */ @Remote('catalog') catalog(): PermissionCatalog +/** + * Switch one live Session to another preset, opened as a Remote call so a + * caller's Session access is decided before any preset is resolved or any + * knob is written. The call's `session` resource is the Session named by + * `request.sessionId`, per {@link PermissionPresetSetRequest}; the session + * controller's resolver names it. + * + * The switch appends `permission/preset` and the changed knob events to the + * Session log, so persisted-only Sessions are refused: they have no live log + * to append to. + * @param request - live target Session and the preset name to switch to. + * @returns the Session's current selection after the switch, read the way + * the client reads it: the recorded preset while its bundle still matches, + * otherwise the first preset whose bundle matches, otherwise `custom`. + * @throws {RemoteError} `gateway/bad-request` for an unknown preset name or a + * Session this process does not hold live; neither call writes. + */ +@Remote({ name: 'set' }) setPreset(request: PermissionPresetSetRequest): PermissionSelection + /** * Publish the fixed current-session Auto preset for the calling * integration's effect lifetime. diff --git a/docs/subsystems/permission-presets.zh.md b/docs/subsystems/permission-presets.zh.md index 9353cc8db3..6126f3e697 100644 --- a/docs/subsystems/permission-presets.zh.md +++ b/docs/subsystems/permission-presets.zh.md @@ -72,6 +72,8 @@ interface PresetOption { `set(session, name)` 解析预设(未知名称抛出异常),在适用时运行 Auto 准入,在 `name` 尚不是生效预设时追加一条仅记日志的 `permission/preset` 事件,然后通过各旋钮自己的 setter([dsh-sandbox-policy](../../packages/sandbox/sandbox-policy) 的 `setSandboxMode` 与 [dsh-user-approval](../../packages/interaction/user-approval) 的 `setApprovalPolicy`)写入,且仅当该 knob 的生效值发生变化时才写。同一轮次内,选择事件先于旋钮事件出现;重新选择当前生效的预设则什么都不追加。 +`permissionPresets/set` Remote(`setPreset`)是这条写入路径的 Remote 面:它通过 `set` 切换一个 live Session,并把该 Session 声明为 Gateway 要判定的 `session` 资源,因此访问控制在解析任何预设之前就已执行。 + `permission/preset` 是持久、仅记日志的用户意图:它不进入模型 transcript(文本记录),模型可见的后果由 knob 事件经各自消费方承担;它存在是为了在两个预设共享同一个旋钮组合时,让 `current()` 仍能保住用户选择的究竟是哪一个预设。`permissions` 投影把该选择与两个 knob 事件一同折叠,并保留用于区分空恢复 seed 与新会话的 `session/end-seed` 边界;回放不需要任何追赶状态或原始日志重扫。恢复的 `auto` 选择在 agent 发布前必须存在 live Auto 注册。完整事件声明见[持久化日志事件目录](../persistence-catalog.zh.md);方法签名见生成的[服务目录](#ctxpermissionpresets--permissionpresetservice)。 @@ -95,6 +97,25 @@ Owns the deployment's configured permission presets, the fixed Auto integration */ @Remote('catalog') catalog(): PermissionCatalog +/** + * Switch one live Session to another preset, opened as a Remote call so a + * caller's Session access is decided before any preset is resolved or any + * knob is written. The call's `session` resource is the Session named by + * `request.sessionId`, per {@link PermissionPresetSetRequest}; the session + * controller's resolver names it. + * + * The switch appends `permission/preset` and the changed knob events to the + * Session log, so persisted-only Sessions are refused: they have no live log + * to append to. + * @param request - live target Session and the preset name to switch to. + * @returns the Session's current selection after the switch, read the way + * the client reads it: the recorded preset while its bundle still matches, + * otherwise the first preset whose bundle matches, otherwise `custom`. + * @throws {RemoteError} `gateway/bad-request` for an unknown preset name or a + * Session this process does not hold live; neither call writes. + */ +@Remote({ name: 'set' }) setPreset(request: PermissionPresetSetRequest): PermissionSelection + /** * Publish the fixed current-session Auto preset for the calling * integration's effect lifetime. diff --git a/docs/subsystems/ptc-runtime.i18n.yaml b/docs/subsystems/ptc-runtime.i18n.yaml index ab2fae6ee9..4f9e3495c7 100644 --- a/docs/subsystems/ptc-runtime.i18n.yaml +++ b/docs/subsystems/ptc-runtime.i18n.yaml @@ -9,8 +9,8 @@ en: 94ba725bef6684b7 zh: f113745a4a07952a /ptc-runtime/bindings-host-functions-as-program-globals: - en: 182147ddf388c600 - zh: c0a7d77602c78bcd + en: a387577007373804 + zh: a330173368db598d /ptc-runtime/captured-output-and-the-failure-taxonomy: en: ef553620e77bd638 zh: 40ff2f5ba3de5ed5 diff --git a/docs/subsystems/ptc-runtime.md b/docs/subsystems/ptc-runtime.md index 60c694b13d..94ba67192c 100644 --- a/docs/subsystems/ptc-runtime.md +++ b/docs/subsystems/ptc-runtime.md @@ -115,7 +115,7 @@ type PtcProgramFormat = 'function-body' | 'repl' | 'script' | 'scoped-repl' ## Bindings: host functions as program globals -Each `PtcBindingNamespace` becomes a global object of async callables; PTC passes `tools`. Arguments and resolutions must be lossless JSON. Providers enforce their own transport caps; the seam sets no uniform binding-byte limit. An optional error-class descriptor creates program-visible typed rejections without naming a consumer inside the runtime. Binding names are own properties, so `__proto__` cannot traverse a prototype: +Each `PtcBindingNamespace` becomes a global object of async callables; PTC passes `tools`. Arguments and resolutions must be lossless JSON, with host-issued `PtcImage` and `PtcInspectableValue` descriptors adapted by the provider. Providers enforce their own transport caps; the seam sets no uniform binding-byte limit. An optional error-class descriptor creates program-visible typed rejections without naming a consumer inside the runtime. Binding names are own properties, so `__proto__` cannot traverse a prototype: ```ts type-equiv /** @@ -168,15 +168,38 @@ type PtcJsonValue = null | boolean | number | string | PtcJsonValue[] | { [key: /** * One host-side function exposed to the program as an async callable. The * runtime bridges calls to it (possibly across a serialization boundary), so - * `args` must be lossless JSON; resolutions also support host-issued PtcImage values. A runtime rejects a - * lossy or non-cloneable value with a descriptive error rather than corrupting - * the run. No seam-level byte cap applies to a binding resolution. A rejection - * of this function surfaces inside the program as a rejection of the - * corresponding call. + * `args` must be lossless JSON; resolutions also support host-issued PtcImage and + * PtcInspectableValue values. An inspectable resolution delivers its JSON object + * or array to the program and uses its text only when that unchanged value is + * inspected directly. A runtime rejects a lossy or non-cloneable value with a + * descriptive error rather than corrupting the run. No seam-level byte cap + * applies to a binding resolution. A rejection of this function surfaces inside + * the program as a rejection of the corresponding call. */ type PtcBindingFunction = (args: unknown) => Promise ``` +`PtcInspectableValue`, exported from `@deepseek-ai/dsh-ptc-runtime`, associates a lossless JSON object or array with host-authored text through `new PtcInspectableValue(value, text)`. The provider delivers the data itself to the program, without exposing the descriptor or adding program-visible properties. Direct `inspect` of the original result uses its text only while the data matches its initial snapshot; empty text emits nothing. Copies, field selections, modified results, and nested values use ordinary formatting. The Node process owns this association, which is neither serialized into Session logs nor transferred by copying a program value. See [`src/inspectable-value.ts`](../../packages/ptc-runtime/ptc-runtime/src/inspectable-value.ts). + +The data may contain host-issued `PtcImage` descriptors. The provider preserves their program `Image` identities in the inspection snapshot. Direct inspection of the unchanged container displays its supplied text; inspecting an Image field displays that image. + +```ts public-api +/** A binding result whose unchanged object or array displays the supplied text when inspected directly. */ +declare class PtcInspectableValue { + readonly [key: string]: PtcJsonValue; + /** The JSON object or array delivered unchanged to the program. */ + readonly value: PtcJsonValue[] | { [key: string]: PtcJsonValue }; + /** Text shown by a direct inspection of the unchanged value; empty text emits nothing. */ + readonly text: string; + /** + * Associate an object or array with its host-authored inspection text. + * @param value - Lossless JSON data retained for programmatic access. + * @param text - Text to display instead of generic object formatting. + */ + constructor(value: PtcJsonValue[] | { [key: string]: PtcJsonValue }, text: string); +} +``` + ## Captured output and the failure taxonomy `output` contains text and image entries in emission order: `{ type: 'text', text }` or `{ type: 'image', attachment }`. Text entries retain emitted newline characters; concatenate adjacent text without separators. Each source channel preserves emission order; interleaving across independent channels is backend-dependent. Host bindings return `PtcImage` descriptors containing the attachment reference and a readable execution-world `path`; the program receives an `Image` with that path and the stored pixel dimensions. The Node provider caps serialized text, image descriptors, and completion or diagnostic payloads together; overflow is an explicit failure. diff --git a/docs/subsystems/ptc-runtime.zh.md b/docs/subsystems/ptc-runtime.zh.md index cc077a243d..e8a13600f2 100644 --- a/docs/subsystems/ptc-runtime.zh.md +++ b/docs/subsystems/ptc-runtime.zh.md @@ -115,7 +115,7 @@ type PtcProgramFormat = 'function-body' | 'repl' | 'script' | 'scoped-repl' ## 绑定:宿主函数作为程序全局变量 -每个 `PtcBindingNamespace` 成为一个异步可调用函数的全局对象;PTC 传入 `tools`。参数与返回值必须是无损 JSON。提供方强制各自的传输上限;seam 不设统一的绑定字节上限。可选错误类描述符创建程序可见的类型化拒绝,无需在运行时内点名消费方。绑定名是自有属性,因此 `__proto__` 不能遍历原型: +每个 `PtcBindingNamespace` 成为一个异步可调用函数的全局对象;PTC 传入 `tools`。参数与返回值必须是无损 JSON,宿主签发的 `PtcImage` 和 `PtcInspectableValue` 描述符由提供方适配。提供方强制各自的传输上限;seam 不设统一的绑定字节上限。可选错误类描述符创建程序可见的类型化拒绝,无需在运行时内点名消费方。绑定名是自有属性,因此 `__proto__` 不能遍历原型: ```ts type-equiv /** @@ -168,15 +168,38 @@ type PtcJsonValue = null | boolean | number | string | PtcJsonValue[] | { [key: /** * One host-side function exposed to the program as an async callable. The * runtime bridges calls to it (possibly across a serialization boundary), so - * `args` must be lossless JSON; resolutions also support host-issued PtcImage values. A runtime rejects a - * lossy or non-cloneable value with a descriptive error rather than corrupting - * the run. No seam-level byte cap applies to a binding resolution. A rejection - * of this function surfaces inside the program as a rejection of the - * corresponding call. + * `args` must be lossless JSON; resolutions also support host-issued PtcImage and + * PtcInspectableValue values. An inspectable resolution delivers its JSON object + * or array to the program and uses its text only when that unchanged value is + * inspected directly. A runtime rejects a lossy or non-cloneable value with a + * descriptive error rather than corrupting the run. No seam-level byte cap + * applies to a binding resolution. A rejection of this function surfaces inside + * the program as a rejection of the corresponding call. */ type PtcBindingFunction = (args: unknown) => Promise ``` +`@deepseek-ai/dsh-ptc-runtime` 导出的 `PtcInspectableValue` 通过 `new PtcInspectableValue(value, text)`,为无损 JSON 对象或数组关联宿主提供的文本。提供方向程序交付数据本身,不暴露描述符,也不添加程序可见属性。只有直接 `inspect` 原结果,且其数据仍与初始快照一致时,才使用附带文本;空文本不产生输出。拷贝、字段选择、修改后的结果和嵌套值使用普通格式。该关联由 Node 进程拥有,不序列化到 Session 日志,复制程序值也不会传递该关联。参见 [`src/inspectable-value.ts`](../../packages/ptc-runtime/ptc-runtime/src/inspectable-value.ts)。 + +数据中可以包含宿主提供的 `PtcImage` 描述符。提供方在展示快照中保留对应程序 `Image` 的身份。直接展示未修改的容器时输出附带文本;展示 Image 字段时输出该图片。 + +```ts public-api +/** A binding result whose unchanged object or array displays the supplied text when inspected directly. */ +declare class PtcInspectableValue { + readonly [key: string]: PtcJsonValue; + /** The JSON object or array delivered unchanged to the program. */ + readonly value: PtcJsonValue[] | { [key: string]: PtcJsonValue }; + /** Text shown by a direct inspection of the unchanged value; empty text emits nothing. */ + readonly text: string; + /** + * Associate an object or array with its host-authored inspection text. + * @param value - Lossless JSON data retained for programmatic access. + * @param text - Text to display instead of generic object formatting. + */ + constructor(value: PtcJsonValue[] | { [key: string]: PtcJsonValue }, text: string); +} +``` + ## 捕获的输出与失败分类体系 `output` 按发出顺序保存文本和图片条目:文本使用 `{ type: 'text', text }`,图片使用 `{ type: 'image', attachment }`。文本条目保留实际输出的换行,相邻文本直接拼接,不额外插入分隔符。每个来源通道都保留发出顺序;独立通道之间的交错顺序由后端决定。宿主绑定返回 `PtcImage` 描述符,包含附件引用和可在执行环境读取的 `path`;程序收到带有该路径和存储像素尺寸的 `Image`。Node 提供方对序列化文本、图片描述符、完成值或诊断一起计量;超限会显式失败。 diff --git a/docs/subsystems/session-reference.md b/docs/subsystems/session-reference.md index a2d32d22d4..84e81ddf52 100644 --- a/docs/subsystems/session-reference.md +++ b/docs/subsystems/session-reference.md @@ -184,6 +184,13 @@ Exact-read consumer that prepares immutable cross-session message context. * * Discovery runs at keystroke rate, so titles and subagent labels only ever * come from projection reads; sessions without either fall back to their id. + * + * The list names every Session the session index holds, whatever identity the + * caller acts for; it is not narrowed to Sessions that caller else can read. + * A share viewer therefore learns the id, title, and working-directory path of + * each Session on the owner Host, and {@link prepare} reads the snapshot of a + * cited Session without asking who cited it. That exposure is a recorded + * LiveShare limitation, not a grant: narrowing the list is deferred. * @param agent - target agent; self is excluded and its cwd drives ranking. * @param query - optional search text: label and display title match * fuzzily, session id and working directory as substrings. Matches keep the diff --git a/docs/subsystems/session-reference.zh.md b/docs/subsystems/session-reference.zh.md index 0b2e89a7c4..3f544d040a 100644 --- a/docs/subsystems/session-reference.zh.md +++ b/docs/subsystems/session-reference.zh.md @@ -184,6 +184,13 @@ Exact-read consumer that prepares immutable cross-session message context. * * Discovery runs at keystroke rate, so titles and subagent labels only ever * come from projection reads; sessions without either fall back to their id. + * + * The list names every Session the session index holds, whatever identity the + * caller acts for; it is not narrowed to Sessions that caller else can read. + * A share viewer therefore learns the id, title, and working-directory path of + * each Session on the owner Host, and {@link prepare} reads the snapshot of a + * cited Session without asking who cited it. That exposure is a recorded + * LiveShare limitation, not a grant: narrowing the list is deferred. * @param agent - target agent; self is excluded and its cwd drives ranking. * @param query - optional search text: label and display title match * fuzzily, session id and working directory as substrings. Matches keep the diff --git a/docs/subsystems/slots.i18n.yaml b/docs/subsystems/slots.i18n.yaml index 5f34f8ce71..632ae5542c 100644 --- a/docs/subsystems/slots.i18n.yaml +++ b/docs/subsystems/slots.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/slots.md /web-client-slots: - en: 15c49af3ed8b57ff - zh: e7f9189de6f4334c + en: c3e0c40beeda0651 + zh: a94d81520205694c /web-client-slots/declaration-and-lifecycle: en: f2d2c0d3b8f14ec7 zh: 441ed13ff3f81d2a diff --git a/docs/subsystems/slots.md b/docs/subsystems/slots.md index dea9b7cbec..e24cd26f22 100644 --- a/docs/subsystems/slots.md +++ b/docs/subsystems/slots.md @@ -16,6 +16,8 @@ The root-scoped lists `sidebar.panellist.actions`, `conversation.session.header. [ui-settings](../../packages/client/ui-settings/README.md#filling-the-settings-slots) documents the settings page and navigation-icon extension points. +[ui-session-panel](../../packages/client/ui-session-panel/README.md#contribute-a-section) documents the Session panel's section, title-control, row, and toggle-indicator extension positions. + ## Declaration and lifecycle `SlotMap` is the compile-time registry. A package declaration-merges the key, cardinality, scope, owner props, keyed props, and optional slot-level inject face. The runtime declaration is the matching `children` entry on the component that owns the render location. @@ -148,6 +150,8 @@ root [AppFrame] │ ├─ conversation.session.header.lineage │ ├─ conversation.session.header.actions │ ├─ conversation.session.header.utilities + │ │ └─ id=session-panel [SessionPanelToggle] + │ │ └─ conversation.session.panel.indicator [list, inline] │ ├─ conversation.session.header.views.actions │ └─ conversation.session.header.corner └─ calls Factory: conversation.content @@ -158,6 +162,11 @@ Factory: conversation.content [ConversationContent] │ ├─ id=chat [ChatView] │ │ ├─ conversation.chat.text-interaction [list] │ │ ├─ conversation.chat.markdown.fence [hoc, keyed by fence language] +│ │ ├─ conversation.chat.aside [SessionPanel] +│ │ │ ├─ conversation.session.panel.section [list] +│ │ │ │ └─ id=environment [EnvironmentSection] +│ │ │ │ └─ conversation.session.panel.environment.row [list] +│ │ │ └─ conversation.session.panel.section.actions [keyed] │ │ └─ conversation.chat.flow [ChatFlow] │ │ └─ conversation.chat.node [ChatNodeSeat dispatch] │ │ ├─ key=user [UserMessageNodeView] diff --git a/docs/subsystems/slots.zh.md b/docs/subsystems/slots.zh.md index ecb1455470..2cb79e4060 100644 --- a/docs/subsystems/slots.zh.md +++ b/docs/subsystems/slots.zh.md @@ -16,6 +16,8 @@ root 作用域的 list `sidebar.panellist.actions`、`conversation.session.heade [ui-settings](../../packages/client/ui-settings/README.zh.md#filling-the-settings-slots) 记录设置页面与导航图标扩展点。 +[ui-session-panel](../../packages/client/ui-session-panel/README.zh.md#contribute-a-section) 记录会话面板的分栏、标题控件、行与开关角标扩展位置。 + ## 声明与生命周期 `SlotMap` 是编译期注册表。包通过声明合并写入 key、cardinality(基数)、scope、owner props、keyed props 与可选的 slot 级 inject face。运行时声明则是拥有该渲染位置的组件在 `children` 中给出的对应条目。 @@ -150,6 +152,8 @@ root [AppFrame] │ ├─ conversation.session.header.lineage │ ├─ conversation.session.header.actions │ ├─ conversation.session.header.utilities + │ │ └─ id=session-panel [SessionPanelToggle] + │ │ └─ conversation.session.panel.indicator [list, inline] │ ├─ conversation.session.header.views.actions │ └─ conversation.session.header.corner └─ calls Factory: conversation.content @@ -160,6 +164,11 @@ Factory: conversation.content [ConversationContent] │ ├─ id=chat [ChatView] │ │ ├─ conversation.chat.text-interaction [list] │ │ ├─ conversation.chat.markdown.fence [hoc, keyed by fence language] +│ │ ├─ conversation.chat.aside [SessionPanel] +│ │ │ ├─ conversation.session.panel.section [list] +│ │ │ │ └─ id=environment [EnvironmentSection] +│ │ │ │ └─ conversation.session.panel.environment.row [list] +│ │ │ └─ conversation.session.panel.section.actions [keyed] │ │ └─ conversation.chat.flow [ChatFlow] │ │ └─ conversation.chat.node [ChatNodeSeat dispatch] │ │ ├─ key=user [UserMessageNodeView] diff --git a/docs/subsystems/user-questions.md b/docs/subsystems/user-questions.md index daf0db242a..65738ca720 100644 --- a/docs/subsystems/user-questions.md +++ b/docs/subsystems/user-questions.md @@ -240,11 +240,29 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp * Answer a continued question. The reply is steered into the agent as a * user message whose source names the call; that message is also the * record that closes the question in the projection. + * + * The only call this method can answer is one the projection lists as + * `continued` on this Session, and it steers a user message into the running + * turn, so it speaks for the person the Session runs for. A LiveShare reader + * reaches it through the Session read role, which is safe only while an + * approval question cannot become `continued`: the projection tracks only + * calls made under the timed `ask_user_question` schema, and a call becomes + * `continued` only by returning the pending result a timed wait produces (or, + * for PTC, a pending dispatch) or by resume repair recording + * `TOOL_OUTCOME_UNKNOWN` for a call the process never finished. Plan review + * (`plan-review`) and the CUA approvals (`approval`) reach `ctx.userQuestions.ask` + * without a `wait` and without a `timeout`, so their result is a settled + * answer, an abort, or a failure, never a pending result, and they stay out + * of the projection. A future approval surface must keep asking without + * `wait`/`timeout`, or it must gain its own owner-only gate; giving it a timed + * form makes an approval answerable by a share viewer. * @param agent - Live root agent for the owning Session. * @param callId - Continued question identity. * @param answer - Complete structured answer batch, one item per question of the call. - * @returns Whether the question is still continued; an accepted reply stays - * queued until the agent admits its user message. + * @returns Whether the question is still continued (`false` when this Session + * lists no such continued call, or its composition carries no Session + * projections); an accepted reply stays queued until the agent admits its + * user message. * @throws {UserQuestionError} `BAD_ANSWER` when the batch does not name each * question of the call exactly once, or `REPLY_QUEUED` when a reply is * already waiting for admission. diff --git a/docs/subsystems/user-questions.zh.md b/docs/subsystems/user-questions.zh.md index aeb1818584..7171db0a68 100644 --- a/docs/subsystems/user-questions.zh.md +++ b/docs/subsystems/user-questions.zh.md @@ -240,11 +240,29 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp * Answer a continued question. The reply is steered into the agent as a * user message whose source names the call; that message is also the * record that closes the question in the projection. + * + * The only call this method can answer is one the projection lists as + * `continued` on this Session, and it steers a user message into the running + * turn, so it speaks for the person the Session runs for. A LiveShare reader + * reaches it through the Session read role, which is safe only while an + * approval question cannot become `continued`: the projection tracks only + * calls made under the timed `ask_user_question` schema, and a call becomes + * `continued` only by returning the pending result a timed wait produces (or, + * for PTC, a pending dispatch) or by resume repair recording + * `TOOL_OUTCOME_UNKNOWN` for a call the process never finished. Plan review + * (`plan-review`) and the CUA approvals (`approval`) reach `ctx.userQuestions.ask` + * without a `wait` and without a `timeout`, so their result is a settled + * answer, an abort, or a failure, never a pending result, and they stay out + * of the projection. A future approval surface must keep asking without + * `wait`/`timeout`, or it must gain its own owner-only gate; giving it a timed + * form makes an approval answerable by a share viewer. * @param agent - Live root agent for the owning Session. * @param callId - Continued question identity. * @param answer - Complete structured answer batch, one item per question of the call. - * @returns Whether the question is still continued; an accepted reply stays - * queued until the agent admits its user message. + * @returns Whether the question is still continued (`false` when this Session + * lists no such continued call, or its composition carries no Session + * projections); an accepted reply stays queued until the agent admits its + * user message. * @throws {UserQuestionError} `BAD_ANSWER` when the batch does not name each * question of the call exactly once, or `REPLY_QUEUED` when a reply is * already waiting for admission. diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index 40baec77cf..27ea041b50 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 6cc2cd9ced70bb09 zh: 1c0e6cb4ba2ed637 /tool-schema-catalog/tool-package-map: - en: 4e5bb11e4664bb1c - zh: 4855556d38701373 + en: 789c9c7932024257 + zh: 6d0465e0463b321c /tool-schema-catalog/deepseek-ai-dsh-plugin-manager: en: e0143916bb634762 zh: e0143916bb634762 @@ -72,8 +72,8 @@ en: 8c8643ef46fd075f zh: 8c8643ef46fd075f /tool-schema-catalog/deepseek-ai-dsh-tool-executor-ptc/run-code: - en: cff92e5a2476af7e - zh: 8d56bc41053f0a85 + en: 93d8526bbc4936d2 + zh: 963af83582d289c5 /tool-schema-catalog/deepseek-ai-dsh-plan-mode: en: b500b530845e26a9 zh: b500b530845e26a9 @@ -113,12 +113,9 @@ /tool-schema-catalog/deepseek-ai-dsh-tool-cordis: en: 76c7c62f9029b6f5 zh: 76c7c62f9029b6f5 -/tool-schema-catalog/deepseek-ai-dsh-tool-cordis/cordis-inspect-list: - en: 594e5b42047969cc - zh: 72189ca21345c210 -/tool-schema-catalog/deepseek-ai-dsh-tool-cordis/cordis-inspect-query: - en: 42a647ba98527f9e - zh: c53ade6a47ea523f +/tool-schema-catalog/deepseek-ai-dsh-tool-cordis/cordis-inspect: + en: f804c4e7fccc1c45 + zh: 7538d8201ef16ed9 /tool-schema-catalog/deepseek-ai-dsh-tool-bash-persistent: en: bdd9e88c49029e05 zh: bdd9e88c49029e05 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 68179c6363..12ceedfbb2 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -27,7 +27,7 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-office` | `office_convert`, `office_recalculate`, `office_render` | `ctx.workingDirectory`, `ctx.tools`, `ctx.fs`, `ctx.agents`, `ctx.officeKit`, `ctx.attachments and ctx.llm for office_render` | `tool/call`, `tool/result with rendered image attachments`, `temporary converted files in the Office kit output store` | - | Declared to an Agent from the step after it successfully loads an Office skill, and kept while the previous request header declares an Office tool. Admitted calls fail with the Office service's unavailable error when LibreOffice Kit is not installed. | | `@deepseek-ai/dsh-tool-present` | `present` | `ctx.workingDirectory`, `ctx.tools`, `ctx.fs`, `ctx.agents` | `tool/call`, `deliverables/presented after a successful final result`, `tool/result` | - | Deliveries belong to the calling Session; Web ui-deliverables supplies source-file opening and cards. | | `@deepseek-ai/dsh-tool-pwsh` | `pwsh` | `ctx.workingDirectory`, `ctx.tools`, `ctx.shell`, `ctx.systemPrompt`, `ctx.shellEnv`, `ctx.jobs for run_in_background and the job-backed foreground path` | `tool/call`, `tool/result` | - | The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.shell`); it mirrors the bash tool call-for-call minus sandbox controls — `run_in_background` runs register with the generic `ctx.jobs` runtime and are collected/stopped through the `job_*` tools, and the managed `DSH_*` environment comes from `@deepseek-ai/dsh-shell-env`. Each call runs in a fresh process (no persistent PTY session), with native `C:\...` paths and `$env:NAME` variables. | -| `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect_list`, `cordis_inspect_query` | `ctx.tools`, `ctx.cordisInspect` | `tool/call`, `tool/result` | - | Creator mode provides two read-only runtime inspection tools. The Cordis host runner supplies the inspection registry; Client queries require a connected page. Author persistent changes as bundles and install them with plugin_manager. | +| `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect` | `ctx.tools`, `ctx.cordisInspect` | `tool/call`, `tool/result` | - | Standard and Creator modes provide one read-only runtime inspection tool. Omit query for the provider directory; pass query to inspect a declared method. The Cordis host runner supplies the inspection registry; Client queries require a connected page. Author persistent changes as bundles and install them with plugin_manager. | | `@deepseek-ai/dsh-tool-bash-persistent` | `bash` | `ctx.workingDirectory`, `ctx.tools`, `ctx.terminals`, `an owning Agent at execution time` | `tool/call`, `PTY shell state`, `tool/result` | - | One owner-isolated persistent bash tool; deployment composition supplies the PTY backend and may override the model-facing environment description. | | `@deepseek-ai/dsh-tool-pwsh-persistent` | `pwsh` | `ctx.workingDirectory`, `ctx.tools`, `ctx.terminals`, `an owning Agent at execution time` | `tool/call`, `PTY shell state`, `tool/result` | - | One owner-isolated persistent pwsh tool, the Windows counterpart of the persistent bash tool; deployment composition supplies a pwsh-dialect PTY backend and may override the model-facing environment description. | | `@deepseek-ai/dsh-tool-str-replace-editor` | `str_replace_editor` | `ctx.tools`, `ctx.fs` | `tool/call`, `fs/observed after view presence/absence, edit absence, or successful mutation`, `tool/result` | - | Standalone view/create/unique literal replace/line insert tool over the filesystem seam; it composes with any shell or terminal API. | @@ -623,7 +623,7 @@ ask_user_question keeps the original blocking behavior by default; set `mode: ti ### `run_code` -Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). The program is the body of an async TypeScript function; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level await and return are supported. Use inspect(...values) to display output. Do not use console. Each call runs in a fresh Node process. Node APIs are available through await import(...). Relative paths use the supplied working directory; process.env starts empty. Direct filesystem access follows this execution's sandbox policy. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically. +Execute a TypeScript program against the available tools. Takes two required arguments: `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work), and `description`, a short summary of what the program does. Call tools as `await tools.name(args)` per the declarations in the system prompt. Show selected text and images with inspect(...values). The program is the body of an async TypeScript function; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level await and return are supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. Each call runs in a fresh Node process. Node APIs are available through await import(...). Relative paths use the supplied working directory; process.env starts empty. Direct filesystem access follows this execution's sandbox policy. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically. ```json { @@ -945,58 +945,51 @@ The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for W ## `@deepseek-ai/dsh-tool-cordis` -### `cordis_inspect_list` +### `cordis_inspect` -List every Cordis Inspect Provider currently known to the Host, including local Host Providers and the latest manifests synchronized from the Client. Each entry includes its platform, purpose, read-only methods, and input/output schemas. Call this Tool before writing or configuring a plugin, then select the provider and method for cordis_inspect_query from its result. Do not guess names or treat an Inspect method as a business Service that Plugin code can call. - -```json -{ - "type": "object", - "properties": {} -} -``` - -Source: [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) - -### `cordis_inspect_query` - -Run a read-only query declared by an Inspect Provider. platform, provider, and method must come from cordis_inspect_list, and input must satisfy that method's schema. Use this Tool before writing plugin code to read exact Service methods, Event modes, plugin Config schemas, Tool schemas, theme tokens, or live Slot trees and props. Host queries run locally. A Client query waits for the first valid page response within the configured timeout; otherwise it reports a Client failure or asks you to reconnect and retry. This Tool cannot invoke business Service methods or modify the runtime. +Inspect runtime APIs before writing or configuring plugins. Omit query to discover providers, methods, and input schemas; then query an exact entry from that directory. Read-only: cannot invoke business Service methods or modify the runtime. Client queries require a connected page. ```json { "type": "object", "properties": { - "platform": { - "type": "string", - "description": "Runtime platform that owns the Provider.", - "enum": [ - "host", - "client" + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "platform": { + "type": "string", + "description": "Provider platform.", + "enum": [ + "host", + "client" + ] + }, + "provider": { + "type": "string", + "description": "Provider ID from the directory." + }, + "method": { + "type": "string", + "description": "Method name from the directory." + }, + "input": { + "description": "Arguments matching the method's input schema." + } + }, + "required": [ + "platform", + "provider", + "method" ] - }, - "provider": { - "type": "string", - "description": "Exact Provider ID returned by cordis_inspect_list." - }, - "method": { - "type": "string", - "description": "Exact method name declared by the Provider manifest." - }, - "input": { - "description": "Optional query input; it must satisfy the method input schema." } - }, - "required": [ - "platform", - "provider", - "method" - ] + } } ``` Source: [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) -Creator mode provides two read-only runtime inspection tools. The Cordis host runner supplies the inspection registry; Client queries require a connected page. Author persistent changes as bundles and install them with plugin_manager. +Standard and Creator modes provide one read-only runtime inspection tool. Omit query for the provider directory; pass query to inspect a declared method. The Cordis host runner supplies the inspection registry; Client queries require a connected page. Author persistent changes as bundles and install them with plugin_manager. diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index 40484eccb1..9b07ad4683 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -31,7 +31,7 @@ | `@deepseek-ai/dsh-tool-office` | `office_convert`、`office_recalculate`、`office_render` | `ctx.workingDirectory`、`ctx.tools`、`ctx.fs`、`ctx.agents`、`ctx.officeKit`、`ctx.attachments and ctx.llm for office_render` | `tool/call`、`tool/result with rendered image attachments`、`temporary converted files in the Office kit output store` | - | Agent 成功加载 Office 技能后,从下一步起向其声明这些工具;上一次请求头已声明 Office 工具时继续保留。未安装 LibreOffice Kit 时,已声明工具的调用以 Office 服务的 unavailable 错误失败。 | | `@deepseek-ai/dsh-tool-present` | `present` | `ctx.workingDirectory`、`ctx.tools`, `ctx.fs`, `ctx.agents` | `tool/call`, `deliverables/presented 在成功的最终结果之后`, `tool/result` | - | 交付归调用方 Session 所有;Web ui-deliverables 提供源文件打开与卡片。 | | `@deepseek-ai/dsh-tool-pwsh` | `pwsh` | `ctx.workingDirectory`、`ctx.tools`、`ctx.shell`、`ctx.systemPrompt`、`ctx.shellEnv`、`ctx.jobs for run_in_background and the job-backed foreground path` | `tool/call`、`tool/result` | - | pwsh 工具是 Windows 组合中 bash 执行器 seam 的 PowerShell 方言消费方(由 `@deepseek-ai/dsh-pwsh-local` 等 PowerShell 执行器为 `ctx.shell` 提供后端);除沙箱接口外,它逐项对应 bash 工具调用。使用 `run_in_background` 的运行会注册到通用 `ctx.jobs` 运行时,并通过 `job_*` 工具收集/停止;托管的 `DSH_*` 环境来自 `@deepseek-ai/dsh-shell-env`。每次调用都在新进程中运行,不使用持久 PTY 会话。路径采用原生 `C:\...` 形式,变量采用 `$env:NAME`。 | -| `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect_list`, `cordis_inspect_query` | `ctx.tools`, `ctx.cordisInspect` | `tool/call`, `tool/result` | - | 创造模式提供两个只读运行时检查工具。Cordis host runner 提供检查注册表;Client 查询需要已连接页面。持久化变更编写为组合包,再通过 plugin_manager 安装。 | +| `@deepseek-ai/dsh-tool-cordis` | `cordis_inspect` | `ctx.tools`, `ctx.cordisInspect` | `tool/call`, `tool/result` | - | 标准模式和创造模式提供一个只读运行时检查工具。省略 query 获取 provider 目录;传入 query 查询已声明的方法。Cordis host runner 提供检查注册表;Client 查询需要已连接页面。持久化变更编写为组合包,再通过 plugin_manager 安装。 | | `@deepseek-ai/dsh-tool-bash-persistent` | `bash` | `ctx.workingDirectory`、`ctx.tools`、`ctx.terminals`、`an owning Agent at execution time` | `tool/call`、`PTY shell state`、`tool/result` | - | 一个按所有者隔离的持久 bash 工具;部署组合提供 PTY 后端,并可覆盖面向模型的环境描述。 | | `@deepseek-ai/dsh-tool-pwsh-persistent` | `pwsh` | `ctx.workingDirectory`、`ctx.tools`、`ctx.terminals`、`an owning Agent at execution time` | `tool/call`、`PTY shell state`、`tool/result` | - | 一个按所有者隔离的持久 pwsh 工具,持久 bash 工具的 Windows 对应物;部署组合提供 pwsh 方言的 PTY 后端,并可覆盖面向模型的环境描述。 | | `@deepseek-ai/dsh-tool-str-replace-editor` | `str_replace_editor` | `ctx.tools`、`ctx.fs` | `tool/call`、`fs/observed after view presence/absence, edit absence, or successful mutation`、`tool/result` | - | 基于文件系统 seam 的独立查看/创建/唯一字面量替换/按行插入工具;可与任何 shell 或终端接口组合。 | @@ -627,7 +627,7 @@ ask_user_question 默认保持原有阻塞行为;设置 `mode: timed` 后才 ### `run_code` -针对可用工具执行 TypeScript 程序。接受两个必填参数:`code`,异步函数的函数体(仅限可擦除语法,支持顶层 `await` 和 `return`);以及 `description`,简要说明程序做什么。请按系统提示词中的声明,以 `await tools.name(args)` 调用工具。使用 inspect(...values) 展示选定的文本和图片。程序是异步 TypeScript 函数的函数体,只接受可擦除语法,不支持 enum 或 namespace。类型标注只作提示。支持顶层 await 和 return。使用 inspect(...values) 展示输出。不要使用 console。每次调用在新的 Node 进程中运行,可通过 await import(...) 使用 Node API。相对路径以传入的工作目录为准;process.env 初始为空。直接文件系统访问遵循本次执行的沙箱策略。每个程序从 Session 的当前目录启动,运行中保留初始目录。沙箱提权只为本次完整程序执行授权。嵌套工具保留自身策略与审批。只有在获得拒绝证据后才请求更宽访问。先前效果可能已经发生,请在显式重试前检查。程序不会自动重放。 +针对可用工具执行 TypeScript 程序。接受两个必填参数:`code`,异步函数的函数体(仅限可擦除语法,支持顶层 `await` 和 `return`);以及 `description`,简要说明程序做什么。请按系统提示词中的声明,以 `await tools.name(args)` 调用工具。使用 inspect(...values) 展示选定的文本和图片。程序是异步 TypeScript 函数的函数体,只接受可擦除语法,不支持 enum 或 namespace。类型标注只作提示。支持顶层 await 和 return。使用 inspect(...values) 展示输出。不要使用 console。模板字面量的 raw 形式只用于反斜杠必须原样保留的短文本,例如正则表达式;其他文本,尤其是文件内容和命令,用普通字符串书写。文件内容写成引号字符串数组,每行一个元素,用换行符拼接;不要写成一个模板字面量。每次调用在新的 Node 进程中运行,可通过 await import(...) 使用 Node API。相对路径以传入的工作目录为准;process.env 初始为空。直接文件系统访问遵循本次执行的沙箱策略。每个程序从 Session 的当前目录启动,运行中保留初始目录。沙箱提权只为本次完整程序执行授权。嵌套工具保留自身策略与审批。只有在获得拒绝证据后才请求更宽访问。先前效果可能已经发生,请在显式重试前检查。程序不会自动重放。 ```json { @@ -949,58 +949,51 @@ pwsh 工具是 Windows 组合中 bash 执行器 seam 的 PowerShell 方言消费 ## `@deepseek-ai/dsh-tool-cordis` -### `cordis_inspect_list` +### `cordis_inspect` -列出 Host 当前已知的所有 Cordis Inspect Provider,包括本地 Host Provider 和 Client 同步的最新清单。每项包含平台、用途、只读方法以及输入输出 schema。编写或配置插件前先调用本工具,再从结果选择 cordis_inspect_query 的 provider 和方法。不要猜测名称,也不要把 Inspect 方法当作插件代码可调用的业务 Service。 - -```json -{ - "type": "object", - "properties": {} -} -``` - -来源: [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) - -### `cordis_inspect_query` - -执行 Inspect Provider 声明的只读查询。platform、provider 和 method 必须来自 cordis_inspect_list,input 必须符合该方法的 schema。编写插件代码前,用本工具读取准确的 Service 方法、Event 模式、插件 Config schema、Tool schema、主题 token,或实时 Slot 树与 props。Host 查询在本地运行。Client 查询在配置的超时内等待页面首个有效响应;否则返回 Client 错误,或提示重新连接后重试。本工具不能调用业务 Service 方法或修改运行时。 +编写或配置插件前查询运行时 API。省略 query 以发现 provider、方法和输入 schema,再查询该目录中的具体条目。只读:不能调用业务 Service 方法或修改运行时。Client 查询需要已连接的页面。 ```json { "type": "object", "properties": { - "platform": { - "type": "string", - "description": "Runtime platform that owns the Provider.", - "enum": [ - "host", - "client" + "query": { + "type": "object", + "additionalProperties": false, + "properties": { + "platform": { + "type": "string", + "description": "Provider platform.", + "enum": [ + "host", + "client" + ] + }, + "provider": { + "type": "string", + "description": "Provider ID from the directory." + }, + "method": { + "type": "string", + "description": "Method name from the directory." + }, + "input": { + "description": "Arguments matching the method's input schema." + } + }, + "required": [ + "platform", + "provider", + "method" ] - }, - "provider": { - "type": "string", - "description": "Exact Provider ID returned by cordis_inspect_list." - }, - "method": { - "type": "string", - "description": "Exact method name declared by the Provider manifest." - }, - "input": { - "description": "Optional query input; it must satisfy the method input schema." } - }, - "required": [ - "platform", - "provider", - "method" - ] + } } ``` 来源: [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) -创造模式提供两个只读运行时检查工具。Cordis host runner 提供检查注册表;Client 查询需要已连接页面。持久化变更编写为组合包,再通过 plugin_manager 安装。 +标准模式和创造模式提供一个只读运行时检查工具。省略 query 获取 provider 目录;传入 query 查询已声明的方法。Cordis host runner 提供检查注册表;Client 查询需要已连接页面。持久化变更编写为组合包,再通过 plugin_manager 安装。 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/cordis-inspect-tool/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/cordis-inspect-tool/guide.i18n.yaml new file mode 100644 index 0000000000..0810c77320 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/cordis-inspect-tool/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-rc.3/cordis-inspect-tool/guide.md +/: + en: 74fcdcd04d1f4a09 + zh: 29f3fd6a4996f748 +/use-one-cordis-inspection-tool: + en: da2e5b8ded13d6ad + zh: 67d4ae724c7561e2 +/use-one-cordis-inspection-tool/change: + en: 4ba772b8a87ad4bd + zh: a50b3c0739a68b67 +/use-one-cordis-inspection-tool/migration: + en: c10ebe52b24af1e2 + zh: be4ba383eb213057 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/cordis-inspect-tool/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/cordis-inspect-tool/guide.md new file mode 100644 index 0000000000..d9950ccc26 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/cordis-inspect-tool/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "The cordis_inspect tool replaces cordis_inspect_list and cordis_inspect_query." +--- + +# Use one Cordis inspection tool + +English | [中文](guide.zh.md) + +## Change + +`cordis_inspect` replaces `cordis_inspect_list` and `cordis_inspect_query`. Custom prompts, skills, and tool callers that name either old tool must use the new name and arguments. An omitted `query` returns the provider directory; a supplied `query` selects a provider method. + +## Migration + +1. Replace `cordis_inspect_list({})` calls with `cordis_inspect({})`. +2. Replace `cordis_inspect_query({ platform, provider, method, input })` calls with `cordis_inspect({ query: { platform, provider, method, input } })`. Keep `platform`, `provider`, and `method` inside `query`; `input` remains optional. +3. Confirm that `cordis_inspect({})` returns a provider directory. Select a provider and method from that directory, supply arguments matching its input schema under `query.input`, and confirm that the query returns the requested data. Client queries require a connected page. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/cordis-inspect-tool/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/cordis-inspect-tool/guide.zh.md new file mode 100644 index 0000000000..649e09b1a2 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/cordis-inspect-tool/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "cordis_inspect 工具替代 cordis_inspect_list 和 cordis_inspect_query。" +--- + +# 使用单个 Cordis 检查工具 + +[English](guide.md) | 中文 + +## 变更 + +`cordis_inspect` 替代 `cordis_inspect_list` 和 `cordis_inspect_query`。引用任一旧工具名称的自定义提示词、skill(技能)和工具调用方必须使用新名称及参数。省略 `query` 时返回 provider 目录;提供 `query` 时选择 provider 方法。 + +## 迁移 + +1. 将 `cordis_inspect_list({})` 调用替换为 `cordis_inspect({})`。 +2. 将 `cordis_inspect_query({ platform, provider, method, input })` 调用替换为 `cordis_inspect({ query: { platform, provider, method, input } })`。将 `platform`、`provider` 和 `method` 放在 `query` 内;`input` 仍为可选参数。 +3. 确认 `cordis_inspect({})` 返回 provider 目录。从该目录中选择 provider 和方法,在 `query.input` 下提供符合其输入 schema 的参数,并确认查询返回所请求的数据。Client 查询需要已连接的页面。 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/profile-context-overlay-paths/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/profile-context-overlay-paths/guide.i18n.yaml new file mode 100644 index 0000000000..da4f3f8fb3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/profile-context-overlay-paths/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-rc.3/profile-context-overlay-paths/guide.md +/: + en: c4ef1e7d8d298290 + zh: 31b78ba3894af10c +/read-command-line-overlays-from-their-files: + en: bfab1724009b36aa + zh: 103463ee47fbdafc +/read-command-line-overlays-from-their-files/change: + en: 8abc69fc8b12c36e + zh: 89856745d785a697 +/read-command-line-overlays-from-their-files/migration: + en: 87ea30b7ee93ef13 + zh: 898cfde6b53f8248 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/profile-context-overlay-paths/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/profile-context-overlay-paths/guide.md new file mode 100644 index 0000000000..60381472dc --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/profile-context-overlay-paths/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "ProfileContext replaces parsed overlays with overlay file paths that every composition rereads." +--- + +# Read command-line overlays from their files + +English | [中文](guide.zh.md) + +## Change + +`ProfileContext` from `@deepseek-ai/dsh-app-boot`, provided as `ctx.profileContext`, no longer has `overlays: readonly PatchOptions[]`. It now carries `overlayPaths: readonly string[]`: the absolute `--patch` file paths in argv order. `readProfilePatches()` reads those files on each call, so it returns current overlay contents and throws while an overlay file is missing or invalid. With `dsh-hmr` enabled, editing a `--patch` file recomposes the running profile. Plugins that read `profileContext.overlays` and launchers or tests that construct a `ProfileContext` are affected. + +## Migration + +1. Replace reads of `ctx.profileContext.overlays` with `ctx.profileContext.overlayPaths.flatMap(path => loadOverlayPatches(binName, path))`, which returns the same overlay layer. Call `readProfilePatches(binName, ctx.profileContext)` only when you need the full composition of bundle, profile, home, and overlay layers. +2. Where code constructs a `ProfileContext`, replace `overlays: [...]` with `overlayPaths: [...]`. Write any in-memory overlay rows to a patch file first and pass its absolute path. +3. Confirm the migration by running your type checker: no `overlays` property remains on `ProfileContext` values. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/profile-context-overlay-paths/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/profile-context-overlay-paths/guide.zh.md new file mode 100644 index 0000000000..281e1b9566 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/profile-context-overlay-paths/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "ProfileContext 以 overlay 文件路径取代已解析的 overlay,每次组合都会重新读取这些文件。" +--- + +# 从文件读取命令行 overlay + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-app-boot` 的 `ProfileContext`(以 `ctx.profileContext` 提供)不再包含 `overlays: readonly PatchOptions[]`,改为 `overlayPaths: readonly string[]`:按命令行顺序排列的 `--patch` 文件绝对路径。`readProfilePatches()` 每次调用都会读取这些文件,因此返回当前的 overlay 内容,并在 overlay 文件缺失或无效时抛出异常。启用 `dsh-hmr` 时,编辑 `--patch` 文件会重新组合运行中的 profile。读取 `profileContext.overlays` 的插件,以及构造 `ProfileContext` 的启动器或测试会受到影响。 + +## 迁移 + +1. 将对 `ctx.profileContext.overlays` 的读取替换为 `ctx.profileContext.overlayPaths.flatMap(path => loadOverlayPatches(binName, path))`,它返回相同的 overlay 层。只有需要 bundle、profile、home 与 overlay 各层的完整组合结果时,才调用 `readProfilePatches(binName, ctx.profileContext)`。 +2. 在构造 `ProfileContext` 的代码中,将 `overlays: [...]` 替换为 `overlayPaths: [...]`。内存中的 overlay 行需先写入 patch 文件,再传入该文件的绝对路径。 +3. 运行类型检查确认迁移完成:`ProfileContext` 值上不再存在 `overlays` 属性。 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-mcp-image-values/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/ptc-mcp-image-values/guide.i18n.yaml new file mode 100644 index 0000000000..65f82997f3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-mcp-image-values/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-rc.3/ptc-mcp-image-values/guide.md +/: + en: 4ef7bb2332b41c50 + zh: 64dc0fee94ec109f +/admitted-mcp-image-blocks-become-ptc-image-values: + en: d6de4dbd1d9e5b97 + zh: abfc0e17251123b4 +/admitted-mcp-image-blocks-become-ptc-image-values/change: + en: 49c1de6568812254 + zh: e33b028fb5369be3 +/admitted-mcp-image-blocks-become-ptc-image-values/migration: + en: 7015ecfe11765993 + zh: 677267091fa5458a diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-mcp-image-values/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/ptc-mcp-image-values/guide.md new file mode 100644 index 0000000000..92b53610c3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-mcp-image-values/guide.md @@ -0,0 +1,30 @@ +--- +kind: upgrade-guide +description: "Admitted MCP image blocks carry an attachment reference and reach PTC programs as Image values instead of base64 JSON." +--- + +# Admitted MCP image blocks become PTC `Image` values + +English | [中文](guide.zh.md) + +## Change + +An MCP tool result keeps its canonical `{ content, structuredContent? }` value. Each image block admitted to durable model context now also carries an `attachment` reference beside its original `type`, `mimeType`, and `data` fields. Refused images keep their original fields only. + +In PTC mode, each value entry of the form `{ type: 'image', attachment }` whose attachment appears in the finalized tool result becomes an `Image`, the same value that `read_image` and CUA screenshots return. Previously, the program received the base64 image block, so `inspect(result)` printed the base64 data, and the complete result content, text and pictures, was attached automatically as additional model context. Now `inspect` shows the picture, and the result's text and pictures enter the conversation only when the program inspects them, as for native CUA screenshots. When the value does not reference every image of the final result, or the program cannot read an image file, the program receives the raw blocks and the complete result content is still attached automatically, as before. Image blocks that an output policy removed keep their `attachment` field but stay JSON. + +This affects PTC programs that read `data` or `mimeType` from an admitted MCP image block or rely on the automatic attachment of its result text, and code that compares MCP tool values with the raw server result. + +## Migration + +1. In PTC programs, inspect the `Image` and any result text the model needs, or read the image file through `path`: + + ```js + const result = await tools.mcp__server__screenshot({}); + const image = result.content.find(block => block instanceof Image); + inspect(image); + ``` + +2. Where a program needs the bytes, read `image.path` instead of decoding `data`. +3. In code that compares MCP tool values with the server result, allow the added `attachment` field on admitted image blocks. +4. Run the example with a model route that accepts image input. Confirm that the `run_code` result contains the picture and no base64 text. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-mcp-image-values/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/ptc-mcp-image-values/guide.zh.md new file mode 100644 index 0000000000..ba7964fd34 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-mcp-image-values/guide.zh.md @@ -0,0 +1,30 @@ +--- +kind: upgrade-guide +description: "已接受的 MCP 图片块携带附件引用,并以 Image 值而非 base64 JSON 传给 PTC 程序。" +--- + +# 已接受的 MCP 图片块成为 PTC `Image` 值 + +[English](guide.md) | 中文 + +## 变更 + +MCP 工具结果保留其规范值 `{ content, structuredContent? }`。每个进入持久模型上下文的图片块现在除原有的 `type`、`mimeType` 和 `data` 字段外,还携带 `attachment` 引用。被拒绝的图片仅保留原有字段。 + +在 PTC 模式下,形如 `{ type: 'image', attachment }` 且其附件出现在最终工具结果中的每个值条目都会变为 `Image`,与 `read_image` 和 CUA 截图返回的值相同。此前,程序收到的是 base64 图片块,因此 `inspect(result)` 输出 base64 数据,包括文本与图片在内的完整结果内容则自动作为额外模型上下文附加。现在 `inspect` 展示图片,且结果的文本与图片仅在程序 inspect 时进入对话,与原生 CUA 截图相同。返回值未引用最终结果中的每张图片,或程序无法读取某个图片文件时,程序接收原始块,完整的结果内容仍与此前一样自动附加。被输出策略移除的图片块保留 `attachment` 字段,但仍为 JSON。 + +从已接受的 MCP 图片块读取 `data` 或 `mimeType`、或依赖其结果文本自动附加的 PTC 程序,以及将 MCP 工具值与服务器原始结果比较的代码会受到影响。 + +## 迁移 + +1. 在 PTC 程序中,inspect `Image` 以及模型需要的结果文本,或通过 `path` 读取图片文件: + + ```js + const result = await tools.mcp__server__screenshot({}); + const image = result.content.find(block => block instanceof Image); + inspect(image); + ``` + +2. 程序需要字节数据时,读取 `image.path`,不要解码 `data`。 +3. 在将 MCP 工具值与服务器结果比较的代码中,允许已接受图片块上新增的 `attachment` 字段。 +4. 使用接受图片输入的模型路由运行上面的示例。确认 `run_code` 结果包含图片且不含 base64 文本。 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.i18n.yaml new file mode 100644 index 0000000000..1ede92245b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/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-rc.3/ptc-tool-result-inspection/guide.md +/: + en: 31e27f1eb83f9740 + zh: 85c7c3637222f1d8 +/ptc-tool-result-inspection-and-bootstrap-protocol-4: + en: 2509c4fe8d208eb8 + zh: 5f5dfd41fd29cd55 +/ptc-tool-result-inspection-and-bootstrap-protocol-4/change: + en: a374fea86e00efb1 + zh: fa50515f25ef048e +/ptc-tool-result-inspection-and-bootstrap-protocol-4/migration: + en: bfb868b271b5113d + zh: 597c95d985891d43 diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md new file mode 100644 index 0000000000..3e2d476945 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.md @@ -0,0 +1,34 @@ +--- +kind: upgrade-guide +description: "Direct inspection of unchanged PTC object and array tool results uses tool-rendered text, and custom Node bootstraps require protocol 4." +--- + +# PTC tool-result inspection and bootstrap protocol 4 + +English | [中文](guide.zh.md) + +## Change + +PTC tools keep their declared JSON return values. With or without inspection metadata, field access, copying, and JSON serialization operate on the original data; the host-only descriptor is not exposed to the program. Previously, `inspect(result)` formatted an object or array with Node's generic object formatter. It now displays the tool's final rendered text when the original result is unchanged and its output contains only text. The text includes completed output-policy changes; inspection neither reruns the tool nor calls `output.render` again. Log-only replacements do not affect it. + +Non-empty associated text occupies a separate output group. `inspect('result:', result, 'done')` emits the label and a newline, then the tool text, followed by `done` in another group. Ordinary values in one group remain space-separated. + +Field selections, copies, modified results, and results nested inside another value still use generic formatting. Scalar results, Images, and mixed text/image outputs keep their behavior. This affects programs and checks that depend on the exact text produced by inspecting a complete tool result. Inspectable containers may retain Image fields: direct inspection shows the supplied text; inspect the image field separately to display it. + +The Node bootstrap protocol changes from 3 to 4. `HostMethods.invoke` replies now use `{ value: flatWire, inspection?: string }`. Custom `launch.bootstrapPath` deployments must update their bootstrap; the bundled bootstrap updates with the host. + +## Migration + +1. Keep `inspect(result)` to display the tool's rendered text. To display an object's structure, inspect a copy or selected fields: + + ```js + const result = await tools.read({ file_path: "README.md" }); + inspect(result); + inspect({ ...result }); + inspect(result.lines); + ``` + +2. For an array result, use `inspect([...result])` to display its elements with generic formatting. Update any expected output that relied on the previous full-result object formatting. +3. If you implement a third-party `PtcRuntime`, recognize `PtcInspectableValue` binding results from `@deepseek-ai/dsh-ptc-runtime`. Deliver `.value` as the program's object or array, and associate `.text` with that unchanged value for direct `inspect`. Do not expose the wrapper or add inspection metadata to program fields. +4. If you configure `launch.bootstrapPath`, deploy the matching `@deepseek-ai/dsh-ptc-runtime-node` bootstrap and its dependencies in that execution environment. Use the package's built `lib/process.js`, or `lib/persistent-process.js` for a REPL default. A custom protocol implementation must handle the new reply envelope as well as announce protocol 4; changing the version alone is insufficient. +5. Run the example above. Confirm that the first inspection shows the tool's rendered file text, while the other two show object and array data. For a custom provider, also confirm that field access and `JSON.stringify(result)` use the original data. For a custom bootstrap, confirm that a PTC program starts without a protocol-mismatch error. diff --git a/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.zh.md new file mode 100644 index 0000000000..ad472ea7d5 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/ptc-tool-result-inspection/guide.zh.md @@ -0,0 +1,34 @@ +--- +kind: upgrade-guide +description: "直接展示未修改的 PTC 工具对象和数组结果时使用工具渲染文本,自定义 Node bootstrap 须升级到协议 4。" +--- + +# PTC 工具结果展示与 bootstrap 协议 4 + +[English](guide.md) | 中文 + +## 变更 + +PTC 工具保留声明的 JSON 返回值。无论是否附带展示元数据,字段访问、拷贝和 JSON 序列化都操作原有数据;只供宿主使用的描述符不会暴露给程序。此前,`inspect(result)` 使用 Node 的通用对象格式展示对象或数组。现在,原结果未被修改且其输出仅包含文本时,会展示工具最终渲染的文本。该文本包含已完成的输出策略修改;展示不会重新运行工具或再次调用 `output.render`。仅针对日志的替换不影响此文本。 + +非空的关联文本独占一个输出组。执行 `inspect('result:', result, 'done')` 时,先输出标签并换行,再输出工具文本,随后另起一组输出 `done`。同组普通值仍以空格分隔。 + +字段选择、拷贝、修改后的结果,以及嵌套在其他值中的结果,仍使用通用格式。标量结果、Image 和混合文本与图片的输出保持原有行为。依赖完整工具结果展示文本的程序和检查会受到影响。可展示的容器可以保留 Image 字段:直接展示容器时输出附带文本;单独展示图片字段时输出该图片。 + +Node bootstrap 协议从 3 升至 4。`HostMethods.invoke` 的回复现在使用 `{ value: flatWire, inspection?: string }`。自定义 `launch.bootstrapPath` 部署必须更新 bootstrap;内置 bootstrap 随宿主一同更新。 + +## 迁移 + +1. 保留 `inspect(result)` 可展示工具渲染的文本。如需展示对象结构,改为展示拷贝或选定字段: + + ```js + const result = await tools.read({ file_path: "README.md" }); + inspect(result); + inspect({ ...result }); + inspect(result.lines); + ``` + +2. 对数组结果,使用 `inspect([...result])` 以通用格式展示元素。更新依赖此前完整结果对象格式的预期输出。 +3. 如果实现了第三方 `PtcRuntime`,请识别绑定返回的 `@deepseek-ai/dsh-ptc-runtime` 包中的 `PtcInspectableValue`。将 `.value` 作为程序的对象或数组,并为该未修改的原值关联 `.text`,供直接 `inspect` 使用。不要暴露包装对象,也不要向程序字段添加展示元数据。 +4. 如果配置了 `launch.bootstrapPath`,请在执行环境中部署匹配版本的 `@deepseek-ai/dsh-ptc-runtime-node` bootstrap 及其依赖。使用包内构建产物 `lib/process.js`,或默认采用 REPL 的 `lib/persistent-process.js`。自定义协议实现必须处理新的回复信封并声明协议 4;只改版本号并不足够。 +5. 运行上面的示例。确认第一次展示工具渲染的文件文本,后两次分别展示对象和数组数据。对于自定义提供方,还须确认字段访问和 `JSON.stringify(result)` 使用原有数据。对于自定义 bootstrap,确认 PTC 程序启动时不再报告协议不匹配。 diff --git a/docs/user/develop/practice/dynamic-cordis.i18n.yaml b/docs/user/develop/practice/dynamic-cordis.i18n.yaml index b8605313fd..9e99bfb6fd 100644 --- a/docs/user/develop/practice/dynamic-cordis.i18n.yaml +++ b/docs/user/develop/practice/dynamic-cordis.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/user/develop/practice/dynamic-cordis.md /configure-persistent-plugins-from-a-prompt: - en: d50e336357663f75 - zh: 4364e91403387e2a + en: e61e42a805142826 + zh: da51aa93305f2a3c /configure-persistent-plugins-from-a-prompt/connect-an-mcp-server: en: f9fefda94ba8a005 zh: f1a9a977a0732fc0 diff --git a/docs/user/develop/practice/dynamic-cordis.md b/docs/user/develop/practice/dynamic-cordis.md index e387722cea..ea805bc92f 100644 --- a/docs/user/develop/practice/dynamic-cordis.md +++ b/docs/user/develop/practice/dynamic-cordis.md @@ -2,7 +2,7 @@ English | [中文](dynamic-cordis.zh.md) -Standard and Creator modes provide [Plugin Manager](../../../../packages/boot/plugin-manager/README.md); Creator mode adds read-only [runtime inspection](../../../../packages/extensions/tool-cordis/README.md). Plugin configuration belongs to the current profile, affects its sessions, and survives process restarts. +Standard and Creator modes provide [Plugin Manager](../../../../packages/boot/plugin-manager/README.md) and read-only [runtime inspection](../../../../packages/extensions/tool-cordis/README.md). Plugin configuration belongs to the current profile, affects its sessions, and survives process restarts. ## Connect an MCP server diff --git a/docs/user/develop/practice/dynamic-cordis.zh.md b/docs/user/develop/practice/dynamic-cordis.zh.md index 1ee91c7479..5c1d10bd56 100644 --- a/docs/user/develop/practice/dynamic-cordis.zh.md +++ b/docs/user/develop/practice/dynamic-cordis.zh.md @@ -2,7 +2,7 @@ [English](dynamic-cordis.md) | 中文 -标准模式和创造模式提供 [Plugin Manager](../../../../packages/boot/plugin-manager/README.zh.md);创造模式还提供只读[运行时检查](../../../../packages/extensions/tool-cordis/README.zh.md)。插件配置属于当前 profile,影响其会话,并在进程重启后保留。 +标准模式和创造模式提供 [Plugin Manager](../../../../packages/boot/plugin-manager/README.zh.md) 和只读[运行时检查](../../../../packages/extensions/tool-cordis/README.zh.md)。插件配置属于当前 profile,影响其会话,并在进程重启后保留。 ## 连接 MCP 服务器 diff --git a/docs/user/guide/schedule.i18n.yaml b/docs/user/guide/schedule.i18n.yaml index 31fba2c702..d3008b6662 100644 --- a/docs/user/guide/schedule.i18n.yaml +++ b/docs/user/guide/schedule.i18n.yaml @@ -15,8 +15,8 @@ en: 762ecb7a7743cd2d zh: 1b163ae679601767 /schedule-reminders/inspect-run-and-delete-tasks: - en: 9f1e9d732597aa28 - zh: 66feec44adf24332 + en: cad6e8f2facb59a7 + zh: d624b2f4bba8fd9f /schedule-reminders/edit-a-task: en: fe8c59251f0b4620 zh: a422e44f758adae1 diff --git a/docs/user/guide/schedule.md b/docs/user/guide/schedule.md index bdee6c86b3..31bb568e31 100644 --- a/docs/user/guide/schedule.md +++ b/docs/user/guide/schedule.md @@ -38,7 +38,7 @@ Ask the model to list reminders to see the reminders of every conversation, acti Open Automation tasks from the sidebar to view reminders across Sessions without activating their conversations. Search by the task name, the instruction, or the id of the task's conversation, and filter by Task status: All, Enabled, Paused, or Ended. Rows are ordered by their scheduled time, earliest first. Each row shows the task name and one summary line: the status of a paused or ended task, the frequency, and, for an enabled task, Next scheduled time with its local and relative time. -A Session's tasks are the tasks that deliver to it, including the latest run of a task that creates a new conversation for every run, and the tasks that its Agent created or edited. An idle, unarchived Session row whose Session has at least one active task shows a clock mark; an archived row keeps that cell blank, with its live status on the hover card only. A long hover on a Session row with active tasks lists up to two of those tasks with their frequency and their next run as a device-zone time with its relative duration. The open Session's header shows an icon-only reminder clock while the Session has active tasks: it opens the sole task's details in the right sidebar, or otherwise a list of those tasks in which each row opens the task's details or deletes the task. +The Session header clock, row mark, and hover list show active tasks with that Session as a fixed delivery target. These tasks deliver to an existing Session or reuse the Session created for their first delivery. An idle, unarchived Session row with at least one such task shows a clock mark. An archived row shows its live status only in the hover card. A long hover on a Session row with such tasks lists up to two of those tasks with their frequency and their next run as a device-zone time with its relative duration. The open Session's header shows an icon-only reminder clock while that Session has such tasks. The clock opens the sole task's details in the right sidebar. For multiple tasks, it opens a list where each row can open the task's details or delete the task. Select a task to open its details. Rules shows the task name, Next run with its local and relative time or the status of a paused or ended task, the instruction, Repeat, and Run in, which shows Current linked conversation for a task that delivers to an existing conversation. The bottom of the details shows Linked session, or Latest run conversation for a task that creates a new conversation for every run. Its button opens that conversation when the Session is available and unarchived, and is disabled otherwise; before the first run creates the conversation, the entry shows Pending creation. For a task that delivers to an existing conversation, Rules states when that conversation is archived, unavailable, or still loading. The task details and deletion remain available even when a conversation cannot open. Browsing tasks does not unarchive Sessions. diff --git a/docs/user/guide/schedule.zh.md b/docs/user/guide/schedule.zh.md index ebf7b24946..5e8401c404 100644 --- a/docs/user/guide/schedule.zh.md +++ b/docs/user/guide/schedule.zh.md @@ -38,7 +38,7 @@ 从侧栏打开自动化任务页面,可跨 Session 查看提醒,而不激活相应对话。按任务名称、指令或任务所属对话的 id 搜索,并用“任务状态”(“全部”“已开启”“已暂停”或“已结束”)过滤。各行按计划时间排列,最早的在前。每行显示任务名称和一行摘要:已暂停或已结束任务的状态、频率,以及已开启任务的“下次计划时间”与其本地时间和相对时间。 -一个 Session 的任务包括投递到该 Session 的任务(对于每次运行都新建对话的任务,以其最近一次运行为准),以及该 Session 的 Agent(智能体)创建或修改过的任务。空闲、未归档且至少有一个活动任务的 Session 行显示时钟标识;归档行该格留空,其实时状态只在悬浮卡片中显示。长时间悬停在带活动任务的 Session 行上时,最多列出其中两个任务及其频率,以及设备时区下的下次运行时间与相对时长。已打开 Session 的顶部在该 Session 有活动任务时显示仅图标的提醒时钟:只有一个任务时,它在右侧栏打开该任务的详情;否则列出这些任务,每行可打开任务详情或删除任务。 +Session 的页头时钟、行标识和悬浮列表只显示以该 Session 为固定投递目标的活动任务。此类任务投递到现有 Session,或复用首次投递时创建的 Session。空闲且未归档的 Session 行有此类任务时显示时钟标识。归档行的实时状态只在悬浮卡片中显示。长时间悬停在有此类任务的 Session 行上时,最多列出其中两个任务及其频率,以及设备时区下的下次运行时间与相对时长。已打开的 Session 有此类任务时,页头显示仅图标的提醒时钟。只有一个任务时,时钟在右侧栏打开任务详情。有多个任务时,时钟打开任务列表,每行可打开任务详情或删除任务。 选择任务打开其详情。“规则”显示任务名称、“下次运行”及其本地时间和相对时间(已暂停或已结束的任务显示其状态)、指令、“重复”和“执行位置”;投递到现有对话的任务,“执行位置”显示“当前关联对话”。详情底部显示“关联会话”;对于每次运行都新建对话的任务,显示“最近运行对话”。其按钮在 Session 可用且未归档时打开该对话,否则禁用;首次运行创建对话之前,该条目显示“待创建”。对于投递到现有对话的任务,“规则”会说明该对话已归档、不可用或仍在加载。即使对话无法打开,任务详情与删除操作仍然可用。浏览任务不会取消 Session 归档。 diff --git a/package.json b/package.json index a5c4860a84..044355f600 100644 --- a/package.json +++ b/package.json @@ -279,7 +279,7 @@ "jsdom": "29.1.1", "lefthook": "^2.1.12", "lightningcss": "^1.33.0", - "mdast-util-from-markdown": "^2.0.3", + "mdast-util-from-markdown": "^2.1.0", "mdast-util-gfm": "^3.1.0", "mermaid": "11.17.2", "micromark-extension-gfm": "^3.0.0", diff --git a/packages/account/deepseek-account/src/index.ts b/packages/account/deepseek-account/src/index.ts index bb6da3620c..54e724a933 100644 --- a/packages/account/deepseek-account/src/index.ts +++ b/packages/account/deepseek-account/src/index.ts @@ -809,7 +809,7 @@ export class DeepSeekAccount extends TypertRemoteService { signal.throwIfAborted() if (result.data.user != null) { try { attempt.initialProfile = { token: result.data.token, value: { status: 'ready', value: profile(result.data.user) } } } - catch { + catch (_invalidUser) { // Invalid optional user data falls back to current without discarding a valid authorization. } } diff --git a/packages/account/deepseek-account/src/logout.ts b/packages/account/deepseek-account/src/logout.ts index 7c165d3be6..8806d8c1bd 100644 --- a/packages/account/deepseek-account/src/logout.ts +++ b/packages/account/deepseek-account/src/logout.ts @@ -29,9 +29,10 @@ export async function revokeAccount(origin: string, token: string, policy: Logou try { await logoutAccount(origin, token, AbortSignal.any([signal, AbortSignal.timeout(policy.requestTimeoutMs)]), headers) - return - } catch { + } catch (_revokeFailed) { // HTTP, business, and transport failures consume one attempt without restoring credentials. + continue } + return } } diff --git a/packages/api/gateway/src/client/remote-stream.ts b/packages/api/gateway/src/client/remote-stream.ts index 66b0f6544b..51dbc9280a 100644 --- a/packages/api/gateway/src/client/remote-stream.ts +++ b/packages/api/gateway/src/client/remote-stream.ts @@ -224,7 +224,7 @@ async function closeRemoteStreamIterator( ): Promise { try { await iterator.return?.() - } catch { + } catch (_iteratorReturnFailed) { // The disposed logical stream has no remaining consumer for cancellation failures. } } diff --git a/packages/api/gateway/tests/gateway-stream.host.spec.ts b/packages/api/gateway/tests/gateway-stream.host.spec.ts index eca96aca95..244f82e383 100644 --- a/packages/api/gateway/tests/gateway-stream.host.spec.ts +++ b/packages/api/gateway/tests/gateway-stream.host.spec.ts @@ -146,7 +146,7 @@ class FeedService extends TypertRemoteService { async *swallow(signal: AbortSignal): RemoteStream { try { for await (const item of this.invocation().uplink()) yield item - } catch { + } catch (_uplinkFailed) { // The fixture keeps yielding after the rejected item on purpose. } yield 'swallowed' diff --git a/packages/api/job-controller/src/index.ts b/packages/api/job-controller/src/index.ts index d056e288e4..54356ab362 100644 --- a/packages/api/job-controller/src/index.ts +++ b/packages/api/job-controller/src/index.ts @@ -68,6 +68,9 @@ export class JobController extends TypertRemoteService { * Stream the jobs one session can see — its own plus every unowned job — * as whole-set frames: one on open, then one after each coalesced burst of * lifecycle commits. The stream has no natural end; the carrier closes it. + * + * The Gateway names this call's Session resource from `request.sessionId` + * through the session controller's resolver; no explicit reader is needed. * @param request - the session whose visible set to mirror. * @param signal - cancellation owned by the Remote stream carrier. * @returns the roster frames. diff --git a/packages/api/job-controller/tests/kill.host.spec.ts b/packages/api/job-controller/tests/kill.host.spec.ts index bfaf0c2141..92342ce840 100644 --- a/packages/api/job-controller/tests/kill.host.spec.ts +++ b/packages/api/job-controller/tests/kill.host.spec.ts @@ -7,11 +7,17 @@ import type { JobId, JobOutcome } from '@deepseek-ai/dsh-jobs' import LocalJobRegistry from '@deepseek-ai/dsh-jobs-local' import SessionStore from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' -import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' +import { remoteErrorOf, remoteMethods } from '@deepseek-ai/dsh-typert-protocol' +import type { InvocationDescriptor, InvocationParameterDescriptor } from '@deepseek-ai/dsh-typert-protocol' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' import { describe, expect, it } from 'vitest' +import { callResources } from '../../gateway/src/access.ts' +import { resolveSessionResource } from '../../session-controller/src/session-resource.ts' import { JobController } from '../src/index.ts' +/** The Typert registry {@link callResources} resolves against. */ +type Typert = Parameters[0] + function producer(label = 'sleep 60') { let settle!: (outcome: JobOutcome) => void const cancels: (string | undefined)[] = [] @@ -57,6 +63,18 @@ async function harness(): Promise<{ return { ctx, session, agent, controller: ctx.jobController } } +/** + * Install the Session Controller's own `session` resource default with the + * resolver it registers. Mounting the whole Session Controller would drag its + * entire dependency web into the job harness, while this registration is the + * one Host-side step that names the resource; the controller's own suite + * covers the rest of it. + * @param ctx - context holding the live Typert registry. + */ +function installSessionResolver(ctx: Context): void { + ctx.typert.resources.register('session', { resolve: resolveSessionResource }) +} + function failureCode(run: () => unknown): string { try { run() @@ -68,6 +86,87 @@ function failureCode(run: () => unknown): string { throw new Error('expected a RemoteError failure') } +/** + * The invocation the Gateway holds for one endpoint: these methods are direct + * and take only JSON arguments, so their wire parameters are the decorated + * ones in declaration order. + * @param wires - the method's JSON parameter wires, in order. + * @returns the invocation and parameters {@link callResources} reads. + */ +function invocationOf(wires: readonly string[]): Pick { + return { + invocation: { kind: 'direct' }, + parameters: wires.map((wire): InvocationParameterDescriptor => ({ name: wire, wire, source: 'json', codec: { mode: 'src-json' } })), + } +} + +/** + * The resources the Gateway resolves for one call: the readers the live + * Service declares, the registry they resolve against, and the call's named + * arguments. `list` and `follow` take their cancellation signal after the + * request, so the caller passes it as the trailing positional argument. + * @param service - the mounted Remote Service. + * @param typert - the registry the Gateway resolves against. + * @param method - Remote method name. + * @param wires - the method's JSON parameter wires, in order. + * @param args - named arguments, the request included, plus the cancellation signal. + * @returns the resolved resources, or `undefined` when they are invalid. + */ +function resourcesOf( + service: JobController, + typert: Typert, + method: string, + wires: readonly string[], + args: Readonly>, +): ReturnType { + const readers = remoteMethods(service).find(candidate => candidate.exportName === method || candidate.method === method)?.resources + return callResources(typert, readers, invocationOf(wires), args, NEVER) +} + +const NEVER = new AbortController().signal + +describe('JobController Remote Session resources', () => { + const SESSION = { kind: 'session' } as const + + it('names the Session of the request on the roster, the follow stream, and a kill', async () => { + // The production composition mounts the Session Controller beside this + // Service, so its default `session` resolver — not a reader on these + // methods — is the layer that names the resource. The assertions read the + // resource the Gateway resolves against, so losing that resolver here + // turns them global and fails them. + const { ctx, session, controller } = await harness() + installSessionResolver(ctx) + const jobId = 'bash-1' as JobId + const request = { sessionId: session.id, jobId } + expect(resourcesOf(controller, ctx.typert, 'list', ['request'], { request: { sessionId: session.id }, signal: NEVER })) + .toEqual([{ kind: SESSION.kind, id: session.id }]) + expect(resourcesOf(controller, ctx.typert, 'follow', ['request'], { request, signal: NEVER })) + .toEqual([{ kind: SESSION.kind, id: session.id }]) + expect(resourcesOf(controller, ctx.typert, 'kill', ['request'], { request })) + .toEqual([{ kind: SESSION.kind, id: session.id }]) + }) + + it('resolves those endpoints to the global resource without a resolver', async () => { + // The counterpart above: the endpoints declare no reader of their own, so + // omitting the Session Controller's resolver leaves every call global. + const { ctx, session, controller } = await harness() + const request = { sessionId: session.id, jobId: 'bash-1' as JobId } + for (const [method, wires] of [['list', ['request']], ['follow', ['request']], ['kill', ['request']]] as const) { + expect(resourcesOf(controller, ctx.typert, method, wires, method === 'kill' ? { request } : { request, signal: NEVER })) + .toEqual([{ kind: 'global' }]) + } + }) + + it('falls back to the global resource for a follow of an unowned job', async () => { + // An unowned job is observer-visible to any caller, so its request names + // no Session and the resolver has nothing to answer. + const { ctx, controller } = await harness() + installSessionResolver(ctx) + const args = { request: { jobId: 'bash-1' as JobId }, signal: NEVER } + expect(resourcesOf(controller, ctx.typert, 'follow', ['request'], args)).toEqual([{ kind: 'global' }]) + }) +}) + describe('JobController.kill', () => { it('kills an owned running job without claiming the terminal report', async () => { const { ctx, session, agent, controller } = await harness() diff --git a/packages/api/session-controller/src/index.ts b/packages/api/session-controller/src/index.ts index 5a8b178a6e..3fb061e585 100644 --- a/packages/api/session-controller/src/index.ts +++ b/packages/api/session-controller/src/index.ts @@ -13,7 +13,7 @@ import { canOpenNativePath, nativeFileManager, nativeFileApplications, openNativ import type { SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-session-projection-cache' import type { SessionObservation } from '@deepseek-ai/dsh-session-query' -import { Remote, RemoteError, TypertRemoteService, principalOf, type TypertResourceResolveInput } from '@deepseek-ai/dsh-typert-protocol' +import { Remote, RemoteError, TypertRemoteService, principalOf } from '@deepseek-ai/dsh-typert-protocol' import { canonicalClientTimeZone } from '@deepseek-ai/dsh-util-time' import { assertNever } from '@deepseek-ai/dsh-util-values' import type {} from '@deepseek-ai/dsh-api-remote-access' @@ -22,6 +22,7 @@ import { type ApiSessionAgentResult, } from './agent.ts' import { SessionCommandController, hasPromptContent } from './commands.ts' +import { resolveSessionResource } from './session-resource.ts' import { SessionControlController } from './control.ts' import { HistoryController } from './history/controller.ts' import { StateController } from './state/controller.ts' @@ -35,7 +36,6 @@ import { ArchivedSessionGate } from './archived-session-gate.ts' import type { ModelCatalog, SessionWorkspacePathApplication, - SessionAddress, SessionAttachmentRequest, SessionAttachmentValue, SessionCancelRequest, @@ -79,34 +79,6 @@ declare module '@deepseek-ai/cordis' { } } -/** - * Extract the Session resource from an ID or a history address. - * - * Registers as the `session` kind default, so it applies to every Remote method of - * every namespace: a top-level `sessionId` parameter, otherwise the first object - * parameter carrying `sessionId` or an `address`. A new request type whose first - * object parameter has an unrelated `address` field would be read as an address. - * @param input - validated wire arguments and their ordered parameter descriptions. - * @returns the named Session identity, otherwise the first object's Session identity or history address. - * @throws Error when the request object supplies both sessionId and address. - */ -function resolveSessionResource({ args, parameters }: TypertResourceResolveInput): SessionId | undefined { - const sessionParameter = parameters.find(parameter => parameter.name === 'sessionId' || parameter.wire === 'sessionId') - if (sessionParameter !== undefined) return args[sessionParameter.wire] as SessionId | undefined - for (const parameter of parameters) { - const value = args[parameter.wire] - if (typeof value !== 'object' || value === null || Array.isArray(value)) continue - const request = value as { readonly sessionId?: SessionId; readonly address?: SessionAddress } - const address = request.address - if (request.sessionId !== undefined && address !== undefined) { - throw new Error('Session resource request must not contain both sessionId and address') - } - return request.sessionId ?? (address === undefined ? undefined - : address.kind === 'session' ? address.sessionId : address.childSessionId) - } - return undefined -} - /** Session Controller deployment policy. */ export interface Config { /** Override platform desktop-opener detection. */ diff --git a/packages/api/session-controller/src/session-resource.ts b/packages/api/session-controller/src/session-resource.ts new file mode 100644 index 0000000000..70a6158874 --- /dev/null +++ b/packages/api/session-controller/src/session-resource.ts @@ -0,0 +1,38 @@ +/** + * The `session` resource kind's default identity extraction: the Session one + * Remote call names, read from its validated wire arguments. + * @module @deepseek-ai/dsh-api-session-controller/session-resource + */ + +import type { SessionId } from '@deepseek-ai/dsh-session' +import type { TypertResourceResolveInput } from '@deepseek-ai/dsh-typert-protocol' +import type { SessionAddress } from './types.ts' + +/** + * Extract the Session resource from an ID or a history address. + * + * Registers as the `session` kind default, so it applies to every Remote method of + * every namespace: a top-level `sessionId` parameter, otherwise the first object + * parameter carrying `sessionId` or an `address`. A new request type whose first + * object parameter has an unrelated `address` field would be read as an address. + * @param input - validated wire arguments and their ordered parameter descriptions. + * @returns the named Session identity, otherwise the first object's Session identity or history address. + * @throws Error when the request object supplies both sessionId and address. + */ +export function resolveSessionResource(input: TypertResourceResolveInput): SessionId | undefined { + const { args, parameters } = input + const sessionParameter = parameters.find(parameter => parameter.name === 'sessionId' || parameter.wire === 'sessionId') + if (sessionParameter !== undefined) return args[sessionParameter.wire] as SessionId | undefined + for (const parameter of parameters) { + const value = args[parameter.wire] + if (typeof value !== 'object' || value === null || Array.isArray(value)) continue + const request = value as { readonly sessionId?: SessionId; readonly address?: SessionAddress } + const address = request.address + if (request.sessionId !== undefined && address !== undefined) { + throw new Error('Session resource request must not contain both sessionId and address') + } + return request.sessionId ?? (address === undefined ? undefined + : address.kind === 'session' ? address.sessionId : address.childSessionId) + } + return undefined +} diff --git a/packages/api/session-controller/tsconfig.host.json b/packages/api/session-controller/tsconfig.host.json index 168fd5a0c7..c4011222a9 100644 --- a/packages/api/session-controller/tsconfig.host.json +++ b/packages/api/session-controller/tsconfig.host.json @@ -9,6 +9,7 @@ "src/index.ts", "src/types.ts", "src/remote-events.ts", + "src/session-resource.ts", "src/agent.ts", "src/assistant-stream.ts", "src/catalog.ts", diff --git a/packages/api/workspace-files/src/client/change-feed.ts b/packages/api/workspace-files/src/client/change-feed.ts index cf43b68b6c..115e0b4bb2 100644 --- a/packages/api/workspace-files/src/client/change-feed.ts +++ b/packages/api/workspace-files/src/client/change-feed.ts @@ -174,7 +174,7 @@ class SessionFeed { assertNever(frame) } } - } catch { + } catch (_streamEnded) { // A terminal stream failure or the Host's end: followers end quietly // below, and the metadata they hold stays the last known. } finally { diff --git a/packages/api/workspace-files/tests/changes.spec.ts b/packages/api/workspace-files/tests/changes.spec.ts index fcb1920393..a480a8a3bf 100644 --- a/packages/api/workspace-files/tests/changes.spec.ts +++ b/packages/api/workspace-files/tests/changes.spec.ts @@ -1,6 +1,7 @@ /** Target-scoped Host changes, fresh filesystem metadata, and watcher ownership. */ import { afterEach, beforeEach, describe, expect, it, onTestFailed, vi } from 'vitest' import type { Mock, MockInstance } from 'vitest' +import { watch as nativeWatch } from 'node:fs' import { mkdir, rename, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { performance } from 'node:perf_hooks' @@ -69,6 +70,25 @@ async function ready(stream: ReturnType): Promise { await expect(stream.next()).resolves.toEqual({ done: false, value: { kind: 'ready' } }) } +/** + * Block until this process's native directory watches deliver events. Chokidar + * reports `ready` once `fs.watch()` returns, but libuv on darwin builds the + * per-process FSEvents stream later on its CoreFoundation thread + * (`uv__fsevents_init` only signals that thread), so a mutation that lands + * before then is never reported. Closing a second directory handle runs + * `uv__fsevents_close`, whose `uv_sem_wait` returns only after + * `uv__fsevents_reschedule` rebuilt and started the stream with the remaining + * handles, so a watch registered before this call observes the next mutation. + * Any existing directory works because the stream is per process; Linux inotify + * and Windows `ReadDirectoryChangesW` are armed inside `fs.watch()`, so there + * this is an immediate open and close. The HMR config-watch spec waits the same + * way; should a libuv release drop the close-time wait, these cases regain the + * darwin loss rate rather than failing deterministically. + */ +function ensureNativeWatchLive(directory: string): void { + nativeWatch(directory).close() +} + /** Give disposal cases an independently unloadable service owner. */ async function ownedEndpoint() { let service: WorkspaceFiles | undefined @@ -448,6 +468,10 @@ describe('workspaceFiles.changes — backends and access', () => { const stream = open(service, path) mark('waiting-ready') await ready(stream) + // The rename below is this directory's only native event, so wait until the + // FSEvents stream can report it. + ensureNativeWatchLive(harness.outside) + mark('native-watch-armed') const pending = stream.next() mark('renaming') await rename(staging, path) @@ -479,6 +503,7 @@ describe('workspaceFiles.changes — backends and access', () => { cleanups.push(async () => { detach() }) const stream = open(service, harness.workspace) await ready(stream) + ensureNativeWatchLive(harness.workspace) const pending = stream.next() if (operation === 'remove') await rm(path) else await writeFile(path, 'after external mutation') diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index f0fecadd3b..24c97f03cc 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/README.i18n.yaml @@ -24,8 +24,8 @@ en: 65bf2834b81f87da zh: c864ac60a3005b99 /deepseek-ai-dsh-app-boot/use-this-package/profiles: - en: 781fe487a973ee6f - zh: e95188274f75f9ad + en: ba1c456bf22d8fc0 + zh: 018bd12bd56912e4 /deepseek-ai-dsh-app-boot/use-this-package/previewing-the-effective-configuration: en: 646a0ccdd7881ad1 zh: e3696acb1573dd7b @@ -36,14 +36,14 @@ en: 91d80c444ac0cfe5 zh: e7db496043528ffb /deepseek-ai-dsh-app-boot/use-this-package/startup-and-reload-failures: - en: dc13dfa1f79292e4 - zh: d51682ced7a18ac2 + en: 9b9e08c8638a975b + zh: 8a3f906c4d98cb89 /deepseek-ai-dsh-app-boot/understand-the-implementation: en: f4a2695cb4c8a570 zh: 89837235d2f376cf /deepseek-ai-dsh-app-boot/understand-the-implementation/design-notes: - en: 6eba01e24a2a68ab - zh: 64af424489087ec7 + en: 2943e0f4e90f2dde + zh: 1c752b58515153e5 /deepseek-ai-dsh-app-boot/understand-the-implementation/helper-behavior: en: 6fa850d1bb000d0e zh: aa83a40a9d3db295 diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index f480a5886d..2425e7aabf 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -64,7 +64,7 @@ Your machine-local preferences also live in the Harness home: - **`.env`** — your ordinary environment layers: the invoking directory's file outranks the Harness-home file, and both sit below the inherited environment. Variables that decide how the process starts (`PATH`, `DSH_*`, `XDG_*` and similar) are rejected from files: export them instead. The four proxy names (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY`) in any letter case and the DeepSeek endpoint names (`DEEPSEEK_BASE_URL`, `DEEPSEEK_SEARCH_BASE_URL`) in exactly that spelling are accepted from the Harness-home file only, never from the invoking directory's, which arrives with a clone. For a non-product bin that just wants one directory's `.env`, a missing file is fine and an unloadable one prints one labelled warning line. - **`cordis.patch.yml`** — your tweak layer, applied after every bundle layer (per-profile first, then the home-level file, which therefore outranks it): replace one entry's whole config (restating the fields you keep), insert new entries, or interpolate `!!js` expressions at boot. A patch naming an entry that does not exist prints a stderr warning; an empty or comments-only file fails boot — disable the layer with `[]` instead. -The enabled `dsh-hmr` plugin watches the profile manifest and both user patch files, re-reads the ordered bundle layers, and applies the [reload failure policy](#startup-and-reload-failures). [DSH HMR](../hmr/README.md) serializes these reloads with [Plugin Manager](../plugin-manager/README.md) configuration writes; package operations run outside its queue. The launcher does not install HMR or watchers; disabled or absent HMR means changes require restart. +The enabled `dsh-hmr` plugin watches the profile manifest, both user patch files, and every `--patch` overlay file, re-reads the ordered bundle layers, and applies the [reload failure policy](#startup-and-reload-failures). [DSH HMR](../hmr/README.md) serializes these reloads with [Plugin Manager](../plugin-manager/README.md) configuration writes; package operations run outside its queue. The launcher does not install HMR or watchers; disabled or absent HMR means changes require restart, except that a Config Editor save applies the current contents of every patch and overlay file. Inserted plugin names may be absolute filesystem paths, file URLs, or package specifiers. Patch loading converts absolute paths and patch-relative `./` or `../` paths to file URLs within `insert` rows and their nested groups; existing-entry name assertions and replacement `config` values remain literal. @@ -101,7 +101,7 @@ After the Loader settles, app-boot warns when only optional entries are inactive | Failure pattern | Optional entry at startup | Required entry at startup | Later configuration HMR | |---|---|---|---| -| Root config or required overlay is missing, unreadable, malformed, or contains invalid entries | Stop startup | Stop startup | Malformed or invalid live patches are rejected without changing the running configuration; a valid edit applies | +| Root config or required overlay is missing, unreadable, malformed, or contains invalid entries | Stop startup | Stop startup | Missing, malformed, or invalid live patches and overlays are rejected without changing the running configuration; a valid edit applies | | Module import fails or module evaluation throws | Warn; continue | Stop startup | Report the error; keep successful siblings; a corrected import can activate | | Plugin config schema validation fails | Warn; continue | Stop startup | A new entry stays inactive; an existing entry retains its prior instance and config; a valid correction applies | | Config `!!js` evaluation throws | Warn; continue | Stop startup | Report the error; keep successful siblings; a valid correction can activate | @@ -133,7 +133,7 @@ This section explains how the outcomes above are realized and points at the code ### Design notes - **Runtime version.** `getDshRuntimeVersion()` reads this package's manifest through a filesystem path, including the executable's virtual filesystem; missing or invalid versions fail rather than bypassing compatibility checks. -- **Profile launch data.** `ctx.profileContext` contains only profile locations, startup bundle names, parsed invocation overlays and the telemetry opt-out value. `readProfilePatches()` composes the supplied startup profile or reads current files at those locations; callers schedule and apply the result. +- **Profile launch data.** `ctx.profileContext` contains only profile locations, startup bundle names, absolute invocation overlay paths and the telemetry opt-out value. `readProfilePatches()` composes the supplied startup profile or reads current files at those locations, and always rereads the overlay files; callers schedule and apply the result. Plugin Manager listings and Config Editor writes call it with or without HMR, so they see current overlay contents and fail while an overlay file is missing or invalid. - **Process-local module resolution.** The launcher installs the runtime resolution on Node's internal ESM and CommonJS resolvers before profile rows mount. Node still owns exports, conditions, subpaths, module caches, and error codes; routed ESM failures report the original importer. Explicit CommonJS `paths` always retain native lookup, including paths inside profiles. - **Linked directories.** A profile link to an external directory admits its importers to peer-aware ancestor lookup, even without its own `package.json`. At each `D/node_modules` position, current `D/package.json` peer names present in the runtime table use the runtime package; other names use the physical candidate. A nearer physical package precedes a later peer declaration, and a peer position needs no physical `node_modules`. Installation-scope package directories are excluded from linked interception; overlapping roots do not change the importer's lookup order ([rule](../../../.agents/notes/implemented/architecture/2026-09-19-profile-resolution-lookup-order.md)). - **Package metadata.** `ctx.pluginPackages.packageOf` locates the owning package without loading code or requiring an exported `package.json`; a subpath selects its package without validating that file. The installed runtime resolution owns selection even for a miss. Low-level embedders that install the service without one retain native lookup. Display metadata uses the separate entry-aware reader described above. diff --git a/packages/boot/app-boot/README.zh.md b/packages/boot/app-boot/README.zh.md index 2a9c53a38e..8d2d4adf5b 100644 --- a/packages/boot/app-boot/README.zh.md +++ b/packages/boot/app-boot/README.zh.md @@ -64,7 +64,7 @@ profile 导入插件前,DSH 会将其声明的 DSH 版本要求与 `getDshRunt - **`.env`**——你的普通环境层:调用目录的文件优先于 harness home 的文件,两者都低于继承环境。在文件中设置的进程启动变量(如 `PATH`、`DSH_*`、`XDG_*`)会被拒绝:请改为导出这些变量。四个代理名(`HTTP_PROXY`、`HTTPS_PROXY`、`ALL_PROXY`、`NO_PROXY`,大小写不限)和 DeepSeek 端点变量名(`DEEPSEEK_BASE_URL`、`DEEPSEEK_SEARCH_BASE_URL`,须按此拼写)只从 harness home 的文件接受,绝不从调用目录的文件接受——后者随 clone 一起到来。对于只想加载某个目录 `.env` 的非产品 bin,文件缺失不影响启动,文件无法加载时输出一行带标签的警告。 - **`cordis.patch.yml`**——你的 tweak 层,应用在所有组合包层之后(先应用逐 profile 的文件,再应用 home 级文件,因此后者优先级更高):替换某个条目的整个配置(重述你要保留的字段)、插入新条目,或在启动时插值 `!!js` 表达式。patch 指定的条目不存在时输出 stderr 警告;空文件或仅含注释的文件会导致启动失败——如需禁用该层,请改用 `[]`。 -启用的 `dsh-hmr` 插件会监视 profile manifest 与两份用户 patch 文件,重新读取按顺序排列的组合包层,并应用[重载失败策略](#startup-and-reload-failures)。[DSH HMR](../hmr/README.zh.md) 将这些重载与[插件管理器](../plugin-manager/README.zh.md)的配置写入串行化;包操作在其队列之外执行。启动器不安装 HMR 或监视器;HMR 被禁用或不存在时,更改需要重启。 +启用的 `dsh-hmr` 插件会监视 profile manifest、两份用户 patch 文件与每个 `--patch` overlay 文件,重新读取按顺序排列的组合包层,并应用[重载失败策略](#startup-and-reload-failures)。[DSH HMR](../hmr/README.zh.md) 将这些重载与[插件管理器](../plugin-manager/README.zh.md)的配置写入串行化;包操作在其队列之外执行。启动器不安装 HMR 或监视器;HMR 被禁用或不存在时,更改需要重启;例外是 Config Editor 保存时会应用所有 patch 与 overlay 文件的当前内容。 插入条目的插件名可以是绝对文件系统路径、文件 URL 或包标识符。patch 加载会把 `insert` 条目及其嵌套分组中的绝对路径以及相对于 patch 文件的 `./` 或 `../` 路径转换为文件 URL;对已有条目名称的断言及替换用的 `config` 值保持原样。 @@ -101,7 +101,7 @@ Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如 | 失败模式 | Optional 条目启动时 | Required 条目启动时 | 后续配置 HMR | |---|---|---|---| -| 根配置或必需 overlay 缺失、不可读、格式错误,或包含无效条目 | 终止启动 | 终止启动 | 拒绝格式错误或无效的实时 patch,不改变运行中的配置;有效修改可以应用 | +| 根配置或必需 overlay 缺失、不可读、格式错误,或包含无效条目 | 终止启动 | 终止启动 | 拒绝缺失、格式错误或无效的实时 patch 与 overlay,不改变运行中的配置;有效修改可以应用 | | 模块 import 失败或模块求值抛出异常 | 警告;继续 | 终止启动 | 报告错误;保留成功的兄弟插件;修正 import 后可以激活 | | 插件配置 schema 校验失败 | 警告;继续 | 终止启动 | 新条目保持未激活;现有条目保留原实例与配置;有效修正可以应用 | | 配置 `!!js` 求值抛出异常 | 警告;继续 | 终止启动 | 报告错误;保留成功的兄弟插件;有效修正后可以激活 | @@ -133,7 +133,7 @@ Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如 ### 设计说明 - **运行时版本。** `getDshRuntimeVersion()` 通过文件系统路径读取本包清单,也支持可执行文件内的虚拟文件系统;版本缺失或无效时会失败,而不会绕过兼容性检查。 -- **Profile 启动数据。** `ctx.profileContext` 只包含 profile 位置、启动时组合包名称、已解析的调用级 overlay 与遥测退出值。`readProfilePatches()` 组合传入的启动 profile,或读取这些位置上的当前文件;调用方负责调度和应用结果。 +- **Profile 启动数据。** `ctx.profileContext` 只包含 profile 位置、启动时组合包名称、调用级 overlay 的绝对路径与遥测退出值。`readProfilePatches()` 组合传入的启动 profile,或读取这些位置上的当前文件,并且总是重新读取 overlay 文件;调用方负责调度和应用结果。插件管理器的列表与 Config Editor 的写入无论是否启用 HMR 都调用它,因此会读到当前 overlay 内容,并在 overlay 文件缺失或无效时失败。 - **进程内模块解析。** launcher 在挂载 profile 条目前,将 runtime resolution 安装到 Node 的 ESM 与 CommonJS 内部 resolver。exports、conditions、子路径、模块缓存和错误码仍由 Node 负责;路由后的 ESM 失败报告原始 importer。显式 CommonJS `paths` 始终保留原生查询,包括指向 profile 内的路径。 - **链接目录。** profile 链接到树外目录时,其下的 importer 参与逐层 peer 查询,即使目标没有自身的 `package.json`。在每个 `D/node_modules` 位置,当前 `D/package.json` 的 peer 包名若存在于运行时表,就使用运行时包;其他包名查询物理候选。更近的物理包先于后续 peer 声明,peer 位置无需物理 `node_modules`。installation 作用域包目录不参与 linked 拦截,重叠 root 不改变 importer 的查询顺序([规则](../../../.agents/notes/implemented/architecture/2026-09-19-profile-resolution-lookup-order.zh.md))。 - **包元数据。** `ctx.pluginPackages.packageOf` 定位所属包,不加载代码,也不要求导出 `package.json`;子路径选择其所属包,不校验该文件。安装 runtime resolution 后,即使查询未命中也以其选包规则为准。仅安装服务而不提供 runtime resolution 的底层嵌入方保留原生查询。展示元数据使用上文另述的入口感知读取器。 diff --git a/packages/boot/app-boot/src/index.ts b/packages/boot/app-boot/src/index.ts index 13b3ff792c..f92ff64d4f 100644 --- a/packages/boot/app-boot/src/index.ts +++ b/packages/boot/app-boot/src/index.ts @@ -918,7 +918,7 @@ export function installFailLoud( timer = setTimeout(resolve, FAIL_LOUD_RELEASE_TIMEOUT_MS) }), ]) - } catch { + } catch (_releaseFailed) { // The terminal release failed; the fatal exit below is the outcome that // matters, and no reporter runs after it. } diff --git a/packages/boot/app-boot/src/profile-context.ts b/packages/boot/app-boot/src/profile-context.ts index e2ebfad5ce..32e94426fa 100644 --- a/packages/boot/app-boot/src/profile-context.ts +++ b/packages/boot/app-boot/src/profile-context.ts @@ -1,7 +1,7 @@ /** Launcher-owned profile locations and composition inputs. */ import { join } from 'node:path' import { composeEntries, loadProfileDirectory, PROFILE_PATCH_FILENAME, type Profile } from './profile.ts' -import { loadOptionalPatches } from './index.ts' +import { loadOptionalPatches, loadOverlayPatches } from './index.ts' import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include' /** Application-owned package manager executable; environment applies only to package operations. */ @@ -23,8 +23,8 @@ export interface ProfileContext { readonly home: string /** Bundle packages used to start this process, before any persisted edits. */ readonly startedBundles: readonly string[] - /** Parsed command-line overlays, applied above profile and home patches. */ - readonly overlays: readonly PatchOptions[] + /** Absolute command-line overlay files in argv order, read on every composition and applied above profile and home patches. */ + readonly overlayPaths: readonly string[] /** Launch-time DSH_TELEMETRY_DISABLED value; any non-empty value opts out. */ readonly telemetryDisabledEnv: string | undefined } @@ -65,18 +65,19 @@ export function readBundlePatches(binName: string, context: ProfileContext, init return profile.layers.flatMap(layer => layer.patches) } -/** Read current bundle and user layers with the launch-time overlays. +/** Read current bundle, user, and command-line overlay layers. * @param binName Diagnostic prefix for malformed or missing configuration. * @param context Data supplied by the profile launcher. * @param initialProfile Already loaded startup profile; omitted reads the current files. * @returns Detached ordered patches; this function does not update the Loader. + * @throws When a present patch file or any overlay file is missing, unreadable, or not a patch list. */ export function readProfilePatches(binName: string, context: ProfileContext, initialProfile?: Profile): PatchOptions[] { const patches = structuredClone([ ...readBundlePatches(binName, context, initialProfile), ...(initialProfile?.patches ?? loadOptionalPatches(binName, context.patchPath) ?? []), ...(loadOptionalPatches(binName, join(context.home, PROFILE_PATCH_FILENAME)) ?? []), - ...context.overlays, + ...context.overlayPaths.flatMap(path => loadOverlayPatches(binName, path)), ]) const telemetryPatch = resolveTelemetryPatch(context.telemetryDisabledEnv, composeEntries([patches]).some(row => row.id === TELEMETRY_ROW_ID)) diff --git a/packages/boot/app-boot/tests/compatibility-preflight.spec.ts b/packages/boot/app-boot/tests/compatibility-preflight.spec.ts index 0fcf850d56..7b97e4c9a8 100644 --- a/packages/boot/app-boot/tests/compatibility-preflight.spec.ts +++ b/packages/boot/app-boot/tests/compatibility-preflight.spec.ts @@ -51,7 +51,7 @@ export function apply() { record('apply:${name}') } const profile: ProfileContext = { name: 'preflight', dir, patchPath: join(dir, 'cordis.patch.yml'), installAnchor: join(dir, 'package.json'), cwd: dir, home: dir, - startedBundles: [], overlays: [], telemetryDisabledEnv: undefined, + startedBundles: [], overlayPaths: [], telemetryDisabledEnv: undefined, } const configPath = join(dir, 'cordis.yml') writeFileSync(configPath, '[]\n') diff --git a/packages/boot/app-boot/tests/profile.spec.ts b/packages/boot/app-boot/tests/profile.spec.ts index 7122ff80f3..c935206adf 100644 --- a/packages/boot/app-boot/tests/profile.spec.ts +++ b/packages/boot/app-boot/tests/profile.spec.ts @@ -198,7 +198,7 @@ describe('resolveProfileDir', () => { }) }) -it('composes current files from profile data and retains launch overlay and telemetry precedence', () => { +it('composes current profile, home, and overlay files with telemetry precedence', () => { const home = tmp() const installAnchor = stageInstallation({ base: { patch: '- insert:\n - id: session-telemetry-otel\n name: telemetry\n' } }) const dir = resolveProfileDir('test', home) @@ -206,23 +206,26 @@ it('composes current files from profile data and retains launch overlay and tele const patchPath = join(dir, 'application.patch.yml') writeFileSync(patchPath, '- id: session-telemetry-otel\n disabled: true\n') writeFileSync(join(home, PROFILE_PATCH_FILENAME), '- id: session-telemetry-otel\n disabled: false\n') + const overlayPath = join(home, 'overlay.yml') + writeFileSync(overlayPath, '- id: session-telemetry-otel\n disabled: false\n') const context = { name: 'test', dir, patchPath, installAnchor, home, cwd: home, startedBundles: ['base'], - overlays: [{ id: 'session-telemetry-otel', disabled: false }], telemetryDisabledEnv: 'false', + overlayPaths: [overlayPath], telemetryDisabledEnv: 'false', } expect(composeEntries([readProfilePatches('test', context)])[0]?.disabled).toBe(true) const enabled = { ...context, telemetryDisabledEnv: undefined } expect(composeEntries([readProfilePatches('test', enabled)])[0]?.disabled).toBe(false) - const patches = readProfilePatches('test', enabled) - patches.at(-1)!.disabled = true - expect(context.overlays[0]?.disabled).toBe(false) + writeFileSync(overlayPath, '- id: session-telemetry-otel\n disabled: true\n') + expect(composeEntries([readProfilePatches('test', enabled)])[0]?.disabled).toBe(true) + rmSync(overlayPath) + expect(() => readProfilePatches('test', enabled)).toThrow(`failed to read overlay ${overlayPath}`) writeFileSync(join(home, PROFILE_PATCH_FILENAME), '- id: session-telemetry-otel\n disabled: true\n') - expect(composeEntries([readProfilePatches('test', { ...enabled, overlays: [] })])[0]?.disabled).toBe(true) + expect(composeEntries([readProfilePatches('test', { ...enabled, overlayPaths: [] })])[0]?.disabled).toBe(true) writeFileSync(join(home, PROFILE_PATCH_FILENAME), '[]\n') - expect(composeEntries([readProfilePatches('test', { ...enabled, overlays: [] })])[0]?.disabled).toBe(true) + expect(composeEntries([readProfilePatches('test', { ...enabled, overlayPaths: [] })])[0]?.disabled).toBe(true) writeFileSync(patchPath, '- id: session-telemetry-otel\n disabled: false\n') - expect(composeEntries([readProfilePatches('test', { ...enabled, overlays: [] })])[0]?.disabled).toBe(false) + expect(composeEntries([readProfilePatches('test', { ...enabled, overlayPaths: [] })])[0]?.disabled).toBe(false) }) describe('initProfile', () => { diff --git a/packages/boot/hmr/README.i18n.yaml b/packages/boot/hmr/README.i18n.yaml index 776c0d0fe7..6f0b6aab63 100644 --- a/packages/boot/hmr/README.i18n.yaml +++ b/packages/boot/hmr/README.i18n.yaml @@ -21,8 +21,8 @@ en: 11ef18c6d08f39f3 zh: 2911cdd03ff3747d /deepseek-ai-dsh-hmr/understand-the-implementation: - en: bd608f418630317f - zh: 053fa77a3fa571a9 + en: a1eede170f8754f0 + zh: dd2bfef9ad06ee3b /deepseek-ai-dsh-hmr/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 diff --git a/packages/boot/hmr/README.md b/packages/boot/hmr/README.md index 8d2270b4a1..a5399d6ac4 100644 --- a/packages/boot/hmr/README.md +++ b/packages/boot/hmr/README.md @@ -56,9 +56,9 @@ Profile recompositions run by HMR's profile watches and by Plugin Manager also r
Implementation internals — click to expand -`watchConfig()` registers an awaited configuration handler and watches only its target path and required parent directories; sibling files, including temporary writer locks, are excluded before native watcher creation. `runExclusive()` serializes configuration changes and Loader updates with automatic reloads and rejects nested transactions. Package installation and removal run outside this queue. HMR does not acquire the package writer lock; manifest notifications reload only when the ordered `dsh.profile.bundles` list changes. Profile and home patch changes also trigger recomposition. File events received during a configuration transaction are processed afterward. Include refreshes and profile reconciliation reach plugins through ordinary Loader entry updates; Loader commits volatile-only changes in place. +`watchConfig()` registers an awaited configuration handler and watches only its target path and required parent directories; sibling files, including temporary writer locks, are excluded before native watcher creation. `runExclusive()` serializes configuration changes and Loader updates with automatic reloads and rejects nested transactions. Package installation and removal run outside this queue. HMR does not acquire the package writer lock; manifest notifications reload only when the ordered `dsh.profile.bundles` list changes. Profile, home, and `--patch` overlay file changes also trigger recomposition. File events received during a configuration transaction are processed afterward. Include refreshes and profile reconciliation reach plugins through ordinary Loader entry updates; Loader commits volatile-only changes in place. -App-boot owns profile parsing and patch precedence. HMR reads the launcher’s data-only `profileContext`, registers the profile manifest and both user patch watches during initialization, and waits for application readiness before processing changes. Its disposal closes the watchers and cancels reloads waiting for startup. Configuration watchers start outside the active transaction context so later notifications can enter the queue. +App-boot owns profile parsing and patch precedence. HMR reads the launcher’s data-only `profileContext`, registers watches for the profile manifest, both user patches, and each `--patch` overlay during initialization, watching a file named under several spellings once, and waits for application readiness before processing changes. Its disposal closes the watchers and cancels reloads waiting for startup. Configuration watchers start outside the active transaction context so later notifications can enter the queue. `reconcileProfile()` is shared by HMR’s profile watches and Plugin Manager; callers hold `runExclusive()`. Config Editor recomposes through app-boot without replacing modules. App-boot prepares and preflights the generation before caches or running entries change. diff --git a/packages/boot/hmr/README.zh.md b/packages/boot/hmr/README.zh.md index 21044fe7d1..ceef662a95 100644 --- a/packages/boot/hmr/README.zh.md +++ b/packages/boot/hmr/README.zh.md @@ -56,9 +56,9 @@ HMR 的 profile 监听和 Plugin Manager 执行的 profile 重新组合,还会
实现细节——点击展开 -`watchConfig()` 注册会被等待的配置处理器,仅监听目标路径及必要的父目录;同级文件(包括临时写锁)在创建原生 watcher 前即被排除。`runExclusive()` 将配置变更、Loader 更新与自动重载串行化,并拒绝嵌套事务。包安装和删除在该队列之外执行。HMR 不获取包操作写锁;manifest 通知仅在有序的 `dsh.profile.bundles` 列表变化时触发重载。profile 与 home patch 变化也会触发重新组合。配置事务期间收到的文件事件在事务结束后处理。 Include 刷新和 profile 重载都通过普通的 Loader 条目更新到达插件;仅 volatile 变化由 Loader 就地提交。 +`watchConfig()` 注册会被等待的配置处理器,仅监听目标路径及必要的父目录;同级文件(包括临时写锁)在创建原生 watcher 前即被排除。`runExclusive()` 将配置变更、Loader 更新与自动重载串行化,并拒绝嵌套事务。包安装和删除在该队列之外执行。HMR 不获取包操作写锁;manifest 通知仅在有序的 `dsh.profile.bundles` 列表变化时触发重载。profile、home 与 `--patch` overlay 文件的变化也会触发重新组合。配置事务期间收到的文件事件在事务结束后处理。 Include 刷新和 profile 重载都通过普通的 Loader 条目更新到达插件;仅 volatile 变化由 Loader 就地提交。 -App-boot 负责 profile 解析和 patch 优先级规则。HMR 读取启动器提供的纯数据 `profileContext`,在初始化时注册 profile manifest 和两份用户 patch 的监听,并等待应用就绪后处理更改。销毁 HMR 时会关闭监听器并取消等待启动的重载。配置监听器在当前事务上下文之外启动,使后续通知可以进入队列。 +App-boot 负责 profile 解析和 patch 优先级规则。HMR 读取启动器提供的纯数据 `profileContext`,在初始化时注册 profile manifest、两份用户 patch 与每个 `--patch` overlay 的监听,以不同写法指向同一文件的路径只监听一次,并等待应用就绪后处理更改。销毁 HMR 时会关闭监听器并取消等待启动的重载。配置监听器在当前事务上下文之外启动,使后续通知可以进入队列。 `reconcileProfile()` 由 HMR 的 profile 监听和 Plugin Manager 共用;调用方持有 `runExclusive()`。Config Editor 通过 app-boot 重新组合,不替换模块。app-boot 在缓存或运行中条目发生变化前准备新一代组合并执行预检。 diff --git a/packages/boot/hmr/src/index.ts b/packages/boot/hmr/src/index.ts index 112732ca77..3d2ca35735 100644 --- a/packages/boot/hmr/src/index.ts +++ b/packages/boot/hmr/src/index.ts @@ -382,7 +382,14 @@ class Hmr extends Service { }) yield () => { unsubscribe(); started.resolve(false); return Promise.resolve() } const manifestPath = join(profile.dir, 'package.json') - const patchFiles = [profile.patchPath, join(profile.home, PROFILE_PATCH_FILENAME)] + // A file named by several layers or repeated `--patch` options, under any spelling, is watched and compared once. + const canonicalFiles = new Set() + const patchFiles = [profile.patchPath, join(profile.home, PROFILE_PATCH_FILENAME), ...profile.overlayPaths].filter((filename) => { + const canonical = canonicalPath(filename) + if (canonicalFiles.has(canonical)) return false + canonicalFiles.add(canonical) + return true + }) let lastInputs: string | undefined let lastBundles = JSON.stringify(profile.startedBundles) const refresh = async (manifestOnly: boolean): Promise => { diff --git a/packages/boot/hmr/tests/package-reload.spec.ts b/packages/boot/hmr/tests/package-reload.spec.ts index cb084b3deb..0e0d01d329 100644 --- a/packages/boot/hmr/tests/package-reload.spec.ts +++ b/packages/boot/hmr/tests/package-reload.spec.ts @@ -129,7 +129,7 @@ async function fixture(bundles = ['addon', 'other'], before?: (home: string, dir await before?.(home, dir) const profile: ProfileContext = { name: 'test', dir, patchPath: join(dir, 'cordis.patch.yml'), home, cwd: home, - installAnchor: join(home, 'package.json'), startedBundles: bundles, overlays: [], telemetryDisabledEnv: undefined, + installAnchor: join(home, 'package.json'), startedBundles: bundles, overlayPaths: [], telemetryDisabledEnv: undefined, } writeFileSync(profile.patchPath, JSON.stringify([{ insert: [ { id: 'timer', name: 'cordis:timer' }, diff --git a/packages/boot/hmr/tests/profile.spec.ts b/packages/boot/hmr/tests/profile.spec.ts index e096e6dbc5..7d92da88c3 100644 --- a/packages/boot/hmr/tests/profile.spec.ts +++ b/packages/boot/hmr/tests/profile.spec.ts @@ -1,5 +1,5 @@ /** Profile watches share HMR's queue and readiness barrier without waiting for package installation. */ -import { mkdtempSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, mkdirSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { pathToFileURL } from 'node:url' @@ -23,14 +23,32 @@ vi.mock('chokidar', async (original) => { } } }) -async function fixture(beforeWatch?: (profile: ProfileContext) => void) { +/** An overlay file's content, or the empty home patch named directly or through a linked directory. */ +type Overlay = string | { home: 'path' | 'link' } + +/** Write each overlay beside the home patch. */ +async function fixture(beforeWatch?: (profile: ProfileContext) => void, overlays: readonly Overlay[] = []) { const home = realpathSync(mkdtempSync(join(tmpdir(), 'hmr-profile-'))) const dir = join(home, 'profiles', 'test') initProfile(dir, []) writeFileSync(join(dir, 'cordis.yml'), '[]\n') + const homePatch = join(home, 'cordis.patch.yml') + const overlayPaths = overlays.map((overlay, index) => { + if (typeof overlay === 'string') { + const path = join(home, `overlay-${index}.yml`) + writeFileSync(path, overlay) + return path + } + writeFileSync(homePatch, '[]\n') + if (overlay.home === 'path') return homePatch + // A directory junction aliases the home patch on every platform without file-symlink privileges. + const alias = join(home, `alias-${index}`) + symlinkSync(home, alias, 'junction') + return join(alias, 'cordis.patch.yml') + }) const profile: ProfileContext = { name: 'test', dir, patchPath: join(dir, 'cordis.patch.yml'), home, cwd: home, - installAnchor: join(home, 'package.json'), startedBundles: [], overlays: [], telemetryDisabledEnv: undefined, + installAnchor: join(home, 'package.json'), startedBundles: [], overlayPaths, telemetryDisabledEnv: undefined, } const rows = [{ insert: [ { id: 'timer', name: 'cordis:timer' }, @@ -49,7 +67,8 @@ async function fixture(beforeWatch?: (profile: ProfileContext) => void) { host.loader.builtins.probe = { apply(ctx: Context, config: { value: string }) { ctx.provide('profileProbe', config.value) } } }) onTestFinished(async () => { await ctx.fiber.dispose(); rmSync(home, { recursive: true, force: true }) }) - const configWatches = watchers.slice(start, start + 3) + // Profile, home, and overlay patch watches precede the manifest watch. + const configWatches = watchers.slice(start, start + 3 + overlayPaths.length) const emit = (index: number, filename: string) => { configWatches[index]!.emit('change', filename) } const drain = () => ctx.hmr.runExclusive(async () => {}) return { ctx, profile, dir, home, emit, drain, commit: () => commit?.() } @@ -205,3 +224,50 @@ it('applies a patch edited after boot parsing but before watcher registration', await f.drain() expect(f.ctx.get('profileProbe')).toBe('edited-during-boot') }) + +it('applies edited --patch overlays above profile and home patches in argv order', async () => { + const f = await fixture(undefined, ['- id: probe\n config: { value: first }\n', '[]\n']) + f.commit() + expect(f.ctx.get('profileProbe')).toBe('first') + const [first, second] = f.profile.overlayPaths + writeFileSync(second!, '- id: probe\n config: { value: second }\n') + f.emit(3, second!) + await f.drain() + expect(f.ctx.get('profileProbe')).toBe('second') + writeFileSync(join(f.home, 'cordis.patch.yml'), '- id: probe\n config: { value: home }\n') + writeFileSync(second!, '[]\n') + f.emit(1, join(f.home, 'cordis.patch.yml')) + await f.drain() + expect(f.ctx.get('profileProbe')).toBe('first') + writeFileSync(first!, '[]\n') + f.emit(2, first!) + await f.drain() + expect(f.ctx.get('profileProbe')).toBe('home') +}) + +it('keeps the running configuration when an overlay file disappears and recovers when it returns', async () => { + const f = await fixture(undefined, ['- id: probe\n config: { value: overlay }\n']) + f.commit() + const warn = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warn.mockRestore() }) + const [overlay] = f.profile.overlayPaths + rmSync(overlay!) + f.emit(2, overlay!) + await f.drain() + expect(warn.mock.calls.some(([reason]) => reason instanceof Error && reason.message.includes(`failed to read overlay ${overlay}`))).toBe(true) + expect(f.ctx.get('profileProbe')).toBe('overlay') + writeFileSync(overlay!, '- id: probe\n config: { value: restored }\n') + f.emit(2, overlay!) + await f.drain() + expect(f.ctx.get('profileProbe')).toBe('restored') +}) + +it('watches a home patch also named by repeated or linked-directory overlays once', async () => { + const f = await fixture(undefined, [{ home: 'path' }, { home: 'path' }, { home: 'link' }]) + f.commit() + const homePatch = join(f.home, 'cordis.patch.yml') + writeFileSync(homePatch, '- id: probe\n config: { value: home }\n') + f.emit(1, homePatch) + await f.drain() + expect(f.ctx.get('profileProbe')).toBe('home') +}) diff --git a/packages/boot/plugin-manager/src/registry.ts b/packages/boot/plugin-manager/src/registry.ts index 92f67daab7..2cad202b95 100644 --- a/packages/boot/plugin-manager/src/registry.ts +++ b/packages/boot/plugin-manager/src/registry.ts @@ -28,7 +28,7 @@ export const REGISTRY_URL = /^https?:\/\/\S+$/ export function normalizeRegistry(url: string): string { let parsed: URL | undefined try { parsed = new URL(url) } - catch { /* named below: only an http(s) URL is a registry */ } + catch (_invalidUrl) { /* `parsed` stays undefined and the check below throws the registry error */ } if (parsed === undefined || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) { throw new Error(`a registry must be an http(s) URL: ${url}`) } diff --git a/packages/boot/plugin-manager/tests/bundle-detail.spec.ts b/packages/boot/plugin-manager/tests/bundle-detail.spec.ts index 732f08e6aa..8aa162e5f3 100644 --- a/packages/boot/plugin-manager/tests/bundle-detail.spec.ts +++ b/packages/boot/plugin-manager/tests/bundle-detail.spec.ts @@ -63,7 +63,7 @@ async function fixture(config: Config = {}) { writeFileSync(join(dir, 'cordis.yml'), '[]\n') const profile: ProfileContext = { name: 'test', startedBundles: loadProfileDirectory('test', dir, join(home, 'package.json')).layers.map(layer => layer.packageName), - dir, patchPath: join(dir, 'cordis.patch.yml'), installAnchor: join(home, 'package.json'), cwd: home, home, overlays: [], telemetryDisabledEnv: undefined, + dir, patchPath: join(dir, 'cordis.patch.yml'), installAnchor: join(home, 'package.json'), cwd: home, home, overlayPaths: [], telemetryDisabledEnv: undefined, } const ctx = await boot('test', join(dir, 'cordis.yml'), readProfilePatches('test', profile), (root) => { owner = root diff --git a/packages/boot/plugin-manager/tests/manager.spec.ts b/packages/boot/plugin-manager/tests/manager.spec.ts index 6ab1cf8029..b36e4ae14f 100644 --- a/packages/boot/plugin-manager/tests/manager.spec.ts +++ b/packages/boot/plugin-manager/tests/manager.spec.ts @@ -63,13 +63,14 @@ async function fixture(reload: 'live' | 'startup' = 'live', overlay = false, pre writeFileSync(join(dir, 'package.json'), JSON.stringify(manifest)) writeFileSync(join(dir, 'cordis.yml'), '[]\n') prepareFiles?.(dir) - const overlays: PatchOptions[] = overlay ? [{ id: 'managed', disabled: true }] : [] + const overlayPath = join(home, 'overlay.patch.yml') + writeFileSync(overlayPath, JSON.stringify(overlay ? [{ id: 'managed', disabled: true }] : [])) const profile: ProfileContext = { name: 'test', ...(packageManager === undefined ? {} : { packageManager }), startedBundles: loadProfileDirectory('test', dir, anchor).layers.map(layer => layer.packageName), dir, patchPath: join(dir, 'cordis.patch.yml'), installAnchor: anchor, cwd: home, home, - overlays, telemetryDisabledEnv: undefined, + overlayPaths: [overlayPath], telemetryDisabledEnv: undefined, } const ctx = await boot('test', join(dir, 'cordis.yml'), readProfilePatches('test', profile), (ctx) => { owner = ctx @@ -90,7 +91,7 @@ async function fixture(reload: 'live' | 'startup' = 'live', overlay = false, pre stopHmr = () => owner.dispose() await ctx.hmr.runExclusive(async () => {}) } - return { ctx, dir, manager: ctx.pluginManager, bundle, profile, stopHmr, overlays, connection, gitConnection } + return { ctx, dir, manager: ctx.pluginManager, bundle, profile, stopHmr, overlayPath, connection, gitConnection } } it.each(['live', 'startup'] as const)('refuses an unsupported bundle before saving or applying it with %s reload', async (reload) => { @@ -736,6 +737,15 @@ it('reports an overlay overriding a saved plugin toggle', async () => { expect(await manager.setPluginEnabled(id, true)).toMatchObject({ changed: false, application: 'overridden' }) }) +it('lists plugins from current overlay files in a startup-only profile', async () => { + const { manager, overlayPath } = await fixture('startup') + const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId + rmSync(overlayPath) + await expect(manager.listPlugins()).rejects.toThrow(`failed to read overlay ${overlayPath}`) + writeFileSync(overlayPath, '[]\n') + expect((await manager.listPlugins()).some(row => row.entryId === id)).toBe(true) +}) + it('saves startup-only toggles and refuses removal of currently used packages', async () => { const { manager } = await fixture('startup') const id = (await manager.listPlugins()).find(row => row.patchId === 'managed')!.entryId @@ -1463,9 +1473,10 @@ it('omits installation-owned plain packages from the bundle inventory', async () }) it('does not delete a bundle retained by a higher-priority overlay', async () => { - const { ctx, manager, overlays, dir } = await fixture() + const { ctx, manager, overlayPath, dir } = await fixture() const entry = [...ctx.loader.entries()].find(row => row.id === 'include:managed')! - overlays.push({ insert: [{ ...entry.options }] }) + const retained: PatchOptions[] = [{ insert: [{ ...entry.options }] }] + writeFileSync(overlayPath, JSON.stringify(retained)) const remove = vi.spyOn(operations, 'runProfilePnpm') onTestFinished(() => { remove.mockRestore() }) expect(await manager.removeBundle('extra')).toMatchObject({ changed: true, application: 'failed', error: { code: 'bundle-in-use' } }) diff --git a/packages/boot/plugin-manager/tests/operations-process.spec.ts b/packages/boot/plugin-manager/tests/operations-process.spec.ts index e040b23558..db20674cca 100644 --- a/packages/boot/plugin-manager/tests/operations-process.spec.ts +++ b/packages/boot/plugin-manager/tests/operations-process.spec.ts @@ -86,7 +86,7 @@ function fixture(child: string, descendant: string) { writeFileSync(stopFile, '') if (existsSync(pidFile)) { const pid = Number(readFileSync(pidFile, 'utf8')) - try { process.kill(pid, 'SIGKILL') } catch { /* the descendant exited with its own timer */ } + try { process.kill(pid, 'SIGKILL') } catch (_alreadyExited) { /* The descendant exited on its own timer, so there is nothing left to kill. */ } await awaitGone(pid) } rmSync(home, { recursive: true, force: true }) @@ -150,7 +150,7 @@ it('waits for a run recorded by an exited operation before starting its own', as stdio: 'ignore', }) onTestFinished(async () => { - try { orphan.kill('SIGKILL') } catch { /* the recorded run already exited */ } + try { orphan.kill('SIGKILL') } catch (_alreadyExited) { /* The recorded run already exited, so there is nothing left to kill. */ } await awaitGone(orphan.pid as number) }) const dir = join(context.home, 'profiles', 'test') diff --git a/packages/boot/plugin-manager/tests/package-reload.spec.ts b/packages/boot/plugin-manager/tests/package-reload.spec.ts index b5569a6229..0b63af8382 100644 --- a/packages/boot/plugin-manager/tests/package-reload.spec.ts +++ b/packages/boot/plugin-manager/tests/package-reload.spec.ts @@ -123,7 +123,7 @@ export function apply(ctx) { const loaded = loadProfileDirectory('test', dir, installAnchor) const profile: ProfileContext = { name: 'test', dir, patchPath: join(dir, 'cordis.patch.yml'), installAnchor, cwd: home, home, - startedBundles: loaded.layers.map(layer => layer.packageName), overlays: [], telemetryDisabledEnv: undefined, + startedBundles: loaded.layers.map(layer => layer.packageName), overlayPaths: [], telemetryDisabledEnv: undefined, } const resolution = await createRuntimeResolution({ installAnchor, profile: loaded, home }) const trace: string[] = [] diff --git a/packages/boot/plugin-manager/tests/patch.spec.ts b/packages/boot/plugin-manager/tests/patch.spec.ts index 9580da1e52..34538377c4 100644 --- a/packages/boot/plugin-manager/tests/patch.spec.ts +++ b/packages/boot/plugin-manager/tests/patch.spec.ts @@ -23,7 +23,7 @@ async function fixture(text?: string, rows: object[] = []): Promise { diff --git a/packages/boot/plugin-market/src/repository-cache.ts b/packages/boot/plugin-market/src/repository-cache.ts index 4391646731..4db6239390 100644 --- a/packages/boot/plugin-market/src/repository-cache.ts +++ b/packages/boot/plugin-market/src/repository-cache.ts @@ -6,7 +6,7 @@ */ import { createHash } from 'node:crypto' import { addAbortListener } from 'node:events' -import { existsSync } from 'node:fs' +import { existsSync, type Dirent } from 'node:fs' import { mkdir, mkdtemp, readdir, rename, rm, stat, utimes } from 'node:fs/promises' import { join } from 'node:path' import { execa } from 'execa' @@ -392,17 +392,14 @@ export class RepositoryCache { const now = Date.now() const entries: { path: string; size: number; used: number }[] = [] for (const entry of await readdir(this.options.dir, { withFileTypes: true })) { - const path = join(this.options.dir, entry.name) + let measured: { path: string; size: number; used: number } | undefined try { - const used = (await stat(path)).mtimeMs - if (entry.name.startsWith(STAGING_PREFIX)) { - if (now - used > this.options.timeoutMs) await rm(path, { recursive: true, force: true }) - } else if (entry.isDirectory()) { - entries.push({ path, size: await sizeOf(path), used }) - } - } catch (_removed) { - // Another operation deleted the directory while it was measured; it no longer counts. + measured = await this.measure(join(this.options.dir, entry.name), entry, now) + } catch (_unmeasurable) { + // Usually another operation deleted the entry while it was measured. An entry that cannot be measured or + // removed stays out of this pass, which leaves it on disk for the next eviction to retry. } + if (measured !== undefined) entries.push(measured) } let total = entries.reduce((sum, entry) => sum + entry.size, 0) // The repository in use goes last: it is deleted only when it alone exceeds the cache, after its operation ends. @@ -414,6 +411,19 @@ export class RepositoryCache { } } + /** + * Measure one cache entry for eviction, deleting a staging directory older than the Git deadline. + * @returns the repository's size and last use, or `undefined` for a staging directory or a non-directory. + */ + private async measure(path: string, entry: Dirent, now: number): Promise<{ path: string; size: number; used: number } | undefined> { + const used = (await stat(path)).mtimeMs + if (entry.name.startsWith(STAGING_PREFIX)) { + if (now - used > this.options.timeoutMs) await rm(path, { recursive: true, force: true }) + return undefined + } + return entry.isDirectory() ? { path, size: await sizeOf(path), used } : undefined + } + /** * The regular files directly below a tree path, or the file at a path, with their blob ids; listing reads only trees, * so it fetches no file contents. diff --git a/packages/boot/plugin-market/tests/configuration.spec.ts b/packages/boot/plugin-market/tests/configuration.spec.ts index 321fff1e1b..3c26936795 100644 --- a/packages/boot/plugin-market/tests/configuration.spec.ts +++ b/packages/boot/plugin-market/tests/configuration.spec.ts @@ -30,7 +30,7 @@ it('saves index sources without remounting, announces them, and restores them at writeFileSync(join(dir, 'cordis.yml'), '[]\n') const profile: ProfileContext = { name: 'test', startedBundles: ['test-bundle'], dir, patchPath: join(dir, 'cordis.patch.yml'), - installAnchor: join(home, 'package.json'), cwd: home, home, overlays: [], telemetryDisabledEnv: undefined, + installAnchor: join(home, 'package.json'), cwd: home, home, overlayPaths: [], telemetryDisabledEnv: undefined, } const start = () => boot('test', join(dir, 'cordis.yml'), readProfilePatches('test', profile), (root) => { root.provide('profileContext', profile) @@ -99,7 +99,7 @@ it('reads a market entry detail document and serves its images through the compo writeFileSync(join(dir, 'cordis.yml'), '- name: cordis:connection\n') const profile: ProfileContext = { name: 'test', startedBundles: ['test-bundle'], dir, patchPath: join(dir, 'cordis.patch.yml'), - installAnchor: join(home, 'package.json'), cwd: home, home, overlays: [], telemetryDisabledEnv: undefined, + installAnchor: join(home, 'package.json'), cwd: home, home, overlayPaths: [], telemetryDisabledEnv: undefined, } ctx = await boot('test', join(dir, 'cordis.yml'), readProfilePatches('test', profile), (root) => { root.provide('profileContext', profile) diff --git a/packages/boot/plugin-market/tests/detail-remote.spec.ts b/packages/boot/plugin-market/tests/detail-remote.spec.ts index ddcf9d1333..86bbcadf94 100644 --- a/packages/boot/plugin-market/tests/detail-remote.spec.ts +++ b/packages/boot/plugin-market/tests/detail-remote.spec.ts @@ -79,7 +79,7 @@ async function mount(options: { profile?: boolean; connection?: boolean } = {}) if (options.profile === true) { ctx.provide('profileContext', { name: 'test', startedBundles: [], dir: join(home, 'profile'), patchPath: join(home, 'profile', 'cordis.patch.yml'), - installAnchor: join(home, 'package.json'), cwd: home, home, overlays: [], telemetryDisabledEnv: undefined, + installAnchor: join(home, 'package.json'), cwd: home, home, overlayPaths: [], telemetryDisabledEnv: undefined, }) } const routes = new Map Promise>() diff --git a/packages/bundle/web-app/README.i18n.yaml b/packages/bundle/web-app/README.i18n.yaml index de0886efaa..ed254d7226 100644 --- a/packages/bundle/web-app/README.i18n.yaml +++ b/packages/bundle/web-app/README.i18n.yaml @@ -30,8 +30,8 @@ en: df205a26b6d49168 zh: e46ed7cf9e06248a /deepseek-ai-dsh-web-app/use-this-package/per-session-agent-setup: - en: 1f16cd1737256729 - zh: 1d24cd133933ad9e + en: 23cd05a35a675076 + zh: 6f32ef8a4a6a2c4d /deepseek-ai-dsh-web-app/understand-the-implementation: en: 567cf3afa68e6b68 zh: f065cdb56c28d4e6 diff --git a/packages/bundle/web-app/README.md b/packages/bundle/web-app/README.md index 9fdb2d8b51..1d8bb92a3c 100644 --- a/packages/bundle/web-app/README.md +++ b/packages/bundle/web-app/README.md @@ -96,7 +96,7 @@ When you launch `dsh --profile web` over SSH, the URL line still prints but the Each browser session selects a shipped preset (`standard` by default). The Agent presets settings page changes the default and edits preset child plugins; saves persist in `$DSH_HOME/profiles/web/cordis.patch.yml`. Standard and Creator enable the plugin-management tool only when the Host provides an editable profile. -Standard and Creator include the `dsh-doc` skill for questions about DSH and requested plugin or preset work. It guides the agent to the installed version's documentation and source. See [Model Experience](#model-experience) for loading and context effects. +Both modes expose read-only runtime inspection through `cordis_inspect`; see [its context effects](../../extensions/tool-cordis/README.md#model-experience). Standard and Creator include the `dsh-doc` skill for questions about DSH and requested plugin or preset work. It guides the agent to the installed version's documentation and source. See [Model Experience](#model-experience) for loading and context effects. The packaged skill uses the custom skill root: a same-named project skill overrides it, and it overrides same-named user skills. One catalog entry wins without an error; see [skill-root priority](../../skill/skill-filesystem/README.md). diff --git a/packages/bundle/web-app/README.zh.md b/packages/bundle/web-app/README.zh.md index 2a617e9f52..ffc1eed63d 100644 --- a/packages/bundle/web-app/README.zh.md +++ b/packages/bundle/web-app/README.zh.md @@ -96,7 +96,7 @@ dsh --profile web --no-open --host "$(hostname -i | awk '{print $1}')" --public- 每个浏览器会话选择一个随发行版交付的 preset(默认 `standard`)。Agent 预设设置页可更改默认项并编辑预设的子插件;保存结果持久化到 `$DSH_HOME/profiles/web/cordis.patch.yml`。只有 Host 提供可编辑的 profile 时,标准模式和 Creator 才会启用插件管理工具。 -标准模式和创造模式包含 `dsh-doc` skill,用于 DSH 相关问题以及你要求的插件或预设工作。该 skill 引导 agent 查阅已安装版本的文档和源码。加载方式及其对上下文的影响参见[模型体验](#model-experience)。 +两种模式均通过 `cordis_inspect` 提供只读运行时检查;参见[其上下文影响](../../extensions/tool-cordis/README.zh.md#model-experience)。标准模式和创造模式包含 `dsh-doc` skill,用于 DSH 相关问题以及你要求的插件或预设工作。该 skill 引导 agent 查阅已安装版本的文档和源码。加载方式及其对上下文的影响参见[模型体验](#model-experience)。 打包的 skill 使用自定义 skill 根目录:同名的项目 skill 会覆盖打包的 skill,打包的 skill 又会覆盖同名的用户 skill。skill 目录中只保留优先级最高的一个条目,不会报错;参见 [skill 根目录优先级](../../skill/skill-filesystem/README.zh.md)。 diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index 33d4db4333..810f2cb6f5 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -435,6 +435,11 @@ - id: ui-schedule name: '@deepseek-ai/dsh-client-ui-schedule' + # Session panel: the header toggle and the floating panel over the main + # Conversation body, with the Environment section other plugins extend. + - id: ui-session-panel + name: '@deepseek-ai/dsh-client-ui-session-panel' + # Goal surface: GoalBar in the input dock over the goal session projection. - id: ui-goal name: '@deepseek-ai/dsh-client-ui-goal' diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index 73efcb5d84..8ad0dbefe9 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -109,6 +109,7 @@ "@deepseek-ai/dsh-client-ui-reference": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-schedule": "workspace:*", + "@deepseek-ai/dsh-client-ui-session-panel": "workspace:*", "@deepseek-ai/dsh-client-ui-secret-mask": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", diff --git a/packages/bundle/web-app/presets/standard.patch.yml b/packages/bundle/web-app/presets/standard.patch.yml index a3532d0f3a..b47e613917 100644 --- a/packages/bundle/web-app/presets/standard.patch.yml +++ b/packages/bundle/web-app/presets/standard.patch.yml @@ -125,6 +125,8 @@ config: fetch: true searchTimeoutMs: 60000 + - id: tool-cordis + name: '@deepseek-ai/dsh-tool-cordis' - id: present name: '@deepseek-ai/dsh-tool-present' - id: tool-office diff --git a/packages/bundle/web-app/tests/browser-defaults.spec.ts b/packages/bundle/web-app/tests/browser-defaults.spec.ts index 73ee9b1a82..1aef765ddf 100644 --- a/packages/bundle/web-app/tests/browser-defaults.spec.ts +++ b/packages/bundle/web-app/tests/browser-defaults.spec.ts @@ -26,7 +26,7 @@ it.each([ if (profile !== undefined) { ctx.provide('profileContext', { name: profile, dir: '/profile', patchPath: '/profile/cordis.patch.yml', installAnchor: '/profile/package.json', - cwd: '/workspace', home: '/home', startedBundles: [], overlays: [], telemetryDisabledEnv: undefined, + cwd: '/workspace', home: '/home', startedBundles: [], overlayPaths: [], telemetryDisabledEnv: undefined, }) } ctx.baseUrl = 'file:///' diff --git a/packages/bundle/web-app/tests/desktop-office.spec.ts b/packages/bundle/web-app/tests/desktop-office.spec.ts index 33bdcd81da..b6b2d23559 100644 --- a/packages/bundle/web-app/tests/desktop-office.spec.ts +++ b/packages/bundle/web-app/tests/desktop-office.spec.ts @@ -71,7 +71,7 @@ async function boot(profile: string, primaryRuntime: (root: string) => string | onTestFinished(() => ctx.fiber.dispose()) ctx.provide('profileContext', { name: profile, dir: '/profile', patchPath: '/profile/cordis.patch.yml', installAnchor: join(root, 'package.json'), - cwd: workspace, home: '/home', startedBundles: [], overlays: [], telemetryDisabledEnv: undefined, + cwd: workspace, home: '/home', startedBundles: [], overlayPaths: [], telemetryDisabledEnv: undefined, }) ctx.provide('dshHomePath', dshHomePath) provideWorkingDirectoryFixture(ctx, workspace) diff --git a/packages/bundle/web-app/tests/product-analytics.spec.ts b/packages/bundle/web-app/tests/product-analytics.spec.ts index d9bf9f31dd..1531aaecad 100644 --- a/packages/bundle/web-app/tests/product-analytics.spec.ts +++ b/packages/bundle/web-app/tests/product-analytics.spec.ts @@ -26,7 +26,7 @@ it.each(['desktop', 'web'])('limits collection and its shutdown to the Desktop l onTestFinished(() => ctx.fiber.dispose()) ctx.provide('profileContext', { name: profile, dir: '/profile', patchPath: '/profile/cordis.patch.yml', installAnchor: '/profile/package.json', - cwd: '/workspace', home: '/home', startedBundles: [], overlays: [], telemetryDisabledEnv: undefined, + cwd: '/workspace', home: '/home', startedBundles: [], overlayPaths: [], telemetryDisabledEnv: undefined, }) const identity = vi.fn().mockResolvedValue(undefined) ctx.provide('deepseekAccount', { getDeviceIdentity: identity } as never) diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml index 0e4d3960bb..3cb0445b68 100644 --- a/packages/client/README.i18n.yaml +++ b/packages/client/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /client-web-gui-browser-half/packages: - en: e6b93119ee411a50 - zh: a9ed12dd8cc8864a + en: 77ed389434202e77 + zh: b82d32cf95253760 /client-web-gui-browser-half/related-documentation: en: d1d506e68fab7333 zh: 1a90fe6f3f8f24a9 diff --git a/packages/client/README.md b/packages/client/README.md index 20f96c17cc..6f655cfb5f 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -69,6 +69,7 @@ The kernel packages boot and serve the page; the UI feature packages present it. | [`ui-subagent/`](ui-subagent/README.md) | Provides subagent navigation, child transcript states, and inline references | — | | [`ui-jobs/`](ui-jobs/README.md) | Lists this session's background jobs with on-demand streaming record panels | — | | [`ui-schedule/`](ui-schedule/README.md) | Provides the sidebar Automation tasks page and right Sidebar task tab, which create, edit, run, pause, resume, and delete Host scheduled tasks, plus the Session header clock and row mark | — | +| [`ui-session-panel/`](ui-session-panel/README.md) | Adds the Session header toggle and the floating Session panel whose sections plugins register, with the Environment section | — | | [`ui-model-selection/`](ui-model-selection/README.md) | Provides model selection in conversation surfaces | — | | [`ui-permission-presets/`](ui-permission-presets/README.md) | Configures default permissions and switches the current session's access | — | | [`ui-plan/`](ui-plan/README.md) | Presents active plan-mode status and its exit control | — | diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md index ca1c6018d0..9ce1181967 100644 --- a/packages/client/README.zh.md +++ b/packages/client/README.zh.md @@ -69,6 +69,7 @@ kind: "package-group" | [`ui-subagent/`](ui-subagent/README.zh.md) | 提供 subagent 导航、子级 transcript(文本记录)状态与内联引用 | — | | [`ui-jobs/`](ui-jobs/README.zh.md) | 列出本会话的后台任务,并提供按需展开的流式输出面板 | — | | [`ui-schedule/`](ui-schedule/README.zh.md) | 提供侧栏“自动化任务”页面与右侧栏任务页签,用于创建、编辑、立即运行、暂停、恢复和删除宿主的计划任务,并提供 Session 顶部时钟与行标记 | — | +| [`ui-session-panel/`](ui-session-panel/README.zh.md) | 提供会话标题栏开关与悬浮会话面板,分栏由插件注册,并内置「环境」分栏 | — | | [`ui-model-selection/`](ui-model-selection/README.zh.md) | 在对话界面中提供模型选择 | — | | [`ui-permission-presets/`](ui-permission-presets/README.zh.md) | 配置默认权限并切换当前会话的访问模式 | — | | [`ui-plan/`](ui-plan/README.zh.md) | 展示生效中的 plan mode 状态及其退出控件 | — | diff --git a/packages/client/modules/src/index.ts b/packages/client/modules/src/index.ts index 52fa047650..4581333515 100644 --- a/packages/client/modules/src/index.ts +++ b/packages/client/modules/src/index.ts @@ -469,7 +469,7 @@ function buildComboSourceMap( if (sourceMap !== undefined) { try { section = comboSectionMap(resource, sourceMap) - } catch { + } catch (_malformedSourceMap) { // An invalid authored source URL is a malformed map, so the generated // bundle remains debuggable through the same identity fallback. } @@ -974,15 +974,16 @@ export class ClientModuleRegistry extends Service { while (true) { const candidate = join(dir, 'package.json') if (existsSync(candidate)) { + let name: unknown try { - const name = (JSON.parse(readFileSync(candidate, 'utf8')) as { name?: unknown }).name - if (typeof name === 'string' && (expectedPackageName === undefined || name === expectedPackageName)) { - return { path: candidate, packageName: name } - } - } catch { + name = (JSON.parse(readFileSync(candidate, 'utf8')) as { name?: unknown }).name + } catch (_unreadableManifest) { // An unreadable or malformed intermediate manifest cannot own the // module; keep walking toward the declaring package root. } + if (typeof name === 'string' && (expectedPackageName === undefined || name === expectedPackageName)) { + return { path: candidate, packageName: name } + } } const parent = dirname(dir) if (parent === dir) break diff --git a/packages/client/store/src/index.ts b/packages/client/store/src/index.ts index 09414e95e6..32c0acdff8 100644 --- a/packages/client/store/src/index.ts +++ b/packages/client/store/src/index.ts @@ -239,7 +239,7 @@ export function defineStore>( if (persistKey === undefined || typeof localStorage === 'undefined') return try { localStorage.removeItem(persistKey) - } catch { + } catch (_storageUnavailable) { // Storage failures (private mode, quota teardown races) only skip // cleanup — the same non-fatal contract as attachPersistence. } diff --git a/packages/client/ui-agent-preset/src/client/guide-locales.ts b/packages/client/ui-agent-preset/src/client/guide-locales.ts index d193002324..2401935497 100644 --- a/packages/client/ui-agent-preset/src/client/guide-locales.ts +++ b/packages/client/ui-agent-preset/src/client/guide-locales.ts @@ -10,7 +10,7 @@ export const guideEn = { guideStandardIntro: 'Choose Standard mode when starting a new task. Describe what you want to accomplish, point to the relevant files, and explain how to check the result.', guideStandardExplanation: [ '### How it works', - 'The agent calls tools directly to read and edit files, search, and run terminal commands. It includes Skills, planning, goals, subagents, workflows, plugin management, and context compaction.', + 'The agent calls tools directly to read and edit files, search, and run terminal commands. It includes Skills, planning, goals, subagents, workflows, plugin management, read-only runtime inspection, and context compaction.', 'For questions about DSH and plugin or preset work you request, the dsh-doc skill guides the agent to the installed documentation and source. Its instructions load only when requested or relevant; loading it does not change files, tools, or the profile.', '### When to choose it', 'Start here for everyday coding, file work, and research. Standard mode can also write scripts and process files in batches. PTC changes how tool calls are organized; it is not required for batch tasks.', @@ -55,7 +55,7 @@ export const guideEn = { guideCordisIntro: 'Choose Creator mode for a new task. Describe the capability you want, where it should appear, and how you will verify it.', guideCordisExplanation: [ '### What you can create', - 'Creator mode includes the standard task tools and adds runtime inspection. Standard and Creator share the dsh-doc guidance for plugin and preset development. The agent can create a plugin that adds a capability or UI, or a preset that combines tools and prompts for a particular job.', + 'Creator mode focuses on customizing DSH. It shares read-only runtime inspection and dsh-doc guidance with Standard mode. The agent can create a plugin that adds a capability or UI, or a preset that combines tools and prompts for a particular job.', '### Plugins and modes', 'A plugin adds capabilities to DSH, such as a tool, a service connection, or a UI entry. A mode is an agent preset that selects tools and defines how the agent works in a task. A plugin can be included in a custom preset.', '### How the result takes effect', @@ -89,7 +89,7 @@ export const guideZh: Record = { guideStandardIntro: '新建任务时选择「标准模式」,说明要完成什么、相关文件在哪里,以及怎样判断任务完成。', guideStandardExplanation: [ '### 工作方式', - 'Agent 直接调用工具来读写文件、检索资料和执行终端命令。包含 Skills、计划、目标、子 Agent、工作流、插件管理和上下文压缩等能力。', + 'Agent 直接调用工具来读写文件、检索资料和执行终端命令。包含 Skills、计划、目标、子 Agent、工作流、插件管理、只读运行时检查和上下文压缩等能力。', '对于 DSH 相关问题以及你要求的插件或预设工作,dsh-doc skill 引导 Agent 查阅已安装的文档和源码。其指令仅在被要求加载或与当前任务相关时加载;加载该 skill 不会改变文件、工具或 profile。', '### 什么时候选', '日常编程、文件处理和资料整理可以从这里开始。标准模式也能编写脚本、批量处理文件;PTC 改变的是工具调用方式,批量任务并不必须使用 PTC。', @@ -134,7 +134,7 @@ export const guideZh: Record = { guideCordisIntro: '新建任务时选择「创造模式」,说明希望增加什么能力、从哪里使用,以及怎样验证效果。', guideCordisExplanation: [ '### 可以创造什么', - '创造模式包含标准任务工具,并增加了运行时检查。标准模式和创造模式共用 dsh-doc 指引,用于插件和预设开发。Agent 可以创建插件来添加能力或界面,也可以创建预设,为特定工作组合工具和提示词。', + '创造模式专注于定制 DSH。它与标准模式共用只读运行时检查和 dsh-doc 指引。Agent 可以创建插件来添加能力或界面,也可以创建预设,为特定工作组合工具和提示词。', '### 插件与模式的关系', '插件为 DSH 增加能力,例如工具、服务连接或界面入口。模式是一份 Agent 预设,用来选择任务可用的工具,并约定 Agent 的工作方式。自定义模式中也可以使用自己开发的插件。', '### 怎样让成果生效', @@ -163,7 +163,7 @@ export const guideJa = { 'guideCopied': 'コピーしました', 'guideFootnotes': '脚注', 'guideStandardIntro': '新しいタスクを始めるときは標準モードを選びます。達成したいことを説明し、関連するファイルを示し、結果の確認方法を伝えてください。', - 'guideStandardExplanation': '### 仕組み\n\nエージェントはツールを直接呼び出してファイルの読み取りや編集、検索、ターミナルコマンドの実行を行います。スキル、計画、目標、サブエージェント、ワークフロー、プラグイン管理、コンテキストの圧縮に対応しています。\n\n### 選ぶべき場面\n\n日々のコーディング、ファイル作業、調査はまずここから始めてください。標準モードではスクリプトの作成やファイルの一括処理も行えます。PTC はツール呼び出しの構成を変えるものであり、一括処理に必須ではありません。', + 'guideStandardExplanation': '### 仕組み\n\nエージェントはツールを直接呼び出してファイルの読み取りや編集、検索、ターミナルコマンドの実行を行います。スキル、計画、目標、サブエージェント、ワークフロー、プラグイン管理、読み取り専用のランタイム検査、コンテキストの圧縮に対応しています。\n\n### 選ぶべき場面\n\n日々のコーディング、ファイル作業、調査はまずここから始めてください。標準モードではスクリプトの作成やファイルの一括処理も行えます。PTC はツール呼び出しの構成を変えるものであり、一括処理に必須ではありません。', 'guideStandardUsage': '### バグを修正する\n\n> 検索フォームを二度送信すると結果が消える原因を調べてください。修正して関連するテストを実行し、原因と変更内容を説明してください。\n\n期待される出力: コードの変更、関連するテスト結果、原因の説明。\n\n### プロジェクトのメモを整理する\n\n> このプロジェクト内の Markdown メモを読み、合意された決定と未解決の課題を、元ファイルへのリンク付きで要約してください。\n\n期待される出力: 元のメモと照合できる参照付きの要約。', 'guidePtcIntro': '新しいタスクを始めるときは PTC モードを選びます。入力ファイル、処理ルール、出力形式を指定してください。コードはエージェントが書きます。', 'guidePtcExplanation': '### ツールの呼び出され方\n\nPTC は Programmatic Tool Calling の略です。この組み込みプリセットでは、エージェントは run_code を使い、生成された SDK 経由でツールを呼び出す TypeScript プログラムを書きます。プログラムではループ、条件分岐、エラー処理、必要に応じて並行呼び出しを利用できます。\n\n### モデルに届くもの\n\nツールの結果はまずプログラムに届き、そこでフィルタリングや結合ができます。モデルが受け取るのはプログラムが出力または返した内容です。画像の結果は別途添付されます。ネストされたツール呼び出しも記録され、ツール権限の対象のままです。\n\n### 標準モードとの比較\n\nどちらのモードもコーディングや一括処理のタスクを扱えます。標準モードは個々のツールを直接公開し、PTC はツール呼び出しをコードで整理します。現在の PTC プリセットではワークフローとプラグイン管理ツールが無効になっています。速度とトークン消費はタスクやプログラムの結果の扱い方によって変わります。', @@ -172,7 +172,7 @@ export const guideJa = { 'guideMinimalExplanation': '### 含まれるもの\n\n永続的なシェルツール 1 つ、read_image、固定のシステムプロンプト。画像の読み取りには画像対応モデルが必要です。古い履歴はコンテキストの負荷に応じて自動的に圧縮されます。エージェントがアイドル状態のときに /compact を使えば手動で圧縮できます。この組み込みプリセットはスキル、計画、標準のランタイムコンテキストを読み込みません。\n\n### 選ぶべき場面\n\n実験や比較のベースラインとして使用します。シェルコマンド経由でファイルの読み取りやスクリプトの実行はできますが、長いタスクを管理するための組み込み手段は少なくなります。ツールが少ないからといって、初心者にとって必ずしも簡単になるわけではありません。', 'guideMinimalUsage': '### 小さなバグ修正で性能を比較する\n\n> このプロジェクトのテストを実行し、失敗の原因を見つけて最小限の修正をしてください。関連するテストを再度実行し、結果を報告してください。\n\n同じ開始状態から、標準モードと最小モードで同じタスクを別々に実行します。タスクの完了状況、ツール呼び出し、生じた変更を比較してください。最小モードはターミナルコマンドを通じて作業を行います。', 'guideCordisIntro': '新しいタスクにはクリエイターモードを選びます。実現したい機能、表示される場所、確認方法を説明してください。', - 'guideCordisExplanation': '### 作成できるもの\n\nクリエイターモードには標準的なタスクツールに加え、ランタイムの検査、Cordis プラグインやエージェントプリセットの作成ガイドが含まれます。機能や UI を追加するプラグインを作成することも、特定の作業向けにツールとプロンプトを組み合わせたプリセットを作成することもできます。\n\n### プラグインとモード\n\nプラグインはツール、サービス接続、UI エントリなど、DSH に機能を追加します。モードはエージェントプリセットであり、ツールを選択し、タスク内でのエージェントの動作を定義します。プラグインはカスタムプリセットに含めることができます。\n\n### 結果を反映させる方法\n\nソースコードを生成するだけでなく、エージェントにインストールと確認を依頼してください。プラグインは変更内容によっては即座に読み込まれるか、再起動が必要になる場合があります。新しく作成したプリセットは、新しいタスクを始めるときに選択されます。', + 'guideCordisExplanation': '### 作成できるもの\n\nクリエイターモードは DSH のカスタマイズに重点を置いています。読み取り専用のランタイム検査と dsh-doc のガイドを標準モードと共有しています。エージェントは機能や UI を追加するプラグインを作成することも、特定の作業向けにツールとプロンプトを組み合わせたプリセットを作成することもできます。\n\n### プラグインとモード\n\nプラグインはツール、サービス接続、UI エントリなど、DSH に機能を追加します。モードはエージェントプリセットであり、ツールを選択し、タスク内でのエージェントの動作を定義します。プラグインはカスタムプリセットに含めることができます。\n\n### 結果を反映させる方法\n\nソースコードを生成するだけでなく、エージェントにインストールと確認を依頼してください。プラグインは変更内容によっては即座に読み込まれるか、再起動が必要になる場合があります。新しく作成したプリセットは、新しいタスクを始めるときに選択されます。', 'guideCordisUsage': '### UI を追加する\n\n> サイドバーにプロジェクトメモのエントリを追加する DSH プラグインを作成してください。このワークスペース内の Markdown ファイルを閲覧でき、選択したメモをプレビューできるようにしてください。インストールしてページが開くことを確認してください。\n\n期待される出力: 動作するエントリとプレビューページを備えた、インストール済みのプラグイン。残っている有効化手順があればそれも含みます。\n\n### ツールを追加する\n\n> このプロジェクトのテストレポートを読み、失敗したテストを要約するツールを備えたプラグインを作成してください。登録し、サンプルのレポートで確認してください。\n\n期待される出力: 呼び出し可能なツールを備えたプラグインと、確認済みのサンプル呼び出し。\n\n### 独自のモードを作成する\n\n> 標準モードをベースに「コードレビュー」モードを作成してください。潜在的なバグとテストの不足を優先し、ファイルパスと行番号を示し、ファイルを変更する前に確認を求めるようにしてください。選択可能なプリセットとして保存してください。\n\n期待される出力: 新しいタスク用のカスタムプリセット。これらのレビュー指示はエージェントを導くものであり、実行できる操作は権限設定によって決まります。', } satisfies Record @@ -188,7 +188,7 @@ export const guideEs = { guideStandardIntro: 'Elija el modo Estándar al iniciar una nueva tarea. Describe lo que quieres lograr, señala los archivos relevantes y explica cómo verificar el resultado.', guideStandardExplanation: [ '### Cómo funciona', - 'El agente llama a herramientas directamente para leer y editar archivos, buscar y ejecutar comandos de terminal. Incluye habilidades, planificación, objetivos, subagentes, flujos de trabajo, gestión de complementos y compactación de contexto.', + 'El agente llama a herramientas directamente para leer y editar archivos, buscar y ejecutar comandos de terminal. Incluye habilidades, planificación, objetivos, subagentes, flujos de trabajo, gestión de complementos, inspección del tiempo de ejecución de solo lectura y compactación de contexto.', '### Cuándo elegirlo', 'Comience aquí para la codificación, el trabajo con archivos y la investigación diaria. El modo estándar también puede escribir scripts y procesar archivos en lotes. PTC cambia la forma en que se organizan las llamadas a herramientas; no es necesario para tareas por lotes.', ].join('\n\n\n\n'), @@ -232,7 +232,7 @@ export const guideEs = { guideCordisIntro: 'Elija el modo Creador para una nueva tarea. Describe la capacidad que deseas, dónde debería aparecer y cómo la verificarás.', guideCordisExplanation: [ '### Lo que puedes crear', - 'El modo Creador incluye las herramientas de tareas estándar además de inspección del tiempo de ejecución y orientación para crear Cordis complementos y ajustes preestablecidos de agentes. Puede crear un complemento que agregue una capacidad o interfaz de usuario, o un ajuste preestablecido que combine herramientas e indicaciones para un trabajo en particular.', + 'El modo Creador se centra en personalizar DSH. Comparte la inspección del tiempo de ejecución de solo lectura y la orientación de dsh-doc con el modo Estándar. El agente puede crear un complemento que agregue una capacidad o interfaz de usuario, o un ajuste preestablecido que combine herramientas e indicaciones para un trabajo en particular.', '### Complementos y modos', 'Un complemento agrega capacidades a DSH, como una herramienta, una conexión de servicio o una entrada de UI. Un modo es un ajuste preestablecido del agente que selecciona herramientas y define cómo trabaja el agente en una tarea. Se puede incluir un complemento en un ajuste preestablecido personalizado.', '### Cómo surte efecto el resultado', @@ -263,7 +263,7 @@ export const guideFr = { guideStandardIntro: 'Choisissez le mode Standard lorsque vous démarrez une nouvelle tâche. Décrivez ce que vous souhaitez accomplir, pointez vers les fichiers pertinents et expliquez comment vérifier le résultat.', guideStandardExplanation: [ '### Comment ça marche', - "L'agent appelle directement des outils pour lire et modifier des fichiers, rechercher et exécuter des commandes de terminal. Il comprend les compétences, la planification, les objectifs, les sous-agents, les flux de travail, la gestion des plugins et le compactage du contexte.", + "L'agent appelle directement des outils pour lire et modifier des fichiers, rechercher et exécuter des commandes de terminal. Il comprend les compétences, la planification, les objectifs, les sous-agents, les flux de travail, la gestion des plugins, l\'inspection d\'exécution en lecture seule et le compactage du contexte.", '### Quand le choisir', "Commencez ici pour le codage quotidien, le travail sur les fichiers et la recherche. Le mode standard peut également écrire des scripts et traiter des fichiers par lots. PTC modifie la façon dont les appels d'outils sont organisés ; il n'est pas requis pour les tâches par lots.", ].join('\n\n\n\n'), @@ -307,7 +307,7 @@ export const guideFr = { guideCordisIntro: 'Choisissez le mode Créateur pour une nouvelle tâche. Décrivez la fonctionnalité souhaitée, où elle doit apparaître et comment vous la vérifierez.', guideCordisExplanation: [ '### Ce que vous pouvez créer', - "Le mode Créateur inclut les outils de tâches standard, ainsi qu'une inspection d'exécution et des conseils pour la création de Cordis plug-ins et préréglages d'agent. Il peut créer un plugin qui ajoute une fonctionnalité ou une interface utilisateur, ou un préréglage combinant des outils et des invites pour une tâche particulière.", + "Le mode Créateur se concentre sur la personnalisation de DSH. Il partage l'inspection d'exécution en lecture seule et les conseils de dsh-doc avec le mode Standard. L'agent peut créer un plugin qui ajoute une fonctionnalité ou une interface utilisateur, ou un préréglage combinant des outils et des invites pour une tâche particulière.", '### Plugins et modes', "Un plug-in ajoute des fonctionnalités à DSH, telles qu'un outil, une connexion à un service ou une entrée d'interface utilisateur. Un mode est un préréglage d'agent qui sélectionne les outils et définit la manière dont l'agent fonctionne dans une tâche. Un plugin peut être inclus dans un préréglage personnalisé.", '### Comment le résultat prend effet', @@ -338,7 +338,7 @@ export const guideDe = { guideStandardIntro: 'Wählen Sie den Standardmodus, wenn Sie eine neue Aufgabe starten. Beschreiben Sie, was Sie erreichen möchten, zeigen Sie auf die relevanten Dateien und erklären Sie, wie Sie das Ergebnis überprüfen können.', guideStandardExplanation: [ '### Wie es funktioniert', - 'Der Agent ruft Tools direkt auf, um Dateien zu lesen und zu bearbeiten, zu suchen und Terminalbefehle auszuführen. Es umfasst Fähigkeiten, Planung, Ziele, Subagenten, Arbeitsabläufe, Plugin-Verwaltung und Kontextkomprimierung.', + 'Der Agent ruft Tools direkt auf, um Dateien zu lesen und zu bearbeiten, zu suchen und Terminalbefehle auszuführen. Es umfasst Fähigkeiten, Planung, Ziele, Subagenten, Arbeitsabläufe, Plugin-Verwaltung, schreibgeschützte Laufzeitprüfung und Kontextkomprimierung.', '### Wann man es wählt', 'Beginnen Sie hier mit alltäglicher Codierung, Dateiarbeit und Recherche. Im Standardmodus können auch Skripts geschrieben und Dateien stapelweise verarbeitet werden. PTC ändert die Organisation von Toolaufrufen; Für Batch-Aufgaben ist es nicht erforderlich.', ].join('\n\n\n\n'), @@ -382,7 +382,7 @@ export const guideDe = { guideCordisIntro: 'Wählen Sie den Erstellermodus für eine neue Aufgabe. Beschreiben Sie die gewünschte Funktion, wo sie angezeigt werden soll und wie Sie sie überprüfen.', guideCordisExplanation: [ '### Was Sie erstellen können', - 'Der Erstellermodus umfasst die Standardaufgabentools sowie eine Laufzeitprüfung und Anleitungen zum Erstellen von Cordis-Plugins und Agent-Voreinstellungen. Es kann ein Plugin erstellt werden, das eine Funktion oder Benutzeroberfläche hinzufügt, oder eine Voreinstellung, die Tools und Eingabeaufforderungen für einen bestimmten Job kombiniert.', + 'Der Erstellermodus konzentriert sich auf die Anpassung von DSH. Er bietet dieselbe schreibgeschützte Laufzeitprüfung und dieselben dsh-doc-Anleitungen wie der Standardmodus. Der Agent kann ein Plugin erstellen, das eine Funktion oder Benutzeroberfläche hinzufügt, oder eine Voreinstellung, die Tools und Eingabeaufforderungen für einen bestimmten Job kombiniert.', '### Plugins und Modi', 'Ein Plugin fügt DSH Funktionen hinzu, beispielsweise ein Tool, eine Dienstverbindung oder einen UI-Eintrag. Ein Modus ist eine Agentenvoreinstellung, die Tools auswählt und definiert, wie der Agent in einer Aufgabe arbeitet. Ein Plugin kann in eine benutzerdefinierte Voreinstellung eingebunden werden.', '### Wie das Ergebnis wirksam wird', @@ -413,7 +413,7 @@ export const guideRu = { guideStandardIntro: 'Выбирайте стандартный режим при запуске новой задачи. Опишите, чего вы хотите добиться, укажите соответствующие файлы и объясните, как проверить результат.', guideStandardExplanation: [ '### Как это работает', - 'Агент напрямую вызывает инструменты для чтения и редактирования файлов, поиска и выполнения команд терминала. Он включает в себя навыки, планирование, цели, субагенты, рабочие процессы, управление плагинами и сжатие контекста.', + 'Агент напрямую вызывает инструменты для чтения и редактирования файлов, поиска и выполнения команд терминала. Он включает в себя навыки, планирование, цели, субагенты, рабочие процессы, управление плагинами, проверку во время выполнения только для чтения и сжатие контекста.', '### Когда это выбирать', 'Начните здесь ежедневное программирование, работу с файлами и исследования. Стандартный режим также позволяет писать сценарии и обрабатывать файлы в пакетном режиме. PTC изменяет организацию вызовов инструментов; для пакетных задач это не требуется.', ].join('\n\n\n\n'), @@ -457,7 +457,7 @@ export const guideRu = { guideCordisIntro: 'Выберите режим «Создатель» для новой задачи. Опишите желаемую возможность, где она должна появиться и как вы ее проверите.', guideCordisExplanation: [ '### Что вы можете создать', - 'Режим Creator включает в себя стандартные инструменты задач, а также проверку во время выполнения и рекомендации по созданию подключаемых модулей Cordis и предустановок агента. Он может создать плагин, добавляющий возможности или пользовательский интерфейс, или предустановку, объединяющую инструменты и подсказки для конкретной работы.', + 'Режим Creator предназначен для настройки DSH. Он предоставляет ту же проверку во время выполнения только для чтения и те же рекомендации dsh-doc, что и стандартный режим. Агент может создать плагин, добавляющий возможности или пользовательский интерфейс, или предустановку, объединяющую инструменты и подсказки для конкретной работы.', '### Плагины и режимы', 'Плагин добавляет к DSH возможности, такие как инструмент, подключение к службе или запись пользовательского интерфейса. Режим — это предустановка агента, которая выбирает инструменты и определяет, как агент работает над задачей. Плагин может быть включен в пользовательский пресет.', '### Как результат вступает в силу', @@ -488,7 +488,7 @@ export const guidePt = { guideStandardIntro: 'Escolha o modo Padrão ao iniciar uma nova tarefa. Descreva o que você deseja realizar, indique os arquivos relevantes e explique como verificar o resultado.', guideStandardExplanation: [ '### Como funciona', - 'O agente chama ferramentas diretamente para ler e editar arquivos, pesquisar e executar comandos de terminal. Inclui habilidades, planejamento, metas, subagentes, fluxos de trabalho, gerenciamento de plugins e compactação de contexto.', + 'O agente chama ferramentas diretamente para ler e editar arquivos, pesquisar e executar comandos de terminal. Inclui habilidades, planejamento, metas, subagentes, fluxos de trabalho, gerenciamento de plugins, inspeção de tempo de execução somente leitura e compactação de contexto.', '### Quando escolher', 'Comece aqui para codificação diária, trabalho de arquivo e pesquisa. O modo padrão também pode escrever scripts e processar arquivos em lotes. PTC altera a forma como as chamadas de ferramenta são organizadas; não é necessário para tarefas em lote.', ].join('\n\n\n\n'), @@ -532,7 +532,7 @@ export const guidePt = { guideCordisIntro: 'Escolha o modo Criador para uma nova tarefa. Descreva o recurso desejado, onde ele deve aparecer e como você o verificará.', guideCordisExplanation: [ '### O que você pode criar', - 'O modo Criador inclui ferramentas de tarefas padrão, além de inspeção de tempo de execução e orientação para criação de Cordis plug-ins e predefinições de agente. Ele pode criar um plug-in que adicione um recurso ou UI, ou uma predefinição que combine ferramentas e prompts para um trabalho específico.', + 'O modo Criador se concentra na personalização do DSH. Ele compartilha a inspeção de tempo de execução somente leitura e a orientação do dsh-doc com o modo Padrão. O agente pode criar um plug-in que adicione um recurso ou UI, ou uma predefinição que combine ferramentas e prompts para um trabalho específico.', '### Plug-ins e modos', 'Um plug-in adiciona recursos a DSH, como uma ferramenta, uma conexão de serviço ou uma entrada de IU. Um modo é uma predefinição de agente que seleciona ferramentas e define como o agente trabalha em uma tarefa. Um plugin pode ser incluído em uma predefinição personalizada.', '### Como o resultado entra em vigor', diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index a986f761c4..ae1adac098 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -39,8 +39,8 @@ en: f6d8bbae13a1a8f8 zh: 96c8f400c215e33d /deepseek-ai-dsh-client-ui-chat/scroll-ownership: - en: 1b12aa6c505dde3b - zh: 88e1654dd63816d7 + en: 596c30d730cdbce7 + zh: 6009f248a3b9d39f /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 70921859ae..84e81d7c62 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -158,7 +158,9 @@ Chat waits for initial history before automatic content, scroll, or size updates Chat restores semantic anchors across history prepend and renderer remounts, with browser scroll anchoring disabled on its scrollport only while following the tail. Pinned scroll deliveries without reader movement, and reader input that reaches the floor within subpixel rounding, update follow ownership immediately, before subsequent layout changes can invalidate their floor. Other reader movement remains pending until the sampling interval or `scrollend`, even inside the follow threshold, so layout growth cannot erase small scroll gestures. Under completion-time folding, submitting transcript input or steering immediately restores tail following and clears an older pending reader sample. Under next-message folding, transcript input that no fold batch carries lands on one native animation; steering lands at once under either timing, because the running Turn keeps streaming above its echo. While the reader is pinned to the floor, `ResizeObserver` follows the new floor and selects the latest loaded Turn without reading row geometry. Once the reader moves away, flow-height changes preserve the top position and the reading-line geometry selects the active Turn. Turn-rail previews paint above sticky Markdown code-block banners, while the rail frame remains inside the transcript band above the composer. -The turn rail and back-to-bottom button sit outside the clipped transcript. They use the shared conversation scrollport for sticky positioning, or the Chat frame for absolute positioning when Chat owns its scrollport. The rail hides when the transcript's available width, excluding its horizontal padding, is at most 900px; the browser viewport width is not the criterion. +The turn rail and back-to-bottom button sit outside the clipped transcript. They use the shared conversation scrollport for sticky positioning, or the Chat frame for absolute positioning when Chat owns its scrollport. The rail sits at the scrollport's start edge, which leaves the end gutter to the [Session panel](../ui-session-panel/README.md), and its previews open toward the transcript. The rail hides when the transcript's available width, excluding its horizontal padding, is at most 900px; the browser viewport width is not the criterion. + +The `conversation.chat.aside` slot holds one Session-level occupant beside the transcript, such as the [Session panel](../ui-session-panel/README.md). Every Chat View occurrence, main or embedded, renders it in a zero-height layer at the top of the Chat frame, positioned like the turn rail, so it stays in place while the transcript scrolls and inherits `--dsh-composer-height` and `--dsh-conversation-viewport-height` from the shared scrollport. The layer stacks above the turn rail and the back-to-bottom button and passes pointer events through. The layer measures nothing: its stylesheet publishes the end gutter, the inline space between the centered transcript column and the frame's end edge, as the `--dsh-chat-aside-gutter` custom property, `max(0px, (100% - var(--dsh-chat-content-width)) / 2)`. The percentage resolves against the layer in the inline sizes of an element whose containing block is the layer, so an occupant sizes and places itself in CSS, and the Chat View neither re-renders nor observes sizes for it. The transcript root uses `overflow-x: visible; overflow-y: clip`: vertical overflow is clipped without creating a scroll container. Sticky Markdown code banners and expanded compaction headers therefore retain the actual conversation scrollport as their reference when no nearer scrolling ancestor exists. Capped process groups and terminal sections keep their own scrollports. diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index d50ba90f91..6243b9825a 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -158,7 +158,9 @@ Chat 等待初始历史就绪后,才允许自动内容、滚动或尺寸更新 Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且只在跟随底部时禁用自己滚动区域的浏览器自动锚定。没有读者移动的贴底滚动事件,以及到达底部(容许小于 1px 的取整误差)的读者输入,会立即更新跟随归属,避免后续布局变化使其底部位置失效。其他读者移动即使位于跟随阈值内,也保持待处理直到采样周期或 `scrollend`,防止布局增长抵消小幅滚动操作。采用完成时收起时,提交正文输入或 steering 会立即恢复跟随底部,并清除先前待处理的读者滚动采样。采用下次消息时收起时,没有折叠批次承载的正文输入用一次原生动画落到底部;steering 在两种时机下都立即落到底部,因为运行中的 Turn 仍在其回显上方持续输出。读者跟随底部时,`ResizeObserver` 追随新的底部,并且无需读取行几何就选中最后一个已加载轮次;读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃轮次。轮次导航预览位于 Markdown 代码块粘性头栏上方,而导航外框始终处于 composer 上方的 transcript 区域内。 -轮次轨道与回到底部按钮位于正文裁剪层外。它们相对共享会话滚动容器做 sticky 定位;Chat 自己持有滚动容器时,则相对 Chat 外框做 absolute 定位。正文扣除水平内边距后的可用宽度不超过 900px 时,隐藏轮次轨道;判断依据不是浏览器视口宽度。 +轮次轨道与回到底部按钮位于正文裁剪层外。它们相对共享会话滚动容器做 sticky 定位;Chat 自己持有滚动容器时,则相对 Chat 外框做 absolute 定位。轮次轨道贴在滚动容器的起始边,把末端留白让给[会话面板](../ui-session-panel/README.zh.md),预览朝正文方向弹出。正文扣除水平内边距后的可用宽度不超过 900px 时,隐藏轮次轨道;判断依据不是浏览器视口宽度。 + +`conversation.chat.aside` slot 放一个位于正文旁边、面向整个会话的组件,例如[会话面板](../ui-session-panel/README.zh.md)。每个 Chat 视图实例(主正文区或嵌入的)都会渲染它:它位于 Chat 外框顶部的零高度图层中,定位方式与轮次轨道相同,因此不随正文滚动,并从共享滚动容器继承 `--dsh-composer-height` 与 `--dsh-conversation-viewport-height`。该图层叠在轮次轨道与回到底部按钮之上,自身不拦截指针事件。图层不做任何测量:它的样式表把末端留白(居中的正文列到外框末端边缘之间的行向空间)发布为自定义属性 `--dsh-chat-aside-gutter`,值为 `max(0px, (100% - var(--dsh-chat-content-width)) / 2)`。其中的百分比在以该图层为包含块的元素的行向尺寸里按图层宽度解析,因此占位组件用 CSS 决定自身的尺寸与位置,Chat 视图既不为它重新渲染,也不为它观察尺寸。 正文根节点使用 `overflow-x: visible; overflow-y: clip`:裁剪纵向溢出,但不创建滚动容器。因此,在没有更近的滚动祖先时,Markdown 代码块的 sticky 头栏和展开的压缩摘要头栏仍以实际会话滚动容器为参照。限高过程组和终端区域保留各自的滚动容器。 diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index 7e4a3a5f01..56bb503a9a 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -245,6 +245,7 @@ export function apply(ctx: Context): void { 'conversation.chat.flow': { kind: 'single', scope: 'session', inject: CHAT_FLOW_INJECT }, 'conversation.chat.text-interaction': { kind: 'keyed', scope: 'session' }, 'conversation.chat.markdown.fence': { kind: 'hoc', scope: 'session' }, + 'conversation.chat.aside': { kind: 'single', scope: 'session' }, }, store: chatStore, inject: (sessionId: SessionId): ChatViewInjected => { diff --git a/packages/client/ui-chat/src/client/chat/ChatAside.tsx b/packages/client/ui-chat/src/client/chat/ChatAside.tsx new file mode 100644 index 0000000000..1e314c8d41 --- /dev/null +++ b/packages/client/ui-chat/src/client/chat/ChatAside.tsx @@ -0,0 +1,15 @@ +/** The Chat View's aside layer: one Session-level occupant beside the transcript, which the layer's stylesheet tells the end gutter. */ +import { memo } from 'react' +import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import css from './ChatView.module.css' + +/** + * Render the aside layer with its occupant. The Chat View's `renderSlot` is + * stable per registration, so the layer renders once and transcript updates + * do not re-render it; its geometry is CSS only. + * @param props - the Chat View's slot renderer. + * @returns the zero-height aside layer. + */ +export const ChatAside = memo(function ChatAside({ renderSlot }: Pick, 'renderSlot'>) { + return
{renderSlot('conversation.chat.aside', {})}
+}) diff --git a/packages/client/ui-chat/src/client/chat/ChatView.module.css b/packages/client/ui-chat/src/client/chat/ChatView.module.css index 1f84e97842..520b899f08 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.module.css +++ b/packages/client/ui-chat/src/client/chat/ChatView.module.css @@ -356,6 +356,30 @@ /* Floating controls sit outside the clipped transcript. A standalone Chat anchors them to its frame; the shared host supplies the sticky scrollport. */ +/* The aside layer: zero height at the frame's top, sticky in a shared + scrollport so its occupant stays put while the transcript scrolls and + inherits the scrollport's --dsh-composer-height and + --dsh-conversation-viewport-height. Above the turn rail (7) and the + back-to-bottom control (8). It publishes the end gutter, the inline space + between the centered transcript column and the frame's end edge, for the + occupant's inline sizes: the percentage resolves against the layer in an + element whose containing block is the layer, as it does in the + back-to-bottom control's padding below. */ +.asideSlot { + position: absolute; + top: 0; + right: 0; + left: 0; + z-index: 9; + height: 0; + pointer-events: none; + --dsh-chat-aside-gutter: max(0px, calc((100% - var(--dsh-chat-content-width, 100%)) / 2)); +} + +:global([data-conversation-scroll]) .asideSlot { + position: sticky; +} + .toBottomSlot { position: absolute; right: 0; diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index c9143248a1..2c361fa35e 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx @@ -16,6 +16,7 @@ import type { ChatFlowHookContext, ChatViewSlotProps, OpenFileOptions } from '.. import type { ChatSnapshot } from '../contract/snapshot.ts' import { markdownLabels } from '../markdown-labels.ts' import { TurnNavigator } from './TurnNavigator.tsx' +import { ChatAside } from './ChatAside.tsx' import { mergeTurnRailItems } from './turn-rail-items.ts' import { useTextInteraction } from './text-interaction.ts' import { useChatScroll } from './use-chat-scroll.ts' @@ -239,6 +240,7 @@ export function ChatView({ t={t} /> )} +
- & PropsRenderSlots<'conversation.chat.flow' | 'conversation.chat.text-interaction' | 'conversation.chat.markdown.fence'> + & PropsRenderSlots<'conversation.chat.flow' | 'conversation.chat.text-interaction' | 'conversation.chat.markdown.fence' | 'conversation.chat.aside'> & PropsStore & InjectFace & PropsLocale<'chat'> @@ -431,6 +431,20 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { 'conversation.chat.text-interaction': { kind: 'keyed'; scope: 'session'; owner: TextInteractionSurface } /** Language-keyed layers around one Markdown fence in the Chat flow; the content is the plain code block. */ 'conversation.chat.markdown.fence': { kind: 'hoc'; scope: 'session'; owner: MarkdownDelegateFenceInfo } + /** + * One Session-level occupant beside the transcript, such as a summary + * panel. Every Chat View occurrence renders it in a zero-height layer at + * the top of the Chat frame, which stays in place while the transcript + * scrolls and inherits the shared scrollport's composer and viewport + * heights. The layer passes pointer events through; the occupant + * positions itself in it, enables its own pointer events, and keeps + * within the end gutter to stay clear of the transcript column. The + * layer publishes that gutter, the inline space between the transcript + * column and the frame's end edge, as the `--dsh-chat-aside-gutter` + * custom property; its percentage resolves in the inline sizes of an + * element whose containing block is the layer. + */ + 'conversation.chat.aside': { kind: 'single'; scope: 'session' } /** Ordered Chat rows and local echoes with viewport-bound visibility hooks. */ 'conversation.chat.flow': { diff --git a/packages/client/ui-chat/tests/aside-styles.client.spec.ts b/packages/client/ui-chat/tests/aside-styles.client.spec.ts new file mode 100644 index 0000000000..d8e612bd10 --- /dev/null +++ b/packages/client/ui-chat/tests/aside-styles.client.spec.ts @@ -0,0 +1,31 @@ +/** + * The Chat aside layer as CSS text. jsdom has no layout, so the rendering + * spec shows where the layer sits but not what it tells its occupant; this + * reads the declarations an occupant's inline sizes depend on. + */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const css = readFileSync(fileURLToPath(new URL('../src/client/chat/ChatView.module.css', import.meta.url)), 'utf8') + +function declarationsOf(selector: string): string[] { + const text = css.replace(/\/\*[\s\S]*?\*\//g, ' ') + const rule = new RegExp(`(?:^|[{}])\\s*${selector.replace(/[.[\]():*+^$\\]/g, '\\$&')}\\s*\\{([^{}]*)\\}`).exec(text) + if (rule === null) throw new Error(`no \`${selector}\` rule`) + return (rule[1] ?? '').split(';').map(part => part.trim()).filter(Boolean) +} + +describe('Chat aside layer', () => { + it('spans the frame at zero height and passes pointer events through', () => { + expect(declarationsOf('.asideSlot')).toEqual(expect.arrayContaining([ + 'position: absolute', 'right: 0', 'left: 0', 'height: 0', 'pointer-events: none', + ])) + }) + + it('publishes the end gutter as half the frame width the transcript column leaves, never negative', () => { + expect(declarationsOf('.asideSlot')).toContain( + '--dsh-chat-aside-gutter: max(0px, calc((100% - var(--dsh-chat-content-width, 100%)) / 2))', + ) + }) +}) 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 311679176c..ed04662097 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -500,12 +500,17 @@ function makeHarness( return renderUserContent(owner as UserContentInput, renderImages, props.t) } const fenceCalls: { owner: MarkdownDelegateFenceInfo; entryKey: string | undefined }[] = [] + const asideRenders = { count: 0 } const renderSlot = ( key: string, owner: ChatFlowOwnerProps | MarkdownDelegateFenceInfo, opts: Parameters[2] & { entryKey?: string; children?: React.ReactNode }, ) => { if (key === 'conversation.chat.text-interaction') return null + if (key === 'conversation.chat.aside') { + asideRenders.count += 1 + return + } if (key === 'conversation.chat.markdown.fence' && 'lang' in owner) { fenceCalls.push({ owner, entryKey: opts.entryKey }) return opts.children ?? null @@ -608,7 +613,7 @@ function makeHarness( setConnection: (state: ConnectionState) => { connection.set(state) }, openFile, openUserFile, loadOlder, consumeOlder, prepareOlder, loadThrough, openView, setOutline: (value: unknown) => { outlineValue = value }, - chatScroll, forkAt, toolOwners, fenceCalls, + chatScroll, forkAt, toolOwners, fenceCalls, asideRenders, setPerformanceUsage: (mode: 'compact' | 'detailed') => { performanceUsage.set(mode) }, setGrouped: (value: ConversationGroupedView | undefined) => { grouped = value @@ -763,7 +768,7 @@ describe('Chat node rendering', () => { const { getTriggerProps } = useMarkdownDelegate() return <>{targets.map((target, index) => )} } - const view = render( } />) + const view = render( key === 'conversation.chat.aside' ? null : } />) directory = '/workspace/moved' for (const [index, target] of targets.entries()) { const button = view.getByRole('button', { name: String(index) }) @@ -863,6 +868,26 @@ describe('Chat node rendering', () => { }) describe('ChatView', () => { + it('renders the aside once in a layer at the top of the Chat frame, which observes no sizes', () => { + const observed: Element[] = [] + vi.stubGlobal('ResizeObserver', class { + observe(target: Element): void { observed.push(target) } + unobserve(): void {} + disconnect(): void {} + }) + const h = makeHarness({}, {}, chatSnapshotFixture({ nodes: [user(1, 'hello')] })) + const view = render() + const frame = view.container.firstElementChild as HTMLElement + const layer = frame.querySelector('[data-chat-aside]') as HTMLElement + expect(layer.parentElement).toBe(frame) + expect(layer.querySelector('[data-chat-aside-probe]')).not.toBeNull() + // The layer's stylesheet publishes the gutter; the layer itself measures nothing. + expect(observed).not.toContain(layer) + // Transcript updates do not re-render the aside. + act(() => { h.setSession({ running: true }) }) + expect(h.asideRenders.count).toBe(1) + }) + it('renders only referenced Nodes without deleting unreferenced Node data', () => { const snapshot = chatSnapshotFixture({ nodes: [user(1, 'included'), user(2, 'omitted')] }) const h = makeHarness({}, {}, snapshot) @@ -4922,7 +4947,7 @@ it('formats Portuguese elapsed minutes with numeric units', () => { 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( <> + const view = render( key === 'conversation.chat.aside' ? null : <> Plugin link + + ))} + + + ) +} diff --git a/packages/client/ui-schedule/src/client/TaskManagerPage.module.css b/packages/client/ui-schedule/src/client/TaskManagerPage.module.css index 6abf1a18f8..1d49839577 100644 --- a/packages/client/ui-schedule/src/client/TaskManagerPage.module.css +++ b/packages/client/ui-schedule/src/client/TaskManagerPage.module.css @@ -1365,8 +1365,18 @@ --dsh-button-outline-color: var(--dsw-alias-state-error-primary); } +/* The instruction only identifies the task here, so a long one stays a + three-line excerpt instead of growing the dialog. */ .confirmPrompt { + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; + line-clamp: 3; margin: 0; + overflow: hidden; + color: var(--dsw-alias-label-secondary); + font-size: 13px; + line-height: 22px; white-space: pre-wrap; overflow-wrap: anywhere; } @@ -1441,3 +1451,136 @@ font-size: 16px; } } + +/* Recommended tasks under the empty Enabled and All views: a two-column grid, + one column below 600px of content width. The heading starts on the tiles' + 12px inset. */ +.recommendations { + container-type: inline-size; + margin-top: 8px; +} + +.recommendationsHeading { + margin: 0 0 6px; + padding: 0 12px; + color: var(--dsw-alias-label-tertiary); + font-size: 13px; + line-height: 20px; + font-weight: 500; +} + +.recommendationGrid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 4px 16px; + margin: 0; + padding: 0; + list-style: none; +} + +@container (max-width: 600px) { + .recommendationGrid { + grid-template-columns: minmax(0, 1fr); + } +} + +.recommendation { + display: flex; + align-items: flex-start; + justify-content: flex-start; + gap: 14px; + width: 100%; + height: auto; + padding: 12px; + border-radius: var(--dsw-radius-lg); + text-align: left; + white-space: normal; +} + +/* Tiles take the empty illustration's background. Glyphs draw in the blue + accent, and each glyph's main shape takes a 16% tint of that blue, which + stays visible against the tile in both themes. */ +.tile { + display: flex; + flex: none; + align-items: center; + justify-content: center; + width: 40px; + height: 40px; + border-radius: var(--dsw-radius-md); + background: var(--dsw-alias-illustration-background); + color: var(--dsw-alias-state-business-primary); +} + +.tile [data-fill] { + fill: currentColor; + fill-opacity: 0.16; +} + +.tileGlyph { + flex: none; + width: 20px; + height: 20px; +} + +.tilePlus { + display: none; + flex: none; +} + +.recommendation:focus-visible .tileGlyph { + display: none; +} + +.recommendation:focus-visible .tilePlus { + display: block; +} + +@media (hover: hover) { + .recommendation:hover .tileGlyph { + display: none; + } + + .recommendation:hover .tilePlus { + display: block; + } +} + +.recommendationContent, +.recommendationDetails { + display: flex; + flex-direction: column; + min-width: 0; +} + +.recommendationContent { + flex: 1; +} + +.recommendationTitle { + font-weight: 500; + line-height: 22px; +} + +.recommendationDescription { + margin-top: 2px; + color: var(--dsw-alias-label-secondary); + font-size: 13px; + line-height: 20px; +} + +.recommendationWhen { + display: flex; + align-items: center; + gap: 6px; + margin-top: 6px; + color: var(--dsw-alias-label-tertiary); + font-size: 13px; + line-height: 20px; +} + +.whenGlyph { + flex: none; + width: 14px; + height: 14px; +} diff --git a/packages/client/ui-schedule/src/client/TaskManagerPage.tsx b/packages/client/ui-schedule/src/client/TaskManagerPage.tsx index a9a301f1bb..5ca57d5933 100644 --- a/packages/client/ui-schedule/src/client/TaskManagerPage.tsx +++ b/packages/client/ui-schedule/src/client/TaskManagerPage.tsx @@ -20,6 +20,7 @@ import { useRelativeClock } from './relative-clock.ts' import { formatScheduleFrequency, nextRunParts, taskName, zoneLabel } from './schedule-format.ts' import type { FrequencyZone } from './schedule-format.ts' import { ScheduleEmptyIllustration } from './ScheduleEmptyIllustration.tsx' +import { ScheduleRecommendations } from './ScheduleRecommendations.tsx' import css from './TaskManagerPage.module.css' /** Injected catalog and task actions for the management page. */ @@ -31,6 +32,12 @@ export interface TaskManagerInjected extends TaskDetailInjected { * schedule it, using the existing new-conversation action. */ readonly onNewTask: () => void + /** + * Start a new Session with a recommended task's request prefilled, through + * the same new-conversation action as `onNewTask`. + * @param prompt - the recommendation's localized request. + */ + readonly onUseRecommendation: (prompt: string) => void /** * Remove every ended Host task, after this page has confirmed the action. * @@ -59,7 +66,7 @@ type StatusFilter = 'all' | ScheduleCatalogEntry['status'] * @returns the searchable task list beside the selected task's detail. */ export function TaskManagerPage(props: TaskManagerPageProps) { - const { useCatalog, onNewTask, onClearEnded, onRetry, onCreateTask, t } = props + const { useCatalog, onNewTask, onUseRecommendation, onClearEnded, onRetry, onCreateTask, t } = props const [createMenuOpen, setCreateMenuOpen] = useState(false) const [manualOpen, setManualOpen] = useState(false) const catalog = useCatalog(snapshot => snapshot) @@ -101,6 +108,8 @@ export function TaskManagerPage(props: TaskManagerPageProps) { ), [records, statusFilter]) const rows = useMemo(() => rowIndex.search(search), [rowIndex, search]) + const showRecommendations = status === 'ready' && rows.length === 0 && search.trim() === '' + && (statusFilter === 'active' || statusFilter === 'all') const emptyTitle = search.trim() !== '' ? 'list.noMatches' : statusFilter === 'paused' ? 'list.emptyPaused' : statusFilter === 'ended' ? 'list.emptyInactive' @@ -285,6 +294,7 @@ export function TaskManagerPage(props: TaskManagerPageProps) { {t('empty.action')}
} + {showRecommendations && }
    {rows.map((record) => { // One pair per row: the same absolute stamp and distance reach diff --git a/packages/client/ui-schedule/src/client/index.ts b/packages/client/ui-schedule/src/client/index.ts index 5df353095f..8a6e92ee1c 100644 --- a/packages/client/ui-schedule/src/client/index.ts +++ b/packages/client/ui-schedule/src/client/index.ts @@ -215,6 +215,11 @@ export function apply(ctx: ClientContext): void { locale: MANAGER_NS, inject: (): ScheduleTaskCatalogInjected & ScheduleTaskBindingInjected => ({ hooks: detail.hooks, taskBindings }), }, ScheduleTaskTabTitle)) + // New and every recommendation open a new conversation with a request in its + // composer, appended to the draft of a reused blank conversation. + const startWithPrompt = (prompt: string): void => { + ctx.uiWorkspace.startSession(undefined, { prompt, whenDraftExists: 'append' }) + } yield ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL_ID, @@ -222,7 +227,8 @@ export function apply(ctx: ClientContext): void { store: createEditorStore(), inject: (): TaskManagerInjected => ({ ...detail, - onNewTask: () => { ctx.uiWorkspace.startSession(undefined, { prompt: t('host.createPrompt'), whenDraftExists: 'append' }) }, + onNewTask: () => { startWithPrompt(t('host.createPrompt')) }, + onUseRecommendation: startWithPrompt, onClearEnded: async () => { const outcome = await clearEnded() deleteToast.reportClear(outcome) diff --git a/packages/client/ui-schedule/src/client/recent-time-zones.ts b/packages/client/ui-schedule/src/client/recent-time-zones.ts index ae7474f48b..409ab1e40b 100644 --- a/packages/client/ui-schedule/src/client/recent-time-zones.ts +++ b/packages/client/ui-schedule/src/client/recent-time-zones.ts @@ -38,7 +38,7 @@ export function rememberTimeZone(recent: readonly string[], zone: string): reado if (typeof localStorage !== 'undefined') { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)) - } catch { + } catch (_storageUnavailable) { // A private or full browser store must not block editing the rule. } } diff --git a/packages/client/ui-schedule/src/client/recommendation-locales.ts b/packages/client/ui-schedule/src/client/recommendation-locales.ts new file mode 100644 index 0000000000..ec965a647a --- /dev/null +++ b/packages/client/ui-schedule/src/client/recommendation-locales.ts @@ -0,0 +1,265 @@ +/** Copy for the recommended tasks shown in the empty task catalog. */ + +/** English recommendation copy. */ +export const recommendationEn = { + 'recommend.heading': 'Recommended', + 'recommend.dailyBrief.title': 'Daily brief', + 'recommend.dailyBrief.description': 'Recent changes in the workspace and what needs follow-up, with what to do first today.', + 'recommend.dailyBrief.schedule': 'Weekdays at 9:00', + 'recommend.dailyBrief.prompt': 'Create an automation task named "Daily brief": every weekday at 9:00, review the last 24 hours of changes in the current workspace and list what needs my follow-up and what to do first today; when the workspace is a code repository, also cover new commits, pull requests awaiting my review, and failing CI.', + 'recommend.issueScan.title': 'Issue scan', + 'recommend.issueScan.description': 'Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply.', + 'recommend.issueScan.schedule': 'Weekdays at 10:00', + 'recommend.issueScan.prompt': 'Create an automation task named "Issue scan": every weekday at 10:00, scan new issues in the current workspace repository, sort them into bugs, requests, and questions, and flag duplicates and ones that need my reply. Summarize here only; do not reply on GitHub.', + 'recommend.pluginCompat.title': 'Plugin compatibility check', + 'recommend.pluginCompat.description': 'When a new DSH version ships, check whether installed and self-made plugins need changes.', + 'recommend.pluginCompat.schedule': 'Daily at 10:00', + 'recommend.pluginCompat.prompt': 'Create an automation task named "Plugin compatibility check": every day at 10:00, check whether a new DSH version is available; if so, read its upgrade guide, check whether each non-official or self-made plugin I have installed is affected, and list what to change and how.', + 'recommend.topicTracking.title': 'Topic and paper tracking', + 'recommend.topicTracking.description': 'Search for news and new arXiv papers on chosen topics and list the key points.', + 'recommend.topicTracking.schedule': 'Daily at 9:00', + 'recommend.topicTracking.prompt': 'Create an automation task named "Topic and paper tracking": every day at 9:00, search for new articles and arXiv papers on the topics I follow and list a few key points for each. Before creating it, ask me for the topics, keywords, and sources.', + 'recommend.branchCleanup.title': 'Branch and worktree cleanup', + 'recommend.branchCleanup.description': 'List local branches and worktrees whose pull requests merged or closed, and delete them after confirmation.', + 'recommend.branchCleanup.schedule': 'Fridays at 17:00', + 'recommend.branchCleanup.prompt': 'Create an automation task named "Branch and worktree cleanup": every Friday at 17:00, list local branches and worktrees in the current workspace whose pull requests are merged or closed, and delete them only after I confirm.', + 'recommend.weather.title': 'Weather and travel', + 'recommend.weather.description': 'Weather for today and the next three days, with a note when an umbrella or warmer clothes are needed.', + 'recommend.weather.schedule': 'Daily at 7:30', + 'recommend.weather.prompt': 'Create an automation task named "Weather and travel": every day at 7:30, tell me the weather in my city for today and the next three days, and call out when I should bring an umbrella, dress warmer, or expect travel disruption. Before creating it, ask me for my city.', + 'recommend.workout.title': 'Weekly workout plan', + 'recommend.workout.description': 'Plan next week\'s workouts around your goals and training days.', + 'recommend.workout.schedule': 'Sundays at 20:00', + 'recommend.workout.prompt': 'Create an automation task named "Weekly workout plan": every Sunday at 20:00, plan my workouts for next week around my goals and the days I can train, without asking me anything when it runs. Before creating it, ask me about my goals, how many days a week I can train, which days I am free, and where I train.', +} as const + +/** Simplified Chinese recommendation copy. */ +export const recommendationZh: Record = { + 'recommend.heading': '推荐', + 'recommend.dailyBrief.title': '每日简报', + 'recommend.dailyBrief.description': '汇总工作区最近的变化和待跟进的事,列出今天先做什么。', + 'recommend.dailyBrief.schedule': '工作日 9:00', + 'recommend.dailyBrief.prompt': '创建一个名为「每日简报」的自动化任务:每个工作日 9:00 查看当前工作区过去 24 小时的变化,列出需要我跟进的事和今天先做的事;工作区是代码仓库时,也看新提交、待我评审的 PR 和失败的 CI。', + 'recommend.issueScan.title': 'Issue 扫描', + 'recommend.issueScan.description': '把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。', + 'recommend.issueScan.schedule': '工作日 10:00', + 'recommend.issueScan.prompt': '创建一个名为「Issue 扫描」的自动化任务:每个工作日 10:00 扫描当前工作区仓库新开的 issue,分成 bug、需求、提问,标出重复的和需要我回复的,只在这里汇总,不在 GitHub 上回复。', + 'recommend.pluginCompat.title': '插件兼容检查', + 'recommend.pluginCompat.description': 'DSH 出新版本时,检查已装的插件和自己做的插件要不要改。', + 'recommend.pluginCompat.schedule': '每天 10:00', + 'recommend.pluginCompat.prompt': '创建一个名为「插件兼容检查」的自动化任务:每天 10:00 检查 DSH 有没有新版本;有的话读这个版本的升级指引,逐个检查我装的非官方插件和自己做的插件会不会受影响,列出要改的地方和改法。', + 'recommend.topicTracking.title': '主题和论文追踪', + 'recommend.topicTracking.description': '搜索关注主题的新消息和 arXiv 新论文,各列几条要点。', + 'recommend.topicTracking.schedule': '每天 9:00', + 'recommend.topicTracking.prompt': '创建一个名为「主题和论文追踪」的自动化任务:每天 9:00 搜索我关注主题的新消息和 arXiv 新论文,各列几条要点。创建前先问我主题、关键词和来源。', + 'recommend.branchCleanup.title': '分支和 worktree 清理', + 'recommend.branchCleanup.description': '列出 PR 已合并或关闭的本地分支和 worktree,确认后再删。', + 'recommend.branchCleanup.schedule': '周五 17:00', + 'recommend.branchCleanup.prompt': '创建一个名为「分支和 worktree 清理」的自动化任务:每周五 17:00 列出当前工作区里 PR 已合并或关闭的本地分支和 worktree,我确认后再删。', + 'recommend.weather.title': '天气和出行', + 'recommend.weather.description': '今天和接下来三天的天气,要带伞或加衣时提一句。', + 'recommend.weather.schedule': '每天 7:30', + 'recommend.weather.prompt': '创建一个名为「天气和出行」的自动化任务:每天 7:30 告诉我所在城市今天和接下来三天的天气,要带伞、加衣或出行受影响时单独提一句。创建前先问我城市。', + 'recommend.workout.title': '一周运动计划', + 'recommend.workout.description': '按目标和每周能练的日子排好下周的运动计划。', + 'recommend.workout.schedule': '周日 20:00', + 'recommend.workout.prompt': '创建一个名为「一周运动计划」的自动化任务:每周日 20:00 按我的目标和每周能练的日子排好下周的运动计划,运行时不再问我。创建前先问我目标、每周能练几天、哪几天有空、在哪练。', +} + +/** Japanese recommendation copy. */ +export const recommendationJa: Record = { + 'recommend.heading': 'おすすめ', + 'recommend.dailyBrief.title': 'デイリーブリーフィング', + 'recommend.dailyBrief.description': 'ワークスペースの最近の変化とフォローが必要なことをまとめ、今日最初にやることを挙げます。', + 'recommend.dailyBrief.schedule': '平日 9:00', + 'recommend.dailyBrief.prompt': '「デイリーブリーフィング」という名前の自動化タスクを作成してください。平日は毎日 9:00 に、現在のワークスペースの過去24時間の変化を確認し、私がフォローすべきことと今日最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、新しいコミット、私のレビュー待ちのプルリクエスト、失敗した CI も確認してください。', + 'recommend.issueScan.title': 'Issue スキャン', + 'recommend.issueScan.description': '新しい Issue をバグ・要望・質問に分類し、重複しているものと返信が必要なものを指摘します。', + 'recommend.issueScan.schedule': '平日 10:00', + 'recommend.issueScan.prompt': '「Issue スキャン」という名前の自動化タスクを作成してください。平日は毎日 10:00 に、現在のワークスペースのリポジトリで新しい Issue をスキャンし、バグ・要望・質問に分類して、重複しているものと私の返信が必要なものを指摘してください。まとめはここでだけ行い、GitHub では返信しないでください。', + 'recommend.pluginCompat.title': 'プラグイン互換性チェック', + 'recommend.pluginCompat.description': 'DSH の新しいバージョンが出たら、インストール済みのプラグインや自作のプラグインに変更が必要か確認します。', + 'recommend.pluginCompat.schedule': '毎日 10:00', + 'recommend.pluginCompat.prompt': '「プラグイン互換性チェック」という名前の自動化タスクを作成してください。毎日 10:00 に DSH の新しいバージョンが出ているか確認し、出ていればそのアップグレードガイドを読んで、私がインストールした非公式プラグインや自作プラグインが影響を受けるかを一つずつ調べ、変更が必要な箇所と変更方法を挙げてください。', + 'recommend.topicTracking.title': 'トピックと論文の追跡', + 'recommend.topicTracking.description': '選んだトピックのニュースと arXiv の新しい論文を検索し、要点を挙げます。', + 'recommend.topicTracking.schedule': '毎日 9:00', + 'recommend.topicTracking.prompt': '「トピックと論文の追跡」という名前の自動化タスクを作成してください。毎日 9:00 に、私がフォローしているトピックについて新しい記事と arXiv の新しい論文を検索し、それぞれ要点をいくつか挙げてください。作成する前に、トピック、キーワード、情報源を私に聞いてください。', + 'recommend.branchCleanup.title': 'ブランチと worktree の整理', + 'recommend.branchCleanup.description': 'プルリクエストがマージまたはクローズされたローカルブランチと worktree を一覧にし、確認後に削除します。', + 'recommend.branchCleanup.schedule': '毎週金曜日 17:00', + 'recommend.branchCleanup.prompt': '「ブランチと worktree の整理」という名前の自動化タスクを作成してください。毎週金曜日の 17:00 に、現在のワークスペースで、プルリクエストがマージ済みまたはクローズ済みのローカルブランチと worktree を一覧にし、削除は私が確認してから行ってください。', + 'recommend.weather.title': '天気とお出かけ', + 'recommend.weather.description': '今日と今後3日間の天気を伝え、傘や暖かい服装が必要なときはひと言添えます。', + 'recommend.weather.schedule': '毎日 7:30', + 'recommend.weather.prompt': '「天気とお出かけ」という名前の自動化タスクを作成してください。毎日 7:30 に、私のいる都市の今日と今後3日間の天気を教えてください。傘を持っていくべきとき、暖かい服装にすべきとき、交通の乱れが予想されるときは、そのことをひと言添えてください。作成する前に、私のいる都市を聞いてください。', + 'recommend.workout.title': '1週間の運動プラン', + 'recommend.workout.description': '目標と運動できる曜日に合わせて、翌週の運動プランを立てます。', + 'recommend.workout.schedule': '毎週日曜日 20:00', + 'recommend.workout.prompt': '「1週間の運動プラン」という名前の自動化タスクを作成してください。毎週日曜日の 20:00 に、私の目標と運動できる曜日に合わせて翌週の運動プランを立ててください。実行時には私に質問しないでください。作成する前に、目標、週に何日運動できるか、何曜日が空いているか、どこで運動するかを私に聞いてください。', +} + +/** Spanish recommendation copy. */ +export const recommendationEs: Record = { + 'recommend.heading': 'Recomendadas', + 'recommend.dailyBrief.title': 'Resumen diario', + 'recommend.dailyBrief.description': 'Cambios recientes en el espacio de trabajo y pendientes de seguimiento, con lo primero que hacer hoy.', + 'recommend.dailyBrief.schedule': 'De lunes a viernes a las 9:00', + 'recommend.dailyBrief.prompt': 'Crea una tarea de automatización llamada «Resumen diario»: de lunes a viernes a las 9:00, revisa los cambios de las últimas 24 horas en el espacio de trabajo actual y enumera lo que requiere mi seguimiento y lo primero que debo hacer hoy; si el espacio de trabajo es un repositorio de código, incluye también los commits nuevos, los pull requests pendientes de mi revisión y los fallos de CI.', + 'recommend.issueScan.title': 'Revisión de issues', + 'recommend.issueScan.description': 'Clasifica los issues nuevos en bugs, solicitudes y preguntas, y señala los duplicados y los que necesitan respuesta.', + 'recommend.issueScan.schedule': 'De lunes a viernes a las 10:00', + 'recommend.issueScan.prompt': 'Crea una tarea de automatización llamada «Revisión de issues»: de lunes a viernes a las 10:00, revisa los issues nuevos del repositorio del espacio de trabajo actual, clasifícalos en bugs, solicitudes y preguntas, y señala los duplicados y los que necesitan mi respuesta. Haz el resumen solo aquí; no respondas en GitHub.', + 'recommend.pluginCompat.title': 'Compatibilidad de complementos', + 'recommend.pluginCompat.description': 'Cuando sale una nueva versión de DSH, comprueba si los complementos instalados y los que has creado necesitan cambios.', + 'recommend.pluginCompat.schedule': 'Diariamente a las 10:00', + 'recommend.pluginCompat.prompt': 'Crea una tarea de automatización llamada «Compatibilidad de complementos»: todos los días a las 10:00, comprueba si hay una nueva versión de DSH; si la hay, lee su guía de actualización, revisa uno por uno si los complementos no oficiales o creados por mí que tengo instalados se ven afectados, y enumera qué hay que cambiar y cómo.', + 'recommend.topicTracking.title': 'Seguimiento de temas y artículos', + 'recommend.topicTracking.description': 'Busca noticias y artículos nuevos de arXiv sobre los temas elegidos y enumera los puntos clave.', + 'recommend.topicTracking.schedule': 'Diariamente a las 9:00', + 'recommend.topicTracking.prompt': 'Crea una tarea de automatización llamada «Seguimiento de temas y artículos»: todos los días a las 9:00, busca noticias y artículos nuevos de arXiv sobre los temas que sigo y enumera algunos puntos clave de cada uno. Antes de crearla, pregúntame por los temas, las palabras clave y las fuentes.', + 'recommend.branchCleanup.title': 'Limpieza de ramas y worktrees', + 'recommend.branchCleanup.description': 'Enumera las ramas locales y los worktrees cuyos pull requests se fusionaron o cerraron, y los elimina previa confirmación.', + 'recommend.branchCleanup.schedule': 'Los viernes a las 17:00', + 'recommend.branchCleanup.prompt': 'Crea una tarea de automatización llamada «Limpieza de ramas y worktrees»: todos los viernes a las 17:00, enumera las ramas locales y los worktrees del espacio de trabajo actual cuyos pull requests están fusionados o cerrados, y elimínalos solo después de que yo lo confirme.', + 'recommend.weather.title': 'Clima y desplazamientos', + 'recommend.weather.description': 'El clima de hoy y de los próximos tres días, con un aviso cuando haga falta paraguas o más abrigo.', + 'recommend.weather.schedule': 'Diariamente a las 7:30', + 'recommend.weather.prompt': 'Crea una tarea de automatización llamada «Clima y desplazamientos»: todos los días a las 7:30, dime el clima de mi ciudad para hoy y los próximos tres días, y avísame cuando deba llevar paraguas, abrigarme más o esperar problemas en los desplazamientos. Antes de crearla, pregúntame cuál es mi ciudad.', + 'recommend.workout.title': 'Plan de entrenamiento semanal', + 'recommend.workout.description': 'Planifica los entrenamientos de la próxima semana según tus objetivos y tus días de entrenamiento.', + 'recommend.workout.schedule': 'Los domingos a las 20:00', + 'recommend.workout.prompt': 'Crea una tarea de automatización llamada «Plan de entrenamiento semanal»: todos los domingos a las 20:00, planifica mis entrenamientos de la próxima semana según mis objetivos y los días en que puedo entrenar, sin preguntarme nada cuando se ejecute. Antes de crearla, pregúntame por mis objetivos, cuántos días a la semana puedo entrenar, qué días tengo libres y dónde entreno.', +} + +/** French recommendation copy. */ +export const recommendationFr: Record = { + 'recommend.heading': 'Recommandées', + 'recommend.dailyBrief.title': 'Résumé quotidien', + 'recommend.dailyBrief.description': 'Changements récents dans l\'espace de travail et points à suivre, avec les priorités du jour.', + 'recommend.dailyBrief.schedule': 'Du lundi au vendredi à 9:00', + 'recommend.dailyBrief.prompt': 'Crée une tâche d\'automatisation nommée « Résumé quotidien » : du lundi au vendredi à 9:00, passe en revue les changements des dernières 24 heures dans l\'espace de travail actuel et liste ce qui demande mon suivi et ce que je dois faire en premier aujourd\'hui ; si l\'espace de travail est un dépôt de code, couvre aussi les nouveaux commits, les pull requests en attente de ma revue et les échecs de CI.', + 'recommend.issueScan.title': 'Analyse des issues', + 'recommend.issueScan.description': 'Trie les nouvelles issues en bugs, demandes et questions, et signale les doublons et celles qui nécessitent une réponse.', + 'recommend.issueScan.schedule': 'Du lundi au vendredi à 10:00', + 'recommend.issueScan.prompt': 'Crée une tâche d\'automatisation nommée « Analyse des issues » : du lundi au vendredi à 10:00, analyse les nouvelles issues du dépôt de l\'espace de travail actuel, trie-les en bugs, demandes et questions, et signale les doublons et celles qui nécessitent ma réponse. Fais le résumé ici uniquement ; ne réponds pas sur GitHub.', + 'recommend.pluginCompat.title': 'Compatibilité des plugins', + 'recommend.pluginCompat.description': 'Quand une nouvelle version de DSH sort, vérifie si les plugins installés et ceux faits maison doivent être modifiés.', + 'recommend.pluginCompat.schedule': 'Tous les jours à 10:00', + 'recommend.pluginCompat.prompt': 'Crée une tâche d\'automatisation nommée « Compatibilité des plugins » : tous les jours à 10:00, vérifie si une nouvelle version de DSH est disponible ; si oui, lis son guide de mise à niveau, examine pour chaque plugin non officiel ou fait maison que j\'ai installé s\'il est concerné, et liste ce qu\'il faut modifier et comment.', + 'recommend.topicTracking.title': 'Suivi de sujets et d\'articles', + 'recommend.topicTracking.description': 'Recherche les actualités et les nouveaux articles arXiv sur les sujets choisis, et liste les points clés.', + 'recommend.topicTracking.schedule': 'Tous les jours à 9:00', + 'recommend.topicTracking.prompt': 'Crée une tâche d\'automatisation nommée « Suivi de sujets et d\'articles » : tous les jours à 9:00, recherche les actualités et les nouveaux articles arXiv sur les sujets que je suis, et liste quelques points clés pour chacun. Avant de la créer, demande-moi les sujets, les mots-clés et les sources.', + 'recommend.branchCleanup.title': 'Nettoyage des branches et worktrees', + 'recommend.branchCleanup.description': 'Liste les branches et worktrees locaux dont les pull requests sont fusionnées ou fermées, et les supprime après confirmation.', + 'recommend.branchCleanup.schedule': 'Le vendredi à 17:00', + 'recommend.branchCleanup.prompt': 'Crée une tâche d\'automatisation nommée « Nettoyage des branches et worktrees » : tous les vendredis à 17:00, liste les branches locales et les worktrees de l\'espace de travail actuel dont les pull requests sont fusionnées ou fermées, et ne les supprime qu\'après ma confirmation.', + 'recommend.weather.title': 'Météo et déplacements', + 'recommend.weather.description': 'Météo du jour et des trois prochains jours, avec un rappel s\'il faut un parapluie ou des vêtements plus chauds.', + 'recommend.weather.schedule': 'Tous les jours à 7:30', + 'recommend.weather.prompt': 'Crée une tâche d\'automatisation nommée « Météo et déplacements » : tous les jours à 7:30, donne-moi la météo de ma ville pour aujourd\'hui et les trois prochains jours, et préviens-moi quand je dois prendre un parapluie, me couvrir davantage ou m\'attendre à des perturbations dans les transports. Avant de la créer, demande-moi ma ville.', + 'recommend.workout.title': 'Plan d\'entraînement hebdomadaire', + 'recommend.workout.description': 'Planifie les entraînements de la semaine prochaine selon tes objectifs et tes jours d\'entraînement.', + 'recommend.workout.schedule': 'Le dimanche à 20:00', + 'recommend.workout.prompt': 'Crée une tâche d\'automatisation nommée « Plan d\'entraînement hebdomadaire » : tous les dimanches à 20:00, planifie mes entraînements de la semaine suivante en fonction de mes objectifs et des jours où je peux m\'entraîner, sans me poser de question pendant l\'exécution. Avant de la créer, demande-moi mes objectifs, combien de jours par semaine je peux m\'entraîner, quels jours je suis libre et où je m\'entraîne.', +} + +/** German recommendation copy. */ +export const recommendationDe: Record = { + 'recommend.heading': 'Empfohlen', + 'recommend.dailyBrief.title': 'Tagesüberblick', + 'recommend.dailyBrief.description': 'Aktuelle Änderungen im Arbeitsbereich und offene Punkte, dazu, was heute zuerst ansteht.', + 'recommend.dailyBrief.schedule': 'Mo–Fr um 9:00', + 'recommend.dailyBrief.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Tagesüberblick“: Prüfe montags bis freitags um 9:00 Uhr die Änderungen der letzten 24 Stunden im aktuellen Arbeitsbereich und liste auf, was ich nachverfolgen muss und was heute zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige auch neue Commits, auf mein Review wartende Pull Requests und fehlgeschlagene CI-Läufe.', + 'recommend.issueScan.title': 'Issue-Sichtung', + 'recommend.issueScan.description': 'Sortiert neue Issues in Bugs, Feature-Wünsche und Fragen und hebt Duplikate sowie Issues hervor, die eine Antwort brauchen.', + 'recommend.issueScan.schedule': 'Mo–Fr um 10:00', + 'recommend.issueScan.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Issue-Sichtung“: Sichte montags bis freitags um 10:00 Uhr die neuen Issues im Repository des aktuellen Arbeitsbereichs, sortiere sie in Bugs, Feature-Wünsche und Fragen und hebe Duplikate sowie Issues hervor, die meine Antwort brauchen. Fasse alles nur hier zusammen; antworte nicht auf GitHub.', + 'recommend.pluginCompat.title': 'Plugin-Kompatibilitätsprüfung', + 'recommend.pluginCompat.description': 'Prüft, sobald eine neue DSH-Version erscheint, ob installierte und selbst erstellte Plugins angepasst werden müssen.', + 'recommend.pluginCompat.schedule': 'Täglich um 10:00', + 'recommend.pluginCompat.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Plugin-Kompatibilitätsprüfung“: Prüfe täglich um 10:00 Uhr, ob eine neue DSH-Version verfügbar ist; falls ja, lies die zugehörige Upgrade-Anleitung, prüfe für jedes nicht offizielle oder selbst erstellte Plugin, das ich installiert habe, ob es betroffen ist, und liste auf, was zu ändern ist und wie.', + 'recommend.topicTracking.title': 'Themen- und Paper-Tracking', + 'recommend.topicTracking.description': 'Sucht Neuigkeiten und neue arXiv-Paper zu ausgewählten Themen und listet die wichtigsten Punkte auf.', + 'recommend.topicTracking.schedule': 'Täglich um 9:00', + 'recommend.topicTracking.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Themen- und Paper-Tracking“: Suche täglich um 9:00 Uhr neue Artikel und arXiv-Paper zu den Themen, die ich verfolge, und liste zu jedem ein paar Kernpunkte auf. Frag mich vor dem Erstellen nach den Themen, Stichwörtern und Quellen.', + 'recommend.branchCleanup.title': 'Branch- und Worktree-Bereinigung', + 'recommend.branchCleanup.description': 'Listet lokale Branches und Worktrees mit gemergten oder geschlossenen Pull Requests auf und löscht sie nach Bestätigung.', + 'recommend.branchCleanup.schedule': 'Freitags um 17:00', + 'recommend.branchCleanup.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Branch- und Worktree-Bereinigung“: Liste freitags um 17:00 Uhr die lokalen Branches und Worktrees im aktuellen Arbeitsbereich auf, deren Pull Requests gemergt oder geschlossen sind, und lösche sie erst, nachdem ich es bestätigt habe.', + 'recommend.weather.title': 'Wetter und Verkehr', + 'recommend.weather.description': 'Das Wetter für heute und die nächsten drei Tage, mit Hinweis, wenn ein Schirm oder wärmere Kleidung nötig ist.', + 'recommend.weather.schedule': 'Täglich um 7:30', + 'recommend.weather.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wetter und Verkehr“: Sag mir täglich um 7:30 Uhr das Wetter in meiner Stadt für heute und die nächsten drei Tage und weise mich darauf hin, wenn ich einen Schirm mitnehmen, mich wärmer anziehen oder mit Verkehrsbehinderungen rechnen sollte. Frag mich vor dem Erstellen nach meiner Stadt.', + 'recommend.workout.title': 'Wöchentlicher Trainingsplan', + 'recommend.workout.description': 'Plant die Trainingseinheiten der nächsten Woche passend zu deinen Zielen und Trainingstagen.', + 'recommend.workout.schedule': 'Sonntags um 20:00', + 'recommend.workout.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wöchentlicher Trainingsplan“: Plane sonntags um 20:00 Uhr meine Trainingseinheiten für die nächste Woche passend zu meinen Zielen und den Tagen, an denen ich trainieren kann, ohne mich bei der Ausführung etwas zu fragen. Frag mich vor dem Erstellen nach meinen Zielen, wie viele Tage pro Woche ich trainieren kann, an welchen Tagen ich frei bin und wo ich trainiere.', +} + +/** Russian recommendation copy. */ +export const recommendationRu: Record = { + 'recommend.heading': 'Рекомендуемые', + 'recommend.dailyBrief.title': 'Ежедневная сводка', + 'recommend.dailyBrief.description': 'Недавние изменения в рабочей области и то, что требует внимания, а также первоочередные дела на сегодня.', + 'recommend.dailyBrief.schedule': 'По будням в 9:00', + 'recommend.dailyBrief.prompt': 'Создай задачу автоматизации под названием «Ежедневная сводка»: по будням в 9:00 просматривай изменения в текущей рабочей области за последние 24 часа и перечисляй, что требует моего внимания и с чего начать сегодня; если рабочая область — репозиторий кода, учитывай также новые коммиты, пул-реквесты, ожидающие моего ревью, и сбои CI.', + 'recommend.issueScan.title': 'Обзор issues', + 'recommend.issueScan.description': 'Делит новые issues на баги, пожелания и вопросы и выделяет дубликаты и те, на которые нужно ответить.', + 'recommend.issueScan.schedule': 'По будням в 10:00', + 'recommend.issueScan.prompt': 'Создай задачу автоматизации под названием «Обзор issues»: по будням в 10:00 просматривай новые issues в репозитории текущего рабочего пространства, дели их на баги, пожелания и вопросы и выделяй дубликаты и те, на которые нужен мой ответ. Сводку пиши только здесь; на GitHub не отвечай.', + 'recommend.pluginCompat.title': 'Проверка совместимости плагинов', + 'recommend.pluginCompat.description': 'При выходе новой версии DSH проверяет, нужно ли изменить установленные и созданные вами плагины.', + 'recommend.pluginCompat.schedule': 'Ежедневно в 10:00', + 'recommend.pluginCompat.prompt': 'Создай задачу автоматизации под названием «Проверка совместимости плагинов»: ежедневно в 10:00 проверяй, вышла ли новая версия DSH; если да, прочитай её руководство по обновлению, выясни, затронут ли каждый установленный у меня неофициальный или созданный мной плагин, и перечисли, что и как нужно изменить.', + 'recommend.topicTracking.title': 'Отслеживание тем и статей', + 'recommend.topicTracking.description': 'Ищет новости и новые статьи на arXiv по выбранным темам и перечисляет ключевые моменты.', + 'recommend.topicTracking.schedule': 'Ежедневно в 9:00', + 'recommend.topicTracking.prompt': 'Создай задачу автоматизации под названием «Отслеживание тем и статей»: ежедневно в 9:00 ищи новости и новые статьи на arXiv по темам, за которыми я слежу, и перечисляй по каждой несколько ключевых моментов. Перед созданием спроси у меня темы, ключевые слова и источники.', + 'recommend.branchCleanup.title': 'Очистка веток и worktrees', + 'recommend.branchCleanup.description': 'Перечисляет локальные ветки и worktrees, чьи пул-реквесты слиты или закрыты, и удаляет их после подтверждения.', + 'recommend.branchCleanup.schedule': 'По пятницам в 17:00', + 'recommend.branchCleanup.prompt': 'Создай задачу автоматизации под названием «Очистка веток и worktrees»: по пятницам в 17:00 перечисляй локальные ветки и worktrees в текущем рабочем пространстве, чьи пул-реквесты слиты или закрыты, и удаляй их только после моего подтверждения.', + 'recommend.weather.title': 'Погода и поездки', + 'recommend.weather.description': 'Погода на сегодня и ближайшие три дня, с пометкой, когда нужен зонт или одежда потеплее.', + 'recommend.weather.schedule': 'Ежедневно в 7:30', + 'recommend.weather.prompt': 'Создай задачу автоматизации под названием «Погода и поездки»: ежедневно в 7:30 сообщай мне погоду в моём городе на сегодня и ближайшие три дня и отдельно предупреждай, если стоит взять зонт, одеться теплее или ожидать проблем с транспортом. Перед созданием спроси у меня, в каком я городе.', + 'recommend.workout.title': 'План тренировок на неделю', + 'recommend.workout.description': 'Составляет план тренировок на следующую неделю с учётом целей и дней для тренировок.', + 'recommend.workout.schedule': 'По воскресеньям в 20:00', + 'recommend.workout.prompt': 'Создай задачу автоматизации под названием «План тренировок на неделю»: по воскресеньям в 20:00 составляй мне план тренировок на следующую неделю с учётом моих целей и дней, когда я могу тренироваться, ничего не спрашивая у меня во время запуска. Перед созданием спроси у меня о целях, сколько дней в неделю я могу тренироваться, в какие дни я свободен и где тренируюсь.', +} + +/** Portuguese recommendation copy. */ +export const recommendationPt: Record = { + 'recommend.heading': 'Recomendadas', + 'recommend.dailyBrief.title': 'Resumo diário', + 'recommend.dailyBrief.description': 'Mudanças recentes no espaço de trabalho e o que precisa de acompanhamento, com o que fazer primeiro hoje.', + 'recommend.dailyBrief.schedule': 'Segunda a sexta às 9:00', + 'recommend.dailyBrief.prompt': 'Crie uma tarefa de automação chamada “Resumo diário”: de segunda a sexta às 9:00, revise as mudanças das últimas 24 horas no espaço de trabalho atual e liste o que precisa do meu acompanhamento e o que fazer primeiro hoje; se o espaço de trabalho for um repositório de código, inclua também os novos commits, os pull requests aguardando minha revisão e as falhas de CI.', + 'recommend.issueScan.title': 'Varredura de issues', + 'recommend.issueScan.description': 'Classifica as novas issues em bugs, solicitações e perguntas e destaca as duplicadas e as que precisam de resposta.', + 'recommend.issueScan.schedule': 'Segunda a sexta às 10:00', + 'recommend.issueScan.prompt': 'Crie uma tarefa de automação chamada “Varredura de issues”: de segunda a sexta às 10:00, faça uma varredura nas novas issues do repositório do espaço de trabalho atual, classifique-as em bugs, solicitações e perguntas e destaque as duplicadas e as que precisam da minha resposta. Faça o resumo só aqui; não responda no GitHub.', + 'recommend.pluginCompat.title': 'Compatibilidade de plug-ins', + 'recommend.pluginCompat.description': 'Quando sai uma nova versão do DSH, verifica se os plug-ins instalados e os criados por você precisam de ajustes.', + 'recommend.pluginCompat.schedule': 'Diariamente às 10:00', + 'recommend.pluginCompat.prompt': 'Crie uma tarefa de automação chamada “Compatibilidade de plug-ins”: todos os dias às 10:00, verifique se há uma nova versão do DSH; se houver, leia o guia de atualização dessa versão, confira um a um se os plug-ins não oficiais ou criados por mim que tenho instalados são afetados e liste o que mudar e como.', + 'recommend.topicTracking.title': 'Acompanhamento de temas e artigos', + 'recommend.topicTracking.description': 'Busca notícias e novos artigos do arXiv sobre os temas escolhidos e lista os pontos principais.', + 'recommend.topicTracking.schedule': 'Diariamente às 9:00', + 'recommend.topicTracking.prompt': 'Crie uma tarefa de automação chamada “Acompanhamento de temas e artigos”: todos os dias às 9:00, busque notícias e novos artigos do arXiv sobre os temas que eu acompanho e liste alguns pontos principais de cada um. Antes de criá-la, me pergunte quais são os temas, as palavras-chave e as fontes.', + 'recommend.branchCleanup.title': 'Limpeza de branches e worktrees', + 'recommend.branchCleanup.description': 'Lista as branches locais e os worktrees cujos pull requests foram mesclados ou fechados e os exclui após confirmação.', + 'recommend.branchCleanup.schedule': 'Sextas às 17:00', + 'recommend.branchCleanup.prompt': 'Crie uma tarefa de automação chamada “Limpeza de branches e worktrees”: toda sexta-feira às 17:00, liste as branches locais e os worktrees do espaço de trabalho atual cujos pull requests foram mesclados ou fechados, e exclua-os só depois que eu confirmar.', + 'recommend.weather.title': 'Clima e deslocamentos', + 'recommend.weather.description': 'O clima de hoje e dos próximos três dias, com um aviso quando for preciso guarda-chuva ou mais agasalho.', + 'recommend.weather.schedule': 'Diariamente às 7:30', + 'recommend.weather.prompt': 'Crie uma tarefa de automação chamada “Clima e deslocamentos”: todos os dias às 7:30, me diga o clima da minha cidade para hoje e os próximos três dias e avise quando eu precisar levar guarda-chuva, me agasalhar mais ou me preparar para problemas nos deslocamentos. Antes de criá-la, me pergunte qual é a minha cidade.', + 'recommend.workout.title': 'Plano de treino semanal', + 'recommend.workout.description': 'Planeja os treinos da próxima semana de acordo com seus objetivos e dias de treino.', + 'recommend.workout.schedule': 'Domingos às 20:00', + 'recommend.workout.prompt': 'Crie uma tarefa de automação chamada “Plano de treino semanal”: todo domingo às 20:00, planeje meus treinos da próxima semana de acordo com meus objetivos e os dias em que posso treinar, sem me perguntar nada durante a execução. Antes de criá-la, me pergunte quais são meus objetivos, quantos dias por semana posso treinar, quais dias tenho livres e onde treino.', +} diff --git a/packages/client/ui-schedule/src/client/session-schedule-state.ts b/packages/client/ui-schedule/src/client/session-schedule-state.ts index cc27321f00..4f8bd03fe4 100644 --- a/packages/client/ui-schedule/src/client/session-schedule-state.ts +++ b/packages/client/ui-schedule/src/client/session-schedule-state.ts @@ -2,7 +2,7 @@ * One Session's scheduled-task state for its header, Sidebar row mark, and hover card. * * These views project the Host catalog the page already owns — `schedule/catalog()` - * returns every Host task with its target and involved Sessions — so N + * returns every Host task with its delivery target — so N * visible rows share one Remote read and follow one `schedule/changed` * invalidation instead of issuing a query per row or header. */ @@ -10,7 +10,6 @@ import type { HostObservable, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ScheduleCatalogEntry } from '@deepseek-ai/dsh-schedule/client' -import { taskInvolvesSession } from './task-record.ts' import type { CatalogSnapshot } from './catalog-source.ts' /** Selector hook the renderer binds from a slot's `hooks.catalog` observable. */ @@ -30,15 +29,11 @@ export interface SessionScheduleFacts { const NO_RECORDS: readonly ScheduleCatalogEntry[] = [] /** - * Project the shared Host catalog onto one Session's active tasks. + * Select active tasks whose fixed delivery target is this Session. + * A Session with only paused or ended tasks has an empty list. * - * `schedule/catalog()` returns every Host task in every lifecycle state, so - * both facts come from this one snapshot filtered to the tasks that target or - * involve the Session with `status === 'active'`. A read that never settled - * answers no active task; a refresh republishes `loading` over the records of - * the last successful read, and the Host emits `schedule/changed` after every - * delivery, so following `status` here would blank a Session's mark for each - * roundtrip. A Session whose tasks are all paused or ended lists nothing. + * Refreshes use the last successful catalog so the clock stays visible + * while a delivery-triggered read is pending. * @param snapshot - shared Host catalog snapshot. * @param sessionId - Session whose facts are selected. * @returns this Session's active-task facts. @@ -49,7 +44,7 @@ export function selectSessionScheduleFacts( ): SessionScheduleFacts { if (!snapshot.settled) return { hasActive: false, records: NO_RECORDS } const records = snapshot.records.filter( - record => taskInvolvesSession(record, sessionId) && record.status === 'active', + record => record.status === 'active' && record.target.kind !== 'new' && record.target.sessionId === sessionId, ) return { hasActive: records.length > 0, records } } diff --git a/packages/client/ui-schedule/src/client/task-manager-locales.ts b/packages/client/ui-schedule/src/client/task-manager-locales.ts index 13ef7c9052..627141661c 100644 --- a/packages/client/ui-schedule/src/client/task-manager-locales.ts +++ b/packages/client/ui-schedule/src/client/task-manager-locales.ts @@ -1,4 +1,8 @@ /** Copy for the retained-reminder task manager's `schedule.manager` namespace. */ +import { + recommendationDe, recommendationEn, recommendationEs, recommendationFr, recommendationJa, recommendationPt, recommendationRu, + recommendationZh, +} from './recommendation-locales.ts' import { frequencyEn, frequencyJa, frequencyEs, frequencyFr, frequencyDe, frequencyRu, frequencyPt, frequencyZh } from './frequency-locales.ts' /** English task-manager dictionary and key domain. */ @@ -102,6 +106,7 @@ export const en = { 'frequency.once': 'Once', 'frequency.every': 'Every {value} {unit}', ...frequencyEn, + ...recommendationEn, 'timing.date': 'Date', 'timing.time': 'Time', 'timing.hour': 'Hour', @@ -268,6 +273,7 @@ export const zh: Record = { 'frequency.once': '仅一次', 'frequency.every': '每 {value} {unit}', ...frequencyZh, + ...recommendationZh, 'timing.date': '日期', 'timing.time': '时间', 'timing.hour': '时', @@ -331,6 +337,7 @@ export const zh: Record = { /** Japanese copy, checked against the English keys. */ export const ja = { ...frequencyJa, + ...recommendationJa, 'host.create': '作成', 'host.createMethod': '作成方法を選択', 'host.chatCreate': '会話で作成', @@ -544,6 +551,7 @@ export const es = { 'frequency.once': 'una vez', 'frequency.every': 'Cada {value} {unit}', ...frequencyEs, + ...recommendationEs, 'timing.date': 'Fecha', 'timing.time': 'tiempo', 'timing.hour': 'Hora', @@ -705,6 +713,7 @@ export const fr = { 'frequency.once': 'Une fois', 'frequency.every': 'Chaque {value} {unit}', ...frequencyFr, + ...recommendationFr, 'timing.date': 'Date', 'timing.time': 'Temps', 'timing.hour': 'Heure', @@ -866,6 +875,7 @@ export const de = { 'frequency.once': 'Einmal', 'frequency.every': 'Jeder {value} {unit}', ...frequencyDe, + ...recommendationDe, 'timing.date': 'Datum', 'timing.time': 'Zeit', 'timing.hour': 'Stunde', @@ -1027,6 +1037,7 @@ export const ru = { 'frequency.once': 'Однажды', 'frequency.every': 'Каждый {value} {unit}', ...frequencyRu, + ...recommendationRu, 'timing.date': 'Дата', 'timing.time': 'Время', 'timing.hour': 'Час', @@ -1188,6 +1199,7 @@ export const pt = { 'frequency.once': 'Uma vez', 'frequency.every': 'A cada {value} {unit}', ...frequencyPt, + ...recommendationPt, 'timing.date': 'Data', 'timing.time': 'Hora', 'timing.hour': 'Hora', diff --git a/packages/client/ui-schedule/src/client/task-record.ts b/packages/client/ui-schedule/src/client/task-record.ts index abb6a965f6..9321cbc8c5 100644 --- a/packages/client/ui-schedule/src/client/task-record.ts +++ b/packages/client/ui-schedule/src/client/task-record.ts @@ -20,15 +20,6 @@ export function taskSessionId(task: Pick { } }) + it('starts each recommendation in a new conversation with its single-line request in every language', async () => { + const sidebar = sidebarStubs() + const ctx = await baseContext(undefined, sidebar) + const owner = ctx.slots.register({ + name: 'root', + children: { + 'sidebar.right.pane.tab': { kind: 'keyed', scope: 'session' }, + 'sidebar.right.pane.tab.title': { kind: 'keyed', scope: 'session' }, + main: { kind: 'keyed', scope: 'root' }, + }, + } as never, Empty) + const startSession = vi.spyOn(ctx.uiWorkspace, 'startSession') + const fiber = ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + try { + const panel = injectedFace(ctx.slots.entries('main')[0]!, undefined as never) as TaskManagerInjected + for (const dictionary of Object.values(managerLocales)) { + const prompts = Object.entries(dictionary).filter(([key]) => key.startsWith('recommend.') && key.endsWith('.prompt')) + expect(prompts).toHaveLength(7) + for (const [, prompt] of prompts) { + expect(prompt).not.toContain('\n') + panel.onUseRecommendation(prompt) + expect(startSession).toHaveBeenLastCalledWith(undefined, { prompt, whenDraftExists: 'append' }) + } + } + expect(startSession).toHaveBeenCalledTimes(56) + } finally { + await fiber.dispose() + owner() + await ctx.fiber.dispose() + } + }) + + it('states each recommendation\'s shown run time in its request in every language', () => { + for (const dictionary of Object.values(managerLocales)) { + const schedules = Object.entries(dictionary).filter(([key]) => key.startsWith('recommend.') && key.endsWith('.schedule')) + expect(schedules).toHaveLength(7) + for (const [key, schedule] of schedules) { + const times = schedule.match(/\d{1,2}:\d{2}/g) + expect(times).toHaveLength(1) + // A digit boundary keeps 0:00 from matching inside 20:00. + expect(dictionary[key.replace(/schedule$/, 'prompt') as keyof typeof dictionary]) + .toMatch(new RegExp(`(? { const sidebar = sidebarStubs() const ctx = await baseContext(undefined, sidebar) diff --git a/packages/client/ui-schedule/tests/host-task-editor.client.spec.tsx b/packages/client/ui-schedule/tests/host-task-editor.client.spec.tsx index 0e43769d41..5567afb9d5 100644 --- a/packages/client/ui-schedule/tests/host-task-editor.client.spec.tsx +++ b/packages/client/ui-schedule/tests/host-task-editor.client.spec.tsx @@ -67,7 +67,7 @@ function mount(rows: readonly ScheduleCatalogEntry[] = [task], overrides: Partia useSessionStatus: select => select(new Map()), useSessionRetainInfo: () => undefined, useResource: () => { throw new Error('Task editor loads no document resources') }, useContextMenu: contextMenuHook(), - onNewTask: vi.fn(), onClearEnded: vi.fn(async () => {}), + onNewTask: vi.fn(), onUseRecommendation: vi.fn(), onClearEnded: vi.fn(async () => {}), onCreateTask: vi.fn(async () => ({ created: task })), onDelete: vi.fn(async () => 'deleted'), onRetry: vi.fn(async () => {}), onOpenSession: vi.fn(), hostActions: hostActions(), diff --git a/packages/client/ui-schedule/tests/session-schedule-state.client.spec.ts b/packages/client/ui-schedule/tests/session-schedule-state.client.spec.ts index 8cf7e0d7d7..aaf5e1f121 100644 --- a/packages/client/ui-schedule/tests/session-schedule-state.client.spec.ts +++ b/packages/client/ui-schedule/tests/session-schedule-state.client.spec.ts @@ -19,7 +19,7 @@ function catalogEntry(taskId: string, sessionId: string, status: Entry['status'] } /** - * A task whose every delivery creates a fresh Session; the Host leaves created Sessions out of `involvedSessionIds`. + * Build a `new` task with no fixed delivery Session. * @param taskId - task identity. * @param latestRun - Session that the latest delivery created, if one ran. * @returns an active per-run task created from {@link CREATOR}. @@ -45,28 +45,39 @@ function hostSnapshot( describe('shared Host catalog projection', () => { it('selects only the given Session’s active tasks from every lifecycle state', () => { - const mine = catalogEntry('mine', SESSION, 'active') - const other = catalogEntry('other', 'other-session', 'active') + const mine = { ...catalogEntry('mine', SESSION, 'active'), involvedSessionIds: [CREATOR, SESSION] } + const otherSession = 'other-session' as SessionId + const other = { ...catalogEntry('other', otherSession, 'active'), involvedSessionIds: [SESSION, otherSession] } const paused = catalogEntry('paused', SESSION, 'paused') const ended = catalogEntry('ended', SESSION, 'ended') const catalog = hostSnapshot('ready', [mine, other, paused, ended]) expect(selectSessionScheduleFacts(catalog, SESSION)).toEqual({ hasActive: true, records: [mine] }) - expect(selectSessionScheduleFacts(catalog, 'other-session' as SessionId)) + expect(selectSessionScheduleFacts(catalog, otherSession)) .toEqual({ hasActive: true, records: [other] }) - expect(selectSessionScheduleFacts(catalog, 'empty-session' as SessionId)) + expect(selectSessionScheduleFacts(catalog, CREATOR)) .toEqual({ hasActive: false, records: [] }) }) - it('lists a per-run task under its creator and under the Session its latest delivery created', () => { + it('lists a new_once task only for its reserved Session before the first delivery', () => { + const waiting: Entry = { + ...catalogEntry('waiting', SESSION, 'active'), + target: { kind: 'new_once', sessionId: SESSION, create: {} }, + involvedSessionIds: [CREATOR, SESSION], + } + const catalog = hostSnapshot('ready', [waiting]) + + expect(selectSessionScheduleFacts(catalog, SESSION)).toEqual({ hasActive: true, records: [waiting] }) + expect(selectSessionScheduleFacts(catalog, CREATOR)).toEqual({ hasActive: false, records: [] }) + }) + + it('leaves the creator and latest delivery Session empty for per-run tasks', () => { const ran = perRunEntry('ran', SESSION) const waiting = perRunEntry('waiting') const catalog = hostSnapshot('ready', [ran, waiting]) - expect(selectSessionScheduleFacts(catalog, SESSION)).toEqual({ hasActive: true, records: [ran] }) - expect(selectSessionScheduleFacts(catalog, CREATOR)).toEqual({ hasActive: true, records: [ran, waiting] }) - expect(selectSessionScheduleFacts(catalog, 'other-session' as SessionId)) - .toEqual({ hasActive: false, records: [] }) + expect(selectSessionScheduleFacts(catalog, SESSION)).toEqual({ hasActive: false, records: [] }) + expect(selectSessionScheduleFacts(catalog, CREATOR)).toEqual({ hasActive: false, records: [] }) }) it('answers no active task for a Session whose tasks are all paused or ended', () => { diff --git a/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx b/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx index 55447e823b..33eb9e2628 100644 --- a/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx +++ b/packages/client/ui-schedule/tests/task-manager-page.client.spec.tsx @@ -172,6 +172,7 @@ function mount( onDelete: vi.fn(async () => 'deleted'), onRetry: vi.fn(async () => {}), onNewTask: vi.fn(), + onUseRecommendation: vi.fn(), onClearEnded: vi.fn(async () => {}), onCreateTask: vi.fn(async () => ({ created: at })), onOpenSession: vi.fn(), @@ -839,6 +840,70 @@ describe('Task manager catalog', () => { expect(emptyNewTaskButton().textContent).toBe(en['empty.action']) }) + const RECOMMENDATION_IDS = ['dailyBrief', 'issueScan', 'pluginCompat', 'topicTracking', 'branchCleanup', + 'weather', 'workout'] as const + + function recommendations(dictionary: Dictionary = en): HTMLElement | null { + return screen.queryByRole('region', { name: dictionary['recommend.heading'] }) + } + + it('lists the built-in recommendations under the empty Enabled view and prefills each request', () => { + const h = mount({ records: [] }, en, {}, { startAtAll: false }) + const buttons = within(recommendations()!).getAllByRole('button') + expect(buttons.map(button => button.getAttribute('aria-label'))) + .toEqual(RECOMMENDATION_IDS.map(id => en[`recommend.${id}.title`])) + for (const [index, id] of RECOMMENDATION_IDS.entries()) { + const button = buttons[index]! + // The description and the run time are separate references, so a screen reader pauses between them. + expect(button.getAttribute('aria-describedby')!.split(' ').map(ref => document.getElementById(ref)?.textContent)) + .toEqual([en[`recommend.${id}.description`], en[`recommend.${id}.schedule`]]) + expect(button.querySelectorAll('svg[aria-hidden="true"]')).toHaveLength(3) + fireEvent.click(button) + expect(h.props.onUseRecommendation).toHaveBeenLastCalledWith(en[`recommend.${id}.prompt`]) + } + expect(h.props.onUseRecommendation).toHaveBeenCalledTimes(RECOMMENDATION_IDS.length) + expect(h.props.onNewTask).not.toHaveBeenCalled() + expect(emptyNewTaskButton().textContent).toBe(en['empty.action']) + }) + + it('shows the recommendations under the empty All view in the active language', () => { + mount({ records: [] }, zh) + const section = recommendations(zh)! + expect(within(section).getByRole('button', { name: zh['recommend.weather.title'] })).toBeDefined() + expect(section.textContent).toContain(zh['recommend.weather.schedule']) + }) + + it.each([ + ['paused', 'list.emptyPaused'], + ['ended', 'list.emptyInactive'], + ] as const)('omits the recommendations from the empty %s view', (status, title) => { + mount({ records: [] }) + const statuses = screen.getByRole('group', { name: en['statusFilter.label'] }) + fireEvent.click(within(statuses).getByRole('button', { name: en[`status.${status}`] })) + expect(screen.getByRole('status').textContent).toContain(en[title]) + expect(recommendations()).toBeNull() + }) + + it('omits the recommendations while rows are listed, a search matches nothing, or the catalog loads', () => { + const h = mount({ records }) + expect(recommendations()).toBeNull() + fireEvent.change(screen.getByRole('searchbox', { name: en['search.label'] }), { target: { value: 'no such task' } }) + expect(screen.getByRole('status').textContent).toContain(en['list.noMatches']) + expect(recommendations()).toBeNull() + h.view.unmount() + mount({ records: [], status: 'loading' }) + expect(recommendations()).toBeNull() + }) + + it('lists every recommendation under the empty Enabled view while paused and ended tasks use their titles', () => { + mount({ records: [ + { ...paused, title: en['recommend.dailyBrief.title'] }, + { ...ended, title: en['recommend.weather.title'] }, + ] }, en, {}, { startAtAll: false }) + expect(within(recommendations()!).getAllByRole('button').map(button => button.getAttribute('aria-label'))) + .toEqual(RECOMMENDATION_IDS.map(id => en[`recommend.${id}.title`])) + }) + it('distinguishes an empty catalog, loading, and a failed read', () => { const h = mount({ records: [], status: 'loading' }) expect(screen.getByRole('status', { name: en['list.loading'] }).textContent).toBe('') @@ -2062,7 +2127,7 @@ describe('Task manager deletion', () => { const dialog = openDelete() const cancel = within(dialog).getByRole('button', { name: en['delete.cancel'] }) const confirm = within(dialog).getByRole('button', { name: en['delete.confirm'] }) - const content = dialog.querySelector(`.${css.confirmContent}`)! + const content = dialog.querySelector(`.${css.confirmContent}`)! expect(dialog.classList.contains(css.confirmDialog!)).toBe(true) expect(content.textContent).toContain(at.prompt) expect(content.contains(cancel)).toBe(false) @@ -2075,9 +2140,16 @@ describe('Task manager deletion', () => { // installed. The dialog's cap must follow the padding of the Modal layer // that holds it, and the scrolling content must sit inside that cap instead // of pinning a number that a wrong layer padding could not contradict. - installStyles({ confirmDialog: css.confirmDialog, confirmContent: css.confirmContent }) + installStyles({ confirmDialog: css.confirmDialog, confirmContent: css.confirmContent, confirmPrompt: css.confirmPrompt }) expect(getComputedStyle(dialog).maxHeight).toBe(`calc(100dvh - ${MODAL_LAYER_PADDING * 2}px)`) expect(getComputedStyle(content).overflowY).toBe('auto') + // The instruction is a three-line excerpt, so a long one cannot stretch the dialog. + const prompt = within(content).getByText(/^Review release/) + const clamp = getComputedStyle(prompt) + expect(clamp.display).toBe('-webkit-box') + expect(clamp.getPropertyValue('-webkit-box-orient')).toBe('vertical') + expect(clamp.overflow).toBe('hidden') + expect(clamp.getPropertyValue('-webkit-line-clamp')).toBe('3') const footer = dialog.lastElementChild as HTMLElement expect(getComputedStyle(footer).flexShrink).toBe('0') fireEvent.click(confirm) diff --git a/packages/client/ui-session-panel/README.i18n.yaml b/packages/client/ui-session-panel/README.i18n.yaml new file mode 100644 index 0000000000..97d36774c6 --- /dev/null +++ b/packages/client/ui-session-panel/README.i18n.yaml @@ -0,0 +1,43 @@ +# 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-session-panel/README.md +/: + en: 8409e6477f312897 + zh: b982bc13dfe0e002 +/deepseek-ai-dsh-client-ui-session-panel: + en: aff5b9d70836e810 + zh: 2cb8c75d3c82fba9 +/deepseek-ai-dsh-client-ui-session-panel/summary: + en: b5a091528bf5375a + zh: 48a22fec747fb07a +/deepseek-ai-dsh-client-ui-session-panel/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-client-ui-session-panel/use-this-package: + en: 395514000d22bf29 + zh: 8a8e1f0dc91a21fa +/deepseek-ai-dsh-client-ui-session-panel/use-this-package/docking-and-the-overlay: + en: 67b33b9f412a687d + zh: 2a9b8c89c8bb22e4 +/deepseek-ai-dsh-client-ui-session-panel/use-this-package/contribute-a-section: + en: 1e82e57556909a29 + zh: fc68f414ec254403 +/deepseek-ai-dsh-client-ui-session-panel/understand-the-implementation: + en: e414b3b6a3aef7fc + zh: 384ad365ae5529a9 +/deepseek-ai-dsh-client-ui-session-panel/further-exploration: + en: 09b403af819bd155 + zh: e949998de4794393 +/deepseek-ai-dsh-client-ui-session-panel/model-experience: + en: 7e8bbe318a76fd54 + zh: c60e87da2a37642a +/deepseek-ai-dsh-client-ui-session-panel/model-experience/kv-cache-effect: + en: 47f982e326fe77fd + zh: 275b2ef7eec3ab19 +/deepseek-ai-dsh-client-ui-session-panel/known-limitations-and-deferred-work: + en: d5cf7883b7f7e0ab + zh: f5407439447acc44 +/deepseek-ai-dsh-client-ui-session-panel/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: b532016223ceceef diff --git a/packages/client/ui-session-panel/README.md b/packages/client/ui-session-panel/README.md new file mode 100644 index 0000000000..957fbe8480 --- /dev/null +++ b/packages/client/ui-session-panel/README.md @@ -0,0 +1,126 @@ +--- +description: "The Session panel: a header toggle and a floating panel in the Chat View's aside whose sections other plugins register, with the built-in Environment section." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-session-panel + +English | [中文](README.zh.md) + +## Summary + +`dsh-client-ui-session-panel` adds a Session header toggle that shows or hides a floating panel of facts about the current Session. The panel lives in the Chat View: it docks in the Chat View's end gutter when the gutter can hold it, and otherwise opens over the transcript on request. It draws section titles and leaves section content to the plugins that register sections; it ships the Environment section with the working folder row. + +## 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 `@deepseek-ai/dsh-web-app` bundle loads this package by default. The toggle is the first Session header utility, before change requests, sharing, and the schedule catalog. It is an icon button with the panel name and its indicators as its accessible name, a tooltip that says whether a press shows or hides the panel, shown after 500ms of hover or at once on keyboard focus, and `aria-expanded` for whether the panel shows. + +### Docking and the overlay + +The panel docks while the gutter between the transcript column and the Chat frame's end edge is at least 348px: 40px clear of the column and its width handle, the panel's 300px minimum width, and an 8px edge margin. Docked, it is 300–360px wide, 8px from the end edge, starts 12px below the header, stops above the composer stack, and scrolls inside itself in a reserved scrollbar column 2px from its end edge, so its content keeps one width whether or not it scrolls. Pressing the toggle then flips one docking preference that every Session shares and that persists in `localStorage` under `dsh.sessionPanel.pinned`; the panel docks by default. + +A narrower gutter hides the docked panel, so it never covers the transcript. This includes a narrow window, an expanded right sidebar, and a dragged-wide transcript column. Pressing the toggle then opens the panel over the transcript with the prominent elevation, 280px wide so it covers less of the transcript than the docked panel takes beside it, 8px from the end edge, above the composer stack and not covering it. The overlay closes from the toggle, on Escape, and on a pointer press outside the panel, the toggle, and any open menu, such as a row's context menu; Escape returns focus to the toggle when focus was inside the panel. A modal above the page, an input method composing text, and a handler that already took the key, such as an open menu's, keep Escape; otherwise the overlay takes it first, so with the overlay open the first Escape from the composer closes the overlay and does not count toward stopping a running turn. Closing it does not change the docking preference. At most one Session's overlay is open; it closes once the gutter widens enough to dock and once no Chat View shows the Session, as after switching to another Session or View, and switching back does not reopen it. When the panel hides while focus is inside it, focus moves to the toggle. + +Other Views, such as the trajectory View, show no panel. While no Chat View shows the Session, the toggle is unavailable: it stays in the header with its indicators, dimmed, and its tooltip asks to switch to the Chat view. + + +### Contribute a section + +A section is one `conversation.session.panel.section` list registration: `id` addresses it, `order` sorts it ascending, and the required `label` is its title, which the panel draws in the active locale. The section component receives `presentation` (`docked` or `overlay`) and `dismissOverlay()` as owner props; it renders its body and renders nothing when it has nothing to show, which hides its title too. Register trailing title controls, such as a count or a refresh button, in the keyed `conversation.session.panel.section.actions` slot under the section's `id`. A section without a label is reported to the console and not shown. + +Plugins share a title by registering rows in a section owner's row slot. The built-in Environment section (`id: 'environment'`, `order: 0`) declares `conversation.session.panel.environment.row`; its `project` row (`order: 0`) shows the Session's working folder: the current directory from the `workingDirectory` projection, or, before the projection arrives or when it records none, the directory the Session was created in, then the directory of the Workspace that lists the Session. The row shows the folder name followed by its parent folder in tertiary ink, which clips with an ellipsis; its tooltip, shown after 500ms of hover, names the working folder and gives the full path. Both abbreviate the Host home to `~`. Right-clicking the row or pressing its More button opens the shared `directory` context menu. A plugin that owns a shared section declares its own row slot the same way. + +Marks that must stay visible while the panel is hidden, such as an attention dot, go in the `conversation.session.panel.indicator` list. Each occupant is one element: the toggle sizes it to a 6px dot at the glyph's corner, and the occupant sets its `background` and includes text that names it, which becomes part of the toggle's accessible name. Occupants overlap, and a higher `order` paints above a lower one. The `panelShown` owner prop lets a mark that only repeats the panel's content render nothing while the panel shows. + +Rows share one look without sharing a component. A section's component, or an Environment row entry, writes its row's markup and marks the parts, and the panel's stylesheet lays them out, so icon, text, and trailing areas line up across packages while each package owns what its row contains. + +| Mark | Part | +|---|---| +| `data-session-panel-row` | The row: one 28px line. A row with an action or a menu highlights as a whole on hover and while one of its menus is open. | +| `data-row-part="body"` | The icon and the text. A ` + + ) +} diff --git a/packages/client/ui-session-panel/src/client/element-ids.ts b/packages/client/ui-session-panel/src/client/element-ids.ts new file mode 100644 index 0000000000..f6e881ee55 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/element-ids.ts @@ -0,0 +1,20 @@ +/** DOM ids that connect a Session's toggle and panel across their separate slot entries. */ +import type { SessionId } from '@deepseek-ai/dsh-session/types' + +/** + * Id of a Session's panel element, which the toggle names in `aria-controls`. + * @param sessionId - Session that owns the panel. + * @returns the element id. + */ +export function panelElementId(sessionId: SessionId): string { + return `dsh-session-panel-${sessionId}` +} + +/** + * Id of a Session's toggle, which receives focus when its overlay closes from the keyboard. + * @param sessionId - Session whose header holds the toggle. + * @returns the element id. + */ +export function toggleElementId(sessionId: SessionId): string { + return `dsh-session-panel-toggle-${sessionId}` +} diff --git a/packages/client/ui-session-panel/src/client/index.ts b/packages/client/ui-session-panel/src/client/index.ts new file mode 100644 index 0000000000..c8233b7d31 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/index.ts @@ -0,0 +1,102 @@ +/** + * Session panel plugin, browser half: a Session header toggle and a floating + * panel in the Chat View's aside. The panel draws the titles of the sections + * other plugins register, lays out the rows they mark, and ships the + * Environment section with the working folder row. + */ +import type { Context as ClientContext } from '@deepseek-ai/cordis' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import type {} from '@deepseek-ai/dsh-client-ui-chat/client' +import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-connection/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import { EnvironmentSection } from './EnvironmentSection.tsx' +import { ProjectRow } from './ProjectRow.tsx' +import { SessionPanel } from './SessionPanel.tsx' +import { SessionPanelToggle } from './SessionPanelToggle.tsx' +import { sectionSource } from './sections.ts' +import type { ProjectRowInjected, SessionPanelInjected, SessionPanelToggleInjected } from './slots.ts' +import { SessionPanelState } from './visibility.ts' +import { de, en, es, fr, ja, NS, pt, ru, zh, type SessionPanelKey } from './locales.ts' + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + /** Session panel copy. */ + sessionPanel: SessionPanelKey + } +} + +export type { + EnvironmentSectionProps, ProjectRowInjected, ProjectRowProps, SessionPanelDockable, SessionPanelIndicatorOwnerProps, SessionPanelInjected, + SessionPanelPresentation, SessionPanelProbes, SessionPanelProps, SessionPanelSectionEntry, SessionPanelSectionOwnerProps, + SessionPanelToggleInjected, SessionPanelToggleProps, SessionPanelVisibility, +} from './slots.ts' + +/** Required services: the slot registry, dictionaries, and the Host facts of the Remote carrier. */ +export const inject = ['slots', 'locale', 'remote'] + +/** + * Client plugin body: register the dictionaries, the header toggle, the panel, + * and the Environment section with its project row. + * @param ctx - client root context. + */ +export function apply(ctx: ClientContext): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-session-panel: dictionaries') + const t = ctx.locale.bind(NS) + const state = new SessionPanelState() + ctx.effect(() => () => { state.dispose() }, 'ui-session-panel: overlay follower and dock probes') + const sections = sectionSource(ctx) + const host: ObservableSnapshot = { + getSnapshot: () => ctx.remote.$host, + subscribe: listener => ctx.on('connection/reset', listener), + } + + ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({ + name: 'conversation.session.header.utilities', + id: 'session-panel', + // The first utility: left of change requests, sharing, and the schedule catalog. + order: -10, + locale: NS, + children: { + 'conversation.session.panel.indicator': { kind: 'list', scope: 'session', inline: true }, + }, + inject: (): SessionPanelToggleInjected => ({ + hooks: { visibility: state.visibility, dockable: state.dockable }, + toggle: (sessionId) => { state.toggle(sessionId) }, + }), + }, SessionPanelToggle)) + + ctx.slots.inject('conversation.chat.aside', () => ctx.slots.register({ + name: 'conversation.chat.aside', + locale: NS, + children: { + 'conversation.session.panel.section': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' }, + }, + inject: (): SessionPanelInjected => ({ + hooks: { visibility: state.visibility, sections, probes: state.probes }, + createProbeRef: (sessionId, probe) => state.createProbeRef(sessionId, probe), + closeOverlay: (sessionId) => { state.closeOverlay(sessionId) }, + }), + }, SessionPanel)) + + ctx.slots.inject('conversation.session.panel.section', () => ctx.slots.register({ + name: 'conversation.session.panel.section', + id: 'environment', + order: 0, + label: () => t('section.environment'), + children: { + 'conversation.session.panel.environment.row': { kind: 'list', scope: 'session' }, + }, + }, EnvironmentSection)) + + ctx.slots.inject('conversation.session.panel.environment.row', () => ctx.slots.register({ + name: 'conversation.session.panel.environment.row', + id: 'project', + order: 0, + locale: NS, + inject: (): ProjectRowInjected => ({ hooks: { host } }), + }, ProjectRow)) +} diff --git a/packages/client/ui-session-panel/src/client/locales.ts b/packages/client/ui-session-panel/src/client/locales.ts new file mode 100644 index 0000000000..1264e8ad94 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/locales.ts @@ -0,0 +1,95 @@ +/** `sessionPanel` namespace dictionaries. */ + +/** Dictionary namespace owned by this plugin. */ +export const NS = 'sessionPanel' + +/** Simplified Chinese dictionary (the key-set source of truth). */ +export const zh = { + 'panel.name': '会话面板', + 'toggle.show': '显示会话面板', + 'toggle.hide': '隐藏会话面板', + 'toggle.unavailable': '切换到「对话」视图后可显示会话面板', + 'section.environment': '环境', + 'project.label': '工作目录', + 'project.actions': '工作目录操作', +} as const + +/** Every key of the `sessionPanel` namespace. */ +export type SessionPanelKey = keyof typeof zh + +/** English dictionary, key-identical to the Chinese source of truth. */ +export const en: Record = { + 'panel.name': 'Session panel', + 'toggle.show': 'Show session panel', + 'toggle.hide': 'Hide session panel', + 'toggle.unavailable': 'Switch to the Chat view to show the session panel', + 'section.environment': 'Environment', + 'project.label': 'Working folder', + 'project.actions': 'Working folder actions', +} + +/** Japanese dictionary. */ +export const ja = { + 'panel.name': 'セッションパネル', + 'toggle.show': 'セッションパネルを表示', + 'toggle.hide': 'セッションパネルを非表示', + 'toggle.unavailable': '「チャット」ビューに切り替えるとセッションパネルを表示できます', + 'section.environment': '環境', + 'project.label': '作業フォルダー', + 'project.actions': '作業フォルダーの操作', +} satisfies Record + +/** Spanish dictionary. */ +export const es = { + 'panel.name': 'Panel de la sesión', + 'toggle.show': 'Mostrar el panel de la sesión', + 'toggle.hide': 'Ocultar el panel de la sesión', + 'toggle.unavailable': 'Cambia a la vista Chat para mostrar el panel de la sesión', + 'section.environment': 'Entorno', + 'project.label': 'Carpeta de trabajo', + 'project.actions': 'Acciones de la carpeta de trabajo', +} satisfies Record + +/** French dictionary. */ +export const fr = { + 'panel.name': 'Panneau de session', + 'toggle.show': 'Afficher le panneau de session', + 'toggle.hide': 'Masquer le panneau de session', + 'toggle.unavailable': 'Passez à la vue Discussion pour afficher le panneau de session', + 'section.environment': 'Environnement', + 'project.label': 'Dossier de travail', + 'project.actions': 'Actions sur le dossier de travail', +} satisfies Record + +/** German dictionary. */ +export const de = { + 'panel.name': 'Sitzungsbereich', + 'toggle.show': 'Sitzungsbereich anzeigen', + 'toggle.hide': 'Sitzungsbereich ausblenden', + 'toggle.unavailable': 'Wechseln Sie zur Ansicht „Chat“, um den Sitzungsbereich anzuzeigen', + 'section.environment': 'Umgebung', + 'project.label': 'Arbeitsordner', + 'project.actions': 'Aktionen für den Arbeitsordner', +} satisfies Record + +/** Russian dictionary. */ +export const ru = { + 'panel.name': 'Панель сеанса', + 'toggle.show': 'Показать панель сеанса', + 'toggle.hide': 'Скрыть панель сеанса', + 'toggle.unavailable': 'Переключитесь на вид «Чат», чтобы показать панель сеанса', + 'section.environment': 'Среда', + 'project.label': 'Рабочая папка', + 'project.actions': 'Действия с рабочей папкой', +} satisfies Record + +/** Brazilian Portuguese dictionary. */ +export const pt = { + 'panel.name': 'Painel da sessão', + 'toggle.show': 'Mostrar painel da sessão', + 'toggle.hide': 'Ocultar painel da sessão', + 'toggle.unavailable': 'Mude para a visualização Chat para mostrar o painel da sessão', + 'section.environment': 'Ambiente', + 'project.label': 'Pasta de trabalho', + 'project.actions': 'Ações da pasta de trabalho', +} satisfies Record diff --git a/packages/client/ui-session-panel/src/client/sections.ts b/packages/client/ui-session-panel/src/client/sections.ts new file mode 100644 index 0000000000..fcc9feed5e --- /dev/null +++ b/packages/client/ui-session-panel/src/client/sections.ts @@ -0,0 +1,66 @@ +/** Projection of the section list's registrations into the titles the panel draws. */ +import type { Context as ClientContext } from '@deepseek-ai/cordis' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import { resolveSlotLabel, type StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' +import type { SessionPanelSectionEntry } from './slots.ts' + +const SECTION_SLOT = 'conversation.session.panel.section' + +/** + * Project live section registrations in display order. A registration + * without a label cannot be titled; it is reported and left out. + * @param entries - shadowing winners of the section list in ledger order. + * @param report - receives one message per unlabeled registration. + * @returns sections ordered by ascending `order`, then registration order. + */ +export function projectSections( + entries: readonly StoredEntry[], report: (message: string) => void, +): readonly SessionPanelSectionEntry[] { + const rows: (SessionPanelSectionEntry & { readonly order: number })[] = [] + for (const entry of entries) { + /* v8 ignore next -- list registration validates id at load. */ + const id = entry.options.id ?? '' + const label = resolveSlotLabel(entry.options.label) + if (label === undefined || label === '') { + report(`ui-session-panel: section "${id}" from ${entry.registrant ?? 'an unknown registrant'} has no label and is not shown`) + continue + } + rows.push({ id, label, order: entry.options.order ?? 0 }) + } + return rows.sort((a, b) => a.order - b.order).map(({ id, label }) => ({ id, label })) +} + +/** + * Observable section roster: recomputed when the section list's ledger or + * the active locale changes, and identity-stable between changes. + * @param ctx - client context whose slot registry and locale the roster follows. + * @returns the section source. + */ +export function sectionSource(ctx: ClientContext): ObservableSnapshot { + let version = -1 + let revision = -1 + let sections: readonly SessionPanelSectionEntry[] = [] + return { + getSnapshot: () => { + const nextVersion = ctx.slots.getVersion(SECTION_SLOT) + const nextRevision = ctx.locale.getSnapshot().revision + if (nextVersion !== version || nextRevision !== revision) { + const reportOnce = version !== nextVersion + version = nextVersion + revision = nextRevision + sections = projectSections(ctx.slots.entriesOfSlot(SECTION_SLOT), (message) => { + if (reportOnce) console.error(message) + }) + } + return sections + }, + subscribe: (listener) => { + const offLedger = ctx.slots.subscribe(SECTION_SLOT, listener) + const offLocale = ctx.locale.subscribe(listener) + return () => { + offLedger() + offLocale() + } + }, + } +} diff --git a/packages/client/ui-session-panel/src/client/slots.ts b/packages/client/ui-session-panel/src/client/slots.ts new file mode 100644 index 0000000000..54a24145f1 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/slots.ts @@ -0,0 +1,172 @@ +/** Session panel slot declarations and composed component props. */ +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { + InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, +} from '@deepseek-ai/dsh-client-ui-slots' +import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import type {} from '@deepseek-ai/dsh-client-ui-chat/client' +import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type { NS } from './locales.ts' + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** + * Sections of the Session panel. `id` addresses the section, `order` sorts + * the sections ascending, and the required `label` is the section title, + * which the panel draws. A section with nothing to show renders nothing, + * and the panel hides its title with it. + */ + 'conversation.session.panel.section': { + kind: 'list' + scope: 'session' + owner: SessionPanelSectionOwnerProps + } + /** Trailing controls of one section title, keyed by the section's `id`. */ + 'conversation.session.panel.section.actions': { kind: 'keyed'; scope: 'session' } + /** + * Marks over the panel toggle, such as an attention dot. Each occupant is + * one element: the toggle sizes it to a 6px dot at the glyph's corner, and + * the occupant sets its `background` and includes text that names it for + * assistive technology, which becomes part of the toggle's name. Occupants + * overlap, and a higher `order` paints above a lower one. An occupant that + * only repeats what the panel shows renders nothing while `panelShown`. + */ + 'conversation.session.panel.indicator': { + kind: 'list' + scope: 'session' + inline: true + owner: SessionPanelIndicatorOwnerProps + } + /** Rows of the built-in Environment section in ascending `order`. */ + 'conversation.session.panel.environment.row': { kind: 'list'; scope: 'session' } + } +} + +/** How the panel currently shows. */ +export type SessionPanelPresentation = + /** Beside the transcript in the Chat View's end gutter. */ + | 'docked' + /** Over the transcript, opened from the toggle while the gutter is too narrow. */ + | 'overlay' + +/** Values every section receives from the panel. */ +export interface SessionPanelSectionOwnerProps { + /** Current presentation; sections may lower their density in the overlay. */ + readonly presentation: SessionPanelPresentation + /** Close the overlay, for example after a row opened another surface; no effect while docked. */ + readonly dismissOverlay: () => void +} + +/** Values every toggle indicator receives from the toggle. */ +export interface SessionPanelIndicatorOwnerProps { + /** Whether the panel shows, docked or as an overlay. */ + readonly panelShown: boolean +} + +/** One section the panel draws, projected from the section list's registrations. */ +export interface SessionPanelSectionEntry { + /** Registration id. */ + readonly id: string + /** Localized title. */ + readonly label: string +} + +/** Panel visibility shared by the toggle and the panel. */ +export interface SessionPanelVisibility { + /** Whether the panel docks while the gutter has room; persisted across reloads. */ + readonly pinned: boolean + /** Session whose overlay is open, or null. */ + readonly overlay: SessionId | null +} + +/** + * Whether each Session whose Chat View holds a panel has room to dock it: + * true when the end gutter of at least one of its Chat Views holds the docked + * panel. A Session without an entry shows no Chat View. + */ +export type SessionPanelDockable = ReadonlyMap + +/** + * Whether the end gutter of each mounted panel's Chat View holds the docked + * panel, by the id the panel gave its dock probe. + */ +export type SessionPanelProbes = ReadonlyMap + +/** Business face of the header toggle. */ +export interface SessionPanelToggleInjected { + /** Shared visibility and each Session's room to dock; the renderer binds them as `useVisibility` and `useDockable`. */ + readonly hooks: { + readonly visibility: ObservableSnapshot + readonly dockable: ObservableSnapshot + } + /** + * Show or hide the panel. With room to dock this flips the docking + * preference and closes any overlay; otherwise it opens or closes the + * Session's overlay. No effect while no Chat View shows the Session. + * @param sessionId - Session whose header holds the toggle. + */ + readonly toggle: (sessionId: SessionId) => void +} + +/** Business face of the panel. */ +export interface SessionPanelInjected { + /** + * Shared visibility, the projected section roster, and each dock probe's + * room; the renderer binds them as `useVisibility`, `useSections`, and `useProbes`. + */ + readonly hooks: { + readonly visibility: ObservableSnapshot + readonly sections: ObservableSnapshot + readonly probes: ObservableSnapshot + } + /** + * Create the ref of one mounted panel's dock probe, the element whose + * stylesheet width says whether the Chat View's end gutter holds the docked + * panel. The plugin observes the element while it is attached and records + * the probe's room under `probe`, and the Session's for the toggle. + * @param sessionId - Session the panel's Chat View shows. + * @param probe - identity of the panel within the page. + * @returns the ref callback for the probe element; detaching withdraws the probe. + */ + readonly createProbeRef: (sessionId: SessionId, probe: string) => (element: HTMLElement | null) => void + /** + * Close the Session's overlay. + * @param sessionId - Session whose overlay closes; another Session's overlay stays. + */ + readonly closeOverlay: (sessionId: SessionId) => void +} + +/** Business face of the project row. */ +export interface ProjectRowInjected { + /** Host facts from the connection's ready frame; the renderer binds them as `useHost`. */ + readonly hooks: { readonly host: ObservableSnapshot } +} + +/** Full props of the header toggle. */ +export type SessionPanelToggleProps = + PropsRuntime<'conversation.session.header.utilities'> + & PropsRenderSlots<'conversation.session.panel.indicator'> + & InjectFace + & PropsLocale + +/** Full props of the panel. */ +export type SessionPanelProps = + PropsRuntime<'conversation.chat.aside'> + & PropsRenderSlots<'conversation.session.panel.section' | 'conversation.session.panel.section.actions'> + & InjectFace + & PropsLocale + +/** Full props of the built-in Environment section. */ +export type EnvironmentSectionProps = + PropsRuntime<'conversation.session.panel.section'> + & PropsRenderSlots<'conversation.session.panel.environment.row'> + +/** Full props of the project row. */ +export type ProjectRowProps = + PropsRuntime<'conversation.session.panel.environment.row'> + & PropsRenderFactories + & InjectFace + & PropsLocale diff --git a/packages/client/ui-session-panel/src/client/visibility.ts b/packages/client/ui-session-panel/src/client/visibility.ts new file mode 100644 index 0000000000..2e4b036036 --- /dev/null +++ b/packages/client/ui-session-panel/src/client/visibility.ts @@ -0,0 +1,188 @@ +/** Session panel visibility: the persisted docking preference, the transient overlay, the dock probes, and the presentation. */ +import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SessionPanelDockable, SessionPanelPresentation, SessionPanelProbes, SessionPanelVisibility } from './slots.ts' + +/** localStorage key of the docking preference. */ +export const PINNED_STORAGE_KEY = 'dsh.sessionPanel.pinned' + +const NO_SESSIONS: SessionPanelDockable = new Map() +const NO_PROBES: SessionPanelProbes = new Map() + +/** + * Decide how the panel shows for one Session. + * @param fits - whether the gutter can hold the docked panel. + * @param visibility - shared visibility state. + * @param sessionId - Session whose panel is decided. + * @returns the presentation, or `hidden` when the panel renders nothing. + */ +export function presentationOf( + fits: boolean, visibility: SessionPanelVisibility, sessionId: SessionId, +): SessionPanelPresentation | 'hidden' { + if (fits) return visibility.pinned ? 'docked' : 'hidden' + return visibility.overlay === sessionId ? 'overlay' : 'hidden' +} + +/** + * Visibility shared by every Session's toggle and panel, and whether each + * mounted panel and each Session has room to dock. The panel's stylesheet + * decides the room: each mounted panel renders a dock probe that is 1px wide + * while its Chat View's end gutter holds the docked panel and 0 otherwise, + * and this state observes only that probe, so it hears the decision flip + * and nothing while the window resizes on one side of it or the transcript + * grows. Docking follows one preference for all Sessions; at most one + * Session's overlay is open, and it closes once its Session has room to dock + * or no Chat View shows that Session any longer. + */ +export class SessionPanelState { + // A stored value other than `false` keeps the default: the panel docks. + private readonly pinned = createSnapshotStore(true, { persist: { name: PINNED_STORAGE_KEY } }) + private readonly overlay = createSnapshotStore(null) + private readonly room = createSnapshotStore(NO_SESSIONS) + private readonly fits = createSnapshotStore(NO_PROBES) + /** The Session of every attached probe. */ + private readonly owners = new Map() + /** Stops observing each attached probe. */ + private readonly detachers = new Set<() => void>() + private current: SessionPanelVisibility = { pinned: this.pinned.getSnapshot() !== false, overlay: null } + /** Stops following the open overlay's gutter. */ + private unfollow: () => void = () => {} + + /** Combined visibility; the snapshot keeps its identity until a member changes. */ + readonly visibility: ObservableSnapshot = { + getSnapshot: () => { + const pinned = this.pinned.getSnapshot() !== false + const overlay = this.overlay.getSnapshot() + if (pinned !== this.current.pinned || overlay !== this.current.overlay) this.current = { pinned, overlay } + return this.current + }, + subscribe: (listener) => { + const offPinned = this.pinned.subscribe(listener) + const offOverlay = this.overlay.subscribe(listener) + return () => { + offPinned() + offOverlay() + } + }, + } + + /** + * Whether each Session with a mounted panel has room to dock it: true while + * any of its probes does. The snapshot keeps its identity until a Session + * gains or loses its entry or its room changes. + */ + readonly dockable: ObservableSnapshot = this.room + + /** + * Whether each attached probe's gutter holds the docked panel. The snapshot + * keeps its identity until a probe attaches, detaches, or flips. + */ + readonly probes: ObservableSnapshot = this.fits + + /** + * Create the element-ref lifecycle of one mounted panel's dock probe. + * Attaching the element enters the probe without room and observes its + * size; a probe at least 1px wide has room. Detaching stops the + * observation and withdraws the probe. Without `ResizeObserver` the probe + * stays without room, so the panel shows only as an overlay. + * @param sessionId - Session the panel's Chat View shows. + * @param probe - identity of the panel within the page. + * @returns the ref callback for the probe element. + */ + createProbeRef(sessionId: SessionId, probe: string): (element: HTMLElement | null) => void { + let detach: (() => void) | undefined + return (element) => { + detach?.() + detach = element === null ? undefined : this.attach(sessionId, probe, element) + } + } + + /** + * Show or hide the panel from a Session's toggle. With room to dock this + * flips the docking preference and closes any overlay; otherwise it opens + * or closes the Session's overlay. No effect while no Chat View shows the Session. + * @param sessionId - Session whose header holds the toggle. + */ + toggle(sessionId: SessionId): void { + const dockable = this.room.getSnapshot().get(sessionId) + if (dockable === undefined) return + if (dockable) { + this.pinned.set(!this.visibility.getSnapshot().pinned) + this.setOverlay(null) + return + } + this.setOverlay(this.overlay.getSnapshot() === sessionId ? null : sessionId) + } + + /** + * Close a Session's overlay. + * @param sessionId - Session whose overlay closes; another Session's overlay stays open. + */ + closeOverlay(sessionId: SessionId): void { + if (this.overlay.getSnapshot() === sessionId) this.setOverlay(null) + } + + /** Stop following the open overlay's Session and stop observing every attached probe. */ + dispose(): void { + this.stopFollowing() + for (const detach of [...this.detachers]) detach() + } + + private stopFollowing(): void { + this.unfollow() + this.unfollow = () => {} + } + + private setOverlay(sessionId: SessionId | null): void { + this.stopFollowing() + this.overlay.set(sessionId) + if (sessionId === null) return + const check = (): void => { + if (this.room.getSnapshot().get(sessionId) !== false) this.closeOverlay(sessionId) + } + this.unfollow = this.room.subscribe(check) + } + + private attach(sessionId: SessionId, probe: string, element: HTMLElement): () => void { + this.report(sessionId, probe, false) + const measure: ResizeObserverCallback = (entries) => { + for (const entry of entries) this.report(sessionId, probe, entry.contentRect.width >= 1) + } + const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(measure) + observer?.observe(element) + const detach = (): void => { + // The ref callback and dispose may both detach; the first one withdraws the probe. + if (!this.detachers.delete(detach)) return + observer?.disconnect() + this.report(sessionId, probe, null) + } + this.detachers.add(detach) + return detach + } + + /** Record one probe's room, or its withdrawal, publishing only what changed. */ + private report(sessionId: SessionId, probe: string, dockable: boolean | null): void { + const fits = this.fits.getSnapshot() + if (fits.get(probe) !== (dockable ?? undefined)) { + const next = new Map(fits) + if (dockable === null) { + next.delete(probe) + this.owners.delete(probe) + } else { + next.set(probe, dockable) + this.owners.set(probe, sessionId) + } + this.fits.set(next) + } + let any: boolean | undefined + for (const [id, owner] of this.owners) { + if (owner === sessionId) any = any === true || this.fits.getSnapshot().get(id) === true + } + const room = this.room.getSnapshot() + if (room.get(sessionId) === any) return + const next = new Map(room) + if (any === undefined) next.delete(sessionId) + else next.set(sessionId, any) + this.room.set(next) + } +} diff --git a/packages/client/ui-session-panel/src/css-modules.d.ts b/packages/client/ui-session-panel/src/css-modules.d.ts new file mode 100644 index 0000000000..8811db1264 --- /dev/null +++ b/packages/client/ui-session-panel/src/css-modules.d.ts @@ -0,0 +1,4 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} diff --git a/packages/client/ui-session-panel/src/index.ts b/packages/client/ui-session-panel/src/index.ts new file mode 100644 index 0000000000..76ee1f0c6a --- /dev/null +++ b/packages/client/ui-session-panel/src/index.ts @@ -0,0 +1,9 @@ +/** + * Node half of the Session panel plugin. The browser half in `src/client/` + * owns every contribution; this entry exists so the package appears as an + * ordinary Loader row. + * @module @deepseek-ai/dsh-client-ui-session-panel + */ + +/** Loader-visible no-op body; the browser half carries the feature. */ +export function apply(): void {} diff --git a/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts b/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts new file mode 100644 index 0000000000..a0bcd21814 --- /dev/null +++ b/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts @@ -0,0 +1,141 @@ +/** + * ui-session-panel plugin halves: the browser entry's dictionaries, header + * toggle, panel, Environment section, and project row against the real + * SlotRegistry, the inject faces those entries receive, the section roster + * projection, fiber teardown removing every contribution (HMR safety), and + * the inert node entry. + */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' +import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { apply, inject } from '../src/client/index.ts' +import type { ProjectRowInjected, SessionPanelInjected, SessionPanelToggleInjected } from '../src/client/slots.ts' +import { apply as applyNode } from '../src/index.ts' + +const SID = 'session-1' as SessionId + +afterEach(() => { + vi.restoreAllMocks() +}) + +/** Boot the browser half over a real slot tree that declares the header utilities and the Chat aside. */ +async function bench() { + const ctx = new Context() + await ctx.plugin(SlotRegistry).await() + ctx.slots.register({ + name: 'root', + children: { + 'conversation.session.header.utilities': { kind: 'list', scope: 'session' }, + 'conversation.chat.aside': { kind: 'single', scope: 'session' }, + }, + } as never, () => null) + const host = { home: '/Users/me', isLoopback: true } + ctx.provide('connection', { api: { settings: {} }, isLoopback: false } as never) + ctx.provide('remote', { $on: () => () => {}, $host: host } as never) + ctx.provide('configForms', { developerTools: { enabled: createSnapshotStore(true) }, get: () => stubConfigForm().scope } as never) + await ctx.plugin({ inject: localeInject, apply: applyLocale }).await() + ctx.locale.setLocale('zh') + const fiber = ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + return { ctx, fiber, host } +} + +/** Inject face of one registration, called for the test Session. */ +function faceOf(ctx: Context, slot: string, id: string | undefined): unknown { + const entry = ctx.slots.entries(slot as never).find(candidate => candidate.options.id === id) + const face = entry?.inject as ((sessionId: SessionId) => unknown) | undefined + if (face === undefined) throw new Error(`${slot} entry ${id ?? '(single)'} registered no inject face`) + return face(SID) +} + +describe('ui-session-panel browser half', () => { + it('declares the services it binds', () => { + expect(inject).toEqual(['slots', 'locale', 'remote']) + }) + + it('registers the toggle first among the header utilities, the panel in the Chat aside, the Environment section, and the project row', async () => { + const { ctx } = await bench() + const toggle = ctx.slots.entries('conversation.session.header.utilities').find(entry => entry.options.id === 'session-panel') + expect(toggle?.options.order).toBe(-10) + expect(ctx.slots.entries('conversation.chat.aside')).toHaveLength(1) + const section = ctx.slots.entries('conversation.session.panel.section').find(entry => entry.options.id === 'environment') + expect(section?.options.order).toBe(0) + expect(ctx.slots.entries('conversation.session.panel.environment.row').map(entry => entry.options.id)).toEqual(['project']) + }) + + it('hands the toggle the room to dock the panel tracks, and both the shared visibility', async () => { + const { ctx, fiber } = await bench() + const toggle = faceOf(ctx, 'conversation.session.header.utilities', 'session-panel') as SessionPanelToggleInjected + const panel = faceOf(ctx, 'conversation.chat.aside', undefined) as SessionPanelInjected + expect(toggle.hooks.visibility).toBe(panel.hooks.visibility) + const attach = panel.createProbeRef(SID, 'main') + // The node suite has no DOM or ResizeObserver; the probe enters without room and stays unobserved. + attach({} as HTMLElement) + expect(panel.hooks.probes.getSnapshot().get('main')).toBe(false) + expect(toggle.hooks.dockable.getSnapshot().get(SID)).toBe(false) + toggle.toggle(SID) + expect(panel.hooks.visibility.getSnapshot()).toEqual({ pinned: true, overlay: SID }) + panel.closeOverlay(SID) + expect(panel.hooks.visibility.getSnapshot().overlay).toBeNull() + toggle.toggle(SID) + // Disposing the plugin withdraws the probe and stops the open overlay from following the room to dock. + await fiber.dispose() + expect(toggle.hooks.dockable.getSnapshot().has(SID)).toBe(false) + attach(null) + expect(panel.hooks.visibility.getSnapshot().overlay).toBe(SID) + }) + + it('projects the section roster in the active locale and keeps it stable between changes', async () => { + const { ctx } = await bench() + const panel = faceOf(ctx, 'conversation.chat.aside', undefined) as SessionPanelInjected + const roster = panel.hooks.sections + const first = roster.getSnapshot() + expect(first).toEqual([{ id: 'environment', label: '环境' }]) + expect(roster.getSnapshot()).toBe(first) + const listener = vi.fn() + const off = roster.subscribe(listener) + ctx.locale.setLocale('en') + expect(listener).toHaveBeenCalled() + expect(roster.getSnapshot()).toEqual([{ id: 'environment', label: 'Environment' }]) + + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + const dispose = ctx.slots.register({ name: 'conversation.session.panel.section', id: 'untitled', order: 5 }, () => null) + expect(roster.getSnapshot()).toEqual([{ id: 'environment', label: 'Environment' }]) + roster.getSnapshot() + expect(error).toHaveBeenCalledTimes(1) + ctx.locale.setLocale('zh') + roster.getSnapshot() + expect(error).toHaveBeenCalledTimes(1) + dispose() + off() + }) + + it('gives the project row the Host facts and follows connection resets', async () => { + const { ctx, host } = await bench() + const row = faceOf(ctx, 'conversation.session.panel.environment.row', 'project') as ProjectRowInjected + expect(row.hooks.host.getSnapshot()).toBe(host) + const listener = vi.fn() + const off = row.hooks.host.subscribe(listener) + ctx.emit('connection/reset' as never) + expect(listener).toHaveBeenCalledTimes(1) + off() + }) + + it('removes every contribution with the fiber (HMR safety)', async () => { + const { ctx, fiber } = await bench() + await fiber.dispose() + expect(ctx.slots.entries('conversation.session.header.utilities')).toHaveLength(0) + expect(ctx.slots.entries('conversation.chat.aside')).toHaveLength(0) + expect(ctx.slots.entries('conversation.session.panel.section')).toHaveLength(0) + }) +}) + +describe('ui-session-panel node half', () => { + it('contributes no host behavior', () => { + expect(applyNode).not.toThrow() + }) +}) diff --git a/packages/client/ui-session-panel/tests/components.client.spec.tsx b/packages/client/ui-session-panel/tests/components.client.spec.tsx new file mode 100644 index 0000000000..613ad0c5fd --- /dev/null +++ b/packages/client/ui-session-panel/tests/components.client.spec.tsx @@ -0,0 +1,470 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { useRef, type ReactNode } from 'react' +import { useModalLayer } from '@deepseek-ai/dsh-client-ui-primitives' +import { bindSnapshotSelector, contextMenuHook, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { EnvironmentSection } from '../src/client/EnvironmentSection.tsx' +import { ProjectRow } from '../src/client/ProjectRow.tsx' +import { SessionPanel } from '../src/client/SessionPanel.tsx' +import { SessionPanelToggle } from '../src/client/SessionPanelToggle.tsx' +import type { + EnvironmentSectionProps, ProjectRowProps, SessionPanelDockable, SessionPanelProbes, SessionPanelProps, SessionPanelSectionEntry, + SessionPanelSectionOwnerProps, SessionPanelToggleProps, SessionPanelVisibility, +} from '../src/client/slots.ts' +import { SessionPanelState } from '../src/client/visibility.ts' +import { en, zh } from '../src/client/locales.ts' + +const SID = 'session-1' as SessionId +const t = makeTranslate(zh) as SessionPanelToggleProps['t'] +const DOCKED: SessionPanelVisibility = { pinned: true, overlay: null } + +function selectorOf(value: T) { + return (select: (current: T) => S): S => select(value) +} + +beforeEach(() => { + vi.stubGlobal('ResizeObserver', class { + observe(): void {} + unobserve(): void {} + disconnect(): void {} + }) + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true, addEventListener() {}, removeEventListener() {} }))) +}) + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() + vi.useRealTimers() +}) + +/** Whether a hovered anchor's tooltip shows before and at 500ms of hover. */ +function tooltipAfterHover(anchor: Element): { readonly early: boolean; readonly at500: boolean } { + vi.useFakeTimers() + fireEvent.pointerEnter(anchor, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(499) }) + const early = screen.queryByRole('tooltip', { hidden: true }) !== null + act(() => { vi.advanceTimersByTime(1) }) + return { early, at500: screen.queryByRole('tooltip', { hidden: true }) !== null } +} + +describe('SessionPanelToggle', () => { + function toggleProps(dockable: boolean | undefined, visibility: SessionPanelVisibility, toggle = vi.fn()) { + const renderSlot = vi.fn(() => 需要处理) + const entries: SessionPanelDockable = new Map(dockable === undefined ? [] : [[SID, dockable]]) + const props = { + sessionId: SID, useDockable: selectorOf(entries), useVisibility: selectorOf(visibility), toggle, renderSlot, t, + } as SessionPanelToggleProps + return { props, toggle, renderSlot } + } + + it('names the panel together with its indicators and reports the docked panel as expanded', () => { + const { props, renderSlot } = toggleProps(true, DOCKED) + render() + const button = screen.getByRole('button', { name: '会话面板 需要处理' }) + expect(button.getAttribute('aria-expanded')).toBe('true') + expect(button.getAttribute('aria-controls')).toBe(`dsh-session-panel-${SID}`) + expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.indicator', { panelShown: true }) + }) + + it('flips docking with room to dock and opens the overlay without it', () => { + const wide = toggleProps(true, DOCKED) + render() + fireEvent.click(screen.getByRole('button')) + expect(wide.toggle).toHaveBeenCalledWith(SID) + cleanup() + const narrow = toggleProps(false, DOCKED) + render() + const button = screen.getByRole('button') + expect(button.getAttribute('aria-expanded')).toBe('false') + expect(button.hasAttribute('aria-controls')).toBe(false) + fireEvent.click(button) + expect(narrow.toggle).toHaveBeenCalledWith(SID) + }) + + it('reports an open overlay as expanded', () => { + const { props } = toggleProps(false, { pinned: false, overlay: SID }) + render() + expect(screen.getByRole('button').getAttribute('aria-expanded')).toBe('true') + }) + + it('tells its indicators whether the panel shows', () => { + const { props, renderSlot } = toggleProps(false, DOCKED) + render() + expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.indicator', { panelShown: false }) + }) + + it('shows its tooltip after 500ms of hover', () => { + const { props } = toggleProps(true, DOCKED) + render() + expect(tooltipAfterHover(screen.getByRole('button'))).toEqual({ early: false, at500: true }) + }) + + it('is unavailable and says why while no Chat View shows the Session', () => { + const { props } = toggleProps(undefined, { pinned: true, overlay: SID }) + render() + const button = screen.getByRole('button') + expect(button.getAttribute('aria-disabled')).toBe('true') + expect(button.getAttribute('aria-expanded')).toBe('false') + expect(button.hasAttribute('aria-controls')).toBe(false) + fireEvent.keyDown(document.body, { key: 'Tab' }) + fireEvent.focus(button) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe('切换到「对话」视图后可显示会话面板') + }) +}) + +describe('SessionPanel', () => { + const SECTIONS: readonly SessionPanelSectionEntry[] = [ + { id: 'environment', label: '环境' }, + { id: 'change-requests', label: '变更请求' }, + ] + + /** Ids of the probes the rendered panels created, so a later props object answers for the mounted panel. */ + const probeIds = new Set() + afterEach(() => { probeIds.clear() }) + + /** Panel props whose dock probes all have, or all lack, room to dock. */ + function panelProps(dockable: boolean, visibility: SessionPanelVisibility, closeOverlay = vi.fn()) { + const owners: SessionPanelSectionOwnerProps[] = [] + const renderSlot = ((key: string, owner: object, opts?: { only?: string; entryKey?: string }): ReactNode => { + if (key === 'conversation.session.panel.section.actions') { + return opts?.entryKey === 'change-requests' ? : null + } + owners.push(owner as SessionPanelSectionOwnerProps) + return

    {`${opts?.only ?? ''} body`}

    + }) as SessionPanelProps['renderSlot'] + const attached = vi.fn<(element: HTMLElement | null) => void>() + const createProbeRef = vi.fn((_sessionId: SessionId, probe: string) => { + probeIds.add(probe) + return attached + }) + const props = { + sessionId: SID, + useVisibility: selectorOf(visibility), + useSections: selectorOf(SECTIONS), + useProbes: (select: (probes: SessionPanelProbes) => S): S => select(new Map([...probeIds].map(id => [id, dockable]))), + createProbeRef, + closeOverlay, + renderSlot, + t, + } as SessionPanelProps + return { props, owners, closeOverlay, createProbeRef, attached } + } + + it('attaches its dock probe through the injected ref once and detaches it on unmount', () => { + const { props, createProbeRef, attached } = panelProps(true, DOCKED) + const view = render() + const probe = view.container.querySelector('[data-session-panel-probe]') + expect(probe).not.toBeNull() + expect(createProbeRef.mock.calls).toEqual([[SID, expect.any(String)]]) + expect(attached.mock.calls).toEqual([[probe]]) + // A later render keeps the ref, so the probe is neither detached nor attached again. + const next = panelProps(true, DOCKED) + view.rerender() + expect(next.createProbeRef).not.toHaveBeenCalled() + expect(attached).toHaveBeenCalledTimes(1) + view.unmount() + expect(attached.mock.calls.at(-1)).toEqual([null]) + }) + + it('renders again only when its dock probe flips', () => { + const observed: { readonly element: Element; readonly callback: ResizeObserverCallback }[] = [] + vi.stubGlobal('ResizeObserver', class { + private readonly callback: ResizeObserverCallback + constructor(callback: ResizeObserverCallback) { this.callback = callback } + observe(element: Element): void { observed.push({ element, callback: this.callback }) } + unobserve(): void {} + disconnect(): void {} + }) + const state = new SessionPanelState() + const base = panelProps(false, DOCKED) + const props = { + ...base.props, + useProbes: bindSnapshotSelector(state.probes), + createProbeRef: (sessionId: SessionId, probe: string) => state.createProbeRef(sessionId, probe), + } as SessionPanelProps + const view = render() + const resize = (width: number): void => { + act(() => { + for (const { element, callback } of observed) { + callback([{ target: element, contentRect: { width } } as ResizeObserverEntry], {} as ResizeObserver) + } + }) + } + expect(observed.map(entry => entry.element)).toEqual([view.container.querySelector('[data-session-panel-probe]')]) + expect(screen.queryByRole('complementary')).toBeNull() + expect(state.dockable.getSnapshot().get(SID)).toBe(false) + resize(1) + expect(screen.getByRole('complementary').getAttribute('data-session-panel')).toBe('docked') + // CSS sizes the docked panel; no measured width reaches its style. + expect(screen.getByRole('complementary').getAttribute('style')).toBeNull() + const settled = base.owners.length + resize(1) + expect(base.owners).toHaveLength(settled) + // A probe under 1px wide sits within a pixel below the gutter that docks the panel. + resize(0.5) + expect(screen.queryByRole('complementary')).toBeNull() + expect(state.dockable.getSnapshot().get(SID)).toBe(false) + view.unmount() + expect(state.dockable.getSnapshot().has(SID)).toBe(false) + }) + + it('renders only its dock probe while hidden', () => { + const { props } = panelProps(true, { pinned: false, overlay: null }) + const view = render() + expect(view.container.querySelector('[data-session-panel]')).toBeNull() + expect(view.container.children).toHaveLength(1) + expect(view.container.firstElementChild?.hasAttribute('data-session-panel-probe')).toBe(true) + }) + + it('docks with one titled region per section in roster order and each section body', () => { + const { props, owners } = panelProps(true, DOCKED) + render() + const panel = screen.getByRole('complementary', { name: '会话面板' }) + expect(panel.getAttribute('data-session-panel')).toBe('docked') + expect(panel.id).toBe(`dsh-session-panel-${SID}`) + const regions = screen.getAllByRole('region') + expect(regions.map(region => region.getAttribute('aria-labelledby'))).toEqual([ + `dsh-session-panel-${SID}-environment`, `dsh-session-panel-${SID}-change-requests`, + ]) + expect(screen.getByRole('heading', { name: '变更请求' })).toBeTruthy() + expect(screen.getByText('environment body')).toBeTruthy() + expect(screen.getByRole('button', { name: '刷新' })).toBeTruthy() + expect(owners.every(owner => owner.presentation === 'docked')).toBe(true) + }) + + it('closes the overlay on Escape from inside and returns focus to the toggle', () => { + const { props, owners, closeOverlay } = panelProps(false, { pinned: true, overlay: SID }) + const toggle = document.createElement('button') + toggle.id = `dsh-session-panel-toggle-${SID}` + document.body.append(toggle) + try { + render() + const panel = screen.getByRole('complementary') + expect(panel.getAttribute('data-session-panel')).toBe('overlay') + fireEvent.keyDown(document, { key: 'Enter' }) + expect(closeOverlay).not.toHaveBeenCalled() + screen.getByRole('button', { name: '刷新' }).focus() + fireEvent.keyDown(document.activeElement as Element, { key: 'Escape' }) + expect(closeOverlay).toHaveBeenCalledWith(SID) + expect(document.activeElement).toBe(toggle) + owners[0]?.dismissOverlay() + expect(closeOverlay).toHaveBeenCalledTimes(2) + } finally { + toggle.remove() + } + }) + + it('closes the overlay on Escape from the page without moving focus', () => { + const { props, closeOverlay } = panelProps(false, { pinned: true, overlay: SID }) + render() + const outside = document.createElement('input') + document.body.append(outside) + try { + outside.focus() + fireEvent.keyDown(outside, { key: 'Escape' }) + expect(closeOverlay).toHaveBeenCalledWith(SID) + expect(document.activeElement).toBe(outside) + } finally { + outside.remove() + } + }) + + it('closes the overlay on an outside pointerdown but not on the panel, the toggle, or an open menu', () => { + const { props, closeOverlay } = panelProps(false, { pinned: true, overlay: SID }) + const toggle = document.createElement('button') + toggle.id = `dsh-session-panel-toggle-${SID}` + const menu = document.createElement('div') + menu.setAttribute('role', 'menu') + const item = document.createElement('button') + menu.append(item) + document.body.append(toggle, menu) + try { + render() + fireEvent.pointerDown(screen.getByText('environment body')) + fireEvent.pointerDown(toggle) + fireEvent.pointerDown(item) + expect(closeOverlay).not.toHaveBeenCalled() + fireEvent.pointerDown(document.body) + expect(closeOverlay).toHaveBeenCalledWith(SID) + } finally { + toggle.remove() + menu.remove() + } + }) + + it('leaves Escape to other handlers while docked, after another handler took it, or behind a modal', () => { + const docked = panelProps(true, DOCKED) + render() + fireEvent.keyDown(document, { key: 'Escape' }) + fireEvent.pointerDown(document.body) + expect(docked.closeOverlay).not.toHaveBeenCalled() + cleanup() + const overlay = panelProps(false, { pinned: true, overlay: SID }) + render() + const event = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }) + event.preventDefault() + document.dispatchEvent(event) + expect(overlay.closeOverlay).not.toHaveBeenCalled() + // A modal opened over the overlay registers its Escape after the panel's, so the panel sees it first. + function Modal() { + const dialog = useRef(null) + useModalLayer(dialog, true, () => {}) + return
    + } + const modal = render() + fireEvent.keyDown(document, { key: 'Escape' }) + expect(overlay.closeOverlay).not.toHaveBeenCalled() + modal.unmount() + fireEvent.keyDown(document, { key: 'Escape' }) + expect(overlay.closeOverlay).toHaveBeenCalledWith(SID) + }) + + it('leaves Escape to an input method composing text, including the key that ends the composition', () => { + const { props, closeOverlay } = panelProps(false, { pinned: true, overlay: SID }) + render() + fireEvent(document, new Event('compositionstart')) + fireEvent.keyDown(document, { key: 'Escape', isComposing: true }) + fireEvent(document, new Event('compositionend')) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(closeOverlay).not.toHaveBeenCalled() + fireEvent.keyUp(document, { key: 'Escape' }) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(closeOverlay).toHaveBeenCalledWith(SID) + }) + + it('hands focus to the toggle when the panel hides with the keyboard inside it', () => { + const toggle = document.createElement('button') + toggle.id = `dsh-session-panel-toggle-${SID}` + const outside = document.createElement('button') + document.body.append(toggle, outside) + try { + const docked = panelProps(true, DOCKED) + const view = render() + const control = screen.getByRole('button', { name: '刷新' }) + control.focus() + // Moves within the panel, and blurs that name no next target, keep the keyboard inside. + fireEvent.focusOut(control, { relatedTarget: screen.getByRole('complementary') }) + fireEvent.focusOut(control, { relatedTarget: null }) + view.rerender() + expect(document.activeElement).toBe(toggle) + // Focus that already left the panel stays where it went. + view.rerender() + screen.getByRole('button', { name: '刷新' }).focus() + outside.focus() + view.rerender() + expect(document.activeElement).toBe(outside) + // A panel that hides without having held focus moves nothing. + view.rerender() + view.rerender() + expect(document.activeElement).toBe(outside) + } finally { + toggle.remove() + outside.remove() + } + }) +}) + +describe('EnvironmentSection', () => { + it('renders its rows straight into the section body', () => { + const renderSlot = vi.fn(() => row) + render(<>{EnvironmentSection({ renderSlot } as EnvironmentSectionProps)}) + expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.environment.row', {}) + expect(screen.getByText('row')).toBeTruthy() + }) +}) + +describe('ProjectRow', () => { + function rowProps(over: { + workingDirectory?: string | null + workspacePath?: string + cwd?: string + home?: string + }, open = vi.fn()) { + const renderFactorySlot = vi.fn((_name: string, input: { label: string }) => ) + const props = { + sessionId: SID, + useProjection: (key: string) => key === 'workingDirectory' ? over.workingDirectory : undefined, + useWorkspaces: selectorOf({ + items: over.workspacePath === undefined ? [] : [{ path: over.workspacePath, sessionIds: [SID] }], + }), + useSessions: selectorOf({ byId: over.cwd === undefined ? {} : { [SID]: { cwd: over.cwd } } }), + useHost: selectorOf({ home: over.home, isLoopback: true }), + useContextMenu: contextMenuHook(open), + renderFactorySlot, + t, + } as ProjectRowProps + return { props, renderFactorySlot, open } + } + + function folderOf(container: HTMLElement): { name: string | null; parent: string | null } { + const folder = container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement + const [name, parent] = [...folder.children] + return { name: name?.textContent ?? null, parent: parent?.textContent ?? null } + } + + it('shows the working directory as its name and parent folder, with the label and full path in the tooltip', () => { + const { props, renderFactorySlot } = rowProps({ + workingDirectory: '/Users/me/projects/app/.worktrees/fix', + cwd: '/Users/me/projects/app', + workspacePath: '/Users/me/projects/app', + home: '/Users/me', + }) + const view = render() + expect(folderOf(view.container)).toEqual({ name: 'fix', parent: '~/projects/app/.worktrees' }) + fireEvent.keyDown(document.body, { key: 'Tab' }) + fireEvent.focus(view.container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement) + expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe('工作目录\n~/projects/app/.worktrees/fix') + fireEvent.blur(view.container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement) + expect(tooltipAfterHover(view.container.querySelector('[data-session-panel-project] [tabindex="0"]') as HTMLElement)) + .toEqual({ early: false, at500: true }) + expect(renderFactorySlot).toHaveBeenCalledWith('contextMenu.button', expect.objectContaining({ + target: { kind: 'directory', value: { sessionId: SID, path: '/Users/me/projects/app/.worktrees/fix' } }, + label: '工作目录操作', + })) + expect(renderFactorySlot.mock.calls[0]?.[1]).not.toHaveProperty('size') + expect(screen.getByRole('button', { name: '工作目录操作' })).toBeTruthy() + }) + + it('marks its parts for the panel\'s row rules: icon and folder in the body, then the More button as the row menu', () => { + const view = render() + const row = view.container.querySelector('[data-session-panel-row]') as HTMLElement + expect(row.hasAttribute('data-session-panel-project')).toBe(true) + expect([...row.children].map(part => part.getAttribute('data-row-part'))).toEqual(['body', 'menu']) + const [body, menu] = [...row.children] as [HTMLElement, HTMLElement] + expect(body.tagName).toBe('SPAN') + expect([...body.children].map(part => part.getAttribute('data-row-part'))).toEqual(['icon', 'content']) + expect(body.children[0]?.getAttribute('aria-hidden')).toBe('true') + expect(body.children[1]?.textContent).toBe('app/srv') + expect(menu.querySelector('button')?.textContent).toBe('工作目录操作') + }) + + it('falls back to the directory the Session was created in and opens the directory menu on right-click', () => { + const { props, open } = rowProps({ cwd: '/srv/app', workspacePath: '/srv' }) + const view = render() + expect(folderOf(view.container)).toEqual({ name: 'app', parent: '/srv' }) + fireEvent.contextMenu(view.container.querySelector('[data-session-panel-project]') as HTMLElement) + expect(open).toHaveBeenCalledWith({ kind: 'directory', value: { sessionId: SID, path: '/srv/app' } }, expect.anything()) + }) + + it('falls back to the listing Workspace when no directory is recorded, keeping a root parent and omitting an absent one', () => { + const atRoot = render() + expect(folderOf(atRoot.container)).toEqual({ name: 'srv', parent: '/' }) + atRoot.unmount() + const atHome = render() + expect(folderOf(atHome.container)).toEqual({ name: '~', parent: null }) + }) + + it('renders nothing before the Session directory is known', () => { + const { props } = rowProps({}) + const view = render() + expect(view.container.innerHTML).toBe('') + }) +}) + +describe('dictionaries', () => { + it('keeps the English dictionary key-identical to the Chinese source of truth', () => { + expect(Object.keys(en).sort()).toEqual(Object.keys(zh).sort()) + }) +}) diff --git a/packages/client/ui-session-panel/tests/sections.client.spec.ts b/packages/client/ui-session-panel/tests/sections.client.spec.ts new file mode 100644 index 0000000000..5500f97256 --- /dev/null +++ b/packages/client/ui-session-panel/tests/sections.client.spec.ts @@ -0,0 +1,43 @@ +import { describe, expect, it, vi } from 'vitest' +import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' +import { projectSections } from '../src/client/sections.ts' + +function entry(id: string, order: number | undefined, label: StoredEntry['options']['label'], registrant?: string): StoredEntry { + return { + component: () => null, + options: { id, ...order === undefined ? {} : { order }, ...label === undefined ? {} : { label } }, + ...registrant === undefined ? {} : { registrant }, + } +} + +describe('projectSections', () => { + it('orders sections by ascending order, keeping registration order for ties, and resolves locale thunks', () => { + const report = vi.fn() + const sections = projectSections([ + entry('later', 100, 'Change requests'), + entry('first', 0, () => 'Environment'), + entry('tie', 100, 'Outputs'), + entry('default', undefined, 'Default order'), + ], report) + expect(sections).toEqual([ + { id: 'first', label: 'Environment' }, + { id: 'default', label: 'Default order' }, + { id: 'later', label: 'Change requests' }, + { id: 'tie', label: 'Outputs' }, + ]) + expect(report).not.toHaveBeenCalled() + }) + + it('reports and leaves out a section that cannot be titled', () => { + const report = vi.fn() + const sections = projectSections([ + entry('untitled', 0, undefined, 'acme-plugin'), + entry('blank', 1, ''), + entry('titled', 2, 'Titled'), + ], report) + expect(sections).toEqual([{ id: 'titled', label: 'Titled' }]) + expect(report).toHaveBeenCalledTimes(2) + expect(report.mock.calls[0]?.[0]).toContain('"untitled" from acme-plugin') + expect(report.mock.calls[1]?.[0]).toContain('"blank" from an unknown registrant') + }) +}) diff --git a/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts new file mode 100644 index 0000000000..048c87a7a7 --- /dev/null +++ b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts @@ -0,0 +1,116 @@ +/** + * The Session panel's stylesheet as CSS text. jsdom has no layout, so the + * component suite cannot show that the dock probe is 1px wide exactly from + * the gutter that holds the docked panel, or that marked rows get one + * geometry; this reads the declarations and evaluates the docking ones for + * gutters around that boundary. + */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const css = readFileSync(fileURLToPath(new URL('../src/client/SessionPanel.module.css', import.meta.url)), 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, ' ') + +/** Declarations of the rule with exactly this selector list, with whitespace collapsed. */ +function declarationsOf(selector: string): Record { + const pattern = selector.split(',').map(part => part.trim().replace(/[.[\]():*+^$\\'=]/g, '\\$&')).join('\\s*,\\s*') + const rule = new RegExp(`(?:^|[{}])\\s*${pattern}\\s*\\{([^{}]*)\\}`).exec(css) + if (rule === null) throw new Error(`SessionPanel.module.css has no \`${selector}\` rule`) + const entries = (rule[1] ?? '').split(';').map(part => part.trim()).filter(Boolean).map((part): [string, string] => { + const colon = part.indexOf(':') + return [part.slice(0, colon).trim(), part.slice(colon + 1).replace(/\s+/g, ' ').replace(/\( /g, '(').replace(/ \)/g, ')').trim()] + }) + return Object.fromEntries(entries) +} + +const px = (value: string | undefined): number => { + const match = /^(-?\d+(?:\.\d+)?)px$/.exec(value ?? '') + if (match === null) throw new Error(`not a px length: ${String(value)}`) + return Number(match[1]) +} + +describe('SessionPanel.module.css docking geometry', () => { + const metrics = declarationsOf('.panel, .dockProbe') + const clear = px(metrics['--panel-clear']) + const edge = px(metrics['--panel-edge']) + const minWidth = px(metrics['--panel-min-width']) + + it('derives the docked width and the dock probe from one set of metrics', () => { + expect([clear, edge, minWidth]).toEqual([40, 8, 300]) + const panel = declarationsOf('.panel') + expect(panel['right']).toBe('var(--panel-edge)') + expect(panel['width']).toBe( + 'clamp(var(--panel-min-width), calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge)), 360px)', + ) + const probe = declarationsOf('.dockProbe') + expect(probe['width']).toBe( + 'calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width) + 1px)', + ) + expect(probe['max-width']).toBe('1px') + }) + + it('makes the probe 1px wide exactly from the gutter that holds the panel at its minimum width', () => { + // The declarations above, evaluated: a width below 0 is used as 0, and max-width caps the probe at 1px. + const probeWidth = (gutter: number): number => Math.min(1, Math.max(0, gutter - clear - edge - minWidth + 1)) + const dockedWidth = (gutter: number): number => Math.min(360, Math.max(minWidth, gutter - clear - edge)) + expect([probeWidth(0), probeWidth(347), probeWidth(347.5), probeWidth(348), probeWidth(900)]).toEqual([0, 0, 0.5, 1, 1]) + // At the first gutter that docks, the panel is at its minimum width and keeps both clearances. + expect(dockedWidth(348)).toBe(minWidth) + expect(348 - dockedWidth(348) - edge).toBe(clear) + expect([dockedWidth(377), dockedWidth(500)]).toEqual([329, 360]) + }) + + it('keeps the probe out of sight, out of the layout flow, and away from the pointer', () => { + expect(declarationsOf('.dockProbe')).toMatchObject({ + 'position': 'absolute', 'height': '0', 'visibility': 'hidden', 'pointer-events': 'none', + }) + }) + + it('floats the overlay narrower than the docked panel, at the same edge inset', () => { + expect(declarationsOf(".panel[data-session-panel='overlay']")['width']).toBe('min(280px, calc(100% - 2 * var(--panel-edge)))') + }) +}) + +describe('SessionPanel.module.css row rules', () => { + /** A rule for marked row markup: `.panel :where()`. */ + const row = (inner: string, tail = ''): Record => declarationsOf(`.panel :where(${inner})${tail}`) + + it('lays a marked row out as one 28px line with the icon and the menu on fixed columns', () => { + expect(row('[data-session-panel-row]')).toMatchObject({ + 'display': 'flex', 'align-items': 'center', 'gap': '8px', 'min-height': '28px', 'padding': '0 6px', + }) + expect(row("[data-session-panel-row] > [data-row-part='body']")).toMatchObject({ flex: '1 1 auto', height: '28px', gap: '8px' }) + // 6px of padding and half of the 16px box put the icon's center 14px from the row's start, and the menu's from its end. + expect(row("[data-session-panel-row] [data-row-part='icon']")).toMatchObject({ width: '16px', height: '16px', flex: 'none' }) + expect(row("[data-session-panel-row] > [data-row-part='menu']")).toMatchObject({ 'width': '16px', 'justify-content': 'center' }) + expect(row("[data-session-panel-row] [data-row-part='content']")).toMatchObject({ + 'overflow': 'hidden', 'text-overflow': 'ellipsis', 'white-space': 'nowrap', + }) + }) + + it('makes a button body the action of the whole row and rings the row when it has keyboard focus', () => { + expect(row("[data-session-panel-row] > button[data-row-part='body']", '::after')).toMatchObject({ position: 'absolute', inset: '0' }) + expect(row("[data-session-panel-row] > [data-row-part='trailing'], [data-session-panel-row] > [data-row-part='menu']")) + .toMatchObject({ 'position': 'relative', 'z-index': '1' }) + expect(row("[data-session-panel-row]:has(> button[data-row-part='body']:focus-visible)")['outline-offset']).toBe('-2px') + }) + + it('gives a plain button in the menu a 24px target and a tertiary glyph without a fill', () => { + expect(row("[data-session-panel-row] > [data-row-part='menu']", ' button')).toMatchObject({ + width: '24px', height: '24px', margin: '-4px', background: 'transparent', color: 'var(--dsw-alias-label-tertiary)', + }) + }) + + it('highlights only a row with an action or a menu that renders something, and keeps an open menu and its row shown', () => { + const interactive = "[data-session-panel-row]:has(> button[data-row-part='body'], > [data-row-part='menu']:not(:empty))" + expect(row("[data-session-panel-row] > [data-row-part='menu']:empty")).toEqual({ display: 'none' }) + expect(row(`${interactive}:has([aria-expanded='true'])`)['background']).toBe('var(--dsw-alias-interactive-bg-hover)') + expect(row("[data-session-panel-row] > [data-row-part='menu']:has([aria-expanded='true'])")['opacity']).toBe('1') + // Hover rules stay inside the hover media query, where the menu hides until the row is hovered or focused. + const hover = /@media \(hover: hover\) \{([\s\S]*?)\n\}/.exec(css)?.[1] ?? '' + expect(hover).toContain(`.panel :where(${interactive}:hover)`) + expect(hover).toMatch(/\[data-row-part='menu'\]\) \{\s*opacity: 0;/) + expect(css.replace(/@media \(hover: hover\) \{[\s\S]*?\n\}/g, '')).not.toContain(':hover') + }) +}) diff --git a/packages/client/ui-session-panel/tests/visibility.client.spec.ts b/packages/client/ui-session-panel/tests/visibility.client.spec.ts new file mode 100644 index 0000000000..29ee583e7a --- /dev/null +++ b/packages/client/ui-session-panel/tests/visibility.client.spec.ts @@ -0,0 +1,263 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { PINNED_STORAGE_KEY, SessionPanelState, presentationOf } from '../src/client/visibility.ts' + +const A = 'session-a' as SessionId +const B = 'session-b' as SessionId + +/** What the stubbed ResizeObserver holds for each observed probe element. */ +interface Observation { + /** Deliver one size report for the element. */ + readonly report: (width: number) => void + /** Whether the observer was disconnected. */ + disconnected: boolean +} + +const observations = new Map() +let nextProbe = 0 + +beforeEach(() => { + localStorage.clear() + observations.clear() + vi.stubGlobal('ResizeObserver', class { + private readonly callback: ResizeObserverCallback + private readonly targets: Observation[] = [] + constructor(callback: ResizeObserverCallback) { this.callback = callback } + observe(element: Element): void { + const observation: Observation = { + report: (width) => { this.callback([{ target: element, contentRect: { width } } as ResizeObserverEntry], {} as ResizeObserver) }, + disconnected: false, + } + this.targets.push(observation) + observations.set(element, observation) + } + + unobserve(): void {} + disconnect(): void { for (const observation of this.targets) observation.disconnected = true } + }) +}) + +afterEach(() => { + localStorage.clear() + vi.unstubAllGlobals() +}) + +/** + * One mounted panel's dock probe: its id, a size report for its element, and + * its detachment, as the panel's ref drives them. + */ +function probeOf(state: SessionPanelState, sessionId: SessionId, width = 0) { + nextProbe += 1 + const id = `probe-${nextProbe}` + const element = document.createElement('span') + const ref = state.createProbeRef(sessionId, id) + ref(element) + const observation = observations.get(element) + if (observation === undefined) throw new Error('the probe element is not observed') + if (width > 0) observation.report(width) + return { id, element, observation, resize: observation.report, detach: () => { ref(null) } } +} + +/** A state whose Chat Views show `A` and `B` without room to dock. */ +function newState() { + const state = new SessionPanelState() + return { state, a: probeOf(state, A), b: probeOf(state, B) } +} + +describe('presentationOf', () => { + it.each([ + [true, true, null, 'docked'], + [true, true, A, 'docked'], + [true, false, null, 'hidden'], + [true, false, A, 'hidden'], + [false, true, null, 'hidden'], + [false, false, null, 'hidden'], + [false, true, A, 'overlay'], + [false, false, A, 'overlay'], + [false, true, B, 'hidden'], + ] as const)('fits=%s pinned=%s overlay=%s shows %s', (fits, pinned, overlay, expected) => { + expect(presentationOf(fits, { pinned, overlay }, A)).toBe(expected) + }) +}) + +describe('SessionPanelState dock probes', () => { + it('enters an attached probe without room and gives it room from 1px of width', () => { + const state = new SessionPanelState() + expect(state.probes.getSnapshot().size).toBe(0) + const probe = probeOf(state, A) + expect(state.probes.getSnapshot().get(probe.id)).toBe(false) + expect(state.dockable.getSnapshot().get(A)).toBe(false) + // Within a pixel below the gutter that docks the panel the probe is narrower than 1px. + probe.resize(0.5) + expect(state.probes.getSnapshot().get(probe.id)).toBe(false) + probe.resize(1) + expect(state.probes.getSnapshot().get(probe.id)).toBe(true) + expect(state.dockable.getSnapshot().get(A)).toBe(true) + probe.resize(0) + expect(state.probes.getSnapshot().get(probe.id)).toBe(false) + expect(state.dockable.getSnapshot().get(A)).toBe(false) + }) + + it('gives a Session room while any of its probes has it, and drops the Session once its last probe detaches', () => { + const state = new SessionPanelState() + const main = probeOf(state, A, 1) + const embedded = probeOf(state, A) + expect(state.probes.getSnapshot()).toEqual(new Map([[main.id, true], [embedded.id, false]])) + expect(state.dockable.getSnapshot().get(A)).toBe(true) + main.detach() + expect(main.observation.disconnected).toBe(true) + expect(state.probes.getSnapshot()).toEqual(new Map([[embedded.id, false]])) + expect(state.dockable.getSnapshot().get(A)).toBe(false) + embedded.resize(1) + expect(state.dockable.getSnapshot().get(A)).toBe(true) + embedded.detach() + expect(state.dockable.getSnapshot().has(A)).toBe(false) + expect(state.probes.getSnapshot().size).toBe(0) + // A second detachment of the same element withdraws nothing more. + const before = state.dockable.getSnapshot() + embedded.detach() + expect(state.dockable.getSnapshot()).toBe(before) + }) + + it('publishes only when a probe flips or a Session changes its room', () => { + const state = new SessionPanelState() + const main = probeOf(state, A, 1) + const probes = state.probes.getSnapshot() + const dockable = state.dockable.getSnapshot() + let probeCalls = 0 + let sessionCalls = 0 + const offProbes = state.probes.subscribe(() => { probeCalls += 1 }) + const offSessions = state.dockable.subscribe(() => { sessionCalls += 1 }) + main.resize(1) + expect(state.probes.getSnapshot()).toBe(probes) + expect(state.dockable.getSnapshot()).toBe(dockable) + // A second Chat View without room changes the probes, not the Session's room. + const embedded = probeOf(state, A) + expect([probeCalls, sessionCalls]).toEqual([1, 0]) + main.resize(0) + expect([probeCalls, sessionCalls]).toEqual([2, 1]) + embedded.detach() + expect([probeCalls, sessionCalls]).toEqual([3, 1]) + offProbes() + offSessions() + }) + + it('keeps a probe without room where ResizeObserver is missing', () => { + vi.stubGlobal('ResizeObserver', undefined) + const state = new SessionPanelState() + const ref = state.createProbeRef(A, 'unobserved') + ref(document.createElement('span')) + expect(state.probes.getSnapshot().get('unobserved')).toBe(false) + expect(state.dockable.getSnapshot().get(A)).toBe(false) + ref(null) + expect(state.dockable.getSnapshot().has(A)).toBe(false) + }) + + it('stops observing every attached probe on dispose, after which a detachment withdraws nothing', () => { + const { state, a, b } = newState() + state.dispose() + expect([a.observation.disconnected, b.observation.disconnected]).toEqual([true, true]) + expect(state.probes.getSnapshot().size).toBe(0) + expect(state.dockable.getSnapshot().size).toBe(0) + const before = state.probes.getSnapshot() + a.detach() + expect(state.probes.getSnapshot()).toBe(before) + }) +}) + +describe('SessionPanelState visibility', () => { + it('docks by default and keeps the snapshot identity until a member changes', () => { + const { state } = newState() + const first = state.visibility.getSnapshot() + expect(first).toEqual({ pinned: true, overlay: null }) + expect(state.visibility.getSnapshot()).toBe(first) + }) + + it('flips and persists the docking preference when the gutter has room, closing any overlay', () => { + const { state, a } = newState() + state.toggle(A) + expect(state.visibility.getSnapshot().overlay).toBe(A) + a.resize(1) + expect(state.visibility.getSnapshot().overlay).toBeNull() + state.toggle(A) + expect(state.visibility.getSnapshot()).toEqual({ pinned: false, overlay: null }) + expect(localStorage.getItem(PINNED_STORAGE_KEY)).toBe('false') + expect(new SessionPanelState().visibility.getSnapshot().pinned).toBe(false) + state.toggle(A) + expect(state.visibility.getSnapshot().pinned).toBe(true) + }) + + it('opens and closes one Session overlay without touching the docking preference', () => { + const { state } = newState() + state.toggle(A) + state.toggle(B) + expect(state.visibility.getSnapshot()).toEqual({ pinned: true, overlay: B }) + state.closeOverlay(A) + expect(state.visibility.getSnapshot().overlay).toBe(B) + state.toggle(B) + expect(state.visibility.getSnapshot().overlay).toBeNull() + state.toggle(A) + state.closeOverlay(A) + expect(state.visibility.getSnapshot().overlay).toBeNull() + }) + + it('ignores the toggle of a Session that no Chat View shows', () => { + const state = new SessionPanelState() + const before = state.visibility.getSnapshot() + state.toggle(A) + expect(state.visibility.getSnapshot()).toBe(before) + }) + + it('treats a stored value other than false as the default', () => { + localStorage.setItem(PINNED_STORAGE_KEY, '"yes"') + expect(newState().state.visibility.getSnapshot().pinned).toBe(true) + }) + + it('notifies subscribers of both members and stops after unsubscribe', () => { + const { state, a } = newState() + let calls = 0 + const off = state.visibility.subscribe(() => { calls += 1 }) + state.toggle(A) + a.resize(1) + state.toggle(A) + const seen = calls + expect(seen).toBeGreaterThanOrEqual(2) + off() + state.toggle(A) + expect(calls).toBe(seen) + }) + + it('closes an overlay once its gutter can dock the panel, without reopening it when the gutter narrows again', () => { + const { state, a } = newState() + state.toggle(A) + a.resize(0.5) + expect(state.visibility.getSnapshot().overlay).toBe(A) + a.resize(1) + expect(state.visibility.getSnapshot()).toEqual({ pinned: true, overlay: null }) + a.resize(0) + expect(presentationOf(false, state.visibility.getSnapshot(), A)).toBe('hidden') + }) + + it('closes an overlay once no Chat View shows its Session, so returning to it shows no overlay', () => { + const { state, a } = newState() + state.toggle(A) + a.detach() + expect(state.visibility.getSnapshot().overlay).toBeNull() + probeOf(state, A) + expect(presentationOf(false, state.visibility.getSnapshot(), A)).toBe('hidden') + }) + + it('follows only the open overlay, and nothing after dispose', () => { + const { state, a } = newState() + state.toggle(A) + state.toggle(B) + // A's Chat View no longer matters once B holds the overlay. + a.detach() + expect(state.visibility.getSnapshot().overlay).toBe(B) + // Dispose withdraws B's probe too, but nothing follows the overlay any longer. + state.dispose() + expect(state.dockable.getSnapshot().has(B)).toBe(false) + expect(state.visibility.getSnapshot().overlay).toBe(B) + }) +}) diff --git a/packages/client/ui-session-panel/tsconfig.json b/packages/client/ui-session-panel/tsconfig.json new file mode 100644 index 0000000000..e868af02be --- /dev/null +++ b/packages/client/ui-session-panel/tsconfig.json @@ -0,0 +1,66 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../../api/session-controller/tsconfig.client.json" + }, + { + "path": "../../api/workspace-controller/tsconfig.client.json" + }, + { + "path": "../connection/tsconfig.client.json" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../store" + }, + { + "path": "../ui-chat/tsconfig.client.json" + }, + { + "path": "../ui-context-menu" + }, + { + "path": "../ui-conversation/tsconfig.client.json" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-session" + }, + { + "path": "../ui-slots" + }, + { + "path": "../../core/session" + }, + { + "path": "../../util/workspace-path" + }, + { + "path": "../../session/working-directory" + }, + { + "path": "../../workspace/workspace" + } + ] +} diff --git a/packages/client/ui-session-panel/tsdown.config.ts b/packages/client/ui-session-panel/tsdown.config.ts new file mode 100644 index 0000000000..7aa03cebc1 --- /dev/null +++ b/packages/client/ui-session-panel/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-sidebar-browser/src/client/browser/url.ts b/packages/client/ui-sidebar-browser/src/client/browser/url.ts index 3ced712338..5bcadea93a 100644 --- a/packages/client/ui-sidebar-browser/src/client/browser/url.ts +++ b/packages/client/ui-sidebar-browser/src/client/browser/url.ts @@ -35,7 +35,7 @@ export function parseBrowserAddress(input: string, applicationOrigin?: string): if (applicationOrigin !== undefined && applicationOrigin !== 'null') { try { if (url.origin === new URL(applicationOrigin).origin) return { ok: false, reason: 'application-origin' } - } catch { + } catch (_invalidApplicationOrigin) { // An unavailable application origin cannot grant access to a target. } } diff --git a/packages/client/ui-sidebar-right/README.i18n.yaml b/packages/client/ui-sidebar-right/README.i18n.yaml index ae8159f93c..0fbcd1aa5d 100644 --- a/packages/client/ui-sidebar-right/README.i18n.yaml +++ b/packages/client/ui-sidebar-right/README.i18n.yaml @@ -36,8 +36,8 @@ en: b6c64c7649203e12 zh: c9341bbfd548a5eb /deepseek-ai-dsh-client-ui-sidebar-right/the-guide: - en: 68fd575ef382223e - zh: 1ab1653ee20c64e9 + en: 2cc38fa6666dbc17 + zh: 1063018c8fe95012 /deepseek-ai-dsh-client-ui-sidebar-right/copy: en: 67386560b71672a4 zh: 35cf8cb7ddf618ce diff --git a/packages/client/ui-sidebar-right/README.md b/packages/client/ui-sidebar-right/README.md index b336f6f165..7fac795ae6 100644 --- a/packages/client/ui-sidebar-right/README.md +++ b/packages/client/ui-sidebar-right/README.md @@ -126,7 +126,7 @@ A tab type can declare `multiple: true` for independent instances such as termin Default pages depend on the number of registered guide entries, not tab types or open tabs. Exactly one entry opens its page directly; zero or multiple entries open the guide. Explicitly adding a guide always opens the guide. Closing follows the [sole-docked-tab rule](#state). -The guide tab is a muted compass over one entry capsule per `guide` entry the registered types contributed, in `order`, centred in the body; the guide has no words of its own. A capsule shows the entry's glyph — or the guide's quieter cube placeholder when the entry registered none — and its title; while at most four entries are listed, an entry that registered a `description` shows it under the title, and a longer list drops every description. Picking a default capsule or a **More tools** row calls `tab.actions.openTab(entry.kind, { replaceTab: true })` and then `tab.actions.close()`, so the guide gives way to the page it opened and closes itself when that page was revealed; the open-page shortcut from a focused guide does the same. A pane holds at most one guide tab. The strip's add control is drawn only while its pane holds none and opens one there with `openTab('guide', { paneId, revealIfOpened: false })`, so a guide in another pane does not capture the click; opening the guide into a pane that already has one focuses it instead; a guide dragged, dropped, or docked into such a pane merges into it — the arriving guide closes and the pane's own is focused; `duplicateTab` on the guide records nothing. A split, an expanded empty root pane, and the pane a sole tab vacates by dropping on its own edge use the same default-page rule, one tab per new pane; the self-edge drop leaves the dragged tab focused. A plain `openTab('guide')` opens or focuses the guide only within the active or named pane. Splitting an empty pane does nothing and returns no new pane. The product allows two horizontal panes, initially equal, with divider ratios limited to 20%–80%. Insufficient width blocks a new split; with two panes already present, a body drop moves the tab between panes instead of creating a third. At the two-pane limit, split controls are disabled with a focusable reason; closing back to one pane enables them. +The guide tab is a muted compass over one entry capsule per `guide` entry the registered types contributed, in `order`, centred in the body; a guide taller than its pane starts at the top and scrolls. The guide has no words of its own. A capsule shows the entry's glyph — or the guide's quieter cube placeholder when the entry registered none — and its title; while at most four entries are listed, an entry that registered a `description` shows it under the title, and a longer list drops every description. Picking a default capsule or a **More tools** row calls `tab.actions.openTab(entry.kind, { replaceTab: true })` and then `tab.actions.close()`, so the guide gives way to the page it opened and closes itself when that page was revealed; the open-page shortcut from a focused guide does the same. A pane holds at most one guide tab. The strip's add control is drawn only while its pane holds none and opens one there with `openTab('guide', { paneId, revealIfOpened: false })`, so a guide in another pane does not capture the click; opening the guide into a pane that already has one focuses it instead; a guide dragged, dropped, or docked into such a pane merges into it — the arriving guide closes and the pane's own is focused; `duplicateTab` on the guide records nothing. A split, an expanded empty root pane, and the pane a sole tab vacates by dropping on its own edge use the same default-page rule, one tab per new pane; the self-edge drop leaves the dragged tab focused. A plain `openTab('guide')` opens or focuses the guide only within the active or named pane. Splitting an empty pane does nothing and returns no new pane. The product allows two horizontal panes, initially equal, with divider ratios limited to 20%–80%. Insufficient width blocks a new split; with two panes already present, a body drop moves the tab between panes instead of creating a third. At the two-pane limit, split controls are disabled with a focusable reason; closing back to one pane enables them. ## Copy diff --git a/packages/client/ui-sidebar-right/README.zh.md b/packages/client/ui-sidebar-right/README.zh.md index 039062a104..54aef8cc2f 100644 --- a/packages/client/ui-sidebar-right/README.zh.md +++ b/packages/client/ui-sidebar-right/README.zh.md @@ -126,7 +126,7 @@ root 作用域的 `sidebar.right.tab.guide.actions` list 有注册项时,引 默认页取决于已注册的引导入口数,不取决于 tab 类型数或已打开的 tab 数。恰好一个入口时直接打开对应页面;没有入口或有多个入口时打开引导页。显式添加引导页始终打开引导页。关闭遵循[唯一停靠 tab 规则](#state)。 -引导 tab 是一枚弱化的罗盘,下方是各已注册类型贡献的每个 `guide` 条目一个入口胶囊,按 `order` 排列并在正文中居中;引导页自己没有文字。胶囊显示条目的图标——条目没注册图标时用引导页自己更浅的立方体占位符——和标题;列出的条目不超过四个时,注册了 `description` 的条目在标题下显示它,更长的列表则去掉所有描述。点击默认胶囊或**更多工具**菜单行会调用 `tab.actions.openTab(entry.kind, { replaceTab: true })`,再调用 `tab.actions.close()`,于是引导页让位给它打开的页,该页被揭示时引导页关闭自己;在聚焦的引导页上用快捷键打开页时也是如此。一个格最多持有一个引导 tab。tab 条的添加控件只在该格没有引导 tab 时绘制,并以 `openTab('guide', { paneId, revealIfOpened: false })` 在该格打开一个,这样别的格里的引导页不会截走这次点击;把引导页开进已有引导页的格则改为聚焦它;把引导页拖入、放入或收回到这样的格会合并进去——来者关闭,该格自己的被聚焦;对引导页 `duplicateTab` 不记录任何东西。分栏、展开且为空的根格、以及唯一 tab 拖到本格边缘分屏后腾出的格使用相同的默认页规则,每个新格一个 tab;这种本格边缘拖放让被拖的 tab 保持聚焦。普通的 `openTab('guide')` 只在活跃或指定分栏内打开或聚焦引导页。对空分栏执行 split 不产生变化,也不返回新分栏。产品最多保留左右两格,默认均分,分隔条限定在 20%~80%。宽度不足以容纳两格时不允许新分栏;已有两格时,正文拖放用于跨格移动,不再创建第三格。达到两格上限时禁用分栏控件并提供可聚焦的原因提示;关闭回单格后重新启用。 +引导 tab 是一枚弱化的罗盘,下方是各已注册类型贡献的每个 `guide` 条目一个入口胶囊,按 `order` 排列并在正文中居中;引导页高于所在格时从顶部开始排列并可滚动。引导页自己没有文字。胶囊显示条目的图标——条目没注册图标时用引导页自己更浅的立方体占位符——和标题;列出的条目不超过四个时,注册了 `description` 的条目在标题下显示它,更长的列表则去掉所有描述。点击默认胶囊或**更多工具**菜单行会调用 `tab.actions.openTab(entry.kind, { replaceTab: true })`,再调用 `tab.actions.close()`,于是引导页让位给它打开的页,该页被揭示时引导页关闭自己;在聚焦的引导页上用快捷键打开页时也是如此。一个格最多持有一个引导 tab。tab 条的添加控件只在该格没有引导 tab 时绘制,并以 `openTab('guide', { paneId, revealIfOpened: false })` 在该格打开一个,这样别的格里的引导页不会截走这次点击;把引导页开进已有引导页的格则改为聚焦它;把引导页拖入、放入或收回到这样的格会合并进去——来者关闭,该格自己的被聚焦;对引导页 `duplicateTab` 不记录任何东西。分栏、展开且为空的根格、以及唯一 tab 拖到本格边缘分屏后腾出的格使用相同的默认页规则,每个新格一个 tab;这种本格边缘拖放让被拖的 tab 保持聚焦。普通的 `openTab('guide')` 只在活跃或指定分栏内打开或聚焦引导页。对空分栏执行 split 不产生变化,也不返回新分栏。产品最多保留左右两格,默认均分,分隔条限定在 20%~80%。宽度不足以容纳两格时不允许新分栏;已有两格时,正文拖放用于跨格移动,不再创建第三格。达到两格上限时禁用分栏控件并提供可聚焦的原因提示;关闭回单格后重新启用。 ## 文案 diff --git a/packages/client/ui-sidebar-right/src/client/tab-inventory.ts b/packages/client/ui-sidebar-right/src/client/tab-inventory.ts index 1dfc139518..1fc33eeb1b 100644 --- a/packages/client/ui-sidebar-right/src/client/tab-inventory.ts +++ b/packages/client/ui-sidebar-right/src/client/tab-inventory.ts @@ -21,19 +21,21 @@ export class SidebarTabInventory { /** Read saved layouts once before the root service is published. */ constructor() { + let keys: readonly (string | null)[] = [] try { - if (typeof localStorage === 'undefined') return - const keys = Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)) - for (const key of keys) { - if (key === null || !key.startsWith(`${sidebarPersistence}.`)) continue - const sessionId = key.slice(sidebarPersistence.length + 1) as SessionId - const saved = readSidebarLayout(sessionId) - if (saved !== undefined) this.sessions.set(sessionId, Object.values(saved.layout.tabs).map(tab => ({ - sessionId, tabId: tab.id, kind: tab.kind, contentId: tab.contentId, - }))) - } - this.publish() - } catch (_storageUnavailable) { /* Adopted in-memory layouts still publish their open tabs. */ } + keys = typeof localStorage === 'undefined' ? [] : Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)) + } catch (_storageUnavailable) { + // Inaccessible storage holds no saved layouts; adopted in-memory layouts still publish their open tabs. + } + for (const key of keys) { + if (key === null || !key.startsWith(`${sidebarPersistence}.`)) continue + const sessionId = key.slice(sidebarPersistence.length + 1) as SessionId + const saved = readSidebarLayout(sessionId) + if (saved !== undefined) this.sessions.set(sessionId, Object.values(saved.layout.tabs).map(tab => ({ + sessionId, tabId: tab.id, kind: tab.kind, contentId: tab.contentId, + }))) + } + this.publish() } /** diff --git a/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.module.css b/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.module.css index b78983aa2d..f3d2133213 100644 --- a/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.module.css +++ b/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.module.css @@ -2,23 +2,26 @@ stylesheet does not carry them. Tokens only. */ /* The capsules form one centred column at the column's own 14px gap, lifted - above the body's middle by the spacer below. The minimum height centres a - short guide while allowing a tall guide to grow into the pane's scroller. */ + above the body's middle by the spacer below. The guide fills the tab body, + which clips, and scrolls itself; `safe` centring starts a guide taller than + the pane at its top so every capsule stays reachable. The block padding + keeps a scrolled-to-end capsule's focus ring off the pane's edge. */ .guide { --dsl-guide-entry-radius: var(--dsw-radius-xl); display: flex; + flex: 1 1 auto; flex-direction: column; gap: 14px; align-items: center; - justify-content: center; + justify-content: safe center; box-sizing: border-box; - min-height: 100%; - padding: 0 24px; + padding: 14px 24px; + overflow-y: auto; } /* The lift, as a share of the pane's height (a column flex basis resolves against it): the centred column rises 5% of the pane, and a short pane - gives it up before the capsules clip. */ + gives it up before the column overflows. */ .guide::after { content: ''; flex: 0 1 10%; diff --git a/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx b/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx index 4cff92b514..6c73fa8869 100644 --- a/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx +++ b/packages/client/ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx @@ -9,8 +9,9 @@ * cannot be outvoted by accident. * * The shipped guide is a muted compass over the pinned entry capsules every - * registered type contributed, centred in the body, with no heading, as a - * browser start page shows its doors without a caption. While at most four + * registered type contributed, centred in the body (scrolling from the top when + * taller than the pane), with no heading, as a browser start page shows its + * doors without a caption. While at most four * capsules are visible, a capsule with a description shows it under the title; * a longer list drops every description to stay light. A More card follows * while `sidebar.right.tab.guide.actions` has registrations. diff --git a/packages/client/ui-skill/src/client/SkillRow.tsx b/packages/client/ui-skill/src/client/SkillRow.tsx index cee91367cf..fb3c3710ca 100644 --- a/packages/client/ui-skill/src/client/SkillRow.tsx +++ b/packages/client/ui-skill/src/client/SkillRow.tsx @@ -27,16 +27,17 @@ function firstLine(text: string): string { /** Skill names are the only call argument the compact row presents. */ function skillName(argsRaw: string, callId: string): string { + let parsed: unknown try { - const parsed: unknown = JSON.parse(argsRaw) - if (typeof parsed === 'object' && parsed !== null) { - const name = (parsed as Record).name - if (typeof name === 'string' && name !== '') return firstLine(name) - } - } catch { + parsed = JSON.parse(argsRaw) + } catch (_truncatedArgs) { // Streaming can expose a truncated JSON prefix; its first line is still // more useful than replacing the call with an unrelated catalog lookup. } + if (typeof parsed === 'object' && parsed !== null) { + const name = (parsed as Record).name + if (typeof name === 'string' && name !== '') return firstLine(name) + } return argsRaw === '' ? callId : firstLine(argsRaw) } diff --git a/packages/client/ui-tool/src/client/contract/slots.ts b/packages/client/ui-tool/src/client/contract/slots.ts index f07bf685e8..22689a876d 100644 --- a/packages/client/ui-tool/src/client/contract/slots.ts +++ b/packages/client/ui-tool/src/client/contract/slots.ts @@ -15,9 +15,8 @@ import type { ToolFileInjected } from '../tool/file-menu.ts' declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { /** - * Key by wire name, including custom tools. Use `key: ''`; a typo never renders. - * Occupied keys replace the view; unclaimed keys use the generic row. Owner - * phase data includes `name` and lazy `args`; preparing arguments may be incomplete. + * Key by wire name, including custom tools; a typo never renders. Unclaimed keys use the generic row. + * Use `key: ''` to replace the view; phase data has `name` and lazy, possibly partial `args`. */ 'tool.call.toolview': { kind: 'keyed' diff --git a/packages/client/ui-tool/src/client/tool/models/inspection-details-model.ts b/packages/client/ui-tool/src/client/tool/models/inspection-details-model.ts index 652ee09333..1b9d8cf9bd 100644 --- a/packages/client/ui-tool/src/client/tool/models/inspection-details-model.ts +++ b/packages/client/ui-tool/src/client/tool/models/inspection-details-model.ts @@ -18,11 +18,11 @@ function dateText(value: string | number, locale: string): string { function cordisDetails(name: string, args: Record, value: unknown, t: DetailTranslate): ToolDetailsModel | null { if (!detailRecord(value)) return null - if (name === 'cordis_inspect_list') { + if (name === 'cordis_inspect_list' || (name === 'cordis_inspect' && Array.isArray(value.providers))) { if (!Array.isArray(value.providers)) return null return detailList(inspectionItems(value.providers, t), t('detail.providers.count', { count: value.providers.length }), t) } - if (name === 'cordis_inspect_query') { + if (name === 'cordis_inspect_query' || name === 'cordis_inspect') { if (!('data' in value) || typeof value.provider !== 'string' || typeof value.method !== 'string') return null return detailList(inspectionItems(value.data, t), `${value.provider}.${value.method}`, t) } @@ -164,6 +164,7 @@ export function inspectionDetails( ): ToolDetailsModel | null { if (hasSpillNotice(text)) return null switch (name) { + case 'cordis_inspect': case 'cordis_inspect_list': case 'cordis_inspect_query': case 'cordis_inspect_self': return cordisDetails(name, args, json, t) diff --git a/packages/client/ui-tool/src/client/tool/models/tool-call-model.ts b/packages/client/ui-tool/src/client/tool/models/tool-call-model.ts index 9f81138d3b..3c5c6291a3 100644 --- a/packages/client/ui-tool/src/client/tool/models/tool-call-model.ts +++ b/packages/client/ui-tool/src/client/tool/models/tool-call-model.ts @@ -95,6 +95,7 @@ const TOOL_TITLE_KEYS: Record = { schedule_edit: 'tool.title.editSchedule', schedule_delete: 'tool.title.deleteSchedule', schedule_update: 'tool.title.updateSchedule', + cordis_inspect: 'tool.title.inspect', cordis_inspect_list: 'tool.title.inspectProviders', cordis_inspect_query: 'tool.title.queryRuntime', cordis_inspect_self: 'tool.title.inspectPlugins', diff --git a/packages/client/ui-tool/src/client/tool/toolviews/details-row.tsx b/packages/client/ui-tool/src/client/tool/toolviews/details-row.tsx index dbf66f7951..559691a2f5 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/details-row.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/details-row.tsx @@ -64,7 +64,9 @@ export function DetailsRow({ toolName, block, cwd, home, openFile, inspect, useD const operation = toolName === 'lsp' ? parsedToolCall(block)?.args.operation : undefined const titleKey = typeof operation === 'string' && Object.hasOwn(LSP_TITLE_KEYS, operation) ? LSP_TITLE_KEYS[operation as keyof typeof LSP_TITLE_KEYS] - : model.titleKey + : toolName === 'cordis_inspect' + ? parsedToolCall(block)?.args.query === undefined ? 'tool.title.inspectProviders' : 'tool.title.queryRuntime' + : model.titleKey const isWait = toolName === 'wait_agent' return ( { }) it('accepts Cordis, workflow, and Ralph producer results', () => { + expect(details('cordis_inspect', '{"providers":[{"name":"Service","status":"ready"}]}')?.summary).toBe('1 inspect providers') + expect(details('cordis_inspect', '{"provider":"Service","method":"get","data":{"value":1}}')?.summary).toBe('Service.get') + expect(details('cordis_inspect', '{}')).toBeNull() expect(details('cordis_inspect_list', '{"providers":[{"name":"Service","status":"ready"}]}')?.summary).toBe('1 inspect providers') expect(details('cordis_inspect_query', '{"provider":"Service","method":"get","data":{"value":1}}')?.summary).toBe('Service.get') expect(details('cordis_inspect_self', '{"mode":"client","plugins":[]}')?.summary).toBe('0 dynamic plugins') diff --git a/packages/client/ui-tool/tests/details-row.client.spec.tsx b/packages/client/ui-tool/tests/details-row.client.spec.tsx index e21206109f..9379f04f7a 100644 --- a/packages/client/ui-tool/tests/details-row.client.spec.tsx +++ b/packages/client/ui-tool/tests/details-row.client.spec.tsx @@ -211,15 +211,32 @@ describe('DetailsRow', () => { expect(header.textContent).toBe('Waiting for messages…') }) + it.each([ + ['cordis_inspect_list', {}, { providers: [] }], + ['cordis_inspect_query', { platform: 'host', provider: 'Service', method: 'listService' }, { provider: 'Service', method: 'listService', data: {} }], + ] as const)('keeps the %s title and details for the unified tool', (legacyName, query, value) => { + const legacy = result(legacyName, value, JSON.stringify(query)) + const current = result('cordis_inspect', value, JSON.stringify(legacyName === 'cordis_inspect_list' ? {} : { query })) + expect(detailsCardModel(current, t, 'en')).toEqual(detailsCardModel(legacy, t, 'en')) + const oldView = render( + [0]} />, + ) + const title = screen.getByRole('button', { expanded: false }).textContent + oldView.unmount() + render([0]} />) + expect(screen.getByRole('button', { expanded: false }).textContent).toBe(title) + }) + it('registers the supported tool names through the scoped keyed slot', () => { const register = vi.fn((_spec: unknown, _component: unknown) => () => undefined) const inject = vi.fn((_name: string, callback: () => Iterable<() => void>) => { for (const dispose of callback()) dispose() }) detailsToolview.apply({ slots: { inject, register } } as never) - expect(register.mock.calls).toHaveLength(40) + expect(register.mock.calls).toHaveLength(41) const specs = register.mock.calls.map(([spec]) => spec) expect(specs).toContainEqual({ name: 'tool.call.toolview', key: 'subagent_fork', locale: 'conversation' }) + expect(specs).toContainEqual({ name: 'tool.call.toolview', key: 'cordis_inspect', locale: 'conversation' }) expect(specs).toContainEqual({ name: 'tool.call.toolview', key: 'cordis_inspect_query', locale: 'conversation' }) for (const key of ['schedule_create', 'schedule_list', 'schedule_view', 'schedule_edit', 'schedule_update', 'schedule_delete']) { expect(specs).toContainEqual({ name: 'tool.call.toolview', key, locale: 'conversation' }) diff --git a/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts b/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts index 0cee57d7bf..077baefc03 100644 --- a/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts +++ b/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts @@ -5,7 +5,7 @@ import * as PtcToolExecutor from '@deepseek-ai/dsh-tool-executor-ptc' import { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import type { ToolResultNode } from '@deepseek-ai/dsh-client-ui-chat/client' -import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcInspectableValue, PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' import type { PtcRunRequest, PtcRunSpec, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import { estimateContent } from '@deepseek-ai/dsh-token-meter/estimate' import type { ToolCallId } from '@deepseek-ai/dsh-llm' @@ -61,7 +61,8 @@ async function executeShell(text: string, nested: boolean, name = 'bash', maxInl async run(spec: PtcRunSpec): Promise { const tool = spec.bindings.find(binding => binding.global === 'tools')?.functions[name] if (tool === undefined) throw new Error('missing fixture binding') - const blocks = await tool(shellArgs) + const resolved = await tool(shellArgs) + const blocks = resolved instanceof PtcInspectableValue ? resolved.value : resolved expect(blocks).toEqual([{ type: 'text', text }]) return { output: [{ type: 'text', text: 'true' }] } } diff --git a/packages/context/file-reference-local/tests/search.spec.ts b/packages/context/file-reference-local/tests/search.spec.ts index a12b41a5b6..639119048c 100644 --- a/packages/context/file-reference-local/tests/search.spec.ts +++ b/packages/context/file-reference-local/tests/search.spec.ts @@ -47,7 +47,7 @@ async function workspace(): Promise { await writeFile(join(root, 'node_modules', 'ignored-package', 'index.js'), 'ignored') try { await symlink(join(root, 'src', 'tui.spec.ts'), join(root, 'linked-test.ts')) - } catch { + } catch (_symlinkDenied) { // Windows may deny symlink creation without Developer Mode; the product // still skips every non-file/non-directory Dirent on platforms that expose one. } diff --git a/packages/context/session-reference/src/index.ts b/packages/context/session-reference/src/index.ts index 4392a2578d..b9f83f8140 100644 --- a/packages/context/session-reference/src/index.ts +++ b/packages/context/session-reference/src/index.ts @@ -197,6 +197,13 @@ export class SessionReferenceResolver extends TypertRemoteService { * * Discovery runs at keystroke rate, so titles and subagent labels only ever * come from projection reads; sessions without either fall back to their id. + * + * The list names every Session the session index holds, whatever identity the + * caller acts for; it is not narrowed to Sessions that caller else can read. + * A share viewer therefore learns the id, title, and working-directory path of + * each Session on the owner Host, and {@link prepare} reads the snapshot of a + * cited Session without asking who cited it. That exposure is a recorded + * LiveShare limitation, not a grant: narrowing the list is deferred. * @param agent - target agent; self is excluded and its cwd drives ranking. * @param query - optional search text: label and display title match * fuzzily, session id and working directory as substrings. Matches keep the diff --git a/packages/core/tool-executor-ptc/README.i18n.yaml b/packages/core/tool-executor-ptc/README.i18n.yaml index 1974e1e0f9..009b299646 100644 --- a/packages/core/tool-executor-ptc/README.i18n.yaml +++ b/packages/core/tool-executor-ptc/README.i18n.yaml @@ -15,14 +15,14 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-tool-executor-ptc/use-this-package: - en: a883aa8ddca03a66 - zh: c926a9100d2b506f + en: 5e30a05bb69e7ebe + zh: caecedba18dcae4f /deepseek-ai-dsh-tool-executor-ptc/understand-the-implementation: en: 78708b3779d999a9 zh: ad6173f9f01630de /deepseek-ai-dsh-tool-executor-ptc/understand-the-implementation/ptc-mode: - en: d93c8f10d1247f80 - zh: a35d953631ca1c83 + en: 4da0f9293816b976 + zh: c5f77ea403d30ff5 /deepseek-ai-dsh-tool-executor-ptc/further-exploration: en: ee69078c38c655a9 zh: fb0873407f23c8c5 @@ -60,8 +60,8 @@ en: f4703836365dc3d4 zh: a09ff48a6550fd69 /deepseek-ai-dsh-tool-executor-ptc/known-limitations-and-deferred-work: - en: b45acbcff554e15a - zh: 170ec90af3d0adc3 + en: 0159ba9c4dda070f + zh: 9be2f81d398868a1 /deepseek-ai-dsh-tool-executor-ptc/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/core/tool-executor-ptc/README.md b/packages/core/tool-executor-ptc/README.md index 3cdbebcf8c..6adeaa3400 100644 --- a/packages/core/tool-executor-ptc/README.md +++ b/packages/core/tool-executor-ptc/README.md @@ -40,6 +40,8 @@ Root `run_code` calls are exclusive and execute serially. `maxParallelSubCalls` `PtcRuntime` providers must report `language: 'typescript'`. The selected executor rejects other languages during prompt assembly and execution, without falling back to native tools; the `/run-code` factory rejects them when creating a program tool. Schema reads and execution also validate the current provider. The executor generates a TypeScript SDK and tool schema; the provider supplies execution. +Tool calls retain their declared JSON return values. Passing an unchanged object or array result directly to `inspect` displays the tool's final text-only output. Fields, copies, modified results, and results nested inside another value use ordinary Node formatting. Use `inspect({ ...result })` for an object's raw structure or `inspect(result.lines)` for selected fields. Scalar results use ordinary formatting; Images and mixed text/image outputs follow the image rules below. + This package declares `ctx.ptcRuntime` and `ctx.systemPrompt` as required injections; Agent-owned programs need `ctx.workingDirectory`. The executor activates only after its runtime is available and withdraws when that runtime unloads. An enabled PTC executor without a runtime stops application startup. A withdrawn PTC selection never falls back to native execution. Shared dispatch events and the `ptc-mode` message-source declaration live in `@deepseek-ai/dsh-tool-executor-ptc/types`; Client code imports the same declarations through `@deepseek-ai/dsh-tool-executor-ptc/client`. Both entries exclude Host service declarations. Host policy extensions use `import type` from the package entry for `PtcDispatchLog` and `tools/ptc-dispatch-log` without mounting the executor. @@ -64,9 +66,11 @@ The executor receives the entire raw call batch and owns parsing, scheduling, ca The PTC executor exposes the reserved `run_code` transport and a deterministic TypeScript SDK. Each SDK binding captures a frozen ToolSchema and passes it through the scheduler to its execution context. Before policy, a started call records only pairing ids, name, and normalized arguments; its settle event preserves the rendered result, optional presentation metadata, and structured error. Metadata is projected from that call’s canonical value and frozen; it changes neither the program value nor model content. Description and parameters remain transient and never enter Session events or SDK output. Calls are scheduled through a per-run pool that reuses the native concurrency contract. Under `ptc` alone, a model-direct call naming a program-only SDK tool resolves to `UNKNOWN_TOOL` before policy — the announced surface and the callable surface stay the same. Intermediate binding values are execution-local; only the outer `run_code` result has a hard size cap. +Text inspection reuses the completed pipeline's `output.render` result after content policies. It neither executes the tool nor renders it again. Replacements made only for the dispatch log do not change the program's inspection text. + New sub-calls use `:ptc:` ids. Consumers treat these ids as opaque and correlate events by exact equality; restored historical ids retain their original bytes. The [PTC mode decision](../../../.agents/notes/implemented/feature/2026-06-15-ptc.md) owns durable naming and restoration rules. -TypeScript bindings for `read_image` and CUA screenshot operations return an `Image` with a readable `path`, `width`, and `height`. Passing it to `inspect` places its durable attachment among the captured text in the `run_code` result. Images nested in arrays and objects are displayed with their containing value. On program failure, inspected output accompanies the original diagnostic; outer result replacements remain authoritative. If an output policy removes a screenshot or read_image image, the binding rejects with ToolCallError and includes the retained text notice. Additional contexts retain their producing tool’s attribution. +TypeScript bindings for `read_image` and CUA screenshot operations return an `Image` with a readable `path`, `width`, and `height`. Other tool values are substituted all or nothing: when `{ type: 'image', attachment }` entries reference every image of the finalized result and the program can read each one, those entries become `Image`s, as admitted MCP image blocks do, and the result's text and images reach the model only through `inspect`; otherwise the value stays raw and the complete result content reaches the model as additional context. Passing it to `inspect` places its durable attachment among the captured text in the `run_code` result. Images nested in arrays and objects are displayed with their containing value. On program failure, inspected output accompanies the original diagnostic; outer result replacements remain authoritative. If an output policy removes a screenshot or read_image image, the binding rejects with ToolCallError and includes the retained text notice. Additional contexts retain their producing tool’s attribution. When the caller cancels and the runtime reports `abort`, `run_code` waits for cleanup and returns the native tool cancellation result: `AbortError` / `ABORTED`, with `Error: tool call aborted` as its content. Retained runtimes append their cancellation diagnostic, including whether variables were preserved or cleared. The Agent records the specific cancellation cause in `turn/end`, including a hook's reason. Other runtime failures retain `CODE_RUN_FAILED` and their diagnostics, even if the caller also cancels. A runtime rejection keeps a `PtcRuntimeError` code and otherwise becomes `CODE_RUN_FAILED` with the rejection as `cause`. A blank `description`, an invalid `timeoutMs`, or `timeoutMs` or `sandbox_permissions` on a runtime that does not support it fails as `ToolArgsError` with `INVALID_ARGS`; a call after executor disposal fails with `CODE_RUN_UNAVAILABLE`; and a missing runtime, `workingDirectory`, or `sandboxPolicy` fails as `ToolContextUnavailableError`. Cancellation can discard retained runtime state and does not undo completed tool effects. @@ -152,8 +156,8 @@ The schema remains stable while the caller's description and runtime settings re These constraints apply to the host integration and accepted calls. -- **Program Images cover read_image and CUA screenshots** — other image-producing tools keep their declared values and automatically attach their pictures as additional model context. -- **Program Images require attachment path mapping** — the filesystem must map stored host attachments to readable program paths. `fs-ssh` has no such mapping, so image adaptation rejects in that composition. +- **Program Images need a value reference** — read_image, CUA screenshots, and values whose `{ type: 'image', attachment }` entries reference every result image yield `Image`s; other image-producing tools keep their declared values and automatically attach their pictures as additional model context. +- **Program Images require attachment path mapping** — the filesystem must map stored host attachments to readable program paths. `fs-ssh` has no such mapping, so read_image and CUA image adaptation rejects in that composition, while value-referenced images stay raw JSON and reach the model as additional context. - **No built-in reset control** — the shipped Loader plugin does not expose its executor instance through a service, GUI control or SDK endpoint. Hosts needing reset must mount and retain `PtcExecutor` in their own composition; that integration owns retries after a failed reset. - **PTC mode uses TypeScript, and presentation is per agent rather than per tool** — PTC execution requires `ctx.ptcRuntime.language === 'typescript'`; within one agent no tool can be native-only while another is ptc-only. - **PTC mode intermediate values are execution-local and unbounded by bytes** — they cannot be reconstructed from session replay and may exhaust process or worker memory; only the outer `run_code` output has the worker's configurable hard cap. diff --git a/packages/core/tool-executor-ptc/README.zh.md b/packages/core/tool-executor-ptc/README.zh.md index ab4de1124c..5662d9f5b5 100644 --- a/packages/core/tool-executor-ptc/README.zh.md +++ b/packages/core/tool-executor-ptc/README.zh.md @@ -40,6 +40,8 @@ kind: "package-reference" `PtcRuntime` 提供方必须报告 `language: 'typescript'`。已选中的执行器在提示词组装与执行时拒绝其他语言,不回落到 native 工具;`/run-code` 工厂在创建程序工具时拒绝其他语言。读取 schema 和执行时也会验证当前提供方。执行器生成 TypeScript SDK 与工具 schema;提供方负责执行。 +工具调用保留声明的 JSON 返回值。将未修改的对象或数组结果直接传给 `inspect`,会展示工具最终的纯文本输出。字段、拷贝、修改后的结果,以及嵌套在其他值中的结果,使用普通 Node 格式。可用 `inspect({ ...result })` 查看对象的原始结构,或用 `inspect(result.lines)` 展示选定字段。标量结果使用普通格式;Image 和混合文本与图片的输出遵循下文的图片规则。 + 本包将 `ctx.ptcRuntime` 和 `ctx.systemPrompt` 声明为必需注入;带 Agent 的程序要求 `ctx.workingDirectory`。执行器在运行时可用后才激活,并在运行时卸载时撤回。启用 PTC 执行器但未提供运行时会阻止应用启动。已撤回的 PTC 选择不会回退到原生执行。 共享分派事件与 `ptc-mode` 消息来源声明位于 `@deepseek-ai/dsh-tool-executor-ptc/types`;Client 代码通过 `@deepseek-ai/dsh-tool-executor-ptc/client` 导入同一组声明。两个入口都不引入 Host 服务声明。Host 策略扩展通过包主入口的 `import type` 获取 `PtcDispatchLog` 与 `tools/ptc-dispatch-log`,无需挂载执行器。 @@ -64,9 +66,11 @@ kind: "package-reference" PTC 执行器公开保留的 `run_code` 传输,以及确定性的 TypeScript SDK。每个 SDK 绑定捕获冻结的 ToolSchema,经由调度器传入该次执行上下文。已开始的调用在策略之前只记录配对 id、名称和规范化参数;其结算事件保留渲染结果、可选展示元数据与结构化错误;元数据由该次调用的规范值投影并冻结,不改变程序读取的值或模型内容。描述与参数 schema 仅临时存活,不进入 Session 事件或 SDK 输出。调用通过复用原生并发约定的每次运行独有池调度。在纯 `ptc` 下,模型直呼仅供程序使用的 SDK 工具都会在策略之前解析为 `UNKNOWN_TOOL`——通告面与可调用面保持一致。中间绑定值只存在于执行局部;只有外层 `run_code` 结果有硬大小上限。 +文本展示复用已完成流水线中经过内容策略处理的 `output.render` 结果,不会再次执行工具或渲染。仅针对派发日志的替换不改变程序的展示文本。 + 新子调用使用 `:ptc:` 标识。消费方将这些标识视为不透明值,并通过精确相等关联事件;恢复的历史标识保留原始字节。[PTC mode 决策](../../../.agents/notes/implemented/feature/2026-06-15-ptc.zh.md) 负责持久化命名与恢复规则。 -TypeScript 中的 `read_image` 与 CUA 截图操作返回 `Image`,其中包含可读取的 `path`、`width` 和 `height`。将其传给 `inspect` 后,持久附件会按顺序与文本一起进入 `run_code` 结果。数组和对象内嵌的图片会随所在值一起展示。程序失败时,已 inspect 的输出随原始诊断一起呈现;外层替换的结果保持生效。输出策略移除截图或 read_image 图片时,绑定以 ToolCallError 拒绝,并包含保留的文本提示。额外上下文保留生成工具的归属。 +TypeScript 中的 `read_image` 与 CUA 截图操作返回 `Image`,其中包含可读取的 `path`、`width` 和 `height`。其他工具的返回值按全有或全无的方式替换:当 `{ type: 'image', attachment }` 条目引用了最终结果中的每张图片且程序能读取每张图片时,这些条目会变为 `Image`,与已接受的 MCP 图片块相同,结果的文本与图片仅通过 `inspect` 进入模型;否则返回值保持原样,完整的结果内容作为额外上下文进入模型。将其传给 `inspect` 后,持久附件会按顺序与文本一起进入 `run_code` 结果。数组和对象内嵌的图片会随所在值一起展示。程序失败时,已 inspect 的输出随原始诊断一起呈现;外层替换的结果保持生效。输出策略移除截图或 read_image 图片时,绑定以 ToolCallError 拒绝,并包含保留的文本提示。额外上下文保留生成工具的归属。 调用方取消且运行时报告 `abort` 时,`run_code` 等待清理完成,并返回原生工具的取消结果:`AbortError` / `ABORTED`,内容为 `Error: tool call aborted`。保留状态的运行时会附加取消诊断,包括变量被保留还是清空。Agent 在 `turn/end` 中记录具体取消原因,包括 hook 的理由。其他运行时失败保留 `CODE_RUN_FAILED` 及其诊断,即使调用方同时取消。运行时拒绝保留 `PtcRuntimeError` 的 code,否则变为 `CODE_RUN_FAILED` 并以该拒绝为 `cause`。`description` 为空白、`timeoutMs` 无效,或运行时不支持却传入 `timeoutMs` 或 `sandbox_permissions` 时,以带 `INVALID_ARGS` 的 `ToolArgsError` 失败;执行器释放后的调用以 `CODE_RUN_UNAVAILABLE` 失败;缺少运行时、`workingDirectory` 或 `sandboxPolicy` 时以 `ToolContextUnavailableError` 失败。取消可能丢弃保留的运行时状态,也不会撤销已完成的工具操作。 @@ -152,8 +156,8 @@ Error: code run failed (abort): run_code exceeded its limit of 2048 tool calls ( 以下约束适用于宿主集成及已开始的调用。 -- **程序 Image 仅覆盖 read_image 与 CUA 截图**:其他图片工具保留其声明的返回值,并将图片自动附加到模型的额外上下文。 -- **程序 Image 要求附件路径映射**:文件系统必须将宿主存储的附件映射为程序可读的路径。`fs-ssh` 没有这项映射,因此该组合中的图片适配会拒绝。 +- **程序 Image 需要返回值引用**:read_image、CUA 截图以及其 `{ type: 'image', attachment }` 条目引用了每张结果图片的返回值会产生 `Image`;其他图片工具保留其声明的返回值,并将图片自动附加到模型的额外上下文。 +- **程序 Image 要求附件路径映射**:文件系统必须将宿主存储的附件映射为程序可读的路径。`fs-ssh` 没有这项映射,因此该组合中的 read_image 与 CUA 图片适配会拒绝,而返回值引用的图片保持原始 JSON,并作为额外上下文进入模型。 - **没有内置重置控件**:自带的 Loader 插件不通过服务、GUI 控件或 SDK 端点暴露执行器实例。需要重置的宿主必须在自己的组合中挂载并保留 `PtcExecutor`,该集成负责失败后的重试。 - **PTC mode 使用 TypeScript,且呈现方式按 agent 而非按工具**:PTC 执行要求 `ctx.ptcRuntime.language === 'typescript'`;同一个 agent 内不能让一个工具仅使用 Native,而另一个仅使用 PTC。 - **PTC mode 中间值只存在于执行局部,且没有字节上限**:它们无法从会话回放重建,并可能耗尽进程或 worker 内存;只有外层 `run_code` 输出受 worker 可配置的硬上限约束。 diff --git a/packages/core/tool-executor-ptc/src/program-images.ts b/packages/core/tool-executor-ptc/src/program-images.ts new file mode 100644 index 0000000000..40ebc43824 --- /dev/null +++ b/packages/core/tool-executor-ptc/src/program-images.ts @@ -0,0 +1,52 @@ +/** + * Program images for tool values that reference their result images through + * `{ type: 'image', attachment }` entries, such as admitted MCP image blocks. + * @module + */ + +import type { ImageBlock } from '@deepseek-ai/dsh-llm' +import type { PtcJsonValue } from '@deepseek-ai/dsh-ptc-runtime' +import type { JsonValue } from '@deepseek-ai/dsh-util-values' + +/** + * Replace each image entry whose attachment is one of the finalized result images. + * Entries naming another attachment, such as an image a policy removed, stay JSON. + * @param value - Canonical tool value; it is not modified. + * @param images - Image blocks of the finalized result content. + * @param image - Creates the program value for one finalized reference, or returns undefined when the program cannot read it. + * @returns The substituted value, or undefined unless every finalized image was substituted. + */ +export function substituteProgramImages( + value: JsonValue, images: readonly ImageBlock[], image: (ref: ImageBlock['attachment']) => PtcJsonValue | undefined, +): PtcJsonValue | undefined { + const refs = new Map(images.map(block => [String(block.attachment.attachmentId), block.attachment])) + const substituted = new Set() + const unreadable = new Set() + const result = mapImageEntries(value, (attachmentId) => { + const ref = refs.get(attachmentId) + if (ref === undefined) return undefined + const programImage = image(ref) + if (programImage === undefined) unreadable.add(attachmentId) + else substituted.add(attachmentId) + return programImage + }) + return unreadable.size === 0 && substituted.size === refs.size ? result : undefined +} + +function mapImageEntries(value: JsonValue, replace: (attachmentId: string) => PtcJsonValue | undefined): PtcJsonValue { + if (value === null || typeof value !== 'object') return value + if (Array.isArray(value)) { + const items = value.map(item => mapImageEntries(item, replace)) + return items.some((item, index) => item !== value[index]) ? items : value + } + const attachment = value.attachment + if (value.type === 'image' && attachment !== null && typeof attachment === 'object' && !Array.isArray(attachment) + && typeof attachment.attachmentId === 'string') { + const replaced = replace(attachment.attachmentId) + if (replaced !== undefined) return replaced + } + const entries = Object.entries(value) + const mapped = entries.map(([key, item]) => [key, mapImageEntries(item, replace)] as const) + // Object.fromEntries defines own data properties, so a `__proto__` key stays an ordinary key. + return mapped.some(([, item], index) => item !== entries[index]?.[1]) ? Object.fromEntries(mapped) : value +} diff --git a/packages/core/tool-executor-ptc/src/ptc.ts b/packages/core/tool-executor-ptc/src/ptc.ts index aa8158d8ad..9cffc34185 100644 --- a/packages/core/tool-executor-ptc/src/ptc.ts +++ b/packages/core/tool-executor-ptc/src/ptc.ts @@ -13,8 +13,8 @@ import { brandString } from '@deepseek-ai/dsh-brand' import { createUserMessage, HarnessError, resolveImageAttachmentAccess } from '@deepseek-ai/dsh-llm' import type { ContentBlock, ToolCallId, ToolSchema } from '@deepseek-ai/dsh-llm' -import { PtcImage } from '@deepseek-ai/dsh-ptc-runtime' -import type { PtcOutput } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcImage, PtcInspectableValue } from '@deepseek-ai/dsh-ptc-runtime' +import type { PtcJsonValue, PtcOutput } from '@deepseek-ai/dsh-ptc-runtime' import type { PtcBindingFunction, PtcRunResult, PtcRunSandbox, PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' import { approveEscalation, ESCALATION_TARGETS, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox' import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox' @@ -31,6 +31,7 @@ import { toolErrorMessage } from '@deepseek-ai/dsh-tools/pipeline' import { scopeTarget } from '@deepseek-ai/dsh-scope' import type { PtcCalls } from './ptc-calls.ts' import { CodeRunFailedError, ToolCallLimitExceededError } from './errors.ts' +import { substituteProgramImages } from './program-images.ts' import type { Config } from './config.ts' import type { RunCodeToolOptions } from './run-code.ts' import type { ToolDefinition, ToolExecution, ToolExecutionFailure, ToolExecutionResult, ToolRunContext } from '@deepseek-ai/dsh-tools' @@ -244,13 +245,17 @@ export function createRunCodeTransport( failure?: Pick output: PtcOutput[] }>() - const programImage = (ref: ImageRef): PtcImage => { + const readableImage = (ref: ImageRef): PtcImage | undefined => { const attachments = ctx.get('attachments') const fs = ctx.get('fs') const access = attachments === undefined || fs === undefined ? undefined : resolveImageAttachmentAccess(attachments, path => fs.processPathFromHostPath(path), ref) - if (access === undefined) throw new Error('Image storage must expose a readable path in the program filesystem') - return new PtcImage(access.readonlyPath, ref) + return access === undefined ? undefined : new PtcImage(access.readonlyPath, ref) + } + const programImage = (ref: ImageRef): PtcImage => { + const image = readableImage(ref) + if (image === undefined) throw new Error('Image storage must expose a readable path in the program filesystem') + return image } const stateOwners = new WeakMap>() const definition = defineTool({ @@ -452,7 +457,7 @@ export function createRunCodeTransport( // would be narrowed away by control flow analysis. const runOver = (): boolean => runController.signal.aborted - const binding = (schema: ToolSchema): PtcBindingFunction => async (rawArgs: unknown): Promise => { + const binding = (schema: ToolSchema): PtcBindingFunction => async (rawArgs: unknown): Promise => { const { name } = schema // FIXME: Let image-producing tools declare their program result adaptation. const usesProgramImage = name === 'read_image' || name === 'cua' @@ -480,13 +485,13 @@ export function createRunCodeTransport( signal: runController.signal, } type DispatchOutcome = { isError: true; message: string } - | { isError: false; value: JsonValue; content: ContentBlock[]; imageRemoved: boolean } + | { isError: false; value: PtcJsonValue; content: ContentBlock[]; imageRemoved: boolean } const outcome = await new Promise((resolve, reject) => { // Set by the dispatch stage (or start() for a pre-settled result): what commit() finalizes in submission order. let parked: | { kind: 'post-result' | 'final-result'; exec: ToolRunContext; result: ToolExecutionResult } | undefined - const settle = (result: ToolExecutionResult, imageRemoved: boolean): void => { + const settle = (result: ToolExecutionResult, imageRemoved: boolean, programValue?: PtcJsonValue): void => { // The program gets its value NOW: the log-content listener (for // example, a spill backend) must never delay the binding or occupy // a dispatch slot. The event append is tracked side work; the run's @@ -495,7 +500,7 @@ export function createRunCodeTransport( // chain cannot reject). resolve(result.isError ? { isError: true, message: result.error.message } - : { isError: false, value: result.value, content: result.content, imageRemoved }) + : { isError: false, value: programValue ?? result.value, content: result.content, imageRemoved }) const agent = exec.agent if (agent === undefined) return const task: Promise = (async () => { @@ -561,7 +566,18 @@ export function createRunCodeTransport( /* v8 ignore next -- commit() runs only after `settled` flipped, which set parked. */ if (parked === undefined) return const result = await executor.complete(parked.exec, parked) - if (!usesProgramImage && !result.isError && result.content.some(block => block.type === 'image')) { + const images = result.content.filter(block => block.type === 'image') + // A value carrying every result image goes to the program; otherwise the content reaches the model directly. + let programValue: PtcJsonValue | undefined + if (!usesProgramImage && !result.isError && images.length > 0) { + // The ordered lane must not reject: a failed substitution keeps the content in model context. + try { + programValue = substituteProgramImages(result.value, images, readableImage) + } catch (error: unknown) { + logger.warn(`tools: ${name} result images stay in model context: ${toolErrorMessage(error)}`) + } + } + if (!usesProgramImage && !result.isError && images.length > 0 && programValue === undefined) { exec.deferContext(createUserMessage({ content: result.content, source: { kind: 'ptc-mode' }, @@ -577,7 +593,7 @@ export function createRunCodeTransport( // failure cannot stop the turn through a recovering program. if (result.concludesTurn) exec.concludeTurn() settle(result, parked.result.content.some(block => block.type === 'image') - && !result.content.some(block => block.type === 'image')) + && images.length === 0, programValue) // Backpressure on pending event-append tasks: each task retains // a full result while a slow backend stores it, so the pool cap // bounds their count. Beyond the cap, the @@ -609,6 +625,10 @@ export function createRunCodeTransport( } if (name === 'read_image' || images.length > 1) throw new Error('Image-producing tools must return exactly one image') } + if (outcome.value !== null && typeof outcome.value === 'object' + && outcome.content.every(block => block.type === 'text')) { + return new PtcInspectableValue(outcome.value, outcome.content.map(block => block.text).join('\n')) + } return outcome.value } diff --git a/packages/core/tool-executor-ptc/tests/ptc.spec.ts b/packages/core/tool-executor-ptc/tests/ptc.spec.ts index 72776d464d..e0383fcb6d 100644 --- a/packages/core/tool-executor-ptc/tests/ptc.spec.ts +++ b/packages/core/tool-executor-ptc/tests/ptc.spec.ts @@ -10,11 +10,12 @@ import { Context } from '@deepseek-ai/cordis' import { brandString } from '@deepseek-ai/dsh-brand' import { createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' +import type { AttachmentId } from '@deepseek-ai/dsh-attachment' import type { ToolSchema } from '@deepseek-ai/dsh-llm' import { createScope } from '@deepseek-ai/dsh-scope' import type { Scope } from '@deepseek-ai/dsh-scope' import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt' -import { PtcRuntime, PtcRuntimeError } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcImage, PtcRuntime, PtcRuntimeError, PtcInspectableValue } from '@deepseek-ai/dsh-ptc-runtime' import type { PtcRunFailure, PtcRunRequest, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import ToolRuntime, { RUN_CODE_NAME, TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH, defineTool } from '@deepseek-ai/dsh-tools' import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit' @@ -175,6 +176,66 @@ async function runCode( }) } +it('carries final tool rendering with structured binding values independently of the durable log copy', async () => { + const { ctx, runtime } = await setup({ mode: 'ptc' }) + try { + const render = vi.fn((_args: unknown, value: { count: number }) => [{ type: 'text' as const, text: `Count: ${value.count}` }]) + ctx.tools.register(defineTool({ + name: 'count', description: 'Count a fixture.', parameters: {}, + output: { + schema: { type: 'object', additionalProperties: false, properties: { count: { type: 'number', required: true } } }, + render, + }, + execute: async () => ({ count: 2 }), + finalizeContent: () => [{ type: 'text', text: 'Final count: 2' }], + })) + ctx.on('tools/ptc-dispatch-log', async () => [{ type: 'text', text: 'Durable preview' }]) + const session = Session.create(brandString('ptc-inspection')) + const agent = { ctx, session } as Agent + runtime.behavior = async (request) => { + const result = await request.bindings[0]!.functions.count!({}) + expect(result).toBeInstanceOf(PtcInspectableValue) + if (!(result instanceof PtcInspectableValue)) throw new Error('Expected rendered binding value') + expect(result.value).toEqual({ count: 2 }) + expect(result.text).toBe('Final count: 2') + return printed(result.text) + } + const result = await runCode(ctx, 'inspect(await tools.count({}))', { agent }) + expect(result.isError).toBe(false) + expect(result.content).toEqual([{ type: 'text', text: 'Final count: 2' }]) + expect(render).toHaveBeenCalledOnce() + expect(session.snapshotEvents().find(event => event.type === 'tool/ptc-dispatch')?.data.content) + .toEqual([{ type: 'text', text: 'Durable preview' }]) + } finally { + await ctx.fiber.dispose() + } +}) + +it.each([{ value: [] }, { value: [1, 2] }])('carries rendered text for array binding value $value', async ({ value }) => { + const { ctx, runtime } = await setup({ mode: 'ptc' }) + try { + ctx.tools.register(defineTool({ + name: 'list', description: 'List a fixture.', parameters: {}, + output: { + schema: { type: 'array', items: { type: 'number' } }, + render: () => [{ type: 'text', text: 'List:' }, { type: 'text', text: `${value.length} items` }], + }, + execute: async () => value, + })) + runtime.behavior = async (request) => { + const result = await request.bindings[0]!.functions.list!({}) + expect(result).toBeInstanceOf(PtcInspectableValue) + if (!(result instanceof PtcInspectableValue)) throw new Error('Expected rendered binding value') + expect(result.value).toEqual(value) + expect(result.text).toBe(`List:\n${value.length} items`) + return printed(result.text) + } + expect((await runCode(ctx, 'inspect(await tools.list({}))')).isError).toBe(false) + } finally { + await ctx.fiber.dispose() + } +}) + it('logs detached frozen nested metadata without changing the binding value or log-content policy', async () => { const { ctx, runtime } = await setup({ mode: 'ptc' }) try { @@ -1646,25 +1707,30 @@ describe('the run_code dispatch bridge', () => { ]) }) - it('records image-bearing sub-call results for the TypeScript runtime', async () => { + it('delivers result images the program value does not reference as deferred context', async () => { const { ctx, runtime } = await setup({ mode: 'ptc' }) - ctx.tools.register(defineContentToolFixture({ + ctx.tools.register(defineTool({ name: 'image_result', description: 'Return one durable image.', parameters: {}, - execute: () => Promise.resolve([ - { type: 'text', text: 'image result' }, - { - type: 'image', - attachment: { - attachmentId: 'sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' as never, - mediaType: 'image/png', bytes: 1, width: 1, height: 1, + output: { + schema: { type: 'json' }, + render: () => [ + { type: 'text', text: 'image result' }, + { + type: 'image', + attachment: { + attachmentId: brandString('sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'), + mediaType: 'image/png', bytes: 1, width: 1, height: 1, + }, }, - }, - ]), + ], + }, + execute: () => Promise.resolve({ content: [{ type: 'text', text: 'image result' }, { type: 'image', data: 'AQ==' }] }), })) + let value: unknown runtime.behavior = async (request) => { - await request.bindings[0]!.functions.image_result!({}) + value = await request.bindings[0]!.functions.image_result!({}) return printed('done') } @@ -1678,6 +1744,85 @@ describe('the run_code dispatch bridge', () => { ], }]) expect(result.content).toEqual([{ type: 'text', text: 'done' }]) + expect(value).toEqual({ content: [{ type: 'text', text: 'image result' }, { type: 'image', data: 'AQ==' }] }) + }) + + it('substitutes program images for value entries that reference finalized result images', async () => { + const { ctx, runtime } = await setup({ mode: 'ptc' }) + onTestFinished(() => ctx.fiber.dispose()) + const ref = (letter: string) => ({ + attachmentId: brandString(`sha256:${letter.repeat(64)}`), mediaType: 'image/png' as const, bytes: 1, width: 1, height: 1, + }) + ctx.provide('attachments', { imageHostPath: (image: { attachmentId: string }) => `/host/${image.attachmentId}.png` } as never) + ctx.provide('fs', { processPathFromHostPath: (path: string) => `/program${path}` } as never) + const shown = ref('a') + const removed = ref('b') + ctx.tools.register(defineTool({ + name: 'screenshot', + description: 'Return text, one shown image, and one image a policy removed.', + parameters: {}, + output: { + schema: { type: 'json' }, + render: () => [{ type: 'text', text: 'Window state' }, { type: 'image', attachment: shown }], + }, + execute: () => Promise.resolve({ content: [ + { type: 'text', text: 'Window state' }, + { type: 'image', data: 'AQ==', attachment: shown }, + { type: 'image', data: 'Ag==', attachment: removed }, + ] }), + })) + let value: unknown + runtime.behavior = async (request) => { + value = await request.bindings[0]!.functions.screenshot!({}) + return printed('done') + } + + const result = await runCode(ctx, 'program') + + expect(result.isError).toBe(false) + expect(result.additionalContexts).toBeUndefined() + const content = (value as { content: unknown[] }).content + expect(content[0]).toEqual({ type: 'text', text: 'Window state' }) + expect(content[1]).toBeInstanceOf(PtcImage) + expect(content[1]).toMatchObject({ path: `/program/host/${shown.attachmentId}.png`, attachment: shown }) + expect(content[2]).toEqual({ type: 'image', data: 'Ag==', attachment: removed }) + }) + + it.each(['missing', 'throwing', 'deep'] as const)('delivers referenced result images as deferred context with %s substitution input', async (storage) => { + const { ctx, runtime } = await setup({ mode: 'ptc' }) + onTestFinished(() => ctx.fiber.dispose()) + if (storage !== 'missing') { + ctx.provide('attachments', { imageHostPath: () => { + if (storage === 'throwing') throw new Error('invalid reference') + return '/host/image.png' + } } as never) + ctx.provide('fs', { processPathFromHostPath: (path: string) => path } as never) + } + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + const shown = { attachmentId: brandString(`sha256:${'a'.repeat(64)}`), mediaType: 'image/png' as const, bytes: 1, width: 1, height: 1 } + let deep: JsonValue = [] + for (let depth = 0; depth < (storage === 'deep' ? 5_000 : 0); depth++) deep = [deep] + const raw = { content: [{ type: 'image', data: 'AQ==', attachment: shown }], deep } + ctx.tools.register(defineTool({ + name: 'screenshot', description: 'Return an image without a program path.', parameters: {}, + output: { schema: { type: 'json' }, render: () => [{ type: 'image', attachment: shown }] }, + execute: () => Promise.resolve(raw), + })) + let value: unknown + runtime.behavior = async (request) => { + value = await request.bindings[0]!.functions.screenshot!({}) + return printed('done') + } + + const result = await runCode(ctx, 'program') + + // Recursive equality would exceed the stack on the deep fixture; the deep member is checked by depth. + expect((value as typeof raw).content).toEqual(raw.content) + let depth = 0 + for (let level: JsonValue = (value as typeof raw).deep; Array.isArray(level) && level.length > 0; level = level[0]!) depth++ + expect(depth).toBe(storage === 'deep' ? 5_000 : 0) + expect(result.additionalContexts).toMatchObject([{ source: { kind: 'ptc-mode' }, content: [{ type: 'image', attachment: shown }] }]) + expect(warn).toHaveBeenCalledTimes(storage === 'missing' ? 0 : 1) }) it.each([ @@ -1715,7 +1860,13 @@ describe('the run_code dispatch bridge', () => { name: 'cua', description: 'Return a text observation.', parameters: {}, execute: () => Promise.resolve([{ type: 'text', text: 'Window selected' }]), })) - runtime.behavior = async request => printed(await request.bindings[0]!.functions.cua!({})) + runtime.behavior = async (request) => { + const result = await request.bindings[0]!.functions.cua!({}) + expect(result).toBeInstanceOf(PtcInspectableValue) + if (!(result instanceof PtcInspectableValue)) throw new Error('Expected rendered binding value') + expect(result.text).toBe('Window selected') + return printed(result.value) + } const result = await runCode(ctx, 'program') expect(result.isError).toBe(false) diff --git a/packages/core/tools/tests/gen-tool-catalog.spec.ts b/packages/core/tools/tests/gen-tool-catalog.spec.ts index b9fe22584c..9ba715bf16 100644 --- a/packages/core/tools/tests/gen-tool-catalog.spec.ts +++ b/packages/core/tools/tests/gen-tool-catalog.spec.ts @@ -27,8 +27,7 @@ describe('gen-tool-catalog collectToolCatalog', () => { const catalog = await collectToolCatalog() const names = catalog.flatMap(entry => entry.schemas.map(s => s.name)).sort() expect(names).toEqual([ - 'apply_patch', 'ask_user_question', 'bash', 'bash', 'cordis_inspect_list', - 'cordis_inspect_query', + 'apply_patch', 'ask_user_question', 'bash', 'bash', 'cordis_inspect', 'create_goal', 'create_worktree', 'edit', 'exit_plan_mode', 'get_goal', 'glob', 'grep', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_mcp_resource_templates', 'list_mcp_resources', diff --git a/packages/document/tool-office/tests/activation.spec.ts b/packages/document/tool-office/tests/activation.spec.ts index fdbf5a7bd8..b2f2f0703c 100644 --- a/packages/document/tool-office/tests/activation.spec.ts +++ b/packages/document/tool-office/tests/activation.spec.ts @@ -9,7 +9,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' import { brandString } from '@deepseek-ai/dsh-brand' import { createUserMessage, LlmAdapter, type ToolCallId, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm' -import { PtcRuntime, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' +import { PtcInspectableValue, PtcRuntime, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime' import { type SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' import * as JsonlPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' import SkillRegistry from '@deepseek-ai/dsh-skill' @@ -56,7 +56,8 @@ class SkillRuntime extends PtcRuntime { return { ...request, cwd: request.cwd ?? process.cwd(), timeoutMs: request.timeoutMs ?? 120_000 } } async run(request: PtcRunRequest): Promise { - return { output: [], value: await request.bindings[0]!.functions.skill!({ name: this.skill }) } + const resolved = await request.bindings[0]!.functions.skill!({ name: this.skill }) + return { output: [], value: resolved instanceof PtcInspectableValue ? resolved.value : resolved } } } diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index dd8533387d..7ca24482b3 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 240a0267069304b5 - zh: 1e28533a1706a37d + en: 007a499b05d4b48a + zh: d32f1dad71099177 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 8a32164b43695f96 - zh: c5659ca104118d3b + en: 6dd304b2ee1d1771 + zh: 9749536a0672dc8f /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b @@ -30,8 +30,8 @@ en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 4cc0215ddd1aa565 - zh: 5a39cbdafc70fce9 + en: fbbb6498637ec87d + zh: e1616f743fa30869 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index d0f8fddb70..30d7651ee9 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -38,9 +38,9 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color, with its head branch end filled in the color of running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll. - **Tab** — the first row names the checked-out branch, or the abbreviated commit on a detached HEAD, after a folder glyph for the project directory or a branch glyph for a worktree, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip adds the path with the Host home shortened to `~`, its button copies the full path, and for a removed worktree it offers Restore. Below it, each change request card shows a glyph for its state, its title, which opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the header button's red dot does. The card's header also offers Open in browser, Copy change request link, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended. An expanded card shows the head and base branches, then one row per fact, each a glyph and its value. For an open change request, the rows are the checks, whose menu groups the failed, running, and cancelled checks with their durations and links, lists the passed and skipped ones on request, and offers Rerun failed when the user may rerun checks and a failed check names a rerun none of whose checks is still running; the review decision with the first three reviewers' avatars and how many more, whose menu lists each reviewer with their kind and latest outcome, notes an outcome given before the latest commit, and, when the user may request reviews, re-requests a review from a reviewer or requests one from someone else through a search that lists the host's suggestions first; the merge state, which names a head behind its base and, when the user may update it, offers Update branch, whose menu chooses merge or rebase, pins the displayed head when opened, and disables Confirm update once a poll names another head; the changed lines, formatted in the selected UI language, with the unresolved threads, whose count ends in `+` when the provider counted only some threads, in a row that opens the changes view; and the linked issues the host closes when the change request merges, each linking to its page. A merged or closed one shows when it ended and the changed lines. Rerun failed, a review request, Update branch, Ready for review, and Merge report their outcome in a toast, which asks to check the change request in the browser when the host did not confirm the outcome, and new commits since the displayed head stop a rerun or an update. An open draft also offers Ready for review; a change request the host would merge now offers Merge, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When exactly one bound change request is open, its card starts expanded. Refresh inspects the checkout, checks sign-in, and polls every change request again; its icon turns until the inspection and the sign-in check end. When sign-in is missing, a banner shows the sign-in command the provider names, such as `gh auth login --hostname github.com`, with a button that copies it. - **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, which is always the default base below, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent. -- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. The toolbar and the header each keep one line: as the toolbar narrows, the line totals, expanding all files, two columns, and wrapping move into a More menu first, then the test file switch, with the viewed progress label shortened to a bare count beside its ring, and then refresh, while header buttons keep their labels on one line and the menus and title shorten. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. Expanded unchanged lines and pending file reads survive a refresh of review marks for the same commit range, head, and patches. +- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. The toolbar and the header each keep one line: as the toolbar narrows, the line totals, expanding all files, two columns, and wrapping move into a More menu first, then the test file switch, with the viewed progress label shortened to a bare count beside its ring, and then refresh, while header buttons keep their labels on one line and the menus and title shorten. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A row of at most 20 lines expands with one click. A longer row expands 20 lines at a time, down from the hunk above it or up from the hunk below it, the row before the first hunk only up and the row after the last hunk only down, and shows how many lines it still hides; the first click on the unknown lines after the last hunk reads the file and shows their first 20. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. Expanded unchanged lines and pending file reads survive a refresh of review marks for the same commit range, head, and patches. -- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, as a ring filled to the viewed share and a label such as 2 / 3 viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. A change of the file mode alone, such as `chmod +x`, also counts as a new change. A change request's view of all its commits uses the viewed marks its provider keeps on the code host, as the GitHub provider does: the view reads them with the diff, shows a mark at once, and saves it at the displayed head, keeping that file's checkbox disabled until the host answers; a file GitHub reports as changed since it was viewed shows Changed since viewed. A mark the host refuses, or one that new commits made stale, returns to its previous state, and a toast says why; a mark the host may have saved without confirming it stays, and a toast says to refresh to see where it stands. When the marks cannot be read, a notice says so and offers Retry, and no file can be marked. Hovering a checkbox tells where its mark is kept. Other marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. +- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; when the counts do not fit the tree's width, it shows the layer names alone and each count in the hover text of its layer. Where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, as a ring filled to the viewed share and a label such as 2 / 3 viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. The file tree draws a viewed file subdued, and a directory once every file in it is viewed, so the files left to review stand out; a file changed since it was viewed draws as unviewed, and assistive technology reads the state as each row's description. A change of the file mode alone, such as `chmod +x`, also counts as a new change. A change request's view of all its commits uses the viewed marks its provider keeps on the code host, as the GitHub provider does: the view reads them with the diff, shows a mark at once, and saves it at the displayed head, keeping that file's checkbox disabled until the host answers; a file GitHub reports as changed since it was viewed shows Changed since viewed. A mark the host refuses, or one that new commits made stale, returns to its previous state, and a toast says why; a mark the host may have saved without confirming it stays, and a toast says to refresh to see where it stands. When the marks cannot be read, a notice says so and offers Retry, and no file can be marked. Hovering a checkbox tells where its mark is kept. Other marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. - **Review threads** — A change request view overlays the review threads its code host read at the shown head. A thread on lines follows the row of its last line, on the side it was written on, or the collapsed unchanged lines that hold it; it shows the place it was written, each comment's avatar, author, time, and Markdown with raw HTML left out, and tags for the change request's author, bots, and comments still pending in the signed-in user's review. A resolved thread folds into one row that unfolds on request. Threads on a whole file open the file, and threads later commits made outdated gather after its lines in a section that shows the end of the hunk they were written on and offers View file at that commit, which reads the file at the commit they were written on with their lines marked. Chosen commits show only new-side threads whose lines number the last chosen commit. The file tree and each file header count unresolved threads. Each click on the count in a header goes to the file's next unresolved thread in the order the file shows them, threads the chosen commits do not hold last, and from the last back to the first; the Threads toolbar button opens the thread list, which groups the threads by file in file tree order and orders each file's threads the same way, shows the Unresolved, Resolved, or All threads, Unresolved first, and opens each thread at its place, choosing all commits for one the chosen commits do not hold. The list docks beside the files in a view at least 1,040px wide, floats over them in a narrower one and closes before it opens a thread there, and takes their whole width below 480px. The list names a truncated read. A thread offers Add to input, which quotes the whole thread, View on GitHub, and the writes the signed-in user may make. Without a pending review, its reply field replies at once, and its menu starts a pending review with the reply; with one, the field adds the reply to it, as GitHub adds every reply of the user to the pending review. Resolve thread and Unresolve thread change its state, and the menu of the user's own comment edits or deletes it after asking, saying when deleting the only comment deletes the thread. A resolved thread stays open while the user writes a reply or an edit in it. A write the code host refuses keeps the text and says why; a write whose outcome is unknown reads the threads again and asks the user to check them before trying again. Every write reads the threads again, since resolving a thread does not change a GitHub pull request's update time. Threads are read again at each status while the view shows, and from the code host after Refresh even while the panel keeps an earlier read; a failed read keeps the last threads and offers Retry, and a provider that does not read reviews shows none. - **Extension API** — Other plugins extend the changes view through the [extension API](../../../docs/subsystems/forge.md#extension-api). A Host plugin registers a filter lens with `ctx.forgePanel.registerLens`, and a Client plugin names it with `ctx.forgeChanges.describeLens`; the toolbar then offers a Lens menu after Hide test files, which keeps the files of the chosen layer that the chosen lens keeps, counts each lens's files once it ran, and folds the hunks a kept file's lens is not about into a row that shows them. A running lens shows its progress on the menu button; a failed, refused, or interrupted run says why and offers Retry and Clear lens, and a lens whose plugin unloads stops filtering with a toast. While no lens is chosen, the menu folds into the More menu with the test switch. `ctx.forgeChanges` also opens a view with a file and a lens chosen and registers line annotation sources, whose notes stack after the comments and threads of their last line, in the column of their side, whole-file notes first and notes on an earlier change last, at most `maxAnnotationsPerFile` in a file. Plugins add toolbar tools, which fold into the More menu first, file menu rows, comment form buttons after Add to input, and card head buttons through the `forge.changes.toolbar`, `forge.changes.file.menu`, `forge.diff.comment.actions`, and `forge.change-request.card.actions` slots. @@ -50,7 +50,7 @@ The diff follows the file tree’s depth-first order: directories before files, `gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCachedReviewBytes`, `reviewRefreshMs`, `maxCommits`, `testPaths`, `interfacePaths`, `lensTimeoutMs`, `maxLensReadBytes`, `maxCachedLensBytes`, and `maxAnnotationsPerFile` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). -All files opens a searchable directory tree with the selected file scrolled to its middle. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree. Files and folders reserve the same disclosure column so each child is indented from its parent. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. Several editors can stay open at once, and choosing the range of an open one focuses it again. In two columns, each comment sits under its own side of the row, so a left and a right comment share that row side by side, each continuing its line’s background. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer that shows the file name, side and lines, and comment, and on hover the file path; multiple quotes are sent together only when the user sends that composer. Once the review threads are read and the user may review, the split button adds the comment to the user's pending review on the code host, starting one when there is none; the comment then shows as a thread tagged Pending, which only the user sees until the review is submitted. Its menu publishes a single comment immediately and is absent while the user has a pending review. Agent references and published comments remain beside their code. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. With a pending review, it submits that review, keeping a submission whose outcome is unknown blocked until the user checks GitHub, as a direct submission is, and Discard review deletes the review and its comments after a confirmation; without one, it publishes the summary as one review. Decisions the code host does not let the user record are unavailable, such as Approve and Request changes on the user's own pull request on GitHub; when only Comment remains, the dialog says so. The view's copy names the code host and its word for a change request, such as GitHub and PR, after the change request's provider. Added and deleted files show only their populated line-number column. The summary, decision, and records of Agent references and published comments are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears them, and reopening starts an empty summary. The pending review, published GitHub comments, and references already added to the main composer are unaffected. Comment drafts an earlier version kept in this browser stay beside their code tagged Browser draft and can be edited, deleted, or added to the pending review; they keep Submit review disabled while a pending review exists, and without one Submit review publishes them with the summary. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission. +All files opens a searchable directory tree with the selected file scrolled to its middle. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree, which stays at least as wide as the lens above it needs to show the layer names whole. Files and folders reserve the same disclosure column so each child is indented from its parent. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. Several editors can stay open at once, and choosing the range of an open one focuses it again. In two columns, each comment sits under its own side of the row, so a left and a right comment share that row side by side, each continuing its line’s background. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer that shows the file name, side and lines, and comment, and on hover the file path; multiple quotes are sent together only when the user sends that composer. Once the review threads are read and the user may review, the split button adds the comment to the user's pending review on the code host, starting one when there is none; the comment then shows as a thread tagged Pending, which only the user sees until the review is submitted. Its menu publishes a single comment immediately and is absent while the user has a pending review. Agent references and published comments remain beside their code. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. With a pending review, it submits that review, keeping a submission whose outcome is unknown blocked until the user checks GitHub, as a direct submission is, and Discard review deletes the review and its comments after a confirmation; without one, it publishes the summary as one review. Decisions the code host does not let the user record are unavailable, such as Approve and Request changes on the user's own pull request on GitHub; when only Comment remains, the dialog says so. The view's copy names the code host and its word for a change request, such as GitHub and PR, after the change request's provider. Added and deleted files show only their populated line-number column. The summary, decision, and records of Agent references and published comments are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears them, and reopening starts an empty summary. The pending review, published GitHub comments, and references already added to the main composer are unaffected. Comment drafts an earlier version kept in this browser stay beside their code tagged Browser draft and can be edited, deleted, or added to the pending review; they keep Submit review disabled while a pending review exists, and without one Submit review publishes them with the summary. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission. ----- @@ -77,7 +77,7 @@ Each inspection also decides whether the worktree is missing: the Session's dire `changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service. -The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and passes each file section values that keep their identity across its renders, including the tab's visibility, so a render redraws only the sections whose values changed and a visibility change redraws every section. An expanded file draws its lines, highlighted with the shared code highlighter in the same render, once its section first comes within 1200px of the scrollport or a jump to one of its review threads targets it, keeps them drawn after that, and until then holds a 22px row per drawn line; a chip title shows its name with the changes icon. +The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and passes each file section values that keep their identity across its renders, including the tab's visibility, so a render redraws only the sections whose values changed and a visibility change redraws every section. An expanded file draws its lines, highlighted with the shared code highlighter in the same render, once its section first comes within 1200px of the scrollport or a jump to one of its review threads targets it, keeps them drawn after that, and until then holds a 22px row per drawn line; a chip title shows its name with the changes icon. Once a file's whole new side is known, read for an expansion or, for local changes, read once per comparison when the file draws, each side of each run of drawn rows is highlighted again in idle time after up to 120 lines of the file before it, the old side rebuilt from the new side and the hunks; the new colors apply in one update after every run is done, and wait while the reader drags or holds a text selection in the file. A change request's files are not read for this, since each read is a request to the code host. | Source | Responsibility | |---|---| @@ -152,6 +152,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Changes scopes** — deferred: a scope for the last turn. The Branch scope's Default needs a remote whose default branch HEAD shares history with, or a worktree the Session created; otherwise a base branch must be chosen. - **Very many branches** — the base branch menu reads every ref before it filters, so a search can reach any branch. Refs over `maxDiffBytes`, about 165,000 at the default, or a listing over `gitTimeoutMs`, leave the menu saying that branches could not be read; Default keeps working. - **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View in browser. Without wrapping, the side-by-side view cuts long lines at the column edge. +- **Highlighting across collapsed lines** — rows after collapsed unchanged lines take the colors of the lines before them only once the file is read: local files when they draw, change request files after one of their gaps expands. A code block, comment, or string that opens more than 120 lines before a run still leaves the run colored as if it started there. - **Undrawn files** — until the reader scrolls near an expanded file, it holds 22 px per drawn line, which leaves out side-by-side pairing, wrapped lines, unchanged-line rows, and review cards, so the scroll range shifts a little as files draw; its saved review comments also appear only once it draws. - **Find in page over long diffs** — an expanded file draws its lines only once the reader scrolls near it, so the browser's find in page does not match lines of files further down until they are drawn; a page-wide search of the diff needs a find control of the view's own. - **Viewed files on the code host** — GitHub keeps one viewed mark per file and user, not one per commit, so marks in a view of chosen commits stay in this browser, and another browser or device starts without them. A file beyond the provider's `maxViewedFiles` shows no mark from GitHub until it is marked in this view. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index d7d03f88bd..73f35b515c 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -38,9 +38,9 @@ kind: "package-reference" - **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。 - **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行,由图标与取值组成。打开的变更请求依次是:检查,其菜单按失败、运行中、已取消分组列出检查及其耗时与链接,按需列出通过与跳过的检查,用户可以重跑检查、且有失败检查指向一个其中没有检查仍在进行的重跑时提供“重跑失败项”;评审结论,带前三位评审者的头像与其余人数,其菜单列出每位评审者的类型与最近结论,注明早于最新提交的结论,用户可以请求评审时还能重新请求某位评审者,或通过先列出托管平台建议的搜索向其他人请求评审;合并状态,会注明 head 落后于基线,用户可以更新时提供“更新分支”,其菜单在 merge 与 rebase 之间选择,打开时固定卡片显示的 head,轮询发现 head 变化后禁用“确认更新”;按所选界面语言格式化的变更行数与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`),点击该行打开变更视图;以及合并时托管平台会关闭的关联 issue,各自链接到其页面。已合并或已关闭的显示结束时间与变更行数。“重跑失败项”、评审请求、“更新分支”、“标记为可评审”与“合并”的结果都以 toast 报告,托管平台未确认结果时提示到浏览器中查看变更请求;显示的 head 之后有新提交时不会重跑或更新。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示提供方给出的登录命令(例如 `gh auth login --hostname github.com`),并提供复制按钮。 - **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`,始终是下文的默认基准)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 -- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。刷新评审标记时,如果比较的提交范围、末端提交和补丁都相同,已经展开的未变更行和正在读取的文件内容会保留。 +- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。工具栏和标题栏各自保持一行:工具栏变窄时,先把变更行数、全部展开、左右对比与自动换行收进“更多视图选项”菜单,再收起“隐藏测试文件”开关,已审阅进度的文字缩短为圆环旁的计数,最后收起刷新;标题栏的按钮文字不换行,菜单和标题先缩短。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。不超过 20 行的折叠行点一次全部展开。更长的折叠行每次展开 20 行,可以从上方 hunk 向下展开,也可以从下方 hunk 向上展开;第一个 hunk 之前的折叠行只能向上展开,最后一个 hunk 之后的只能向下展开;折叠行上显示还隐藏的行数。最后一个 hunk 之后行数未知的折叠行,第一次点击时读取文件并显示前 20 行。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。刷新评审标记时,如果比较的提交范围、末端提交和补丁都相同,已经展开的未变更行和正在读取的文件内容会保留。 -- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏以按已审阅比例填充的圆环和“已审阅 2 / 3”这样的文字显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。只改文件模式(例如 `chmod +x`)也算新改动。变更请求的全部提交视图使用提供方保存在代码托管平台上的已审阅标记(GitHub 提供方即如此):视图随 diff 一起读取这些标记,勾选后立即显示,并在显示的 head 上保存,平台答复前该文件的复选框保持禁用;GitHub 报告为标记后又有改动的文件显示“有新改动”。平台拒绝或因新提交而过期的标记恢复原状,并以 toast 说明原因;平台可能已保存但未确认的标记保持不变,toast 提示刷新查看实际状态。无法读取标记时,提示条说明原因并提供“重试”,此时不能标记任何文件。悬停复选框会说明标记保存在哪里。其他标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 +- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;文件树宽度放不下数量时,只显示各层名称,数量在悬停提示里。不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏以按已审阅比例填充的圆环和“已审阅 2 / 3”这样的文字显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。文件树把已审阅的文件置灰,目录下的文件全部已审阅时目录也置灰,以便看出还没审阅的文件;有新改动的文件按未审阅显示,辅助技术把这一状态读作每行的描述。只改文件模式(例如 `chmod +x`)也算新改动。变更请求的全部提交视图使用提供方保存在代码托管平台上的已审阅标记(GitHub 提供方即如此):视图随 diff 一起读取这些标记,勾选后立即显示,并在显示的 head 上保存,平台答复前该文件的复选框保持禁用;GitHub 报告为标记后又有改动的文件显示“有新改动”。平台拒绝或因新提交而过期的标记恢复原状,并以 toast 说明原因;平台可能已保存但未确认的标记保持不变,toast 提示刷新查看实际状态。无法读取标记时,提示条说明原因并提供“重试”,此时不能标记任何文件。悬停复选框会说明标记保存在哪里。其他标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 - **评审讨论**——变更请求视图会叠加代码托管平台在所显示 head 处读到的评审讨论。行级讨论显示在它最后一行所在的行之后,位于写下时所在的那一侧;若该行折叠在未变更的行中,则显示在折叠行之后。讨论标明写下时的位置,每条评论显示头像、作者、时间和 Markdown 正文(不显示原始 HTML),并用标签标出变更请求作者、机器人账号,以及当前登录用户尚未提交的评审中的评论。已解决的讨论折叠成一行,可以展开。针对整个文件的讨论显示在文件开头;被后续提交改到而过期的讨论集中在文件的行之后,显示写下时那段 hunk 的末尾,并提供“查看当时的文件”,读取写下讨论时那个提交上的文件并标出相应的行。选择了部分提交时,只显示行号对应最后一个所选提交的新版本侧讨论。文件树和每个文件标题都显示未解决讨论数。每点击一次文件标题上的计数,就按文件中的显示顺序跳到该文件的下一条未解决讨论(所选提交中没有的讨论排在最后),到最后一条后回到第一条;工具栏的“讨论”按钮打开讨论列表。列表按文件树顺序分组,组内讨论的顺序与文件中相同,可显示未解决、已解决或全部讨论,默认显示未解决的讨论;点击讨论会跳到它的位置,若所选提交中没有该讨论,会先切换到全部提交。视图宽度不小于 1,040px 时列表停靠在文件旁;更窄时浮在文件之上,并在跳到讨论前先关闭;窄于 480px 时占满文件区的宽度。读取被截断时,列表会注明。讨论上提供“添加到输入框”(把整个讨论作为引用插入)、“在 GitHub 中查看”,以及当前登录用户可以执行的写操作。没有待提交评审时,回复框立即回复,其下拉菜单可以带着这条回复开始待提交评审;有待提交评审时,回复框把回复加入其中,因为 GitHub 会把用户的每条回复都加入待提交评审。“解决讨论”和“取消解决”切换讨论状态;用户自己评论的菜单可以编辑或删除该评论,删除前会先确认,删除讨论中唯一的评论会一并删除讨论,确认时会说明这一点。用户正在讨论中写回复或编辑评论时,即使讨论已被解决,也保持展开。代码托管平台拒绝写操作时保留输入的文字并说明原因;结果不明时会重新读取讨论,并请用户核对后再重试。每次写操作后都会重新读取讨论,因为解决讨论不会改变 GitHub pull request 的更新时间。视图显示期间,每收到一次状态就重新读取讨论;点击刷新后,即使面板还保留着之前的读取结果,也会从代码托管平台重新读取;读取失败时保留上次的讨论并提供重试,提供方不支持读取讨论时不显示讨论。 - **扩展 API**——其他插件通过[扩展 API](../../../docs/subsystems/forge.zh.md#extension-api)扩展变更视图。Host 插件用 `ctx.forgePanel.registerLens` 注册筛选透镜,Client 插件用 `ctx.forgeChanges.describeLens` 给它起名;工具栏随后在“隐藏测试文件”之后提供“透镜”菜单:只保留所选分层中被所选透镜保留的文件,透镜运行过之后显示它保留的文件数,并把被保留文件中透镜不关心的 hunk 折叠成一行,点开即显示。透镜运行时,菜单按钮显示进度;运行失败、被拒绝或中断时说明原因,并提供“重试”和“清除透镜”;透镜所在的插件卸载后停止筛选,并弹出提示。没有选透镜时,菜单与测试文件开关一起收进“更多”菜单。`ctx.forgeChanges` 还可以打开选定了文件和透镜的视图,并注册行注解数据源:注解放在其最后一行的评论和讨论之后、所在一侧的那一栏,整个文件的注解排在最前,写在较早改动上的注解排在最后,每个文件最多显示 `maxAnnotationsPerFile` 条。插件可以通过 `forge.changes.toolbar`、`forge.changes.file.menu`、`forge.diff.comment.actions` 与 `forge.change-request.card.actions` 这些 slot 添加工具栏工具(最先收进“更多”菜单)、文件菜单项、放在“添加到输入框”之后的评论框按钮,以及卡片头部按钮。 @@ -50,7 +50,7 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后 `gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCachedReviewBytes`、`reviewRefreshMs`、`maxCommits`、`testPaths`、`interfacePaths`、`lensTimeoutMs`、`maxLensReadBytes`、`maxCachedLensBytes` 与 `maxAnnotationsPerFile` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 -“全部文件”打开可搜索的目录树,并把选中文件滚动到中间;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。可以同时打开多个评论框,再次选中已打开评论框的范围会回到该评论框。两栏时每条评论位于该行自己一侧的下方,左右两侧的评论并排处在同一行,各自延续所在行的底色。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,引用显示文件名、侧与行号以及评论,悬停时显示文件路径;多条引用只会在用户发送主输入框时一起发送。读到评审讨论且用户可以评审时,分段按钮会把这条评论加入用户在代码托管平台上的待提交评审,没有时先开始一个;评论随后显示为带“待提交”标签的讨论,提交评审之前只有用户自己能看到。下拉菜单可以立即发布单条评论;用户有待提交评审时没有该菜单。Agent 引用和已发布的评论保留在对应代码旁。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。有待提交评审时提交该评审,结果不明的提交与直接提交一样,在用户到 GitHub 核对之前阻止再次提交;“丢弃评审”在确认后删除该评审及其中的评论;没有待提交评审时,把总结作为一次评审发布。代码托管平台不允许用户记录的结论不可用,例如在 GitHub 上用户自己的 PR 里,“批准”和“请求更改”不可用;只剩“评论”时,对话框会说明。视图中的文案按变更请求的提供方称呼代码托管平台及其对变更请求的叫法,例如 GitHub 和 PR。新建和删除文件只显示有内容的一侧行号。总结、评审决定,以及 Agent 引用与已发布评论的记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空它们,重新打开从空总结开始。待提交评审、已发布到 GitHub 的评论与已加入主输入框的引用不受影响。早期版本保存在此浏览器中的评论草稿保留在对应代码旁,带“浏览器草稿”标签,可以编辑、删除或加入待提交评审;存在待提交评审时,它们会让“提交评审”保持不可用;没有待提交评审时,“提交评审”把它们连同总结一起发布。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。 +“全部文件”打开可搜索的目录树,并把选中文件滚动到中间;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度;文件树至少保持上方透镜完整显示各层名称所需的宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。可以同时打开多个评论框,再次选中已打开评论框的范围会回到该评论框。两栏时每条评论位于该行自己一侧的下方,左右两侧的评论并排处在同一行,各自延续所在行的底色。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,引用显示文件名、侧与行号以及评论,悬停时显示文件路径;多条引用只会在用户发送主输入框时一起发送。读到评审讨论且用户可以评审时,分段按钮会把这条评论加入用户在代码托管平台上的待提交评审,没有时先开始一个;评论随后显示为带“待提交”标签的讨论,提交评审之前只有用户自己能看到。下拉菜单可以立即发布单条评论;用户有待提交评审时没有该菜单。Agent 引用和已发布的评论保留在对应代码旁。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。有待提交评审时提交该评审,结果不明的提交与直接提交一样,在用户到 GitHub 核对之前阻止再次提交;“丢弃评审”在确认后删除该评审及其中的评论;没有待提交评审时,把总结作为一次评审发布。代码托管平台不允许用户记录的结论不可用,例如在 GitHub 上用户自己的 PR 里,“批准”和“请求更改”不可用;只剩“评论”时,对话框会说明。视图中的文案按变更请求的提供方称呼代码托管平台及其对变更请求的叫法,例如 GitHub 和 PR。新建和删除文件只显示有内容的一侧行号。总结、评审决定,以及 Agent 引用与已发布评论的记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空它们,重新打开从空总结开始。待提交评审、已发布到 GitHub 的评论与已加入主输入框的引用不受影响。早期版本保存在此浏览器中的评论草稿保留在对应代码旁,带“浏览器草稿”标签,可以编辑、删除或加入待提交评审;存在待提交评审时,它们会让“提交评审”保持不可用;没有待提交评审时,“提交评审”把它们连同总结一起发布。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。 ----- @@ -77,7 +77,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi `changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。 -浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内,或跳转到它的某个评审讨论时,才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。 +浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内,或跳转到它的某个评审讨论时,才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。文件的整个新版本已知时(为展开而读取,或本地变更在文件绘制时按每次比较读取一次),每段绘制行的每一侧会在空闲时带上文件中它之前最多 120 行重新高亮,旧版本由新版本与 hunk 还原;所有段都算完后新颜色在一次更新中生效,读者正在拖选或文件内有文本选区时等它结束。变更请求的文件不为此读取,因为每次读取都是一次对代码托管平台的请求。 | 源码 | 职责 | |---|---| @@ -152,6 +152,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **变更范围**——待办:上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。 - **分支极多**——基准分支菜单在筛选前读取全部引用,这样搜索才能找到任意分支。引用超过 `maxDiffBytes`(默认约 165,000 个)或列出时间超过 `gitTimeoutMs` 时,菜单提示无法读取分支;“默认”仍可使用。 - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 +- **跨折叠行的高亮**——折叠的未变更行之后的行,要等文件被读取后才按它之前的内容着色:本地文件在绘制时读取,变更请求的文件要等它的某处折叠行展开后。在一段行之前超过 120 行处开始的代码块、注释或字符串,这段行仍按从段首开始着色。 - **尚未绘制的文件**——读者滚动到展开的文件附近之前,它按每个绘制行 22 px 占位,没有计入左右对比的配对、自动换行、未变更行按钮和评审卡片,所以文件绘制时滚动范围会略有变化;它已保存的评审评论也要等它绘制后才显示。 - **长 diff 中的页内查找**——展开的文件要等读者滚动到附近才绘制各行,所以浏览器的页内查找在更靠后的文件绘制之前匹配不到它们的行;要在整个 diff 中查找,需要视图自己的查找控件。 - **代码托管平台上的已审阅状态**——GitHub 对每个文件和用户只保存一个已审阅标记,不按提交区分,因此所选提交视图中的标记只保存在本浏览器中,换浏览器或设备后没有这些标记。超出提供方 `maxViewedFiles` 的文件在本视图中标记之前不显示 GitHub 上的标记。 diff --git a/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css b/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css index db93e6decd..9580a61457 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css @@ -8,6 +8,10 @@ /* Unresolved host review threads of a file, in the thread count chip treatment of the file header. */ .threads { flex: none; min-width: 16px; padding: 0 5px; box-sizing: border-box; border-radius: var(--dsw-radius-xs); background: color-mix(in srgb, var(--dsw-alias-state-business-primary) 12%, transparent); color: var(--dsw-alias-state-business-primary); font-size: 11px; line-height: 16px; text-align: center; } .selected { background: var(--dsw-alias-interactive-bg-hover); } +/* A viewed file, or a directory whose files are all viewed, recedes so the files left to review stand out; the + disclosure chevron and the unresolved thread count keep their weight. */ +.viewed .name { color: var(--dsw-alias-label-tertiary); } +.viewed > :not(.chevron):not(.name):not(.threads) { opacity: 0.5; } .chevron { display: inline-flex; flex: 0 0 12px; } .collapsed { transform: rotate(-90deg); } .empty { padding: 12px 8px; color: var(--dsw-alias-label-secondary); } diff --git a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx index 73edf2f7aa..17e6301686 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx @@ -5,7 +5,7 @@ import { FileTypeIcon, IconChevronDownOutlineRegular, IconFolderCloseRegular, In import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ForgeDiffFile } from '../types.ts' import { Counts } from './DiffFile.tsx' -import { changedFileTree, filesInTreeOrder, filterFileTree, type ChangedFileNode } from './file-tree.ts' +import { changedFileTree, filesInTreeOrder, filterFileTree, viewedNodes, type ChangedFileNode } from './file-tree.ts' import type { NS } from './locales.ts' import css from './ChangedFiles.module.css' @@ -27,11 +27,17 @@ export interface ChangedFilesProps extends PropsLocale { readonly menu?: boolean /** Unresolved host review threads by file path; files without any are absent. */ readonly threadCounts?: ReadonlyMap + /** Paths of the files marked viewed at their current change, which draw subdued with any directory they fill. */ + readonly viewed?: ReadonlySet } -function Rows({ nodes, depth, props }: { +const NONE_VIEWED: ReadonlySet = new Set() + +function Rows({ nodes, depth, done, props }: { readonly nodes: readonly ChangedFileNode[] readonly depth: number + /** Paths of the viewed files and of the directories whose files are all viewed. */ + readonly done: ReadonlySet readonly props: ChangedFilesProps }): ReactNode { const { state, toggle, jump, menu, threadCounts, t } = props @@ -41,10 +47,13 @@ function Rows({ nodes, depth, props }: { const threads = node.kind === 'file' ? threadCounts?.get(node.path) ?? 0 : 0 const label = node.kind === 'file' && node.file.previousPath !== null ? t('diff.renamedPath', { from: node.file.previousPath, path: node.path }) : node.path + const viewed = done.has(node.path) return
    - - {node.kind === 'directory' && expanded && } + {node.kind === 'directory' && expanded && }
    }) } @@ -92,6 +101,7 @@ export function ChangedFiles(props: ChangedFilesProps): ReactNode { const tree = useMemo(() => changedFileTree(props.files), [props.files]) const nodes = useMemo(() => filterFileTree(tree, props.state.query), [tree, props.state.query]) const order = useMemo(() => filesInTreeOrder(tree), [tree]) + const done = useMemo(() => viewedNodes(tree, props.viewed ?? NONE_VIEWED), [tree, props.viewed]) const selectedIndex = order.findIndex(file => file.path === props.state.selected) const rows = useRef(null) const query = useRef(props.state.query) @@ -121,7 +131,7 @@ export function ChangedFiles(props: ChangedFilesProps): ReactNode { value={props.state.query} onChange={(event) => { props.filter(event.target.value) }} onKeyDown={(event) => { if (['Home', 'End', 'ArrowLeft', 'ArrowRight'].includes(event.key)) event.stopPropagation() }} />
    - {nodes.length === 0 ?
    {props.t('diff.noMatchingFiles')}
    : } + {nodes.length === 0 ?
    {props.t('diff.noMatchingFiles')}
    : }
} diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css index 2fb235b36d..d953976af6 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -734,8 +734,9 @@ /* Collapsed unchanged lines; the row expands them. */ /* Collapsed unchanged lines, a collapsed large file, and a file whose lines cannot be drawn share one strip; - only the first two open on a click. */ + only the first two open on a click. Unchanged lines over one expansion step name their count beside step buttons. */ .gap, +.gapSteps, .fileNote { display: flex; align-items: center; @@ -769,6 +770,41 @@ cursor: progress; } +.gapSteps { + gap: 2px; + padding-inline-start: 7px; +} + +.gapSteps > span { + margin-inline-start: 4px; +} + +.gapStep { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 22px; + height: 20px; + padding: 0; + border: 0; + border-radius: var(--dsw-radius-sm); + background: transparent; + color: var(--dsw-alias-label-secondary); + cursor: pointer; +} + +@media (hover: hover) { + .gapStep:hover:not(:disabled) { + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-primary); + } +} + +.gapStep:disabled { + cursor: progress; +} + /* The local changes card of the panel: its toggle and refs, the view link and create action, then its files. */ .local { min-width: 0; @@ -902,7 +938,8 @@ .fileToggle:focus-visible, .localFile:focus-visible, .select:focus-visible, -.gap:focus-visible { +.gap:focus-visible, +.gapStep:focus-visible { outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); outline-offset: -2px; } diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 11f279afac..43dac9691f 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -53,7 +53,7 @@ import { SectionReach } from './section-reach.ts' import { FileTreePane, type FileTreePosition } from './FileTreePane.tsx' import { changedFileTree, filesInTreeOrder } from './file-tree.ts' import { ChangedFilesMenu, type ChangedFilesProps, type ChangedFilesState } from './ChangedFiles.tsx' -import { drawnLines, matchesHunks, textLines } from './diff-rows.ts' +import { drawnLines, matchesHunks, revealGap, textLines, type GapExpansion, type GapReveal } from './diff-rows.ts' import { ChangeRequestGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' import { useForgeCopy } from './forge-copy.ts' @@ -200,7 +200,7 @@ interface WriteRefusal { interface Expansion { readonly source: string | Extract | null readonly texts: Readonly> - readonly open: Readonly>> + readonly open: Readonly>> } /** Files whose hunks draw more lines show the large-file notice until revealed. */ @@ -209,7 +209,7 @@ const LARGE_FILE_LINES = 1000 /** Lines the files above may change before a file starts collapsed. */ const OPEN_LINES = 5000 -const NO_GAPS: ReadonlySet = new Set() +const NO_GAPS: ReadonlyMap = new Map() const NO_FOLDS: ReadonlyMap; readonly lens: string }> = new Map() @@ -619,6 +619,8 @@ export function ChangesTab({ const [treeState, setTreeState] = useState({ query: '', collapsed: {}, selected: null }) const [treePosition, setTreePosition] = useState('left') const [treeWidth, setTreeWidth] = useState(0) + // The lens's labels set the least width of the tree they sit above. + const [lensWidth, setLensWidth] = useState(0) const treeId = useId() const [chosen, setChosen] = useState>>({}) // Each navigation applies once; its file, if it names one, opens and scrolls into view. @@ -795,6 +797,9 @@ export function ChangesTab({ else report('viewed.syncFailed', { ...hostCopy, message: failure.message }) }) const marks = host?.marks ?? localMarks + // Files marked viewed at their current change, which the file tree draws subdued. + const viewedPaths = useMemo(() => new Set(files.filter(file => viewedStateOf(marks, file.path, file.digest) === 'viewed').map(file => file.path)), + [files, marks]) // The centered loader marks a first read; the toolbar's glyph turns only while shown changes are read again. const rereading = read !== null && finished !== read && data !== null const failed = failure !== null && failure.key === dataKey ? failure.code : null @@ -805,6 +810,8 @@ export function ChangesTab({ const [expansion, setExpansion] = useState({ source: null, texts: {}, open: {} }) const current = expansion.source === expansionSource ? expansion : { source: expansionSource, texts: {}, open: {} } const latest = useRef(expansionSource) + // Files whose new side was read ahead for highlighting in this comparison, each read at most once. + const contextReads = useRef<{ readonly source: typeof expansionSource; readonly paths: Set }>({ source: null, paths: new Set() }) useLayoutEffect(() => { latest.current = expansionSource }, [expansionSource]) const [revealed, setRevealed] = useState>(new Set()) // The line budget counts the files not marked viewed when the diff loads, so later marks leave it unchanged. A file stays @@ -876,9 +883,9 @@ export function ChangesTab({ return change(previous.source === expansionSource ? previous : { source: expansionSource, texts: {}, open: {} }) }) } - const expand = (owner: ChangesData, file: ForgeDiffFile, index: number): void => { + const expand = (owner: ChangesData, file: ForgeDiffFile, index: number, expansion: GapExpansion): void => { const path = file.path - update(value => ({ ...value, open: { ...value.open, [path]: new Set([...value.open[path] ?? [], index]) } })) + update(value => ({ ...value, open: { ...value.open, [path]: revealGap(value.open[path], index, expansion) } })) if (current.texts[path] !== undefined) return update(value => ({ ...value, texts: { ...value.texts, [path]: 'loading' } })) const reading = owner.kind === 'local' ? localText(owner.scope, path) : changeRequestText(owner.url, owner.headSha, path) @@ -897,6 +904,23 @@ export function ChangesTab({ }) }) } + /** + * Read a local file's new side ahead of any expansion, once per comparison, so its rows can be highlighted with the + * lines before them. A change request's files are not read for this, since each read costs a request to the code host. + */ + const readContext = (owner: ChangesData, file: ForgeDiffFile): void => { + const path = file.path + if (owner.kind !== 'local') return + if (contextReads.current.source !== expansionSource) contextReads.current = { source: expansionSource, paths: new Set() } + if (contextReads.current.paths.has(path)) return + contextReads.current.paths.add(path) + void localText(owner.scope, path).then((result) => { + const lines = result.ok ? textLines(result.value) : undefined + // A read that fails or no longer matches leaves the file as it is, and an expansion reads it again and says why. + if (lines === undefined || !matchesHunks(lines, file.hunks)) return + update(value => value.texts[path] !== undefined ? value : { ...value, texts: { ...value.texts, [path]: lines } }) + }) + } const fileActions = (owner: ChangesData, file: ForgeDiffFile): DiffFileAction[] => { const list: DiffFileAction[] = [{ label: 'diff.copyPath', run: () => { copyPath(file.path) } }] if (file.status === 'deleted') return list @@ -1112,8 +1136,8 @@ export function ChangesTab({ // an effect would hand them the previous diff's links. A render React discards leaves values derived from the same // props and state, which the retried render assigns again. const callbacks = { - data, expandedByDefault, expand, markViewed, fileActions, publishReview, writeReview, addPending, report, nextThread, lensTitle, - renderSlot, kept, t, + data, expandedByDefault, expand, readContext, markViewed, fileActions, publishReview, writeReview, addPending, report, nextThread, + lensTitle, renderSlot, kept, t, } const live = useRef(callbacks) live.current = callbacks @@ -1123,10 +1147,15 @@ export function ChangesTab({ setChosen(value => ({ ...value, [file.path]: !(value[file.path] ?? byDefault) })) }, reveal: (path) => { setRevealed(value => new Set([...value, path])) }, - expand: (file, index) => { + expand: (file, index, expansion) => { const { data: owner, expand: open } = live.current /* v8 ignore next -- sections render only while changes are loaded */ - if (owner !== null) open(owner, file, index) + if (owner !== null) open(owner, file, index, expansion) + }, + readContext: (file) => { + const { data: owner, readContext: read } = live.current + /* v8 ignore next -- sections render only while changes are loaded */ + if (owner !== null) read(owner, file) }, view: (file, viewed) => { const { data: owner, markViewed: mark } = live.current @@ -1250,7 +1279,7 @@ export function ChangesTab({ ) } const navigator: ChangedFilesProps = { - files, state: treeState, t, + files, state: treeState, t, viewed: viewedPaths, filter: (query) => { setTreeState(value => ({ ...value, query })) }, toggle: (path) => { setTreeState(value => ({ ...value, collapsed: { ...value.collapsed, [path]: value.collapsed[path] !== true } })) }, jump, @@ -1297,7 +1326,7 @@ export function ChangesTab({ {!reviewOpen && reviewError !== null && reviewState.uncertain === null && {reviewError}}
{/* Above the file tree, the lens spans the tree's width; elsewhere a menu in the toolbar takes its place. */} - {treeShown &&
} + {treeShown &&
}
{tab.visible && source.kind === 'local' && { actions.scoped(tab.id, next) }} t={t} />} {tab.visible && } @@ -1405,7 +1434,9 @@ export function ChangesTab({ {reviewForm}
{body} - {allFiles.length > 0 && } + {allFiles.length > 0 && ( + + )} {review !== null && data?.kind === 'change' && threadList.open && ( { setThreadList(value => ({ ...value, filter })) }} diff --git a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx index a46d46a4ef..e5b7cf760c 100644 --- a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx +++ b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx @@ -10,18 +10,21 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState, type CSSProper import clsx from 'clsx' import { flushSync } from 'react-dom' import { - FileTypeIcon, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconEllipsisOutlineRegular, IconPlusOutlineRegular, + FileTypeIcon, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconChevronUpOutlineRegular, IconEllipsisOutlineRegular, + IconPlusOutlineRegular, Tag, Tooltip, languageForPath, Menu, MenuItemButton, useCodeHighlighter, type CodeHighlighter, type HighlightSpan, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ForgeDiffFile } from '../types.ts' -import { drawnLines, segmentsOf, splitRows, type DiffRow, type SplitCell, type SplitRow } from './diff-rows.ts' +import { + drawnLines, EXPAND_STEP, hidesLine, segmentsOf, splitRows, + type DiffRow, type DiffSegment, type GapExpansion, type GapReveal, type SplitCell, type SplitRow, +} from './diff-rows.ts' import { codeSideAt, readCodeSelection } from './code-selection.ts' import { reviewMatches, selectReviewLines, type ReviewSelection } from './review.ts' import { ReviewThread, useFileReview } from './ReviewThread.tsx' import { OutdatedThreads, ThreadCard, type FileThreads, type LineThread, type ThreadActions } from './ReviewThreads.tsx' -import { gapOf } from './review-threads.ts' import type { FileReviewState } from './review-queue.ts' import { ReviewComposer, type ReviewActions } from './ReviewComposer.tsx' import reviewCss from './ReviewComposer.module.css' @@ -30,6 +33,7 @@ import type { ForgePanelKey, NS } from './locales.ts' import type { ViewedState } from './viewed-files.ts' import type { SectionReach } from './section-reach.ts' import type { SourcedAnnotation } from './annotations.ts' +import { oldSideLines, runKey, sideRun, useContextHighlight, type FileSides, type SideRun } from './highlight-context.ts' import css from './ChangesTab.module.css' type Translate = PropsLocale['t'] @@ -54,8 +58,10 @@ export interface DiffFileHandlers { readonly toggle: (file: ForgeDiffFile) => void /** Show a large file anyway. */ readonly reveal: (path: string) => void - /** Expand one gap of a file. */ - readonly expand: (file: ForgeDiffFile, index: number) => void + /** Show more of one gap of a file. */ + readonly expand: (file: ForgeDiffFile, index: number, expansion: GapExpansion) => void + /** Read a file's new side ahead of any expansion, for highlighting rows after its collapsed lines; a source may ignore it. */ + readonly readContext: (file: ForgeDiffFile) => void /** Mark a file viewed, which also collapses it, or clear the mark. */ readonly view: (file: ForgeDiffFile, viewed: boolean) => void /** Rows of a file's menu, read whenever the menu draws. */ @@ -90,8 +96,8 @@ export interface DiffFileProps { readonly revealed: boolean /** The file's new side, which supplies collapsed unchanged lines. */ readonly text: DiffFileText - /** Indexes of the expanded gaps. */ - readonly open: ReadonlySet + /** The lines each expanded gap shows, by gap index. */ + readonly open: ReadonlyMap /** Whether deletions and additions show in two columns; a file with only additions or only deletions keeps one. */ readonly split: boolean /** Whether long lines wrap. */ @@ -145,24 +151,33 @@ const SIGN: Record = { add: '+', del: '-', context: '' /** Highlighted tokens of one side's lines by line number, or undefined while the grammar is unavailable. */ type SideSpans = ReadonlyMap | undefined -/** A segment ready to draw: collapsed lines, or rows with the tokens of each side. */ +/** A segment ready to draw: collapsed lines, or rows with the tokens of each side and the lines each side numbers. */ type Prepared = - | { readonly kind: 'gap'; readonly index: number; readonly count: number | null } - | { readonly kind: 'folded'; readonly hunks: readonly number[] } - | { readonly kind: 'rows'; readonly rows: readonly DiffRow[]; readonly old: SideSpans; readonly new: SideSpans } - -/** Highlight one side of a run of rows as one fragment, so tokens spanning lines keep their state. */ -function sideSpans(rows: readonly DiffRow[], side: 'old' | 'new', highlighter: CodeHighlighter): SideSpans { - const numbered: { readonly no: number; readonly text: string }[] = [] - for (const row of rows) { - const no = row[side] - if (no !== null) numbered.push({ no, text: row.text }) + | Extract + | { + readonly kind: 'rows' + readonly rows: readonly DiffRow[] + readonly old: SideSpans + readonly new: SideSpans + readonly oldRun: SideRun | undefined + readonly newRun: SideRun | undefined } - if (numbered.length === 0) return new Map() - const highlighted = highlighter(numbered.map(line => line.text).join('\n')) + +/** + * Highlight one side of a run of rows as one fragment, so tokens spanning lines keep their state. The tokens are kept by + * the change and the run's lines in `kept`, which the caller replaces with the file or the highlighter. + */ +function sideSpans(run: SideRun | undefined, change: string, highlighter: CodeHighlighter, kept: Map): SideSpans { + if (run === undefined) return new Map() + const key = runKey(change, run) + const known = kept.get(key) + if (known !== undefined) return known + const highlighted = highlighter(run.texts.join('\n')) if (highlighted === undefined) return undefined // Shiki omits a final empty token row, so a final empty line gets no tokens. - return new Map(numbered.map((line, index) => [line.no, highlighted[index] ?? []])) + const spans = new Map(run.texts.map((_text, index) => [run.first + index, highlighted[index] ?? []])) + kept.set(key, spans) + return spans } function Code({ text, spans, old, next }: { @@ -348,10 +363,30 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme && inHunks(file, [index], thread.selection.comment.side, thread.selection.comment.endLine))) return new Set([...folded.hunks].filter(index => !holds(index))) }, [folded, editors, review, comments.threads, file]) - const prepared = useMemo(() => segmentsOf(file, lines, open, foldHunks).map((segment): Prepared => segment.kind !== 'rows' - ? segment - : { ...segment, old: sideSpans(segment.rows, 'old', highlighter), new: sideSpans(segment.rows, 'new', highlighter) }), - [file, lines, open, foldHunks, highlighter]) + // Runs whose lines stay the same keep their tokens when the file's text arrives or another gap expands. + const kept = useMemo(() => new Map(), [file, highlighter]) + const prepared = useMemo(() => segmentsOf(file, lines, open, foldHunks).map((segment): Prepared => { + if (segment.kind !== 'rows') return segment + const oldRun = sideRun(segment.rows, 'old') + const newRun = sideRun(segment.rows, 'new') + return { + ...segment, oldRun, newRun, + old: sideSpans(oldRun, file.digest, highlighter, kept), new: sideSpans(newRun, file.digest, highlighter, kept), + } + }), [file, lines, open, foldHunks, highlighter, kept]) + // Rows drawn after collapsed lines take the colors of the lines before them once the whole file is known, after they draw. + const runs = useMemo(() => prepared.flatMap(segment => segment.kind !== 'rows' ? [] + : [segment.oldRun, segment.newRun].filter((run): run is SideRun => run !== undefined)), [prepared]) + const sides = useMemo((): FileSides | undefined => lines === undefined ? undefined + : { new: lines, old: oldSideLines(lines, file.hunks) }, [lines, file.hunks]) + const corrected = useContextHighlight(runs, sides, file.digest, highlighter, root, selecting) + const spansOf = (spans: SideSpans, run: SideRun | undefined): SideSpans => run === undefined ? spans + : corrected.get(runKey(file.digest, run)) ?? spans + const collapsed = prepared.some(segment => segment.kind === 'gap') + const grammar = languageForPath(file.path) !== undefined + useEffect(() => { + if (text === undefined && collapsed && grammar) handlers.readContext(file) + }, [text, collapsed, grammar, file, handlers]) // Returns whether the range was accepted; a range across hunks or outside them keeps the previous selection. const choose = (side: 'L' | 'R', line: number, extend: boolean): boolean => { /* v8 ignore next -- the line buttons and hover pluses that choose a range draw only with review actions */ @@ -500,21 +535,46 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme ) rows.push(
{side(pair.left, left)}{side(pair.right, right)}
) } - for (const [at, segment] of prepared.entries()) { - if (segment.kind === 'gap') { - rows.push() + {label} + + } + const step = (expansion: 'down' | 'up'): ReactNode => { + const name = t(expansion === 'down' ? 'diff.expandDown' : 'diff.expandUp', { count: String(EXPAND_STEP) }) + return + + + } + return
+ {segment.edge !== 'leading' && step('down')} + {segment.edge !== 'trailing' && step('up')} + {label} +
+ } + for (const [at, segment] of prepared.entries()) { + const oldSpans = segment.kind === 'rows' ? spansOf(segment.old, segment.oldRun) : undefined + const newSpans = segment.kind === 'rows' ? spansOf(segment.new, segment.newRun) : undefined + if (segment.kind === 'gap') { + rows.push(gapRow(segment)) for (const item of unplaced) { - if (gapOf(file, item.place.side, item.place.endLine) !== segment.index) continue + if (!hidesLine(segment, item.place.side, item.place.endLine)) continue rows.push(threadCard(item)) unplaced.delete(item) } for (const item of unplacedNotes) { const at = lastLine(item) - if (gapOf(file, at.side, at.line) !== segment.index) continue + if (!hidesLine(segment, at.side, at.line)) continue rows.push(annotationOf(item)) unplacedNotes.delete(item) } @@ -540,7 +600,7 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme for (const [index, pair] of splitRows(segment.rows).entries()) { rows.push(
{ extendAdd(event.buttons, pair.left?.no ?? null, pair.right?.no ?? null) }}> - {cell(pair.left, segment.old, 'L')}{cell(pair.right, segment.new, 'R')} + {cell(pair.left, oldSpans, 'L')}{cell(pair.right, newSpans, 'R')}
) notes(`notes-${at}-${index}`, pair) } @@ -551,7 +611,7 @@ function Lines({ file, text, open, handlers, split, wrap, review, visible, comme rows.push(
{ extendAdd(event.buttons, row.old, row.new) }}> {singleSide !== 'R' && number('L', row.old, row.kind === 'del' && !labeled)}{singleSide !== 'L' && number('R', row.new, row.kind !== 'del' && !labeled)}{SIGN[row.kind]} - +
) rows.push(...commentsAt('L', row.old), ...commentsAt('R', row.new)) } diff --git a/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx b/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx index a4995615f1..c19fbcfde5 100644 --- a/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx +++ b/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx @@ -15,12 +15,15 @@ export type FileTreePosition = 'right' | 'left' | 'hidden' /** * Render a keyboard- and pointer-resizable tree beside the diff. - * @param props - tree rows, pane position, the toggle's controlled element id, and the receiver of the shown width. + * @param props - tree rows, pane position, the toggle's controlled element id, the width the cell above the tree needs, + * and the receiver of the shown width. * @returns the bounded pane and its resize separator. */ -export function FileTreePane({ position, id, onWidth, ...props }: ChangedFilesProps & { +export function FileTreePane({ position, id, least = 0, onWidth, ...props }: ChangedFilesProps & { readonly position: FileTreePosition readonly id: string + /** Width in pixels the toolbar cell above the tree needs, which raises the pane's least width above its own. */ + readonly least?: number /** Receives the pane's width in pixels whenever it changes, so the toolbar can align a cell with it. */ readonly onWidth: (width: number) => void }): ReactNode { @@ -42,13 +45,15 @@ export function FileTreePane({ position, id, onWidth, ...props }: ChangedFilesPr observer.observe(parent) return () => { observer.disconnect() } }, []) - const shown = Math.min(width, maximum) + const floor = Math.max(MIN_WIDTH, least) + const top = Math.max(floor, maximum) + const shown = Math.max(floor, Math.min(width, top)) useLayoutEffect(() => { onWidth(shown) }, [shown, onWidth]) const direction = position === 'left' ? 1 : -1 - const resize = (next: number): void => { setWidth(Math.round(Math.max(MIN_WIDTH, Math.min(maximum, next)))) } + const resize = (next: number): void => { setWidth(Math.round(Math.max(floor, Math.min(top, next)))) } return