diff --git a/CHANGELOG.md b/CHANGELOG.md index 9074d08..8237ed9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,12 @@ - 不可用时自动回退旧的逐文件实现(浏览器/测试通道) - stats() 新增 ipc 计数,便于改造前后对比 +### v3.26.251 补记(2026-12-05)登记表保护 + 缩略图批量读 + +- data.json 保护:每次启动把上一轮留成 `data.json.bak`;若读到的 `assets` 比 bak 少 30% 以上,判定为登记表异常 —— 保留 bak 不覆盖、写 `_boot.log`(assets-regress-load),并在 `stats().assetsGuard` 暴露;运行期骤减只记录(assets-regress-write) +- 缩略图批量读(批次 A2):新增 Rust 命令 `read_files_b64` + `readDisplayThumbsMany`;画布打开时从「每张 3 次 exists + 1 次读文件」改为「一次列 thumbs 目录 + 一次批量读」,浏览器/命令不可用时回退逐张 +- 守卫:`tests/storage-assets-guard-test.js`(normal bak / 异常保留 bak / 日志),`storage-flush-persist` 增加批量缩略图断言 + ## v3.26.250(2026-12-05)参考图:图库拖入/插入按本地图处理 - 图库拖入与「插入到画布」的节点把引用对象({__blob})放在 url 字段(refArgsOf 的既有设计),却被 URL 行判定当成空节点 ⇒ 多出一条永远空着的输入框 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 34d77f3..bda0935 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,7 +41,7 @@ build esbuild 打包到 dist/(单 dist/app.js = src/ 模块按序 node --check app.js 与 dist/app.js 语法 check-dist.js 产物体检 lint ESLint(src/ + app.js,正确性规则) -test:unit 145 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) +test:unit 146 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) test relay-task-graph-fixture + iwb-v32-web-test test:facts 事实基线守门(见 §5) typecheck 渐进类型检查(tsc --noEmit;范围 = src/*.js,不含 app.js) diff --git a/app.js b/app.js index bbde170..9a2e2b5 100644 --- a/app.js +++ b/app.js @@ -5338,14 +5338,22 @@ const tbCenterSeed = (type, refs) => { jobs.push({ key: key, v: v }) if (jobs.length >= DISPLAY_THUMB_HASH_MAX) break } + // 2026-12-05(批次 A2):先把 h16 算完,再一次批量读缩略图(一次列目录 + 一次读文件); + // 不可用时回退旧的逐张路径。 + const h16s = [] + for (const job of jobs) { try { h16s.push((await wSha256(String(job.key))).slice(0, 16)) } catch (e) { h16s.push('') } } + let thumbBatch = null + try { + if (typeof F.readDisplayThumbsMany === 'function') thumbBatch = await F.readDisplayThumbsMany(h16s.map((h) => ({ hash: h, max: 768 }))) + } catch (e) { thumbBatch = null } let n = 0 - for (const job of jobs) { + for (let ji = 0; ji < jobs.length; ji++) { + const job = jobs[ji] const key = job.key + const h16 = h16s[ji] || '' try { - const hex = await wSha256(String(key)) - const h16 = hex.slice(0, 16) - let url = '' - if (typeof F.readDisplayThumbUrl === 'function') { + let url = (thumbBatch && h16 && thumbBatch[h16 + '_768']) ? thumbBatch[h16 + '_768'] : '' + if (!url && typeof F.readDisplayThumbUrl === 'function') { try { url = await F.readDisplayThumbUrl(h16) } catch (e) { url = '' } } if (!url) url = await F.readDisplayThumb(h16) diff --git a/docs/standards/architecture-current-state.md b/docs/standards/architecture-current-state.md index c6fc0f8..dcfbbca 100644 --- a/docs/standards/architecture-current-state.md +++ b/docs/standards/architecture-current-state.md @@ -22,7 +22,7 @@ - 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob__`** (A) `app.js:2143`;`{__cache}`(Cache Storage)为兜底;\`ref_\`(`app.js` 内定义的 `IDB_REF_PREFIX = 'ref_'`)为 legacy 形态 (A)。 - 大图判定:`isBigDataUrl` = `data:` 且 `length > 3000` (A) `app.js:2018`;**画布保存保留阈值** `< 16384` 才原样保留 (A) `app.js:2182`。**两处阈值并存,含义不同**。 - 单测是**源码契约测试**:`tests/` 目录共 **493** 处源码文本钉点(`source.includes` / `source.indexOf` / `/re/.test(source)`),分布在 **20** 个文件(其中 `iwb-v32-web-test.js` 一个就占 **407**)→ **结构性重构会先打红测试**。**该数字已由 `tests/source-text-ratchet-test.js` 的「只减不增」棘轮守门**(2026-10-20 起守卫范围从 1 个文件扩到全目录:新增任何一处源码文本钉点都会打红)。**2026-11-12 复算**(`npm run audit:pins`,v3.24.76):二分 STRUCT **417** / NAME **76**;形态 **POS 403 / NEG 87 / COUNT 3**;难度 **易 62 / 中 316 / 难 115**。钉点减法第一批(v3.24.72)把 **537 → 505**:8 条探针钉点改为「门禁内 spec 是否真的读该计数器」、5 条改为运行时断言(生产态 `window` 上无探针)、10 条改为 DOM 断言(质量档位禁用 / 传输页无三模式按钮 / 模型项 title)、4 条改为运行时对象断言(健康检查两域、策略对象冻结)、其余 9 条有同文件 DOM 等价断言或仅剩 NEG。第二批(v3.24.76)把 **505 → 493**:94-5~7 三条「多标签释放语义」(10 处正则)换成 `tests/iwb-tabs-release.spec.js` 的 3 条真 e2e,剩 1 条「消费方契约」(断言该 spec 在门禁内且 spec 源码真的读两个探针);另 2 条 `wPurgeIntent.add` 钉点改为读 `src/workspace-purge.js`。**这一批一换就查出 3 个真缺陷**(objectURL 从未释放 / 彻底删除留孤儿标签 · session / 刷新后误回收打开标签的图)—— 见 CHANGELOG v3.24.76。 -- `app.js` = 单 IIFE **9,519 行**(**双层预算**:绝对上限 9,529 / 占总源码 ≤ 40%,现 **26.3%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,710 行**(上限 **2,710**,余量 0;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **129** 个模块 / 26,610 行,`sourceModules` 129 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 +- `app.js` = 单 IIFE **9,527 行**(**双层预算**:绝对上限 9,529 / 占总源码 ≤ 40%,现 **26.3%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,710 行**(上限 **2,710**,余量 0;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **129** 个模块 / 26,689 行,`sourceModules` 129 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 - 门禁:`npm run verify` = `verify:ci`(`build` → `node --check app.js` → `node --check dist/app.js` → `check-dist.js` → `lint`(ESLint 正确性规则,`src/` + `app.js`,P4-16a)→ `test:unit` → `test` → `test:facts`)+ `test:e2e` (A) `package.json`。 ## 1.5 内存基线(2026-11-30,v3.26.115,Windows / WebView2 实测) diff --git a/package.json b/package.json index c0cb759..5b09da0 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "app:build": "tauri build", "lint": "eslint src app.js", "test": "node tests/relay-task-graph-fixture-test.js && node tests/plugin-style-node-test.js && node tests/inherit-text-test.js", - "test:unit": "node tests/result-img-doubleclick-test.js && node tests/gallery-audit-test.js && node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/album-task-graph-test.js && node tests/plugin-text-node-refs-test.js && node tests/generation-endpoint-test.js && node tests/storage-config-shape-test.js && node tests/generation-default-model-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/clipboard-native-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/image-writeback-test.js && node tests/image-ingest-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js && node tests/image-file-ref-preview-test.js && node tests/image-download-contract-test.js && node tests/icon-assets-test.js && node tests/strip-plugins-test.js && node tests/plugin-manifest-hashes-test.js && node tests/boot-progress-test.js && node tests/idb-gc-plugin-refs-test.js && node tests/canvas-v3-test.js && node tests/canvas-v3-hit-test.js && node tests/image-cache-migrate-test.js && node tests/storage-flush-persist-test.js && node tests/canvas-save-settle-test.js", + "test:unit": "node tests/result-img-doubleclick-test.js && node tests/gallery-audit-test.js && node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/album-task-graph-test.js && node tests/plugin-text-node-refs-test.js && node tests/generation-endpoint-test.js && node tests/storage-config-shape-test.js && node tests/generation-default-model-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/clipboard-native-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/image-writeback-test.js && node tests/image-ingest-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js && node tests/image-file-ref-preview-test.js && node tests/image-download-contract-test.js && node tests/icon-assets-test.js && node tests/strip-plugins-test.js && node tests/plugin-manifest-hashes-test.js && node tests/boot-progress-test.js && node tests/idb-gc-plugin-refs-test.js && node tests/canvas-v3-test.js && node tests/canvas-v3-hit-test.js && node tests/image-cache-migrate-test.js && node tests/storage-flush-persist-test.js && node tests/canvas-save-settle-test.js && node tests/storage-assets-guard-test.js", "test:diagnostics": "node tests/runtime-diagnostics-hotpath-test.js", "test:facts": "node tests/architecture-facts-guard-test.js && node tests/release-records-test.js", "check:plugins": "node scripts/check-plugins-sync.js", diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index a4bdf33..adf4bf3 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -419,6 +419,34 @@ async fn list_dir_entries(base: String, rel: String) -> Result } + +#[derive(serde::Serialize)] +struct FileB64 { + rel: String, + b64: Option, + error: Option, +} + +#[tauri::command] +async fn read_files_b64(base: String, rels: Vec) -> Result, String> { + use base64::Engine; + let base_path = std::path::PathBuf::from(&base); + let mut out = Vec::with_capacity(rels.len()); + for rel in rels { + let mut item = FileB64 { rel: rel.clone(), b64: None, error: None }; + match resolve_under(&base_path, &rel) { + Some(abs) => match tokio::fs::read(&abs).await { + Ok(bytes) => item.b64 = Some(base64::engine::general_purpose::STANDARD.encode(bytes)), + Err(e) => item.error = Some(e.to_string()), + }, + None => item.error = Some("bad-path".to_string()), + } + out.push(item); + } + Ok(out) +} + + // 2026-12-04(文件版下载,默认关闭):流式写文件,避免整包 base64 过 IPC。 // 目标路径由 JS 提供(资料目录下的 cache/tmp/),这里只负责抓字节 + 落盘;失败会删半成品。 #[tauri::command] @@ -2296,6 +2324,7 @@ pub fn run() { stat_many, read_text_many, list_dir_entries, + read_files_b64, ]) .setup(|app| { if cfg!(debug_assertions) { diff --git a/src/storage-file.js b/src/storage-file.js index f393e0b..783fe0d 100644 --- a/src/storage-file.js +++ b/src/storage-file.js @@ -25,6 +25,12 @@ let loaded = false let timer = null let writing = null + // 2026-12-05(事故后保护):data.json 的 assets 登记表骤减检测。 + // 事故:登记表被旧版本覆盖 ⇒ 图库/输出老图全部解析不到文件(文件还在)。 + // 做法:每次启动把上一轮 data.json 留成 data.json.bak;读到的 assets 若比 bak 少 30% 以上, + // 判定为异常,**保留 bak 不覆盖**并写 _boot.log;运行期再骤减也只记录、不改 bak。 + let lastGoodAssets = 0 + let assetsGuard = null // 惰性取 __TAURI__:模块加载时它未必已注入,但每个调用点都要能拿到 const tk = () => { if (!tauri) { try { tauri = global.__TAURI__ || null } catch (e) { tauri = null } } return tauri } @@ -48,6 +54,10 @@ if (!enabled() || !dir) return null try { const r = await rustInvoke('list_dir_entries', { base: dir, rel: String(rel || '') }); return Array.isArray(r) ? r : null } catch (e) { return null } } + const readFilesB64Of = async (rels) => { + if (!enabled() || !dir || !Array.isArray(rels) || !rels.length) return null + try { const r = await rustInvoke('read_files_b64', { base: dir, rels: rels }); return Array.isArray(r) ? r : null } catch (e) { return null } + } const join = async (...p) => { const P = path() @@ -165,6 +175,14 @@ } // 2026-12-04:data.json 用内容签名判重(不含 at),没变化就不写 if (dataSig !== lastDataSig) { + // 2026-12-05:assets 骤减只记录(bak 已在启动时保存,不在运行期覆盖) + const curN = Object.keys(assets).length + if (lastGoodAssets > 20 && curN < lastGoodAssets * 0.7) { + assetsGuard = { cur: curN, prev: lastGoodAssets, at: Date.now() } + try { await blog('assets-regress-write cur=' + curN + ' prev=' + lastGoodAssets) } catch (e) { /* ignore */ } + } else { + lastGoodAssets = Math.max(lastGoodAssets, curN) + } const tmp2 = await join(dir, DATA_FILE + '.tmp') await fs().writeTextFile(tmp2, body) await fs().rename(tmp2, target) @@ -857,6 +875,27 @@ return fromDataJson ? 'loaded' : 'migrated' } + // 2026-12-05:启动时的 data.json 备份 + 登记表骤减检测(见顶部 lastGoodAssets 注释)。 + async function guardDataJsonBackup () { + try { + const target = await join(dir, DATA_FILE) + const bak = await join(dir, DATA_FILE + '.bak') + let curTxt = '' + try { curTxt = await fs().readTextFile(target) } catch (e) { return } + let bakN = 0 + try { const b = JSON.parse(await fs().readTextFile(bak)); bakN = Object.keys((b && b.assets) || {}).length } catch (e) { bakN = 0 } + let curN = 0 + try { const c = JSON.parse(curTxt); curN = Object.keys((c && c.assets) || {}).length } catch (e) { curN = 0 } + lastGoodAssets = Math.max(curN, bakN) + if (bakN > 20 && curN < bakN * 0.7) { + assetsGuard = { cur: curN, prev: bakN, at: Date.now() } + await blog('assets-regress-load cur=' + curN + ' prev=' + bakN) + return + } + try { await fs().writeTextFile(bak, curTxt) } catch (e) { /* ignore */ } + } catch (e) { /* ignore */ } + } + // 一次性迁移:把老版本存在 IndexedDB 里的图片字节搬到 images/ 下(跑过一次就写标记文件) // 启动日志:超过 256KB 只保留最后 64KB(否则长年累月会一直长) const blog = async (m) => { @@ -1035,6 +1074,7 @@ try { await repairCanvasFileNames() } catch (e) { /* 修复失败按原样装载 */ } bpReport('prepare', 4, 4) await loadInto() + try { await guardDataJsonBackup() } catch (e) { /* 保护失败不影响启动 */ } // 从 WebView 的 localStorage 捞回被截断/覆盖的画布(一次性) try { await recoverFromWebStorage() } catch (e) { /* 忽略 */ } loaded = true @@ -1372,6 +1412,45 @@ return url } catch (e) { return '' } } + // 2026-12-05(批次 A2):画布打开时的缩略图批量读取。 + // 旧实现每张图 3 次 exists + 1 次读文件;这里改成「一次列 thumbs 目录 + 一次批量读」。 + // 返回 { '_': dataURL };命令不可用/失败返回 null(调用方回退逐张)。 + async function readDisplayThumbsMany (pairs) { + try { + if (!enabled() || !dir || !Array.isArray(pairs) || !pairs.length) return null + const ents = await listDirEntriesOf(IMG_DIR + '/thumbs') + if (!ents) return null + const names = new Set(ents.filter((e) => e && !e.is_dir).map((e) => String(e.name))) + if (!names.size) return {} + const plan = [] + const rels = [] + for (const p of pairs) { + const h = String((p && p.hash) || '') + if (!h) continue + const m = Math.max(64, Number(p.max) || 768) + const ck = h + '_' + m + let name = '' + for (const ext of ['.webp', '.jpg', '.png']) { const n = h + '_' + m + ext; if (names.has(n)) { name = n; break } } + if (!name) continue + rels.push(IMG_DIR + '/thumbs/' + name) + plan.push({ ck: ck, name: name }) + } + if (!rels.length) return {} + const got = await readFilesB64Of(rels) + if (!got) return null + const byName = new Map(plan.map((x) => [x.name, x.ck])) + const out = {} + for (const g of got) { + if (!g || !g.b64) continue + const name = String(g.rel || '').split('/').pop() + const ck = byName.get(name) + if (!ck) continue + const mime = /\.png$/i.test(name) ? 'image/png' : (/\.webp$/i.test(name) ? 'image/webp' : 'image/jpeg') + out[ck] = 'data:' + mime + ';base64,' + String(g.b64) + } + return out + } catch (e) { return null } + } // v3.25.78:缩略图没有回收机制,历史上会无限增长(实测 470 个 / 67MB)。 // 这里按总大小封顶(默认 300MB,超了删最老的 20%),缩略图可再生,删掉不影响数据。 async function pruneThumbs (maxMB) { @@ -1845,7 +1924,7 @@ enabled, ready: init, flush, // 供其它模块把诊断写进 _boot.log(v3.26.109) logLine: (m) => blog(m), - runtime, pickDir, switchTo, migrateTo, deleteImageBytes, deleteGalleryBytesFor, galleryAudit, gcImages, rotateTrash, galleryThumb, galleryThumbUrl, galleryThumbOfEntry, galleryOriginalOf, galleryOriginalBlob, putFileFrom, displayThumbDataUrlOfRef, readDisplayThumb, readDisplayThumbUrl, makeDisplayThumb, makeDisplayThumbFromPath, resizeDataUrl, decodeStats, thumbStats, writeDisplayThumb, writeDisplayThumbBlob, pruneThumbs, cleanupLegacy, maintain, + runtime, pickDir, switchTo, migrateTo, deleteImageBytes, deleteGalleryBytesFor, galleryAudit, gcImages, rotateTrash, galleryThumb, galleryThumbUrl, galleryThumbOfEntry, galleryOriginalOf, galleryOriginalBlob, putFileFrom, displayThumbDataUrlOfRef, readDisplayThumb, readDisplayThumbUrl, readDisplayThumbsMany, makeDisplayThumb, makeDisplayThumbFromPath, resizeDataUrl, decodeStats, thumbStats, 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, readBytes: pluginFileReadBytes, listAll: pluginFilesListAll }, @@ -1853,7 +1932,7 @@ kv: () => kv, dir: () => dir, setDir: async (next) => { dir = String(next || ''); await flush();}, - stats: () => ({ dir, keys: Object.keys(mem).length, images: Object.keys(assets).length, ipc: ipcCalls }), + stats: () => ({ dir, keys: Object.keys(mem).length, images: Object.keys(assets).length, ipc: ipcCalls, assetsGuard: assetsGuard, lastGoodAssets: lastGoodAssets }), __internals: { snapshot, loadInto, sha16, extOf, dataUrlToBytes, bytesToDataUrl, pluginFileNameOk }, } // 关窗/收托盘前强制刷盘(beforeunload 在桌面端不保证,但能救一次是一次) diff --git a/tests/storage-assets-guard-test.js b/tests/storage-assets-guard-test.js new file mode 100644 index 0000000..bda93f9 --- /dev/null +++ b/tests/storage-assets-guard-test.js @@ -0,0 +1,67 @@ +/* storage-assets-guard-test.js —— data.json 备份与 assets 骤减保护(2026-12-05 事故后加) + * + * 事故:data.json 的 assets 登记表被旧版本覆盖 ⇒ 图库/输出老图全部解析不到文件(文件其实都在)。 + * 保护:每次启动把上一轮 data.json 留成 data.json.bak;若读到的 assets 比 bak 少 30% 以上, + * 判定异常 —— 保留 bak 不覆盖、写 _boot.log,并在 stats().assetsGuard 暴露。 + */ +'use strict' +const fs = require('node:fs') +const os = require('node:os') +const path = require('node:path') +const assert = require('node:assert') + +const SRC = fs.readFileSync(path.join(__dirname, '..', 'src', 'storage-file.js'), 'utf8') + +const boot = async (root) => { + const ls = new Map([['iwb.dataDir', root]]) + const makeFs = () => ({ + readTextFile: async (p) => fs.readFileSync(p, 'utf8'), + writeTextFile: async (p, t, o) => { fs.mkdirSync(path.dirname(p), { recursive: true }); if (o && o.append) fs.appendFileSync(p, t); else fs.writeFileSync(p, t) }, + writeFile: async (p, u8) => { fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, Buffer.from(u8)) }, + readFile: async (p) => new Uint8Array(fs.readFileSync(p)), + rename: async (a, b) => { fs.mkdirSync(path.dirname(b), { recursive: true }); fs.renameSync(a, b) }, + remove: async (p) => { try { fs.rmSync(p, { recursive: true, force: true }) } catch (e) { /* ignore */ } }, + mkdir: async (p) => { fs.mkdirSync(p, { recursive: true }) }, + exists: async (p) => fs.existsSync(p), + readDir: async (p) => fs.readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, isDirectory: d.isDirectory(), isFile: d.isFile() })), + stat: async (p) => fs.statSync(p), + }) + const g = { + __TAURI__: { core: { invoke: async () => true }, path: { join: async (...p) => path.join(...p.map(String)), documentDir: async () => root }, fs: makeFs() }, + localStorage: { getItem: (k) => (ls.has(k) ? ls.get(k) : null), setItem: (k, v) => ls.set(k, String(v)), removeItem: (k) => ls.delete(k), key: (i) => Array.from(ls.keys())[i] || null, get length() { return ls.size } }, + addEventListener() {}, document: { addEventListener() {}, visibilityState: 'visible' }, + setTimeout, clearTimeout, crypto: globalThis.crypto, atob, btoa, console, + } + const F = new Function('window', 'globalThis', SRC + '\nreturn window.IWBStorageFile')(g, g) + await F.ready({ dir: root }) + return F +} +const seed = (root, rel, obj) => { const p = path.join(root, rel); fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, JSON.stringify(obj)) } +const mkAssets = (n) => { const a = {}; for (let i = 0; i < n; i++) a['imgblob_k' + i] = { f: 'images/canvas/x' + i + '.png', k: 'blob', m: 'image/png' }; return a } + +;(async () => { + // ① 正常:bak 在启动时写成上一轮 data.json + const R1 = fs.mkdtempSync(path.join(os.tmpdir(), 'iwb-guard1-')) + seed(R1, 'data.json', { v: 1, keys: {}, assets: mkAssets(40), small: {} }) + await boot(R1) + assert.ok(fs.existsSync(path.join(R1, 'data.json.bak')), '① 启动后应生成 data.json.bak') + const bak1 = JSON.parse(fs.readFileSync(path.join(R1, 'data.json.bak'), 'utf8')) + assert.strictEqual(Object.keys(bak1.assets).length, 40, '① bak 应是上一轮内容(40 个 assets)') + + // ② 异常:data.json 只有 2 个 assets,bak 有 40 → 保留 bak、暴露 assetsGuard + const R2 = fs.mkdtempSync(path.join(os.tmpdir(), 'iwb-guard2-')) + seed(R2, 'data.json', { v: 1, keys: {}, assets: mkAssets(2), small: {} }) + seed(R2, 'data.json.bak', { v: 1, keys: {}, assets: mkAssets(40), small: {} }) + const F2 = await boot(R2) + const st = F2.stats() + assert.ok(st.assetsGuard && st.assetsGuard.prev === 40 && st.assetsGuard.cur === 2, '② 骤减应被判定并暴露 assetsGuard') + const bak2 = JSON.parse(fs.readFileSync(path.join(R2, 'data.json.bak'), 'utf8')) + assert.strictEqual(Object.keys(bak2.assets).length, 40, '② 异常时绝不能覆盖好的 bak') + const log = fs.existsSync(path.join(R2, '_boot.log')) ? fs.readFileSync(path.join(R2, '_boot.log'), 'utf8') : '' + assert.ok(log.indexOf('assets-regress-load') >= 0, '② 必须留下 assets-regress-load 日志') + + fs.rmSync(R1, { recursive: true, force: true }) + fs.rmSync(R2, { recursive: true, force: true }) + console.log('storage-assets-guard: 5 通过 / 0 失败') +})().catch((e) => { console.error('storage-assets-guard FAILED:', e && (e.stack || e.message)); process.exit(1) }) + diff --git a/tests/storage-flush-persist-test.js b/tests/storage-flush-persist-test.js index 1cbe63f..ac16745 100644 --- a/tests/storage-flush-persist-test.js +++ b/tests/storage-flush-persist-test.js @@ -65,6 +65,9 @@ const boot = async () => { if (cmd === 'stat_many') return (args.rels || []).map((rel) => { try { const st = fs.statSync(path.join(base, rel)); return { rel: rel, exists: true, size: st.size, mtime: st.mtimeMs } } catch (e) { return { rel: rel, exists: false, size: 0, mtime: 0 } } }) + if (cmd === 'read_files_b64') return (args.rels || []).map((rel) => { + try { return { rel: rel, b64: fs.readFileSync(path.join(base, rel)).toString('base64') } } catch (e) { return { rel: rel, error: String(e && e.message) } } + }) if (cmd === 'list_dir_entries') { const dir = path.join(base, String(args.rel || '')) return fs.readdirSync(dir, { withFileTypes: true }).map((d) => { @@ -118,6 +121,11 @@ const boot = async () => { await F1.flush() assert.ok(readFile('canvases/ws1.json').includes('hello-edited'), '① 画布编辑必须立刻落盘(会被 writing 卡死吞掉)') + // 批次 A2:批量缩略图(一次列目录 + 一次批量读) + writeSeed('images/thumbs/abcdef0123456789_768.webp', 'RIFFxxxxWEBPVP8 ') + const many = await F1.readDisplayThumbsMany([{ hash: 'abcdef0123456789', max: 768 }]) + assert.ok(many && String(many['abcdef0123456789_768'] || '').indexOf('data:image/webp;base64,') === 0, 'A2 批量缩略图应返回 dataURL') + F1.storage().setItem('iwb_web_config', '{"x":1}') await F1.flush() const data = JSON.parse(readFile('data.json')) @@ -149,6 +157,6 @@ const boot = async () => { assert.ok(readFile('canvases/ws1.json').includes('hello-retry'), '⑤ 失败键应在重试后落盘(否则等于一次失败永久丢)') fs.rmSync(ROOT, { recursive: true, force: true }) - console.log('storage-flush-persist: 10 通过 / 0 失败') + console.log('storage-flush-persist: 11 通过 / 0 失败') })().catch((e) => { console.error('storage-flush-persist FAILED:', e && (e.stack || e.message)); process.exit(1) })