import type { AssistantMessage, Context } from "@earendil-works/pi-ai"; import { SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent"; import { describe, expect, it } from "vitest"; import { assertVoiceRequestBudget, checkpointVoiceContext, voiceChildSettings, voiceContextHead, } from "../src/voice-context.ts"; const assistant = (text = "reply"): AssistantMessage => ({ role: "assistant", content: [{ type: "text", text }], api: "openai-responses", provider: "test", model: "test", timestamp: 1, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, }, stopReason: "stop", }); const exchange = (manager: SessionManager, text: string) => { const id = manager.appendMessage({ role: "user", content: text, timestamp: 1, }); manager.appendMessage(assistant()); return id; }; const users = (manager: SessionManager) => manager .buildSessionContext() .messages.filter((message) => message.role === "user"); describe("deterministic voice context", () => { it("caps each mechanically rebuilt section with explicit truncation", () => { const value = "x".repeat(20_000); const head = voiceContextHead({ task: value, questions: value, users: value, results: value, }); expect(head.match(/\[truncated\]/gu)).toHaveLength(4); expect(head.length).toBeLessThan(11_300); expect(head).toContain("Unaccepted Pi questions"); expect( voiceContextHead({ task: [], questions: [], users: [], results: [] }), ).not.toContain("[truncated]"); }); it("keeps exactly the newest 32 complete exchanges without deleting the archive", () => { const manager = SessionManager.inMemory(); const ids = Array.from({ length: 40 }, (_, index) => exchange(manager, `user-${index}`), ); const count = manager.getEntryCount(); const identity = manager.getSessionId(); const window = checkpointVoiceContext(manager, "mechanical head"); expect(window).toMatchObject({ exchanges: 32, firstId: ids[8], omitted: 8, }); expect(users(manager)).toHaveLength(32); expect(users(manager)[0]?.content).toBe("user-8"); expect(manager.getEntryCount()).toBe(count + 1); expect(manager.getSessionId()).toBe(identity); expect(manager.getEntry(ids[0]!)?.type).toBe("message"); expect(checkpointVoiceContext(manager, "refreshed head")).toMatchObject({ omitted: 8, hasOmittedHistory: true, }); }); it("evicts whole exchanges under 64k and records omissions", () => { const manager = SessionManager.inMemory(); for (let index = 0; index < 10; index++) exchange(manager, `${index}${"x".repeat(12_000)}`); const window = checkpointVoiceContext(manager, "head"); expect(window.exchanges).toBe(5); expect(window.chars).toBeLessThanOrEqual(64_000); expect(manager.buildSessionContext().messages[0]).toMatchObject({ role: "compactionSummary", summary: expect.stringContaining("[older complete exchanges omitted]"), }); }); it("keeps paired tool calls/results intact across repeated checkpoints", () => { const manager = SessionManager.inMemory(); exchange(manager, "earlier"); manager.appendMessage({ role: "user", content: "use a tool", timestamp: 1, }); manager.appendMessage({ ...assistant(), stopReason: "toolUse", content: [ { type: "toolCall", id: "call", name: "voice_executor_state", arguments: {}, }, ], }); manager.appendMessage({ role: "toolResult", toolCallId: "call", toolName: "voice_executor_state", content: [{ type: "text", text: "state" }], isError: false, timestamp: 1, }); manager.appendMessage(assistant()); checkpointVoiceContext(manager, "old head"); checkpointVoiceContext(manager, "new head"); const messages = manager.buildSessionContext().messages; expect( messages.filter((message) => message.role === "compactionSummary"), ).toHaveLength(1); expect( messages.filter((message) => message.role === "toolResult"), ).toHaveLength(1); expect(JSON.stringify(messages)).not.toContain("old head"); }); it("pins a large in-flight exchange until the next idle checkpoint", () => { const manager = SessionManager.inMemory(); for (let index = 0; index < 32; index++) exchange(manager, `earlier-${index}`); checkpointVoiceContext(manager, "head"); const current = manager.appendMessage({ role: "user", content: "x".repeat(100_000), timestamp: 1, }); expect(users(manager)).toHaveLength(33); expect(manager.buildSessionContext().messages.at(-1)).toMatchObject({ content: "x".repeat(100_000), }); manager.appendMessage(assistant()); expect(checkpointVoiceContext(manager, "next head").exchanges).toBe(0); expect(manager.getEntry(current)).toBeDefined(); expect( checkpointVoiceContext(manager, "another head").hasOmittedHistory, ).toBe(true); }); it("never replays an aborted orphan tool call or an invented result", () => { const manager = SessionManager.inMemory(); exchange(manager, "earlier"); manager.appendMessage({ role: "user", content: "interrupted", timestamp: 1, }); manager.appendMessage({ ...assistant(), stopReason: "aborted", content: [ { type: "toolCall", id: "orphan", name: "voice_executor_dispatch", arguments: { text: "work" }, }, ], }); exchange(manager, "newer"); expect(checkpointVoiceContext(manager, "head").exchanges).toBe(1); expect(users(manager).map((message) => message.content)).toEqual(["newer"]); expect( manager .getEntries() .some( (entry) => entry.type === "message" && entry.message.role === "assistant" && entry.message.stopReason === "aborted", ), ).toBe(true); }); it("respects retry context edits and replaces old model-generated summaries", () => { const manager = SessionManager.inMemory(); const kept = exchange(manager, "kept"); const failed = manager.appendMessage({ ...assistant("retry-me"), stopReason: "error", }); manager.appendCompaction("old LLM summary", kept, 100); manager.appendContextEdit(failed, null); checkpointVoiceContext(manager, "mechanical head"); const context = JSON.stringify(manager.buildSessionContext()); expect(context).not.toContain("old LLM summary"); expect(context).not.toContain("retry-me"); expect(context).toContain("mechanical head"); }); it("disables auxiliary model work only through child-local in-memory settings", () => { const parent = SettingsManager.inMemory({ compaction: { enabled: true }, cacheWarming: "streaming", }); const child = voiceChildSettings(); expect(child.getCompactionEnabled()).toBe(false); expect(child.getCacheWarmingMode()).toBe("off"); expect(parent.getCompactionEnabled()).toBe(true); expect(parent.getCacheWarmingMode()).toBe("streaming"); }); it("refuses oversized request pins instead of splitting or truncating data", () => { const context: Context = { messages: [{ role: "user", content: "x".repeat(100_000), timestamp: 1 }], }; expect(() => assertVoiceRequestBudget(context)).not.toThrow(); context.messages.push({ role: "user", content: "y".repeat(160_000), timestamp: 1, }); expect(() => assertVoiceRequestBudget(context)).toThrow( "context safety limit", ); expect(context.messages).toHaveLength(2); }); });