workflow-worker-thread.spec.ts 69 KB

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