child-bash-lifecycle.test.ts 12 KB

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