Merge pull request #7932 from deepseek-harness/fix/subagent-catalog-explicit-expand

fix(ui-subagent): 显式展开时补读一层子目录
This commit is contained in:
Dudu-0223 authored and GitHub committed 2026-11-07 14:49:27 +08:00
commit 1f00b4defc
16 files changed
+524 -159

No files matched your search

@@ -9,8 +9,8 @@
en: ab63c8127d68d294
zh: d3f99489c96ff1d4
/agent-note-open-the-session-when-migration-is-required/decision:
en: 32627d744a6e7410
zh: 2836a95ee5390111
en: 310ff84cece51901
zh: a9a29e3ba30e03a8
/agent-note-open-the-session-when-migration-is-required/alternatives-considered:
en: baea781018a49252
zh: bcc452029bf229fd
@@ -18,7 +18,7 @@ Other fork callers omit that option and allow automatic migration.
The `formatStatus` returned by `stat` carries the migration library's existing classification; `header` remains the current logical format. It describes the stored format, not migration-task progress or prepared in-memory history.
When migration is required and `subagentCatalog` is absent, Web marks the Session's row “Migration required” and keeps its history-opening actions without descendant expansion or changing its subagent mode. Opening the Session supplies its catalog through history and control projections. Available catalogs remain usable, including empty catalogs. Session-list lineage resolves navigation addresses, not missing catalog membership. Ordinary loading, cancellation, and storage errors do not become this migration branch.
When migration is required and `subagentCatalog` is absent, Web keeps the Session row's history-opening actions without a format notice, descendant expansion, or changing its subagent mode. Opening the Session supplies its catalog through history and control projections. Available catalogs remain usable, including empty catalogs. Session-list lineage resolves navigation addresses, not missing catalog membership. Ordinary loading, cancellation, and storage errors do not become this migration branch.
Create/adopt, full-text search, and ordinary history opening allow automatic migration.
@@ -18,7 +18,7 @@ WorkspaceBrowser 行菜单的 fork 请求携带 `allowMigration: false`,由 Ho
`stat` 返回的 `formatStatus` 携带迁移库已有的分类;`header` 仍是当前逻辑格式。它描述存储格式,不描述迁移任务进度或内存准备缓存。
在需要迁移且缺少 `subagentCatalog` 时,Web 将该会话行标为“需要迁移”,保留打开历史的操作,但不能展开下级,也不改变子会话的 mode。打开会话后,历史与 control 投影提供其目录。已有目录仍可使用,包括空目录。会话列表的谱系用于解析导航地址,不用于补齐缺失的目录成员。普通加载、取消和存储错误不转换成这一迁移分支。
在需要迁移且缺少 `subagentCatalog` 时,Web 保留该会话行打开历史的操作,不显示格式提示,不展开下级,也不改变子会话的 mode。打开会话后,历史与 control 投影提供其目录。已有目录仍可使用,包括空目录。会话列表的谱系用于解析导航地址,不用于补齐缺失的目录成员。普通加载、取消和存储错误不转换成这一迁移分支。
create/adopt、全文搜索和普通历史打开允许自动迁移。
@@ -1,13 +1,13 @@
# Before opening the child
- tree "Subagent sessions":
- treeitem "historical researcher migration-catalog-child · Migration required · not running" [level=1]:
- text: historical researcher migration-catalog-child Migration required
- treeitem "historical researcher migration-catalog-child · continuable · not running" [level=1]:
- text: historical researcher migration-catalog-child
- button "Open historical researcher in sidebar"
# After opening the child
- tree "Subagent sessions":
- treeitem "historical editor migration-catalog-grandchild · Migration required · not running" [level=1]:
- text: historical editor migration-catalog-grandchild Migration required
- treeitem "historical editor migration-catalog-grandchild · continuable · not running" [level=1]:
- text: historical editor migration-catalog-grandchild
- button "Open historical editor in sidebar"
+8 -4
View File
@@ -547,10 +547,14 @@ it.skipIf(MODE === 'record')('automatically shows a numbered PR when gh JSON omi
await change.getByText('等待评审 · 1 条未解决讨论', { exact: true }).waitFor()
await compareOrRefreshGolden(join(EXPECTED, 'reference.expected.md'),
await captureStableAria(page, `[data-forge-change="${PULL}"]`, scaffold.workspaceCwd), MODE)
expect(events.flatMap((event) => {
const record = pluginRecordOf(event)
return record?.type === 'plugin:forge-session/binding' ? [record.data] : []
})).toEqual([{ action: 'reference', url: PULL }])
await expect.poll(async () => {
await scaffold.ctx.sessionPersistence.flush()
const boundEvents = await readPersistedEvents(scaffold, sessionId)
return boundEvents.flatMap((event) => {
const record = pluginRecordOf(event)
return record?.type === 'plugin:forge-session/binding' ? [record.data] : []
})
}).toEqual([{ action: 'reference', url: PULL }])
const calls = (await readFile(join(project, '.fixture-bin', 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])
expect(calls).toContainEqual(['pr', 'view', '7', '--repo', 'octo/demo', '--json', 'url'])
expect(tripwire.pageErrors).toEqual([])
+97 -18
View File
@@ -365,6 +365,61 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
if (failures.length > 1) throw new AggregateError(failures, 'subagent Web teardown failed')
})
it('retries a failed cold catalog and discovers descendants without reopening the menu', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-unread-catalog'))
const reads = apiCalls.filter(path => path === '/api/session/projections').length
const observe = vi.spyOn(scaffold.ctx.sessionQuery, 'observeSession')
const projections = vi.spyOn(scaffold.ctx.sessionController, 'projections')
try {
const trigger = page.getByRole('button', { name: '2 subagents', exact: true })
await page.locator('[data-composer-input]').first().hover()
await trigger.hover()
const tree = page.getByRole('tree', { name: 'Subagent sessions' })
const child = tree.getByRole('treeitem', { name: new RegExp(LABEL) })
await child.waitFor()
expect(await child.getAttribute('aria-expanded')).toBeNull()
expect(await tree.getByRole('button', { name: /^(Expand|Collapse) /u }).count()).toBe(0)
expect(await tree.getByText(/Loading subagents|unknown/u).count()).toBe(0)
expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(reads)
expect(observe).not.toHaveBeenCalled()
const parentUrl = page.url()
await page.route('**/api/session/projections', route => route.abort('failed'), { times: 1 })
await trigger.click()
const retry = tree.getByRole('button', { name: 'Retry', exact: true })
await retry.waitFor()
expect(await tree.getByRole('button', { name: /^(Expand|Collapse) /u }).count()).toBe(0)
expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(reads + 1)
expect(projections).not.toHaveBeenCalled()
await retry.click()
await retry.waitFor({ state: 'detached' })
const expand = page.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true })
await expand.waitFor()
await expect.poll(() => projections.mock.calls.map(([request]) => request.sessionId)).toEqual([parentId, childId, oneShotId])
expect(observe.mock.calls.some(([id]) => id === grandchildId)).toBe(false)
const lastRead = page.waitForResponse('**/api/session/projections')
await expand.click()
await (await lastRead).finished()
await expect.poll(() => projections.mock.calls.map(([request]) => request.sessionId))
.toEqual([parentId, childId, oneShotId, grandchildId])
const grandchild = tree.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) })
await grandchild.waitFor()
expect(await grandchild.getAttribute('aria-expanded')).toBeNull()
await compareOrRefreshGolden(
TREE_EXPECTED,
await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd), MODE,
)
expect(page.url()).toBe(parentUrl)
expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined()
await page.keyboard.press('Escape')
await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' })
} finally {
await page.unroute('**/api/session/projections')
observe.mockRestore()
projections.mockRestore()
}
})
it('lists direct subagents by label in the reference menu', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-reference-title'))
expect(liveReferenceOptions.some(text => text.includes(LABEL))).toBe(true)
@@ -424,7 +479,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
}
expect(await row.getAttribute('aria-label')).toContain(`${LABEL} ${CHILD_NAME} `)
expect(await row.getByRole('button', { name: /description/u }).count()).toBe(0)
expect(await row.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).count()).toBe(1)
await row.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).waitFor()
expect(await row.getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).count()).toBe(1)
expect(page.url()).toBe(originalUrl)
expect(await page.getByRole('tooltip').count()).toBe(0)
@@ -438,9 +493,34 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
}
})
it('recovers a current-format cold child catalog cache miss without activating either level', async () => {
it('expands locally available cold catalogs without requesting or activating either level', async () => {
onTestFailed(() => saveFailureShot(page, 'screenshots/non-migrating-session-reads/web-e2e-subagent-tree'))
await page.getByRole('button', { name: '2 subagents' }).hover()
const warningStart = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
const trigger = page.getByRole('button', { name: '2 subagents', exact: true })
await trigger.waitFor()
acknowledgeReloadConnectionLoss(tripwire, warningStart)
const siblingsRead = page.waitForResponse((response) => {
if (!response.url().endsWith('/api/session/projections')) return false
const body = response.request().postDataJSON() as { payload: { args: { request: { sessionId: SessionId } } } }
return body.payload.args.request.sessionId === oneShotId
})
await trigger.click()
await (await siblingsRead).finished()
const expand = page.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true })
await expand.waitFor()
const descendantsRead = page.waitForResponse((response) => {
if (!response.url().endsWith('/api/session/projections')) return false
const body = response.request().postDataJSON() as { payload: { args: { request: { sessionId: SessionId } } } }
return body.payload.args.request.sessionId === grandchildId
})
await expand.click()
await (await descendantsRead).finished()
await page.keyboard.press('Escape')
await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' })
const catalogReads = apiCalls.filter(path => path === '/api/session/projections').length
await page.locator('[data-composer-input]').first().hover()
await trigger.hover()
const catalogTree = page.getByRole('tree', { name: 'Subagent sessions' })
expect(await catalogTree.evaluate((element) => {
const rect = element.getBoundingClientRect()
@@ -453,6 +533,10 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
name: `Expand ${ONE_SHOT_LABEL} descendants`,
})
expect(await oneShotDisclosure.count()).toBe(0)
await compareOrRefreshGolden(
fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/disclosures.expected.md', import.meta.url)),
await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd), MODE,
)
const oneShotRow = page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) })
expect(await oneShotRow.locator('[data-state="done"]').count()).toBe(1)
expect(await oneShotRow.getByText('~6mo 12d', { exact: true }).count()).toBe(1)
@@ -501,18 +585,13 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
expect(await page.getByText(PARENT_PROMPT, { exact: true }).isVisible()).toBe(true)
expect(await page.locator('[data-sidebar-chat]').count()).toBe(0)
}
const observe = vi.spyOn(scaffold.ctx.sessionQuery, 'observeSession')
try {
const projections = page.waitForResponse(response => new URL(response.url()).pathname === '/api/session/projections')
await clickDisclosureGutter(3)
await projections
await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ timeout: 15_000 })
expect(await sectionHeader.count()).toBe(0)
expect(observe.mock.calls.some(([id]) => id === childId)).toBe(true)
expect(observe.mock.calls.some(([id]) => id === grandchildId)).toBe(false)
} finally {
observe.mockRestore()
}
await clickDisclosureGutter(3)
const grandchildRow = page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) })
await grandchildRow.waitFor({ timeout: 15_000 })
expect(await catalogTree.getByText('Loading subagents…', { exact: true }).count()).toBe(0)
expect(await grandchildRow.getAttribute('aria-expanded')).toBeNull()
expect(await grandchildRow.getByRole('button', { name: `Expand ${NESTED_LABEL} descendants` }).count()).toBe(0)
expect(await sectionHeader.count()).toBe(0)
await clickDisclosureGutter(26)
await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ state: 'detached' })
expect(await childRow.getAttribute('aria-expanded')).toBe('false')
@@ -571,6 +650,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
scaffold.workspaceCwd,
)
await compareOrRefreshGolden(TREE_EXPECTED, snapshot, MODE)
expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(catalogReads)
await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).getByText(grandchildId, { exact: true }).click()
await page.getByText(NESTED_PROMPT).waitFor()
const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
@@ -994,10 +1074,9 @@ describe('web e2e: migration-required subagent catalog', () => {
const tree = page.getByRole('tree', { name: 'Subagent sessions' })
const childRow = tree.getByRole('treeitem', { name: new RegExp(childLabel) })
await childRow.waitFor()
await expect.poll(() => childRow.textContent()).toContain('Migration required')
await expect.poll(() => childRow.getByRole('button', { name: `Expand ${childLabel} descendants`, exact: true }).count()).toBe(0)
expect(await childRow.getAttribute('aria-expanded')).toBeNull()
expect(await childRow.textContent()).toContain('Migration required')
expect(await childRow.textContent()).not.toContain('Migration required')
expect(await childRow.textContent()).not.toContain('unknown mode')
expect(await childRow.getByRole('button', { name: `Open ${childLabel} in sidebar`, exact: true }).isEnabled()).toBe(true)
expect(await tree.getByRole('treeitem').count()).toBe(1)
@@ -1015,7 +1094,7 @@ describe('web e2e: migration-required subagent catalog', () => {
await page.getByRole('button', { name: '1 subagent', exact: true }).hover()
const grandchildRow = tree.getByRole('treeitem', { name: new RegExp(grandchildLabel) })
await grandchildRow.waitFor()
expect(await grandchildRow.textContent()).toContain('Migration required')
expect(await grandchildRow.textContent()).not.toContain('Migration required')
expect(await grandchildRow.getAttribute('aria-expanded')).toBeNull()
expect(await grandchildRow.getByRole('button', { name: `Expand ${grandchildLabel} descendants`, exact: true }).count()).toBe(0)
expect(projections).not.toHaveBeenCalled()
+8 -8
View File
@@ -15,11 +15,11 @@
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
/deepseek-ai-dsh-client-ui-subagent/use-this-package:
en: bc1c5164849937a8
zh: e03adf54d2d5a668
en: c7a9485c0cdcd9de
zh: 903ad54e44d79eae
/deepseek-ai-dsh-client-ui-subagent/use-this-package/browsing-the-tree:
en: 5ea28139189887e9
zh: f5a51f041c39b0fa
en: 35e983f0276188d0
zh: df588dc1523031da
/deepseek-ai-dsh-client-ui-subagent/use-this-package/continuing-a-conversation:
en: e4ec261d3b122eb5
zh: 320bb2efc93dccdc
@@ -30,8 +30,8 @@
en: c158f12dcaed87b7
zh: e5d315e7b1fb4fa9
/deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/catalog-derivation:
en: 45772c086f8a55f1
zh: c80584bf49897b8f
en: 3c06acc93d7d4d59
zh: b967155aec39df0c
/deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/duration-completion-and-tokens:
en: dcbc58d4cad47fa8
zh: e962a8cbdfd4a914
@@ -57,8 +57,8 @@
en: de2762a99572475f
zh: 9b41107ad14ebf8a
/deepseek-ai-dsh-client-ui-subagent/known-limitations-and-deferred-work:
en: ee310ff3cd487639
zh: 23793aa1c28a23af
en: ea983111988e4b9b
zh: c0ed7a583d2cad52
/deepseek-ai-dsh-client-ui-subagent/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: 3bb0c20c93f16f98
+6 -4
View File
@@ -25,7 +25,7 @@ Browse local subagent conversations and external tasks from the parent header. L
<a id="use-this-package"></a>
## 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 loads nested catalogs only when their rows expand. 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. 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.
This package registers the `dsh-resource://subagentchat/session/<child>?parent=<parent>&mode=<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.
@@ -39,7 +39,7 @@ The wide root count trigger shows a 14px Users icon in its 14px slot when no chi
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.
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. A row is a known leaf only after its own catalog loads empty.
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.
### Continuing a conversation
@@ -61,11 +61,11 @@ The [subagent runtime](../../subagent/subagent/README.md) owns continuation and
### Catalog derivation
The header lineage renderer reads `projectionsBySession` through the standard `useSessions` hook. The renderer selects `subagentCatalog` from each Session’s shared values for membership, disclosure, and counts. Activity prefers the unified UI status and falls back to Session summaries; summaries supply titles and usage. Expanding a row reads its target's projections, including ordinary cold history. A list row with `formatStatus: migration-required` displays “Migration required” before expansion and keeps its history-opening actions without descendant expansion or changing its subagent mode; a projection read requiring migration without a catalog supplies the same notice. Opening the Session supplies its catalog through history and control projections. Otherwise, an available catalog remains usable, including an explicit empty catalog. Live projection frames update every loaded level without menu subscriptions or repeated membership queries. Other rows remain expandable while their catalogs are absent, loading, or failed, and become known leaves after ready empty catalogs. External rows are always leaves and do not load child Sessions.
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.
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.
Opening a catalog dropdown does not request its root catalog. Child-catalog expansion and failed-read retries call `refreshProjection`; shared projection-value changes update the display automatically.
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.
Breadcrumb addresses derive from the Provider-bound Session address, loaded parent catalogs, or already-listed subagent lineage, including never-selected ancestors.
@@ -123,6 +123,8 @@ Append-only. This package never edits earlier request tokens.
These limits define what the catalog can show and what `@` references mean; they are current package constraints.
- **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.
- **`@` references remain display-title text** — duplicate or renamed labels are ambiguous, so they intentionally do not acquire continuation semantics.
<a id="dev-note"></a>
+6 -4
View File
@@ -25,7 +25,7 @@ kind: "package-reference"
<a id="use-this-package"></a>
## 使用本包
会话页头的普通面包屑使用会话标题。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 行高。当会话的直接目录有子项或读取失败时,后代数量触发器渲染在页头操作区中预设标签之后,不带任何面包屑分隔符。目录缺席或为空时隐藏数量触发器,除非根 Session 已开启且可用的 Team 任务板有共享任务或任务记录错误。仅开启 Team 模式不会显示空入口。触发器打开该直接目录,以总数作为无障碍名称、运行数作为无障碍描述,并在用户显式打开时发现下一层目录。选择任意深度,即可用该子会话的确切 `{parentSessionId, childSessionId, mode}` 地址打开其对话;也可以使用非当前本地行的行尾箭头在右侧 Sidebar 打开同一地址,并在空间允许时优先使用独立分栏。
本包注册 `dsh-resource://subagentchat/session/<child>?parent=<parent>&mode=<mode>` 资源与 builtin Sidebar tab 类型。资源直接根据地址保留 child 的 `SessionReference`,不刷新 parent 目录,并在 tab 记录关闭时释放 reference。tab 通过 `sidebar.chat.conversation` 渲染共享 `conversation.content` Factory,把局部 View 固定为 Chat,并省略主 Conversation 的 Header 与宽度控制。
@@ -39,7 +39,7 @@ kind: "package-reference"
数量、负责人及侧边栏操作的工具提示在悬停 500ms 后显示。悬停文字可见的触发器 150ms 后打开目录;指针离开触发器和目录后,经过 120ms 关闭。点击后代数量触发器会打开并固定目录,或关闭已固定的目录。纯图标数量触发器不会因悬停而打开,包括等待悬停打开期间切换到窄布局的情况。点击可切换固定菜单的开关状态;ArrowDown 会打开并固定菜单,并将焦点移至首行。点击外部或按 Escape 可关闭已固定的菜单。点击会将焦点移入面板,此时 ArrowDown/Home 进入首个树行,ArrowUp/End 进入最后一个树行;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。只有一行自身的目录加载为空后,它才是已知叶子。
目录行在智能体名称上方显示创建描述,缺少创建描述时使用可用的 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 活动状态图标。读取失败时保留导航操作并提供重试。
### 续接对话
@@ -61,11 +61,11 @@ kind: "package-reference"
### 目录派生
页头谱系 renderer 通过标准 `useSessions` 钩子读取 `projectionsBySession`。renderer 从每个 Session 的共享值中选择 `subagentCatalog`,用于成员关系、展开控件与数量。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要提供标题与用量。展开行读取目标投影,包括普通冷历史。列表行的 `formatStatus` 为 `migration-required` 时,行在展开前即显示“需要迁移”,保留打开历史的操作,但不能展开下级,也不改变子会话的 mode;投影读取需要迁移且缺少目录时,也显示同一提示。打开会话后,历史与 control 投影提供其目录。其他情况下,已有目录仍可使用,包括显式空目录。实时 projection 帧更新所有已加载层级,无需菜单订阅或重复成员查询。其他行在目录缺席、加载中或失败时保持可展开,并在目录就绪且为空后成为已知叶子。外部行始终为叶子,不加载子 Session。
页头谱系 renderer 通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需每个菜单单独订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。渲染与悬停仅使用本地投影,不会请求缺失目录。尚未读取的空菜单显示“尚未加载子智能体”;仅请求进行中显示加载提示。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。
每个页头入口在树下方声明 footer 插槽。可选 UI 通过该插槽加入同一滚动容器;目录负责打开和关闭。CSS 锚点让面板跟随触发器,并按布局视口限制尺寸。浏览器缩放和平移时面板随页面移动,因此可以超出视觉视口。内部滚动、悬停行为、点击固定展开和焦点恢复保持独立。
打开目录下拉菜单不会请求其根目录。展开子节点目录或重试失败读取时调用 `refreshProjection`;共享投影值的变化会自动更新显示。
显式激活菜单、展开分支或重试失败读取时,`prepareCatalog` 读取当前目录及其直接子节点。点击祖先标题会导航到该 Session。Session 对象层合并重复读取,并在重连后刷新之前请求过的投影。
面包屑地址从 Provider 所绑定的 Session 地址、已加载的 parent 目录或已列出的 subagent 谱系推导,也包括从未选中过的祖先。
@@ -123,6 +123,8 @@ one-shot 和模式未知的 child 选用只读编辑器。可继续 child 经由
这些限制定义目录能显示什么、`@` 引用意味着什么;它们是当前包约束。
- **非完成的 inactive 结果仍合并显示**:目录能区分最近一次正常完成与其他 inactive 状态,但不区分失败、取消、拒绝、token 耗尽或尚无已结束轮次的 child;UI 不公开 Activation 身份,停止能力仅限编辑器上针对运行中可继续 child 的当前轮次 Stop。
- **祖先菜单的未缓存分支需要键盘激活**:悬停不读取,点击祖先标题会导航。聚焦标题后按 ArrowDown,可在不离开当前 Session 的情况下准备这一层。
- **单层发现会在中断后停止**:意外的读取拒绝会停止后续兄弟节点,并记录到控制台。重连可能在直接子节点读取前中断发现;需再次显式打开菜单来准备这一层。
- **`@` 引用仍是显示标题文本**:重复或改名后的 label 会有歧义,因此它们刻意不获得继续执行语义。
<a id="dev-note"></a>
@@ -350,8 +350,7 @@
}
.label,
.secondaryLabel,
.summary {
.secondaryLabel {
white-space: normal;
overflow-wrap: anywhere;
}
@@ -370,14 +369,10 @@
color: var(--dsw-alias-label-tertiary);
}
.summary,
.metrics {
color: var(--dsw-alias-label-tertiary);
font-size: 10px;
line-height: 15px;
}
.metrics {
display: grid;
grid-template-rows: 17px 15px;
flex: none;
@@ -455,10 +450,6 @@
height: 23px;
}
.children[aria-busy='true']::before {
content: none;
}
.children > .node::before {
top: 0;
bottom: 0;
@@ -19,7 +19,7 @@ import type {} from './slots.ts'
import css from './SubagentHeaderLineage.module.css'
type SubagentCatalogSnapshot = Omit<SessionProjectionSnapshot, 'values' | 'state'> & {
state: 'loading' | 'ready' | 'migration-required' | 'error'
state: 'idle' | 'loading' | 'ready' | 'migration-required' | 'error'
entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[]
}
type Catalogs = Readonly<Record<SessionId, SubagentCatalogSnapshot>>
@@ -29,6 +29,8 @@ 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<void>
}
/** Root catalog actions and availability of its optional footer. */
@@ -203,9 +205,11 @@ function CatalogLoadingRows({ t }: { t: TranslateNS<typeof NS> }) {
return <div className={css.notice}>{t('loading.label')}</div>
}
/** A child becomes a known leaf only after its own authoritative catalog loads empty. */
function isKnownLeaf(catalog: SubagentCatalogSnapshot | undefined): boolean {
return catalog?.state === 'ready' && catalog.entries.length === 0
/** 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. */
@@ -252,12 +256,12 @@ function CatalogRows({
return () => { clearInterval(timer) }
}, [running])
const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0
const reserveDisclosure = catalog.entries.some(entry =>
entry.mode !== 'external' && !isKnownLeaf(catalogs[entry.id])
&& summaries[entry.id]?.formatStatus !== 'migration-required'
&& catalogs[entry.id]?.state !== 'migration-required')
const reserveDisclosure = catalog.entries.some(entry => canExpandCatalog(entry, catalogs, summaries))
return (
<>
{catalog.state === 'idle' && catalog.entries.length === 0 && (
<div className={css.notice}>{t('load.idle')}</div>
)}
{emptyLoading && (
<CatalogLoadingRows t={t} />
)}
@@ -278,13 +282,10 @@ function CatalogRows({
const external = entry.mode === 'external'
const childCatalog = catalogs[entry.id]
const isCurrent = entry.id === currentSessionId
const knownLeaf = external || isKnownLeaf(childCatalog)
const requiresOpening = summaries[entry.id]?.formatStatus === 'migration-required'
|| childCatalog?.state === 'migration-required'
const canExpand = !knownLeaf && !requiresOpening
const canExpand = canExpandCatalog(entry, catalogs, summaries)
const isExpanded = canExpand && expanded.has(entry.id)
const childLoading = childCatalog === undefined
|| (childCatalog.state === 'loading' && childCatalog.entries.length === 0)
const summary = summaries[entry.id]
const description = entry.label || summary?.title
const name = entryName(entry)
@@ -298,7 +299,7 @@ function CatalogRows({
: completed
? t('activity.completed')
: t('activity.inactive')
const secondary = [secondaryLabel, requiresOpening ? t('catalog.migrationRequired') : mode, activity]
const secondary = [secondaryLabel, mode, activity]
.filter(value => value !== undefined)
.join(' · ')
const totalTokens = tokenTotal(summary?.projectionValues?.tokenUsage)
@@ -385,7 +386,6 @@ function CatalogRows({
{secondaryLabel !== undefined && (
<span className={css.secondaryLabel}>{secondaryLabel}</span>
)}
{requiresOpening && <span className={css.summary}>{t('catalog.migrationRequired')}</span>}
</span>
{metrics !== '' && (
<span className={css.metrics}>
@@ -426,31 +426,35 @@ function CatalogRows({
)}
</div>
</div>
{isExpanded && (
{!isExpanded && !external && !requiresOpening && childCatalog?.state === 'error' && (
<div className={css.error} role="alert">
<span>{t('load.error')}</span>
<button type="button" className={css.refresh} onClick={() => { refreshProjection(entry.id) }}>
<IconRefreshOutlineRegular size={14} />
{t('retry')}
</button>
</div>
)}
{childCatalog !== undefined && isExpanded && (
<div
role="group"
className={css.children}
aria-busy={childLoading || undefined}
>
{childCatalog === undefined
? <CatalogLoadingRows t={t} />
: (
<CatalogRows
parentSessionId={entry.id}
currentSessionId={currentSessionId}
catalog={childCatalog}
catalogs={catalogs}
summaries={summaries}
expanded={expanded}
level={level + 1}
openChild={openChild}
openChildAside={openChildAside}
refreshProjection={refreshProjection}
toggleBranch={toggleBranch}
closeCatalog={closeCatalog}
t={t}
/>
)}
<CatalogRows
parentSessionId={entry.id}
currentSessionId={currentSessionId}
catalog={childCatalog}
catalogs={catalogs}
summaries={summaries}
expanded={expanded}
level={level + 1}
openChild={openChild}
openChildAside={openChildAside}
refreshProjection={refreshProjection}
toggleBranch={toggleBranch}
closeCatalog={closeCatalog}
t={t}
/>
</div>
)}
</div>
@@ -497,7 +501,7 @@ type CatalogDropdownProps = CatalogDropdownSharedProps & (
function CatalogDropdown(props: CatalogDropdownProps) {
const {
rootSessionId, currentSessionId, displayTitle, openTitle, variant,
useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t, hasSharedTasks = false,
useSessions, useSessionStatus, openChild, openChildAside, prepareCatalog, t, hasSharedTasks = false,
} = props
const ancestorSwitcher = variant === 'switcher' && openTitle !== undefined
const projections = useSessions(state => state.projectionsBySession)
@@ -507,7 +511,7 @@ function CatalogDropdown(props: CatalogDropdownProps) {
return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => {
const projected = snapshot.values.subagentCatalog
const state = snapshot.state === 'idle'
? projected === undefined ? 'loading' : 'ready'
? projected === undefined ? 'idle' : 'ready'
: snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state
return [id, {
state,
@@ -521,6 +525,11 @@ function CatalogDropdown(props: CatalogDropdownProps) {
}))
}, [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<ReadonlySet<SessionId>>(() => new Set())
const rootRef = useRef<HTMLDivElement>(null)
@@ -546,7 +555,7 @@ function CatalogDropdown(props: CatalogDropdownProps) {
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: 'loading', error: null }
? { entries: [], state: 'idle', error: null }
: undefined)
const cancelHoverClose = (): void => {
@@ -622,7 +631,7 @@ function CatalogDropdown(props: CatalogDropdownProps) {
return
}
setExpanded(current => new Set(current).add(childSessionId))
refreshProjection(childSessionId)
prepareLevel(childSessionId)
}
useEffect(() => {
@@ -736,6 +745,7 @@ function CatalogDropdown(props: CatalogDropdownProps) {
}
pinnedRef.current = true
if (!open) changeOpen(true)
prepareLevel(rootSessionId)
queueMicrotask(() => { menuRef.current?.focus() })
}
: () => {
@@ -748,6 +758,7 @@ function CatalogDropdown(props: CatalogDropdownProps) {
event.preventDefault()
if (variant === 'count' && !allowsHoverOpen()) pinnedRef.current = true
if (!open) changeOpen(true)
prepareLevel(rootSessionId)
queueMicrotask(() => { focusAt(0) })
}}
>
@@ -804,7 +815,7 @@ function CatalogDropdown(props: CatalogDropdownProps) {
level={1}
openChild={openChild}
openChildAside={openChildAside}
refreshProjection={refreshProjection}
refreshProjection={prepareLevel}
toggleBranch={toggleBranch}
closeCatalog={() => { changeOpen(false) }}
t={t}
@@ -841,7 +852,7 @@ export function SubagentCatalogAction(props: SubagentCatalogActionProps) {
/** Bind task-board visibility only in root conversations. */
function RootCatalogAction({
sessionId, useProjection, useSessions, useSessionStatus, useFooterAvailable,
openChild, openChildAside, refreshProjection, t, renderSlot,
openChild, openChildAside, refreshProjection, prepareCatalog, t, renderSlot,
}: SubagentCatalogActionProps) {
const hasSharedTasks = useProjection('agentTeam', team => team?.enabled === true
&& team.tasks.some(task => task.status !== 'deleted'))
@@ -860,6 +871,7 @@ function RootCatalogAction({
openChild={openChild}
openChildAside={openChildAside}
refreshProjection={refreshProjection}
prepareCatalog={prepareCatalog}
t={t}
/>
)
@@ -872,7 +884,7 @@ function RootCatalogAction({
*/
export function SubagentHeaderLineage({
lineageSessionId, displayTitle, openTitle,
useSessions, useSession, useSessionStatus, openChild, openChildAside, refreshProjection, t,
useSessions, useSession, useSessionStatus, openChild, openChildAside, refreshProjection, prepareCatalog, t,
}: SubagentHeaderLineageProps) {
const address = useSession(session => session.subagent?.address)
const parentId = useSessions((state) => {
@@ -883,7 +895,7 @@ export function SubagentHeaderLineage({
const summary = state.byId[lineageSessionId]
return summary?.origin === 'subagent' ? summary.parentId : undefined
})
const shared = { useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t }
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
@@ -62,6 +62,19 @@ export function apply(ctx: ClientContext): void {
preferNewPane: true,
})
},
async prepareCatalog(parentSessionId: SessionId) {
await ctx.sessions.refreshProjections(parentSessionId)
const parent = ctx.sessions.list.getSnapshot().projectionsBySession[parentSessionId]
if (parent?.state !== 'ready') return
for (const entry of parent.values.subagentCatalog ?? []) {
if (entry.mode === 'external') continue
const state = ctx.sessions.list.getSnapshot()
if (state.byId[entry.id]?.formatStatus === 'migration-required'
|| state.projectionsBySession[entry.id]?.state === 'migration-required'
|| state.projectionsBySession[entry.id]?.state === 'error') continue
await ctx.sessions.refreshProjections(entry.id)
}
},
refreshProjection(parentSessionId: SessionId) {
void ctx.sessions.refreshProjections(parentSessionId)
},
@@ -26,8 +26,8 @@ export const zh = {
'tokens.million': '{value}M',
'tokens.total': '{value} tok',
'loading.label': '正在加载子智能体…',
'load.idle': '尚未加载子智能体',
'load.error': '无法加载子智能体',
'catalog.migrationRequired': '需要迁移',
'retry': '重试',
'mode.external': '外部任务',
'mode.oneShot': '一次性',
@@ -77,8 +77,8 @@ export const en: Record<SubagentKey, string> = {
'tokens.million': '{value}M',
'tokens.total': '{value} tok',
'loading.label': 'Loading subagents…',
'load.idle': 'Subagents not loaded',
'load.error': 'Unable to load subagents',
'catalog.migrationRequired': 'Migration required',
'retry': 'Retry',
'mode.external': 'External task',
'mode.oneShot': 'one-shot',
@@ -131,8 +131,8 @@ export const ja = {
'tokens.million': '{value}M',
'tokens.total': '{value} tok',
'loading.label': 'サブエージェントを読み込み中…',
'load.idle': 'サブエージェントは未読み込みです',
'load.error': 'サブエージェントを読み込めません',
'catalog.migrationRequired': '移行が必要です',
'retry': '再試行',
'mode.external': '外部タスク',
'mode.oneShot': '単発',
@@ -182,8 +182,8 @@ export const es = {
'tokens.million': '{value}M',
'tokens.total': 'Tok {value}',
'loading.label': 'Cargando subagentes…',
'load.idle': 'Subagentes sin cargar',
'load.error': 'No se pueden cargar subagentes',
'catalog.migrationRequired': 'Migración requerida',
'retry': 'Reintentar',
'mode.external': 'tarea externa',
'mode.oneShot': 'un solo disparo',
@@ -233,8 +233,8 @@ export const fr = {
'tokens.million': '{value}M',
'tokens.total': 'Jeton {value}',
'loading.label': 'Chargement des sous-agents…',
'load.idle': 'Sous-agents non chargés',
'load.error': 'Impossible de charger les sous-agents',
'catalog.migrationRequired': 'Migration requise',
'retry': 'Réessayer',
'mode.external': 'Tâche externe',
'mode.oneShot': 'un coup',
@@ -284,8 +284,8 @@ export const de = {
'tokens.million': '{value}M',
'tokens.total': '{value}-Token',
'loading.label': 'Subagenten werden geladen…',
'load.idle': 'Subagenten nicht geladen',
'load.error': 'Subagenten können nicht geladen werden',
'catalog.migrationRequired': 'Migration erforderlich',
'retry': 'Erneut versuchen',
'mode.external': 'Externe Aufgabe',
'mode.oneShot': 'One-Shot',
@@ -335,8 +335,8 @@ export const ru = {
'tokens.million': '{value}M',
'tokens.total': '{value} ток',
'loading.label': 'Загрузка субагентов…',
'load.idle': 'Субагенты не загружены',
'load.error': 'Невозможно загрузить субагенты',
'catalog.migrationRequired': 'Требуется миграция',
'retry': 'Повторить',
'mode.external': 'Внешняя задача',
'mode.oneShot': 'одноразовый',
@@ -386,8 +386,8 @@ export const pt = {
'tokens.million': '{value}M',
'tokens.total': '{value} valor',
'loading.label': 'Carregando subagentes…',
'load.idle': 'Subagentes não carregados',
'load.error': 'Não foi possível carregar subagentes',
'catalog.migrationRequired': 'Migração necessária',
'retry': 'Tentar novamente',
'mode.external': 'Tarefa externa',
'mode.oneShot': 'tiro único',
@@ -4,7 +4,7 @@ import { Context } from '@deepseek-ai/cordis'
import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime'
import { describe, expect, it, onTestFinished, vi } from 'vitest'
import type {
SessionListState, SessionSnapshot, SessionSummary,
SessionListState, SessionSnapshot, SessionSummary, SessionProjectionSnapshot,
} from '@deepseek-ai/dsh-api-session-controller/client'
import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client'
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
@@ -35,7 +35,8 @@ const sid = (id: string) => id as SessionId
function sessionsWith(sessions: SessionSummary[]) {
const byId: Record<string, SessionSummary> = {}
for (const s of sessions) byId[s.id] = s
const snapshot: SessionListState = { ids: sessions.map(s => s.id), byId, phase: 'ready', projectionsBySession: {} }
const projections: Record<SessionId, SessionProjectionSnapshot> = {}
const snapshot: SessionListState = { ids: sessions.map(s => s.id), byId, phase: 'ready', projectionsBySession: projections }
const actionCalls: { method: string; args: unknown[] }[] = []
const address: SubagentAddress = {
parentSessionId: sid('parent'),
@@ -48,6 +49,7 @@ function sessionsWith(sessions: SessionSummary[]) {
subscribe: () => () => {},
},
actionCalls,
projections,
subagentAddress: (childSessionId: SessionId) => childSessionId === address.childSessionId
? address
: undefined,
@@ -121,6 +123,40 @@ describe('apply', () => {
expect(ctx.slots.entries('conversation.session.header.actions.subagent.footer')).toHaveLength(1)
})
it('reads direct child catalogs sequentially after reading the parent', async () => {
const { ctx, face } = await fullBench([...FAMILY, summary({ id: sid('legacy'), formatStatus: 'migration-required' })])
onTestFinished(() => ctx.fiber.dispose())
const entry = ctx.slots.entries('conversation.session.header.lineage')
.find(entry => entry.component === SubagentHeaderLineage)!
const actions = (entry.inject as (id: SessionId) => SubagentCatalogInjected)(sid('parent'))
const projections = face.projections
const held = Promise.withResolvers<undefined>()
const refresh = vi.spyOn(face, 'refreshProjections').mockImplementation(async (id) => {
if (id === sid('parent')) projections[id] = { state: 'ready', error: null, values: { subagentCatalog: [
{ id: sid('external'), mode: 'external', createdAt: 1 },
...['c1', 'c2', 'legacy', 'blocked', 'failed'].map(id => ({ id: sid(id), mode: 'one-shot' as const, createdAt: 1 })),
] } }
if (id === sid('c1')) {
await held.promise
projections[id] = { state: 'ready', error: null, values: { subagentCatalog: [
{ id: sid('grandchild'), mode: 'one-shot', createdAt: 1 },
] } }
}
})
onTestFinished(() => { refresh.mockRestore() })
projections[sid('blocked')] = { state: 'migration-required', error: null, values: {} }
projections[sid('failed')] = { state: 'error', error: null, values: {} }
const reading = actions.prepareCatalog(sid('parent'))
await vi.waitFor(() => { expect(refresh.mock.calls).toEqual([[sid('parent')], [sid('c1')]]) })
held.resolve(undefined)
await reading
expect(refresh.mock.calls).toEqual([[sid('parent')], [sid('c1')], [sid('c2')]])
await actions.prepareCatalog(sid('c2'))
projections[sid('c2')] = { state: 'ready', error: null, values: {} }
await actions.prepareCatalog(sid('c2'))
expect(refresh.mock.calls.slice(3)).toEqual([[sid('c2')], [sid('c2')]])
})
it('registers catalog actions and selects read-only subagent composers from session facts', async () => {
const { ctx, face } = await fullBench(FAMILY)
const catalogEntry = ctx.slots.entries('conversation.session.header.lineage')
@@ -75,31 +75,44 @@ function props(
) {
const catalogs = value === undefined ? nested : { [PARENT]: value, ...nested }
const statuses: SessionStatusSnapshot = new Map()
const byId: Record<SessionId, SessionSummary> = {
...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: 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(),
},
},
byId,
phase: 'ready',
projectionsBySession: Object.fromEntries(Object.entries(catalogs).map(([id, catalog]) => [id, {
state: catalog.state, error: catalog.error,
values: {
...catalog.team === undefined ? {} : { agentTeam: catalog.team },
subagentCatalog: catalog.entries.map(({ activity: _activity, ...entry }) => ({ ...entry, createdAt: 1 })),
},
}])) ,
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 })),
},
}])),
},
} 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<T>(select: (snapshot: SessionListState) => T): T {
return select(state)
}
@@ -142,6 +155,7 @@ function props(
openChild: vi.fn(),
openChildAside: vi.fn(),
refreshProjection: vi.fn(),
prepareCatalog: vi.fn<(id: SessionId) => Promise<void>>().mockResolvedValue(),
renderSlot: vi.fn(() => null),
lineageSessionId: PARENT,
displayTitle: 'Parent title',
@@ -528,8 +542,8 @@ describe('SubagentHeaderLineage', () => {
expect(screen.getByText('worker')).toBeTruthy()
expect(screen.queryByText('正在扫描项目文件')).toBeNull()
expect(screen.getByRole('treeitem', { name: /reviewer child-2 · 一次性 · 当前未运行/ })).toBeTruthy()
expect(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })).toBeTruthy()
expect(screen.getByRole('button', { name: '展开 reviewer 的下级子智能体' })).toBeTruthy()
expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull()
expect(screen.queryByRole('button', { name: '展开 reviewer 的下级子智能体' })).toBeNull()
const sidebarButton = within(screen.getByRole('treeitem', { name: /worker/ }))
.getByRole('button', { name: '在侧边栏打开 worker' })
@@ -732,8 +746,11 @@ describe('SubagentHeaderLineage', () => {
expect(screen.getByRole('treeitem', { name: /worker/ }).children).toHaveLength(1)
})
it('aligns a known leaf with siblings whose child catalog is still unknown', () => {
render(<HeaderCatalog {...props(catalog(), { [CHILD]: catalog({ entries: [] }) })} />)
it('aligns a known leaf with siblings whose child catalog contains descendants', () => {
render(<HeaderCatalog {...props(catalog(), {
[CHILD]: catalog({ entries: [] }),
['child-2' as SessionId]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'nested', activity: 'inactive' }] }),
})} />)
hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ }))
expect(screen.getByRole('treeitem', { name: /worker/ }).children).toHaveLength(2)
@@ -1043,6 +1060,7 @@ describe('SubagentHeaderLineage', () => {
origin: 'subagent' as const,
running: activity === 'running',
projectionValues: {
subagentCatalog: [],
subagentTiming: {
settledMs,
...(id === 'finished'
@@ -1111,6 +1129,7 @@ describe('SubagentHeaderLineage', () => {
origin: 'subagent',
running: true,
projectionValues: {
subagentCatalog: [],
subagentTiming: { settledMs: 0, active: { since: now - 5_000, through: now } },
},
},
@@ -1147,7 +1166,7 @@ describe('SubagentHeaderLineage', () => {
hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ }))
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
expect(input.refreshProjection).toHaveBeenCalledWith(CHILD)
expect(input.refreshProjection).not.toHaveBeenCalled()
const nested = screen.getByRole('treeitem', { name: /indexer/ })
expect(nested.getAttribute('aria-level')).toBe('2')
@@ -1158,15 +1177,15 @@ describe('SubagentHeaderLineage', () => {
})
})
it('keeps ordinary cold descendants loading until their real catalog arrives', () => {
it('reveals cold descendants only when shared catalog data arrives', () => {
const secondGrandchild = 'grandchild-2' as SessionId
const summaries = {
[CHILD]: { ...summary(CHILD, 1), running: true },
[GRANDCHILD]: {
...summary(GRANDCHILD, 1), parentId: CHILD, origin: 'subagent' as const,
...summary(GRANDCHILD, 1), projectionValues: { subagentCatalog: [] }, parentId: CHILD, origin: 'subagent' as const,
},
[secondGrandchild]: {
...summary(secondGrandchild, 1), parentId: CHILD, origin: 'subagent' as const,
...summary(secondGrandchild, 1), projectionValues: { subagentCatalog: [] }, parentId: CHILD, origin: 'subagent' as const,
running: true,
},
}
@@ -1176,11 +1195,11 @@ describe('SubagentHeaderLineage', () => {
const current = { ...deferred, useSessions: <T,>(select: (snapshot: SessionListState) => T): T => select(state) }
const view = render(<HeaderCatalog {...current} />)
hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ }))
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull()
expect(deferred.refreshProjection).toHaveBeenCalledWith(CHILD)
expect(screen.getByRole('group').getAttribute('aria-busy')).toBe('true')
expect(screen.getByText('正在加载子智能体…')).toBeTruthy()
expect(deferred.refreshProjection).not.toHaveBeenCalled()
expect(screen.getByRole('treeitem', { name: /worker/ }).getAttribute('aria-busy')).toBeNull()
expect(screen.queryByText('正在加载子智能体…')).toBeNull()
expect(screen.queryByRole('treeitem', { name: '正在加载子智能体' })).toBeNull()
expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull()
expect(screen.queryByText(/模式未知/)).toBeNull()
@@ -1193,7 +1212,7 @@ describe('SubagentHeaderLineage', () => {
},
}
view.rerender(<HeaderCatalog {...current} />)
expect(screen.getByText('正在加载子智能体…')).toBeTruthy()
expect(screen.queryByText('正在加载子智能体…')).toBeNull()
expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull()
expect(screen.queryByText(/模式未知/)).toBeNull()
@@ -1213,16 +1232,162 @@ describe('SubagentHeaderLineage', () => {
}, summaries)
state = { ...state, projectionsBySession: ready.useSessions(value => value.projectionsBySession) }
view.rerender(<HeaderCatalog {...current} />)
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
expect(screen.getByRole('group').getAttribute('aria-busy')).toBeNull()
expect(screen.getByRole('treeitem', { name: /indexer/ }).querySelector('[data-state="idle"]')).not.toBeNull()
expect(screen.getByRole('treeitem', { name: /critic/ }).querySelector('[data-state="ongoing"]')).not.toBeNull()
expect(screen.queryByText('正在加载子智能体…')).toBeNull()
expect(screen.queryByText(/模式未知/)).toBeNull()
expect(deferred.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD)
expect(deferred.refreshProjection).not.toHaveBeenCalled()
expect(deferred.openChild).not.toHaveBeenCalled()
})
it.each([false, true])('shows list migration status before expanding, with cached descendants=%s', (cached) => {
it.each([
{ running: true, completed: false, dot: 'ongoing' },
{ running: false, completed: true, dot: 'done' },
{ running: false, completed: false, dot: 'idle' },
])('preserves the $dot activity marker while an unknown directory loads', ({ running, completed, dot }) => {
const input = props(catalog({ entries: [{
id: CHILD, mode: 'continuable', label: 'worker', activity: running ? 'running' : 'inactive',
}] }), {}, { [CHILD]: {
...summary(CHILD, 1), running,
projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: completed } },
} })
let state = input.useSessions(value => value)
const current = { ...input, useSessions: <T,>(select: (value: SessionListState) => T): T => select(state) }
const view = render(<HeaderCatalog {...current} />)
fireEvent.click(screen.getByRole('button', { name: '1 个子智能体' }))
const row = screen.getByRole('treeitem', { name: /worker/ })
const marker = row.querySelector(`[data-state="${dot}"]`)
expect(marker).not.toBeNull()
expect(row.children).toHaveLength(1)
expect(input.refreshProjection).not.toHaveBeenCalled()
state = { ...state, projectionsBySession: { ...state.projectionsBySession, [CHILD]: {
...state.projectionsBySession[CHILD]!, state: 'loading',
} } }
view.rerender(<HeaderCatalog {...current} />)
expect(screen.getByRole('treeitem', { name: /worker/ })).toBe(row)
expect(row.querySelector(`[data-state="${dot}"]`)).toBe(marker)
expect(screen.queryByText('正在加载子智能体…')).toBeNull()
expect(row.hasAttribute('aria-busy')).toBe(false)
expect(row.hasAttribute('aria-expanded')).toBe(false)
expect(within(row).getByRole('button', { name: '在侧边栏打开 worker' }).hasAttribute('disabled')).toBe(false)
expect(input.refreshProjection).not.toHaveBeenCalled()
})
it('leaves missing catalogs unread and retries only an explicitly selected failure', () => {
const input = props(catalog(), {}, { [CHILD]: summary(CHILD, 1) })
let state = input.useSessions(value => value)
const current = { ...input, useSessions: <T,>(select: (value: SessionListState) => T): T => select(state) }
const view = render(<HeaderCatalog {...current} />)
expect(input.refreshProjection).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' }))
expect(input.refreshProjection).not.toHaveBeenCalled()
expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull()
expect(screen.queryByText('正在加载子智能体…')).toBeNull()
state = { ...state, projectionsBySession: {
...state.projectionsBySession,
[CHILD]: { state: 'error', values: {}, error: new RemoteError('gateway/internal', 'private diagnostic', {}) },
} }
view.rerender(<HeaderCatalog {...current} />)
expect(screen.getByRole('alert').textContent).toContain('无法加载子智能体')
expect(screen.queryByText('private diagnostic')).toBeNull()
expect(screen.queryByRole('status')).toBeNull()
expect(input.refreshProjection).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: '重试' }))
expect(input.prepareCatalog.mock.calls).toEqual([[PARENT], [CHILD]])
expect(input.refreshProjection).not.toHaveBeenCalled()
expect(input.openChild).not.toHaveBeenCalled()
state = { ...state, projectionsBySession: {
...state.projectionsBySession, [CHILD]: { state: 'ready', values: { subagentCatalog: [] }, error: null },
} }
view.rerender(<HeaderCatalog {...current} />)
expect(screen.queryByRole('alert')).toBeNull()
expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull()
expect(screen.getByRole('treeitem', { name: /worker/ }).getAttribute('aria-busy')).toBeNull()
})
it('expands cached shared projections without reading the next level', () => {
const childSummary = { ...summary(CHILD, 1), projectionValues: { subagentCatalog: [
{ id: GRANDCHILD, createdAt: 1, mode: 'continuable' as const, label: 'indexer' },
] } }
const input = props(catalog(), {}, { [CHILD]: childSummary, [GRANDCHILD]: summary(GRANDCHILD, 1) })
let state = input.useSessions(value => value)
const current = { ...input, useSessions: <T,>(select: (value: SessionListState) => T): T => select(state) }
const view = render(<HeaderCatalog {...current} />)
fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' }))
expect(input.refreshProjection).not.toHaveBeenCalled()
expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull()
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
expect(screen.getByRole('treeitem', { name: /indexer/ })).toBeTruthy()
expect(input.refreshProjection).not.toHaveBeenCalled()
expect(screen.queryByRole('button', { name: '展开 indexer 的下级子智能体' })).toBeNull()
state = { ...state, projectionsBySession: {
...state.projectionsBySession, [CHILD]: { state: 'ready', error: null, values: { subagentCatalog: [] } },
} }
view.rerender(<HeaderCatalog {...current} />)
expect(screen.queryByRole('button', { name: '收起 worker 的下级子智能体' })).toBeNull()
expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull()
})
it('updates disclosure when a visible leaf gains children without fetching any level', () => {
const input = props(catalog())
let state = input.useSessions(value => value)
const current = { ...input, useSessions: <T,>(select: (value: SessionListState) => T): T => select(state) }
const view = render(<HeaderCatalog {...current} />)
fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' }))
const worker = screen.getByRole('treeitem', { name: /worker/ })
expect(worker.hasAttribute('aria-expanded')).toBe(false)
state = { ...state, projectionsBySession: { ...state.projectionsBySession, [CHILD]: {
state: 'idle', error: null, values: {
subagentCatalog: [{ id: GRANDCHILD, createdAt: 1, mode: 'continuable', label: 'indexer' }],
},
} } }
view.rerender(<HeaderCatalog {...current} />)
expect(screen.getByRole('treeitem', { name: /worker/ })).toBe(worker)
expect(worker.getAttribute('aria-expanded')).toBe('false')
expect(input.refreshProjection).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
expect(input.refreshProjection).not.toHaveBeenCalled()
expect(screen.getByRole('treeitem', { name: /indexer/ })).toBeTruthy()
})
it('prepares only explicitly opened levels', () => {
const input = props(catalog(), {
[CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'indexer', activity: 'inactive' }] }),
})
render(<HeaderCatalog {...input} />)
const trigger = screen.getByRole('button', { name: /\d+ 个子智能体$/ })
hoverCatalog(trigger)
expect(input.prepareCatalog).not.toHaveBeenCalled()
fireEvent.click(trigger)
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
expect(input.prepareCatalog.mock.calls).toEqual([[PARENT], [CHILD]])
fireEvent.click(screen.getByRole('button', { name: '收起 worker 的下级子智能体' }))
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
expect(input.prepareCatalog).toHaveBeenCalledTimes(2)
fireEvent.keyDown(trigger, { key: 'ArrowDown' })
expect(input.prepareCatalog.mock.calls.at(-1)).toEqual([PARENT])
})
it('reports an unexpected explicit catalog failure', async () => {
const input = props(catalog())
const failure = new Error('projection reader failed')
input.prepareCatalog.mockRejectedValueOnce(failure)
const report = vi.spyOn(console, 'error').mockImplementation(() => {})
try {
render(<HeaderCatalog {...input} />)
fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ }))
await vi.waitFor(() => { expect(report).toHaveBeenCalledWith('[ui-subagent] catalog discovery failed:', failure) })
} finally {
report.mockRestore()
}
})
it.each([false, true])('keeps legacy rows navigable without a migration notice, with cached descendants=%s', (cached) => {
const input = props(catalog(), cached ? {
[CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'indexer', activity: 'inactive' }] }),
} : {}, {
@@ -1235,7 +1400,8 @@ describe('SubagentHeaderLineage', () => {
hoverCatalog(trigger)
const child = screen.getByRole('treeitem', { name: /worker/ })
expect(within(child).getByText(/需要迁移/)).toBeTruthy()
expect(within(child).queryByText(/需要迁移/)).toBeNull()
expect(child.getAttribute('aria-label')).not.toContain('需要迁移')
expect(within(child).queryByRole('button', { name: /下级子智能体/ })).toBeNull()
fireEvent.keyDown(child, { key: 'ArrowRight' })
expect(input.refreshProjection).not.toHaveBeenCalled()
@@ -1248,8 +1414,13 @@ describe('SubagentHeaderLineage', () => {
view.rerender(<HeaderCatalog {...current} />)
hoverCatalog(trigger)
expect(screen.queryByText(/需要迁移/)).toBeNull()
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
expect(input.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD)
if (cached) {
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
expect(input.refreshProjection).not.toHaveBeenCalled()
} else {
expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull()
expect(input.refreshProjection).not.toHaveBeenCalled()
}
})
it.each(['ready', 'migration-required'] as const)('stops at a migration-required child until its real catalog arrives with %s read state', (readState) => {
@@ -1272,7 +1443,7 @@ describe('SubagentHeaderLineage', () => {
const current = { ...input, useSessions: <T,>(select: (snapshot: SessionListState) => T): T => select(state) }
const view = render(<HeaderCatalog {...current} />)
hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ }))
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull()
expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull()
state = {
@@ -1287,15 +1458,15 @@ describe('SubagentHeaderLineage', () => {
expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull()
expect(screen.queryByRole('treeitem', { name: /ordinary-fork/ })).toBeNull()
const child = screen.getByRole('treeitem', { name: /worker/ })
expect(within(child).getByText(/需要迁移/)).toBeTruthy()
expect(within(child).queryByText(/需要迁移/)).toBeNull()
expect(child.getAttribute('aria-label')).not.toContain('需要迁移')
expect(within(child).queryByText(/模式未知/)).toBeNull()
expect(en['catalog.migrationRequired']).toBe('Migration required')
expect(child.hasAttribute('aria-expanded')).toBe(false)
expect(within(child).queryByRole('button', { name: /下级子智能体/ })).toBeNull()
expect(screen.queryByRole('group')).toBeNull()
expect(screen.queryByText('正在加载子智能体…')).toBeNull()
fireEvent.keyDown(child, { key: 'ArrowRight' })
expect(input.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD)
expect(input.refreshProjection).not.toHaveBeenCalled()
expect(input.openChild).not.toHaveBeenCalled()
fireEvent.click(child)
expect(input.openChild).toHaveBeenCalledExactlyOnceWith({
@@ -1347,7 +1518,8 @@ describe('SubagentHeaderLineage', () => {
fireEvent.keyDown(child, { key: 'ArrowRight' })
fireEvent.keyDown(child, { key: 'ArrowRight' })
expect(input.refreshProjection).not.toHaveBeenCalled()
expect(within(child).getByText(/需要迁移/)).toBeTruthy()
expect(within(child).queryByText(/需要迁移/)).toBeNull()
expect(child.getAttribute('aria-label')).not.toContain('需要迁移')
expect(within(child).queryByText(/模式未知/)).toBeNull()
expect(child.hasAttribute('aria-expanded')).toBe(false)
expect(within(child).queryByRole('button', { name: /下级子智能体/ })).toBeNull()
@@ -1406,7 +1578,30 @@ describe('SubagentHeaderLineage', () => {
expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull()
})
it('closes expanded descendants even when their own catalogs have not arrived', () => {
it('collapses expanded descendants whose catalog is removed before their parent closes', () => {
const input = props(catalog(), {
[CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'indexer', activity: 'inactive' }] }),
[GRANDCHILD]: catalog({ entries: [{ id: 'great-grandchild' as SessionId, mode: 'continuable', label: 'deep', activity: 'inactive' }] }),
})
let state = input.useSessions(value => value)
const current = { ...input, useSessions: <T,>(select: (value: SessionListState) => T): T => select(state) }
const view = render(<HeaderCatalog {...current} />)
fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' }))
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
fireEvent.click(screen.getByRole('button', { name: '展开 indexer 的下级子智能体' }))
const { [GRANDCHILD]: _projection, ...projectionsBySession } = state.projectionsBySession
const { [GRANDCHILD]: _summary, ...byId } = state.byId
state = { ...state, projectionsBySession, byId }
view.rerender(<HeaderCatalog {...current} />)
fireEvent.click(screen.getByRole('button', { name: '收起 worker 的下级子智能体' }))
expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull()
state = input.useSessions(value => value)
view.rerender(<HeaderCatalog {...current} />)
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
expect(screen.getByRole('treeitem', { name: /indexer/ }).getAttribute('aria-expanded')).toBe('false')
})
it('closes a branch while the visible descendants are loading', () => {
const input = props(catalog(), {
[CHILD]: catalog({
entries: [{
@@ -1414,11 +1609,12 @@ describe('SubagentHeaderLineage', () => {
label: 'indexer', activity: 'running',
}],
}),
})
}, { [GRANDCHILD]: summary(GRANDCHILD, 1) })
render(<HeaderCatalog {...input} />)
hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ }))
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
fireEvent.click(screen.getByRole('button', { name: '展开 indexer 的下级子智能体' }))
expect(screen.queryByRole('button', { name: '展开 indexer 的下级子智能体' })).toBeNull()
expect(screen.getByRole('treeitem', { name: /indexer/ }).getAttribute('aria-busy')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: '收起 worker 的下级子智能体' }))
expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull()
@@ -1443,7 +1639,8 @@ describe('SubagentHeaderLineage', () => {
hoverCatalog(screen.getByRole('button', { name: /0 个子智能体/ }))
expect(screen.getByText('index down')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: /重试/ }))
expect(failed.refreshProjection).toHaveBeenCalledWith(PARENT)
expect(failed.prepareCatalog).toHaveBeenCalledExactlyOnceWith(PARENT)
expect(failed.refreshProjection).not.toHaveBeenCalled()
})
it.each(['absent', 'idle', 'loading', 'ready'] as const)('does not expose header-only descendants when the projection read is %s', (state) => {
@@ -1584,7 +1781,9 @@ describe('SubagentHeaderLineage', () => {
const switcher = screen.getByRole('button', { name: '切换子智能体:worker' })
hoverCatalog(switcher)
expect(screen.getByText('正在加载子智能体…')).toBeTruthy()
expect(input.prepareCatalog).not.toHaveBeenCalled()
expect(screen.getByText('尚未加载子智能体')).toBeTruthy()
expect(screen.queryByText('正在加载子智能体…')).toBeNull()
expect(screen.queryAllByRole('treeitem')).toEqual([])
expect(input.refreshProjection).not.toHaveBeenCalled()
})
@@ -1690,11 +1889,30 @@ describe('SubagentHeaderLineage', () => {
const switcher = screen.getByRole('button', { name: '切换子智能体:正在扫描项目文件' })
expect(input.refreshProjection).not.toHaveBeenCalled()
hoverCatalog(switcher)
expect(screen.getByText('正在加载子智能体…')).toBeTruthy()
expect(input.prepareCatalog).not.toHaveBeenCalled()
expect(screen.getByText('尚未加载子智能体')).toBeTruthy()
expect(screen.queryByText('正在加载子智能体…')).toBeNull()
expect(screen.queryAllByRole('treeitem')).toEqual([])
expect(input.refreshProjection).not.toHaveBeenCalled()
})
it.each(['idle', 'loading'] as const)('shows the actual %s state of an empty title menu', (state) => {
const input = {
...props(undefined, {}, {}, { parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }),
lineageSessionId: CHILD,
displayTitle: 'worker',
}
const initial = input.useSessions(value => value)
render(<HeaderCatalog {...input} useSessions={select => select({
...initial,
projectionsBySession: { [PARENT]: { state, error: null, values: {} } },
})} />)
hoverCatalog(screen.getByRole('button', { name: '切换子智能体:worker' }))
expect(screen.getByText(state === 'idle' ? zh['load.idle'] : zh['loading.label'])).toBeTruthy()
expect(screen.queryByText(state === 'idle' ? zh['loading.label'] : zh['load.idle'])).toBeNull()
expect(input.prepareCatalog).not.toHaveBeenCalled()
})
it('keeps a nested title switcher scoped to its direct-parent catalog', () => {
const input = {
...props(catalog(), {
@@ -0,0 +1,8 @@
- tree "Subagent sessions":
- treeitem "event-sourcing researcher agent-1 · continuable · completed 7.9K tok · {{duration}}" [level=1]:
- button "Expand event-sourcing researcher descendants"
- text: event-sourcing researcher agent-1 7.9K tok {{duration}}
- button "Open event-sourcing researcher in sidebar"
- treeitem "event-sourcing reviewer recorded-one-shot · one-shot · completed 0 tok · {{duration}}" [level=1]:
- text: event-sourcing reviewer recorded-one-shot 0 tok ~6mo 12d
- button "Open event-sourcing reviewer in sidebar"