Skip to content

Build your personal knowledge base with Trilium Notes

78.8 KB
Raw Blame
import type { LlmStreamChunk } from "@triliumnext/commons";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import type { ClaudeSession } from "./claude_session_pool.js";

const queryMock = vi.hoisted(() => vi.fn());
const errorLogMock = vi.hoisted(() => vi.fn());
const infoLogMock = vi.hoisted(() => vi.fn());
/** Streaming-input-only Query controls the session pool drives. */
const setModelMock = vi.hoisted(() => vi.fn());
const closeMock = vi.hoisted(() => vi.fn());

vi.mock("@anthropic-ai/claude-agent-sdk", () => ({
    query: queryMock
}));

vi.mock("@triliumnext/core", () => ({
    getLog: () => ({ info: infoLogMock, error: errorLogMock })
}));

// buildSystemPrompt (reached via composeSystemPrompt) reads the workspace task
// states; no custom states in this unit test.
vi.mock("@triliumnext/core/src/services/task_states.js", () => ({ getTaskStates: () => [] }));

// In-process MCP: the provider hands the agent Trilium's own MCP server
// instance; stub the factory so tests don't build the real tool registry.
const createMcpServerMock = vi.hoisted(() => vi.fn(() => ({ mcpServerInstance: true })));
vi.mock("../../mcp/mcp_server.js", () => ({ createMcpServer: createMcpServerMock }));

vi.mock("../../data_dir.js", async () => {
    const os = await import("os");
    const path = await import("path");
    return { default: { TRILIUM_DATA_DIR: path.join(os.tmpdir(), "trilium-claude-agent-spec") } };
});

vi.mock("../../port.js", () => ({ default: 8080 }));

const buildNoteHintMock = vi.hoisted(() => vi.fn((noteId: string): string | null => `NOTE_META(${noteId})`));
vi.mock("@triliumnext/core/src/services/llm/note_hint.js", () => ({ buildNoteHint: buildNoteHintMock }));

// The stored selection names the models a chat can use; no provider is configured here.
const getSelectedModelMock = vi.hoisted(() => vi.fn((_providerId: string | undefined, _modelId: string): { id: string; name: string } | undefined => undefined));
vi.mock("@triliumnext/core/src/services/llm/index.js", () => ({ getSelectedModel: getSelectedModelMock }));

// BYO binary resolution shells out to the user's `claude`; stub it so tests
// don't depend on a real install. Resolves a path by default; can be made to
// reject (missing binary) per-test.
const resolveClaudeBinaryMock = vi.hoisted(() => vi.fn(async () => "/usr/bin/claude"));
vi.mock("./claude_binary.js", () => ({ resolveClaudeBinaryPath: resolveClaudeBinaryMock }));

// Attachment resolution reads bytes out of Becca, which the core mock above
// omits — stub it so the multimodal tests drive block construction directly.
const resolveAttachmentPartMock = vi.hoisted(() => vi.fn());
vi.mock("@triliumnext/core/src/services/llm/attachment_content.js", async (importOriginal) => ({
    ...await importOriginal<typeof import("@triliumnext/core/src/services/llm/attachment_content.js")>(),
    resolveAttachmentPart: resolveAttachmentPartMock
}));

// The Windows `.cmd` shim delegates to child_process.spawn; the provider never
// spawns otherwise, so mocking the whole module is safe.
const spawnMock = vi.hoisted(() => vi.fn());
vi.mock("child_process", () => ({ spawn: spawnMock }));

const { buildSeededPrompt, buildSubscriptionModelList, ClaudeAgentProvider, hashTranscript, resetAgentCwdForTests, resetSubscriptionModelCacheForTests, TITLE_TIMEOUT_MS } = await import("./claude_agent.js");
const { MAX_WARM_SESSIONS, Pushable, releaseSession, rememberSession: rememberWarmSession, resetClaudeSessionPoolForTests } = await import("./claude_session_pool.js");
const { buildTitlePrompt, MAX_TITLES_PER_SESSION } = await import("./transcript.js");
const { TOOL_CALL_DECLINED_REASON, ToolApprovals } = await import("@triliumnext/core/src/services/llm/tool_approval.js");
type PushablePrompt = { pending: readonly { message: { role: string; content: unknown[] } }[] };

/**
 * Every turn now feeds the session's streaming input, so the `prompt` option is
 * always a Pushable and the turn's own message is what was pushed onto it.
 */
function pushedMessages(prompt: unknown): { message: { role: string; content: unknown[] } }[] {
    const pending = (prompt as PushablePrompt)?.pending;
    if (!Array.isArray(pending)) {
        throw new Error("expected the prompt to be a streaming-input Pushable");
    }
    return [...pending];
}

/** The single user message a turn streamed (multimodal path). */
function drainPrompt(prompt: unknown): { role: string; content: unknown[] } {
    const messages = pushedMessages(prompt);
    expect(messages).toHaveLength(1);
    return messages[0].message;
}

/** The plain text a turn pushed, for the non-multimodal path. */
function promptText(prompt: unknown): string {
    return drainPrompt(prompt).content
        .map(block => (block && typeof block === "object" && "text" in block ? String(block.text) : ""))
        .join("");
}

/**
 * One long-lived query stream serving several turns, as a warm session does:
 * the provider consumes up to each turn's `result` and resumes from there on
 * the next turn instead of starting a new query.
 */
function scriptAgentSession(turns: unknown[][]) {
    queryMock.mockImplementation(() => makeQuery(turns.flat()));
}

/** Make query() replay the given SDK messages and record its invocation. */
function scriptAgent(messages: unknown[]) {
    queryMock.mockImplementation(() => makeQuery(messages));
}

/**
 * A stand-in for the SDK's Query: an async generator plus the control methods
 * that only exist in streaming input mode, which the pool drives.
 */
function makeQuery(messages: unknown[]) {
    const generator = (async function* () {
        for (const message of messages) {
            yield message;
        }
    })();
    return Object.assign(generator, { setModel: setModelMock, close: closeMock });
}

/** The reply chunks of a turn, without the status that precedes a cold start (see {@link collectAll}). */
async function collect(iterable: AsyncIterable<LlmStreamChunk>): Promise<LlmStreamChunk[]> {
    return (await collectAll(iterable)).filter(chunk => chunk.type !== "status");
}

async function collectAll(iterable: AsyncIterable<LlmStreamChunk>): Promise<LlmStreamChunk[]> {
    const chunks: LlmStreamChunk[] = [];
    for await (const chunk of iterable) {
        chunks.push(chunk);
    }
    return chunks;
}

function textDelta(text: string) {
    return {
        type: "stream_event",
        parent_tool_use_id: null,
        session_id: "sess-1",
        event: { type: "content_block_delta", index: 0, delta: { type: "text_delta", text } }
    };
}

function successResult(sessionId = "sess-1") {
    return {
        type: "result",
        subtype: "success",
        is_error: false,
        result: "ok",
        session_id: sessionId,
        total_cost_usd: 0.05,
        usage: { input_tokens: 100, output_tokens: 40 }
    };
}

