Spot it. Save it. Free, local-first Chrome extension for images, videos and prompts. Explore 2,000+ curated cases and connect your library to AI Agents via MCP. 提示词导演
JavaScript ai-artai-videochrome-extensionclaude-codecodexhiggsfieldjimenglocal-firstmcpmidjourneymoodboardprompt-engineeringprompt-libraryprompt-managerreference-libraryseedancevisual-bookmarksweb-clipper
Release 1.28.0: complete Skills and faster case details (#43)
wchao6891f601f6436112
diff --git a/.github/actions/setup-browser/action.yml b/.github/actions/setup-browser/action.ymlindex aaf7289..10e7100 100644--- a/.github/actions/setup-browser/action.yml+++ b/.github/actions/setup-browser/action.yml@@ -12,7 +12,7 @@ runs:python-version: "3.12"- run: npm cishell: bash- - run: python -m pip install playwright==1.58.0+ - run: python -m pip install playwright==1.64.0shell: bash- if: runner.os == 'Linux'shell: bashdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9a5d8aa..78630d1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,15 @@了解每个版本带来的功能变化与使用改善。下载请前往 [GitHub Releases](https://github.com/wchao6891/PromptDirector/releases/latest)。+## 1.28.0++- 案例详情先显示图片与正文,再补充生成信息和相似案例;减少标签重复整理、透明度重复扫描及密集瀑布流重排开销。++- Skill 导入、编辑、导出与精选保存完整保留包内文件,包括脚本、许可和二进制资源;查看脚本不会执行它。+- Skill 详情和创作中心新增文件树、文本编辑与媒体预览,下载整包或当前文件统一到原下载入口。+- 精选 Skill 支持完整参考文件,来源资料不再在投稿过程中被静默删除。+- 简化 Skill 详情标题区,封面统一使用横向展示区域,避免长图挤占阅读空间。+## 1.27.1- 修复首次手选追加覆盖已有采集内容的问题,保留正文、提示词、图片和截图;同一图片合并可用来源。diff --git a/docs/RELEASE_VERIFICATION.md b/docs/RELEASE_VERIFICATION.mdindex ea7197f..b30d093 100644--- a/docs/RELEASE_VERIFICATION.md+++ b/docs/RELEASE_VERIFICATION.md@@ -21,7 +21,7 @@ Each browser receipt includes its complete planned scenario list, every result,Only a full successful run uploads `promptdirector-tested-packages-<commit>` with `ci-validation.json`; partial checks never produce a full-release artifact. Download that exact artifact for publication and compare its recorded source tree with the merged commit. Publish the existing ZIP/checksum files after readback verification; do not rebuild them. The store ZIP remains a separate channel.-Linux browser shards and the Linux upgrade job use Ubuntu 24.04, supported by the pinned Playwright 1.58.0 browser runtime. Keep that runner label aligned with `.github/actions/setup-browser/action.yml` when changing the test runtime.+Linux browser shards and the Linux upgrade job use Ubuntu 24.04, supported by the pinned Playwright 1.64.0 browser runtime. Keep that runner label aligned with `.github/actions/setup-browser/action.yml` when changing the test runtime.## Triggers and local checksdiff --git a/extension/background.js b/extension/background.jsindex a2becdb..62aa687 100644--- a/extension/background.js+++ b/extension/background.js@@ -1,3 +1,4 @@+import { skillRevision } from "./skill-operations.js";import { sameUndoState } from './undo-state.js';import { normalizeAnalysisScope, selectAnalysisScope, sameAnalysisTargets } from "./analysis-scope.js";import { createDedupeMediaVerifier } from './dedupe-media-verifier.js';@@ -4081,6 +4082,8 @@ async function createCreativeSkillAction(message) {async function saveCreativeSkillVersionAction(message) {const stored = await libraryStorage.get(['creativeSkills', 'composerSessions', 'creativeRuns', 'creativeJobs']);+ const current = normalizeCreativeSkillsState(stored.creativeSkills).items.find(skill => skill.id === message.skillId);+ if (message.expectedRevision && await skillRevision(current) !== message.expectedRevision) throw new Error("Skill 已变化,请重新打开后再编辑");const result = saveCreativeSkillVersion(stored[STORAGE_KEYS.creativeSkills], message.skillId, message.version, { protectedVersionIds: protectedSkillVersionIds(stored) });await commitSkillCoverResult(result, message.cover);await deleteUnreferencedMedia(normalizeCreativeSkillsState(stored[STORAGE_KEYS.creativeSkills]).items.flatMap(skillPackageAssetIds)).catch(error => console.warn("Skill资源清理未完成", error));diff --git a/extension/collector.js b/extension/collector.jsindex 22248ab..d44eb1d 100644--- a/extension/collector.js+++ b/extension/collector.js@@ -329,7 +329,7 @@ elements.contentType.addEventListener("change", () => updateCaptureMetadata({}));await captureAssistantView.restore();-void startAutomaticPageCapture();+export const collectorStartup = startAutomaticPageCapture();async function startAutomaticPageCapture() {if (autoPageCaptureActive || pageCaptureBatch || pageCaptureRequestId || pendingCaptureActiondiff --git a/extension/creative-skill-package.js b/extension/creative-skill-package.jsindex 8b8b11b..49e210f 100644--- a/extension/creative-skill-package.js+++ b/extension/creative-skill-package.js@@ -97,18 +97,20 @@ export async function exportStoredSkillPackage(skillValue = {}, options = {}) {}export async function storedSkillFiles(skillValue = {}, options = {}) {+ const selected = options.paths ? new Set(options.paths) : null;const packageFiles = Array.isArray(skillValue.packageFiles) ? skillValue.packageFiles : [];const hasStoredDocument = packageFiles.some(file => file.path === "SKILL.md" || file.path.endsWith("/SKILL.md"));if (!packageFiles.length) {const versions = Array.isArray(skillValue.versions) ? skillValue.versions : [];const version = versions.find((item) => item.id === skillValue.currentVersionId) ?? versions.at(-1) ?? {};- return generatedSkillFiles({+ const generated = generatedSkillFiles({portableId: skillValue.portableId,description: skillValue.description,skillMarkdown: version.skillMarkdown,references: version.references,provenanceMarkdown: version.provenanceMarkdown});+ return selected ? new Map([...generated].filter(([path]) => selected.has(path))) : generated;}if (typeof options.readFile !== "function") throw new Error("Skill 导出缺少文件读取器");const version = (skillValue.versions ?? []).find(item => item.id === skillValue.currentVersionId) ?? skillValue.versions?.at(-1);@@ -117,6 +119,7 @@ export async function storedSkillFiles(skillValue = {}, options = {}) {...version})].map(([name, data]) => ({ name, data }));for (const file of packageFiles) {+ if (selected && !selected.has(file.path)) continue;const path = normalizePackagePath(file?.path);if (!path || path !== file?.path) throw new Error("Skill 包含不安全的文件路径");const blob = await options.readFile(file.assetId);@@ -127,25 +130,35 @@ export async function storedSkillFiles(skillValue = {}, options = {}) {files.push({ name: path, data: blob });}const result = new Map(files.map(({ name, data }) => [name, data]));- if (hasStoredDocument && version) await applyCurrentVersionFiles(result, skillValue, version);- return result;+ if (hasStoredDocument && version) await applyCurrentVersionFiles(result, skillValue, version, selected);+ return selected ? new Map([...result].filter(([path]) => selected.has(path))) : result;+}++export function storedSkillPaths(skillValue = {}) {+ const version = (skillValue.versions ?? []).find(item => item.id === skillValue.currentVersionId) ?? skillValue.versions?.at(-1) ?? {};+ const paths = (skillValue.packageFiles ?? []).map(file => file.path);+ const main = paths.find(path => path === "SKILL.md" || path.endsWith("/SKILL.md")) ?? "SKILL.md";+ const prefix = main.slice(0, -"SKILL.md".length);+ return [...new Set([...paths, main, ...(version.references ?? []).map(ref => prefix + ref.path), ...(version.provenanceMarkdown ? [prefix + "references/provenance.md"] : [])])];}// Stored package blobs are the import-time snapshot; the current version's edited// SKILL.md, references, and provenance replace their copies at the same package paths.-async function applyCurrentVersionFiles(files, skillValue, version) {- const skillPath = [...files.keys()].find(path => path === "SKILL.md" || path.endsWith("/SKILL.md"));+async function applyCurrentVersionFiles(files, skillValue, version, selected) {+ const skillPath = storedSkillPaths(skillValue).find(path => path === "SKILL.md" || path.endsWith("/SKILL.md"));const prefix = skillPath.slice(0, -"SKILL.md".length);- const storedMarkdown = await readMarkdown(files.get(skillPath), skillPath);- const storedFields = parseFrontmatter(storedMarkdown.match(/^---\n([\s\S]*?)\n---(?:\n|$)/)?.[1]);- const storedDescription = cleanInline(storedFields.description);- const description = cleanInline(skillValue.description) || storedDescription;- const body = stripFrontmatter(version.skillMarkdown);- if (body && (body !== stripFrontmatter(storedMarkdown) || description !== storedDescription)) {- const markdown = buildSkillMarkdown({ name: normalizePortableId(storedFields.name) || skillValue.portableId, description, body });- const extra = extraFrontmatter(storedMarkdown);- const merged = extra ? markdown.replace(/\n---\n/, `\n${extra}\n---\n`) : markdown;- files.set(skillPath, new Blob([merged], { type: markdownType }));+ if (!selected || selected.has(skillPath)) {+ const storedMarkdown = await readMarkdown(files.get(skillPath), skillPath);+ const storedFields = parseFrontmatter(storedMarkdown.match(/^---\n([\s\S]*?)\n---(?:\n|$)/)?.[1]);+ const storedDescription = cleanInline(storedFields.description);+ const description = cleanInline(skillValue.description) || storedDescription;+ const body = stripFrontmatter(version.skillMarkdown);+ if (body && (body !== stripFrontmatter(storedMarkdown) || description !== storedDescription)) {+ const markdown = buildSkillMarkdown({ name: normalizePortableId(storedFields.name) || skillValue.portableId, description, body });+ const extra = extraFrontmatter(storedMarkdown);+ const merged = extra ? markdown.replace(/\n---\n/, `\n${extra}\n---\n`) : markdown;+ files.set(skillPath, new Blob([merged], { type: markdownType }));+ }}const references = new Map((Array.isArray(version.references) ? version.references : []).map(reference => [normalizeReferencePath(reference?.path), normalizeMarkdown(reference?.markdown)]));@@ -154,6 +167,7 @@ async function applyCurrentVersionFiles(files, skillValue, version) {for (const [path, markdown] of references) {if (!path || !markdown) continue;const packagePath = `${prefix}${path}`;+ if (selected && !selected.has(packagePath)) continue;const current = files.get(packagePath);if (current && normalizeMarkdown(await current.text()) === markdown) continue;files.set(packagePath, new Blob([`${markdown}\n`], { type: markdownType }));diff --git a/extension/curated-skill-catalog.js b/extension/curated-skill-catalog.jsindex e5c37b2..278b040 100644--- a/extension/curated-skill-catalog.js+++ b/extension/curated-skill-catalog.js@@ -1,7 +1,7 @@import { parseSkillArchive } from "./creative-skill-package.js";import { LIBRARY_TRANSFER_LIMITS } from "./resource-limits.js";import { sha256Hex } from "./sync-crypto.js";-import { isSkillCoverPath, normalizeSkillCoverMetadata, validateSkillCover } from "./skill-cover.js";+import { normalizeSkillCoverMetadata, validateSkillCover } from "./skill-cover.js";import { CURATED_SKILL_CATALOG_URL } from "./curated-config.js";export const CURATED_SKILL_CATALOG_FORMAT = "prompt-director-curated-skills";@@ -46,13 +46,6 @@ export async function validateCuratedSkillPackage(itemValue, archive) {const item = normalizeItem(itemValue);const parsed = await parseSkillArchive(archive);if (parsed.name !== item.skillId) throw new Error("精选 Skill 包身份与目录不一致");- for (const path of parsed.files.keys()) {- const relative = parsed.root && path.startsWith(`${parsed.root}/`) ? path.slice(parsed.root.length + 1) : path;- if (relative !== "SKILL.md" && !isSkillCoverPath(relative) && !/^references\/[A-Za-z0-9._/-]+\.md$/i.test(relative)) {- throw new Error(`精选 Skill 包包含不允许的文件:${relative}`);- }- }- if (parsed.dependencies.length) throw new Error("精选 Skill 包不能依赖脚本、程序或外部工具");return parsed;}diff --git a/extension/curated-skill-install.js b/extension/curated-skill-install.jsindex 2db23d3..85f34d0 100644--- a/extension/curated-skill-install.js+++ b/extension/curated-skill-install.js@@ -39,8 +39,8 @@ export async function installCuratedSkillTransaction(options = {}) {source: "imported",reason: "imported",packageFiles,- runtimeDependencies: [],- textModeConfirmed: false,+ runtimeDependencies: options.parsed.dependencies,+ textModeConfirmed: options.parsed.requiresTextModeConfirmation,curatedOrigin: {catalogId: clean(options.item?.id),skillId: clean(options.item?.skillId),diff --git a/extension/curated-skill-package.js b/extension/curated-skill-package.jsindex f8ef445..b84f073 100644--- a/extension/curated-skill-package.js+++ b/extension/curated-skill-package.js@@ -20,7 +20,7 @@ export async function buildCuratedSkillSnapshot(skillValue, metadata = {}, optioconst parsed = await parseSkillFiles(stored);const files = new Map([...stored].map(([path, blob]) => [parsed.root ? path.slice(parsed.root.length + 1) : path, blob]));for (const path of files.keys()) {- if (isSkillCoverPath(path) || (path === "references/provenance.md" && metadata.includeProvenance !== true)) files.delete(path);+ if (isSkillCoverPath(path)) files.delete(path);}files.set(cover.path, cover.blob);const preview = [];diff --git a/extension/curated-skill-page.css b/extension/curated-skill-page.cssindex 3aafdd5..e41526c 100644--- a/extension/curated-skill-page.css+++ b/extension/curated-skill-page.css@@ -5,13 +5,10 @@.curated-skill-card-actions button:last-child { margin-left: auto; }.curated-skill-dialog { width: min(920px, calc(100vw - 32px)); max-height: calc(100dvh - 32px); border: 1px solid var(--ui-border-strong); border-radius: var(--ui-container-radius); padding: 0; color: var(--ui-text); background: var(--ui-surface); }.curated-skill-detail { padding: 24px; }-.curated-skill-detail header { display: flex; align-items: start; justify-content: space-between; gap: 18px; padding-right: 42px; }+.curated-skill-detail > header { display: flex; align-items: start; justify-content: space-between; gap: 18px; padding-right: 42px; }.curated-skill-detail-copy { display: grid; max-width: 650px; gap: 7px; }.curated-skill-detail h1 { margin: 0; font-size: 24px; line-height: 1.3; }.curated-skill-detail p { margin: 0; color: var(--ui-muted); }-.curated-skill-maintenance { margin-top: 18px; border-top: 1px solid var(--ui-border); padding-top: 12px; color: var(--ui-muted); font-size: var(--ui-meta-size); }-.curated-skill-maintenance summary { width: max-content; cursor: pointer; color: var(--ui-text); font-weight: 750; }-.curated-skill-maintenance-copy { display: flex; flex-wrap: wrap; gap: 6px 14px; padding-top: 10px; }.curated-skill-markdown { margin-top: 18px; border-top: 1px solid var(--ui-border); padding-top: 18px; }.curated-skill-empty { display: grid; min-height: 55dvh; align-content: center; justify-items: center; gap: 10px; padding: 32px 20px; color: var(--ui-muted); text-align: center; }.curated-skill-state-copy { display: grid; justify-items: center; gap: 8px; }@@ -25,6 +22,6 @@.curated-skill-grid, .curated-skill-app .curated-loading { grid-template-columns: 1fr; }.curated-skill-dialog { width: calc(100vw - 16px); max-height: calc(100dvh - 16px); }.curated-skill-detail { padding: 18px 14px; }- .curated-skill-detail header { display: grid; padding-right: 38px; }- .curated-skill-detail header > button { justify-self: start; }+ .curated-skill-detail > header { display: grid; padding-right: 38px; }+ .curated-skill-detail > header > button { justify-self: start; }}diff --git a/extension/curated-skill-page.js b/extension/curated-skill-page.jsindex 3bc1b81..10f2323 100644--- a/extension/curated-skill-page.js+++ b/extension/curated-skill-page.js@@ -16,7 +16,7 @@ import { fetchCuratedPackage, readResponseBlobWithProgress } from "./curated-dowimport { installCuratedSkillTransaction, planCuratedSkillInstall } from "./curated-skill-install.js";import { initializeUi, t, translateUiMessage } from "./i18n.js";import { saveSkillPackageBlob } from "./media-store.js";-import { renderMarkdownDocument } from "./markdown-renderer.js";+import { createSkillFileBrowser } from "./skill-file-browser.js";await initializeUi();@@ -25,6 +25,8 @@ const elements = Object.fromEntries([].map((id) => [camel(id), document.querySelector(`#${id}`)]));const state = { catalog: null, creativeSkills: { version: 1, items: [] }, parsed: new Map(), archives: new Map(), query: "" };let toastTimer = 0;+let detailFiles = null;+let detailGeneration = 0;const covers = new Map();function loadCover(item) {if (!item.cover) return null;@@ -35,6 +37,7 @@ function loadCover(item) {elements.returnLibrary.addEventListener("click", () => location.assign(chrome.runtime.getURL("library.html")));elements.retryCatalog.addEventListener("click", start);elements.skillSearch.addEventListener("input", () => { state.query = elements.skillSearch.value.trim().toLocaleLowerCase(); render(); });+elements.skillDetailDialog.addEventListener("close", () => { detailGeneration++; detailFiles?.dispose(); });elements.skillDetailClose.addEventListener("click", () => elements.skillDetailDialog.close());elements.skillDetailDialog.addEventListener("click", (event) => { if (event.target === elements.skillDetailDialog) elements.skillDetailDialog.close(); });@@ -109,18 +112,24 @@ function card(item) {}async function openDetail(item) {+ const generation = ++detailGeneration;+ detailFiles?.dispose();for (const host of elements.skillDetailContent.querySelectorAll(".skill-cover-detail")) clearSkillCoverImage(host);elements.skillDetailContent.replaceChildren(element("div", "curated-skill-detail", t("正在校验并读取 Skill…")));elements.skillDetailDialog.showModal();try {const parsed = await loadParsed(item);- renderDetail(item, parsed);+ if (generation === detailGeneration) renderDetail(item, parsed);} catch (error) {+ if (generation !== detailGeneration) return;elements.skillDetailContent.replaceChildren(element("div", "curated-skill-detail", translateUiMessage(error.message) || t("Skill 读取失败")));}}function renderDetail(item, parsed) {+ const selectedPath = detailFiles?.selection();+ detailFiles?.dispose();+ for (const host of elements.skillDetailContent.querySelectorAll(".skill-cover-detail")) clearSkillCoverImage(host);const root = element("article", "curated-skill-detail");const header = element("header");const copy = element("div", "curated-skill-detail-copy");@@ -128,23 +137,12 @@ function renderDetail(item, parsed) {const action = installButton(item, parsed);action.classList.add("curated-skill-primary");header.append(copy, action);- const maintenance = element("details", "curated-skill-maintenance");- maintenance.append(element("summary", "", t("版本与许可")));- const maintenanceCopy = element("div", "curated-skill-maintenance-copy");- maintenanceCopy.append(- element("span", "", t("作者:{author}", { author: item.author })),- element("span", "", t("版本:{version}", { version: item.version })),- element("span", "", t("许可:{license}", { license: item.license })),- element("span", "", t("人工审核通过"))- );- maintenance.append(maintenanceCopy);const markdown = element("section", "curated-skill-markdown");- const document = renderMarkdownDocument(parsed.body);- removeDuplicateTitleHeading(document, item.title);- markdown.append(document);+ detailFiles = createSkillFileBrowser({ host: markdown });+ detailFiles.setSource({ paths: [...parsed.files.keys()], mainPath: parsed.root ? `${parsed.root}/SKILL.md` : 'SKILL.md', readFile: path => parsed.files.get(path) }, selectedPath);const cover = element("div", "skill-cover-detail");showSkillCoverImage(cover, () => loadCover(item), { alt: item.title });- root.append(cover, header, maintenance, markdown);+ root.append(cover, header, markdown);elements.skillDetailContent.replaceChildren(root);}@@ -168,6 +166,7 @@ async function loadParsed(item) {}async function install(item, parsed, button) {+ const generation = detailGeneration;button.disabled = true;button.setAttribute("aria-busy", "true");button.classList.add("is-progressing");@@ -191,7 +190,7 @@ async function install(item, parsed, button) {});showToast(t(installed.status === "already-installed" ? "这个版本已经在本地" : installed.status === "install-update-copy" ? "新版本已另存,不会覆盖本地修改" : "精选 Skill 已保存到本地"));render();- if (elements.skillDetailDialog.open) renderDetail(item, verified);+ if (elements.skillDetailDialog.open && generation === detailGeneration) renderDetail(item, verified);} catch (error) {button.disabled = planCuratedSkillInstall(state.creativeSkills, item).action === "already-installed";button.removeAttribute("aria-busy");@@ -219,15 +218,6 @@ function installButton(item, parsed = null) {return button;}-function removeDuplicateTitleHeading(document, title) {- const heading = document.querySelector?.("h1");- if (heading && normalizedHeading(heading.textContent) === normalizedHeading(title)) heading.remove();-}--function normalizedHeading(value) {- return String(value ?? "").trim().replace(/\s+/g, " ").toLocaleLowerCase();-}-function loading() {const node = element("section", "curated-loading");node.setAttribute("aria-label", t("正在加载精选 Skill"));diff --git a/extension/curated-skills.html b/extension/curated-skills.htmlindex 3b8e6be..0c5b3fb 100644--- a/extension/curated-skills.html+++ b/extension/curated-skills.html@@ -9,6 +9,7 @@<link rel="stylesheet" href="curated.css" /><link rel="stylesheet" href="curated-skill-page.css" /><link rel="stylesheet" href="skill-cover.css" />+ <link rel="stylesheet" href="skill-file-browser.css" /></head><body><header class="curated-header curated-header--skills">diff --git a/extension/facets.js b/extension/facets.jsindex e249c5a..f6ff13d 100644--- a/extension/facets.js+++ b/extension/facets.js@@ -58,8 +58,7 @@ export function facetNodes(catalog, facetId) {);}-export function facetNodePath(catalog, nodeId) {- const byId = new Map(normalizeFacetCatalog(catalog).nodes.map((item) => [item.id, item]));+export function facetNodePath(catalog, nodeId, byId = new Map(normalizeFacetCatalog(catalog).nodes.map((item) => [item.id, item]))) {const result = [];const seen = new Set();let current = byId.get(nodeId);@@ -71,8 +70,8 @@ export function facetNodePath(catalog, nodeId) {return result;}-export function formatFacetNodePath(catalog, nodeId) {- return facetNodePath(catalog, nodeId).map((item) => item.name).join(" / ");+export function formatFacetNodePath(catalog, nodeId, byId) {+ return facetNodePath(catalog, nodeId, byId).map((item) => item.name).join(" / ");}export function facetDescendants(catalog, nodeId) {diff --git a/extension/i18n.js b/extension/i18n.jsindex 4b8c5ec..937df37 100644--- a/extension/i18n.js+++ b/extension/i18n.js@@ -1,6 +1,24 @@import { normalizeUiPreferences, resolveLocale } from "./preferences.js";const EN = Object.freeze({+ "收起文件栏": "Collapse files",+ "展开文件栏": "Expand files",+ "文件": "Files",+ "Skill 包文件": "Skill package files",+ "正在读取文件…": "Reading file\u2026",+ "文件读取失败": "Could not read the file",+ "无法预览此文件,可从顶部下载": "Preview unavailable. Download this file from the top menu.",+ "编辑文件:{path}": "Edit file: {path}",+ "文件已切换": "The selected file changed",+ "空文件 · 0 B": "Empty file \u00b7 0 B",+ "替换同名文件?": "Replace files with the same names?",+ "替换": "Replace",+ "请在正文编辑区修改 SKILL.md;完整包请使用导入": "Edit SKILL.md in the main editor. Use Import for a complete package.",+ "下载完整 Skill": "Download complete Skill",+ "下载当前文件": "Download current file",+ "添加文件": "Add files",+ "添加文件夹": "Add folder",+"所选案例仍有关联引用或变化,本次未清理": "The selected cases still have references or have changed. Nothing was cleaned up.","案例引用或内容已变化,本次未清理": "Case references or content changed. Nothing was cleaned up.","创作会话": "Creative conversation",diff --git a/extension/image-transparency.js b/extension/image-transparency.jsindex 15d926b..7a56163 100644--- a/extension/image-transparency.js+++ b/extension/image-transparency.js@@ -1,30 +1,51 @@+import { ResourceCache } from './resource-cache.js';++// Blob URLs identify immutable bytes. Keep only completed booleans, never pixels+// or image elements, and use the caller's existing preview-cache budget.+export function createImageTransparencyObserver({ maxEntries }) {+ const results = new ResourceCache({ maxEntries });+ return (image, onResult) => observeImageTransparency(image, onResult, results);+}+// Inspect decoded pixels in small tiles so large originals do not require a// second full-size canvas or block opening the viewer.-export function observeImageTransparency(image, onResult) {+export function observeImageTransparency(image, onResult, results) {let generation = 0;const inspect = async () => {const token = ++generation;- if (!image.naturalWidth || !image.naturalHeight) return;+ const source = image.currentSrc || image.src;+ const requestedSource = image.src;+ const isCurrent = () => token === generation && image.isConnected &&+ requestedSource === image.src && source === (image.currentSrc || image.src);+ if (!image.naturalWidth || !image.naturalHeight || !isCurrent()) return;+ const cacheable = source.startsWith('blob:');+ const cached = cacheable ? results?.get(source) : undefined;+ if (cached !== undefined) { onResult(cached); return; }+ const finish = transparent => {+ if (!isCurrent()) return;+ if (cacheable) results?.set(source, transparent);+ onResult(transparent);+ };const canvas = document.createElement('canvas');canvas.width = canvas.height = 256;const context = canvas.getContext('2d', { willReadFrequently: true });try {for (let y = 0; y < image.naturalHeight; y += canvas.height) {for (let x = 0; x < image.naturalWidth; x += canvas.width) {- if (token !== generation) return;+ if (!isCurrent()) return;const width = Math.min(canvas.width, image.naturalWidth - x);const height = Math.min(canvas.height, image.naturalHeight - y);context.clearRect(0, 0, width, height);context.drawImage(image, x, y, width, height, 0, 0, width, height);const pixels = context.getImageData(0, 0, width, height).data;for (let at = 3; at < pixels.length; at += 4) {- if (pixels[at] < 255) { onResult(true); return; }+ if (pixels[at] < 255) { finish(true); return; }}}await new Promise(resolve => setTimeout(resolve, 0));- if (!image.isConnected || token !== generation) return;+ if (!isCurrent()) return;}- onResult(false);+ finish(false);} catch { /* An unreadable external image keeps the solid viewer background. */ }};image.addEventListener('load', inspect);diff --git a/extension/library-model.js b/extension/library-model.jsindex ea623ff..8b821cf 100644--- a/extension/library-model.js+++ b/extension/library-model.js@@ -54,19 +54,26 @@ function prepareFacetSelections(catalog, facetSelections) {});}-export function groupEntryAssignments(entry = {}, catalogValue, status = "confirmed") {+// Rebuild this reader when the catalog changes; assignments are read fresh on every call.+export function createEntryAssignmentReader(catalogValue) {const catalog = normalizeFacetCatalog(catalogValue);const nodeById = new Map(catalog.nodes.map((item) => [item.id, item]));- const grouped = new Map();- for (const assignment of entry.facetAssignments ?? []) {- if (assignment.status !== status) continue;- const node = nodeById.get(assignment.nodeId);- if (!node || node.status !== "active") continue;- const values = grouped.get(node.facetId) ?? [];- values.push({ ...assignment, name: node.name, path: formatFacetNodePath(catalog, node.id) });- grouped.set(node.facetId, values);- }- return grouped;+ return (entry = {}, status = "confirmed") => {+ const grouped = new Map();+ for (const assignment of entry.facetAssignments ?? []) {+ if (assignment.status !== status) continue;+ const node = nodeById.get(assignment.nodeId);+ if (!node || node.status !== "active") continue;+ const values = grouped.get(node.facetId) ?? [];+ values.push({ ...assignment, name: node.name, path: formatFacetNodePath(catalog, node.id, nodeById) });+ grouped.set(node.facetId, values);+ }+ return grouped;+ };+}++export function groupEntryAssignments(entry = {}, catalogValue, status = "confirmed") {+ return createEntryAssignmentReader(catalogValue)(entry, status);}export function entryAttributeSummary(entry, catalogValue, limit = 4) {diff --git a/extension/library.js b/extension/library.jsindex a347d74..06315f8 100644--- a/extension/library.js+++ b/extension/library.js@@ -58,7 +58,7 @@ import { attachArticleEditor } from "./article-editor.js";import { renderArticleBlockText } from "./article-text-view.js";import { articleBlockIsMarkdown, articleDocumentForReading } from "./article-document.js";import { libraryTitleForLocale, libraryTitleForStorage, renderLibraryJson, screenshotStorageKey } from "./lib.js";-import { observeImageTransparency } from "./image-transparency.js";+import { createImageTransparencyObserver } from "./image-transparency.js";import { createDetailProjectSelector } from "./detail-project-selector.js";import { readImageDimensions, imageNeedsOriginalPlayback } from "./image-metadata.js";import { readVideoMedia } from "./browser-video-media.js";@@ -118,7 +118,7 @@ import {entryContentTypeIds,entrySourceMetadataRows,filterEntries,- groupEntryAssignments,+ createEntryAssignmentReader,isEntryPending} from "./library-model.js";import {@@ -361,6 +361,7 @@ const PAGE_SIZE = 24;const DETAIL_TAG_PREVIEW_LIMIT = 6;const cacheWorkingBytes = operationBudget().workingBytes / 4;const previewCacheEntries = Math.max(PAGE_SIZE * 2, Math.floor(cacheWorkingBytes / (640 * 640 * 4)));+const observeImageTransparency = createImageTransparencyObserver({ maxEntries: previewCacheEntries });let mediaDragCard = null;const mediaDragUrls = new Set();const urlProtected = url => mediaDragUrls.has(url) || [...document.querySelectorAll('img[src],video[src],audio[src],source[src]')].some(node => node.src === url);@@ -442,6 +443,7 @@ elements.trashDialog.addEventListener('close', () => {const detailMediaUrls = new Set();const detailControllerCleanups = new Set();let activeDetailDiscovery = null;+let cancelPendingDiscovery = null;const documentPreviewUrls = new ResourceUrlCache({ maxBytes: cacheWorkingBytes, protectedValue: urlProtected });const documentDerived = new ResourceCache({ maxEntries: previewCacheEntries, maxBytes: cacheWorkingBytes,cost: value => (value.searchText?.length || 0) * 2 + (value.thumbnail?.size || 0) + (value.remoteImages || []).reduce((sum, image) => sum + (image.blob?.size || 0), 0) });@@ -472,6 +474,7 @@ let startupBrowsePlan = null;let taxonomy = { nodes: [] };let classificationRules = [];let facetCatalog = { facets: [], nodes: [] };+let readEntryAssignments = createEntryAssignmentReader(facetCatalog);const readVocabularyUsage = createVocabularyUsageReader();let settings = {};let organizerState = { collections: [] };@@ -1637,6 +1640,7 @@ async function refreshLibrary({ response: suppliedResponse, progressive = falsetaxonomy = response.taxonomy ?? { nodes: [] };classificationRules = response.classificationRules ?? [];facetCatalog = normalizeFacetCatalog(response.facetCatalog);+ readEntryAssignments = createEntryAssignmentReader(facetCatalog);settings = response.settings ?? {};organizerState = response.organizerState ?? { collections: [] };importJobsState = response.importJobs ?? { items: [] };@@ -1774,7 +1778,7 @@ async function applyLibraryEntriesChange(nextEntries, { changedEntryIds: knownIdrequestAnimationFrame(() => setTimeout(() => {if (currentDetailId !== entryId || detailRenderGeneration !== generation) return;const entry = logicalCases.find(item => item.id === entryId);- if (entry) refreshLocalDiscovery(entry);+ if (entry) refreshDeferredDetailSections(entry);}, 0));}done();@@ -6436,7 +6440,7 @@ async function renderDetail({ resetScroll = false, rebuildMedia = false } = {})const renderEntryId = currentDetailId;let entry = logicalCases.find((item) => item.id === currentDetailId);if (!entry) return closeDetail();- if (!usesArticleReader(entry)) entry = await readDetailGenerationInfo(entry);+ if (entry.compoundCase && !usesArticleReader(entry)) entry = await readDetailGenerationInfo(entry);if (renderGeneration !== detailRenderGeneration || currentDetailId !== renderEntryId) return;const codeCase = contentRoleForEntry(entry) === CONTENT_ROLES.codeCase || Boolean(entry.sourceFacts?.codePreviewAvailable && codePreviewHtml(entry.text));const mediaIdentity = JSON.stringify(entryMediaAssets(entry).filter(asset => asset.usage !== "poster").map(({ id, kind, usage, storageMode, contentHash, sourceUrl, reference, recordType }) =>@@ -6459,7 +6463,7 @@ async function renderDetail({ resetScroll = false, rebuildMedia = false } = {})if (attributes) previousAttributes.replaceWith(attributes);else previousAttributes.remove();} else if (attributes) mountedBody.insertBefore(attributes, organization);- mountAuthoredNotes(mountedBody, entry, t); arrangeDetailWorkspace(mountedBody); refreshLocalDiscovery(entry); return;+ mountAuthoredNotes(mountedBody, entry, t); arrangeDetailWorkspace(mountedBody); refreshDeferredDetailSections(entry); return;}if (!rebuildMedia && !resetScroll && usesArticleReader(entry) && elements.detailDrawer.dataset.entryId === entry.id&& mountedBody?.dataset.mediaIdentity === mediaIdentity && mountedBody.dataset.presentation === presentation@@ -6468,7 +6472,7 @@ async function renderDetail({ resetScroll = false, rebuildMedia = false } = {})if (header) replaceDetailSection(header, createDetailHeader(entry));refreshActiveDetailAssetSections(entry);mountAuthoredNotes(mountedBody, entry, t);- refreshLocalDiscovery(entry);+ refreshDeferredDetailSections(entry);return;}const mountedGallery = elements.detailContent.querySelector(".detail-visual-gallery");@@ -6500,7 +6504,7 @@ async function renderDetail({ resetScroll = false, rebuildMedia = false } = {})}mountAuthoredNotes(mountedBody, entry, t);arrangeDetailWorkspace(mountedBody);- refreshLocalDiscovery(entry);+ refreshDeferredDetailSections(entry);return;}releaseDetailControllers();@@ -6563,11 +6567,6 @@ async function renderDetail({ resetScroll = false, rebuildMedia = false } = {})if (breakdown) body.append(breakdown);primary.append(body);content.append(primary);- // When cases changed since the similarity index was built, show the case first and add its- // similar cases right after, instead of holding the whole detail until the index is rebuilt.- const deferDiscovery = localSimilarityIndexStale || !imageDerivedMetadataLoaded;- const discovery = deferDiscovery ? null : createLocalDiscovery(entry);- if (discovery) content.append(discovery.section);if (renderGeneration !== detailRenderGeneration || currentDetailId !== renderEntryId) return;mountAuthoredNotes(body, entry, t);elements.detailDrawer.dataset.entryId = entry.id;@@ -6577,16 +6576,7 @@ async function renderDetail({ resetScroll = false, rebuildMedia = false } = {})arrangeDetailWorkspace(body);const disposeWorkspace = () => { body.disposeWorkspace?.(); detailControllerCleanups.delete(disposeWorkspace); };detailControllerCleanups.add(disposeWorkspace);- discovery?.mount();- if (deferDiscovery) requestAnimationFrame(() => setTimeout(async () => {- try { await loadImageDerivedMetadata(); }- catch (error) { showFeedback(error.message || "无法读取本机资料", true); return; }- if (renderGeneration !== detailRenderGeneration || currentDetailId !== renderEntryId || !content.isConnected) return;- const deferred = createLocalDiscovery(entry);- if (!deferred) return;- content.append(deferred.section);- deferred.mount();- }, 0));+ refreshDeferredDetailSections(entry);if (hasMediaStage) {const dispose = attachDetailSplit(primary, {label: t("调整图文分栏宽度"),@@ -6629,15 +6619,61 @@ function invalidateDetailContent(entryId) {elements.detailContent.scrollTop = 0;}-function refreshLocalDiscovery(entry) {- const previous = activeDetailDiscovery;- previous?.cleanup();- const next = createLocalDiscovery(entry);- if (previous) {- if (next) previous.section.replaceWith(next.section);- else previous.section.remove();- } else if (next) elements.detailContent.append(next.section);- next?.mount();+function refreshDeferredDetailSections(entry) {+ cancelPendingDiscovery?.();+ const generation = detailRenderGeneration;+ let cancelled = false;+ let timer = 0;+ const isCurrent = () => !cancelled && generation === detailRenderGeneration &&+ currentDetailId === entry.id && elements.detailDrawer.dataset.entryId === entry.id;+ const cleanup = () => {+ cancelled = true;+ cancelAnimationFrame(frame);+ clearTimeout(timer);+ detailControllerCleanups.delete(cleanup);+ if (cancelPendingDiscovery === cleanup) cancelPendingDiscovery = null;+ };+ // Give the case its first frame before ranking, even with a warm similarity index.+ const frame = requestAnimationFrame(() => {+ timer = setTimeout(async () => {+ try {+ if (!isCurrent()) return;+ if (!usesArticleReader(entry)) void refreshDetailGenerationMetadata(entry, generation);+ await loadImageDerivedMetadata();+ if (!isCurrent()) return;+ const previous = activeDetailDiscovery;+ const next = createLocalDiscovery(entry);+ previous?.cleanup();+ if (previous) {+ if (next) previous.section.replaceWith(next.section);+ else previous.section.remove();+ } else if (next) elements.detailContent.append(next.section);+ next?.mount();+ } catch (error) {+ if (isCurrent()) showFeedback(error.message || "无法读取本机资料", true);+ } finally { cleanup(); }+ }, 0);+ });+ cancelPendingDiscovery = cleanup;+ detailControllerCleanups.add(cleanup);+}++async function refreshDetailGenerationMetadata(entry, generation) {+ // Old exports may lack generation metadata. Recover it without holding the+ // image, prompt or editors behind reads of every original in the case.+ const enriched = await readDetailGenerationInfo(entry);+ if (generation !== detailRenderGeneration || currentDetailId !== entry.id) return;+ const actions = elements.detailContent.querySelector('.detail-quick-organization > .metadata-actions');+ if (!actions) return;+ const source = createDetailSourceAction(enriched);+ if (!source) return;+ const current = actions.querySelector('.source-open-action');+ if (current?.getAttribute('aria-description') === source.getAttribute('aria-description')) return;+ if (current) {+ const focused = document.activeElement === current;+ current.replaceWith(source);+ if (focused) source.focus({ preventScroll: true });+ } else actions.prepend(source);}function createLocalDiscovery(entry) {@@ -7801,7 +7837,7 @@ function createCurrentVideoReconstruction(entry, asset, record, aiSource = "analonError: error => showFeedback(error.message, true)});card.querySelector(".prompt-read-body").classList.add("video-reconstruction-text");- const assignedTagNames = new Set([...groupEntryAssignments(entry, facetCatalog, "confirmed").values()].flat().map(item => item.name));+ const assignedTagNames = new Set([...readEntryAssignments(entry, "confirmed").values()].flat().map(item => item.name));const unassignedTags = (record.tags || []).filter(tag => !assignedTagNames.has(tag.t || tag.g));if (unassignedTags.length) {const tags = el("div", "detail-tags video-analysis-tags");@@ -9844,7 +9880,7 @@ function documentTypeLabel(mimeType, sourceFormat = "") {function createDetailAttributes(entry) {- const grouped = groupEntryAssignments(entry, facetCatalog, "confirmed");+ const grouped = readEntryAssignments(entry, "confirmed");const tags = [];let stableOrder = 0;for (const facet of facetCatalog.facets.filter((item) => item.status === "active").sort((a, b) => a.order - b.order)) {@@ -10573,7 +10609,7 @@ function createEntryEditor(entry, options = {}) {}};const renderSelectedTags = () => {- const grouped = groupEntryAssignments(entry, facetCatalog, "confirmed");+ const grouped = readEntryAssignments(entry, "confirmed");const existing = new Map([...selected.children].map(button => [button.dataset.nodeId, button]));const buttons = [];for (const facet of facetCatalog.facets.filter(item => item.status === "active").sort((a, b) => a.order - b.order)) {@@ -12063,7 +12099,10 @@ async function applyStagedAnalysisRebuild() {});if (!response?.ok) throw new Error(response?.message || "无法应用重建缓存");analysisBatchPreview = null;- if (response.facetCatalog) facetCatalog = normalizeFacetCatalog(response.facetCatalog);+ if (response.facetCatalog) {+ facetCatalog = normalizeFacetCatalog(response.facetCatalog);+ readEntryAssignments = createEntryAssignmentReader(facetCatalog);+ }if (response.analysisBatchJob) analysisBatchJob = response.analysisBatchJob;showTextBatchFeedback(response.message);await refreshLibrary();diff --git a/extension/manifest.json b/extension/manifest.jsonindex 16877d6..43f88a9 100644--- a/extension/manifest.json+++ b/extension/manifest.json@@ -1,7 +1,7 @@{"manifest_version": 3,"name": "__MSG_extensionName__",- "version": "1.27.1",+ "version": "1.28.0","key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq2m8W9ACXJTkJqPAd36sPrtzonmHhOYU34uS7c+D7DXX6ggWNMwB4xZapGFJ4ScBQJv71PeG9KfsEnhcXFZ9RoX/X3wY+57evL19hf6woNX1xxhKOe1rtx5QmzWCEYIr99TzW50k/N9U6tS9Ri+2DHKYA85ssXTC8B2yRQ5zUXhsAWZe/HDU18UFuvUKXYt3ZdIUi31c2vIlgFFBfsyKbIUMny9LlxL/smb4vJzU/+A3LwJDjjvOtS/lmQ2vHoQGjHJItO18bYI6h67fIEvmWk+HJKtO08Ca+5RLS8TYhI+K7l7S0RyDVNujyVWtvhAULot1H0BvteYL87fKu3SNywIDAQAB","homepage_url": "https://github.com/wchao6891/PromptDirector","default_locale": "zh_CN",diff --git a/extension/markdown-renderer.js b/extension/markdown-renderer.jsindex fa440e0..ba1664a 100644--- a/extension/markdown-renderer.js+++ b/extension/markdown-renderer.js@@ -143,11 +143,14 @@ function appendInline(parent, sourceValue, options) {function appendInlineToken(parent, token, options) {const media = token.match(/^(!?)\[([^\]]*)\]\(([^)]+)\)$/);if (media) {- if (media[1] && /^document-image:\d+$/u.test(media[3]) && options.loadLocalImage) {- parent.append(localDocumentImage(media[3], media[2], options));+ const localLink = !media[1] && options.renderLink?.(media[3], media[2]);+ if (localLink) { parent.append(localLink); return; }+ const reference = options.resolveLink?.(media[3], Boolean(media[1])) ?? media[3];+ if (media[1] && /^document-image:\d+$/u.test(reference) && options.loadLocalImage) {+ parent.append(localDocumentImage(reference, media[2], options));return;}- const url = safeRemoteUrl(media[3]);+ const url = safeRemoteUrl(reference);if (media[1]) parent.append(remoteImage(url, media[2], options));else {const link = document.createElement("a");diff --git a/extension/skill-cover.css b/extension/skill-cover.cssindex 84912f0..28e5d33 100644--- a/extension/skill-cover.css+++ b/extension/skill-cover.css@@ -1,7 +1,7 @@.skill-cover-card { width: 100%; aspect-ratio: 4 / 3; overflow: hidden; border-radius: var(--ui-control-radius, 10px); background: var(--ui-surface-muted, #171a1d); }.skill-cover-card img, .skill-cover-preview img, .skill-cover-option img { display: block; width: 100%; height: 100%; object-fit: contain; }-.skill-cover-detail { margin: 0 0 20px; text-align: center; }-.skill-cover-detail img { display: block; max-width: 100%; max-height: 65dvh; margin: auto; object-fit: contain; border-radius: var(--ui-control-radius, 10px); }+.skill-cover-detail { width: 100%; margin: 0 0 20px; aspect-ratio: 16 / 9; max-height: 320px; overflow: hidden; text-align: center; background: var(--ui-surface-muted, #171a1d); border-radius: var(--ui-control-radius, 10px); }+.skill-cover-detail img { display: block; width: 100%; height: 100%; object-fit: contain; }.skill-cover-editor { display: flex; gap: 16px; align-items: center; margin: 16px 0; }.skill-cover-preview { width: min(220px, 40%); aspect-ratio: 4 / 3; flex: 0 0 auto; border-radius: var(--ui-control-radius, 10px); overflow: hidden; background: var(--ui-surface-muted, #171a1d); }.skill-cover-controls { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }diff --git a/extension/skill-file-browser.css b/extension/skill-file-browser.cssnew file mode 100644index 0000000..28e1cde--- /dev/null+++ b/extension/skill-file-browser.css@@ -0,0 +1,26 @@+.skill-detail-description { margin: 0 0 18px; color: var(--muted); line-height: 1.7; }+.skill-file-browser { display: grid; grid-template-columns: minmax(200px, 250px) minmax(0, 1fr); gap: 12px; align-items: stretch; }+.skill-file-browser.is-collapsed { grid-template-columns: 1fr; }+.skill-file-browser.is-collapsed .skill-file-sidebar { display: none; }+.skill-file-sidebar, .skill-file-reader { min-width: 0; border: 1px solid var(--line); border-radius: var(--ui-container-radius); background: var(--card); }+.skill-file-sidebar > header, .skill-file-toolbar { display: flex; align-items: center; gap: 10px; min-height: 48px; padding: 10px 12px; border-bottom: 1px solid var(--line); font-size: 12px; }+.skill-file-sidebar > header { justify-content: space-between; }+.skill-file-sidebar nav { padding: 8px; max-height: 65vh; overflow: auto; }+.skill-file-sidebar summary { padding: 7px 6px; cursor: pointer; font-size: 12px; overflow-wrap: anywhere; }+.skill-file-children { padding-left: 12px; }+.skill-file-row { display: flex; justify-content: flex-start; gap: 8px; width: 100%; min-height: 34px; padding: 7px 8px; border: 1px solid transparent; background: transparent; color: var(--ink); text-align: left; font-size: 12px; font-weight: 400; white-space: normal; overflow-wrap: anywhere; }+.skill-file-row[aria-current=true] { background: var(--selection); border-color: var(--selection-edge); box-shadow: inset 2px 0 var(--accent-emphasis); }+.skill-file-row .ui-icon { flex-shrink: 0; width: 15px; height: 15px; color: var(--muted); }+.skill-file-toolbar strong { min-width: 0; overflow-wrap: anywhere; }+.skill-file-toolbar span { color: var(--muted); font-size: 11px; white-space: nowrap; }+.skill-file-reader .skill-detail-markdown { padding: clamp(18px, 3vw, 32px); border: 0; border-radius: 0; min-height: 440px; max-height: 68vh; overflow: auto; }+.skill-file-reader .skill-markdown-editor { min-height: 400px; width: 100%; resize: vertical; }+.skill-file-text { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font: 13px/1.7 ui-monospace, monospace; }+.skill-file-media { display: block; max-width: 100%; max-height: 58vh; margin: auto; }+.skill-file-browser [hidden] { display: none !important; }+@media (max-width: 760px) {+ .skill-file-browser { grid-template-columns: 1fr; }+ .skill-file-sidebar nav { max-height: 240px; }+ .skill-file-reader .skill-detail-markdown { padding: 16px; min-height: 330px; max-height: none; }+ .skill-file-toolbar span { display: none; }+}diff --git a/extension/skill-file-browser.js b/extension/skill-file-browser.jsnew file mode 100644index 0000000..fc0927c--- /dev/null+++ b/extension/skill-file-browser.js@@ -0,0 +1,145 @@+import { renderMarkdownDocument } from './markdown-renderer.js';+import { createUiIcon } from './ui-icons.js';+import { assetFormatForFile } from './asset-formats.js';+import { blobToDataUrl } from './vision.js';+import { resolveSkillFileLink } from './skill-package-edit.js';+import { t, translateUiMessage } from './i18n.js';++// A file viewer, never a script runner. Files are read only when selected.+export function createSkillFileBrowser({ host, onSelect = () => {} }) {+ let source = null, selected = '', generation = 0, disabled = false;+ const urls = new Set(), expanded = new Set();+ host.classList.add('skill-file-browser');+ const sidebar = node('aside', 'skill-file-sidebar');+ const heading = node('header');+ const collapse = iconButton('panel-left-close', t('收起文件栏'));+ heading.append(node('strong', '', t('文件')), collapse);+ const tree = node('nav'); tree.setAttribute('aria-label', t('Skill 包文件'));+ sidebar.append(heading, tree);+ const reader = node('section', 'skill-file-reader');+ const toolbar = node('header', 'skill-file-toolbar');+ const expand = iconButton('panel-left', t('展开文件栏'));+ const pathLabel = node('strong'), size = node('span');+ toolbar.append(expand, pathLabel, size);+ const content = node('div', 'skill-detail-markdown');+ content.setAttribute('aria-live', 'polite');+ reader.append(toolbar, content); host.append(sidebar, reader);+ function setCollapsed(value) { host.classList.toggle('is-collapsed', value); expand.hidden = !value; }+ collapse.onclick = () => setCollapsed(true); expand.onclick = () => setCollapsed(false);+ setCollapsed(matchMedia('(max-width:760px)').matches);++ function release() {+ generation++;+ for (const url of urls) URL.revokeObjectURL(url);+ urls.clear(); content.replaceChildren();+ }+ function objectUrl(blob) { const url = URL.createObjectURL(blob); urls.add(url); return url; }+ function renderTree() {+ const root = new Map();+ for (const path of source.paths) {+ let parent = root;+ const parts = path.split('/');+ parts.forEach((part, index) => {+ if (index === parts.length - 1) parent.set(part, path);+ else { if (!parent.has(part)) parent.set(part, new Map()); parent = parent.get(part); }+ });+ }+ function children(map, prefix = '') {+ const fragment = document.createDocumentFragment();+ for (const [name, value] of [...map].sort(([a, av], [b, bv]) => a === 'SKILL.md' ? -1 : b === 'SKILL.md' ? 1 : Number(typeof av === 'string') - Number(typeof bv === 'string') || a.localeCompare(b))) {+ if (typeof value === 'string') {+ const button = node('button', 'button-secondary skill-file-row'); button.type = 'button'; button.disabled = disabled;+ button.append(createUiIcon('file-text'), document.createTextNode(name)); button.title = value;+ button.setAttribute('aria-current', String(value === selected));+ button.onclick = () => select(value); fragment.append(button);+ } else {+ const folder = prefix + name;+ const details = node('details'); details.open = expanded.has(folder) || selected.startsWith(folder + '/');+ details.ontoggle = () => details.open ? expanded.add(folder) : expanded.delete(folder);+ const group = node('div', 'skill-file-children'); group.append(children(value, folder + '/'));+ details.append(node('summary', '', name), group); fragment.append(details);+ }+ }+ return fragment;+ }+ tree.replaceChildren(children(root));+ }+ async function select(path) {+ if (!source || !source.paths.includes(path)) return;+ release(); selected = path; renderTree(); pathLabel.textContent = path; size.textContent = '';+ onSelect(path);+ const token = generation, current = source;+ content.textContent = t('正在读取文件…');+ try {+ if (current.mainEditor && path === current.mainPath) {+ content.replaceChildren(current.mainEditor); current.mainEditor.disabled = disabled; return;+ }+ const blob = await current.readFile(path);+ if (token !== generation) return;+ if (!(blob instanceof Blob)) throw new Error(t('文件读取失败'));+ size.textContent = `${blob.size.toLocaleString()} B`;+ content.replaceChildren();+ const format = assetFormatForFile({ name: path, type: blob.type });+ if (['image', 'video', 'audio'].includes(format?.kind) && !/\.svg$/i.test(path)) {+ const tag = format.kind === 'image' ? 'img' : format.kind;+ const media = node(tag, 'skill-file-media');+ media.src = objectUrl(blob.slice(0, blob.size, format.mimeTypes[0]));+ if (tag === 'img') media.alt = path;+ else { media.controls = true; media.preload = 'metadata'; }+ media.onerror = () => { if (token === generation) content.textContent = t('无法预览此文件,可从顶部下载'); };+ content.append(media); return;+ }+ let text;+ try { text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(await blob.arrayBuffer()); if (text.includes('\0')) text = null; }+ catch { text = null; }+ if (token !== generation) return;+ if (text === null) { content.textContent = t('无法预览此文件,可从顶部下载'); return; }+ if (current.onChange) {+ const editor = node('textarea', 'skill-markdown-editor'); editor.value = text; editor.disabled = disabled;+ editor.setAttribute('aria-label', t('编辑文件:{path}', { path }));+ editor.oninput = () => current.onChange(path, new Blob([editor.value], { type: blob.type }));+ content.append(editor);+ } else if (/\.md$/i.test(path)) {+ const localImages = [];+ const display = text.replace(path === current.mainPath ? /^\uFEFF?---\r?\n[\s\S]*?\r?\n---\r?\n/ : /$^/, '');+ const article = renderMarkdownDocument(display, {+ renderLink: (href, label) => {+ const target = resolveSkillFileLink(path, href, current.paths);+ if (!target) return null;+ const link = node('a', '', label);+ link.href = '#' + encodeURIComponent(target.path);+ link.onclick = event => { event.preventDefault(); select(target.path); };+ return link;+ },+ resolveLink: (href, image) => {+ const target = image && resolveSkillFileLink(path, href, current.paths);+ if (!target) return href;+ localImages.push(target.path); return `document-image:${localImages.length - 1}`;+ },+ loadLocalImage: async ref => {+ const image = await current.readFile(localImages[Number(ref.split(':')[1])]);+ if (token !== generation) throw new Error(t('文件已切换'));+ const format = assetFormatForFile({ name: localImages[Number(ref.split(':')[1])], type: image.type });+ return blobToDataUrl(image.slice(0, image.size, format?.mimeTypes[0] || image.type));+ } });+ content.append(article);+ } else content.append(node('pre', 'skill-file-text', text || t('空文件 · 0 B')));+ } catch (error) {+ if (token === generation) content.textContent = translateUiMessage(error.message) || t('文件读取失败');+ }+ }+ return {+ setSource(value, preferred = selected) {+ source = value;+ const path = value.paths.includes(preferred) ? preferred : value.mainPath ?? value.paths[0];+ return select(path);+ },+ selection: () => selected,+ async selectedFile() { const path = selected, current = source; return { path, blob: await current.readFile(path) }; },+ setDisabled(value) { disabled = value; for (const control of host.querySelectorAll('button,textarea')) control.disabled = value; },+ dispose() { source = null; release(); tree.replaceChildren(); }+ };+}++function node(tag, className = '', text = '') { const element = document.createElement(tag); element.className = className; element.textContent = text; return element; }+function iconButton(icon, label) { const button = node('button', 'icon-button'); button.type = 'button'; button.title = label; button.setAttribute('aria-label', label); button.append(createUiIcon(icon)); return button; }diff --git a/extension/skill-package-edit.js b/extension/skill-package-edit.jsnew file mode 100644index 0000000..03746c2--- /dev/null+++ b/extension/skill-package-edit.js@@ -0,0 +1,42 @@+import { generatedSkillFiles, storedSkillFiles, parseSkillFiles } from './creative-skill-package.js';+import { currentCreativeSkillVersion } from './creative-skills.js';++// Reuse unchanged blobs and publish a complete file list with the new version.+// saveFile is owned by the caller's media stage, so failed saves remain recoverable.+export async function prepareSkillFileEdit({ skill, input, changes, readFile, saveFile }) {+ const cache = new Map();+ const read = id => { if (!cache.has(id)) cache.set(id, Promise.resolve(readFile(id))); return cache.get(id); };+ const original = skill ? await storedSkillFiles(skill, { readFile: read }) : new Map();+ let files;+ if (skill) {+ const draft = structuredClone(skill);+ draft.description = input.description;+ Object.assign(currentCreativeSkillVersion(draft), { skillMarkdown: input.skillMarkdown, provenanceMarkdown: input.provenanceMarkdown });+ files = await storedSkillFiles(draft, { readFile: read });+ } else files = generatedSkillFiles(input);+ for (const [path, blob] of changes) files.set(path, blob);+ const parsed = await parseSkillFiles(files);+ if (skill && parsed.name !== skill.portableId) throw new Error('包内 name 与现有 Skill 不同');+ const packageFiles = [];+ for (const [path, blob] of parsed.files) {+ const previous = skill?.packageFiles.find(file => file.path === path);+ // Cover validation may attach a MIME type without changing its bytes.+ const unchanged = previous && !changes.has(path) && files.get(path) === original.get(path);+ packageFiles.push(unchanged ? previous : await saveFile(path, blob));+ }+ return {+ portableId: parsed.name, description: parsed.description, skillMarkdown: parsed.body,+ references: parsed.references,+ provenanceMarkdown: parsed.references.find(ref => ref.path === 'references/provenance.md')?.markdown ?? '',+ packageFiles, runtimeDependencies: parsed.dependencies, textModeConfirmed: parsed.requiresTextModeConfirmation+ };+}++export function resolveSkillFileLink(from, href, paths) {+ if (!href || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href)) return null;+ try {+ const url = new URL(href, new URL(from, 'https://skill.invalid/'));+ const path = decodeURIComponent(url.pathname.slice(1));+ return paths.includes(path) ? { path, hash: decodeURIComponent(url.hash.slice(1)) } : null;+ } catch { return null; }+}diff --git a/extension/skills-page.css b/extension/skills-page.cssindex 9800f4c..aa00790 100644--- a/extension/skills-page.css+++ b/extension/skills-page.css@@ -128,9 +128,6 @@ body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }.skill-call-name b { padding-left: 10px; color: var(--accent, #39784d); }.skill-call-name input { min-width: 0; flex: 1; border: 0; background: transparent; }.skill-markdown-editor { width: 100%; min-height: 420px; resize: vertical; font: 13px/1.65 ui-monospace, SFMono-Regular, Menlo, monospace; }-.skill-draft-editor { margin: 12px 0; border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); }-.skill-draft-editor > summary { min-height: 36px; display: flex; align-items: center; padding: 7px 11px; cursor: pointer; font-size: 12px; font-weight: 750; }-.skill-draft-editor > label { border-top: 1px solid var(--skill-line); padding: 12px; }.skill-version-list { display: grid; gap: 6px; }.skill-version-item { display: grid; grid-template-columns: 1fr auto; gap: 12px; align-items: center; padding: 10px 0; border-top: 1px solid var(--skill-line); }.skill-version-item:first-child { border-top: 0; }@@ -165,14 +162,6 @@ body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }.skill-detail-more-panel { position: absolute; z-index: 8; top: calc(100% + 6px); right: 0; display: grid; width: max-content; min-width: 170px; gap: 4px; border: 1px solid var(--line); border-radius: var(--ui-container-radius); padding: 6px; background: var(--raised); box-shadow: var(--shadow); }.skill-detail-more-panel button { width: 100%; min-height: 30px; justify-content: flex-start; text-align: left; font-size: 11px; }.skill-workspace-mode { margin: 0 0 4px; color: var(--muted); font-size: 11px; }-.skill-detail-layout { display: grid; grid-template-columns: minmax(220px, 300px) minmax(0, 1fr); align-items: start; gap: 12px; }-.skill-detail-summary, .skill-detail-markdown { border: 1px solid var(--skill-line); border-radius: var(--ui-container-radius); background: var(--skill-panel); }-.skill-detail-summary { padding: 18px; }-.skill-detail-summary > p { margin: 0 0 20px; color: var(--muted, #697069); line-height: 1.6; }-.skill-detail-summary dl { display: grid; gap: 10px; margin: 0; }-.skill-detail-summary dl > div { display: flex; justify-content: space-between; gap: 12px; border-top: 1px solid var(--skill-line); padding-top: 10px; }-.skill-detail-summary dt { color: var(--muted, #697069); font-size: 11px; }-.skill-detail-summary dd { margin: 0; font-size: 12px; text-align: right; }.skill-detail-markdown { min-width: 0; padding: clamp(18px, 3vw, 32px); }.skill-detail-markdown .markdown-reader > :first-child { margin-top: 0; }.skill-detail-markdown .markdown-reader > :last-child { margin-bottom: 0; }@@ -225,7 +214,6 @@ body:not([data-skill-view="list"]) .skills-main { padding-top: 20px; }.skill-detail-actions > button { flex: 1 1 140px; }.skill-detail-more { flex: 1 1 140px; }.skill-detail-more > summary { justify-content: center; }- .skill-detail-layout { grid-template-columns: 1fr; }.skill-case-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }.skill-case-scroll { max-height: 520px; }.skill-runtime-grid, .skill-name-grid { grid-template-columns: 1fr; }diff --git a/extension/skills-page.js b/extension/skills-page.jsindex 9fe4eb7..e603551 100644--- a/extension/skills-page.js+++ b/extension/skills-page.js@@ -8,6 +8,9 @@ import { createUiIcon } from "./ui-icons.js";import { bindVideoHoverPreview } from "./video-hover-preview.js";import { createSourceVideoPreview, bindSourceVideoCover } from "./source-video-preview.js";import { createSkillCoverEditor, showSkillCoverImage, clearSkillCoverImage } from "./skill-cover-ui.js";+import { createSkillFileBrowser } from "./skill-file-browser.js";+import { skillRevision } from "./skill-operations.js";+import { prepareSkillFileEdit } from "./skill-package-edit.js";import { readSkillCover } from "./skill-cover.js";import { DEFAULT_COMPOSER_REQUEST_TIMEOUT_MS, normalizeAiSettings } from "./deepseek.js";import { normalizeComposerSettings, referenceSourcePartsForAsset } from "./composer.js";@@ -19,6 +22,8 @@ import {import {buildProvenanceMarkdown,exportStoredSkillPackage,+ storedSkillFiles,+ storedSkillPaths,parseSkillFile,parseSkillFiles} from "./creative-skill-package.js";@@ -56,7 +61,6 @@ import {saveSkillPackageBlob} from "./media-store.js";import { entryMediaAssets, primaryImageAsset } from "./media.js";-import { renderMarkdownDocument } from "./markdown-renderer.js";import { blobToDataUrl, normalizeVisionSettings } from "./vision.js";import { currentLocale, initializeUi, t, translateUiMessage } from "./i18n.js";import { confirmAppAction, showAppDialog } from "./ui-dialogs.js";@@ -75,10 +79,10 @@ const CURATED_SKILL_PUBLISHER_STORAGE_KEY = "curatedSkillPublisher";const elements = Object.fromEntries(["skill-search", "skill-import", "skill-create", "skill-context-back", "skill-zip-file", "skill-folder-files", "skill-library", "skill-summary", "skill-feedback", "skill-list", "skill-empty",- "skill-detail", "skill-detail-title", "skill-detail-call-name", "skill-detail-feedback", "skill-detail-description", "skill-detail-version", "skill-detail-source", "skill-detail-updated", "skill-detail-markdown", "skill-detail-edit", "skill-detail-more", "skill-detail-refine", "skill-export", "skill-submit-curated",+ "skill-detail", "skill-detail-title", "skill-detail-call-name", "skill-detail-feedback", "skill-detail-description", "skill-detail-files", "skill-detail-download", "skill-download-file", "skill-detail-edit", "skill-detail-more", "skill-detail-refine", "skill-export", "skill-submit-curated","skill-workspace", "skill-workspace-kicker", "skill-workspace-title", "skill-delete", "skill-builder", "skill-source-sidebar", "skill-source-step", "skill-target-step", "skill-selected-count", "skill-project-picker", "skill-project-label", "skill-project-filter", "skill-case-search", "skill-clear-selection", "skill-visible-select", "skill-selection-summary", "skill-case-scroll", "skill-case-grid", "skill-case-load-more","skill-run-evidence-step", "skill-run-evidence-count", "skill-run-evidence-list",- "skill-show-draft", "skill-back-sources", "skill-draft-preview", "skill-goal", "skill-use-vision", "skill-vision-toggle-note", "skill-vision-preview", "skill-advanced", "skill-text-provider-menu", "skill-vision-provider-menu", "skill-text-instruction", "skill-vision-instruction", "skill-restore-instructions", "skill-request-preview", "skill-generate", "skill-retry-vision", "skill-run-panel", "skill-generation-status", "skill-run-elapsed", "skill-stop-run", "skill-run-progress", "skill-run-stages", "skill-run-log", "skill-generation-feedback", "skill-draft-step", "skill-draft-editor", "skill-version-label", "skill-call-name", "skill-description", "skill-markdown", "skill-save", "skill-test", "skill-save-status", "skill-versions-step", "skill-version-list",+ "skill-show-draft", "skill-back-sources", "skill-draft-preview", "skill-goal", "skill-use-vision", "skill-vision-toggle-note", "skill-vision-preview", "skill-advanced", "skill-text-provider-menu", "skill-vision-provider-menu", "skill-text-instruction", "skill-vision-instruction", "skill-restore-instructions", "skill-request-preview", "skill-generate", "skill-retry-vision", "skill-run-panel", "skill-generation-status", "skill-run-elapsed", "skill-stop-run", "skill-run-progress", "skill-run-stages", "skill-run-log", "skill-generation-feedback", "skill-draft-step", "skill-add-files", "skill-add-folder", "skill-add-files-input", "skill-add-folder-input", "skill-version-label", "skill-call-name", "skill-description", "skill-markdown", "skill-save", "skill-test", "skill-save-status", "skill-versions-step", "skill-version-list","skill-source-inspector-backdrop", "skill-source-inspector", "skill-source-inspector-title", "skill-source-inspector-close", "skill-source-select-all", "skill-source-clear", "skill-source-text-option", "skill-source-include-text", "skill-source-asset-list", "skill-source-cancel", "skill-source-apply","skill-import-dialog", "skill-import-close", "skill-import-zip", "skill-import-folder","skill-submission-dialog", "skill-submission-close", "skill-submission-author", "skill-submission-author-error", "skill-submission-summary", "skill-submission-summary-error", "skill-submission-rights", "skill-submission-rights-error", "skill-submission-refresh", "skill-submission-open", "skill-submission-feedback", "skill-submission-findings", "skill-submission-preview"@@ -115,6 +119,10 @@ let skillRuntimeSettings = null;let activeSkillRun = null;let visionPreferenceTouched = false;let curatedSubmissionSnapshot = null;+let pendingSkillFiles = new Map();+let draftPortableId = '';+const detailFiles = createSkillFileBrowser({ host: elements.skillDetailFiles });+const editorFiles = createSkillFileBrowser({ host: elements.skillDraftPreview });const coverEditor = createSkillCoverEditor({host: document.querySelector("#skill-cover-editor"), readFile: getMediaBlob,@@ -130,6 +138,14 @@ function bindEvents() {elements.skillContextBack.addEventListener("click", () => safely(navigateBack)());elements.skillDetailEdit.addEventListener("click", () => navigateTo("editor", activeSkillId));elements.skillDetailRefine.addEventListener("click", () => navigateTo("refine", activeSkillId));+ elements.skillDownloadFile.addEventListener('click', () => safely(async () => {+ elements.skillDetailDownload.open = false;+ const file = await detailFiles.selectedFile();+ await downloadBlob(file.blob, { filename: file.path.split('/').at(-1) });+ })());+ elements.skillAddFiles.addEventListener('click', () => elements.skillAddFilesInput.click());+ elements.skillAddFolder.addEventListener('click', () => elements.skillAddFolderInput.click());+ for (const input of [elements.skillAddFilesInput, elements.skillAddFolderInput]) input.addEventListener('change', () => safely(() => addSkillFiles(input))());elements.skillExport.addEventListener("click", () => safely(exportSkill)());elements.skillSubmitCurated.addEventListener("click", () => runCuratedSubmissionAction(openCuratedSubmission));elements.skillImport.addEventListener("click", () => elements.skillImportDialog.showModal());@@ -155,7 +171,7 @@ function bindEvents() {sourceLoader.observe(elements.skillCaseLoadMore);elements.skillShowDraft.addEventListener("click", showDraftResult);elements.skillBackSources.addEventListener("click", showSourceWorkspace);- elements.skillMarkdown.addEventListener("input", renderDraftPreview);+elements.skillGoal.addEventListener("input", renderRequestPreview);elements.skillUseVision.addEventListener("change", () => { visionPreferenceTouched = true; renderVisionPreview(); renderRequestPreview(); });elements.skillTextInstruction.addEventListener("input", renderRequestPreview);@@ -178,7 +194,7 @@ function bindEvents() {addEventListener("keydown", (event) => {if (event.key === "Escape" && !elements.skillSourceInspector.hidden) cancelSourceInspector();});- addEventListener("beforeunload", () => { activeSkillRun?.controller.abort(); releaseThumbnails(); releaseSourceVideos(); });+ addEventListener("beforeunload", () => { detailFiles.dispose(); editorFiles.dispose(); activeSkillRun?.controller.abort(); releaseThumbnails(); releaseSourceVideos(); });}// The Skill list only needs Skills. The whole case library (the slow part of opening this page)@@ -331,7 +347,7 @@ function routeUrl(route) {function renderRoute(route) {requestedRoute = route;- if (route.view !== "list" && !libraryEntriesReady) {+ if (["create", "refine"].includes(route.view) && !libraryEntriesReady) {document.body.dataset.skillLoading = "true";void readLibraryEntries().then(() => {delete document.body.dataset.skillLoading;@@ -352,6 +368,9 @@ function renderRoute(route) {elements.skillImport.hidden = !listView;elements.skillCreate.hidden = !listView;elements.skillDetailMore.open = false;+ elements.skillDetailDownload.open = false;+ detailFiles.dispose();+ editorFiles.dispose();elements.skillLibrary.hidden = route.view !== "list";elements.skillDetail.hidden = route.view !== "detail";elements.skillWorkspace.hidden = !["create", "editor", "refine"].includes(route.view);@@ -382,15 +401,13 @@ function renderSkillDetail() {releaseThumbnails();const skill = activeSkill();if (!skill) return navigateTo("list", "", { replace: true });- const version = currentCreativeSkillVersion(skill);- showSkillCoverImage(document.querySelector("#skill-detail-cover"), () => readSkillCover(skill, getMediaBlob), { alt: skill.callName });elements.skillDetailTitle.textContent = skill.callName;elements.skillDetailCallName.textContent = `/${skill.callName}`;elements.skillDetailDescription.textContent = skill.description || t("暂无说明");- elements.skillDetailVersion.textContent = `v${versionNumber(skill, version.id)}`;- elements.skillDetailSource.textContent = version.source === "imported" ? t("外部包") : "PromptDirector";- elements.skillDetailUpdated.textContent = formatDate(skill.updatedAt);- elements.skillDetailMarkdown.replaceChildren(renderMarkdownDocument(version.skillMarkdown));+ const paths = storedSkillPaths(skill);+ detailFiles.setSource({ paths, mainPath: paths.find(path => path === 'SKILL.md' || path.endsWith('/SKILL.md')),+ readFile: async path => (await storedSkillFiles(skill, { readFile: getMediaBlob, paths: [path] })).get(path)+ });setFeedback(elements.skillDetailFeedback, "");}@@ -414,6 +431,8 @@ function renderWorkspace(view, skillId = "") {finishSkillRun();const skill = activeSkill();coverEditor.reset(skill);+ pendingSkillFiles = new Map();+ draftPortableId = skill?.portableId ?? `skill-${crypto.randomUUID()}`;const selectingSources = view === "create" || view === "refine";elements.skillBuilder.dataset.mode = view;elements.skillBuilder.dataset.stage = "sources";@@ -445,7 +464,7 @@ function renderWorkspace(view, skillId = "") {elements.skillDescription.value = skill.description;elements.skillMarkdown.value = version.skillMarkdown;elements.skillDraftStep.hidden = false;- elements.skillDraftEditor.open = view === "editor";+elements.skillVersionsStep.hidden = false;elements.skillVersionLabel.textContent = t("当前 v{version}", { version: versionNumber(skill, version.id) });renderVersions(skill);@@ -454,7 +473,7 @@ function renderWorkspace(view, skillId = "") {elements.skillDescription.value = "";elements.skillMarkdown.value = "";elements.skillDraftStep.hidden = true;- elements.skillDraftEditor.open = false;+elements.skillVersionsStep.hidden = true;}setFeedback(elements.skillGenerationStatus, "");@@ -1171,14 +1190,35 @@ async function generateTextDraft(settingsValue = null, sourcesValue = null) {}function renderDraftPreview() {- elements.skillDraftPreview.replaceChildren(renderMarkdownDocument(elements.skillMarkdown.value));+ const skill = activeSkill();+ const paths = [...new Set([...(skill ? storedSkillPaths(skill) : ['SKILL.md']), ...pendingSkillFiles.keys()])];+ const mainPath = paths.find(path => path === 'SKILL.md' || path.endsWith('/SKILL.md'));+ elements.skillMarkdown.hidden = false;+ editorFiles.setSource({ paths, mainPath, mainEditor: elements.skillMarkdown,+ readFile: async path => pendingSkillFiles.get(path) ?? (await storedSkillFiles(skill, { readFile: getMediaBlob, paths: [path] })).get(path),+ onChange: (path, blob) => pendingSkillFiles.set(path, blob)+ });+}++async function addSkillFiles(input) {+ const files = [...input.files]; input.value = '';+ const skill = activeSkill();+ const paths = skill ? storedSkillPaths(skill) : ['SKILL.md'];+ const main = paths.find(path => path === 'SKILL.md' || path.endsWith('/SKILL.md'));+ const prefix = main.slice(0, -'SKILL.md'.length);+ const additions = files.map(file => [prefix + (file.webkitRelativePath || file.name), file]);+ if (additions.some(([path]) => path === main)) throw new Error(t('请在正文编辑区修改 SKILL.md;完整包请使用导入'));+ const overwritten = additions.filter(([path]) => paths.includes(path) || pendingSkillFiles.has(path));+ if (overwritten.length && !await confirmAppAction({ title: t('替换同名文件?'), description: overwritten.map(([path]) => path).join('\n'), confirmLabel: t('替换') })) return;+ for (const [path, file] of additions) pendingSkillFiles.set(path, file);+ renderDraftPreview();}function showDraftResult() {sourceScrollPosition = window.scrollY;closeSourceInspector();renderDraftPreview();- elements.skillDraftEditor.open = false;+elements.skillBuilder.dataset.stage = "result";elements.skillDraftStep.hidden = false;elements.skillShowDraft.hidden = false;@@ -1201,6 +1241,9 @@ async function saveSkill() {const creating = !activeSkillId;elements.skillSave.disabled = true;coverEditor.setDisabled(true);+ const fileStage = createMediaStage();+ editorFiles.setDisabled(true);+ elements.skillAddFiles.disabled = elements.skillAddFolder.disabled = true;const editableFields = [elements.skillCallName, elements.skillDescription, elements.skillMarkdown];editableFields.forEach(field => { field.readOnly = true; });try {@@ -1221,18 +1264,32 @@ async function saveSkill() {const message = activeSkillId ? {type: "SAVE_CREATIVE_SKILL_VERSION",skillId: activeSkillId,+ expectedRevision: await skillRevision(activeSkill()),version: { callName, description, skillMarkdown, provenanceMarkdown, reason: "improved", source: activeSkill()?.versions.at(-1)?.source,- coverOnly: activeView === "editor" && callName === activeSkill()?.callName && description === activeSkill()?.description && skillMarkdown === currentCreativeSkillVersion(activeSkill())?.skillMarkdown }+ coverOnly: !pendingSkillFiles.size && activeView === "editor" && callName === activeSkill()?.callName && description === activeSkill()?.description && skillMarkdown === currentCreativeSkillVersion(activeSkill())?.skillMarkdown }} : {type: "CREATE_CREATIVE_SKILL",skill: { callName, description, skillMarkdown, provenanceMarkdown, reason: "created", source: "generated" }};+ if (pendingSkillFiles.size) {+ const input = message.version ?? message.skill;+ Object.assign(input, await prepareSkillFileEdit({ skill: activeSkill(), input: { ...input, portableId: draftPortableId },+ changes: pendingSkillFiles, readFile: getMediaBlob,+ saveFile: async (path, blob) => {+ const assetId = `skill-file:${crypto.randomUUID()}`;+ await fileStage.register([assetId]); await saveSkillPackageBlob(assetId, blob);+ return { path, assetId, byteSize: blob.size, mimeType: blob.type || 'application/octet-stream' };+ }+ }));+ }if (coverEditor.value() !== undefined) message.cover = coverEditor.value();const response = await chrome.runtime.sendMessage(message);if (!response?.ok) throw new Error(response?.message || t("Skill 保存失败"));creativeSkills = normalizeCreativeSkillsState(response.creativeSkills);activeSkillId = response.skill.id;coverEditor.reset(response.skill);+ pendingSkillFiles = new Map();+ renderDraftPreview();elements.skillDelete.hidden = false;elements.skillVersionsStep.hidden = false;elements.skillWorkspaceTitle.textContent = response.skill.callName;@@ -1242,6 +1299,9 @@ async function saveSkill() {setFeedback(elements.skillDetailFeedback, response.message);} else setFeedback(elements.skillSaveStatus, response.message);} finally {+ await fileStage.release();+ editorFiles.setDisabled(false);+ elements.skillAddFiles.disabled = elements.skillAddFolder.disabled = false;elements.skillSave.disabled = false;coverEditor.setDisabled(false);editableFields.forEach(field => { field.readOnly = false; });@@ -1272,6 +1332,8 @@ async function restoreVersion(versionId) {const version = currentCreativeSkillVersion(response.skill);elements.skillMarkdown.value = version.skillMarkdown;elements.skillDescription.value = response.skill.description;+ pendingSkillFiles = new Map();+ renderDraftPreview();renderVersions(response.skill);setFeedback(elements.skillSaveStatus, response.message);}@@ -1295,6 +1357,7 @@ async function testSkill() {}async function exportSkill() {+ elements.skillDetailDownload.open = false;const skill = activeSkill();if (!skill) return;const archive = await exportStoredSkillPackage(skill, { readFile: getMediaBlob });@@ -1457,17 +1520,6 @@ async function importFolder() {}async function importParsedSkill(parsed, sourceName) {- if (parsed.requiresTextModeConfirmation) {- const approved = await confirmAppAction({- title: t("以文字模式导入?"),- description: t("“{source}”依赖 {dependencies}。PromptDirector 不会执行这些程序或工具,只能使用可读取的文字方法。", {- source: sourceName,- dependencies: parsed.dependencies.join(currentLocale() === "en" ? ", " : "、")- }),- confirmLabel: t("仍要导入")- });- if (!approved) return;- }const packageFiles = [];const stage = createMediaStage();try {@@ -1774,7 +1826,7 @@ function safely(action) {? elements.skillDetailFeedback: activeView === "list"? elements.skillFeedback- : elements.skillGenerationFeedback;+ : activeView === "editor" || elements.skillBuilder.dataset.stage === "result" ? elements.skillSaveStatus : elements.skillGenerationFeedback;setFeedback(target, error.message || t("操作失败"), true);}};diff --git a/extension/skills.html b/extension/skills.htmlindex 40256cd..f927327 100644--- a/extension/skills.html+++ b/extension/skills.html@@ -8,6 +8,7 @@<link rel="stylesheet" href="ui-foundation.css" /><link rel="stylesheet" href="library.css" /><link rel="stylesheet" href="skills-page.css" />+ <link rel="stylesheet" href="skill-file-browser.css" /><link rel="stylesheet" href="skill-cover.css" /><link rel="stylesheet" href="source-video-preview.css" /></head>@@ -36,29 +37,25 @@<div class="skill-detail-actions"><button id="skill-test" type="button" data-i18n="用此 Skill 创作">用此 Skill 创作</button><button id="skill-detail-edit" class="button-secondary" type="button" data-i18n="编辑">编辑</button>+ <details id="skill-detail-download" class="skill-detail-more">+ <summary data-i18n="下载">下载</summary>+ <div class="skill-detail-more-panel">+ <button id="skill-export" class="button-secondary" type="button" data-i18n="下载完整 Skill">下载完整 Skill</button>+ <button id="skill-download-file" class="button-secondary" type="button" data-i18n="下载当前文件">下载当前文件</button>+ </div>+ </details><details id="skill-detail-more" class="skill-detail-more"><summary data-i18n="更多">更多</summary><div class="skill-detail-more-panel"><button id="skill-detail-refine" class="button-secondary" type="button" data-i18n="用证据改进 Skill">用证据改进 Skill</button>- <button id="skill-export" class="button-secondary" type="button" data-i18n="导出 Skill">导出 Skill</button><button id="skill-submit-curated" class="button-secondary" type="button" data-i18n="投稿到精选 Skill">投稿到精选 Skill</button></div></details></div></header><p id="skill-detail-feedback" class="skill-feedback ui-task-feedback" role="status"></p>- <div id="skill-detail-cover" class="skill-cover-detail" hidden></div>- <div class="skill-detail-layout">- <aside class="skill-detail-summary">- <p id="skill-detail-description"></p>- <dl>- <div><dt data-i18n="版本">版本</dt><dd id="skill-detail-version"></dd></div>- <div><dt data-i18n="来源">来源</dt><dd id="skill-detail-source"></dd></div>- <div><dt data-i18n="更新">更新</dt><dd id="skill-detail-updated"></dd></div>- </dl>- </aside>- <article id="skill-detail-markdown" class="skill-detail-markdown"></article>- </div>+ <p id="skill-detail-description" class="skill-detail-description"></p>+ <div id="skill-detail-files"></div></section><section id="skill-workspace" class="skill-workspace" hidden>@@ -116,14 +113,16 @@<section id="skill-draft-step" class="skill-step skill-draft-step" tabindex="-1" hidden><div class="skill-section-heading"><div><small>03</small><strong data-i18n="编辑并保存">编辑并保存</strong></div><span id="skill-version-label"></span></div>- <div class="skill-result-actions"><button data-i18n="返回选材" id="skill-back-sources" class="button-secondary" type="button">返回选材</button><button id="skill-save" type="button" data-i18n="保存 Skill">保存 Skill</button></div>+ <div class="skill-result-actions"><button data-i18n="返回选材" id="skill-back-sources" class="button-secondary" type="button">返回选材</button><button id="skill-add-files" class="button-secondary" type="button" data-i18n="添加文件">添加文件</button><button id="skill-add-folder" class="button-secondary" type="button" data-i18n="添加文件夹">添加文件夹</button><button id="skill-save" type="button" data-i18n="保存 Skill">保存 Skill</button></div><div class="skill-name-grid"><label><span data-i18n="调用名">调用名</span><div class="skill-call-name"><b>/</b><input id="skill-call-name" maxlength="80" placeholder="你的 Skill 名称" data-i18n-placeholder="你的 Skill 名称" /></div></label><label><span data-i18n="说明">说明</span><input id="skill-description" maxlength="240" placeholder="它在什么创作任务中发挥作用" data-i18n-placeholder="它在什么创作任务中发挥作用" /></label></div><div id="skill-cover-editor"></div>- <article id="skill-draft-preview" class="skill-draft-preview"></article>- <details id="skill-draft-editor" class="skill-draft-editor"><summary data-i18n="查看并编辑 SKILL.md">查看并编辑 SKILL.md</summary><label><span data-i18n="SKILL.md 正文">SKILL.md 正文</span><textarea id="skill-markdown" class="skill-markdown-editor" rows="22"></textarea></label></details>+ <div id="skill-draft-preview"></div>+ <textarea id="skill-markdown" class="skill-markdown-editor" rows="22" aria-label="SKILL.md 正文" data-i18n-aria-label="SKILL.md 正文" hidden></textarea>+ <input id="skill-add-files-input" type="file" multiple hidden />+ <input id="skill-add-folder-input" type="file" webkitdirectory multiple hidden /><p id="skill-save-status" class="skill-feedback ui-task-feedback" role="status"></p></section>diff --git a/extension/virtual-gallery.js b/extension/virtual-gallery.jsindex 627d194..2a98fad 100644--- a/extension/virtual-gallery.js+++ b/extension/virtual-gallery.js@@ -44,12 +44,12 @@ export function createVirtualGallery(container, options) {geometry = readGeometry();columns = Array.from({ length: geometry.count }, () => []);const heights = Array(geometry.count).fill(0);+ // A detail overlay can change the gallery width. Batch width writes before+ // measuring; alternating writes and reads forces one layout per card.+ for (const record of mounted.values()) record.card.style.width = `${geometry.cardWidth}px`;for (const record of records) {if (previous && previous.cardWidth !== geometry.cardWidth && options.mode() !== 'list') record.height *= geometry.cardWidth / previous.cardWidth;- if (record.card) {- record.card.style.width = `${geometry.cardWidth}px`;- record.height = record.card.getBoundingClientRect().height;- }+ if (record.card) record.height = record.card.getBoundingClientRect().height;if (geometry.list && Number.isFinite(geometry.rowHeight)) record.height = geometry.rowHeight;// Image readiness changes heights, not the user's existing columns.// Reassign only when a viewport/zoom change actually changes the grid.@@ -59,8 +59,8 @@ export function createVirtualGallery(container, options) {record.top = heights[record.column];heights[record.column] += record.height + geometry.gap;columns[record.column].push(record);- if (record.card) position(record, record.card);}+ for (const record of mounted.values()) position(record, record.card);container.style.height = `${Math.max(0, ...heights) - (records.length ? geometry.gap : 0)}px`;container.dataset.loadedCount = String(records.length);options.onLayout?.();diff --git a/package-lock.json b/package-lock.jsonindex 2be7264..dd764b5 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "prompt-case-collector",- "version": "1.27.1",+ "version": "1.28.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "prompt-case-collector",- "version": "1.27.1",+ "version": "1.28.0","license": "Apache-2.0","dependencies": {"@jonahschulte/rtf-toolkit": "0.5.0",diff --git a/package.json b/package.jsonindex e66ba66..3958dc5 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "prompt-case-collector",- "version": "1.27.1",+ "version": "1.28.0","private": false,"license": "Apache-2.0","repository": "https://github.com/wchao6891/PromptDirector",diff --git a/store/DISTRIBUTION.md b/store/DISTRIBUTION.mdindex 5acb8aa..c518265 100644--- a/store/DISTRIBUTION.md+++ b/store/DISTRIBUTION.md@@ -6,7 +6,7 @@ Public distribution formats and the permissions used by PromptDirector.- Chrome Web Store item public key: stored in the source `manifest.json` for local identity verification only; `package:release` removes `key` from the upload manifest.- Expected extension ID: `iahakaahijddcjjldidbclicedibgpjm`.-- Current upload artifact: `dist/store/PromptDirector-1.27.1-Chrome-Web-Store.zip`. Keep this artifact local for Web Store submission. The sole GitHub extension installation package is `PromptDirector-1.27.1.zip`, with stable identity and the local updater.+- Current upload artifact: `dist/store/PromptDirector-1.28.0-Chrome-Web-Store.zip`. Keep this artifact local for Web Store submission. The sole GitHub extension installation package is `PromptDirector-1.28.0.zip`, with stable identity and the local updater.- Generate a candidate only with `npm run package:release`; the command verifies the source public key against the expected identity, then removes `key` from the Web Store upload manifest and excludes the local program installer.## Store listingdiff --git a/test/capture_native_sidepanel_e2e.py b/test/capture_native_sidepanel_e2e.pyindex 91b5638..0027118 100644--- a/test/capture_native_sidepanel_e2e.py+++ b/test/capture_native_sidepanel_e2e.py@@ -32,6 +32,7 @@ with tempfile.TemporaryDirectory(prefix='pd-native-sender-') as tmp:for _ in range(100):if evaluate("Boolean(document.querySelector('#open-capture-assistant'))"):breakp.wait_for_timeout(50)+ evaluate("import(chrome.runtime.getURL('collector.js')).then(module => module.collectorStartup)")sender=evaluate("chrome.runtime.sendMessage({type:'PROBE_SENDER'})")assert 'documentId' not in sender,senderevaluate("document.querySelector('#open-capture-assistant').click()")diff --git a/test/capture_organization_progress_e2e.py b/test/capture_organization_progress_e2e.pyindex 7841eaf..3bea0a3 100644--- a/test/capture_organization_progress_e2e.py+++ b/test/capture_organization_progress_e2e.py@@ -184,7 +184,14 @@ def main(on_download=None):assert p.evaluate('()=>window.progressNodeBefore===document.querySelector("#feedback progress")')assert p.evaluate("async()=>(await import(chrome.runtime.getURL('library-storage.js')).then(({getLibraryStorage}) => getLibraryStorage().get('entries'))).entries.length")==0p.screenshot(path=str(out/'writing-after-download.png'))- worker.evaluate("()=>globalThis.captureFixture.gates.get('commit')()")+ worker.evaluate("""async () => {+ const deadline = Date.now() + 30000;+ while (typeof globalThis.captureFixture.gates.get('commit') !== 'function') {+ if (Date.now() >= deadline) throw new Error('Fixture commit gate was not created');+ await new Promise(resolve => setTimeout(resolve, 20));+ }+ globalThis.captureFixture.gates.get('commit')();+ }""")expect(p.locator('#page-capture')).to_be_hidden(timeout=30000)state=p.evaluate("()=>chrome.runtime.sendMessage({type:'GET_STATE'})")assert len(state['entries'])==1diff --git a/test/capture_save_discard_e2e.py b/test/capture_save_discard_e2e.pyindex 0bd453e..f2f0bc1 100644--- a/test/capture_save_discard_e2e.py+++ b/test/capture_save_discard_e2e.py@@ -60,6 +60,7 @@ def main():captureSaveInput:{type:'COMMIT_PAGE_CAPTURE',saveRequestId:status,batch}});}''', status)page.reload()+ page.evaluate("async () => await (await import('./collector.js')).collectorStartup")expect(page.locator('#page-capture')).to_be_visible()if status != 'pending':expect(page.locator('#collector-footer')).to_be_hidden()@@ -84,6 +85,7 @@ def main():entries = page.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_CASE_LIBRARY_STATE'})).entries")assert any(entry['text'] == '必须保留' for entry in entries), entriespage.reload()+ page.evaluate("async () => await (await import('./collector.js')).collectorStartup")expect(page.locator('#page-capture')).to_be_hidden()# A new visible capture now proceeds through the real save service and library commit.page.evaluate('''status=>{diff --git a/test/creative_skills_e2e.py b/test/creative_skills_e2e.pyindex 1e4eb50..0fa9385 100644--- a/test/creative_skills_e2e.py+++ b/test/creative_skills_e2e.py@@ -161,7 +161,7 @@ Run `scripts/helper.py` before applying the composition guidance.expect(skills.locator("#skill-draft-step")).to_be_visible()expect(skills.locator("#skill-markdown")).to_have_value(re.compile("视觉组织方法"))expect(skills.locator("#skill-target-step")).to_be_hidden()- expect(skills.locator("#skill-draft-preview")).to_contain_text("视觉组织方法")+ expect(skills.locator("#skill-draft-preview #skill-markdown")).to_have_value(re.compile("视觉组织方法"))expect(skills.locator("#skill-save")).to_be_in_viewport()skills.screenshot(path=str(Path(tempfile.gettempdir()) / "pd-skill-result.png"))skills.locator("#skill-back-sources").click()@@ -185,13 +185,13 @@ Run `scripts/helper.py` before applying the composition guidance.skills.locator("#skill-save").click()expect(skills.locator("#skill-detail")).to_be_visible()expect(skills.locator("#skill-detail-feedback")).to_contain_text("Skill 已保存")- expect(skills.locator("#skill-detail-version")).to_have_text("v1")- expect(skills.locator("#skill-detail-markdown")).to_contain_text("视觉组织方法")+ expect(skills.locator("#skill-detail-version")).to_have_count(0)+ expect(skills.locator("#skill-detail-files .skill-detail-markdown")).to_contain_text("视觉组织方法")expect(skills.locator("#skill-export")).to_have_count(1)expect(skills.locator("#skill-search")).to_be_hidden()expect(skills.locator("#skill-import")).to_be_hidden()expect(skills.locator("#skill-create")).to_be_hidden()- skills.locator("#skill-detail-more > summary").click()+ skills.locator("#skill-detail-download > summary").click()skills.locator("#skill-export").click()exported_skill, _ = wait_for_download(skills)assert zipfile.is_zipfile(exported_skill)@@ -239,7 +239,7 @@ Run `scripts/helper.py` before applying the composition guidance.skills = composerexpect(skills.locator("#skill-detail")).to_be_visible()expect(skills.locator("#skill-workspace")).to_be_hidden()- expect(skills.locator("#skill-detail-markdown")).to_contain_text("视觉组织方法")+ expect(skills.locator("#skill-detail-files .skill-detail-markdown")).to_contain_text("视觉组织方法")assert "view=detail" in skills.urlskills.go_back()expect(skills.locator("#skill-library")).to_be_visible()@@ -284,7 +284,7 @@ Run `scripts/helper.py` before applying the composition guidance.expect(skills.locator("#skill-source-sidebar")).to_be_visible()expect(skills.locator("#skill-draft-step")).to_be_hidden()skills.locator("#skill-show-draft").click()- expect(skills.locator("#skill-draft-preview")).to_contain_text("视觉组织方法")+ expect(skills.locator("#skill-draft-preview #skill-markdown")).to_have_value(re.compile("视觉组织方法"))skills.locator("#skill-back-sources").click()expect(skills.locator("#skill-run-evidence-step")).to_be_visible()expect(skills.locator("#skill-run-evidence-list")).to_contain_text("保留主体层级")@@ -300,12 +300,16 @@ Run `scripts/helper.py` before applying the composition guidance.expect(skills.locator("#skill-library")).to_be_visible()skills.locator("#skill-import").click()skills.locator("#skill-zip-file").set_input_files(str(external_zip))- dependency_dialog = skills.locator("#promptdirector-app-dialog")- expect(dependency_dialog).to_be_visible()- dependency_warning = dependency_dialog.text_content()- dependency_dialog.get_by_role("button", name="仍要导入", exact=True).click()expect(skills.locator("#skill-feedback")).to_contain_text("已导入 /external-method")- assert "scripts" in dependency_warning+ expect(skills.locator("#promptdirector-app-dialog")).not_to_be_visible()+ imported_script = skills.evaluate("""async () => {+ const {creativeSkills} = await chrome.storage.local.get('creativeSkills');+ const skill = creativeSkills.items.find(item => item.callName === 'external-method');+ const file = skill.packageFiles.find(item => item.path.endsWith('scripts/helper.py'));+ const {getMediaBlob} = await import(chrome.runtime.getURL('media-store.js'));+ return (await getMediaBlob(file.assetId)).text();+ }""")+ assert imported_script == "print('helper')\n"expect(skills.locator(".skill-card")).to_have_count(2)card_layout = skills.evaluate("""() => {const cards = [...document.querySelectorAll('.skill-card')];diff --git a/test/curated-skill-catalog.test.js b/test/curated-skill-catalog.test.jsindex 139cf36..9f95c5d 100644--- a/test/curated-skill-catalog.test.js+++ b/test/curated-skill-catalog.test.js@@ -60,7 +60,7 @@ test("curated Skill catalog accepts a readable multilingual call name without re}});-test("verified curated Skill packages accept only SKILL.md and UTF-8 Markdown references", async () => {+test("verified curated Skill packages preserve scripts and license files without executing them", async () => {const { archive, item } = await fixture();await verifyCuratedSkillPackageBlob(archive, item.sha256, item.archiveBytes);const parsed = await validateCuratedSkillPackage(item, archive);@@ -69,5 +69,6 @@ test("verified curated Skill packages accept only SKILL.md and UTF-8 Markdown re{ name: "SKILL.md", data: new Blob(["---\nname: unsafe\ndescription: Unsafe.\n---\n\n# Unsafe\n"]) },{ name: "scripts/run.sh", data: new Blob(["echo no"]) }]);- await assert.rejects(() => validateCuratedSkillPackage({ ...item, skillId: "unsafe", callName: "unsafe" }, unsafe), /不允许的文件/);+ const full = await validateCuratedSkillPackage({ ...item, skillId: "unsafe", callName: "unsafe" }, unsafe);+ assert.equal(await full.files.get("scripts/run.sh").text(), "echo no");});diff --git a/test/curated-skill-navigation.test.js b/test/curated-skill-navigation.test.jsindex 709b225..ff6d0b3 100644--- a/test/curated-skill-navigation.test.js+++ b/test/curated-skill-navigation.test.js@@ -28,7 +28,7 @@ test("curated cases and curated Skills are independent sibling pages", async ()test("ordinary lossless export and curated submission are separate Skill detail actions", async () => {const { skillsCenter, skillsPage } = await sources();- assert.match(skillsCenter, /id="skill-export"[^>]*data-i18n="导出 Skill"/);+ assert.match(skillsCenter, /id="skill-export"[^>]*data-i18n="下载完整 Skill"/);assert.match(skillsCenter, /id="skill-submit-curated"[^>]*data-i18n="投稿到精选 Skill"/);assert.match(skillsCenter, /id="skill-submission-dialog"/);assert.match(skillsCenter, /id="skill-submission-preview"/);@@ -75,7 +75,7 @@ test("curated Skill page distinguishes load failure, an empty catalog, and no seassert.doesNotMatch(curatedSkillPage, /showStatus\(error\.message/);});-test("Skill discovery surfaces share one compact visual contract and keep maintenance facts secondary", async () => {+test("Skill discovery surfaces share one compact visual contract and keep metadata out of the reading actions", async () => {const { casesHtml, skillsHtml, curatedSkillPage, foundation, composerPage, composerStyle } = await sources();assert.match(foundation, /\.ui-segmented\s*\{/);assert.match(foundation, /\.ui-segmented-item\s*\{/);@@ -86,9 +86,8 @@ test("Skill discovery surfaces share one compact visual contract and keep mainteassert.match(curatedSkillPage, /ui-skill-card curated-skill-card/);assert.match(curatedSkillPage, /查看说明/);assert.match(curatedSkillPage, /保存到本地/);- assert.match(curatedSkillPage, /版本与许可/);- assert.match(curatedSkillPage, /curated-skill-maintenance/);- assert.match(curatedSkillPage, /removeDuplicateTitleHeading/);+ assert.doesNotMatch(curatedSkillPage, /版本与许可|curated-skill-maintenance/);+ assert.match(curatedSkillPage, /createSkillFileBrowser/);assert.match(composerPage, /ui-skill-card composer-skill-card/);assert.match(composerStyle, /\.composer-skill-card/);});diff --git a/test/curated-skill-package.test.js b/test/curated-skill-package.test.jsindex 5d49664..f2817ea 100644--- a/test/curated-skill-package.test.js+++ b/test/curated-skill-package.test.js@@ -20,18 +20,18 @@ function fixture(overrides = {}) {description: "把主体层级组织成清晰画面。",skillMarkdown: "# 构图方法\n\n保持主体清晰。",references: [{ path: "references/guide.md", markdown: "# Guide\n\nUse depth.", runtime: true }],- provenanceMarkdown: `# 私人来源\n\n${["", "Users", "private", "cases.md"].join("/")}`+ provenanceMarkdown: "# Public provenance\n\nOriginal evidence."}, { id: "local:one", versionId: "version:one", now: "2026-08-23T00:00:00.000Z" }).skill;}-test("curated submission snapshot includes a byte-verified image, is exact-previewable, and excludes private provenance by default", async () => {+test("curated submission snapshot includes a byte-verified image, is exact-previewable, and retains provenance instead of silently excluding files", async () => {const skill = fixture();const snapshot = await buildCuratedSkillSnapshot(skill, {author: "Creator One",summary: "A reusable composition method.",rightsConfirmed: true});- assert.deepEqual([...snapshot.files.keys()], ["SKILL.md", "references/guide.md", "assets/cover.gif"]);+ assert.deepEqual([...snapshot.files.keys()], ["SKILL.md", "references/guide.md", "references/provenance.md", "assets/cover.gif"]);assert.equal(snapshot.findings.length, 0);assert.doesNotMatch(await snapshot.files.get("SKILL.md").text(), /私人来源|\/Users\/private/);assert.equal(snapshot.manifest.reviewStatus, "pending");@@ -42,7 +42,7 @@ test("curated submission snapshot includes a byte-verified image, is exact-previassert.equal("authorId" in snapshot.manifest, false);assert.equal("skillVersion" in snapshot.manifest, false);assert.equal(snapshot.preview[0].text, await snapshot.files.get("SKILL.md").text());- assert.equal(currentCreativeSkillVersion(skill).provenanceMarkdown.includes("private"), true);+ assert.equal(await snapshot.files.get("references/provenance.md").text(), currentCreativeSkillVersion(skill).provenanceMarkdown + "\n");});test("privacy findings are reported without mutating the final preview", async () => {@@ -75,7 +75,7 @@ test("submission archive contains a manifest and the reviewed method and cover passert.equal("authorId" in manifest, false);assert.equal("skillVersion" in manifest, false);const payload = await readZipBlob(outer.get("payload.zip"));- assert.deepEqual([...payload.keys()], ["SKILL.md", "references/guide.md", "assets/cover.gif"]);+ assert.deepEqual([...payload.keys()], ["SKILL.md", "references/guide.md", "references/provenance.md", "assets/cover.gif"]);});test("curated submission rejects missing public consent and derives its stable id from the Skill", async () => {@@ -106,3 +106,12 @@ test("new submissions need a cover but historical methods stay valid locally", aawait assert.rejects(() => buildCuratedSkillSnapshot(skill, { author: "Creator", summary: "Method", rightsConfirmed: true }), /成果封面/);assert.ok(currentCreativeSkillVersion(skill).skillMarkdown);});++ test("private provenance remains in the preview and blocks publication rather than disappearing", async () => {+ const skill = fixture();+ skill.versions[0].provenanceMarkdown = ['','Users','private','source.md'].join('/');+ const snapshot = await buildCuratedSkillSnapshot(skill, { author: 'Creator', summary: 'Method', rightsConfirmed: true });+ assert.ok(snapshot.files.has('references/provenance.md'));+ assert.ok(snapshot.findings.some(item => item.path === 'references/provenance.md'));+ await assert.rejects(() => buildCuratedSkillSubmissionArchive(snapshot), /隐私风险/);+});diff --git a/test/curated_skills_install_e2e.py b/test/curated_skills_install_e2e.pyindex ab4f209..89359ae 100644--- a/test/curated_skills_install_e2e.py+++ b/test/curated_skills_install_e2e.py@@ -7,23 +7,28 @@ import zipfilefrom playwright.sync_api import expect-from e2e_support import extension_session+from e2e_support import extension_session, wait_for_async_conditionCATALOG_URL = "https://wchao6891.github.io/PromptDirector-Curated/skills-catalog.json"GOOD_URL = "https://github.com/wchao6891/PromptDirector-Curated/releases/download/skills/good-skill.zip"ROLLBACK_URL = "https://github.com/wchao6891/PromptDirector-Curated/releases/download/skills/rollback-skill.zip"+SCRIPT_URL = "https://github.com/wchao6891/PromptDirector-Curated/releases/download/skills/script-skill.zip"+SCRIPT_FILES = {"scripts/run.js": "globalThis.__skillScriptExecuted = true;\n", "scripts/run.py": "print(\"preserve this script\")\n", "RIGHTS.md": "# Fixture rights\n"}UNSAFE_URL = "https://github.com/wchao6891/PromptDirector-Curated/releases/download/skills/unsafe-skill.zip"-def skill_archive(name: str, description: str, body: str, *, unsafe_script: bool = False) -> bytes:+def skill_archive(name: str, description: str, body: str, *, scripts: bool = False, unsafe_path: bool = False) -> bytes:stream = io.BytesIO()skill_markdown = f"---\nname: {name}\ndescription: {description}\n---\n\n{body}\n"with zipfile.ZipFile(stream, "w", zipfile.ZIP_DEFLATED) as archive:archive.writestr("SKILL.md", skill_markdown)archive.writestr("references/guide.md", "# Guide\n\nKeep the subject readable.\n")- if unsafe_script:- archive.writestr("scripts/run.sh", "echo should-never-run\n")+ if scripts:+ for path, text in SCRIPT_FILES.items():+ archive.writestr(path, text)+ if unsafe_path:+ archive.writestr("../escape.txt", "must not be imported")return stream.getvalue()@@ -85,11 +90,13 @@ def persisted_snapshot(page) -> dict:def main() -> None:good_archive = skill_archive("good-skill", "A safe synthetic Skill.", "# 安全精选 Skill\n\n## 使用方法\n\nUse clear hierarchy.")rollback_archive = skill_archive("rollback-skill", "A rollback fixture.", "# Rollback method\n\nKeep local work intact.")- unsafe_archive = skill_archive("unsafe-skill", "An unsafe fixture.", "# Unsafe method\n\nThis text itself is inert.", unsafe_script=True)+ unsafe_archive = skill_archive("unsafe-skill", "An unsafe fixture.", "# Unsafe method\n\nThis text itself is inert.", unsafe_path=True)+ script_archive = skill_archive("script-skill", "A complete package.", "# Script method", scripts=True)items = [catalog_item(catalog_id="[email protected]", skill_id="good-skill", title="安全精选 Skill", call_name="中式意境巨构", download_url=GOOD_URL, archive=good_archive, order=1),catalog_item(catalog_id="[email protected]", skill_id="rollback-skill", title="回滚精选 Skill", download_url=ROLLBACK_URL, archive=rollback_archive, order=2),- catalog_item(catalog_id="[email protected]", skill_id="unsafe-skill", title="不安全精选 Skill", download_url=UNSAFE_URL, archive=unsafe_archive, order=3),+ catalog_item(catalog_id="[email protected]", skill_id="script-skill", title="完整脚本 Skill", download_url=SCRIPT_URL, archive=script_archive, order=3),+ catalog_item(catalog_id="[email protected]", skill_id="unsafe-skill", title="不安全精选 Skill", download_url=UNSAFE_URL, archive=unsafe_archive, order=4),]catalog = {"format": "prompt-director-curated-skills",@@ -111,6 +118,7 @@ def main() -> None:fulfill(CATALOG_URL, "application/json", json.dumps(catalog, ensure_ascii=False))fulfill(GOOD_URL, "application/zip", good_archive)fulfill(ROLLBACK_URL, "application/zip", rollback_archive)+ fulfill(SCRIPT_URL, "application/zip", script_archive)fulfill(UNSAFE_URL, "application/zip", unsafe_archive)setup = session.open_page("collector.html")@@ -122,7 +130,7 @@ def main() -> None:setup.close()page = session.open_page("curated-skills.html")- expect(page.locator(".curated-skill-card")).to_have_count(3)+ expect(page.locator(".curated-skill-card")).to_have_count(4)assert requests == [CATALOG_URL], requestsgood_card = page.locator(".curated-skill-card").filter(has=page.get_by_role("heading", name="安全精选 Skill", exact=True))@@ -152,13 +160,16 @@ def main() -> None:good_card = page.locator(".curated-skill-card").filter(has=page.get_by_role("heading", name="安全精选 Skill", exact=True))good_card.get_by_role("button", name="查看说明", exact=True).click()expect(page.locator("#skill-detail-dialog")).to_be_visible()- expect(page.locator(".curated-skill-markdown")).to_contain_text("使用方法")- expect(page.locator(".curated-skill-markdown h1")).to_have_count(0)- maintenance = page.locator(".curated-skill-maintenance")- expect(maintenance).not_to_have_attribute("open", "")- expect(maintenance.get_by_text("许可:CC BY 4.0", exact=True)).to_be_hidden()- maintenance.locator("summary").click()- expect(maintenance.get_by_text("许可:CC BY 4.0", exact=True)).to_be_visible()+ reader = page.locator("#skill-detail-dialog .skill-detail-markdown")+ expect(reader).to_contain_text("使用方法")+ expect(reader.locator("h1")).to_have_count(1)+ expect(page.locator(".curated-skill-maintenance")).to_have_count(0)+ sidebar = page.locator("#skill-detail-dialog .skill-file-sidebar")+ sidebar.locator("summary", has_text="references").click()+ sidebar.get_by_role("button", name="guide.md", exact=True).click()+ expect(reader).to_contain_text("Keep the subject readable.")+ sidebar.get_by_role("button", name="SKILL.md", exact=True).click()+ expect(reader).to_contain_text("Use clear hierarchy.")# Force a second click through the real handler so the idempotent transaction is exercised,# rather than only accepting the disabled UI as evidence.@@ -185,19 +196,40 @@ def main() -> None:assert patched is Truepage.locator(".curated-skill-card", has_text="回滚精选 Skill").get_by_role("button", name="保存到本地", exact=True).click()expect(page.locator("#skill-toast")).to_have_text("模拟元数据提交失败")+ # Durable stage cleanup runs after feedback so a cleanup delay cannot block the UI.+ wait_for_async_condition(page, """async () => {+ const stored = await chrome.storage.local.get('stagedMediaWrites');+ return Object.keys(stored.stagedMediaWrites ?? {}).length === 0;+ }""")rolled_back = persisted_snapshot(page)assert len(rolled_back["skills"]) == 1, rolled_backassert rolled_back["keys"] == first["keys"], {"before": first, "after": rolled_back}page.evaluate("chrome.runtime.sendMessage = window.__promptDirectorOriginalSendMessage")+ script_card = page.locator(".curated-skill-card", has_text="完整脚本 Skill")+ script_card.get_by_role("button", name="保存到本地", exact=True).click()+ expect(page.locator("#skill-toast")).to_have_text("精选 Skill 已保存到本地")+ with_scripts = persisted_snapshot(page)+ assert len(with_scripts["skills"]) == 2, with_scripts+ assert len(with_scripts["keys"]) == 7, with_scripts+ script_text = {file["path"]: file["text"] for file in with_scripts["files"] if file["skillId"] == "script-skill"}+ for path, text in SCRIPT_FILES.items():+ assert script_text[path] == text, script_text+ script_card.get_by_role("button", name="查看说明", exact=True).click()+ sidebar.locator("summary", has_text="scripts").click()+ for path in ("scripts/run.py", "scripts/run.js"):+ sidebar.get_by_role("button", name=path.split("/")[-1], exact=True).click()+ expect(page.locator(".skill-file-text")).to_have_text(SCRIPT_FILES[path])+ assert page.evaluate("typeof globalThis.__skillScriptExecuted") == "undefined"+ page.locator("#skill-detail-close").click()unsafe_card = page.locator(".curated-skill-card", has_text="不安全精选 Skill")unsafe_card.get_by_role("button", name="保存到本地", exact=True).click()- expect(page.locator("#skill-toast")).to_contain_text("包含不允许的文件")+ expect(page.locator("#skill-toast")).to_contain_text("路径")after_unsafe = persisted_snapshot(page)- assert len(after_unsafe["skills"]) == 1, after_unsafe- assert after_unsafe["keys"] == first["keys"], {"before": first, "after": after_unsafe}+ assert len(after_unsafe["skills"]) == 2, after_unsafe+ assert after_unsafe["keys"] == with_scripts["keys"], {"before": with_scripts, "after": after_unsafe}- assert requests == [CATALOG_URL, GOOD_URL, ROLLBACK_URL, UNSAFE_URL], requests+ assert requests == [CATALOG_URL, GOOD_URL, ROLLBACK_URL, SCRIPT_URL, UNSAFE_URL], requestspage.evaluate("""async () => chrome.storage.local.set({uiPreferences: {locale: 'en', theme: 'dark', motion: 'none'}@@ -205,7 +237,7 @@ def main() -> None:page.set_viewport_size({"width": 390, "height": 844})page.reload(wait_until="domcontentloaded")expect(page.locator("html")).to_have_attribute("data-theme", "dark")- expect(page.locator(".curated-skill-card")).to_have_count(3)+ expect(page.locator(".curated-skill-card")).to_have_count(4)expect(page.locator("#skill-search")).to_have_attribute("placeholder", "Search by Skill or purpose")page.locator(".curated-skill-card").first.hover()mobile_visual = page.evaluate("""() => {@@ -231,7 +263,8 @@ def main() -> None:"storedPackageFiles": len(after_unsafe["keys"]),"sameVersionIdempotent": True,"metadataFailureRolledBack": True,- "unsafePackageRejected": True,+ "scriptsPreservedWithoutExecution": True,+ "unsafePathRejected": True,"mobileDarkVisualContract": mobile_visual,"externalNetworkRequests": 0,})diff --git a/test/detail-performance.test.js b/test/detail-performance.test.jsnew file mode 100644index 0000000..6999274--- /dev/null+++ b/test/detail-performance.test.js@@ -0,0 +1,52 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import * as model from '../extension/library-model.js';++function fixture() {+ let reads = 0;+ const nodes = Array.from({length: 3000}, (_, i) => ({id:`n${i}`, get name() { reads++; return `Tag ${i}`; },+ facetId:'style', parentId:i ? 'n0' : null, status:'active', aliases:[], patterns:[]}));+ const catalog = {facets:[{id:'style',name:'Style',status:'active'}],nodes};+ const entry = {facetAssignments:Array.from({length:12},(_,i)=>({facetId:'style',nodeId:`n${i+1}`,status:'confirmed',source:'manual',importance:i/12}))};+ return {catalog,entry,reads:()=>reads};+}++test('many detail tags traverse the catalog once, not once per tag path', () => {+ const {catalog,entry,reads} = fixture();+ const trim = String.prototype.trim; let normalizedNames=0;+ String.prototype.trim = function() { if (String(this).startsWith('Tag ')) normalizedNames++; return trim.call(this); };+ let result;+ try { result = model.groupEntryAssignments(entry,catalog).get('style'); }+ finally { String.prototype.trim=trim; }+ assert.equal(normalizedNames,catalog.nodes.length,'tag paths must not normalize the entire catalog again');+ assert.equal(result.length,12);+ assert.equal(result[0].path,'Tag 0 / Tag 1');+ assert.equal(reads(),catalog.nodes.length,'one normalization of the unchanged tag catalog');+});++test('detail sections share a catalog snapshot while edits to assignments and a new catalog are visible', () => {+ const {catalog,entry,reads} = fixture();+ const read = model.createEntryAssignmentReader(catalog);+ const a = read(entry); const b = read(entry);+ assert.deepEqual(a,b); assert.equal(reads(),catalog.nodes.length);+ a.get('style')[0].name='caller changed result';+ assert.equal(read(entry).get('style')[0].name,'Tag 1');+ entry.facetAssignments[0].nodeId='n20';+ assert.equal(read(entry).get('style')[0].name,'Tag 20');+ const next = structuredClone(catalog);next.nodes[20].name='Renamed';next.nodes[20].parentId='n2';+ const updated=model.createEntryAssignmentReader(next);+ assert.equal(updated(entry).get('style')[0].path,'Tag 0 / Tag 2 / Renamed');+ next.nodes[20].status='archived';+ assert.equal(model.createEntryAssignmentReader(next)(entry).get('style').length,11);+});++test('prepared tag reads preserve cycles, missing parents, pending status and entry data', () => {+ const catalog={facets:[{id:'s',name:'Style'}],nodes:[+ {id:'a',name:'A',facetId:'s',parentId:'b'}, {id:'b',name:'B',facetId:'s',parentId:'a'},+ {id:'c',name:'C',facetId:'s',parentId:'missing'}]};+ const entry={facetAssignments:[{nodeId:'a',status:'confirmed'},{nodeId:'c',status:'pending'},{nodeId:'missing',status:'confirmed'}]};+ const before=structuredClone({catalog,entry}); const read=model.createEntryAssignmentReader(catalog);+ assert.equal(read(entry).get('s')[0].path,'B / A');+ assert.equal(read(entry,'pending').get('s')[0].path,'C');+ assert.deepEqual({catalog,entry},before);+});diff --git a/test/detail_open_performance_e2e.py b/test/detail_open_performance_e2e.pynew file mode 100644index 0000000..0672c6d--- /dev/null+++ b/test/detail_open_performance_e2e.py@@ -0,0 +1,131 @@+"""Exercise first-frame scheduling and cancellation through real detail opens."""+import json+import base64+import os+import re+import tempfile+from pathlib import Path+from playwright.sync_api import expect+from e2e_support import EXTENSION_DIR, base_entry, extension_session+from image_generation_info_e2e import png_bytes+++def main():+ with tempfile.TemporaryDirectory(prefix='pd-detail-source-') as tmp:+ ext = Path(tmp)+ for source in EXTENSION_DIR.iterdir():+ if source.name != 'library.js':+ (ext / source.name).symlink_to(source, target_is_directory=source.is_dir())+ source = (EXTENSION_DIR / 'library.js').read_text()+ source = source.replace('function createLocalDiscovery(entry) {', '''function createLocalDiscovery(entry) {+ window.detailEvents.push({kind: 'rank', id: entry.id});''', 1)+ source = source.replace('async function loadImageDerivedMetadata({ refresh = false } = {}) {', '''async function loadImageDerivedMetadata({ refresh = false } = {}) {+ if (window.detailMetadataGate) { window.detailMetadataStarted = true; await window.detailMetadataGate; }''', 1)+ source = source.replace('const readDetailGenerationInfo = createGenerationInfoViewReader(getMediaBlob);', """const actualReadDetailGenerationInfo = createGenerationInfoViewReader(getMediaBlob);+ async function readDetailGenerationInfo(...args) {+ if (window.generationGate) await window.generationGate;+ return actualReadDetailGenerationInfo(...args);+ }""", 1)+ hooks = '''+window.detailEvents = [];+window.detailTest = {+ async prepare(stale) { await loadImageDerivedMetadata(); currentSimilarityIndex(); localSimilarityIndexStale = stale; if(stale) imageDerivedMetadataLoaded=false; },+ open: openDetail, close: closeDetail, ready: () => libraryFullyLoaded,+ expected(id) { const index=currentSimilarityIndex(); return rankSimilarEntries(index,id,index.profiles.size).map(item=>item.entry.title); }+};+'''+ source = source.replace('try {\n await openLibraryProgressively();', hooks + '\ntry {\n await openLibraryProgressively();', 1)+ (ext / 'library.js').write_text(source)+ with extension_session('pd-detail-scheduling-', extension_dir=ext, viewport={'width':1280,'height':900}) as session:+ setup = session.open_page('collector.html')+ entries = []+ for i in range(60):+ entry = base_entry(f'perf-{i}', f'Case {i}', 'Cinematic city in rain', 'content:prompt:image')+ entry.update(mediaAssets=[{'id':f'image-{i}', 'kind':'image', 'usage':'content', 'storageMode':'managed',+ 'mimeType':'image/png', 'palette':{'version':1,'colors':['#112233','#445566']}}], primaryMediaId=f'image-{i}')+ entries.append(entry)+ session.seed_storage(setup, {'entries':entries, 'uiPreferences':{'locale':'zh-CN','detailMode':'fullscreen'}})+ setup.evaluate('''async png => {+ const {saveMediaBlob}=await import('./media-store.js');+ const canvas=document.createElement('canvas');canvas.width=canvas.height=32;+ canvas.getContext('2d').fillRect(0,0,16,32);+ const blob=await new Promise(resolve=>canvas.toBlob(resolve));+ for(let i=0;i<60;i++) await saveMediaBlob(`image-${i}`,blob,{checkCapacity:false});+ await saveMediaBlob('image-0',new Blob([Uint8Array.from(atob(png),c=>c.charCodeAt(0))],{type:'image/png'}),{checkCapacity:false});+ }''',base64.b64encode(png_bytes()).decode())+ page = session.open_page('library.html')+ page.on('pageerror', lambda error: print(str(error), flush=True))+ page.wait_for_selector('.case-card')+ page.wait_for_function('() => window.detailTest?.ready()')+ # Metadata may be slow; visible case content must not wait for this optional enrichment.+ page.evaluate("""() => {+ window.generationGate=new Promise(resolve=>window.releaseGeneration=resolve);+ void window.detailTest.open('perf-0');+ }""")+ expect(page.locator('#detail-drawer')).to_have_attribute('data-entry-id','perf-0')+ expect(page.locator('#detail-content .detail-image')).to_be_visible()+ page.wait_for_function("() => { const image=document.querySelector('#detail-content .detail-image');return image?.complete && image.naturalWidth>0 && getComputedStyle(document.querySelector('#detail-drawer')).opacity==='1'; }")+ if os.environ.get('PD_E2E_ARTIFACT_DIR'):+ out=Path(os.environ['PD_E2E_ARTIFACT_DIR']);out.mkdir(parents=True,exist_ok=True)+ page.screenshot(path=str(out/'metadata-still-pending.png'))+ page.get_by_role('button',name='编辑原始提示词',exact=True).click()+ draft=page.get_by_role('textbox',name='编辑原始提示词',exact=True)+ draft.fill('Unsaved draft must survive metadata enrichment')+ page.evaluate('() => { window.generationGate=null;window.releaseGeneration(); }')+ expect(page.locator('#detail-content .source-open-action')).to_have_attribute('aria-description', re.compile('.*18446744073709551615.*', re.S))+ expect(draft).to_have_value('Unsaved draft must survive metadata enrichment')+ page.locator('.prompt-edit-actions').get_by_role('button',name='取消',exact=True).click()+ page.locator('#detail-close').click()+ for stale in [False, True]:+ page.evaluate('(stale)=>window.detailTest.prepare(stale)', stale)+ events = page.evaluate('''async () => {+ window.detailEvents=[];+ document.querySelector('.case-card[data-entry-id="perf-0"]').click();+ await new Promise(resolve=>{+ const tick=()=>{+ if(document.querySelector('#detail-drawer').dataset.entryId==='perf-0') {+ window.detailEvents.push({kind:'ready-frame',id:'perf-0'});resolve();+ } else requestAnimationFrame(tick);+ };requestAnimationFrame(tick);+ });return window.detailEvents;+ }''')+ assert events[0]['kind'] == 'ready-frame', events+ page.wait_for_selector('.detail-discovery .local-discovery-item')+ assert page.evaluate('window.detailEvents.filter(e=>e.kind==="rank").map(e=>e.id)') == ['perf-0']+ expected = page.evaluate('window.detailTest.expected("perf-0")')+ expect(page.locator('.detail-discovery-heading')).to_contain_text(str(len(expected)))+ actual = page.locator('.local-discovery-item').evaluate_all("nodes => nodes.map(node => node.getAttribute('aria-label').split(':')[1].split(';')[0])")+ # The section retains the complete ranking, with its existing paged DOM.+ assert actual == expected[:len(actual)] and len(actual) > 0, (actual,expected[:24])+ page.locator('#detail-close').click()+ for action in ['close','switch']:+ page.evaluate('''async action => {+ window.detailEvents=[];+ await window.detailTest.open('perf-0');+ if(action==='close') window.detailTest.close();+ else await window.detailTest.open('perf-1');+ }''',action)+ if action == 'switch':+ page.wait_for_selector('.detail-discovery .local-discovery-item')+ expect(page.locator('#detail-drawer')).to_have_attribute('data-entry-id','perf-1')+ page.wait_for_timeout(150)+ assert not page.evaluate('window.detailEvents.some(e=>e.kind==="rank"&&e.id==="perf-0")')+ if action == 'close': assert page.locator('.detail-discovery').count() == 0+ else: page.locator('#detail-close').click()+ # Closing while the deferred metadata read is still pending must also cancel ranking.+ page.evaluate("""async () => {+ window.detailEvents=[];window.detailMetadataStarted=false;+ window.detailMetadataGate=new Promise(resolve=>window.releaseDetailMetadata=resolve);+ await window.detailTest.open('perf-0');+ }""")+ page.wait_for_function('() => window.detailMetadataStarted')+ page.evaluate('() => { window.detailTest.close();window.detailMetadataGate=null;window.releaseDetailMetadata(); }')+ page.wait_for_timeout(150)+ assert page.evaluate('window.detailEvents') == []+ assert page.locator('.detail-discovery').count() == 0+ assert not session.page_errors, session.page_errors+ print(json.dumps({'first_frame_before_ranking':True,'warm_and_stale':True,'cancel_close_switch':True}))+++if __name__ == '__main__':+ main()diff --git a/test/e2e-runner.test.js b/test/e2e-runner.test.jsindex 01f0bcd..b7448d5 100644--- a/test/e2e-runner.test.js+++ b/test/e2e-runner.test.js@@ -27,7 +27,8 @@ test("E2E runner executes independent business scripts and reports after all com];assert.equal(JSON.parse(packageJson).scripts["test:e2e"], "python3 test/run_e2e.py");scripts.forEach((script) => assert.match(runner, new RegExp(`"${script.replaceAll(".", "\\.")}"`)));- assert.match(runner, /check=False/);+ assert.match(runner, /returncode = process\.wait\(\)/);+ assert.match(runner, /for line in process\.stdout:/);assert.match(runner, /results\.append\(result\)/);assert.match(runner, /if failed:/);await assert.rejects(access(new URL("./extension_e2e.py", import.meta.url)));diff --git a/test/e2e_support.py b/test/e2e_support.pyindex a8f9f47..446e6a8 100644--- a/test/e2e_support.py+++ b/test/e2e_support.py@@ -56,6 +56,11 @@ def seed_extension_storage(page: Page, payload: dict) -> None:"""Seed a fixture only after the extension's first state migration has settled."""result = page.evaluate("""async (payload) => {+ // DOMContentLoaded does not wait for collector's top-level awaits.+ // Settle its restore/read hooks before replacing the fixture state.+ if (location.pathname === '/collector.html') {+ await import(chrome.runtime.getURL('collector.js'));+ }await chrome.runtime.sendMessage({type: 'GET_STATE'});await chrome.storage.local.clear();await chrome.storage.local.set(payload);@@ -166,7 +171,10 @@ def launch_context(record_page_errors(bootstrap, bootstrap_errors)try:bootstrap.goto(f"chrome-extension://{worker.url.split('/')[2]}/collector.html", wait_until="domcontentloaded")- bootstrap.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_STATE'})")+ bootstrap.evaluate("""async () => {+ await import(chrome.runtime.getURL('collector.js'));+ await chrome.runtime.sendMessage({type: 'GET_STATE'});+ }""")assert not bootstrap_errors, f"扩展首次初始化出现运行时错误:{bootstrap_errors}"finally:bootstrap.close()diff --git a/test/image-transparency.test.js b/test/image-transparency.test.jsnew file mode 100644index 0000000..21e6a12--- /dev/null+++ b/test/image-transparency.test.js@@ -0,0 +1,61 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import * as transparency from '../extension/image-transparency.js';++const settle = () => new Promise(resolve => setTimeout(resolve, 15));+function canvasHarness() {+ let reads = 0;+ globalThis.document = { createElement() {+ let image;+ return { getContext: () => ({ clearRect() {}, drawImage(value) { image = value; },+ getImageData() {+ reads++;+ if (image.unreadable) throw new Error('tainted');+ return {data: new Uint8Array([0, 0, 0, image.alpha ? 0 : 255])};+ }+ }) };+ } };+ return () => reads;+}+function image(src, alpha = false) {+ const target = new EventTarget();+ return Object.assign(target, {src, currentSrc: '', alpha, complete: true,+ naturalWidth: 1, naturalHeight: 1, isConnected: true});+}++test('reopened immutable images reuse both opaque and transparent results within the preview budget', async () => {+ const reads = canvasHarness();+ const observe = transparency.createImageTransparencyObserver({maxEntries: 2});+ const results = [];+ for (const [src, alpha] of [['blob:a',false],['blob:b',true],['blob:a',false],['blob:b',true]]) {+ observe(image(src,alpha), value => results.push(value)); await settle();+ }+ assert.deepEqual(results,[false,true,false,true]); assert.equal(reads(),2);+ observe(image('blob:c'),()=>{}); await settle();+ observe(image('blob:a'),()=>{}); await settle();+ assert.equal(reads(),4,'evicted images are inspected again');+});++test('changed sources, detached viewers and unreadable images never publish or cache a stale result', async () => {+ const reads=canvasHarness(); const observe=transparency.createImageTransparencyObserver({maxEntries:2});+ const results=[];const changed=image('blob:old');changed.naturalHeight=512;+ observe(changed,v=>results.push(v)); changed.src='blob:new'; await settle();+ assert.deepEqual(results,[]);+ changed.alpha=true;changed.dispatchEvent(new Event('load'));await settle();+ assert.deepEqual(results,[true]);+ const detached=image('blob:detached');observe(detached,v=>results.push(v));detached.isConnected=false;await settle();+ assert.deepEqual(results,[true]);+ const bad=image('blob:bad');bad.unreadable=true;observe(bad,v=>results.push(v));await settle();+ const before=reads();observe(image('blob:bad'),v=>results.push(v));await settle();+ assert.equal(reads(),before+1);assert.deepEqual(results,[true,false]);+});++test('mutable remote URLs are rechecked and transparency beyond the first tile remains detected', async () => {+ const reads=canvasHarness();const observe=transparency.createImageTransparencyObserver({maxEntries:2});+ const results=[];+ observe(image('https://example.test/image',false),v=>results.push(v));await settle();+ observe(image('https://example.test/image',true),v=>results.push(v));await settle();+ const large=image('blob:large');large.naturalHeight=512;+ observe(large,v=>results.push(v));large.alpha=true;await settle();+ assert.deepEqual(results,[false,true,true]);assert.equal(reads(),4);+});diff --git a/test/library_startup_read_scope_e2e.py b/test/library_startup_read_scope_e2e.pyindex b8fdb5d..5778557 100644--- a/test/library_startup_read_scope_e2e.py+++ b/test/library_startup_read_scope_e2e.py@@ -64,9 +64,13 @@ const libraryStorage = {...pdScopeStorage, get: async keys => {}""")before = setup.evaluate("async () => chrome.storage.local.get(null)")before_entries = setup.evaluate("async () => (await (await import('./library-storage.js')).getLibraryStorage().get('entries')).entries")+ # The fixture collector refreshes GET_CAPTURE_WORKSPACE on storage changes.+ # Close it so the audit measures gallery reads rather than another workspace.+ setup.close()worker = run.context.service_workers[0]worker.evaluate('globalThis.pdScopeReads=[]')page = run.open_page('library.html')+ setup = pagepage.wait_for_selector('body[data-library-state="ready"]')page.locator('.case-card[data-entry-id="public"]').wait_for()assert page.locator('.case-card[data-entry-id="hidden"]').count() == 0diff --git a/test/run_e2e.py b/test/run_e2e.pyindex e0a5867..7a04eb6 100644--- a/test/run_e2e.py+++ b/test/run_e2e.py@@ -160,6 +160,8 @@ SCRIPTS = ["dialog_input_safety_e2e.py","library_detail_actions_e2e.py","library_detail_rendering_e2e.py",+ "detail_open_performance_e2e.py",+ "virtual_gallery_layout_e2e.py","library_detail_sidebar_responsive_e2e.py","library_responsive_layout_e2e.py","library_discovery_e2e.py",@@ -295,6 +297,8 @@ CASE_MANAGEMENT_SCRIPTS = ["video_detail_layout_e2e.py","library_detail_actions_e2e.py","library_detail_rendering_e2e.py",+ "detail_open_performance_e2e.py",+ "virtual_gallery_layout_e2e.py","library_detail_sidebar_responsive_e2e.py","library_responsive_layout_e2e.py","library_discovery_e2e.py",@@ -331,19 +335,21 @@ def main() -> None:results: list[Result] = []for script in scripts:started = time.monotonic()- completed = subprocess.run(- [sys.executable, str(TEST_DIR / script)],- cwd=TEST_DIR.parent,- capture_output=True,- text=True,- check=False,- )- result = Result(script, completed.returncode, time.monotonic() - started, completed.stdout + completed.stderr)+ print(f"[RUN] {script}", flush=True)+ output = []+ with subprocess.Popen(+ [sys.executable, "-u", str(TEST_DIR / script)],+ cwd=TEST_DIR.parent, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ text=True, bufsize=1,+ ) as process:+ for line in process.stdout:+ output.append(line)+ print(line, end="", flush=True)+ returncode = process.wait()+ result = Result(script, returncode, time.monotonic() - started, "".join(output))results.append(result)state = "PASS" if result.returncode == 0 else "FAIL"print(f"[{state}] {script} ({result.duration:.1f}s)", flush=True)- if result.returncode:- print(result.output.rstrip(), flush=True)print(f"\nE2E summary: {len(results) - sum(result.returncode != 0 for result in results)}/{len(results)} passed")for result in results:diff --git a/test/skill-package-edit.test.js b/test/skill-package-edit.test.jsnew file mode 100644index 0000000..e7147c4--- /dev/null+++ b/test/skill-package-edit.test.js@@ -0,0 +1,81 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { prepareSkillFileEdit, resolveSkillFileLink } from '../extension/skill-package-edit.js';+import { createCreativeSkill, saveCreativeSkillVersion, restoreCreativeSkillVersion } from '../extension/creative-skills.js';+import { parseSkillFiles, parseSkillArchive, storedSkillFiles, storedSkillPaths, exportStoredSkillPackage } from '../extension/creative-skill-package.js';+import { createZipBlob, readZipBlob } from '../extension/zip.js';+import { validateCuratedSkillPackage } from '../extension/curated-skill-catalog.js';+import { installCuratedSkillTransaction } from '../extension/curated-skill-install.js';+import { buildCuratedSkillSnapshot, buildCuratedSkillSubmissionArchive } from '../extension/curated-skill-package.js';++async function fixture(prefix = '') {+ const files = new Map(Object.entries({+ 'SKILL.md': new Blob(['---\nname: full-package\ndescription: Complete files.\nlicense: MIT\n---\n\nRun scripts/helper.py when supported.\n']),+ 'RIGHTS.md': new Blob(['Rights retained.']),+ 'LICENSE': new Blob(['MIT']),+ 'scripts/helper.py': new Blob(['raise RuntimeError("Do not execute this fixture")\n']),+ 'scripts/config.json': new Blob(['{"enabled":true}']),+ 'references/完整原词.txt': new Blob(['original\nfull prompt\n']),+ 'references/guide.md': new Blob(['# guide\n\nOriginal text.\n']),+ 'references/provenance.md': new Blob(['Public source.\n']),+ 'assets/empty.bin': new Blob([]),+ 'assets/data.bin': new Blob([new Uint8Array([0, 255, 128, 13])]),+ 'assets/cover.gif': new Blob([readFileSync(new URL('./fixtures/transfer-media/original.gif', import.meta.url))], { type: 'image/gif' })+ }).map(([path, blob]) => [prefix + path, blob]));+ const parsed = await parseSkillFiles(files), blobs = new Map();+ const saveFile = async (path, blob) => { const assetId = crypto.randomUUID(); blobs.set(assetId, blob); return { path, assetId, byteSize: blob.size, mimeType: blob.type }; };+ const packageFiles = await Promise.all([...files].map(([path, blob]) => saveFile(path, blob)));+ const { skill, state } = createCreativeSkill({}, { callName: 'Full package', portableId: parsed.name, description: parsed.description, skillMarkdown: parsed.body, references: parsed.references, packageFiles });+ return { files, parsed, skill, state, blobs, saveFile, readFile: async id => blobs.get(id) };+}++test('selecting a script reads only that file; full export preserves every byte and frontmatter', async () => {+ const f = await fixture('bundle/'); const reads = [];+ const files = await storedSkillFiles(f.skill, { paths: ['bundle/scripts/helper.py'], readFile: async id => { reads.push(id); return f.blobs.get(id); } });+ assert.equal(reads.length, 1); assert.deepEqual([...files.keys()], ['bundle/scripts/helper.py']);+ const exported = await parseSkillArchive(await exportStoredSkillPackage(f.skill, { readFile: f.readFile }));+ assert.deepEqual(new Set(storedSkillPaths(f.skill)), new Set(f.files.keys()));+ for (const [path, blob] of f.files) assert.deepEqual(await exported.files.get(path).arrayBuffer(), await blob.arrayBuffer());+});++test('editing Python and a reference preserves unrelated binary, empty and original files, and complete history restores them', async () => {+ const f = await fixture('bundle/');+ // A main-document edit already exists above the imported bytes.+ const edited = saveCreativeSkillVersion(f.state, f.skill.id, { skillMarkdown: 'Changed method.', description: 'Edited description.' });+ const input = { skillMarkdown: 'Changed method again.', description: 'Edited description.', provenanceMarkdown: 'Public source.' };+ const changes = new Map([['bundle/scripts/helper.py', new Blob(['# edited, never executed\n'])], ['bundle/references/guide.md', new Blob([])], ['bundle/assets/new.dat', new Blob([new Uint8Array([0,1,2])])]]);+ const patch = await prepareSkillFileEdit({ ...f, skill: edited.skill, input, changes });+ const saved = saveCreativeSkillVersion(edited.state, f.skill.id, { ...input, ...patch });+ const exported = await storedSkillFiles(saved.skill, { readFile: f.readFile });+ assert.equal(await exported.get('bundle/scripts/helper.py').text(), '# edited, never executed\n');+ assert.equal(exported.get('bundle/references/guide.md').size, 0);+ for (const name of ['assets/empty.bin','assets/data.bin','references/完整原词.txt','LICENSE']) assert.deepEqual(await exported.get('bundle/'+name).arrayBuffer(), await f.files.get('bundle/'+name).arrayBuffer());+ assert.match(await exported.get('bundle/SKILL.md').text(), /license: MIT/);+ const restored = restoreCreativeSkillVersion(saved.state, saved.skill.id, f.skill.currentVersionId);+ const original = await storedSkillFiles(restored.skill, { readFile: f.readFile });+ for (const [path, blob] of f.files) assert.deepEqual(await original.get(path).arrayBuffer(), await blob.arrayBuffer());+});++test('complete package passes submission payload, curated installation and re-export with provenance and dependency facts', async () => {+ const f = await fixture();+ const snapshot = await buildCuratedSkillSnapshot(f.skill, { author: 'Author', summary: 'Full method', rightsConfirmed: true }, { readFile: f.readFile });+ const outer = await readZipBlob(await buildCuratedSkillSubmissionArchive(snapshot));+ const archive = outer.get('payload.zip');+ const item = { id:'[email protected]',skillId:'full-package',version:'1.0.0',title:'Full package',callName:'Full package',authorId:'author',author:'Author',license:'MIT',reviewStatus:'approved',reviewedAt:'2026-10-22T00:00:00Z',summary:'Full method',downloadUrl:'https://github.com/example/repo/releases/download/v1/full.zip',sha256:'a'.repeat(64),archiveBytes:archive.size,order:1 };+ const parsed = await validateCuratedSkillPackage(item, archive);+ let installed;+ await installCuratedSkillTransaction({ state:{},item,parsed, saveBlob: async (id,blob) => f.blobs.set(id,blob),deleteBlobs:async()=>{},createSkill:async input=>{installed=createCreativeSkill({},input).skill;return {skill:installed};} });+ assert.ok(installed.runtimeDependencies.includes('scripts'));+ const exported = await parseSkillArchive(await exportStoredSkillPackage(installed,{readFile:f.readFile}));+ for (const [path, blob] of f.files) assert.deepEqual(await exported.files.get(path).arrayBuffer(), await blob.arrayBuffer());+});++test('internal references stay inside the known package and external sources are not mistaken for files', () => {+ const paths=['references/原词.txt','assets/photo.png'];+ assert.equal(resolveSkillFileLink('references/index.md','%E5%8E%9F%E8%AF%8D.txt',paths).path,'references/原词.txt');+ assert.equal(resolveSkillFileLink('references/index.md','../assets/photo.png',paths).path,'assets/photo.png');+ assert.equal(resolveSkillFileLink('SKILL.md','https://example.com/a',paths),null);+ assert.equal(resolveSkillFileLink('SKILL.md','javascript:alert(1)',paths),null);+ assert.equal(resolveSkillFileLink('SKILL.md','missing.txt',paths),null);+});diff --git a/test/skill_cover_e2e.py b/test/skill_cover_e2e.pyindex b846297..0f5dfa9 100644--- a/test/skill_cover_e2e.py+++ b/test/skill_cover_e2e.py@@ -44,8 +44,13 @@ def main():assert second['assetId'] != first['assetId']assert page.evaluate("async id => !!await (await import(chrome.runtime.getURL('media-store.js'))).getMediaBlob(id)", first['assetId']) is Falsepage.goto(f'chrome-extension://{session.extension_id}/skills.html?view=detail&skill={skill_id}')- expect(page.locator('#skill-detail-cover img')).to_be_visible()- page.locator('#skill-detail-more > summary').click()+ files = page.locator('#skill-detail-files')+ files.locator('summary', has_text='assets').click()+ files.get_by_role('button', name='cover.avif', exact=True).click()+ expect(files.locator('img.skill-file-media')).to_be_visible()+ page.wait_for_function("() => document.querySelector('#skill-detail-files img')?.naturalWidth === 64")+ files.get_by_role('button', name='SKILL.md', exact=True).click()+ page.locator('#skill-detail-download > summary').click()page.locator('#skill-export').click()exported, _ = wait_for_download(page)with zipfile.ZipFile(exported) as archive:@@ -88,7 +93,12 @@ def main():assert restored['skills'][0]['versions'] == before['skills'][0]['versions']assert restored['entries'][0]['text'] == keep['text']page.goto(f'chrome-extension://{session.extension_id}/skills.html?view=detail&skill={restored["skills"][0]["id"]}')- expect(page.locator('#skill-detail-cover img')).to_be_visible()+ files = page.locator('#skill-detail-files')+ files.locator('summary', has_text='assets').click()+ files.get_by_role('button', name='cover.avif', exact=True).click()+ expect(files.locator('img.skill-file-media')).to_be_visible()+ page.wait_for_function("() => document.querySelector('#skill-detail-files img')?.naturalWidth === 64")+ files.get_by_role('button', name='SKILL.md', exact=True).click()page.set_viewport_size({'width': 390, 'height': 844})assert page.evaluate('document.documentElement.scrollWidth <= innerWidth')page.screenshot(path='/tmp/promptdirector-skill-cover-restored-narrow.png', full_page=True)diff --git a/test/virtual-gallery.test.js b/test/virtual-gallery.test.jsindex 69cca9c..0961ab1 100644--- a/test/virtual-gallery.test.js+++ b/test/virtual-gallery.test.js@@ -5,16 +5,18 @@ import {readFile} from 'node:fs/promises';const source = (await readFile(new URL('../extension/virtual-gallery.js', import.meta.url), 'utf8')).replace('export function', 'function');function fixture(minimum = 270) {const observers = [], frames = new Map(), cards = new Map(), released = [];- let scrollY = 0, frameId = 0;- const container = {children: [], style: {}, dataset: {}, clientWidth: 1120,- getBoundingClientRect: () => ({top: -scrollY}),+ let scrollY = 0, frameId = 0, dirty = false, forcedReads = 0;+ const style = () => new Proxy({}, { set(target, key, value) { dirty = true; target[key] = value; return true; } });+ const readLayout = () => { if (dirty) forcedReads++; dirty = false; };+ const container = {children: [], style: style(), dataset: {}, clientWidth: 1120,+ getBoundingClientRect: () => { readLayout(); return {top: -scrollY}; },append(card) {this.children.push(card); card.parent = this;},insertBefore(card, before) {this.children = this.children.filter(c => c !== card); const i = this.children.indexOf(before); this.children.splice(i < 0 ? this.children.length : i, 0, card);}};function createCard(id) {- const card = {dataset: {entryId: id}, style: {}, imageHeight: 220,+ const card = {dataset: {entryId: id}, style: style(), imageHeight: 220,get isConnected() {return container.children.includes(this);},- getBoundingClientRect() {const height = 40 + this.imageHeight * (Number.parseFloat(this.style.width || 270) / 270);+ getBoundingClientRect() {readLayout(); const height = 40 + this.imageHeight * (Number.parseFloat(this.style.width || 270) / 270);const top = Number.parseFloat(this.style.top || 0) - scrollY; return {height, top, bottom: top + height};},contains: () => false,remove() {container.children = container.children.filter(c => c !== this);}@@ -32,6 +34,7 @@ function fixture(minimum = 270) {releaseCard: card => released.push(card.dataset.entryId)});const flush = () => {for (let i = 0; frames.size && i < 20; i++) {const batch = [...frames.values()]; frames.clear(); batch.forEach(cb => cb());} assert.equal(frames.size, 0);};return {gallery, cards, container, released, createCard, flush,+ resetForcedReads() { forcedReads = 0; dirty = false; }, forcedReads: () => forcedReads,resizeCards() {observers[0].callback(container.children.map(target => ({target}))); flush();},scroll(y) {scrollY = y; observers[1].callback([]); flush();},zoom(min) {gallery.resize(() => {minimum = min;}); flush();}@@ -68,3 +71,14 @@ test('zooming down to minimum and back retains the visible case and its screen pf.zoom(270);assert.ok(anchor.isConnected); assert.ok(Math.abs(anchor.getBoundingClientRect().top - top) <= 1);});+++test('dense gallery resize batches geometry instead of forcing layout once per retained card', () => {+ const f = fixture(140);+ const cards = Array.from({length: 240}, (_, i) => f.createCard(String(i)));+ cards.forEach(card => f.container.append(card)); f.gallery.append(cards);+ const retained = f.container.children.length;+ assert.ok(retained > 50, 'exercise the dense wall kept behind an opening detail');+ f.resetForcedReads(); f.gallery.resize(); f.flush();+ assert.ok(f.forcedReads() <= 4, `geometry phases should be bounded, got ${f.forcedReads()} for ${retained} cards`);+});diff --git a/test/virtual_gallery_layout_e2e.py b/test/virtual_gallery_layout_e2e.pynew file mode 100644index 0000000..c29e894--- /dev/null+++ b/test/virtual_gallery_layout_e2e.py@@ -0,0 +1,49 @@+"""A dense wall must not reflow once per card when opening details changes its width."""+import json+from e2e_support import extension_session+++def main():+ with extension_session('pd-dense-layout-', viewport={'width':2560,'height':1210}) as session:+ page=session.open_page('collector.html')+ page.evaluate('''async () => {+ const {createVirtualGallery}=await import('./virtual-gallery.js');+ document.body.replaceChildren();document.body.style.margin='0';+ const container=document.createElement('div');+ container.style.cssText='position:relative;width:100%;--masonry-card-min-width:140px;--masonry-gap:12px';+ document.body.append(container);+ const createCard=id=>{+ const card=document.createElement('article');card.dataset.entryId=id;+ card.style.cssText='height:auto;aspect-ratio:1;box-sizing:border-box;border:1px solid';+ card.textContent=`Case ${id}`;return card;+ };+ window.denseGallery=createVirtualGallery(container,{mode:()=> 'waterfall',createCard});+ const cards=Array.from({length:600},(_,i)=>createCard(String(i)));+ container.append(...cards);window.denseGallery.append(cards);window.denseContainer=container;+ }''')+ page.wait_for_timeout(200)+ cdp=session.context.new_cdp_session(page);cdp.send('Performance.enable')+ def metrics():+ return {v['name']:v['value'] for v in cdp.send('Performance.getMetrics')['metrics']}+ before=metrics()+ page.evaluate('''async () => {+ window.denseContainer.style.width='calc(100% - 16px)';window.denseGallery.resize();+ await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));+ }''')+ after=metrics()+ result={'cards':page.locator('article').count(),'layouts':after['LayoutCount']-before['LayoutCount'],+ 'layout_ms':round((after['LayoutDuration']-before['LayoutDuration'])*1000,2)}+ print(json.dumps(result),flush=True)+ assert result['cards']>200,result+ assert result['layouts']<=5,result+ geometry=page.locator('article').evaluate_all('nodes=>nodes.map(node=>({id:node.dataset.entryId,left:node.offsetLeft,top:node.offsetTop,width:node.offsetWidth,height:node.offsetHeight}))')+ columns={}+ for card in geometry:+ column=columns.setdefault(card['left'],[]);column.append(card)+ for column in columns.values():+ column.sort(key=lambda card:card['top'])+ assert all(a['top']+a['height']<=b['top'] for a,b in zip(column,column[1:])),column+ assert not session.page_errors,session.page_errors+++if __name__=='__main__':main()