workflow-workerthread.spec.ts 53 KB

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