diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml index 83daa37ac0..1370e90833 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml @@ -9,8 +9,8 @@ en: 344bcc7e9825bbc8 zh: c1d0f4b54f5b3786 /agent-note-change-request-panel-and-worktree-sessions/decision: - en: 4695a1e4f8aa7a25 - zh: e17be0e36ea3eaa3 + en: a2da424833a8aa0a + zh: 9ab23d2e5bde31de /agent-note-change-request-panel-and-worktree-sessions/deferred: en: 32ef8af85f4d2f66 zh: b82b67f94346399e diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md index 32b6fb4edc..b729671744 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md @@ -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. diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md index 6e8438080c..d5fcf439c0 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md @@ -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 服务作为插件页中默认禁用的一个条目发布。 评审与工作树控件服务于同一个代码修改流程。统一插件入口让用户可以一次启用这些能力,无需根据底层包的拆分判断应该开启哪张卡片。包与两套工作树服务仍保持独立,分别负责会话开始前和对话中创建工作树的流程。 diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml b/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml index a661424786..2ef5bf0f10 100644 --- a/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml @@ -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 diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.md b/.agents/notes/implemented/feature/2026-11-05-session-panel.md index 7dbb92ce80..7ef1e8f306 100644 --- a/.agents/notes/implemented/feature/2026-11-05-session-panel.md +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.md @@ -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. diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md b/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md index de8e0914a5..5a2a4bada2 100644 --- a/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md @@ -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 中。 diff --git a/apps/web/tests/agent-preset-selection.e2e.ts b/apps/web/tests/agent-preset-selection.e2e.ts index 2a378530ab..2d2d675ae3 100644 --- a/apps/web/tests/agent-preset-selection.e2e.ts +++ b/apps/web/tests/agent-preset-selection.e2e.ts @@ -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"') diff --git a/apps/web/tests/agent-team-panel.e2e.ts b/apps/web/tests/agent-team-panel.e2e.ts index 869eda7fdc..7438bc86ce 100644 --- a/apps/web/tests/agent-team-panel.e2e.ts +++ b/apps/web/tests/agent-team-panel.e2e.ts @@ -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 { + 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 { + return (await showSessionPanel(page)).locator(SHARED_TASKS_SECTION) +} + async function openTeamSettings(page: Page, chinese = false): Promise { 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 => { + 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((resolve) => { + panel.evaluate(element => new Promise((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) }) }) diff --git a/apps/web/tests/anchored-panels.e2e.ts b/apps/web/tests/anchored-panels.e2e.ts index 5770d228c7..e62d618503 100644 --- a/apps/web/tests/anchored-panels.e2e.ts +++ b/apps/web/tests/anchored-panels.e2e.ts @@ -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' }, diff --git a/apps/web/tests/background-job-list.e2e.ts b/apps/web/tests/background-job-list.e2e.ts index fff8cd823d..f0d0ee013c 100644 --- a/apps/web/tests/background-job-list.e2e.ts +++ b/apps/web/tests/background-job-list.e2e.ts @@ -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(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('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(/^ - + + + + + {task.subject} + + + )} + content={renderFactorySlot('conversation.session.panel.details', { + title: task.subject, + lines: [t('hover.owner', { name: owner }), ...task.description ? [task.description] : []], + status: { state, label: status }, + })} + /> {expanded && (
{task.description &&

{task.description}

} @@ -78,35 +124,66 @@ function TaskRow({ task, rootId, expanded, onToggle, t }: Pick (state.projectionsBySession[sessionId]?.values.subagentCatalog?.length ?? 0) > 0) + const unfolded = useStore(state => state.unfolded) const [expandedTaskId, setExpandedTaskId] = useState(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 : ( -
{t('failure', { message: team.failure })}
- ) - if (tasks.length === 0) return failure === null ? null :
{failure}
+ 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 ( -
-

- - {t('tasks')} - {progressLabel(tasks, t)} -

- {failure} -
    - {tasks.map(task => ( - { setExpandedTaskId(current => current === task.id ? null : task.id) }} - t={t} - /> - ))} -
-
+
+ {team.failure !== undefined && ( +
{t('failure', { message: team.failure })}
+ )} + {tasks.length > 0 && ( + // Moving between rows swaps their hover cards without another dwell. + +
    + {tasks.map(task => ( + { setExpandedTaskId(current => current === task.id ? null : task.id) }} + renderFactorySlot={renderFactorySlot} + t={t} + /> + ))} +
+
+ )} + {foldable && renderFactorySlot('conversation.session.panel.fold', { + expanded: unfolded, + label, + name: t('list.foldName', { label }), + onToggle: () => { actions.unfoldedSet(!unfolded) }, + })} +
) } + +/** + * 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 {progress} +} diff --git a/packages/client/ui-agent-team/src/client/index.ts b/packages/client/ui-agent-team/src/client/index.ts index 23de9e7ee5..08484146ff 100644 --- a/packages/client/ui-agent-team/src/client/index.ts +++ b/packages/client/ui-agent-team/src/client/index.ts @@ -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' /** diff --git a/packages/client/ui-agent-team/src/client/locales.ts b/packages/client/ui-agent-team/src/client/locales.ts index f7bba69ff8..33fb6c330f 100644 --- a/packages/client/ui-agent-team/src/client/locales.ts +++ b/packages/client/ui-agent-team/src/client/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', diff --git a/packages/client/ui-agent-team/src/client/mount.ts b/packages/client/ui-agent-team/src/client/mount.ts index c2dec89b0a..c84e653564 100644 --- a/packages/client/ui-agent-team/src/client/mount.ts +++ b/packages/client/ui-agent-team/src/client/mount.ts @@ -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) + }) } diff --git a/packages/client/ui-agent-team/src/client/team-board-store.ts b/packages/client/ui-agent-team/src/client/team-board-store.ts new file mode 100644 index 0000000000..312f7d72e4 --- /dev/null +++ b/packages/client/ui-agent-team/src/client/team-board-store.ts @@ -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 { + 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 + }, + }, + }) +} diff --git a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts index 95011ef4cf..22def8176a 100644 --- a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts @@ -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() diff --git a/packages/client/ui-agent-team/tests/team-board.client.spec.tsx b/packages/client/ui-agent-team/tests/team-board.client.spec.tsx index f60eb99e4a..7f81bcc470 100644 --- a/packages/client/ui-agent-team/tests/team-board.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-board.client.spec.tsx @@ -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['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 ( +
+ {title !== undefined &&
{title}
} + {lines.map(line =>
{line}
)} + {status !== undefined &&
{status.label}
} + {facts.length > 0 &&
{facts.map(fact => {fact.label})}
} +
+ ) + } + const fold = input as PanelFoldProps + return +} + function bench(options: { projections?: Projections sessionId?: SessionId byId?: Record 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 = { useProjection: props.useProjection, t: props.t } + const view = render() + 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() - 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() - 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() + 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() + 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() + fireEvent.click(fold() as HTMLElement) + expect(store.getSnapshot()).toEqual({ unfolded: true }) + first.unmount() + render() + 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() 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() 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() - 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() + vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: query === '(any-hover: hover)' }))) + render() 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() }) }) diff --git a/packages/client/ui-agent-team/tsconfig.json b/packages/client/ui-agent-team/tsconfig.json index 429b9adac3..b5d6224ca9 100644 --- a/packages/client/ui-agent-team/tsconfig.json +++ b/packages/client/ui-agent-team/tsconfig.json @@ -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" }, diff --git a/packages/client/ui-jobs/README.i18n.yaml b/packages/client/ui-jobs/README.i18n.yaml index f6bb8ea61f..6da1b12ab5 100644 --- a/packages/client/ui-jobs/README.i18n.yaml +++ b/packages/client/ui-jobs/README.i18n.yaml @@ -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 diff --git a/packages/client/ui-jobs/README.md b/packages/client/ui-jobs/README.md index 04abc0f1d1..687b51cfff 100644 --- a/packages/client/ui-jobs/README.md +++ b/packages/client/ui-jobs/README.md @@ -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) ## 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
Implementation internals — click to expand -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.
@@ -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. ----- diff --git a/packages/client/ui-jobs/README.zh.md b/packages/client/ui-jobs/README.zh.md index 0f226d9973..9107a6cac2 100644 --- a/packages/client/ui-jobs/README.zh.md +++ b/packages/client/ui-jobs/README.zh.md @@ -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" ## 使用本包 -通过 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"
实现内幕——点击展开 -头部操作带里的一个 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)中的标准菜单项圆角;带底色运行行内的控件保留紧凑圆角。
@@ -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` 表面。 ----- diff --git a/packages/client/ui-jobs/package.json b/packages/client/ui-jobs/package.json index 299c2c4765..14f52837df 100644 --- a/packages/client/ui-jobs/package.json +++ b/packages/client/ui-jobs/package.json @@ -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" } diff --git a/packages/client/ui-jobs/src/client/JobListAction.module.css b/packages/client/ui-jobs/src/client/JobListAction.module.css deleted file mode 100644 index 6b72ce3241..0000000000 --- a/packages/client/ui-jobs/src/client/JobListAction.module.css +++ /dev/null @@ -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; -} diff --git a/packages/client/ui-jobs/src/client/JobListAction.tsx b/packages/client/ui-jobs/src/client/JobListAction.tsx deleted file mode 100644 index 803970716c..0000000000 --- a/packages/client/ui-jobs/src/client/JobListAction.tsx +++ /dev/null @@ -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 -} - -/** Full props for the session-header job-list action. */ -export type JobListActionProps = - PropsRuntime<'conversation.session.header.actions'> - & PropsLocale - & InjectFace - -/** 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): 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): 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): 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 -}) { - 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 = ( - - {duration} - - ) - const body = live - ? ( - <> - - - - {job.label} - - - {job.kind} - {detail !== undefined ? {detail} : null} - {durationCell} - - - {/* A live row is always observable: its output may still arrive. */} - - - - - ) - : ( - <> - - {job.kind} - {job.label} - {detail ?? status} - {durationCell} - {observable - ? ( - - - - ) - : 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 ( -
  • -
    - {observable - ? ( - - ) - : ( - - {body} - - )} - {kill !== undefined - ? ( - - ) - : null} -
    - {expanded && view !== undefined - ? ( -
    - {view.gapBefore ?
    {t('output.gap')}
    : null} - {view.error !== undefined - ?
    {t('output.error', { error: view.error })}
    - : null} - -
    - ) - : null} -
  • - ) -} - -/** - * 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 | undefined>(undefined) - const hoverCloseTimer = useRef | undefined>(undefined) - if (menuState.sessionId !== sessionId) setMenuState({ sessionId, mode: 'closed' }) - const [expandedKey, setExpandedKey] = useState(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(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>(() => new Set()) - // One kill affordance advances at a time: arming a row disarms any other. - const [killPhase, setKillPhase] = useState<{ key: string; state: Exclude } | undefined>(undefined) - const rootRef = useRef(null) - const triggerRef = useRef(null) - const countRef = useRef(null) - const menuRef = useRef(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): 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): 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): 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(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) => ( - { - 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 ( -
    - - - - {liveRows.length > 0 && } - {open - ? createPortal( - { changeOpen(true) }} - onFocusCapture={() => { changeOpen(true) }} - > -
      - {liveRows.length > 0 - ? - : null} - {liveRows.map(item)} - {settledRows.length > 0 - ? ( -
    • - - -
    • - ) - : null} - {settledExpanded ? settledRows.map(item) : null} -
    -
    , - document.body, - ) - : null} -
    - ) -} diff --git a/packages/client/ui-jobs/src/client/JobsSection.module.css b/packages/client/ui-jobs/src/client/JobsSection.module.css new file mode 100644 index 0000000000..1250827987 --- /dev/null +++ b/packages/client/ui-jobs/src/client/JobsSection.module.css @@ -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); +} diff --git a/packages/client/ui-jobs/src/client/JobsSection.tsx b/packages/client/ui-jobs/src/client/JobsSection.tsx new file mode 100644 index 0000000000..3449162cca --- /dev/null +++ b/packages/client/ui-jobs/src/client/JobsSection.tsx @@ -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 +} + +/** Full props for the Session panel's background-jobs section. */ +export type JobsSectionProps = + PropsRuntime<'conversation.session.panel.section'> + & PropsRenderFactories + & PropsLocale + & InjectFace + & PropsStore> + +/** Business face of the running dot on the Session panel toggle. */ +export type JobsRunningIndicatorInjected = Pick + +/** Full props of the running dot on the Session panel toggle. */ +export type JobsRunningIndicatorProps = + PropsRuntime<'conversation.session.panel.indicator'> + & PropsLocale + & InjectFace + +/** 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): 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): 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): 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 & { + 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 +}) { + 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(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 = ( + <> + + {job.label} + {`${job.kind} · ${state}`} + {duration} + + ) + // 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 ( +
  • + {/* The card leaves the command out: it can run to many lines, and the row's output panel shows it in full. */} + + {observable + ? ( + + ) + : {body}} + {kill !== undefined + ? ( + + + + ) + : null} + {/* The row button's overlay takes presses here too; a row without output keeps the column empty. */} + +
  • + )} + /> + {expanded && view !== undefined + ? ( +
    + {view.gapBefore ?
    {t('output.gap')}
    : null} + {view.error !== undefined + ?
    {t('output.error', { error: view.error })}
    + : null} + +
    + ) + : null} + + ) +} + +/** + * 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(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 } | 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) => ( + { + 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 ( +
  • + {renderFactorySlot('conversation.session.panel.fold', { + expanded: unfolded[group], + label, + name: t(`${group}.foldName`, { label }), + onToggle: () => { actions.unfoldedSet(group, !unfolded[group]) }, + })} +
  • + ) + } + + return ( + // Moving between rows swaps their hover cards without another dwell. + + {/* The section's heading names the region; a list name would repeat it. */} +
      + {shownLive.map(item)} + {liveFoldable ? fold('live', liveRows.length - FOLD_LIMIT) : null} + {settledRows.length > 0 + ? ( +
    • + + +
    • + ) + : null} + {shownSettled.map(item)} + {settledExpanded && settledFoldable ? fold('settled', settledRows.length - FOLD_LIMIT) : null} +
    +
    + ) +} + +/** + * 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 ( + + {t('indicator.running', { count: running })} + + ) +} diff --git a/packages/client/ui-jobs/src/client/index.ts b/packages/client/ui-jobs/src/client/index.ts index b4595f53cb..2e20caba1d 100644 --- a/packages/client/ui-jobs/src/client/index.ts +++ b/packages/client/ui-jobs/src/client/index.ts @@ -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)) } diff --git a/packages/client/ui-jobs/src/client/jobs-store.ts b/packages/client/ui-jobs/src/client/jobs-store.ts new file mode 100644 index 0000000000..7c540ba096 --- /dev/null +++ b/packages/client/ui-jobs/src/client/jobs-store.ts @@ -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 + /** 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 +} + +/** 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 { + 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 + }, + }, + }) +} diff --git a/packages/client/ui-jobs/src/client/locales.ts b/packages/client/ui-jobs/src/client/locales.ts index c968a08b5d..c34f762133 100644 --- a/packages/client/ui-jobs/src/client/locales.ts +++ b/packages/client/ui-jobs/src/client/locales.ts @@ -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 = { - '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 = { '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}', diff --git a/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts b/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts index 73092ce046..ee6ae6fb4d 100644 --- a/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-jobs/tests/browser-plugin.client.spec.ts @@ -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 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('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 () => { diff --git a/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx b/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx deleted file mode 100644 index df947f5931..0000000000 --- a/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx +++ /dev/null @@ -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 { - 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 { - return job({ output: { total: 12, earliest: 0 }, ...over }) -} - -function props( - jobs: readonly JobView[], - observe: JobListActionProps['observe'] = () => () => {}, - observed: Readonly> = {}, - killJob: JobListActionProps['killJob'] = async () => true, - watchRows: JobListActionProps['watchRows'] = () => () => {}, - mayKill = true, -): JobListActionProps { - const jobsState: JobsSnapshot = { rows: jobs.length > 0 ? { [SESSION]: jobs } : {}, observed } - function useJobs(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() - expect(screen.getByRole('button', { name: one, description: dictionary['section.live'] })).toBeDefined() - rerender() - expect(screen.getByRole('button', { name: one, description: dictionary['section.live'] })).toBeDefined() - rerender() - expect(screen.getByRole('button', { name: two, description: '' })).toBeDefined() - }) -}) - -describe('JobListAction visibility', () => { - it('renders nothing while the session sees no jobs', () => { - const { container } = render() - 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() - expect(watchRows).toHaveBeenCalledWith(SESSION) - expect(stop).not.toHaveBeenCalled() - unmount() - expect(stop).toHaveBeenCalledTimes(1) - }) - - it('counts live jobs on the trigger', () => { - render() - 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() - 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() - expect(screen.getByRole('button')).toBe(trigger) - expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull() - rerender() - 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() - 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() - const trigger = screen.getByRole('button') - const count = trigger.querySelector('[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() - const trigger = screen.getByRole('button') - const count = trigger.querySelector('[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() - const trigger = screen.getByRole('button') - trigger.querySelector('[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() - 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() - 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() - 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() - 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() - 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() - openList() - expect(view.container.querySelector('[data-kill-state]')).toBeNull() - }) - - it('pins pointer interaction so leaving cannot interrupt stop confirmation', () => { - vi.useFakeTimers() - render() - 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() - 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() - 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() - 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( 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() - pointer(screen.getByRole('button'), 'pointerover') - rerender() - advance(150) - expect(screen.queryByRole('list')).toBeNull() - const trigger = hoverOpen() - fireEvent.click(trigger) - rerender() - expect(screen.queryByRole('list')).toBeNull() - pointer(screen.getByRole('button'), 'pointerover') - rerender() - advance(150) - expect(vi.getTimerCount()).toBe(0) - rerender() - hoverOpen() - fireEvent.click(screen.getByRole('button', { name: '1 个后台任务' })) - rerender() - rerender() - expect(screen.queryByRole('list')).toBeNull() - }) -}) - -describe('JobListAction rows', () => { - it('renders a settled job without retained output as a static row', () => { - render() - 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() - 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() - 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() - 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() - 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() - 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() - 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() - 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() - 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() - 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() - openList() - expect(within(screen.getByRole('list')).getByText('signal: SIGTERM')).toBeDefined() - }) - - it('renders settled status words and every lifecycle indicator', () => { - render() - 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() - 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() - 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('[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(<>) - 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() - const trigger = screen.getByRole('button', { name: '1 个后台任务' }) - fireEvent.click(trigger) - const menu = screen.getByRole('list', { name: zh['list.aria'] }).closest('[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() - 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() - 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() - 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() - 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() - 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() - 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() - 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( 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() - openList() - fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) - rerender() - 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() - 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() - 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() - 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() - 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() - 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((resolve) => { resolveKill = resolve })) - render() - 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() - openList() - const stop = screen.getByTitle(stopTitle('pnpm run build')) - fireEvent.click(stop) - expect(stop.getAttribute('data-kill-state')).toBe('armed') - rerender() - // 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() - expect(screen.getByRole('button', { name: `Фоновые задачи: ${count}` })).toBeDefined() - view.rerender( ({ ...item, status: 'completed', finishedAt: 1_700_000_003_000 })))} t={translate} />) - expect(screen.getByRole('button', { name: `Фоновые задачи: ${count}` })).toBeDefined() -}) diff --git a/packages/client/ui-jobs/tests/jobs-section.client.spec.tsx b/packages/client/ui-jobs/tests/jobs-section.client.spec.tsx new file mode 100644 index 0000000000..a90eb6236f --- /dev/null +++ b/packages/client/ui-jobs/tests/jobs-section.client.spec.tsx @@ -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 { + 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 { + return job({ output: { total: 12, earliest: 0 }, ...over }) +} + +/** One Session's section store, as the registration mints it. */ +type SectionStore = ReturnType['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 ( +
    + {title !== undefined &&
    {title}
    } + {lines.map(line =>
    {line}
    )} + {status !== undefined &&
    {status.label}
    } + {facts.length > 0 &&
    {facts.map(fact => {fact.label})}
    } +
    + ) + } + const fold = input as PanelFoldProps + return +} + +/** Test-local selector hook over a framework-neutral store instance. */ +function hookOf(instance: { subscribe: (listener: () => void) => () => void; getSnapshot: () => T }) { + return function useSelector(select: (state: T) => S): S { + return select(useSyncExternalStore(instance.subscribe, instance.getSnapshot)) + } +} + +function props( + jobs: readonly JobView[], + observe: JobsSectionProps['observe'] = () => () => {}, + observed: Readonly> = {}, + 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(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 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 as JobsRunningIndicatorProps + return render() + } + + 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() + 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() + 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() + // 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() + 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() + 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() + 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() + fireEvent.click(screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') })) + fireEvent.click(screen.getByRole('button', { name: zh['section.clear'] })) + first.unmount() + render() + 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() + fireEvent.click(toggle()) + first.unmount() + render() + 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() + 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() + // 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() + 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() + 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() + 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() + 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() + expect(within(screen.getByRole('list')).getByText('bash · signal: SIGTERM')).toBeDefined() + }) + + it('renders settled status words and every lifecycle indicator', () => { + render() + 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() + 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() + 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() + 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-`, 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-`, 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('[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() + expect(items()).toEqual(['live-5', 'live-4', 'live-3', 'live-2', 'live-1', 'live-0', '{已结束 1}']) + six.unmount() + render() + // 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() + // 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() + expect(items()).toHaveLength(7) + expect(folds()).toHaveLength(0) + first.unmount() + const second = render() + 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() + 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() + fireEvent.click(folds()[0] as HTMLElement) + first.unmount() + render() + 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() + 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() + 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() + 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() + 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() + 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() + 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() + fireEvent.click(screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') })) + rerender() + 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() + 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() + 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() + 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() + 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() + 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((resolve) => { resolveKill = resolve })) + render() + 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() + const stop = screen.getByRole('button', { name: stopTitle('pnpm run build') }) + fireEvent.click(stop) + expect(stop.getAttribute('data-kill-state')).toBe('armed') + rerender() + // 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() + 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() + 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() + const row = view.container.querySelector('[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() + const anchor = (view.container.querySelector('[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() + expect(view.container.querySelector('[title]')).toBeNull() + const label = view.container.querySelector('[data-job-label]')! + Object.defineProperty(label, 'scrollWidth', { value: 300, configurable: true }) + Object.defineProperty(label, 'clientWidth', { value: 200, configurable: true }) + const row = label.closest('[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() + } + }) +}) diff --git a/packages/client/ui-jobs/tests/jobs-styles.client.spec.ts b/packages/client/ui-jobs/tests/jobs-styles.client.spec.ts new file mode 100644 index 0000000000..84025b76b4 --- /dev/null +++ b/packages/client/ui-jobs/tests/jobs-styles.client.spec.ts @@ -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/) + }) +}) diff --git a/packages/client/ui-jobs/tsconfig.json b/packages/client/ui-jobs/tsconfig.json index f5e1825084..aaf0919623 100644 --- a/packages/client/ui-jobs/tsconfig.json +++ b/packages/client/ui-jobs/tsconfig.json @@ -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" } diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 008c6b8907..9cc32a1ba4 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -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 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index cc25340659..c7745cac13 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -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. ----- diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 9ca3abc2ba..6fad582dde 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -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 动画与弹窗生命周期计时。普通下拉菜单不经过右键菜单的准备延迟。 ----- diff --git a/packages/client/ui-primitives/src/HoverCard.module.css b/packages/client/ui-primitives/src/HoverCard.module.css index e98ff29d69..176674d722 100644 --- a/packages/client/ui-primitives/src/HoverCard.module.css +++ b/packages/client/ui-primitives/src/HoverCard.module.css @@ -17,6 +17,48 @@ box-shadow: var(--dsw-shadow-lv3); } +/* A compact card sits beside its anchor's end edge with its top on the + anchor's top: the insets keep it 8px from the anchor and from the viewport's + edges. When that would cross the viewport, the first fallback that fits + places it: beside the start edge; on either side with its bottom at the + viewport's margin; then, with room on neither side, below the anchor from + the anchor's start edge, or above it, so the card does not cover its anchor. + A card too tall for that holds the viewport's bottom and end margins. + Chromium tries five fallbacks, so there the browser's own overflow shift + keeps such a card inside the viewport instead, against its edges. */ +.compact { + position-area: inline-end span-block-end; + inset: 0 8px 8px; + position-try-fallbacks: + flip-inline, + --dsh-hover-card-low, + --dsh-hover-card-low flip-inline, + --dsh-hover-card-below, + --dsh-hover-card-above, + --dsh-hover-card-held; +} + +@position-try --dsh-hover-card-low { + position-area: inline-end span-all; + align-self: end; +} + +@position-try --dsh-hover-card-below { + position-area: block-end span-inline-end; + inset: 8px 8px 8px 0; +} + +@position-try --dsh-hover-card-above { + position-area: block-start span-inline-end; + inset: 8px 8px 8px 0; +} + +@position-try --dsh-hover-card-held { + position-area: span-all; + justify-self: end; + align-self: end; +} + .copyable { cursor: pointer; } diff --git a/packages/client/ui-primitives/src/HoverCard.tsx b/packages/client/ui-primitives/src/HoverCard.tsx index bd727d0c85..1bf15d713e 100644 --- a/packages/client/ui-primitives/src/HoverCard.tsx +++ b/packages/client/ui-primitives/src/HoverCard.tsx @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react' +import { useCallback, useContext, useEffect, useId, useLayoutEffect, useRef, useState } from 'react' import type { CSSProperties, ReactNode, RefObject, SyntheticEvent } from 'react' import clsx from 'clsx' import { createPortal } from 'react-dom' @@ -16,15 +16,19 @@ const INLINE_PREVIEW_WIDTH = 300 const ANCHOR_GAP = 8 const VIEWPORT_MARGIN = 8 +/** Where the script places a card; a compact card has no coordinates, since the stylesheet anchors it. */ interface CardPosition { - left: number - top: number + left?: number + top?: number width?: number maxWidth?: number maxHeight?: number bridge?: { left: number; top: number; width: number; height: number } } +/** The position of every compact card: one value, so placing it again renders nothing. */ +const ANCHORED: CardPosition = {} + /** * Render an anchor with a hover-triggered preview card independently of nested tooltips. * Touch entry does not open a preview or intercept the anchor's action. @@ -32,9 +36,11 @@ interface CardPosition { * @param props.content - card content; the pointer may rest on it, so it is * readable and selectable, but it carries no dismissal affordance of its own. * @param props.openDelayMs - hover dwell before the card shows (default 500). - * @param props.variant - compact card beside the anchor, or a preview above/below it - * with 24px side insets, a 420px height cap, the frame-top clearance (capped below an anchor inside the top strip), - * and 100ms opacity transitions. + * @param props.variant - compact card beside the anchor's end edge, or its start edge when only that side fits, or + * below the anchor, else above it, when neither side fits, or in the viewport's bottom end corner when it is too + * tall for those, which the stylesheet decides by CSS anchor positioning; or a preview above/below it with 24px + * side insets, a 420px height cap, the frame-top clearance (capped below an anchor inside the top strip), and 100ms + * opacity transitions. * @param props.widthAnchorRef - optional element whose width and horizontal position size the preview. * @param props.inline - keep the anchor in prose; show a contained preview on hover or keyboard focus. * Its hover region connects the anchor and preview across the visual gap. @@ -67,6 +73,8 @@ export function HoverCard({ copyLabel?: string copiedLabel?: string })) { + const compact = variant !== 'preview' && !inline + const anchorName = `--dsh-hover-card-${useId().replaceAll(':', '')}` const rootRef = useRef(null) const cardRef = useRef(null) const portalRef = useRef(null) @@ -168,6 +176,8 @@ export function HoverCard({ // Fixed-position from the anchor rect before paint; track the anchor while // open (capture-phase scroll catches nested panes), as in Menu portal mode. + // The stylesheet anchors a compact card, so it needs neither the rect nor + // the tracking. useLayoutEffect(() => { if (!open) { setPos(null); return } const place = () => { @@ -178,6 +188,10 @@ export function HoverCard({ dismissImmediately() return } + if (compact) { + setPos(ANCHORED) + return + } const r = wrapper.getBoundingClientRect() const h = cardRef.current?.offsetHeight ?? 0 if (variant === 'preview') { @@ -196,32 +210,27 @@ export function HoverCard({ }) return } - if (inline) { - const height = Math.max(h, cardRef.current?.scrollHeight ?? 0) - const maxWidth = Math.max(0, Math.min(INLINE_PREVIEW_WIDTH, window.innerWidth - VIEWPORT_MARGIN * 2)) - const width = fitContent ? Math.min(cardRef.current?.offsetWidth ?? maxWidth, maxWidth) : maxWidth - const topMargin = overlayTopMargin(VIEWPORT_MARGIN, r, ANCHOR_GAP) - const belowTop = Math.max(topMargin, r.bottom + ANCHOR_GAP) - const above = Math.max(0, r.top - ANCHOR_GAP - topMargin) - const below = Math.max(0, window.innerHeight - belowTop - VIEWPORT_MARGIN) - const onTop = height > below && above > below - const maxHeight = onTop ? above : below - const left = Math.max(VIEWPORT_MARGIN, Math.min(r.left, window.innerWidth - width - VIEWPORT_MARGIN)) - const top = onTop ? r.top - ANCHOR_GAP - Math.min(height, maxHeight) : belowTop - const bridgeTop = onTop ? top + Math.min(height, maxHeight) : r.bottom - const bridgeLeft = Math.min(r.left, left) - setPos({ - left, top, ...fitContent ? {} : { width }, maxWidth, maxHeight, - bridge: { - left: bridgeLeft, top: bridgeTop, - width: Math.max(r.right, left + width) - bridgeLeft, - height: Math.max(0, (onTop ? r.top : top) - bridgeTop), - }, - }) - return - } - const top = r.top + h > window.innerHeight - VIEWPORT_MARGIN ? window.innerHeight - h - VIEWPORT_MARGIN : r.top - setPos({ left: r.right + ANCHOR_GAP, top }) + const height = Math.max(h, cardRef.current?.scrollHeight ?? 0) + const maxWidth = Math.max(0, Math.min(INLINE_PREVIEW_WIDTH, window.innerWidth - VIEWPORT_MARGIN * 2)) + const width = fitContent ? Math.min(cardRef.current?.offsetWidth ?? maxWidth, maxWidth) : maxWidth + const topMargin = overlayTopMargin(VIEWPORT_MARGIN, r, ANCHOR_GAP) + const belowTop = Math.max(topMargin, r.bottom + ANCHOR_GAP) + const above = Math.max(0, r.top - ANCHOR_GAP - topMargin) + const below = Math.max(0, window.innerHeight - belowTop - VIEWPORT_MARGIN) + const onTop = height > below && above > below + const maxHeight = onTop ? above : below + const left = Math.max(VIEWPORT_MARGIN, Math.min(r.left, window.innerWidth - width - VIEWPORT_MARGIN)) + const top = onTop ? r.top - ANCHOR_GAP - Math.min(height, maxHeight) : belowTop + const bridgeTop = onTop ? top + Math.min(height, maxHeight) : r.bottom + const bridgeLeft = Math.min(r.left, left) + setPos({ + left, top, ...fitContent ? {} : { width }, maxWidth, maxHeight, + bridge: { + left: bridgeLeft, top: bridgeTop, + width: Math.max(r.right, left + width) - bridgeLeft, + height: Math.max(0, (onTop ? r.top : top) - bridgeTop), + }, + }) } place() // Observe only the anchor's ancestors: an offscreen drawer can hide without resizing its retained row. @@ -229,31 +238,21 @@ export function HoverCard({ for (let ancestor = rootRef.current?.parentElement; ancestor != null; ancestor = ancestor.parentElement) { visibility.observe(ancestor, { attributes: true, attributeFilter: ['inert', 'hidden'] }) } - const observer = (variant === 'preview' || inline) && typeof ResizeObserver !== 'undefined' ? new ResizeObserver(place) : null + const observer = !compact && typeof ResizeObserver !== 'undefined' ? new ResizeObserver(place) : null for (const element of [cardRef.current, rootRef.current, widthAnchorRef?.current]) { if (element !== null && element !== undefined) observer?.observe(element) } - window.addEventListener('scroll', place, true) - window.addEventListener('resize', place) + if (!compact) { + window.addEventListener('scroll', place, true) + window.addEventListener('resize', place) + } return () => { observer?.disconnect() visibility.disconnect() window.removeEventListener('scroll', place, true) window.removeEventListener('resize', place) } - }, [open, variant, widthAnchorRef, positioned, inline, fitContent, dismissImmediately]) - - // The first placement ran before the card mounted (height read 0): once the - // card's real height is measurable, correct the bottom-edge clamp. The - // correction converges — a clamped top satisfies the guard, so it runs once. - useLayoutEffect(() => { - if (!open || pos === null || variant === 'preview' || inline) return - /* v8 ignore next -- the card is mounted whenever pos is set, so the ref is attached here. */ - const h = cardRef.current?.offsetHeight ?? 0 - if (pos.top + h > window.innerHeight - VIEWPORT_MARGIN) { - setPos({ left: pos.left, top: window.innerHeight - h - VIEWPORT_MARGIN }) - } - }, [open, pos, variant, inline]) + }, [open, compact, variant, widthAnchorRef, positioned, fitContent, dismissImmediately]) const copy = async (text: string): Promise => { if (copied || copyingRef.current) return @@ -280,9 +279,13 @@ export function HoverCard({ const card = open && pos !== null && (
    { if (!disabled && event.target.matches(':focus-visible')) { cancelClose(); setPhase('open') } } : undefined} diff --git a/packages/client/ui-primitives/src/Marquee.module.css b/packages/client/ui-primitives/src/Marquee.module.css new file mode 100644 index 0000000000..562113c9fe --- /dev/null +++ b/packages/client/ui-primitives/src/Marquee.module.css @@ -0,0 +1,47 @@ +/* Single-line text that clips with an ellipsis at rest. While it marquees + (data-marquee), the ellipsis drops, the inner span travels to the far edge + over the distance and time the hook measured, and both clipping edges fade + in over 12px instead of hard-cutting a character. */ +.text { + display: block; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* At the far edge the end fade lifts so the final character reads at full + strength: a zero-length animation, delayed by the travel's duration, swaps + the mask and holds it. */ +.text[data-marquee] { + text-overflow: clip; + mask-image: linear-gradient(to right, transparent, #000 12px, #000 calc(100% - 12px), transparent); + animation: dsh-marquee-arrive 0s var(--dsh-marquee-duration) forwards; +} + +@keyframes dsh-marquee-arrive { + to { mask-image: linear-gradient(to right, transparent, #000 12px); } +} + +/* Inline at rest, so the ellipsis cuts between characters; a transform needs a box. */ +.text[data-marquee] > .travel { + display: inline-block; + animation: dsh-marquee-travel var(--dsh-marquee-duration) linear forwards; +} + +@keyframes dsh-marquee-travel { + to { transform: translateX(calc(-1 * var(--dsh-marquee-range))); } +} + +/* Reduced motion shows the far edge at once, so only the start edge hides text. */ +@media (prefers-reduced-motion: reduce) { + .text[data-marquee] { + mask-image: linear-gradient(to right, transparent, #000 12px); + animation: none; + } + + .text[data-marquee] > .travel { + animation: none; + transform: translateX(calc(-1 * var(--dsh-marquee-range))); + } +} diff --git a/packages/client/ui-primitives/src/Marquee.tsx b/packages/client/ui-primitives/src/Marquee.tsx new file mode 100644 index 0000000000..0bbf0d3b3d --- /dev/null +++ b/packages/client/ui-primitives/src/Marquee.tsx @@ -0,0 +1,109 @@ +// Hover marquee for single-line text that its cell clips: while the pointer is +// on the owning row, a CSS animation carries the text to its far edge, and +// leaving returns it to the start. + +import { forwardRef, useCallback, useEffect, useMemo, useRef } from 'react' +import type { HTMLAttributes, PointerEvent, RefObject } from 'react' +import clsx from 'clsx' +import css from './Marquee.module.css' + +/* Overflow this small hides no meaningful tail; travelling for it reads as an + accidental jitter, so the text stays put. */ +const MIN_REVEAL_PX = 8 + +/* Travel speed: slow enough to read the text as it passes. */ +const PX_PER_MS = 0.03 + +/** Pointer handlers of the row whose hover marquees one text; spread them onto the row. */ +export interface HoverMarquee { + /** Start the travel; touch pointers and text that fits do nothing. */ + readonly onPointerEnter: (event: PointerEvent) => void + /** Return the text to its start in one step, unless the marquee is held. */ + readonly onPointerLeave: () => void +} + +/** Options of {@link useHoverMarquee}. */ +export interface HoverMarqueeOptions { + /** Marquee the text while true, with or without the pointer on the row, such as while the row's menu is open. */ + readonly hold?: boolean | undefined +} + +/** + * Start the text's travel unless it already marquees: measure how far the text + * overflows its cell, and hand the stylesheet that distance and the time it + * takes at the constant speed. + * @param text - the clipping text element. + */ +function travel(text: HTMLElement): void { + if (text.dataset.marquee !== undefined) return + const range = text.scrollWidth - text.clientWidth + if (range <= MIN_REVEAL_PX) return + text.style.setProperty('--dsh-marquee-range', `${range}px`) + text.style.setProperty('--dsh-marquee-duration', `${Math.round(range / PX_PER_MS)}ms`) + text.dataset.marquee = '' +} + +/** + * Return the text to its resting state: at its start, with the ellipsis and + * without fades. + * @param text - the clipping text element. + */ +function rest(text: HTMLElement): void { + delete text.dataset.marquee + text.style.removeProperty('--dsh-marquee-range') + text.style.removeProperty('--dsh-marquee-duration') +} + +/** + * Marquee one-line text wider than its cell while the pointer is on its row: + * the text travels at 30px/s until its far edge is in view, then rests there + * under the pointer. Overflow of at most 8px stays put. Leaving returns the + * text to the start in one step, because the resting ellipsis and the narrowed + * cell would otherwise meet the text while it travelled back. The stylesheet + * animates the travel and its fades, so the script only measures the overflow + * once per entry; reduced motion shows the far edge at once. + * @param text - ref to the clipping text element, a {@link MarqueeText}. + * @param options - whether the marquee is held without the pointer. + * @returns stable pointer enter and leave handlers for the row. + */ +export function useHoverMarquee(text: RefObject, { hold = false }: HoverMarqueeOptions = {}): HoverMarquee { + const hovered = useRef(false) + const held = useRef(hold) + const sync = useCallback((): void => { + const element = text.current + if (element === null) return + if (hovered.current || held.current) travel(element) + else rest(element) + }, [text]) + useEffect(() => { + held.current = hold + sync() + }, [hold, sync]) + return useMemo(() => ({ + onPointerEnter: (event: PointerEvent): void => { + if (event.pointerType === 'touch') return + hovered.current = true + sync() + }, + onPointerLeave: (): void => { + hovered.current = false + sync() + }, + }), [sync]) +} + +/** Props of single-line text that a {@link useHoverMarquee} can marquee. */ +export type MarqueeTextProps = HTMLAttributes + +/** + * Render single-line text that clips with an ellipsis at rest and, while a + * {@link useHoverMarquee} marquees it, drops the ellipsis and fades whichever + * edge still hides text. The children sit in an inner span, which travels. + */ +export const MarqueeText = forwardRef(function MarqueeText({ className, children, ...attributes }, ref) { + return ( + + {children} + + ) +}) diff --git a/packages/client/ui-primitives/src/Menu.tsx b/packages/client/ui-primitives/src/Menu.tsx index 47b31bb407..8af49993dc 100644 --- a/packages/client/ui-primitives/src/Menu.tsx +++ b/packages/client/ui-primitives/src/Menu.tsx @@ -119,9 +119,11 @@ export function MenuItemButton({ onSelect, ...props }: MenuItemButtonProps) { * @param props.selectedId - row shown as selected. * @param props.selectedIds - rows shown as selected when a menu contains independent option groups. * @param props.onSelect - data-row activation callback (not called for disabled rows or submenu parents that only open children). - * @param props.onClose - invoked on outside click, Escape, or a window blur - * that moved focus into an iframe (the only signal a pointerdown inside a - * cross-origin iframe leaves). + * @param props.onClose - invoked on outside click, on activating another popup + * trigger (an `aria-haspopup` control outside this menu that + * `isExternalTrigger` does not claim) even when that trigger stops its + * pointer presses, on Escape, or on a window blur that moved focus into an + * iframe (the only signal a pointerdown inside a cross-origin iframe leaves). * @param props.align - list alignment against the anchor (default 'start'). * @param props.side - open below (`bottom`, default) or above (`top`) the anchor. * @param props.portal - render the list into document.body, fixed-positioned @@ -337,6 +339,17 @@ export function Menu({ open, anchor, items = [], children, submenuBackLabel, sel if (listRef.current?.contains(e.target) === true || submenuEvents.current.contains(e.target)) return onClose() } + // Activating another popup trigger closes this menu even when that trigger + // isolates its presses from its owners, as the shared context-menu button + // does: its pointerdown never reaches the listener above, so the + // activating click is caught in the capture phase instead. + const onOtherTrigger = (e: MouseEvent) => { + const trigger = e.target instanceof Element ? e.target.closest('[aria-haspopup]') : null + if (trigger === null || rootRef.current?.contains(trigger) === true || anchorRef?.current?.contains(trigger) === true) return + if (isExternalTrigger?.(trigger) === true) return + if (listRef.current?.contains(trigger) === true || submenuEvents.current.contains(trigger)) return + onClose() + } const onKeyDown = (e: KeyboardEvent) => { if (composition.guards(e) || isBehindModal(triggerRef.current ?? rootRef.current) || e.defaultPrevented || e.ctrlKey || e.altKey || e.metaKey) return @@ -435,6 +448,7 @@ export function Menu({ open, anchor, items = [], children, submenuBackLabel, sel if (document.activeElement instanceof HTMLIFrameElement) onClose() } document.addEventListener('pointerdown', onPointerDown) + document.addEventListener('click', onOtherTrigger, true) const onEscape = (event: KeyboardEvent): void => { if (event.key === 'Escape') onKeyDown(event) } const onOtherKey = (event: KeyboardEvent): void => { if (event.key !== 'Escape') onKeyDown(event) } document.addEventListener('keydown', onOtherKey) @@ -443,6 +457,7 @@ export function Menu({ open, anchor, items = [], children, submenuBackLabel, sel return () => { composition.dispose() document.removeEventListener('pointerdown', onPointerDown) + document.removeEventListener('click', onOtherTrigger, true) document.removeEventListener('keydown', onOtherKey) document.removeEventListener('keydown', onEscape, true) window.removeEventListener('blur', onWindowBlur) diff --git a/packages/client/ui-primitives/src/icons/artwork.ts b/packages/client/ui-primitives/src/icons/artwork.ts index 76e4235739..c3fd3ef4d0 100644 --- a/packages/client/ui-primitives/src/icons/artwork.ts +++ b/packages/client/ui-primitives/src/icons/artwork.ts @@ -95,6 +95,7 @@ export const ICON_ARTWORK = { 'queue-outline': { size: 14, svg: strokeWidth => `` }, 'checklist-outline': { size: 14, svg: strokeWidth => `` }, 'list-pen-outline': { size: 16, svg: strokeWidth => `` }, + 'files-diff-outline': { size: 16, svg: strokeWidth => `` }, 'goal-outline': { size: 16, svg: strokeWidth => `` }, 'sparkle': { size: 16, svg: strokeWidth => `` }, 'inspect-outline': { size: 12, svg: strokeWidth => `` }, diff --git a/packages/client/ui-primitives/src/icons/index.tsx b/packages/client/ui-primitives/src/icons/index.tsx index 1b4aa7eca7..7ed1d9c2aa 100644 --- a/packages/client/ui-primitives/src/icons/index.tsx +++ b/packages/client/ui-primitives/src/icons/index.tsx @@ -462,6 +462,12 @@ export const IconListPenOutlineRegular = productIcon('list-pen-outline', 'regula /** Medium IconListPenOutline artwork with a 1.3px stroke. */ export const IconListPenOutlineMedium = productIcon('list-pen-outline', 'medium') +/** Regular one-pixel IconFilesDiffOutline artwork. */ +export const IconFilesDiffOutlineRegular = productIcon('files-diff-outline', 'regular') + +/** Medium IconFilesDiffOutline artwork with a 1.3px stroke. */ +export const IconFilesDiffOutlineMedium = productIcon('files-diff-outline', 'medium') + /** Regular one-pixel IconGoalOutline artwork. */ export const IconGoalOutlineRegular = productIcon('goal-outline', 'regular') diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 3f1756bfbf..c8b7bf521e 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -26,6 +26,8 @@ export type { SegmentedTab } from './SegmentedTabs.tsx' export { Tag } from './Tag.tsx' export type { TagTone } from './Tag.tsx' export { PathLabel } from './PathLabel.tsx' +export { MarqueeText, useHoverMarquee } from './Marquee.tsx' +export type { HoverMarquee, HoverMarqueeOptions, MarqueeTextProps } from './Marquee.tsx' export { Switch } from './Switch.tsx' export { SegmentedControl } from './SegmentedControl.tsx' export type { SegmentedControlOption } from './SegmentedControl.tsx' diff --git a/packages/client/ui-primitives/tests/hover-card-styles.client.spec.ts b/packages/client/ui-primitives/tests/hover-card-styles.client.spec.ts new file mode 100644 index 0000000000..8897727435 --- /dev/null +++ b/packages/client/ui-primitives/tests/hover-card-styles.client.spec.ts @@ -0,0 +1,50 @@ +/** + * The compact HoverCard's placement as CSS text: the component suite sees CSS + * Modules as class-name maps and jsdom lays out nothing, so only the stylesheet + * proves which positions the browser tries, and in which order. + */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const css = readFileSync(fileURLToPath(new URL('../src/HoverCard.module.css', import.meta.url)), 'utf8').replace(/\/\*[\s\S]*?\*\//g, ' ') + +function declarations(selector: string): Map { + const found = new Map() + for (const [, selectorList = '', body = ''] of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) { + if (!selectorList.split(',').map(value => value.trim()).includes(selector)) continue + for (const part of body.split(';')) { + const colon = part.indexOf(':') + if (colon !== -1) found.set(part.slice(0, colon).trim(), part.slice(colon + 1).trim().replace(/\s+/g, ' ')) + } + } + return found +} + +describe('HoverCard.module.css', () => { + it('places a compact card beside its anchor\'s end edge, top on the anchor\'s top, 8px from the anchor and the viewport', () => { + expect(declarations('.card').get('position')).toBe('fixed') + const compact = declarations('.compact') + expect([compact.get('position-area'), compact.get('inset')]).toEqual(['inline-end span-block-end', '0 8px 8px']) + }) + + it('tries the start side, then a bottom-held card on either side, then below the anchor and above it, then the viewport\'s corner', () => { + expect(declarations('.compact').get('position-try-fallbacks')).toBe( + 'flip-inline, --dsh-hover-card-low, --dsh-hover-card-low flip-inline, --dsh-hover-card-below, --dsh-hover-card-above, --dsh-hover-card-held', + ) + const low = declarations('@position-try --dsh-hover-card-low') + expect([low.get('position-area'), low.get('align-self')]).toEqual(['inline-end span-all', 'end']) + }) + + it('keeps a card that fits on neither side off its anchor: 8px below or above it, from the anchor\'s start edge', () => { + const below = declarations('@position-try --dsh-hover-card-below') + expect([below.get('position-area'), below.get('inset')]).toEqual(['block-end span-inline-end', '8px 8px 8px 0']) + const above = declarations('@position-try --dsh-hover-card-above') + expect([above.get('position-area'), above.get('inset')]).toEqual(['block-start span-inline-end', '8px 8px 8px 0']) + }) + + it('holds a card too tall to go below or above its anchor at the viewport\'s bottom and end margins, as the last fallback', () => { + const held = declarations('@position-try --dsh-hover-card-held') + expect([held.get('position-area'), held.get('justify-self'), held.get('align-self')]).toEqual(['span-all', 'end', 'end']) + }) +}) diff --git a/packages/client/ui-primitives/tests/hover-card.client.spec.tsx b/packages/client/ui-primitives/tests/hover-card.client.spec.tsx index 56e4ef5044..a5ad226fab 100644 --- a/packages/client/ui-primitives/tests/hover-card.client.spec.tsx +++ b/packages/client/ui-primitives/tests/hover-card.client.spec.tsx @@ -137,8 +137,9 @@ describe('HoverCard', () => { expect(screen.getByText('card body')).toBeTruthy() }) - it('opens after the dwell delay, positioned right of the anchor', () => { + it('opens after the dwell delay, anchored to its wrapper by name for the stylesheet to place', () => { const { wrapper } = mount() + expect(wrapper.style.anchorName).toBe('') fireEvent.pointerEnter(wrapper) expect(screen.queryByText('card body')).toBeNull() act(() => { vi.advanceTimersByTime(499) }) @@ -146,8 +147,29 @@ describe('HoverCard', () => { act(() => { vi.advanceTimersByTime(1) }) const card = screen.getByText('card body').parentElement as HTMLElement expect(card.parentElement?.parentElement).toBe(document.body) - expect(card.style.left).toBe('208px') - expect(card.style.top).toBe('40px') + // The stylesheet places a compact card against the named anchor, so the script gives it no coordinates. + expect(wrapper.style.anchorName).toMatch(/^--dsh-hover-card-/) + expect(card.style.positionAnchor).toBe(wrapper.style.anchorName) + expect([card.style.left, card.style.top]).toEqual(['', '']) + // The name lasts as long as the card. + fireEvent.pointerLeave(wrapper) + act(() => { vi.advanceTimersByTime(POINTER_GRACE_MS) }) + expect(wrapper.style.anchorName).toBe('') + }) + + it('gives each compact card its own anchor name', () => { + render( + <> + first} content={
    first body
    } /> + second} content={
    second body
    } /> + , + ) + const wrappers = ['first', 'second'].map(text => screen.getByText(text).parentElement as HTMLElement) + for (const wrapper of wrappers) fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(500) }) + const names = wrappers.map(wrapper => wrapper.style.anchorName) + expect(new Set(names).size).toBe(2) + expect(['first body', 'second body'].map(text => (screen.getByText(text).parentElement as HTMLElement).style.positionAnchor)).toEqual(names) }) it('insets a preview by 24px on each side and follows anchor resizing', () => { @@ -600,46 +622,18 @@ describe('HoverCard', () => { expect(screen.queryByText('card body')).toBeNull() }) - it('corrects the bottom-edge clamp once the mounted card height is measurable', () => { - // First placement reads height 0 (card not yet mounted) and keeps the - // anchor top; the post-mount correction re-clamps with the real height. - window.innerHeight = 300 - const offsetHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight')! - Object.defineProperty(HTMLElement.prototype, 'offsetHeight', { configurable: true, get: () => 120 }) - try { - const { wrapper } = mount() - stubAnchorRect(screen.getByText('row'), { top: 280, right: 200 }) - fireEvent.pointerEnter(wrapper) - act(() => { vi.advanceTimersByTime(500) }) - const card = screen.getByText('card body').parentElement as HTMLElement - // 300 - 120 - 8 = 172, instead of the anchor top 280. - expect(card.style.top).toBe('172px') - } finally { - Object.defineProperty(HTMLElement.prototype, 'offsetHeight', offsetHeight) - } - }) - - it('clamps inside placement itself when the card is already measured (resize path)', () => { - window.innerHeight = 300 + it('measures nothing for a compact card: not at open, on scroll, or on resize', () => { const { wrapper } = mount() - stubAnchorRect(screen.getByText('row'), { top: 280, right: 200 }) + const rect = vi.spyOn(wrapper, 'getBoundingClientRect') + const listen = vi.spyOn(window, 'addEventListener') fireEvent.pointerEnter(wrapper) act(() => { vi.advanceTimersByTime(500) }) const card = screen.getByText('card body').parentElement as HTMLElement - Object.defineProperty(card, 'offsetHeight', { value: 120 }) - act(() => { fireEvent.resize(window) }) - expect(card.style.top).toBe('172px') - }) - - it('repositions on capture-phase scroll while open and stops listening after close', () => { - const { wrapper } = mount() - fireEvent.pointerEnter(wrapper) - act(() => { vi.advanceTimersByTime(500) }) - stubAnchorRect(screen.getByText('row'), { top: 90, right: 300 }) act(() => { fireEvent.scroll(document) }) - const card = screen.getByText('card body').parentElement as HTMLElement - expect(card.style.left).toBe('308px') - expect(card.style.top).toBe('90px') + act(() => { fireEvent.resize(window) }) + expect(rect).not.toHaveBeenCalled() + expect(listen.mock.calls.map(([type]) => type).filter(type => type === 'scroll' || type === 'resize')).toEqual([]) + expect([card.style.left, card.style.top]).toEqual(['', '']) fireEvent.pointerLeave(wrapper) act(() => { vi.advanceTimersByTime(POINTER_GRACE_MS) }) expect(screen.queryByText('card body')).toBeNull() diff --git a/packages/client/ui-primitives/tests/marquee-styles.client.spec.ts b/packages/client/ui-primitives/tests/marquee-styles.client.spec.ts new file mode 100644 index 0000000000..b1e3fbed23 --- /dev/null +++ b/packages/client/ui-primitives/tests/marquee-styles.client.spec.ts @@ -0,0 +1,57 @@ +/** + * MarqueeText's clipping, travel, and fade masks as CSS text: the component + * suite sees CSS Modules as class-name maps, so only the stylesheet proves that + * a marqueeing text drops its ellipsis, travels by the measured distance and + * time, and fades the edges that still hide text. + */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const source = readFileSync(fileURLToPath(new URL('../src/Marquee.module.css', import.meta.url)), 'utf8').replace(/\/\*[\s\S]*?\*\//g, ' ') +const reduced = /@media \(prefers-reduced-motion: reduce\) \{([\s\S]*)\}\s*$/.exec(source)?.[1] ?? '' +const base = source.replace(/@media \(prefers-reduced-motion: reduce\) \{[\s\S]*\}\s*$/, '') + +function declarations(css: string, selector: string): Map { + const found = new Map() + for (const [, selectorList = '', body = ''] of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) { + if (!selectorList.split(',').map(value => value.trim()).includes(selector)) continue + for (const part of body.split(';')) { + const colon = part.indexOf(':') + if (colon !== -1) found.set(part.slice(0, colon).trim(), part.slice(colon + 1).trim().replace(/\s+/g, ' ')) + } + } + return found +} + +const START_FADE = 'linear-gradient(to right, transparent, #000 12px)' + +describe('Marquee.module.css', () => { + it('clips one line with an ellipsis at rest, with the travelling span inline so the ellipsis cuts between characters', () => { + const rest = declarations(base, '.text') + expect([rest.get('overflow'), rest.get('text-overflow'), rest.get('white-space')]).toEqual(['hidden', 'ellipsis', 'nowrap']) + expect(declarations(base, '.travel').size).toBe(0) + }) + + it('drops the ellipsis and fades both edges while the text travels, then only the start edge once the travel time has passed', () => { + const travelling = declarations(base, '.text[data-marquee]') + expect(travelling.get('text-overflow')).toBe('clip') + expect(travelling.get('mask-image')).toBe('linear-gradient(to right, transparent, #000 12px, #000 calc(100% - 12px), transparent)') + expect(travelling.get('animation')).toBe('dsh-marquee-arrive 0s var(--dsh-marquee-duration) forwards') + expect(base.replace(/\s+/g, ' ')).toContain(`@keyframes dsh-marquee-arrive { to { mask-image: ${START_FADE}; } }`) + }) + + it('carries the span over the measured distance in the measured time at a constant speed and holds the far edge', () => { + const travel = declarations(base, '.text[data-marquee] > .travel') + expect(travel.get('display')).toBe('inline-block') + expect(travel.get('animation')).toBe('dsh-marquee-travel var(--dsh-marquee-duration) linear forwards') + expect(base.replace(/\s+/g, ' ')).toContain('@keyframes dsh-marquee-travel { to { transform: translateX(calc(-1 * var(--dsh-marquee-range))); } }') + }) + + it('shows the far edge at once under reduced motion, with the start fade alone', () => { + const text = declarations(reduced, '.text[data-marquee]') + expect([text.get('mask-image'), text.get('animation')]).toEqual([START_FADE, 'none']) + const travel = declarations(reduced, '.text[data-marquee] > .travel') + expect([travel.get('animation'), travel.get('transform')]).toEqual(['none', 'translateX(calc(-1 * var(--dsh-marquee-range)))']) + }) +}) diff --git a/packages/client/ui-primitives/tests/marquee.client.spec.tsx b/packages/client/ui-primitives/tests/marquee.client.spec.tsx new file mode 100644 index 0000000000..1e80d2e974 --- /dev/null +++ b/packages/client/ui-primitives/tests/marquee.client.spec.tsx @@ -0,0 +1,97 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { useRef } from 'react' +import { MarqueeText, useHoverMarquee } from '../src/Marquee.tsx' + +afterEach(cleanup) + +function Row({ text, hold }: { readonly text: string; readonly hold?: boolean }) { + const ref = useRef(null) + const marquee = useHoverMarquee(ref, { hold }) + return ( +
    + {text} +
    + ) +} + +/** The clipping element and the span inside it that travels. */ +function parts(): { text: HTMLElement; travel: HTMLElement } { + const text = document.querySelector('[data-cell]') as HTMLElement + return { text, travel: text.firstElementChild as HTMLElement } +} + +/** State the clipped text's geometry outright: jsdom lays out nothing. */ +function geometry(element: HTMLElement, scrollWidth: number, clientWidth: number): void { + Object.defineProperty(element, 'scrollWidth', { value: scrollWidth, configurable: true }) + Object.defineProperty(element, 'clientWidth', { value: clientWidth, configurable: true }) +} + +/** What the stylesheet reads: whether the text marquees, the travel distance, and its duration. */ +function marquee(text: HTMLElement): (string | undefined)[] { + return [text.dataset.marquee, text.style.getPropertyValue('--dsh-marquee-range'), text.style.getPropertyValue('--dsh-marquee-duration')] +} + +describe('useHoverMarquee', () => { + it('hands the stylesheet the overflow and its time at 30px/s while hovered, and rests at once on leave', () => { + render() + const row = screen.getByRole('row') + const { text, travel } = parts() + expect(text.className).toContain('cell') + expect(travel.textContent).toBe('A cell long enough to clip') + geometry(text, 320, 180) + fireEvent.pointerEnter(row, { pointerType: 'touch' }) + expect(marquee(text)).toEqual([undefined, '', '']) + fireEvent.pointerEnter(row) + expect(marquee(text)).toEqual(['', '140px', '4667ms']) + // A repeated entry while it marquees measures nothing again, so the travel does not restart. + geometry(text, 400, 180) + fireEvent.pointerEnter(row) + expect(marquee(text)).toEqual(['', '140px', '4667ms']) + fireEvent.pointerLeave(row) + expect(marquee(text)).toEqual([undefined, '', '']) + }) + + it('leaves text that fits or overflows by at most 8px at rest', () => { + render() + const row = screen.getByRole('row') + const { text } = parts() + for (const [scrollWidth, expected] of [[180, false], [188, false], [189, true]] as const) { + geometry(text, scrollWidth, 180) + fireEvent.pointerEnter(row) + expect(text.hasAttribute('data-marquee')).toBe(expected) + fireEvent.pointerLeave(row) + } + }) + + it('marquees while held, with or without the pointer, and rests when neither remains', () => { + const view = render() + const row = screen.getByRole('row') + const { text } = parts() + geometry(text, 300, 200) + view.rerender() + expect(marquee(text)).toEqual(['', '100px', '3333ms']) + fireEvent.pointerEnter(row) + fireEvent.pointerLeave(row) + expect(text.hasAttribute('data-marquee')).toBe(true) + view.rerender() + expect(text.hasAttribute('data-marquee')).toBe(false) + // The pointer keeps a marquee whose hold ends. + fireEvent.pointerEnter(row) + view.rerender() + view.rerender() + expect(text.hasAttribute('data-marquee')).toBe(true) + }) + + it('ignores hover before its text element mounts', () => { + function Detached() { + const ref = useRef(null) + return
    + } + render() + fireEvent.pointerEnter(screen.getByRole('row')) + fireEvent.pointerLeave(screen.getByRole('row')) + expect(screen.getByRole('row').childElementCount).toBe(0) + }) +}) diff --git a/packages/client/ui-primitives/tests/menu-submenu.client.spec.tsx b/packages/client/ui-primitives/tests/menu-submenu.client.spec.tsx index 798640da95..248725c85b 100644 --- a/packages/client/ui-primitives/tests/menu-submenu.client.spec.tsx +++ b/packages/client/ui-primitives/tests/menu-submenu.client.spec.tsx @@ -97,6 +97,35 @@ describe('Menu submenus', () => { expect(close).toHaveBeenCalledOnce() }) + it('closes when another popup trigger is activated, even one that stops its pointer presses', () => { + const close = vi.fn() + render(<> + + + Own} items={entries} onClose={close} /> + ) + fireEvent.click(screen.getByRole('button', { name: 'Own' })) + fireEvent.click(screen.getByRole('menuitem', { name: 'Applications' })) + fireEvent.click(screen.getByRole('button', { name: 'Plain' })) + expect(close).not.toHaveBeenCalled() + const isolated = screen.getByRole('button', { name: 'Isolated more' }) + fireEvent.pointerDown(isolated) + expect(close).not.toHaveBeenCalled() + fireEvent.click(isolated) + expect(close).toHaveBeenCalledOnce() + }) + + it('leaves other popup triggers the external-trigger rule claims to their own popup', () => { + const close = vi.fn() + render(<> + + node instanceof Element && node.hasAttribute('data-context-menu-trigger')} /> + ) + fireEvent.click(screen.getByRole('button', { name: 'Claimed' })) + expect(close).not.toHaveBeenCalled() + }) + it('does not activate an external popup trigger on ArrowRight', () => { render() const trigger = screen.getByRole('button', { name: 'External more' }) diff --git a/packages/client/ui-session-panel/README.i18n.yaml b/packages/client/ui-session-panel/README.i18n.yaml index 97d36774c6..b2577faa28 100644 --- a/packages/client/ui-session-panel/README.i18n.yaml +++ b/packages/client/ui-session-panel/README.i18n.yaml @@ -15,17 +15,17 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-session-panel/use-this-package: - en: 395514000d22bf29 - zh: 8a8e1f0dc91a21fa + en: 62a513f72d48d6e2 + zh: 7f0eb3e873c0473f /deepseek-ai-dsh-client-ui-session-panel/use-this-package/docking-and-the-overlay: en: 67b33b9f412a687d zh: 2a9b8c89c8bb22e4 /deepseek-ai-dsh-client-ui-session-panel/use-this-package/contribute-a-section: - en: 1e82e57556909a29 - zh: fc68f414ec254403 + en: b76852d8740aee0f + zh: ccfeb7774e1b0e27 /deepseek-ai-dsh-client-ui-session-panel/understand-the-implementation: - en: e414b3b6a3aef7fc - zh: 384ad365ae5529a9 + en: ede595ecc4aab24a + zh: 5a30a4042ab7483a /deepseek-ai-dsh-client-ui-session-panel/further-exploration: en: 09b403af819bd155 zh: e949998de4794393 diff --git a/packages/client/ui-session-panel/README.md b/packages/client/ui-session-panel/README.md index 957fbe8480..43ba71d18e 100644 --- a/packages/client/ui-session-panel/README.md +++ b/packages/client/ui-session-panel/README.md @@ -25,7 +25,7 @@ English | [中文](README.zh.md) ## Use this package -The `@deepseek-ai/dsh-web-app` bundle loads this package by default. The toggle is the first Session header utility, before change requests, sharing, and the schedule catalog. It is an icon button with the panel name and its indicators as its accessible name, a tooltip that says whether a press shows or hides the panel, shown after 500ms of hover or at once on keyboard focus, and `aria-expanded` for whether the panel shows. +The `@deepseek-ai/dsh-web-app` bundle loads this package by default. The toggle is the first Session header utility, before sharing and the schedule catalog. It is an icon button with the panel name and its indicators as its accessible name, a tooltip that says whether a press shows or hides the panel, shown after 500ms of hover or at once on keyboard focus, and `aria-expanded` for whether the panel shows. ### Docking and the overlay @@ -38,25 +38,31 @@ Other Views, such as the trajectory View, show no panel. While no Chat View show ### Contribute a section -A section is one `conversation.session.panel.section` list registration: `id` addresses it, `order` sorts it ascending, and the required `label` is its title, which the panel draws in the active locale. The section component receives `presentation` (`docked` or `overlay`) and `dismissOverlay()` as owner props; it renders its body and renders nothing when it has nothing to show, which hides its title too. Register trailing title controls, such as a count or a refresh button, in the keyed `conversation.session.panel.section.actions` slot under the section's `id`. A section without a label is reported to the console and not shown. +A section is one `conversation.session.panel.section` list registration: `id` addresses it, `order` sorts it ascending, and the required `label` is its title, which the panel draws in the active locale. The section component receives `presentation` (`docked` or `overlay`) and `dismissOverlay()` as owner props; it renders its body and renders nothing when it has nothing to show, which hides its title too. Register trailing title controls, such as a count or a refresh button, in the keyed `conversation.session.panel.section.actions` slot under the section's `id`. A section without a label is reported to the console and not shown. The shipped sections are Environment (`order: 0`), Change requests from the [forge bundle](../../experimental/client-ui-forge/README.md) (`100`), [Subagents](../ui-subagent/README.md) (`200`), [Shared tasks](../ui-agent-team/README.md) (`250`), and [Background jobs](../ui-jobs/README.md) (`300`). -Plugins share a title by registering rows in a section owner's row slot. The built-in Environment section (`id: 'environment'`, `order: 0`) declares `conversation.session.panel.environment.row`; its `project` row (`order: 0`) shows the Session's working folder: the current directory from the `workingDirectory` projection, or, before the projection arrives or when it records none, the directory the Session was created in, then the directory of the Workspace that lists the Session. The row shows the folder name followed by its parent folder in tertiary ink, which clips with an ellipsis; its tooltip, shown after 500ms of hover, names the working folder and gives the full path. Both abbreviate the Host home to `~`. Right-clicking the row or pressing its More button opens the shared `directory` context menu. A plugin that owns a shared section declares its own row slot the same way. +Plugins share a title by registering rows in a section owner's row slot. The built-in Environment section (`id: 'environment'`, `order: 0`) declares `conversation.session.panel.environment.row`, whose rows receive the same owner props as a section; its `project` row (`order: 0`) shows the Session's working folder: the current directory from the `workingDirectory` projection, or, before the projection arrives or when it records none, the directory the Session was created in, then the directory of the Workspace that lists the Session. The row shows the folder name followed by its parent folder in tertiary ink, which clips with an ellipsis; its tooltip, shown after 500ms of hover, names the working folder and gives the full path. Both abbreviate the Host home to `~`. Right-clicking the row or pressing its More button opens the shared `directory` context menu. The forge bundle adds its checkout and local changes rows at orders 20 and 30. A plugin that owns a shared section declares its own row slot the same way. -Marks that must stay visible while the panel is hidden, such as an attention dot, go in the `conversation.session.panel.indicator` list. Each occupant is one element: the toggle sizes it to a 6px dot at the glyph's corner, and the occupant sets its `background` and includes text that names it, which becomes part of the toggle's accessible name. Occupants overlap, and a higher `order` paints above a lower one. The `panelShown` owner prop lets a mark that only repeats the panel's content render nothing while the panel shows. +Marks that must stay visible while the panel is hidden, such as an attention dot, go in the `conversation.session.panel.indicator` list. Each occupant is one element: the toggle sizes it to a 6px dot at the glyph's corner, and the occupant sets its `background` and includes text that names it, which becomes part of the toggle's accessible name. Occupants overlap, and a higher `order` paints above a lower one. The `panelShown` owner prop lets a mark that only repeats the panel's content render nothing while the panel shows. Subagents and Background jobs show a blue dot while work runs and the panel does not show (orders 10 and 20); the forge bundle's red attention dot (order 100) paints above them and stays while the panel shows. Rows share one look without sharing a component. A section's component, or an Environment row entry, writes its row's markup and marks the parts, and the panel's stylesheet lays them out, so icon, text, and trailing areas line up across packages while each package owns what its row contains. | Mark | Part | |---|---| | `data-session-panel-row` | The row: one 28px line. A row with an action or a menu highlights as a whole on hover and while one of its menus is open. | -| `data-row-part="body"` | The icon and the text. A ` +
    + ) +} diff --git a/packages/client/ui-session-panel/src/client/SessionPanel.module.css b/packages/client/ui-session-panel/src/client/SessionPanel.module.css index fa05289733..f16ef86393 100644 --- a/packages/client/ui-session-panel/src/client/SessionPanel.module.css +++ b/packages/client/ui-session-panel/src/client/SessionPanel.module.css @@ -148,6 +148,9 @@ covers the whole row [data-row-part='icon'] a 16px glyph in the row ink [data-row-part='content'] one line of text, clipped with an ellipsis + [data-row-part='lines'] in a two-line row, wraps the content and + the detail + [data-row-part='detail'] a second line in smaller tertiary type [data-row-part='trailing'] a value or control after the text [data-row-part='menu'] row actions, such as a More button @@ -229,6 +232,36 @@ white-space: nowrap; } +/* A detail line under the content: the row grows by its 17px line and 4px + insets, and the icon keeps the first line's 20px box, so its center stays + level with that line. */ +.panel :where([data-session-panel-row] > [data-row-part='body']:has([data-row-part='detail'])) { + align-items: flex-start; + height: auto; + padding: 4px 0; +} + +.panel :where([data-session-panel-row] > [data-row-part='body']:has([data-row-part='detail']) > [data-row-part='icon']) { + height: 20px; +} + +.panel :where([data-session-panel-row] [data-row-part='lines']) { + display: flex; + flex: 1 1 auto; + flex-direction: column; + min-width: 0; +} + +.panel :where([data-session-panel-row] [data-row-part='detail']) { + min-width: 0; + overflow: hidden; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + line-height: 17px; + text-overflow: ellipsis; + white-space: nowrap; +} + .panel :where([data-session-panel-row] > [data-row-part='trailing'], [data-session-panel-row] > [data-row-part='menu']) { position: relative; z-index: 1; @@ -292,8 +325,11 @@ } } -/* An open menu keeps its row highlighted and its trigger visible after the pointer leaves for the menu. */ -.panel :where([data-session-panel-row]:has(> button[data-row-part='body'], > [data-row-part='menu']:not(:empty)):has([aria-expanded='true'])) { +/* An open menu keeps its row highlighted and its trigger visible after the + pointer leaves for the menu. Only the menu part counts: a body button that + discloses something else carries aria-expanded too, and its row highlights + on hover alone. */ +.panel :where([data-session-panel-row]:has(> [data-row-part='menu'] [aria-expanded='true'])) { background: var(--dsw-alias-interactive-bg-hover); } @@ -308,3 +344,30 @@ .panel :where([data-session-panel-row]:has(> button[data-row-part='body']:active)) { background: var(--dsw-alias-interactive-bg-active); } + +/* A list's fold control (data-session-panel-row='fold'): the last row of a + list or of one of its groups, which shows the rows held back or folds them + again. It is quieter than a data row: the type of the counts beside the + section titles, with a 14px chevron in the icon column and the text where + the row names start. These rules follow the row rules they adjust, since + every rule for a part has the same specificity. */ +.panel :where([data-session-panel-row='fold']) { + color: var(--dsw-alias-label-tertiary); + font: var(--dsw-font-xxs-12); + font-variant-numeric: tabular-nums; +} + +.panel :where([data-session-panel-row='fold'] [data-row-part='icon']) svg { + width: 14px; + height: 14px; +} + +.panel :where([data-session-panel-row='fold']:has(> button:focus-visible)) { + color: var(--dsw-alias-label-secondary); +} + +@media (hover: hover) { + .panel :where([data-session-panel-row='fold']:hover) { + color: var(--dsw-alias-label-secondary); + } +} diff --git a/packages/client/ui-session-panel/src/client/index.ts b/packages/client/ui-session-panel/src/client/index.ts index c8233b7d31..e75283bca3 100644 --- a/packages/client/ui-session-panel/src/client/index.ts +++ b/packages/client/ui-session-panel/src/client/index.ts @@ -1,7 +1,8 @@ /** * Session panel plugin, browser half: a Session header toggle and a floating * panel in the Chat View's aside. The panel draws the titles of the sections - * other plugins register, lays out the rows they mark, and ships the + * other plugins register, lays out the rows they mark, offers the fold control + * their lists end with and the details their rows show on hover, and ships the * Environment section with the working folder row. */ import type { Context as ClientContext } from '@deepseek-ai/cordis' @@ -13,6 +14,8 @@ import type {} from '@deepseek-ai/dsh-client-connection/client' import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import { EnvironmentSection } from './EnvironmentSection.tsx' +import { PanelDetails } from './PanelDetails.tsx' +import { PanelFold } from './PanelFold.tsx' import { ProjectRow } from './ProjectRow.tsx' import { SessionPanel } from './SessionPanel.tsx' import { SessionPanelToggle } from './SessionPanelToggle.tsx' @@ -29,17 +32,18 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } export type { - EnvironmentSectionProps, ProjectRowInjected, ProjectRowProps, SessionPanelDockable, SessionPanelIndicatorOwnerProps, SessionPanelInjected, - SessionPanelPresentation, SessionPanelProbes, SessionPanelProps, SessionPanelSectionEntry, SessionPanelSectionOwnerProps, - SessionPanelToggleInjected, SessionPanelToggleProps, SessionPanelVisibility, + EnvironmentSectionProps, PanelDetailsFact, PanelDetailsProps, PanelFoldProps, ProjectRowInjected, ProjectRowProps, SessionPanelDockable, + SessionPanelIndicatorOwnerProps, SessionPanelInjected, SessionPanelPresentation, SessionPanelProbes, SessionPanelProps, + SessionPanelSectionEntry, SessionPanelSectionOwnerProps, SessionPanelToggleInjected, SessionPanelToggleProps, SessionPanelVisibility, } from './slots.ts' /** Required services: the slot registry, dictionaries, and the Host facts of the Remote carrier. */ export const inject = ['slots', 'locale', 'remote'] /** - * Client plugin body: register the dictionaries, the header toggle, the panel, - * and the Environment section with its project row. + * Client plugin body: register the dictionaries, the fold control and row + * details Factories, the header toggle, the panel, and the Environment section + * with its project row. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { @@ -53,6 +57,9 @@ export function apply(ctx: ClientContext): void { subscribe: listener => ctx.on('connection/reset', listener), } + ctx.slots.registerFactory({ name: 'conversation.session.panel.fold', scope: 'root' }, PanelFold) + ctx.slots.registerFactory({ name: 'conversation.session.panel.details', scope: 'root' }, PanelDetails) + ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({ name: 'conversation.session.header.utilities', id: 'session-panel', diff --git a/packages/client/ui-session-panel/src/client/slots.ts b/packages/client/ui-session-panel/src/client/slots.ts index 54a24145f1..67eb471b26 100644 --- a/packages/client/ui-session-panel/src/client/slots.ts +++ b/packages/client/ui-session-panel/src/client/slots.ts @@ -5,6 +5,7 @@ import type { } from '@deepseek-ai/dsh-client-ui-slots' import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { StateDotState } from '@deepseek-ai/dsh-client-ui-primitives' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import type {} from '@deepseek-ai/dsh-client-ui-chat/client' import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' @@ -40,9 +41,62 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { inline: true owner: SessionPanelIndicatorOwnerProps } - /** Rows of the built-in Environment section in ascending `order`. */ - 'conversation.session.panel.environment.row': { kind: 'list'; scope: 'session' } + /** Rows of the built-in Environment section in ascending `order`; they receive the section's owner values. */ + 'conversation.session.panel.environment.row': { kind: 'list'; scope: 'session'; owner: SessionPanelSectionOwnerProps } } + interface SlotFactoryMap { + /** + * The fold control of a panel list. A list shows at most five rows of a + * group and then this control as its last row, which shows the rest or + * folds them again; a list folds only when that hides two rows or more, + * since the control takes a row itself. The list keeps the fold state and + * decides which rows show. + */ + 'conversation.session.panel.fold': { scope: 'root'; props: PanelFoldProps } + /** + * The details of one panel row, for the content of the row's HoverCard: the + * row's full name, secondary lines such as its owner, its state, and its + * measures. A row whose single line clips or leaves these out shows them + * here. + */ + 'conversation.session.panel.details': { scope: 'root'; props: PanelDetailsProps } + } +} + +/** What a panel row's hover card says about the row. */ +export interface PanelDetailsProps { + /** + * The full name of what the row shows; it wraps instead of clipping. Omit it + * when the name can run long, such as a command, and the row's own view + * shows it in full. + */ + readonly title?: string | undefined + /** Lines in secondary type under the title, such as the owner; each stops after six lines. */ + readonly lines?: readonly string[] | undefined + /** The state, after its dot. */ + readonly status?: { readonly state: StateDotState; readonly label: string } | undefined + /** Measures on one line, at most one of each kind. */ + readonly facts?: readonly PanelDetailsFact[] | undefined +} + +/** One measure in a panel row's hover card. */ +export interface PanelDetailsFact { + /** What the measure counts, which selects its icon: a database for `tokens`, a clock for `duration`. */ + readonly kind: 'tokens' | 'duration' + /** The measure as the card shows it, such as "3.3M tok" or "6m 56s". */ + readonly label: string +} + +/** Props of the fold control that ends a folded panel list. */ +export interface PanelFoldProps { + /** Whether the list shows every row; the control then folds it again. */ + readonly expanded: boolean + /** Visible text for the current state, such as "Show 14 more" or "Show less". */ + readonly label: string + /** Accessible name for the current state; it starts with `label` and names what the list holds. */ + readonly name: string + /** Show every row, or fold the list again. */ + readonly onToggle: () => void } /** How the panel currently shows. */ diff --git a/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts b/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts index a0bcd21814..f909fdccca 100644 --- a/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-session-panel/tests/browser-plugin.client.spec.ts @@ -1,6 +1,6 @@ /** - * ui-session-panel plugin halves: the browser entry's dictionaries, header - * toggle, panel, Environment section, and project row against the real + * ui-session-panel plugin halves: the browser entry's dictionaries, fold + * control Factory, header toggle, panel, Environment section, and project row against the real * SlotRegistry, the inject faces those entries receive, the section roster * projection, fiber teardown removing every contribution (HMR safety), and * the inert node entry. @@ -57,8 +57,10 @@ describe('ui-session-panel browser half', () => { expect(inject).toEqual(['slots', 'locale', 'remote']) }) - it('registers the toggle first among the header utilities, the panel in the Chat aside, the Environment section, and the project row', async () => { + it('registers the fold control and row details Factories, the toggle first among the header utilities, the panel in the Chat aside, the Environment section, and the project row', async () => { const { ctx } = await bench() + expect(ctx.slots.snapshot('factory:conversation.session.panel.fold')).toHaveLength(1) + expect(ctx.slots.snapshot('factory:conversation.session.panel.details')).toHaveLength(1) const toggle = ctx.slots.entries('conversation.session.header.utilities').find(entry => entry.options.id === 'session-panel') expect(toggle?.options.order).toBe(-10) expect(ctx.slots.entries('conversation.chat.aside')).toHaveLength(1) @@ -128,6 +130,8 @@ describe('ui-session-panel browser half', () => { it('removes every contribution with the fiber (HMR safety)', async () => { const { ctx, fiber } = await bench() await fiber.dispose() + expect(ctx.slots.snapshot('factory:conversation.session.panel.fold')).toHaveLength(0) + expect(ctx.slots.snapshot('factory:conversation.session.panel.details')).toHaveLength(0) expect(ctx.slots.entries('conversation.session.header.utilities')).toHaveLength(0) expect(ctx.slots.entries('conversation.chat.aside')).toHaveLength(0) expect(ctx.slots.entries('conversation.session.panel.section')).toHaveLength(0) diff --git a/packages/client/ui-session-panel/tests/components.client.spec.tsx b/packages/client/ui-session-panel/tests/components.client.spec.tsx index 613ad0c5fd..81cf2211d5 100644 --- a/packages/client/ui-session-panel/tests/components.client.spec.tsx +++ b/packages/client/ui-session-panel/tests/components.client.spec.tsx @@ -4,14 +4,17 @@ import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { useRef, type ReactNode } from 'react' import { useModalLayer } from '@deepseek-ai/dsh-client-ui-primitives' import { bindSnapshotSelector, contextMenuHook, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { FactoryComponentPropsOf } from '@deepseek-ai/dsh-client-ui-slots' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { EnvironmentSection } from '../src/client/EnvironmentSection.tsx' +import { PanelDetails } from '../src/client/PanelDetails.tsx' +import { PanelFold } from '../src/client/PanelFold.tsx' import { ProjectRow } from '../src/client/ProjectRow.tsx' import { SessionPanel } from '../src/client/SessionPanel.tsx' import { SessionPanelToggle } from '../src/client/SessionPanelToggle.tsx' import type { - EnvironmentSectionProps, ProjectRowProps, SessionPanelDockable, SessionPanelProbes, SessionPanelProps, SessionPanelSectionEntry, - SessionPanelSectionOwnerProps, SessionPanelToggleProps, SessionPanelVisibility, + EnvironmentSectionProps, PanelDetailsProps, ProjectRowProps, SessionPanelDockable, SessionPanelProbes, SessionPanelProps, + SessionPanelSectionEntry, SessionPanelSectionOwnerProps, SessionPanelToggleProps, SessionPanelVisibility, } from '../src/client/slots.ts' import { SessionPanelState } from '../src/client/visibility.ts' import { en, zh } from '../src/client/locales.ts' @@ -367,10 +370,12 @@ describe('SessionPanel', () => { }) describe('EnvironmentSection', () => { - it('renders its rows straight into the section body', () => { + it('renders its rows straight into the section body with the section owner values', () => { const renderSlot = vi.fn(() => row) - render(<>{EnvironmentSection({ renderSlot } as EnvironmentSectionProps)}) - expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.environment.row', {}) + const dismissOverlay = vi.fn<() => void>() + render(<>{EnvironmentSection({ presentation: 'overlay', dismissOverlay, renderSlot } as Pick as EnvironmentSectionProps)}) + expect(renderSlot).toHaveBeenCalledWith('conversation.session.panel.environment.row', { presentation: 'overlay', dismissOverlay }) expect(screen.getByText('row')).toBeTruthy() }) }) @@ -463,6 +468,79 @@ describe('ProjectRow', () => { }) }) +describe('PanelFold', () => { + type FoldProps = FactoryComponentPropsOf<'conversation.session.panel.fold'> + + /** Render the control with the props a list passes; the renderer's standard seats are left out, as the control reads none. */ + function fold(expanded: boolean) { + const onToggle = vi.fn<() => void>() + const props = { + expanded, onToggle, + label: expanded ? 'Show less' : 'Show 14 more', + name: expanded ? 'Show less (subagents)' : 'Show 14 more (subagents)', + } as Pick as FoldProps + const view = render() + return { onToggle, row: view.container.firstElementChild as HTMLElement } + } + + it('is a panel row whose body is the button, with a down chevron in the icon part while rows are held back', () => { + const { row, onToggle } = fold(false) + expect(row.getAttribute('data-session-panel-row')).toBe('fold') + expect([...row.children].map(part => `${part.tagName}:${part.getAttribute('data-row-part') ?? ''}`)).toEqual(['BUTTON:body']) + const button = screen.getByRole('button', { name: 'Show 14 more (subagents)' }) + expect(button.getAttribute('aria-expanded')).toBe('false') + expect([...button.children].map(part => part.getAttribute('data-row-part'))).toEqual(['icon', 'content']) + expect(button.children[0]?.getAttribute('aria-hidden')).toBe('true') + expect(button.querySelector('svg')?.getAttribute('data-icon')).toBe('dsw-icon-chevron-down-outline-regular') + expect(button.children[1]?.textContent).toBe('Show 14 more') + fireEvent.click(button) + expect(onToggle).toHaveBeenCalledOnce() + }) + + it('points the chevron up and reports expanded once the list shows every row', () => { + const { row } = fold(true) + const button = screen.getByRole('button', { name: 'Show less (subagents)' }) + expect(button.getAttribute('aria-expanded')).toBe('true') + expect(row.querySelector('svg')?.getAttribute('data-icon')).toBe('dsw-icon-chevron-up-outline-regular') + expect(row.querySelector('[data-row-part="content"]')?.textContent).toBe('Show less') + }) +}) + +describe('PanelDetails', () => { + /** Render the details with the props a row passes; the renderer's standard seats are left out, as the details read none. */ + function details(input: PanelDetailsProps): HTMLElement { + const view = render(} />) + return view.container.querySelector('[data-session-panel-details]') as HTMLElement + } + + it('stacks the title, lines, state, and measures in order, each measure after the icon of its kind', () => { + const root = details({ + title: 'Survey open-source harnesses', + lines: ['Owner: open-source-arch'], + status: { state: 'done', label: 'Completed' }, + facts: [{ kind: 'tokens', label: '3.3M tok' }, { kind: 'duration', label: '6m 56s' }], + }) + expect([...root.children].map(child => child.textContent)) + .toEqual(['Survey open-source harnesses', 'Owner: open-source-arch', 'Completed', '3.3M tok6m 56s']) + expect(root.children[2]?.querySelector('[data-state="done"]')).not.toBeNull() + const facts = [...(root.children[3] as HTMLElement).children] + expect(facts.map(fact => [fact.getAttribute('data-fact'), fact.querySelector('svg')?.getAttribute('data-icon')])).toEqual([ + ['tokens', 'dsw-icon-database-outline-regular'], + ['duration', 'dsw-icon-clock-outline-regular'], + ]) + expect(facts.every(fact => fact.firstElementChild?.getAttribute('aria-hidden') === 'true')).toBe(true) + }) + + it('renders only the title when nothing else is given', () => { + expect(details({ title: 'sleep 30' }).children).toHaveLength(1) + }) + + it('starts with the lines when the title is omitted', () => { + const root = details({ lines: ['bash'], status: { state: 'ongoing', label: 'running' } }) + expect([...root.children].map(child => child.textContent)).toEqual(['bash', 'running']) + }) +}) + describe('dictionaries', () => { it('keeps the English dictionary key-identical to the Chinese source of truth', () => { expect(Object.keys(en).sort()).toEqual(Object.keys(zh).sort()) diff --git a/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts index 048c87a7a7..fb87b56c88 100644 --- a/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts +++ b/packages/client/ui-session-panel/tests/session-panel-styles.client.spec.ts @@ -89,6 +89,24 @@ describe('SessionPanel.module.css row rules', () => { }) }) + it('grows a row with a detail line and keeps the icon level with the first line', () => { + const tall = "[data-session-panel-row] > [data-row-part='body']:has([data-row-part='detail'])" + expect(row(tall)).toEqual({ 'align-items': 'flex-start', 'height': 'auto', 'padding': '4px 0' }) + expect(row(`${tall} > [data-row-part='icon']`)).toEqual({ height: '20px' }) + expect(row("[data-session-panel-row] [data-row-part='lines']")).toMatchObject({ 'display': 'flex', 'flex-direction': 'column', 'min-width': '0' }) + expect(row("[data-session-panel-row] [data-row-part='detail']")).toMatchObject({ + 'color': 'var(--dsw-alias-label-tertiary)', 'font-size': '12px', 'line-height': '17px', 'text-overflow': 'ellipsis', 'white-space': 'nowrap', + }) + // The two-line rules follow the one-line ones they adjust, since every rule for a part has the same specificity. + const order = (selector: string): number => { + const at = css.indexOf(`.panel :where(${selector}) {`) + expect(at).toBeGreaterThan(-1) + return at + } + expect(order(tall)).toBeGreaterThan(order("[data-session-panel-row] > button[data-row-part='body']")) + expect(order(`${tall} > [data-row-part='icon']`)).toBeGreaterThan(order("[data-session-panel-row] [data-row-part='icon']")) + }) + it('makes a button body the action of the whole row and rings the row when it has keyboard focus', () => { expect(row("[data-session-panel-row] > button[data-row-part='body']", '::after')).toMatchObject({ position: 'absolute', inset: '0' }) expect(row("[data-session-panel-row] > [data-row-part='trailing'], [data-session-panel-row] > [data-row-part='menu']")) @@ -105,7 +123,10 @@ describe('SessionPanel.module.css row rules', () => { it('highlights only a row with an action or a menu that renders something, and keeps an open menu and its row shown', () => { const interactive = "[data-session-panel-row]:has(> button[data-row-part='body'], > [data-row-part='menu']:not(:empty))" expect(row("[data-session-panel-row] > [data-row-part='menu']:empty")).toEqual({ display: 'none' }) - expect(row(`${interactive}:has([aria-expanded='true'])`)['background']).toBe('var(--dsw-alias-interactive-bg-hover)') + // Only an open control in the menu part keeps the row highlighted; an expanded body button does not. + expect(row("[data-session-panel-row]:has(> [data-row-part='menu'] [aria-expanded='true'])")) + .toEqual({ background: 'var(--dsw-alias-interactive-bg-hover)' }) + expect(css).not.toMatch(/:has\(\[aria-expanded='true'\]\)\)\s*\{\s*background/) expect(row("[data-session-panel-row] > [data-row-part='menu']:has([aria-expanded='true'])")['opacity']).toBe('1') // Hover rules stay inside the hover media query, where the menu hides until the row is hovered or focused. const hover = /@media \(hover: hover\) \{([\s\S]*?)\n\}/.exec(css)?.[1] ?? '' @@ -113,4 +134,22 @@ describe('SessionPanel.module.css row rules', () => { expect(hover).toMatch(/\[data-row-part='menu'\]\) \{\s*opacity: 0;/) expect(css.replace(/@media \(hover: hover\) \{[\s\S]*?\n\}/g, '')).not.toContain(':hover') }) + + it('sets a fold control in the quiet type of the section counts with a 14px chevron, darker on hover and keyboard focus', () => { + const fold = "[data-session-panel-row='fold']" + expect(row(fold)).toEqual({ + 'color': 'var(--dsw-alias-label-tertiary)', 'font': 'var(--dsw-font-xxs-12)', 'font-variant-numeric': 'tabular-nums', + }) + expect(row(`${fold} [data-row-part='icon']`, ' svg')).toEqual({ width: '14px', height: '14px' }) + expect(row(`${fold}:has(> button:focus-visible)`)).toEqual({ color: 'var(--dsw-alias-label-secondary)' }) + expect(row(`${fold}:hover`)).toEqual({ color: 'var(--dsw-alias-label-secondary)' }) + // The fold rules follow the row rules they adjust, since every rule for a part has the same specificity. + const at = (selector: string, tail = ''): number => { + const index = css.indexOf(`.panel :where(${selector})${tail} {`) + expect(index).toBeGreaterThan(-1) + return index + } + expect(at(fold)).toBeGreaterThan(at('[data-session-panel-row]')) + expect(at(`${fold} [data-row-part='icon']`, ' svg')).toBeGreaterThan(at("[data-session-panel-row] [data-row-part='icon']", ' svg')) + }) }) diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml index 7381b1f9d5..855eca71ba 100644 --- a/packages/client/ui-subagent/README.i18n.yaml +++ b/packages/client/ui-subagent/README.i18n.yaml @@ -3,23 +3,23 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-subagent/README.md /: - en: ff1b1fbd0d7f629b - zh: c68a59640e73c0ce + en: 49ee66424b5c8618 + zh: 4441c8abb6dc84d3 /deepseek-ai-dsh-client-ui-subagent: en: 930db612ece65ad4 zh: ad7e9d9afb4545ac /deepseek-ai-dsh-client-ui-subagent/summary: - en: 6e0bbf514ad3bef7 - zh: 5a29d88c124d35cc + en: bf25f4c1e4529221 + zh: f47270149bb0466f /deepseek-ai-dsh-client-ui-subagent/table-of-contents: en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-subagent/use-this-package: - en: c7a9485c0cdcd9de - zh: 903ad54e44d79eae + en: 77677cfa89b26de8 + zh: 83909430c95f3a6b /deepseek-ai-dsh-client-ui-subagent/use-this-package/browsing-the-tree: - en: 35e983f0276188d0 - zh: df588dc1523031da + en: da87d582146106c4 + zh: f640b3a3fcc11209 /deepseek-ai-dsh-client-ui-subagent/use-this-package/continuing-a-conversation: en: e4ec261d3b122eb5 zh: 320bb2efc93dccdc @@ -30,17 +30,17 @@ en: c158f12dcaed87b7 zh: e5d315e7b1fb4fa9 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/catalog-derivation: - en: 3c06acc93d7d4d59 - zh: b967155aec39df0c + en: 00965349c6aa0639 + zh: 465e3585dc7c9131 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/duration-completion-and-tokens: - en: dcbc58d4cad47fa8 - zh: e962a8cbdfd4a914 + en: 88ac879a43f1a8d7 + zh: f62c7b02e3658507 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/composer-election: - en: 8ff34f93e40fbdc2 - zh: cc3430130c9df0a4 + en: b56cfe4a6bc89088 + zh: c0d15e2b96df11ae /deepseek-ai-dsh-client-ui-subagent/further-exploration: - en: 1766e9012e307178 - zh: f3ee637f5941aae5 + en: 24c8ea783899b577 + zh: baa248477f0b9474 /deepseek-ai-dsh-client-ui-subagent/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 @@ -57,8 +57,8 @@ en: de2762a99572475f zh: 9b41107ad14ebf8a /deepseek-ai-dsh-client-ui-subagent/known-limitations-and-deferred-work: - en: ea983111988e4b9b - zh: c0ed7a583d2cad52 + en: de28efa7934ae6aa + zh: 5f3f682c10c1ce4c /deepseek-ai-dsh-client-ui-subagent/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-subagent/README.md b/packages/client/ui-subagent/README.md index 555c6fd2d9..e1a6e31218 100644 --- a/packages/client/ui-subagent/README.md +++ b/packages/client/ui-subagent/README.md @@ -1,5 +1,5 @@ --- -description: "Subagent conversation catalog, continuation routing UI, and '@' reference source for the dsh web client." +description: "Subagent conversation catalog in the Session panel, breadcrumb sibling switcher, continuation routing UI, and '@' reference source for the dsh web client." kind: "package-reference" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Browse local subagent conversations and external tasks from the parent header. Local conversations show activity, token usage, and duration; continuable children accept follow-up prompts and support Stop. External tasks appear as non-navigable leaves without an execution status. Historical one-shot conversations open as read-only records. The ordinary sidebar omits subagent conversations, and the separate `@` source inserts a running child's label without granting continuation authority. +Browse local subagent conversations and external tasks in the Session panel's Subagents section, and switch between siblings from a child conversation's breadcrumb. Local conversations show activity, token usage, and duration; continuable children accept follow-up prompts and support Stop. External tasks appear as non-navigable leaves without an execution status. Historical one-shot conversations open as read-only records. The ordinary sidebar omits subagent conversations, and the separate `@` source inserts a running child's label without granting continuation authority. ## Table of Contents @@ -25,21 +25,21 @@ Browse local subagent conversations and external tasks from the parent header. L ## Use this package -The session header uses the session title for ordinary breadcrumbs. Subagent breadcrumbs prefer the original creation description (`entry.label`), then the agent name (`entry.name`), then the Session id. Ordinary and subagent breadcrumb titles both use 14px text with a 20px line height. When the session's direct catalog has entries or a read has failed, the descendant-count trigger renders after the preset label in the header actions band, with no breadcrumb separator. An absent or empty catalog hides the count trigger unless the root Session has an enabled, available Team board with shared tasks or a task-record error. Enabling Team mode alone does not show an empty entry. The trigger opens that direct catalog, uses the total count as its accessible name and the running count as its accessible description, and discovers the next level on explicit activation. Select a local child at any depth to open that child's conversation with its exact `{parentSessionId, childSessionId, mode}` address, or use a noncurrent local row's trailing arrow to open the same address in the right Sidebar, preferring a separate pane when room permits. +The session header uses the session title for ordinary breadcrumbs. Subagent breadcrumbs prefer the original creation description (`entry.label`), then the agent name (`entry.name`), then the Session id. Ordinary and subagent breadcrumb titles both use 14px text with a 20px line height. Each subagent breadcrumb title is a switcher over its parent's direct catalog that marks the title's Session as current; root Sessions have no switcher. The [Session panel](../ui-session-panel/README.md#contribute-a-section) section `subagents` (order 200, titled “Subagents”) lists the current Session's direct catalog, in root and child conversations alike, when the catalog has entries or a read has failed. Showing the section reads nothing; expanding a branch prepares that branch. An absent or empty catalog hides the section and its title unless a footer contribution is available and the Session's enabled `agentTeam` projection has nondeleted shared tasks or a task-record error. Enabling Team mode alone does not show an empty section. Select a local child at any depth to open that child's conversation with its exact `{parentSessionId, childSessionId, mode}` address, or use a noncurrent local row's trailing arrow to open the same address in the right Sidebar, preferring a separate pane when room permits. Either action closes the panel's overlay or the switcher menu that holds the row. This package registers the `dsh-resource://subagentchat/session/?parent=&mode=` resource and builtin Sidebar tab type. The resource retains the child `SessionReference` directly from its address without refreshing the parent catalog, and releases the reference when the tab record closes. The tab renders the shared `conversation.content` Factory through `sidebar.chat.conversation`, fixes the local View to Chat, and omits the main Conversation header and width controls. -Every open catalog menu is 360px wide with 6px outer padding, constrained to fit the layout viewport. The root menu shows noncollapsible Subagents and Shared tasks headers only when Team mode is enabled, at least one nondeleted shared task exists, and the footer contribution is available. The Subagents header uses a Users icon and counts direct entries in completed, in progress, not running, and external order; zero counts are omitted and the separator matches the input task list. External tasks never count as running or completed. An empty Subagents section shows “No subagents” only alongside shared tasks. With Team mode off or no shared tasks, the menu shows only the subagent list, without section headers, a shared-task module, empty-state copy, or a divider; a real task-record failure remains a separate alert. 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; sections have no nested scrolling. In WebKit-compatible browsers, the native 5px scrollbar sits in the right 6px inset with inset track ends and a stable gutter, preserving content width when scrolling becomes necessary. Other browsers retain their standard native scrollbar. +The section's title control (`conversation.session.panel.section.actions`, key `subagents`) shows direct-member progress: completed, in progress, not running, and external counts in that order, with zero counts omitted and the separator matching the input task list. External tasks never count as running or completed. The section lists running subagents first, the most recently started first, and then the others, the most recently updated first. It shows five rows 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 rows or more, the choice holds for the Session, also after the panel is hidden and shown again, and an expanded branch's own rows all show. The section hides with its title while the Session has no subagents and no failed catalog read. While direct subagents 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; external tasks do not count. The Session panel scrolls the section; the tree has no nested scrolling. The breadcrumb switcher menu is 360px wide with 6px outer padding, constrained to fit the layout viewport, and only the menu scrolls. In WebKit-compatible browsers, its native 5px scrollbar sits in the right 6px inset with inset track ends and a stable gutter, preserving content width when scrolling becomes necessary. Other browsers retain their standard native scrollbar. -The root catalog exposes `conversation.session.header.actions.subagent.footer` for shared tasks. Child and ancestor breadcrumb catalogs show navigation only, without section headers. +Breadcrumb switcher menus show navigation only. -The wide root count trigger shows a 14px Users icon in its 14px slot when no child is running and the shared ongoing loader otherwise, without a dropdown arrow. As the title row narrows, passive preset text hides at widths of 540px or less and the count text hides at 460px or less. The compact trigger always shows the Users icon, including while children are running; running indicators remain inside the menu. It matches More and sidebar controls: a 28×28px action 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. The icon-only tooltip exposes the full count. Resizing preserves focus on the trigger. Subagent switchers retain their description-first text and existing icon. +The switcher title is at most 244px wide, ellipsizes, and is followed by an up-down chevron icon. The current Session's title uses primary ink at weight 500; an ancestor's title uses tertiary ink at regular weight. ### Browsing the tree -Count, owner, and sidebar-action tooltips appear after 500ms of hover. Hovering a text-visible trigger opens its catalog after 150ms; leaving both trigger and catalog closes it after 120ms. Clicking the descendant-count trigger opens and pins its catalog, or closes an already pinned catalog. The icon-only count trigger does not open on hover, including when a pending hover crosses into the narrow layout. Clicking toggles its pinned menu; ArrowDown opens and pins the menu and focuses its first row. Outside click or Escape dismisses a pinned menu. Clicking moves focus into the panel, where ArrowDown/Home enters the first tree row and ArrowUp/End enters the last; Escape returns focus when it was inside. Breadcrumb-title clicks navigate to the corresponding conversation. +The sidebar-action tooltip appears after 500ms of hover. Hovering a switcher with a non-touch pointer opens its menu after 150ms; leaving both the switcher and its menu closes it after 120ms. Clicking the current Session's title opens and pins the menu and moves focus into it, and a pinned menu ignores pointer leave; clicking an ancestor's title navigates to that ancestor instead. ArrowDown on a switcher opens its menu and focuses the first row; on an open menu it moves focus into the menu, to the first row once the rows have loaded. An outside press or Escape closes the menu, and Escape returns focus to the switcher when focus was inside the menu. -Rows show the creation description, or an available Session title, above the agent name, which is unique among its siblings. Entries recorded without a name show the Session id in its place. Without either description, the row shows only the name or Session id. Navigation, row identity, and Sidebar addresses always use the Session id. Local rows use compact 4px vertical padding; their clickable content uses 6px horizontal padding and 7px gaps, aligned with shared-task rows while retaining the tree's left offset. A decorative trailing check marks the current conversation and is not an action; other local rows retain the sidebar arrow. Primary titles use 13px text and secondary names use 12px. All rows wrap descriptions and names in full, including on touch screens. Running uses the shared ongoing loader, an inactive child whose latest closed turn completed normally uses the shared success dot, and other inactive children use the shared idle dot. Every row reserves the same 14px status column, centering smaller dots so titles align with the loader state. The text-visible header trigger vertically centers its activity glyph and count with a 4px gap. The trailing column stacks total durable provider usage above active-turn duration. Keyboard navigation works with ArrowRight/ArrowLeft to expand and collapse branches and ArrowUp/ArrowDown, Home, End, and Escape to navigate or close the tree. An unlabeled one-shot row falls back to its session id. Only rows with confirmed children show an expansion arrow. Clicking or keyboard-opening the menu reads its catalog and its direct children; expanding a branch does the same for that branch. Each activation reads direct children sequentially through the existing projection reader, which reuses completed reads and merges in-flight requests. It does not recursively discover deeper descendants. Hover and rendering do not initiate reads. Once started, a level read may finish after the menu closes. Missing catalogs show no expansion arrow or unknown marker; shared projection updates reveal confirmed branches while preserving the agent activity marker. Failed reads keep navigation available and offer Retry. +Rows show the creation description, or an available Session title, with the agent name, which is unique among its siblings: in switcher menus the name sits below the title, and in the Session panel each row is one 28px line whose hover card, after 500ms of hover, shows the title, the name as its owner, the activity with the mode, and the token total and exact duration. Entries recorded without a name show the Session id in its place. Without either description, the row shows only the name or Session id. Navigation, row identity, and Sidebar addresses always use the Session id. Local rows use compact 4px vertical padding. In the Session panel they follow the panel's columns: the status glyph's center 14px from the row start, titles at 30px, and the sidebar arrow's center 14px from the row end. In switcher menus, their clickable content uses 6px horizontal padding and 7px gaps while retaining the tree's left offset. A decorative trailing check marks the current conversation and is not an action; other local rows retain the sidebar arrow, a 24px target whose glyph darkens on hover without a fill in the panel and in switcher menus alike. Primary titles use 13px text and secondary names use 12px. Switcher rows wrap descriptions and names in full, including on touch screens; panel titles clip with an ellipsis, and the row's accessible name keeps the name, mode, activity, and measures. Running uses the shared ongoing loader, an inactive child whose latest closed turn completed normally uses the shared success dot, and other inactive children use the shared idle dot. Every row reserves the same status column, 16px in the panel and 14px in switcher menus, centering smaller dots so titles align with the loader state. In switcher menus the trailing column stacks total durable provider usage above active-turn duration; panel rows show only the compact duration, in 12px text. In the tree, Enter or Space opens the focused row, ArrowRight/ArrowLeft expand and collapse branches, and ArrowUp/ArrowDown, Home, and End move between rows. An unlabeled one-shot row falls back to its session id. Only rows with confirmed children show an expansion arrow. Preparing a level reads its catalog and its direct children sequentially through the existing projection reader, which reuses completed reads and merges in-flight requests; it does not recursively discover deeper descendants. Once started, a level read may finish after the panel hides or the menu closes. Missing catalogs show no expansion arrow or unknown marker; shared projection updates reveal confirmed branches while preserving the agent activity marker. Failed reads keep navigation available and offer Retry. ### Continuing a conversation @@ -61,17 +61,17 @@ The [subagent runtime](../../subagent/subagent/README.md) owns continuation and ### Catalog derivation -The header lineage renderer reads `subagentCatalog` only from `projectionsBySession` through the standard `useSessions` hook. The Session object layer merges list-cache hints, explicit reads, and the Host-wide control stream into these shared values; live frames update loaded levels without per-menu subscriptions. Activity prefers the unified UI status and falls back to Session summaries; summaries also supply titles and usage. Rendering and hovering use only local projections and never request missing catalogs. An unread empty menu says “Subagents not loaded”; the loading notice appears only during a request. Missing and explicitly empty catalogs have no expansion arrow; a later shared projection with children makes the arrow available. Failures require explicit retry. Migration-required rows keep their history-opening actions without a format notice or descendant expansion; opening the Session supplies its catalog through history and control projections. External rows are always leaves and do not load child Sessions. +The Subagents section, its progress control, and the breadcrumb switcher read `subagentCatalog` only from `projectionsBySession` through the standard `useSessions` hook. The Session object layer merges list-cache hints, explicit reads, and the Host-wide control stream into these shared values; live frames update loaded levels without per-tree subscriptions. Activity prefers the unified UI status and falls back to Session summaries; summaries also supply titles and usage. Showing the section, rendering, and hovering use only local projections and never request missing catalogs. An unread empty switcher menu says “Subagents not loaded”; the loading notice appears only during a request. Missing and explicitly empty catalogs have no expansion arrow; a later shared projection with children makes the arrow available. Failures require explicit retry. Migration-required rows keep their history-opening actions without a format notice or descendant expansion; opening the Session supplies its catalog through history and control projections. External rows are always leaves and do not load child Sessions. -Each header entry declares a footer slot below its tree. Optional UI contributes there within the same scroll container; the catalog owns opening and dismissal. CSS anchors keep the panel 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. Internal scrolling, hover behavior, pinned opening, and focus restoration remain independent. +The Session panel owns showing, scrolling, and dismissing the section. The switcher menu is a body-mounted `MenuSurface`; CSS anchors keep it attached to its title within layout-viewport size limits. Browser zoom and panning move it with the page, so it may extend beyond the visual viewport. Internal scrolling, hover behavior, pinned opening, and focus restoration remain independent. -Explicit menu activation, branch expansion, and failed-read retries call `prepareCatalog` to read the current catalog and its direct children. Ancestor-title clicks navigate to that Session. The Session object layer deduplicates reads and refreshes previously requested projections after reconnect. +A pinning click or ArrowDown on a switcher title, branch expansion, and failed-read retries call `prepareCatalog` to read the current catalog and its direct children; a rejected preparation is logged to the console. Ancestor-title clicks navigate to that Session. The Session object layer deduplicates reads and refreshes previously requested projections after reconnect. Breadcrumb addresses derive from the Provider-bound Session address, loaded parent catalogs, or already-listed subagent lineage, including never-selected ancestors. ### Duration, completion, and tokens -Each visible catalog level advances its own clock while it contains a running child; collapsing the level or closing the menu releases that clock. Token totals sum the four disjoint `tokenUsage` buckets. The `subagentTiming` projection sums completed-turn duration and supplies `latestTurnCompleted` for both the success dot and completed count; opening another turn clears that completion until its own `turn/end`. Duration advances once per second only for an open turn on a running child and freezes after the child becomes inactive; an interrupted open turn is bounded by its same-cut `active.through`, never by newer session metadata. +Each visible catalog level advances its own clock while it contains a running child; collapsing the level, hiding the panel, or closing the switcher menu releases that clock. Token totals sum the four disjoint `tokenUsage` buckets. The `subagentTiming` projection sums completed-turn duration and supplies `lastTurnCompleted` for both the success dot and completed count; opening another turn clears that completion until its own `turn/end`. Duration advances once per second only for an open turn on a running child and freezes after the child becomes inactive; an interrupted open turn is bounded by its same-cut `active.through`, never by newer session metadata. ### Composer election @@ -79,7 +79,7 @@ One-shot and unknown-mode children elect a read-only composer. Continuable child Unknown-mode catalog rows remain visible and clickable, using the child id when no label is available. Their composer is read-only until child history establishes a supported mode; a read failure is reported in the child conversation. -Lineage-menu highlights follow the [standard menu edge geometry](../../../docs/ui-radius.md#nested-hover). Each branch disclosure target covers its 28px left gutter and full row height without overlapping adjacent rows; only the 12px glyph rotates in place, and disclosure clicks do not trigger row or sidebar navigation. Disclosure hover highlights only its arrow; navigation-body hover and keyboard focus retain their background highlight. Thin level-3 border connectors align with the first-line glyph centers, cross reserved disclosure space to reach leaf status glyphs, and end the final vertical stem at its glyph center. +Catalog row highlights use the standard menu item radius from the [nested geometry rules](../../../docs/ui-radius.md#nested-hover). Each branch disclosure target covers its 28px left gutter and full row height without overlapping adjacent rows; only the 12px glyph rotates in place, and disclosure clicks do not trigger row or sidebar navigation. Disclosure hover highlights only its arrow; navigation-body hover and keyboard focus retain their background highlight. Thin level-3 border connectors align with the first-line glyph centers, cross reserved disclosure space to reach leaf status glyphs, and end the final vertical stem at its glyph center. @@ -90,7 +90,8 @@ Lineage-menu highlights follow the [standard menu edge geometry](../../../docs/u These pages cover the conversation surface, the host seam, and the design notes. -- [ui-conversation](../ui-conversation/README.md) — the chat surface hosting the header action and composer chain. +- [ui-conversation](../ui-conversation/README.md) — the chat surface hosting the breadcrumb lineage and composer chain. +- [ui-session-panel](../ui-session-panel/README.md) — the Session panel hosting the Subagents section. - [ui-input-trigger](../ui-input-trigger/README.md) — the suggestion machinery hosting the `@` source. - [subagent](../../subagent/subagent/README.md) — the host-side capability seam behind continuable children. - [historical Web subagent conversations](../../../.agents/notes/archived/feature/2026-07-27-web-subagent-conversations.md) — the catalog and composer specification. @@ -125,6 +126,7 @@ These limits define what the catalog can show and what `@` references mean; they - **Non-completed inactive outcomes remain grouped** — the catalog distinguishes a latest normal completion from other inactive states, but does not distinguish failure, cancellation, refusal, token exhaustion, or a child with no closed turn; the UI exposes no Activation identity, and stopping is limited to the composer's current-turn Stop for a running continuable child. - **Ancestor menus require keyboard activation for uncached branches** — hovering does not read, and clicking the ancestor title navigates. Focus the title and press ArrowDown to prepare that level without leaving the current Session. - **Level discovery stops on interruption** — an unexpected read rejection stops later siblings and is logged to the console. A reconnect can interrupt discovery before direct children are read; explicitly reopen the menu to prepare the level again. +- **The Session panel section has no level activation** — showing the section reads nothing, so a direct subagent whose catalog the Session list has not cached offers no expansion arrow there until its catalog arrives, for example after its own conversation opens or a sibling's breadcrumb switcher prepares the level. - **`@` references remain display-title text** — duplicate or renamed labels are ambiguous, so they intentionally do not acquire continuation semantics. diff --git a/packages/client/ui-subagent/README.zh.md b/packages/client/ui-subagent/README.zh.md index 056fad6cde..eaf55b25f9 100644 --- a/packages/client/ui-subagent/README.zh.md +++ b/packages/client/ui-subagent/README.zh.md @@ -1,5 +1,5 @@ --- -description: "dsh Web 客户端的 subagent 对话目录、续接路由 UI 与 '@' 引用 source。" +description: "dsh Web 客户端会话面板中的 subagent 对话目录、面包屑同级切换器、续接路由 UI 与 '@' 引用 source。" kind: "package-reference" --- @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -从父会话页头浏览本地子代理对话与外部任务。本地对话展示活跃状态、token 用量和耗时;可继续子代理接受后续提示词并支持 Stop。外部任务显示为不可打开的叶子项,不展示执行状态。历史一次性对话以只读记录打开。普通侧边栏省略子代理对话;独立的 `@` 来源插入运行中子代理的标签,不授予继续执行权限。 +在会话面板的「子智能体」分栏中浏览本地子代理对话与外部任务,并从子会话的面包屑切换同级子代理。本地对话展示活跃状态、token 用量和耗时;可继续子代理接受后续提示词并支持 Stop。外部任务显示为不可打开的叶子项,不展示执行状态。历史一次性对话以只读记录打开。普通侧边栏省略子代理对话;独立的 `@` 来源插入运行中子代理的标签,不授予继续执行权限。 ## 目录 @@ -25,21 +25,21 @@ kind: "package-reference" ## 使用本包 -会话页头的普通面包屑使用会话标题。subagent 面包屑优先使用创建时的原始描述(`entry.label`),其次使用智能体名称(`entry.name`),最后回退到 Session id。普通与 subagent 面包屑标题均使用 14px 文字和 20px 行高。当会话的直接目录有子项或读取失败时,后代数量触发器渲染在页头操作区中预设标签之后,不带任何面包屑分隔符。目录缺席或为空时隐藏数量触发器,除非根 Session 已开启且可用的 Team 任务板有共享任务或任务记录错误。仅开启 Team 模式不会显示空入口。触发器打开该直接目录,以总数作为无障碍名称、运行数作为无障碍描述,并在用户显式打开时发现下一层目录。选择任意深度,即可用该子会话的确切 `{parentSessionId, childSessionId, mode}` 地址打开其对话;也可以使用非当前本地行的行尾箭头在右侧 Sidebar 打开同一地址,并在空间允许时优先使用独立分栏。 +会话页头的普通面包屑使用会话标题。subagent 面包屑优先使用创建时的原始描述(`entry.label`),其次使用智能体名称(`entry.name`),最后回退到 Session id。普通与 subagent 面包屑标题均使用 14px 文字和 20px 行高。每个 subagent 面包屑标题都是覆盖其父会话直接目录的切换器,并把该标题对应的 Session 标为当前项;根 Session 没有切换器。[会话面板](../ui-session-panel/README.zh.md#contribute-a-section)分栏 `subagents`(order 200,标题为“子智能体”)在根会话和子会话中都列出当前 Session 的直接目录,前提是目录有子项或读取失败。显示分栏不读取任何内容;展开分支时准备该分支。目录缺席或为空时,分栏连同标题一起隐藏,除非存在可用的 footer 扩展,且 Session 已开启的 `agentTeam` 投影含有未删除的共享任务或任务记录错误。仅开启 Team 模式不会显示空分栏。选择任意深度的本地 child,即可用该子会话的确切 `{parentSessionId, childSessionId, mode}` 地址打开其对话;也可以使用非当前本地行的行尾箭头在右侧 Sidebar 打开同一地址,并在空间允许时优先使用独立分栏。两种操作都会关闭面板浮层或该行所在的切换器菜单。 本包注册 `dsh-resource://subagentchat/session/?parent=&mode=` 资源与 builtin Sidebar tab 类型。资源直接根据地址保留 child 的 `SessionReference`,不刷新 parent 目录,并在 tab 记录关闭时释放 reference。tab 通过 `sidebar.chat.conversation` 渲染共享 `conversation.content` Factory,把局部 View 固定为 Chat,并省略主 Conversation 的 Header 与宽度控制。 -每个打开的目录菜单宽度均为 360px,外层内边距为 6px,并受布局视口可用宽度约束。仅当 Team 模式已开启、存在至少一个未删除的共享任务且 footer 扩展可用时,根菜单才显示不可折叠的“子智能体”和“共享任务”标题。“子智能体”标题使用 Users 图标,仅统计直接条目,依次显示已完成、进行中、未运行和外部任务数量;省略零值,分隔符与输入区任务列表一致。外部任务不计入运行中或已完成数量。空的“子智能体”区域仅在同时展示共享任务时显示“暂无子智能体”。Team 模式关闭或没有共享任务时,菜单仅显示 subagent 列表,不显示区域标题、共享任务模块、空状态文案或分隔线;真实的任务记录错误仍以独立警告显示。共享任务上方保留 4px 外边距,不显示分隔线。两个区域标题均保留 7px 图标与文字间距,并在统计数量前额外留出 4px。仅菜单本身滚动,各区域不单独滚动。在兼容 WebKit 的浏览器中,原生 5px 滚动条位于右侧 6px 内边距内,轨道两端内缩,并保留稳定的滚动条空间,使内容在需要滚动时保持原有宽度。其他浏览器保留标准原生滚动条。 +分栏的标题控件(`conversation.session.panel.section.actions`,键为 `subagents`)显示直接成员进度:依次为已完成、进行中、未运行和外部任务数量;省略零值,分隔符与输入区任务列表一致。外部任务不计入运行中或已完成数量。分栏把运行中的子智能体排在最前,最近开始的在前,然后是其余的,最近更新的在前。它只显示五行,然后是会话面板的收起控件「显示其余 {count} 个」,点击后显示其余的行并变为「收起」;只有能收起两行及以上时列表才收起,这个选择在 Session 内保持,隐藏后再次显示面板也不变;展开某个分支后,该分支自己的行全部显示。会话没有子智能体且目录读取未失败时,分栏连同标题一起隐藏。直接子智能体运行中且面板未显示时,面板开关上的蓝点(`conversation.session.panel.indicator`)会提示这一状态,并向辅助技术说明数量;外部任务不计入。会话面板负责分栏滚动,目录树不单独滚动。面包屑切换器菜单宽度为 360px,外层内边距为 6px,并受布局视口可用宽度约束,仅菜单本身滚动。在兼容 WebKit 的浏览器中,其原生 5px 滚动条位于右侧 6px 内边距内,轨道两端内缩,并保留稳定的滚动条空间,使内容在需要滚动时保持原有宽度。其他浏览器保留标准原生滚动条。 -根会话目录通过 `conversation.session.header.actions.subagent.footer` 提供共享任务扩展。子会话与祖先面包屑目录只显示导航,不显示区域标题。 +面包屑切换器菜单只显示导航。 -宽布局下,根会话数量触发器在没有运行中 child 时,于 14px 图标位内显示 14px Users 图标,否则显示共享 ongoing loader,不带下拉箭头。标题行变窄时,静态预设文字在宽度不超过 540px 时隐藏,数量文字在不超过 460px 时隐藏。紧凑触发器始终显示 Users 图标,包括 child 运行期间;运行指示器仍在菜单内显示。它与更多及侧边栏控件一致:28×28px 操作区域,无内边距,15px 图标位内显示 15px 图标,使用次级前景色以及 ghost 悬停和按下背景。页头操作在紧凑布局中间距为 8px,宽布局中为 10px。纯图标工具提示提供完整数量。调整宽度不会丢失触发器焦点。subagent 切换器保留描述优先的文本与原有图标。 +切换器标题最宽 244px,超出时以省略号截断,后接上下双向箭头图标。当前 Session 的标题使用主前景色、字重 500;祖先标题使用三级前景色、常规字重。 ### 浏览目录 -数量、负责人及侧边栏操作的工具提示在悬停 500ms 后显示。悬停文字可见的触发器 150ms 后打开目录;指针离开触发器和目录后,经过 120ms 关闭。点击后代数量触发器会打开并固定目录,或关闭已固定的目录。纯图标数量触发器不会因悬停而打开,包括等待悬停打开期间切换到窄布局的情况。点击可切换固定菜单的开关状态;ArrowDown 会打开并固定菜单,并将焦点移至首行。点击外部或按 Escape 可关闭已固定的菜单。点击会将焦点移入面板,此时 ArrowDown/Home 进入首个树行,ArrowUp/End 进入最后一个树行;Escape 在焦点原本位于面板内时将其送回。点击面包屑标题会导航至对应会话。 +侧边栏操作的工具提示在悬停 500ms 后显示。非触摸指针悬停切换器 150ms 后打开其菜单;指针离开切换器和菜单后,经过 120ms 关闭。点击当前 Session 的标题会打开并固定菜单,并将焦点移入菜单,已固定的菜单不因指针离开而关闭;点击祖先标题则导航至该祖先。在切换器上按 ArrowDown 会打开菜单,并将焦点移至首行;菜单已打开时,焦点移入菜单,行加载完成后移至首行。点击外部或按 Escape 可关闭菜单;焦点原本位于菜单内时,Escape 将焦点送回切换器。 -目录行在智能体名称上方显示创建描述,缺少创建描述时使用可用的 Session title;名称在同级子智能体中唯一。没有名称的历史目录项在相同位置显示 Session id。两者均缺少时,该行仅显示名称或 Session id。导航、行身份与 Sidebar 地址始终使用 Session id。本地行使用紧凑的 4px 垂直内边距;可点击内容使用 6px 水平内边距和 7px 间距,与共享任务行对齐,同时保留树的左侧偏移。当前对话在行尾显示装饰性对勾,该对勾不是操作控件;其他本地行保留侧边栏箭头。主标题使用 13px 文字,次级名称使用 12px。所有行均将描述与名称换行完整展示,包括在触屏上。running 使用共享 ongoing loading,最近一个已结束轮次正常完成的 inactive child 使用共享 success 绿点,其他 inactive child 使用共享 idle 灰点。每行都为状态图标预留相同的 14px 列宽,并将较小的圆点居中,使 title 与 loading 状态对齐。文字可见的页头触发器会垂直居中活动图标与数量,并保留 4px 水平间距。尾随列在上行显示提供方的持久化 token 用量总计,在下行显示活跃轮次耗时。键盘导航:ArrowRight/ArrowLeft 展开和折叠分支;ArrowUp/ArrowDown、Home、End 与 Escape 用于导航或关闭树。没有 label 的 one-shot 行回退到其会话 id。只有确认存在下级的行才显示展开箭头。点击或通过键盘打开菜单时,读取当前目录及其直属子节点的目录;展开分支时对该分支执行相同操作。每次打开操作通过现有投影读取器依次读取直接子节点,复用已完成的读取并合并进行中的请求,不递归发现更深层后代。悬停与渲染不触发读取。已开始的单层读取可能在菜单关闭后完成。缺少目录的行不显示展开箭头或未知标记;共享投影更新确认存在下级后显示箭头,并保持 agent 活动状态图标。读取失败时保留导航操作并提供重试。 +目录行显示创建描述(缺少时使用可用的 Session title)和智能体名称,名称在同级子智能体中唯一:切换器菜单中名称位于标题下方;会话面板中每行只占 28px 一行,悬停 500ms 后的悬停卡片显示标题、作为负责人的名称、活动状态与模式,以及 token 总计和精确耗时。没有名称的历史目录项在相同位置显示 Session id。两者均缺少时,该行仅显示名称或 Session id。导航、行身份与 Sidebar 地址始终使用 Session id。本地行使用紧凑的 4px 垂直内边距。在会话面板中,它们遵循面板的列:状态图标中心距行起始 14px,标题从 30px 开始,侧边栏箭头中心距行末端 14px。在切换器菜单中,可点击内容使用 6px 水平内边距和 7px 间距,同时保留树的左侧偏移。当前对话在行尾显示装饰性对勾,该对勾不是操作控件;其他本地行保留侧边栏箭头:点击区域 24px,在面板和切换器菜单中都是悬停时箭头变深、没有底色。主标题使用 13px 文字,次级名称使用 12px。切换器菜单中的行将描述与名称换行完整展示,包括在触屏上;面板中的标题以省略号截断,行的无障碍名称仍包含名称、模式、活动状态与度量。running 使用共享 ongoing loading,最近一个已结束轮次正常完成的 inactive child 使用共享 success 绿点,其他 inactive child 使用共享 idle 灰点。每行都为状态图标预留相同的列宽(面板中 16px,切换器菜单中 14px),并将较小的圆点居中,使 title 与 loading 状态对齐。切换器菜单中,尾随列在上行显示提供方的持久化 token 用量总计,在下行显示活跃轮次耗时;面板中的行只以 12px 文字显示简短耗时。在目录树中,Enter 或 Space 打开获得焦点的行,ArrowRight/ArrowLeft 展开和折叠分支,ArrowUp/ArrowDown、Home 与 End 在行间移动。没有 label 的 one-shot 行回退到其会话 id。只有确认存在下级的行才显示展开箭头。准备一层时,通过现有投影读取器依次读取其目录及直接子节点的目录,复用已完成的读取并合并进行中的请求,不递归发现更深层后代。已开始的单层读取可能在面板隐藏或菜单关闭后完成。缺少目录的行不显示展开箭头或未知标记;共享投影更新确认存在下级后显示箭头,并保持 agent 活动状态图标。读取失败时保留导航操作并提供重试。 ### 续接对话 @@ -61,17 +61,17 @@ kind: "package-reference" ### 目录派生 -页头谱系 renderer 通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需每个菜单单独订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。渲染与悬停仅使用本地投影,不会请求缺失目录。尚未读取的空菜单显示“尚未加载子智能体”;仅请求进行中显示加载提示。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。 +「子智能体」分栏、其进度控件与面包屑切换器通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需逐树订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。显示分栏、渲染与悬停仅使用本地投影,不会请求缺失目录。尚未读取的空切换器菜单显示“尚未加载子智能体”;仅请求进行中显示加载提示。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。 -每个页头入口在树下方声明 footer 插槽。可选 UI 通过该插槽加入同一滚动容器;目录负责打开和关闭。CSS 锚点让面板跟随触发器,并按布局视口限制尺寸。浏览器缩放和平移时面板随页面移动,因此可以超出视觉视口。内部滚动、悬停行为、点击固定展开和焦点恢复保持独立。 +会话面板负责分栏的显示、滚动和关闭。切换器菜单是挂载到 body 的 `MenuSurface`;CSS 锚点让菜单跟随其标题,并按布局视口限制尺寸。浏览器缩放和平移时菜单随页面移动,因此可以超出视觉视口。内部滚动、悬停行为、点击固定展开和焦点恢复保持独立。 -显式激活菜单、展开分支或重试失败读取时,`prepareCatalog` 读取当前目录及其直接子节点。点击祖先标题会导航到该 Session。Session 对象层合并重复读取,并在重连后刷新之前请求过的投影。 +在切换器标题上固定打开的点击或按 ArrowDown、展开分支以及重试失败读取时,`prepareCatalog` 读取当前目录及其直接子节点;准备被拒绝时记录到控制台。点击祖先标题会导航到该 Session。Session 对象层合并重复读取,并在重连后刷新之前请求过的投影。 面包屑地址从 Provider 所绑定的 Session 地址、已加载的 parent 目录或已列出的 subagent 谱系推导,也包括从未选中过的祖先。 ### 耗时、完成状态与 token -每个可见目录层在包含运行中 child 时独立推进时钟;折叠该层或关闭菜单会释放时钟。token 用量总计为四个互不重叠的 `tokenUsage` 桶之和。`subagentTiming` 投影会累加已结束轮次的耗时,并提供 `latestTurnCompleted`,用于成功圆点与已完成数量;新轮次开始时会清除该完成状态,直到自身的 `turn/end` 到达。耗时仅在运行中 child 存在未结束轮次时每秒递增一次,并在 child 变为 inactive 后冻结;被中断的未结束轮次以其同一切面的 `active.through` 为上界,绝不使用更新的会话元数据。 +每个可见目录层在包含运行中 child 时独立推进时钟;折叠该层、隐藏面板或关闭切换器菜单会释放时钟。token 用量总计为四个互不重叠的 `tokenUsage` 桶之和。`subagentTiming` 投影会累加已结束轮次的耗时,并提供 `lastTurnCompleted`,用于成功圆点与已完成数量;新轮次开始时会清除该完成状态,直到自身的 `turn/end` 到达。耗时仅在运行中 child 存在未结束轮次时每秒递增一次,并在 child 变为 inactive 后冻结;被中断的未结束轮次以其同一切面的 `active.through` 为上界,绝不使用更新的会话元数据。 ### 编辑器选举 @@ -79,7 +79,7 @@ one-shot 和模式未知的 child 选用只读编辑器。可继续 child 经由 模式未知的目录项仍可见、可点击,没有标签时显示子会话 id。读取子历史并确认受支持模式前,输入区保持只读;读取失败在该子会话中报告。 -会话树菜单高亮遵循[标准菜单边缘几何](../../../docs/ui-radius.zh.md#nested-hover)。每个分支展开控件的点击区域覆盖左侧 28px 空间与所在行的完整高度,不与相邻行重叠;仅原位的 12px 图标旋转,点击展开控件不会触发行导航或侧边栏导航。悬停展开控件仅高亮箭头;悬停导航主体或键盘聚焦时仍保留背景高亮。细连接线使用三级边框颜色,与首行图标中心对齐,跨过预留的展开控件空间连接叶子状态图标,末端竖线止于对应图标中心。 +目录行高亮使用[嵌套几何规则](../../../docs/ui-radius.zh.md#nested-hover)中的标准菜单项圆角。每个分支展开控件的点击区域覆盖左侧 28px 空间与所在行的完整高度,不与相邻行重叠;仅原位的 12px 图标旋转,点击展开控件不会触发行导航或侧边栏导航。悬停展开控件仅高亮箭头;悬停导航主体或键盘聚焦时仍保留背景高亮。细连接线使用三级边框颜色,与首行图标中心对齐,跨过预留的展开控件空间连接叶子状态图标,末端竖线止于对应图标中心。 @@ -90,7 +90,8 @@ one-shot 和模式未知的 child 选用只读编辑器。可继续 child 经由 以下页面覆盖对话界面、宿主 seam 与设计笔记。 -- [ui-conversation](../ui-conversation/README.zh.md)——承载页头操作与编辑器链的聊天界面。 +- [ui-conversation](../ui-conversation/README.zh.md)——承载面包屑谱系与编辑器链的聊天界面。 +- [ui-session-panel](../ui-session-panel/README.zh.md)——承载「子智能体」分栏的会话面板。 - [ui-input-trigger](../ui-input-trigger/README.zh.md)——承载 `@` source 的建议机制。 - [subagent](../../subagent/subagent/README.zh.md)——可继续 child 背后的宿主能力 seam。 - [历史Web subagent 对话](../../../.agents/notes/archived/feature/2026-07-27-web-subagent-conversations.md)——目录与编辑器规范。 @@ -125,6 +126,7 @@ one-shot 和模式未知的 child 选用只读编辑器。可继续 child 经由 - **非完成的 inactive 结果仍合并显示**:目录能区分最近一次正常完成与其他 inactive 状态,但不区分失败、取消、拒绝、token 耗尽或尚无已结束轮次的 child;UI 不公开 Activation 身份,停止能力仅限编辑器上针对运行中可继续 child 的当前轮次 Stop。 - **祖先菜单的未缓存分支需要键盘激活**:悬停不读取,点击祖先标题会导航。聚焦标题后按 ArrowDown,可在不离开当前 Session 的情况下准备这一层。 - **单层发现会在中断后停止**:意外的读取拒绝会停止后续兄弟节点,并记录到控制台。重连可能在直接子节点读取前中断发现;需再次显式打开菜单来准备这一层。 +- **会话面板分栏没有层级激活**:显示分栏不读取任何内容,因此 Session 列表未缓存其目录的直接子智能体在分栏中没有展开箭头,直到其目录到达,例如打开它自己的对话后,或在兄弟会话的面包屑切换器中准备这一层后。 - **`@` 引用仍是显示标题文本**:重复或改名后的 label 会有歧义,因此它们刻意不获得继续执行语义。 diff --git a/packages/client/ui-subagent/package.json b/packages/client/ui-subagent/package.json index f6b08201bc..0f3ac4e008 100644 --- a/packages/client/ui-subagent/package.json +++ b/packages/client/ui-subagent/package.json @@ -34,10 +34,11 @@ "@deepseek-ai/dsh-client-resources", "@deepseek-ai/dsh-client-ui-chat", "@deepseek-ai/dsh-client-ui-conversation", - "@deepseek-ai/dsh-client-ui-primitives", - "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-input-trigger", + "@deepseek-ai/dsh-client-ui-primitives", + "@deepseek-ai/dsh-client-ui-session-panel", "@deepseek-ai/dsh-client-ui-session-status", + "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-workspace" ], "platform": "web" @@ -52,28 +53,29 @@ "@deepseek-ai/cordis": "workspace:~" }, "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-session-controller": "workspace:*", + "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-resources": "workspace:*", + "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-client-ui-chat": "workspace:*", "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-input-trigger": "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-session-status": "workspace:*", + "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-token-meter": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", - "react-dom": "^18.2.0", - "@deepseek-ai/dsh-api-session-controller": "workspace:*", - "@deepseek-ai/dsh-client-connection": "workspace:*", - "@deepseek-ai/dsh-session": "workspace:*", - "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", - "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", - "@deepseek-ai/dsh-client-ui-session": "workspace:*", - "@deepseek-ai/dsh-client-ui-session-status": "workspace:*", - "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", - "@deepseek-ai/dsh-agent-team": "workspace:*" + "react-dom": "^18.2.0" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css b/packages/client/ui-subagent/src/client/SubagentCatalog.module.css similarity index 74% rename from packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css rename to packages/client/ui-subagent/src/client/SubagentCatalog.module.css index c450098395..86cc042428 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css +++ b/packages/client/ui-subagent/src/client/SubagentCatalog.module.css @@ -11,7 +11,6 @@ margin-left: 6px; } -.trigger, .switcherTrigger { display: inline-flex; align-items: center; @@ -26,10 +25,6 @@ cursor: pointer; } -.trigger { - gap: 4px; -} - .switcherTrigger { gap: 4px; min-width: 0; @@ -57,25 +52,6 @@ flex: none; } -.activitySlot { - display: inline-flex; - flex: none; - align-items: center; - justify-content: center; - width: 14px; - height: 14px; -} - -.trigger:focus-visible { - color: var(--dsw-alias-label-primary); -} - -@media (hover: hover) { - .trigger:hover { - color: var(--dsw-alias-label-primary); - } -} - .switcherTrigger:focus-visible { color: var(--dsw-alias-label-primary); } @@ -100,55 +76,6 @@ transition: transform 120ms ease; } -.trigger .compactIcon { - display: none; -} - -/* The title-row container drops passive preset text at 540px; this action yields later. */ -@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); - } - } -} - .menu { position: fixed; z-index: 100; @@ -193,47 +120,112 @@ } } -.sectionHeader { - display: flex; - align-items: flex-start; - gap: 7px; - padding: 4px 7px 8px; -} - -.sectionIcon { - display: grid; - flex: none; - place-items: center; - width: 14px; - height: 24px; - color: var(--dsw-alias-label-tertiary); -} - -.sectionTitle { - flex: none; - margin: 0; - color: var(--dsw-alias-label-primary); - font-size: 13px; - font-weight: 500; - line-height: 24px; -} - +/* Progress beside the Session panel section title, one line that clips before the title does. */ .sectionProgress { - margin-inline-start: 4px; - flex: 1 1 auto; min-width: 0; - padding-top: 2px; + overflow: hidden; color: var(--dsw-alias-label-tertiary); - font-size: 13px; - line-height: 20px; - overflow-wrap: anywhere; + font: var(--dsw-font-xxs-12); + font-variant-numeric: tabular-nums; + text-overflow: ellipsis; + white-space: nowrap; } -.sectionEmpty { - margin: 0; - padding: 0 7px 8px 28px; +/* 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; +} + +/* The Session panel section supplies the inset and scrolling. Rows 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. */ +.sectionBody { + display: flex; + flex-direction: column; + min-width: 0; +} + +/* One 28px line per row: the name clips, and its owner, state, and tokens show in the row's hover card. */ +.sectionBody .row { + gap: 8px; + min-height: 28px; + padding: 4px 6px; +} + +.sectionBody .clickarea { + gap: 8px; + border-radius: var(--dsw-radius-sm); +} + +.sectionBody .rowActivitySlot { + width: 16px; + height: 20px; +} + +.sectionBody .disclosure, +.sectionBody .disclosureSpace { + width: 16px; + height: 20px; +} + +.sectionBody .label { + overflow: hidden; + line-height: 20px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.sectionBody .duration { + flex: none; color: var(--dsw-alias-label-tertiary); font-size: 12px; + font-variant-numeric: tabular-nums; + line-height: 20px; + white-space: nowrap; +} + +/* The tree's spine sits on the status column's center, and leaves a parent row + just below its 6px dot. Each row sits in its hover card's anchor wrapper. */ +.sectionBody .children { + --branch-anchor-y: 14px; + margin-left: 14px; +} + +.sectionBody .children::before { + top: -10px; + height: 10px; +} + +.sectionBody .children > .node > :first-child > .row::before { + content: ''; + position: absolute; + top: calc(var(--branch-anchor-y) - 0.25px); + left: -3px; + width: 9px; + border-top: 0.5px solid var(--dsw-alias-border-l3); +} + +.sectionBody .children > .node > :first-child > .row:has(> .disclosureSpace)::before { + width: 33px; +} + +/* In the panel's columns the arrow's 24px target centers on the trailing column + and overhangs the 20px line, so the row keeps its 28px. */ +.sectionBody .sidebarButton, +.sectionBody .sidebarSpace { + align-self: center; + width: 24px; + height: 24px; + margin: -2px -4px; } .node { @@ -390,7 +382,6 @@ grid-row: 2; } -.sidebarButton, .sidebarSpace { box-sizing: border-box; flex: none; @@ -405,26 +396,32 @@ color: var(--dsw-alias-label-primary); } +/* The arrow shares its row's highlight: a 24px target whose glyph darkens + without a fill, in the panel and in the switcher menu alike. In the menu it + keeps the 28px trailing column the current row's check also fills. */ .sidebarButton { + box-sizing: border-box; display: inline-flex; + flex: none; align-items: center; justify-content: center; - padding: 6px; + width: 24px; + height: 24px; + margin: 6px 2px; + padding: 0; border: 0; - border-radius: var(--dsw-radius-sm); + border-radius: var(--dsw-radius-xs); background: transparent; color: var(--dsw-alias-label-tertiary); cursor: pointer; } .sidebarButton:focus-visible { - background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); } @media (hover: hover) { .sidebarButton:hover { - background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); } } diff --git a/packages/client/ui-subagent/src/client/SubagentCatalog.tsx b/packages/client/ui-subagent/src/client/SubagentCatalog.tsx new file mode 100644 index 0000000000..ced031b05b --- /dev/null +++ b/packages/client/ui-subagent/src/client/SubagentCatalog.tsx @@ -0,0 +1,602 @@ +/** Subagent catalog tree shared by the Session panel section and the breadcrumb switcher. */ +import { useEffect, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' +import type { + SessionListState, SessionProjectionMap, SessionProjectionSnapshot, SessionSummary, +} from '@deepseek-ai/dsh-api-session-controller/client' +import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' +import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { + HoverCard, IconCheckOutlineRegular, IconChevronRightOutlineRegular, IconRefreshOutlineRegular, StateDot, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' +import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' +import type {} from '@deepseek-ai/dsh-token-meter/client' +import css from './SubagentCatalog.module.css' + +/** One Session's direct subagents with their live activity. */ +export type SubagentCatalogSnapshot = Omit & { + state: 'idle' | 'loading' | 'ready' | 'migration-required' | 'error' + entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[] +} + +/** Catalogs of every Session whose projections the Client holds. */ +export type Catalogs = Readonly> + +/** Business actions supplied by the slot registrations. */ +export type SubagentCatalogInjected = { + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + refreshProjection: (parentSessionId: SessionId) => void + /** Read this catalog and its direct children after explicit activation or retry. */ + prepareCatalog: (parentSessionId: SessionId) => Promise +} + +interface CatalogRowsProps { + parentSessionId: SessionId + currentSessionId: SessionId | undefined + catalog: SubagentCatalogSnapshot + catalogs: Catalogs + summaries: Readonly> + expanded: ReadonlySet + level: number + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + refreshProjection: (parentSessionId: SessionId) => void + toggleBranch: (childSessionId: SessionId) => void + closeCatalog: () => void + panelDetails: CatalogTreeProps['panelDetails'] +} + +/** + * List the focusable rows of a catalog tree in display order. + * @param root - the tree or an element that contains it. + * @returns the rows that accept focus. + */ +export function treeItems(root: HTMLElement): HTMLElement[] { + return Array.from(root.querySelectorAll('[role="treeitem"]:not([aria-disabled="true"])')) +} + +/** Compact token count shared in shape with the conversation stats strip. */ +function formatTokens(value: number, t: TranslateNS): string { + const scaled = (next: number): string => next >= 100 + ? String(Math.round(next)) + : String(Math.round(next * 10) / 10) + if (value < 1_000) return String(value) + if (value < 1_000_000) return t('tokens.thousand', { value: scaled(value / 1_000) }) + return t('tokens.million', { value: scaled(value / 1_000_000) }) +} + +/** Sum the four disjoint durable provider-usage buckets. */ +function tokenTotal( + usage: SessionProjectionMap['tokenUsage'] | undefined, +): number | undefined { + return usage === undefined + ? undefined + : usage.uncachedInputTokens + usage.outputTokens + + usage.cacheReadTokens + usage.cacheWriteTokens +} + +/** Exact whole-second active-turn duration for one catalog row. */ +function activityDuration( + summary: SessionSummary | undefined, + activity: 'running' | 'inactive', + now: number, +): number | undefined { + if (summary === undefined) return undefined + const timing: SessionProjectionMap['subagentTiming'] | undefined + = summary.projectionValues?.subagentTiming + if (timing === undefined) return undefined + if (timing.active === undefined) return timing.settledMs + const end = activity === 'running' + ? now + : timing.active.through + return timing.settledMs + Math.max(0, end - timing.active.since) +} + +interface DurationParts { + seconds: number + minutes: number + hours: number + days: number + totalMinutes: number + totalHours: number +} + +function splitDuration(ms: number): DurationParts { + const totalSeconds = Math.floor(Math.max(0, ms) / 1_000) + const totalMinutes = Math.floor(totalSeconds / 60) + const totalHours = Math.floor(totalMinutes / 60) + return { + seconds: totalSeconds % 60, + minutes: totalMinutes % 60, + hours: totalHours % 24, + days: Math.floor(totalHours / 24), + totalMinutes, + totalHours, + } +} + +/** Format a duration with decreasing visual precision at larger scales. */ +function formatDuration(ms: number, t: TranslateNS): string { + const { seconds, minutes, hours, days, totalMinutes, totalHours } = splitDuration(ms) + if (days >= 365) { + const years = Math.floor(days / 365) + const months = Math.floor((days % 365) / 30) + return months === 0 + ? t('duration.years', { years }) + : t('duration.yearsMonths', { years, months }) + } + if (days >= 30) { + const months = Math.floor(days / 30) + const remainingDays = days % 30 + return remainingDays === 0 + ? t('duration.months', { months }) + : t('duration.monthsDays', { months, days: remainingDays }) + } + if (days > 0) { + return hours === 0 + ? t('duration.days', { days }) + : t('duration.daysHours', { days, hours }) + } + if (totalHours > 0) { + return t('duration.hours', { + hours: totalHours, + minutes: String(minutes).padStart(2, '0'), + seconds: String(seconds).padStart(2, '0'), + }) + } + if (totalMinutes > 0) { + return t('duration.minutes', { + minutes: totalMinutes, + seconds: String(seconds).padStart(2, '0'), + }) + } + return t('duration.seconds', { seconds }) +} + +/** Preserve exact whole seconds for hover and accessible naming. */ +function formatExactDuration(ms: number, t: TranslateNS): string { + const { seconds, minutes, hours, days } = splitDuration(ms) + return days === 0 + ? formatDuration(ms, t) + : t('duration.exactDays', { + days, + hours: String(hours).padStart(2, '0'), + minutes: String(minutes).padStart(2, '0'), + seconds: String(seconds).padStart(2, '0'), + }) +} + +/** Render catalog loading without inventing child membership. */ +function CatalogLoadingRows({ t }: { t: TranslateNS }) { + return
    {t('loading.label')}
    +} + +/** Only confirmed child membership exposes a branch disclosure. */ +function canExpandCatalog(entry: SubagentCatalogSnapshot['entries'][number], catalogs: Catalogs, summaries: CatalogRowsProps['summaries']): boolean { + return entry.mode !== 'external' && (catalogs[entry.id]?.entries.length ?? 0) > 0 + && summaries[entry.id]?.formatStatus !== 'migration-required' + && catalogs[entry.id]?.state !== 'migration-required' +} + +/** The agent name unique among the row's siblings, or the Session ID for entries recorded without one. */ +/** + * Name a catalog entry when it has no description. + * @param entry - catalog entry. + * @returns the entry's display name. + */ +export function entryName(entry: SubagentCatalogSnapshot['entries'][number]): string { + return entry.mode === 'continuable' || entry.mode === 'external' ? entry.name ?? entry.id : entry.id +} + +/** Only a local child's last closed, normally completed turn receives the completed marker. */ +function completedEntry(entry: SubagentCatalogSnapshot['entries'][number], summary: SessionSummary | undefined): boolean { + return entry.mode !== 'external' && entry.activity === 'inactive' + && summary?.projectionValues?.subagentTiming?.lastTurnCompleted === true +} + +/** Count direct catalog members without treating external or other inactive entries as completed. */ +function catalogProgress(entries: SubagentCatalogSnapshot['entries'], summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { + let completed = 0 + let active = 0 + let inactive = 0 + let external = 0 + for (const entry of entries) { + if (entry.mode === 'external') external++ + else if (entry.activity === 'running') active++ + else if (completedEntry(entry, summaries[entry.id])) completed++ + else inactive++ + } + return [ + ...completed > 0 ? [t('progress.completed', { count: completed })] : [], + ...active > 0 ? [t('progress.active', { count: active })] : [], + ...inactive > 0 ? [t('progress.inactive', { count: inactive })] : [], + ...external > 0 ? [t('progress.external', { count: external })] : [], + ].join('\u2002·\u2002') +} + +/** Render one catalog level and recurse only through explicitly expanded rows. */ +function CatalogRows({ + parentSessionId, currentSessionId, catalog, catalogs, summaries, expanded, level, + openChild, openChildAside, refreshProjection, toggleBranch, closeCatalog, panelDetails, t, +}: CatalogRowsProps & { t: TranslateNS }) { + const dense = panelDetails !== undefined + const [now, setNow] = useState(() => Date.now()) + const running = catalog.entries.some(entry => entry.activity === 'running') + useEffect(() => { + if (!running) return + const timer = setInterval(() => { setNow(Date.now()) }, 1_000) + return () => { clearInterval(timer) } + }, [running]) + const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0 + const reserveDisclosure = catalog.entries.some(entry => canExpandCatalog(entry, catalogs, summaries)) + return ( + <> + {catalog.state === 'idle' && catalog.entries.length === 0 && ( +
    {t('load.idle')}
    + )} + {emptyLoading && ( + + )} + {catalog.state === 'error' && ( +
    + {catalog.error?.message ?? t('load.error')} + +
    + )} + {catalog.entries.map((entry) => { + const external = entry.mode === 'external' + const childCatalog = catalogs[entry.id] + const isCurrent = entry.id === currentSessionId + const requiresOpening = summaries[entry.id]?.formatStatus === 'migration-required' + || childCatalog?.state === 'migration-required' + const canExpand = canExpandCatalog(entry, catalogs, summaries) + const isExpanded = canExpand && expanded.has(entry.id) + const summary = summaries[entry.id] + const description = entry.label || summary?.title + const name = entryName(entry) + const primaryLabel = description || name + const secondaryLabel = description ? name : undefined + const mode = external ? t('mode.external') : entry.mode === 'unknown' ? t('mode.unknown') + : entry.mode === 'one-shot' ? t('mode.oneShot') : t('mode.continuable') + const completed = completedEntry(entry, summary) + const activity = external ? undefined : entry.activity === 'running' + ? t('activity.running') + : completed + ? t('activity.completed') + : t('activity.inactive') + const secondary = [secondaryLabel, mode, activity] + .filter(value => value !== undefined) + .join(' · ') + const totalTokens = tokenTotal(summary?.projectionValues?.tokenUsage) + const durationMs = activityDuration( + summary, + entry.activity, + now, + ) + const tokenMetric = totalTokens === undefined + ? undefined + : t('tokens.total', { value: formatTokens(totalTokens, t) }) + const durationMetric = durationMs === undefined + ? undefined + : { + compact: formatDuration(durationMs, t), + exact: formatExactDuration(durationMs, t), + } + const metrics = [tokenMetric, durationMetric?.exact] + .filter(value => value !== undefined) + .join(' · ') + const dotState = entry.activity === 'running' ? 'ongoing' : completed ? 'done' : 'idle' + + const open = (): void => { + if (external) return + openChild({ + parentSessionId, + childSessionId: entry.id, + mode: entry.mode, + }) + closeCatalog() + } + const handleKey = (event: KeyboardEvent): void => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault() + event.stopPropagation() + open() + } else if ( + (event.key === 'ArrowRight' && canExpand && !isExpanded) + || (event.key === 'ArrowLeft' && isExpanded) + ) { + event.preventDefault() + event.stopPropagation() + toggleBranch(entry.id) + } + } + const toggle = (event: MouseEvent): void => { + event.preventDefault() + event.stopPropagation() + toggleBranch(entry.id) + } + + const row = ( +
    value !== '').join(' ')} + {...canExpand ? { 'aria-expanded': isExpanded } : {}} + className={css.row} + onClick={open} + onKeyDown={handleKey} + > + {!canExpand + ? reserveDisclosure && + : ( + + )} +
    + + + + + {primaryLabel} + {!dense && secondaryLabel !== undefined && ( + {secondaryLabel} + )} + + {dense + ? durationMetric !== undefined && {durationMetric.compact} + : metrics !== '' && ( + + {tokenMetric !== undefined && {tokenMetric}} + {durationMetric !== undefined && ( + {durationMetric.compact} + )} + + )} + {isCurrent + ? ( + + + + ) + : external ? : ( + + + + )} +
    +
    + ) + const details = panelDetails?.({ + title: primaryLabel, + lines: secondaryLabel === undefined ? [] : [t('hover.owner', { name: secondaryLabel })], + status: { state: dotState, label: [activity, mode].filter(value => value !== undefined).join(' · ') }, + facts: [ + ...tokenMetric === undefined ? [] : [{ kind: 'tokens' as const, label: tokenMetric }], + ...durationMetric === undefined ? [] : [{ kind: 'duration' as const, label: durationMetric.exact }], + ], + }) + + return ( +
    + {dense ? : row} + {!isExpanded && !external && !requiresOpening && childCatalog?.state === 'error' && ( +
    + {t('load.error')} + +
    + )} + {childCatalog !== undefined && isExpanded && ( +
    + +
    + )} +
    + ) + })} + + ) +} + +/** + * Build every held Session's catalog from its projection and live status. + * @param projections - projection snapshots by Session. + * @param summaries - Session list rows by id. + * @param statuses - live Session statuses. + * @returns catalogs keyed by parent Session. + */ +export function deriveCatalogs( + projections: SessionListState['projectionsBySession'], + summaries: SessionListState['byId'], + statuses: SessionStatusSnapshot, +): Catalogs { + return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => { + const projected = snapshot.values.subagentCatalog + const state = snapshot.state === 'idle' + ? projected === undefined ? 'idle' : 'ready' + : snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state + return [id, { + state, + error: snapshot.error, + entries: (projected ?? []).map(entry => ({ + ...entry, + activity: (statuses.get(entry.id)?.running ?? summaries[entry.id]?.running) === true + ? 'running' as const : 'inactive' as const, + })), + } satisfies SubagentCatalogSnapshot] + })) +} + +/** + * The direct subagents of `catalog`'s Session plus progress, as one phrase such as "2 of 3 done". + * @param catalog - catalog whose entries are counted. + * @param summaries - Session list rows by id. + * @param t - subagent copy. + * @returns the progress phrase, or an empty string without entries. + */ +export function progressOf(catalog: SubagentCatalogSnapshot, summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { + return catalogProgress(catalog.entries, summaries, t) +} + +/** + * Bind catalog preparation as a fire-and-forget level read; a rejection is + * logged, and the next activation or retry prepares the level again. + * @param prepareCatalog - the injected catalog action. + * @returns a callback that prepares one level. + */ +export function levelPreparer(prepareCatalog: SubagentCatalogInjected['prepareCatalog']): (sessionId: SessionId) => void { + return (sessionId) => { + void prepareCatalog(sessionId).catch((error: unknown) => { + console.error('[ui-subagent] catalog discovery failed:', error) + }) + } +} + +/** Props of one subagent tree. */ +export interface CatalogTreeProps { + /** Session whose direct catalog roots the tree. */ + rootSessionId: SessionId + /** Selected descendant highlighted in the tree. */ + currentSessionId?: SessionId | undefined + catalog: SubagentCatalogSnapshot + catalogs: Catalogs + summaries: CatalogRowsProps['summaries'] + openChild: (address: SubagentAddress) => void + openChildAside: (address: SubagentAddress) => void + /** Read a level's catalog and its direct children; the tree calls it on branch expansion and retry. */ + prepareLevel: (parentSessionId: SessionId) => void + /** Called after a row opened a Session, so a surrounding popover or overlay can close. */ + onOpened: () => void + /** Focus the first row on mount, as a keyboard-opened popover does. */ + focusFirst?: boolean + /** + * Renders the Session panel's row details. With it the tree lists one-line + * rows, as the Session panel does, and each row shows its name, owner, + * state, and measures in a hover card. + */ + panelDetails?: ((details: PanelDetailsProps) => ReactNode) | undefined + t: TranslateNS +} + +/** + * Render a subagent tree with expandable branches and roving arrow-key focus. + * A row offers expansion only after its own catalog has entries; expanding it + * prepares that level, and collapsing a branch also collapses its descendants. + * @param props - catalog data, actions, and copy. + * @returns the tree. + */ +export function CatalogTree({ + rootSessionId, currentSessionId, catalog, catalogs, summaries, + openChild, openChildAside, prepareLevel, onOpened, focusFirst = false, panelDetails, t, +}: CatalogTreeProps) { + const [expanded, setExpanded] = useState>(() => new Set()) + const treeRef = useRef(null) + useEffect(() => { + // Effects run after commit, when the tree element is attached. + if (focusFirst) treeItems(treeRef.current as HTMLDivElement)[0]?.focus() + }, [focusFirst]) + + const closeBranch = (root: SessionId): void => { + const closing = new Set() + const visit = (parentSessionId: SessionId): void => { + if (closing.has(parentSessionId) || !expanded.has(parentSessionId)) return + closing.add(parentSessionId) + for (const entry of catalogs[parentSessionId]?.entries ?? []) visit(entry.id) + } + visit(root) + setExpanded(current => new Set([...current].filter(id => !closing.has(id)))) + } + + const toggleBranch = (childSessionId: SessionId): void => { + if (expanded.has(childSessionId)) { + closeBranch(childSessionId) + return + } + setExpanded(current => new Set(current).add(childSessionId)) + prepareLevel(childSessionId) + } + + const navigate = (event: KeyboardEvent): void => { + const items = treeItems(event.currentTarget) + const index = items.indexOf(document.activeElement as HTMLElement) + const focusAt = (next: number): void => { items[(next + items.length) % items.length]?.focus() } + if (items.length === 0) return + if (event.key === 'Home') focusAt(0) + else if (event.key === 'End') focusAt(items.length - 1) + else if (event.key === 'ArrowDown') focusAt(index + 1) + else if (event.key === 'ArrowUp') focusAt(index < 0 ? items.length - 1 : index - 1) + else return + event.preventDefault() + } + + return ( +
    + +
    + ) +} diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx index 8cbb5be217..aff8538a83 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx @@ -1,182 +1,22 @@ -import { useMemo, useEffect, useId, useRef, useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' +/** Breadcrumb switcher for subagent Sessions: the current title opens its siblings' tree. */ +import { useMemo, useEffect, useId, useRef, useState } from 'react' import { createPortal } from 'react-dom' -import { - type SessionProjectionMap, type SessionSummary, - type SessionProjectionSnapshot, -} from '@deepseek-ai/dsh-api-session-controller/client' -import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { - IconChevronRightOutlineRegular, IconRefreshOutlineRegular, IconUsersOutlineRegular, - IconCheckOutlineRegular, MenuSurface, StateDot, Tooltip, -} from '@deepseek-ai/dsh-client-ui-primitives' -import type { HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import { MenuSurface } 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 type {} from '@deepseek-ai/dsh-token-meter/client' -import type {} from '@deepseek-ai/dsh-agent-team/client' -import type {} from './slots.ts' -import css from './SubagentHeaderLineage.module.css' +import { + CatalogTree, deriveCatalogs, entryName, levelPreparer, treeItems, type SubagentCatalogInjected, type SubagentCatalogSnapshot, +} from './SubagentCatalog.tsx' +import css from './SubagentCatalog.module.css' -type SubagentCatalogSnapshot = Omit & { - state: 'idle' | 'loading' | 'ready' | 'migration-required' | 'error' - entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[] -} -type Catalogs = Readonly> - -/** Business actions supplied by the slot registration. */ -export type SubagentCatalogInjected = { - openChild: (address: SubagentAddress) => void - openChildAside: (address: SubagentAddress) => void - refreshProjection: (parentSessionId: SessionId) => void - /** Read this catalog and its direct children after explicit activation or retry. */ - prepareCatalog: (parentSessionId: SessionId) => Promise -} - -/** Root catalog actions and availability of its optional footer. */ -export type SubagentCatalogActionInjected = SubagentCatalogInjected & { - hooks: { - /** Whether the catalog footer currently has a registered contributor. */ - footerAvailable: HostObservable - } -} +export type { SubagentCatalogInjected } from './SubagentCatalog.tsx' /** Full props for the session-header lineage renderer. */ export type SubagentHeaderLineageProps = PropsRuntime<'conversation.session.header.lineage'> & InjectFace & PropsLocale -interface CatalogRowsProps { - parentSessionId: SessionId - currentSessionId: SessionId | undefined - catalog: SubagentCatalogSnapshot - catalogs: Catalogs - summaries: Readonly> - expanded: ReadonlySet - level: number - openChild: (address: SubagentAddress) => void - openChildAside: (address: SubagentAddress) => void - refreshProjection: (parentSessionId: SessionId) => void - toggleBranch: (childSessionId: SessionId) => void - closeCatalog: () => void -} - -function treeItems(root: HTMLDivElement | null): HTMLElement[] { - return root === null - ? [] - : Array.from(root.querySelectorAll('[role="treeitem"]:not([aria-disabled="true"])')) -} - -/** Compact token count shared in shape with the conversation stats strip. */ -function formatTokens(value: number, t: TranslateNS): string { - const scaled = (next: number): string => next >= 100 - ? String(Math.round(next)) - : String(Math.round(next * 10) / 10) - if (value < 1_000) return String(value) - if (value < 1_000_000) return t('tokens.thousand', { value: scaled(value / 1_000) }) - return t('tokens.million', { value: scaled(value / 1_000_000) }) -} - -/** Sum the four disjoint durable provider-usage buckets. */ -function tokenTotal( - usage: SessionProjectionMap['tokenUsage'] | undefined, -): number | undefined { - return usage === undefined - ? undefined - : usage.uncachedInputTokens + usage.outputTokens - + usage.cacheReadTokens + usage.cacheWriteTokens -} - -/** Exact whole-second active-turn duration for one catalog row. */ -function activityDuration( - summary: SessionSummary | undefined, - activity: 'running' | 'inactive', - now: number, -): number | undefined { - if (summary === undefined) return undefined - const timing: SessionProjectionMap['subagentTiming'] | undefined - = summary.projectionValues?.subagentTiming - if (timing === undefined) return undefined - if (timing.active === undefined) return timing.settledMs - const end = activity === 'running' - ? now - : timing.active.through - return timing.settledMs + Math.max(0, end - timing.active.since) -} - -interface DurationParts { - seconds: number - minutes: number - hours: number - days: number - totalMinutes: number - totalHours: number -} - -function splitDuration(ms: number): DurationParts { - const totalSeconds = Math.floor(Math.max(0, ms) / 1_000) - const totalMinutes = Math.floor(totalSeconds / 60) - const totalHours = Math.floor(totalMinutes / 60) - return { - seconds: totalSeconds % 60, - minutes: totalMinutes % 60, - hours: totalHours % 24, - days: Math.floor(totalHours / 24), - totalMinutes, - totalHours, - } -} - -/** Format a duration with decreasing visual precision at larger scales. */ -function formatDuration(ms: number, t: TranslateNS): string { - const { seconds, minutes, hours, days, totalMinutes, totalHours } = splitDuration(ms) - if (days >= 365) { - const years = Math.floor(days / 365) - const months = Math.floor((days % 365) / 30) - return months === 0 - ? t('duration.years', { years }) - : t('duration.yearsMonths', { years, months }) - } - if (days >= 30) { - const months = Math.floor(days / 30) - const remainingDays = days % 30 - return remainingDays === 0 - ? t('duration.months', { months }) - : t('duration.monthsDays', { months, days: remainingDays }) - } - if (days > 0) { - return hours === 0 - ? t('duration.days', { days }) - : t('duration.daysHours', { days, hours }) - } - if (totalHours > 0) { - return t('duration.hours', { - hours: totalHours, - minutes: String(minutes).padStart(2, '0'), - seconds: String(seconds).padStart(2, '0'), - }) - } - if (totalMinutes > 0) { - return t('duration.minutes', { - minutes: totalMinutes, - seconds: String(seconds).padStart(2, '0'), - }) - } - return t('duration.seconds', { seconds }) -} - -/** Preserve exact whole seconds for hover and accessible naming. */ -function formatExactDuration(ms: number, t: TranslateNS): string { - const { seconds, minutes, hours, days } = splitDuration(ms) - return days === 0 - ? formatDuration(ms, t) - : t('duration.exactDays', { - days, - hours: String(hours).padStart(2, '0'), - minutes: String(minutes).padStart(2, '0'), - seconds: String(seconds).padStart(2, '0'), - }) -} - function SubagentSwitcherIcon() { return ( }) { - return
    {t('loading.label')}
    -} -/** Only confirmed child membership exposes a branch disclosure. */ -function canExpandCatalog(entry: SubagentCatalogSnapshot['entries'][number], catalogs: Catalogs, summaries: CatalogRowsProps['summaries']): boolean { - return entry.mode !== 'external' && (catalogs[entry.id]?.entries.length ?? 0) > 0 - && summaries[entry.id]?.formatStatus !== 'migration-required' - && catalogs[entry.id]?.state !== 'migration-required' -} - -/** The agent name unique among the row's siblings, or the Session ID for entries recorded without one. */ -function entryName(entry: SubagentCatalogSnapshot['entries'][number]): string { - return entry.mode === 'continuable' || entry.mode === 'external' ? entry.name ?? entry.id : entry.id -} - -/** Only a local child's last closed, normally completed turn receives the completed marker. */ -function completedEntry(entry: SubagentCatalogSnapshot['entries'][number], summary: SessionSummary | undefined): boolean { - return entry.mode !== 'external' && entry.activity === 'inactive' - && summary?.projectionValues?.subagentTiming?.lastTurnCompleted === true -} - -/** Count direct catalog members without treating external or other inactive entries as completed. */ -function catalogProgress(entries: SubagentCatalogSnapshot['entries'], summaries: CatalogRowsProps['summaries'], t: TranslateNS): string { - let completed = 0 - let active = 0 - let inactive = 0 - let external = 0 - for (const entry of entries) { - if (entry.mode === 'external') external++ - else if (entry.activity === 'running') active++ - else if (completedEntry(entry, summaries[entry.id])) completed++ - else inactive++ - } - return [ - ...completed > 0 ? [t('progress.completed', { count: completed })] : [], - ...active > 0 ? [t('progress.active', { count: active })] : [], - ...inactive > 0 ? [t('progress.inactive', { count: inactive })] : [], - ...external > 0 ? [t('progress.external', { count: external })] : [], - ].join('\u2002·\u2002') -} - -/** Render one catalog level and recurse only through explicitly expanded rows. */ -function CatalogRows({ - parentSessionId, currentSessionId, catalog, catalogs, summaries, expanded, level, - openChild, openChildAside, refreshProjection, toggleBranch, closeCatalog, t, -}: CatalogRowsProps & { t: TranslateNS }) { - const [now, setNow] = useState(() => Date.now()) - const running = catalog.entries.some(entry => entry.activity === 'running') - useEffect(() => { - if (!running) return - const timer = setInterval(() => { setNow(Date.now()) }, 1_000) - return () => { clearInterval(timer) } - }, [running]) - const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0 - const reserveDisclosure = catalog.entries.some(entry => canExpandCatalog(entry, catalogs, summaries)) - return ( - <> - {catalog.state === 'idle' && catalog.entries.length === 0 && ( -
    {t('load.idle')}
    - )} - {emptyLoading && ( - - )} - {catalog.state === 'error' && ( -
    - {catalog.error?.message ?? t('load.error')} - -
    - )} - {catalog.entries.map((entry) => { - const external = entry.mode === 'external' - const childCatalog = catalogs[entry.id] - const isCurrent = entry.id === currentSessionId - const requiresOpening = summaries[entry.id]?.formatStatus === 'migration-required' - || childCatalog?.state === 'migration-required' - const canExpand = canExpandCatalog(entry, catalogs, summaries) - const isExpanded = canExpand && expanded.has(entry.id) - const summary = summaries[entry.id] - const description = entry.label || summary?.title - const name = entryName(entry) - const primaryLabel = description || name - const secondaryLabel = description ? name : undefined - const mode = external ? t('mode.external') : entry.mode === 'unknown' ? t('mode.unknown') - : entry.mode === 'one-shot' ? t('mode.oneShot') : t('mode.continuable') - const completed = completedEntry(entry, summary) - const activity = external ? undefined : entry.activity === 'running' - ? t('activity.running') - : completed - ? t('activity.completed') - : t('activity.inactive') - const secondary = [secondaryLabel, mode, activity] - .filter(value => value !== undefined) - .join(' · ') - const totalTokens = tokenTotal(summary?.projectionValues?.tokenUsage) - const durationMs = activityDuration( - summary, - entry.activity, - now, - ) - const tokenMetric = totalTokens === undefined - ? undefined - : t('tokens.total', { value: formatTokens(totalTokens, t) }) - const durationMetric = durationMs === undefined - ? undefined - : { - compact: formatDuration(durationMs, t), - exact: formatExactDuration(durationMs, t), - } - const metrics = [tokenMetric, durationMetric?.exact] - .filter(value => value !== undefined) - .join(' · ') - - const open = (): void => { - if (external) return - openChild({ - parentSessionId, - childSessionId: entry.id, - mode: entry.mode, - }) - closeCatalog() - } - const handleKey = (event: KeyboardEvent): void => { - if (event.key === 'Enter' || event.key === ' ') { - event.preventDefault() - event.stopPropagation() - open() - } else if ( - (event.key === 'ArrowRight' && canExpand && !isExpanded) - || (event.key === 'ArrowLeft' && isExpanded) - ) { - event.preventDefault() - event.stopPropagation() - toggleBranch(entry.id) - } - } - const toggle = (event: MouseEvent): void => { - event.preventDefault() - event.stopPropagation() - toggleBranch(entry.id) - } - - return ( -
    -
    value !== '').join(' ')} - {...canExpand ? { 'aria-expanded': isExpanded } : {}} - className={css.row} - onClick={open} - onKeyDown={handleKey} - > - {!canExpand - ? reserveDisclosure && - : ( - - )} -
    - - - - - {primaryLabel} - {secondaryLabel !== undefined && ( - {secondaryLabel} - )} - - {metrics !== '' && ( - - {tokenMetric !== undefined && {tokenMetric}} - {durationMetric !== undefined && ( - - {durationMetric.compact} - - )} - - )} - {isCurrent - ? ( - - - - ) - : external ? : ( - - - - )} -
    -
    - {!isExpanded && !external && !requiresOpening && childCatalog?.state === 'error' && ( -
    - {t('load.error')} - -
    - )} - {childCatalog !== undefined && isExpanded && ( -
    - -
    - )} -
    - ) - })} - - ) -} - -interface CatalogDropdownSharedProps extends InjectFace { - /** Session whose direct catalog roots the tree. */ +interface SwitcherProps extends InjectFace { + /** Parent Session whose direct catalog roots the tree. */ rootSessionId: SessionId + /** Selected descendant highlighted in the tree. */ + currentSessionId: SessionId + /** Visible title included in the switcher's hover target. */ + displayTitle: string + /** Optional ancestor navigation when the combined title is clicked. */ + openTitle?: () => void useSessions: SubagentHeaderLineageProps['useSessions'] useSessionStatus: SubagentHeaderLineageProps['useSessionStatus'] t: TranslateNS - /** Section labels are useful only beside a visible shared-task list. */ - hasSharedTasks?: boolean - /** Retain an empty catalog's entry for shared tasks or a task-board error. */ - hasBoardContent?: boolean - renderFooter?: () => ReactNode } -type CatalogDropdownProps = CatalogDropdownSharedProps & ( - | { - /** Descendant-count control. */ - variant: 'count' - currentSessionId?: never - displayTitle?: never - openTitle?: never - } - | { - /** Current-title sibling switcher. */ - variant: 'switcher' - /** Selected descendant highlighted in the catalog. */ - currentSessionId: SessionId - /** Visible title included in the switcher's hover target. */ - displayTitle: string - /** Optional ancestor navigation when the combined title is clicked. */ - openTitle?: () => void - } -) - -/** One trigger-plus-tree dropdown over the catalog rooted at `rootSessionId`. */ -function CatalogDropdown(props: CatalogDropdownProps) { - const { - rootSessionId, currentSessionId, displayTitle, openTitle, variant, - useSessions, useSessionStatus, openChild, openChildAside, prepareCatalog, t, hasSharedTasks = false, - } = props - const ancestorSwitcher = variant === 'switcher' && openTitle !== undefined +/** + * Title-and-chevron dropdown over the parent's subagent tree. Hover opens it + * after 150ms and leaving both surfaces closes it after 120ms; a click pins it + * until an outside press or Escape. With `openTitle`, a click navigates to the + * ancestor instead. Hovering reads nothing; a pinning click or ArrowDown + * prepares the parent's level. + * @param props - tree root, current Session, title, Session hooks, actions, and copy. + * @returns the switcher. + */ +function Switcher({ + rootSessionId, currentSessionId, displayTitle, openTitle, + useSessions, useSessionStatus, openChild, openChildAside, prepareCatalog, t, +}: SwitcherProps) { const projections = useSessions(state => state.projectionsBySession) const summaries = useSessions(state => state.byId) const statuses = useSessionStatus(value => value) - const catalogs = useMemo(() => { - return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => { - const projected = snapshot.values.subagentCatalog - const state = snapshot.state === 'idle' - ? projected === undefined ? 'idle' : 'ready' - : snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state - return [id, { - state, - error: snapshot.error, - entries: (projected ?? []).map(entry => ({ - ...entry, - activity: (statuses.get(entry.id)?.running ?? summaries[entry.id]?.running) === true - ? 'running' as const : 'inactive' as const, - })), - } satisfies SubagentCatalogSnapshot] - })) - }, [projections, summaries, statuses]) - const catalog = catalogs[rootSessionId] - const prepareLevel = (sessionId: SessionId): void => { - void prepareCatalog(sessionId).catch((error: unknown) => { - console.error('[ui-subagent] catalog discovery failed:', error) - }) - } - const [open, setOpen] = useState(false) - const [expanded, setExpanded] = useState>(() => new Set()) + const catalogs = useMemo(() => deriveCatalogs(projections, summaries, statuses), [projections, summaries, statuses]) + const catalog: SubagentCatalogSnapshot = catalogs[rootSessionId] ?? { entries: [], state: 'idle', error: null } + const prepareLevel = levelPreparer(prepareCatalog) + const [open, setOpen] = useState<'closed' | 'hover' | 'pinned' | 'keyboard'>('closed') const rootRef = useRef(null) const triggerRef = useRef(null) - const countRef = useRef(null) - const activityId = useId() const menuRef = useRef(null) - const anchorName = `--dsh-subagents-${activityId.replaceAll(':', '')}` - const hoverOpenTimer = useRef | undefined>(undefined) - const hoverCloseTimer = useRef | undefined>(undefined) - // A click-opened (pinned) menu ignores hover-out; only explicit dismissal closes it. - const pinnedRef = useRef(false) - const currentEntry = currentSessionId === undefined - ? undefined - : catalog?.entries.find(entry => entry.id === currentSessionId) - const switcherDisplayTitle = currentEntry !== undefined - ? currentEntry.label || entryName(currentEntry) - : displayTitle - const directChildren = catalog?.entries ?? [] - const directCount = directChildren.length - const runningCount = directChildren.filter(entry => entry.activity === 'running').length - const progress = catalogProgress(directChildren, summaries, t) - const totalCountKey = directCount === 1 ? 'count.total.one' : 'count.total.other' - const runningCountKey = runningCount === 1 ? 'count.running.one' : 'count.running.other' - const presentedCatalog: SubagentCatalogSnapshot | undefined = catalog ?? (variant === 'switcher' || props.hasBoardContent - ? { entries: [], state: 'idle', error: null } - : undefined) + const anchorName = `--dsh-subagents-${useId().replaceAll(':', '')}` + const hoverTimer = useRef | undefined>(undefined) + const currentEntry = catalog.entries.find(entry => entry.id === currentSessionId) + const title = currentEntry !== undefined ? currentEntry.label || entryName(currentEntry) : displayTitle + const shown = open !== 'closed' - const cancelHoverClose = (): void => { - if (hoverCloseTimer.current === undefined) return - clearTimeout(hoverCloseTimer.current) - hoverCloseTimer.current = undefined + const cancelHover = (): void => { + clearTimeout(hoverTimer.current) + hoverTimer.current = undefined } - - const cancelHoverOpen = (): void => { - if (hoverOpenTimer.current === undefined) return - clearTimeout(hoverOpenTimer.current) - hoverOpenTimer.current = undefined - } - - const changeOpen = (next: boolean, restoreFocus = false): void => { - cancelHoverOpen() - cancelHoverClose() - if (next) { - const trigger = triggerRef.current - /* v8 ignore next -- a queued callback can outlive the trigger */ - if (trigger === null) return - setOpen(true) - } - else { - pinnedRef.current = false - setOpen(false) - setExpanded(new Set()) - } + const close = (restoreFocus = false): void => { + cancelHover() + setOpen('closed') if (restoreFocus) queueMicrotask(() => { triggerRef.current?.focus() }) } - // CSS owns the header-width breakpoint; interaction reads its result only when scheduling hover. - const allowsHoverOpen = (): boolean => variant === 'switcher' - || (countRef.current !== null && getComputedStyle(countRef.current).display !== 'none') - - const scheduleHoverOpen = (): void => { - cancelHoverOpen() - cancelHoverClose() - if (open || !allowsHoverOpen()) return - hoverOpenTimer.current = setTimeout(() => { - hoverOpenTimer.current = undefined - if (allowsHoverOpen()) changeOpen(true) - }, 150) - } - - const scheduleHoverClose = (): void => { - cancelHoverOpen() - cancelHoverClose() - if (pinnedRef.current) return - hoverCloseTimer.current = setTimeout(() => { - hoverCloseTimer.current = undefined - changeOpen(false) - }, 120) - } - - const closeBranch = (root: SessionId): void => { - const closing = new Set() - const visit = (parentSessionId: SessionId): void => { - if (closing.has(parentSessionId) || !expanded.has(parentSessionId)) return - closing.add(parentSessionId) - const branch = catalogs[parentSessionId] - for (const entry of branch?.entries ?? []) { - visit(entry.id) - } - } - visit(root) - setExpanded(current => new Set([...current].filter(id => !closing.has(id)))) - } - - const toggleBranch = (childSessionId: SessionId): void => { - if (expanded.has(childSessionId)) { - closeBranch(childSessionId) - return - } - setExpanded(current => new Set(current).add(childSessionId)) - prepareLevel(childSessionId) - } - useEffect(() => { - if (!open) return + if (!shown) return const closeOutside = (event: PointerEvent): void => { - if ( - event.target instanceof Node - && !rootRef.current?.contains(event.target) - && !menuRef.current?.contains(event.target) - ) { - changeOpen(false) - } + if (event.target instanceof Node && !rootRef.current?.contains(event.target) && !menuRef.current?.contains(event.target)) close() } - document.addEventListener('pointerdown', closeOutside) const dismiss = (event: globalThis.KeyboardEvent): void => { if (event.key !== 'Escape') return event.preventDefault() - changeOpen(false, menuRef.current?.contains(document.activeElement) === true) + close(menuRef.current?.contains(document.activeElement) === true) } + document.addEventListener('pointerdown', closeOutside) document.addEventListener('keydown', dismiss) return () => { document.removeEventListener('pointerdown', closeOutside) document.removeEventListener('keydown', dismiss) } - }, [open]) + }, [shown]) + useEffect(() => cancelHover, []) - useEffect(() => () => { - cancelHoverOpen() - cancelHoverClose() - }, []) - - const visible = presentedCatalog !== undefined - && (variant === 'switcher' - || props.hasBoardContent || presentedCatalog.state === 'error' - || presentedCatalog.entries.length > 0) - useEffect(() => { - if (visible) return - cancelHoverOpen() - cancelHoverClose() - if (!open) return - pinnedRef.current = false - setOpen(false) - setExpanded(new Set()) - }, [visible, open]) - - if (!visible) return null - - const focusAt = (index: number): void => { - const items = treeItems(menuRef.current) - if (items.length === 0) return - items[(index + items.length) % items.length]?.focus() + const hoverIn = (pointerType: string): void => { + if (pointerType === 'touch') return + cancelHover() + if (shown) return + hoverTimer.current = setTimeout(() => { setOpen('hover') }, 150) } - - const navigate = (event: KeyboardEvent): void => { - if (event.target instanceof Element - && event.target !== triggerRef.current && event.target !== menuRef.current - && event.target.closest('[role="tree"]') === null) return - const items = treeItems(menuRef.current) - const index = items.indexOf(document.activeElement as HTMLElement) - if (event.key === 'Home') { - event.preventDefault() - focusAt(0) - } else if (event.key === 'End') { - event.preventDefault() - focusAt(items.length - 1) - } else if (event.key === 'ArrowDown') { - event.preventDefault() - focusAt(index + 1) - } else if (event.key === 'ArrowUp') { - event.preventDefault() - focusAt(index < 0 ? items.length - 1 : index - 1) - } + const hoverOut = (): void => { + cancelHover() + if (open !== 'hover') return + hoverTimer.current = setTimeout(() => { setOpen('closed') }, 120) } return ( -
    - + - - {variant === 'count' && runningCount > 0 && ( - - )} - {open && createPortal(( + {title} + + + {shown && createPortal(( { - if (event.pointerType !== 'touch') cancelHoverClose() + onKeyDown={(event) => { + // A pinned menu takes focus itself; the tree handles keys once a row has focus. + if (event.target !== event.currentTarget) return + const items = treeItems(event.currentTarget) + const row = event.key === 'ArrowDown' || event.key === 'Home' ? items[0] + : event.key === 'ArrowUp' || event.key === 'End' ? items.at(-1) : undefined + if (row === undefined) return + event.preventDefault() + row.focus() }} - onPointerLeave={scheduleHoverClose} + onPointerEnter={(event) => { if (event.pointerType !== 'touch') cancelHover() }} + onPointerLeave={hoverOut} >
    - {hasSharedTasks && ( -
    - -

    {t('section.title')}

    - {progress && {progress}} -
    - )} - {hasSharedTasks && presentedCatalog.state === 'ready' && directCount === 0 && ( -

    {t('section.empty')}

    - )} -
    - { changeOpen(false) }} - t={t} - /> -
    - {props.renderFooter?.()} + { close() }} + focusFirst={open === 'keyboard'} + t={t} + />
    ), document.body)} @@ -829,56 +206,9 @@ function CatalogDropdown(props: CatalogDropdownProps) { ) } -/** Full props for the root-session catalog entry in the header actions band. */ -export type SubagentCatalogActionProps = - PropsRuntime<'conversation.session.header.actions'> & InjectFace & PropsLocale - & Omit, 'SessionProvider'> - /** - * Session-header catalog action for root sessions: the descendant count and - * its dropdown after the preset label in the header actions band. Child sessions render nothing - * here — their breadcrumb switcher in the lineage slot owns the same - * navigation. - * @param props - Session standard props plus the catalog actions and translator. - * @returns The count dropdown, or null on a child session. - */ -export function SubagentCatalogAction(props: SubagentCatalogActionProps) { - const addressedChild = props.useSession(snapshot => snapshot.subagent !== null) - const listedChild = props.useSessions(state => state.byId[props.sessionId]?.origin === 'subagent') - if (addressedChild || listedChild) return null - return -} - -/** Bind task-board visibility only in root conversations. */ -function RootCatalogAction({ - sessionId, useProjection, useSessions, useSessionStatus, useFooterAvailable, - openChild, openChildAside, refreshProjection, prepareCatalog, t, renderSlot, -}: SubagentCatalogActionProps) { - const hasSharedTasks = useProjection('agentTeam', team => team?.enabled === true - && team.tasks.some(task => task.status !== 'deleted')) - const hasTaskFailure = useProjection('agentTeam', team => team?.enabled === true && team.failure !== undefined) - const footerAvailable = useFooterAvailable(value => value) - return ( - renderSlot('conversation.session.header.actions.subagent.footer', {})} - useSessions={useSessions} - useSessionStatus={useSessionStatus} - openChild={openChild} - openChildAside={openChildAside} - refreshProjection={refreshProjection} - prepareCatalog={prepareCatalog} - t={t} - /> - ) -} - -/** - * Render one breadcrumb title together with its subagent navigation. + * Render one breadcrumb title together with its sibling switcher. The + * Session's own subagents are listed by the Session panel section. * @param props - Breadcrumb title, session standard props, and catalog actions. * @returns A title-and-chevron sibling switcher, or nothing on a root session. */ @@ -895,29 +225,21 @@ export function SubagentHeaderLineage({ const summary = state.byId[lineageSessionId] return summary?.origin === 'subagent' ? summary.parentId : undefined }) - const shared = { useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, prepareCatalog, t } - // Root sessions carry no breadcrumb; their descendant count lives in the - // header actions band (SubagentCatalogAction). if (parentId === undefined) return null return ( - <> - - {openTitle === undefined && ( - - )} - + ) } diff --git a/packages/client/ui-subagent/src/client/SubagentsSection.tsx b/packages/client/ui-subagent/src/client/SubagentsSection.tsx new file mode 100644 index 0000000000..deb1492470 --- /dev/null +++ b/packages/client/ui-subagent/src/client/SubagentsSection.tsx @@ -0,0 +1,170 @@ +/** Session panel section listing the current Session's subagents. */ +import { useCallback, useMemo } from 'react' +import { HoverCardGroup } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsLocale, PropsRenderFactories, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' +import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' +import { + CatalogTree, deriveCatalogs, levelPreparer, progressOf, type Catalogs, type SubagentCatalogInjected, type SubagentCatalogSnapshot, +} from './SubagentCatalog.tsx' +import type { createSubagentsSectionStore } from './subagents-store.ts' +import css from './SubagentCatalog.module.css' + +/** Full props of the subagents section. */ +export type SubagentsSectionProps = + PropsRuntime<'conversation.session.panel.section'> + & PropsRenderFactories + & InjectFace + & PropsStore> + & PropsLocale + +/** Rows the list shows before its fold control holds the rest back. */ +const FOLD_LIMIT = 5 + +const NO_ENTRIES: SubagentCatalogSnapshot['entries'] = [] + +/** Full props of the section's progress title control. */ +export type SubagentsProgressProps = + PropsRuntime<'conversation.session.panel.section.actions'> & PropsLocale + +/** Full props of the running dot on the Session panel toggle. */ +export type SubagentsRunningIndicatorProps = + PropsRuntime<'conversation.session.panel.indicator'> & PropsLocale + +function deriveSummaries(state: Parameters[0]>[0]) { + return state.byId +} + +/** + * Read every held Session's catalog from the standard Session hooks. + * @param props - Session list and status hooks. + * @returns catalogs keyed by parent Session, and the Session list rows. + */ +function useCatalogs({ useSessions, useSessionStatus }: Pick): { + readonly catalogs: Catalogs + readonly summaries: ReturnType +} { + const projections = useSessions(state => state.projectionsBySession) + const summaries = useSessions(deriveSummaries) + const statuses = useSessionStatus(value => value) + const catalogs = useMemo(() => deriveCatalogs(projections, summaries, statuses), [projections, summaries, statuses]) + return { catalogs, summaries } +} + +/** + * Order the section's rows: running subagents first, the most recently started + * first, then the others, the most recently active first. A running subagent + * sorts by the start of its open turn and another one by its Session's last + * update. A subagent the Client holds neither for sorts by when its parent + * created it: its turn timing is not read yet, or its Session is not in the + * Host list, whose stand-in row carries no update time. Rows that tie keep + * their catalog order. + * @param entries - the Session's direct subagents in catalog order. + * @param summaries - Session list rows by id. + * @returns the entries in display order. + */ +function sectionOrder( + entries: SubagentCatalogSnapshot['entries'], summaries: ReturnType, +): SubagentCatalogSnapshot['entries'] { + return entries + .map((entry) => { + const summary = summaries[entry.id] + const running = entry.activity === 'running' + // A Session is last updated after it is created, so the later of the two is the update time when the Client has one. + const at = running + ? summary?.projectionValues?.subagentTiming?.active?.since ?? entry.createdAt + : Math.max(summary?.updatedAt ?? 0, entry.createdAt) + return { entry, running, at } + }) + .sort((left, right) => Number(right.running) - Number(left.running) || right.at - left.at) + .map(row => row.entry) +} + +/** + * Render the Session's subagent tree, running subagents first and then the + * most recently active ones. The list 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. The section renders nothing while the Session has no + * subagents and no failed catalog read. Showing it reads nothing: rows offer + * expansion from locally known catalogs, and expanding a branch or retrying a + * failed read prepares that level. Opening a subagent closes the panel's + * overlay. + * @param props - Session hooks, panel owner values, the fold store, catalog actions, and copy. + * @returns the section body, or null with nothing to show. + */ +export function SubagentsSection({ + sessionId, dismissOverlay, useSessions, useSessionStatus, useStore, actions, openChild, openChildAside, prepareCatalog, + renderFactorySlot, t, +}: SubagentsSectionProps) { + const { catalogs, summaries } = useCatalogs({ useSessions, useSessionStatus }) + const catalog = catalogs[sessionId] + const unfolded = useStore(state => state.unfolded) + const prepareLevel = useMemo(() => levelPreparer(prepareCatalog), [prepareCatalog]) + const panelDetails = useCallback( + (details: PanelDetailsProps) => renderFactorySlot('conversation.session.panel.details', details), [renderFactorySlot], + ) + const ordered = useMemo(() => catalog === undefined ? NO_ENTRIES : sectionOrder(catalog.entries, summaries), [catalog, summaries]) + // Folding holds back two rows or more, since the fold control takes a row itself. + const foldable = ordered.length > FOLD_LIMIT + 1 + const shown = useMemo( + () => catalog === undefined ? undefined : { ...catalog, entries: foldable && !unfolded ? ordered.slice(0, FOLD_LIMIT) : ordered }, + [catalog, ordered, foldable, unfolded], + ) + if (shown === undefined || (shown.state !== 'error' && ordered.length === 0)) return null + const label = unfolded ? t('list.less') : t('list.more', { count: ordered.length - FOLD_LIMIT }) + return ( +
    + {/* Moving between rows swaps their hover cards without another dwell. */} + + + + {foldable && renderFactorySlot('conversation.session.panel.fold', { + expanded: unfolded, + label, + name: t('list.foldName', { label }), + onToggle: () => { actions.unfoldedSet(!unfolded) }, + })} +
    + ) +} + +/** + * Render the direct subagents' progress beside the section title. + * @param props - Session hooks and copy. + * @returns the progress phrase, or null without subagents. + */ +export function SubagentsProgress({ sessionId, useSessions, useSessionStatus, t }: SubagentsProgressProps) { + const { catalogs, summaries } = useCatalogs({ useSessions, useSessionStatus }) + const catalog = catalogs[sessionId] + const progress = catalog === undefined ? '' : progressOf(catalog, summaries, t) + if (progress === '') return null + return {progress} +} + +/** + * Show on the panel toggle that direct subagents run while the panel does not + * show them. External tasks do not count, as in the section's progress. + * @param props - Session hooks, whether the panel shows, and copy. + * @returns the dot with its name for assistive technology, or null with nothing to report. + */ +export function SubagentsRunningIndicator({ sessionId, panelShown, useSessions, useSessionStatus, t }: SubagentsRunningIndicatorProps) { + const { catalogs } = useCatalogs({ useSessions, useSessionStatus }) + const running = catalogs[sessionId]?.entries.filter(entry => entry.mode !== 'external' && entry.activity === 'running').length ?? 0 + if (panelShown || running === 0) return null + return ( + + {t('indicator.running', { count: running })} + + ) +} diff --git a/packages/client/ui-subagent/src/client/index.ts b/packages/client/ui-subagent/src/client/index.ts index d6fe29b2d8..9ab568f2ba 100644 --- a/packages/client/ui-subagent/src/client/index.ts +++ b/packages/client/ui-subagent/src/client/index.ts @@ -3,7 +3,10 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { SubagentCatalogAction, SubagentHeaderLineage, type SubagentCatalogInjected, type SubagentCatalogActionInjected } from './SubagentHeaderLineage.tsx' +import { SubagentHeaderLineage } from './SubagentHeaderLineage.tsx' +import type { SubagentCatalogInjected } from './SubagentCatalog.tsx' +import { SubagentsProgress, SubagentsRunningIndicator, SubagentsSection } from './SubagentsSection.tsx' +import { createSubagentsSectionStore } from './subagents-store.ts' import { SubagentReadOnlyComposer, type SubagentReadOnlyMatch, } from './SubagentReadOnlyComposer.tsx' @@ -12,11 +15,11 @@ import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-chat/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 type {} from '@deepseek-ai/dsh-client-ui-session-status/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import { en, ja, es, fr, de, ru, pt, NS, zh, type SubagentKey } from './locales.ts' -export type * from './slots.ts' declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { @@ -25,16 +28,17 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } } -export type { - SubagentCatalogActionProps, SubagentCatalogInjected, SubagentCatalogActionInjected, SubagentHeaderLineageProps, -} from './SubagentHeaderLineage.tsx' +export type { SubagentCatalogInjected } from './SubagentCatalog.tsx' +export type { SubagentHeaderLineageProps } from './SubagentHeaderLineage.tsx' +export type { SubagentsProgressProps, SubagentsRunningIndicatorProps, SubagentsSectionProps } from './SubagentsSection.tsx' export type { SubagentReadOnlyComposerProps, SubagentReadOnlyMatch, } from './SubagentReadOnlyComposer.tsx' /** * Required services for subagent presentation and navigation. `uiSession.sessionStatus` provides the - * `useSessionStatus` hook the lineage header renders with, so the plugin unloads and reloads with it. + * `useSessionStatus` hook the lineage header and the Session panel entries render with, so the plugin unloads and + * reloads with it. */ export const inject = ['sessions', 'uiWorkspace', 'slots', 'locale', 'sidebarRight', 'uiSession.sessionStatus'] @@ -48,11 +52,13 @@ function selectReadOnlySubagent(owner: ComposerChainProps): SubagentReadOnlyMatc } /** - * Client plugin body: register the subagent catalog and read-only composer seats. + * Client plugin body: register the breadcrumb switcher, the Session panel + * subagents section, and the read-only composer. * @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-subagent: dictionaries') + const t = ctx.locale.bind(NS) ctx.inject(['resources', 'sidebarRightTabs'], (scope) => { registerSidebarChat(scope, ctx.locale.bind(NS)) }) @@ -83,10 +89,6 @@ export function apply(ctx: ClientContext): void { void ctx.sessions.refreshProjections(parentSessionId) }, }) - const footerAvailable = { - getSnapshot: () => ctx.slots.entries('conversation.session.header.actions.subagent.footer').length > 0, - subscribe: (listener: () => void) => ctx.slots.subscribe('conversation.session.header.actions.subagent.footer', listener), - } ctx.slots.inject( 'conversation.session.header.lineage', () => ctx.slots.register({ @@ -95,20 +97,30 @@ export function apply(ctx: ClientContext): void { inject: catalogActions, }, SubagentHeaderLineage), ) - ctx.slots.inject( - 'conversation.session.header.actions', - () => ctx.slots.register({ - name: 'conversation.session.header.actions', - id: 'subagent-catalog', - // Between the preset label (-10) and background tasks (20). - order: 10, + ctx.slots.inject('conversation.session.panel.section', function* () { + yield ctx.slots.register({ + name: 'conversation.session.panel.section', + id: 'subagents', + // After change requests (100), before shared tasks (250). + order: 200, + label: () => t('section.title'), locale: NS, - inject: (sessionId): SubagentCatalogActionInjected => ({ - ...catalogActions(sessionId), hooks: { footerAvailable }, - }), - children: { 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' } }, - }, SubagentCatalogAction), - ) + store: createSubagentsSectionStore(), + inject: catalogActions, + }, SubagentsSection) + yield ctx.slots.register({ + name: 'conversation.session.panel.section.actions', + key: 'subagents', + locale: NS, + }, SubagentsProgress) + }) + ctx.slots.inject('conversation.session.panel.indicator', () => ctx.slots.register({ + name: 'conversation.session.panel.indicator', + id: 'subagents.running', + // Below an attention mark, which paints above running dots. + order: 10, + locale: NS, + }, SubagentsRunningIndicator)) ctx.slots.inject( 'conversation.composer', () => ctx.slots.register({ diff --git a/packages/client/ui-subagent/src/client/locales.ts b/packages/client/ui-subagent/src/client/locales.ts index 83754edd6c..0e1c80e59b 100644 --- a/packages/client/ui-subagent/src/client/locales.ts +++ b/packages/client/ui-subagent/src/client/locales.ts @@ -6,11 +6,14 @@ export const NS = 'subagent' /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { 'section.title': '子智能体', - 'section.empty': '暂无子智能体', + 'indicator.running': '{count} 个子智能体运行中', 'progress.completed': '{count} 已完成', 'progress.active': '{count} 进行中', 'progress.inactive': '{count} 未运行', 'progress.external': '{count} 外部任务', + 'list.more': '显示其余 {count} 个', + 'list.less': '收起', + 'list.foldName': '{label}(子智能体)', 'duration.seconds': '{seconds}秒', 'duration.minutes': '{minutes}分{seconds}秒', 'duration.hours': '{hours}小时{minutes}分{seconds}秒', @@ -21,10 +24,10 @@ export const zh = { 'duration.years': '约{years}年', 'duration.yearsMonths': '约{years}年{months}个月', 'duration.exactDays': '{days}天{hours}小时{minutes}分{seconds}秒', - 'duration.exactTitle': '总活跃耗时:{duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} tok', + 'hover.owner': '负责人:{name}', 'loading.label': '正在加载子智能体…', 'load.idle': '尚未加载子智能体', 'load.error': '无法加载子智能体', @@ -39,10 +42,6 @@ export const zh = { 'activity.inactive': '当前未运行', 'branch.collapse': '收起 {label} 的下级子智能体', 'branch.expand': '展开 {label} 的下级子智能体', - 'count.total.one': '{count} 个子智能体', - 'count.total.other': '{count} 个子智能体', - 'count.running.one': '{count} 个子智能体,正在运行', - 'count.running.other': '{count} 个子智能体,正在运行', 'switcher.aria': '切换子智能体:{title}', 'tree.aria': '子智能体会话', 'open.sidebar': '在侧边栏打开', @@ -57,11 +56,14 @@ export const zh = { /** English dictionary, key-identical to the Chinese source of truth. */ export const en: Record = { 'section.title': 'Subagents', - 'section.empty': 'No subagents', + 'indicator.running': 'Subagents running: {count}', 'progress.completed': '{count} completed', 'progress.active': '{count} in progress', 'progress.inactive': '{count} not running', 'progress.external': '{count} external', + 'list.more': 'Show {count} more', + 'list.less': 'Show less', + 'list.foldName': '{label} (subagents)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -72,10 +74,10 @@ export const en: Record = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Total active duration: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} tok', + 'hover.owner': 'Owner: {name}', 'loading.label': 'Loading subagents…', 'load.idle': 'Subagents not loaded', 'load.error': 'Unable to load subagents', @@ -90,10 +92,6 @@ export const en: Record = { 'activity.inactive': 'not running', 'branch.collapse': 'Collapse {label} descendants', 'branch.expand': 'Expand {label} descendants', - 'count.total.one': '{count} subagent', - 'count.total.other': '{count} subagents', - 'count.running.one': '{count} subagent running', - 'count.running.other': '{count} subagents running', 'switcher.aria': 'Switch subagent: {title}', 'tree.aria': 'Subagent sessions', 'open.sidebar': 'Open in sidebar', @@ -111,11 +109,14 @@ export type SubagentKey = keyof typeof zh /** Japanese copy, checked against the English keys. */ export const ja = { 'section.title': 'サブエージェント', - 'section.empty': 'サブエージェントはありません', + 'indicator.running': '実行中のサブエージェント: {count}', 'progress.completed': '{count}件完了', 'progress.active': '{count}件進行中', 'progress.inactive': '{count}件停止中', 'progress.external': '{count}件外部タスク', + 'list.more': '残り{count}件を表示', + 'list.less': '折りたたむ', + 'list.foldName': '{label}(サブエージェント)', 'duration.seconds': '{seconds}秒', 'duration.minutes': '{minutes}分{seconds}秒', 'duration.hours': '{hours}時間{minutes}分{seconds}秒', @@ -126,10 +127,10 @@ export const ja = { 'duration.years': '約{years}年', 'duration.yearsMonths': '約{years}年{months}ヶ月', 'duration.exactDays': '{days}日{hours}時間{minutes}分{seconds}秒', - 'duration.exactTitle': '合計アクティブ時間: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} tok', + 'hover.owner': '担当:{name}', 'loading.label': 'サブエージェントを読み込み中…', 'load.idle': 'サブエージェントは未読み込みです', 'load.error': 'サブエージェントを読み込めません', @@ -144,10 +145,6 @@ export const ja = { 'activity.inactive': '停止中', 'branch.collapse': '{label}の子孫を折りたたむ', 'branch.expand': '{label}の子孫を展開', - 'count.total.one': 'サブエージェント{count}件', - 'count.total.other': 'サブエージェント{count}件', - 'count.running.one': '実行中のサブエージェント{count}件', - 'count.running.other': '実行中のサブエージェント{count}件', 'switcher.aria': 'サブエージェントを切り替え: {title}', 'tree.aria': 'サブエージェントセッション', 'open.sidebar': 'サイドバーで開く', @@ -162,11 +159,14 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { 'section.title': 'Subagentes', - 'section.empty': 'No hay subagentes', + 'indicator.running': 'Subagentes en ejecución: {count}', 'progress.completed': '{count} completado', 'progress.active': '{count} en progreso', 'progress.inactive': '{count} sin ejecutar', 'progress.external': '{count} externos', + 'list.more': 'Mostrar {count} más', + 'list.less': 'Mostrar menos', + 'list.foldName': '{label} (subagentes)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -177,10 +177,10 @@ export const es = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Duración total activa: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': 'Tok {value}', + 'hover.owner': 'Responsable: {name}', 'loading.label': 'Cargando subagentes…', 'load.idle': 'Subagentes sin cargar', 'load.error': 'No se pueden cargar subagentes', @@ -195,10 +195,6 @@ export const es = { 'activity.inactive': 'no corriendo', 'branch.collapse': 'Contraer descendientes de {label}', 'branch.expand': 'Ampliar descendientes de {label}', - 'count.total.one': 'Subagente {count}', - 'count.total.other': 'Subagentes {count}', - 'count.running.one': 'Subagente {count} ejecutándose', - 'count.running.other': 'Subagentes {count} ejecutándose', 'switcher.aria': 'Cambiar subagente: {title}', 'tree.aria': 'Sesiones de subagente', 'open.sidebar': 'Abrir en la barra lateral', @@ -213,11 +209,14 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { 'section.title': 'Sous-agents', - 'section.empty': 'Aucun sous-agent', + 'indicator.running': 'Sous-agents en cours : {count}', 'progress.completed': '{count} terminé', 'progress.active': '{count} en cours', 'progress.inactive': '{count} à l’arrêt', 'progress.external': '{count} externes', + 'list.more': 'Afficher {count} de plus', + 'list.less': 'Afficher moins', + 'list.foldName': '{label} (sous-agents)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -228,10 +227,10 @@ export const fr = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': "Durée totale d'activité : {duration}", 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': 'Jeton {value}', + 'hover.owner': 'Responsable : {name}', 'loading.label': 'Chargement des sous-agents…', 'load.idle': 'Sous-agents non chargés', 'load.error': 'Impossible de charger les sous-agents', @@ -246,10 +245,6 @@ export const fr = { 'activity.inactive': 'ne fonctionne pas', 'branch.collapse': 'Réduire les descendants de {label}', 'branch.expand': 'Développer les descendants de {label}', - 'count.total.one': 'Sous-agent {count}', - 'count.total.other': 'Sous-agents {count}', - 'count.running.one': "Sous-agent {count} en cours d'exécution", - 'count.running.other': "Sous-agents {count} en cours d'exécution", 'switcher.aria': 'Changer de sous-agent : {title}', 'tree.aria': 'Sessions de sous-agents', 'open.sidebar': 'Ouvrir dans la barre latérale', @@ -264,11 +259,14 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { 'section.title': 'Subagenten', - 'section.empty': 'Keine Subagenten', + 'indicator.running': 'Laufende Subagenten: {count}', 'progress.completed': '{count} abgeschlossen', 'progress.active': '{count} in Bearbeitung', 'progress.inactive': '{count} nicht aktiv', 'progress.external': '{count} extern', + 'list.more': '{count} weitere anzeigen', + 'list.less': 'Weniger anzeigen', + 'list.foldName': '{label} (Subagenten)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -279,10 +277,10 @@ export const de = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Gesamte aktive Dauer: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value}-Token', + 'hover.owner': 'Zuständig: {name}', 'loading.label': 'Subagenten werden geladen…', 'load.idle': 'Subagenten nicht geladen', 'load.error': 'Subagenten können nicht geladen werden', @@ -297,10 +295,6 @@ export const de = { 'activity.inactive': 'läuft nicht', 'branch.collapse': '{label}-Nachkommen reduzieren', 'branch.expand': 'Erweitern Sie {label}-Nachkommen', - 'count.total.one': '{count}-Subagent', - 'count.total.other': '{count}-Subagenten', - 'count.running.one': '{count}-Subagent läuft', - 'count.running.other': '{count} Subagenten laufen', 'switcher.aria': 'Subagent wechseln: {title}', 'tree.aria': 'Subagentensitzungen', 'open.sidebar': 'In der Seitenleiste öffnen', @@ -315,11 +309,14 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { 'section.title': 'Субагенты', - 'section.empty': 'Нет субагентов', + 'indicator.running': 'Выполняется субагентов: {count}', 'progress.completed': '{count} завершено', 'progress.active': '{count} в процессе', 'progress.inactive': '{count} не выполняются', 'progress.external': '{count} внешних', + 'list.more': 'Показать ещё {count}', + 'list.less': 'Свернуть', + 'list.foldName': '{label} (субагенты)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -330,10 +327,10 @@ export const ru = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}y {months}mo', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Общая активная продолжительность: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} ток', + 'hover.owner': 'Ответственный: {name}', 'loading.label': 'Загрузка субагентов…', 'load.idle': 'Субагенты не загружены', 'load.error': 'Невозможно загрузить субагенты', @@ -348,10 +345,6 @@ export const ru = { 'activity.inactive': 'не работает', 'branch.collapse': 'Свернуть потомков {label}', 'branch.expand': 'Развернуть потомков {label}', - 'count.total.one': 'Субагент {count}', - 'count.total.other': 'Субагенты {count}', - 'count.running.one': 'Субагент {count} работает', - 'count.running.other': 'Субагенты {count} работают', 'switcher.aria': 'Переключить субагент: {title}', 'tree.aria': 'Сеансы субагента', 'open.sidebar': 'Открыть в боковой панели', @@ -366,11 +359,14 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { 'section.title': 'Subagentes', - 'section.empty': 'Nenhum subagente', + 'indicator.running': 'Subagentes em execução: {count}', 'progress.completed': '{count} concluído', 'progress.active': '{count} em andamento', 'progress.inactive': '{count} sem execução', 'progress.external': '{count} externos', + 'list.more': 'Mostrar mais {count}', + 'list.less': 'Mostrar menos', + 'list.foldName': '{label} (subagentes)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', @@ -381,10 +377,10 @@ export const pt = { 'duration.years': '~{years}y', 'duration.yearsMonths': '~{years}a {months}mês', 'duration.exactDays': '{days}d {hours}h {minutes}m {seconds}s', - 'duration.exactTitle': 'Duração total ativa: {duration}', 'tokens.thousand': '{value}K', 'tokens.million': '{value}M', 'tokens.total': '{value} valor', + 'hover.owner': 'Responsável: {name}', 'loading.label': 'Carregando subagentes…', 'load.idle': 'Subagentes não carregados', 'load.error': 'Não foi possível carregar subagentes', @@ -399,10 +395,6 @@ export const pt = { 'activity.inactive': 'não está funcionando', 'branch.collapse': 'Recolher {label} descendentes', 'branch.expand': 'Expandir {label} descendentes', - 'count.total.one': '{count} subagente', - 'count.total.other': '{count} subagentes', - 'count.running.one': '{count} subagente em execução', - 'count.running.other': '{count} subagentes em execução', 'switcher.aria': 'Alternar subagente: {title}', 'tree.aria': 'Sessões de subagente', 'open.sidebar': 'Abrir na barra lateral', diff --git a/packages/client/ui-subagent/src/client/slots.ts b/packages/client/ui-subagent/src/client/slots.ts deleted file mode 100644 index a3e379e62f..0000000000 --- a/packages/client/ui-subagent/src/client/slots.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** Extension position below the root conversation's subagent catalog. */ - -declare module '@deepseek-ai/dsh-client-ui-slots' { - interface SlotMap { - /** Content below the root Session's subagent tree. */ - 'conversation.session.header.actions.subagent.footer': { - kind: 'list' - scope: 'session' - } - } -} - -export {} diff --git a/packages/client/ui-subagent/src/client/subagents-store.ts b/packages/client/ui-subagent/src/client/subagents-store.ts new file mode 100644 index 0000000000..c650efe170 --- /dev/null +++ b/packages/client/ui-subagent/src/client/subagents-store.ts @@ -0,0 +1,38 @@ +/** + * Whether the user unfolded the subagents 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 subagents list. */ +export interface SubagentsSectionState { + /** Whether the list shows every row instead of holding back the rows past its limit. */ + unfolded: boolean +} + +/** The subagents section store's write set. */ +type SubagentsSectionActions = { + unfoldedSet: (draft: SubagentsSectionState, unfolded: boolean) => void +} + +/** + * Declare the subagents section's store. + * @returns the store handle to declare on the registration. + */ +export function createSubagentsSectionStore(): EngineStoreHandle { + return defineStore({ + init: (): SubagentsSectionState => ({ unfolded: false }), + actions: { + /** + * Record the user's choice to show every row or fold the list again. + * @param d - draft state. + * @param unfolded - whether the list now shows every row. + */ + unfoldedSet: (d, unfolded: boolean) => { + d.unfolded = unfolded + }, + }, + }) +} diff --git a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts index 4dae089f5a..dc7ea06f05 100644 --- a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts @@ -11,9 +11,10 @@ import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client' import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client' -import { - SubagentHeaderLineage, type SubagentCatalogInjected, type SubagentCatalogActionInjected, -} from '../src/client/SubagentHeaderLineage.tsx' +import { SubagentHeaderLineage } from '../src/client/SubagentHeaderLineage.tsx' +import type { SubagentCatalogInjected } from '../src/client/SubagentCatalog.tsx' +import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots' +import { en } from '../src/client/locales.ts' import { SubagentReadOnlyComposer, type SubagentReadOnlyMatch, } from '../src/client/SubagentReadOnlyComposer.tsx' @@ -66,7 +67,9 @@ async function provideSlotFaces(ctx: Context): Promise { name: 'root', children: { 'conversation.session.header.lineage': { kind: 'single', scope: 'session' }, - 'conversation.session.header.actions': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section': { kind: 'list', scope: 'session' }, + 'conversation.session.panel.section.actions': { kind: 'keyed', scope: 'session' }, + 'conversation.session.panel.indicator': { kind: 'list', scope: 'session' }, 'conversation.composer': { kind: 'chain', scope: 'session' }, }, } as never, () => null) @@ -114,14 +117,13 @@ describe('apply', () => { it('keeps the root catalog extension available when optional Sidebar services arrive', async () => { const { ctx } = await fullBench(FAMILY) onTestFinished(() => ctx.fiber.dispose()) - ctx.slots.register({ name: 'conversation.session.header.actions.subagent.footer', id: 'test-content' }, () => null) const registerResource = vi.fn(() => () => {}) const registerTab = vi.fn(() => () => {}) ctx.provide('resources', { register: registerResource } as never) ctx.provide('sidebarRightTabs', { register: registerTab } as never) await vi.waitFor(() => { expect(registerResource).toHaveBeenCalledOnce() }) expect(registerTab).toHaveBeenCalledOnce() - expect(ctx.slots.entries('conversation.session.header.actions.subagent.footer')).toHaveLength(1) + expect(ctx.slots.entries('conversation.session.panel.section').map(entry => entry.options.id)).toEqual(['subagents']) }) it('reads direct child catalogs sequentially after reading the parent', async () => { @@ -183,26 +185,17 @@ describe('apply', () => { { method: 'refreshProjections', args: [sid('parent')] }, ]) - // The root-session catalog seat registers in the actions band with the - // same business face, between the preset label (-10) and background - // tasks (20). - const actionEntry = ctx.slots.entries('conversation.session.header.actions') - .find(entry => entry.options.id === 'subagent-catalog')! - expect(actionEntry.options.order).toBe(10) - const actionProps = (actionEntry.inject as (id: SessionId) => SubagentCatalogActionInjected)(sid('parent')) - const source = actionProps.hooks.footerAvailable - const changed = vi.fn() - const unsubscribe = source.subscribe(changed) - expect(source.getSnapshot()).toBe(false) - const remove = ctx.slots.register({ - name: 'conversation.session.header.actions.subagent.footer', id: 'test-footer', - }, () => null) - expect(source.getSnapshot()).toBe(true) - await vi.waitFor(() => { expect(changed).toHaveBeenCalledOnce() }) - remove() - expect(source.getSnapshot()).toBe(false) - await vi.waitFor(() => { expect(changed).toHaveBeenCalledTimes(2) }) - unsubscribe() + // The Session panel section registers with the same business face, + // after change requests (100) and before background jobs (300), together + // with its progress control beside the title. + const sectionEntry = ctx.slots.entries('conversation.session.panel.section') + .find(entry => entry.options.id === 'subagents')! + expect(sectionEntry.options.order).toBe(200) + expect(resolveSlotLabel(sectionEntry.options.label)).toBe(en['section.title']) + expect(ctx.slots.entries('conversation.session.panel.section.actions').map(entry => entry.options.key)).toEqual(['subagents']) + expect(ctx.slots.entries('conversation.session.panel.indicator')[0]).toMatchObject({ options: { id: 'subagents.running', order: 10 } }) + const sectionActions = (sectionEntry.inject as (id: SessionId) => SubagentCatalogInjected)(sid('parent')) + expect(Object.keys(sectionActions).sort()).toEqual(['openChild', 'openChildAside', 'prepareCatalog', 'refreshProjection']) const composerEntry = ctx.slots.entries('conversation.composer') .find(entry => entry.component === SubagentReadOnlyComposer)! diff --git a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx index 7ff86bb02c..a13821a1c8 100644 --- a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx +++ b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx @@ -2,20 +2,23 @@ import { contextMenuHook } from '@deepseek-ai/dsh-client-test-runtime' import { afterEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' -import { allowAllAccess, makeTranslate, RemoteError, sessionSnapshot } from '@deepseek-ai/dsh-client-test-runtime' +import { useState } from 'react' +import { allowAllAccess, bindSnapshotSelector, makeTranslate, RemoteError, sessionSnapshot } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionListState, SessionSummary, SessionSnapshot, } from '@deepseek-ai/dsh-api-session-controller/client' import type { SubagentAddress, SubagentCatalogEntry } from '@deepseek-ai/dsh-subagent/client' -import type { TeamProjection, TeamTaskId, TeamTaskView } from '@deepseek-ai/dsh-agent-team/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session-status/client' +import { SubagentHeaderLineage, type SubagentHeaderLineageProps } from '../src/client/SubagentHeaderLineage.tsx' import { - SubagentCatalogAction, SubagentHeaderLineage, - type SubagentCatalogActionProps, type SubagentHeaderLineageProps, -} from '../src/client/SubagentHeaderLineage.tsx' + SubagentsProgress, SubagentsRunningIndicator, SubagentsSection, + type SubagentsProgressProps, type SubagentsRunningIndicatorProps, type SubagentsSectionProps, +} from '../src/client/SubagentsSection.tsx' import { SubagentReadOnlyComposer } from '../src/client/SubagentReadOnlyComposer.tsx' +import { createSubagentsSectionStore } from '../src/client/subagents-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() @@ -29,26 +32,21 @@ const CHILD = 'child' as SessionId const GRANDCHILD = 'grandchild' as SessionId const t: SubagentHeaderLineageProps['t'] = makeTranslate(zh) -type HeaderCatalogProps = SubagentHeaderLineageProps - & Pick +/** One Session's section store, as the registration mints it. */ +type SectionStore = ReturnType['create']> + +type HeaderCatalogProps = SubagentHeaderLineageProps & { dismissOverlay?: () => void; store?: SectionStore | undefined } type CatalogFixtureEntry = Entry extends SubagentCatalogEntry ? Omit & { activity: 'running' | 'inactive' } : never type CatalogFixture = { - team?: TeamProjection entries: readonly CatalogFixtureEntry[] state: SessionListState['projectionsBySession'][SessionId]['state'] error: SessionListState['projectionsBySession'][SessionId]['error'] } -const sharedTask: TeamTaskView = { - id: 'shared-task' as TeamTaskId, revision: 1, subject: 'Plan shared work', description: 'Prepare the implementation', - status: 'pending', blockedBy: [], writeScopes: [], ready: true, writeScopeWarnings: [], -} -const sharedTeam: TeamProjection = { enabled: true, tasks: [sharedTask] } - function catalog(over: Partial = {}): CatalogFixture { return { entries: [ @@ -75,44 +73,30 @@ function props( ) { const catalogs = value === undefined ? nested : { [PARENT]: value, ...nested } const statuses: SessionStatusSnapshot = new Map() - const byId: Record = { - ...Object.fromEntries(Object.values(catalogs).flatMap(catalog => catalog.entries.map(entry => [entry.id, { - id: entry.id, displayTitle: entry.label ?? entry.id, running: entry.activity === 'running', blank: false, updatedAt: 1, retainedBy: {}, projectionValues: { subagentCatalog: [] }, - }]))), - [CHILD]: { - id: CHILD, - title: '正在扫描项目文件', - displayTitle: 'worker', - running: Object.values(catalogs).some(catalog => catalog.entries.some(entry => entry.id === CHILD && entry.activity === 'running')), - retainedBy: {}, - blank: false, - updatedAt: Date.now(), - projectionValues: { subagentCatalog: [] }, - }, - ...summaries, - } const state = { ids: [CHILD], - byId, - phase: 'ready', - projectionsBySession: { - ...Object.fromEntries(Object.entries(byId).flatMap(([id, entry]) => entry.projectionValues === undefined ? [] : [[id, { - state: 'idle' as const, error: null, values: entry.projectionValues, - }]])), - ...Object.fromEntries(Object.entries(catalogs).map(([id, catalog]) => [id, { - state: catalog.state, error: catalog.error, - values: { - ...byId[id as SessionId]?.projectionValues, - ...catalog.team === undefined ? {} : { agentTeam: catalog.team }, - subagentCatalog: catalog.entries.map(({ activity: _activity, ...entry }) => ({ ...entry, createdAt: 1 })), - }, - }])), + byId: summaries ?? { + ...Object.fromEntries(Object.values(catalogs).flatMap(catalog => catalog.entries.map(entry => [entry.id, { + id: entry.id, displayTitle: entry.label ?? entry.id, running: entry.activity === 'running', blank: false, updatedAt: 1, retainedBy: {}, + }]))), + [CHILD]: { + id: CHILD, + title: '正在扫描项目文件', + displayTitle: 'worker', + running: Object.values(catalogs).some(catalog => catalog.entries.some(entry => entry.id === CHILD && entry.activity === 'running')), + retainedBy: {}, + blank: false, + updatedAt: Date.now(), + }, }, + phase: 'ready', + projectionsBySession: Object.fromEntries(Object.entries(catalogs).map(([id, catalog]) => [id, { + state: catalog.state, error: catalog.error, + values: { + subagentCatalog: catalog.entries.map(({ activity: _activity, ...entry }) => ({ ...entry, createdAt: 1 })), + }, + }])) , } satisfies SessionListState - for (const [id, entry] of Object.entries(byId)) { - const projection = state.projectionsBySession[id] - if (projection !== undefined) byId[id as SessionId] = { ...entry, projectionValues: projection.values } - } function useSessions(select: (snapshot: SessionListState) => T): T { return select(state) } @@ -149,14 +133,12 @@ function props( ...standard, sessionId: PARENT, useSessions, - useFooterAvailable: (select: (available: boolean) => T): T => select(true), useSessionStatus: (select: (snapshot: SessionStatusSnapshot) => T): T => select(statuses), useSession: (select: (snapshot: SessionSnapshot) => T): T => select(snapshot), openChild: vi.fn(), openChildAside: vi.fn(), refreshProjection: vi.fn(), prepareCatalog: vi.fn<(id: SessionId) => Promise>().mockResolvedValue(), - renderSlot: vi.fn(() => null), lineageSessionId: PARENT, displayTitle: 'Parent title', t, @@ -197,126 +179,74 @@ function enableTooltips(): void { } /** - * Both header seats as the real header composes them: the breadcrumb switcher - * (child sessions, lineage slot) and the actions-band catalog entry (root - * sessions) — exactly one renders per form. The actions seat sees the same - * session the lineage renders. + * Rest the pointer on a Session panel row past the hover card's 500ms dwell and + * read the card's parts in order, then leave it. + * @param row - the row's treeitem. + * @returns the card's lines, or null while no card shows. */ -function HeaderCatalog(props: HeaderCatalogProps) { - const actionProps: SubagentCatalogActionProps = { - ...props, sessionId: props.lineageSessionId, - useProjection: ((_key: 'agentTeam', selector: (value: TeamProjection | undefined) => boolean) => - props.useSessions(state => selector(state.projectionsBySession[props.lineageSessionId]?.values.agentTeam))) as SubagentCatalogActionProps['useProjection'], - } +async function hoverDetailsOf(row: HTMLElement): Promise { + vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: query === '(any-hover: hover)' }))) + const anchor = row.parentElement as HTMLElement + fireEvent.pointerEnter(anchor, { pointerType: 'mouse' }) + await act(async () => { await vi.advanceTimersByTimeAsync(500) }) + const card = document.querySelector('[data-session-panel-details]') + const lines = card === null ? null : [...card.children].map(child => child.textContent ?? '') + fireEvent.pointerLeave(anchor, { pointerType: 'mouse' }) + await act(async () => { await vi.advanceTimersByTimeAsync(400) }) + return lines +} + +/** + * The two surfaces as the real page composes them: the breadcrumb switcher + * (child sessions, lineage slot) and the Session panel section listing the + * Session's own subagents. The section sees the same Session the lineage renders. + */ +function HeaderCatalog({ store, ...props }: HeaderCatalogProps) { return ( <> - +
    ) } +/** + * The Session panel's Factories as these suites render 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 ( +
    + {title !== undefined &&
    {title}
    } + {lines.map(line =>
    {line}
    )} + {status !== undefined &&
    {status.label}
    } + {facts.length > 0 &&
    {facts.map(fact => {fact.label})}
    } +
    + ) + } + const fold = input as PanelFoldProps + return +} + +/** The section with the panel owner values, its Session's store (a fresh one unless given), and the fold control. */ +function Section({ store, dismissOverlay, ...props }: Omit) { + const [own] = useState(() => store ?? createSubagentsSectionStore().create()) + const [useStore] = useState(() => bindSnapshotSelector(own)) + const sectionProps = { + ...props, presentation: 'docked', dismissOverlay: dismissOverlay ?? vi.fn(), useStore, actions: own.actions, renderFactorySlot: renderPanelFactory, + } as SubagentsSectionProps + return +} + describe('SubagentHeaderLineage', () => { - it.each([ - { dictionary: zh, total: '2 个子智能体', running: '1 个子智能体,正在运行' }, - { dictionary: en, total: '2 subagents', running: '1 subagent running' }, - ])('keeps the total accessible name separate from the running description: $total', ({ dictionary, total, running }) => { - const input = props(catalog()) - const view = render() - const trigger = screen.getByRole('button', { name: total }) - expect(trigger.textContent).toBe(total) - expect(document.getElementById(trigger.getAttribute('aria-describedby')!)?.textContent).toBe(running) - view.rerender() - expect(screen.getByRole('button', { name: total }).getAttribute('aria-describedby')).toBeNull() - }) - it('shows a non-collapsible heading with direct-member progress beside shared tasks', () => { - const finished = 'finished' as SessionId - const paused = 'paused' as SessionId - const external = 'external' as SessionId - const entries: CatalogFixture['entries'] = [ - { id: CHILD, mode: 'continuable', label: 'worker', activity: 'running' }, - { id: finished, mode: 'continuable', label: 'finished', activity: 'inactive' }, - { id: paused, mode: 'continuable', label: 'paused', activity: 'inactive' }, - { id: external, mode: 'external', label: 'external', activity: 'running' }, - ] - const summaries: Record = { - [CHILD]: { ...summary(CHILD, 1), running: true, projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } } }, - [finished]: { ...summary(finished, 1), projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } } }, - [paused]: { ...summary(paused, 1), projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: false } } }, - [external]: { - ...summary(external, 1), running: true, projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } }, - }, - } - const input = props(catalog({ entries, team: sharedTeam }), { - [CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'nested', activity: 'running' }] }), - }, summaries) - const view = render() - fireEvent.click(screen.getByRole('button', { name: '4 个子智能体' })) - const header = view.container.ownerDocument.querySelector('[data-subagent-section-header]')! - expect(within(header).getByRole('heading', { name: '子智能体' })).toBeTruthy() - expect(within(header).queryByRole('button')).toBeNull() - expect(header.textContent).toBe('子智能体1 已完成\u2002·\u20021 进行中\u2002·\u20021 未运行\u2002·\u20021 外部任务') - fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) - expect(header.textContent).toContain('1 进行中') - expect(header.textContent).not.toContain('2 进行中') - view.rerender() - expect(header.textContent).toBe('Subagents1 completed\u2002·\u20021 in progress\u2002·\u20021 not running\u2002·\u20021 external') - }) - - it('omits zero progress counts from a completed-only catalog header', () => { - const input = props(catalog({ - team: sharedTeam, entries: [{ id: CHILD, mode: 'continuable', label: 'finished', activity: 'inactive' }], - }), {}, { - [CHILD]: { ...summary(CHILD, 1), projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: true } } }, - }) - render() - fireEvent.click(screen.getByRole('button', { name: '1 个子智能体' })) - const header = document.querySelector('[data-subagent-section-header]')! - expect(header.textContent).toBe('子智能体1 已完成') - }) - - it.each([ - { name: 'absent Team projection', team: undefined, footer: true }, - { name: 'disabled Team mode', team: { ...sharedTeam, enabled: false }, footer: true }, - { name: 'empty tasks', team: { enabled: true, tasks: [] }, footer: true }, - { name: 'deleted-only tasks', team: { enabled: true, tasks: [{ ...sharedTask, status: 'deleted' }] }, footer: true }, - { name: 'failure without tasks', team: { enabled: true, tasks: [], failure: 'Invalid task record' }, footer: true }, - { name: 'unavailable task footer', team: sharedTeam, footer: false }, - ] satisfies { name: string; team: TeamProjection | undefined; footer: boolean }[])( - 'omits section headings from a members-only catalog with $name', ({ team, footer }) => { - const input = props(catalog({ ...team === undefined ? {} : { team } })) - render( select(footer)} />) - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) - expect(screen.getByRole('tree')).toBeTruthy() - expect(screen.queryByRole('heading')).toBeNull() - expect(document.querySelector('[data-subagent-section-header]')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - }, - ) - - it('shows the description above the Session id and opens the row without a description toggle', () => { - const description = 'Check the construction and all bounds. '.repeat(20).trim() - const input = props(catalog({ - entries: [{ id: CHILD, mode: 'continuable', label: description, activity: 'running' }], - })) - render() - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) - const row = screen.getByRole('treeitem', { name: new RegExp(CHILD) }) - const primary = within(row).getByText(description) - const id = within(row).getByText(CHILD) - expect(primary.compareDocumentPosition(id) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - expect(row.getAttribute('aria-label')).toMatch(/^Check the construction/) - expect(primary.tagName).toBe('SPAN') - expect(primary.getAttribute('aria-expanded')).toBeNull() - expect(primary.querySelector('svg')).toBeNull() - expect(within(row).queryByRole('button', { name: /描述/ })).toBeNull() - fireEvent.click(primary) - expect(input.openChild).toHaveBeenCalledExactlyOnceWith({ parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }) - expect(screen.queryByRole('treeitem')).toBeNull() + it('omits section headings from a catalog of members', () => { + render() + expect(screen.getByRole('tree')).toBeTruthy() + expect(screen.queryByRole('heading')).toBeNull() + expect(document.querySelector('[data-subagent-section-header]')).toBeNull() }) it.each([undefined, ''])('keeps a single ID line when the creation description is %s', (label) => { @@ -324,13 +254,13 @@ describe('SubagentHeaderLineage', () => { entries: [{ id: CHILD, mode: 'one-shot', ...label === undefined ? {} : { label }, activity: 'running' }], }), {}, { [CHILD]: { ...summary(CHILD, 1), running: true } }) render() - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) const row = screen.getByRole('treeitem', { name: new RegExp(CHILD) }) expect(within(row).getAllByText(CHILD)).toHaveLength(1) expect(row.getAttribute('aria-label')).toMatch(new RegExp(`^${CHILD}`)) }) - it('shows agent names in place of Session ids while navigation keeps the Session id', () => { + it('shows agent names in place of Session ids while navigation keeps the Session id', async () => { + vi.useFakeTimers() const external = 'external-id' as SessionId const input = props(catalog({ entries: [ @@ -340,11 +270,11 @@ describe('SubagentHeaderLineage', () => { ], }), {}, { [CHILD]: { ...summary(CHILD, 1), running: true } }) render() - fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) const named = screen.getByRole('treeitem', { name: /^Review the diff reviewer/ }) - expect(within(named).getByText('Review the diff').compareDocumentPosition(within(named).getByText('reviewer')) - & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + // The panel row shows one line; its hover card names the agent as the owner. + expect(within(named).queryByText('reviewer')).toBeNull() expect(within(named).queryByText(CHILD)).toBeNull() + expect(await hoverDetailsOf(named)).toEqual(['Review the diff', '负责人:reviewer', '正在运行 · 可继续']) const undescribed = screen.getByRole('treeitem', { name: /^checker/ }) expect(within(undescribed).getAllByText('checker')).toHaveLength(1) expect(within(undescribed).queryByText(GRANDCHILD)).toBeNull() @@ -353,91 +283,9 @@ describe('SubagentHeaderLineage', () => { expect(input.openChild).toHaveBeenCalledExactlyOnceWith({ parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }) }) - it('hides an empty Team entry but keeps shared tasks and errors reachable without children', () => { - const input = props(catalog({ entries: [] })) - const initial = input.useSessions(state => state) - const mode: { enabled: boolean; tasks: TeamTaskView[]; failure?: string } = { enabled: true, tasks: [] } - const values = { ...initial.projectionsBySession[PARENT]!.values, agentTeam: mode } - const current = { - ...input, - useSessions: (select: (snapshot: SessionListState) => T): T => select({ - ...initial, projectionsBySession: { [PARENT]: { state: 'ready', error: null, values } }, - }), - renderSlot: () => mode.tasks.some(task => task.status !== 'deleted') - ?
    Tasks
    - : mode.failure === undefined ? null :
    {mode.failure}
    , - } - const view = render() - expect(screen.queryByRole('button')).toBeNull() - mode.tasks = [{ - id: 'task-1' as TeamTaskId, revision: 1, subject: 'Plan work', description: 'Prepare tasks before spawning workers', - status: 'pending', blockedBy: [], writeScopes: [], ready: true, writeScopeWarnings: [], - }] - view.rerender() - fireEvent.click(screen.getByRole('button', { name: '0 个子智能体' })) - const tree = screen.getByRole('tree') - const board = screen.getByRole('region', { name: 'Shared tasks' }) - expect(tree.compareDocumentPosition(board) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - expect(screen.getByRole('heading', { name: zh['section.title'] })).toBeTruthy() - expect(screen.getByText(zh['section.empty'])).toBeTruthy() - expect(screen.getAllByRole('dialog')).toHaveLength(1) - mode.tasks = [] - view.rerender() - expect(screen.queryByRole('dialog')).toBeNull() - expect(screen.queryByRole('button')).toBeNull() - mode.tasks = [{ ...sharedTask, status: 'deleted' }] - view.rerender() - expect(screen.queryByRole('button')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - mode.tasks = [] - mode.failure = 'Invalid task record' - view.rerender() - fireEvent.click(screen.getByRole('button', { name: '0 个子智能体' })) - expect(screen.getByRole('dialog')).toBeTruthy() - expect(screen.queryByRole('heading')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - expect(document.querySelector('[data-subagent-section-header]')).toBeNull() - view.rerender( select(false)} />) - expect(screen.queryByRole('button')).toBeNull() - mode.enabled = false - view.rerender() - expect(screen.queryByRole('dialog')).toBeNull() - expect(screen.queryByRole('button')).toBeNull() - }) - - it.each([false, true])('keeps child navigation without reading or rendering a task board (listed: %s)', (listed) => { - const input = props(catalog({ team: sharedTeam }), {}, listed ? { - [CHILD]: { ...summary(CHILD, 1), origin: 'subagent', parentId: PARENT }, - } : {}, { parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }) - const readProjection = vi.fn((): never => { throw new Error('child task-board projection read') }) - const readFooter = vi.fn((): never => { throw new Error('child footer subscription') }) - const renderFooter = vi.fn(() =>
    Tasks
    ) - render(<> - - - ) - fireEvent.click(screen.getByRole('button', { name: /切换子智能体/u })) - expect(screen.getByRole('tree')).toBeTruthy() - expect(screen.queryByRole('region', { name: 'Shared tasks' })).toBeNull() - expect(screen.queryByRole('heading')).toBeNull() - expect(screen.queryByText(zh['section.empty'])).toBeNull() - expect(document.querySelector('[data-subagent-section-header]')).toBeNull() - expect(readProjection).not.toHaveBeenCalled() - expect(readFooter).not.toHaveBeenCalled() - expect(renderFooter).not.toHaveBeenCalled() - }) - - it('leaves task-board keys alone and dismisses the shared panel from outside focus', () => { + it('leaves Escape from outside focus alone', () => { const input = props(catalog()) - render(<>