#!/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_URL,
  UI_TIMEOUT_MS,
  ensureAuthenticated,
} = require("./tree-shell-smoke-helpers");

const TASK = "task502-page-ai-agent-selector-context-smoke";
const OUTPUT_DIR = path.join(process.cwd(), "tmp", TASK);
const RESULT_PATH = path.join(OUTPUT_DIR, "result.json");
const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
  || ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium", "/usr/bin/chromium"]
    .find((candidate) => fs.existsSync(candidate));

function fileUrl(localPath) {
  return `file://${localPath}`;
}

function localMdDocumentId(relativePath) {
  return `local-md:${relativePath.replaceAll("/", "~2F")}`;
}

function writeWorkspaceManifest(root, ownerId, workspaceId) {
  fs.mkdirSync(path.join(root, ".mnote"), { recursive: true });
  fs.writeFileSync(
    path.join(root, ".mnote", "workspace.json"),
    `${JSON.stringify({
      workspaceId,
      ownerId,
      createdAt: new Date().toISOString(),
      capabilities: ["local_files", "ai_sessions", "markdown_edit"],
    }, null, 2)}\n`,
    "utf8",
  );
}

function documentUrl(root, relativePath) {
  const url = new URL(`${BASE_URL}/documents/${encodeURIComponent(localMdDocumentId(relativePath))}`);
  url.searchParams.set("sourceKind", "local_folder");
  url.searchParams.set("rootUri", fileUrl(root));
  url.searchParams.set("treeView", "filetree");
  return url.toString();
}

async function saveScreenshot(page, name) {
  const target = path.join(OUTPUT_DIR, `${name}.png`);
  await page.screenshot({ path: target, fullPage: false });
  return target;
}

async function waitForCapturedRunCount(captured, minCount, timeoutMs = UI_TIMEOUT_MS) {
  const started = Date.now();
  while (Date.now() - started < timeoutMs) {
    if (captured.filter((item) => item.kind === "run").length >= minCount) return;
    await new Promise((resolve) => setTimeout(resolve, 50));
  }
  throw new Error(`captured run 数量不足，期望至少 ${minCount}，实际 ${captured.filter((item) => item.kind === "run").length}`);
}