describe("ClaudeAgentProvider.chatChunks", () => {
    beforeEach(() => {
        queryMock.mockReset();
        errorLogMock.mockReset();
        createMcpServerMock.mockClear(); // clear calls, keep the instance impl
        resolveAttachmentPartMock.mockReset();
        // Sessions outlive a turn now, so each test must start from a cold
        // pool. Reset it *before* clearing the mocks: tearing down a leftover
        // session calls close() and would otherwise count against this test.
        resetClaudeSessionPoolForTests();
        setModelMock.mockClear();
        closeMock.mockClear();
    });

    it("titles every session it opens, so Claude Code generates no title of its own", async () => {
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));
        scriptTitleAgent(async () => [titleResult("Title")]);
        await provider.generateTitle("hi");

        expect(queryMock).toHaveBeenCalledTimes(2);
        for (const [{ options }] of queryMock.mock.calls) {
            expect(options.title).toEqual(expect.stringMatching(/\S/));
        }
    });

    it("names Claude Code's web tools the way the other providers name theirs", async () => {
        const webCall = (id: string, name: string, input: Record<string, unknown>) => [
            {
                type: "stream_event",
                parent_tool_use_id: null,
                session_id: "sess-1",
                event: { type: "content_block_start", index: 0, content_block: { type: "tool_use", id, name } }
            },
            {
                type: "assistant",
                parent_tool_use_id: null,
                session_id: "sess-1",
                message: { content: [{ type: "tool_use", id, name, input }] }
            },
            {
                type: "user",
                parent_tool_use_id: null,
                session_id: "sess-1",
                message: { content: [{ type: "tool_result", tool_use_id: id, content: "found" }] }
            }
        ];
        scriptAgent([
            { type: "system", subtype: "init", session_id: "sess-1" },
            ...webCall("toolu_s", "WebSearch", { query: "trilium" }),
            ...webCall("toolu_f", "WebFetch", { url: "https://triliumnotes.org", prompt: "Summarize" }),
            successResult()
        ]);

        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], { enableWebSearch: true }));

        expect(chunks.filter(c => c.type.startsWith("tool_")).map(c => [c.type, "toolName" in c ? c.toolName : undefined])).toEqual([
            ["tool_input_start", "web_search"],
            ["tool_use", "web_search"],
            ["tool_result", "web_search"],
            ["tool_input_start", "read_web_page"],
            ["tool_use", "read_web_page"],
            ["tool_result", "read_web_page"]
        ]);
        expect(chunks).toContainEqual({
            type: "tool_use", toolCallId: "toolu_f", toolName: "read_web_page",
            toolInput: { url: "https://triliumnotes.org", prompt: "Summarize" }
        });
    });

    it("maps stream events, tool calls, results, and usage to chunks in order", async () => {
        scriptAgent([
            { type: "system", subtype: "init", session_id: "sess-1" },
            textDelta("Hello "),
            {
                type: "stream_event",
                parent_tool_use_id: null,
                session_id: "sess-1",
                event: {
                    type: "content_block_start",
                    index: 1,
                    content_block: { type: "tool_use", id: "toolu_1", name: "mcp__trilium__search_notes" }
                }
            },
            {
                type: "stream_event",
                parent_tool_use_id: null,
                session_id: "sess-1",
                event: { type: "content_block_delta", index: 1, delta: { type: "input_json_delta", partial_json: '{"query":' } }
            },
            {
                type: "assistant",
                parent_tool_use_id: null,
                session_id: "sess-1",
                message: {
                    content: [
                        { type: "text", text: "Hello " },
                        { type: "tool_use", id: "toolu_1", name: "mcp__trilium__search_notes", input: { query: "x" } }
                    ]
                }
            },
            {
                type: "user",
                parent_tool_use_id: null,
                session_id: "sess-1",
                message: {
                    content: [
                        { type: "tool_result", tool_use_id: "toolu_1", content: [{ type: "text", text: "3 notes found" }] },
                        // A result for an unknown (e.g. replayed) tool call must be dropped.
                        { type: "tool_result", tool_use_id: "toolu_stale", content: "old" }
                    ]
                }
            },
            textDelta("world"),
            successResult()
        ]);

        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));

        expect(chunks).toEqual([
            { type: "text", content: "Hello " },
            { type: "tool_input_start", toolCallId: "toolu_1", toolName: "search_notes" },
            { type: "tool_input_delta", toolCallId: "toolu_1", delta: '{"query":' },
            { type: "tool_use", toolCallId: "toolu_1", toolName: "search_notes", toolInput: { query: "x" } },
            { type: "tool_result", toolCallId: "toolu_1", toolName: "search_notes", result: "3 notes found", isError: false },
            { type: "text", content: "world" },
            {
                type: "usage",
                // No cost even though the SDK result carries total_cost_usd: usage is
                // covered by the subscription, so a per-turn dollar figure isn't shown.
                usage: { promptTokens: 100, completionTokens: 40, totalTokens: 140, provider: "claude-agent" }
            },
            { type: "done" }
        ]);
    });

    it("reports the friendly model name in usage, falling back to the raw ID for unknown models", async () => {
        const provider = new ClaudeAgentProvider();
        const usageModel = async (config: { providerId?: string; model?: string }) => {
            scriptAgent([successResult()]);
            const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], config));
            const usage = chunks.find(c => c.type === "usage");
            return usage?.type === "usage" ? usage.usage.model : undefined;
        };
        getSelectedModelMock.mockImplementation((providerId, modelId) =>
            providerId === "claude-1" && modelId === "claude-opus-4-8[1m]" ? { id: modelId, name: "Opus 4.8 (1M context)" } : undefined);

        try {
            // The stored selection names the model (the chat pane renders it verbatim).
            expect(await usageModel({ providerId: "claude-1", model: "claude-opus-4-8[1m]" })).toBe("Opus 4.8 (1M context)");
            // An ID no selection names passes through unchanged rather than becoming undefined.
            expect(await usageModel({ providerId: "claude-1", model: "some-unknown-model" })).toBe("some-unknown-model");
        } finally {
            getSelectedModelMock.mockReset();
        }
    });

    it("leaves the model to Claude Code when the chat names none, or names the default", async () => {
        const provider = new ClaudeAgentProvider();
        for (const config of [{}, { model: "default" }]) {
            queryMock.mockClear();
            scriptAgent([successResult()]);
            await collect(provider.chatChunks([{ role: "user", content: "hi" }], config));
            expect(queryMock.mock.calls[0][0].options.model).toBeUndefined();
        }
    });

    it("ignores subagent traffic (non-null parent_tool_use_id)", async () => {
        scriptAgent([
            { ...textDelta("subagent text"), parent_tool_use_id: "toolu_parent" },
            successResult()
        ]);

        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));

        expect(chunks.filter(c => c.type === "text")).toEqual([]);
    });

    it("keeps one warm session across turns, pushing the next message onto its streaming input", async () => {
        const provider = new ClaudeAgentProvider();
        const config = { chatNoteId: "note-resume" };

        scriptAgentSession([
            [textDelta("first reply"), successResult("sess-A")],
            [textDelta("second reply"), successResult("sess-A")]
        ]);

        // Turn 1 — no history, no mapping: plain prompt, no resume. Starting the
        // subprocess is announced before anything else.
        const first = await collectAll(provider.chatChunks([{ role: "user", content: "first question" }], config));
        expect(first[0]).toEqual({ type: "status", status: "starting_agent" });

        expect(queryMock).toHaveBeenCalledTimes(1);
        const call = queryMock.mock.calls[0][0];
        expect(call.options.resume).toBeUndefined();

        // Turn 2 — the transcript still matches, so the live subprocess is
        // reused: no second query(), just another message on the same input.
        const second = await collectAll(provider.chatChunks([
            { role: "user", content: "first question" },
            { role: "assistant", content: "first reply" },
            { role: "user", content: "second question" }
        ], config));

        expect(queryMock).toHaveBeenCalledTimes(1);
        expect(second).toContainEqual({ type: "text", content: "second reply" });
        expect(second.some(chunk => chunk.type === "status")).toBe(false);
        const pushed = pushedMessages(call.prompt).map(m => (m.message.content[0] as { text: string }).text);
        expect(pushed).toEqual(["first question", "second question"]);
    });

    it("reseeds a fresh session from the transcript when the history diverged", async () => {
        const provider = new ClaudeAgentProvider();
        const config = { chatNoteId: "note-diverged" };

        scriptAgent([textDelta("reply"), successResult("sess-B")]);
        await collect(provider.chatChunks([{ role: "user", content: "original" }], config));

        // The user edited the first message — the stored hash no longer matches.
        scriptAgent([textDelta("re-reply"), successResult("sess-C")]);
        await collect(provider.chatChunks([
            { role: "user", content: "edited" },
            { role: "assistant", content: "reply" },
            { role: "user", content: "follow-up" }
        ], config));

        const secondCall = queryMock.mock.calls[1][0];
        expect(secondCall.options.resume).toBeUndefined();
        expect(promptText(secondCall.prompt)).toContain("<conversation_history>");
        expect(promptText(secondCall.prompt)).toContain("User: edited");
        expect(promptText(secondCall.prompt)).toContain("Assistant: reply");
        expect(promptText(secondCall.prompt)).toContain("follow-up");
    });

    it("prepends the current-note metadata hint to the user message when contextNoteId is set", async () => {
        buildNoteHintMock.mockClear();
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks(
            [{ role: "user", content: "what is this note about?" }],
            { contextNoteId: "note-abc" }
        ));

        expect(buildNoteHintMock).toHaveBeenCalledWith("note-abc", false);
        expect(promptText(queryMock.mock.calls[0][0].prompt)).toBe("NOTE_META(note-abc)\n\nwhat is this note about?");
    });

    it("does not prepend a hint when the context note no longer exists", async () => {
        buildNoteHintMock.mockReturnValueOnce(null);
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks(
            [{ role: "user", content: "hello" }],
            { contextNoteId: "gone" }
        ));

        expect(promptText(queryMock.mock.calls[0][0].prompt)).toBe("hello");
    });

    it("keeps the note hint out of the session hash so a later turn still resumes", async () => {
        const provider = new ClaudeAgentProvider();
        const config = { contextNoteId: "note-abc", chatNoteId: "note-hint-resume" };

        scriptAgentSession([
            [textDelta("first reply"), successResult("sess-H")],
            [textDelta("second reply"), successResult("sess-H")]
        ]);
        await collect(provider.chatChunks([{ role: "user", content: "q1" }], config));

        // Turn 2: transcript matches turn 1 (unhinted), so the warm session is
        // reused, and the new message still carries the freshly-built hint.
        await collect(provider.chatChunks([
            { role: "user", content: "q1" },
            { role: "assistant", content: "first reply" },
            { role: "user", content: "q2" }
        ], config));

        expect(queryMock).toHaveBeenCalledTimes(1);
        const pushed = pushedMessages(queryMock.mock.calls[0][0].prompt);
        expect((pushed[1].message.content[0] as { text: string }).text).toBe("NOTE_META(note-abc)\n\nq2");
    });

    it("sends a supported image as a base64 block via a one-message stream", async () => {
        resolveAttachmentPartMock.mockReturnValue({ kind: "image", bytes: new Uint8Array([1, 2, 3]), mime: "image/png" });
        scriptAgent([textDelta("I see it"), successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([
            { role: "user", content: [
                { type: "text", text: "what is this?" },
                { type: "image", attachmentId: "att-1", mime: "image/png" }
            ] }
        ], {}));

        const message = drainPrompt(queryMock.mock.calls[0][0].prompt);
        expect(message.role).toBe("user");
        expect(message.content).toEqual([
            { type: "text", text: "what is this?" },
            { type: "image", source: { type: "base64", media_type: "image/png", data: "AQID" } }
        ]);
    });

    it("sends a PDF as a document block and leads with the note hint", async () => {
        resolveAttachmentPartMock.mockReturnValue({ kind: "file", bytes: new Uint8Array([37, 80, 68, 70]), mime: "application/pdf", filename: "report.pdf" });
        scriptAgent([textDelta("summary"), successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([
            { role: "user", content: [{ type: "file", attachmentId: "att-2", mime: "application/pdf", filename: "report.pdf" }] }
        ], { contextNoteId: "note-abc" }));

        const message = drainPrompt(queryMock.mock.calls[0][0].prompt);
        expect(message.content).toEqual([
            { type: "text", text: "NOTE_META(note-abc)" },
            { type: "document", title: "report.pdf", source: { type: "base64", media_type: "application/pdf", data: "JVBERg==" } }
        ]);
    });

    it("degrades unsupported attachments to text and keeps the plain string prompt", async () => {
        // An SVG resolves to inlined text; the string path (not the stream) is used.
        resolveAttachmentPartMock.mockReturnValue({ kind: "text", text: "<file name=\"d.svg\">\n<svg/>\n</file>" });
        scriptAgent([textDelta("ok"), successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([
            { role: "user", content: [
                { type: "text", text: "read this" },
                { type: "image", attachmentId: "att-3", mime: "image/svg+xml" }
            ] }
        ], {}));

        // Degrades to a single text block rather than image/document blocks.
        const message = drainPrompt(queryMock.mock.calls[0][0].prompt);
        expect(message.content).toEqual([
            { type: "text", text: "read this\n\n<file name=\"d.svg\">\n<svg/>\n</file>" }
        ]);
    });

    it("wires Trilium's in-process MCP server instance and disables built-in tools", async () => {
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], { enableNoteTools: true }));

        const options = queryMock.mock.calls[0][0].options;
        expect(options.tools).toEqual([]);
        // Note tools are not pre-approved: each call goes through `canUseTool`.
        expect(options.allowedTools).toEqual([]);
        expect(options.canUseTool).toEqual(expect.any(Function));
        // In-process (sdk) transport, not an HTTP endpoint — the instance is
        // Trilium's own createMcpServer(), tunneled over the SDK control channel.
        expect(options.mcpServers.trilium.type).toBe("sdk");
        expect(options.mcpServers.trilium.instance).toEqual({ mcpServerInstance: true });
        expect(createMcpServerMock).toHaveBeenCalled();
        expect(options.permissionMode).toBe("default");
        expect(options.settingSources).toEqual([]);
    });

    it("asks the running turn's approvals before a note tool runs, across the turns of a warm session", async () => {
        const config = { chatNoteId: "note-approval", enableNoteTools: true };
        const signal = new AbortController().signal;
        const sdk = { name: "trilium", source: "sdk" };
        const ask = (options: { canUseTool: (...args: unknown[]) => Promise<unknown> }, toolName: string, toolUseID: string, mcpServer?: object) =>
            options.canUseTool(toolName, { noteId: "n" }, { signal, toolUseID, requestId: "r", mcpServer });
        const decisions: unknown[] = [];
        queryMock.mockImplementation(({ options }) => Object.assign((async function* () {
            decisions.push(await ask(options, "mcp__trilium__rename_note", "toolu_1", sdk));
            decisions.push(await ask(options, "Bash", "toolu_2"));
            yield textDelta("first reply");
            yield successResult("sess-A");
            decisions.push(await ask(options, "mcp__trilium__delete_note", "toolu_3", sdk));
            yield successResult("sess-A");
        })(), { setModel: setModelMock, close: closeMock }));

        const provider = new ClaudeAgentProvider();
        const requests: unknown[] = [];
        const approvalsAnswering = (approved: boolean) => {
            const approvals = new ToolApprovals();
            approvals.onRequest = (request) => {
                requests.push(request);
                queueMicrotask(() => approvals.answer(request.toolCallId, approved));
            };
            return approvals;
        };
        await collect(provider.chatChunks([{ role: "user", content: "first" }], { ...config, toolApprovals: approvalsAnswering(true) }));
        await collect(provider.chatChunks([
            { role: "user", content: "first" },
            { role: "assistant", content: "first reply" },
            { role: "user", content: "second" }
        ], { ...config, toolApprovals: approvalsAnswering(false) }));

        expect(queryMock).toHaveBeenCalledOnce();
        const { options } = queryMock.mock.calls[0][0];
        expect(options.permissionMode).toBe("default");
        expect(options.allowedTools).toEqual([]);
        expect(requests).toEqual([
            { toolCallId: "toolu_1", toolName: "rename_note", toolInput: { noteId: "n" } },
            { toolCallId: "toolu_3", toolName: "delete_note", toolInput: { noteId: "n" } }
        ]);
        expect(decisions).toEqual([
            { behavior: "allow", updatedInput: { noteId: "n" } },
            { behavior: "deny", message: expect.any(String) },
            { behavior: "deny", message: TOOL_CALL_DECLINED_REASON }
        ]);
        // Between turns no approvals are open, so a call runs unasked.
        await expect(ask(options, "mcp__trilium__get_note", "toolu_4", sdk))
            .resolves.toEqual({ behavior: "allow", updatedInput: { noteId: "n" } });
        // A tool named like Trilium's but served from configuration is never Trilium's.
        await expect(ask(options, "mcp__trilium__get_note", "toolu_5", { name: "trilium", source: "user" }))
            .resolves.toMatchObject({ behavior: "deny" });
    });

    it("enables adaptive extended thinking when the turn requests it", async () => {
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], { enableExtendedThinking: true }));

        expect(queryMock.mock.calls[0][0].options.thinking).toEqual({ type: "adaptive", display: "summarized" });
    });

    it("disables extended thinking by default", async () => {
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));

        expect(queryMock.mock.calls[0][0].options.thinking).toEqual({ type: "disabled" });
    });

    it("drives the user's resolved claude binary (bring-your-own-binary)", async () => {
        resolveClaudeBinaryMock.mockResolvedValueOnce("/opt/homebrew/bin/claude");
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));

        expect(queryMock.mock.calls[0][0].options.pathToClaudeCodeExecutable).toBe("/opt/homebrew/bin/claude");
    });

    it("surfaces a friendly error (and never spawns) when Claude Code isn't installed", async () => {
        resolveClaudeBinaryMock.mockRejectedValueOnce(
            new Error("Claude Code CLI not found. Install it and run `claude /login`...")
        );
        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));

        expect(queryMock).not.toHaveBeenCalled();
        const errors = chunks.filter(c => c.type === "error");
        expect(errors).toHaveLength(1);
        expect(errors[0].error).toContain("Claude Code CLI not found");
    });

    it("uses Trilium's shared system prompt (skill/link/markdown guidance) when note tools are live", async () => {
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], { enableNoteTools: true }));

        const systemPrompt = queryMock.mock.calls[0][0].options.systemPrompt;
        // Parity with the AI-SDK providers: the shared buildSystemPrompt content.
        expect(systemPrompt).toContain("load_skill");
        expect(systemPrompt).toContain("wiki-link format [[noteId]]");
        expect(systemPrompt).toContain("Mermaid diagrams");
        // Note tools ARE live, so no "turned off" degradation notice.
        expect(systemPrompt).not.toContain("MCP server is turned off");
    });

    it("isolates the agent cwd from enclosing projects with a .git marker", async () => {
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));

        const path = await import("path");
        const fs = await import("fs");
        const cwd = queryMock.mock.calls[0][0].options.cwd;
        // Absolute cwd (TRILIUM_DATA_DIR may be relative in dev runs) with a
        // .git marker so Claude Code never resolves an enclosing repo as the
        // agent's project — that would apply the repo's disabledMcpjsonServers
        // list (silently disabling the "trilium" server by name), CLAUDE.md,
        // and auto-memory to note chats.
        expect(path.isAbsolute(cwd)).toBe(true);
        expect(fs.existsSync(path.join(cwd, ".git", "HEAD"))).toBe(true);
    });

    it("omits note-tools wiring (and its prompt guidance) when the chat disables note tools, and enables web search", async () => {
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], { enableNoteTools: false, enableWebSearch: true }));

        const options = queryMock.mock.calls[0][0].options;
        expect(options.mcpServers).toBeUndefined();
        expect(createMcpServerMock).not.toHaveBeenCalled();
        expect(options.tools).toEqual(["WebSearch", "WebFetch"]);
        expect(options.allowedTools).toEqual(["WebSearch", "WebFetch"]);
        // Prompt matches the wiring: no note-tools guidance when they're off.
        expect(options.systemPrompt).not.toContain("load_skill");
        expect(options.systemPrompt).toContain("do not have access to the user's notes");
    });

    // A caller with no opinion gets no note access, the same reading `base_provider` gives an
    // absent flag — so what a request leaves unsaid means one thing across every provider. This
    // used to go the other way here, handing the whole tree to anything that simply did not ask.
    it("omits note-tools wiring when the chat says nothing about them", async () => {
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));

        const options = queryMock.mock.calls[0][0].options;
        expect(options.mcpServers).toBeUndefined();
        expect(createMcpServerMock).not.toHaveBeenCalled();
        expect(options.allowedTools).toEqual([]);
        expect(options.systemPrompt).not.toContain("load_skill");
    });

    it("logs a diagnostic when the in-process MCP bridge fails to connect", async () => {
        scriptAgent([
            { type: "system", subtype: "init", session_id: "s", mcp_servers: [{ name: "trilium", status: "failed" }] },
            successResult()
        ]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));

        expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("failed to connect"));
    });

    it("does not log a bridge diagnostic on a healthy connected init", async () => {
        scriptAgent([
            { type: "system", subtype: "init", session_id: "s", mcp_servers: [{ name: "trilium", status: "connected" }] },
            successResult()
        ]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));

        expect(errorLogMock).not.toHaveBeenCalled();
    });

    it("surfaces authentication failures with a login hint", async () => {
        scriptAgent([
            {
                type: "assistant",
                parent_tool_use_id: null,
                session_id: "sess-1",
                error: "authentication_failed",
                message: { content: [] }
            },
            { ...successResult(), subtype: "error_during_execution", is_error: true, errors: ["auth failed"] }
        ]);

        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));

        const errors = chunks.filter(c => c.type === "error");
        expect(errors[0].error).toContain("claude /login");
    });

    it("emits an error chunk when the agent subprocess fails", async () => {
        queryMock.mockImplementation(() => (async function* () {
            yield textDelta("partial");
            throw new Error("spawn claude ENOENT");
        })());

        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));

        const errors = chunks.filter(c => c.type === "error");
        expect(errors).toHaveLength(1);
        expect(errors[0].error).toContain("Failed to start Claude Code");
    });

    it("forwards a mid-stream abort to the agent's abort controller", async () => {
        scriptAgent([textDelta("partial"), successResult()]);
        const controller = new AbortController();
        const provider = new ClaudeAgentProvider();
        const stream = provider.chatChunks([{ role: "user", content: "hi" }], {}, controller.signal);

        const chunks: LlmStreamChunk[] = [];
        for await (const chunk of stream) {
            chunks.push(chunk);
            // Fire the abort after the first chunk; the mocked SDK stream keeps
            // yielding, proving the listener path itself doesn't break the loop.
            controller.abort();
        }
        expect(chunks.some(c => c.type === "text")).toBe(true);
    });

    it("does not spawn the agent when the signal is already aborted at entry", async () => {
        // An abort listener alone would never fire for a pre-aborted signal —
        // the provider must bail out before spawning the subprocess.
        const controller = new AbortController();
        controller.abort();

        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}, controller.signal));

        expect(chunks).toEqual([]);
        expect(queryMock).not.toHaveBeenCalled();
    });

    it("rejects a conversation that does not end with a user message (or is empty)", async () => {
        const provider = new ClaudeAgentProvider();
        const expected = [{ type: "error", error: "The last message must be a user message." }];
        expect(await collect(provider.chatChunks([{ role: "assistant", content: "hi" }], {}))).toEqual(expected);
        expect(await collect(provider.chatChunks([], {}))).toEqual(expected);
        expect(queryMock).not.toHaveBeenCalled();
    });

    it("exposes only Claude Code's default offline, zero pricing, and no chat() implementation", () => {
        const provider = new ClaudeAgentProvider();
        expect(provider.getAvailableModels()).toEqual([
            { id: "default", name: "Default", pricing: { input: 0, output: 0 }, isDefault: true, isSubscription: true }
        ]);
        // Any model the price table knows is free on the subscription, as is the default.
        expect(provider.getModelPricing("claude-sonnet-5-5")).toEqual({ input: 0, output: 0 });
        expect(provider.getModelPricing("default")).toEqual({ input: 0, output: 0 });
        // A long-context variant prices like its base model, not as an unknown.
        expect(provider.getModelPricing("claude-opus-4-8[1m]")).toEqual(expect.objectContaining({ input: 0, output: 0 }));
        expect(provider.getModelPricing("no-such-model")).toBeUndefined();
        expect(provider.getModelPricing("no-such-model[1m]")).toBeUndefined();
        expect(() => provider.chat()).toThrow(/chatChunks/);
    });

    it("streams thinking deltas as thinking chunks", async () => {
        scriptAgent([
            {
                type: "stream_event",
                parent_tool_use_id: null,
                session_id: "sess-1",
                event: { type: "content_block_delta", index: 0, delta: { type: "thinking_delta", thinking: "pondering…" } }
            },
            successResult()
        ]);
        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));
        expect(chunks).toContainEqual({ type: "thinking", content: "pondering…" });
    });

    it("ignores stream noise: non-tool block starts, unknown deltas, unmapped tool indexes, other events", async () => {
        scriptAgent([
            // content_block_start for a plain text block — no chunk.
            {
                type: "stream_event",
                parent_tool_use_id: null,
                session_id: "sess-1",
                event: { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }
            },
            // A delta type the provider doesn't map — no chunk.
            {
                type: "stream_event",
                parent_tool_use_id: null,
                session_id: "sess-1",
                event: { type: "content_block_delta", index: 0, delta: { type: "signature_delta", signature: "sig" } }
            },
            // input_json_delta for a block index that never had a tool_use start.
            {
                type: "stream_event",
                parent_tool_use_id: null,
                session_id: "sess-1",
                event: { type: "content_block_delta", index: 9, delta: { type: "input_json_delta", partial_json: "{}" } }
            },
            // A stream event that is neither block start nor delta.
            {
                type: "stream_event",
                parent_tool_use_id: null,
                session_id: "sess-1",
                event: { type: "message_start" }
            },
            // An SDK message type the provider doesn't know (and no session_id).
            { type: "diagnostic" },
            successResult()
        ]);
        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));
        expect(chunks.map(c => c.type)).toEqual(["usage", "done"]);
    });

    it("ignores assistant/user messages from subagents and non-array user content", async () => {
        scriptAgent([
            {
                type: "assistant",
                parent_tool_use_id: "toolu_parent",
                session_id: "sess-1",
                message: { content: [{ type: "tool_use", id: "toolu_sub", name: "sub_tool", input: {} }] }
            },
            {
                type: "user",
                parent_tool_use_id: "toolu_parent",
                session_id: "sess-1",
                message: { content: [{ type: "tool_result", tool_use_id: "toolu_sub", content: "sub result" }] }
            },
            {
                type: "user",
                parent_tool_use_id: null,
                session_id: "sess-1",
                message: { content: "a plain string user echo" }
            },
            successResult()
        ]);
        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));
        expect(chunks.map(c => c.type)).toEqual(["usage", "done"]);
    });

    it("flattens tool results of every content shape and skips non-result blocks", async () => {
        // No `input` field — exercises the `block.input ?? {}` fallback on the tool_use chunk.
        const toolUse = (id: string) => ({ type: "tool_use", id, name: `mcp__trilium__t_${id}` });
        scriptAgent([
            {
                type: "assistant",
                parent_tool_use_id: null,
                session_id: "sess-1",
                message: { content: [toolUse("t1"), toolUse("t2"), toolUse("t3"), toolUse("t4")] }
            },
            {
                type: "user",
                parent_tool_use_id: null,
                session_id: "sess-1",
                message: {
                    content: [
                        // A non-result block and an id-less result must both be skipped.
                        { type: "text", text: "interleaved commentary" },
                        { type: "tool_result", content: "no id" },
                        { type: "tool_result", tool_use_id: "t1", content: "plain string" },
                        { type: "tool_result", tool_use_id: "t2" }, // no content
                        { type: "tool_result", tool_use_id: "t3", content: [{ type: "image" }] },
                        { type: "tool_result", tool_use_id: "t4", content: { odd: true } }
                    ]
                }
            },
            successResult()
        ]);
        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));

        const results = chunks.filter(c => c.type === "tool_result");
        expect(results.map(r => [r.toolName, r.result])).toEqual([
            ["t_t1", "plain string"],
            ["t_t2", ""],
            ["t_t3", ""], // array without text blocks flattens to nothing
            ["t_t4", '{"odd":true}']
        ]);
    });

    it("reports a stop reason when the agent fails without an error list", async () => {
        scriptAgent([
            { ...successResult(), subtype: "error_max_turns", is_error: true }
        ]);
        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));
        const errors = chunks.filter(c => c.type === "error");
        expect(errors).toEqual([{ type: "error", error: "Agent stopped: error_max_turns" }]);
    });

    it("maps oauth failures to the login hint and other assistant errors to a generic message", async () => {
        scriptAgent([
            {
                type: "assistant",
                parent_tool_use_id: null,
                session_id: "sess-1",
                error: "oauth_org_not_allowed",
                message: { content: [] }
            },
            {
                type: "assistant",
                parent_tool_use_id: null,
                session_id: "sess-1",
                error: "billing_issue",
                message: { content: [] }
            },
            successResult()
        ]);
        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));
        const errors = chunks.filter(c => c.type === "error").map(c => c.error);
        expect(errors[0]).toContain("claude /login");
        expect(errors[1]).toBe("Claude Agent error: billing_issue");
    });

    it("stringifies non-Error throws from the SDK", async () => {
        queryMock.mockImplementation(() => {
            throw "subprocess exploded";
        });
        const provider = new ClaudeAgentProvider();
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));
        expect(chunks).toContainEqual({ type: "error", error: "subprocess exploded" });
    });

    it("ignores non-init system messages and inits without a trilium MCP entry", async () => {
        scriptAgent([
            { type: "system", subtype: "compact_boundary", session_id: "s" },
            { type: "system", subtype: "init", session_id: "s" }, // no mcp_servers at all
            { type: "system", subtype: "init", session_id: "s", mcp_servers: [{ name: "other", status: "failed" }] },
            successResult()
        ]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));
        expect(errorLogMock).not.toHaveBeenCalled();
    });

    it("degrades unresolved and natively-unsupported attachments to placeholders around real blocks", async () => {
        resolveAttachmentPartMock
            .mockReturnValueOnce({ kind: "image", bytes: new Uint8Array([1]), mime: "image/png" })
            .mockReturnValueOnce(null) // missing/protected attachment
            .mockReturnValueOnce({ kind: "image", bytes: new Uint8Array([2]), mime: "image/tiff" })
            .mockReturnValueOnce({ kind: "file", bytes: new Uint8Array([3]), mime: "application/zip", filename: "a.zip" });
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([
            { role: "user", content: [
                { type: "image", attachmentId: "png", mime: "image/png" },
                { type: "image", attachmentId: "gone", mime: "image/png" },
                { type: "image", attachmentId: "tiff", mime: "image/tiff" },
                { type: "file", attachmentId: "zip", mime: "application/zip", filename: "a.zip" }
            ] }
        ], {}));

        const message = drainPrompt(queryMock.mock.calls[0][0].prompt);
        expect(message.content).toEqual([
            { type: "image", source: { type: "base64", media_type: "image/png", data: "AQ==" } },
            { type: "text", text: "[attached image]" },
            { type: "text", text: "[attached image]" },
            { type: "text", text: "[attached file: a.zip]" }
        ]);
    });

    it("keeps the plain string prompt for parts-form content without attachments", async () => {
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([
            { role: "user", content: [{ type: "text", text: "line one" }, { type: "text", text: "line two" }] }
        ], {}));
        expect(promptText(queryMock.mock.calls[0][0].prompt)).toBe("line one\nline two");
    });

    it("creates the isolating .git marker only when it is absent", async () => {
        const path = await import("path");
        const fs = await import("fs");
        const os = await import("os");
        const agentDir = path.join(os.tmpdir(), "trilium-claude-agent-spec", "claude-agent");

        resetAgentCwdForTests();
        fs.rmSync(agentDir, { recursive: true, force: true });
        scriptAgent([successResult()]);
        const provider = new ClaudeAgentProvider();
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));
        expect(fs.existsSync(path.join(agentDir, ".git", "HEAD"))).toBe(true);

        // Second initialization finds the marker in place and leaves it alone.
        const headBefore = fs.statSync(path.join(agentDir, ".git", "HEAD")).mtimeMs;
        resetAgentCwdForTests();
        scriptAgent([successResult()]);
        await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));
        expect(fs.statSync(path.join(agentDir, ".git", "HEAD")).mtimeMs).toBe(headBefore);
    });

    it("switches models on the live session instead of respawning it", async () => {
        const provider = new ClaudeAgentProvider();
        const config = { chatNoteId: "note-model" };
        scriptAgentSession([
            [textDelta("a"), successResult("sess-M")],
            [textDelta("b"), successResult("sess-M")]
        ]);

        await collect(provider.chatChunks([{ role: "user", content: "q1" }], { ...config, model: "claude-sonnet-5" }));
        await collect(provider.chatChunks([
            { role: "user", content: "q1" },
            { role: "assistant", content: "a" },
            { role: "user", content: "q2" }
        ], { ...config, model: "claude-haiku-4-5-20251001" }));

        // setModel is a streaming-input-only control: it is why a model change
        // costs ~0 ms instead of a cold start.
        expect(queryMock).toHaveBeenCalledTimes(1);
        expect(setModelMock).toHaveBeenCalledExactlyOnceWith("claude-haiku-4-5-20251001");
    });

    it.each([
        [ "note tools", { enableNoteTools: true }, { enableNoteTools: false } ],
        [ "web search", {}, { enableWebSearch: true } ],
        [ "extended thinking", {}, { enableExtendedThinking: true } ]
    ])("starts a new session when %s, fixed at construction, changes", async (_option, before, after) => {
        const provider = new ClaudeAgentProvider();
        const config = { chatNoteId: "note-fixed" };
        scriptAgent([textDelta("a"), successResult("sess-F")]);
        await collect(provider.chatChunks([{ role: "user", content: "q1" }], { ...config, ...before }));

        // The option is wired into query()'s options and can't be changed on a
        // live session, so this must build a new one (and retire the old).
        scriptAgent([textDelta("b"), successResult("sess-F2")]);
        await collect(provider.chatChunks([
            { role: "user", content: "q1" },
            { role: "assistant", content: "a" },
            { role: "user", content: "q2" }
        ], { ...config, ...after }));

        expect(queryMock).toHaveBeenCalledTimes(2);
        expect(closeMock).toHaveBeenCalled();
    });

    it("closes the session after an aborted turn rather than reusing a half-finished one", async () => {
        const controller = new AbortController();
        const provider = new ClaudeAgentProvider();
        const config = { chatNoteId: "note-abort" };

        // The turn is cancelled mid-stream, so the session's real state is
        // unknown — it must not be handed to the next turn.
        queryMock.mockImplementation(() => makeQuery([textDelta("partial"), successResult("sess-X")]));
        const chunks = await collect(provider.chatChunks(
            [{ role: "user", content: "q" }],
            config,
            (controller.abort(), controller.signal)
        ));

        expect(chunks).toEqual([]);
        expect(closeMock).not.toHaveBeenCalled(); // nothing was started to close

        // A later turn starts a fresh session rather than resuming.
        scriptAgent([textDelta("ok"), successResult("sess-Y")]);
        await collect(provider.chatChunks([{ role: "user", content: "q" }], config));
        expect(queryMock).toHaveBeenCalledTimes(1);
    });

    it("evicts the oldest chat-note mapping once the session cap is exceeded", async () => {
        const provider = new ClaudeAgentProvider();

        scriptAgent([textDelta("r"), successResult("sess-victim")]);
        await collect(provider.chatChunks([{ role: "user", content: "q" }], { chatNoteId: "victim" }));

        // 200 further distinct chat notes push "victim" past the cap.
        for (let i = 0; i < 200; i++) {
            scriptAgent([textDelta("r"), successResult(`sess-${i}`)]);
            await collect(provider.chatChunks([{ role: "user", content: "q" }], { chatNoteId: `filler-${i}` }));
        }

        // This test is about the chat-note → session-id map, not the warm
        // subprocess pool; drop the warm sessions so both follow-ups have to
        // start a query and reveal what they would resume.
        resetClaudeSessionPoolForTests();

        // Despite a perfectly matching transcript, the victim can no longer resume.
        scriptAgent([successResult()]);
        await collect(provider.chatChunks([
            { role: "user", content: "q" },
            { role: "assistant", content: "r" },
            { role: "user", content: "q2" }
        ], { chatNoteId: "victim" }));
        const lastCall = queryMock.mock.calls[queryMock.mock.calls.length - 1][0];
        expect(lastCall.options.resume).toBeUndefined();

        // A recent filler still resumes — only the oldest entry was dropped.
        scriptAgent([successResult()]);
        await collect(provider.chatChunks([
            { role: "user", content: "q" },
            { role: "assistant", content: "r" },
            { role: "user", content: "q2" }
        ], { chatNoteId: "filler-199" }));
        const fillerCall = queryMock.mock.calls[queryMock.mock.calls.length - 1][0];
        expect(fillerCall.options.resume).toBe("sess-199");
    });

    it("closes a session whose stream failed mid-turn instead of handing it to the next turn", async () => {
        const provider = new ClaudeAgentProvider();
        const config = { chatNoteId: "note-broken" };
        const followUp = [
            { role: "user" as const, content: "q1" },
            { role: "assistant" as const, content: "a" },
            { role: "user" as const, content: "q2" }
        ];
        // One stream: the first turn completes, the second fails partway.
        queryMock.mockImplementation(() => Object.assign((async function* () {
            yield textDelta("a");
            yield successResult("sess-B");
            yield textDelta("partial");
            throw new Error("stream broke");
        })(), { setModel: setModelMock, close: closeMock }));
        await collect(provider.chatChunks([{ role: "user", content: "q1" }], config));

        const failed = await collect(provider.chatChunks(followUp, config));
        expect(failed.some(c => c.type === "error")).toBe(true);
        expect(closeMock).toHaveBeenCalledTimes(1);

        // A retry on the same history starts a new query.
        scriptAgent([textDelta("b"), successResult("sess-B")]);
        const retried = await collect(provider.chatChunks(followUp, config));
        expect(queryMock).toHaveBeenCalledTimes(2);
        expect(retried).toContainEqual({ type: "text", content: "b" });
    });

    it("starts a new session after the agent's stream ended mid-turn", async () => {
        const provider = new ClaudeAgentProvider();
        const config = { chatNoteId: "note-ended" };
        scriptAgent([textDelta("cut off")]);
        const chunks = await collect(provider.chatChunks([{ role: "user", content: "q" }], config));
        expect(chunks).toContainEqual({ type: "text", content: "cut off" });

        scriptAgent([textDelta("fresh"), successResult()]);
        await collect(provider.chatChunks([{ role: "user", content: "q" }], config));
        expect(queryMock).toHaveBeenCalledTimes(2);
    });

    it("keeps to the warm-session cap by closing idle sessions behind a busy oldest one", () => {
        const fakeSession = (): ClaudeSession => ({
            query: { close: vi.fn() } as unknown as ClaudeSession["query"],
            input: new Pushable(),
            fingerprint: "",
            closed: false,
            busy: false
        });
        const busy = fakeSession();
        rememberWarmSession("busy", busy);
        const idle: ClaudeSession[] = [];
        for (let i = 0; i < MAX_WARM_SESSIONS; i++) {
            const session = fakeSession();
            rememberWarmSession(`idle-${i}`, session);
            releaseSession(`idle-${i}`, session);
            idle.push(session);
        }

        expect(busy.closed).toBe(false);
        expect(idle.map(s => s.closed)).toEqual([true, ...Array(MAX_WARM_SESSIONS - 1).fill(false)]);
    });
});

