/// <reference lib="dom" />
// The DOM lib types the functions this scenario runs in the page.
import { expect } from "e2e";

import { test, WEB } from "./t3.ts";

const countHistoryRequests = () =>
  performance
    .getEntriesByType("resource")
    .filter((entry) => /\/api\/orchestration\/threads\/[^/]+\/history/.test(entry.name)).length;

test(
  "One Arrow Up loads at most one earlier history page",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("prompt-recall-pages");
    // Every turn here is started by an agent, so no page holds a prompt the composer recalls.
    const thread = await t3.thread({
      project,
      title: "Agent turns",
      messages: Array.from({ length: 200 }, (_, index) => `Agent turn ${index + 1}`),
    });
    await t3.open(thread);
    const composer = screen.getByTestId("composer-editor");
    await expect(screen.getByText("Agent turn 200")).toBeVisible();
    await browser.evaluate(() => {
      performance.setResourceTimingBufferSize(10_000);
      return null;
    });
    const before = await browser.evaluate(countHistoryRequests);

    await composer.press("ArrowUp");
    // Let any page loads that one press chained together finish.
    await new Promise((resolve) => setTimeout(resolve, 3_000));
    const requests = (await browser.evaluate(countHistoryRequests)) - before;
    console.log("DEBUG", { before, requests });
    try {
      expect(requests).toBeLessThanOrEqual(1);
    } finally {
      await app.screenshot("one-arrow-up");
    }
  },
);
