workflow-workerthread.spec.ts 44 KB

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