Compare commits

...
7 Commits
Author SHA1 Message Date
qiqi 56a159486b docs(win): 固定本次 Windows 打包版本为 3.25.1 + 发布 3.25.1 mac 包(releases.json/下载页)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m49s
2026-11-17 15:43:02 +08:00
qiqi 4aa0e6affe docs(facts): 基线锚点同步到 3.25.1
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m34s
2026-11-17 15:38:41 +08:00
qiqi 3f2eb03fe3 chore(release): 3.25.1(性能与数据卫生优化) 2026-11-17 15:37:33 +08:00
qiqi 3bbf1ea85d perf(image): 图库清单去 base64(367KB→1.6KB,按 thumbHash 读文件)+ 画布显示缩略图 768px 落盘
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m36s
2026-11-17 15:36:20 +08:00
qiqi e9a6402373 chore(log): _boot.log 超过 256KB 只保留最后 64KB(窗口多屏恢复已有中心点校验,无需改)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 2m0s
2026-11-17 15:17:12 +08:00
qiqi ce575d2640 refactor(app): 插件加载/市场/备份抽成 src 模块(app.js 8880→8764 行);备份包含插件
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m31s
2026-11-17 15:14:46 +08:00
qiqi 0ec11bfca8 perf(storage): gcImages 递归子目录 + trash 30 天轮转(本机清出 20.2MB 未引用图片)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m58s
2026-11-17 15:08:23 +08:00
22 changed files with 564 additions and 172 deletions

No files matched your search

