Files
apes-sidebar/tests/subagent-live-polling.spec.tsx
T
Menghuan1918 6586e3e2d3 feat: adapt to DSH 0.1.7-alpha.1 and yield the read-only previews
DSH 0.1.7-alpha.1 is 1299 commits past 0.1.6-alpha.2 and rewrites four
contracts this plugin was built on. The peer floor moves to
^0.1.7-alpha.1 (semver's prerelease rule means ^0.1.6-alpha.2 can never
match a 0.1.7 prerelease); 0.1.6-alpha.2 and earlier stay on v0.19.1.
Released as 0.21.0-alpha.1 (dist-tag alpha).

Hard breaks:
- dsh-settings was rewritten: register(ns, schema) is gone, a form is
  addressed by the plugin row's Loader entry id and read from the
  module's exported Config. The preferences are merged into Config and
  marked volatile — which requires DSH's own schemastery, because only
  that build wraps a volatile field in the cosmokit reference the
  loader's volatile commit walks. With the public package a settings
  write reports success and revision 1 while the effective value never
  changes.
- ui-primitives renamed its whole icon family (IconXxx14/16 ->
  IconXxxRegular/Medium): 26 imported symbols, 17 files. The failing
  mode is render-time, not load-time. Five call sites that relied on the
  old 14px default now pass size={14} explicitly.
- Session format v4 rejects source.kind === 'plugin'; the side-chat
  boundary injection now writes plugin:dsh-better-sidebar, the same kind
  DSH's own v3->v4 migration produces, so historical threads survive.
  Tool results moved to role 'tool' with top-level content/isError; all
  four parsers accept both shapes.
- The client session snapshot dropped subagentsByParent/jobsBySession
  and the on-demand subagent-catalog observation API. The Tasks page
  reads projectionsBySession and a new jobs.list route.

Yields and convergence:
- The read-only previews go to DSH's documentpreview (Office->PDF, a
  spreadsheet worker, zoom, per-directory refresh); editor.canOpen
  refuses those 26 extensions. Markdown, HTML (with its sandbox
  switches) and the editable code buffer stay.
- The host browser kind is desktop-profile-only now, so the web e2e
  lanes expect no browser entry and assert its absence.
- Link takeover claims only urlTarget links and passes the rest to the
  host, fixing a regression from the 0.1.6 round: the fallback pointed
  at a 'browser' type the plugin no longer registers, so http links in
  its own markdown did nothing.

Also fixed, found along the way:
- The file tree refreshes live (new directory watch over the plugin's
  own socket), since the plugin owns the `files` kind.
- ctx.sessions.list has no `current` field at either tag; the three
  readers were dead. They now use ctx.sidebarRight.mounted.
- package.json.files was missing lib/client-locale.js.
- Two genuinely dead call sites: sessions.openSubagent/open/
  refreshSubagents do not exist on the current baseline, so the
  topology click, the jump-back and the retry were all no-ops.
- The test harness window shim lacked addEventListener, which the 0.1.7
  primitives call at module-evaluation time; and the e2e token exchange
  needs Playwright's request stack, not Node's fetch.
2026-09-22 17:09:08 +08:00

262 lines
10 KiB
TypeScript

