workflow-workerthread.spec.ts 43 KB

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