Skip to content

Open-source, local-first AI agent for real work.

8.8 KB
Raw Blame
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
	isProcessGroupAlive,
	parseProcessElapsedTime,
	parseProcessGroupStartTimes,
} from "../../src/coding/host/detached-process-group.js";
import {
	createNodeBackgroundCommandHost,
	createNodeDetachedProcessRegistry,
	createNodeForegroundCommandHost,
} from "../../src/coding/host/index.js";
import { createBackgroundCommandToolExecutor, createBashToolRegistration } from "../../src/coding/index.js";
import { appendDetachedProcessNote } from "../../src/coding/shared/background-command-executor.js";
import type { DetachedProcessRegistry } from "../../src/coding/shared/background-command-host.js";
import { createBackgroundCommandService } from "../../src/coding/shared/background-command-lifecycle.js";
import type {
	BackgroundCommandService,
	BackgroundCommandSnapshot,
} from "../../src/coding/shared/background-command-service.js";

const posix = process.platform !== "win32";
const shell = () => ({ executable: "/bin/sh", args: ["-c"] });
const FAST = { detachedGraceMs: 150, detachedPollMs: 50 } as const;

const services: BackgroundCommandService[] = [];
const groups: number[] = [];
const directories: string[] = [];

afterEach(async () => {
	for (const service of services.splice(0)) await service.shutdown();
	for (const group of groups.splice(0)) {
		try {
			process.kill(-group, "SIGKILL");
		} catch {
			// Already gone.
		}
	}
	for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true });
});

function createService(registry?: DetachedProcessRegistry): BackgroundCommandService {
	const service = createBackgroundCommandService(
		createNodeBackgroundCommandHost({ resolveShell: shell, detachedProcessRegistry: registry, ...FAST }),
	);
	services.push(service);
	return service;
}

function createRegistry(sessionId = "session-a") {
	const directory = mkdtempSync(join(tmpdir(), "vetta-detached-"));
	directories.push(directory);
	const filePath = join(directory, "detached-processes.v1.json");
	return { filePath, registry: createNodeDetachedProcessRegistry({ filePath, sessionId }) };
}

/** Runs a command the way the bash tool does (spawn, then wait for the shell). */
async function runForeground(service: BackgroundCommandService, command: string): Promise<BackgroundCommandSnapshot> {
	const task = service.spawn({ command, cwd: process.cwd(), env: { ...process.env } });
	const result = await service.wait(task.id, { maxMs: 10_000 });
	expect(result.stillRunning).toBe(false);
	return result.snapshot;
}

function adopted(service: BackgroundCommandService, origin: BackgroundCommandSnapshot): BackgroundCommandSnapshot {
	const task = origin.detachedTaskId ? service.get(origin.detachedTaskId) : undefined;
	if (!task) throw new Error(`No detached task adopted from ${origin.id}`);
	if (task.processGroupId) groups.push(task.processGroupId);
	return task;
}

async function until(predicate: () => boolean, timeoutMs = 5_000): Promise<void> {
	const deadline = Date.now() + timeoutMs;
	while (!predicate()) {
		if (Date.now() > deadline) throw new Error("Timed out waiting for condition");
		await new Promise((resolve) => setTimeout(resolve, 25));
	}
}

