Files
mnote/scripts/task-pi-lab-history-tail-smoke.js

181 lines
7.7 KiB
JavaScript

#!/usr/bin/env node
"use strict";
const { loginViaAuthForm } = require('./lib/browser-auth-login');
const assert = require("node:assert");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { chromium } = require("playwright");
const {
setupWorkspaceAccess,
seedAiPolicy,
seedAiRuntime,
} = require("./lib/control-plane-dev-seed");
const BASE = process.env.MNOTE_UI_BASE_URL || "http://127.0.0.1:3000";
const STAMP = Date.now();
const OUT = process.env.MNOTE_PI_HISTORY_TAIL_OUT || path.join(os.tmpdir(), `mnote-pi-history-tail-${STAMP}`);
const TIMEOUT = Number.parseInt(process.env.UI_TIMEOUT_MS || "90000", 10);
const ACTOR_ID = process.env.MNOTE_E2E_ACTOR_ID || "mnote-e2e";
const WORKSPACE_ID = `local-ws:${ACTOR_ID}:pi-history-tail`;
const ROOT_PATH = path.join(OUT, "workspace");
const ROOT_URI = `file://${ROOT_PATH}`;
const PAGE_PATH = `pi-history-tail-${STAMP}.md`;
const MODEL_PROVIDER = "omniroute";
const MODEL_ID = "gpt-5.4-mini";
const CHROMIUM_EXECUTABLE = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE
|| (fs.existsSync("/usr/bin/chromium-browser") ? "/usr/bin/chromium-browser" : "")
|| (fs.existsSync("/usr/bin/chromium") ? "/usr/bin/chromium" : "")
|| (fs.existsSync("/usr/bin/google-chrome") ? "/usr/bin/google-chrome" : "");
async function quickLogin(page) {
// 7-76 P0: 标准表单登录(无测试快速登录按钮)
const base =
(typeof BASE_URL !== "undefined" && BASE_URL) ||
(typeof baseUrl !== "undefined" && baseUrl) ||
process.env.MNOTE_UI_BASE_URL ||
"http://127.0.0.1:3000";
const timeout =
(typeof UI_TIMEOUT_MS !== "undefined" && UI_TIMEOUT_MS) ||
(typeof TIMEOUT !== "undefined" && TIMEOUT) ||
30_000;
if (!String(page.url() || "").includes("/auth")) {
await page.goto(String(base).replace(/\/+$/, "") + "/auth", {
waitUntil: "commit",
timeout,
});
}
await loginViaAuthForm(page, {
baseUrl: base,
timeoutMs: timeout,
gotoAuth: false,
});
await page
.waitForURL((url) => !String(url).includes("/auth"), { timeout })
.catch(() => {});
}
async function main() {
fs.mkdirSync(ROOT_PATH, { recursive: true });
fs.writeFileSync(path.join(ROOT_PATH, PAGE_PATH), "# Pi history tail smoke\n", "utf8");
fs.mkdirSync(OUT, { recursive: true });
const sessionId = `pi-history-tail-${STAMP}`;
const runId = `pi_run_${sessionId}`;
const duplicateText = `DUPLICATE_TAIL_REPLY_${STAMP}`;
const result = { ok: false, outputDir: OUT, checks: {}, screenshots: {} };
const browser = await chromium.launch({
headless: process.env.MNOTE_PI_HISTORY_TAIL_HEADED === "1" ? false : true,
executablePath: CHROMIUM_EXECUTABLE || undefined,
});
const context = await browser.newContext({ viewport: { width: 1440, height: 980 } });
await context.addInitScript(() => {
window.__MNOTE_PI_LAB_TEST__ = true;
});
const page = await context.newPage();
try {
await quickLogin(page);
const piSessionDir = path.join(OUT, "pi-session");
const piSessionFile = path.join(piSessionDir, `${STAMP}_session.jsonl`);
fs.mkdirSync(piSessionDir, { recursive: true });
fs.writeFileSync(
piSessionFile,
[
JSON.stringify({ id: "u1", type: "message", message: { role: "user", content: "first duplicate history turn" }, seq: 1 }),
JSON.stringify({ id: "a1", parentId: "u1", type: "message", message: { role: "assistant", content: [{ type: "text", text: duplicateText }] }, seq: 2 }),
].join("\n") + "\n",
"utf8",
);
await setupWorkspaceAccess(page.request, BASE, {
actorId: ACTOR_ID,
email: "mnote.e2e@example.com",
username: ACTOR_ID,
displayName: ACTOR_ID,
role: "admin",
workspaceId: WORKSPACE_ID,
workspaceName: "Pi history tail smoke",
rootPath: ROOT_PATH,
rootUri: ROOT_URI,
permission: "write",
capabilities: ["ai", "read", "write"],
timeoutMs: TIMEOUT,
});
await seedAiPolicy(page.request, BASE, {
id: `pi-history-tail-policy-${STAMP}`,
userId: ACTOR_ID,
workspaceId: WORKSPACE_ID,
allowedRootsJson: [{ rootUri: ROOT_URI, rootPath: ROOT_PATH, permission: "write" }],
modelPolicyJson: {
defaultModel: `${MODEL_PROVIDER}/${MODEL_ID}`,
allowedModels: [`${MODEL_PROVIDER}/${MODEL_ID}`],
tools: {},
skills: {},
mcpServers: {},
},
quotaJson: { daily: 20 },
timeoutMs: TIMEOUT,
});
await seedAiRuntime(page.request, BASE, {
userId: ACTOR_ID,
workspaceId: WORKSPACE_ID,
documentId: PAGE_PATH,
sessionId,
runId,
title: "Pi history duplicate tail smoke",
profile: "pi_lab",
acpRuntime: "pi",
status: "runtime_running",
runtimeJson: {
runtimeMode: "rpc",
rootUri: ROOT_URI,
workspaceId: WORKSPACE_ID,
pagePath: PAGE_PATH,
pageTitle: "Pi history duplicate tail smoke",
modelProvider: MODEL_PROVIDER,
modelId: MODEL_ID,
thinkingLevel: "high",
piSessionDir,
piSessionFile,
},
payloadJson: { message: "history duplicate tail smoke" },
events: [
{ eventType: "user_prompt", payloadJson: { message: "first duplicate history turn" } },
{ eventType: "pi_rpc_event", payloadJson: { type: "message_update", assistantMessageEvent: { type: "text_delta", delta: duplicateText } } },
{ eventType: "pi_rpc_event", payloadJson: { type: "message_update", assistantMessageEvent: { type: "text_end" } } },
{ eventType: "pi_rpc_event", payloadJson: { type: "message_update", assistantMessageEvent: { type: "text_delta", delta: duplicateText } } },
{ eventType: "pi_rpc_event", payloadJson: { type: "message_update", assistantMessageEvent: { type: "text_end" } } },
{ eventType: "pi_rpc_event", payloadJson: { type: "agent_end", messages: [{ role: "assistant", content: [{ type: "text", text: duplicateText }] }] } },
],
timeoutMs: TIMEOUT,
});
await page.goto(`${BASE}/page-ai/pi`, { waitUntil: "commit", timeout: TIMEOUT });
await page.locator('[data-page-ai-pi-lab="drawer"]').waitFor({ state: "visible", timeout: TIMEOUT });
await page.waitForFunction(() => !!window.__mnotePiLabTest, null, { timeout: TIMEOUT });
await page.locator("[data-page-ai-pi-lab-history]").click();
await page.locator(`[data-page-ai-pi-lab-history-row="${sessionId}"]`).waitFor({ state: "visible", timeout: TIMEOUT });
await page.locator(`[data-page-ai-pi-lab-history-session="${sessionId}"]`).first().click();
await page.waitForFunction(
({ text }) => Array.from(document.querySelectorAll('[data-page-ai-pi-lab-message-role="assistant"]'))
.filter((node) => (node.textContent || "").includes(text)).length === 1,
{ text: duplicateText },
{ timeout: TIMEOUT },
);
result.checks.duplicateAssistantCount = await page.locator('[data-page-ai-pi-lab-message-role="assistant"]', { hasText: duplicateText }).count();
assert.equal(result.checks.duplicateAssistantCount, 1, "history replay should use Pi JSONL tree as the single message source");
result.screenshots.history = path.join(OUT, "history-tail.png");
await page.screenshot({ path: result.screenshots.history, fullPage: false });
result.ok = true;
} catch (error) {
result.error = error && error.stack ? error.stack : String(error);
result.screenshots.failure = path.join(OUT, "failure.png");
await page.screenshot({ path: result.screenshots.failure, fullPage: true }).catch(() => {});
process.exitCode = 1;
} finally {
fs.writeFileSync(path.join(OUT, "result.json"), JSON.stringify(result, null, 2), "utf8");
await browser.close();
console.log(JSON.stringify({ ok: result.ok, outputDir: OUT, result: path.join(OUT, "result.json") }, null, 2));
}
}
main();