From bed29b367446b2d9f07a41e2a3b31a78ad43cad9 Mon Sep 17 00:00:00 2001 From: qiqi Date: Fri, 4 Dec 2026 14:49:00 +0800 Subject: [PATCH] =?UTF-8?q?fix(storage):=20=E4=BF=AE=20flush=20=E5=86=99?= =?UTF-8?q?=E7=9B=98=E9=80=9A=E9=81=93=E8=A2=AB=E6=B0=B8=E4=B9=85=E5=8D=A1?= =?UTF-8?q?=E6=AD=BB=EF=BC=88=E7=94=BB=E5=B8=83=E6=94=B9=E5=8A=A8=E9=87=8D?= =?UTF-8?q?=E5=90=AF=E5=8D=B3=E4=B8=A2=EF=BC=89+=20=E5=9B=9E=E5=BD=92?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 7 ++ CONTRIBUTING.md | 2 +- docs/standards/architecture-current-state.md | 2 +- package.json | 4 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- src/storage-file.js | 16 ++- tests/storage-flush-persist-test.js | 117 +++++++++++++++++++ 9 files changed, 141 insertions(+), 13 deletions(-) create mode 100644 tests/storage-flush-persist-test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cf167e..bb3b3c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,13 @@ - 历史条目补录:该 tag 当时未在 CHANGELOG 记录(release-records 守卫要求 tag 与条目双向一致),内容按当时提交补一句占位说明。 +## v3.26.247(2026-12-04)修存储写盘通道被永久卡死(画布改动重启即丢) + +- 根因:244 的「内容未变不写盘」让启动那次 flush 变全同步,`writing = (async(){…finally{writing=null}})()` 在函数体没有 await 时先执行 finally、再被赋值成一个永不清理的已解决 promise ⇒ 之后每次 flush 都直接 return,整个会话不再写盘(画布/设置/图库索引全停写) +- 修法:flush 先赋值 `writing = p` 再 `await p`,收尾用 `if (writing === p) writing = null` 判定,彻底避开同步完成竞态 +- 三处一次性维护(图库缩略图回填 / 图库自愈重建 / 清内联缩略图)改为经 storage.setItem 写,补上 244 新增的 libDirty 标记 +- 新增 tests/storage-flush-persist-test.js:真实 storage-file + 假 Tauri fs,断言「启动 → 连续 flush → 编辑 → 落盘 → 重载仍在」,并验证旧实现必红 + ## v3.26.246(2026-12-05)参考图:气泡图标对调、本地图去掉 URL 输入 - 气泡图标对调:替换 = 图片+号(ref),上传到图库 = 上行箭头(upload) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6452da7..ad2ffcd 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 143 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底)) +test:unit 144 个单测文件(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/docs/standards/architecture-current-state.md b/docs/standards/architecture-current-state.md index 557d8e1..8d52d70 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,515 行**(**双层预算**:绝对上限 9,529 / 占总源码 ≤ 40%,现 **26.4%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,706 行**(上限 **2,706**,余量 0;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **129** 个模块 / 26,519 行,`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,515 行**(**双层预算**:绝对上限 9,529 / 占总源码 ≤ 40%,现 **26.4%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,706 行**(上限 **2,706**,余量 0;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **129** 个模块 / 26,523 行,`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 90b962e..d0bfdc7 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "image-workbench-web", "private": true, - "version": "3.26.246", + "version": "3.26.247", "description": "Browser-based node canvas image workbench", "scripts": { "build": "node scripts/build.js && node scripts/copy-plugins.js", @@ -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", + "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", "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/Cargo.lock b/src-tauri/Cargo.lock index 6e71885..bb0c4d3 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2014,7 +2014,7 @@ dependencies = [ [[package]] name = "image-workbench" -version = "3.26.246" +version = "3.26.247" dependencies = [ "arboard", "base64 0.22.1", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 88fcbd8..42d0f28 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "image-workbench" -version = "3.26.246" +version = "3.26.247" description = "无限画布 · 生图工作台桌面版" authors = ["malongan"] license = "" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 6f3df50..e357b0d 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.246", + "version": "3.26.247", "identifier": "com.malongan.imageworkbench", "build": { "frontendDist": "../dist", diff --git a/src/storage-file.js b/src/storage-file.js index 093e9e6..82dc079 100644 --- a/src/storage-file.js +++ b/src/storage-file.js @@ -98,7 +98,10 @@ const dataSig = JSON.stringify(parts) const body = JSON.stringify(Object.assign({ v: SCHEMA, at: Date.now() }, parts)) const target = await join(dir, DATA_FILE) - writing = (async () => { + // 2026-12-04:先赋值、再 await —— 若函数体没有 await(244 之后启动那次 flush 就是全同步: + // 画布不脏、库不脏、data.json 签名相同),IIFE 会同步跑完把 writing 置回 null,随后赋值又写成 + // 一个已解决的 promise,此后所有 flush 都卡在「if (writing) return writing」⇒ 整个会话不再写盘。 + const p = (async () => { try { if (wsDirty.length) { const cdir = await join(dir, CANVAS_DIR) @@ -147,9 +150,10 @@ } catch (e) { try { await fs().writeTextFile(target, body) } catch (e2) { /* ignore */ } return false - } finally { writing = null } + } })() - return writing + writing = p + try { return await p } finally { if (writing === p) writing = null } } // 图片:内容哈希(SHA-256 前 16 位)→ images/.,同图只存一份 @@ -373,7 +377,7 @@ n++ } catch (e) { /* 单张失败忽略 */ } } - if (n) { mem['iwb_web_outputs'] = JSON.stringify(items); await flush() } + if (n) { storage.setItem('iwb_web_outputs', JSON.stringify(items)); await flush() } await fs().writeTextFile(marker, String(n)) return n } catch (e) { return 0 } @@ -1026,7 +1030,7 @@ it.thumbHash = String(a.f).split('/').pop().replace(/\.[^.]+$/, '') } catch (e) { /* 单张失败不影响其它 */ } } - mem['iwb_web_outputs'] = JSON.stringify(items) + storage.setItem('iwb_web_outputs', JSON.stringify(items)) await flush() await blog('gallery:rebuilt ' + items.length) } @@ -1576,7 +1580,7 @@ if (!it || !it.data) continue if (it.thumbHash && map[String(it.thumbHash)]) { it.data = ''; n++ } } - if (n) { mem['iwb_web_outputs'] = JSON.stringify(items); await flush() } + if (n) { storage.setItem('iwb_web_outputs', JSON.stringify(items)); await flush() } await fs().writeTextFile(marker, String(n)) return n } catch (e) { return 0 } diff --git a/tests/storage-flush-persist-test.js b/tests/storage-flush-persist-test.js new file mode 100644 index 0000000..cbd4440 --- /dev/null +++ b/tests/storage-flush-persist-test.js @@ -0,0 +1,117 @@ +/* storage-flush-persist-test.js —— 「没变化就不写」之后,编辑必须仍然落盘(v3.26.247) + * + * 背景(2026-12-04 回归):244 引入「内容未变不写盘」后,启动那次 flush 变全同步 + * (画布不脏 / 库不脏 / data.json 签名相同)。原实现是 + * writing = (async () => { ... finally { writing = null } })() + * 函数体没有 await 时 IIFE 同步跑完,finally 先把 writing 置 null,随后赋值又把 writing 写成 + * 一个已解决且永不清理的 promise ⇒ 此后每次 flush 都在 if (writing) return writing 处直接返回, + * 整个会话不再写盘(用户实测:画布改动重启后消失)。 + * + * 本用例跑真实 src/storage-file.js + 假 Tauri fs(真实临时目录),断言行为: + * ① 启动后编辑画布 → flush → 磁盘文件变化 → 重载(新实例)仍在 + * ② 启动(无改动)后连续 flush 两次不把写盘通道卡死 + * ③ 非分板键写进 data.json + * ④ 资源库键写进 library/<文件>(含 gallery 新布局) + * ⑤ 一次性维护路径也经由 storage.setItem 标脏(不直写 mem) + */ +'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 ROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'iwb-flush-persist-')) + +const writeSeed = (rel, text) => { + const abs = path.join(ROOT, rel) + fs.mkdirSync(path.dirname(abs), { recursive: true }) + fs.writeFileSync(abs, text) +} +const readFile = (rel) => fs.readFileSync(path.join(ROOT, rel), 'utf8') + +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) { /* 不存在 */ } }, + mkdir: async (p) => { fs.mkdirSync(p, { recursive: true }) }, + exists: async (p) => fs.existsSync(p), + readDir: async (p) => { + if (!fs.existsSync(p)) throw new Error('ENOENT') + return fs.readdirSync(p, { withFileTypes: true }).map((d) => ({ name: d.name, isDirectory: d.isDirectory(), isFile: d.isFile() })) + }, + stat: async (p) => fs.statSync(p), +}) + +// 每个「进程」一个独立 global:模拟重启 +const boot = async () => { + const ls = new Map([['iwb.dataDir', ROOT]]) + 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 load = new Function('window', 'globalThis', SRC + '\nreturn window.IWBStorageFile') + const F = load(g, g) + const ok = await F.ready({ dir: ROOT }) + assert.ok(ok, '存储底座应能初始化') + return F +} + +;(async () => { + const WS1 = '{"id":"ws1","name":"c1","nodes":[{"id":"n1","type":"text","data":{"text":"hello"}}],"edges":[],"groups":[]}' + writeSeed('canvases/ws1.json', WS1) + writeSeed('data.json', JSON.stringify({ v: 1, keys: {}, assets: {}, small: {} })) + + const F1 = await boot() + assert.strictEqual(F1.storage().getItem('iwb_ws_ws1'), WS1, '① 启动应把画布文件读进内存表') + + // ② 启动那次 flush 是全同步路径:连续两次不能让写盘通道卡死 + await F1.flush() + await F1.flush() + + const WS2 = WS1.replace('hello', 'hello-edited') + F1.storage().setItem('iwb_ws_ws1', WS2) + await F1.flush() + assert.ok(readFile('canvases/ws1.json').includes('hello-edited'), '① 画布编辑必须立刻落盘(会被 writing 卡死吞掉)') + + F1.storage().setItem('iwb_web_config', '{"x":1}') + await F1.flush() + const data = JSON.parse(readFile('data.json')) + assert.strictEqual(data.keys.iwb_web_config, '{"x":1}', '③ 非分板键应写进 data.json') + + writeSeed('library/gallery.json', '[]') + F1.storage().setItem('iwb_web_outputs', '[{"name":"a.png"}]') + await F1.flush() + assert.ok(readFile('library/gallery/index.json').includes('a.png'), '④ 图库清单应写到 library/gallery/index.json') + assert.ok(!fs.existsSync(path.join(ROOT, 'library/gallery.json')), '④ 新布局写成功后应删掉旧的平铺文件') + + const F2 = await boot() + assert.ok(String(F2.storage().getItem('iwb_ws_ws1')).includes('hello-edited'), '① 重启后编辑仍在(用户实测的回归点)') + assert.strictEqual(F2.storage().getItem('iwb_web_config'), '{"x":1}', '③ 重启后非分板键仍在') + assert.ok(String(F2.storage().getItem('iwb_web_outputs')).includes('a.png'), '④ 重启后图库清单仍在') + + assert.ok(!/mem\['iwb_web_outputs'\]\s*=\s*JSON\.stringify/.test(SRC), '⑤ 维护路径应经 storage.setItem 标脏,不能直写 mem 后 flush') + + fs.rmSync(ROOT, { recursive: true, force: true }) + console.log('storage-flush-persist: 8 通过 / 0 失败') +})().catch((e) => { console.error('storage-flush-persist FAILED:', e && (e.stack || e.message)); process.exit(1) }) +