describe("generateTitle", () => {
    beforeEach(() => {
        queryMock.mockReset();
        errorLogMock.mockReset();
        infoLogMock.mockReset();
        resetClaudeSessionPoolForTests();
        closeMock.mockClear();
    });

    it("names chats in one shared session on the cheap model, one title at a time", async () => {
        let inFlight = 0;
        let maxInFlight = 0;
        const answered: string[] = [];
        const pushed = scriptTitleAgent(async prompt => {
            inFlight++;
            maxInFlight = Math.max(maxInFlight, inFlight);
            await new Promise(resolve => setTimeout(resolve, 5));
            inFlight--;
            const name = prompt.slice(prompt.lastIndexOf("\n") + 1);
            answered.push(name);
            return [textDelta("streamed noise"), titleResult(`  "${name.toUpperCase()} notes"  `)];
        });

        const provider = new ClaudeAgentProvider();
        await expect(Promise.all([provider.generateTitle("a"), provider.generateTitle("b"), provider.generateTitle("c")]))
            .resolves.toEqual(["A notes", "B notes", "C notes"]);

        expect(answered).toEqual(["a", "b", "c"]);
        expect(maxInFlight).toBe(1);
        await vi.waitFor(() => expect(pushed).toEqual([
            buildTitlePrompt("a"), "/clear", buildTitlePrompt("b"), "/clear", buildTitlePrompt("c"), "/clear"
        ]));
        expect(queryMock).toHaveBeenCalledTimes(1);
        const options = queryMock.mock.calls[0][0].options;
        expect(options).toMatchObject({ model: "claude-haiku-4-5-20251001", maxTurns: 1, persistSession: false });
        expect(options.mcpServers).toBeUndefined();
        expect(closeMock).not.toHaveBeenCalled();
    });

    it("sends the shared title prompt, which tells the agent to ignore earlier titles", async () => {
        const prompts: string[] = [];
        scriptTitleAgent(async prompt => {
            prompts.push(prompt);
            return [titleResult("Title")];
        });

        await new ClaudeAgentProvider().generateTitle("x".repeat(600));

        expect(prompts).toEqual([buildTitlePrompt("x".repeat(600))]);
        expect(prompts[0]).toContain("earlier messages in this conversation do not apply");
    });

    it("states the five-word limit with example titles in the system prompt, since /clear leaves none in the history", async () => {
        scriptTitleAgent(async () => [titleResult("Title")]);

        await new ClaudeAgentProvider().generateTitle("hi");

        const systemPrompt: string = queryMock.mock.calls[0][0].options.systemPrompt;
        expect(systemPrompt).toContain("at most five words");
        const examples = [...systemPrompt.matchAll(/"([^"]+)"/g)].map(match => match[1]).filter(text => /^[A-Z]/.test(text) && text.includes(" "));
        expect(examples.length).toBeGreaterThanOrEqual(2);
        for (const example of examples) {
            expect(example.split(/\s+/).length).toBeLessThanOrEqual(5);
        }
    });

    it("empties the session with /clear after a title, without holding that title back", async () => {
        let releaseClear = () => {};
        const gate = new Promise<void>(resolve => {
            releaseClear = resolve;
        });
        const pushed = scriptTitleAgent(
            async prompt => [titleResult(prompt.slice(prompt.lastIndexOf("\n") + 1).toUpperCase())],
            async () => {
                await gate;
                return clearedMessages();
            }
        );
        const provider = new ClaudeAgentProvider();

        await expect(provider.generateTitle("a")).resolves.toBe("A");
        const second = provider.generateTitle("b");
        await vi.waitFor(() => expect(pushed).toEqual([buildTitlePrompt("a"), "/clear"]));

        releaseClear();
        await expect(second).resolves.toBe("B");
        expect(pushed.slice(0, 3)).toEqual([buildTitlePrompt("a"), "/clear", buildTitlePrompt("b")]);
        expect(queryMock).toHaveBeenCalledTimes(1);
    });

    it("keeps one session however many titles it answers", async () => {
        scriptTitleAgent(async () => [titleResult("Title")]);
        const provider = new ClaudeAgentProvider();

        for (let i = 0; i < MAX_TITLES_PER_SESSION + 5; i++) {
            await expect(provider.generateTitle("hi")).resolves.toBe("Title");
        }

        expect(queryMock).toHaveBeenCalledTimes(1);
        expect(closeMock).not.toHaveBeenCalled();
    });

    it("replaces the title session when a title or a /clear fails, or its stream ended", async () => {
        let clears = 0;
        scriptTitleAgent(async prompt => {
            if (prompt.endsWith("boom")) {
                throw new Error("agent crashed");
            }
            if (prompt.endsWith("quit")) {
                return null;
            }
            return [titleResult("Title")];
        }, async () => {
            clears++;
            if (clears === 1) {
                throw new Error("clear crashed");
            }
            return clears === 2 ? null : clearedMessages();
        });
        const provider = new ClaudeAgentProvider();

        // A /clear that throws closes the session, and the next title starts another.
        await expect(provider.generateTitle("hi")).resolves.toBe("Title");
        await expect(provider.generateTitle("hi")).resolves.toBe("Title");
        expect(queryMock).toHaveBeenCalledTimes(2);
        expect(closeMock).toHaveBeenCalledTimes(1);
        expect(infoLogMock).toHaveBeenCalledWith(expect.stringContaining("clear crashed"));

        // A /clear whose stream ends closes the session too.
        await expect(provider.generateTitle("hi")).resolves.toBe("Title");
        expect(queryMock).toHaveBeenCalledTimes(3);

        // Failed: the session is closed, the failure logged, and the next title starts another.
        await expect(provider.generateTitle("boom")).resolves.toBe("");
        expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("agent crashed"));
        await expect(provider.generateTitle("hi")).resolves.toBe("Title");
        expect(queryMock).toHaveBeenCalledTimes(4);

        // Ended: a stream that stops before its result yields no title, and the next title starts another.
        await expect(provider.generateTitle("quit")).resolves.toBe("");
        await expect(provider.generateTitle("hi")).resolves.toBe("Title");
        expect(queryMock).toHaveBeenCalledTimes(5);
    });

    it("gives up on a title or a /clear that gets no reply in time, so later titles still run", async () => {
        vi.useFakeTimers();
        try {
            const never = new Promise<null>(() => {});
            scriptTitleAgent(async prompt => (prompt.endsWith("hang") ? never : [titleResult("Title")]), async () => never);
            const provider = new ClaudeAgentProvider();

            const hung = provider.generateTitle("hang");
            await vi.advanceTimersByTimeAsync(TITLE_TIMEOUT_MS);
            await expect(hung).resolves.toBe("");
            expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("no reply"));

            const answered = provider.generateTitle("hi");
            await vi.advanceTimersByTimeAsync(0);
            await expect(answered).resolves.toBe("Title");
            const next = provider.generateTitle("hi");
            await vi.advanceTimersByTimeAsync(TITLE_TIMEOUT_MS);
            await expect(next).resolves.toBe("Title");

            expect(queryMock).toHaveBeenCalledTimes(3);
            expect(closeMock).toHaveBeenCalledTimes(2);
        } finally {
            // The last title's /clear hangs as well; let it time out so the next test's titles can run.
            await vi.advanceTimersByTimeAsync(TITLE_TIMEOUT_MS);
            vi.useRealTimers();
        }
    }, 5000);

    it("keeps the session after an unsuccessful result, which leaves it in a known state", async () => {
        scriptTitleAgent(async prompt => (prompt.endsWith("fail")
            ? [{ ...successResult(), subtype: "error_during_execution", is_error: true, errors: [] }]
            : [titleResult("Title")]));
        const provider = new ClaudeAgentProvider();

        await expect(provider.generateTitle("fail")).resolves.toBe("");
        await expect(provider.generateTitle("hi")).resolves.toBe("Title");

        expect(queryMock).toHaveBeenCalledTimes(1);
        expect(closeMock).not.toHaveBeenCalled();
    });

    it("returns an empty title and logs when the agent cannot start", async () => {
        resolveClaudeBinaryMock.mockRejectedValueOnce(new Error("claude not found"));

        await expect(new ClaudeAgentProvider().generateTitle("hi")).resolves.toBe("");
        expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("claude not found"));
    });
});

