Merge remote-tracking branch 'origin/master' into refactor/llm-route-credential

This commit is contained in:
LegGasai committed 2026-11-16 15:17:39 +08:00
commit a1c0299977
256 files changed
+10159 -8527

No files matched your search

@@ -9,11 +9,11 @@
en: c389c332bdadbbe4
zh: 217520278ccf0932
/agent-note-unambiguous-tool-argument-compatibility/decision:
en: 71c04efcfd972b02
zh: d1f842920b1b0e3f
en: c6ac657b3875c95f
zh: 7b0a4cca7baafd03
/agent-note-unambiguous-tool-argument-compatibility/alternatives-considered:
en: b2a96695819a978f
zh: c6f84b244be0dddf
/agent-note-unambiguous-tool-argument-compatibility/consequences:
en: bd24ad737c617c90
zh: dbb7fa67c41af828
en: 7d21da549466232c
zh: a373e135f79c5423
@@ -10,7 +10,7 @@ Models can populate optional fields that do not affect the requested operation.
## Decision
`grep` treats an exact empty `include` as omitted. Whitespace-only, negated, and comma-separated filters remain invalid. `update_goal` uses replacement fields only for `edit` and a blocker reason only for `blocked`; other actions ignore those known fields. Declared types, consumed values, authority, and exact revisions remain validated. Ignored fields never reach another goal operation or change unrelated state, and call summaries select only values used by the action. `write` and `edit` allow absent or blank justification when no sandbox mode is requested or the effective mode is repeated; actual widening retains its reason and approval requirements, and filesystem observation and denial checks remain active.
`grep` treats an exact empty `include` as omitted. Whitespace-only, negated, and comma-separated filters remain invalid. `update_goal` uses replacement fields only for `edit` and a blocker reason only for `blocked`; other actions ignore those known fields. Declared types, consumed values, authority, and exact revisions remain validated. Ignored fields never reach another goal operation or change unrelated state, and call summaries select only values used by the action. `write` and `edit` allow absent or blank justification when no sandbox mode is requested or the effective mode is repeated; actual widening retains its reason and approval requirements, and filesystem observation and denial checks remain active. `subagent` and `list_subagent_models` treat an exact empty `provider`, `model`, or `reasoning_effort` as omitted; an empty subagent `name` remains invalid because its error states the accepted format.
This partially supersedes the unused-field rejection in the [goal-tool decision](../feature/2026-07-19-model-facing-goal-tools.md). Its authority, lifecycle, scheduling, and persistence decisions remain active. The rules apply to every provider and stay inside the owning tool rather than weakening its underlying service.
@@ -22,4 +22,4 @@ This partially supersedes the unused-field rejection in the [goal-tool decision]
## Consequences
The tools accept these calls without extra mutations. Unit tests cover ignored fields for every goal action, consumed-field and authority failures, stale revisions, filter validation, and real search results. A headless recorded-session scenario verifies both file extensions are searched and completion preserves the original objective and round cap. These rules give up detecting conflicting intent expressed only in inactive goal fields; they do not weaken authorization or establish a generic coercion policy.
The tools accept these calls without extra mutations. Unit tests cover ignored fields for every goal action, consumed-field and authority failures, stale revisions, filter validation, and real search results. A headless recorded-session scenario verifies both file extensions are searched and completion preserves the original objective and round cap. An SDK recorded-session scenario verifies that empty route fields start a subagent on its default route. These rules give up detecting conflicting intent expressed only in inactive goal fields; they do not weaken authorization or establish a generic coercion policy.
@@ -10,7 +10,7 @@ Status: implemented
## 决策
`grep` 将值恰好为空字符串的 `include` 视为省略。仅含空白、否定形式和逗号分隔的过滤器仍然无效。`update_goal` 仅在 `edit` 时使用替换字段,仅在 `blocked` 时使用阻塞原因;其他 action 忽略这些已知字段。声明的类型、实际使用的值、权限和精确修订号仍会校验。被忽略的字段不会传入另一种目标操作,也不会改变无关状态;调用摘要仅选择当前 action 使用的值。未请求沙箱模式或重复当前生效模式时,`write` 和 `edit` 允许省略理由或提供空白理由;真正升权仍需理由和审批,文件系统观察与拒绝检查继续生效。
`grep` 将值恰好为空字符串的 `include` 视为省略。仅含空白、否定形式和逗号分隔的过滤器仍然无效。`update_goal` 仅在 `edit` 时使用替换字段,仅在 `blocked` 时使用阻塞原因;其他 action 忽略这些已知字段。声明的类型、实际使用的值、权限和精确修订号仍会校验。被忽略的字段不会传入另一种目标操作,也不会改变无关状态;调用摘要仅选择当前 action 使用的值。未请求沙箱模式或重复当前生效模式时,`write` 和 `edit` 允许省略理由或提供空白理由;真正升权仍需理由和审批,文件系统观察与拒绝检查继续生效。`subagent` 和 `list_subagent_models` 将值恰好为空字符串的 `provider`、`model` 或 `reasoning_effort` 视为省略;空的 subagent `name` 仍然无效,因为其报错会说明可接受的格式。
本决策部分取代[目标工具决策](../feature/2026-07-19-model-facing-goal-tools.zh.md)中对无关字段的拒绝规则。其权限、生命周期、调度和持久化决策继续生效。这些规则适用于所有提供方,并保留在所属工具内,不削弱底层服务的校验。
@@ -22,4 +22,4 @@ Status: implemented
## 后果
工具接受这些调用,且不会产生额外变更。单元测试覆盖每种目标 action 对无关字段的忽略、有效字段与权限失败、陈旧修订号、过滤器校验以及真实搜索结果。headless 会话回放验证两种扩展名的文件都参与搜索,并且完成操作保留原始目标和轮数上限。这些规则放弃检测仅由非当前 action 的目标字段表达的冲突意图;它们不削弱授权,也不建立通用类型转换策略。
工具接受这些调用,且不会产生额外变更。单元测试覆盖每种目标 action 对无关字段的忽略、有效字段与权限失败、陈旧修订号、过滤器校验以及真实搜索结果。headless 会话回放验证两种扩展名的文件都参与搜索,并且完成操作保留原始目标和轮数上限。SDK 会话回放验证空路由字段会让 subagent 按默认路由启动。这些规则放弃检测仅由非当前 action 的目标字段表达的冲突意图;它们不削弱授权,也不建立通用类型转换策略。
@@ -9,8 +9,8 @@
en: 344bcc7e9825bbc8
zh: c1d0f4b54f5b3786
/agent-note-change-request-panel-and-worktree-sessions/decision:
en: 4695a1e4f8aa7a25
zh: e17be0e36ea3eaa3
en: a2da424833a8aa0a
zh: 9ab23d2e5bde31de
/agent-note-change-request-panel-and-worktree-sessions/deferred:
en: 32ef8af85f4d2f66
zh: b82b67f94346399e
@@ -10,7 +10,7 @@ English | [中文](2026-10-09-forge-panel.zh.md)
## Decision
[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.md) is a two-face package. Its Host half, the `forgePanel` Remote, assembles everything the panel shows for one Session into one streamed state; the forge registry and the binding service keep only their domain operations. Its Client half is a right-sidebar tab, a Session header button that shows or hides it, a New Session option, a creation card above the composer, a toast, and the [Session list icons and hover card section](2026-10-20-forge-session-list.md). Every surface calls a bound item a change request, the forge registry's term, whatever its code host calls it. The [forge bundle](../../../../packages/experimental/forge-bundle/README.md) ships the panel, the forge registry, the GitHub provider, the bindings, the worktree model tool, and an isolated worktree service for the panel as one default-disabled Plugins page entry.
[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.md) is a two-face package. Its Host half, the `forgePanel` Remote, assembles everything the panel shows for one Session into one streamed state; the forge registry and the binding service keep only their domain operations. Its Client half is a Change requests section, checkout and local changes rows, and an attention mark in the [Session panel](2026-11-05-session-panel.md), a changes view, a New Session option, a creation card above the composer, a toast, and the [Session list icons and hover card section](2026-10-20-forge-session-list.md). Every surface calls a bound item a change request, the forge registry's term, whatever its code host calls it. The [forge bundle](../../../../packages/experimental/forge-bundle/README.md) ships the panel, the forge registry, the GitHub provider, the bindings, the worktree model tool, and an isolated worktree service for the panel as one default-disabled Plugins page entry.
Review and worktree controls serve one code-change workflow. One Plugins entry lets users enable that workflow without having to distinguish the underlying package split. Packages and the two worktree services remain independent so each owns its before-Session or in-conversation creation flow.
@@ -10,7 +10,7 @@ Status: implemented
## Decision
[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.zh.md) 是一个双端包。宿主端的 `forgePanel` Remote 把面板为一个 Session 展示的全部内容组装成一条流式状态;forge 注册表与绑定服务只保留各自的领域操作。客户端包括一个右侧边栏标签页、一个显示或隐藏它的 Session 标题栏按钮、一个新会话选项、一张位于输入框上方的创建卡片、一个 toast,以及[会话列表中的图标与悬浮卡片部分](2026-10-20-forge-session-list.zh.md)。所有界面都把已绑定的条目称为变更请求(forge 注册表的术语),不随代码托管平台的叫法变化。[forge 套件](../../../../packages/experimental/forge-bundle/README.zh.md)把面板、forge 注册表、GitHub 提供方、绑定服务、工作树模型工具与面板使用的一个隔离 worktree 服务作为插件页中默认禁用的一个条目发布。
[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.zh.md) 是一个双端包。宿主端的 `forgePanel` Remote 把面板为一个 Session 展示的全部内容组装成一条流式状态;forge 注册表与绑定服务只保留各自的领域操作。客户端包括[会话面板](2026-11-05-session-panel.zh.md)中的“变更请求”分栏、检出行与本地变更行和提醒标记,以及一个变更视图、一个新会话选项、一张位于输入框上方的创建卡片、一个 toast,以及[会话列表中的图标与悬浮卡片部分](2026-10-20-forge-session-list.zh.md)。所有界面都把已绑定的条目称为变更请求(forge 注册表的术语),不随代码托管平台的叫法变化。[forge 套件](../../../../packages/experimental/forge-bundle/README.zh.md)把面板、forge 注册表、GitHub 提供方、绑定服务、工作树模型工具与面板使用的一个隔离 worktree 服务作为插件页中默认禁用的一个条目发布。
评审与工作树控件服务于同一个代码修改流程。统一插件入口让用户可以一次启用这些能力,无需根据底层包的拆分判断应该开启哪张卡片。包与两套工作树服务仍保持独立,分别负责会话开始前和对话中创建工作树的流程。
@@ -15,8 +15,8 @@
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
en: 783b146c3396bebb
zh: 0f71205fdb744961
/agent-note-session-panel-in-the-chat-view-s-end-gutter/decision/the-turn-rail-sits-at-the-start-edge:
en: 08e720a4ea75d4d6
zh: 5e2e5b8452f67d36
@@ -24,5 +24,5 @@
en: 6adaf7a36da05668
zh: c0ace7297995d764
/agent-note-session-panel-in-the-chat-view-s-end-gutter/consequences:
en: 6c2f625c9c36ebd0
zh: 0060e818dbf233ce
en: 0b6e547a08c042bc
zh: 154a69e3f54692cd
@@ -26,6 +26,8 @@ Each section is one list registration with `id`, `order`, and a required `label`
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.
A section's list shows five rows of each group and then a fold control, because a Session with many subagents, shared tasks, or background jobs would otherwise push the later sections out of the panel's height. Each list orders its rows so that the ones it holds back are the least current: running rows first and then the most recent ones, or for shared tasks, which carry no times, the unfinished tasks before the completed ones. The fold control is the one row the panel does offer as a Component Factory, `conversation.session.panel.fold`: it is the same in every section and takes only data and a callback, while each section keeps its fold state and decides which rows show.
### 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.
@@ -47,3 +49,4 @@ The turn rail sits at the scrollport's start edge with its marks, focus ring, an
- `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.
- Change requests, background jobs, and subagents became sections, replacing the change requests sidebar tab, its start-page entry, and the header controls of jobs and subagents; the header keeps the subagent breadcrumb switcher for child Sessions. A section mounts only while the panel shows, so state that must outlast hiding the panel, such as cleared job rows, lives in a per-Session slot store.
@@ -26,6 +26,8 @@ Status: implemented
各贡献方的行通过面板的样式表共享同一外观,而不是共享组件:各贡献方自己写行的标记并标出各个部分,由面板统一排版,使不同包的图标、文字与尾部区域对齐。共享的行组件要把各贡献方的图标、文字和控件作为 React 节点从 props 传入,这是客户端规则禁止的;功能包之间也不能共享各自的行组件。
分栏的列表每个分组只显示五行,然后是一个收起控件;否则子智能体、共享任务或后台任务很多的会话会把后面的分栏挤出面板的高度。每个列表按顺序排列,使被收起的是最不需要看的行:运行中的在前,然后是最近的;共享任务没有时间信息,则未完成的排在已完成的前面。收起控件是面板唯一以 Component Factory 提供的行,即 `conversation.session.panel.fold`:它在每个分栏里都一样,只接收数据和一个回调,而收起状态和显示哪些行由各分栏自己决定。
### 轮次轨道位于起始边
轮次轨道连同刻度、焦点环和预览位于滚动容器的起始边,末端留白留给停靠面板;它的 900px 隐藏规则保证旁边有足够空间容纳起始侧的宽度拖拽条。
@@ -47,3 +49,4 @@ Status: implemented
- `ui-chat` 多了一个 slot,侧边层多了一个自定义属性,但不为它们观察任何尺寸。每个已挂载的面板在停靠探针上多一个 `ResizeObserver`,只在停靠判断翻转时回调。`ui-conversation` 把默认正文宽度上限定为 880px。
- 面板只出现在 Chat 视图中;其他视图下开关仍在标题栏中,但不可用。每个 Chat 视图实例都会渲染侧边层,因此同一会话同时显示在主正文区和嵌入的对话中时,两处都会显示浮层。
- 轮次轨道的位置对所有用户都变了;行为和隐藏规则不变。
- 变更请求、后台任务和子智能体成为分栏,取代变更请求侧边栏标签页、其起始页入口,以及标题栏中的后台任务和子智能体控件;标题栏仍为子会话保留子智能体面包屑切换器。分栏只在面板显示时挂载,因此需要在隐藏面板后保留的状态(例如已清空的任务行)放在按会话划分的 slot store 中。
+4 -3
View File
@@ -428,9 +428,10 @@ describe('web e2e: agent-preset selection', () => {
await compareOrRefreshGolden(HEADER_EXPECTED, snapshot, MODE)
expect(snapshot).toContain('Minimal mode')
expect(snapshot).toContain('button "1 subagent"')
expect(snapshot.indexOf('Minimal mode')).toBeLessThan(snapshot.indexOf('button "1 subagent"'))
expect(snapshot.indexOf('button "1 subagent"')).toBeLessThan(snapshot.indexOf('button "More actions"'))
// The Session's subagents live in the Session panel, whose toggle follows the preset label.
expect(snapshot).not.toContain('button "1 subagent"')
expect(snapshot.indexOf('Minimal mode')).toBeLessThan(snapshot.indexOf('button "Session panel"'))
expect(snapshot.indexOf('button "Session panel"')).toBeLessThan(snapshot.indexOf('button "More actions"'))
// Static chrome, not a control: the header can only report a composition
// the host would refuse to change.
expect(snapshot).not.toContain('button "Minimal mode"')
+243 -278
View File
@@ -2,7 +2,8 @@
// over the real Host projection frame flow.
import { fileURLToPath } from 'node:url'
import { join } from 'node:path'
import type { Browser, Page } from 'playwright'
import { homedir } from 'node:os'
import type { Browser, Locator, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished, vi } from 'vitest'
import type {} from '@deepseek-ai/dsh-agent-team'
@@ -10,16 +11,22 @@ import type { SessionId } from '@deepseek-ai/dsh-session'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { CommandId } from '@deepseek-ai/dsh-commands/types'
import { createMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
import { abbreviateHomePath } from '@deepseek-ai/dsh-util-workspace-path'
import {
acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { assertWarningDialogLayout, connectFreshWorkspace, connectFreshWorkspaceZh, newEnglishPage, saveFailureShot, writeComposerDraft } from './support.ts'
import {
assertWarningDialogLayout, connectFreshWorkspace, connectFreshWorkspaceZh, dismissSessionPanel, foldControlLayout, newEnglishPage,
saveFailureShot, sessionPanelToggle, showSessionPanel, writeComposerDraft,
} from './support.ts'
const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/agent-team-panel', import.meta.url))
const PANEL_EXPECTED = join(SNAPSHOT_DIR, 'task.expected.md')
const RESIZE_EXPECTED = join(SNAPSHOT_DIR, 'resize.expected.md')
const MODE = webSnapshotMode()
const SUBAGENTS_SECTION = '[data-session-panel-section="subagents"]'
const SHARED_TASKS_SECTION = '[data-session-panel-section="shared-tasks"]'
const RESEARCHER_DESCRIPTION = 'Researcher: investigate the construction and verify every bound before reporting the result. '.repeat(8).trim()
const RECEIPT_LOCALES = [
{
@@ -40,6 +47,26 @@ const RECEIPT_LOCALES = [
type ReceiptLocale = typeof RECEIPT_LOCALES[number]
/**
* Show the Session panel and return its Subagents section once the panel's
* entrance animation has ended, so geometry reads see its resting position.
* @param page - the page under test.
* @returns the section, hidden while it has nothing to show.
*/
async function showSubagentsSection(page: Page): Promise<Locator> {
return (await showSessionPanel(page)).locator(SUBAGENTS_SECTION)
}
/**
* Show the Session panel and return its Shared tasks section once the panel's
* entrance animation has ended.
* @param page - the page under test.
* @returns the section, hidden while it has nothing to show.
*/
async function showSharedTasksSection(page: Page): Promise<Locator> {
return (await showSessionPanel(page)).locator(SHARED_TASKS_SECTION)
}
async function openTeamSettings(page: Page, chinese = false): Promise<void> {
const trigger = page.getByRole('button', { name: chinese ? /^选择模型/u : /^Select model/u })
await trigger.click()
@@ -252,7 +279,11 @@ describe('web e2e: agent teamwork panel', () => {
it('defaults off and saves a Session selection in the model menu', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-team-mode'))
expect(await page.locator('[data-subagent-action]').count()).toBe(0)
const assertNoSubagentsSection = async (): Promise<void> => {
expect(await (await showSubagentsSection(page)).locator('[data-subagents-section]').count()).toBe(0)
await dismissSessionPanel(page)
}
await assertNoSubagentsSection()
await openTeamSettings(page)
const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true })
await toggle.waitFor()
@@ -266,7 +297,7 @@ describe('web e2e: agent teamwork panel', () => {
await page.keyboard.press('Space')
await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true')
await closeModelMenu(page)
expect(await page.locator('[data-subagent-action]').count()).toBe(0)
await assertNoSubagentsSection()
const agent = scaffold.ctx.agents.list()[0]!
expect(scaffold.ctx.commands.list(agent).some(command => command.name === 'team')).toBe(false)
expect(agent.session.ownEvents().filter(event => event.type === 'command/run' || event.type === 'command/done')).toEqual([])
@@ -275,8 +306,8 @@ describe('web e2e: agent teamwork panel', () => {
await other.dispose()
const beforeReload = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
await assertNoSubagentsSection()
await openTeamSettings(page)
expect(await page.locator('[data-subagent-action]').count()).toBe(0)
expect(await toggle.getAttribute('aria-checked')).toBe('true')
await closeModelMenu(page)
acknowledgeReloadConnectionLoss(tripwire, beforeReload)
@@ -310,37 +341,32 @@ describe('web e2e: agent teamwork panel', () => {
expect(tripwire.pageErrors).toEqual([])
})
it('shows tasks without children or a divider and hides the entry after the last task is deleted', async () => {
it('shows tasks in their own section without subagents and hides it after the last task is deleted', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-team-task-only'))
const agent = scaffold.ctx.agents.list()[0]!
expect(await page.locator('[data-subagent-action]').count()).toBe(0)
const section = await showSharedTasksSection(page)
expect(await section.locator('[data-team-panel]').count()).toBe(0)
expect(await section.isVisible()).toBe(false)
const task = await scaffold.ctx.agentTeams.createTask(agent, {
subject: 'Plan before delegation', description: 'Prepare shared work before creating subagents',
})
await page.getByRole('button', { name: '0 subagents', exact: true }).click()
const board = page.locator('[data-team-panel]')
const board = section.locator('[data-team-panel]')
await board.getByText(task.subject, { exact: true }).waitFor()
const panel = page.locator('[data-subagent-panel]')
expect(await panel.getByRole('treeitem').count()).toBe(0)
await panel.getByText('No subagents', { exact: true }).waitFor()
expect(await panel.locator('[data-subagent-section-header]').textContent()).toBe('Subagents')
expect(await panel.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0)
expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
expect(await page.locator(SUBAGENTS_SECTION).isVisible()).toBe(false)
expect(await section.getByRole('heading', { level: 2 }).locator('..').textContent()).toBe('Shared tasks1 pending')
expect(await section.locator('h2 button, h3 button').count()).toBe(0)
expect(await board.locator('[data-team-task-details]').count()).toBe(0)
expect(await board.getByRole('button', { expanded: false }).count()).toBe(1)
expect(await board.evaluate((element) => {
const style = getComputedStyle(element)
return { border: style.borderTopWidth, margin: style.marginTop }
})).toEqual({ border: '0px', margin: '0px' })
await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'task-only.expected.md'),
await captureStableAria(page, '[data-subagent-panel]', scaffold.workspaceCwd), MODE)
await captureStableAria(page, SHARED_TASKS_SECTION, scaffold.workspaceCwd), MODE)
await scaffold.ctx.agentTeams.updateTask(agent, { taskId: task.id, expectedRevision: task.revision, action: 'delete' })
await page.locator('[data-subagent-action]').waitFor({ state: 'hidden' })
await page.locator('[data-subagent-panel]').waitFor({ state: 'hidden' })
await board.waitFor({ state: 'detached' })
await section.waitFor({ state: 'hidden' })
await dismissSessionPanel(page)
expect(tripwire.pageErrors).toEqual([])
})
it('opens the member tree and live read-only tasks in one panel', async () => {
it('opens the member tree and live read-only tasks in their own sections', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-team-panel'))
const projectionReads = vi.spyOn(scaffold.ctx.sessionController, 'projections')
onTestFinished(() => { projectionReads.mockRestore() })
@@ -350,32 +376,16 @@ describe('web e2e: agent teamwork panel', () => {
version: 2, childId: memberId, childCreatedAt: Date.now(), mode: 'external',
label: RESEARCHER_DESCRIPTION,
})
const countAction = page.locator('[data-subagent-action]')
await countAction.waitFor()
await page.mouse.move(2, 2)
expect(await countAction.evaluate((element) => {
const header = element.closest('[data-slot="conversation.session.header.actions"]')!.parentElement!
const preset = header.querySelector('[data-icon="dsw-icon-agent-preset-outline-regular"]')!
const users = element.querySelector('[data-icon="dsw-icon-users-outline-regular"]')!
return {
display: getComputedStyle(header).display, gap: getComputedStyle(header).gap,
presetOpacity: getComputedStyle(preset).opacity,
presetParentOpacity: getComputedStyle(preset.parentElement!).opacity,
sameColor: getComputedStyle(preset).color === getComputedStyle(users).color,
}
})).toEqual({ display: 'flex', gap: '10px', presetOpacity: '1', presetParentOpacity: '1', sameColor: true })
const countTrigger = countAction.getByRole('button', { name: /subagents?$/u })
await countTrigger.click()
await countTrigger.click()
await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' })
expect(await countTrigger.evaluate(element => element === document.activeElement)).toBe(true)
await countTrigger.click()
const action = page.locator('[data-subagent-panel]')
const toggle = sessionPanelToggle(page)
await toggle.click()
await toggle.click()
await page.locator('[data-session-panel]').waitFor({ state: 'detached' })
expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true)
const action = await showSubagentsSection(page)
await action.getByRole('treeitem', { name: /Researcher/u }).waitFor()
expect(await action.locator('[data-team-panel], [data-subagent-section-header]').count()).toBe(0)
expect(await action.getByText('No shared tasks yet. Create them through the conversation.').count()).toBe(0)
expect(await action.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
expect(await action.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0)
expect(await page.locator('[data-team-panel]').count()).toBe(0)
expect(await page.getByText('No shared tasks yet. Create them through the conversation.').count()).toBe(0)
expect(await action.locator('h2 button, h3 button').count()).toBe(0)
expect(await action.getByRole('heading', { name: 'Members', exact: true }).count()).toBe(0)
expect(projectionReads).not.toHaveBeenCalled()
@@ -383,52 +393,32 @@ describe('web e2e: agent teamwork panel', () => {
expect(await action.getByRole('button', { name: /Refresh/u }).count()).toBe(0)
await action.getByRole('treeitem', { name: /Researcher/u }).waitFor()
expect(await page.locator('[data-subagent-panel]').count()).toBe(1)
expect(await page.locator('[data-subagents-section]').count()).toBe(1)
expect(await page.getByRole('button', { name: 'Task board', exact: true }).count()).toBe(0)
const task = await scaffold.ctx.agentTeams.createTask(agent, {
subject: 'Agent task', description: 'Created by the root agent', writeScopes: ['src/web'],
})
const row = action.locator(`[data-team-task="${task.id}"]`)
const tasks = page.locator(SHARED_TASKS_SECTION)
const row = tasks.locator(`[data-team-task="${task.id}"]`)
await row.getByRole('button', { name: 'Pending Agent task', exact: true, expanded: false }).waitFor()
expect(await action.locator('[data-subagent-section-header]').textContent()).toBe('Subagents1 external')
expect(await action.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0)
expect(await action.locator('[data-team-panel]').evaluate((element) => {
const style = getComputedStyle(element)
return { border: style.borderTopWidth, margin: style.marginTop }
})).toEqual({ border: '0px', margin: '4px' })
expect(await action.evaluate((element) => {
const tree = element.querySelector('[role="tree"]')!
const board = element.querySelector('[data-team-panel]')!
return Boolean(tree.compareDocumentPosition(board) & Node.DOCUMENT_POSITION_FOLLOWING)
})).toBe(true)
const head = action.getByRole('heading', { level: 2 }).locator('..')
expect(await head.textContent()).toBe('Subagents1 external')
expect(await action.locator('h2 button, h3 button').count()).toBe(0)
expect(await action.evaluate((element, selector) => Boolean(
element.compareDocumentPosition(document.querySelector(selector)!) & Node.DOCUMENT_POSITION_FOLLOWING,
), SHARED_TASKS_SECTION)).toBe(true)
expect(await row.evaluate(element => ({ tag: element.tagName, parent: element.parentElement?.tagName })))
.toEqual({ tag: 'LI', parent: 'UL' })
expect(await action.locator('[data-team-task-details], article').count()).toBe(0)
expect(await action.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
await action.getByRole('heading', { name: 'Shared tasks 1 pending', exact: true }).waitFor()
expect(await action.evaluate(element => getComputedStyle(element).padding)).toBe('6px')
expect(await action.locator('[data-subagent-section-header]').evaluate((element) => {
const style = getComputedStyle(element)
return { padding: style.padding, gap: style.gap }
})).toEqual({ padding: '4px 7px 8px', gap: '7px' })
expect(await action.locator('[data-team-panel]').getByRole('heading')
.evaluate(element => getComputedStyle(element).columnGap)).toBe('7px')
for (const [title, progress] of [
[action.locator('[data-subagent-section-header]').getByRole('heading'), action.getByText('1 external', { exact: true })],
[action.locator('[data-team-panel]').getByText('Shared tasks', { exact: true }), action.getByText('1 pending', { exact: true })],
] as const) {
expect(await progress.evaluate(element => getComputedStyle(element).marginInlineStart)).toBe('4px')
const titleRight = await title.evaluate(element => element.getBoundingClientRect().right)
const progressLeft = await progress.evaluate(element => element.getBoundingClientRect().left)
expect(Math.abs(progressLeft - titleRight - 11)).toBeLessThanOrEqual(1)
}
expect(await tasks.locator('[data-team-task-details], article').count()).toBe(0)
const tasksHead = tasks.getByRole('heading', { level: 2 }).locator('..')
expect(await tasksHead.textContent()).toBe('Shared tasks1 pending')
expect(await tasks.getByRole('heading', { level: 2 }).evaluate(element => getComputedStyle(element).font))
.toBe(await action.getByRole('heading', { level: 2 }).evaluate(element => getComputedStyle(element).font))
const member = action.getByRole('treeitem', { name: /Researcher/u })
const memberTitle = member.getByText(RESEARCHER_DESCRIPTION, { exact: true })
const taskTitle = row.getByText('Agent task', { exact: true })
const titleLefts = await Promise.all([
memberTitle,
action.locator('[data-subagent-section-header]').getByRole('heading'),
action.locator('[data-team-panel]').getByText('Shared tasks', { exact: true }),
taskTitle,
].map(locator => locator.evaluate(element => element.getBoundingClientRect().left)))
expect(Math.max(...titleLefts) - Math.min(...titleLefts)).toBeLessThanOrEqual(1)
@@ -438,8 +428,8 @@ describe('web e2e: agent teamwork panel', () => {
})))
expect(primaryStyles.map(style => style.fontSize)).toEqual(['13px', '13px'])
expect(primaryStyles[1]).toEqual(primaryStyles[0])
expect(await member.getByText('team-panel-researcher', { exact: true })
.evaluate(element => getComputedStyle(element).fontSize)).toBe('12px')
// The member's name moves from the row to its hover card.
expect(await member.getByText('team-panel-researcher', { exact: true }).count()).toBe(0)
const memberHover = member.locator(':scope > div')
for (const target of [member, memberHover]) {
expect(await target.evaluate((element) => {
@@ -447,27 +437,33 @@ describe('web e2e: agent teamwork panel', () => {
return [style.paddingTop, style.paddingBottom]
})).toEqual(['4px', '4px'])
}
expect(await member.evaluate(element => getComputedStyle(element).minHeight)).toBe('40px')
expect(await member.evaluate(element => getComputedStyle(element).minHeight)).toBe('28px')
expect(await member.evaluate((element) => {
const style = getComputedStyle(element)
return { left: style.paddingLeft, right: style.paddingRight, gap: style.gap }
})).toEqual({ left: '9px', right: '6px', gap: '7px' })
})).toEqual({ left: '6px', right: '6px', gap: '8px' })
expect(await memberHover.evaluate((element) => {
const style = getComputedStyle(element)
return { left: style.paddingLeft, right: style.paddingRight, gap: style.gap, margin: style.margin }
})).toEqual({ left: '6px', right: '6px', gap: '7px', margin: '-4px -6px' })
})).toEqual({ left: '6px', right: '6px', gap: '8px', margin: '-4px -6px' })
const taskHover = row.getByRole('button')
expect(await taskHover.evaluate((element) => {
const style = getComputedStyle(element)
return [style.paddingTop, style.paddingBottom]
})).toEqual(['7px', '7px'])
expect(await taskHover.evaluate(element => element.getBoundingClientRect().height)).toBe(31)
})).toEqual(['4px', '4px'])
expect(await taskHover.evaluate(element => element.getBoundingClientRect().height)).toBe(28)
expect(await taskHover.evaluate((element) => {
const style = getComputedStyle(element)
return { left: style.paddingLeft, right: style.paddingRight, gap: style.gap, margin: style.margin }
})).toEqual({ left: '6px', right: '6px', gap: '7px', margin: '0px -6px' })
expect(await taskHover.evaluate(element => element.getBoundingClientRect().width
- element.parentElement!.getBoundingClientRect().width)).toBe(12)
})).toEqual({ left: '6px', right: '6px', gap: '8px', margin: '0px' })
// Status glyphs and trailing chevrons of both rows share their columns.
const columns = await Promise.all([
member.locator('[data-state]').first(), row.locator('[data-state]').first(),
].map(locator => locator.evaluate((element) => {
const bounds = element.getBoundingClientRect()
return bounds.left + bounds.width / 2
})))
expect(Math.abs(columns[0]! - columns[1]!)).toBeLessThanOrEqual(0.5)
const hoverStyles = []
for (const target of [memberHover, taskHover]) {
await target.hover()
@@ -488,26 +484,28 @@ describe('web e2e: agent teamwork panel', () => {
expect(await row.locator('[data-team-task-details]').evaluate((element) => {
const style = getComputedStyle(element)
return { fontSize: style.fontSize, indent: style.paddingLeft }
})).toEqual({ fontSize: '12px', indent: '21px' })
})).toEqual({ fontSize: '12px', indent: '30px' })
expect(await row.locator('[data-team-task-details] p, [data-team-task-owner]')
.evaluateAll(elements => elements.every(element => getComputedStyle(element).fontSize === '12px'))).toBe(true)
expect(await row.getByRole('button').getAttribute('aria-expanded')).toBe('true')
expect(await action.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
await scaffold.ctx.agentTeams.updateTask(agent, {
taskId: task.id, expectedRevision: task.revision, action: 'claim',
})
await row.getByRole('img', { name: 'In progress', exact: true }).waitFor()
await row.locator('[data-team-task-owner]').filter({ hasText: 'Owner: lead' }).waitFor()
await action.getByRole('heading', { name: 'Shared tasks 1 in progress', exact: true }).waitFor()
expect(await action.getByRole('button', { name: /^(New task|Edit|Complete|Reopen|Delete)$/u }).count()).toBe(0)
expect(await action.locator('input, select, textarea').count()).toBe(0)
await tasks.getByText('1 in progress', { exact: true }).waitFor()
expect(await tasks.getByRole('button', { name: /^(New task|Edit|Complete|Reopen|Delete)$/u }).count()).toBe(0)
expect(await tasks.locator('input, select, textarea').count()).toBe(0)
const snapshot = await captureStableAria(page, '[data-subagent-panel]', scaffold.workspaceCwd)
// The working directory row abbreviates the home directory, which holds the scratch workspace on CI.
const snapshot = await captureStableAria(page, '[data-session-panel]', scaffold.workspaceCwd, {
replacements: [[abbreviateHomePath(scaffold.workspaceCwd, homedir()), '{{cwd}}']],
})
await compareOrRefreshGolden(PANEL_EXPECTED, snapshot, MODE)
expect(projectionReads).not.toHaveBeenCalled()
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
await page.keyboard.press('Escape')
await dismissSessionPanel(page)
}, 60_000)
it('hides the board while disabled and restores its tasks when re-enabled', async () => {
@@ -515,94 +513,47 @@ describe('web e2e: agent teamwork panel', () => {
const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true })
await toggle.click()
await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false')
expect(await page.locator('[data-subagent-action]').count()).toBe(1)
await closeModelMenu(page)
await page.locator('[data-subagent-action]').getByRole('button', { name: '1 subagent', exact: true }).click()
await page.getByRole('treeitem', { name: /Researcher/u }).waitFor()
const section = await showSubagentsSection(page)
await section.getByRole('treeitem', { name: /Researcher/u }).waitFor()
expect(await page.locator('[data-subagents-section]').count()).toBe(1)
expect(await page.locator('[data-team-panel]').count()).toBe(0)
expect(await page.locator('[data-subagent-panel]').evaluate(element => element.getBoundingClientRect().width)).toBe(360)
expect(await page.locator('[data-subagent-section-header]').count()).toBe(0)
await page.keyboard.press('Escape')
await dismissSessionPanel(page)
await openTeamSettings(page)
await toggle.click()
await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true')
await closeModelMenu(page)
await page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u }).click()
await page.locator('[data-subagent-panel]').getByText('Agent task', { exact: true }).waitFor()
await page.keyboard.press('Escape')
await (await showSharedTasksSection(page)).getByText('Agent task', { exact: true }).waitFor()
await dismissSessionPanel(page)
})
it('keeps the narrow Users trigger focused and opens its catalog only on explicit activation', async () => {
it('keeps the toggle focused in a narrow window and opens the catalog only on explicit activation', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-team-narrow-trigger'))
const trigger = page.locator('[data-subagent-action]').getByRole('button', { name: '1 subagent', exact: true })
const panel = page.locator('[data-subagent-panel]')
const count = trigger.locator('[data-subagent-count]')
const trigger = sessionPanelToggle(page)
const panel = page.locator('[data-session-panel]')
const viewport = page.viewportSize()!
expect(await count.isVisible()).toBe(true)
expect(await trigger.locator('[data-icon="dsw-icon-users-outline-regular"]').count()).toBe(1)
expect(await trigger.locator('[data-icon="dsw-icon-users-outline-regular"]').evaluate((element) => {
const bounds = element.getBoundingClientRect()
return { width: bounds.width, height: bounds.height }
})).toEqual({ width: 14, height: 14 })
expect(await trigger.locator('[data-icon="dsw-icon-chevron-down-outline-regular"]').count()).toBe(0)
expect(await trigger.locator('svg').count()).toBe(1)
await trigger.focus()
const original = await trigger.elementHandle()
if (original === null) throw new Error('Subagent trigger is missing')
if (original === null) throw new Error('Session panel toggle is missing')
try {
await page.setViewportSize({ width: 390, height: 700 })
await expect.poll(() => count.evaluate(element => getComputedStyle(element).display)).toBe('none')
expect(await original.evaluate(element => element.isConnected && element === document.activeElement)).toBe(true)
const expandSidebar = page.locator('[data-sidebar-right-expand]')
const compactStyles = await Promise.all([trigger, expandSidebar].map(control => control.evaluate((element) => {
const bounds = element.getBoundingClientRect()
const icon = element.querySelector('svg')!.getBoundingClientRect()
const style = getComputedStyle(element)
return { width: bounds.width, height: bounds.height, padding: style.padding, radius: style.borderRadius,
color: style.color, iconWidth: icon.width, iconHeight: icon.height }
})))
expect(compactStyles[0]).toEqual(compactStyles[1])
expect(compactStyles[0]).toMatchObject({ width: 28, height: 28, padding: '0px', iconWidth: 15, iconHeight: 15 })
expect(await trigger.evaluate(element => getComputedStyle(element.closest('[data-slot="conversation.session.header.actions"]')!.parentElement!).gap)).toBe('8px')
await expandSidebar.hover()
const expandHover = await expandSidebar.evaluate((element) => {
const style = getComputedStyle(element)
return { background: style.backgroundColor, color: style.color }
})
await page.mouse.move(1, 1)
await page.keyboard.press('Tab')
const countTooltip = page.getByRole('tooltip', { name: '1 subagent', exact: true })
await countTooltip.waitFor({ state: 'hidden' })
await trigger.hover()
expect(await trigger.evaluate((element) => {
const style = getComputedStyle(element)
return { background: style.backgroundColor, color: style.color }
})).toEqual(expandHover)
expect(expandHover.background).not.toBe('rgba(0, 0, 0, 0)')
// Observe beyond the wide trigger's 150ms hover-open deadline.
// Hover alone opens nothing, even past the 150ms delay of hover-opened subagent menus.
await page.waitForTimeout(200)
expect(await panel.count()).toBe(0)
await countTooltip.waitFor({ state: 'visible' })
expect(await panel.count()).toBe(0)
await trigger.click()
await panel.waitFor()
expect(await panel.getAttribute('data-session-panel')).toBe('overlay')
expect(await trigger.getAttribute('aria-expanded')).toBe('true')
expect(await page.getByRole('tooltip', { name: '1 subagent', exact: true }).count()).toBe(0)
await panel.getByRole('treeitem', { name: /Researcher/u }).waitFor()
const section = panel.locator(SUBAGENTS_SECTION)
await section.getByRole('treeitem', { name: /Researcher/u }).waitFor()
await panel.locator('[data-team-task]').getByRole('button', { expanded: false }).waitFor()
await trigger.click()
await panel.waitFor({ state: 'detached' })
expect(await trigger.getAttribute('aria-expanded')).toBe('false')
await trigger.press('ArrowDown')
await panel.waitFor()
await page.mouse.move(1, 1)
// Keyboard activation stays pinned beyond the 120ms pointer-leave grace.
await page.waitForTimeout(180)
expect(await panel.count()).toBe(1)
await page.keyboard.press('Escape')
await panel.waitFor({ state: 'detached' })
} finally {
await page.keyboard.press('Escape')
await page.setViewportSize(viewport)
await original.dispose()
}
@@ -610,56 +561,77 @@ describe('web e2e: agent teamwork panel', () => {
it('keeps the panel inside the viewport and closes on outside click or Escape', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-team-panel-keyboard'))
const panel = page.locator('[data-subagent-panel]')
const trigger = page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u })
const panel = page.locator('[data-session-panel]')
const section = panel.locator(SUBAGENTS_SECTION)
const tasksHeading = panel.locator(SHARED_TASKS_SECTION).getByRole('heading', { name: 'Shared tasks', exact: true })
const trigger = sessionPanelToggle(page)
const viewport = page.viewportSize()!
await trigger.click()
await panel.getByRole('heading', { name: /Shared tasks/u }).waitFor()
try {
for (const size of [{ width: 760, height: 540 }, { width: 600, height: 420 }, { width: 390, height: 700 }]) {
await page.setViewportSize(size)
await showSessionPanel(page)
await tasksHeading.waitFor()
await expect.poll(() => panel.evaluate((element) => {
const rect = element.getBoundingClientRect()
return element.parentElement === document.body
&& rect.left >= 16 && rect.top >= 16
&& rect.right <= window.innerWidth - 16 && rect.bottom <= window.innerHeight - 16
return element.getAttribute('data-session-panel') === 'overlay'
&& rect.left >= 0 && rect.top >= 0
&& rect.right <= window.innerWidth && rect.bottom <= window.innerHeight
&& [[rect.left + 12, rect.top + 12], [rect.right - 12, rect.bottom - 12]]
.every(([x, y]) => element.contains(document.elementFromPoint(x!, y!)))
})).toBe(true)
}
const row = panel.getByRole('treeitem', { name: /Researcher/u })
const row = section.getByRole('treeitem', { name: /Researcher/u })
const primary = row.getByText(RESEARCHER_DESCRIPTION, { exact: true })
const secondary = row.getByText('team-panel-researcher', { exact: true })
expect(await row.getByRole('button').count()).toBe(0)
expect(await primary.evaluate((element) => {
const style = getComputedStyle(element)
return {
tag: element.tagName, clipped: element.scrollWidth > element.clientWidth || element.scrollHeight > element.clientHeight,
whiteSpace: style.whiteSpace, overflowWrap: style.overflowWrap,
}
})).toEqual({ tag: 'SPAN', clipped: false, whiteSpace: 'normal', overflowWrap: 'anywhere' })
const primaryBounds = await primary.boundingBox()
const secondaryBounds = await secondary.boundingBox()
expect(primaryBounds).not.toBeNull()
expect(secondaryBounds).not.toBeNull()
expect(primaryBounds!.y + primaryBounds!.height).toBeLessThanOrEqual(secondaryBounds!.y)
// The row keeps one line at every width: the description clips, and the name shows in its hover card.
expect(await primary.evaluate(element => ({ tag: element.tagName, whiteSpace: getComputedStyle(element).whiteSpace })))
.toEqual({ tag: 'SPAN', whiteSpace: 'nowrap' })
expect(await row.getByText('team-panel-researcher', { exact: true }).count()).toBe(0)
expect(await panel.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
await primary.hover()
const card = page.locator('[data-session-panel-details]')
await card.waitFor()
expect(await card.evaluate(element => [...element.children].slice(0, 2).map(child => child.textContent)))
.toEqual([RESEARCHER_DESCRIPTION, 'Owner: team-panel-researcher'])
// The window has room for the card on neither side of the row, and this description fills a card too
// tall to open under or over the row, so the card covers the row; it stays inside the viewport.
expect(await card.evaluate((element) => {
// The details sit inside the fixed card.
let fixed = element
while (getComputedStyle(fixed).position !== 'fixed') fixed = fixed.parentElement!
const rect = fixed.getBoundingClientRect()
return rect.left >= 0 && rect.top >= 0 && rect.right <= window.innerWidth && rect.bottom <= window.innerHeight
})).toBe(true)
await page.mouse.move(20, 400)
await card.waitFor({ state: 'detached' })
// A card that fits under its row opens there, from the row's start edge and inside the viewport's
// margin, so the row stays clear.
const task = panel.locator('[data-team-task]').getByRole('button')
await task.hover()
await card.waitFor()
const anchor = await task.locator('xpath=..').boundingBox()
if (anchor === null) throw new Error('the task row has no box')
const placed = await card.evaluate((element) => {
let fixed = element
while (getComputedStyle(fixed).position !== 'fixed') fixed = fixed.parentElement!
const bounds = fixed.getBoundingClientRect()
return { left: bounds.left, top: bounds.top, right: bounds.right, viewport: window.innerWidth }
})
expect({ below: placed.top - (anchor.y + anchor.height), start: placed.left - anchor.x }).toEqual({ below: 8, start: 0 })
expect(placed.right).toBeLessThanOrEqual(placed.viewport - 8)
const beforeClick = page.url()
await primary.click()
expect(page.url()).toBe(beforeClick)
expect(await page.getByRole('tooltip', { name: RESEARCHER_DESCRIPTION, exact: true }).count()).toBe(0)
expect(await panel.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
expect(await secondary.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
await secondary.hover()
expect(await page.getByRole('tooltip').count()).toBe(0)
await panel.getByRole('heading', { name: /Shared tasks/u }).click()
await tasksHeading.click()
expect(await panel.count()).toBe(1)
await page.mouse.click(2, 2)
await panel.waitFor({ state: 'detached' })
await page.setViewportSize(viewport)
await trigger.focus()
await page.keyboard.press('Enter')
await panel.getByRole('heading', { name: /Shared tasks/u }).waitFor()
expect(await panel.evaluate(element => element === document.activeElement)).toBe(true)
await tasksHeading.waitFor()
await panel.locator('[data-team-task]').getByRole('button').focus()
await page.keyboard.press('Escape')
await panel.waitFor({ state: 'detached' })
expect(await trigger.evaluate(element => element === document.activeElement)).toBe(true)
@@ -676,24 +648,7 @@ describe('web e2e: agent teamwork panel', () => {
}
})
it('keeps the hovered panel open when the pointer returns directly to its trigger', async () => {
onTestFailed(async () => {
await saveFailureShot(page, 'web-e2e-agent-team-hover')
console.error('Agent Team hover diagnostics', JSON.stringify({ errors: tripwire.pageErrors, warnings: tripwire.warnings }))
})
const trigger = page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u })
const panel = page.locator('[data-subagent-panel]')
await trigger.hover()
await panel.waitFor()
await panel.hover()
await trigger.hover()
// The assertion spans the 120ms dismissal grace while the pointer stays on the trigger.
await page.waitForTimeout(180)
expect(await panel.count()).toBe(1)
await page.keyboard.press('Escape')
})
it('keeps compact tasks ordered, opens one full detail at a time, and scrolls only the fixed-width menu', async () => {
it('keeps compact tasks ordered, opens one full detail at a time, and scrolls only the Session panel', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-team-compact-details'))
const agent = scaffold.ctx.agents.list()[0]!
const completed = await scaffold.ctx.agentTeams.createTask(agent, {
@@ -714,64 +669,46 @@ describe('web e2e: agent teamwork panel', () => {
subject, description, blockedBy: [blocker.id], writeScopes: ['src/web/components'],
})
const viewport = page.viewportSize()!
const trigger = page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u })
const panel = page.locator('[data-subagent-panel]')
const board = panel.locator('[data-team-panel]')
const panel = page.locator('[data-session-panel]')
const section = panel.locator(SHARED_TASKS_SECTION)
const board = section.locator('[data-team-panel]')
const row = board.locator(`[data-team-task="${task.id}"]`)
const emptyRow = board.locator(`[data-team-task="${completed.id}"]`)
onTestFinished(() => page.setViewportSize(viewport))
// Constrain the menu so closed and expanded task rows both exercise its scrollbar.
await page.setViewportSize({ width: viewport.width, height: 540 })
await trigger.click()
// Constrain the panel so closed and expanded task rows both exercise its scrollbar.
await page.setViewportSize({ width: viewport.width, height: 500 })
await showSharedTasksSection(page)
await row.waitFor()
expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
expect(await board.locator('[data-team-task-details], article').count()).toBe(0)
expect(await board.getByRole('button', { expanded: false }).count()).toBe(4)
expect(await board.locator('[data-team-task]').evaluateAll(elements => elements.map(element => element.getAttribute('data-status'))))
.toEqual(['in_progress', 'completed', 'pending', 'pending'])
const counts = board.getByText('1 completed\u2002·\u20021 in progress\u2002·\u20022 pending', { exact: true })
.toEqual(['in_progress', 'pending', 'pending', 'completed'])
const counts = section.getByText('1 completed\u2002·\u20021 in progress\u2002·\u20022 pending', { exact: true })
await counts.waitFor()
expect(await counts.textContent()).toBe('1 completed\u2002·\u20021 in progress\u2002·\u20022 pending')
expect(await panel.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0)
expect(await panel.getByRole('button', { name: /^Show (more|less)$/u }).count()).toBe(0)
expect(await section.locator('h2 button, h3 button').count()).toBe(0)
expect(await section.getByRole('button', { name: /^Show (more|less)$/u }).count()).toBe(0)
await row.getByRole('img', { name: 'Blocked by dependencies', exact: true }).waitFor()
// The panel itself scrolls; its client box ends where its scrollbar track begins.
const measureScroll = async () => panel.evaluate((element) => {
const style = getComputedStyle(element)
const bounds = element.getBoundingClientRect()
const scroller = element.querySelector('[role="tree"]')!.parentElement!
const scrollStyle = getComputedStyle(scroller)
const scrollBounds = scroller.getBoundingClientRect()
const taskBounds = element.querySelector('[data-team-task] button')!.getBoundingClientRect()
const scrollbarWidth = Number.parseFloat(getComputedStyle(scroller, '::-webkit-scrollbar').width)
const trackLeft = bounds.left + element.clientLeft + element.clientWidth
return {
innerWidth: bounds.width - Number.parseFloat(style.paddingLeft) - Number.parseFloat(style.paddingRight)
- Number.parseFloat(style.borderLeftWidth) - Number.parseFloat(style.borderRightWidth),
clientWidth: scroller.clientWidth, clientHeight: scroller.clientHeight, scrollHeight: scroller.scrollHeight,
overflowing: scroller.scrollHeight > scroller.clientHeight,
gutter: scrollStyle.scrollbarGutter, marginRight: scrollStyle.marginRight,
trackMargin: scrollStyle.getPropertyValue('--dsh-scrollbar-track-margin').trim(),
overflowing: element.scrollHeight > element.clientHeight,
taskLeft: taskBounds.left, taskRight: taskBounds.right,
trackLeft: scrollBounds.right - scrollbarWidth, trackRight: scrollBounds.right, panelRight: bounds.right,
arrowsBeforeTrack: [...element.querySelectorAll('[data-team-task] button svg')]
.every(arrow => arrow.getBoundingClientRect().right <= scrollBounds.right - scrollbarWidth),
.every(arrow => arrow.getBoundingClientRect().right <= trackLeft),
}
})
const closedScroll = await measureScroll()
expect(closedScroll.overflowing, JSON.stringify(closedScroll)).toBe(true)
expect(Math.abs(closedScroll.clientWidth - closedScroll.innerWidth), JSON.stringify(closedScroll)).toBeLessThanOrEqual(1)
expect(closedScroll.gutter).toBe('stable')
expect(closedScroll.marginRight).toBe('-5px')
expect(closedScroll.trackMargin).toBe('6px')
await row.getByRole('button').click()
const expandedScroll = await measureScroll()
expect(expandedScroll.overflowing).toBe(true)
expect(expandedScroll.clientWidth).toBe(closedScroll.clientWidth)
expect(expandedScroll.taskLeft).toBe(closedScroll.taskLeft)
expect(expandedScroll.taskRight).toBe(closedScroll.taskRight)
expect(expandedScroll.arrowsBeforeTrack).toBe(true)
expect(expandedScroll.trackLeft).toBeGreaterThanOrEqual(expandedScroll.panelRight - 6)
expect(expandedScroll.trackRight).toBeLessThanOrEqual(expandedScroll.panelRight - 1)
expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
const details = row.locator('[data-team-task-details]')
expect(await details.locator('p:not([data-team-task-owner])').textContent()).toBe(description)
expect(await details.locator('[data-team-task-owner]').textContent()).toBe('Owner: Unowned')
@@ -786,35 +723,32 @@ describe('web e2e: agent teamwork panel', () => {
await page.setViewportSize({ width: 390, height: 700 })
await expect.poll(() => panel.evaluate((element) => {
const rect = element.getBoundingClientRect()
return rect.width === Math.min(360, innerWidth - 32) && rect.left >= 16 && rect.right <= innerWidth - 16
&& rect.top >= 16 && rect.bottom <= innerHeight - 16
return element.getAttribute('data-session-panel') === 'overlay'
&& rect.left >= 0 && rect.right <= innerWidth && rect.top >= 0 && rect.bottom <= innerHeight
&& element.scrollWidth <= element.clientWidth
})).toBe(true)
expect(await panel.locator('*').evaluateAll((elements) => {
const scrollers = elements.filter(element =>
expect(await panel.evaluate((panelElement) => {
const scrollers = [panelElement, ...panelElement.querySelectorAll('*')].filter(element =>
['auto', 'scroll'].includes(getComputedStyle(element).overflowY)
&& element.scrollHeight > element.clientHeight)
return scrollers.map(element => ({
hasHeader: element.querySelector('[data-subagent-section-header]') !== null,
panel: element === panelElement,
hasTree: element.querySelector('[role="tree"]') !== null,
hasBoard: element.querySelector('[data-team-panel]') !== null,
fitsWidth: element.scrollWidth <= element.clientWidth,
}))
})).toEqual([{ hasHeader: true, hasTree: true, hasBoard: true, fitsWidth: true }])
const narrowScroll = await measureScroll()
expect(Math.abs(narrowScroll.clientWidth - narrowScroll.innerWidth), JSON.stringify(narrowScroll)).toBeLessThanOrEqual(1)
expect(narrowScroll.arrowsBeforeTrack).toBe(true)
const scroller = panel.getByRole('tree').locator('..')
await scroller.hover({ position: { x: 20, y: 20 } })
})).toEqual([{ panel: true, hasTree: true, hasBoard: true, fitsWidth: true }])
expect((await measureScroll()).arrowsBeforeTrack).toBe(true)
await panel.hover({ position: { x: 20, y: 20 } })
await Promise.all([
scroller.evaluate(element => new Promise<void>((resolve) => {
panel.evaluate(element => new Promise<void>((resolve) => {
element.addEventListener('scrollend', () => { resolve() }, { once: true })
})),
page.mouse.wheel(0, 180),
])
await expect.poll(() => scroller.evaluate(element => element.scrollTop)).toBeGreaterThan(0)
await scroller.evaluate((element) => { element.scrollTo({ top: 0 }) })
await expect.poll(() => scroller.evaluate(element => element.scrollTop)).toBe(0)
await expect.poll(() => panel.evaluate(element => element.scrollTop)).toBeGreaterThan(0)
await panel.evaluate((element) => { element.scrollTo({ top: 0 }) })
await expect.poll(() => panel.evaluate(element => element.scrollTop)).toBe(0)
expect(await row.getByText(subject, { exact: true }).evaluate(element =>
element.scrollWidth <= element.clientWidth && getComputedStyle(element).whiteSpace === 'pre-wrap')).toBe(true)
expect(await details.locator('p:not([data-team-task-owner])').evaluate(element => element.scrollHeight === element.clientHeight)).toBe(true)
@@ -828,13 +762,17 @@ describe('web e2e: agent teamwork panel', () => {
expect(await details.locator('[data-team-task-owner], [data-team-task-owner] span')
.evaluateAll(elements => elements.map(element => getComputedStyle(element).color)))
.toEqual([detailColor, detailColor, detailColor])
expect(await counts.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
const titleBounds = await board.getByText('Shared tasks', { exact: true }).boundingBox()
// Long progress clips on the title's line; the title itself keeps its full width.
const title = section.getByRole('heading', { name: 'Shared tasks', exact: true })
expect(await title.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
const titleBounds = await title.boundingBox()
const countBounds = await counts.boundingBox()
const sectionBounds = await section.boundingBox()
expect(titleBounds).not.toBeNull()
expect(countBounds).not.toBeNull()
expect(countBounds!.y).toBeGreaterThanOrEqual(titleBounds!.y + titleBounds!.height)
await compareOrRefreshGolden(RESIZE_EXPECTED, await captureStableAria(page, '[data-subagent-panel]', scaffold.workspaceCwd), MODE)
expect(Math.abs((countBounds!.y + countBounds!.height / 2) - (titleBounds!.y + titleBounds!.height / 2))).toBeLessThanOrEqual(1)
expect(countBounds!.x + countBounds!.width).toBeLessThanOrEqual(sectionBounds!.x + sectionBounds!.width)
await compareOrRefreshGolden(RESIZE_EXPECTED, await captureStableAria(page, SHARED_TASKS_SECTION, scaffold.workspaceCwd), MODE)
await emptyRow.getByRole('button').click()
expect(await row.getAttribute('data-expanded')).toBe('false')
expect(await row.locator('[data-team-task-details]').count()).toBe(0)
@@ -846,13 +784,45 @@ describe('web e2e: agent teamwork panel', () => {
await emptyRow.getByRole('button').click()
expect(await board.locator('[data-team-task-details]').count()).toBe(0)
await page.setViewportSize(viewport)
expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
} finally {
await page.keyboard.press('Escape')
await page.setViewportSize(viewport)
}
})
it('holds back the tasks past five behind the fold control and keeps the choice while the panel is hidden', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-team-task-fold'))
const agent = scaffold.ctx.agents.list()[0]!
const before = scaffold.ctx.agentTeams.listTasks(agent).filter(task => task.status !== 'deleted')
// The tasks so far: one in progress, pending ones, and a completed one. Pending tasks bring the list to eight.
for (let index = before.length; index < 8; index++) {
await scaffold.ctx.agentTeams.createTask(agent, { subject: `Fold task ${String(index)}`, description: 'Fills the list.', writeScopes: [] })
}
const section = await showSharedTasksSection(page)
const tasks = section.locator('[data-team-task]')
const fold = section.locator('[data-session-panel-row="fold"]')
const statuses = (): Promise<(string | null)[]> => tasks.evaluateAll(items => items.map(item => item.getAttribute('data-status')))
// Five tasks show: the one in progress, then pending ones in source order. The completed task is held back.
await expect.poll(statuses, { timeout: 15_000 }).toEqual(['in_progress', 'pending', 'pending', 'pending', 'pending'])
expect(await fold.textContent()).toBe('Show 3 more')
// The control follows the list, at the row height, with its chevron under the state marks and its text under the subjects.
expect(await section.getByRole('list').locator('[data-session-panel-row="fold"]').count()).toBe(0)
expect(await foldControlLayout(fold, tasks.first().getByRole('button'), '[class*="subject"]'))
.toEqual({ heights: [28, 28], chevronOffset: 0, textOffset: 0, fontSize: '12px', expanded: 'false' })
await section.getByRole('button', { name: 'Show 3 more (shared tasks)', exact: true }).click()
await expect.poll(statuses).toEqual(['in_progress', 'pending', 'pending', 'pending', 'pending', 'pending', 'pending', 'completed'])
const less = section.getByRole('button', { name: 'Show less (shared tasks)', exact: true })
expect([await less.textContent(), await less.getAttribute('aria-expanded')]).toEqual(['Show less', 'true'])
// The choice is the Session's: it holds while the panel is hidden.
await dismissSessionPanel(page)
await showSharedTasksSection(page)
await expect.poll(() => tasks.count()).toBe(8)
await less.click()
await expect.poll(() => tasks.count()).toBe(5)
expect(tripwire.pageErrors).toEqual([])
await dismissSessionPanel(page)
})
it('confirms disabling after a recorded model request and keeps cancellation side-effect free', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-team-disable-confirmation'))
const agent = scaffold.ctx.agents.list()[0]!
@@ -897,24 +867,21 @@ describe('web e2e: agent teamwork panel', () => {
expect(tripwire.pageErrors).toEqual([])
})
it('removes both section headings and the board divider when the last shared task is deleted', async () => {
it('hides the Shared tasks section when the last shared task is deleted', async () => {
const agent = scaffold.ctx.agents.list()[0]!
await page.getByRole('button', { name: '1 subagent', exact: true }).click()
const panel = page.locator('[data-subagent-panel]')
await panel.locator('[data-team-panel]').waitFor()
const tasks = await showSharedTasksSection(page)
await tasks.locator('[data-team-panel]').waitFor()
for (const task of scaffold.ctx.agentTeams.listTasks(agent).toReversed()) {
if (task.status === 'deleted') continue
await scaffold.ctx.agentTeams.updateTask(agent, {
taskId: task.id, expectedRevision: task.revision, action: 'delete',
})
}
await panel.locator('[data-team-panel]').waitFor({ state: 'detached' })
expect(await panel.locator('[data-subagent-section-header]').count()).toBe(0)
expect(await panel.getByRole('heading').count()).toBe(0)
expect(await panel.getByText('No shared tasks yet. Create them through the conversation.').count()).toBe(0)
expect(await panel.getByRole('treeitem', { name: /Researcher/u }).count()).toBe(1)
expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
await page.keyboard.press('Escape')
await tasks.locator('[data-team-panel]').waitFor({ state: 'detached' })
await tasks.waitFor({ state: 'hidden' })
expect(await page.getByText('No shared tasks yet. Create them through the conversation.').count()).toBe(0)
expect(await page.locator(SUBAGENTS_SECTION).getByRole('treeitem', { name: /Researcher/u }).count()).toBe(1)
await dismissSessionPanel(page)
})
it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => {
@@ -1047,21 +1014,19 @@ it.each(RECEIPT_LOCALES)('renders historical Team failures in $language without
})
})
it('shows the Chinese empty subagent section above compact shared tasks', async () => {
it('shows the Chinese Shared tasks section without subagents', async () => {
await withTeamReceiptPage(RECEIPT_LOCALES[1], async (page, scaffold) => {
const agent = scaffold.ctx.agents.list()[0]!
await scaffold.ctx.agentTeams.setEnabled(agent, true)
await scaffold.ctx.agentTeams.createTask(agent, {
subject: '准备协作', description: '先准备共享任务,再创建子智能体。',
})
await page.getByRole('button', { name: '0 个子智能体', exact: true }).click()
const panel = page.locator('[data-subagent-panel]')
await panel.getByText('暂无子智能体', { exact: true }).waitFor()
expect(await panel.locator('[data-subagent-section-header]').textContent()).toBe('子智能体')
expect(await panel.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0)
expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
await panel.getByRole('heading', { name: '共享任务 1 待处理', exact: true }).waitFor()
expect(await panel.locator('[data-team-task-details]').count()).toBe(0)
const section = await showSharedTasksSection(page)
await section.getByText('准备协作', { exact: true }).waitFor()
expect(await section.getByRole('heading', { level: 2 }).locator('..').textContent()).toBe('共享任务1 待处理')
expect(await section.locator('h2 button, h3 button').count()).toBe(0)
expect(await section.locator('[data-team-task-details]').count()).toBe(0)
expect(await page.locator(SUBAGENTS_SECTION).isVisible()).toBe(false)
})
})
+1 -2
View File
@@ -10,9 +10,8 @@ const PANELS = [
{ file: 'client/ui-schedule/src/client/TaskMenu.module.css', classes: 'list portal scrollable alignEnd', align: 'end' },
{ file: 'client/ui-schedule/src/client/PickerPopover.module.css', classes: 'panel', align: 'start' },
{ file: 'client/ui-schedule/src/client/ScheduleCatalogAction.module.css', classes: 'menu', align: 'start' },
{ file: 'client/ui-subagent/src/client/SubagentHeaderLineage.module.css', classes: 'menu', align: 'start' },
{ file: 'client/ui-subagent/src/client/SubagentCatalog.module.css', classes: 'menu', align: 'start' },
{ file: 'client/ui-approval/src/client/ApprovalPanel.module.css', classes: 'warningPopover', align: 'end' },
{ file: 'client/ui-jobs/src/client/JobListAction.module.css', classes: 'menu', align: 'start' },
{ file: 'client/ui-conversation/src/client/skeleton/ContextMeter.module.css', classes: 'panel', align: 'start' },
{ file: 'client/ui-chat/src/client/chat/stat-dialog.module.css', classes: 'panel', align: 'start' },
{ file: 'client/ui-sidebar-documentpreview/src/client/office/FontNotice.module.css', classes: 'panel', align: 'start' },
+152 -130
View File
@@ -1,6 +1,6 @@
import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit'
// Session-header background jobs driven by a real `ctx.jobs` entry. No model
// call is involved.
// The Session panel's background-jobs section driven by a real `ctx.jobs`
// entry. No model call is involved.
import { readFile, writeFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import { join } from 'node:path'
@@ -16,12 +16,13 @@ import {
assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { newEnglishPage, saveFailureShot } from './support.ts'
import { foldControlLayout, newEnglishPage, saveFailureShot, sessionPanelToggle, showSessionPanel } from './support.ts'
const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v3.jsonl', import.meta.url))
const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/background-job-list', import.meta.url))
const RUNNING_EXPECTED = join(SNAPSHOT_DIR, 'running.expected.md')
const SETTLED_EXPECTED = join(SNAPSHOT_DIR, 'settled.expected.md')
const SECTION = '[data-session-panel-section="background-jobs"]'
const MODE = webSnapshotMode()
const SEED_ID = 'background-job-list-web-e2e'
// A hold on a barrier file the test owns in the job's cwd: the process never
@@ -82,12 +83,18 @@ describe.skipIf(MODE === 'record')('web e2e: background job list', () => {
await scaffold?.close()
})
it('shows a running background job in the header without a refresh, then kills it from the two-press stop control', async () => {
it('shows a running background job in the Session panel without a refresh, then kills it from the two-press stop control', async () => {
let phase = 'running'
onTestFailed(() => saveFailureShot(page, `web-e2e-background-job-${phase}`))
// Polling for zero would pass at t=0 before delivery and prove nothing.
const trigger = page.getByRole('button', { name: '1 background job', exact: true })
expect(await trigger.count()).toBe(0)
const toggle = sessionPanelToggle(page)
const section = (await showSessionPanel(page)).locator(SECTION)
const list = section.getByRole('list')
// The mounted section keeps the roster stream open but renders no rows
// yet, so the panel hides it with its title. A one-shot check: polling for
// zero would pass at t=0 before delivery and prove nothing.
expect(await section.count()).toBe(1)
expect(await section.isVisible()).toBe(false)
expect(await list.count()).toBe(0)
const started = await executeToolFixture(scaffold.ctx, {
signal: new AbortController().signal,
@@ -101,31 +108,26 @@ describe.skipIf(MODE === 'record')('web e2e: background job list', () => {
if (matched === null) throw new Error(`background bash reported no job id: ${reported}`)
const jobId = brandString<JobId>(matched[0])
await trigger.waitFor({ timeout: 15_000 })
expect(await trigger.locator('[data-state="ongoing"]').count()).toBe(1)
expect(await trigger.locator('[data-icon="dsw-icon-chevron-down-outline-regular"]').count()).toBe(0)
await trigger.hover()
const list = page.getByRole('list', { name: 'Background jobs' })
const row = list.getByRole('listitem').first()
await row.waitFor({ timeout: 10_000 })
await row.waitFor({ timeout: 15_000 })
await expect.poll(() => row.textContent()).toContain(COMMAND)
expect(await trigger.getAttribute('aria-expanded')).toBe('true')
await row.hover()
await row.getByRole('button', { name: /Show live output/ }).focus()
await page.mouse.move(2, 2)
// Focusing a menu control pins it beyond the 120ms hover-leave deadline.
await page.waitForTimeout(180)
expect(await list.count()).toBe(1)
await trigger.click()
expect(await section.getByRole('heading', { name: 'Background jobs', level: 2 }).isVisible()).toBe(true)
expect(await row.locator('[data-state="ongoing"]').count()).toBe(1)
expect(await page.locator('[data-jobs-running]').count()).toBe(0)
// Hiding the panel unmounts the section, and a blue dot on the toggle reports the running job.
await toggle.click()
await list.waitFor({ state: 'detached' })
await trigger.click()
await list.waitFor()
await page.mouse.move(2, 2)
await page.waitForTimeout(180)
expect(await list.count()).toBe(1)
expect(await trigger.getAttribute('aria-label')).toBe('1 background job')
const dot = page.locator('[data-jobs-running]')
await dot.waitFor()
await page.getByRole('button', { name: 'Session panel Background jobs running: 1', exact: true }).waitFor()
expect(await dot.evaluate(element => getComputedStyle(element).width)).toBe('6px')
// Showing it again lists the live job, and the dot goes away.
await showSessionPanel(page)
await row.waitFor({ timeout: 10_000 })
expect(await toggle.getAttribute('aria-expanded')).toBe('true')
await dot.waitFor({ state: 'detached' })
const running = await captureStableAria(page, '[class*="menu"]', scaffold.workspaceCwd, { runningJobs: 'keep' })
const running = await captureStableAria(page, SECTION, scaffold.workspaceCwd)
await compareOrRefreshGolden(RUNNING_EXPECTED, running, MODE)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
@@ -133,151 +135,171 @@ describe.skipIf(MODE === 'record')('web e2e: background job list', () => {
phase = 'settled'
// The whole human path: arm, confirm, job.kill, registry kill, jobs
// frames flipping the row — no registry call from the test.
const stop = page.locator('[data-kill-state]')
const stop = section.locator('[data-kill-state]')
await stop.waitFor({ timeout: 10_000 })
await stop.click()
await expect.poll(() => stop.getAttribute('data-kill-state')).toBe('armed')
await stop.click()
expect(await trigger.getAttribute('aria-label')).toBe('1 background job')
// The unclaimed report's reason lands in the settled row's detail.
await expect.poll(
() => page.getByRole('list', { name: 'Background jobs' }).textContent(),
{ timeout: 15_000 },
).toContain('cancelled by the user')
// The unclaimed report's reason lands in the settled row's detail; presses
// inside the overlay leave it open.
await expect.poll(() => list.textContent(), { timeout: 15_000 }).toContain('cancelled by the user')
expect(await toggle.getAttribute('aria-expanded')).toBe('true')
expect(scaffold.ctx.jobs.get(jobId, agent.id).status).toBe('killed')
const settled = await captureStableAria(page, '[class*="menu"]', scaffold.workspaceCwd)
const settled = await captureStableAria(page, SECTION, scaffold.workspaceCwd)
await compareOrRefreshGolden(SETTLED_EXPECTED, settled, MODE)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
}, 90_000)
it('keeps the open list above the expanded right sidebar and in the header Tab order', async () => {
it('opens the section over the conversation beside the expanded right sidebar and closes it with Escape', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-background-job-right-sidebar'))
const trigger = page.getByRole('button', { name: '1 background job', exact: true })
if (await trigger.getAttribute('aria-expanded') === 'true') await trigger.click()
const toggle = sessionPanelToggle(page)
await page.getByRole('button', { name: 'Open right sidebar' }).click()
const sidebar = page.locator('[data-rightbar-col]')
// A toggle holds data-animating on the frame until its tracks settle.
await expect.poll(() => sidebar.evaluate(column => column.parentElement?.hasAttribute('data-animating'))).toBe(false)
await trigger.click()
const list = page.getByRole('list', { name: 'Background jobs' })
await list.waitFor({ timeout: 10_000 })
// The list crosses into the sidebar column, so the hit test below covers it.
const [menuBox, sidebarBox] = await Promise.all([list.boundingBox(), sidebar.boundingBox()])
if (menuBox === null || sidebarBox === null) throw new Error('job list geometry is unavailable')
expect(menuBox.x + menuBox.width).toBeGreaterThan(sidebarBox.x)
// Every corner of the list hit-tests to the list itself; the inset clears its rounded corners.
const covered = await list.evaluate((menu) => {
const rect = menu.getBoundingClientRect()
const panel = await showSessionPanel(page)
expect(await panel.getAttribute('data-session-panel')).toBe('overlay')
const section = panel.locator(SECTION)
const settledToggle = section.getByRole('button', { name: 'Finished 1', exact: true })
await settledToggle.waitFor({ timeout: 10_000 })
// The overlay stays in the conversation body, clear of the sidebar column.
const [panelBox, sidebarBox] = await Promise.all([panel.boundingBox(), sidebar.boundingBox()])
if (panelBox === null || sidebarBox === null) throw new Error('Session panel geometry is unavailable')
expect(panelBox.x + panelBox.width).toBeLessThanOrEqual(sidebarBox.x)
// Every corner of the panel hit-tests to the panel itself; the inset clears its rounded corners.
const covered = await panel.evaluate((element) => {
const rect = element.getBoundingClientRect()
const inset = 20
const points: Array<[number, number]> = [
[rect.left + inset, rect.top + inset], [rect.right - inset, rect.top + inset],
[rect.left + inset, rect.bottom - inset], [rect.right - inset, rect.bottom - inset],
]
return points.filter(([x, y]) => !menu.contains(document.elementFromPoint(x, y)))
return points.filter(([x, y]) => !element.contains(document.elementFromPoint(x, y)))
})
expect(covered).toEqual([])
// Keyboard order matches the in-place list: the trigger leads into the
// list, and Tab off its last control reaches the control after the trigger.
const after = await trigger.evaluate((node) => {
const all = [...document.querySelectorAll<HTMLElement>('button, a[href], [tabindex]:not([tabindex="-1"])')]
const outside = all.filter(el => el.closest('[aria-label="Background jobs"]') === null && el.tabIndex >= 0)
return outside[outside.indexOf(node as HTMLElement) + 1]?.outerHTML.slice(0, 120)
})
expect(after).toMatch(/^<button/)
await trigger.focus()
await page.keyboard.press('Tab')
expect(await list.evaluate(menu => menu.contains(document.activeElement))).toBe(true)
const controls = await list.evaluate(menu => menu.querySelectorAll('button:not(:disabled)').length)
for (let i = 1; i < controls; i += 1) await page.keyboard.press('Tab')
await page.keyboard.press('Tab')
expect(await page.evaluate(() => document.activeElement?.outerHTML.slice(0, 120))).toBe(after)
await trigger.focus()
await page.keyboard.press('Tab')
// Escape from a control in the section closes the overlay and returns focus to the toggle.
await settledToggle.focus()
await page.keyboard.press('Escape')
await list.waitFor({ state: 'detached', timeout: 10_000 })
expect(await trigger.evaluate(node => node === document.activeElement)).toBe(true)
await panel.waitFor({ state: 'detached', timeout: 10_000 })
expect(await toggle.getAttribute('aria-expanded')).toBe('false')
expect(await toggle.evaluate(node => node === document.activeElement)).toBe(true)
}, 60_000)
it('keeps the compact Layers trigger focused and opens jobs only on click or keyboard', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-background-job-compact-trigger'))
const trigger = page.getByRole('button', { name: '1 background job', exact: true })
const list = page.getByRole('list', { name: 'Background jobs' })
const count = trigger.locator('[data-job-count]')
it('fits the section into the narrow overlay and closes it on a press outside', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-background-job-narrow-overlay'))
const toggle = sessionPanelToggle(page)
const viewport = page.viewportSize()!
await page.getByRole('button', { name: 'Collapse right sidebar', exact: true }).click()
await expect.poll(() => page.locator('[data-rightbar-col]')
.evaluate(column => column.parentElement?.hasAttribute('data-animating'))).toBe(false)
await page.getByRole('button', { name: 'Open right sidebar', exact: true }).waitFor()
await page.mouse.move(2, 2)
expect(await count.isVisible()).toBe(true)
expect(await trigger.locator('[data-icon="dsw-icon-layers-outline-regular"]').count()).toBe(1)
expect(await trigger.locator('svg').count()).toBe(1)
expect(await trigger.locator('svg').evaluate((element) => {
const bounds = element.getBoundingClientRect()
return [bounds.width, bounds.height]
})).toEqual([14, 14])
await trigger.focus()
const original = await trigger.elementHandle()
if (original === null) throw new Error('Background jobs trigger is missing')
await toggle.focus()
const original = await toggle.elementHandle()
if (original === null) throw new Error('Session panel toggle is missing')
try {
await page.setViewportSize({ width: 390, height: 700 })
await expect.poll(() => count.evaluate(element => getComputedStyle(element).display)).toBe('none')
expect(await original.evaluate(element => element.isConnected && element === document.activeElement)).toBe(true)
const expandSidebar = page.locator('[data-sidebar-right-expand]')
const compactStyles = await Promise.all([trigger, expandSidebar].map(control => control.evaluate((element) => {
const style = getComputedStyle(element)
const bounds = element.getBoundingClientRect()
const icon = element.querySelector('svg')!.getBoundingClientRect()
return { width: bounds.width, height: bounds.height, padding: style.padding, radius: style.borderRadius,
color: style.color, iconWidth: icon.width, iconHeight: icon.height }
})))
expect(compactStyles[0]).toEqual(compactStyles[1])
expect(compactStyles[0]).toMatchObject({ width: 28, height: 28, padding: '0px', iconWidth: 15, iconHeight: 15 })
expect(await trigger.evaluate(element => getComputedStyle(element.closest('[data-slot="conversation.session.header.actions"]')!.parentElement!).gap)).toBe('8px')
await expandSidebar.hover()
const expandHover = await expandSidebar.evaluate((element) => {
const style = getComputedStyle(element)
return { background: style.backgroundColor, color: style.color }
})
await expect.poll(() => trigger.evaluate((element) => {
const bounds = element.getBoundingClientRect()
return element.contains(document.elementFromPoint(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2))
})).toBe(true)
await trigger.hover()
expect(await trigger.evaluate((element) => {
const style = getComputedStyle(element)
return { background: style.backgroundColor, color: style.color }
})).toEqual(expandHover)
expect(expandHover.background).not.toBe('rgba(0, 0, 0, 0)')
// Compact hover stays closed beyond the wide trigger's 150ms open deadline.
await page.waitForTimeout(200)
expect(await list.count()).toBe(0)
await trigger.click()
await list.waitFor()
const panel = await showSessionPanel(page)
expect(await panel.getAttribute('data-session-panel')).toBe('overlay')
const list = panel.locator(SECTION).getByRole('list')
await list.getByRole('button', { name: 'Finished 1', exact: true }).waitFor()
await trigger.click()
await list.waitFor({ state: 'detached' })
await trigger.press('ArrowDown')
await list.waitFor()
expect(await list.getByRole('button').first().evaluate(element => element === document.activeElement)).toBe(true)
await page.mouse.move(2, 2)
// Keyboard activation remains pinned after leaving both trigger and menu.
await page.waitForTimeout(180)
expect(await list.count()).toBe(1)
await page.mouse.click(2, 2)
await list.waitFor({ state: 'detached' })
expect(await trigger.getAttribute('aria-expanded')).toBe('false')
// The long command truncates inside its row instead of widening the panel past the viewport.
const fit = await panel.evaluate((element) => {
const rect = element.getBoundingClientRect()
const rows = [...element.querySelectorAll<HTMLElement>('[data-jobs-section] li')]
return {
inViewport: rect.left >= 0 && rect.right <= innerWidth,
panelOverflow: element.scrollWidth > element.clientWidth,
rowOverflow: rows.some(row => row.getBoundingClientRect().right > rect.right),
}
})
expect(fit).toEqual({ inViewport: true, panelOverflow: false, rowOverflow: false })
// The overlay's inline margin is transcript: a press there is outside the panel.
const box = await panel.boundingBox()
if (box === null) throw new Error('Session panel geometry is unavailable')
expect(box.x).toBeGreaterThan(4)
await page.mouse.click(box.x / 2, box.y + box.height / 2)
await panel.waitFor({ state: 'detached' })
expect(await toggle.getAttribute('aria-expanded')).toBe('false')
} finally {
await page.keyboard.press('Escape')
await page.setViewportSize(viewport)
await original.dispose()
}
})
it('marks a job that finished with a nonzero exit code with the warning dot', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-background-job-nonzero-exit'))
await executeToolFixture(scaffold.ctx, {
signal: new AbortController().signal,
callId: brandString<ToolCallId>('background-job-list-nonzero-e2e'),
name: 'bash',
arguments: { command: 'exit 3', description: 'Exit with a failure', run_in_background: true },
agent: scaffold.ctx.agents.list()[0]!,
})
const panel = await showSessionPanel(page)
const row = panel.locator(SECTION).getByRole('listitem').filter({ hasText: 'exit 3' })
await row.getByText('bash · exit code: 3', { exact: true }).waitFor({ timeout: 15_000 })
expect(await row.locator('[data-state]').getAttribute('data-state')).toBe('warning')
})
it('holds back the rows past five in each group behind its fold control and keeps the choice while the panel is hidden', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-background-job-folds'))
// Seven jobs on the suite's barrier file: they run until this case, or `afterAll`, releases it.
for (let index = 0; index < 7; index++) {
await executeToolFixture(scaffold.ctx, {
signal: new AbortController().signal,
callId: brandString<ToolCallId>(`background-job-list-fold-${String(index)}`),
name: 'bash',
arguments: { command: `: fold-${String(index)}; ${COMMAND}`, description: 'Hold a slot for the fold', run_in_background: true },
agent,
})
}
const section = (await showSessionPanel(page)).locator(SECTION)
const rows = section.locator('[data-job-row]')
const liveRows = section.locator('[data-job-row]:has([data-state="ongoing"])')
const folds = section.locator('[data-session-panel-row="fold"]')
const names = async (): Promise<(string | undefined)[]> => (await liveRows.allTextContents()).map(text => /fold-\d/.exec(text)?.[0])
// The five jobs started last show, the most recent first, and the group's fold control follows them.
await expect.poll(names, { timeout: 20_000 }).toEqual(['fold-6', 'fold-5', 'fold-4', 'fold-3', 'fold-2'])
expect(await folds.allTextContents()).toEqual(['Show 2 more running'])
expect(await section.locator('li:has([data-session-panel-row="fold"])').count()).toBe(1)
// The control is one more row: the row height, its chevron under the state marks, its text under the commands.
expect(await foldControlLayout(folds.first(), liveRows.first(), '[data-job-label]'))
.toEqual({ heights: [28, 28], chevronOffset: 0, textOffset: 0, fontSize: '12px', expanded: 'false' })
const more = section.getByRole('button', { name: 'Show 2 more running (running background jobs)', exact: true })
await more.click()
await expect.poll(names).toEqual(['fold-6', 'fold-5', 'fold-4', 'fold-3', 'fold-2', 'fold-1', 'fold-0'])
const less = section.getByRole('button', { name: 'Show less (running background jobs)', exact: true })
expect([await less.textContent(), await less.getAttribute('aria-expanded')]).toEqual(['Show less', 'true'])
// The same button stays under the pointer's focus across the change.
expect(await less.evaluate(element => element === document.activeElement)).toBe(true)
// The choice is the Session's: hiding the panel unmounts the section, and showing it again lists every live row.
await sessionPanelToggle(page).click()
await section.getByRole('list').waitFor({ state: 'detached' })
await showSessionPanel(page)
await expect.poll(() => liveRows.count(), { timeout: 10_000 }).toBe(7)
// Released, the jobs settle. With nothing live the settled group opens, with its five latest rows and its own control.
await writeFile(join(scaffold.workspaceCwd, RELEASE), '')
await expect.poll(() => liveRows.count(), { timeout: 30_000 }).toBe(0)
const header = section.getByRole('button', { name: /^Finished \d+$/ })
await expect.poll(async () => Number(/\d+/.exec(await header.textContent() ?? '')?.[0]), { timeout: 15_000 }).toBeGreaterThanOrEqual(7)
const settled = Number(/\d+/.exec(await header.textContent() ?? '')?.[0])
expect(await header.getAttribute('aria-expanded')).toBe('true')
await expect.poll(() => rows.count()).toBe(5)
expect(await folds.allTextContents()).toEqual([`Show ${String(settled - 5)} more finished`])
expect(await foldControlLayout(folds.first(), rows.first(), '[data-job-label]'))
.toEqual({ heights: [28, 28], chevronOffset: 0, textOffset: 0, fontSize: '12px', expanded: 'false' })
await folds.first().getByRole('button').click()
await expect.poll(() => rows.count()).toBe(settled)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
}, 120_000)
it('keeps its snapshot inventory closed', async () => {
await assertFixtureInventory(SNAPSHOT_DIR, ['running.expected.md', 'settled.expected.md'])
})
+2 -3
View File
@@ -10,7 +10,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session'
import type {} from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-subagent'
import { launchWebScaffold, selectedSessionFixture, webSnapshotMode, type WebScaffold } from './scaffold.ts'
import { connectFreshWorkspace, newEnglishPage, openSettings, saveFailureShot } from './support.ts'
import { connectFreshWorkspace, newEnglishPage, openSettings, saveFailureShot, showSessionPanel } from './support.ts'
const BASE_FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v3.jsonl', import.meta.url))
const LABEL = 'event-sourcing researcher'
@@ -104,8 +104,7 @@ describe('web e2e: composer paste routing', () => {
parent,
})
await waitForAgentToSettle(scaffold, started.childId)
await page.getByRole('button', { name: '1 subagent', exact: true }).hover()
await page.getByRole('treeitem', { name: new RegExp(LABEL) })
await (await showSessionPanel(page)).getByRole('treeitem', { name: new RegExp(LABEL) })
.getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).click()
await page.locator('[data-sidebar-chat] [data-composer-card]').waitFor({ timeout: 15_000 })
})
@@ -1,6 +1,5 @@
- navigation "Session hierarchy": Seeded turn
- text: Minimal mode
- button "1 subagent"
- button "Session panel"
- button "More actions"
- button "Open right sidebar"
@@ -1,4 +1,3 @@
- button "本地变更"
- text: HEAD → origin/main
- button "查看本会话的变更:1 个文件,新增 1 行,删除 0 行": +1 −0 1 个文件
- button "创建变更请求"
- button "本地变更 · 1 个文件,新增 1 行,删除 0 行": 本地变更 · 1 个文件
- text: +1 −0
- button "本地变更操作"
@@ -1,21 +1,22 @@
- text: feat 项目目录
- button "复制项目目录路径"
- button "本地变更"
- text: HEAD → origin/main
- button "查看本会话的变更:4 个文件,新增 4 行,删除 1 行": +4 −1 4 个文件
- heading "本会话的变更请求 · 1" [level=3]
- button "刷新状态"
- list:
- listitem:
- img "变更请求状态:需要处理"
- link "Add the pull request panel":
- /url: https://github.com/octo/demo/pull/7
- text: "#7 feat → main"
- button "在浏览器中打开"
- button "复制变更请求链接"
- 'button "从本会话移除 #7"'
- 'button "收起 #7" [expanded]'
- button "检查 已加载 1 项检查,仍有更多"
- button "评审 等待评审"
- text: 合并 无冲突
- 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论
- complementary "会话面板":
- region "环境":
- heading "环境" [level=2]
- text: workspace {{cwd}} feat 项目目录
- button "本地变更 · 4 个文件,新增 4 行,删除 1 行": 本地变更 · 4 个文件
- text: +4 −1
- button "本地变更操作"
- region "变更请求":
- heading "变更请求" [level=2]
- text: "1"
- list:
- listitem:
- img "变更请求状态:需要处理"
- link "Add the pull request panel":
- /url: https://github.com/octo/demo/pull/7
- text: "#7 feat → main"
- button "#7 的操作"
- 'button "收起 #7" [expanded]'
- button "检查 已加载 1 项检查,仍有更多"
- button "评审 等待评审"
- text: 合并 无冲突
- 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论
@@ -1,4 +1,3 @@
- button "Local changes"
- text: HEAD → origin/main
- 'button "View the changes of this Session: 60 files, 60 lines added, 0 lines deleted"': +60 −0 60 files
- button "Create change request"
- button "Local changes · 60 files, 60 lines added, 0 lines deleted": Local changes · 60 files
- text: +60 −0
- button "Local changes actions"
@@ -1,18 +1,19 @@
- text: dsh-{{worktree}} 工作树 · 基于 release
- button "复制工作树路径"
- heading "本会话的变更请求 · 1" [level=3]
- button "刷新状态"
- list:
- listitem:
- img "变更请求状态:需要处理"
- link "Add the pull request panel":
- /url: https://github.com/octo/demo/pull/7
- text: "#7 feat → main"
- button "在浏览器中打开"
- button "复制变更请求链接"
- 'button "从本会话移除 #7"'
- 'button "收起 #7" [expanded]'
- button "检查 已加载 1 项检查,仍有更多"
- button "评审 等待评审"
- text: 合并 无冲突
- 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论
- complementary "会话面板":
- region "环境":
- heading "环境" [level=2]
- text: dsh-{{worktree}} {{cwd}}/workspace/.agents/worktrees dsh-{{worktree}} 工作树 · 基于 release
- region "变更请求":
- heading "变更请求" [level=2]
- text: "1"
- list:
- listitem:
- img "变更请求状态:需要处理"
- link "Add the pull request panel":
- /url: https://github.com/octo/demo/pull/7
- text: "#7 feat → main"
- button "#7 的操作"
- 'button "收起 #7" [expanded]'
- button "检查 已加载 1 项检查,仍有更多"
- button "评审 等待评审"
- text: 合并 无冲突
- 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 1 条未解决讨论
@@ -3,9 +3,7 @@
- link "Add the pull request panel":
- /url: https://github.com/octo/demo/pull/7
- text: "#7 feat → main"
- button "在浏览器中打开"
- button "复制变更请求链接"
- 'button "从本会话移除 #7"'
- button "#7 的操作"
- 'button "收起 #7" [expanded]'
- button "检查 已加载 1 项检查,仍有更多"
- button "评审 等待评审"
@@ -1 +0,0 @@
- button "代码审查和变更 查看代码变更与本会话的变更请求"
@@ -1,35 +0,0 @@
# Background jobs above the Browser dock
```json
{
"collapsed": {
"dockMode": "push",
"bodyMounted": true,
"fixed": true,
"anchored": true,
"viewportBounded": true,
"overlapsBrowser": true,
"aboveBrowser": true
},
"expanded": {
"dockMode": "push",
"bodyMounted": true,
"fixed": true,
"anchored": true,
"viewportBounded": true,
"overlapsBrowser": true,
"aboveBrowser": true
},
"resized": {
"dockMode": "push",
"bodyMounted": true,
"fixed": true,
"anchored": true,
"viewportBounded": true,
"overlapsBrowser": true,
"aboveBrowser": true
},
"escapeRestoresFocus": true,
"outsideDismisses": true
}
```
@@ -0,0 +1,38 @@
# Background jobs beside the Browser dock
```json
{
"collapsed": {
"dockMode": "push",
"presentation": "overlay",
"insideBody": true,
"clearOfBrowser": true,
"clearOfComposer": true,
"viewportBounded": true,
"sectionShown": true,
"onTop": true
},
"expanded": {
"dockMode": "push",
"presentation": "overlay",
"insideBody": true,
"clearOfBrowser": true,
"clearOfComposer": true,
"viewportBounded": true,
"sectionShown": true,
"onTop": true
},
"resized": {
"dockMode": "push",
"presentation": "overlay",
"insideBody": true,
"clearOfBrowser": true,
"clearOfComposer": true,
"viewportBounded": true,
"sectionShown": true,
"onTop": true
},
"escapeRestoresFocus": true,
"outsideDismisses": true
}
```
@@ -43,7 +43,7 @@
- code: "@deepseek-ai/dsh-experimental-forge-session"
- text: 已关闭
- listitem:
- text: 变更请求面板 在侧栏标签页中显示会话的变更请求,并让新会话可以在工作树中开始。
- text: 变更请求面板 在会话面板中显示会话的变更请求,并让新会话可以在工作树中开始。
- code: forge-panel
- code: "@deepseek-ai/dsh-experimental-client-ui-forge"
- text: 已关闭
@@ -1,8 +1,6 @@
- banner:
- navigation "Session hierarchy": Delegate a background job.
- button "1 subagent"
- button "1 background job"
- button "Session panel"
- 'button "Session panel Subagents running: 1 Background jobs running: 1"'
- button "More actions"
- button "Open right sidebar"
- tablist:
@@ -2,12 +2,12 @@
- tree "Subagent sessions":
- treeitem "historical researcher migration-catalog-child · continuable · not running" [level=1]:
- text: historical researcher migration-catalog-child
- text: historical researcher
- button "Open historical researcher in sidebar"
# After opening the child
- tree "Subagent sessions":
- treeitem "historical editor migration-catalog-grandchild · continuable · not running" [level=1]:
- text: historical editor migration-catalog-grandchild
- text: historical editor
- button "Open historical editor in sidebar"
+3 -5
View File
@@ -25,7 +25,7 @@ import { sessionFixtureName } from '@deepseek-ai/dsh-session-snapshot'
import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent'
import { createChatScrollFixture, type ChatScrollFixture } from './chat-scroll-fixture.ts'
import { launchWebScaffold, parseSeedFixture, seedSession, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts'
import { newEnglishPage, openSettings } from './support.ts'
import { newEnglishPage, openSettings, showSessionPanel } from './support.ts'
declare global {
interface Window {
@@ -621,10 +621,8 @@ async function prepareWorld(browser: Browser, scenario: Case, scaffold: WebScaff
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await openSessionBySearch(page, parentFixture.markers.user(1))
await choosePreferences(page, scenario)
const trigger = page.getByRole('button', { name: '1 subagent', exact: true })
await trigger.waitFor({ timeout: 15_000 })
await trigger.hover()
const openAside = page.getByRole('treeitem', { name: new RegExp(CHILD_LABEL) })
const panel = await showSessionPanel(page)
const openAside = panel.getByRole('treeitem', { name: new RegExp(CHILD_LABEL) })
.getByRole('button', { name: /^Open .+ in sidebar$/u })
await expect.poll(() => openAside.count()).toBe(1)
await openAside.click()
+136 -110
View File
@@ -17,7 +17,9 @@ import {
captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, readPersistedEvents, watchConsole,
webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { connectFreshWorkspaceZh, saveFailureShot, writeComposerDraft, ZH_BROWSER_LOCALE } from './support.ts'
import {
connectFreshWorkspaceZh, hideSessionPanel, saveFailureShot, sessionPanelToggle, showSessionPanel, writeComposerDraft, ZH_BROWSER_LOCALE,
} from './support.ts'
declare global {
interface Window {
@@ -639,6 +641,48 @@ async function sendPrompt(page: Page, scaffold: WebScaffold): Promise<{ readonly
return { prompt, settled }
}
/**
* Choose an item from the More menu of a change request card.
* @param page - the page under test.
* @param change - the card.
* @param name - the card's name in the menu button, such as `#7`.
* @param item - the item to choose.
*/
async function chooseCardAction(page: Page, change: Locator, name: string, item: string): Promise<void> {
await change.getByRole('button', { name: `${name} 的操作`, exact: true }).click()
await page.getByRole('menuitem', { name: item, exact: true }).click()
}
/** Accessible name of the panel toggle while a change request needs attention. */
const TOGGLE_ATTENTION = '会话面板 本会话的变更请求需要处理'
/**
* A Session panel row as the panel's row rules lay it out: its height, how far
* the centers of its icon and menu columns sit from its start and end edges
* (null for a part that takes no room), and the part a press reaches at its
* start edge and on its trailing part.
*/
function panelRowLayout(row: Locator) {
return row.evaluate((element) => {
const box = element.getBoundingClientRect()
const rectOf = (part: string): DOMRect | null => {
const rect = element.querySelector(`[data-row-part="${part}"]`)?.getBoundingClientRect()
return rect === undefined || rect.width === 0 ? null : rect
}
const partAt = (x: number, y: number): string | null =>
document.elementFromPoint(x, y)?.closest('[data-row-part]')?.getAttribute('data-row-part') ?? null
const [icon, trailing, menu] = [rectOf('icon'), rectOf('trailing'), rectOf('menu')]
return {
marked: element.hasAttribute('data-session-panel-row'),
height: box.height,
iconCenter: icon === null ? null : icon.left + icon.width / 2 - box.left,
menuCenter: menu === null ? null : box.right - (menu.left + menu.width / 2),
startPress: partAt(box.left + 2, box.top + 2),
trailingPress: trailing === null ? null : partAt(trailing.left + trailing.width / 2, trailing.top + trailing.height / 2),
}
})
}
function worktreeRecords(events: readonly SessionEvent[]): unknown[] {
return events.flatMap((event) => {
const record = pluginRecordOf(event)
@@ -656,9 +700,15 @@ it.skipIf(MODE === 'record')('reads local Git with full access when the sandbox
const { settled } = await sendPrompt(page, scaffold)
const sessionId = await settled
await page.getByText('LIGHTHOUSE', { exact: true }).waitFor()
await page.locator('[data-forge-header]').click()
const panel = page.locator('[data-forge-panel]')
await panel.getByText('无法读取 Git 信息', { exact: true }).waitFor({ timeout: 20_000 })
const panel = await showSessionPanel(page)
const failed = panel.locator('[data-forge-checkout][data-failed]')
await failed.getByText('无法读取 Git 信息', { exact: true }).waitFor({ timeout: 20_000 })
// The failure's reason shows from the info button, also on a press as touch screens need; another press hides it.
const reason = failed.getByRole('button', { name: '查看原因', exact: true })
await reason.click()
await expect.poll(async () => (await page.getByRole('tooltip').textContent())?.trim().length ?? 0).toBeGreaterThan(0)
await reason.click()
await expect.poll(() => page.getByRole('tooltip').count()).toBe(0)
const permission = page.locator('button[aria-label^="访问模式"]').first()
await permission.click()
@@ -666,16 +716,23 @@ it.skipIf(MODE === 'record')('reads local Git with full access when the sandbox
const confirmation = page.getByRole('dialog', { name: '确认启用完全权限?' })
await confirmation.getByRole('checkbox', { name: '我已了解风险,并愿意继续' }).check()
await confirmation.getByRole('button', { name: '启用完全权限' }).click()
await showSessionPanel(page)
const local = page.locator('[data-forge-local]')
await local.getByRole('button', { name: '查看本会话的变更:1 个文件,新增 1 行,删除 0 行', exact: true }).waitFor({ timeout: 20_000 })
await local.getByRole('button', { name: '本地变更 · 1 个文件,新增 1 行,删除 0 行', exact: true }).waitFor({ timeout: 20_000 })
await compareOrRefreshGolden(join(EXPECTED, 'full-access.expected.md'), await captureStableAria(page, '[data-forge-local]', scaffold.workspaceCwd), MODE)
await local.getByRole('button', { name: '查看本会话的变更:1 个文件,新增 1 行,删除 0 行', exact: true }).click()
// The panel lays the row out by its marks: one 28px line with the icon and the More button on the panel columns.
// The body is the row's button, so a press at the row's edge reaches it, while the diff size stays above it.
expect(await panelRowLayout(local)).toEqual({ marked: true, height: 28, iconCenter: 14, menuCenter: 14, startPress: 'body', trailingPress: 'trailing' })
// This composition registers no directory menu entries: the checkout row's menu takes no room, and its body is not a button.
expect(await panelRowLayout(panel.locator('[data-forge-checkout]')))
.toEqual({ marked: true, height: 28, iconCenter: 14, menuCenter: null, startPress: null, trailingPress: 'trailing' })
await local.getByRole('button', { name: '本地变更 · 1 个文件,新增 1 行,删除 0 行', exact: true }).click()
await page.locator('[data-forge-diff-file="README.md"]').getByText('changed', { exact: true }).waitFor()
await permission.click()
await page.getByRole('menuitem', { name: '工作区内修改', exact: true }).click()
if (!await panel.isVisible()) await page.locator('[data-forge-header]').click()
await panel.getByText('无法读取 Git 信息', { exact: true }).waitFor({ timeout: 20_000 })
await showSessionPanel(page)
await failed.getByText('无法读取 Git 信息', { exact: true }).waitFor({ timeout: 20_000 })
await expect.poll(async () => (await readPersistedEvents(scaffold, sessionId))
.filter(event => event.type === 'sandbox/mode').map(event => event.data.mode).slice(-2))
.toEqual(['danger-full-access', 'workspace-write'])
@@ -691,8 +748,8 @@ it.skipIf(MODE === 'record')('reports incomplete filter configuration and retrie
const { settled } = await sendPrompt(page, scaffold)
await settled
await page.getByText('LIGHTHOUSE', { exact: true }).waitFor()
await page.locator('[data-forge-header]').click()
const openChanges = page.locator('[data-forge-local]').getByRole('button', { name: '查看本会话的变更:1 个文件,新增 1 行,删除 0 行', exact: true })
await showSessionPanel(page)
const openChanges = page.locator('[data-forge-local]').getByRole('button', { name: '本地变更 · 1 个文件,新增 1 行,删除 0 行', exact: true })
await openChanges.waitFor({ timeout: 20_000 })
const key = `filter.${'long'.repeat(200)}.clean`
await git(project, 'config', key, 'cat')
@@ -716,9 +773,8 @@ it.skipIf(MODE === 'record')('reports incomplete filter configuration and retrie
* @param sessionId - Session whose binding records are read.
*/
async function expectNumberedReference({ scaffold, page, project, tripwire }: PanelLaunch, sessionId: SessionId): Promise<void> {
const header = page.locator('[data-forge-header]')
await expect.poll(() => header.getAttribute('aria-label'), { timeout: 20_000 }).toBe('本会话的变更请求需要处理')
await header.click()
await page.getByRole('button', { name: TOGGLE_ATTENTION, exact: true }).waitFor({ timeout: 20_000 })
await showSessionPanel(page)
const change = page.locator(`[data-forge-change="${PULL}"]`)
await change.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 })
await change.getByText('等待评审', { exact: true }).waitFor()
@@ -800,9 +856,8 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
// A change request bound the way a `gh pr create` result binds one.
scaffold.ctx.forgeSession.track(session, PULL)
const header = page.locator('[data-forge-header]')
await expect.poll(() => header.getAttribute('aria-label'), { timeout: 20_000 }).toBe('本会话的变更请求需要处理')
expect(await header.getAttribute('aria-pressed')).toBe('false')
await page.getByRole('button', { name: TOGGLE_ATTENTION, exact: true }).waitFor({ timeout: 20_000 })
expect(await sessionPanelToggle(page).getAttribute('aria-expanded')).toBe('false')
// The Session row marks the worktree and its change request's state, and its hover card names both.
const row = page.locator(`[data-row-key="session:${sessionId}"]`)
@@ -820,9 +875,7 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
await captureStableAria(page, '[data-forge-session-hover]', scaffold.workspaceCwd, { replacements: [[branch, 'dsh-{{worktree}}']] }), MODE)
await page.mouse.move(0, 0)
await rowHover.waitFor({ state: 'detached' })
await header.click()
await expect.poll(() => header.getAttribute('aria-pressed')).toBe('true')
const panel = page.locator('[data-forge-panel]')
const panel = await showSessionPanel(page)
const checkout = panel.locator('[data-forge-checkout]')
const checkoutName = checkout.getByText(branch, { exact: true })
await checkoutName.waitFor({ timeout: 20_000 })
@@ -837,7 +890,9 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
await change.getByText('等待评审', { exact: true }).waitFor()
// The random branch suffix can read as a duration, so the branch is replaced before the capture normalizes durations.
await compareOrRefreshGolden(join(EXPECTED, 'panel.expected.md'),
await captureStableAria(page, '[data-forge-panel]', scaffold.workspaceCwd, { replacements: [[branch, 'dsh-{{worktree}}']] }), MODE)
await captureStableAria(page, '[data-session-panel]', scaffold.workspaceCwd, {
replacements: [[branch, 'dsh-{{worktree}}'], [abbreviateHomePath(scaffold.workspaceCwd, homedir()), '{{cwd}}']],
}), MODE)
const beforeChecks = (await readFile(join(root, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])
expect(beforeChecks.some(args => args.includes('id=rollup-7'))).toBe(false)
const checksRow = change.getByRole('button', { name: /^检查/ })
@@ -856,18 +911,18 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
const record = pluginRecordOf(event)
return record?.type === 'plugin:forge-session/binding' ? [record.data] : []
})
await change.getByRole('button', { name: '从本会话移除 #7', exact: true }).click()
await chooseCardAction(page, change, '#7', '从本会话移除')
await change.waitFor({ state: 'detached' })
await panel.getByText('本会话还没有变更请求', { exact: true }).waitFor()
await panel.locator('[data-session-panel-section="change-requests"]').waitFor({ state: 'hidden' })
await page.getByRole('alert').filter({ hasText: '已从本会话移除 #7' }).getByRole('button', { name: '撤销', exact: true }).click()
await showSessionPanel(page)
await title.waitFor({ timeout: 20_000 })
await expect.poll(bindings).toEqual([{ action: 'track', url: PULL }, { action: 'dismiss', url: PULL }, { action: 'track', url: PULL }])
const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])
expect(calls).toContainEqual(['auth', 'status', '--hostname', 'github.com'])
expect(calls.some(args => args[0] === 'api' && args[1] === 'graphql' && args.includes('--hostname'))).toBe(true)
await header.click()
await expect.poll(() => header.getAttribute('aria-pressed')).toBe('false')
await hideSessionPanel(page)
// Removing the worktree outside the Session holds the next message in the inbox until the worktree is restored.
await git(project, 'worktree', 'remove', '--force', directory)
@@ -880,6 +935,7 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
const missing = page.locator('[data-forge-missing]')
await missing.getByText(`可以在原位置恢复分支 ${branch} 的工作树。删除前未提交的修改无法恢复`, { exact: true }).waitFor()
await missing.getByText('恢复工作树或在项目目录继续后,消息会接着发送', { exact: true }).waitFor()
await showSessionPanel(page)
await expect.poll(() => checkout.getAttribute('data-missing')).toBe('')
const turns = async (): Promise<number> => (await readPersistedEvents(scaffold, sessionId)).filter(event => event.type === 'turn/start').length
expect(await turns()).toBe(1)
@@ -888,6 +944,7 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me
await page.getByRole('alert').filter({ hasText: '工作树已恢复' }).waitFor()
expect(await git(directory, 'rev-parse', '--abbrev-ref', 'HEAD')).toBe(branch)
expect(await git(directory, 'rev-parse', 'HEAD')).toBe(baseCommit)
await showSessionPanel(page)
await expect.poll(() => checkout.getAttribute('data-missing')).toBeNull()
// The waiting message goes on in the restored worktree.
await page.getByText(FOLLOW_UP_REPLY, { exact: true }).waitFor({ timeout: 20_000 })
@@ -924,8 +981,7 @@ it.skipIf(MODE === 'record')('keeps the first message waiting when the worktree
expect(worktreeRecords(events)).toEqual([{ action: 'request', from: 'main' }, { action: 'request', from: 'release' }, { action: 'cancel' }])
expect(events.filter(event => event.type === 'turn/start')).toHaveLength(1)
expect(events.some(event => event.type === 'user/message' && event.data.source.kind === 'working-directory')).toBe(false)
await page.locator('[data-forge-header]').click({ timeout: 20_000 })
const checkout = page.locator('[data-forge-panel] [data-forge-checkout]')
const checkout = (await showSessionPanel(page)).locator('[data-forge-checkout]')
const checkoutName = checkout.getByText('main', { exact: true })
await checkoutName.waitFor({ timeout: 20_000 })
await checkout.getByText('项目目录', { exact: true }).waitFor()
@@ -944,14 +1000,12 @@ it.skipIf(MODE === 'record')('marks a draft change request ready for review and
if (session === undefined) throw new Error('The Session must stay loaded')
scaffold.ctx.forgeSession.track(session, DRAFT)
const header = page.locator('[data-forge-header]')
await expect.poll(() => header.getAttribute('aria-label'), { timeout: 20_000 }).toBe('本会话的变更请求')
await header.click()
await showSessionPanel(page)
const change = page.locator(`[data-forge-change="${DRAFT}"]`)
await change.getByRole('link', { name: 'Add the merge button', exact: true }).waitFor({ timeout: 20_000 })
// The only open change request starts expanded, so its action is in view.
await change.getByRole('button', { name: '标记为可评审', exact: true }).click()
// The only open change request starts expanded, so its Merge action shows once it is ready.
await chooseCardAction(page, change, '#9', '标记为可评审')
await page.getByRole('alert').filter({ hasText: '已将 #9 标记为可评审' }).waitFor()
const merge = change.getByRole('button', { name: '合并', exact: true })
await merge.waitFor({ timeout: 20_000 })
@@ -1004,18 +1058,11 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
await page.getByText('LIGHTHOUSE', { exact: true }).waitFor()
const session = scaffold.ctx.sessions.get(sessionId)
if (session === undefined) throw new Error('The Session must stay loaded')
const header = page.locator('[data-forge-header]')
await page.getByRole('button', { name: '打开右侧边栏', exact: true }).click()
const guide = page.locator('[data-sidebar-right-guide]')
await guide.getByRole('button', { name: /^代码审查和变更/ }).waitFor()
await compareOrRefreshGolden(join(EXPECTED, 'review-guide.expected.md'),
await captureStableAria(page, '[data-sidebar-right-guide-entry="forge-panel"]', scaffold.workspaceCwd), MODE)
await guide.getByRole('button', { name: /^代码审查和变更/ }).click()
// The New Session screen inspected the checkout before these changes, which came from outside the Session.
await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click()
// The New Session screen inspected the checkout before these changes, which came from outside the Session;
// opening the panel inspects it again.
await showSessionPanel(page)
const card = page.locator('[data-forge-local]')
await card.getByText('HEAD → origin/main', { exact: true }).waitFor({ timeout: 20_000 })
await card.getByRole('button', { name: '查看本会话的变更:4 个文件,新增 4 行,删除 1 行', exact: true }).click()
await card.getByRole('button', { name: '本地变更 · 4 个文件,新增 4 行,删除 1 行', exact: true }).click({ timeout: 20_000 })
const local = page.locator('[data-forge-changes="local"]')
await local.getByRole('button', { name: '基准分支:origin/main', exact: true }).waitFor({ timeout: 20_000 })
@@ -1086,18 +1133,21 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
// A change request bound the way a `gh pr create` result binds one.
scaffold.ctx.forgeSession.track(session, PULL)
await expect.poll(() => header.getAttribute('aria-pressed'), { timeout: 20_000 }).toBe('false')
await header.click()
await showSessionPanel(page)
const change = page.locator(`[data-forge-change="${PULL}"]`)
await change.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 })
await card.getByRole('button', { name: '查看本会话的变更:4 个文件,新增 4 行,删除 1 行', exact: true }).waitFor()
expect(await card.getByRole('button', { name: '创建变更请求', exact: true }).count()).toBe(0)
await compareOrRefreshGolden(join(EXPECTED, 'local-and-pr.expected.md'),
await captureStableAria(page, '[data-forge-panel]', scaffold.workspaceCwd), MODE)
await card.getByRole('button', { name: '查看本会话的变更:4 个文件,新增 4 行,删除 1 行', exact: true }).click()
await card.getByRole('button', { name: '本地变更 · 4 个文件,新增 4 行,删除 1 行', exact: true }).waitFor()
// The open change request of the checked-out branch replaces the offer to create one.
await card.getByRole('button', { name: '本地变更操作', exact: true }).click()
await page.getByRole('menuitem', { name: '查看变更', exact: true }).waitFor()
expect(await page.getByRole('menuitem', { name: '创建变更请求', exact: true }).count()).toBe(0)
await card.getByRole('button', { name: '本地变更操作', exact: true }).click()
await compareOrRefreshGolden(join(EXPECTED, 'local-and-pr.expected.md'), await captureStableAria(page, '[data-session-panel]', scaffold.workspaceCwd, {
replacements: [[abbreviateHomePath(scaffold.workspaceCwd, homedir()), '{{cwd}}']],
}), MODE)
await card.getByRole('button', { name: '本地变更 · 4 个文件,新增 4 行,删除 1 行', exact: true }).click()
await local.getByText('暂存区与 HEAD 比较', { exact: true }).waitFor()
await expect.poll(() => header.getAttribute('aria-pressed')).toBe('false')
await header.click()
await showSessionPanel(page)
await change.getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click()
const view = page.locator('[data-forge-changes="change"]')
const panelFile = view.locator('[data-forge-diff-file="src/panel.ts"]')
@@ -1297,7 +1347,7 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
await page.setViewportSize({ width: 1680, height: 1000 })
await page.locator('[data-dockkit-tab]').filter({ hasText: '#7 的变更' }).locator('[data-dockkit-tab-close]').click()
await expect.poll(() => view.count()).toBe(0)
if (await header.getAttribute('aria-pressed') !== 'true') await header.click()
await showSessionPanel(page)
await change.getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click()
await panelFile.getByRole('button', { name: '6 行未变更', exact: true }).waitFor()
expect(await panelFile.locator('[data-forge-review-thread]').count()).toBe(0)
@@ -1309,8 +1359,7 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
// Pull request 9 changes 301 files, more than the pull request diff endpoint accepts; the compare read shows every file.
scaffold.ctx.forgeSession.track(session, DRAFT)
await expect.poll(() => header.getAttribute('aria-pressed'), { timeout: 20_000 }).toBe('false')
await header.click()
await showSessionPanel(page)
const draft = page.locator(`[data-forge-change="${DRAFT}"]`)
await draft.getByRole('button', { name: '展开 #9', exact: true }).click()
await draft.getByRole('button', { name: '查看 #9 的变更:新增 30 行,删除 2 行', exact: true }).click({ timeout: 20_000 })
@@ -1327,7 +1376,7 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an
scaffold.ctx.forge.refresh({ repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number: 9 })
await expect.poll(() => scaffold.ctx.forge.latest({ repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' }, number: 9 }),
{ timeout: 20_000 }).toMatchObject({ snapshot: { headSha: 'd'.repeat(40) } })
if (await header.getAttribute('aria-pressed') !== 'true') await header.click()
await showSessionPanel(page)
const expand = draft.getByRole('button', { name: '展开 #9', exact: true })
if (await expand.count() > 0) await expand.click()
await draft.getByRole('button', { name: '查看 #9 的变更:新增 30 行,删除 2 行', exact: true }).click({ timeout: 20_000 })
@@ -1368,8 +1417,11 @@ it.skipIf(MODE === 'record')('retains a wrapped code line and tree width across
scaffold.ctx.forgeSession.track(session, PULL)
// Keep the file tree and the Session sidebar visible together on every platform.
await page.setViewportSize({ width: 2400, height: 700 })
await page.locator('[data-forge-header]').click()
await showSessionPanel(page)
await page.locator(`[data-forge-change="${PULL}"]`).getByRole('button', { name: /查看 #7 的变更/ }).click()
// A start page beside the changes tab is the other tab the switches below show.
await page.getByRole('button', { name: '新标签页', exact: true }).first().click()
await page.getByRole('tab').filter({ hasText: '#7 的变更' }).click()
const view = page.locator('[data-forge-changes="change"]')
const scroll = view.locator('[data-forge-changes-scroll]')
const file = view.locator('[data-forge-diff-file="src/server.ts"]')
@@ -1408,7 +1460,7 @@ it.skipIf(MODE === 'record')('retains a wrapped code line and tree width across
expect(position.line).toBe('300')
expect(position.offset).toBe(-7)
for (const destination of ['tab', 'session', 'tab', 'session']) {
if (destination === 'tab') await page.getByRole('tab').filter({ hasText: '变更请求' }).click()
if (destination === 'tab') await page.getByRole('tab').filter({ hasText: '开始' }).click()
else await page.getByRole('button', { name: '新建会话', exact: true }).last().click()
await expect.poll(() => view.isVisible()).toBe(false)
await layout()
@@ -1436,9 +1488,8 @@ it.skipIf(MODE === 'record')('uses horizontal arrows to navigate files while pre
}
const { settled } = await sendPrompt(page, scaffold)
await settled
await page.locator('[data-forge-header]').click()
await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click()
await page.locator('[data-forge-local]').getByRole('button', { name: /查看本会话的变更:3 个文件/ }).click()
await showSessionPanel(page)
await page.locator('[data-forge-local]').getByRole('button', { name: /本地变更 · 3 个文件/ }).click()
const view = page.locator('[data-forge-changes="local"]')
const scroll = view.getByRole('region', { name: '全部 3 个文件', exact: true })
await scroll.waitFor()
@@ -1516,9 +1567,8 @@ it.skipIf(MODE === 'record')('opens a comment from the hover plus in one press w
await writeFile(join(project, 'notes.txt'), ['keep 1', 'keep 2', 'keep 4', 'keep 5', 'added', 'keep 6'].map(line => `${line}\n`).join(''))
const { settled } = await sendPrompt(page, scaffold)
await settled
await page.locator('[data-forge-header]').click()
await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click()
await page.locator('[data-forge-local]').getByRole('button', { name: /查看本会话的变更/ }).click()
await showSessionPanel(page)
await page.locator('[data-forge-local]').getByRole('button', { name: /^本地变更 · / }).click()
const view = page.locator('[data-forge-changes="local"]')
const file = view.locator('[data-forge-diff-file="README.md"]')
const number = (name: string) => file.getByRole('button', { name: `选择第 ${name} 行`, exact: true })
@@ -1637,10 +1687,8 @@ it.skipIf(MODE === 'record')('keeps tall branch and changed-file menus aligned w
await git(project, 'commit', '--quiet', '-m', 'long file list')
const { settled } = await sendPrompt(page, scaffold)
await settled
await page.locator('[data-forge-header]').click()
const panel = page.locator('[data-forge-panel]')
await panel.getByRole('button', { name: '刷新状态', exact: true }).click()
await panel.getByRole('button', { name: /^查看本会话的变更:60 个文件/ }).click()
const panel = await showSessionPanel(page)
await panel.getByRole('button', { name: /^本地变更 · 60 个文件/ }).click()
const changes = page.locator('[data-forge-changes="local"]')
const files = changes.getByRole('button', { name: '全部 60 个文件', exact: true })
await files.click()
@@ -1666,7 +1714,7 @@ it.skipIf(MODE === 'record')('keeps tall branch and changed-file menus aligned w
expect(tripwire.warnings).toEqual([])
})
it.skipIf(MODE === 'record')('aligns localized status rows by their glyphs and keeps long file lists inside one vertical scroller', async () => {
it.skipIf(MODE === 'record')('aligns localized status rows by their glyphs in the Session panel at every width', async () => {
const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-layout')
await page.locator('[data-forge-current-branch]').waitFor()
await compareOrRefreshGolden(join(EXPECTED, 'worktree-option.expected.md'),
@@ -1684,29 +1732,8 @@ it.skipIf(MODE === 'record')('aligns localized status rows by their glyphs and k
const session = scaffold.ctx.sessions.get(await settled)
if (session === undefined) throw new Error('The Session must stay loaded')
scaffold.ctx.forgeSession.track(session, PULL)
await page.locator('[data-forge-header]').click()
const panel = page.locator('[data-forge-panel]')
await panel.getByRole('button', { name: '刷新状态', exact: true }).click()
const local = panel.locator('[data-forge-local]')
await local.locator('button[aria-expanded]').click()
await expect.poll(() => local.locator('li').count(), { timeout: 20_000 }).toBe(60)
for (const width of [1280, 390]) {
await page.setViewportSize({ width, height: 700 })
const outerScrollers = await panel.evaluate((element) => {
const scrollers: string[] = []
for (let ancestor = element.parentElement; ancestor !== null; ancestor = ancestor.parentElement) {
if (/auto|scroll/.test(getComputedStyle(ancestor).overflowY) && ancestor.scrollHeight > ancestor.clientHeight + 1) {
scrollers.push(ancestor.className)
}
}
return scrollers
})
expect(outerScrollers).toEqual([])
expect(await panel.evaluate(element => element.scrollHeight > element.clientHeight)).toBe(true)
await local.locator('li').last().scrollIntoViewIfNeeded()
expect(await local.locator('li').last().isVisible()).toBe(true)
}
await local.locator('button[aria-expanded]').click()
const panel = await showSessionPanel(page)
await panel.locator('[data-forge-local]').getByRole('button', { name: /^本地变更 · 60 个文件/ }).waitFor({ timeout: 20_000 })
const change = panel.locator(`[data-forge-change="${PULL}"]`)
for (const [locale, labels] of [
['zh', ['检查', '评审', '合并', '变更']],
@@ -1721,6 +1748,8 @@ it.skipIf(MODE === 'record')('aligns localized status rows by their glyphs and k
}
for (const width of [1280, 390]) {
await page.setViewportSize({ width, height: 700 })
// A narrower window can hide the panel, which then opens over the conversation.
await showSessionPanel(page)
await expect.poll(() => change.evaluate(element => element.getBoundingClientRect().right)).toBeLessThanOrEqual(width)
// Each row names its fact for assistive technology only; the row starts with its glyph.
const rowOf = (label: string) => change.getByText(label, { exact: true }).locator('xpath=../..')
@@ -1823,9 +1852,8 @@ it.skipIf(MODE === 'record').each(['darwin', 'win32'] as const)('closes diff men
await writeFile(join(project, 'README.md'), 'review this change\n')
const { settled } = await sendPrompt(page, scaffold)
const sessionId = await settled
await page.locator('[data-forge-header]').click()
await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click()
await page.locator('[data-forge-local]').getByRole('button', { name: /查看本会话的变更:1 个文件/ }).click()
await showSessionPanel(page)
await page.locator('[data-forge-local]').getByRole('button', { name: /本地变更 · 1 个文件/ }).click()
const view = page.locator('[data-forge-changes="local"]')
await view.locator('[data-forge-diff-file="README.md"]').waitFor()
for (const name of ['分支', '全部 1 个文件', 'README.md 的更多操作']) {
@@ -1894,7 +1922,7 @@ it.skipIf(MODE === 'record').each([120, 4000])('types a review comment beside %i
const session = scaffold.ctx.sessions.get(sessionId)
if (session === undefined) throw new Error('Session must stay loaded')
scaffold.ctx.forgeSession.track(session, PULL)
await page.locator('[data-forge-header]').click()
await showSessionPanel(page)
const change = page.locator(`[data-forge-change="${PULL}"]`)
await change.getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click()
const file = page.locator('[data-forge-diff-file="src/typing.ts"]')
@@ -1943,7 +1971,7 @@ async function openReview(page: Page, scaffold: WebScaffold): Promise<{ readonly
const session = scaffold.ctx.sessions.get(sessionId)
if (session === undefined) throw new Error('Session must stay loaded')
scaffold.ctx.forgeSession.track(session, PULL)
await page.locator('[data-forge-header]').click()
await showSessionPanel(page)
await page.locator(`[data-forge-change="${PULL}"]`).getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click()
await page.getByRole('button', { name: '全屏', exact: true }).click()
const view = page.locator('[data-forge-changes="change"]')
@@ -1968,7 +1996,7 @@ it.skipIf(MODE === 'record')('lets a plugin filter the changes by its lens, anno
const session = scaffold.ctx.sessions.get(await settled)
if (session === undefined) throw new Error('Session must stay loaded')
scaffold.ctx.forgeSession.track(session, PULL)
await page.locator('[data-forge-header]').click()
await showSessionPanel(page)
// The card button the plugin adds opens the changes view with its lens chosen.
await page.locator(`[data-forge-change="${PULL}"]`).getByRole('button', { name: '打开导出视图', exact: true }).click()
@@ -2100,11 +2128,9 @@ it.skipIf(MODE === 'record')('keeps local viewed marks across reloads, clears a
await writeFile(join(project, 'notes.md'), 'note\n')
const { settled } = await sendPrompt(page, scaffold)
await settled
await page.getByRole('button', { name: '打开右侧边栏', exact: true }).click()
await page.locator('[data-sidebar-right-guide]').getByRole('button', { name: /^代码审查和变更/ }).click()
await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click()
await showSessionPanel(page)
const card = page.locator('[data-forge-local]')
await card.getByRole('button', { name: /^查看本会话的变更:3 个文件/ }).click({ timeout: 20_000 })
await card.getByRole('button', { name: /^本地变更 · 3 个文件/ }).click({ timeout: 20_000 })
const local = page.locator('[data-forge-changes="local"]')
const app = local.locator('[data-forge-diff-file="src/app.ts"]')
await app.getByRole('checkbox', { name: '将 app.ts 标记为已审阅', exact: true }).check({ timeout: 20_000 })
@@ -2182,7 +2208,10 @@ it.skipIf(MODE === 'record')('overlays the review threads of a change request an
await view.locator('[data-forge-diff-file="docs/panel.md"] [data-forge-thread="whole-file"]').getByText('文件级讨论', { exact: true }).waitFor()
const count = panel.getByRole('button', { name: 'panel.ts 有 3 条未解决的讨论,跳到下一条', exact: true })
await count.waitFor()
await view.getByRole('navigation').getByTitle('3 条未解决的讨论', { exact: true }).waitFor()
// The tree names the count in a tooltip once the pointer rests on it.
await view.getByRole('navigation').getByRole('button', { name: 'src/panel.ts', exact: true }).getByText('3', { exact: true }).hover()
await page.getByRole('tooltip').getByText('3 条未解决的讨论', { exact: true }).waitFor()
await page.mouse.move(1, 1)
await compareOrRefreshGolden(join(EXPECTED, 'review-threads.expected.md'),
await captureStableAria(page, '[data-forge-diff-file="src/panel.ts"]', scaffold.workspaceCwd), MODE)
@@ -2317,10 +2346,8 @@ it.skipIf(MODE === 'record')('keeps a narrow file header\'s viewed mark and menu
await git(project, 'commit', '--quiet', '-am', 'Rename the module')
const { settled } = await sendPrompt(page, scaffold)
await settled
await page.getByRole('button', { name: '打开右侧边栏', exact: true }).click()
await page.locator('[data-sidebar-right-guide]').getByRole('button', { name: /^代码审查和变更/ }).click()
await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click()
await page.locator('[data-forge-local]').getByRole('button', { name: /^查看本会话的变更/ }).click({ timeout: 20_000 })
await showSessionPanel(page)
await page.locator('[data-forge-local]').getByRole('button', { name: /^本地变更 · / }).click({ timeout: 20_000 })
const local = page.locator('[data-forge-changes="local"]')
const name = 'renamed-review-module-with-an-even-longer-name.ts'
const file = local.locator(`[data-forge-diff-file="${to}"]`)
@@ -2475,7 +2502,7 @@ it.skipIf(MODE === 'record')('summarizes checks, reviewers, and the merge state
const session = scaffold.ctx.sessions.get(await settled)
if (session === undefined) throw new Error('Session must stay loaded')
scaffold.ctx.forgeSession.track(session, PULL)
await page.locator('[data-forge-header]').click()
await showSessionPanel(page)
const card = page.locator(`[data-forge-change="${PULL}"]`)
// The card chooses its default expansion once its first status arrives, which names the title.
await card.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 })
@@ -2545,9 +2572,8 @@ async function openLocalChanges(failureShot: string): Promise<PanelLaunch & { re
await writeFile(join(project, 'notes.md'), 'note\n')
const { settled } = await sendPrompt(page, scaffold)
await settled
await page.locator('[data-forge-header]').click()
await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click()
await page.locator('[data-forge-local]').getByRole('button', { name: /查看本会话的变更/ }).click()
await showSessionPanel(page)
await page.locator('[data-forge-local]').getByRole('button', { name: /^本地变更 · / }).click({ timeout: 20_000 })
const view = page.locator('[data-forge-changes="local"]')
await view.locator('[data-forge-diff-file="README.md"]').waitFor()
await page.getByRole('button', { name: '全屏', exact: true }).click()
@@ -1,4 +1,4 @@
/** Background-job menu geometry over the normal Browser dock in the shipped Web composition. */
/** Session panel geometry with an expanded background job beside the normal Browser dock in the shipped Web composition. */
import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit'
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
@@ -15,55 +15,50 @@ import {
assertFixtureInventory, compareOrRefreshGolden, launchWebScaffold, seedSession,
watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { newEnglishPage, saveFailureShot } from './support.ts'
import { newEnglishPage, saveFailureShot, sessionPanelToggle, showSessionPanel } from './support.ts'
const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v3.jsonl', import.meta.url))
const EXPECTED_DIR = fileURLToPath(new URL('./expected/jobs-menu-layering', import.meta.url))
const EXPECTED_DIR = fileURLToPath(new URL('./expected/jobs-panel-layering', import.meta.url))
const MODE = webSnapshotMode()
const SEED_ID = brandString<SessionId>('jobs-menu-layering-web-e2e')
const SEED_ID = brandString<SessionId>('jobs-panel-layering-web-e2e')
// The private scaffold cwd owns the barrier; the loop bounds an orphan's lifetime.
const RELEASE = '.jobs-menu-layering.release'
const COMMAND = `printf 'jobs-menu-%s\\n' output; for _ in $(seq 1 3000); do [ -e ${RELEASE} ] && break; sleep 0.2; done`
const RELEASE = '.jobs-panel-layering.release'
const COMMAND = `printf 'jobs-panel-%s\\n' output; for _ in $(seq 1 3000); do [ -e ${RELEASE} ] && break; sleep 0.2; done`
/** Measure actual overlap and hit testing; ARIA alone cannot expose clipping or stacking. */
function placement(page: Page) {
return page.evaluate(() => {
const list = document.querySelector<HTMLElement>('ul[aria-label="Background jobs"]')
const anchor = document.querySelector<HTMLElement>('button[aria-label="1 background job"]')
const panel = document.querySelector<HTMLElement>('[data-session-panel]')
const section = document.querySelector<HTMLElement>('[data-session-panel-section="background-jobs"]')
const frame = document.querySelector<HTMLElement>('[data-sidebar-browser-frame]')
const dock = document.querySelector<HTMLElement>('[data-sidebar-right-panel][data-sidebar-right-open]')
if (list === null || anchor === null || frame === null || dock === null) {
throw new Error('job menu, trigger, or Browser dock is missing')
if (panel === null || section === null || frame === null || dock === null) {
throw new Error('Session panel, jobs section, or Browser dock is missing')
}
const menu = list.closest<HTMLElement>('[data-menu-material]') ?? list
const box = menu.getBoundingClientRect()
const trigger = anchor.getBoundingClientRect()
const body = panel.closest<HTMLElement>('[data-conversation-content]')
const seat = body?.querySelector<HTMLElement>('[data-composer-seat]') ?? null
if (body === null || seat === null) throw new Error('conversation body or composer seat is missing')
const box = panel.getBoundingClientRect()
const host = body.getBoundingClientRect()
const browser = frame.getBoundingClientRect()
const left = Math.max(box.left, browser.left)
const right = Math.min(box.right, browser.right)
const top = Math.max(box.top, browser.top)
const bottom = Math.min(box.bottom, browser.bottom)
const overlapsBrowser = right - left > 8 && bottom - top > 8
const aboveBrowser = overlapsBrowser && [0.25, 0.5, 0.75].every(x =>
[0.25, 0.5, 0.75].every(y => menu.contains(document.elementFromPoint(
left + (right - left) * x, top + (bottom - top) * y,
))))
const verticalGap = Math.min(Math.abs(box.top - trigger.bottom - 5), Math.abs(trigger.top - box.bottom - 5))
const horizontalAlignment = Math.min(Math.abs(box.left - trigger.left), Math.abs(box.right - trigger.right))
const composer = seat.getBoundingClientRect()
const sectionBox = section.getBoundingClientRect()
return {
dockMode: dock.dataset.sidebarRightPanel,
bodyMounted: menu.parentElement === document.body,
fixed: getComputedStyle(menu).position === 'fixed',
anchored: verticalGap <= 1 && horizontalAlignment <= 1,
viewportBounded: box.left >= 11 && box.top >= 11
&& box.right <= innerWidth - 11 && box.bottom <= innerHeight - 11,
overlapsBrowser,
aboveBrowser,
presentation: panel.dataset.sessionPanel,
insideBody: box.left >= host.left && box.right <= host.right && box.top >= host.top,
clearOfBrowser: box.right <= browser.left,
clearOfComposer: box.bottom <= composer.top,
viewportBounded: box.left >= 0 && box.top >= 0 && box.right <= innerWidth && box.bottom <= innerHeight,
sectionShown: sectionBox.height > 0,
onTop: [0.25, 0.5, 0.75].every(x => [0.25, 0.5, 0.75].every(y => panel.contains(document.elementFromPoint(
box.left + box.width * x, box.top + box.height * y,
)))),
}
})
}
describe.skipIf(MODE === 'record')('web e2e: jobs menu layering', () => {
describe.skipIf(MODE === 'record')('web e2e: jobs panel layering', () => {
let scaffold: WebScaffold
let browser: Browser
let page: Page
@@ -80,7 +75,7 @@ describe.skipIf(MODE === 'record')('web e2e: jobs menu layering', () => {
page = await newEnglishPage(browser)
await page.emulateMedia({ reducedMotion: 'reduce' })
await page.route('https://browser.test/**', async route => route.fulfill({
contentType: 'text/html', body: '<h1>Jobs menu browser fixture</h1>',
contentType: 'text/html', body: '<h1>Jobs panel browser fixture</h1>',
}))
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
@@ -94,18 +89,18 @@ describe.skipIf(MODE === 'record')('web e2e: jobs menu layering', () => {
if (jobId !== undefined) {
const settled = await scaffold.ctx.jobs.wait(jobId, 15_000, agent.id)
if (settled.status === 'running' || settled.status === 'stopping') {
throw new Error('jobs menu fixture did not settle after releasing its barrier')
throw new Error('jobs panel fixture did not settle after releasing its barrier')
}
}
} catch (error) { failures.push(error) }
}
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, 'jobs menu layering teardown failed')
if (failures.length > 0) throw new AggregateError(failures, 'jobs panel layering teardown failed')
})
it('keeps the list and live output above the Browser dock while anchored and dismissable', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-jobs-menu-layering'))
it('keeps the section and its live output in the conversation body beside the Browser dock and dismissable', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-jobs-panel-layering'))
const initialViewport = page.viewportSize()!
const session = page.locator(`[data-row-key="session:${SEED_ID}"]`)
await expect.poll(async () => {
@@ -121,9 +116,9 @@ describe.skipIf(MODE === 'record')('web e2e: jobs menu layering', () => {
agent = opened
const started = await executeToolFixture(scaffold.ctx, {
signal: new AbortController().signal,
callId: brandString<ToolCallId>('jobs-menu-layering-e2e'),
callId: brandString<ToolCallId>('jobs-panel-layering-e2e'),
name: 'bash',
arguments: { command: COMMAND, description: 'Emit output and hold the jobs menu fixture', run_in_background: true },
arguments: { command: COMMAND, description: 'Emit output and hold the jobs panel fixture', run_in_background: true },
agent,
})
const reported = started.content.map(block => block.type === 'text' ? block.text : '').join('')
@@ -135,7 +130,7 @@ describe.skipIf(MODE === 'record')('web e2e: jobs menu layering', () => {
await expect.poll(() => {
const job = scaffold.ctx.jobs.get(startedJobId, agent.id)
const output = scaffold.ctx.jobs.readAt(startedJobId, 0, agent.id).chunks.map(chunk => chunk.text).join('')
return job.status !== 'running' || output.includes('jobs-menu-output')
return job.status !== 'running' || output.includes('jobs-panel-output')
}, { timeout: 15_000 }).toBe(true)
const readyJob = scaffold.ctx.jobs.get(startedJobId, agent.id)
const readyOutput = scaffold.ctx.jobs.readAt(startedJobId, 0, agent.id).chunks.map(chunk => chunk.text).join('')
@@ -145,61 +140,54 @@ describe.skipIf(MODE === 'record')('web e2e: jobs menu layering', () => {
const column = page.locator('[data-rightbar-col]')
await column.locator('[data-sidebar-right-guide-entry="browser"]').click()
const address = column.getByRole('textbox', { name: 'Enter an HTTP(S) address' })
await address.fill('https://browser.test/jobs-menu')
await address.fill('https://browser.test/jobs-panel')
await address.press('Enter')
await page.frameLocator('[data-sidebar-browser-frame]')
.getByRole('heading', { name: 'Jobs menu browser fixture' }).waitFor()
.getByRole('heading', { name: 'Jobs panel browser fixture' }).waitFor()
const trigger = page.getByRole('button', { name: '1 background job', exact: true })
await trigger.waitFor({ timeout: 15_000 })
await trigger.focus()
const toggle = sessionPanelToggle(page)
await toggle.focus()
await page.keyboard.press('Enter')
const list = page.getByRole('list', { name: 'Background jobs' })
await list.waitFor()
await page.keyboard.press('Tab')
expect(await list.getByRole('button', { name: /Show live output/ })
.evaluate(element => element === document.activeElement)).toBe(true)
const panel = page.locator('[data-session-panel]')
await panel.waitFor()
const list = panel.locator('[data-session-panel-section="background-jobs"]').getByRole('list')
await list.getByRole('button', { name: /Show live output/ }).waitFor({ timeout: 15_000 })
const expectedPlacement = {
dockMode: 'push', bodyMounted: true, fixed: true, anchored: true,
viewportBounded: true, overlapsBrowser: true, aboveBrowser: true,
dockMode: 'push', presentation: 'overlay', insideBody: true, clearOfBrowser: true,
clearOfComposer: true, viewportBounded: true, sectionShown: true, onTop: true,
}
await expect.poll(() => placement(page)).toEqual(expectedPlacement)
const collapsed = await placement(page)
await list.getByRole('button', { name: /Show live output/ }).click()
await list.getByText('jobs-menu-output', { exact: true }).waitFor({ timeout: 15_000 })
await list.getByText('jobs-panel-output', { exact: true }).waitFor({ timeout: 15_000 })
await expect.poll(() => placement(page)).toEqual(expectedPlacement)
const expanded = await placement(page)
await page.setViewportSize({ width: 1280, height: 760 })
await showSessionPanel(page)
await expect.poll(() => placement(page)).toEqual(expectedPlacement)
const resized = await placement(page)
await list.getByRole('button', { name: /Hide live output/ }).focus()
await page.keyboard.press('Escape')
await list.waitFor({ state: 'detached' })
const escapeRestoresFocus = await trigger.evaluate(node => node === document.activeElement)
await panel.waitFor({ state: 'detached' })
const escapeRestoresFocus = await toggle.evaluate(node => node === document.activeElement)
expect(escapeRestoresFocus).toBe(true)
await trigger.click()
await list.waitFor()
await showSessionPanel(page)
await address.click()
await list.waitFor({ state: 'detached' })
const outsideDismisses = await trigger.getAttribute('aria-expanded') === 'false'
await panel.waitFor({ state: 'detached' })
const outsideDismisses = await toggle.getAttribute('aria-expanded') === 'false'
expect(outsideDismisses).toBe(true)
expect(await address.evaluate(element => element === document.activeElement)).toBe(true)
await page.setViewportSize(initialViewport)
await trigger.hover()
await list.waitFor()
expect(await address.evaluate(element => element === document.activeElement)).toBe(true)
await page.keyboard.press('Escape')
await list.waitFor({ state: 'detached' })
expect(await address.evaluate(element => element === document.activeElement)).toBe(true)
expect(scaffold.ctx.jobs.get(jobId, agent.id).status).toBe('running')
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
await mkdir(EXPECTED_DIR, { recursive: true })
await compareOrRefreshGolden(join(EXPECTED_DIR, 'geometry.expected.md'), [
'# Background jobs above the Browser dock', '',
'# Background jobs beside the Browser dock', '',
'```json',
JSON.stringify({ collapsed, expanded, resized, escapeRestoresFocus, outsideDismisses }, null, 2),
'```',
+31 -31
View File
@@ -1,8 +1,8 @@
import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit'
// Session-header job list driven by a real background bash run: the job row
// arrives over the job roster stream, expanding it opens the output
// observation stream, and the panel shows the process's real output while it
// is still running. No model call is involved.
// The Session panel's background-jobs section driven by a real background
// bash run: the job row arrives over the job roster stream, expanding it opens
// the output observation stream, and the row shows the process's real output
// while it is still running. No model call is involved.
import { readFile, writeFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import { join } from 'node:path'
@@ -18,12 +18,13 @@ import {
assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { newEnglishPage, saveFailureShot } from './support.ts'
import { hideSessionPanel, newEnglishPage, saveFailureShot, showSessionPanel } from './support.ts'
const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v2.jsonl', import.meta.url))
const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/live-job-stream', import.meta.url))
const STREAMING_EXPECTED = join(SNAPSHOT_DIR, 'streaming.expected.md')
const SETTLED_EXPECTED = join(SNAPSHOT_DIR, 'settled.expected.md')
const SECTION = '[data-session-panel-section="background-jobs"]'
const MODE = webSnapshotMode()
const SEED_ID = 'live-job-stream-web-e2e'
// One fixed line of early output, then a hold on a barrier file the test owns
@@ -83,11 +84,12 @@ describe.skipIf(MODE === 'record')('web e2e: live job stream', () => {
await scaffold?.close()
})
it('streams a running job\'s real output into the expanded panel, then settles it in place on kill', async () => {
it('streams a running job\'s real output into the expanded row, then settles it in place on kill', async () => {
let phase = 'streaming'
onTestFailed(() => saveFailureShot(page, `web-e2e-live-job-${phase}`))
const trigger = page.getByRole('button', { name: '1 background job', exact: true })
expect(await trigger.count()).toBe(0)
const list = page.locator(SECTION).getByRole('list')
await showSessionPanel(page)
expect(await list.count()).toBe(0)
const started = await executeToolFixture(scaffold.ctx, {
signal: new AbortController().signal,
@@ -109,43 +111,41 @@ describe.skipIf(MODE === 'record')('web e2e: live job stream', () => {
const readyOutput = scaffold.ctx.jobs.readAt(jobId, 0, agent.id).chunks.map(chunk => chunk.text).join('')
expect(readyJob.status, `${readyJob.detail ?? ''}\n${readyOutput}`).toBe('running')
// The job row reaches the header over the job roster stream.
await trigger.waitFor({ timeout: 15_000 })
await trigger.click()
// Expanding the row opens the output observation stream; the panel then renders
// the command's real stdout while the process is still running.
const expand = page.getByRole('button', { name: /Show live output/ })
await expand.waitFor({ timeout: 10_000 })
// The job row reaches the open section over the job roster stream.
// Expanding the row opens the output observation stream; the row then
// renders the command's real stdout while the process is still running.
const expand = list.getByRole('button', { name: /Show live output/ })
await expand.waitFor({ timeout: 15_000 })
await expand.click()
await page.getByText('streamed-marker-line').waitFor({ timeout: 15_000 })
await list.getByText('streamed-marker-line').waitFor({ timeout: 15_000 })
const streaming = await captureStableAria(page, '[class*="menu"]', scaffold.workspaceCwd, { runningJobs: 'keep' })
const streaming = await captureStableAria(page, SECTION, scaffold.workspaceCwd)
await compareOrRefreshGolden(STREAMING_EXPECTED, streaming, MODE)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
await trigger.click()
await page.getByRole('list', { name: 'Background jobs' }).waitFor({ state: 'detached' })
// Hiding the panel unmounts the section, which closes the observation
// stream; showing it again lists the row collapsed, and expanding it
// reopens the stream from the retained output.
await hideSessionPanel(page)
await list.waitFor({ state: 'detached' })
expect(await page.getByText('streamed-marker-line', { exact: true }).count()).toBe(0)
await page.mouse.move(2, 2)
await trigger.hover()
await page.getByRole('list', { name: 'Background jobs' }).waitFor()
await page.getByRole('button', { name: /Hide live output/ }).waitFor()
await page.getByText('streamed-marker-line', { exact: true }).waitFor()
await showSessionPanel(page)
await list.getByRole('button', { name: /Show live output/ }).click()
await list.getByRole('button', { name: /Hide live output/ }).waitFor()
await list.getByText('streamed-marker-line', { exact: true }).waitFor({ timeout: 15_000 })
expect(scaffold.ctx.jobs.get(jobId, agent.id).status).toBe('running')
phase = 'settled'
expect(scaffold.ctx.jobs.kill(jobId, agent.id, 'web e2e cancellation')).toBe('requested')
// The unchanged count label is not a settlement signal; the output row owns that state.
await page.getByRole('button', { name: 'Finished 1', exact: true }).waitFor({ timeout: 20_000 })
await expect.poll(() => page.getByRole('list', { name: 'Background jobs' }).textContent()).toContain('web e2e cancellation')
expect(await trigger.getAttribute('aria-label')).toBe('1 background job')
// The settled section line owns the settlement signal; the expanded row moves under it.
await list.getByRole('button', { name: 'Finished 1', exact: true }).waitFor({ timeout: 20_000 })
await expect.poll(() => list.textContent()).toContain('web e2e cancellation')
expect(scaffold.ctx.jobs.get(jobId, agent.id).status).toBe('killed')
await page.getByText('streamed-marker-line').waitFor({ timeout: 10_000 })
await list.getByText('streamed-marker-line').waitFor({ timeout: 10_000 })
const settled = await captureStableAria(page, '[class*="menu"]', scaffold.workspaceCwd)
const settled = await captureStableAria(page, SECTION, scaffold.workspaceCwd)
await compareOrRefreshGolden(SETTLED_EXPECTED, settled, MODE)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
+3 -6
View File
@@ -48,7 +48,7 @@ import {
buildVfsExampleFiles,
} from '../../../packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts'
import { captureStableAria, compareOrRefreshGolden, webSnapshotMode } from './scaffold.ts'
import { expandOwningTurnProcess, newEnglishPage, REPO_ROOT, saveFailureShot } from './support.ts'
import { expandOwningTurnProcess, hideSessionPanel, newEnglishPage, REPO_ROOT, saveFailureShot, showSessionPanel } from './support.ts'
const DIST_ROOT = fileURLToPath(new URL('../dist', import.meta.url))
/** Optional bundles that compose a profile of their own; the Web plugin page hides them, the Host inventory still reports them. */
@@ -547,13 +547,10 @@ async function bootPreview(site: Site, manifest: ImageManifest, browser: Browser
await preview.getByRole('heading', { name: 'Preview Workspace', exact: true }).waitFor({ state: 'visible' })
expect(await preview.locator('[data-dockkit-tab-title]').allTextContents()).toEqual(['PREVIEW.md'])
const subagents = page.getByRole('button', { name: '2 subagents', exact: true })
await subagents.waitFor({ timeout: 15_000 })
await subagents.hover()
const catalog = page.getByRole('tree', { name: 'Subagent sessions' })
const catalog = (await showSessionPanel(page)).getByRole('tree', { name: 'Subagent sessions' })
await catalog.getByRole('treeitem', { name: /Review preview architecture/ }).waitFor()
await catalog.getByRole('treeitem', { name: /Continue preview verification/ }).waitFor()
await catalog.press('Escape')
await hideSessionPanel(page)
// Auto-prefetch may already have published the page, and a pointer click can
// land on whatever moved under it; activate the control only while it still
+2 -12
View File
@@ -1656,18 +1656,13 @@ function normalizeAria(snapshot: string, workspaceCwd: string, age: boolean): st
/**
* Capture the region's aria snapshot at a settled milestone: poll until two
* consecutive normalized captures are equal — a single-shot capture races the
* last React commits. A foreground shell command is a job while it runs, and
* its removal reaches the browser one coalesced roster frame after the tool
* result, so by default the capture first waits for the session header's
* running-job control to leave; a scenario whose milestone is a running job
* keeps it with `runningJobs: 'keep'`.
* last React commits.
* @param page - the page under test.
* @param selector - the region locator selector.
* @param workspaceCwd - normalization input.
* @param options - `normalizeAge` collapses relative-time buckets to `{{age}}`
* for a region whose rows are dated from live wall-clock state;
* `replacements` tokenizes scenario-owned values before generic normalization;
* `runningJobs` is `'settle'` (default: wait for no running-job control) or `'keep'`.
* `replacements` tokenizes scenario-owned values before generic normalization.
* @returns the stable normalized snapshot.
*/
export async function captureStableAria(
@@ -1677,13 +1672,8 @@ export async function captureStableAria(
options: {
normalizeAge?: boolean
replacements?: readonly (readonly [value: string, token: string])[]
runningJobs?: 'settle' | 'keep'
} = {},
): Promise<string> {
if ((options.runningJobs ?? 'settle') === 'settle') {
await page.getByRole('button', { name: /background jobs? running/ })
.waitFor({ state: 'detached', timeout: 10_000 })
}
const region = page.locator(selector).first()
const age = options.normalizeAge === true
const normalize = (snapshot: string): string => {
+1 -2
View File
@@ -170,8 +170,7 @@ describe.skipIf(MODE === 'record')('web e2e: archiving a running Session stops i
expect(scaffold.ctx.agents.get(sessionId)?.status).toBe('running')
expect(await childAlive(cwd)).toBe(true)
await expect.poll(() => sessionRow().count()).toBe(1)
// The Bash command is a running job while the dialog is open, by design.
const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd, { runningJobs: 'keep' })
const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
await compareOrRefreshGolden(DIALOG_EXPECTED, snapshot, MODE)
// Cancel keeps everything as it was.
@@ -248,6 +248,15 @@ describe.skipIf(MODE === 'record')('web e2e: Session panel layout', () => {
})
await other.mouse.move(5, 5)
await expect.poll(async () => (await rowLayout(other)).highlighted).toBe(false)
// The row's open menu keeps the row highlighted and the More button shown after the pointer leaves for the menu.
await row.locator('[data-row-part="menu"] button').click()
await other.getByRole('menu').waitFor()
await other.mouse.move(5, 5)
expect(await rowLayout(other)).toEqual({
...resting, menu: { center: 14, target: [24, 24], opacity: '1' }, hovered: false, highlighted: true,
})
await other.keyboard.press('Escape')
await expect.poll(async () => (await rowLayout(other)).highlighted).toBe(false)
expect(errors.pageErrors).toEqual([])
})
})
+23 -42
View File
@@ -19,7 +19,7 @@ import {
webSnapshotMode,
type WebScaffold,
} from './scaffold.ts'
import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
import { connectFreshWorkspace, newEnglishPage, saveFailureShot, sessionPanelToggle, showSessionPanel } from './support.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/sidebar-subagent-activity', import.meta.url))
@@ -146,9 +146,10 @@ describe('web e2e: sidebar subagent activity', () => {
)
expect(await ownerRow.locator('[data-state="ongoing"]').count()).toBe(1)
await ownerRow.click()
const runningTrigger = page.getByRole('button', { name: '1 subagent', exact: true })
await runningTrigger.waitFor({ timeout: 10_000 })
expect(await runningTrigger.locator('[data-state="ongoing"]').count()).toBe(1)
const toggle = sessionPanelToggle(page)
const subagents = (await showSessionPanel(page)).locator('[data-session-panel-section="subagents"]')
await subagents.getByRole('treeitem').locator('[data-state="ongoing"]').waitFor({ timeout: 10_000 })
expect(await subagents.getByText('1 in progress', { exact: true }).isVisible()).toBe(true)
// This directly created owner has no tool preset; the fixture collects its own job.
scaffold.ctx.effect(() => scaffold.ctx.jobs.attachController('compact header fixture'), 'compact header job controller')
const completion = Promise.withResolvers<{ status: 'completed' }>()
@@ -161,54 +162,34 @@ describe('web e2e: sidebar subagent activity', () => {
},
})
const viewport = page.viewportSize()!
const panel = page.locator('[data-session-panel]')
const assertRunningSections = async (): Promise<void> => {
await showSessionPanel(page)
for (const section of ['subagents', 'background-jobs']) {
await panel.locator(`[data-session-panel-section="${section}"]`).locator('[data-state="ongoing"]').first()
.waitFor({ timeout: 10_000 })
}
expect(await panel.getAttribute('data-session-panel')).toBe('overlay')
await page.keyboard.press('Escape')
await panel.waitFor({ state: 'detached' })
}
try {
const jobTrigger = page.getByRole('button', { name: '1 background job', exact: true })
await jobTrigger.waitFor()
expect(await jobTrigger.evaluate(element => document.getElementById(element.getAttribute('aria-describedby')!)?.textContent)).toBe('Running')
const controls = [
{ trigger: runningTrigger, icon: '[data-icon="dsw-icon-users-outline-regular"]', count: '[data-subagent-count]' },
{ trigger: jobTrigger, icon: '[data-icon="dsw-icon-layers-outline-regular"]', count: '[data-job-count]' },
]
for (const { trigger, icon, count } of controls) {
expect(await trigger.locator(count).isVisible()).toBe(true)
expect(await trigger.locator('[data-state="ongoing"]').isVisible()).toBe(true)
expect(await trigger.locator(icon).isVisible()).toBe(false)
}
await runningTrigger.focus()
await assertRunningSections()
await toggle.focus()
await page.setViewportSize({ width: 390, height: 700 })
for (const { trigger, icon, count } of controls) {
await expect.poll(() => trigger.locator(count).isVisible()).toBe(false)
expect(await trigger.locator(icon).isVisible()).toBe(true)
expect(await trigger.locator('[data-state="ongoing"]').isVisible()).toBe(false)
}
expect(await runningTrigger.evaluate(element => element === document.activeElement)).toBe(true)
expect(await jobTrigger.evaluate(element => document.getElementById(element.getAttribute('aria-describedby')!)?.textContent)).toBe('Running')
expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true)
await compareOrRefreshGolden(
join(SNAPSHOT_DIR, 'compact-running.expected.md'),
await captureStableAria(page, 'header:has([data-subagent-action])', scaffold.workspaceCwd),
await captureStableAria(page, 'header:has([data-session-panel-toggle])', scaffold.workspaceCwd),
MODE,
)
await saveFailureShot(page, 'web-e2e-compact-running-icons')
await runningTrigger.click()
const members = page.locator('[data-subagent-panel]')
await members.waitFor()
expect(await members.getByRole('treeitem').locator('[data-state="ongoing"]').isVisible()).toBe(true)
await page.keyboard.press('Escape')
await jobTrigger.click()
const jobs = page.getByRole('list', { name: 'Background jobs', exact: true })
await jobs.waitFor()
expect(await jobs.locator('[data-state="ongoing"]').isVisible()).toBe(true)
await page.keyboard.press('Escape')
await saveFailureShot(page, 'web-e2e-compact-running-header')
await assertRunningSections()
await page.setViewportSize(viewport)
for (const { trigger, icon, count } of controls) {
await expect.poll(() => trigger.locator(count).isVisible()).toBe(true)
expect(await trigger.locator('[data-state="ongoing"]').isVisible()).toBe(true)
expect(await trigger.locator(icon).isVisible()).toBe(false)
}
await assertRunningSections()
} finally {
completion.resolve({ status: 'completed' })
await scaffold.ctx.jobs.wait(jobId, 5_000, ownerId)
await page.keyboard.press('Escape')
await page.setViewportSize(viewport)
}
await assertFixtureInventory(SNAPSHOT_DIR, ['owner-running.expected.md', 'compact-running.expected.md'])
@@ -1,10 +1,10 @@
// Web e2e scenario: hovering a sidebar session row marquees a title wider than
// its cell. The jsdom lane pins only the positions the handler writes; the
// assembled browser is where the title really clips, really crawls toward its
// own hovered extent (the trailing relative-time cell yields to the row menu
// while the pointer rests on the row, so the hovered cell is wider than the
// resting one), really fades its moved left edge, and really returns to its
// start when the pointer leaves.
// its cell. The jsdom lane pins only the distance and time the handler hands
// the stylesheet; the assembled browser is where the title really clips,
// really travels toward its own hovered extent (the trailing relative-time
// cell yields to the row menu while the pointer rests on the row, so the
// hovered cell is wider than the resting one) without a frame script, really
// fades its cut edges, and really returns to its start when the pointer leaves.
//
// Zero model calls: seeding one renamed session and hovering its row touches no
// provider.
@@ -48,60 +48,79 @@ describe('web e2e: hovering a clipped session title marquees it to its far edge'
onTestFailed(() => saveFailureShot(page, 'web-e2e-sidebar-title-hover-scroll'))
const row = page.getByRole('treeitem').filter({ has: page.getByText(TITLE, { exact: true }) })
await row.waitFor({ timeout: 20_000 })
const title = row.getByText(TITLE, { exact: true })
// The title text sits in the span that travels; its parent clips it.
const travel = row.getByText(TITLE, { exact: true })
const title = travel.locator('xpath=..')
/** How far the text has travelled from its start, in CSS pixels. */
const travelled = async (): Promise<number> => travel.evaluate((el) => {
const transform = getComputedStyle(el).transform
return transform === 'none' ? 0 : -new DOMMatrix(transform).m41
})
/** Top of the title's glyphs: the text keeps its line while its span becomes a box to travel. */
const glyphTop = async (): Promise<number> => travel.evaluate((el) => {
const glyphs = document.createRange()
glyphs.selectNodeContents(el)
return glyphs.getBoundingClientRect().top
})
/** The distance the hook measured for the hovered cell. */
const range = async (): Promise<number> => title.evaluate(el => Number.parseFloat(el.style.getPropertyValue('--dsh-marquee-range')))
// At rest the row clips its title with an ellipsis and holds its start.
expect(await title.evaluate(el => el.scrollWidth - el.clientWidth)).toBeGreaterThan(0)
expect(await title.evaluate(el => getComputedStyle(el).textOverflow)).toBe('ellipsis')
expect(await title.evaluate(el => el.scrollLeft)).toBe(0)
expect(await travelled()).toBe(0)
const restingTop = await glyphTop()
// The stylesheet moves the text, so the page runs no frame callback per frame while it travels.
await page.evaluate(() => {
const request = window.requestAnimationFrame.bind(window)
Reflect.set(window, 'marqueeFrames', 0)
window.requestAnimationFrame = (callback) => {
Reflect.set(window, 'marqueeFrames', Number(Reflect.get(window, 'marqueeFrames')) + 1)
return request(callback)
}
})
await row.hover()
// The marquee crawls instead of jumping: the title is caught mid-travel,
// strictly between its start and its far edge, with both cut edges
// publishing their fade-mask hooks.
await expect.poll(
async () => title.evaluate(el => el.scrollLeft > 0),
{ timeout: 5_000 },
).toBe(true)
expect(await title.evaluate(el => el.scrollLeft < el.scrollWidth - el.clientWidth - 1)).toBe(true)
expect(await title.evaluate(el => el.hasAttribute('data-scrolled'))).toBe(true)
expect(await title.evaluate(el => el.hasAttribute('data-clipped'))).toBe(true)
expect(await title.evaluate(el => getComputedStyle(el).maskImage)).toContain('linear-gradient')
// The crawl still reaches the far edge of the hovered cell (the wider
// The marquee travels instead of jumping: the title is caught mid-travel,
// strictly between its start and its far edge, with both cut edges faded.
await expect.poll(async () => await travelled() > 0, { timeout: 5_000 }).toBe(true)
expect(await travelled()).toBeLessThan(await range() - 1)
expect(await title.evaluate(el => el.hasAttribute('data-marquee'))).toBe(true)
expect(await title.evaluate(el => getComputedStyle(el).maskImage)).toContain('calc(100% - 12px)')
expect(Math.abs(await glyphTop() - restingTop)).toBeLessThan(0.5)
// Constant 30px/s: one second of travel covers about 30px.
const before = await travelled()
const started = Date.now()
await page.waitForTimeout(1_000)
const speed = (await travelled() - before) / ((Date.now() - started) / 1_000)
expect(speed).toBeGreaterThan(24)
expect(speed).toBeLessThan(36)
// The travel still reaches the far edge of the hovered cell (the wider
// one — the relative-time label yields to the row menu) and rests there,
// lifting the right fade so the final character reads at full strength.
// The fade lifts on the frame that lands exactly on the far edge, one or
// two frames after scrollLeft first rounds within a pixel of it.
// lifting the end fade so the final character reads at full strength.
await expect.poll(async () => await travelled() >= await range() - 1, { timeout: 20_000 }).toBe(true)
await expect.poll(
async () => title.evaluate(el => el.scrollLeft >= el.scrollWidth - el.clientWidth - 1),
{ timeout: 20_000 },
).toBe(true)
await expect.poll(
async () => title.evaluate(el => el.hasAttribute('data-clipped')),
async () => title.evaluate(el => getComputedStyle(el).maskImage.includes('calc(100% - 12px)')),
{ timeout: 5_000 },
).toBe(false)
expect(await title.evaluate(el => getComputedStyle(el).maskImage)).toContain('linear-gradient')
// At its extent, the title must not paint the ellipsis over the
// characters the marquee reached.
expect(await title.evaluate(el => getComputedStyle(el).textOverflow)).toBe('clip')
// A frame script would have run once per frame for the whole travel; other parts of the page may ask for a frame or two.
expect(await page.evaluate(() => Number(Reflect.get(window, 'marqueeFrames')))).toBeLessThan(10)
// Leaving returns in one step: a crawl back would still be travelling
// Leaving returns in one step: a travel back would still be under way
// inside this window, and it would carry the resting ellipsis with it.
await page.mouse.move(0, 0)
await expect.poll(
async () => title.evaluate(el => el.scrollLeft),
{ timeout: 150, interval: 20 },
).toBe(0)
expect(await title.evaluate(el => el.hasAttribute('data-scrolled'))).toBe(false)
await expect.poll(travelled, { timeout: 150, interval: 20 }).toBe(0)
expect(await title.evaluate(el => el.hasAttribute('data-marquee'))).toBe(false)
expect(await title.evaluate(el => getComputedStyle(el).textOverflow)).toBe('ellipsis')
// Reduced motion reaches the handler's matchMedia probe: the reveal jumps
// to the far edge instead of crawling.
// Reduced motion shows the far edge at once instead of travelling to it.
await page.emulateMedia({ reducedMotion: 'reduce' })
await row.hover()
await expect.poll(
async () => title.evaluate(el => el.scrollLeft >= el.scrollWidth - el.clientWidth - 1),
{ timeout: 500, interval: 20 },
).toBe(true)
await expect.poll(async () => await travelled() >= await range() - 1, { timeout: 500, interval: 20 }).toBe(true)
await page.mouse.move(0, 0)
await page.emulateMedia({ reducedMotion: null })
expect(tripwire.pageErrors).toEqual([])
@@ -1,26 +1,22 @@
- dialog "Subagent sessions":
- heading "Subagents" [level=3]
- text: 1 external
- tree "Subagent sessions":
- 'treeitem "Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. team-panel-researcher · External task" [disabled] [level=1]': "Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. team-panel-researcher"
- region "Task board":
- heading "Shared tasks 1 completed · 1 in progress · 2 pending" [level=3]
- list:
- listitem:
- button "In progress Agent task":
- img "In progress"
- text: Agent task
- listitem:
- button "Completed Completed preparation":
- img "Completed"
- text: Completed preparation
- listitem:
- button "Pending Dependency task":
- img "Pending"
- text: Dependency task
- listitem:
- button "Blocked by dependencies Responsive task with a long title that remains fully readable when expanded at the minimum supported viewport" [expanded]:
- img "Blocked by dependencies"
- text: Responsive task with a long title that remains fully readable when expanded at the minimum supported viewport
- paragraph: Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work.
- paragraph: "Owner: Unowned"
- region "Shared tasks":
- heading "Shared tasks" [level=2]
- text: 1 completed · 1 in progress · 2 pending
- list:
- listitem:
- button "In progress Agent task":
- img "In progress"
- text: Agent task
- listitem:
- button "Pending Dependency task":
- img "Pending"
- text: Dependency task
- listitem:
- button "Blocked by dependencies Responsive task with a long title that remains fully readable when expanded at the minimum supported viewport" [expanded]:
- img "Blocked by dependencies"
- text: Responsive task with a long title that remains fully readable when expanded at the minimum supported viewport
- paragraph: Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work.
- paragraph: "Owner: Unowned"
- listitem:
- button "Completed Completed preparation":
- img "Completed"
- text: Completed preparation
@@ -1,11 +1,8 @@
- dialog "Subagent sessions":
- heading "Subagents" [level=3]
- paragraph: No subagents
- tree "Subagent sessions"
- region "Task board":
- heading "Shared tasks 1 pending" [level=3]
- list:
- listitem:
- button "Pending Plan before delegation":
- img "Pending"
- text: Plan before delegation
- region "Shared tasks":
- heading "Shared tasks" [level=2]
- text: 1 pending
- list:
- listitem:
- button "Pending Plan before delegation":
- img "Pending"
- text: Plan before delegation
@@ -1,10 +1,15 @@
- dialog "Subagent sessions":
- heading "Subagents" [level=3]
- text: 1 external
- tree "Subagent sessions":
- 'treeitem "Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. team-panel-researcher · External task" [disabled] [level=1]': "Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. team-panel-researcher"
- region "Task board":
- heading "Shared tasks 1 in progress" [level=3]
- complementary "Session panel":
- region "Environment":
- heading "Environment" [level=2]
- text: workspace {{cwd}}
- region "Subagents":
- heading "Subagents" [level=2]
- text: 1 external
- tree "Subagent sessions":
- 'treeitem "Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. team-panel-researcher · External task" [disabled] [level=1]': "Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result."
- region "Shared tasks":
- heading "Shared tasks" [level=2]
- text: 1 in progress
- list:
- listitem:
- button "In progress Agent task" [expanded]:
@@ -1,9 +1,11 @@
- list "Background jobs":
- listitem:
- button "Finished 1" [expanded]
- button "Clear"
- listitem:
- button "Hide live output of printf 'streamed-%s\\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done" [expanded]: "bash printf 'streamed-%s\\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done signal: SIGTERM; web e2e cancellation {{duration}}"
- text: $ printf 'streamed-%s\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done
- button "Copy"
- text: streamed-marker-line
- region "Background jobs":
- heading "Background jobs" [level=2]
- list:
- listitem:
- button "Finished 1" [expanded]
- button "Clear"
- listitem:
- button "Hide live output of printf 'streamed-%s\\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done" [expanded]: "printf 'streamed-%s\\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done bash · signal: SIGTERM; web e2e cancellation {{duration}}"
- text: $ printf 'streamed-%s\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done
- button "Copy"
- text: streamed-marker-line
@@ -1,7 +1,9 @@
- list "Background jobs":
- listitem:
- button "Hide live output of printf 'streamed-%s\\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done" [expanded]: printf 'streamed-%s\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done bash {{duration}}
- button "Stop task printf 'streamed-%s\\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done"
- text: $ printf 'streamed-%s\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done
- button "Copy"
- text: streamed-marker-line
- region "Background jobs":
- heading "Background jobs" [level=2]
- list:
- listitem:
- button "Hide live output of printf 'streamed-%s\\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done" [expanded]: printf 'streamed-%s\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done bash · running {{duration}}
- button "Stop task printf 'streamed-%s\\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done"
- text: $ printf 'streamed-%s\n' marker-line; for _ in $(seq 1 3000); do [ -e .live-job-stream.release ] && break; sleep 0.2; done
- button "Copy"
- text: streamed-marker-line
+209 -134
View File
@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import { zstdCompressSync } from 'node:zlib'
import type { Browser, Page } from 'playwright'
import type { Browser, Locator, Page, Response } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished, vi } from 'vitest'
import { prepareSessionSnapshotFixtureForComparison } from '@deepseek-ai/dsh-llm-replay'
@@ -20,7 +20,10 @@ import {
launchWebScaffold, readPersistedEvents, realizeSeedFixture, seedSession, selectedSessionFixture, watchConsole,
webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { connectFreshWorkspace, newEnglishPage, pinBrowserClock, pinHostClock, saveFailureShot, writeComposerDraft } from './support.ts'
import {
connectFreshWorkspace, dismissSessionPanel, foldControlLayout, newEnglishPage, pinBrowserClock, pinHostClock, saveFailureShot,
sessionPanelToggle, showSessionPanel, writeComposerDraft,
} from './support.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
const BASE_FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v3.jsonl', import.meta.url))
@@ -39,6 +42,7 @@ const MIGRATING_CHILD_EXPECTED = fileURLToPath(new URL(
'./expected/subagent-conversation/migration-required-child.expected.md', import.meta.url,
))
const MODE = webSnapshotMode()
const SUBAGENTS_SECTION = '[data-session-panel-section="subagents"]'
const LABEL = 'event-sourcing researcher'
/** The live child's catalog name; it is the parent's first named child. */
const CHILD_NAME = 'agent-1'
@@ -80,6 +84,24 @@ function childFixture(source: string, fixtureId: string, withContinuation: boole
return [childHeader, ...eventLines, ...continued, ''].join('\n')
}
/**
* Show the Session panel and return its Subagents section.
* @param page - the page under test.
* @returns the section.
*/
async function showSubagentsSection(page: Page): Promise<Locator> {
return (await showSessionPanel(page)).locator(SUBAGENTS_SECTION)
}
/** Whether a response answers the projection read of one Session. */
function projectionReadOf(sessionId: SessionId): (response: Response) => boolean {
return (response) => {
if (!response.url().endsWith('/api/session/projections')) return false
const body = response.request().postDataJSON() as { payload: { args: { request: { sessionId: SessionId } } } }
return body.payload.args.request.sessionId === sessionId
}
}
async function waitForAgentToSettle(scaffold: WebScaffold, id: SessionId): Promise<void> {
const deadline = Date.now() + 30_000
while (scaffold.ctx.agents.get(id) !== undefined) {
@@ -222,7 +244,8 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
await oneShotHandle.close()
scaffold.ctx.sessionProjectionCache.coldSnapshot(oneShotHeader, SessionLogOffset(0), oneShotEvents)
await waitForCacheRow(scaffold, oneShotHeader)
await page.getByRole('button', { name: '1 subagent', exact: true }).waitFor({ timeout: 15_000 })
const pushedSection = await showSubagentsSection(page)
await pushedSection.getByRole('treeitem', { name: new RegExp(LABEL) }).waitFor({ timeout: 15_000 })
const catalogReads = apiCalls.filter(path => path === '/api/session/projections').length
parent.session.append('subagent/catalog', {
version: 0,
@@ -231,10 +254,12 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
mode: 'one-shot',
label: ONE_SHOT_LABEL,
})
const pushedCount = page.getByRole('button', { name: '2 subagents', exact: true })
await pushedCount.waitFor({ timeout: 15_000 })
await pushedSection.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) }).waitFor({ timeout: 15_000 })
await pushedSection.getByText('1 completed\u2002·\u20021 not running', { exact: true }).waitFor({ timeout: 15_000 })
expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(catalogReads)
await compareOrRefreshGolden(CATALOG_PUSH_EXPECTED, await pushedCount.ariaSnapshot(), MODE)
await compareOrRefreshGolden(CATALOG_PUSH_EXPECTED,
await pushedSection.getByRole('heading', { level: 2 }).locator('..').ariaSnapshot(), MODE)
await dismissSessionPanel(page)
grandchildId = brandString<sessionId>('recorded-grandchild')
const authoredAt = Date.now()
const grandchildHeader: SessionHeader = {
@@ -343,13 +368,9 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
const warningStart = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
const catalogButton = page.getByRole('button', { name: '2 subagents', exact: true })
await catalogButton.waitFor({ timeout: 15_000 })
await catalogButton.hover()
const catalogTree = page.getByRole('tree', { name: 'Subagent sessions' })
const catalogTree = (await showSubagentsSection(page)).getByRole('tree', { name: 'Subagent sessions' })
await catalogTree.getByRole('treeitem').nth(1).waitFor({ timeout: 15_000 })
await catalogTree.press('Escape')
await page.getByRole('button', { name: '2 subagents' }).waitFor({ timeout: 15_000 })
await dismissSessionPanel(page)
acknowledgeReloadConnectionLoss(tripwire, warningStart)
}, 120_000)
@@ -366,58 +387,59 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
if (failures.length > 1) throw new AggregateError(failures, 'subagent Web teardown failed')
})
it('retries a failed cold catalog and discovers descendants without reopening the menu', async () => {
it('retries a failed cold catalog and discovers descendants through the breadcrumb switcher', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-unread-catalog'))
const reads = apiCalls.filter(path => path === '/api/session/projections').length
const observe = vi.spyOn(scaffold.ctx.sessionQuery, 'observeSession')
// The Session panel reads nothing when it shows; the child's switcher is the explicit activation of the parent's level.
const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
const trigger = hierarchy.getByRole('button', { name: `Switch subagent: ${LABEL}`, exact: true })
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(LABEL, { exact: true }).click()
await trigger.waitFor()
// A reload forgets every catalog read while the child conversation stays open.
const warningStart = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
await trigger.waitFor({ timeout: 30_000 })
acknowledgeReloadConnectionLoss(tripwire, warningStart)
const projections = vi.spyOn(scaffold.ctx.sessionController, 'projections')
const menu = page.locator('[data-subagent-panel]')
const tree = menu.getByRole('tree', { name: 'Subagent sessions' })
try {
const trigger = page.getByRole('button', { name: '2 subagents', exact: true })
const childUrl = page.url()
await page.locator('[data-composer-input]').first().hover()
const reads = apiCalls.filter(path => path === '/api/session/projections').length
await trigger.hover()
const tree = page.getByRole('tree', { name: 'Subagent sessions' })
const child = tree.getByRole('treeitem', { name: new RegExp(LABEL) })
await child.waitFor()
expect(await child.getAttribute('aria-expanded')).toBeNull()
expect(await tree.getByRole('button', { name: /^(Expand|Collapse) /u }).count()).toBe(0)
expect(await tree.getByText(/Loading subagents|unknown/u).count()).toBe(0)
await tree.getByRole('treeitem', { name: new RegExp(LABEL) }).waitFor()
// The open child's own conversation supplies its catalog; its sibling's stays unread until activation.
expect(await tree.getByRole('button', { name: `Expand ${ONE_SHOT_LABEL} descendants`, exact: true }).count()).toBe(0)
expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(reads)
expect(observe).not.toHaveBeenCalled()
const parentUrl = page.url()
await page.route('**/api/session/projections', route => route.abort('failed'), { times: 1 })
await trigger.click()
const retry = tree.getByRole('button', { name: 'Retry', exact: true })
await retry.waitFor()
expect(await tree.getByRole('button', { name: /^(Expand|Collapse) /u }).count()).toBe(0)
expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(reads + 1)
expect(projections).not.toHaveBeenCalled()
const siblingsRead = page.waitForResponse(projectionReadOf(oneShotId))
await retry.click()
await (await siblingsRead).finished()
await retry.waitFor({ state: 'detached' })
const expand = page.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true })
const expand = tree.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true })
await expand.waitFor()
await expect.poll(() => projections.mock.calls.map(([request]) => request.sessionId)).toEqual([parentId, childId, oneShotId])
expect(observe.mock.calls.some(([id]) => id === grandchildId)).toBe(false)
const lastRead = page.waitForResponse('**/api/session/projections')
expect(projections.mock.calls.map(([request]) => request.sessionId)).toEqual(expect.arrayContaining([parentId, oneShotId]))
expect(projections.mock.calls.some(([request]) => request.sessionId === grandchildId)).toBe(false)
const descendantsRead = page.waitForResponse(projectionReadOf(grandchildId))
await expand.click()
await (await lastRead).finished()
await expect.poll(() => projections.mock.calls.map(([request]) => request.sessionId))
.toEqual([parentId, childId, oneShotId, grandchildId])
await (await descendantsRead).finished()
const grandchild = tree.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) })
await grandchild.waitFor()
expect(await grandchild.getAttribute('aria-expanded')).toBeNull()
await compareOrRefreshGolden(
TREE_EXPECTED,
await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd), MODE,
)
expect(page.url()).toBe(parentUrl)
expect(page.url()).toBe(childUrl)
expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined()
await page.keyboard.press('Escape')
await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' })
await menu.waitFor({ state: 'detached' })
} finally {
await page.unroute('**/api/session/projections')
observe.mockRestore()
projections.mockRestore()
await hierarchy.getByRole('button').first().click()
await trigger.waitFor({ state: 'detached' })
}
})
@@ -435,9 +457,11 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
await writeComposerDraft(page, input, '')
})
it('enters the member tree after pointer or keyboard activation of its trigger', async () => {
it('enters the sibling tree after pointer or keyboard activation of the breadcrumb switcher', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-trigger-focus'))
const trigger = page.getByRole('button', { name: '2 subagents', exact: true })
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(LABEL, { exact: true }).click()
const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
const trigger = hierarchy.getByRole('button', { name: `Switch subagent: ${LABEL}`, exact: true })
const panel = page.locator('[data-subagent-panel]')
try {
for (const activation of ['click', 'Enter', 'Space']) {
@@ -453,83 +477,86 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
}
} finally {
await page.locator('[data-composer-input]').first().hover()
await hierarchy.getByRole('button').first().click()
await trigger.waitFor({ state: 'detached' })
}
})
it('shows complete descriptions and names without hover at desktop and touch widths', async () => {
it('shows each subagent on one line and its name, state, and measures in a hover card', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-catalog-labels'))
const originalViewport = page.viewportSize()!
const originalUrl = page.url()
try {
for (const width of [originalViewport.width, 390]) {
await page.setViewportSize({ ...originalViewport, width })
const trigger = page.getByRole('button', { name: '2 subagents', exact: true })
await trigger.click()
const panel = page.locator('[data-subagent-panel]')
const row = panel.getByRole('treeitem', { name: new RegExp(LABEL) })
const primary = row.getByText(LABEL, { exact: true })
const secondary = row.getByText(CHILD_NAME, { exact: true })
const primaryBounds = await primary.boundingBox()
const secondaryBounds = await secondary.boundingBox()
expect(primaryBounds).not.toBeNull()
expect(secondaryBounds).not.toBeNull()
expect(primaryBounds!.y + primaryBounds!.height).toBeLessThanOrEqual(secondaryBounds!.y)
for (const label of [primary, secondary]) {
expect(await label.evaluate(element => element.scrollWidth <= element.clientWidth
&& element.scrollHeight <= element.clientHeight)).toBe(true)
}
expect(await row.getAttribute('aria-label')).toContain(`${LABEL} ${CHILD_NAME} `)
expect(await row.getByRole('button', { name: /description/u }).count()).toBe(0)
await row.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).waitFor()
expect(await row.getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).count()).toBe(1)
expect(page.url()).toBe(originalUrl)
expect(await page.getByRole('tooltip').count()).toBe(0)
expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
await page.keyboard.press('Escape')
await panel.waitFor({ state: 'detached' })
}
const panel = await showSubagentsSection(page)
const row = panel.getByRole('treeitem', { name: new RegExp(LABEL) })
const primary = row.getByText(LABEL, { exact: true })
// The row holds one 28px line; the name stays in its accessible name.
expect(await row.evaluate(element => element.getBoundingClientRect().height)).toBe(28)
expect(await primary.evaluate(element => getComputedStyle(element).whiteSpace)).toBe('nowrap')
expect(await row.getByText(CHILD_NAME, { exact: true }).count()).toBe(0)
expect(await row.getAttribute('aria-label')).toContain(`${LABEL} ${CHILD_NAME} `)
expect(await row.getByRole('button', { name: /description/u }).count()).toBe(0)
await row.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).waitFor()
expect(await row.getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).count()).toBe(1)
await primary.hover()
const card = page.locator('[data-session-panel-details]')
await card.waitFor()
expect(await card.evaluate(element => [...element.children].map(child => child.textContent).slice(0, 3)))
.toEqual([LABEL, `Owner: ${CHILD_NAME}`, 'completed · continuable'])
// The panel sits at the window's end, so the stylesheet opens the card on the row's start side:
// 8px before the row, its top on the row's top, inside the viewport.
const placement = await card.evaluate((element) => {
// The details sit inside the fixed card, and the card's anchor wraps the row.
let fixed = element
while (getComputedStyle(fixed).position !== 'fixed') fixed = fixed.parentElement!
const bounds = fixed.getBoundingClientRect()
const row = document.querySelector('[data-subagents-section] [role="treeitem"]')!.parentElement!.getBoundingClientRect()
return { inside: bounds.left >= 8, gap: row.left - bounds.right, top: bounds.top - row.top }
})
expect(placement).toEqual({ inside: true, gap: 8, top: 0 })
expect(page.url()).toBe(originalUrl)
expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
await page.locator('[data-composer-input]').first().hover()
await card.waitFor({ state: 'detached' })
await dismissSessionPanel(page)
} finally {
await page.setViewportSize(originalViewport)
await page.locator('[data-composer-input]').first().hover()
}
})
it('expands locally available cold catalogs without requesting or activating either level', async () => {
onTestFailed(() => saveFailureShot(page, 'screenshots/non-migrating-session-reads/web-e2e-subagent-tree'))
// From a fresh page, the child's switcher prepares the parent's level and the child's; back in the parent, the
// panel expands both from the catalogs those reads left, requesting nothing more.
const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
const trigger = hierarchy.getByRole('button', { name: `Switch subagent: ${LABEL}`, exact: true })
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(LABEL, { exact: true }).click()
await trigger.waitFor()
const warningStart = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
const trigger = page.getByRole('button', { name: '2 subagents', exact: true })
await trigger.waitFor()
await trigger.waitFor({ timeout: 30_000 })
acknowledgeReloadConnectionLoss(tripwire, warningStart)
const siblingsRead = page.waitForResponse((response) => {
if (!response.url().endsWith('/api/session/projections')) return false
const body = response.request().postDataJSON() as { payload: { args: { request: { sessionId: SessionId } } } }
return body.payload.args.request.sessionId === oneShotId
})
const siblingsRead = page.waitForResponse(projectionReadOf(oneShotId))
await trigger.click()
await (await siblingsRead).finished()
const expand = page.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true })
const menu = page.locator('[data-subagent-panel]')
const expand = menu.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true })
await expand.waitFor()
const descendantsRead = page.waitForResponse((response) => {
if (!response.url().endsWith('/api/session/projections')) return false
const body = response.request().postDataJSON() as { payload: { args: { request: { sessionId: SessionId } } } }
return body.payload.args.request.sessionId === grandchildId
})
const descendantsRead = page.waitForResponse(projectionReadOf(grandchildId))
await expand.click()
await (await descendantsRead).finished()
await page.keyboard.press('Escape')
await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' })
const catalogReads = apiCalls.filter(path => path === '/api/session/projections').length
await menu.waitFor({ state: 'detached' })
await hierarchy.getByRole('button').first().click()
await trigger.waitFor({ state: 'detached' })
await page.locator('[data-composer-input]').first().hover()
await trigger.hover()
const catalogTree = page.getByRole('tree', { name: 'Subagent sessions' })
const catalogTree = (await showSubagentsSection(page)).getByRole('tree', { name: 'Subagent sessions' })
await catalogTree.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).waitFor()
const catalogReads = apiCalls.filter(path => path === '/api/session/projections').length
expect(await catalogTree.evaluate((element) => {
const rect = element.getBoundingClientRect()
const hit = document.elementFromPoint(rect.left + 8, rect.top + 8)
return hit !== null && element.contains(hit)
})).toBe(true)
const sectionHeader = page.locator('[data-subagent-section-header]')
expect(await sectionHeader.count()).toBe(0)
const oneShotDisclosure = page.getByRole('button', {
name: `Expand ${ONE_SHOT_LABEL} descendants`,
})
@@ -592,7 +619,6 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
expect(await catalogTree.getByText('Loading subagents…', { exact: true }).count()).toBe(0)
expect(await grandchildRow.getAttribute('aria-expanded')).toBeNull()
expect(await grandchildRow.getByRole('button', { name: `Expand ${NESTED_LABEL} descendants` }).count()).toBe(0)
expect(await sectionHeader.count()).toBe(0)
await clickDisclosureGutter(26)
await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ state: 'detached' })
expect(await childRow.getAttribute('aria-expanded')).toBe('false')
@@ -605,7 +631,8 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
const dotBounds = dot.getBoundingClientRect()
const slot = dot.parentElement!.getBoundingClientRect()
const horizontal = getComputedStyle(row, '::before')
const node = row.parentElement!
// The row sits in its hover card's anchor wrapper inside the tree node.
const node = row.closest('[role="group"] > *')!
const spine = getComputedStyle(node, '::before')
const stroke = Number.parseFloat(horizontal.borderTopWidth)
const colorProbe = document.createElement('span')
@@ -652,20 +679,19 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
)
await compareOrRefreshGolden(TREE_EXPECTED, snapshot, MODE)
expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(catalogReads)
await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).getByText(grandchildId, { exact: true }).click()
await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).getByText(NESTED_LABEL, { exact: true }).click()
await page.getByText(NESTED_PROMPT).waitFor()
const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
await hierarchy.getByRole('button', { name: `Switch subagent: ${LABEL}`, exact: true }).waitFor()
expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined()
await hierarchy.getByRole('button').first().click()
await page.getByRole('button', { name: '2 subagents', exact: true }).waitFor()
await hierarchy.getByRole('button', { name: /^Switch subagent:/u }).waitFor({ state: 'detached' })
})
it('opens child history in the right Sidebar and releases it when closed', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-sidebar-chat'))
await page.getByRole('button', { name: '2 subagents' }).hover()
await page.getByRole('treeitem', { name: new RegExp(LABEL) }).getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).click()
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(LABEL) })
.getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).click()
const sidebarChat = page.locator('[data-sidebar-chat]')
await sidebarChat.getByText(/^Explain event sourcing in one sentence\./).waitFor({ timeout: 15_000 })
await compareOrRefreshGolden(
@@ -676,8 +702,8 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
await page.locator('[data-sidebar-right-panel] [data-dockkit-tab-close]').click()
await sidebarChat.waitFor({ state: 'detached' })
await page.getByRole('button', { name: '2 subagents' }).hover()
await page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) }).getByRole('button', { name: `Open ${ONE_SHOT_LABEL} in sidebar`, exact: true }).click()
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) })
.getByRole('button', { name: `Open ${ONE_SHOT_LABEL} in sidebar`, exact: true }).click()
await page.locator('[data-sidebar-chat]').getByText(
'One-shot tasks do not accept follow-ups; review the full execution record here.',
).waitFor({ timeout: 15_000 })
@@ -687,8 +713,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
it('opens the completed child from persistence without activating it', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-open'))
await page.getByRole('button', { name: '2 subagents' }).hover()
await page.getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(LABEL, { exact: true }).click()
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(LABEL, { exact: true }).click()
await expect.poll(
() => page.getByText(/^Explain event sourcing in one sentence\./).count(),
{ timeout: 15_000 },
@@ -714,8 +739,12 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
.toEqual([{ fontSize: '14px', lineHeight: '20px' }, { fontSize: '14px', lineHeight: '20px' }])
expect(Math.abs(crumbGeometry[0]!.top - crumbGeometry[1]!.top), JSON.stringify(crumbGeometry)).toBeLessThanOrEqual(1)
expect(Math.abs(crumbGeometry[0]!.bottom - crumbGeometry[1]!.bottom), JSON.stringify(crumbGeometry)).toBeLessThanOrEqual(1)
expect(await hierarchy.getByRole('button', { name: '1 subagent', exact: true })
.evaluate(element => getComputedStyle(element).fontSize)).toBe('12px')
// The breadcrumb holds only the two titles; the child's own subagents are listed by its Session panel.
expect(await hierarchy.getByRole('button').count()).toBe(2)
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor()
await dismissSessionPanel(page)
// Park the pointer off the toggle so its tooltip stays out of later captures.
await page.locator('[data-composer-input]').first().hover()
const sidebar = await captureStableAria(
page,
'[role="tree"][aria-label="Sessions"]',
@@ -801,8 +830,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
it('opens a persisted grandchild with input enabled while its creator is offline', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-grandchild'))
await page.getByRole('button', { name: '1 subagent' }).hover()
const tree = page.getByRole('tree', { name: 'Subagent sessions' })
const tree = (await showSubagentsSection(page)).getByRole('tree', { name: 'Subagent sessions' })
const nestedRow = tree.locator('[role="treeitem"]').filter({ hasText: NESTED_LABEL })
await nestedRow.waitFor({ timeout: 15_000 })
const nestedDisclosure = page.getByRole('button', {
@@ -811,23 +839,23 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
expect(await nestedDisclosure.count()).toBe(0)
const clickArea = nestedRow.locator(':scope > div')
expect(await clickArea.count()).toBe(1)
const [menuBox, clickAreaBox] = await Promise.all([
page.locator('[data-subagent-panel]').boundingBox(),
const [panelBox, clickAreaBox] = await Promise.all([
page.locator('[data-session-panel]').boundingBox(),
clickArea.boundingBox(),
])
expect(menuBox).not.toBeNull()
expect(panelBox).not.toBeNull()
expect(clickAreaBox).not.toBeNull()
expect([
Math.round(clickAreaBox!.x - menuBox!.x),
Math.round(menuBox!.x + menuBox!.width - clickAreaBox!.x - clickAreaBox!.width),
// Menu padding plus the branchless row's one-pixel leading inset.
]).toEqual([7, 6])
Math.round(clickAreaBox!.x - panelBox!.x),
Math.round(panelBox!.x + panelBox!.width - clickAreaBox!.x - clickAreaBox!.width),
// The panel's padding on both sides: the row spans the section body.
]).toEqual([8, 8])
await compareOrRefreshGolden(
BRANCHLESS_EXPECTED,
await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd),
MODE,
)
await nestedRow.getByText(grandchildId, { exact: true }).click()
await nestedRow.getByText(NESTED_LABEL, { exact: true }).click()
await page.getByText(NESTED_PROMPT).waitFor()
expect(await page.getByRole('textbox', { name: 'Message or run a task, / commands, @ files or sessions' }).isEnabled()).toBe(true)
const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
@@ -847,8 +875,8 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
const parentSession = page.getByRole('tree', { name: 'Sessions' })
.getByRole('treeitem', { name: /Ask a research subagent to/ })
await parentSession.click()
await page.getByRole('button', { name: '2 subagents' }).hover()
await page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) }).getByText(oneShotId, { exact: true }).click()
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) })
.getByText(ONE_SHOT_LABEL, { exact: true }).click()
await page.getByText('One-shot tasks do not accept follow-ups; review the full execution record here.').waitFor()
expect(scaffold.ctx.agents.get(oneShotId)).toBeUndefined()
})
@@ -858,8 +886,8 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
await page.getByRole('tree', { name: 'Sessions' })
.getByRole('treeitem', { name: /Ask a research subagent to/ })
.click()
await page.getByRole('button', { name: '2 subagents' }).hover()
await page.getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(CHILD_NAME, { exact: true }).click()
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(LABEL) })
.getByText(LABEL, { exact: true }).click()
await page.getByRole('textbox', { name: 'Message or run a task, / commands, @ files or sessions' }).waitFor()
const forkResponse = page.waitForResponse(response =>
new URL(response.url()).pathname === '/api/session/fork')
@@ -887,8 +915,8 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-post-fork-followup'))
const sessions = page.getByRole('tree', { name: 'Sessions' })
await sessions.getByRole('treeitem', { name: /Ask a research subagent to/ }).click()
await page.getByRole('button', { name: '2 subagents' }).hover()
await page.getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(CHILD_NAME, { exact: true }).click()
await (await showSubagentsSection(page)).getByRole('treeitem', { name: new RegExp(LABEL) })
.getByText(LABEL, { exact: true }).click()
await page.locator('[data-composer-input][contenteditable="true"]').first().waitFor()
expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
@@ -904,8 +932,9 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
await expect.poll(() => scaffold.ctx.agents.get(forkId)).not.toBeUndefined()
await sessions.getByRole('treeitem', { name: /Ask a research subagent to/ }).click()
await page.getByRole('button', { name: '2 subagents' }).press('ArrowDown')
await page.getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(CHILD_NAME, { exact: true }).click()
await sessionPanelToggle(page).press('Enter')
await page.locator(SUBAGENTS_SECTION).getByRole('treeitem', { name: new RegExp(LABEL) })
.getByText(LABEL, { exact: true }).click()
const input = page.locator('[data-composer-input][contenteditable="true"]').first()
await input.waitFor()
const promptResponse = page.waitForResponse(response =>
@@ -941,25 +970,24 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
})
await page.getByRole('tree', { name: 'Sessions' })
.getByRole('treeitem', { name: /Ask a research subagent to/ }).click()
await page.getByRole('button', { name: '2 subagents', exact: true }).click()
await page.locator('[data-team-panel]').getByText('Root-only shared task', { exact: true }).waitFor()
const rootHeader = page.locator('[data-subagent-section-header]')
const rootSection = await showSubagentsSection(page)
await page.locator('[data-session-panel-section="shared-tasks"] [data-team-panel]')
.getByText('Root-only shared task', { exact: true }).waitFor()
const rootHeader = rootSection.getByRole('heading', { level: 2 }).locator('..')
expect(await rootHeader.textContent()).toBe('Subagents1 completed\u2002·\u20021 not running')
expect(await rootHeader.getByRole('button').count()).toBe(0)
expect(await rootHeader.locator('[data-icon="dsw-icon-users-outline-regular"]').count()).toBe(1)
const progress = await rootHeader.textContent()
await page.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).click()
await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor()
expect(await rootHeader.textContent()).toBe(progress)
await page.getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(CHILD_NAME, { exact: true }).click()
await page.getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(LABEL, { exact: true }).click()
const switcher = page.getByRole('button', { name: `Switch subagent: ${LABEL}`, exact: true })
await switcher.click()
const panel = page.locator('[data-subagent-panel]')
await panel.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) }).waitFor()
expect(await panel.locator('[data-team-panel]').count()).toBe(0)
expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360)
const header = panel.locator('[data-subagent-section-header]')
expect(await header.count()).toBe(0)
expect(await panel.getByRole('heading').count()).toBe(0)
expect(await switcher.textContent()).toBe(LABEL)
const currentRow = panel.getByRole('treeitem', { name: new RegExp(LABEL) })
const currentCheck = currentRow.locator('[data-subagent-current]')
@@ -978,7 +1006,54 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
await page.keyboard.press('Escape')
})
it('holds back the subagents past five behind the fold control and keeps the choice while the panel is hidden', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-fold'))
const parent = scaffold.ctx.agents.get(parentId)
if (parent === undefined) throw new Error('fold fixture requires the live parent')
await page.getByRole('tree', { name: 'Sessions' })
.getByRole('treeitem', { name: /Ask a research subagent to/ }).click()
// Six catalog-only members, each created after every row so far: the Client holds no summary for them,
// so they sort by when the parent created them, the latest first.
const createdAfter = Date.now() + 60_000
for (let index = 0; index < 6; index++) {
parent.session.append('subagent/catalog', {
version: 0,
childId: brandString<sessionId>(`fold-member-${String(index)}`),
childCreatedAt: createdAfter + index,
mode: 'one-shot',
label: `fold member ${String(index)}`,
})
}
const section = await showSubagentsSection(page)
const rows = section.getByRole('treeitem')
const fold = section.locator('[data-session-panel-row="fold"]')
const labels = async (): Promise<string[]> => (await rows.evaluateAll(items => items.map(item => item.getAttribute('aria-label') ?? '')))
.map(label => /^fold member \d/.exec(label)?.[0] ?? 'earlier')
// Eight members: the five created last show, the latest first, and the fold control holds back three.
await expect.poll(labels, { timeout: 15_000 })
.toEqual(['fold member 5', 'fold member 4', 'fold member 3', 'fold member 2', 'fold member 1'])
expect(await fold.textContent()).toBe('Show 3 more')
// The title counts every member, shown or held back.
expect(await section.getByRole('heading', { level: 2 }).locator('..').textContent()).toBe('Subagents1 completed\u2002·\u20027 not running')
// The control follows the tree, at the row height, with its chevron under the state marks and its text under the names.
expect(await section.getByRole('tree').locator('[data-session-panel-row="fold"]').count()).toBe(0)
expect(await foldControlLayout(fold, rows.first(), '[class*="content"] > span'))
.toEqual({ heights: [28, 28], chevronOffset: 0, textOffset: 0, fontSize: '12px', expanded: 'false' })
await section.getByRole('button', { name: 'Show 3 more (subagents)', exact: true }).click()
await expect.poll(labels).toEqual([
'fold member 5', 'fold member 4', 'fold member 3', 'fold member 2', 'fold member 1', 'fold member 0', 'earlier', 'earlier',
])
const less = section.getByRole('button', { name: 'Show less (subagents)', exact: true })
expect([await less.textContent(), await less.getAttribute('aria-expanded')]).toEqual(['Show less', 'true'])
// The choice is the Session's: it holds while the panel is hidden.
await dismissSessionPanel(page)
await showSubagentsSection(page)
await expect.poll(() => rows.count()).toBe(8)
await less.click()
await expect.poll(() => rows.count()).toBe(5)
expect(tripwire.pageErrors).toEqual([])
await dismissSessionPanel(page)
})
})
describe('web e2e: migration-required subagent catalog', () => {
@@ -1071,8 +1146,8 @@ describe('web e2e: migration-required subagent catalog', () => {
const workspaceRow = page.getByRole('tree', { name: 'Sessions' }).getByRole('treeitem').first()
await workspaceRow.click()
await page.locator(`[data-row-key="session:${parentId}"]`).click()
await page.getByRole('button', { name: '1 subagent', exact: true }).hover()
const tree = page.getByRole('tree', { name: 'Subagent sessions' })
await showSessionPanel(page)
const tree = page.locator(SUBAGENTS_SECTION).getByRole('tree', { name: 'Subagent sessions' })
const childRow = tree.getByRole('treeitem', { name: new RegExp(childLabel) })
await childRow.waitFor()
await expect.poll(() => childRow.getByRole('button', { name: `Expand ${childLabel} descendants`, exact: true }).count()).toBe(0)
@@ -1090,9 +1165,9 @@ describe('web e2e: migration-required subagent catalog', () => {
expect(observe.mock.calls.some(([id]) => id === childId || id === grandchildId)).toBe(false)
expect(projections).not.toHaveBeenCalled()
await childRow.getByText(childId, { exact: true }).click()
await childRow.getByText(childLabel, { exact: true }).click()
await page.getByRole('button', { name: `Switch subagent: ${childLabel}`, exact: true }).waitFor()
await page.getByRole('button', { name: '1 subagent', exact: true }).hover()
await showSessionPanel(page)
const grandchildRow = tree.getByRole('treeitem', { name: new RegExp(grandchildLabel) })
await grandchildRow.waitFor()
expect(await grandchildRow.textContent()).not.toContain('Migration required')
+3 -3
View File
@@ -11,7 +11,7 @@ import { expect, it, onTestFailed } from 'vitest'
import { parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
import type {} from '@deepseek-ai/dsh-subagent'
import { launchWebScaffold, selectedSessionFixture, watchConsole } from './scaffold.ts'
import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
import { connectFreshWorkspace, newEnglishPage, saveFailureShot, showSessionPanel } from './support.ts'
const DIR = fileURLToPath(new URL('../../../snapshots/web/subagent-fork-schedule', import.meta.url))
const LABEL = 'Check child reminder refusal'
@@ -50,8 +50,8 @@ it('places the inherited-history divider between the parent turn and the child p
} finally {
await activation.dispose()
}
await page.getByRole('button', { name: '1 subagent' }).click()
await page.getByRole('tree', { name: 'Subagent sessions' }).getByRole('treeitem', { name: new RegExp(LABEL) }).click()
const subagents = (await showSessionPanel(page)).locator('[data-session-panel-section="subagents"]')
await subagents.getByRole('tree', { name: 'Subagent sessions' }).getByRole('treeitem', { name: new RegExp(LABEL) }).click()
const divider = page.getByRole('separator', { name: 'Inherited history above' })
await divider.waitFor({ timeout: 15_000 })
expect(await divider.count()).toBe(1)
+5 -7
View File
@@ -8,7 +8,7 @@
// Replay-binding note: only the PRIMARY script can hang, and scripts bind by
// first-call order, so the child issues the composition's first model call
// (claiming the overridden primary) and the parent's one UI prompt — needed
// so the non-blank parent renders its header catalog — binds to a derived
// so the non-blank parent lists its subagents in the Session panel — binds to a derived
// child fixture afterwards.
import { existsSync } from 'node:fs'
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
@@ -25,7 +25,7 @@ import {
acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
launchWebScaffold, readPersistedEvents, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts'
import { connectFreshWorkspace, newEnglishPage, saveFailureShot, showSessionPanel } from './support.ts'
const BASE_FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v3.jsonl', import.meta.url))
@@ -171,7 +171,7 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co
const warningStart = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
await page.getByRole('button', { name: /1 subagent/ }).waitFor({ timeout: 15_000 })
await (await showSessionPanel(page)).getByRole('treeitem', { name: new RegExp(LABEL) }).waitFor({ timeout: 15_000 })
acknowledgeReloadConnectionLoss(tripwire, warningStart)
expect(scaffold.ctx.agents.get(childId)?.status).toBe('running')
}, 120_000)
@@ -209,8 +209,7 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co
await page.reload({ waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
acknowledgeReloadConnectionLoss(tripwire, warningStart)
await page.getByRole('button', { name: /1 subagent/ }).click()
await page.getByRole('treeitem', { name: new RegExp(LABEL) }).press('Enter')
await (await showSessionPanel(page)).getByRole('treeitem', { name: new RegExp(LABEL) }).press('Enter')
const input = page.locator('[data-composer-input]').first()
await input.waitFor({ timeout: 15_000 })
await page.getByText(/^Explain event sourcing in one sentence\./)
@@ -269,8 +268,7 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co
acknowledgeReloadConnectionLoss(tripwire, warningStart)
await page.getByRole('navigation', { name: 'Session hierarchy' })
.getByRole('button').first().click()
await page.getByRole('button', { name: /1 subagent/ }).click()
await page.getByRole('treeitem', { name: new RegExp(LABEL) }).press('Enter')
await (await showSessionPanel(page)).getByRole('treeitem', { name: new RegExp(LABEL) }).press('Enter')
// A live continuable child advertises the ordinary steer-all gesture, so
// that placeholder is the composer's accessible name in this window. It
// changes back as the queue drains, so later interactions address the
+90
View File
@@ -480,6 +480,96 @@ export async function openSettings(page: Page, locale: 'en' | 'zh' | 'ja'): Prom
await page.getByRole('menuitem', { name: labels[locale][1], exact: true }).click()
}
/** The Session panel toggle in the Session header. */
export function sessionPanelToggle(page: Page): Locator {
return page.locator('[data-session-panel-toggle]')
}
/**
* Show the Session panel unless it already shows, and wait for its entrance
* animation so geometry reads see the final position. A panel over the
* conversation closes on presses outside it and a narrower window can hide
* it, so each step that reads the panel shows it first. While the layout
* settles after a resize the gutter can briefly read wide enough to dock, so
* the toggle is pressed again until the panel stays visible.
* @param page - the page under test.
* @returns the panel.
*/
export async function showSessionPanel(page: Page): Promise<Locator> {
const toggle = sessionPanelToggle(page)
const panel = page.locator('[data-session-panel]')
await toggle.waitFor({ timeout: 20_000 })
// A plain loop, not expect.poll, so suite setup can call it too.
const deadline = Date.now() + 20_000
while (true) {
if (await toggle.getAttribute('aria-expanded') !== 'true') await toggle.click()
if (await panel.isVisible()) break
if (Date.now() >= deadline) throw new Error('the Session panel did not show')
await page.waitForTimeout(250)
}
await panel.evaluate(async (element) => {
await Promise.all(element.getAnimations().map(animation => animation.finished))
})
return panel
}
/**
* Close the Session panel shown over the conversation with Escape.
* @param page - the page under test.
*/
export async function dismissSessionPanel(page: Page): Promise<void> {
await page.keyboard.press('Escape')
await page.locator('[data-session-panel]').waitFor({ state: 'detached' })
}
/**
* Measure a Session panel fold control against a data row of its list: both
* heights, how far the control's chevron sits from the row's state mark and
* its text from the row's name, in px, and the control's type size and state.
* @param control - the fold control row (`[data-session-panel-row="fold"]`).
* @param row - a data row of the same list.
* @param name - selector of the row's name element inside `row`.
* @returns the measurements.
*/
export async function foldControlLayout(control: Locator, row: Locator, name: string): Promise<{
heights: [number, number]
chevronOffset: number
textOffset: number
fontSize: string
expanded: string | null
}> {
const rowBox = await row.evaluate((element, selector) => {
const mark = element.querySelector('[data-state]')!.getBoundingClientRect()
return {
height: element.getBoundingClientRect().height,
markCenter: mark.left + mark.width / 2,
nameLeft: element.querySelector(selector)!.getBoundingClientRect().left,
}
}, name)
return control.evaluate((element, data) => {
const chevron = element.querySelector('svg')!.getBoundingClientRect()
const text = document.createRange()
text.selectNodeContents(element.querySelector('[data-row-part="content"]')!)
return {
heights: [element.getBoundingClientRect().height, data.height] as [number, number],
chevronOffset: chevron.left + chevron.width / 2 - data.markCenter,
textOffset: text.getBoundingClientRect().left - data.nameLeft,
fontSize: getComputedStyle(element).fontSize,
expanded: element.querySelector('button')!.getAttribute('aria-expanded'),
}
}, rowBox)
}
/**
* Hide the Session panel unless it is already hidden.
* @param page - the page under test.
*/
export async function hideSessionPanel(page: Page): Promise<void> {
const toggle = sessionPanelToggle(page)
if (await toggle.getAttribute('aria-expanded') === 'true') await toggle.click()
await expect.poll(() => toggle.getAttribute('aria-expanded')).toBe('false')
}
/**
* The right Sidebar's fullscreen panel box: 1px wider than the viewport, so the
* first column's divider sits past the window's left edge where the frame clips it.
+2 -2
View File
@@ -16,6 +16,7 @@ import {
} from './scaffold.ts'
import {
connectFreshWorkspace, expandOwningTurnProcess, expandTurnProcesses, newEnglishPage, REPO_ROOT, saveFailureShot,
showSessionPanel,
} from './support.ts'
const MODE = webSnapshotMode()
@@ -218,8 +219,7 @@ describe.skipIf(MODE === 'record')('web e2e: durable workflow run in Chat', () =
await page.getByText(CHILD_PROMPT, { exact: false }).waitFor()
expect(await page.getByRole('button', { name: /^Open Reply with exactly the word/ }).count()).toBe(0)
await page.getByRole('button', { name: '1 subagent', exact: true }).hover()
const catalog = page.getByRole('tree', { name: 'Subagent sessions' })
const catalog = (await showSessionPanel(page)).getByRole('tree', { name: 'Subagent sessions' })
await catalog.getByRole('treeitem', { name: /snapshot-flow child 1/ }).press('Enter')
await page.getByText(CHILD_PROMPT, { exact: true }).waitFor({ timeout: 15_000 })
expect(await page.locator('[data-composer-input][contenteditable="true"]').count()).toBe(1)
@@ -541,6 +541,15 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo
// crossing ground that belongs to neither. Hovering it must not dismiss
// it — the hazard this scenario pins.
const card = page.getByRole('button', { name: `Copy: ${rowTitle}` })
// The stylesheet anchors the card: beside the row's end edge, its top on the row's top.
const beside = async (): Promise<{ gap: number; top: number; bottomMargin: number }> => {
const row = await sessionRow.boundingBox()
const box = await card.boundingBox()
if (row === null || box === null) throw new Error('the row or its hover card has no box')
const height = await page.evaluate(() => window.innerHeight)
return { gap: box.x - (row.x + row.width), top: box.y - row.y, bottomMargin: height - (box.y + box.height) }
}
expect(await beside()).toMatchObject({ gap: 8, top: 0 })
await card.hover()
await page.waitForTimeout(POINTER_HOLD_MS)
expect(await page.getByText('Idle', { exact: true }).count()).toBeGreaterThanOrEqual(1)
@@ -559,6 +568,23 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo
// Leaving anchor and card together closes it after the grace.
await page.getByRole('button', { name: 'Account menu', exact: true }).hover()
await expect.poll(() => card.count(), { timeout: 5_000 }).toBe(0)
// In a window too short for the card below the row's top, the card keeps
// its side and holds its bottom at the viewport's 8px margin.
const viewport = page.viewportSize()
const row = await sessionRow.boundingBox()
if (viewport === null || row === null) throw new Error('no viewport or row box')
await page.setViewportSize({ width: viewport.width, height: Math.ceil(row.y + row.height + 24) })
try {
await sessionRow.hover()
await card.waitFor({ timeout: 5_000 })
const held = await beside()
expect(held).toMatchObject({ gap: 8, bottomMargin: 8 })
expect(held.top).toBeLessThan(0)
await page.mouse.move(viewport.width - 20, 4)
await expect.poll(() => card.count(), { timeout: 5_000 }).toBe(0)
} finally {
await page.setViewportSize(viewport)
}
expect(tripwire.pageErrors).toEqual([])
}, 60_000)
+1 -1
View File
@@ -101,7 +101,7 @@
"tests/excel-opc.e2e.ts",
"tests/office-fixture.ts",
"tests/sidebar-browser.e2e.ts",
"tests/jobs-menu-layering.e2e.ts",
"tests/jobs-panel-layering.e2e.ts",
"tests/plugin-config.e2e.ts",
"tests/input-plugin-extensions.e2e.ts",
"tests/plugin-manager.e2e.ts",
+2 -2
View File
@@ -1206,7 +1206,7 @@ export interface Config {
worktreePrefix?: string
/** Largest diff, file read to show unchanged lines, or list of base branch refs, in bytes. */
maxDiffBytes?: number
/** Most untracked files a local diff or the local changes card includes. */
/** Most untracked files a local diff or the local changes row includes. */
maxUntrackedFiles?: number
/** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */
maxCachedDiffBytes?: number
@@ -4717,7 +4717,7 @@ export interface Config {
- `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections`
- `refs`: [`AgentOptions`](subsystems/core.md)
- `source`: [`packages/subagent/tool-subagent/src/index.ts:46`](../packages/subagent/tool-subagent/src/index.ts)
- `source`: [`packages/subagent/tool-subagent/src/index.ts:47`](../packages/subagent/tool-subagent/src/index.ts)
```ts config-catalog
/** Config: which registered provider this tool delegates to, plus child defaults. */
+2 -2
View File
@@ -1208,7 +1208,7 @@ export interface Config {
worktreePrefix?: string
/** Largest diff, file read to show unchanged lines, or list of base branch refs, in bytes. */
maxDiffBytes?: number
/** Most untracked files a local diff or the local changes card includes. */
/** Most untracked files a local diff or the local changes row includes. */
maxUntrackedFiles?: number
/** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */
maxCachedDiffBytes?: number
@@ -4719,7 +4719,7 @@ export interface Config {
- `inject`: `tools` · `subagents` · `systemPrompt` · `sessionProjections`
- `refs`: [`AgentOptions`](subsystems/core.zh.md)
- `source`: [`packages/subagent/tool-subagent/src/index.ts:46`](../packages/subagent/tool-subagent/src/index.ts)
- `source`: [`packages/subagent/tool-subagent/src/index.ts:47`](../packages/subagent/tool-subagent/src/index.ts)
```ts config-catalog
/** Config: which registered provider this tool delegates to, plus child defaults. */
+2 -2
View File
@@ -1104,8 +1104,8 @@
en: f604eebb973fe2cf
zh: 0c0aba1e17ecf66e
/session-persistence-event-catalog/resolved-persistence-types/jobsettlecause:
en: 748a4269d86e007a
zh: 4ce04c4451bdcfe8
en: 3f193f1c8bbae065
zh: b8c828959d28480d
/session-persistence-event-catalog/resolved-persistence-types/jobsettleddata:
en: fc8caf270a7581f7
zh: b467e1d4191106eb
+1 -1
View File
@@ -3895,7 +3895,7 @@ Sources: [`packages/jobs/jobs/src/types.ts:24`](../packages/jobs/jobs/src/types.
SHA-256: `750a2b129d67704df675c06823c20c80b65cbae89d5aaa914fd5a72e3df395b5`
Sources: [`packages/jobs/jobs/src/types.ts:247`](../packages/jobs/jobs/src/types.ts)
Sources: [`packages/jobs/jobs/src/types.ts:253`](../packages/jobs/jobs/src/types.ts)
One of:
+1 -1
View File
@@ -3897,7 +3897,7 @@ SHA-256: `e3056e0dda3a379e895386e368c3ce42131460ea65e410e1d091cca98a347305`
SHA-256: `750a2b129d67704df675c06823c20c80b65cbae89d5aaa914fd5a72e3df395b5`
来源:[`packages/jobs/jobs/src/types.ts:247`](../packages/jobs/jobs/src/types.ts)
来源:[`packages/jobs/jobs/src/types.ts:253`](../packages/jobs/jobs/src/types.ts)
以下类型之一:
+1 -1
View File
@@ -361,7 +361,7 @@
{"digest":"71bb3254ec8f1e491ce63b762a7b5f18709de23aa4e8abcc8b886f4b6ce051dd","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:27"]},
{"digest":"72ec79127a9c0d0241b1106a74cc2b24c81ce467170f1c3c93f7b71a9496d227","names":[],"sources":[]},
{"digest":"7382c4fc95fe8c5db65ca4d9da572b115d0dbb818b7f32c22ab040318ffbb4bc","names":[],"sources":[]},
{"digest":"750a2b129d67704df675c06823c20c80b65cbae89d5aaa914fd5a72e3df395b5","names":["packages/jobs/jobs/src/types.ts#JobSettleCause"],"sources":["packages/jobs/jobs/src/types.ts:247"]},
{"digest":"750a2b129d67704df675c06823c20c80b65cbae89d5aaa914fd5a72e3df395b5","names":["packages/jobs/jobs/src/types.ts#JobSettleCause"],"sources":["packages/jobs/jobs/src/types.ts:253"]},
{"digest":"7554565be416b0342053ee6a46256c9dab07c487349b4a5f10bab1edc151c619","names":[],"sources":[]},
{"digest":"756b5e23a5cb2c7f486f366a828f7461c88902af21125bd6810881f4ccbff6cc","names":[],"sources":[]},
{"digest":"7624ca28c61ca0eaa4f015140f3cea6e0c16cce2f2960fab5f531203d253903e","names":[],"sources":[]},
+2 -2
View File
@@ -24,8 +24,8 @@
en: 74255d6005e1c9e8
zh: 252d0d552f1e26a1
/forges/panel:
en: 7dcefe2825490257
zh: 38cec4d1ae3b0d6e
en: 0fc2e5a367d0a3ad
zh: a1028e4ecf61b70c
/forges/extension-api:
en: f35345e482e84f4f
zh: 2ecb7d9498decb31
+2 -2
View File
@@ -1121,7 +1121,7 @@ type ForgeChangeRequestStatesFrame =
| { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] }
```
The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`, which returns a patch only for that head commit, or the `ForgeCommitRange` it names through the provider's `compare`; both return files that the Host parsed into `ForgeDiffFile` hunks, each with its review layer and change digest. `localCommits` and `changeRequestCommits` list the commits a range can name, the latter as null when the provider does not read commits. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. When the head moved past the latest status, the provider returns `stale` and `ctx.forge.diff` polls the change request at once, once per head commit; `changeRequestDiff` rejects with `forgePanel/stale-head` and caches nothing, and the changes view keeps loading until a later status arrives, then reads again at that status's head. Review comments therefore always address the commit whose lines the view shows.
The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`, which returns a patch only for that head commit, or the `ForgeCommitRange` it names through the provider's `compare`; both return files that the Host parsed into `ForgeDiffFile` hunks, each with its review layer and change digest. `localCommits` and `changeRequestCommits` list the commits a range can name, the latter as null when the provider does not read commits. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the Session panel's local changes row, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. When the head moved past the latest status, the provider returns `stale` and `ctx.forge.diff` polls the change request at once, once per head commit; `changeRequestDiff` rejects with `forgePanel/stale-head` and caches nothing, and the changes view keeps loading until a later status arrives, then reads again at that status's head. Review comments therefore always address the commit whose lines the view shows.
`changeRequestReview(session, url, headSha, fresh)` reads the threads of a bound change request at the head of the diff the view shows and refuses another head with `forgePanel/stale-head`, `forgePanel/review-unsupported` for a provider without review reads, and `forgePanel/review-failed` otherwise. It keeps one read per change request in memory, keyed by head commit and the status's update time and bounded by `maxCachedReviewBytes`, and reads again once the kept read is `reviewRefreshMs` old or when `fresh` asks for it, as the first read after the reader refreshes the view does: on GitHub a new comment or reply changes a pull request's update time, but resolving a thread does not. The changes view asks again at every status it receives while visible, and overlays the threads on the files the [panel README](../../packages/experimental/client-ui-forge/README.md#use-this-package) describes.
@@ -1309,7 +1309,7 @@ interface ForgeChangedFile {
```
```ts type-equiv
/** Size of the `branch` scope, which the panel's local changes card shows. */
/** Size of the `branch` scope, which the Session panel's local changes row shows. */
interface ForgeLocalChanges {
/** Ref or abbreviated commit the scope compares with. */
readonly base: string
+2 -2
View File
@@ -1123,7 +1123,7 @@ type ForgeChangeRequestStatesFrame =
| { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] }
```
变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更(提供方只返回描述该 head 提交的补丁),或经提供方的 `compare` 读取它指定的 `ForgeCommitRange`;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk,并带有分层与改动摘要。`localCommits` 与 `changeRequestCommits` 列出范围可以指定的提交,提供方不读取提交时后者返回 null。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。head 已越过最新状态时,提供方返回 `stale`,`ctx.forge.diff` 立即重新轮询该变更请求(每个 head 提交一次);`changeRequestDiff` 以 `forgePanel/stale-head` 拒绝且不缓存任何内容,变更视图保持加载,直到更新的状态到达后按该状态的 head 重新读取。因此评审评论始终指向视图所显示行的那个提交。
变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更(提供方只返回描述该 head 提交的补丁),或经提供方的 `compare` 读取它指定的 `ForgeCommitRange`;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk,并带有分层与改动摘要。`localCommits` 与 `changeRequestCommits` 列出范围可以指定的提交,提供方不读取提交时后者返回 null。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供会话面板的本地变更行使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。head 已越过最新状态时,提供方返回 `stale`,`ctx.forge.diff` 立即重新轮询该变更请求(每个 head 提交一次);`changeRequestDiff` 以 `forgePanel/stale-head` 拒绝且不缓存任何内容,变更视图保持加载,直到更新的状态到达后按该状态的 head 重新读取。因此评审评论始终指向视图所显示行的那个提交。
`changeRequestReview(session, url, headSha, fresh)` 在视图所显示 diff 的 head 处读取已绑定变更请求的讨论;head 不同时以 `forgePanel/stale-head` 拒绝,提供方不支持读取讨论时返回 `forgePanel/review-unsupported`,其他失败返回 `forgePanel/review-failed`。每个变更请求在内存里保留一次读取结果,以 head 提交和状态的更新时间为键、受 `maxCachedReviewBytes` 约束,保留时间达到 `reviewRefreshMs` 后,或 `fresh` 要求时(读者刷新视图后的第一次读取就是这样)重新读取:在 GitHub 上,新评论和回复会改变 PR 的更新时间,解决讨论则不会。变更视图可见时,每收到一次状态就重新请求一次,并按[面板 README](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package) 所述把讨论叠加到文件上。
@@ -1311,7 +1311,7 @@ interface ForgeChangedFile {
```
```ts type-equiv
/** Size of the `branch` scope, which the panel's local changes card shows. */
/** Size of the `branch` scope, which the Session panel's local changes row shows. */
interface ForgeLocalChanges {
/** Ref or abbreviated commit the scope compares with. */
readonly base: string
+8
View File
@@ -181,6 +181,12 @@ interface JobOutcome {
* reason, the registry appends that reason.
*/
detail?: string
/**
* Exit code of the process the job ran, for a producer that runs one. A
* nonzero code on a `completed` job means the command reported failure while
* the job itself finished.
*/
exitCode?: number
/**
* Return value for jobs whose result is a value rather than a stream (a
* workflow's rendered result, a subagent's report). The output ring carries
@@ -295,6 +301,8 @@ interface JobView {
readonly progress?: string
/** Terminal reason (`exit code: 3`); a recorded kill reason is merged in. */
readonly detail?: string
/** Exit code of the process the job ran, once settled, for a producer that reports one. */
readonly exitCode?: number
/** Epoch ms when the job was registered. */
readonly startedAt: number
/** Epoch ms when the job settled; absent while live. */
+8
View File
@@ -181,6 +181,12 @@ interface JobOutcome {
* reason, the registry appends that reason.
*/
detail?: string
/**
* Exit code of the process the job ran, for a producer that runs one. A
* nonzero code on a `completed` job means the command reported failure while
* the job itself finished.
*/
exitCode?: number
/**
* Return value for jobs whose result is a value rather than a stream (a
* workflow's rendered result, a subagent's report). The output ring carries
@@ -295,6 +301,8 @@ interface JobView {
readonly progress?: string
/** Terminal reason (`exit code: 3`); a recorded kill reason is merged in. */
readonly detail?: string
/** Exit code of the process the job ran, once settled, for a producer that reports one. */
readonly exitCode?: number
/** Epoch ms when the job was registered. */
readonly startedAt: number
/** Epoch ms when the job settled; absent while live. */
+2 -2
View File
@@ -264,8 +264,8 @@
en: 841abe0dd5913ea7
zh: 841abe0dd5913ea7
/tool-schema-catalog/deepseek-ai-dsh-tool-subagent/list-subagent-models:
en: 0e21650bbe8c71c7
zh: fe4033efb38d51a3
en: 1fa8a23ffccd029f
zh: 5d1b9d618976d580
/tool-schema-catalog/deepseek-ai-dsh-tool-subagent/subagent:
en: 9912eeda5bc40b43
zh: 0cb70f9a0d923bee
+2 -2
View File
@@ -2199,7 +2199,7 @@ The subagent_oar tool selects among configured aliases for external providers. T
### `list_subagent_models`
Inspect the routes available for explicit subagent model selection. No arguments: authorized providers. `provider`: that provider's authorized models. `provider` + `model`: that model and its reasoning efforts. Query when choosing an explicit child route or reasoning effort. Omit optional fields rather than sending empty strings.
Inspect the routes available for explicit subagent model selection. No arguments: authorized providers. `provider`: that provider's authorized models. `provider` + `model`: that model and its reasoning efforts.
```json
{
@@ -2207,7 +2207,7 @@ Inspect the routes available for explicit subagent model selection. No arguments
"properties": {
"provider": {
"type": "string",
"description": "Registered LLM provider id."
"description": "Provider id from the no-argument listing."
},
"model": {
"type": "string",
+2 -2
View File
@@ -2205,7 +2205,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录
### `list_subagent_models`
查询允许为 subagent 显式选择的路由。无参数:提供方;`provider`:允许的模型;`provider` + `model`:该模型及其推理强度。选择子级提供方和模型前先在此查询选项,再将返回的 id 用于委派。
查询允许为 subagent 显式选择的路由。无参数:提供方;`provider`:允许的模型;`provider` + `model`:该模型及其推理强度。
```json
{
@@ -2213,7 +2213,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录
"properties": {
"provider": {
"type": "string",
"description": "Registered LLM provider id."
"description": "Provider id from the no-argument listing."
},
"model": {
"type": "string",
+2 -2
View File
@@ -21,8 +21,8 @@
en: fb6d50f3139ad186
zh: 668cb0c02bd22167
/dsh-unified-corner-radius-standard/nested-geometry-and-hover:
en: 7fe4eb7707e6a9f3
zh: be7530a05c205e27
en: 76037a56b0e1bf64
zh: 890f512cc1db5263
/dsh-unified-corner-radius-standard/settings-card-materials:
en: 126066f9c638433c
zh: a7416d255f838b92
+1 -1
View File
@@ -68,7 +68,7 @@ Distinguish these three arrangements before changing a child radius:
| Fill flush against an enclosing edge | The enclosure owns the visible corner; clip the fill or inherit the matching corner | A split-button card with two independent hover regions |
| Separate card or form group inside another surface | Choose the child's semantic tier; do not subtract all parent padding mechanically | R16 editor within an R20 settings card |
Standard menus use outer R16, 4px padding, and R12 items, including command selection, task menus, and the exposed highlights in subagent and background-job menus. Tree disclosure gutters retain their indentation; controls inside a filled job row keep their own compact geometry. Compact menus use outer R12, 4px padding, and R8 items. Shared `SegmentedControl` uses outer R12, 4px inset, and R8 segments/indicator; `SegmentedTabs` uses outer R16, 4px inset, and R12 segments/indicator. Keep indicator offsets, width calculations, submenu alignment, and pointer bridges consistent when changing padding.
Standard menus use outer R16, 4px padding, and R12 items, including command selection, task menus, and the exposed highlights in the subagent switcher menu. Tree disclosure gutters retain their indentation. Compact menus use outer R12, 4px padding, and R8 items. Shared `SegmentedControl` uses outer R12, 4px inset, and R8 segments/indicator; `SegmentedTabs` uses outer R16, 4px inset, and R12 segments/indicator. Keep indicator offsets, width calculations, submenu alignment, and pointer bridges consistent when changing padding.
The radius subtraction is also the nominal sizing rule for nested superellipses. Equal exponents do not make them exact offset curves, so their diagonal gap may differ from the side inset. Keep the shared superellipse menu and segmented-control treatments; use circular arcs when strict equal radial spacing is required.
+1 -1
View File
@@ -68,7 +68,7 @@ H 表示以 CSS 像素计、包含边框的设计外部高度。R 表示浏览
| 底色紧贴容器边缘 | 由外框决定可见圆角;裁切底色或继承相应圆角 | 两个独立 hover 区域组成的分体按钮卡片 |
| 容器内独立的卡片或表单组 | 按子元素用途选择档位;不机械减去全部父级内边距 | R20 设置卡片内的 R16 编辑器 |
标准菜单使用外层 R16、4px 内边距、R12 菜单项,包含命令选择、任务菜单,以及子会话和后台任务菜单的外露高亮区域。树形展开操作保留缩进;带底色任务行内的控件保留各自的紧凑几何。紧凑菜单使用外层 R12、4px 内边距、R8 菜单项。公共 `SegmentedControl` 使用外层 R12、4px 内缩、R8 分段和指示器;`SegmentedTabs` 使用外层 R16、4px 内缩、R12 分段和指示器。修改内边距时,同步保持指示器偏移、宽度计算、子菜单对齐与指针桥接区域一致。
标准菜单使用外层 R16、4px 内边距、R12 菜单项,包含命令选择、任务菜单,以及子会话切换菜单的外露高亮区域。树形展开操作保留缩进。紧凑菜单使用外层 R12、4px 内边距、R8 菜单项。公共 `SegmentedControl` 使用外层 R12、4px 内缩、R8 分段和指示器;`SegmentedTabs` 使用外层 R16、4px 内缩、R12 分段和指示器。修改内边距时,同步保持指示器偏移、宽度计算、子菜单对齐与指针桥接区域一致。
半径相减也用于嵌套超级椭圆的名义尺寸关系。相同指数不意味着两条曲线严格等距,因此对角线间隙可能不同于侧边内缩。菜单与分段控件保留公共的超级椭圆样式;要求径向严格等距时使用圆弧。
@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/session-panel-entries/guide.md
/:
en: 9036df7633bfa9a8
zh: 6509cb0a0a1d1d01
/session-header-entries-move-into-the-session-panel:
en: 8ac9f4ef04cd1f1b
zh: 63cd71f51f8acd3e
/session-header-entries-move-into-the-session-panel/change:
en: b967d3f7d4292d8a
zh: 46371550a5458694
/session-header-entries-move-into-the-session-panel/migration:
en: e87313ba54c260b4
zh: 3147a7648d44dad2
@@ -0,0 +1,26 @@
---
kind: upgrade-guide
description: "Background jobs, subagents, and forge change requests move from the Session header and right sidebar into the Session panel, which removes the subagent footer slot and retires the forge tab type."
---
# Session header entries move into the Session panel
English | [中文](guide.zh.md)
## Change
The Web and Desktop Session header used to show a background-jobs button, a subagents button whose menu ended with the `conversation.session.header.actions.subagent.footer` slot, and, with the forge bundle, a change requests button that opened the `forge-panel` right-sidebar tab. These entries now live in the [Session panel](../../../../packages/client/ui-session-panel/README.md) that the header toggle opens:
- [`dsh-client-ui-jobs`](../../../../packages/client/ui-jobs/README.md) and [`dsh-client-ui-subagent`](../../../../packages/client/ui-subagent/README.md) register Background jobs and Subagents sections; the subagent footer slot is removed, and the shared task board that filled it is now its own Shared tasks section.
- [`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.md) registers a Change requests section, checkout and local changes rows in the Environment section, and an attention mark on the toggle. It no longer registers the `forge-panel` tab type, its tab title, or a `conversation.session.header.utilities` entry; the changes view keeps its `forge-changes` tab type.
- In the forge changes extension API, `ctx.forgeChanges.kinds` keeps only `changes`, because `panel` named the retired tab type; the `forge.change-request.card.actions` slot keeps its owner props and renders on each card of the Change requests section, before the card's actions menu.
- Type exports follow the components: `JobsSection*` replaces `JobListAction*`/`JobListInjected`, `SubagentsSection*` replaces `SubagentCatalogAction*`, and the forge `ChangeRequestsSection*`, `ChangeRequestsActions*`, `CheckoutRow*`, `LocalChangesRow*`, and `AttentionIndicator*` types replace `ForgeTab*`, `HeaderButton*`, and `LocalChangesCardProps`.
Client plugins and runtime extensions that register into the old footer slot, open the `forge-panel` tab type, read `ctx.forgeChanges.kinds.panel`, or import the removed types are affected. A right sidebar restored with a `forge-panel` tab no longer shows that tab. Session data and configuration keys are unchanged.
## Migration
1. In Client plugins and runtime extensions, replace every `conversation.session.header.actions.subagent.footer` registration with a `conversation.session.panel.section` registration that has its own `id`, `order`, and `label`, and remove child declarations of the old slot.
2. Replace calls such as `ctx.sidebarRight.openTab('forge-panel')` and reads of `ctx.forgeChanges.kinds.panel` by asking the user to open the Session panel; to place content beside the change requests, register a `conversation.session.panel.section` entry, as the [Session panel README](../../../../packages/client/ui-session-panel/README.md) describes.
3. Update type imports to the names listed under Change.
4. Confirm the migration by running `pnpm run typecheck`, then opening a Session in Web, clicking the Session panel toggle in the header, and finding the content in its own section.
@@ -0,0 +1,26 @@
---
kind: upgrade-guide
description: "后台任务、子智能体与 forge 变更请求从会话标题栏和右侧边栏移入会话面板,子智能体页脚 slot 随之移除,forge 标签页类型退役。"
---
# 会话标题栏入口移入会话面板
[English](guide.md) | 中文
## 变更
Web 与 Desktop 的会话标题栏此前显示后台任务按钮、子智能体按钮(其菜单末尾是 `conversation.session.header.actions.subagent.footer` slot),以及启用 forge 套件时打开 `forge-panel` 右侧边栏标签页的变更请求按钮。这些入口现在位于由标题栏开关打开的[会话面板](../../../../packages/client/ui-session-panel/README.zh.md)中:
- [`dsh-client-ui-jobs`](../../../../packages/client/ui-jobs/README.zh.md) 与 [`dsh-client-ui-subagent`](../../../../packages/client/ui-subagent/README.zh.md) 注册“后台任务”与“子智能体”分栏;子智能体页脚 slot 已移除,原来填充它的共享任务板现在是独立的“共享任务”分栏。
- [`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.zh.md) 注册“变更请求”分栏、“环境”分栏中的检出行与本地变更行,以及开关上的提醒标记。它不再注册 `forge-panel` 标签页类型及其标题,也不再注册 `conversation.session.header.utilities` 条目;变更视图仍使用 `forge-changes` 标签页类型。
- forge 变更视图扩展 API 中,`ctx.forgeChanges.kinds` 只保留 `changes`,因为 `panel` 指的是已退役的标签页类型;`forge.change-request.card.actions` slot 的 owner props 不变,改为渲染在“变更请求”分栏每张卡片的操作菜单之前。
- 类型导出随组件改名:`JobsSection*` 取代 `JobListAction*`/`JobListInjected`,`SubagentsSection*` 取代 `SubagentCatalogAction*`,forge 的 `ChangeRequestsSection*`、`ChangeRequestsActions*`、`CheckoutRow*`、`LocalChangesRow*` 与 `AttentionIndicator*` 类型取代 `ForgeTab*`、`HeaderButton*` 与 `LocalChangesCardProps`。
注册到旧页脚 slot、打开 `forge-panel` 标签页类型、读取 `ctx.forgeChanges.kinds.panel` 或导入已移除类型的 Client 插件与运行时扩展会受影响。恢复右侧边栏时,`forge-panel` 标签页不再显示。Session 数据与配置键不变。
## 迁移
1. 在 Client 插件与运行时扩展中,把对 `conversation.session.header.actions.subagent.footer` 的注册改为带自己的 `id`、`order` 和 `label` 的 `conversation.session.panel.section` 注册,并移除旧 slot 的子 slot 声明。
2. 把 `ctx.sidebarRight.openTab('forge-panel')` 之类的调用与对 `ctx.forgeChanges.kinds.panel` 的读取改为提示用户打开会话面板;如需在变更请求旁放置内容,按[会话面板 README](../../../../packages/client/ui-session-panel/README.zh.md) 的说明注册 `conversation.session.panel.section` 条目。
3. 按“变更”中列出的名称更新类型导入。
4. 运行 `pnpm run typecheck`,然后在 Web 中打开一个 Session,点击标题栏中的会话面板开关,在其独立分栏中找到这些内容,即确认迁移完成。
+12 -12
View File
@@ -3,29 +3,29 @@
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/ui-agent-team/README.md
/:
en: cecfe90c9079279f
zh: 58062db454093088
en: 7dc6eba0f4471f92
zh: 9fdf11a94995a75d
/deepseek-ai-dsh-client-ui-agent-team:
en: 39c47e6e926425bf
zh: 0fd155c454355e3a
/deepseek-ai-dsh-client-ui-agent-team/summary:
en: 88103cec4c91d755
zh: 6536e4307a5ce122
en: f856eb1b0b6645d1
zh: 91fa3b344ec21e66
/deepseek-ai-dsh-client-ui-agent-team/table-of-contents:
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
/deepseek-ai-dsh-client-ui-agent-team/use-this-package:
en: ffbcd39a17cd2fb1
zh: db21ca6ca1cdf853
en: a6f265f152ef528f
zh: ad414805a2bda4a5
/deepseek-ai-dsh-client-ui-agent-team/use-this-package/inspect-the-task-board:
en: 2f606827b3ab14bc
zh: 7f713d10268e7498
en: 49312c9357e23060
zh: ce1a9b52667977e8
/deepseek-ai-dsh-client-ui-agent-team/understand-the-implementation:
en: 24377b9e51d557de
zh: 9205961784386745
en: 34ad591d4c206d69
zh: 0f6796c19f4ebfb8
/deepseek-ai-dsh-client-ui-agent-team/further-exploration:
en: 4d9214370681b02e
zh: 4acb21b9ecf25e85
en: 5bc48efe19557367
zh: c00e5e1a75d0afa8
/deepseek-ai-dsh-client-ui-agent-team/model-experience:
en: 47ebeba07d72759d
zh: 8fe8133f6dd845a9
+8 -8
View File
@@ -1,5 +1,5 @@
---
description: "Inspect the shared task board from the Web conversation header."
description: "Inspect the shared task board in the Web Session panel's Shared tasks section."
kind: "package-reference"
---
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
This package displays shared tasks below the Subagent tree in one header panel. Host projection frames keep task state current without a refresh control. Ordinary subagent navigation owns the member list and teammate conversations. The Web bundle loads this package; it adds no model-facing input.
This package adds the Shared tasks section to the Session panel, between Subagents and Background jobs. Host projection frames keep task state current without a refresh control. Ordinary subagent navigation owns the member list and teammate conversations. The Web bundle loads this package; it adds no model-facing input.
## Table of Contents
@@ -25,7 +25,7 @@ This package displays shared tasks below the Subagent tree in one header panel.
<a id="use-this-package"></a>
## Use this package
In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings pane, then turn on **Enable agent teamwork**. The root row shows the saved On/Off state without changing it. The settings pane shows the switch above the shared-task coordination, complex-task results, and token-cost explanation as ordinary text that describes the switch, without an information tooltip. Opening the pane focuses the enabled switch. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving.
In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings pane, then turn on **Enable agent teamwork**. The root row shows the saved On/Off state without changing it. The settings pane shows the switch above the shared-task coordination, complex-task results, and token-cost explanation as ordinary text that describes the switch, without an information tooltip. Opening the pane focuses the enabled switch. New Sessions default to off. While enabled, open the root conversation’s Session panel to see members in the Subagents section and tasks in the Shared tasks section below it. Child conversations keep subagent navigation without a Team switch, including before their subagent address is discovered. The board reads the current Session’s `agentTeam` projection, so it appears only in a Session whose own projection is enabled. The Shared tasks section lists the tasks in progress first, then the pending ones, each in source order, then the completed ones with the latest in source order first, since a task carries no completion time. It shows five tasks and then the Session panel's fold control, “Show {count} more”, which shows the rest and then reads “Show less”; the list folds only when that holds back two tasks or more, and the choice holds for the Session, also after the panel is hidden and shown again. The section is hidden while the Session has no shared tasks and no task-record error, independently of the Subagents section. Turning it off retains tasks and subagents. The entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving.
Turning off the menu switch requires confirmation after the Session records a model request; a model choice alone does not require it. The switch waits while request history is unavailable. The dialog explains the tool, coordination, and possible cache effects without deleting task records. Cancel, Escape, or closing the dialog leaves Team mode unchanged. Dismissing the dialog returns focus to the model selector. Confirmation targets the originating Session, waits for the save, and keeps failures visible for retry; it does not depend on the model menu remaining open. Team mode has no slash command; menu changes create no `command/run` or `command/done` records.
@@ -37,7 +37,7 @@ The [Web bundle](../../bundle/web-app/README.md) loads this package by default.
Ready pending tasks use idle, blocked pending tasks use warning, in-progress tasks use ongoing, and completed tasks use done.
The noncollapsible Shared tasks header uses a Checklist icon and completed, in-progress, and pending counts, with zero counts omitted and wording and separators matching the input task list. Compact read-only rows show the subject, status, and a chevron, with 13px primary titles and hover geometry aligned to subagent rows; expanded details use 12px text. Task rows use 7px vertical padding, 6px horizontal padding, and 7px gaps to align their clickable content with subagent rows. All task details start closed; opening one closes the previous task. Details show only the full description when present, followed by a single-line owner label and owner name in the same color with a 4px gap. Long owner names are ellipsized and reveal their full text in a tooltip only when clipped. Task-text and owner tooltips appear after 500ms of hover. Owners display the task's saved `ownerName`, such as `lead` or `reviewer/checker`, independently of loaded subagent catalogs. A task without `ownerName` displays its `ownerId`; a task without either field displays the localized unowned label. The shared menu is 360px wide with 6px outer padding, constrained to fit the viewport. Shared tasks have a 4px top margin rather than a divider. Both section headers keep a 7px icon/title gap and an additional 4px before their counts. Only the menu scrolls; task lists and details have no nested scrolling. Agents mutate tasks through tools; the panel provides no mutation controls. A projection failure appears separately above any retained tasks and remains visible when no tasks exist.
The panel draws the section title, and the title control (`conversation.session.panel.section.actions`, key `shared-tasks`) shows completed, in-progress, and pending counts, with zero counts omitted and wording and separators matching the input task list. Compact read-only rows show the subject, status, and a chevron on one 28px line, with 13px primary titles; expanded details use 12px text and start at the title's edge. Resting the pointer on a collapsed row for 500ms opens a hover card with the full subject, the owner, the description, and the status. Task rows follow the panel's columns, like subagent rows: the status glyph's center 14px from the row start, titles at 30px, and the chevron's center 14px from the row end. All task details start closed; opening one closes the previous task. Details show only the full description when present, followed by a single-line owner label and owner name in the same color with a 4px gap. Long owner names are ellipsized and reveal their full text in a tooltip only when clipped. Owner tooltips appear after 500ms of hover. Owners display the task's saved `ownerName`, such as `lead` or `reviewer/checker`, independently of loaded subagent catalogs. A task without `ownerName` displays its `ownerId`; a task without either field displays the localized unowned label. The Session panel scrolls the board; task lists and details have no nested scrolling. Agents mutate tasks through tools; the panel provides no mutation controls. A projection failure appears separately above any retained tasks and remains visible when no tasks exist.
-----
@@ -47,15 +47,15 @@ The noncollapsible Shared tasks header uses a Checklist icon and completed, in-p
<details>
<summary>Implementation internals — click to expand</summary>
The Client export registers its locale dictionaries and subagent-catalog and model-menu slots through Cordis effects; it mounts no Remote namespace. The [model menu](../ui-model-selection/README.md#use-this-package) owns pane navigation and focus return; Team contributes the root summary through `conversation.input.model.options` and settings through `conversation.input.model.pane` with key `agent-team`. Disposing the plugin fiber removes its registrations.
The Client export registers its locale dictionaries, its Session panel section with the title control, and its model-menu slots through Cordis effects; it mounts no Remote namespace. The [model menu](../ui-model-selection/README.md#use-this-package) owns pane navigation and focus return; Team contributes the root summary through `conversation.input.model.options` and settings through `conversation.input.model.pane` with key `agent-team`. Disposing the plugin fiber removes its registrations.
The Subagent catalog owns the shared panel, scrolling, hover, keyboard, and dismissal interactions. This package contributes the task section only below the root conversation’s tree. The board reads the current Session’s mode and tasks through `useProjection('agentTeam')`. An available, enabled projection supplies the task section only when it contains nondeleted tasks; a projection failure can render independently without a task section. Task IDs, dependencies, readiness, write scopes, and write scope warnings remain in task data but are not displayed as detail fields; blocked pending tasks still use the warning glyph.
The Session panel owns showing, scrolling, and dismissing the section, which registers as `shared-tasks` at `order: 250`. The board reads the current Session’s mode and tasks through `useProjection('agentTeam')`. An available, enabled projection supplies the task section only when it contains nondeleted tasks; a projection failure can render independently without a task section. Task IDs, dependencies, readiness, write scopes, and write scope warnings remain in task data but are not displayed as detail fields; blocked pending tasks still use the warning glyph.
The [Chat visibility policy](../ui-chat/src/client/contract/chat-visibility.ts) hides only historical commands named `team` whose trimmed recorded arguments are exactly `on` or `off` and whose outcome is pending or successful. The remaining receipts use a localized running summary or preserve raw successful output, with a localized completed fallback when that text is empty. Rendering neither reads the current Team projection nor parses English outcome text. Filtering and localization affect only Chat presentation: command records, logs, trajectory, and raw errors remain unchanged.
| File | Role |
|---|---|
| [`src/client/mount.ts`](src/client/mount.ts) | Locale, catalog-section, and model-menu registrations |
| [`src/client/mount.ts`](src/client/mount.ts) | Locale, Session panel section, and model-menu registrations |
| [`src/client/TeamBoard.tsx`](src/client/TeamBoard.tsx) | Projection-derived task section |
| [`src/client/locales.ts`](src/client/locales.ts) | Panel and command copy in eight languages |
| [`src/index.ts`](src/index.ts) | Inert Host entry |
@@ -69,7 +69,7 @@ The [Chat visibility policy](../ui-chat/src/client/contract/chat-visibility.ts)
- [Web bundle](../../bundle/web-app/README.md) — mounts the Client plugin by default.
- [Agent Teams service](../../team/agent-team/README.md) — authoritative task and projection behavior.
- [Conversation UI](../ui-conversation/README.md) — the stable header slot and addressed-subagent navigation surface.
- [Session panel](../ui-session-panel/README.md) — hosts the Shared tasks section and draws its title.
-----
+8 -8
View File
@@ -1,5 +1,5 @@
---
description: "从 Web 对话标题栏查看共享任务板。"
description: "在 Web 会话面板的「共享任务」分栏中查看共享任务板。"
kind: "package-reference"
---
@@ -9,7 +9,7 @@ kind: "package-reference"
## 概述
此包在同一个页头面板中,将共享任务显示在 Subagent 树下方。Host 投影帧持续更新任务状态,无需刷新控件。普通 subagent(子智能体)导航负责成员列表和队友对话。Web bundle 默认加载此包;它不添加模型可见输入。
此包为会话面板添加「共享任务」分栏,位于「子智能体」与「后台任务」之间。Host 投影帧持续更新任务状态,无需刷新控件。普通 subagent(子智能体)导航负责成员列表和队友对话。Web bundle 默认加载此包;它不添加模型可见输入。
## 目录
@@ -25,7 +25,7 @@ kind: "package-reference"
<a id="use-this-package"></a>
## 使用本包
在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置面板后打开**开启智能体团队协作**。一级行显示已保存的开启/关闭状态,不改变选择。设置面板将开关放在共享任务协调、复杂任务效果与 token 开销的说明上方;说明使用普通正文,并作为开关的描述,不使用信息 tooltip。打开设置面板时聚焦可用的开关。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。
在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置面板后打开**开启智能体团队协作**。一级行显示已保存的开启/关闭状态,不改变选择。设置面板将开关放在共享任务协调、复杂任务效果与 token 开销的说明上方;说明使用普通正文,并作为开关的描述,不使用信息 tooltip。打开设置面板时聚焦可用的开关。新 Session 默认关闭。开启后,打开根会话的会话面板,即可在「子智能体」分栏查看成员,并在其下方的「共享任务」分栏查看任务。子会话保留子智能体导航,不显示 Team 开关,包括尚未发现子代理地址时。任务板读取当前 Session 的 `agentTeam` 投影,因此只在自身投影已开启的 Session 中显示。「共享任务」分栏先列进行中的任务,再列待处理的任务,各按任务原顺序;最后是已完成的任务,原顺序靠后的在前,因为任务没有完成时间。它只显示五个任务,然后是会话面板的收起控件「显示其余 {count} 个」,点击后显示其余的任务并变为「收起」;只有能收起两个及以上任务时列表才收起,这个选择在 Session 内保持,隐藏后再次显示面板也不变。会话没有共享任务且没有任务记录错误时,隐藏「共享任务」分栏,与「子智能体」分栏互不影响。关闭后保留任务和子代理。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。
会话记录过模型请求后,从菜单开关关闭团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。
@@ -37,7 +37,7 @@ Chat 隐藏历史 `/team on` 和 `/team off` 记录中尚未完成或执行成
可开始的 pending 任务使用 idle 灰点,被依赖阻塞的 pending 任务使用 warning 橙点,in-progress 任务使用 ongoing loading,completed 任务使用 done 绿点。
不可折叠的“共享任务”标题使用 Checklist 图标,并显示已完成、进行中和待处理数量;省略零值,文案和分隔符与输入区任务列表一致。紧凑只读行显示主题、状态和展开箭头,13px 主标题与悬停区域对齐子智能体行;展开详情使用 12px 文字。任务行使用 7px 垂直内边距、6px 水平内边距和 7px 间距,使可点击内容与 subagent 行对齐。所有任务详情初始关闭,打开一项会关闭上一项。详情仅显示完整描述(如有),下方以单行显示负责人标签和负责人名称,两者使用相同颜色,间距为 4px。过长的负责人名称以省略号截断,仅在被截断时通过工具提示显示完整内容。任务文字和负责人的工具提示在悬停 500ms 后显示。负责人显示任务保存的 `ownerName`,例如 `lead` 或 `reviewer/checker`,不依赖已加载的 subagent 目录。缺少 `ownerName` 时显示 `ownerId`;两个字段都没有时显示本地化的无负责人标签。共享菜单宽度为 360px,外层内边距为 6px,并受视口可用宽度约束。共享任务上方保留 4px 外边距,不显示分隔线。两个区域标题均保留 7px 图标与文字间距,并在统计数量前额外留出 4px。仅菜单本身滚动,任务列表与详情不单独滚动。Agent 通过工具修改任务;面板不提供修改控件。投影失败以独立警告显示在保留的任务上方,即使没有任务也保持可见。
分栏标题由面板绘制,标题控件(`conversation.session.panel.section.actions`,键为 `shared-tasks`)显示已完成、进行中和待处理数量;省略零值,文案和分隔符与输入区任务列表一致。紧凑只读行在 28px 的一行中显示主题、状态和展开箭头,主标题 13px;展开详情使用 12px 文字,并从标题边缘开始。指针在收起的行上停留 500ms 后,悬停卡片显示完整主题、负责人、描述和状态。任务行与子智能体行一样遵循面板的列:状态图标中心距行起始 14px,标题从 30px 开始,箭头中心距行末端 14px。所有任务详情初始关闭,打开一项会关闭上一项。详情仅显示完整描述(如有),下方以单行显示负责人标签和负责人名称,两者使用相同颜色,间距为 4px。过长的负责人名称以省略号截断,仅在被截断时通过工具提示显示完整内容。负责人的工具提示在悬停 500ms 后显示。负责人显示任务保存的 `ownerName`,例如 `lead` 或 `reviewer/checker`,不依赖已加载的 subagent 目录。缺少 `ownerName` 时显示 `ownerId`;两个字段都没有时显示本地化的无负责人标签。会话面板负责任务板滚动,任务列表与详情不单独滚动。Agent 通过工具修改任务;面板不提供修改控件。投影失败以独立警告显示在保留的任务上方,即使没有任务也保持可见。
-----
@@ -47,15 +47,15 @@ Chat 隐藏历史 `/team on` 和 `/team off` 记录中尚未完成或执行成
<details>
<summary>实现细节——点击展开</summary>
Client export 通过 Cordis effect 注册语言字典、子代理目录与模型菜单 slot;它不挂载 Remote namespace。[模型菜单](../ui-model-selection/README.zh.md#use-this-package)负责面板导航和焦点返回;Team 通过 `conversation.input.model.options` 提供一级摘要,并通过 `conversation.input.model.pane` 的 `agent-team` 键提供设置内容。销毁插件 fiber 会移除这些注册。
Client export 通过 Cordis effect 注册语言字典、带标题控件的会话面板分栏与模型菜单 slot;它不挂载 Remote namespace。[模型菜单](../ui-model-selection/README.zh.md#use-this-package)负责面板导航和焦点返回;Team 通过 `conversation.input.model.options` 提供一级摘要,并通过 `conversation.input.model.pane` 的 `agent-team` 键提供设置内容。销毁插件 fiber 会移除这些注册。
Subagent 目录负责共享面板的滚动、悬停、键盘和关闭交互。本包仅在根会话的树下方提供任务区。任务板通过 `useProjection('agentTeam')` 读取当前 Session 的模式与任务;仅当投影可用、已开启且含有未删除的任务时才显示任务区;投影错误可独立显示,不需要任务区。任务 ID、依赖、准备状态、写入范围及其提示仍保留在任务数据中,但不作为详情字段显示;被依赖阻塞的 pending 任务仍使用 warning 图标。
会话面板负责分栏的显示、滚动和关闭;分栏注册为 `shared-tasks`,`order: 250`。任务板通过 `useProjection('agentTeam')` 读取当前 Session 的模式与任务;仅当投影可用、已开启且含有未删除的任务时才显示任务区;投影错误可独立显示,不需要任务区。任务 ID、依赖、准备状态、写入范围及其提示仍保留在任务数据中,但不作为详情字段显示;被依赖阻塞的 pending 任务仍使用 warning 图标。
[Chat 可见性策略](../ui-chat/src/client/contract/chat-visibility.ts) 仅隐藏名称为 `team`、已记录参数去除首尾空白后恰为 `on` 或 `off`,且尚未完成或执行成功的历史命令。其余回执在执行中显示本地化摘要,成功时保留原始结果文本,文本为空则使用本地化的完成提示。渲染既不读取当前 Team 投影,也不解析英文结果文案。过滤与本地化仅影响 Chat 展示:命令记录、日志、轨迹和原始错误均保持不变。
| 文件 | 职责 |
|---|---|
| [`src/client/mount.ts`](src/client/mount.ts) | 语言字典、目录任务区和模型菜单注册 |
| [`src/client/mount.ts`](src/client/mount.ts) | 语言字典、会话面板分栏和模型菜单注册 |
| [`src/client/TeamBoard.tsx`](src/client/TeamBoard.tsx) | 从投影派生的任务区 |
| [`src/client/locales.ts`](src/client/locales.ts) | 八种语言的面板与命令文案 |
| [`src/index.ts`](src/index.ts) | 不执行行为的 Host entry |
@@ -69,7 +69,7 @@ Subagent 目录负责共享面板的滚动、悬停、键盘和关闭交互。
- [Web bundle](../../bundle/web-app/README.zh.md)——默认挂载本 Client plugin。
- [Agent Teams 服务](../../team/agent-team/README.zh.md) — 任务和投影行为的权威来源。
- [会话 UI](../ui-conversation/README.zh.md)——稳定 header slot 与 addressed-subagent 导航表层。
- [会话面板](../ui-session-panel/README.zh.md)——承载「共享任务」分栏并绘制其标题。
-----
+3 -2
View File
@@ -34,7 +34,8 @@
"@deepseek-ai/dsh-client-ui-conversation",
"@deepseek-ai/dsh-client-ui-chat",
"@deepseek-ai/dsh-client-ui-layout",
"@deepseek-ai/dsh-client-ui-primitives"
"@deepseek-ai/dsh-client-ui-primitives",
"@deepseek-ai/dsh-client-ui-session-panel"
],
"platform": "web"
}
@@ -69,7 +70,7 @@
"@deepseek-ai/dsh-client-ui-model-selection": "workspace:*",
"@deepseek-ai/dsh-client-ui-layout": "workspace:*",
"@deepseek-ai/dsh-api-remotes": "workspace:*",
"@deepseek-ai/dsh-client-ui-subagent": "workspace:*",
"@deepseek-ai/dsh-client-ui-session-panel": "workspace:*",
"@deepseek-ai/dsh-agent": "workspace:*"
},
"files": [
@@ -1,46 +1,18 @@
/* Rows share the Session panel's columns: the glyph's center 14px from the row
start, text at 30px, and the chevron's center 14px from the row end. */
.board {
min-width: 0;
padding: 8px 7px;
}
.board[data-with-members='true'] {
margin-top: 4px;
}
.header {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 4px 7px;
margin: 0 0 4px;
padding: 0;
}
.lead,
.glyph,
.chevron {
display: grid;
flex: none;
place-items: center;
color: var(--dsw-alias-label-tertiary);
}
.title {
flex: none;
color: var(--dsw-alias-label-primary);
font-size: 13px;
font-weight: 500;
line-height: 24px;
}
/* Beside the section title, one line that clips before the title does. */
.progress {
margin-inline-start: 4px;
min-width: 0;
overflow: hidden;
color: var(--dsw-alias-label-tertiary);
font-size: 13px;
font-weight: 400;
font: var(--dsw-font-xxs-12);
font-variant-numeric: tabular-nums;
line-height: 20px;
overflow-wrap: anywhere;
text-overflow: ellipsis;
white-space: nowrap;
}
.tasks {
@@ -59,18 +31,16 @@
box-sizing: border-box;
display: flex;
align-items: center;
gap: 7px;
width: calc(100% + 12px);
gap: 8px;
width: 100%;
min-width: 0;
margin: 0 -6px;
padding: 7px 6px;
min-height: 28px;
padding: 4px 6px;
border: 0;
border-radius: var(--dsw-radius-md);
border-radius: var(--dsw-radius-sm);
background: transparent;
color: var(--dsw-alias-label-primary);
font: inherit;
font-size: 13px;
line-height: 17px;
font: var(--dsw-font-xs-13);
text-align: left;
cursor: pointer;
}
@@ -86,9 +56,14 @@
}
}
.glyph {
width: 14px;
height: 17px;
.glyph,
.chevron {
display: grid;
flex: none;
place-items: center;
width: 16px;
height: 20px;
color: var(--dsw-alias-label-tertiary);
}
.subject {
@@ -113,13 +88,8 @@
transform: rotate(180deg);
}
.chevron {
width: 28px;
height: 17px;
}
.details {
padding: 0 0 8px 21px;
padding: 0 6px 8px 30px;
color: var(--dsw-alias-label-secondary);
font-size: 12px;
line-height: 18px;
@@ -156,8 +126,8 @@
.error {
display: flex;
align-items: flex-start;
gap: 7px;
padding: 8px 0;
gap: 8px;
padding: 5px 6px;
color: var(--dsw-alias-state-error-primary);
font-size: 12px;
line-height: 18px;
@@ -1,23 +1,37 @@
import { useState } from 'react'
/** Shared tasks section of the Session panel: the task rows and the progress beside the section title. */
import { useMemo, useState } from 'react'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type { TeamTaskView, TeamTaskId } from '@deepseek-ai/dsh-agent-team/client'
import type { TeamProjection, TeamTaskView, TeamTaskId } from '@deepseek-ai/dsh-agent-team/client'
import type {} from '@deepseek-ai/dsh-api-session-controller/client'
import {
IconChecklistOutlineRegular, IconChevronDownOutlineRegular,
HoverCard, HoverCardGroup, IconChevronDownOutlineRegular,
StateDot, Tooltip, type StateDotState,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type {} from '@deepseek-ai/dsh-client-ui-subagent/client'
import type { PropsLocale, PropsRenderFactories, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client'
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
import { NS, type TeamKey } from './locales.ts'
import type { createTeamBoardStore } from './team-board-store.ts'
import css from './TeamBoard.module.css'
/** Full props of the task board below the shared subagent catalog. */
/** Full props of the shared tasks section body. */
export type TeamBoardProps =
PropsRuntime<'conversation.session.header.actions.subagent.footer'> & PropsLocale<typeof NS>
PropsRuntime<'conversation.session.panel.section'>
& PropsRenderFactories
& PropsStore<ReturnType<typeof createTeamBoardStore>>
& PropsLocale<typeof NS>
/** Tasks the list shows before its fold control holds the rest back. */
const FOLD_LIMIT = 5
type VisibleTask = TeamTaskView & { status: Exclude<TeamTaskView['status'], 'deleted'> }
const NO_TASKS: readonly VisibleTask[] = []
/** Full props of the progress beside the section title. */
export type TeamProgressProps =
PropsRuntime<'conversation.session.panel.section.actions'> & PropsLocale<typeof NS>
const statusKeys = {
pending: 'status.pending', in_progress: 'status.in_progress', completed: 'status.completed',
} satisfies Record<VisibleTask['status'], TeamKey>
@@ -26,6 +40,26 @@ const dotStates = {
pending: 'idle', in_progress: 'ongoing', completed: 'done',
} satisfies Record<VisibleTask['status'], StateDotState>
function visibleTasks(team: TeamProjection): VisibleTask[] {
return team.tasks.filter((task): task is VisibleTask => task.status !== 'deleted')
}
/**
* Order the tasks for the list: the ones in progress, then the pending ones,
* each in source order, then the completed ones with the latest in source
* order first. A task carries no completion time, so source order stands in
* for it.
* @param tasks - the visible tasks in source order.
* @returns the tasks in display order.
*/
function listOrder(tasks: readonly VisibleTask[]): VisibleTask[] {
return [
...tasks.filter(task => task.status === 'in_progress'),
...tasks.filter(task => task.status === 'pending'),
...tasks.filter(task => task.status === 'completed').reverse(),
]
}
function progressLabel(tasks: readonly VisibleTask[], t: TeamBoardProps['t']): string {
const completed = tasks.filter(task => task.status === 'completed').length
const active = tasks.filter(task => task.status === 'in_progress').length
@@ -37,7 +71,7 @@ function progressLabel(tasks: readonly VisibleTask[], t: TeamBoardProps['t']): s
].join('\u2002·\u2002')
}
function TaskRow({ task, rootId, expanded, onToggle, t }: Pick<TeamBoardProps, 't'> & {
function TaskRow({ task, rootId, expanded, onToggle, renderFactorySlot, t }: Pick<TeamBoardProps, 'renderFactorySlot' | 't'> & {
task: VisibleTask
rootId: SessionId
expanded: boolean
@@ -46,23 +80,35 @@ function TaskRow({ task, rootId, expanded, onToggle, t }: Pick<TeamBoardProps, '
const owner = task.ownerName ?? task.ownerId ?? t('unowned')
const blocked = task.status === 'pending' && !task.ready
const detailsId = `team-task-${rootId}-${task.id}`
const state = blocked ? 'warning' : dotStates[task.status]
const status = blocked ? t('blocked') : t(statusKeys[task.status])
// An expanded row already shows its details, so its hover card stays closed.
return (
<li className={css.task} data-team-task={task.id} data-status={task.status} data-expanded={expanded}>
<Tooltip label={task.subject} onlyWhenClipped disabled={expanded} delayMs={500} portal side="top">
<button
type="button"
className={css.taskRow}
aria-expanded={expanded}
aria-controls={detailsId}
onClick={onToggle}
>
<span className={css.glyph} role="img" aria-label={blocked ? t('blocked') : t(statusKeys[task.status])}>
<StateDot state={blocked ? 'warning' : dotStates[task.status]} />
</span>
<span className={css.subject}>{task.subject}</span>
<span className={css.chevron} aria-hidden><IconChevronDownOutlineRegular size={14} /></span>
</button>
</Tooltip>
<HoverCard
grouped
disabled={expanded}
anchor={(
<button
type="button"
className={css.taskRow}
aria-expanded={expanded}
aria-controls={detailsId}
onClick={onToggle}
>
<span className={css.glyph} role="img" aria-label={status}>
<StateDot state={state} />
</span>
<span className={css.subject}>{task.subject}</span>
<span className={css.chevron} aria-hidden><IconChevronDownOutlineRegular size={14} /></span>
</button>
)}
content={renderFactorySlot('conversation.session.panel.details', {
title: task.subject,
lines: [t('hover.owner', { name: owner }), ...task.description ? [task.description] : []],
status: { state, label: status },
})}
/>
{expanded && (
<div className={css.details} id={detailsId} data-team-task-details>
{task.description && <p className={css.description}>{task.description}</p>}
@@ -78,35 +124,66 @@ function TaskRow({ task, rootId, expanded, onToggle, t }: Pick<TeamBoardProps, '
)
}
/** Render read-only tasks in source order; the enclosing subagent menu owns scrolling. */
export function TeamBoard({ sessionId, useProjection, useSessions, t }: TeamBoardProps) {
/**
* Render read-only tasks: the ones in progress first, then the pending ones,
* then the completed ones. The list shows five tasks and then a fold control
* that shows the rest, once that holds back two tasks or more; the choice is
* kept per Session. The Session panel owns the title and scrolling, and hides
* the section while this renders nothing.
* @param props - Session values, the `agentTeam` projection, the fold store, and copy.
* @returns the task list with any board failure, or null with neither.
*/
export function TeamBoard({ sessionId, useProjection, useStore, actions, renderFactorySlot, t }: TeamBoardProps) {
const team = useProjection('agentTeam')
const hasMembers = useSessions(state => (state.projectionsBySession[sessionId]?.values.subagentCatalog?.length ?? 0) > 0)
const unfolded = useStore(state => state.unfolded)
const [expandedTaskId, setExpandedTaskId] = useState<TeamTaskId | null>(null)
const ordered = useMemo(() => team?.enabled === true ? listOrder(visibleTasks(team)) : NO_TASKS, [team])
if (!team?.enabled) return null
const tasks = team.tasks.filter((task): task is VisibleTask => task.status !== 'deleted')
const failure = team.failure === undefined ? null : (
<div className={css.error} role="alert"><StateDot state="error" />{t('failure', { message: team.failure })}</div>
)
if (tasks.length === 0) return failure === null ? null : <div className={css.board}>{failure}</div>
if (ordered.length === 0 && team.failure === undefined) return null
// Folding holds back two tasks or more, since the fold control takes a row itself.
const foldable = ordered.length > FOLD_LIMIT + 1
const tasks = foldable && !unfolded ? ordered.slice(0, FOLD_LIMIT) : ordered
const label = unfolded ? t('list.less') : t('list.more', { count: ordered.length - FOLD_LIMIT })
return (
<section className={css.board} data-with-members={hasMembers} aria-label={t('trigger')} data-team-panel>
<h3 className={css.header}>
<span className={css.lead} aria-hidden><IconChecklistOutlineRegular size={14} /></span>
<span className={css.title}>{t('tasks')}</span>
<span className={css.progress}>{progressLabel(tasks, t)}</span>
</h3>
{failure}
<ul className={css.tasks}>
{tasks.map(task => (
<TaskRow
key={task.id} task={task} rootId={sessionId}
expanded={expandedTaskId === task.id}
onToggle={() => { setExpandedTaskId(current => current === task.id ? null : task.id) }}
t={t}
/>
))}
</ul>
</section>
<div className={css.board} data-team-panel="">
{team.failure !== undefined && (
<div className={css.error} role="alert"><StateDot state="error" />{t('failure', { message: team.failure })}</div>
)}
{tasks.length > 0 && (
// Moving between rows swaps their hover cards without another dwell.
<HoverCardGroup>
<ul className={css.tasks}>
{tasks.map(task => (
<TaskRow
key={task.id} task={task} rootId={sessionId}
expanded={expandedTaskId === task.id}
onToggle={() => { setExpandedTaskId(current => current === task.id ? null : task.id) }}
renderFactorySlot={renderFactorySlot}
t={t}
/>
))}
</ul>
</HoverCardGroup>
)}
{foldable && renderFactorySlot('conversation.session.panel.fold', {
expanded: unfolded,
label,
name: t('list.foldName', { label }),
onToggle: () => { actions.unfoldedSet(!unfolded) },
})}
</div>
)
}
/**
* Render the tasks' progress beside the section title, one line that clips.
* @param props - the `agentTeam` projection and copy.
* @returns the progress phrase, or null without visible tasks.
*/
export function TeamProgress({ useProjection, t }: TeamProgressProps) {
const team = useProjection('agentTeam')
if (!team?.enabled) return null
const progress = progressLabel(visibleTasks(team), t)
if (progress === '') return null
return <span className={css.progress}>{progress}</span>
}
@@ -4,7 +4,7 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis'
import { registerAgentTeamUi } from './mount.ts'
export { inject } from './mount.ts'
export type { TeamBoardProps } from './TeamBoard.tsx'
export type { TeamBoardProps, TeamProgressProps } from './TeamBoard.tsx'
export type { TeamKey } from './locales.ts'
/**
@@ -8,12 +8,14 @@ export const zh = {
'progress.completed': '{count} 已完成',
'progress.active': '{count} 进行中',
'progress.pending': '{count} 待处理',
'list.more': '显示其余 {count} 个',
'list.less': '收起',
'list.foldName': '{label}(共享任务)',
'command.title': '智能体团队协作',
'command.running': '执行中',
'command.done': '已完成',
'command.failed': '执行失败',
'command.failedReason': '执行失败:{reason}',
trigger: '任务板',
'mode.label': '开启智能体团队协作',
'mode.on': '开启',
'mode.off': '关闭',
@@ -32,6 +34,7 @@ export const zh = {
tasks: '共享任务',
owner: '负责人',
unowned: '未分配',
'hover.owner': '负责人:{name}',
blocked: '被依赖阻塞',
'status.pending': '待处理',
'status.in_progress': '进行中',
@@ -46,12 +49,14 @@ export const en = {
'progress.completed': '{count} completed',
'progress.active': '{count} in progress',
'progress.pending': '{count} pending',
'list.more': 'Show {count} more',
'list.less': 'Show less',
'list.foldName': '{label} (shared tasks)',
'command.title': 'Agent teamwork',
'command.running': 'Running',
'command.done': 'Completed',
'command.failed': 'Failed',
'command.failedReason': 'Failed: {reason}',
trigger: 'Task board',
'mode.label': 'Enable agent teamwork',
'mode.on': 'On',
'mode.off': 'Off',
@@ -70,6 +75,7 @@ export const en = {
tasks: 'Shared tasks',
owner: 'Owner',
unowned: 'Unowned',
'hover.owner': 'Owner: {name}',
blocked: 'Blocked by dependencies',
'status.pending': 'Pending',
'status.in_progress': 'In progress',
@@ -81,6 +87,9 @@ export const ja = {
'progress.completed': '{count}件完了',
'progress.active': '{count}件進行中',
'progress.pending': '{count}件保留中',
'list.more': '残り{count}件を表示',
'list.less': '折りたたむ',
'list.foldName': '{label}(共有タスク)',
'command.title': 'エージェント連携',
'command.running': '実行中',
'command.done': '完了',
@@ -97,7 +106,6 @@ export const ja = {
'disable.cancel': 'キャンセル',
'disable.confirm': '無効にする',
'disable.close': '閉じる',
'trigger': 'タスクボード',
'loading': 'タスクボードを読み込み中…',
'unavailable': 'タスクボードは利用できません',
'failure': '保存されたタスクレコードが無効です: {message}',
@@ -105,6 +113,7 @@ export const ja = {
'tasks': '共有タスク',
'owner': 'オーナー',
'unowned': 'オーナーなし',
'hover.owner': '担当:{name}',
'blocked': '依存関係によりブロック中',
'status.pending': '保留中',
'status.in_progress': '進行中',
@@ -116,6 +125,9 @@ export const es = {
'progress.completed': '{count} completado',
'progress.active': '{count} en progreso',
'progress.pending': '{count} pendiente',
'list.more': 'Mostrar {count} más',
'list.less': 'Mostrar menos',
'list.foldName': '{label} (tareas compartidas)',
'command.title': 'Colaboración entre agentes',
'command.running': 'En ejecución',
'command.done': 'Completado',
@@ -132,7 +144,6 @@ export const es = {
'disable.cancel': 'Cancelar',
'disable.confirm': 'Confirmar desactivación',
'disable.close': 'Cerrar',
trigger: 'Tablero de tareas',
loading: 'Cargando tablero de tareas…',
unavailable: 'El tablero de tareas no está disponible',
failure: 'Registro de tarea persistente no válido: {message}',
@@ -140,6 +151,7 @@ export const es = {
tasks: 'Tareas compartidas',
owner: 'propietario',
unowned: 'Sin dueño',
'hover.owner': 'Responsable: {name}',
blocked: 'Bloqueado por dependencias',
'status.pending': 'Pendiente',
'status.in_progress': 'En progreso',
@@ -151,6 +163,9 @@ export const fr = {
'progress.completed': '{count} terminé',
'progress.active': '{count} en cours',
'progress.pending': '{count} en attente',
'list.more': 'Afficher {count} de plus',
'list.less': 'Afficher moins',
'list.foldName': '{label} (tâches partagées)',
'command.title': 'Collaboration entre agents',
'command.running': 'En cours',
'command.done': 'Terminé',
@@ -167,7 +182,6 @@ export const fr = {
'disable.cancel': 'Annuler',
'disable.confirm': 'Confirmer la désactivation',
'disable.close': 'Fermer',
trigger: 'Tableau des tâches',
loading: 'Chargement du tableau des tâches…',
unavailable: 'Le tableau des tâches n’est pas disponible',
failure: 'Enregistrement de tâche persistant non valide : {message}',
@@ -175,6 +189,7 @@ export const fr = {
tasks: 'Tâches partagées',
owner: 'Propriétaire',
unowned: 'Sans propriétaire',
'hover.owner': 'Responsable : {name}',
blocked: 'Bloqué par les dépendances',
'status.pending': 'En attente',
'status.in_progress': 'En cours',
@@ -186,6 +201,9 @@ export const de = {
'progress.completed': '{count} abgeschlossen',
'progress.active': '{count} in Bearbeitung',
'progress.pending': '{count} ausstehend',
'list.more': '{count} weitere anzeigen',
'list.less': 'Weniger anzeigen',
'list.foldName': '{label} (geteilte Aufgaben)',
'command.title': 'Agentenzusammenarbeit',
'command.running': 'Wird ausgeführt',
'command.done': 'Abgeschlossen',
@@ -202,7 +220,6 @@ export const de = {
'disable.cancel': 'Abbrechen',
'disable.confirm': 'Deaktivierung bestätigen',
'disable.close': 'Schließen',
trigger: 'Aufgabenübersicht',
loading: 'Aufgabenübersicht wird geladen…',
unavailable: 'Aufgabenübersicht ist nicht verfügbar',
failure: 'Ungültiger gespeicherter Aufgabeneintrag: {message}',
@@ -210,6 +227,7 @@ export const de = {
tasks: 'Geteilte Aufgaben',
owner: 'Besitzer',
unowned: 'Unbesessen',
'hover.owner': 'Zuständig: {name}',
blocked: 'Blockiert durch Abhängigkeiten',
'status.pending': 'Ausstehend',
'status.in_progress': 'In Bearbeitung',
@@ -221,6 +239,9 @@ export const ru = {
'progress.completed': '{count} завершено',
'progress.active': '{count} в процессе',
'progress.pending': '{count} в ожидании',
'list.more': 'Показать ещё {count}',
'list.less': 'Свернуть',
'list.foldName': '{label} (общие задачи)',
'command.title': 'Совместная работа агентов',
'command.running': 'Выполняется',
'command.done': 'Завершено',
@@ -237,7 +258,6 @@ export const ru = {
'disable.cancel': 'Отмена',
'disable.confirm': 'Подтвердить отключение',
'disable.close': 'Закрыть',
trigger: 'Доска задач',
loading: 'Загрузка доски задач…',
unavailable: 'Доска задач недоступна',
failure: 'Недопустимая сохранённая запись задачи: {message}',
@@ -245,6 +265,7 @@ export const ru = {
tasks: 'Общие задачи',
owner: 'Владелец',
unowned: 'Невладеющий',
'hover.owner': 'Ответственный: {name}',
blocked: 'Заблокировано зависимостями',
'status.pending': 'Ожидается',
'status.in_progress': 'В процессе',
@@ -256,6 +277,9 @@ export const pt = {
'progress.completed': '{count} concluído',
'progress.active': '{count} em andamento',
'progress.pending': '{count} pendente',
'list.more': 'Mostrar mais {count}',
'list.less': 'Mostrar menos',
'list.foldName': '{label} (tarefas compartilhadas)',
'command.title': 'Colaboração entre agentes',
'command.running': 'Em execução',
'command.done': 'Concluído',
@@ -272,7 +296,6 @@ export const pt = {
'disable.cancel': 'Cancelar',
'disable.confirm': 'Confirmar desativação',
'disable.close': 'Fechar',
trigger: 'Quadro de tarefas',
loading: 'Carregando quadro de tarefas…',
unavailable: 'O quadro de tarefas não está disponível',
failure: 'Registro de tarefa persistente inválido: {message}',
@@ -280,6 +303,7 @@ export const pt = {
tasks: 'Tarefas compartilhadas',
owner: 'Proprietário',
unowned: 'Sem dono',
'hover.owner': 'Responsável: {name}',
blocked: 'Bloqueado por dependências',
'status.pending': 'Pendente',
'status.in_progress': 'Em andamento',
@@ -2,7 +2,7 @@
import type { Context as ClientContext } from '@deepseek-ai/cordis'
import type {} from '@deepseek-ai/dsh-api-session-controller/client'
import type {} from '@deepseek-ai/dsh-client-ui-subagent/client'
import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client'
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
import type {} from '@deepseek-ai/dsh-client-locale/client'
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
@@ -12,7 +12,8 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { TeamDisableConfirmation, type TeamDisableConfirmationInjected, type TeamDisableRequest } from './TeamDisableConfirmation.tsx'
import { TeamModePane, TeamModeToggle, type TeamModePaneInjected } from './TeamModeToggle.tsx'
import { TeamBoard } from './TeamBoard.tsx'
import { TeamBoard, TeamProgress } from './TeamBoard.tsx'
import { createTeamBoardStore } from './team-board-store.ts'
import { TeamCommandRow } from './TeamCommandRow.tsx'
import { en, ja, es, fr, de, ru, pt, NS, zh, type TeamKey } from './locales.ts'
@@ -27,12 +28,13 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
export const inject = ['slots', 'locale']
/**
* Register the task-board dictionaries and subagent catalog sections.
* The panel reads the root Session’s `agentTeam` projection through standard Session hooks.
* Register the task-board dictionaries and the Session panel's shared tasks section.
* The section reads the root Session’s `agentTeam` projection through standard Session hooks.
* @param ctx - Client Context carrying the injected locale and slot services.
*/
export function registerAgentTeamUi(ctx: ClientContext): void {
ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'client-ui-agent-team: dictionaries')
const t = ctx.locale.bind(NS)
ctx.slots.inject('conversation.chat.commandview', () => ctx.slots.register({
name: 'conversation.chat.commandview', key: 'team', locale: NS,
}, TeamCommandRow))
@@ -68,7 +70,20 @@ export function registerAgentTeamUi(ctx: ClientContext): void {
}, TeamModePane))
})
})
ctx.slots.inject('conversation.session.header.actions.subagent.footer', () => ctx.slots.register({
name: 'conversation.session.header.actions.subagent.footer', id: 'agent-team', locale: NS,
}, TeamBoard))
ctx.slots.inject('conversation.session.panel.section', function* () {
yield ctx.slots.register({
name: 'conversation.session.panel.section',
id: 'shared-tasks',
// After subagents (200), before background jobs (300).
order: 250,
label: () => t('tasks'),
locale: NS,
store: createTeamBoardStore(),
}, TeamBoard)
yield ctx.slots.register({
name: 'conversation.session.panel.section.actions',
key: 'shared-tasks',
locale: NS,
}, TeamProgress)
})
}
@@ -0,0 +1,38 @@
/**
* Whether the user unfolded the shared tasks list of the Session panel. The
* registration declares it as an exclusive store, so each Session keeps its
* own while its scope is retained, across hiding and showing the panel.
*/
import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store'
/** The fold of one Session's shared tasks list. */
export interface TeamBoardState {
/** Whether the list shows every task instead of holding back the tasks past its limit. */
unfolded: boolean
}
/** The shared tasks store's write set. */
type TeamBoardActions = {
unfoldedSet: (draft: TeamBoardState, unfolded: boolean) => void
}
/**
* Declare the shared tasks section's store.
* @returns the store handle to declare on the registration.
*/
export function createTeamBoardStore(): EngineStoreHandle<TeamBoardState, TeamBoardActions> {
return defineStore({
init: (): TeamBoardState => ({ unfolded: false }),
actions: {
/**
* Record the user's choice to show every task or fold the list again.
* @param d - draft state.
* @param unfolded - whether the list now shows every task.
*/
unfoldedSet: (d, unfolded: boolean) => {
d.unfolded = unfolded
},
},
})
}
@@ -5,9 +5,10 @@ import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
import { TeamModePane, TeamModeToggle, type TeamModePaneInjected } from '../src/client/TeamModeToggle.tsx'
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
import { TeamBoard } from '../src/client/TeamBoard.tsx'
import { TeamBoard, TeamProgress } from '../src/client/TeamBoard.tsx'
import { TeamCommandRow } from '../src/client/TeamCommandRow.tsx'
import { TeamDisableConfirmation, type TeamDisableConfirmationInjected } from '../src/client/TeamDisableConfirmation.tsx'
import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots'
import { apply, inject } from '../src/client/index.ts'
import { apply as nodeApply } from '../src/index.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
@@ -20,43 +21,52 @@ async function bench() {
const collapseHeader = ctx.slots.register({
name: 'root',
children: {
'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' },
'conversation.session.panel.section': { kind: 'list', scope: 'session' },
'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' },
'conversation.input.model': { kind: 'single', scope: 'session' },
'shell.overlay': { kind: 'list', scope: 'root' },
},
} as never, () => null)
const fiber = ctx.plugin({ inject: [...inject], apply })
await fiber.await()
const entry = () => ctx.slots.entries('conversation.session.header.actions.subagent.footer')
const entry = () => ctx.slots.entries('conversation.session.panel.section')
.find(candidate => candidate.component === TeamBoard)
return { ctx, fiber, entry, collapseHeader }
const progress = () => ctx.slots.entries('conversation.session.panel.section.actions')
.find(candidate => candidate.component === TeamProgress)
return { ctx, fiber, entry, progress, collapseHeader }
}
describe('task-board browser plugin', () => {
it('registers a disposable root task-board section without navigation or Team Remote services', async () => {
it('registers a disposable shared tasks section with its progress, without navigation or Team Remote services', async () => {
const b = await bench()
expect(inject).toEqual(['slots', 'locale'])
expect(b.entry()).toMatchObject({
options: { id: 'agent-team' },
options: { id: 'shared-tasks', order: 250 },
locale: 'agent-team',
})
expect(b.entry()!.inject).toBeUndefined()
expect(resolveSlotLabel(b.entry()!.options.label)).toBe('Shared tasks')
expect(b.progress()).toMatchObject({ options: { key: 'shared-tasks' }, locale: 'agent-team' })
expect(b.ctx.slots.entries('conversation.session.header.actions')).toHaveLength(0)
const t = b.ctx.locale.bind('agent-team')
expect(t('trigger')).toBe('Task board')
expect(t('tasks')).toBe('Shared tasks')
await b.fiber.dispose()
expect(b.entry()).toBeUndefined()
expect(b.progress()).toBeUndefined()
expect(t('empty')).toBe('empty')
})
it('re-registers when the conversation header slot is declared again', async () => {
it('re-registers when the section slot is declared again', async () => {
const b = await bench()
expect(b.entry()).toBeDefined()
b.collapseHeader()
expect(b.entry()).toBeUndefined()
b.ctx.slots.register({
name: 'root',
children: { 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' } },
children: {
'conversation.session.panel.section': { kind: 'list', scope: 'session' },
'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' },
},
} as never, () => null)
await Promise.resolve()
expect(b.entry()).toBeDefined()
@@ -8,8 +8,10 @@ import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-sess
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
import { TeamBoard, type TeamBoardProps } from '../src/client/TeamBoard.tsx'
import { TeamBoard, TeamProgress, type TeamBoardProps, type TeamProgressProps } from '../src/client/TeamBoard.tsx'
import { createTeamBoardStore } from '../src/client/team-board-store.ts'
import { en, zh } from '../src/client/locales.ts'
import type { PanelDetailsProps, PanelFoldProps } from '@deepseek-ai/dsh-client-ui-session-panel/client'
afterEach(() => {
cleanup()
@@ -46,11 +48,35 @@ function summary(id: SessionId, title?: string): SessionSummary {
}
}
/** One Session's board store, as the registration mints it. */
type BoardStore = ReturnType<ReturnType<typeof createTeamBoardStore>['create']>
/**
* The Session panel's Factories as this suite renders them: the fold control as a button with its state, name, and
* label, and a row's details as one element per part in order. ui-session-panel's own suite owns their markup.
*/
function renderPanelFactory(name: string, input: object) {
if (name === 'conversation.session.panel.details') {
const { title, lines = [], status, facts = [] } = input as PanelDetailsProps
return (
<div data-session-panel-details="">
{title !== undefined && <div>{title}</div>}
{lines.map(line => <div key={line}>{line}</div>)}
{status !== undefined && <div data-state={status.state}>{status.label}</div>}
{facts.length > 0 && <div>{facts.map(fact => <span key={fact.kind} data-fact={fact.kind}>{fact.label}</span>)}</div>}
</div>
)
}
const fold = input as PanelFoldProps
return <button type="button" data-fold="" aria-expanded={fold.expanded} aria-label={fold.name} onClick={fold.onToggle}>{fold.label}</button>
}
function bench(options: {
projections?: Projections
sessionId?: SessionId
byId?: Record<SessionId, SessionSummary>
value?: TeamProjection
store?: BoardStore
} = {}) {
const sessionId = options.sessionId ?? SESSION
const byId = options.byId ?? { [SESSION]: summary(SESSION) }
@@ -63,12 +89,14 @@ function bench(options: {
const value = state.projectionsBySession[sessionId]?.values.agentTeam
return selector === undefined ? value : selector(value)
})) as TeamBoardProps['useProjection']
const store = options.store ?? createTeamBoardStore().create()
const props = {
sessionId, useProjection,
useSessions: bindSnapshotSelector(sessions),
useStore: bindSnapshotSelector(store), actions: store.actions, renderFactorySlot: renderPanelFactory,
t: makeTranslate(zh, commonZh),
} as TeamBoardProps
return { props, sessions }
return { props, sessions, store }
}
function setProjectionSnapshot(
@@ -108,14 +136,20 @@ function enableTooltips(): void {
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })))
}
/** The text the progress beside the section title renders for these props. */
function progressText(props: TeamBoardProps): string {
const progress: Pick<TeamProgressProps, 'useProjection' | 't'> = { useProjection: props.useProjection, t: props.t }
const view = render(<TeamProgress {...progress as TeamProgressProps} />)
const text = view.container.textContent
view.unmount()
return text
}
describe('TeamBoard', () => {
it('shows a nonclickable Checklist header and compact initially closed rows', () => {
it('leaves the title to the panel and shows compact initially closed rows', () => {
const b = bench()
render(<TeamBoard {...b.props} />)
const heading = screen.getByRole('heading')
expect(heading.textContent).toBe(`${zh.tasks}${b.props.t('progress.active', { count: 1 })}`)
expect(heading.querySelector('button')).toBeNull()
expect(heading.querySelector('[data-icon="dsw-icon-checklist-outline-regular"]')).toBeTruthy()
expect(screen.queryByRole('heading')).toBeNull()
expect(screen.getAllByRole('button')).toEqual([row()])
expect(row().getAttribute('aria-expanded')).toBe('false')
expect(row().textContent).toBe(task.subject)
@@ -163,7 +197,7 @@ describe('TeamBoard', () => {
expect(screen.getAllByRole('button').every(button => button.getAttribute('aria-expanded') === 'false')).toBe(true)
})
it('preserves source order, keeps completed tasks, and excludes deleted tombstones from rows and counts', () => {
it('lists tasks in progress, then pending, then completed, and excludes deleted tombstones from rows and counts', () => {
const b = bench({ value: { ...team, tasks: [
{ ...task, subject: 'Pending first', status: 'pending', ready: true },
{ ...task, id: TASK_2, subject: 'Completed second', status: 'completed' },
@@ -171,10 +205,10 @@ describe('TeamBoard', () => {
{ ...task, id: 'deleted' as TeamTaskId, subject: 'Deleted task', status: 'deleted' },
] } })
render(<TeamBoard {...b.props} />)
expect(screen.getAllByRole('button').map(button => button.textContent)).toEqual(['Pending first', 'Completed second', 'Active third'])
expect(screen.getByRole('heading').textContent).toBe(`${zh.tasks}${[
expect(screen.getAllByRole('button').map(button => button.textContent)).toEqual(['Active third', 'Pending first', 'Completed second'])
expect(progressText(b.props)).toBe([
b.props.t('progress.completed', { count: 1 }), b.props.t('progress.active', { count: 1 }), b.props.t('progress.pending', { count: 1 }),
].join('\u2002·\u2002')}`)
].join('\u2002·\u2002'))
expect(screen.queryByText('Deleted task')).toBeNull()
expect(row('Pending first').querySelector('[data-state="idle"]')).toBeTruthy()
expect(row('Completed second').querySelector('[data-state="done"]')).toBeTruthy()
@@ -184,6 +218,65 @@ describe('TeamBoard', () => {
expect(screen.getByText(task.description)).toBeTruthy()
})
/** A task named by its id. */
const named = (id: string, status: TeamTask['status']): TeamTask => ({ ...task, id: id as TeamTaskId, subject: id, status, ready: true })
/** The task rows' names in display order. */
const shownTasks = (): (string | null)[] => [...document.querySelectorAll('[data-team-task]')].map(item => item.getAttribute('data-team-task'))
const fold = (): HTMLElement | null => document.querySelector('[data-fold]')
it('keeps source order within the tasks in progress and the pending ones, and lists the latest completed task first', () => {
const b = bench({ value: { ...team, tasks: [
named('done-1', 'completed'), named('wait-1', 'pending'), named('run-1', 'in_progress'), named('done-2', 'completed'),
named('wait-2', 'pending'), named('run-2', 'in_progress'),
] } })
render(<TeamBoard {...b.props} />)
expect(shownTasks()).toEqual(['run-1', 'run-2', 'wait-1', 'wait-2', 'done-2', 'done-1'])
// Six tasks show in full: folding would hold back one task for a control that takes a row itself.
expect(fold()).toBeNull()
})
it('holds two tasks back from seven, behind a fold control that shows them and folds again', () => {
const tasks = [
named('done-1', 'completed'), named('done-2', 'completed'), named('run-1', 'in_progress'), named('wait-1', 'pending'),
named('wait-2', 'pending'), named('wait-3', 'pending'), named('wait-4', 'pending'),
]
const b = bench({ value: { ...team, tasks } })
render(<TeamBoard {...b.props} />)
expect(shownTasks()).toEqual(['run-1', 'wait-1', 'wait-2', 'wait-3', 'wait-4'])
const control = fold() as HTMLElement
expect([control.textContent, control.getAttribute('aria-label'), control.getAttribute('aria-expanded')])
.toEqual(['显示其余 2 个', '显示其余 2 个(共享任务)', 'false'])
// The control follows the list instead of joining it, so the list holds only tasks.
expect(screen.getByRole('list').contains(control)).toBe(false)
fireEvent.click(control)
expect(shownTasks()).toEqual(['run-1', 'wait-1', 'wait-2', 'wait-3', 'wait-4', 'done-2', 'done-1'])
expect([fold()?.textContent, fold()?.getAttribute('aria-label'), fold()?.getAttribute('aria-expanded')]).toEqual(['收起', '收起(共享任务)', 'true'])
fireEvent.click(fold() as HTMLElement)
expect(shownTasks()).toHaveLength(5)
// The progress beside the title counts every task, shown or held back.
expect(progressText(b.props)).toBe([
b.props.t('progress.completed', { count: 2 }), b.props.t('progress.active', { count: 1 }), b.props.t('progress.pending', { count: 4 }),
].join('\u2002·\u2002'))
})
it('keeps the fold in the Session store while the section is unmounted', () => {
const store = createTeamBoardStore().create()
const tasks = Array.from({ length: 8 }, (_, index) => named(`wait-${index}`, 'pending'))
const first = render(<TeamBoard {...bench({ value: { ...team, tasks }, store }).props} />)
fireEvent.click(fold() as HTMLElement)
expect(store.getSnapshot()).toEqual({ unfolded: true })
first.unmount()
render(<TeamBoard {...bench({ value: { ...team, tasks }, store }).props} />)
expect(shownTasks()).toHaveLength(8)
expect(fold()?.getAttribute('aria-expanded')).toBe('true')
})
it.each(Object.entries({ zh, en }))('names the fold control with its visible text first in %s', (_locale, copy) => {
for (const label of [copy['list.more'].replace('{count}', '3'), copy['list.less']]) {
expect(copy['list.foldName'].replace('{label}', label).startsWith(label)).toBe(true)
}
})
it('announces blocked status without displaying readiness, dependencies, scopes, warnings, or task ids', () => {
const { ownerId: _ownerId, ownerName: _ownerName, ...unowned } = task
const b = bench({ value: { ...team, tasks: [
@@ -244,6 +337,7 @@ describe('TeamBoard', () => {
const b = bench()
render(<TeamBoard {...b.props} />)
setProjection(b.sessions, SESSION, { ...team, enabled: false })
expect(progressText(b.props)).toBe('')
expect(screen.queryByRole('region')).toBeNull()
expect(screen.queryByText(task.subject)).toBeNull()
setProjection(b.sessions, SESSION, team)
@@ -283,7 +377,6 @@ describe('TeamBoard', () => {
const view = render(<TeamBoard {...b.props} />)
expect(screen.getByRole('alert').textContent).toBe('任务记录无效:revision is not contiguous')
expect(row()).toBeTruthy()
expect(screen.getByRole('heading')).toBeTruthy()
for (const tasks of [[], [{ ...task, status: 'deleted' as const }]]) {
setProjectionSnapshot(b.sessions, SESSION, { state: 'ready', error: null, values: {
agentTeam: { enabled: true, tasks, failure: 'invalid task' },
@@ -293,11 +386,8 @@ describe('TeamBoard', () => {
expect(alert.textContent).toBe('任务记录无效:invalid task')
expect(screen.getAllByRole('alert')).toHaveLength(1)
expect(view.container.textContent).toBe(alert.textContent)
expect(view.container.querySelector('[data-with-members="true"]')).toBeNull()
expect(screen.queryByRole('heading')).toBeNull()
expect(screen.queryByRole('region')).toBeNull()
expect(screen.queryByText(zh.empty)).toBeNull()
expect(document.querySelector('[data-team-panel]')).toBeNull()
expect(progressText(b.props)).toBe('')
}
setProjection(b.sessions, SESSION, { enabled: false, tasks: [], failure: 'invalid task' })
expect(view.container.childElementCount).toBe(0)
@@ -334,7 +424,7 @@ describe('TeamBoard', () => {
it('uses translated English progress and details without Show more or Show less controls', () => {
const b = bench()
render(<TeamBoard {...b.props} t={makeTranslate(en)} />)
expect(screen.getByRole('heading').textContent).toBe(`${en.tasks}${makeTranslate(en)('progress.active', { count: 1 })}`)
expect(progressText({ ...b.props, t: makeTranslate(en) })).toBe(makeTranslate(en)('progress.active', { count: 1 }))
fireEvent.click(row())
expect(ownerValue()).toBe('lead')
expect(document.querySelector('[data-team-task-owner]')?.textContent).toBe(`${en.owner}: lead`)
@@ -374,36 +464,28 @@ describe('TeamBoard', () => {
expect(ownerValue()).toBeNull()
})
it('delays clipped collapsed subject hover by 500ms while keeping keyboard focus immediate', () => {
it('shows the subject, owner, description, and state in a hover card after 500ms, and none while the row is expanded', () => {
vi.useFakeTimers()
enableTooltips()
const view = render(<TeamBoard {...bench().props} />)
vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: query === '(any-hover: hover)' })))
render(<TeamBoard {...bench().props} />)
const button = row()
const subject = screen.getByText(task.subject)
const scrollWidth = vi.spyOn(Element.prototype, 'scrollWidth', 'get').mockReturnValue(80)
vi.spyOn(Element.prototype, 'clientWidth', 'get').mockReturnValue(80)
fireEvent.pointerEnter(button)
act(() => { vi.advanceTimersByTime(500) })
expect(screen.queryByRole('tooltip')).toBeNull()
fireEvent.pointerLeave(button)
scrollWidth.mockImplementation(function (this: Element) { return this === subject ? 180 : 80 })
fireEvent.pointerEnter(button)
const anchor = button.parentElement as HTMLElement
const details = (): string[] | null => {
const card = document.querySelector('[data-session-panel-details]')
return card === null ? null : [...card.children].map(child => child.textContent ?? '')
}
fireEvent.pointerEnter(anchor, { pointerType: 'mouse' })
act(() => { vi.advanceTimersByTime(499) })
expect(screen.queryByRole('tooltip')).toBeNull()
expect(details()).toBeNull()
act(() => { vi.advanceTimersByTime(1) })
expect(screen.getByRole('tooltip').textContent).toBe(task.subject)
expect(view.container.contains(screen.getByRole('tooltip'))).toBe(false)
expect(details()).toEqual([task.subject, '负责人:lead', task.description, '进行中'])
// Expanding the row shows the same details in place, so the card closes and stays closed.
fireEvent.click(button)
expect(row()).toBe(button)
expect(screen.queryByRole('tooltip')).toBeNull()
fireEvent.pointerLeave(button)
fireEvent.pointerEnter(button)
act(() => { vi.advanceTimersByTime(200) })
expect(details()).toBeNull()
fireEvent.pointerLeave(anchor, { pointerType: 'mouse' })
fireEvent.pointerEnter(anchor, { pointerType: 'mouse' })
act(() => { vi.advanceTimersByTime(500) })
expect(screen.queryByRole('tooltip')).toBeNull()
fireEvent.click(button)
fireEvent.pointerLeave(button)
fireEvent.keyDown(document.body, { key: 'Tab' })
fireEvent.focus(button)
expect(screen.getByRole('tooltip').textContent).toBe(task.subject)
expect(details()).toBeNull()
})
})
+1 -1
View File
@@ -13,7 +13,7 @@
{ "path": "../ui-model-selection" },
{ "path": "../ui-layout" },
{ "path": "../../core/agent" },
{ "path": "../ui-subagent" },
{ "path": "../ui-session-panel" },
{ "path": "../locale/tsconfig.client.json" },
{ "path": "../store" },
{ "path": "../ui-conversation/tsconfig.client.json" },
+12 -12
View File
@@ -3,32 +3,32 @@
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/ui-jobs/README.md
/:
en: 063a69d5d6281c07
zh: 04562d2b1dd29590
en: ee6ba7faaa030a05
zh: c74dcdb3f5d7d0b7
/deepseek-ai-dsh-client-ui-jobs:
en: faa1eecdc7f06930
zh: c6e7b06ccb434f0b
/deepseek-ai-dsh-client-ui-jobs/summary:
en: b61245c057c1a924
zh: 6013131975ece32e
en: 4181e6f8df4dc4e9
zh: 7a8f25a775bd854a
/deepseek-ai-dsh-client-ui-jobs/table-of-contents:
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
/deepseek-ai-dsh-client-ui-jobs/use-this-package:
en: 3466553808f81088
zh: 02a806ece1c3e012
en: 6ebf1b995be0d5ba
zh: a6dba97d5b8f6bfb
/deepseek-ai-dsh-client-ui-jobs/use-this-package/one-row-per-job:
en: 64c1f55b35e73295
zh: 4d93594923cf787f
en: 67eec41471ccdf6b
zh: 2ffe602ad5575643
/deepseek-ai-dsh-client-ui-jobs/use-this-package/the-expanded-panel:
en: c34dad62fee63306
zh: 167d9da7928a9488
/deepseek-ai-dsh-client-ui-jobs/understand-the-implementation:
en: 640e8bd39b28c07d
zh: 86c7eb39acfeebc0
en: e5bbb2f24732e6e9
zh: ac3f248b255c5211
/deepseek-ai-dsh-client-ui-jobs/further-exploration:
en: 01eaaecb5850f391
zh: 2eabd14cde191ab8
en: e9370f09a7b49495
zh: 6b297e9dbf7a6aa6
/deepseek-ai-dsh-client-ui-jobs/model-experience:
en: 84ad94ba940f17af
zh: 0199b09d360df0d8
+12 -10
View File
@@ -1,5 +1,5 @@
---
description: "The session-header background-job list: expandable streaming output panels, running/finished sections, and static rows for settled jobs without retained output."
description: "The Session panel's background-jobs section: expandable streaming output panels, live rows above a folded finished list, and static rows for settled jobs without retained output."
kind: "package-reference"
---
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
## Summary
`dsh-client-ui-jobs` shows the session's background jobs in one header control, with lifecycle, elapsed time, progress, and terminal detail. Live jobs and settled jobs with retained output offer expandable output panels; collapsing stops the stream. Live rows lead with a ticking duration, followed by kind and status. Settled rows fold under a section heading; those without retained output, including subagents whose answers went to the model, stay static.
`dsh-client-ui-jobs` shows the session's background jobs in the Session panel's Background jobs section, with lifecycle, elapsed time, progress, and terminal detail. Live jobs and settled jobs with retained output offer expandable output panels; collapsing stops the stream. Live rows show the label above the kind, current progress, and a ticking duration. Settled rows fold under a count; those without retained output, including subagents whose answers went to the model, stay static.
## Table of Contents
@@ -25,17 +25,17 @@ English | [中文](README.zh.md)
<a id="use-this-package"></a>
## Use this package
Load the plugin through the web-app manifest; it renders nothing until the session can see at least one job, so an ordinary conversation never grows a control for a capability it is not using.
Load the plugin through the web-app manifest. It registers the [Session panel](../ui-session-panel/README.md#contribute-a-section) section `background-jobs` at order 300, after Subagents, titled “Background jobs”. While jobs run and the panel does not show, a blue dot on the panel toggle (`conversation.session.panel.indicator`) says so and names their number for assistive technology; it keeps the Session's roster stream open while the toggle is mounted. The section renders nothing until the session can see at least one job, so the panel hides it together with its title and an ordinary conversation shows no section for a capability it is not using.
The header shows the live job count when any jobs are running or stopping, otherwise the visible job count, without repeating the spinner's running state in visible text. The trigger's accessible description identifies live work in both wide and compact layouts. In wide layout, a 14px icon slot shows the spinner for live jobs or the 14px layers icon for idle jobs; the root trigger has no disclosure arrow. At container widths up to 460px, the count hides and the trigger always shows the layers icon, including while jobs are live; running indicators remain inside the menu. The trigger matches More and sidebar controls: a 28×28px icon button with no padding, a 15px glyph in a 15px slot, secondary ink, and ghost hover and active backgrounds. Header actions use an 8px gap in compact layout and 10px in wide layout. Its count tooltip appears after 500ms of hover or immediately on keyboard focus, and stays hidden while the list is open.
Live rows come first, the most recently started first; settled rows follow newest-first under a “Finished {count}” toggle, whose chevron follows the text, with a “Clear” action. The toggle starts folded while a job is live and open otherwise; the user's choice holds for the Session, also after the panel is hidden and shown again. Each of the two groups shows five rows and then the Session panel's fold control as its last row, “Show {count} more running” or “Show {count} more finished”, which shows the rest and then reads “Show less”; a group folds only when that holds back two rows or more. That choice also holds for the Session, and Clear folds the settled group to five rows again. An expanded row stops observing its output while its group holds it back. Each row is one 28px line with the command, then the duration, the stop control while the job runs, and a chevron at its end, in the Session panel's columns; the whole row, chevron included, expands and collapses it. A command the row clips crawls into view while the pointer rests on the row, and the stop control names its action after 500ms of hover. Resting the pointer on a row for 500ms opens a hover card with the job kind, the status or terminal detail, and the duration, but not the command, which can run to many lines and shows in full, with Copy, in the expanded output panel; the card stays closed while the pointer rests on the stop control; assistive technology reads the kind and status as the row's description. A job that finished with a nonzero exit code shows the warning dot, like a stopped one, and a `failed` job the error dot. The settled list folds while any job is live and opens when only settled jobs remain; pressing the toggle overrides that default. Clear hides the current settled rows in this client while the Session stays open, also after the panel is hidden and shown again; the registry keeps their records, a job that settles later appears normally, and the section hides when no rows remain.
Non-touch hover on the text-visible trigger opens the list after 150ms; leaving both the trigger and its portaled list closes it after 120ms. Clicking the wide trigger opens or pins the list; clicking an already pinned trigger closes it. The compact trigger toggles on click and never opens on hover, including when the count hides during a pending hover. ArrowDown opens and pins the list and focuses its first control. Pointer interaction or keyboard focus inside also pins it. Outside click or Escape dismisses it, and Tab connects the trigger to the portaled controls. Hover timers and pins reset when the session changes, no visible jobs remain, or the component unmounts.
Pressing an observable row expands its output panel, and pressing it again collapses it; one row expands at a time. Each duration has a tooltip, “Running for {duration}” on live rows and “Took {duration}” on settled rows, and live durations advance once per second while any job is live.
### One row per job
The `job.list` stream `ctx.jobs` mirrors is the single roster: each `JobView` row carries lifecycle, duration, the live `progress` line or the terminal `detail`, and its retained byte count — a live job, or a settled one with retained output, is what makes a row expandable. There is no second roster to join.
Running job rows also carry a two-press stop control: the first press arms it, the confirming press within three seconds calls `ctx.jobs.kill`, and the row converges through the roster stream (`stopping`, then the settled section, whose detail carries `cancelled by the user`). The kill claims nothing in the model's notice ledger, so the owning agent still receives the standard completion notice — the model is told the user stopped its task rather than left to infer it ([reference](../../jobs/tool-jobs/README.md)). The settled section folds behind its count while live work exists and can be cleared client-side.
Running job rows also carry a two-press stop control, whose tooltip reads “Stop task” without the command: the first press arms it and widens it into a “Confirm stop” button, the confirming press within three seconds calls `ctx.jobs.kill`, and the row converges through the roster stream (`stopping`, then the settled list, whose detail carries `cancelled by the user`). A rejected kill shows “Stop failed” for four seconds. The kill claims nothing in the model's notice ledger, so the owning agent still receives the standard completion notice — the model is told the user stopped its task rather than left to infer it ([reference](../../jobs/tool-jobs/README.md)).
### The expanded panel
@@ -49,15 +49,16 @@ Expanding an observable row opens that job's output observation stream from `ctx
<details>
<summary>Implementation internals — click to expand</summary>
One slot entry in the header actions band (after the preset label) renders the trigger; its popover uses a body-mounted `MenuSurface` with fixed positioning so dock panels and clipping ancestors cannot cover it. CSS anchors keep the popover attached to its trigger within layout-viewport size limits. Browser zoom and panning move it with the page, so it may extend beyond the visual viewport. Its internal scrolling and dismissal remain available. All data arrives through `ctx.jobs` — the component holds no transport state. The roster follows the mount: one `useEffect` keeps the session's `job.list` stream open while the control lives. Observation follows visibility: another `useEffect` opens the stream for the expanded row's job and closes it on collapse, unmount, or popover close.
One `conversation.session.panel.section` registration renders the section body; the Session panel draws its title, supplies its inset, and scrolls it. All data arrives through `ctx.jobs` — the component holds no transport state. The roster follows the mount: one `useEffect` keeps the session's `job.list` stream open while the section is mounted, which is while the Session panel shows. Observation follows visibility: another `useEffect` opens the stream for the expanded row's job and closes it on collapse or unmount, including when the panel hides.
| File | Role |
|---|---|
| [`src/client/JobListAction.tsx`](src/client/JobListAction.tsx) | The job list: sections, durations, panels |
| [`src/client/index.ts`](src/client/index.ts) | Slot registration and the dictionaries |
| [`src/client/JobsSection.tsx`](src/client/JobsSection.tsx) | The section: live and settled rows, durations, the stop control, output panels |
| [`src/client/jobs-store.ts`](src/client/jobs-store.ts) | Per-Session store of cleared rows |
| [`src/client/index.ts`](src/client/index.ts) | Session panel section registration and the dictionaries |
| [`src/client/locales.ts`](src/client/locales.ts) | The `job` namespace copy (zh source of truth) |
Background-job rows follow the [standard menu edge geometry](../../../docs/ui-radius.md#nested-hover); controls inside a filled running row retain compact corners.
Background-job rows use the standard menu item radius from the [nested geometry rules](../../../docs/ui-radius.md#nested-hover); controls inside a filled running row retain compact corners.
</details>
@@ -68,6 +69,7 @@ Background-job rows follow the [standard menu edge geometry](../../../docs/ui-ra
- [`dsh-api-job-controller`](../../api/job-controller/README.md) — the `job.list` and `job.follow` streams, the `job.kill` Remote, and the `ctx.jobs` service behind the rows, the panel, and the stop control.
- [`dsh-jobs`](../../jobs/jobs/README.md) — the registry contract that owns the ring and projection semantics.
- [`dsh-client-ui-session-panel`](../ui-session-panel/README.md) — the Session panel that orders, titles, and scrolls this section.
- [`dsh-client-ui-primitives`](../ui-primitives/README.md) — the `TerminalBlock` surface the panel configures.
-----
+12 -10
View File
@@ -1,5 +1,5 @@
---
description: "会话头部后台任务列表:可展开的流式输出面板、进行中/已结束分组,以及无保留输出的已结束任务的静态行。"
description: "会话面板的「后台任务」分栏:可展开的流式输出面板、位于已折叠的已结束列表上方的进行中行,以及无保留输出的已结束任务的静态行。"
kind: "package-reference"
---
@@ -9,7 +9,7 @@ kind: "package-reference"
## 概述
`dsh-client-ui-jobs` 在一个头部控件中展示本会话的后台任务,包括生命周期、耗时、进度与终态详情。进行中的任务和保留了输出的已结束任务提供可展开的输出面板;收起即停流。进行中的行以持续更新的时长为主行,随后展示类型与状态。已结束的行折叠在分组标题下;没有保留输出的任务保持静态,包括回答已交给模型的 subagent。
`dsh-client-ui-jobs` 在会话面板的「后台任务」分栏中展示本会话的后台任务,包括生命周期、耗时、进度与终态详情。进行中的任务和保留了输出的已结束任务提供可展开的输出面板;收起即停流。进行中的行在标签下方展示类型、当前进度与持续更新的时长。已结束的行折叠在计数之下;没有保留输出的任务保持静态,包括回答已交给模型的 subagent。
## 目录
@@ -25,17 +25,17 @@ kind: "package-reference"
<a id="use-this-package"></a>
## 使用本包
通过 web-app 清单加载本插件;在会话看得到至少一个 job 之前它不渲染任何东西,因此普通对话不会为未使用的能力长出控件。
通过 web-app 清单加载本插件。它在 order 300 注册[会话面板](../ui-session-panel/README.zh.md#contribute-a-section)分栏 `background-jobs`,位于「子智能体」之后,标题为「后台任务」。任务运行中且面板未显示时,面板开关上的蓝点(`conversation.session.panel.indicator`)会提示这一状态,并向辅助技术说明数量;开关挂载期间它保持该会话的任务列表订阅。在会话看得到至少一个 job 之前,该分栏不渲染任何东西,面板因此连同标题一起隐藏它,普通对话不会为未使用的能力显示分栏。
有运行中或正在停止的任务时,头部显示这些任务的数量;否则显示可见任务总数,可见文字不重复旋转指示器已表达的运行状态。宽布局和紧凑布局中的触发器均通过无障碍描述说明是否有进行中的任务。宽布局下,14px 图标区域在有进行中任务时显示旋转指示器,否则显示 14px 图层图标;根触发器不带展开箭头。容器宽度不超过 460px 时,数量文字隐藏,触发器始终显示图层图标,包括任务运行期间;运行指示器仍在菜单内显示。触发器与更多及侧边栏控件一致:28×28px 图标按钮,无内边距,15px 图标位内显示 15px 图标,使用次级前景色以及 ghost 悬停和按下背景。页头操作在紧凑布局中间距为 8px,宽布局中为 10px。数量工具提示在悬停 500ms 后或获得键盘焦点时立即显示,列表打开期间保持隐藏。
进行中的行排在最前,最近开始的在前;已结束的行按结束时间从新到旧排在「已结束 {count}」切换按钮之下,箭头紧跟文字,旁边有「清空」操作。有进行中的任务时默认折叠,否则默认展开;用户的选择在 Session 内保持,隐藏后再次显示面板也不变。两个分组各自只显示五行,然后以会话面板的收起控件作为最后一行:「显示其余 {count} 个运行中」或「显示其余 {count} 个已结束」,点击后显示其余的行并变为「收起」;只有能收起两行及以上时分组才收起。这个选择同样在 Session 内保持,「清空」会让已结束分组回到只显示五行。已展开的行被分组收起期间停止观察输出。每行只占 28px 一行:命令,行尾依次是时长、运行时的停止按钮和箭头,遵循会话面板的列;点整行(包括箭头)都能展开或收起。命令放不下时,指针停在这一行上会滚动显示全文;停止按钮悬停 500ms 后显示其操作说明。指针在行上停留 500ms 后,悬停卡片显示任务类型、状态或结束详情以及时长,但不显示命令:命令可能有很多行,展开输出面板后可查看全文并复制;指针停在停止按钮上时不显示悬停卡片;辅助技术把任务类型和状态作为该行的描述读出。以非 0 退出码结束的任务显示警告色圆点,与被停止的任务相同;`failed` 的任务显示错误色圆点。有任务进行中时已结束列表折叠,只剩已结束任务时展开;按下切换按钮会覆盖该默认状态。「清空」在本客户端中隐藏当前已结束的行,Session 保持打开期间一直有效,隐藏后再次显示面板也不变;注册表保留其记录,之后结束的 job 照常出现,没有剩余行时分栏隐藏。
非触摸指针在文字可见的触发器上悬停 150ms 后打开列表;指针离开触发器和挂载到 portal 的列表后,经过 120ms 关闭。点击宽布局触发器会打开或固定列表;再次点击已固定的触发器会关闭列表。紧凑触发器通过点击切换开关状态,不因悬停打开,包括等待悬停期间数量文字隐藏的情况。ArrowDown 会打开并固定列表,将焦点移至首个控件。在列表内进行指针交互或移入键盘焦点也会固定列表。点击外部或按 Escape 可关闭列表,Tab 将触发器与 portal 内的控件连接起来。切换会话、没有可见任务或组件卸载时,悬停计时器与固定状态都会重置。
按下可观察的行会展开其输出面板,再次按下则收起;同一时间只展开一行。每个时长都带工具提示:进行中的行为「已运行 {duration}」,已结束的行为「耗时 {duration}」;有任务进行中时,进行中的时长每秒更新一次。
### 一 job 一行
`ctx.jobs` 镜像的 `job.list` 流是唯一名册:每个 `JobView` 行携带生命周期、时长、实时 `progress` 行或终态 `detail`,以及其保留字节数——进行中的 job,或留有保留输出的已结束 job,就是行可展开的依据。不存在需要 join 的第二份名册。
运行中的 job 行还带一个两击式停止控件:首击武装,三秒内的确认击调用 `ctx.jobs.kill`,行状态经名册流收敛(先 `stopping`,再入已结束分组,其 detail 携带 `cancelled by the user`)。该 kill 不在模型的播报台账里认领任何东西,任务的 owner agent 因此照常收到标准完成通知——模型被明确告知用户停止了它的任务,而不是留给它去猜([参考](../../jobs/tool-jobs/README.zh.md))。已结束分组在有进行中工作时折叠在其计数之后,并可在客户端清空。
运行中的 job 行还带一个两击式停止控件,其提示只写「停止任务」,不带命令:首击武装并将其展宽为「确认停止」按钮,三秒内的确认击调用 `ctx.jobs.kill`,行状态经名册流收敛(先 `stopping`,再入已结束列表,其 detail 携带 `cancelled by the user`)。kill 被拒绝时显示「停止失败」四秒。该 kill 不在模型的播报台账里认领任何东西,任务的 owner agent 因此照常收到标准完成通知——模型被明确告知用户停止了它的任务,而不是留给它去猜([参考](../../jobs/tool-jobs/README.zh.md))。
### 展开的面板
@@ -49,15 +49,16 @@ kind: "package-reference"
<details>
<summary>实现内幕——点击展开</summary>
头部操作带里的一个 slot 条目(preset 标签之后)渲染触发器;弹出层通过挂载到 body 的 `MenuSurface` 固定定位,避免被停靠面板遮挡或被祖先容器裁剪。CSS 锚点让弹层跟随触发器,并按布局视口限制尺寸。浏览器缩放和平移时弹层随页面移动,因此可以超出视觉视口。内部滚动和关闭操作保持可用。所有数据经 `ctx.jobs` 到达——组件不持有任何传输状态。名册跟随挂载:一个 `useEffect` 在控件存活期间保持会话的 `job.list` 流打开。观测跟随可见性:另一个 `useEffect` 为展开行的 job 打开流,并在收起、卸载或弹出层关闭时关闭它。
一条 `conversation.session.panel.section` 注册渲染分栏正文;会话面板绘制其标题、提供内边距并负责滚动。所有数据经 `ctx.jobs` 到达——组件不持有任何传输状态。名册跟随挂载:一个 `useEffect` 在分栏挂载期间(即会话面板显示期间)保持会话的 `job.list` 流打开。观测跟随可见性:另一个 `useEffect` 为展开行的 job 打开流,并在收起或卸载时关闭它,包括面板隐藏时。
| 文件 | 角色 |
|---|---|
| [`src/client/JobListAction.tsx`](src/client/JobListAction.tsx) | 任务列表:分组、时长、面板 |
| [`src/client/index.ts`](src/client/index.ts) | slot 注册与词典 |
| [`src/client/JobsSection.tsx`](src/client/JobsSection.tsx) | 分栏:进行中与已结束的行、时长、停止控件、输出面板 |
| [`src/client/jobs-store.ts`](src/client/jobs-store.ts) | 按 Session 保存已清空行的 store |
| [`src/client/index.ts`](src/client/index.ts) | 会话面板分栏注册与词典 |
| [`src/client/locales.ts`](src/client/locales.ts) | `job` 命名空间文案(zh 为事实源) |
后台任务行遵循[标准菜单边缘几何](../../../docs/ui-radius.zh.md#nested-hover);带底色运行行内的控件保留紧凑圆角。
后台任务行使用[嵌套几何规则](../../../docs/ui-radius.zh.md#nested-hover)中的标准菜单项圆角;带底色运行行内的控件保留紧凑圆角。
</details>
@@ -68,6 +69,7 @@ kind: "package-reference"
- [`dsh-api-job-controller`](../../api/job-controller/README.zh.md) —— 行、面板与停止控件背后的 `job.list`、`job.follow` 流、`job.kill` Remote 与 `ctx.jobs` 服务。
- [`dsh-jobs`](../../jobs/jobs/README.zh.md) —— 拥有环与投影语义的注册表契约。
- [`dsh-client-ui-session-panel`](../ui-session-panel/README.zh.md) —— 为本分栏排序、绘制标题并负责滚动的会话面板。
- [`dsh-client-ui-primitives`](../ui-primitives/README.zh.md) —— 面板所配置的 `TerminalBlock` 表面。
-----
+5 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-client-ui-jobs",
"description": "Session-header background-job list with on-demand streaming record panels",
"description": "Session panel background-job list with on-demand streaming record panels",
"version": "0.2.2-rc.3",
"type": "module",
"main": "lib/index.js",
@@ -39,11 +39,12 @@
"@deepseek-ai/dsh-api-job-controller": "workspace:*",
"@deepseek-ai/dsh-brand": "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-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-session-panel": "workspace:*",
"@deepseek-ai/dsh-client-ui-slots": "workspace:*",
"@deepseek-ai/dsh-jobs": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
@@ -64,8 +65,8 @@
"inject": [
"@deepseek-ai/dsh-api-job-controller",
"@deepseek-ai/dsh-client-locale",
"@deepseek-ai/dsh-client-ui-conversation",
"@deepseek-ai/dsh-client-ui-primitives"
"@deepseek-ai/dsh-client-ui-primitives",
"@deepseek-ai/dsh-client-ui-session-panel"
],
"platform": "web"
}
@@ -1,502 +0,0 @@
.trigger {
display: inline-flex;
align-items: center;
gap: 4px;
min-height: 28px;
padding: 3px 2px;
border: 0;
border-radius: var(--dsw-radius-sm);
background: transparent;
color: var(--dsw-alias-label-tertiary);
font-size: 12px;
line-height: 18px;
cursor: pointer;
}
.trigger:focus-visible {
color: var(--dsw-alias-label-secondary);
}
@media (hover: hover) {
.trigger:hover {
color: var(--dsw-alias-label-secondary);
}
}
.activitySlot {
display: inline-flex;
flex: none;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
}
.trigger .compactIcon {
display: none;
}
@container (max-width: 460px) {
.trigger .compactIcon {
display: block;
}
.trigger .textModeActivity {
display: none;
}
.trigger .count {
display: none;
}
.trigger {
box-sizing: border-box;
width: 28px;
height: 28px;
padding: 0;
justify-content: center;
color: var(--dsw-alias-label-secondary);
}
.trigger .activitySlot,
.trigger .activitySlot > svg {
width: 15px;
height: 15px;
}
.trigger:focus-visible {
color: var(--dsw-alias-label-secondary);
}
.trigger:active {
background: var(--dsw-alias-interactive-bg-active);
}
@media (hover: hover) {
.trigger:hover {
color: var(--dsw-alias-label-secondary);
background: var(--dsw-alias-interactive-bg-hover);
}
}
}
/* Portaled above the right sidebar (at most 40) and below modal overlays (1000). */
.menu {
position: fixed;
z-index: 100;
box-sizing: border-box;
display: flex;
flex-direction: column;
width: 500px;
max-width: min(560px, calc(100vw - 32px));
max-height: min(480px, calc(100dvh - 140px));
overflow: hidden;
--dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);
--dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);
--dsw-elevation-stroke-color: var(--dsw-alias-border-l1);
box-shadow: var(--dsw-elevation-prominent);
position-area: none;
top: max(12px, calc(anchor(bottom) + 5px));
bottom: 12px;
left: max(12px, anchor(left));
right: 12px;
position-try-fallbacks: --dsh-jobs-window, --dsh-jobs-opposite, --dsh-jobs-wide-opposite, --dsh-jobs-tall, --dsh-jobs-viewport;
align-self: start;
justify-self: start;
height: fit-content;
min-height: 0;
margin: 0;
}
.menuBody {
display: flex;
flex-direction: column;
gap: 1px;
min-height: 0;
margin: 0;
padding: 4px;
overflow: auto;
list-style: none;
}
/* Section labels over the live rows and the settled tail. */
.sectionHeader {
display: flex;
align-items: center;
justify-content: space-between;
margin: 4px 4px 1px;
padding: 4px 0 3px;
border-top: 0.5px solid var(--dsw-alias-border-l1);
color: var(--dsw-alias-label-tertiary);
font-size: 11px;
line-height: 16px;
}
/* The leading section needs no divider above it. */
.sectionHeader:first-child {
margin-top: 0;
border-top: 0;
}
/* Fold toggle and clear action on the settled section line. */
.sectionToggle,
.sectionClear {
display: inline-flex;
gap: 3px;
align-items: center;
padding: 2px 4px;
border: 0;
border-radius: var(--dsw-radius-sm);
background: transparent;
color: var(--dsw-alias-label-tertiary);
font-size: 11px;
line-height: 16px;
cursor: pointer;
}
.sectionToggle:focus-visible,
.sectionClear:focus-visible {
background: var(--dsw-alias-fill-l1);
color: var(--dsw-alias-label-secondary);
}
@media (hover: hover) {
.sectionToggle:hover,
.sectionClear:hover {
background: var(--dsw-alias-fill-l1);
color: var(--dsw-alias-label-secondary);
}
}
.sectionChevron {
transform: rotate(-90deg);
transition: transform 120ms ease;
}
.sectionChevronOpen {
transform: none;
}
.item {
display: flex;
flex-direction: column;
}
/* Row plus its optional kill button; the row button keeps its full-width hit
area by flexing, so non-job rows render identically to before. */
.rowLine {
display: flex;
gap: 6px;
align-items: stretch;
}
/* Live rows read as filled cards so running work outranks the settled tail;
the inner padding frames the row and both trailing controls on the fill,
and the hover wash sits on the card so the controls never escape it. */
.rowLineLive {
padding: 4px 8px 4px 2px;
border-radius: var(--dsw-radius-md);
background: var(--dsw-alias-fill-l2);
}
@media (hover: hover) {
.rowLineLive:hover {
background: color-mix(in srgb, var(--dsw-alias-label-primary) 9%, transparent);
}
}
/* The kind badge shares the card fill, so it pops on the menu surface instead. */
.rowLineLive .kind {
background: var(--dsw-specific-menu);
}
.rowLine .row {
flex: 1;
min-width: 0;
}
/* The card carries the hover wash; the inner row stays transparent so the
two washes never stack, keeping keyboard focus its own visible state. */
@media (hover: hover) {
.rowLineLive .row:hover {
background: transparent;
}
}
.rowLineLive .row {
border-radius: var(--dsw-radius-sm);
}
.rowLineLive .row:focus-visible {
background: color-mix(in srgb, var(--dsw-alias-label-primary) 6%, transparent);
}
/* The expand affordance on live rows: a persistent bordered square, so the
control reads as a button before hover (it lives inside the row toggle). */
.chevronBox {
display: inline-flex;
flex: none;
align-items: center;
align-self: center;
justify-content: center;
width: 20px;
height: 20px;
border: 0.5px solid var(--dsw-alias-border-l2);
border-radius: var(--dsw-radius-sm);
background: var(--dsw-specific-menu);
}
/* Two-press kill affordance on running job rows: same persistent square. */
.stop {
display: inline-flex;
flex: none;
align-items: center;
align-self: center;
justify-content: center;
width: 20px;
height: 20px;
padding: 0;
border: 0.5px solid var(--dsw-alias-border-l2);
border-radius: var(--dsw-radius-sm);
background: var(--dsw-specific-menu);
color: var(--dsw-alias-label-secondary);
cursor: pointer;
}
.stop:focus-visible {
border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent);
color: var(--dsw-alias-state-error-primary);
}
@media (hover: hover) {
.stop:hover {
border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent);
color: var(--dsw-alias-state-error-primary);
}
}
/* The armed press widens into a labeled danger pill so the confirm step is
legible without hover; the state-error token is the one StateDot uses. */
.stopArmed,
.stopArmed:focus-visible {
gap: 4px;
width: auto;
padding: 0 7px;
border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent);
background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 12%, transparent);
color: var(--dsw-alias-state-error-primary);
}
@media (hover: hover) {
.stopArmed:hover {
gap: 4px;
width: auto;
padding: 0 7px;
border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent);
background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 12%, transparent);
color: var(--dsw-alias-state-error-primary);
}
}
.stopLabel {
font-size: 11px;
line-height: 18px;
white-space: nowrap;
}
.stopFailed {
color: var(--dsw-alias-state-error-primary);
}
.row {
display: flex;
align-items: center;
gap: 6px;
box-sizing: border-box;
width: 100%;
min-height: 28px;
padding: 4px 7px;
border: 0;
border-radius: var(--dsw-radius-md);
background: transparent;
color: var(--dsw-alias-label-primary);
font-size: 12px;
line-height: 17px;
text-align: left;
cursor: pointer;
}
.row:focus-visible {
background: var(--dsw-alias-fill-l1);
}
@media (hover: hover) {
.row:hover {
background: var(--dsw-alias-fill-l1);
}
}
/* A row with no observable output offers no interaction. */
.rowStatic {
cursor: default;
}
@media (hover: hover) {
.rowStatic:hover {
background: transparent;
}
}
.rowSettled {
color: var(--dsw-alias-label-tertiary);
}
/* Live rows align the dot with the first text line, not the row center. */
.row .rowDot {
flex: none;
}
.main {
display: flex;
flex: 1;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.primary {
display: flex;
align-items: baseline;
gap: 8px;
min-width: 0;
}
.secondary {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.kind {
flex: none;
padding: 0 5px;
border-radius: var(--dsw-radius-xs);
background: var(--dsw-alias-fill-l2);
color: var(--dsw-alias-label-secondary);
font-size: 10px;
line-height: 16px;
}
.label {
flex: 1;
min-width: 0;
overflow: hidden;
font-family: var(--dsw-font-mono);
white-space: nowrap;
text-overflow: ellipsis;
}
/* A failed task's detail is the producer's raw text, so it has no bound;
without this it widens the row past the menu instead of eliding like .label. */
.status {
flex: none;
max-width: 60%;
overflow: hidden;
color: var(--dsw-alias-label-tertiary);
font-size: 10px;
line-height: 16px;
white-space: nowrap;
text-overflow: ellipsis;
}
.duration {
flex: none;
color: var(--dsw-alias-label-tertiary);
font-size: 11px;
line-height: 18px;
font-variant-numeric: tabular-nums;
}
.chevron {
flex: none;
color: var(--dsw-alias-label-tertiary);
}
.chevronOpen {
transform: rotate(180deg);
}
.panel {
margin: 0 8px 8px;
/* Long commands and output lines wrap in full instead of ellipsizing or
scrolling sideways, and the output region scrolls within a fixed height
instead of folding its middle lines. */
--dsl-terminal-command-whitespace: pre-wrap;
--dsl-terminal-line-whitespace: pre-wrap;
--dsl-terminal-output-max-height: 288px;
}
/* The row carries the state dot, so the panel omits its own and reclaims the
dot gutter down to an ordinary content inset. The override targets the card
element itself because the gutter variable is declared on it — a value
inherited from this container would lose to that declaration. */
.panel :global([data-terminal]) {
--dsl-terminal-gutter: 12px;
}
.notice {
margin: 0 8px 6px;
color: var(--dsw-alias-label-tertiary);
font-size: 11px;
line-height: 16px;
}
.noticeError {
color: var(--dsw-alias-state-error-primary);
}
@position-try --dsh-jobs-window {
position-area: none;
top: max(12px, calc(anchor(bottom) + 5px));
bottom: 12px;
left: 12px;
right: 12px;
margin: 0;
align-self: safe start;
justify-self: safe end;
}
@position-try --dsh-jobs-opposite {
top: max(12px, var(--dsh-frame-overlay-top, 12px));
bottom: max(12px, calc(anchor(top) + 5px));
align-self: end;
}
@position-try --dsh-jobs-wide-opposite {
top: max(12px, var(--dsh-frame-overlay-top, 12px));
bottom: max(12px, calc(anchor(top) + 5px));
left: 12px;
right: 12px;
align-self: end;
justify-self: safe end;
}
@position-try --dsh-jobs-tall {
position-area: none;
top: max(12px, var(--dsh-frame-overlay-top, 12px));
bottom: 12px;
left: max(12px, anchor(left));
right: 12px;
margin: 0;
align-self: safe start;
justify-self: start;
}
@position-try --dsh-jobs-viewport {
position-area: none;
inset: max(12px, var(--dsh-frame-overlay-top, 12px)) 12px 12px;
margin: 0;
align-self: safe start;
justify-self: safe end;
}
@@ -1,639 +0,0 @@
import { useCallback, useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type PointerEvent } from 'react'
import { createPortal } from 'react-dom'
import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import {
IconChevronDownOutlineRegular, IconLayersOutlineRegular, IconStopFillRegular, MenuSurface, StateDot, TerminalBlock, Tooltip,
useDismissOnOutsidePointer,
type StateDotState, type TerminalBlockLabels,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { InjectFace, PropsLocale, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
import { NS } from './locales.ts'
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
import css from './JobListAction.module.css'
/** Registration-side business face for the job list. */
export interface JobListInjected {
hooks: {
/** Client jobs snapshot (rosters and observations) bound by the renderer as useJobs. */
jobs: {
getSnapshot(): JobsSnapshot
subscribe(listener: () => void): () => void
}
}
/**
* Keep one session's roster current while the list is mounted; returns the
* stop function. Reference-counted by the client service.
*/
watchRows: (sessionId: SessionId) => () => void
/**
* Start observing one job's live output; returns the stop function.
* Reference-counted by the client service, so panels can overlap safely.
*/
observe: (sessionId: SessionId | undefined, id: JobView['id']) => () => void
/**
* Kill one background job on the human's behalf. Resolves `true` when the
* registry admitted the request (`requested` or `already-finished`); row
* state itself converges through the jobs control frames.
*/
killJob: (sessionId: SessionId, jobId: string) => Promise<boolean>
}
/** Full props for the session-header job-list action. */
export type JobListActionProps =
PropsRuntime<'conversation.session.header.actions'>
& PropsLocale<typeof NS>
& InjectFace<JobListInjected>
/** Stable empty list so a session with no jobs keeps one array identity. */
const NO_JOBS: readonly JobView[] = []
/** Keyboard-reachable controls inside the list, in document order. */
const FOCUSABLE = 'button:not(:disabled), a[href], [tabindex]:not([tabindex="-1"])'
/** How long an armed kill waits for its confirming press before disarming. */
const KILL_ARM_MS = 3_000
/** How long a failed kill keeps its hint before the button resets. */
const KILL_FAILED_MS = 4_000
function isLive(job: JobView): boolean {
return job.status === 'running' || job.status === 'stopping'
}
/**
* Whether the row offers an output panel: every live job (its output may
* still arrive) and a settled one that left retained output behind.
*/
function isObservable(job: JobView): boolean {
return isLive(job) || job.output.total > 0
}
/** The one-line qualifier beside the status: live progress while running, the terminal reason once settled. */
function jobDetail(job: JobView): string | undefined {
return job.progress ?? job.detail
}
/** Closed-union exhaustiveness fence for the wire status set. */
/* v8 ignore next 3 -- closed-union backstop; only reached if a status is forged */
function assertNever(value: never): never {
throw new Error(`unhandled job status: ${JSON.stringify(value)}`)
}
/**
* Status marker semantics. `stopping` and `killed` share the attention color:
* both mean the work ended (or is ending) on request rather than on its own.
*/
function dotState(status: JobView['status']): StateDotState {
switch (status) {
case 'running': return 'ongoing'
case 'stopping': return 'warning'
case 'completed': return 'done'
case 'killed': return 'warning'
case 'failed': return 'error'
/* v8 ignore next -- closed wire status union */
default: return assertNever(status)
}
}
function statusLabel(status: JobView['status'], t: TranslateNS<typeof NS>): string {
switch (status) {
case 'running': return t('status.running')
case 'stopping': return t('status.stopping')
case 'completed': return t('status.completed')
case 'killed': return t('status.killed')
case 'failed': return t('status.failed')
/* v8 ignore next -- closed wire status union */
default: return assertNever(status)
}
}
/**
* Elapsed time in at most two adjacent units. A job that outlives an hour is
* already exceptional, so hours is the widest unit — beyond that the figure
* stays in hours rather than growing a day/month vocabulary no producer
* currently reaches.
*/
function formatDuration(elapsedMs: number, t: TranslateNS<typeof NS>): string {
const total = Math.max(0, Math.floor(elapsedMs / 1_000))
const seconds = total % 60
const minutes = Math.floor(total / 60) % 60
const hours = Math.floor(total / 3_600)
if (hours > 0) return t('duration.hours', { hours, minutes })
if (minutes > 0) return t('duration.minutes', { minutes, seconds })
return t('duration.seconds', { seconds })
}
/** Localized display copy for the embedded terminal panel. */
function terminalLabels(t: TranslateNS<typeof NS>): TerminalBlockLabels {
return {
commandLine: line => t('terminal.commandLine', { n: line }),
// The labels contract requires exit-fact formatters, but this panel never
// passes exit facts, so TerminalBlock never invokes them.
/* v8 ignore next */
signal: signal => t('terminal.signal', { signal }),
/* v8 ignore next */
exitCode: code => t('terminal.exitCode', { code }),
noExitCode: t('terminal.noExitCode'),
running: t('terminal.running'),
failed: t('terminal.failed'),
done: t('terminal.done'),
copy: t('terminal.copy'),
copied: t('terminal.copied'),
noOutput: t('terminal.noOutput'),
collapseAria: t('terminal.collapseAria'),
collapse: t('terminal.collapse'),
// The panel never caps lines (it scrolls), so the fold controls that
// would invoke these stay unrendered.
/* v8 ignore next */
expandAria: hidden => t('terminal.expandAria', { n: hidden }),
/* v8 ignore next */
expand: hidden => t('terminal.expand', { n: hidden }),
}
}
/**
* Live rows first in start order, then settled rows newest-first. Two rows
* that settled in the same millisecond fall back to start order, so the sort
* never depends on the host's map iteration.
*/
function ordered(jobs: readonly JobView[]): JobView[] {
return [...jobs].sort((left, right) => {
const liveLeft = isLive(left)
if (liveLeft !== isLive(right)) return liveLeft ? -1 : 1
if (liveLeft) return left.startedAt - right.startedAt
const finished = (right.finishedAt ?? right.startedAt) - (left.finishedAt ?? left.startedAt)
return finished !== 0 ? finished : left.startedAt - right.startedAt
})
}
/**
* Two-press kill affordance state: `armed` waits for the confirming second
* press (and disarms on a timer), `pending` covers the in-flight RPC until the
* row's own status flip removes the button, `failed` shows briefly after a
* rejected kill.
*/
type KillState = 'idle' | 'armed' | 'pending' | 'failed'
/** One job row plus, when observable and expanded, its live output panel. */
function JobItem({ job, view, expanded, now, onToggle, kill, t }: {
job: JobView
view: ObservedJob | undefined
expanded: boolean
/** Clock sample live rows derive their running duration from. */
now: number
onToggle: () => void
/** Present on running rows: the human-kill button state and press handler. */
kill?: { state: KillState; onPress: () => void }
t: TranslateNS<typeof NS>
}) {
const live = isLive(job)
const status = statusLabel(job.status, t)
const detail = jobDetail(job)
const observable = isObservable(job)
const labels = useMemo(() => terminalLabels(t), [t])
const elapsed = live ? now - job.startedAt : (job.finishedAt ?? job.startedAt) - job.startedAt
const duration = formatDuration(elapsed, t)
const durationCell = (
<span
className={css.duration}
title={t(live ? 'duration.title.live' : 'duration.title.done', { duration })}
>
{duration}
</span>
)
const body = live
? (
<>
<StateDot state={dotState(job.status)} className={css.rowDot} />
<span className={css.main}>
<span className={css.primary}>
<span className={css.label} title={job.label}>{job.label}</span>
</span>
<span className={css.secondary} title={detail ?? status}>
<span className={css.kind}>{job.kind}</span>
{detail !== undefined ? <span className={css.status}>{detail}</span> : null}
{durationCell}
</span>
</span>
{/* A live row is always observable: its output may still arrive. */}
<span className={css.chevronBox}>
<IconChevronDownOutlineRegular size={12} className={expanded ? `${css.chevron} ${css.chevronOpen}` : css.chevron} />
</span>
</>
)
: (
<>
<StateDot state={dotState(job.status)} className={css.rowDot} />
<span className={css.kind}>{job.kind}</span>
<span className={css.label} title={job.label}>{job.label}</span>
<span className={css.status} title={detail ?? status}>{detail ?? status}</span>
{durationCell}
{observable
? (
<span className={css.chevronBox}>
<IconChevronDownOutlineRegular size={12} className={expanded ? `${css.chevron} ${css.chevronOpen}` : css.chevron} />
</span>
)
: null}
</>
)
const killTitle = kill === undefined
? undefined
: kill.state === 'armed'
? t('kill.confirm')
: kill.state === 'failed' ? t('kill.failed') : t('kill.stop', { label: job.label })
return (
<li className={css.item}>
<div className={live ? `${css.rowLine} ${css.rowLineLive}` : css.rowLine}>
{observable
? (
<button
type="button"
className={live ? css.row : `${css.row} ${css.rowSettled}`}
aria-expanded={expanded}
aria-label={t(expanded ? 'row.collapseAria' : 'row.expandAria', { label: job.label })}
onClick={onToggle}
>
{body}
</button>
)
: (
<span className={`${css.row} ${css.rowSettled} ${css.rowStatic}`}>
{body}
</span>
)}
{kill !== undefined
? (
<button
type="button"
className={
kill.state === 'armed'
? `${css.stop} ${css.stopArmed}`
: kill.state === 'failed' ? `${css.stop} ${css.stopFailed}` : css.stop
}
data-kill-state={kill.state}
disabled={kill.state === 'pending'}
aria-label={killTitle}
title={killTitle}
onClick={kill.onPress}
>
<IconStopFillRegular size={10} />
{/* The armed press must be legible without hover: the button
widens into a labeled confirm pill instead of a tint only. */}
{kill.state === 'armed' ? <span className={css.stopLabel}>{t('kill.confirmAction')}</span> : null}
</button>
)
: null}
</div>
{expanded && view !== undefined
? (
<div className={css.panel}>
{view.gapBefore ? <div className={css.notice}>{t('output.gap')}</div> : null}
{view.error !== undefined
? <div className={`${css.notice} ${css.noticeError}`}>{t('output.error', { error: view.error })}</div>
: null}
<TerminalBlock
command={job.label}
output={view.text}
running={live}
copyText={job.label}
// The row above the panel already carries the state dot.
runStateDot={false}
// The panel scrolls its output (a stylesheet height cap) instead
// of collapsing the middle.
maxLines={Number.POSITIVE_INFINITY}
labels={labels}
/>
</div>
)
: null}
</li>
)
}
/**
* Session-header entry point for this session's background jobs. Mounting it
* keeps the session's roster stream open; it renders nothing at all until the
* session can see at least one job. Expanding an observable row (a live job,
* or a settled one with retained output) starts its observation stream, and
* collapsing (or closing the popover) stops it — output only flows while
* someone is watching. A running row carries a two-press stop button that
* requests a human kill through the job controller. Non-touch hover on a
* text-visible trigger opens after 150ms and closes after 120ms outside both
* trigger and portal. Compact triggers toggle on click; ArrowDown opens and
* pins either layout. Interacting inside also pins the menu until explicit
* dismissal; timers and the pin are local to the mounted session.
* @param props - runtime slot currency, the jobs snapshot hook, the roster,
* observation, and kill controls, and the namespace translator.
* @returns the trigger and its popover list, or null when there is nothing to show.
*/
export function JobListAction({ sessionId, useJobs, watchRows, observe, killJob, t, useAccess }: JobListActionProps) {
// The stop control follows job/kill; a reader that may list a job but not stop it sees the row only.
const mayKill = useAccess('job/kill')
const activityId = useId()
const jobs = useJobs(state => state.rows[sessionId]) ?? NO_JOBS
const observedViews = useJobs(state => state.observed)
const [menuState, setMenuState] = useState<{ sessionId: SessionId; mode: 'closed' | 'hover' | 'pinned' }>(
{ sessionId, mode: 'closed' },
)
const hoverOpenTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
const hoverCloseTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
if (menuState.sessionId !== sessionId) setMenuState({ sessionId, mode: 'closed' })
const [expandedKey, setExpandedKey] = useState<string | undefined>(undefined)
const [now, setNow] = useState(() => Date.now())
// Settled-section fold: an explicit user toggle wins; before one, the tail
// folds only while live work exists (a settled-only list opens expanded).
const [settledOpen, setSettledOpen] = useState<boolean | undefined>(undefined)
// Rows the user cleared from the settled tail (client-side hide only; the
// registry keeps its records and a later settlement reappears normally).
const [clearedKeys, setClearedKeys] = useState<ReadonlySet<string>>(() => new Set())
// One kill affordance advances at a time: arming a row disarms any other.
const [killPhase, setKillPhase] = useState<{ key: string; state: Exclude<KillState, 'idle'> } | undefined>(undefined)
const rootRef = useRef<HTMLDivElement>(null)
const triggerRef = useRef<HTMLButtonElement>(null)
const countRef = useRef<HTMLSpanElement>(null)
const menuRef = useRef<HTMLDivElement>(null)
const rows = useMemo(() => ordered(jobs), [jobs])
const liveRows = useMemo(() => rows.filter(isLive), [rows])
const settledRows = useMemo(
() => rows.filter(job => !isLive(job) && !clearedKeys.has(String(job.id))),
[rows, clearedKeys],
)
const settledExpanded = settledOpen ?? liveRows.length === 0
const visibleCount = liveRows.length + settledRows.length
const hasJobs = visibleCount > 0
const open = hasJobs && menuState.sessionId === sessionId && menuState.mode !== 'closed'
const cancelHover = useCallback((): void => {
clearTimeout(hoverOpenTimer.current)
clearTimeout(hoverCloseTimer.current)
hoverOpenTimer.current = undefined
hoverCloseTimer.current = undefined
}, [])
const changeOpen = useCallback((next: boolean): void => {
cancelHover()
if (next) setNow(Date.now())
setMenuState({ sessionId, mode: next ? 'pinned' : 'closed' })
}, [cancelHover, sessionId])
// CSS owns the compact breakpoint; read its result only for pointer gestures.
const allowsHoverOpen = (): boolean => countRef.current !== null
&& getComputedStyle(countRef.current).display !== 'none'
const hoverEnter = (event: PointerEvent<HTMLElement>): void => {
if (event.pointerType === 'touch') return
cancelHover()
if (open || !allowsHoverOpen()) return
hoverOpenTimer.current = setTimeout(() => {
hoverOpenTimer.current = undefined
if (!allowsHoverOpen()) return
setNow(Date.now())
setMenuState({ sessionId, mode: 'hover' })
}, 150)
}
const hoverLeave = (event: PointerEvent<HTMLElement>): void => {
if (event.pointerType === 'touch') return
cancelHover()
if (!open || menuState.mode === 'pinned') return
hoverCloseTimer.current = setTimeout(() => {
hoverCloseTimer.current = undefined
setMenuState({ sessionId, mode: 'closed' })
}, 120)
}
// Timers belong to this mounted session and cannot survive a disappearing trigger.
useEffect(() => cancelHover, [cancelHover, sessionId, hasJobs])
const anchorName = `--dsh-jobs-${useId().replaceAll(':', '')}`
useDismissOnOutsidePointer(rootRef, open, changeOpen, menuRef)
// Hover does not move focus; Escape must also work from the rest of the page.
useEffect(() => {
if (!open) return
const dismiss = (event: globalThis.KeyboardEvent): void => {
if (event.key !== 'Escape' || event.defaultPrevented) return
event.preventDefault()
changeOpen(false)
}
document.addEventListener('keydown', dismiss)
return () => { document.removeEventListener('keydown', dismiss) }
}, [open, changeOpen])
// The roster follows the mounted session: one stream while this control
// lives, released with it.
useEffect(() => watchRows(sessionId), [sessionId, watchRows])
// The clock only runs while an open list is showing something that moves.
useEffect(() => {
if (!open || liveRows.length === 0) return
setNow(Date.now())
const timer = setInterval(() => { setNow(Date.now()) }, 1_000)
return () => { clearInterval(timer) }
}, [open, liveRows.length])
// Observation follows visibility: the stream opens when an observable panel
// expands and closes when it collapses, unmounts, or the popover closes.
const expandedRow = open && expandedKey !== undefined
? rows.find(job => String(job.id) === expandedKey)
: undefined
const activeJob = expandedRow !== undefined && isObservable(expandedRow) ? expandedRow.id : undefined
useEffect(() => {
if (activeJob === undefined) return
return observe(sessionId, activeJob)
}, [sessionId, activeJob, observe])
// A returning roster starts closed rather than restoring an obsolete pin.
useEffect(() => {
if (!hasJobs) changeOpen(false)
}, [hasJobs, changeOpen])
// An expanded row that left the list (owner disposal) folds its panel.
useEffect(() => {
if (expandedKey !== undefined && !rows.some(job => String(job.id) === expandedKey)) {
setExpandedKey(undefined)
}
}, [rows, expandedKey])
// An armed kill disarms on a timer, and a failed one clears its hint; the
// pending phase instead waits for the RPC (or the row's own status flip).
// The cleanup clears the timer on every phase change, so a firing timer
// always describes the current phase and may reset unconditionally.
useEffect(() => {
if (killPhase === undefined || killPhase.state === 'pending') return
const timer = setTimeout(
() => { setKillPhase(undefined) },
killPhase.state === 'armed' ? KILL_ARM_MS : KILL_FAILED_MS,
)
return () => { clearTimeout(timer) }
}, [killPhase])
// A phase whose row stopped being killable (settled, stopping, removed)
// has no button to describe any more.
useEffect(() => {
if (killPhase !== undefined
&& !rows.some(job => String(job.id) === killPhase.key && job.status === 'running')) {
setKillPhase(undefined)
}
}, [rows, killPhase])
const pressKill = (job: JobView): void => {
const key = String(job.id)
if (killPhase?.key !== key || killPhase.state !== 'armed') {
setKillPhase({ key, state: 'armed' })
return
}
setKillPhase({ key, state: 'pending' })
void killJob(sessionId, key).then((ok) => {
// An admitted kill stays pending: the unary response (HTTP) and the jobs
// frames (control stream) have no cross-carrier ordering, so re-enabling
// here could offer a duplicate kill while the row still reads `running`.
// The authoritative jobs frame flips the row to `stopping`, which removes
// the button and clears the phase through the killable-set effect above.
setKillPhase(current => current?.key === key && !ok
? { key, state: 'failed' }
: current)
})
}
if (visibleCount === 0) return null
const count = liveRows.length > 0 ? liveRows.length : visibleCount
const countLabel = t(count === 1 ? 'count.idle.one' : 'count.idle.other', { count })
const clearSettled = (): void => {
setClearedKeys((current) => {
const next = new Set(current)
for (const job of settledRows) next.add(String(job.id))
return next
})
if (expandedKey !== undefined && settledRows.some(job => String(job.id) === expandedKey)) {
setExpandedKey(undefined)
}
}
// The portaled list sits at the end of the document, so Tab is bridged to
// keep the in-place order: the trigger leads into the list, and leaving
// either end of the list returns to the trigger's position in the page.
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {
const trigger = triggerRef.current
if (event.key === 'Escape') {
event.preventDefault()
changeOpen(false)
trigger?.focus()
return
}
if (!open) return
const menu = menuRef.current
/* v8 ignore next -- both refs are attached while the open list renders. */
if (event.key !== 'Tab' || trigger === null || menu === null) return
const focusable = [...menu.querySelectorAll<HTMLElement>(FOCUSABLE)]
if (event.target === trigger) {
// Every list carries a control: a live row's toggle or the settled section's buttons.
if (event.shiftKey) return
event.preventDefault()
focusable[0]?.focus()
} else if (event.shiftKey ? event.target === focusable[0] : event.target === focusable.at(-1)) {
// Shift+Tab lands on the trigger itself; Tab continues from it to the
// control that follows the trigger.
if (event.shiftKey) event.preventDefault()
trigger.focus()
}
}
const item = (job: JobView) => (
<JobItem
key={String(job.id)}
job={job}
view={isObservable(job) ? observedViews[String(job.id)] : undefined}
expanded={expandedKey === String(job.id)}
now={now}
onToggle={() => {
setExpandedKey(current => current === String(job.id) ? undefined : String(job.id))
}}
{...job.status === 'running' && mayKill
? {
kill: {
state: killPhase?.key === String(job.id) ? killPhase.state : 'idle' as const,
onPress: () => { pressKill(job) },
},
}
: {}}
t={t}
/>
)
return (
<div ref={rootRef} style={{ anchorName }} onKeyDown={onKeyDown}>
<Tooltip label={countLabel} disabled={open} delayMs={500} portal side="bottom">
<button
ref={triggerRef}
type="button"
className={css.trigger}
aria-expanded={open}
aria-label={countLabel}
aria-describedby={liveRows.length > 0 ? activityId : undefined}
onPointerEnter={hoverEnter}
onPointerLeave={hoverLeave}
onClick={() => { changeOpen(!open || (allowsHoverOpen() && menuState.mode !== 'pinned')) }}
onKeyDown={(event) => {
if (event.key !== 'ArrowDown') return
event.preventDefault()
changeOpen(true)
queueMicrotask(() => { menuRef.current?.querySelector<HTMLElement>(FOCUSABLE)?.focus() })
}}
>
<span className={css.activitySlot} aria-hidden>
<IconLayersOutlineRegular size={14} className={liveRows.length > 0 ? css.compactIcon : undefined} />
{liveRows.length > 0 && <StateDot state="ongoing" className={css.textModeActivity} />}
</span>
<span ref={countRef} className={css.count} data-job-count>{countLabel}</span>
</button>
</Tooltip>
{liveRows.length > 0 && <span id={activityId} hidden>{t('section.live')}</span>}
{open
? createPortal(
<MenuSurface
ref={menuRef}
className={css.menu}
style={{ positionAnchor: anchorName }}
onPointerEnter={hoverEnter}
onPointerLeave={hoverLeave}
onPointerDownCapture={() => { changeOpen(true) }}
onFocusCapture={() => { changeOpen(true) }}
>
<ul className={css.menuBody} aria-label={t('list.aria')}>
{liveRows.length > 0
? <li className={css.sectionHeader} aria-hidden="true">{t('section.live')}</li>
: null}
{liveRows.map(item)}
{settledRows.length > 0
? (
<li className={css.sectionHeader}>
<button
type="button"
className={css.sectionToggle}
aria-expanded={settledExpanded}
onClick={() => { setSettledOpen(!settledExpanded) }}
>
<IconChevronDownOutlineRegular size={12} className={settledExpanded ? `${css.sectionChevron} ${css.sectionChevronOpen}` : css.sectionChevron} />
{t('section.settledCount', { count: settledRows.length })}
</button>
<button type="button" className={css.sectionClear} onClick={clearSettled}>
{t('section.clear')}
</button>
</li>
)
: null}
{settledExpanded ? settledRows.map(item) : null}
</ul>
</MenuSurface>,
document.body,
)
: null}
</div>
)
}
@@ -0,0 +1,266 @@
/* The panel toggle sizes and places this dot; it names the state for assistive technology. */
.runningIndicator {
background: var(--dsw-alias-state-business-primary);
}
.visuallyHidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
/* Rows sit inside the Session panel section body, which supplies the inset and
scrolling. They share the panel's columns: the status glyph's center 14px
from the row start, text at 30px, and the chevron's center 14px from the row
end. */
.list {
display: flex;
flex-direction: column;
margin: 0;
padding: 0;
list-style: none;
}
/* Fold toggle and clear action over the settled tail. */
.sectionHeader {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 24px;
margin-top: 4px;
padding: 0 6px;
border-top: 0.5px solid var(--dsw-alias-border-l1);
}
/* The leading section needs no divider above it. */
.sectionHeader:first-child {
margin-top: 0;
border-top: 0;
}
.sectionToggle,
.sectionClear {
display: inline-flex;
align-items: center;
gap: 2px;
padding: 0;
border: 0;
background: transparent;
color: var(--dsw-alias-label-tertiary);
font: var(--dsw-font-xxs-12);
font-variant-numeric: tabular-nums;
cursor: pointer;
}
.sectionToggle:focus-visible,
.sectionClear:focus-visible {
color: var(--dsw-alias-label-secondary);
}
@media (hover: hover) {
.sectionToggle:hover,
.sectionClear:hover {
color: var(--dsw-alias-label-secondary);
}
}
.sectionChevron {
transform: rotate(-90deg);
transition: transform 120ms ease;
}
.sectionChevronOpen {
transform: none;
}
.item {
display: flex;
flex-direction: column;
}
/* One 28px line per job: the command, its duration, the stop control, and the
chevron; the kind and state show in the row's hover card. The row button's
overlay covers the whole line, so the line highlights as one row; the stop
control sits above the overlay and the chevron reads through it. */
.rowLine {
position: relative;
display: flex;
align-items: center;
gap: 8px;
min-height: 28px;
box-sizing: border-box;
padding: 4px 6px;
border-radius: var(--dsw-radius-sm);
}
@media (hover: hover) {
.rowInteractive:hover {
background: var(--dsw-alias-interactive-bg-hover);
}
}
.rowLine:has(> .row:focus-visible) {
outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
outline-offset: -2px;
}
.row {
display: flex;
flex: 1;
align-items: center;
gap: 8px;
min-width: 0;
padding: 0;
border: 0;
background: transparent;
color: var(--dsw-alias-label-primary);
font: inherit;
text-align: left;
}
button.row {
cursor: pointer;
}
button.row::after {
position: absolute;
inset: 0;
border-radius: inherit;
content: '';
}
button.row:focus-visible {
outline: none;
}
.glyph {
display: grid;
flex: none;
place-items: center;
width: 16px;
height: 20px;
}
.label {
flex: 1;
font-size: 13px;
line-height: 20px;
}
.duration {
flex: none;
color: var(--dsw-alias-label-tertiary);
font-size: 12px;
font-variant-numeric: tabular-nums;
line-height: 20px;
}
/* The trailing column; a row without output keeps it empty so the durations
stay aligned. It takes no presses: the row button's overlay below takes
them, also once the open chevron's rotation would paint it above that overlay. */
.chevron {
display: grid;
pointer-events: none;
flex: none;
align-self: center;
place-items: center;
width: 16px;
height: 20px;
color: var(--dsw-alias-label-tertiary);
}
.chevronOpen {
transform: rotate(180deg);
}
/* Two-press kill: a plain glyph like the row's other trailing icons, with a 24px
target that overhangs the 20px line, so a running row keeps its 28px. */
.stop {
position: relative;
z-index: 1;
display: inline-flex;
flex: none;
align-items: center;
align-self: center;
justify-content: center;
min-width: 24px;
height: 24px;
margin: -2px -4px;
padding: 0;
border: 0;
border-radius: var(--dsw-radius-xs);
background: transparent;
color: var(--dsw-alias-label-tertiary);
cursor: pointer;
}
.stop:focus-visible {
outline-offset: -2px;
color: var(--dsw-alias-state-error-primary);
}
@media (hover: hover) {
.stop:hover {
color: var(--dsw-alias-state-error-primary);
}
}
/* The armed press widens into a labeled danger pill so the confirm step is
legible without hover; the state-error token is the one StateDot uses. The
pill is the 20px the row's padding leaves, so arming keeps the 28px line. */
.stopArmed {
gap: 4px;
height: 20px;
margin: 0;
padding: 0 6px;
border-radius: var(--dsw-radius-sm);
background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 12%, transparent);
color: var(--dsw-alias-state-error-primary);
}
.stopLabel {
font-size: 11px;
line-height: 18px;
white-space: nowrap;
}
.stopFailed {
color: var(--dsw-alias-state-error-primary);
}
.panel {
margin: 2px 6px 6px;
/* Long commands and output lines wrap in full instead of ellipsizing or
scrolling sideways, and the output region scrolls within a fixed height
instead of folding its middle lines. */
--dsl-terminal-command-whitespace: pre-wrap;
--dsl-terminal-line-whitespace: pre-wrap;
--dsl-terminal-output-max-height: 288px;
}
/* The row carries the state dot, so the panel omits its own and reclaims the
dot gutter down to an ordinary content inset. It takes the density of a tool
call's terminal card. The overrides target the card element itself because
these variables are declared on it — a value inherited from this container
would lose to that declaration. */
.panel :global([data-terminal]) {
--dsl-terminal-gutter: 12px;
--dsl-terminal-font: var(--dsw-font-markdown-code-block-small);
--dsl-terminal-line-height: 18px;
margin: 0;
border: 0.5px solid var(--dsw-alias-border-l1);
}
.notice {
margin: 0 8px 6px;
color: var(--dsw-alias-label-tertiary);
font-size: 11px;
line-height: 16px;
}
.noticeError {
color: var(--dsw-alias-state-error-primary);
}
@@ -0,0 +1,526 @@
import { useEffect, useId, useMemo, useRef, useState } from 'react'
import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import {
HoverCard, HoverCardGroup, IconChevronDownOutlineRegular, IconStopFillRegular, MarqueeText,
StateDot, type StateDotState, TerminalBlock, type TerminalBlockLabels, Tooltip, useHoverMarquee,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { InjectFace, PropsLocale, PropsRenderFactories, PropsRuntime, PropsStore, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
import type { createJobsSectionStore, JobGroup } from './jobs-store.ts'
import { NS } from './locales.ts'
import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client'
import css from './JobsSection.module.css'
/** Registration-side business face for the background-jobs section. */
export interface JobsSectionInjected {
hooks: {
/** Client jobs snapshot (rosters and observations) bound by the renderer as useJobs. */
jobs: {
getSnapshot(): JobsSnapshot
subscribe(listener: () => void): () => void
}
}
/**
* Keep one session's roster current while the list is mounted; returns the
* stop function. Reference-counted by the client service.
*/
watchRows: (sessionId: SessionId) => () => void
/**
* Start observing one job's live output; returns the stop function.
* Reference-counted by the client service, so panels can overlap safely.
*/
observe: (sessionId: SessionId | undefined, id: JobView['id']) => () => void
/**
* Kill one background job on the human's behalf. Resolves `true` when the
* registry admitted the request (`requested` or `already-finished`); row
* state itself converges through the jobs control frames.
*/
killJob: (sessionId: SessionId, jobId: string) => Promise<boolean>
}
/** Full props for the Session panel's background-jobs section. */
export type JobsSectionProps =
PropsRuntime<'conversation.session.panel.section'>
& PropsRenderFactories
& PropsLocale<typeof NS>
& InjectFace<JobsSectionInjected>
& PropsStore<ReturnType<typeof createJobsSectionStore>>
/** Business face of the running dot on the Session panel toggle. */
export type JobsRunningIndicatorInjected = Pick<JobsSectionInjected, 'hooks' | 'watchRows'>
/** Full props of the running dot on the Session panel toggle. */
export type JobsRunningIndicatorProps =
PropsRuntime<'conversation.session.panel.indicator'>
& PropsLocale<typeof NS>
& InjectFace<JobsRunningIndicatorInjected>
/** Stable empty list so a session with no jobs keeps one array identity. */
const NO_JOBS: readonly JobView[] = []
/** Rows a group shows before its fold control holds the rest back. */
const FOLD_LIMIT = 5
/** How long an armed kill waits for its confirming press before disarming. */
const KILL_ARM_MS = 3_000
/** How long a failed kill keeps its hint before the button resets. */
const KILL_FAILED_MS = 4_000
function isLive(job: JobView): boolean {
return job.status === 'running' || job.status === 'stopping'
}
/**
* Whether the row offers an output panel: every live job (its output may
* still arrive) and a settled one that left retained output behind.
*/
function isObservable(job: JobView): boolean {
return isLive(job) || job.output.total > 0
}
/** The one-line qualifier beside the status: live progress while running, the terminal reason once settled. */
function jobDetail(job: JobView): string | undefined {
return job.progress ?? job.detail
}
/** Closed-union exhaustiveness fence for the wire status set. */
/* v8 ignore next 3 -- closed-union backstop; only reached if a status is forged */
function assertNever(value: never): never {
throw new Error(`unhandled job status: ${JSON.stringify(value)}`)
}
/**
* Status marker semantics. `stopping` and `killed` share the attention color:
* both mean the work ended (or is ending) on request rather than on its own.
* So does a job that finished with a nonzero exit code: the command reported a
* failure, while `failed` means the job itself broke.
*/
function dotState(job: JobView): StateDotState {
switch (job.status) {
case 'running': return 'ongoing'
case 'stopping': return 'warning'
case 'completed': return job.exitCode === undefined || job.exitCode === 0 ? 'done' : 'warning'
case 'killed': return 'warning'
case 'failed': return 'error'
/* v8 ignore next -- closed wire status union */
default: return assertNever(job.status)
}
}
function statusLabel(status: JobView['status'], t: TranslateNS<typeof NS>): string {
switch (status) {
case 'running': return t('status.running')
case 'stopping': return t('status.stopping')
case 'completed': return t('status.completed')
case 'killed': return t('status.killed')
case 'failed': return t('status.failed')
/* v8 ignore next -- closed wire status union */
default: return assertNever(status)
}
}
/**
* Elapsed time in at most two adjacent units. A job that outlives an hour is
* already exceptional, so hours is the widest unit — beyond that the figure
* stays in hours rather than growing a day/month vocabulary no producer
* currently reaches.
*/
function formatDuration(elapsedMs: number, t: TranslateNS<typeof NS>): string {
const total = Math.max(0, Math.floor(elapsedMs / 1_000))
const seconds = total % 60
const minutes = Math.floor(total / 60) % 60
const hours = Math.floor(total / 3_600)
if (hours > 0) return t('duration.hours', { hours, minutes })
if (minutes > 0) return t('duration.minutes', { minutes, seconds })
return t('duration.seconds', { seconds })
}
/** Localized display copy for the embedded terminal panel. */
function terminalLabels(t: TranslateNS<typeof NS>): TerminalBlockLabels {
return {
commandLine: line => t('terminal.commandLine', { n: line }),
// The labels contract requires exit-fact formatters, but this panel never
// passes exit facts, so TerminalBlock never invokes them.
/* v8 ignore next */
signal: signal => t('terminal.signal', { signal }),
/* v8 ignore next */
exitCode: code => t('terminal.exitCode', { code }),
noExitCode: t('terminal.noExitCode'),
running: t('terminal.running'),
failed: t('terminal.failed'),
done: t('terminal.done'),
copy: t('terminal.copy'),
copied: t('terminal.copied'),
noOutput: t('terminal.noOutput'),
collapseAria: t('terminal.collapseAria'),
collapse: t('terminal.collapse'),
// The panel never caps lines (it scrolls), so the fold controls that
// would invoke these stay unrendered.
/* v8 ignore next */
expandAria: hidden => t('terminal.expandAria', { n: hidden }),
/* v8 ignore next */
expand: hidden => t('terminal.expand', { n: hidden }),
}
}
/**
* Live rows first, the most recently started first, then settled rows
* newest-first, so the rows a group holds back past its limit are its oldest.
* Two rows that settled in the same millisecond fall back to start order, so
* the sort never depends on the host's map iteration.
*/
function ordered(jobs: readonly JobView[]): JobView[] {
return [...jobs].sort((left, right) => {
const liveLeft = isLive(left)
if (liveLeft !== isLive(right)) return liveLeft ? -1 : 1
if (liveLeft) return right.startedAt - left.startedAt
const finished = (right.finishedAt ?? right.startedAt) - (left.finishedAt ?? left.startedAt)
return finished !== 0 ? finished : left.startedAt - right.startedAt
})
}
/**
* Two-press kill affordance state: `armed` waits for the confirming second
* press (and disarms on a timer), `pending` covers the in-flight RPC until the
* row's own status flip removes the button, `failed` shows briefly after a
* rejected kill.
*/
type KillState = 'idle' | 'armed' | 'pending' | 'failed'
/** One job row plus, when observable and expanded, its live output panel. */
function JobItem({ job, view, expanded, now, onToggle, kill, renderFactorySlot, t }: Pick<JobsSectionProps, 'renderFactorySlot'> & {
job: JobView
view: ObservedJob | undefined
expanded: boolean
/** Clock sample live rows derive their running duration from. */
now: number
onToggle: () => void
/** Present on running rows: the human-kill button state and press handler. */
kill?: { state: KillState; onPress: () => void }
t: TranslateNS<typeof NS>
}) {
const live = isLive(job)
const status = statusLabel(job.status, t)
const detail = jobDetail(job)
const observable = isObservable(job)
const labels = useMemo(() => terminalLabels(t), [t])
const elapsed = live ? now - job.startedAt : (job.finishedAt ?? job.startedAt) - job.startedAt
const duration = formatDuration(elapsed, t)
const labelRef = useRef<HTMLSpanElement>(null)
const marquee = useHoverMarquee(labelRef)
const summaryId = useId()
// The stop control names its action in its own tooltip, so the row's hover card stays closed while the pointer is on it.
const [onStop, setOnStop] = useState(false)
const state = detail ?? status
// The row shows the command alone; the kind and state reach assistive technology here and sighted users in the hover card.
const body = (
<>
<span className={css.glyph}><StateDot state={dotState(job)} /></span>
<MarqueeText ref={labelRef} className={css.label} data-job-label="">{job.label}</MarqueeText>
<span id={summaryId} className={css.visuallyHidden}>{`${job.kind} · ${state}`}</span>
<span className={css.duration}>{duration}</span>
</>
)
// The tooltip names the action alone, since the command can run to many lines; the accessible name keeps the command
// to tell the rows' buttons apart.
const killTitle = kill?.state === 'armed' ? t('kill.confirm') : kill?.state === 'failed' ? t('kill.failed') : t('kill.stop')
const killName = kill?.state === 'armed' || kill?.state === 'failed' ? killTitle : t('kill.stopAria', { label: job.label })
return (
<li className={css.item}>
{/* The card leaves the command out: it can run to many lines, and the row's output panel shows it in full. */}
<HoverCard
grouped
disabled={onStop && kill !== undefined}
content={renderFactorySlot('conversation.session.panel.details', {
lines: [job.kind],
status: { state: dotState(job), label: state },
facts: [{ kind: 'duration', label: duration }],
})}
anchor={(
// A command its cell clips crawls into view while the pointer rests on the row.
<div
className={observable ? `${css.rowLine} ${css.rowInteractive}` : css.rowLine}
data-job-row=""
{...marquee}
>
{observable
? (
<button
type="button"
className={css.row}
aria-expanded={expanded}
aria-label={t(expanded ? 'row.collapseAria' : 'row.expandAria', { label: job.label })}
aria-describedby={summaryId}
onClick={onToggle}
>
{body}
</button>
)
: <span className={css.row}>{body}</span>}
{kill !== undefined
? (
<Tooltip label={killTitle} side="bottom" align="end" delayMs={500} portal>
<button
type="button"
className={
kill.state === 'armed'
? `${css.stop} ${css.stopArmed}`
: kill.state === 'failed' ? `${css.stop} ${css.stopFailed}` : css.stop
}
data-kill-state={kill.state}
disabled={kill.state === 'pending'}
aria-label={killName}
onPointerEnter={() => { setOnStop(true) }}
onPointerLeave={() => { setOnStop(false) }}
onClick={kill.onPress}
>
<IconStopFillRegular size={12} />
{/* The armed press must be legible without hover: the button
widens into a labeled confirm pill instead of a tint only. */}
{kill.state === 'armed' ? <span className={css.stopLabel}>{t('kill.confirmAction')}</span> : null}
</button>
</Tooltip>
)
: null}
{/* The row button's overlay takes presses here too; a row without output keeps the column empty. */}
<span className={css.chevron} aria-hidden="true">
{observable ? <IconChevronDownOutlineRegular size={14} className={expanded ? css.chevronOpen : undefined} /> : null}
</span>
</div>
)}
/>
{expanded && view !== undefined
? (
<div className={css.panel}>
{view.gapBefore ? <div className={css.notice}>{t('output.gap')}</div> : null}
{view.error !== undefined
? <div className={`${css.notice} ${css.noticeError}`}>{t('output.error', { error: view.error })}</div>
: null}
<TerminalBlock
command={job.label}
output={view.text}
running={live}
copyText={job.label}
// The row above the panel already carries the state dot.
runStateDot={false}
// The panel scrolls its output (a stylesheet height cap) instead
// of collapsing the middle.
maxLines={Number.POSITIVE_INFINITY}
labels={labels}
/>
</div>
)
: null}
</li>
)
}
/**
* Session panel section for this session's background jobs. Mounting it keeps
* the session's roster stream open; it renders nothing until the session can
* see at least one job, so the panel hides the section with its title. Live
* rows come first; settled rows fold under a count that expands and clears
* client-side. Each of the two groups shows five rows and then a fold control
* that shows the rest, once that holds back two rows or more; the choice is
* kept per Session. Expanding an observable row (a live job, or a settled one
* with retained output) starts its observation stream, and collapsing it or
* folding it out of the list stops it — output only flows while someone is
* watching. A running row carries a two-press stop button that requests a
* human kill through the job controller.
* @param props - runtime slot currency, the jobs snapshot hook, the roster,
* observation, and kill controls, the fold store, and the namespace translator.
* @returns the job list, or null when there is nothing to show.
*/
export function JobsSection({
sessionId, useJobs, watchRows, observe, killJob, useStore, actions, renderFactorySlot, t, useAccess,
}: JobsSectionProps) {
// The stop control follows job/kill; a reader that may list a job but not stop it sees the row only.
const mayKill = useAccess('job/kill')
const jobs = useJobs(state => state.rows[sessionId]) ?? NO_JOBS
const observedViews = useJobs(state => state.observed)
const [expandedKey, setExpandedKey] = useState<string | undefined>(undefined)
const [now, setNow] = useState(() => Date.now())
// Settled-section fold: the user's choice, kept per Session, wins; before one,
// the tail folds only while live work exists (a settled-only list opens expanded).
const settledOpen = useStore(state => state.settledOpen)
// Rows the user cleared from the settled tail (client-side hide only; the
// registry keeps its records and a later settlement reappears normally).
const cleared = useStore(state => state.cleared)
const unfolded = useStore(state => state.unfolded)
// One kill affordance advances at a time: arming a row disarms any other.
const [killPhase, setKillPhase] = useState<{ key: string; state: Exclude<KillState, 'idle'> } | undefined>(undefined)
const rows = useMemo(() => ordered(jobs), [jobs])
const liveRows = useMemo(() => rows.filter(isLive), [rows])
const settledRows = useMemo(
() => rows.filter(job => !isLive(job) && cleared[String(job.id)] !== true),
[rows, cleared],
)
const settledExpanded = settledOpen ?? liveRows.length === 0
// Folding holds back two rows or more, since the fold control takes a row itself.
const liveFoldable = liveRows.length > FOLD_LIMIT + 1
const shownLive = liveFoldable && !unfolded.live ? liveRows.slice(0, FOLD_LIMIT) : liveRows
const settledFoldable = settledRows.length > FOLD_LIMIT + 1
const openSettled = settledExpanded ? settledRows : NO_JOBS
const shownSettled = settledFoldable && !unfolded.settled ? openSettled.slice(0, FOLD_LIMIT) : openSettled
// The roster follows the mounted section: one stream while it lives, released with it.
useEffect(() => watchRows(sessionId), [sessionId, watchRows])
// The clock only runs while the list shows something that moves.
useEffect(() => {
if (liveRows.length === 0) return
setNow(Date.now())
const timer = setInterval(() => { setNow(Date.now()) }, 1_000)
return () => { clearInterval(timer) }
}, [liveRows.length])
// Observation follows visibility: the stream opens when an observable panel
// expands and closes when it collapses, its row folds out of the list, or
// the section unmounts.
const expandedRow = expandedKey === undefined
? undefined
: [...shownLive, ...shownSettled].find(job => String(job.id) === expandedKey)
const activeJob = expandedRow !== undefined && isObservable(expandedRow) ? expandedRow.id : undefined
useEffect(() => {
if (activeJob === undefined) return
return observe(sessionId, activeJob)
}, [sessionId, activeJob, observe])
// An armed kill disarms on a timer, and a failed one clears its hint; the
// pending phase instead waits for the RPC (or the row's own status flip).
// The cleanup clears the timer on every phase change, so a firing timer
// always describes the current phase and may reset unconditionally.
useEffect(() => {
if (killPhase === undefined || killPhase.state === 'pending') return
const timer = setTimeout(
() => { setKillPhase(undefined) },
killPhase.state === 'armed' ? KILL_ARM_MS : KILL_FAILED_MS,
)
return () => { clearTimeout(timer) }
}, [killPhase])
// A phase whose row stopped being killable (settled, stopping, removed)
// has no button to describe any more.
const killable = killPhase !== undefined
&& rows.some(job => String(job.id) === killPhase.key && job.status === 'running')
if (killPhase !== undefined && !killable) setKillPhase(undefined)
const pressKill = (job: JobView): void => {
const key = String(job.id)
if (killPhase?.key !== key || killPhase.state !== 'armed') {
setKillPhase({ key, state: 'armed' })
return
}
setKillPhase({ key, state: 'pending' })
void killJob(sessionId, key).then((ok) => {
// An admitted kill stays pending: the unary response (HTTP) and the jobs
// frames (control stream) have no cross-carrier ordering, so re-enabling
// here could offer a duplicate kill while the row still reads `running`.
// The authoritative jobs frame flips the row to `stopping`, which removes
// the button and clears the phase above.
setKillPhase(current => current?.key === key && !ok
? { key, state: 'failed' }
: current)
})
}
if (liveRows.length + settledRows.length === 0) return null
const clearSettled = (): void => {
actions.cleared(settledRows.map(job => String(job.id)))
if (expandedKey !== undefined && settledRows.some(job => String(job.id) === expandedKey)) {
setExpandedKey(undefined)
}
}
const item = (job: JobView) => (
<JobItem
key={String(job.id)}
job={job}
view={isObservable(job) ? observedViews[String(job.id)] : undefined}
expanded={expandedKey === String(job.id)}
now={now}
onToggle={() => {
setExpandedKey(current => current === String(job.id) ? undefined : String(job.id))
}}
renderFactorySlot={renderFactorySlot}
{...job.status === 'running' && mayKill
? {
kill: {
state: killPhase?.key === String(job.id) ? killPhase.state : 'idle' as const,
onPress: () => { pressKill(job) },
},
}
: {}}
t={t}
/>
)
/** The fold control of one group, as the group's last row. */
const fold = (group: JobGroup, hidden: number) => {
const label = unfolded[group] ? t('fold.less') : t(`${group}.more`, { count: hidden })
return (
<li key={`fold-${group}`} className={css.item}>
{renderFactorySlot('conversation.session.panel.fold', {
expanded: unfolded[group],
label,
name: t(`${group}.foldName`, { label }),
onToggle: () => { actions.unfoldedSet(group, !unfolded[group]) },
})}
</li>
)
}
return (
// Moving between rows swaps their hover cards without another dwell.
<HoverCardGroup>
{/* The section's heading names the region; a list name would repeat it. */}
<ul className={css.list} data-jobs-section="">
{shownLive.map(item)}
{liveFoldable ? fold('live', liveRows.length - FOLD_LIMIT) : null}
{settledRows.length > 0
? (
<li className={css.sectionHeader}>
<button
type="button"
className={css.sectionToggle}
aria-expanded={settledExpanded}
onClick={() => { actions.settledOpened(!settledExpanded) }}
>
{t('section.settledCount', { count: settledRows.length })}
<IconChevronDownOutlineRegular size={14} className={settledExpanded ? `${css.sectionChevron} ${css.sectionChevronOpen}` : css.sectionChevron} />
</button>
<button type="button" className={css.sectionClear} onClick={clearSettled}>
{t('section.clear')}
</button>
</li>
)
: null}
{shownSettled.map(item)}
{settledExpanded && settledFoldable ? fold('settled', settledRows.length - FOLD_LIMIT) : null}
</ul>
</HoverCardGroup>
)
}
/**
* Show on the panel toggle that the Session's background jobs run while the
* panel does not show them. The toggle stays mounted while the section does
* not, so this keeps the Session's roster stream open itself; the client
* service counts its watchers.
* @param props - Session values, the jobs snapshot hook, the roster control, whether the panel shows, and copy.
* @returns the dot with its name for assistive technology, or null with nothing to report.
*/
export function JobsRunningIndicator({ sessionId, panelShown, useJobs, watchRows, t }: JobsRunningIndicatorProps) {
const running = useJobs(state => (state.rows[sessionId] ?? NO_JOBS).filter(isLive).length)
useEffect(() => watchRows(sessionId), [sessionId, watchRows])
if (panelShown || running === 0) return null
return (
<span className={css.runningIndicator} data-jobs-running="">
<span className={css.visuallyHidden}>{t('indicator.running', { count: running })}</span>
</span>
)
}
+31 -15
View File
@@ -1,17 +1,19 @@
/**
* Background-job plugin, browser half: contributes one session-header action
* that renders this session's jobs. Job rows, per-row observation streams,
* and the human kill all go through the `jobs` client service; this plugin
* holds no transport state of its own.
* Background-job plugin, browser half: contributes the Session panel's
* background-jobs section. Job rows, per-row observation streams, and the
* human kill all go through the `jobs` client service; this plugin holds no
* transport state of its own.
*/
import type { Context as ClientContext } from '@deepseek-ai/cordis'
import type { JobId } from '@deepseek-ai/dsh-jobs/types'
import { JobListAction } from './JobListAction.tsx'
import type { JobListInjected } from './JobListAction.tsx'
import { JobsRunningIndicator, JobsSection } from './JobsSection.tsx'
import type { JobsRunningIndicatorInjected, JobsSectionInjected } from './JobsSection.tsx'
import { createJobsSectionStore } from './jobs-store.ts'
import type {} from '@deepseek-ai/dsh-api-job-controller/client'
import type {} from '@deepseek-ai/dsh-client-locale/client'
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
import type {} from '@deepseek-ai/dsh-client-ui-session/client'
import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client'
import { en, ja, es, fr, de, ru, pt, NS, zh, type JobKey } from './locales.ts'
declare module '@deepseek-ai/dsh-client-ui-slots' {
@@ -21,26 +23,29 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
}
}
export type { JobListActionProps, JobListInjected } from './JobListAction.tsx'
export type { JobsRunningIndicatorInjected, JobsRunningIndicatorProps, JobsSectionProps, JobsSectionInjected } from './JobsSection.tsx'
/** Required services: the jobs rosters, observations, and kill, the slot registry, and dictionaries. */
export const inject = ['jobs', 'slots', 'locale']
/**
* Client plugin body: register the dictionaries and the header action.
* Client plugin body: register the dictionaries, the Session panel section, and its running dot on the panel toggle.
* @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-jobs: dictionaries')
const t = ctx.locale.bind(NS)
ctx.slots.inject(
'conversation.session.header.actions',
'conversation.session.panel.section',
() => ctx.slots.register({
name: 'conversation.session.header.actions',
id: 'job-list',
// Background work follows the preset label in the header actions band.
order: 20,
name: 'conversation.session.panel.section',
id: 'background-jobs',
// After change requests (100) and subagents (200).
order: 300,
label: () => t('list.aria'),
locale: NS,
inject: (): JobListInjected => ({
store: createJobsSectionStore(),
inject: (): JobsSectionInjected => ({
hooks: { jobs: ctx.jobs.state },
watchRows: sessionId => ctx.jobs.watchRows(sessionId),
observe: (sessionId, id) => ctx.jobs.observe(sessionId, id),
@@ -48,6 +53,17 @@ export function apply(ctx: ClientContext): void {
// roster stream delivered, so the wire boundary stamps it back here.
killJob: async (sessionId, jobId) => (await ctx.jobs.kill(sessionId, jobId as JobId)).ok,
}),
}, JobListAction),
}, JobsSection),
)
ctx.slots.inject('conversation.session.panel.indicator', () => ctx.slots.register({
name: 'conversation.session.panel.indicator',
id: 'background-jobs.running',
// Below an attention mark, which paints above running dots.
order: 20,
locale: NS,
inject: (): JobsRunningIndicatorInjected => ({
hooks: { jobs: ctx.jobs.state },
watchRows: sessionId => ctx.jobs.watchRows(sessionId),
}),
}, JobsRunningIndicator))
}
@@ -0,0 +1,68 @@
/**
* Settled rows the user cleared from the background-jobs section, whether the
* user opened or folded the settled rows, and which of the section's two
* groups the user unfolded past their row limit. The registration declares it
* as an exclusive store, so each Session keeps its own while its scope is
* retained, across hiding and showing the panel.
*/
import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store'
/** A group of the section's rows: the live ones, or the settled ones under their fold. */
export type JobGroup = 'live' | 'settled'
/** Cleared row keys and the folds of one Session. */
export interface JobsSectionState {
/** Keys of the settled rows the user cleared. */
cleared: Record<string, true>
/** Whether the user opened (true) or folded (false) the settled rows; null until the user chooses. */
settledOpen: boolean | null
/** Whether each group shows every row instead of holding back the rows past its limit. */
unfolded: Record<JobGroup, boolean>
}
/** The jobs section store's write set. */
type JobsSectionActions = {
cleared: (draft: JobsSectionState, keys: readonly string[]) => void
settledOpened: (draft: JobsSectionState, open: boolean) => void
unfoldedSet: (draft: JobsSectionState, group: JobGroup, unfolded: boolean) => void
}
/**
* Declare the jobs section's store.
* @returns the store handle to declare on the registration.
*/
export function createJobsSectionStore(): EngineStoreHandle<JobsSectionState, JobsSectionActions> {
return defineStore({
init: (): JobsSectionState => ({ cleared: {}, settledOpen: null, unfolded: { live: false, settled: false } }),
actions: {
/**
* Hide settled rows from the section; the registry keeps their records.
* The settled group folds to its limit again for the rows that settle next.
* @param d - draft state.
* @param keys - row keys to hide.
*/
cleared: (d, keys: readonly string[]) => {
for (const key of keys) d.cleared[key] = true
d.unfolded.settled = false
},
/**
* Record the user's choice to open or fold the settled rows.
* @param d - draft state.
* @param open - whether the settled rows are now open.
*/
settledOpened: (d, open: boolean) => {
d.settledOpen = open
},
/**
* Record the user's choice to show every row of a group or fold it to its limit again.
* @param d - draft state.
* @param group - the group the choice is about.
* @param unfolded - whether the group now shows every row.
*/
unfoldedSet: (d, group: JobGroup, unfolded: boolean) => {
d.unfolded[group] = unfolded
},
},
})
}
+64 -48
View File
@@ -5,15 +5,19 @@ export const NS = 'job'
/** Simplified Chinese dictionary (the key-set source of truth). */
export const zh = {
'count.idle.one': '{count} 个后台任务',
'count.idle.other': '{count} 个后台任务',
'list.aria': '后台任务',
'section.live': '进行中',
'indicator.running': '{count} 个后台任务运行中',
'section.settledCount': '已结束 {count}',
'section.clear': '清空',
'live.more': '显示其余 {count} 个运行中',
'live.foldName': '{label}(运行中的后台任务)',
'settled.more': '显示其余 {count} 个已结束',
'settled.foldName': '{label}(已结束的后台任务)',
'fold.less': '收起',
'row.expandAria': '展开 {label} 的实时输出',
'row.collapseAria': '收起 {label} 的实时输出',
'kill.stop': '停止任务 {label}',
'kill.stop': '停止任务',
'kill.stopAria': '停止任务 {label}',
'kill.confirm': '再次点击确认停止',
'kill.confirmAction': '确认停止',
'kill.failed': '停止失败',
@@ -25,8 +29,6 @@ export const zh = {
'duration.seconds': '{seconds}秒',
'duration.minutes': '{minutes}分{seconds}秒',
'duration.hours': '{hours}小时{minutes}分',
'duration.title.live': '已运行 {duration}',
'duration.title.done': '耗时 {duration}',
'output.gap': '……较早的输出已丢弃……',
'output.error': '实时输出流中断:{error}',
'terminal.signal': '信号 {signal}',
@@ -47,15 +49,19 @@ export const zh = {
/** English dictionary, key-identical to the Chinese source of truth. */
export const en: Record<JobKey, string> = {
'count.idle.one': '{count} background job',
'count.idle.other': '{count} background jobs',
'list.aria': 'Background jobs',
'section.live': 'Running',
'indicator.running': 'Background jobs running: {count}',
'section.settledCount': 'Finished {count}',
'section.clear': 'Clear',
'live.more': 'Show {count} more running',
'live.foldName': '{label} (running background jobs)',
'settled.more': 'Show {count} more finished',
'settled.foldName': '{label} (finished background jobs)',
'fold.less': 'Show less',
'row.expandAria': 'Show live output of {label}',
'row.collapseAria': 'Hide live output of {label}',
'kill.stop': 'Stop task {label}',
'kill.stop': 'Stop task',
'kill.stopAria': 'Stop task {label}',
'kill.confirm': 'Click again to confirm',
'kill.confirmAction': 'Confirm stop',
'kill.failed': 'Stop failed',
@@ -67,8 +73,6 @@ export const en: Record<JobKey, string> = {
'duration.seconds': '{seconds}s',
'duration.minutes': '{minutes}m {seconds}s',
'duration.hours': '{hours}h {minutes}m',
'duration.title.live': 'Running for {duration}',
'duration.title.done': 'Took {duration}',
'output.gap': '… earlier output dropped …',
'output.error': 'live output stream interrupted: {error}',
'terminal.signal': 'signal {signal}',
@@ -92,15 +96,19 @@ export type JobKey = keyof typeof zh
/** Japanese copy, checked against the English keys. */
export const ja = {
'count.idle.one': 'バックグラウンドジョブ {count} 件',
'count.idle.other': 'バックグラウンドジョブ {count} 件',
'list.aria': 'バックグラウンドジョブ',
'section.live': '実行中',
'indicator.running': '実行中のバックグラウンドジョブ: {count}',
'section.settledCount': '完了 {count} 件',
'section.clear': 'クリア',
'live.more': '実行中の残り{count}件を表示',
'live.foldName': '{label}(実行中のバックグラウンドジョブ)',
'settled.more': '完了した残り{count}件を表示',
'settled.foldName': '{label}(完了したバックグラウンドジョブ)',
'fold.less': '折りたたむ',
'row.expandAria': '{label} のライブ出力を表示',
'row.collapseAria': '{label} のライブ出力を非表示',
'kill.stop': 'タスク {label} を停止',
'kill.stop': 'タスクを停止',
'kill.stopAria': 'タスク {label} を停止',
'kill.confirm': 'もう一度クリックして確定',
'kill.confirmAction': '停止を確定',
'kill.failed': '停止に失敗しました',
@@ -112,8 +120,6 @@ export const ja = {
'duration.seconds': '{seconds}秒',
'duration.minutes': '{minutes}分 {seconds}秒',
'duration.hours': '{hours}時間 {minutes}分',
'duration.title.live': '実行時間 {duration}',
'duration.title.done': '所要時間 {duration}',
'output.gap': '…以前の出力は破棄されました…',
'output.error': 'ライブ出力ストリームが中断されました: {error}',
'terminal.signal': 'シグナル {signal}',
@@ -134,15 +140,19 @@ export const ja = {
/** Spanish dictionary, checked against the English keys. */
export const es = {
'count.idle.one': 'Tareas en segundo plano: {count}',
'count.idle.other': 'Tareas en segundo plano: {count}',
'list.aria': 'Trabajos en segundo plano',
'section.live': 'corriendo',
'indicator.running': 'Trabajos en segundo plano en ejecución: {count}',
'section.settledCount': 'Terminado {count}',
'section.clear': 'Borrar',
'live.more': 'Mostrar {count} más en ejecución',
'live.foldName': '{label} (trabajos en segundo plano en ejecución)',
'settled.more': 'Mostrar {count} más terminados',
'settled.foldName': '{label} (trabajos en segundo plano terminados)',
'fold.less': 'Mostrar menos',
'row.expandAria': 'Mostrar salida en vivo de {label}',
'row.collapseAria': 'Ocultar salida en vivo de {label}',
'kill.stop': 'Detener tarea {label}',
'kill.stop': 'Detener tarea',
'kill.stopAria': 'Detener tarea {label}',
'kill.confirm': 'Haga clic nuevamente para confirmar',
'kill.confirmAction': 'Confirmar parada',
'kill.failed': 'Detener falló',
@@ -154,8 +164,6 @@ export const es = {
'duration.seconds': '{seconds}s',
'duration.minutes': '{minutes}m {seconds}s',
'duration.hours': '{hours}h {minutes}m',
'duration.title.live': 'Corriendo para {duration}',
'duration.title.done': 'Tomó {duration}',
'output.gap': '… la producción anterior cayó…',
'output.error': 'transmisión de salida en vivo interrumpida: {error}',
'terminal.signal': 'señal {signal}',
@@ -176,15 +184,19 @@ export const es = {
/** French dictionary, checked against the English keys. */
export const fr = {
'count.idle.one': 'Tâches en arrière-plan : {count}',
'count.idle.other': 'Tâches en arrière-plan : {count}',
'list.aria': 'Travaux en arrière-plan',
'section.live': 'Courir',
'indicator.running': 'Travaux en arrière-plan en cours : {count}',
'section.settledCount': 'Terminé {count}',
'section.clear': 'Effacer',
'live.more': 'Afficher {count} de plus en cours',
'live.foldName': '{label} (travaux en arrière-plan en cours)',
'settled.more': 'Afficher {count} de plus terminés',
'settled.foldName': '{label} (travaux en arrière-plan terminés)',
'fold.less': 'Afficher moins',
'row.expandAria': 'Afficher la sortie en direct de {label}',
'row.collapseAria': 'Masquer la sortie en direct de {label}',
'kill.stop': 'Arrêter la tâche {label}',
'kill.stop': 'Arrêter la tâche',
'kill.stopAria': 'Arrêter la tâche {label}',
'kill.confirm': 'Cliquez à nouveau pour confirmer',
'kill.confirmAction': "Confirmer l'arrêt",
'kill.failed': "L'arrêt a échoué",
@@ -196,8 +208,6 @@ export const fr = {
'duration.seconds': '{seconds}s',
'duration.minutes': '{minutes}m {seconds}s',
'duration.hours': '{hours}h {minutes}m',
'duration.title.live': 'Courir pour {duration}',
'duration.title.done': 'A pris {duration}',
'output.gap': '… la production antérieure a chuté…',
'output.error': 'flux de sortie en direct interrompu : {error}',
'terminal.signal': 'signal {signal}',
@@ -218,15 +228,19 @@ export const fr = {
/** German dictionary, checked against the English keys. */
export const de = {
'count.idle.one': 'Hintergrundaufgaben: {count}',
'count.idle.other': 'Hintergrundaufgaben: {count}',
'list.aria': 'Hintergrundjobs',
'section.live': 'Laufen',
'indicator.running': 'Laufende Hintergrundjobs: {count}',
'section.settledCount': 'Fertig {count}',
'section.clear': 'Klar',
'live.more': '{count} weitere laufende anzeigen',
'live.foldName': '{label} (laufende Hintergrundjobs)',
'settled.more': '{count} weitere beendete anzeigen',
'settled.foldName': '{label} (beendete Hintergrundjobs)',
'fold.less': 'Weniger anzeigen',
'row.expandAria': 'Live-Ausgabe von {label} anzeigen',
'row.collapseAria': 'Live-Ausgabe von {label} ausblenden',
'kill.stop': 'Stoppen Sie die Aufgabe {label}',
'kill.stop': 'Aufgabe stoppen',
'kill.stopAria': 'Stoppen Sie die Aufgabe {label}',
'kill.confirm': 'Klicken Sie zur Bestätigung erneut',
'kill.confirmAction': 'Stopp bestätigen',
'kill.failed': 'Stoppen ist fehlgeschlagen',
@@ -238,8 +252,6 @@ export const de = {
'duration.seconds': '{seconds}s',
'duration.minutes': '{minutes}m {seconds}s',
'duration.hours': '{hours}h {minutes}m',
'duration.title.live': 'Laufen für {duration}',
'duration.title.done': 'Nahm {duration}',
'output.gap': '… frühere Produktion gesunken …',
'output.error': 'Live-Ausgabestream unterbrochen: {error}',
'terminal.signal': 'Signal {signal}',
@@ -260,15 +272,19 @@ export const de = {
/** Russian dictionary, checked against the English keys. */
export const ru = {
'count.idle.one': 'Фоновые задачи: {count}',
'count.idle.other': 'Фоновые задачи: {count}',
'list.aria': 'Фоновые задания',
'section.live': 'Бег',
'indicator.running': 'Выполняется фоновых заданий: {count}',
'section.settledCount': 'Закончено {count}',
'section.clear': 'Очистить',
'live.more': 'Показать ещё {count} выполняющихся',
'live.foldName': '{label} (выполняющиеся фоновые задания)',
'settled.more': 'Показать ещё {count} завершённых',
'settled.foldName': '{label} (завершённые фоновые задания)',
'fold.less': 'Свернуть',
'row.expandAria': 'Показать живой вывод {label}',
'row.collapseAria': 'Скрыть прямой вывод {label}',
'kill.stop': 'Остановить задачу {label}',
'kill.stop': 'Остановить задачу',
'kill.stopAria': 'Остановить задачу {label}',
'kill.confirm': 'Нажмите еще раз, чтобы подтвердить',
'kill.confirmAction': 'Подтвердить остановку',
'kill.failed': 'Остановить не удалось',
@@ -280,8 +296,6 @@ export const ru = {
'duration.seconds': '{seconds}s',
'duration.minutes': '{minutes}m {seconds}s',
'duration.hours': '{hours}h {minutes}m',
'duration.title.live': 'Бегу за {duration}',
'duration.title.done': 'Взял {duration}',
'output.gap': '… ранее объемы производства упали …',
'output.error': 'поток вывода в реальном времени прерван: {error}',
'terminal.signal': 'сигнал {signal}',
@@ -302,15 +316,19 @@ export const ru = {
/** Portuguese dictionary, checked against the English keys. */
export const pt = {
'count.idle.one': 'Tarefas em segundo plano: {count}',
'count.idle.other': 'Tarefas em segundo plano: {count}',
'list.aria': 'Trabalhos em segundo plano',
'section.live': 'Correndo',
'indicator.running': 'Trabalhos em segundo plano em execução: {count}',
'section.settledCount': 'Concluído {count}',
'section.clear': 'Limpar',
'live.more': 'Mostrar mais {count} em execução',
'live.foldName': '{label} (trabalhos em segundo plano em execução)',
'settled.more': 'Mostrar mais {count} concluídos',
'settled.foldName': '{label} (trabalhos em segundo plano concluídos)',
'fold.less': 'Mostrar menos',
'row.expandAria': 'Mostrar saída ao vivo de {label}',
'row.collapseAria': 'Ocultar saída ao vivo de {label}',
'kill.stop': 'Parar tarefa {label}',
'kill.stop': 'Parar tarefa',
'kill.stopAria': 'Parar tarefa {label}',
'kill.confirm': 'Clique novamente para confirmar',
'kill.confirmAction': 'Confirmar parada',
'kill.failed': 'Falha na parada',
@@ -322,8 +340,6 @@ export const pt = {
'duration.seconds': '{seconds}s',
'duration.minutes': '{minutes}m {seconds}s',
'duration.hours': '{hours}h {minutes}m',
'duration.title.live': 'Correndo por {duration}',
'duration.title.done': 'Levou {duration}',
'output.gap': '… a produção anterior caiu…',
'output.error': 'transmissão ao vivo interrompida: {error}',
'terminal.signal': 'sinal {signal}',
@@ -10,17 +10,18 @@ import { brandString } from '@deepseek-ai/dsh-brand'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { describe, expect, it } from 'vitest'
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots'
import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime'
import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client'
import { apply, inject } from '../src/client/index.ts'
import type { JobListInjected } from '../src/client/JobListAction.tsx'
import type { JobsRunningIndicatorInjected, JobsSectionInjected } from '../src/client/JobsSection.tsx'
import { apply as applyNode } from '../src/index.ts'
import { en, NS, zh } from '../src/client/locales.ts'
/** Slot ledger reader: entry ids currently registered in the header list. */
function headerEntryIds(ctx: Context): (string | undefined)[] {
/** Slot ledger reader: entry ids currently registered in the Session panel section list. */
function sectionEntryIds(ctx: Context): (string | undefined)[] {
return ctx.slots
.entries('conversation.session.header.actions')
.entries('conversation.session.panel.section')
.map(entry => entry.options.id)
}
@@ -40,7 +41,8 @@ async function bench(): Promise<{ ctx: Context; fiber: ReturnType<Context['plugi
ctx.slots.register({
name: 'root',
children: {
'conversation.session.header.actions': { kind: 'list', scope: 'session' },
'conversation.session.panel.section': { kind: 'list', scope: 'session' },
'conversation.session.panel.indicator': { kind: 'list', scope: 'session' },
},
} as never, () => null)
ctx.provide('jobs', {
@@ -81,10 +83,10 @@ describe('ui-jobs browser half', () => {
it('exposes the jobs source and the roster, observation, and kill controls through the inject face', async () => {
const { ctx } = await bench()
const entry = ctx.slots
.entries('conversation.session.header.actions')
.find(candidate => candidate.options.id === 'job-list')
const inject = entry?.inject as (() => JobListInjected) | undefined
if (inject === undefined) throw new Error('job-list entry registered no inject face')
.entries('conversation.session.panel.section')
.find(candidate => candidate.options.id === 'background-jobs')
const inject = entry?.inject as (() => JobsSectionInjected) | undefined
if (inject === undefined) throw new Error('background-jobs entry registered no inject face')
const face = inject()
expect(face.hooks.jobs).toBeDefined()
const release = face.watchRows(brandString<SessionId>('session'))
@@ -103,11 +105,20 @@ describe('ui-jobs browser half', () => {
expect(kills).toEqual([['sess-live', 'bash-3'], ['sess-live', 'bash-4']])
})
it('registers the header action, and fiber teardown removes it (HMR safety)', async () => {
it('registers the Session panel section, and fiber teardown removes it (HMR safety)', async () => {
const { ctx, fiber } = await bench()
expect(headerEntryIds(ctx)).toContain('job-list')
expect(sectionEntryIds(ctx)).toContain('background-jobs')
const entry = ctx.slots.entries('conversation.session.panel.section').find(candidate => candidate.options.id === 'background-jobs')
expect(entry?.options.order).toBe(300)
expect(resolveSlotLabel(entry?.options.label)).toBe(zh['list.aria'])
const dot = ctx.slots.entries('conversation.session.panel.indicator')[0]
expect(dot).toMatchObject({ options: { id: 'background-jobs.running', order: 20 } })
const face = dot?.inject as (() => JobsRunningIndicatorInjected) | undefined
face?.().watchRows('dot-session' as SessionId)()
expect(watched).toContain('dot-session')
await fiber.dispose()
expect(headerEntryIds(ctx)).not.toContain('job-list')
expect(sectionEntryIds(ctx)).not.toContain('background-jobs')
expect(ctx.slots.entries('conversation.session.panel.indicator')).toHaveLength(0)
})
it('registers both dictionaries under its own namespace and releases them with the fiber', async () => {
@@ -1,960 +0,0 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { JobListAction, type JobListActionProps } from '../src/client/JobListAction.tsx'
import { zh, en, ja, es, fr, de, ru, pt } from '../src/client/locales.ts'
beforeEach(() => {
class TooltipObserver implements ResizeObserver {
constructor(private readonly callback: ResizeObserverCallback) {}
observe(target: Element): void {
const size = { inlineSize: 160, blockSize: 30 }
this.callback([{
target, borderBoxSize: [size], contentBoxSize: [size], devicePixelContentBoxSize: [size], contentRect: new DOMRect(),
}], this)
}
unobserve(): void {}
disconnect(): void {}
}
vi.stubGlobal('ResizeObserver', TooltipObserver)
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })))
})
beforeEach(() => {
vi.stubGlobal('CSS', { supports: (property: string) => property === '-webkit-backdrop-filter' })
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
vi.unstubAllGlobals()
vi.useRealTimers()
})
const SESSION = 'session' as SessionId
const t: JobListActionProps['t'] = makeTranslate(zh)
/** A running job with nothing retained yet. */
function job(over: Partial<JobView> = {}): JobView {
return {
id: 'bash-1' as JobView['id'],
kind: 'bash',
label: 'pnpm run build',
status: 'running',
startedAt: 1_700_000_000_000,
output: { total: 0, earliest: 0 },
...over,
}
}
/** A job that left retained output behind, so its row offers a panel even once settled. */
function outputJob(over: Partial<JobView> = {}): JobView {
return job({ output: { total: 12, earliest: 0 }, ...over })
}
function props(
jobs: readonly JobView[],
observe: JobListActionProps['observe'] = () => () => {},
observed: Readonly<Record<string, ObservedJob>> = {},
killJob: JobListActionProps['killJob'] = async () => true,
watchRows: JobListActionProps['watchRows'] = () => () => {},
mayKill = true,
): JobListActionProps {
const jobsState: JobsSnapshot = { rows: jobs.length > 0 ? { [SESSION]: jobs } : {}, observed }
function useJobs<T>(select: (value: JobsSnapshot) => T): T {
return select(jobsState)
}
return {
sessionId: SESSION, useJobs, watchRows, observe, killJob, t,
useAccess: () => mayKill,
} as JobListActionProps
}
function openList(): void {
fireEvent.click(screen.getAllByRole('button')[0]!)
}
describe('JobListAction count copy', () => {
it.each([
[zh, '1 个后台任务', '2 个后台任务'],
[en, '1 background job', '2 background jobs'],
[ja, 'バックグラウンドジョブ 1 件', 'バックグラウンドジョブ 2 件'],
[es, 'Tareas en segundo plano: 1', 'Tareas en segundo plano: 2'],
[fr, 'Tâches en arrière-plan : 1', 'Tâches en arrière-plan : 2'],
[de, 'Hintergrundaufgaben: 1', 'Hintergrundaufgaben: 2'],
[ru, 'Фоновые задачи: 1', 'Фоновые задачи: 2'],
[pt, 'Tarefas em segundo plano: 1', 'Tarefas em segundo plano: 2'],
] as const)('uses neutral count copy for live and settled jobs in locale %#', (dictionary, one, two) => {
const translate: JobListActionProps['t'] = makeTranslate(dictionary)
const settled = job({ id: 'settled' as JobView['id'], status: 'completed', finishedAt: 1_700_000_003_000 })
const { rerender } = render(<JobListAction {...props([job(), settled])} t={translate} />)
expect(screen.getByRole('button', { name: one, description: dictionary['section.live'] })).toBeDefined()
rerender(<JobListAction {...props([job({ status: 'stopping' }), settled])} t={translate} />)
expect(screen.getByRole('button', { name: one, description: dictionary['section.live'] })).toBeDefined()
rerender(<JobListAction {...props([job({ status: 'completed' }), settled])} t={translate} />)
expect(screen.getByRole('button', { name: two, description: '' })).toBeDefined()
})
})
describe('JobListAction visibility', () => {
it('renders nothing while the session sees no jobs', () => {
const { container } = render(<JobListAction {...props([])} />)
expect(container.innerHTML).toBe('')
})
it('watches the session roster while mounted and releases it on unmount', () => {
const stop = vi.fn()
const watchRows = vi.fn(() => stop)
const { unmount } = render(<JobListAction {...props([], undefined, {}, undefined, watchRows)} />)
expect(watchRows).toHaveBeenCalledWith(SESSION)
expect(stop).not.toHaveBeenCalled()
unmount()
expect(stop).toHaveBeenCalledTimes(1)
})
it('counts live jobs on the trigger', () => {
render(<JobListAction {...props([
outputJob(),
job({ id: 'subagent-1' as JobView['id'], kind: 'subagent', label: 'explore' }),
])} />)
expect(screen.getByRole('button', { name: '2 个后台任务' })).toBeDefined()
})
it('retains the compact Layers icon through running, stopping, and idle states without a root chevron', () => {
const { rerender } = render(<JobListAction {...props([job()])} />)
const trigger = screen.getByRole('button')
expect(trigger.querySelector('[data-icon="dsw-icon-layers-outline-regular"]')).not.toBeNull()
expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull()
expect(trigger.querySelector('[data-icon="dsw-icon-chevron-down-outline-regular"]')).toBeNull()
rerender(<JobListAction {...props([job({ status: 'stopping' })])} />)
expect(screen.getByRole('button')).toBe(trigger)
expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull()
rerender(<JobListAction {...props([job({ status: 'completed' })])} />)
expect(screen.getByRole('button')).toBe(trigger)
expect(trigger.querySelector('[data-state="ongoing"]')).toBeNull()
const icon = trigger.querySelector('[data-icon="dsw-icon-layers-outline-regular"]')
expect(icon?.getAttribute('width')).toBe('14')
expect(trigger.querySelectorAll('svg')).toHaveLength(1)
})
it('falls back to the total when nothing is live', () => {
render(<JobListAction {...props([
job({ status: 'completed', finishedAt: 1_700_000_003_000 }),
])} />)
expect(screen.getByRole('button', { name: '1 个后台任务' })).toBeDefined()
})
})
describe('JobListAction hover', () => {
function pointer(target: Element, type: 'pointerover' | 'pointerout', pointerType = 'mouse'): void {
// jsdom lacks PointerEvent; preserve its pointer type on the native event.
const event = new MouseEvent(type, { bubbles: true })
Object.defineProperty(event, 'pointerType', { value: pointerType })
fireEvent(target, event)
}
function advance(ms: number): void {
act(() => { vi.advanceTimersByTime(ms) })
}
function hoverOpen(): HTMLElement {
const trigger = screen.getByRole('button', { name: '1 个后台任务' })
pointer(trigger, 'pointerover')
advance(149)
expect(screen.queryByRole('list')).toBeNull()
advance(1)
expect(trigger.getAttribute('aria-expanded')).toBe('true')
return trigger
}
it('keeps the compact trigger click-only and shows its count tooltip after 500ms', () => {
vi.useFakeTimers()
render(<JobListAction {...props([job()])} />)
const trigger = screen.getByRole('button')
const count = trigger.querySelector<HTMLElement>('[data-job-count]')!
count.style.display = 'none'
pointer(trigger, 'pointerover')
advance(499)
expect(screen.queryByRole('list')).toBeNull()
expect(screen.queryByRole('tooltip')).toBeNull()
advance(1)
expect(screen.getByRole('tooltip').textContent).toBe('1 个后台任务')
fireEvent.click(trigger)
expect(screen.queryByRole('tooltip')).toBeNull()
pointer(trigger, 'pointerout')
advance(500)
expect(screen.getByRole('list')).toBeDefined()
fireEvent.click(trigger)
expect(screen.queryByRole('list')).toBeNull()
})
it('cancels pending wide hover when CSS hides the count and compact clicks close hover-opened lists', () => {
vi.useFakeTimers()
render(<JobListAction {...props([job()])} />)
const trigger = screen.getByRole('button')
const count = trigger.querySelector<HTMLElement>('[data-job-count]')!
pointer(trigger, 'pointerover')
advance(100)
count.style.display = 'none'
advance(50)
expect(screen.queryByRole('list')).toBeNull()
pointer(trigger, 'pointerout')
count.style.display = ''
hoverOpen()
count.style.display = 'none'
fireEvent.click(trigger)
expect(screen.queryByRole('list')).toBeNull()
})
it('shows count on keyboard focus immediately and opens and pins with ArrowDown', async () => {
vi.useFakeTimers()
render(<JobListAction {...props([job()])} />)
const trigger = screen.getByRole('button')
trigger.querySelector<HTMLElement>('[data-job-count]')!.style.display = 'none'
fireEvent.keyDown(document.body, { key: 'Tab' })
act(() => { trigger.focus() })
expect(screen.getByRole('tooltip').textContent).toBe('1 个后台任务')
fireEvent.keyDown(trigger, { key: 'ArrowDown' })
await act(async () => { vi.runAllTicks() })
expect(screen.queryByRole('tooltip')).toBeNull()
const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })
expect(document.activeElement).toBe(row)
pointer(trigger, 'pointerout')
advance(120)
expect(screen.getByRole('list')).toBeDefined()
fireEvent.keyDown(row, { key: 'Escape' })
expect(screen.queryByRole('list')).toBeNull()
expect(document.activeElement).toBe(trigger)
})
it('waits for hover, bridges the portal gap, and closes after leaving both surfaces', () => {
vi.useFakeTimers()
const observe = vi.fn(() => () => {})
const { container } = render(<JobListAction {...props([job()], observe)} />)
const trigger = hoverOpen()
const menu = screen.getByRole('list').parentElement!
expect(container.contains(menu)).toBe(false)
expect(observe).not.toHaveBeenCalled()
pointer(trigger, 'pointerout')
advance(119)
pointer(menu, 'pointerover')
advance(120)
expect(screen.getByRole('list')).toBeDefined()
pointer(menu, 'pointerout')
advance(119)
expect(screen.getByRole('list')).toBeDefined()
advance(1)
expect(screen.queryByRole('list')).toBeNull()
})
it('cancels short hover and preserves a returning pointer during leave grace', () => {
vi.useFakeTimers()
render(<JobListAction {...props([job()])} />)
const trigger = screen.getByRole('button')
pointer(trigger, 'pointerover')
advance(149)
pointer(trigger, 'pointerout')
advance(150)
expect(screen.queryByRole('list')).toBeNull()
hoverOpen()
pointer(trigger, 'pointerout')
advance(100)
pointer(trigger, 'pointerover')
advance(120)
expect(screen.getByRole('list')).toBeDefined()
})
it('pins a hover-opened list on click until explicit dismissal', () => {
vi.useFakeTimers()
render(<JobListAction {...props([job()])} />)
const trigger = hoverOpen()
fireEvent.click(trigger)
pointer(trigger, 'pointerout')
advance(120)
expect(screen.getByRole('list')).toBeDefined()
fireEvent.click(trigger)
expect(screen.queryByRole('list')).toBeNull()
hoverOpen()
fireEvent.click(trigger)
fireEvent.pointerDown(document.body)
expect(screen.queryByRole('list')).toBeNull()
hoverOpen()
pointer(trigger, 'pointerout')
advance(120)
expect(screen.queryByRole('list')).toBeNull()
})
it('ignores touch hover while keeping tap usable', () => {
vi.useFakeTimers()
render(<JobListAction {...props([job()])} />)
const trigger = screen.getByRole('button')
pointer(trigger, 'pointerover', 'touch')
advance(150)
expect(screen.queryByRole('list')).toBeNull()
fireEvent.click(trigger)
pointer(trigger, 'pointerout', 'touch')
advance(120)
expect(screen.getByRole('list')).toBeDefined()
fireEvent.click(trigger)
expect(screen.queryByRole('list')).toBeNull()
})
it('pins keyboard focus and releases expanded output on Escape or hover close', () => {
vi.useFakeTimers()
const stop = vi.fn()
const observe = vi.fn(() => stop)
render(<JobListAction {...props([outputJob()], observe)} />)
const trigger = hoverOpen()
pointer(trigger, 'pointerout')
act(() => { trigger.focus() })
fireEvent.keyDown(trigger, { key: 'Tab' })
const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })
expect(document.activeElement).toBe(row)
advance(120)
fireEvent.click(row)
expect(observe).toHaveBeenCalledTimes(1)
fireEvent.keyDown(row, { key: 'Escape' })
expect(document.activeElement).toBe(trigger)
expect(stop).toHaveBeenCalledTimes(1)
hoverOpen()
expect(observe).toHaveBeenCalledTimes(2)
pointer(trigger, 'pointerout')
advance(120)
expect(screen.queryByRole('list')).toBeNull()
expect(stop).toHaveBeenCalledTimes(2)
})
it('omits the stop control without job/kill access', () => {
const view = render(<JobListAction {...props([job({ status: 'running' })], undefined, undefined, undefined, undefined, false)} />)
openList()
expect(view.container.querySelector('[data-kill-state]')).toBeNull()
})
it('pins pointer interaction so leaving cannot interrupt stop confirmation', () => {
vi.useFakeTimers()
render(<JobListAction {...props([job()])} />)
const trigger = hoverOpen()
pointer(trigger, 'pointerout')
const stop = screen.getByTitle(zh['kill.stop'].replace('{label}', 'pnpm run build'))
fireEvent.pointerDown(stop)
fireEvent.click(stop)
pointer(screen.getByRole('list').parentElement!, 'pointerout')
advance(120)
expect(stop.getAttribute('data-kill-state')).toBe('armed')
expect(screen.getByRole('list')).toBeDefined()
})
it('dismisses a hover-opened list with Escape while focus is elsewhere', () => {
vi.useFakeTimers()
render(<JobListAction {...props([job()])} />)
hoverOpen()
fireEvent.keyDown(document.body, { key: 'a' })
expect(screen.getByRole('list')).toBeDefined()
fireEvent.keyDown(document.body, { key: 'Escape' })
expect(screen.queryByRole('list')).toBeNull()
})
it.each(['opening', 'closing'] as const)('cleans up a pending %s timer on unmount', (phase) => {
vi.useFakeTimers()
const { unmount } = render(<JobListAction {...props([job()])} />)
const trigger = screen.getByRole('button')
pointer(trigger, 'pointerover')
if (phase === 'closing') {
advance(150)
pointer(trigger, 'pointerout')
}
unmount()
expect(vi.getTimerCount()).toBe(0)
advance(150)
expect(screen.queryByRole('list')).toBeNull()
})
it('releases expanded output and pending hover close before showing another session', () => {
vi.useFakeTimers()
const stop = vi.fn()
const observe = vi.fn(() => stop)
const first = props([outputJob()], observe)
const { rerender } = render(<JobListAction {...first} />)
const trigger = hoverOpen()
const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })
fireEvent.click(row)
expect(observe).toHaveBeenCalledTimes(1)
pointer(trigger, 'pointerout')
const nextId = 'next-session' as SessionId
rerender(<JobListAction
{...first}
sessionId={nextId}
useJobs={select => select({ rows: { [nextId]: [outputJob()] }, observed: {} })}
/>)
expect(stop).toHaveBeenCalledTimes(1)
expect(observe).toHaveBeenCalledTimes(1)
expect(vi.getTimerCount()).toBe(0)
hoverOpen()
advance(120)
expect(screen.getByRole('list')).toBeDefined()
expect(observe).toHaveBeenLastCalledWith(nextId, 'bash-1')
})
it('cancels pending hover and clears pins on session change or an empty roster', () => {
vi.useFakeTimers()
const first = props([job()])
const nextId = 'next-session' as SessionId
const next: JobListActionProps = {
...first,
sessionId: nextId,
useJobs: select => select({ rows: { [nextId]: [job()] }, observed: {} }),
}
const { rerender } = render(<JobListAction {...first} />)
pointer(screen.getByRole('button'), 'pointerover')
rerender(<JobListAction {...next} />)
advance(150)
expect(screen.queryByRole('list')).toBeNull()
const trigger = hoverOpen()
fireEvent.click(trigger)
rerender(<JobListAction {...first} />)
expect(screen.queryByRole('list')).toBeNull()
pointer(screen.getByRole('button'), 'pointerover')
rerender(<JobListAction {...props([])} />)
advance(150)
expect(vi.getTimerCount()).toBe(0)
rerender(<JobListAction {...first} />)
hoverOpen()
fireEvent.click(screen.getByRole('button', { name: '1 个后台任务' }))
rerender(<JobListAction {...props([])} />)
rerender(<JobListAction {...first} />)
expect(screen.queryByRole('list')).toBeNull()
})
})
describe('JobListAction rows', () => {
it('renders a settled job without retained output as a static row', () => {
render(<JobListAction {...props([
job({ id: 'subagent-1' as JobView['id'], kind: 'subagent', label: 'explore the repo', status: 'completed', finishedAt: 1_700_000_003_000 }),
])} />)
expect(screen.getByRole('button', { name: '1 个后台任务' })).toBeDefined()
openList()
expect(screen.getByText('explore the repo')).toBeDefined()
expect(screen.queryByRole('button', { name: zh['row.expandAria'].replace('{label}', 'explore the repo') })).toBeNull()
})
it('offers a panel on a live row before any output arrived', () => {
render(<JobListAction {...props([job({ label: 'warming up' })])} />)
openList()
expect(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'warming up') })).toBeDefined()
})
it('shows the live progress line in place of the status word', () => {
render(<JobListAction {...props([job({ status: 'stopping', progress: 'winding down' })])} />)
openList()
const list = screen.getByRole('list', { name: zh['list.aria'] })
expect(within(list).getByText('pnpm run build')).toBeDefined()
expect(within(list).getByText('winding down')).toBeDefined()
})
it('folds the settled tail behind its count while live work exists, and clears on demand', () => {
const settled = [job({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 })]
render(<JobListAction {...props([job(), ...settled])} />)
openList()
expect(screen.getByText(zh['section.live'], { selector: 'li' })).toBeDefined()
const toggle = screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })
// Folded by default while something runs; the toggle expands it.
expect(toggle.getAttribute('aria-expanded')).toBe('false')
expect(screen.queryByText('settled work')).toBeNull()
fireEvent.click(toggle)
expect(screen.getByText('settled work')).toBeDefined()
// Clearing hides the tail client-side and drops the whole section line.
fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] }))
expect(screen.queryByText('settled work')).toBeNull()
expect(screen.queryByRole('button', { name: zh['section.clear'] })).toBeNull()
})
it('opens the settled tail by default when nothing is live', () => {
render(<JobListAction {...props([
job({ status: 'completed', finishedAt: 1_700_000_012_000 }),
])} />)
openList()
expect(screen.getByText('pnpm run build')).toBeDefined()
expect(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }).getAttribute('aria-expanded')).toBe('true')
})
it('clearing drops an expanded settled panel with its rows', () => {
const observe = vi.fn(() => () => {})
render(<JobListAction {...props(
[outputJob({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 })],
observe,
)} />)
openList()
// Nothing live: the tail is open; expand the settled row's output panel.
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'settled work') }))
expect(observe).toHaveBeenCalledWith(SESSION, 'bash-2')
fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] }))
expect(screen.queryByText('settled work')).toBeNull()
expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'settled work') })).toBeNull()
})
it('shows a settled duration and ticks a live one', () => {
vi.useFakeTimers({ now: 1_700_000_020_000 })
render(<JobListAction {...props([
job({ startedAt: 1_700_000_015_000 }),
job({ id: 'bash-2' as JobView['id'], status: 'completed', startedAt: 1_700_000_000_000, finishedAt: 1_700_000_012_000 }),
job({ id: 'bash-3' as JobView['id'], status: 'completed', startedAt: 1_699_996_200_000, finishedAt: 1_700_000_000_000 }),
job({ id: 'bash-4' as JobView['id'], status: 'completed', startedAt: 1_699_999_900_000, finishedAt: 1_699_999_972_000 }),
])} />)
openList()
fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') }))
expect(screen.getByText('5秒')).toBeDefined()
expect(screen.getByText('12秒')).toBeDefined()
expect(screen.getByText('1小时3分')).toBeDefined()
expect(screen.getByText('1分12秒')).toBeDefined()
act(() => { vi.advanceTimersByTime(1_000) })
expect(screen.getByText('6秒')).toBeDefined()
})
it('lists rows with kind, label, and detail-or-status', () => {
render(<JobListAction {...props([
outputJob(),
outputJob({ id: 'bash-2' as JobView['id'], status: 'failed', detail: 'exit code: 3', finishedAt: 1_700_000_002_000 }),
])} />)
openList()
fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }))
const list = screen.getByRole('list', { name: zh['list.aria'] })
const items = within(list).getAllByRole('listitem')
// The section line is a listitem too now: live row, section, settled row.
expect(items).toHaveLength(3)
expect(items[0]?.textContent).toContain('pnpm run build')
// A live row's second line is kind · duration; the status word only
// appears through a detail (none while running).
expect(items[0]?.textContent).toMatch(/小时|分|秒/)
expect(items[2]?.textContent).toContain('exit code: 3')
})
it('orders live rows first by start and settled rows newest-first with tie-breaks', () => {
const settled = (id: string, label: string, startedAt: number, finishedAt?: number): JobView =>
job({
id: id as JobView['id'],
label,
status: 'completed',
startedAt,
...finishedAt !== undefined ? { finishedAt } : {},
})
render(<JobListAction {...props([
settled('bash-a', 'settled-a', 10, 100),
settled('bash-c', 'settled-c', 80, 100),
settled('bash-b', 'settled-b', 90),
settled('bash-e', 'settled-e', 95, 50),
settled('bash-d', 'settled-d', 10, 200),
job({ id: 'bash-l1' as JobView['id'], label: 'live-1', startedAt: 5 }),
job({ id: 'bash-l2' as JobView['id'], label: 'live-2', startedAt: 3 }),
])} />)
openList()
fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '5') }))
const labels = within(screen.getByRole('list', { name: zh['list.aria'] }))
.getAllByRole('listitem')
.map(item => item.querySelector('[title]')?.getAttribute('title'))
.filter((title): title is string => title != null && !title.startsWith('已运行') && !title.startsWith('耗时'))
expect(labels).toEqual([
'live-2', 'live-1', 'settled-d', 'settled-a', 'settled-c', 'settled-b', 'settled-e',
])
expect(screen.getAllByText(zh['status.completed']).length).toBeGreaterThan(0)
})
it('breaks a settled tie on start order so map iteration never decides it', () => {
render(<JobListAction {...props([
job({ id: 'bash-2' as JobView['id'], label: 'second', status: 'completed', startedAt: 1_700_000_000_000 + 10, finishedAt: 1_700_000_000_000 + 100 }),
job({ id: 'bash-1' as JobView['id'], label: 'first', status: 'completed', startedAt: 1_700_000_000_000, finishedAt: 1_700_000_000_000 + 100 }),
])} />)
openList()
expect(within(screen.getByRole('list')).getAllByRole('listitem').map(row => row.querySelector('[title]')?.getAttribute('title')).filter(title => title !== undefined))
.toEqual(['first', 'second'])
})
it('prefers the producer detail over the generic status word', () => {
render(<JobListAction {...props([
job({ status: 'killed', detail: 'signal: SIGTERM', finishedAt: 1_700_000_000_000 + 2_000 }),
])} />)
openList()
expect(within(screen.getByRole('list')).getByText('signal: SIGTERM')).toBeDefined()
})
it('renders settled status words and every lifecycle indicator', () => {
render(<JobListAction {...props([
job({ id: 'bash-1' as JobView['id'], label: 'a', status: 'running' }),
job({ id: 'bash-2' as JobView['id'], label: 'b', status: 'stopping' }),
job({ id: 'bash-3' as JobView['id'], label: 'c', status: 'completed', finishedAt: 1_700_000_000_000 }),
job({ id: 'bash-4' as JobView['id'], label: 'd', status: 'killed', finishedAt: 1_700_000_000_000 }),
job({ id: 'bash-5' as JobView['id'], label: 'e', status: 'failed', finishedAt: 1_700_000_000_000 }),
])} />)
openList()
fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') }))
for (const word of ['已完成', '已取消', '已失败']) {
expect(within(screen.getByRole('list')).getByText(word)).toBeDefined()
}
expect([...screen.getByRole('list').querySelectorAll('li [data-state]')].map(node => node.getAttribute('data-state')))
.toEqual(['ongoing', 'warning', 'done', 'warning', 'error'])
})
})
describe('JobListAction observation', () => {
it('marks killed rows, renders every output line unfolded, and copies the command', async () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
const lines = Array.from({ length: 24 }, (_value, index) => `line ${index + 1}`).join('\n')
const view: ObservedJob = {
jobId: 'bash-1' as JobView['id'],
text: lines,
gapBefore: false,
streaming: false,
}
render(<JobListAction {...props(
[outputJob({ status: 'killed', finishedAt: 1_700_000_001_000 })],
undefined,
{ 'bash-1': view },
)} />)
openList()
expect(screen.getByText(zh['status.killed'])).toBeDefined()
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }))
// The panel scrolls instead of folding: every line renders, no fold control.
expect(screen.getByText('line 1')).toBeDefined()
expect(screen.getByText('line 24')).toBeDefined()
expect(screen.queryByRole('button', { name: zh['terminal.expandAria'].replace('{n}', '8') })).toBeNull()
// The panel draws no state dot or label of its own — the row carries it.
expect(screen.queryByText(zh['terminal.done'])).toBeNull()
// The copy control carries the command, not the output.
await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['terminal.copy'] })) })
expect(writeText).toHaveBeenCalledWith('pnpm run build')
})
it('anchors the portaled list with CSS without reading geometry on resize or ancestor scroll', () => {
const { container } = render(<JobListAction {...props([outputJob()])} />)
const trigger = screen.getByRole('button', { name: '1 个后台任务' })
const anchor = trigger.closest('div')!
const measure = vi.spyOn(anchor, 'getBoundingClientRect')
fireEvent.click(trigger)
const list = screen.getByRole('list', { name: zh['list.aria'] })
const menu = list.closest<HTMLElement>('[data-menu-material]')!
expect(menu.parentElement).toBe(document.body)
expect(container.contains(list)).toBe(false)
expect(anchor.style.anchorName).not.toBe('')
expect(menu.style.positionAnchor).toBe(anchor.style.anchorName)
expect(menu.style.left).toBe('')
expect(menu.style.top).toBe('')
fireEvent(window, new Event('resize'))
fireEvent.scroll(container)
expect(menu.style.positionAnchor).toBe(anchor.style.anchorName)
expect(measure).not.toHaveBeenCalled()
})
it('gives independent job controls separate CSS anchors', () => {
render(<><JobListAction {...props([outputJob()])} /><JobListAction {...props([outputJob()])} /></>)
const triggers = screen.getAllByRole('button', { name: '1 个后台任务' })
const first = triggers[0]!.closest('div')!
const second = triggers[1]!.closest('div')!
expect(first.style.anchorName).not.toBe('')
expect(second.style.anchorName).not.toBe('')
expect(first.style.anchorName).not.toBe(second.style.anchorName)
})
it('keeps visual viewport changes out of inline placement and closes normally', () => {
const viewport = Object.assign(new EventTarget(), { width: 600, height: 500, offsetLeft: 40, offsetTop: 60 })
vi.stubGlobal('visualViewport', viewport)
const listen = vi.spyOn(viewport, 'addEventListener')
render(<JobListAction {...props([outputJob()])} />)
const trigger = screen.getByRole('button', { name: '1 个后台任务' })
fireEvent.click(trigger)
const menu = screen.getByRole('list', { name: zh['list.aria'] }).closest<HTMLElement>('[data-menu-material]')!
const placement = menu.style.positionAnchor
act(() => {
viewport.offsetLeft = 100
viewport.offsetTop = 120
viewport.dispatchEvent(new Event('scroll'))
viewport.height = 200
viewport.dispatchEvent(new Event('resize'))
})
expect(menu.style.positionAnchor).toBe(placement)
expect(menu.style.left).toBe('')
expect(menu.style.top).toBe('')
expect(menu.style.getPropertyValue('--dsh-anchored-max-width')).toBe('')
expect(menu.style.getPropertyValue('--dsh-anchored-max-height')).toBe('')
expect(listen).not.toHaveBeenCalled()
fireEvent.click(trigger)
expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull()
})
it('keeps portaled controls interactive and releases observation on dismissal and unmount', () => {
const stop = vi.fn()
const observe = vi.fn(() => stop)
const { container, unmount } = render(<JobListAction {...props([outputJob()], observe)} />)
const trigger = screen.getByRole('button', { name: '1 个后台任务' })
trigger.focus()
fireEvent.click(trigger)
const list = screen.getByRole('list', { name: zh['list.aria'] })
expect(container.contains(list)).toBe(false)
const row = screen.getByRole('button', {
name: zh['row.expandAria'].replace('{label}', 'pnpm run build'),
})
fireEvent.pointerDown(row)
fireEvent.click(row)
expect(screen.getByRole('list', { name: zh['list.aria'] })).toBe(list)
expect(observe).toHaveBeenCalledTimes(1)
expect(stop).not.toHaveBeenCalled()
const kill = screen.getByTitle(zh['kill.stop'].replace('{label}', 'pnpm run build'))
fireEvent.pointerDown(kill)
fireEvent.click(kill)
expect(kill.getAttribute('data-kill-state')).toBe('armed')
expect(screen.getByRole('list', { name: zh['list.aria'] })).toBe(list)
row.focus()
fireEvent.keyDown(row, { key: 'Escape' })
expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull()
expect(document.activeElement).toBe(trigger)
expect(stop).toHaveBeenCalledTimes(1)
fireEvent.click(trigger)
expect(observe).toHaveBeenCalledTimes(2)
fireEvent.pointerDown(document.body)
expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull()
expect(stop).toHaveBeenCalledTimes(2)
fireEvent.click(trigger)
expect(observe).toHaveBeenCalledTimes(3)
const reopened = screen.getByRole('list', { name: zh['list.aria'] })
unmount()
expect(document.body.contains(reopened)).toBe(false)
expect(stop).toHaveBeenCalledTimes(3)
})
it('ignores other keys while open and closes once the roster empties', () => {
const settledPair = [
outputJob({ id: 'bash-1' as JobView['id'], status: 'completed', finishedAt: 2 }),
outputJob({ id: 'bash-2' as JobView['id'], status: 'completed', finishedAt: 3 }),
]
const { rerender } = render(<JobListAction {...props(settledPair)} />)
expect(screen.getByRole('button', { name: '2 个后台任务' })).toBeDefined()
openList()
const list = screen.getByRole('list', { name: zh['list.aria'] })
fireEvent.keyDown(list, { key: 'a' })
expect(screen.getByRole('list', { name: zh['list.aria'] })).toBeDefined()
// The roster emptying unmounts the control entirely; the open flag resets first.
rerender(<JobListAction {...props([])} />)
expect(screen.queryByRole('button')).toBeNull()
})
it('starts observing on expand with the session identity, renders the live text, and stops on collapse', () => {
const stop = vi.fn()
const observe = vi.fn(() => stop)
const view: ObservedJob = {
jobId: 'bash-1' as JobView['id'],
text: 'compiling…\n',
gapBefore: false,
streaming: true,
}
render(<JobListAction {...props([outputJob()], observe, { 'bash-1': view })} />)
openList()
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }))
expect(observe).toHaveBeenCalledWith(SESSION, 'bash-1')
expect(screen.getByText('compiling…')).toBeDefined()
fireEvent.click(screen.getByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'pnpm run build') }))
expect(stop).toHaveBeenCalledTimes(1)
})
it('renders a running panel with the prompt alone for a live row whose output has not arrived', () => {
const view: ObservedJob = {
jobId: 'bash-1' as JobView['id'],
text: '',
gapBefore: false,
streaming: true,
}
render(<JobListAction {...props([job()], undefined, { 'bash-1': view })} />)
openList()
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }))
expect(screen.getByRole('list', { name: zh['list.aria'] }).querySelector('[data-running]')).not.toBeNull()
expect(screen.queryByText(zh['terminal.noOutput'])).toBeNull()
})
it('surfaces retention gaps and stream failures above the panel', () => {
const view: ObservedJob = {
jobId: 'bash-1' as JobView['id'],
text: 'tail only',
gapBefore: true,
streaming: false,
error: 'connection lost',
}
render(<JobListAction {...props([outputJob()], undefined, { 'bash-1': view })} />)
openList()
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }))
expect(screen.getByText(zh['output.gap'])).toBeDefined()
expect(screen.getByText('实时输出流中断:connection lost')).toBeDefined()
})
it('bridges Tab between the trigger and the portaled list and closes on Escape', () => {
render(<JobListAction {...props([job()])} />)
const trigger = screen.getAllByRole('button')[0]!
fireEvent.keyDown(trigger, { key: 'Tab' })
openList()
const [first, last] = within(screen.getByRole('list', { name: zh['list.aria'] })).getAllByRole('button')
trigger.focus()
// Shift+Tab from the trigger leaves toward the controls before it.
expect(fireEvent.keyDown(trigger, { key: 'Tab', shiftKey: true })).toBe(true)
expect(document.activeElement).toBe(trigger)
// Tab from the trigger enters the list.
expect(fireEvent.keyDown(trigger, { key: 'Tab' })).toBe(false)
expect(document.activeElement).toBe(first)
// Inside the list Tab stays the browser's until an end is reached.
expect(fireEvent.keyDown(first!, { key: 'Tab' })).toBe(true)
// Tab off the last control resumes from the trigger's place in the page.
expect(fireEvent.keyDown(last!, { key: 'Tab' })).toBe(true)
expect(document.activeElement).toBe(trigger)
// Shift+Tab off the first control returns to the trigger itself.
first!.focus()
expect(fireEvent.keyDown(first!, { key: 'Tab', shiftKey: true })).toBe(false)
expect(document.activeElement).toBe(trigger)
first!.focus()
fireEvent.keyDown(first!, { key: 'Escape' })
expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull()
expect(document.activeElement).toBe(trigger)
})
it('stops observation when the popover closes via Escape', () => {
const stop = vi.fn()
render(<JobListAction {...props([outputJob()], () => stop)} />)
openList()
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }))
fireEvent.keyDown(screen.getByRole('list', { name: zh['list.aria'] }), { key: 'Escape' })
expect(stop).toHaveBeenCalledTimes(1)
expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull()
})
it('folds an expanded panel whose row left the roster', () => {
const stop = vi.fn()
// One stable observe identity across renders, as the inject face provides.
const observe = () => stop
const { rerender } = render(<JobListAction {...props([outputJob()], observe)} />)
openList()
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }))
rerender(<JobListAction {...props([outputJob({ id: 'bash-2' as JobView['id'], label: 'other' })], observe)} />)
expect(stop).toHaveBeenCalledTimes(1)
expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'other') })).toBeNull()
})
})
describe('JobListAction human kill', () => {
const stopTitle = (label: string): string => zh['kill.stop'].replace('{label}', label)
it('offers the stop control only on running rows', () => {
render(<JobListAction {...props([
job(),
job({ id: 'bash-2' as JobView['id'], label: 'done', status: 'completed', finishedAt: 1_700_000_100_000 }),
])} />)
openList()
expect(screen.getByTitle(stopTitle('pnpm run build'))).toBeDefined()
expect(screen.queryByTitle(stopTitle('done'))).toBeNull()
})
it('arms on the first press and kills on the confirming press', async () => {
const killJob = vi.fn(async () => true)
render(<JobListAction {...props([job()], undefined, {}, killJob)} />)
openList()
const stop = screen.getByTitle(stopTitle('pnpm run build'))
fireEvent.click(stop)
expect(killJob).not.toHaveBeenCalled()
expect(stop.getAttribute('data-kill-state')).toBe('armed')
expect(screen.getByTitle(zh['kill.confirm'])).toBe(stop)
// The armed step is legible without hover: the button carries the label.
expect(stop.textContent).toBe(zh['kill.confirmAction'])
await act(async () => { fireEvent.click(stop) })
expect(killJob).toHaveBeenCalledWith(SESSION, 'bash-1')
// An admitted kill stays pending: the unary response and the jobs frames
// have no cross-carrier ordering, so only the authoritative frame (the row
// leaving the killable set) releases the control — never the response.
expect(stop.getAttribute('data-kill-state')).toBe('pending')
expect(stop.hasAttribute('disabled')).toBe(true)
})
it('an armed press disarms after the confirmation window', () => {
vi.useFakeTimers()
const killJob = vi.fn(async () => true)
render(<JobListAction {...props([job()], undefined, {}, killJob)} />)
openList()
const stop = screen.getByTitle(stopTitle('pnpm run build'))
fireEvent.click(stop)
expect(stop.getAttribute('data-kill-state')).toBe('armed')
act(() => { vi.advanceTimersByTime(3_000) })
expect(stop.getAttribute('data-kill-state')).toBe('idle')
expect(killJob).not.toHaveBeenCalled()
})
it('a rejected kill shows its hint and then resets', async () => {
// Fake timers from the start so the failed-hint reset arms on the fake clock.
vi.useFakeTimers()
const killJob = vi.fn(async () => false)
render(<JobListAction {...props([job()], undefined, {}, killJob)} />)
openList()
const stop = screen.getByTitle(stopTitle('pnpm run build'))
fireEvent.click(stop)
await act(async () => { fireEvent.click(stop) })
expect(stop.getAttribute('data-kill-state')).toBe('failed')
expect(screen.getByTitle(zh['kill.failed'])).toBe(stop)
act(() => { vi.advanceTimersByTime(4_000) })
expect(stop.getAttribute('data-kill-state')).toBe('idle')
})
it('arming a second row disarms the first', () => {
render(<JobListAction {...props([
job(),
job({ id: 'bash-2' as JobView['id'], label: 'pnpm run watch' }),
])} />)
openList()
const first = screen.getByTitle(stopTitle('pnpm run build'))
fireEvent.click(first)
expect(first.getAttribute('data-kill-state')).toBe('armed')
const second = screen.getByTitle(stopTitle('pnpm run watch'))
fireEvent.click(second)
expect(second.getAttribute('data-kill-state')).toBe('armed')
expect(first.getAttribute('data-kill-state')).toBe('idle')
})
it('a kill resolving after another row armed leaves the newer phase alone', async () => {
let resolveKill!: (ok: boolean) => void
const killJob = vi.fn(() => new Promise<boolean>((resolve) => { resolveKill = resolve }))
render(<JobListAction {...props([
job(),
job({ id: 'bash-2' as JobView['id'], label: 'pnpm run watch' }),
], undefined, {}, killJob)} />)
openList()
const first = screen.getByTitle(stopTitle('pnpm run build'))
fireEvent.click(first)
fireEvent.click(first)
expect(killJob).toHaveBeenCalledTimes(1)
// While the first kill is in flight, the user arms the second row; the
// late resolution must not clobber that newer phase.
const second = screen.getByTitle(stopTitle('pnpm run watch'))
fireEvent.click(second)
expect(second.getAttribute('data-kill-state')).toBe('armed')
await act(async () => { resolveKill(false) })
expect(second.getAttribute('data-kill-state')).toBe('armed')
expect(first.getAttribute('data-kill-state')).toBe('idle')
})
it('clears an armed phase whose row stopped being killable', () => {
const { rerender } = render(<JobListAction {...props([job()])} />)
openList()
const stop = screen.getByTitle(stopTitle('pnpm run build'))
fireEvent.click(stop)
expect(stop.getAttribute('data-kill-state')).toBe('armed')
rerender(<JobListAction {...props([job({ status: 'stopping' })])} />)
// The stopping row offers no kill control any more, and the stale phase is gone.
expect(screen.queryByTitle(stopTitle('pnpm run build'))).toBeNull()
expect(document.querySelector('[data-kill-state]')).toBeNull()
})
})
it.each([1, 2, 5, 21])('renders count-independent Russian labels for %i jobs', (count) => {
const jobs = Array.from({ length: count }, (_, i) => job({ id: `job-${i}` as JobView['id'] }))
const translate: JobListActionProps['t'] = makeTranslate(ru)
const view = render(<JobListAction {...props(jobs)} t={translate} />)
expect(screen.getByRole('button', { name: `Фоновые задачи: ${count}` })).toBeDefined()
view.rerender(<JobListAction {...props(jobs.map(item => ({ ...item, status: 'completed', finishedAt: 1_700_000_003_000 })))} t={translate} />)
expect(screen.getByRole('button', { name: `Фоновые задачи: ${count}` })).toBeDefined()
})
@@ -0,0 +1,759 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useSyncExternalStore } from 'react'
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { JobsRunningIndicator, JobsSection, type JobsRunningIndicatorProps, type JobsSectionProps } from '../src/client/JobsSection.tsx'
import { createJobsSectionStore } from '../src/client/jobs-store.ts'
import { en, zh, ru } from '../src/client/locales.ts'
import type { PanelDetailsProps, PanelFoldProps } from '@deepseek-ai/dsh-client-ui-session-panel/client'
beforeEach(() => {
class TooltipObserver implements ResizeObserver {
constructor(private readonly callback: ResizeObserverCallback) {}
observe(target: Element): void {
const size = { inlineSize: 160, blockSize: 30 }
this.callback([{
target, borderBoxSize: [size], contentBoxSize: [size], devicePixelContentBoxSize: [size], contentRect: new DOMRect(),
}], this)
}
unobserve(): void {}
disconnect(): void {}
}
vi.stubGlobal('ResizeObserver', TooltipObserver)
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })))
})
beforeEach(() => {
vi.stubGlobal('CSS', { supports: (property: string) => property === '-webkit-backdrop-filter' })
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
vi.unstubAllGlobals()
vi.useRealTimers()
})
const SESSION = 'session' as SessionId
const t: JobsSectionProps['t'] = makeTranslate(zh)
/** A running job with nothing retained yet. */
function job(over: Partial<JobView> = {}): JobView {
return {
id: 'bash-1' as JobView['id'],
kind: 'bash',
label: 'pnpm run build',
status: 'running',
startedAt: 1_700_000_000_000,
output: { total: 0, earliest: 0 },
...over,
}
}
/** A job that left retained output behind, so its row offers a panel even once settled. */
function outputJob(over: Partial<JobView> = {}): JobView {
return job({ output: { total: 12, earliest: 0 }, ...over })
}
/** One Session's section store, as the registration mints it. */
type SectionStore = ReturnType<ReturnType<typeof createJobsSectionStore>['create']>
/**
* The Session panel's Factories as this suite renders them: the fold control as a button with its state, name, and
* label, and a row's details as one element per part in order. ui-session-panel's own suite owns their markup.
*/
function renderPanelFactory(name: string, input: object) {
if (name === 'conversation.session.panel.details') {
const { title, lines = [], status, facts = [] } = input as PanelDetailsProps
return (
<div data-session-panel-details="">
{title !== undefined && <div>{title}</div>}
{lines.map(line => <div key={line}>{line}</div>)}
{status !== undefined && <div data-state={status.state}>{status.label}</div>}
{facts.length > 0 && <div>{facts.map(fact => <span key={fact.kind} data-fact={fact.kind}>{fact.label}</span>)}</div>}
</div>
)
}
const fold = input as PanelFoldProps
return <button type="button" data-fold="" aria-expanded={fold.expanded} aria-label={fold.name} onClick={fold.onToggle}>{fold.label}</button>
}
/** Test-local selector hook over a framework-neutral store instance. */
function hookOf<T>(instance: { subscribe: (listener: () => void) => () => void; getSnapshot: () => T }) {
return function useSelector<S>(select: (state: T) => S): S {
return select(useSyncExternalStore(instance.subscribe, instance.getSnapshot))
}
}
function props(
jobs: readonly JobView[],
observe: JobsSectionProps['observe'] = () => () => {},
observed: Readonly<Record<string, ObservedJob>> = {},
killJob: JobsSectionProps['killJob'] = async () => true,
watchRows: JobsSectionProps['watchRows'] = () => () => {},
store: SectionStore = createJobsSectionStore().create(),
mayKill = true,
): JobsSectionProps {
const jobsState: JobsSnapshot = { rows: jobs.length > 0 ? { [SESSION]: jobs } : {}, observed }
function useJobs<T>(select: (value: JobsSnapshot) => T): T {
return select(jobsState)
}
return {
sessionId: SESSION, useJobs, watchRows, observe, killJob, useStore: hookOf(store), actions: store.actions, t,
useAccess: () => mayKill, renderFactorySlot: renderPanelFactory,
} as Pick<JobsSectionProps,
'sessionId' | 'useJobs' | 'watchRows' | 'observe' | 'killJob' | 'useStore' | 'actions' | 't' | 'useAccess' | 'renderFactorySlot'> as JobsSectionProps
}
describe('JobsRunningIndicator', () => {
function indicator(jobs: readonly JobView[], panelShown: boolean, watchRows: JobsSectionProps['watchRows'] = () => () => {}) {
const section = props(jobs, undefined, {}, undefined, watchRows)
const dotProps = {
sessionId: section.sessionId, useJobs: section.useJobs, watchRows: section.watchRows, t: section.t, panelShown,
} as Pick<JobsRunningIndicatorProps, 'sessionId' | 'useJobs' | 'watchRows' | 't' | 'panelShown'> as JobsRunningIndicatorProps
return render(<JobsRunningIndicator {...dotProps} />)
}
it('shows a named dot while jobs run and the panel does not show them, counting stopping jobs', () => {
const view = indicator([
job(), job({ id: 'bash-2' as JobView['id'], status: 'stopping' }), job({ id: 'bash-3' as JobView['id'], status: 'completed' }),
], false)
expect(view.container.querySelector('[data-jobs-running]')?.textContent).toBe(zh['indicator.running'].replace('{count}', '2'))
})
it('renders nothing while the panel shows, without jobs, and after they settle', () => {
expect(indicator([job()], true).container.innerHTML).toBe('')
cleanup()
expect(indicator([], false).container.innerHTML).toBe('')
cleanup()
expect(indicator([job({ status: 'completed' })], false).container.innerHTML).toBe('')
})
it('keeps the roster stream open while the toggle is mounted, even while the panel shows', () => {
const stop = vi.fn()
const watchRows = vi.fn(() => stop)
const view = indicator([], true, watchRows)
expect(watchRows).toHaveBeenCalledWith(SESSION)
expect(stop).not.toHaveBeenCalled()
view.unmount()
expect(stop).toHaveBeenCalledOnce()
})
})
describe('JobsSection visibility', () => {
it('renders nothing while the session sees no jobs', () => {
const { container } = render(<JobsSection {...props([])} />)
expect(container.innerHTML).toBe('')
})
it('watches the session roster while mounted and releases it on unmount', () => {
const stop = vi.fn()
const watchRows = vi.fn(() => stop)
const { unmount } = render(<JobsSection {...props([], undefined, {}, undefined, watchRows)} />)
expect(watchRows).toHaveBeenCalledWith(SESSION)
expect(stop).not.toHaveBeenCalled()
unmount()
expect(stop).toHaveBeenCalledTimes(1)
})
})
describe('JobsSection rows', () => {
it('renders a settled job without retained output as a static row', () => {
render(<JobsSection {...props([
job({ id: 'subagent-1' as JobView['id'], kind: 'subagent', label: 'explore the repo', status: 'completed', finishedAt: 1_700_000_003_000 }),
])} />)
// The section heading names the region, so the list carries no name of its own.
expect(screen.getByRole('list').hasAttribute('aria-label')).toBe(false)
expect(screen.getByText('explore the repo')).toBeDefined()
expect(screen.queryByRole('button', { name: zh['row.expandAria'].replace('{label}', 'explore the repo') })).toBeNull()
})
it('offers a panel on a live row before any output arrived', () => {
render(<JobsSection {...props([job({ label: 'warming up' })])} />)
expect(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'warming up') })).toBeDefined()
})
it('shows the live progress line in place of the status word', () => {
render(<JobsSection {...props([job({ status: 'stopping', progress: 'winding down' })])} />)
const list = screen.getByRole('list')
expect(within(list).getByText('pnpm run build')).toBeDefined()
expect(within(list).getByText('bash · winding down')).toBeDefined()
})
it('folds the settled tail behind its count while live work exists, and clears on demand', () => {
const settled = [job({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 })]
render(<JobsSection {...props([job(), ...settled])} />)
const toggle = screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })
// Folded by default while something runs; the toggle expands it.
expect(toggle.getAttribute('aria-expanded')).toBe('false')
expect(screen.queryByText('settled work')).toBeNull()
fireEvent.click(toggle)
expect(screen.getByText('settled work')).toBeDefined()
// Clearing hides the tail client-side and drops the whole section line.
fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] }))
expect(screen.queryByText('settled work')).toBeNull()
expect(screen.queryByRole('button', { name: zh['section.clear'] })).toBeNull()
})
it('keeps cleared rows hidden when the section mounts again for the same Session', () => {
const store = createJobsSectionStore().create()
const settled = job({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 })
const first = render(<JobsSection {...props([job(), settled], undefined, {}, undefined, undefined, store)} />)
fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }))
fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] }))
first.unmount()
render(<JobsSection {...props([job(), settled], undefined, {}, undefined, undefined, store)} />)
expect(screen.queryByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })).toBeNull()
expect(screen.queryByText('settled work')).toBeNull()
})
it('keeps the settled fold the user opened when the section mounts again for the same Session', () => {
const store = createJobsSectionStore().create()
const settled = job({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 })
const toggle = (): HTMLElement => screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })
const first = render(<JobsSection {...props([job(), settled], undefined, {}, undefined, undefined, store)} />)
fireEvent.click(toggle())
first.unmount()
render(<JobsSection {...props([job(), settled], undefined, {}, undefined, undefined, store)} />)
expect([toggle().getAttribute('aria-expanded'), screen.queryByText('settled work') !== null]).toEqual(['true', true])
})
it('opens the settled tail by default when nothing is live', () => {
render(<JobsSection {...props([
job({ status: 'completed', finishedAt: 1_700_000_012_000 }),
])} />)
expect(screen.getByText('pnpm run build')).toBeDefined()
expect(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }).getAttribute('aria-expanded')).toBe('true')
})
it('clearing drops an expanded settled panel with its rows', () => {
const observe = vi.fn(() => () => {})
render(<JobsSection {...props(
[outputJob({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 })],
observe,
)} />)
// Nothing live: the tail is open; expand the settled row's output panel.
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'settled work') }))
expect(observe).toHaveBeenCalledWith(SESSION, 'bash-2')
fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] }))
expect(screen.queryByText('settled work')).toBeNull()
expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'settled work') })).toBeNull()
})
it('shows a settled duration and ticks a live one', () => {
vi.useFakeTimers({ now: 1_700_000_020_000 })
render(<JobsSection {...props([
job({ startedAt: 1_700_000_015_000 }),
job({ id: 'bash-2' as JobView['id'], status: 'completed', startedAt: 1_700_000_000_000, finishedAt: 1_700_000_012_000 }),
job({ id: 'bash-3' as JobView['id'], status: 'completed', startedAt: 1_699_996_200_000, finishedAt: 1_700_000_000_000 }),
job({ id: 'bash-4' as JobView['id'], status: 'completed', startedAt: 1_699_999_900_000, finishedAt: 1_699_999_972_000 }),
])} />)
fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') }))
expect(screen.getByText('5秒')).toBeDefined()
expect(screen.getByText('12秒')).toBeDefined()
expect(screen.getByText('1小时3分')).toBeDefined()
expect(screen.getByText('1分12秒')).toBeDefined()
act(() => { vi.advanceTimersByTime(1_000) })
expect(screen.getByText('6秒')).toBeDefined()
})
it('lists rows with kind, label, and detail-or-status', () => {
render(<JobsSection {...props([
outputJob(),
outputJob({ id: 'bash-2' as JobView['id'], status: 'failed', detail: 'exit code: 3', finishedAt: 1_700_000_002_000 }),
])} />)
fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }))
const list = screen.getByRole('list')
const items = within(list).getAllByRole('listitem')
// The section line is a listitem too now: live row, section, settled row.
expect(items).toHaveLength(3)
expect(items[0]?.textContent).toContain('pnpm run build')
// A live row's second line is kind · duration; the status word only
// appears through a detail (none while running).
expect(items[0]?.textContent).toMatch(/小时|分|秒/)
expect(items[2]?.textContent).toContain('exit code: 3')
})
it('orders live rows first by latest start and settled rows newest-first with tie-breaks', () => {
const settled = (id: string, label: string, startedAt: number, finishedAt?: number): JobView =>
job({
id: id as JobView['id'],
label,
status: 'completed',
startedAt,
...finishedAt !== undefined ? { finishedAt } : {},
})
render(<JobsSection {...props([
settled('bash-a', 'settled-a', 10, 100),
settled('bash-c', 'settled-c', 80, 100),
settled('bash-b', 'settled-b', 90),
settled('bash-e', 'settled-e', 95, 50),
settled('bash-d', 'settled-d', 10, 200),
job({ id: 'bash-l1' as JobView['id'], label: 'live-1', startedAt: 5 }),
job({ id: 'bash-l2' as JobView['id'], label: 'live-2', startedAt: 3 }),
])} />)
fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '5') }))
const labels = within(screen.getByRole('list'))
.getAllByRole('listitem')
.map(item => item.querySelector('[data-job-label]')?.textContent)
.filter((label): label is string => label != null)
expect(labels).toEqual([
'live-1', 'live-2', 'settled-d', 'settled-a', 'settled-c', 'settled-b', 'settled-e',
])
expect(screen.getAllByText(`bash · ${zh['status.completed']}`).length).toBeGreaterThan(0)
})
it('breaks a settled tie on start order so map iteration never decides it', () => {
render(<JobsSection {...props([
job({ id: 'bash-2' as JobView['id'], label: 'second', status: 'completed', startedAt: 1_700_000_000_000 + 10, finishedAt: 1_700_000_000_000 + 100 }),
job({ id: 'bash-1' as JobView['id'], label: 'first', status: 'completed', startedAt: 1_700_000_000_000, finishedAt: 1_700_000_000_000 + 100 }),
])} />)
expect(within(screen.getByRole('list')).getAllByRole('listitem').map(row => row.querySelector('[data-job-label]')?.textContent).filter(label => label !== undefined))
.toEqual(['first', 'second'])
})
it('prefers the producer detail over the generic status word', () => {
render(<JobsSection {...props([
job({ status: 'killed', detail: 'signal: SIGTERM', finishedAt: 1_700_000_000_000 + 2_000 }),
])} />)
expect(within(screen.getByRole('list')).getByText('bash · signal: SIGTERM')).toBeDefined()
})
it('renders settled status words and every lifecycle indicator', () => {
render(<JobsSection {...props([
job({ id: 'bash-1' as JobView['id'], label: 'a', status: 'running' }),
job({ id: 'bash-2' as JobView['id'], label: 'b', status: 'stopping' }),
job({ id: 'bash-3' as JobView['id'], label: 'c', status: 'completed', finishedAt: 1_700_000_000_000 }),
job({ id: 'bash-4' as JobView['id'], label: 'd', status: 'killed', finishedAt: 1_700_000_000_000 }),
job({ id: 'bash-5' as JobView['id'], label: 'e', status: 'failed', finishedAt: 1_700_000_000_000 }),
])} />)
fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '3') }))
for (const word of ['已完成', '已取消', '已失败']) {
expect(within(screen.getByRole('list')).getByText(`bash · ${word}`)).toBeDefined()
}
expect([...screen.getByRole('list').querySelectorAll('li [data-state]')].map(node => node.getAttribute('data-state')))
.toEqual(['ongoing', 'warning', 'done', 'warning', 'error'])
})
it('marks a job that finished with a nonzero exit code with the warning dot', () => {
render(<JobsSection {...props([
job({ id: 'bash-1' as JobView['id'], label: 'a', status: 'completed', exitCode: 71, detail: 'exit code: 71', finishedAt: 1_700_000_000_003 }),
job({ id: 'bash-2' as JobView['id'], label: 'b', status: 'completed', exitCode: 0, detail: 'exit code: 0', finishedAt: 1_700_000_000_002 }),
job({ id: 'bash-3' as JobView['id'], label: 'c', status: 'completed', finishedAt: 1_700_000_000_001 }),
])} />)
expect([...screen.getByRole('list').querySelectorAll('li [data-state]')].map(node => node.getAttribute('data-state')))
.toEqual(['warning', 'done', 'done'])
expect(screen.getByText('bash · exit code: 71')).toBeDefined()
})
it('keeps the trailing column on a row without output, with no chevron and no row button', () => {
const view = render(<JobsSection {...props([job({ status: 'completed', finishedAt: 1_700_000_000_001 })])} />)
const line = view.container.querySelector('[data-job-row]') as HTMLElement
expect(within(line).queryByRole('button')).toBeNull()
expect(line.lastElementChild?.getAttribute('aria-hidden')).toBe('true')
expect(line.lastElementChild?.childElementCount).toBe(0)
})
it('places the fold chevron after the settled count', () => {
render(<JobsSection {...props([job({ status: 'completed', finishedAt: 1_700_000_000_001 })])} />)
const toggle = screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })
expect(toggle.lastElementChild?.tagName.toLowerCase()).toBe('svg')
expect(toggle.firstChild?.nodeType).toBe(Node.TEXT_NODE)
})
})
describe('JobsSection group folds', () => {
/** Live jobs named `live-<n>`, a higher n started later. */
const live = (count: number): JobView[] => Array.from({ length: count }, (_, index) =>
outputJob({ id: `live-${index}` as JobView['id'], label: `live-${index}`, startedAt: 1_700_000_000_000 + index }))
/** Settled jobs named `done-<n>`, a higher n finished later. */
const done = (count: number): JobView[] => Array.from({ length: count }, (_, index) =>
outputJob({ id: `done-${index}` as JobView['id'], label: `done-${index}`, status: 'completed', finishedAt: 1_700_000_100_000 + index }))
/** The list's items in order: a job's label, the settled header as `{…}`, a fold control as `[…]`. */
const items = (): string[] => within(screen.getByRole('list')).getAllByRole('listitem').map((item) => {
const control = item.querySelector('[data-fold]')
if (control !== null) return `[${control.textContent}]`
return item.querySelector('[data-job-label]')?.textContent ?? `{${item.querySelector('button')?.textContent ?? ''}}`
})
const folds = (): HTMLElement[] => [...document.querySelectorAll<HTMLElement>('[data-fold]')]
const settledToggle = (count: number): HTMLElement => screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', String(count)) })
it('shows six live rows in full and holds two back from seven, behind the group fold control before the settled header', () => {
const six = render(<JobsSection {...props([...live(6), ...done(1)])} />)
expect(items()).toEqual(['live-5', 'live-4', 'live-3', 'live-2', 'live-1', 'live-0', '{已结束 1}'])
six.unmount()
render(<JobsSection {...props([...live(7), ...done(1)])} />)
// The most recently started rows stay; the control is the group's last row, an item of the list.
expect(items()).toEqual(['live-6', 'live-5', 'live-4', 'live-3', 'live-2', '[显示其余 2 个运行中]', '{已结束 1}'])
const control = folds()[0] as HTMLElement
expect([control.getAttribute('aria-label'), control.getAttribute('aria-expanded')]).toEqual(['显示其余 2 个运行中(运行中的后台任务)', 'false'])
fireEvent.click(control)
expect(items()).toEqual(['live-6', 'live-5', 'live-4', 'live-3', 'live-2', 'live-1', 'live-0', '[收起]', '{已结束 1}'])
expect([folds()[0]?.getAttribute('aria-label'), folds()[0]?.getAttribute('aria-expanded')]).toEqual(['收起(运行中的后台任务)', 'true'])
fireEvent.click(folds()[0] as HTMLElement)
expect(items()).toHaveLength(7)
})
it('folds the open settled group on its own, and offers no settled control while the group is closed', () => {
render(<JobsSection {...props([...live(7), ...done(8)])} />)
// Live work keeps the settled group closed: only the live group has a control.
expect(folds().map(control => control.textContent)).toEqual(['显示其余 2 个运行中'])
fireEvent.click(settledToggle(8))
expect(items().slice(6)).toEqual(['{已结束 8}', 'done-7', 'done-6', 'done-5', 'done-4', 'done-3', '[显示其余 3 个已结束]'])
const settled = folds()[1] as HTMLElement
expect(settled.getAttribute('aria-label')).toBe('显示其余 3 个已结束(已结束的后台任务)')
fireEvent.click(settled)
// Each control folds only its own group.
expect(items()).toEqual([
'live-6', 'live-5', 'live-4', 'live-3', 'live-2', '[显示其余 2 个运行中]',
'{已结束 8}', 'done-7', 'done-6', 'done-5', 'done-4', 'done-3', 'done-2', 'done-1', 'done-0', '[收起]',
])
expect(folds()[1]?.getAttribute('aria-label')).toBe('收起(已结束的后台任务)')
fireEvent.click(settledToggle(8))
expect(folds()).toHaveLength(1)
})
it('shows six settled rows in full, and folds the group to its limit again after a clear', () => {
const store = createJobsSectionStore().create()
const first = render(<JobsSection {...props(done(6), undefined, {}, undefined, undefined, store)} />)
expect(items()).toHaveLength(7)
expect(folds()).toHaveLength(0)
first.unmount()
const second = render(<JobsSection {...props(done(9), undefined, {}, undefined, undefined, store)} />)
fireEvent.click(folds()[0] as HTMLElement)
expect(store.getSnapshot().unfolded).toEqual({ live: false, settled: true })
fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] }))
expect(store.getSnapshot().unfolded).toEqual({ live: false, settled: false })
second.unmount()
// Rows that settle after the clear fold at the limit again.
const later = Array.from({ length: 7 }, (_, index) => outputJob({
id: `later-${index}` as JobView['id'], label: `later-${index}`, status: 'completed', finishedAt: 1_700_000_200_000 + index,
}))
render(<JobsSection {...props([...done(9), ...later], undefined, {}, undefined, undefined, store)} />)
expect(items()).toEqual(['{已结束 7}', 'later-6', 'later-5', 'later-4', 'later-3', 'later-2', '[显示其余 2 个已结束]'])
})
it('keeps a group unfolded when the section mounts again for the same Session', () => {
const store = createJobsSectionStore().create()
const first = render(<JobsSection {...props(live(8), undefined, {}, undefined, undefined, store)} />)
fireEvent.click(folds()[0] as HTMLElement)
first.unmount()
render(<JobsSection {...props(live(8), undefined, {}, undefined, undefined, store)} />)
expect(items()).toHaveLength(9)
expect(folds()[0]?.getAttribute('aria-expanded')).toBe('true')
})
it('stops observing an expanded row that folds out of the list, and observes it again once it shows', () => {
const stop = vi.fn()
const observe = vi.fn(() => stop)
render(<JobsSection {...props(live(7), observe)} />)
fireEvent.click(folds()[0] as HTMLElement)
// live-0 started first, so the fold holds it back.
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'live-0') }))
expect(observe).toHaveBeenCalledExactlyOnceWith(SESSION, 'live-0')
fireEvent.click(folds()[0] as HTMLElement)
expect(stop).toHaveBeenCalledTimes(1)
expect(screen.queryByText('live-0')).toBeNull()
fireEvent.click(folds()[0] as HTMLElement)
expect(observe).toHaveBeenCalledTimes(2)
expect(screen.getByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'live-0') })).toBeDefined()
})
it('stops observing an expanded settled row while its group is closed', () => {
const stop = vi.fn()
const observe = vi.fn(() => stop)
render(<JobsSection {...props(done(2), observe)} />)
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'done-1') }))
expect(observe).toHaveBeenCalledExactlyOnceWith(SESSION, 'done-1')
fireEvent.click(settledToggle(2))
expect(stop).toHaveBeenCalledTimes(1)
})
it.each(Object.entries({ zh, en }))('names each fold control with its visible text first in %s', (_locale, copy) => {
for (const group of ['live', 'settled'] as const) {
for (const label of [copy[`${group}.more`].replace('{count}', '3'), copy['fold.less']]) {
expect(copy[`${group}.foldName`].replace('{label}', label).startsWith(label)).toBe(true)
}
}
})
})
describe('JobsSection observation', () => {
it('marks killed rows, renders every output line unfolded, and copies the command', async () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } })
const lines = Array.from({ length: 24 }, (_value, index) => `line ${index + 1}`).join('\n')
const view: ObservedJob = {
jobId: 'bash-1' as JobView['id'],
text: lines,
gapBefore: false,
streaming: false,
}
render(<JobsSection {...props(
[outputJob({ status: 'killed', finishedAt: 1_700_000_001_000 })],
undefined,
{ 'bash-1': view },
)} />)
expect(screen.getByText(`bash · ${zh['status.killed']}`)).toBeDefined()
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }))
// The panel scrolls instead of folding: every line renders, no fold control.
expect(screen.getByText('line 1')).toBeDefined()
expect(screen.getByText('line 24')).toBeDefined()
expect(screen.queryByRole('button', { name: zh['terminal.expandAria'].replace('{n}', '8') })).toBeNull()
// The panel draws no state dot or label of its own — the row carries it.
expect(screen.queryByText(zh['terminal.done'])).toBeNull()
// The copy control carries the command, not the output.
await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['terminal.copy'] })) })
expect(writeText).toHaveBeenCalledWith('pnpm run build')
})
it('starts observing on expand with the session identity, renders the live text, and stops on collapse', () => {
const stop = vi.fn()
const observe = vi.fn(() => stop)
const view: ObservedJob = {
jobId: 'bash-1' as JobView['id'],
text: 'compiling…\n',
gapBefore: false,
streaming: true,
}
render(<JobsSection {...props([outputJob()], observe, { 'bash-1': view })} />)
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }))
expect(observe).toHaveBeenCalledWith(SESSION, 'bash-1')
expect(screen.getByText('compiling…')).toBeDefined()
fireEvent.click(screen.getByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'pnpm run build') }))
expect(stop).toHaveBeenCalledTimes(1)
})
it('renders a running panel with the prompt alone for a live row whose output has not arrived', () => {
const view: ObservedJob = {
jobId: 'bash-1' as JobView['id'],
text: '',
gapBefore: false,
streaming: true,
}
render(<JobsSection {...props([job()], undefined, { 'bash-1': view })} />)
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }))
expect(screen.getByRole('list').querySelector('[data-running]')).not.toBeNull()
expect(screen.queryByText(zh['terminal.noOutput'])).toBeNull()
})
it('surfaces retention gaps and stream failures above the panel', () => {
const view: ObservedJob = {
jobId: 'bash-1' as JobView['id'],
text: 'tail only',
gapBefore: true,
streaming: false,
error: 'connection lost',
}
render(<JobsSection {...props([outputJob()], undefined, { 'bash-1': view })} />)
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }))
expect(screen.getByText(zh['output.gap'])).toBeDefined()
expect(screen.getByText('实时输出流中断:connection lost')).toBeDefined()
})
it('folds an expanded panel whose row left the roster', () => {
const stop = vi.fn()
// One stable observe identity across renders, as the inject face provides.
const observe = () => stop
const { rerender } = render(<JobsSection {...props([outputJob()], observe)} />)
fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }))
rerender(<JobsSection {...props([outputJob({ id: 'bash-2' as JobView['id'], label: 'other' })], observe)} />)
expect(stop).toHaveBeenCalledTimes(1)
expect(screen.queryByRole('button', { name: zh['row.collapseAria'].replace('{label}', 'other') })).toBeNull()
})
})
describe('JobsSection human kill', () => {
const stopTitle = (label: string): string => zh['kill.stopAria'].replace('{label}', label)
it('offers the stop control only on running rows', () => {
render(<JobsSection {...props([
job(),
job({ id: 'bash-2' as JobView['id'], label: 'done', status: 'completed', finishedAt: 1_700_000_100_000 }),
])} />)
expect(screen.getByRole('button', { name: stopTitle('pnpm run build') })).toBeDefined()
expect(screen.queryByRole('button', { name: stopTitle('done') })).toBeNull()
})
it('arms on the first press and kills on the confirming press', async () => {
const killJob = vi.fn(async () => true)
render(<JobsSection {...props([job()], undefined, {}, killJob)} />)
const stop = screen.getByRole('button', { name: stopTitle('pnpm run build') })
fireEvent.click(stop)
expect(killJob).not.toHaveBeenCalled()
expect(stop.getAttribute('data-kill-state')).toBe('armed')
expect(screen.getByRole('button', { name: zh['kill.confirm'] })).toBe(stop)
// The armed step is legible without hover: the button carries the label.
expect(stop.textContent).toBe(zh['kill.confirmAction'])
await act(async () => { fireEvent.click(stop) })
expect(killJob).toHaveBeenCalledWith(SESSION, 'bash-1')
// An admitted kill stays pending: the unary response and the jobs frames
// have no cross-carrier ordering, so only the authoritative frame (the row
// leaving the killable set) releases the control — never the response.
expect(stop.getAttribute('data-kill-state')).toBe('pending')
expect(stop.hasAttribute('disabled')).toBe(true)
})
it('an armed press disarms after the confirmation window', () => {
vi.useFakeTimers()
const killJob = vi.fn(async () => true)
render(<JobsSection {...props([job()], undefined, {}, killJob)} />)
const stop = screen.getByRole('button', { name: stopTitle('pnpm run build') })
fireEvent.click(stop)
expect(stop.getAttribute('data-kill-state')).toBe('armed')
act(() => { vi.advanceTimersByTime(3_000) })
expect(stop.getAttribute('data-kill-state')).toBe('idle')
expect(killJob).not.toHaveBeenCalled()
})
it('a rejected kill shows its hint and then resets', async () => {
// Fake timers from the start so the failed-hint reset arms on the fake clock.
vi.useFakeTimers()
const killJob = vi.fn(async () => false)
render(<JobsSection {...props([job()], undefined, {}, killJob)} />)
const stop = screen.getByRole('button', { name: stopTitle('pnpm run build') })
fireEvent.click(stop)
await act(async () => { fireEvent.click(stop) })
expect(stop.getAttribute('data-kill-state')).toBe('failed')
expect(screen.getByRole('button', { name: zh['kill.failed'] })).toBe(stop)
act(() => { vi.advanceTimersByTime(4_000) })
expect(stop.getAttribute('data-kill-state')).toBe('idle')
})
it('arming a second row disarms the first', () => {
render(<JobsSection {...props([
job(),
job({ id: 'bash-2' as JobView['id'], label: 'pnpm run watch' }),
])} />)
const first = screen.getByRole('button', { name: stopTitle('pnpm run build') })
fireEvent.click(first)
expect(first.getAttribute('data-kill-state')).toBe('armed')
const second = screen.getByRole('button', { name: stopTitle('pnpm run watch') })
fireEvent.click(second)
expect(second.getAttribute('data-kill-state')).toBe('armed')
expect(first.getAttribute('data-kill-state')).toBe('idle')
})
it('a kill resolving after another row armed leaves the newer phase alone', async () => {
let resolveKill!: (ok: boolean) => void
const killJob = vi.fn(() => new Promise<boolean>((resolve) => { resolveKill = resolve }))
render(<JobsSection {...props([
job(),
job({ id: 'bash-2' as JobView['id'], label: 'pnpm run watch' }),
], undefined, {}, killJob)} />)
const first = screen.getByRole('button', { name: stopTitle('pnpm run build') })
fireEvent.click(first)
fireEvent.click(first)
expect(killJob).toHaveBeenCalledTimes(1)
// While the first kill is in flight, the user arms the second row; the
// late resolution must not clobber that newer phase.
const second = screen.getByRole('button', { name: stopTitle('pnpm run watch') })
fireEvent.click(second)
expect(second.getAttribute('data-kill-state')).toBe('armed')
await act(async () => { resolveKill(false) })
expect(second.getAttribute('data-kill-state')).toBe('armed')
expect(first.getAttribute('data-kill-state')).toBe('idle')
})
it('clears an armed phase whose row stopped being killable', () => {
const { rerender } = render(<JobsSection {...props([job()])} />)
const stop = screen.getByRole('button', { name: stopTitle('pnpm run build') })
fireEvent.click(stop)
expect(stop.getAttribute('data-kill-state')).toBe('armed')
rerender(<JobsSection {...props([job({ status: 'stopping' })])} />)
// The stopping row offers no kill control any more, and the stale phase is gone.
expect(screen.queryByRole('button', { name: stopTitle('pnpm run build') })).toBeNull()
expect(document.querySelector('[data-kill-state]')).toBeNull()
})
it('omits the stop control without job/kill access', () => {
const view = render(<JobsSection {...props([job({ status: 'running' })], undefined, undefined, undefined, undefined, undefined, false)} />)
expect(view.getByText('pnpm run build')).toBeTruthy()
expect(view.container.querySelector('[data-kill-state]')).toBeNull()
})
})
it('renders the Russian settled-count copy', () => {
const translate: JobsSectionProps['t'] = makeTranslate(ru)
render(<JobsSection {...props([job({ status: 'completed', finishedAt: 1_700_000_003_000 })])} t={translate} />)
expect(screen.getByRole('button', { name: ru['section.settledCount'].replace('{count}', '1') })).toBeDefined()
})
describe('JobsSection hover', () => {
it('shows the kind, state, and duration without the command in a hover card after 500ms, and the kind and state to assistive technology', () => {
vi.useFakeTimers({ now: 1_700_000_010_000 })
vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: query === '(any-hover: hover)' })))
try {
const view = render(<JobsSection {...props([outputJob()])} />)
const row = view.container.querySelector<HTMLElement>('[data-job-row]')!
const button = within(row).getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })
expect(document.getElementById(button.getAttribute('aria-describedby') ?? '')?.textContent).toBe('bash · 运行中')
const anchor = row.parentElement as HTMLElement
fireEvent.pointerEnter(anchor, { pointerType: 'mouse' })
act(() => { vi.advanceTimersByTime(499) })
expect(document.querySelector('[data-session-panel-details]')).toBeNull()
act(() => { vi.advanceTimersByTime(1) })
const card = document.querySelector('[data-session-panel-details]') as HTMLElement
expect([...card.children].map(child => child.textContent)).toEqual(['bash', '运行中', '10秒'])
} finally {
vi.useRealTimers()
}
})
it('keeps the hover card closed while the pointer rests on the stop control, and closes an open one there', () => {
vi.useFakeTimers({ now: 1_700_000_010_000 })
vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: query === '(any-hover: hover)' })))
try {
const view = render(<JobsSection {...props([job()])} />)
const anchor = (view.container.querySelector<HTMLElement>('[data-job-row]')!).parentElement as HTMLElement
const stop = screen.getByRole('button', { name: zh['kill.stopAria'].replace('{label}', 'pnpm run build') })
// Entering the row at the stop control reaches the anchor first, then the control.
fireEvent.pointerEnter(anchor, { pointerType: 'mouse' })
fireEvent.pointerEnter(stop, { pointerType: 'mouse' })
act(() => { vi.advanceTimersByTime(1000) })
expect(document.querySelector('[data-session-panel-details]')).toBeNull()
expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe(zh['kill.stop'])
fireEvent.pointerLeave(stop, { pointerType: 'mouse' })
fireEvent.pointerLeave(anchor, { pointerType: 'mouse' })
act(() => { vi.advanceTimersByTime(1000) })
// A card the row opened closes once the pointer reaches the stop control.
fireEvent.pointerEnter(anchor, { pointerType: 'mouse' })
act(() => { vi.advanceTimersByTime(500) })
expect(document.querySelector('[data-session-panel-details]')).not.toBeNull()
fireEvent.pointerEnter(stop, { pointerType: 'mouse' })
act(() => { vi.advanceTimersByTime(1000) })
expect(document.querySelector('[data-session-panel-details]')).toBeNull()
} finally {
vi.useRealTimers()
}
})
it('reveals a clipped command on row hover instead of native titles, and names only the stop action in a tooltip after 500ms', () => {
vi.useFakeTimers()
try {
const view = render(<JobsSection {...props([job()])} />)
expect(view.container.querySelector('[title]')).toBeNull()
const label = view.container.querySelector<HTMLElement>('[data-job-label]')!
Object.defineProperty(label, 'scrollWidth', { value: 300, configurable: true })
Object.defineProperty(label, 'clientWidth', { value: 200, configurable: true })
const row = label.closest<HTMLElement>('[data-job-row]')!
fireEvent.pointerEnter(row)
expect([label.hasAttribute('data-marquee'), label.style.getPropertyValue('--dsh-marquee-range')]).toEqual([true, '100px'])
fireEvent.pointerLeave(row)
expect([label.hasAttribute('data-marquee'), label.style.getPropertyValue('--dsh-marquee-range')]).toEqual([false, ''])
const stop = screen.getByRole('button', { name: zh['kill.stopAria'].replace('{label}', 'pnpm run build') })
fireEvent.pointerEnter(stop, { pointerType: 'mouse' })
act(() => { vi.advanceTimersByTime(499) })
expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull()
act(() => { vi.advanceTimersByTime(1) })
expect(screen.getByRole('tooltip', { hidden: true }).textContent).toBe(zh['kill.stop'])
} finally {
vi.useRealTimers()
}
})
})
@@ -0,0 +1,39 @@
/**
* Job row geometry as CSS text: CSS Modules resolve to class-name maps in the
* component suite, so only the stylesheet proves that the chevron leaves its
* presses to the row button, including once the open chevron rotates, and that
* a row keeps one 28px line.
*/
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
const css = readFileSync(fileURLToPath(new URL('../src/client/JobsSection.module.css', import.meta.url)), 'utf8')
function rule(selector: string): string {
const match = new RegExp(`(?:^|\\n)${selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*\\{([^}]*)\\}`).exec(css.replace(/\/\*[\s\S]*?\*\//g, ''))
if (match === null) throw new Error(`JobsSection.module.css has no ${selector} rule`)
return match[1] ?? ''
}
describe('JobsSection.module.css', () => {
it('lets presses on the chevron reach the row button beneath it', () => {
expect(rule('.chevron')).toMatch(/pointer-events:\s*none/)
expect(rule('.chevronOpen')).toMatch(/transform:\s*rotate\(180deg\)/)
})
it('keeps a job on one 28px line, with the stop target overhanging it', () => {
expect(rule('.rowLine')).toMatch(/min-height:\s*28px/)
expect(rule('.rowLine')).toMatch(/padding:\s*4px 6px/)
expect(rule('.label')).toMatch(/line-height:\s*20px/)
expect(rule('.stop')).toMatch(/height:\s*24px/)
expect(rule('.stop')).toMatch(/margin:\s*-2px -4px/)
})
it('keeps the 28px line while the stop control is armed, its pill filling the row padding', () => {
expect(rule('.stopArmed')).toMatch(/height:\s*20px/)
expect(rule('.stopArmed')).toMatch(/margin:\s*0;/)
expect(rule('.stopArmed')).toMatch(/padding:\s*0 6px/)
expect(rule('.stopLabel')).toMatch(/line-height:\s*18px/)
})
})
+7 -4
View File
@@ -8,20 +8,20 @@
"src"
],
"references": [
{
"path": "../../../vendor/cordis"
},
{
"path": "../../api/job-controller/tsconfig.client.json"
},
{
"path": "../../api/session-controller/tsconfig.client.json"
},
{
"path": "../../../vendor/cordis"
},
{
"path": "../locale/tsconfig.client.json"
},
{
"path": "../ui-conversation/tsconfig.client.json"
"path": "../store"
},
{
"path": "../ui-primitives"
@@ -32,6 +32,9 @@
{
"path": "../ui-session"
},
{
"path": "../ui-session-panel"
},
{
"path": "../ui-slots"
}
@@ -18,8 +18,8 @@
en: 33a5b39959a595c6
zh: efd1088e9f13ed67
/deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog:
en: 320dba9d3737458f
zh: efd132302c7e17f4
en: 07574e4640e01163
zh: cc3f074a6ec0a17d
/deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons:
en: fd3499ef403a0594
zh: 3a17727316d3c666
@@ -27,8 +27,8 @@
en: 7fed4894a6d0d568
zh: c22881bfcef2d4b6
/deepseek-ai-dsh-client-ui-primitives/use-this-package/localizing-copy:
en: 3fd7072b662eed0a
zh: 88c6c299c0a6f8cd
en: 90c17f874ec27b52
zh: 21bf452318578f03
/deepseek-ai-dsh-client-ui-primitives/understand-the-implementation:
en: 88448dce667337fe
zh: 5d9b6035191a0b08
+4 -3
View File
@@ -55,6 +55,7 @@ Check this table before writing a control in a feature package. A plugin cannot
| `SegmentedTabs` | Controlled equal-width tabs with a sliding indicator and Left/Right, Home, and End navigation. The caller supplies labels, tab/panel ids, and panel content. Default `size="md"` is 42px tall with a 4px inset; `size="sm"` is 34px tall with a 2px inset. |
| `Tag` | Read-only capsule badge; `tone` selects one of eight palettes. |
| `PathLabel` | Single-line file path with subdued directories, a primary filename, and the full path on hover. Fitting paths align left; clipped paths preserve their suffix with a left-edge fade that updates on path and size changes. |
| `MarqueeText`, `useHoverMarquee` | Single-line text that clips with an ellipsis at rest, and the hook that marquees it: spread the pointer handlers it returns onto the owning row, and while the pointer is on the row a clipped text travels at 30px/s to its far edge and holds there, fading the edges that still hide text; leaving returns it to the start at once. The stylesheet animates the travel, and the hook measures the overflow once per entry. `hold` keeps the text marqueed without the pointer, such as while the row's menu is open. Overflow of at most 8px, touch pointers, and text that fits stay put; reduced motion shows the far edge at once. |
| `StateDot` | Solid green `done`, amber `warning`, red `error`, and neutral-grey `idle` marks in a 10px slot, plus a tertiary-grey 14px rotating `ongoing` loader whose animations pin to document time zero on mount and on every animation restart, such as a list reorder, so every visible loader rotates in phase. `aria-hidden`, so the render site owns the name. `appearance="step"` shows a filled check for completion and a hollow pending circle. |
| `ConnectionIndicator` | Inline connection-recovery control across outage, retry, and recovered states. |
| `DisclosureRow` | 24px compact disclosure that lays title and content side by side. The header supplies tertiary at rest and secondary on hover; text and icons inherit it regardless of expandability or open state unless the caller supplies a feature-specific override. Semantic status colors remain explicit. Collapsed rows preview a down chevron on hover, and expanded rows keep an up chevron visible. `headerAccessory` places an independent action outside the disclosure target and shimmer; with an accessory, the title row shrinks to its content width. Memoized with shallow prop comparison; keep callbacks and React-node props stable when their content is unchanged. |
@@ -64,7 +65,7 @@ Check this table before writing a control in a feature package. A plugin cannot
| `Modal` | Centered dialog over a page mask. A nested dialog can intercept keys with `onKeyDownCapture` before document Escape handlers. The tint and dialog fade in while backdrop blur stays fully applied, honoring reduced motion. Set `backdropBlur={false}` when the caller already blurs the source page. `tone="warning"` places an amber warning icon in the title and removes the body's extra top margin; other dialogs retain their spacing. |
| `RiskConfirmation` | Sensitive action gated behind an explicit checkbox, using the shared warning-title layout. |
| `Tooltip` | Hover and keyboard-focus text anchored to a cloned child; optional `delayMs` controls hover delay and `focusDelayMs` controls keyboard-focus delay, both defaulting to 0 ms. Optional `portal` rendering escapes clipping containers and ancestor stacking contexts that cap the bubble's z-index. |
| `HoverCard`, `HoverCardGroup` | Readable, optionally copyable hover preview; a physical list can opt cards into shared first-display dwell and exclusive display. |
| `HoverCard`, `HoverCardGroup` | Readable, optionally copyable hover preview; a physical list can opt cards into shared first-display dwell and exclusive display. A compact card opens beside the anchor's end edge, or beside its start edge when it would cross the viewport's end and fits there, as for rows of a panel at the window's end; with room on neither side it opens below the anchor from the anchor's start edge, or above it without room below, so it does not cover the anchor; a card too tall for either stays inside the viewport, in its bottom end corner. CSS anchor positioning places it, so the card follows its anchor without script measurement; Firefox resolves the anchor without the transforms of its ancestors, so a compact card whose anchor sits under a transformed ancestor is misplaced there. |
| `DraggableImage` | Original-image gestures with explicit transfer and feedback callbacks. |
| `ImageLightbox` | Shared image modal with focus restoration and Escape dismissal. |
| `usePointerGrace` | Cancelable dismissal delay that lets the pointer cross the gap between a trigger and its card; pending timers are cleared on unmount. |
@@ -79,7 +80,7 @@ Check this table before writing a control in a feature package. A plugin cannot
| `UserTextRun`, `ReferenceChip` | Uninterpreted inline text and business-resolved reference labels or activation buttons. |
| `CommandText` | Selectable command or argument text; only horizontal overflow adds a named keyboard focus target. |
| `TerminalBlock`, `ReadBlock`, `DiffBlock`, `SearchBlock`, `WebBlock` | The agent-output card matching each tool-result intent. |
| `icons/*`, `FishLogo`, `BrandWordmark`, `ReferenceIconRegular`/`ReferenceIconMedium`, `LinkIconRegular`/`LinkIconMedium` | Glyphs and brand marks. `IconDragHandleOutlineRegular`/`Medium` draw a three-line grip for reordering. The thinking glyph keeps an inset orbit within its 16px view box. `IconAppsAddOutlineRegular`/`Medium`, the More launcher glyph, take `compact` to draw their tiles closer together at card size. Use `LinkIconMedium` for 14px clickable-link categories and known-site marks. |
| `icons/*`, `FishLogo`, `BrandWordmark`, `ReferenceIconRegular`/`ReferenceIconMedium`, `LinkIconRegular`/`LinkIconMedium` | Glyphs and brand marks. `IconDragHandleOutlineRegular`/`Medium` draw a three-line grip for reordering. `IconFilesDiffOutlineRegular`/`Medium` draw two stacked pages, the front one marked with a plus over a minus, for the changes across a set of files. The thinking glyph keeps an inset orbit within its 16px view box. `IconAppsAddOutlineRegular`/`Medium`, the More launcher glyph, take `compact` to draw their tiles closer together at card size. Use `LinkIconMedium` for 14px clickable-link categories and known-site marks. |
| `PermissionIconReadOnlyRegular`/`Medium`, `PermissionIconWorkspaceWriteRegular`/`Medium`, `PermissionIconFullAccessRegular`/`Medium`, `PermissionIconAutoReviewRegular`/`Medium` | Permission-mode glyphs for read-only, workspace-write, full-access, and auto-review choices. |
| `PluginArtworkTerminal`/`Loop`/`Subagent`/`Search`/`Default` | Fixed-palette 36×36 plugin artwork; `Terminal` supplies the light-blue prompt in plugin cards and sidebar guide entries. `Default` marks plugins without artwork of their own. Def ids are per-instance, so the same artwork repeats safely on one page. |
| `GuideArtworkBrowser`/`Files` | Fixed-palette 36×36 browser and folder artwork for sidebar guide entries. |
@@ -133,7 +134,7 @@ Explicit `./`, `../`, slash/backslash-rooted paths (including UNC), and Windows
The atoms cannot read the application locale, so every piece of user-facing copy arrives through required label props. `HoverCard`, `TerminalBlock`, `JsonTree`, `CodeBlock`, `MarkdownText`, `JsonBlock`, `ConnectionIndicator`, `Modal`, `DiffBlock`, `ReadBlock`, `SearchBlock`, `WebBlock`, and `ZoomControls` accept complete localized labels. The package owns no language fallback; omission fails typechecking, and each feature maps its typed `t` seat into the primitive's label interface.
`Menu.anchorRef` names a trigger rendered outside the component, including one attached later in the same commit or replaced between openings. Keyboard dismissal of an `autoFocus` menu restores the previously focused control while it remains connected. `anchorPoint` accepts client-viewport coordinates, matching `event.clientX`/`clientY` and `getBoundingClientRect()`. On Safari, opening the menu or changing the point converts these coordinates to the layout viewport once. CSS then handles zoom and panning without continuous viewport listeners or rectangle measurements. `Menu.contextual` positions from that point without the frame inset and closes on a right-click inside the popup. Contextual popups with no rendered `role="menuitem"` rows stay hidden, including when legacy Slots return no content. Structured `items` reserve an icon column per divider group; `footer` and each submenu calculate their own groups. A contextual `footer` with a leading separator uses that line instead of adding a second border. Opaque `children` retain their own layout; a legacy Slot after data rows keeps its declared leading separator. `exiting` retains an inert popup for its fade; `returnFocus` restores the original control after asynchronous preparation. `MenuSurface.phase` fades the material, direct content, and macOS backing separately so the material keeps blurring the page. `MENU_TRANSITION_MS` supplies both CSS timing and the popup lifecycle timers. Ordinary dropdowns open without the contextual preparation delay.
`Menu.anchorRef` names a trigger rendered outside the component, including one attached later in the same commit or replaced between openings. An open menu closes when another popup trigger (an `aria-haspopup` control outside it) is activated, including one that stops its pointer presses, such as the shared context-menu button; `isExternalTrigger` exempts the triggers a popup manages itself. Keyboard dismissal of an `autoFocus` menu restores the previously focused control while it remains connected. `anchorPoint` accepts client-viewport coordinates, matching `event.clientX`/`clientY` and `getBoundingClientRect()`. On Safari, opening the menu or changing the point converts these coordinates to the layout viewport once. CSS then handles zoom and panning without continuous viewport listeners or rectangle measurements. `Menu.contextual` positions from that point without the frame inset and closes on a right-click inside the popup. Contextual popups with no rendered `role="menuitem"` rows stay hidden, including when legacy Slots return no content. Structured `items` reserve an icon column per divider group; `footer` and each submenu calculate their own groups. A contextual `footer` with a leading separator uses that line instead of adding a second border. Opaque `children` retain their own layout; a legacy Slot after data rows keeps its declared leading separator. `exiting` retains an inert popup for its fade; `returnFocus` restores the original control after asynchronous preparation. `MenuSurface.phase` fades the material, direct content, and macOS backing separately so the material keeps blurring the page. `MENU_TRANSITION_MS` supplies both CSS timing and the popup lifecycle timers. Ordinary dropdowns open without the contextual preparation delay.
-----
+4 -3
View File
@@ -55,6 +55,7 @@ kind: "package-library"
| `SegmentedTabs` | 受控的等宽分段标签,支持滑动指示条及左/右方向键、Home、End 导航。调用方提供文案、标签与面板 id,以及面板内容。默认 `size="md"` 总高 42px、内边距 4px;`size="sm"` 总高 34px、内边距 2px。 |
| `Tag` | 只读胶囊徽章;`tone` 选择八种配色之一。 |
| `PathLabel` | 单行文件路径:目录使用弱化颜色,文件名使用主色,悬停可查看完整路径。空间足够时靠左显示;溢出时保留尾部并在左侧渐隐,路径或尺寸变化时更新。 |
| `MarqueeText`、`useHoverMarquee` | 静止时以省略号截断的单行文字,以及让它滚动显示的 hook:把 hook 返回的指针处理函数展开到所在的行上,指针停在行上时,被截断的文字以 30px/s 匀速移到末尾并停在那里,仍有文字被遮住的边缘渐隐;离开时立即回到开头。移动由样式表的动画完成,hook 每次进入只测量一次溢出宽度。`hold` 让文字在指针不在行上时也保持滚动显示,例如行的菜单打开期间。溢出不超过 8px、触摸指针以及放得下的文字都不滚动;减少动态效果时直接显示末尾。 |
| `StateDot` | 10px 槽内的绿色 `done`、琥珀色 `warning`、红色 `error`、中性灰色 `idle` 圆点,以及 tertiary 灰色 14px 旋转 `ongoing` loading,其动画在挂载时以及每次动画重启(如列表重排)时固定到文档时间零点,所以所有可见 loading 同相旋转。它是 `aria-hidden` 的,名称由渲染点提供。 `appearance="step"` 以实心勾表示完成、空心圆表示等待。 |
| `ConnectionIndicator` | 行内连接恢复控件,覆盖断线、重试与已恢复三种状态。 |
| `DisclosureRow` | 24px 紧凑折叠行,标题与内容左右排列。标题行默认使用 tertiary,悬停时使用 secondary;文字与图标继承该颜色,不受能否展开及开合状态影响,调用方可提供功能专属覆盖。语义状态色保持显式指定。收起时悬停预览向下箭头,展开后持续显示向上箭头。`headerAccessory` 将独立操作放在折叠触发区域和流光之外;有此操作时,标题行收窄到内容宽度。使用浅层 prop 比较进行 memo;内容未变时,保持回调与 React 节点 prop 的引用稳定。 |
@@ -64,7 +65,7 @@ kind: "package-library"
| `Modal` | 页面遮罩之上的居中对话框。嵌套对话框可通过 `onKeyDownCapture` 在文档级 Escape 处理器之前拦截按键。 色层与弹窗淡入,背景模糊始终完整生效,并遵循减少动态效果偏好。调用方已模糊源页面时设置 `backdropBlur={false}`。`tone="warning"` 在标题中显示橙色警告图标,并移除正文额外的顶部间距;其他弹窗的间距保持不变。 |
| `RiskConfirmation` | 以显式复选框把关的敏感操作确认,采用共用的警告标题布局。 |
| `Tooltip` | 锚定在克隆子元素上的悬停与键盘聚焦提示;可选的 `delayMs` 控制悬停延迟,`focusDelayMs` 控制键盘聚焦延迟,均默认为 0 毫秒。可通过 `portal` 渲染到外层,避免被容器裁剪,或受祖先层叠上下文限制其 z-index。 |
| `HoverCard`、`HoverCardGroup` | 可阅读、可选带复制按钮的悬停预览;物理列表可选择让卡片共享首次显示等待,并互斥显示。 |
| `HoverCard`、`HoverCardGroup` | 可阅读、可选带复制按钮的悬停预览;物理列表可选择让卡片共享首次显示等待,并互斥显示。紧凑卡片出现在锚点结束一侧;会超出视口结束边缘、而开始一侧放得下时出现在开始一侧,例如窗口末端面板中的行;两侧都放不下时出现在锚点下方,与锚点的开始边缘对齐,下方放不下则出现在上方,因此不会盖住锚点;高到上下都放不下的卡片留在视口内,位于底部结束一角。它由 CSS 锚点定位放置,卡片跟随锚点时不需要脚本测量;Firefox 解析锚点位置时不计入祖先元素的 transform,锚点位于带 transform 的祖先之内时,紧凑卡片在 Firefox 中的位置会偏移。 |
| `DraggableImage` | 通过显式传递与反馈回调提供原图拖放。 |
| `ImageLightbox` | 共享图片浮层,支持焦点恢复与 Esc 关闭。 |
| `usePointerGrace` | 可取消的延迟关闭,让指针能够跨越触发控件与卡片间的空隙;卸载时清除待执行定时器。 |
@@ -79,7 +80,7 @@ kind: "package-library"
| `UserTextRun`、`ReferenceChip` | 不做解析的行内文本,以及业务已解析的引用标签或激活按钮。 |
| `CommandText` | 可选中的命令或参数文本;仅横向溢出时添加具名的键盘聚焦目标。 |
| `TerminalBlock`、`ReadBlock`、`DiffBlock`、`SearchBlock`、`WebBlock` | 与各类工具结果意图对应的 agent 输出卡片。 |
| `icons/*`、`FishLogo`、`BrandWordmark`、`ReferenceIconRegular`/`ReferenceIconMedium`、`LinkIconRegular`/`LinkIconMedium` | 字形与品牌标识。`IconDragHandleOutlineRegular`/`Medium` 以三条横线表示可拖动的排序手柄。思考图标的轨道在 16px 视口内保留内边距。“更多”入口使用的 `IconAppsAddOutlineRegular`/`Medium` 接受 `compact`,在卡片尺寸下让方块更靠近。`LinkIconMedium` 用于 14px 的可点击链接分类及已知站点标记。 |
| `icons/*`、`FishLogo`、`BrandWordmark`、`ReferenceIconRegular`/`ReferenceIconMedium`、`LinkIconRegular`/`LinkIconMedium` | 字形与品牌标识。`IconDragHandleOutlineRegular`/`Medium` 以三条横线表示可拖动的排序手柄。`IconFilesDiffOutlineRegular`/`Medium` 画两页叠放的文件,前页带上加下减,表示一组文件的变更。思考图标的轨道在 16px 视口内保留内边距。“更多”入口使用的 `IconAppsAddOutlineRegular`/`Medium` 接受 `compact`,在卡片尺寸下让方块更靠近。`LinkIconMedium` 用于 14px 的可点击链接分类及已知站点标记。 |
| `PermissionIconReadOnlyRegular`/`Medium`、`PermissionIconWorkspaceWriteRegular`/`Medium`、`PermissionIconFullAccessRegular`/`Medium`、`PermissionIconAutoReviewRegular`/`Medium` | 只读、工作区写入、完全访问与自动审查选项使用的权限模式图形。 |
| `PluginArtworkTerminal`/`Loop`/`Subagent`/`Search`/`Default` | 固定配色的 36×36 插件插画;`Terminal` 为插件卡片和侧边栏开始页入口提供浅蓝色提示符。`Default` 用于没有自有插画的插件。def id 按实例生成,同一插画可在一页中安全重复。 |
| `GuideArtworkBrowser`/`Files` | 固定配色的 36×36 浏览器与文件夹插画,用于侧栏引导入口。 |
@@ -133,7 +134,7 @@ kind: "package-library"
这些原子组件无法读取应用 locale,因此每段面向用户的文案都必须通过 label prop 提供。`HoverCard`、`TerminalBlock`、`JsonTree`、`CodeBlock`、`MarkdownText`、`JsonBlock`、`ConnectionIndicator`、`Modal`、`DiffBlock`、`ReadBlock`、`SearchBlock`、`WebBlock` 与 `ZoomControls` 接收完整的本地化 label。本包不拥有语言回退;遗漏会导致类型检查失败,各功能会把带类型的 `t` 席位映射到 primitive 的 label 接口。
`Menu` 的 `anchorRef` 指定组件外部的触发元素,支持同一次提交中稍后挂载的元素,以及在两次打开之间替换的元素。`autoFocus` 菜单通过键盘关闭时,会恢复到打开前仍在页面中的焦点控件。`anchorPoint` 接收客户端视口坐标,与 `event.clientX`/`clientY` 和 `getBoundingClientRect()` 一致。Safari 在菜单打开或坐标变化时将其转换为布局视口坐标一次,后续缩放和平移由 CSS 处理,不持续监听视口或测量矩形。`Menu.contextual` 从该指针位置定位而不避让顶部栏,并在弹窗内右键时关闭。右键弹窗没有实际渲染的 `role="menuitem"` 行时保持隐藏,包括旧 Slot 返回空内容的情况。结构化 `items` 按分隔线组预留图标栏;`footer` 与各子菜单独立计算分组。右键菜单的 `footer` 以分隔线开头时,直接使用该线,不再叠加边框。不透明的 `children` 保留原有布局;数据行后方的旧 Slot 保留其声明的首条分隔线。`exiting` 在淡出期间保留不可交互的弹窗;`returnFocus` 在异步准备后恢复原控件焦点。`MenuSurface.phase` 分别对材质层、直接内容和 macOS 背景淡入淡出,让材质层继续模糊页面。`MENU_TRANSITION_MS` 同时提供 CSS 动画与弹窗生命周期计时。普通下拉菜单不经过右键菜单的准备延迟。
`Menu` 的 `anchorRef` 指定组件外部的触发元素,支持同一次提交中稍后挂载的元素,以及在两次打开之间替换的元素。打开的菜单在它之外的另一个弹出触发器(带 `aria-haspopup` 的控件)被激活时关闭,包括会拦截自身指针按下的触发器,例如共享右键菜单的按钮;`isExternalTrigger` 认领的触发器由所属弹窗自行处理。`autoFocus` 菜单通过键盘关闭时,会恢复到打开前仍在页面中的焦点控件。`anchorPoint` 接收客户端视口坐标,与 `event.clientX`/`clientY` 和 `getBoundingClientRect()` 一致。Safari 在菜单打开或坐标变化时将其转换为布局视口坐标一次,后续缩放和平移由 CSS 处理,不持续监听视口或测量矩形。`Menu.contextual` 从该指针位置定位而不避让顶部栏,并在弹窗内右键时关闭。右键弹窗没有实际渲染的 `role="menuitem"` 行时保持隐藏,包括旧 Slot 返回空内容的情况。结构化 `items` 按分隔线组预留图标栏;`footer` 与各子菜单独立计算分组。右键菜单的 `footer` 以分隔线开头时,直接使用该线,不再叠加边框。不透明的 `children` 保留原有布局;数据行后方的旧 Slot 保留其声明的首条分隔线。`exiting` 在淡出期间保留不可交互的弹窗;`returnFocus` 在异步准备后恢复原控件焦点。`MenuSurface.phase` 分别对材质层、直接内容和 macOS 背景淡入淡出,让材质层继续模糊页面。`MENU_TRANSITION_MS` 同时提供 CSS 动画与弹窗生命周期计时。普通下拉菜单不经过右键菜单的准备延迟。
-----
Loaded 100 of 256 files, more files were not shown because too many files have changed in this diff. Show more