workflow-worker-thread.spec.ts 68 KB

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