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

test("Interrupted color code preserves subsequent CJK command output", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("build-demo", {
    "build.sh": "printf '\\033[3'; printf '构建失败，请检查日志。\\n第二行输出\\n'",
  });
  await chmod(`${project}/build.sh`, 0o755);
  const output = execFileSync("/bin/sh", ["./build.sh"], { cwd: project, encoding: "utf8" });
  const update = (value: unknown) => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: value } } });
  const frames = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    update({ sessionUpdate: "tool_call", toolCallId: "build", kind: "execute", title: "./build.sh", status: "in_progress", rawInput: { command: "./build.sh" } }),
    update({ sessionUpdate: "tool_call_update", toolCallId: "build", status: "completed", rawOutput: output }),
    update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "The build script finished." } }),
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  await writeFile(`${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`, frames.map(x => JSON.stringify(x)).join("\n") + "\n");
  const thread = await t3.thread({ project, title: "Interrupted color code", messages: ["Run ./build.sh exactly once and tell me what it printed."], model: "command-output" });
  await t3.open(thread);
  await screen.getByRole("button", "Worked for", { exact: false }).tap();
  await screen.getByRole("button", "./build.sh", { exact: true }).first().tap();
  await app.screenshot("expanded-command-output");
  await expect(screen.getByText("建失败，请检查日志。", { exact: false })).toBeVisible();
  await expect(screen.getByText("第二行输出", { exact: false })).toBeVisible();
});
