workflow-worker-thread.spec.ts 69 KB

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