import { expect, gotoWorkbench, saveScreenshot, test } from "../fixtures/test";
import { selectors, sessionTab } from "../fixtures/selectors";

test("session rail, messages, composer and trace status stay consistent", async ({ page }, testInfo) => {
  await gotoWorkbench(page);
  await expect(page.locator(sessionTab("ses_running"))).toHaveAttribute("data-running", "true");
  await expect(page.locator(`${selectors.messageCard}[data-role="agent"][data-status="running"]`)).toBeVisible();
  await expect(page.locator(selectors.commandSend)).toHaveAttribute("data-action", "cancel");

  await page.locator(sessionTab("ses_failed")).click();
  await expect(page.locator(sessionTab("ses_failed"))).toHaveAttribute("data-status", "failed");
  await expect(page.locator(`${selectors.messageCard}[data-role="agent"][data-status="failed"]`)).toContainText("缺少受控依赖");
  await expect(page.locator(`${selectors.traceTimeline}[data-status="failed"]`)).toBeVisible();

  await page.locator(sessionTab("ses_canceled")).click();
  await expect(page.locator(sessionTab("ses_canceled"))).toHaveAttribute("data-status", "canceled");
  await expect(page.locator(`${selectors.messageCard}[data-role="agent"][data-status="canceled"]`)).toContainText("运行已取消");

  await page.locator(sessionTab("ses_completed")).click();
  await expect(page.locator(sessionTab("ses_completed"))).toHaveAttribute("data-running", "false");
  await expect(page.locator(`${selectors.messageCard}[data-role="agent"][data-status="completed"]`)).toContainText("构建和 Trace 渲染检查完成");
  await saveScreenshot(page, testInfo, "status-consistency-completed");
});

test.describe("terminal turn with stale active session authority", () => {
  test.use({ scenarioId: "terminal-turn-stale-session-active" });

  test("session rail shows terminal status instead of stale active", async ({ page }, testInfo) => {
    await gotoWorkbench(page, "/workbench/sessions/ses_completed");
    await expect(page.locator(sessionTab("ses_completed"))).toHaveAttribute("data-status", "completed");
    await expect(page.locator(sessionTab("ses_completed"))).toHaveAttribute("data-running", "false");
    await expect(page.locator(`${selectors.messageCard}[data-role="agent"][data-status="completed"]`)).toContainText("构建和 Trace 渲染检查完成");
    await expect(page.locator(`${selectors.messageCard}[data-role="agent"][data-status="failed"]`)).toHaveCount(0);
    await expect(page.locator(selectors.commandSend)).toHaveAttribute("data-action", "turn");
    await expect(page.locator(".composer-mode")).not.toContainText("运行中");
    await saveScreenshot(page, testInfo, "stale-active-session-terminal-tab");
  });
});
