workflow-workerthread.spec.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import Loader from '@cordisjs/plugin-loader'
  4. import { AgentId } from '@deepseek-ai/dsh-agent'
  5. import type { Agent } from '@deepseek-ai/dsh-agent'
  6. import SubagentService from '@deepseek-ai/dsh-subagent'
  7. import type { SubagentCapabilities, SubagentProvider, SubagentResult, SubagentRun, SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
  8. import type { WorkflowMeta, WorkflowResult, WorkflowResultInfo, WorkflowRunInfo } from '@deepseek-ai/dsh-workflow'
  9. import * as workerEngineModule from '../src/index.ts'
  10. import WorkerWorkflowEngine, { type Config } from '../src/index.ts'
  11. /** A minimal parent stand-in: the engine only threads it through to the provider. */
  12. function fakeParent(): Agent {
  13. return { id: AgentId('workflow-parent'), options: {} } as unknown as Agent
  14. }
  15. /** The vm-context escape hatch, spelled once: real Worker tests use it to make the WORKER misbehave. */
  16. const ESCAPE = "globalThis.constructor.constructor('return process')()"
  17. /** One controllable child run: the test (or auto mode) settles it. */
  18. interface ControlledRun {
  19. request: SubagentStartRequest
  20. settle(result: SubagentResult): void
  21. cancelled: string | undefined
  22. disposed: boolean
  23. disposeCalls: number
  24. }
  25. /**
  26. * A scripted in-test provider over the REAL SubagentService registry: `auto`
  27. * settles each run via the reply function on a microtask; `manual` piles runs
  28. * up in `runs` for the test to settle. A run aborts (settles `aborted`) when
  29. * the request signal fires, like the real in-process backends.
  30. */
  31. class StubProvider implements SubagentProvider {
  32. readonly capabilities: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: true }
  33. readonly inheritsParentContext = false
  34. readonly runs: ControlledRun[] = []
  35. constructor(
  36. readonly name: string,
  37. private readonly reply?: (request: SubagentStartRequest, index: number) => SubagentResult,
  38. private readonly disposeDelayMs = 0,
  39. ) {}
  40. start(request: SubagentStartRequest): SubagentRun {
  41. let settle!: (result: SubagentResult) => void
  42. const result = new Promise<SubagentResult>((resolve) => { settle = resolve })
  43. const controlled: ControlledRun = { request, settle, cancelled: undefined, disposed: false, disposeCalls: 0 }
  44. this.runs.push(controlled)
  45. const index = this.runs.length - 1
  46. request.signal?.addEventListener('abort', () => { settle({ output: [], stopReason: 'aborted' }) }, { once: true })
  47. if (this.reply) {
  48. const reply = this.reply
  49. queueMicrotask(() => { settle(reply(request, index)) })
  50. }
  51. return {
  52. id: AgentId(`stub-child-${index}`),
  53. result,
  54. cancel: (reason?: string) => {
  55. controlled.cancelled = reason ?? 'cancelled'
  56. settle({ output: [], stopReason: 'aborted' })
  57. },
  58. dispose: () => {
  59. controlled.disposeCalls += 1
  60. if (this.disposeDelayMs === 0) {
  61. controlled.disposed = true
  62. return Promise.resolve()
  63. }
  64. return new Promise<void>((resolve) => {
  65. setTimeout(() => {
  66. controlled.disposed = true
  67. resolve()
  68. }, this.disposeDelayMs)
  69. })
  70. },
  71. }
  72. }
  73. }
  74. /** Text-reply helper for auto providers. */
  75. function text(reply: string): SubagentResult {
  76. return { output: [{ type: 'text', text: reply }], stopReason: 'completed' }
  77. }
  78. interface SetupOptions {
  79. config?: Config
  80. reply?: (request: SubagentStartRequest, index: number) => SubagentResult
  81. manual?: boolean
  82. disposeDelayMs?: number
  83. }
  84. async function setup(options?: SetupOptions) {
  85. const ctx = new Context()
  86. await ctx.plugin(SubagentService)
  87. const provider = new StubProvider(
  88. 'stub',
  89. options?.manual ? undefined : options?.reply ?? (() => text('stub reply')),
  90. options?.disposeDelayMs ?? 0,
  91. )
  92. ctx.subagents.registerProvider(provider)
  93. // A fixed concurrency ceiling: the auto-resolved default is machine-derived
  94. // (cores - 2, floored at 1), so tests that expect N children in flight
  95. // would wedge on small CI runners.
  96. await ctx.plugin(WorkerWorkflowEngine, { provider: 'stub', maxConcurrentAgents: 8, ...options?.config })
  97. return { ctx, provider, parent: fakeParent() }
  98. }
  99. /** The standard test meta plus a body, spread into a start request. */
  100. function scripted(body: string, metaExtra?: Partial<WorkflowMeta>): { script: string; meta: WorkflowMeta } {
  101. return { script: body, meta: { name: 'test-flow', description: 'a test workflow', ...metaExtra } }
  102. }
  103. /** Start + await one run, disposing on the way out. */
  104. async function run(ctx: Context, parent: Agent, source: { script: string; meta: WorkflowMeta }, args?: unknown): Promise<WorkflowResult> {
  105. const handle = ctx.workflows.start({ ...source, parent, ...args !== undefined ? { args } : {} })
  106. try {
  107. return await handle.result
  108. } finally {
  109. await handle.dispose()
  110. }
  111. }
  112. describe('dsh-workflow-workerthread', () => {
  113. describe('script execution over a real worker thread', () => {
  114. it('runs a script end-to-end: agent() text results, phases, log, args, return value, events', async () => {
  115. const { ctx, parent, provider } = await setup({ reply: (_request, index) => text(`answer-${index}`) })
  116. const events: [string, unknown[]][] = []
  117. for (const name of ['workflow/start', 'workflow/phase', 'workflow/log', 'workflow/agent-start', 'workflow/agent-end', 'workflow/end'] as const) {
  118. ctx.on(name, (...payload: unknown[]) => { events.push([name, payload]) })
  119. }
  120. const result = await run(ctx, parent, scripted(`
  121. phase('Scan')
  122. log('starting with ' + args.files.length + ' files')
  123. const answers = await pipeline(args.files, (prev, item) => agent('read ' + item))
  124. phase('Report')
  125. return { answers, count: args.files.length }
  126. `, { phases: [{ title: 'Scan' }, { title: 'Report' }] }), { files: ['a.ts', 'b.ts'] })
  127. expect(result.stopReason).toBe('completed')
  128. expect(result.agentsStarted).toBe(2)
  129. expect(result.value).toEqual({ answers: ['answer-0', 'answer-1'], count: 2 })
  130. expect(provider.runs.every(r => r.disposed)).toBe(true)
  131. const names = events.map(([name]) => name)
  132. expect(names[0]).toBe('workflow/start')
  133. expect(names).toContain('workflow/phase')
  134. expect(names).toContain('workflow/log')
  135. expect(names.at(-1)).toBe('workflow/end')
  136. const info = events[0]![1][0] as WorkflowRunInfo
  137. expect(info.meta.name).toBe('test-flow')
  138. const end = events.at(-1)![1][1] as Record<string, unknown>
  139. expect(end).toEqual({ stopReason: 'completed', agentsStarted: 2 })
  140. expect('value' in end).toBe(false)
  141. })
  142. it('agent({schema, model}) forwards outputSchema and agentOptions to the provider across the thread', async () => {
  143. const { ctx, parent, provider } = await setup({
  144. reply: () => ({ output: [], structured: { files: ['x.ts', 'y.ts'] }, stopReason: 'completed' }),
  145. })
  146. const result = await run(ctx, parent, scripted(`
  147. const found = await agent('list files', { model: 'deepseek-v4-pro', schema: { type: 'object', properties: { files: { type: 'array', items: { type: 'string' } } }, required: ['files'] } })
  148. return { first: found.files[0], count: found.files.length }
  149. `))
  150. expect(result.value).toEqual({ first: 'x.ts', count: 2 })
  151. expect(provider.runs[0]!.request.outputSchema).toEqual({
  152. type: 'object',
  153. properties: { files: { type: 'array', items: { type: 'string' } } },
  154. required: ['files'],
  155. })
  156. expect(provider.runs[0]!.request.agentOptions).toEqual({ model: 'deepseek-v4-pro' })
  157. expect(provider.runs[0]!.request.parent).toBeDefined()
  158. })
  159. it('a fatal hook error inside the worker kills the script and reports the error', async () => {
  160. const { ctx, parent } = await setup()
  161. const result = await run(ctx, parent, scripted("return await parallel([() => agent('x', { isolation: 'worktree' })])"))
  162. expect(result.stopReason).toBe('error')
  163. expect(result.error).toContain('"isolation" is deferred')
  164. })
  165. it('a provider start failure crosses back as a fatal AGENT_START error', async () => {
  166. const { ctx, parent } = await setup({ config: { provider: 'nonexistent' } })
  167. const result = await run(ctx, parent, scripted("return await pipeline([1], () => agent('p'))"))
  168. expect(result.stopReason).toBe('error')
  169. expect(result.error).toContain('agent() could not start a child')
  170. })
  171. it('a child result REJECTION crosses back as a fatal AGENT_RESULT error (a broken provider is not a failed child)', async () => {
  172. const ctx = new Context()
  173. await ctx.plugin(SubagentService)
  174. const provider: SubagentProvider = {
  175. name: 'rejecting',
  176. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true },
  177. inheritsParentContext: false,
  178. start: () => ({
  179. id: AgentId('reject-child'),
  180. result: Promise.reject(new Error('backend exploded')),
  181. cancel: () => { /* nothing in flight */ },
  182. dispose: () => Promise.resolve(),
  183. }),
  184. }
  185. ctx.subagents.registerProvider(provider)
  186. await ctx.plugin(WorkerWorkflowEngine, { provider: 'rejecting', maxConcurrentAgents: 2 })
  187. const result = await run(ctx, fakeParent(), scripted(`
  188. try { await agent('p'); return 'unreachable' } catch (e) { return { name: e.name, code: e.code, fatal: e.fatal, message: e.message } }
  189. `))
  190. expect(result.value).toMatchObject({ name: 'WorkflowError', code: 'AGENT_RESULT', fatal: true })
  191. expect((result.value as { message: string }).message).toContain('backend exploded')
  192. })
  193. it('a child whose dispose() rejects cannot wedge the script (the host acks anyway)', async () => {
  194. const ctx = new Context()
  195. await ctx.plugin(SubagentService)
  196. const provider: SubagentProvider = {
  197. name: 'bad-dispose',
  198. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true },
  199. inheritsParentContext: false,
  200. start: () => ({
  201. id: AgentId('bad-dispose-child'),
  202. result: Promise.resolve({ output: [{ type: 'text', text: 'fine' }], stopReason: 'completed' }),
  203. cancel: () => { /* settled already */ },
  204. dispose: () => Promise.reject(new Error('dispose exploded')),
  205. }),
  206. }
  207. ctx.subagents.registerProvider(provider)
  208. await ctx.plugin(WorkerWorkflowEngine, { provider: 'bad-dispose', maxConcurrentAgents: 2 })
  209. const result = await run(ctx, fakeParent(), scripted("return await agent('p')"))
  210. expect(result.stopReason).toBe('completed')
  211. expect(result.value).toBe('fine')
  212. })
  213. it('a child dispose() rejecting an UNRENDERABLE value still acks — the containment warn is total', async () => {
  214. const ctx = new Context()
  215. await ctx.plugin(SubagentService)
  216. const provider: SubagentProvider = {
  217. name: 'coercion-trap-dispose',
  218. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true },
  219. inheritsParentContext: false,
  220. start: () => ({
  221. id: AgentId('trap-child'),
  222. result: Promise.resolve({ output: [{ type: 'text', text: 'fine' }], stopReason: 'completed' }),
  223. cancel: () => { /* settled already */ },
  224. // The rejection VALUE's own coercion throws: a warn built with bare
  225. // String(error) would itself throw, skipping the ChildDisposed ack
  226. // and wedging the script's finally until the grace/terminate path.
  227. // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- the non-Error rejection IS the scenario under test
  228. dispose: () => Promise.reject({ toString: () => { throw new Error('coercion trap') } }),
  229. }),
  230. }
  231. ctx.subagents.registerProvider(provider)
  232. await ctx.plugin(WorkerWorkflowEngine, { provider: 'coercion-trap-dispose', maxConcurrentAgents: 2 })
  233. const result = await run(ctx, fakeParent(), scripted("return await agent('p')"))
  234. expect(result.stopReason).toBe('completed')
  235. expect(result.value).toBe('fine')
  236. })
  237. it('the worker spawns with an EMPTY environment: an escaped script finds no ambient credentials', async () => {
  238. const { ctx, parent } = await setup()
  239. // A canary in the HARNESS process's env: with an inherited environment
  240. // the escape below would read it back (exactly how DEEPSEEK_API_KEY
  241. // would leak); env: {} in the spawn options is what keeps it out.
  242. process.env.WORKFLOW_ENV_CANARY = 'leak me'
  243. try {
  244. const result = await run(ctx, parent, scripted(`
  245. const proc = ${ESCAPE}
  246. return { canary: proc.env.WORKFLOW_ENV_CANARY ?? null, keys: Object.keys(proc.env).length }
  247. `))
  248. expect(result.stopReason).toBe('completed')
  249. expect(result.value).toEqual({ canary: null, keys: 0 })
  250. } finally {
  251. delete process.env.WORKFLOW_ENV_CANARY
  252. }
  253. })
  254. })
  255. describe('lifecycle: parse errors, cancellation, termination, disposal', () => {
  256. it('start() throws synchronously for invalid meta data or an unparseable body (host-side pre-checks)', async () => {
  257. const { ctx, parent } = await setup()
  258. // Meta is DATA — shape violations reject loud, every one named.
  259. expect(() => ctx.workflows.start({ script: 'return 1', meta: { name: '', description: 'd' }, parent })).toThrow(/meta\.name must be a non-empty string/)
  260. expect(() => ctx.workflows.start({ script: 'return 1', meta: { name: 'x', description: 'd', extra: 1 } as unknown as WorkflowMeta, parent })).toThrow(/META_INVALID|not a recognized field/)
  261. expect(() => ctx.workflows.start({ ...scripted('return ((('), parent })).toThrow(/does not parse/)
  262. // The likeliest authoring slip — a Claude Code-style meta header in the
  263. // body — gets a pointed message, not a bare SyntaxError.
  264. expect(() => ctx.workflows.start({ ...scripted("export const meta = { name: 'x', description: 'd' }\nreturn 1"), parent })).toThrow(/meta rides the `meta` request field/)
  265. })
  266. it('cancel() aborts in-flight children (signal AND cancel RPC) and settles the run cancelled', async () => {
  267. const { ctx, parent, provider } = await setup({ manual: true })
  268. const ends: unknown[] = []
  269. ctx.on('workflow/agent-end', (_info, agent) => { ends.push(agent) })
  270. const runEnds: WorkflowResultInfo[] = []
  271. ctx.on('workflow/end', (_info, result) => { runEnds.push(result) })
  272. const handle = ctx.workflows.start({ ...scripted("return await agent('long job')"), parent })
  273. await vi.waitFor(() => { expect(provider.runs.length).toBe(1) })
  274. handle.cancel('user stopped it')
  275. const result = await handle.result
  276. expect(result.stopReason).toBe('cancelled')
  277. expect(result.error).toContain('user stopped it')
  278. await handle.dispose()
  279. expect(provider.runs[0]!.disposed).toBe(true)
  280. expect(ends).toEqual([expect.objectContaining({ seq: 1, outcome: 'cancelled' })])
  281. // workflow/end is an observer's only death signal: it fires for a
  282. // cancelled run too, mirroring the settled outcome data.
  283. expect(runEnds).toEqual([{ stopReason: 'cancelled', error: result.error, agentsStarted: result.agentsStarted }])
  284. })
  285. it('an already-aborted request signal cancels before the body ever runs (the go handshake holds it)', async () => {
  286. const { ctx, parent, provider } = await setup()
  287. const controller = new AbortController()
  288. controller.abort()
  289. const logs: string[] = []
  290. ctx.on('workflow/log', (_info, message) => { logs.push(message) })
  291. const handle = ctx.workflows.start({ ...scripted("log('ran')\nreturn 123"), parent, signal: controller.signal })
  292. const result = await handle.result
  293. expect(result.stopReason).toBe('cancelled')
  294. expect(result.value).toBeNull()
  295. expect(logs).toEqual([])
  296. expect(provider.runs.length).toBe(0)
  297. await handle.dispose()
  298. })
  299. it('cancel() right after start() cancels before the body runs; the signal aborting mid-run cancels like cancel()', async () => {
  300. const { ctx, parent, provider } = await setup({ manual: true })
  301. const first = ctx.workflows.start({ ...scripted("return await agent('never')"), parent })
  302. // No-reason cancel: the canonical default reason must ride the result.
  303. first.cancel()
  304. const firstResult = await first.result
  305. expect(firstResult.stopReason).toBe('cancelled')
  306. expect(firstResult.error).toContain('workflow cancelled')
  307. expect(provider.runs.length).toBe(0)
  308. await first.dispose()
  309. const controller = new AbortController()
  310. const second = ctx.workflows.start({ ...scripted("return await agent('job')"), parent, signal: controller.signal })
  311. await vi.waitFor(() => { expect(provider.runs.length).toBe(1) })
  312. controller.abort()
  313. expect((await second.result).stopReason).toBe('cancelled')
  314. await second.dispose()
  315. })
  316. it('a child-start racing the host cancel is refused: no child starts after cancellation', async () => {
  317. const { ctx, parent, provider } = await setup({ manual: true })
  318. // Cancel from INSIDE the log listener: the worker has already posted
  319. // its child-start (queued right behind the log message), so the host
  320. // processes it with cancelReason set — the refusal arm no real-world
  321. // timing can hit reliably. (The closure runs only after `handle` below
  322. // is initialized — the listener fires on the worker's first message.)
  323. ctx.on('workflow/log', () => { handle.cancel('cancelled from the log listener') })
  324. const handle = ctx.workflows.start({ ...scripted("log('mark')\nreturn await agent('late')"), parent })
  325. const result = await handle.result
  326. expect(result.stopReason).toBe('cancelled')
  327. expect(provider.runs.length).toBe(0)
  328. await handle.dispose()
  329. })
  330. it('post-cancel narration is suppressed host-side, and completion racing a cancel reports cancelled', async () => {
  331. const { ctx, parent } = await setup()
  332. const narration: string[] = []
  333. ctx.on('workflow/log', (_info, message) => { narration.push(message) })
  334. ctx.on('workflow/phase', (_info, title) => { narration.push(`phase:${title}`) })
  335. const handle = ctx.workflows.start({
  336. // The sync spin keeps the worker's loop busy so the cancel message
  337. // cannot be processed before the script settles `completed` — the
  338. // worker posts a completed result that must LOSE to the in-flight
  339. // host cancellation. The trailing narration exercises host-side
  340. // suppression: posted pre-cancel-processing worker-side, arriving
  341. // post-cancel host-side.
  342. ...scripted(`
  343. log('started')
  344. const end = Date.now() + 1000
  345. while (Date.now() < end) {}
  346. phase('late phase')
  347. log('late log')
  348. return 'done'
  349. `),
  350. parent,
  351. })
  352. await vi.waitFor(() => { expect(narration).toContain('started') })
  353. handle.cancel('raced the completion')
  354. const result = await handle.result
  355. expect(result.stopReason).toBe('cancelled')
  356. expect(result.error).toContain('raced the completion')
  357. expect(narration).toEqual(['started'])
  358. await handle.dispose()
  359. }, 15_000)
  360. it('cancel() force-settles a script parked on a promise no hook owns, and TERMINATES its worker', async () => {
  361. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: 50 } })
  362. const runEnds: WorkflowResultInfo[] = []
  363. ctx.on('workflow/end', (_info, result) => { runEnds.push(result) })
  364. const handle = ctx.workflows.start({
  365. ...scripted("await new Promise(() => {})\nreturn 'unreachable'"),
  366. parent,
  367. })
  368. handle.cancel('user aborted')
  369. const result = await handle.result
  370. expect(result.stopReason).toBe('cancelled')
  371. expect(result.error).toContain('user aborted')
  372. // The grace force-settle fires workflow/end exactly like an ordinary
  373. // settlement — a terminated script's death still reaches observers.
  374. expect(runEnds).toEqual([{ stopReason: 'cancelled', error: result.error, agentsStarted: 0 }])
  375. await handle.dispose()
  376. })
  377. it('dispose() on a stuck script returns within the grace instead of hanging (result settles cancelled)', async () => {
  378. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: 50 } })
  379. const handle = ctx.workflows.start({
  380. ...scripted("await new Promise(() => {})\nreturn 'unreachable'"),
  381. parent,
  382. })
  383. const before = Date.now()
  384. await handle.dispose()
  385. expect(Date.now() - before).toBeLessThan(2000)
  386. const result = await handle.result
  387. expect(result.stopReason).toBe('cancelled')
  388. })
  389. it('dispose() is idempotent and settles cleanly after a completed run', async () => {
  390. const { ctx, parent } = await setup()
  391. const handle = ctx.workflows.start({ ...scripted('return 1'), parent })
  392. await handle.result
  393. await handle.dispose()
  394. await handle.dispose()
  395. })
  396. it('a settled run arms NO grace timer: disposing a completed run must not pin it for disposeGraceMs', async () => {
  397. // A distinctive grace so the spy can tell the cancel-path grace timer
  398. // apart from every other timeout in flight.
  399. const GRACE = 44_444
  400. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: GRACE } })
  401. const handle = ctx.workflows.start({ ...scripted('return 1'), parent })
  402. await handle.result
  403. const spy = vi.spyOn(globalThis, 'setTimeout')
  404. try {
  405. await handle.dispose()
  406. // dispose()'s own bounded-wait sleep is the ONLY grace-sized timer
  407. // allowed here; before the settled guard, cancel() armed a second one
  408. // that nothing would ever clear (the run was already settled), keeping
  409. // the WorkerRun/Worker closure alive until the grace expired.
  410. const graceTimers = spy.mock.calls.filter(call => call[1] === GRACE)
  411. expect(graceTimers.length).toBe(1)
  412. } finally {
  413. spy.mockRestore()
  414. }
  415. })
  416. it('strays: children fired without await are aborted once the script settles, and dispose() waits for their disposal', async () => {
  417. const { ctx, parent, provider } = await setup({ manual: true, disposeDelayMs: 40 })
  418. const handle = ctx.workflows.start({
  419. ...scripted(`
  420. agent('stray')
  421. return 'done without awaiting'
  422. `),
  423. parent,
  424. })
  425. const result = await handle.result
  426. expect(result.stopReason).toBe('completed')
  427. await vi.waitFor(() => { expect(provider.runs.length).toBe(1) })
  428. await handle.dispose()
  429. // Not a waitFor: by the time dispose() returns, the slow child disposal
  430. // must already be complete (host-side registry quiescence).
  431. expect(provider.runs[0]!.disposed).toBe(true)
  432. })
  433. it('the settle-reap fires the request signal too: a provider honoring ONLY the signal winds its stray down promptly', async () => {
  434. const ctx = new Context()
  435. await ctx.plugin(SubagentService)
  436. const aborted: string[] = []
  437. const provider: SubagentProvider = {
  438. name: 'signal-only',
  439. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true },
  440. inheritsParentContext: false,
  441. start: (request) => {
  442. let settle!: (result: SubagentResult) => void
  443. const result = new Promise<SubagentResult>((resolve) => { settle = resolve })
  444. request.signal?.addEventListener('abort', () => {
  445. aborted.push(String(request.signal?.reason))
  446. settle({ output: [], stopReason: 'aborted' })
  447. }, { once: true })
  448. return {
  449. id: AgentId('signal-only-child'),
  450. result,
  451. // The seam leaves a provider free to honor EITHER cancel channel;
  452. // this one deliberately ignores run.cancel() — only the request
  453. // signal can wind it down.
  454. cancel: () => { /* signal-only by design */ },
  455. dispose: () => Promise.resolve(),
  456. }
  457. },
  458. }
  459. ctx.subagents.registerProvider(provider)
  460. await ctx.plugin(WorkerWorkflowEngine, { provider: 'signal-only', maxConcurrentAgents: 2 })
  461. const handle = ctx.workflows.start({
  462. ...scripted(`
  463. agent('stray, never awaited')
  464. return 'done'
  465. `),
  466. parent: fakeParent(),
  467. })
  468. const result = await handle.result
  469. expect(result.stopReason).toBe('completed')
  470. // BEFORE dispose(): the settlement itself must have aborted the signal —
  471. // without it this child would stay live until dispose's terminate.
  472. await vi.waitFor(() => { expect(aborted).toEqual(['workflow settled']) })
  473. await handle.dispose()
  474. })
  475. it("cancel() drives each child's explicit cancel() host-side: a wedged worker cannot delay it", async () => {
  476. const ctx = new Context()
  477. await ctx.plugin(SubagentService)
  478. let starts = 0
  479. const cancelled: string[] = []
  480. const provider: SubagentProvider = {
  481. name: 'cancel-only',
  482. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true },
  483. inheritsParentContext: false,
  484. start: () => {
  485. starts += 1
  486. return {
  487. id: AgentId('cancel-only-child'),
  488. result: new Promise(() => { /* only cancel() ends this child */ }),
  489. // Deliberately ignores the request signal — the seam leaves a
  490. // provider free to honor ONLY the explicit cancel() channel.
  491. cancel: (reason?: string) => { cancelled.push(reason ?? 'cancelled') },
  492. dispose: () => Promise.resolve(),
  493. }
  494. },
  495. }
  496. ctx.subagents.registerProvider(provider)
  497. // A deliberately huge grace: if only the grace/terminate reap could
  498. // reach this child, the assertion below would time out first.
  499. await ctx.plugin(WorkerWorkflowEngine, { provider: 'cancel-only', maxConcurrentAgents: 2, disposeGraceMs: 30_000 })
  500. const handle = ctx.workflows.start({
  501. // The stray child's start RPC reaches the host, then the script wedges
  502. // its own worker in a synchronous spin: the worker cannot process the
  503. // Cancel message, so it can relay NO ChildCancel RPC — only the host's
  504. // own children loop can deliver the explicit cancel in time. The
  505. // microtask yields let the agent() continuation POST its child-start
  506. // before the spin seizes the worker's loop (the posted message needs
  507. // no further worker-loop turns to reach the host).
  508. ...scripted(`
  509. agent('wedged child')
  510. for (let i = 0; i < 20; i++) await null
  511. const end = Date.now() + 1500
  512. while (Date.now() < end) {}
  513. return 'raced'
  514. `),
  515. parent: fakeParent(),
  516. })
  517. await vi.waitFor(() => { expect(starts).toBe(1) })
  518. handle.cancel('stop now')
  519. await vi.waitFor(() => { expect(cancelled).toEqual(['stop now']) }, { timeout: 800 })
  520. // The wedged worker's own completion loses to the in-flight cancel.
  521. const result = await handle.result
  522. expect(result.stopReason).toBe('cancelled')
  523. await handle.dispose()
  524. }, 15_000)
  525. it('dispose() on a wedged worker host-drives child disposal inside the grace: it returns with the children DISPOSED, not with their teardown still in flight', async () => {
  526. const { ctx, parent, provider } = await setup({
  527. manual: true,
  528. disposeDelayMs: 40,
  529. config: { provider: 'stub', maxConcurrentAgents: 8, disposeGraceMs: 400 },
  530. })
  531. const handle = ctx.workflows.start({
  532. // Same shape as the wedged-cancel test above: the child's start RPC
  533. // reaches the host, then the script seizes its worker's loop, so the
  534. // worker can relay NO dispose RPC — the host's own dispose() drive is
  535. // the only thing that can start (and finish) this child's disposal
  536. // before the grace runs out.
  537. ...scripted(`
  538. agent('wedged child')
  539. for (let i = 0; i < 20; i++) await null
  540. const end = Date.now() + 1500
  541. while (Date.now() < end) {}
  542. return 'raced'
  543. `),
  544. parent,
  545. })
  546. await vi.waitFor(() => { expect(provider.runs.length).toBe(1) })
  547. const before = Date.now()
  548. await handle.dispose()
  549. // Bounded by the grace (plus the terminate), never by the 1.5s spin.
  550. expect(Date.now() - before).toBeLessThan(1200)
  551. // Not a waitFor: dispose() resolving IS the quiescence claim — the slow
  552. // child disposal must be complete, not merely started (before the
  553. // host-driven drive, disposal only STARTED at the post-terminate reap,
  554. // so dispose() returned with it still in flight).
  555. expect(provider.runs[0]!.disposed).toBe(true)
  556. const result = await handle.result
  557. expect(result.stopReason).toBe('cancelled')
  558. }, 15_000)
  559. it('a live child disposed by the dispose() drive is disposed ONCE, and the worker\'s late dispose RPC still gets its ack (the script settles, not the grace)', async () => {
  560. const { ctx, parent, provider } = await setup({ manual: true })
  561. const handle = ctx.workflows.start({
  562. ...scripted(`
  563. await agent('long child')
  564. return 'unreachable'
  565. `),
  566. parent,
  567. })
  568. await vi.waitFor(() => { expect(provider.runs.length).toBe(1) })
  569. const handleDispose = handle.dispose()
  570. const result = await handle.result
  571. // The script itself settled (the wrapper's own dispose RPC found the
  572. // child already reaped host-side and was acked) — a missing ack would
  573. // wedge the wrapper's finally until the 5s default grace force-settle.
  574. expect(result.stopReason).toBe('cancelled')
  575. expect(result.error).toContain('workflow disposed')
  576. await handleDispose
  577. expect(provider.runs[0]!.disposed).toBe(true)
  578. // The memo: the host drive and the worker's RPC share one disposal.
  579. expect(provider.runs[0]!.disposeCalls).toBe(1)
  580. })
  581. it('the grace force-settle pairs every stranded start: a host-synthesized cancelled agent-end lands before workflow/end', async () => {
  582. const { ctx, parent, provider } = await setup({ manual: true, config: { provider: 'stub', maxConcurrentAgents: 8, disposeGraceMs: 300 } })
  583. const ends: { seq: number; outcome: string }[] = []
  584. const order: string[] = []
  585. ctx.on('workflow/agent-start', (_info, agent) => { order.push(`start:${agent.seq}`) })
  586. ctx.on('workflow/agent-end', (_info, agent) => {
  587. ends.push({ seq: agent.seq, outcome: agent.outcome })
  588. order.push(`end:${agent.seq}`)
  589. })
  590. ctx.on('workflow/end', () => { order.push('run-end') })
  591. const handle = ctx.workflows.start({
  592. // 'slow' starts and its agent-start crosses to observers (the awaited
  593. // 'fast' call keeps the worker loop turning), then the script seizes
  594. // the loop: the wedged worker can never author slow's agent-end —
  595. // only the host's ledger can close the pair.
  596. ...scripted(`
  597. const p = agent('slow')
  598. await agent('fast')
  599. const end = Date.now() + 1500
  600. while (Date.now() < end) {}
  601. return 'raced'
  602. `),
  603. parent,
  604. })
  605. await vi.waitFor(() => { expect(order.filter(entry => entry.startsWith('start:')).length).toBe(2) })
  606. const fast = provider.runs.find(run => (run.request.prompt[0] as { text?: string }).text === 'fast')!
  607. fast.settle(text('fast done'))
  608. handle.cancel('stop now')
  609. const result = await handle.result
  610. expect(result.stopReason).toBe('cancelled')
  611. // fast's end is the worker's own report; slow's is host-synthesized at
  612. // the force-settle — exactly one end per started seq, no third event.
  613. expect(ends).toEqual([
  614. { seq: 2, outcome: 'completed' },
  615. { seq: 1, outcome: 'cancelled' },
  616. ])
  617. // Both ends reached observers BEFORE workflow/end: a progress consumer
  618. // can finalize its state at run-end without dangling agents.
  619. expect(order.indexOf('run-end')).toBe(order.length - 1)
  620. await handle.dispose()
  621. }, 15_000)
  622. it('graceful cancellation keeps pairing worker-authored: exactly one agent-end per start, nothing synthesized on top', async () => {
  623. const { ctx, parent, provider } = await setup({ manual: true })
  624. const ends: { seq: number; outcome: string }[] = []
  625. const order: string[] = []
  626. ctx.on('workflow/agent-end', (_info, agent) => {
  627. ends.push({ seq: agent.seq, outcome: agent.outcome })
  628. order.push(`end:${agent.seq}`)
  629. })
  630. ctx.on('workflow/end', () => { order.push('run-end') })
  631. const handle = ctx.workflows.start({
  632. ...scripted("await parallel([() => agent('a'), () => agent('b')])\nreturn 'unreachable'"),
  633. parent,
  634. })
  635. await vi.waitFor(() => { expect(provider.runs.length).toBe(2) })
  636. handle.cancel('user stop')
  637. const result = await handle.result
  638. expect(result.stopReason).toBe('cancelled')
  639. // The live worker reported both pairs itself; the ledger must not add
  640. // a synthesized duplicate on any path that settles inside the grace.
  641. expect(ends.map(end => end.outcome)).toEqual(['cancelled', 'cancelled'])
  642. expect(new Set(ends.map(end => end.seq)).size).toBe(2)
  643. expect(order.indexOf('run-end')).toBe(order.length - 1)
  644. await handle.dispose()
  645. })
  646. })
  647. describe('worker death', () => {
  648. it('a worker that exits before settling reports an error result and reaps its children', async () => {
  649. const ctx = new Context()
  650. await ctx.plugin(SubagentService)
  651. // The child's dispose() REJECTS on top of the worker death: the reap
  652. // must contain it (warn, not crash) while still emptying the registry.
  653. const cancelled: string[] = []
  654. const provider: SubagentProvider = {
  655. name: 'doomed',
  656. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true },
  657. inheritsParentContext: false,
  658. start: () => ({
  659. id: AgentId('doomed-child'),
  660. result: new Promise(() => { /* never settles; the reap is the teardown */ }),
  661. cancel: (reason?: string) => { cancelled.push(reason ?? 'cancelled') },
  662. dispose: () => Promise.reject(new Error('dispose exploded during reap')),
  663. }),
  664. }
  665. ctx.subagents.registerProvider(provider)
  666. await ctx.plugin(WorkerWorkflowEngine, { provider: 'doomed', maxConcurrentAgents: 2 })
  667. const runEnds: WorkflowResultInfo[] = []
  668. ctx.on('workflow/end', (_info, result) => { runEnds.push(result) })
  669. const handle = ctx.workflows.start({
  670. // The stray child's start RPC reaches the host, then the script kills
  671. // its own worker through the documented vm escape — the host must
  672. // settle `error` with the exit diagnostics and wind the child down.
  673. ...scripted(`
  674. agent('doomed')
  675. const proc = ${ESCAPE}
  676. const st = globalThis.constructor.constructor('return setTimeout')()
  677. await new Promise(resolve => st(resolve, 200))
  678. proc.exit(7)
  679. `),
  680. parent: fakeParent(),
  681. })
  682. const result = await handle.result
  683. expect(result.stopReason).toBe('error')
  684. expect(result.error).toContain('exit code 7')
  685. expect(result.agentsStarted).toBe(1)
  686. // A worker death is a stop reason like any other: workflow/end fires
  687. // with the error outcome — for a bus observer it is the only obituary.
  688. expect(runEnds).toEqual([{ stopReason: 'error', error: result.error, agentsStarted: 1 }])
  689. await vi.waitFor(() => { expect(cancelled.length).toBe(1) })
  690. await handle.dispose()
  691. }, 15_000)
  692. it('an uncaught exception inside the worker surfaces as an error result and reaps the in-flight child', async () => {
  693. const { ctx, parent, provider } = await setup({ manual: true })
  694. const handle = ctx.workflows.start({
  695. ...scripted(`
  696. agent('in flight when the worker dies')
  697. const proc = ${ESCAPE}
  698. const st = globalThis.constructor.constructor('return setTimeout')()
  699. await new Promise(resolve => st(resolve, 200))
  700. proc.nextTick(() => { throw new Error('worker blew up') })
  701. await new Promise(() => {})
  702. `),
  703. parent,
  704. })
  705. const result = await handle.result
  706. expect(result.stopReason).toBe('error')
  707. expect(result.error).toContain('worker blew up')
  708. // The reap wound the stray child down (cancel + a CLEAN dispose).
  709. await vi.waitFor(() => {
  710. expect(provider.runs.length).toBe(1)
  711. expect(provider.runs[0]!.disposed).toBe(true)
  712. })
  713. await handle.dispose()
  714. }, 15_000)
  715. it('a worker death pairs every stranded start: the synthesized cancelled agent-end precedes the error workflow/end', async () => {
  716. const { ctx, parent, provider } = await setup({ manual: true })
  717. const ends: { seq: number; outcome: string }[] = []
  718. const order: string[] = []
  719. ctx.on('workflow/agent-start', (_info, agent) => { order.push(`start:${agent.seq}`) })
  720. ctx.on('workflow/agent-end', (_info, agent) => {
  721. ends.push({ seq: agent.seq, outcome: agent.outcome })
  722. order.push(`end:${agent.seq}`)
  723. })
  724. ctx.on('workflow/end', () => { order.push('run-end') })
  725. const handle = ctx.workflows.start({
  726. // Same choreography as the force-settle pairing test, but the worker
  727. // DIES (the documented vm escape) instead of being terminated: the
  728. // exit path must close slow's pair from the ledger too. The escaped
  729. // setTimeout lets the already-posted messages flush before the kill.
  730. ...scripted(`
  731. const p = agent('slow')
  732. await agent('fast')
  733. const proc = ${ESCAPE}
  734. const st = globalThis.constructor.constructor('return setTimeout')()
  735. await new Promise(resolve => st(resolve, 150))
  736. proc.exit(7)
  737. `),
  738. parent,
  739. })
  740. await vi.waitFor(() => { expect(order.filter(entry => entry.startsWith('start:')).length).toBe(2) })
  741. const fast = provider.runs.find(run => (run.request.prompt[0] as { text?: string }).text === 'fast')!
  742. fast.settle(text('fast done'))
  743. const result = await handle.result
  744. expect(result.stopReason).toBe('error')
  745. expect(result.error).toContain('exit code 7')
  746. expect(ends).toEqual([
  747. { seq: 2, outcome: 'completed' },
  748. { seq: 1, outcome: 'cancelled' },
  749. ])
  750. expect(order.indexOf('run-end')).toBe(order.length - 1)
  751. await handle.dispose()
  752. }, 15_000)
  753. it('a dispose ack racing the worker death is dropped, not crashed (post after exit)', async () => {
  754. // Slow child disposal: the ack resolves only AFTER the worker died, so
  755. // it has nowhere to go and must be dropped silently (the workerGone
  756. // guard in post()).
  757. const { ctx, parent, provider } = await setup({ disposeDelayMs: 300 })
  758. const handle = ctx.workflows.start({
  759. // The STRAY child settles instantly, so its wrapper starts the slow
  760. // host-side disposal concurrently while the script goes on to kill
  761. // its own worker — the ack then resolves into a dead thread.
  762. ...scripted(`
  763. agent('stray, never awaited')
  764. const proc = ${ESCAPE}
  765. const st = globalThis.constructor.constructor('return setTimeout')()
  766. await new Promise(resolve => st(resolve, 150))
  767. proc.exit(5)
  768. `),
  769. parent,
  770. })
  771. const result = await handle.result
  772. expect(result.stopReason).toBe('error')
  773. expect(result.error).toContain('exit code 5')
  774. await vi.waitFor(() => { expect(provider.runs[0]!.disposed).toBe(true) })
  775. await handle.dispose()
  776. }, 15_000)
  777. it('a worker death AFTER a cancel reports cancelled, not error', async () => {
  778. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: 60_000 } })
  779. const handle = ctx.workflows.start({
  780. ...scripted(`
  781. const proc = ${ESCAPE}
  782. const st = globalThis.constructor.constructor('return setTimeout')()
  783. log('armed')
  784. await new Promise(resolve => st(resolve, 400))
  785. proc.exit(3)
  786. `),
  787. parent,
  788. })
  789. const logs: string[] = []
  790. ctx.on('workflow/log', (_info, message) => { logs.push(message) })
  791. await vi.waitFor(() => { expect(logs).toContain('armed') })
  792. handle.cancel('stop it')
  793. // The grace is deliberately huge: only the worker's own death (exit 3,
  794. // unreachable by the cancel — the script ignores hooks) settles this.
  795. const result = await handle.result
  796. expect(result.stopReason).toBe('cancelled')
  797. expect(result.error).toContain('stop it')
  798. await handle.dispose()
  799. }, 15_000)
  800. })
  801. describe('service surface', () => {
  802. it('run ids are unique per start; the run handle and event payloads hold SEPARATE meta clones', async () => {
  803. const { ctx, parent } = await setup()
  804. let eventMeta: WorkflowRunInfo | undefined
  805. ctx.on('workflow/start', (info) => { eventMeta = info })
  806. const first = ctx.workflows.start({ ...scripted('return 1'), parent })
  807. const second = ctx.workflows.start({ ...scripted('return 2'), parent })
  808. expect(first.id).not.toBe(second.id)
  809. eventMeta!.meta.name = 'corrupted'
  810. expect(second.meta.name).toBe('test-flow')
  811. await Promise.all([first.result, second.result])
  812. await first.dispose()
  813. await second.dispose()
  814. })
  815. it('unregisters ctx.workflows when the engine fiber is disposed (HMR safety), and default config runs (auto concurrency)', async () => {
  816. const ctx = new Context()
  817. await ctx.plugin(SubagentService)
  818. const fiber = await ctx.plugin(WorkerWorkflowEngine, {})
  819. expect(ctx.get('workflows')).toBeDefined()
  820. // A zero-agent run through the DEFAULT config exercises the auto
  821. // concurrency resolution (cores - 2, capped) in start().
  822. const result = await run(ctx, fakeParent(), scripted('return 6 * 7'))
  823. expect(result.value).toBe(42)
  824. await fiber.dispose()
  825. expect(ctx.get('workflows')).toBeUndefined()
  826. })
  827. it('has the class-plugin export shape (default = the engine service class)', () => {
  828. expect(workerEngineModule.default).toBe(WorkerWorkflowEngine)
  829. const loader = Object.create(Loader.prototype) as Loader
  830. const unwrapped: unknown = loader.unwrapExports(workerEngineModule)
  831. expect(unwrapped).toBe(WorkerWorkflowEngine)
  832. })
  833. })
  834. })