/**
 * A title session: Claude Code in streaming input mode, answering each title
 * prompt pushed onto its input with what `reply` returns for its text, and each
 * `/clear` with what `clear` returns. `null` ends the stream, as a process that
 * exits does. Returns the texts pushed, in order.
 */
function scriptTitleAgent(
    reply: (prompt: string) => Promise<unknown[] | null>,
    clear: () => Promise<unknown[] | null> = async () => clearedMessages()
): string[] {
    type Pushed = { message: { content: { text: string }[] } };
    const pushed: string[] = [];
    queryMock.mockImplementation(({ prompt }: { prompt: string | AsyncIterable<Pushed> }) => {
        const generator = (async function* () {
            const input = typeof prompt === "string" ? [prompt] : prompt;
            for await (const message of input) {
                const text = typeof message === "string" ? message : message.message.content.map(block => block.text).join("");
                pushed.push(text);
                const messages = await (text === "/clear" ? clear() : reply(text));
                if (!messages) {
                    return;
                }
                yield* messages;
            }
        })();
        return Object.assign(generator, { setModel: setModelMock, close: closeMock });
    });
    return pushed;
}

/** What Claude Code streams for a `/clear`, as recorded from CLI 2.1.287. */
function clearedMessages() {
    return [
        { type: "conversation_reset", trigger: "clear", session_id: "sess-1", new_conversation_id: "conv-2" },
        { type: "system", subtype: "init", session_id: "sess-2" },
        { ...successResult("sess-2"), result: "" }
    ];
}

