Skip to content

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

2.2 KB
Raw Blame
import type { BackgroundCommandService } from "@vetta/runtime-node/coding";
import { describe, expect, it, vi } from "vitest";
import {
	CodingAgentBackgroundWorkController,
	type CodingAgentSubagentWorkRuntime,
} from "../../src/execution/background/work-controller.js";

describe("Coding Agent background work controller", () => {
	it("separates subagent cleanup from the combined background cleanup", () => {
		const clearBackground = vi.fn(() => 3);
		const clearSubagents = vi.fn(() => 2);
		const controller = new CodingAgentBackgroundWorkController(
			backgroundService(clearBackground),
			subagentRuntime(clearSubagents),
		);

		expect(controller.clearFinishedSubagents()).toBe(2);
		expect(clearBackground).not.toHaveBeenCalled();
		expect(controller.clearFinished()).toBe(5);
		expect(clearBackground).toHaveBeenCalledOnce();
		expect(clearSubagents).toHaveBeenCalledTimes(2);
	});

	it("stops every live subagent and running command on an unconditional stop", () => {
		const stop = vi.fn(() => true);
		const interruptAll = vi.fn(() => [{ id: "child-a" }, { id: "child-b" }] as never);
		const service = backgroundService(() => 0);
		const controller = new CodingAgentBackgroundWorkController(
			{
				...service,
				list: () => [
					{ id: "running", status: "running" },
					// A settled command must not be killed again.
					{ id: "done", status: "completed" },
				],
				stop,
			} as unknown as BackgroundCommandService,
			{ ...subagentRuntime(() => 0), interruptAll },
		);

		expect(controller.stopAllWork()).toBe(3);
		expect(interruptAll).toHaveBeenCalledOnce();
		expect(stop.mock.calls).toEqual([["running", "caller"]]);
	});
});

function backgroundService(clearFinished: () => number): BackgroundCommandService {
	return {
		spawn: () => {
			throw new Error("Not used");
		},
		subscribe: () => () => {},
		subscribeNotifications: () => () => {},
		wait: async () => {
			throw new Error("Not used");
		},
		get: () => undefined,
		list: () => [],
		clearFinished,
		readOutput: () => "",
		stop: () => false,
		dispose() {},
		async shutdown() {},
	};
}

function subagentRuntime(clearFinished: () => number): CodingAgentSubagentWorkRuntime {
	return {
		clearFinished,
		list: () => [],
		interrupt: () => undefined,
		interruptAll: () => [],
	};
}