Skip to content

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

13.3 KB
Raw Blame
import { describe, expect, it, vi } from "vitest";
import {
	CatalogRoutedRuntimeHostSessionBackend,
	RuntimeHost,
	type RuntimeHostSessionAssembly,
	type RuntimeHostSessionBackend,
	type RuntimeSessionCatalog,
	type RuntimeSessionCreateRequest,
} from "../../src/index.js";
import type { SessionContextRecord } from "../../src/kernel/index.js";

describe("CatalogRoutedRuntimeHostSessionBackend", () => {
	it("coalesces concurrent creation requests for the same persisted Session path", async () => {
		const entered = deferred();
		const proceed = deferred();
		const createAssembly = vi.fn(async (request: RuntimeSessionCreateRequest) => {
			entered.resolve();
			await proceed.promise;
			const created = assembly("session-shared");
			return {
				...created,
				lifecycle: { ...created.lifecycle, sessionPath: request.sessionPath },
			};
		});
		const sessionBackend: RuntimeHostSessionBackend = { createAssembly };
		const runtime = new RuntimeHost({ sessionBackend });
		const config = { sessionPath: "C:/sessions/shared.conversation.jsonl" };

		const first = runtime.createSession(config);
		await entered.promise;
		const second = runtime.createSession(config);

		expect(createAssembly).toHaveBeenCalledOnce();
		proceed.resolve();
		expect(await Promise.all([first, second])).toEqual([
			{ sessionId: "session-shared" },
			{ sessionId: "session-shared" },
		]);

		await runtime.close();
	});

	describe("when a persisted path resolves to another open Session file", () => {
		const legacyPath = "C:/sessions/2026-01-01_legacy.jsonl";
		const importedPath = "C:/sessions/legacy-import-a.conversation.jsonl";

		// 生产 Backend 对同一 Session id 只允许一个活动组合;第二次组合会直接失败。
		// 假 Backend 记下当前打开的组合(Session id → 文件),关闭时移除。
		function importingRuntime() {
			const openAssemblies = new Map<string, string | undefined>();
			const createAssembly = async (request: RuntimeSessionCreateRequest) => {
				if (request.sessionPath !== importedPath) throw new Error(`unexpected path: ${request.sessionPath}`);
				if (openAssemblies.has("legacy-import-a")) {
					throw new Error("Coding Agent image configuration scope is already registered: legacy-import-a");
				}
				openAssemblies.set("legacy-import-a", request.sessionPath);
				const created = assembly("legacy-import-a");
				return {
					...created,
					lifecycle: {
						...created.lifecycle,
						sessionPath: importedPath,
						dispose: async () => {
							openAssemblies.delete("legacy-import-a");
						},
					},
				};
			};
			const resolvedPaths: string[] = [];
			const resolveSessionPath = async ({ sessionPath }: { sessionPath: string }) => {
				resolvedPaths.push(sessionPath);
				return sessionPath === legacyPath ? importedPath : sessionPath;
			};
			const runtime = new RuntimeHost({ sessionBackend: { createAssembly }, resolveSessionPath });
			return { runtime, openAssemblies, resolvedPaths };
		}

		it("reuses the Session already open from the imported file", async () => {
			const { runtime, openAssemblies } = importingRuntime();

			await expect(runtime.createSession({ sessionPath: importedPath })).resolves.toEqual({
				sessionId: "legacy-import-a",
			});
			await expect(runtime.createSession({ sessionPath: legacyPath })).resolves.toEqual({
				sessionId: "legacy-import-a",
			});

			expect(openAssemblies).toEqual(new Map([["legacy-import-a", importedPath]]));
			await runtime.close();
			expect(openAssemblies.size).toBe(0);
		});

		it("reuses the Session when the same historical path is reopened", async () => {
			const { runtime, openAssemblies } = importingRuntime();

			await runtime.createSession({ sessionPath: legacyPath });
			await expect(runtime.createSession({ sessionPath: legacyPath })).resolves.toEqual({
				sessionId: "legacy-import-a",
			});

			// 唯一打开的组合落在导入后的文件上,而不是历史路径。
			expect(openAssemblies).toEqual(new Map([["legacy-import-a", importedPath]]));
			expect(runtime.getSessionView("legacy-import-a").sessionPath).toBe(importedPath);
			await runtime.close();
			expect(openAssemblies.size).toBe(0);
		});

		it("coalesces concurrent opens of the historical and imported paths", async () => {
			const { runtime, openAssemblies, resolvedPaths } = importingRuntime();

			const results = await Promise.all([
				runtime.createSession({ sessionPath: legacyPath }),
				runtime.createSession({ sessionPath: importedPath }),
				runtime.createSession({ sessionPath: legacyPath }),
			]);

			expect(results).toEqual([
				{ sessionId: "legacy-import-a" },
				{ sessionId: "legacy-import-a" },
				{ sessionId: "legacy-import-a" },
			]);
			expect(openAssemblies).toEqual(new Map([["legacy-import-a", importedPath]]));
			// 同一路径的并发请求只解析一次,迁移不会被并发触发。
			expect(resolvedPaths.filter((path) => path === legacyPath)).toHaveLength(1);
			await runtime.close();
			expect(openAssemblies.size).toBe(0);
		});
	});

	it("exposes a session-scoped view without creating a second lifecycle owner", async () => {
		const dispose = vi.fn(async () => {});
		const retry = vi.fn(async () => {});
		const sessionBackend: RuntimeHostSessionBackend = {
			createAssembly: async () => ({
				...assembly("session-view"),
				lifecycle: { sessionId: "session-view", sessionPath: "C:/sessions/view.jsonl", dispose },
				corePorts: {
					...assembly("session-view").corePorts,
					turnControl: {
						...assembly("session-view").corePorts.turnControl,
						retry,
					},
				},
			}),
		};
		const runtime = new RuntimeHost({ sessionBackend });
		const { sessionId } = await runtime.createSession();
		const session = runtime.getSessionView(sessionId);

		expect(session.sessionId).toBe("session-view");
		expect(session.sessionPath).toBe("C:/sessions/view.jsonl");
		expect(session.readState().isStreaming).toBe(false);
		await session.retry();
		expect(retry).toHaveBeenCalledOnce();

		await session.dispose();
		expect(dispose).toHaveBeenCalledOnce();
		expect(() => session.readState()).toThrow("Session not found");
	});

	it("forwards waiting prompt admission with its context and cancellation owner", async () => {
		const promptWhenAvailable = vi.fn(async () => ({ status: "completed" as const, turnId: "turn-1" }));
		const base = assembly("session-waiting-prompt");
		const sessionBackend: RuntimeHostSessionBackend = {
			createAssembly: async () => ({
				...base,
				corePorts: {
					...base.corePorts,
					turnControl: { ...base.corePorts.turnControl, promptWhenAvailable },
				},
			}),
		};
		const runtime = new RuntimeHost({ sessionBackend });
		const { sessionId } = await runtime.createSession();
		const controller = new AbortController();
		const context: readonly SessionContextRecord[] = [
			{
				type: "test.context",
				content: [{ type: "text", text: "attached" }],
				modelVisible: false,
			},
		];

		await expect(
			runtime.promptWhenAvailable(sessionId, { text: "continue", context }, controller.signal),
		).resolves.toEqual({ status: "completed", turnId: "turn-1" });
		expect(promptWhenAvailable).toHaveBeenCalledWith(
			{
				text: "continue",
				context,
				images: undefined,
				streamingBehavior: undefined,
				promptRef: undefined,
				attachments: undefined,
				modelKey: undefined,
				reasoning: undefined,
				metadata: undefined,
			},
			controller.signal,
		);
		await runtime.close();
	});

	it("forwards the caller's message id so the durable user message keeps the optimistic identity", async () => {
		const prompt = vi.fn(async () => ({ status: "queued" as const, pendingCount: 1, queueItemId: "q-1" }));
		const promptWhenAvailable = vi.fn(async () => ({ status: "completed" as const, turnId: "turn-1" }));
		const base = assembly("session-message-id");
		const sessionBackend: RuntimeHostSessionBackend = {
			createAssembly: async () => ({
				...base,
				corePorts: {
					...base.corePorts,
					turnControl: { ...base.corePorts.turnControl, prompt, promptWhenAvailable },
				},
			}),
		};
		const runtime = new RuntimeHost({ sessionBackend });
		const { sessionId } = await runtime.createSession();

		await runtime.prompt(sessionId, { text: "queued", messageId: "user-7", streamingBehavior: "followUp" });
		await runtime.promptWhenAvailable(sessionId, { text: "waiting", messageId: "user-8" });

		expect(prompt).toHaveBeenCalledWith(expect.objectContaining({ messageId: "user-7" }));
		expect(promptWhenAvailable).toHaveBeenCalledWith(expect.objectContaining({ messageId: "user-8" }), undefined);
		await runtime.close();
	});

	it("uses the explicit default backend only for new sessions", async () => {
		const defaultBackend = backend("default");
		const legacyBackend = backend("legacy");
		const greenfieldBackend = backend("greenfield");
		const onRoute = vi.fn();
		const routed = new CatalogRoutedRuntimeHostSessionBackend({
			defaultBackend,
			defaultRouteId: "greenfield",
			routes: [
				{ id: "legacy", catalog: catalog((path) => path.endsWith(".jsonl")), backend: legacyBackend },
				{
					id: "greenfield",
					catalog: catalog((path) => path.endsWith(".conversation.jsonl")),
					backend: greenfieldBackend,
				},
			],
			onRoute,
		});

		await routed.createAssembly(request());

		expect(defaultBackend.createAssembly).toHaveBeenCalledOnce();
		expect(legacyBackend.createAssembly).not.toHaveBeenCalled();
		expect(greenfieldBackend.createAssembly).not.toHaveBeenCalled();
		expect(onRoute).toHaveBeenCalledWith({ routeId: "greenfield", source: "default" });
	});

	it("routes an existing path to the first catalog that owns its format", async () => {
		const defaultBackend = backend("default");
		const legacyBackend = backend("legacy");
		const greenfieldBackend = backend("greenfield");
		const onRoute = vi.fn();
		const routed = new CatalogRoutedRuntimeHostSessionBackend({
			defaultBackend,
			routes: [
				{ id: "legacy", catalog: catalog((path) => path.endsWith(".legacy.jsonl")), backend: legacyBackend },
				{
					id: "greenfield",
					catalog: catalog((path) => path.endsWith(".conversation.jsonl")),
					backend: greenfieldBackend,
				},
			],
			onRoute,
		});
		const input = request("C:/sessions/example.conversation.jsonl");

		await routed.createAssembly(input);

		expect(greenfieldBackend.createAssembly).toHaveBeenCalledWith(input);
		expect(defaultBackend.createAssembly).not.toHaveBeenCalled();
		expect(legacyBackend.createAssembly).not.toHaveBeenCalled();
		expect(onRoute).toHaveBeenCalledWith({ routeId: "greenfield", source: "catalog" });
	});

	it("rejects unknown persisted formats instead of falling back", async () => {
		const defaultBackend = backend("default");
		const onRoute = vi.fn();
		const routed = new CatalogRoutedRuntimeHostSessionBackend({
			defaultBackend,
			routes: [{ catalog: catalog(() => false), backend: backend("known") }],
			onRoute,
		});

		await expect(routed.createAssembly(request("C:/sessions/unknown.data"))).rejects.toThrow(
			"No RuntimeHost session backend owns",
		);
		expect(defaultBackend.createAssembly).not.toHaveBeenCalled();
		expect(onRoute).not.toHaveBeenCalled();
	});
});

