session.spec.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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: hooks throw at entry and 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.AgentEnd)[0]!.info.outcome).toBe('cancelled')
  221. // No post-cancel narration left the runtime (the hooks threw at entry).
  222. expect(host.ofType(WorkerToHostType.Phase).map(m => m.title)).toEqual(['before'])
  223. expect(host.ofType(WorkerToHostType.Log)).toEqual([])
  224. host.close()
  225. })
  226. it('cancellation between a queued waiter and its slot: the waiter rejects without a child-start', async () => {
  227. const host = fakeHost({ go: true })
  228. void runWorkerSession(host.port, init(
  229. "return await parallel([() => agent('a'), () => agent('b')])",
  230. undefined,
  231. { maxConcurrentAgents: 1 },
  232. ))
  233. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1) })
  234. host.send({ type: HostToWorkerType.Cancel, reason: 'raced' })
  235. const result = await host.result()
  236. expect(result.stopReason).toBe('cancelled')
  237. // Only the first agent ever reached the host.
  238. expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1)
  239. host.close()
  240. })
  241. it('a stray (never-awaited) agent is reaped after settlement: cancel + dispose RPCs flow, no unhandled rejection', async () => {
  242. const unhandled: unknown[] = []
  243. const onUnhandled = (reason: unknown): void => { unhandled.push(reason) }
  244. process.on('unhandledRejection', onUnhandled)
  245. try {
  246. const host = fakeHost()
  247. void runWorkerSession(host.port, init(`
  248. agent('stray, never awaited')
  249. return 'done without awaiting'
  250. `))
  251. const result = await host.result()
  252. expect(result.stopReason).toBe('completed')
  253. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1) })
  254. const callId = host.ofType(WorkerToHostType.ChildStart)[0]!.callId
  255. host.send({ type: HostToWorkerType.ChildStarted, callId, childId: 'child-0' })
  256. host.send({ type: HostToWorkerType.ChildSettled, callId, result: { output: [], stopReason: 'aborted' } })
  257. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildDispose).map(m => m.callId)).toContain(callId) })
  258. await new Promise(resolve => setTimeout(resolve, 20))
  259. expect(unhandled).toEqual([])
  260. host.close()
  261. } finally {
  262. process.off('unhandledRejection', onUnhandled)
  263. }
  264. })
  265. it('an unparseable body settles an error result instead of dying without one (host pre-parse skew guard)', async () => {
  266. const host = fakeHost()
  267. await runWorkerSession(host.port, init('return ((('))
  268. const result = await host.result()
  269. expect(result.stopReason).toBe('error')
  270. expect(result.error).toContain('does not parse')
  271. expect(result.agentsStarted).toBe(0)
  272. host.close()
  273. })
  274. it('a synchronous spin in the initial slice dies by the in-worker vm timeout', async () => {
  275. const host = fakeHost()
  276. void runWorkerSession(host.port, init('while (true) {}', undefined, { syncTimeoutMs: 50 }))
  277. const result = await host.result()
  278. expect(result.stopReason).toBe('error')
  279. expect(result.error?.toLowerCase()).toContain('timed out')
  280. host.close()
  281. })
  282. it('a non-JSON return value fails loud as RESULT_UNSERIALIZABLE', async () => {
  283. const host = fakeHost()
  284. void runWorkerSession(host.port, init('return { when: new Date(0) }'))
  285. const result = await host.result()
  286. expect(result.stopReason).toBe('error')
  287. expect(result.error).toContain('not plain JSON data')
  288. host.close()
  289. })
  290. it('tolerates replies for unknown callIds (a teardown race): nothing crashes, the run completes', async () => {
  291. const host = fakeHost({ reply: () => text('fine') })
  292. void runWorkerSession(host.port, init("return await agent('p')"))
  293. host.send({ type: HostToWorkerType.ChildStarted, callId: 999, childId: 'ghost' })
  294. host.send({ type: HostToWorkerType.ChildStartError, callId: 999, rendered: 'ghost' })
  295. host.send({ type: HostToWorkerType.ChildSettled, callId: 999, result: text('ghost') })
  296. host.send({ type: HostToWorkerType.ChildFailed, callId: 999, rendered: 'ghost' })
  297. host.send({ type: HostToWorkerType.ChildDisposed, callId: 999 })
  298. const result = await host.result()
  299. expect(result.stopReason).toBe('completed')
  300. expect(result.value).toBe('fine')
  301. host.close()
  302. })
  303. it('caps and malformed hook arguments reject loud (the runtime runs unchanged inside the session)', async () => {
  304. const cases: [string, string][] = [
  305. ['return await agent(42)', 'non-empty prompt string'],
  306. ["return await agent('')", 'non-empty prompt string'],
  307. ["return await agent('p', 'opts')", 'options must be an object'],
  308. ["return await agent('p', { label: 3 })", '"label" must be a string'],
  309. ["return await agent('p', { get label() { throw new Error('read failed') } })", 'options must be plain JSON data'],
  310. ["return await agent('p', { bogus: true })", '"bogus" is not recognized'],
  311. ["return await agent('p', { effort: 'high' })", '"effort" is deferred'],
  312. ["return await agent('p', { schema: { type: 'object', oneOf: [] } })", 'outside the supported subset'],
  313. ['return await parallel([() => 1, () => 2, () => 3])', 'over the per-call cap (2)'],
  314. ['return await pipeline([1, 2, 3], (x) => x)', 'maxItemsPerCall'],
  315. ["return await parallel('no')", 'parallel() requires an array'],
  316. ['return await parallel([3])', 'item 0 is not a function'],
  317. ["return await pipeline('no', () => 1)", 'pipeline() requires an items array'],
  318. ['return await pipeline([1])', 'at least one stage'],
  319. ["return await pipeline([1], 'x')", 'stage 0 is not a function'],
  320. ["phase('')", 'phase() requires a non-empty title string'],
  321. ['log(3)', 'log() requires a message string'],
  322. ]
  323. for (const [body, expected] of cases) {
  324. const host = fakeHost({ reply: () => text('ok') })
  325. void runWorkerSession(host.port, init(body, undefined, { maxItemsPerCall: 2 }))
  326. const result = await host.result()
  327. expect(result.stopReason).toBe('error')
  328. expect(result.error).toContain(expected)
  329. host.close()
  330. }
  331. })
  332. it('combinator semantics: thunk/stage throws null the item; a forged fatal-shaped object stays null; real fatals propagate', async () => {
  333. const host = fakeHost({ reply: () => text('fine') })
  334. void runWorkerSession(host.port, init(`
  335. const viaParallel = await parallel([
  336. () => { throw new Error('boom') },
  337. () => agent('fine'),
  338. () => 'plain value',
  339. () => { throw { name: 'WorkflowError', fatal: true, message: 'forged fatal' } },
  340. ])
  341. const viaPipeline = await pipeline([10, 20],
  342. (prev, item, index) => { if (item === 10) throw new Error('ordinary failure'); return 'kept-' + item + '-' + index },
  343. )
  344. return { viaParallel, viaPipeline }
  345. `))
  346. const result = await host.result()
  347. expect(result.stopReason).toBe('completed')
  348. expect(result.value).toEqual({
  349. viaParallel: [null, 'fine', 'plain value', null],
  350. viaPipeline: [null, 'kept-20-1'],
  351. })
  352. host.close()
  353. })
  354. it('trips the total-agent cap with a message naming the config knob', async () => {
  355. const host = fakeHost({ reply: () => text('ok') })
  356. void runWorkerSession(host.port, init("await agent('1'); await agent('2'); await agent('3')", undefined, { maxTotalAgents: 2 }))
  357. const result = await host.result()
  358. expect(result.stopReason).toBe('error')
  359. expect(result.error).toContain('total agent cap (2)')
  360. expect(result.agentsStarted).toBe(2)
  361. host.close()
  362. })
  363. it('queued agents proceed through the concurrency semaphore in FIFO order', async () => {
  364. const host = fakeHost({ reply: request => text(`ok:${request.prompt}`) })
  365. void runWorkerSession(host.port, init(
  366. "return await parallel([1, 2, 3].map((n) => () => agent('job ' + n)))",
  367. undefined,
  368. { maxConcurrentAgents: 1 },
  369. ))
  370. const result = await host.result()
  371. expect(result.value).toEqual(['ok:job 1', 'ok:job 2', 'ok:job 3'])
  372. host.close()
  373. })
  374. it('labels default from the prompt first line, truncated; explicit label/phase options win', async () => {
  375. const host = fakeHost({ reply: () => text('ok') })
  376. void runWorkerSession(host.port, init(`
  377. phase('Find')
  378. await agent('a prompt that is quite long and will surely get truncated down to a display label\\n'
  379. + 'with a second line the label must not include')
  380. await agent('short', { label: 'named', phase: 'Custom' })
  381. return null
  382. `))
  383. await host.result()
  384. const starts = host.ofType(WorkerToHostType.AgentStart).map(m => m.info)
  385. expect(starts[0]).toMatchObject({ seq: 1, phase: 'Find' })
  386. expect(starts[0]!.label.length).toBeLessThanOrEqual(48)
  387. expect(starts[0]!.label).not.toContain('second line')
  388. expect(starts[1]).toMatchObject({ seq: 2, label: 'named', phase: 'Custom' })
  389. host.close()
  390. })
  391. it('non-text output blocks are filtered out of the text result', async () => {
  392. const host = fakeHost({
  393. reply: () => ({
  394. output: [
  395. { type: 'text', text: 'first ' },
  396. { type: 'tool_call', id: 'c1', name: 'x', arguments: {} } as never,
  397. { type: 'text', text: 'second' },
  398. ],
  399. stopReason: 'completed',
  400. }),
  401. })
  402. void runWorkerSession(host.port, init("return await agent('p')"))
  403. const result = await host.result()
  404. expect(result.value).toBe('first second')
  405. host.close()
  406. })
  407. it('a cancel landing DURING the start round-trip disposes the fresh child and dies cancelled', async () => {
  408. const host = fakeHost({ manual: true })
  409. void runWorkerSession(host.port, init("return await agent('p')"))
  410. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1) })
  411. const callId = host.ofType(WorkerToHostType.ChildStart)[0]!.callId
  412. // Simulate a teardown race by delivering cancellation before a stale start reply.
  413. host.send({ type: HostToWorkerType.Cancel, reason: 'raced the start' })
  414. host.send({ type: HostToWorkerType.ChildStarted, callId, childId: 'child-0' })
  415. const result = await host.result()
  416. expect(result.stopReason).toBe('cancelled')
  417. await vi.waitFor(() => {
  418. expect(host.ofType(WorkerToHostType.ChildDispose).map(m => m.callId)).toContain(callId)
  419. })
  420. // The unpublished child is disposed without a lifecycle announcement.
  421. expect(host.ofType(WorkerToHostType.AgentStart)).toEqual([])
  422. host.close()
  423. })
  424. it('a start refusal arriving after a cancel reads as the cancellation, not a broken seam', async () => {
  425. const host = fakeHost({ manual: true })
  426. void runWorkerSession(host.port, init(`
  427. try { await agent('p'); return 'unreachable' } catch (e) { return { code: e.code } }
  428. `))
  429. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1) })
  430. const callId = host.ofType(WorkerToHostType.ChildStart)[0]!.callId
  431. host.send({ type: HostToWorkerType.Cancel, reason: 'stopping' })
  432. host.send({ type: HostToWorkerType.ChildStartError, callId, rendered: 'workflow run cancelled: stopping' })
  433. const result = await host.result()
  434. // The run reports cancelled (the script died of CANCELLED, not AGENT_START).
  435. expect(result.stopReason).toBe('cancelled')
  436. host.close()
  437. })
  438. it('a child result rejection while cancelled pairs a cancelled agent-end, and the run reports cancelled', async () => {
  439. const host = fakeHost({ manual: true })
  440. void runWorkerSession(host.port, init("return await agent('doomed')"))
  441. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.ChildStart).length).toBe(1) })
  442. const callId = host.ofType(WorkerToHostType.ChildStart)[0]!.callId
  443. host.send({ type: HostToWorkerType.ChildStarted, callId, childId: 'child-0' })
  444. await vi.waitFor(() => { expect(host.ofType(WorkerToHostType.AgentStart).length).toBe(1) })
  445. host.send({ type: HostToWorkerType.Cancel, reason: 'user aborted' })
  446. host.send({ type: HostToWorkerType.ChildFailed, callId, rendered: 'backend crashed on abort' })
  447. const result = await host.result()
  448. expect(result.stopReason).toBe('cancelled')
  449. expect(host.ofType(WorkerToHostType.AgentEnd)[0]!.info.outcome).toBe('cancelled')
  450. host.close()
  451. })
  452. })
  453. describe('the worker bootstrap', () => {
  454. it('requireParentPort narrows a real port and throws on the main thread', () => {
  455. const channel = new MessageChannel()
  456. expect(requireParentPort(channel.port1)).toBe(channel.port1)
  457. channel.port1.close()
  458. expect(() => requireParentPort(null)).toThrow(/inside a worker thread/)
  459. })
  460. it('the entry module itself throws when loaded on the main thread (no parentPort)', async () => {
  461. // This import EXECUTES ../src/worker.ts on the main thread, which is what
  462. // covers the bootstrap file: requireParentPort throws before
  463. // runWorkerSession is reached.
  464. await expect(import('../src/worker.ts')).rejects.toThrow(/inside a worker thread/)
  465. })
  466. })