session.spec.ts 24 KB

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