function titleResult(title: string) {
    return { ...successResult(), result: title };
}

describe("transcript helpers", () => {
    it("hashTranscript is stable across content shapes and sensitive to edits", () => {
        const stringForm = hashTranscript([{ role: "user", content: "hello" }]);
        const partsForm = hashTranscript([{ role: "user", content: [{ type: "text", text: "hello" }] }]);
        expect(stringForm).toBe(partsForm);
        expect(hashTranscript([{ role: "user", content: "hello!" }])).not.toBe(stringForm);
        // Attachment parts flatten to stable placeholders, so re-sent bytes don't break resume.
        const withImage = hashTranscript([{ role: "user", content: [{ type: "image", attachmentId: "a", mime: "image/png" }] }]);
        expect(withImage).toBe(hashTranscript([{ role: "user", content: "[attached image]" }]));
    });

    it("buildSeededPrompt replays the transcript with role labels", () => {
        const prompt = buildSeededPrompt(
            [
                { role: "user", content: "q1" },
                { role: "assistant", content: "a1" }
            ],
            "q2"
        );
        expect(prompt).toContain("User: q1");
        expect(prompt).toContain("Assistant: a1");
        expect(prompt.endsWith("q2")).toBe(true);
    });
});

describe("buildSubscriptionModelList", () => {
    const prices = {
        "claude-opus-5-5": { input: 5, output: 25, ctx: 1000000 },
        "claude-sonnet-5": { input: 3, output: 15, ctx: 1000000 },
        "claude-haiku-4-5-20251001": { input: 1, output: 5, ctx: 200000 }
    };

    it("resolves aliases to canonical ids, dedupes, and takes the context window from the price table", () => {
        const models = buildSubscriptionModelList([
            { value: "sonnet", resolvedModel: "claude-sonnet-5", displayName: "Sonnet 5" },
            { value: "claude-sonnet-5", displayName: "Sonnet 5 (again)" }, // dup of the resolved alias → dropped
            { value: "claude-haiku-4-5-20251001", displayName: "Haiku 4.5" },
            { value: "claude-fable-9" }
        ], prices);

        // Claude Code's order and names; the subscription makes every row free, whatever the API costs.
        expect(models).toEqual([
            { id: "claude-sonnet-5", name: "Sonnet 5", contextWindow: 1000000, pricing: { input: 0, output: 0 }, isSubscription: true, isDefault: true },
            { id: "claude-haiku-4-5-20251001", name: "Haiku 4.5", contextWindow: 200000, pricing: { input: 0, output: 0 }, isSubscription: true },
            // A model the price table has never heard of keeps its id as its name and has no context window.
            { id: "claude-fable-9", name: "claude-fable-9", contextWindow: undefined, pricing: { input: 0, output: 0 }, isSubscription: true }
        ]);
    });

    it("flags the model the `default` alias resolves to, without listing the alias itself", () => {
        const models = buildSubscriptionModelList([
            { value: "default", resolvedModel: "claude-opus-5-5", displayName: "Default (recommended)" },
            { value: "sonnet", resolvedModel: "claude-sonnet-5", displayName: "Sonnet 5" },
            { value: "opus", resolvedModel: "claude-opus-5-5", displayName: "Opus 5.5" }
        ], prices);

        expect(models.map(m => m.name)).toEqual(["Sonnet 5", "Opus 5.5"]);
        expect(models.filter(m => m.isDefault).map(m => m.id)).toEqual(["claude-opus-5-5"]);
    });

    it("gives a long-context id the context window of its base model when the table lacks the variant", () => {
        const [variant] = buildSubscriptionModelList([{ value: "sonnet[1m]", resolvedModel: "claude-sonnet-5[1m]" }], prices);
        expect(variant).toMatchObject({ id: "claude-sonnet-5[1m]", contextWindow: 1000000, isDefault: true });
    });
});

