Files
deepseek-harness/apps/web/tests/sidebar-subagent-activity.e2e.ts
T
LegGasai bd99b1e062 Merge branch 'feat/session-panel' into feat/session-panel-sections
Brings master (through feat/session-panel) into this branch. Master changed
controls this branch had moved into the Session panel, so its changes are
carried over to their new homes:

- Jobs: master hides the stop control without `job/kill` access in the
  header list this branch removed; the panel's Background jobs section now
  reads `useAccess('job/kill')` the same way.
- Forge: master takes the sign-in command from the provider
  (`readiness.signIn`) in the sidebar tab this branch removed; the panel's
  sign-in row now does, for any code host, instead of building a GitHub
  command itself.
- Agent team: the team settings pane and its copy from master, with this
  branch's Shared tasks section registration.
- Tests: master's helpers for the team settings pane and its numbered
  reference helper are combined with this branch's panel steps; the
  status fixture gains master's `completionFailed`.
- READMEs of ui-agent-team and client-ui-forge are merged sentence by
  sentence; generated catalogs, the persistence schema, and pairing
  records are regenerated.

The upgrade guide moves to docs/upgrade-guide/v0.2.2-rc.3, the root
version after master's release.
2026-11-15 13:00:24 +08:00

200 lines
8.5 KiB
TypeScript

