Merge pull request #7965 from deepseek-harness/feat/session-panel

feat(panel): add the floating Session panel
This commit is contained in:
LegGasai authored and GitHub committed 2026-11-15 15:20:08 +08:00
commit eaf815665a
181 files changed
+3911 -70

No files matched your search

@@ -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
@@ -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.
@@ -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 视图实例都会渲染侧边层,因此同一会话同时显示在主正文区和嵌入的对话中时,两处都会显示浮层。
- 轮次轨道的位置对所有用户都变了;行为和隐藏规则不变。
+1 -1
View File
@@ -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)
@@ -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"
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": Clickable links gallery
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": Use only Cordis tools. First
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -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:
@@ -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:
@@ -1,6 +1,7 @@
- banner:
- navigation "Session hierarchy": workspace
- text: Standard mode
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": CJK strong emphasis
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": Markdown image policy
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": Inline code links
- button "Session panel"
- button "More actions"
- tablist:
- tab "Chat" [selected]
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": Math rendering
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": Reference order target
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -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:
@@ -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:
@@ -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:
@@ -1,5 +1,6 @@
- banner:
- navigation "Session hierarchy": {{workspace}}
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -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:
@@ -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:
@@ -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:
+253
View File
@@ -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<SessionId>('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<HTMLElement>('[data-chat-aside]')
const column = document.querySelector<HTMLElement>('[data-chat-flow]')
const probe = document.querySelector<HTMLElement>('[data-session-panel-probe]')
const toggle = document.querySelector<HTMLElement>('[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<HTMLElement>('[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<void> {
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<void> {
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<HTMLElement>('[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<typeof watchConsole>
/** 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<void> {
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<void> {
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([])
})
})
@@ -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:
+1
View File
@@ -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",
+2 -1
View File
@@ -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) |
+2 -1
View File
@@ -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) |
+1 -1
View File
@@ -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) |
+1 -1
View File
@@ -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) |
+2
View File
@@ -196,6 +196,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` | — |
+2
View File
@@ -198,6 +198,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"]
@@ -1661,6 +1662,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` | — |
+6 -6
View File
@@ -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: 3216b23c131d0070
zh: 73ca171c6014f16e
+3 -3
View File
@@ -1329,7 +1329,7 @@ Source: [`packages/web/web-search-deepseek/src/provider.ts:89`](../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 |
|---|---|---|
+3 -3
View File
@@ -1331,7 +1331,7 @@ export type SessionEvent<T extends SessionEventType = SessionEventType> = {
}
```
来源:[`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)
| 属性 | 存在性 | 类型 |
|---|---|---|
+2 -2
View File
@@ -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":[]},
@@ -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":[]},
+2 -2
View File
@@ -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
+9
View File
@@ -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]
+9
View File
@@ -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]
+5
View File
@@ -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'
+1
View File
@@ -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:*",
+2 -2
View File
@@ -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
+1
View File
@@ -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 | — |
+1
View File
@@ -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 状态及其退出控件 | — |
+2 -2
View File
@@ -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
+3 -1
View File
@@ -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.
+3 -1
View File
@@ -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 头栏和展开的压缩摘要头栏仍以实际会话滚动容器为参照。限高过程组和终端区域保留各自的滚动容器。
@@ -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 => {
@@ -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<PropsRenderSlots<'conversation.chat.aside'>, 'renderSlot'>) {
return <div className={css.asideSlot} data-chat-aside="">{renderSlot('conversation.chat.aside', {})}</div>
})
@@ -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;
@@ -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}
/>
)}
<ChatAside renderSlot={renderSlot} />
<div className={css.root} data-chat-following-tail={scroll.followingTail ? '' : undefined}>
<div ref={scroll.listRef} className={css.scroll}>
<div ref={scroll.columnRef} className={css.column} data-chat-flow=""
@@ -30,7 +30,8 @@
position: absolute;
top: calc(var(--turn-rail-band) / 2);
right: 12px;
/* The start edge: the end gutter belongs to the Session panel. */
left: 12px;
width: 28px;
/* Fixed-pitch marks never compress: a ladder taller than the band scrolls
inside this frame instead of pushing marks under the composer or above
@@ -97,14 +98,14 @@
.mark::before {
position: absolute;
top: 50%;
right: 0;
left: 0;
width: 20px;
height: 2px;
border-radius: 2px;
background: var(--dsw-alias-border-l4);
content: '';
transform: translateY(-50%) scaleX(0.6);
transform-origin: right center;
transform-origin: left center;
transition: transform 140ms ease, background-color 140ms ease;
}
@@ -142,11 +143,11 @@
.mark:focus-visible::after {
position: absolute;
inset: 0 0 0 auto;
inset: 0 auto 0 0;
width: 20px;
border-radius: inherit;
outline: 1px solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
/* The scroller clips the right edge; keep the marker's ring inside it. */
/* The scroller clips the left edge; keep the marker's ring inside it. */
outline-offset: -1px;
content: '';
}
@@ -158,7 +159,7 @@
calc(var(--turn-preview-center) - var(--turn-preview-height) / 2),
calc(100% - var(--turn-preview-height))
);
right: calc(100% + 10px);
left: calc(100% + 10px);
box-sizing: border-box;
width: min(300px, calc(100cqw - 120px));
max-height: var(--turn-preview-height);
@@ -194,7 +195,7 @@
}
@keyframes dsh-turn-preview-enter {
from { opacity: 0; transform: translateX(4px); }
from { opacity: 0; transform: translateX(-4px); }
to { opacity: 1; transform: translateX(0); }
}
@@ -390,7 +390,7 @@ export type ChatFlowSlotProps =
/** Full Chat view props. */
export type ChatViewSlotProps =
PropsRuntime<'conversation.view'>
& 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<ChatStore>
& InjectFace<ChatViewInjected>
& 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': {
@@ -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))',
)
})
})
@@ -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<FlowRenderer>[2] & { entryKey?: string; children?: React.ReactNode },
) => {
if (key === 'conversation.chat.text-interaction') return null
if (key === 'conversation.chat.aside') {
asideRenders.count += 1
return <span data-chat-aside-probe="" />
}
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<ProcessGroupData> | undefined) => {
grouped = value
@@ -763,7 +768,7 @@ describe('Chat node rendering', () => {
const { getTriggerProps } = useMarkdownDelegate()
return <>{targets.map((target, index) => <button key={index} {...getTriggerProps!(target)}>{index}</button>)}</>
}
const view = render(<ChatView {...h.props} renderSlot={() => <References />} />)
const view = render(<ChatView {...h.props} renderSlot={(key: string) => key === 'conversation.chat.aside' ? null : <References />} />)
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(<h.ChatView {...h.props} />)
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(<ChatView {...h.props} renderSlot={() => <>
const view = render(<ChatView {...h.props} renderSlot={(key: string) => key === 'conversation.chat.aside' ? null : <>
<a href="https://example.com/plugin">Plugin link</a>
<button data-file-path="/plugin/private.txt">Undeclared file</button>
<button onContextMenu={(event) => {
@@ -21,8 +21,8 @@
en: 4a094cd97426ad18
zh: 5faadddb7e2b0a43
/deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props:
en: 25dd776b1c1562f1
zh: 1efe8e6e56e73153
en: dcbdef97e4532896
zh: 23d6840c89f66bab
/deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries:
en: 59cd63057dfb6eeb
zh: b2e2c86e810b7bb8
@@ -116,6 +116,8 @@ View selection is deterministic: a registered persisted selection wins, otherwis
The shell reads the persisted View preference before rendering when a Session first binds or a cached Session becomes current, activates the registered preferred View or Chat fallback, and activates later tab or focus selections before committing them to the store. A blank Session still omits the `conversation.view` slot; no unselected target is activated.
Until the user drags a width, the main transcript is 64% of the Conversation body wide, from 680px up to 880px; an embedded transcript is the body width less 32px, up to 880px. Beside the main transcript, the composer card is 32px wider than the transcript.
Active transcripts in the main occurrence expose content-width drag handles in their uncovered side gutters; embedded occurrences omit them. A View that paints into a gutter raises only its concrete painted element above the handle; transparent full-width wrappers stay below so they do not claim empty gutter. This requires the path between that element and the Conversation body to remain outside an intermediate stacking context; the shipped Chromium behavior is pinned by the browser scenario. Chat applies the rule to table elements, while its column-bounded tool cards need no raise. Wheel motion over a handle still scrolls the transcript, while Ctrl+wheel remains a browser zoom gesture. The handle scrolls the first `[data-conversation-scroll]` element inside the body, which is the body's own scroll element even when frame layers wrap it. The sticky composer owns its full footer band, which is not a resize target; a captured drag continues under the band and under gutter tables, which cover its indicator. In an active transcript the composer rests at the scrollport floor even when no View fills the column, keeps one stacking rank in every state, above transcript sticky headers and the back-to-bottom control, so menus it opens upward cover that control, and never serves as a scroll-anchoring target. It keeps its own compositor layer whatever lies beneath it, which makes it the containing block for fixed-position descendants: contributions to `conversation.composer`, `conversation.composer.bar`, `conversation.composer.dock`, `conversation.input.dock`, and the other `conversation.input.*` slots must portal fixed overlays to the document body, for example with `Tooltip` or `Menu` `portal` or `createPortal` ([handle and composer styles](src/client/skeleton/ConversationRoot.module.css)).
The width-handle indicator follows the pointer only during a captured drag; ordinary hover leaves its position unchanged.
@@ -116,6 +116,8 @@ View 选择规则固定:有效且已注册的持久化选择优先,其次是
Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染前读取持久化 View 偏好,激活已注册的偏好 View 或 Chat fallback,并在后续 tab 或 focus 选择写入 store 前先激活对应 target。blank Session 仍不渲染 `conversation.view` slot;未选中的 target 不会激活。
用户拖动调整宽度之前,主 transcript 宽度为 Conversation 主体宽度的 64%,范围 680px 到 880px;嵌入式 transcript 为主体宽度减 32px,最多 880px。主 transcript 下方的输入框卡片比 transcript 宽 32px。
主 occurrence 的活跃 transcript 只在未被内容覆盖的两侧沟槽中提供正文宽度拖拽条;嵌入式 occurrence 省略这些拖拽条。View 如果绘制进沟槽,只将具体的可见元素提到拖拽条上方;透明的全宽包装层保持在下方,不会占用空白沟槽。该规则要求此元素与 Conversation body 之间不能引入中间堆叠上下文;浏览器场景固定了交付 Chromium 的行为。Chat 将该规则用于表格元素,其限定在阅读列内的工具卡片无需提高层级。指针位于拖拽条上时,滚轮仍会滚动 transcript,Ctrl+滚轮则保留为浏览器缩放手势。拖拽条滚动的是 body 内第一个 `[data-conversation-scroll]` 元素;即使有 frame 层包在外面,它也是 body 自己的滚动区。粘滞 composer 拥有完整的底部区带,该区域不是宽度调整目标;已捕获的拖拽会在该区带和沟槽中的表格下方继续,此时指示线被它们遮住。在活跃 transcript 中,即使没有 View 撑满整列,composer 也停在滚动区底部;它在所有状态下保持同一层级,高于 transcript 的吸顶标题与“回到底部”按钮,因此它向上打开的菜单会盖住该按钮;它也从不作为滚动锚定目标。无论下方是什么内容,它都保持自己的合成层,因此成为 fixed 定位后代的包含块:向 `conversation.composer`、`conversation.composer.bar`、`conversation.composer.dock`、`conversation.input.dock` 以及其他 `conversation.input.*` slot 贡献的内容,必须把 fixed 浮层 portal 到 document body,例如使用 `Tooltip` 或 `Menu` 的 `portal`,或 `createPortal`([拖动手柄与 composer 样式](src/client/skeleton/ConversationRoot.module.css))。
宽度拖拽条的指示线只在已捕获指针的拖拽期间跟随指针,普通悬停不改变其位置。
@@ -467,7 +467,7 @@
preference; embedded occurrences override this adaptive axis below. */
--dsh-chat-content-width: var(
--dsh-chat-user-width,
clamp(680px, calc(var(--dsh-conversation-column-width, 0px) * 0.64), 920px)
clamp(680px, calc(var(--dsh-conversation-column-width, 0px) * 0.64), 880px)
);
--dsh-composer-card-max-width: calc(var(--dsh-chat-content-width) + 32px);
--dsh-composer-side-clearance: 16px;
@@ -476,8 +476,8 @@
.embeddedBody {
overflow: hidden;
--dsh-chat-content-width: min(calc(100% - 32px), 920px);
--dsh-composer-card-max-width: min(calc(100% - 16px), 952px);
--dsh-chat-content-width: min(calc(100% - 32px), 880px);
--dsh-composer-card-max-width: min(calc(100% - 16px), 912px);
--dsh-composer-side-clearance: 8px;
--dsh-composer-dock-inset: 8px;
}
@@ -24,7 +24,7 @@ function readWidthPreference(): number | null {
function resolveContentWidth(columnWidth: number, preference: number | null): number {
const max = Math.max(CONTENT_MIN, columnWidth - CONTENT_EDGE_BUDGET)
if (preference !== null) return Math.min(Math.max(preference, CONTENT_MIN), max)
return Math.max(680, Math.min(columnWidth * 0.64, 920))
return Math.max(680, Math.min(columnWidth * 0.64, 880))
}
/** Convert a wheel event's vertical delta to scrollport pixels. */
@@ -972,32 +972,32 @@ describe('ConversationRoot resident composer', () => {
Element.prototype.releasePointerCapture = function () { captured.delete(this) }
Element.prototype.hasPointerCapture = function () { return captured.has(this) }
try {
// Base resolves from the adaptive clamp: min(1600*0.64, 920) = 920.
// Dragging the right handle outward by 25px widens by 2×25 = 50 → 970,
// Base resolves from the adaptive clamp: min(1600*0.64, 880) = 880.
// Dragging the right handle outward by 25px widens by 2×25 = 50 → 930,
// inside both bounds (max = 1600 − 176 = 1424 keeps the handles on-column).
fireEvent.pointerDown(handle, { pointerId: 1, clientX: 800, clientY: 300 })
fireEvent.pointerMove(handle, { pointerId: 1, clientX: 825, clientY: 300 })
expect(handle.style.getPropertyValue('--dsh-width-handle-pointer-y')).toBe('300px')
fireEvent.pointerUp(handle, { pointerId: 1, clientX: 825, clientY: 300 })
expect(handle.hasAttribute('data-dragging')).toBe(false)
expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('970px')
expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('970')
expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('930px')
expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930')
// Window shrinks: the displayed width re-clamps (900 − 176 = 724) but the
// preference stays.
Object.defineProperty(content, 'offsetWidth', { value: 900, configurable: true })
act(() => { fireResize(content) })
expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px')
expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('970')
expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930')
// A press without travel (a real double-click delivers two such
// press/release rounds) must not commit the clamped display value over
// the stored preference.
fireEvent.pointerDown(handle, { pointerId: 1, clientX: 800, clientY: 300 })
fireEvent.pointerUp(handle, { pointerId: 1, clientX: 800, clientY: 300 })
expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('970')
expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930')
expect(root.style.getPropertyValue('--dsh-chat-user-width')).toBe('724px')
// No reset affordance on the handle: double-click leaves the preference alone.
fireEvent.doubleClick(handle)
expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('970')
expect(localStorage.getItem('dsh.conversation.contentWidth')).toBe('930')
} finally {
for (const [name, descriptor] of originals) {
if (descriptor === undefined) Reflect.deleteProperty(Element.prototype, name)
@@ -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
+126
View File
@@ -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)
-----
<a id="use-this-package"></a>
## 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.
<a id="contribute-a-section"></a>
### 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 `<button>` body is the row's action, and its press area covers the whole row; the trailing part and the menu stay separate controls above it. |
| `data-row-part="icon"` | A 16px decorative glyph inside the body, in the row ink; mark it `aria-hidden`. |
| `data-row-part="content"` | One line of text inside the body, clipped with an ellipsis. |
| `data-row-part="trailing"` | A value or control after the body. |
| `data-row-part="menu"` | Row actions, such as a More button, in a 16px column whose center sits 14px from the row's end. A plain `button` there gets a 24px target and a tertiary glyph that darkens on hover without a fill, so it needs no tooltip of its own. They show on row hover, on focus inside the row, and while one has its menu open, and always without hover. |
Leave out a part the row does not have: a `<button>` body or a menu part is what makes the row highlight. A menu part that renders nothing, such as a shared menu button whose target has no menu entries, counts as absent: it takes no room and the row does not highlight for it. Each rule for a part has the specificity of one class, so a row's own class adjusts it.
-----
<a id="understand-the-implementation"></a>
## Understand the implementation
<details>
<summary>Implementation internals — click to expand</summary>
The panel is the `conversation.chat.aside` occupant of [`dsh-client-ui-chat`](../ui-chat/README.md#scroll-ownership), so it renders only in Chat Views. The toggle and the panel are separate Slot entries that share one plugin-owned state: the persisted docking preference, the Session whose overlay is open, and whether each mounted panel and each Session has room to dock. The stylesheet decides that room. The aside layer publishes its end gutter as `--dsh-chat-aside-gutter`; the docked width and a zero-height dock probe derive from it and from one set of metrics (40px clear, 8px edge, 300px minimum width), so the probe is 1px wide exactly from the 348px gutter that holds the panel at its minimum width and 0 below it. The panel always renders the probe and attaches it through the injected `createProbeRef`, and the plugin observes only that element with a `ResizeObserver`: it hears the docking decision flip and nothing while the window resizes on one side of it, the transcript width is dragged, or the transcript grows. A probe has room from 1px of width, a Session has room while any of its probes does, and a Session without a probe shows no Chat View. The panel reads its own probe and the toggle its Session, and both decide the presentation with the same pure function, so the toggle's state never disagrees with the panel; opening, closing, or docking the panel renders nothing in the Chat View. Without `ResizeObserver` no probe gains room, and the panel shows only as an overlay. The aside layer also inherits the scrollport's composer and viewport heights.
The panel projects the section list's live registrations (`entriesOfSlot`, so a higher-priority registration with the same `id` replaces a shipped section) into `{ id, label }` rows, recomputed only when the ledger version or the locale revision changes. It renders each section through `renderSlot(..., { only: id })` inside its own title and body; a CSS `:has()` rule hides a section whose body outlet stayed empty, including a shared section whose row outlet stayed empty.
| File | Role |
|---|---|
| [`src/client/index.ts`](src/client/index.ts) | Dictionaries, the toggle, the panel, the Environment section, and the project row |
| [`src/client/slots.ts`](src/client/slots.ts) | Slot declarations and component props |
| [`src/client/visibility.ts`](src/client/visibility.ts) | Presentation, the shared visibility state, the dock probes, and each Session's room to dock |
| [`src/client/sections.ts`](src/client/sections.ts) | Section roster projection |
| [`src/client/SessionPanel.tsx`](src/client/SessionPanel.tsx) | The panel, its dock probe, its section titles, and Escape handling |
| [`src/client/SessionPanelToggle.tsx`](src/client/SessionPanelToggle.tsx) | The header toggle and its indicators |
| [`src/client/SessionPanel.module.css`](src/client/SessionPanel.module.css) | The panel's geometry, the dock probe, and the rules for marked rows |
| [`src/client/ProjectRow.tsx`](src/client/ProjectRow.tsx) | The working folder row |
</details>
-----
<a id="further-exploration"></a>
## Further Exploration
- [Web Client Slots](../../../docs/subsystems/slots.md) — list, keyed, and owner-prop semantics the sections rely on.
- [`dsh-client-ui-chat`](../ui-chat/README.md#scroll-ownership) — the `conversation.chat.aside` layer and its `--dsh-chat-aside-gutter` property.
- [`dsh-client-ui-conversation`](../ui-conversation/README.md) — the Session header utilities.
- [`dsh-client-ui-primitives`](../ui-primitives/README.md#component-catalog) — `Button`, `Tooltip`, the icons, and the modal and composition guards.
-----
<a id="model-experience"></a>
## Model Experience
None, as this package renders facts the Client already holds for a human and touches no prompt, message, schema, stream, or tool result.
#### KV Cache effect
None; the package never assembles or sends provider requests.
## Known Limitations and Deferred Work
<a id="known-limitations-and-deferred-work"></a>
These limits define current package constraints, not a task backlog.
- **Laptop widths overlay rather than dock** — with the default transcript width the body must be at least about 1608px wide to dock; narrower bodies use the overlay. Docking by moving the transcript column aside is a separate layout decision.
- **No execution environment row** — the Client has no per-Session fact for the local machine, an SSH host, or the sandbox mode, so the Environment section names only the working folder.
- **No section customization** — every live section shows; hiding or reordering sections from the panel is not offered.
- **No switch back to Chat from other Views** — `dsh-client-ui-conversation` exposes no View selection to plugins, so the toggle in the trajectory View cannot select the Chat View for the user.
- **An overlay shows in each Chat View of its Session** — every Chat View occurrence, main or embedded, renders the aside, so a Session shown in the main body and in an embedded Conversation at once shows its overlay in both.
<a id="dev-note"></a>
### Dev Note
<details>
<summary>Working context for maintainers — click to expand</summary>
None.
</details>
@@ -0,0 +1,126 @@
---
description: "会话面板:会话标题栏开关与 Chat 视图侧边层中的悬浮面板,分栏由其他插件注册,并内置「环境」分栏。"
kind: "package-reference"
---
# @deepseek-ai/dsh-client-ui-session-panel
[English](README.md) | 中文
## 概述
`dsh-client-ui-session-panel` 在会话标题栏加一个开关,用来显示或隐藏一块汇总当前会话信息的悬浮面板。面板只出现在 Chat 视图中:Chat 视图末端留白放得下面板时,面板停靠在留白里;放不下时,按需浮在对话正文上方。面板只绘制分栏标题,分栏内容交给注册分栏的插件;本包内置「环境」分栏及其工作目录行。
## 目录
- [使用本包](#use-this-package)
- [理解实现](#understand-the-implementation)
- [进一步探索](#further-exploration)
- [模型体验](#model-experience)
- [已知限制与延期工作](#known-limitations-and-deferred-work)
- [开发备注](#dev-note)
-----
<a id="use-this-package"></a>
## 使用本包
`@deepseek-ai/dsh-web-app` 套件默认加载本包。开关是会话标题栏的第一个工具按钮,位于变更请求、共享和计划任务目录之前。它是图标按钮:无障碍名称由面板名称和其角标组成,提示文字说明按下后是显示还是隐藏面板(悬停 500ms 后显示,键盘聚焦时立即显示),`aria-expanded` 表示面板当前是否显示。
### 停靠与浮层
正文列到 Chat 外框末端边缘的留白不少于 348px 时,面板停靠:与正文列及其宽度手柄保持 40px 间距,面板最小宽度 300px,外加 8px 边距。停靠时面板宽 300–360px,距末端边缘 8px,位于标题栏下方 12px,止于输入框区域上方,内容在面板内滚动,并为滚动条在距面板末端边缘 2px 处预留一列,因此无论是否滚动,内容宽度都不变。此时按开关会切换所有会话共用的停靠偏好,偏好存放在 `localStorage` 的 `dsh.sessionPanel.pinned` 中;默认停靠。
留白更窄时隐藏停靠面板,保证不遮挡正文。窗口变窄、展开右侧栏、把正文列拖宽都会如此。此时按开关,面板以更强的阴影浮在正文上方,宽 280px,比停靠时窄,以少遮挡正文,距末端边缘 8px,位于输入框区域之上,且不遮挡输入框。浮层可以用开关关闭,也会在按 Esc 时,或在面板、开关和任何已打开的菜单(例如行的上下文菜单)之外按下指针时关闭;焦点原本在面板内时,按 Esc 后焦点回到开关。页面上方有模态框、输入法正在组字,或已有处理程序(例如打开的菜单)接手了这次按键时,Esc 不归浮层;其余情况由浮层先处理,因此浮层打开时,在输入框按下的第一次 Esc 只关闭浮层,不计入停止当前轮次的连按。关闭浮层不改变停靠偏好。同一时间最多一个会话的浮层处于打开状态;留白变宽到可以停靠时,以及没有 Chat 视图再显示该会话时(例如切到其他会话或其他视图),浮层都会关闭,切回来也不会重新打开。面板隐藏时如果焦点在面板内,焦点移到开关。
轨迹等其他视图不显示面板。没有 Chat 视图显示该会话时,开关不可用:它连同角标留在标题栏中并变淡,悬停提示请用户切换到「对话」视图。
<a id="contribute-a-section"></a>
### 贡献分栏
一个分栏是 `conversation.session.panel.section` 列表里的一次注册:`id` 用于寻址,`order` 升序排列,必填的 `label` 是标题,面板按当前语言绘制。分栏组件通过 owner props 收到 `presentation`(`docked` 或 `overlay`)和 `dismissOverlay()`;它负责渲染正文,没有内容时什么都不渲染,标题随之隐藏。标题尾部的控件(例如计数或刷新按钮)注册到以分栏 `id` 为键的 keyed slot `conversation.session.panel.section.actions`。缺少 label 的分栏会报告到控制台,并且不显示。
多个插件共用一个标题时,把行注册到分栏拥有者的行 slot 中。内置「环境」分栏(`id: 'environment'`,`order: 0`)声明 `conversation.session.panel.environment.row`;其 `project` 行(`order: 0`)显示会话的工作目录:`workingDirectory` 投影记录的当前目录;投影尚未送达或没有记录时,依次取会话创建时所在的目录、列出本会话的工作区目录。该行先显示目录名,再以三级文字色显示父目录,放不下时以省略号截断;悬停 500ms 后出现的提示写明工作目录并给出完整路径。两处都把宿主家目录缩写为 `~`。右键该行或点其「更多」按钮会打开共享的 `directory` 上下文菜单。拥有共享分栏的插件用同样方式声明自己的行 slot。
面板隐藏时也要可见的标记(例如需要处理的红点)放进 `conversation.session.panel.indicator` 列表。每个占位是一个元素:开关把它定为图标角上的 6px 圆点,占位负责设置 `background`,并带有说明自身的文字,这些文字会成为开关无障碍名称的一部分。占位会重叠,`order` 高的画在低的上方。owner 属性 `panelShown` 让只是重复面板内容的标记在面板显示时不渲染。
各行共享同一外观,但不共享组件。分栏的组件或「环境」分栏的行条目自己写行的标记并标出各个部分,由面板的样式表统一排版,因此不同包的图标、文字与尾部区域对齐,而行里放什么由各包自己决定。
| 标记 | 部分 |
|---|---|
| `data-session-panel-row` | 行:占 28px 一行。带操作或菜单的行在悬停时以及其菜单打开期间整行高亮。 |
| `data-row-part="body"` | 图标与文字。用 `<button>` 作为 body 时,它就是这一行的操作,点击区域覆盖整行;尾部区域与菜单仍是位于其上的独立控件。 |
| `data-row-part="icon"` | body 内的 16px 装饰图标,沿用行文字颜色;需标记 `aria-hidden`。 |
| `data-row-part="content"` | body 内的单行文字,溢出时以省略号截断。 |
| `data-row-part="trailing"` | body 之后的数值或控件。 |
| `data-row-part="menu"` | 行操作(例如「更多」按钮),位于 16px 宽的一列,中心距行末端 14px。其中的普通 `button` 有 24px 点击区和三级文字色图标,悬停时图标变深、没有底色,因此不需要自己的 tooltip。鼠标悬停在行上、焦点在行内或其菜单打开时显示,没有悬停能力的设备上始终显示。 |
行没有的部分就不要写:有 `<button>` body 或菜单部分的行才会高亮。没有渲染任何内容的菜单部分(例如目标没有菜单项时的共享菜单按钮)视同不存在:不占位置,行也不会因它高亮。每条针对某个部分的规则只有一个类的优先级,因此行自己的类可以调整它。
-----
<a id="understand-the-implementation"></a>
## 理解实现
<details>
<summary>实现内幕——点击展开</summary>
面板是 [`dsh-client-ui-chat`](../ui-chat/README.zh.md#scroll-ownership) 中 `conversation.chat.aside` 的占位组件,因此只渲染在 Chat 视图中。开关与面板是两个独立的 Slot 条目,共享一份插件持有的状态:持久化的停靠偏好、打开了浮层的会话,以及每个已挂载的面板和每个会话是否有停靠空间。停靠空间由样式表决定。侧边层把末端留白发布为 `--dsh-chat-aside-gutter`;停靠宽度和一个零高度的停靠探针都由它和同一组尺寸(间距 40px、边距 8px、最小宽度 300px)推出,因此探针恰好从留白 348px(放得下最小宽度的面板)起宽 1px,更窄时宽度为 0。面板始终渲染探针,并通过注入的 `createProbeRef` 挂接它;插件只用 `ResizeObserver` 观察这一个元素,所以只在停靠判断翻转时收到通知,窗口在阈值同一侧缩放、拖动正文宽度或正文增长时都不会。探针宽度达到 1px 即有停靠空间;会话的任一探针有空间时该会话就有停靠空间,没有探针的会话表示没有 Chat 视图在显示它。面板读取自己的探针,开关读取所在会话,两者用同一个纯函数决定呈现方式,因此开关状态始终与面板一致;打开、关闭或停靠面板也不会让 Chat 视图重新渲染。没有 `ResizeObserver` 时任何探针都不会获得空间,面板只以浮层显示。侧边层还从滚动容器继承输入框区域与视口高度。
面板把分栏列表的实时注册(`entriesOfSlot`,因此同 `id` 且优先级更高的注册会替换已发布的分栏)投影为 `{ id, label }` 行,只在台账版本或语言版本变化时重新计算。它在各分栏自己的标题和正文容器里用 `renderSlot(..., { only: id })` 渲染内容;CSS `:has()` 规则隐藏正文出口为空的分栏,也包括行出口为空的共享分栏。
| 文件 | 作用 |
|---|---|
| [`src/client/index.ts`](src/client/index.ts) | 字典、开关、面板、「环境」分栏与项目行 |
| [`src/client/slots.ts`](src/client/slots.ts) | Slot 声明与组件 props |
| [`src/client/visibility.ts`](src/client/visibility.ts) | 呈现方式、共享可见性状态、停靠探针与每个会话的停靠空间 |
| [`src/client/sections.ts`](src/client/sections.ts) | 分栏名单投影 |
| [`src/client/SessionPanel.tsx`](src/client/SessionPanel.tsx) | 面板、停靠探针、分栏标题与 Esc 处理 |
| [`src/client/SessionPanelToggle.tsx`](src/client/SessionPanelToggle.tsx) | 标题栏开关及其角标 |
| [`src/client/SessionPanel.module.css`](src/client/SessionPanel.module.css) | 面板的几何、停靠探针,以及带标记的行的样式规则 |
| [`src/client/ProjectRow.tsx`](src/client/ProjectRow.tsx) | 工作目录行 |
</details>
-----
<a id="further-exploration"></a>
## 进一步探索
- [Web Client Slots](../../../docs/subsystems/slots.zh.md)——分栏依赖的 list、keyed 与 owner props 语义。
- [`dsh-client-ui-chat`](../ui-chat/README.zh.md#scroll-ownership)——`conversation.chat.aside` 图层及其 `--dsh-chat-aside-gutter` 属性。
- [`dsh-client-ui-conversation`](../ui-conversation/README.zh.md)——会话标题栏工具区。
- [`dsh-client-ui-primitives`](../ui-primitives/README.zh.md#component-catalog)——`Button`、`Tooltip`、图标,以及模态层与输入法组合的判断。
-----
<a id="model-experience"></a>
## 模型体验
无。本包为用户展示客户端已有的信息,不涉及任何 prompt、消息、schema、流或工具结果。
#### KV 缓存影响
无;本包从不组装或发送模型请求。
## 已知限制与延期工作
<a id="known-limitations-and-deferred-work"></a>
以下限制定义的是当前包的约束,而非任务待办清单。
- **笔记本宽度下使用浮层而非停靠**——在默认正文宽度下,对话区宽度需约 1608px 以上才能停靠;更窄时使用浮层。通过把正文列移开来停靠属于另一项布局决策。
- **没有运行环境行**——客户端没有区分本机、SSH 主机或沙箱模式的会话级信息,因此「环境」分栏只显示工作目录。
- **不能自定义分栏**——所有有内容的分栏都会显示;面板不提供隐藏或重新排序分栏的功能。
- **不能从其他视图切回 Chat**——`dsh-client-ui-conversation` 没有向插件开放视图选择,因此轨迹视图中的开关无法替用户切换到 Chat 视图。
- **浮层会出现在其会话的每个 Chat 视图中**——每个 Chat 视图实例(主正文区或嵌入的)都会渲染侧边层,因此同一会话同时显示在主正文区和嵌入的对话中时,两处都会显示浮层。
<a id="dev-note"></a>
### 开发备注
<details>
<summary>维护者工作语境——点击展开</summary>
无。
</details>
@@ -0,0 +1,6 @@
{
"meta": {
"title": "Sitzungsbereich",
"description": "Ein schwebender Bereich, der sich über die Sitzungskopfzeile öffnet und Informationen zur aktuellen Sitzung bündelt, etwa ihren Arbeitsordner."
}
}
@@ -0,0 +1,6 @@
{
"meta": {
"title": "Session panel",
"description": "A floating panel opened from the Session header that gathers facts about the current Session, such as its working folder."
}
}
@@ -0,0 +1,6 @@
{
"meta": {
"title": "Panel de la sesión",
"description": "Un panel flotante que se abre desde el encabezado de la sesión y reúne información de la sesión actual, como su carpeta de trabajo."
}
}
@@ -0,0 +1,6 @@
{
"meta": {
"title": "Panneau de session",
"description": "Un panneau flottant ouvert depuis l'en-tête de la session qui regroupe les informations de la session en cours, comme son dossier de travail."
}
}
@@ -0,0 +1,6 @@
{
"meta": {
"title": "セッションパネル",
"description": "セッションのヘッダーから開くフローティングパネルで、作業フォルダーなど現在のセッションに関する情報をまとめて表示します。"
}
}
@@ -0,0 +1,6 @@
{
"meta": {
"title": "Painel da sessão",
"description": "Um painel flutuante aberto pelo cabeçalho da sessão que reúne informações da sessão atual, como a pasta de trabalho."
}
}
@@ -0,0 +1,6 @@
{
"meta": {
"title": "Панель сеанса",
"description": "Плавающая панель, которая открывается из заголовка сеанса и собирает сведения о текущем сеансе, например его рабочую папку."
}
}
@@ -0,0 +1,6 @@
{
"meta": {
"title": "会话面板",
"description": "在会话标题栏打开悬浮面板,集中展示工作目录等与当前会话相关的信息。"
}
}
@@ -0,0 +1,84 @@
{
"name": "@deepseek-ai/dsh-client-ui-session-panel",
"description": "Floating Session panel opened from the Session header, composed of sections that plugins register",
"version": "0.2.2-rc.3",
"type": "module",
"main": "lib/index.js",
"types": "lib/types/index.d.ts",
"exports": {
".": {
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./client": {
"types": "./lib/types/client/index.d.ts",
"default": "./lib/client.js"
},
"./src/*": "./src/*",
"./package.json": "./package.json",
"./locale/*.json": "./locale/*.json"
},
"scripts": {
"bundle": "tsdown",
"watch": "tsdown --watch"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
"directory": "packages/client/ui-session-panel"
},
"publishConfig": {
"access": "public"
},
"peerDependencies": {
"@deepseek-ai/cordis": "workspace:~"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-api-remotes": "workspace:*",
"@deepseek-ai/dsh-api-session-controller": "workspace:*",
"@deepseek-ai/dsh-api-workspace-controller": "workspace:*",
"@deepseek-ai/dsh-client-connection": "workspace:*",
"@deepseek-ai/dsh-client-locale": "workspace:*",
"@deepseek-ai/dsh-client-store": "workspace:*",
"@deepseek-ai/dsh-client-test-runtime": "workspace:*",
"@deepseek-ai/dsh-client-ui-chat": "workspace:*",
"@deepseek-ai/dsh-client-ui-context-menu": "workspace:*",
"@deepseek-ai/dsh-client-ui-conversation": "workspace:*",
"@deepseek-ai/dsh-client-ui-primitives": "workspace:*",
"@deepseek-ai/dsh-client-ui-renderer": "workspace:*",
"@deepseek-ai/dsh-client-ui-session": "workspace:*",
"@deepseek-ai/dsh-client-ui-slots": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
"@deepseek-ai/dsh-util-workspace-path": "workspace:*",
"@deepseek-ai/dsh-working-directory": "workspace:*",
"@deepseek-ai/dsh-workspace": "workspace:*",
"@testing-library/react": "^16.3.3",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"files": [
"locale/*.json",
"lib/index.js",
"lib/client.js",
"lib/types/**/*.d.ts",
"lib/types/**/*.d.ts.map",
"lib/**/*.js.map",
"src"
],
"dsh": {
"client": {
"inject": [
"@deepseek-ai/dsh-api-remotes",
"@deepseek-ai/dsh-client-connection",
"@deepseek-ai/dsh-client-locale",
"@deepseek-ai/dsh-client-ui-chat",
"@deepseek-ai/dsh-client-ui-context-menu",
"@deepseek-ai/dsh-client-ui-conversation",
"@deepseek-ai/dsh-client-ui-primitives"
],
"platform": "web"
}
}
}
@@ -0,0 +1,13 @@
/** Built-in Environment section: one shared title over the rows other plugins register. */
import type { ReactNode } from 'react'
import type { EnvironmentSectionProps } from './slots.ts'
/**
* Render the Environment rows. The rows render straight into the section
* body, so a section without rows renders nothing and the panel hides it.
* @param props - the section's child renderer.
* @returns the row outlet.
*/
export function EnvironmentSection({ renderSlot }: EnvironmentSectionProps): ReactNode {
return renderSlot('conversation.session.panel.environment.row', {})
}
@@ -0,0 +1,41 @@
/* [name] · [parent]: the name keeps its width up to the row, and the parent
fills the rest of the line and clips with an ellipsis. With less than 5em
left for it, the parent wraps onto a second line, which the one-line height
hides, so the row never shows a separator without a parent. The separator
is decorative, so assistive technology reads the name and the parent alone. */
.folder {
display: flex;
flex-wrap: wrap;
align-items: baseline;
min-width: 0;
height: 1lh;
overflow: hidden;
white-space: nowrap;
}
.folder:focus-visible {
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
outline-offset: 1px;
}
.name {
flex: 0 1 auto;
min-width: 0;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
}
.parent {
flex: 1 1 0;
min-width: 5em;
overflow: hidden;
color: var(--dsw-alias-label-tertiary);
text-overflow: ellipsis;
}
.parent::before {
padding: 0 4px;
content: '·' / '';
}
@@ -0,0 +1,51 @@
/** Environment row naming the Session's working folder. */
import type { ReactNode } from 'react'
import { IconFolderCloseRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'
import { abbreviateHomePath, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path'
import type {} from '@deepseek-ai/dsh-working-directory/types'
import type { ProjectRowProps } from './slots.ts'
import css from './ProjectRow.module.css'
const ROOT = /^(?:[/\\]|[A-Za-z]:[/\\])$/
/**
* Render the Session's working folder as its name followed by its parent
* folder, with the label and the full path in the tooltip. The folder is the
* Session's current working directory; before that projection arrives, or
* when it records none, it is the directory the Session was created in, else
* the Workspace that lists the Session. Paths under the Host account home
* start with `~`. The row and its More button open the directory context menu.
* @param props - Session values, the working directory projection, Workspace and Session list hooks, Host facts, menu bindings, and copy.
* @returns the row, or null before the Session's directory is known.
*/
export function ProjectRow({
sessionId, useProjection, useWorkspaces, useSessions, useHost, useContextMenu, renderFactorySlot, t,
}: ProjectRowProps): ReactNode {
const current = useProjection('workingDirectory')
const createdIn = useSessions(snapshot => snapshot.byId[sessionId]?.cwd)
const workspacePath = useWorkspaces(snapshot => snapshot.items.find(item => item.sessionIds.includes(sessionId))?.path)
const home = useHost(facts => facts.home)
const { getTriggerProps } = useContextMenu()
const path = current ?? createdIn ?? workspacePath
if (path === undefined) return null
const shown = abbreviateHomePath(path, home)
const { directory, name } = pathPartsOf(shown)
const parent = ROOT.test(directory) ? directory : directory.replace(/[/\\]+$/, '')
const target = { kind: 'directory', value: { sessionId, path } } as const
return (
<div {...getTriggerProps(target)} data-session-panel-row="" data-session-panel-project="">
<span data-row-part="body">
<span data-row-part="icon" aria-hidden="true"><IconFolderCloseRegular size={16} /></span>
<span data-row-part="content">
<Tooltip label={`${t('project.label')}\n${shown}`} side="left" delayMs={500}>
<span className={css.folder} tabIndex={0}>
<span className={css.name}>{name}</span>
{parent !== '' && <span className={css.parent}>{parent}</span>}
</span>
</Tooltip>
</span>
</span>
<span data-row-part="menu">{renderFactorySlot('contextMenu.button', { target, label: t('project.actions') })}</span>
</div>
)
}
@@ -0,0 +1,310 @@
/* The panel floats in the Chat View's aside layer, a zero-height box across
the top of the Chat frame that passes pointer events through. The layer
inherits the scrollport's --dsh-conversation-viewport-height and
--dsh-composer-height and publishes --dsh-chat-aside-gutter, the inline
space between the transcript column and the frame's end edge. */
/* The docked panel's inline metrics: 40px clear of the transcript column,
past its width handle, 8px from the end edge, and at least 300px wide. The
panel's width and the dock probe both derive from them, so the gutter that
docks the panel is exactly the one that holds its minimum width. */
.panel,
.dockProbe {
--panel-clear: 40px;
--panel-edge: 8px;
--panel-min-width: 300px;
}
.panel {
position: absolute;
top: 12px;
right: var(--panel-edge);
box-sizing: border-box;
width: clamp(
var(--panel-min-width),
calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge)),
360px
);
/* Stops above the composer stack, whose seat fades and takes presses across the body's full width. */
max-height: calc(var(--dsh-conversation-viewport-height, 100dvh) - var(--dsh-composer-height, 152px) - 24px);
overflow-y: auto;
overscroll-behavior: contain;
/* The bar has a place of its own: the content keeps its width whether or not
the panel scrolls, and the end inset stays 8px. A transparent end border
over the panel's own background holds the bar 2px from the edge, as the
sidebar does, and the track margin keeps the thumb out of the rounded corners. */
scrollbar-gutter: stable;
--dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);
--dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);
--dsh-scrollbar-track-margin: 12px;
padding: 6px calc(8px - 2px - var(--dsh-scrollbar-width)) 6px 8px;
border: 0;
border-right: 2px solid transparent;
/* The standard menu tier: a compact summary surface, not an enclosing panel. */
border-radius: var(--dsw-radius-lg);
color: var(--dsw-alias-label-primary);
background: var(--dsw-alias-bg-layer-1);
box-shadow: var(--dsw-elevation-panel);
pointer-events: auto;
animation: dsh-session-panel-enter 120ms ease-out;
}
/* Over the transcript the panel is narrower than docked, so it covers less of
the transcript, and takes the prominent elevation. */
.panel[data-session-panel='overlay'] {
width: min(280px, calc(100% - 2 * var(--panel-edge)));
box-shadow: var(--dsw-elevation-prominent);
}
/* The dock probe tells the plugin whether the gutter holds the docked panel
without a pixel measurement: it is 1px wide from the gutter that fits the
panel's minimum width and 0 below it, a width under 0 being used as 0. A
size observer on it therefore reports only when the docking decision
flips, not while the window resizes on one side of it or the transcript
grows. It has no height and takes no pointer events. */
.dockProbe {
position: absolute;
top: 0;
right: 0;
width: calc(var(--dsh-chat-aside-gutter, 0px) - var(--panel-clear) - var(--panel-edge) - var(--panel-min-width) + 1px);
max-width: 1px;
height: 0;
visibility: hidden;
pointer-events: none;
}
.section {
padding: 4px 0 6px;
}
/* An empty body hides its section: a plain section renders into one outlet
anchor, and a shared section renders its own row outlet inside it. */
.section:has(> .body > [data-slot]:empty),
.section:has(> .body > [data-slot] > [data-slot]:only-child:empty) {
display: none;
}
.section:not(:has(> .body > [data-slot]:empty), :has(> .body > [data-slot] > [data-slot]:only-child:empty))
~ .section:not(:has(> .body > [data-slot]:empty), :has(> .body > [data-slot] > [data-slot]:only-child:empty)) {
margin-top: 2px;
padding-top: 8px;
border-top: 0.5px solid var(--dsw-alias-border-l2);
}
.head {
display: flex;
align-items: center;
gap: 8px;
min-height: 24px;
padding: 0 6px;
}
/* Secondary ink at medium weight: apart from the primary rows below and the tertiary counts beside it. */
.title {
flex: 0 1 auto;
min-width: 0;
margin: 0;
overflow: hidden;
color: var(--dsw-alias-label-secondary);
font: var(--dsw-font-xxs-12);
font-weight: 500;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Takes what the title leaves and clips first, so long progress never squeezes the title. */
.actions {
display: inline-flex;
flex: 1 1000 0;
align-items: center;
justify-content: flex-end;
gap: 2px;
min-width: 0;
overflow: hidden;
}
.actions:has(> [data-slot]:empty) {
display: none;
}
@keyframes dsh-session-panel-enter {
from { opacity: 0; transform: translateY(-4px); }
to { opacity: 1; transform: translateY(0); }
}
@media (prefers-reduced-motion: reduce) {
.panel {
animation: none;
}
}
/* Rows. The rows of every section share one look without sharing a
component: each contributor writes its row's markup and marks the parts,
and these rules lay them out.
[data-session-panel-row] the row: one 28px line
[data-row-part='body'] the icon and the text; a <button> body is
the row's action, and its press area
covers the whole row
[data-row-part='icon'] a 16px glyph in the row ink
[data-row-part='content'] one line of text, clipped with an ellipsis
[data-row-part='trailing'] a value or control after the text
[data-row-part='menu'] row actions, such as a More button
The icon's center sits 14px from the row's start and the menu's 14px from
its end, the columns the other panel rows align to. A row with an action
or a menu highlights as a whole; the trailing part and the menu sit above
the action's press area. A menu part that renders nothing counts as
absent: it takes no room and does not make the row highlight. A rule for
a part has the specificity of one class, so a row's own class adjusts it. */
.panel :where([data-session-panel-row]) {
position: relative;
display: flex;
align-items: center;
gap: 8px;
box-sizing: border-box;
min-width: 0;
min-height: 28px;
padding: 0 6px;
border-radius: var(--dsw-radius-sm);
color: var(--dsw-alias-label-primary);
font: var(--dsw-font-xs-13);
}
.panel :where([data-session-panel-row] > [data-row-part='body']) {
display: flex;
flex: 1 1 auto;
align-items: center;
gap: 8px;
min-width: 0;
height: 28px;
}
.panel :where([data-session-panel-row] > button[data-row-part='body']) {
margin: 0;
padding: 0;
border: 0;
color: inherit;
background: transparent;
font: inherit;
text-align: start;
cursor: pointer;
}
.panel :where([data-session-panel-row] > button[data-row-part='body'])::after {
position: absolute;
inset: 0;
border-radius: inherit;
content: '';
}
.panel :where([data-session-panel-row] > button[data-row-part='body']:focus-visible) {
outline: none;
}
.panel :where([data-session-panel-row]:has(> button[data-row-part='body']:focus-visible)) {
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
outline-offset: -2px;
}
.panel :where([data-session-panel-row] [data-row-part='icon']) {
display: inline-flex;
flex: none;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
}
.panel :where([data-session-panel-row] [data-row-part='icon']) svg {
width: 16px;
height: 16px;
}
.panel :where([data-session-panel-row] [data-row-part='content']) {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.panel :where([data-session-panel-row] > [data-row-part='trailing'], [data-session-panel-row] > [data-row-part='menu']) {
position: relative;
z-index: 1;
display: inline-flex;
flex: none;
align-items: center;
gap: 4px;
}
.panel :where([data-session-panel-row] > [data-row-part='trailing']) {
color: var(--dsw-alias-label-tertiary);
}
/* A 16px column, so the action's 24px target reaches past it without moving the glyph. */
.panel :where([data-session-panel-row] > [data-row-part='menu']) {
justify-content: center;
width: 16px;
}
/* A shared menu button renders nothing while its target has no menu entries. */
.panel :where([data-session-panel-row] > [data-row-part='menu']:empty) {
display: none;
}
/* Row actions share the row's highlight: the glyph darkens on hover, without a fill. */
.panel :where([data-session-panel-row] > [data-row-part='menu']) button {
display: inline-flex;
flex: none;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
margin: -4px;
padding: 0;
border: 0;
border-radius: var(--dsw-radius-xs);
background: transparent;
color: var(--dsw-alias-label-tertiary);
cursor: pointer;
}
.panel :where([data-session-panel-row] > [data-row-part='menu']) button:focus-visible {
outline-offset: -2px;
}
@media (hover: hover) {
.panel :where([data-session-panel-row]:has(> button[data-row-part='body'], > [data-row-part='menu']:not(:empty)):hover) {
background: var(--dsw-alias-interactive-bg-hover);
}
.panel :where([data-session-panel-row] > [data-row-part='menu']) {
opacity: 0;
}
.panel :where([data-session-panel-row]:hover > [data-row-part='menu'], [data-session-panel-row]:focus-within > [data-row-part='menu']) {
opacity: 1;
}
.panel :where([data-session-panel-row] > [data-row-part='menu']) button:hover {
color: var(--dsw-alias-label-primary);
}
}
/* An open menu keeps its row highlighted and its trigger visible after the pointer leaves for the menu. */
.panel :where([data-session-panel-row]:has(> button[data-row-part='body'], > [data-row-part='menu']:not(:empty)):has([aria-expanded='true'])) {
background: var(--dsw-alias-interactive-bg-hover);
}
.panel :where([data-session-panel-row] > [data-row-part='menu']:has([aria-expanded='true'])) {
opacity: 1;
}
.panel :where([data-session-panel-row] > [data-row-part='menu']) button[aria-expanded='true'] {
color: var(--dsw-alias-label-primary);
}
.panel :where([data-session-panel-row]:has(> button[data-row-part='body']:active)) {
background: var(--dsw-alias-interactive-bg-active);
}
@@ -0,0 +1,137 @@
/** Floating Session panel in the Chat View's aside: section titles drawn from the section roster, bodies from the section slot. */
import { useCallback, useEffect, useId, useMemo, useRef, useState, type FocusEvent, type ReactNode } from 'react'
import { isBehindModal, observeComposition } from '@deepseek-ai/dsh-client-ui-primitives'
import { panelElementId, toggleElementId } from './element-ids.ts'
import type { SessionPanelProps, SessionPanelSectionOwnerProps } from './slots.ts'
import { presentationOf } from './visibility.ts'
import css from './SessionPanel.module.css'
/**
* Close the overlay on Escape and on a pointerdown outside the panel. The
* toggle and open menus, such as a row's context menu, count as inside; a
* modal above the page and an input method composing text keep Escape, as
* does a handler that already took it. Escape returns focus to the toggle
* when focus was inside the panel.
* @param panel - the overlay element.
* @param open - whether the overlay shows; false detaches the listeners.
* @param toggleId - id of the Session's toggle.
* @param close - closes the overlay.
*/
function useOverlayDismissal(panel: { readonly current: HTMLElement | null }, open: boolean, toggleId: string, close: () => void): void {
useEffect(() => {
if (!open) return
const composition = observeComposition(document)
const inside = (target: EventTarget | null): boolean => target instanceof Element && (
panel.current?.contains(target) === true
|| document.getElementById(toggleId)?.contains(target) === true
|| target.closest('[role="menu"]') !== null
)
const onPointerDown = (event: PointerEvent): void => {
if (!inside(event.target)) close()
}
const onKeyDown = (event: KeyboardEvent): void => {
if (event.key !== 'Escape' || composition.guards(event) || event.defaultPrevented || isBehindModal(panel.current)) return
event.preventDefault()
const focused = panel.current?.contains(document.activeElement) === true
close()
if (focused) document.getElementById(toggleId)?.focus()
}
document.addEventListener('pointerdown', onPointerDown)
document.addEventListener('keydown', onKeyDown)
return () => {
document.removeEventListener('pointerdown', onPointerDown)
document.removeEventListener('keydown', onKeyDown)
composition.dispose()
}
}, [panel, open, toggleId, close])
}
/**
* Hand focus to the toggle when the panel hides with the keyboard inside it,
* as when a narrower gutter hides the docked panel: the focused control is
* gone and the toggle is the control that brings it back.
* @param hidden - whether the panel renders nothing.
* @param toggleId - id of the Session's toggle.
* @returns focus handlers for the panel element.
*/
function useFocusReturn(hidden: boolean, toggleId: string): {
readonly onFocus: () => void
readonly onBlur: (event: FocusEvent<HTMLElement>) => void
} {
const inside = useRef(false)
useEffect(() => {
if (!hidden || !inside.current) return
inside.current = false
document.getElementById(toggleId)?.focus({ preventScroll: true })
}, [hidden, toggleId])
return useMemo(() => ({
onFocus: () => { inside.current = true },
onBlur: (event) => {
// Removal can report no next target; only a move to another element leaves the panel.
if (event.relatedTarget instanceof Element && !event.currentTarget.contains(event.relatedTarget)) inside.current = false
},
}), [])
}
/**
* Render the panel while it docks or shows as an overlay, and always its
* dock probe. Each section keeps its title row and body; CSS hides a section
* whose body rendered nothing. The overlay closes on Escape and on an
* outside pointerdown. CSS sizes the docked panel from the Chat View's end
* gutter and makes the probe 1px wide while that gutter holds the panel; the
* plugin observes the probe, so the panel renders again only when the
* docking decision flips.
* @param props - Session values, shared visibility, sections, the dock probes and their ref factory, and copy.
* @returns the dock probe and, unless hidden, the panel.
*/
export function SessionPanel({
sessionId, useVisibility, useSections, useProbes, createProbeRef, closeOverlay, renderSlot, t,
}: SessionPanelProps): ReactNode {
const probe = useId()
// One ref lifecycle for this mounted panel: the entry remounts with its Session, so the Session is fixed.
const [probeRef] = useState(() => createProbeRef(sessionId, probe))
const fits = useProbes(probes => probes.get(probe) === true)
const presentation = useVisibility(visibility => presentationOf(fits, visibility, sessionId))
const sections = useSections(entries => entries)
const panel = useRef<HTMLElement>(null)
const dismissOverlay = useCallback(() => { closeOverlay(sessionId) }, [closeOverlay, sessionId])
const owner = useMemo((): SessionPanelSectionOwnerProps | undefined => presentation === 'hidden'
? undefined
: { presentation, dismissOverlay },
[presentation, dismissOverlay])
useOverlayDismissal(panel, presentation === 'overlay', toggleElementId(sessionId), dismissOverlay)
const focus = useFocusReturn(owner === undefined, toggleElementId(sessionId))
return (
<>
<span ref={probeRef} className={css.dockProbe} data-session-panel-probe="" />
{owner !== undefined && (
<aside
id={panelElementId(sessionId)}
className={css.panel}
aria-label={t('panel.name')}
ref={panel}
onFocus={focus.onFocus}
onBlur={focus.onBlur}
data-session-panel={owner.presentation}
>
{sections.map((section) => {
const titleId = `${panelElementId(sessionId)}-${section.id}`
return (
<section key={section.id} className={css.section} aria-labelledby={titleId} data-session-panel-section={section.id}>
<div className={css.head}>
<h2 id={titleId} className={css.title}>{section.label}</h2>
<div className={css.actions}>
{renderSlot('conversation.session.panel.section.actions', {}, { entryKey: section.id })}
</div>
</div>
<div className={css.body}>
{renderSlot('conversation.session.panel.section', owner, { only: section.id })}
</div>
</section>
)
})}
</aside>
)}
</>
)
}
@@ -0,0 +1,60 @@
/* Icon-only header entry: the shared compact Button owns the radius, height,
and interaction fills, as for the header's other utilities. Indicators sit
at the glyph's top-right corner. */
.trigger {
position: relative;
flex: none;
width: 28px;
padding: 0;
color: var(--dsw-alias-label-secondary);
}
/* The panel shows; the expanded fill outranks the Button's hover fill. */
.trigger[aria-expanded='true'] {
color: var(--dsw-alias-label-primary);
background: var(--dsw-alias-interactive-bg-active);
}
@media (hover: hover) {
.trigger[aria-expanded='true']:hover:not(:disabled) {
color: var(--dsw-alias-label-primary);
background: var(--dsw-alias-interactive-bg-active);
}
.trigger[aria-disabled='true']:hover:not(:disabled) {
background: transparent;
}
}
/* No Chat View shows the Session: the toggle stays focusable for its tooltip. */
.trigger[aria-disabled='true'] {
cursor: default;
opacity: 0.4;
}
/* The name reaches assistive technology; the tooltip carries it visually. */
.name {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
/* The indicators' wrapper only gives the accessible name a reference; it lays out nothing. */
.indicators {
display: contents;
}
/* One 6px dot at the glyph's corner; the ring separates it from the glyph, and the occupant colors it. */
.indicators > :global([data-slot='conversation.session.panel.indicator']) > * {
position: absolute;
top: 5px;
right: 5px;
width: 6px;
height: 6px;
border-radius: 50%;
corner-shape: round;
box-shadow: 0 0 0 1.5px var(--dsw-alias-bg-base);
}
@@ -0,0 +1,49 @@
/** Session header entry that shows or hides the Session panel. */
import { useId, type ReactNode } from 'react'
import { Button, IconFlatListOutlineRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'
import { panelElementId, toggleElementId } from './element-ids.ts'
import type { SessionPanelToggleProps } from './slots.ts'
import { presentationOf } from './visibility.ts'
import css from './SessionPanelToggle.module.css'
/**
* Render the toggle. Its accessible name is the panel name followed by the
* text of any indicator; the expanded state says whether the panel shows.
* While no Chat View shows the Session, as in the trajectory View, the panel
* has no place to show: the toggle is unavailable and its tooltip says so.
* @param props - Session values, the room to dock, shared visibility, the toggle action, and copy.
* @returns the header entry.
*/
export function SessionPanelToggle({
sessionId, useDockable, useVisibility, toggle, renderSlot, t,
}: SessionPanelToggleProps): ReactNode {
const dockable = useDockable(entries => entries.get(sessionId))
const shown = useVisibility(visibility => presentationOf(dockable === true, visibility, sessionId) !== 'hidden')
const available = dockable !== undefined
const open = available && shown
const label = available ? t(open ? 'toggle.hide' : 'toggle.show') : t('toggle.unavailable')
const nameId = useId()
const indicatorsId = useId()
return (
<Tooltip label={label} side="bottom" delayMs={500}>
<Button
size="sm"
id={toggleElementId(sessionId)}
className={css.trigger}
aria-expanded={open}
aria-controls={open ? panelElementId(sessionId) : undefined}
aria-disabled={available ? undefined : true}
// The name and the indicators' text join with a space, as the referenced elements of a label do.
aria-labelledby={`${nameId} ${indicatorsId}`}
data-session-panel-toggle=""
onClick={() => { toggle(sessionId) }}
>
<IconFlatListOutlineRegular size={16} />
<span id={nameId} className={css.name}>{t('panel.name')}</span>
<span id={indicatorsId} className={css.indicators}>
{renderSlot('conversation.session.panel.indicator', { panelShown: open })}
</span>
</Button>
</Tooltip>
)
}
@@ -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}`
}
@@ -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<RemoteHostFacts> = {
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))
}
@@ -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<SessionPanelKey, string> = {
'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<keyof typeof en, string>
/** 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<keyof typeof en, string>
/** 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<keyof typeof en, string>
/** 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<keyof typeof en, string>
/** Russian dictionary. */
export const ru = {
'panel.name': 'Панель сеанса',
'toggle.show': 'Показать панель сеанса',
'toggle.hide': 'Скрыть панель сеанса',
'toggle.unavailable': 'Переключитесь на вид «Чат», чтобы показать панель сеанса',
'section.environment': 'Среда',
'project.label': 'Рабочая папка',
'project.actions': 'Действия с рабочей папкой',
} satisfies Record<keyof typeof en, string>
/** 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<keyof typeof en, string>
@@ -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<readonly SessionPanelSectionEntry[]> {
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()
}
},
}
}
@@ -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<SessionId, boolean>
/**
* 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<string, boolean>
/** 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<SessionPanelVisibility>
readonly dockable: ObservableSnapshot<SessionPanelDockable>
}
/**
* 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<SessionPanelVisibility>
readonly sections: ObservableSnapshot<readonly SessionPanelSectionEntry[]>
readonly probes: ObservableSnapshot<SessionPanelProbes>
}
/**
* 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<RemoteHostFacts> }
}
/** Full props of the header toggle. */
export type SessionPanelToggleProps =
PropsRuntime<'conversation.session.header.utilities'>
& PropsRenderSlots<'conversation.session.panel.indicator'>
& InjectFace<SessionPanelToggleInjected>
& PropsLocale<typeof NS>
/** Full props of the panel. */
export type SessionPanelProps =
PropsRuntime<'conversation.chat.aside'>
& PropsRenderSlots<'conversation.session.panel.section' | 'conversation.session.panel.section.actions'>
& InjectFace<SessionPanelInjected>
& PropsLocale<typeof NS>
/** 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<ProjectRowInjected>
& PropsLocale<typeof NS>
@@ -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<unknown>(true, { persist: { name: PINNED_STORAGE_KEY } })
private readonly overlay = createSnapshotStore<SessionId | null>(null)
private readonly room = createSnapshotStore<SessionPanelDockable>(NO_SESSIONS)
private readonly fits = createSnapshotStore<SessionPanelProbes>(NO_PROBES)
/** The Session of every attached probe. */
private readonly owners = new Map<string, SessionId>()
/** 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<SessionPanelVisibility> = {
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<SessionPanelDockable> = 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<SessionPanelProbes> = 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)
}
}
+4
View File
@@ -0,0 +1,4 @@
declare module '*.module.css' {
const classes: Record<string, string>
export default classes
}
@@ -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 {}
@@ -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()
})
})
@@ -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<T>(value: T) {
return <S,>(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(() => <span>需要处理</span>)
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(<SessionPanelToggle {...props} />)
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(<SessionPanelToggle {...wide.props} />)
fireEvent.click(screen.getByRole('button'))
expect(wide.toggle).toHaveBeenCalledWith(SID)
cleanup()
const narrow = toggleProps(false, DOCKED)
render(<SessionPanelToggle {...narrow.props} />)
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(<SessionPanelToggle {...props} />)
expect(screen.getByRole('button').getAttribute('aria-expanded')).toBe('true')
})
it('tells its indicators whether the panel shows', () => {
const { props, renderSlot } = toggleProps(false, DOCKED)
render(<SessionPanelToggle {...props} />)
expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.indicator', { panelShown: false })
})
it('shows its tooltip after 500ms of hover', () => {
const { props } = toggleProps(true, DOCKED)
render(<SessionPanelToggle {...props} />)
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(<SessionPanelToggle {...props} />)
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<string>()
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' ? <button type="button">刷新</button> : null
}
owners.push(owner as SessionPanelSectionOwnerProps)
return <p>{`${opts?.only ?? ''} body`}</p>
}) 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: <S,>(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(<SessionPanel {...props} />)
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(<SessionPanel {...next.props} />)
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(<SessionPanel {...props} />)
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(<SessionPanel {...props} />)
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(<SessionPanel {...props} />)
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(<SessionPanel {...props} />)
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(<SessionPanel {...props} />)
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(<SessionPanel {...props} />)
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(<SessionPanel {...docked.props} />)
fireEvent.keyDown(document, { key: 'Escape' })
fireEvent.pointerDown(document.body)
expect(docked.closeOverlay).not.toHaveBeenCalled()
cleanup()
const overlay = panelProps(false, { pinned: true, overlay: SID })
render(<SessionPanel {...overlay.props} />)
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<HTMLDivElement>(null)
useModalLayer(dialog, true, () => {})
return <div ref={dialog} role="dialog" aria-modal="true" />
}
const modal = render(<Modal />)
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(<SessionPanel {...props} />)
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(<SessionPanel {...docked.props} />)
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(<SessionPanel {...panelProps(false, DOCKED).props} />)
expect(document.activeElement).toBe(toggle)
// Focus that already left the panel stays where it went.
view.rerender(<SessionPanel {...docked.props} />)
screen.getByRole('button', { name: '刷新' }).focus()
outside.focus()
view.rerender(<SessionPanel {...panelProps(false, DOCKED).props} />)
expect(document.activeElement).toBe(outside)
// A panel that hides without having held focus moves nothing.
view.rerender(<SessionPanel {...docked.props} />)
view.rerender(<SessionPanel {...panelProps(false, DOCKED).props} />)
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(() => <span>row</span>)
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 }) => <button type="button">{input.label}</button>)
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(<ProjectRow {...props} />)
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(<ProjectRow {...rowProps({ cwd: '/srv/app' }).props} />)
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(<ProjectRow {...props} />)
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(<ProjectRow {...rowProps({ workingDirectory: null, workspacePath: '/srv' }).props} />)
expect(folderOf(atRoot.container)).toEqual({ name: 'srv', parent: '/' })
atRoot.unmount()
const atHome = render(<ProjectRow {...rowProps({ workingDirectory: '/Users/me', home: '/Users/me' }).props} />)
expect(folderOf(atHome.container)).toEqual({ name: '~', parent: null })
})
it('renders nothing before the Session directory is known', () => {
const { props } = rowProps({})
const view = render(<ProjectRow {...props} />)
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())
})
})
@@ -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')
})
})
@@ -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<string, string> {
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(<row selector>)<tail>`. */
const row = (inner: string, tail = ''): Record<string, string> => 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')
})
})
@@ -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<Element, Observation>()
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)
})
})
@@ -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"
}
]
}
@@ -0,0 +1,3 @@
import { clientBundle } from '../tsdown.client.ts'
export default clientBundle(import.meta.dirname, ['lib/types/index.js'])
@@ -216,6 +216,47 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.approval.detail\', () => ctx.slots.register(\n { name: \'conversation.approval.detail\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-approval/src/client/contract/slots.ts:47',
},
{
key: 'conversation.chat.aside',
kind: 'single',
scope: 'session',
summary: 'One Session-level occupant beside the transcript, such as a summary panel.',
doc: 'One Session-level occupant beside the transcript, such as a summary\npanel. Every Chat View occurrence renders it in a zero-height layer at\nthe top of the Chat frame, which stays in place while the transcript\nscrolls and inherits the shared scrollport\'s composer and viewport\nheights. The layer passes pointer events through; the occupant\npositions itself in it, enables its own pointer events, and keeps\nwithin the end gutter to stay clear of the transcript column. The\nlayer publishes that gutter, the inline space between the transcript\ncolumn and the frame\'s end edge, as the `--dsh-chat-aside-gutter`\ncustom property; its percentage resolves in the inline sizes of an\nelement whose containing block is the layer.',
registerOptions: [],
ownerProps: [],
ownerPropsReferences: [],
standardProps: [
'useRemoteAccess: (action: RemoteEndpoint) => boolean',
'useResource: UseResource',
'useContextMenu: UseContextMenu',
'useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>',
'usePanelInfo: UsePanelInfo',
'useSessionStatus: UseSessionStatus',
'useSessions: UseSessions',
'useSessionRetainInfo: UseSessionRetainInfo',
'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean',
'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean',
'useChat: UseChat',
'useConversation: UseConversation',
'useInput: SnapshotSelectorHook<InputState>',
'inputActions: InputActions',
'useSession: SessionSnapshotSelector',
'sessionId: SessionId',
'useProjection: UseProjection',
'useAccess: (action: RemoteEndpoint) => boolean',
'useTrajectory: UseTrajectory',
],
keyDomain: '',
hookContext: '',
slotInject: '',
declaredBy: 'an entry in \'conversation.view\' (client-ui-chat), so it exists while that entry is mounted',
occupants: [
'client-ui-session-panel SessionPanel',
],
replaceRisk: 'shadows-shipped-ui',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.aside\', () => ctx.slots.register(\n { name: \'conversation.chat.aside\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:447',
},
{
key: 'conversation.chat.assistant-actions',
kind: 'list',
@@ -278,7 +319,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.assistant-actions\', () => ctx.slots.register(\n { name: \'conversation.chat.assistant-actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:498',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:512',
},
{
key: 'conversation.chat.commandview',
@@ -332,7 +373,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'shadows-shipped-ui',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.commandview\', () => ctx.slots.register(\n { name: \'conversation.chat.commandview\', key: \'<one key the owner dispatches>\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:480',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:494',
},
{
key: 'conversation.chat.flow',
@@ -379,7 +420,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'shadows-shipped-ui',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.flow\', () => ctx.slots.register(\n { name: \'conversation.chat.flow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:436',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:450',
},
{
key: 'conversation.chat.markdown.fence',
@@ -492,7 +533,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'shadows-shipped-ui',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.message.images\', () => ctx.slots.register(\n { name: \'conversation.chat.message.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:472',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:486',
},
{
key: 'conversation.chat.node',
@@ -565,7 +606,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'shadows-shipped-ui',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.node\', () => ctx.slots.register(\n { name: \'conversation.chat.node\', key: \'<one key the owner dispatches>\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:448',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:462',
},
{
key: 'conversation.chat.reasoning.body',
@@ -609,7 +650,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'shadows-shipped-ui',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.reasoning.body\', () => ctx.slots.register(\n { name: \'conversation.chat.reasoning.body\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:486',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:500',
},
{
key: 'conversation.chat.text-interaction',
@@ -728,7 +769,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.turnTail\', () => ctx.slots.register(\n { name: \'conversation.chat.turnTail\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:492',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:506',
},
{
key: 'conversation.chat.user.before',
@@ -778,7 +819,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.user.before\', () => ctx.slots.register(\n { name: \'conversation.chat.user.before\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:462',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:476',
},
{
key: 'conversation.chat.user.images',
@@ -825,7 +866,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'shadows-shipped-ui',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.user.images\', () => ctx.slots.register(\n { name: \'conversation.chat.user.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:474',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:488',
},
{
key: 'conversation.composer',
@@ -2359,6 +2400,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
declaredBy: 'an entry in \'conversation.session.header\' (client-ui-conversation), so it exists while that entry is mounted',
occupants: [
'client-ui-schedule ScheduleCatalogAction id \'schedule-catalog\'',
'client-ui-session-panel SessionPanelToggle id \'session-panel\'',
'experimental-client-ui-forge HeaderButton id \'forge-panel\'',
'experimental-liveshare LiveshareShareAction id \'liveshare-share\'',
],
@@ -2421,6 +2463,236 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.views.actions\', () => ctx.slots.register(\n { name: \'conversation.session.header.views.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-conversation/src/client/contract/slots.ts:283',
},
{
key: 'conversation.session.panel.environment.row',
kind: 'list',
scope: 'session',
summary: 'Rows of the built-in Environment section in ascending `order`.',
doc: 'Rows of the built-in Environment section in ascending `order`.',
registerOptions: [
{
name: 'id',
requirement: 'required',
type: 'string',
doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.',
},
{
name: 'order',
requirement: 'optional',
type: 'number',
doc: 'Position among the entries, ascending (default 0).',
},
{
name: 'label',
requirement: 'optional',
type: 'string | (() => string)',
doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.',
},
],
ownerProps: [],
ownerPropsReferences: [],
standardProps: [
'useRemoteAccess: (action: RemoteEndpoint) => boolean',
'useResource: UseResource',
'useContextMenu: UseContextMenu',
'useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>',
'usePanelInfo: UsePanelInfo',
'useSessionStatus: UseSessionStatus',
'useSessions: UseSessions',
'useSessionRetainInfo: UseSessionRetainInfo',
'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean',
'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean',
'useChat: UseChat',
'useConversation: UseConversation',
'useInput: SnapshotSelectorHook<InputState>',
'inputActions: InputActions',
'useSession: SessionSnapshotSelector',
'sessionId: SessionId',
'useProjection: UseProjection',
'useAccess: (action: RemoteEndpoint) => boolean',
'useTrajectory: UseTrajectory',
],
keyDomain: '',
hookContext: '',
slotInject: '',
declaredBy: 'an entry in \'conversation.session.panel.section\' (client-ui-session-panel), so it exists while that entry is mounted',
occupants: [
'client-ui-session-panel ProjectRow id \'project\'',
],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.panel.environment.row\', () => ctx.slots.register(\n { name: \'conversation.session.panel.environment.row\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-session-panel/src/client/slots.ts:44',
},
{
key: 'conversation.session.panel.indicator',
kind: 'list',
scope: 'session',
summary: 'Marks over the panel toggle, such as an attention dot.',
doc: 'Marks over the panel toggle, such as an attention dot. Each occupant is\none element: the toggle sizes it to a 6px dot at the glyph\'s corner, and\nthe occupant sets its `background` and includes text that names it for\nassistive technology, which becomes part of the toggle\'s name. Occupants\noverlap, and a higher `order` paints above a lower one. An occupant that\nonly repeats what the panel shows renders nothing while `panelShown`.',
registerOptions: [
{
name: 'id',
requirement: 'required',
type: 'string',
doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.',
},
{
name: 'order',
requirement: 'optional',
type: 'number',
doc: 'Position among the entries, ascending (default 0).',
},
{
name: 'label',
requirement: 'optional',
type: 'string | (() => string)',
doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.',
},
],
ownerProps: [
'/** Values every toggle indicator receives from the toggle. */\nexport interface SessionPanelIndicatorOwnerProps {\n /** Whether the panel shows, docked or as an overlay. */\n readonly panelShown: boolean\n}',
],
ownerPropsReferences: [],
standardProps: [
'useRemoteAccess: (action: RemoteEndpoint) => boolean',
'useResource: UseResource',
'useContextMenu: UseContextMenu',
'useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>',
'usePanelInfo: UsePanelInfo',
'useSessionStatus: UseSessionStatus',
'useSessions: UseSessions',
'useSessionRetainInfo: UseSessionRetainInfo',
'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean',
'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean',
'useChat: UseChat',
'useConversation: UseConversation',
'useInput: SnapshotSelectorHook<InputState>',
'inputActions: InputActions',
'useSession: SessionSnapshotSelector',
'sessionId: SessionId',
'useProjection: UseProjection',
'useAccess: (action: RemoteEndpoint) => boolean',
'useTrajectory: UseTrajectory',
],
keyDomain: '',
hookContext: '',
slotInject: '',
declaredBy: 'an entry in \'conversation.session.header.utilities\' (client-ui-session-panel), so it exists while that entry is mounted',
occupants: [],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.panel.indicator\', () => ctx.slots.register(\n { name: \'conversation.session.panel.indicator\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-session-panel/src/client/slots.ts:37',
},
{
key: 'conversation.session.panel.section',
kind: 'list',
scope: 'session',
summary: 'Sections of the Session panel.',
doc: 'Sections of the Session panel. `id` addresses the section, `order` sorts\nthe sections ascending, and the required `label` is the section title,\nwhich the panel draws. A section with nothing to show renders nothing,\nand the panel hides its title with it.',
registerOptions: [
{
name: 'id',
requirement: 'required',
type: 'string',
doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.',
},
{
name: 'order',
requirement: 'optional',
type: 'number',
doc: 'Position among the entries, ascending (default 0).',
},
{
name: 'label',
requirement: 'optional',
type: 'string | (() => string)',
doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.',
},
],
ownerProps: [
'/** Values every section receives from the panel. */\nexport interface SessionPanelSectionOwnerProps {\n /** Current presentation; sections may lower their density in the overlay. */\n readonly presentation: SessionPanelPresentation\n /** Close the overlay, for example after a row opened another surface; no effect while docked. */\n readonly dismissOverlay: () => void\n}',
],
ownerPropsReferences: [
'SessionPanelPresentation',
],
standardProps: [
'useRemoteAccess: (action: RemoteEndpoint) => boolean',
'useResource: UseResource',
'useContextMenu: UseContextMenu',
'useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>',
'usePanelInfo: UsePanelInfo',
'useSessionStatus: UseSessionStatus',
'useSessions: UseSessions',
'useSessionRetainInfo: UseSessionRetainInfo',
'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean',
'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean',
'useChat: UseChat',
'useConversation: UseConversation',
'useInput: SnapshotSelectorHook<InputState>',
'inputActions: InputActions',
'useSession: SessionSnapshotSelector',
'sessionId: SessionId',
'useProjection: UseProjection',
'useAccess: (action: RemoteEndpoint) => boolean',
'useTrajectory: UseTrajectory',
],
keyDomain: '',
hookContext: '',
slotInject: '',
declaredBy: 'an entry in \'conversation.chat.aside\' (client-ui-session-panel), so it exists while that entry is mounted',
occupants: [
'client-ui-session-panel EnvironmentSection id \'environment\'',
],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.panel.section\', () => ctx.slots.register(\n { name: \'conversation.session.panel.section\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-session-panel/src/client/slots.ts:22',
},
{
key: 'conversation.session.panel.section.actions',
kind: 'keyed',
scope: 'session',
summary: 'Trailing controls of one section title, keyed by the section\'s `id`.',
doc: 'Trailing controls of one section title, keyed by the section\'s `id`.',
registerOptions: [
{
name: 'key',
requirement: 'required',
type: 'string',
doc: 'Your cell key: the entry renders where the owner dispatches this exact key. Registering an already-occupied key replaces that occupant.',
},
],
ownerProps: [],
ownerPropsReferences: [],
standardProps: [
'useRemoteAccess: (action: RemoteEndpoint) => boolean',
'useResource: UseResource',
'useContextMenu: UseContextMenu',
'useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>',
'usePanelInfo: UsePanelInfo',
'useSessionStatus: UseSessionStatus',
'useSessions: UseSessions',
'useSessionRetainInfo: UseSessionRetainInfo',
'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean',
'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean',
'useChat: UseChat',
'useConversation: UseConversation',
'useInput: SnapshotSelectorHook<InputState>',
'inputActions: InputActions',
'useSession: SessionSnapshotSelector',
'sessionId: SessionId',
'useProjection: UseProjection',
'useAccess: (action: RemoteEndpoint) => boolean',
'useTrajectory: UseTrajectory',
],
keyDomain: 'open: any string the owner dispatches (no compile-time key set), none are taken yet',
hookContext: '',
slotInject: '',
declaredBy: 'an entry in \'conversation.chat.aside\' (client-ui-session-panel), so it exists while that entry is mounted',
occupants: [],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.panel.section.actions\', () => ctx.slots.register(\n { name: \'conversation.session.panel.section.actions\', key: \'<one key the owner dispatches>\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-session-panel/src/client/slots.ts:28',
},
{
key: 'conversation.trajectory.images',
kind: 'single',
@@ -4422,7 +4694,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'shell.quota-notice\', () => ctx.slots.register(\n { name: \'shell.quota-notice\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:506',
source: 'packages/client/ui-chat/src/client/contract/slots.ts:520',
},
{
key: 'sidebar',
@@ -100,6 +100,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo
| `@deepseek-ai/dsh-client-ui-schedule` | no | Host task management page and Session reminder catalog |
| `@deepseek-ai/dsh-client-ui-secret-mask` | no | Web display masking for recognized credentials in sent user text |
| `@deepseek-ai/dsh-client-ui-session` | no | Session Controller adapter for React and session-scoped slots |
| `@deepseek-ai/dsh-client-ui-session-panel` | no | Floating Session panel opened from the Session header, composed of sections that plugins register |
| `@deepseek-ai/dsh-client-ui-session-status` | no | Client Session status table over Host reading records: running state, the effective pending interaction, and read or unread reminders shared by clients of one Host |
| `@deepseek-ai/dsh-client-ui-settings` | no | Settings domain base plugin: shared configuration forms and the canonical settings slot-type contract |
| `@deepseek-ai/dsh-client-ui-settings-account` | yes | Manage DeepSeek login and open Platform billing pages |
@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 87d7d2dbd7777429
/deepseek-ai-dsh-working-directory/use-this-package:
en: e65405026debde7c
zh: e12a648eb10ed16b
en: 4bb4eccf3b4b5f2f
zh: 41aae306e7fc82cf
/deepseek-ai-dsh-working-directory/understand-the-implementation:
en: 82d7372a58bb75c5
zh: e18ee833daa99581
@@ -33,6 +33,8 @@ Mount alongside `fs`, `sessionProjections`, and `systemPrompt`. `defaultDirector
-----
Client programs that read the `workingDirectory` projection import its type declarations from `@deepseek-ai/dsh-working-directory/types`, which loads no runtime code.
Directory validation and publication delegate through `working-directory/access`, so the owner of a directory being removed can hold `ensure` and `set` into that directory until its operation settles. A listener waits only for an operation on the requested or current path, honours the request's `signal` while waiting, and otherwise calls `next()` at once; a rejection fails that access and leaves the recorded directory unchanged, with no fallback. Existing subprocesses keep their own directories.
<a id="understand-the-implementation"></a>
@@ -33,6 +33,8 @@ kind: "package-reference"
-----
读取 `workingDirectory` 投影的 Client 程序从 `@deepseek-ai/dsh-working-directory/types` 导入其类型声明,该入口不加载运行时代码。
目录验证与发布通过 `working-directory/access` 委派,使正在删除某目录的所有者可以阻塞进入该目录的 `ensure` 与 `set`,直到其操作结束。监听器只为请求路径或当前路径上的操作等待,等待时遵守请求的 `signal`,其余情况立即调用 `next()`;拒绝会使本次访问失败并保持记录的目录不变,不做回退。已有子进程保留各自的目录。
<a id="understand-the-implementation"></a>
@@ -18,6 +18,10 @@
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
},
"./types": {
"types": "./lib/types/types.d.ts",
"default": "./lib/types/types.js"
},
"./src/*": "./src/*",
"./locale/*.json": "./locale/*.json",
"./package.json": "./package.json"
@@ -25,6 +29,7 @@
"files": [
"locale/*.json",
"lib/index.js",
"lib/types/**/*.js",
"lib/types/**/*.d.ts",
"lib/types/**/*.d.ts.map",
"lib/**/*.js.map",
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff. Show more