describe("ClaudeAgentProvider.listModels", () => {
    function scriptSupportedModels(models: unknown[] | (() => Promise<unknown[]>)) {
        queryMock.mockReturnValue({
            supportedModels: typeof models === "function" ? models : async () => models
        });
    }

    beforeEach(() => {
        queryMock.mockReset();
        resetSubscriptionModelCacheForTests();
        resolveClaudeBinaryMock.mockClear();
    });

    it("probes the live catalog without running a chat turn", async () => {
        scriptSupportedModels([
            { value: "sonnet", resolvedModel: "claude-sonnet-5", displayName: "Sonnet 5" },
            { value: "claude-fable-9", displayName: "Claude Fable 9" }
        ]);
        const provider = new ClaudeAgentProvider();
        const models = await provider.listModels();

        expect(models.map(m => m.id)).toEqual(["claude-sonnet-5", "claude-fable-9"]);
        expect(models.every(m => m.isSubscription)).toBe(true);
        // The committed price table supplies the context window.
        expect(models[0].contextWindow).toBe(1000000);

        // The probe uses a streaming prompt that yields nothing — never a string,
        // so no user turn (and no tokens) is sent — capped at a single turn.
        const { prompt, options } = queryMock.mock.calls[0][0];
        expect(typeof prompt).not.toBe("string");
        expect(prompt[Symbol.asyncIterator]).toBeTypeOf("function");
        expect(options.maxTurns).toBe(1);
    });

    it("serves the cached list on the next call without re-spawning", async () => {
        scriptSupportedModels([{ value: "claude-sonnet-5", displayName: "Sonnet 5" }]);
        const provider = new ClaudeAgentProvider();
        const first = await provider.listModels();
        // A fresh instance still hits the shared module-level cache.
        const second = await new ClaudeAgentProvider().listModels();

        expect(second).toBe(first);
        expect(queryMock).toHaveBeenCalledTimes(1);
    });

    it("deduplicates concurrent probes into a single spawn", async () => {
        scriptSupportedModels([{ value: "claude-sonnet-5", displayName: "Sonnet 5" }]);
        const provider = new ClaudeAgentProvider();
        // The second call arrives while the first probe is still in flight and
        // shares its promise instead of spawning a second CLI subprocess.
        const [a, b] = await Promise.all([provider.listModels(), provider.listModels()]);

        expect(a).toBe(b);
        expect(queryMock).toHaveBeenCalledTimes(1);
    });

    it("propagates the probe failure so the modal can surface it (e.g. not authenticated)", async () => {
        scriptSupportedModels(async () => {
            throw new Error("Claude Code is not authenticated");
        });
        const provider = new ClaudeAgentProvider();
        await expect(provider.listModels()).rejects.toThrow("not authenticated");
    });

    it("times out when the init handshake never surfaces the catalog", async () => {
        vi.useFakeTimers();
        try {
            // supportedModels() never resolves → the 15s timeout wins the race.
            scriptSupportedModels(() => new Promise<never>(() => {}));
            const provider = new ClaudeAgentProvider();
            const promise = provider.listModels();
            // Surface the rejection now so it isn't reported as unhandled while
            // we advance the clock; assert on it after the timer fires.
            const settled = promise.then(() => "resolved", (e: Error) => e.message);
            await vi.advanceTimersByTimeAsync(15_000);
            expect(await settled).toMatch(/Timed out reading the Claude Code model catalog/);
        } finally {
            vi.useRealTimers();
        }
    });

    it("propagates when Claude Code isn't installed, without spawning a probe", async () => {
        resolveClaudeBinaryMock.mockRejectedValueOnce(new Error("Claude Code CLI not found"));
        const provider = new ClaudeAgentProvider();

        await expect(provider.listModels()).rejects.toThrow("not found");
        expect(queryMock).not.toHaveBeenCalled();
    });

    it("feeds query() a no-input prompt that stays open until teardown, then finishes once aborted", async () => {
        // The probe hands query() a prompt whose iterator never yields a user
        // message — it registers a teardown listener and only resolves `done`
        // once the probe aborts. Drive that iterator here (the mock never would).
        let probeIterator: AsyncIterator<unknown> | undefined;
        let firstPull: Promise<IteratorResult<unknown>> | undefined;
        queryMock.mockImplementation((opts: { prompt: AsyncIterable<unknown> }) => {
            probeIterator = opts.prompt[Symbol.asyncIterator]();
            // Pull once while the probe's controller is still un-aborted: this
            // runs the iterator body and registers the abort ("finish") listener.
            firstPull = probeIterator.next();
            return { supportedModels: async () => [{ value: "claude-sonnet-5", displayName: "Sonnet 5" }] };
        });

        await new ClaudeAgentProvider().listModels();

        // The probe's teardown aborted the controller, resolving the pending pull.
        expect(firstPull).toBeDefined();
        await expect(firstPull).resolves.toEqual({ done: true, value: undefined });

        // A later pull sees the already-aborted signal and finishes immediately.
        expect(probeIterator).toBeDefined();
        await expect(probeIterator?.next()).resolves.toEqual({ done: true, value: undefined });
    });
});

