session.spec.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { MessageChannel } from 'node:worker_threads'
  3. import type { MessagePort } from 'node:worker_threads'
  4. import { HostToWorkerType, WorkerToHostType } from '../src/protocol.ts'
  5. import type { HostToWorkerMessage, WorkerToHostMessage } from '../src/protocol.ts'
  6. import { requireParentPort, runWorkerSession } from '../src/session.ts'
  7. import type { ChildResult, WorkerInit } from '../src/types.ts'
  8. /** Default limits for in-process sessions (concurrency pinned; auto is machine-derived). */
  9. function limits(overrides?: Partial<WorkerInit['limits']>): WorkerInit['limits'] {
  10. return { maxConcurrentAgents: 8, maxTotalAgents: 1000, maxItemsPerCall: 4096, syncTimeoutMs: 5000, ...overrides }
  11. }
  12. /** Wrap a body in the minimal valid meta header (the session receives it pre-extracted). */
  13. function init(body: string, args?: unknown, limitOverrides?: Partial<WorkerInit['limits']>): WorkerInit {
  14. return {
  15. meta: { name: 'test-flow', description: 'a test workflow' },
  16. body,
  17. ...args !== undefined ? { args } : {},
  18. limits: limits(limitOverrides),
  19. }
  20. }
  21. /** One scripted host over the other end of a MessageChannel. */
  22. interface FakeHost {
  23. port: MessagePort
  24. messages: WorkerToHostMessage[]
  25. /** Messages of one type, as they arrive. */
  26. ofType<T extends WorkerToHostMessage['type']>(type: T): Extract<WorkerToHostMessage, { type: T }>[]
  27. send(message: HostToWorkerMessage): void
  28. /** Resolves with the terminal result message. */
  29. result(): Promise<Extract<WorkerToHostMessage, { type: 'result' }>['result']>
  30. close(): void
  31. }
  32. interface FakeHostOptions {
  33. /** Auto-respond to child-start: reply started + settled per child index. Omit a reply to leave the child pending. */
  34. reply?: (request: { prompt: string; schema?: unknown; model?: string }, index: number) => ChildResult | undefined
  35. /** Reject the start instead (child-start-error) when returning a string. */
  36. refuse?: (index: number) => string | undefined
  37. /** Auto-send `go` on `ready` (default true). */
  38. go?: boolean
  39. /** Manual mode: do NOT auto-answer child-start at all (the test scripts the replies). */
  40. manual?: boolean
  41. }
  42. /**
  43. * Drive runWorkerSession IN-PROCESS over a MessageChannel: this is where the
  44. * worker-side files earn their coverage — code inside a real Worker is
  45. * invisible to main-process coverage. The fake host mirrors the real host's
  46. * protocol discipline (one started/start-error per start; settled/disposed
  47. * follow).
  48. */
  49. function fakeHost(options?: FakeHostOptions): FakeHost {
  50. const channel = new MessageChannel()
  51. const messages: WorkerToHostMessage[] = []
  52. const resultGate = Promise.withResolvers<Extract<WorkerToHostMessage, { type: 'result' }>['result']>()
  53. let childIndex = 0
  54. channel.port1.on('message', (message: WorkerToHostMessage) => {
  55. messages.push(message)
  56. switch (message.type) {
  57. case WorkerToHostType.Ready:
  58. if (options?.go !== false) channel.port1.postMessage({ type: HostToWorkerType.Go } satisfies HostToWorkerMessage)
  59. break
  60. case WorkerToHostType.ChildStart: {
  61. if (options?.manual) break
  62. const index = childIndex
  63. childIndex += 1
  64. const refusal = options?.refuse?.(index)
  65. if (refusal !== undefined) {
  66. channel.port1.postMessage(
  67. { type: HostToWorkerType.ChildStartError, callId: message.callId, rendered: refusal } satisfies HostToWorkerMessage,
  68. )
  69. break
  70. }
  71. channel.port1.postMessage({ type: HostToWorkerType.ChildStarted, callId: message.callId, childId: `child-${index}` } satisfies HostToWorkerMessage)
  72. const reply = options?.reply?.(message.request, index)
  73. if (reply !== undefined) {
  74. channel.port1.postMessage(
  75. { type: HostToWorkerType.ChildSettled, callId: message.callId, result: reply } satisfies HostToWorkerMessage,
  76. )
  77. }
  78. break
  79. }
  80. case WorkerToHostType.ChildDispose:
  81. channel.port1.postMessage({ type: HostToWorkerType.ChildDisposed, callId: message.callId } satisfies HostToWorkerMessage)
  82. break
  83. case WorkerToHostType.Result:
  84. resultGate.resolve(message.result)
  85. break
  86. default:
  87. break
  88. }
  89. })
  90. return {
  91. port: channel.port2,
  92. messages,
  93. ofType: type => messages.filter((message): message is never => message.type === type),
  94. send: (message) => { channel.port1.postMessage(message) },
  95. result: () => resultGate.promise,
  96. close: () => { channel.port1.close() },
  97. }
  98. }
  99. /** A completed text child result. */
  100. function text(reply: string): ChildResult {
  101. return { output: [{ type: 'text', text: reply }], stopReason: 'completed' }
  102. }
  103. describe('runWorkerSession over an in-process MessageChannel', () => {
  104. it('runs a script end to end: ready/go handshake, phases, log, agents, result', async () => {
  105. const host = fakeHost({ reply: (_request, index) => text(`answer-${index}`) })
  106. const session = runWorkerSession(host.port, init(`
  107. phase('Scan')
  108. log('starting with ' + args.files.length + ' files')
  109. const answers = await pipeline(args.files, (prev, item) => agent('read ' + item))
  110. return { answers }
  111. `, { files: ['a.ts', 'b.ts'] }))
  112. const result = await host.result()
  113. await session
  114. expect(result.stopReason).toBe('completed')
  115. expect(result.agentsStarted).toBe(2)
  116. expect(result.value).toEqual({ answers: ['answer-0', 'answer-1'] })
  117. expect(host.messages[0]!.type).toBe('ready')
  118. expect(host.ofType(WorkerToHostType.Phase).map(m => m.title)).toEqual(['Scan'])
  119. expect(host.ofType(WorkerToHostType.Log).map(m => m.message)).toEqual(['starting with 2 files'])
  120. expect(host.ofType(WorkerToHostType.AgentStart).map(m => m.info.childId)).toEqual(['child-0', 'child-1'])
  121. expect(host.ofType(WorkerToHostType.AgentEnd).every(m => m.info.outcome === 'completed')).toBe(true)
  122. host.close()
  123. })
  124. it('agent({schema}) forwards the schema on the start request and returns the structured value', async () => {
  125. const host = fakeHost({ reply: () => ({ output: [], structured: { files: ['x.ts'] }, stopReason: 'completed' }) })
  126. void runWorkerSession(host.port, init(`
  127. const found = await agent('list files', { schema: { type: 'object', properties: { files: { type: 'array', items: { type: 'string' } } } }, model: 'deepseek-v4-pro' })
  128. return { first: found.files[0] }
  129. `))
  130. const result = await host.result()
  131. expect(result.value).toEqual({ first: 'x.ts' })
  132. const start = host.ofType(WorkerToHostType.ChildStart)[0]!
  133. expect(start.request.schema).toEqual({ type: 'object', properties: { files: { type: 'array', items: { type: 'string' } } } })
  134. expect(start.request.model).toBe('deepseek-v4-pro')
  135. host.close()
  136. })
  137. it('a schema child completing WITHOUT a structured value resolves null with a failed outcome', async () => {
  138. const host = fakeHost({ reply: () => text('prose, no structure') })
  139. void runWorkerSession(host.port, init("return await agent('p', { schema: { type: 'object' } })"))
  140. const result = await host.result()
  141. expect(result.value).toBeNull()
  142. expect(host.ofType(WorkerToHostType.AgentEnd)[0]!.info.outcome).toBe('failed')
  143. host.close()
  144. })
  145. it('a child settling non-completed resolves null (scripts filter), never throwing into the script', async () => {
  146. const host = fakeHost({ reply: (_request, index) => index === 0 ? { output: [], stopReason: 'error' } : text('ok') })
  147. void runWorkerSession(host.port, init("return await parallel([() => agent('one'), () => agent('two')])"))
  148. const result = await host.result()
  149. expect(result.value).toEqual([null, 'ok'])
  150. expect(host.ofType(WorkerToHostType.AgentEnd).map(m => m.info.outcome)).toEqual(expect.arrayContaining(['failed', 'completed']))
  151. host.close()
  152. })
  153. it('a start refusal (child-start-error) is a fatal AGENT_START that kills the script through a combinator', async () => {
  154. const host = fakeHost({ refuse: () => 'no provider here' })
  155. void runWorkerSession(host.port, init("return await pipeline([1], () => agent('p'))"))
  156. const result = await host.result()
  157. expect(result.stopReason).toBe('error')
  158. expect(result.error).toContain('agent() could not start a child')
  159. expect(result.error).toContain('no provider here')
  160. host.close()
  161. })
  162. it('a child-failed message (infrastructure rejection) is fatal AGENT_RESULT with the paired failed outcome', async () => {
  163. const host = fakeHost()
  164. void runWorkerSession(host.port, init(`
  165. try { await agent('p'); return 'unreachable' } catch (e) { return { name: e.name, code: e.code, fatal: e.fatal } }
  166. `))
  167. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1) })
  168. const callId = host.ofType(WorkerToHostType.ChildStart)[0]!.callId
  169. host.send({ type: HostToWorkerType.ChildStarted, callId, childId: 'child-0' })
  170. host.send({ type: HostToWorkerType.ChildFailed, callId, rendered: 'backend exploded' })
  171. const result = await host.result()
  172. expect(result.value).toMatchObject({ name: 'WorkflowError', code: 'AGENT_RESULT', fatal: true })
  173. expect(host.ofType(WorkerToHostType.AgentEnd)[0]!.info.outcome).toBe('failed')
  174. host.close()
  175. })
  176. it('cancel before go: the body never runs at all and the result is cancelled (a second cancel is a no-op)', async () => {
  177. const host = fakeHost({ go: false })
  178. const session = runWorkerSession(host.port, init("log('ran')\nreturn 123"))
  179. await vi.waitFor(() => { expect(host.messages.some(m => m.type === WorkerToHostType.Ready)).toBe(true) })
  180. host.send({ type: HostToWorkerType.Cancel, reason: 'aborted before start' })
  181. // Idempotence: the first reason wins; a duplicate cancel changes nothing.
  182. host.send({ type: HostToWorkerType.Cancel, reason: 'a later reason that must lose' })
  183. const result = await host.result()
  184. await session
  185. expect(result.stopReason).toBe('cancelled')
  186. expect(result.error).toContain('aborted before start')
  187. expect(result.error).not.toContain('must lose')
  188. expect(result.value).toBeNull()
  189. expect(host.ofType(WorkerToHostType.Log)).toEqual([])
  190. host.close()
  191. })
  192. it('a script with no return value resolves value: null', async () => {
  193. const host = fakeHost({ reply: () => text('ok') })
  194. void runWorkerSession(host.port, init("await agent('p')"))
  195. const result = await host.result()
  196. expect(result.stopReason).toBe('completed')
  197. expect(result.value).toBeNull()
  198. host.close()
  199. })
  200. it('cancel mid-run: in-flight children get cancel RPCs, hooks throw at entry, the run reports cancelled', async () => {
  201. const host = fakeHost()
  202. void runWorkerSession(host.port, init(`
  203. phase('before')
  204. try { await agent('x') } catch (e) {}
  205. try { phase('after') } catch (e) {}
  206. try { log('after') } catch (e) {}
  207. try { await parallel([() => 'ran']) } catch (e) {}
  208. try { await pipeline(['item'], p => p) } catch (e) {}
  209. return 'survived by catching'
  210. `))
  211. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1) })
  212. const callId = host.ofType(WorkerToHostType.ChildStart)[0]!.callId
  213. host.send({ type: HostToWorkerType.ChildStarted, callId, childId: 'child-0' })
  214. host.send({ type: HostToWorkerType.Cancel, reason: 'stop everything' })
  215. // The real host settles the aborted child; mirror it.
  216. host.send({ type: HostToWorkerType.ChildSettled, callId, result: { output: [], stopReason: 'aborted' } })
  217. const result = await host.result()
  218. expect(result.stopReason).toBe('cancelled')
  219. expect(result.error).toContain('stop everything')
  220. expect(host.ofType(WorkerToHostType.ChildCancel).map(m => m.callId)).toContain(callId)
  221. expect(host.ofType(WorkerToHostType.AgentEnd)[0]!.info.outcome).toBe('cancelled')
  222. // No post-cancel narration left the runtime (the hooks threw at entry).
  223. expect(host.ofType(WorkerToHostType.Phase).map(m => m.title)).toEqual(['before'])
  224. expect(host.ofType(WorkerToHostType.Log)).toEqual([])
  225. host.close()
  226. })
  227. it('cancellation between a queued waiter and its slot: the waiter rejects without a child-start', async () => {
  228. const host = fakeHost({ go: true })
  229. void runWorkerSession(host.port, init(
  230. "return await parallel([() => agent('a'), () => agent('b')])",
  231. undefined,
  232. { maxConcurrentAgents: 1 },
  233. ))
  234. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1) })
  235. host.send({ type: HostToWorkerType.Cancel, reason: 'raced' })
  236. const result = await host.result()
  237. expect(result.stopReason).toBe('cancelled')
  238. // Only the first agent ever reached the host.
  239. expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1)
  240. host.close()
  241. })
  242. it('a stray (never-awaited) agent is reaped after settlement: cancel + dispose RPCs flow, no unhandled rejection', async () => {
  243. const unhandled: unknown[] = []
  244. const onUnhandled = (reason: unknown): void => { unhandled.push(reason) }
  245. process.on('unhandledRejection', onUnhandled)
  246. try {
  247. const host = fakeHost()
  248. void runWorkerSession(host.port, init(`
  249. agent('stray, never awaited')
  250. return 'done without awaiting'
  251. `))
  252. const result = await host.result()
  253. expect(result.stopReason).toBe('completed')
  254. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1) })
  255. const callId = host.ofType(WorkerToHostType.ChildStart)[0]!.callId
  256. host.send({ type: HostToWorkerType.ChildStarted, callId, childId: 'child-0' })
  257. host.send({ type: HostToWorkerType.ChildSettled, callId, result: { output: [], stopReason: 'aborted' } })
  258. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildDispose).map(m => m.callId)).toContain(callId) })
  259. await new Promise(resolve => setTimeout(resolve, 20))
  260. expect(unhandled).toEqual([])
  261. host.close()
  262. } finally {
  263. process.off('unhandledRejection', onUnhandled)
  264. }
  265. })
  266. it('an unparseable body settles an error result instead of dying without one (host pre-parse skew guard)', async () => {
  267. const host = fakeHost()
  268. await runWorkerSession(host.port, init('return ((('))
  269. const result = await host.result()
  270. expect(result.stopReason).toBe('error')
  271. expect(result.error).toContain('does not parse')
  272. expect(result.agentsStarted).toBe(0)
  273. host.close()
  274. })
  275. it('a synchronous spin in the initial slice dies by the in-worker vm timeout', async () => {
  276. const host = fakeHost()
  277. void runWorkerSession(host.port, init('while (true) {}', undefined, { syncTimeoutMs: 50 }))
  278. const result = await host.result()
  279. expect(result.stopReason).toBe('error')
  280. expect(result.error?.toLowerCase()).toContain('timed out')
  281. host.close()
  282. })
  283. it('a non-JSON return value fails loud as RESULT_UNSERIALIZABLE', async () => {
  284. const host = fakeHost()
  285. void runWorkerSession(host.port, init('return { when: new Date(0) }'))
  286. const result = await host.result()
  287. expect(result.stopReason).toBe('error')
  288. expect(result.error).toContain('not plain JSON data')
  289. host.close()
  290. })
  291. it('tolerates replies for unknown callIds (a teardown race): nothing crashes, the run completes', async () => {
  292. const host = fakeHost({ reply: () => text('fine') })
  293. void runWorkerSession(host.port, init("return await agent('p')"))
  294. host.send({ type: HostToWorkerType.ChildStarted, callId: 999, childId: 'ghost' })
  295. host.send({ type: HostToWorkerType.ChildStartError, callId: 999, rendered: 'ghost' })
  296. host.send({ type: HostToWorkerType.ChildSettled, callId: 999, result: text('ghost') })
  297. host.send({ type: HostToWorkerType.ChildFailed, callId: 999, rendered: 'ghost' })
  298. host.send({ type: HostToWorkerType.ChildDisposed, callId: 999 })
  299. const result = await host.result()
  300. expect(result.stopReason).toBe('completed')
  301. expect(result.value).toBe('fine')
  302. host.close()
  303. })
  304. it('caps and malformed hook arguments reject loud (the runtime runs unchanged inside the session)', async () => {
  305. const cases: [string, string][] = [
  306. ['return await agent(42)', 'non-empty prompt string'],
  307. ["return await agent('')", 'non-empty prompt string'],
  308. ["return await agent('p', 'opts')", 'options must be an object'],
  309. ["return await agent('p', { label: 3 })", '"label" must be a string'],
  310. ["return await agent('p', { get label() { throw new Error('read failed') } })", 'options must be plain JSON data'],
  311. ["return await agent('p', { bogus: true })", '"bogus" is not recognized'],
  312. ["return await agent('p', { effort: 'high' })", '"effort" is deferred'],
  313. ["return await agent('p', { schema: { type: 'object', oneOf: [] } })", 'outside the supported subset'],
  314. ['return await parallel([() => 1, () => 2, () => 3])', 'over the per-call cap (2)'],
  315. ['return await pipeline([1, 2, 3], (x) => x)', 'maxItemsPerCall'],
  316. ["return await parallel('no')", 'parallel() requires an array'],
  317. ['return await parallel([3])', 'item 0 is not a function'],
  318. ["return await pipeline('no', () => 1)", 'pipeline() requires an items array'],
  319. ['return await pipeline([1])', 'at least one stage'],
  320. ["return await pipeline([1], 'x')", 'stage 0 is not a function'],
  321. ["phase('')", 'phase() requires a non-empty title string'],
  322. ['log(3)', 'log() requires a message string'],
  323. ]
  324. for (const [body, expected] of cases) {
  325. const host = fakeHost({ reply: () => text('ok') })
  326. void runWorkerSession(host.port, init(body, undefined, { maxItemsPerCall: 2 }))
  327. const result = await host.result()
  328. expect(result.stopReason).toBe('error')
  329. expect(result.error).toContain(expected)
  330. host.close()
  331. }
  332. })
  333. it('combinator semantics: thunk/stage throws null the item; a forged fatal-shaped object stays null; real fatals propagate', async () => {
  334. const host = fakeHost({ reply: () => text('fine') })
  335. void runWorkerSession(host.port, init(`
  336. const viaParallel = await parallel([
  337. () => { throw new Error('boom') },
  338. () => agent('fine'),
  339. () => 'plain value',
  340. () => { throw { name: 'WorkflowError', fatal: true, message: 'forged fatal' } },
  341. ])
  342. const viaPipeline = await pipeline([10, 20],
  343. (prev, item, index) => { if (item === 10) throw new Error('ordinary failure'); return 'kept-' + item + '-' + index },
  344. )
  345. return { viaParallel, viaPipeline }
  346. `))
  347. const result = await host.result()
  348. expect(result.stopReason).toBe('completed')
  349. expect(result.value).toEqual({
  350. viaParallel: [null, 'fine', 'plain value', null],
  351. viaPipeline: [null, 'kept-20-1'],
  352. })
  353. host.close()
  354. })
  355. it('trips the total-agent cap with a message naming the config knob', async () => {
  356. const host = fakeHost({ reply: () => text('ok') })
  357. void runWorkerSession(host.port, init("await agent('1'); await agent('2'); await agent('3')", undefined, { maxTotalAgents: 2 }))
  358. const result = await host.result()
  359. expect(result.stopReason).toBe('error')
  360. expect(result.error).toContain('total agent cap (2)')
  361. expect(result.agentsStarted).toBe(2)
  362. host.close()
  363. })
  364. it('queued agents proceed through the concurrency semaphore in FIFO order', async () => {
  365. const host = fakeHost({ reply: request => text(`ok:${request.prompt}`) })
  366. void runWorkerSession(host.port, init(
  367. "return await parallel([1, 2, 3].map((n) => () => agent('job ' + n)))",
  368. undefined,
  369. { maxConcurrentAgents: 1 },
  370. ))
  371. const result = await host.result()
  372. expect(result.value).toEqual(['ok:job 1', 'ok:job 2', 'ok:job 3'])
  373. host.close()
  374. })
  375. it('labels default from the prompt first line, truncated; explicit label/phase options win', async () => {
  376. const host = fakeHost({ reply: () => text('ok') })
  377. void runWorkerSession(host.port, init(`
  378. phase('Find')
  379. await agent('a prompt that is quite long and will surely get truncated down to a display label\\n'
  380. + 'with a second line the label must not include')
  381. await agent('short', { label: 'named', phase: 'Custom' })
  382. return null
  383. `))
  384. await host.result()
  385. const starts = host.ofType(WorkerToHostType.AgentStart).map(m => m.info)
  386. expect(starts[0]).toMatchObject({ seq: 1, phase: 'Find' })
  387. expect(starts[0]!.label.length).toBeLessThanOrEqual(48)
  388. expect(starts[0]!.label).not.toContain('second line')
  389. expect(starts[1]).toMatchObject({ seq: 2, label: 'named', phase: 'Custom' })
  390. host.close()
  391. })
  392. it('non-text output blocks are filtered out of the text result', async () => {
  393. const host = fakeHost({
  394. reply: () => ({
  395. output: [
  396. { type: 'text', text: 'first ' },
  397. { type: 'tool_call', id: 'c1', name: 'x', arguments: {} } as never,
  398. { type: 'text', text: 'second' },
  399. ],
  400. stopReason: 'completed',
  401. }),
  402. })
  403. void runWorkerSession(host.port, init("return await agent('p')"))
  404. const result = await host.result()
  405. expect(result.value).toBe('first second')
  406. host.close()
  407. })
  408. it('a cancel landing DURING the start round-trip winds the fresh child down (cancel + dispose) and dies cancelled', async () => {
  409. const host = fakeHost({ manual: true })
  410. void runWorkerSession(host.port, init("return await agent('p')"))
  411. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1) })
  412. const callId = host.ofType(WorkerToHostType.ChildStart)[0]!.callId
  413. // Cancel FIRST, then the (stale) started reply: the worker processes them
  414. // in order, so the agent() continuation resumes already-cancelled — the
  415. // window the real host cannot produce (it refuses starts once cancelled)
  416. // but a teardown race can.
  417. host.send({ type: HostToWorkerType.Cancel, reason: 'raced the start' })
  418. host.send({ type: HostToWorkerType.ChildStarted, callId, childId: 'child-0' })
  419. const result = await host.result()
  420. expect(result.stopReason).toBe('cancelled')
  421. await vi.waitFor(() => {
  422. expect(host.ofType(WorkerToHostType.ChildCancel).map(m => m.callId)).toContain(callId)
  423. expect(host.ofType(WorkerToHostType.ChildDispose).map(m => m.callId)).toContain(callId)
  424. })
  425. // The child never became an agent-start: it was wound down pre-lifecycle.
  426. expect(host.ofType(WorkerToHostType.AgentStart)).toEqual([])
  427. host.close()
  428. })
  429. it('a start refusal arriving after a cancel reads as the cancellation, not a broken seam', async () => {
  430. const host = fakeHost({ manual: true })
  431. void runWorkerSession(host.port, init(`
  432. try { await agent('p'); return 'unreachable' } catch (e) { return { code: e.code } }
  433. `))
  434. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1) })
  435. const callId = host.ofType(WorkerToHostType.ChildStart)[0]!.callId
  436. host.send({ type: HostToWorkerType.Cancel, reason: 'stopping' })
  437. host.send({ type: HostToWorkerType.ChildStartError, callId, rendered: 'workflow run cancelled: stopping' })
  438. const result = await host.result()
  439. // The run reports cancelled (the script died of CANCELLED, not AGENT_START).
  440. expect(result.stopReason).toBe('cancelled')
  441. host.close()
  442. })
  443. it('a child result rejection while cancelled pairs a cancelled agent-end, and the run reports cancelled', async () => {
  444. const host = fakeHost({ manual: true })
  445. void runWorkerSession(host.port, init("return await agent('doomed')"))
  446. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1) })
  447. const callId = host.ofType(WorkerToHostType.ChildStart)[0]!.callId
  448. host.send({ type: HostToWorkerType.ChildStarted, callId, childId: 'child-0' })
  449. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.AgentStart).length).toBe(1) })
  450. host.send({ type: HostToWorkerType.Cancel, reason: 'user aborted' })
  451. host.send({ type: HostToWorkerType.ChildFailed, callId, rendered: 'backend crashed on abort' })
  452. const result = await host.result()
  453. expect(result.stopReason).toBe('cancelled')
  454. expect(host.ofType(WorkerToHostType.AgentEnd)[0]!.info.outcome).toBe('cancelled')
  455. host.close()
  456. })
  457. })
  458. describe('the worker bootstrap', () => {
  459. it('requireParentPort narrows a real port and throws on the main thread', () => {
  460. const channel = new MessageChannel()
  461. expect(requireParentPort(channel.port1)).toBe(channel.port1)
  462. channel.port1.close()
  463. expect(() => requireParentPort(null)).toThrow(/inside a worker thread/)
  464. })
  465. it('the entry module itself throws when loaded on the main thread (no parentPort)', async () => {
  466. // This import EXECUTES ../src/worker.ts on the main thread, which is what
  467. // covers the bootstrap file: requireParentPort throws before
  468. // runWorkerSession is reached.
  469. await expect(import('../src/worker.ts')).rejects.toThrow(/inside a worker thread/)
  470. })
  471. })