browser-plugin.spec.ts 11 KB

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