function backend(sessionId: string): RuntimeHostSessionBackend & {
	readonly createAssembly: ReturnType<typeof vi.fn>;
} {
	return {
		createAssembly: vi.fn(async () => assembly(sessionId)),
	};
}

function catalog(owns: (path: string) => boolean): RuntimeSessionCatalog {
	return {
		ownsSession: async (path) => owns(path),
		listProjects: async () => [],
		listSessions: async () => [],
		renameSession: async () => {},
		deleteSessionArtifacts: async () => {},
	};
}

function request(sessionPath?: string): RuntimeSessionCreateRequest {
	return {
		sessionPath,
		executionMode: "full-access",
		getSessionId: () => undefined,
	};
}

function deferred() {
	let resolve!: () => void;
	const promise = new Promise<void>((complete) => {
		resolve = complete;
	});
	return { promise, resolve };
}

function assembly(sessionId: string): RuntimeHostSessionAssembly {
	return {
		lifecycle: { sessionId, sessionPath: undefined, dispose: async () => {} },
		historyReader: { readHistory: () => [] },
		historyController: {
			navigateForEdit: async () => ({ text: "", cancelled: false }),
			switchBranch: async () => ({ leafId: "" }),
			appendBranchSummary: async () => ({ entryId: "" }),
			deleteMessage: async () => ({ leafId: null }),
			replaceLastUserMessage: async () => ({ leafId: null }),
			forkSession: async () => ({ path: "", text: "" }),
			setName: async () => {},
		},
		executionController: { isBusy: () => false, reconfigure: async () => {} },
		workspaceView: { readWorkingDirectory: () => undefined },
		configurationController: {
			setSteeringMode: () => {},
			setFollowUpMode: () => {},
		},
		modelController: {
			selectModel: async () => {},
			setThinkingLevel: () => {},
			refreshAuth: async () => {},
		},
		modelView: {
			readCurrentModel: () => undefined,
			refreshAvailableModels: () => {},
			readAvailableModels: () => [],
			resolveApiKey: async () => undefined,
		},
		corePorts: {
			turnControl: {
				prompt: async () => undefined,
				promptWhenAvailable: async () => undefined,
				continue: async () => {},
				retry: async () => {},
				abort: async () => {},
			},
			eventStream: { subscribe: () => () => {} },
			stateReader: {
				readState: () => ({
					thinkingLevel: "off",
					activeToolNames: [],
					isStreaming: false,
					messageCount: 0,
					contextPercent: 0,
					contextWindow: 0,
				}),
				readMessages: () => [],
			},
		},
	};
}