diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts index 56dfb22620..703c4ff272 100644 --- a/apps/web/tests/subagent-conversation.e2e.ts +++ b/apps/web/tests/subagent-conversation.e2e.ts @@ -21,7 +21,7 @@ import { webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { - connectFreshWorkspace, dismissSessionPanel, newEnglishPage, pinBrowserClock, pinHostClock, saveFailureShot, + connectFreshWorkspace, dismissSessionPanel, foldControlLayout, newEnglishPage, pinBrowserClock, pinHostClock, saveFailureShot, sessionPanelToggle, showSessionPanel, writeComposerDraft, } from './support.ts' import { brandString } from '@deepseek-ai/dsh-brand' @@ -1002,7 +1002,54 @@ describe('web e2e: persisted subagent conversation and human continuation', () = await page.keyboard.press('Escape') }) - + it('holds back the subagents past five behind the fold control and keeps the choice while the panel is hidden', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-fold')) + const parent = scaffold.ctx.agents.get(parentId) + if (parent === undefined) throw new Error('fold fixture requires the live parent') + await page.getByRole('tree', { name: 'Sessions' }) + .getByRole('treeitem', { name: /Ask a research subagent to/ }).click() + // Six catalog-only members, each created after every row so far: the Client holds no summary for them, + // so they sort by when the parent created them, the latest first. + const createdAfter = Date.now() + 60_000 + for (let index = 0; index < 6; index++) { + parent.session.append('subagent/catalog', { + version: 0, + childId: brandString(`fold-member-${String(index)}`), + childCreatedAt: createdAfter + index, + mode: 'one-shot', + label: `fold member ${String(index)}`, + }) + } + const section = await showSubagentsSection(page) + const rows = section.getByRole('treeitem') + const fold = section.locator('[data-session-panel-row="fold"]') + const labels = async (): Promise => (await rows.evaluateAll(items => items.map(item => item.getAttribute('aria-label') ?? ''))) + .map(label => /^fold member \d/.exec(label)?.[0] ?? 'earlier') + // Eight members: the five created last show, the latest first, and the fold control holds back three. + await expect.poll(labels, { timeout: 15_000 }) + .toEqual(['fold member 5', 'fold member 4', 'fold member 3', 'fold member 2', 'fold member 1']) + expect(await fold.textContent()).toBe('Show 3 more') + // The title counts every member, shown or held back. + expect(await section.getByRole('heading', { level: 2 }).locator('..').textContent()).toBe('Subagents1 completed\u2002·\u20027 not running') + // The control follows the tree, at the row height, with its chevron under the state marks and its text under the names. + expect(await section.getByRole('tree').locator('[data-session-panel-row="fold"]').count()).toBe(0) + expect(await foldControlLayout(fold, rows.first(), '[class*="content"] > span')) + .toEqual({ heights: [28, 28], chevronOffset: 0, textOffset: 0, fontSize: '12px', expanded: 'false' }) + await section.getByRole('button', { name: 'Show 3 more (subagents)', exact: true }).click() + await expect.poll(labels).toEqual([ + 'fold member 5', 'fold member 4', 'fold member 3', 'fold member 2', 'fold member 1', 'fold member 0', 'earlier', 'earlier', + ]) + const less = section.getByRole('button', { name: 'Show less (subagents)', exact: true }) + expect([await less.textContent(), await less.getAttribute('aria-expanded')]).toEqual(['Show less', 'true']) + // The choice is the Session's: it holds while the panel is hidden. + await dismissSessionPanel(page) + await showSubagentsSection(page) + await expect.poll(() => rows.count()).toBe(8) + await less.click() + await expect.poll(() => rows.count()).toBe(5) + expect(tripwire.pageErrors).toEqual([]) + await dismissSessionPanel(page) + }) }) describe('web e2e: migration-required subagent catalog', () => { diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml index f1d666aca5..855eca71ba 100644 --- a/packages/client/ui-subagent/README.i18n.yaml +++ b/packages/client/ui-subagent/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-subagent/use-this-package: - en: 49aa081e1dbae290 - zh: 1493da9b1ecb49ae + en: 77677cfa89b26de8 + zh: 83909430c95f3a6b /deepseek-ai-dsh-client-ui-subagent/use-this-package/browsing-the-tree: en: da87d582146106c4 zh: f640b3a3fcc11209 diff --git a/packages/client/ui-subagent/README.md b/packages/client/ui-subagent/README.md index a3aedb7b7b..e1a6e31218 100644 --- a/packages/client/ui-subagent/README.md +++ b/packages/client/ui-subagent/README.md @@ -29,7 +29,7 @@ The session header uses the session title for ordinary breadcrumbs. Subagent bre 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. -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 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 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. Breadcrumb switcher menus show navigation only. diff --git a/packages/client/ui-subagent/README.zh.md b/packages/client/ui-subagent/README.zh.md index 7516bc8031..eaf55b25f9 100644 --- a/packages/client/ui-subagent/README.zh.md +++ b/packages/client/ui-subagent/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" 本包注册 `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 与宽度控制。 -分栏的标题控件(`conversation.session.panel.section.actions`,键为 `subagents`)显示直接成员进度:依次为已完成、进行中、未运行和外部任务数量;省略零值,分隔符与输入区任务列表一致。外部任务不计入运行中或已完成数量。会话没有子智能体且目录读取未失败时,分栏连同标题一起隐藏。直接子智能体运行中且面板未显示时,面板开关上的蓝点(`conversation.session.panel.indicator`)会提示这一状态,并向辅助技术说明数量;外部任务不计入。会话面板负责分栏滚动,目录树不单独滚动。面包屑切换器菜单宽度为 360px,外层内边距为 6px,并受布局视口可用宽度约束,仅菜单本身滚动。在兼容 WebKit 的浏览器中,其原生 5px 滚动条位于右侧 6px 内边距内,轨道两端内缩,并保留稳定的滚动条空间,使内容在需要滚动时保持原有宽度。其他浏览器保留标准原生滚动条。 +分栏的标题控件(`conversation.session.panel.section.actions`,键为 `subagents`)显示直接成员进度:依次为已完成、进行中、未运行和外部任务数量;省略零值,分隔符与输入区任务列表一致。外部任务不计入运行中或已完成数量。分栏把运行中的子智能体排在最前,最近开始的在前,然后是其余的,最近更新的在前。它只显示五行,然后是会话面板的收起控件「显示其余 {count} 个」,点击后显示其余的行并变为「收起」;只有能收起两行及以上时列表才收起,这个选择在 Session 内保持,隐藏后再次显示面板也不变;展开某个分支后,该分支自己的行全部显示。会话没有子智能体且目录读取未失败时,分栏连同标题一起隐藏。直接子智能体运行中且面板未显示时,面板开关上的蓝点(`conversation.session.panel.indicator`)会提示这一状态,并向辅助技术说明数量;外部任务不计入。会话面板负责分栏滚动,目录树不单独滚动。面包屑切换器菜单宽度为 360px,外层内边距为 6px,并受布局视口可用宽度约束,仅菜单本身滚动。在兼容 WebKit 的浏览器中,其原生 5px 滚动条位于右侧 6px 内边距内,轨道两端内缩,并保留稳定的滚动条空间,使内容在需要滚动时保持原有宽度。其他浏览器保留标准原生滚动条。 面包屑切换器菜单只显示导航。 diff --git a/packages/client/ui-subagent/package.json b/packages/client/ui-subagent/package.json index 0d3da2b07a..0f3ac4e008 100644 --- a/packages/client/ui-subagent/package.json +++ b/packages/client/ui-subagent/package.json @@ -58,6 +58,7 @@ "@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:*", diff --git a/packages/client/ui-subagent/src/client/SubagentsSection.tsx b/packages/client/ui-subagent/src/client/SubagentsSection.tsx index 6bff1d011f..ddf3f8866a 100644 --- a/packages/client/ui-subagent/src/client/SubagentsSection.tsx +++ b/packages/client/ui-subagent/src/client/SubagentsSection.tsx @@ -1,20 +1,28 @@ /** Session panel section listing the current Session's subagents. */ import { useMemo } from 'react' import { HoverCardGroup } from '@deepseek-ai/dsh-client-ui-primitives' -import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { InjectFace, PropsLocale, PropsRenderFactories, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' import type { NS } from './locales.ts' import type {} from '@deepseek-ai/dsh-client-ui-session-panel/client' import { - CatalogTree, deriveCatalogs, levelPreparer, progressOf, type Catalogs, type SubagentCatalogInjected, + 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 @@ -44,28 +52,70 @@ function useCatalogs({ useSessions, useSessionStatus }: Pick, +): 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, openChild, openChildAside, prepareCatalog, t, + 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]) - if (catalog === undefined || (catalog.state !== 'error' && catalog.entries.length === 0)) return null + 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) }, + })}
) } diff --git a/packages/client/ui-subagent/src/client/index.ts b/packages/client/ui-subagent/src/client/index.ts index 793beb4b90..9ab568f2ba 100644 --- a/packages/client/ui-subagent/src/client/index.ts +++ b/packages/client/ui-subagent/src/client/index.ts @@ -6,6 +6,7 @@ import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation 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' @@ -104,6 +105,7 @@ export function apply(ctx: ClientContext): void { order: 200, label: () => t('section.title'), locale: NS, + store: createSubagentsSectionStore(), inject: catalogActions, }, SubagentsSection) yield ctx.slots.register({ diff --git a/packages/client/ui-subagent/src/client/locales.ts b/packages/client/ui-subagent/src/client/locales.ts index 747962ae15..0e1c80e59b 100644 --- a/packages/client/ui-subagent/src/client/locales.ts +++ b/packages/client/ui-subagent/src/client/locales.ts @@ -11,6 +11,9 @@ export const zh = { '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}秒', @@ -58,6 +61,9 @@ export const en: Record = { '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', @@ -108,6 +114,9 @@ export const ja = { '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}秒', @@ -155,6 +164,9 @@ export const es = { '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', @@ -202,6 +214,9 @@ export const fr = { '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', @@ -249,6 +264,9 @@ export const de = { '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', @@ -296,6 +314,9 @@ export const ru = { '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', @@ -343,6 +364,9 @@ export const pt = { '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', 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/conversation-ui.client.spec.tsx b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx index 98e1d52bc3..f342284d62 100644 --- a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx +++ b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx @@ -2,7 +2,8 @@ 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' @@ -15,6 +16,7 @@ import { 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' afterEach(() => { @@ -29,7 +31,10 @@ const CHILD = 'child' as SessionId const GRANDCHILD = 'grandchild' as SessionId const t: SubagentHeaderLineageProps['t'] = makeTranslate(zh) -type HeaderCatalogProps = SubagentHeaderLineageProps & { dismissOverlay?: () => void } +/** 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' } @@ -195,18 +200,33 @@ async function hoverDetailsOf(row: HTMLElement): Promise { * (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(props: HeaderCatalogProps) { - const sectionProps: SubagentsSectionProps = { - ...props, sessionId: props.lineageSessionId, presentation: 'docked', dismissOverlay: props.dismissOverlay ?? vi.fn(), - } +function HeaderCatalog({ store, ...props }: HeaderCatalogProps) { return ( <> - +
) } +/** + * The Session panel's fold control Factory as these suites render it: a button with its state, name, and label. + * ui-session-panel's own suite owns the control's markup. + */ +function renderFold(_name: string, input: { expanded: boolean; label: string; name: string; onToggle: () => void }) { + 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: renderFold, + } as SubagentsSectionProps + return +} + describe('SubagentHeaderLineage', () => { it('omits section headings from a catalog of members', () => { @@ -925,6 +945,8 @@ describe('SubagentsSection', () => { })) as Record const input = props(catalog({ entries }), {}, summaries) render() + // Nine rows fold to five; this case reads every row's measures. + fireEvent.click(document.querySelector('[data-fold]') as HTMLElement) const runningRow = screen.getByRole('treeitem', { name: /running.*4\.6K tok · 1分10秒/ }) // The row keeps only the compact duration; the tokens and exact duration show in its hover card. @@ -1337,11 +1359,106 @@ describe('SubagentsSection', () => { expect(screen.queryByRole('treeitem', { name: /great/ })).toBeNull() }) + /** A catalog entry named by its id. */ + const member = (id: string, activity: 'running' | 'inactive' = 'inactive'): CatalogFixtureEntry => + ({ id: id as SessionId, mode: 'continuable', label: id, activity }) + /** Summaries that give a running subagent the start of its open turn and another one its last update. */ + const timed = (rows: Readonly>): Record => + Object.fromEntries(Object.entries(rows).map(([id, { running, updated }]) => [id, { + ...summary(id as SessionId, updated ?? 0), + running: running !== undefined, + ...running === undefined + ? {} + : { projectionValues: { subagentTiming: { settledMs: 0, active: { since: running, through: running } } } }, + }])) + /** The rows' names in display order; a row's accessible name starts with its label. */ + const shownRows = (): string[] => screen.getAllByRole('treeitem').map(row => (row.getAttribute('aria-label') ?? '').split(' ')[0] ?? '') + const fold = (): HTMLElement | null => document.querySelector('[data-fold]') + + it('lists running subagents first by latest start, then the others by latest update, and a subagent without either by its creation', () => { + const entries = [ + member('old-done'), member('early-run', 'running'), member('new-done'), member('late-run', 'running'), member('unlisted'), member('unknown'), + ] + render() + // `unlisted` has no update time and `unknown` no summary: both sort by the fixture's creation time, 1, in catalog order. + expect(shownRows()).toEqual(['late-run', 'early-run', 'new-done', 'old-done', 'unlisted', 'unknown']) + expect(fold()).toBeNull() + }) + + it('sorts a running subagent whose turn timing is not read yet by its creation', () => { + const entries = [member('timed', 'running'), member('untimed', 'running')] + render() + // `untimed` falls back to the fixture's creation time, 1, which is later than the other row's turn start. + expect(shownRows()).toEqual(['untimed', 'timed']) + }) + + it('keeps catalog order among rows that tie', () => { + const entries = [member('a'), member('b', 'running'), member('c'), member('d', 'running')] + const summaries = timed({ a: { updated: 7 }, b: { running: 3 }, c: { updated: 7 }, d: { running: 3 } }) + render() + expect(shownRows()).toEqual(['b', 'd', 'a', 'c']) + }) + + it('shows six rows in full and holds two back from seven, behind a fold control that shows them and folds again', () => { + const six = ['a', 'b', 'c', 'd', 'e', 'f'].map(id => member(id)) + const full = render() + expect(shownRows()).toHaveLength(6) + expect(fold()).toBeNull() + full.unmount() + render() + expect(shownRows()).toEqual(['a', 'b', 'c', 'd', 'e']) + const control = fold() as HTMLElement + expect([control.textContent, control.getAttribute('aria-label'), control.getAttribute('aria-expanded')]) + .toEqual(['显示其余 2 个', '显示其余 2 个(子智能体)', 'false']) + // The control follows the tree instead of joining it, so the tree holds only its rows. + expect(screen.getByRole('tree').contains(control)).toBe(false) + fireEvent.click(control) + expect(shownRows()).toEqual(['a', 'b', 'c', 'd', 'e', 'f', 'g']) + expect([fold()?.textContent, fold()?.getAttribute('aria-label'), fold()?.getAttribute('aria-expanded')]) + .toEqual(['收起', '收起(子智能体)', 'true']) + fireEvent.click(fold() as HTMLElement) + expect(shownRows()).toHaveLength(5) + }) + + it('holds back running subagents too once more than five run, counting every row behind the control', () => { + const entries = [...Array.from({ length: 8 }, (_, index) => member(`run-${index}`, 'running')), member('done-0'), member('done-1')] + render( + [entry.id, entry.activity === 'running' ? { running: index } : { updated: index }]))))} />) + expect(shownRows()).toEqual(['run-7', 'run-6', 'run-5', 'run-4', 'run-3']) + expect(fold()?.textContent).toBe('显示其余 5 个') + }) + + it('keeps the fold in the Session store while the section is unmounted', () => { + const store = createSubagentsSectionStore().create() + const entries = Array.from({ length: 9 }, (_, index) => member(`s-${index}`)) + const first = render() + fireEvent.click(fold() as HTMLElement) + expect(store.getSnapshot()).toEqual({ unfolded: true }) + first.unmount() + render() + expect(shownRows()).toHaveLength(9) + 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('renders nothing without subagents or a failed read, and keeps a failed read reachable', () => { const empty = render() expect(document.querySelector('[data-subagents-section]')).toBeNull() empty.unmount() - const absent = render() + const absent = render(
) expect(absent.container.innerHTML).toBe('') absent.unmount() render() diff --git a/packages/client/ui-subagent/tsconfig.json b/packages/client/ui-subagent/tsconfig.json index 38a81d0416..0efb4d9c5e 100644 --- a/packages/client/ui-subagent/tsconfig.json +++ b/packages/client/ui-subagent/tsconfig.json @@ -32,6 +32,9 @@ { "path": "../resources" }, + { + "path": "../store" + }, { "path": "../ui-chat/tsconfig.client.json" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 93002959b7..ff348574c4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7012,6 +7012,9 @@ importers: '@deepseek-ai/dsh-client-resources': specifier: workspace:* version: link:../resources + '@deepseek-ai/dsh-client-store': + specifier: workspace:* + version: link:../store '@deepseek-ai/dsh-client-test-runtime': specifier: workspace:* version: link:../../test-support/client-runtime