Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

16.0 KB
Raw Blame
// @vitest-environment jsdom

import { act, renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useChat } from "./use-chat";
import fixture from "../../../../types/fixtures/views.conformance.json";

const mocks = vi.hoisted(() => ({
  signal: undefined as AbortSignal | undefined,
  getConversation: vi.fn(),
  postChatMessage: vi.fn(),
}));

vi.mock("@/lib/api/chat", () => ({
  getConversation: mocks.getConversation,
  postChatMessage: mocks.postChatMessage,
}));

describe("useChat lifecycle", () => {
  beforeEach(() => {
    mocks.signal = undefined;
    mocks.getConversation.mockReset();
    mocks.postChatMessage.mockReset();
    mocks.postChatMessage.mockImplementation(
      (_repoId: string, options: { signal?: AbortSignal }) => {
        mocks.signal = options.signal;
        return new Promise<Response>(() => undefined);
      },
    );
  });

  it("aborts an in-flight request when its repository owner unmounts", () => {
    const { result, unmount } = renderHook(() => useChat("r1"));

    act(() => {
      void result.current.sendMessage("Explain this page");
    });
    expect(mocks.signal?.aborted).toBe(false);

    unmount();
    expect(mocks.signal?.aborted).toBe(true);
  });

  it("clears repository-scoped state when the repository changes", () => {
    const { result, rerender } = renderHook(
      ({ repoId }) => useChat(repoId),
      { initialProps: { repoId: "r1" } },
    );

    act(() => {
      void result.current.sendMessage("Explain repository one");
    });
    expect(result.current.messages).toHaveLength(2);
    const firstSignal = mocks.signal;

    rerender({ repoId: "r2" });

    expect(firstSignal?.aborted).toBe(true);
    expect(result.current.messages).toEqual([]);
    expect(result.current.conversationId).toBeNull();
  });

  it("cancels streaming without erasing the conversation", () => {
    const { result } = renderHook(() => useChat("r1"));

    act(() => {
      void result.current.sendMessage("Explain this page");
    });
    expect(result.current.messages).toHaveLength(2);
    expect(result.current.isStreaming).toBe(true);

    act(() => result.current.cancel());

    expect(mocks.signal?.aborted).toBe(true);
    expect(result.current.messages).toHaveLength(2);
    expect(result.current.messages.at(-1)?.isStreaming).toBe(false);
    expect(result.current.isStreaming).toBe(false);
  });

  it("buffers rapid text deltas until the next animation frame", async () => {
    let frame: FrameRequestCallback | undefined;
    vi.stubGlobal(
      "requestAnimationFrame",
      vi.fn((callback: FrameRequestCallback) => {
        frame = callback;
        return 1;
      }),
    );
    vi.stubGlobal("cancelAnimationFrame", vi.fn());
    let streamController!: ReadableStreamDefaultController<Uint8Array>;
    const stream = new ReadableStream<Uint8Array>({
      start(controller) {
        streamController = controller;
      },
    });
    mocks.postChatMessage.mockImplementationOnce(
      (_repoId: string, options: { signal?: AbortSignal }) => {
        mocks.signal = options.signal;
        return Promise.resolve(new Response(stream));
      },
    );
    const { result } = renderHook(() => useChat("r1"));

    act(() => {
      void result.current.sendMessage("Explain this page");
    });
    await act(async () => {
      streamController.enqueue(
        new TextEncoder().encode(
          ["a", "b", "c"]
            .map((text) => `data: ${JSON.stringify({ type: "text_delta", text })}\n`)
            .join(""),
        ),
      );
      await Promise.resolve();
      await Promise.resolve();
    });

    expect(result.current.messages.at(-1)?.text).toBe("");
    expect(requestAnimationFrame).toHaveBeenCalledTimes(1);
    act(() => frame?.(16));
    expect(result.current.messages.at(-1)?.text).toBe("abc");

    act(() => result.current.cancel());
    vi.unstubAllGlobals();
  });

  it.each([
    ["an errored read", { error: "no git metadata available" }, "error"],
    ["a good read", { targets: { "a.py": {} } }, "done"],
  ] as const)("marks %s on the tool call", async (_label, data, expected) => {
    // The server reports an unservable read as an `error` key. Before this,
    // tool_result set "done" unconditionally, so a failed read rendered
    // identically to a good one and the answer above it looked evidence-backed.
    let streamController!: ReadableStreamDefaultController<Uint8Array>;
    const stream = new ReadableStream<Uint8Array>({
      start(controller) {
        streamController = controller;
      },
    });
    mocks.postChatMessage.mockImplementationOnce(() =>
      Promise.resolve(new Response(stream)),
    );
    const { result } = renderHook(() => useChat("r1"));

    act(() => {
      void result.current.sendMessage("What is risky here?");
    });
    await act(async () => {
      streamController.enqueue(
        new TextEncoder().encode(
          [
            `data: ${JSON.stringify({
              type: "tool_start",
              tool_id: "t1",
              tool_name: "get_risk",
              input: {},
            })}
`,
            `data: ${JSON.stringify({
              type: "tool_result",
              tool_id: "t1",
              tool_name: "get_risk",
              summary: "Risk assessment",
              artifact: { type: "risk_report", data },
            })}
`,
          ].join(""),
        ),
      );
      await Promise.resolve();
      await Promise.resolve();
    });

    expect(result.current.messages.at(-1)?.toolCalls?.[0]?.status).toBe(expected);

    act(() => result.current.cancel());
  });

  it.each(["resolve", "reject"] as const)(
    "ignores a late conversation %s from the previous repository",
    async (outcome) => {
      let resolveLoad!: (value: unknown) => void;
      let rejectLoad!: (reason: unknown) => void;
      mocks.getConversation.mockReturnValueOnce(
        new Promise((resolve, reject) => {
          resolveLoad = resolve;
          rejectLoad = reject;
        }),
      );
      const { result, rerender } = renderHook(
        ({ repoId }) => useChat(repoId),
        { initialProps: { repoId: "r1" } },
      );

      let loading!: Promise<void>;
      act(() => {
        loading = result.current.loadConversation("c1");
      });
      rerender({ repoId: "r2" });
      await act(async () => {
        if (outcome === "resolve") {
          resolveLoad({
            messages: [
              {
                id: "m1",
                conversation_id: "c1",
                role: "assistant",
                content: { text: "Repository one" },
                created_at: "2026-08-28T00:00:00Z",
              },
            ],
          });
        } else {
          rejectLoad(new Error("Repository one failed"));
        }
        await loading;
      });

      expect(result.current.messages).toEqual([]);
      expect(result.current.error).toBeNull();
    },
  );

  it("lets only the newest conversation load update state", async () => {
    let resolveFirst!: (value: unknown) => void;
    let resolveSecond!: (value: unknown) => void;
    mocks.getConversation
      .mockReturnValueOnce(new Promise((resolve) => { resolveFirst = resolve; }))
      .mockReturnValueOnce(new Promise((resolve) => { resolveSecond = resolve; }));
    const { result } = renderHook(() => useChat("r1"));
    let first!: Promise<void>;
    let second!: Promise<void>;
    act(() => {
      first = result.current.loadConversation("c1");
      second = result.current.loadConversation("c2");
    });
    const response = (id: string, text: string) => ({ messages: [{ id: `m-${id}`, conversation_id: id, role: "assistant", content: { text }, created_at: "2026-08-28T00:00:00Z" }] });
    await act(async () => { resolveSecond(response("c2", "newest")); await second; });
    await act(async () => { resolveFirst(response("c1", "stale")); await first; });
    expect(result.current.conversationId).toBe("c2");
    expect(result.current.messages[0]?.text).toBe("newest");
  });

  it("does not restore a load that resolves after reset", async () => {
    let resolveLoad!: (value: unknown) => void;
    mocks.getConversation.mockReturnValueOnce(new Promise((resolve) => { resolveLoad = resolve; }));
    const { result } = renderHook(() => useChat("r1"));
    let loading!: Promise<void>;
    act(() => { loading = result.current.loadConversation("c1"); });
    act(() => result.current.reset());
    await act(async () => {
      resolveLoad({ messages: [{ id: "m1", conversation_id: "c1", role: "assistant", content: { text: "stale" }, created_at: "2026-08-28T00:00:00Z" }] });
      await loading;
    });
    expect(result.current.messages).toEqual([]);
    expect(result.current.conversationId).toBeNull();
  });

  it("stores artifact mutations outside transcript messages", () => {
    const { result } = renderHook(() => useChat("r1"));
    const artifact = { id: "a1", version: 1 as const, type: "risk", tool_name: "get_risk", presentation: "risk", pinned: true, data: {} };
    const messages = result.current.messages;
    act(() => result.current.replaceArtifact(artifact));
    expect(result.current.artifactOverrides.a1).toEqual(artifact);
    expect(result.current.messages).toBe(messages);
  });

});

