browser-plugin.spec.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. ctx.provide('conversation', {})
  75. }
  76. /** Boot the plugin over fake slash/sessions faces; returns the captured source and the list face. */
  77. async function fullBench(sessions: SessionSummary[]) {
  78. const ctx = new Context()
  79. let captured: SlashSource | undefined
  80. const face = sessionsWith(sessions)
  81. ctx.provide('slash', { registerSource: (src: SlashSource) => { captured = src; return () => {} } })
  82. ctx.provide('sessions', face)
  83. await provideSlotFaces(ctx)
  84. await ctx.plugin({ inject: ['slots'], apply: applyLocale }).await()
  85. await ctx.plugin({ inject: [...inject], apply }).await()
  86. return { source: captured!, face, ctx }
  87. }
  88. /** Source-only bench for the behavior-contract suites. */
  89. async function bench(sessions: SessionSummary[]): Promise<SlashSource> {
  90. return (await fullBench(sessions)).source
  91. }
  92. const FAMILY: SessionSummary[] = [
  93. summary({ id: sid('parent'), displayTitle: 'parent', running: true }),
  94. summary({ id: sid('c1'), parentId: sid('parent'), displayTitle: 'worker-1', running: true }),
  95. summary({ id: sid('c2'), parentId: sid('parent'), displayTitle: 'worker-2', running: true }),
  96. // Filtered out: not running / other parent / label miss.
  97. summary({ id: sid('c3'), parentId: sid('parent'), displayTitle: 'worker-3', running: false }),
  98. summary({ id: sid('c4'), parentId: sid('other'), displayTitle: 'worker-4', running: true }),
  99. summary({ id: sid('c5'), parentId: sid('parent'), displayTitle: 'scout', running: true }),
  100. ]
  101. const proj = (id: string): ClientSessionContext => ({ sessionId: sid(id) })
  102. const req = (query: string) =>
  103. ({ query, position: 'inline' as const, signal: new AbortController().signal })
  104. describe('apply', () => {
  105. it('declares the services it binds', () => {
  106. expect(inject).toEqual(['slash', 'sessions', 'conversation', 'slots', 'locale'])
  107. })
  108. it('registers the "@" subagent source; disposal frees the name (HMR safety)', async () => {
  109. const ctx = new Context()
  110. await ctx.plugin(SlashService).await()
  111. ctx.provide('sessions', sessionsWith(FAMILY))
  112. await provideSlotFaces(ctx)
  113. await ctx.plugin({ inject: ['slots'], apply: applyLocale }).await()
  114. const fiber = ctx.plugin({ inject: [...inject], apply })
  115. await fiber.await()
  116. const slash = ctx.get('slash') as SlashService
  117. const rival = {
  118. trigger: '@' as const,
  119. name: 'subagent',
  120. candidates: () => Promise.resolve([]),
  121. onPick: () => undefined,
  122. }
  123. // Live registration holds the (trigger, name) seat…
  124. expect(() => slash.registerSource(rival)).toThrow(/already registered/)
  125. // …and fiber teardown releases it.
  126. await fiber.dispose()
  127. expect(() => slash.registerSource(rival)).not.toThrow()
  128. })
  129. it('registers catalog actions and selects read-only subagent composers from session facts', async () => {
  130. const { ctx, face } = await fullBench(FAMILY)
  131. const catalogEntry = ctx.slots.entries('conversation.session.header.actions')
  132. .find(entry => entry.component === SubagentCatalogAction)!
  133. const actions = (catalogEntry.inject as unknown as (id: SessionId) => SubagentCatalogInjected)(sid('parent'))
  134. const address: SubagentAddress = {
  135. parentSessionId: sid('parent'),
  136. childSessionId: sid('c1'),
  137. mode: 'continuable',
  138. }
  139. actions.openChild(address)
  140. actions.refresh(sid('parent'))
  141. actions.setCatalogOpen(sid('parent'), true)
  142. expect(face.actionCalls).toEqual([
  143. { method: 'openSubagent', args: [address] },
  144. { method: 'refreshSubagents', args: [sid('parent')] },
  145. { method: 'setSubagentCatalogOpen', args: [sid('parent'), true] },
  146. ])
  147. const composerEntry = ctx.slots.entries('conversation.composer')
  148. .find(entry => entry.component === SubagentReadOnlyComposer)!
  149. const select = composerEntry.select as (owner: ComposerChainProps) => SubagentReadOnlyMatch | null
  150. const owner = (
  151. subagent: ConversationSnapshot['subagent'] | undefined,
  152. ): ComposerChainProps => ({
  153. interactions: [],
  154. session: subagent === undefined
  155. ? undefined
  156. : ({ subagent } 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. expect(select(owner({ address, parentAvailable: true }))).toBeNull()
  163. expect(select(owner({ address, parentAvailable: false })))
  164. .toEqual({ reason: 'parent-unavailable' })
  165. })
  166. })
  167. describe('candidates', () => {
  168. it('returns running children of the projected session, filtered by label containment', async () => {
  169. const source = await bench(FAMILY)
  170. await expect(source.candidates(proj('parent'), req('worker'))).resolves.toEqual([
  171. { name: 'worker-1' }, { name: 'worker-2' },
  172. ])
  173. })
  174. it('matches every running child on an empty query (containment, not prefix)', async () => {
  175. const source = await bench(FAMILY)
  176. await expect(source.candidates(proj('parent'), req(''))).resolves.toEqual([
  177. { name: 'worker-1' }, { name: 'worker-2' }, { name: 'scout' },
  178. ])
  179. })
  180. it('is candidate-less for a session with no children', async () => {
  181. const source = await bench(FAMILY)
  182. await expect(source.candidates(proj('childless'), req(''))).resolves.toEqual([])
  183. })
  184. })
  185. describe('lexicon', () => {
  186. it('synchronously serves the projected session\'s full running-children roster', async () => {
  187. const source = await bench(FAMILY)
  188. expect(source.lexicon!(proj('parent'))).toEqual(['worker-1', 'worker-2', 'scout'])
  189. expect(source.lexicon!(proj('childless'))).toEqual([])
  190. })
  191. it('subscribeLexicon forwards the session-list change feed and unsubscribes cleanly', async () => {
  192. const { source, face } = await fullBench(FAMILY)
  193. let notified = 0
  194. const off = source.subscribeLexicon!(proj('parent'), () => { notified += 1 })
  195. expect(face.listenerCount()).toBe(1)
  196. face.notify()
  197. expect(notified).toBe(1)
  198. off()
  199. expect(face.listenerCount()).toBe(0)
  200. face.notify()
  201. expect(notified).toBe(1)
  202. })
  203. })
  204. describe('pick and codec', () => {
  205. it('onPick returns the literal @label text with a closing space (decision 21)', async () => {
  206. const source = await bench(FAMILY)
  207. const outcome = source.onPick({
  208. candidate: { name: 'worker-1' },
  209. session: proj('parent'),
  210. position: 'inline',
  211. via: 'menu',
  212. span: { start: 4, end: 8, draftRev: 3 },
  213. })
  214. expect(outcome).toEqual({ text: '@worker-1 ' })
  215. })
  216. it('codec projects clipboard `@label` and serializes the same raw label this phase', async () => {
  217. const source = await bench(FAMILY)
  218. expect(source.codec!.clipboardText('worker-1')).toBe('@worker-1')
  219. await expect(source.codec!.serialize('worker-1', new AbortController().signal))
  220. .resolves.toBe('@worker-1')
  221. })
  222. })
  223. describe('adjudication', () => {
  224. it('never participates: no matchSpace/matchEnter hooks on the subagent source', async () => {
  225. const source = await bench(FAMILY)
  226. expect('matchSpace' in source && source.matchSpace !== undefined).toBe(false)
  227. expect('matchEnter' in source && source.matchEnter !== undefined).toBe(false)
  228. })
  229. })