describe("Windows .cmd spawn shim", () => {
    const realPlatform = process.platform;

    function setPlatform(value: string) {
        Object.defineProperty(process, "platform", { value, configurable: true });
    }

    beforeEach(() => {
        queryMock.mockReset();
        spawnMock.mockReset();
    });
    afterEach(() => {
        setPlatform(realPlatform);
        // Restore the default binary path the other suites depend on.
        resolveClaudeBinaryMock.mockReset();
        resolveClaudeBinaryMock.mockImplementation(async () => "/usr/bin/claude");
    });

    it("wraps the CLI spawn in a shell for a .cmd shim on Windows", async () => {
        // Node's spawn() can't execute a .cmd batch file (the npm shim) directly,
        // so the provider installs a spawn override that delegates via a shell.
        setPlatform("win32");
        resolveClaudeBinaryMock.mockResolvedValue("C:\\Users\\me\\claude.cmd");
        scriptAgent([successResult()]);
        await collect(new ClaudeAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));

        const spawnClaudeCodeProcess = queryMock.mock.calls[0][0].options.spawnClaudeCodeProcess;
        expect(spawnClaudeCodeProcess).toBeTypeOf("function");

        const fakeChild = { pid: 123 };
        spawnMock.mockReturnValue(fakeChild);
        const child = spawnClaudeCodeProcess({ command: "claude.cmd", args: ["--print"], cwd: "/tmp", env: { A: "1" }, signal: undefined });

        expect(spawnMock).toHaveBeenCalledWith(
            "claude.cmd",
            ["--print"],
            expect.objectContaining({ shell: true, stdio: "pipe", cwd: "/tmp", env: { A: "1" } })
        );
        expect(child).toBe(fakeChild);
    });

    it("installs no spawn override on non-Windows hosts", async () => {
        setPlatform("linux");
        resolveClaudeBinaryMock.mockResolvedValue("/usr/bin/claude");
        scriptAgent([successResult()]);
        await collect(new ClaudeAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));

        expect(queryMock.mock.calls[0][0].options.spawnClaudeCodeProcess).toBeUndefined();
    });

    it("installs no spawn override for a non-.cmd binary on Windows", async () => {
        setPlatform("win32");
        resolveClaudeBinaryMock.mockResolvedValue("C:\\Users\\me\\claude.exe");
        scriptAgent([successResult()]);
        await collect(new ClaudeAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));

        expect(queryMock.mock.calls[0][0].options.spawnClaudeCodeProcess).toBeUndefined();
    });
});

describe("ClaudeAgentProvider.recommendedModelIds", () => {
    it("applies Anthropic's per-family newest-version rule, not the generic default", () => {
        // The subscription catalog shares Anthropic's id shape, so it recommends
        // one model per family rather than every non-preview, non-legacy model.
        const ids = new ClaudeAgentProvider().recommendedModelIds(
            ["claude-fable-5", "claude-opus-4-8", "claude-opus-4-7", "claude-sonnet-5", "claude-haiku-4-5-20251001"]
                .map(id => ({ id, name: id }))
        );
        expect([...ids].sort()).toEqual([
            "claude-haiku-4-5-20251001", "claude-opus-4-8", "claude-sonnet-5"
        ]);
    });

    it("ranks long-context ids under their base model so they are recommended too", () => {
        // `claude-opus-4-8[1m]` doesn't parse as a family/version on its own; unranked
        // it would be left out even though it is the only Opus row Claude Code offers.
        const ids = new ClaudeAgentProvider().recommendedModelIds(
            ["claude-opus-4-8[1m]", "claude-opus-4-7", "claude-sonnet-5"].map(id => ({ id, name: id }))
        );
        expect([...ids].sort()).toEqual(["claude-opus-4-8[1m]", "claude-sonnet-5"]);
    });
});