292 lines
14 KiB
JavaScript
292 lines
14 KiB
JavaScript
#!/usr/bin/env node
|
|
"use strict";
|
|
|
|
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 BASE = process.env.MNOTE_UI_BASE_URL || "http://127.0.0.1:3000";
|
|
const STAMP = Date.now();
|
|
const OUT = process.env.MNOTE_PI_FULL_ACCESS_BUILTIN_OUT || path.join(os.tmpdir(), `mnote-pi-full-access-builtin-disabled-${STAMP}`);
|
|
const TIMEOUT = Number.parseInt(process.env.UI_TIMEOUT_MS || "360000", 10);
|
|
const ACTOR_ID = process.env.MNOTE_E2E_ACTOR_ID || "mnote-e2e";
|
|
const WORKSPACE_ID = process.env.MNOTE_PI_FULL_ACCESS_BUILTIN_WORKSPACE_ID || "local-ws:mnote-e2e:my-space";
|
|
const ROOT_PATH = process.env.MNOTE_PI_FULL_ACCESS_BUILTIN_ROOT_PATH || "/mnt/Data1T/Mnote_data/users/mnote-e2e/workspaces/my-space";
|
|
const ROOT_URI = process.env.MNOTE_PI_FULL_ACCESS_BUILTIN_ROOT_URI || `file://${ROOT_PATH}`;
|
|
const MODEL_PROVIDER = process.env.MNOTE_PI_FULL_ACCESS_BUILTIN_MODEL_PROVIDER || "omniroute";
|
|
const MODEL_ID = process.env.MNOTE_PI_FULL_ACCESS_BUILTIN_MODEL_ID || "freefirst";
|
|
const MARKER = `PI_FULL_ACCESS_BUILTIN_DISABLED_OK_${STAMP}`;
|
|
const PAGE_PATH = `pi-full-access-builtin-disabled-${STAMP}.md`;
|
|
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" : "");
|
|
|
|
function mkdirp(dir) {
|
|
fs.mkdirSync(dir, { recursive: true });
|
|
}
|
|
|
|
async function quickLogin(page) {
|
|
await page.goto(`${BASE}/auth`, { waitUntil: "commit", timeout: TIMEOUT });
|
|
const quickLoginButton = page.getByRole("button", { name: "测试账号快速登录" });
|
|
await quickLoginButton.waitFor({ state: "visible", timeout: TIMEOUT });
|
|
await Promise.all([
|
|
page.waitForURL((url) => !url.toString().includes("/auth"), { timeout: TIMEOUT }).catch(() => null),
|
|
quickLoginButton.click(),
|
|
]);
|
|
}
|
|
|
|
async function requestJson(page, url, options = {}) {
|
|
const response = await page.request.fetch(`${BASE}${url}`, {
|
|
...options,
|
|
headers: {
|
|
accept: "application/json",
|
|
"content-type": "application/json",
|
|
...(options.headers || {}),
|
|
},
|
|
timeout: options.timeout || TIMEOUT,
|
|
});
|
|
const text = await response.text();
|
|
let body = {};
|
|
try {
|
|
body = text ? JSON.parse(text) : {};
|
|
} catch {
|
|
body = { raw: text };
|
|
}
|
|
assert(response.ok(), `${options.method || "GET"} ${url} failed: ${response.status()} ${text.slice(0, 800)}`);
|
|
return body;
|
|
}
|
|
|
|
function piExtensionConfig(name, description, source, toolNames, riskLevel, requiredScopes = []) {
|
|
return { name, description, source, toolNames, riskLevel, requiredScopes, enabled: true };
|
|
}
|
|
|
|
function policyForFullAccessBuiltinDisabled() {
|
|
return {
|
|
defaultModel: `${MODEL_PROVIDER}/${MODEL_ID}`,
|
|
allowedModels: [`${MODEL_PROVIDER}/${MODEL_ID}`],
|
|
tools: {
|
|
"mnote.current_page.read": "allow",
|
|
"mnote.allowed_roots.describe": "allow",
|
|
"mnote.tool_receipt.write": "allow",
|
|
},
|
|
skills: {},
|
|
mcpServers: {},
|
|
piExtensions: {
|
|
"pi-rust-official-question": piExtensionConfig("Pi Rust Official Question", "Pi Rust 官方索引 question 扩展的本地镜像。", "pi-rust-official:question", ["question"], "low", ["ui:ask"]),
|
|
"pi-rust-official-questionnaire": piExtensionConfig("Pi Rust Official Questionnaire", "Pi Rust 官方索引 questionnaire 扩展的本地镜像。", "pi-rust-official:questionnaire", ["questionnaire"], "low", ["ui:ask"]),
|
|
"pi-rust-official-permission-gate": piExtensionConfig("Pi Rust Official Permission Gate", "Pi Rust 官方索引 permission-gate 扩展的本地镜像。", "pi-rust-official:permission-gate", [], "high", ["tool:policy"]),
|
|
},
|
|
};
|
|
}
|
|
|
|
async function seedWorkspace(page) {
|
|
mkdirp(ROOT_PATH);
|
|
fs.writeFileSync(path.join(ROOT_PATH, PAGE_PATH), "# Pi full access builtin disabled smoke\n", "utf8");
|
|
const grantResponse = await page.request.fetch(`${BASE}/api/admin/access-policy/grants`, {
|
|
method: "POST",
|
|
headers: {
|
|
accept: "application/json",
|
|
"content-type": "application/json",
|
|
},
|
|
data: {
|
|
userId: ACTOR_ID,
|
|
rootUri: ROOT_URI,
|
|
rootPath: ROOT_PATH,
|
|
permission: "write",
|
|
recursive: true,
|
|
capabilities: ["ai"],
|
|
},
|
|
timeout: TIMEOUT,
|
|
});
|
|
const grantText = await grantResponse.text();
|
|
let grantBody = {};
|
|
try {
|
|
grantBody = grantText ? JSON.parse(grantText) : {};
|
|
} catch {
|
|
grantBody = { raw: grantText };
|
|
}
|
|
if (!grantResponse.ok() && grantBody.code !== "local_access_policy_grant_duplicate") {
|
|
throw new Error(`POST /api/admin/access-policy/grants failed: ${grantResponse.status()} ${grantText.slice(0, 800)}`);
|
|
}
|
|
await requestJson(page, "/api/ai-admin/settings", {
|
|
method: "PUT",
|
|
data: {
|
|
...policyForFullAccessBuiltinDisabled(),
|
|
quota: { daily: 200 },
|
|
},
|
|
});
|
|
await requestJson(page, `/api/ai-settings/effective?workspaceId=${encodeURIComponent(WORKSPACE_ID)}`);
|
|
}
|
|
|
|
async function abortExistingSession(page) {
|
|
const status = await requestJson(page, "/api/page-ai/pi/status").catch(() => null);
|
|
const sessionId = status && status.session && status.session.sessionId;
|
|
if (!sessionId) return null;
|
|
await requestJson(page, "/api/page-ai/pi/abort", { method: "POST", data: { sessionId } }).catch(() => null);
|
|
return sessionId;
|
|
}
|
|
|
|
async function startRealPi(page) {
|
|
const sessionId = `pi-full-access-builtin-disabled-${STAMP}`;
|
|
const start = await requestJson(page, "/api/page-ai/pi/start", {
|
|
method: "POST",
|
|
data: {
|
|
sessionId,
|
|
rootUri: ROOT_URI,
|
|
workspaceId: WORKSPACE_ID,
|
|
pagePath: PAGE_PATH,
|
|
pageTitle: "Pi full access builtin disabled smoke",
|
|
modelProvider: MODEL_PROVIDER,
|
|
modelId: MODEL_ID,
|
|
thinkingLevel: "medium",
|
|
permissionMode: "full_access",
|
|
},
|
|
});
|
|
assert.equal(start.ok, true, "Pi start ok should be true");
|
|
assert.equal(start.permissionMode, "full_access", "start response should expose full_access mode");
|
|
assert.equal(start.session.runtimePolicySnapshot.permissionMode, "full_access", "runtime policy should persist full_access");
|
|
assert.equal(start.session.runtimeMode, "rpc", `Pi 必须以 rpc 模式启动,实际=${start.session.runtimeMode}`);
|
|
assert(start.session.runtimePid, "真实 Pi RPC 启动后应有 runtimePid");
|
|
return start.session;
|
|
}
|
|
|
|
async function openPiUi(page) {
|
|
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(() => {
|
|
const text = document.querySelector("[data-page-ai-pi-lab-status-text]")?.textContent || "";
|
|
return /ready|running|streaming/.test(text);
|
|
}, null, { timeout: TIMEOUT }).catch(() => null);
|
|
}
|
|
|
|
function readSessionJsonl(sessionDir) {
|
|
const files = [];
|
|
const walk = (dir) => {
|
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
const full = path.join(dir, entry.name);
|
|
if (entry.isDirectory()) {
|
|
walk(full);
|
|
} else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
|
|
files.push(full);
|
|
}
|
|
}
|
|
};
|
|
walk(sessionDir);
|
|
files.sort();
|
|
const sessionFile = files[files.length - 1];
|
|
assert(sessionFile, `session jsonl not found in ${sessionDir}`);
|
|
return { sessionFile, raw: fs.readFileSync(sessionFile, "utf8") };
|
|
}
|
|
|
|
async function main() {
|
|
mkdirp(OUT);
|
|
const browser = await chromium.launch({
|
|
headless: process.env.MNOTE_PI_FULL_ACCESS_BUILTIN_HEADED === "1" ? false : true,
|
|
executablePath: CHROMIUM_EXECUTABLE || undefined,
|
|
});
|
|
const context = await browser.newContext({ viewport: { width: 1440, height: 980 } });
|
|
const page = await context.newPage();
|
|
const consoleMessages = [];
|
|
page.on("console", (message) => {
|
|
if (["error", "warning"].includes(message.type())) consoleMessages.push(`${message.type()}: ${message.text()}`);
|
|
});
|
|
page.on("pageerror", (error) => consoleMessages.push(`pageerror: ${error.message}`));
|
|
|
|
const result = {
|
|
base: BASE,
|
|
outputDir: OUT,
|
|
marker: MARKER,
|
|
rootUri: ROOT_URI,
|
|
screenshots: {},
|
|
checks: {},
|
|
consoleMessages,
|
|
};
|
|
|
|
try {
|
|
await quickLogin(page);
|
|
await seedWorkspace(page);
|
|
await abortExistingSession(page);
|
|
const session = await startRealPi(page);
|
|
result.session = {
|
|
sessionId: session.sessionId,
|
|
runtimePid: session.runtimePid,
|
|
piSessionDir: session.piSessionDir,
|
|
runtimePolicySnapshot: session.runtimePolicySnapshot,
|
|
};
|
|
const enabledSources = session.runtimePolicySnapshot.enabledPiExtensionSources || [];
|
|
const permissionConfigPath = path.join(session.piSessionDir, "config", "extensions", "pi-permission-system", "config.json");
|
|
result.permissionConfigPath = permissionConfigPath;
|
|
result.checks.permissionSystemConfigAbsent = !fs.existsSync(permissionConfigPath);
|
|
result.checks.noLegacyNpmAskUser = !enabledSources.includes("npm:pi-ask-user");
|
|
result.checks.noExternalPermissionSystem = !enabledSources.includes("npm:@gotgenes/pi-permission-system");
|
|
result.checks.officialPermissionGateConfigured = enabledSources.includes("pi-rust-official:permission-gate");
|
|
result.checks.managedBuiltinToolsDisabledAtStart = (session.runtimePolicySnapshot.managedBuiltinTools || []).length === 0;
|
|
assert.equal(result.checks.permissionSystemConfigAbsent, true, "full_access smoke should not generate legacy pi-permission-system config");
|
|
assert.equal(result.checks.noLegacyNpmAskUser, true, "full_access smoke should not use unavailable npm:pi-ask-user");
|
|
assert.equal(result.checks.noExternalPermissionSystem, true, "full_access smoke should not load incompatible pi-permission-system");
|
|
assert.equal(result.checks.officialPermissionGateConfigured, true, "policy should include Pi Rust official permission-gate");
|
|
|
|
await openPiUi(page);
|
|
await page.screenshot({ path: path.join(OUT, "01-full-access-started.png"), fullPage: false });
|
|
result.screenshots.started = path.join(OUT, "01-full-access-started.png");
|
|
|
|
const prompt = [
|
|
"请调用 mnote_allowed_roots_describe 工具,读取 MNote 返回的 allowedRoots、deniedPiBuiltinTools、managedPiBuiltinTools、permissionProvider。",
|
|
"不要调用 bash/read/write/edit/hashline_edit/grep/find/ls 这些 Pi 内置工具。",
|
|
"用一句话说明:full_access 下 MNote 当前仍默认禁用 Pi Rust 内置文件/命令工具,文件权限由 MNote bridge 管控。",
|
|
`最终单独输出一行:${MARKER}`,
|
|
].join("\n");
|
|
await page.locator("[data-page-ai-pi-lab-input]").fill(prompt);
|
|
await page.locator("[data-page-ai-pi-lab-btn-send]").click();
|
|
|
|
const markerLocator = page
|
|
.locator('[data-page-ai-pi-lab-message-role="assistant"] .wolai-page-ai-pi-lab-text, [data-page-ai-pi-lab-message-role="assistant"] .wolai-page-ai-pi-lab-markdown')
|
|
.filter({ hasText: MARKER })
|
|
.last();
|
|
const startedAt = Date.now();
|
|
while (Date.now() - startedAt < TIMEOUT) {
|
|
const permissionVisible = await page.locator("text=Permission Required").count();
|
|
assert.equal(permissionVisible, 0, "official permission-gate smoke should not ask legacy Permission Required dialog");
|
|
if (await markerLocator.isVisible({ timeout: 500 }).catch(() => false)) break;
|
|
await page.waitForTimeout(500);
|
|
}
|
|
await markerLocator.waitFor({ state: "visible", timeout: 1000 });
|
|
await page.screenshot({ path: path.join(OUT, "02-full-access-builtin-disabled-answer.png"), fullPage: false });
|
|
result.screenshots.answer = path.join(OUT, "02-full-access-builtin-disabled-answer.png");
|
|
|
|
const sessionJsonl = readSessionJsonl(session.piSessionDir);
|
|
result.session.sessionFile = sessionJsonl.sessionFile;
|
|
result.answerText = ((await markerLocator.textContent({ timeout: TIMEOUT })) || "").trim();
|
|
result.checks.allowedRootsToolCalled = /mnote_allowed_roots_describe/.test(sessionJsonl.raw);
|
|
result.checks.deniedBuiltinsRecorded = /deniedPiBuiltinTools/.test(sessionJsonl.raw) && /hashline_edit/.test(sessionJsonl.raw);
|
|
result.checks.managedBuiltinsEmptyRecorded = /managedPiBuiltinTools/.test(sessionJsonl.raw);
|
|
result.checks.noRawBuiltinCalled = !/"name":"(bash|read|write|edit|hashline_edit|grep|find|ls)"/.test(sessionJsonl.raw);
|
|
result.checks.noPermissionRequiredPrompt = await page.locator("text=Permission Required").count() === 0;
|
|
assert(result.checks.allowedRootsToolCalled, "Pi session JSONL should record mnote_allowed_roots_describe call");
|
|
assert(result.checks.deniedBuiltinsRecorded, "Pi session JSONL should include deniedPiBuiltinTools");
|
|
assert(result.checks.managedBuiltinsEmptyRecorded, "Pi session JSONL should include managedPiBuiltinTools");
|
|
assert(result.checks.noRawBuiltinCalled, "Pi raw builtin tools should remain disabled by default");
|
|
assert(result.checks.noPermissionRequiredPrompt, "official permission-gate smoke should not show legacy Permission Required prompt");
|
|
|
|
await requestJson(page, "/api/page-ai/pi/abort", { method: "POST", data: { sessionId: session.sessionId } }).catch(() => ({}));
|
|
result.ok = true;
|
|
} catch (error) {
|
|
result.ok = false;
|
|
result.error = error && error.stack ? error.stack : String(error);
|
|
try {
|
|
await page.screenshot({ path: path.join(OUT, "99-failure.png"), fullPage: true });
|
|
result.screenshots.failure = path.join(OUT, "99-failure.png");
|
|
} 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();
|