workflow-workerthread.spec.ts 58 KB

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