Skip to content

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

11.2 KB
Raw Blame
import type { Message } from "@vetta/ai";
import { describe, expect, it } from "vitest";
import {
	type ErrorEvent,
	RUNTIME_HOST_LIFECYCLE_OBSERVATION,
	type RunningChangedReason,
	RuntimeHost,
	type RuntimeHostLifecycleObservation,
	type RuntimeHostSessionAssembly,
	type RuntimeHostSessionBackend,
	type RuntimeObservationRecord,
	type SessionEvent,
} from "../../src/index.js";

/**
 * running-changed 的 reason 是渲染端队列策略的唯一依据(ADR-0060):
 * agent_end = 自然结束(允许继续消费队列),aborted / error = 终止(队列暂停)。
 * turn.failed 只产生 error observation + agent_end,这里锁住 error 不得伪装成
 * agent_end;同时锁住重试恢复成功的回合不得残留早前的 error 标记。
 */
describe("RuntimeHost running-changed reason", () => {
	async function setup(): Promise<{
		emit(event: SessionEvent): void;
		reasons: Array<{ running: boolean; reason: RunningChangedReason | undefined }>;
		observedCompactions: Array<Extract<SessionEvent, { readonly type: "compaction.start" | "compaction.end" }>>;
		observedErrors: ErrorEvent[];
	}> {
		let handler: ((event: SessionEvent) => void) | undefined;
		const backend: RuntimeHostSessionBackend = {
			createAssembly: async () =>
				assembly("session-1", (h) => {
					handler = h;
				}),
		};
		const observedErrors: ErrorEvent[] = [];
		const observedCompactions: Array<
			Extract<SessionEvent, { readonly type: "compaction.start" | "compaction.end" }>
		> = [];
		const host = new RuntimeHost({
			sessionBackend: backend,
			sessionErrorObserver: (event) => observedErrors.push(event),
			sessionCompactionObserver: (event) => observedCompactions.push(event),
		});
		const reasons: Array<{ running: boolean; reason: RunningChangedReason | undefined }> = [];
		host.onRunningChanged((_path, running, _sessionId, reason) => {
			reasons.push({ running, reason });
		});
		await host.createSession({});
		if (!handler) throw new Error("event stream not subscribed");
		const emit = (event: SessionEvent): void => handler?.(event);
		return { emit, observedCompactions, observedErrors, reasons };
	}

	function lifecycle(phase: "agent_start" | "agent_end" | "aborted"): SessionEvent {
		return { ...base(), type: "session.lifecycle", phase } as SessionEvent;
	}

	function errorEvent(): SessionEvent {
		return {
			...base(),
			type: "error",
			error: { code: "PROVIDER_ERROR", message: "boom", retryable: false, origin: "runtime" },
		} as SessionEvent;
	}

	function assistantFinal(stopReason: string): SessionEvent {
		return {
			...base(),
			schemaVersion: 1,
			eventId: "assistant-done",
			channel: "assistant",
			source: "agent",
			modelCallIndex: 1,
			type: "done",
			reason: "stop",
			message: { role: "assistant", stopReason } as unknown as Message,
		} as SessionEvent;
	}

	function base(): { sessionId: string; source: "runtime-core"; timestamp: number } {
		return { sessionId: "session-1", source: "runtime-core", timestamp: 1 };
	}

	it("turn.failed 路径(error observation + agent_end)报告 reason=error", async () => {
		const { emit, observedErrors, reasons } = await setup();
		emit(lifecycle("agent_start"));
		emit(errorEvent());
		emit(lifecycle("agent_end"));
		expect(reasons).toEqual([
			{ running: true, reason: undefined },
			{ running: false, reason: "error" },
		]);
		expect(observedErrors).toHaveLength(1);
		expect(observedErrors[0]?.error).toMatchObject({ code: "PROVIDER_ERROR", message: "boom" });
	});

	it("abort 路径(lifecycle aborted + agent_end)报告 reason=aborted", async () => {
		const { emit, reasons } = await setup();
		emit(lifecycle("agent_start"));
		emit(lifecycle("aborted"));
		emit(lifecycle("agent_end"));
		expect(reasons.at(-1)).toEqual({ running: false, reason: "aborted" });
	});

	it("重试后成功收尾的回合不残留 error 标记,reason=agent_end", async () => {
		const { emit, reasons } = await setup();
		emit(lifecycle("agent_start"));
		emit(errorEvent());
		emit(assistantFinal("end_turn"));
		emit(lifecycle("agent_end"));
		expect(reasons.at(-1)).toEqual({ running: false, reason: "agent_end" });
	});

	it("回合外的合成 error(pre-stream 校验失败)不影响下一回合的 reason", async () => {
		const { emit, reasons } = await setup();
		emit(errorEvent());
		emit(lifecycle("agent_start"));
		emit(lifecycle("agent_end"));
		expect(reasons.at(-1)).toEqual({ running: false, reason: "agent_end" });
	});

	it("不依赖外部订阅即可旁路观察上下文压缩生命周期", async () => {
		const { emit, observedCompactions } = await setup();
		emit({
			...base(),
			type: "compaction.start",
			reason: "threshold",
			contextTokens: 91_000,
			contextWindow: 100_000,
			thresholdTokens: 90_000,
		} as SessionEvent);
		emit({
			...base(),
			type: "compaction.end",
			success: true,
			reason: "threshold",
			tokensBefore: 91_000,
		} as SessionEvent);

		expect(observedCompactions).toMatchObject([
			{ type: "compaction.start", contextTokens: 91_000, thresholdTokens: 90_000 },
			{ type: "compaction.end", success: true, tokensBefore: 91_000 },
		]);
	});

	it("对每个订阅者抑制重复工具快照,同时保留真实工具变化", async () => {
		let streamListener: ((event: SessionEvent) => void) | undefined;
		let activeToolNames = ["read"];
		const host = new RuntimeHost({
			sessionBackend: {
				createAssembly: async () =>
					assembly(
						"tools-session",
						(handler) => {
							streamListener = handler;
						},
						() => activeToolNames,
					),
			},
		});
		await host.createSession({});
		const events: SessionEvent[] = [];
		host.subscribe("tools-session", (event) => events.push(event));

		streamListener?.({
			...base(),
			sessionId: "tools-session",
			type: "active_tools_update",
			activeToolNames: ["read"],
		} as SessionEvent);
		activeToolNames = ["read", "bash"];
		streamListener?.({
			...base(),
			sessionId: "tools-session",
			type: "active_tools_update",
			activeToolNames,
		} as SessionEvent);

		expect(events.flatMap((event) => (event.type === "active_tools_update" ? [event.activeToolNames] : []))).toEqual([
			["read"],
			["read", "bash"],
		]);
		await host.close();
	});

	it("通过统一 Observation 隔离 Session 维护、Observer 与外部监听器失败", async () => {
		const streamListeners = new Set<(event: SessionEvent) => void>();
		const records: RuntimeObservationRecord[] = [];
		let resolveQueueObservation: (() => void) | undefined;
		const queueObservation = new Promise<void>((resolve) => {
			resolveQueueObservation = resolve;
		});
		const baseAssembly = assembly("observed-session", (handler) => streamListeners.add(handler));
		const backend: RuntimeHostSessionBackend = {
			createAssembly: async () => ({
				...baseAssembly,
				workspaceView: { readWorkingDirectory: () => "/private/workspace" },
			}),
		};
		const host = new RuntimeHost({
			sessionBackend: backend,
			pathServices: {
				normalize: (path) => path,
				ensureDirectory: async () => {
					throw new Error("secret workspace failure");
				},
			},
			queueSidecarStore: {
				read: async () => undefined,
				write: async () => {
					throw new Error("secret queue failure");
				},
				remove: async () => {},
			},
			sessionErrorObserver: () => {
				throw new Error("secret error observer failure");
			},
			sessionCompactionObserver: () => {
				throw new Error("secret compaction observer failure");
			},
			observationPort: {
				record: (record) => {
					records.push(record);
					const payload = record.payload as RuntimeHostLifecycleObservation;
					if (record.token === RUNTIME_HOST_LIFECYCLE_OBSERVATION && payload.component === "queue-sidecar") {
						resolveQueueObservation?.();
					}
				},
			},
		});
		await host.createSession({});
		expect(() =>
			host.subscribe("observed-session", () => {
				throw new Error("secret listener failure");
			}),
		).not.toThrow();
		let delivered = 0;
		host.subscribe("observed-session", () => {
			delivered += 1;
		});

		for (const listener of streamListeners) {
			listener(errorEvent());
			listener({
				...base(),
				sessionId: "observed-session",
				type: "compaction.start",
				reason: "threshold",
				contextTokens: 90,
				contextWindow: 100,
				thresholdTokens: 80,
			} as SessionEvent);
			listener({
				...base(),
				sessionId: "observed-session",
				type: "queue.changed",
				paused: false,
				entries: [{ id: "queued", behavior: "followUp", displayText: "private prompt" }],
				snapshot: { private: true },
			} as SessionEvent);
		}
		await host.prompt("observed-session", { text: "private prompt" });
		await queueObservation;

		expect(delivered).toBeGreaterThan(2);
		const failures = records
			.filter((record) => record.token === RUNTIME_HOST_LIFECYCLE_OBSERVATION)
			.map((record) => record.payload as RuntimeHostLifecycleObservation);
		expect(failures).toEqual(
			expect.arrayContaining([
				expect.objectContaining({ operation: "session.prepare", component: "session-workspace" }),
				expect.objectContaining({ operation: "session.persist", component: "queue-sidecar" }),
				expect.objectContaining({ operation: "listener.notify", component: "session-event-listener" }),
				expect.objectContaining({ operation: "observer.notify", component: "session-error-observer" }),
				expect.objectContaining({ operation: "observer.notify", component: "session-compaction-observer" }),
			]),
		);
		expect(JSON.stringify(failures)).not.toContain("secret");
		expect(JSON.stringify(failures)).not.toContain("private prompt");
		await host.close();
	});
});

function assembly(
	sessionId: string,
	onSubscribe: (handler: (event: SessionEvent) => void) => void,
	readActiveToolNames: () => readonly string[] = () => [],
): RuntimeHostSessionAssembly {
	return {
		lifecycle: { sessionId, sessionPath: `/tmp/${sessionId}.jsonl`, 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: (handler) => {
					onSubscribe(handler);
					return () => {};
				},
			},
			stateReader: {
				readState: () => ({
					thinkingLevel: "off",
					activeToolNames: [...readActiveToolNames()],
					isStreaming: false,
					messageCount: 0,
					contextPercent: 0,
					contextWindow: 0,
				}),
				readMessages: () => [],
			},
		},
	};
}