Compare commits

...
21 Commits
Author SHA1 Message Date
qiqi bf7ed841ae fix(gallery): 收紧插入取源顺序与归档通知时序(自查发现)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m35s
- localCopySrcOf 取源改为「原图文件 → 远程原图(8s 上限)→ 缩略图」:上一版把 320 缩略图
  排在远程之前,会出现「有远程原图却插进一张小图」,标注完导出才发现糊了。顺序与宿主既有
  口径(wResolveOutputSrc 默认 url 优先于 localData)一致;超时保护避免慢图床拖着插入不放。
- refreshOutputs 改为返回 Promise:逐张归档要在 emit 之前确认 React outputs 已换成新列表
  (插件的 list/thumb 读的就是这份 state),否则通知到了却还是旧列表。
- 新增一条测试守住「别拿缩略图顶替远程原图」;BACKLOG 记 1.2(标注插件「转存」文案无对应
  入口 / 一次失败不再重试)。
2026-11-24 17:16:13 +08:00
qiqi e94012db84 docs: 锚点对齐 v3.26.61+9b78535(图库出图即见 + 插入落本地副本)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m42s
2026-11-24 17:12:26 +08:00
qiqi 9b78535791 feat(gallery): v3.26.61 出图即入图库 + 插入落地本地副本(能标注)
用户报障:① 生图后图库不显示上游传来的图 ② 图库多个入口插入的是链接,画布不能标注。
用户裁定 B6 = 复制:多占空间可以接受,要求不丢数据。

出图即见
- handleCompletedJob 每张完成即 archiveEntryNow(串行队列 + 等缩略图),不再只在整轮结束写一次
- 宿主新增 IWBPluginGallery.emit / onChanged;图库插件订阅后 260ms 防抖重拉
  (此前只有「面板可见且距上次拉取 >5s」一个入口,生成时面板一直可见 ⇒ 永远不刷)

插入能标注
- insertOutputsToCanvas 取源改本地字节优先:原图档 → 清单 data → 缩略图 → 按需抓远程
  (桌面端走 Rust 请求不受 CORS)→ 按档缩尺寸 → {__blob} 引用(字节落 images/canvas/)
- 抓不到才保留原链接,节点 data.srcUrl 留痕 + toast 提示「可能无法标注」;图库拖入同一收口
- getNodeImage 候选补 data.localRef(远程参考图本地缓存字段):此前漏读它 ⇒ 缓存命中过,
  标注插件仍只看到 http 链接并判「远程图片不支持标注」,这是报障②的直接成因

批量插入不再叠图
- 旧实现循环里每张各自 findSpot,而 findSpot 只看已提交节点 ⇒ 同批全落一处;
  改为一次 commit + 4 列栅格铺开

gallery 1.7.0
- 格子「插入」补 insertK(此前忽略插入尺寸档,与右键/顶部不一致)
- 插入补「插入中…」状态;删除改为等宿主删完再重拉(固定 250ms 会拉到未删完的清单)

结构
- 新增 src/gallery-sync.js(约 200 行),app.js 只 attach 装配;新增 tests/gallery-sync-test.js(11 项)
- 行数棘轮 9095 → 9115:+13 行是注入表与 commit 分发(闭包组件内 state),+6 行是纠错注释;
  同时新增一个 src 模块 ⇒ 占比棘轮反而下降。理由已写入棘轮文件

口径纠错(用户要求把旧的不准确描述改掉)
- 图库/缩略图/原图档在桌面端是 images/thumbs、images/gallery 文件,不是 IndexedDB
- 1K 插入档降的是长边像素不是体积(PNG 源仍无损,1024 复杂图 ~500KB~1MB)
- docs/plans/gallery-insert-perf-v324.md 加时效注记(网页版时期口径)
2026-11-24 17:11:01 +08:00
qiqi 5e127bd23f docs(site): v3.26.60 补 Windows x64 记录
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 54s
2026-11-24 15:52:14 +08:00
qiqi 0c1c30dc20 chore(release): v3.26.60 下载站与发布记录(mac 双架构 dmg)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 46s
2026-11-24 15:35:22 +08:00
qiqi 6002c34c0f docs: 锚点对齐 v3.26.60+cf0e9a0(浮层字号上调一档) 2026-11-24 15:33:13 +08:00
qiqi cf0e9a09b9 style(popover): v3.26.60 浮层字号上调一档(模型设置/图像设置不再小字)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 46s
用户反馈两个贴节点浮层的选项文字偏小。改动集中在 .iwb-pop 的 6 个 token
(两个面板共用同一套,改一处两边同步):

- --iwb-pop-chip-size   font-xs(11) → font-md(13)
- --iwb-pop-chip-h      22px → 28px
- --iwb-pop-chip-pad-x  space-6(6) → space-10(10)
- --iwb-pop-chip-gap    space-4(4) → space-6(6)
- --iwb-pop-title-size  font-sm(12) → font-base(14)
- --iwb-pop-w           328px → 360px(抵消放大后多出来的换行)

辅助小字同步:.iwb-setlabel 11→12、.iwb-setalign/.iwb-gc-label/.iwb-gc-sub
12→13、.iwb-pop .iwb-set-num 12→13、新增 .iwb-pop .iwb-hint 10→12。

顺带修 .iwb-gen-config 宽度写死 min(92vw,320px)(绕过 token,字号放大后
不跟着变宽)→ 引用 var(--iwb-pop-w)。

契约不变:模型名仍单行不省略、超长独占一行(min-width:max-content +
面板横向滚动兜底);作用域只在 .iwb-pop,画布节点与左栏不受影响。

验证:headless Chromium 实测 面板 360 / 胶囊 28px·13px·padding10 /
标题 14 / 标签 12 / 说明 12 / 数字框 13·28·68,无文字截断、无横向滚动;
lint:tokens 0 处新增裸值;design-token-ratchet 13 项未超基线
(字号写死 159→152、圆角 95→92、间距 377→366);test:unit 全绿。
2026-11-24 15:32:55 +08:00
qiqi 83029e9bc7 chore(release): v3.26.59 下载站与发布记录(mac 双架构 dmg)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m3s
2026-11-24 15:19:19 +08:00
qiqi 2ca9512b49 docs: 锚点对齐 v3.26.59+e966b34(备份带插件文件)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m36s
2026-11-24 15:16:11 +08:00
qiqi e966b348b9 feat(backup): v3.26.59 备份带上插件文件(提示词封面不再换机丢失)
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
2026-11-24 15:16:08 +08:00
qiqi 054db215cd feat(plugins): 同步提示词库 promptlib v1.10.1(移除封面开关 + 详情竖向分割线)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 46s
2026-11-24 14:25:17 +08:00
qiqi b34b936d2e feat(plugins): 同步提示词库 promptlib v1.10.0(文本/文件分享双路径 + 新入口布局)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m11s
2026-11-24 14:19:15 +08:00
qiqi 1ebb07d389 feat(plugins): 同步提示词库 promptlib v1.9.3(编辑区变量浅主色底色)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m3s
2026-11-24 13:36:10 +08:00
qiqi b45d6b2712 feat(plugins): 同步提示词库 promptlib v1.9.2(分享封面开关)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 45s
2026-11-24 13:25:26 +08:00
qiqi 7e99b2ba42 docs(site): v3.26.58 补 Windows x64 记录
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m7s
2026-11-24 12:46:01 +08:00
qiqi d77c70bf67 docs(site): v3.26.58
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 41s
2026-11-24 12:11:09 +08:00
qiqi 129fedc596 docs: 锚点对齐 v3.26.58+ffd342f(publish 自动) 2026-11-24 12:09:42 +08:00
qiqi ffd342fa4c release: v3.26.58 浮层紧凑规格 C1 2026-11-24 12:08:19 +08:00
qiqi fdfaf9e12f style(popover): 采用 C1 紧凑规格(328 宽 / 22px 选项 / 11px 字号),宽度改走 token 2026-11-24 12:08:19 +08:00
qiqi 1d9ef0cc99 feat(plugins): 同步便利贴 sticky v1.0.7(自定义调色后自动收起色板)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 48s
2026-11-24 11:55:08 +08:00
qiqi 18dad1b9af feat(plugins): 同步便利贴 sticky v1.0.6(文本回缩外框自动降高)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 33s
2026-11-24 11:52:28 +08:00
44 changed files with 1551 additions and 296 deletions

No files matched your search

