/// <reference lib="dom" />
import { readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("A completed oversized OSC does not displace earlier terminal history", WEB, async ({t3, app, browser, screen}) => {
  const sizes: number[] = [];
  const files: Record<string,string> = {};
  for (const n of sizes) files[`osc-${n}.sh`] = `stty -echo\nprintf '\\033cHISTORY-SENTINEL OSC ${n}\\r\\n'\nprintf '\\033]0;'; head -c ${n-4} /dev/zero | tr '\\000' x\ntouch ready-${n}\nwhile [ ! -f release-${n} ]; do sleep 0.1; done\nprintf 'TAIL-LEAK\\007DONE ${n}\\r\\n'\n`;
  const project = await t3.project("terminal-proof",files);
  const thread = await t3.thread({project,title:"Terminal sequence proof",messages:["Start"]});
  await browser.setViewport({width:1440,height:1080});
  await t3.open(thread);
  await screen.getByRole("button","Toggle terminal drawer").tap();
  const input=screen.getByRole("textbox","Terminal input");
  await expect(input).toHaveAttribute("data-workspace-focus-default","");
  const read=async(name:string)=>readFile(`${project}/${name}`,"utf8").catch(()=>"");
  await expect.poll(async()=>{ await input.focus(); await browser.keyboard.type("PS1='$ '; export PS1; exec /bin/sh\n"); await browser.keyboard.type("echo ready > shell-ready\n"); return read("shell-ready"); },{timeout:30000}).toBe("ready\n");
  const text=async()=>{
    await input.focus();
    await browser.keyboard.press("Control+Shift+a");
    return browser.evaluate(()=>{const el=document.querySelector<HTMLTextAreaElement>('[aria-label="Terminal input"]')!;el.dispatchEvent(new ClipboardEvent("copy",{bubbles:true}));return el.value;});
  };
  await writeFile(`${project}/completed-osc.sh`, "stty -echo\nprintf '\\033cHISTORY-SENTINEL LARGE OSC\\r\\n'\nprintf '\\033]0;stuck'; seq 1 2000000; printf '\\007DONE-LARGE\\r\\n'\n");
  await input.focus(); await browser.keyboard.press("Control+u");
  await browser.keyboard.type("sh completed-osc.sh\n");
  await expect.poll(text,{timeout:120000}).toContain("DONE-LARGE");
  await app.screenshot("completed-osc-before-reattach");
  await browser.evaluate(()=>{location.reload();return null;});
  await expect(input).toHaveAttribute("data-workspace-focus-default","");
  await expect.poll(text,{timeout:60000}).toContain("DONE-LARGE");
  const output=await text();
  await app.screenshot("completed-osc-after-reattach");
  expect(output).toContain("HISTORY-SENTINEL LARGE OSC");
});
