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

test("Unfinished terminal strings preserve history and suppress continuation after reload", WEB, async ({t3, app, browser, screen}) => {
  const sizes = [4095,4096,4097,524287,524288,524289];
  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("Meta+a");
    return browser.evaluate(()=>{const el=document.querySelector<HTMLTextAreaElement>('[aria-label="Terminal input"]')!;el.dispatchEvent(new ClipboardEvent("copy",{bubbles:true}));return el.value;});
  };
  const results=[];
  for(const n of sizes){
    await input.focus(); await browser.keyboard.press("Control+u"); await browser.keyboard.type(`sh osc-${n}.sh\n`);
    await expect.poll(()=>read(`ready-${n}`),{timeout:60000}).toBe("");
    // The gate file is empty; stat distinguishes it from an absent file.
    await expect.poll(()=>readFile(`${project}/ready-${n}`).then(()=>true).catch(()=>false),{timeout:60000}).toBe(true);
    await browser.evaluate(()=>{location.reload();return null;});
    await expect(input).toHaveAttribute("data-workspace-focus-default","");
    await writeFile(`${project}/release-${n}`,"go");
    await expect.poll(text,{timeout:60000}).toContain(`DONE ${n}`);
    const output=await text();
    await browser.keyboard.press("ArrowRight");
    await app.screenshot(`osc-${n}-reattached`);
    results.push({size:n,history:output.includes(`HISTORY-SENTINEL OSC ${n}`),leak:output.includes("TAIL-LEAK")});
  }
  console.log(JSON.stringify(results));
  expect(results).toEqual(sizes.map(size=>({size,history:true,leak:false})));
});
