api-proxy-subagents.spec.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import type { SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  4. import { SessionQueryError } from '@deepseek-ai/dsh-session-query'
  5. import { SubagentError } from '@deepseek-ai/dsh-subagent'
  6. import { RpcId } from '../src/api/rpc.ts'
  7. import type { RpcRequest } from '../src/api/rpc.ts'
  8. import { createApiProxy } from '../src/api-proxy.ts'
  9. const sid = (value: string): SessionId => value as SessionId
  10. const PARENT = sid('parent')
  11. const CHILD = sid('child')
  12. function request<P>(payload: P): RpcRequest<P> {
  13. return { rpcId: RpcId('subagent-rpc'), payload }
  14. }
  15. function bench(options: {
  16. parentLive?: boolean
  17. childStatus?: 'idle' | 'running'
  18. entries?: object[]
  19. followupError?: Error
  20. listError?: Error
  21. readError?: Error
  22. historyParent?: SessionId
  23. } = {}) {
  24. const parent = { id: PARENT }
  25. const child = options.childStatus === undefined
  26. ? undefined
  27. : { id: CHILD, status: options.childStatus }
  28. const getAgent = vi.fn((id: SessionId) => {
  29. if (options.parentLive !== false && id === PARENT) return parent
  30. if (id === CHILD) return child
  31. return undefined
  32. })
  33. const listChildren = vi.fn(() => options.listError === undefined
  34. ? Promise.resolve(options.entries ?? [
  35. {
  36. kind: 'child', id: CHILD, mode: 'continuable', label: 'worker',
  37. activity: 'inactive', hasChildren: false,
  38. },
  39. ])
  40. : Promise.reject(options.listError))
  41. const followup = vi.fn((
  42. _parent: unknown,
  43. _childId: SessionId,
  44. _content: unknown,
  45. _delivery: { source: { kind: string; rpcId: RpcId }; signal: AbortSignal },
  46. ) => options.followupError === undefined
  47. ? Promise.resolve('message-1')
  48. : Promise.reject(options.followupError))
  49. const readSession = vi.fn(() => options.readError === undefined
  50. ? Promise.resolve({
  51. session: {
  52. version: 0, id: CHILD, createdAt: 1, parentSession: options.historyParent ?? PARENT,
  53. } satisfies SessionHeader,
  54. events: [
  55. { type: 'user/message', seq: 0, time: 1, data: { content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } } },
  56. ] as unknown as SessionEvent[],
  57. })
  58. : Promise.reject(options.readError))
  59. const ctx = new Context()
  60. ctx.provide('agents', { get: getAgent })
  61. ctx.provide('subagents', { listChildren, followup })
  62. ctx.provide('sessionQuery', { readSession })
  63. ctx.provide('userInteraction', { registerProvider: () => () => {} })
  64. const api = createApiProxy(ctx, {
  65. provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp',
  66. })
  67. return { api, getAgent, listChildren, readSession, followup, parent }
  68. }
  69. describe('subagent gateway', () => {
  70. it('lists the complete catalog and reports exact live-parent availability', async () => {
  71. const { api, listChildren } = bench({ parentLive: false, entries: [
  72. {
  73. kind: 'child', id: CHILD, mode: 'continuable', label: 'worker',
  74. activity: 'inactive', hasChildren: true,
  75. },
  76. {
  77. kind: 'child', id: sid('one-shot'), mode: 'one-shot',
  78. activity: 'inactive', hasChildren: false,
  79. },
  80. { kind: 'diagnostic', id: sid('bad'), reason: 'corrupt' },
  81. ] })
  82. const response = await api.subagents.list(request({ parentSessionId: PARENT }))
  83. expect(response.rpcId).toBe('subagent-rpc')
  84. expect(response.result).toMatchObject({
  85. ok: true,
  86. value: {
  87. parentAvailable: false,
  88. entries: [
  89. { kind: 'child', mode: 'continuable' },
  90. { kind: 'child', mode: 'one-shot' },
  91. { kind: 'diagnostic' },
  92. ],
  93. },
  94. })
  95. expect(listChildren).toHaveBeenCalledWith(PARENT, undefined)
  96. })
  97. it('derives catalog activity from the live child Agent rather than Session residency', async () => {
  98. const residentIdle = bench({ childStatus: 'idle', entries: [{
  99. kind: 'child', id: CHILD, mode: 'continuable', label: 'worker',
  100. activity: 'running', hasChildren: false,
  101. }] })
  102. expect((await residentIdle.api.subagents.list(request({ parentSessionId: PARENT }))).result)
  103. .toMatchObject({ ok: true, value: { entries: [{ activity: 'inactive' }] } })
  104. const running = bench({ childStatus: 'running' })
  105. expect((await running.api.subagents.list(request({ parentSessionId: PARENT }))).result)
  106. .toMatchObject({ ok: true, value: { entries: [{ activity: 'running' }] } })
  107. })
  108. it('reads a healthy direct child without looking up or activating any Agent', async () => {
  109. const { api, getAgent, readSession } = bench()
  110. const response = await api.subagents.history(request({
  111. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', maxMessages: 10,
  112. }))
  113. expect(response.result).toMatchObject({
  114. ok: true,
  115. value: { hasMore: false, events: [{ event: { type: 'user/message', seq: 0 } }] },
  116. })
  117. expect(readSession).toHaveBeenCalledWith(CHILD)
  118. expect(getAgent).not.toHaveBeenCalled()
  119. })
  120. it('reads one-shot history and rejects an address with the wrong mode', async () => {
  121. const oneShot = {
  122. kind: 'child', id: CHILD, mode: 'one-shot', label: 'batch',
  123. activity: 'inactive', hasChildren: false,
  124. }
  125. const { api, readSession } = bench({ entries: [oneShot] })
  126. expect((await api.subagents.history(request({
  127. parentSessionId: PARENT, childSessionId: CHILD, mode: 'one-shot',
  128. }))).result).toMatchObject({ ok: true })
  129. expect((await api.subagents.history(request({
  130. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable',
  131. }))).result).toMatchObject({ ok: false, error: { code: 'subagent-not-found' } })
  132. expect(readSession).toHaveBeenCalledTimes(1)
  133. })
  134. it('rejects a diagnostic address before reading history', async () => {
  135. const { api, readSession } = bench({ entries: [
  136. { kind: 'diagnostic', id: CHILD, reason: 'unsupported' },
  137. ] })
  138. const response = await api.subagents.history(request({
  139. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable',
  140. }))
  141. expect(response.result).toMatchObject({
  142. ok: false,
  143. error: {
  144. code: 'subagent-catalog-diagnostic',
  145. details: { parentSessionId: PARENT, childSessionId: CHILD, reason: 'unsupported' },
  146. },
  147. })
  148. expect(readSession).not.toHaveBeenCalled()
  149. })
  150. it('routes human content through the exact live parent with rpc attribution', async () => {
  151. const { api, parent, followup } = bench()
  152. const content = [{ type: 'text' as const, text: '继续' }]
  153. const signal = new AbortController().signal
  154. const response = await api.subagents.prompt(request({
  155. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content,
  156. }), signal)
  157. expect(response.result).toMatchObject({
  158. ok: true, value: { messageId: 'message-1' },
  159. })
  160. expect(followup).toHaveBeenCalledWith(
  161. parent,
  162. CHILD,
  163. content,
  164. { source: { kind: 'user', rpcId: RpcId('subagent-rpc') }, signal },
  165. )
  166. })
  167. it('fails before delivery when the parent is absent and maps continuation failures', async () => {
  168. const absent = bench({ parentLive: false })
  169. expect((await absent.api.subagents.prompt(request({
  170. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  171. }), new AbortController().signal)).result).toMatchObject({
  172. ok: false, error: { code: 'subagent-parent-unavailable' },
  173. })
  174. expect(absent.listChildren).not.toHaveBeenCalled()
  175. const failed = bench({ followupError: new SubagentError('draining', 'DRAINING') })
  176. expect((await failed.api.subagents.prompt(request({
  177. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  178. }), new AbortController().signal)).result).toMatchObject({
  179. ok: false, error: { code: 'subagent-delivery-unavailable' },
  180. })
  181. })
  182. it('maps history disappearance and hides unexpected backend details', async () => {
  183. const disappeared = bench({
  184. readError: new SessionQueryError('secret path', 'SESSION_QUERY_SESSION_NOT_FOUND'),
  185. })
  186. expect((await disappeared.api.subagents.history(request({
  187. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable',
  188. }))).result).toMatchObject({
  189. ok: false,
  190. error: {
  191. code: 'subagent-not-found',
  192. message: 'subagent disappeared during history read',
  193. details: { parentSessionId: PARENT, childSessionId: CHILD },
  194. },
  195. })
  196. const catalog = bench({ listError: new Error('secret descriptor') })
  197. expect((await catalog.api.subagents.list(request({
  198. parentSessionId: PARENT,
  199. }))).result).toMatchObject({
  200. ok: false,
  201. error: { code: 'internal', message: 'subagent catalog read failed' },
  202. })
  203. const prompt = bench({ followupError: new Error('secret provider') })
  204. expect((await prompt.api.subagents.prompt(request({
  205. parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable', content: [],
  206. }), new AbortController().signal)).result).toMatchObject({
  207. ok: false,
  208. error: { code: 'internal', message: 'subagent prompt failed' },
  209. })
  210. })
  211. })