browser-plugin.spec.ts 11 KB

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