+16
View File
@@ -138,6 +138,22 @@
---
### 1.2 标注插件「远程图片不支持标注」的收尾(2026-11-24 · 中等收益)
> 证据:`image-annotate/src/index.js:9218` 只在 `getNodeImage` 返回 `dataUrl` 时才开编辑器,否则报
> 「该节点是远程图片,暂不支持标注(请先转存为本地位图)」。
v3.26.61 已把三个成因收敛掉(`getNodeImage` 补 `data.localRef` 候选 / 只有远程时按需抓字节并写回
`localRef` / 图库插入改本地副本),但两条尾巴还在:
1. **文案里的「转存」没有对应入口** —— 抓取失败(离线、图床拦跨域且不在 Tauri http 白名单)时,
用户看到「请先转存为本地位图」却找不到按钮。二选一:① 画布 ref 节点右键加「转存为本地图片」
(`wImgRefWrite` → `localRef`);② 把文案改成可执行引导(「下载到本地后拖进画布」)。
2. **一次失败不再重试** —— `image-remote-cache` 的 `tried` 集合记住节点 id 后永不重试;网络恢复后
只能靠用户手动再点。可加「右键重试取图」。
---
## 2. P1 — 有明确证据支撑,价值高
### 2.0 ✅ 图库索引(`OUT_KEY`)跨标签页「读-改-写」—— **已修(2026-11-16,v3.24.85)**
+57
View File
@@ -16,6 +16,63 @@
> 3. 核验正式地址版本 → 之后才移动 `stable` / `stable-verified-<日期>` 标签、更新本 CHANGELOG、写 GitHub Release(`gh release create`)。
> 测试发现问题 → 改 → 再 `deploy:test`,正式环境不受影响。回滚点 `git reset --hard stable`。
## v3.26.61(2026-11-24)图库:出图即见 + 插入落地本地副本(能标注)
> 状态:代码完成(宿主 + gallery 1.7.0)
用户报障两条:①「生图后图库不能及时显示上游传来的图」②「多个入口插入的是上游图片链接,画布不能标注」。
用户裁定 B6 = **复制**(多占空间可以接受,要求不丢数据)。
- **出图即见**:归档从「整轮结束写一次」改为**每张完成即入库**(`handleCompletedJob` → `archiveEntryNow`)。
串行队列避免并发读改写索引互相吃;等这张的缩略图落盘再通知,避免插件先闪远程大图。
宿主新增 `IWBPluginGallery.emit`,图库插件订阅 `ctx.gallery.onChanged`(260ms 防抖重拉)——
此前只有「面板重新可见且距上次拉取 >5s」一个入口,而生成时面板一直可见 ⇒ 永远不刷。
- **插入能标注**:`insertOutputsToCanvas` 取源改为「本地字节优先」——原图档 → 清单 data → 缩略图 →
按需抓一次远程(桌面端走 Rust 请求,不受 CORS)→ 压缩 → `{__blob}` 引用(字节落 `images/canvas/`)。
抓不到才保留原链接,节点 `data.srcUrl` 留痕,toast 明确提示「可能无法标注」。图库拖入同一收口。
- **批量插入不再叠图**:旧实现在循环里每张各自 `findSpot`,而 `findSpot` 只看已提交节点 ⇒ 同批全落一处。
改为一次 commit + 4 列栅格铺开。
- **插件取图补 `localRef`**:`canvasBridge.getNodeImage` 候选列表漏了 `data.localRef`(远程参考图本地缓存
写的字段)⇒ 缓存明明命中,标注插件仍只看到 http 链接并判「远程图片不支持标注」。只有远程时按需
抓一次字节并写回 `localRef`,抓不到才返回 `{ url }`。
- gallery 1.7.0:格子「插入」补 `insertK`(此前忽略「插入尺寸」档,与右键/顶部不一致);插入/删除补
「插入中…」状态;删除改为等宿主删完再重拉(固定 250ms 会拉到未删完的清单,格子出现「图片已丢失」)。
- 新增 `src/gallery-sync.js`(取源/归档/栅格/取图的判定都在这),app.js 只 `attach(...)` 装配;
新增 `tests/gallery-sync-test.js`(11 项)。行数棘轮 9095 → 9115(理由记在棘轮文件里)。
- 纠错过时口径(用户要求):图库/缩略图/原图档在桌面端是 `images/thumbs`、`images/gallery` 文件,
不是 IndexedDB;「1K 插入档降的是长边像素、不是体积」(PNG 源仍无损输出,1024 复杂图 ~500KB~1MB)。
## v3.26.60(2026-11-24)浮层字号上调一档(「模型设置 / 图像设置」不再小字)
> 状态:正式发布(macOS arm64 / x86_64)
- 用户反馈两个贴节点浮层里的选项文字偏小,整体放大一档:选择项 **11 → 13px**、高度 **22 → 28px**、左右内距 **6 → 10px**、间距 **4 → 6px**、面板标题 **12 → 14px**,面板宽 **328 → 360px**(抵消放大后多出来的换行)
- 辅助小字同步:分组标签(质量/尺寸/分辨率/宽高比)11 → 12、`16 倍数对齐` 与服务商/分组/模型标签 12 → 13、尺寸数字框 12 → 13、浮层内说明文字 10 → 12
- 改动全部落在 `.iwb-pop` 的 6 个 token 上(两个面板共用同一套),模型名「单行不省略、超长独占一行」的契约不变
- `.iwb-gen-config` 的宽度原来写死 `min(92vw, 320px)`(绕过 token,字号放大后不跟着变宽)→ 改为引用 `--iwb-pop-w`
- 同步 `docs/standards/design-tokens.md` §3.13 的 token 表;token 棘轮三项计数顺带下降(字号写死 159→152、圆角 95→92、间距 377→366)
## v3.26.59(2026-11-24)备份带上插件文件(提示词封面不再换机丢失)
> 状态:正式发布(macOS arm64 / x86_64)
- **P0 备份补洞**:`plugin-data/<id>/files/` 里的插件文件(提示词封面等)随 ZIP 写成 `plugin-files/<id>/<文件名>`,恢复时写回沙箱。此前只备份 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)
- 面板宽 380 → **328**,内边距 16/20 → 10/12,分组间距 8
- 选项高 32 → **22px**,字号 13 → **11px**,左右内边距 12 → 6,圆角 8 → 6
- 分组标签 12 → 11px + 600 字重;数字框与选项同高
- 图像设置面板高度 496 → **约 310px**(含提示行)
- 修 `.iwb-image-settings` 硬编码 `width:380px` 覆盖 `--iwb-pop-w` 的问题,宽度只认 token
- 规范 §3.13 同步为 C1 数值
## v3.26.57(2026-11-24)节点浮层收口:去掉左上闪现、选择项统一尺寸、popover token
> 状态:正式发布(macOS arm64 / x86_64)
+1 -1
View File
@@ -40,7 +40,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 124 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
test:unit 125 个单测文件(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)
+58 -38
View File
@@ -840,7 +840,9 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
// ==== 丙方案 C3:图片引用直出(hydrate 不再把图片字节读回 base64 常驻 JS 堆)====
// 画布记录里只留引用,字节独立存放(对标 opentu 的资产模型:记录 = 引用 + 元数据):
// · { __cache: '/__iwb_cache__/<hash>' } —— 方案A 既有形态;字节在 Cache Storage,sw.js 可直出虚拟路径
// · { __blob: 'imgblob_<hash>_<len>' } —— C3 新形态;字节在 IndexedDB 的 Blob(src/image-blob-store.js)
// · { __blob: 'imgblob_<hash>_<len>' } —— C3 新形态;字节落在**注入的 idb 后端**(src/image-blob-store.js):
// 浏览器 = IndexedDB;桌面端 = storage-file 的文件 KV(见 wImageBlobStore 的 storageRuntime 注入)⇒
// 实际是 images/canvas/<sha16>.<ext> + data.json 的 assets 登记。判读口径见 docs/standards/image-storage-map.md
// 显示层统一经 wResolveImg 解析为**本会话 objectURL**(caches.match / IDB.getBlob → wRegisterBlobUrl)。
// objectURL **单一归属**:一律由 wRegisterBlobUrl 创建并登记(拿得回原 Blob,绕开 CSP 对 fetch(blob:) 的拦截),
// 由 wImgUrlByRef 台账回收;**不调用** ImageBlobStore.resolveUrl/revokeAll —— 否则同一张图会有两套 URL
@@ -1741,7 +1743,9 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
if (!ProviderPing) return Promise.resolve({ results: urls.map((u) => ({ url: String(u || '').trim(), ok: false, ms: 0, error: '测速模块未加载' })) })
return ProviderPing.pingAll(urls, { normalizeEndpointBase: (_wCfgShape && _wCfgShape.normalizeEndpointBase) || null })
}
// 历史出图(IndexedDB 缩略图 + localStorage 索引;图床 URL 只作显示兜底,图床过期不丢图库图)
// 历史出图:索引在 localStorage(out_ 前缀),字节落「注入的 idb 后端」——浏览器 = IndexedDB,
// 桌面端 = storage-file 文件 KV(images/thumbs 缩略图 / images/gallery 原图档);图床 URL 只作显示兜底。
// 判读口径见 docs/standards/image-storage-map.md
const OUT_KEY = StorageContract.localKeys.outputs
const RuntimeConstants = (typeof window !== 'undefined' && window.IWBRuntimeConstants) || { outputLimit: 10000, galleryRanges: {} }
const GalleryHydration = typeof window !== 'undefined' && window.IWBGalleryHydration
@@ -1841,8 +1845,9 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
return { removed, files: existing.size }
}
const imageFolderApi = { pick: imageFolderPick, sync: imageFolderSync, save: imageFolderSaveItem, name: imageFolderName }
// 生成图 → 压缩缩略图 dataURL → IndexedDB(图库显示用;原图仍走图床 URL,放大/下载时用图床或本地上传)
// 失败(跨域/网络)静默:仅保留图床 URL,显示回退
// 生成图 → 压缩缩略图 dataURL → 缩略图存储(浏览器 IndexedDB / 桌面端 images/thumbs 文件);
// 原图档另写 out_orig_(只有「应用内备份原图」开启时;桌面端落在 images/gallery/)。
// 两张都抓不到(图床跨域/网络)时静默降级:只保留图床 URL 作显示与下载兜底。
// 调试计数器:仅在显式开启时记录高频路径,默认完全关闭。
function iwbDebugCounter(name, extra) {
if (typeof window === 'undefined' || window.__IWB_DEBUG__ !== true) return
@@ -1967,7 +1972,8 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
const maxFiles = Number(ret.maxFiles) || 0
if (maxDays > 0) list = list.filter((f) => now - f.mtime <= maxDays * 86400e3)
list = list.sort((a, b) => (b.mtime - a.mtime)).slice(0, maxFiles > 0 ? maxFiles : RuntimeConstants.outputLimit)
// hydrate:IndexedDB 缩略图 → data 字段(图床 URL 仍作兜底显示);limit>0 时只 hydrate 前 limit 张(列表分页加载,缓解首开慢)
// hydrate:缩略图 → data 字段(清单只存 thumbHash/idb 键,桌面端的字节在 images/thumbs/);
// 图床 URL 仍作兜底显示。limit>0 时只 hydrate 前 limit 张(列表分页加载,缓解首开慢)
const hydList = (args && typeof args.limit === 'number' && args.limit > 0) ? list.slice(0, args.limit) : list
if (galleryHydrator) {
const hydrated = await galleryHydrator.hydrate(hydList)
@@ -2058,26 +2064,33 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
}
return added
}
// ── 图库同步边界(v3.26.61)───────────────────────────────────────────────
// 逻辑在 src/gallery-sync.js(单张归档串行队列 / 通知插件 / 条目→本地字节 / 插入栅格 / 节点取图),
// 这里只把现有能力装配进去;装配表放在一行是因为 app.js 有行数棘轮(新功能必须落 src)。
const wGallerySync = (typeof window !== 'undefined' && window.IWBGallerySync) ? window.IWBGallerySync.attach({ addOutputs: (items, o) => wAddOutputs(items, o), flatten: (entries) => flattenGenerationEntries(entries), emit: (reason) => { try { if (typeof window !== 'undefined' && window.IWBPluginGallery) window.IWBPluginGallery.emit(reason) } catch (e) { /* ignore */ } }, get: (k) => IDB.get(k), refDataUrl: (v) => wImgRefDataUrl(v), isDesktop: () => wIsTauri(), desktopFetch: (u) => (wTauri && wTauri.http && typeof wTauri.http.fetch === 'function') ? wTauri.http.fetch(u) : Promise.reject(new Error('no-http')), blobFromSrc: (s) => wBlobFromSrc(s), blobToDataUrl: (b) => wImgBlobToDataUrl(b), notice: (msg) => wLogNotice(String(msg || ''), 'err') }) : null
const wArchiveEntryNow = (entry, refresh) => (wGallerySync ? wGallerySync.archiveEntryNow(entry, refresh) : Promise.resolve(false))
const wGalleryChanged = (reason) => { if (wGallerySync) wGallerySync.notifyChanged(reason) }
const wDelGalleryBytes /* 图库删图一并清理磁盘字节(只删索引会留下文件) */ = (names) => { const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null; try { if (F && F.deleteGalleryBytesFor) F.deleteGalleryBytesFor(names, lsGet(OUT_KEY, [])).catch(() => {}) } catch (e) { /* ignore */ } }
async function wActionOutputs(args) {
const action = args && args.action
if (ModularOutputStore && action === 'clear') {
await wClearOutputIdb() // 原图 out_orig_ 不在 ModularOutputStore 管辖,单独整体清空
const modular = await ModularOutputStore.clear()
if (modular && modular.ok) return { ok: true }
if (modular && modular.ok) { wGalleryChanged('clear'); return { ok: true } }
}
if (ModularOutputStore && action === 'delete') {
const names = Array.isArray(args.names) ? args.names : []
await wPruneOutputIdb(names); await wDelGalleryBytes(names) // 缩略图 + 原图 + 磁盘字节
const modular = await ModularOutputStore.remove(names)
if (modular && modular.ok) return { ok: true, removed: modular.meta && modular.meta.removed !== undefined ? modular.meta.removed : names.length }
if (modular && modular.ok) { wGalleryChanged('remove'); return { ok: true, removed: modular.meta && modular.meta.removed !== undefined ? modular.meta.removed : names.length } }
}
if (action === 'clear') { await wClearOutputIdb(); lsSet(OUT_KEY, []); return { ok: true } }
if (action === 'clear') { await wClearOutputIdb(); lsSet(OUT_KEY, []); wGalleryChanged('clear'); return { ok: true } }
if (action === 'delete') {
const names = Array.isArray(args.names) ? args.names : []
await wPruneOutputIdb(names); await wDelGalleryBytes(names)
const idx = lsGet(OUT_KEY, [])
lsSet(OUT_KEY, idx.filter((f) => !names.includes(f.name)))
wGalleryChanged('remove')
return { ok: true, removed: names.length }
}
if (action === 'restore') {
@@ -2086,6 +2099,7 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
const files = Array.isArray(args.files) ? args.files : []
if (ModularOutputStore) await ModularOutputStore.mutate(() => files).catch(() => null)
else lsSet(OUT_KEY, files)
wGalleryChanged('restore')
return { ok: true, restored: files.length }
}
return { ok: true }
@@ -2187,8 +2201,8 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
}
// 图库条目取画质最优的 src:优先本地原图(out_orig_)→ 远程 url(原分辨率,<img> 不受 CORS)→ 缩略图(data/out_)兜底。
// 用于预览/下载/复制/插入/拖到画布为参考图,保证参考图是清晰原图/高清远程,缩略图仅作网格展示。
// 运行时缩略图缓存:url → IndexedDB 缩略图 dataURL。输出节点网格优先用本地缩略图(快、不随远程 URL 失效),
// 远程 URL 仅作兜底,避免「图床 URL 慢/过期导致输出节点图片空白或消失」。
// 运行时缩略图缓存:url → 缩略图 dataURL(桌面端字节在 images/thumbs/)。输出节点网格优先用本地缩略图
// (快、不随远程 URL 失效),远程 URL 仅作兜底,避免「图床 URL 慢/过期导致输出节点图片空白或消失」。
// v3.87.8 数据保护:用户"明确彻底删除"的画板 id(只作用于紧随其后的那次写入)。
// 用途:写索引时做并集守卫——存储里已有的画板不能被"漏掉"(本机实测出现过"画布从列表消失")。
const wPurgeIntent = new Set()
@@ -3740,9 +3754,13 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
}
// 生成归档边界:图库索引/缩略图属于旁路缓存,不能阻塞生成结果和画布保存。
// v3.26.61:每张结果在生成过程中已由 wArchiveEntryNow 逐张入库(图库要「出图即见」),
// 这里只补剩下没归档的(失败条目/兜底路径),不再整批重写一遍 —— 否则同一张图会入两次库。
async function archiveGenerationResults(entries, refresh) {
const results = flattenGenerationEntries(entries)
const all = Array.isArray(entries) ? entries : []
const results = flattenGenerationEntries(all)
iwbDebugCounter('archiveGenerationResults', { entries: results.length })
const pendingEntries = all.filter((e) => !(wGallerySync && wGallerySync.wasArchived(e)))
for (const hook of wPluginGenHooks) {
if (typeof hook.afterResult !== 'function') continue
try { hook.afterResult(results) } catch (e) { /* 插件钩子异常不得影响结果归档 */ }
@@ -3752,8 +3770,10 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
// 只有「自动下载」开启时才等归档完成:它要从本地原图复制,必须等 out_orig_ 落盘;
// 没开就保持后台异步归档,避免出图到图库可点开的时间被拖长。
const needArchiveWait = !!(wAutoSaver && typeof wAutoSaver.enabled === 'function' && wAutoSaver.enabled())
try { await wAddOutputs(results, { awaitArchive: needArchiveWait }) } catch (e) { /* 图库缓存失败不影响画布结果 */ }
const rest = flattenGenerationEntries(pendingEntries)
if (rest.length) { try { await wAddOutputs(rest, { awaitArchive: needArchiveWait }) } catch (e) { /* 图库缓存失败不影响画布结果 */ } }
try { if (typeof refresh === 'function') await refresh() } catch (e) { /* ignore */ }
try { wGalleryChanged('output') } catch (e) { /* ignore */ }
try { if (wAutoSaver) await wAutoSaver.saveResults(results) } catch (e) { /* 自动下载失败不影响生图 */ }
})
return Promise.resolve(results)
@@ -5491,9 +5511,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) {
@@ -5756,17 +5777,11 @@ const tbCenterSeed = (type, refs) => {
const n = id ? refs.nodes.find((x) => x.id === id) : null
return n ? { id: n.id, type: n.type, name: String((n.data && (n.data.name || n.data.title)) || '') } : null
},
// v3.26.61:逻辑在 src/gallery-sync.js 的 nodeImageOf(补 localRef 候选 + 远程按需落地)
getNodeImage: async (id) => {
const n = refs.nodes.find((x) => x.id === id)
if (!n || !n.data) return null
const firstResult = Array.isArray(n.data.result) ? (n.data.result[0] || {}) : n.data.result
const candidates = [n.data.data, n.data.url, firstResult && (firstResult.url || firstResult.data)]
for (const v of candidates) {
if (!v) continue
if (typeof v === 'string') return /^data:/i.test(v) ? { dataUrl: v } : { url: v }
if (typeof v === 'object') { const dataUrl = await wImgRefDataUrl(v); if (dataUrl) return { dataUrl } }
}
return null
if (!n || !wGallerySync) return null
return wGallerySync.nodeImageOf(n, { writeRef: (src) => wImgRefWrite(src), onLocalRef: (ref) => updateNode(n.id, { localRef: ref }) })
},
createNode: (type, x, y, data) => {
// 插件节点传的是变体 id(web/style…):不在 NODE_TYPES 里,交给 addPluginNode 拼出 plugin:<插件>:<变体>
@@ -5817,7 +5832,9 @@ const tbCenterSeed = (type, refs) => {
const INSERT_K = { orig: 0, '2k': 2048, '1k': 1024, '0.5k': 512 }
const [insertK, setInsertK] = useState(() => { try { const v = lsGet('iwb.insertSizeK', '1k'); return INSERT_K[v] === undefined ? '1k' : v } catch (e) { return '1k' } })
const setInsertKPersist = (v) => { setInsertK(v); try { lsSet('iwb.insertSizeK', v) } catch (e) { /* ignore */ } }
// 按选中档位压缩插入图(算法在 src/image-compress.js 的 toMaxEdge)
// 按选中档位缩尺寸(src/image-compress.js 的 toMaxEdge)。事实口径:它只把 JPEG/WebP 源编码成
// JPEG,PNG 源仍无损 ⇒ 降的是**长边像素**不是体积(1024 复杂图 ~500KB~1MB)。用户 2026-11-24
// 裁定:插入一律留本地副本、可多占空间,所以不把 PNG 转 JPEG(转了就丢透明,标注图外框变黑底)。
const shrinkForInsert = (dataUrl, k) => {
const kk = (k && INSERT_K[k] !== undefined) ? k : insertK
if (kk === 'orig') return Promise.resolve(dataUrl)
@@ -6386,19 +6403,19 @@ const tbCenterSeed = (type, refs) => {
const addRefFromUrl = (...a) => wbCmd().addRefFromUrl(...a)
const refreshOutputs = (...a) => wbCmd().refreshOutputs(...a); IWWorkbenchHooks.useOutputsSync(OUT_KEY, 'iwb_outputs_sync', () => refreshOutputs(100))
const deleteOutputs = (...a) => wbCmd().deleteOutputs(...a)
// 批量插入:把图库里选中的图片按「插入尺寸」档压缩后,作为参考图节点加到画布(与单图插入同一入口)
// 批量插入:图库选中的图片 → 参考图节点。取源与栅格在 src/gallery-sync.js —— 旧实现在循环里
// 每张各自 findSpot(只看已提交节点)⇒ 同批全叠一处;且 http 链接会直接进 data.url 导致无法标注。
const insertOutputsToCanvas = async (list, k) => {
const added = []
for (const f of list) {
let src0 = await wbCmd().refSrcOf(await wResolveOutputSrc(f), (msg) => showToast(msg, 'err'))
if (typeof src0 === 'string' && src0.indexOf('data:') === 0) src0 = await shrinkForInsert(src0, k)
const ref0 = (typeof src0 === 'string' && src0.indexOf('data:') === 0) ? await wImgRefWrite(src0) : null
const spot = findSpot('ref')
added.push({ id: uid('n'), type: 'ref', x: spot.x, y: spot.y, data: { url: ref0 || src0 || '', data: null, name: f.name, localName: null } })
}
const prep = wGallerySync
? await wGallerySync.prepareInsert(list, k, { refSrcOf: (s, n) => wbCmd().refSrcOf(s, n), shrink: shrinkForInsert, writeRef: wImgRefWrite })
: { items: [], remoteOnly: 0 }
if (!prep.items.length) return 0
const spots = wGallerySync.gridSpots(findSpot('ref'), prep.items.length, { stepX: NODE_W + 24, stepY: NODE_H.ref + 24 })
const added = prep.items.map((p, i) => ({ id: uid('n'), type: 'ref', x: spots[i].x, y: spots[i].y, data: { url: p.src, data: null, name: p.name, localName: null, srcUrl: p.srcUrl || '' } }))
commitCanvas(refs.nodes.concat(added), undefined, undefined)
setSel(added.map((n) => n.id))
showToast('已插入 ' + added.length + ' 张到画布')
if (prep.remoteOnly) showToast('已插入 ' + added.length + ' 张(其中 ' + prep.remoteOnly + ' 张取不到本地字节,按原链接插入,可能无法标注)', 'err')
else showToast('已插入 ' + added.length + ' 张到画布')
return added.length
}
const loadDemo = (...a) => wbCmd().loadDemo(...a)
@@ -7489,7 +7506,7 @@ const tbCenterSeed = (type, refs) => {
useEffect(() => IWWorkbenchLogic.startWsMoreOutside({ wsMoreOpen, setWsMoreOpen }), [wsMoreOpen])
// drag & drop import(逻辑已外移到 src/runtime-workbench-logic.js.startCanvasDrop,2026-11-06)
useEffect(() => IWWorkbenchLogic.startCanvasDrop({ canvasEl, refs, uiZoom, importCanvasFile, instantiateGroup, wResolveOutputSrc, wImgRefWrite, wImportImage, uid, pushHistory, commitCanvas, setSel, setNotice, outputs }), [])
useEffect(() => IWWorkbenchLogic.startCanvasDrop({ canvasEl, refs, uiZoom, importCanvasFile, instantiateGroup, localSrcOfOutput: (item) => (wGallerySync ? wGallerySync.localCopySrcOf(item) : wResolveOutputSrc(item)), wResolveOutputSrc, wImgRefWrite, wImportImage, uid, pushHistory, commitCanvas, setSel, setNotice, outputs }), [])
// 节点组数据变化(收藏/删除/其它标签页同步)→ 通知 grouplib 插件重拉,避免插件显示旧列表
useEffect(() => { if (window.IWBPluginGroupLib) window.IWBPluginGroupLib.emit('host') }, [savedGroups, nodeGroupGroups])
useEffect(() => { if (window.IWBPluginPromptLib) window.IWBPluginPromptLib.emit('host') }, [prompts, promptGroups])
@@ -7522,7 +7539,8 @@ const tbCenterSeed = (type, refs) => {
}
// runNode 已搬到 src/workbench-logic.js(2026-10-29):每次调用现取闭包值,不会有陈旧闭包。
const runNode = async (nodeId, taskPromptId, onDone, opts) => IWWorkbenchLogic.runNode({ acquireGenSlot, activeWsId, activeWsIdRef, commitRunNodes, ensurePolished, finishGenerationRun, persistRuns, pushHistory, refreshOutputs, refs, runLockConflicts, runWorkspaceNodes, setBusy, setNotice, setProgress, updateNode }, nodeId, taskPromptId, onDone, opts)
// archiveOne:单张结果完成即入图库(图库面板要「出图即见」,不能等整轮);见 wArchiveEntryNow
const runNode = async (nodeId, taskPromptId, onDone, opts) => IWWorkbenchLogic.runNode({ acquireGenSlot, activeWsId, activeWsIdRef, archiveOne: (entry) => wArchiveEntryNow(entry, () => refreshOutputs(100)), commitRunNodes, ensurePolished, finishGenerationRun, persistRuns, pushHistory, refreshOutputs, refs, runLockConflicts, runWorkspaceNodes, setBusy, setNotice, setProgress, updateNode }, nodeId, taskPromptId, onDone, opts)
// 生图节点全部任务的总张数(逻辑在 src/runtime-workbench-logic.js.taskCountOf)
const taskCountOf = (g) => IWWorkbenchLogic.taskCountOf({ refs, buildGenerationTasks }, g)
@@ -8252,7 +8270,9 @@ const tbCenterSeed = (type, refs) => {
}
if (window.IWBPluginGallery) window.IWBPluginGallery.setImpl({
list: (o) => window.IWBPluginGallery.query(outputs, o),
thumb: (name) => { const f = (outputs || []).find((x) => x.name === name); return f ? wDisplayThumbOf((f.data || f.url) || '') : '' },
// v3.26.61:缩略图取源顺序(清单 data → images/thumbs → 本地原图 → 远程)在 gallery-sync 里,
// 原因是「生图后图库不显示」有一半出在这里 —— 新图 data 还没 hydrate 就只剩远程 url 可退。
thumb: (name) => (wGallerySync ? wGallerySync.thumbFor(name, { outputs, displayThumbOf: wDisplayThumbOf, galleryThumb: (h) => { const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null; return (F && typeof F.galleryThumb === 'function') ? F.galleryThumb(h) : Promise.resolve('') } }) : ''),
preview: (name) => setPreview({ list: outputs.map((x) => ({ __gallery: true, name: x.name, origIdb: x.origIdb, idb: x.idb, url: x.url, thumb: x.data || null })), idx: Math.max(0, outputs.findIndex((x) => x.name === name)) }),
download: async (names) => {
const failed = []
+6
View File
@@ -4,6 +4,12 @@
> 触发:用户反馈 —— 「图库的图片插入到画布后,刷新画布,图片状态会改变,双击就不能打开了;
> 刷新后图片有数倍内存占用,过一会儿内存会回落」
> 用户目标:**不要建立画布的性能**(可以牺牲这个功能)
>
> ⚠️ 2026-11-24 注记(读本篇前必看):本文是**网页版时期**的链路口径 —— 文中的
> `localStorage['iwb_web_outputs']` + 「IndexedDB 缩略图字节」只对当时的网页版成立。
> 现在桌面端(Tauri)的字节落在 `images/thumbs`、`images/gallery` 文件里,索引在
> `library/gallery/index.json`;实际映射见 `docs/standards/image-storage-map.md`。
> 本文的**结论**(插入只记引用、别把整图塞进画布数据)仍然有效,**存储位置描述已过时**。
---
+5 -5
View File
@@ -1,7 +1,7 @@
# 现状架构与性能事实基线(桌面版)
> **本文档是什么**:现状**事实快照**,不是规范。用途:任何性能 / 内存 / 存储相关改动,先对齐这里的现实,避免把已经调好的东西改坏。
> 日期 **2026-10-20**(**2026-11-16 复算 · v3.24.85**)| 基线(**最近一次 bump 版本的提交**,不是主干 HEAD)`main = 93871f7`(线上 `v3.26.57+93871f7` —— 2026-11-23 **节点正文文本区修复**:提示词/文本节点正文透明继承卡片底色(白卡片消失)、编辑态三层框(控件 border / 聚焦光晕 / D8 焦点环)全去掉,规范补表面角色三分法与 `node-scope-test` 第 5 条守卫,8 张基线重录;上一条 `v3.26.51+21554b0` —— **M6 延展验证**:插件面板两段六次叠加样式合并重写、133 行新增零裸值;补 `--iwb-font-base`(14px) 第 8 档与亮色状态色调深(对浅页面 2.13 → ≥4.6),对比度守卫 114→138 对;新增 ⑦⑧ 组件夹具基线共 16 张;`batch-export` 1.2.2 状态色走宿主 token、去掉纯蓝主按钮;棘轮基线首次下调。M1–M6 全部完成;上一条 `v3.26.50+cab473c` —— **M5 闸门**:新增 `scripts/token-lint.js`(只查 diff 新增行,CSS 与 JS 内联样式两套判据、四类白名单)+ `tests/design-token-ratchet-test.js`(13 项计数只降不升)+ `tests/theme-contrast-test.js`(亮/暗 × 文字 × 表面 114 对),三条各做一次打红验证后接进 `verify:ci`;顺手把首启动「选择资料目录」弹窗 token 化(全仓最后一个完全未 token 化的界面);上一条 `v3.26.49+1743453` —— **M4-B6 收尾**:`style.css` 剩余 16 处半像素字号全清零(守卫收紧为全文件断言)、`--iwb-control-h` 裁定不扩到全局控件(并排表单 vs 成组紧凑控件);插件主题契约重写,`ALLOW_FILES` 文件级豁免 **6 → 0** —— 改为「私有皮肤 manifest 自声明 `skin` + chroma 强调色判据 + 内容色行内标记」,声明私有皮肤的插件不得引用宿主颜色 token;同步 4 个插件版本,插件侧中性色写死归零;视觉基线 8 张因字号栅格化变化更新,A/B 回退确认非环境噪声;上一条 `v3.26.48+cb9cb9c` —— **M4-B5 节点**:节点卡内部表面统一 `--iwb-field` —— 端口底色从 `#161616`(暗色对卡片差 39 级,一颗黑洞)改 `#494949`(差 12 级),同病灶另 6 处(ref-img/ref-single/upload-link/refmini-empty/task-result-img/node-head:hover)一并改;浮条与任务卡 hover 改 `color-mix(text 10%)`(原来 panel 与 layer2 深色同色,hover 无反馈);字号 12/15/11/13 全归档位、圆角 8/6/5/14 归并、间距 52 处等值 + 13 处 1px 级微调;删 6 个死类名;新增 `tests/node-scope-test.js` 钉「节点内禁用面板表面色」;上一条 `v3.26.47+f5c8174` —— **M4-B4 设置/外观**:新增 `--iwb-control-h`(30px) 修「同行输入框 33px / 按钮 24px」的 9px 落差;设置页正文 14→13、标题 16→15,范围内半像素字号清零;删 21 条死规则(setcell/setgrid/set-row/appear-val 等);新增 `tests/settings-scope-test.js` 钉「控件等高 / 死类名不复现 / 引用的 token 必须存在」;上一条 `v3.26.46+9f29996` —— 2026-11-23 **M4-B3 首页/库**:删 30 条零生产者规则(25 个类名在产物里 0 次)+ 4 条被 specificity 覆盖的死声明,`style.css` 2391→2339 行;首页/库 106 条规则换 token,间距写死 91→5(只剩版心与导航让位的布局值)、字号写死清零,新增 `--iwb-font-display:24px` 第 7 档;验收改为「计算样式逐元素 diff + 12 张基线只首页 2 张变化」;上一条 `v3.26.45+968ff46` —— **M4-B2 浮层层级表 + 阴影四档**:14 档 `--iwb-z-*`(裸 z-index 取值种类 42→31)、`--iwb-elevation-1..4`(浮层 8 种阴影写法→4 档)、`.iwb-pop` 圆角 18→`radius-popover(14)`;修「弹窗里点保存看不到提示」—— 根因不是层级数字而是 `.iwb-overlay` 本身就是堆叠上下文,toast 改为 portal 到 `body`;新增 `tests/overlay-layer-test.js` 钉 9 条顺序约束;上一条 `v3.26.44+846a59b` —— **设计 token 体系重建**:D1–D9 色彩模型改为真正的深色(#121212 底 / 正文 #e3e3e3、13 个表面逐层相对派生 + 对比度生成期夹紧)、D10 新增 `--iwb-field` 卡片内控件面(暗色不再在灰卡上挖黑洞)、M3 单一源(`derive()` → `design-tokens.css` + `tokens.json`,`tokens:check` 进 CI);**安装包已本地构建,NAS 尚未上传**);上一条 `v3.26.41+2b8e337`:继承态提示词把上游文案与参考图交给组合/连接节点(来源判定加 `(edges, nodes)`,组合拼接逻辑零改动);再上一条 `v3.26.40+d9e3d84`:左右停靠栏配色对齐主色调(新增 `--iwb-dock-bg` 进灰阶 ramp + 头部深一档 + `.iwb-pcard` 补白底)+ 修 `Cargo.toml`/`Cargo.lock` 版本漂移,四处统一到 3.25.58)。上一条 3.25.30:线上实际运行提交是 docs 提交 `7df9dc4`,bump 提交为 `4be78c0`;2026-11-16 已发**测试站 + 正式站**,三地址一致 + `IWB_VERIFY_STRICT=1` 通过Line truncated
> 日期 **2026-10-20**(**2026-11-16 复算 · v3.24.85**)| 基线(**最近一次 bump 版本的提交**,不是主干 HEAD)`main = 9b78535`(线上 `v3.26.61+9b78535` —— 2026-11-24 **图库:出图即入图库 + 插入落本地副本(能标注)**:每张生成完成即归档并通知插件(此前只在整轮结束写一次 ⇒ 生成中图库一直空)、插入取源改本地字节优先并引用化(抓不到才留原链接 + 提示)、`getNodeImage` 补 `data.localRef` 候选(远程缓存命中却仍判「不支持标注」的直接成因)、批量插入改 4 列栅格(旧实现同批全叠一处),逻辑落 `src/gallery-sync.js`,app.js 只装配;上一条 `v3.26.60+cf0e9a0` —— **浮层字号上调一档**:「模型设置」「图像设置」选择项 11→13px、高 22→28、左右内距 6→10、间距 4→6、标题 12→14、面板 328→360,改动全落在 `.iwb-pop` 的 6 个 token(两面板共用一套);上一条 `v3.26.59+e966b34` —— 备份新增 `plugin-files/` 通道,提示词封面换机不再丢;再上一条 2026-11-23 **节点正文文本区修复**:提示词/文本节点正文透明继承卡片底色(白卡片消失)、编辑态三层框(控件 border / 聚焦光晕 / D8 焦点环)全去掉,规范补表面角色三分法与 `node-scope-test` 第 5 条守卫,8 张基线重录;上一条 `v3.26.51+21554b0` —— **M6 延展验证**:插件面板两段六次叠加样式合并重写、133 行新增零裸值;补 `--iwb-font-base`(14px) 第 8 档与亮色状态色调深(对浅页面 2.13 → ≥4.6),对比度守卫 114→138 对;新增 ⑦⑧ 组件夹具基线共 16 张;`batch-export` 1.2.2 状态色走宿主 token、去掉纯蓝主按钮;棘轮基线首次下调。M1–M6 全部完成;上一条 `v3.26.50+cab473c` —— **M5 闸门**:新增 `scripts/token-lint.js`(只查 diff 新增行,CSS 与 JS 内联样式两套判据、四类白名单)+ `tests/design-token-ratchet-test.js`(13 项计数只降不升)+ `tests/theme-contrast-test.js`(亮/暗 × 文字 × 表面 114 对),三条各做一次打红验证后接进 `verify:ci`;顺手把首启动「选择资料目录」弹窗 token 化(全仓最后一个完全未 token 化的界面);上一条 `v3.26.49+1743453` —— **M4-B6 收尾**:`style.css` 剩余 16 处半像素字号全清零(守卫收紧为全文件断言)、`--iwb-control-h` 裁定不扩到全局控件(并排表单 vs 成组紧凑控件);插件主题契约重写,`ALLOW_FILES` 文件级豁免 **6 → 0** —— 改为「私有皮肤 manifest 自声明 `skin` + chroma 强调色判据 + 内容色行内标记」,声明私有皮肤的插件不得引用宿主颜色 token;同步 4 个插件版本,插件侧中性色写死归零;视觉基线 8 张因字号栅格化变化更新,A/B 回退确认非环境噪声;上一条 `v3.26.48+cb9cb9c` —— **M4-B5 节点**:节点卡内部表面统一 `--iwb-field` —— 端口底色从 `#161616`(暗色对卡片差 39 级,一颗黑洞)改 `#494949`(差 12 级),同病灶另 6 处(ref-img/ref-single/upload-link/refmini-empty/task-result-img/node-head:hover)一并改;浮条与任务卡 hover 改 `color-mix(text 10%)`(原来 panel 与 layer2 深色同色,hover 无反馈);字号 12/15/11/13 全归档位、圆角 8/6/5/14 归并、间距 52 处等值 + 13 处 1px 级微调;删 6 个死类名;新增 `tests/node-scope-test.js` 钉「节点内禁用面板表面色」;上一条 `v3.26.47+f5c8174` —— **M4-B4 设置/外观**:新增 `--iwb-control-h`(30px) 修「同行输入框 33px / 按钮 24px」的 9px 落差;设置页正文 14→13、标题 16→15,范围内半像素字号清零;删 21 条死规则(setcell/setgrid/set-row/appear-val 等);新增 `tests/settings-scope-test.js` 钉「控件等高 / 死类名不复现 / 引用的 token 必须存在」;上一条 `v3.26.46+9f29996` —— 2026-11-23 **M4-B3 首页/库**:删 30 条零生产者规则(25 个类名在产物里 0 次)+ 4 条被 specificity 覆盖的死声明,`style.css` 2391→2339 行;首页/库 106 条规则换 token,间距写死 91→5(只剩版心与导航让位的布局值)、字号写死清零,新增 `--iwb-font-display:24px` 第 7 档;验收改为「计算样式逐元素 diff + 12 张基线只首页 2 张变化」;上一条 `v3.26.45+968ff46` —— **M4-B2 浮层层级表 + 阴影四档**:14 档 `--iwb-z-*`(裸 z-index 取值种类 42→31)、`--iwb-elevation-1..4`(浮层 8 种阴影写法→4 档)、`.iwb-pop` 圆角 18→`radius-popover(14)`;修「弹窗里点保存看不到提示」—— 根因不是层级数字而是 `.iwb-overlay` 本身就是堆叠上下文,toast 改为 portal 到 `body`;新增 `tests/overlay-layer-test.js` 钉 9 条顺序约束;上一条 `v3.26.44+846a59b` —— **设计 token 体系重建**:D1–D9 色彩模型改为真正的深色(#121Line truncated
<!-- 2026-10-28 P1 拆分批 1:新增 src/generation-task-graph.js(5 个任务图纯函数自 app.js 迁出)
⇒ 模块数 60→61、耦合面 51→52、sourceModules 60→61。耦合面只**新增** IWBWTaskGraph,无删除。
2026-10-28 P1 拆分批 2:新增 src/storage-config-shape.js(9 个配置形状纯函数自 app.js 迁出)
@@ -22,7 +22,7 @@
- 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob_<hash>_<len>`** (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 **8,508 行**(**双层预算**:绝对上限 8,700 / 占总源码 ≤ 40%,现 **36.8%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,998 行**(上限 **3,030**,余量 32;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **108** 个模块 / 14,607 行,`sourceModules` 108 项;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 **8,508 行**(**双层预算**:绝对上限 8,700 / 占总源码 ≤ 40%,现 **36.8%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,998 行**(上限 **3,030**,余量 32;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **109** 个模块 / 14,607 行,`sourceModules` 109 项;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`。
## 2. 门禁与环境现状
@@ -167,7 +167,7 @@
- 同一张图被 3 个节点引用、hydrate 成 3 个不同 objectURL 时,preview/display 缓存各自 miss → 重复解码(与 F2 相邻)。
- **F10|`refs.genScheduler` 是桩** (A) → 未接线,暂无运行时影响(P3)。
- **F11|已建但未接线的模块层(2026-10-17 接线审计;2026-10-18 复核更正)** (A)
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**108 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**109 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
- **仅被测试引用(9 模块 + 2 导出)**:`canvas-domain`、`generation-retry`、`generation-service`、`runtime-recovery-runner`、`runtime-state-bridge`、`runtime-store`、`storage-reconcile`、`storage-result`、`workspace-service`;导出 `IWBStorageHealthFactory`、`IWBPluginHostFactory`。(`storage-result` 是**存储层共享结果类型**,被 6 个存储模块读取,**非死代码**;`runtime-store` 为状态模型 epic 地基。)
- **app.js 零引用(1 模块 + 3 导出)**:模块 `generation-controller`;导出 `IWBRuntimeMetricsFactory`、`IWBStorageRuntimeFactory`、`IWBUIComponents`。`canvas-relations` 已随 `06cf211` 删除(本文档早前把它列为"唯一可删者",实际已删)。零引用证据 = `grep -rn "<名字>" .`(排除 `node_modules|dist|vendor|test-results`)**只命中其自身赋值行**。
- **半接线 / 未接线**:`IWBRuntimeStateBridge` **无 app.js 引用(仅测试)**;`IWBRuntimeRunContext` **已接线**(`runNode` 读取运行上下文);`IWBGenerationController` 是完整但**从未被调用**的工厂;`ModularWorkspaceStore`(`app.js` 内)是 `storage-workspace` 的**预留接线 seam**(当前无下游使用,保留);`window.IWBImageFolder` 自注册后读回(装载路径)。
@@ -183,7 +183,7 @@
| `storage-reconcile` | 存储对账(`createReconciler`/`check`) | 内联对账 | 存储层收口 |
| `runtime-recovery-runner` | 执行恢复候选(`candidate`/`valid`/`run`) | 内联恢复 | 断点恢复 |
| `canvas-domain` | 画布域模型(`commit`/`updateNode`/`deleteNodes`…) | `CanvasStore` 那一套 | Workbench 解耦(P2-9) |
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**87** 项)与 `sourceModules` 顺序(**108** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**88** 项)与 `sourceModules` 顺序(**109** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
## 12. 易踩的坑
@@ -254,7 +254,7 @@
**信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**87** 项)与 `sourceModules` 顺序(**108** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**88** 项)与 `sourceModules` 顺序(**109** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。
**关键陷阱**:`normalizeNodes`(现位于 `src/canvas-normalize.js`)会**静默丢弃**不在 `NODE_H` 里的节点类型 ⇒ 新增节点类型必须先登记 `NODE_H`,否则节点一刷新就消失(§13.27 规则三的同一失败模式)。
+20 -12
View File
@@ -791,28 +791,36 @@ L3 Contract ── 组件整体换肤时才加,能不建就不建
- 复选框统一 `input[type=checkbox]` 尺寸与 `accent-color: var(--iwb-brand)`,不再各页写 15px/18px
- 按钮高度统一 `--iwb-control-h`、圆角 `--iwb-radius-control`;操作组间距用 `--iwb-set-btn-gap`
- 备份/外观等页的操作按钮不再单独写高度或间距
### 3.13 浮层弹窗(popover,L3,v3.26.57)
### 3.13 浮层弹窗(popover,L3,v3.26.58)
画布节点上的「模型设置」「图像设置」等贴节点浮层,统一用 `.iwb-pop` 这一套 shell;
画布节点上的「模型设置」「图像设置」等贴节点浮层,统一用 `.iwb-pop` 这套 shell;
token 定义在 `.iwb-pop` 作用域内,**同类浮层只允许引用它们 + L2 尺度 token**。
字号档(v3.26.60 上调):选择项 13px / 高 28px / 左右内距 10px / 间距 6px、标题 14px、分组标签 12px。
上一版是 11px / 22px / 6px / 4px / 12px / 11px,用户反馈「文字有些小」,整体放大一档;
面板宽度同时 328 → 360px,抵消放大带来的额外换行。
| token | 值 | 用途 |
|---|---|---|
| `--iwb-pop-w` | `380px` | 面板宽度(窄屏由 `max-width: calc(100vw - 16px)` 兜底) |
| `--iwb-pop-pad-y` | `var(--iwb-space-16)` | 面板上下内边距 |
| `--iwb-pop-pad-x` | `var(--iwb-space-20)` | 面板左右内边距 |
| `--iwb-pop-gap` | `var(--iwb-space-12)` | 面板内分组之间 |
| `--iwb-pop-w` | `360px` | 面板宽度(窄屏由 `max-width: calc(100vw - 16px)` 兜底) |
| `--iwb-pop-pad-y` | `var(--iwb-space-10)` | 面板上下内边距 |
| `--iwb-pop-pad-x` | `var(--iwb-space-12)` | 面板左右内边距 |
| `--iwb-pop-gap` | `var(--iwb-space-8)` | 面板内分组之间 |
| `--iwb-pop-radius` | `var(--iwb-radius-popover)` | 面板圆角(阴影用 `--iwb-elevation-3`) |
| `--iwb-pop-title-size` | `var(--iwb-font-base)` | 面板标题字号 |
| `--iwb-pop-chip-h` | `32px` | 选择项/下拉框统一高度 |
| `--iwb-pop-chip-pad-x` | `var(--iwb-space-12)` | 选择项左右内边距 |
| `--iwb-pop-chip-radius` | `var(--iwb-radius-control)` | 选择项圆角(矩形,非胶囊) |
| `--iwb-pop-chip-gap` | `var(--iwb-space-8)` | 选择项之间 / 换行后的行距 |
| `--iwb-pop-chip-size` | `var(--iwb-font-md)` | 选择项与下拉框字号 |
| `--iwb-pop-title-size` | `var(--iwb-font-base)` | 面板标题字号(14px) |
| `--iwb-pop-chip-h` | `28px` | 选择项/下拉框/数字框统一高度 |
| `--iwb-pop-chip-pad-x` | `var(--iwb-space-10)` | 选择项左右内边距 |
| `--iwb-pop-chip-radius` | `6px` | 选择项圆角(矩形,非胶囊) |
| `--iwb-pop-chip-gap` | `var(--iwb-space-6)` | 选择项之间 / 换行后的行距 |
| `--iwb-pop-chip-size` | `var(--iwb-font-md)` | 选择项字号(13px) |
分组标签 `.iwb-setlabel` 用 `--iwb-font-sm` + 600 字重,分组内间距 `space-4`;浮层内说明文字 `.iwb-pop .iwb-hint` 用 `--iwb-font-sm`。
规则:
- 同一浮层里**所有选择项高度、圆角、字号必须一致**(`.iwb-chip-line` 与 `.iwb-gc-item` 都吃这套 token)
- 面板宽度只能由 `--iwb-pop-w` 决定;禁止再写 `width: 380px` 之类硬编码(曾因此让 token 失效;
`.iwb-gen-config` 原来写死 `min(92vw, 320px)` 就是这么失效的,v3.26.60 已改成引用 token)
- 触发浮层时必须在**绘制前**完成定位:定位用 `useLayoutEffect`,未定位前 `visibility: hidden`;
禁止先用 `{x:40,y:40}` 之类默认坐标渲染(用户会看到左上角闪一下再跳到锚点)
- 浮层必须 portal 到 `body`(节点在画布 `transform` 里,否则 fixed 会被变成相对定位)
+101
View File
@@ -0,0 +1,101 @@
# 图片存哪:运行时 × 键前缀 × 落点
> 用途:回答「这张图存在哪 / 为什么节点里是链接 / 删了会不会留垃圾」这类问题前,先按本文判读。
> 本文是**判读口径**,不是功能说明;与代码冲突时以代码 + `scripts/audit-image-storage.js` 的输出为准。
## 1. 第一件事:确认运行时
同一个 `IWBImageBlobStore`,在两种运行时落到完全不同的地方。判断入口只有一个:
```js
window.IWBStorageFile && window.IWBStorageFile.enabled() // 桌面端 true
```
`app.js` 的 `storageRuntime()` 据此返回 `fileStore.runtime` 或 `window.IWBStorageRuntime`;
`wImageBlobStore()` 把 `storageRuntime().indexedDb` 注入给 blob 仓库。
| 运行时 | 注入的 idb 是什么 | Blob 最终落在 |
|---|---|---|
| 桌面端(Tauri,资料目录就绪) | `storage-file.js` 的文件 KV(`kv`) | `~/Documents/ImageWorkbench/images/canvas/<sha16>.<ext>` + `data.json` 的 `assets` 登记 |
| 浏览器(网页版) | 真正的 IndexedDB | 页面 IndexedDB(受浏览器配额限制) |
**「字节在 IndexedDB」只对网页版成立。** 桌面端 `image-blob-store.js` 只是"调用 put/get/del",
它不知道背后是文件;把该文件头部的 "IndexedDB" 当桌面端事实,是 2026-11-24 一次误判的起点。
## 2. 键前缀 → 目录(`storage-file.js:catOfKey`)
| key 前缀 | 桌面端目录 | 写入方 |
|---|---|---|
| `out_orig_` | `images/gallery/` | 图库原图(生成归档时下载) |
| `out_` | `images/thumbs/` | 图库缩略图 / `_768` 显示版 |
| `imgblob_` | `images/canvas/` | 画布图:插入副本、粘贴、本地导入 |
| `http…` | `images/legacy/` | 旧版 `__cache__` 绝对 URL 键 |
| 其它 | `images/canvas/` | 兜底 |
`data.json` 的 `assets` 是**唯一登记表**:`{ "<key>": { f: "images/canvas/xxx.png", k: "blob"|"dataurl", m } }`。
文件在目录里但 `assets` 没登记 = 孤儿(`_768` 显示版属于已知例外)。
## 3. 节点的四种引用形态
| 形态 | 字节位置 | 解析函数 | 能否标注/喂上游 |
|---|---|---|---|
| `{ __blob: 'imgblob_…' }` | 见上表(桌面 `images/canvas/`) | `wImgRefDataUrl` / `ImageBlobStore.getBlob` | 能 |
| `{ __idb: 'out_orig_…' }` | `assets[key].f` | `IDB.get` | 能 |
| `{ __cache: '/__iwb_cache__/…' }` | Cache Storage(web)/ `images/legacy` | `caches.match` | 能(桌面端重启后不可靠,已不新增) |
| `"https://…"` | 远程图床 | 只能 `fetch` / `wTauri.http.fetch` | **不能**,除非先"素材化"落本地 |
`addRefFromUrl`(生成结果→参考图 / 链接拖入)对非 SVG **仍原样写 url**(2026-11-11 用户裁定:
节点 `data.url` 保持原链接,提交生成时仍用链接),所以这类节点靠 `data.localRef` 旁路缓存 +
`getNodeImage` 的按需落地来获得可标注能力。**图库插入不走这条路**(见第 7 节)。
## 7. 2026-11-24 收口:插入一律落本地副本,取图认 localRef
用户裁定(本次):**B6 = 复制** —— 图库插入多占一份空间可以接受,条件是「不能丢数据、
不能插进去是个链接导致不能标注」。据此定了三条口径:
| 入口 | 现在的行为 | 落在哪 |
|---|---|---|
| 图库「插入」(右键 / 格子 / 顶部 / 批量拖入) | 取本地字节(原图→清单 data→缩略图→按需抓远程)→ 按档缩尺寸 → 引用化 | `{__blob}` → `images/canvas/` |
| 图库拖入画布(带 `x-iwb-gallery-orig`) | 同上(与按钮同一条链) | 同上 |
| 生成结果→参考图 / 链接拖入 | 保持原链接(旧裁定不变) | `data.url` + `localRef` 缓存 |
| 插件取图(`canvasBridge.getNodeImage`) | 候选含 `data.localRef`;只有远程时抓一次并写回 `localRef` | — |
抓不到本地字节(离线 / 图床拦跨域)时的行为:**保留原链接插入**,节点 `data.srcUrl` 留痕,
toast 明确提示「可能无法标注」。宁可有链接,也不静默丢图。
代码位置:判定与取源都在 `src/gallery-sync.js`(`localCopySrcOf` / `prepareInsert` /
`nodeImageOf` / `thumbFor` / `archiveEntryNow`),`app.js` 只 `attach(...)` 装配。
顺带的第二个成因(「生图后图库不显示」):归档原本只在整轮结束写一次。现在 `handleCompletedJob`
每张完成即 `archiveEntryNow`(串行队列 + 等缩略图 + 刷新 React outputs + `IWBPluginGallery.emit`),
图库插件订阅 `ctx.gallery.onChanged` 后 260ms 防抖重拉。
## 4. 回答"图存哪"的三步实证法
```bash
node scripts/audit-image-storage.js # ① 目录/登记/孤儿/节点形态一次看全
node -e "…library/gallery/index.json 的 origIdb 覆盖率…" # ② 图库条目是否真有本地原图
```
③ 只在必要时做:真机点一次目标入口,看新节点 `data.url` / `data.data` 落到哪种形态。
**禁止**只读代码注释、默认值或变量名就下结论。`canvas.backupOriginals` 默认 false ≠ 用户库里没有原图;
实测这批数据 6/6 条目都有 `origIdb`,原图就在 `images/gallery/`。
## 5. 反例(2026-11-24):三处误判与各自成因
| 错误结论 | 当时的"依据" | 真正的成因 |
|---|---|---|
| 副本写进 IndexedDB | `image-blob-store.js` 头部注释与实现都写 IDB | 只读了仓库层,没跟到 `wImageBlobStore()` 注入的是文件 KV;注释本身还是网页版口径 |
| 图库条目通常没有 `origIdb`,所以插入得到 url | `backupOriginals` 默认 false 的代码路径 | 用"默认值"代替"实际数据",没打开 `library/gallery/index.json` |
| 图库插入会留 http 链接 | `insertOutputsToCanvas` 里 `url: ref0 \|\| src0` | 静态推断了分支,却把 `addRefFromUrl` 的产物(生成结果→参考图)算到了图库插入头上;没统计节点形态 |
共同点:**先用注释/默认值形成假设,再用同一假设去"验证"代码,从未读真实数据。**
数据一统计就翻案:`data.url` 里 0 个 `__blob`,`data.data` 里 66 个 `__blob`。
## 6. 硬规则
1. 存储路径类结论必须有 `audit-image-storage.js` 输出或 `assets` 记录支撑,不得由注释推断。
2. 判断"用户数据长什么样"就读用户数据,"默认值/典型情况"只能用来解释代码分支。
3. 同一函数在两种运行时语义可能不同:先确认 `enabled()`,再谈落点。
4. 改插件/宿主里任何"存图"逻辑后,重跑一次 audit,确认目录与登记仍然成对。
+2 -1
View File
@@ -26,7 +26,8 @@ git checkout 178b36c -- promptlib/styles.css promptlib/src/index.js
- 记录选区只在 `keyup / mouseup / input / select`,**绝对不要在 `blur` 记录**(WebKit 失焦会重置选区 → 插入到前一个字符)
- 点击时先 `focus()` → 用 `lastSel` 计算插入点,直接 `value.slice` 拼接(确定性 splice)
- 插入后 `setSelectionRange` 选中变量名,并同步 `lastSel`
- **不要用「透明 textarea + 高亮层」做编辑区**:两层即使字体相同,变量加粗/换行差异也会让点击位置逐次左移(v1.8.18 实测:第 1 次对、第 2 次偏 1 字、第 3 次偏 2 字)。编辑正文直接由 textarea 渲染(v1.8.20)
- **不要用「透明 textarea + 高亮层画文字」做编辑区**:两层即使字体相同,变量加粗/换行差异也会让点击位置逐次左移(v1.8.18 实测:第 1 次对、第 2 次偏 1 字、第 3 次偏 2 字)。编辑正文直接由 textarea 渲染(v1.8.20)
- **v1.9.3 起的允许例外**:textarea 文字保持可见、变量 span 不加粗,背层只画浅主色背景块(`--iwb-plp-accent` 的 color-mix);两层字体/行高/padding/滚动条占位一致并双向同步滚动。因为文字仍由 textarea 自己绘制,不会复发上面的点击偏移。实现见 `iwb-plugins-desktop/promptlib/styles.css` 的 v1.9.3 注释块。
- **不要用 `document.execCommand("insertText")`**:WKWebView 内部光标与 `selectionStart` 会漂移,第一次正常、第二次起偏移一个字符(v1.8.16 实测)
## 四、发布前检查清单
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "image-workbench-web",
"private": true,
"version": "3.26.57",
"version": "3.26.61",
"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/plugin-archive-test.js && node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-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/storage-config-shape-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/image-blob-store-test.js && node tests/image-preview-derive-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/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/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",
"test:unit": "node tests/plugin-archive-test.js && node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-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/storage-config-shape-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-preview-derive-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/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/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",
"test:diagnostics": "node tests/runtime-diagnostics-hotpath-test.js",
"test:facts": "node tests/architecture-facts-guard-test.js && node tests/release-records-test.js",
"plugins:gc": "node scripts/plugins-publish.mjs --gc",
+40 -5
View File
@@ -1,8 +1,15 @@
// iwb-plugin: 图库 —— 右栏「图库」面板(宿主只提供 ctx.gallery 数据能力,界面全部在插件里)
//
// 依赖客户端能力:gallery(list/thumb/preview/download/insert/remove)+ panels。
// 依赖客户端能力:gallery(list/thumb/preview/download/insert/remove/onChanged)+ panels。
// 数据:插件自己的配置(插入尺寸/图幅/时间筛选)存 ctx.data,不塞 settings。
// 视觉:复用宿主的 .iwb-gal-* / .iwb-history-* 类名(宿主 style.css 保留这些样式)。
//
// v1.7.0(2026-11-24):
// ① 订阅 ctx.gallery.onChanged —— 出图途中宿主每归档一张就通知,面板立刻长出新图;
// 此前只有「面板重新可见且距上次拉取 >5s」一个入口,而生成时面板一直可见 ⇒ 永远不刷。
// ② 格子「插入」补 insertK(与右键/顶部一致,尺寸档不再被忽略)。
// ③ 插入/删除补「插入中…」状态,删除改成等宿主删完再重拉(固定 250ms 会拉到未删完的清单)。
// 注:搜索框在 v1.6.1 已按用户意见移除,不再加回。
;(function (global) {
'use strict'
if (!global.IWBPluginHost) return
@@ -184,6 +191,7 @@
menu.appendChild(b)
}
item('插入画布', function () {
setStatus('插入中…(取本地原图 → 按插入尺寸压缩)')
Promise.resolve(ctx.gallery.insert([it.name], { insertK: cfg.insertK || '1k' }))
.then(function () { setStatus('已插入:' + it.name) })
.catch(function () { setStatus('插入失败') })
@@ -202,11 +210,14 @@
var ask = (C && C.askOrNative) ? C.askOrNative('删除「' + it.name + '」?不可恢复。', { title: '删除图片', okText: '删除' }) : Promise.resolve(global.confirm('删除「' + it.name + '」?'))
ask.then(function (ok) {
if (!ok) return
// 先本地摘掉,避免删除后还渲染一格「图片已丢失」
items = items.filter(function (x) { return x.name !== it.name })
total = Math.max(0, total - 1)
delete picked[it.name]
render()
Promise.resolve(ctx.gallery.remove([it.name])).then(function () { setTimeout(load, 250) }).catch(function () {})
// v1.7.0:等宿主真的删完再重拉(旧写法固定 setTimeout 250ms,磁盘慢/多张时会拉到还没删完的清单,
// 格子里出现「图片已丢失」,用户以为删坏了)
return Promise.resolve(ctx.gallery.remove([it.name])).then(function () { return load() }).catch(function () {})
}).catch(function () {})
})
document.body.appendChild(menu)
@@ -227,6 +238,7 @@
try { names = JSON.parse(raw) } catch (err) { return }
if (!names || names.length < 2) return
e.preventDefault(); e.stopPropagation()
setStatus('插入中…(' + names.length + ' 张)')
Promise.resolve(ctx.gallery.insert(names, { insertK: cfg.insertK || '1k' })).then(function (r) {
if (r && r.ok === false) { setStatus('批量插入失败'); return }
setStatus('已插入 ' + names.length + ' 张')
@@ -264,6 +276,7 @@
actions.appendChild(btn('插入', '把选中的图片插入画布(尺寸按「设置 → 插入尺寸」)', function () {
var names = pickedNames()
var k = cfg.insertK || '1k'
setStatus('插入中…(' + names.length + ' 张)')
Promise.resolve(ctx.gallery.insert(names, { insertK: k })).then(function (r) {
if (r && r.ok === false) { setStatus('插入失败'); return }
setStatus('已插入 ' + names.length + ' 张(' + String(k).toUpperCase() + ')')
@@ -282,7 +295,7 @@
picked = {}
render()
return Promise.resolve(ctx.gallery.remove(names)).then(function () {
setTimeout(load, 250)
return load() // v1.7.0:等宿主真删完再重拉(固定延时会拉到未删完的清单)
})
}).catch(function () {})
}, true, true))
@@ -437,7 +450,13 @@
b.addEventListener('click', function (e) { e.stopPropagation(); fn() })
return b
}
acts.appendChild(act('插入', '插入到画布(参考图节点)', function () { ctx.gallery.insert([it.name]).catch(function () {}) }))
acts.appendChild(act('插入', '插入到画布(参考图节点 · 尺寸按「设置 → 插入尺寸」)', function () {
// v1.7.0:格子里的「插入」此前没带 insertK,宿主按默认 1k 处理 —— 与右键菜单/顶部「插入」不一致
setStatus('插入中…')
ctx.gallery.insert([it.name], { insertK: cfg.insertK || '1k' }).then(function () {
setStatus('已插入:' + it.name)
}).catch(function () { setStatus('插入失败') })
}))
acts.appendChild(act('下载', '下载到本地', function () { doDownload([it.name]) }))
box.appendChild(acts)
return box
@@ -514,11 +533,25 @@
// v1.3.0:自动恢复 —— 面板重新可见(切回 tab / 窗口聚焦 / 后台回来)且距上次拉取 >5s 时重拉一次,
// 这样图床恢复、后台补图后不必手动刷新;同时保留底部「刷新」按钮做即时重试。
// v1.7.0:这只是**兜底**。主通道改成宿主主动通知(下面 onChanged)—— 生成途中面板一直是可见的,
// 靠「可见性变化」触发永远等不到,用户看到的就是「生图完成但图库没图」。
var lastLoadAt = 0
var autoRefresh = function () {
if (Date.now() - lastLoadAt < 5000) return
load()
}
var unsubChanged = null
var changedTimer = 0
try {
var G = ctx.gallery
if (G && typeof G.onChanged === 'function') {
unsubChanged = G.onChanged(function () {
// 合并同一批的连续通知(一张图会触发「归档完成」一次),260ms 内只重拉一次
clearTimeout(changedTimer)
changedTimer = setTimeout(function () { load() }, 260)
})
}
} catch (e) { /* 旧宿主没有 onChanged:退回可见性刷新 + 手动刷新 */ }
try {
if (typeof IntersectionObserver === 'function') {
var io = new IntersectionObserver(function (entries) {
@@ -545,6 +578,8 @@
return function dispose () {
if (ro) { try { ro.disconnect() } catch (e) { /* ignore */ } }
clearTimeout(changedTimer)
try { if (typeof unsubChanged === 'function') unsubChanged() } catch (e) { /* ignore */ }
try { document.removeEventListener('pointerdown', onMenuDown, true) } catch (e) { /* ignore */ }
try { document.removeEventListener('keydown', onMenuKey, true) } catch (e) { /* ignore */ }
try { document.removeEventListener('drop', onDocDrop, true) } catch (e) { /* ignore */ }
@@ -555,7 +590,7 @@
global.IWBPluginHost.register({
id: 'gallery',
name: '图库',
version: '1.6.12',
version: '1.7.0',
apiVersion: 1,
capabilities: ['panels', 'gallery'],
data: { schemaVersion: 1, maxBytes: 65536 },
+2 -2
View File
@@ -1,7 +1,7 @@
{
"id": "gallery",
"name": "图库",
"version": "1.6.12",
"version": "1.7.0",
"apiVersion": 1,
"main": "main.js",
"style": "styles.css",
@@ -13,7 +13,7 @@
"图库"
],
"files": {
"main.js": "a5fb039684937de44d1033c75d9872b9e6d1c8c2c9582cd5feee948562e9b7d1",
"main.js": "77b8e95c06c6811fdee3a832195e2b76bc6197d8bfdf9df0a47a52b6b4dfb38f",
"styles.css": "35ae17de8b0f3bddab9cbef6270cd8bbf5153c9ecf6ed2b4f06216f6fef45b8b"
}
}
+8 -8
View File
@@ -22,9 +22,9 @@
"dir": "gallery",
"main": "main.js",
"style": "styles.css",
"version": "1.6.12",
"version": "1.7.0",
"files": {
"main.js": "a5fb039684937de44d1033c75d9872b9e6d1c8c2c9582cd5feee948562e9b7d1",
"main.js": "77b8e95c06c6811fdee3a832195e2b76bc6197d8bfdf9df0a47a52b6b4dfb38f",
"styles.css": "35ae17de8b0f3bddab9cbef6270cd8bbf5153c9ecf6ed2b4f06216f6fef45b8b"
}
},
@@ -44,10 +44,10 @@
"dir": "promptlib",
"main": "main.js",
"style": "styles.css",
"version": "1.9.1",
"version": "1.11.0",
"files": {
"main.js": "9743c44630a5190f43921060dee1296052c96d9d958b2c95f53e70a1ab63603b",
"styles.css": "d799321065172c2844c565cea9abc69053663ef9ec962e35911e0331bcff85aa"
"main.js": "0e1bd0f235b05b3edbdccd19ffe24791f0ce82bb5180ebe5a60dcaa6b2ed3ce8",
"styles.css": "23fd4beb4f5b89be1f763ee7221e3dbdafced85afc378cd5cc1a9e03b14d7046"
}
},
{
@@ -64,9 +64,9 @@
},
{
"id": "sticky",
"file": "plugin-sticky.ec6ffaa21fe4.js",
"version": "1.0.5",
"integrity": "sha256-7G/6oh/kod4qe0Zvt25O/5OFbO1hWJdk36mHcYEH218="
"file": "plugin-sticky.af8e7249f0c7.js",
"version": "1.0.7",
"integrity": "sha256-r45ySfDHwBDMFUTuWpOpq21cJcqlYtq5DnOKUtndSLI="
},
{
"id": "style-source",
+253 -122
View File
@@ -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) {
@@ -162,12 +170,55 @@
if (!item || typeof item.text !== 'string' || !item.text.trim()) return null
return item
}
function plpSharePayload (p) {
return plpCoverUrl(p).then(function (cv) {
var body = { app: 'image-workbench', kind: 'prompt-share', version: 1, sharing: { name: p.name || '', text: p.text || '', vars: detectVars(p.text || ''), group: p.group || '', tags: p.tags || [] } }
if (cv && cv.length < 300000) body.sharing.cover = cv
return SHARE_TAG + '\n' + JSON.stringify(body)
// 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 () {
@@ -232,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 + ' 个'
})
}
@@ -279,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 = {}
@@ -302,31 +353,8 @@
})
}).catch(function (e) { impBtn.disabled = false; status.textContent = '导入失败:' + ((e && e.message) || e) })
})
var impShareBtn = el('button', { class: 'iwb-btn iwb-btn-sm', title: '读取剪贴板里别人分享的单条提示词', text: '导入分享…' })
impShareBtn.addEventListener('click', function () {
impShareBtn.disabled = true; status.textContent = '读取剪贴板…'
Promise.resolve(PLP_CTX.promptlib.paste && PLP_CTX.promptlib.paste()).then(function (r) {
impShareBtn.disabled = false
if (!r || r.ok === false) { status.textContent = '读取剪贴板失败'; return null }
var item = plpParseShare(r.text)
if (!item) { status.textContent = '剪贴板里没有可识别的提示词分享'; return null }
var name = String(item.name || '').trim() || ('导入的提示词 ' + String(item.text).slice(0, 8) + '…')
state.prompts = state.prompts.concat([{ id: 'q' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), name: name, text: item.text, group: String(item.group || ''), tags: item.tags || [], vars: detectVars(item.text) }])
var g2 = String(item.group || '').trim()
if (g2 && !state.groups.some(function (x) { return x.name === g2 })) state.groups = state.groups.concat([{ id: g2, name: g2 }])
return save()
}).then(function (r2) {
if (!r2) return
return PLP_CTX.promptlib.list().then(function (cur) {
state.prompts = (cur && cur.prompts) || state.prompts
state.groups = (cur && cur.groups) || state.groups
paint(); refreshUsage()
status.textContent = '已导入分享'
plpNotify('已导入分享的提示词')
})
}).catch(function (e) { impShareBtn.disabled = false; status.textContent = '导入失败:' + ((e && e.message) || e) })
})
s2.appendChild(el('div', { class: 'iwb-plp-sbtns' }, expBtn, impBtn, impShareBtn))
// v1.10.0:设置面板不再放单条提示词导入入口,导入统一走词库面板顶部的「文件 / 文本」。
s2.appendChild(el('div', { class: 'iwb-plp-sbtns' }, expBtn, impBtn))
s2.appendChild(el('label', { class: 'iwb-plp-sopt' }, overwrite, el('span', { text: '导入时覆盖同名条目' })))
s2.appendChild(status)
root.appendChild(s2)
@@ -334,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() })
@@ -389,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)
@@ -442,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 })
@@ -470,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++
@@ -497,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) {
@@ -514,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() })
}
@@ -684,26 +773,15 @@
e.preventDefault(); e.stopPropagation()
closeMenu()
var menu = el('div', { class: 'iwb-ctxmenu iwb-lib-group-menu', style: 'left:' + e.clientX + 'px;top:' + e.clientY + 'px' })
menu.appendChild(el('div', { class: 'iwb-ctx-title', text: '移动到分组' }))
var item = function (label, value) {
var b = el('button', { class: 'iwb-ctx-item', text: label })
b.addEventListener('click', function () {
closeMenu()
save(prompts.map(function (x) { return x.id === p.id ? Object.assign({}, x, { group: value }) : x }))
.then(function () { notify('已移动到' + (value || '未分组')) })
})
menu.appendChild(b)
}
item('未分组', '')
groupsOf().forEach(function (g) { item(g.name, g.name) })
var sep = el('div', { class: 'iwb-ctx-sep' })
menu.appendChild(sep)
var ed = el('button', { class: 'iwb-ctx-item', text: '编辑…' })
ed.addEventListener('click', function () { closeMenu(); openEditModal(p, false) })
menu.appendChild(ed)
var sh = el('button', { class: 'iwb-ctx-item', text: '分享…' })
sh.addEventListener('click', function () { closeMenu(); doShare(p) })
menu.appendChild(sh)
var st = el('button', { class: 'iwb-ctx-item', text: '文本分享' })
st.addEventListener('click', function () { closeMenu(); doShareText(p) })
menu.appendChild(st)
var sf = el('button', { class: 'iwb-ctx-item', text: '文件分享' })
sf.addEventListener('click', function () { closeMenu(); doShareFile(p) })
menu.appendChild(sf)
document.body.appendChild(menu)
menuEl = menu
setTimeout(function () { document.addEventListener('pointerdown', onDocDown, true) }, 0)
@@ -1141,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 })
@@ -1303,37 +1379,68 @@
// ===== 2026-11-24:单条提示词分享 / 导入别人的分享 =====
// 分享格式刻意做成「可读的 JSON 文本」,直接粘到微信/QQ 也能看懂;导入时两种都认:
// ① 带 IWB-PROMPT 头的整段文本 ② 直接是 {kind:'prompt-share'} 的 JSON
function sharePayload (p) {
// v1.10.0:withCover 显式传入——文本分享恒传 false(纯文字、短),文件分享传 true(封面放文件里不怕大)。
// v1.10.1:开关已删,只认显式布尔;未传一律按纯文字,不再回退读设置。
function sharePayload (p, withCover) {
var body = { app: 'image-workbench', kind: 'prompt-share', version: 1, sharing: { name: p.name || '', text: p.text || '', vars: varsOf(p), group: p.group || '', tags: p.tags || [] } }
var wantCover = withCover === true
if (!wantCover) return Promise.resolve(SHARE_TAG + '\n' + JSON.stringify(body))
return coverToDataUrl(p).then(function (cv) {
var body = { app: 'image-workbench', kind: 'prompt-share', version: 1, sharing: { name: p.name || '', text: p.text || '', vars: varsOf(p), group: p.group || '', tags: p.tags || [] } }
if (cv && cv.length < 300000) body.sharing.cover = cv
return SHARE_TAG + '\n' + JSON.stringify(body)
})
}
function doShare (p) {
function shareFileName (p) {
return (String((p && p.name) || '提示词').replace(/[\\/:*?"<>|]/g, '_').trim() || '提示词').slice(0, 40) + '.json'
}
// 文本分享:复制纯文字(不带封面),内容最短,直接粘到聊天软件。
function doShareText (p) {
if (!p) return
sharePayload(p).then(function (text) {
sharePayload(p, false).then(function (text) {
return Promise.resolve(api.copy(text)).then(function (r) {
if (r && r.ok === false) { notify('分享失败:' + ((r && r.error) || '剪贴板不可用'), 'err'); return }
notify('已复制分享内容,粘贴给对方即可')
notify('已复制纯文字分享,粘贴给对方即可')
})
}).catch(function (e) { notify('分享失败:' + ((e && e.message) || e), 'err') })
}
// 文件分享:导出带封面的 .json 文件,作为附件发给对方(文件不怕大)。
function doShareFile (p) {
if (!p) return
sharePayload(p, true).then(function (text) {
return Promise.resolve(api.exportText(shareFileName(p), text)).then(function (r) {
if (r && r.ok) notify('已导出分享文件:' + (r.path || shareFileName(p)))
else if (r && r.canceled) notify('已取消')
else notify('导出失败:' + ((r && r.error) || '未知错误'), 'err')
})
}).catch(function (e) { notify('导出失败:' + ((e && e.message) || e), 'err') })
}
// 分享入库:剪贴板导入与文件导入共用,避免两套逻辑跑偏。
function importShareItem (item) {
var name = String(item.name || '').trim() || ('导入的提示词 ' + String(item.text).slice(0, 8) + '…')
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(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])
return persist().then(function () { render(); notify('已导入分享:' + (p2.name || '')); return { ok: true, name: p2.name } })
})
}
function doImportShare () {
return Promise.resolve(api.paste && api.paste()).then(function (r) {
if (!r || r.ok === false) { notify('读取剪贴板失败:' + ((r && r.error) || '剪贴板不可用'), 'err'); return { ok: false } }
var item = plpParseShare(r.text)
if (!item) { notify('剪贴板里没有可识别的提示词分享', 'err'); return { ok: false, error: 'no-share' } }
var name = String(item.name || '').trim() || ('导入的提示词 ' + String(item.text).slice(0, 8) + '…')
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(incoming)
return ready.then(function (p2) {
prompts = prompts.concat([p2])
return persist().then(function () { render(); notify('已导入分享:' + (p2.name || '')); return { ok: true, name: p2.name } })
})
return importShareItem(item)
}).catch(function (e) { notify('导入失败:' + ((e && e.message) || e), 'err'); return { ok: false } })
}
function importShareFromFile () {
return Promise.resolve(api.importText && api.importText()).then(function (r) {
if (!r || r.ok === false) { notify((r && r.canceled) ? '已取消' : ('读取文件失败:' + ((r && r.error) || '未知错误'))); return { ok: false } }
var item = plpParseShare(r.text)
if (!item) { notify('文件里没有可识别的提示词分享', 'err'); return { ok: false, error: 'no-share' } }
return importShareItem(item)
}).catch(function (e) { notify('导入失败:' + ((e && e.message) || e), 'err'); return { ok: false } })
}
@@ -1402,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 })
@@ -1502,12 +1607,14 @@
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('已复制全文') }) })
var share = el('button', { class: 'iwb-btn iwb-btn-sm', title: '复制这条提示词的分享内容,粘贴给对方即可导入', text: '分享' })
share.addEventListener('click', function () { doShare(p) })
var shareText = el('button', { class: 'iwb-btn iwb-btn-sm', title: '复制纯文字分享,粘贴给对方即可导入(不含封面,内容短)', text: '文本分享' })
shareText.addEventListener('click', function () { doShareText(p) })
var shareFile = el('button', { class: 'iwb-btn iwb-btn-sm', title: '导出带封面的分享文件,作为附件发给对方', text: '文件分享' })
shareFile.addEventListener('click', function () { doShareFile(p) })
ins.addEventListener('click', function () { dlg.close(); beginPlacement('prompt', { text: filled(), name: p.name || '' }) })
var insImg = null
if (p.cover) {
@@ -1522,7 +1629,11 @@
}).catch(function () { notify('插入封面失败', 'err') })
})
}
footEl.appendChild(del); footEl.appendChild(el('span', { class: 'iwb-drawer-spacer' })); if (insTpl) footEl.appendChild(insTpl); footEl.appendChild(cp); footEl.appendChild(share)
footEl.appendChild(del); footEl.appendChild(el('span', { class: 'iwb-drawer-spacer' }))
footEl.appendChild(shareText); footEl.appendChild(shareFile)
// v1.10.1:分享组与插入组之间加竖向分割线(替代原来的 26px 空白)。
footEl.appendChild(el('span', { class: 'iwb-plp-foot-vsep' }))
footEl.appendChild(cp); if (insTpl) footEl.appendChild(insTpl)
if (insImg) footEl.appendChild(insImg)
footEl.appendChild(ins)
},
@@ -1563,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') })
}
@@ -1630,7 +1745,8 @@
if (last < v.length) hl.appendChild(document.createTextNode(v.slice(last)))
hl.appendChild(document.createTextNode('\n'))
}
textIn.addEventListener('scroll', function () { hl.scrollTop = textIn.scrollTop })
// v1.9.3:高亮层只画变量色块,必须跟随 textarea 双向滚动(补横向,纵向沿用)
textIn.addEventListener('scroll', function () { hl.scrollTop = textIn.scrollTop; hl.scrollLeft = textIn.scrollLeft })
textIn.value = draft.text || ''
paintHl()
var varEd = makeVarsEditor(draft.text || '', draft.vars || [], function (nt) { textIn.value = nt; dirty = true; paintHl() })
@@ -1707,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()
@@ -1742,20 +1864,29 @@
var top = el('div', { class: 'iwb-row' })
var search = el('input', { class: 'iwb-input iwb-grow', placeholder: '搜索名称 / 内容 / 标签…', value: query })
search.addEventListener('input', function () { query = search.value; render(); var n = wrap.querySelector('input.iwb-input'); if (n) { n.focus(); try { n.setSelectionRange(n.value.length, n.value.length) } catch (e) { /* ignore */ } } })
// 2026-11-24:导入/新建都放搜索行,避免「导入分享」藏在设置里(用户反馈多绕一层)。
var importBtn = el('button', { class: 'iwb-btn iwb-btn-sm', title: '从剪贴板导入别人分享的词例', text: '导入词例' })
var newBtn = el('button', { class: 'iwb-btn iwb-btn-sm iwb-btn-primary', title: '新建词例', text: '+ 新建词例' })
// v1.10.0:顶部三入口 = 文件(从分享文件导入)/ 文本(从剪贴板导入)/ 新建。
var fileBtn = el('button', { class: 'iwb-btn iwb-btn-sm', title: '从分享文件导入词例', text: '文件' })
var textBtn = el('button', { class: 'iwb-btn iwb-btn-sm', title: '从剪贴板导入词例', text: '文本' })
var newBtn = el('button', { class: 'iwb-btn iwb-btn-sm iwb-btn-primary', title: '新建词例', text: '新建' })
importBtn.addEventListener('click', function () {
importBtn.disabled = true
fileBtn.addEventListener('click', function () {
fileBtn.disabled = true
importShareFromFile().then(function (r) {
fileBtn.disabled = false
if (r && r.ok === false && r.error === 'no-share') notify('文件里没有可识别的词例分享', 'err')
else if (r && r.ok === false) notify('导入失败', 'err')
}).catch(function (e) { fileBtn.disabled = false; notify('导入失败:' + ((e && e.message) || e), 'err') })
})
textBtn.addEventListener('click', function () {
textBtn.disabled = true
doImportShare().then(function (r) {
importBtn.disabled = false
textBtn.disabled = false
if (r && r.ok === false && r.error === 'no-share') notify('剪贴板里没有可识别的词例分享', 'err')
else if (r && r.ok === false) notify('导入失败', 'err')
}).catch(function (e) { importBtn.disabled = false; notify('导入失败:' + ((e && e.message) || e), 'err') })
}).catch(function (e) { textBtn.disabled = false; notify('导入失败:' + ((e && e.message) || e), 'err') })
})
newBtn.addEventListener('click', function () { openEditModal(null, true) })
top.appendChild(search); top.appendChild(importBtn); top.appendChild(newBtn)
top.appendChild(search); top.appendChild(fileBtn); top.appendChild(textBtn); top.appendChild(newBtn)
fixed.appendChild(top)
if (words().length) {
@@ -1828,7 +1959,7 @@
items.forEach(function (p) {
var starred = (p.group || '') === '收藏'
var coverUrl = coverOf(p)
var card = el('div', { class: 'iwb-plp-card' + (p.cover ? ' has-cover' : ' no-cover'), title: '双击查看详情 · 拖到画布插入 · 右键移动到分组' })
var card = el('div', { class: 'iwb-plp-card' + (p.cover ? ' has-cover' : ' no-cover'), title: '双击查看详情 · 拖到画布插入 · 右键编辑/分享' })
var bg = el('div', { class: 'iwb-plp-bg' })
bg.style.background = coverUrl ? 'var(--iwb-plugin-inset)' : gradOf(p)
if (coverUrl) bg.appendChild(el('img', { class: 'iwb-plp-cover', src: coverUrl, alt: '', draggable: 'false' }))
@@ -1870,11 +2001,13 @@
global.IWBPluginHost.register({
id: 'promptlib',
name: '提示词库',
version: '1.9.1',
version: '1.11.0',
apiVersion: 1,
capabilities: ['panels', 'promptlib', 'nodeTypes', 'canvas', 'canvasWrite'],
data: { schemaVersion: 3, maxBytes: 4 * 1024 * 1024 },
settings: { panel: { type: 'custom', label: '分组与备份', render: renderPluginSettings } },
settings: {
panel: { type: 'custom', label: '分组与备份', render: renderPluginSettings },
},
}, function (ctx) {
PLP_CTX = ctx
// v1.5.0:插件激活时就把旧数据迁到插件目录(不等面板打开),
@@ -1907,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 })
+3 -3
View File
@@ -1,7 +1,7 @@
{
"id": "promptlib",
"name": "提示词库",
"version": "1.9.1",
"version": "1.11.0",
"apiVersion": 1,
"main": "main.js",
"style": "styles.css",
@@ -13,7 +13,7 @@
"提示词"
],
"files": {
"main.js": "9743c44630a5190f43921060dee1296052c96d9d958b2c95f53e70a1ab63603b",
"styles.css": "d799321065172c2844c565cea9abc69053663ef9ec962e35911e0331bcff85aa"
"main.js": "0e1bd0f235b05b3edbdccd19ffe24791f0ce82bb5180ebe5a60dcaa6b2ed3ce8",
"styles.css": "23fd4beb4f5b89be1f763ee7221e3dbdafced85afc378cd5cc1a9e03b14d7046"
}
}
+19 -4
View File
@@ -348,6 +348,11 @@ height: 1px; margin: 4px 6px; background: var(--iwb-border); flex: 0 0 auto;
.iwb-promptlib .iwb-drawer-spacer {
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 12px; background: var(--iwb-border);
}
.iwb-plp-dialog .iwb-section-sub {
margin-top: 2px;
}
@@ -484,7 +489,8 @@ body.iwb-plp-dragging, body.iwb-plp-dragging *{user-select:none!important;-webki
tab-size:4!important;
}
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap .iwb-plp-etext{overflow-y:auto!important;scrollbar-gutter:stable}
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-hl{overflow:hidden!important}
/* v1.9.3:高亮层与 textarea 用同样的滚动条占位,避免换行位置不一致导致色块漂移 */
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap .iwb-plp-hl{overflow:hidden!important;scrollbar-gutter:stable}
/* v1.7.9:详情正文独立滚动,长文不再压到底部按钮 */
.iwb-plp-dialog-detail .iwb-plp-dbody{overflow:hidden;align-items:stretch}
.iwb-plp-dialog-detail .iwb-plp-dright{flex:1 1 auto;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:hidden}
@@ -557,8 +563,17 @@ body.iwb-plp-dragging, body.iwb-plp-dragging *{user-select:none!important;-webki
.iwb-plp-dialog .iwb-plp-dcov .iwb-plp-cover,.iwb-plp-dialog .iwb-plp-ecov .iwb-plp-cover{background:transparent!important}
/* v1.8.19:编辑区高亮变量不得加粗——加粗会改变字形宽度,导致点击位置逐次向左偏移 */
.iwb-plp-hlvar{font-weight:400!important;letter-spacing:normal!important}
/* v1.8.20:编辑区不再用透明 textarea+高亮层(两层字体/换行差异会让点击坐标逐次偏移);正文直接由 textarea 渲染,插入点 100% 对应光标 */
.iwb-plp-ewrap .iwb-plp-hl{display:none!important}
/* v1.9.3:变量着色改为「textarea 只负责文字 + 背层只画浅主色色块」——
两层字体/换行/滚动条占位由 v1.7.7 规则保持一致,变量 span 沿用 400 字重(不加粗,宽度不漂移),
文字仍由 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: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) */
/* 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:6px;padding:0 2px}
/* 回滚开关:若真机发现任何点击/光标异常,把下行打开即回到 v1.8.20 纯 textarea 状态。
.iwb-plp-ewrap .iwb-plp-hl{display:none!important} */
@@ -218,6 +218,9 @@
}
var act = t.getAttribute && t.getAttribute('data-act')
if (act === 'wheel') {
// 点开系统取色器后这个浮层就完成使命:无论最终确认还是取消都先收起,
// 避免取色器关闭后色板还压在便签上(用户报的“自定义调色后面板不退出”)。
st.palOpen = false; pal.hidden = true
try { colorInput.click() } catch (e2) { /* noop */ }
}
}
@@ -227,6 +230,8 @@
var up = st.props && st.props.onUpdate
var id = st.node && st.node.id
if (up && id && e.target && e.target.value) up(id, { bgColor: e.target.value })
// 自定义色确认后兜底再收一次(个别平台 change 先于上面的收起逻辑到达)。
st.palOpen = false; pal.hidden = true
}
colorInput.addEventListener('change', onColor)
@@ -299,7 +304,10 @@
// 读出来还是旧高度,会自我锁死);
// 2. 首次遇到「旧 h 明显大于内容」时把 node.h 校正到内容高度,顺手把外框 minHeight
// 覆盖成同一个值——resize 起点 (onResizeStart 读 n0.h) 才和实际视觉一致,拖小立刻生效。
// 用户之后手动拖大的 h 不会再次被校正(只针对首次记录的 stale h),所以仍然可以拖大拖小。
// 区分两种 h:
// - 插件自动跟随内容写出的 h:内容长高就涨、缩回就降(v1.0.6 修的「两行退回一行不缩」);
// - 用户拖手柄改出的 h:h 相对上一帧变了 ⇒ 尊重手动尺寸,只在内容超过它时顶一下。
// 首次遇到的旧大 h 校正一次(staleH),之后进入自动跟随。
function fitOuterBox(st, node) {
if (!st || !st.root || !node) return
var toolsH = st.tools.offsetHeight || 30
@@ -308,9 +316,24 @@
var content = Math.round(toolsH + bodyH + 2) // +2 = 宿主节点上下各 1px 边框
var h = Number(node.h) || 0
if (st.staleH == null) st.staleH = h
// 文字变大后内容超过旧 h:同步把 h 顶上去,resize 起点才不会滞后一大截。
// 首次遇到的旧大 h 也校正到内容高度;用户之后拖出来的其它更大 h 原样保留。
if (h < content - 2 || (h > content + 2 && st.staleH === h)) node.h = content
if (st.lastBoxH != null && h !== st.lastBoxH) {
// 外部(用户拖手柄)改了 h:退出自动跟随,保留手动尺寸
st.autoFollow = false
} else if (st.autoFollow == null) {
// 首帧:旧 h 若明显大于内容,先校正一次,然后进入自动跟随
if (h > content + 2 && st.staleH === h) { node.h = content; h = content }
st.autoFollow = true
}
if (st.autoFollow) {
// 自动跟随:文本/字号增减都双向贴合(这是两行退回一行能缩回去的关键)
if (Math.abs(h - content) > 1) { node.h = content; h = content }
} else if (h < content - 2) {
// 手动尺寸只在内容超出时才顶高,不覆盖用户主动拖大的高度
node.h = content; h = content
}
st.lastBoxH = h
var floor = Math.max(content, Number(node.h) || 0)
// root → host(.iwb-plugin-node-body) → card(.iwb-node)
var card = st.root.parentNode && st.root.parentNode.parentNode
@@ -418,7 +441,7 @@
global.IWBPluginHost.register({
id: 'sticky',
name: '便利贴',
version: '1.0.5',
version: '1.0.7',
apiVersion: 1,
capabilities: ['panels', 'nodeTypes', 'canvas'],
}, function (ctx) {
+174
View File
@@ -0,0 +1,174 @@
#!/usr/bin/env node
/* 图片存储巡检(只读):回答「图存在哪 / 节点里为什么是链接 / 有没有孤儿文件」。
*
* 用法:
* node scripts/audit-image-storage.js # 默认读 ~/Documents/ImageWorkbench
* node scripts/audit-image-storage.js --dir /path # 指定资料目录
*
* 判读口径见 docs/standards/image-storage-map.md。本脚本**不修改任何文件**,
* 存在的意义是:存储结论必须由实际数据支撑,不能由注释或默认值推断(2026-11-24 误判的教训)。
*/
'use strict'
const fs = require('fs')
const path = require('path')
const os = require('os')
const args = process.argv.slice(2)
const dirArg = (() => {
const i = args.indexOf('--dir')
if (i >= 0 && args[i + 1]) return args[i + 1]
return process.env.IWB_DATA_DIR || path.join(os.homedir(), 'Documents', 'ImageWorkbench')
})()
const kb = (n) => (n >= 1048576 ? (n / 1048576).toFixed(1) + 'MB' : (n / 1024).toFixed(0) + 'KB')
const readJson = (p, fb) => { try { return JSON.parse(fs.readFileSync(p, 'utf8')) } catch (e) { return fb } }
const dirSize = (p) => {
let n = 0
try {
for (const f of fs.readdirSync(p)) {
const abs = path.join(p, f)
try {
const st = fs.statSync(abs)
n += st.isDirectory() ? dirSize(abs) : st.size
} catch (e) { /* 单文件失败忽略 */ }
}
} catch (e) { return 0 }
return n
}
if (!fs.existsSync(dirArg)) {
console.log('资料目录不存在:' + dirArg)
console.log('(说明:这是网页版/未初始化环境,图片字节在浏览器 IndexedDB,不在磁盘上)')
process.exit(0)
}
console.log('资料目录:' + dirArg)
console.log('总体积:' + kb(dirSize(dirArg)))
console.log('')
// ---- ① data.json 登记表 ----
const data = readJson(path.join(dirArg, 'data.json'), {})
const assets = (data && data.assets) || {}
const keys = Object.keys(assets)
const regByCat = {}
const regByKind = {}
const registeredFiles = new Set()
for (const k of keys) {
const a = assets[k] || {}
const parts = String(a.f || '').split('/')
const cat = parts[0] === 'images' ? (parts[1] || '?') : '(非图片)'
regByCat[cat] = (regByCat[cat] || 0) + 1
regByKind[a.k || '?'] = (regByKind[a.k || '?'] || 0) + 1
if (a.f) registeredFiles.add(a.f)
}
console.log('① 登记表 data.json:' + kb(fs.statSync(path.join(dirArg, 'data.json')).size) +
' · assets ' + keys.length + ' 条 · imgblob_ ' + keys.filter((k) => k.indexOf('imgblob_') === 0).length + ' 条')
console.log(' 按目录:' + JSON.stringify(regByCat))
console.log(' 按类型:' + JSON.stringify(regByKind))
console.log('')
// ---- ② 目录实际文件 vs 登记(孤儿) ----
const imgRoot = path.join(dirArg, 'images')
let orphanAll = 0
if (fs.existsSync(imgRoot)) {
console.log('② images/ 实际文件(未登记 = 孤儿;_768 显示版属已知例外)')
for (const cat of fs.readdirSync(imgRoot)) {
const abs = path.join(imgRoot, cat)
let st = null
try { st = fs.statSync(abs) } catch (e) { continue }
if (!st.isDirectory()) continue
const files = fs.readdirSync(abs)
let bytes = 0
let reg = 0
let orphan = 0
let display = 0
const samples = []
for (const f of files) {
const rel = 'images/' + cat + '/' + f
let sz = 0
try { sz = fs.statSync(path.join(abs, f)).size } catch (e) { /* ignore */ }
bytes += sz
if (/_768\.(jpg|webp)$/i.test(f) && !registeredFiles.has(rel)) { display++; continue }
if (registeredFiles.has(rel)) reg++
else { orphan++; if (samples.length < 2) samples.push(f) }
}
orphanAll += orphan
console.log(' ' + cat.padEnd(8) + String(files.length).padStart(4) + ' 个 ' + kb(bytes).padStart(8) +
' · 已登记 ' + reg + ' · 孤儿 ' + orphan + (display ? ' · 显示版 ' + display : '') +
(samples.length ? ' · 例 ' + samples.join(', ') : ''))
}
console.log('')
}
// ---- ③ 图库清单 ----
const gi = readJson(path.join(dirArg, 'library', 'gallery', 'index.json'), null)
const gList = Array.isArray(gi) ? gi : (gi && Array.isArray(gi.files) ? gi.files : null)
if (gList) {
const scheme = {}
let withOrig = 0
for (const f of gList) {
if (f && f.origIdb) withOrig++
const u = f && f.url
const s = typeof u === 'string' && u ? (u.slice(0, 5).toLowerCase() === 'https' ? 'https' : (u.indexOf('data:') === 0 ? 'dataURL' : 'other')) : '(空)'
scheme[s] = (scheme[s] || 0) + 1
}
console.log('③ 图库清单 library/gallery/index.json:' + gList.length + ' 条')
console.log(' 有 origIdb(本地原图在 images/gallery/):' + withOrig + '/' + gList.length)
console.log(' url 形态:' + JSON.stringify(scheme))
console.log('')
} else {
console.log('③ 图库清单不存在或为空\n')
}
// ---- ④ 画布节点引用形态 ----
const cvDir = path.join(dirArg, 'canvases')
if (fs.existsSync(cvDir)) {
const files = fs.readdirSync(cvDir).filter((f) => f.endsWith('.json'))
const shape = (v) => {
if (!v) return '空'
if (typeof v === 'string') {
if (/^https?:/i.test(v)) return 'http 链接'
if (v.indexOf('data:') === 0) return '内联 base64'
return '其它字符串'
}
if (v.__blob) return '{__blob} → images/canvas'
if (v.__idb) return '{__idb} → images/*'
if (v.__cache) return '{__cache}'
return '其它对象'
}
const inUrl = {}
const inData = {}
let refs = 0
const host = {}
for (const f of files) {
const j = readJson(path.join(cvDir, f), null)
if (!j) continue
const ws = Array.isArray(j) ? j : (j.workspaces || [j])
for (const w of ws) {
for (const n of (w && w.nodes) || []) {
if (!n || n.type !== 'ref') continue
refs++
const d = n.data || {}
const a = shape(d.url); inUrl[a] = (inUrl[a] || 0) + 1
const b = shape(d.data); inData[b] = (inData[b] || 0) + 1
if (typeof d.url === 'string' && /^https?:/i.test(d.url)) {
let h = '?'
try { h = new URL(d.url).host } catch (e) { /* ignore */ }
host[h] = (host[h] || 0) + 1
}
}
}
}
console.log('④ 画布存档 ' + files.length + ' 个 · 参考图节点 ' + refs + ' 个')
console.log(' data.url :' + JSON.stringify(inUrl))
console.log(' data.data:' + JSON.stringify(inData))
const hosts = Object.keys(host).sort((a, b) => host[b] - host[a]).slice(0, 6)
if (hosts.length) console.log(' data.url 远程域名 top:' + hosts.map((h) => h + '×' + host[h]).join(' · '))
console.log('')
}
console.log('结论提示:')
console.log(' · data.url 里 http 占多数 ⇒ 这些节点不能标注/吃不到上游,需要"素材化"落本地')
console.log(' · data.data 里 {__blob} ⇒ 桌面端字节在 images/canvas/,由 wCleanIdb 按引用集回收')
console.log(' · 图库条目 origIdb 覆盖率高 ⇒ 插入"原图档"可零拷贝引用,无需再复制一份')
if (orphanAll) console.log(' · 存在 ' + orphanAll + ' 个孤儿文件(可被 wCleanIdb 回收,或由用户手动清理)')
+1
View File
@@ -101,6 +101,7 @@ const sourceModules = [
'canvas-grid.js',
'image-display-thumb.js',
'image-remote-cache.js',
'gallery-sync.js',
'image-thumb-pick.js',
'ui-modal-drag.js',
'ui-nav-rail.js',
+2 -2
View File
@@ -3,7 +3,7 @@
<title>插件开发规范 · Image Workbench</title>
<link rel="icon" href="/assets/favicon.png" type="image/png">
<link rel="apple-touch-icon" href="/assets/logo.png">
<link rel="stylesheet" href="/assets/style.css?v=3.26.57-mwu5p2lf">
<link rel="stylesheet" href="/assets/style.css?v=3.26.60-mwuecf3f">
<style>
.devdoc{max-width:860px;margin:0 auto;padding:40px 0 72px;color:var(--ink,#1b1f24);font-size:15px;line-height:1.75}
.devdoc h1{font-size:38px;line-height:1.2;margin:8px 0 18px}
@@ -33,7 +33,7 @@
</div>
<div class="right">
<a class="btn" href="/plugins/">插件市场</a>
<a class="btn primary" href="/download/">下载 v3.26.57</a>
<a class="btn primary" href="/download/">下载 v3.26.60</a>
</div>
</div></nav>
<main>
+18 -6
View File
@@ -57,18 +57,18 @@
<h2>下载</h2>
<div class="row">
<div class="name">macOS · Apple Silicon<div class="hint">M1 / M2 / M3 / M4</div></div>
<div class="meta">版本 3.26.57 · 8.4 MB · .dmg<div class="hash">sha256 3e45e7ddbd0367a5…</div></div>
<a class="btn" href="/updates/darwin-aarch64/image-workbench_3.26.57_aarch64.dmg?h=3e45e7ddbd03">下载</a>
<div class="meta">版本 3.26.60 · 8.4 MB · .dmg<div class="hash">sha256 e3cd2adff23b1d2b…</div></div>
<a class="btn" href="/updates/darwin-aarch64/image-workbench_3.26.60_aarch64.dmg?h=e3cd2adff23b">下载</a>
</div>
<div class="row">
<div class="name">macOS · Intel<div class="hint">x86_64</div></div>
<div class="meta">版本 3.26.57 · 8.8 MB · .dmg<div class="hash">sha256 de9b2e7f102c479b…</div></div>
<a class="btn" href="/updates/darwin-x86_64/image-workbench_3.26.57_x64.dmg?h=de9b2e7f102c">下载</a>
<div class="meta">版本 3.26.60 · 8.8 MB · .dmg<div class="hash">sha256 1dd4ce4fa5b47a09…</div></div>
<a class="btn" href="/updates/darwin-x86_64/image-workbench_3.26.60_x64.dmg?h=1dd4ce4fa5b4">下载</a>
</div>
<div class="row">
<div class="name">Windows · x64<div class="hint">需要 WebView2</div></div>
<div class="meta"></div>
<span class="muted">暂未提供</span>
<div class="meta">版本 3.26.60 · 4.8 MB · .exe<div class="hash">sha256 9c41e7a6f438b6a3…</div></div>
<a class="btn" href="/updates/windows-x86_64/image-workbench_3.26.60_x64-setup.exe?h=9c41e7a6f438">下载</a>
</div>
<h2>系统要求</h2>
@@ -97,6 +97,18 @@
</ol>
<h2>历史版本</h2>
<div class="row">
<div class="name">3.26.60<div class="hint">浮层字号上调一档:模型设置/图像设置的选择项 11→13px、高 28px,面板 360px</div></div>
<div class="meta">2026-11-24<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
</div>
<div class="row">
<div class="name">3.26.59<div class="hint">备份带上插件文件(提示词封面不再换机丢失);promptlib 1.11.0 封面文件治理</div></div>
<div class="meta">2026-11-24<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.26.58</div>
<div class="meta">2026-11-24<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
</div>
<div class="row">
<div class="name">3.26.57</div>
<div class="meta">2026-11-24<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
+9 -9
View File
@@ -4,7 +4,7 @@
<meta name="description" content="本地优先的 AI 生图无限画布:节点式工作流、插件按需安装、数据全部留在本机。">
<link rel="icon" href="/assets/favicon.png" type="image/png">
<link rel="apple-touch-icon" href="/assets/logo.png">
<link rel="stylesheet" href="/assets/style.css?v=3.26.57-mwu5p2lf">
<link rel="stylesheet" href="/assets/style.css?v=3.26.60-mwuecf3f">
</head><body>
<nav><div class="wrap inner">
<a class="brand" href="/"><img class="logo" src="/assets/logo.png" alt="" width="26" height="26">Image Workbench</a>
@@ -17,19 +17,19 @@
</div>
<div class="right">
<a class="btn" href="/plugins/">插件市场</a>
<a class="btn primary" href="/download/">下载 v3.26.57</a>
<a class="btn primary" href="/download/">下载 v3.26.60</a>
</div>
</div></nav>
<main>
<section class="hero hero-art">
<div class="hero-bg"><img src="/assets/painting.jpg?v=3.26.57-mwu5p2lf" alt=""></div>
<div class="hero-bg"><img src="/assets/painting.jpg?v=3.26.60-mwuecf3f" alt=""></div>
<div class="hero-veil"></div>
<div class="wrap">
<span class="kicker">v3.26.57 · macOS / Windows · 数据在本地</span>
<span class="kicker">v3.26.60 · macOS / Windows · 数据在本地</span>
<h1>本地优先的<br>AI 生图无限画布</h1>
<p class="sub">用节点把「参考图 → 提示词 → 批量生成 → 图库」串成一条生产线。<br>图片、提示词、模型配置全部留在你自己的电脑里,插件按需安装。</p>
<div class="cta">
<a class="btn primary lg" href="/download/">下载 v3.26.57</a>
<a class="btn primary lg" href="/download/">下载 v3.26.60</a>
<a class="btn lg" href="/plugins/">浏览 12 个插件</a>
</div>
<div class="meta">支持 macOS 12+ 与 Windows 10 1803+ · 安装包约 7 MB · 无需登录</div>
@@ -85,7 +85,7 @@
</div>
<div class="pcard" data-name="提示词库 promptlib 右栏提示词列表:搜索/分组/收藏/新建编辑/插入画布/复制(数据由客户端提供) 资源 提示词" data-tags="资源,提示词">
<div class="head"><span class="av" style="background:#eef2f6">📖</span>
<div><div class="nm">提示词库</div><div class="ver">v1.9.1 · 官方</div></div></div>
<div><div class="nm">提示词库</div><div class="ver">v1.11.0 · 官方</div></div></div>
<div class="desc">右栏提示词列表:搜索/分组/收藏/新建编辑/插入画布/复制(数据由客户端提供)</div>
<div class="tags"><span class="tag">资源</span><span class="tag">提示词</span></div>
</div>
@@ -96,9 +96,9 @@
<section class="section"><div class="wrap">
<h2>下载 Image Workbench</h2>
<p class="lead">选你的平台。装过一次之后,以后在应用内「设置 → 通用 → 版本与更新」就能一键升级。</p>
<div class="dl"><a href="/updates/darwin-aarch64/image-workbench_3.26.57_aarch64.dmg?h=3e45e7ddbd03"><div class="n">macOS · Apple Silicon</div><div class="s">M1 / M2 / M3 / M4 · 8.4 MB · .dmg</div></a>
<a href="/updates/darwin-x86_64/image-workbench_3.26.57_x64.dmg?h=de9b2e7f102c"><div class="n">macOS · Intel</div><div class="s">x86_64 · 8.8 MB · .dmg</div></a>
<div class="none"><div class="n">Windows · x64</div><div class="s">暂未提供</div></div></div>
<div class="dl"><a href="/updates/darwin-aarch64/image-workbench_3.26.60_aarch64.dmg?h=e3cd2adff23b"><div class="n">macOS · Apple Silicon</div><div class="s">M1 / M2 / M3 / M4 · 8.4 MB · .dmg</div></a>
<a href="/updates/darwin-x86_64/image-workbench_3.26.60_x64.dmg?h=1dd4ce4fa5b4"><div class="n">macOS · Intel</div><div class="s">x86_64 · 8.8 MB · .dmg</div></a>
<a href="/updates/windows-x86_64/image-workbench_3.26.60_x64-setup.exe?h=9c41e7a6f438"><div class="n">Windows · x64</div><div class="s">需要 WebView2 · 4.8 MB · .exe</div></a></div>
<div style="margin-top:20px;color:#9ca3af;font-size:12.5px">安装包未做 Apple 公证 / Windows 代码签名,首次打开需手动放行一次,细节见 <a href="/download/" style="text-decoration:underline">下载页</a>。</div>
</div></section>
</main>
+22 -22
View File
@@ -1,6 +1,6 @@
{
"version": 2,
"updatedAt": "2026-11-24T03:49:11.170Z",
"updatedAt": "2026-11-24T07:15:05.519Z",
"plugins": [
{
"id": "batch-export",
@@ -180,26 +180,26 @@
"资源",
"提示词"
],
"version": "1.9.1",
"version": "1.11.0",
"apiVersion": 1,
"bundle": "plugins/promptlib-1.9.1.zip",
"bundleSize": 157855,
"bundleSha256": "9d8a7d3514fe3368881147cc08d4bc24b3bc9eb682271e130572d4d7c023d38c",
"bundle": "plugins/promptlib-1.11.0.zip",
"bundleSize": 167890,
"bundleSha256": "66fca4b8c06b2e399383d095c92604c5c23b520238379bbf8bfa89c4c86a08ad",
"files": [
{
"path": "manifest.json",
"sha256": "3464379a6867c22d47207e175943290fd08463048a3201746000398aee7f93d7",
"size": 540
"sha256": "15212a82a8ad8bf1195598740077125dbee8f3f210d7426ec38a7bdf2abe07bc",
"size": 541
},
{
"path": "main.js",
"sha256": "9743c44630a5190f43921060dee1296052c96d9d958b2c95f53e70a1ab63603b",
"size": 114481
"sha256": "0e1bd0f235b05b3edbdccd19ffe24791f0ce82bb5180ebe5a60dcaa6b2ed3ce8",
"size": 122957
},
{
"path": "styles.css",
"sha256": "d799321065172c2844c565cea9abc69053663ef9ec962e35911e0331bcff85aa",
"size": 42524
"sha256": "23fd4beb4f5b89be1f763ee7221e3dbdafced85afc378cd5cc1a9e03b14d7046",
"size": 44082
}
]
},
@@ -280,27 +280,27 @@
"标注",
"便签"
],
"version": "1.0.5",
"version": "1.0.7",
"apiVersion": 1,
"bundle": "plugins/sticky-1.0.5.zip",
"bundleSize": 24256,
"bundleSha256": "8f3e392ae65fd222c4b4e6adf172f11e29245f6f764859dbf6b5896182e9665c",
"bundle": "plugins/sticky-1.0.7.zip",
"bundleSize": 25425,
"bundleSha256": "1087fc1a8f842145e75cfca909acb0caf839fbf7349de6a7eee1d112843df369",
"files": [
{
"path": "manifest.json",
"sha256": "81c995a4eb823ba427d0cfef9ca2cf64de3e6f53d8ddf32a0196c94fde8a4103",
"sha256": "17e5bf6fb11cfe6d7748957d902f3e78585cdb7a1df44b387fd6dbdcae3a7958",
"size": 400
},
{
"path": "main.js",
"sha256": "ec6ffaa21fe4a1de2a7b466fb76e4eff93856ced61589764dfa987718107db5f",
"size": 23642
"sha256": "af8e7249f0c7c010cc1544ee5a93a9ab6d5c25caa562dab90e738a52d9dd48b2",
"size": 24811
}
],
"file": "plugins/plugin-sticky.ec6ffaa21fe4.js",
"size": 23642,
"sha256": "ec6ffaa21fe4a1de2a7b466fb76e4eff93856ced61589764dfa987718107db5f",
"integrity": "sha256-7G/6oh/kod4qe0Zvt25O/5OFbO1hWJdk36mHcYEH218="
"file": "plugins/plugin-sticky.af8e7249f0c7.js",
"size": 24811,
"sha256": "af8e7249f0c7c010cc1544ee5a93a9ab6d5c25caa562dab90e738a52d9dd48b2",
"integrity": "sha256-r45ySfDHwBDMFUTuWpOpq21cJcqlYtq5DnOKUtndSLI="
},
{
"id": "style-source",
+4 -4
View File
@@ -3,7 +3,7 @@
<title>插件市场 · Image Workbench</title>
<link rel="icon" href="/assets/favicon.png" type="image/png">
<link rel="apple-touch-icon" href="/assets/logo.png">
<link rel="stylesheet" href="/assets/style.css?v=3.26.57-mwu5p2lf">
<link rel="stylesheet" href="/assets/style.css?v=3.26.60-mwuecf3f">
</head><body>
<nav><div class="wrap inner">
<a class="brand" href="/"><img class="logo" src="/assets/logo.png" alt="" width="26" height="26">Image Workbench</a>
@@ -16,7 +16,7 @@
</div>
<div class="right">
<a class="btn" href="/plugins/">插件市场</a>
<a class="btn primary" href="/download/">下载 v3.26.57</a>
<a class="btn primary" href="/download/">下载 v3.26.60</a>
</div>
</div></nav>
<main>
@@ -80,7 +80,7 @@
</div>
<div class="pcard" data-name="提示词库 promptlib 右栏提示词列表:搜索/分组/收藏/新建编辑/插入画布/复制(数据由客户端提供) 资源 提示词" data-tags="资源,提示词">
<div class="head"><span class="av" style="background:#eef2f6">📖</span>
<div><div class="nm">提示词库</div><div class="ver">v1.9.1 · 官方</div></div></div>
<div><div class="nm">提示词库</div><div class="ver">v1.11.0 · 官方</div></div></div>
<div class="desc">右栏提示词列表:搜索/分组/收藏/新建编辑/插入画布/复制(数据由客户端提供)</div>
<div class="tags"><span class="tag">资源</span><span class="tag">提示词</span></div>
</div>
@@ -98,7 +98,7 @@
</div>
<div class="pcard" data-name="便利贴 sticky 画布便利贴:多行文本 + 字号/粗细调节 + 8 色背景,纯说明不连线 标注 便签" data-tags="标注,便签">
<div class="head"><span class="av" style="background:#fdf3d0">📝</span>
<div><div class="nm">便利贴</div><div class="ver">v1.0.5 · 官方</div></div></div>
<div><div class="nm">便利贴</div><div class="ver">v1.0.7 · 官方</div></div></div>
<div class="desc">画布便利贴:多行文本 + 字号/粗细调节 + 8 色背景,纯说明不连线</div>
<div class="tags"><span class="tag">标注</span><span class="tag">便签</span></div>
</div>
+78 -1
View File
@@ -1,8 +1,85 @@
{
"app": "Image Workbench",
"subtitle": "本地优先的 AI 生图无限画布 · 桌面版(Tauri v2)",
"updatedAt": "2026-11-24T03:49:57.900Z",
"updatedAt": "2026-11-24T07:52:04.104Z",
"releases": [
{
"version": "3.26.60",
"date": "2026-11-24",
"notes": "浮层字号上调一档:模型设置/图像设置的选择项 11→13px、高 28px,面板 360px",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.26.60_aarch64.dmg",
"size": 8799262,
"sha256": "e3cd2adff23b1d2b4e1f5c52114c9151392a7864eb44686a9a607ef0272212ce",
"h": "e3cd2adff23b",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.26.60_x64.dmg",
"size": 9186576,
"sha256": "1dd4ce4fa5b47a093d6f558b92af5e6074728c114629eec18c929bf1bb8c79c4",
"h": "1dd4ce4fa5b4",
"kind": "dmg"
},
"windows-x86_64": {
"file": "updates/windows-x86_64/image-workbench_3.26.60_x64-setup.exe",
"size": 5005719,
"sha256": "9c41e7a6f438b6a349e5853d82c99930c6607cc69807b75f430e741417df67e9",
"h": "9c41e7a6f438",
"kind": "exe"
}
}
},
{
"version": "3.26.59",
"date": "2026-11-24",
"notes": "备份带上插件文件(提示词封面不再换机丢失);promptlib 1.11.0 封面文件治理",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.26.59_aarch64.dmg",
"size": 8798901,
"sha256": "31af87020085457e801143e471c53a7062fa29d47e54c08d4a200530e2949a06",
"h": "31af87020085",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.26.59_x64.dmg",
"size": 9185089,
"sha256": "ef8bac19b21fed48686ad23262325529fc539881d59f4089436fb380893230a3",
"h": "ef8bac19b21f",
"kind": "dmg"
}
}
},
{
"version": "3.26.58",
"date": "2026-11-24",
"notes": "",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.26.58_aarch64.dmg",
"size": 8798836,
"sha256": "f2d0499c263727dc201fb84f4f52ec837294e93645bcf2bbf502a2e947e360ac",
"h": "f2d0499c2637",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.26.58_x64.dmg",
"size": 9186843,
"sha256": "357bcf1f5c6c027328058b858a44ab151d8b62d5540e6db70b9012d28af2610b",
"h": "357bcf1f5c6c",
"kind": "dmg"
},
"windows-x86_64": {
"file": "updates/windows-x86_64/image-workbench_3.26.58_x64-setup.exe",
"size": 5006832,
"sha256": "1d471517cbb1d1322037127e44ba68e293339eb1453280f509451b69bb8a16d7",
"h": "1d471517cbb1",
"kind": "exe"
}
}
},
{
"version": "3.26.57",
"date": "2026-11-24",
+1 -1
View File
@@ -1983,7 +1983,7 @@ dependencies = [
[[package]]
name = "image-workbench"
version = "3.26.57"
version = "3.26.60"
dependencies = [
"arboard",
"base64 0.22.1",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "image-workbench"
version = "3.26.57"
version = "3.26.61"
description = "无限画布 · 生图工作台桌面版"
authors = ["malongan"]
license = ""
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "image-workbench",
"version": "3.26.57",
"version": "3.26.61",
"identifier": "com.malongan.imageworkbench",
"build": {
"frontendDist": "../dist",
+191
View File
@@ -0,0 +1,191 @@
/* gallery-sync.js —— 图库 ↔ 画布的同步边界(v3.26.61)
*
* 这里只放「跨存储区域」的动作,app.js 只做装配(注入既有能力)和 commit:
* ① archiveEntryNow(entry, refresh) —— 单张生成结果立刻入图库(串行队列 + 等缩略图 + 通知插件)
* ② notifyChanged(reason) —— 图库变了(删除/恢复/清空/归档)→ 通知图库插件重拉
* ③ localCopySrcOf(item) —— 图库条目 → **本地字节**(dataURL);本地没有就抓一次远程
* ④ prepareInsert(list, k) —— 条目 → 可建节点的 [{src, srcUrl, name}](压缩 + 引用化)
* ⑤ gridSpots(base, n, opt) —— 批量插入的栅格落点
*
* 为什么需要 ①:归档原本只在整轮结束做一次(archiveGenerationResults),而一次 4 张、每张 20s,
* 第 1 张上图时图库还是空的。为什么需要 ③:解析不出本地字节时旧实现把 http 链接直接写进
* 节点 data.url,标注插件判「远程图片不支持标注」,用户以为插入失败。
* 用户裁定(2026-11-24):B6 = 复制 —— 插入一律落地本地副本,多占空间可以,不能丢数据。
*/
;(function (global) {
'use strict'
function create (deps) {
const d = deps || {}
const queue = { chain: Promise.resolve() }
// 同一 entry 只归档一次(WeakSet:entry 对象用完即回收,不给画布数据添字段)
const archived = (typeof WeakSet === 'function') ? new WeakSet() : null
function notifyChanged (reason) {
try { if (typeof d.emit === 'function') d.emit(reason || 'changed') } catch (e) { /* 插件回调异常不影响宿主 */ }
}
// 单张结果 → 图库。串行是必须的:多个任务并发完成时,索引是「读-改-写」,
// 并发写会互相吃掉条目。awaitArchive 让这张的缩略图先落盘,插件取 thumb 直接命中。
function archiveEntryNow (entry, refresh) {
if (!entry) return Promise.resolve(false)
if (archived) {
if (archived.has(entry)) return Promise.resolve(false)
archived.add(entry) // 先打标:重试调用也只归档一次
}
const job = queue.chain.then(async () => {
const items = (typeof d.flatten === 'function') ? d.flatten([entry]) : []
if (items.length && typeof d.addOutputs === 'function') {
try { await d.addOutputs(items, { awaitArchive: true }) } catch (e) { /* 图库缓存失败不影响画布结果 */ }
}
try { if (typeof refresh === 'function') await refresh() } catch (e) { /* ignore */ }
notifyChanged('output')
return true
})
queue.chain = job.then(() => {}, () => {}) // 队列只关心「上一张结束」,不传递结果/异常
return job
}
// 图库条目 → **本地字节**(dataURL)。取源顺序沿用宿主既有口径「画质最优优先」:
// ① 原图文件(桌面端 images/gallery,浏览器 IndexedDB)
// ② 远程原图抓一次字节(桌面端走 Rust 请求不受 CORS;8s 超时,慢图床不拖着插入不放)
// ③ 清单里已 hydrate 的 data / 320 缩略图(能标注,但画质将就)
// ④ '' —— 交给调用方保留原链接,绝不阻断插入、绝不丢图
// 注意 ②③ 的顺序:缩略图排远程之后。反过来的话「有远程原图却插进一张 320 小图」,
// 用户标注完导出才发现糊了。
async function localCopySrcOf (item) {
if (!item) return ''
const fetchRemote = async (url) => {
if (!/^https?:/i.test(url)) return ''
if (typeof d.isDesktop === 'function' && d.isDesktop() && typeof d.desktopFetch === 'function') {
try { const r = await d.desktopFetch(url); if (r && r.ok) { const b = await r.blob(); const du = b && typeof d.blobToDataUrl === 'function' ? await d.blobToDataUrl(b) : ''; if (du) return du } } catch (e) { /* 白名单外/网络失败 → 落到 WebView fetch */ }
}
if (typeof d.blobFromSrc !== 'function') return ''
const blob = await d.blobFromSrc(url).catch(() => null)
return (blob && typeof d.blobToDataUrl === 'function') ? await d.blobToDataUrl(blob) : ''
}
try {
if (item.origIdb && typeof d.get === 'function') {
const v = await d.get(item.origIdb).catch(() => null)
if (v) return v
}
const url = String(item.url || '')
if (/^https?:/i.test(url)) {
// 8s 上限:抓不到就走缩略图,别让插入卡在图床超时上
const remote = await Promise.race([fetchRemote(url), new Promise((r) => setTimeout(() => r(''), 8000))])
if (remote) return remote
}
const data = (item.data && typeof item.data === 'object' && typeof d.refDataUrl === 'function')
? await d.refDataUrl(item.data) : item.data
if (typeof data === 'string' && data) return data
if (item.idb && typeof d.get === 'function') {
const v = await d.get(item.idb).catch(() => null)
if (v) return v
}
if (url.indexOf('data:') === 0) return url
} catch (e) { /* 取不到就交给调用方兜底 */ }
return ''
}
// 条目 → 插入用源。每张:本地副本 → SVG 纠正 → 按档压缩 → 引用化({__blob})。
// 全部拿不到本地字节时保留原链接(remoteOnly 交给调用方提示),绝不阻断插入、绝不丢图。
// extra:组件内才有的能力(refSrcOf / shrink / writeRef),按次注入,不放进 create 的长依赖表。
async function prepareInsert (list, k, extra) {
const e = extra || {}
const refSrcOf = e.refSrcOf || d.refSrcOf
const shrink = e.shrink || d.shrink
const writeRef = e.writeRef || d.writeRef
const items = Array.isArray(list) ? list.filter(Boolean) : []
const out = []
let remoteOnly = 0
for (const f of items) {
let src = await localCopySrcOf(f)
if (!src) { src = String(f.url || ''); if (src) remoteOnly++ }
if (typeof refSrcOf === 'function') src = await refSrcOf(src, (msg) => { if (typeof d.notice === 'function') d.notice(msg) })
if (typeof src === 'string' && src.indexOf('data:') === 0 && typeof shrink === 'function') src = await shrink(src, k)
const ref = (typeof src === 'string' && src.indexOf('data:') === 0 && typeof writeRef === 'function') ? await writeRef(src) : null
out.push({ src: ref || src || '', srcUrl: String(f.url || ''), name: f.name })
}
return { items: out, remoteOnly: remoteOnly }
}
// 批量插入的落点:旧实现在循环里每张都 findSpot,而 findSpot 只看已 commit 的节点 ⇒
// 整批落在同一坐标,视觉上只有一张。这里按 4 列栅格铺开(与「粘贴多图」同一手感)。
function gridSpots (base, n, opt) {
const o = opt || {}
const stepX = Number(o.stepX) || 288
const stepY = Number(o.stepY) || 276
const cols = Math.max(1, Number(o.cols) || 4)
const x0 = (base && Number(base.x)) || 0
const y0 = (base && Number(base.y)) || 0
const out = []
for (let i = 0; i < Math.max(0, n); i++) out.push({ x: x0 + (i % cols) * stepX, y: y0 + Math.floor(i / cols) * stepY })
return out
}
// 这条结果是否已经逐张归档过(整轮归档据此跳过,避免同一张图入两次库)
function wasArchived (entry) {
return !!(archived && entry && typeof entry === 'object' && archived.has(entry))
}
// 节点 → 可标注的图。候选里必须带 data.localRef:远程参考图的本地缓存
// (src/image-remote-cache.js)命中后写在那个字段上,早先这里没读它,于是「缓存明明有了」
// 插件仍只看 data.url 的 http 链接,直接判「远程图片不支持标注」(用户报障的直接成因)。
// 只有远程链接时按需抓一次并写回 localRef(之后都走本地);抓不到返回 url,不丢数据。
async function nodeImageOf (node, extra) {
const e = extra || {}
const n = node
if (!n || !n.data) return null
const first = Array.isArray(n.data.result) ? (n.data.result[0] || {}) : n.data.result
const candidates = [n.data.data, n.data.localRef, n.data.url, first && (first.url || first.data)]
const resolveRef = (typeof d.refDataUrl === 'function') ? d.refDataUrl : null
let remote = ''
for (const v of candidates) {
if (!v) continue
if (typeof v === 'string') {
if (/^data:/i.test(v)) return { dataUrl: v }
if (/^https?:/i.test(v)) { if (!remote) remote = v; continue } // 先记住远程,继续找本地
return { url: v }
}
if (resolveRef) { const dataUrl = await resolveRef(v); if (dataUrl) return { dataUrl } }
}
if (!remote) return null
const du = await localCopySrcOf({ url: remote })
if (!du) return { url: remote }
if (typeof e.writeRef === 'function') {
try { const ref = await e.writeRef(du); if (ref && typeof e.onLocalRef === 'function') e.onLocalRef(ref) } catch (err) { /* 写回失败不影响本次结果 */ }
}
return { dataUrl: du }
}
// 图库格子的缩略图地址。新图刚入库时 React 快照可能还没带上 data(缩略图在后台并发生成),
// 旧实现直接 `f.data || f.url` —— 于是要么空、要么现拉远程图床(慢、跨域、限流都会转成
// 「图片已丢失」)。这里按 清单 data → images/thumbs/ 缩略图 → 本地原图 → 远程 顺序取。
async function thumbFor (name, extra) {
const e = extra || {}
const f = (Array.isArray(e.outputs) ? e.outputs : []).find((x) => x && x.name === name)
if (!f) return ''
const display = (typeof e.displayThumbOf === 'function') ? e.displayThumbOf : ((v) => v)
if (f.data) return display(f.data)
if (f.thumbHash && typeof e.galleryThumb === 'function') {
try { const v = await e.galleryThumb(f.thumbHash); if (v) return display(v) } catch (err) { /* 继续本地原图 */ }
}
const local = await localCopySrcOf(f)
if (local) return display(local)
return display(f.url || '')
}
return { archiveEntryNow, wasArchived, notifyChanged, localCopySrcOf, prepareInsert, gridSpots, nodeImageOf, thumbFor }
}
let attached = null
// 单例装配:app.js 只需一行就能拿到全部能力(依赖表长,写在 app.js 里会撑破行数棘轮)
function attach (deps) {
attached = create(deps)
return attached
}
function get () { return attached }
global.IWBGallerySync = { create, attach, get }
})(typeof window !== 'undefined' ? window : globalThis)
+3 -1
View File
@@ -1,7 +1,9 @@
/* 图片字节的 Blob 仓库(借鉴 OpenTu 的资产模型:记录只留引用 + 元数据,字节独立存放)
*
* 目的:画板记录(以及每份撤销快照、每次落库)不再携带 MB 级 base64 字符串。
* - 写入:dataURL/base64 → 存成 IDB 里的 **Blob**,返回 key(内容哈希去重 ⇒ 同图只存一份)
* - 写入:dataURL/base64 → 存成**注入的 idb 后端**里的 Blob,返回 key(内容哈希去重 ⇒ 同图只存一份)
* idb 由调用方注入:浏览器 = IndexedDB;桌面端 = storage-file 的文件 KV ⇒ 落 images/canvas/<sha16>.<ext>
* (本文件不认识"文件",只认识 put/get/del;任何"字节在 IndexedDB"的结论都要先看调用方注入了谁)
* - 记录里只放引用对象 { __blob: 'imgblob_<hash>_<len>' }
* - 渲染/导出时按需 resolve(dataURL 或 Blob),用完不驻留
* - 内存 Blob 缓存为**有界 LRU**(create({ blobCacheMax }),缺省 200):淘汰只丢句柄,getBlob 会回 IDB 重读;
+3
View File
@@ -4,6 +4,9 @@
* 做法:空闲时下载一次,写入本地引用存储,节点上只记 data.localRef(显示用)。
*
* 约束(用户裁定):节点 data.url 保持原样 ⇒ **提交生成时仍然用链接**。
* 谁在读 localRef(v3.26.61 修正):插件取图走 canvasBridge.getNodeImage,它的候选列表里必须有
* localRef —— 早先漏了它,于是缓存明明命中,标注插件仍只看到 data.url 的 http 链接,
* 直接判「远程图片不支持标注」(用户报障的直接成因)。改这个字段的写入时机/格式前先看那里。
*/
;(function (global) {
'use strict'
+21 -3
View File
@@ -1,16 +1,22 @@
/* plugin-api-gallery.js —— 宿主 gallery capability(M5)
*
* 给插件一块**只读为主**的图库访问面:列表 / 缩略图 / 预览 / 下载 / 插入画布 / 删除。
* 图片字节仍留在宿主(images/ + 图库索引),插件拿不到文件路径,只能拿元数据与缩略图 URL。
* 图片字节仍留在宿主(桌面端 = images/gallery + images/thumbs 文件,浏览器 = IndexedDB),
* 插件拿不到文件路径,只能拿元数据与缩略图 URL。
*
* 为什么要这层「impl 桥」:
* capability 在 PluginHost.init 时创建(早于组件渲染),拿不到 Workbench 的 state/refs。
* 所以这里只保存一组**稳定的代理函数**,真正的实现由 Workbench 每次渲染时 setImpl 注入。
*
* v1.7.0(2026-11-24):补 onChanged —— 此前只有「拉」没有「推」,出图后图库面板要等
* 可见性变化/5s 节流才刷新,用户看到的是「生成了但图库没图」。宿主在归档、删除、恢复后
* emit 一次,插件订阅后自己 load()。
*/
;(function (global) {
'use strict'
let impl = null
const listeners = []
function setImpl (next) {
impl = (next && typeof next === 'object') ? next : null
@@ -24,6 +30,13 @@
}
}
// 图库数据变了下发一次(生成结果逐张归档 / 删除 / 恢复 / 清空 / 保留策略剪枝)
function emit (reason) {
for (const fn of listeners.slice()) {
try { fn(reason || 'changed') } catch (e) { /* 插件回调异常不影响宿主 */ }
}
}
// 稳定代理:插件拿到的对象永不变,内部每次都取最新的 impl
const API = {
list: call('list'),
@@ -33,6 +46,11 @@
insert: call('insert'),
remove: call('remove'),
openFolder: call('openFolder'),
onChanged: function (fn) {
if (typeof fn !== 'function') return function () {}
listeners.push(fn)
return function () { const i = listeners.indexOf(fn); if (i >= 0) listeners.splice(i, 1) }
},
}
// 纯函数:把宿主 outputs + 查询参数变成插件要的条目(不含 data,避免把 base64 递给插件)
@@ -50,5 +68,5 @@
return { items: items, total: res.total || items.length }
}
global.IWBPluginGallery = { setImpl: setImpl, api: function () { return API }, query: query }
})(typeof window !== 'undefined' ? window : globalThis)
global.IWBPluginGallery = { setImpl: setImpl, api: function () { return API }, query: query, emit: emit }
})(typeof window !== 'undefined' ? window : globalThis)
+49
View File
@@ -230,12 +230,61 @@
return { bytes: n, count: all.length }
}
// ---- 插件文件(plugin-data/<id>/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)
+12 -4
View File
@@ -82,7 +82,7 @@
// ── runNode ──────────────────────────────────────────────
async function runNode(ctx, nodeId, taskPromptId, onDone, opts) {
const { acquireGenSlot, activeWsId, activeWsIdRef, commitRunNodes, ensurePolished, finishGenerationRun, persistRuns, pushHistory, refreshOutputs, refs, runLockConflicts, runWorkspaceNodes, setBusy, setNotice, setProgress, updateNode } = ctx
const { acquireGenSlot, activeWsId, activeWsIdRef, archiveOne, commitRunNodes, ensurePolished, finishGenerationRun, persistRuns, pushHistory, refreshOutputs, refs, runLockConflicts, runWorkspaceNodes, setBusy, setNotice, setProgress, updateNode } = ctx
const node = refs.nodes.find((n) => n.id === nodeId)
if (!node) return 0
const activeProvider = (wRawCfg().providers || []).find((p) => p.id === node.data.provider) || null
@@ -372,6 +372,9 @@
results[idx0] = entry
// 流式展示逐张执行,不等待整个批次。
liveUpsert(j.t.id, j.i, entry)
// v3.26.61:这张已经上图 → 立刻归档进图库(串行队列 + 等缩略图,内部再通知插件)。
// 不 await:归档慢(原图落盘 + 缩略图)不能拖住下一张的调度;失败也不影响本张结果。
try { if (typeof archiveOne === 'function') archiveOne(entry) } catch (e) { /* ignore */ }
// 出图后的自动保存统一由 archiveGenerationResults → wAutoSaver 负责:先等图库归档完成,
// 再从本地原图字节(images/gallery 的 out_orig_)复制到导出目录。
// 这里过去调用交互式 downloadUrl(),导致两个线上问题:
@@ -1030,7 +1033,7 @@
// ── 画布拖拽导入(2026-11-06 从 Workbench 外移;行为逐字保留)───────────────────
function startCanvasDrop(ctx) {
const { canvasEl, refs, uiZoom, importCanvasFile, instantiateGroup, wResolveOutputSrc, wImgRefWrite, wImportImage, uid, pushHistory, commitCanvas, setSel, setNotice, outputs } = ctx
const { canvasEl, refs, uiZoom, importCanvasFile, instantiateGroup, localSrcOfOutput, wResolveOutputSrc, wImgRefWrite, wImportImage, uid, pushHistory, commitCanvas, setSel, setNotice, outputs } = ctx
const el0 = canvasEl && canvasEl.el
if (!el0) return undefined
const onDragOver = (e) => { e.preventDefault() }
@@ -1079,7 +1082,10 @@
}
if (origName) {
const item = (refs.outputs || outputs || []).find((x) => x && x.name === origName)
wResolveOutputSrc(item).then(async (src) => {
// v3.26.61:拖入也走「本地字节目录」(含按需抓远程再落副本),与「插入」按钮同一条路,
// 否则拖进来的节点仍可能是 http 链接 —— 同一张图,按钮插入能标注、拖进来不能,说不过去。
const pickSrc = () => (typeof localSrcOfOutput === 'function' ? localSrcOfOutput(item) : wResolveOutputSrc(item))
Promise.resolve(pickSrc()).then(async (src) => {
// 与「图库插入」按钮同一收口:SVG 先纠正成 PNG,否则矢量会一路传到模型接口
const raw = await refSrcOf(src || localRefPayload || (item && item.url) || '', (msg) => setNotice({ type: 'err', text: msg }))
if (!raw) { insertRef(''); return }
@@ -2094,7 +2100,9 @@
}
const refreshOutputs = (limit) => {
const requestId = ++outputRequestSeq.current
api('outputs', limit ? { limit } : undefined).then((r) => { if (requestId === outputRequestSeq.current && r && Array.isArray(r.files)) { setOutputs(r.files); setOutputsInfo(r) } }).catch(() => {})
// v3.26.61:**返回 Promise** —— 逐张归档要在「图库插件收到通知」之前确认 React outputs 已经换成新列表
// (插件的 list/thumb 走 impl,读的就是这份 state;不 await 就可能通知到了却还是旧列表)
return api('outputs', limit ? { limit } : undefined).then((r) => { if (requestId === outputRequestSeq.current && r && Array.isArray(r.files)) { setOutputs(r.files); setOutputsInfo(r) } }).catch(() => {})
}
const deleteOutputs = (names) => {
const list = Array.isArray(names) ? names : []
+2 -2
View File
@@ -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 {
+32 -1
View File
@@ -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/<id>/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,
+79 -17
View File
@@ -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/<id>/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 文件,请自行妥善保管。',
),
),
)
+16 -10
View File
@@ -1455,9 +1455,9 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
.iwb-size-num::-webkit-outer-spin-button, .iwb-size-num::-webkit-inner-spin-button { -webkit-appearance: none; appearance: none; margin: 0; }
/* ===== v3.86.5 图像设置浮层(质量 / 尺寸 / 分辨率 / 宽高比网格) ===== */
.iwb-image-settings { width: 380px; max-width: calc(100vw - 32px); }
.iwb-image-settings { width: var(--iwb-pop-w); max-width: calc(100vw - 32px); }
.iwb-image-settings .iwb-modal-body { display: flex; flex-direction: column; gap: 12px; }
.iwb-setgroup { display: flex; flex-direction: column; gap: var(--iwb-space-8); }
.iwb-setgroup { display: flex; flex-direction: column; gap: var(--iwb-space-4); }
/* v3.87.5:质量档位一行放 6 个 chip(自动/快速/标准/高清/极高/最高)→ 只在这个浮层里收紧内边距;
.iwb-setrow 本来就有 flex-wrap,字体差异导致放不下时自然换行,不存在溢出。 */
.iwb-image-settings .iwb-chip-line { padding: 0 var(--iwb-pop-chip-pad-x); }
@@ -1466,9 +1466,9 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
/* 设置里模型行的「质量」勾选:紧跟名字,不参与右侧按钮的挤压 */
.iwb-modelrow-q { flex: 0 0 auto; font-size: 12px; }
.iwb-modelrow-q input { margin: 0; }
.iwb-setlabel { color: var(--iwb-text2); font-size: var(--iwb-font-sm); font-weight: 700; }
.iwb-setlabel { color: var(--iwb-text2); font-size: var(--iwb-font-sm); font-weight: 600; }
.iwb-sethd { display: flex; align-items: center; justify-content: space-between; gap: var(--iwb-space-8); }
.iwb-setalign { font-size: var(--iwb-font-sm); white-space: nowrap; }
.iwb-setalign { font-size: var(--iwb-font-md); white-space: nowrap; }
.iwb-setrow { display: flex; flex-wrap: wrap; align-items: center; gap: var(--iwb-pop-chip-gap); }
.iwb-setx { color: var(--iwb-text2); flex: 0 0 auto; }
.iwb-set-num { flex: 0 0 auto; width: 74px; min-width: 0; text-align: center; font-variant-numeric: tabular-nums; -moz-appearance: textfield; appearance: textfield; }
@@ -1479,10 +1479,13 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
/* ===== v3.86.5 图像设置:贴节点浮层(popover)形态 ===== */
.iwb-pop-anchor { position: fixed; z-index: var(--iwb-z-anchor); }
/* 浮层弹窗(模型设置 / 图像设置 / 后续同类)统一 token —— 见 docs/standards/design-tokens.md §3.13 */
.iwb-pop { --iwb-pop-w: 380px; --iwb-pop-pad-y: var(--iwb-space-16); --iwb-pop-pad-x: var(--iwb-space-20); --iwb-pop-gap: var(--iwb-space-12); --iwb-pop-radius: var(--iwb-radius-popover); --iwb-pop-title-size: var(--iwb-font-base); --iwb-pop-chip-h: 32px; --iwb-pop-chip-pad-x: var(--iwb-space-12); --iwb-pop-chip-radius: var(--iwb-radius-control); --iwb-pop-chip-gap: var(--iwb-space-8); --iwb-pop-chip-size: var(--iwb-font-md); width: var(--iwb-pop-w); max-width: calc(100vw - 16px); background: var(--iwb-panel); border: 1px solid var(--iwb-border); border-radius: var(--iwb-pop-radius); box-shadow: var(--iwb-elevation-3); padding: var(--iwb-pop-pad-y) var(--iwb-pop-pad-x); display: flex; flex-direction: column; gap: var(--iwb-pop-gap); max-height: calc(100vh - 32px); overflow-y: auto; }
/* v3.26.60:字号整体上调一档(用户反馈 11px 太小)——胶囊 11→13px、高 22→28px、左右内距 6→10、
间距 4→6、标题 12→14,面板同步 328→360px 抵消放大后的换行。仍是「所有选项同一套数值」,
模型名永不省略的契约不变(靠 min-width: max-content + 面板横向滚动兜底)。 */
.iwb-pop { --iwb-pop-w: 360px; --iwb-pop-pad-y: var(--iwb-space-10); --iwb-pop-pad-x: var(--iwb-space-12); --iwb-pop-gap: var(--iwb-space-8); --iwb-pop-radius: var(--iwb-radius-popover); --iwb-pop-title-size: var(--iwb-font-base); --iwb-pop-chip-h: 28px; --iwb-pop-chip-pad-x: var(--iwb-space-10); --iwb-pop-chip-radius: 6px; --iwb-pop-chip-gap: var(--iwb-space-6); --iwb-pop-chip-size: var(--iwb-font-md); width: var(--iwb-pop-w); max-width: calc(100vw - 16px); background: var(--iwb-panel); border: 1px solid var(--iwb-border); border-radius: var(--iwb-pop-radius); box-shadow: var(--iwb-elevation-3); padding: var(--iwb-pop-pad-y) var(--iwb-pop-pad-x); display: flex; flex-direction: column; gap: var(--iwb-pop-gap); max-height: calc(100vh - 32px); overflow-y: auto; }
.iwb-pop-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.iwb-pop-title { font-weight: 700; color: var(--iwb-text); font-size: var(--iwb-pop-title-size); }
.iwb-pop-body { display: flex; flex-direction: column; gap: 12px; }
.iwb-pop-body { display: flex; flex-direction: column; gap: var(--iwb-pop-gap); }
/* 纯描边胶囊:与截图一致(选中只加重描边与文字色,不填充) */
.iwb-chip-line { background: transparent; border: 1px solid var(--iwb-border); color: var(--iwb-text); border-radius: 999px; padding: 5px 14px; }
.iwb-chip-line:hover { border-color: var(--iwb-brand); color: var(--iwb-text); }
@@ -1532,7 +1535,9 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
/* 弹窗内四组控件的形状统一:跟随「尺寸」那组(圆角矩形,非胶囊);字号统一 15px */
.iwb-pop .iwb-chip-line { display: inline-flex; align-items: center; border-radius: var(--iwb-pop-chip-radius); min-height: var(--iwb-pop-chip-h); padding: 0 var(--iwb-pop-chip-pad-x); font-size: var(--iwb-pop-chip-size); }
.iwb-pop .iwb-set-num { font-size: var(--iwb-font-lg); }
.iwb-pop .iwb-set-num { height: var(--iwb-pop-chip-h); font-size: var(--iwb-font-md); width: 68px; }
/* 浮层里的说明文字比全局 .iwb-hint(10px)大一档:与胶囊文字只差 1px,读起来是同一层信息 */
.iwb-pop .iwb-hint { font-size: var(--iwb-font-sm); line-height: 1.55; margin-top: 0; }
.iwb-pop-title { font-size: var(--iwb-pop-title-size); }
/* ---------- 分层节点(layer)----------
@@ -1637,13 +1642,14 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
模型列表用「标签流式排列」:每个按内容宽度,排满一行自动折行(2026-10-31 用户指定样式);
超长名字靠 min-width: max-content 撑开 ⇒ 面板内横向滚动,仍不省略。
文字 nowrap + 不设 text-overflow ⇒ 永不省略(省略会导致无法识别具体模型)。 */
.iwb-gen-config { width: min(92vw, 320px); max-height: min(78vh, calc(100vh - 24px)); display: flex; flex-direction: column; gap: var(--iwb-space-10); padding: var(--iwb-space-12) var(--iwb-space-16); }
/* 宽度跟随 --iwb-pop-w(原来写死 320px 会绕过 token,字号放大后模型面板不跟着变宽) */
.iwb-gen-config { width: min(92vw, var(--iwb-pop-w)); max-height: min(78vh, calc(100vh - 24px)); display: flex; flex-direction: column; gap: var(--iwb-space-10); padding: var(--iwb-space-12) var(--iwb-space-16); }
.iwb-gc-row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.iwb-gc-field { display: flex; align-items: center; gap: 6px; min-width: 0; }
.iwb-gc-label { font-size: var(--iwb-font-sm); color: var(--iwb-text2); white-space: nowrap; }
.iwb-gc-label { font-size: var(--iwb-font-md); color: var(--iwb-text2); white-space: nowrap; }
.iwb-gc-select { height: var(--iwb-pop-chip-h); font-size: var(--iwb-pop-chip-size); padding: 0 var(--iwb-pop-chip-pad-x); border: 1px solid var(--iwb-border); border-radius: var(--iwb-pop-chip-radius); background: var(--iwb-panel); color: var(--iwb-text); max-width: 220px; }
.iwb-gc-select:disabled { opacity: 0.5; }
.iwb-gc-sub { font-size: var(--iwb-font-sm); font-weight: 700; color: var(--iwb-text2); letter-spacing: 0.5px; }
.iwb-gc-sub { font-size: var(--iwb-font-md); font-weight: 700; color: var(--iwb-text2); letter-spacing: 0.5px; }
/* ── 节点背景色(2026-11-01 第二轮)──────────────────────────────────────────
数据侧:`data.bg` 存**令牌**(white/cyan/purple/pink/orange/yellow/green),
颜色值由本文件按主题映射 ⇒ 暗色主题是**独立的一套深色**,不是把浅色压暗。
+8 -1
View File
@@ -306,8 +306,15 @@ const refEntrySites = [
['拖入图片链接', /refSrcOf\(url, \(msg\) => setNotice/],
]
for (const [label, re] of refEntrySites) assert('参考图入口经过收口:' + label, re.test(logicSrc), '')
// v3.26.61:图库插入的取源从 wResolveOutputSrc 换成 src/gallery-sync.js 的 prepareInsert
//(本地副本优先 + 按需抓远程),所以钉点不能只认旧实现那一行;改为在 insertOutputsToCanvas
// 区间内要求两件事同时成立:① 仍经过 refSrcOf 收口(SVG → PNG,参考图格式约定)
// ② 取源走 gallery-sync(不再直连 http 链接)。区间用两个锚点切,不在这两个锚点之外的代码里误判。
const _insertAt = appJs.indexOf('const insertOutputsToCanvas = async')
const _insertEnd = appJs.indexOf('const loadDemo', _insertAt)
const _insertSrc = (_insertAt >= 0 && _insertEnd > _insertAt) ? appJs.slice(_insertAt, _insertEnd) : ''
assert('图库「插入」按钮经过收口(app.js 侧只做装配)',
appJs.includes('wbCmd().refSrcOf(await wResolveOutputSrc(f)'), '')
/wbCmd\(\)\.refSrcOf\(/.test(_insertSrc) && /wGallerySync\.prepareInsert\(/.test(_insertSrc), '')
assert('refSrcOf 已从 createWorkbenchCommands 导出(否则 app.js 侧调用是 undefined)',
/addRefFromUrl, refSrcOf,/.test(logicSrc), '')
+1
View File
@@ -13,6 +13,7 @@
"IWBDesktopHelpers",
"IWBDockArea",
"IWBGalleryHydration",
"IWBGallerySync",
"IWBGenerationRequestShape",
"IWBGenerationResults",
"IWBGenerationScheduler",
+1
View File
@@ -73,6 +73,7 @@
"canvas-grid.js",
"image-display-thumb.js",
"image-remote-cache.js",
"gallery-sync.js",
"image-thumb-pick.js",
"ui-modal-drag.js",
"ui-nav-rail.js",
+161
View File
@@ -0,0 +1,161 @@
'use strict'
// gallery-sync 行为回归(v3.26.61)
// 守三件用户报障直接相关的事:
// ① 单张归档只归档一次、且串行(并发完成时索引是读-改-写,乱序会互相吃掉条目);
// ② 条目→本地字节的取源顺序(有本地原图就不该去抓远程);
// ③ 节点取图必须读 data.localRef —— 漏了它,远程参考图即使已缓存,插件仍只看到 http 链接,
// 标注插件直接判「远程图片不支持标注」(这是 2026-11-24 用户报障的直接成因)。
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const src = fs.readFileSync(path.resolve(__dirname, '..', 'src', 'gallery-sync.js'), 'utf8')
const sandbox = { window: {}, console, Promise, setTimeout, clearTimeout, Object, Array, JSON, Math, String, Number, WeakSet }
vm.runInNewContext(src, sandbox)
const Sync = sandbox.window.IWBGallerySync
const checks = []
const ok = (name, fn) => checks.push({ name, fn })
ok('attach 单例可重复取用', () => {
const a = Sync.attach({})
assert.strictEqual(Sync.get(), a)
assert.strictEqual(typeof a.archiveEntryNow, 'function')
})
// ① 串行 + 去重
ok('archiveEntryNow:同一 entry 只归档一次(并发重复调用)', async () => {
const added = []
let chainRunning = 0
let maxParallel = 0
const s = Sync.create({
flatten: (entries) => entries.map((e) => ({ name: e.name })),
addOutputs: async (items) => {
chainRunning++
maxParallel = Math.max(maxParallel, chainRunning)
await new Promise((r) => setTimeout(r, 5))
chainRunning--
added.push(items[0].name)
},
emit: () => {},
})
const entry = { name: 'a.png' }
await Promise.all([s.archiveEntryNow(entry), s.archiveEntryNow(entry), s.archiveEntryNow(entry)])
await s.archiveEntryNow({ name: 'b.png' })
assert.deepStrictEqual(added, ['a.png', 'b.png'], '实际 ' + added.join(','))
assert.strictEqual(maxParallel, 1, '归档必须串行,实际并行 ' + maxParallel)
assert.strictEqual(s.wasArchived(entry), true)
})
ok('archiveEntryNow:归档失败不阻断后续(队列不断链)', async () => {
const added = []
let n = 0
const s = Sync.create({
flatten: (e) => e.map((x) => x),
addOutputs: async (items) => { n++; if (n === 1) throw new Error('boom'); added.push(items[0].id) },
emit: () => {},
})
await s.archiveEntryNow({ id: 'x' })
await s.archiveEntryNow({ id: 'y' })
assert.deepStrictEqual(added, ['y'])
})
// ② 取源顺序
ok('localCopySrcOf:有 origIdb 时直接用本地原图,不抓远程', async () => {
let fetched = 0
const s = Sync.create({
get: async (k) => (k === 'out_orig_a.png' ? 'data:image/png;base64,AAA' : null),
blobFromSrc: async () => { fetched++; return null },
})
const got = await s.localCopySrcOf({ name: 'a.png', origIdb: 'out_orig_a.png', url: 'https://x/y.png' })
assert.strictEqual(got, 'data:image/png;base64,AAA')
assert.strictEqual(fetched, 0, '本地已有字节就不该联网')
})
ok('localCopySrcOf:只剩远程时抓一次,抓到即返回 dataURL', async () => {
let fetched = 0
const s = Sync.create({
get: async () => null,
blobFromSrc: async () => { fetched++; return { size: 3 } },
blobToDataUrl: async () => 'data:image/png;base64,BBBB',
})
const got = await s.localCopySrcOf({ name: 'r.png', url: 'https://x/y.png' })
assert.strictEqual(got, 'data:image/png;base64,BBBB')
assert.strictEqual(fetched, 1)
})
ok('localCopySrcOf:有远程原图时不拿 320 缩略图顶替(画质优先)', async () => {
const s = Sync.create({
get: async () => null,
blobFromSrc: async () => ({ size: 9 }),
blobToDataUrl: async () => 'data:image/png;base64,FULL',
})
const got = await s.localCopySrcOf({ name: 'q.png', data: 'data:image/jpeg;base64,THUMB320', url: 'https://x/q.png' })
assert.strictEqual(got, 'data:image/png;base64,FULL', '应取远程原图,实际 ' + String(got).slice(0, 30))
})
ok('localCopySrcOf:全抓不到返回空串(调用方退回原链接,不丢图)', async () => {
const s = Sync.create({ get: async () => null, blobFromSrc: async () => null })
assert.strictEqual(await s.localCopySrcOf({ name: 'z.png', url: 'https://blocked/y.png' }), '')
})
// ③ 节点取图必须认 localRef
ok('nodeImageOf:remote 节点已缓存 localRef 时返回本地 dataUrl(不再给 url)', async () => {
const s = Sync.create({ refDataUrl: async (v) => (v && v.__blob === 'imgblob_x' ? 'data:image/png;base64,CC' : '') })
const node = { id: 'n1', data: { url: 'https://i.ibb.co/a.png', localRef: { __blob: 'imgblob_x' } } }
const got = await s.nodeImageOf(node)
// 跨 vm realm 的对象原型不同,deepStrictEqual 会因原型不等而红 ⇒ 按结构比
assert.strictEqual(JSON.stringify(got), JSON.stringify({ dataUrl: 'data:image/png;base64,CC' }))
})
ok('nodeImageOf:只有远程时按需抓字节并写回 localRef', async () => {
let written = null
const s = Sync.create({
refDataUrl: async () => '',
blobFromSrc: async () => ({ size: 1 }),
blobToDataUrl: async () => 'data:image/png;base64,DD',
})
const node = { id: 'n2', data: { url: 'https://i.ibb.co/b.png' } }
const got = await s.nodeImageOf(node, { writeRef: async (d) => ({ __blob: 'k' }), onLocalRef: (r) => { written = r } })
assert.strictEqual(JSON.stringify(got), JSON.stringify({ dataUrl: 'data:image/png;base64,DD' }))
assert.strictEqual(JSON.stringify(written), JSON.stringify({ __blob: 'k' }))
})
ok('nodeImageOf:抓不到时返回 { url }(宁可留链接也不返回空)', async () => {
const s = Sync.create({ refDataUrl: async () => '', blobFromSrc: async () => null })
const got = await s.nodeImageOf({ id: 'n3', data: { url: 'https://blocked/c.png' } })
assert.strictEqual(JSON.stringify(got), JSON.stringify({ url: 'https://blocked/c.png' }))
})
// ④ 插入准备 + 栅格
ok('prepareInsert:本地副本走压缩+引用化;抓不到的计入 remoteOnly 并保留原链接', async () => {
const s = Sync.create({ get: async (k) => (k === 'o1' ? 'data:image/png;base64,E' : null), blobFromSrc: async () => null })
const out = await s.prepareInsert(
[{ name: 'a.png', origIdb: 'o1', url: 'https://x/a.png' }, { name: 'b.png', url: 'https://x/b.png' }], '1k',
{ refSrcOf: async (v) => v, shrink: async (v) => v + '-1k', writeRef: async (v) => ({ __blob: 'k:' + v }) }
)
assert.strictEqual(out.items.length, 2)
assert.ok(out.items[0].src && out.items[0].src.__blob, '本地副本应被引用化')
assert.strictEqual(out.items[1].src, 'https://x/b.png', '抓不到时保留原链接')
assert.strictEqual(out.items[1].srcUrl, 'https://x/b.png', '原链接留痕')
assert.strictEqual(out.remoteOnly, 1)
})
ok('gridSpots:批量插入不重叠(旧实现全叠在一处)', () => {
const s = Sync.create({})
const spots = s.gridSpots({ x: 100, y: 200 }, 5, { stepX: 288, stepY: 276 })
assert.strictEqual(spots.length, 5)
const keys = new Set(spots.map((p) => p.x + ',' + p.y))
assert.strictEqual(keys.size, 5, '四个坐标必须互不相同')
assert.strictEqual(JSON.stringify(spots[4]), JSON.stringify({ x: 100, y: 200 + 276 }), '第 5 张换行回到第一列')
})
;(async () => {
let bad = 0
for (const c of checks) {
try { await c.fn(); console.log(' ✓ ' + c.name) } catch (e) { bad++; console.log(' ✗ ' + c.name + ' —— ' + ((e && e.message) || e)) }
}
console.log('gallery-sync checks: ' + (checks.length - bad) + ' 通过 / ' + bad + ' 失败')
if (bad) process.exit(1)
})()
+31 -1
View File
@@ -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/<id>/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) })
+9 -1
View File
@@ -149,7 +149,15 @@ const MAX_SRC_COMPONENT_LINES = 531
// ② 同时守「app.js 占总源码 ≤ 40%」(2026-11-12 实测 38.4%)—— app.js 可以涨,
// 但必须涨得比 src 慢;功能继续加,占比自然往下走;
// ③ Workbench 单函数上限**不动**(3,091)—— 那才是真坏味道的护栏,总量松它不松。
const MAX_APP_JS_LINES = 9095 // 2026-11-21 v3.26.18:小地图避让 install 调用(逻辑在 src/ui-minimap-fit.js)
// 2026-11-24(v3.26.61):9095 → **9114**。两笔:
// ① 图库/生成/画布三者的同步动作(单张归档串行队列、通知插件重拉、条目→本地字节、插入栅格、
// 节点取图、格子缩略图取源)全部落到新模块 src/gallery-sync.js(约 200 行),app.js 只剩
// `attach(...)` 装配 + commit 分发,净增 13 行 —— 这 13 行闭包组件内 refs/setSel/commitCanvas/
// updateNode,是「装配」本身,无法外移;新增模块后占比棘轮(app.js ≤ 40%)反而下降。
// ② 纠正过时的存储口径注释(用户要求:旧的不准确描述要改掉):图库/缩略图/原图档在桌面端是
// images/thumbs、images/gallery 文件,不是 IndexedDB;「1K 插入档降的是长边像素不是体积」。
// 共 6 行注释,属于事实纠错而非功能代码。
const MAX_APP_JS_LINES = 9115 // 2026-11-24 v3.26.61:图库同步边界抽到 src/gallery-sync.js + 纠错存储口径注释
const MAX_APP_JS_SHARE = 0.40
// ── 历史记账(供回溯,逐条保留)──────────────────────────────────────────────