Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

6.7 KB
Raw Blame
/**
 * Regression for #89: a Task posted after reloading a completed Session must execute — and
 * must carry the whole draft, the per-turn thinking level included.
 */
import { test, expect } from "@playwright/test";
import { provisionAndLogin } from "./auth.mjs";

const BASE = process.env.BASE_URL;
const MOCK = process.env.MOCK_URL;
const U = "reloadedfollowupuser";
const P = "password123";

async function createSession(page) {
  await provisionAndLogin(page.request, U, P);
  const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
  const projectId = projects.projects[0].projectId;
  const models = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
    data: {
      defaultModel: { provider: "custom", modelId: "claude-4-8" },
      models: [
        {
          provider: "custom",
          modelId: "claude-4-8",
          apiKey: "sk-mock",
          baseUrl: MOCK,
          contextWindow: 200000,
        },
      ],
    },
  });
  expect(models.ok(), "put models").toBeTruthy();
  const session = await page.request.post(
    `${BASE}/api/projects/${projectId}/agents/default_agent/sessions`,
    {
      data: {
        provider: "custom",
        modelId: "claude-4-8",
        approvalMode: "always-ask",
      },
    },
  );
  expect(session.ok(), `create session: ${await session.text()}`).toBeTruthy();
  return (await session.json()).session.sessionId;
}

test("a stale steer response after reload queues the follow-up instead of stranding it", async ({
  page,
}) => {
  const sessionId = await createSession(page);
  await page.goto(`${BASE}/chat/${sessionId}`);
  const composer = page.locator("textarea").first();
  await composer.waitFor();

  await composer.fill("first task before reload");
  const firstPost = page.waitForResponse((response) =>
    response.url().endsWith(`/sessions/${sessionId}/tasks`),
  );
  await page.getByRole("button", { name: "发送" }).click();
  expect((await firstPost).status()).toBe(202);

  // Reproduce the post-reload stale-state seam deterministically: the client still sees a
  // running Task, but /steer reports that the core run just ended. The fallback must use the
  // server's queue-if-busy path, which is safe on both sides of the completion race.
  await expect(page.getByRole("button", { name: "允许" })).toBeVisible();
  await page.route(`**/api/sessions/${sessionId}/steer`, (route) =>
    route.fulfill({
      status: 409,
      contentType: "application/json",
      body: JSON.stringify({
        error: {
          code: "not_running",
          message: "This Session has no Task in progress; send a new task instead.",
        },
      }),
    }),
  );
  await page.reload();
  await composer.waitFor();
  await expect(page.getByRole("button", { name: "停止" })).toBeVisible();
  await expect(page.getByRole("button", { name: "允许" })).toBeVisible();

  // A per-turn thinking level picked mid-run must ride the queued follow-up, exactly as it
  // rides an ordinary send: the server keeps it with the queued input and applies it when the
  // follow-up auto-starts. The picker is only disabled while a send is in flight, so it is
  // editable here; the pick is per-turn and does not write through to the Agent config.
  //
  // This conversation already has history, so the mid-chat switch guard (#310) stages the
  // pick behind its dialog instead of applying it. Cancel first: the guard must leave the
  // displayed level exactly where it was, never half-applied.
  // The trigger carries the plain Chinese name ("中"); only the menu rows annotate it with the
  // wire value ("高 (high)"), which is why the two are matched differently here.
  const thinkingBtn = page.getByRole("button", { name: "思考等级" });
  await expect(thinkingBtn).toContainText("中");
  await expect(thinkingBtn).not.toContainText("medium");
  await thinkingBtn.click();
  await page.getByRole("button", { name: "高 (high)", exact: true }).click();
  // The dialog's title is its accessible name, not body text — assert on its choices.
  await expect(page.getByRole("button", { name: "仍要切换", exact: true })).toBeVisible();
  await expect(page.getByRole("button", { name: "压缩后切换", exact: true })).toBeDisabled();
  await page.getByRole("button", { name: "取消", exact: true }).click();
  await expect(thinkingBtn).toContainText("中");

  // Now switch for real: a compaction cannot start while the task runs, so "压缩后切换" is
  // disabled here and "仍要切换" is the applying choice. The pick PINS the loaded Session
  // (PATCH /sessions { thinkingLevel }) — the level is no longer a per-task field, so the
  // follow-up below must not carry it and the pin is what makes it stick.
  await thinkingBtn.click();
  await page.getByRole("button", { name: "高 (high)", exact: true }).click();
  const pinned = page.waitForResponse(
    (r) =>
      r.request().method() === "PATCH" &&
      new URL(r.url()).pathname === `/api/sessions/${sessionId}`,
  );
  await page.getByRole("button", { name: "仍要切换", exact: true }).click();
  expect((await pinned).request().postDataJSON()).toMatchObject({ thinkingLevel: "high" });
  await expect(thinkingBtn).toContainText("高");

  await composer.fill("hello after reload");
  const followUpPost = page.waitForResponse((response) =>
    response.url().endsWith(`/sessions/${sessionId}/tasks`),
  );
  await page.getByRole("button", { name: "发送给运行中的 Agent" }).click();
  const response = await followUpPost;
  expect(response.status()).toBe(202);
  const queuedBody = response.request().postDataJSON();
  expect(queuedBody).toMatchObject({ queueIfBusy: true });
  // The pin above already put the level on the Session; a task-level copy would now be a
  // second, competing source of truth (upstream removed TaskCreateRequest.thinkingLevel).
  expect(queuedBody).not.toHaveProperty("thinkingLevel");
  expect(await response.json()).toMatchObject({ queued: true });
  // The queued hint is now one line per entry carrying that entry's own content (the bare
  // "N queued" count is only the fallback for a server that predates pendingFollowUps), and
  // it ends in the icon-only recall control — which must still answer to its name (#287).
  await expect(
    page.getByText("跟进消息已排队,本轮结束后自动发送:hello after reload"),
  ).toBeVisible();
  await expect(page.getByRole("button", { name: "撤回" })).toHaveCount(1);
  await expect(composer).toHaveValue("");

  // The first task completes, then the accepted follow-up reaches the LLM and produces a
  // second answer instead of remaining an inert 202 response.
  await page.getByRole("button", { name: "允许" }).click();
  await expect(page.getByText("Command finished; the result looks as expected.")).toHaveCount(2, {
    timeout: 30_000,
  });
});