#!/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 { setupWorkspaceAccess, seedAiPolicy, } = 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_MODEL_CONTROLS_OUT || path.join(os.tmpdir(), `mnote-pi-model-controls-${STAMP}`); const TIMEOUT = Number.parseInt(process.env.UI_TIMEOUT_MS || "240000", 10); const ACTOR_ID = process.env.MNOTE_E2E_ACTOR_ID || "mnote-e2e"; const DEFAULT_E2E_ROOT = "/mnt/Data1T/Mnote_data/users/mnote-e2e/workspaces/my-space"; const ROOT_FROM_ENV = process.env.MNOTE_PI_MODEL_ROOT_PATH; const ROOT_PATH = ROOT_FROM_ENV || (ACTOR_ID === "mnote-e2e" && fs.existsSync(DEFAULT_E2E_ROOT) ? DEFAULT_E2E_ROOT : path.join(OUT, "workspace")); const USING_DEFAULT_E2E_ROOT = !ROOT_FROM_ENV && ACTOR_ID === "mnote-e2e" && ROOT_PATH === DEFAULT_E2E_ROOT; const WORKSPACE_ID = process.env.MNOTE_PI_MODEL_WORKSPACE_ID || (USING_DEFAULT_E2E_ROOT ? "local-ws:mnote-e2e:my-space" : `local-ws:${ACTOR_ID}:pi-model-controls`); const ROOT_URI = process.env.MNOTE_PI_MODEL_ROOT_URI || `file://${ROOT_PATH}`; const PAGE_PATH = `pi-model-controls-${STAMP}/pi-model-controls-${STAMP}.md`; const MODEL_PROVIDER = process.env.MNOTE_PI_MODEL_PROVIDER || "omniroute"; const MODEL_ID = process.env.MNOTE_PI_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" : ""); 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: "测试账号快速登录" }); if (!(await quickLoginButton.isVisible({ timeout: 4000 }).catch(() => false))) return; 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 policy() { return { defaultModel: `${MODEL_PROVIDER}/${MODEL_ID}`, allowedModels: [`${MODEL_PROVIDER}/${MODEL_ID}`], tools: { "mnote.current_page.read": "allow", "mnote.selection.read": "allow", "mnote.allowed_roots.describe": "allow", "mnote.local_file.read": "allow", "mnote.local_file.patch": "ask", "mnote.knowledge_rag.status": "allow", "mnote.knowledge_rag.query": "allow", "mnote.knowledge_rag.section_context": "allow", "mnote.knowledge_rag.open_reference": "allow", "mnote.reference.open": "allow", "mnote.tool_receipt.write": "allow", "mnote.codex_rescue.request": "ask", }, skills: {}, mcpServers: {}, }; } async function seedWorkspace(page) { mkdirp(path.dirname(path.join(ROOT_PATH, PAGE_PATH))); fs.writeFileSync(path.join(ROOT_PATH, PAGE_PATH), "# Pi model controls\n\nMODEL_CONTROLS_OK\n", "utf8"); if (USING_DEFAULT_E2E_ROOT) return; 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 model controls smoke", rootPath: ROOT_PATH, rootUri: ROOT_URI, permission: "write", capabilities: ["ai", "read", "write"], timeoutMs: TIMEOUT, }); await seedAiPolicy(page.request, BASE, { id: `pi-model-controls-policy-${ACTOR_ID}-${WORKSPACE_ID}`, userId: ACTOR_ID, workspaceId: WORKSPACE_ID, allowedRootsJson: [{ rootUri: ROOT_URI, rootPath: ROOT_PATH, permission: "write" }], modelPolicyJson: policy(), quotaJson: { daily: 200 }, timeoutMs: TIMEOUT, }); } async function main() { mkdirp(OUT); const browser = await chromium.launch({ headless: process.env.MNOTE_PI_MODEL_CONTROLS_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(); const result = { base: BASE, outputDir: OUT, rootUri: ROOT_URI, pagePath: PAGE_PATH, screenshots: {}, checks: {}, }; try { await quickLogin(page); await seedWorkspace(page); const start = await requestJson(page, "/api/page-ai/pi/start", { method: "POST", data: { sessionId: `pi-model-controls-${STAMP}`, rootUri: ROOT_URI, workspaceId: WORKSPACE_ID, pagePath: PAGE_PATH, pageTitle: "Pi model controls", modelProvider: MODEL_PROVIDER, modelId: MODEL_ID, thinkingLevel: "medium", }, }); assert.equal(start.ok, true, "start should succeed"); 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 }); const modelToggle = page.locator("[data-page-ai-pi-lab-model-menu-toggle]"); const modelLabel = page.locator("[data-page-ai-pi-lab-model-label]"); const thinkingToggle = page.locator("[data-page-ai-pi-lab-thinking-menu-toggle]"); const thinkingLabel = page.locator("[data-page-ai-pi-lab-thinking-label]"); await modelToggle.waitFor({ state: "visible", timeout: TIMEOUT }); await thinkingToggle.waitFor({ state: "visible", timeout: TIMEOUT }); await modelLabel.waitFor({ state: "visible", timeout: TIMEOUT }); await thinkingLabel.waitFor({ state: "visible", timeout: TIMEOUT }); result.checks.modelToggleDisabled = await modelToggle.isDisabled(); result.checks.thinkingToggleDisabled = await thinkingToggle.isDisabled(); assert.equal(result.checks.modelToggleDisabled, false, "model toggle button should be enabled"); assert.equal(result.checks.thinkingToggleDisabled, false, "thinking toggle button should be enabled"); // Open thinking menu via toggle button await thinkingToggle.click(); const thinkingMenu = page.locator("[data-page-ai-pi-lab-thinking-menu]"); await thinkingMenu.waitFor({ state: "visible", timeout: TIMEOUT }); // Assert menu position: bounding box above toggle, horizontally adjacent const thinkingMenuBox = await thinkingMenu.boundingBox(); const thinkingToggleBox = await thinkingToggle.boundingBox(); result.checks.thinkingMenuBox = thinkingMenuBox; result.checks.thinkingToggleBox = thinkingToggleBox; if (thinkingMenuBox && thinkingToggleBox) { result.checks.thinkingMenuAboveToggle = thinkingMenuBox.y + thinkingMenuBox.height <= thinkingToggleBox.y + 1; result.checks.thinkingMenuHorizAdjacent = Math.abs(thinkingMenuBox.x - thinkingToggleBox.x) <= 100; assert.equal(result.checks.thinkingMenuAboveToggle, true, "thinking menu should be above toggle button"); assert.equal(result.checks.thinkingMenuHorizAdjacent, true, "thinking menu should be horizontally adjacent to toggle"); } // Assert mutual exclusion: open thinking menu, model menu should be closed const modelWrap = page.locator("[data-page-ai-pi-lab-model-menu-wrap]"); result.checks.thinkingOpenModelClosed = await modelWrap.getAttribute("data-open"); assert.equal(result.checks.thinkingOpenModelClosed, "false", "model menu should close when thinking menu opens"); const configureRequestPromise = page.waitForRequest( (request) => request.url().includes("/api/page-ai/pi/configure") && request.method() === "POST", { timeout: TIMEOUT }, ); const offOption = page.locator('[data-page-ai-pi-lab-thinking-option="off"]'); await offOption.click(); const configureRequest = await configureRequestPromise; result.checks.configureRequest = configureRequest.postDataJSON(); assert.equal(result.checks.configureRequest.sessionId, start.session.sessionId, "configure should keep current session"); assert.equal(result.checks.configureRequest.modelProvider, MODEL_PROVIDER); assert.equal(result.checks.configureRequest.modelId, MODEL_ID); assert.equal(result.checks.configureRequest.thinkingLevel, "off"); // Verify label updated await page.waitForFunction( () => document.querySelector("[data-page-ai-pi-lab-thinking-label]")?.textContent?.includes("思考 关"), null, { timeout: TIMEOUT }, ); // Open model menu and verify thinking menu closed (mutual exclusion reverse) await modelToggle.click(); const modelMenu = page.locator("[data-page-ai-pi-lab-model-menu]"); await modelMenu.waitFor({ state: "visible", timeout: TIMEOUT }); const thinkingWrap = page.locator("[data-page-ai-pi-lab-thinking-menu-wrap]"); result.checks.modelOpenThinkingClosed = await thinkingWrap.getAttribute("data-open"); assert.equal(result.checks.modelOpenThinkingClosed, "false", "thinking menu should close when model menu opens"); // Close menu by clicking outside (click on drawer body outside the controls) const drawer = page.locator('[data-page-ai-pi-lab="drawer"]'); const drawerBox = await drawer.boundingBox(); if (drawerBox) { const closeX = drawerBox.x + drawerBox.width - 10; const closeY = drawerBox.y + 10; await page.mouse.click(closeX, closeY); await page.waitForTimeout(200); } result.checks.modelMenuClosedOutsideClick = await modelWrap.getAttribute("data-open"); assert.equal(result.checks.modelMenuClosedOutsideClick, "false", "model menu should close on outside click"); // Re-open model menu to verify it still anchors correctly await modelToggle.click(); await modelMenu.waitFor({ state: "visible", timeout: TIMEOUT }); const modelMenuBox = await modelMenu.boundingBox(); const modelToggleBox = await modelToggle.boundingBox(); result.checks.modelMenuBox = modelMenuBox; result.checks.modelToggleBox = modelToggleBox; if (modelMenuBox && modelToggleBox) { result.checks.modelMenuAboveToggle = modelMenuBox.y + modelMenuBox.height <= modelToggleBox.y + 1; result.checks.modelMenuHorizAdjacent = Math.abs(modelMenuBox.x - modelToggleBox.x) <= 100; assert.equal(result.checks.modelMenuAboveToggle, true, "model menu should be above toggle button after re-open"); assert.equal(result.checks.modelMenuHorizAdjacent, true, "model menu should be horizontally adjacent to toggle after re-open"); } // + menu should replace model menu. await page.locator("[data-page-ai-pi-lab-action-menu-toggle]").click(); result.checks.plusOpenedModelClosed = { actionMenuOpen: await page.locator(".wolai-page-ai-pi-lab-composer").getAttribute("data-menu-open"), modelMenuOpen: await modelWrap.getAttribute("data-open"), }; assert.equal(result.checks.plusOpenedModelClosed.actionMenuOpen, "true", "+ menu should open"); assert.equal(result.checks.plusOpenedModelClosed.modelMenuOpen, "false", "model menu should close when + menu opens"); // Access control should replace + menu. await page.locator("[data-page-ai-pi-lab-permission]").click(); const permissionWrap = page.locator("[data-page-ai-pi-lab-permission-wrap]"); result.checks.permissionOpenedPlusClosed = { actionMenuOpen: await page.locator(".wolai-page-ai-pi-lab-composer").getAttribute("data-menu-open"), permissionMenuOpen: await permissionWrap.getAttribute("data-open"), }; assert.equal(result.checks.permissionOpenedPlusClosed.actionMenuOpen, "false", "+ menu should close when access control opens"); assert.equal(result.checks.permissionOpenedPlusClosed.permissionMenuOpen, "true", "access control menu should open"); // Model menu should replace access control and remain anchored. await modelToggle.click(); await modelMenu.waitFor({ state: "visible", timeout: TIMEOUT }); result.checks.modelOpenedPermissionClosed = { modelMenuOpen: await modelWrap.getAttribute("data-open"), permissionMenuOpen: await permissionWrap.getAttribute("data-open"), }; assert.equal(result.checks.modelOpenedPermissionClosed.modelMenuOpen, "true", "model menu should reopen"); assert.equal(result.checks.modelOpenedPermissionClosed.permissionMenuOpen, "false", "access control should close when model menu opens"); // Close model menu via outside click again. if (drawerBox) { const closeX = drawerBox.x + drawerBox.width - 10; const closeY = drawerBox.y + 10; await page.mouse.click(closeX, closeY); await page.waitForTimeout(200); } await page.locator("[data-page-ai-pi-lab-status-text]").waitFor({ state: "attached", timeout: TIMEOUT }); result.checks.statusText = (await page.locator("[data-page-ai-pi-lab-status-text]").textContent() || "").trim(); await page.screenshot({ path: path.join(OUT, "01-model-thinking-enabled-configured.png"), fullPage: false }); result.screenshots.modelThinkingConfigured = path.join(OUT, "01-model-thinking-enabled-configured.png"); fs.writeFileSync(path.join(OUT, "result.json"), JSON.stringify(result, null, 2), "utf8"); console.log(`✅ Pi Lab model/thinking controls smoke passed. Output: ${OUT}`); } finally { await browser.close(); } } main().catch((error) => { console.error(error); process.exit(1); });