/* ui-backup-modal.js —— 自 app.js 收编(结构优化,2026-10-28) * * 无状态 UI 组件:数据与回调经 props 传入;React / el / hooks 从 global 解析。 * 宿主(app.js)通过 inject() 一次性注入应用层助手。 * * ⚠️ 为什么 inject 而不是 props 注入依赖: * 这些依赖在 app.js 里都是 const 单次赋值 / 函数声明,运行期不变 ⇒ 加载时注入没有"快照失效"问题。 * 好处是组件函数体可以**逐字不动**地搬过来,等价性由 scripts/verify-move.js 证明。 * * ⚠️ 依赖清单是用 ESLint 的 no-undef 反推出来的(不是人肉枚举),漏项会被 CI 直接抓到。 */ ;(function (global) { 'use strict' function askConfirm (text, opts) { const D = (typeof window !== 'undefined') ? window.IWBDesktop : null const native = !!(D && D.isTauri && D.isTauri()) const C = (typeof window !== 'undefined') ? window.IWBUIConfirm : null if (native && C && typeof C.ask === 'function') return C.ask(Object.assign({ text: text }, opts || {})) return Promise.resolve(window.confirm(text)) } // 存储入口收敛(2026-11-06):统一走 IWBStorageLocal 门面,配额/异常集中处理 const _lstore = () => (typeof window !== 'undefined' && window.IWBStorageLocal && typeof window.IWBStorageLocal.getStore === 'function') ? window.IWBStorageLocal.getStore() : null const React = global.React || {} const el = (type, prop, ...children) => React.createElement(type, prop, ...children) const useState = React.useState const useEffect = React.useEffect const useRef = React.useRef const useMemo = React.useMemo const useCallback = React.useCallback const useLayoutEffect = React.useLayoutEffect let IDB, IMG_BLOB_PREFIX, ImageBlobStore, ModularBackupStore, SchemaVersions, StorageContract, api, backupChecksumPayload, backupImageManifest, hydrateGroupSnapshot, iwbCacheRead, mapGroupsSeq, normalizeBackup, prepareGroupSnapshotForStorage, wBackupConfig, wBlobFromDataUrl, wCfgHasPlaintextKeys, wCreateStoreZip, wDownloadBlob, wImgBlobToDataUrl, wIsBlobRef, wLog, wOpenZipBlob, wSanitizeFileName, wSha256, withoutGenerationResults, W_KEEP function inject (d) { if (!d) throw new Error('[iwb][IWBUIBackupModal] 依赖未注入') IDB = d.IDB IMG_BLOB_PREFIX = d.IMG_BLOB_PREFIX ImageBlobStore = d.ImageBlobStore ModularBackupStore = d.ModularBackupStore SchemaVersions = d.SchemaVersions StorageContract = d.StorageContract api = d.api backupChecksumPayload = d.backupChecksumPayload backupImageManifest = d.backupImageManifest hydrateGroupSnapshot = d.hydrateGroupSnapshot iwbCacheRead = d.iwbCacheRead mapGroupsSeq = d.mapGroupsSeq normalizeBackup = d.normalizeBackup prepareGroupSnapshotForStorage = d.prepareGroupSnapshotForStorage wBackupConfig = d.wBackupConfig wBlobFromDataUrl = d.wBlobFromDataUrl wCfgHasPlaintextKeys = d.wCfgHasPlaintextKeys wCreateStoreZip = d.wCreateStoreZip wDownloadBlob = d.wDownloadBlob wImgBlobToDataUrl = d.wImgBlobToDataUrl wIsBlobRef = d.wIsBlobRef wLog = d.wLog wOpenZipBlob = d.wOpenZipBlob wSanitizeFileName = d.wSanitizeFileName wSha256 = d.wSha256 withoutGenerationResults = d.withoutGenerationResults W_KEEP = d.W_KEEP return true } function BackupModal(props) { const [counts, setCounts] = useState({ prompts: 0, nodeGroups: 0, workspaces: 0, outputs: 0 }) // 备份区 // 2026-10-29:默认勾选「设置」与「包含 API Key」。 // 原因:此前两者默认关 ⇒ 备份文件里根本没有设置(还原时无设置可恢复), // 用户遇到的就是「设置/服务/自定义模型/Key 全都还原不回来」。 const [bk, setBk] = useState({ prompts: true, nodeGroups: true, workspaces: true, config: true, withKeys: true, outputs: false }) const [bkBusy, setBkBusy] = useState(false) const [bkMsg, setBkMsg] = useState(null) // 恢复区 const [restoreData, setRestoreData] = useState(null) // 解析后的备份文件 const [restoreSel, setRestoreSel] = useState(null) // 勾选的恢复项 {config,prompts,nodeGroups,workspaces} const [rstBusy, setRstBusy] = useState(false) const [rstMsg, setRstMsg] = useState(null) const [restoreMerge, setRestoreMerge] = useState(false) const [clearBusy, setClearBusy] = useState(false) const [clearMsg, setClearMsg] = useState(null) useEffect(() => { let alive = true Promise.all([ api('prompts').then((r) => (r && Array.isArray(r.prompts) ? r.prompts.length : 0)).catch(() => 0), api('groups').then((r) => (r && Array.isArray(r.groups) ? r.groups.length : 0)).catch(() => 0), api('workspaces').then((r) => (r && Array.isArray(r.workspaces) ? r.workspaces.length : 0)).catch(() => 0), api('outputs').then((r) => (r && Array.isArray(r.files) ? r.files.length : 0)).catch(() => 0), ]).then(([a, b, c, d]) => { if (alive) setCounts({ prompts: a, nodeGroups: b, workspaces: c, outputs: d }) }).catch(() => {}) return () => { alive = false } }, []) const bkAll = bk.prompts && bk.nodeGroups && bk.workspaces && bk.config const setBkAll = (v) => setBk({ prompts: v, nodeGroups: v, workspaces: v, config: v, withKeys: bk.withKeys, outputs: false }) // 备份仅带参考图;生成结果图片不随画布数据转移,避免备份体积随出图历史膨胀。 const collectBackupImages = async () => { const list = [] try { const ws = await api('workspaces') const seen = new Set() for (const w of (ws && ws.workspaces) || []) for (const n of (w && w.nodes) || []) { if (!n || n.type !== 'ref') continue const d = n.data || {} for (const fld of ['data', 'url']) { const val = d[fld] || {} if (val && val.__idb) { if (!seen.has(val.__idb)) { seen.add(val.__idb); list.push({ key: val.__idb, name: wSanitizeFileName((d.name || 'ref') + '.png') }) } } else if (val && val.__cache) { if (!seen.has(val.__cache)) { seen.add(val.__cache); list.push({ key: val.__cache, name: wSanitizeFileName((d.name || 'ref') + '.png'), isCache: true }) } } // C3:Blob 仓库里的图(imgblob_)也要随备份带走,否则换机恢复后引用指向不存在的字节 else if (wIsBlobRef(val)) { if (!seen.has(val.__blob)) { seen.add(val.__blob); list.push({ key: val.__blob, name: wSanitizeFileName((d.name || 'ref') + '.png'), isBlob: true }) } } } } } catch (e) { /* 收集失败不影响主数据备份 */ } const seenK = new Set(), out = [] for (const im of list) { if (!seenK.has(im.key)) { seenK.add(im.key); out.push(im) } } return out } // 图库图片(缩略图 out_ + 原图 out_orig_):可选随备份导出(默认不勾选)。按 IDB key 收集并唯一化。 // 只收集「引用元数据」(key/name),图片本体留到写包时逐张读、立即释放 —— // 原实现先把整库原图读进 imgData 数组再写 ZIP,同一份数据在堆里放大 3~4 份(OOM 主因)。 const collectBackupOutputImages = async (files) => { const out = [] const seen = new Set() for (const f of (files || [])) { if (!f) continue for (const key of [f.origIdb, f.idb]) { if (!key || seen.has(key)) continue seen.add(key) out.push({ key, name: 'gallery_' + wSanitizeFileName(String(key)) + '.png' }) } } return out } // 逐张读图 → Blob(不累积数组:写完该张即可放手,堆里同时只有一张图) const readBackupImageBlob = async (im) => { // C3:Blob 仓库的键直接取 Blob(零 base64 往返) if (im.isBlob) { try { return ImageBlobStore ? await ImageBlobStore.getBlob(im.key) : null } catch (e) { return null } } let data = null try { data = im.isCache ? await iwbCacheRead(im.key) : await IDB.get(im.key) } catch (e) { data = null } if (!data) return null try { return await wBlobFromDataUrl(data) } catch (e) { return null } } // 导出前体积预估:图库索引的 size 字段求和(缺失时退化为按张数提示) const estimateBackupBytes = (outputItems) => { let sum = 0 for (const f of (Array.isArray(outputItems) ? outputItems : [])) sum += Number(f && f.size) || 0 return sum } const doBackup = async () => { setBkBusy(true); setBkMsg(null) try { const items = {} const jobs = [] if (bk.prompts) jobs.push(api('prompts').then((r) => { items.prompts = { prompts: (r && r.prompts) || [], groups: (r && r.groups) || [] } })) // 收藏组必须先 hydrate 成 base64 再进备份:备份是跨设备/跨浏览器的,缓存引用在别的设备上不存在 → 组里会没有图。 if (bk.nodeGroups) jobs.push(api('groups').then(async (r) => { const groups = await mapGroupsSeq((r && r.groups) || [], (g) => hydrateGroupSnapshot(g)) items.nodeGroups = { groups: groups, groupGroups: (r && r.groupGroups) || [] } })) if (bk.workspaces) jobs.push(api('workspaces').then((r) => { items.workspaces = { workspaces: withoutGenerationResults((r && r.workspaces) || []), activeId: (r && r.activeId) || '' } })) // 设置:**唯一**合法来源是 wBackupConfig()(源 = wRawCfg() 真实完整设置)。 // 禁止改回 api('config')/wCfgPublic():那是展示形态,只含白名单子集与掩码, // 写进备份就是"设置还原不回来"(v3.0.4 用户实测;同类形状缺陷已出现两次)。 // withKeys 语义在 wBackupConfig 内部生效:false ⇒ 敏感字段 __KEEP__,true ⇒ 明文。 if (bk.config) jobs.push(Promise.resolve().then(() => { items.config = wBackupConfig(!!bk.withKeys) })) if (bk.outputs) jobs.push(api('outputs').then((r) => { // 剥离已 hydrate 的 data(缩略图 base64),仅保留元数据 + idb/origIdb 引用;图片本体走 images/ 快照 items.outputs = ((r && r.files) || []).map((f) => { const o = Object.assign({}, f); delete o.data; return o }) })) await Promise.all(jobs) // 插件(清单 + 源码)随备份走:换机器恢复后不用重装 try { const pb = (typeof window !== 'undefined') ? window.IWBRuntimePluginBackup : null; if (pb && pb.collect) { const ps = await pb.collect(); if (ps && ps.length) items.plugins = ps } } catch (e) { /* 插件快照失败不影响主备份 */ } // v3.25.42:插件数据(plugin-data/.json)一并备份,换机后插件配置不丢 try { const pd = (typeof window !== 'undefined') ? window.IWBPluginData : null; if (pd && pd.collectAll) { const pl = await pd.collectAll(); if (pl && pl.length) items.pluginData = pl } } catch (e) { /* 插件数据快照失败不影响主备份 */ } // 收集图片(画布引用大图 + 勾选的图库缩略图/原图)并读取数据 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 }))) // 导出前体积预估 + 二次确认:几百 MB 的图库导出会持续拉高内存,先让用户确认 if (imgMeta.length) { const estMB = estimateBackupBytes(items.outputs) / 1048576 const needConfirm = estMB >= 20 || imgMeta.length >= 20 const sizeText = estMB >= 1 ? ('约 ' + estMB.toFixed(0) + ' MB') : '未记录(按张数估算偏大)' if (needConfirm && typeof window !== 'undefined' && typeof window.confirm === 'function') { const okGo = await askConfirm('本次备份包含 ' + imgMeta.length + ' 张图片,预计体积 ' + sizeText + '。\n导出期间内存占用会明显上升,图库很大时页面会变慢。\n确定继续导出吗?', { title: '导出备份', okText: '继续导出' }) if (!okGo) { setBkMsg({ type: 'err', text: '已取消导出(' + imgMeta.length + ' 张图片 / ' + sizeText + ')' }) return } } } const core = { app: 'image-workbench', kind: 'backup', backupVersion: 3, schemaVersion: SchemaVersions.backup, at: Date.now(), items, images: imgMeta } 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 ts = new Date().toISOString().slice(0, 10) let exportedImages = 0 // 主路径:原生 ZIP 写入器(STORE)——逐张读 → 立即以 Blob 写包 → 立即释放,堆里同时只有一张图 let zipBlob = null try { const zw = wCreateStoreZip() await zw.add('iwb-backup.json', new Blob([JSON.stringify(manifest, null, 1)], { type: 'application/json' })) for (const im of imgMeta) { const imgBlob = await readBackupImageBlob(im) if (!imgBlob) continue await zw.add('images/' + im.name, imgBlob) exportedImages++ await new Promise((r) => setTimeout(r, 0)) // 让出事件循环,给 GC 回收上一张的 base64 字符串 } zipBlob = zw.finish() } catch (e) { zipBlob = null; exportedImages = 0 } if (zipBlob) { wDownloadBlob(zipBlob, 'image-workbench-backup-' + ts + '.zip') setBkMsg({ type: 'ok', text: '✓ 已导出 ZIP 备份(' + Object.keys(items).join(' / ') + ' + ' + exportedImages + ' 张图片),含校验和,恢复时可校验' }) } else { // 兜底:原生写入器失败 → JSON 内嵌图片 base64。整包字符串无法避免,仅作兜底。 // (原来这里还有一条「CDN 加载 JSZip 写 ZIP」的兜底:线上 CSP script-src 'self' 会直接拦死该 script, // 该分支在线上永远不可达,已删除;ZIP 导出只剩下面的原生 STORE 写入器这一条路。) const imagesData = [] for (const im of imgMeta) { let data = null try { // C3:Blob 仓库的键转成 dataURL 内嵌(ZIP 路径直接写 Blob 字节) if (im.isBlob) { const b = ImageBlobStore ? await ImageBlobStore.getBlob(im.key) : null; data = b ? await wImgBlobToDataUrl(b) : null } else data = im.isCache ? await iwbCacheRead(im.key) : await IDB.get(im.key) } catch (e) { data = null } if (data) imagesData.push({ key: im.key, name: im.name, data }) } exportedImages = imagesData.length const m2 = Object.assign({}, manifest, { imagesData }) delete m2.images const blob = new Blob([JSON.stringify(m2)], { type: 'application/json' }) wDownloadBlob(blob, 'image-workbench-backup-' + ts + '.json') setBkMsg({ type: 'ok', text: '✓ 已导出备份(JSON 内嵌 ' + exportedImages + ' 张图片;联网时导出 ZIP 更小更稳)' }) } wLog('backup', '导出备份:' + Object.keys(items).join('/') + ' + 图片 ' + exportedImages) // 记录"上次导出"时间(2026-11-07):自动备份与数据同在浏览器里,导出磁盘才是异地保险 try { const stx = _lstore(); if (stx) stx.rawSet('iwb_backup_last_export_at', String(Date.now())) } catch (e) { /* ignore */ } } catch (e) { setBkMsg({ type: 'err', text: '备份失败:' + String((e && e.message) || e) }) } finally { setBkBusy(false) } } // 备份内容摘要(2026-10-29):还原前把"这份备份里到底有什么"明确列出来。 // 动机:用户报告"勾了设置和 Key,还原却没匹配上" —— 实际最常见原因是**备份文件本身没有设置** // (旧版本导出只写展示形态,或导出时没勾「设置」)或**用了合并模式**(按设计不覆盖设置)。 // 与其让用户猜,不如把内容和缺失项直接显示出来。 const [restoreInfo, setRestoreInfo] = useState(null) const cfgSummary = (cfg) => { const ps = (cfg && Array.isArray(cfg.providers)) ? cfg.providers : [] let models = 0, plainKeys = 0, keepKeys = 0 for (const p of ps) { models += (Array.isArray(p.models) ? p.models.length : 0) for (const k of (Array.isArray(p.keys) ? p.keys : [])) { if (k && k.value === W_KEEP) keepKeys++ else if (k && k.value) plainKeys++ } } const llmPs = (cfg && cfg.llm && Array.isArray(cfg.llm.providers)) ? cfg.llm.providers : [] for (const p of llmPs) for (const k of (Array.isArray(p.keys) ? p.keys : [])) { if (k && k.value === W_KEEP) keepKeys++ else if (k && k.value) plainKeys++ } return { providers: ps.length, models, plainKeys, keepKeys, llmProviders: llmPs.length } } const acceptRestoreData = async (data, images) => { 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))) if (h !== data.checksum) { // 旧版 JSON 备份校验和按「含 images」计算但文件不含 images → 必然不匹配; // 这里降级为提示而非硬失败,仍可继续解析/还原(结构完整性仍由 normalizeBackup 校验) data.__checksumMismatch = { expected: String(data.checksum).slice(0, 12), got: h.slice(0, 12) } } } const nd = normalizeBackup(data) const manifest = backupImageManifest(nd) const byName = new Map(manifest.map((im) => [String(im && im.name || ''), im])) const zipImages = (images || []).map((im) => { const meta = byName.get(String(im && im.name || '')) return Object.assign({}, im, { key: (meta && meta.key) || im.key || null }) }) 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 })) setRestoreData(nd) // 摘要:让"备份里有没有设置/密钥"一眼可见 const cs = cfgSummary(nd.items.config) setRestoreInfo({ hasConfig: !!nd.items.config, ...cs, 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, }) 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) } const pickRestore = (file) => { if (!file) return if (/\.zip$/i.test(file.name || '')) { setRstMsg({ type: 'ok', text: '正在解析 ZIP 备份…' }) // 原生 ZIP 读取(不依赖 CDN / 网络 / CSP 允许的第三方脚本) wOpenZipBlob(file).then(async (z) => { try { const jf = z.file('iwb-backup.json') if (!jf) throw new Error('ZIP 中缺少 iwb-backup.json(不是本工具的备份)') const data = JSON.parse(await jf.async('string')) const images = [] 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 }) } } await acceptRestoreData(data, images) } catch (e) { setRstMsg({ type: 'err', text: 'ZIP 备份解析失败:' + String((e && e.message) || e) }) } }).catch((e) => setRstMsg({ type: 'err', text: 'ZIP 备份解析失败:' + String((e && e.message) || e) })) return } const rd = new FileReader() rd.onload = () => { try { const data = JSON.parse(/** @type {string} */ (rd.result)) acceptRestoreData(data, []).catch((e) => setRstMsg({ type: 'err', text: '备份文件解析失败:' + String((e && e.message) || e) })) } catch (e) { setRstMsg({ type: 'err', text: '备份文件解析失败:' + String((e && e.message) || e) }) } } rd.readAsText(file) } const doRestore = async () => { if (!restoreData || !restoreSel) return const items = restoreData.items const want = Object.keys(restoreSel).filter((k) => restoreSel[k]) if (!want.length) { setRstMsg({ type: 'err', text: '请至少勾选一项要恢复的数据' }); return } if (!(await askConfirm((restoreMerge ? '将以「合并」方式导入(追加去重,不覆盖已有):' : '将用备份覆盖当前数据:') + want.map((k) => ({ config: '设置', prompts: '提示词库', nodeGroups: '节点组', workspaces: '画布工作台', outputs: '图库(含缩略图+原图)' })[k]).join('、') + '。确定恢复?', { title: '恢复备份', okText: '开始恢复' }))) return setRstBusy(true); setRstMsg(null) try { props.onSaveNow && props.onSaveNow() // 导入前保存当前画布(避免导入后丢失未保存改动) const jobs = [] let cfgMissingKeep = [] if (restoreSel.config && items.config) { // 覆盖导入:整份设置写回(wCfgSave 内部解析 __KEEP__ 为本机值,并保留未知字段) if (!restoreMerge) jobs.push(api('config', items.config).then((r) => { cfgMissingKeep = (r && r.missingKeep) || []; return r })) // 合并模式不覆盖设置(含密钥,安全考虑) } if (restoreSel.prompts && items.prompts) { if (restoreMerge) { const cur = await api('prompts').catch(() => ({ prompts: [], groups: [] })) const curP = (cur && cur.prompts) || [], curG = (cur && cur.groups) || [] const merged = { prompts: mergeById(curP, items.prompts.prompts || []), groups: mergeById(curG, items.prompts.groups || []) } jobs.push(api('prompts', merged)) } else jobs.push(api('prompts', { prompts: items.prompts.prompts || [], groups: items.prompts.groups || [] })) } if (restoreSel.nodeGroups && items.nodeGroups) { // 备份里的组是 base64 原图(为了跨设备可用):写回前先转引用形态,否则 localStorage 会被大图顶爆。 const incomingGroups = await mapGroupsSeq(items.nodeGroups.groups || [], (g) => prepareGroupSnapshotForStorage(g)) if (restoreMerge) { const cur = await api('groups').catch(() => ({ groups: [], groupGroups: [] })) jobs.push(api('groups', { groups: mergeById((cur && cur.groups) || [], incomingGroups), groupGroups: mergeById((cur && cur.groupGroups) || [], items.nodeGroups.groupGroups || []) })) } else jobs.push(api('groups', { groups: incomingGroups, groupGroups: items.nodeGroups.groupGroups || [] })) } if (restoreSel.workspaces && items.workspaces) { if (restoreMerge) { const cur = await api('workspaces').catch(() => ({ workspaces: [] })) jobs.push(api('workspaces', { workspaces: mergeById((cur && cur.workspaces) || [], items.workspaces.workspaces || []), activeId: (cur && cur.activeId) || '' })) } else jobs.push(api('workspaces', { workspaces: items.workspaces.workspaces || [], activeId: items.workspaces.activeId || '' })) } if (items.plugins && items.plugins.length) { try { const pb = (typeof window !== 'undefined') ? window.IWBRuntimePluginBackup : null; if (pb && pb.restore) await pb.restore(items.plugins) } catch (e) { /* 插件还原失败不阻塞其它项 */ } } 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) { /* 插件数据还原失败不阻塞其它项 */ } } if (restoreSel.outputs && items.outputs) { if (restoreMerge) { const cur = await api('outputs').catch(() => ({ files: [] })) jobs.push(api('outputs', { action: 'restore', files: mergeById((cur && cur.files) || [], items.outputs) })) } else jobs.push(api('outputs', { action: 'restore', files: items.outputs })) } await Promise.all(jobs) // 还原后校验(只读):把关键条数读回与备份比对,不一致在状态行明示(合并模式下实际≥备份属正常) let restoreVerify = '' try { const checks = [] if (restoreSel.prompts && items.prompts) { const cur = await api('prompts').catch(() => null); const got = cur && Array.isArray(cur.prompts) ? cur.prompts.length : -1; const exp = (items.prompts.prompts || []).length; if (got >= 0) checks.push('提示词 ' + got + '/' + exp) } if (restoreSel.workspaces && items.workspaces) { const cur = await api('workspaces').catch(() => null); const got = cur && Array.isArray(cur.workspaces) ? cur.workspaces.length : -1; const exp = (items.workspaces.workspaces || []).length; if (got >= 0) checks.push('画布 ' + got + '/' + exp) } if (restoreSel.outputs && items.outputs) { const cur = await api('outputs').catch(() => null); const got = cur && Array.isArray(cur.files) ? cur.files.length : -1; const exp = Array.isArray(items.outputs) ? items.outputs.length : 0; if (got >= 0) checks.push('图库 ' + got + '/' + exp) } if (checks.length) restoreVerify = ';校验(实际/备份):' + checks.join(' · ') + (restoreMerge ? '(合并模式,实际≥备份属正常)' : '') } catch (e) { restoreVerify = '' } // 图片写回 IndexedDB(ZIP 内 images/ 或 JSON 内嵌;key 为原始 IDB 键) const imgs = (restoreData.images || []).concat(Array.isArray(restoreData.imagesData) ? restoreData.imagesData.map((x) => ({ key: x.key, data: x.data })) : []) let imgOk = 0 const imgBad = [] const restoreGallery = !!restoreSel.outputs const restoreRefs = !!(restoreSel.nodeGroups || restoreSel.workspaces) for (const im of imgs) { if (!im.key || !im.data) continue // 只恢复与所选项目相关的图片:未选图库时跳过 gallery_*(避免写回孤儿字节), // 只恢复设置/提示词时也不写任何图片。 if (!restoreGallery && String(im.name || '').indexOf('gallery_') === 0) continue if (!restoreGallery && !restoreRefs) continue try { // C3:Blob 仓库的键必须写 Blob(备份里是 dataURL/字节)——否则 image-blob-store 读出来不是 Blob let val = im.data if (String(im.key).indexOf(IMG_BLOB_PREFIX) === 0 && typeof val === 'string') { const b = await wBlobFromDataUrl(val) if (!b) { imgBad.push(im.key); continue } val = b } 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 : '')) // __KEEP__ 边界(v3.0.5):备份里标记"保留本机原值"的密钥字段,本机没有对应值 ⇒ **可见提示**, // 绝不静默留空。用阻塞式确认 + 状态行双重提示,并写进诊断日志;确认后才刷新页面。 const keepMiss = cfgMissingKeep || [] let keepWarn = '' if (keepMiss.length) { const uniqLabel = [] for (const m of keepMiss) { const t = (m && (m.label || m.path)) || '密钥'; if (uniqLabel.indexOf(t) === -1) uniqLabel.push(t) } keepWarn = '⚠︎ 有 ' + keepMiss.length + ' 个密钥字段在备份里是「保留本机原值」(__KEEP__),但本机没有对应值,已保持为空:' + uniqLabel.slice(0, 3).join('、') + (uniqLabel.length > 3 ? ' 等 ' + uniqLabel.length + ' 类' : '') + '。请到「服务与 Key 设置」里补填。' wLog('restore', 'KEEP-MISS:' + keepMiss.map((m) => m && m.path).join(', ')) try { await askConfirm(keepWarn + '\n\n点「确定」继续(恢复已完成,随后刷新页面生效)。', { title: '恢复提示', okText: '知道了', cancelText: '关闭' }) } catch (e) { /* ignore */ } } 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 + ',即将刷新页面', }) setTimeout(() => { try { location.reload() } catch (e) { /* ignore */ } }, keepWarn ? 3000 : 900) } catch (e) { setRstMsg({ type: 'err', text: '恢复失败:' + String((e && e.message) || e) }) } finally { setRstBusy(false) } } // 按 id 去重合并(备份项追加,不覆盖已有) const mergeById = (cur, inc) => { const map = new Map() for (const x of (cur || [])) map.set(x.id || x.name || JSON.stringify(x), x) for (const x of (inc || [])) { const k = x.id || x.name || JSON.stringify(x); if (!map.has(k)) map.set(k, x) } return Array.from(map.values()) } const bkCheck = (key, label, extra) => el('label', { className: 'iwb-backup-item' }, el('input', { type: 'checkbox', checked: bk[key], onChange: (e) => setBk((b) => ({ ...b, [key]: e.target.checked })) }, null), el('span', { className: 'iwb-backup-item-name' }, label), extra ? el('span', { className: 'iwb-backup-item-count' }, extra) : null, ) const rstRow = (key, label, n) => el('label', { className: 'iwb-backup-item' }, el('input', { type: 'checkbox', checked: !!(restoreSel && restoreSel[key]), onChange: (e) => setRestoreSel((s) => ({ ...s, [key]: e.target.checked })) }, null), el('span', { className: 'iwb-backup-item-name' }, label), el('span', { className: 'iwb-backup-item-count' }, n), ) // 本组件**只以嵌入形式**使用(设置面板的「备份与还原」Tab)。 // 2026-10-29:用户要求移除另外两个菜单入口后,独立弹层分支(遮罩 + 标题栏 ✕)已无调用方, // 属于死代码 ⇒ 一并删除;同时嵌入时不套 `.iwb-modal`,避免设置面板里多出一层外框(用户反馈"不要框住了")。 return el('div', { className: 'iwb-backup-embedded' }, el('div', { className: 'iwb-modal-body' }, el('div', { className: 'iwb-backup-sec' }, el('div', { className: 'iwb-backup-sec-title' }, '① 备份(导出所选数据)'), el('label', { className: 'iwb-backup-item iwb-backup-all' }, el('input', { type: 'checkbox', checked: bkAll, onChange: (e) => setBkAll(e.target.checked) }, null), el('span', { className: 'iwb-backup-item-name' }, '全部基础数据'), el('span', { className: 'iwb-backup-item-count' }, bkAll ? '已全选' : '全选'), ), bkCheck('prompts', '提示词库(含分组)', counts.prompts + ' 条'), bkCheck('nodeGroups', '节点组(含分组)', counts.nodeGroups + ' 组'), bkCheck('workspaces', '画布工作台', counts.workspaces + ' 个'), bkCheck('config', '设置(服务/图床/LLM/口令等)', null), bk.config ? el('label', { className: 'iwb-backup-item iwb-backup-keys' }, el('input', { type: 'checkbox', checked: bk.withKeys, onChange: (e) => setBk((b) => ({ ...b, withKeys: e.target.checked })) }, null), el('span', { className: 'iwb-backup-item-name' }, '包含 API Key(敏感)'), el('span', { className: 'iwb-backup-item-count iwb-warn' }, bk.withKeys ? '备份文件含密钥,请妥善保管' : '不勾选则不导出密钥'), ) : null, bkCheck('outputs', '图库(含缩略图+原图)', counts.outputs + ' 张'), el('div', { className: 'iwb-backup-actions' }, el('button', { className: 'iwb-btn iwb-btn-primary', disabled: bkBusy || (!bk.prompts && !bk.nodeGroups && !bk.workspaces && !bk.config && !bk.outputs), onClick: doBackup }, bkBusy ? '导出中…' : '导出所选备份 (ZIP/JSON)'), ), bkMsg ? el('div', { className: 'iwb-status-' + (bkMsg.type === 'err' ? 'err' : 'ok') }, bkMsg.text) : null, ), el('div', { className: 'iwb-backup-sec' }, el('div', { className: 'iwb-backup-sec-title' }, '② 恢复(从备份文件导入)'), !restoreData ? el('label', { className: 'iwb-btn iwb-btn-primary' }, el('input', { type: 'file', accept: '.zip,.json,application/json,application/zip', style: { display: 'none' }, onChange: (e) => { pickRestore(e.target.files && e.target.files[0]); e.target.value = '' } }, null), '选择备份文件…(.zip 含图片 / .json)', ) : [ el('div', { className: 'iwb-backup-file' }, '备份时间:' + (restoreData.at ? new Date(restoreData.at).toLocaleString() : '未知') + (restoreData.version ? ' · 格式 v' + restoreData.version : ''), ), // 用统一清单判定"是否真的含明文密钥":只看 llm.apiKey 会把 withKeys 备份误判成"不含密钥" rstRow('config', '设置', restoreInfo ? (restoreInfo.providers + ' 个服务 / ' + restoreInfo.models + ' 个模型 / ' + (restoreInfo.plainKeys ? restoreInfo.plainKeys + ' 个明文密钥' : '无明文密钥') + (restoreInfo.keepKeys ? '(' + restoreInfo.keepKeys + ' 个保留本机值)' : '')) : (wCfgHasPlaintextKeys(restoreData.items.config) ? '含密钥' : '不含密钥')), rstRow('prompts', '提示词库(含分组)', ((restoreData.items.prompts && restoreData.items.prompts.prompts) || []).length + ' 条'), rstRow('nodeGroups', '节点组(含分组)', ((restoreData.items.nodeGroups && restoreData.items.nodeGroups.groups) || []).length + ' 组'), rstRow('workspaces', '画布工作台', ((restoreData.items.workspaces && restoreData.items.workspaces.workspaces) || []).length + ' 个'), rstRow('outputs', '图库(含缩略图+原图)', ((restoreData.items.outputs && restoreData.items.outputs.length) || 0) + ' 张'), restoreData.checksum ? el('div', { className: 'iwb-backup-item-count iwb-ok', style: { color: '#15803d' } }, '✓ 校验和已通过') : null, // 2026-10-29:把"备份里到底有什么/缺什么"直接说出来 —— 用户报告"还原没匹配上", // 最常见原因就是备份文件本身没有设置,或勾了「合并」(按设计不覆盖设置)。 restoreInfo && !restoreInfo.hasConfig ? el('div', { className: 'iwb-status-err' }, '⚠ 该备份**不含设置**:服务、自定义模型、API Key 都无法恢复(导出时未勾选「设置」,或备份来自旧版本)') : null, restoreInfo && restoreInfo.hasConfig && !restoreInfo.plainKeys && restoreInfo.keepKeys ? el('div', { className: 'iwb-status-err' }, '⚠ 该备份的设置里密钥是「保留本机原值」:换到没有该 Key 的设备上,Key 会为空(导出时请勾选「包含 API Key」)') : null, 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, 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' }, '合并导入(追加去重)'), el('span', { className: 'iwb-backup-item-count' }, restoreMerge ? '不覆盖已有' : '覆盖导入'), ), el('div', { className: 'iwb-backup-actions' }, el('button', { className: 'iwb-btn iwb-btn-primary', disabled: rstBusy, onClick: doRestore }, rstBusy ? '恢复中…' : '恢复所选'), el('button', { className: 'iwb-btn', onClick: () => { setRestoreData(null); setRestoreSel(null); setRstMsg(null) } }, '重新选择'), ), ], rstMsg ? el('div', { className: 'iwb-status-' + (rstMsg.type === 'err' ? 'err' : 'ok') }, rstMsg.text) : null, ), el('div', { className: 'iwb-backup-note' }, '提示:若需连同出图一起备份,请勾选「图库(含缩略图+原图)」(默认不勾选,避免备份体积随出图历史膨胀);画布工作台备份仍只带参考图,生成结果不入画布数据。备份为 ZIP/JSON 文件,请自行妥善保管。', ), ), ) } global.IWBUIBackupModal = { inject, BackupModal } })(typeof window !== 'undefined' ? window : globalThis)