From e966b348b9cb3427597fa4bdc60ffa634badd339 Mon Sep 17 00:00:00 2001 From: qiqi Date: Tue, 24 Nov 2026 15:16:08 +0800 Subject: [PATCH] =?UTF-8?q?feat(backup):=20v3.26.59=20=E5=A4=87=E4=BB=BD?= =?UTF-8?q?=E5=B8=A6=E4=B8=8A=E6=8F=92=E4=BB=B6=E6=96=87=E4=BB=B6=EF=BC=88?= =?UTF-8?q?=E6=8F=90=E7=A4=BA=E8=AF=8D=E5=B0=81=E9=9D=A2=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E6=8D=A2=E6=9C=BA=E4=B8=A2=E5=A4=B1=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P0(宿主): - 备份 ZIP 新增 plugin-files/<插件id>/<文件名> 通道,恢复时写回沙箱; 此前只备份 JSON ⇒ 换机后「提示词都在、封面全是灰块」,而状态行写着「已恢复」 - IWBStorageFile.pluginFiles 增 readBytes / listAll(不 mkdir、只读字节) - IWBPluginData 增 listFiles / readFile / restoreFiles:清单一次给出、字节逐条读写 (插件文件单插件上限 64MB,攒数组会 OOM) - 校验和口径统一:images / imagesData / pluginFiles / pluginFilesData 全部排除; JSON 兜底导出按自身内容重算 checksum,避免「换个打包形态就报校验不一致」 - 备份二次确认的体积/张数把插件文件计入;恢复摘要显示「含 N 个插件文件(封面等)」 - tests/plugin-data-test:新增插件文件清单/读字节/写回 三条行为断言 P1(插件 promptlib 1.11.0,随包同步): - 封面保存/上传即落成文件(JSON 只留文件名)、孤儿封面可回收 (启动后一次 + 删词条后一次 + 设置页手动入口;空集合/非插件数据来源一律不删) - 四处内联 djb2 哈希合并为 coverFileName,同图不再存两份 - 样式散值归零(4px→6px、margin 13px→12px),插件尺度棘轮基线保持 0 --- CHANGELOG.md | 10 ++ app.js | 7 +- package.json | 2 +- plugins/index.json | 6 +- plugins/promptlib/main.js | 215 +++++++++++++++++++++++++------- plugins/promptlib/manifest.json | 6 +- plugins/promptlib/styles.css | 6 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- src/plugin-data.js | 49 ++++++++ src/storage-backup.js | 4 +- src/storage-file.js | 33 ++++- src/ui-backup-modal.js | 96 +++++++++++--- tests/plugin-data-test.js | 32 ++++- 14 files changed, 387 insertions(+), 83 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 025783d..25fde9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,16 @@ > 3. 核验正式地址版本 → 之后才移动 `stable` / `stable-verified-<日期>` 标签、更新本 CHANGELOG、写 GitHub Release(`gh release create`)。 > 测试发现问题 → 改 → 再 `deploy:test`,正式环境不受影响。回滚点 `git reset --hard stable`。 +## v3.26.59(2026-11-24)备份带上插件文件(提示词封面不再换机丢失) + +> 状态:正式发布(macOS arm64 / x86_64) + +- **P0 备份补洞**:`plugin-data//files/` 里的插件文件(提示词封面等)随 ZIP 写成 `plugin-files//<文件名>`,恢复时写回沙箱。此前只备份 JSON ⇒ 换机后「提示词都在、封面全是灰块」,而状态行还写着「已恢复」 +- 新增 `IWBPluginData.listFiles / readFile / restoreFiles` 与 `IWBStorageFile.pluginFiles.readBytes / listAll`:清单一次给出、字节**逐条读**(写一张放一张,不攒数组,插件文件单插件上限 64MB) +- 校验和口径统一:图片与插件文件的**字节**不进 checksum(`images / imagesData / pluginFiles / pluginFilesData` 全排除);JSON 兜底导出按自身内容重算 checksum,避免「换个打包形态就报校验不一致」 +- 备份确认弹窗的体积估算与张数把插件文件计入;恢复摘要新增「含 N 个插件文件(封面等)」 +- 同步 `promptlib` 1.11.0:封面保存/上传即落成文件(数据里只留文件名)、未被引用的封面可回收(启动后自动一次 + 设置页「清理未引用封面」) + ## v3.26.58(2026-11-24)节点浮层改为紧凑规格(C1) > 状态:正式发布(macOS arm64 / x86_64) diff --git a/app.js b/app.js index f7f5053..ee100cb 100644 --- a/app.js +++ b/app.js @@ -5491,9 +5491,10 @@ const tbCenterSeed = (type, refs) => { function backupChecksumPayload(data) { const out = Object.assign({}, data || {}) - delete out.checksum - delete out.imagesData - delete out.images + // 图片 / 插件文件(v3.26.59)的**字节**不进校验和:它们分别走 images/ 与 plugin-files/ 目录, + // ZIP 与 JSON 兜底两种形态下字段名不同(images/imagesData、pluginFiles/pluginFilesData), + // 不排除就会出现「同一份数据换个打包形态 ⇒ 校验和不一致」的假报错。 + delete out.checksum; delete out.imagesData; delete out.images; delete out.pluginFiles; delete out.pluginFilesData return out } function backupImageManifest(data) { diff --git a/package.json b/package.json index 524d858..1d895fa 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "image-workbench-web", "private": true, - "version": "3.26.58", + "version": "3.26.59", "description": "Browser-based node canvas image workbench", "scripts": { "build": "node scripts/build.js && node scripts/copy-plugins.js", diff --git a/plugins/index.json b/plugins/index.json index 299302c..ab82da0 100644 --- a/plugins/index.json +++ b/plugins/index.json @@ -44,10 +44,10 @@ "dir": "promptlib", "main": "main.js", "style": "styles.css", - "version": "1.10.1", + "version": "1.11.0", "files": { - "main.js": "41d73c02cf4791312d0b922b572ff991a83341aabe3a000a84e9b249e77afac8", - "styles.css": "1ff5e60079166968cfaed95c875a1347884d5476090419491e317cdec2c4e6cd" + "main.js": "0e1bd0f235b05b3edbdccd19ffe24791f0ce82bb5180ebe5a60dcaa6b2ed3ce8", + "styles.css": "23fd4beb4f5b89be1f763ee7221e3dbdafced85afc378cd5cc1a9e03b14d7046" } }, { diff --git a/plugins/promptlib/main.js b/plugins/promptlib/main.js index 2d1f716..3652b2b 100644 --- a/plugins/promptlib/main.js +++ b/plugins/promptlib/main.js @@ -55,6 +55,14 @@ } function uid (prefix) { return prefix + Date.now().toString(36) + Math.random().toString(36).slice(2, 7) } function groupRef (name) { return { id: name, name: name } } + // v1.11.0:封面文件名 = 内容哈希(同名即同图,天然去重;不会因改名/移动分组产生新文件)。 + // 抽成模块级:迁移、保存、设置面板导入三处必须用同一个算法,否则同一张图会存出两个文件。 + function coverFileName (dataUrl) { + var s = String(dataUrl || '') + var h = 5381 + for (var i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0 + return 'c' + h.toString(36) + '.jpg' + } // 文件沙箱:新客户端有独立 files 能力;老客户端退到 promptlib 能力上的 file* 方法。 function fileApi (ctx) { @@ -165,6 +173,54 @@ // v1.10.1:分享封面开关已移除——文本分享恒纯文字、文件分享恒带封面,不再有全局开关。 // (旧的 shareWithCover() / plpSharePayload() 已删除;plpCoverUrl 仍供备份导出使用。) + // ===== v1.11.0:未引用封面回收(P1)===== + // 为什么要有:封面是「内容哈希命名的图片文件」。换封面 / 删词条 / 取消编辑都会留下不再被引用的文件, + // 久了 64MB 沙箱被垃圾占满(用户看到「总量超限,请先清理」却找不到可清的东西)。 + // 判定放在模块级:面板(有 prompts 作用域)与设置页(自带 state)必须用**同一套**规则, + // 否则两处各删一半,第三处又不知道谁还在用。 + // 安全线:keep 为空时不删(空集合 = 把封面全删的形状,只有人工显式确认的路径才允许)。 + var PLP_GC_BUSY = false + function plpGcCoverFiles (FA, keepNames, opts) { + var o = opts || {} + if (!FA || typeof FA.list !== 'function' || typeof FA.remove !== 'function') return Promise.resolve({ removed: 0, bytes: 0, skipped: 'no-fs' }) + if (PLP_GC_BUSY) return Promise.resolve({ removed: 0, bytes: 0, skipped: 'busy' }) + var keep = {} + var kept = 0 + ;(keepNames || []).forEach(function (n) { + n = String(n || '') + if (n) { keep[n] = 1; kept++ } + }) + if (!kept && !o.manual) return Promise.resolve({ removed: 0, bytes: 0, skipped: 'empty' }) + PLP_GC_BUSY = true + return Promise.resolve(FA.list()).then(function (list) { + var rows = Array.isArray(list) ? list : ((list && list.files) || []) + var victims = rows.filter(function (f) { + var name = String((f && f.name) || '') + if (!name || keep[name]) return false + return /\.(jpg|jpeg|png|webp)$/i.test(name) + }) + var bytes = 0 + victims.forEach(function (f) { bytes += Number(f && f.size) || 0 }) + var removed = 0 + var seq = Promise.resolve() + victims.forEach(function (f) { + seq = seq.then(function () { + return Promise.resolve(FA.remove(f.name)).then(function (r) { if (!r || r.ok !== false) removed++ }).catch(function () {}) + }) + }) + return seq.then(function () { PLP_GC_BUSY = false; return { removed: removed, bytes: bytes } }) + }).catch(function () { PLP_GC_BUSY = false; return { removed: 0, bytes: 0, skipped: 'error' } }) + } + // 从词条列表里取「被引用的封面文件名」 + function plpCoverNamesOf (list) { + var out = [] + ;(list || []).forEach(function (p) { + var c = p && p.cover + if (c && typeof c === 'object' && c.img) out.push(String(c.img)) + }) + return out + } + function renderPluginSettings () { var root = el('div', { class: 'iwb-plp-settings' }) var state = { prompts: [], groups: [] } @@ -227,7 +283,9 @@ var st = rs[1] || {} var covers = state.prompts.filter(function (p) { return p && p.cover }).length var size = st.bytes || 0 - usage.textContent = (rs[0] || 'plugin-data/promptlib') + ' · ' + (size > 1024 ? (size / 1024).toFixed(0) + ' KB' : size + ' B') + ' · ' + state.prompts.length + ' 条 · ' + state.groups.length + ' 个分组 · ' + covers + ' 张封面' + var files = Number(st.count) || 0 + // v1.11.0:封面「引用数 / 文件数」分开显示 —— 两者不等就说明有孤儿文件可清。 + usage.textContent = (rs[0] || 'plugin-data/promptlib') + ' · ' + (size > 1024 ? (size / 1024).toFixed(0) + ' KB' : size + ' B') + ' · ' + state.prompts.length + ' 条 · ' + state.groups.length + ' 个分组 · 封面 ' + covers + ' 张 / 文件 ' + files + ' 个' }) } @@ -274,9 +332,7 @@ return Promise.all(payload.prompts.map(function (p) { var c = p && p.cover if (typeof c !== 'string' || c.indexOf('data:') !== 0 || !PLP_CTX.files) return Promise.resolve(p) - var h = 5381 - for (var i = 0; i < c.length; i++) h = ((h << 5) + h + c.charCodeAt(i)) >>> 0 - var name = 'c' + h.toString(36) + '.jpg' + var name = coverFileName(c) return Promise.resolve(PLP_CTX.files.put(name, c)).then(function (res) { return res && res.ok ? Object.assign({}, p, { cover: { img: name } }) : p }).catch(function () { return p }) })).then(function (incoming) { var byId = {} @@ -306,13 +362,39 @@ var s3 = el('div', { class: 'iwb-plp-ssec' }) s3.appendChild(el('div', { class: 'iwb-plp-stitle', text: '数据位置' })) s3.appendChild(usage) + // v1.11.0:未引用封面回收。换封面/删词条会留下孤儿文件,久了把 64MB 沙箱占满。 + // 自动清理已在面板加载后跑一次;这里是「我想立刻清」的显式入口(会先读一次最新数据做引用集合)。 + var gcBtn = el('button', { class: 'iwb-btn iwb-btn-sm', title: '删除已不再被任何词条引用的封面图片文件', text: '清理未引用封面' }) var openBtn = el('button', { class: 'iwb-btn iwb-btn-sm', text: '打开数据目录' }) openBtn.addEventListener('click', function () { var ctx = PLP_CTX || {} if (!ctx.promptlib || typeof ctx.promptlib.openPath !== 'function') { plpNotify('当前客户端不支持打开目录', 'err'); return } Promise.resolve(ctx.promptlib.openPath('plugin-data/promptlib')).catch(function (e) { plpNotify('打开失败:' + ((e && e.message) || e), 'err') }) }) - s3.appendChild(el('div', { class: 'iwb-plp-sbtns' }, openBtn)) + gcBtn.addEventListener('click', function () { + var ctx = PLP_CTX || {} + var FA = fileApi(ctx) + if (!FA) { plpNotify('文件能力不可用,无法清理', 'err'); return } + gcBtn.disabled = true; status.textContent = '正在清理未引用封面…' + // 每次现读一次数据:设置页可能比面板更"新"(面板没开时用户刚删过词条) + Promise.resolve(plpLoad()).then(function (d) { + state.prompts = (d && d.prompts) || state.prompts + state.groups = (d && d.groups) || state.groups + return plpGcCoverFiles(FA, plpCoverNamesOf(state.prompts), { manual: true }) + }).then(function (r) { + gcBtn.disabled = false + if (!r || !r.removed) { + status.textContent = (r && r.skipped === 'no-fs') ? '文件能力不可用,无法清理' : '没有未引用的封面(文件已经是最简状态)' + } else { + status.textContent = '✓ 已清理 ' + r.removed + ' 个未引用封面' + (r.bytes ? '(约 ' + Math.max(1, Math.round(r.bytes / 1024)) + ' KB)' : '') + } + refreshUsage(); paint(); plpNotify(status.textContent) + }).catch(function (e) { + gcBtn.disabled = false + status.textContent = '清理失败:' + ((e && e.message) || e) + }) + }) + s3.appendChild(el('div', { class: 'iwb-plp-sbtns' }, gcBtn, openBtn)) root.appendChild(s3) plpLoad().then(function (d) { state.prompts = d.prompts || []; state.groups = d.groups || []; paint(); refreshUsage() }) @@ -361,11 +443,6 @@ var SCHEMA = 3 var migrateDone = false - function hashName (s) { - var h = 5381 - for (var i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) >>> 0 - return 'c' + h.toString(36) - } function coverNameOf (p) { var c = p && p.cover if (c && typeof c === 'object' && c.img) return String(c.img) @@ -414,7 +491,7 @@ var jobs = list.map(function (p) { var c = p && p.cover if (!FILEAPI || typeof c !== 'string' || c.indexOf('data:') !== 0) return Promise.resolve(p) - var name = hashName(c) + '.jpg' + var name = coverFileName(c) return Promise.resolve(FILEAPI.put(name, c)).then(function (res) { return res && res.ok ? Object.assign({}, p, { cover: { img: name } }) : p }).catch(function () { return p }) @@ -442,9 +519,7 @@ var failed = 0 Promise.all(need.map(function (p) { var c = p.cover - var h = 5381 - for (var i = 0; i < c.length; i++) h = ((h << 5) + h + c.charCodeAt(i)) >>> 0 - var name = 'c' + h.toString(36) + '.jpg' + var name = coverFileName(c) return Promise.resolve(FILEAPI.put(name, c)).then(function (r) { if (r && r.ok) return { id: p.id, item: Object.assign({}, p, { cover: { img: name } }) } failed++ @@ -469,6 +544,46 @@ } }).catch(function () {}) } + + // ===== v1.11.0:封面文件治理(P1)===== + // 背景:封面是「按内容哈希命名的图片文件」。换封面 / 删词条 / 取消编辑都会留下**不再被引用的文件**, + // 时间久了 64MB 沙箱被垃圾占满(用户看到「总量超限,请先清理」却找不到东西可清)。 + // 纪律(每条都对应一次真实误删风险): + // ① 自动 GC 只在「数据确实来自插件 JSON」时跑:数据没读到 ⇒ keep 集合为空 ⇒ 会把封面全删; + // ② 库为空时自动 GC 也不跑(keep 为空同样是删光的形状); + // ③ 刚 put 进沙箱、还没被 prompts 引用的名字进 pending,GC 必须跳过; + // ④ 只删图片扩展名的文件;两张词条共用同一封面 = 同一个名字,天然保留。 + var pendingCoverNames = {} + var dataFromPlugin = false + + // dataURL → { img: 文件名 };失败原样返回(宁可留着内联 base64,也不丢封面) + function ensureCoverFile (cover) { + if (!FILEAPI || typeof cover !== 'string' || cover.indexOf('data:') !== 0) return Promise.resolve(cover) + var name = coverFileName(cover) + pendingCoverNames[name] = 1 + return Promise.resolve(FILEAPI.put(name, cover)).then(function (r) { + if (r && r.ok) return { img: name } + delete pendingCoverNames[name] + return cover + }).catch(function () { delete pendingCoverNames[name]; return cover }) + } + // 回收未被任何词条引用的封面文件(判定在模块级 plpGcCoverFiles,设置页复用同一套)。 + // 返回 { removed, bytes, skipped } + function gcCoverFiles (opts) { + var o = opts || {} + // 自动路径(启动后 / 删词条后):数据不是从插件 JSON 读来的就**不删**—— + // 那种情况下 prompts 可能是空数组,keep 集合同样为空,一刀下去封面全没。 + if (!o.manual && !dataFromPlugin) return Promise.resolve({ removed: 0, bytes: 0, skipped: 'no-source' }) + var names = [] + prompts.forEach(function (p) { var n = coverNameOf(p); if (n) names.push(n) }) + Object.keys(pendingCoverNames).forEach(function (n) { names.push(n) }) + return plpGcCoverFiles(FILEAPI, names, o) + } + // 启动后就地跑一次:延迟到 convertInlineCovers 的写入之后,避免删掉刚落盘的封面 + function scheduleCoverGc (delay) { + setTimeout(function () { gcCoverFiles() }, delay || 4000) + } + function load () { return loadOnce(0) } try { ctx.storage && ctx.storage.set('diag', JSON.stringify({ files: !!ctx.files, keys: Object.keys(ctx.promptlib || {}).slice(0, 24), hasPut: typeof (ctx.promptlib || {}).filePut, hasData: !!ctx.data })) } catch (e) { /* ignore */ } function loadOnce (attempt) { @@ -486,11 +601,13 @@ loadError = '' prompts = d.prompts.map(normalize) groups = Array.isArray(d.groups) ? d.groups : [] + dataFromPlugin = true render() convertInlineCovers() + scheduleCoverGc(4000) return true } - if (d && Array.isArray(d.prompts) && !d.prompts.length) { prompts = []; groups = []; render(); return true } + if (d && Array.isArray(d.prompts) && !d.prompts.length) { prompts = []; groups = []; dataFromPlugin = true; render(); return true } return migrateFromHost() }).catch(function () { return legacyLoad() }) } @@ -1102,9 +1219,7 @@ return Promise.all(payload.prompts.map(function (p) { var c = p && p.cover if (typeof c !== 'string' || c.indexOf('data:') !== 0 || !FILEAPI) return Promise.resolve(p) - var h = 5381 - for (var i2 = 0; i2 < c.length; i2++) h = ((h << 5) + h + c.charCodeAt(i2)) >>> 0 - var name = 'c' + h.toString(36) + '.jpg' + var name = coverFileName(c) return Promise.resolve(FILEAPI.put(name, c)).then(function (res) { return res && res.ok ? Object.assign({}, p, { cover: { img: name } }) : p }).catch(function () { return p }) @@ -1305,7 +1420,7 @@ var incoming = normalize({ id: uid('q'), name: name, text: item.text, group: String(item.group || ''), tags: item.tags || [] }) var cv = item.cover var ready = (typeof cv === 'string' && cv.indexOf('data:') === 0 && FILEAPI) - ? Promise.resolve(FILEAPI.put(hashName(cv) + '.jpg', cv)).then(function (res) { return res && res.ok ? Object.assign({}, incoming, { cover: { img: hashName(cv) + '.jpg' } }) : incoming }).catch(function () { return incoming }) + ? Promise.resolve(FILEAPI.put(coverFileName(cv), cv)).then(function (res) { return res && res.ok ? Object.assign({}, incoming, { cover: { img: coverFileName(cv) } }) : incoming }).catch(function () { return incoming }) : Promise.resolve(incoming) return ready.then(function (p2) { prompts = prompts.concat([p2]) @@ -1394,9 +1509,7 @@ return Promise.all(payload.prompts.map(function (p) { var c = p && p.cover if (typeof c !== 'string' || c.indexOf('data:') !== 0 || !FILEAPI) return Promise.resolve(p) - var h = 5381 - for (var i2 = 0; i2 < c.length; i2++) h = ((h << 5) + h + c.charCodeAt(i2)) >>> 0 - var name = 'c' + h.toString(36) + '.jpg' + var name = coverFileName(c) return Promise.resolve(FILEAPI.put(name, c)).then(function (res) { return res && res.ok ? Object.assign({}, p, { cover: { img: name } }) : p }).catch(function () { return p }) @@ -1494,7 +1607,7 @@ ask('删除提示词「' + (p.name || '未命名') + '」?', { title: '删除提示词', okText: '删除' }).then(function (ok) { if (!ok) return dlg.close() - save(prompts.filter(function (x) { return x.id !== p.id })).then(function () { notify('已删除') }) + save(prompts.filter(function (x) { return x.id !== p.id })).then(function () { notify('已删除'); scheduleCoverGc(1200) }) }) }) cp.addEventListener('click', function () { Promise.resolve(api.copy(filled())).then(function (r) { if (r && r.ok === false) notify('复制失败', 'err'); else notify('已复制全文') }) }) @@ -1561,15 +1674,19 @@ rd.onload = function () { Promise.resolve(api.putCover(String(rd.result || ''))).then(function (r) { if (!(r && r.ok && r.ref)) { notify('封面上传失败', 'err'); return } - draft.cover = r.ref - dirty = true - Object.keys(coverCache).forEach(function (k) { if (k.indexOf(draft.id + '|') === 0) delete coverCache[k] }) - Promise.resolve(api.coverUrl(r.ref)).then(function (u) { - if (u && u.url) { - draft._coverUrl = u.url - coverCache[draft.id + '|s:' + String(r.ref).slice(-32)] = u.url - } - repaint(); render(); notify('封面已更新') + // v1.11.0:上传即落成文件(数据里只留文件名)—— + // 之前 draft.cover 存的是 dataURL,doSave 直接把它写进 JSON,一条封面就把数据文件顶大几十 KB。 + return ensureCoverFile(r.ref).then(function (cover) { + draft.cover = cover + dirty = true + Object.keys(coverCache).forEach(function (k) { if (k.indexOf(draft.id + '|') === 0) delete coverCache[k] }) + return resolveCoverUrl(cover).then(function (u) { + if (u) { + draft._coverUrl = u + coverCache[draft.id + '|s:' + String(cover).slice(-32)] = u + } + repaint(); render(); notify('封面已更新') + }) }) }).catch(function () { notify('封面上传失败', 'err') }) } @@ -1706,23 +1823,29 @@ var text = String(c.text || '').trim() if (!text) { notify('提示词内容不能为空', 'err'); return } var name = String(c.name || '').trim() || ('提示词 ' + text.slice(0, 8) + '…') - var item = { id: c.id, name: name, text: text, tags: c.tags, group: String(c.group || '').trim(), cover: c.cover, vars: c.vars || [] } - var list = isNew ? prompts.concat([item]) : prompts.map(function (x) { return x.id === item.id ? item : x }) - var gs = groupsOf().slice() - if (item.group && !gs.some(function (g) { return g.name === item.group })) gs.push(groupRef(item.group)) - close() - save(list, gs).then(function () { - notify(isNew ? '已创建' : '已保存') - if (!isNew) { try { openDetailModal(item) } catch (e) { /* ignore */ } } - }) + // v1.11.0:保存前把内联封面落成文件(数据里只留 { img }),避免 base64 把 JSON 顶大 + saveBtn.disabled = true + ensureCoverFile(c.cover).then(function (finalCover) { + var item = { id: c.id, name: name, text: text, tags: c.tags, group: String(c.group || '').trim(), cover: finalCover, vars: c.vars || [] } + var list = isNew ? prompts.concat([item]) : prompts.map(function (x) { return x.id === item.id ? item : x }) + var gs = groupsOf().slice() + if (item.group && !gs.some(function (g) { return g.name === item.group })) gs.push(groupRef(item.group)) + close() + return save(list, gs).then(function () { + notify(isNew ? '已创建' : '已保存') + if (!isNew) { try { openDetailModal(item) } catch (e) { /* ignore */ } } + }) + }).catch(function () { saveBtn.disabled = false; notify('保存失败', 'err') }) } saveBtn.addEventListener('click', doSave) cancelBtn.addEventListener('click', function () { close(); if (!isNew && p) { try { openDetailModal(p) } catch (e) { /* ignore */ } } }) dupBtn.addEventListener('click', function () { var c = collect() - var copy = Object.assign({}, c, { id: uid('q'), name: (String(c.name || '提示词').trim()) + ' 副本' }) close() - save(prompts.concat([copy])).then(function () { notify('已另存副本') }) + ensureCoverFile(c.cover).then(function (cover) { + var copy = Object.assign({}, c, { id: uid('q'), name: (String(c.name || '提示词').trim()) + ' 副本', cover: cover }) + return save(prompts.concat([copy])).then(function () { notify('已另存副本') }) + }).catch(function () { notify('另存副本失败', 'err') }) }) insBtn.addEventListener('click', function () { var c = collect() @@ -1878,7 +2001,7 @@ global.IWBPluginHost.register({ id: 'promptlib', name: '提示词库', - version: '1.10.1', + version: '1.11.0', apiVersion: 1, capabilities: ['panels', 'promptlib', 'nodeTypes', 'canvas', 'canvasWrite'], data: { schemaVersion: 3, maxBytes: 4 * 1024 * 1024 }, @@ -1917,9 +2040,7 @@ return Promise.all(list.map(function (p) { var c = p && p.cover if (typeof c !== 'string' || c.indexOf('data:') !== 0) return Promise.resolve(p) - var h = 5381 - for (var i2 = 0; i2 < c.length; i2++) h = ((h << 5) + h + c.charCodeAt(i2)) >>> 0 - var name = 'c' + h.toString(36) + '.jpg' + var name = coverFileName(c) return Promise.resolve(FA.put(name, c)).then(function (res) { return res && res.ok ? Object.assign({}, p, { cover: { img: name } }) : p }).catch(function () { return p }) diff --git a/plugins/promptlib/manifest.json b/plugins/promptlib/manifest.json index ca1e817..2ce1c35 100644 --- a/plugins/promptlib/manifest.json +++ b/plugins/promptlib/manifest.json @@ -1,7 +1,7 @@ { "id": "promptlib", "name": "提示词库", - "version": "1.10.1", + "version": "1.11.0", "apiVersion": 1, "main": "main.js", "style": "styles.css", @@ -13,7 +13,7 @@ "提示词" ], "files": { - "main.js": "41d73c02cf4791312d0b922b572ff991a83341aabe3a000a84e9b249e77afac8", - "styles.css": "1ff5e60079166968cfaed95c875a1347884d5476090419491e317cdec2c4e6cd" + "main.js": "0e1bd0f235b05b3edbdccd19ffe24791f0ce82bb5180ebe5a60dcaa6b2ed3ce8", + "styles.css": "23fd4beb4f5b89be1f763ee7221e3dbdafced85afc378cd5cc1a9e03b14d7046" } } diff --git a/plugins/promptlib/styles.css b/plugins/promptlib/styles.css index 017f51c..3755941 100644 --- a/plugins/promptlib/styles.css +++ b/plugins/promptlib/styles.css @@ -351,7 +351,7 @@ flex: 1 1 auto; /* v1.10.1:详情底部分享组(文本/文件分享)与插入组之间的竖向分割线 */ .iwb-plp-dialog .iwb-plp-foot-vsep { display: inline-block; width: 1px; height: 18px; flex: 0 0 auto; -align-self: center; margin: 0 13px; background: var(--iwb-border); +align-self: center; margin: 0 12px; background: var(--iwb-border); } .iwb-plp-dialog .iwb-section-sub { margin-top: 2px; @@ -568,12 +568,12 @@ body.iwb-plp-dragging, body.iwb-plp-dragging *{user-select:none!important;-webki 文字仍由 textarea 自己画(可见),所以插入点/点击/选区完全不受影响。 注:v1.8.20 停用高亮层是因为当时「透明 textarea + 背层画文字」两层文字错位;本版不画文字,只画色块,不会复发。 */ .iwb-plp-ewrap .iwb-plp-hl{display:block!important;color:transparent!important;-webkit-text-fill-color:transparent!important} -.iwb-plp-hlvar{color:transparent!important;-webkit-text-fill-color:transparent!important;background:color-mix(in srgb, var(--iwb-plp-accent, #7c4dff) 16%, transparent);border-radius:4px;box-shadow:0 0 0 1px color-mix(in srgb, var(--iwb-plp-accent, #7c4dff) 22%, transparent)} +.iwb-plp-hlvar{color:transparent!important;-webkit-text-fill-color:transparent!important;background:color-mix(in srgb, var(--iwb-plp-accent, #7c4dff) 16%, transparent);border-radius:6px;box-shadow:0 0 0 1px color-mix(in srgb, var(--iwb-plp-accent, #7c4dff) 22%, transparent)} .iwb-plp-ewrap .iwb-plp-etext{color:var(--iwb-text,#2a2f36)!important;background:transparent!important} /* v1.8.21:正文文字必须可见(覆盖旧的 transparent !important) */ .iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap .iwb-plp-etext{color:var(--iwb-text,#2a2f36)!important;caret-color:var(--iwb-text,#2a2f36)!important;-webkit-text-fill-color:var(--iwb-text,#2a2f36)!important} /* v1.9.3:右侧变量名与详情正文里的变量也用主色呼应(只读区,零功能风险) */ .iwb-plp-dialog .iwb-plp-vname{color:var(--iwb-plp-accent,#5a3fd0)} -.iwb-plp-dialog .iwb-plp-dvar{color:var(--iwb-plp-accent,#5a3fd0);background:var(--iwb-plp-accent-soft,#f1ecff);border-radius:4px;padding:0 2px} +.iwb-plp-dialog .iwb-plp-dvar{color:var(--iwb-plp-accent,#5a3fd0);background:var(--iwb-plp-accent-soft,#f1ecff);border-radius:6px;padding:0 2px} /* 回滚开关:若真机发现任何点击/光标异常,把下行打开即回到 v1.8.20 纯 textarea 状态。 .iwb-plp-ewrap .iwb-plp-hl{display:none!important} */ diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index cf71fbc..2e5c5d6 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "image-workbench" -version = "3.26.58" +version = "3.26.59" description = "无限画布 · 生图工作台桌面版" authors = ["malongan"] license = "" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 27f6361..2b78ebf 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "image-workbench", - "version": "3.26.58", + "version": "3.26.59", "identifier": "com.malongan.imageworkbench", "build": { "frontendDist": "../dist", diff --git a/src/plugin-data.js b/src/plugin-data.js index b6810d4..2c4db7f 100644 --- a/src/plugin-data.js +++ b/src/plugin-data.js @@ -230,12 +230,61 @@ return { bytes: n, count: all.length } } + // ---- 插件文件(plugin-data//files/,v3.26.59)---- + // 为什么放在这层:备份/还原只认 IWBPluginData 一个入口。此前只备份 JSON, + // 于是「提示词封面」这类图片文件换机后全丢(标题栏说"已恢复",打开却是灰块)。 + // 内存纪律:清单(id/name/size)一次性给出;字节**逐条读**(调用方写完即放手), + // 不做"全部读进数组再写包"——插件文件单插件上限 64MB,攒起来会 OOM。 + function pluginFilesFacade () { + const F = global.IWBStorageFile + const pf = F && F.pluginFiles + return (pf && typeof pf.listAll === 'function') ? pf : null + } + async function listFiles () { + const pf = pluginFilesFacade() + if (!pf) return [] + let groups = [] + try { groups = await pf.listAll() } catch (e) { groups = [] } + const out = [] + for (const g of (Array.isArray(groups) ? groups : [])) { + if (!g || !g.id) continue + for (const f of (g.files || [])) { + if (!f || !f.name) continue + out.push({ id: String(g.id), name: String(f.name), size: Number(f.size) || 0 }) + } + } + return out + } + async function readFile (id, name) { + const pf = pluginFilesFacade() + if (!pf || typeof pf.readBytes !== 'function') return null + try { return await pf.readBytes(String(id), String(name)) } catch (e) { return null } + } + // list = [{ id, name, data: dataURL }],单条失败不影响其它 + async function restoreFiles (list) { + const F = global.IWBStorageFile + const pf = F && F.pluginFiles + if (!pf || typeof pf.put !== 'function') return 0 + let n = 0 + for (const it of (Array.isArray(list) ? list : [])) { + if (!it || !it.id || !it.name || !it.data) continue + try { + const r = await pf.put(String(it.id), String(it.name), String(it.data)) + if (r && r.ok) n++ + } catch (e) { /* 单个失败不影响其它 */ } + } + return n + } + global.IWBPluginData = { create: create, stripLegacy: stripLegacy, collectAll: collectAll, restoreAll: restoreAll, totalSize: totalSize, + listFiles: listFiles, + readFile: readFile, + restoreFiles: restoreFiles, _bytesOf: bytesOf, } })(typeof window !== 'undefined' ? window : globalThis) \ No newline at end of file diff --git a/src/storage-backup.js b/src/storage-backup.js index 949f8e0..32b15af 100644 --- a/src/storage-backup.js +++ b/src/storage-backup.js @@ -7,8 +7,8 @@ const checksum = config.checksum const payload = (data) => { const copy = JSON.parse(JSON.stringify(data || {})) - delete copy.checksum - delete copy.imagesData + // 与 app.js 的 backupChecksumPayload 同口径:字节载荷(图片 / 插件文件)不进校验和 + delete copy.checksum; delete copy.imagesData; delete copy.images; delete copy.pluginFiles; delete copy.pluginFilesData return copy } return { diff --git a/src/storage-file.js b/src/storage-file.js index ce2f663..6664378 100644 --- a/src/storage-file.js +++ b/src/storage-file.js @@ -656,6 +656,37 @@ return { ok: true, files: files, bytes: files.reduce((n, f) => n + (f.size || 0), 0), count: files.length } } catch (e) { return { ok: false, files: [], bytes: 0, count: 0 } } } + // 备份用(v3.26.59):读原始字节,ZIP 直接写字节 —— 不做 dataURL 往返,省掉 33% 的 base64 膨胀。 + async function pluginFileReadBytes (id, name) { + try { + if (!pluginFileNameOk(name)) return null + const u8 = await fs().readFile(await join(await pluginFilesDir(id), name)) + return (u8 && u8.length) ? u8 : null + } catch (e) { return null } + } + // 备份用:枚举「所有插件」的插件文件(plugin-data//files/)。 + // 不调 pluginFilesDir(那个会 mkdir):没有 files 目录的插件直接跳过。 + async function pluginFilesListAll () { + const out = [] + let entries = [] + try { entries = await fs().readDir(await pluginDataDir()) } catch (e) { return out } + for (const e of entries) { + if (!e || !e.isDirectory) continue + const id = String(e.name || '') + if (!/^[A-Za-z0-9][A-Za-z0-9._-]{1,63}$/.test(id)) continue + let fe = [] + try { fe = await fs().readDir(await join(await pluginDataDir(), id, PFILE_DIR)) } catch (err) { continue } + const files = [] + for (const f of fe) { + if (!f || f.isDirectory || !pluginFileNameOk(f.name)) continue + let size = 0 + try { const u8 = await fs().readFile(await join(await pluginDataDir(), id, PFILE_DIR, f.name)); size = u8 ? u8.length : 0 } catch (err2) { size = 0 } + files.push({ name: f.name, size: size }) + } + if (files.length) { files.sort((a, b) => a.name.localeCompare(b.name)); out.push({ id: id, files: files }) } + } + return out + } async function loadInto() { // data.json 不存在 ⇒ 把当前 WebView 里的数据迁过去(只做一次) @@ -1318,7 +1349,7 @@ enabled, ready: init, flush, runtime, pickDir, switchTo, migrateTo, deleteImageBytes, deleteGalleryBytesFor, gcImages, rotateTrash, galleryThumb, readDisplayThumb, readDisplayThumbUrl, writeDisplayThumb, writeDisplayThumbBlob, pruneThumbs, cleanupLegacy, maintain, plugins: { manifest: pluginManifest, read: pluginRead, write: pluginWrite, remove: pluginRemove, dir: pluginDir, listLocal: pluginListLocal, listDirs: pluginListDirs, readFile: pluginReadFile, writeFile: pluginWriteFile, writeBinary: pluginWriteBinary, mkdir: pluginMkdir, removeDir: pluginRemoveDir, renameDir: pluginRenameDir, existsDir: pluginExistsDir }, pluginData: { read: pluginDataRead, write: pluginDataWrite, remove: pluginDataRemove, list: pluginDataList }, - pluginFiles: { put: pluginFilePut, get: pluginFileGet, list: pluginFileList, remove: pluginFileRemove, stat: pluginFileStat, dir: pluginFilesDir }, + pluginFiles: { put: pluginFilePut, get: pluginFileGet, list: pluginFileList, remove: pluginFileRemove, stat: pluginFileStat, dir: pluginFilesDir, readBytes: pluginFileReadBytes, listAll: pluginFilesListAll }, storage: () => storage, kv: () => kv, dir: () => dir, diff --git a/src/ui-backup-modal.js b/src/ui-backup-modal.js index c325223..e3666cb 100644 --- a/src/ui-backup-modal.js +++ b/src/ui-backup-modal.js @@ -147,6 +147,18 @@ function BackupModal(props) { for (const f of (Array.isArray(outputItems) ? outputItems : [])) sum += Number(f && f.size) || 0 return sum } + // ---- 插件文件(plugin-data//files/,v3.26.59)---- + // 只收清单,写包时逐条读字节(与图片同一套内存纪律:写一张放一张,不攒数组)。 + const pdata = () => ((typeof window !== 'undefined') ? window.IWBPluginData : null) + const collectPluginFiles = async () => { + try { const pd = pdata(); if (pd && typeof pd.listFiles === 'function') return await pd.listFiles() } catch (e) { /* 清单失败不影响主备份 */ } + return [] + } + const readPluginFileBytes = async (f) => { + try { const pd = pdata(); const b = (pd && typeof pd.readFile === 'function') ? await pd.readFile(f.id, f.name) : null; return (b && b.length) ? b : null } catch (e) { return null } + } + const mimeOfPluginFile = (name) => /\.png$/i.test(name) ? 'image/png' : (/\.webp$/i.test(name) ? 'image/webp' : 'image/jpeg') + const bytesToBase64 = (u8) => { let s = ''; for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000)); return btoa(s) } const doBackup = async () => { setBkBusy(true); setBkMsg(null) try { @@ -177,25 +189,30 @@ function BackupModal(props) { const refMeta = await collectBackupImages() const galleryMeta = (bk.outputs && items.outputs) ? (await collectBackupOutputImages(items.outputs)) : [] const imgMeta = refMeta.concat(galleryMeta.map((im) => ({ key: im.key, name: im.name }))) + // 插件文件(如提示词封面):跟 items.pluginData 同进退,不单独设勾选项 + const pluginFileMeta = await collectPluginFiles() + const pluginFileBytes = pluginFileMeta.reduce((n, f) => n + (Number(f && f.size) || 0), 0) // 导出前体积预估 + 二次确认:几百 MB 的图库导出会持续拉高内存,先让用户确认 - if (imgMeta.length) { - const estMB = estimateBackupBytes(items.outputs) / 1048576 - const needConfirm = estMB >= 20 || imgMeta.length >= 20 + if (imgMeta.length || pluginFileMeta.length) { + const estMB = (estimateBackupBytes(items.outputs) + pluginFileBytes) / 1048576 + const needConfirm = estMB >= 20 || (imgMeta.length + pluginFileMeta.length) >= 20 const sizeText = estMB >= 1 ? ('约 ' + estMB.toFixed(0) + ' MB') : '未记录(按张数估算偏大)' + const countText = imgMeta.length + ' 张图片' + (pluginFileMeta.length ? '(另含 ' + pluginFileMeta.length + ' 个插件文件)' : '') if (needConfirm && typeof window !== 'undefined' && typeof window.confirm === 'function') { - const okGo = await askConfirm('本次备份包含 ' + imgMeta.length + ' 张图片,预计体积 ' + sizeText + '。\n导出期间内存占用会明显上升,图库很大时页面会变慢。\n确定继续导出吗?', { title: '导出备份', okText: '继续导出' }) + const okGo = await askConfirm('本次备份包含 ' + countText + ',预计体积 ' + sizeText + '。\n导出期间内存占用会明显上升,图库很大时页面会变慢。\n确定继续导出吗?', { title: '导出备份', okText: '继续导出' }) if (!okGo) { - setBkMsg({ type: 'err', text: '已取消导出(' + imgMeta.length + ' 张图片 / ' + sizeText + ')' }) + setBkMsg({ type: 'err', text: '已取消导出(' + countText + ' / ' + sizeText + ')' }) return } } } - const core = { app: 'image-workbench', kind: 'backup', backupVersion: 3, schemaVersion: SchemaVersions.backup, at: Date.now(), items, images: imgMeta } + const core = { app: 'image-workbench', kind: 'backup', backupVersion: 3, schemaVersion: SchemaVersions.backup, at: Date.now(), items, images: imgMeta, pluginFiles: pluginFileMeta } const exported = ModularBackupStore ? await ModularBackupStore.export(items, { extra: { images: imgMeta, at: core.at } }) : null const checksum = await wSha256(JSON.stringify(backupChecksumPayload(core))) - const manifest = exported && exported.ok ? Object.assign({}, exported.value, { images: imgMeta }) : Object.assign({}, core, { checksum }) + const manifest = exported && exported.ok ? Object.assign({}, exported.value, { images: imgMeta, pluginFiles: pluginFileMeta }) : Object.assign({}, core, { checksum }) const ts = new Date().toISOString().slice(0, 10) let exportedImages = 0 + let exportedPluginFiles = 0 // 主路径:原生 ZIP 写入器(STORE)——逐张读 → 立即以 Blob 写包 → 立即释放,堆里同时只有一张图 let zipBlob = null try { @@ -208,11 +225,19 @@ function BackupModal(props) { exportedImages++ await new Promise((r) => setTimeout(r, 0)) // 让出事件循环,给 GC 回收上一张的 base64 字符串 } + // 插件文件:plugin-files/<插件id>/<文件名>,写原始字节(不做 base64 往返) + for (const pf of pluginFileMeta) { + const bytes = await readPluginFileBytes(pf) + if (!bytes) continue + await zw.add('plugin-files/' + pf.id + '/' + pf.name, new Blob([bytes])) + exportedPluginFiles++ + await new Promise((r) => setTimeout(r, 0)) + } zipBlob = zw.finish() - } catch (e) { zipBlob = null; exportedImages = 0 } + } catch (e) { zipBlob = null; exportedImages = 0; exportedPluginFiles = 0 } if (zipBlob) { wDownloadBlob(zipBlob, 'image-workbench-backup-' + ts + '.zip') - setBkMsg({ type: 'ok', text: '✓ 已导出 ZIP 备份(' + Object.keys(items).join(' / ') + ' + ' + exportedImages + ' 张图片),含校验和,恢复时可校验' }) + setBkMsg({ type: 'ok', text: '✓ 已导出 ZIP 备份(' + Object.keys(items).join(' / ') + ' + ' + exportedImages + ' 张图片' + (exportedPluginFiles ? ' + ' + exportedPluginFiles + ' 个插件文件' : '') + '),含校验和,恢复时可校验' }) } else { // 兜底:原生写入器失败 → JSON 内嵌图片 base64。整包字符串无法避免,仅作兜底。 // (原来这里还有一条「CDN 加载 JSZip 写 ZIP」的兜底:线上 CSP script-src 'self' 会直接拦死该 script, @@ -228,13 +253,22 @@ function BackupModal(props) { if (data) imagesData.push({ key: im.key, name: im.name, data }) } exportedImages = imagesData.length - const m2 = Object.assign({}, manifest, { imagesData }) + const pluginFilesData = [] + for (const pf of pluginFileMeta) { + const bytes = await readPluginFileBytes(pf) + if (!bytes) continue + pluginFilesData.push({ id: pf.id, name: pf.name, data: 'data:' + mimeOfPluginFile(pf.name) + ';base64,' + bytesToBase64(bytes) }) + } + exportedPluginFiles = pluginFilesData.length + const m2 = Object.assign({}, manifest, { imagesData, pluginFilesData }) delete m2.images + // 插件文件/图片的键都进 payload 的排除项(见 backupChecksumPayload),这里重算才能自洽 + m2.checksum = await wSha256(JSON.stringify(backupChecksumPayload(m2))) const blob = new Blob([JSON.stringify(m2)], { type: 'application/json' }) wDownloadBlob(blob, 'image-workbench-backup-' + ts + '.json') - setBkMsg({ type: 'ok', text: '✓ 已导出备份(JSON 内嵌 ' + exportedImages + ' 张图片;联网时导出 ZIP 更小更稳)' }) + setBkMsg({ type: 'ok', text: '✓ 已导出备份(JSON 内嵌 ' + exportedImages + ' 张图片' + (exportedPluginFiles ? ' + ' + exportedPluginFiles + ' 个插件文件' : '') + ';可联网时导出 ZIP 更小更稳)' }) } - wLog('backup', '导出备份:' + Object.keys(items).join('/') + ' + 图片 ' + exportedImages) + wLog('backup', '导出备份:' + Object.keys(items).join('/') + ' + 图片 ' + exportedImages + ' + 插件文件 ' + exportedPluginFiles) // 记录"上次导出"时间(2026-11-07):自动备份与数据同在浏览器里,导出磁盘才是异地保险 try { const stx = _lstore(); if (stx) stx.rawSet('iwb_backup_last_export_at', String(Date.now())) } catch (e) { /* ignore */ } @@ -264,7 +298,7 @@ function BackupModal(props) { } return { providers: ps.length, models, plainKeys, keepKeys, llmProviders: llmPs.length } } - const acceptRestoreData = async (data, images) => { + const acceptRestoreData = async (data, images, pluginFiles) => { if (!data || data.kind !== 'backup' || !data.items || typeof data.items !== 'object' || Array.isArray(data.items)) throw new Error('不是本工具的备份文件') if (data.checksum) { const h = await wSha256(JSON.stringify(backupChecksumPayload(data))) @@ -283,6 +317,11 @@ function BackupModal(props) { }) nd.images = zipImages if (!nd.images.length && Array.isArray(nd.imagesData)) nd.images = nd.imagesData.map((x) => ({ key: x.key, name: x.name, data: x.data })) + // 插件文件:ZIP 里直接拿到 dataURL;JSON 兜底看 pluginFilesData + const pfs = Array.isArray(pluginFiles) && pluginFiles.length + ? pluginFiles + : (Array.isArray(nd.pluginFilesData) ? nd.pluginFilesData.map((x) => ({ id: x.id, name: x.name, data: x.data })) : []) + nd.pluginFiles = pfs.filter((x) => x && x.id && x.name && x.data) setRestoreData(nd) // 摘要:让"备份里有没有设置/密钥"一眼可见 const cs = cfgSummary(nd.items.config) @@ -291,6 +330,7 @@ function BackupModal(props) { prompts: (nd.items.prompts && (nd.items.prompts.prompts || []).length) || 0, workspaces: (nd.items.workspaces && (nd.items.workspaces.workspaces || []).length) || 0, groups: (nd.items.nodeGroups && (nd.items.nodeGroups.groups || []).length) || 0, + pluginFiles: nd.pluginFiles.length, }) setRestoreSel({ config: !!nd.items.config, prompts: !!nd.items.prompts, nodeGroups: !!nd.items.nodeGroups, workspaces: !!nd.items.workspaces, outputs: !!nd.items.outputs }) setRstMsg(data.__checksumMismatch ? { type: 'err', text: '⚠︎ 校验和与文件内容不一致(可能是旧版备份格式),文件仍已解析;请确认备份完整后再恢复' } : null) @@ -306,13 +346,23 @@ function BackupModal(props) { if (!jf) throw new Error('ZIP 中缺少 iwb-backup.json(不是本工具的备份)') const data = JSON.parse(await jf.async('string')) const images = [] + const pluginFiles = [] for (const p of Object.keys(z.files)) { if (p.indexOf('images/') === 0) { const b64 = await z.files[p].async('base64') images.push({ key: null, name: p.slice(7), data: 'data:image/png;base64,' + b64 }) + } else if (p.indexOf('plugin-files/') === 0) { + const rest = p.slice('plugin-files/'.length) + const cut = rest.indexOf('/') + if (cut <= 0) continue + const pid = rest.slice(0, cut) + const name = rest.slice(cut + 1) + if (!name || name.indexOf('/') >= 0) continue + const b64 = await z.files[p].async('base64') + pluginFiles.push({ id: pid, name: name, data: 'data:' + mimeOfPluginFile(name) + ';base64,' + b64 }) } } - await acceptRestoreData(data, images) + await acceptRestoreData(data, images, pluginFiles) } catch (e) { setRstMsg({ type: 'err', text: 'ZIP 备份解析失败:' + String((e && e.message) || e) }) } @@ -374,6 +424,15 @@ function BackupModal(props) { if (items.pluginData && items.pluginData.length) { try { const pd = (typeof window !== 'undefined') ? window.IWBPluginData : null; if (pd && pd.restoreAll) await pd.restoreAll(items.pluginData) } catch (e) { /* 插件数据还原失败不阻塞其它项 */ } } + // 插件文件(提示词封面等):与 pluginData 同进退 —— 只恢复 JSON 却丢图,等于「提示词都在、封面全丢」 + let pluginFileOk = 0 + const pluginFileList = Array.isArray(restoreData.pluginFiles) ? restoreData.pluginFiles : [] + if (pluginFileList.length) { + try { + const pd = (typeof window !== 'undefined') ? window.IWBPluginData : null + if (pd && pd.restoreFiles) pluginFileOk = await pd.restoreFiles(pluginFileList) + } catch (e) { /* 插件文件还原失败不阻塞其它项 */ } + } if (restoreSel.outputs && items.outputs) { if (restoreMerge) { const cur = await api('outputs').catch(() => ({ files: [] })) @@ -413,7 +472,7 @@ function BackupModal(props) { if (await IDB.put(im.key, val)) imgOk++; else imgBad.push(im.key) } catch (e) { imgBad.push(im.key) } } - wLog('restore', '恢复(' + (restoreMerge ? '合并' : '覆盖') + '):' + want.join('/') + ' + 图片 ' + imgOk + (imgBad.length ? ',失败 ' + imgBad.length : '')) + wLog('restore', '恢复(' + (restoreMerge ? '合并' : '覆盖') + '):' + want.join('/') + ' + 图片 ' + imgOk + (imgBad.length ? ',失败 ' + imgBad.length : '') + ' + 插件文件 ' + pluginFileOk) // __KEEP__ 边界(v3.0.5):备份里标记"保留本机原值"的密钥字段,本机没有对应值 ⇒ **可见提示**, // 绝不静默留空。用阻塞式确认 + 状态行双重提示,并写进诊断日志;确认后才刷新页面。 const keepMiss = cfgMissingKeep || [] @@ -427,7 +486,7 @@ function BackupModal(props) { } setRstMsg({ type: (imgBad.length || keepWarn) ? 'err' : 'ok', - text: (imgBad.length ? '⚠︎ ' : '✓ ') + '已恢复所选数据' + (imgOk ? '(含 ' + imgOk + ' 张图片' + (imgBad.length ? ',' + imgBad.length + ' 张写入失败:' + imgBad.slice(0, 3).join(', ') + '…' : '') + ')' : '') + (imgBad.length ? ';图片可能显示为“已丢失”,可重新导入' : '') + (keepWarn ? ' ' + keepWarn : '') + restoreVerify + ',即将刷新页面', + text: (imgBad.length ? '⚠︎ ' : '✓ ') + '已恢复所选数据' + (imgOk || pluginFileOk ? '(含 ' + imgOk + ' 张图片' + (pluginFileOk ? ' + ' + pluginFileOk + ' 个插件文件' : '') + (imgBad.length ? ',' + imgBad.length + ' 张写入失败:' + imgBad.slice(0, 3).join(', ') + '…' : '') + ')' : '') + (imgBad.length ? ';图片可能显示为“已丢失”,可重新导入' : '') + (keepWarn ? ' ' + keepWarn : '') + restoreVerify + ',即将刷新页面', }) setTimeout(() => { try { location.reload() } catch (e) { /* ignore */ } }, keepWarn ? 3000 : 900) } catch (e) { @@ -507,6 +566,9 @@ function BackupModal(props) { restoreMerge && restoreSel && restoreSel.config ? el('div', { className: 'iwb-status-err' }, '⚠ 已勾选「合并导入」:合并模式**不会覆盖设置**(含密钥)。要恢复设置请取消合并') : null, restoreData.images && restoreData.images.length ? el('div', { className: 'iwb-backup-item-count' }, '含 ' + restoreData.images.length + ' 张图片') : null, + // v3.26.59:插件文件(提示词封面等)单独列出 —— 否则用户以为"提示词库已回来", + // 打开却是灰块(JSON 有、图片字节没有)。 + restoreData.pluginFiles && restoreData.pluginFiles.length ? el('div', { className: 'iwb-backup-item-count' }, '含 ' + restoreData.pluginFiles.length + ' 个插件文件(封面等)') : null, el('label', { className: 'iwb-backup-item', title: '追加去重,不覆盖已有数据(设置项不导入)' }, el('input', { type: 'checkbox', checked: restoreMerge, onChange: (e) => setRestoreMerge(e.target.checked) }, null), el('span', { className: 'iwb-backup-item-name' }, '合并导入(追加去重)'), @@ -520,7 +582,7 @@ function BackupModal(props) { rstMsg ? el('div', { className: 'iwb-status-' + (rstMsg.type === 'err' ? 'err' : 'ok') }, rstMsg.text) : null, ), el('div', { className: 'iwb-backup-note' }, - '提示:若需连同出图一起备份,请勾选「图库(含缩略图+原图)」(默认不勾选,避免备份体积随出图历史膨胀);画布工作台备份仍只带参考图,生成结果不入画布数据。备份为 ZIP/JSON 文件,请自行妥善保管。', + '提示:若需连同出图一起备份,请勾选「图库(含缩略图+原图)」(默认不勾选,避免备份体积随出图历史膨胀);画布工作台备份仍只带参考图,生成结果不入画布数据。插件数据与插件文件(如提示词封面)随备份自动包含。备份为 ZIP/JSON 文件,请自行妥善保管。', ), ), ) diff --git a/tests/plugin-data-test.js b/tests/plugin-data-test.js index 03f3e02..fe8e7c3 100644 --- a/tests/plugin-data-test.js +++ b/tests/plugin-data-test.js @@ -91,5 +91,35 @@ function memBackend () { await PD.restoreAll([{ id: 'restored-x', data: { ok: true } }]) eq(await PD.create('restored-x').read(), { ok: true }, 'restoreAll 应写回数据') - console.log('plugin-data checks passed(串行队列 / 上限 / 迁移 / 备份)') + // ---- 插件文件(v3.26.59 / P0):备份必须带上 plugin-data//files/ 的字节 ---- + // 动机:只备份 JSON 时,提示词封面这类图片文件换机后全丢,用户看到「已恢复」却是灰块。 + // 这里用内存假 FS 跑行为断言(不依赖 Tauri),覆盖「清单 / 读字节 / 写回」三条路。 + const fakeFiles = { promptlib: { 'cabc.jpg': Buffer.from('JPEGDATA', 'utf8') }, 'other-plugin': { 'cxyz.webp': Buffer.from([1, 2, 3]) } } + const putLog = [] + sandbox.IWBStorageFile = { + pluginFiles: { + listAll: async () => Object.keys(fakeFiles).map((id) => ({ id, files: Object.keys(fakeFiles[id]).map((name) => ({ name, size: fakeFiles[id][name].length })) })), + readBytes: async (id, name) => (fakeFiles[id] && fakeFiles[id][name]) || null, + put: async (id, name, data) => { putLog.push({ id, name, data }); return { ok: true } }, + }, + } + const files = await PD.listFiles() + assert.strictEqual(files.length, 2, 'listFiles 应枚举所有插件的插件文件') + assert.strictEqual(JSON.stringify(files.map((f) => f.id + '/' + f.name).sort()), '["other-plugin/cxyz.webp","promptlib/cabc.jpg"]', 'listFiles 的 id/name 必须成对正确') + assert.strictEqual(files.find((f) => f.name === 'cabc.jpg').size, 8, 'listFiles 应带 size(体积预估用)') + const bytes = await PD.readFile('promptlib', 'cabc.jpg') + assert.ok(bytes && Buffer.from(bytes).toString('utf8') === 'JPEGDATA', 'readFile 应返回原始字节') + assert.strictEqual(await PD.readFile('promptlib', 'missing.jpg'), null, '不存在的文件返回 null(不抛)') + + const n = await PD.restoreFiles([ + { id: 'promptlib', name: 'cabc.jpg', data: 'data:image/jpeg;base64,QUJD' }, + { id: '', name: 'bad.jpg', data: 'x' }, + { id: 'promptlib', name: 'nofile.jpg' }, + ]) + assert.strictEqual(n, 1, 'restoreFiles 只写合法条目(缺 id/name/data 的跳过)') + assert.strictEqual(putLog.length, 1, 'restoreFiles 不应多写') + assert.strictEqual(putLog[0].id, 'promptlib', 'restoreFiles 应带插件 id') + assert.ok(putLog[0].data.indexOf('data:image/jpeg;base64,') === 0, 'restoreFiles 应把 dataURL 交给 pluginFiles.put') + + console.log('plugin-data checks passed(串行队列 / 上限 / 迁移 / 备份 / 插件文件)') })().catch((e) => { console.error(e); process.exit(1) }) \ No newline at end of file