tool-tasks.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { CallId } from '@deepseek-ai/dsh-llm'
  4. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  5. import ToolRegistry from '@deepseek-ai/dsh-tools'
  6. import AgentRegistry from '@deepseek-ai/dsh-agent'
  7. import type { Agent } from '@deepseek-ai/dsh-agent'
  8. import TaskService from '@deepseek-ai/dsh-tasks'
  9. import type { TaskHooks, TaskOutcome, TaskSnapshot, TaskStart } from '@deepseek-ai/dsh-tasks'
  10. import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks'
  11. import { statusLine } from '@deepseek-ai/dsh-tool-tasks'
  12. const agentRegistryDisposers = new WeakMap<Agent, () => void>()
  13. async function setup(config: ToolTasks.Config = {}) {
  14. const ctx = new Context()
  15. await ctx.plugin(SystemPrompt)
  16. await ctx.plugin(ToolRegistry)
  17. const agentsFiber = await ctx.plugin(AgentRegistry)
  18. await ctx.plugin(TaskService)
  19. const toolsFiber = await ctx.plugin(ToolTasks, config)
  20. return { ctx, agentsFiber, toolsFiber }
  21. }
  22. /**
  23. * A fake agent whose session token is `sessionId`, registered in `ctx.agents`.
  24. * The agent id is deliberately different so session authorization and exact
  25. * lifecycle ownership cannot be confused in tests.
  26. */
  27. function fakeAgent(ctx: Context, sessionId: string, inject: (...args: unknown[]) => void = () => {}): Agent {
  28. const scopeFiber = ctx.plugin(() => {})
  29. const agent = {
  30. id: `agent-${sessionId}`,
  31. ctx: scopeFiber.ctx,
  32. inject,
  33. session: { header: { version: 0, id: sessionId, createdAt: 0 } },
  34. } as unknown as Agent
  35. agentRegistryDisposers.set(agent, ctx.agents.register(agent))
  36. return agent
  37. }
  38. function detachAgent(agent: Agent): void {
  39. const dispose = agentRegistryDisposers.get(agent)
  40. if (dispose === undefined) throw new Error(`missing registry disposer for agent "${agent.id}"`)
  41. dispose()
  42. }
  43. /** A controllable producer start-spec (settle `done` on demand, record cancels). */
  44. function producer(overrides: Partial<Omit<TaskStart, 'run'> & TaskHooks> = {}) {
  45. let settle!: (outcome: TaskOutcome) => void
  46. const cancels: (string | undefined)[] = []
  47. const { kind = 'bash', label = 'sleep 60', owner, ...hookOverrides } = overrides
  48. const hooks: TaskHooks = {
  49. cancel(reason) { cancels.push(reason) },
  50. done: new Promise<TaskOutcome>((res) => { settle = res }),
  51. ...hookOverrides,
  52. }
  53. const spec: TaskStart = { kind, label, ...owner !== undefined ? { owner } : {}, run: () => hooks }
  54. return { spec, settle, cancels }
  55. }
  56. let callCounter = 0
  57. function call(ctx: Context, name: string, args: unknown, agent?: Agent) {
  58. return ctx.tools.execute({ callId: CallId(`call-${++callCounter}`), name, arguments: args, ...agent ? { agent } : {} })
  59. }
  60. function text(result: { content: { type: string; text?: string }[] }): string {
  61. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  62. }
  63. const tick = () => new Promise<void>(r => setTimeout(r, 0))
  64. describe('tool-tasks setup', () => {
  65. it('attaches the control surface on load and detaches it with the fiber', async () => {
  66. const { ctx, toolsFiber } = await setup()
  67. expect(() => ctx.tasks.start(producer().spec)).not.toThrow()
  68. await toolsFiber.dispose()
  69. expect(() => ctx.tasks.start(producer().spec)).toThrow('no control surface is attached')
  70. })
  71. it('rejects a config whose default wait exceeds the cap', async () => {
  72. const ctx = new Context()
  73. await ctx.plugin(SystemPrompt)
  74. await ctx.plugin(ToolRegistry)
  75. await ctx.plugin(TaskService)
  76. await expect(ctx.plugin(ToolTasks, { waitTimeoutMs: 100, maxWaitTimeoutMs: 50 }))
  77. .rejects.toThrow('waitTimeoutMs (100) exceeds maxWaitTimeoutMs (50)')
  78. })
  79. it('renders status lines with and without producer detail', () => {
  80. const base = { id: 'bash-1', kind: 'bash', label: 'x', startedAt: 0, reported: false } as unknown as TaskSnapshot
  81. expect(statusLine({ ...base, status: 'running' })).toBe('[status: running]')
  82. expect(statusLine({ ...base, status: 'completed', detail: 'exit code: 0' })).toBe('[status: completed, exit code: 0]')
  83. })
  84. it('applies the built-in wait bounds when apply() receives a bare config', async () => {
  85. // Bypasses the schemastery defaults on purpose: apply() must stand on its
  86. // own `??` fallbacks when embedded programmatically without the schema.
  87. const ctx = new Context()
  88. await ctx.plugin(SystemPrompt)
  89. await ctx.plugin(ToolRegistry)
  90. await ctx.plugin(TaskService)
  91. ToolTasks.apply(ctx, {})
  92. expect(ctx.tools.get('task_output')).toBeDefined()
  93. expect(() => ctx.tasks.start(producer().spec)).not.toThrow()
  94. })
  95. })
  96. describe('task_output', () => {
  97. it('reads a consuming delta with a trailing status line', async () => {
  98. const { ctx } = await setup()
  99. const chunks = ['line one\n', '']
  100. ctx.tasks.start(producer({ readOutput: () => chunks.shift() ?? '' }).spec)
  101. // A body already ending in a newline gets no doubled separator.
  102. expect(text(await call(ctx, 'task_output', { task_id: 'bash-1' }))).toBe('line one\n[status: running]')
  103. expect(text(await call(ctx, 'task_output', { task_id: 'bash-1' }))).toBe('(no new output)\n[status: running]')
  104. })
  105. it('returns the final output of a settled final-output task', async () => {
  106. const { ctx } = await setup()
  107. const p = producer({ kind: 'subagent', label: 'research' })
  108. ctx.tasks.start(p.spec)
  109. expect(text(await call(ctx, 'task_output', { task_id: 'subagent-1' }))).toBe('(no new output)\n[status: running]')
  110. p.settle({ status: 'completed', detail: 'completed', output: 'the answer' })
  111. await tick()
  112. expect(text(await call(ctx, 'task_output', { task_id: 'subagent-1' }))).toBe('the answer\n[status: completed, completed]')
  113. })
  114. it('wait: true blocks until settlement and reports the terminal state', async () => {
  115. const { ctx } = await setup()
  116. const p = producer({ kind: 'subagent', label: 'research' })
  117. ctx.tasks.start(p.spec)
  118. const pending = call(ctx, 'task_output', { task_id: 'subagent-1', wait: true })
  119. p.settle({ status: 'completed', output: 'done deal' })
  120. expect(text(await pending)).toBe('done deal\n[status: completed]')
  121. })
  122. it('wait: true times out against the configured cap and leaves the task alive', async () => {
  123. const { ctx } = await setup({ waitTimeoutMs: 10, maxWaitTimeoutMs: 20 })
  124. ctx.tasks.start(producer().spec)
  125. // A model-supplied timeout far above the cap is clamped: this returns
  126. // promptly (≤ the 20ms cap), not after ten minutes.
  127. const result = await call(ctx, 'task_output', { task_id: 'bash-1', wait: true, timeout_ms: 600_000 })
  128. expect(text(result)).toBe('(no new output)\n[status: running]')
  129. })
  130. it('rejects an empty or unknown task id as an errored result', async () => {
  131. const { ctx } = await setup()
  132. expect((await call(ctx, 'task_output', { task_id: '' })).isError).toBe(true)
  133. const unknown = await call(ctx, 'task_output', { task_id: 'bash-99' })
  134. expect(unknown.isError).toBe(true)
  135. expect(text(unknown)).toContain('unknown task bash-99')
  136. })
  137. })
  138. describe('task_list', () => {
  139. it('lists caller-visible tasks and renders the empty case', async () => {
  140. const { ctx } = await setup()
  141. expect(text(await call(ctx, 'task_list', {}))).toBe('(no background tasks)')
  142. const alice = fakeAgent(ctx, 'sess-alice')
  143. ctx.tasks.start(producer({ owner: alice, label: 'pnpm test' }).spec)
  144. ctx.tasks.start(producer({ kind: 'subagent', label: 'open research' }).spec)
  145. const p = producer({ owner: alice, label: 'build' })
  146. ctx.tasks.start(p.spec)
  147. p.settle({ status: 'completed', detail: 'exit code: 0' })
  148. await tick()
  149. expect(text(await call(ctx, 'task_list', {}, alice))).toBe([
  150. 'bash-1 [bash] running — pnpm test',
  151. 'subagent-1 [subagent] running — open research',
  152. 'bash-2 [bash] completed — build',
  153. ].join('\n'))
  154. // A different caller sees only the unowned task.
  155. const bob = fakeAgent(ctx, 'sess-bob')
  156. expect(text(await call(ctx, 'task_list', {}, bob))).toBe('subagent-1 [subagent] running — open research')
  157. })
  158. })
  159. describe('task_kill', () => {
  160. it('requests cancellation with the forwarded reason', async () => {
  161. const { ctx } = await setup()
  162. const p = producer()
  163. ctx.tasks.start(p.spec)
  164. const result = await call(ctx, 'task_kill', { task_id: 'bash-1', reason: 'superseded' })
  165. expect(text(result)).toBe('requested cancellation of task bash-1')
  166. expect(p.cancels).toEqual(['superseded'])
  167. })
  168. it('reports an already-finished task without consuming its pending delta', async () => {
  169. const { ctx } = await setup()
  170. let delta = 'unread tail'
  171. const p = producer({ readOutput: () => { const d = delta; delta = ''; return d } })
  172. ctx.tasks.start(p.spec)
  173. p.settle({ status: 'completed', detail: 'exit code: 0' })
  174. await tick()
  175. expect(text(await call(ctx, 'task_kill', { task_id: 'bash-1' })))
  176. .toBe('task bash-1 had already finished [status: completed, exit code: 0]')
  177. // The kill described the task via a non-consuming snapshot: the delta is intact.
  178. expect(text(await call(ctx, 'task_output', { task_id: 'bash-1' }))).toBe('unread tail\n[status: completed, exit code: 0]')
  179. })
  180. it('rejects an empty task id as an errored result', async () => {
  181. const { ctx } = await setup()
  182. expect((await call(ctx, 'task_kill', { task_id: '' })).isError).toBe(true)
  183. })
  184. })
  185. describe('tool-owned UI presentation (presentCall)', () => {
  186. it('renders generic cards for all three control tools', async () => {
  187. const { ctx } = await setup()
  188. expect(ctx.tools.get('task_output')?.presentCall?.({ task_id: 'bash-1' }))
  189. .toEqual({ card: 'generic', title: 'Read output from background task bash-1', kind: 'read', rawInput: 'bash-1' })
  190. expect(ctx.tools.get('task_list')?.presentCall?.({}))
  191. .toEqual({ card: 'generic', title: 'List background tasks', kind: 'read' })
  192. expect(ctx.tools.get('task_kill')?.presentCall?.({ task_id: 'subagent-2' }))
  193. .toEqual({ card: 'generic', title: 'Kill background task subagent-2', kind: 'execute', rawInput: 'subagent-2' })
  194. })
  195. })
  196. describe('completion notices', () => {
  197. it('injects a notice into the owning agent when an unreported task settles', async () => {
  198. const { ctx } = await setup()
  199. const inject = vi.fn()
  200. const owner = fakeAgent(ctx, 'sess-1', inject)
  201. const p = producer({ owner, label: 'pnpm test' })
  202. ctx.tasks.start(p.spec)
  203. p.settle({ status: 'completed', detail: 'exit code: 0' })
  204. await tick()
  205. expect(inject).toHaveBeenCalledTimes(1)
  206. expect(inject).toHaveBeenCalledWith(
  207. [{ type: 'text', text: 'background task bash-1 (bash: pnpm test) finished [status: completed, exit code: 0]. Read its output with task_output.' }],
  208. { source: { kind: 'plugin', plugin: 'tool-tasks' } },
  209. )
  210. })
  211. it('suppresses the notice for a task the model already killed', async () => {
  212. const { ctx } = await setup()
  213. const inject = vi.fn()
  214. const owner = fakeAgent(ctx, 'sess-1', inject)
  215. const p = producer({ owner })
  216. ctx.tasks.start(p.spec)
  217. await call(ctx, 'task_kill', { task_id: 'bash-1' }, owner)
  218. p.settle({ status: 'killed' })
  219. await tick()
  220. expect(inject).not.toHaveBeenCalled()
  221. })
  222. it('suppresses the notice when a wait returned the terminal state', async () => {
  223. const { ctx } = await setup()
  224. const inject = vi.fn()
  225. const owner = fakeAgent(ctx, 'sess-1', inject)
  226. const p = producer({ owner, kind: 'subagent' })
  227. ctx.tasks.start(p.spec)
  228. const pending = call(ctx, 'task_output', { task_id: 'subagent-1', wait: true }, owner)
  229. p.settle({ status: 'completed', output: 'answer' })
  230. expect(text(await pending)).toContain('answer')
  231. expect(inject).not.toHaveBeenCalled()
  232. })
  233. it('drops the notice for unowned tasks and for a disposed owner (benign race)', async () => {
  234. const { ctx } = await setup()
  235. // Unowned: settles with nobody to notify — nothing throws.
  236. const unowned = producer()
  237. ctx.tasks.start(unowned.spec)
  238. unowned.settle({ status: 'completed' })
  239. await tick()
  240. // Disposed owner: inject throws the disposed message — contained.
  241. const inject = vi.fn(() => { throw new Error('agent "agent-sess-1" is disposed') })
  242. const owner = fakeAgent(ctx, 'sess-1', inject)
  243. const p = producer({ owner })
  244. ctx.tasks.start(p.spec)
  245. p.settle({ status: 'completed' })
  246. await tick()
  247. expect(inject).toHaveBeenCalledTimes(1)
  248. })
  249. it('does not route an old owner completion notice to a same-session replacement', async () => {
  250. const { ctx } = await setup()
  251. const oldInject = vi.fn(() => { throw new Error('agent "agent-shared" is disposed') })
  252. const oldOwner = fakeAgent(ctx, 'shared', oldInject)
  253. const p = producer({ owner: oldOwner })
  254. ctx.tasks.start(p.spec)
  255. detachAgent(oldOwner)
  256. const replacementInject = vi.fn()
  257. fakeAgent(ctx, 'shared', replacementInject)
  258. p.settle({ status: 'completed' })
  259. await tick()
  260. expect(oldInject).toHaveBeenCalledTimes(1)
  261. expect(replacementInject).not.toHaveBeenCalled()
  262. })
  263. it('propagates a non-disposed inject failure (a real bug must surface)', async () => {
  264. const { ctx } = await setup()
  265. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  266. const owner = fakeAgent(ctx, 'sess-1', () => { throw new Error('unexpected inject bug') })
  267. const p = producer({ owner })
  268. ctx.tasks.start(p.spec)
  269. p.settle({ status: 'completed' })
  270. await tick()
  271. // The throw escapes the notice listener and is contained (logged) by the
  272. // registry's per-listener containment — visible, not swallowed.
  273. expect(warn).toHaveBeenCalledWith(expect.stringContaining('unexpected inject bug'))
  274. })
  275. it('keeps using the exact owner after the agent registry is gone', async () => {
  276. const { ctx, agentsFiber } = await setup()
  277. const inject = vi.fn()
  278. const owner = fakeAgent(ctx, 'sess-1', inject)
  279. // Settlement must not depend on a later registry lookup: the exact owner
  280. // supplied at start remains the destination while its own scope is live.
  281. const p1 = producer({ owner })
  282. ctx.tasks.start(p1.spec)
  283. const p2 = producer({ owner })
  284. ctx.tasks.start(p2.spec)
  285. await agentsFiber.dispose()
  286. p1.settle({ status: 'completed' })
  287. p2.settle({ status: 'failed' })
  288. await tick()
  289. expect(inject).toHaveBeenCalledTimes(2)
  290. })
  291. })