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

test("Grok multi-call history uses per-call context tiers", WEB, async ({ t3, app, browser, screen }) => {
  // Synthetic copy of the reported turn totals; every original prompt was below 272K.
  // GROK_HOME must point at an isolated scratch directory and be inherited by the app.
  const home = process.env.GROK_HOME!;
  await mkdir(`${home}/sessions/synthetic`, { recursive: true });
  const usage = { inputTokens: 619097, cachedReadTokens: 549632, outputTokens: 395, modelCalls: 15 };
  await writeFile(`${home}/sessions/synthetic/updates.jsonl`, JSON.stringify({
    timestamp: Date.now(), method: "_x.ai/session/update", params: {
      sessionId: "synthetic-multicall", update: {
        sessionUpdate: "turn_completed", prompt_id: "prompt-1",
        usage: { ...usage, modelUsage: { "gpt-6.1-sol": usage } },
      },
    },
  }) + "\n");
  const project = await t3.project("usage-context-tier");
  const thread = await t3.thread({ project, title: "Synthetic usage evidence", messages: ["Start"] });
  await t3.open(thread);
  await browser.evaluate(() => localStorage.setItem("t3code:usage-page-preferences:v1", JSON.stringify({
    metric: "cost", windowDays: 30,
    hiddenProviders: ["codex", "claude", "cursor", "opencode", "antigravity", "pi", "muse"],
  })));
  await t3.open("/usage");
  await screen.getByText("gpt-6.1-sol", { exact: true }).first().waitFor({ state: "visible" });
  try {
    await expect(screen.getByText("$0.20", { exact: true }).first()).toBeVisible();
    await expect(screen.getByText("$1.04", { exact: true }).first()).toBeVisible();
  } finally {
    await app.screenshot("grok-multicall-cost-and-cache-savings");
  }
});