async function main() {
  fs.mkdirSync(OUTPUT_DIR, { recursive: true });
  const suffix = Date.now().toString(36);
  const actorId = "mnote-e2e";
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task502-agent-context-"));
  const rootUri = fileUrl(root);
  const workspaceId = `local-ws:${actorId}:task502`;
  const relativePath = "AgentContext.md";
  const documentId = localMdDocumentId(relativePath);
  const captured = [];
  let caughtError = null;

  writeWorkspaceManifest(root, actorId, workspaceId);
  fs.writeFileSync(
    path.join(root, relativePath),
    ["# Agent Context", "", `Task502 ${suffix}`, ""].join("\n"),
    "utf8",
  );

  const browser = await chromium.launch({
    headless: true,
    ...(CHROMIUM_EXECUTABLE_PATH ? { executablePath: CHROMIUM_EXECUTABLE_PATH } : {}),
  });
  const context = await browser.newContext({
    viewport: { width: 1440, height: 960 },
    locale: "zh-CN",
    extraHTTPHeaders: {
      "x-mnote-actor-id": actorId,
      "x-mnote-actor-type": "user",
    },
  });
  const page = await context.newPage();

  try {
    await page.route("**/api/user/access-policy**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          controlPlane: "sqlite",
          grants: [{
            id: `grant_task502_${suffix}`,
            userId: actorId,
            workspaceId,
            rootUri,
            rootPath: root,
            permission: "write",
            recursive: true,
            capabilities: ["ai", "markdown_edit"],
            source: "user",
            status: "active",
          }],
        }),
      });
    });
    await page.route("**/api/ui/preferences**", async (route) => {
      captured.push({
        kind: "ui-preferences",
        method: route.request().method(),
        body: route.request().postData() || "",
      });
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, owner: "mnote-web", result: {} }),
      });
    });
    await page.route("**/api/hermes/client/gateway/health**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          gateway: { ok: true, status: "mocked" },
          profile: { name: "reasonix", modelConfigured: true, apiKeyConfigured: true },
          suggestions: [],
        }),
      });
    });
    await page.route("**/api/hermes/client/tools**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true, tools: [] }),
      });
    });
    await page.route("**/api/ai/agent-profiles**", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          agentId: "hermes",
          profiles: [
            { profileId: "shared_deepseek_chat", kind: "shared", displayName: "DeepSeek Chat", baseProfile: "deepseek-chat", isolatedProfile: "openclaw-deepseek-chat", canRun: true, canManageSkills: false, canManageConfig: false, readonly: true },
            { profileId: "shared_doubao_chat", kind: "shared", displayName: "豆包 Chat", baseProfile: "doubao-chat", isolatedProfile: "openclaw-doubao-chat", canRun: true, canManageSkills: false, canManageConfig: false, readonly: true },
            { profileId: "shared_gemini_chat", kind: "shared", displayName: "Gemini Chat", baseProfile: "gemini-chat", isolatedProfile: "openclaw-gemini-chat", canRun: true, canManageSkills: false, canManageConfig: false, readonly: true },
            { profileId: "usr_task502_default", kind: "personal", displayName: "我的 Hermes", baseProfile: "default", isolatedProfile: "mnote-u-task502-default", canRun: true, canManageSkills: true, canManageConfig: true },
            { profileId: "shared_lite", kind: "shared", displayName: "Lite", baseProfile: "lite", isolatedProfile: "lite", canRun: true, canManageSkills: false, canManageConfig: false, readonly: true },
          ],
        }),
      });
    });
    await page.route("**/api/hermes/client/profiles", async (route) => {
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          active: "mnoteai",
          profiles: [
            { name: "mnoteai", label: "MNote AI", modelConfigured: true, apiKeyConfigured: true },
            { name: "chemist", label: "Chemist", modelConfigured: true, apiKeyConfigured: true },
          ],
        }),
      });
    });
    await page.route("**/api/hermes/client/profiles/active", async (route) => {
      captured.push({ kind: "profile-active", method: route.request().method(), body: route.request().postData() || "" });
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true }),
      });
    });
    await page.route("**/api/hermes/client/skills/toggle", async (route) => {
      captured.push({ kind: "skill-toggle", method: route.request().method(), body: route.request().postData() || "" });
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true }),
      });
    });
    await page.route("**/api/hermes/client/capabilities/toggle", async (route) => {
      captured.push({ kind: "capability-toggle", method: route.request().method(), body: route.request().postData() || "" });
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ ok: true }),
      });
    });
    await page.route("**/api/hermes/client/capabilities**", async (route) => {
      const url = new URL(route.request().url());
      if (url.pathname.endsWith("/toggle")) {
        captured.push({ kind: "capability-toggle", method: route.request().method(), body: route.request().postData() || "" });
        await route.fulfill({
          status: 200,
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ ok: true }),
        });
        return;
      }
      const body = {
        ok: true,
        runtime: "mnote",
        categories: [{
          name: "mnote",
          title: "MNote AI 能力",
          capabilities: [
            { id: "mnote-current-page", name: "mnote-current-page", title: "当前页读取", description: "读取当前页", enabled: true, source: "mnote", origin: "builtin", builtin: true, configurable: true, configScope: "user_sqlite", skillKind: "mnote_capability", uiKind: "ai_capability", toolCount: 1, tools: [{ name: "mnote.context.snapshot", enabled: true }] },
            { id: "mnote-mindmap", name: "mnote-mindmap", title: "思维导图读写", description: "读取、编辑或从 outline 生成思维导图", enabled: true, source: "mnote", origin: "builtin", builtin: true, configurable: true, configScope: "user_sqlite", skillKind: "mnote_capability", uiKind: "ai_capability", toolNames: ["mnote.mindmap.fetch", "mnote.mindmap.create_from_outline"], toolCount: 2, tools: [{ name: "mnote.mindmap.fetch", enabled: true }, { name: "mnote.mindmap.create_from_outline", enabled: true }] },
          ],
        }],
        archived: [],
      };
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify(body),
      });
    });
    await page.route("**/api/hermes/client/skills**", async (route) => {
      const url = new URL(route.request().url());
      if (url.pathname.endsWith("/toggle")) {
        captured.push({ kind: "skill-toggle", method: route.request().method(), body: route.request().postData() || "" });
        await route.fulfill({
          status: 200,
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ ok: true }),
        });
        return;
      }
      const runtime = url.searchParams.get("runtime");
      const profile = url.searchParams.get("profileId") || url.searchParams.get("profile") || "usr_task502_default";
      const body = runtime === "mnote"
        ? {
          ok: true,
          runtime: "mnote",
          categories: [{
            name: "mnote",
            skills: [
              { id: "mnote-current-page", name: "mnote-current-page", title: "当前页读取", description: "读取当前页", enabled: true, source: "mnote", origin: "builtin", builtin: true, configurable: true, configScope: "user_sqlite", skillKind: "mnote_builtin" },
              { id: "mnote-mindmap", name: "mnote-mindmap", title: "思维导图读写", description: "读取、编辑或从 outline 生成思维导图", enabled: true, source: "mnote", origin: "builtin", builtin: true, configurable: true, configScope: "user_sqlite", skillKind: "mnote_builtin", toolNames: ["mnote.mindmap.fetch", "mnote.mindmap.create_from_outline"] },
            ],
          }],
          archived: [],
        }
        : runtime === "reasonix"
          ? {
            ok: true,
            runtime: "reasonix",
            categories: [{ name: "project", skills: [{ id: "reasonix-review", name: "reasonix-review", description: "Reasonix review", enabled: true, toggleable: true, source: "reasonix", origin: "project" }] }],
            archived: [],
          }
          : {
            ok: true,
            profile,
            categories: [{
              name: "writing",
              skills: [
                { id: "hermes-builtin", name: "hermes-builtin", title: "Hermes builtin", description: `Builtin ${profile}`, enabled: true, source: "builtin", origin: "builtin", skillKind: "hermes_profile", profileId: profile, configurable: profile !== "shared_lite" },
                { id: profile === "shared_lite" ? "hermes-lite" : "hermes-writer", name: profile === "shared_lite" ? "hermes-lite" : "hermes-writer", title: profile === "shared_lite" ? "Hermes lite" : "Hermes writer", description: `Hermes ${profile}`, enabled: profile !== "shared_lite", source: "local", origin: "installed", skillKind: "hermes_profile", profileId: profile, configurable: profile !== "shared_lite", readonly: profile === "shared_lite" },
              ],
            }],
            archived: [],
          };
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify(body),
      });
    });
    await page.route("**/api/hermes/client/sessions", async (route) => {
      captured.push({ kind: "session", method: route.request().method(), body: route.request().postData() || "" });
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          sessionId: `mnote_task502_${suffix}`,
          title: "task502",
          traceId: `trace_task502_session_${suffix}`,
          persistence: "local_ai_session_jsonl",
          sessionStorage: "local_private",
        }),
      });
    });
    await page.route("**/api/hermes/client/runs", async (route) => {
      captured.push({ kind: "run", method: route.request().method(), body: route.request().postData() || "" });
      await route.fulfill({
        status: 200,
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          ok: true,
          sessionId: `mnote_task502_${suffix}`,
          runId: `run_task502_${suffix}`,
          events: [],
          traceId: `trace_task502_run_${suffix}`,
        }),
      });
    });
    await page.route("**/api/hermes/client/events/*", async (route) => {
      const includeReceipt = captured.filter((item) => item.kind === "run").length > 1;
      const completed = { event: "run.completed", run_id: `run_task502_${suffix}`, output: "Task502 response" };
      if (includeReceipt) {
        completed.agentAudit = {
          rootUri,
          actorId: "mnote-e2e",
          actorType: "user",
          agentKind: "reasonix",
          changedFiles: [{ path: relativePath, changeType: "modified", summary: "task502 receipt" }],
          agentRunReceipt: {
            schema: "mnote.agent_run_receipt.v1",
            runId: `run_task502_${suffix}`,
            sessionId: `mnote_task502_${suffix}`,
            workspaceId,
            documentId,
            rootUri,
            agentKind: "reasonix",
            status: "completed",
            permission: "write",
            changedFiles: [{ path: relativePath, changeType: "modified", summary: "task502 receipt" }],
            refresh: {
              touchesCurrentFile: true,
              currentDocumentId: documentId,
              strategy: "refresh_current_file",
            },
          },
        };
      }
      await route.fulfill({
        status: 200,
        headers: { "content-type": "text/event-stream; charset=utf-8" },
        body:
          `data: ${JSON.stringify({ event: "message.delta", run_id: `run_task502_${suffix}`, delta: "Task502 response" })}\n\n` +
          `data: ${JSON.stringify(completed)}\n\n`,
      });
    });

    await ensureAuthenticated(page, context.request);
    const response = await page.goto(documentUrl(root, relativePath), {
      waitUntil: "domcontentloaded",
      timeout: UI_TIMEOUT_MS,
    });
    assert(response && response.status() === 200, `文档页状态码异常: ${response && response.status()}`);
    await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"] .ProseMirror').first().waitFor({
      state: "visible",
      timeout: UI_TIMEOUT_MS,
    });
    await page.getByTestId("wolai-floating-ai").click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-testid="wolai-page-ai-drawer"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });

    const drawer = page.locator('[data-testid="wolai-page-ai-drawer"]');
    const defaultChatText = await drawer.innerText({ timeout: UI_TIMEOUT_MS });
    assert(!defaultChatText.includes("问 Hermes"), "默认输入区不应继续固定写“问 Hermes”");
    assert(!defaultChatText.includes("model.default"), "默认聊天面不应显示 model.default");
    assert(!defaultChatText.includes("gateway:"), "默认聊天面不应显示 gateway 技术详情");
    assert(!defaultChatText.includes("Hermes profile"), "默认聊天面不应显示 Hermes profile 技术项");

    assert.strictEqual(
      await page.locator("[data-page-ai-agent-selector]").count(),
      0,
      "默认输入区不应继续平铺 agent selector，应收敛为一个 agent 按钮",
    );
    const agentButton = page.locator("[data-page-ai-agent-button]");
    await agentButton.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    assert(
      await agentButton.evaluate((node) => Boolean(node.closest(".wolai-page-ai-composer-bar"))),
      "agent 按钮应显示在输入区下方工具栏中",
    );
    const agentButtonLabel = await agentButton.getAttribute("aria-label");
    assert(agentButtonLabel.includes("Agent"), `agent 按钮应提供当前 agent 摘要: ${agentButtonLabel}`);
    await agentButton.click({ timeout: UI_TIMEOUT_MS });
    const agentPopover = page.locator("[data-page-ai-agent-popover]");
    await agentPopover.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await agentPopover.locator('[data-page-ai-agent-section="chat_only"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await agentPopover.locator('[data-page-ai-agent-section="hermes"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    assert.strictEqual(
      await page.locator('[data-page-ai-agent-section="chat_only"] [data-page-ai-profile-id="shared_deepseek_chat"]').count(),
      1,
      "ChatOnly 二级菜单应包含 DeepSeek",
    );
    assert.strictEqual(
      await page.locator('[data-page-ai-agent-section="chat_only"] [data-page-ai-profile-id="shared_doubao_chat"]').count(),
      1,
      "ChatOnly 二级菜单应包含豆包",
    );
    assert.strictEqual(
      await page.locator('[data-page-ai-agent-section="chat_only"] [data-page-ai-profile-id="shared_gemini_chat"]').count(),
      1,
      "ChatOnly 二级菜单应包含 Gemini",
    );
    assert.strictEqual(
      await page.locator('[data-page-ai-agent-section="hermes"] [data-page-ai-profile-id="usr_task502_default"]').count(),
      1,
      "Hermes 二级菜单应包含个人 profile",
    );
    assert.strictEqual(
      await page.locator('[data-page-ai-agent-section="hermes"] [data-page-ai-profile-id="shared_lite"]').count(),
      1,
      "Hermes 二级菜单应包含 shared_lite profile",
    );
    const agentChip = page.locator("[data-page-ai-agent-chip]");
    await page.locator('[data-page-ai-agent-section="chat_only"] [data-page-ai-profile-id="shared_gemini_chat"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => document.documentElement.getAttribute("data-mnote-page-ai-agent-id") === "chat_only"
        && document.documentElement.getAttribute("data-mnote-page-ai-profile") === "shared_gemini_chat",
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    assert((await agentChip.innerText({ timeout: UI_TIMEOUT_MS })).includes("ChatOnly / Gemini"), "上下文按钮右侧标签应显示当前 ChatOnly agent");
    await agentButton.click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-agent-section="hermes"] [data-page-ai-profile-id="shared_lite"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => document.documentElement.getAttribute("data-mnote-page-ai-agent-id") === "hermes"
        && document.documentElement.getAttribute("data-mnote-page-ai-profile") === "shared_lite",
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    assert((await agentChip.innerText({ timeout: UI_TIMEOUT_MS })).includes("Hermes / Lite"), "上下文按钮右侧标签应显示当前 Hermes profile");
    await agentButton.click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-agent-section="reasonix"] [data-page-ai-agent-id="reasonix"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => document.documentElement.getAttribute("data-mnote-page-ai-agent-id") === "reasonix",
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    assert((await agentChip.innerText({ timeout: UI_TIMEOUT_MS })).includes("Reasonix"), "上下文按钮右侧标签应显示当前 Reasonix agent");

    const contextRefs = page.locator("[data-page-ai-context-refs]");
    assert.strictEqual(
      await contextRefs.count(),
      0,
      "默认输入区不应继续平铺 contextRef chip，应收敛为一个上下文按钮",
    );
    const contextButton = page.locator("[data-page-ai-context-button]");
    await contextButton.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    assert(
      await contextButton.evaluate((node) => Boolean(node.closest(".wolai-page-ai-composer-bar"))),
      "上下文按钮应显示在输入区下方工具栏中",
    );
    const targetButton = page.locator("[data-page-ai-target-button]");
    await targetButton.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    assert(
      await targetButton.evaluate((node) => Boolean(node.closest(".wolai-page-ai-composer-bar"))),
      "目标按钮应显示在输入区下方工具栏中",
    );
    const targetChip = page.locator("[data-page-ai-target-chip]");
    await targetChip.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const targetChipText = (await targetChip.innerText({ timeout: UI_TIMEOUT_MS })).trim();
    assert(targetChipText.includes("AgentContext") || targetChipText.includes("当前页"), `目标 chip 应展示当前写入目标: ${targetChipText}`);
    await targetButton.click({ timeout: UI_TIMEOUT_MS });
    const targetPopover = page.locator("[data-page-ai-target-popover]");
    await targetPopover.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    assert(
      await targetPopover.locator("[data-page-ai-target-option]").first().isVisible(),
      "目标 popover 应提供至少一个可选目标",
    );
    await targetPopover.locator('[data-page-ai-action="close-target-popover"]').click({ timeout: UI_TIMEOUT_MS });
    await page.evaluate(({ documentId, rootUri, workspaceId }) => {
      const runtime = window.__mnoteDocumentPaneRuntime;
      if (!runtime || typeof runtime.getOpenEditorsSnapshot !== "function") {
        throw new Error("缺少 open editors snapshot runtime");
      }
      const original = runtime.getOpenEditorsSnapshot.bind(runtime);
      runtime.getOpenEditorsSnapshot = () => {
        const snapshot = original();
      const mindmapResource = {
          objectIdentity: "resource:mindmap:task502",
          workspacePath: {
            schema: "mnote.workspace_path.v1",
            workspaceId,
            sourceKind: "local_folder",
            rootUri,
            relativePath: "maps/Task502.mindmap.json",
            documentId,
            objectIdentity: "resource:mindmap:task502",
            assetId: "task502-mindmap",
            resourceKind: "mindmap",
          },
          paneRole: "primary",
          documentId,
          workspaceId,
          title: "Task502 Mindmap",
          kind: "mindmap",
          editorKind: "mindmap",
          active: false,
          dirtyState: "",
          preview: false,
          pinned: true,
          lastActiveAt: Date.now(),
          assetId: "task502-mindmap",
          path: "maps/Task502.mindmap.json",
        };
      const officeResource = {
        objectIdentity: "resource:office:task502",
        workspacePath: {
          schema: "mnote.workspace_path.v1",
          workspaceId,
          sourceKind: "local_folder",
          rootUri,
          relativePath: "office/Task502 Deck.pptx",
          documentId,
          objectIdentity: "resource:office:task502",
          assetId: "task502-office",
          resourceKind: "office",
        },
        paneRole: "primary",
        documentId,
        workspaceId,
        title: "Task502 Deck",
        kind: "office",
        editorKind: "office",
        active: false,
        dirtyState: "",
        preview: false,
        pinned: true,
        lastActiveAt: Date.now(),
        assetId: "task502-office",
        path: "office/Task502 Deck.pptx",
        onlyofficeSessionId: "mnote-oo-task502-office",
        bridgeSessionId: "mnote-oo-task502-office",
        bridgeSessionReady: true,
      };
      const officePreviewResource = {
        objectIdentity: "resource:office-preview:task502",
        workspacePath: {
          schema: "mnote.workspace_path.v1",
          workspaceId,
          sourceKind: "local_folder",
          rootUri,
          relativePath: "office/Task502 Preview.docx",
          documentId,
          objectIdentity: "resource:office-preview:task502",
          assetId: "task502-office-preview",
          resourceKind: "attachment",
        },
        paneRole: "primary",
        documentId,
        workspaceId,
        title: "Task502 Preview DOCX",
        kind: "office",
        editorKind: "office",
        active: false,
        dirtyState: "",
        preview: true,
        pinned: true,
        lastActiveAt: Date.now(),
        assetId: "task502-office-preview",
        path: "office/Task502 Preview.docx",
        officeOpenMode: "preview",
        onlyofficeSessionId: "",
        bridgeSessionId: "",
        bridgeSessionReady: false,
      };
      const resources = [mindmapResource, officeResource, officePreviewResource];
        const withoutResource = (items) => (Array.isArray(items) ? items : [])
          .filter((item) => !resources.some((resource) => item?.objectIdentity === resource.objectIdentity));
        const groups = snapshot.groups || {};
        const primary = groups.primary || {};
        return {
          ...snapshot,
          editors: [...withoutResource(snapshot.editors), ...resources],
          resourceEditors: [...withoutResource(snapshot.resourceEditors), ...resources],
          groups: {
            ...groups,
            primary: {
              ...primary,
              resourceEditors: [...withoutResource(primary.resourceEditors), ...resources],
            },
          },
        };
      };
    }, { documentId, rootUri, workspaceId });
    await targetButton.click({ timeout: UI_TIMEOUT_MS });
    await targetPopover.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await targetPopover.locator('[data-page-ai-target-option="resource:office:task502"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => (document.querySelector("[data-page-ai-target-chip]")?.textContent || "").includes("Task502 Deck"),
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    assert.strictEqual(
      await page.locator('.wolai-page-ai-composer-bar [data-page-ai-action="history"]').count(),
      0,
      "历史会话不应继续占用输入区下方工具栏位置",
    );
    assert(
      await page.locator('.wolai-page-ai-header-actions [data-page-ai-action="history"]').isVisible(),
      "历史会话入口应移动到右上角设置旁边",
    );
    assert(
      await page.locator('.wolai-page-ai-header-actions [data-page-ai-tab="skills"]').isVisible(),
      "技能入口应显示在右上角历史按钮左侧",
    );
    await page.locator('.wolai-page-ai-header-actions [data-page-ai-tab="skills"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-panel="skills"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const skillSourceSelect = page.locator('[data-page-ai-panel="skills"] [data-page-ai-skill-source-select]');
    await skillSourceSelect.waitFor({ state: "attached", timeout: UI_TIMEOUT_MS });
    const skillSourceOptions = await skillSourceSelect.locator("option").evaluateAll((nodes) =>
      nodes.map((node) => ({ value: node.value, text: node.textContent || "" })),
    );
    assert(skillSourceOptions.some((item) => item.value === "mnote" && item.text.includes("MNote 公共能力")), "能力来源应包含 MNote");
    assert(skillSourceOptions.some((item) => item.value === "reasonix" && item.text.includes("Reasonix skill")), "能力来源应包含 Reasonix 自带 skill 查看入口");
    assert(skillSourceOptions.some((item) => item.value === "hermes:usr_task502_default" && item.text.includes("Hermes skill")), "能力来源应包含个人 Hermes profile skill 查看入口");
    assert(!skillSourceOptions.some((item) => item.value === "hermes:shared_deepseek_chat"), "Chat-only Hermes profile 不应作为能力来源展示");
    assert(!skillSourceOptions.some((item) => item.value === "hermes:shared_lite"), "Hermes Lite chat-only profile 不应作为能力来源展示");
    await page.locator('[data-page-ai-skill-group="mnote"] [data-page-ai-skill-toggle="mnote-current-page"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-skill-group="mnote"] [data-page-ai-skill-toggle="mnote-mindmap"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const skillPanelText = await page.locator('[data-page-ai-panel="skills"]').innerText({ timeout: UI_TIMEOUT_MS });
    assert(skillPanelText.includes("MNote 公共能力"), "能力面板应展示 MNote 来源");
    assert(!skillPanelText.includes("user_sqlite"), "MNote 能力面板不应展示内部 SQLite policy 细节");
    assert(!skillPanelText.includes("profile_tool_policy"), "MNote 能力面板不应展示内部 profile policy 细节");
    assert(!skillPanelText.includes("reasonix-review"), "选择 MNote 时不应同时展示 Reasonix 能力条目");
    assert(!skillPanelText.includes("Hermes writer"), "选择 MNote 时不应同时展示 Hermes 能力条目");
    const mnoteSkillsScreenshot = await saveScreenshot(page, "00-mnote-skills-panel");
    await page.locator('[data-page-ai-skill-group-toggle="mnote"]').click({ timeout: UI_TIMEOUT_MS });
    assert.strictEqual(
      await page.locator('[data-page-ai-skill-group="mnote"] [data-page-ai-skill-toggle="mnote-current-page"]').count(),
      0,
      "MNote 技能分组折叠后不应显示组内技能",
    );
    assert.strictEqual(
      await page.locator('[data-page-ai-skill-group="mnote"] [data-page-ai-skill-toggle="mnote-mindmap"]').count(),
      0,
      "MNote 技能分组折叠后不应显示 mindmap 技能",
    );
    await page.locator('[data-page-ai-skill-group-toggle="mnote"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-skill-group="mnote"] [data-page-ai-skill-toggle="mnote-current-page"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-skill-group="mnote"] [data-page-ai-skill-toggle="mnote-mindmap"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-skill-group="mnote"] [data-page-ai-skill-toggle="mnote-current-page"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-skill-group="mnote"] [data-page-ai-skill-toggle="mnote-mindmap"]').click({ timeout: UI_TIMEOUT_MS });
    await skillSourceSelect.selectOption("reasonix", { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-skill-group="reasonix"] .wolai-page-ai-skill-name', { hasText: "reasonix-review" }).waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    assert.strictEqual(
      await page.locator('[data-page-ai-skill-group="reasonix"] [data-page-ai-skill-toggle="reasonix-review"]').count(),
      0,
      "Reasonix 自带 skill 在能力页只读查看，不显示开关",
    );
    await skillSourceSelect.selectOption("hermes:usr_task502_default", { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-skill-group="hermes"] .wolai-page-ai-skill-name', { hasText: "Hermes writer" }).waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    assert.strictEqual(
      await page.locator('[data-page-ai-skill-group="hermes"] [data-page-ai-skill-toggle="hermes-writer"]').count(),
      0,
      "Hermes profile skill 在能力页只读查看，不显示开关",
    );
    const skillsScreenshot = await saveScreenshot(page, "00-hermes-skills-panel");
    await page.locator('[data-page-ai-panel="skills"] [data-page-ai-tab="chat"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-panel="chat"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const contextButtonText = await contextButton.innerText({ timeout: UI_TIMEOUT_MS });
    assert(
      contextButtonText.trim() === "⇅",
      `上下文按钮应显示为单个上下文图标: ${contextButtonText}`,
    );
    const contextButtonLabel = await contextButton.getAttribute("aria-label");
    assert(
      contextButtonLabel.includes("当前页") && contextButtonLabel.includes("打开资源"),
      `上下文按钮 aria-label 应摘要展示已选上下文: ${contextButtonLabel}`,
    );
    await contextButton.click({ timeout: UI_TIMEOUT_MS });
    const contextPopover = page.locator("[data-page-ai-context-popover]");
    await contextPopover.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    assert(
      await contextPopover.locator('input[type="checkbox"][data-page-ai-context-ref="current_page"]:checked').isVisible(),
      "当前页 contextRef 应在 popover checkbox 中默认勾选",
    );
    await contextPopover.locator('[data-page-ai-action="close-context-popover"]').click({ timeout: UI_TIMEOUT_MS });
    assert.strictEqual(
      await page.locator(".wolai-page-ai-composer > [data-page-ai-allowed-roots]").count(),
      0,
      "授权区域不应继续在输入区显示黑色 chip，应收敛到上下文 popover 内",
    );
    await contextButton.click({ timeout: UI_TIMEOUT_MS });
    assert(
      (await contextPopover.innerText({ timeout: UI_TIMEOUT_MS })).includes("授权区域"),
      "SQLite 授权区域应在上下文 popover 内展示",
    );
    await contextPopover.locator('[data-page-ai-action="close-context-popover"]').click({ timeout: UI_TIMEOUT_MS });

    await page.locator("[data-page-ai-input]").fill("收到请回复收到", { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => (document.querySelector('[data-testid="wolai-page-ai-drawer"]')?.textContent || "").includes("Task502 response"),
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    assert.strictEqual(
      await page.locator("[data-page-ai-tool-card]").count(),
      0,
      "纯聊天短请求不应显示 MNote tool card",
    );
    const ackRuns = captured.filter((item) => item.kind === "run");
    assert(ackRuns.length >= 1, "未捕获纯聊天 Page AI run payload");
    const ackRunBody = JSON.parse(ackRuns[ackRuns.length - 1].body);
    assert.strictEqual(ackRunBody.pageContext?.aiContext?.pageText, undefined, "Page AI run 不应默认上传 pageText");
    assert.strictEqual(ackRunBody.pageContext?.aiContext?.pageXml, undefined, "Page AI run 不应默认上传 pageXml");
    assert.strictEqual(ackRunBody.pageContext?.aiContext?.contextBlocks, undefined, "Page AI run 不应默认上传 contextBlocks");
    assert.strictEqual(ackRunBody.pageContext?.evidence, undefined, "Page AI run 不应默认上传选区 evidence 正文");
    assert.strictEqual(ackRunBody.selectedText, "", "Page AI run 不应默认上传 selectedText 正文");
    assert.strictEqual(ackRunBody.targetPackage?.schema, "mnote.agent_target_package.v1", "纯聊天 run 也应冻结目标包合同");
    assert(ackRunBody.targetPackage?.primaryTargetId, "targetPackage 应包含 primaryTargetId");
    assert(Array.isArray(ackRunBody.targetPackage?.targets), "targetPackage 应包含 targets 数组");
    assert.strictEqual(ackRunBody.targetPackage?.primaryTargetId, "resource:office:task502", "targetPackage 应冻结用户选择的 Office target");
    assert.strictEqual(ackRunBody.targetPackage?.onlyofficeSessionId, "mnote-oo-task502-office", "Office targetPackage 应携带 bridge session");
    assert(
      ackRunBody.targetPackage.targets.some((target) => target.resourceKind === "only_office" && target.relativePath === "office/Task502 Deck.pptx" && target.onlyofficeSessionId === "mnote-oo-task502-office"),
      `默认目标应标记 only_office resourceKind: ${JSON.stringify(ackRunBody.targetPackage)}`,
    );
    assert.strictEqual(ackRunBody.targetPackage?.policy?.writeRequiresExplicitTarget, true, "targetPackage policy 应要求显式目标");
    await page.waitForFunction(
      () => ["completed", "idle"].includes(document.documentElement.getAttribute("data-mnote-page-ai-run-status") || ""),
      null,
      { timeout: UI_TIMEOUT_MS },
    );

    await targetButton.click({ timeout: UI_TIMEOUT_MS });
    await targetPopover.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await targetPopover.locator('[data-page-ai-target-option="resource:office-preview:task502"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => (document.querySelector("[data-page-ai-target-chip]")?.textContent || "").includes("Task502 Preview DOCX"),
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    const previewRunCountBefore = captured.filter((item) => item.kind === "run").length;
    await page.locator("[data-page-ai-input]").fill("预览 docx 请正常回复", { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS });
    await waitForCapturedRunCount(captured, previewRunCountBefore + 1);
    await page.waitForFunction(
      () => (document.querySelector('[data-testid="wolai-page-ai-drawer"]')?.textContent || "").includes("Task502 response"),
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    const previewRuns = captured.filter((item) => item.kind === "run");
    assert(previewRuns.length >= 2, "未捕获 Office 预览 Page AI run payload");
    const previewRunBody = JSON.parse(previewRuns[previewRuns.length - 1].body);
    assert.strictEqual(previewRunBody.targetPackage?.primaryTargetId, "resource:office-preview:task502", "Office 预览 targetPackage 应冻结预览资源");
    assert.strictEqual(previewRunBody.targetPackage?.resourceKind, "attachment", `Office 预览不应被归一为 only_office: ${JSON.stringify(previewRunBody.targetPackage)}`);
    assert.strictEqual(previewRunBody.targetPackage?.onlyofficeSessionId, "", "Office 预览 targetPackage 不应要求 bridge session");
    assert(
      previewRunBody.targetPackage.targets.some((target) => target.resourceKind === "attachment" && target.relativePath === "office/Task502 Preview.docx" && !target.onlyofficeSessionId),
      `Office 预览 target 应作为普通附件上下文发送: ${JSON.stringify(previewRunBody.targetPackage)}`,
    );

    await page.locator('.wolai-page-ai-header-actions [data-page-ai-tab="agent"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-panel="agent"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const commonSettingsText = await page.locator('[data-page-ai-panel="agent"]').innerText({ timeout: UI_TIMEOUT_MS });
    assert(commonSettingsText.includes("授权区域"), "Common 设置页应展示授权区域");
    assert(commonSettingsText.includes("默认上下文"), "Common 设置页应展示默认 contextRefs");
    assert(commonSettingsText.includes("审计"), "Common 设置页应展示审计/changed files 共性设置");
    assert(!commonSettingsText.includes("Hermes profile"), "Common 设置页不应包含 Hermes profile");
    assert(!commonSettingsText.includes("ACP runtime"), "Common 设置页不应包含 agent runtime 差异项");

    await page.locator('[data-page-ai-panel="agent"] [data-page-ai-tab="hermes-settings"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-panel="hermes-settings"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const hermesSettingsText = await page.locator('[data-page-ai-panel="hermes-settings"]').innerText({ timeout: UI_TIMEOUT_MS });
    assert(hermesSettingsText.includes("Hermes profile"), "Hermes 设置页应只承接 Hermes profile");
    assert(!hermesSettingsText.includes("Reasonix 专属设置"), "Hermes 设置页不应混入 Reasonix 设置");

    await page.locator('[data-page-ai-panel="hermes-settings"] [data-page-ai-tab="reasonix-settings"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-panel="reasonix-settings"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const reasonixSettingsText = await page.locator('[data-page-ai-panel="reasonix-settings"]').innerText({ timeout: UI_TIMEOUT_MS });
    assert(reasonixSettingsText.includes("ACP runtime"), "Reasonix 设置页应展示 ACP runtime");
    assert(reasonixSettingsText.includes("Reasonix 专属设置"), "Reasonix 设置页应展示 Reasonix 专属设置");
    assert(!reasonixSettingsText.includes("Hermes profile"), "Reasonix 设置页不应混入 Hermes profile");

    await page.locator('[data-page-ai-panel="reasonix-settings"] [data-page-ai-tab="chat-only-settings"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-panel="chat-only-settings"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    const chatOnlySettingsText = await page.locator('[data-page-ai-panel="chat-only-settings"]').innerText({ timeout: UI_TIMEOUT_MS });
    assert(chatOnlySettingsText.includes("默认不申请文件写权限"), "Chat-only 设置页应说明默认不申请写权限");
    assert(!chatOnlySettingsText.includes("ACP runtime"), "Chat-only 设置页不应混入 ACP runtime");
    await page.locator('[data-page-ai-panel="chat-only-settings"] [data-page-ai-tab="chat"]').click({ timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-panel="chat"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });

    await contextButton.click({ timeout: UI_TIMEOUT_MS });
    await contextPopover.locator('input[type="checkbox"][data-page-ai-context-ref="current_page"]').click({ timeout: UI_TIMEOUT_MS });
    await contextPopover.locator('input[type="checkbox"][data-page-ai-context-ref="folder"]').click({ timeout: UI_TIMEOUT_MS });
    await contextPopover.locator('input[type="checkbox"][data-page-ai-context-ref="changed_files"]').click({ timeout: UI_TIMEOUT_MS });
    const updatedContextButtonLabel = await contextButton.getAttribute("aria-label");
    assert(
      updatedContextButtonLabel.includes("打开资源") && updatedContextButtonLabel.includes("文件夹"),
      `勾选变化后上下文按钮摘要应更新: ${updatedContextButtonLabel}`,
    );
    await contextPopover.locator('[data-page-ai-action="close-context-popover"]').click({ timeout: UI_TIMEOUT_MS });
    await targetButton.click({ timeout: UI_TIMEOUT_MS });
    await targetPopover.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
    await targetPopover.locator('[data-page-ai-target-option="resource:mindmap:task502"]').click({ timeout: UI_TIMEOUT_MS });
    await page.waitForFunction(
      () => (document.querySelector("[data-page-ai-target-chip]")?.textContent || "").includes("Task502 Mindmap"),
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    const runsBeforeDocumentTask = captured.filter((item) => item.kind === "run").length;
    await page.locator("[data-page-ai-input]").fill(`Task502 agent/context ${suffix}`, { timeout: UI_TIMEOUT_MS });
    await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS });
    const runWaitStarted = Date.now();
    while (captured.filter((item) => item.kind === "run").length <= runsBeforeDocumentTask) {
      assert(Date.now() - runWaitStarted < UI_TIMEOUT_MS, "未捕获第二次 Page AI run payload");
      await page.waitForTimeout(50);
    }
    await page.waitForFunction(
      () => (document.querySelector('[data-testid="wolai-page-ai-drawer"]')?.textContent || "").includes("Task502 response"),
      null,
      { timeout: UI_TIMEOUT_MS },
    );

    const runs = captured.filter((item) => item.kind === "run");
    assert(runs.length >= 1, "未捕获 Page AI run payload");
    const runBody = JSON.parse(runs[runs.length - 1].body);
    assert.strictEqual(runBody.agentId, "reasonix");
    assert(Array.isArray(runBody.contextRefs), "run payload 必须包含 contextRefs 数组");
    assert(!runBody.contextRefs.some((item) => item.kind === "current_page"), "取消当前页后不应发送 current_page contextRef");
    assert.strictEqual(runBody.pageContext?.aiContext?.pageText, undefined, "Page AI run 不应默认上传 pageText");
    assert.strictEqual(runBody.pageContext?.aiContext?.pageXml, undefined, "Page AI run 不应默认上传 pageXml");
    assert.strictEqual(runBody.pageContext?.aiContext?.contextBlocks, undefined, "Page AI run 不应默认上传 contextBlocks");
    assert.strictEqual(runBody.pageContext?.evidence, undefined, "Page AI run 不应默认上传选区 evidence 正文");
    assert.strictEqual(runBody.selectedText, "", "Page AI run 不应默认上传 selectedText 正文");
    const activeEditorRef = runBody.contextRefs.find((item) => item.kind === "active_editor" && item.documentId === documentId);
    assert(activeEditorRef, "run payload 应包含 active_editor contextRef");
    assert.strictEqual(activeEditorRef.targetId, "resource:mindmap:task502", `active_editor contextRef 应冻结 mindmap targetId: ${JSON.stringify(activeEditorRef)}`);
    assert.strictEqual(activeEditorRef.objectIdentity, "resource:mindmap:task502", `active_editor contextRef 应冻结 mindmap objectIdentity: ${JSON.stringify(activeEditorRef)}`);
    assert.strictEqual(activeEditorRef.resourceKind, "mindmap", `active_editor contextRef 应标记 mindmap resourceKind: ${JSON.stringify(activeEditorRef)}`);
    assert.strictEqual(activeEditorRef.assetId, "task502-mindmap", `active_editor contextRef 应携带 mindmap assetId: ${JSON.stringify(activeEditorRef)}`);
    assert.strictEqual(activeEditorRef.relativePath, "maps/Task502.mindmap.json", `active_editor contextRef 应携带 mindmap relativePath: ${JSON.stringify(activeEditorRef)}`);
    assert(runBody.contextRefs.some((item) => item.kind === "folder" && item.rootUri === rootUri));
    assert(runBody.contextRefs.some((item) => item.kind === "changed_files"));
    assert.strictEqual(runBody.skillPreferences?.mnote?.["mnote-current-page"], false, "MNote skill 开关应进入 run payload");
    assert.strictEqual(runBody.skillPreferences?.mnote?.["mnote-mindmap"], false, "MNote mindmap skill 开关应进入 run payload");
    assert.strictEqual(runBody.targetPackage?.schema, "mnote.agent_target_package.v1", "文档任务 run 应携带目标包");
    assert(runBody.targetPackage?.primaryTargetId, "文档任务 targetPackage 应包含 primaryTargetId");
    assert(Array.isArray(runBody.targetPackage?.targets), "文档任务 targetPackage 应包含 targets 数组");
    assert.strictEqual(runBody.targetPackage?.primaryTargetId, "resource:mindmap:task502", "文档任务 targetPackage 应冻结用户选择的 mindmap target");
    assert(
      runBody.targetPackage.targets.some((target) => target.resourceKind === "mindmap" && target.relativePath === "maps/Task502.mindmap.json"),
      `文档任务 targetPackage 应包含 mindmap 目标: ${JSON.stringify(runBody.targetPackage)}`,
    );
    assert.strictEqual(runBody.targetPackage?.policy?.writeRequiresExplicitTarget, true, "文档任务 targetPackage policy 应要求显式目标");
    const preferenceBodies = captured
      .filter((item) => item.kind === "ui-preferences" && item.method === "PUT")
      .map((item) => JSON.parse(item.body || "{}"));
    assert(preferenceBodies.some((body) => body.updates?.["ai.agent.hermes.profile_id"] === "shared_lite"), "Agent 内的 Hermes profile 选择应写入 SQLite UI preference");
    assert(captured.some((item) => item.kind === "capability-toggle" && JSON.parse(item.body || "{}").id === "mnote-current-page"), "MNote 能力开关应调用服务端 per-user SQLite policy");
    assert(preferenceBodies.some((body) => body.updates?.["ai.common.skills.groups.collapsed"]?.mnote === true), "能力分组折叠状态应写入 SQLite UI preference");
    assert(!preferenceBodies.some((body) => body.updates?.["ai.agent.reasonix.skills.enabled"]), "能力页不应再写入 Reasonix 自带 skill 偏好");
    assert(!preferenceBodies.some((body) => body.updates?.["ai.agent.hermes.skills.hide_builtin"] === true), "能力页不应再写入 Hermes 内置 skill 过滤偏好");
    assert(Array.isArray(runBody.allowedRoots), "run payload 必须包含 allowedRoots 数组");
    assert(runBody.allowedRoots.some((item) =>
      item.rootUri === rootUri
        && item.permission === "write"
        && item.source === "sqlite_directory_grant"
    ));
    assert.strictEqual(runBody.runTargetSnapshot?.source, "open_editors_snapshot");
    await page.waitForFunction(
      () => document.documentElement.getAttribute("data-mnote-page-ai-receipt-current-refresh") === "true",
      null,
      { timeout: UI_TIMEOUT_MS },
    );
    assert.strictEqual(
      await page.evaluate(() => document.documentElement.getAttribute("data-mnote-page-ai-receipt-filetree-refresh")),
      "true",
      "agentRunReceipt.changedFiles 应触发文件树事件驱动刷新",
    );

    const screenshot = await saveScreenshot(page, "01-agent-selector-context");
    const result = {
      ok: true,
      task: TASK,
      baseUrl: BASE_URL,
      root,
      rootUri,
      documentId,
      mnoteSkillsScreenshot,
      screenshot,
      skillsScreenshot,
      captured,
    };
    fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8");
    console.log(JSON.stringify(result, null, 2));
  } catch (error) {
    caughtError = error;
    await saveScreenshot(page, "failure").catch(() => undefined);
  } finally {
    fs.rmSync(root, { recursive: true, force: true });
    await page.close().catch(() => undefined);
    await context.close().catch(() => undefined);
    await browser.close().catch(() => undefined);
  }

  if (caughtError) {
    throw caughtError;
  }
}

if (require.main === module) {
  main().catch((error) => {
    console.error(error);
    process.exit(1);
  });
}
