import * as FS from "node:fs/promises";
import * as Path from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Bash clobber redirect preserves the live program label", WEB, async ({t3, app, screen}) => {
  const project = await t3.project("command-label-proof");
  const seed = await t3.thread({project, title: "Setup", messages: ["Hello"]});
  const settingsPath = Path.join(T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await FS.readFile(settingsPath, "utf8"));
  settings.providerInstances.opencode = {driver: "opencode", enabled: true, config: {binaryPath: "opencode"}};
  await FS.writeFile(settingsPath, JSON.stringify(settings));
  await t3.open(seed);
  const {cli} = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project,
    "Use your Bash tool to run exactly this command, verbatim, without changing it or wrapping it: 2>|/dev/null sleep 20 . The final period is punctuation and is not part of the command. Do not run any other command.",
    "--title", "Bash clobber redirect", "--provider", "opencode", "--model", "openai/gpt-6-luna", "--json"]));
  const {threadId} = JSON.parse(started.stdout);
  await t3.open({threadId});
  await screen.getByText(/^Running (command|sleep)$/).first().waitFor({timeout: 120000});
  try {
    await expect(screen.getByText("Running sleep", {exact: true}).first()).toBeVisible({timeout: 1000});
  } finally {
    await app.screenshot("live-clobber-command-label");
    await screen.getByRole("button", /^Running (command|sleep)$/).tap();
    await screen.getByText("2>|/dev/null sleep 20", {exact: true}).first().waitFor();
    await app.screenshot("verbatim-bash-command");
  }
});
