workflow-workerthread.spec.ts 46 KB

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