tool-workflow.spec.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import Loader from '@deepseek-ai/cordis-plugin-loader'
  4. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  5. import ToolRuntime, { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools'
  6. import type { ToolExecutionResult, ToolExecutionToken } from '@deepseek-ai/dsh-tools'
  7. import type { Agent } from '@deepseek-ai/dsh-agent'
  8. import { WorkflowRunId, WorkflowEngine } from '@deepseek-ai/dsh-workflow'
  9. import type {
  10. WorkflowAgentEndInfo, WorkflowAgentInfo, WorkflowResult, WorkflowRun,
  11. WorkflowRunId as WorkflowRunIdType, WorkflowStartRequest,
  12. } from '@deepseek-ai/dsh-workflow'
  13. import { ToolCallId } from '@deepseek-ai/dsh-llm'
  14. import SubagentRuntime from '@deepseek-ai/dsh-subagent'
  15. import WorkerThreadWorkflowEngine from '@deepseek-ai/dsh-workflow-worker-thread'
  16. import * as toolWorkflow from '../src/index.ts'
  17. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  18. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  19. const testToolSignal = new AbortController().signal
  20. /** A controllable engine standing in behind ctx.workflowEngine (the tool's only seam). */
  21. class StubEngine extends WorkflowEngine {
  22. requests: WorkflowStartRequest[] = []
  23. cancels: string[] = []
  24. disposed = 0
  25. disposeBarrier: Promise<void> | undefined
  26. settle!: (result: WorkflowResult) => void
  27. readonly settlements = new Map<WorkflowRunIdType, (result: WorkflowResult) => void>()
  28. startError: Error | undefined
  29. start(request: WorkflowStartRequest): WorkflowRun {
  30. if (this.startError) throw this.startError
  31. this.requests.push(request)
  32. const id = WorkflowRunId(`run-${this.requests.length}`)
  33. const result = new Promise<WorkflowResult>((resolve) => { this.settle = resolve })
  34. this.settlements.set(id, this.settle)
  35. request.signal?.addEventListener('abort', () => {
  36. this.settle({ value: null, stopReason: 'cancelled', error: 'signal', agentsStarted: 0 })
  37. }, { once: true })
  38. return {
  39. id,
  40. meta: request.meta,
  41. result,
  42. cancel: (reason?: string) => {
  43. this.cancels.push(reason ?? 'cancelled')
  44. this.settle({ value: null, stopReason: 'cancelled', ...reason !== undefined ? { error: reason } : {}, agentsStarted: 0 })
  45. },
  46. dispose: async () => {
  47. this.disposed += 1
  48. await this.disposeBarrier
  49. this.settlements.delete(id)
  50. },
  51. }
  52. }
  53. settleRun(id: WorkflowRunIdType, result: WorkflowResult): void {
  54. const settle = this.settlements.get(id)
  55. if (settle === undefined) throw new Error(`unknown stub workflow ${id}`)
  56. settle(result)
  57. }
  58. agentStart(id: WorkflowRunIdType, agent: WorkflowAgentInfo): void {
  59. this.emitWorkflowEvent('workflow/agent-start', {
  60. id,
  61. meta: this.requests[Number(String(id).slice(4)) - 1]!.meta,
  62. }, agent)
  63. }
  64. agentEnd(id: WorkflowRunIdType, agent: WorkflowAgentEndInfo): void {
  65. this.emitWorkflowEvent('workflow/agent-end', {
  66. id,
  67. meta: this.requests[Number(String(id).slice(4)) - 1]!.meta,
  68. }, agent)
  69. }
  70. }
  71. async function setup(config?: { toolName?: string; maxResultChars?: number }) {
  72. const ctx = new Context()
  73. await ctx.plugin(SystemPrompt)
  74. await ctx.plugin(ToolRuntime)
  75. await ctx.plugin(StubEngine)
  76. await ctx.plugin(toolWorkflow, config ?? {})
  77. const engine = ctx.workflowEngine as StubEngine
  78. const session = Session.create(SessionId('caller'))
  79. const parent = { id: session.id, options: {}, session } as unknown as Agent
  80. return { ctx, engine, parent, session }
  81. }
  82. const SCRIPT = 'return 1'
  83. const META = { name: 'audit', description: 'd' }
  84. function execute(ctx: Context, args: unknown, extra?: {
  85. agent?: Agent
  86. signal?: AbortSignal
  87. parent?: ToolExecutionToken
  88. }): Promise<ToolExecutionResult> {
  89. return ctx.tools.execute({
  90. signal: testToolSignal,
  91. callId: ToolCallId('call-1'),
  92. name: 'workflow',
  93. arguments: args,
  94. ...extra?.agent ? { agent: extra.agent } : {},
  95. ...extra?.signal ? { signal: extra.signal } : {},
  96. ...extra?.parent ? { parent: extra.parent } : {},
  97. })
  98. }
  99. describe('dsh-tool-workflow', () => {
  100. it('starts a run with the script/args/parent/signal and renders the completed value', async () => {
  101. const { ctx, engine, parent } = await setup()
  102. const controller = new AbortController()
  103. const pending = execute(ctx, { script: SCRIPT, meta: META, args: { files: ['a.ts'] } }, { agent: parent, signal: controller.signal })
  104. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  105. expect(engine.requests[0]).toMatchObject({ script: SCRIPT, meta: META, args: { files: ['a.ts'] }, parent })
  106. expect(engine.requests[0]!.signal).toBe(controller.signal)
  107. engine.settle({ value: { findings: [1, 2] }, stopReason: 'completed', agentsStarted: 7 })
  108. const result = await pending
  109. expect(result.isError).toBe(false)
  110. if (result.isError) throw new Error('expected workflow success')
  111. expect(result.value).toEqual({ runId: 'run-1', agentsStarted: 7, result: { findings: [1, 2] } })
  112. const rendered = (result.content[0] as { text: string }).text
  113. expect(rendered).toContain('workflow "audit" completed (7 agents)')
  114. expect(rendered).toContain('"findings"')
  115. expect(engine.disposed).toBe(1)
  116. })
  117. it('records one top-level run and its members in the calling Session after cleanup', async () => {
  118. const { ctx, engine, parent, session } = await setup()
  119. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  120. await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
  121. const runId = WorkflowRunId('run-1')
  122. engine.agentStart(runId, {
  123. seq: 1,
  124. label: '',
  125. phase: '',
  126. childId: SessionId('child-1'),
  127. })
  128. engine.agentEnd(runId, {
  129. seq: 1,
  130. label: '',
  131. phase: '',
  132. childId: SessionId('child-1'),
  133. outcome: 'completed',
  134. })
  135. engine.settleRun(runId, { value: 1, stopReason: 'completed', agentsStarted: 1 })
  136. expect((await pending).isError).toBe(false)
  137. expect(engine.disposed).toBe(1)
  138. expect(session.snapshotEvents().map(event => [event.type, event.data])).toEqual([
  139. ['tool-workflow/run-start', { runId: 'run-1', name: 'audit' }],
  140. ['tool-workflow/agent-start', {
  141. runId: 'run-1', seq: 1, label: '', phase: '', childId: 'child-1',
  142. }],
  143. ['tool-workflow/agent-end', { runId: 'run-1', seq: 1, outcome: 'completed' }],
  144. ['tool-workflow/run-end', { runId: 'run-1', stopReason: 'completed' }],
  145. ])
  146. })
  147. it('writes run-end only after run disposal reaches quiescence', async () => {
  148. const { ctx, engine, parent, session } = await setup()
  149. const barrier = Promise.withResolvers<undefined>()
  150. engine.disposeBarrier = barrier.promise
  151. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  152. await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
  153. engine.settleRun(WorkflowRunId('run-1'), {
  154. value: null, stopReason: 'completed', agentsStarted: 0,
  155. })
  156. await vi.waitFor(() => { expect(engine.disposed).toBe(1) })
  157. expect(session.snapshotEvents().map(event => event.type)).toEqual(['tool-workflow/run-start'])
  158. barrier.resolve(undefined)
  159. expect((await pending).isError).toBe(false)
  160. expect(session.snapshotEvents().map(event => event.type)).toEqual([
  161. 'tool-workflow/run-start', 'tool-workflow/run-end',
  162. ])
  163. })
  164. it('records zero-member and concurrent runs independently', async () => {
  165. const { ctx, engine, parent, session } = await setup()
  166. const first = execute(ctx, { script: SCRIPT, meta: { ...META, name: 'first' } }, { agent: parent })
  167. const second = execute(ctx, { script: SCRIPT, meta: { ...META, name: 'second' } }, { agent: parent })
  168. await vi.waitFor(() => { expect(engine.requests).toHaveLength(2) })
  169. const secondId = WorkflowRunId('run-2')
  170. engine.agentStart(secondId, {
  171. seq: 1, label: 'member', childId: SessionId('child-2'),
  172. })
  173. engine.agentEnd(secondId, {
  174. seq: 1, label: 'member', childId: SessionId('child-2'), outcome: 'failed',
  175. })
  176. engine.settleRun(WorkflowRunId('run-1'), { value: null, stopReason: 'completed', agentsStarted: 0 })
  177. engine.settleRun(secondId, { value: null, stopReason: 'error', error: 'child failed', agentsStarted: 1 })
  178. expect((await first).isError).toBe(false)
  179. expect((await second).isError).toBe(true)
  180. expect(session.snapshotEvents().filter(event => event.type === 'tool-workflow/agent-start'))
  181. .toHaveLength(1)
  182. expect(session.snapshotEvents().filter(event => event.type === 'tool-workflow/run-end').map(event => event.data))
  183. .toEqual([
  184. { runId: 'run-1', stopReason: 'completed' },
  185. { runId: 'run-2', stopReason: 'error' },
  186. ])
  187. })
  188. it('does not record nested transport executions', async () => {
  189. const { ctx, engine, parent, session } = await setup()
  190. const pending = execute(ctx, { script: SCRIPT, meta: META }, {
  191. agent: parent,
  192. parent: Symbol('outer') as ToolExecutionToken,
  193. })
  194. await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
  195. engine.settleRun(WorkflowRunId('run-1'), { value: null, stopReason: 'completed', agentsStarted: 0 })
  196. expect((await pending).isError).toBe(false)
  197. expect(session.snapshotEvents()).toEqual([])
  198. })
  199. it.each([
  200. 'tool-workflow/run-start',
  201. 'tool-workflow/agent-start',
  202. 'tool-workflow/agent-end',
  203. 'tool-workflow/run-end',
  204. ] as const)('isolates a first append failure at %s and preserves a valid prefix', async (failedType) => {
  205. const { ctx, engine, parent, session } = await setup()
  206. const warnings: string[] = []
  207. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  208. const append = session.append.bind(session)
  209. session.append = ((type: Parameters<Session['append']>[0], data: never) => {
  210. if (type === failedType) throw new Error(`injected ${failedType} failure`)
  211. return append(type, data)
  212. }) as Session['append']
  213. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  214. await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
  215. const runId = WorkflowRunId('run-1')
  216. engine.agentStart(runId, {
  217. seq: 1, label: 'member', childId: SessionId('child-1'),
  218. })
  219. engine.agentEnd(runId, {
  220. seq: 1, label: 'member', childId: SessionId('child-1'), outcome: 'completed',
  221. })
  222. engine.settleRun(runId, { value: null, stopReason: 'completed', agentsStarted: 1 })
  223. expect((await pending).isError).toBe(false)
  224. expect(engine.disposed).toBe(1)
  225. expect(warnings).toHaveLength(1)
  226. expect(warnings[0]).toContain(failedType)
  227. const types = session.snapshotEvents().map(event => event.type)
  228. const expectedPrefixes = {
  229. 'tool-workflow/run-start': [],
  230. 'tool-workflow/agent-start': ['tool-workflow/run-start'],
  231. 'tool-workflow/agent-end': ['tool-workflow/run-start', 'tool-workflow/agent-start'],
  232. 'tool-workflow/run-end': [
  233. 'tool-workflow/run-start', 'tool-workflow/agent-start', 'tool-workflow/agent-end',
  234. ],
  235. } as const
  236. expect(types).toEqual(expectedPrefixes[failedType])
  237. })
  238. it('contains an append failure whose thrown value cannot be rendered', async () => {
  239. const { ctx, engine, parent, session } = await setup()
  240. const warnings: string[] = []
  241. ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn
  242. session.append = () => {
  243. throw { toString: () => { throw new Error('coercion trap') } }
  244. }
  245. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  246. await vi.waitFor(() => { expect(engine.requests).toHaveLength(1) })
  247. engine.settleRun(WorkflowRunId('run-1'), {
  248. value: null, stopReason: 'completed', agentsStarted: 0,
  249. })
  250. expect((await pending).isError).toBe(false)
  251. expect(warnings).toHaveLength(1)
  252. expect(warnings[0]).toContain('[unrenderable thrown value]')
  253. })
  254. it('maps a non-completed stop reason to an isError result (and still disposes)', async () => {
  255. const { ctx, engine, parent } = await setup()
  256. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  257. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  258. engine.settle({ value: null, stopReason: 'error', error: 'script threw: boom', agentsStarted: 2 })
  259. const result = await pending
  260. expect(result.isError).toBe(true)
  261. expect((result.content[0] as { text: string }).text).toContain('workflow run failed: script threw: boom')
  262. expect(engine.disposed).toBe(1)
  263. })
  264. it('reports a cancelled run distinctly (with and without a reason)', async () => {
  265. const { ctx, engine, parent } = await setup()
  266. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  267. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  268. engine.settle({ value: null, stopReason: 'cancelled', error: 'user', agentsStarted: 0 })
  269. const result = await pending
  270. expect(result.isError).toBe(true)
  271. expect((result.content[0] as { text: string }).text).toContain('workflow run was cancelled (user)')
  272. const bare = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  273. await vi.waitFor(() => { expect(engine.requests.length).toBe(2) })
  274. engine.settle({ value: null, stopReason: 'cancelled', agentsStarted: 0 })
  275. expect(((await bare).content[0] as { text: string }).text.trim().endsWith('cancelled')).toBe(true)
  276. })
  277. it('an error result without a message renders the unknown-error fallback', async () => {
  278. const { ctx, engine, parent } = await setup()
  279. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  280. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  281. engine.settle({ value: null, stopReason: 'error', agentsStarted: 0 })
  282. expect(((await pending).content[0] as { text: string }).text).toContain('unknown error')
  283. })
  284. it('cancels the run when exec.signal aborts MID-FLIGHT (the abort bridge)', async () => {
  285. const { ctx, engine, parent } = await setup()
  286. const controller = new AbortController()
  287. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent, signal: controller.signal })
  288. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  289. controller.abort()
  290. const result = await pending
  291. expect(result.isError).toBe(true)
  292. expect(engine.cancels).toContain('parent step aborted')
  293. expect(engine.disposed).toBe(1)
  294. })
  295. it('a synchronous engine start throw (meta/parse failure) becomes an isError result', async () => {
  296. const { ctx, engine, parent } = await setup()
  297. engine.startError = new Error('invalid meta: meta.name must be a non-empty string')
  298. const result = await execute(ctx, { script: 'nope', meta: { name: '', description: 'd' } }, { agent: parent })
  299. expect(result.isError).toBe(true)
  300. expect((result.content[0] as { text: string }).text).toContain('meta.name must be a non-empty string')
  301. })
  302. it('requires a calling agent (fails loud without exec.agent)', async () => {
  303. const { ctx, engine } = await setup()
  304. const result = await execute(ctx, { script: SCRIPT, meta: META })
  305. expect(result.isError).toBe(true)
  306. expect((result.content[0] as { text: string }).text).toContain('requires a calling agent')
  307. expect(engine.requests.length).toBe(0)
  308. })
  309. it('validates its own arguments via the schema DSL (missing script)', async () => {
  310. const { ctx, parent } = await setup()
  311. const result = await execute(ctx, {}, { agent: parent })
  312. expect(result.isError).toBe(true)
  313. expect(result.error?.info?.code).toBe('INVALID_ARGS')
  314. })
  315. it('skips workflow startup when exec.signal is already aborted', async () => {
  316. const { ctx, engine, parent } = await setup()
  317. const controller = new AbortController()
  318. controller.abort()
  319. const result = await execute(ctx, { script: SCRIPT, meta: META }, { agent: parent, signal: controller.signal })
  320. expect(result.isError).toBe(true)
  321. expect(result.error).toEqual({
  322. message: 'tool call aborted before dispatch',
  323. info: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  324. })
  325. expect(engine.requests).toHaveLength(0)
  326. expect(engine.cancels).toHaveLength(0)
  327. expect(engine.disposed).toBe(0)
  328. })
  329. it('truncates an oversized rendered value with a notice (maxResultChars)', async () => {
  330. const { ctx, engine, parent } = await setup({ maxResultChars: 40 })
  331. const pending = execute(ctx, { script: SCRIPT, meta: META }, { agent: parent })
  332. await vi.waitFor(() => { expect(engine.requests.length).toBe(1) })
  333. engine.settle({ value: { blob: 'x'.repeat(500) }, stopReason: 'completed', agentsStarted: 1 })
  334. const result = await pending
  335. if (result.isError) throw new Error('expected workflow success')
  336. expect(result.value).toEqual({ runId: 'run-1', agentsStarted: 1, result: { blob: 'x'.repeat(500) } })
  337. const rendered = (result.content[0] as { text: string }).text
  338. expect(rendered).toContain('[truncated:')
  339. expect(rendered.length).toBeLessThan(400)
  340. })
  341. it('registers under a configured toolName and unregisters on fiber dispose (HMR safety)', async () => {
  342. const ctx = new Context()
  343. await ctx.plugin(SystemPrompt)
  344. await ctx.plugin(ToolRuntime)
  345. await ctx.plugin(StubEngine)
  346. const fiber = await ctx.plugin(toolWorkflow, { toolName: 'orchestrate' })
  347. expect(ctx.tools.get('orchestrate')).toBeDefined()
  348. expect(ctx.tools.get('workflow')).toBeUndefined()
  349. // The usage-policy prompt section rides the same registration: present
  350. // under the CONFIGURED name (its guidance names the tool it describes)…
  351. const sections = (await ctx.systemPrompt.assemble()).sections
  352. const section = sections.find(s => s.name === 'tool:orchestrate')
  353. expect(section?.text).toContain('orchestrate')
  354. expect(sections.some(s => s.name === 'tool:workflow')).toBe(false)
  355. ctx.systemPrompt.section({ name: 'tool:cordis-order-probe', order: 115.5, text: 'Cordis' })
  356. expect((await ctx.systemPrompt.assemble()).sections
  357. .filter(s => s.name === 'tool:cordis-order-probe' || s.name === 'tool:orchestrate')
  358. .map(s => s.name)).toEqual(['tool:cordis-order-probe', 'tool:orchestrate'])
  359. await fiber.dispose()
  360. expect(ctx.tools.get('orchestrate')).toBeUndefined()
  361. // …and gone with the fiber — a reload must not leak a stale section.
  362. expect((await ctx.systemPrompt.assemble()).sections.some(s => s.name === 'tool:orchestrate')).toBe(false)
  363. })
  364. it('presents a generic pending card titled by the meta name, with the script as rawInput', async () => {
  365. const { ctx } = await setup()
  366. const tool = ctx.tools.get('workflow')!
  367. const view = tool.presentCall!({ script: SCRIPT, meta: META })
  368. expect(view).toMatchObject({ card: 'generic', title: 'workflow: audit', rawInput: SCRIPT })
  369. })
  370. it('presentResult keeps the generic card; presentation is pure and replay-safe on malformed args', async () => {
  371. const { ctx } = await setup()
  372. const tool = ctx.tools.get('workflow')!
  373. expect(tool.presentResult!({ script: SCRIPT, meta: META }, { content: [], isError: false })).toEqual({ card: 'generic' })
  374. // defineTool soft-validates presentation args: a malformed logged shape
  375. // (wrong fields entirely, or a call missing its meta) falls back to
  376. // undefined instead of throwing mid-replay.
  377. expect(tool.presentCall!({ not: 'the schema' })).toBeUndefined()
  378. expect(tool.presentCall!({ script: SCRIPT })).toBeUndefined()
  379. })
  380. it('has the namespace-plugin export shape (no stray default)', () => {
  381. expect('default' in toolWorkflow).toBe(false)
  382. expect(toolWorkflow.name).toBe('tool-workflow')
  383. expect(toolWorkflow.inject).toEqual(['tools', 'workflowEngine', 'systemPrompt'])
  384. const loader = Object.create(Loader.prototype) as Loader
  385. const unwrapped = loader.unwrapExports(toolWorkflow) as Record<string, unknown>
  386. expect(unwrapped).toBe(toolWorkflow)
  387. expect(typeof unwrapped.apply).toBe('function')
  388. })
  389. describe('composition with the REAL worker-thread engine (the mock above must stay honest)', () => {
  390. it('an abort releases the tool even when the script parks on a promise no hook owns', async () => {
  391. // The tool and loop await run.result before cleanup, so cancellation must settle a script
  392. // parked on an unowned promise. Exercise that guarantee through the real registry and worker.
  393. const ctx = new Context()
  394. await ctx.plugin(SystemPrompt)
  395. await ctx.plugin(ToolRuntime)
  396. await ctx.plugin(SessionProjectionRegistry)
  397. await ctx.plugin(SubagentRuntime)
  398. ctx.subagents.registerProvider({
  399. name: 'spawn',
  400. capabilities: { agentOptions: true, outputSchema: true, depthLimit: true, toolFilter: true, persona: true },
  401. inheritsParentContext: false,
  402. start: () => Promise.reject(new Error('the parked-script fixture must not start a child')),
  403. })
  404. await ctx.plugin(WorkerThreadWorkflowEngine, { disposeGraceMs: 30 })
  405. await ctx.plugin(toolWorkflow, {})
  406. const session = Session.create(SessionId('caller'))
  407. const parent = { id: session.id, options: {}, session } as unknown as Agent
  408. const controller = new AbortController()
  409. const pending = execute(ctx, {
  410. script: 'await new Promise(() => {})\nreturn 1',
  411. meta: { name: 'stuck', description: 'parks forever' },
  412. }, { agent: parent, signal: controller.signal })
  413. // Give the run a beat to start (past its synchronous slice), then abort.
  414. await new Promise(resolve => setTimeout(resolve, 20))
  415. controller.abort('user abort')
  416. const result = await pending
  417. expect(result.isError).toBe(true)
  418. expect((result.content[0] as { text: string }).text).toContain('cancelled')
  419. })
  420. })
  421. })