Files
deepseek-harness/apps/web/tests/sidebar-subagent-activity.e2e.ts
T
a39d44b5dc feat(session): add host reading status to SessionStatus (#6858)
* ✨ feat(session): persist and synchronize read state

* 🌐 fix(client): complete Japanese labels after base update

* 📝 docs: refresh session read-state dependency graph

* 🧪 test(web): align session menu and read-state snapshots

* 🌐 fix(session): complete Japanese plugin metadata

* 🧪 test(web): distinguish unread from pending user input

* 🐛 修复会话阅读状态的故障隔离与生命周期

* 🐛 修复阅读状态依赖检查并补齐自动已读覆盖

* 🐛 恢复会话绿点并移除未读标题加粗

* ♻️ Keep shared session reading state in Host memory

* 🌐 Complete reading-state metadata for supported locales

* 📝 Refresh module graph after removing storage dependency

* 🧹 Move storage dependency policy out of memory-only reading

* 🐛 Wait for sidebar catalog before replay navigation

* 🔧 Give Host TypeScript checks 8 GiB of heap

* ✅ Align Host heap checks and Windows diagnostics

* ♻️ Keep CI repairs outside the session reading PR

* 🐛 Show failed unread turns with an error indicator

* 🔧 Adjust npm layout budget for the reading package

* 🧪 Scope projection stream assertions to observed units

* 🧪 Scope permission and title assertions to their projections

* ♻️ Simplify session reading updates to explicit positions

* 🐛 Align session reading package with release version

* 🧪 Load reading state in LiveShare viewer fixtures

* 🧹 Remove persistence-only type link from memory PR

* 🧪 Align context menu expectations with reading actions

* 🐛 Sync reading package with the release version

* 🧪 Include turn boundaries in session summary expectations

* ♻️ Derive reading failure facts from Host events instead of a projection

The reading service took each completion from the Agent turn-boundary
projection, which forced a stateVersion bump and put that projection's whole
internal state on the wire for every Session list row. The service now records
`turn/end` itself, so `core/agent` and the persisted projection schema are
untouched.

History that ended before the service started raises no reminder, which keeps
"existing history reads as read" without a startup scan. The failure flag
therefore describes only turns this Host observed: marking a Session whose last
turn failed before a restart shows the ordinary unread reminder.

* 🐛 Preserve manual unread until explicit Session interaction

* 🧪 Align cold Session reading snapshot with unloaded title

* 🔖 chore(session): align session-read-state with 0.2.2-rc.2

Master moved the root and every released manifest to 0.2.2-rc.2, but the
new dsh-session-read-state package still declared 0.2.2-rc.1, failing
constraints, verify-version-sync, verify-npm-install-layout, and
release:verify after the master merge.

* ♻️ refactor(gateway): recognize Remote stream carrier loss by error code

RemoteStream now decides whether a generation end or failure is a
retryable carrier loss by the stable code 'gateway/carrier-lost' instead
of `instanceof RemoteStreamCarrierError`. RemoteStreamCarrierError keeps
working and carries that code, so existing callers are unchanged, while a
Client feature package can return a coded Error from `ended` without
importing the class. The new RemoteStreamCarrierFailure type describes
such errors; terminal-controller classifies disconnects the same way.

* ♻️ refactor(session): move Session reading into ui-session-status

Fold the reading feature into the single package
packages/client/ui-session-status and delete session-read-state.

- Host face: SessionStatusService keeps in-memory reading records and
  serves the sessionStatus Remote namespace (mark, follow) with
  session-status/* error codes; its service key is registered only for
  Gateway discovery and is not declared on Context.
- Client face: a package-internal reading model follows the Host stream
  through RemoteSnapshotStream; ctx.uiSession.sessionStatus folds the
  records into completionUnread and completionFailed and exposes mark and
  readingReady; main-view acknowledgement and the
  session-status/read-intent event live here. No reading service or type
  is exported.
- verify-client-packages lets a packages/client feature package request
  packages/api rows through dsh.client.external; feature-to-feature
  requests stay rejected.
- ui-workspace, ui-conversation, bundles, remotes, LiveShare, the client
  test runtime, docs, Agent Notes, and the upgrade guide follow.

* ♻️ refactor(session): clear manual unread only when the main view switches to the Session

Remove the session-status/read-intent event. ui-session-status now clears an
existing manual unread mark when the main view switches to a different
Session, including the first selection after a page load, once the reading
baseline is ready and the body arrives. Window focus, visibility changes,
a replaced binding for the same Session, and activity in the open Session
preserve manual unread.

ui-conversation returns to master (only the ui-session-status client
tsconfig reference remains), and ui-workspace navigation no longer emits
the event. Tests, the session-reading Web e2e case, READMEs, and the
reading Agent Note follow the new rule.

* 🐛 fix(session): address the Session status review findings

- Open the reading stream only while ctx.remoteAccess allows
  sessionStatus/follow, so a LiveShare viewer opens no owner-only stream,
  keeps readingReady false, and logs no synchronization failure; access
  changes start or stop the stream.
- Hide the unacknowledged completion of the Session the visible, focused
  main view retains; manual marks stay visible, completionFailed follows
  completionUnread, and the reminder returns on blur, hiding, or a switch.
- Declare ctx.sessionStatus on Context and restore its SERVICE_PAGE and
  SERVICE_ROLES entries; the service and SessionRead* types document on
  docs/subsystems/web-client.md, which now owns the reading section with
  the failed field.
- Document that a Host plugin reload can leave the Client with a terminal
  error until a page reload; drop the redundant types import and the
  unused publish() result.
- Archived Sessions read as read and offer no reading mark in the row
  menu or the toggle-read shortcut.
- session.toggleRead names the open dialog, open panel, or archived
  Session that blocks it instead of asking to select a Session.
- isRemoteStreamCarrierFailure rejects a RemoteError from the Host even
  when it carries gateway/carrier-lost; the code is Client-local.
- ./types is types-only like ui-trajectory, and files no longer ship
  lib/types JavaScript.

* 🐛 fix(session): close the remaining Session status review gaps

- The Gateway Client exports isRemoteStreamCarrierFailure, and the
  terminal view uses it, so a Host RemoteError carrying the carrier code
  shows as failed rather than disconnected.
- Each access grant's reading stream carries a token: frames a revoked
  or superseded stream still delivers are discarded, and cleanup waits
  for disposal before leaving reading unavailable unless a newer grant
  is active.
- The status table hides the viewed Session's natural reminder only
  while that Session is open; the panel case is a documented limitation.
- The README limitation and the upgrade guide state that only the
  main-view switch rule, including a reload restore, clears manual
  unread automatically.
- Add the missing blank line before the next heading in the web-client
  reading section.

* ♻️ refactor(session): install reading under the Session status table

- apply returns to master's form plus one line: UiSessionStatus is the
  root, published as the useSessionStatus source, and installReading()
  from the new src/client/read.ts follows Host reading records into it.
  UiSessionStatus takes master's three constructor parameters and
  creates its own SessionReadModel as the package-internal `reading`
  member; installSessionStatus is removed and acknowledge.ts stays a
  separate file.
- The viewed Session's snapshot subscription republishes the table only
  when its openState changes, so streamed events do not rebuild it.
- Remove the obsolete Dev Note sentence about failure outcomes.
- session.toggleRead passes when the Peer may not mark reading, matching
  the row menu, and reports readingUnavailable only while unsynchronized.

---------

Co-authored-by: imccyu <[email protected]>
Co-authored-by: imccyu <[email protected]>
2026-11-12 05:35:57 +00:00

219 lines
9.8 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 } 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 runningTrigger = page.getByRole('button', { name: '1 subagent', exact: true })
await runningTrigger.waitFor({ timeout: 10_000 })
expect(await runningTrigger.locator('[data-state="ongoing"]').count()).toBe(1)
// 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()!
try {
const jobTrigger = page.getByRole('button', { name: '1 background job', exact: true })
await jobTrigger.waitFor()
expect(await jobTrigger.evaluate(element => document.getElementById(element.getAttribute('aria-describedby')!)?.textContent)).toBe('Running')
const controls = [
{ trigger: runningTrigger, icon: '[data-icon="dsw-icon-users-outline-regular"]', count: '[data-subagent-count]' },
{ trigger: jobTrigger, icon: '[data-icon="dsw-icon-layers-outline-regular"]', count: '[data-job-count]' },
]
for (const { trigger, icon, count } of controls) {
expect(await trigger.locator(count).isVisible()).toBe(true)
expect(await trigger.locator('[data-state="ongoing"]').isVisible()).toBe(true)
expect(await trigger.locator(icon).isVisible()).toBe(false)
}
await runningTrigger.focus()
await page.setViewportSize({ width: 390, height: 700 })
for (const { trigger, icon, count } of controls) {
await expect.poll(() => trigger.locator(count).isVisible()).toBe(false)
expect(await trigger.locator(icon).isVisible()).toBe(true)
expect(await trigger.locator('[data-state="ongoing"]').isVisible()).toBe(false)
}
expect(await runningTrigger.evaluate(element => element === document.activeElement)).toBe(true)
expect(await jobTrigger.evaluate(element => document.getElementById(element.getAttribute('aria-describedby')!)?.textContent)).toBe('Running')
await compareOrRefreshGolden(
join(SNAPSHOT_DIR, 'compact-running.expected.md'),
await captureStableAria(page, 'header:has([data-subagent-action])', scaffold.workspaceCwd),
MODE,
)
await saveFailureShot(page, 'web-e2e-compact-running-icons')
await runningTrigger.click()
const members = page.locator('[data-subagent-panel]')
await members.waitFor()
expect(await members.getByRole('treeitem').locator('[data-state="ongoing"]').isVisible()).toBe(true)
await page.keyboard.press('Escape')
await jobTrigger.click()
const jobs = page.getByRole('list', { name: 'Background jobs', exact: true })
await jobs.waitFor()
expect(await jobs.locator('[data-state="ongoing"]').isVisible()).toBe(true)
await page.keyboard.press('Escape')
await page.setViewportSize(viewport)
for (const { trigger, icon, count } of controls) {
await expect.poll(() => trigger.locator(count).isVisible()).toBe(true)
expect(await trigger.locator('[data-state="ongoing"]').isVisible()).toBe(true)
expect(await trigger.locator(icon).isVisible()).toBe(false)
}
} finally {
completion.resolve({ status: 'completed' })
await scaffold.ctx.jobs.wait(jobId, 5_000, ownerId)
await page.keyboard.press('Escape')
await page.setViewportSize(viewport)
}
await assertFixtureInventory(SNAPSHOT_DIR, ['owner-running.expected.md', 'compact-running.expected.md'])
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
})
})