workflow-workerthread.spec.ts 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { fileURLToPath } from 'node:url'
  3. import type { Worker } from 'node:worker_threads'
  4. import { Context } from 'cordis'
  5. import Loader from '@cordisjs/plugin-loader'
  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, WorkflowRun, WorkflowRunInfo } from '@deepseek-ai/dsh-workflow'
  10. import * as workerEngineModule from '../src/index.ts'
  11. import WorkerWorkflowEngine, { type Config } from '../src/index.ts'
  12. import { HostToWorkerType, WorkerToHostType } from '../src/protocol.ts'
  13. import { SessionId } from '@deepseek-ai/dsh-session'
  14. /** A minimal parent stand-in: the engine only threads it through to the provider. */
  15. function fakeParent(): Agent {
  16. return { id: SessionId('workflow-parent'), options: {} } as unknown as Agent
  17. }
  18. // Allow cold worker startup on contended CI runners.
  19. vi.setConfig({ testTimeout: 30_000 })
  20. /**
  21. * Wait up to 10 seconds for CPU-bound worker startup or cross-thread delivery on contended CI.
  22. * Host reactions after an observed event use explicit tight overrides, so this generous startup
  23. * allowance cannot hide multi-second reap regressions.
  24. */
  25. function waitFor(assertion: () => void, timeout = 10_000): Promise<void> {
  26. return vi.waitFor(assertion, { timeout, interval: 50 })
  27. }
  28. /** The vm-context escape hatch, spelled once: real Worker tests use it to make the WORKER misbehave. */
  29. const ESCAPE = "globalThis.constructor.constructor('return process')()"
  30. /** One controllable child run: the test (or auto mode) settles it. */
  31. interface ControlledRun {
  32. request: SubagentStartRequest
  33. /** Fulfill the provider's async start with a ready child. */
  34. publish(): void
  35. /** Reject the provider's async start before ownership transfer. */
  36. rejectStart(error: unknown): void
  37. settle(result: SubagentResult): void
  38. rejectResult(error: unknown): void
  39. cancelled: string | undefined
  40. disposed: boolean
  41. disposeCalls: number
  42. }
  43. /**
  44. * A scripted in-test provider over the REAL SubagentService registry: `auto`
  45. * settles each run via the reply function on a microtask; `manual` piles runs
  46. * up in `runs` for the test to settle. A run aborts (settles `aborted`) when
  47. * the request signal fires, like the real in-process backends.
  48. */
  49. class StubProvider implements SubagentProvider {
  50. readonly capabilities: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: true, persona: false }
  51. readonly inheritsParentContext = false
  52. readonly runs: ControlledRun[] = []
  53. constructor(
  54. readonly name: string,
  55. private readonly reply?: (request: SubagentStartRequest, index: number) => SubagentResult,
  56. private readonly disposeDelayMs = 0,
  57. private readonly deferStart = false,
  58. private readonly onAbortString?: (reason: string | undefined, index: number) => void,
  59. private readonly onSignalAbort?: (reason: unknown, index: number) => void,
  60. ) {}
  61. async start(request: SubagentStartRequest): Promise<SubagentRun> {
  62. const startGate = Promise.withResolvers<undefined>()
  63. const terminal = Promise.withResolvers<SubagentResult>()
  64. terminal.promise.catch(() => { /* provider owns early settlement until publication */ })
  65. let published = false
  66. const controlled: ControlledRun = {
  67. request,
  68. publish: () => { published = true; startGate.resolve(undefined) },
  69. rejectStart: (error) => { startGate.reject(error) },
  70. settle: (result) => { terminal.resolve(result) },
  71. rejectResult: (error) => { terminal.reject(error) },
  72. cancelled: undefined,
  73. disposed: false,
  74. disposeCalls: 0,
  75. }
  76. this.runs.push(controlled)
  77. const index = this.runs.length - 1
  78. request.signal.addEventListener('abort', () => {
  79. controlled.cancelled = String(request.signal.reason ?? 'cancelled')
  80. this.onAbortString?.(String(request.signal.reason ?? 'cancelled'), index)
  81. this.onSignalAbort?.(request.signal.reason, index)
  82. if (published) terminal.resolve({ output: [], stopReason: 'aborted' })
  83. else startGate.reject(new Error('child start aborted before publication'))
  84. }, { once: true })
  85. if (!this.deferStart) controlled.publish()
  86. if (this.reply) {
  87. const reply = this.reply
  88. queueMicrotask(() => { terminal.resolve(reply(request, index)) })
  89. }
  90. try {
  91. await startGate.promise
  92. } catch (error: unknown) {
  93. controlled.disposeCalls += 1
  94. controlled.disposed = true
  95. throw error
  96. }
  97. if (request.signal.aborted) throw new Error('child start aborted before publication')
  98. return {
  99. id: SessionId(`stub-child-${index}`),
  100. localAgent: undefined,
  101. result: terminal.promise,
  102. dispose: () => {
  103. controlled.disposeCalls += 1
  104. if (this.disposeDelayMs === 0) {
  105. controlled.disposed = true
  106. return Promise.resolve()
  107. }
  108. return new Promise<void>((resolve) => {
  109. setTimeout(() => {
  110. controlled.disposed = true
  111. resolve()
  112. }, this.disposeDelayMs)
  113. })
  114. },
  115. }
  116. }
  117. }
  118. /** Text-reply helper for auto providers. */
  119. function text(reply: string): SubagentResult {
  120. return { output: [{ type: 'text', text: reply }], stopReason: 'completed' }
  121. }
  122. interface SetupOptions {
  123. config?: Config
  124. reply?: (request: SubagentStartRequest, index: number) => SubagentResult
  125. manual?: boolean
  126. disposeDelayMs?: number
  127. deferStart?: boolean
  128. onChildAbortString?: (reason: string | undefined, index: number) => void
  129. onChildSignalAbort?: (reason: unknown, index: number) => void
  130. }
  131. async function setup(options?: SetupOptions) {
  132. const ctx = new Context()
  133. await ctx.plugin(SubagentService)
  134. const provider = new StubProvider(
  135. 'stub',
  136. options?.manual ? undefined : options?.reply ?? (() => text('stub reply')),
  137. options?.disposeDelayMs ?? 0,
  138. options?.deferStart ?? false,
  139. options?.onChildAbortString,
  140. options?.onChildSignalAbort,
  141. )
  142. ctx.subagents.registerProvider(provider)
  143. // A fixed concurrency ceiling: the auto-resolved default is machine-derived
  144. // (cores - 2, floored at 1), so tests that expect N children in flight
  145. // would wedge on small CI runners.
  146. const engineFiber = await ctx.plugin(WorkerWorkflowEngine, { provider: 'stub', maxConcurrentAgents: 8, ...options?.config })
  147. return { ctx, provider, parent: fakeParent(), engineFiber }
  148. }
  149. /** The standard test meta plus a body, spread into a start request. */
  150. function scripted(body: string, metaExtra?: Partial<WorkflowMeta>): { script: string; meta: WorkflowMeta } {
  151. return { script: body, meta: { name: 'test-flow', description: 'a test workflow', ...metaExtra } }
  152. }
  153. /** Start + await one run, disposing on the way out. */
  154. async function run(ctx: Context, parent: Agent, source: { script: string; meta: WorkflowMeta }, args?: unknown): Promise<WorkflowResult> {
  155. const handle = ctx.workflows.start({ ...source, parent, ...args !== undefined ? { args } : {} })
  156. try {
  157. return await handle.result
  158. } finally {
  159. await handle.dispose()
  160. }
  161. }
  162. describe('dsh-workflow-workerthread', () => {
  163. describe('script execution over a real worker thread', () => {
  164. it('runs a script end-to-end: agent() text results, phases, log, args, return value, events', async () => {
  165. const { ctx, parent, provider } = await setup({ reply: (_request, index) => text(`answer-${index}`) })
  166. const events: [string, unknown[]][] = []
  167. for (const name of ['workflow/start', 'workflow/phase', 'workflow/log', 'workflow/agent-start', 'workflow/agent-end', 'workflow/end'] as const) {
  168. ctx.on(name, (...payload: unknown[]) => { events.push([name, payload]) })
  169. }
  170. const result = await run(ctx, parent, scripted(`
  171. phase('Scan')
  172. log('starting with ' + args.files.length + ' files')
  173. const answers = await pipeline(args.files, (prev, item) => agent('read ' + item))
  174. phase('Report')
  175. return { answers, count: args.files.length }
  176. `, { phases: [{ title: 'Scan' }, { title: 'Report' }] }), { files: ['a.ts', 'b.ts'] })
  177. expect(result.stopReason).toBe('completed')
  178. expect(result.agentsStarted).toBe(2)
  179. expect(result.value).toEqual({ answers: ['answer-0', 'answer-1'], count: 2 })
  180. expect(provider.runs.every(r => r.disposed)).toBe(true)
  181. const names = events.map(([name]) => name)
  182. expect(names[0]).toBe('workflow/start')
  183. expect(names).toContain('workflow/phase')
  184. expect(names).toContain('workflow/log')
  185. expect(names.at(-1)).toBe('workflow/end')
  186. const info = events[0]![1][0] as WorkflowRunInfo
  187. expect(info.meta.name).toBe('test-flow')
  188. const end = events.at(-1)![1][1] as Record<string, unknown>
  189. expect(end).toEqual({ stopReason: 'completed', agentsStarted: 2 })
  190. expect('value' in end).toBe(false)
  191. })
  192. it('agent({schema, model}) forwards outputSchema and agentOptions to the provider across the thread', async () => {
  193. const { ctx, parent, provider } = await setup({
  194. reply: () => ({ output: [], structured: { files: ['x.ts', 'y.ts'] }, stopReason: 'completed' }),
  195. })
  196. const result = await run(ctx, parent, scripted(`
  197. const found = await agent('list files', { model: 'deepseek-v4-pro', schema: { type: 'object', properties: { files: { type: 'array', items: { type: 'string' } } }, required: ['files'] } })
  198. return { first: found.files[0], count: found.files.length }
  199. `))
  200. expect(result.value).toEqual({ first: 'x.ts', count: 2 })
  201. expect(provider.runs[0]!.request.outputSchema).toEqual({
  202. type: 'object',
  203. properties: { files: { type: 'array', items: { type: 'string' } } },
  204. required: ['files'],
  205. })
  206. expect(provider.runs[0]!.request.agentOptions).toEqual({ model: 'deepseek-v4-pro' })
  207. expect(provider.runs[0]!.request.parent).toBeDefined()
  208. })
  209. it('agent({provider}) forwards provider-only agentOptions across the thread', async () => {
  210. const { ctx, parent, provider } = await setup()
  211. const result = await run(ctx, parent, scripted("return await agent('route me', { provider: 'openai' })"))
  212. expect(result.value).toBe('stub reply')
  213. expect(provider.runs[0]!.request.agentOptions).toEqual({ provider: 'openai' })
  214. })
  215. it('a start-request provider override selects every child without changing the engine default', async () => {
  216. const { ctx, parent, provider } = await setup()
  217. const selected = new StubProvider('selected', () => text('selected reply'))
  218. ctx.subagents.registerProvider(selected)
  219. const overridden = ctx.workflows.start({
  220. ...scripted("return await agent('route this run')"),
  221. parent,
  222. subagentProvider: 'selected',
  223. })
  224. expect((await overridden.result).value).toBe('selected reply')
  225. await overridden.dispose()
  226. expect(selected.runs).toHaveLength(1)
  227. expect(provider.runs).toHaveLength(0)
  228. const ordinary = await run(ctx, parent, scripted("return await agent('use the default')"))
  229. expect(ordinary.value).toBe('stub reply')
  230. expect(provider.runs).toHaveLength(1)
  231. })
  232. it('rejects invalid start-request provider routes before publishing a run', async () => {
  233. const { ctx, parent } = await setup()
  234. let starts = 0
  235. ctx.on('workflow/start', () => { starts += 1 })
  236. const messages: string[] = []
  237. for (const subagentProvider of ['', 'missing']) {
  238. let run: WorkflowRun | undefined
  239. let thrown: unknown
  240. try {
  241. run = ctx.workflows.start({
  242. ...scripted("return 'must not start'"),
  243. parent,
  244. subagentProvider,
  245. })
  246. } catch (error: unknown) {
  247. thrown = error
  248. }
  249. await run?.dispose()
  250. messages.push(thrown instanceof Error ? thrown.message : '')
  251. }
  252. expect(messages).toEqual([
  253. 'workflow subagentProvider must be a non-empty normalized string',
  254. 'no subagent provider registered for "missing"',
  255. ])
  256. expect(starts).toBe(0)
  257. })
  258. it('rejects invalid per-run total-agent caps before publishing a run', async () => {
  259. const { ctx, parent } = await setup({ config: { maxTotalAgents: 2 } })
  260. let starts = 0
  261. ctx.on('workflow/start', () => { starts += 1 })
  262. const errors: unknown[] = []
  263. for (const maxTotalAgents of [0, 1.5, Number.NaN, 3]) {
  264. try {
  265. const handle = ctx.workflows.start({
  266. ...scripted("return 'must not start'"),
  267. parent,
  268. maxTotalAgents,
  269. })
  270. await handle.dispose()
  271. } catch (error: unknown) {
  272. errors.push(error)
  273. }
  274. }
  275. expect(errors.slice(0, 3)).toEqual(Array(3).fill(expect.objectContaining({
  276. code: 'INVALID_ARGUMENT',
  277. message: 'workflow maxTotalAgents must be a positive safe integer',
  278. })))
  279. expect(errors[3]).toMatchObject({
  280. code: 'INVALID_ARGUMENT',
  281. message: 'workflow maxTotalAgents 3 exceeds the engine ceiling 2',
  282. })
  283. expect(starts).toBe(0)
  284. })
  285. it('enforces a per-run total-agent cap below the engine ceiling', async () => {
  286. const { ctx, parent } = await setup({ config: { maxTotalAgents: 2 } })
  287. const handle = ctx.workflows.start({
  288. ...scripted("await agent('first'); await agent('second'); return 'unreachable'"),
  289. parent,
  290. maxTotalAgents: 1,
  291. })
  292. const result = await handle.result
  293. expect(result.stopReason).toBe('error')
  294. expect(result.agentsStarted).toBe(1)
  295. expect(result.error).toContain('total agent cap (1)')
  296. await handle.dispose()
  297. })
  298. it('a fatal hook error inside the worker kills the script and reports the error', async () => {
  299. const { ctx, parent } = await setup()
  300. const result = await run(ctx, parent, scripted("return await parallel([() => agent('x', { isolation: 'worktree' })])"))
  301. expect(result.stopReason).toBe('error')
  302. expect(result.error).toContain('"isolation" is deferred')
  303. })
  304. it('rejects an unregistered configured provider before publishing a run', async () => {
  305. const { ctx, parent } = await setup({ config: { provider: 'nonexistent' } })
  306. let thrown: unknown
  307. try {
  308. ctx.workflows.start({ ...scripted("return 'must not start'"), parent })
  309. } catch (error: unknown) {
  310. thrown = error
  311. }
  312. expect(thrown).toMatchObject({
  313. code: 'AGENT_START',
  314. message: 'no subagent provider registered for "nonexistent"',
  315. })
  316. })
  317. it('waits for async provider start before announcing a result that settled early', async () => {
  318. const { ctx, parent, provider } = await setup({ manual: true, deferStart: true })
  319. const order: string[] = []
  320. ctx.on('workflow/agent-start', (_info, agent) => { order.push(`start:${agent.seq}`) })
  321. ctx.on('workflow/agent-end', (_info, agent) => { order.push(`end:${agent.outcome}`) })
  322. ctx.on('workflow/end', () => { order.push('run-end') })
  323. const handle = ctx.workflows.start({ ...scripted("return await agent('p')"), parent })
  324. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  325. const early = text('accepted value')
  326. provider.runs[0]!.settle(early)
  327. // The provider still owns this early result while start is pending.
  328. await new Promise(resolve => setTimeout(resolve, 0))
  329. expect(order).toEqual([])
  330. provider.runs[0]!.publish()
  331. const result = await handle.result
  332. expect(result.value).toBe('accepted value')
  333. expect(order).toEqual(['start:1', 'end:completed', 'run-end'])
  334. await handle.dispose()
  335. expect(provider.runs[0]!.disposeCalls).toBe(1)
  336. })
  337. it('observes an early result rejection but sends ChildStarted before ChildFailed after start fulfills', async () => {
  338. const { ctx, parent, provider } = await setup({ manual: true, deferStart: true })
  339. const lifecycle: string[] = []
  340. ctx.on('workflow/agent-start', () => { lifecycle.push('start') })
  341. ctx.on('workflow/agent-end', (_info, agent) => { lifecycle.push(`end:${agent.outcome}`) })
  342. const handle = ctx.workflows.start({
  343. ...scripted("try { await agent('p'); return 'unreachable' } catch (e) { return { code: e.code, message: e.message } }"),
  344. parent,
  345. })
  346. const worker = (handle as unknown as { worker: { postMessage(message: unknown): void } }).worker
  347. const post = vi.spyOn(worker, 'postMessage')
  348. const childMessageTypes = (): HostToWorkerType[] => post.mock.calls
  349. .map(([message]) => (message as { type: HostToWorkerType }).type)
  350. .filter(type => type === HostToWorkerType.ChildStarted || type === HostToWorkerType.ChildFailed)
  351. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  352. provider.runs[0]!.rejectResult(new Error('backend failed before publication'))
  353. await new Promise(resolve => setTimeout(resolve, 0))
  354. expect(childMessageTypes()).toEqual([])
  355. expect(lifecycle).toEqual([])
  356. provider.runs[0]!.publish()
  357. const result = await handle.result
  358. expect(result.value).toMatchObject({ code: 'AGENT_RESULT' })
  359. expect((result.value as { message: string }).message).toContain('backend failed before publication')
  360. expect(childMessageTypes()).toEqual([HostToWorkerType.ChildStarted, HostToWorkerType.ChildFailed])
  361. expect(lifecycle).toEqual(['start', 'end:failed'])
  362. post.mockRestore()
  363. await handle.dispose()
  364. })
  365. it('classifies provider start rejection as AGENT_START, drops an early result, and emits no false lifecycle pair', async () => {
  366. const { ctx, parent, provider } = await setup({ manual: true, deferStart: true })
  367. const lifecycle: string[] = []
  368. ctx.on('workflow/agent-start', () => { lifecycle.push('start') })
  369. ctx.on('workflow/agent-end', () => { lifecycle.push('end') })
  370. const handle = ctx.workflows.start({
  371. ...scripted("try { await agent('p'); return 'unreachable' } catch (e) { return { code: e.code, message: e.message } }"),
  372. parent,
  373. })
  374. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  375. // ACP-style failure can settle result(error) before its session/publication
  376. // boundary rejects. Start rejection must dominate that buffered child outcome.
  377. provider.runs[0]!.settle({ output: [], stopReason: 'error' })
  378. await new Promise(resolve => setTimeout(resolve, 0))
  379. provider.runs[0]!.rejectStart(new Error('publication rolled back'))
  380. const result = await handle.result
  381. expect(result.value).toMatchObject({ code: 'AGENT_START' })
  382. expect((result.value as { message: string }).message).toContain('publication rolled back')
  383. expect(lifecycle).toEqual([])
  384. await waitFor(() => {
  385. expect(provider.runs[0]!.disposed).toBe(true)
  386. expect(provider.runs[0]!.disposeCalls).toBe(1)
  387. })
  388. await handle.dispose()
  389. expect(provider.runs[0]!.disposeCalls).toBe(1)
  390. })
  391. it('aborts a pending provider start once without publishing workflow lifecycle', async () => {
  392. const { ctx, parent, provider } = await setup({ manual: true, deferStart: true, config: { disposeGraceMs: 500 } })
  393. const lifecycle: string[] = []
  394. ctx.on('workflow/agent-start', () => { lifecycle.push('start') })
  395. ctx.on('workflow/agent-end', () => { lifecycle.push('end') })
  396. const handle = ctx.workflows.start({ ...scripted("return await agent('pending')"), parent })
  397. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  398. const disposal = handle.dispose()
  399. await waitFor(() => {
  400. expect(provider.runs[0]!.cancelled).toBe('workflow disposed')
  401. expect(provider.runs[0]!.disposed).toBe(true)
  402. })
  403. // Ensure the host-driven disposal removed the registry entry before the
  404. // late start rejection; its callback must not invoke dispose again.
  405. await new Promise(resolve => setTimeout(resolve, 0))
  406. provider.runs[0]!.rejectStart(new Error('cancelled before publication'))
  407. const result = await handle.result
  408. await disposal
  409. expect(result.stopReason).toBe('cancelled')
  410. expect(lifecycle).toEqual([])
  411. expect(provider.runs[0]!.disposeCalls).toBe(1)
  412. })
  413. it('a child result REJECTION crosses back as a fatal AGENT_RESULT error (a broken provider is not a failed child)', async () => {
  414. const ctx = new Context()
  415. await ctx.plugin(SubagentService)
  416. const provider: SubagentProvider = {
  417. name: 'rejecting',
  418. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false },
  419. inheritsParentContext: false,
  420. start: async () => ({
  421. id: SessionId('reject-child'),
  422. localAgent: undefined,
  423. result: Promise.reject(new Error('backend exploded')),
  424. dispose: () => Promise.resolve(),
  425. }),
  426. }
  427. ctx.subagents.registerProvider(provider)
  428. await ctx.plugin(WorkerWorkflowEngine, { provider: 'rejecting', maxConcurrentAgents: 2 })
  429. const result = await run(ctx, fakeParent(), scripted(`
  430. try { await agent('p'); return 'unreachable' } catch (e) { return { name: e.name, code: e.code, fatal: e.fatal, message: e.message } }
  431. `))
  432. expect(result.value).toMatchObject({ name: 'WorkflowError', code: 'AGENT_RESULT', fatal: true })
  433. expect((result.value as { message: string }).message).toContain('backend exploded')
  434. })
  435. it('maps a non-JSON ready-child result to fatal AGENT_RESULT instead of wedging the bridge', async () => {
  436. const { ctx, parent } = await setup({
  437. reply: () => ({ output: [], structured: () => { /* deliberately outside lossless JSON */ }, stopReason: 'completed' }),
  438. })
  439. const result = await run(ctx, parent, scripted(`
  440. try { await agent('p'); return 'unreachable' } catch (e) { return { code: e.code, message: e.message } }
  441. `))
  442. expect(result.value).toMatchObject({ code: 'AGENT_RESULT' })
  443. expect((result.value as { message: string }).message).toContain('workflow child result could not cross the worker boundary')
  444. })
  445. it('contains a non-JSON result even if the injected subagent service violates its normalization contract', async () => {
  446. // The real worker boundary must reject a non-JSON same-process result.
  447. const { ctx, parent } = await setup()
  448. const invalid = {
  449. output: [],
  450. structured: () => { /* deliberately outside lossless JSON */ },
  451. stopReason: 'completed',
  452. } as unknown as SubagentResult
  453. const start = vi.spyOn(ctx.subagents, 'start').mockResolvedValue({
  454. id: SessionId('raw-invalid-child'),
  455. localAgent: undefined,
  456. result: Promise.resolve(invalid),
  457. dispose: () => Promise.resolve(),
  458. })
  459. const result = await run(ctx, parent, scripted(`
  460. try { await agent('p'); return 'unreachable' } catch (e) { return { code: e.code, message: e.message } }
  461. `))
  462. expect(start).toHaveBeenCalledOnce()
  463. expect(result.value).toMatchObject({ code: 'AGENT_RESULT' })
  464. expect((result.value as { message: string }).message)
  465. .toContain('workflow child result could not cross the worker boundary')
  466. })
  467. it('a child whose dispose() throws synchronously cannot wedge the script (the host acks anyway)', async () => {
  468. const ctx = new Context()
  469. await ctx.plugin(SubagentService)
  470. const provider: SubagentProvider = {
  471. name: 'bad-dispose',
  472. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false },
  473. inheritsParentContext: false,
  474. start: async () => ({
  475. id: SessionId('bad-dispose-child'),
  476. localAgent: undefined,
  477. result: Promise.resolve({ output: [{ type: 'text', text: 'fine' }], stopReason: 'completed' }),
  478. cancel: () => { /* settled already */ },
  479. dispose: () => { throw new Error('dispose exploded') },
  480. }),
  481. }
  482. ctx.subagents.registerProvider(provider)
  483. await ctx.plugin(WorkerWorkflowEngine, { provider: 'bad-dispose', maxConcurrentAgents: 2 })
  484. const result = await run(ctx, fakeParent(), scripted("return await agent('p')"))
  485. expect(result.stopReason).toBe('completed')
  486. expect(result.value).toBe('fine')
  487. })
  488. it('a child dispose() rejecting an UNRENDERABLE value still acks — the containment warn is total', async () => {
  489. const ctx = new Context()
  490. await ctx.plugin(SubagentService)
  491. const provider: SubagentProvider = {
  492. name: 'coercion-trap-dispose',
  493. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false },
  494. inheritsParentContext: false,
  495. start: async () => ({
  496. id: SessionId('trap-child'),
  497. localAgent: undefined,
  498. result: Promise.resolve({ output: [{ type: 'text', text: 'fine' }], stopReason: 'completed' }),
  499. cancel: () => { /* settled already */ },
  500. // The rejection VALUE's own coercion throws: a warn built with bare
  501. // String(error) would itself throw, skipping the ChildDisposed ack
  502. // and wedging the script's finally until the grace/terminate path.
  503. // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- the non-Error rejection IS the scenario under test
  504. dispose: () => Promise.reject({ toString: () => { throw new Error('coercion trap') } }),
  505. }),
  506. }
  507. ctx.subagents.registerProvider(provider)
  508. await ctx.plugin(WorkerWorkflowEngine, { provider: 'coercion-trap-dispose', maxConcurrentAgents: 2 })
  509. const result = await run(ctx, fakeParent(), scripted("return await agent('p')"))
  510. expect(result.stopReason).toBe('completed')
  511. expect(result.value).toBe('fine')
  512. })
  513. it('the worker spawns with an EMPTY environment: an escaped script finds no ambient credentials', async () => {
  514. const { ctx, parent } = await setup()
  515. // A canary in the HARNESS process's env: with an inherited environment
  516. // the escape below would read it back (exactly how DEEPSEEK_API_KEY
  517. // would leak); env: {} in the spawn options is what keeps it out.
  518. process.env.WORKFLOW_ENV_CANARY = 'leak me'
  519. try {
  520. const result = await run(ctx, parent, scripted(`
  521. const proc = ${ESCAPE}
  522. return { canary: proc.env.WORKFLOW_ENV_CANARY ?? null, keys: Object.keys(proc.env).length }
  523. `))
  524. expect(result.stopReason).toBe('completed')
  525. expect(result.value).toEqual({ canary: null, keys: 0 })
  526. } finally {
  527. delete process.env.WORKFLOW_ENV_CANARY
  528. }
  529. })
  530. it('the unbuilt worker forwards exactly TSX_TSCONFIG_PATH through the scrub: the paths-map pin survives, secrets do not', async () => {
  531. const { ctx, parent } = await setup()
  532. // The ACP snapshot harness runs the parent with its cwd OUTSIDE the
  533. // repo and pins the repo tsconfig through this variable; the worker
  534. // must inherit the pin (or its dsh-* imports silently resolve to
  535. // unbuilt lib/ bundles) while every other variable stays scrubbed.
  536. const tsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url))
  537. process.env.TSX_TSCONFIG_PATH = tsconfig
  538. process.env.WORKFLOW_ENV_CANARY = 'leak me'
  539. try {
  540. const result = await run(ctx, parent, scripted(`
  541. const proc = ${ESCAPE}
  542. return { keys: Object.keys(proc.env), tsconfig: proc.env.TSX_TSCONFIG_PATH }
  543. `))
  544. expect(result.stopReason).toBe('completed')
  545. expect(result.value).toEqual({ keys: ['TSX_TSCONFIG_PATH'], tsconfig })
  546. } finally {
  547. delete process.env.TSX_TSCONFIG_PATH
  548. delete process.env.WORKFLOW_ENV_CANARY
  549. }
  550. })
  551. })
  552. describe('lifecycle: parse errors, cancellation, termination, disposal', () => {
  553. it('start() throws synchronously for invalid meta data or an unparseable body (host-side pre-checks)', async () => {
  554. const { ctx, parent } = await setup()
  555. // Meta is DATA — shape violations reject loud, every one named.
  556. expect(() => ctx.workflows.start({ script: 'return 1', meta: { name: '', description: 'd' }, parent })).toThrow(/meta\.name must be a non-empty string/)
  557. 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/)
  558. expect(() => ctx.workflows.start({ ...scripted('return ((('), parent })).toThrow(/does not parse/)
  559. // The likeliest authoring slip — a Claude Code-style meta header in the
  560. // body — gets a pointed message, not a bare SyntaxError.
  561. expect(() => ctx.workflows.start({ ...scripted("export const meta = { name: 'x', description: 'd' }\nreturn 1"), parent })).toThrow(/meta rides the `meta` request field/)
  562. })
  563. it('cancel() aborts in-flight children (signal AND cancel RPC) and settles the run cancelled', async () => {
  564. const { ctx, parent, provider } = await setup({ manual: true })
  565. const ends: unknown[] = []
  566. ctx.on('workflow/agent-end', (_info, agent) => { ends.push(agent) })
  567. const runEnds: WorkflowResultInfo[] = []
  568. ctx.on('workflow/end', (_info, result) => { runEnds.push(result) })
  569. const handle = ctx.workflows.start({ ...scripted("return await agent('long job')"), parent })
  570. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  571. handle.cancel('user stopped it')
  572. const result = await handle.result
  573. expect(result.stopReason).toBe('cancelled')
  574. expect(result.error).toContain('user stopped it')
  575. await handle.dispose()
  576. expect(provider.runs[0]!.disposed).toBe(true)
  577. expect(ends).toEqual([expect.objectContaining({ seq: 1, outcome: 'cancelled' })])
  578. // workflow/end is an observer's only death signal: it fires for a
  579. // cancelled run too, mirroring the settled outcome data.
  580. expect(runEnds).toEqual([{ stopReason: 'cancelled', error: result.error, agentsStarted: result.agentsStarted }])
  581. })
  582. it('an already-aborted request signal cancels before the body ever runs (the go handshake holds it)', async () => {
  583. const { ctx, parent, provider } = await setup()
  584. const controller = new AbortController()
  585. controller.abort()
  586. const logs: string[] = []
  587. ctx.on('workflow/log', (_info, message) => { logs.push(message) })
  588. const handle = ctx.workflows.start({ ...scripted("log('ran')\nreturn 123"), parent, signal: controller.signal })
  589. const result = await handle.result
  590. expect(result.stopReason).toBe('cancelled')
  591. expect(result.value).toBeNull()
  592. expect(logs).toEqual([])
  593. expect(provider.runs.length).toBe(0)
  594. await handle.dispose()
  595. })
  596. it('cancel() right after start() cancels before the body runs; the signal aborting mid-run cancels like cancel()', async () => {
  597. const { ctx, parent, provider } = await setup({ manual: true })
  598. const first = ctx.workflows.start({ ...scripted("return await agent('never')"), parent })
  599. // No-reason cancel: the canonical default reason must ride the result.
  600. first.cancel()
  601. const firstResult = await first.result
  602. expect(firstResult.stopReason).toBe('cancelled')
  603. expect(firstResult.error).toContain('workflow cancelled')
  604. expect(provider.runs.length).toBe(0)
  605. await first.dispose()
  606. const controller = new AbortController()
  607. const second = ctx.workflows.start({ ...scripted("return await agent('job')"), parent, signal: controller.signal })
  608. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  609. controller.abort()
  610. expect((await second.result).stopReason).toBe('cancelled')
  611. await second.dispose()
  612. })
  613. it('removes the exact external abort callback on first settlement or teardown', async () => {
  614. const { ctx, parent } = await setup()
  615. const settledController = new AbortController()
  616. const settledAdd = vi.spyOn(settledController.signal, 'addEventListener')
  617. const settledRemove = vi.spyOn(settledController.signal, 'removeEventListener')
  618. const completed = ctx.workflows.start({ ...scripted('return 123'), parent, signal: settledController.signal })
  619. const settledAbort = settledAdd.mock.calls.find(([type]) => type === 'abort')?.[1]
  620. expect(typeof settledAbort).toBe('function')
  621. await expect(completed.result).resolves.toMatchObject({ value: 123, stopReason: 'completed' })
  622. expect(settledRemove).toHaveBeenCalledWith('abort', settledAbort)
  623. const cancelAfterSettle = vi.spyOn(completed, 'cancel')
  624. settledController.abort()
  625. expect(cancelAfterSettle).not.toHaveBeenCalled()
  626. cancelAfterSettle.mockRestore()
  627. await completed.dispose()
  628. const manual = await setup({ manual: true })
  629. const teardownController = new AbortController()
  630. const teardownAdd = vi.spyOn(teardownController.signal, 'addEventListener')
  631. const teardownRemove = vi.spyOn(teardownController.signal, 'removeEventListener')
  632. const tornDown = manual.ctx.workflows.start({
  633. ...scripted("return await agent('job')"),
  634. parent: manual.parent,
  635. signal: teardownController.signal,
  636. })
  637. await waitFor(() => { expect(manual.provider.runs).toHaveLength(1) })
  638. const teardownAbort = teardownAdd.mock.calls.find(([type]) => type === 'abort')?.[1]
  639. expect(typeof teardownAbort).toBe('function')
  640. const disposing = tornDown.dispose()
  641. expect(teardownRemove).toHaveBeenCalledWith('abort', teardownAbort)
  642. await disposing
  643. })
  644. it('a child-start racing the host cancel is refused: no child starts after cancellation', async () => {
  645. const { ctx, parent, provider } = await setup({ manual: true })
  646. // Cancel from INSIDE the log listener: the worker has already posted
  647. // its child-start (queued right behind the log message), so the host
  648. // processes it with cancelReason set — the refusal arm no real-world
  649. // timing can hit reliably. (The closure runs only after `handle` below
  650. // is initialized — the listener fires on the worker's first message.)
  651. ctx.on('workflow/log', () => { handle.cancel('cancelled from the log listener') })
  652. const handle = ctx.workflows.start({ ...scripted("log('mark')\nreturn await agent('late')"), parent })
  653. const result = await handle.result
  654. expect(result.stopReason).toBe('cancelled')
  655. expect(provider.runs.length).toBe(0)
  656. await handle.dispose()
  657. })
  658. it('post-cancel narration is suppressed host-side, and completion racing a cancel reports cancelled', async () => {
  659. const { ctx, parent } = await setup()
  660. const narration: string[] = []
  661. ctx.on('workflow/log', (_info, message) => { narration.push(message) })
  662. ctx.on('workflow/phase', (_info, title) => { narration.push(`phase:${title}`) })
  663. const handle = ctx.workflows.start({
  664. // The sync spin keeps the worker's loop busy so the cancel message
  665. // cannot be processed before the script settles `completed` — the
  666. // worker posts a completed result that must LOSE to the in-flight
  667. // host cancellation. The trailing narration exercises host-side
  668. // suppression: posted pre-cancel-processing worker-side, arriving
  669. // post-cancel host-side.
  670. ...scripted(`
  671. log('started')
  672. const end = Date.now() + 1000
  673. while (Date.now() < end) {}
  674. phase('late phase')
  675. log('late log')
  676. return 'done'
  677. `),
  678. parent,
  679. })
  680. await waitFor(() => { expect(narration).toContain('started') })
  681. handle.cancel('raced the completion')
  682. const result = await handle.result
  683. expect(result.stopReason).toBe('cancelled')
  684. expect(result.error).toContain('raced the completion')
  685. expect(narration).toEqual(['started'])
  686. await handle.dispose()
  687. }, 15_000)
  688. it('cancel() force-settles a script parked on a promise no hook owns, and TERMINATES its worker', async () => {
  689. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: 50 } })
  690. const runEnds: WorkflowResultInfo[] = []
  691. ctx.on('workflow/end', (_info, result) => { runEnds.push(result) })
  692. const handle = ctx.workflows.start({
  693. ...scripted("await new Promise(() => {})\nreturn 'unreachable'"),
  694. parent,
  695. })
  696. handle.cancel('user aborted')
  697. const result = await handle.result
  698. expect(result.stopReason).toBe('cancelled')
  699. expect(result.error).toContain('user aborted')
  700. // The grace force-settle fires workflow/end exactly like an ordinary
  701. // settlement — a terminated script's death still reaches observers.
  702. expect(runEnds).toEqual([{ stopReason: 'cancelled', error: result.error, agentsStarted: 0 }])
  703. await handle.dispose()
  704. })
  705. it('dispose() on a stuck script returns within the grace instead of hanging (result settles cancelled)', async () => {
  706. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: 50 } })
  707. const handle = ctx.workflows.start({
  708. ...scripted("await new Promise(() => {})\nreturn 'unreachable'"),
  709. parent,
  710. })
  711. const before = Date.now()
  712. await handle.dispose()
  713. expect(Date.now() - before).toBeLessThan(2000)
  714. const result = await handle.result
  715. expect(result.stopReason).toBe('cancelled')
  716. })
  717. it('dispose() is idempotent and settles cleanly after a completed run', async () => {
  718. const { ctx, parent } = await setup()
  719. const handle = ctx.workflows.start({ ...scripted('return 1'), parent })
  720. await handle.result
  721. await handle.dispose()
  722. await handle.dispose()
  723. })
  724. it('a settled run arms NO grace timer: disposing a completed run must not pin it for disposeGraceMs', async () => {
  725. // A distinctive grace so the spy can tell the cancel-path grace timer
  726. // apart from every other timeout in flight.
  727. const GRACE = 44_444
  728. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: GRACE } })
  729. const handle = ctx.workflows.start({ ...scripted('return 1'), parent })
  730. await handle.result
  731. const spy = vi.spyOn(globalThis, 'setTimeout')
  732. try {
  733. await handle.dispose()
  734. // dispose()'s own bounded-wait sleep is the ONLY grace-sized timer
  735. // allowed here; before the settled guard, cancel() armed a second one
  736. // that nothing would ever clear (the run was already settled), keeping
  737. // the WorkerRun/Worker closure alive until the grace expired.
  738. const graceTimers = spy.mock.calls.filter(call => call[1] === GRACE)
  739. expect(graceTimers.length).toBe(1)
  740. } finally {
  741. spy.mockRestore()
  742. }
  743. })
  744. it('strays: children fired without await are aborted once the script settles, and dispose() waits for their disposal', async () => {
  745. const { ctx, parent, provider } = await setup({ manual: true, disposeDelayMs: 40 })
  746. const handle = ctx.workflows.start({
  747. ...scripted(`
  748. agent('stray')
  749. return 'done without awaiting'
  750. `),
  751. parent,
  752. })
  753. const result = await handle.result
  754. expect(result.stopReason).toBe('completed')
  755. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  756. await handle.dispose()
  757. // Not a waitFor: by the time dispose() returns, the slow child disposal
  758. // must already be complete (host-side registry quiescence).
  759. expect(provider.runs[0]!.disposed).toBe(true)
  760. })
  761. it('result settlement reaps a registered stray even when the worker cannot relay disposal', async () => {
  762. const { ctx, parent, provider } = await setup({
  763. manual: true,
  764. config: { provider: 'stub', disposeGraceMs: 30_000 },
  765. })
  766. const handle = ctx.workflows.start({
  767. ...scripted("agent('stray')\nawait new Promise(() => {})"),
  768. parent,
  769. })
  770. await waitFor(() => { expect(provider.runs).toHaveLength(1) })
  771. // Claim the host result while the real worker remains wedged, so it can
  772. // send neither ChildDispose nor an exit. This leaves the accepted child
  773. // in the host registry when public disposal begins.
  774. const worker = (handle as unknown as { worker: Worker }).worker
  775. worker.emit('message', {
  776. type: WorkerToHostType.Result,
  777. result: { value: 'synthetic completion', stopReason: 'completed', agentsStarted: 1 },
  778. })
  779. await expect(handle.result).resolves.toMatchObject({ stopReason: 'completed' })
  780. await waitFor(() => { expect(provider.runs[0]!.disposed).toBe(true) }, 1000)
  781. const disposal = handle.dispose()
  782. await disposal
  783. expect(provider.runs[0]!.disposeCalls).toBe(1)
  784. await ctx.fiber.dispose()
  785. })
  786. it('the settle-reap fires the request signal too: a provider honoring ONLY the signal winds its stray down promptly', async () => {
  787. const ctx = new Context()
  788. await ctx.plugin(SubagentService)
  789. const aborted: string[] = []
  790. const provider: SubagentProvider = {
  791. name: 'signal-only',
  792. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false },
  793. inheritsParentContext: false,
  794. start: async (request) => {
  795. let settle!: (result: SubagentResult) => void
  796. const result = new Promise<SubagentResult>((resolve) => { settle = resolve })
  797. request.signal.addEventListener('abort', () => {
  798. aborted.push(String(request.signal.reason))
  799. settle({ output: [], stopReason: 'aborted' })
  800. }, { once: true })
  801. return {
  802. id: SessionId('signal-only-child'),
  803. localAgent: undefined,
  804. result,
  805. dispose: () => Promise.resolve(),
  806. }
  807. },
  808. }
  809. ctx.subagents.registerProvider(provider)
  810. await ctx.plugin(WorkerWorkflowEngine, { provider: 'signal-only', maxConcurrentAgents: 2 })
  811. const handle = ctx.workflows.start({
  812. ...scripted(`
  813. agent('stray, never awaited')
  814. return 'done'
  815. `),
  816. parent: fakeParent(),
  817. })
  818. const result = await handle.result
  819. expect(result.stopReason).toBe('completed')
  820. // BEFORE dispose(): the settlement itself must have aborted the signal —
  821. // without it this child would stay live until dispose's terminate. This
  822. // is a HOST-PROMPTNESS claim, not a cold-start race — a tight explicit
  823. // bound (unlike the file default) so a multi-second reap regression
  824. // cannot pass by outlasting the wait.
  825. await waitFor(() => { expect(aborted).toEqual(['workflow settled']) }, 1000)
  826. await handle.dispose()
  827. })
  828. it('the settle-reap aborts a pending provider start before workflow/end', async () => {
  829. const { ctx, parent, provider } = await setup({ manual: true, deferStart: true })
  830. const childLifecycle: string[] = []
  831. let cancellationAtWorkflowEnd: string | undefined
  832. ctx.on('workflow/agent-start', () => { childLifecycle.push('start') })
  833. ctx.on('workflow/agent-end', () => { childLifecycle.push('end') })
  834. ctx.on('workflow/end', () => {
  835. cancellationAtWorkflowEnd = provider.runs[0]?.cancelled
  836. })
  837. const handle = ctx.workflows.start({
  838. ...scripted(`
  839. agent('start-pending stray')
  840. return 'done'
  841. `),
  842. parent,
  843. })
  844. const result = await handle.result
  845. expect(result.stopReason).toBe('completed')
  846. expect(provider.runs).toHaveLength(1)
  847. expect(provider.runs[0]!.request.signal?.aborted).toBe(true)
  848. expect(provider.runs[0]!.request.signal?.reason).toBe('workflow settled')
  849. expect(provider.runs[0]!.cancelled).toBe('workflow settled')
  850. expect(cancellationAtWorkflowEnd).toBe('workflow settled')
  851. expect(childLifecycle).toEqual([])
  852. await handle.dispose()
  853. expect(provider.runs[0]!.disposeCalls).toBe(1)
  854. })
  855. it('a duplicate Result after the terminal claim cannot repeat cleanup or rewrite the outcome', async () => {
  856. let signalAborts = 0
  857. const { ctx, parent, provider } = await setup({
  858. manual: true,
  859. onChildAbortString: (_reason, index) => { if (index === 0) signalAborts += 1 },
  860. })
  861. const handle = ctx.workflows.start({
  862. ...scripted("agent('stray')\nawait new Promise(() => {})"),
  863. parent,
  864. })
  865. await waitFor(() => { expect(provider.runs).toHaveLength(1) })
  866. const worker = (handle as unknown as { worker: Worker }).worker
  867. worker.emit('message', {
  868. type: WorkerToHostType.Result,
  869. result: { value: 'first', stopReason: 'completed', agentsStarted: 1 },
  870. })
  871. worker.emit('message', {
  872. type: WorkerToHostType.Result,
  873. result: { value: 'late', stopReason: 'completed', agentsStarted: 1 },
  874. })
  875. await expect(handle.result).resolves.toMatchObject({ value: 'first', stopReason: 'completed' })
  876. expect(signalAborts).toBe(1)
  877. await handle.dispose()
  878. expect(signalAborts).toBe(1)
  879. await ctx.fiber.dispose()
  880. })
  881. it('a grace-terminated worker reaps its child on exit without waiting for consumer dispose()', async () => {
  882. const { ctx, parent, provider } = await setup({
  883. manual: true,
  884. config: { provider: 'stub', maxConcurrentAgents: 2, disposeGraceMs: 100 },
  885. })
  886. const handle = ctx.workflows.start({
  887. // Let child-start cross, then make the worker unable to process its
  888. // Cancel message. Grace settles the result and terminates the thread;
  889. // that exit must independently own the host registry's disposal pass.
  890. ...scripted(`
  891. agent('survives until exit reap')
  892. for (let i = 0; i < 20; i++) await null
  893. const end = Date.now() + 1500
  894. while (Date.now() < end) {}
  895. return 'unreachable'
  896. `),
  897. parent,
  898. })
  899. await waitFor(() => { expect(provider.runs).toHaveLength(1) })
  900. handle.cancel('force termination')
  901. const result = await handle.result
  902. expect(result.stopReason).toBe('cancelled')
  903. // Deliberately assert before handle.dispose(): host-owned worker exit,
  904. // not consumer courtesy, is responsible for this resource guarantee.
  905. await waitFor(() => { expect(provider.runs[0]!.disposed).toBe(true) }, 1000)
  906. expect(provider.runs[0]!.disposeCalls).toBe(1)
  907. await handle.dispose()
  908. await ctx.fiber.dispose()
  909. }, 15_000)
  910. 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 () => {
  911. const { ctx, parent, provider } = await setup({
  912. manual: true,
  913. disposeDelayMs: 40,
  914. config: { provider: 'stub', maxConcurrentAgents: 8, disposeGraceMs: 400 },
  915. })
  916. const handle = ctx.workflows.start({
  917. // Same shape as the wedged-cancel test above: the child's start RPC
  918. // reaches the host, then the script seizes its worker's loop, so the
  919. // worker can relay NO dispose RPC — the host's own dispose() drive is
  920. // the only thing that can start (and finish) this child's disposal
  921. // before the grace runs out.
  922. ...scripted(`
  923. agent('wedged child')
  924. for (let i = 0; i < 20; i++) await null
  925. const end = Date.now() + 1500
  926. while (Date.now() < end) {}
  927. return 'raced'
  928. `),
  929. parent,
  930. })
  931. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  932. const before = Date.now()
  933. await handle.dispose()
  934. // Bounded by the grace (plus the terminate), never by the 1.5s spin.
  935. expect(Date.now() - before).toBeLessThan(1200)
  936. // Not a waitFor: dispose() resolving IS the quiescence claim — the slow
  937. // child disposal must be complete, not merely started (before the
  938. // host-driven drive, disposal only STARTED at the post-terminate reap,
  939. // so dispose() returned with it still in flight).
  940. expect(provider.runs[0]!.disposed).toBe(true)
  941. const result = await handle.result
  942. expect(result.stopReason).toBe('cancelled')
  943. }, 15_000)
  944. 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 () => {
  945. const { ctx, parent, provider } = await setup({ manual: true })
  946. const handle = ctx.workflows.start({
  947. ...scripted(`
  948. await agent('long child')
  949. return 'unreachable'
  950. `),
  951. parent,
  952. })
  953. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  954. const handleDispose = handle.dispose()
  955. const result = await handle.result
  956. // The script itself settled (the wrapper's own dispose RPC found the
  957. // child already reaped host-side and was acked) — a missing ack would
  958. // wedge the wrapper's finally until the 5s default grace force-settle.
  959. expect(result.stopReason).toBe('cancelled')
  960. expect(result.error).toContain('workflow disposed')
  961. await handleDispose
  962. expect(provider.runs[0]!.disposed).toBe(true)
  963. // The memo: the host drive and the worker's RPC share one disposal.
  964. expect(provider.runs[0]!.disposeCalls).toBe(1)
  965. })
  966. it('the grace force-settle pairs every stranded start: a host-synthesized cancelled agent-end lands before workflow/end', async () => {
  967. const { ctx, parent, provider } = await setup({ manual: true, config: { provider: 'stub', maxConcurrentAgents: 8, disposeGraceMs: 300 } })
  968. const ends: { seq: number; outcome: string }[] = []
  969. const order: string[] = []
  970. ctx.on('workflow/agent-start', (_info, agent) => { order.push(`start:${agent.seq}`) })
  971. ctx.on('workflow/agent-end', (_info, agent) => {
  972. ends.push({ seq: agent.seq, outcome: agent.outcome })
  973. order.push(`end:${agent.seq}`)
  974. })
  975. ctx.on('workflow/end', () => { order.push('run-end') })
  976. const handle = ctx.workflows.start({
  977. // 'slow' starts and its agent-start crosses to observers (the awaited
  978. // 'fast' call keeps the worker loop turning), then the script seizes
  979. // the loop: the wedged worker can never author slow's agent-end —
  980. // only the host's ledger can close the pair.
  981. ...scripted(`
  982. const p = agent('slow')
  983. await agent('fast')
  984. const end = Date.now() + 1500
  985. while (Date.now() < end) {}
  986. return 'raced'
  987. `),
  988. parent,
  989. })
  990. await waitFor(() => { expect(order.filter(entry => entry.startsWith('start:')).length).toBe(2) })
  991. const fast = provider.runs.find(run => (run.request.prompt[0] as { text?: string }).text === 'fast')!
  992. fast.settle(text('fast done'))
  993. handle.cancel('stop now')
  994. const result = await handle.result
  995. expect(result.stopReason).toBe('cancelled')
  996. // fast's end is the worker's own report; slow's is host-synthesized at
  997. // the force-settle — exactly one end per started seq, no third event.
  998. expect(ends).toEqual([
  999. { seq: 2, outcome: 'completed' },
  1000. { seq: 1, outcome: 'cancelled' },
  1001. ])
  1002. // Both ends reached observers BEFORE workflow/end: a progress consumer
  1003. // can finalize its state at run-end without dangling agents.
  1004. expect(order.indexOf('run-end')).toBe(order.length - 1)
  1005. await handle.dispose()
  1006. }, 15_000)
  1007. it('graceful cancellation keeps pairing worker-authored: exactly one agent-end per start, nothing synthesized on top', async () => {
  1008. const { ctx, parent, provider } = await setup({ manual: true })
  1009. const ends: { seq: number; outcome: string }[] = []
  1010. const order: string[] = []
  1011. ctx.on('workflow/agent-end', (_info, agent) => {
  1012. ends.push({ seq: agent.seq, outcome: agent.outcome })
  1013. order.push(`end:${agent.seq}`)
  1014. })
  1015. ctx.on('workflow/end', () => { order.push('run-end') })
  1016. const handle = ctx.workflows.start({
  1017. ...scripted("await parallel([() => agent('a'), () => agent('b')])\nreturn 'unreachable'"),
  1018. parent,
  1019. })
  1020. await waitFor(() => { expect(provider.runs.length).toBe(2) })
  1021. handle.cancel('user stop')
  1022. const result = await handle.result
  1023. expect(result.stopReason).toBe('cancelled')
  1024. // The live worker reported both pairs itself; the ledger must not add
  1025. // a synthesized duplicate on any path that settles inside the grace.
  1026. expect(ends.map(end => end.outcome)).toEqual(['cancelled', 'cancelled'])
  1027. expect(new Set(ends.map(end => end.seq)).size).toBe(2)
  1028. expect(order.indexOf('run-end')).toBe(order.length - 1)
  1029. await handle.dispose()
  1030. })
  1031. })
  1032. describe('worker death', () => {
  1033. it('the first death signal closes admission to messages Node delivers before exit', async () => {
  1034. const { ctx, parent, provider } = await setup({ manual: true })
  1035. const phases: string[] = []
  1036. ctx.on('workflow/phase', (_info, title) => { phases.push(title) })
  1037. const handle = ctx.workflows.start({
  1038. ...scripted('await new Promise(() => {})'),
  1039. parent,
  1040. })
  1041. const worker = (handle as unknown as { worker: Worker }).worker
  1042. // Node may physically emit error -> queued message -> exit. Reproduce
  1043. // that ordering deterministically at the Worker event boundary: the
  1044. // late protocol data must not create work, narrate, or rewrite error.
  1045. worker.emit('error', new Error('synthetic error-before-message'))
  1046. worker.emit('message', { type: WorkerToHostType.Phase, title: 'late phase' })
  1047. worker.emit('message', {
  1048. type: WorkerToHostType.ChildStart,
  1049. callId: 999,
  1050. request: { prompt: 'late child' },
  1051. })
  1052. worker.emit('message', {
  1053. type: WorkerToHostType.Result,
  1054. result: { value: 'late', stopReason: 'completed', agentsStarted: 1 },
  1055. })
  1056. const result = await handle.result
  1057. expect(result.stopReason).toBe('error')
  1058. expect(result.error).toContain('synthetic error-before-message')
  1059. expect(provider.runs).toHaveLength(0)
  1060. expect(phases).toEqual([])
  1061. await handle.dispose()
  1062. await ctx.fiber.dispose()
  1063. })
  1064. it('refuses and disposes a provider run that becomes ready after its real worker dies', async () => {
  1065. const ctx = new Context()
  1066. await ctx.plugin(SubagentService)
  1067. const requested = Promise.withResolvers<SubagentStartRequest>()
  1068. const ready = Promise.withResolvers<SubagentRun>()
  1069. let disposeCalls = 0
  1070. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => ctx.logger)
  1071. const provider: SubagentProvider = {
  1072. name: 'late-ready',
  1073. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false },
  1074. inheritsParentContext: false,
  1075. start: (request) => {
  1076. requested.resolve(request)
  1077. // Model a backend whose independent startup boundary cannot be
  1078. // interrupted promptly. The host must still reject ownership if the
  1079. // worker dies before this promise transfers the ready run.
  1080. return ready.promise
  1081. },
  1082. }
  1083. ctx.subagents.registerProvider(provider)
  1084. await ctx.plugin(WorkerWorkflowEngine, { provider: 'late-ready', maxConcurrentAgents: 1 })
  1085. const lifecycle: string[] = []
  1086. ctx.on('workflow/agent-start', () => { lifecycle.push('start') })
  1087. ctx.on('workflow/agent-end', () => { lifecycle.push('end') })
  1088. const handle = ctx.workflows.start({
  1089. ...scripted("return await agent('pending startup')"),
  1090. parent: fakeParent(),
  1091. })
  1092. const request = await requested.promise
  1093. const worker = (handle as unknown as { worker: Worker }).worker
  1094. // Kill the actual Worker while provider startup is independently
  1095. // pending. Death closes admission and aborts the shared signal, but this
  1096. // deliberately uncooperative provider still fulfills afterward.
  1097. await worker.terminate()
  1098. const result = await handle.result
  1099. expect(result.stopReason).toBe('error')
  1100. expect(result.error).toContain('exit code')
  1101. expect(request.signal.aborted).toBe(true)
  1102. expect(request.signal.reason).toBe('workflow worker gone')
  1103. ready.resolve({
  1104. id: SessionId('late-ready-child'),
  1105. localAgent: undefined,
  1106. result: Promise.resolve({ output: [], stopReason: 'aborted' }),
  1107. dispose: () => {
  1108. disposeCalls += 1
  1109. return Promise.reject(new Error('late ready dispose failed'))
  1110. },
  1111. })
  1112. await waitFor(() => {
  1113. expect(disposeCalls).toBe(1)
  1114. expect(warn).toHaveBeenCalledWith(expect.stringContaining('refused child dispose failed: Error: late ready dispose failed'))
  1115. }, 1000)
  1116. expect(lifecycle).toEqual([])
  1117. await handle.dispose()
  1118. expect(disposeCalls).toBe(1)
  1119. await ctx.fiber.dispose()
  1120. })
  1121. it('a worker that exits before settling reports an error result and reaps its children', async () => {
  1122. const ctx = new Context()
  1123. await ctx.plugin(SubagentService)
  1124. // The child's dispose() REJECTS on top of the worker death: the reap
  1125. // must contain it (warn, not crash) while still emptying the registry.
  1126. const signalAborts: unknown[] = []
  1127. const provider: SubagentProvider = {
  1128. name: 'doomed',
  1129. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: false },
  1130. inheritsParentContext: false,
  1131. start: async (request) => {
  1132. request.signal.addEventListener('abort', () => {
  1133. signalAborts.push(request.signal.reason)
  1134. // The death claim precedes the shared-signal fanout. This
  1135. // synchronous callback cannot turn death into cancellation.
  1136. handle.cancel('reentered from worker-death signal cleanup')
  1137. }, { once: true })
  1138. return {
  1139. id: SessionId('doomed-child'),
  1140. localAgent: undefined,
  1141. result: new Promise(() => { /* never settles; the reap is the teardown */ }),
  1142. dispose: () => Promise.reject(new Error('dispose exploded during reap')),
  1143. }
  1144. },
  1145. }
  1146. ctx.subagents.registerProvider(provider)
  1147. await ctx.plugin(WorkerWorkflowEngine, { provider: 'doomed', maxConcurrentAgents: 2 })
  1148. const runEnds: WorkflowResultInfo[] = []
  1149. ctx.on('workflow/end', (_info, result) => { runEnds.push(result) })
  1150. const handle = ctx.workflows.start({
  1151. // The stray child's start RPC reaches the host, then the script kills
  1152. // its own worker through the documented vm escape — the host must
  1153. // settle `error` with the exit diagnostics and wind the child down.
  1154. ...scripted(`
  1155. agent('doomed')
  1156. const proc = ${ESCAPE}
  1157. const st = globalThis.constructor.constructor('return setTimeout')()
  1158. await new Promise(resolve => st(resolve, 200))
  1159. proc.exit(7)
  1160. `),
  1161. parent: fakeParent(),
  1162. })
  1163. const result = await handle.result
  1164. expect(result.stopReason).toBe('error')
  1165. expect(result.error).toContain('exit code 7')
  1166. expect(result.agentsStarted).toBe(1)
  1167. // A worker death is a stop reason like any other: workflow/end fires
  1168. // with the error outcome — for a bus observer it is the only obituary.
  1169. expect(runEnds).toEqual([{ stopReason: 'error', error: result.error, agentsStarted: 1 }])
  1170. // Result already settled — this is the reap's promptness, not a
  1171. // cold-start race; tight explicit bound (see the helper's doc comment).
  1172. await waitFor(() => {
  1173. expect(signalAborts).toEqual(['workflow worker gone'])
  1174. }, 1000)
  1175. await Promise.resolve()
  1176. expect(result.stopReason).toBe('error')
  1177. await handle.dispose()
  1178. }, 15_000)
  1179. it('an uncaught exception inside the worker surfaces as an error result and reaps the in-flight child', async () => {
  1180. const { ctx, parent, provider } = await setup({ manual: true })
  1181. const handle = ctx.workflows.start({
  1182. ...scripted(`
  1183. agent('in flight when the worker dies')
  1184. const proc = ${ESCAPE}
  1185. const st = globalThis.constructor.constructor('return setTimeout')()
  1186. await new Promise(resolve => st(resolve, 200))
  1187. proc.nextTick(() => { throw new Error('worker blew up') })
  1188. await new Promise(() => {})
  1189. `),
  1190. parent,
  1191. })
  1192. const result = await handle.result
  1193. expect(result.stopReason).toBe('error')
  1194. expect(result.error).toContain('worker blew up')
  1195. // The reap wound the stray child down (cancel + a CLEAN dispose).
  1196. // Result already settled — this is the reap's promptness, not a
  1197. // cold-start race; tight explicit bound (see the helper's doc comment).
  1198. await waitFor(() => {
  1199. expect(provider.runs.length).toBe(1)
  1200. expect(provider.runs[0]!.disposed).toBe(true)
  1201. }, 1000)
  1202. await handle.dispose()
  1203. }, 15_000)
  1204. it('a worker death pairs every stranded start: the synthesized cancelled agent-end precedes the error workflow/end', async () => {
  1205. const { ctx, parent, provider } = await setup({ manual: true })
  1206. const ends: { seq: number; outcome: string }[] = []
  1207. const order: string[] = []
  1208. ctx.on('workflow/agent-start', (_info, agent) => { order.push(`start:${agent.seq}`) })
  1209. ctx.on('workflow/agent-end', (_info, agent) => {
  1210. ends.push({ seq: agent.seq, outcome: agent.outcome })
  1211. order.push(`end:${agent.seq}`)
  1212. })
  1213. ctx.on('workflow/end', () => { order.push('run-end') })
  1214. const handle = ctx.workflows.start({
  1215. // Same choreography as the force-settle pairing test, but the worker
  1216. // DIES (the documented vm escape) instead of being terminated: the
  1217. // exit path must close slow's pair from the ledger too. The escaped
  1218. // setTimeout lets the already-posted messages flush before the kill.
  1219. ...scripted(`
  1220. const p = agent('slow')
  1221. await agent('fast')
  1222. const proc = ${ESCAPE}
  1223. const st = globalThis.constructor.constructor('return setTimeout')()
  1224. await new Promise(resolve => st(resolve, 150))
  1225. proc.exit(7)
  1226. `),
  1227. parent,
  1228. })
  1229. await waitFor(() => { expect(order.filter(entry => entry.startsWith('start:')).length).toBe(2) })
  1230. const fast = provider.runs.find(run => (run.request.prompt[0] as { text?: string }).text === 'fast')!
  1231. fast.settle(text('fast done'))
  1232. const result = await handle.result
  1233. expect(result.stopReason).toBe('error')
  1234. expect(result.error).toContain('exit code 7')
  1235. expect(ends).toEqual([
  1236. { seq: 2, outcome: 'completed' },
  1237. { seq: 1, outcome: 'cancelled' },
  1238. ])
  1239. expect(order.indexOf('run-end')).toBe(order.length - 1)
  1240. await handle.dispose()
  1241. }, 15_000)
  1242. it('a dispose ack racing the worker death is dropped, not crashed (post after exit)', async () => {
  1243. // Slow child disposal: the ack resolves only AFTER the worker died, so
  1244. // it has nowhere to go and must be dropped silently (the workerGone
  1245. // guard in post()).
  1246. const { ctx, parent, provider } = await setup({ disposeDelayMs: 300 })
  1247. const handle = ctx.workflows.start({
  1248. // The STRAY child settles instantly, so its wrapper starts the slow
  1249. // host-side disposal concurrently while the script goes on to kill
  1250. // its own worker — the ack then resolves into a dead thread.
  1251. ...scripted(`
  1252. agent('stray, never awaited')
  1253. const proc = ${ESCAPE}
  1254. const st = globalThis.constructor.constructor('return setTimeout')()
  1255. await new Promise(resolve => st(resolve, 150))
  1256. proc.exit(5)
  1257. `),
  1258. parent,
  1259. })
  1260. const result = await handle.result
  1261. expect(result.stopReason).toBe('error')
  1262. expect(result.error).toContain('exit code 5')
  1263. // Result already settled — this is the reap's promptness (bounded
  1264. // above the mock's fixed 300ms dispose delay, not a cold-start race);
  1265. // tight explicit bound (see the helper's doc comment).
  1266. await waitFor(() => { expect(provider.runs[0]!.disposed).toBe(true) }, 1000)
  1267. await handle.dispose()
  1268. }, 15_000)
  1269. it('a worker death AFTER a cancel reports cancelled, not error', async () => {
  1270. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: 60_000 } })
  1271. const handle = ctx.workflows.start({
  1272. ...scripted(`
  1273. const proc = ${ESCAPE}
  1274. const st = globalThis.constructor.constructor('return setTimeout')()
  1275. log('armed')
  1276. await new Promise(resolve => st(resolve, 400))
  1277. proc.exit(3)
  1278. `),
  1279. parent,
  1280. })
  1281. const logs: string[] = []
  1282. ctx.on('workflow/log', (_info, message) => { logs.push(message) })
  1283. await waitFor(() => { expect(logs).toContain('armed') })
  1284. handle.cancel('stop it')
  1285. // The grace is deliberately huge: only the worker's own death (exit 3,
  1286. // unreachable by the cancel — the script ignores hooks) settles this.
  1287. const result = await handle.result
  1288. expect(result.stopReason).toBe('cancelled')
  1289. expect(result.error).toContain('stop it')
  1290. await handle.dispose()
  1291. }, 15_000)
  1292. })
  1293. describe('service surface', () => {
  1294. it('run ids are unique and lifecycle meta is the run\'s borrowed immutable value', async () => {
  1295. const { ctx, parent } = await setup()
  1296. let eventMeta: WorkflowRunInfo | undefined
  1297. ctx.on('workflow/start', (info) => { eventMeta = info })
  1298. const first = ctx.workflows.start({ ...scripted('return 1'), parent })
  1299. const second = ctx.workflows.start({ ...scripted('return 2'), parent })
  1300. expect(first.id).not.toBe(second.id)
  1301. expect(eventMeta!.meta).toBe(second.meta)
  1302. expect(second.meta.name).toBe('test-flow')
  1303. await Promise.all([first.result, second.result])
  1304. await first.dispose()
  1305. await second.dispose()
  1306. })
  1307. it('unregisters ctx.workflows when the engine fiber is disposed (HMR safety)', async () => {
  1308. const ctx = new Context()
  1309. await ctx.plugin(SubagentService)
  1310. const fiber = await ctx.plugin(WorkerWorkflowEngine, {})
  1311. expect(ctx.get('workflows')).toBeDefined()
  1312. await fiber.dispose()
  1313. expect(ctx.get('workflows')).toBeUndefined()
  1314. })
  1315. it('keeps a holder-owned run usable when the engine unloads before its child starts', async () => {
  1316. const { ctx, parent, provider, engineFiber } = await setup({ reply: () => text('survived reload') })
  1317. let handle!: ReturnType<typeof ctx.workflows.start>
  1318. const holder = await ctx.plugin(Object.assign((inner: Context) => {
  1319. handle = inner.workflows.start({ ...scripted("return await agent('after reload')"), parent })
  1320. }, { inject: ['workflows'] }))
  1321. try {
  1322. // A real worker cannot deliver child-start in the synchronous start()
  1323. // slice. Unload the provider before that message arrives: the returned
  1324. // run belongs to `holder`, not to the engine fiber being reloaded.
  1325. expect(provider.runs).toHaveLength(0)
  1326. await engineFiber.dispose()
  1327. expect(ctx.get('workflows')).toBeUndefined()
  1328. await expect(handle.result).resolves.toEqual({
  1329. value: 'survived reload',
  1330. stopReason: 'completed',
  1331. agentsStarted: 1,
  1332. })
  1333. expect(provider.runs).toHaveLength(1)
  1334. } finally {
  1335. await handle.dispose()
  1336. await holder.dispose()
  1337. await ctx.fiber.dispose()
  1338. }
  1339. })
  1340. it('has the class-plugin export shape (default = the engine service class)', () => {
  1341. expect(workerEngineModule.default).toBe(WorkerWorkflowEngine)
  1342. expect('WorkerWorkflowEngine' in workerEngineModule).toBe(false)
  1343. const loader = Object.create(Loader.prototype) as Loader
  1344. const unwrapped: unknown = loader.unwrapExports(workerEngineModule)
  1345. expect(unwrapped).toBe(WorkerWorkflowEngine)
  1346. })
  1347. })
  1348. })