diff --git a/CHANGELOG.md b/CHANGELOG.md index e6d10e6..041629a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,32 @@ > 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) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9f41ba4..8ed5763 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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) diff --git a/app.js b/app.js index ee100cb..55b084f 100644 --- a/app.js +++ b/app.js @@ -840,7 +840,9 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct // ==== 丙方案 C3:图片引用直出(hydrate 不再把图片字节读回 base64 常驻 JS 堆)==== // 画布记录里只留引用,字节独立存放(对标 opentu 的资产模型:记录 = 引用 + 元数据): // · { __cache: '/__iwb_cache__/' } —— 方案A 既有形态;字节在 Cache Storage,sw.js 可直出虚拟路径 - // · { __blob: 'imgblob__' } —— C3 新形态;字节在 IndexedDB 的 Blob(src/image-blob-store.js) + // · { __blob: 'imgblob__' } —— C3 新形态;字节落在**注入的 idb 后端**(src/image-blob-store.js): + // 浏览器 = IndexedDB;桌面端 = storage-file 的文件 KV(见 wImageBlobStore 的 storageRuntime 注入)⇒ + // 实际是 images/canvas/. + 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(原分辨率, 不受 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) @@ -5757,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:<插件>:<变体> @@ -5818,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) @@ -6387,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) @@ -7490,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]) @@ -7523,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) @@ -8253,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 = [] diff --git a/docs/plans/gallery-insert-perf-v324.md b/docs/plans/gallery-insert-perf-v324.md index 93c788a..e889938 100644 --- a/docs/plans/gallery-insert-perf-v324.md +++ b/docs/plans/gallery-insert-perf-v324.md @@ -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`。 +> 本文的**结论**(插入只记引用、别把整图塞进画布数据)仍然有效,**存储位置描述已过时**。 --- diff --git a/docs/standards/architecture-current-state.md b/docs/standards/architecture-current-state.md index 6116946..af81857 100644 --- a/docs/standards/architecture-current-state.md +++ b/docs/standards/architecture-current-state.md @@ -22,7 +22,7 @@ - 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob__`** (A) `app.js:2143`;`{__cache}`(Cache Storage)为兜底;\`ref_\`(`app.js` 内定义的 `IDB_REF_PREFIX = 'ref_'`)为 legacy 形态 (A)。 - 大图判定:`isBigDataUrl` = `data:` 且 `length > 3000` (A) `app.js:2018`;**画布保存保留阈值** `< 16384` 才原样保留 (A) `app.js:2182`。**两处阈值并存,含义不同**。 - 单测是**源码契约测试**:`tests/` 目录共 **493** 处源码文本钉点(`source.includes` / `source.indexOf` / `/re/.test(source)`),分布在 **20** 个文件(其中 `iwb-v32-web-test.js` 一个就占 **407**)→ **结构性重构会先打红测试**。**该数字已由 `tests/source-text-ratchet-test.js` 的「只减不增」棘轮守门**(2026-10-20 起守卫范围从 1 个文件扩到全目录:新增任何一处源码文本钉点都会打红)。**2026-11-12 复算**(`npm run audit:pins`,v3.24.76):二分 STRUCT **417** / NAME **76**;形态 **POS 403 / NEG 87 / COUNT 3**;难度 **易 62 / 中 316 / 难 115**。钉点减法第一批(v3.24.72)把 **537 → 505**:8 条探针钉点改为「门禁内 spec 是否真的读该计数器」、5 条改为运行时断言(生产态 `window` 上无探针)、10 条改为 DOM 断言(质量档位禁用 / 传输页无三模式按钮 / 模型项 title)、4 条改为运行时对象断言(健康检查两域、策略对象冻结)、其余 9 条有同文件 DOM 等价断言或仅剩 NEG。第二批(v3.24.76)把 **505 → 493**:94-5~7 三条「多标签释放语义」(10 处正则)换成 `tests/iwb-tabs-release.spec.js` 的 3 条真 e2e,剩 1 条「消费方契约」(断言该 spec 在门禁内且 spec 源码真的读两个探针);另 2 条 `wPurgeIntent.add` 钉点改为读 `src/workspace-purge.js`。**这一批一换就查出 3 个真缺陷**(objectURL 从未释放 / 彻底删除留孤儿标签 · session / 刷新后误回收打开标签的图)—— 见 CHANGELOG v3.24.76。 -- `app.js` = 单 IIFE **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 规则三的同一失败模式)。 diff --git a/docs/standards/image-storage-map.md b/docs/standards/image-storage-map.md new file mode 100644 index 0000000..60142df --- /dev/null +++ b/docs/standards/image-storage-map.md @@ -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/.` + `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` 是**唯一登记表**:`{ "": { 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,确认目录与登记仍然成对。 diff --git a/package.json b/package.json index d4d9416..acaa090 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "image-workbench-web", "private": true, - "version": "3.26.60", + "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", diff --git a/plugins/gallery/main.js b/plugins/gallery/main.js index 3980d51..84980b4 100644 --- a/plugins/gallery/main.js +++ b/plugins/gallery/main.js @@ -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 }, diff --git a/plugins/gallery/manifest.json b/plugins/gallery/manifest.json index 4d8d201..e06c681 100644 --- a/plugins/gallery/manifest.json +++ b/plugins/gallery/manifest.json @@ -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" } } diff --git a/plugins/index.json b/plugins/index.json index ab82da0..0c3d675 100644 --- a/plugins/index.json +++ b/plugins/index.json @@ -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" } }, diff --git a/scripts/audit-image-storage.js b/scripts/audit-image-storage.js new file mode 100644 index 0000000..18b85cc --- /dev/null +++ b/scripts/audit-image-storage.js @@ -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 回收,或由用户手动清理)') diff --git a/scripts/build.js b/scripts/build.js index ce732aa..ce6ea76 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -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', diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index ad776f1..f0e70a1 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "image-workbench" -version = "3.26.60" +version = "3.26.61" description = "无限画布 · 生图工作台桌面版" authors = ["malongan"] license = "" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index a16fb7e..2ae4dcd 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "image-workbench", - "version": "3.26.60", + "version": "3.26.61", "identifier": "com.malongan.imageworkbench", "build": { "frontendDist": "../dist", diff --git a/src/gallery-sync.js b/src/gallery-sync.js new file mode 100644 index 0000000..5630124 --- /dev/null +++ b/src/gallery-sync.js @@ -0,0 +1,181 @@ +/* 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 + } + + // 图库条目 → 本地字节。顺序:原图文件 → 清单里已 hydrate 的 data → 缩略图 → + // 按需抓一次远程(桌面端走 Rust 侧请求,不受 CORS)→ ''(交给调用方退回原链接) + async function localCopySrcOf (item) { + if (!item) return '' + try { + if (item.origIdb && typeof d.get === 'function') { + const v = await d.get(item.origIdb).catch(() => null) + if (v) return v + } + 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 + } + const url = String(item.url || '') + if (/^https?:/i.test(url)) { + let blob = null + if (typeof d.isDesktop === 'function' && d.isDesktop() && typeof d.desktopFetch === 'function') { + try { const r = await d.desktopFetch(url); if (r && r.ok) blob = await r.blob() } catch (e) { /* 落到 WebView fetch */ } + } + if (!blob && typeof d.blobFromSrc === 'function') blob = await d.blobFromSrc(url).catch(() => null) + const du = (blob && typeof d.blobToDataUrl === 'function') ? await d.blobToDataUrl(blob) : '' + if (du) return du + } + 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) diff --git a/src/image-blob-store.js b/src/image-blob-store.js index 9963463..177a647 100644 --- a/src/image-blob-store.js +++ b/src/image-blob-store.js @@ -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/. + * (本文件不认识"文件",只认识 put/get/del;任何"字节在 IndexedDB"的结论都要先看调用方注入了谁) * - 记录里只放引用对象 { __blob: 'imgblob__' } * - 渲染/导出时按需 resolve(dataURL 或 Blob),用完不驻留 * - 内存 Blob 缓存为**有界 LRU**(create({ blobCacheMax }),缺省 200):淘汰只丢句柄,getBlob 会回 IDB 重读; diff --git a/src/image-remote-cache.js b/src/image-remote-cache.js index 3de5fa9..9abd02f 100644 --- a/src/image-remote-cache.js +++ b/src/image-remote-cache.js @@ -4,6 +4,9 @@ * 做法:空闲时下载一次,写入本地引用存储,节点上只记 data.localRef(显示用)。 * * 约束(用户裁定):节点 data.url 保持原样 ⇒ **提交生成时仍然用链接**。 + * 谁在读 localRef(v3.26.61 修正):插件取图走 canvasBridge.getNodeImage,它的候选列表里必须有 + * localRef —— 早先漏了它,于是缓存明明命中,标注插件仍只看到 data.url 的 http 链接, + * 直接判「远程图片不支持标注」(用户报障的直接成因)。改这个字段的写入时机/格式前先看那里。 */ ;(function (global) { 'use strict' diff --git a/src/plugin-api-gallery.js b/src/plugin-api-gallery.js index 154a5eb..d87ca0c 100644 --- a/src/plugin-api-gallery.js +++ b/src/plugin-api-gallery.js @@ -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) \ No newline at end of file + global.IWBPluginGallery = { setImpl: setImpl, api: function () { return API }, query: query, emit: emit } +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/src/runtime-workbench-logic.js b/src/runtime-workbench-logic.js index 398b593..50def8b 100644 --- a/src/runtime-workbench-logic.js +++ b/src/runtime-workbench-logic.js @@ -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 } diff --git a/tests/architecture-boundary-guard-test.js b/tests/architecture-boundary-guard-test.js index acb411b..d7d9e83 100644 --- a/tests/architecture-boundary-guard-test.js +++ b/tests/architecture-boundary-guard-test.js @@ -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), '') diff --git a/tests/fixtures/iwb-app-global-reads.json b/tests/fixtures/iwb-app-global-reads.json index 0adbfd8..a683126 100644 --- a/tests/fixtures/iwb-app-global-reads.json +++ b/tests/fixtures/iwb-app-global-reads.json @@ -13,6 +13,7 @@ "IWBDesktopHelpers", "IWBDockArea", "IWBGalleryHydration", + "IWBGallerySync", "IWBGenerationRequestShape", "IWBGenerationResults", "IWBGenerationScheduler", diff --git a/tests/fixtures/iwb-source-modules-order.json b/tests/fixtures/iwb-source-modules-order.json index c600c93..3f66b4d 100644 --- a/tests/fixtures/iwb-source-modules-order.json +++ b/tests/fixtures/iwb-source-modules-order.json @@ -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", diff --git a/tests/gallery-sync-test.js b/tests/gallery-sync-test.js new file mode 100644 index 0000000..497c859 --- /dev/null +++ b/tests/gallery-sync-test.js @@ -0,0 +1,151 @@ +'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:全抓不到返回空串(调用方退回原链接,不丢图)', 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) +})() diff --git a/tests/source-text-ratchet-test.js b/tests/source-text-ratchet-test.js index a4b4a0c..c204b71 100644 --- a/tests/source-text-ratchet-test.js +++ b/tests/source-text-ratchet-test.js @@ -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 // ── 历史记账(供回溯,逐条保留)──────────────────────────────────────────────