workflow-workerthread.spec.ts 64 KB

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