/// <reference lib="dom" />
import { readFileSync, writeFileSync } from "node:fs";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Bracket display math stays typeset while the reply streams", WEB, async ({ t3, app, screen, browser }) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = readFileSync(fixture, "utf8");
  const chunk = (text: string, afterMs = 30) => ({ type: "emit_inbound", afterMs, frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } } });
  const recording = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    chunk("Bracket display math:\n\n\\[\nx\n\ny\n\\]\n\nThe turn keeps streaming."),
    ...Array.from({ length: 25 }, (_, i) => chunk(`\n\nStill streaming ${i + 1}.`, 1000)),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  writeFileSync(fixture, recording.map((entry) => JSON.stringify(entry)).join("\n"));
  try {
    await t3.project("math-demo");
    await t3.open("/settings/appearance");
    await screen.getByRole("switch", "Render math", { exact: true }).tap();
    await t3.open();
    await screen.getByRole("textbox").waitFor();
    await browser.evaluate(() => window.t3dev!.replay("showcase"));
    await screen.getByText("Still streaming 5.", { exact: false }).waitFor();
    await screen.getByRole("button", "Stop generation").waitFor();
    await app.screenshot("display-math-while-streaming");
    const display = await browser.evaluate(() => document.querySelectorAll('[data-markdown-math="display"] svg').length);
    expect(display).toBe(1);
  } finally {
    writeFileSync(fixture, original);
  }
});
