import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "e2e";
import { APP_DIR, MOBILE, MOBILE_T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise } from "./t3.ts";
import { IOS, test } from "./t3-mobile.ts";

test("Mobile local clear keeps Send while a replay turn runs", IOS, async ({ t3, app, screen }) => {
  // Only the replay model's second response is lengthened, so device actions fit inside a turn.
  const recording = join(APP_DIR, "apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson");
  const original = await readFile(recording, "utf8");
  const prompt = {type: "expect_outbound", frame: {kind: "request", method: "session/prompt", params: "<any>"}};
  const response = {type: "emit_inbound", frame: {kind: "response", method: "session/prompt", result: {stopReason: "end_turn"}}};
  const message = (text: string) => ({type: "emit_inbound", frame: {kind: "notification", method: "session/update", params: {sessionId: "replay", update: {sessionUpdate: "agent_message_chunk", content: {type: "text", text}}}}});
  try {
    const project = await t3.project("Composer demo");
    const thread = await t3.thread({project, title: "Local command actions", messages: ["Review the sample project"], model: "multi-turn"});
  await writeFile(recording, [prompt, message("Reviewing the synthetic project. ".repeat(1200)), response].map(x => JSON.stringify(x)).join("\n") + "\n");
    await t3.open();
    await screen.getByText("Local command actions", {exact: false}).first().tap({timeout: 120000});
    const composer = screen.getByRole("textbox");
    await composer.fill("Review the project again");
    await screen.getByRole("button", "Send", {exact: true}).tap();
    await screen.getByRole("button", "Stop agent").waitFor({state: "visible"});
    const { cli } = makeState(MOBILE_T3_HOME, { T3CODE_PORT: String(MOBILE.serverPort) });
    await runPromise(cli(["thread", "send", thread.threadId, "Check formatting after the current review"]));
    await composer.fill("An ordinary follow-up");
    await app.screenshot("mobile-ordinary-with-queue");
    await composer.fill("/clear");
    await app.screenshot("mobile-clear-while-running");
    await expect(screen.getByRole("button", "Send", {exact: true})).toBeVisible();
  } finally {
    await writeFile(recording, original);
  }
});
