workflow-workerthread.spec.ts 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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, { 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. settle(result: SubagentResult): void
  46. cancelled: string | undefined
  47. disposed: boolean
  48. disposeCalls: number
  49. }
  50. /**
  51. * A scripted in-test provider over the REAL SubagentService registry: `auto`
  52. * settles each run via the reply function on a microtask; `manual` piles runs
  53. * up in `runs` for the test to settle. A run aborts (settles `aborted`) when
  54. * the request signal fires, like the real in-process backends.
  55. */
  56. class StubProvider implements SubagentProvider {
  57. readonly capabilities: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: true }
  58. readonly inheritsParentContext = false
  59. readonly runs: ControlledRun[] = []
  60. constructor(
  61. readonly name: string,
  62. private readonly reply?: (request: SubagentStartRequest, index: number) => SubagentResult,
  63. private readonly disposeDelayMs = 0,
  64. ) {}
  65. start(request: SubagentStartRequest): SubagentRun {
  66. let settle!: (result: SubagentResult) => void
  67. const result = new Promise<SubagentResult>((resolve) => { settle = resolve })
  68. const controlled: ControlledRun = { request, settle, cancelled: undefined, disposed: false, disposeCalls: 0 }
  69. this.runs.push(controlled)
  70. const index = this.runs.length - 1
  71. request.signal?.addEventListener('abort', () => { settle({ output: [], stopReason: 'aborted' }) }, { once: true })
  72. if (this.reply) {
  73. const reply = this.reply
  74. queueMicrotask(() => { settle(reply(request, index)) })
  75. }
  76. return {
  77. id: AgentId(`stub-child-${index}`),
  78. result,
  79. cancel: (reason?: string) => {
  80. controlled.cancelled = reason ?? 'cancelled'
  81. settle({ output: [], stopReason: 'aborted' })
  82. },
  83. dispose: () => {
  84. controlled.disposeCalls += 1
  85. if (this.disposeDelayMs === 0) {
  86. controlled.disposed = true
  87. return Promise.resolve()
  88. }
  89. return new Promise<void>((resolve) => {
  90. setTimeout(() => {
  91. controlled.disposed = true
  92. resolve()
  93. }, this.disposeDelayMs)
  94. })
  95. },
  96. }
  97. }
  98. }
  99. /** Text-reply helper for auto providers. */
  100. function text(reply: string): SubagentResult {
  101. return { output: [{ type: 'text', text: reply }], stopReason: 'completed' }
  102. }
  103. interface SetupOptions {
  104. config?: Config
  105. reply?: (request: SubagentStartRequest, index: number) => SubagentResult
  106. manual?: boolean
  107. disposeDelayMs?: number
  108. }
  109. async function setup(options?: SetupOptions) {
  110. const ctx = new Context()
  111. await ctx.plugin(SubagentService)
  112. const provider = new StubProvider(
  113. 'stub',
  114. options?.manual ? undefined : options?.reply ?? (() => text('stub reply')),
  115. options?.disposeDelayMs ?? 0,
  116. )
  117. ctx.subagents.registerProvider(provider)
  118. // A fixed concurrency ceiling: the auto-resolved default is machine-derived
  119. // (cores - 2, floored at 1), so tests that expect N children in flight
  120. // would wedge on small CI runners.
  121. await ctx.plugin(WorkerWorkflowEngine, { provider: 'stub', maxConcurrentAgents: 8, ...options?.config })
  122. return { ctx, provider, parent: fakeParent() }
  123. }
  124. /** The standard test meta plus a body, spread into a start request. */
  125. function scripted(body: string, metaExtra?: Partial<WorkflowMeta>): { script: string; meta: WorkflowMeta } {
  126. return { script: body, meta: { name: 'test-flow', description: 'a test workflow', ...metaExtra } }
  127. }
  128. /** Start + await one run, disposing on the way out. */
  129. async function run(ctx: Context, parent: Agent, source: { script: string; meta: WorkflowMeta }, args?: unknown): Promise<WorkflowResult> {
  130. const handle = ctx.workflows.start({ ...source, parent, ...args !== undefined ? { args } : {} })
  131. try {
  132. return await handle.result
  133. } finally {
  134. await handle.dispose()
  135. }
  136. }
  137. describe('dsh-workflow-workerthread', () => {
  138. describe('script execution over a real worker thread', () => {
  139. it('runs a script end-to-end: agent() text results, phases, log, args, return value, events', async () => {
  140. const { ctx, parent, provider } = await setup({ reply: (_request, index) => text(`answer-${index}`) })
  141. const events: [string, unknown[]][] = []
  142. for (const name of ['workflow/start', 'workflow/phase', 'workflow/log', 'workflow/agent-start', 'workflow/agent-end', 'workflow/end'] as const) {
  143. ctx.on(name, (...payload: unknown[]) => { events.push([name, payload]) })
  144. }
  145. const result = await run(ctx, parent, scripted(`
  146. phase('Scan')
  147. log('starting with ' + args.files.length + ' files')
  148. const answers = await pipeline(args.files, (prev, item) => agent('read ' + item))
  149. phase('Report')
  150. return { answers, count: args.files.length }
  151. `, { phases: [{ title: 'Scan' }, { title: 'Report' }] }), { files: ['a.ts', 'b.ts'] })
  152. expect(result.stopReason).toBe('completed')
  153. expect(result.agentsStarted).toBe(2)
  154. expect(result.value).toEqual({ answers: ['answer-0', 'answer-1'], count: 2 })
  155. expect(provider.runs.every(r => r.disposed)).toBe(true)
  156. const names = events.map(([name]) => name)
  157. expect(names[0]).toBe('workflow/start')
  158. expect(names).toContain('workflow/phase')
  159. expect(names).toContain('workflow/log')
  160. expect(names.at(-1)).toBe('workflow/end')
  161. const info = events[0]![1][0] as WorkflowRunInfo
  162. expect(info.meta.name).toBe('test-flow')
  163. const end = events.at(-1)![1][1] as Record<string, unknown>
  164. expect(end).toEqual({ stopReason: 'completed', agentsStarted: 2 })
  165. expect('value' in end).toBe(false)
  166. })
  167. it('agent({schema, model}) forwards outputSchema and agentOptions to the provider across the thread', async () => {
  168. const { ctx, parent, provider } = await setup({
  169. reply: () => ({ output: [], structured: { files: ['x.ts', 'y.ts'] }, stopReason: 'completed' }),
  170. })
  171. const result = await run(ctx, parent, scripted(`
  172. const found = await agent('list files', { model: 'deepseek-v4-pro', schema: { type: 'object', properties: { files: { type: 'array', items: { type: 'string' } } }, required: ['files'] } })
  173. return { first: found.files[0], count: found.files.length }
  174. `))
  175. expect(result.value).toEqual({ first: 'x.ts', count: 2 })
  176. expect(provider.runs[0]!.request.outputSchema).toEqual({
  177. type: 'object',
  178. properties: { files: { type: 'array', items: { type: 'string' } } },
  179. required: ['files'],
  180. })
  181. expect(provider.runs[0]!.request.agentOptions).toEqual({ model: 'deepseek-v4-pro' })
  182. expect(provider.runs[0]!.request.parent).toBeDefined()
  183. })
  184. it('a fatal hook error inside the worker kills the script and reports the error', async () => {
  185. const { ctx, parent } = await setup()
  186. const result = await run(ctx, parent, scripted("return await parallel([() => agent('x', { isolation: 'worktree' })])"))
  187. expect(result.stopReason).toBe('error')
  188. expect(result.error).toContain('"isolation" is deferred')
  189. })
  190. it('a provider start failure crosses back as a fatal AGENT_START error', async () => {
  191. const { ctx, parent } = await setup({ config: { provider: 'nonexistent' } })
  192. const result = await run(ctx, parent, scripted("return await pipeline([1], () => agent('p'))"))
  193. expect(result.stopReason).toBe('error')
  194. expect(result.error).toContain('agent() could not start a child')
  195. })
  196. it('a child result REJECTION crosses back as a fatal AGENT_RESULT error (a broken provider is not a failed child)', async () => {
  197. const ctx = new Context()
  198. await ctx.plugin(SubagentService)
  199. const provider: SubagentProvider = {
  200. name: 'rejecting',
  201. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true },
  202. inheritsParentContext: false,
  203. start: () => ({
  204. id: AgentId('reject-child'),
  205. result: Promise.reject(new Error('backend exploded')),
  206. cancel: () => { /* nothing in flight */ },
  207. dispose: () => Promise.resolve(),
  208. }),
  209. }
  210. ctx.subagents.registerProvider(provider)
  211. await ctx.plugin(WorkerWorkflowEngine, { provider: 'rejecting', maxConcurrentAgents: 2 })
  212. const result = await run(ctx, fakeParent(), scripted(`
  213. try { await agent('p'); return 'unreachable' } catch (e) { return { name: e.name, code: e.code, fatal: e.fatal, message: e.message } }
  214. `))
  215. expect(result.value).toMatchObject({ name: 'WorkflowError', code: 'AGENT_RESULT', fatal: true })
  216. expect((result.value as { message: string }).message).toContain('backend exploded')
  217. })
  218. it('a child whose dispose() rejects cannot wedge the script (the host acks anyway)', async () => {
  219. const ctx = new Context()
  220. await ctx.plugin(SubagentService)
  221. const provider: SubagentProvider = {
  222. name: 'bad-dispose',
  223. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true },
  224. inheritsParentContext: false,
  225. start: () => ({
  226. id: AgentId('bad-dispose-child'),
  227. result: Promise.resolve({ output: [{ type: 'text', text: 'fine' }], stopReason: 'completed' }),
  228. cancel: () => { /* settled already */ },
  229. dispose: () => Promise.reject(new Error('dispose exploded')),
  230. }),
  231. }
  232. ctx.subagents.registerProvider(provider)
  233. await ctx.plugin(WorkerWorkflowEngine, { provider: 'bad-dispose', maxConcurrentAgents: 2 })
  234. const result = await run(ctx, fakeParent(), scripted("return await agent('p')"))
  235. expect(result.stopReason).toBe('completed')
  236. expect(result.value).toBe('fine')
  237. })
  238. it('a child dispose() rejecting an UNRENDERABLE value still acks — the containment warn is total', async () => {
  239. const ctx = new Context()
  240. await ctx.plugin(SubagentService)
  241. const provider: SubagentProvider = {
  242. name: 'coercion-trap-dispose',
  243. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true },
  244. inheritsParentContext: false,
  245. start: () => ({
  246. id: AgentId('trap-child'),
  247. result: Promise.resolve({ output: [{ type: 'text', text: 'fine' }], stopReason: 'completed' }),
  248. cancel: () => { /* settled already */ },
  249. // The rejection VALUE's own coercion throws: a warn built with bare
  250. // String(error) would itself throw, skipping the ChildDisposed ack
  251. // and wedging the script's finally until the grace/terminate path.
  252. // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- the non-Error rejection IS the scenario under test
  253. dispose: () => Promise.reject({ toString: () => { throw new Error('coercion trap') } }),
  254. }),
  255. }
  256. ctx.subagents.registerProvider(provider)
  257. await ctx.plugin(WorkerWorkflowEngine, { provider: 'coercion-trap-dispose', maxConcurrentAgents: 2 })
  258. const result = await run(ctx, fakeParent(), scripted("return await agent('p')"))
  259. expect(result.stopReason).toBe('completed')
  260. expect(result.value).toBe('fine')
  261. })
  262. it('the worker spawns with an EMPTY environment: an escaped script finds no ambient credentials', async () => {
  263. const { ctx, parent } = await setup()
  264. // A canary in the HARNESS process's env: with an inherited environment
  265. // the escape below would read it back (exactly how DEEPSEEK_API_KEY
  266. // would leak); env: {} in the spawn options is what keeps it out.
  267. process.env.WORKFLOW_ENV_CANARY = 'leak me'
  268. try {
  269. const result = await run(ctx, parent, scripted(`
  270. const proc = ${ESCAPE}
  271. return { canary: proc.env.WORKFLOW_ENV_CANARY ?? null, keys: Object.keys(proc.env).length }
  272. `))
  273. expect(result.stopReason).toBe('completed')
  274. expect(result.value).toEqual({ canary: null, keys: 0 })
  275. } finally {
  276. delete process.env.WORKFLOW_ENV_CANARY
  277. }
  278. })
  279. it('the unbuilt worker forwards exactly TSX_TSCONFIG_PATH through the scrub: the paths-map pin survives, secrets do not', async () => {
  280. const { ctx, parent } = await setup()
  281. // The ACP snapshot harness runs the parent with its cwd OUTSIDE the
  282. // repo and pins the repo tsconfig through this variable; the worker
  283. // must inherit the pin (or its dsh-* imports silently resolve to
  284. // unbuilt lib/ bundles) while every other variable stays scrubbed.
  285. const tsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url))
  286. process.env.TSX_TSCONFIG_PATH = tsconfig
  287. process.env.WORKFLOW_ENV_CANARY = 'leak me'
  288. try {
  289. const result = await run(ctx, parent, scripted(`
  290. const proc = ${ESCAPE}
  291. return { keys: Object.keys(proc.env), tsconfig: proc.env.TSX_TSCONFIG_PATH }
  292. `))
  293. expect(result.stopReason).toBe('completed')
  294. expect(result.value).toEqual({ keys: ['TSX_TSCONFIG_PATH'], tsconfig })
  295. } finally {
  296. delete process.env.TSX_TSCONFIG_PATH
  297. delete process.env.WORKFLOW_ENV_CANARY
  298. }
  299. })
  300. })
  301. describe('lifecycle: parse errors, cancellation, termination, disposal', () => {
  302. it('start() throws synchronously for invalid meta data or an unparseable body (host-side pre-checks)', async () => {
  303. const { ctx, parent } = await setup()
  304. // Meta is DATA — shape violations reject loud, every one named.
  305. expect(() => ctx.workflows.start({ script: 'return 1', meta: { name: '', description: 'd' }, parent })).toThrow(/meta\.name must be a non-empty string/)
  306. 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/)
  307. expect(() => ctx.workflows.start({ ...scripted('return ((('), parent })).toThrow(/does not parse/)
  308. // The likeliest authoring slip — a Claude Code-style meta header in the
  309. // body — gets a pointed message, not a bare SyntaxError.
  310. expect(() => ctx.workflows.start({ ...scripted("export const meta = { name: 'x', description: 'd' }\nreturn 1"), parent })).toThrow(/meta rides the `meta` request field/)
  311. })
  312. it('cancel() aborts in-flight children (signal AND cancel RPC) and settles the run cancelled', async () => {
  313. const { ctx, parent, provider } = await setup({ manual: true })
  314. const ends: unknown[] = []
  315. ctx.on('workflow/agent-end', (_info, agent) => { ends.push(agent) })
  316. const runEnds: WorkflowResultInfo[] = []
  317. ctx.on('workflow/end', (_info, result) => { runEnds.push(result) })
  318. const handle = ctx.workflows.start({ ...scripted("return await agent('long job')"), parent })
  319. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  320. handle.cancel('user stopped it')
  321. const result = await handle.result
  322. expect(result.stopReason).toBe('cancelled')
  323. expect(result.error).toContain('user stopped it')
  324. await handle.dispose()
  325. expect(provider.runs[0]!.disposed).toBe(true)
  326. expect(ends).toEqual([expect.objectContaining({ seq: 1, outcome: 'cancelled' })])
  327. // workflow/end is an observer's only death signal: it fires for a
  328. // cancelled run too, mirroring the settled outcome data.
  329. expect(runEnds).toEqual([{ stopReason: 'cancelled', error: result.error, agentsStarted: result.agentsStarted }])
  330. })
  331. it('an already-aborted request signal cancels before the body ever runs (the go handshake holds it)', async () => {
  332. const { ctx, parent, provider } = await setup()
  333. const controller = new AbortController()
  334. controller.abort()
  335. const logs: string[] = []
  336. ctx.on('workflow/log', (_info, message) => { logs.push(message) })
  337. const handle = ctx.workflows.start({ ...scripted("log('ran')\nreturn 123"), parent, signal: controller.signal })
  338. const result = await handle.result
  339. expect(result.stopReason).toBe('cancelled')
  340. expect(result.value).toBeNull()
  341. expect(logs).toEqual([])
  342. expect(provider.runs.length).toBe(0)
  343. await handle.dispose()
  344. })
  345. it('cancel() right after start() cancels before the body runs; the signal aborting mid-run cancels like cancel()', async () => {
  346. const { ctx, parent, provider } = await setup({ manual: true })
  347. const first = ctx.workflows.start({ ...scripted("return await agent('never')"), parent })
  348. // No-reason cancel: the canonical default reason must ride the result.
  349. first.cancel()
  350. const firstResult = await first.result
  351. expect(firstResult.stopReason).toBe('cancelled')
  352. expect(firstResult.error).toContain('workflow cancelled')
  353. expect(provider.runs.length).toBe(0)
  354. await first.dispose()
  355. const controller = new AbortController()
  356. const second = ctx.workflows.start({ ...scripted("return await agent('job')"), parent, signal: controller.signal })
  357. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  358. controller.abort()
  359. expect((await second.result).stopReason).toBe('cancelled')
  360. await second.dispose()
  361. })
  362. it('a child-start racing the host cancel is refused: no child starts after cancellation', async () => {
  363. const { ctx, parent, provider } = await setup({ manual: true })
  364. // Cancel from INSIDE the log listener: the worker has already posted
  365. // its child-start (queued right behind the log message), so the host
  366. // processes it with cancelReason set — the refusal arm no real-world
  367. // timing can hit reliably. (The closure runs only after `handle` below
  368. // is initialized — the listener fires on the worker's first message.)
  369. ctx.on('workflow/log', () => { handle.cancel('cancelled from the log listener') })
  370. const handle = ctx.workflows.start({ ...scripted("log('mark')\nreturn await agent('late')"), parent })
  371. const result = await handle.result
  372. expect(result.stopReason).toBe('cancelled')
  373. expect(provider.runs.length).toBe(0)
  374. await handle.dispose()
  375. })
  376. it('post-cancel narration is suppressed host-side, and completion racing a cancel reports cancelled', async () => {
  377. const { ctx, parent } = await setup()
  378. const narration: string[] = []
  379. ctx.on('workflow/log', (_info, message) => { narration.push(message) })
  380. ctx.on('workflow/phase', (_info, title) => { narration.push(`phase:${title}`) })
  381. const handle = ctx.workflows.start({
  382. // The sync spin keeps the worker's loop busy so the cancel message
  383. // cannot be processed before the script settles `completed` — the
  384. // worker posts a completed result that must LOSE to the in-flight
  385. // host cancellation. The trailing narration exercises host-side
  386. // suppression: posted pre-cancel-processing worker-side, arriving
  387. // post-cancel host-side.
  388. ...scripted(`
  389. log('started')
  390. const end = Date.now() + 1000
  391. while (Date.now() < end) {}
  392. phase('late phase')
  393. log('late log')
  394. return 'done'
  395. `),
  396. parent,
  397. })
  398. await waitFor(() => { expect(narration).toContain('started') })
  399. handle.cancel('raced the completion')
  400. const result = await handle.result
  401. expect(result.stopReason).toBe('cancelled')
  402. expect(result.error).toContain('raced the completion')
  403. expect(narration).toEqual(['started'])
  404. await handle.dispose()
  405. }, 15_000)
  406. it('cancel() force-settles a script parked on a promise no hook owns, and TERMINATES its worker', async () => {
  407. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: 50 } })
  408. const runEnds: WorkflowResultInfo[] = []
  409. ctx.on('workflow/end', (_info, result) => { runEnds.push(result) })
  410. const handle = ctx.workflows.start({
  411. ...scripted("await new Promise(() => {})\nreturn 'unreachable'"),
  412. parent,
  413. })
  414. handle.cancel('user aborted')
  415. const result = await handle.result
  416. expect(result.stopReason).toBe('cancelled')
  417. expect(result.error).toContain('user aborted')
  418. // The grace force-settle fires workflow/end exactly like an ordinary
  419. // settlement — a terminated script's death still reaches observers.
  420. expect(runEnds).toEqual([{ stopReason: 'cancelled', error: result.error, agentsStarted: 0 }])
  421. await handle.dispose()
  422. })
  423. it('dispose() on a stuck script returns within the grace instead of hanging (result settles cancelled)', async () => {
  424. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: 50 } })
  425. const handle = ctx.workflows.start({
  426. ...scripted("await new Promise(() => {})\nreturn 'unreachable'"),
  427. parent,
  428. })
  429. const before = Date.now()
  430. await handle.dispose()
  431. expect(Date.now() - before).toBeLessThan(2000)
  432. const result = await handle.result
  433. expect(result.stopReason).toBe('cancelled')
  434. })
  435. it('dispose() is idempotent and settles cleanly after a completed run', async () => {
  436. const { ctx, parent } = await setup()
  437. const handle = ctx.workflows.start({ ...scripted('return 1'), parent })
  438. await handle.result
  439. await handle.dispose()
  440. await handle.dispose()
  441. })
  442. it('a settled run arms NO grace timer: disposing a completed run must not pin it for disposeGraceMs', async () => {
  443. // A distinctive grace so the spy can tell the cancel-path grace timer
  444. // apart from every other timeout in flight.
  445. const GRACE = 44_444
  446. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: GRACE } })
  447. const handle = ctx.workflows.start({ ...scripted('return 1'), parent })
  448. await handle.result
  449. const spy = vi.spyOn(globalThis, 'setTimeout')
  450. try {
  451. await handle.dispose()
  452. // dispose()'s own bounded-wait sleep is the ONLY grace-sized timer
  453. // allowed here; before the settled guard, cancel() armed a second one
  454. // that nothing would ever clear (the run was already settled), keeping
  455. // the WorkerRun/Worker closure alive until the grace expired.
  456. const graceTimers = spy.mock.calls.filter(call => call[1] === GRACE)
  457. expect(graceTimers.length).toBe(1)
  458. } finally {
  459. spy.mockRestore()
  460. }
  461. })
  462. it('strays: children fired without await are aborted once the script settles, and dispose() waits for their disposal', async () => {
  463. const { ctx, parent, provider } = await setup({ manual: true, disposeDelayMs: 40 })
  464. const handle = ctx.workflows.start({
  465. ...scripted(`
  466. agent('stray')
  467. return 'done without awaiting'
  468. `),
  469. parent,
  470. })
  471. const result = await handle.result
  472. expect(result.stopReason).toBe('completed')
  473. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  474. await handle.dispose()
  475. // Not a waitFor: by the time dispose() returns, the slow child disposal
  476. // must already be complete (host-side registry quiescence).
  477. expect(provider.runs[0]!.disposed).toBe(true)
  478. })
  479. it('the settle-reap fires the request signal too: a provider honoring ONLY the signal winds its stray down promptly', async () => {
  480. const ctx = new Context()
  481. await ctx.plugin(SubagentService)
  482. const aborted: string[] = []
  483. const provider: SubagentProvider = {
  484. name: 'signal-only',
  485. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true },
  486. inheritsParentContext: false,
  487. start: (request) => {
  488. let settle!: (result: SubagentResult) => void
  489. const result = new Promise<SubagentResult>((resolve) => { settle = resolve })
  490. request.signal?.addEventListener('abort', () => {
  491. aborted.push(String(request.signal?.reason))
  492. settle({ output: [], stopReason: 'aborted' })
  493. }, { once: true })
  494. return {
  495. id: AgentId('signal-only-child'),
  496. result,
  497. // The seam leaves a provider free to honor EITHER cancel channel;
  498. // this one deliberately ignores run.cancel() — only the request
  499. // signal can wind it down.
  500. cancel: () => { /* signal-only by design */ },
  501. dispose: () => Promise.resolve(),
  502. }
  503. },
  504. }
  505. ctx.subagents.registerProvider(provider)
  506. await ctx.plugin(WorkerWorkflowEngine, { provider: 'signal-only', maxConcurrentAgents: 2 })
  507. const handle = ctx.workflows.start({
  508. ...scripted(`
  509. agent('stray, never awaited')
  510. return 'done'
  511. `),
  512. parent: fakeParent(),
  513. })
  514. const result = await handle.result
  515. expect(result.stopReason).toBe('completed')
  516. // BEFORE dispose(): the settlement itself must have aborted the signal —
  517. // without it this child would stay live until dispose's terminate. This
  518. // is a HOST-PROMPTNESS claim, not a cold-start race — a tight explicit
  519. // bound (unlike the file default) so a multi-second reap regression
  520. // cannot pass by outlasting the wait.
  521. await waitFor(() => { expect(aborted).toEqual(['workflow settled']) }, 1000)
  522. await handle.dispose()
  523. })
  524. it("cancel() drives each child's explicit cancel() host-side: a wedged worker cannot delay it", async () => {
  525. const ctx = new Context()
  526. await ctx.plugin(SubagentService)
  527. let starts = 0
  528. const cancelled: string[] = []
  529. const provider: SubagentProvider = {
  530. name: 'cancel-only',
  531. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true },
  532. inheritsParentContext: false,
  533. start: () => {
  534. starts += 1
  535. return {
  536. id: AgentId('cancel-only-child'),
  537. result: new Promise(() => { /* only cancel() ends this child */ }),
  538. // Deliberately ignores the request signal — the seam leaves a
  539. // provider free to honor ONLY the explicit cancel() channel.
  540. cancel: (reason?: string) => { cancelled.push(reason ?? 'cancelled') },
  541. dispose: () => Promise.resolve(),
  542. }
  543. },
  544. }
  545. ctx.subagents.registerProvider(provider)
  546. // A deliberately huge grace: if only the grace/terminate reap could
  547. // reach this child, the assertion below would time out first.
  548. await ctx.plugin(WorkerWorkflowEngine, { provider: 'cancel-only', maxConcurrentAgents: 2, disposeGraceMs: 30_000 })
  549. const handle = ctx.workflows.start({
  550. // The stray child's start RPC reaches the host, then the script wedges
  551. // its own worker in a synchronous spin: the worker cannot process the
  552. // Cancel message, so it can relay NO ChildCancel RPC — only the host's
  553. // own children loop can deliver the explicit cancel in time. The
  554. // microtask yields let the agent() continuation POST its child-start
  555. // before the spin seizes the worker's loop (the posted message needs
  556. // no further worker-loop turns to reach the host).
  557. ...scripted(`
  558. agent('wedged child')
  559. for (let i = 0; i < 20; i++) await null
  560. const end = Date.now() + 1500
  561. while (Date.now() < end) {}
  562. return 'raced'
  563. `),
  564. parent: fakeParent(),
  565. })
  566. await waitFor(() => { expect(starts).toBe(1) })
  567. handle.cancel('stop now')
  568. await waitFor(() => { expect(cancelled).toEqual(['stop now']) }, 800)
  569. // The wedged worker's own completion loses to the in-flight cancel.
  570. const result = await handle.result
  571. expect(result.stopReason).toBe('cancelled')
  572. await handle.dispose()
  573. }, 15_000)
  574. 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 () => {
  575. const { ctx, parent, provider } = await setup({
  576. manual: true,
  577. disposeDelayMs: 40,
  578. config: { provider: 'stub', maxConcurrentAgents: 8, disposeGraceMs: 400 },
  579. })
  580. const handle = ctx.workflows.start({
  581. // Same shape as the wedged-cancel test above: the child's start RPC
  582. // reaches the host, then the script seizes its worker's loop, so the
  583. // worker can relay NO dispose RPC — the host's own dispose() drive is
  584. // the only thing that can start (and finish) this child's disposal
  585. // before the grace runs out.
  586. ...scripted(`
  587. agent('wedged child')
  588. for (let i = 0; i < 20; i++) await null
  589. const end = Date.now() + 1500
  590. while (Date.now() < end) {}
  591. return 'raced'
  592. `),
  593. parent,
  594. })
  595. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  596. const before = Date.now()
  597. await handle.dispose()
  598. // Bounded by the grace (plus the terminate), never by the 1.5s spin.
  599. expect(Date.now() - before).toBeLessThan(1200)
  600. // Not a waitFor: dispose() resolving IS the quiescence claim — the slow
  601. // child disposal must be complete, not merely started (before the
  602. // host-driven drive, disposal only STARTED at the post-terminate reap,
  603. // so dispose() returned with it still in flight).
  604. expect(provider.runs[0]!.disposed).toBe(true)
  605. const result = await handle.result
  606. expect(result.stopReason).toBe('cancelled')
  607. }, 15_000)
  608. 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 () => {
  609. const { ctx, parent, provider } = await setup({ manual: true })
  610. const handle = ctx.workflows.start({
  611. ...scripted(`
  612. await agent('long child')
  613. return 'unreachable'
  614. `),
  615. parent,
  616. })
  617. await waitFor(() => { expect(provider.runs.length).toBe(1) })
  618. const handleDispose = handle.dispose()
  619. const result = await handle.result
  620. // The script itself settled (the wrapper's own dispose RPC found the
  621. // child already reaped host-side and was acked) — a missing ack would
  622. // wedge the wrapper's finally until the 5s default grace force-settle.
  623. expect(result.stopReason).toBe('cancelled')
  624. expect(result.error).toContain('workflow disposed')
  625. await handleDispose
  626. expect(provider.runs[0]!.disposed).toBe(true)
  627. // The memo: the host drive and the worker's RPC share one disposal.
  628. expect(provider.runs[0]!.disposeCalls).toBe(1)
  629. })
  630. it('the grace force-settle pairs every stranded start: a host-synthesized cancelled agent-end lands before workflow/end', async () => {
  631. const { ctx, parent, provider } = await setup({ manual: true, config: { provider: 'stub', maxConcurrentAgents: 8, disposeGraceMs: 300 } })
  632. const ends: { seq: number; outcome: string }[] = []
  633. const order: string[] = []
  634. ctx.on('workflow/agent-start', (_info, agent) => { order.push(`start:${agent.seq}`) })
  635. ctx.on('workflow/agent-end', (_info, agent) => {
  636. ends.push({ seq: agent.seq, outcome: agent.outcome })
  637. order.push(`end:${agent.seq}`)
  638. })
  639. ctx.on('workflow/end', () => { order.push('run-end') })
  640. const handle = ctx.workflows.start({
  641. // 'slow' starts and its agent-start crosses to observers (the awaited
  642. // 'fast' call keeps the worker loop turning), then the script seizes
  643. // the loop: the wedged worker can never author slow's agent-end —
  644. // only the host's ledger can close the pair.
  645. ...scripted(`
  646. const p = agent('slow')
  647. await agent('fast')
  648. const end = Date.now() + 1500
  649. while (Date.now() < end) {}
  650. return 'raced'
  651. `),
  652. parent,
  653. })
  654. await waitFor(() => { expect(order.filter(entry => entry.startsWith('start:')).length).toBe(2) })
  655. const fast = provider.runs.find(run => (run.request.prompt[0] as { text?: string }).text === 'fast')!
  656. fast.settle(text('fast done'))
  657. handle.cancel('stop now')
  658. const result = await handle.result
  659. expect(result.stopReason).toBe('cancelled')
  660. // fast's end is the worker's own report; slow's is host-synthesized at
  661. // the force-settle — exactly one end per started seq, no third event.
  662. expect(ends).toEqual([
  663. { seq: 2, outcome: 'completed' },
  664. { seq: 1, outcome: 'cancelled' },
  665. ])
  666. // Both ends reached observers BEFORE workflow/end: a progress consumer
  667. // can finalize its state at run-end without dangling agents.
  668. expect(order.indexOf('run-end')).toBe(order.length - 1)
  669. await handle.dispose()
  670. }, 15_000)
  671. it('graceful cancellation keeps pairing worker-authored: exactly one agent-end per start, nothing synthesized on top', async () => {
  672. const { ctx, parent, provider } = await setup({ manual: true })
  673. const ends: { seq: number; outcome: string }[] = []
  674. const order: string[] = []
  675. ctx.on('workflow/agent-end', (_info, agent) => {
  676. ends.push({ seq: agent.seq, outcome: agent.outcome })
  677. order.push(`end:${agent.seq}`)
  678. })
  679. ctx.on('workflow/end', () => { order.push('run-end') })
  680. const handle = ctx.workflows.start({
  681. ...scripted("await parallel([() => agent('a'), () => agent('b')])\nreturn 'unreachable'"),
  682. parent,
  683. })
  684. await waitFor(() => { expect(provider.runs.length).toBe(2) })
  685. handle.cancel('user stop')
  686. const result = await handle.result
  687. expect(result.stopReason).toBe('cancelled')
  688. // The live worker reported both pairs itself; the ledger must not add
  689. // a synthesized duplicate on any path that settles inside the grace.
  690. expect(ends.map(end => end.outcome)).toEqual(['cancelled', 'cancelled'])
  691. expect(new Set(ends.map(end => end.seq)).size).toBe(2)
  692. expect(order.indexOf('run-end')).toBe(order.length - 1)
  693. await handle.dispose()
  694. })
  695. })
  696. describe('worker death', () => {
  697. it('a worker that exits before settling reports an error result and reaps its children', async () => {
  698. const ctx = new Context()
  699. await ctx.plugin(SubagentService)
  700. // The child's dispose() REJECTS on top of the worker death: the reap
  701. // must contain it (warn, not crash) while still emptying the registry.
  702. const cancelled: string[] = []
  703. const provider: SubagentProvider = {
  704. name: 'doomed',
  705. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true },
  706. inheritsParentContext: false,
  707. start: () => ({
  708. id: AgentId('doomed-child'),
  709. result: new Promise(() => { /* never settles; the reap is the teardown */ }),
  710. cancel: (reason?: string) => { cancelled.push(reason ?? 'cancelled') },
  711. dispose: () => Promise.reject(new Error('dispose exploded during reap')),
  712. }),
  713. }
  714. ctx.subagents.registerProvider(provider)
  715. await ctx.plugin(WorkerWorkflowEngine, { provider: 'doomed', maxConcurrentAgents: 2 })
  716. const runEnds: WorkflowResultInfo[] = []
  717. ctx.on('workflow/end', (_info, result) => { runEnds.push(result) })
  718. const handle = ctx.workflows.start({
  719. // The stray child's start RPC reaches the host, then the script kills
  720. // its own worker through the documented vm escape — the host must
  721. // settle `error` with the exit diagnostics and wind the child down.
  722. ...scripted(`
  723. agent('doomed')
  724. const proc = ${ESCAPE}
  725. const st = globalThis.constructor.constructor('return setTimeout')()
  726. await new Promise(resolve => st(resolve, 200))
  727. proc.exit(7)
  728. `),
  729. parent: fakeParent(),
  730. })
  731. const result = await handle.result
  732. expect(result.stopReason).toBe('error')
  733. expect(result.error).toContain('exit code 7')
  734. expect(result.agentsStarted).toBe(1)
  735. // A worker death is a stop reason like any other: workflow/end fires
  736. // with the error outcome — for a bus observer it is the only obituary.
  737. expect(runEnds).toEqual([{ stopReason: 'error', error: result.error, agentsStarted: 1 }])
  738. // Result already settled — this is the reap's promptness, not a
  739. // cold-start race; tight explicit bound (see the helper's doc comment).
  740. await waitFor(() => { expect(cancelled.length).toBe(1) }, 1000)
  741. await handle.dispose()
  742. }, 15_000)
  743. it('an uncaught exception inside the worker surfaces as an error result and reaps the in-flight child', async () => {
  744. const { ctx, parent, provider } = await setup({ manual: true })
  745. const handle = ctx.workflows.start({
  746. ...scripted(`
  747. agent('in flight when the worker dies')
  748. const proc = ${ESCAPE}
  749. const st = globalThis.constructor.constructor('return setTimeout')()
  750. await new Promise(resolve => st(resolve, 200))
  751. proc.nextTick(() => { throw new Error('worker blew up') })
  752. await new Promise(() => {})
  753. `),
  754. parent,
  755. })
  756. const result = await handle.result
  757. expect(result.stopReason).toBe('error')
  758. expect(result.error).toContain('worker blew up')
  759. // The reap wound the stray child down (cancel + a CLEAN dispose).
  760. // Result already settled — this is the reap's promptness, not a
  761. // cold-start race; tight explicit bound (see the helper's doc comment).
  762. await waitFor(() => {
  763. expect(provider.runs.length).toBe(1)
  764. expect(provider.runs[0]!.disposed).toBe(true)
  765. }, 1000)
  766. await handle.dispose()
  767. }, 15_000)
  768. it('a worker death pairs every stranded start: the synthesized cancelled agent-end precedes the error workflow/end', async () => {
  769. const { ctx, parent, provider } = await setup({ manual: true })
  770. const ends: { seq: number; outcome: string }[] = []
  771. const order: string[] = []
  772. ctx.on('workflow/agent-start', (_info, agent) => { order.push(`start:${agent.seq}`) })
  773. ctx.on('workflow/agent-end', (_info, agent) => {
  774. ends.push({ seq: agent.seq, outcome: agent.outcome })
  775. order.push(`end:${agent.seq}`)
  776. })
  777. ctx.on('workflow/end', () => { order.push('run-end') })
  778. const handle = ctx.workflows.start({
  779. // Same choreography as the force-settle pairing test, but the worker
  780. // DIES (the documented vm escape) instead of being terminated: the
  781. // exit path must close slow's pair from the ledger too. The escaped
  782. // setTimeout lets the already-posted messages flush before the kill.
  783. ...scripted(`
  784. const p = agent('slow')
  785. await agent('fast')
  786. const proc = ${ESCAPE}
  787. const st = globalThis.constructor.constructor('return setTimeout')()
  788. await new Promise(resolve => st(resolve, 150))
  789. proc.exit(7)
  790. `),
  791. parent,
  792. })
  793. await waitFor(() => { expect(order.filter(entry => entry.startsWith('start:')).length).toBe(2) })
  794. const fast = provider.runs.find(run => (run.request.prompt[0] as { text?: string }).text === 'fast')!
  795. fast.settle(text('fast done'))
  796. const result = await handle.result
  797. expect(result.stopReason).toBe('error')
  798. expect(result.error).toContain('exit code 7')
  799. expect(ends).toEqual([
  800. { seq: 2, outcome: 'completed' },
  801. { seq: 1, outcome: 'cancelled' },
  802. ])
  803. expect(order.indexOf('run-end')).toBe(order.length - 1)
  804. await handle.dispose()
  805. }, 15_000)
  806. it('a dispose ack racing the worker death is dropped, not crashed (post after exit)', async () => {
  807. // Slow child disposal: the ack resolves only AFTER the worker died, so
  808. // it has nowhere to go and must be dropped silently (the workerGone
  809. // guard in post()).
  810. const { ctx, parent, provider } = await setup({ disposeDelayMs: 300 })
  811. const handle = ctx.workflows.start({
  812. // The STRAY child settles instantly, so its wrapper starts the slow
  813. // host-side disposal concurrently while the script goes on to kill
  814. // its own worker — the ack then resolves into a dead thread.
  815. ...scripted(`
  816. agent('stray, never awaited')
  817. const proc = ${ESCAPE}
  818. const st = globalThis.constructor.constructor('return setTimeout')()
  819. await new Promise(resolve => st(resolve, 150))
  820. proc.exit(5)
  821. `),
  822. parent,
  823. })
  824. const result = await handle.result
  825. expect(result.stopReason).toBe('error')
  826. expect(result.error).toContain('exit code 5')
  827. // Result already settled — this is the reap's promptness (bounded
  828. // above the mock's fixed 300ms dispose delay, not a cold-start race);
  829. // tight explicit bound (see the helper's doc comment).
  830. await waitFor(() => { expect(provider.runs[0]!.disposed).toBe(true) }, 1000)
  831. await handle.dispose()
  832. }, 15_000)
  833. it('a worker death AFTER a cancel reports cancelled, not error', async () => {
  834. const { ctx, parent } = await setup({ config: { provider: 'stub', disposeGraceMs: 60_000 } })
  835. const handle = ctx.workflows.start({
  836. ...scripted(`
  837. const proc = ${ESCAPE}
  838. const st = globalThis.constructor.constructor('return setTimeout')()
  839. log('armed')
  840. await new Promise(resolve => st(resolve, 400))
  841. proc.exit(3)
  842. `),
  843. parent,
  844. })
  845. const logs: string[] = []
  846. ctx.on('workflow/log', (_info, message) => { logs.push(message) })
  847. await waitFor(() => { expect(logs).toContain('armed') })
  848. handle.cancel('stop it')
  849. // The grace is deliberately huge: only the worker's own death (exit 3,
  850. // unreachable by the cancel — the script ignores hooks) settles this.
  851. const result = await handle.result
  852. expect(result.stopReason).toBe('cancelled')
  853. expect(result.error).toContain('stop it')
  854. await handle.dispose()
  855. }, 15_000)
  856. })
  857. describe('service surface', () => {
  858. it('run ids are unique per start; the run handle and event payloads hold SEPARATE meta clones', async () => {
  859. const { ctx, parent } = await setup()
  860. let eventMeta: WorkflowRunInfo | undefined
  861. ctx.on('workflow/start', (info) => { eventMeta = info })
  862. const first = ctx.workflows.start({ ...scripted('return 1'), parent })
  863. const second = ctx.workflows.start({ ...scripted('return 2'), parent })
  864. expect(first.id).not.toBe(second.id)
  865. eventMeta!.meta.name = 'corrupted'
  866. expect(second.meta.name).toBe('test-flow')
  867. await Promise.all([first.result, second.result])
  868. await first.dispose()
  869. await second.dispose()
  870. })
  871. it('unregisters ctx.workflows when the engine fiber is disposed (HMR safety), and default config runs (auto concurrency)', async () => {
  872. const ctx = new Context()
  873. await ctx.plugin(SubagentService)
  874. const fiber = await ctx.plugin(WorkerWorkflowEngine, {})
  875. expect(ctx.get('workflows')).toBeDefined()
  876. // A zero-agent run through the DEFAULT config exercises the auto
  877. // concurrency resolution (cores - 2, capped) in start().
  878. const result = await run(ctx, fakeParent(), scripted('return 6 * 7'))
  879. expect(result.value).toBe(42)
  880. await fiber.dispose()
  881. expect(ctx.get('workflows')).toBeUndefined()
  882. })
  883. it('has the class-plugin export shape (default = the engine service class)', () => {
  884. expect(workerEngineModule.default).toBe(WorkerWorkflowEngine)
  885. const loader = Object.create(Loader.prototype) as Loader
  886. const unwrapped: unknown = loader.unwrapExports(workerEngineModule)
  887. expect(unwrapped).toBe(WorkerWorkflowEngine)
  888. })
  889. })
  890. })