diff --git a/external_plugins/web-task-extension/.zcode-plugin/plugin.json b/external_plugins/web-task-extension/.zcode-plugin/plugin.json new file mode 100644 index 00000000..7934d582 --- /dev/null +++ b/external_plugins/web-task-extension/.zcode-plugin/plugin.json @@ -0,0 +1,58 @@ +{ + "name": "web-task-extension", + "version": "0.1.0", + "description": "Turn a browser chore you repeat into a Chrome / Edge extension. Describe it; it becomes steps (open, click, fill, wait, extract rows with fields across pages, download CSV / JSON or linked files) with user settings, and a Manifest V3 extension with a Run button popup, an options page, minimal permissions explained in plain words, and a store-ready zip. The manifest and code are validated (references, icons, permissions vs. steps, MV3 CSP, scripts, locales). No login automation.", + "description_i18n": { + "en": "Turn a browser chore you repeat into a Chrome / Edge extension. Describe it; it becomes steps (open, click, fill, wait, extract rows with fields across pages, download CSV / JSON or linked files) with user settings, and a Manifest V3 extension with a Run button popup, an options page, minimal permissions explained in plain words, and a store-ready zip. The manifest and code are validated (references, icons, permissions vs. steps, MV3 CSP, scripts, locales). No login automation.", + "zh-CN": "把你在浏览器里反复做的操作变成 Chrome / Edge 扩展。描述一下流程,就会整理成步骤(打开、点击、填写、等待、跨页提取带字段的数据、下载 CSV / JSON 或链接文件)和设置项,并生成 Manifest V3 扩展:带“运行任务”按钮的弹窗、设置页、最小权限及通俗的权限说明,以及可上传商店的 zip。自动校验 manifest 和代码(引用文件、图标、权限与步骤是否一致、MV3 CSP、脚本、多语言)。不做自动登录。" + }, + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "keywords": [ + "chrome extension", + "browser extension", + "manifest v3", + "automation", + "web scraping", + "rpa", + "edge", + "浏览器扩展", + "自动化", + "网页操作", + "数据提取", + "插件" + ], + "skills": "skills", + "mcpServers": { + "web-task-extension": { + "type": "stdio", + "command": "node", + "args": [ + "${ZCODE_PLUGIN_ROOT}/dist/server.mjs" + ], + "cwd": "${ZCODE_PROJECT_DIR}", + "timeoutMs": 900000, + "env": { + "ZCODE_WORKSPACE_ROOT": "${ZCODE_PROJECT_DIR}" + } + } + }, + "ui": { + "surfaces": [ + { + "id": "editor", + "title": { + "zh-CN": "网页操作转浏览器扩展", + "en-US": "Web Task Extension" + }, + "icon": "puzzle", + "server": "web-task-extension", + "resourceUri": "ui://web-task-extension/panel.html", + "availability": "session" + } + ] + } +} diff --git a/external_plugins/web-task-extension/LICENSE b/external_plugins/web-task-extension/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/web-task-extension/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Penova + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/external_plugins/web-task-extension/README.md b/external_plugins/web-task-extension/README.md new file mode 100644 index 00000000..eb6bdfd6 --- /dev/null +++ b/external_plugins/web-task-extension/README.md @@ -0,0 +1,63 @@ +# Web Task Extension + +Turn a chore you repeat in the browser into a **Chrome / Edge extension** you run with one click. Describe the routine; the agent writes it as steps and this plugin generates, validates and zips a **Manifest V3** extension with **minimal, explained permissions**. + +## What it does + +- **Steps**: + - `open` a URL, `click` (by selector, optionally by text), `fill` text / `, true/false for checkboxes; {{setting}} / {{today}} placeholders allowed"), submit: z.boolean().optional().describe("Submit the form afterwards"), ...base }), + z.object({ action: z.literal("wait"), selector: selector.optional(), text: z.string().max(200).optional(), gone: z.boolean().optional().describe("Wait until it disappears"), ms: z.number().int().min(0).max(60_000).optional(), ...base }), + z.object({ action: z.literal("extract"), selector: selector.describe("One element per record (e.g. table rows)"), fields: z.record(z.string().regex(FIELD_NAME, "Column names: 1–40 letters (incl. Chinese/Japanese/Korean), digits, space, _ or -"), z.string().max(300)).optional().describe('Column → "css" (text), "css@attr" (attribute; href/src are absolute), "@attr" or "." (the record itself). Omit for plain text'), into: z.string().regex(/^[\w-]{1,40}$/).optional().describe('Dataset name (default "rows")'), next: selector.optional().describe("Next-page link/button to follow"), maxPages: z.number().int().min(1).max(50).optional(), limit: z.number().int().min(1).max(100_000).optional(), ...base }), + z.object({ action: z.literal("download"), from: z.string().regex(/^[\w-]{1,40}$/).optional().describe("Dataset to save (default rows)"), format: z.enum(["csv", "json"]).optional(), selector: selector.optional().describe("Instead of a dataset: download the files these links point to"), filename: z.string().max(200).optional().describe("Path inside the Downloads folder; placeholders allowed"), limit: z.number().int().min(1).max(100).optional(), ...base }), +]); +export const SettingSchema = z.object({ key: z.string().regex(/^[A-Za-z][\w]{0,39}$/), label: z.string().max(80).optional(), type: z.enum(["text", "number", "date", "select"]).optional(), options: z.array(z.string().max(100)).max(100).optional(), default: z.string().max(2000).optional(), required: z.boolean().optional(), placeholder: z.string().max(100).optional(), help: z.string().max(300).optional() }); +export type Step = z.infer; +export type Setting = z.infer; + +export interface Task { name: string; description: string; version: string; steps: Step[]; settings: Setting[]; sites: string[]; timeoutMs?: number; color?: string } +export interface Permission { name: string; kind: "permission" | "host"; en: string; zh: string } +export interface Problem { level: "error" | "warn"; where: string; message: string } + +const PLACE = /\{\{\s*([\w.-]+)\s*\}\}/g; +const BUILTIN = new Set(["today", "now"]); +export const slug = (s: string) => s.normalize("NFKD").replace(/[^\w-]+/g, "-").replace(/-{2,}/g, "-").replace(/^-+|-+$/g, "").toLowerCase().slice(0, 40) || "web-task"; + +/** "example.com" / "https://x.com/a" / "*.x.com" / match pattern → Chrome match pattern (scheme + host, any path). */ +export function toPattern(site: string): string | null { + const s = site.trim(); + if (!s) return null; + if (s === "") return s; + const m = s.match(/^(\*|https?):\/\/([^/]+)(\/.*)?$/i); + if (m) { + const host = m[2].replace(/:\d+$/, "").toLowerCase(); + if (!/^(\*|(\*\.)?[a-z0-9.-]+|\[[0-9a-f:]+\])$/i.test(host)) return null; + return `${m[1].toLowerCase()}://${host}/*`; + } + if (/^(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)+$/i.test(s) || /^localhost$/i.test(s)) return `https://${s.toLowerCase()}/*`; + return null; +} +export const MATCH_PATTERN = /^(|(\*|https?|wss?|ftp|file):\/\/(\*|(\*\.)?[^/*:]+|\[[0-9a-fA-F:]+\])?\/.*)$/; +export function patternCovers(pattern: string, url: string): boolean { + if (pattern === "") return true; + const m = pattern.match(/^(\*|[a-z]+):\/\/([^/]*)\//); + if (!m) return false; + let u: URL; + try { u = new URL(url); } catch { return false; } + const scheme = u.protocol.slice(0, -1); + if (m[1] === "*" ? !["http", "https"].includes(scheme) : m[1] !== scheme) return false; + const host = m[2]; + if (host === "*") return true; + if (host.startsWith("*.")) return u.hostname === host.slice(2) || u.hostname.endsWith(host.slice(1)); + return u.hostname === host; +} + +/** 校验并规范化任务;返回问题列表(error 会阻止生成)。 */ +export function checkTask(task: Task): Problem[] { + const p: Problem[] = []; + const keys = new Set(task.settings.map((s) => s.key)); + const dup = task.settings.map((s) => s.key).filter((k, i, a) => a.indexOf(k) !== i); + for (const k of new Set(dup)) p.push({ level: "error", where: "settings", message: `Setting "${k}" is defined twice.` }); + for (const s of task.settings) if (s.type === "select" && !s.options?.length) p.push({ level: "error", where: `settings.${s.key}`, message: "A select setting needs options." }); + if (!task.steps.length) p.push({ level: "error", where: "steps", message: "Add at least one step." }); + const datasets = new Set(); + task.steps.forEach((s, i) => { + const at = `step ${i + 1} (${s.action})`; + for (const v of [("url" in s ? s.url : ""), ("value" in s ? s.value : ""), ("filename" in s ? s.filename : "") ?? "", ("text" in s ? s.text : "") ?? ""]) for (const m of String(v ?? "").matchAll(PLACE)) if (!keys.has(m[1]) && !BUILTIN.has(m[1])) p.push({ level: "error", where: at, message: `Unknown placeholder {{${m[1]}}}; add a setting with key "${m[1]}" (built-ins: today, now).` }); + if (s.action === "open") { + const probe = s.url.replace(PLACE, "x"); + let u: URL | null = null; + try { u = new URL(probe); } catch { /* below */ } + if (!u || !/^https?:$/.test(u.protocol)) p.push({ level: "error", where: at, message: `Open needs an http(s) URL (got ${s.url}).` }); + else if (/\{\{/.test(s.url.replace(/^\w+:\/\//, "").split(/[/?#]/)[0])) p.push({ level: "error", where: at, message: "Placeholders can't change the site (host) of an Open URL; the extension only gets access to fixed sites." }); + } + if (s.action === "wait" && !s.selector && !s.ms) p.push({ level: "error", where: at, message: "Wait needs a selector or ms." }); + if (s.action === "extract") datasets.add(s.into ?? "rows"); + if (s.action === "download" && !s.selector && !datasets.has(s.from ?? "rows")) p.push({ level: "error", where: at, message: `Nothing extracted into "${s.from ?? "rows"}" before this download.` }); + if (s.action === "download" && s.selector && s.format) p.push({ level: "warn", where: at, message: "format is ignored when downloading linked files." }); + if ("filename" in s && s.filename && (/(^|\/)\.\.(\/|$)/.test(s.filename) || s.filename.startsWith("/"))) p.push({ level: "error", where: at, message: "filename must be a relative path inside Downloads." }); + if (s.action === "fill" && /pass(word)?|pwd|otp|token|secret/i.test(s.selector + " " + s.value)) p.push({ level: "warn", where: at, message: "Looks like a password or code. Logging in is out of scope: sign in yourself before running; don't store secrets in the task." }); + }); + if (task.steps[0] && task.steps[0].action !== "open") p.push({ level: "warn", where: "step 1", message: "The task doesn't start with Open, so it runs on whatever tab is active when you press Run (uses activeTab)." }); + for (const site of task.sites) { + const pat = toPattern(site); + if (!pat) p.push({ level: "error", where: "sites", message: `"${site}" isn't a site or match pattern.` }); + else if (pat === "" || /:\/\/\*\//.test(pat)) p.push({ level: "error", where: "sites", message: `"${site}" would grant access to every website; list the specific sites instead.` }); + } + return p; +} + +const tabsOnly = (task: Task) => task.steps[0]?.action !== "open"; +/** 最小权限:只列步骤用到的。 */ +export function permissions(task: Task): Permission[] { + const out: Permission[] = [ + { name: "storage", kind: "permission", en: "Keeps your settings and the last run's results in this browser.", zh: "在本浏览器里保存你的设置和上次运行的结果。" }, + { name: "scripting", kind: "permission", en: "Runs the click / fill / wait / extract steps inside the task's pages, only when you press Run.", zh: "只在你点“运行任务”时,在任务网页里执行点击、填写、等待、提取这些步骤。" }, + ]; + if (task.steps.some((s) => s.action === "download")) out.push({ name: "downloads", kind: "permission", en: "Saves the extracted data (CSV/JSON) or the linked files to your Downloads folder.", zh: "把提取的数据(CSV/JSON)或链接的文件保存到“下载”文件夹。" }); + if (tabsOnly(task)) out.push({ name: "activeTab", kind: "permission", en: "Works on the tab you are looking at when you click the extension, and on no other tab.", zh: "只在你点开扩展时正在看的那个标签页上工作,不碰其他标签页。" }); + for (const h of hostPatterns(task)) out.push({ name: h, kind: "host", en: `Lets the steps open and read pages on ${h.replace(/^\w+:\/\/|\/\*$/g, "")}. No other site is accessible.`, zh: `允许步骤打开并读取 ${h.replace(/^\w+:\/\/|\/\*$/g, "")} 上的网页;其他网站都无法访问。` }); + return out; +} +export function hostPatterns(task: Task): string[] { + const set = new Set(); + for (const s of task.steps) if (s.action === "open") { const pat = toPattern(s.url.replace(PLACE, "x").replace(/\?.*$/, "")); if (pat) set.add(pat); } + for (const site of task.sites) { const pat = toPattern(site); if (pat && pat !== "" && !/:\/\/\*\//.test(pat)) set.add(pat); } + return [...set]; +} diff --git a/ui-plugins/web-task-extension/test/_mkclient.ts b/ui-plugins/web-task-extension/test/_mkclient.ts new file mode 100644 index 00000000..ab96ba54 --- /dev/null +++ b/ui-plugins/web-task-extension/test/_mkclient.ts @@ -0,0 +1,18 @@ +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { createServer } from "../src/server.ts"; + +export async function mkclient(prefix: string) { + const root = mkdtempSync(join(tmpdir(), prefix)); + const server = createServer({ workspaceRoot: root, assetRoot: join(import.meta.dirname, "../dist") } as any); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + const client = new Client({ name: "t", version: "1" }); + await client.connect(b); + const call = async (name: string, args: Record) => (await client.callTool({ name, arguments: args })) as any; + const text = (r: any) => (r.content ?? []).map((c: any) => c.text ?? "").join(" "); + return { root, call, text }; +} diff --git a/ui-plugins/web-task-extension/test/findings-fixes.test.ts b/ui-plugins/web-task-extension/test/findings-fixes.test.ts new file mode 100644 index 00000000..8c4deab7 --- /dev/null +++ b/ui-plugins/web-task-extension/test/findings-fixes.test.ts @@ -0,0 +1,30 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { FIELD_NAME } from "../src/task.ts"; +import { mkclient } from "./_mkclient.ts"; + +describe("DRYRUN #29: Chinese column names in extract.fields", () => { + it("accepts CJK/Latin names with and without the u flag, rejects punctuation and over-long names", () => { + const noU = new RegExp(FIELD_NAME.source); + const withU = new RegExp(FIELD_NAME.source, "u"); + for (const ok of ["书名", "价格", "Price", "库存 数量", "評価", "가격", "item_id", "名称-2"]) { expect(noU.test(ok), ok).toBe(true); expect(withU.test(ok), ok).toBe(true); } + for (const bad of ["", "价格{{x}}", "a/b", "名".repeat(41), "😀"]) expect(noU.test(bad), bad).toBe(false); + }); + it("ext_new builds an extension with 书名/价格 columns", async () => { + const { root, call, text } = await mkclient("wte-"); + const r = await call("ext_new", { + name: "图书价格导出", + sites: ["https://books.toscrape.com/*"], + steps: [ + { action: "open", url: "https://books.toscrape.com/" }, + { action: "extract", selector: "article.product_pod", fields: { 书名: "h3 a@title", 价格: ".price_color" } }, + { action: "download", format: "csv" }, + ], + }); + expect(r.isError, text(r)).toBeFalsy(); + const out = r.structuredContent?.saved?.out ?? r.structuredContent?.out; + const task = JSON.parse(readFileSync(join(root, out, "task.json"), "utf8")); + expect(Object.keys(task.steps[1].fields)).toEqual(["书名", "价格"]); + }); +}); diff --git a/ui-plugins/web-task-extension/test/tools.test.ts b/ui-plugins/web-task-extension/test/tools.test.ts new file mode 100644 index 00000000..a435e073 --- /dev/null +++ b/ui-plugins/web-task-extension/test/tools.test.ts @@ -0,0 +1,116 @@ +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { unzipSync } from "fflate"; +import { beforeAll, describe, expect, it } from "vitest"; +import { pngSize } from "../src/icons.ts"; +import { checkTask, permissions, toPattern } from "../src/task.ts"; +import { createServer } from "../src/server.ts"; + +// 样例:虚构的 Harbor Bikes 供应商门户任务(搜索、翻页、导出 CSV、下载规格单)、books.toscrape.com 任务、以及“当前标签页”任务。 +const S = process.env.TASK_SAMPLES ?? "/workspace/zcode-new-plugins/samples/webtask"; +const sample = (f: string, portal = "http://127.0.0.1:8123") => JSON.parse(readFileSync(join(S, f), "utf8").replaceAll("{{PORTAL}}", portal)); +let ws: string; +let call: (name: string, args: Record) => Promise; +beforeAll(async () => { + ws = mkdtempSync(join(tmpdir(), "wte-")); + const server = createServer({ workspaceRoot: ws, assetRoot: join(import.meta.dirname, "../dist") }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + const client = new Client({ name: "t", version: "1" }); + await client.connect(b); + call = async (name, args) => (await client.callTool({ name, arguments: args })) as any; +}); + +describe("task model", () => { + it("derives minimal permissions", () => { + const portal = { ...sample("portal-task.json"), version: "1.0.0", sites: [] }; + expect(permissions(portal).map((p) => p.name)).toEqual(["storage", "scripting", "downloads", "http://127.0.0.1/*"]); + const books = { ...sample("books-task.json"), version: "1.0.0", settings: [], sites: [] }; + expect(permissions(books).map((p) => p.name)).toEqual(["storage", "scripting", "downloads", "https://books.toscrape.com/*"]); + const tab = { ...sample("current-tab-task.json"), version: "1.0.0", settings: [], sites: [] }; + expect(permissions(tab).map((p) => p.name)).toEqual(["storage", "scripting", "downloads", "activeTab"]); + expect(toPattern("shop.example.com")).toBe("https://shop.example.com/*"); + expect(toPattern("http://localhost:3000/app?x=1")).toBe("http://localhost/*"); + expect(toPattern("*.example.org")).toBe("https://*.example.org/*"); + expect(toPattern("not a site")).toBeNull(); + }); + it("catches task mistakes", () => { + const base = { name: "x", description: "", version: "1.0.0", settings: [], sites: [] as string[] }; + const errs = (t: object) => checkTask({ ...base, ...t } as never).filter((p) => p.level === "error").map((p) => p.message); + expect(errs({ steps: [{ action: "fill", selector: "#q", value: "{{term}}" }] })[0]).toMatch(/Unknown placeholder \{\{term\}\}/); + expect(errs({ steps: [{ action: "open", url: "https://{{host}}.example.com/" }], settings: [{ key: "host" }] })[0]).toMatch(/can't change the site/); + expect(errs({ steps: [{ action: "open", url: "ftp://x.com/" }] })[0]).toMatch(/http\(s\)/); + expect(errs({ steps: [{ action: "download" }] })[0]).toMatch(/Nothing extracted/); + expect(errs({ steps: [{ action: "wait" }] })[0]).toMatch(/selector or ms/); + expect(errs({ steps: [{ action: "open", url: "https://a.com/" }], sites: [""] })[0]).toMatch(/every website/); + expect(errs({ steps: [{ action: "extract", selector: "tr" }, { action: "download", filename: "../x.csv" }] })[0]).toMatch(/relative path/); + const warns = checkTask({ ...base, steps: [{ action: "fill", selector: "#password", value: "x" }] } as never).filter((p) => p.level === "warn").map((p) => p.message); + expect(warns.join(" ")).toMatch(/password.*out of scope/i); + }); +}); + +describe("tools", () => { + it("generates, validates and zips the portal extension", async () => { + const r = await call("ext_new", sample("portal-task.json")); + expect(r.isError).toBeFalsy(); + const s = r.structuredContent.saved; + expect(s).toMatchObject({ out: "extensions/harbor-parts-price-export", version: "1.0.0", errors: 0, warnings: 0, zip: "extensions/harbor-parts-price-export-1.0.0.zip" }); + expect(s.checks.every((c: { ok: boolean }) => c.ok)).toBe(true); + const dir = join(ws, s.out); + const m = JSON.parse(readFileSync(join(dir, "manifest.json"), "utf8")); + expect(m).toMatchObject({ manifest_version: 3, permissions: ["storage", "scripting", "downloads"], host_permissions: ["http://127.0.0.1/*"], action: { default_popup: "popup.html" }, options_page: "options.html", background: { service_worker: "background.js" } }); + expect(m.content_scripts).toBeUndefined(); + expect(pngSize(readFileSync(join(dir, "icons/icon128.png")))).toEqual([128, 128]); + expect(readFileSync(join(dir, "PERMISSIONS.md"), "utf8")).toMatch(/`downloads` \| Saves the extracted data/); + const z = unzipSync(readFileSync(join(ws, s.zip))); + expect(Object.keys(z)).toContain("manifest.json"); + expect(Object.keys(z)).not.toContain("README.md"); + expect(Object.keys(z).sort()).toEqual(["_locales/en/messages.json", "_locales/zh_CN/messages.json", "background.js", "common.js", "icons/icon128.png", "icons/icon16.png", "icons/icon32.png", "icons/icon48.png", "manifest.json", "options.html", "options.js", "popup.html", "popup.js", "steps.js", "task.json", "ui.css"]); + expect(r.structuredContent.preview.zh).toContain("运行任务"); + expect(r.content[0].text).toMatch(/Load unpacked/); + const again = await call("ext_new", sample("portal-task.json")); + expect(again.content[0].text).toMatch(/\[exists\]/); + }); + it("rejects a bad task with the reason", async () => { + const r = await call("ext_new", { name: "Bad", steps: [{ action: "fill", selector: "#q", value: "{{nope}}" }] }); + expect(r.isError).toBe(true); + expect(r.content[0].text).toMatch(/\[bad_task\].*nope/s); + }); + it("updates, bumps the version and keeps permissions in step with the steps", async () => { + await call("ext_new", sample("books-task.json")); + const r = await call("ext_update", { out: "extensions/mystery-books-price-list", steps: sample("books-task.json").steps.slice(0, 3) }); + const s = r.structuredContent.saved; + expect(s.version).toBe("1.0.1"); + expect(s.permissions.map((p: { name: string }) => p.name)).toEqual(["storage", "scripting", "https://books.toscrape.com/*"]); + expect(s.zip).toBe("extensions/mystery-books-price-list-1.0.1.zip"); + const list = await call("ext_list", {}); + expect(list.content[0].text).toMatch(/mystery-books-price-list\/ — “Mystery books price list” 1\.0\.1/); + }); + it("ext_check catches hand edits that break MV3 rules", async () => { + await call("ext_new", { ...sample("current-tab-task.json"), out: "ext/tab" }); + const dir = join(ws, "ext/tab"); + const ok = await call("ext_check", { out: "ext/tab" }); + expect(ok.structuredContent.saved.errors).toBe(0); + expect(ok.structuredContent.saved.warnings).toBe(1); // 不以 Open 开头 → activeTab 提醒 + const m = JSON.parse(readFileSync(join(dir, "manifest.json"), "utf8")); + m.permissions.push("tabs"); + m.host_permissions = [""]; + writeFileSync(join(dir, "manifest.json"), JSON.stringify(m)); + writeFileSync(join(dir, "popup.html"), readFileSync(join(dir, "popup.html"), "utf8").replace("", '')); + writeFileSync(join(dir, "options.js"), "const x = eval('1'); function ("); + writeFileSync(join(dir, "icons/icon48.png"), readFileSync(join(dir, "icons/icon16.png"))); + const bad = await call("ext_check", { out: "ext/tab" }); + const c = Object.fromEntries(bad.structuredContent.saved.checks.map((x: { id: string }) => [x.id, x])); + expect(c.csp.ok).toBe(false); + expect(c.csp.message).toMatch(/inline