+28
View File
@@ -14,6 +14,34 @@
> 3. 核验正式地址版本 → 之后才移动 `stable` / `stable-verified-<日期>` 标签、更新本 CHANGELOG、写 GitHub Release(`gh release create`)。
> 测试发现问题 → 改 → 再 `deploy:test`,正式环境不受影响。回滚点 `git reset --hard stable`。
## v3.25.1(2026-11-17)性能与数据卫生:回收 20.2MB 垃圾图片 + 图库清单去 base64(223 倍)+ 备份含插件
> **状态:代码已合并** 分支 `main`。Windows 安装包基于本版本构建。
### 性能 / 体积
- **图库清单去 base64**:`library/gallery/index.json` 367,887 → **1,646 字节**(只留 `thumbHash`,缩略图按需从 `images/thumbs/` 读)。
- **画布显示缩略图落盘**:768px 派生结果写 `images/thumbs/<sha16>_768.jpg`,启动预读命中,省掉重复 4K 解码。
- **`gcImages` 递归子目录**:此前只扫 `images/` 根目录,`canvas/gallery/thumbs/legacy` 里的孤儿永远清不掉。本机首跑回收 **20.2 MB**(21 个无引用文件)。
- **`trash/` 30 天轮转**:清理只是移进 trash,现在超过 30 天自动删除。
### 数据卫生
- 清除 7 个坏画布文件(早期文件名少 2 字符的残留:`active.json` / `wsve.json` 等),画布 49 → 42(1341 节点完好)。
- `assets` ↔ 文件一致性校验:0 缺失。
### 备份 / 结构
- **备份包含插件**:导出带 `items.plugins`(清单 + 源码),恢复写回 `<资料目录>/plugins/` 并合并清单 —— 换机不再丢插件。
- **app.js 瘦身**:插件加载 / 市场 / 备份抽成 `src/runtime-plugin-loader.js`、`runtime-plugin-market.js`、`runtime-plugin-backup.js`。
- **`_boot.log` 轮转**:超过 256KB 只保留最后 64KB。
### 已验证
- `verify:ci` exit 0(658 通过 / 0 新增失败)
- 真实启动:5 个外部插件全部 `loaded`
- 图库 7/7 条目可解析到缩略图文件,清单 `data` 字段全空
## v3.25.0(2026-11-17)桌面版:应用不再内置插件 + 插件市场 + 页内确认(替代原生 confirm)
> **状态:✅ 已出 macOS 安装包(dmg)** 分支 `main`,bump 提交 `9d0e57c`。
+74 -145
View File
@@ -1654,7 +1654,7 @@
const RuntimeConstants = (typeof window !== 'undefined' && window.IWBRuntimeConstants) || { outputLimit: 10000, galleryRanges: {} }
const GalleryHydration = typeof window !== 'undefined' && window.IWBGalleryHydration
const galleryHydrator = GalleryHydration && typeof GalleryHydration.create === 'function'
? GalleryHydration.create({ get: (key) => IDB.get(key) })
? GalleryHydration.create({ get: (key) => IDB.get(key), thumb: (hash) => { const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null; return (F && typeof F.galleryThumb === 'function') ? F.galleryThumb(hash) : Promise.resolve('') } })
: null
const ModularOutputStore = typeof window !== 'undefined' && window.IWBStorageOutputs && ModularLocalStore && ModularIndexedStore
? window.IWBStorageOutputs.create({ local: ModularLocalStore, indexedDb: ModularIndexedStore, key: OUT_KEY, prefix: 'out_', limit: RuntimeConstants.outputLimit, hydrate: galleryHydrator && ((items) => galleryHydrator.hydrate(items)) })
@@ -4643,6 +4643,48 @@ const tbCenterSeed = (type, refs) => {
previewUrls.clear(); previewPending.clear()
}
// 显示缩略图落盘(768px):下次启动直接读文件,不用再解码原图
const DISPLAY_THUMB_HASH_MAX = 512
const displayThumbSaved = new Set()
function wStoreMod () {
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
return (F && typeof F.readDisplayThumb === 'function') ? F : null
}
function wSaveDisplayThumb (key, dataUrl) {
const F = wStoreMod()
if (!F || !key || !dataUrl) return
if (displayThumbSaved.has(key) || displayThumbSaved.size > 2000) return
displayThumbSaved.add(key)
wSha256(String(key)).then(function (hex) {
try { F.writeDisplayThumb(hex.slice(0, 16), dataUrl) } catch (e) { /* ignore */ }
}).catch(function () { /* ignore */ })
}
async function wPreloadDisplayThumbs (nodes) {
const F = wStoreMod()
if (!F || !Array.isArray(nodes) || !nodes.length) return 0
const keys = []
for (const n of nodes) {
const d = n && n.data
if (!d) continue
const v = wResolveImg(d.data) || d.url
if (!v || typeof v !== 'string' || v.indexOf('data:') === 0) continue
const key = wDisplayThumbKey(v)
if (!key || displayThumbs.has(key) || keys.indexOf(key) >= 0) continue
keys.push(key)
if (keys.length >= DISPLAY_THUMB_HASH_MAX) break
}
let n = 0
for (const key of keys) {
try {
const hex = await wSha256(String(key))
const dataUrl = await F.readDisplayThumb(hex.slice(0, 16))
if (dataUrl) { displayThumbs.set(key, dataUrl); displayThumbSaved.add(key); n++ }
} catch (e) { /* 单张失败忽略 */ }
}
if (n && typeof wThumbBump === 'function') { try { wThumbBump() } catch (e) { /* ignore */ } }
return n
}
function wDisplayThumbOf(v) {
// C3:结果项 / 图片节点的 data 可能是引用对象(hydrate 直出)→ 先解析成显示 URL
if (v && typeof v === 'object') v = wResolveImg(v)
@@ -4679,6 +4721,7 @@ const tbCenterSeed = (type, refs) => {
const small = cv.toDataURL('image/jpeg', 0.78)
if (displayThumbs.size >= DISPLAY_THUMB_CACHE_MAX) { const first = displayThumbs.keys().next().value; if (first !== undefined) displayThumbs.delete(first) }
wRememberThumb(small)
try { wSaveDisplayThumb(key, small) } catch (e) { /* ignore */ }
displayThumbPending.delete(key)
if (typeof wThumbBump === 'function') { try { wThumbBump() } catch (e) { /* ignore */ } }
} catch (e) { displayThumbPending.delete(key); wRememberThumb(v) } // 失败也记下:不再每次渲染重复解码整图
@@ -6173,6 +6216,8 @@ const tbCenterSeed = (type, refs) => {
refs.syncing = true // 切换/同步载入不触发自动保存(避免轮询-保存死循环)
setSel([]); setSelEdge(null)
openSession(id) // S3:先激活 session,再从它加载历史(session 化)
// 显示缩略图预热(768px 文件已存在就直接命中,省掉一次 4K 解码)
try { setTimeout(function () { wPreloadDisplayThumbs(ns).catch(function () { /* ignore */ }) }, 0) } catch (e) { /* ignore */ }
const sess = sessionsStore.get(id)
if (sess) { sess.nodes = ns; sess.edges = es; sess.groups = gs; sess.dirty = false } // S6:装载即同步 session 并清脏(装载不算本地编辑)
refs.history = (sess && sess.history) ? sess.history : { stack: [], idx: -1 } // S3:历史随 session(不再全局清空)
@@ -8458,156 +8503,40 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
// 插件自我注册。同源脚本本就被 CSP script-src 'self' 允许 ⇒ 不放宽 CSP、不重编译主包。
// 按需下载:启动只下载「已启用」的远程插件;未启用的记为 idle、不下载,等用户在插件管理里勾选时再加载。
// 单条远程插件的下载+激活(启动批量加载与按需加载共用):注入脚本(SRI 强制校验)→ 自我注册 → 持久化开关已开则激活。
async function wLoadPluginEntry(record) {
record.status = 'loading'
const integrity = record.integrity
try {
await new Promise((resolve, reject) => {
const script = document.createElement('script')
script.src = '/plugins/' + record.file
script.async = false
if (integrity) { script.integrity = integrity; script.crossOrigin = 'anonymous' }
script.onload = () => resolve()
script.onerror = () => reject(new Error(integrity ? '脚本完整性校验失败(integrity 不符或加载失败)' : '脚本加载失败'))
document.head.appendChild(script)
})
const registered = PluginHost && typeof PluginHost.list === 'function' && PluginHost.list().some((p) => p.id === record.id)
record.status = registered ? 'loaded' : 'not-registered'
if (registered && typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(record.id)) PluginHost.setEnabled(record.id, true)
return record.status === 'loaded'
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
// 加载实现已抽到 src/runtime-plugin-loader.js(app.js 只做装配)
function wPluginLoader () {
return (typeof window !== 'undefined') ? window.IWBRuntimePluginLoader : null
}
// 外部插件(P1):代码在 <资料目录>/plugins/ 下,不经 HTTP。
// 读文本 → 用 WebCrypto 校验清单里的 sha256 → 通过后才用 blob URL 注入(CSP 已放行 blob:)。
function wPluginSource() {
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
return (F && F.plugins && typeof F.plugins.read === 'function') ? F.plugins : null
function wPluginSource () {
const L = wPluginLoader()
return (L && typeof L.source === 'function') ? L.source() : null
}
async function wVerifyPluginCode(code, integrity) {
if (!integrity) return false
const expect = String(integrity).replace(/^sha256-/, '')
const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(code))
let bin = ''
const u8 = new Uint8Array(buf)
for (let i = 0; i < u8.length; i++) bin += String.fromCharCode(u8[i])
return btoa(bin) === expect
// 市场实现已抽到 src/runtime-plugin-market.js
function wMarketMod () {
return (typeof window !== 'undefined') ? window.IWBRuntimePluginMarket : null
}
async function wLoadExternalPluginEntry(record) {
record.status = 'loading'
const src = wPluginSource()
if (!src) { record.status = 'error'; record.error = '外部插件不可用'; return false }
try {
const code = await src.read(record.file)
if (record.integrity) {
const okHash = await wVerifyPluginCode(code, record.integrity)
if (!okHash) throw new Error('完整性校验失败(外部插件)')
}
const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }))
try {
await new Promise((resolve, reject) => {
const script = document.createElement('script')
script.src = url
script.async = false
script.onload = () => resolve()
script.onerror = () => reject(new Error('外部插件脚本执行失败'))
document.head.appendChild(script)
})
} finally { setTimeout(() => { try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000) }
const registered = PluginHost && typeof PluginHost.list === 'function' && PluginHost.list().some((p) => p.id === record.id)
record.status = registered ? 'loaded' : 'not-registered'
if (registered && typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(record.id)) PluginHost.setEnabled(record.id, true)
return record.status === 'loaded'
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
async function wMarketList () { const M = wMarketMod(); return M ? M.list() : [] }
async function wMarketInstalled () { const M = wMarketMod(); return M ? M.installed() : [] }
async function wMarketInstall (id) { const M = wMarketMod(); return M ? M.install(id) : { ok: false, error: '市场模块未就绪' } }
async function wMarketUninstall (id) { const M = wMarketMod(); return M ? M.uninstall(id) : { ok: false, error: '市场模块未就绪' } }
async function wVerifyPluginCode (code, integrity) {
const L = wPluginLoader()
return (L && typeof L.verifyCode === 'function') ? L.verifyCode(code, integrity) : false
}
// ---- 插件市场(P2):静态索引 market.maqiart.eu.org/index.json → 下载 → sha256 校验 → 写入 plugins/ ----
const W_MARKET_URL = 'https://market.maqiart.eu.org/index.json'
// 桌面端优先用 Tauri 的原生 HTTP(Rust 侧):WKWebView 在代理/fake-IP 环境下直连会 Load failed
function wMarketFetch(url) {
const T = (typeof window !== 'undefined' && window.__TAURI__ && window.__TAURI__.http) ? window.__TAURI__.http : null
if (T && typeof T.fetch === 'function') return T.fetch(url)
return fetch(url, { cache: 'no-store' })
async function wLoadPluginEntry (record) {
const L = wPluginLoader()
if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false }
return L.loadBuiltin(record)
}
async function wMarketList() {
const resp = await wMarketFetch(W_MARKET_URL)
if (!resp.ok) throw new Error('市场不可达:HTTP ' + resp.status)
const j = await resp.json()
return Array.isArray(j && j.plugins) ? j.plugins : []
async function wLoadExternalPluginEntry (record) {
const L = wPluginLoader()
if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false }
return L.loadExternal(record)
}
async function wMarketInstalled() {
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
if (!F || !F.plugins) return []
return await F.plugins.manifest()
}
async function wMarketInstall(id) {
try {
const list = await wMarketList()
const item = list.find((p) => p && p.id === id)
if (!item) return { ok: false, error: '市场里没有这个插件' }
const base = W_MARKET_URL.replace(/index\.json$/, '')
const resp = await wMarketFetch(base + item.file)
if (!resp.ok) throw new Error('下载失败:HTTP ' + resp.status)
const text = await resp.text()
const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
const hex = Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, '0')).join('')
if (item.sha256 && hex !== item.sha256) return { ok: false, error: '校验失败(sha256 不符)' }
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
if (!F || !F.plugins) return { ok: false, error: '外部插件目录不可用' }
const file = String(item.file).split('/').pop()
await F.plugins.write(file, text)
const cur = await F.plugins.manifest()
const next = cur.filter((p) => p && p.id !== id).concat([{ id: id, file: file, version: item.version, integrity: item.integrity }])
await F.plugins.write('index.json', JSON.stringify(next, null, 2) + '\n')
return { ok: true, restart: true, file: file }
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
}
async function wMarketUninstall(id) {
try {
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
if (!F || !F.plugins) return { ok: false, error: '外部插件目录不可用' }
const cur = await F.plugins.manifest()
const hit = cur.find((p) => p && p.id === id)
const next = cur.filter((p) => p && p.id !== id)
await F.plugins.write('index.json', JSON.stringify(next, null, 2) + '\n')
if (hit && hit.file) await F.plugins.remove(hit.file)
return { ok: true, restart: true }
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
}
// 开发者模式插件(plugins/local/<id>/plugin.js):未签名,仅在设置里打开开关时加载
async function wLoadLocalPluginEntry(record) {
record.status = 'loading'
try {
const code = String(record.code || '')
if (!code) throw new Error('插件源码为空')
const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }))
try {
await new Promise((resolve, reject) => {
const script = document.createElement('script')
script.src = url
script.async = false
script.onload = () => resolve()
script.onerror = () => reject(new Error('本地插件脚本执行失败'))
document.head.appendChild(script)
})
} finally { setTimeout(() => { try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000) }
const registered = PluginHost && typeof PluginHost.list === 'function' && PluginHost.list().some((p) => p.id === record.id)
record.status = registered ? 'loaded' : 'not-registered'
if (registered && typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(record.id)) PluginHost.setEnabled(record.id, true)
return record.status === 'loaded'
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
async function wLoadLocalPluginEntry (record) {
const L = wPluginLoader()
if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false }
return L.loadLocal(record)
}
// 按需加载(插件管理里勾选 idle 行):下载脚本 → 注册 → 显式启用;失败时返回错误供 UI 回滚勾选并提示。
+6
View File
@@ -1,5 +1,11 @@
# Windows 出包步骤(手把手)
> **本版要打的版本:3.25.1**(仓库里已经是这个号,直接构建,不要再改)
>
> 确认命令:node -e "console.log(require('./package.json').version)" → 应输出 3.25.1
>
> 产物名:image-workbench_3.25.1_x64-setup.exe / image-workbench_3.25.1_x64_en-US.msi
> 目标:在一台 Windows 机器上,从 Gitea 拉代码 → 打出安装包 → 自测 → 把产物回传到 NAS。
## 0. 前置检查
+3 -2
View File
@@ -51,10 +51,11 @@ npm ci
## 第三步:定版本号
先问我这次要发的版本号。若我未指定,用 **3.25.0**。
**本次版本已定:3.25.1**(仓库里 package.json / tauri.conf.json / Cargo.toml 都是这个号)。
不要自行改版本号;只有我明确要求时才用 `node scripts/set-version.js <新版本>`。
```powershell
node scripts/set-version.js 3.25.0
node -e "console.log(require('./package.json').version)" # 应输出 3.25.1
```
确认三处一致:
+5 -5
View File
@@ -1,7 +1,7 @@
# 现状架构与性能事实基线(image-workbench-web)
> **本文档是什么**:现状**事实快照**,不是规范。用途:任何性能 / 内存 / 存储相关改动,先对齐这里的现实,避免把已经调好的东西改坏。
> 日期 **2026-10-20**(**2026-11-16 复算 · v3.24.85**)| 基线(**最近一次 bump 版本的提交**,不是主干 HEAD)`main = 9d0e57c`(线上 `v3.25.0+9d0e57c` —— 线上实际运行提交是 docs 提交 `7df9dc4`,bump 提交为 `4be78c0`;2026-11-16 已发**测试站 + 正式站**,三地址一致 + `IWB_VERIFY_STRICT=1` 通过。v3.24.85 是「代码体检收口」(棘轮收回 Workbench 3090→2998 + 图库索引 4 条绕过锁的写路径收口到 `mutate` + 文档数字校准),`stable` / `stable-v3.24.85` / `stable-verified-2026-11-16` 均指向 `7df9dc4`。上一条 —— 2026-11-14 发**测试站 + 正式站** `https://test.image-workbench-web.pages.dev`:**v3.24.84 修「生图节点连了 3 条上游只出 1 个任务」**(任务 id 与去重基准改用新字段 `ownerNodeId`=本节点自己,不再用随继承冒泡的 `sourceNodeId` ⇒ 连几条线就几个任务;`relay` 仍归约到真实文本来源,同一来源多路径抵达只算一次)。上一条 v3.24.83:**修「插件节点冷启动退化成一段文本」**(插件节点体是异步注册的,`registerNodeType` 在 `render` 由无变有时自增 `NODE_TYPES_REV`,`NodeCard` 比它 ⇒ 注册那一刻重建一次;`canvas-normalize` 按命名规则把 `plugin:<id>:<variant>` 认作已知类型,不再降级成 `plugin` 并写回存档);配套插件 `style-source` 1.3.2 把节点体样式改为**脚本执行时注入**(此前只在面板 `mount()` 注入 ⇒ 从存档直接进画布时节点无样式、缩略图按原图铺满)。上一条 v3.24.82 同批:提示词/文本节点**显示上游继承文本**(自己 `data.text` 为空时把上游那段话显示在框里,改一个字即接管,另有「恢复跟随」清空回跟随;多路上游按 Y 轴取第一条)+ 修 `nodeRefsOf` 的 textout 分支只认 llm/batch/combine 上游导致「样式 → 文本 → 分层」丢参考图;再上一条 v3.24.81:① 插件节点可自定义节点体(`render(node, props, host)` 画真实 DOM,宿主不每帧重建 ⇒ 输入框不失焦);② 节点自带参考图(`data.refOn/refUrl` ⇒ 任务图里补伪参考图,坐标取节点自身 ⇒ 仍参与「图片按 X 轴排序」);③ 连线白名单按 `data.outKind === 'prompt'` 归一化,7 条规则一次放行,内置节点行为逐字不变。上一条 v3.24.80 = 离开页面的兜底保存不递增 rev(2026-11-14 07:20 补发 —— 首发 11-13 23:25 撞 Cloudflare Workers API 事故 `503 no healthy upstream`,期间正式站保持在 `v3.24.79+8598a57` 未动)。v3.24.83 的 bump 提交即 `0a27a42`(v3.24.82 为 `ef6cf42`、v3.24.81 为 `dba71e3`);主干 HEAD 会继续前进,见 [`RELEASES.md`](../RELEASES.md))| 历史分支 `refactor/architecture` / `feat/multi-canvas-tabs` / `refactor/state-store` 已于 2026-10-20 清理(内容均已并入 main,归档标签 `archive/*`),本文**计数类事实**已按 main HEAD 复算。
> 日期 **2026-10-20**(**2026-11-16 复算 · v3.24.85**)| 基线(**最近一次 bump 版本的提交**,不是主干 HEAD)`main = 3f2eb03`(线上 `v3.25.1+3f2eb03` —— 线上实际运行提交是 docs 提交 `7df9dc4`,bump 提交为 `4be78c0`;2026-11-16 已发**测试站 + 正式站**,三地址一致 + `IWB_VERIFY_STRICT=1` 通过。v3.24.85 是「代码体检收口」(棘轮收回 Workbench 3090→2998 + 图库索引 4 条绕过锁的写路径收口到 `mutate` + 文档数字校准),`stable` / `stable-v3.24.85` / `stable-verified-2026-11-16` 均指向 `7df9dc4`。上一条 —— 2026-11-14 发**测试站 + 正式站** `https://test.image-workbench-web.pages.dev`:**v3.24.84 修「生图节点连了 3 条上游只出 1 个任务」**(任务 id 与去重基准改用新字段 `ownerNodeId`=本节点自己,不再用随继承冒泡的 `sourceNodeId` ⇒ 连几条线就几个任务;`relay` 仍归约到真实文本来源,同一来源多路径抵达只算一次)。上一条 v3.24.83:**修「插件节点冷启动退化成一段文本」**(插件节点体是异步注册的,`registerNodeType` 在 `render` 由无变有时自增 `NODE_TYPES_REV`,`NodeCard` 比它 ⇒ 注册那一刻重建一次;`canvas-normalize` 按命名规则把 `plugin:<id>:<variant>` 认作已知类型,不再降级成 `plugin` 并写回存档);配套插件 `style-source` 1.3.2 把节点体样式改为**脚本执行时注入**(此前只在面板 `mount()` 注入 ⇒ 从存档直接进画布时节点无样式、缩略图按原图铺满)。上一条 v3.24.82 同批:提示词/文本节点**显示上游继承文本**(自己 `data.text` 为空时把上游那段话显示在框里,改一个字即接管,另有「恢复跟随」清空回跟随;多路上游按 Y 轴取第一条)+ 修 `nodeRefsOf` 的 textout 分支只认 llm/batch/combine 上游导致「样式 → 文本 → 分层」丢参考图;再上一条 v3.24.81:① 插件节点可自定义节点体(`render(node, props, host)` 画真实 DOM,宿主不每帧重建 ⇒ 输入框不失焦);② 节点自带参考图(`data.refOn/refUrl` ⇒ 任务图里补伪参考图,坐标取节点自身 ⇒ 仍参与「图片按 X 轴排序」);③ 连线白名单按 `data.outKind === 'prompt'` 归一化,7 条规则一次放行,内置节点行为逐字不变。上一条 v3.24.80 = 离开页面的兜底保存不递增 rev(2026-11-14 07:20 补发 —— 首发 11-13 23:25 撞 Cloudflare Workers API 事故 `503 no healthy upstream`,期间正式站保持在 `v3.24.79+8598a57` 未动)。v3.24.83 的 bump 提交即 `0a27a42`(v3.24.82 为 `ef6cf42`、v3.24.81 为 `dba71e3`);主干 HEAD 会继续前进,见 [`RELEASES.md`](../RELEASES.md))| 历史分支 `refactor/architecture` / `feat/multi-canvas-tabs` / `refactor/state-store` 已于 2026-10-20 清理(内容均已并入 main,归档标签 `archive/*`),本文**计数类事实**已按 main HEAD 复算。
<!-- 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`(现 **81** 个模块 / 14,607 行,`sourceModules` 81 项;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`(现 **84** 个模块 / 14,607 行,`sourceModules` 84 项;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` 不引用模块全局)。**81 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**84 个模块中 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 耦合面(**71** 项)与 `sourceModules` 顺序(**81** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**73** 项)与 `sourceModules` 顺序(**84** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
## 12. 易踩的坑
@@ -254,7 +254,7 @@
**信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**71** 项)与 `sourceModules` 顺序(**81** 项);新增模块、新增耦合、新增 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 耦合面」(**73** 项)与 `sourceModules` 顺序(**84** 项);新增模块、新增耦合、新增 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 规则三的同一失败模式)。
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "image-workbench-web",
"private": true,
"version": "3.25.0",
"version": "3.25.1",
"description": "Browser-based node canvas image workbench",
"scripts": {
"build": "node scripts/build.js && node scripts/copy-plugins.js",
+3
View File
@@ -97,6 +97,9 @@ const sourceModules = [
'workspace-list.js',
'workspace-purge.js',
'generation-provider-ping.js',
'runtime-plugin-loader.js',
'runtime-plugin-market.js',
'runtime-plugin-backup.js',
'ui-canvas-view.js',
'ui-confirm.js',
'ui-settings-sections.js',
+6 -2
View File
@@ -35,8 +35,8 @@
<h2>下载</h2>
<div class="row">
<div class="name">macOS · Apple Silicon<div class="hint">M1 / M2 / M3 / M4</div></div>
<div class="meta">版本 3.25.0 · 6.2 MB · .dmg<div class="hash">sha256 60d88875b86a4673…</div></div>
<a class="btn" href="/updates/darwin-aarch64/image-workbench_3.25.0_aarch64.dmg">下载</a>
<div class="meta">版本 3.25.1 · 6.2 MB · .dmg<div class="hash">sha256 5b711840b36a10ba…</div></div>
<a class="btn" href="/updates/darwin-aarch64/image-workbench_3.25.1_aarch64.dmg">下载</a>
</div>
<div class="row">
<div class="name">macOS · Intel<div class="hint">x86_64</div></div>
@@ -57,6 +57,10 @@
</div>
<h2>历史版本</h2>
<div class="row">
<div class="name">3.25.1<div class="hint">性能与数据卫生:图库清单去 base64(223 倍)、画布缩略图落盘、回收 20.2MB 垃圾图、备份含插件</div></div>
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon</div></div>
</div>
<div class="row">
<div class="name">3.25.0<div class="hint">应用不再内置插件(全部从市场安装);页内确认替代原生 confirm;插件市场与开发者模式</div></div>
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon</div></div>
+14 -1
View File
@@ -1,8 +1,21 @@
{
"app": "Image Workbench",
"subtitle": "本地优先的 AI 生图无限画布 · 桌面版(Tauri v2)",
"updatedAt": "2026-11-17T06:25:27.704Z",
"updatedAt": "2026-11-17T07:41:57.912Z",
"releases": [
{
"version": "3.25.1",
"date": "2026-11-17",
"notes": "性能与数据卫生:图库清单去 base64(223 倍)、画布缩略图落盘、回收 20.2MB 垃圾图、备份含插件",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.1_aarch64.dmg",
"size": 6545041,
"sha256": "5b711840b36a10ba2983ad48923c662897d25e55ea30de9fb7ea944694648124",
"kind": "dmg"
}
}
},
{
"version": "3.25.0",
"date": "2026-11-17",
+1 -1
View File
@@ -1666,7 +1666,7 @@ dependencies = [
[[package]]
name = "image-workbench"
version = "3.25.0"
version = "3.25.1"
dependencies = [
"log",
"serde",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "image-workbench"
version = "3.25.0"
version = "3.25.1"
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.25.0",
"version": "3.25.1",
"identifier": "com.malongan.imageworkbench",
"build": {
"frontendDist": "../dist",
+8 -1
View File
@@ -4,6 +4,8 @@
function createHydrator(options) {
const opt = options || {}
const get = typeof opt.get === 'function' ? opt.get : (() => Promise.resolve(null))
// 文件存储:清单只留 thumbHash,缩略图按需从 images/thumbs/ 读
const thumb = typeof opt.thumb === 'function' ? opt.thumb : null
let sequence = 0
let disposed = false
async function hydrate(items, requestId) {
@@ -11,7 +13,12 @@
if (id > sequence) sequence = id
const list = Array.isArray(items) ? items : []
const values = await Promise.all(list.map(async (item) => {
if (!item || !item.idb) return item
if (!item) return item
if (item.data) return item
if (thumb && item.thumbHash) {
try { const v = await thumb(item.thumbHash); if (v) return Object.assign({}, item, { data: v }) } catch (e) { /* 读文件失败退回 idb */ }
}
if (!item.idb) return item
try {
const value = await get(item.idb)
return value == null ? item : Object.assign({}, item, { data: value })
+52
View File
@@ -0,0 +1,52 @@
/* runtime-plugin-backup.js —— 插件进出备份
*
* 备份里带上插件清单与源码(体积很小),换机器恢复后不必重装。
* collect() → [{ id, version, file, integrity, code }]
* restore(v) → 写回 <资料目录>/plugins/ 并合并清单(备份里没有的插件保留)
*/
;(function (global) {
'use strict'
function store () {
const F = global.IWBStorageFile || null
return (F && F.plugins) ? F.plugins : null
}
async function collect () {
const s = store()
if (!s) return []
let list = []
try { list = await s.manifest() } catch (e) { return [] }
const out = []
for (const e of (Array.isArray(list) ? list : [])) {
if (!e || !e.id || !e.file) continue
try {
const text = await s.read(e.file)
out.push({ id: e.id, version: e.version || '', file: e.file, integrity: e.integrity || '', code: String(text || '') })
} catch (err) { /* 单个插件读失败不影响其它 */ }
}
return out
}
async function restore (list) {
const s = store()
if (!s || !Array.isArray(list) || !list.length) return 0
let cur = []
try { cur = await s.manifest() } catch (e) { cur = [] }
const byId = new Map((Array.isArray(cur) ? cur : []).map(function (e) { return [String(e && e.id), e] }))
let n = 0
for (const p of list) {
if (!p || !p.id || !p.file) continue
if (!/^[A-Za-z0-9._-]+$/.test(String(p.file))) continue
try {
await s.write(String(p.file), String(p.code || ''))
byId.set(String(p.id), { id: String(p.id), file: String(p.file), version: String(p.version || ''), integrity: String(p.integrity || '') })
n++
} catch (err) { /* 单个失败忽略 */ }
}
try { await s.write('index.json', JSON.stringify(Array.from(byId.values()))) } catch (e) { /* ignore */ }
return n
}
global.IWBRuntimePluginBackup = { collect: collect, restore: restore }
})(typeof window !== 'undefined' ? window : globalThis)
+120
View File
@@ -0,0 +1,120 @@
/* runtime-plugin-loader.js —— 插件脚本加载(内置 / 外部 / 本地开发)
*
* 从 app.js 抽出来:app.js 只做装配,加载细节在这里。
* 三个入口都返回 boolean,并把状态写回传进来的 record(status/error),供插件面板展示。
* · loadBuiltin :同源 /plugins/<file>,走 SRI(integrity 强制校验)
* · loadExternal :<资料目录>/plugins/<file>,先读文本 → WebCrypto 校验 sha256 → blob 注入
* · loadLocal :开发者模式,code 已在内存里(免签名),blob 注入
*/
;(function (global) {
'use strict'
function host () {
return global.IWBPluginHost || null
}
// 外部插件源(<资料目录>/plugins/ 的读写封装)
function source () {
const F = global.IWBStorageFile || null
return (F && F.plugins && typeof F.plugins.read === 'function') ? F.plugins : null
}
async function verifyCode (code, integrity) {
if (!integrity) return false
const expect = String(integrity).replace(/^sha256-/, '')
const buf = await global.crypto.subtle.digest('SHA-256', new global.TextEncoder().encode(code))
const u8 = new Uint8Array(buf)
let bin = ''
for (let i = 0; i < u8.length; i++) bin += String.fromCharCode(u8[i])
return global.btoa(bin) === expect
}
// 注入一段脚本并等它执行完(插件在加载期自我注册)
function inject (attrs) {
return new Promise(function (resolve, reject) {
const script = global.document.createElement('script')
script.src = attrs.src
script.async = false
if (attrs.integrity) { script.integrity = attrs.integrity; script.crossOrigin = 'anonymous' }
script.onload = function () { resolve() }
script.onerror = function () { reject(new Error(attrs.error || '脚本加载失败')) }
global.document.head.appendChild(script)
})
}
function markResult (record) {
const H = host()
const registered = !!(H && typeof H.list === 'function' && H.list().some(function (p) { return p.id === record.id }))
record.status = registered ? 'loaded' : 'not-registered'
if (registered && typeof H.isEnabled === 'function' && H.isEnabled(record.id)) H.setEnabled(record.id, true)
return record.status === 'loaded'
}
async function loadBuiltin (record) {
record.status = 'loading'
const integrity = record.integrity
try {
await inject({
src: '/plugins/' + record.file,
integrity: integrity,
error: integrity ? '脚本完整性校验失败(integrity 不符或加载失败)' : '脚本加载失败'
})
return markResult(record)
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
}
async function loadExternal (record) {
record.status = 'loading'
const src = source()
if (!src) { record.status = 'error'; record.error = '外部插件不可用'; return false }
try {
const code = await src.read(record.file)
if (record.integrity) {
const ok = await verifyCode(code, record.integrity)
if (!ok) throw new Error('完整性校验失败(外部插件)')
}
const url = global.URL.createObjectURL(new global.Blob([code], { type: 'text/javascript' }))
try {
await inject({ src: url, error: '外部插件脚本执行失败' })
} finally {
setTimeout(function () { try { global.URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000)
}
return markResult(record)
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
}
async function loadLocal (record) {
record.status = 'loading'
try {
const code = String(record.code || '')
if (!code) throw new Error('插件源码为空')
const url = global.URL.createObjectURL(new global.Blob([code], { type: 'text/javascript' }))
try {
await inject({ src: url, error: '本地插件脚本执行失败' })
} finally {
setTimeout(function () { try { global.URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000)
}
return markResult(record)
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
}
global.IWBRuntimePluginLoader = {
source: source,
verifyCode: verifyCode,
loadBuiltin: loadBuiltin,
loadExternal: loadExternal,
loadLocal: loadLocal
}
})(typeof window !== 'undefined' ? window : globalThis)
+73
View File
@@ -0,0 +1,73 @@
/* runtime-plugin-market.js —— 插件市场(下载 / 校验 / 安装 / 卸载)
*
* 索引:https://market.maqiart.eu.org/index.json,产物同域 plugin-<id>.<hash>.js
* 落点:<资料目录>/plugins/(清单 index.json + 插件文件)
* 校验:市场索引里的 sha256(hex)与下载文本比对,不符直接拒绝
*/
;(function (global) {
'use strict'
const MARKET_URL = 'https://market.maqiart.eu.org/index.json'
function store () {
const F = global.IWBStorageFile || null
return (F && F.plugins) ? F.plugins : null
}
// 桌面端优先走 Tauri 原生 HTTP(WKWebView 在代理/fake-IP 环境下 fetch 会 Load failed)
function marketFetch (url) {
const T = (global.__TAURI__ && global.__TAURI__.http) ? global.__TAURI__.http : null
if (T && typeof T.fetch === 'function') return T.fetch(url)
return global.fetch(url, { cache: 'no-store' })
}
async function list () {
const resp = await marketFetch(MARKET_URL)
if (!resp.ok) throw new Error('市场不可达:HTTP ' + resp.status)
const j = await resp.json()
return Array.isArray(j && j.plugins) ? j.plugins : []
}
async function installed () {
const s = store()
if (!s) return []
return await s.manifest()
}
async function install (id) {
try {
const items = await list()
const item = items.find(function (p) { return p && p.id === id })
if (!item) return { ok: false, error: '市场里没有这个插件' }
const base = MARKET_URL.replace(/index\.json$/, '')
const resp = await marketFetch(base + item.file)
if (!resp.ok) throw new Error('下载失败:HTTP ' + resp.status)
const text = await resp.text()
const buf = await global.crypto.subtle.digest('SHA-256', new global.TextEncoder().encode(text))
const hex = Array.from(new Uint8Array(buf)).map(function (b) { return b.toString(16).padStart(2, '0') }).join('')
if (item.sha256 && hex !== item.sha256) return { ok: false, error: '校验失败(sha256 不符)' }
const s = store()
if (!s) return { ok: false, error: '外部插件目录不可用' }
const file = String(item.file).split('/').pop()
await s.write(file, text)
const cur = await s.manifest()
const next = cur.filter(function (p) { return p && p.id !== id }).concat([{ id: id, file: file, version: item.version, integrity: item.integrity }])
await s.write('index.json', JSON.stringify(next, null, 2) + '\n')
return { ok: true, restart: true, file: file }
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
}
async function uninstall (id) {
try {
const s = store()
if (!s) return { ok: false, error: '外部插件目录不可用' }
const cur = await s.manifest()
const hit = cur.find(function (p) { return p && p.id === id })
const next = cur.filter(function (p) { return p && p.id !== id })
await s.write('index.json', JSON.stringify(next, null, 2) + '\n')
if (hit && hit.file) await s.remove(hit.file)
return { ok: true, restart: true }
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
}
global.IWBRuntimePluginMarket = { list: list, installed: installed, install: install, uninstall: uninstall }
})(typeof window !== 'undefined' ? window : globalThis)
+151 -11
View File
@@ -324,8 +324,11 @@
try {
const u8 = await fs().readFile(await join(dir, a.f))
if (!u8 || u8.length > 96 * 1024) continue
it.data = bytesToDataUrl(a.m || 'image/jpeg', u8)
it.thumbHash = String(a.f).split('/').pop().replace(/\.[^.]+$/, '')
const hash = String(a.f).split('/').pop().replace(/\.[^.]+$/, '')
const thumbPath = await join(dir, IMG_DIR, 'thumbs', hash + '.jpg')
try { if (!(await fs().exists(thumbPath))) await fs().writeFile(thumbPath, u8) } catch (e) { /* 写失败不阻塞 */ }
it.thumbHash = hash
it.data = ''
n++
} catch (e) { /* 单张失败忽略 */ }
}
@@ -494,7 +497,23 @@
}
// 一次性迁移:把老版本存在 IndexedDB 里的图片字节搬到 images/ 下(跑过一次就写标记文件)
const blog = async (m) => { try { await fs().writeTextFile(await join(dir, '_boot.log'), new Date().toISOString() + ' ' + m + '\n', { append: true }) } catch (e) { /* ignore */ } }
// 启动日志:超过 256KB 只保留最后 64KB(否则长年累月会一直长)
const blog = async (m) => {
try {
const logPath = await join(dir, '_boot.log')
let tail = ''
try {
const st = await fs().stat(logPath)
if (st && st.size > 262144) {
const txt = await fs().readTextFile(logPath)
tail = txt.slice(-65536)
}
} catch (e) { /* 文件不存在就是首次 */ }
const line = new Date().toISOString() + ' ' + m + '\n'
if (tail) await fs().writeTextFile(logPath, tail + line)
else await fs().writeTextFile(logPath, line, { append: true })
} catch (e) { /* ignore */ }
}
async function migrateBlobs() {
try {
await blog('migrate:start dir=' + dir)
@@ -626,6 +645,10 @@
try { await migrateBlobs() } catch (e) { /* 迁移失败不阻塞启动 */ }
// 图库清单补齐缩略图(一次性)
try { await backfillGalleryThumbs() } catch (e) { /* 忽略 */ }
// 图库清单去 base64(一次性):缩略图已在 images/thumbs/,清单只留 thumbHash
try { await stripInlineGalleryThumbs() } catch (e) { /* 忽略 */ }
// trash/ 轮转:gcImages 只是移进来,超过 30 天在这里真正删除
try { await rotateTrash(30) } catch (e) { /* 忽略 */ }
// 自愈:图库清单丢了但 assets 还有 out_ 键 ⇒ 按键重建(名称/时间/idb 可推,label/远程 url 无法恢复)
try {
if (mem['iwb_web_outputs'] === undefined) {
@@ -677,31 +700,148 @@
// 清理未引用图片:只动「没有任何 assets 条目指向」的文件,移到 trash/(不直接删)。
// 保守策略:assets 里还有登记的键一律保留,避免误删仍在画布上引用的图。
// trash/ 轮转:超过 maxAgeDays 的文件直接删除(gcImages 只是移进来,不清)
async function rotateTrash(maxAgeDays) {
const days = Number(maxAgeDays) > 0 ? Number(maxAgeDays) : 30
try {
if (!enabled() || !dir) return 0
const trashAbs = await join(dir, 'trash')
const cutoff = Date.now() - days * 86400000
let removed = 0
const walk = async (abs, depth) => {
if (depth > 3) return
let entries = []
try { entries = await fs().readDir(abs) } catch (e) { return }
for (const e of entries) {
if (!e) continue
const child = await join(abs, e.name)
if (e.isDirectory) { await walk(child, depth + 1); continue }
try {
const st = await fs().stat(child)
const mt = st && st.mtime ? new Date(st.mtime).getTime() : 0
if (mt && mt < cutoff) { await fs().remove(child); removed++ }
} catch (err) { /* 单条失败忽略 */ }
}
}
await walk(trashAbs, 0)
return removed
} catch (e) { return 0 }
}
// 图库缩略图:清单里只存 thumbHash,渲染时按需从 images/thumbs/ 读(避免 base64 撑爆 index.json)
let thumbMapCache = null
async function thumbFileMap() {
if (thumbMapCache) return thumbMapCache
const map = {}
try {
const abs = await join(dir, IMG_DIR, 'thumbs')
const entries = await fs().readDir(abs)
for (const e of entries) {
if (!e || e.isDirectory) continue
const base = String(e.name).replace(/\.[^.]+$/, '')
if (!map[base]) map[base] = String(e.name)
}
} catch (e) { /* 没有 thumbs 目录就返回空表 */ }
thumbMapCache = map
return map
}
async function galleryThumb(hash) {
try {
if (!enabled() || !dir || !hash) return ''
const map = await thumbFileMap()
const name = map[String(hash)]
if (!name) return ''
const u8 = await fs().readFile(await join(dir, IMG_DIR, 'thumbs', name))
if (!u8 || !u8.length) return ''
const mime = /\.png$/i.test(name) ? 'image/png' : 'image/jpeg'
return bytesToDataUrl(mime, u8)
} catch (e) { return '' }
}
// 画布显示缩略图(768px)落盘:重启后直接命中,不用重新解码 4K 原图
async function readDisplayThumb(hash) {
try {
if (!enabled() || !dir || !hash) return ''
const abs = await join(dir, IMG_DIR, 'thumbs', String(hash) + '_768.jpg')
if (!(await fs().exists(abs))) return ''
const u8 = await fs().readFile(abs)
if (!u8 || !u8.length) return ''
return bytesToDataUrl('image/jpeg', u8)
} catch (e) { return '' }
}
async function writeDisplayThumb(hash, dataUrl) {
try {
if (!enabled() || !dir || !hash || !dataUrl) return false
const m = /^data:[^;]+;base64,(.*)$/.exec(String(dataUrl))
if (!m) return false
const bin = atob(m[1])
const u8 = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i)
const abs = await join(dir, IMG_DIR, 'thumbs', String(hash) + '_768.jpg')
if (await fs().exists(abs)) return true
await fs().mkdir(await join(dir, IMG_DIR, 'thumbs'), { recursive: true })
await fs().writeFile(abs, u8)
return true
} catch (e) { return false }
}
// 一次性:图库清单里历史遗留的 base64 data 删掉(缩略图已在 images/thumbs/)
async function stripInlineGalleryThumbs() {
try {
const marker = await join(dir, 'gallery-data-stripped.flag')
if (await fs().exists(marker)) return 0
const raw = mem['iwb_web_outputs']
if (!raw) { await fs().writeTextFile(marker, '0'); return 0 }
const items = JSON.parse(raw)
if (!Array.isArray(items)) return 0
const map = await thumbFileMap()
let n = 0
for (const it of items) {
if (!it || !it.data) continue
if (it.thumbHash && map[String(it.thumbHash)]) { it.data = ''; n++ }
}
if (n) { mem['iwb_web_outputs'] = JSON.stringify(items); await flush() }
await fs().writeTextFile(marker, String(n))
return n
} catch (e) { return 0 }
}
async function gcImages(opts) {
const dryRun = !!(opts && opts.dryRun)
try {
if (!enabled() || !dir) return { ok: false, error: '资料目录未就绪' }
const used = new Set(Object.keys(assets).map((k) => assets[k] && assets[k].f).filter(Boolean))
const imgAbs = await join(dir, IMG_DIR)
const entries = await fs().readDir(imgAbs)
// 子目录也要扫:images/{canvas,gallery,thumbs,legacy}/ 里的孤儿同样占空间
const subs = ['', 'canvas', 'gallery', 'thumbs', 'legacy']
const orphans = []
for (const e of entries) {
if (!e || e.isDirectory) continue
if (!used.has(IMG_DIR + '/' + e.name)) orphans.push(e.name)
for (const sub of subs) {
const abs = sub ? await join(imgAbs, sub) : imgAbs
let entries = []
try { entries = await fs().readDir(abs) } catch (e) { continue }
for (const e of entries) {
if (!e || e.isDirectory) continue
const rel = IMG_DIR + '/' + (sub ? sub + '/' : '') + e.name
if (!used.has(rel)) orphans.push({ sub: sub, name: e.name, rel: rel })
}
}
if (dryRun || !orphans.length) return { ok: true, orphans: orphans.length, moved: 0, dryRun: dryRun }
const trashAbs = await join(dir, 'trash')
try { await fs().mkdir(trashAbs, { recursive: true }) } catch (e) { /* 已存在 */ }
let moved = 0
for (const name of orphans) {
try { await fs().rename(await join(imgAbs, name), await join(trashAbs, name)); moved++ } catch (e) { /* 单条失败忽略 */ }
for (const item of orphans) {
try {
const targetDir = item.sub ? await join(trashAbs, item.sub) : trashAbs
await fs().mkdir(targetDir, { recursive: true })
await fs().rename(await join(imgAbs, item.sub, item.name), await join(targetDir, item.name))
moved++
} catch (e) { /* 单条失败忽略 */ }
}
return { ok: true, orphans: orphans.length, moved: moved, dryRun: dryRun }
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
}
global.IWBStorageFile = {
enabled, ready: init, flush, runtime, pickDir, switchTo, migrateTo, gcImages,
enabled, ready: init, flush, runtime, pickDir, switchTo, migrateTo, gcImages, rotateTrash, galleryThumb, readDisplayThumb, writeDisplayThumb,
plugins: { manifest: pluginManifest, read: pluginRead, write: pluginWrite, remove: pluginRemove, dir: pluginDir, listLocal: pluginListLocal },
storage: () => storage,
kv: () => kv,
+5
View File
@@ -169,6 +169,8 @@ function BackupModal(props) {
items.outputs = ((r && r.files) || []).map((f) => { const o = Object.assign({}, f); delete o.data; return o })
}))
await Promise.all(jobs)
// 插件(清单 + 源码)随备份走:换机器恢复后不用重装
try { const pb = (typeof window !== 'undefined') ? window.IWBRuntimePluginBackup : null; if (pb && pb.collect) { const ps = await pb.collect(); if (ps && ps.length) items.plugins = ps } } catch (e) { /* 插件快照失败不影响主备份 */ }
// 收集图片(画布引用大图 + 勾选的图库缩略图/原图)并读取数据
const refMeta = await collectBackupImages()
const galleryMeta = (bk.outputs && items.outputs) ? (await collectBackupOutputImages(items.outputs)) : []
@@ -364,6 +366,9 @@ function BackupModal(props) {
jobs.push(api('workspaces', { workspaces: mergeById((cur && cur.workspaces) || [], items.workspaces.workspaces || []), activeId: (cur && cur.activeId) || '' }))
} else jobs.push(api('workspaces', { workspaces: items.workspaces.workspaces || [], activeId: items.workspaces.activeId || '' }))
}
if (items.plugins && items.plugins.length) {
try { const pb = (typeof window !== 'undefined') ? window.IWBRuntimePluginBackup : null; if (pb && pb.restore) await pb.restore(items.plugins) } catch (e) { /* 插件还原失败不阻塞其它项 */ }
}
if (restoreSel.outputs && items.outputs) {
if (restoreMerge) {
const cur = await api('outputs').catch(() => ({ files: [] }))
+2
View File
@@ -35,6 +35,8 @@
"IWBRuntimeLifecycle",
"IWBRuntimeLifecycleFactory",
"IWBRuntimeMetrics",
"IWBRuntimePluginLoader",
"IWBRuntimePluginMarket",
"IWBRuntimeRecord",
"IWBRuntimeRecovery",
"IWBRuntimeRunContext",
+3
View File
@@ -69,6 +69,9 @@
"workspace-list.js",
"workspace-purge.js",
"generation-provider-ping.js",
"runtime-plugin-loader.js",
"runtime-plugin-market.js",
"runtime-plugin-backup.js",
"ui-canvas-view.js",
"ui-confirm.js",
"ui-settings-sections.js",
+3 -1
View File
@@ -86,7 +86,9 @@ const root = path.resolve(__dirname, '..')
// app.js loader:integrity 存在则交给浏览器强制校验;格式不合法即拒;**缺失即拒(fail-closed)**
const appJs = fs.readFileSync(path.join(root, 'app.js'), 'utf8')
assert.ok(/script\.integrity = integrity; script\.crossOrigin = 'anonymous'/.test(appJs), 'loader 应把 integrity 交给浏览器强制校验')
// 2026-11-17:加载器已抽到 src/runtime-plugin-loader.js,断言改读该模块(不是删断言)
const loaderSrc = require('fs').readFileSync(require('path').resolve(__dirname, '..', 'src', 'runtime-plugin-loader.js'), 'utf8')
assert.ok(/script\.integrity = attrs\.integrity; script\.crossOrigin = 'anonymous'/.test(loaderSrc), 'loader 应把 integrity 交给浏览器强制校验')
assert.ok(/record\.status = 'bad-entry'; record\.error = 'integrity 格式不合法'/.test(appJs), 'integrity 格式不合法应拒绝加载')
// 2026-11-17:本地开发插件(source=local)免 integrity,其余(市场/内置)仍然 fail-closed
assert.ok(/if \(!integrity && !isLocalEntry\) \{ record\.status = 'bad-entry'; record\.error = 'integrity 缺失(拒绝加载)'; continue \}/.test(appJs), '缺失 integrity 应拒绝加载(fail-closed,本地开发插件除外)')
+4
View File
@@ -25,6 +25,10 @@ interface Window {
__TAURI__?: any
__IWB_UPDATE__?: any
IWBUIConfirm?: any
IWBPluginBackup?: any
IWBRuntimePluginLoader?: any
IWBRuntimePluginMarket?: any
IWBRuntimePluginBackup?: any
IWBDesktop?: any
IWBStorageFallbackIndexedDb?: any
// 画布 / 工作台