describe.runIf(posix)("processes a command leaves running", () => {
	it("adopts a `cmd &` daemon as a running background task the user can stop", async () => {
		const service = createService();
		const origin = await runForeground(service, "sleep 30 > /dev/null 2>&1 & echo started");

		expect(origin).toMatchObject({ status: "completed", exitCode: 0, tail: "started\n" });
		const daemon = adopted(service, origin);
		expect(daemon).toMatchObject({
			kind: "detached-process",
			status: "running",
			command: "sleep 30 > /dev/null 2>&1 & echo started",
		});
		expect(isProcessGroupAlive(daemon.processGroupId ?? 0)).toBe(true);

		expect(service.stop(daemon.id, "caller")).toBe(true);
		await until(() => service.get(daemon.id)?.status !== "running");

		expect(service.get(daemon.id)).toMatchObject({ status: "killed", endedBy: "caller" });
		expect(isProcessGroupAlive(daemon.processGroupId ?? 0)).toBe(false);
	});

	it("keeps collecting what the daemon prints and reports when it exits on its own", async () => {
		const service = createService();
		const ended: BackgroundCommandSnapshot[] = [];
		service.subscribeNotifications((task) => ended.push(task));

		const origin = await runForeground(service, "(sleep 0.4; echo from-daemon) & echo from-shell");
		const daemon = adopted(service, origin);
		await until(() => service.get(daemon.id)?.status === "completed");

		expect(service.get(daemon.id)?.tail).toContain("from-daemon");
		expect(service.readOutput(daemon.id, { fromStart: true, advanceCursor: false })).toContain("from-daemon");
		expect(ended.map((task) => task.id)).toContain(daemon.id);
	});

	it("tells the model through the bash tool result that the process it backgrounded is now a task", async () => {
		const backgroundService = createService();
		const foreground = createNodeForegroundCommandHost({ resolveShell: shell });
		const executor = createBackgroundCommandToolExecutor({
			...foreground,
			foregroundExecutor: { execute: () => Promise.reject(new Error("unused")) },
			backgroundService,
		});
		const { tool } = createBashToolRegistration(process.cwd(), { executor });

		const result = await tool.execute({
			sessionId: "session-1",
			turnId: "turn-1",
			toolCallId: "tool-call-1",
			input: { command: "sleep 30 > /dev/null 2>&1 &" },
			signal: new AbortController().signal,
		});

		const daemon = backgroundService.list().find((task) => task.kind === "detached-process");
		if (daemon?.processGroupId) groups.push(daemon.processGroupId);
		expect(daemon).toMatchObject({ status: "running", toolCallId: "tool-call-1" });
		expect(result.content[0]).toMatchObject({
			text: expect.stringContaining(`tracked as background task ${daemon?.id}`),
		});
	});

	it("does not adopt children that exit right after the shell", async () => {
		const service = createService();
		const origin = await runForeground(service, "(sleep 0.05) & echo done");

		expect(origin.detachedTaskId).toBeUndefined();
		expect(service.list()).toHaveLength(1);
	});

	it("leaves adopted processes running when the session ends and shows them again in the next one", async () => {
		const { filePath, registry } = createRegistry();
		const first = createService(registry);
		const daemon = adopted(first, await runForeground(first, "nohup sleep 30 > /dev/null 2>&1 &"));
		const processGroupId = daemon.processGroupId ?? 0;

		await first.shutdown();
		expect(isProcessGroupAlive(processGroupId)).toBe(true);
		expect(JSON.parse(readFileSync(filePath, "utf8")).entries).toMatchObject([
			{ sessionId: "session-a", processGroupId, command: "nohup sleep 30 > /dev/null 2>&1 &" },
		]);

		const otherSession = createService(createNodeDetachedProcessRegistry({ filePath, sessionId: "session-b" }));
		const second = createService(registry);
		await until(() => second.list().length === 1);

		expect(otherSession.list()).toEqual([]);
		const resumed = second.list()[0];
		expect(resumed).toMatchObject({ kind: "detached-process", status: "running", processGroupId });

		second.stop(resumed?.id ?? "", "caller");
		await until(() => second.get(resumed?.id ?? "")?.status === "killed");
		expect(isProcessGroupAlive(processGroupId)).toBe(false);
		expect(registry.list()).toEqual([]);
	});

	it("forgets recorded groups that ended while the host was away", async () => {
		const { registry } = createRegistry();
		registry.record({
			processGroupId: 2_147_483_000,
			adoptedAt: Date.now(),
			command: "gone",
			cwd: process.cwd(),
			outputFile: "/nonexistent",
		});

		const service = createService(registry);
		await until(() => registry.list().length === 0);
		expect(service.list()).toEqual([]);
	});
});

describe("detached process helpers", () => {
	it("parses ps elapsed times", () => {
		expect(parseProcessElapsedTime("00:05")).toBe(5_000);
		expect(parseProcessElapsedTime("01:02:03")).toBe(3_723_000);
		expect(parseProcessElapsedTime("2-00:00:01")).toBe(172_801_000);
		expect(parseProcessElapsedTime("bogus")).toBeUndefined();
	});

	it("reads start times of one process group only", () => {
		const output = "  100   00:10\n  200   00:20\n  100 01:00\n";
		expect(parseProcessGroupStartTimes(output, 100, 100_000)).toEqual([90_000, 40_000]);
	});

	it("tells the model which task now tracks the leftover processes", () => {
		const base: BackgroundCommandSnapshot = {
			id: "b1",
			command: "sleep 30 &",
			cwd: "/",
			status: "completed",
			outputFile: "/tmp/x",
			exitCode: 0,
			startedAt: 0,
			tail: "",
		};
		expect(appendDetachedProcessNote("out", base)).toBe("out");
		expect(appendDetachedProcessNote("out", { ...base, detachedTaskId: "b2" })).toContain("background task b2");
	});
});