workflow-worker-thread.spec.ts 68 KB

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