describe("useChat grounding and truncation events", () => {
  function streamed(events: object[]) {
    let streamController!: ReadableStreamDefaultController<Uint8Array>;
    const stream = new ReadableStream<Uint8Array>({
      start(controller) {
        streamController = controller;
      },
    });
    mocks.postChatMessage.mockImplementationOnce(
      (_repoId: string, options: { signal?: AbortSignal }) => {
        mocks.signal = options.signal;
        return Promise.resolve(new Response(stream));
      },
    );
    return async () => {
      streamController.enqueue(
        new TextEncoder().encode(
          events.map((event) => `data: ${JSON.stringify(event)}\n`).join(""),
        ),
      );
      streamController.close();
      await Promise.resolve();
      await Promise.resolve();
    };
  }

  const artifact = {
    id: "art-1",
    version: 1 as const,
    type: "context",
    tool_name: "get_context",
    presentation: "context",
    data: { targets: { "src/a.py": {} } },
  };

  it("records a grounding read as a completed step made for the page", async () => {
    const push = streamed([
      {
        type: "grounding",
        tool_id: "grounding-1",
        tool_name: "get_context",
        input: { targets: ["src/a.py"] },
        summary: "src/a.py",
        artifact,
      },
      { type: "done", conversation_id: "c1", message_id: "m1" },
    ]);
    const { result } = renderHook(() => useChat("r1"));

    await act(async () => {
      const sending = result.current.sendMessage("What does this do?");
      await push();
      await sending;
    });

    const step = result.current.messages.at(-1)?.toolCalls[0];
    expect(step).toMatchObject({
      id: "grounding-1",
      name: "get_context",
      status: "done",
      origin: "grounding",
      summary: "src/a.py",
      arguments: { targets: ["src/a.py"] },
    });
    expect(step?.artifact?.id).toBe("art-1");
    expect(result.current.isStreaming).toBe(false);
    expect(result.current.error).toBeNull();
  });

  it("carries the turn's next steps onto the answer", async () => {
    const followUps = [
      { text: "Which decisions govern a.py?", source: "followup", toolHint: "get_why" },
    ];
    const push = streamed([
      { type: "suggestions", suggestions: followUps },
      { type: "done", conversation_id: "c1", message_id: "m1" },
    ]);
    const { result } = renderHook(() => useChat("r1"));

    await act(async () => {
      const sending = result.current.sendMessage("Is a.py risky?");
      await push();
      await sending;
    });

    expect(result.current.messages.at(-1)?.followUps).toEqual(followUps);
  });

  it("drops the last turn's next steps when a new conversation starts", async () => {
    const push = streamed([
      {
        type: "suggestions",
        suggestions: [{ text: "Which decisions govern a.py?", source: "followup" }],
      },
      { type: "done", conversation_id: "c1", message_id: "m1" },
    ]);
    const { result } = renderHook(() => useChat("r1"));

    await act(async () => {
      const sending = result.current.sendMessage("Is a.py risky?");
      await push();
      await sending;
    });
    expect(result.current.messages.at(-1)?.followUps).toHaveLength(1);

    act(() => result.current.reset());
    expect(result.current.messages).toEqual([]);
  });

  it("flags the answer when the server reports the step ceiling", async () => {
    const push = streamed([
      { type: "truncated", loops: 10 },
      { type: "done", conversation_id: "c1", message_id: "m1" },
    ]);
    const { result } = renderHook(() => useChat("r1"));

    await act(async () => {
      const sending = result.current.sendMessage("loop");
      await push();
      await sending;
    });

    expect(result.current.messages.at(-1)?.truncated).toBe(true);
    expect(result.current.messages.at(-1)?.isStreaming).toBe(false);
    expect(result.current.error).toBeNull();
  });

  it("marks the figures the numeric check could not find", async () => {
    const spans = [{ text: "17", start: 9, end: 11 }];
    const push = streamed([
      { type: "text_delta", text: "a.py has 17 callers." },
      {
        type: "diagnostics",
        figures_checked: 1,
        figures_unverified: 1,
        unverified_figures: spans,
      },
      { type: "done", conversation_id: "c1", message_id: "m1" },
    ]);
    const { result } = renderHook(() => useChat("r1"));

    await act(async () => {
      const sending = result.current.sendMessage("callers?");
      await push();
      await sending;
    });

    expect(result.current.messages.at(-1)?.unverifiedFigures).toEqual(spans);
  });

  it("shows a show_view call as a step and puts its view on the answer", async () => {
    const view = fixture.valid.c1;
    const receipt = { view_id: "c1", kind: "chart", title: view.title };
    const push = streamed([
      { type: "tool_start", tool_id: "t2", tool_name: "show_view", input: { view: "table" } },
      {
        type: "tool_result",
        tool_id: "t2",
        tool_name: "show_view",
        summary: "Built a chart",
        artifact: { ...artifact, id: "art-2", tool_name: "show_view", data: receipt },
      },
      { type: "view", tool_id: "t2", view },
      // A repeat id and a part that does not validate are both dropped.
      { type: "view", tool_id: "t2", view },
      { type: "view", tool_id: "t3", view: { id: "v9", kind: "table" } },
      { type: "done", conversation_id: "c1", message_id: "m1" },
    ]);
    const { result } = renderHook(() => useChat("r1"));

    await act(async () => {
      const sending = result.current.sendMessage("chart it");
      await push();
      await sending;
    });

    const answer = result.current.messages.at(-1);
    expect(answer?.toolCalls).toEqual([
      {
        id: "t2",
        name: "show_view",
        arguments: { view: "table" },
        result: receipt,
        summary: "Built a chart",
        status: "done",
      },
    ]);
    expect(answer?.views?.map((part) => part.id)).toEqual(["c1"]);
    expect(answer?.isStreaming).toBe(false);
    expect(result.current.error).toBeNull();
  });

  it("marks a refused show_view step as failed and adds no view", async () => {
    const push = streamed([
      { type: "tool_start", tool_id: "t2", tool_name: "show_view", input: {} },
      {
        type: "tool_result",
        tool_id: "t2",
        tool_name: "show_view",
        summary: "Error: insufficient coverage",
        artifact: {
          ...artifact,
          id: "art-2",
          tool_name: "show_view",
          data: { error: "insufficient coverage", error_code: "insufficient_coverage" },
        },
      },
      { type: "done", conversation_id: "c1", message_id: "m1" },
    ]);
    const { result } = renderHook(() => useChat("r1"));

    await act(async () => {
      const sending = result.current.sendMessage("chart it");
      await push();
      await sending;
    });

    const answer = result.current.messages.at(-1);
    expect(answer?.toolCalls[0]?.status).toBe("error");
    expect(answer).not.toHaveProperty("views");
  });
});