Skip to content

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. 提示词导演

发布 1.20.1:简化设置并支持保留资料的本地程序升级

MigenAIb3dafb4b1ac6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ae37bbf..ef34dd2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,12 @@
# Changelog
+## 1.20.1
+
+- 设置首页收紧布局:关联按钮与功能同排、保存改为图标,跨设备同步按需展开;许可与版本详情移到“关于”。
+- 商店版由 Chrome 自动更新;GitHub 本地版支持验证安装目录和更新包后原位替换程序,案例与媒体无需导出、迁移或重新导入。
+- 本地升级显示准备与写入进度,跳过未变化的程序文件;写入失败可回退,重启后核验实际版本,提供临时程序副本清理与中断恢复入口。
+- 修复返回案例库时的浏览位置与创作台搜索条件差异。
+
## 1.20.0
- 网页采集补全 Higgsfield 作品、教程与 LibTV 公开案例的媒体、原始提示词、来源元信息和附件;重新保存可补齐缺失媒体,保留已编辑内容。
diff --git a/README.md b/README.md
index f9344ae..0ab6016 100644
--- a/README.md
+++ b/README.md
@@ -29,7 +29,13 @@ PromptDirector 是一个免费、开源、本地优先的 Chrome 扩展。它把
需要检查源码或参与开发时,可从 [GitHub Releases](https://github.com/wchao6891/PromptDirector/releases) 下载名称带 `FIXED-ID-DEV` 的最新 ZIP 并解压。在 Chrome 或 Edge 的扩展管理页开启“开发者模式”,选择“加载已解压的扩展程序”,然后选择解压后的目录。这个包保留 Chrome Web Store 分配的固定扩展身份,适合本地开发验证。
-不带 `FIXED-ID-DEV` 的同版本 ZIP 仅供维护者上传 Chrome Web Store,清单中按商店要求移除了 `key`,不要把它作为本地解压安装包。升级前请先在“更多 → 备份与同步”创建并验证完整资料夹备份;如曾使用其他扩展 ID,请按[扩展身份迁移说明](docs/EXTENSION_ID_MIGRATION.md)恢复资料。
+不带 `FIXED-ID-DEV` 的同版本 ZIP 仅供维护者上传 Chrome Web Store,清单中按商店要求移除了 `key`,不要把它作为本地解压安装包。同一扩展身份下的常规更新不需要导出或重新导入案例;如曾使用其他扩展 ID,请按[扩展身份迁移说明](docs/EXTENSION_ID_MIGRATION.md)恢复资料。
+
+## 本地版更新
+
+已具备本地升级功能的版本:在“设置”检查更新,点击“升级本地版”,选择 Chrome 当前加载的安装文件夹并授权。程序更新后重启插件,重新打开设置核对版本;如出现“清理升级临时文件”,点击完成清理。案例和媒体继续使用当前浏览器中的原资料库。
+
+旧版本首次接入:下载新版 `FIXED-ID-DEV` ZIP,将包内程序文件覆盖到 Chrome 当前加载的原目录,再到扩展管理页点击重新加载。保持原插件与固定身份,无需卸载,也无需备份再导入案例。源码工作目录通过 Git 更新。
## 从源码构建
@@ -40,7 +46,7 @@ npm install
npm run verify
```
-`npm run verify` 是完整验证门槛,构建与验证不会自动发布 GitHub Release 或上传商店:先完成源码、资源、历史数据兼容与单元测试,再把固定 ID 本地包加载到隔离的 Chrome for Testing 中跑完整浏览器 E2E;全部通过后生成商店包,并用上一正式版资料执行同一 Chrome Profile 的最终包升级演练。任一阶段失败都不会通过门禁。只需快速检查源码时可运行 `npm run verify:source`,只检查历史数据合同可运行 `npm run check:compat`。`npm run test:local-extension` 是打包后自动化主验收;`npm run package` 生成保留固定身份的本地安装包;`npm run package:release` 生成移除 `key` 的 Chrome Web Store 上传包。两者包含相同的运行代码,只有安装身份用途不同。正式身份缺失时命令会明确失败,避免用户资料被错误扩展 ID 隔离。
+`npm run verify` 是完整验证门槛,构建与验证不会自动发布 GitHub Release 或上传商店:先完成源码、资源、历史数据兼容与单元测试,再把固定 ID 本地包加载到隔离的 Chrome for Testing 中跑完整浏览器 E2E;全部通过后生成商店包,并用上一正式版资料执行同一 Chrome Profile 的最终包升级演练。任一阶段失败都不会通过门禁。只需快速检查源码时可运行 `npm run verify:source`,只检查历史数据合同可运行 `npm run check:compat`。`npm run test:local-extension` 是打包后自动化主验收;`npm run package` 生成保留固定身份的本地安装包;`npm run package:release` 生成移除 `key` 的 Chrome Web Store 上传包。两者共用案例、媒体和创作功能。商店包移除本地程序安装器,只保留 Chrome 更新;固定身份本地包保留原位升级。正式身份缺失时命令会明确失败,避免用户资料被错误扩展 ID 隔离。
已发布数据的长期支持规则、权威夹具和升级门禁见[数据兼容说明](docs/DATA_COMPATIBILITY.md)。当前浏览器兼容边界和已确认但延期的增强记录在[已知限制](docs/KNOWN_LIMITATIONS.md)。
diff --git a/background.js b/background.js
index f66553f..5ad44ce 100644
--- a/background.js
+++ b/background.js
@@ -471,6 +471,7 @@ let visionAnalysisInFlight = false;
const aiProviderModule = createAiProviderModule();
const extensionUpdateLifecycle = createExtensionUpdateLifecycle({
runtime: chrome.runtime,
+ getInstallation: () => chrome.management.getSelf(),
storage: chrome.storage.local,
fetchFn: (...args) => fetch(...args),
notify: (status) => chrome.runtime.sendMessage({
diff --git a/docs/EXTENSION_ID_MIGRATION.md b/docs/EXTENSION_ID_MIGRATION.md
index 5506015..98b7e61 100644
--- a/docs/EXTENSION_ID_MIGRATION.md
+++ b/docs/EXTENSION_ID_MIGRATION.md
@@ -2,10 +2,12 @@
Chrome 会把扩展资料绑定到浏览器配置和扩展 ID。更换为另一个扩展 ID 时,新版无法直接读取旧版本地资料。
+同一扩展 ID 的常规更新保留原资料库,按 [README](../README.md#本地版更新) 更新程序即可。下面的备份恢复步骤仅用于更换扩展身份。
+
## 安全迁移
1. 保持旧扩展已安装,不要先卸载。
-2. 在旧扩展的“更多 → 备份与同步”创建完整资料夹备份。
+2. 在旧扩展的“设置 → 备份与同步”创建完整资料夹备份。
3. 打开备份目录,确认包含完成标记和媒体文件,并记录资料库显示的案例数量。1.19.2 及之后创建的新备份还会包含回收站案例和项目,并把可读取的本机链接原件复制成可恢复文件。
4. 安装新扩展,在“备份与同步”中选择刚才的完整资料夹备份恢复。
5. 随机打开多个案例,核对文字、媒体和项目关系;确认无误后再移除旧扩展。
diff --git a/docs/KNOWN_LIMITATIONS.md b/docs/KNOWN_LIMITATIONS.md
index d40a3cb..abff4c1 100644
--- a/docs/KNOWN_LIMITATIONS.md
+++ b/docs/KNOWN_LIMITATIONS.md
@@ -11,3 +11,9 @@ PromptDirector 目前依赖 Chrome 的原生媒体解码能力。遇到浏览器
案例库中的本地视频可以在用户确认后,以 Base64 发送给 GLM-5.3-Flash 做视频分析。智谱当前公开的 [GLM-5.3-Flash 模型页](https://docs.bigmodel.cn/cn/guide/models/vlm/glm-5.3-flash)和 [Chat Completions 接口页](https://docs.bigmodel.cn/api-reference/%E6%A8%A1%E5%9E%8B-api/%E5%AF%B9%E8%AF%9D%E8%A1%A5%E5%85%A8)没有声明直连视频的文件大小上限,因此 PromptDirector 不擅自设置 8 MB 等未公开限制。
当前版本不会自动压缩、截断、抽帧或改用其他模型,因为这些降级会改变分析对象或产生额外费用。若服务端拒绝文件大小、格式或内容,请求会显示所选服务返回的错误且不会自动重试。只有公网视频文件直链可走 URL 分析;YouTube、Bilibili、抖音、X 或 Vimeo 的播放页面不等同于视频文件直链。
+
+## 本地程序升级
+
+本地升级需要 Chrome 开发者模式和当前安装目录的读写授权。旧版首次接入需原目录覆盖程序;以后使用设置页升级。不同扩展 ID、非当前安装目录或新增必要权限的更新包会停止自动写入。只创建程序恢复副本,不复制案例和媒体。
+
+若写入中断后无法运行,在扩展管理页加载原目录内的 `PromptDirector-Update-Recovery` 程序副本,以相同身份恢复原版本;不要先卸载插件。目录写权限在重启后可能需要再次授权才能清理临时程序文件。
diff --git a/extension-update.js b/extension-update.js
index ad05f7c..bc7f96a 100644
--- a/extension-update.js
+++ b/extension-update.js
@@ -29,8 +29,13 @@ export function compareExtensionVersions(left, right) {
return 0;
}
-export function extensionUpdateChannel(manifest = {}) {
- return typeof manifest.key === "string" && manifest.key.trim() ? "development" : "store";
+export function extensionUpdateChannel(installation = {}) {
+ if (installation.installType === "development") return "development";
+ try {
+ const url = new URL(installation.updateUrl);
+ if (url.protocol === "https:" && url.hostname === "clients2.google.com" && url.pathname === "/service/update2/crx") return "store";
+ } catch { /* An unavailable source must not be presented as automatic updating. */ }
+ return "unknown";
}
export function githubLatestReleaseUrl(homepageUrl) {
@@ -87,10 +92,9 @@ function validVersionOrEmpty(value) {
return parseExtensionVersion(version) ? version : "";
}
-function normalizedState(stored, manifest) {
+function normalizedState(stored, manifest, channel) {
const currentVersion = validVersionOrEmpty(manifest?.version);
if (!currentVersion) throw new Error("当前扩展版本号无效");
- const channel = extensionUpdateChannel(manifest);
const source = stored && typeof stored === "object" ? stored : {};
let pendingVersion = validVersionOrEmpty(source.pendingVersion);
let latestVersion = validVersionOrEmpty(source.latestVersion);
@@ -129,7 +133,7 @@ function normalizedState(stored, manifest) {
installedAt: normalizeTimestamp(source.installedAt),
canApply: storeUpdateAvailable || developmentUpdateAvailable,
applyBehavior: developmentUpdateAvailable
- ? "reload_development_directory"
+ ? "upgrade_local_package"
: storeUpdateAvailable ? "install_downloaded_update" : null
};
}
@@ -146,6 +150,7 @@ function errorMessage(error) {
export function createExtensionUpdateLifecycle({
runtime,
storage,
+ getInstallation = () => globalThis.chrome.management.getSelf(),
fetchFn = globalThis.fetch,
now = () => Date.now(),
notify = () => undefined,
@@ -156,6 +161,7 @@ export function createExtensionUpdateLifecycle({
}
let operationQueue = Promise.resolve();
+ const readChannel = async () => extensionUpdateChannel(await Promise.resolve().then(getInstallation).catch(() => ({})));
const runExclusive = (operation) => {
const run = operationQueue.then(operation, operation);
operationQueue = run.catch(() => undefined);
@@ -165,11 +171,11 @@ export function createExtensionUpdateLifecycle({
async function readStatus() {
const manifest = runtime.getManifest();
const stored = await storage.get(EXTENSION_UPDATE_STORAGE_KEY);
- return normalizedState(stored?.[EXTENSION_UPDATE_STORAGE_KEY], manifest);
+ return normalizedState(stored?.[EXTENSION_UPDATE_STORAGE_KEY], manifest, await readChannel());
}
async function writeStatus(status) {
- const normalized = normalizedState(status, runtime.getManifest());
+ const normalized = normalizedState(status, runtime.getManifest(), await readChannel());
await storage.set({ [EXTENSION_UPDATE_STORAGE_KEY]: persistedState(normalized) });
await Promise.resolve(notify(normalized)).catch(() => undefined);
return normalized;
@@ -256,14 +262,16 @@ export function createExtensionUpdateLifecycle({
},
check() {
- return runExclusive(async () => extensionUpdateChannel(runtime.getManifest()) === "development"
- ? checkDevelopmentRelease()
- : checkStoreUpdate());
+ return runExclusive(async () => {
+ const channel = await readChannel();
+ if (channel === "development") return checkDevelopmentRelease();
+ if (channel === "store") return checkStoreUpdate();
+ return writeStatus({ ...await readStatus(), checkStatus: "error", lastError: "无法确认安装来源,请重新打开设置后重试" });
+ });
},
handleStartup() {
- if (extensionUpdateChannel(runtime.getManifest()) !== "development") return runExclusive(readStatus);
- return runExclusive(checkDevelopmentRelease);
+ return runExclusive(async () => await readChannel() === "development" ? checkDevelopmentRelease() : readStatus());
},
handleUpdateAvailable(details) {
@@ -304,7 +312,7 @@ export function createExtensionUpdateLifecycle({
apply() {
return runExclusive(async () => {
const status = await readStatus();
- if (!status.canApply || !status.applyBehavior) {
+ if (status.channel !== "store" || !status.canApply) {
return {
ok: false,
status,
@@ -312,19 +320,16 @@ export function createExtensionUpdateLifecycle({
installsUpdate: false,
message: status.channel === "store"
? "Chrome 尚未下载可安装的更新"
- : "当前目录已是最新版本"
+ : "本地版需要先安装更新包,重新载入不会安装新版本"
};
}
scheduleReload(() => runtime.reload());
- const installsUpdate = status.channel === "store";
return {
ok: true,
status,
willReload: true,
- installsUpdate,
- message: installsUpdate
- ? "即将重载并应用 Chrome 已下载的更新"
- : "即将重载当前开发目录;这不会下载或安装新版本"
+ installsUpdate: true,
+ message: "即将重载并应用 Chrome 已下载的更新"
};
});
}
diff --git a/i18n.js b/i18n.js
index 7634b0c..90bd69d 100644
--- a/i18n.js
+++ b/i18n.js
@@ -1,6 +1,46 @@
import { normalizeUiPreferences, resolveLocale } from "./preferences.js";
const EN = Object.freeze({
+ "清理升级临时文件": "Clear temporary update files",
+ "已清理升级临时文件": "Temporary update files cleared",
+ "上次准备更新中断,原插件未更改。清理临时程序副本后继续。": "Update preparation was interrupted; the extension was not changed. Clear the temporary program copy to continue.",
+ "已恢复原版本,案例与媒体仍在原资料库": "The previous version has been restored. Cases and media remain in your library.",
+ "未连接": "Not connected",
+ "待解锁": "Locked",
+ "正在停止同步…": "Stopping sync\u2026",
+ "同步已停止": "Sync stopped",
+ "已同步": "Synced",
+ "待同步": "Pending sync",
+ "清理上次程序恢复副本": "Clear the previous program recovery copy",
+ "已确认上次升级成功。允许清理程序恢复副本后继续;不会删除案例。": "The previous upgrade was verified. Allow cleanup of its program recovery copy to continue. Cases are not deleted.",
+ "允许并继续": "Allow and continue",
+
+ "关于": "About",
+ "资料库": "Library",
+ "本地版": "Local version",
+ "查看源码": "View source",
+ "升级本地版": "Upgrade local version",
+ "选择已下载的更新包": "Choose a downloaded update package",
+ "商店版由 Chrome 自动更新": "Chrome updates the store version automatically",
+ "只更新插件程序,案例和媒体留在原资料库。升级会重启插件,请先保存正在编辑的内容。": "Only the extension program is updated. Cases and media stay in your library. The extension will restart; save your edits first.",
+ "正在准备更新 · {completed} 个程序文件": "Preparing update · {completed} program files",
+ "验证更新包": "Verify update package",
+ "下载更新包": "Download update package",
+ "正在验证更新包…": "Verifying update package\u2026",
+ "无法下载对应的本地更新包,请稍后重试": "Could not download the local update package. Try again later.",
+ "所选更新包与官方发布内容不一致,已停止升级": "This package differs from the official release. Upgrade stopped.",
+ "更新包版本与发布版本不一致": "The package version does not match the release.",
+ "升级到 {version}": "Upgrade to {version}",
+ "请选择 Chrome 当前加载的插件文件夹。无需卸载、备份或导入案例。": "Choose the extension folder currently loaded by Chrome. No uninstall, case backup, or import is needed.",
+ "选择安装文件夹并升级": "Choose installation folder and upgrade",
+ "正在核对安装目录…": "Verifying installation folder\u2026",
+ "另一个页面正在升级,请等待完成": "Another page is upgrading. Please wait.",
+ "正在更新程序 {completed}/{total}": "Updating program {completed}/{total}",
+ "程序已写入,正在重启验证版本…": "Program written. Restarting to verify the version\u2026",
+ "已升级到 {version}": "Upgraded to {version}",
+ "上次升级尚未完成,请先处理升级恢复提示": "The previous upgrade is incomplete. Please follow the recovery instructions first.",
+ "上次升级未完成。请在 Chrome 扩展管理中加载安装目录内的 {folder},恢复原版本;无需卸载或导入案例。": "The previous upgrade did not finish. In Chrome extensions, load {folder} inside the installation folder to restore the previous version. No uninstall or case import is needed.",
+
"当前页面未显示原始提示词": "No original prompt is shown on this page",
"正文保存失败": "Could not save article text",
"提示词范围": "Prompt scope",
diff --git a/library.css b/library.css
index ea4a29d..5512d15 100644
--- a/library.css
+++ b/library.css
@@ -88,14 +88,6 @@ details:not([open]) > .detail-project-popover { display: none; }
.top-actions .add-menu .package-menu-panel { top: calc(100% + 8px); right: 20px; left: auto; }
.package-preferences { margin-top: 3px; border-top: 1px solid var(--line); padding: 4px 5px 0; }
.package-preferences > summary { min-height: 34px; padding: 8px 5px; color: var(--muted); cursor: pointer; font-size: 11px; font-weight: 750; list-style-position: inside; }
-.package-preferences-body { display: grid; gap: 9px; padding: 5px 0; }
-.package-preferences-body label { display: grid; grid-template-columns: 96px 1fr; align-items: center; gap: 9px; color: var(--muted); font-size: 11px; font-weight: 700; }
-.package-preferences-body select { min-height: 34px; }
-.library-storage-settings { display: grid; gap: 8px; border-top: 1px solid var(--line); padding: 11px 5px 5px; }
-.library-storage-settings label { display: grid; gap: 4px; color: var(--muted); font-size: 11px; font-weight: 700; }
-.library-storage-settings input { min-height: 34px; }
-.library-storage-settings div { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
-.package-menu-panel .library-storage-settings button { min-height: 34px; padding: 6px 8px; font-size: 11px; }
.data-safety-dialog {
width: min(620px, calc(100vw - 32px));
@@ -142,7 +134,6 @@ details:not([open]) > .detail-project-popover { display: none; }
.about-dialog dd { margin: 0; }
.source-link { display: inline-block; max-width: 100%; overflow: hidden; color: var(--ink); font-weight: 700; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; }
.source-link:hover { color: var(--accent-ink); }
-.update-download-action { display: inline-flex; align-items: center; justify-content: center; text-decoration: none; }
.data-safety-summary { display: flex; align-items: center; justify-content: space-between; gap: 12px; border-radius: 10px; padding: 12px; background: var(--raised); }
.data-safety-summary strong { font-size: 13px; }
.data-safety-summary span { color: var(--muted); font-size: 11px; text-align: right; }
@@ -876,25 +867,49 @@ details:not([open]) > .selection-menu-panel { display: none; }
.settings-rules-panel .analysis-protocol > summary { cursor: pointer; font-weight: 600; }
.settings-rules-panel .analysis-settings-form { align-content: start; }
.settings-tabs { flex-wrap: wrap; }
-.settings-general-section { grid-column: 1 / -1; display: grid; gap: 12px; border-top: 1px solid var(--line); padding-top: 16px; }
-.capture-permission-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
-.capture-permission-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 12px; border: 1px solid var(--line); border-radius: 7px; padding: 11px 12px; background: var(--raised); }
-.capture-permission-row > div { display: grid; min-width: 0; gap: 3px; }
-.capture-permission-row strong { color: var(--ink); font-size: 11px; }
-.capture-permission-row span { color: var(--muted); font-size: 10px; }
+/* General settings keep each action next to its field or function. */
+.settings-dialog .compact-general { display: flex; flex-direction: column; align-items: stretch; gap: 0; padding: 0; }
+.compact-general .setting-section { padding: 12px 0; border-bottom: 1px solid var(--line); }
+.compact-general .setting-section:first-child { padding-top: 8px; }
+.setting-section-heading { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin-bottom: 8px; min-height: 24px; }
+.setting-section-heading h3 { margin: 0; color: var(--ink); font-size: 13px; font-weight: 650; }
+.setting-section-heading small { color: var(--muted); font-size: 11px; font-weight: 400; }
+.appearance-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
+.appearance-grid label { display: grid; grid-template-columns: 1fr; gap: 8px; color: var(--muted); font-size: 11px; }
+.setting-row { display: grid; grid-template-columns: 108px minmax(0, 1fr) auto; gap: 12px; align-items: center; min-height: 36px; }
+.setting-row + .setting-row { margin-top: 8px; }
+.setting-row > label { font-size: 12px; color: var(--muted); }
+.setting-row input { width: 100%; min-height: 36px; }
+.setting-row .field-span { grid-column: 2 / -1; }
+.capture-permission-list { display: flex; flex-wrap: wrap; gap: 8px 32px; }
+.capture-permission-row { display: flex; align-items: center; gap: 12px; min-height: 36px; }
+.capture-permission-row strong { color: var(--ink); font-size: 12px; font-weight: 500; }
+.capture-permission-row span { color: var(--muted); font-size: 11px; }
.capture-permission-row span.is-granted { color: var(--success); }
-.capture-permission-row button { min-height: 30px; padding: 5px 8px; font-size: 10px; }
-.settings-about { grid-column: 1 / -1; display: grid; gap: 9px; border-top: 1px solid var(--line); padding-top: 14px; color: var(--muted); font-size: 11px; }
-.settings-about strong { color: var(--ink); font-size: 12px; }
-.settings-about-heading { display: flex; align-items: start; justify-content: space-between; gap: 12px; }
-.settings-about-heading > div { display: grid; gap: 3px; }
-.settings-update-details, .settings-update-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; }
-.settings-update-explanation { max-width: 720px; margin: 0; line-height: 1.55; }
-.settings-update-actions button { min-height: 32px; }
-.update-status-badge { flex: none; border-radius: 999px; padding: 5px 8px; color: var(--muted); background: var(--raised); font-size: 10px; }
-.update-status-badge.is-current { color: var(--success); background: color-mix(in srgb, var(--success) 10%, var(--raised)); }
-.update-status-badge.is-available { color: var(--accent-ink); background: var(--accent-soft); }
-.update-status-badge.is-error { color: var(--danger); background: color-mix(in srgb, var(--danger) 9%, var(--raised)); }
+.capture-permission-row button { min-height: 30px; padding: 5px 9px; font-size: 11px; }
+.compact-general .settings-data-safety { border-bottom: 0; padding-bottom: 0; }
+.compact-general .data-safety-primary-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
+.compact-general .data-safety-primary-actions button { display: inline-flex; align-items: center; gap: 7px; min-height: 36px; }
+.compact-general .share-package-import { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; min-height: 36px; }
+.share-package-import > span { font-size: 12px; }
+.share-package-import button { min-height: 30px; padding: 5px 10px; font-size: 11px; }
+.compact-general .sync-settings { margin-top: 8px; padding: 0; border: 0; }
+.compact-general .sync-settings summary { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; min-height: 36px; padding: 0; color: var(--ink); font-size: 12px; font-weight: 500; }
+.compact-general .sync-settings summary::-webkit-details-marker { display: none; }
+.sync-settings summary > .ui-icon { width: 14px; height: 14px; color: var(--muted); }
+.sync-settings[open] summary > .ui-icon { transform: rotate(90deg); }
+.sync-settings summary small { color: var(--muted); font-size: 11px; font-weight: 400; }
+.compact-general .sync-settings-body { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; padding: 8px 0 4px; }
+.compact-general .data-safety-password { display: grid; grid-template-columns: max-content 240px; align-items: center; gap: 12px; font-size: 12px; font-weight: 400; }
+.compact-general .data-safety-password input { width: 240px; min-width: 0; min-height: 36px; }
+.settings-about { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--line); min-height: 42px; color: var(--muted); font-size: 11px; }
+.settings-about strong { color: var(--ink); font-size: 12px; font-weight: 600; }
+.settings-about button { min-height: 30px; padding: 5px 8px; }
+.compact-general .compact-icon { width: 30px; height: 30px; min-height: 30px; padding: 0; flex: none; }
+.settings-about .about-trigger { background: transparent; border-color: transparent; color: var(--muted); font-size: 11px; }
+.settings-about .is-available { color: var(--accent-ink); }
+.settings-about .is-error { color: var(--danger); }
+.settings-about .data-safety-feedback { font-size: 11px; }
.settings-tasks-panel { gap: 12px; }
.analysis-settings-form { display: grid; gap: 14px; }
.analysis-settings-form label { display: grid; gap: 6px; color: var(--muted); font-size: 11px; font-weight: 700; }
@@ -1227,8 +1242,6 @@ details:not([open]) > .selection-menu-panel { display: none; }
.brand > div { display: grid; min-width: 0; gap: 1px; }
.brand-wordmark { overflow: visible; font-size: 14px; line-height: 17px; text-overflow: clip; white-space: nowrap; }
.brand .product-brand-tagline { overflow: visible; color: var(--muted); font-size: 10px; font-weight: 550; line-height: 13px; letter-spacing: -.01em; text-overflow: clip; white-space: nowrap; }
-.library-name-note { grid-column: 1 / -1; margin: -2px 0 4px; color: var(--muted); font-size: 10px; line-height: 1.45; }
-.settings-brand-slogan { margin: 0 0 10px; color: var(--ink); font-size: 12px; font-weight: 750; }
.global-search input { padding-inline: 14px; background: var(--input); }
.top-actions { align-items: center; gap: 6px; }
.top-actions > button, .top-actions .package-menu > summary { min-height: 36px; padding: 7px 11px; }
@@ -1263,15 +1276,7 @@ details:not([open]) > .selection-menu-panel { display: none; }
.data-safety-header { min-height: 64px; padding: 13px 16px; }
.data-safety-body { gap: 14px; padding: 18px; }
.data-safety-summary { border-radius: 6px; background: var(--raised); }
-.share-package-import { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 16px; border: 1px solid var(--line); border-radius: 6px; padding: 14px; background: var(--raised); box-shadow: none; }
-.share-package-import > div { display: grid; gap: 3px; }
-.share-package-import span { color: var(--muted); font-size: 11px; line-height: 1.5; }
-.share-package-import button { min-width: 96px; }
-.settings-dialog { display: grid; grid-template-rows: 64px minmax(0, 1fr); width: min(1040px, calc(100vw - 40px)); height: min(780px, calc(100dvh - 40px)); max-height: none; overflow: hidden; }
-.settings-dialog .package-preferences-body { grid-template-columns: repeat(3, minmax(0, 1fr)); align-items: start; gap: 12px; }
-.settings-dialog .package-preferences-body > label { grid-template-columns: 1fr; align-content: start; }
-.settings-dialog .library-storage-settings { grid-column: 1 / -1; grid-template-columns: 1fr 1fr; gap: 12px; padding: 16px 0 0; }
-.settings-dialog .library-storage-settings > div { grid-column: 1 / -1; display: flex; }
+.settings-dialog { display: grid; grid-template-rows: 64px minmax(0, 1fr); width: min(880px, calc(100vw - 40px)); height: min(680px, calc(100dvh - 40px)); max-height: none; overflow: hidden; }
.manager-dialog { display: grid; grid-template-columns: 184px minmax(0, 1fr); grid-template-rows: 64px minmax(0, 1fr); width: min(1040px, calc(100vw - 40px)); }
.manager-header { grid-column: 1 / -1; min-height: 64px; padding: 12px 16px; }
@@ -1357,12 +1362,8 @@ details:not([open]) > .selection-menu-panel { display: none; }
.manager-tabs button[aria-selected="true"]::after { inset: auto 0 -1px; width: auto; height: 1px; }
.manager-panel { height: calc(100% - 112px); padding: 18px 12px 42px; }
.settings-tabs { overflow-x: auto; }
- .settings-dialog .package-preferences-body { grid-template-columns: 1fr; }
- .settings-dialog .library-storage-settings { grid-column: auto; grid-template-columns: 1fr; }
.import-source { grid-template-columns: 1fr; }
.import-source > .import-last-job { grid-column: auto; }
- .share-package-import { grid-template-columns: 1fr; }
- .share-package-import button { justify-self: start; }
.detail-drawer { transform: translateY(8px); }
.detail-drawer.open { transform: translateY(0); }
.detail-drawer.detail-sidebar-mode { inset: 0; width: 100vw; min-width: 0; max-width: none; border-left: 0; }
@@ -1432,3 +1433,19 @@ details:not([open]) > .selection-menu-panel { display: none; }
.platform-playback-fallback:not(.has-poster) .platform-link-actions { justify-content: center; }
.media-playback-error { padding: 16px; margin: 0; color: var(--ink); background: var(--raised); }
.detail-video-wrap.has-playback-error .detail-video { display: none; }
+
+@media (max-width: 680px) {
+ .appearance-grid { grid-template-columns: 1fr; gap: 8px; }
+ .appearance-grid label { grid-template-columns: 92px minmax(0, 1fr); align-items: center; }
+ .setting-row { grid-template-columns: 92px minmax(0, 1fr) auto; gap: 8px; }
+ .compact-general .sync-settings-body { gap: 8px; }
+ .compact-general .data-safety-password { flex: 1; grid-template-columns: max-content minmax(0, 1fr); gap: 8px; min-width: 0; }
+ .compact-general .data-safety-password span { flex: none; }
+ .compact-general .data-safety-password input { width: 100%; }
+ .compact-general .sync-settings-body button { padding: 7px 8px; font-size: 11px; }
+}
+
+@media (min-width: 681px) {
+ .settings-dialog { --settings-top: max(20px, calc((100dvh - 680px) / 2)); inset: var(--settings-top) 0 auto; margin: 0 auto; max-height: calc(100dvh - var(--settings-top) - 20px); }
+ .settings-dialog:has(.compact-general:not([hidden])) { height: auto; }
+}
diff --git a/library.html b/library.html
index fe3b0f7..2e182f9 100644
--- a/library.html
+++ b/library.html
@@ -286,86 +286,54 @@
<button type="button" data-settings-tab="rules" aria-selected="false" data-i18n="分析与创作规则">分析与创作规则</button>
<button type="button" data-settings-tab="tasks" aria-selected="false" data-i18n="任务与维护">任务与维护</button>
</nav>
- <section id="settings-general-panel" class="settings-panel package-preferences-body" data-settings-panel="general">
- <label><span data-i18n="界面语言">界面语言</span><select id="ui-locale"><option value="system" data-i18n="跟随浏览器">跟随浏览器</option><option value="zh-CN" data-i18n="中文">中文</option><option value="en">English</option></select></label>
- <label><span data-i18n="主题">主题</span><select id="ui-theme"><option value="system" data-i18n="跟随系统">跟随系统</option><option value="light" data-i18n="浅色">浅色</option><option value="dark" data-i18n="深色">深色</option></select></label>
- <label><span data-i18n="动态效果">动态效果</span><select id="ui-motion"><option value="system" data-i18n="跟随系统">跟随系统</option><option value="reduced" data-i18n="减少动态效果">减少动态效果</option></select></label>
- <section class="library-storage-settings">
- <label><span data-i18n="资料库名称">资料库名称</span><input id="library-name-setting" autocomplete="off" /></label>
- <p class="library-name-note" data-i18n="资料库名称用于工作空间和导出文件,不会改变 PromptDirector 品牌名称。">资料库名称用于工作空间和导出文件,不会改变 PromptDirector 品牌名称。</p>
- <label><span data-i18n="分享包下载路径">分享包下载路径</span><input id="export-path-setting" autocomplete="off" /></label>
- <div><button id="save-library-settings" class="button-secondary" type="button" disabled data-i18n="保存设置">保存设置</button></div>
+ <section id="settings-general-panel" class="settings-panel compact-general" data-settings-panel="general">
+ <section class="setting-section appearance-grid">
+ <label><span data-i18n="界面语言">界面语言</span><select id="ui-locale"><option value="system" data-i18n="跟随浏览器">跟随浏览器</option><option value="zh-CN" data-i18n="中文">中文</option><option value="en">English</option></select></label>
+ <label><span data-i18n="主题">主题</span><select id="ui-theme"><option value="system" data-i18n="跟随系统">跟随系统</option><option value="light" data-i18n="浅色">浅色</option><option value="dark" data-i18n="深色">深色</option></select></label>
+ <label><span data-i18n="动态效果">动态效果</span><select id="ui-motion"><option value="system" data-i18n="跟随系统">跟随系统</option><option value="reduced" data-i18n="减少动态效果">减少动态效果</option></select></label>
</section>
- <section class="settings-general-section capture-permission-settings">
- <div class="section-heading section-heading-tight"><div><h3 data-i18n="采集权限">采集权限</h3><p data-i18n="仅在你主动截图、采集网页或提取剪贴板时使用。">仅在你主动截图、采集网页或提取剪贴板时使用。</p></div></div>
+ <section class="setting-section">
+ <div class="setting-section-heading"><h3 data-i18n="资料库">资料库</h3></div>
+ <div class="setting-row"><label for="library-name-setting" data-i18n="资料库名称">资料库名称</label><div class="field-span"><input id="library-name-setting" autocomplete="off" /></div></div>
+ <div class="setting-row"><label for="export-path-setting" data-i18n="分享包下载路径">分享包下载路径</label><input id="export-path-setting" autocomplete="off" /><button id="save-library-settings" class="icon-button compact-icon" type="button" disabled aria-label="保存设置" data-i18n-aria-label="保存设置" title="保存设置" data-i18n-title="保存设置"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-save"></use></svg></button></div>
+ <p id="library-settings-feedback" class="data-safety-feedback" role="status" aria-live="polite"></p>
+ </section>
+ <section class="setting-section capture-permission-settings">
+ <div class="setting-section-heading"><h3 data-i18n="采集权限">采集权限</h3></div>
<div class="capture-permission-list">
- <div class="capture-permission-row">
- <div><strong data-i18n="网页采集与截图">网页采集与截图</strong><span id="capture-web-permission-status" data-i18n="正在检查…">正在检查…</span></div>
- <button id="revoke-capture-web-permission" class="button-secondary" type="button" disabled data-i18n="撤销">撤销</button>
- </div>
- <div class="capture-permission-row">
- <div><strong data-i18n="剪贴板提取">剪贴板提取</strong><span id="capture-clipboard-permission-status" data-i18n="正在检查…">正在检查…</span></div>
- <button id="revoke-capture-clipboard-permission" class="button-secondary" type="button" disabled data-i18n="撤销">撤销</button>
- </div>
+ <div class="capture-permission-row"><strong data-i18n="网页采集与截图">网页采集与截图</strong><span id="capture-web-permission-status" data-i18n="正在检查…">正在检查…</span><button id="revoke-capture-web-permission" class="button-secondary" type="button" disabled data-i18n="撤销">撤销</button></div>
+ <div class="capture-permission-row"><strong data-i18n="剪贴板提取">剪贴板提取</strong><span id="capture-clipboard-permission-status" data-i18n="正在检查…">正在检查…</span><button id="revoke-capture-clipboard-permission" class="button-secondary" type="button" disabled data-i18n="撤销">撤销</button></div>
</div>
<p id="capture-permission-settings-feedback" class="data-safety-feedback" role="status" aria-live="polite"></p>
- <p class="data-safety-note" data-i18n="这里不会读取剪贴板。撤销后,下次主动使用对应采集功能时会重新说明用途并由你确认。">这里不会读取剪贴板。撤销后,下次主动使用对应采集功能时会重新说明用途并由你确认。</p>
</section>
- <section id="data-safety-dialog" class="settings-general-section settings-data-safety">
- <div class="section-heading section-heading-tight"><div><h3 data-i18n="备份与同步">备份与同步</h3><p data-i18n="备份、恢复或连接自己的同步文件夹。">备份、恢复或连接自己的同步文件夹。</p></div></div>
- <section class="data-safety-summary">
- <strong id="data-safety-count" data-i18n="0 个案例 · 0 张图片">0 个案例 · 0 张图片</strong>
- <span id="data-safety-status" data-i18n="尚未连接同步文件夹">尚未连接同步文件夹</span>
- </section>
+ <section id="data-safety-dialog" class="setting-section settings-data-safety">
+ <div class="setting-section-heading data-heading"><h3 data-i18n="备份与同步">备份与同步</h3><small id="data-safety-count"></small><div class="data-safety-primary-actions">
+ <button id="create-folder-backup" class="button-secondary" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-download"></use></svg><span data-i18n="备份资料库">备份资料库</span></button>
+ <button id="restore-folder-backup" class="button-secondary" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-upload"></use></svg><span data-i18n="恢复资料库">恢复资料库</span></button>
+ </div></div>
<p id="data-safety-feedback" class="data-safety-feedback" role="status" aria-live="polite"></p>
- <section class="share-package-import">
- <div><strong data-i18n="导入分享包">导入分享包</strong><span data-i18n="添加别人分享的案例或项目,不覆盖现有资料">添加别人分享的案例或项目,不覆盖现有资料</span></div>
- <button id="import-library-package" class="button-secondary" type="button" data-i18n="选择 ZIP">选择 ZIP</button>
- <input id="library-package-file" type="file" accept=".zip,application/zip" multiple hidden />
- </section>
- <div class="data-safety-primary-actions">
- <button id="create-folder-backup" type="button" data-i18n="备份资料库">备份资料库</button>
- <button id="restore-folder-backup" class="button-secondary" type="button" data-i18n="恢复资料库">恢复资料库</button>
- </div>
- <div class="data-safety-secondary-actions">
- <button id="restore-library-replacement-point" class="quiet-danger" type="button" hidden data-i18n="回退上次精确恢复">回退上次精确恢复</button>
- </div>
- <p class="data-safety-note" data-i18n="备份会把案例和本地媒体逐项写入资料夹;恢复默认安全合并。只有完整备份可在明确选择并建立回退点后精确替换。">备份会把案例和本地媒体逐项写入资料夹;恢复默认安全合并。只有完整备份可在明确选择并建立回退点后精确替换。</p>
+ <div class="share-package-import"><span data-i18n="导入分享包">导入分享包</span><button id="import-library-package" class="button-secondary" type="button" data-i18n="选择 ZIP">选择 ZIP</button><input id="library-package-file" type="file" accept=".zip,application/zip" multiple hidden /></div>
+ <button id="restore-library-replacement-point" class="quiet-danger" type="button" hidden data-i18n="回退上次精确恢复">回退上次精确恢复</button>
<details id="sync-settings" class="sync-settings">
- <summary data-i18n="跨设备同步">跨设备同步</summary>
+ <summary><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-chevron-right"></use></svg><span data-i18n="跨设备同步">跨设备同步</span><small id="data-safety-status"></small></summary>
<div class="sync-settings-body">
- <p class="data-safety-note" data-i18n="同一台电脑可选择普通本地文件夹;跨设备请选择已登录的 iCloud Drive、Dropbox 或 OneDrive 文件夹。两端选择同一个父文件夹并使用相同密码。插件会在其中创建 PromptDirector-Sync,请勿手动修改。">同一台电脑可选择普通本地文件夹;跨设备请选择已登录的 iCloud Drive、Dropbox 或 OneDrive 文件夹。两端选择同一个父文件夹并使用相同密码。插件会在其中创建 PromptDirector-Sync,请勿手动修改。</p>
- <p class="data-safety-note" data-i18n="连接和解锁只验证文件夹与密码,不会读取、合并或上传资料。只有你再次确认“立即同步”后,才会执行一次同步。">连接和解锁只验证文件夹与密码,不会读取、合并或上传资料。只有你再次确认“立即同步”后,才会执行一次同步。</p>
<label id="data-safety-password" class="data-safety-password"><span data-i18n="同步密码">同步密码</span><input id="sync-password" type="password" minlength="8" autocomplete="off" placeholder="至少 8 个字符" data-i18n-placeholder="至少 8 个字符" /></label>
- <div class="data-safety-secondary-actions">
- <button id="connect-sync-folder" type="button" data-i18n="连接同步文件夹">连接同步文件夹</button>
- <button id="unlock-sync-vault" type="button" data-i18n="解锁同步库">解锁同步库</button>
- <button id="sync-now" type="button" data-i18n="立即同步">立即同步</button>
- <button id="cancel-sync" class="button-secondary" type="button" hidden data-i18n="停止同步">停止同步</button>
- <button id="disconnect-sync-folder" class="quiet-danger" type="button" data-i18n="断开同步">断开同步</button>
- </div>
+ <button id="connect-sync-folder" class="button-secondary" type="button" data-i18n="连接同步文件夹">连接同步文件夹</button>
+ <button id="unlock-sync-vault" class="button-secondary" type="button" hidden data-i18n="解锁同步库">解锁同步库</button>
+ <button id="sync-now" class="" type="button" hidden data-i18n="立即同步">立即同步</button>
+ <button id="cancel-sync" class="button-secondary" type="button" hidden data-i18n="停止同步">停止同步</button>
+ <button id="disconnect-sync-folder" class="quiet-danger" type="button" hidden data-i18n="断开同步">断开同步</button>
</div>
</details>
</section>
<footer class="settings-about">
- <p class="settings-brand-slogan" data-i18n="提示词导演,你的视觉创作私人灵感库。">提示词导演,你的视觉创作私人灵感库。</p>
- <div class="settings-about-heading">
- <div><strong id="about-version">PromptDirector</strong><span id="update-channel" data-i18n="正在确认安装方式…">正在确认安装方式…</span></div>
- <strong id="update-status" class="update-status-badge" data-i18n="正在检查">正在检查</strong>
- </div>
- <div class="settings-update-details">
- <span id="update-checked-at" data-i18n="最近检查:—">最近检查:—</span>
- <span id="update-available-version" data-i18n="可用版本:—">可用版本:—</span>
- </div>
- <p id="update-explanation" class="settings-update-explanation" data-i18n="商店版由 Chrome 自动更新;本地开发版可安全重载当前目录。">商店版由 Chrome 自动更新;本地开发版可安全重载当前目录。</p>
- <div class="settings-update-actions">
- <button id="check-extension-update" class="button-secondary" type="button" data-i18n="检查更新">检查更新</button>
- <button id="apply-extension-update" type="button" hidden></button>
- <a id="update-release-link" class="button-primary update-download-action" href="https://github.com/wchao6891/PromptDirector/releases" target="_blank" rel="noopener noreferrer" hidden data-i18n="下载新版本">下载新版本</a>
- </div>
+ <input id="local-extension-package" type="file" accept=".zip,application/zip" hidden />
+ <strong id="about-version">PromptDirector</strong>
+ <span id="update-status" role="status"></span>
+ <button id="check-extension-update" class="icon-button compact-icon" type="button" aria-label="检查更新" data-i18n-aria-label="检查更新" title="检查更新" data-i18n-title="检查更新"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-refresh-cw"></use></svg></button>
+ <button id="apply-extension-update" type="button" hidden></button>
+ <button id="open-about" class="about-trigger" type="button" data-i18n="关于">关于</button>
<p id="update-feedback" class="data-safety-feedback" role="status" aria-live="polite"></p>
- <span data-i18n="免费、开源、本地优先 · Apache-2.0">免费、开源、本地优先 · Apache-2.0</span>
- <a class="source-link" href="https://github.com/wchao6891/PromptDirector" target="_blank" rel="noopener noreferrer">github.com/wchao6891/PromptDirector</a>
</footer>
</section>
<section id="settings-tasks-panel" class="settings-panel settings-tasks-panel" data-settings-panel="tasks" hidden>
diff --git a/library.js b/library.js
index 4f03f84..ff3fe0e 100644
--- a/library.js
+++ b/library.js
@@ -227,7 +227,7 @@ const elements = Object.fromEntries([
"add-quick-note", "organize-detail-tags", "organize-detail-status", "pause-analysis-batch", "pause-library-maintenance", "preview-analysis-batch", "preview-analysis-reanalyze", "preview-reanalyze", "reanalyze-preview", "result-count", "resume-analysis-batch", "resume-library-maintenance", "retry-analysis-failures", "retry-library-maintenance", "start-analysis-reanalyze",
"project-selection-actions", "project-selection-cancel", "project-selection-clear", "project-selection-count", "project-selection-save", "project-selection-select-all", "project-selection-select-filtered", "project-selection-title", "project-order-status", "restore-analysis-default", "search-input", "share-bar", "share-cancel", "share-count", "share-export", "start-analysis-batch", "start-compose", "toggle-filters", "undo-analysis-batch", "undo-facet", "vocabulary-facet", "workspace-library", "workspace-unassigned",
"share-dialog", "share-dialog-close", "share-dialog-title", "share-dialog-meta", "share-dialog-options", "share-dialog-export", "share-dialog-submit", "share-dialog-disclosure", "share-dialog-result", "share-dialog-result-text", "share-dialog-show-files", "share-dialog-open-form",
- "add-menu", "export-path-setting", "media-file", "media-folder", "library-name-setting", "save-library-settings", "select-cases", "selection-select-filtered", "selection-clear", "selection-label-input", "selection-add-labels", "selection-add-project", "selection-move-project", "selection-remove-project", "selection-new-project", "selection-combine", "selection-analyze", "selection-video-analyze", "selection-project-impact", "selection-project-target", "selection-trash", "open-settings", "settings-dialog", "settings-close", "settings-update-badge", "update-channel", "update-status", "update-checked-at", "update-available-version", "update-explanation", "check-extension-update", "apply-extension-update", "update-release-link", "update-feedback",
+ "add-menu", "export-path-setting", "media-file", "media-folder", "library-name-setting", "save-library-settings", "select-cases", "selection-select-filtered", "selection-clear", "selection-label-input", "selection-add-labels", "selection-add-project", "selection-move-project", "selection-remove-project", "selection-new-project", "selection-combine", "selection-analyze", "selection-video-analyze", "selection-project-impact", "selection-project-target", "selection-trash", "open-settings", "settings-dialog", "settings-close", "settings-update-badge", "open-about", "local-extension-package", "library-settings-feedback", "update-status", "check-extension-update", "apply-extension-update", "update-feedback",
"project-section", "project-root-drop", "manage-project-order", "selection-simple-actions", "selection-selected-actions", "show-analysis-diagnostics", "ui-locale", "ui-theme", "ui-motion", "vocabulary-tree",
"vision-instructions-en", "vision-instructions-zh", "vision-protocol", "vision-settings-form", "vision-settings-status", "restore-vision-default",
"video-instructions-en", "video-instructions-zh", "video-settings-form", "video-settings-status", "restore-video-default", "video-protocol",
@@ -387,6 +387,8 @@ let importDragDepth = 0;
let externalLibraryRefreshTimer = 0;
let externalLibraryRefreshPending = false;
let extensionUpdateStatus = null;
+let localUpgradeFeedback = "";
+let localUpgradeCleanupRequired = false;
const importTagEditor = createTagEditor({
placeholder: "例如:风格不错,很喜欢",
@@ -458,7 +460,15 @@ elements.uiTheme.value = uiPreferences.theme;
elements.uiMotion.value = uiPreferences.motion;
elements.showAnalysisDiagnostics.checked = uiPreferences.analysisDiagnostics;
elements.aboutVersion.textContent = `PromptDirector ${chrome.runtime.getManifest().version}`;
-void refreshExtensionUpdateStatus();
+void refreshExtensionUpdateStatus().then(async () => {
+ if (extensionUpdateStatus?.channel !== "development") return;
+ try {
+ const result = await (await import("./local-extension-upgrade-ui.js")).runningUpgradeFeedback();
+ localUpgradeFeedback = result.message;
+ localUpgradeCleanupRequired = result.cleanupRequired;
+ renderExtensionUpdateStatus(extensionUpdateStatus);
+ } catch (error) { showUpdateFeedback(error.message, true); }
+});
await refreshLibrary();
await openRequestedLibraryTarget();
await resumeImportJob();
@@ -627,6 +637,14 @@ function bindEvents() {
elements.openSettings.addEventListener("click", () => openSettingsDialog("general"));
elements.settingsClose.addEventListener("click", () => elements.settingsDialog.close());
elements.checkExtensionUpdate.addEventListener("click", checkExtensionUpdate);
+ elements.openAbout.addEventListener("click", showExtensionAbout);
+ elements.localExtensionPackage.addEventListener("change", async () => {
+ const archive = elements.localExtensionPackage.files?.[0];
+ elements.localExtensionPackage.value = "";
+ if (!archive) return;
+ try { await (await import("./local-extension-upgrade-ui.js")).openLocalUpgrade(extensionUpdateStatus, archive); }
+ catch (error) { showUpdateFeedback(error.message, true); }
+ });
elements.applyExtensionUpdate.addEventListener("click", applyExtensionUpdate);
elements.revokeCaptureWebPermission.addEventListener("click", () => void revokeCapturePermission("web"));
elements.revokeCaptureClipboardPermission.addEventListener("click", () => void revokeCapturePermission("clipboard"));
@@ -3280,14 +3298,26 @@ async function checkExtensionUpdate() {
}
async function applyExtensionUpdate() {
+ if (localUpgradeCleanupRequired) {
+ elements.applyExtensionUpdate.disabled = true;
+ try {
+ if (await (await import("./local-extension-upgrade-ui.js")).finishLocalUpgrade()) {
+ localUpgradeCleanupRequired = false;
+ localUpgradeFeedback = t("已清理升级临时文件");
+ renderExtensionUpdateStatus(extensionUpdateStatus);
+ }
+ } catch (error) { showUpdateFeedback(error.message, true); }
+ finally { elements.applyExtensionUpdate.disabled = false; }
+ return;
+ }
const status = extensionUpdateStatus;
- if (!status?.canApply || !status.applyBehavior) return;
- const development = status.applyBehavior === "reload_development_directory";
- const confirmed = await confirmAppAction(development ? {
- title: "安全重载当前目录?",
- description: "当前资料库页面会关闭,Chrome 会重新载入你已经选择的本地目录。不会下载或覆盖代码,本地案例和素材不会丢失。",
- confirmLabel: "安全重载"
- } : {
+ if (!status?.canApply) return;
+ if (status.channel === "development") {
+ try { await (await import("./local-extension-upgrade-ui.js")).openLocalUpgrade(status); }
+ catch (error) { showUpdateFeedback(error.message, true); }
+ return;
+ }
+ const confirmed = await confirmAppAction({
title: "立即应用更新并重启 PromptDirector?",
description: "当前资料库页面会关闭,但本地案例和素材不会丢失。",
confirmLabel: "应用并重启"
@@ -3295,11 +3325,10 @@ async function applyExtensionUpdate() {
if (!confirmed) return;
elements.applyExtensionUpdate.disabled = true;
elements.applyExtensionUpdate.setAttribute("aria-busy", "true");
- showUpdateFeedback(development ? "正在安全重载当前目录…" : "正在应用更新并重启…");
+ showUpdateFeedback("正在应用更新并重启…");
try {
const response = await chrome.runtime.sendMessage({ type: "APPLY_EXTENSION_UPDATE" });
- if (response?.status) renderExtensionUpdateStatus(response.status);
- if (!response?.ok) throw new Error(response?.status?.lastError || response?.message || "无法应用更新");
+ if (!response?.ok) throw new Error(response?.message || "无法应用更新");
} catch (error) {
showUpdateFeedback(error?.message || "无法应用更新", true);
elements.applyExtensionUpdate.disabled = false;
@@ -3310,85 +3339,58 @@ async function applyExtensionUpdate() {
function renderExtensionUpdateStatus(nextStatus, fallbackError = "") {
if (nextStatus) extensionUpdateStatus = { ...(extensionUpdateStatus ?? {}), ...nextStatus };
const status = extensionUpdateStatus;
- const currentVersion = status?.currentVersion || chrome.runtime.getManifest().version;
- elements.aboutVersion.textContent = `PromptDirector ${currentVersion}`;
- if (!status) {
- elements.updateChannel.textContent = t("安装方式暂不可用");
- elements.updateStatus.textContent = t(fallbackError ? "状态不可用" : "正在检查");
- elements.updateStatus.className = `update-status-badge${fallbackError ? " is-error" : ""}`;
- elements.updateCheckedAt.textContent = t("最近检查:—");
- elements.updateAvailableVersion.textContent = t("可用版本:—");
- elements.updateExplanation.textContent = t("重新打开设置时会再次读取更新状态。");
- showUpdateFeedback(translateUiMessage(fallbackError), Boolean(fallbackError));
- return;
- }
-
- const development = status.channel === "development";
- elements.updateChannel.textContent = t(development ? "本地开发版 · 手动替换代码" : "商店版 · Chrome 自动更新");
- const updateVersion = status.pendingVersion || status.latestVersion || "—";
- elements.updateCheckedAt.textContent = t("最近检查:{time}", { time: formatUpdateCheckTime(status.checkedAt) });
- elements.updateAvailableVersion.textContent = t("可用版本:{version}", { version: updateVersion });
-
- const display = updateStatusDisplay(status);
- elements.updateStatus.textContent = t(display.label);
- elements.updateStatus.className = `update-status-badge ${display.className}`.trim();
- elements.updateExplanation.textContent = t(updateExplanation(status));
-
- const releaseUrl = development && status.updateAvailable ? safeHttpUrl(status.releaseUrl) : "";
- elements.updateReleaseLink.hidden = !releaseUrl;
- if (releaseUrl) elements.updateReleaseLink.href = releaseUrl;
- else elements.updateReleaseLink.removeAttribute("href");
-
- elements.applyExtensionUpdate.hidden = !status.canApply;
- elements.applyExtensionUpdate.disabled = false;
- elements.applyExtensionUpdate.removeAttribute("aria-busy");
- elements.applyExtensionUpdate.classList.toggle("button-secondary", development);
- elements.applyExtensionUpdate.textContent = t(status.applyBehavior === "reload_development_directory"
- ? "重新载入目录"
- : "应用更新并重启");
-
- const hasUpdate = Boolean(status.updateAvailable);
+ elements.aboutVersion.textContent = `PromptDirector ${status?.currentVersion || chrome.runtime.getManifest().version}`;
+ const development = status?.channel === "development";
+ const hasUpdate = Boolean(status?.updateAvailable);
+ elements.updateStatus.textContent = hasUpdate ? t("发现新版本") : status?.channel === "store" ? t("自动更新") : "";
+ elements.updateStatus.className = hasUpdate ? "is-available" : "";
+ elements.checkExtensionUpdate.hidden = status?.channel === "store";
+ elements.applyExtensionUpdate.hidden = !status?.canApply && !localUpgradeCleanupRequired;
+ elements.applyExtensionUpdate.textContent = t(localUpgradeCleanupRequired ? "清理升级临时文件" : development ? "升级本地版" : "应用更新并重启");
elements.settingsUpdateBadge.hidden = !hasUpdate;
elements.openSettings.setAttribute("aria-label", t(hasUpdate ? "设置,有可用更新" : "设置"));
- elements.openSettings.title = hasUpdate ? t("设置 · {status}", { status: t(display.label) }) : t("设置");
- showUpdateFeedback(translateUiMessage(status.lastError || ""), Boolean(status.lastError));
+ elements.openSettings.title = t(hasUpdate ? "设置,有可用更新" : "设置");
+ showUpdateFeedback(status?.lastError || fallbackError || localUpgradeFeedback, Boolean(status?.lastError || fallbackError));
}
-function updateStatusDisplay(status) {
- if (status.updateKind === "store_downloaded") return { label: "已下载,可应用", className: "is-available" };
- if (status.updateKind === "development_release" || status.updateAvailable) return { label: "发现新版本", className: "is-available" };
- if (status.checkStatus === "error") return { label: "检查失败", className: "is-error" };
- if (status.checkStatus === "no_update") return { label: "已是最新", className: "is-current" };
- if (status.checkStatus === "throttled") return { label: "刚刚检查过", className: "is-current" };
- return { label: "自动更新", className: "" };
-}
-
-function updateExplanation(status) {
- if (status.channel === "development") {
- return status.updateAvailable
- ? "发现新的 GitHub Release。扩展无法自行覆盖本机目录;请从链接下载并替换代码,再安全重载。固定 ID 升级无需导出、导入案例。"
- : "本地开发版不会被扩展自行覆盖。安全重载只会重新载入当前目录,不会下载或安装新版本;固定 ID 升级无需导出、导入案例。";
- }
- return status.updateKind === "store_downloaded"
- ? "新版本已由 Chrome 下载。立即应用会关闭当前资料库页面并重启扩展;案例和素材不会丢失。"
- : "商店版由 Chrome 自动更新,无需反复下载插件;更新下载完成后也可以在这里立即应用。";
+async function showExtensionAbout() {
+ const manifest = chrome.runtime.getManifest();
+ const status = extensionUpdateStatus;
+ const result = await showAppDialog({
+ title: "关于 PromptDirector",
+ confirmLabel: "完成",
+ renderBody: ({ body }) => {
+ body.append(rawTextEl("p", "", `PromptDirector ${manifest.version}`));
+ body.append(rawTextEl("p", "", t("免费、开源、本地优先 · Apache-2.0")));
+ body.append(rawTextEl("p", "", t(status?.channel === "development" ? "本地版" : status?.channel === "store" ? "商店版 · Chrome 自动更新" : "安装方式暂不可用")));
+ if (status?.checkedAt) body.append(rawTextEl("p", "", t("最近检查:{time}", { time: new Date(status.checkedAt).toLocaleString() })));
+ const link = document.createElement("a");
+ link.textContent = t("查看源码");
+ link.href = safeHttpUrl(manifest.homepage_url);
+ link.target = "_blank";
+ link.rel = "noopener noreferrer";
+ body.append(link);
+ if (status?.channel === "development") {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = "button-secondary";
+ button.textContent = t("选择已下载的更新包");
+ button.addEventListener("click", () => { button.closest("form").requestSubmit(); elements.localExtensionPackage.click(); });
+ body.append(button);
+ }
+ }
+ });
+ return result;
}
function updateCheckFeedback(status) {
- if (status?.updateAvailable) return t(status.channel === "development" ? "发现新版本,可打开 Release 下载。" : "新版本已下载,可以立即应用。");
+ if (status?.updateAvailable) return "";
if (status?.checkStatus === "throttled") return t("刚刚检查过,已保留最近结果。");
return t("已是最新版本。");
}
-function formatUpdateCheckTime(value) {
- if (!value) return t("尚未检查");
- const date = new Date(value);
- if (Number.isNaN(date.getTime())) return t("尚未检查");
- return date.toLocaleString(currentLocale() === "en" ? "en" : "zh-CN");
-}
-
function showUpdateFeedback(message, isError = false) {
- elements.updateFeedback.textContent = message || "";
+ elements.updateFeedback.textContent = translateUiMessage(message || "");
elements.updateFeedback.classList.toggle("error", isError);
}
@@ -10213,6 +10215,7 @@ function renderReanalysisPreview() {
}
function updateLibrarySettingsSaveState() {
+ elements.librarySettingsFeedback.textContent = "";
const titleChanged = elements.libraryNameSetting.value !== (elements.libraryNameSetting.dataset.savedValue ?? "");
const pathChanged = elements.exportPathSetting.value !== (elements.exportPathSetting.dataset.savedValue ?? "");
elements.saveLibrarySettings.disabled = !(titleChanged || pathChanged);
@@ -10224,20 +10227,26 @@ async function saveLibrarySettings() {
elements.libraryNameSetting.dataset.storedValue,
currentLocale()
);
- const response = await perform(elements.saveLibrarySettings, {
- type: "UPDATE_SETTINGS",
- settings: {
- libraryTitle,
- outputPath: elements.exportPathSetting.value
- }
- }, false);
- if (!response?.ok) return;
+ const button = elements.saveLibrarySettings;
+ button.disabled = true;
+ let response;
+ try {
+ response = await chrome.runtime.sendMessage({ type: "UPDATE_SETTINGS", settings: { libraryTitle, outputPath: elements.exportPathSetting.value } });
+ if (!response?.ok) throw new Error(response?.message || "保存失败");
+ elements.librarySettingsFeedback.textContent = t("已保存");
+ elements.librarySettingsFeedback.classList.remove("error");
+ } catch (error) {
+ updateLibrarySettingsSaveState();
+ elements.librarySettingsFeedback.textContent = translateUiMessage(error.message);
+ elements.librarySettingsFeedback.classList.add("error");
+ return;
+ }
const displayedLibraryTitle = libraryTitleForLocale(response.settings.libraryTitle, currentLocale());
elements.libraryNameSetting.value = displayedLibraryTitle;
elements.libraryNameSetting.dataset.savedValue = displayedLibraryTitle;
elements.libraryNameSetting.dataset.storedValue = response.settings.libraryTitle || "";
elements.exportPathSetting.dataset.savedValue = elements.exportPathSetting.value;
- updateLibrarySettingsSaveState();
+ button.disabled = true;
}
async function perform(button, message, refresh = true) {
@@ -10581,8 +10590,8 @@ async function renderDataSafetyStatus() {
}
syncStatus = response.syncStatus ?? {};
elements.dataSafetyCount.textContent = currentLocale() === "en"
- ? `${response.entryCount} cases · ${response.mediaCount} media (${response.videoCount} videos)`
- : `${response.entryCount} 个案例 · ${response.mediaCount} 项媒体(${response.videoCount} 个视频)`;
+ ? `${response.entryCount} cases · ${response.mediaCount} media`
+ : `${response.entryCount} 个案例 · ${response.mediaCount} 项媒体`;
elements.dataSafetyStatus.textContent = syncStatusMessage(syncStatus);
const missingLocation = syncStatus.lastErrorCode === SYNC_ERROR_CODES.LOCATION_NOT_FOUND;
const needsFolder = missingLocation || !syncStatus.connected || syncStatus.permission !== "granted";
@@ -10808,18 +10817,18 @@ function localizedImportReportDescription(report) {
}
function syncStatusMessage(status) {
- if (!status.connected) return t("尚未连接同步文件夹");
+ if (!status.connected) return t("未连接");
if (status.permission !== "granted") return t("同步文件夹需要重新授权");
- if (!status.unlocked) return t("同步库已锁定,请输入密码解锁");
+ if (!status.unlocked) return t("待解锁");
if (status.lastErrorCode === SYNC_ERROR_CODES.LOCATION_NOT_FOUND) {
return t("同步文件夹中的文件或目录不存在,请重新选择同步文件夹后再同步");
}
- if (status.active) return status.cancelRequested ? "正在停止本次同步…" : "正在执行一次手动同步…";
+ if (status.active) return t(status.cancelRequested ? "正在停止同步…" : "正在同步…");
if (status.lastError) return status.lastError;
- if (status.state === "canceled") return "上次手动同步已停止,本机未提交的资料没有改变";
- if (status.state === "up-to-date") return "已检查:两端没有变化,没有写入同步文件夹";
- if (status.localDirty) return "本机有尚未同步的变化;只有点击并确认后才会同步";
- if (!status.lastSyncAt) return t("同步库已连接,尚未完成首次同步");
+ if (status.state === "canceled") return t("同步已停止");
+ if (status.state === "up-to-date") return t("已同步");
+ if (status.localDirty) return t("待同步");
+ if (!status.lastSyncAt) return t("已连接");
const date = new Date(status.lastSyncAt);
const formatted = Number.isNaN(date.getTime()) ? status.lastSyncAt : date.toLocaleString(currentLocale() === "en" ? "en" : "zh-CN");
return currentLocale() === "en" ? `Last synced ${formatted}` : `上次成功同步:${formatted}`;
diff --git a/local-extension-upgrade-ui.js b/local-extension-upgrade-ui.js
new file mode 100644
index 0000000..326a75a
--- /dev/null
+++ b/local-extension-upgrade-ui.js
@@ -0,0 +1,127 @@
+import { showAppDialog } from "./ui-dialogs.js";
+import { t } from "./i18n.js";
+import { blobDigest, installLocalUpgrade, localReleasePackageUrl, localUpgradeRecord, prepareLocalUpgrade, RECOVERY_DIRECTORY, verifyRecoveredUpgrade, verifyRunningUpgrade } from "./local-extension-upgrade.js";
+
+let active = false;
+
+export async function openLocalUpgrade(status, archive = null) {
+ if (active) return;
+ if ((await chrome.management.getSelf()).installType !== "development") throw new Error(t("商店版由 Chrome 自动更新"));
+ active = true;
+ try {
+ const pending = await localUpgradeRecord();
+ if (pending) {
+ if (pending.phase !== "preparing" && !await verifyRunningUpgrade(pending, chrome.runtime)) throw new Error(t("上次升级尚未完成,请先处理升级恢复提示"));
+ const cleared = await showAppDialog({
+ title: "清理上次程序恢复副本",
+ description: pending.phase === "preparing" ? "上次准备更新中断,原插件未更改。清理临时程序副本后继续。" : "已确认上次升级成功。允许清理程序恢复副本后继续;不会删除案例。",
+ confirmLabel: "允许并继续",
+ onSubmit: finishLocalUpgrade
+ });
+ if (!cleared) return;
+ }
+ let prepared;
+ const ready = await showAppDialog({
+ title: "升级本地版",
+ description: "只更新插件程序,案例和媒体留在原资料库。升级会重启插件,请先保存正在编辑的内容。",
+ confirmLabel: archive ? "验证更新包" : "下载更新包",
+ pendingLabel: "正在验证更新包…",
+ dismissOnBackdrop: false,
+ onSubmit: async () => {
+ if (archive) prepared = await prepareLocalUpgrade(archive, chrome.runtime);
+ const version = prepared?.manifest.version || status.latestVersion;
+ const releaseUrl = prepared
+ ? `${chrome.runtime.getManifest().homepage_url}/releases/tag/v${version}`
+ : status.releaseUrl;
+ const url = localReleasePackageUrl(chrome.runtime.getManifest(), releaseUrl, version);
+ const response = await fetch(url, { cache: "no-store", credentials: "omit" });
+ if (!response.ok) throw new Error(t("无法下载对应的本地更新包,请稍后重试"));
+ const published = await response.blob();
+ if (archive && await blobDigest(archive) !== await blobDigest(published)) throw new Error(t("所选更新包与官方发布内容不一致,已停止升级"));
+ prepared = await prepareLocalUpgrade(published, chrome.runtime);
+ if (prepared.manifest.version !== version) throw new Error(t("更新包版本与发布版本不一致"));
+ return true;
+ }
+ });
+ if (!ready) return;
+ let writing = false;
+ await showAppDialog({
+ title: t("升级到 {version}", { version: prepared.manifest.version }),
+ description: "请选择 Chrome 当前加载的插件文件夹。无需卸载、备份或导入案例。",
+ confirmLabel: "选择安装文件夹并升级",
+ pendingLabel: "正在核对安装目录…",
+ dismissOnBackdrop: false,
+ onReady: ({ dialog }) => {
+ dialog.addEventListener("cancel", event => {
+ if (writing) { event.preventDefault(); event.stopImmediatePropagation(); }
+ }, { capture: true });
+ },
+ onSubmit: async (_values, controls) => {
+ let root;
+ try { root = await window.showDirectoryPicker({ mode: "readwrite" }); }
+ catch (error) { if (error.name === "AbortError") return false; throw error; }
+ writing = true;
+ const beforeUnload = event => { event.preventDefault(); event.returnValue = ""; };
+ window.addEventListener("beforeunload", beforeUnload);
+ try {
+ await navigator.locks.request("promptdirector-extension-upgrade", { ifAvailable: true }, async lock => {
+ if (!lock) throw new Error(t("另一个页面正在升级,请等待完成"));
+ await installLocalUpgrade(root, prepared, {
+ runtime: chrome.runtime,
+ saveRecord: localUpgradeRecord,
+ onProgress: ({ phase, completed, total }) => {
+ controls.status().textContent = phase === "preparing"
+ ? t("正在准备更新 · {completed} 个程序文件", { completed })
+ : t("正在更新程序 {completed}/{total}", { completed, total });
+ }
+ });
+ controls.status().textContent = t("程序已写入,正在重启验证版本…");
+ chrome.runtime.reload();
+ });
+ } finally {
+ writing = false;
+ window.removeEventListener("beforeunload", beforeUnload);
+ }
+ return true;
+ }
+ });
+ } finally { active = false; }
+}
+
+export async function runningUpgradeFeedback() {
+ const record = await localUpgradeRecord();
+ if (!record) return { message: "", cleanupRequired: false };
+ if (record.phase === "preparing") return { message: t("上次准备更新中断,原插件未更改。清理临时程序副本后继续。"), cleanupRequired: true };
+ if (await verifyRecoveredUpgrade(record, chrome.runtime)) {
+ // The recovery folder may now be the active installation. Never delete it here.
+ await localUpgradeRecord(null);
+ return { message: t("已恢复原版本,案例与媒体仍在原资料库"), cleanupRequired: false };
+ }
+ if (!await verifyRunningUpgrade(record, chrome.runtime)) {
+ return { message: t("上次升级未完成。请在 Chrome 扩展管理中加载安装目录内的 {folder},恢复原版本;无需卸载或导入案例。", { folder: RECOVERY_DIRECTORY }), cleanupRequired: false };
+ }
+ let cleanupRequired = true;
+ if (await record.root.queryPermission({ mode: "readwrite" }) === "granted") {
+ try {
+ await record.root.removeEntry(RECOVERY_DIRECTORY, { recursive: true });
+ await localUpgradeRecord(null);
+ cleanupRequired = false;
+ } catch (error) {
+ console.warn("Upgrade verified; program recovery cleanup pending", error);
+ }
+ }
+ return { message: t("已升级到 {version}", { version: record.targetVersion }), cleanupRequired };
+}
+
+export async function finishLocalUpgrade() {
+ const record = await localUpgradeRecord();
+ if (!record) return true;
+ if (await record.root.requestPermission({ mode: "readwrite" }) !== "granted") return false;
+ if (record.phase !== "preparing" && !await verifyRunningUpgrade(record, chrome.runtime)) {
+ throw new Error(t("上次升级尚未完成,请先处理升级恢复提示"));
+ }
+ try { await record.root.removeEntry(RECOVERY_DIRECTORY, { recursive: true }); }
+ catch (error) { if (error.name !== "NotFoundError") throw error; }
+ await localUpgradeRecord(null);
+ return true;
+}
diff --git a/local-extension-upgrade.js b/local-extension-upgrade.js
new file mode 100644
index 0000000..4e7216e
--- /dev/null
+++ b/local-extension-upgrade.js
@@ -0,0 +1,200 @@
+import { readZipBlob } from "./zip.js";
+import { compareExtensionVersions, githubLatestReleaseUrl } from "./extension-update.js";
+
+export const RECOVERY_DIRECTORY = "PromptDirector-Update-Recovery";
+const RECORD_KEY = "pending";
+
+export function isExtensionProgramPath(path) {
+ if (path.split("/").some(part => !part || part === "." || part === "..") || /[\\\u0000:]/u.test(path)) return false;
+ return /^(?:[^/]+\.(?:js|css|html)|manifest\.json|LICENSE|NOTICE|THIRD_PARTY_NOTICES\.md)$/u.test(path)
+ || /^assets\/(?:ui-icons\.svg|icons\/(?:icon-source\.svg|icon-(?:16|32|48|128)\.png))$/u.test(path)
+ || /^_locales\/[^/]+\/messages\.json$/u.test(path)
+ || /^vendor\/(?:pdfjs|document-ingestion)\/.+/u.test(path);
+}
+
+export async function extensionIdForKey(key) {
+ if (typeof key !== "string" || !key.trim()) throw new Error("请选择 FIXED-ID-DEV 本地安装包");
+ const bytes = Uint8Array.from(atob(key.replace(/\s/gu, "")), char => char.charCodeAt(0));
+ const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
+ return [...hash.slice(0, 16)].map(byte => String.fromCharCode(97 + (byte >> 4), 97 + (byte & 15))).join("");
+}
+
+export async function blobDigest(blob) {
+ const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", await blob.arrayBuffer()));
+ return [...hash].map(byte => byte.toString(16).padStart(2, "0")).join("");
+}
+
+export function localReleasePackageUrl(manifest, releaseUrl, version) {
+ const base = githubLatestReleaseUrl(manifest.homepage_url);
+ if (!base) throw new Error("扩展主页未配置有效的版本发布地址");
+ const repository = base.replace(/\/releases\/latest$/u, "");
+ const release = new URL(releaseUrl);
+ if (release.origin + release.pathname !== `${repository}/releases/tag/v${version}`
+ && release.origin + release.pathname !== `${repository}/releases/tag/${version}`) throw new Error("更新地址与版本不一致");
+ const tag = release.pathname.split("/").at(-1);
+ return `${repository}/releases/download/${tag}/PromptDirector-${version}-FIXED-ID-DEV.zip`;
+}
+
+export async function prepareLocalUpgrade(archive, runtime) {
+ const current = runtime.getManifest();
+ const files = await readZipBlob(archive);
+ for (const path of files.keys()) if (!isExtensionProgramPath(path)) throw new Error(`更新包包含非程序文件:${path}`);
+ if (!files.has("manifest.json")) throw new Error("更新包缺少 manifest.json");
+ const manifest = JSON.parse(await files.get("manifest.json").text());
+ if (await extensionIdForKey(manifest.key) !== runtime.id) throw new Error("更新包与当前插件身份不同,已停止升级;请保留原插件");
+ if (manifest.homepage_url !== current.homepage_url || manifest.manifest_version !== 3) throw new Error("更新包不属于当前产品");
+ if (compareExtensionVersions(manifest.version, current.version) <= 0) throw new Error("更新包版本没有高于当前版本");
+ // A reload can disable an extension when its required permissions change.
+ for (const key of ["permissions", "host_permissions"]) {
+ const granted = new Set(current[key] || []);
+ if ((manifest[key] || []).some(value => !granted.has(value))) throw new Error("新版增加了必要权限,本次原位升级已停止,请先确认新版安装要求");
+ }
+ const required = [manifest.background?.service_worker, manifest.side_panel?.default_path, "library.html", ...Object.values(manifest.icons || {})];
+ for (const path of required) if (!path || !files.has(path)) throw new Error(`更新包缺少运行文件:${path || "入口"}`);
+ const hashes = {};
+ for (const [path, blob] of files) hashes[path] = await blobDigest(blob);
+ return { manifest, files, hashes, previousVersion: current.version };
+}
+
+async function fileAt(root, path, create = false) {
+ const parts = path.split("/");
+ const name = parts.pop();
+ let directory = root;
+ for (const part of parts) directory = await directory.getDirectoryHandle(part, { create });
+ return { directory, name, handle: await directory.getFileHandle(name, { create }) };
+}
+
+async function readFile(root, path) {
+ try { return await (await fileAt(root, path)).handle.getFile(); }
+ catch (error) { if (error.name === "NotFoundError") return null; throw error; }
+}
+
+async function writeFile(root, path, blob) {
+ const { handle } = await fileAt(root, path, true);
+ const writer = await handle.createWritable();
+ try { await writer.write(blob); await writer.close(); }
+ catch (error) { await writer.abort().catch(() => undefined); throw error; }
+ const written = await handle.getFile();
+ if (await blobDigest(written) !== await blobDigest(blob)) throw new Error(`程序文件写入校验失败:${path}`);
+}
+
+async function* programFiles(root, prefix = "") {
+ for await (const [name, handle] of root.entries()) {
+ const path = prefix + name;
+ if (handle.kind === "file" && isExtensionProgramPath(path)) yield [path, await handle.getFile()];
+ if (handle.kind === "directory" && ["assets", "assets/icons", "_locales", "vendor", "vendor/pdfjs", "vendor/document-ingestion"].some(base => path === base || path.startsWith(base + "/"))) {
+ yield* programFiles(handle, path + "/");
+ }
+ }
+}
+
+export async function verifyInstallationDirectory(root, runtime, fetchFn = fetch) {
+ try {
+ await root.getDirectoryHandle(".git");
+ throw new Error("这是源码工作目录,请通过项目更新代码,避免覆盖尚未发布的修改");
+ } catch (error) { if (error.name !== "NotFoundError") throw error; }
+ const disk = await readFile(root, "manifest.json");
+ if (!disk) throw new Error("所选文件夹不是插件安装目录");
+ const manifest = JSON.parse(await disk.text());
+ if (manifest.version !== runtime.getManifest().version || await extensionIdForKey(manifest.key) !== runtime.id) {
+ throw new Error("所选目录与正在运行的插件不一致");
+ }
+ const name = `promptdirector-directory-check-${crypto.randomUUID()}.txt`;
+ const token = crypto.randomUUID();
+ try {
+ await writeFile(root, name, new Blob([token]));
+ const response = await fetchFn(runtime.getURL(name), { cache: "no-store" });
+ if (!response.ok || await response.text() !== token) throw new Error("请选择 Chrome 当前实际加载的安装目录,不能选择另一份解压副本");
+ } finally {
+ await root.removeEntry(name).catch(error => { if (error.name !== "NotFoundError") throw error; });
+ }
+}
+
+export async function installLocalUpgrade(root, prepared, { runtime, fetchFn = fetch, saveRecord, onProgress = () => undefined }) {
+ await verifyInstallationDirectory(root, runtime, fetchFn);
+ // Do not overwrite a recovery point left by an interrupted upgrade.
+ try {
+ await root.getDirectoryHandle(RECOVERY_DIRECTORY);
+ throw new Error("安装目录中有未清理的升级恢复副本,请先恢复或完成上次升级");
+ } catch (error) { if (error.name !== "NotFoundError") throw error; }
+ const recovery = await root.getDirectoryHandle(RECOVERY_DIRECTORY, { create: true });
+ const oldFiles = new Map();
+ const written = [];
+ let recorded = false;
+ const record = { root, previousVersion: prepared.previousVersion, targetVersion: prepared.manifest.version, hashes: prepared.hashes };
+ const oldHashes = {};
+ try {
+ await saveRecord({ ...record, phase: "preparing" });
+ recorded = true;
+ for await (const [path, blob] of programFiles(root)) {
+ oldFiles.set(path, blob);
+ await writeFile(recovery, path, blob);
+ oldHashes[path] = await blobDigest(blob);
+ onProgress({ phase: "preparing", completed: oldFiles.size });
+ }
+ if (!oldFiles.has("manifest.json")) throw new Error("无法建立程序恢复副本");
+ await saveRecord({ ...record, oldHashes, phase: "writing" });
+ const paths = [...prepared.files.keys()].filter(path => path !== "manifest.json");
+ paths.push("manifest.json");
+ for (const [index, path] of paths.entries()) {
+ if (oldHashes[path] !== prepared.hashes[path]) {
+ written.push(path);
+ await writeFile(root, path, prepared.files.get(path));
+ }
+ onProgress({ phase: "writing", completed: index + 1, total: paths.length });
+ }
+ await saveRecord({ ...record, oldHashes, phase: "written" });
+ } catch (error) {
+ try {
+ for (const path of written.reverse()) {
+ const old = oldFiles.get(path);
+ if (old) await writeFile(root, path, await readFile(recovery, path));
+ else {
+ try {
+ const { directory, name } = await fileAt(root, path);
+ await directory.removeEntry(name);
+ } catch (missing) { if (missing.name !== "NotFoundError") throw missing; }
+ }
+ }
+ await root.removeEntry(RECOVERY_DIRECTORY, { recursive: true });
+ if (recorded) await saveRecord(null);
+ } catch (recoveryError) {
+ console.error("Local extension upgrade rollback failed", recoveryError);
+ throw new Error(`升级中断,程序恢复副本保留在 ${RECOVERY_DIRECTORY}。请在 Chrome 扩展管理中加载该文件夹恢复原版本,无需卸载或导入案例。`);
+ }
+ throw error;
+ }
+}
+
+export async function localUpgradeRecord(value = undefined) {
+ const db = await new Promise((resolve, reject) => {
+ const request = indexedDB.open("promptdirector-extension-updater", 1);
+ request.onupgradeneeded = () => request.result.createObjectStore("state");
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error);
+ });
+ try {
+ return await new Promise((resolve, reject) => {
+ const transaction = db.transaction("state", value === undefined ? "readonly" : "readwrite");
+ const store = transaction.objectStore("state");
+ const request = value === undefined ? store.get(RECORD_KEY) : value === null ? store.delete(RECORD_KEY) : store.put(value, RECORD_KEY);
+ transaction.oncomplete = () => resolve(request.result);
+ transaction.onerror = () => reject(transaction.error);
+ transaction.onabort = () => reject(transaction.error || new Error("无法记录升级进度"));
+ });
+ } finally { db.close(); }
+}
+
+export async function verifyRunningUpgrade(record, runtime, fetchFn = fetch) {
+ if (runtime.getManifest().version !== record.targetVersion) return false;
+ for (const [path, hash] of Object.entries(record.hashes)) {
+ const response = await fetchFn(runtime.getURL(path), { cache: "no-store" });
+ if (!response.ok || await blobDigest(await response.blob()) !== hash) return false;
+ }
+ return true;
+}
+
+export async function verifyRecoveredUpgrade(record, runtime, fetchFn = fetch) {
+ if (!record.oldHashes || !Object.keys(record.oldHashes).length) return false;
+ return verifyRunningUpgrade({ targetVersion: record.previousVersion, hashes: record.oldHashes }, runtime, fetchFn);
+}
diff --git a/manifest.json b/manifest.json
index ca35c17..2af62cf 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "__MSG_extensionName__",
- "version": "1.20.0",
+ "version": "1.20.1",
"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/package-lock.json b/package-lock.json
index d5dfa38..954faf9 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "prompt-case-collector",
- "version": "1.20.0",
+ "version": "1.20.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prompt-case-collector",
- "version": "1.20.0",
+ "version": "1.20.1",
"license": "Apache-2.0",
"dependencies": {
"@jonahschulte/rtf-toolkit": "0.5.0",
diff --git a/package.json b/package.json
index f8359c4..a3d13a2 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "prompt-case-collector",
- "version": "1.20.0",
+ "version": "1.20.1",
"private": false,
"license": "Apache-2.0",
"repository": "https://github.com/wchao6891/PromptDirector",
diff --git a/store/CHROME_WEB_STORE_SUBMISSION.md b/store/CHROME_WEB_STORE_SUBMISSION.md
index 86f01a5..d9620a8 100644
--- a/store/CHROME_WEB_STORE_SUBMISSION.md
+++ b/store/CHROME_WEB_STORE_SUBMISSION.md
@@ -6,10 +6,8 @@ This file is the source-of-truth worksheet for the current PromptDirector manife
- 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 source build artifact: `dist/PromptDirector-1.20.0.zip`. Version 1.20.0 is a source checkpoint; no GitHub Release or Chrome Web Store submission is authorized for this checkpoint.
-- Candidate size: 9,018,284 bytes.
-- Candidate SHA-256: `6e7f037602d8b6e0d1b0ebfa5a66f34a511a14422052609ae57d189f75109b1e`.
-- 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.
+- Current upload artifact: `dist/PromptDirector-1.20.1.zip`. The GitHub `FIXED-ID-DEV` artifact is for local installations only.
+- 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. Record the generated ZIP size and SHA-256 from the final release assets.
## Store listing
@@ -69,14 +67,16 @@ Chinese Dashboard value:
## Privacy practices
-- Remote code: **No, the extension does not use remote code.** Remote JSON, media, curated archives, and AI responses are treated as data and are never executed as extension code.
+- Policy reference: [Manifest V3 requirements](https://developer.chrome.com/docs/webstore/program-policies/mv3-requirements/) require packaged executable logic; the upload build excludes the GitHub program installer.
+- Distribution updates: the Web Store archive contains no local program installer; updates are delivered by Chrome. The separate GitHub development archive supports user-authorized in-place program updates.
+- Remote code: **No, the Web Store extension does not use remote code.** Remote JSON, media, curated archives, and AI responses are treated as data and are never executed as extension code.
- User data: disclose website content and resources, saved source URLs/browsing activity, user-provided prompts/notes/media, and locally stored AI-service authentication information. These categories are handled even when they remain on-device.
- Data transfer: user-selected content is sent only to the AI service or compatible endpoint selected and authorized by the user. Curated catalog and Release requests contain no private library data.
- Limited Use: certify all applicable statements. There is no sale of user data, personalized advertising, analytics collection, or developer-operated content server.
Chinese remote-code declaration:
-> 不使用远程代码。所有可执行 JavaScript、CSS、PDF 与文档解析器和 ZIP 逻辑均随扩展包提供。远程 JSON、媒体、精选包和 AI 响应只作为经过校验的数据处理,绝不作为代码执行。
+> 商店包不包含本地程序安装器,更新由 Chrome 分发。不使用远程代码。所有可执行 JavaScript、CSS、PDF 与文档解析器和 ZIP 逻辑均随扩展包提供。远程 JSON、媒体、精选包和 AI 响应只作为经过校验的数据处理,绝不作为代码执行。
Data types handled, including local-only handling:
diff --git a/store/PRIVACY_POLICY.md b/store/PRIVACY_POLICY.md
index 6aee32d..07a60d2 100644
--- a/store/PRIVACY_POLICY.md
+++ b/store/PRIVACY_POLICY.md
@@ -57,8 +57,8 @@
- `scripting`:仅在用户主动启动采集、选图或截图工具时向当前页面注入所需脚本。
- `storage` 与 `unlimitedStorage`:保存用户主动收藏的资料、媒体、设置和本地 AI 服务配置。
- `https://wchao6891.github.io/*`:读取 PromptDirector 官方精选目录、目录指标、封面和只读预览数据。
-- `https://github.com/*`:读取用户明确选择保存的官方精选 Release 包,并打开公开的问题反馈或投稿页面。
-- `https://objects.githubusercontent.com/*` 与 `https://release-assets.githubusercontent.com/*`:跟随 GitHub Release 的受信下载链读取用户明确选择的精选包及其媒体;不会读取其他 GitHub 账号数据。
+- `https://github.com/*`:读取用户明确选择保存的官方精选 Release 包,并打开公开的问题反馈或投稿页面;本地开发版还会读取官方更新版本,并在用户确认后下载程序更新包。
+- `https://objects.githubusercontent.com/*` 与 `https://release-assets.githubusercontent.com/*`:跟随 GitHub Release 的受信下载链读取用户明确选择的精选包及其媒体,或本地开发版的程序更新包;不会读取其他 GitHub 账号数据。
- 可选的 `<all_urls>`:不在安装时授予。只有用户主动使用需要相应站点权限的采集功能或保存第三方 AI 服务、自定义兼容接口时,扩展才会请求相应域名的运行时权限。
- 可选的 `clipboardRead`:只在用户明确触发需要读取剪贴板内容的功能时请求。
- 可选的 `declarativeNetRequestWithHostAccess`:只在用户已授予相应站点访问权限、且功能需要按该权限处理网络请求时使用。
@@ -106,8 +106,8 @@ PromptDirector complies with the Limited Use requirements of the Chrome Web Stor
- `scripting`: inject the required capture, selection, or screenshot code only after a user starts that action.
- `storage` and `unlimitedStorage`: retain the user's selected references, media, settings, and local AI configuration.
- `https://wchao6891.github.io/*`: read the official curated catalog, metrics, covers, and read-only previews.
-- `https://github.com/*`: read an official curated Release package selected by the user and open public feedback or submission pages.
-- `https://objects.githubusercontent.com/*` and `https://release-assets.githubusercontent.com/*`: follow GitHub's trusted Release download chain for a curated package and its media selected by the user; no other GitHub account data is read.
+- `https://github.com/*`: read an official curated Release package selected by the user and open public feedback or submission pages. Local development builds also check official versions and download program updates after user confirmation.
+- `https://objects.githubusercontent.com/*` and `https://release-assets.githubusercontent.com/*`: follow GitHub's trusted Release download chain for user-selected curated packages and media, or local development program updates; no other GitHub account data is read.
- Optional `<all_urls>`: not granted at installation. PromptDirector requests only the specific origin needed when the user starts a site-dependent capture or saves a third-party or compatible AI endpoint.
- Optional `clipboardRead`: requested only for a user-triggered feature that reads clipboard content.
- Optional `declarativeNetRequestWithHostAccess`: requested only when a user-granted site permission and the chosen feature require a bounded network rule.
diff --git a/test/data-safety-ui.test.js b/test/data-safety-ui.test.js
index a9e4209..1f3580d 100644
--- a/test/data-safety-ui.test.js
+++ b/test/data-safety-ui.test.js
@@ -61,14 +61,14 @@ test("share-package import is separate from the two backup actions while sync st
html.indexOf('<footer class="settings-about"')
);
- assert.match(panel, /id="create-folder-backup"[^>]*>备份资料库/);
- assert.match(panel, /id="restore-folder-backup"[^>]*>恢复资料库/);
+ assert.match(panel, /id="create-folder-backup"[\s\S]*?data-i18n="备份资料库"/);
+ assert.match(panel, /id="restore-folder-backup"[\s\S]*?data-i18n="恢复资料库"/);
assert.match(panel, /class="share-package-import"/);
assert.match(panel, /id="import-library-package"[^>]*>选择 ZIP/);
assert.match(panel, /id="library-package-file"[^>]*accept="\.zip,application\/zip"/);
assert.doesNotMatch(panel, /create-portable-backup|restore-portable-backup|小型 ZIP|从 ZIP/);
assert.match(panel, /<details id="sync-settings"/);
- assert.match(panel, /<summary[^>]*data-i18n="跨设备同步"/);
+ assert.match(panel, /<summary>[\s\S]*?data-i18n="跨设备同步"/);
assert.equal((panel.match(/class="data-safety-primary-actions"/g) ?? []).length, 1);
const primaryActions = panel.slice(
panel.indexOf('class="data-safety-primary-actions"'),
diff --git a/test/dialog-layout.test.js b/test/dialog-layout.test.js
index 963445d..1f1f5e6 100644
--- a/test/dialog-layout.test.js
+++ b/test/dialog-layout.test.js
@@ -20,7 +20,7 @@ test("AI settings use full-width task and service views instead of a cramped spl
assert.match(html, /data-ai-routing-tab="providers"[^>]*aria-selected="false"/);
assert.match(html, /data-ai-routing-panel="tasks"/);
assert.match(html, /data-ai-routing-panel="providers"[^>]*hidden/);
- assert.match(css, /\.settings-dialog\s*\{[^}]*width:\s*min\(1040px, calc\(100vw - 40px\)\)/s);
+ assert.match(css, /\.settings-dialog\s*\{[^}]*width:\s*min\(880px, calc\(100vw - 40px\)\)/s);
assert.match(css, /\.ai-routing-regions\s*\{[^}]*grid-template-columns:\s*minmax\(0, 1fr\)/s);
assert.doesNotMatch(css, /\.ai-routing-regions\s*\{[^}]*1\.35fr/s);
});
diff --git a/test/extension-package-variants.test.js b/test/extension-package-variants.test.js
new file mode 100644
index 0000000..9e14ec2
--- /dev/null
+++ b/test/extension-package-variants.test.js
@@ -0,0 +1,24 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { packageRuntimeFiles } from "../tools/extension-package-variants.mjs";
+
+const files = [
+ { name: "library.js", data: "shared library" },
+ { name: "local-extension-upgrade.js", data: "local installer" },
+ { name: "local-extension-upgrade-ui.js", data: "local update controls" }
+];
+
+test("local packages retain the complete in-place updater", () => {
+ assert.equal(packageRuntimeFiles(files), files);
+});
+
+test("store packages contain no program downloader or writer and preserve shared application files", () => {
+ const store = packageRuntimeFiles(files, { release: true });
+ assert.equal(store.find(file => file.name === "library.js"), files[0]);
+ assert.equal(store.some(file => file.name === "local-extension-upgrade.js"), false);
+ const ui = store.find(file => file.name === "local-extension-upgrade-ui.js").data;
+ assert.doesNotMatch(ui, /fetch\(|showDirectoryPicker|createWritable|local-extension-upgrade\.js/);
+ for (const name of ["openLocalUpgrade", "runningUpgradeFeedback", "finishLocalUpgrade"]) assert.match(ui, new RegExp(`export async function ${name}\\(`));
+ assert.match(ui, /商店版由 Chrome 自动更新/);
+ assert.equal(files[2].data, "local update controls");
+});
diff --git a/test/extension-update-ui.test.js b/test/extension-update-ui.test.js
index 0e6d39b..c425248 100644
--- a/test/extension-update-ui.test.js
+++ b/test/extension-update-ui.test.js
@@ -1,65 +1,49 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
-
+import { load } from "cheerio";
const root = new URL("../", import.meta.url);
-const [html, css, source] = await Promise.all([
- readFile(new URL("library.html", root), "utf8"),
- readFile(new URL("library.css", root), "utf8"),
- readFile(new URL("library.js", root), "utf8")
-]);
-
-test("about settings expose status and state-specific update actions", () => {
- const about = html.slice(html.indexOf('<footer class="settings-about">'), html.indexOf("</footer>", html.indexOf('<footer class="settings-about">')));
- assert.match(about, /id="about-version"/);
- assert.match(about, /id="update-channel"/);
- assert.match(about, /id="update-checked-at"/);
- assert.match(about, /id="update-available-version"/);
- assert.match(about, /id="check-extension-update"/);
- assert.match(about, /id="apply-extension-update"/);
- assert.match(about, /id="update-release-link"/);
- assert.match(source, /"应用更新并重启"/);
- assert.match(source, /"重新载入目录"/);
- assert.match(about, /class="button-primary update-download-action"[^>]*hidden[^>]*>下载新版本/);
- assert.match(css, /\.settings-update-actions/);
-});
-
-test("green actions are visible only for a real store or development update", () => {
- const render = source.slice(source.indexOf("function renderExtensionUpdateStatus"), source.indexOf("function updateStatusDisplay"));
- assert.match(render, /updateReleaseLink\.hidden = !releaseUrl/);
- assert.match(render, /applyExtensionUpdate\.hidden = !status\.canApply/);
- assert.match(render, /classList\.toggle\("button-secondary", development\)/);
- assert.match(render, /development && status\.updateAvailable/);
- assert.match(source, /settingsUpdateBadge\.hidden = !hasUpdate/);
-});
+const [html, source, local] = await Promise.all(["library.html", "library.js", "local-extension-upgrade-ui.js"].map(path => readFile(new URL(path, root), "utf8")));
+const $ = load(html);
-test("update UI uses the background lifecycle protocol and refresh event", () => {
- assert.match(source, /type: "GET_EXTENSION_UPDATE_STATUS"/);
- assert.match(source, /type: "CHECK_EXTENSION_UPDATE"/);
- assert.match(source, /type: "APPLY_EXTENSION_UPDATE"/);
- assert.match(source, /message\?\.type !== "EXTENSION_UPDATE_STATUS_CHANGED"/);
- assert.match(source, /renderExtensionUpdateStatus\(message\.status\)/);
+test("settings footer is compact with named icons and on-demand about details", () => {
+ const about = $(".settings-about");
+ assert.equal(about.find("#about-version").length, 1);
+ assert.equal(about.find('#check-extension-update[aria-label="检查更新"] svg').length, 1);
+ assert.equal(about.find("#apply-extension-update[hidden]").length, 1);
+ assert.equal(about.find("#open-about").length, 1);
+ assert.equal(about.find("#update-explanation, #update-channel, #update-checked-at").length, 0);
+ assert.doesNotMatch(about.text(), /安全重载|私人灵感库|Apache|手动替换/);
});
-
-test("development update wording never claims the extension installs or overwrites local code", () => {
- const explanation = source.slice(source.indexOf("function updateExplanation"), source.indexOf("function updateCheckFeedback"));
- assert.match(explanation, /扩展无法自行覆盖本机目录/);
- assert.match(explanation, /安全重载只会重新载入当前目录,不会下载或安装新版本/);
- assert.match(explanation, /固定 ID 升级无需导出、导入案例/);
- assert.doesNotMatch(explanation, /一键安装|自动覆盖本地代码/);
+test("store update remains browser managed; local update runs the package installer", () => {
+ assert.match(source, /checkExtensionUpdate\.hidden = status\?\.channel === "store"/);
+ assert.match(source, /applyExtensionUpdate\.hidden = !status\?\.canApply/);
+ assert.match(source, /openLocalUpgrade\(status\)/);
+ assert.doesNotMatch(source, /reload_development_directory|重新载入目录/);
+ assert.match(local, /installType !== "development"/);
+ assert.match(local, /installLocalUpgrade\(root, prepared/);
+ assert.match(local, /verifyRunningUpgrade\(record, chrome.runtime\)/);
});
-
-test("applying a downloaded store update discloses that the page closes but library data remains", () => {
- const applyFlow = source.slice(source.indexOf("async function applyExtensionUpdate"), source.indexOf("function renderExtensionUpdateStatus"));
- assert.match(applyFlow, /当前资料库页面会关闭/);
- assert.match(applyFlow, /本地案例和素材不会丢失|案例和素材不会丢失/);
- assert.match(applyFlow, /confirmAppAction/);
- assert.match(applyFlow, /applyBehavior === "reload_development_directory"/);
+test("store restart informs the user at the action, not in persistent footer prose", () => {
+ const apply = source.slice(source.indexOf("async function applyExtensionUpdate"), source.indexOf("function renderExtensionUpdateStatus"));
+ assert.match(apply, /confirmAppAction/);
+ assert.match(apply, /当前资料库页面会关闭,但本地案例和素材不会丢失/);
+ assert.match(apply, /type: "APPLY_EXTENSION_UPDATE"/);
});
-
-test("the settings entry uses a low-interruption update badge", () => {
- assert.match(html, /id="settings-update-badge"[^>]*hidden/);
- assert.match(css, /\.settings-update-badge/);
+test("settings update badge and background status events are preserved", () => {
+ assert.equal($("#settings-update-badge[hidden]").length, 1);
assert.match(source, /settingsUpdateBadge\.hidden = !hasUpdate/);
- assert.match(source, /设置,有可用更新/);
+ assert.match(source, /message\?\.type !== "EXTENSION_UPDATE_STATUS_CHANGED"/);
+});
+test("compact settings preserve direct data actions and same-group permission/sync controls", () => {
+ assert.equal($(".capture-permission-row").length, 2);
+ $(".capture-permission-row").each((_i, row) => {
+ assert.equal($(row).children("strong").length, 1);
+ assert.equal($(row).children("button").length, 1);
+ });
+ assert.equal($(".data-heading #create-folder-backup").length, 1);
+ assert.equal($(".data-heading #restore-folder-backup").length, 1);
+ assert.equal($(".sync-settings-body > #connect-sync-folder").length, 1);
+ assert.equal($(".sync-settings-body > #data-safety-password").length, 1);
+ assert.equal($("#save-library-settings[aria-label] svg").length, 1);
});
diff --git a/test/extension-update.test.js b/test/extension-update.test.js
index 2a6b279..65718c9 100644
--- a/test/extension-update.test.js
+++ b/test/extension-update.test.js
@@ -4,7 +4,7 @@ import { readFile } from "node:fs/promises";
import {
compareExtensionVersions,
- createExtensionUpdateLifecycle,
+ createExtensionUpdateLifecycle as actualLifecycle,
EXTENSION_UPDATE_STATUS_CHANGED,
EXTENSION_UPDATE_STORAGE_KEY,
extensionUpdateChannel,
@@ -13,6 +13,11 @@ import {
releaseVersionFromUrl
} from "../extension-update.js";
+// Installation metadata is explicit in the test adapter; production uses getSelf().
+function createExtensionUpdateLifecycle(options) {
+ return actualLifecycle({ getInstallation: async () => options.runtime.installation, ...options });
+}
+
function memoryStorage(initial = {}) {
const values = structuredClone(initial);
return {
@@ -28,6 +33,7 @@ function memoryStorage(initial = {}) {
function fakeRuntime(manifest, updateResult = { status: "no_update" }) {
return {
+ installation: manifest.key ? { installType: "development" } : { installType: "normal", updateUrl: "https://clients2.google.com/service/update2/crx" },
reloadCount: 0,
getManifest: () => structuredClone(manifest),
requestUpdateCheck: async () => structuredClone(updateResult),
@@ -49,9 +55,9 @@ test("Chrome extension versions are parsed and compared with Chrome's strict rul
assert.throws(() => compareExtensionVersions("v1.2", "1.1"), /版本号格式无效/u);
});
-test("package identity selects the update channel and GitHub release tags remain strict", () => {
- assert.equal(extensionUpdateChannel({ version: "1.0" }), "store");
- assert.equal(extensionUpdateChannel({ version: "1.0", key: "public-key" }), "development");
+test("installation metadata selects the update channel and GitHub release tags remain strict", () => {
+ assert.equal(extensionUpdateChannel({ installType: "normal", updateUrl: "https://clients2.google.com/service/update2/crx" }), "store");
+ assert.equal(extensionUpdateChannel({ installType: "development" }), "development");
assert.equal(
githubLatestReleaseUrl("https://github.com/example/prompt-director/"),
"https://github.com/example/prompt-director/releases/latest"
@@ -97,14 +103,14 @@ test("development startup discovers a newer GitHub release without downloading c
assert.equal(status.updateAvailable, true);
assert.equal(status.updateKind, "development_release");
assert.equal(status.canApply, true);
- assert.equal(status.applyBehavior, "reload_development_directory");
+ assert.equal(status.applyBehavior, "upgrade_local_package");
assert.equal(status.checkStatus, "update_available");
assert.equal(notifications.length, 1);
assert.equal(storage.values[EXTENSION_UPDATE_STORAGE_KEY].latestVersion, "1.19.0");
assert.equal("canApply" in storage.values[EXTENSION_UPDATE_STORAGE_KEY], false);
});
-test("development apply only reloads the current directory and never claims to install", async () => {
+test("development apply rejects reloading unchanged code as a package upgrade", async () => {
const runtime = fakeRuntime({
version: "1.18.9",
key: "fixed-development-id",
@@ -127,13 +133,12 @@ test("development apply only reloads the current directory and never claims to i
});
const result = await lifecycle.apply();
- assert.equal(result.ok, true);
+ assert.equal(result.ok, false);
assert.equal(result.installsUpdate, false);
- assert.equal(result.willReload, true);
- assert.match(result.message, /不会下载或安装新版本/u);
+ assert.equal(result.willReload, false);
+ assert.match(result.message, /重新载入不会安装新版本/u);
assert.equal(runtime.reloadCount, 0);
- scheduledReload();
- assert.equal(runtime.reloadCount, 1);
+ assert.equal(scheduledReload, undefined);
});
test("development current version has no reload or primary update action", async () => {
@@ -256,3 +261,15 @@ test("background wires update events and the public message protocol", async ()
}
assert.match(source, new RegExp(EXTENSION_UPDATE_STATUS_CHANGED, "u"));
});
+
+test("actual installation metadata overrides the presence or absence of a manifest key", async () => {
+ const runtime = fakeRuntime({ version: "1.0", homepage_url: "https://github.com/example/prompt-director" });
+ runtime.installation = { installType: "development" };
+ assert.equal((await createExtensionUpdateLifecycle({ runtime, storage: memoryStorage() }).getStatus()).channel, "development");
+ assert.equal(extensionUpdateChannel({ key: "key", installType: "normal" }), "unknown");
+ let checks = 0;
+ runtime.requestUpdateCheck = async () => { checks++; };
+ const service = createExtensionUpdateLifecycle({ runtime, storage: memoryStorage(), getInstallation: async () => { throw new Error("unavailable"); } });
+ assert.equal((await service.check()).checkStatus, "error");
+ assert.equal(checks, 0);
+});
diff --git a/test/i18n.test.js b/test/i18n.test.js
index f5e367b..973b9a3 100644
--- a/test/i18n.test.js
+++ b/test/i18n.test.js
@@ -43,7 +43,7 @@ test("product pages do not leave Chinese interface text outside the translation
});
test("dynamic interface helpers only receive Chinese copy with an English translation", async () => {
- const paths = ["../library.js", "../composer-page.js", "../skills-page.js", "../collector.js", "../curated-page.js", "../ui-dialogs.js", "../tag-editor.js"];
+ const paths = ["../library.js", "../composer-page.js", "../skills-page.js", "../collector.js", "../curated-page.js", "../ui-dialogs.js", "../tag-editor.js", "../local-extension-upgrade-ui.js"];
const missing = [];
for (const path of paths) {
const source = await readFile(new URL(path, import.meta.url), "utf8");
diff --git a/test/library-navigation.test.js b/test/library-navigation.test.js
index b04925d..4d7a1b0 100644
--- a/test/library-navigation.test.js
+++ b/test/library-navigation.test.js
@@ -25,18 +25,15 @@ test("top navigation keeps search-adjacent actions focused on adding, creating,
assert.doesNotMatch(html, /动态视图|save-dynamic-view|dynamic-view-list/);
});
-test("about information is inline at the bottom of general settings", async () => {
+test("about details are on demand while version stays at the bottom of general settings", async () => {
const about = html.slice(html.indexOf('<footer class="settings-about"'), html.indexOf("</footer>", html.indexOf('<footer class="settings-about"')));
const script = await readFile(new URL("../library.js", import.meta.url), "utf8");
- assert.equal((about.match(/<a\b/g) ?? []).length, 2);
assert.match(about, /id="about-version">PromptDirector</);
- assert.doesNotMatch(about, /PromptDirector\s+\d+\.\d+\.\d+/);
- assert.match(script, /aboutVersion\.textContent\s*=\s*`PromptDirector \$\{chrome\.runtime\.getManifest\(\)\.version\}`/);
- assert.match(about, /github\.com\/wchao6891\/PromptDirector/);
- assert.match(about, /id="update-release-link"[^>]*github\.com\/wchao6891\/PromptDirector\/releases[^>]*hidden/);
- assert.match(about, /Apache-2\.0/);
- assert.doesNotMatch(about, /href="LICENSE"|href="NOTICE"|THIRD_PARTY_NOTICES/);
- assert.doesNotMatch(html, /id="about-dialog"|id="open-about"/);
+ assert.match(about, /id="open-about"/);
+ assert.doesNotMatch(about, /Apache-2\.0|github\.com/);
+ assert.match(script, /async function showExtensionAbout/);
+ assert.match(script, /免费、开源、本地优先 · Apache-2\.0/);
+ assert.match(script, /safeHttpUrl\(manifest\.homepage_url\)/);
});
test("closed dialogs cannot enter the page layout", async () => {
diff --git a/test/library-permission-settings.test.js b/test/library-permission-settings.test.js
index 3e03357..342459e 100644
--- a/test/library-permission-settings.test.js
+++ b/test/library-permission-settings.test.js
@@ -14,7 +14,7 @@ test("general settings show separate web-capture and clipboard permission status
assert.match(html, /id="capture-clipboard-permission-status"/);
assert.match(html, /id="revoke-capture-web-permission"/);
assert.match(html, /id="revoke-capture-clipboard-permission"/);
- assert.match(html, /这里不会读取剪贴板/);
+ assert.doesNotMatch(html, /这里不会读取剪贴板/);
assert.match(css, /\.capture-permission-list\s*\{/);
assert.match(css, /\.capture-permission-row\s*\{/);
});
diff --git a/test/local-extension-upgrade.test.js b/test/local-extension-upgrade.test.js
new file mode 100644
index 0000000..6ce06cb
--- /dev/null
+++ b/test/local-extension-upgrade.test.js
@@ -0,0 +1,144 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { createZipBlob } from "../zip.js";
+import { extensionIdForKey, installLocalUpgrade, isExtensionProgramPath, localReleasePackageUrl, prepareLocalUpgrade, RECOVERY_DIRECTORY, verifyInstallationDirectory, verifyRecoveredUpgrade, verifyRunningUpgrade } from "../local-extension-upgrade.js";
+const manifest = JSON.parse(await readFile(new URL("../manifest.json", import.meta.url)));
+const id = await extensionIdForKey(manifest.key);
+const nextVersion = [...manifest.version.split(".").slice(0, -1), Number(manifest.version.split(".").at(-1)) + 1].join(".");
+const runtime = { id, getManifest: () => manifest, getURL: path => `chrome-extension://${id}/${path}` };
+
+// Real temporary disk adapter for the File System Access interface. Chrome permissions
+// and native picker behavior require separate browser verification.
+function missing(error) { if (error.code === "ENOENT") error.name = "NotFoundError"; return error; }
+function directory(path, fault = () => false) {
+ return {
+ kind: "directory", name: path.split("/").at(-1), path,
+ async getDirectoryHandle(name, { create = false } = {}) {
+ const next = join(path, name);
+ try { if (create) await mkdir(next, { recursive: true }); await readdir(next); }
+ catch (error) { throw missing(error); }
+ return directory(next, fault);
+ },
+ async getFileHandle(name, { create = false } = {}) {
+ const next = join(path, name);
+ try { await readFile(next); } catch (error) { if (create && error.code === "ENOENT") await writeFile(next, ""); else throw missing(error); }
+ return {
+ kind: "file", name,
+ async getFile() { return new Blob([await readFile(next)]); },
+ async createWritable() {
+ let content;
+ return {
+ async write(blob) { content = new Uint8Array(await blob.arrayBuffer()); },
+ async close() { if (fault(next)) throw new Error("simulated disk write failure"); await writeFile(next, content); },
+ async abort() {}
+ };
+ }
+ };
+ },
+ async removeEntry(name, { recursive = false } = {}) { try { await rm(join(path, name), { recursive }); } catch (error) { throw missing(error); } },
+ async *entries() {
+ for (const entry of await readdir(path, { withFileTypes: true })) {
+ yield [entry.name, entry.isDirectory() ? directory(join(path, entry.name), fault) : await this.getFileHandle(entry.name)];
+ }
+ }
+ };
+}
+function served(path) {
+ return async url => {
+ try { return new Response(await readFile(join(path, new URL(url).pathname))); }
+ catch { return new Response("", { status: 404 }); }
+ };
+}
+async function fixture(t, fault) {
+ const path = await mkdtemp(join(tmpdir(), "pd-upgrade-test-"));
+ t.after(() => rm(path, { recursive: true, force: true }));
+ await writeFile(join(path, "manifest.json"), JSON.stringify(manifest));
+ await writeFile(join(path, "background.js"), "old background");
+ await writeFile(join(path, "cases.json"), "user library must not move");
+ await mkdir(join(path, "media"));
+ await writeFile(join(path, "media", "user.mp4"), "media bytes");
+ return { path, root: directory(path, fault), fetchFn: served(path) };
+}
+async function packageFor(next = { ...manifest, version: nextVersion }) {
+ const names = new Set(["manifest.json", next.background.service_worker, next.side_panel.default_path, "library.html", ...Object.values(next.icons)]);
+ return createZipBlob([...names].map(name => ({ name, data: name === "manifest.json" ? JSON.stringify(next) : `new program ${name}` })));
+}
+
+test("local package identity and version are validated before directory writes", async () => {
+ const prepared = await prepareLocalUpgrade(await packageFor(), runtime);
+ assert.equal(prepared.manifest.version, nextVersion);
+ await assert.rejects(prepareLocalUpgrade(await packageFor({ ...manifest, key: undefined, version: nextVersion }), runtime), /FIXED-ID/);
+ await assert.rejects(prepareLocalUpgrade(await packageFor(manifest), runtime), /没有高于/);
+ await assert.rejects(prepareLocalUpgrade(await packageFor({ ...manifest, version: nextVersion, permissions: [...manifest.permissions, "management"] }), runtime), /权限/);
+ await assert.rejects(prepareLocalUpgrade(await packageFor(), { ...runtime, id: "different" }), /身份不同/);
+ const files = new Map([["manifest.json", new Blob([JSON.stringify({ ...manifest, version: nextVersion })])]]);
+ await assert.rejects(prepareLocalUpgrade(await createZipBlob([...files].map(([name, data]) => ({ name, data }))), runtime), /缺少运行文件/);
+});
+test("program paths exclude user data and dangerous archive paths", () => {
+ for (const path of ["cases.json", "media/user.mp4", "../background.js", "assets/../../x.js", "C:/x.js", "a\\b.js", ".git/config"]) assert.equal(isExtensionProgramPath(path), false, path);
+ assert.equal(isExtensionProgramPath("vendor/pdfjs/build/pdf.mjs"), true);
+ assert.equal(localReleasePackageUrl(manifest, `${manifest.homepage_url}/releases/tag/v${nextVersion}`, nextVersion), `${manifest.homepage_url}/releases/download/v${nextVersion}/PromptDirector-${nextVersion}-FIXED-ID-DEV.zip`);
+ assert.throws(() => localReleasePackageUrl(manifest, `https://evil.example/releases/tag/v${nextVersion}`, nextVersion), /不一致/);
+});
+test("an identical but inactive directory is rejected and the proof file is removed", async t => {
+ const a = await fixture(t);
+ const b = await fixture(t);
+ await assert.rejects(verifyInstallationDirectory(b.root, runtime, a.fetchFn), /实际加载/);
+ assert.deepEqual((await readdir(b.path)).sort(), ["background.js", "cases.json", "manifest.json", "media"]);
+});
+test("successful update replaces program files while user cases and media stay byte-identical", async t => {
+ const f = await fixture(t);
+ const prepared = await prepareLocalUpgrade(await packageFor(), runtime);
+ let record;
+ await installLocalUpgrade(f.root, prepared, { runtime, fetchFn: f.fetchFn, saveRecord: async value => { record = value; } });
+ assert.equal(JSON.parse(await readFile(join(f.path, "manifest.json"))).version, nextVersion);
+ assert.equal(await readFile(join(f.path, "cases.json"), "utf8"), "user library must not move");
+ assert.equal(await readFile(join(f.path, "media/user.mp4"), "utf8"), "media bytes");
+ const backup = await readdir(join(f.path, RECOVERY_DIRECTORY));
+ assert.equal(backup.includes("cases.json"), false);
+ assert.equal(backup.includes("media"), false);
+ assert.equal(record.phase, "written");
+ assert.equal(await verifyRecoveredUpgrade(record, runtime, served(join(f.path, RECOVERY_DIRECTORY))), true);
+ assert.equal(await verifyRunningUpgrade(record, runtime, f.fetchFn), false, "writing files does not prove Chrome is running the new version");
+ assert.equal(await verifyRunningUpgrade(record, { ...runtime, getManifest: () => prepared.manifest }, f.fetchFn), true);
+ await writeFile(join(f.path, "background.js"), "corrupt");
+ assert.equal(await verifyRunningUpgrade(record, { ...runtime, getManifest: () => prepared.manifest }, f.fetchFn), false);
+});
+test("a mid-write failure rolls back changed code and removes newly created files", async t => {
+ let fired = false;
+ const f = await fixture(t, path => {
+ if (path.endsWith("/library.html") && !path.includes(RECOVERY_DIRECTORY) && !fired) { fired = true; return true; }
+ return false;
+ });
+ let record;
+ await assert.rejects(installLocalUpgrade(f.root, await prepareLocalUpgrade(await packageFor(), runtime), { runtime, fetchFn: f.fetchFn, saveRecord: async value => { record = value; } }), /simulated/);
+ assert.equal(await readFile(join(f.path, "background.js"), "utf8"), "old background");
+ assert.equal(JSON.parse(await readFile(join(f.path, "manifest.json"))).version, manifest.version);
+ assert.equal(record, null);
+ assert.equal((await readdir(f.path)).includes(RECOVERY_DIRECTORY), false);
+ assert.equal((await readdir(f.path)).includes("collector.html"), false);
+});
+test("unchanged program files are backed up and verified without rewriting the live file", async t => {
+ const f = await fixture(t, path => path.endsWith("/background.js") && !path.includes(RECOVERY_DIRECTORY));
+ await writeFile(join(f.path, "background.js"), "new program background.js");
+ const progress = [];
+ const prepared = await prepareLocalUpgrade(await packageFor(), runtime);
+ await installLocalUpgrade(f.root, prepared, {
+ runtime, fetchFn: f.fetchFn, saveRecord: async () => {}, onProgress: value => progress.push(value)
+ });
+ assert.equal(await readFile(join(f.path, RECOVERY_DIRECTORY, "background.js"), "utf8"), "new program background.js");
+ assert.equal(await verifyRunningUpgrade({ targetVersion: prepared.manifest.version, hashes: prepared.hashes }, { ...runtime, getManifest: () => prepared.manifest }, f.fetchFn), true);
+ assert.ok(progress.some(value => value.phase === "preparing" && value.completed > 0));
+ assert.deepEqual(progress.at(-1), { phase: "writing", completed: prepared.files.size, total: prepared.files.size });
+});
+test("a source checkout or existing recovery point is never overwritten", async t => {
+ const f = await fixture(t);
+ await mkdir(join(f.path, ".git"));
+ await assert.rejects(verifyInstallationDirectory(f.root, runtime, f.fetchFn), /源码工作目录/);
+ await rm(join(f.path, ".git"), { recursive: true });
+ await mkdir(join(f.path, RECOVERY_DIRECTORY));
+ await assert.rejects(installLocalUpgrade(f.root, await prepareLocalUpgrade(await packageFor(), runtime), { runtime, fetchFn: f.fetchFn, saveRecord: async () => {} }), /恢复副本/);
+});
diff --git a/test/run_e2e.py b/test/run_e2e.py
index 4c613c2..fc86c61 100644
--- a/test/run_e2e.py
+++ b/test/run_e2e.py
@@ -66,6 +66,7 @@ SCRIPTS = [
"material_management_regressions_e2e.py",
"ui_regressions_e2e.py",
"settings_visual_anchor_e2e.py",
+ "settings_compact_e2e.py",
"brand_i18n_e2e.py",
"english_interaction_states_e2e.py",
"case_management_batch_regression_e2e.py",
diff --git a/test/settings_compact_e2e.py b/test/settings_compact_e2e.py
new file mode 100644
index 0000000..a190aa6
--- /dev/null
+++ b/test/settings_compact_e2e.py
@@ -0,0 +1,79 @@
+from __future__ import annotations
+import os
+from pathlib import Path
+from playwright.sync_api import expect
+from e2e_support import extension_session
+
+# Layout and action-state fixtures run only in a disposable Chrome profile.
+with extension_session('pd-settings-compact-', viewport={'width':1440,'height':1000}) as session:
+ page=session.open_page('library.html')
+ page.locator('#open-settings').dispatch_event('click')
+ expect(page.locator('#settings-general-panel')).to_be_visible()
+ page.locator('#ui-theme').select_option('dark')
+ page.locator('#library-name-setting').fill('设置保存验证')
+ page.locator('#save-library-settings').click()
+ expect(page.locator('#library-settings-feedback')).to_have_text('已保存')
+ saved=page.evaluate("async()=> (await chrome.runtime.sendMessage({type:'GET_STATE'})).settings.libraryTitle")
+ assert saved=='设置保存验证',saved
+ page.evaluate("() => { window.originalSettingsSend=chrome.runtime.sendMessage.bind(chrome.runtime); chrome.runtime.sendMessage=async m=>m.type==='UPDATE_SETTINGS'?{ok:false,message:'保存失败测试'}:window.originalSettingsSend(m); }")
+ page.locator('#library-name-setting').fill('保留未保存的修改')
+ page.locator('#save-library-settings').click()
+ expect(page.locator('#library-settings-feedback')).to_have_text('保存失败测试')
+ expect(page.locator('#library-name-setting')).to_have_value('保留未保存的修改')
+ expect(page.locator('#save-library-settings')).to_be_enabled()
+ page.evaluate('() => { chrome.runtime.sendMessage=window.originalSettingsSend; }')
+ page.locator('#library-name-setting').fill('设置保存验证')
+ page.locator('#sync-settings summary').click()
+ expect(page.locator('#connect-sync-folder')).to_be_visible()
+ expect(page.locator('#sync-password')).to_be_visible()
+ expect(page.locator('#unlock-sync-vault')).to_be_hidden()
+ page.evaluate('''() => {
+ window.settingsSendMessage=chrome.runtime.sendMessage.bind(chrome.runtime);
+ window.settingsFixture={connected:true,permission:'granted',unlocked:false};
+ chrome.runtime.sendMessage=async message=>message.type==='GET_DATA_SAFETY_STATUS'
+ ? {ok:true,entryCount:0,mediaCount:0,videoCount:0,syncStatus:window.settingsFixture}
+ : window.settingsSendMessage(message);
+ }''')
+ async_states=[({'connected':True,'permission':'granted','unlocked':False},'unlock-sync-vault'),
+ ({'connected':True,'permission':'granted','unlocked':True},'sync-now'),
+ ({'connected':True,'permission':'granted','unlocked':True,'active':True},'cancel-sync'),
+ ({'connected':False},'connect-sync-folder')]
+ for state,visible in async_states:
+ page.evaluate('(value)=>window.settingsFixture=value',state)
+ page.locator('[data-settings-tab="ai"]').click()
+ page.locator('[data-settings-tab="general"]').click()
+ expect(page.locator('#'+visible)).to_be_visible()
+ page.evaluate('() => { chrome.runtime.sendMessage=window.settingsSendMessage; }')
+ for width,height in [(1440,1000),(390,844)]:
+ page.set_viewport_size({'width':width,'height':height})
+ page.locator('[data-settings-tab="ai"]').click()
+ page.locator('[data-settings-tab="general"]').click()
+ expect(page.locator('#connect-sync-folder')).to_be_visible()
+ page.locator('#sync-password').scroll_into_view_if_needed()
+ rects=page.evaluate('''() => {
+ const rect = selector => {const r=document.querySelector(selector).getBoundingClientRect();return {top:r.top,bottom:r.bottom,left:r.left,right:r.right};};
+ return {password:rect('#sync-password'),connect:rect('#connect-sync-folder'),permissions:[...document.querySelectorAll('.capture-permission-row')].map(row=>{
+ const s=row.querySelector('span').getBoundingClientRect(), b=row.querySelector('button').getBoundingClientRect();return {gap:b.left-s.right,topDelta:Math.abs(b.top-s.top)};
+ }),scrollWidth:document.querySelector('#settings-general-panel').scrollWidth,clientWidth:document.querySelector('#settings-general-panel').clientWidth};
+ }''')
+ assert abs(rects['password']['top']-rects['connect']['top'])<4,rects
+ assert 0<=rects['connect']['left']-rects['password']['right']<=13,rects
+ assert all(0<=r['gap']<=13 for r in rects['permissions']),rects
+ assert rects['scrollWidth']<=rects['clientWidth'],rects
+ if width>680:
+ full=page.locator('.setting-section').first.bounding_box()
+ panel=page.locator('#settings-general-panel').bounding_box()
+ assert abs(full['width']-panel['width'])<20,(full,panel)
+ output=os.environ.get('PROMPTDIRECTOR_SETTINGS_SCREENSHOT_DIR')
+ if output:
+ dest=Path(output);dest.mkdir(parents=True,exist_ok=True)
+ page.locator('#settings-general-panel').evaluate('el=>el.scrollTop=0')
+ page.screenshot(path=str(dest/f'settings-actual-{width}-sync.png'))
+ page.locator('#sync-settings summary').click()
+ page.screenshot(path=str(dest/f'settings-actual-{width}.png'))
+ if width>680: page.locator('#settings-dialog').screenshot(path=str(dest/'settings-actual-panel.png'))
+ page.locator('#sync-settings summary').click()
+ page.locator('#open-about').click()
+ expect(page.locator('#promptdirector-app-dialog')).to_contain_text('关于 PromptDirector')
+ expect(page.locator('#promptdirector-app-dialog')).to_contain_text('选择已下载的更新包')
+ print({'compact_settings':'passed','save':'persisted','sync_states':4,'viewports':[1440,390]})
diff --git a/test/settings_visual_anchor_e2e.py b/test/settings_visual_anchor_e2e.py
index ba02db7..5ccd796 100644
--- a/test/settings_visual_anchor_e2e.py
+++ b/test/settings_visual_anchor_e2e.py
@@ -44,7 +44,8 @@ def settings_metrics(page) -> dict:
def assert_anchor_stable(baseline: dict, current: dict, label: str, viewport: dict) -> None:
for surface in ("dialog", "header", "tabs"):
- for dimension in ("top", "height"):
+ # General settings now size to their content; the header and tabs stay anchored.
+ for dimension in (("top",) if surface == "dialog" else ("top", "height")):
shift = abs(current[surface][dimension] - baseline[surface][dimension])
assert shift <= MAX_ANCHOR_SHIFT_PX, (
f"{viewport} {label} changed {surface}.{dimension} by {shift:.2f}px: "
diff --git a/test/visual-interaction.test.js b/test/visual-interaction.test.js
index 15b1ff8..da5b763 100644
--- a/test/visual-interaction.test.js
+++ b/test/visual-interaction.test.js
@@ -32,9 +32,8 @@ test("the current project uses the product accent while other library selections
assert.match(rule(source, ".detail-visual-thumb"), /background:\s*var\(--raised\)/);
assert.match(rule(source, '.manager-tabs button[aria-selected="true"]::after'), /height:\s*1px/);
assert.match(rule(source, '.analysis-kind-tabs button[aria-selected="true"]'), /background:\s*var\(--selection\)/);
- assert.match(rule(source, ".share-package-import"), /background:\s*var\(--raised\)/);
- assert.match(rule(source, ".share-package-import"), /border:\s*1px solid var\(--line\)/);
- assert.match(rule(source, ".share-package-import"), /box-shadow:\s*none/);
+ assert.match(rule(source, ".compact-general .share-package-import"), /display:\s*flex/);
+ assert.doesNotMatch(rule(source, ".compact-general .share-package-import"), /background:|box-shadow:|justify-content:\s*space-between/);
assert.match(rule(source, "html"), /scrollbar-gutter:\s*stable/);
assert.doesNotMatch(source, /0 0 0 (?:2px|3px) color-mix\(in srgb, var\(--accent\)/);
});
diff --git a/tools/extension-package-variants.mjs b/tools/extension-package-variants.mjs
new file mode 100644
index 0000000..748bbf0
--- /dev/null
+++ b/tools/extension-package-variants.mjs
@@ -0,0 +1,23 @@
+const storeUpdateUi = `import { t } from "./i18n.js";
+
+export async function openLocalUpgrade() {
+ throw new Error(t("商店版由 Chrome 自动更新"));
+}
+
+export async function runningUpgradeFeedback() {
+ return { message: "", cleanupRequired: false };
+}
+
+export async function finishLocalUpgrade() {
+ throw new Error(t("商店版由 Chrome 自动更新"));
+}
+`;
+
+export function packageRuntimeFiles(files, { release = false } = {}) {
+ if (!release) return files;
+ return files
+ .filter(file => file.name !== "local-extension-upgrade.js")
+ .map(file => file.name === "local-extension-upgrade-ui.js"
+ ? { ...file, data: storeUpdateUi }
+ : file);
+}
diff --git a/tools/package-extension.mjs b/tools/package-extension.mjs
index a6f897c..fdbd926 100644
--- a/tools/package-extension.mjs
+++ b/tools/package-extension.mjs
@@ -5,6 +5,7 @@ import { createZipBlob } from "../zip.js";
import { validateChromeStoreManifest } from "./chrome-store-manifest.mjs";
import { verifyPdfjsRuntime } from "./pdfjs-runtime.mjs";
import { chromeStoreUploadManifest, extensionArchiveName } from "./release-identity.mjs";
+import { packageRuntimeFiles } from "./extension-package-variants.mjs";
const projectRoot = fileURLToPath(new URL("../", import.meta.url));
const sourceManifest = JSON.parse(await readFile(join(projectRoot, "manifest.json"), "utf8"));
@@ -58,10 +59,11 @@ const locales = Object.fromEntries(await Promise.all((await readdir(join(project
validateChromeStoreManifest({ manifest, locales });
validateManifest(manifest, files.map((file) => file.name));
await mkdir(join(projectRoot, "dist"), { recursive: true });
-const archive = await createZipBlob(files);
+const runtimeFilesForDistribution = packageRuntimeFiles(files, { release });
+const archive = await createZipBlob(runtimeFilesForDistribution);
const outputPath = join(projectRoot, "dist", extensionArchiveName(sourceManifest, { release }));
await writeFile(outputPath, new Uint8Array(await archive.arrayBuffer()));
-process.stdout.write(`${outputPath}\n${files.length} 个运行文件,${archive.size} 字节\n`);
+process.stdout.write(`${outputPath}\n${runtimeFilesForDistribution.length} 个运行文件,${archive.size} 字节\n`);
async function packageFile(path) {
return {