workflow-workerthread.spec.ts 63 KB

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