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

test("Manual compaction remains available with the user prompt beyond the loaded page", WEB, async ({ t3, app, screen }) => {
  const agentPath = `${APP_DIR}/apps/server/scripts/dev-replay-agent.ts`;
  const transcriptPath = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const agent = await readFile(agentPath, "utf8");
  const transcript = await readFile(transcriptPath, "utf8");
  // Give the replay provider the same compact command and large tool output as the report.
  const frames: unknown[] = [{type: "expect_outbound", frame: {kind: "request", method: "session/prompt", params: "<any>"}}];
  const update = (value: unknown) => frames.push({type: "emit_inbound", afterMs: 0, frame: {kind: "notification", method: "session/update", params: {sessionId: "replay", update: value}}});
  update({sessionUpdate: "available_commands_update", availableCommands: [{name: "compact", description: "Summarize the conversation and reduce context usage", input: null}]});
  for (let i = 1; i <= 141; i++) {
    update({sessionUpdate: "tool_call", toolCallId: `dump-${i}`, kind: "execute", title: `Run ./dump.sh (${i}/141)`, status: "in_progress", rawInput: {command: "./dump.sh"}});
    update({sessionUpdate: "tool_call_update", toolCallId: `dump-${i}`, status: "completed", content: [{type: "content", content: {type: "text", text: "Synthetic command output for history pagination.\n".repeat(1150)}}]});
  }
  update({sessionUpdate: "agent_message_chunk", content: {type: "text", text: "All 141 command calls finished. The synthetic output is stored in the conversation history."}});
  frames.push({type: "emit_inbound", frame: {kind: "response", method: "session/prompt", result: {stopReason: "end_turn"}}});
  try {
    await writeFile(agentPath, agent.replace('const REPLAYED_UPDATES = new Set([', 'const REPLAYED_UPDATES = new Set(["available_commands_update",'));
    await writeFile(transcriptPath, frames.map(frame => JSON.stringify(frame)).join("\n"));
    const project = await t3.project("compaction-demo", {"dump.sh": "#!/bin/sh\nprintf 'Synthetic output\\n'\n"});
    const thread = await t3.thread({project, title: "Long tool history", model: "showcase", messages: ["Run ./dump.sh 140 separate times as separate shell tool calls, then summarize."]});
    await t3.open(thread);
    await screen.getByRole("button", "Load earlier turns", {exact: false}).waitFor({state: "visible"});
    await screen.getByRole("textbox").fill("/comp");
    await app.screenshot("compact-with-unloaded-history");
    await expect(screen.getByRole("option", "/compact", {exact: false})).toBeVisible();
  } finally {
    await writeFile(agentPath, agent);
    await writeFile(transcriptPath, transcript);
  }
});
