import { expect } from "e2e";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("/compact stays in the slash menu and queues during a running turn", WEB, async ({ t3, app, screen, browser }) => {
  // Replay supplies streaming; advertise the provider commands needed for this UI reproduction.
  const source = join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts");
  const agent = join(T3_HOME, "compact-replay.ts");
  const replay = (await readFile(source, "utf8"))
    .replace('const cwd = typeof params.cwd === "string" ? params.cwd : process.cwd();', 'const cwd = "demo";')
    .replace("new URL(scenario.file, import.meta.url)", `new URL(scenario.file, ${JSON.stringify(pathToFileURL(source).href)})`)
    .replace('sessions.set(sessionId', `send({ method: "session/update", params: { sessionId, update: { sessionUpdate: "available_commands_update", availableCommands: [{ name: "compact", description: "Compact conversation history" }, { name: "autocompact", description: "Configure automatic compaction" }] } } });
        sessions.set(sessionId`);
  await writeFile(agent, replay);
  const settingsPath = join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  settings.providerInstances.devReplay.config.commandArgs = [agent];
  await writeFile(settingsPath, JSON.stringify(settings));
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Compact during work", messages: ["Hello"], model: "showcase" });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.fill("/compa");
  await app.screenshot("idle-compact-menu");
  await composer.fill("Without using any tools, write the numbers from 1 to 600 in words, one per line.");
  await composer.press("Enter");
  await screen.getByRole("button", "Stop generation").waitFor({ state: "visible" });
  await composer.fill("/compact");
  await app.screenshot("running-compact-menu");
  // Record Enter on both commits before asserting the difference.
  await composer.press("Enter");
  await app.screenshot("after-enter");
  const afterEnter = await browser.evaluate(() => document.querySelector('[role="textbox"]')?.textContent ?? "");
  await composer.press("Enter");
  await app.screenshot("queued-command");
  expect(afterEnter.trim()).toBe("/compact");
  await expect(screen.getByRole("button", "Edit queued message")).toBeVisible();
});
