child-bash-lifecycle.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import { mkdtemp, rm } from 'node:fs/promises';
  2. import { tmpdir } from 'node:os';
  3. import { join } from 'node:path';
  4. import { afterEach, describe, expect, it, vi } from 'vitest';
  5. import { LocalBashTool } from '@mavis/agent-tools/desktop';
  6. import { createLocalBashOperations, getShellConfig } from '@earendil-works/pi-coding-agent';
  7. import { createChildBashLifecycle } from '../../src/background-task/child-bash-lifecycle.js';
  8. import { LocalBackgroundTaskService } from '../../src/background-task/service.js';
  9. import {
  10. FsLocalTaskOutputStore,
  11. SqliteLocalBackgroundTaskStore,
  12. } from '../../src/background-task/store.js';
  13. import {
  14. buildLocalBashAdapter,
  15. abortBackgroundLocalBashTasksForHost,
  16. stopBackgroundLocalBashTask,
  17. } from '../../src/background-task/bash-runner.js';
  18. import { closeLocalBackgroundTaskDelivery } from '../../src/background-task/delivery.js';
  19. import { createLocalBackgroundBashExecutor } from '../../../local-runtime-v2/src/service/background-bash/executor.js';
  20. import { closeLocalRuntimeDb } from '../../src/persistence/db.js';
  21. import {
  22. backgroundBashHost,
  23. parentSessionRecord,
  24. taskRecord,
  25. toolContext,
  26. } from './background-task-test-helpers.js';
  27. function nodeCommand(script: string): string {
  28. const shell = getShellConfig().type;
  29. const powershell = shell === 'pwsh' || shell === 'powershell';
  30. const quote = (value: string) => powershell
  31. ? `'${value.replaceAll("'", "''")}'`
  32. : `'${value.replaceAll("'", "'\\''")}'`;
  33. return `${powershell ? '& ' : ''}${quote(process.execPath)} -e ${quote(script)}`;
  34. }
  35. const directories: string[] = [];
  36. const shutdowns: Array<() => Promise<void>> = [];
  37. // Windows CI has exceeded the 10s teardown budget for these SQLite/output fixtures.
  38. // Keep the execution deadlines below separate from this bounded teardown budget.
  39. afterEach(async () => {
  40. // A terminal task can still be finalizing output or scheduling delivery.
  41. // Drain that work before closing SQLite, otherwise it can reopen the file
  42. // while Windows is trying to remove the fixture directory.
  43. for (const shutdown of shutdowns.splice(0)) await shutdown();
  44. for (const path of directories.splice(0)) {
  45. closeLocalRuntimeDb(path);
  46. await rm(path, { recursive: true, force: true });
  47. }
  48. }, process.platform === 'win32' ? 30_000 : 10_000);
  49. async function fixture() {
  50. const dataDir = await mkdtemp(join(tmpdir(), 'child-bash-lifecycle-'));
  51. directories.push(dataDir);
  52. const service = new LocalBackgroundTaskService({
  53. store: new SqliteLocalBackgroundTaskStore(dataDir),
  54. outputStore: new FsLocalTaskOutputStore(dataDir),
  55. stopRuntime: (task, reason) => stopBackgroundLocalBashTask(task, reason),
  56. });
  57. const host = backgroundBashHost(service, dataDir);
  58. shutdowns.push(async () => {
  59. closeLocalBackgroundTaskDelivery(host);
  60. await abortBackgroundLocalBashTasksForHost(host, 'Test fixture shutdown');
  61. });
  62. const controller = new AbortController();
  63. const lifecycle = createChildBashLifecycle(service, {
  64. sessionId: 'child',
  65. turnId: 'turn-child',
  66. signal: controller.signal,
  67. });
  68. const create = (id: string, overrides: Parameters<typeof taskRecord>[2] = {}) =>
  69. service.create(
  70. taskRecord(id, 'child', {
  71. kind: 'bash',
  72. status: 'running',
  73. metadata: { parentTurnId: 'turn-child' },
  74. ...overrides,
  75. }),
  76. );
  77. return { dataDir, service, host, controller, lifecycle, create };
  78. }
  79. const poll = { wait: false, readTaskIds: new Set<string>() };
  80. describe('child Bash lifecycle', () => {
  81. it.each(['succeeded', 'failed', 'canceled', 'lost'] as const)(
  82. 'notifies %s exactly once without acknowledging consumption',
  83. async (status) => {
  84. const { create, lifecycle, service } = await fixture();
  85. await create('bash', { status });
  86. expect(await lifecycle.poll(poll)).toContain(`status="${status}"`);
  87. expect(await lifecycle.poll(poll)).toBeUndefined();
  88. expect((await service.get('bash'))?.deliveredAt).toBeUndefined();
  89. },
  90. );
  91. it('waits at exit, wakes on terminal state, and does not wait mid-turn', async () => {
  92. const { create, lifecycle, service } = await fixture();
  93. expect(await lifecycle.hasPending()).toBe(false);
  94. await create('bash');
  95. expect(await lifecycle.hasPending()).toBe(true);
  96. expect(await lifecycle.poll(poll)).toBeUndefined();
  97. const complete = vi.fn();
  98. const waiting = vi.spyOn(service, 'waitForTaskChange');
  99. const pending = lifecycle.poll({ ...poll, wait: true }).then(complete);
  100. await vi.waitFor(() => expect(waiting).toHaveBeenCalled());
  101. expect(complete).not.toHaveBeenCalled();
  102. await service.patch('bash', { status: 'succeeded' });
  103. await pending;
  104. expect(complete).toHaveBeenCalledWith(expect.stringContaining('task_id="bash"'));
  105. });
  106. it('isolates session and turn, ignores synchronous/consumed results, and pages all tasks', async () => {
  107. const { create, lifecycle, service } = await fixture();
  108. await create('other-session', { ownerSessionId: 'other' });
  109. await create('old-turn', { metadata: { parentTurnId: 'old-turn' } });
  110. await create('read', { status: 'succeeded' });
  111. await create('delivered', { status: 'succeeded', deliveredAt: 1 });
  112. for (let i = 0; i < 105; i++) await create(`done-${i}`, { status: 'succeeded' });
  113. const notice = await lifecycle.poll({ wait: true, readTaskIds: new Set(['read']) });
  114. expect(notice?.match(/<task /g)).toHaveLength(105);
  115. expect(notice).not.toContain('task_id="read"');
  116. await lifecycle.close();
  117. expect((await service.get('other-session'))?.status).toBe('running');
  118. expect((await service.get('old-turn'))?.status).toBe('running');
  119. });
  120. it('cancels a waiting child and stops only its unfinished Bash', async () => {
  121. const { create, lifecycle, service, controller } = await fixture();
  122. await create('bash');
  123. await create('other', { ownerSessionId: 'other' });
  124. const waiting = lifecycle.poll({ ...poll, wait: true });
  125. const rejected = expect(waiting).rejects.toThrow('cancel child');
  126. controller.abort(new Error('cancel child'));
  127. await rejected;
  128. await lifecycle.close();
  129. expect((await service.get('bash'))?.status).toBe('canceled');
  130. expect((await service.get('other'))?.status).toBe('running');
  131. });
  132. it('observes a completion that raced waiter registration', async () => {
  133. const { create, service, controller } = await fixture();
  134. await create('bash', { status: 'succeeded' });
  135. await service.waitForTaskChange('child', ['bash'], controller.signal);
  136. });
  137. it.each(['explicit', 'promoted'] as const)(
  138. 'returns real shell output through the %s background path',
  139. async (mode) => {
  140. const { dataDir, host, lifecycle, service, controller } = await fixture();
  141. const session = {
  142. ...parentSessionRecord(dataDir),
  143. sessionId: 'child',
  144. sessionType: 'branch' as const,
  145. sessionKind: 'task',
  146. parentSessionId: 'parent',
  147. visibility: 'visible' as const,
  148. };
  149. const executor = createLocalBackgroundBashExecutor(
  150. { create: () => createLocalBashOperations({ parentDeathGuard: false }) },
  151. { mode: 'off' },
  152. );
  153. const adapter = buildLocalBashAdapter(host, session, executor);
  154. const command = nodeCommand("setTimeout(() => { console.log('child-bash-ok'); }, 80)");
  155. const started =
  156. mode === 'explicit'
  157. ? await adapter.startBackground(
  158. toolContext('child'),
  159. { command, run_in_background: true },
  160. controller.signal,
  161. )
  162. : await adapter.runManagedForeground!(
  163. toolContext('child'),
  164. { command },
  165. 1,
  166. controller.signal,
  167. );
  168. expect(started.status).toBe(mode === 'explicit' ? 'started' : 'auto_promoted');
  169. const taskId = started.taskId!;
  170. try {
  171. expect(await lifecycle.poll({ ...poll, wait: true })).toContain(taskId);
  172. const task = await service.get(taskId);
  173. expect(task).toMatchObject({
  174. status: 'succeeded',
  175. ownerSessionId: 'child',
  176. metadata: { parentTurnId: 'turn-child' },
  177. });
  178. const output = await service.readOutput(toolContext('child'), taskId, { offset: 0 });
  179. expect(output.content).toContain('child-bash-ok');
  180. expect(await service.get(toolContext('other'), taskId)).toBeUndefined();
  181. expect((await service.readOutput(toolContext('other'), taskId)).content).toBe('');
  182. expect(await service.stop(toolContext('other'), taskId)).toBeUndefined();
  183. } finally {
  184. await lifecycle.close();
  185. }
  186. },
  187. );
  188. });
  189. describe('real child Bash boundaries', () => {
  190. it('uses the actual 15 second LocalBashTool soft yield and then recovers output', async () => {
  191. const { dataDir, host, lifecycle, service, controller } = await fixture();
  192. const session = {
  193. ...parentSessionRecord(dataDir),
  194. sessionId: 'child',
  195. sessionKind: 'task',
  196. parentSessionId: 'parent',
  197. };
  198. const executor = createLocalBackgroundBashExecutor(
  199. { create: () => createLocalBashOperations({ parentDeathGuard: false }) },
  200. { mode: 'off' },
  201. );
  202. const tool = new LocalBashTool(dataDir, buildLocalBashAdapter(host, session, executor), {
  203. mode: 'off',
  204. });
  205. const startedAt = Date.now();
  206. try {
  207. const receipt = await tool.execute(
  208. toolContext('child'),
  209. {
  210. command: nodeCommand("setTimeout(() => console.log('after-real-soft-yield'), 16500)"),
  211. },
  212. controller.signal,
  213. );
  214. expect(receipt.details).toMatchObject({ status: 'auto_promoted' });
  215. expect(Date.now() - startedAt).toBeGreaterThanOrEqual(15000);
  216. const taskId = String(receipt.details?.task_id);
  217. expect(await lifecycle.poll({ ...poll, wait: true })).toContain(taskId);
  218. expect((await service.readOutput(toolContext('child'), taskId)).content).toContain(
  219. 'after-real-soft-yield',
  220. );
  221. } finally {
  222. await lifecycle.close();
  223. }
  224. }, 30000);
  225. it.each(['failure', 'timeout', 'cancel'] as const)(
  226. 'preserves real shell %s and cleans up the process',
  227. async (mode) => {
  228. const { dataDir, host, lifecycle, service, controller } = await fixture();
  229. const session = {
  230. ...parentSessionRecord(dataDir),
  231. sessionId: 'child',
  232. sessionKind: 'task',
  233. parentSessionId: 'parent',
  234. };
  235. const executor = createLocalBackgroundBashExecutor(
  236. { create: () => createLocalBashOperations({ parentDeathGuard: false }) },
  237. { mode: 'off' },
  238. );
  239. const adapter = buildLocalBashAdapter(host, session, executor);
  240. const script =
  241. mode === 'failure'
  242. ? "console.error('failure-evidence');process.exit(7)"
  243. : "setTimeout(() => console.log('too-late'), 10000)";
  244. const receipt = await adapter.startBackground(
  245. toolContext('child'),
  246. {
  247. command: nodeCommand(script),
  248. ...(mode === 'timeout' ? { timeout: 1 } : {}),
  249. },
  250. controller.signal,
  251. );
  252. const taskId = receipt.taskId!;
  253. try {
  254. if (mode === 'cancel') {
  255. controller.abort(new Error('parent canceled'));
  256. await lifecycle.close();
  257. expect((await service.get(taskId))?.status).toBe('canceled');
  258. } else {
  259. expect(await lifecycle.poll({ ...poll, wait: true })).toContain(taskId);
  260. expect((await service.get(taskId))?.status).toBe('failed');
  261. const output = await service.readOutput(taskId);
  262. expect(output.content).toContain(mode === 'failure' ? 'failure-evidence' : 'timed out');
  263. }
  264. } finally {
  265. await lifecycle.close();
  266. }
  267. },
  268. 15000,
  269. );
  270. });
  271. describe('child Bash steering interruption', () => {
  272. it.each(['before-wait', 'during-wait'] as const)(
  273. 'yields to steering %s without canceling Bash or consuming its result',
  274. async (arrival) => {
  275. const { create, lifecycle, service, controller } = await fixture();
  276. await create('bash');
  277. const steering = new AbortController();
  278. const waiting = vi.spyOn(service, 'waitForTaskChange');
  279. if (arrival === 'before-wait') steering.abort();
  280. const pending = lifecycle.poll({ ...poll, wait: true, steeringSignal: steering.signal });
  281. if (arrival === 'during-wait') {
  282. await vi.waitFor(() => expect(waiting).toHaveBeenCalled());
  283. steering.abort();
  284. }
  285. await expect(pending).resolves.toBeUndefined();
  286. expect(controller.signal.aborted).toBe(false);
  287. expect((await service.get('bash'))?.status).toBe('running');
  288. await service.stop('bash', 'parent requested stop');
  289. expect(await lifecycle.hasPending()).toBe(false);
  290. expect(await lifecycle.poll(poll)).toContain('status="canceled"');
  291. expect(await lifecycle.poll(poll)).toBeUndefined();
  292. },
  293. );
  294. });