browser-plugin.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /**
  2. * ui-subagent browser half: source registration (duplicate-name proof) +
  3. * fiber-teardown removal (HMR safety) against the real SlashService, then
  4. * the source behavior contract driven directly on the captured source with
  5. * real ClientSessionContext projections — zero-RPC candidates from the root
  6. * session list (running children of the projected session, label-contains
  7. * filtering, childless session → empty), the synchronous lexicon roster,
  8. * pick → plain-text outcome (the plain-text-reference decision:
  9. * .agents/notes/implemented/architecture/2026-07-25-web-input-machine-and-slash-pipeline.md),
  10. * and the reference codec's two
  11. * projections. Direct driving is deliberate: this spec owns only the
  12. * source's own contract.
  13. */
  14. import { Context } from '@deepseek-ai/cordis'
  15. import { stubSettingsScope } from '@deepseek-ai/dsh-client-test-runtime'
  16. import { describe, expect, it } from 'vitest'
  17. import {
  18. SlotsService, type ConversationSnapshot, type SessionId, type SessionListState,
  19. type SessionSummary, type SubagentAddress,
  20. } from '@deepseek-ai/dsh-client-runtime/client'
  21. import type { ComposerChainProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
  22. import { SlashService } from '@deepseek-ai/dsh-client-ui-slash/client'
  23. import type { ClientSessionContext, SlashSource } from '@deepseek-ai/dsh-client-ui-slash/client'
  24. import { apply as applyLocale, inject as localeInject } from '@deepseek-ai/dsh-client-locale/client'
  25. import {
  26. SubagentCatalogAction, type SubagentCatalogInjected,
  27. } from '../src/client/SubagentCatalogAction.tsx'
  28. import {
  29. SubagentReadOnlyComposer, type SubagentReadOnlyMatch,
  30. } from '../src/client/SubagentReadOnlyComposer.tsx'
  31. import { apply, inject } from '../src/client/index.ts'
  32. function summary(partial: Partial<SessionSummary> & { id: SessionId }): SessionSummary {
  33. return {
  34. displayTitle: partial.id,
  35. running: false,
  36. updatedAt: 0,
  37. ...partial,
  38. } as SessionSummary
  39. }
  40. const sid = (id: string) => id as SessionId
  41. /** Fake root sessions face: the list snapshot the source closes over. */
  42. function sessionsWith(sessions: SessionSummary[]) {
  43. const byId: Record<string, SessionSummary> = {}
  44. for (const s of sessions) byId[s.id] = s
  45. const snapshot = { ids: sessions.map(s => s.id), byId, current: undefined } as unknown as SessionListState
  46. const subs = new Set<() => void>()
  47. const actionCalls: { method: string; args: unknown[] }[] = []
  48. return {
  49. list: {
  50. getSnapshot: () => snapshot,
  51. subscribe: (fn: () => void) => { subs.add(fn); return () => { subs.delete(fn) } },
  52. },
  53. notify: () => { for (const fn of [...subs]) fn() },
  54. listenerCount: () => subs.size,
  55. actionCalls,
  56. openSubagent: (address: SubagentAddress) => {
  57. actionCalls.push({ method: 'openSubagent', args: [address] })
  58. },
  59. refreshSubagents: (parentSessionId: SessionId) => {
  60. actionCalls.push({ method: 'refreshSubagents', args: [parentSessionId] })
  61. return Promise.resolve()
  62. },
  63. setSubagentCatalogOpen: (parentSessionId: SessionId, open: boolean) => {
  64. actionCalls.push({ method: 'setSubagentCatalogOpen', args: [parentSessionId, open] })
  65. },
  66. }
  67. }
  68. async function provideSlotFaces(ctx: Context): Promise<void> {
  69. await ctx.plugin(SlotsService).await()
  70. ctx.slots.register({
  71. name: 'root',
  72. children: {
  73. 'conversation.session.header.actions': { kind: 'list', scope: 'session' },
  74. 'conversation.composer': { kind: 'chain', scope: 'session' },
  75. },
  76. } as never, () => null)
  77. }
  78. /** Boot the plugin over fake slash/sessions faces; returns the captured source and the list face. */
  79. async function fullBench(sessions: SessionSummary[]) {
  80. const ctx = new Context()
  81. let captured: SlashSource | undefined
  82. const face = sessionsWith(sessions)
  83. ctx.provide('slash', { registerSource: (src: SlashSource) => { captured = src; return () => {} } })
  84. ctx.provide('sessions', face)
  85. ctx.provide('connection', { api: { settings: {} }, isLoopback: false } as never)
  86. // ui-theme's Appearance row binds a durable scope through these two.
  87. ctx.provide('remote', { $on: () => () => {} } as never)
  88. ctx.provide('settingsScope', { bind: () => stubSettingsScope().scope } as never)
  89. await provideSlotFaces(ctx)
  90. await ctx.plugin({ inject: localeInject, apply: applyLocale }).await()
  91. await ctx.plugin({ inject: [...inject], apply }).await()
  92. return { source: captured!, face, ctx }
  93. }
  94. /** Source-only bench for the behavior-contract suites. */
  95. async function bench(sessions: SessionSummary[]): Promise<SlashSource> {
  96. return (await fullBench(sessions)).source
  97. }
  98. const FAMILY: SessionSummary[] = [
  99. summary({ id: sid('parent'), displayTitle: 'parent', running: true }),
  100. summary({ id: sid('c1'), parentId: sid('parent'), displayTitle: 'worker-1', running: true }),
  101. summary({ id: sid('c2'), parentId: sid('parent'), displayTitle: 'worker-2', running: true }),
  102. // Filtered out: not running / other parent / label miss.
  103. summary({ id: sid('c3'), parentId: sid('parent'), displayTitle: 'worker-3', running: false }),
  104. summary({ id: sid('c4'), parentId: sid('other'), displayTitle: 'worker-4', running: true }),
  105. summary({ id: sid('c5'), parentId: sid('parent'), displayTitle: 'scout', running: true }),
  106. ]
  107. const proj = (id: string): ClientSessionContext => ({ sessionId: sid(id) })
  108. const req = (query: string) =>
  109. ({ query, position: 'inline' as const, signal: new AbortController().signal })
  110. describe('apply', () => {
  111. it('declares the services it binds', () => {
  112. expect(inject).toEqual(['slash', 'sessions', 'slots', 'locale'])
  113. })
  114. it('registers the "@" subagent source; disposal frees the name (HMR safety)', async () => {
  115. const ctx = new Context()
  116. await ctx.plugin(SlashService).await()
  117. ctx.provide('sessions', sessionsWith(FAMILY))
  118. ctx.provide('connection', { api: { settings: {} }, isLoopback: false } as never)
  119. // ui-theme's Appearance row binds a durable scope through these two.
  120. ctx.provide('remote', { $on: () => () => {} } as never)
  121. ctx.provide('settingsScope', { bind: () => stubSettingsScope().scope } as never)
  122. await provideSlotFaces(ctx)
  123. await ctx.plugin({ inject: localeInject, apply: applyLocale }).await()
  124. const fiber = ctx.plugin({ inject: [...inject], apply })
  125. await fiber.await()
  126. const slash = ctx.get('slash') as SlashService
  127. const rival = {
  128. trigger: '@' as const,
  129. name: 'subagent',
  130. candidates: () => Promise.resolve([]),
  131. onPick: () => undefined,
  132. }
  133. // Live registration holds the (trigger, name) seat…
  134. expect(() => slash.registerSource(rival)).toThrow(/already registered/)
  135. // …and fiber teardown releases it.
  136. await fiber.dispose()
  137. expect(() => slash.registerSource(rival)).not.toThrow()
  138. })
  139. it('registers catalog actions and selects read-only subagent composers from session facts', async () => {
  140. const { ctx, face } = await fullBench(FAMILY)
  141. const catalogEntry = ctx.slots.entries('conversation.session.header.actions')
  142. .find(entry => entry.component === SubagentCatalogAction)!
  143. const actions = (catalogEntry.inject as unknown as (id: SessionId) => SubagentCatalogInjected)(sid('parent'))
  144. const address: SubagentAddress = {
  145. parentSessionId: sid('parent'),
  146. childSessionId: sid('c1'),
  147. mode: 'continuable',
  148. }
  149. actions.openChild(address)
  150. actions.refresh(sid('parent'))
  151. actions.setCatalogOpen(sid('parent'), true)
  152. expect(face.actionCalls).toEqual([
  153. { method: 'openSubagent', args: [address] },
  154. { method: 'refreshSubagents', args: [sid('parent')] },
  155. { method: 'setSubagentCatalogOpen', args: [sid('parent'), true] },
  156. ])
  157. const composerEntry = ctx.slots.entries('conversation.composer')
  158. .find(entry => entry.component === SubagentReadOnlyComposer)!
  159. const select = composerEntry.select as (owner: ComposerChainProps) => SubagentReadOnlyMatch | null
  160. const owner = (
  161. subagent: ConversationSnapshot['subagent'] | undefined,
  162. running = false,
  163. ): ComposerChainProps => ({
  164. interactions: [],
  165. session: subagent === undefined
  166. ? undefined
  167. : ({ subagent, running } as unknown as ConversationSnapshot),
  168. })
  169. expect(select(owner(undefined))).toBeNull()
  170. expect(select(owner(null))).toBeNull()
  171. expect(select(owner({ address: { ...address, mode: 'one-shot' }, parentAvailable: true })))
  172. .toEqual({ reason: 'one-shot' })
  173. // One-shot stays read-only even while running: it has no stop action.
  174. expect(select(owner({ address: { ...address, mode: 'one-shot' }, parentAvailable: true }, true)))
  175. .toEqual({ reason: 'one-shot' })
  176. expect(select(owner({ address, parentAvailable: true }))).toBeNull()
  177. expect(select(owner({ address, parentAvailable: false })))
  178. .toEqual({ reason: 'parent-unavailable' })
  179. // A RUNNING parent-offline continuable yields the default composer, whose
  180. // disabled input still carries the primary Stop; stopped, it takes back over.
  181. expect(select(owner({ address, parentAvailable: false }, true))).toBeNull()
  182. })
  183. })
  184. describe('candidates', () => {
  185. it('returns running children of the projected session, filtered by label containment', async () => {
  186. const source = await bench(FAMILY)
  187. await expect(source.candidates(proj('parent'), req('worker'))).resolves.toEqual([
  188. { name: 'worker-1' }, { name: 'worker-2' },
  189. ])
  190. })
  191. it('matches every running child on an empty query (containment, not prefix)', async () => {
  192. const source = await bench(FAMILY)
  193. await expect(source.candidates(proj('parent'), req(''))).resolves.toEqual([
  194. { name: 'worker-1' }, { name: 'worker-2' }, { name: 'scout' },
  195. ])
  196. })
  197. it('is candidate-less for a session with no children', async () => {
  198. const source = await bench(FAMILY)
  199. await expect(source.candidates(proj('childless'), req(''))).resolves.toEqual([])
  200. })
  201. })
  202. describe('lexicon', () => {
  203. it('synchronously serves the projected session\'s full running-children roster', async () => {
  204. const source = await bench(FAMILY)
  205. expect(source.lexicon!(proj('parent'))).toEqual(['worker-1', 'worker-2', 'scout'])
  206. expect(source.lexicon!(proj('childless'))).toEqual([])
  207. })
  208. it('subscribeLexicon forwards the session-list change feed and unsubscribes cleanly', async () => {
  209. const { source, face } = await fullBench(FAMILY)
  210. let notified = 0
  211. const off = source.subscribeLexicon!(proj('parent'), () => { notified += 1 })
  212. expect(face.listenerCount()).toBe(1)
  213. face.notify()
  214. expect(notified).toBe(1)
  215. off()
  216. expect(face.listenerCount()).toBe(0)
  217. face.notify()
  218. expect(notified).toBe(1)
  219. })
  220. })
  221. describe('pick and codec', () => {
  222. it('onPick returns the literal @label text with a closing space', async () => {
  223. const source = await bench(FAMILY)
  224. const outcome = source.onPick({
  225. candidate: { name: 'worker-1' },
  226. session: proj('parent'),
  227. position: 'inline',
  228. via: 'menu',
  229. span: { start: 4, end: 8, draftRev: 3 },
  230. })
  231. expect(outcome).toEqual({ text: '@worker-1 ' })
  232. })
  233. it('codec projects clipboard `@label` and serializes the same raw label this phase', async () => {
  234. const source = await bench(FAMILY)
  235. expect(source.codec!.clipboardText('worker-1')).toBe('@worker-1')
  236. await expect(source.codec!.serialize('worker-1', new AbortController().signal))
  237. .resolves.toBe('@worker-1')
  238. })
  239. })
  240. describe('adjudication', () => {
  241. it('never participates: no matchSpace/matchEnter hooks on the subagent source', async () => {
  242. const source = await bench(FAMILY)
  243. expect('matchSpace' in source && source.matchSpace !== undefined).toBe(false)
  244. expect('matchEnter' in source && source.matchEnter !== undefined).toBe(false)
  245. })
  246. })