/**
* Component-level regression for the Subagent page live preview polling:
* one shared `subagents.live` request per refresh, never a per-child
* `subagents.history` call, and never a second in-flight request while a
* slow host is still answering.
*/
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { act } from 'react-dom/test-utils'
import { renderRoot } from './test-utils.ts'
import { SubagentView } from '../src/client/SubagentView.tsx'
import type { Context, SidebarSessionList } from '../src/context-types.ts'
/** A subscribable sessions-list snapshot (mirror of the runtime list feed). */
function makeStore(initial: SidebarSessionList) {
let snapshot = initial
const listeners = new Set<() => void>()
return {
getSnapshot: () => snapshot,
subscribe: (fn: () => void) => {
listeners.add(fn)
return () => { listeners.delete(fn) }
},
set(next: SidebarSessionList) {
snapshot = next
for (const fn of [...listeners]) fn()
},
}
}
type Store = ReturnType<typeof makeStore>
/** The client context face SubagentView touches; history is spied for the
* regression assertion (the new page must never call it). */
function makeCtx(store: Store, historySpy: ReturnType<typeof vi.fn>): Context {
return {
sessions: {
list: store,
openSubagent: () => {},
open: () => {},
},
connection: {
api: {
sessions: { history: historySpy },
subagents: { history: historySpy },
},
},
} as unknown as Context
}
function jsonResponse(value: unknown): Response {
return { ok: true, status: 200, json: async () => value } as unknown as Response
}
/** One `subagentCatalog` projection row (DSH 0.1.7 shape). */
function entry(
id: string,
mode: 'one-shot' | 'continuable' | 'unknown',
label?: string,
): { id: string; createdAt: number; mode: 'one-shot' | 'continuable' | 'unknown'; label?: string } {
return { id, createdAt: 1_000, mode, ...(label === undefined ? {} : { label }) }
}
/** One session's loaded projection snapshot. */
function ready(entries: ReturnType<typeof entry>[]) {
return { values: { subagentCatalog: entries }, state: 'ready' as const, error: null }
}
/**
* A topology snapshot with two direct subagents and their catalogs. The rows
* carry no activity of their own any more: the live channel below is what
* marks a child running.
*/
function runningSnapshot(): SidebarSessionList {
return {
byId: {
root: { id: 'root', displayTitle: '主会话' },
a: { id: 'a', displayTitle: 'A', origin: 'subagent', parentId: 'root', running: true },
b: { id: 'b', displayTitle: 'B', origin: 'subagent', parentId: 'root', running: true },
},
projectionsBySession: {
root: ready([entry('a', 'one-shot', 'A'), entry('b', 'one-shot', 'B')]),
a: ready([]),
b: ready([]),
},
}
}
/** The same tree re-rooted under a new ancestor ('grand' becomes the root). */
function reRootedSnapshot(): SidebarSessionList {
return {
byId: {
grand: { id: 'grand', displayTitle: '主会话' },
root: { id: 'root', displayTitle: 'R', origin: 'subagent', parentId: 'grand', running: true },
a: { id: 'a', displayTitle: 'A', origin: 'subagent', parentId: 'root', running: true },
b: { id: 'b', displayTitle: 'B', origin: 'subagent', parentId: 'root', running: true },
},
projectionsBySession: {
grand: ready([entry('root', 'continuable', 'R')]),
root: ready([entry('a', 'one-shot', 'A'), entry('b', 'one-shot', 'B')]),
a: ready([]),
b: ready([]),
},
}
}
beforeEach(() => {
Object.defineProperty(globalThis.navigator, 'language', { value: 'zh-CN', configurable: true })
})
afterEach(() => {
vi.unstubAllGlobals()
vi.useRealTimers()
for (const el of document.querySelectorAll('body > div')) el.remove()
})
describe('SubagentView live polling', () => {
it('sends one subagents.live per poll and never calls per-child history', async () => {
vi.useFakeTimers()
const historySpy = vi.fn()
const liveCalls: string[] = []
vi.stubGlobal('fetch', async (url: string | URL | Request, init?: RequestInit) => {
const method = String(url).split('/').pop()
if (method === 'subagents.live') {
const body = JSON.parse(String(init?.body)) as { rootSessionId?: string }
liveCalls.push(body.rootSessionId ?? '')
return jsonResponse({ ok: true, value: { live: { a: {}, b: {} } } })
}
if (method === 'jobs.list') return jsonResponse({ ok: true, value: { jobs: [] } })
throw new Error(`unexpected fetch ${String(url)}`)
})
const store = makeStore(runningSnapshot())
const { container, unmount } = renderRoot(
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store, historySpy) }),
)
// Initial load plus the first scheduled tick.
await act(async () => { await Promise.resolve() })
expect(liveCalls).toEqual(['root'])
expect(historySpy).not.toHaveBeenCalled()
expect(container.textContent).toContain('思考中…')
await act(async () => { await vi.advanceTimersByTimeAsync(3_000) })
expect(liveCalls).toEqual(['root', 'root'])
expect(historySpy).not.toHaveBeenCalled()
unmount()
})
it('never starts a second request while one is in flight', async () => {
vi.useFakeTimers()
const historySpy = vi.fn()
const liveCalls: string[] = []
let resolveFirst: ((response: Response) => void) | undefined
vi.stubGlobal('fetch', (url: string | URL | Request, init?: RequestInit) => {
const method = String(url).split('/').pop()
if (method === 'subagents.live') {
const body = JSON.parse(String(init?.body)) as { rootSessionId?: string }
liveCalls.push(body.rootSessionId ?? '')
return new Promise<Response>((resolve) => { resolveFirst = resolve })
}
if (method === 'jobs.list') return jsonResponse({ ok: true, value: { jobs: [] } })
throw new Error(`unexpected fetch ${String(url)}`)
})
const store = makeStore(runningSnapshot())
const { unmount } = renderRoot(
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store, historySpy) }),
)
await act(async () => { await Promise.resolve() })
expect(liveCalls).toEqual(['root'])
expect(resolveFirst).toBeTypeOf('function')
// While the first request is pending, no timer can fire a second one.
await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })
expect(liveCalls).toEqual(['root'])
// Settle the first request; only then does the next 3s tick fire.
await act(async () => {
resolveFirst?.(jsonResponse({ ok: true, value: { live: { a: {}, b: {} } } }))
await Promise.resolve()
})
await act(async () => { await vi.advanceTimersByTimeAsync(3_000) })
expect(liveCalls).toEqual(['root', 'root'])
expect(historySpy).not.toHaveBeenCalled()
unmount()
})
it('stops polling and drops the in-flight request when the page hides', async () => {
vi.useFakeTimers()
const historySpy = vi.fn()
const liveCalls: string[] = []
let resolveFirst: ((response: Response) => void) | undefined
vi.stubGlobal('fetch', (url: string | URL | Request, init?: RequestInit) => {
const method = String(url).split('/').pop()
if (method === 'subagents.live') {
const body = JSON.parse(String(init?.body)) as { rootSessionId?: string }
liveCalls.push(body.rootSessionId ?? '')
return new Promise<Response>((resolve) => { resolveFirst = resolve })
}
if (method === 'jobs.list') return jsonResponse({ ok: true, value: { jobs: [] } })
throw new Error(`unexpected fetch ${String(url)}`)
})
const store = makeStore(runningSnapshot())
const { rerender, unmount } = renderRoot(
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store, historySpy) }),
)
await act(async () => { await Promise.resolve() })
expect(liveCalls).toEqual(['root'])
// Hide the page: the effect cleanup aborts the in-flight request and no
// timer may fire afterwards.
rerender(createElement(SubagentView, { sessionId: 'root', active: false, ctx: makeCtx(store, historySpy) }))
await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })
expect(liveCalls).toEqual(['root'])
// Settling the stale response must neither render nor schedule a poll.
await act(async () => {
resolveFirst?.(jsonResponse({ ok: true, value: { live: { a: { text: 'stale' } } } }))
await Promise.resolve()
})
await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })
expect(liveCalls).toEqual(['root'])
expect(historySpy).not.toHaveBeenCalled()
unmount()
})
it('clears the live map and re-polls when the topology root changes', async () => {
vi.useFakeTimers()
const historySpy = vi.fn()
const liveCalls: string[] = []
vi.stubGlobal('fetch', async (url: string | URL | Request, init?: RequestInit) => {
const method = String(url).split('/').pop()
if (method === 'subagents.live') {
const body = JSON.parse(String(init?.body)) as { rootSessionId?: string }
liveCalls.push(body.rootSessionId ?? '')
const live = body.rootSessionId === 'root' ? { a: { text: 'hello' } } : {}
return jsonResponse({ ok: true, value: { live } })
}
if (method === 'jobs.list') return jsonResponse({ ok: true, value: { jobs: [] } })
throw new Error(`unexpected fetch ${String(url)}`)
})
const store = makeStore(runningSnapshot())
const { container, unmount } = renderRoot(
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store, historySpy) }),
)
await act(async () => { await Promise.resolve() })
expect(liveCalls).toEqual(['root'])
expect(container.textContent).toContain('hello')
// The tree is re-rooted under a new ancestor: old rows must not leak.
store.set(reRootedSnapshot())
await act(async () => { await Promise.resolve() })
expect(liveCalls).toEqual(['root', 'grand'])
expect(container.textContent).not.toContain('hello')
expect(historySpy).not.toHaveBeenCalled()
unmount()
})
})