/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Prompt links require visible text while mixed text keeps its warning", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Prompt link proof", {".git/config": '[remote "origin"]\n  url = https://github.com/pingdotgg/t3code.git\n'});
    await runPromise(
      Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl!);
        yield* client.subscribeServerConfig({}).pipe(
          Stream.filter((event) => {
            const providers =
              event.type === "snapshot"
                ? event.config.providers
                : event.type === "providerStatuses"
                  ? event.payload.providers
                  : [];
            return providers.some(
              (provider) =>
                provider.instanceId === "devReplay" &&
                provider.models?.some((model) => model.slug === "multi-turn"),
            );
          }),
          Stream.runHead,
        );
      }).pipe(Effect.scoped, Effect.timeout("30 seconds")),
    );

  const hidden = await t3.thread({project, title:"Hidden only", messages:["\u200b"]});
  const mixed = await t3.thread({project, title:"Visible and hidden", messages:["Hello\u200b world"]});
  await browser.addInitScript(() => {
    (window as any).copiedPrompt = "";
    navigator.clipboard.writeText = async (value) => { (window as any).copiedPrompt = value; };
  });
  await t3.open(hidden);
  const composer = screen.getByTestId("composer-editor");
  await composer.waitFor();
  await screen.getByRole("button", /^Agent/).tap();
  // Capture the sent-message action state before any copy or paste.
  await screen.getByRole("button", "Copy message", {exact:true}).first().hover();
  await app.screenshot("hidden-sent-actions");
  const hiddenSent = await browser.locator('button[aria-label="Copy prompt link"]').count();
  await composer.fill("\u200b");
  await browser.keyboard.press("Control+k");
  const palette = screen.getByRole("dialog", "Command palette");
  await palette.getByRole("combobox").fill("> Copy prompt link");
  await app.screenshot("hidden-draft-palette");
  const hiddenActions = await palette.getByRole("option").count();
  await browser.keyboard.press("Escape");
  await composer.fill(" ");
  await t3.open("/new?prompt=%E2%80%8B");
  await screen.getByText(/This prompt had only hidden characters/).waitFor();
  await app.screenshot("hidden-link-receiver");
  await t3.open(mixed);
  await composer.waitFor();
  await screen.getByRole("button", /^Agent/).tap();
  await screen.getByRole("button", "Copy message", {exact:true}).first().hover();
  await app.screenshot("mixed-sent-actions");
  await screen.getByRole("button", "Copy prompt link", {exact:true}).tap();
  const copied = await browser.evaluate(() => (window as any).copiedPrompt as string);
  await composer.fill(copied);
  await app.screenshot("mixed-sent-copied-url");
  await composer.fill("Hello\u200b world");
  await browser.keyboard.press("Control+k");
  await palette.getByRole("combobox").fill("> Copy prompt link");
  await app.screenshot("mixed-draft-palette");
  await browser.keyboard.press("Escape");
  await t3.open("/new?prompt=Hello%E2%80%8B%20world&repo=pingdotgg/t3code");
  await screen.getByText("This prompt had hidden characters, it may be malicious", {exact:true}).waitFor();
  await app.screenshot("mixed-link-receiver");
  expect(new URL(copied).searchParams.get("prompt")).toBe("Hello\u200b world");
  expect(hiddenSent).toBe(0);
  expect(hiddenActions).toBe(0);
});