import { mkdir } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import type { AgentHandle } from '@deepseek-ai/dsh-agent'
import { createUserMessage, LlmAdapter } from '@deepseek-ai/dsh-llm'
import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm'
import type { SessionId, SessionId as SessionIdValue } from '@deepseek-ai/dsh-session'
import type {} from '@deepseek-ai/dsh-subagent'
import type {} from '@deepseek-ai/dsh-workspace'
import {
assertFixtureInventory,
captureStableAria,
compareOrRefreshGolden,
launchWebScaffold,
watchConsole,
webSnapshotMode,
type WebScaffold,
} from './scaffold.ts'
import { connectFreshWorkspace, newEnglishPage, saveFailureShot, sessionPanelToggle, showSessionPanel } from './support.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/sidebar-subagent-activity', import.meta.url))
const RUNNING_OWNER_EXPECTED = join(SNAPSHOT_DIR, 'owner-running.expected.md')
const MODE = webSnapshotMode()
const HOLD_PROVIDER = 'web-test-hold'
const HOLD_MODEL = 'hold'
/** Model stub that completes the owner turn, then holds its delegated child open. */
class StagedAdapter extends LlmAdapter {
activeCalls = 0
private calls = 0
override async *stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
if (this.calls === 0) {
this.calls += 1
yield { type: 'finish', reason: { kind: 'stop' } }
return
}
this.calls += 1
const signal = options.signal
if (signal === undefined) throw new Error('staged Web adapter requires a turn signal')
this.activeCalls += 1
try {
await new Promise<never>((_resolve, reject) => {
const abort = (): void => {
reject(signal.reason instanceof Error ? signal.reason : new Error('holding Web adapter aborted'))
}
if (signal.aborted) abort()
else signal.addEventListener('abort', abort, { once: true })
})
} finally {
this.activeCalls -= 1
}
}
}
async function waitForRunningChild(
scaffold: WebScaffold,
adapter: StagedAdapter,
childId: SessionIdValue,
): Promise<void> {
const deadline = Date.now() + 10_000
while (adapter.activeCalls !== 1 || scaffold.ctx.agents.get(childId)?.status !== 'running') {
if (Date.now() >= deadline) throw new Error('held child did not enter its running model call')
await new Promise<void>(resolve => setTimeout(resolve, 10))
}
}
describe('web e2e: sidebar subagent activity', () => {
let scaffold: WebScaffold
let browser: Browser
let page: Page
let parentHandle: AgentHandle
let childId: SessionIdValue
let adapter: StagedAdapter
let tripwire: ReturnType<typeof watchConsole>
beforeAll(async () => {
scaffold = await launchWebScaffold()
adapter = new StagedAdapter()
scaffold.ctx.effect(
() => scaffold.ctx.llm.registerAdapter([HOLD_PROVIDER], adapter),
'sidebar subagent activity staged adapter',
)
const cwd = join(scaffold.workspaceCwd, 'workspace')
await mkdir(cwd)
parentHandle = await scaffold.ctx.agents.create({
sessionId: brandString<SessionId>('sidebar-activity-owner'),
meta: { cwd },
agentOptions: { provider: HOLD_PROVIDER, model: HOLD_MODEL },
})
parentHandle.agent.followup(createUserMessage({
content: [{ type: 'text', text: 'Delegate a background job.' }],
source: { kind: 'user' },
}))
await parentHandle.agent.whenIdle()
const started = await scaffold.ctx.subagents.startActivation({
delivery: 'parent',
provider: 'spawn',
label: 'sidebar activity child',
signal: new AbortController().signal,
prompt: [{ type: 'text', text: 'Hold this delegated task open.' }],
parent: parentHandle.agent,
})
childId = started.childId
await waitForRunningChild(scaffold, adapter, childId)
browser = await chromium.launch()
page = await newEnglishPage(browser)
tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
await connectFreshWorkspace(page, scaffold.workspaceCwd)
const workspace = await scaffold.ctx.workspaceRegistry.resolveByPath(cwd)
if (workspace === undefined) throw new Error('connected Web workspace was not registered')
await workspace.attachSession(parentHandle.agent.session.id)
}, 60_000)
afterAll(async () => {
const failures: unknown[] = []
const child = childId === undefined ? undefined : scaffold?.ctx.agents.get(childId)
if (child !== undefined) {
child.cancel({ kind: 'user' })
await child.whenIdle().catch((error: unknown) => failures.push(error))
}
await browser?.close().catch((error: unknown) => failures.push(error))
await parentHandle?.dispose().catch((error: unknown) => failures.push(error))
await scaffold?.close().catch((error: unknown) => failures.push(error))
if (failures.length === 1) throw failures[0]
if (failures.length > 1) throw new AggregateError(failures, 'sidebar subagent activity teardown failed')
})
it('pins a running descendant on its visible idle owner row', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-sidebar-subagent-activity'))
const sidebar = page.getByRole('tree', { name: 'Sessions' })
const ownerRow = sidebar.getByRole('treeitem', { name: /1 subagent running.*Delegate a background job/ })
await ownerRow.waitFor({ timeout: 10_000 })
expect(parentHandle.agent.status).toBe('idle')
await compareOrRefreshGolden(
RUNNING_OWNER_EXPECTED,
await captureStableAria(page, '[role="tree"][aria-label="Sessions"]', scaffold.workspaceCwd),
MODE,
)
expect(await ownerRow.locator('[data-state="ongoing"]').count()).toBe(1)
await ownerRow.click()
const toggle = sessionPanelToggle(page)
const subagents = (await showSessionPanel(page)).locator('[data-session-panel-section="subagents"]')
await subagents.getByRole('treeitem').locator('[data-state="ongoing"]').waitFor({ timeout: 10_000 })
expect(await subagents.getByText('1 in progress', { exact: true }).isVisible()).toBe(true)
// This directly created owner has no tool preset; the fixture collects its own job.
scaffold.ctx.effect(() => scaffold.ctx.jobs.attachController('compact header fixture'), 'compact header job controller')
const completion = Promise.withResolvers<{ status: 'completed' }>()
const ownerId = parentHandle.agent.id
const jobId = scaffold.ctx.jobs.start({
kind: 'bash', label: 'Concurrent background work', owner: ownerId,
run(handle) {
handle.append('Background work is running.\n')
return { done: completion.promise, cancel: () => { completion.resolve({ status: 'completed' }) } }
},
})
const viewport = page.viewportSize()!
const panel = page.locator('[data-session-panel]')
const assertRunningSections = async (): Promise<void> => {
await showSessionPanel(page)
for (const section of ['subagents', 'background-jobs']) {
await panel.locator(`[data-session-panel-section="${section}"]`).locator('[data-state="ongoing"]').first()
.waitFor({ timeout: 10_000 })
}
expect(await panel.getAttribute('data-session-panel')).toBe('overlay')
await page.keyboard.press('Escape')
await panel.waitFor({ state: 'detached' })
}
try {
await assertRunningSections()
await toggle.focus()
await page.setViewportSize({ width: 390, height: 700 })
expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true)
await compareOrRefreshGolden(
join(SNAPSHOT_DIR, 'compact-running.expected.md'),
await captureStableAria(page, 'header:has([data-session-panel-toggle])', scaffold.workspaceCwd),
MODE,
)
await saveFailureShot(page, 'web-e2e-compact-running-header')
await assertRunningSections()
await page.setViewportSize(viewport)
await assertRunningSections()
} finally {
completion.resolve({ status: 'completed' })
await scaffold.ctx.jobs.wait(jobId, 5_000, ownerId)
await page.setViewportSize(viewport)
}
await assertFixtureInventory(SNAPSHOT_DIR, ['owner-running.expected.md', 'compact-running.expected.md'])
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
})
})