Files
image-workbench-desktop/app.js
T

8720 lines
612 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 生图工作台 Image Workbench — 独立版前端
* 依赖: vendor/react + vendor/react-dom(离线 UMD)
* 后端 API: /api/config /api/generate /api/graph /api/prompts /api/outputs
*/
(async function () {
'use strict'
// 桌面端:启动时先把「资料目录」读进内存(异步),之后所有同步存储调用都走内存 + 异步落盘。
// 网页版没有 IWBStorageFile ⇒ 这段整体跳过,行为与原来完全一致。
try {
if (typeof window !== 'undefined' && window.IWBStorageFile && window.IWBStorageFile.enabled()) {
await window.IWBStorageFile.ready()
}
} catch (e) { console.error('[iwb][file-store] 启动装载失败,回退浏览器存储', e) }
// v3.26.18:小地图与底部工具栏避让(右栏挤压时自动隐藏,实现在 src/ui-minimap-fit.js)
try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'function') window.IWBMiniMapFit.install() } catch (e) { /* ignore */ }
const el = React.createElement
const { useState, useEffect, useLayoutEffect, useRef } = React
// 生成结果精简/合并模块(src/generation-results-store.js)。⚠️ 必须在 IIFE 最顶部取:
// 页面加载时就会跑一次保存,声明若在后面会命中 TDZ(异常被 catch 吞掉 ⇒ 落盘退回未精简的 result)。
const GenerationResults = (typeof window !== 'undefined' && window.IWBGenerationResults) || null
// 本地文件引用(2026-11-26 相册):{__file:'/abs/a.png'} 只存路径,按需读盘
// 本地文件引用模块:经 `window.__W_FILE_REF__()` 惰性取用(模块在 src/,加载完成即有值)。
const wFileRefMod = () => {
if (typeof window === 'undefined') return null
if (typeof window.__W_FILE_REF__ !== 'function') {
try { window.__W_FILE_REF__ = () => window.IWBImageFileRef || null } catch (e) { return null }
}
return window.__W_FILE_REF__()
}
// ========== 桌面端(Tauri v2)适配层 ==========
// 仅在 Tauri 内生效:网页版没有 window.__TAURI__ ⇒ 所有分支都走原逻辑,行为零变化。
// 用 withGlobalTauri 注入的官方 API(无需打包器),权限仍由 src-tauri/capabilities 约束。
const wTauri = (typeof window !== 'undefined' && window.__TAURI__) ? window.__TAURI__ : null
const wIsTauri = () => !!(wTauri && wTauri.core)
// ── 默认下载文件夹(桌面端专属设置,存本地;网页版没有这个概念)─────────────
const wDownloadDir = () => {
try { const v = lsGet('iwb.downloadDir', ''); return typeof v === 'string' ? v : '' } catch (e) { return '' }
}
const wSetDownloadDir = (dir) => { try { lsSet('iwb.downloadDir', String(dir || '')) } catch (e) { /* ignore */ } }
// 让用户选一个目录(dialog.open 的 directory 模式;未设置时另存为跟随系统记忆)
const wPickDownloadDir = async () => {
const openDlg = wTauri && wTauri.dialog && wTauri.dialog.open
if (!openDlg) throw new Error('Tauri 对话框不可用')
const dir = await openDlg({ directory: true, multiple: false, title: '选择默认下载文件夹' })
if (!dir) return ''
wSetDownloadDir(dir)
return dir
}
// 拼出「另存为」的初始路径:有默认目录就用目录+文件名,没有就只给文件名
const wDefaultSavePath = async (fileName) => {
const dir = wDownloadDir()
if (!dir) return fileName
const join = wTauri && wTauri.path && wTauri.path.join
try {
if (join) return await join(dir, fileName)
return dir.replace(/[\\/]+$/, '') + '/' + fileName
} catch (e) { return fileName }
}
// 「保存时不再逐个询问」:勾选后,已设默认下载文件夹的情况下直接写盘(批量导出不再弹 N 次框)
// 桌面端默认「点下载 = 直接写进下载目录,不弹窗」;只有写失败(目录被删/无权限)才退回对话框
const wSilentSave = () => { try { const v = lsGet('iwb.silentSave', true); return v !== false } catch (e) { return true } }
const wSetSilentSave = (v) => { try { lsSet('iwb.silentSave', !!v) } catch (e) { /* ignore */ } }
// 自动下载(v3.25.20 用户裁定):勾选后「出图完成」自动存到导出目录;与「点下载是否弹框」解耦
const wAutoDownload = () => { try { return lsGet('iwb.autoDownload', false) === true } catch (e) { return false } }
const wSetAutoDownload = (v) => { try { lsSet('iwb.autoDownload', !!v) } catch (e) { /* ignore */ } }
// 把 Blob 写进指定目录(不弹框)。目录必须此前由 dialog 选过:tauri-plugin-dialog 会把该目录
// 递归加进 fs scope;scope 是「本次运行」的,重启后首次写入会失败 ⇒ 调用方回退到对话框。
const wWriteBlobToDir = async (dir, name, blob) => {
const join = wTauri && wTauri.path && wTauri.path.join
let finalName = name // 重名保护见 src/image-format.js 的 uniqueName(v3.25.18)
try {
const U = (typeof window !== 'undefined' && window.IWBImageFormat && window.IWBImageFormat.uniqueName) ? window.IWBImageFormat.uniqueName : null
if (U) finalName = await U(dir, name, join, wTauri && wTauri.fs && wTauri.fs.exists)
} catch (e) { /* 探测失败按原名写 */ }
const target = join ? await join(dir, finalName) : (dir.replace(/[\\/]+$/, '') + '/' + finalName)
await wTauri.fs.writeFile(target, new Uint8Array(await blob.arrayBuffer()))
return true
}
// 出图自动下载:三态逻辑在 src/download-auto.js。resolveSrc 只从「图库已落盘的原图」复制(按 url 回查索引),本地命中不碰图床。
const wAutoSaver = (typeof window !== 'undefined' && window.IWBDownloadAuto)
? window.IWBDownloadAuto.create({
getDir: wDownloadDir,
isOn: wAutoDownload,
resolveSrc: (item) => window.IWBDownloadAuto.resolveLocalFirst(item, { resolveDirect: (x) => wResolveOutputSrc(x, true), listFiles: () => (ModularOutputStore ? ModularOutputStore.list({ metaOnly: true }).then((r) => (r && r.ok && r.value && r.value.files) || []).catch(() => []) : lsGet(OUT_KEY, [])), readIdb: (k) => IDB.get(k).catch(() => null) }),
// dataURL 直接解码成 Blob(不再 fetch(dataURL));远程 URL 返回 null 让调用方走 fetch
toBlob: (src) => (String(src || '').indexOf('data:') === 0 ? wBlobFromDataUrl(src) : null),
write: wWriteBlobToDir,
toast: (msg, type) => { try { const f = (typeof window !== 'undefined') ? window.__iwbAutoToast__ : null; if (typeof f === 'function') f(msg, type) } catch (e) { /* 组件外调用时忽略 */ } },
})
: null
// 设置里的「打开数据目录」(走一个极小的 Rust 命令,见 src-tauri/src/lib.rs)
const wOpenDataDir = async () => {
const invoke = wTauri && wTauri.core && wTauri.core.invoke
if (!invoke) throw new Error('Tauri 不可用')
return await invoke('open_app_data_dir')
}
// v3.26.143:默认不提升 world/grid 合成层(参考 infinite-canvas);诊断页可显式 opt-in。
try { document.documentElement.dataset.layers = lsGet('iwb_layers_on', false) ? 'on' : 'off' } catch (e) { /* ignore */ }
try { const V3 = (typeof window !== 'undefined' && window.IWBCanvasV3); if (V3 && typeof V3.init === 'function') V3.init() } catch (e) { /* ignore */ }
try { if (lsGet('iwb_noblur_on', false)) document.documentElement.dataset.noblur = 'on' } catch (e) { /* ignore */ }
// 桌面端保存二进制:有导出目录直接写 Uint8Array(不弹框),没目录才弹「另存为」;刻意不经 base64,省一次全量编解码。
const wSaveBlobNative = async (blob, name, title) => {
const save = wTauri && wTauri.dialog && wTauri.dialog.save
const writeFile = wTauri && wTauri.fs && wTauri.fs.writeFile
if (!writeFile) throw new Error('Tauri 文件写入不可用(检查 fs 插件是否初始化)')
const fileName = String(name || 'image.png')
const ext = (fileName.split('.').pop() || 'png').toLowerCase()
const dir = wDownloadDir()
// 是否弹框只看「有没有导出目录」:有目录=静默落盘,写失败也不弹框(旧实现会回退「另存为」,默认路径还是旧目录,叠上出图自动下载就是每张都弹);没目录=弹一次选位置。
if (dir) {
try { await wWriteBlobToDir(dir, fileName, blob); return true } catch (e) { /* fs scope 仍是上一次运行的 */ }
try {
const invoke = wTauri && wTauri.core && wTauri.core.invoke
if (invoke) { await invoke('grant_dir', { dir: String(dir), record: false }); await wWriteBlobToDir(dir, fileName, blob); return true }
} catch (e) { /* 仍然不可写 */ }
wDownloadToast('导出目录不可写:' + dir + '(请到「设置 → 图片导出目录」重新选择)')
return false
}
if (!save) throw new Error('Tauri 保存对话框不可用(检查 dialog 插件是否初始化)')
// 初始路径 = 默认下载文件夹 + 文件名(没设置则只给文件名,跟随系统上次位置)
const defaultPath = await wDefaultSavePath(fileName)
const path = await save({ title: title || '保存', defaultPath, filters: [{ name: ext.toUpperCase() + ' 文件', extensions: [ext] }] })
if (!path) return false
await writeFile(path, new Uint8Array(await blob.arrayBuffer()))
return true
}
// 统一保存出口:桌面端交系统另存为,网页端沿用 <a download>。
// 挂到 window 供 IIFE 深处的导出/诊断/备份复用,避免到处写分支。
const wSaveBlob = (blob, name) => {
if (wIsTauri()) return wSaveBlobNative(blob, name).catch((e) => { console.error('[iwb][tauri] 保存失败', e) })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url; a.download = name
document.body.appendChild(a); a.click(); a.remove()
setTimeout(() => URL.revokeObjectURL(url), 5000)
}
// 把桌面端能力登记到 src/desktop-bridge.js(src 不得反向引用 app.js 的 window 全局,
// architecture-boundary-guard 会红;这里只做注入,设置面板/导出逻辑统一走 IWBDesktop)
// 桌面壳适配(外链 / 原生通知 / 链接拦截)落在 src/ui-desktop-shell.js
try { if (window.IWBUIShell) window.IWBUIShell.installLinkGuard(wIsTauri) } catch (e) { /* ignore */ }
if (typeof window !== 'undefined' && window.IWBDesktop && window.IWBDesktop.configure) {
window.IWBDesktop.configure({
isTauri: wIsTauri,
saveBlob: wSaveBlob,
getDownloadDir: wDownloadDir,
setDownloadDir: wSetDownloadDir,
pickDownloadDir: wPickDownloadDir,
getSilentSave: wSilentSave,
setSilentSave: wSetSilentSave,
getAutoDownload: wAutoDownload,
setAutoDownload: wSetAutoDownload,
openDataDir: wOpenDataDir,
marketList: wMarketList,
marketInstalled: wMarketInstalled,
marketInstall: wMarketInstall,
marketUninstall: wMarketUninstall,
clipboardReadImage: (window.IWBNativeClipboard || {}).readImage,
clipboardWriteImage: (window.IWBNativeClipboard || {}).writeImage,
})
}
// ========== 浏览器本地模式(Cloudflare Pages 免费版)==========
// 数据层:localStorage + IndexedDB;网络层:直连兼容 API(CORS 已验证允许)
// 桌面端(资料目录)是否生效:一堆"浏览器专有"的兜底要按它关掉
function wFileStoreOn() {
try { const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null; return !!(F && F.enabled && F.enabled()) } catch (e) { return false }
}
function storageRuntime() {
if (typeof window === 'undefined') return false
// 桌面端:资料目录就绪后一律走文件底座(内存表 + 异步落盘);否则用原来的 localStorage 实现
const fileStore = window.IWBStorageFile
if (fileStore && fileStore.enabled && fileStore.enabled()) return fileStore.runtime
return window.IWBStorageRuntime
}
function lsGet(k, fb) {
const runtime = storageRuntime()
if (runtime) return runtime.get(k, fb)
try { const v = localStorage.getItem(k); return v ? JSON.parse(v) : fb } catch (e) { return fb }
}
// 返回是否成功:容量超限等写入失败时上层可感知(避免静默丢失后 UI 仍显示「已保存」)
function lsSet(k, v) {
const runtime = storageRuntime()
if (runtime) return runtime.set(k, v)
try { localStorage.setItem(k, JSON.stringify(v)); return true } catch (e) { return false }
}
function lsRemove(k) {
const runtime = storageRuntime()
if (runtime) return runtime.remove(k)
try { localStorage.removeItem(k); return true } catch (e) { return false }
}
function lsRawGet(k, fb) {
const runtime = storageRuntime()
if (runtime) return runtime.rawGet(k, fb)
try { const v = localStorage.getItem(k); return v === null ? fb : v } catch (e) { return fb }
}
function lsRawSet(k, v) {
const runtime = storageRuntime()
if (runtime) return runtime.rawSet(k, v)
try { localStorage.setItem(k, String(v)); return true } catch (e) { return false }
}
function lsKeys() { const out = []; try { for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k) out.push(k) } } catch (e) { /* ignore */ } return out }
// 存储契约统一来自 src/storage-contract.js:P3-13 harness 忠实化后内嵌 fallback 已成死代码,
// 删除以免与 src 双实现漂移(app.js 恒在 src 之后加载,契约恒可用)。
const StorageContract = (typeof window !== 'undefined' && window.IWBStorageContract) || null
// 图片格式判定 / 下载名后缀纠正(src/image-format.js)。放在最前:1558 起的归档命名就要用。
// 判不出格式时各调用点回落到旧行为(.png),不会因为模块缺失而改变任何既有路径。
const ImageFormat = (typeof window !== 'undefined' && window.IWBImageFormat) || null
const RuntimeError = (typeof window !== 'undefined' && window.IWBRuntimeError) || null
const RuntimeLifecycle = (typeof window !== 'undefined' && window.IWBRuntimeLifecycle) || null
const RuntimeFetch = (typeof window !== 'undefined' && window.IWBRuntimeFetch) || null
const RuntimeChannel = (typeof window !== 'undefined' && window.IWBRuntimeChannel) || null
const RuntimeBoundary = (typeof window !== 'undefined' && window.IWBRuntimeBoundary) || null
const RuntimeRecord = (typeof window !== 'undefined' && window.IWBRuntimeRecord) || null
const RuntimeRecovery = (typeof window !== 'undefined' && window.IWBRuntimeRecovery) || null
const RuntimeDiagnosticRecord = (typeof window !== 'undefined' && window.IWBRuntimeDiagnosticRecord) || null
const RuntimeRunContext = (typeof window !== 'undefined' && window.IWBRuntimeRunContext) || null
const RuntimeExecutionContext = (typeof window !== 'undefined' && window.IWBRuntimeExecutionContext) || null
const RuntimeMetrics = (typeof window !== 'undefined' && window.IWBRuntimeMetrics) || null
const StorageHealth = (typeof window !== 'undefined' && window.IWBStorageHealth) || null
const RuntimeDiagnostics = (typeof window !== 'undefined' && window.IWBRuntimeDiagnostics) || null
const CrashLog = (typeof window !== 'undefined' && window.IWBCrashLog) || null
const GenerationState = (typeof window !== 'undefined' && window.IWBGenerationState) || null
const PluginHost = (typeof window !== 'undefined' && window.IWBPluginHost) || null
const wPluginCommands = []
// 右键菜单精简(2026-11-27 用户要求):下面这些插件入口平时用不到,从右键菜单里摘掉。
// 只影响右键菜单;插件本身(工具栏 / 节点气泡 / 插件页)照常,想恢复从列表里删掉对应项即可。
const CTX_SKIP_VARIANTS = ['ptpl', 'style']
const CTX_SKIP_COMMANDS = ['image-annotate', 'image-vectorize', 'collect-selected', 'collect-prompt']
const ctxSkippedVariant = (v) => { const tail = String((v && v.id) || '').split(':').pop(); const t = String((v && v.title) || ''); return CTX_SKIP_VARIANTS.indexOf(tail) >= 0 || t === '提示词模板' || t === '样式节点' }
const ctxSkippedCommand = (c) => { const tail = String((c && c.id) || '').split(':').pop(); const t = String((c && c.title) || ''); return CTX_SKIP_COMMANDS.indexOf(tail) >= 0 || tail.indexOf('collect-') === 0 || t.indexOf('标注 / 修图') === 0 || t.indexOf('位图转矢量') === 0 }
const wPluginNodeVariants = []
// F2(P2-11b):变体元数据渲染回退表(按变体 id)。插件停用/未加载时,旧插件节点仍能渲染标题。
// 与 wPluginNodeVariants(菜单/运行用,仅"已激活"变体)分开,故不影响启停语义。
const wPluginVariantMeta = new Map()
const wPluginPanels = []
const wPluginGenHooks = []
const wPluginProviders = []
let wPluginCanvasBridge = null
const wPluginNodeActions = []
const wRuntimePlugins = []
const StorageMigrations = (typeof window !== 'undefined' && window.IWBStorageMigrations) || null
// 统一的本地存储适配器:业务层不直接依赖 JSON 序列化细节。
const SchemaVersions = Object.assign({ workspace: 1, canvas: 1, backup: 2, groups: 1 }, StorageContract.schema || {})
const ModularLocalStore = typeof window !== 'undefined' && window.IWBStorageLocal && typeof window.IWBStorageLocal.create === 'function'
? window.IWBStorageLocal.create({ storage: (typeof window !== 'undefined' && window.IWBStorageFile && window.IWBStorageFile.enabled()) ? window.IWBStorageFile.storage() : window.localStorage })
: null
const unwrapStorageResult = (value, fallback) => value && value.ok === false ? fallback : (value && value.ok === true && Object.prototype.hasOwnProperty.call(value, 'value') ? value.value : value)
const LocalStore = {
get(key, fallback) {
if (ModularLocalStore) return unwrapStorageResult(ModularLocalStore.get(key, fallback), fallback)
return lsGet(key, fallback)
},
set(key, value) {
if (ModularLocalStore) { const r = ModularLocalStore.set(key, value); return !!(r && (r.ok === undefined ? r : r.ok)) }
return lsSet(key, value)
},
remove(key) {
if (ModularLocalStore) { const r = ModularLocalStore.remove(key); return !!(r && (r.ok === undefined ? r : r.ok)) }
return lsRemove(key)
},
bytes() {
if (ModularLocalStore) { const r = ModularLocalStore.bytes(); return r && r.ok ? r.value : 0 }
return storageRuntime() ? storageRuntime().bytes() : localStorageBytes()
},
key(name) { return StorageContract.localKeys[name] || name },
}
const ModularWorkspaceStore = typeof window !== 'undefined' && window.IWBStorageWorkspace && ModularLocalStore
? window.IWBStorageWorkspace.create({ local: ModularLocalStore, key: StorageContract.localKeys.workspaces, migrations: StorageMigrations })
: null
const ModularBackupStore = typeof window !== 'undefined' && window.IWBStorageBackup
? window.IWBStorageBackup.create({ migrations: StorageMigrations, schemaVersion: SchemaVersions.backup, checksum: (value) => wSha256(value) })
: null
// 统一错误契约:业务层只传递可展示、可分类、可决定是否重试的错误对象。
function iwError(code, message, options) {
const o = options || {}
return { ok: false, code: code || 'unknown', message: String(message || '操作失败'), retryable: !!o.retryable, cause: o.cause ? String(o.cause) : undefined }
}
function iwErrorFrom(error, fallbackCode) {
const e = error || {}
if (e && e.ok === false && e.code && e.message) return e
const name = String(e.name || '')
const code = name === 'AbortError' ? 'cancelled' : (e.iwbType || fallbackCode || 'unknown')
return iwError(code, e.message || e.error || '操作失败', { retryable: code === 'network' || code === 'timeout', cause: name })
}
// 错误可见性(2026-11-07):关键路径的 catch 不纯静默(计数 + 面包屑),实现在 src/runtime-metrics.js
const swallow = (typeof window !== 'undefined' && window.IWBMetricsSwallow) || (() => {})
function storageHealthCheck() {
const guard = (state) => {
if (typeof state !== 'object' || state === null) return state
const bytes = Number(state.bytes) || 0
// localStorage ~5MB;接近 80% 即预警,避免「画布未保存、空间不足」忽然出现
if (!wFileStoreOn() && bytes > 4 * 1024 * 1024) {
const issues = Array.isArray(state.issues) ? state.issues.slice() : []
issues.push(iwError('storage', '本地存储空间将满(localStorage 已用 ' + fmtStorage(bytes) + ' / 约5MB),建议导出备份后清理图库/不用的画布'))
return Object.assign({}, state, { issues })
}
return state
}
if (StorageHealth && typeof StorageHealth.check === 'function') return StorageHealth.check().then((s) => guard({ ok: !!s.ok, localStorage: s.localStorage.status === 'healthy', indexedDB: s.indexedDB.status === 'healthy', bytes: LocalStore.bytes(), issues: Object.keys(s).filter((key) => s[key] && s[key].error).map((key) => iwError('storage', s[key].error)) }))
const out = { ok: true, localStorage: false, indexedDB: false, bytes: 0, issues: [] }
try {
const key = '__iwb_health__'
lsRawSet(key, '1')
out.localStorage = lsRawGet(key, null) === '1'
lsRemove(key)
out.bytes = storageRuntime() ? storageRuntime().bytes() : localStorageBytes()
} catch (e) { out.issues.push(iwError('storage', 'localStorage 不可写入', { cause: e.message })) }
if (typeof indexedDB !== 'undefined') out.indexedDB = true
else out.issues.push(iwError('storage', 'IndexedDB 不可用'))
out.ok = out.localStorage && out.indexedDB
if (!wFileStoreOn() && out.bytes > 4 * 1024 * 1024) out.issues.push(iwError('storage', '本地存储空间将满(localStorage 已用 ' + fmtStorage(out.bytes) + ' / 约5MB),建议导出备份后清理图库/不用的画布'))
return out
}
// localStorage 当前占用字节(UTF-16 计,用于设置页展示;不含 IndexedDB)
function localStorageBytes() {
let n = 0
try { for (const k of lsKeys()) { n += (k.length + (lsRawGet(k, '') || '').length) * 2 } } catch (e) { /* ignore */ }
return n
}
function fmtStorage(bytes) {
const mb = bytes / (1024 * 1024)
return mb >= 1 ? mb.toFixed(1) + ' MB' : Math.round(bytes / 1024) + ' KB'
}
// 跨标签页即时同步发送端(模块级单例):保存成功后广播,同机其他标签页立即比对 rev(轮询兜底)
let syncBC = null
try { if (typeof BroadcastChannel !== 'undefined') syncBC = new BroadcastChannel('iwb_ws_sync') } catch (e) { /* 不支持则仅轮询 */ }
function bcNotify() { try { if (syncBC) syncBC.postMessage({ at: Date.now() }) } catch (e) { /* ignore */ } }
// 生成完成提示音(设置 → 画布 → 生成完成提示音;浏览器需用户交互后 AudioContext 才允许发声)
function playDoneSound() {
try {
const AC = window.AudioContext || window.webkitAudioContext
if (!AC) return
const ctx = new AC()
const beep = (freq, t0, dur) => {
const o = ctx.createOscillator(); const g = ctx.createGain()
o.type = 'sine'; o.frequency.value = freq
o.connect(g); g.connect(ctx.destination)
g.gain.setValueAtTime(0.0001, ctx.currentTime + t0)
g.gain.exponentialRampToValueAtTime(0.28, ctx.currentTime + t0 + 0.02)
g.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + t0 + dur)
o.start(ctx.currentTime + t0); o.stop(ctx.currentTime + t0 + dur + 0.05)
}
beep(880, 0, 0.15); beep(1318.5, 0.18, 0.3)
setTimeout(() => { try { ctx.close() } catch (e) { /* ignore */ } }, 1400)
} catch (e) { /* ignore */ }
}
// 浏览器总通知:权限只在用户点击生图后的首次运行时请求;不支持/拒绝权限时静默降级。
let browserNotificationPermissionPromise = null
function prepareBrowserNotifications() {
if (wIsTauri()) return // 桌面端用原生通知,不需要网页权限
const N = typeof window !== 'undefined' && window.Notification
if (!N || typeof N.requestPermission !== 'function' || N.permission !== 'default' || browserNotificationPermissionPromise) return
try { browserNotificationPermissionPromise = N.requestPermission().catch(() => 'denied') } catch (e) { browserNotificationPermissionPromise = Promise.resolve('denied') }
}
function notifyBrowserGenerationDone(info) {
// 桌面端没有 Web Notification:交给桌面壳模块发原生通知
try { if (window.IWBUIShell && window.IWBUIShell.notifyGenerationDone(info)) return } catch (e) { /* ignore */ }
const N = typeof window !== 'undefined' && window.Notification
if (!N) return
const emit = () => {
if (N.permission !== 'granted') return
const x = info || {}
const total = Number(x.total) || 0
const failed = Number(x.failed) || 0
const title = failed ? '出图完成(部分失败)' : '出图完成'
const body = failed ? ('成功 ' + Math.max(0, total - failed) + ' 张,失败 ' + failed + ' 张') : ('共生成 ' + total + ' 张图片')
try {
const n = new N(title, { body, tag: 'iwb-generation-completed', renotify: true })
setTimeout(() => { try { n.close() } catch (e) { /* ignore */ } }, 8000)
} catch (e) { /* ignore */ }
}
if (N.permission === 'granted') emit()
else if (browserNotificationPermissionPromise) browserNotificationPermissionPromise.then(emit).catch(() => {})
}
// 提示词变量替换(发送生成请求前):{date} 今日日期 / {time} 当前时间 / {model} 所选模型
function expandPromptVars(text, model) {
const d = new Date()
const pad = (n) => String(n).padStart(2, '0')
const map = {
'{date}': d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()),
'{time}': pad(d.getHours()) + ':' + pad(d.getMinutes()),
'{model}': model || '',
}
let out = String(text || '')
for (const k of Object.keys(map)) out = out.split(k).join(map[k])
return out
}
const W_DEF_PROVIDERS = [
{
id: 'tuzi', name: '默认服务', baseUrl: '',
fallbacks: [],
genPath: '/images/generations', editPath: '/images/edits',
keys: [
{ id: 'daily', name: '日常 key(输出约1.5K级)', source: 'literal', value: '' },
{ id: '4k', name: '绘画分组 4K key', source: 'literal', value: '' },
],
},
]
const W_DEF_IMAGE_TRANSFER = {
mode: 'base64', maxRefs: 3,
imageHost: {
type: 'github',
github: { owner: '', repo: '', branch: 'main', dir: 'tmp-refs', token: '', retentionHours: 24 },
imgbb: { key: '' },
generic: { uploadUrl: '', method: 'POST', auth: { type: 'none', token: '', headerName: '' }, fileField: 'image', urlPath: 'data.url', headers: {} },
},
compression: { enabled: true, maxMB: 8, maxEdge: 2048, quality: 0.9, format: 'keep' },
}
const W_DEF_RETENTION = { enabled: true, maxFiles: 500, maxDays: 15 }
// 默认外观在 src/ui-appearance.js(DEFAULTS);这里只放引用,避免两处默认值漂移
const W_DEF_APPEARANCE = (window.IWBUIApearance && window.IWBUIApearance.DEFAULTS) || { canvasBgLight: '#d9dbde', canvasBgDark: '#6f6f6f', accent: '#6b7280' }
// autoSaveImages 已废弃(v3.25.33):保留字段只为老配置兼容,**不再驱动任何下载行为**。
// 「出图自动保存」由 设置 → 图片导出目录 → 自动下载(iwb.autoDownload + wAutoSaver)负责。
// lodLowZoom(v3.25.71):15% 以下是否切轻量节点体(用户可关)
const W_DEF_CANVAS = { generationConcurrency: 4, taskStallEndMs: 300000, autoSaveImages: true, backupOriginals: true, lodLowZoom: true, appearance: W_DEF_APPEARANCE }
// 任务条「结束」按钮出现的阈值:默认 5 分钟。判据是「该任务距上一次进展的时长」,
// 而不是任务总时长 —— 多个变体(如 3 张)正常跑 6 分钟也不会误报"卡住"。
const TASK_STALL_END_MIN = 60000
const TASK_STALL_END_MAX = 3600000
function taskStallEndMs(cfg) {
const n = Number(cfg && cfg.canvas && cfg.canvas.taskStallEndMs)
return Number.isFinite(n) && n > 0 ? Math.max(1000, Math.min(TASK_STALL_END_MAX, Math.round(n))) : 300000
}
// ---------- 私有功能开关(v3.87.4)----------
// 目的:分层(seedream 图层分离)只给自己用,普通用户看不到入口。
// 开启方式(每台设备/每个域名各一次):打开 站点/#iwb-tools=<暗号> → 命中即写入 localStorage,
// 并立刻 history.replaceState 抹掉地址栏里的 fragment(截图/分享不留痕;fragment 本身也不发给服务器)。
// 关闭:站点/#iwb-tools=off。
// 注意:这是"隐藏入口"级别的隐蔽(防顺手发现),不是安全边界——源码公开,懂技术的人可手动置 localStorage。
const PRIVATE_TOOLS_TOKEN = 'malongan'
let wPrivateToolsOn = false
function wReadPrivateTools() {
try { wPrivateToolsOn = lsRawGet('iwb_tools', null) === PRIVATE_TOOLS_TOKEN } catch (e) { wPrivateToolsOn = false }
try {
const m = /(?:^|[#&])iwb-tools=([^&]+)/.exec(location.hash || '')
if (m) {
const v = decodeURIComponent(m[1] || '')
if (v === PRIVATE_TOOLS_TOKEN) { try { lsRawSet('iwb_tools', PRIVATE_TOOLS_TOKEN) } catch (e) { /* 隐私模式忽略 */ } wPrivateToolsOn = true; try { if (CrashLog && CrashLog.breadcrumb) CrashLog.breadcrumb('private-tools', 'on') } catch (e) { /* ignore */ } }
else if (v === 'off') { try { lsRemove('iwb_tools') } catch (e) { /* ignore */ } wPrivateToolsOn = false }
// 无论命中与否都抹掉 fragment:地址栏与历史记录里不留暗号
try { history.replaceState(null, '', location.pathname + location.search) } catch (e) { /* ignore */ }
}
} catch (e) { /* ignore */ }
// 开关是可变 let:读完(含暗号分支)统一同步给设置面板模块,避免它读到过期值
if (typeof window !== 'undefined' && window.IWBUISettingsModal) window.IWBUISettingsModal.setPrivateToolsOn(wPrivateToolsOn)
return wPrivateToolsOn
}
const HOTKEY_DEFAULTS = {
cancel: 'Escape', selectAll: 'Ctrl+A', save: 'Ctrl+S', exportCanvas: 'Ctrl+Shift+S', help: '?', toggleLibrary: 'N', toggleLeftDock: 'T',
fitView: 'Shift+F', fitSelection: 'F', toggleEnabled: 'M', refine: 'Shift+M',
resetView: 'Home', zoomIn: '+', zoomOut: '-', pan: 'Space', detach: 'Alt', group: 'Ctrl+G', ungroup: 'Ctrl+Shift+G',
undo: 'Ctrl+Z', redo: 'Ctrl+Y', copy: 'Ctrl+C', cut: 'Ctrl+X', paste: 'Ctrl+V', duplicate: 'Ctrl+D', delete: 'Delete', rename: 'F2', toolSelect: 'V', toolPan: 'H',
pasteGroup: 'Ctrl+Shift+V', expandEdit: 'Ctrl+E' // 放大编辑提示词(原「适应选中(备用)」已让位)
}
function hotkeyMatches(e, binding) {
const parts = String(binding || '').toLowerCase().split('+').filter(Boolean)
const key = parts.pop()
if (!key) return false
const wantsMeta = parts.includes('meta'), wantsCtrl = parts.includes('ctrl')
const primary = wantsMeta ? !!e.metaKey : (!!e.ctrlKey || !!e.metaKey)
// 空格键:binding 用 'Space' 表示,但浏览器 e.key 是 ' '(空格字符),需兼容 'space'/'Space'/空格
const pressedKey = String(e.key || '').toLowerCase()
const keyMatches = key === 'space' ? (pressedKey === 'space' || pressedKey === ' ' || e.code === 'Space') : pressedKey === key
return keyMatches
&& (wantsCtrl ? primary : !(e.ctrlKey || e.metaKey))
&& (wantsMeta ? !!e.metaKey : true)
&& !!e.altKey === parts.includes('alt')
&& !!e.shiftKey === parts.includes('shift')
}
const W_DEF_WEBHOOK = { enabled: false, url: '' }
// 任务 id 唯一自检:发现重复时追加后缀并告警(防 React key 冲突 / 结果互相覆盖)
function wDedupeTaskIds(tasks) {
const seen = {}
for (const t of tasks) {
if (seen[t.id]) {
const baseId = t.id
let suffix = seen[baseId]
let nextId = baseId + '#dup' + suffix
while (seen[nextId]) { suffix++; nextId = baseId + '#dup' + suffix }
console.warn('[iwb] 任务 id 冲突:', baseId, '→', nextId)
seen[baseId] = suffix + 1
t.id = nextId
seen[nextId] = 1
} else {
seen[t.id] = 1
}
}
return tasks
}
// v3.87.28 生图请求体策略:厂商分类相关字段的白名单清洗(配置读写两处共用)
const W_SHAPE_KINDS = ['openai', 'gemini', 'doubao', 'custom']
// 分层节点专用的「模型宇宙」,与生图模型清单完全隔离(规范 §13.26):
// 生图模型清单常被用户当"随便加的模型名"用,直接复用会把分层节点搞坏。
// 内置的 doubao-seedream-5-0-pro-260628 是唯一实测可用的图层分离模型:永远在列、**不可删除、不可隐藏**
// (隐藏它会让分层节点没有模型可选),其余条目复用同一套去重/trim/visible 归一化。
const BUILTIN_LAYER_MODEL = 'doubao-seedream-5-0-pro-260628'
// ── 配置/模型数据的形状规范化纯函数族:已收编到 src/storage-config-shape.js ─────────────
// (P1 拆分批 2,2026-10-28)迁出 9 个函数:wClone / mergeDeep / wMask / wShapeProviderFields /
// wNormalizeImageModels / wNormalizeLayerModels / wMigrateLlm / storageResult / wStripDerived,
// 连同仅被 wStripDerived 使用的 W_CFG_DERIVED_KEYS 一起搬走。
//
// **边界**:本模块只管「数据长什么样」,不碰 I/O。
// 读写在 app.js 的 wRawCfg / wRawStoredCfg / wCfgSave / wCfgPublic 里(它们调用本模块)。
//
// 迁移前做过等价性验证:25 组用例(含密钥掩码、深合并、模型去重保序、LLM 老形状迁移)
// 新旧实现输出完全一致。
const _wCfgShape = (() => {
const M = (typeof window !== 'undefined' && window.IWBStorageConfigShape) || null
if (!M) return null
try {
return M.create({ W_SHAPE_KINDS, BUILTIN_LAYER_MODEL })
} catch (e) {
// 依赖缺失属于构建/加载错误,必须显式暴露,不静默降级
try { console.error('[iwb][config-shape] 初始化失败:', e && e.message) } catch (e2) {}
return null
}
})()
function _cfgShapeFn(name) {
const fn = _wCfgShape && _wCfgShape[name]
if (typeof fn !== 'function') throw new Error('[iwb][config-shape] 模块未就绪: ' + name)
return fn
}
const wClone = (v) => _cfgShapeFn('wClone')(v)
const mergeDeep = (base, extra) => _cfgShapeFn('mergeDeep')(base, extra)
const wMask = (v) => _cfgShapeFn('wMask')(v)
const wShapeProviderFields = (pr) => _cfgShapeFn('wShapeProviderFields')(pr)
const wNormalizeImageModels = (models) => _cfgShapeFn('wNormalizeImageModels')(models)
const wNormalizeLayerModels = (models) => _cfgShapeFn('wNormalizeLayerModels')(models)
const wMigrateLlm = (cfg) => _cfgShapeFn('wMigrateLlm')(cfg)
const storageResult = (ok, extra) => _cfgShapeFn('storageResult')(ok, extra)
const wStripDerived = (cfg) => _cfgShapeFn('wStripDerived')(cfg)
function wRawCfg() {
const cfg = LocalStore.get(StorageContract.localKeys.config, null)
const providers = (cfg && Array.isArray(cfg.providers) && cfg.providers.length) ? cfg.providers : wClone(W_DEF_PROVIDERS)
return {
providers: providers.map((p) => ({ ...p, models: wNormalizeImageModels(p.models), layerModels: wNormalizeLayerModels(p.layerModels) })),
imageTransfer: mergeDeep(W_DEF_IMAGE_TRANSFER, (cfg && cfg.imageTransfer) || {}),
outputsRetention: Object.assign(wClone(W_DEF_RETENTION), (cfg && cfg.outputsRetention) || {}),
llm: wMigrateLlm((cfg && cfg.llm) || {}),
canvas: Object.assign(wClone(W_DEF_CANVAS), (cfg && cfg.canvas) || {}),
webhook: Object.assign(wClone(W_DEF_WEBHOOK), (cfg && cfg.webhook) || {}),
defaultGen: (cfg && cfg.defaultGen && typeof cfg.defaultGen === 'object') ? wClone(cfg.defaultGen) : null,
}
}
// 磁盘上的**原样**配置对象(未归一化)。用途只有一个:让"未知字段"在写入时不被吃掉。
// 为什么不直接用 wRawCfg():它是**白名单归一化**结果(providers/imageTransfer/llm/canvas/webhook),
// 拿它当写盘基底 ⇒ 任何未列入白名单的新设置项在当前版本往返一次就永久丢失。
function wRawStoredCfg() {
const cfg = LocalStore.get(StorageContract.localKeys.config, null)
return (cfg && typeof cfg === 'object' && !Array.isArray(cfg)) ? cfg : {}
}
// ---------- 敏感字段唯一清单(v3.0.5,结构性保障)----------
// 事故史(同一形状缺陷已出现两次):
// ① v3.0.3:导入图片路径把"对外脱敏形态"当完整设置用 ⇒ imageTransfer.compression 拿到 undefined
// ⇒ 压缩被静默跳过 ⇒ 9.3MB 原图 base64 裸落节点(见 compressConf 的注释)。
// ② v3.0.4:备份导出把 wCfgPublic() 当"完整设置"写进备份 ⇒ 备份里根本没有 compression 等字段
// ⇒ 「设置还原不回来」;同时 withKeys 开关形同虚设(公开形态里压根没有 value/apiKey 字段)。
// 结构性保障:这张表是**导出脱敏的唯一来源**;导入侧按同一批字段位置逐项解析 __KEEP__
// (见 wCfgSave 里的 keepOrInput 调用点),并由契约测试 150-11 逐条强制"表里有几条、
// 导入侧就必须解析几条、且 __KEEP__ 绝不落盘"——新增密钥字段只改一侧必定红。
// 路径段 '*' = 数组或对象通配;表里列出的字段是"值即密钥"的叶子。
const W_KEEP = '__KEEP__'
const W_CLEAR = '__CLEAR__'
const W_SENSITIVE_PATHS = [
['providers', '*', 'keys', '*', 'value'], // 生图服务 Key
['llm', 'providers', '*', 'keys', '*', 'value'], // LLM 渠道 Key
['llm', 'apiKey'], // LLM Key(旧格式)
['imageTransfer', 'imageHost', 'imgbb', 'key'], // ImgBB Key
['imageTransfer', 'imageHost', 'github', 'token'], // GitHub 图床 Token
['imageTransfer', 'imageHost', 'generic', 'auth', 'token'], // 自定义图床 Token
['security', 'password'], // 访问口令
]
// 按清单遍历真实设置;cb(holder, key, path, label)。只回调**存在**的叶子(hasOwnProperty)。
function wEachSensitivePath(root, cb) {
if (!root || typeof root !== 'object') return
const walk = (node, segs, path, label) => {
if (!node || typeof node !== 'object') return
const seg = segs[0]
if (seg === '*') {
const keys = Array.isArray(node) ? node.map((_, i) => i) : Object.keys(node)
for (const k of keys) walk(node[k], segs.slice(1), path.concat(['*']), label)
return
}
if (!Object.prototype.hasOwnProperty.call(node, seg)) return
if (segs.length === 1) { cb(node, seg, path.concat([seg]).join('.'), label); return }
walk(node[seg], segs.slice(1), path.concat([seg]), label)
}
// label 只用于人读的提示(缺失本机值时告诉用户缺的是哪类密钥)
const labels = { 'providers.*.keys.*.value': '生图服务 Key', 'llm.providers.*.keys.*.value': 'LLM Key', 'llm.apiKey': 'LLM Key(旧格式)', 'imageTransfer.imageHost.imgbb.key': 'ImgBB Key', 'imageTransfer.imageHost.github.token': 'GitHub 图床 Token', 'imageTransfer.imageHost.generic.auth.token': '自定义图床 Token', 'security.password': '访问口令' }
for (const p of W_SENSITIVE_PATHS) walk(root, p, [], labels[p.join('.')] || '密钥')
}
// 备份导出的**唯一** config 出口(结构性保障,禁止绕过):
// 源必须是 wRawCfg()(真实完整设置),绝不能是 wCfgPublic()(对外脱敏展示形态,字段是白名单子集)。
// withKeys=false(默认)⇒ 非空敏感字段替换为 __KEEP__(还原时解析为本机值,不覆盖本机密钥)。
// withKeys=true ⇒ 写入明文密钥(用户显式选择"带着密钥一起备份",备份是本地文件,属预期行为)。
// 空字符串表示"本机本来就没有这个密钥":还原时同样不覆盖本机已有值(见 wCfgSave)。
function wBackupConfig(withKeys) {
const cfg = wClone(wRawCfg())
// 归一化视图之外的原样字段也带上(wRawCfg 是白名单视图):备份必须是"完整设置",
// 而不只是"当前版本认识的设置"。否则未知字段一来一回就被吃掉。
const stored = wRawStoredCfg()
for (const k of Object.keys(stored)) if (!Object.prototype.hasOwnProperty.call(cfg, k)) cfg[k] = wClone(stored[k])
if (!withKeys) wEachSensitivePath(cfg, (holder, key) => { if (holder[key]) holder[key] = W_KEEP })
return cfg
}
// 备份里是否**真的**带明文密钥(还原界面用来显示「含密钥/不含密钥」,避免只看 llm.apiKey 而漏判)
function wCfgHasPlaintextKeys(cfg) {
let found = false
wEachSensitivePath(cfg, (holder, key) => { if (holder[key] && holder[key] !== W_KEEP && holder[key] !== W_CLEAR) found = true })
return found
}
// 与 server getConfigPublic 同构(前端设置弹窗依赖)
// ⚠ 用途限定:**仅供对外响应 / 设置弹窗展示**。字段是白名单子集且密钥被掩码,
// **禁止**用于任何持久化 / 导出 / 备份 / 还原路径 —— 那会把"展示形态"当"完整设置"存下来。
// 备份请用 wBackupConfig();写盘请用 wCfgSave()。(v3.0.5 结构性契约,见 W_SENSITIVE_PATHS 注释)
function wCfgPublic() {
const cfg = wRawCfg()
const it = cfg.imageTransfer
const ih = it.imageHost
return {
providers: cfg.providers.map((pr) => Object.assign({
id: pr.id, name: pr.name || pr.id, baseUrl: pr.baseUrl || '', fallbacks: pr.fallbacks || [],
genPath: pr.genPath || '/images/generations', editPath: pr.editPath || '/images/edits',
keys: (pr.keys || []).map((k) => {
const filled = !!k.value
return { id: k.id, name: k.name || k.id, source: k.source || 'literal', filled, masked: filled ? wMask(k.value) : '', qwenName: '' }
}),
models: wNormalizeImageModels(pr.models),
layerModels: wNormalizeLayerModels(pr.layerModels),
}, wShapeProviderFields(pr))),
imgbb: { configured: !!(ih.imgbb.key), masked: ih.imgbb.key ? wMask(ih.imgbb.key) : '' },
imageTransfer: {
mode: it.mode || 'base64', maxRefs: Number(it.maxRefs) || 3,
// v3.0.5:补上 compression —— 设置弹窗「压缩」区绑定的就是这里的值。
// 旧形状缺这个字段 ⇒ 弹窗永远显示硬编码默认值(用户看到的不是本机真实设置),
// 且同形状缺陷正是备份丢 compression / 导入静默不压缩的根因(见 W_SENSITIVE_PATHS 注释)。
compression: wClone(it.compression || W_DEF_IMAGE_TRANSFER.compression),
imageHost: {
type: ih.type || 'github',
// 图床 Token 同属敏感字段:展示形态必须掩码(此前 github token 以明文出现在"公开配置"里)
github: Object.assign({ owner: '', repo: '', branch: 'main', dir: 'tmp-refs', token: '', retentionHours: 24 }, ih.github || {}, { token: ih.github && ih.github.token ? wMask(ih.github.token) : '' }),
imgbb: { key: ih.imgbb && ih.imgbb.key ? wMask(ih.imgbb.key) : '' },
generic: Object.assign(
{ uploadUrl: '', method: 'POST', auth: { type: 'none', token: '', headerName: '' }, fileField: 'image', urlPath: 'data.url', headers: {} },
ih.generic || {},
{ auth: Object.assign({ type: 'none', token: '', headerName: '' }, (ih.generic && ih.generic.auth) || {}, { token: ih.generic && ih.generic.auth && ih.generic.auth.token ? wMask(ih.generic.auth.token) : '' }) },
),
},
},
outputsRetention: cfg.outputsRetention,
defaultGen: cfg.defaultGen || null,
llm: {
providers: (cfg.llm.providers || []).map((p) => ({
id: p.id, name: p.name || 'LLM 渠道', baseUrl: p.baseUrl || '', fallbacks: (p.fallbacks || []).map((u) => String(u || '').trim()).filter(Boolean),
keys: (p.keys || []).map((k) => ({ id: k.id, name: k.name || 'Key', filled: !!k.value, masked: k.value ? wMask(k.value) : '' })),
models: (p.models || []).filter((m) => m && m.name).map((m) => ({ name: String(m.name), default: !!m.default })),
defaultModel: p.defaultModel || '',
})),
defaultProviderId: cfg.llm.defaultProviderId || ((cfg.llm.providers || [])[0] && (cfg.llm.providers)[0].id) || '',
defaultInstruction: cfg.llm.defaultInstruction || '',
},
canvas: cfg.canvas,
webhook: cfg.webhook,
security: { hasPassword: false },
server: { dataDir: '浏览器本地存储', port: '-' },
}
}
// 与 server saveConfigFromClient 同构(掩码/__KEEP__ 保留原值)
// wCfgSave 自己消化的顶层键(其余顶层键一律当"未知字段"原样保留,见 wCfgSave 末尾)
// imgbb/imgbbKey 是公开展示形态的派生字段,绝不能当未知设置项写盘。
const W_CFG_CANONICAL_KEYS = {
providers: 1, imageTransfer: 1, outputsRetention: 1, llm: 1, canvas: 1, webhook: 1, security: 1,
imgbb: 1, imgbbKey: 1, ok: 1, server: 1,
}
// 展示形态(wCfgPublic)专用的派生字段:只在内存里用于渲染,**绝不落盘**。
// 这样"保留未知字段"才敢用 `Object.assign({}, old, incoming)` —— 否则 filled/masked 之类的
// 展示噪音会被当成设置项写进备份,再被下一次备份原样带出去。
// 配置写入的**唯一**实现(设置弹窗保存 + 备份还原共用)。
// 结构原则(v3.0.5,防止"设置了却存不下 / 还原不回来"复发):
// ① 已知分区**深合并**,不再白名单式逐字段重建 —— 白名单漏掉一个字段就是"保存了但没写盘"。
// 历史事故:imageTransfer.compression 不在白名单里 ⇒ 压缩设置保存与还原都被静默丢弃。
// ② 未知字段从**磁盘原对象**起底并保留,避免"以后新增的设置又被旧代码吃掉"。
// ③ 敏感字段只看 W_SENSITIVE_PATHS:__KEEP__ ⇒ 本机当前值;掩码串 ⇒ 绝不写盘(视为保持原值);
// 本机无值时记入 missingKeep,由调用方(备份还原 UI)给出**可见提示**,不静默留空。
function wCfgSave(body) {
const incoming = (body && typeof body === 'object' && !Array.isArray(body)) ? body : {}
const stored = wRawStoredCfg() // 磁盘原对象:未知字段的唯一来源
const prev = wRawCfg() // 归一化后的本机真实设置
const missingKeep = []
// 单个敏感叶子:__KEEP__/掩码/空 ⇒ 保持本机原值;本机也没有 ⇒ 记录(可见提示),不静默留空
const keepOrInput = (raw, localValue, path, label, trim) => {
const local = typeof localValue === 'string' ? localValue : ''
if (typeof raw === 'string' && raw.indexOf('•') !== -1) return local // 掩码串绝不写盘
if (raw === undefined || raw === null || raw === '' || raw === W_KEEP) {
if (raw === W_KEEP && !local) missingKeep.push({ path, label })
return local
}
if (raw === W_CLEAR) return ''
return trim ? String(raw).trim() : String(raw)
}
// ---- 生图服务(keys 按 id 对齐解析 __KEEP__;provider 的未知字段原样保留)----
const prevProv = {}
for (const pr of prev.providers) {
const keys = {}
for (const k of (pr.keys || [])) keys[k.id] = k
prevProv[pr.id] = { pr, keys }
}
const incomingProviders = Array.isArray(incoming.providers) ? incoming.providers : null
const providers = incomingProviders && incomingProviders.length ? incomingProviders.map((pr, pi) => {
const slot = prevProv[pr.id] || {}
const old = slot.pr || {}
const oldKeys = slot.keys || {}
const pid = pr.id || ('p' + pi)
const keys = (pr.keys || []).map((k, ki) => {
const kid = k.id || ('k' + pi + '_' + ki)
const oldKey = oldKeys[k.id] || oldKeys[kid] || {}
const value = keepOrInput(
k.value, oldKey.value,
'providers.' + pid + '.keys.' + kid + '.value',
'生图服务「' + (pr.name || pid) + '」的 Key',
)
return Object.assign({}, oldKey, wStripDerived(k), { id: kid, name: k.name || k.id || 'Key 分组', source: k.source || 'literal', value })
})
return Object.assign({}, old, wStripDerived(pr), {
id: pid, name: pr.name || pr.id || 'Provider', baseUrl: pr.baseUrl || '',
fallbacks: pr.fallbacks || [], genPath: pr.genPath || '/images/generations', editPath: pr.editPath || '/images/edits',
keys,
models: wNormalizeImageModels(pr.models),
layerModels: wNormalizeLayerModels(pr.layerModels),
}, wShapeProviderFields(pr))
}) : prev.providers.map((p) => wClone(p))
// ---- 图片传输(深合并:compression 等全部分区都跟着走)----
const itIn = (incoming.imageTransfer && typeof incoming.imageTransfer === 'object' && !Array.isArray(incoming.imageTransfer)) ? incoming.imageTransfer : null
const it = itIn ? mergeDeep(prev.imageTransfer, itIn) : wClone(prev.imageTransfer)
const ih = (it.imageHost && typeof it.imageHost === 'object') ? it.imageHost : (it.imageHost = wClone(W_DEF_IMAGE_TRANSFER.imageHost))
ih.github = Object.assign({}, W_DEF_IMAGE_TRANSFER.imageHost.github, ih.github || {})
ih.imgbb = Object.assign({}, W_DEF_IMAGE_TRANSFER.imageHost.imgbb, ih.imgbb || {})
ih.generic = mergeDeep(W_DEF_IMAGE_TRANSFER.imageHost.generic, ih.generic || {})
if (itIn) {
const inIH = (itIn.imageHost && typeof itIn.imageHost === 'object') ? itIn.imageHost : {}
const pIH = prev.imageTransfer.imageHost
ih.github.token = keepOrInput(inIH.github && inIH.github.token, pIH.github.token, 'imageTransfer.imageHost.github.token', 'GitHub 图床 Token')
ih.imgbb.key = keepOrInput(inIH.imgbb && inIH.imgbb.key, pIH.imgbb.key, 'imageTransfer.imageHost.imgbb.key', 'ImgBB Key')
ih.generic.auth.token = keepOrInput(inIH.generic && inIH.generic.auth && inIH.generic.auth.token, pIH.generic.auth.token, 'imageTransfer.imageHost.generic.auth.token', '自定义图床 Token')
}
it.mode = String(it.mode || 'base64')
it.maxRefs = Math.max(1, Math.min(12, Number(it.maxRefs) || 3))
it.compression = mergeDeep(W_DEF_IMAGE_TRANSFER.compression, it.compression || {})
// 设置弹窗还会单独送 imgbbKey(公开形态的 imgbb 掩码字段);真值才写盘
const imgbbKeyIn = incoming.imgbbKey
if (imgbbKeyIn && imgbbKeyIn !== W_KEEP && String(imgbbKeyIn).indexOf('•') === -1) ih.imgbb.key = String(imgbbKeyIn)
const outputsRetention = Object.assign(wClone(W_DEF_RETENTION), prev.outputsRetention || {}, (incoming.outputsRetention && typeof incoming.outputsRetention === 'object') ? incoming.outputsRetention : {})
// ---- LLM(渠道/Key 的未知字段原样保留)----
const incLlm = (incoming.llm && typeof incoming.llm === 'object') ? incoming.llm : null
const llm = wMigrateLlm(prev.llm || {})
if (incLlm && Array.isArray(incLlm.providers)) {
// 渠道结构保存:__KEEP__ 保留原 key 值;models 记录默认标记
const llmPrev = wMigrateLlm(prev.llm || {})
llm.providers = incLlm.providers.map((p, pi) => {
const pid = p.id || ('l' + pi)
const oldP = llmPrev.providers.find((x) => x.id === pid) || llmPrev.providers[pi] || {}
const oldKeys = {}
for (const k of (oldP.keys || [])) oldKeys[k.id] = k
const keys = (p.keys || []).map((k, ki) => {
const kid = k.id || ('lk' + pi + '_' + ki)
const oldK = oldKeys[k.id] || oldKeys[kid] || {}
const value = keepOrInput(
k.value, oldK.value,
'llm.providers.' + pid + '.keys.' + kid + '.value',
'LLM 渠道「' + (p.name || pid) + '」的 Key',
true,
)
return Object.assign({}, oldK, wStripDerived(k), { id: kid, name: k.name || ('Key ' + (ki + 1)), value })
})
return Object.assign({}, oldP, wStripDerived(p), {
id: pid, name: p.name || ('渠道 ' + (pi + 1)), baseUrl: (p.baseUrl || '').trim(), fallbacks: (p.fallbacks || []).map((u) => String(u || '').trim()).filter(Boolean),
keys,
models: (p.models || []).filter((m) => m && m.name).map((m) => ({ name: String(m.name).trim(), default: !!m.default })),
defaultModel: (p.defaultModel || '').trim(),
})
})
// v3.0.5:`incLlm.providers` 可能是**空数组**(用户没有配任何 LLM 渠道时的备份/设置草稿),
// 旧代码在这里直接取 `llm.providers[0].id` ⇒ TypeError ⇒ 整个设置还原失败("还原不回来"的第三种形态)。
llm.defaultProviderId = incLlm.defaultProviderId || (llm.providers[0] && llm.providers[0].id) || ''
if (incLlm.defaultInstruction !== undefined) llm.defaultInstruction = String(incLlm.defaultInstruction || '')
} else if (incLlm) {
// 旧格式保存(兼容外部调用):先确保至少有一个渠道对象,避免 providers 为空时崩溃
if (!llm.providers.length) llm.providers = [{ id: 'l0', name: '默认渠道', baseUrl: '', fallbacks: [], keys: [], models: [], defaultModel: '' }]
if (incLlm.baseUrl !== undefined) llm.providers[0].baseUrl = String(incLlm.baseUrl || '')
if (incLlm.model !== undefined) llm.providers[0].defaultModel = String(incLlm.model || '')
if (Array.isArray(incLlm.models)) llm.providers[0].models = incLlm.models.map((m) => ({ name: String(m || '').trim(), default: String(m || '').trim() === incLlm.model }))
if (incLlm.defaultInstruction !== undefined) llm.defaultInstruction = String(incLlm.defaultInstruction || '')
const ak = keepOrInput(incLlm.apiKey, ((llm.providers[0].keys || [])[0] || {}).value, 'llm.apiKey', 'LLM Key(旧格式)', true)
if (ak) llm.providers[0].keys = [{ id: 'lk0_0', name: '默认', value: ak }]
}
const canvas = Object.assign(wClone(W_DEF_CANVAS), prev.canvas || {}, (incoming.canvas && typeof incoming.canvas === 'object') ? incoming.canvas : {})
const webhook = Object.assign(wClone(W_DEF_WEBHOOK), prev.webhook || {}, (incoming.webhook && typeof incoming.webhook === 'object') ? incoming.webhook : {})
// ---- 访问口令(Web 本地模式没有服务端口令,但备份里可能带:按同一套 __KEEP__ 语义解析,保证往返一致)----
const storedSec = (stored.security && typeof stored.security === 'object' && !Array.isArray(stored.security)) ? stored.security : {}
const secIn = (incoming.security && typeof incoming.security === 'object' && !Array.isArray(incoming.security)) ? incoming.security : null
let security = Object.assign({}, storedSec)
if (secIn) {
security = Object.assign(security, wClone(secIn))
security.password = keepOrInput(secIn.password, storedSec.password, 'security.password', '访问口令')
delete security.hasPassword
}
// ---- 组装:磁盘原对象起底(未知字段保留)+ 本版本认识的规范化分区 ----
const next = Object.assign({}, stored, { providers, imageTransfer: it, outputsRetention, llm, canvas, webhook })
if (secIn) {
// 只有在**显式**送来了 security 时才落盘(设置弹窗每次都送)。
// 空口令 = 本机没有口令:不写 `security: {password: ''}` 这种噪音(也等价于显式清空)。
const secOut = Object.assign({}, security)
if (!secOut.password) delete secOut.password
if (Object.keys(secOut).length) next.security = secOut
else delete next.security
}
// 未识别字段:既保留磁盘上的,也保留这次传进来的("以后新增设置又被吃掉"的防线)
for (const k of Object.keys(incoming)) {
if (W_CFG_CANONICAL_KEYS[k]) continue
next[k] = wClone(incoming[k])
}
const ok = lsSet(StorageContract.localKeys.config, next)
return storageResult(ok, ok ? { missingKeep } : { error: '浏览器本地存储空间不足,设置未能保存。', missingKeep })
}
// IndexedDB:历史出图(dataURL)存储
// 生产:直接复用 src/storage-runtime.js 的运行时实例(唯一真实现)。
// 兜底实现已收编到 src/storage-fallback-indexeddb.js(P2-10);单文件模式(未加载 src 模块)
// 回退为等价空实现:本环境无 IndexedDB ⇒ 所有方法均为无副作用空返回,与收编前一致。
const IDB = (() => {
const runtime = storageRuntime()
if (runtime && runtime.indexedDb) return runtime.indexedDb
const Factory = (typeof window !== 'undefined' && window.IWBStorageFallbackIndexeddb) || null
if (Factory && typeof Factory.create === 'function') return Factory.create({ contract: StorageContract.indexedDb })
return {
put() { return Promise.resolve(false) },
get() { return Promise.resolve(null) },
del() { return Promise.resolve(true) },
keys() { return Promise.resolve([]) },
logPut() { return Promise.resolve(false) },
logAll() { return Promise.resolve([]) },
logClear() { return Promise.resolve(true) },
imagesAll() { return Promise.resolve([]) },
kvPut() { return Promise.resolve(false) },
kvGet() { return Promise.resolve(null) },
}
})()
// ---- 方案A(对标 opentu):图片 Blob 存 Cache Storage + 元数据 + SW 虚拟路径 /__iwb_cache__/ ----
// 不再把大 base64 塞 localStorage/IndexedDB;Cache Storage 配额大且刷新后稳定,修复「图片节点刷新后消失」。
const CACHE_PREFIX = '/__iwb_cache__/'
const CACHE_NAME = 'iwb-images-local'
// ==== 丙方案 C3:图片引用直出(hydrate 不再把图片字节读回 base64 常驻 JS 堆)====
// 画布记录里只留引用,字节独立存放(对标 opentu 的资产模型:记录 = 引用 + 元数据):
// · { __cache: '/__iwb_cache__/<hash>' } —— 方案A 既有形态;字节在 Cache Storage,sw.js 可直出虚拟路径
// · { __blob: 'imgblob_<hash>_<len>' } —— C3 新形态;字节落在**注入的 idb 后端**(src/image-blob-store.js):
// 浏览器 = IndexedDB;桌面端 = storage-file 的文件 KV(见 wImageBlobStore 的 storageRuntime 注入)⇒
// 实际是 images/canvas/<sha16>.<ext> + data.json 的 assets 登记。判读口径见 docs/standards/image-storage-map.md
// 显示层统一经 wResolveImg 解析为**本会话 objectURL**(caches.match / IDB.getBlob → wRegisterBlobUrl)。
// objectURL **单一归属**:一律由 wRegisterBlobUrl 创建并登记(拿得回原 Blob,绕开 CSP 对 fetch(blob:) 的拦截),
// 由 wImgUrlByRef 台账回收;**不调用** ImageBlobStore.resolveUrl/revokeAll —— 否则同一张图会有两套 URL
// 与两套回收时机(§8.2「不要两套并用」)。实例只在顶层创建一次,绝不在渲染路径里重复 create。
/* v3.25.10:**惰性绑定**运行时。
* 原来在模块初始化时就 create({ idb: IDB }):那一刻资料目录可能还没就绪,
* IDB 拿到的是浏览器/空实现运行时,于是图片字节写进了「不会落盘」的地方 ——
* 画布里留下 {__blob} 引用,images/ 里没有文件、data.json 里没有登记;
* 重启后引用解析不到 → 图片节点变占位图(用户实测)。现在按当前 runtime 懒绑定并按实例缓存。 */
let wImageBlobStoreCache = null
let wImageBlobStoreRuntime = null
function wImageBlobStore() {
try {
if (typeof window === 'undefined') return null
const Lib = window.IWBImageBlobStore
if (!Lib || typeof Lib.create !== 'function') return null
const rt = storageRuntime()
const idb = rt && rt.indexedDb
if (!idb || typeof idb.put !== 'function') return null
if (wImageBlobStoreCache && wImageBlobStoreRuntime === idb) return wImageBlobStoreCache
// v3.26.117:条数上限之外再给一层字节预算(96MB ≈ 20 张原图)。
// Blob 的后备存储不在 JS 堆里,诊断页看不见,但任务管理器里就是实打实的几百 MB。
wImageBlobStoreCache = Lib.create({ idb: idb, blobCacheMax: 120, blobCacheBytes: 64 * 1024 * 1024 })
wImageBlobStoreRuntime = idb
return wImageBlobStoreCache
} catch (e) { return null }
}
const IMG_BLOB_PREFIX = (function () { try { const S = wImageBlobStore(); return (S && S.PREFIX) ? String(S.PREFIX) : 'imgblob_' } catch (e) { return 'imgblob_' } })()
const wImgUrlByRef = new Map() // 引用键('b:'+blobKey / 'c:'+cacheUrl)→ objectURL
const wImgRefByUrl = new Map() // objectURL → 原引用对象(wBlobRefCache 被 FIFO 驱逐后仍能取回字节)
const wImgUrlPending = new Set() // 正在解析的引用键(幂等:渲染路径会反复调用)
const wImgUrlPendingPromise = new Map() // 引用键 → 解析完成的 Promise(供「等解析完再开预览」用)
const wImgUrlFailed = new Set() // 解析失败的引用键(**耗尽重试后**才进入;换画板/回收时清空)
// v3.87.63(丙方案§13④):把"永久负缓存"改为**有限次退避重试**。
// 根因:迁移是"同步换引用 + 异步写 Cache",启动解析常抢在落盘前 ⇒ 一次 MISS 就永久失败 ⇒
// **永久空图(必须刷新才恢复)** ✗。现改为最多 3 次、间隔 700/1400/2100ms 重试。
const wImgUrlTries = new Map() // 引用键 → 已重试次数(成功/耗尽时删除,故有界)
const W_IMG_URL_TRIES = 3
function wImgUrlRetry(key, v) {
const n = wImgUrlTries.get(key) || 0
if (n >= W_IMG_URL_TRIES) { wImgUrlTries.delete(key); wImgUrlFailed.add(key); return }
wImgUrlTries.set(key, n + 1)
setTimeout(() => { try { wImgUrlPending.delete(key); wEnsureImgUrl(v) } catch (e) { /* ignore */ } }, 700 * (n + 1))
}
let wImgUrlBumpTimer = null
function wIsBlobRef(v) { return !!(v && typeof v === 'object' && !Array.isArray(v) && typeof v.__blob === 'string' && v.__blob) }
function wIsCacheRef(v) { return !!(v && typeof v === 'object' && !Array.isArray(v) && typeof v.__cache === 'string' && v.__cache) }
function wIsFileRef(v) { const M = wFileRefMod(); return !!(M && M.is(v)) }
function wImgRefKey(v) {
if (wIsBlobRef(v)) return 'b:' + String(v.__blob)
if (wIsCacheRef(v)) return 'c:' + String(v.__cache)
if (wIsFileRef(v)) return 'f:' + String(v.__file)
return ''
}
// 一张画布上几十张图会在同一帧内陆续解析完成:合并成一次节点级重渲染(避免 N 次 setState)
function wImgUrlBump() {
if (wImgUrlBumpTimer) return
wImgUrlBumpTimer = setTimeout(() => {
wImgUrlBumpTimer = null
if (typeof wThumbBump === 'function') { try { wThumbBump() } catch (e) { /* ignore */ } }
}, 60)
}
// 引用 → 本会话 objectURL(幂等)。失败负缓存:避免渲染路径反复打 IDB / Cache Storage。
// 2026-10-20:新增「可等待」的解析(wImgUrlPendingPromise)——
// 预览类操作(双击放大)需要**拿到 URL 字符串**才能用,而 wResolveImg 对引用对象
// 首帧返回 ''(等解析完再 bump 重渲染)⇒ 预览会拿到空 src。
// ⇒ 这里把解析 Promise 存下来,供 wResolveImgAsync 等待。
function wEnsureImgUrl(v) {
const key = wImgRefKey(v)
if (!key) return
if (wImgUrlByRef.has(key) || wImgUrlPending.has(key) || wImgUrlFailed.has(key)) return
wImgUrlPending.add(key)
const job = wIsBlobRef(v)
? (wImageBlobStore() ? wImageBlobStore().getBlob(v.__blob) : Promise.resolve(null))
: (wIsFileRef(v) ? (wFileRefMod() || {}).readBlob(v.__file) : iwbCacheBlob(v.__cache))
// 解析 Promise 存进 wImgUrlPendingPromise ⇒ 供 wResolveImgAsync 等待(预览类操作需要 URL 字符串)
const p = Promise.resolve(job).then((blob) => {
wImgUrlPending.delete(key)
if (!blob) { wImgUrlRetry(key, v); return }
const url = wRegisterBlobUrl(blob)
if (!url) { wImgUrlRetry(key, v); return }
wImgUrlTries.delete(key)
wImgUrlByRef.set(key, url)
wImgRefByUrl.set(url, v)
wImgUrlBump()
return url
}).then((url) => (url || ''))
.catch(() => { wImgUrlPending.delete(key); wImgUrlFailed.add(key); return '' })
.finally(() => { wImgUrlPendingPromise.delete(key) })
wImgUrlPendingPromise.set(key, p)
}
// 等引用解析完成并返回 objectURL(2026-10-20)。
// 非引用(字符串)⇒ 原样返回;引用 ⇒ 触发解析并等待 ⇒ 返回 objectURL(失败返回 '')。
// 用途:预览/复制等**需要立即拿到 URL 字符串**的调用点(双击放大、复制图片)。
async function wResolveImgAsync(v) {
if (!v || typeof v !== 'object') return v
const key = wImgRefKey(v)
if (!key) return v
const hit = wImgUrlByRef.get(key)
if (hit) return hit
wEnsureImgUrl(v)
const p = wImgUrlPendingPromise.get(key)
if (!p) return ''
try { return await p } catch (e) { return '' }
}
// 回收:撤销这些引用的 objectURL,并允许后续重新解析(画板切换/降级/孤儿清理时调用)
function wReleaseImgUrls(refKeys) {
const list = refKeys ? Array.from(refKeys) : Array.from(wImgUrlByRef.keys())
for (const k of list) {
const key = String(k || '')
if (!key) continue
const url = wImgUrlByRef.get(key)
if (url) {
// e2e 探针(仅 __IWB_E2E__):只统计**真的撤销了一个在用 objectURL**。
// S14 的契约是"回画布库时打开标签的图一个都不回收",而回收本身没有任何可见副作用
//(图会静默重解析一次),只有计数能区分"该回收"和"不该回收"。
// 计"实际撤销"而不是"申请回收":孤儿清理会按 key 试探性申请一堆并不存在的 URL。
if (typeof window !== 'undefined' && window.__IWB_E2E__ === true) window.__IWB_E2E_URL_RELEASES__ = (window.__IWB_E2E_URL_RELEASES__ || 0) + 1
try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ }
wBlobRefDrop(url)
wImgRefByUrl.delete(url)
wImgUrlByRef.delete(key)
}
wImgUrlFailed.delete(key)
}
}
// 收集一棵数据里出现的全部引用键(回收 / 孤儿清理用)
function wCollectImgRefKeys(value, out) {
const acc = out || new Set()
if (!value) return acc
if (Array.isArray(value)) { for (const x of value) wCollectImgRefKeys(x, acc); return acc }
if (typeof value === 'object') {
const k = wImgRefKey(value)
if (k) { acc.add(k); return acc }
for (const f of Object.keys(value)) wCollectImgRefKeys(value[f], acc)
}
return acc
}
// 按需取真实字节(导出 / 发模型 / 转图床 / 写库兜底):**用完即弃**,绝不写回节点数据
async function wImgRefDataUrl(v) {
if (typeof v === 'string') return v
if (wIsBlobRef(v)) {
if (!wImageBlobStore()) return ''
try { return await wImageBlobStore().resolveDataUrl(v.__blob) } catch (e) { return '' }
}
if (wIsCacheRef(v)) { try { return (await iwbCacheRead(v.__cache)) || '' } catch (e) { return '' } }
// 本地文件引用:生成/预览时按需读盘(用完即弃,不复制字节)
if (wIsFileRef(v)) { const M = wFileRefMod(); try { return (M && await M.readDataUrl(v.__file)) || '' } catch (e) { return '' } }
return ''
}
// 生成参考图参数:在**发请求前**解析成真实字节(本地文件名原样透传,不含字节)
async function wResolveRefArgs(refs) {
const out = []
for (const r of (Array.isArray(refs) ? refs : [])) {
if (!r) continue
if (r.type === 'local') { out.push(r); continue }
const val = (typeof r.value === 'string') ? r.value : await wImgRefDataUrl(r.value)
if (val) out.push({ type: r.type, name: r.name, value: val })
}
return out
}
// 画布导出(.iwb.json):导出那一刻把图片引用还原成 base64(跨设备「带得走」),用完即弃
async function wResolveImagesForExport(nodes) {
const out = []
for (const n of (Array.isArray(nodes) ? nodes : [])) {
if (!n || !n.data) { out.push(n); continue }
const d = Object.assign({}, n.data)
for (const f of ['data', 'url']) {
const v = d[f]
if (v && typeof v === 'object') { const got = await wImgRefDataUrl(v); if (got) d[f] = got }
}
// 相册(outKind:'images'):items[].src 是引用对象,导出时同样还原成 base64
if (d.outKind === 'images' && Array.isArray(d.items)) {
d.items = await Promise.all(d.items.map(async (it) => {
if (!it || !it.src || typeof it.src !== 'object') return it
const got = await wImgRefDataUrl(it.src)
return got ? Object.assign({}, it, { src: got }) : it
}))
}
out.push(Object.assign({}, n, { data: d }))
}
return out
}
function wResolveImg(v) {
if (v && typeof v === 'object') {
// C3 引用直出(有 objectURL 就用,否则异步解析一次);2026-11-25 补 __file:相册只存路径,漏这个分支会让对象被 String 成 "[object Object]" ⇒ 相册的图在组合节点 / 参考图 / 图片节点里全空(生成不受影响,wImgRefDataUrl 早已支持读盘)
if (wIsBlobRef(v) || wIsCacheRef(v) || wIsFileRef(v)) {
const hit = wImgUrlByRef.get(wImgRefKey(v))
if (hit) return hit
wEnsureImgUrl(v)
// v3.87.64(丙方案§13②):**不再首帧返回 SW 虚拟路径** ✗
// 根因:冷启动(SW 尚未接管)时 /__iwb_cache__/… 会 404 ⇒ <img> onError ⇒ 回退**远端 4K**
// ⇒ 既浪费解码又可能显示错图。改为先返回空(React 省略 src ⇒ 不发请求),
// 待 wEnsureImgUrl 解析出 objectURL 后由 wImgUrlBump() 触发重渲染换图 ✓
return ''
}
// 旧版 __idb 引用:应已在 hydrate 阶段还原为 base64;此处兜底返回 null
if (v.__idb) return null
}
return v
}
// 廉价确定性缓存键:内容长度 + 首尾采样哈希(避免每次保存对整段大 base64 做 O(n) 循环,降低主线程 CPU)
function wCacheKeyOf(base64) {
const s = String(base64)
const n = s.length
let h = 5381
const step = Math.max(1, Math.floor(n / 256))
for (let i = 0; i < n; i += step) h = ((h << 5) + h + s.charCodeAt(i)) | 0
h = ((h << 5) + h + ((n << 1) & 0xffff)) | 0
const origin = (typeof location !== 'undefined' && location.origin) || (typeof self !== 'undefined' && self.location.origin) || ''
return origin ? new URL(CACHE_PREFIX + (h >>> 0).toString(36), origin).href : ''
}
const cacheDoneUrls = new Set()
async function iwbCacheWrite(base64) {
// 桌面端:Cache Storage 的虚拟路径 /__iwb_cache__/* 靠 Service Worker 直出,而桌面不注册 SW
// ⇒ 这条兜底只会产生"裂图"。直接判失败,让调用方保留原值/走文件通道。
if (wFileStoreOn()) return null
try {
if (typeof caches === 'undefined' || typeof caches.open !== 'function' || !base64 || String(base64).indexOf('data:') !== 0) return null
const url = wCacheKeyOf(base64)
if (!url) return null
if (cacheDoneUrls.has(url)) return { __cache: url } // 会话内已处理过,跳过重算/重写
const cache = await caches.open(CACHE_NAME)
const hit = await cache.match(url)
if (!hit) {
const parts = String(base64).split(',')
const mime = (parts[0] && parts[0].match(/data:([^;]+)/) || [])[1] || 'image/png'
let bytes
try { const bin = atob(parts[1]); bytes = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i) } catch (e) { return null }
const blob = new Blob([bytes], { type: mime })
await cache.put(url, new Response(blob, { headers: { 'Content-Type': mime, 'Cache-Control': 'no-store' } }))
}
cacheDoneUrls.add(url)
return { __cache: url }
} catch (e) { return null }
}
async function iwbCacheRead(url) {
try {
if (typeof caches === 'undefined' || typeof caches.open !== 'function') return null
const cache = await caches.open(CACHE_NAME)
const hit = await cache.match(url)
if (!hit) return null
const blob = await hit.blob()
return await new Promise((res) => { const fr = new FileReader(); fr.onload = () => res(String(fr.result || '')); fr.onerror = () => res(null); fr.readAsDataURL(blob) })
} catch (e) { return null }
}
// C3:Blob → dataURL(优先用模块实现,避免两份编解码代码;模块缺失时退回 FileReader)
// C3:同上但直接给 Blob —— 显示层用它换 objectURL、发模型/导出用它取真实字节,
// 不再经过「Cache → base64 字符串 → Blob」的往返(那正是 (string) 常驻堆的来源)。
// 页内 caches.match 不依赖 Service Worker 是否已接管,因此在 SW 尚未 controlling 的首访也成立。
async function iwbCacheBlob(url) {
try {
if (typeof caches === 'undefined' || typeof caches.open !== 'function' || !url) return null
await wAwaitCacheWrites() // C3 第2步:等在飞的 Cache 写入落地,避免读到「引用已存在、字节还没写」的中间态
const cache = await caches.open(CACHE_NAME)
const hit = await cache.match(url)
if (!hit) return null
return await hit.blob()
} catch (e) { return null }
}
// C3 第2步:Cache Storage 写入屏障。历史迁移(wMigrateLegacyCanvasBase64)是「同步把 localStorage 里的
// base64 换成 {__cache} 引用 + 异步把字节写进 Cache Storage」;启动时画板读取可能赶在写入落地之前 ⇒
// hydrate/按需取字节读到 MISS,显示端只好退回虚拟 URL(冷启动 SW 未接管时 404 → 回退远端原图)。
// 这里收集在飞的写入 Promise,读取方先等它们落地(带超时兜底,绝不因个别写入卡住而阻塞显示)。
let wPendingCacheWrites = []
let wCacheWriteBarrier = Promise.resolve()
function wTrackCacheWrite(pr) {
try { wPendingCacheWrites.push(Promise.resolve(pr).catch(() => null)) } catch (e) { /* ignore */ }
}
async function wAwaitCacheWrites(ms) {
try { await Promise.race([wCacheWriteBarrier, new Promise((r) => setTimeout(r, Number(ms) || 1500))]) } catch (e) { /* ignore */ }
}
// 跨标签页节点组同步广播(IDB 无 storage 事件,靠 BroadcastChannel 通知同机其他标签页刷新)
let groupsBC = null
try { if (typeof BroadcastChannel !== 'undefined') groupsBC = new BroadcastChannel('iwb_groups_sync') } catch (e) { /* ignore */ }
function bcNotifyGroups() { try { if (groupsBC) groupsBC.postMessage({ at: Date.now() }) } catch (e) { /* ignore */ } }
// 节点组领域适配器:模块优先,旧 IndexedDB/localStorage 实现作为单文件 fallback。
const ModularIndexedStore = typeof window !== 'undefined' && window.IWBStorageIndexedDB && typeof window.IWBStorageIndexedDB.create === 'function'
? window.IWBStorageIndexedDB.create({ contract: StorageContract.indexedDb })
: null
const ModularGroupStore = typeof window !== 'undefined' && window.IWBStorageGroups && ModularLocalStore
? window.IWBStorageGroups.create({ local: ModularLocalStore, indexedDb: ModularIndexedStore, groupsKey: StorageContract.localKeys.groups, groupGroupsKey: StorageContract.localKeys.groupGroups, indexedKey: StorageContract.indexedDb.groupsKey, migrations: StorageMigrations, schemaVersion: SchemaVersions.groups })
: null
const GroupStore = {
async read() {
if (ModularGroupStore) {
const modular = await ModularGroupStore.read()
if (modular && modular.ok) return modular.value
}
const migrate = StorageMigrations && StorageMigrations.migrateGroups
const kv = await IDB.kvGet(StorageContract.indexedDb.groupsKey)
if (kv && migrate) {
const migrated = migrate(kv)
if (migrated.ok) {
if (migrated.changed) await IDB.kvPut(StorageContract.indexedDb.groupsKey, migrated.value)
return migrated.value
}
}
const legacy = { groups: lsGet(StorageContract.localKeys.groups, []), groupGroups: lsGet(StorageContract.localKeys.groupGroups, []) }
const migrated = migrate ? migrate(legacy) : { ok: true, value: legacy, changed: false }
if (migrated.ok) { if (migrated.changed) await IDB.kvPut(StorageContract.indexedDb.groupsKey, migrated.value); return migrated.value }
return { schemaVersion: SchemaVersions.groups, groups: [], groupGroups: [] }
},
async write(groups, groupGroups) {
if (ModularGroupStore) {
const modular = await ModularGroupStore.write(groups, groupGroups)
if (modular && modular.ok) { bcNotifyGroups(); return { ok: true, degraded: !!modular.degraded } }
}
const data = { schemaVersion: SchemaVersions.groups, groups: Array.isArray(groups) ? groups : [], groupGroups: Array.isArray(groupGroups) ? groupGroups : [] }
const okIdb = await IDB.kvPut(StorageContract.indexedDb.groupsKey, data)
const okLs1 = lsSet(StorageContract.localKeys.groups, data.groups)
const okLs2 = lsSet(StorageContract.localKeys.groupGroups, data.groupGroups)
bcNotifyGroups()
const ok = okIdb || (okLs1 && okLs2)
return StorageContract.result(ok, { degraded: !okIdb && okLs1 && okLs2, error: ok ? undefined : '节点组保存失败:浏览器本地存储不可用。' })
},
}
// 节点组持久化兼容函数:保留旧内部命名,逐步迁移调用方。
async function wLoadGroups() { return GroupStore.read() }
// 只准备节点组快照副本:绝不触碰当前画布节点或 React state。
// 收藏快照落库前:**不压缩图片**,只把大图(>3000 字符的 dataURL)换成引用形态({__blob}/{__cache}/{__idb})。
// 与「保存画布」遵循同一条规则(wRefValueAsync → wImgRefWrite 是唯一实现):localStorage/IDB 只留结构与引用,
// 图片本体在 Cache Storage / IDB;实例化与备份导出前用 hydrateGroupSnapshot 还原成 base64。
async function prepareGroupSnapshotForStorage(snapshot) {
if (!snapshot || !Array.isArray(snapshot.nodes)) return snapshot
const nodes = await Promise.all(snapshot.nodes.map(async (n) => {
if (!n || !n.data) return n
const data = Object.assign({}, n.data)
let changed = false
for (const f of ['data', 'url']) {
const v = data[f]
if (!isBigDataUrl(v)) continue
const ref = await wRefValueAsync(v, n.id || 'g', f)
if (ref !== v) { data[f] = ref; changed = true }
}
return changed ? { ...n, data } : n
}))
return { ...snapshot, nodes }
}
// 反向:把收藏快照里的引用还原成 base64(实例化到画布、导出备份前使用)。
// 读不到时保留引用(显示端 wResolveImg 的虚拟 URL 仍可用),与画布 hydrate 同一范式。
async function hydrateGroupSnapshot(snapshot) {
if (!snapshot || !Array.isArray(snapshot.nodes)) return snapshot
const nodes = []
for (const n of snapshot.nodes) {
if (!n || !n.data) { nodes.push(n); continue }
const data = Object.assign({}, n.data)
let changed = false
for (const f of ['data', 'url']) {
const v = data[f]
if (!v || typeof v !== 'object' || (!v.__idb && !v.__cache && !wIsBlobRef(v))) continue
// C3 第2步:hydrate 不再产出 base64,这里改为「按需解析」——实例化/备份导出仍然拿到真实字节
const got = await wImgRefDataUrl(v)
if (got) { data[f] = got; changed = true }
}
nodes.push(changed ? { ...n, data } : n)
}
return { ...snapshot, nodes }
}
// 组批量处理:顺序执行,避免一次并发多张大图的解码/编码造成内存尖峰
async function mapGroupsSeq(groups, fn) {
const out = []
for (const g of (Array.isArray(groups) ? groups : [])) out.push(await fn(g))
return out
}
async function wSaveGroups(groups, groupGroups) { return GroupStore.write(groups, groupGroups) }
// 轻量操作日志(IndexedDB logs store,保留 7 天;出错可回溯)
// logAll() 会读整个 logs store;每次保存都读一遍在日志较多/频繁保存时很贵。7 天过期清理节流到 ≤5min 一次。
let _logCleanLast = 0
// 日志系统自监控(2026-10-20):此前 IDB 写日志失败被 `.catch(() => {})` 静默吞掉
// ⇒ **日志系统自己坏了也是静默的**(配额满 / 隐私模式 / schema 变更),
// 使用者会以为「一切正常」,实际上已瞎。
// 现在:首次失败时留一条面包屑(CrashLog)+ 给用户一次可见提示(见 wLogFailed)。
let _wLogFailed = false
function wLogFailed(reason) {
if (_wLogFailed) return
_wLogFailed = true
try {
if (CrashLog && typeof CrashLog.breadcrumb === 'function') CrashLog.breadcrumb('log-unavailable', String(reason || '').slice(0, 120))
} catch (e) { /* ignore */ }
// 日志写不进去时,让用户知道「诊断日志已失效」——用画布注入的通知槽(与导入失败同一机制),
// 保证可见;只在**首次**失败时提示一次,不打扰日常。
try { wLogNotice('诊断日志暂时无法写入(浏览器存储不可用),本次操作记录不会保存。', 'err') } catch (e) { /* ignore */ }
}
// v3.25.80:收集所有画布引用到的图片文件名(给 legacy 清理用;放在 Workbench 外,避免组件行数上涨)
function wCollectRefImageNames (workspaces) {
const keep = []
try {
for (const ws of (workspaces || [])) {
const txt = JSON.stringify(ws && ws.nodes ? ws.nodes : [])
const m = txt.match(/[0-9a-f]{8,32}\.(?:png|jpe?g|webp|gif)/g)
if (m) for (const x of m) keep.push(x)
}
} catch (e) { /* ignore */ }
return keep
}
function wLog(kind, msg, detail) {
try {
const now = Date.now()
if (now - _logCleanLast > 5 * 60 * 1000) {
_logCleanLast = now
IDB.logAll().then((list) => {
const stale = (list || []).filter((x) => now - (x.at || 0) > 7 * 86400e3)
if (stale.length) stale.forEach((x) => { try { IDB.logPut({ id: x.id, at: 0, _del: true }) } catch (e) { /* ignore */ } })
}).catch((e) => { wLogFailed('logAll:' + String((e && e.message) || e)) })
}
// ⚠️ 存储契约:`IDB.logPut` 失败时**不会 reject**,而是用「结果对象」表示失败 ——
// 三种实现的失败形态**各不相同**(都实测过):
// ① src/storage-indexeddb.js(生产主路径)→ resolve `{ ok:false, error }`
// ② src/storage-fallback-indexeddb.js(兜底)→ resolve `false`(裸布尔)
// ③ app.js 内联空实现(无 IndexedDB 兜底)→ resolve `false`(裸布尔)
// ⇒ 只挂 `.catch()` 是**抓不到**失败的;且只判 `r.ok === false` 也会漏掉 ②③。
// 必须**同时**判「结果为 falsy」与「结果为 ok:false」。
// 这正是「日志系统自己坏了却静默」的根因:此处曾经只有 `.catch(() => {})`。
IDB.logPut({ id: now + '-' + Math.random().toString(36).slice(2, 7), at: now, kind: String(kind || 'info'), msg: String(msg || ''), detail: detail ? String(detail).slice(0, 300) : '' })
.then((r) => {
if (r === false || r === null || r === undefined || (r && r.ok === false)) {
wLogFailed('logPut:' + String((r && r.error && (r.error.message || r.error.code)) || 'failed'))
}
})
.catch((e) => { wLogFailed('logPut:' + String((e && e.message) || e)) })
} catch (e) { wLogFailed('sync:' + String((e && e.message) || e)) }
}
// ── 帧率探针(诊断用,默认关闭)──────────────────────────────────────────
// 打开方式:把下面常量改 true 后本地构建一次。每 6 秒把 rAF 帧间隔分位值写进
// 数据目录的 _boot.log(kind=perf),用来判断「卡」是 JS 还是渲染/合成。
const PERF_PROBE = false
if (PERF_PROBE && typeof requestAnimationFrame === 'function') {
(function () {
let last = 0
let deltas = []
let lastLog = Date.now()
const tick = () => {
const now = performance.now()
if (last) deltas.push(now - last)
last = now
if (Date.now() - lastLog > 1500 && deltas.length) {
const d = deltas.slice().sort((a, b) => a - b)
const at = (q) => d[Math.min(d.length - 1, Math.floor(d.length * q))].toFixed(1)
const over = deltas.filter((x) => x > 32).length
const view = typeof document !== 'undefined' && document.querySelector('.iwb-view-canvas') ? 'canvas' : 'other'
const line = 'PERF f=' + deltas.length + ' p50=' + at(0.5) + ' p95=' + at(0.95) + ' max=' + d[d.length - 1].toFixed(1) + ' >32=' + over + ' ' + view
try {
let hud = document.getElementById('iwb-perf-hud')
if (!hud) {
hud = document.createElement('div')
hud.id = 'iwb-perf-hud'
hud.style.cssText = 'position:fixed;top:6px;right:8px;z-index:99999;background:#111;color:#0f0;font:12px/1.3 ui-monospace,monospace;padding:4px 8px;border-radius:6px;pointer-events:none'
document.body.appendChild(hud)
}
hud.textContent = line
} catch (e) { /* ignore */ }
try { wLog('perf', line) } catch (e) { /* ignore */ }
deltas = []
lastLog = Date.now()
}
requestAnimationFrame(tick)
}
requestAnimationFrame(tick)
})()
}
// 直连兼容:解析 provider/key
function wResolveKey(providerId, keyGroupId) {
const cfg = wRawCfg()
const fromCfg = (cfg.providers || []).find((pr) => pr.id === providerId)
const fromPlugin = fromCfg ? null : wPluginProviders.find((pr) => pr.id === providerId)
const provider = fromCfg || fromPlugin || cfg.providers[0]
if (!provider) throw new Error('未配置服务(左侧栏 → 设置)')
const key = fromPlugin
? { id: 'plugin-key', value: String((fromPlugin.keys && fromPlugin.keys[0] && fromPlugin.keys[0].value) || '') }
: ((provider.keys || []).find((k) => k.id === keyGroupId) || (provider.keys || [])[0])
if (!fromPlugin && (!key || !key.value)) throw new Error('未配置该 Key 分组(设置 → 生图服务)')
const norm = (u) => (_wCfgShape && _wCfgShape.normalizeEndpointBase) ? _wCfgShape.normalizeEndpointBase(u) : String(u || '').trim()
const baseUrl = norm(provider.baseUrl)
// 备用地址(2026-11-24,v3.26.65):此前 fallbacks 只给 LLM 用,生图永远只打主地址。
// 这里统一成候选列表:主地址优先,其余去重去空。
const addrs = []
for (const u of [baseUrl].concat((provider.fallbacks || []).map(norm))) {
if (u && addrs.indexOf(u) < 0) addrs.push(u)
}
return {
provider, key, baseUrl, addrs,
genPath: provider.genPath || '/images/generations',
editPath: provider.editPath || '/images/edits',
auth: provider.auth || null,
}
}
// 端点与鉴权工具(2026-11-24):genPath 生效 + auth 四态 + 地址候选。两处(生图/分层)共用。
function wEndpointTools(genPath, auth, keyValue) {
const EP = (typeof window !== 'undefined' && window.IWBGenerationEndpoint) ? window.IWBGenerationEndpoint : null
const endpointOf = (base) => EP ? EP.joinEndpoint(base, genPath) : String(base || '') + (genPath || '/images/generations')
const headersOf = (extra) => EP ? EP.buildAuthHeaders(auth, keyValue, extra || {}) : Object.assign({}, extra || {}, { Authorization: 'Bearer ' + keyValue })
const urlOf = (base) => EP ? EP.applyAuthQuery(endpointOf(base), auth, keyValue) : endpointOf(base)
return { endpointOf, headersOf, urlOf }
}
function wApiError(message, type, status) {
const e = new Error(message || '请求失败')
e.iwbType = type || 'unknown'
e.status = status || 0
return e
}
function classifyHttpError(status) {
if (status === 401) return 'auth'
if (status === 403) return 'permission'
if (status === 400 || status === 422) return 'param'
if (status === 408 || status === 499) return 'unknown'
if (status === 429) return 'limit'
if (status >= 500) return 'server'
return 'unknown'
}
async function wFetch(url, opts, timeoutMs) {
const ext = opts && opts.signal
const softTimeout = !!(opts && opts.softTimeout)
const onSoftTimeout = opts && opts.onSoftTimeout
if (RuntimeFetch && typeof RuntimeFetch.request === 'function') {
try {
return await RuntimeFetch.request(url, { init: opts || {}, signal: ext, timeoutMs: timeoutMs || 240000, abortOnTimeout: !softTimeout, onSoftTimeout, metrics: RuntimeMetrics })
} catch (e) {
if (e && e.iwbType === 'cancelled') throw wApiError('生成已取消', 'cancel')
if (e && e.iwbType === 'timeout') throw wApiError('请求超时:浏览器已停止等待,服务商结果未知', 'timeout')
throw wApiError('网络连接中断', 'network')
}
}
const ctrl = new AbortController()
let timedOut = false
const timer = setTimeout(() => {
timedOut = true
if (typeof onSoftTimeout === 'function') {
try { onSoftTimeout({ timeoutMs: timeoutMs || 240000 }) } catch (e) {
// 软超时通知抛错:超时仍会照常处理(下面照常 abort),但**用户没收到提示** ⇒ 留痕。
try { if (CrashLog && typeof CrashLog.record === 'function') CrashLog.record('soft-timeout-notify-error', { scope: 'generate', message: String((e && e.message) || e), version: APP_VERSION }) } catch (err) { /* ignore */ }
}
}
if (!softTimeout) ctrl.abort()
}, timeoutMs || 240000)
// 外部取消信号(删除/停用节点时中止生成请求):转发到内部 controller
const onExtAbort = () => ctrl.abort()
if (ext) {
if (ext.aborted) ctrl.abort()
else ext.addEventListener('abort', onExtAbort, { once: true })
}
try {
return await fetch(url, Object.assign({}, opts || {}, { signal: ctrl.signal }))
} catch (e) {
if (e && e.name === 'AbortError') {
if (ext && ext.aborted) throw wApiError('生成已取消', 'cancel')
throw wApiError('请求超时:浏览器已停止等待,服务商结果未知', 'timeout')
}
throw wApiError('网络连接中断', 'network')
} finally {
clearTimeout(timer)
if (ext) { try { ext.removeEventListener('abort', onExtAbort) } catch (e) { /* ignore */ } }
}
}
function wApiErr(parsed) {
const e = parsed && (parsed.error || parsed.message)
return e ? (typeof e === 'string' ? e : JSON.stringify(e).slice(0, 200)) : 'HTTP 请求失败'
}
async function wGenerate(args) {
const { key, provider, addrs, genPath, auth } = wResolveKey(args.providerId, args.keyGroupId)
// 端点/鉴权统一走 wEndpointTools(genPath 从此生效;鉴权支持 bearer/header/query/none)
const EP = (typeof window !== 'undefined' && window.IWBGenerationEndpoint) ? window.IWBGenerationEndpoint : null
const { headersOf, urlOf } = wEndpointTools(genPath, auth, key.value)
const jsonHeaders = () => headersOf({ 'Content-Type': 'application/json' })
const refs = (args.refs || []).filter((r) => r && r.value)
const badRef = refs.find((r) => {
const value = String(r.value || '').trim()
return !/^https?:\/\//i.test(value) && !/^data:image\/[^;]+;base64,/i.test(value)
})
if (badRef) throw wApiError('参考图格式不支持;仅允许公网 URL 或本地图片 Base64', 'param')
// v3.87.28:按「厂商分类」生成请求体(见 src/generation-request-shape.js)
// openai:像素 size(+ 下方 6 档 quality)
// gemini:size=比例("9x16") + quality=分辨率档("2k"),**不发像素、不发 6 档质量**
// doubao:像素 size(比例+档位)或 K 档字符串;显式 watermark:false
// custom:用户模板
const Shape = (typeof window !== 'undefined' && window.IWBGenerationRequestShape) || null
const modelEntry = (provider && Array.isArray(provider.models))
? provider.models.find((m) => m && String(m.name || m) === String(args.model || ''))
: null
const shapeKind = Shape ? Shape.resolveKind(args.model, provider && provider.kind, provider && provider.modelRules, modelEntry && modelEntry.kind) : 'openai'
const shapeTemplate = (provider && provider.requestShape && provider.requestShape.body) || null
const built = Shape ? Shape.buildGenerationBody({
kind: shapeKind, model: args.model, prompt: args.prompt, n: 1,
size: args.size, ratio: args.ratio, res: args.res, sizeMode: args.sizeMode,
responseFormat: 'url', template: shapeTemplate, watermark: args.watermark === true,
}) : null
const payload = built ? built.body : (() => {
// 兜底(模块未加载时):保持 v3.87.26 行为——自动/未指定不发 size
const b = { model: args.model, prompt: args.prompt, n: 1, response_format: 'url' }
if (args.size) b.size = args.size
return b
})()
// 质量三重闸门:① 档位不是「自动」 ② 该 服务商+模型 被判定支持 quality(你的显式设置 / 内置种子)
// ③ 没有被渠道拒绝过。任一不满足就**根本不发**(不白试一次;见 §13.28)。
const qualityWanted = (() => {
// 非 openai 族:quality 语义不同(gemini 族 quality 表示分辨率档,由策略模块写入)→ 不发我们的 6 档
if (shapeKind && shapeKind !== 'openai') return ''
const v = qualityOf({ quality: args.quality })
if (v === 'auto') return ''
if (!modelSupportsQuality(provider, args.model)) return ''
if (isQualityUnsupported(args.providerId, args.model)) return ''
return v
})()
if (qualityWanted) payload.quality = qualityWanted
const imgs = refs.map((r) => r.value).filter(Boolean)
if (imgs.length) payload.image = imgs.length === 1 ? imgs[0] : imgs
for (const hook of wPluginGenHooks) {
if (typeof hook.beforeRequest !== 'function') continue
try {
const patched = hook.beforeRequest(payload, { model: String(args.model || ''), providerId: String(args.providerId || ''), imageCount: imgs.length })
if (patched && typeof patched === 'object') Object.assign(payload, patched)
} catch (e) { /* 插件钩子异常不得影响生图 */ }
}
try { console.info('[iwb] generation submit', { endpoint: '/images/generations', model: String(args.model || ''), size: String(args.size || ''), imageCount: imgs.length, responseFormat: 'url' }) } catch (e) { /* diagnostics must not block submit */ }
try { if (CrashLog && CrashLog.breadcrumb) CrashLog.breadcrumb('gen-submit', String(args.model || '') + ' ' + String(args.size || '') + ' q=' + String(args.quality || 'auto') + ' imgs=' + imgs.length) } catch (e) { /* ignore */ }
// 硬上限计时器必须在整个「等响应头 → 读响应体 → 解析」期间存活,否则 body 卡住时无人收场。
const localCtrl = typeof AbortController === 'function' ? new AbortController() : null
const ext = args && args.signal
let hardTimedOut = false
const onExtAbort = () => { if (localCtrl) { try { localCtrl.abort() } catch (e) { /* ignore */ } } }
if (localCtrl && ext) { if (ext.aborted) onExtAbort(); else ext.addEventListener('abort', onExtAbort, { once: true }) }
const hardTimer = localCtrl ? setTimeout(() => { hardTimedOut = true; try { localCtrl.abort() } catch (e) { /* ignore */ } }, GEN_HARD_TIMEOUT_MS) : null
try {
let curBase = addrs[0] || ''
const post = (body) => wFetch(urlOf(curBase), { method: 'POST', headers: jsonHeaders(), body: JSON.stringify(body), signal: localCtrl ? localCtrl.signal : (args && args.signal), softTimeout: !!(args && args.softTimeout), onSoftTimeout: args && args.onSoftTimeout }, GEN_TIMEOUT_MS)
// 一次完整尝试(含 quality 降档)—— 地址级重试在外层循环,见下
const runOnce = async () => {
let resp = await post(payload)
let parsed = await resp.json().catch(() => null)
if (hardTimedOut) throw wApiError(genHardTimeoutMessage(), 'hard-timeout')
// 渠道不支持 quality:400/422 属 param(请求被拒绝 = 未生成、未计费)→ **有界**降级重试:
// ① max/xhigh 先降一档(max→xhigh→high),避免"选了最高档就把整个模型拉黑";
// ② 仍被拒 → 去掉该参数再试一次,并记住该 服务商+模型,之后不再发送。
// 最多额外 2 次请求;只在这两个状态下发生,绝不违反「结果未知不得自动重提(防重复计费)」。
if (!resp.ok && (resp.status === 400 || resp.status === 422) && payload.quality) {
const lower = QUALITY_DOWNGRADE[qualityOf({ quality: payload.quality })] || ''
if (lower) {
payload.quality = lower
resp = await post(payload)
parsed = await resp.json().catch(() => null)
if (hardTimedOut) throw wApiError(genHardTimeoutMessage(), 'hard-timeout')
}
if (!resp.ok && (resp.status === 400 || resp.status === 422) && payload.quality) {
markQualityUnsupported(args.providerId, args.model)
delete payload.quality
resp = await post(payload)
parsed = await resp.json().catch(() => null)
if (hardTimedOut) throw wApiError(genHardTimeoutMessage(), 'hard-timeout')
}
}
if (!resp.ok || !parsed || !(parsed.data && parsed.data[0])) throw wApiError(wApiErr(parsed), classifyHttpError(resp.status), resp.status)
const item = parsed.data[0]
if (!item || typeof item.url !== 'string' || !/^https?:\/\//i.test(item.url.trim())) {
const returnedBase64 = !!(item && (item.b64_json || item.data))
throw wApiError(returnedBase64 ? '上游返回了 Base64,而不是 URL;已拒绝保存,请检查模型或渠道是否支持 response_format=url' : '上游未返回有效图片 URL;已拒绝保存', 'param')
}
// v3.87.23 可观测:上游返回的尺寸明显小于请求尺寸时留痕(用于区分"我们的 bug"还是"上游不支持")。
// 例:模型名带 -1k 的变体、或需要 image_size/aspect_ratio 等其它字段的渠道,会忽略 size 直接出 1K。
try {
const req = /^(\d+)\s*[x×]\s*(\d+)$/.exec(String(args.size || '').trim())
const gw = Number(item.width) || 0, gh = Number(item.height) || 0
if (req && gw > 0 && gh > 0) {
const rw = Number(req[1]), rh = Number(req[2])
if (gw < rw * 0.9 || gh < rh * 0.9) {
if (CrashLog && typeof CrashLog.record === 'function') CrashLog.record('size-smaller', { scope: 'generate', message: '上游返回尺寸小于请求:' + String(args.model || '') + ' 请求 ' + rw + 'x' + rh + ' → 实际 ' + gw + 'x' + gh, version: APP_VERSION, extra: { requested: rw + 'x' + rh, got: gw + 'x' + gh } })
else if (CrashLog && typeof CrashLog.breadcrumb === 'function') CrashLog.breadcrumb('size-smaller', String(args.model || '') + ' ' + rw + 'x' + rh + '→' + gw + 'x' + gh)
}
}
} catch (e) { /* 观测失败不影响生成 */ }
return [{ ok: true, url: item.url.trim(), width: item.width || 0, height: item.height || 0 }]
}
// 地址回退(2026-11-24):主地址失败且「可安全重试」时换备用地址;循环在 src/generation-endpoint.js
if (!EP) return await runOnce()
return await EP.runWithAddresses(addrs, runOnce, (b) => { curBase = b })
} catch (e) {
// 硬超时优先:无论是等头还是读体被中止,都统一报「结果未知」,交给用户决定是否重试
if (hardTimedOut && !(e && e.iwbType === 'cancel')) throw wApiError(genHardTimeoutMessage(), 'hard-timeout')
throw e
} finally {
if (hardTimer !== null) clearTimeout(hardTimer)
if (ext) { try { ext.removeEventListener('abort', onExtAbort) } catch (e) { /* ignore */ } }
}
}
// ---------- 分层(seedream 图层分离)----------
// 计费实测(见 docs/archive/plans/seedream-layer-decomposition-analysis.md §13):
// 单层 ¥0.15(声明 1K) / ¥0.30(声明 2K),且**返回张数 = 清单层数 + 1**(多一张 z_index=0 的底层合成图,照样计费)。
// 所以预估费用必须是「(层数 + 1) × 单价」;返回 0 张不计费(失败/被内容拦截均为 ¥0)。
const LAYER_PROMPT_PREFIX = '将图片进行精确图层分离:'
const LAYER_PRICE_YUAN = { '1K': 0.15, '2K': 0.30 }
const LAYER_SIZE_KEYS = ['1K', '2K']
const layerSizeParam = (v) => (LAYER_SIZE_KEYS.indexOf(String(v || '')) >= 0 ? String(v) : '1K')
const layerPriceOf = (v) => LAYER_PRICE_YUAN[layerSizeParam(v)]
const layerPriceText = (v) => '¥' + layerPriceOf(v).toFixed(2)
// 清单行数 + 底层图 = 实际计费张数
const layerBillableCount = (layers, withBase) => {
const rows = (Array.isArray(layers) ? layers : []).filter((l) => l && String(l.name || '').trim()).length
return withBase === false ? rows : rows + 1
}
const layerEstimateYuan = (layers, sizeParam) => layerBillableCount(layers) * layerPriceOf(sizeParam)
// 清单 → 提示词:一行一层,带 bbox 的写成 <bbox>x1 y1 x2 y2</bbox>(像素坐标,原图尺寸)
function buildLayerPrompt(layers) {
const rows = (Array.isArray(layers) ? layers : []).map((l) => {
const name = String((l && l.name) || '').trim()
if (!name) return ''
const bb = (l && Array.isArray(l.bbox) && l.bbox.length === 4 && l.bbox.every((v) => Number.isFinite(Number(v)))) ? l.bbox : null
return bb ? (name + ' <bbox>' + bb.map((v) => Math.round(Number(v))).join(' ') + '</bbox>') : name
}).filter(Boolean)
return rows.length ? (LAYER_PROMPT_PREFIX + rows.join(',') + '。') : ''
}
// 上游报错 -> 可读文案(敏感内容拦截按「未生成、未计费」呈现)
function layerErrorText(message, fallback) {
const m = String(message || '')
if (/SensitiveContent|sensitive/i.test(m)) return '图片被判定为敏感内容,未生成图层(未计费);可更换图片后重试'
if (/could not be processed for layer decomposition/i.test(m)) return '这张图片无法被分层处理;请换一张内容更清晰的图片,或改用本地图片上传(Base64)'
if (/WIDTHxHEIGHT size is not supported/i.test(m)) return '分层只支持 1K / 2K 档位,不支持自定义尺寸'
return m || fallback || '分层请求失败'
}
async function wDecomposeLayers(args) {
const { key, provider, addrs, genPath, auth } = wResolveKey(args.providerId, args.keyGroupId)
const { headersOf, urlOf } = wEndpointTools(genPath, auth, key.value)
const jsonHeaders = () => headersOf({ 'Content-Type': 'application/json' })
const img = String((args && args.image) || '').trim()
if (!/^https?:\/\//i.test(img) && !/^data:image\/[^;]+;base64,/i.test(img)) {
throw wApiError('分层需要一张图片:仅允许公网 URL 或本地图片 Base64', 'param')
}
const prompt = String((args && args.prompt) || '').trim()
if (!prompt) throw wApiError('分层说明为空:请至少填写一层(或在提示词节点里写明分层要求)', 'param')
const payload = {
model: args.model,
prompt: prompt,
image: img, // 实测:字符串形态(URL 或 dataURL)都可用;字符串时不计「第 2 张起」的附加费
n: 1,
size: layerSizeParam(args.sizeParam),
response_format: 'url',
output_format: 'png',
layer_decomposition: true, // 布尔即为真(网关计费表达式对布尔与字符串 "true" 同样识别)
watermark: false,
// 注意:不发送 quality —— 那是生图参数,分层带上只会招 400
}
try { console.info('[iwb] layer submit', { endpoint: '/images/generations', model: String(args.model || ''), size: payload.size, imageKind: /^https?:/i.test(img) ? 'url' : 'base64' }) } catch (e) { /* diagnostics must not block submit */ }
const localCtrl = typeof AbortController === 'function' ? new AbortController() : null
const ext = args && args.signal
let hardTimedOut = false
const onExtAbort = () => { if (localCtrl) { try { localCtrl.abort() } catch (e) { /* ignore */ } } }
if (localCtrl && ext) { if (ext.aborted) onExtAbort(); else ext.addEventListener('abort', onExtAbort, { once: true }) }
const hardTimer = localCtrl ? setTimeout(() => { hardTimedOut = true; try { localCtrl.abort() } catch (e) { /* ignore */ } }, GEN_HARD_TIMEOUT_MS) : null
try {
let curBase = addrs[0] || ''
const postLayer = (body) => wFetch(urlOf(curBase), { method: 'POST', headers: jsonHeaders(), body: JSON.stringify(body), signal: localCtrl ? localCtrl.signal : (args && args.signal), softTimeout: !!(args && args.softTimeout), onSoftTimeout: args && args.onSoftTimeout }, GEN_TIMEOUT_MS)
const resp = await postLayer(payload)
const parsed = await resp.json().catch(() => null)
if (hardTimedOut) throw wApiError(genHardTimeoutMessage(), 'hard-timeout')
if (!resp.ok || !parsed) throw wApiError(layerErrorText(wApiErr(parsed), '分层请求失败'), classifyHttpError(resp.status), resp.status)
const list = Array.isArray(parsed.data) ? parsed.data : []
// 与生图不同:这里必须读**全部** data[](每层一张图),而不是 data[0]
const sizePx = (s) => { const m = /^(\d+)\s*[x×]\s*(\d+)$/.exec(String(s || '').trim()); return m ? { width: Number(m[1]), height: Number(m[2]) } : { width: 0, height: 0 } }
const layers = list.map((it, i) => {
const url = it && typeof it.url === 'string' ? it.url.trim() : ''
if (!url || !/^https?:\/\//i.test(url)) return null // 沿用「只接受 URL」的既有红线
const z = Number.isFinite(Number(it.z_index)) ? Number(it.z_index) : i
const bb = (it.bounding_box && Array.isArray(it.bounding_box.absolute) && it.bounding_box.absolute.length === 4)
? { absolute: it.bounding_box.absolute.map(Number), normalized: Array.isArray(it.bounding_box.normalized) ? it.bounding_box.normalized.map(Number) : null }
: null
const px = sizePx(it.size)
return {
ok: true,
url: url,
zIndex: z,
// z_index=0 是底层合成图:接口不带 name/description/bounding_box,这里补默认名
name: String(it.name || '').trim() || (z === 0 ? '底层合成图' : '图层 ' + z),
generated: !!String(it.name || '').trim(),
size: String(it.size || '').trim(),
width: px.width,
height: px.height,
bbox: bb,
description: String(it.description || '').trim(),
outputFormat: String(it.output_format || 'png'),
}
}).filter(Boolean)
if (!layers.length) {
const anyB64 = list.some((it) => it && (it.b64_json || it.data))
throw wApiError(anyB64 ? '上游返回了 Base64,而不是 URL;已拒绝保存' : '上游未返回有效图层 URL;已拒绝保存', 'param')
}
layers.sort((a, b) => (a.zIndex - b.zIndex))
return layers
} catch (e) {
if (hardTimedOut && !(e && e.iwbType === 'cancel')) throw wApiError(genHardTimeoutMessage(), 'hard-timeout')
throw e
} finally {
if (hardTimer !== null) clearTimeout(hardTimer)
if (ext) { try { ext.removeEventListener('abort', onExtAbort) } catch (e) { /* ignore */ } }
}
}
// 分层节点的输入解析(与生图同一套图源语义):
// 图片 = 直连的「图片」节点 + 经「中继」透传的图片 + 相连文本节点(提示词/文本/组合/连接)自身携带的参考图;
// 文本 = 相连文本节点解析出的文本(专家模式:写了就用它当分层说明,覆盖节点内的清单)。
function layerInputsOf(node, nodesArr, edgesArr) {
const nodes = Array.isArray(nodesArr) ? nodesArr : []
const edges = Array.isArray(edgesArr) ? edgesArr : []
const byId = new Map(nodes.map((n) => [n.id, n]))
const incoming = edges.filter((e) => e.to === node.id).map((e) => byId.get(e.from)).filter(Boolean)
const refNodes = []
for (const src of incoming) {
if (!src || (src.data && src.data.enabled === false)) continue
if (src.type === 'ref') { refNodes.push(src); continue }
for (const rn of nodeRefsOf(src, edges, nodes, new Set())) refNodes.push(rn)
}
const refs = orderedUniqueRefNodes(refNodes).flatMap(refArgsOf).filter((a) => a && (a.value || a.name))
let text = ''
try {
const tasks = cachedGenerationTasks(node, nodes, edges)
if (tasks && tasks.length) text = String(tasks[0].text || '').trim()
} catch (e) { /* 解析失败按「无文本来源」处理:回退到节点内清单 */ }
return { refs: refs, refCount: refs.length, text: text }
}
// 分层只需要 1 张图(第 2 张起 ¥0.02/张且对分层无意义):按画布顺序取第一张,URL 优先、本地图退 Base64
function layerImageValue(inputs) {
const list = (inputs && inputs.refs) || []
const pick = list.find((r) => r && r.type === 'url' && r.value) || list.find((r) => r && r.type === 'data' && r.value) || list.find((r) => r && r.value)
return pick && pick.value ? String(pick.value) : ''
}
// 分层节点的模型选项来源:当前服务商的 layerModels(已归一化:内置项永远在列且可见)。
// 与生图模型清单隔离——生图清单常被当成"随便加的模型名",直接复用会把分层节点搞坏(规范 §13.26)。
function layerModelPoolOf(provider) {
return wNormalizeLayerModels(provider && provider.layerModels)
}
// 默认渠道的 baseUrl / 第一个有效 Key / 默认模型(润色运行时用)
// 单渠道解析(baseUrl / 备用地址 / 第一个有效 Key / 默认模型)
function wLlmResolveProv(prov) {
if (!prov) return null
const key = (prov.keys || []).find((k) => k.value) || (prov.keys || [])[0]
const defM = (prov.models || []).find((m) => m && m.default && m.name)
const firstM = (prov.models || [])[0]
const model = String((prov.defaultModel || (defM && defM.name) || (firstM && firstM.name)) || '').trim()
const addrs = [(_wCfgShape && _wCfgShape.normalizeEndpointBase ? _wCfgShape.normalizeEndpointBase(prov.baseUrl) : String(prov.baseUrl || '').trim())].concat((prov.fallbacks || []).filter((u) => u && String(u).trim()).map((u) => (_wCfgShape && _wCfgShape.normalizeEndpointBase ? _wCfgShape.normalizeEndpointBase(u) : String(u).trim()))).filter((u) => u)
return { baseUrl: addrs[0] || '', addrs, key: key && key.value ? String(key.value) : '', model, prov }
}
async function wLlm(args) {
const cfg = wRawCfg()
const llm = cfg.llm || {}
const provs = llm.providers || []
if (!provs.length) throw new Error('未配置 LLM 渠道(设置 → LLM 服务)')
const instruction = String((args && args.instruction) || '').trim() || String(llm.defaultInstruction || '').trim()
const prompt = String((args && args.prompt) || '').trim()
// 渠道顺序:默认渠道优先,其全部地址不可用时按顺序尝试其他渠道(网络/超时/服务端错误类;参数/认证/额度直接抛)
const defIdx = Math.max(0, provs.findIndex((p) => p.id === llm.defaultProviderId))
const ordered = [provs[defIdx]].concat(provs.filter((_, i) => i !== defIdx))
let lastErr = null
for (const prov of ordered) {
const r = wLlmResolveProv(prov)
if (!r || !r.addrs.length) { lastErr = lastErr || new Error('渠道「' + (prov.name || '') + '」未配置地址'); continue }
if (!r.key) { lastErr = lastErr || new Error('渠道「' + (prov.name || '') + '」未配置 Key'); continue }
// 默认渠道可用节点内「本次润色模型」覆盖;跨渠道切换时用该渠道默认模型(避免使用不存在的模型)
const model = (args && args.model && prov.id === ordered[0].id) ? String(args.model).trim() : r.model
for (const ab of r.addrs) {
try {
const resp = await wFetch(ab + '/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + r.key },
body: JSON.stringify({ model: model || 'gpt-4o-mini', messages: [{ role: 'system', content: instruction }, { role: 'user', content: prompt }], max_tokens: 1024 }),
}, 60000)
const parsed = await resp.json().catch(() => null)
if (!resp.ok) throw wApiError(wApiErr(parsed), classifyHttpError(resp.status), resp.status)
const text = parsed && parsed.choices && parsed.choices[0] && parsed.choices[0].message && parsed.choices[0].message.content
return { text: String(text || '') }
} catch (e) {
lastErr = e
const type = (e && e.iwbType) || ''
if (type === 'param' || type === 'auth' || type === 'limit') throw e
// 网络/超时/服务端错误 → 继续下一地址/下一渠道
}
}
}
throw lastErr || new Error('润色失败:所有渠道/地址均不可用')
}
// LLM 渠道测试(设置面板用):内部读取明文 Key,前端不回显;先 /models 验证连接与 Key,再按需用所选模型发最小请求验证
async function wLlmTest(args) {
const cfg = wRawCfg()
const llm = cfg.llm || {}
const prov = (llm.providers || []).find((p) => p.id === (args && args.providerId)) || (llm.providers || [])[0]
if (!prov) throw new Error('渠道不存在')
const keyObj = (prov.keys || []).find((k) => k.id === (args && args.keyId)) || (prov.keys || []).find((k) => k.value) || (prov.keys || [])[0]
if (!keyObj || !keyObj.value) throw new Error('该渠道未配置 Key')
const addrs = [(_wCfgShape && _wCfgShape.normalizeEndpointBase ? _wCfgShape.normalizeEndpointBase(prov.baseUrl) : String(prov.baseUrl || '').trim())].concat((prov.fallbacks || []).filter((u) => u && String(u).trim()).map((u) => (_wCfgShape && _wCfgShape.normalizeEndpointBase ? _wCfgShape.normalizeEndpointBase(u) : String(u).trim()))).filter((u) => u)
if (!addrs.length) throw new Error('该渠道未填 Base URL / 备用地址')
const defM2 = (prov.models || []).find((m) => m && m.default && m.name)
const firstM2 = (prov.models || [])[0]
const model = String(((args && args.model) || prov.defaultModel || (defM2 && defM2.name) || (firstM2 && firstM2.name)) || '').trim()
const mode = (args && args.mode) || 'single'
const targets = mode === 'all' ? addrs : addrs.slice(0, 1)
const results = []
for (const ab of targets) {
const t0 = Date.now()
try {
const resp = await wFetch(ab + '/models', { headers: { Authorization: 'Bearer ' + keyObj.value } }, 20000)
const parsed = await resp.json().catch(() => null)
if (!resp.ok || !parsed || !Array.isArray(parsed.data)) {
const em = (parsed && (parsed.error && (parsed.error.message || parsed.error.type) || parsed.message)) || ('HTTP ' + resp.status + '(' + classifyHttpError(resp.status) + ')')
results.push({ url: ab, ok: false, ms: Date.now() - t0, error: em })
continue
}
results.push({ url: ab, ok: true, ms: Date.now() - t0, models: parsed.data.length })
} catch (e) {
results.push({ url: ab, ok: false, ms: Date.now() - t0, error: String((e && e.message) || e) })
}
}
// 单地址模式且指定模型:用主地址做模型级调用验证
let modelTest = null
if (model && mode !== 'all' && addrs[0]) {
try {
const r2 = await wFetch(addrs[0] + '/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + keyObj.value },
body: JSON.stringify({ model, messages: [{ role: 'user', content: 'ping' }], max_tokens: 1 }),
}, 30000)
const p2 = await r2.json().catch(() => null)
if (!r2.ok) {
const em = (p2 && p2.error && (p2.error.message || p2.error.type)) || ('HTTP ' + r2.status + '(' + classifyHttpError(r2.status) + ')')
modelTest = { tested: false, error: em }
} else modelTest = { tested: true }
} catch (e) {
modelTest = { tested: false, error: String((e && e.message) || e) }
}
}
return { ok: results.some((r) => r.ok), results, model, modelTest }
}
async function wModels(args) {
const { key, baseUrl } = wResolveKey(args && args.providerId, args && args.keyGroupId)
const resp = await wFetch(baseUrl + '/models', { headers: { Authorization: 'Bearer ' + key.value } }, 20000)
const parsed = await resp.json().catch(() => null)
if (!resp.ok || !parsed || !Array.isArray(parsed.data)) throw wApiError('获取模型失败:' + (wApiErr(parsed) || ('HTTP ' + resp.status)), classifyHttpError(resp.status), resp.status)
return { models: parsed.data.map((m) => (m && (m.id || m.name)) || '').filter(Boolean) }
}
// 测速逻辑在 src/provider-ping.js(含 no-cors 兜底,说明见该文件顶部注释)
const ProviderPing = (typeof window !== 'undefined' && window.IWBProviderPing) || null
function wPing(args) {
const urls = (args && Array.isArray(args.urls) ? args.urls : []).slice(0, 10)
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 })
}
// 历史出图:索引在 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
const galleryHydrator = GalleryHydration && typeof GalleryHydration.create === 'function'
? 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)) })
: null
let imageFolderHandle = null
const imageFolderManifest = { version: 1, files: {} }
const imageFolderName = () => imageFolderHandle ? (imageFolderHandle.name || '已选择文件夹') : ''
async function imageFolderPick() {
if (typeof window === 'undefined' || typeof window.showDirectoryPicker !== 'function') throw new Error('当前浏览器不支持文件夹保存,请使用最新版 Chrome 或 Edge')
imageFolderHandle = await window.showDirectoryPicker({ mode: 'readwrite' })
try { await imageFolderHandle.requestPermission({ mode: 'readwrite' }) } catch (e) { /* picker 已授权 */ }
await imageFolderEnsureDirs()
try {
const file = await imageFolderHandle.getFileHandle('manifest.json')
const parsed = JSON.parse(await (await file.getFile()).text())
if (parsed && parsed.files) imageFolderManifest.files = parsed.files
} catch (e) { /* 新目录或无效清单 */ }
await imageFolderWriteManifest()
return imageFolderName()
}
async function imageFolderEnsureDirs() {
if (!imageFolderHandle) return null
const originals = await imageFolderHandle.getDirectoryHandle('originals', { create: true })
const thumbnails = await imageFolderHandle.getDirectoryHandle('thumbnails', { create: true })
return { originals, thumbnails }
}
async function imageFolderWriteManifest() {
if (!imageFolderHandle) return false
const file = await imageFolderHandle.getFileHandle('manifest.json', { create: true })
const writable = await file.createWritable()
await writable.write(JSON.stringify(imageFolderManifest, null, 2))
await writable.close()
return true
}
async function imageFolderSaveItem(item, thumb) {
// 桌面端:**不再「出图就下载」**。下载是用户主动动作(输出节点/图库的下载按钮),
// 自动保存到文件夹会让用户目录里堆满不想要的图 ⇒ 这里直接视为「不做任何事」。
if (wIsTauri()) return false
if (!imageFolderHandle || !item || !item.url || typeof fetch !== 'function') return false
try {
const dirs = await imageFolderEnsureDirs()
if (imageFolderManifest.files[item.name] && imageFolderManifest.files[item.name].url === item.url) {
item.folderPath = imageFolderManifest.files[item.name].original
item.folderStatus = 'available'
return true
}
const base = wSanitizeFileName(item.name || ('gen_' + Date.now()))
const originalResp = await fetch(item.url)
if (!originalResp.ok) return false
const originalBlob = await originalResp.blob()
// v3.24.64:写进图片文件夹的后缀必须跟字节一致 —— SVG 结果曾在这里被存成 .png,双击打不开。
// 以 blob.type(服务端 Content-Type)为准,拿不到才看 URL 后缀,都判不出才回落 .png。
const originalName = (ImageFormat && ImageFormat.fileNameFor) ? ImageFormat.fileNameFor(item.url, base, originalBlob.type) : base.replace(/\.[^.]+$/, '') + '.png'
const originalFile = await dirs.originals.getFileHandle(originalName, { create: true })
const originalWritable = await originalFile.createWritable()
await originalWritable.write(originalBlob)
await originalWritable.close()
let thumbName = ''
if (thumb && String(thumb).indexOf('data:') === 0) {
thumbName = base.replace(/\.[^.]+$/, '') + '.jpg'
const raw = atob(String(thumb).split(',')[1] || '')
const bytes = new Uint8Array(raw.length); for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i)
const thumbFile = await dirs.thumbnails.getFileHandle(thumbName, { create: true })
const thumbWritable = await thumbFile.createWritable(); await thumbWritable.write(bytes); await thumbWritable.close()
}
imageFolderManifest.files[item.name] = { name: item.name, original: 'originals/' + originalName, thumbnail: thumbName ? 'thumbnails/' + thumbName : '', mtime: item.mtime || Date.now(), url: item.url }
await imageFolderWriteManifest()
item.folderPath = 'originals/' + originalName
item.folderStatus = 'available'
return true
} catch (e) { return false }
}
async function imageFolderSync() {
if (!imageFolderHandle) throw new Error('请先选择图片文件夹')
const dirs = await imageFolderEnsureDirs()
const existing = new Set()
for await (const [name] of dirs.originals.entries()) existing.add(name)
// 索引「读-改-写」走图库门面的锁(2026-11-16):此前直连 lsGet/lsSet OUT_KEY,
// 与另一个标签页的归档并发时会互相覆盖(图库莫名少条目)。mutate 的锁是跨标签页的。
let removed = 0
const patchFolderStatus = (idx) => {
for (const item of idx) {
const meta = imageFolderManifest.files[item.name]
if (meta && !existing.has(String(meta.original).split('/').pop())) { item.folderStatus = 'missing'; removed++ }
else if (meta) item.folderStatus = 'available'
}
return idx.filter((x) => x.folderStatus !== 'missing')
}
if (ModularOutputStore) await ModularOutputStore.mutate(patchFolderStatus).catch(() => null)
else lsSet(OUT_KEY, patchFolderStatus(lsGet(OUT_KEY, [])))
await imageFolderWriteManifest()
return { removed, files: existing.size }
}
const imageFolderApi = { pick: imageFolderPick, sync: imageFolderSync, save: imageFolderSaveItem, name: imageFolderName }
// 生成图 → 压缩缩略图 dataURL → 缩略图存储(浏览器 IndexedDB / 桌面端 images/thumbs 文件);
// 原图档另写 out_orig_(只有「应用内备份原图」开启时;桌面端落在 images/gallery/)。
// 两张都抓不到(图床跨域/网络)时静默降级:只保留图床 URL 作显示与下载兜底。
// 调试计数器:仅在显式开启时记录高频路径,默认完全关闭。
function iwbDebugCounter(name, extra) {
if (typeof window === 'undefined' || window.__IWB_DEBUG__ !== true) return
const d = window.__IWB_DEBUG_METRICS__ || (window.__IWB_DEBUG_METRICS__ = {})
const item = d[name] || (d[name] = { count: 0, lastAt: 0 })
item.count++
item.lastAt = Date.now()
if (extra !== undefined) item.last = extra
}
// v3.87.33:抓取失败的输出(多为图床 CORS/403)记入"不再重试",否则每次生成都会把
// 全部失败图重新抓取+整尺寸解码(配合并发 5 → 单次 500~900MB 尖峰,实测 d720/d898)。
const wThumbFail = new Set()
const wThumbProxyTried = new Set() // 经本站代理重试过(每个 URL 只试一次)
const wThumbFailKey = (item) => String((item && item.url) || (item && item.name) || '')
function storeOutputThumb(item, forceOrig) {
iwbDebugCounter('storeOutputThumb:start', item && item.name)
const fkEarly = wThumbFailKey(item)
if (fkEarly && !forceOrig && wThumbFail.has(fkEarly)) return Promise.resolve(null) // 已知抓不到:不再重试
// 图库本地:缩略图(out_,320px)+ [应用内备份原图开→ 完整原图 out_orig_]。
// 远程图床可能 CORS/403 拦 fetch——失败则明确记录(不再静默),仅保留 url 兜底。
// 关键:原图落库与缩略图落库**解耦**——只要抓到 src,先写 out_orig_ + origIdb,
// 不受缩略图成败影响,保证预览/下载/复制/插入能取到原图。
const cfg = wRawCfg() || {}
// v3.87.37:原图备份改为**显式开启才做**(默认配置不持久化该键 ⇒ 默认即关)。
// 默认开启会让每张生成图都抓完整原图存 base64(诊断实测空闲堆 1.4GB+ 的主因之一)。
const backup = true // v3.26.92 用户裁定:不再提供开关,始终保存原图(图床链接会过期,只有本地字节可靠)
// v3.87.59(丙方案收尾):C3 之后 item.data/item.url 可能是**引用对象**({__cache}/{__blob}),
// 旧实现 String() 后判前缀 ⇒ 必然落空(缩略图缺失、可能多一次代理抓取)✗。这里先按需解析:
// {__cache} → 虚拟 URL;{__blob} → objectURL;{__idb} → 仍为 null(迁移后已少见,保持原兜底行为)。
const rawData = (item && item.data && typeof item.data === 'object') ? wResolveImg(item.data) : (item && item.data)
const rawUrl = (item && item.url && typeof item.url === 'object') ? (wResolveImg(item.url) || '') : (item && item.url)
const src0 = (rawData && String(rawData).indexOf('data:') === 0)
? Promise.resolve(rawData)
: ((rawUrl && /^(https?:|blob:)/i.test(String(rawUrl)))
? fetch(rawUrl, { mode: 'cors' }).then((r) => (r.ok ? r.blob() : null)).then((blob) => (blob ? new Promise((res) => { const fr = new FileReader(); fr.onload = () => res(fr.result); fr.onerror = () => res(null); fr.readAsDataURL(blob) }) : null)).catch((e) => { try { console.warn('[iwb] 抓取原图失败(多为图床限跨域 CORS):', item.url, e) } catch (e2) { /* ignore */ } return null })
: Promise.resolve(null))
return src0.then(async (src) => {
iwbDebugCounter('storeOutputThumb:source', { name: item && item.name, found: !!src })
if (!src) { if (backup) { try { idxSet({ orig: 'missing' }) } catch (e) { /* ignore */ } }
// v3.87.35:直连失败(多为图床无 CORS 头)时,改走本站同源代理再试一次——
// 这样豆包图也能归档出缩略图/本地原图(下载第②步此后可离线命中)。
if (fkEarly && /^https:/i.test(fkEarly) && !wThumbProxyTried.has(fkEarly)) {
wThumbProxyTried.add(fkEarly)
try {
// 桌面客户端:用 plugin-http 直取字节(Rust 侧请求,不受 CORS 限制)
if (!wIsTauri()) { if (fkEarly) wThumbFail.add(fkEarly); return null }
const pr = await wTauri.http.fetch(fkEarly)
// v3.87.52(丙方案 C5):交给 wRegisterBlobUrl(入参是 Blob,内部创建并登记 objectURL),
// 避免此前的"创建了 blob URL 却不登记、不回收"✗
if (pr.ok) return storeOutputThumb(Object.assign({}, item, { url: wRegisterBlobUrl(await pr.blob()) }))
} catch (e) { /* 落到失败记忆 */ }
}
if (fkEarly) wThumbFail.add(fkEarly)
return null
} // 记下失败:下次不再白抓
// 同样必须走门面锁:缩略图/原图落库后回写 idb 键,与另一标签页的归档并发会互相覆盖
const idxSet = (pathObj) => {
const patch = (idx) => { const it = idx.find((x) => x.name === item.name); if (!it) return null; Object.assign(it, pathObj); return idx }
if (ModularOutputStore) return ModularOutputStore.mutate(patch).catch(() => null)
const next = patch(lsGet(OUT_KEY, [])); if (next) lsSet(OUT_KEY, next)
}
// ① 原图独立落库:先写 out_orig_ + 回写 origIdb(缩略图失败也不影响)
const origJob = backup
? IDB.put(IDB_ORIG_PREFIX + item.name, src).then((ok) => { if (ok) { item.origIdb = IDB_ORIG_PREFIX + item.name; idxSet({ origIdb: item.origIdb, orig: 'ok' }) } else { try { idxSet({ orig: 'missing' }) } catch (e3) { /* ignore */ } } return ok }).catch((e) => { try { console.warn('[iwb] 原图写入 IndexedDB 失败:', item.name, e) } catch (e2) { /* ignore */ } try { idxSet({ orig: 'missing' }) } catch (e3) { /* ignore */ } return false })
: Promise.resolve(false)
// ② 缩略图独立落库(失败不阻断原图)
const thumbJob = new Promise((resolve) => { compressDataUrl(src, { enabled: true, force: true, maxMB: 0, maxEdge: 320, quality: 0.72, format: 'jpeg' }, resolve) }).then((thumb) => {
if (!thumb || String(thumb).length < 20) return null
return IDB.put(IDB_OUT_PREFIX + item.name, thumb).then((ok) => {
if (!ok) return null
item.idb = IDB_OUT_PREFIX + item.name
idxSet({ idb: item.idb })
if (item.url) outThumbCacheSet(item.url, thumb)
return thumb
})
}).catch((e) => { try { console.warn('[iwb] 缩略图写入失败:', item.name, e) } catch (e2) { /* ignore */ } return null })
return Promise.all([origJob, thumbJob]).then(() => (item && item.origIdb) ? item.origIdb : null)
}).catch(() => null)
}
// e2e 探针:仅在 page.addInitScript 显式置 window.__IWB_E2E__ = true 时暴露,
// 用于在带 CSP 的本地环境里直接验证「压缩链路」与「缩略图落 IDB」是否真的工作
// (生产不设置该标志 → 完全不挂载)。只暴露最小面:压缩 / 存缩略图。
if (typeof window !== 'undefined' && window.__IWB_E2E__ === true) {
window.__IWB_E2E__API__ = {
compress: (dataUrl, opt) => new Promise((resolve) => {
compressDataUrl(dataUrl, Object.assign({ enabled: true, force: true, maxMB: 0, maxEdge: 320, quality: 0.72, format: 'jpeg' }, opt || {}), (out) => resolve(out))
}),
thumb: (item) => storeOutputThumb(item),
// v3.87.6:验证错误边界(设置标志 → 下次渲染时 E2EBoomProbe 抛错 → 边界兜底)
boom: (on) => { window.__IWB_E2E_BOOM__ = on !== false; return true },
crash: () => (typeof window !== 'undefined' && window.IWBCrashLog) ? window.IWBCrashLog.report({ version: APP_VERSION }) : null,
}
}
// 设置/备份**行为级**契约探针:页面显式置 window.__IWB_BACKUP_TEST__ = true 才挂载(生产不挂载)。
// 为什么需要它:备份链路的根因是"用了展示形态当完整设置",只做正则契约挡不住形状回归,
// 必须在真实代码路径上做「导出 → 改值 → 导入 → 断言往返」,并按 W_SENSITIVE_PATHS **逐条**验证
// 导出脱敏与导入解析没有脱节(见 tests/iwb-v32-web-test.js 150-x)。
if (typeof window !== 'undefined' && window.__IWB_BACKUP_TEST__ === true) {
window.__IWB_BACKUP_TEST__API__ = {
raw: () => wClone(wRawCfg()),
publicCfg: () => wCfgPublic(),
backup: (withKeys) => wBackupConfig(!!withKeys),
save: (body) => wCfgSave(body),
hasPlaintext: (cfg) => wCfgHasPlaintextKeys(cfg),
sensitivePaths: () => wClone(W_SENSITIVE_PATHS),
normalize: (data) => normalizeBackup(data),
}
}
async function wListOutputs(args) {
if (ModularOutputStore) {
// v3.87.37:图库列表只取元数据(不再把每条数据读回堆;显示按需经 outSrcOf 取缩略图/代理)
const modular = await ModularOutputStore.list({ retention: wRawCfg().outputsRetention, limit: args && args.limit, metaOnly: true })
if (modular && modular.ok) return modular.value
}
const idx = lsGet(OUT_KEY, [])
const ret = wRawCfg().outputsRetention
let list = idx.slice()
const now = Date.now()
const maxDays = Number(ret.maxDays) || 0
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:缩略图 → 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)
for (let i = 0; i < hydList.length; i++) if (hydrated.items[i] && hydrated.items[i].data !== undefined) hydList[i].data = hydrated.items[i].data
} else await Promise.all(hydList.map(async (f) => {
if (f && f.idb) {
const v = await IDB.get(f.idb)
if (v) f.data = v
}
}))
for (const f of hydList) if (f && f.url && f.data) outThumbCacheSet(f.url, f.data)
return { files: list, retention: ret }
}
// opts.awaitArchive=true:等本批新图原图落盘再返回(自动下载要从本地原图复制,避免与后台归档竞态)
async function wAddOutputs(results, opts) {
const awaitArchive = !!(opts && opts.awaitArchive)
if (ModularOutputStore) {
const items = []
for (const r of (results || [])) {
if (!r || !r.ok || !r.url) continue
items.push({ name: 'gen_' + Date.now() + '_' + Math.floor(Math.random() * 1e6) + '.png', url: r.url, size: 0, mtime: Date.now(), width: r.width || 0, height: r.height || 0, label: r.label || '', snapshot: r.snapshot || null, orig: 'pending' })
}
const prevIdx = lsGet(OUT_KEY, [])
const modular = await ModularOutputStore.add(items, { retention: wRawCfg().outputsRetention })
if (modular && modular.ok) {
// 保留策略剪掉的条目:连同缩略图+原图一并移除(ModularOutputStore 只删 out_,原图 out_orig_ 由 wPruneOutputIdb 处理)
const nowIdx = lsGet(OUT_KEY, [])
const nowNames = new Set(nowIdx.map((f) => f.name))
const removedNames = prevIdx.filter((f) => !nowNames.has(f.name)).map((f) => f.name)
if (removedNames.length) wPruneOutputIdb(removedNames)
const current = await ModularOutputStore.list({ retention: wRawCfg().outputsRetention, metaOnly: true })
const curFiles = (current && current.ok && current.value && current.value.files) || []
// 补缩略图:并发上限 5(无上限并发会让每张原图同时在堆里解码,是出图后的内存尖峰来源)
// 只补"确实还没有缩略图且没被抓失败过"的条目;并发从 5 降到 2(每张原图会在堆里解码,5 张同时解码就是出图后的尖峰)
// v3.87.37:只处理**本次新增**的条目。之前每次生成都会把整库(实测 109 条)重扫 + 逐条 hydrate,
// 点「生成」后 480ms 内就 +720MB(探针实测),这是最大的内存尖峰来源。
const newNames = new Set(items.map((x) => x && x.name).filter(Boolean))
const needThumb = curFiles.filter((item) => item && newNames.has(item.name) && !item.idb && !wThumbFail.has(wThumbFailKey(item)))
if (needThumb.length) {
const thumbJob = runWithConcurrency(needThumb, 2, (item) => storeOutputThumb(item))
const onThumbFail = (e) => {
// 整批缩略图失败此前是**零反馈**:图库里看不到缩略图,用户不知道发生了什么。
// 现在:记录 + 提示一次(整批失败才提示,不逐张刷屏)。
try { if (CrashLog && typeof CrashLog.record === 'function') CrashLog.record('thumb-batch-failed', { scope: 'output-store', message: '缩略图批量生成失败(' + needThumb.length + ' 张):' + String((e && e.message) || e), version: APP_VERSION }) } catch (err) { /* ignore */ }
wLogNotice('部分图片的缩略图生成失败(' + needThumb.length + ' 张),图库中可能显示为空白。', 'err')
}
if (awaitArchive) { try { await thumbJob } catch (e) { onThumbFail(e) } } else thumbJob.catch(onThumbFail)
}
for (const item of curFiles) {
if (item && newNames.has(item.name) && imageFolderApi) imageFolderApi.save(item, item.data).catch(() => {})
}
return modular.value
}
}
const idx = lsGet(OUT_KEY, [])
const added = []
for (const r of (results || [])) {
if (!r || !r.ok || !r.url) continue
const name = 'gen_' + Date.now() + '_' + Math.floor(Math.random() * 1e6) + '.png'
idx.push({ name, url: r.url, size: 0, mtime: Date.now(), w: r.width || 0, h: r.height || 0, label: r.label || '', snapshot: r.snapshot || null, orig: 'pending' })
added.push(name)
}
lsSet(OUT_KEY, idx)
// 按保留策略清理索引
const ret = wRawCfg().outputsRetention
let list = idx.slice()
const now = Date.now()
if (Number(ret.maxDays) > 0) list = list.filter((f) => now - f.mtime <= Number(ret.maxDays) * 86400e3)
if (Number(ret.maxFiles) > 0) list = list.slice(-Number(ret.maxFiles))
lsSet(OUT_KEY, list)
// 异步为每张新图存 IDB 缩略图(不阻塞生成完成;保留策略外的图不存,避免 IDB 无限膨胀;已有缩略图的不重复拉取)
const keptNames = new Set(list.map((f) => f.name))
// 保留策略剪掉的条目:连同缩略图+原图一并移除(Plan A 整体删除,不留孤儿原图)
const removedNames = idx.filter((f) => !keptNames.has(f.name)).map((f) => f.name)
if (removedNames.length) wPruneOutputIdb(removedNames)
const needThumb2 = idx.filter((f) => keptNames.has(f.name) && !f.idb)
if (needThumb2.length) {
const thumbJob2 = runWithConcurrency(needThumb2, 5, (f) => storeOutputThumb(f))
const onThumbFail2 = (e) => {
// 同上:整批失败原先零反馈(用户只看到图库空白,不知道原因)
try { if (CrashLog && typeof CrashLog.record === 'function') CrashLog.record('thumb-batch-failed', { scope: 'output-store', message: '缩略图批量生成失败(' + needThumb2.length + ' 张):' + String((e && e.message) || e), version: APP_VERSION }) } catch (err) { /* ignore */ }
wLogNotice('部分图片的缩略图生成失败(' + needThumb2.length + ' 张),图库中可能显示为空白。', 'err')
}
if (awaitArchive) { try { await thumbJob2 } catch (e) { onThumbFail2(e) } } else thumbJob2.catch(onThumbFail2)
}
for (const f of idx) {
if (keptNames.has(f.name) && imageFolderApi) imageFolderApi.save(f, f.data).catch(() => {})
}
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) { 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) { 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, []); 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') {
// 从备份导入图库索引:整表覆盖也必须持锁 —— 否则「导入期间另一个标签页归档了一张图」
// 会出现两种坏结果:新图被整表覆盖掉,或导入的整表被对方的读-改-写吃掉一半。
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 }
}
// 大图(参考图 base64)从 localStorage 剥离存 IndexedDB,避免 5MB 配额撑爆丢数据
const IDB_REF_PREFIX = 'ref_'
const IDB_OUT_PREFIX = 'out_'
const IDB_ORIG_PREFIX = 'out_orig_'
// 图库条目整体删除(Plan A:缩略图 + 原图 + 索引一并移除,不留孤儿/半态)。
// 同时匹配存储的 idb/origIdb 与确定性 key(out_#name / out_orig_#name),覆盖「条目从未被 hydrate 就因超限被剪掉」的场景。
async function wPruneOutputIdb(names) {
const set = new Set(names || [])
if (!set.size) return
const idx = lsGet(OUT_KEY, [])
const seen = new Set()
const dels = []
for (const f of idx) {
if (!set.has(f.name)) continue
for (const k of [f.idb, f.origIdb, IDB_OUT_PREFIX + f.name, IDB_ORIG_PREFIX + f.name]) {
if (k && !seen.has(k)) { seen.add(k); dels.push(IDB.del(k).catch(() => {})) }
}
}
await Promise.all(dels)
}
// 清空全部图库本地图(缩略图 + 原图)。
// v3.87.37:一次性清理"完整原图副本"(out_orig_)。历史上默认备份原图 ⇒ 每张生成图都存了完整 base64 原图;
// 打开应用时图库会把它们 hydrate 进堆(诊断实测空闲 1.4GB+ 而 comp 量不到)。只删原图副本,保留小缩略图。
const W_PURGE_ORIG_FLAG = 'iwb_purged_orig_v1'
async function wPurgeOutputOriginals() {
try {
// 注意:**不要**在这里 IDB.get 把原图读出来量大小 —— 那会把几百 MB 大字符串拉进堆、把堆顶撑高
// (实测:读 162 个原图后空闲堆从 1.6GB 涨到 2.5GB 且不回落)。只按 key 删除即可。
const all = await IDB.keys()
let n = 0
for (const k of (all || [])) {
if (String(k).indexOf(IDB_ORIG_PREFIX) !== 0) continue
await IDB.del(k).catch(() => {})
n++
}
const bytes = 0
// 清 origIdb 字段同样走门面锁(与归档并发时不至于把对方的整表覆盖回去)
const stripOrigIdb = (idx) => {
if (!Array.isArray(idx) || !idx.length) return null
let changed = false
for (const it of idx) { if (it && it.origIdb) { delete it.origIdb; changed = true } }
return changed ? idx : null
}
if (ModularOutputStore) await ModularOutputStore.mutate(stripOrigIdb).catch(() => null)
else { const next = stripOrigIdb(lsGet(OUT_KEY, [])); if (next) lsSet(OUT_KEY, next) }
const mb = Math.round(bytes / 1048576)
try { if (CrashLog && typeof CrashLog.record === 'function') CrashLog.record('mem-phase', { scope: 'purge', message: '已清理图库原图副本 ' + n + ' 个 / 约 ' + mb + 'MB' }) } catch (e) { /* ignore */ }
try { console.info('[iwb] 已清理图库原图副本', n, '个 /', mb + 'MB') } catch (e) { /* ignore */ }
return { ok: true, count: n, mb: mb }
} catch (e) { return { ok: false } }
}
// v3.87.37:存量图片重压 —— 把画板里历史的大 dataURL(>2.5MB)分批压到 1600 长边/0.85,
// 目标:画板常驻从 50MB 降到几 MB(移动/缩放/保存时不再反复"经过"这堆大字符串)。
// 安全设计:① 每次只处理 1 张、间隔由 15s 采样周期驱动;② 原图先写入 Cache Storage(可回退);
// ③ 压缩收益不足 20% 则保留原值;④ 每张只试一次(tried 集合)避免死循环;⑤ localStorage 标记只跑一次。
const W_RECOMPRESS_FLAG = 'iwb_recompress_v1'
function wGetByPath(o, path) {
const segs = String(path || '').split('.')
let cur = o
for (const sgm of segs) { if (cur == null) return undefined; cur = cur[sgm] }
return cur
}
function wSetByPath(o, path, val) {
const segs = String(path || '').split('.')
let cur = o
for (let i = 0; i < segs.length - 1; i++) {
const k = segs[i]
if (cur[k] == null || typeof cur[k] !== 'object') cur[k] = {}
cur = cur[k]
}
cur[segs[segs.length - 1]] = val
return o
}
function wCollectBigImages(nodes, minBytes) {
const hits = []
const min = Number(minBytes) || 2.5 * 1048576
for (const n of (nodes || [])) {
const d = (n && n.data) || {}
for (const k of Object.keys(d)) {
const v = d[k]
const push = (path, str) => { if (typeof str === 'string' && str.indexOf('data:image/') === 0 && str.length > min) hits.push({ nodeId: n.id, path: path }) }
if (typeof v === 'string') push(k, v)
else if (Array.isArray(v)) v.forEach((x, i) => {
if (typeof x === 'string') push(k + '.' + i, x)
else if (x && typeof x === 'object' && typeof x.value === 'string') push(k + '.' + i + '.value', x.value)
})
else if (v && typeof v === 'object' && typeof v.value === 'string') push(k + '.value', v.value)
}
}
return hits
}
async function wClearOutputIdb() {
const all = await IDB.keys()
for (const k of (all || [])) if (k.indexOf(IDB_OUT_PREFIX) === 0 || k.indexOf(IDB_ORIG_PREFIX) === 0) await IDB.del(k).catch(() => {})
}
// 图库条目取画质最优的 src:优先本地原图(out_orig_)→ 远程 url(原分辨率,<img> 不受 CORS)→ 缩略图(data/out_)兜底。
// 用于预览/下载/复制/插入/拖到画布为参考图,保证参考图是清晰原图/高清远程,缩略图仅作网格展示。
// 运行时缩略图缓存:url → 缩略图 dataURL(桌面端字节在 images/thumbs/)。输出节点网格优先用本地缩略图
// (快、不随远程 URL 失效),远程 URL 仅作兜底,避免「图床 URL 慢/过期导致输出节点图片空白或消失」。
// v3.87.8 数据保护:用户"明确彻底删除"的画板 id(只作用于紧随其后的那次写入)。
// 用途:写索引时做并集守卫——存储里已有的画板不能被"漏掉"(本机实测出现过"画布从列表消失")。
const wPurgeIntent = new Set()
const outThumbCache = new Map()
// 图库缩略图缓存:Map 无上限会随输出图数量无限增长(内存持续升高)。设一个容量上限,超过时逐出最旧项
// (读不到时回退到原 url,仅是多拉一次图,无功能损失)。
const outThumbCacheMax = 400
const outThumbCacheSet = (k, v) => {
if (outThumbCache.size >= outThumbCacheMax) {
const first = outThumbCache.keys().next().value
if (first !== undefined) outThumbCache.delete(first)
}
outThumbCache.set(k, v)
}
async function wResolveOutputSrc(item, localFirst) {
if (!item) return ''
if (item.origIdb) { const v = await IDB.get(item.origIdb).catch(() => null); if (v) return v }
// C3 第2步:物品的 data 可能是引用形态({__cache}/{__blob}/{__idb})——调用方要的是能直接用的字节/dataURL,
// 这里按需解析(不写回物品、不留驻);远程 URL 仍只作最后回退。
const localData = (item.data && typeof item.data === 'object') ? await wImgRefDataUrl(item.data) : item.data
// localFirst(复制图片等怕跨域的场景):本地缩略图 dataURL 先于远程图床 URL,远程只作最后回退
if (localFirst && localData) return localData
if (item.url) return item.url
if (localData) return localData
if (item.idb) { const v = await IDB.get(item.idb).catch(() => null); if (v) return v }
return ''
}
// 图库条目 → 可直接交给 <img>/下载/剪贴板的 src:命中「有界 objectURL 缓存」即复用,
// 避免每次点击都把 2MB+ base64 重新读进堆(驱逐时统一 revoke)。
async function wOutputSrcForUse(item, cacheKey, localFirst) {
if (!item) return ''
// v3.24.65:localFirst 必须进缓存键。此前「复制」(本地优先 ⇒ 拿来的是 320px 缩略图)与
// 「下载」(远程原图优先)共用同一个 key ⇒ 先复制一次,之后下载拿到的就是缩略图那条 objectURL。
const ck = 'out:' + (localFirst ? 'L:' : 'R:') + (cacheKey || item.origIdb || item.name || item.url || '')
const hit = wObjUrlCache.get(ck)
if (hit) return hit
const resolved = await wResolveOutputSrc(item, localFirst)
if (!resolved) return ''
if (String(resolved).indexOf('data:') !== 0) return resolved // 图床 URL 直接用,不进缓存
const blob = await wBlobFromDataUrl(resolved)
if (!blob) return String(resolved)
return wObjUrlPut(ck, wRegisterBlobUrl(blob))
}
// dataURL 判定:data: 前缀且超过阈值 → 移 IndexedDB(短文本/图床 URL 不受影响)。
// 阈值降低到 3000:截图/粘贴的压缩图普遍超过,文本节点几千字以内留在 localStorage 无碍。
function isBigDataUrl(v) {
return typeof v === 'string' && v.indexOf('data:') === 0 && v.length > 3000
}
// 确定性 IDB key:节点 id + 内容 hash。同节点同图 → 同 key:
// ① 重复保存不产生孤儿(wCleanIdb 可安全回收);② beforeunload 同步兜底时可用相同 key 引用已写入的图
function idbKeyOf(prefix, nodeId, value) {
let h = 5381
const s = String(value)
for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) | 0
return prefix + nodeId + '_' + (h >>> 0).toString(36)
}
// 图片引用去重:同一会话内同一确定性 key 只写一次 IDB。保存不再反复把同一张 base64
// 大图重复写库(幂等 key + 内容不变,重复写只增加 I/O 与主线程压力)。删除孤儿键时
// 同步移出,确保删除后能重新写入(避免引用丢失)。
const wIdbDone = new Set()
async function idbPutDedup(key, value) {
if (wIdbDone.has(key)) return true
if (wIdbDone.size > 20000) wIdbDone.clear() // 防会话内无限增长(key 基于内容哈希,去重不会错配)
const ok = await IDB.put(key, value)
if (ok) wIdbDone.add(key)
return ok
}
// 同步把大 dataURL 就地替换为 IDB 引用。writeIdb=true 时(beforeunload 兜底)同步发起 IDB 写入
// (best-effort:幂等 key,事务通常能在页面卸载前完成;即使未完成,也仅该张图缺,其余数据完好)。
// 用于 beforeunload 同步兜底:localStorage 只落文本/引用,避免整份超限全丢。
// 注意:调用方需传入不共享内存的新 data 对象(避免污染内存中的节点状态)。
function stripBigValueSync(value, nodeId, path, write) {
if (isBigDataUrl(value)) {
// 桌面端没有 Service Worker,iwbCacheWrite 恒返回 null;这里若仍写 {__cache}
// 会得到一个永远解析不到的引用(标注大图覆盖保存后重载即丢)。桌面端保留原值,
// 让文件存储按自己的路径落盘;Web 端才用 Cache Storage 兜底。
if (wFileStoreOn()) return value
const cacheUrl = wCacheKeyOf(value)
if (cacheUrl) {
if (write) { try { wTrackCacheWrite(iwbCacheWrite(value)) } catch (e) { return value } }
return { __cache: cacheUrl }
}
return value
}
if (Array.isArray(value)) return value.map((v, i) => stripBigValueSync(v, nodeId, path + '_' + i, write))
if (value && typeof value === 'object' && !value.__cache && !value.__idb) {
const out = {}
for (const k of Object.keys(value)) out[k] = stripBigValueSync(value[k], nodeId, path + '_' + k, write)
return out
}
return value
}
function containsBigDataUrl(value) {
if (isBigDataUrl(value)) return true
if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) if (containsBigDataUrl(value[i])) return true; return false }
if (value && typeof value === 'object') { for (const k of Object.keys(value)) if (containsBigDataUrl(value[k])) return true; return false }
return false
}
function stripBigDataUrlsSync(ws, writeIdb) {
for (const w of (ws && ws.workspaces) || []) {
for (const n of (w && w.nodes) || []) {
if (!n) continue
const d = (n && n.data) || {}
// 惰性:仅当某字段子树真的含有大 dataURL 时才克隆/改写。原实现只处理 data/url/result,
// v3.78 曾改成「对所有字段 stripBigValueSync」——那会对每个节点所有字段(taskActive/taskVariants/result 等)
// 做深拷贝,7k 节点工作台每次保存产生海量对象垃圾 + Major GC,是「改存储后 CPU/内存异常升高」的回归源。
// 改为先探测再改写:既能抓住任意字段内的图片,又不克隆无图字段(回到 v3.77 的分配量级)。
for (const f of Object.keys(d)) if (containsBigDataUrl(d[f])) d[f] = stripBigValueSync(d[f], n.id || 'n', f, writeIdb)
}
}
return ws
}
async function sanitizeBigValue(value, nodeId, path) {
if (isBigDataUrl(value)) {
const key = idbKeyOf(IDB_REF_PREFIX, nodeId + '_' + path, value)
const ok = await idbPutDedup(key, value)
return { value: ok ? { __idb: key } : value, failed: !ok }
}
if (Array.isArray(value)) {
const out = []; let failed = false
for (let i = 0; i < value.length; i++) { const r = await sanitizeBigValue(value[i], nodeId, path + '_' + i); out.push(r.value); failed = failed || r.failed }
return { value: out, failed }
}
if (value && typeof value === 'object' && !value.__idb) {
const out = {}; let failed = false
for (const k of Object.keys(value)) { const r = await sanitizeBigValue(value[k], nodeId, path + '_' + k); out[k] = r.value; failed = failed || r.failed }
return { value: out, failed }
}
return { value, failed: false }
}
// 生成结果是会话态:保留任务节点与参数,但不把生成图片或结果写入工作区、备份、节点组或画布导出。
// 用浅拷贝只清 gen 节点 result:base64 大图是字符串引用,不深拷贝内容(JSON.parse(JSON.stringify)
// 会对含大图的整个 workspace 拷贝两遍字符串,是保存慢/CPU 高的主因之一)。
// 一次性迁移:把历史写入 localStorage 的旧画布/全量快照里的 base64 大图剥离到 IndexedDB(ref_),
// 释放 localStorage 空间(对标 opentu:画布数据轻量化)。best effort:格式不符/失败则跳过,不破坏数据。
function wMigrateLegacyCanvasBase64() {
try {
wPendingCacheWrites = [] // 本次迁移的写入单独成一组,作为后续读取的屏障
const keys = []
for (const k of lsKeys()) {
// 除每个画布独立 key (iwb_ws_*) 与旧全量快照外,还必须清理旧单文件工作台冗余键:
// iwb_web_workspaces(ws-keys 拆分前的整体键)与 iwb_web_workspaces_legacy(启动时 6568 行的整份备份副本)。
// 二者可能各行保存一份 10MB 级 base64(拆分前的历史数据),叠加才把 localStorage 撑满 —— 迁移必须一并剥离。
if (k && (/^iwb_ws_/.test(k) || k === 'iwb_web_workspaces_full' || k === 'iwb_web_workspaces' || k === 'iwb_web_workspaces_legacy')) keys.push(k)
}
for (const k of keys) {
let raw
raw = lsRawGet(k, null); if (!raw) continue
if (!raw || raw.indexOf('data:image') === -1) continue
let obj = null
try { obj = JSON.parse(raw) } catch (e) { continue }
const wrap = Array.isArray(obj.workspaces) ? obj : (Array.isArray(obj.nodes) ? { workspaces: [obj] } : null)
if (!wrap) continue
const before = JSON.stringify(wrap)
try { stripBigDataUrlsSync(wrap, true) } catch (e) { continue }
const after = JSON.stringify(wrap)
if (after === before) continue
const back = (Array.isArray(obj.nodes) && wrap.workspaces.length === 1) ? wrap.workspaces[0] : wrap
lsSet(k, back)
}
// 迁移写出的 {__cache} 引用与后台写入必须成对生效:把这一批写入登记为屏障,读取方先等它们落地
wCacheWriteBarrier = Promise.all(wPendingCacheWrites.splice(0)).then(() => {}, () => {})
} catch (e) { swallow('migration', e) }
}
// 清理已下线功能的本地残留键(v3.21.0 移除 Pinterest 在线参考图库)。
// iwb_pinterest_client(OAuth client_id/secret)、iwb_pinterest_token(access_token)、
// iwb_pinterest_lib(用户粘贴的图片网址列表)—— 功能已下线,这些键不再被读取,
// 其中前两个还可能残留凭据 ⇒ 启动时清掉(best-effort,失败不影响主流程)。
function wCleanRemovedFeatureKeys() {
try {
const dead = ['iwb_pinterest_client', 'iwb_pinterest_token', 'iwb_pinterest_lib']
for (const k of dead) { try { lsRemove(k) } catch (e) { /* ignore */ } }
} catch (e) { /* ignore */ }
}
function withoutGenerationResults(value) {
const scrubNodes = (nodes) => (Array.isArray(nodes) ? nodes : []).map((n) => {
if (n && n.type === 'gen' && n.data && n.data.result !== undefined) return Object.assign({}, n, { data: Object.assign({}, n.data, { result: null }) })
return n
})
if (!value) return value
if (Array.isArray(value.workspaces)) return Object.assign({}, value, { workspaces: value.workspaces.map((w) => (w && Array.isArray(w.nodes)) ? Object.assign({}, w, { nodes: scrubNodes(w.nodes) }) : w) })
if (Array.isArray(value.nodes)) return Object.assign({}, value, { nodes: scrubNodes(value.nodes) })
return value
}
// ---- C3 第3步(§13.34.7 第 2 条):**新写入**主通道切到 IDB Blob({__blob}),Cache Storage 退居兜底 ----
// 开关(默认启用新通道)。回退到旧行为({__cache} 写入)二选一,都是一条改动:
// ① 代码:W_IMG_BLOB_PRIMARY_DEFAULT = false;
// ② 运行期(免发布):localStorage['iwb_img_write'] = 'cache' ⇒ 本会话所有新写入回到 {__cache}。
// 边界:**只影响新写入**。已存在的 {__cache} 引用永不失效(wResolveImg/wHydrate 原样保留并继续解析),
// 不做存量 {__cache} → {__blob} 批量迁移(风险高、收益低)。
const W_IMG_BLOB_PRIMARY_DEFAULT = true
const W_IMG_BLOB_PRIMARY = (function () {
try {
if (lsRawGet('iwb_img_write', null) === 'cache') return false
} catch (e) { /* 开关读不到时按默认(启用)处理,绝不阻塞保存 */ }
return W_IMG_BLOB_PRIMARY_DEFAULT
})()
// 图片引用化**唯一入口**:wSanitizeWs(画布保存)与 wRefValueAsync(收藏快照 / LRU 反 hydrate)都只经这里产出引用。
// 失败回退链:{__blob}(IDB Blob 主通道)→ {__cache}(Cache Storage 兜底)→ null(调用方自行兜底,绝不抛错打断保存)。
// 只有 ImageBlobStore.put 明确 r.ok===true 且带 key 才返回 {__blob},绝不产出「引用指向不存在的字节」。
// 存储自检(桌面迁移排查用):把“字节到底能不能落盘”变成可复制的事实
function wStorageSelfCheck() {
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
const st = (F && typeof F.stats === 'function') ? F.stats() : null
return {
tauri: wIsTauri(), fileEnabled: wFileStoreOn(), dir: (st && st.dir) || '',
assets: (st && st.images) || 0, memKeys: (st && st.keys) || 0,
blobStore: !!wImageBlobStore(), cryptoSubtle: !!(typeof crypto !== 'undefined' && crypto.subtle),
caches: (typeof caches !== 'undefined'),
}
}
async function wImgRefWrite(dataUrl) {
if (W_IMG_BLOB_PRIMARY && wImageBlobStore()) {
try {
const r = await wImageBlobStore().put(dataUrl)
if (r && r.ok && r.key) {
const ref = { __blob: String(r.key) }
try { wPrimeDisplayThumbForRef(ref, dataUrl) } catch (e) { /* ignore */ }
return ref
}
if (r && r.ok === false) swallow('image', new Error(r.error || 'blob-put-failed'))
} catch (e) { swallow('image', e) } // 落 Blob 失败(配额/环境不支持)→ 回退 Cache,但计数留痕
}
// 桌面端不回退 Cache Storage:WebView2 重启后 {__cache} 解析不到(mac 上正常),
// 回退等于“写成功但图没了”。失败就让调用方把字节内联进画布。
if (wIsTauri()) return null
const c = await iwbCacheWrite(dataUrl)
if (c && c.__cache) { try { wPrimeDisplayThumbForRef(c, dataUrl) } catch (e) { /* ignore */ } ; return c }
return null
}
// v3.25.97:提示词封面(宿主图片库)—— 放在 Workbench 外,避免组件行数上涨
// v3.26.0:提示词封面 —— 直接存「压缩后的 dataURL」(≤512 WebP),随 prompts.json 落盘。
// 为什么不用引用({__blob}):封面是**跨会话必须可见**的小图,引用要依赖 IDB + 解析时序,
// 实测会出现“编辑里能看到、列表看不到/重启后丢失”。512px WebP 约 20~60KB,几十条完全可以接受。
// v3.26.34:封面编码/解析抽到 src/image-prompt-cover.js(app.js 让出行数给功能)
let wCoverCtl = null
function wPromptCoverCtl () {
if (wCoverCtl) return wCoverCtl
const M = (typeof window !== 'undefined') ? window.IWBPromptCover : null
if (!M) return null
wCoverCtl = M.create({
compress: (src, conf) => new Promise((resolve) => {
try { compressDataUrl(src, conf, (o) => resolve(o || '')) } catch (e) { resolve('') }
}),
resolve: (ref) => wResolveImgAsync(ref),
})
return wCoverCtl
}
// v3.26.1:把提示词封面插入画布 —— 返回 { ok, error }
async function wPromptInsertImage (host, cover, name) {
try {
let data = cover
let ratio = 1
if (typeof cover === 'string' && cover.indexOf('data:') === 0) {
ratio = await (window.IWBPromptCover ? window.IWBPromptCover.dataUrlAspect(cover) : Promise.resolve(1))
const ref = await wImgRefWrite(cover)
if (ref) data = ref
} else if (cover && typeof cover === 'object') {
const url = await wResolveImgAsync(cover)
if (url) ratio = await (window.IWBPromptCover ? window.IWBPromptCover.dataUrlAspect(url) : Promise.resolve(1))
}
if (!data) return { ok: false, error: '这条提示词没有封面' }
host.insertRefNode(data, name || '封面图片', window.IWBPromptCover ? window.IWBPromptCover.nodeWidthForAspect(ratio) : 280)
return { ok: true }
} catch (e) { return { ok: false, error: '插入封面失败' } }
}
// 兼容:老数据里可能是 {__blob}/{__cache} 引用对象(v3.25.97/98 写入),继续异步解析
async function wPromptCoverUrl (ref) {
try {
if (typeof ref === 'string' && ref.indexOf('data:') === 0) return { ok: true, url: ref }
const url = await wResolveImgAsync(ref)
return { ok: !!url, url: url || '' }
} catch (e) { return { ok: false, url: '' } }
}
// 一次性迁移(桌面版):把历史画布里内联的 dataURL 图转成 {__blob} 引用。
// 只在资料目录生效时跑,跑完打标记;之后保存画布本就会走同一规则。
async function wMigrateInlineImages() {
try {
const fileRuntime = (typeof window !== 'undefined' && window.IWBStorageFile && window.IWBStorageFile.enabled && window.IWBStorageFile.enabled())
? window.IWBStorageFile.runtime : null
if (!fileRuntime || storageRuntime() !== fileRuntime) return
if (lsGet('iwb_inline2blob_v2', false) === true) return
const raw = lsGet(StorageContract.localKeys.workspaces, null)
if (!raw || !Array.isArray(raw.workspaces)) { lsSet('iwb_inline2blob_v2', true); return }
const slim = await wSanitizeWs(raw)
lsSet(StorageContract.localKeys.workspaces, slim)
lsSet('iwb_inline2blob_v2', true)
} catch (e) { /* 迁移失败不影响启动,下次再试 */ }
}
async function wSanitizeWs(ws) {
// 2026-11-03:**不再剥离**生成结果,改为「精简后落盘」——只留 url/宽高/idb + 任务标识,
// 丢掉每条结果上挂的 job(含任务提示词全文、参考图引用数组)与 snapshot。
// 为什么必须落盘:输出节点只是 result 的只读投影,result 一变「会话态」,刷新/新开标签/换设备
// /切画布重装(LRU 驱逐)就全空(用户实拍:第二个标签打开同一画布,输出节点 0 张)。
// 体积代价:每条约 200B,单画布上限 60 条 ⇒ 十几 KB,且 job 不落盘后比原来的内存副本还小。
ws = GenerationResults ? GenerationResults.slimWs(ws) : withoutGenerationResults(ws)
let failed = false
for (const w of (ws && ws.workspaces) || []) {
for (const n of (w && w.nodes) || []) {
const d = (n && n.data) || {}
// data、url、result 内的 dataURL 都可能占用大量空间;生成结果常把图片放在 result.items 中。
for (const f of ['data', 'url']) {
let v = d[f]
if (!isBigDataUrl(v) || (v && v.__idb)) continue
// 节点图片不再压缩(v3.87.1 去掉「保存画布时压缩节点图片」):原图原样保留,
// 只把超过阈值的 dataURL 转成引用(新写入走 IDB Blob {__blob},失败回退 Cache Storage {__cache})。
// 无论缓存成功与否,都必须把当前值写回 d[f](否则压缩结果丢失、退回原图)。
// 2026-11-16(桌面版):阈值从 16384 降到 isBigDataUrl 的 3000 ⇒ 3K~16K 这批内联图也转引用。
// 文件落盘后 base64 没有存在意义(+33% 体积、每次渲染要解码),统一走 images/ 下的文件。
// C3 第3步:引用化只经唯一入口 —— 优先 IDB Blob({__blob}),失败自动回退 Cache({__cache})。
const ref = await wImgRefWrite(v)
// 两条通道都失败(配额/隐私模式):用确定性缓存键引用兜底,而不是把压缩后仍≥16KB 的 base64 塞回画布。
// 否则一张 4K 原图(约 10MB)会滞留 localStorage,单次保存即撑爆 5MB 配额(用户对标的「本地存储空间不足」)。
// 保留画布结构与节点关系,图片由显示端 wResolveImg 按缓存键解析;缓存恢复后可重新载入。
const cacheUrl = ref ? '' : wCacheKeyOf(v)
d[f] = ref || (cacheUrl ? { __cache: cacheUrl } : v)
if (!ref) failed = true // 两条通道都写失败:已用缓存键引用兜底,绝不把大 base64 滞留 localStorage
}
if (d.result !== undefined) {
const result = await sanitizeBigValue(d.result, n.id || 'n', 'result')
d.result = result.value
failed = failed || result.failed
}
}
}
if (failed) ws.__sanitizeFailed = true
return ws
}
// ---- 画板 hydrate 按需 + LRU(对标 opentu MAX_LOADED_BOARDS = 3)----
// 原实现启动时把「所有画布的所有节点」大图都读回 base64 并常驻 state(2 画布 × 200 张 2MB ≈ 900MB)。
// 现在只 hydrate 当前画布,其余保留 {__idb}/{__cache} 引用形态;切过去时再 hydrate;
// 最多同时保留 3 个已 hydrate 的画板,超出时把最旧的还原成引用形态并释放 base64。
const W_MAX_LOADED_BOARDS = 2 // v3.87.7:3 → 2(内存压力大时更早释放;配合 ≥85% 自动降级)
const wLoadedBoards = [] // LRU:末尾最新,元素 { id, w }
let wSessionsRef = null // S4:指向 Workbench 的 sessionsStore 只读视图(驱逐时保护打开画布的画板)
function wTouchLoadedBoard(id, w) {
if (!id) return
const i = wLoadedBoards.findIndex((x) => x.id === id)
if (i >= 0) wLoadedBoards.splice(i, 1)
wLoadedBoards.push({ id, w })
}
// 是否还有未解析的引用({__idb}/{__cache})
function wBoardNeedsHydrate(w) {
const has = (value) => {
if (!value) return false
if (Array.isArray(value)) return value.some(has)
if (typeof value === 'object') {
// C3 第2步:引用只要「已解析 / 解析失败 / 正在解析」就不再需要 hydrate —— 显示端 wResolveImg
// 会在渲染路径里驱动解析,不需要整块画板重读。
const rk = wImgRefKey(value)
if (rk) return !(wImgUrlByRef.has(rk) || wImgUrlFailed.has(rk) || wImgUrlPending.has(rk))
// __idb 迁移尝试过即不再需要(失败保留引用,避免反复重试把装载流程卡住)
if (value.__idb) return !wIdbRefTried.has(String(value.__idb))
for (const k of Object.keys(value)) if (has(value[k])) return true
}
return false
}
for (const n of ((w && w.nodes) || [])) {
const d = (n && n.data) || {}
if (has(d.data) || has(d.url) || has(d.result)) return true
}
return false
}
// C3 第2步:历史 {__idb: key}(ref_ 前缀的 base64 字符串)→ {__blob: key}(IDB Blob)。
// 读出的 base64 只在这一步短暂存在,转存后立即放手;失败保留引用形态(不抹成 null、不丢数据),
// 并用 wIdbRefTried 记账,避免每次装载反复重试、或让 wBoardNeedsHydrate 永远为真而卡住装载流程。
const wIdbRefTried = new Set()
async function wMigrateIdbRef(ref) {
const key = String((ref && ref.__idb) || '')
if (!key) return null
if (wIdbRefTried.has(key)) return ref
wIdbRefTried.add(key)
let raw = null
try { raw = await IDB.get(key) } catch (e) { raw = null }
if (!raw || typeof raw !== 'string' || raw.indexOf('data:') !== 0) return ref
if (wImageBlobStore()) {
try {
const r = await wImageBlobStore().put(raw)
if (r && r.ok && r.key) { const out = wImageBlobStore().refOf(r.key); wEnsureImgUrl(out); return out }
} catch (e) { /* 落 BlobStore 失败 → 退回 Cache 引用 */ }
}
try { const c = await iwbCacheWrite(raw); if (c && c.__cache) { wEnsureImgUrl(c); return c } } catch (e) { /* ignore */ }
return ref
}
async function wHydrateValue(value) {
if (Array.isArray(value)) { const out = []; for (const item of value) out.push(await wHydrateValue(item)); return out }
if (value && typeof value === 'object') {
// C3 第2步:引用形态一律**不产出 base64**
// - __blob / __cache:解析显示 objectURL(引用原样保留);要真字节的路径按需 wImgRefDataUrl
// - __idb:一次性迁移成 __blob
if (wIsBlobRef(value) || wIsCacheRef(value)) { wEnsureImgUrl(value); return value }
if (value.__idb) return await wMigrateIdbRef(value)
const out = {}; for (const k of Object.keys(value)) out[k] = await wHydrateValue(value[k]); return out
}
return value
}
async function wHydrateWorkspace(w) {
const hydList = (w && w.nodes) || [] // 2026-11-05 内存专项:分批水合,每 4 个节点让出主线程
for (let hi = 0; hi < hydList.length; hi++) {
const n = hydList[hi]
const d = (n && n.data) || {}
for (const f of ['data', 'url']) {
const v = d[f]
if (wIsBlobRef(v) || wIsCacheRef(v)) {
// v3.26.115:不再预读全部引用(原来 111 个各读 1.9MB,GC 来不及收 ⇒ ready-2s 恒有 ~170MB 峰);
// 显示层 wResolveImg 会按需解析,只读真正渲染到的。
void v
} else if (v && v.__idb) {
// 历史 __idb 引用 → __blob(读一次即转存,不再把 base64 留在画布数据里)
d[f] = await wMigrateIdbRef(v)
}
}
if (d.result !== undefined) d.result = await wHydrateValue(d.result)
if (hi && hi % 4 === 0) await new Promise((res) => setTimeout(res, 0))
}
return w
}
// 反向:把已 hydrate 的大图还原成引用形态。先确保写入成功再替换,绝不出现「引用指向不存在的数据」。
// 与「保存画布」共用同一引用化入口 wImgRefWrite(新写入主通道 = IDB Blob {__blob},失败回退 Cache)。
async function wRefValueAsync(value, nodeId, path) {
if (isBigDataUrl(value)) {
const ref = await wImgRefWrite(value)
if (ref) return ref
const url = wCacheKeyOf(value)
if (url) {
const key = idbKeyOf(IDB_REF_PREFIX, nodeId + '_' + path, value)
const ok = await idbPutDedup(key, value)
if (ok) return { __idb: key }
return { __cache: url }
}
return value
}
if (Array.isArray(value)) { const out = []; for (let i = 0; i < value.length; i++) out.push(await wRefValueAsync(value[i], nodeId, path + '_' + i)); return out }
if (value && typeof value === 'object' && !value.__idb && !value.__cache && !wIsBlobRef(value)) {
const out = {}; for (const k of Object.keys(value)) out[k] = await wRefValueAsync(value[k], nodeId, path + '_' + k); return out
}
return value
}
async function wUnhydrateWorkspace(w) {
for (const n of ((w && w.nodes) || [])) {
const d = (n && n.data) || {}
for (const f of ['data', 'url']) if (isBigDataUrl(d[f])) d[f] = await wRefValueAsync(d[f], n.id || 'n', f)
if (d.result !== undefined && containsBigDataUrl(d.result)) d.result = await wRefValueAsync(d.result, n.id || 'n', 'result')
}
return w
}
// 装载画板:先按 LRU 腾位置(保证最多 3 个已 hydrate),再 hydrate 目标画板
async function wLoadBoard(w, list, reason) {
if (!w || !w.id) return w
// 目标画板尚未装载时要为它预留一个名额,否则会出现「先加载第 4 个、再判断超限」的越界
const known = wLoadedBoards.some((x) => x.id === w.id)
await wEvictLoadedBoards(w.id, list, known ? W_MAX_LOADED_BOARDS : W_MAX_LOADED_BOARDS - 1)
if (wBoardNeedsHydrate(w)) { if (typeof window !== 'undefined' && window.__IWB_E2E__ === true) window.__IWB_E2E_HYDRATES__ = (window.__IWB_E2E_HYDRATES__ || 0) + 1; await wHydrateWorkspace(w) }
wTouchLoadedBoard(w.id, w)
// v3.87.17 反复加载护栏:同一画板在 60 秒内被反复加载(实测出现过 5 秒 6 次)会反复 hydrate 大图,
// 是"内存尖峰 + 卡顿"的来源之一。超阈值时记 sync-loop 并**暂停自动同步**(用户主动操作仍可继续)。
try {
const now = Date.now()
const st = wLoadGuard.get(w.id) || { at: now, n: 0 }
if (now - st.at > 60000) { st.at = now; st.n = 0 }
st.n++
wLoadGuard.set(w.id, st)
if (st.n === 7 && !wSyncPaused) {
wSyncPaused = true
if (CrashLog && typeof CrashLog.record === 'function') CrashLog.record('sync-loop', { scope: 'board-load', message: '同一画板 60 秒内被加载 ' + st.n + ' 次,已暂停自动同步', version: APP_VERSION, boardId: String(w.id), extra: { loads: st.n } })
}
} catch (e) { /* 护栏失败不影响加载 */ }
try { if (CrashLog && CrashLog.breadcrumb) CrashLog.breadcrumb('board-load', String(w.id) + ' nodes=' + ((w.nodes || []).length) + ' loaded=' + wLoadedBoards.length + (reason ? ' via=' + reason : '')) } catch (e) { /* ignore */ }
try { if (typeof window !== 'undefined' && window.IWBPerf) window.IWBPerf.tag('board') } catch (e) { /* ignore */ }
try { const MG = (typeof window !== 'undefined') ? window.IWBImageCacheMigrate : null; if (MG && typeof MG.once === 'function') MG.once(w, { read: iwbCacheRead, write: wImgRefWrite, bump: wImgUrlBump }).then(function (r) { try { if (r && r.total) { const S = (typeof window !== 'undefined') ? window.IWBStorageFile : null; if (S && S.logLine) S.logLine('cache-migrate ' + String(w.id) + ' ok=' + r.ok + ' fail=' + r.fail + ' total=' + r.total) } } catch (e) { /* ignore */ } }).catch(function () { /* ignore */ }) } catch (e) { /* 迁移失败不影响装载 */ }
return w
}
async function wEvictLoadedBoards(keepIds, list, keepMax, sessionAware) {
const max = Math.max(1, Number(keepMax) || W_MAX_LOADED_BOARDS)
// S4:保留集支持 Set/array/string;默认额外保护所有打开 session 的画板(不驱逐打开画布)
const keep = new Set(Array.isArray(keepIds) ? keepIds : (keepIds instanceof Set ? keepIds : [keepIds].filter(Boolean)))
if (sessionAware !== false && wSessionsRef) { for (const sid of wSessionsRef.keys()) keep.add(sid) }
// 把所有保留画板移到末尾(最近使用)
for (const id of keep) {
const hit = wLoadedBoards.findIndex((x) => x.id === id)
if (hit >= 0) { const it = wLoadedBoards.splice(hit, 1)[0]; wLoadedBoards.push(it) }
}
// 只驱逐非保留画板,直到不超上限(全保留时停止,不无限循环)
while (wLoadedBoards.length > max) {
const idx = wLoadedBoards.findIndex((x) => !keep.has(x.id))
if (idx < 0) break
const victim = wLoadedBoards.splice(idx, 1)[0]
if (!victim) break
const live = (list || []).find((x) => x && x.id === victim.id) || victim.w
try { await wUnhydrateWorkspace(live) } catch (e) { /* 还原失败不影响主流程 */ }
// C3:画板被 LRU 驱逐(不再显示)时,回收它的图片引用 objectURL(字节仍在 IDB/Cache,下次装载重新解析)
try { wReleaseImgUrls(wCollectImgRefKeys({ nodes: (live && live.nodes) || [] })) } catch (e) { /* 回收失败不影响主流程 */ }
}
}
let wLastSelfSaveAt = 0 // v3.87.20:我们自己刚保存完成的时间(用于破除"轮询-保存"自激)
const wLoadGuard = new Map() // boardId → { at, n }:60 秒窗口内的加载次数
let wSyncPaused = false // 触发护栏后暂停自动同步(避免"加载↔保存"自激)
async function wHydrateWs(ws) {
const list = (ws && ws.workspaces) || []
if (!list.length) return ws
// 当前画布:优先 localStorage 记录(与 UI 恢复逻辑一致),退回索引 activeId
let act = ''
act = lsRawGet('iwb_ws_active', '') || ''
const target = list.find((w) => w.id === act) || list.find((w) => w.id === (ws && ws.activeId)) || list[0]
if (target) await wLoadBoard(target, list)
return ws
}
// ---- 内部节点剪贴板单一契约(v3.87 剪贴板审计)----
// 只存「结构(节点/连线/分组)+ 图片引用({__cache}/{__idb}/URL)」,不把 base64 写进 localStorage;
// 每条带 at 时间戳;TTL 10 分钟(读取时过期即忽略并删除)——过期后不再保留 IDB/Cache 里的图,避免配额被永久占住。
const CLIPBOARD_KEY = 'iwb_clipboard'
const CLIPBOARD_TTL_MS = 10 * 60 * 1000
function wClipValid(c) {
return !!(c && c.app === 'image-workbench' && c.type === 'iwb-clipboard' && Array.isArray(c.nodes) && c.nodes.length && Number(c.at) > 0)
}
function wClipDrop() { try { lsRemove(CLIPBOARD_KEY) } catch (e) { /* ignore */ } }
function wClipReadLs() {
let raw = null
try { raw = lsRawGet(CLIPBOARD_KEY, null) } catch (e) { return null }
if (!raw) return null
let parsed = null
try { parsed = JSON.parse(raw) } catch (e) { return null }
if (!wClipValid(parsed)) return null
if (Date.now() - Number(parsed.at) > CLIPBOARD_TTL_MS) { wClipDrop(); return null }
return parsed
}
// 剪贴板里的 {__idb}/{__cache} 是「活引用」:源画布被删或清理时不能当孤儿回收,否则粘贴过来的图会失效。
function wClipCollectRefs(keep) {
const c = wClipReadLs()
if (!c) return
const walk = (v) => {
if (!v) return
if (Array.isArray(v)) { for (const x of v) walk(x); return }
if (typeof v === 'object') {
if (v.__idb) { keep.add(v.__idb); return }
if (v.__cache) { keep.add(v.__cache); return }
if (wIsBlobRef(v)) { keep.add(String(v.__blob)); return }
for (const k of Object.keys(v)) walk(v[k])
}
}
for (const n of c.nodes) walk(n && n.data)
}
// IDB 孤儿清理节流:wCleanIdb 每次保存都会 IDB.keys()(getAllKeys 扫全图库索引)+ 逐条 del。
// 大图库(几百张输出/原图)+ 频繁自动保存时,这会让每 1.5s 一次保存都做 O(图库量) 的 IDB 读+写,
// 是「移动节点后 CPU 持续 10-16% / GC / 不流畅」的显著来源。改为 ≤30s 才真正扫库一次(孤儿最多滞留 30s,IDB 配额大、无损)。
let _cleanIdbLast = 0
// C3:撤销历史栈的只读访问桥(由画布组件登记)。历史快照同样钉住图片字节,
// 不做保留集合的话「删除节点 → 撤销」会因字节被当孤儿回收而丢图(__cache 时代由 Cache 不回收天然规避)。
let wHistoryNodesGetter = null
function wHistorySnapshotNodes() {
try { const h = wHistoryNodesGetter ? wHistoryNodesGetter() : null; return (h && h.stack) || [] } catch (e) { return [] }
}
async function wCleanIdb(ws) {
const keep = new Set()
const collect = (value) => {
if (!value) return
if (Array.isArray(value)) { for (const item of value) collect(item); return }
if (value && typeof value === 'object') {
if (value.__idb) { keep.add(value.__idb); return }
// C3:Blob 引用与 IDB 引用同在 images store,一起进保留集合(否则对象图的字节会被当孤儿删掉)
if (wIsBlobRef(value)) { keep.add(String(value.__blob)); return }
for (const k of Object.keys(value)) collect(value[k])
}
}
// v3.26.116:**递归整个 node.data**。原来只扫 data/url/result,漏掉插件节点里的图片引用
// (相册 data.items[].src)⇒ 固化后的 {__blob} 被当孤儿删掉,重开只剩缩略图(实测 18 个里丢 16 个)。
for (const w of (ws && ws.workspaces) || []) for (const n of (w && w.nodes) || []) collect((n && n.data) || {})
// 出图缩略图/原图:保留 outputs 索引中仍在的(随保留策略删除的索引 → 孤儿一并回收)
const oidx = lsGet(OUT_KEY, [])
for (const f of oidx) { if (f && f.idb) keep.add(f.idb); if (f && f.origIdb) keep.add(f.origIdb) }
// 内部剪贴板里引用的图是活引用(复制 → 切画布/删源画布 → 粘贴):加入保留集合,不能被当孤儿回收。
wClipCollectRefs(keep)
// C3:撤销历史快照里的 blob 引用计入保留集合
try { for (const k of wCollectImgRefKeys(wHistorySnapshotNodes())) { const s = String(k); if (s.indexOf('b:') === 0) keep.add(s.slice(2)) } } catch (e) { /* 读取失败不影响清理 */ }
// S8/§3.12:所有打开 session 的当前数据 + 各自历史栈引用也计入保留集——
// 非激活 session 的历史 blob 引用与未持久化引用不在持久化列表里,不保留会被当孤儿删掉(切过去黑图/撤销丢图)
if (wSessionsRef) {
wSessionsRef.forEach((s) => {
try { for (const k of wCollectImgRefKeys({ nodes: s.nodes || [] })) { const str = String(k); if (str.indexOf('b:') === 0) keep.add(str.slice(2)) } } catch (e) { /* ignore */ }
try { for (const snap of (s.history && s.history.stack) || []) { for (const k of wCollectImgRefKeys(snap)) { const str = String(k); if (str.indexOf('b:') === 0) keep.add(str.slice(2)) } } } catch (e) { /* ignore */ }
})
}
const now = Date.now()
if (now - _cleanIdbLast < 30000) return // 30s 内已扫过:跳过本次全量扫描,降 IDB 读/写与 GC
_cleanIdbLast = now
// 收藏节点组里的图引用同样是活引用(收藏 → 刷新/切画布 → 实例化):必须计入保留集合,
// 否则会被当孤儿回收、实例化出来的组图空白。放在节流之后:只有真要扫库时才读一次收藏组。
try {
const savedGroups = lsGet(StorageContract.localKeys.groups, []) || []
for (const g of savedGroups) for (const n of ((g && g.nodes) || [])) collect((n && n.data) || {})
} catch (e) { /* 读取失败不影响清理 */ }
const keys = await IDB.keys()
for (const k of keys) {
// C3:imgblob_ 前缀(图片字节仓库)单独回收 —— 只保留仍被画布/剪贴板/收藏组引用的那张;
// 删除时同步撤销它已解析出的 objectURL,避免「字节删了、URL 还挂着」。
if (k.indexOf(IMG_BLOB_PREFIX) === 0) {
if (!keep.has(k)) {
wReleaseImgUrls(['b:' + k])
try { if (wImageBlobStore()) { const okDel = await wImageBlobStore().del(k); if (okDel === false) swallow('image', new Error('blob-del-failed')) } else await IDB.del(k) } catch (e) { swallow('image', e) }
}
continue
}
if ((k.indexOf(IDB_REF_PREFIX) === 0 || k.indexOf(IDB_OUT_PREFIX) === 0 || k.indexOf(IDB_ORIG_PREFIX) === 0) && !keep.has(k)) { await IDB.del(k); wIdbDone.delete(k); wIdbRefTried.delete(k) }
}
}
// 存储体检(只读):把 IDB 键与图库索引交给纯函数统计,不删任何东西。
async function wStorageAudit() {
if (!StorageHealth || typeof StorageHealth.audit !== 'function') return null
let idbKeys = []
try { idbKeys = await IDB.keys() } catch (e) { idbKeys = [] }
const outputs = lsGet(OUT_KEY, [])
const res = StorageHealth.audit({ idbKeys, outputsIndex: Array.isArray(outputs) ? outputs : [], prefixes: { blob: IMG_BLOB_PREFIX, ref: IDB_REF_PREFIX, out: IDB_OUT_PREFIX, orig: IDB_ORIG_PREFIX } })
try { const PD = window.IWBPluginData; if (PD && PD.totalSize) { const t = await PD.totalSize(); res.pluginDataBytes = t.bytes; res.pluginDataCount = t.count } } catch (e) { /* M2:插件数据纳入体检 */ }
res.gallery = await (window.IWBGalleryAudit ? window.IWBGalleryAudit.run({ index: outputs, storageFile: window.IWBStorageFile, idbKeys }) : null) // 图库落盘三态(src/gallery-audit.js)
return res
}
// 一键安全回收:复用保存路径的 wCleanIdb(带活引用 keep-set),绕过 30s 节流手动触发一次。
// 哨兵:读不到画布数据就中止 —— 否则 keep-set 为空会把所有图片字节当孤儿删掉。
async function wReclaimOrphansNow() {
const ws = WorkspaceStore.read(null)
if (!ws || !Array.isArray(ws.workspaces) || !ws.workspaces.length) throw new Error('读不到画布数据,已中止(避免误删)')
_cleanIdbLast = 0
await wCleanIdb(ws)
return true
}
// ---- 画布独立存储(ws-keys):localStorage 索引 + 每个画布独立 key iwb_ws_<id> ----
const WS_KEY_PREFIX = 'iwb_ws_'
const wsKey = (id) => WS_KEY_PREFIX + id
const buildWsIndex = (data) => ({
schemaVersion: SchemaVersions.workspace, store: 'ws-keys', activeId: (data && data.activeId) || '',
rev: Number(data && data.rev) || 1,
workspaces: ((data && data.workspaces) || []).map((w) => ({
id: String(w.id || 'ws_default'), name: String(w.name || '未命名画布'),
nodeCount: (w.nodes || []).length, edgeCount: (w.edges || []).length,
category: typeof w.category === 'string' ? w.category : '', starred: !!w.starred, deleted: !!w.deleted,
lastUsed: typeof w.lastUsed === 'number' ? w.lastUsed : 0,
})),
})
const WS_FULL_KEY = 'iwb_web_workspaces_full'
// v3.87.14 增量写:只写"内容真的变了"的画板。
// 原来每次保存都把**全部**画板逐个重写(实测 44 块 → 每次 44 次序列化 + 44 次 setItem),
// 这正是"用着卡一下"与诊断采样里 528MB/1075MB 瞬态尖峰的来源,也是配额被反复冲刷的原因。
const wsWriteSig = new Map() // id → 上次写入的分板记录文本
// v3.87.22 关键:签名**不再 JSON.stringify 整块画板**。
// 原实现每次保存都为主板生成一份完整 JSON(内存里的画板带着 ~30MB base64)→
// 每次保存产生几十 MB 垃圾(活动时每 ~1.5 秒一次)→ V8 堆一级级被撑大(诊断里的"阶梯式上涨"
// 正是这个特征:堆 2671MB 而所有可测结构仅 53.9MB,刷新后立刻回到 205MB)。
// 现在:结构字段直接拼、大字符串只做**无分配的哈希**、小对象才 stringify。
const wSigHash = (v) => { let h = 2166136261; for (let i = 0; i < v.length; i++) { h ^= v.charCodeAt(i); h = (h * 16777619) >>> 0 } return h }
const wSigVal = (v) => {
if (v === undefined) return 'u'
if (v === null) return 'n'
if (typeof v === 'string') return v.length > 64 ? ('#' + wSigHash(v)) : v
if (typeof v === 'number' || typeof v === 'boolean') return String(v)
try { const j = JSON.stringify(v); return (j && j.length > 512) ? ('#' + wSigHash(j)) : String(j) } catch (e) { return '?' }
}
const wsBoardSig = (rec) => {
try {
const nodes = rec.nodes || []
const parts = []
for (const n of nodes) {
const d = (n && n.data) || {}
let dl = ''
for (const k in d) dl += k + '=' + wSigVal(d[k]) + ','
parts.push((n && n.id) + ':' + (n && n.type || '') + ':' + (n && n.w || 0) + 'x' + (n && n.h || 0) + ':' + (n && n.x || 0) + ',' + (n && n.y || 0) + ':' + dl)
}
// v3.26.109:组签名含成员、边签名含端点(原先各自只算条数)——否则「移出单个成员 / 换一条连线」条数不变,会被
// 「内容未变 → 跳过写盘」误判 ⇒ 界面生效但刷新/重启回滚(2026-11-27 实测:换参考图重启后连回旧节点)。
const gsig = (rec.groups || []).map((g) => ((g && g.id) || '') + ':' + (((g && g.memberIds) || []).join('+'))).join(';')
return (rec.id || '') + '|' + (rec.name || '') + '|' + (rec.starred ? 1 : 0) + (rec.deleted ? 1 : 0) + '|' + nodes.length + '|' + wSigVal((rec.edges || []).map((e) => ((e && e.id) || '') + ':' + ((e && e.from) || '') + '>' + ((e && e.to) || '')).join(';')) + '|' + gsig + '|' + parts.join(';')
} catch (e) { return '' }
}
const wsWriteKeys = (data) => {
const list = (data && data.workspaces) || []
let ok = true
// 写入前再剥离大图 base64(>3000)→ IndexedDB ref_,localStorage 只存引用,
// 避免「压缩后仍 >3000 的 base64」累积撑爆 5MB(对标 opentu:画布数据轻量化)。
try { stripBigDataUrlsSync({ workspaces: list }, true) } catch (e) { /* 尽力而为 */ }
for (const w of list) {
if (!w || !w.id) continue
const rec = { id: w.id, name: w.name || '未命名画布', nodes: w.nodes || [], edges: w.edges || [], groups: w.groups || [], category: w.category || '', starred: !!w.starred, deleted: !!w.deleted, lastUsed: typeof w.lastUsed === 'number' ? w.lastUsed : 0 }
// 兜底精简:所有 localStorage 写盘必经此处,漏了就会把 result 里的 job/snapshot 落盘(体积翻十倍)
if (GenerationResults) rec.nodes = rec.nodes.map(GenerationResults.slimNode)
const sig = wsBoardSig(rec)
if (sig && wsWriteSig.get(w.id) === sig) continue // 内容未变 → 跳过写盘
const perOk = LocalStore.set(wsKey(w.id), rec)
if (perOk && sig) wsWriteSig.set(w.id, sig)
if (!perOk) ok = false
}
// 不再把「全量快照」写进 localStorage(它会把所有画布再复制一份,占约一半空间,是 5MB 满的主因)。
// 每个画布独立 key iwb_ws_<id> 已是主数据;全量快照仅作旧数据兜底读取,不再重复落盘。
const idxOk = LocalStore.set(StorageContract.localKeys.workspaces, buildWsIndex(data))
return (idxOk && ok)
}
const wsFullSnapshot = (fallback) => {
const snap = LocalStore.get(WS_FULL_KEY, null)
return (snap && Array.isArray(snap.workspaces)) ? snap : fallback
}
const wsReadKeys = (fallback) => {
const idx = LocalStore.get(StorageContract.localKeys.workspaces, null)
if (!idx || idx.store !== 'ws-keys' || !Array.isArray(idx.workspaces)) return fallback
const list = idx.workspaces.map((meta) => {
const rec = LocalStore.get(wsKey(meta.id), null)
if (rec && Array.isArray(rec.nodes)) return Object.assign({}, rec, { category: (typeof meta.category === 'string' && meta.category) ? meta.category : rec.category, starred: meta.starred, deleted: meta.deleted, lastUsed: meta.lastUsed })
return { id: meta.id, name: meta.name, nodes: [], edges: [], groups: [], category: meta.category, starred: meta.starred, deleted: meta.deleted, lastUsed: meta.lastUsed }
})
// 单画布独立 key 缺失/为空但索引声称有节点 → 采用全量快照兜底,避免节点丢失
const mismatch = list.some((w, i) => idx.workspaces[i] && idx.workspaces[i].nodeCount > 0 && (!w.nodes || w.nodes.length === 0))
if (mismatch) {
const snap = wsFullSnapshot(null)
if (snap && Array.isArray(snap.workspaces) && snap.workspaces.length) return snap
}
return { schemaVersion: SchemaVersions.workspace, workspaces: list, activeId: idx.activeId || (list[0] && list[0].id) || '', rev: idx.rev || 1 }
}
const wsMigrateKeys = () => {
const raw = LocalStore.get(StorageContract.localKeys.workspaces, null)
if (!raw || raw.store === 'ws-keys' || !Array.isArray(raw.workspaces)) return false
const data = { activeId: raw.activeId, rev: raw.rev, workspaces: raw.workspaces.map((w) => Object.assign({}, w, { nodes: w.nodes || [], edges: w.edges || [], groups: w.groups || [] })) }
const ok = wsWriteKeys(data)
if (ok) { try { lsSet('iwb_web_workspaces_legacy', raw) } catch (e) { /* ignore */ } }
return ok
}
// 工作台领域适配器:索引在 localStorage,每个画布完整图存独立 key iwb_ws_<id>(同步读写,刷新/关闭都能保住)
const WorkspaceStore = {
read(fallback) {
const raw = LocalStore.get(StorageContract.localKeys.workspaces, null)
if (raw && raw.store === 'ws-keys') return wsReadKeys(fallback)
if (raw && Array.isArray(raw.workspaces) && raw.workspaces.some((w) => Array.isArray(w.nodes) && w.nodes.length)) {
if (wsMigrateKeys()) return wsReadKeys(fallback)
}
return raw || fallback
},
write(value) { return wsWriteKeys(value) },
}
// 浏览器本地模式标志(无服务器;状态栏等按此显示)
const IS_BROWSER_MODE = true
// 工作台写入串行化:保存会异步压缩/写入参考图到 IndexedDB,并清理孤儿图片。
// 若多个保存同时执行,前一个快照的清理可能误删后一个快照刚写入的参考图。
let workspaceWriteQueue = []
let workspaceWriteRunning = false
const drainWorkspaceWrites = () => {
const item = workspaceWriteQueue.shift()
if (!item) { workspaceWriteRunning = false; return }
workspaceWriteRunning = true
let result
try { result = Promise.resolve(item.task()) } catch (e) { result = Promise.reject(e) }
result.then(item.resolve, item.reject).finally(drainWorkspaceWrites)
}
const enqueueWorkspaceWrite = (task) => new Promise((resolve, reject) => {
workspaceWriteQueue.push({ task, resolve, reject })
if (!workspaceWriteRunning) drainWorkspaceWrites()
})
// 数据层 API(与 server 响应格式一致)
function wApi(name, args) {
if (name === 'config') {
// 读 ⇒ wCfgPublic():**对外/设置弹窗展示形态**(白名单子集 + 密钥掩码),禁止用于持久化/备份。
// 写 ⇒ wCfgSave():真实设置的唯一写入点(设置弹窗保存与备份还原共用)。
// 备份导出不走这里:它必须用 wBackupConfig()(源是 wRawCfg())。
// 历史坑:这里曾有 `config?full=1` 分支,名字与注释都声称"返回完整配置",实际仍返回 wCfgPublic()
// ⇒ 备份只写进了展示形态(丢 compression 等字段、withKeys 开关失效)。已删除该别名,
// 契约测试断言全仓库不再出现 `config?full=1`。
return Promise.resolve(args === undefined ? wCfgPublic() : wCfgSave(args))
}
if (name === 'prompts') {
if (args === undefined) return Promise.resolve({ prompts: lsGet(StorageContract.localKeys.prompts, []) })
const ok = lsSet(StorageContract.localKeys.prompts, (args && args.prompts) || [])
return Promise.resolve(storageResult(ok, ok ? null : { error: '提示词库保存失败:浏览器本地存储空间不足。' }))
}
if (name === 'groups') {
if (args === undefined) return wLoadGroups()
return wSaveGroups(args && args.groups, args && args.groupGroups)
}
if (name === 'workspaces') {
// 轻量轮询同步:只读索引拿 rev(不遍历每个画布的全部节点/引用),避免每 3s 在主线程做 O(全部画布数据) 的读取+JSON 解析。
// 这是「空闲 CPU 持续占用」的主要来源之一(跨标签页轮询)。
if (args && args.light) {
const idx = LocalStore.get(StorageContract.localKeys.workspaces, null)
if (idx && typeof idx.rev === 'number') return Promise.resolve({ rev: idx.rev })
}
if (args === undefined || (args && args.light)) {
const ws = WorkspaceStore.read(null)
if (ws && Array.isArray(ws.workspaces) && ws.workspaces.length) {
// 轻量读取(轮询同步用):只比对 rev,不 hydrate 大图(避免每 3s 全量读 IndexedDB)
if (args && args.light) return Promise.resolve(ws)
return wHydrateWs(ws)
}
const fresh = { schemaVersion: SchemaVersions.workspace, workspaces: [{ id: 'ws_default', name: '工作台 1', nodes: [], edges: [], groups: [] }], activeId: 'ws_default', rev: 1 }
WorkspaceStore.write(fresh)
return Promise.resolve(fresh)
}
const writeWorkspace = async () => {
const prev = WorkspaceStore.read(null)
// ── v3.87.8 索引并集守卫(只增不减)──
// 症状:崩一次/异常返回后,某块画板"从列表里消失"(其它画板还在)。
// 原因方向:写索引时用的列表把该画板漏掉了。这里做**并集**:存储里已有、这次没带、
// 且用户没有明确"彻底删除"的画板,一律补回列表后再写。只增加、绝不删除。
try {
const stored = (prev && Array.isArray(prev.workspaces)) ? prev.workspaces : []
const incoming = (args && Array.isArray(args.workspaces)) ? args.workspaces : []
const inIds = new Set(incoming.map((w) => w && w.id).filter(Boolean))
const kept = stored.filter((w) => w && w.id && !inIds.has(w.id) && !wPurgeIntent.has(w.id))
if (kept.length) {
args.workspaces = incoming.concat(kept)
if (CrashLog && typeof CrashLog.record === 'function') CrashLog.record('index-union-keep', { scope: 'workspace-write', message: '索引并集守卫:补回 ' + kept.length + ' 块被漏掉的画板', version: APP_VERSION, extra: { kept: kept.map((w) => String(w.id)).slice(0, 5) } })
}
} catch (e) { /* 守卫失败不阻塞保存 */ }
wPurgeIntent.clear()
// 保存版本号递增:跨窗口/跨设备轮询据此感知变化并同步
const nextRev = (prev && typeof prev.rev === 'number') ? prev.rev + 1 : 1
let data = { schemaVersion: SchemaVersions.workspace, workspaces: ((args && args.workspaces) || []).map((w) => ({ ...w, nodes: ((w && w.nodes) || []).map((n) => ({ ...n, data: Object.assign({}, (n && n.data) || {}) })) })), activeId: (args && args.activeId) || '', rev: nextRev }
// 先同步写入一份轻量快照:wSanitizeWs 需要 await 图片压缩/IDB,若直接等待,
// React 事件结束后的刷新可能落在该微任务之前,导致最新画布尚未进入 localStorage。
// 同步副本只剥离大 dataURL,不改变异步路径对压缩图片的最终处理。
const syncData = {
schemaVersion: SchemaVersions.workspace,
workspaces: data.workspaces.map((w) => ({ ...w, nodes: (w.nodes || []).map((n) => ({ ...n, data: Object.assign({}, (n && n.data) || {}) })) })),
activeId: data.activeId,
rev: data.rev,
}
// 同步分支也要精简生成结果(否则这条「先写」的快照会把 job/snapshot 一并塞进 localStorage)
if (GenerationResults) syncData.workspaces = GenerationResults.slimList(syncData.workspaces)
stripBigDataUrlsSync(syncData, true)
const syncOk = WorkspaceStore.write(syncData)
let sanitizeError = null
if (!syncOk) sanitizeError = iwError('storage', '同步保存轻量工作台快照失败')
// 压缩/IDB 处理作用于返回的 ws(withoutGenerationResults 会生成新对象),
// 必须用返回值覆盖 data,否则写盘仍是未压缩的原图(保存慢且占空间)。
try { data = await wSanitizeWs(data) } catch (e) { sanitizeError = e }
let ok = false
try { ok = WorkspaceStore.write(data) } catch (e) { sanitizeError = sanitizeError || e }
// 图片压缩/IndexedDB/完整快照写入任一环节失败时,统一回退到已写入的轻量快照。
// 画布结构必须优先保存,不能因为第三方图片缓存失败而提示整张画布未保存。
if (!ok) {
try { ok = WorkspaceStore.write(syncData) } catch (e) { sanitizeError = sanitizeError || e }
if (ok) {
try { await wCleanIdb(WorkspaceStore.read(null) || syncData) } catch (e) { /* best effort */ }
return { ok: true, warn: sanitizeError ? '图片本地缓存暂时不可用,已保存画布结构;图片可在存储恢复后重新载入' : null, rev: nextRev }
}
}
try { await wCleanIdb(WorkspaceStore.read(null) || data) } catch (e) { /* best effort */ }
// 写失败必须让上层感知:不静默返回 ok,避免 UI 显示「已保存」实际却丢失
if (!ok) {
// 先尝试释放冗余快照/legacy(这些是重复副本,可安全清除)腾出 localStorage 再重试一次
try { lsRemove('iwb_web_workspaces_legacy') } catch (e) { /* ignore */ }
try { lsRemove('iwb_web_workspaces_full') } catch (e) { /* ignore */ }
try { lsRemove('iwb_web_save_recovery') } catch (e) { /* ignore */ }
if (!ok) { try { ok = WorkspaceStore.write(syncData) } catch (e) { sanitizeError = sanitizeError || e } }
try { if (CrashLog && typeof CrashLog.record === 'function') CrashLog.record('save-fail', { scope: 'workspace-write', message: '画布写入失败(浏览器本地存储空间不足)', version: APP_VERSION }) } catch (e) { /* ignore */ }
if (!ok) return { ok: false, error: '浏览器本地存储空间不足,画布未能保存。请到设置→图片保存清理图库、或删除部分图片节点/不用的画布后重试。' + ('(' + String((sanitizeError && sanitizeError.message) || '存储已满').slice(0, 120) + ')') }
}
if (data.__sanitizeFailed) return { ok: true, warn: '部分图片写入本地存储失败(空间或隐私模式),已保留画布结构', rev: nextRev }
return { ok: true, rev: nextRev }
}
// 所有工作台保存(包括切换、生成完成和自动保存)共享同一队列。
// 清理必须在当前完整快照写入后完成,下一次保存才能开始,避免旧快照 GC 删除新快照引用。
return enqueueWorkspaceWrite(writeWorkspace)
}
if (name === 'graph') {
if (args === undefined) return Promise.resolve({ graph: null })
return Promise.resolve({ ok: true })
}
if (name === 'outputs') return (args && args.action) ? wActionOutputs(args) : wListOutputs(args)
if (name === 'generate') return wGenerate(args).catch((e) => [{ ok: false, error: String((e && e.message) || e) }])
// 分层失败也走「结果数组」形态(与生图一致),由 runLayerNode 统一落成 error 项
if (name === 'decomposeLayers') return wDecomposeLayers(args).catch((e) => [{ ok: false, error: layerErrorText((e && e.message) || e, '分层请求失败'), errorType: (e && e.iwbType) || 'unknown' }])
if (name === 'llm') return wLlm(args)
if (name === 'llmTest') return wLlmTest(args)
if (name === 'models') return wModels(args)
if (name === 'ping') return wPing(args)
return Promise.resolve({ ok: true })
}
function api(name, args) {
return wApi(name, args)
}
// ---------- constants ----------
const APP_VERSION = 'v3.6.0' // 界面版本标记(刷新后可见,用于确认是否最新代码)
const NODE_W = 264
// 节点视觉宽度的唯一来源:生图节点默认 480px、分层节点 520px(分层清单行更宽),其余节点使用通用宽度。
// 连线、端口、框选、分组和小地图都应使用此函数,避免视觉框与几何计算错位。
const nodeWidth = (n) => n && (n.type === 'relay' ? 72 : (n.w || (n.type === 'gen' ? 480 : (n.type === 'layer' ? 520 : NODE_W))))
// 节点创建/对齐/编组时使用的默认外框宽度:out 固定 420 是既有约定(与 nodeWidth 的兜底值不同,勿合并成一处)。
const defaultNodeBoxWidth = (n) => (n && n.w) || (n && n.type === 'layer' ? 520 : (n && n.type === 'gen' ? 480 : (n && n.type === 'out' ? 420 : NODE_W)))
// 产图节点:会写 data.result 的图源(生图 / 分层)。
// 新增产图类型时**只改这一处**——连线、运行入口、结果作废、输出节点、图库归档全都读它,
// 避免散落的 n.type === 'gen' 漏改(漏在运行入口=点了没反应,漏在作废=改完还显示旧结果)。
const isImageProducer = (n) => { if (!n) return false; const s = NODE_TYPES.get(n.type); return s ? s.producer === true : (n.type === 'gen' || n.type === 'layer') }
const GEN_CONCURRENCY_DEFAULT = 4 // 浏览器同时提交的图片请求数默认上限
const GEN_CONCURRENCY_MIN = 1
const GEN_CONCURRENCY_MAX = 16
function generationConcurrency(cfg) {
const n = Number(cfg && cfg.canvas && cfg.canvas.generationConcurrency)
return Number.isFinite(n) ? Math.max(GEN_CONCURRENCY_MIN, Math.min(GEN_CONCURRENCY_MAX, Math.round(n))) : GEN_CONCURRENCY_DEFAULT
}
const GEN_TIMEOUT_MS = 240000 // 单张生成软超时:仅提示等待,不中断上游请求,避免重复计费
// 单张硬上限(25 分钟):到点只停止浏览器侧等待并标记「结果未知」,绝不自动重提(服务商可能已生成,重试有重复计费风险)。
// 同一个 AbortController 同时覆盖「等响应头」和「读响应体」两段,因此 body 卡住也能收场。
const GEN_HARD_TIMEOUT_MS = 25 * 60 * 1000
const GEN_HARD_TIMEOUT_MIN = Math.round(GEN_HARD_TIMEOUT_MS / 60000)
const genHardTimeoutMessage = (phase) => '已停止等待(' + (phase || '超过 ' + GEN_HARD_TIMEOUT_MIN + ' 分钟') + '):结果未知,服务商可能已生成;是否重试由你决定(重试有重复计费风险)'
const NODE_H = { prompt: 216, ref: 252, gen: 460, out: 320, llm: 240, textout: 220, combine: 240, batch: 240, relay: 72, plugin: 200, layer: 520 }
// v3.1.0 全灰阶:节点类型色改「同深度灰阶梯度」(按原色亮度排序,保留类型间的深浅区分)
const COLORS = { batch: '#737373', prompt: '#7a7a7a', layer: '#7e7e7e', out: '#828282', ref: '#868686', llm: '#8a8a8a', textout: '#8e8e8e', combine: '#969696', relay: '#a1a1a1', gen: '#a7a7a7', plugin: '#969696' }
const NODE_TITLES = { prompt: '提示词', ref: '图片', gen: '配置', out: '输出', llm: '润色', textout: '文本', combine: '组合', batch: '连接', relay: '中继', layer: '分层', plugin: '插件' }
// 节点标题带:显示在节点外框上方左侧(世界坐标,随缩放变化)。
// 标题强制单行省略 → 高度恒定,气泡抬升无需运行时测量,也不引入任何拖拽期 re-render。
// 几何:标题条高 22 + 与节点外框间隙 6 = 28(head 的 bottom:100% + margin-bottom:8px,扣除 2px 上边框后净距 6)。
const NODE_HEAD_H = 28
const NODE_HEAD_FB_GAP = 1 // 组气泡与组操作栏之间再留的间隙(GROUP_LIFT 用)
// 2026-10-30:单节点气泡改为**压在标题带上**(用户要求:气泡与节点顶部的距离 = 标题与节点顶部的距离)。
// 实测标题带底边距节点顶 7px ⇒ 气泡底边也放在 7px 处,气泡会遮住标题(改名入口改到气泡/右键菜单)。
const FLOATBAR_COVER_GAP = 7
// 中继节点不显示标题
const hasNodeTitle = (n) => !!(n && n.type && n.type !== 'relay')
const NODE_ICON = { prompt: 'file-text', ref: 'ref', gen: 'gen', out: 'presentation', llm: 'llm', textout: 'file-type-corner', combine: 'server-plus', batch: 'batch', layer: 'layer', relay: 'circle-dot' }
// ---------- 节点组外框(v3.84.0)----------
// 基础内边距(世界坐标)。顶部必须容纳「节点标题带 28 + 间隙 8 + 组操作栏 40 + 间隙 8」:
// 操作栏钉在外框顶边(top:-10px,高 40)→ 若外框顶边离节点不足,操作栏就会与被标题带抢位置,
// 表现为「点不到组标题、移不动组」(实测重叠 14px、横向完全覆盖)。
// 操作栏几何:必须与 style.css 的 .iwb-group-bar 同步(height:40px / top:-10px / 图标按钮 30px)
const GROUP_BAR_H = 40
const GROUP_BAR_OVERHANG = 10
const GROUP_BAR_GAP = 8
// 外框顶部内边距取两个约束的较大值:
// ① 组操作栏不压节点标题带 → NODE_HEAD_H + GAP + BAR_H − OVERHANG = 28 + 8 + 40 − 10 = 66
// ② 组内**单选**气泡(贴节点,高 40 = FB_EST_H,与节点间隙 7)不得被操作栏盖住
// → FB_EST_H + FLOATBAR_COVER_GAP + (BAR_H − OVERHANG) + 1 = 40 + 7 + 30 + 1 = 78
// ② 是 v3.24.28 新增:气泡与组外统一下移后,需要这 12px 才不至于钻进操作栏底下。
// 改操作栏尺寸时只需改上面三个常量,两条约束都会自动跟随。
const GROUP_PAD_TOP = Math.max(NODE_HEAD_H + GROUP_BAR_GAP + GROUP_BAR_H - GROUP_BAR_OVERHANG, 40 + FLOATBAR_COVER_GAP + GROUP_BAR_H - GROUP_BAR_OVERHANG + 1)
// v3.24.29:左右/底从 20 → 28,节点与外框之间透气(顶部由操作栏推导,单独成立,不受影响)。
const GROUP_PAD_X = 28
const GROUP_PAD_BOTTOM = 28
// 组内**多选**气泡抬升:须越过操作栏顶边(PAD_TOP + OVERHANG = 88)再留间隙(+2 余量)→ 91
// 组内单选气泡不再用这个值(与组外一样贴节点,见 floatbarLift)。
const GROUP_LIFT = GROUP_PAD_TOP + GROUP_BAR_OVERHANG + NODE_HEAD_FB_GAP + 2
// 手动放大的额外留白:g.pad = { t, r, b, l }(世界坐标,均 >= 0)。
// 语义是「比自适应范围再大一圈」——内容移动时这层留白跟着走,因此天然满足「只能比自动范围更大」,
// 也不需要在内容变化后做失效清理(拖回 0 即恢复纯自适应)。
const groupPadOf = (g) => {
const p = (g && g.pad) || null
const num = (v) => (Number.isFinite(v) && v > 0 ? Math.round(v) : 0)
return p ? { t: num(p.t), r: num(p.r), b: num(p.b), l: num(p.l) } : { t: 0, r: 0, b: 0, l: 0 }
}
const hasGroupPad = (p) => !!(p && (p.t || p.r || p.b || p.l))
// 生效外框(世界坐标)= 成员自适应包围盒 + 基础内边距 + 额外留白
const groupBoxOf = (members, hOfFn, pad) => {
const p = pad || { t: 0, r: 0, b: 0, l: 0 }
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
for (const n of members) {
minX = Math.min(minX, n.x); minY = Math.min(minY, n.y)
maxX = Math.max(maxX, n.x + nodeWidth(n)); maxY = Math.max(maxY, n.y + hOfFn(n))
}
const x = minX - GROUP_PAD_X - p.l
const y = minY - GROUP_PAD_TOP - p.t
return { x, y, w: (maxX + GROUP_PAD_X + p.r) - x, h: (maxY + GROUP_PAD_BOTTOM + p.b) - y }
}
// 缩放拖动 → 额外留白:只有被拖的那条边变化,且留白不小于 0(拖回 0 = 恢复纯自适应)
const groupPadFromDrag = (base, dir, dx, dy) => {
const b = base || { t: 0, r: 0, b: 0, l: 0 }
const n = (v) => (Number.isFinite(v) && v > 0 ? Math.round(v) : 0)
return {
t: Math.max(0, n(b.t + (dir.indexOf('n') >= 0 ? -dy : 0))),
r: Math.max(0, n(b.r + (dir.indexOf('e') >= 0 ? dx : 0))),
b: Math.max(0, n(b.b + (dir.indexOf('s') >= 0 ? dy : 0))),
l: Math.max(0, n(b.l + (dir.indexOf('w') >= 0 ? -dx : 0))),
}
}
const withGroupPad = (g, pad) => ({ ...g, pad: hasGroupPad(pad) ? { t: pad.t, r: pad.r, b: pad.b, l: pad.l } : null })
// 气泡抬升(世界坐标):组内**多选**气泡须越过组操作栏;组内**单选**与组外一致(压标题带)。
// v3.24.28:原来组内一律抬到 GROUP_LIFT(86),比组外高 79px,同一节点在组内外看起来是两套间距。
// 单选气泡高度只有 40,把组框顶部内边距提高到 78(见 GROUP_PAD_TOP)后它自然落在操作栏下方,不必再抬。
const floatbarLift = (withTitle, inGroup, single) => (inGroup && !single ? GROUP_LIFT : (withTitle ? (single ? FLOATBAR_COVER_GAP : NODE_HEAD_H + NODE_HEAD_FB_GAP) : 14))
// 气泡(气泡底边贴在 top 上,CSS transform: translate(-50%,-100%) 保证):
// 底边 = 锚点顶边屏幕坐标 - max(14px 屏幕保底, lift × 缩放)。
// lift 与标题带同为世界坐标,故任意缩放级别都不会遮住标题;中继节点无标题 → lift 0,行为与旧版一致。
// 下限用 FLOATBAR_COVER_GAP(7):气泡底边要能与标题带底边齐平(原来硬下限 14 会把 lift=7 抬到 14)
const floatbarTopAt = (anchorY, lift, vp) => vp.y + anchorY * vp.scale - Math.max(7, lift * vp.scale)
// 气泡尺寸随缩放:气泡不在 .iwb-world 内,CSS 尺寸是屏幕 px 固定值,
// 而节点/标题带随视口缩放 → 放大画面时气泡相对节点越来越小(实测 scale=1 时按钮/节点高=0.31,scale=2 时只剩 0.16)。
// 用 k 跟随缩放补偿:k = clamp(1, scale, FB_SCALE_MAX)。下限 1 保证任何缩放级别都点得动;
// 上限避免高倍缩放下气泡过大遮住画布(2 倍以内与节点完全等比)。
const FB_SCALE_MAX = 2
const floatbarScale = (vp) => Math.max(1, Math.min(FB_SCALE_MAX, vp.scale || 1))
// 气泡高度估算与上边缘安全距离:抬升后若上方放不下(节点贴近画布上边缘,.iwb-canvas 会 overflow:hidden 裁掉),
// 改挂到节点下方(below=true → transform 改为 translate(-50%,0)),避免气泡整个不可见。
const FB_EST_H = 40
const FB_MIN_TOP = 8
const floatbarPlace = (anchorTop, anchorBottom, lift, vp) => {
const top = floatbarTopAt(anchorTop, lift, vp)
const k = floatbarScale(vp)
if (top - FB_EST_H * k >= FB_MIN_TOP) return { top, below: false, k }
return { top: vp.y + anchorBottom * vp.scale + 8, below: true, k }
}
// 尺寸 = 比例 × 清晰度(v3:把尺寸与比例分开)
const RATIOS = [
{ value: 'auto', label: '自动', sizes: {} },
{ value: '1:1', label: '1:1 方形', sizes: { '1K': '1024x1024', '2K': '2048x2048', '4K': '2864x2864' } },
{ value: '2:3', label: '2:3 竖版', sizes: { '1K': '832x1248', '2K': '1536x2304', '4K': '2048x3072' } },
{ value: '3:2', label: '3:2 横版', sizes: { '1K': '1248x832', '2K': '2304x1536', '4K': '3072x2048' } },
{ value: '3:4', label: '3:4 竖版', sizes: { '1K': '880x1168', '2K': '2016x2688', '4K': '2448x3264' } },
{ value: '4:3', label: '4:3 横版', sizes: { '1K': '1184x880', '2K': '2688x2016', '4K': '2688x2016' } },
{ value: '4:5', label: '4:5 竖版', sizes: { '1K': '912x1136', '2K': '1632x2032', '4K': '2048x2560' } },
{ value: '5:4', label: '5:4 横版', sizes: { '1K': '1136x896', '2K': '2032x1632', '4K': '2560x2048' } },
{ value: '9:16', label: '9:16 竖版', sizes: { '1K': '768x1360', '2K': '1440x2560', '4K': '2160x3840' } },
{ value: '16:9', label: '16:9 横版', sizes: { '1K': '1360x752', '2K': '2048x1152', '4K': '3840x2160' } },
{ value: '21:9', label: '21:9 超宽', sizes: { '1K': '1552x656', '2K': '2688x1152', '4K': '3840x1648' } },
{ value: '9:21', label: '9:21 超宽竖版', sizes: { '1K': '656x1520', '2K': '1152x2688', '4K': '1648x3840' } },
]
const SIZE_POLICY = typeof window !== 'undefined' && window.IWBGenerationSizePolicy
const RES_KEYS = SIZE_POLICY ? SIZE_POLICY.keys : ['1K', '2K', '4K']
// 旧数据兼容:标准/高清 → 1K/2K
const RES_MAP = SIZE_POLICY ? Object.freeze({ '标准': '1K', '高清': '2K', '1K': '1K', '2K': '2K', '4K': '4K' }) : { '标准': '1K', '高清': '2K', '1K': '1K', '2K': '2K', '4K': '4K' }
// 自定义尺寸仅保留服务端已验证的边长与最大比例保护;不强加 16 对齐或像素总量限制。
function sizeCheck(size) {
if (SIZE_POLICY) return SIZE_POLICY.validateSize(size)
if (String(size || '').trim().toLowerCase() === 'auto') return null
const m = /^(\d+)x(\d+)$/.exec(String(size || '').trim())
if (!m) return '尺寸格式应为 WxH,如 1024x1024'
const w = Number(m[1]), h = Number(m[2])
if (!w || !h) return '宽高必须是正整数'
if (Math.max(w, h) > 3840) return '最大边长不能超过 3840px'
if (Math.max(w, h) / Math.min(w, h) > 3) return '长边与短边的比例不能超过 3:1'
// 像素总量上限(对齐 opentu 的校验):防止拼出超过 4K 档位的超大请求被渠道拒绝。
// 注意:下限 655360 只作为面板提示、不做硬校验——本项目渠道实测支持更小的整数尺寸,
// 硬卡下限会把用户原来可用的尺寸变成不可用(属回归)。
if (w * h > 8294400) return '像素总量不能超过 8294400(约 4K 档位)'
return null
}
function ratioOfSize(size) {
for (const r of RATIOS) for (const k of RES_KEYS) if (r.sizes[k] === size) return r.value
return '1:1'
}
function resOfSize(size) {
for (const r of RATIOS) for (const k of RES_KEYS) if (r.sizes[k] === size) return k
return '标准'
}
// 比例下拉框的显示名:内置比例只显示比例值(如 1:1;遵循既有「不显示中文横竖版」契约),
// 自定义比例显示其可改的名称。value 始终是不可改的稳定标识 —— 改名只改 label、不改 value,
// 因此输入框的 React key 不变,不会因重建而丢焦点(改名无法连续输入的根因)。
function presetDisplayName(r) {
if (!r) return ''
return (r.custom && r.label) ? String(r.label) : String(r.value || '')
}
// ── 质量(quality)参数的唯一来源(规范 §13.28)──
// value = 直接发给服务商的原值;数组顺序 = 由弱到强(UI 排列、提示、校验都用这一份,禁止再写第二份白名单)。
// 注意:档位越高越慢、通常计费越高;auto = 不发该参数(最兼容,也是默认值)。
const QUALITY_LEVELS = [
{ value: 'auto', label: '自动' },
{ value: 'low', label: '快速' },
{ value: 'medium', label: '标准' },
{ value: 'high', label: '高清' },
{ value: 'xhigh', label: '极高' },
{ value: 'max', label: '最高' },
]
const QUALITY_VALUES = QUALITY_LEVELS.map((x) => x.value)
// 400/422 时的**有界**降级顺序:只给风险最高的两档一次下探机会(避免"选了最高档就把整个模型拉黑")
const QUALITY_DOWNGRADE = { max: 'xhigh', xhigh: 'high' }
function qualityOf(data) {
const v = String((data && data.quality) || '')
return QUALITY_VALUES.indexOf(v) >= 0 ? v : 'auto'
}
function qualityLabelOf(v) {
const hit = QUALITY_LEVELS.find((x) => x.value === v)
return hit ? hit.label : '自动'
}
// 只有**明确勾选**「质量」的模型才发送该参数:默认一律不支持(新增/手动添加的模型默认不勾)。
// 不做"自动假定某模型支持"的种子:勾选完全由你手动控制(providers[].models[].supportsQuality === true)。
// false / undefined 行为一致 = 不支持;false 只是把"我明确关掉了"记下来,便于以后排查。
function modelSupportsQuality(provider, model) {
const name = String(model || '')
const prov = (provider && typeof provider === 'object') ? provider : null
if (prov && Array.isArray(prov.models)) {
const hit = prov.models.find((m) => m && String(m.name || '') === name)
if (hit && hit.supportsQuality === true) return true
}
return false
}
// 节点侧便捷判定:按 node.data 里的 provider/model 找到服务商再判定
function supportsQualityOf(cfg, data) {
const d = data || {}
const providers = (cfg && cfg.providers) || []
const prov = providers.find((x) => x.id === d.provider) || providers[0]
return !!(prov && modelSupportsQuality(prov, d.model))
}
// 「质量」参数(quality)的支持情况:按 服务商+模型 记住渠道是否拒绝过它,避免每次都白试一次。
// 依据:HTTP 400/422 被归类为 param(app.js classifyHttpError),表示请求被拒绝 = **未生成、未计费**,
// 所以「降级重试」不违反「结果未知绝不自动重提(防重复计费)」的既有铁律。
const qualityRejected = new Set()
const qualityKeyOf = (providerId, model) => String(providerId || '') + '|' + String(model || '')
function isQualityUnsupported(providerId, model) { return qualityRejected.has(qualityKeyOf(providerId, model)) }
function markQualityUnsupported(providerId, model) { try { qualityRejected.add(qualityKeyOf(providerId, model)) } catch (e) { /* ignore */ } }
function standardSizeOf(data) {
const d = data || {}
if (d.custom && String(d.customSize || '').trim()) return String(d.customSize).trim()
// v3.87.25 修复:分辨率「自动」/未指定时**不要**被规范成 1K。
// 策略模块的 normalizeResolution 对任何未识别值(含 'auto')都回落到 '1K',而这里算的正是
// **实际发出去的尺寸** → 选「自动」(文档语义:不指定档位、交由渠道决定)时却主动发了 1K 尺寸,
// 表现为"某些模型只能出 1K"。现在:自动/未指定 → 用节点里保存的尺寸(用户最近一次明确设定)。
const resKey = String(d.res || '').trim()
if (!resKey || resKey === 'auto' || resKey === '自动') {
const saved = String(d.size || '').trim()
if (saved) return saved
}
if (SIZE_POLICY) return SIZE_POLICY.getSize(d.ratio, resKey) || String(d.size || '1024x1024')
const ratio = RATIOS.find((r) => r.value === d.ratio)
const tier = RES_MAP[d.res] || (RES_KEYS.includes(d.res) ? d.res : resOfSize(d.size)) || '1K'
return ratio && ratio.sizes[tier] ? ratio.sizes[tier] : String(d.size || '1254x1254')
}
const DEFAULTS = {
prompt: { text: '' },
plugin: { variant: '', text: '' },
ref: { url: '', data: null, name: '', localName: null },
gen: { model: 'gpt-image-2', provider: 'tuzi', keyGroup: 'daily', size: '1254x1254', ratio: '1:1', res: '1K', custom: false, customSize: '', quality: 'auto', align16: false, variants: 1, taskVariants: {}, prompt: '', result: null },
llm: { instruction: '', result: null },
textout: { text: '' },
combine: { extra: '', sep: ', ', combined: '' },
batch: { extra: '', sep: ' ', outs: {} },
out: {},
relay: { text: '' },
// 分层(seedream 图层分离):清单即「提示词」的结构化形态,一行一层;bbox 为原图像素坐标 [x1,y1,x2,y2] 或 null
layer: { model: 'doubao-seedream-5-0-pro-260628', provider: 'tuzi', keyGroup: 'daily', sizeParam: '1K', layers: [{ id: 'L1', name: '背景装饰层', bbox: null }, { id: 'L2', name: '主体视觉层', bbox: null }, { id: 'L3', name: '文字标题层', bbox: null }], result: null },
}
// 2026-11-25:新建配置节点的默认服务商/模型/密钥组跟随设置里的 defaultGen(未配置时保留上面的硬编码)。
// getter 让三条建节点路径(工具栏/右键/连线)无需改动;未配置返回原值 ⇒ 存量行为零变化。
;(() => { const M = window.IWBDefaultGenModel; if (!M) return; const pick = () => M.wResolveDefaultGen(wRawCfg()) || {}; for (const [k, f] of [['model', 'model'], ['provider', 'providerId'], ['keyGroup', 'keyGroup']]) Object.defineProperty(DEFAULTS.gen, k, { get: () => pick()[f] || ({ model: 'gpt-image-2', provider: 'tuzi', keyGroup: 'daily' })[k], enumerable: true, configurable: true }) })()
// 节点默认数据逐节点浅拷贝:DEFAULTS 是共享模板,数组字段(如分层清单)必须复制,否则节点之间会串改。
function cloneNodeDefaults(type) {
const d = { ...((DEFAULTS && DEFAULTS[type]) || {}) }
for (const k of Object.keys(d)) if (Array.isArray(d[k])) d[k] = d[k].map((v) => (v && typeof v === 'object' ? { ...v } : v))
return d
}
// P2-11b-1a:节点类型注册表(NODE_TYPES)。内置类型从四表 seed;插件/动态类型运行时经 registerNodeType 注册。
// 四张字面表保持不动(守门第 6 组按字面文本校验),注册表在其上叠加;读取点逐步改走注册表(1b)。
// 插件图标(按插件 id 指定,统一视觉;manifest 自带 icon 时优先用 manifest 的)
const PLUGIN_ICONS = { album: 'puzzle', browser: 'globe', sticky: 'tag', gallery: 'ref', grouplib: 'group', promptlib: 'book', 'style-source': 'palette', 'white-bg-800': 'layout', 'image-annotate': 'edit', 'image-vectorize': 'tool', 'xianyi-cutout': 'scissors', 'batch-export': 'archive', 'blank-canvas': 'panel' }
// 插件图标解析(2026-11-26):插件声明 → 宿主映射 → 拼图兜底;只接受 ICONS 白名单里的名字。
const pluginIconOf = (id) => PLUGIN_ICONS[String(id || '')] || undefined
const PLUGIN_TOOLBAR_HIDE = { promptlib: true, 'style-source': true }
const wPluginDeclaredIcons = {} // pluginId → manifest.icon(插件清单级声明)
const resolvePluginIcon = (pluginId, declared) => {
const ok = (n) => (typeof n === 'string' && Object.prototype.hasOwnProperty.call(ICONS, n)) ? n : ''
return ok(declared) || ok(wPluginDeclaredIcons[pluginId]) || ok(pluginIconOf(pluginId)) || 'puzzle'
}
const NODE_TYPES = new Map()
// 注册表版本号(2026-11-14):插件节点体(render)是**异步**注册的 —— 冷启动时画布先按存档把节点画出来,
// 那一刻插件脚本还在下载,`NODE_TYPES.get(type).render` 是 null ⇒ 走通用兜底体(hint + textarea),
// 看着就是「样式节点只剩一段文本」。等插件注册上 render 时 React 不会自己重画,必须显式通知。
// 只在「render 由无变有 / 换了一个函数」时自增,避免每次重复注册都全画布重建。
const NODE_TYPES_REV = { n: 0, subs: new Set() }
const subscribeNodeTypesRev = (fn) => { NODE_TYPES_REV.subs.add(fn); return () => { NODE_TYPES_REV.subs.delete(fn) } }
const bumpNodeTypesRev = () => {
NODE_TYPES_REV.n += 1
for (const fn of [...NODE_TYPES_REV.subs]) { try { fn(NODE_TYPES_REV.n) } catch (e) { /* 订阅者异常不影响注册 */ } }
}
const registerNodeType = (spec) => {
if (!spec || !spec.id || !/^[a-zA-Z][a-zA-Z0-9_:-]*$/.test(String(spec.id))) return false
const id = String(spec.id)
const builtin = NODE_H[id]
const prevSpec = NODE_TYPES.get(id)
const nextRender = typeof spec.render === 'function' ? spec.render : null
NODE_TYPES.set(id, {
id,
height: Number.isFinite(spec.height) ? spec.height : (builtin || 220),
color: spec.color || COLORS[id] || '#888',
title: spec.title || NODE_TITLES[id] || id,
icon: spec.icon !== undefined ? spec.icon : NODE_ICON[id],
defaults: spec.defaults || DEFAULTS[id] || {},
width: spec.width,
boxWidth: spec.boxWidth,
producer: spec.producer === true,
hasTitle: spec.hasTitle !== false,
ports: spec.ports || null,
render: nextRender,
run: typeof spec.run === 'function' ? spec.run : null,
})
// render 由无变有(插件脚本后到)⇒ 通知画布重画;重复注册同一个函数不触发。
// 首次注册(NODE_TYPES 里还没有这个 id)同样要触发:冷启动时插件节点可能一个字都没预注册过。
if (nextRender && (!prevSpec || prevSpec.render !== nextRender)) bumpNodeTypesRev()
return true
}
for (const t of Object.keys(NODE_H)) registerNodeType({ id: t, height: NODE_H[t], color: COLORS[t], title: NODE_TITLES[t], icon: NODE_ICON[t], defaults: DEFAULTS[t], producer: t === 'gen' || t === 'layer', hasTitle: t !== 'relay' })
// P2-11b-1b:读取点辅助 —— 统一走注册表,内置类型与插件类型行为一致(值等价 ⇒ 零行为变更)。
const nodeTypeH = (type) => { const s = NODE_TYPES.get(type); return s ? s.height : 220 }
const nodeTypeColor = (type) => { const s = NODE_TYPES.get(type); return (s && s.color) || '#888' }
const nodeTypeTitle = (type) => { const s = NODE_TYPES.get(type); return (s && s.title) || type }
const nodeTypeIcon = (type) => { const s = NODE_TYPES.get(type); return s ? s.icon : undefined }
const nodeTypeHasPort = (n, dir) => { const s = n && NODE_TYPES.get(n.type); return !!(s && s.ports && s.ports[dir]) }
// P2-11b-2:插件变体的"真类型 id" = `plugin:<pluginId>:<variantId>`(段内连字符;两段都唯一化,
// 只有 pluginId 全局唯一 ⇒ 用 pluginId 段消歧;禁止 `plugin-<variant>` 那种可撞的扁平 id)。
const pluginTypeSeg = (v) => String(v || '').toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/^-+|-+$/g, '') || 'x'
const pluginTypeId = (pluginId, variantId) => 'plugin:' + pluginTypeSeg(pluginId) + ':' + pluginTypeSeg(variantId)
const isPluginTypeId = (type) => typeof type === 'string' && /^plugin:[a-z0-9-]+:[a-z0-9-]+$/.test(type)
function uid(prefix) { return prefix + Date.now() + '_' + Math.floor(Math.random() * 1000000) }
// 画布数据规范化(纯逻辑收编到 src/canvas-normalize.js,P2-9 第一片):注入节点四表相关的 NODE_H / DEFAULTS
const CanvasNormalize = (typeof window !== 'undefined' && window.IWBCanvasNormalize && typeof window.IWBCanvasNormalize.create === 'function')
? window.IWBCanvasNormalize.create({ NODE_H, DEFAULTS, hasType: (t) => NODE_TYPES.has(t) })
: null
// 连线几何与合法性(纯函数收编到 src/canvas-geometry.js,P2-9):无依赖,直接用模块
const CanvasGeometry = (typeof window !== 'undefined' && window.IWBCanvasGeometry) || null
const IWBCanvasEdges = (typeof window !== 'undefined' && window.IWBCanvasEdges) || { EdgeCanvas: () => null }
const IWCanvasV3NodeLayer = (typeof window !== 'undefined' && window.IWBCanvasV3NodeLayer) || { CanvasNodeLayer: () => null }
const IWCanvasV3Hit = (typeof window !== 'undefined' && window.IWBCanvasV3Hit) || { hitRefNode: () => null }
// 撤销历史快照纯判定(收编到 src/canvas-history.js,P2-9):无依赖,直接用模块
const CanvasHistory = (typeof window !== 'undefined' && window.IWBCanvasHistory) || null
// 工作台列表纯变换(收编到 src/workspace-list.js,状态模型 epic · Pilot 3 片 A):无依赖,直接用模块
const WorkspaceList = (typeof window !== 'undefined' && window.IWBWorkspaceList) || null
// 画布节点数组纯变换(收编到 src/canvas-ops.js,P2-9):注入大图剥离助手 stripBigValueSync
const CanvasOps = (typeof window !== 'undefined' && window.IWBCanvasOps && typeof window.IWBCanvasOps.create === 'function')
? window.IWBCanvasOps.create({ stripBigValueSync })
: null
// rAF 合并器(2026-10-31 自 Workbench 收编,为「抓手工具」腾棘轮行数):模块缺失时退化为「立即执行」,
// 只丢节流不丢功能,绝不让整个 App 白屏。
const createRafBatcher = (typeof window !== 'undefined' && window.IWBCanvasOps && typeof window.IWBCanvasOps.createRafBatcher === 'function') ? window.IWBCanvasOps.createRafBatcher : () => Object.assign((fn) => fn(), { cancel: () => {} })
// SVG 线性图标库(lucide 风格,零依赖内联)
const ICONS = {
// 插件节点通用图标(2026-11-26):底栏「插件节点」入口与插件节点标题共用拼图,避免用文字占位
puzzle: '<path d="M19.439 7.85c-.049.322.059.648.289.878l1.568 1.568c.47.47.706 1.087.706 1.704s-.235 1.233-.706 1.704l-1.611 1.611a.98.98 0 0 1-.837.276c-.47-.07-.802-.48-.968-.925a2.501 2.501 0 1 0-3.214 3.214c.446.166.855.497.925.968a.979.979 0 0 1-.276.837l-1.61 1.61a2.404 2.404 0 0 1-1.705.707 2.402 2.402 0 0 1-1.704-.706l-1.568-1.568a1.026 1.026 0 0 0-.877-.29c-.493.074-.84.504-1.02.968a2.5 2.5 0 1 1-3.237-3.237c.464-.18.894-.527.967-1.02a1.026 1.026 0 0 0-.289-.877l-1.568-1.568A2.402 2.402 0 0 1 1.998 12c0-.617.236-1.234.706-1.704L4.23 8.77c.24-.24.581-.353.917-.303.515.077.877.528 1.073 1.01a2.5 2.5 0 1 0 3.259-3.259c-.482-.196-.933-.558-1.01-1.073-.05-.336.062-.676.303-.917l1.525-1.525A2.402 2.402 0 0 1 12 1.998c.617 0 1.234.236 1.704.706l1.568 1.568c.23.23.556.338.877.29.493-.074.84-.504 1.02-.968a2.5 2.5 0 1 1 3.237 3.237c-.464.18-.894.527-.967 1.02Z"/>',
cut: '<circle cx="6" cy="6" r="3"/><path d="M8.12 8.12 12 12"/><path d="M20 4 8.12 15.88"/><circle cx="6" cy="18" r="3"/><path d="M14.8 14.8 20 20"/>',
prompt: '<path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/>',
ref: '<path d="M16 5h6"/><path d="M19 2v6"/><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/>',
llm: '<path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2M20 14h2M9 13v2M15 13v2"/><path d="m18 2 .5 1.5L20 4l-1.5.5L18 6l-.5-1.5L16 4l1.5-.5Z"/>',
textout: '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4M8 13h8M8 17h8"/>',
gen: '<rect width="20" height="16" x="2" y="4" rx="2"/><path d="M6 8h.01M10 8h.01M14 8h.01M18 8h.01M8 12h8M6 16h12"/>',
out: '<rect width="20" height="16" x="2" y="4" rx="2"/><path d="M8 20v2M16 20v2M12 4v16M2 12h20"/>',
relay: '<path d="m19 5 3-3M2 22l3-3"/><path d="M6.5 6.5 17.5 17.5M6 10l-4 4 8 8 4-4M18 14l4-4-8-8-4 4"/>',
batch: '<path d="M12 22v-5"/><path d="M9 8V2M15 8V2"/><path d="M18 8v5a6 6 0 0 1-12 0V8Z"/>',
layer: '<path d="m12 2 9 5-9 5-9-5 9-5Z"/><path d="m3 12 9 5 9-5"/><path d="m3 17 9 5 9-5"/>',
// v3.24.29 重画:旧 group 是「虚线框 + 两块竖条」(18px 下虚线糊成噪点、两块并排像暂停符号 ⏸),
// 旧 ungroup 是两个等大方块(像「复制」)。改用「收起 / 打开」容器隐喻,且与首页分类图标同源:
// 编组 = 合上的文件夹(把选中项收进一个组);解组 = 打开的文件夹(把组打开,成员散出来)。
group: '<path d="M4 4h6l2 2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/>',
ungroup: '<path d="M4 20V6a2 2 0 0 1 2-2h3.6a2 2 0 0 1 1.6.8l1.2 1.6a2 2 0 0 0 1.6.8H18a2 2 0 0 1 2 2v2"/><path d="M2.7 20.5 4.9 12.6a2 2 0 0 1 1.93-1.5H20.4a1.5 1.5 0 0 1 1.45 1.9l-1.7 6.6a2 2 0 0 1-1.93 1.5H3.6a.9.9 0 0 1-.9-1.1Z"/>',
run: '<polygon points="6 3 20 12 6 21 6 3"/>',
settings: '<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>',
help: '<circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/>',
download: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/>',
upload: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" x2="12" y1="3" y2="15"/>',
save: '<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/>',
github: '<path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"/><path d="M9 18c-4.51 2-5-2-7-2"/>',
fit: '<circle cx="12" cy="12" r="3"/><path d="M3 7V5a2 2 0 0 1 2-2h2"/><path d="M17 3h2a2 2 0 0 1 2 2v2"/><path d="M21 17v2a2 2 0 0 1-2 2h-2"/><path d="M7 21H5a2 2 0 0 1-2-2v-2"/>',
layout: '<rect width="6" height="6" x="3" y="3" rx="1"/><rect width="6" height="6" x="15" y="15" rx="1"/><path d="M9 6h3a3 3 0 0 1 3 3v6"/><path d="m12 12 3 3 3-3"/>',
plus: '<path d="M5 12h14"/><path d="M12 5v14"/>',
minus: '<path d="M5 12h14"/>',
x: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
lock: '<rect width="16" height="11" x="4" y="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/>',
unlock: '<rect width="16" height="11" x="4" y="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 7-2"/>',
sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/>',
moon: '<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>',
palette: '<circle cx="13.5" cy="6.5" r=".5" fill="currentColor"/><circle cx="17.5" cy="10.5" r=".5" fill="currentColor"/><circle cx="8.5" cy="7.5" r=".5" fill="currentColor"/><circle cx="6.5" cy="12.5" r=".5" fill="currentColor"/><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z"/>',
book: '<path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20"/>',
'pencil-ruler': '<path d="M13 7 8.7 2.7a2.41 2.41 0 0 0-3.4 0L2.7 5.3a2.41 2.41 0 0 0 0 3.4L7 13"/><path d="m8 6 2-2"/><path d="m18 16 2-2"/><path d="m17 11 4.3 4.3c.94.94.94 2.46 0 3.4l-2.6 2.6c-.94.94-2.46.94-3.4 0L11 17"/><path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/><path d="m15 5 4 4"/>',
scissors: '<circle cx="6" cy="6" r="3"/><path d="M8.12 8.12 12 12"/><path d="M20 4 8.12 15.88"/><circle cx="6" cy="18" r="3"/><path d="M14.8 14.8 20 20"/>',
'file-type-corner': '<path d="M12 22h6a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v6"/><path d="M14 2v5a1 1 0 0 0 1 1h5"/><path d="M3 16v-1.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 .5.5V16"/><path d="M6 22h2"/><path d="M7 14v8"/>',
'vector-square': '<path d="M17.055 4.533a24 24 0 0 0-10.11 0"/><path d="M19.467 17.055a24 24 0 0 0 0-10.11"/><path d="M4.533 6.945a24 24 0 0 0 0 10.11"/><path d="M6.945 19.467a24 24 0 0 0 10.11 0"/><circle cx="19" cy="19" r="2"/><circle cx="19" cy="5" r="2"/><circle cx="5" cy="19" r="2"/><circle cx="5" cy="5" r="2"/>',
// 钢笔笔头(lucide pen-tool):位图转矢量插件的专属图标。
// 别与 white-bg-800 的 'vector-square' 共用 —— 两个插件同屏时图标一样,认不出谁是谁。
'pen-tool': '<path d="M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z"/><path d="m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18"/><path d="m2.3 2.3 7.286 7.286"/><circle cx="11" cy="11" r="2"/>',
// 地球(lucide globe):浏览器插件面板/网页节点的专属图标;此前插件声明 'globe' 但库里没有,tab 上渲染成空白
globe: '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
maximize: '<path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M21 8V5a2 2 0 0 0-2-2h-3"/><path d="M3 16v3a2 2 0 0 0 2 2h3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/>',
// 底栏缩放(v3.24.83):放大镜 + / −。别用裸 plus/minus(那是「新建」的语义,跟缩放认不出来)
'zoom-in': '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/><path d="M11 8v6M8 11h6"/>',
'zoom-out': '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/><path d="M8 11h6"/>',
// 画布工具组(2026-10-31):pointer=选择工具(默认,拖=框选),hand=抓手(拖=平移画布)
pointer: '<path d="M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"/><path d="M13 13l6 6"/>',
hand: '<path d="M18 11V6a2 2 0 0 0-4 0v5"/><path d="M14 10V4a2 2 0 0 0-4 0v2"/><path d="M10 10.5V6a2 2 0 0 0-4 0v8"/><path d="M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15"/>',
archive: '<path d="M21 8v13a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8"/><path d="M2 3h20v5H2z"/><path d="M10 12h4"/>',
paste: '<path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect width="8" height="4" x="8" y="2" rx="1" ry="1"/>',
trash: '<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>',
check: '<path d="M20 6 9 17l-5-5"/>',
chevronDown: '<path d="m6 9 6 6 6-6"/>',
chevronRight: '<path d="m9 18 6-6-6-6"/>',
chevronLeft: '<path d="m15 18-6-6 6-6"/>',
tag: '<path d="M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"/><circle cx="7.5" cy="7.5" r=".5" fill="currentColor"/>',
'file-text': '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8M16 13H8M16 17H8"/>',
'circle-dot': '<circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="1.5"/>',
'presentation': '<path d="M2 3h20"/><path d="M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3"/><path d="m7 21 5-5 5 5"/>',
'server-plus': '<rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/><path d="M6 6h.01M6 18h.01"/><path d="M18 1v6M15 4h6"/>',
merge: '<circle cx="18" cy="18" r="3"/><circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><path d="M6 9a12 12 0 0 1 12 6"/>',
star: '<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>',
copy: '<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
refresh: '<path d="M21 12a9 9 0 1 1-2.64-6.36L21 8"/><path d="M21 3v5h-5"/>',
box: '<path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" x2="12" y1="22.08" y2="12"/>',
more: '<circle cx="5" cy="12" r="1.6" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.6" fill="currentColor" stroke="none"/><circle cx="19" cy="12" r="1.6" fill="currentColor" stroke="none"/>',
tool: '<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>',
invert: '<path d="M7 7h10v10H7z"/><path d="M4 4h10v10"/><path d="M17 7h3v3"/>',
home: '<path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>',
// 品牌标记:四个圆角笔画拼成 W(与应用图标一致;v3.25.60 导航 logo 用它)
brand: '<path d="M4 4.8 8.2 19.2a1.6 1.6 0 0 0 3.1-.4L12 12.6l.7 6.2a1.6 1.6 0 0 0 3.1.4L20 4.8"/><path d="M4 4.8a1.6 1.6 0 0 1 3.1-.4L8.6 9"/><path d="M20 4.8a1.6 1.6 0 0 0-3.1-.4L15.4 9"/>',
menu: '<line x1="4" x2="20" y1="12" y2="12"/><line x1="4" x2="20" y1="6" y2="6"/><line x1="4" x2="20" y1="18" y2="18"/>',
panel: '<rect width="18" height="18" x="3" y="3" rx="2"/><path d="M9 3v18"/>',
edit: '<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5"/>',
panelRight: '<rect width="18" height="18" x="3" y="3" rx="2"/><path d="M15 3v18"/>',
folder: '<path d="M4 4h6l2 2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/>',
clock: '<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>',
}
// 主题:亮色(默认)/ 暗色 / 跟随系统(后两者写 localStorage 记忆)
function wPrefersDark() {
try { return !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) } catch (e) { return false }
}
// 外观(画布底色 + 主题色)实现在 src/ui-appearance.js:默认值/归一化/写 CSS 变量/对比度提示都在那边。
// 这里只做装配(app.js 有行数棘轮,不再堆细节)。
function applyAppearance(cfg) {
try { const A = window.IWBUIApearance; if (A) A.apply(cfg, document.documentElement.classList.contains('theme-dark')) } catch (e) { /* ignore */ }
}
function applyTheme(t) {
// 'system' 只是存下来的偏好值,真正落地成 dark/light 看系统当前外观
const mode = (t === 'system') ? (wPrefersDark() ? 'dark' : 'light') : (t === 'dark' ? 'dark' : 'light')
document.documentElement.classList.toggle('theme-dark', mode === 'dark')
try { lsRawSet('iwb_theme', t === 'system' ? 'system' : mode) } catch (e) { /* ignore */ }
}
function initTheme() {
let t = 'light'
try { const s = lsRawGet('iwb_theme', null); if (s === 'dark' || s === 'system') t = s } catch (e) { /* ignore */ }
applyTheme(t)
// 跟随系统时,系统外观切换要实时反映(不用重开窗口)。除了切 class 与落盘,还必须广播一次事件:
// 内联 token 由 applyAppearance 写在 <html> 上,它挂的 effect 依赖 [config, theme],而 theme 在这里
// 恒为 'system' 不会变 ⇒ 不广播就会出现「class 已暗、inline 还是亮」的混色半成品(D1,2026-11-23 修)。
try {
const mq = window.matchMedia('(prefers-color-scheme: dark)')
if (mq && mq.addEventListener) mq.addEventListener('change', () => { try { if (lsRawGet('iwb_theme', null) === 'system') { applyTheme('system'); window.dispatchEvent(new CustomEvent('iwb:theme-change')) } } catch (e) { /* ignore */ } })
} catch (e) { /* ignore */ }
return t
}
initTheme()
// 界面缩放已移除(CSS zoom 会改变节点 offsetHeight,导致端口/连线坐标错位)。
// uiZoom() 恒返回 1,保留各处坐标换算(除 1 无影响),避免大规模改动的回归风险
function uiZoom() {
return 1
}
// ── 画布视图组件已收编到 src/ui-canvas-view.js(结构优化 step-1,2026-10-28)
// 依赖一次性注入:它们全是 app.js 的 const 单次赋值 / 函数声明,运行期不变 ⇒ 无快照风险。
// 依赖清单不是人肉枚举的,是用 ESLint 的 no-undef 反推的(漏项会被 lint 直接抓到)。
const _mod = (typeof window !== 'undefined' && window.IWBUICanvasView) || null
if (!_mod || typeof _mod.inject !== 'function') throw new Error('[iwb][app] 模块未就绪: ui-canvas-view')
const I = (...a) => _mod.I(...a)
// 参考图节点 → 生图 API 参数(单张:本地历史图 local / data URL / 外部 URL)
// 批量/组合文案纯助手已收编到 src/canvas-text.js(P2-9):模块级解构,供本文件各处调用
const { compareCanvasTextOrder, batchSrcText, isBatchSrc, batchPortTop, batchJoinedText, combineEdgeTexts, combineInputTexts } = (typeof window !== 'undefined' && window.IWBCanvasText) || {}
function refArgsOf(refNode) {
const out = []
if (!refNode) return out
const d = refNode.data || {}
if (d.localName) out.push({ type: 'local', name: d.localName })
else if (d.data) out.push({ type: 'data', value: d.data, name: d.name || 'ref.png' })
else if (typeof d.url === 'string') { if (d.url.trim()) out.push({ type: 'url', value: d.url.trim() }) } else if (d.url) {
// 图库「插入到画布」会把 {__blob}/{__cache} 引用对象放进 url(既有设计)⇒ 直接 .trim() 会抛错,
// 导致整张画布的「配置」节点显示「渲染错误:o.url.trim is not a function」。
// ⚠️ 这里**必须原样透传引用对象**(value 非字符串):发请求前的 wResolveRefArgs() 会用
// wImgRefDataUrl() 把它转成 base64;若在此处解析成 blob: 临时地址,上游会报「参考图格式不支持」。
out.push({ type: 'data', value: d.url, name: d.name || 'ref.png' })
}
return out
}
// 参考图节点排序:画布坐标(x 从左到右,同 x 按 y 从上到下)
function compareCanvasImageOrder(a, b) { return (Number(a.x) - Number(b.x)) || (Number(a.y) - Number(b.y)) || String(a.id).localeCompare(String(b.id)) }
function sortByPosition(arr) { return arr.slice().sort(compareCanvasImageOrder) }
// ── 生成任务图纯函数族:已收编到 src/task-graph.js(P1 拆分批 1,2026-10-28)─────────
// 原 5 个函数(orderedUniqueRefNodes / createTaskGraphIndex / resolveNodeTaskValues /
// buildGenerationTasksV2 / graphCacheKey)连同 _graphKeyMemo 缓存整体迁出,行为逐字保持不变。
// 迁移前做过等价性验证:同输入下新旧实现输出完全一致(9/9 通过)。
// 依赖经 create() 注入;task-graph.js 不反向依赖 app.js。
// 若模块缺失(旧缓存页面)则回退为空实现 —— 但此时生图任务推导会失败,
// 故在挂载处用显式错误而不是静默返回空值。
const _wTaskGraph = (() => {
const M = (typeof window !== 'undefined' && window.IWBWTaskGraph) || null
if (!M) return null
try {
return M.create({
sortByPosition,
compareCanvasImageOrder,
compareCanvasTextOrder,
dedupeTaskRefs,
isBatchSrc,
batchJoinedText,
wDedupeTaskIds,
refArgsOf,
// P1 拆分批 4(2026-10-28)新增:
batchSrcText, // 批量来源文本提取(来自 src/canvas-text.js)
standardSizeOf, // 实际发出尺寸(createGenerationSnapshot 记录用;尺寸常量表留宿主,注入不搬)
})
} catch (e) {
// 依赖缺失属于**构建/加载错误**,必须显式暴露,不能静默降级成空实现
try { console.error('[iwb][task-graph] 初始化失败:', e && e.message) } catch (e2) {}
return null
}
})()
function _taskGraphFn(name) {
const fn = _wTaskGraph && _wTaskGraph[name]
if (typeof fn !== 'function') throw new Error('[iwb][task-graph] 模块未就绪: ' + name)
return fn
}
const orderedUniqueRefNodes = (refNodes) => _taskGraphFn('orderedUniqueRefNodes')(refNodes)
const createTaskGraphIndex = (nodesArr, edgesArr) => _taskGraphFn('createTaskGraphIndex')(nodesArr, edgesArr)
const resolveNodeTaskValues = (nodeId, graph, context) => _taskGraphFn('resolveNodeTaskValues')(nodeId, graph, context)
// 上游继承文本(2026-11-14):提示词 / 文本节点自己没写字时,节点体要显示上游传进来的那段话
const inheritedTextOf = (nodeId, nodesArr, edgesArr) => _taskGraphFn('inheritedTextOf')(nodeId, nodesArr, edgesArr)
const buildGenerationTasksV2 = (genNode, nodesArr, edgesArr) => _taskGraphFn('buildGenerationTasksV2')(genNode, nodesArr, edgesArr)
const graphCacheKey = (nodesArr, edgesArr) => _taskGraphFn('graphCacheKey')(nodesArr, edgesArr)
// ── P1 拆分批 4:任务图回溯族(4 个纯函数)也并入同一模块 ─────────────────────
// resolveTaskGraph / combineSourcePairs / nodeRefsOf:沿连线图回溯取「文本 + 参考图」
// createGenerationSnapshot:把一条生图任务固化成快照
// 迁移前做过等价性验证:21 组用例(含环形图、batch 指定源、combine 聚合、停用节点、自定义尺寸)输出一致。
const resolveTaskGraph = (node, nodesArr, edgesArr, stack) => _taskGraphFn('resolveTaskGraph')(node, nodesArr, edgesArr, stack)
const combineSourcePairs = (n, inEdge, edgesArr, nodesArr, visited) => _taskGraphFn('combineSourcePairs')(n, inEdge, edgesArr, nodesArr, visited)
const createGenerationSnapshot = (job, nodeData, workspaceId, nodeId) => _taskGraphFn('createGenerationSnapshot')(job, nodeData, workspaceId, nodeId)
const nodeRefsOf = (n, edgesArr, nodesArr, _visited) => _taskGraphFn('nodeRefsOf')(n, edgesArr, nodesArr, _visited)
// P1 批 7:中断恢复的变体级计划是**直接导出**(不经 create),单独委托。
// 抽出来的理由:算错 = 已出图变体被重跑 = 重复扣用户的钱;且可脱离浏览器穷举验证。
const resumeVariantPlan = (args) => {
const M = (typeof window !== 'undefined' && window.IWBWTaskGraph) || null
if (!M || typeof M.resumeVariantPlan !== 'function') throw new Error('[iwb][task-graph] 模块未就绪: resumeVariantPlan')
return M.resumeVariantPlan(args)
}
// 递归收集节点携带的参考图:prompt/textout/combine 都透传其入边 ref(combine 可嵌套)
// 生图失败错误分类:资源/额度、连接、密钥、服务商、其他(用于醒目展示与提示)
function classifyErr(text) {
const t = String(text || '')
const l = t.toLowerCase()
if (/已手动结束|手动结束/.test(t)) return { cls: 'cancelled', tag: '已结束' }
if (/结果未知|已停止等待/.test(t)) return { cls: 'unknown', tag: '结果未知' }
if (/(insufficient|quota|balance|credit|limit|rate.?limit|429|额度|余额|资源|耗尽|扣费|充值)/.test(l)) return { cls: 'quota', tag: '资源/额度' }
if (/(econnrefused|enotfound|fetch failed|timeout|abort|network|socket|etimedout|econnreset|连接|超时|无法连接|网络)/.test(l)) return { cls: 'conn', tag: '连接' }
if (/(unauthor|401|403|api.?key|token|密钥|无效.*key|没有.*key)/.test(l)) return { cls: 'auth', tag: '密钥' }
if (/(500|502|503|server error|内部错误|bad gateway)/.test(l)) return { cls: 'srv', tag: '服务商' }
return { cls: 'other', tag: '其他' }
}
function apiErrorMessage(e) {
return String((e && e.message) || e || '生成失败')
}
// 组合/任务文本排序(方案1):relay 透明穿透,按「真实文本源节点」坐标统一排序。
// 返回 [{ n: 真实文本源节点, text }];ref/停用节点跳过;batch 整块归到 batch 名下(保持既有 batch 语义,不改变其块位置)。
// 方案1 组合排序:按每个 combine 入边展开为 (真实文本源, 文本),relay 透明穿透;batch 只取该边 batchSrcId 指定来源。
function relayCompatTasks(ps, nodes, edges) {
const r = resolveTaskGraph(ps, nodes, edges)
const refs = (r.refs || []).flatMap(refArgsOf)
const texts = r.texts && r.texts.length ? r.texts : ['']
return texts.map((text, i) => ({ id: ps.id + (texts.length > 1 ? '@' + i : ''), text, refs, cycle: !!r.cycle }))
}
// V2 graph index and unified task value resolver.
function dedupeTaskRefs(refs) { const seen = new Set(), out = []; for (const r of (Array.isArray(refs) ? refs : [])) { const k = r && (r.id || r.value || r.name); if (r && k && !seen.has(k)) { seen.add(k); out.push(r) } } return out }
const taskParseCache = new WeakMap()
let _lastTaskCache = null
// graphCacheKey 引用稳定快路径:nodes/edges 引用未变(CanvasStore 只在内容变化时新建数组)→ 直接返回上次 key。
// 否则每个 gen 节点每次重渲染都会对整张图 (含 JSON.stringify(n.data)) 做 O(n) 重算 —— 7k 节点工作台实测是
// cachedGenerationTasks 1.5s / graphCacheKey 840ms 的主因。缓存仅按引用命中,内容变化时引用必然变化,绝不会返回过期 key。
const _graphKeyMemo = { nodes: null, edges: null, key: '' }
function cachedGenerationTasks(genNode, nodesArr, edgesArr) {
const nodes = Array.isArray(nodesArr) ? nodesArr : []
const genId = genNode && genNode.id
// 引用稳定快路径:nodes/edges 引用未变(重渲染时 Content 不变)→ 直接返回上次结果,跳过 O(n) 的 graphCacheKey 重算
const last = _lastTaskCache
if (last && last.nodes === nodesArr && last.edges === edgesArr && last.genId === genId) return last.result
const key = graphCacheKey(nodes, edgesArr), bucket = taskParseCache.get(nodesArr) || new Map(), cacheKey = String(genId) + '::' + key
let result
if (bucket.has(cacheKey)) result = bucket.get(cacheKey)
else {
result = buildGenerationTasksV2(genNode, nodes, edgesArr)
bucket.set(cacheKey, result)
if (bucket.size > 8) bucket.delete(bucket.keys().next().value)
taskParseCache.set(nodesArr, bucket)
}
_lastTaskCache = { nodes: nodesArr, edges: edgesArr, genId, result }
return result
}
function nodePreviewRefsV2(node, nodesArr, edgesArr) {
const graph = createTaskGraphIndex(nodesArr, edgesArr)
const values = resolveNodeTaskValues(node && node.id, graph, {})
return orderedUniqueRefNodes(values.flatMap((v) => v.refNodes || []))
}
// 提示词 / 文本节点的「继承自上游」信息(2026-11-14):
// 自己 data.text 非空 = 已接管(在它上面改过),此时**不再显示**继承;
// 为空 = 跟随上游,节点体把上游文本显示出来(改一个字就落进自己的 data.text)。
function nodeInheritOf(node, nodesArr, edgesArr) {
const own = String((node && node.data && node.data.text) || '').trim()
// 关键:先查上游。没有上游就根本没有「继承/已固定」这回事(用户是纯手写)
const info = inheritedTextOf(node && node.id, nodesArr, edgesArr) || {}
const hasUpstream = !!(info.sourceNodeId || String(info.text || '').trim())
const base = {
sourceNodeId: String(info.sourceNodeId || ''),
more: Number(info.more) || 0,
hasUpstream: hasUpstream,
}
if (own) return Object.assign({ text: '', own: true }, base)
return Object.assign({ text: String(info.text || ''), own: false }, base)
}
// 纯任务构建器:只根据节点图构造 prompt/参考图任务,不修改 state、不发送请求。
function buildGenerationTasks(genNode, nodesArr, edgesArr) {
return cachedGenerationTasks(genNode, nodesArr, edgesArr)
}
// 将任务展开为单张请求 Job:纯函数,不读写 UI 状态。
function createGenerationJobs(tasks, nodeData) {
const out = []
const list = Array.isArray(tasks) ? tasks : []
const data = nodeData || {}
for (const t of list) {
if (!t || (!t.text && !(t.refs && t.refs.length))) continue
const refsArr = (t.refs || []).filter((r) => r && (r.type === 'local' ? (r.name || r.value) : r.value))
const tv = Math.max(1, Math.min(10, (data.taskVariants && data.taskVariants[t.id]) || data.variants || 1))
// 兔子接口将 URL 参考图也定义在 generations 的 image 字段中;只有本地图才走 edits。
const mode = 'generations'
for (let i = 0; i < tv; i++) out.push({ t, i, tv, refsArr, mode })
}
return out
}
// 从生成任务提取可持久化的最小参数快照;不包含密钥或运行时对象。
// 统一生成结果条目:只构造数据,不触碰 React 状态或持久化。
function createGenerationResultEntry(job, items, snapshot) {
const j = job || {}, t = j.t || {}
// at:合并判新旧用(跨标签/跨设备同步时,按(任务,变体)取 at 大的那条,避免被空存档洗掉)
return { promptId: t.id, vi: j.i, label: (t.title || String(t.text || '').slice(0, 16) || '任务') + (j.tv > 1 ? ' · ' + (j.i + 1) : ''), taskTitle: t.title || '', at: Date.now(), snapshot: snapshot || null, items: Array.isArray(items) ? items : [] }
}
// 统一描述生成运行结束时要清理的资源键,不执行副作用。
function generationRunCleanupKeys(runKey) {
return { runKey: runKey || '', busyKey: runKey || '', progressKey: runKey || '' }
}
// 根据调度摘要推导运行终态,供 UI/持久化层共享。
function deriveGenerationRunStatus(summary) {
const s = summary || {}
const total = Math.max(0, Number(s.total) || 0)
const completed = Math.max(0, Number(s.completed === undefined ? s.done : s.completed) || 0)
const failed = Math.max(0, Number(s.failed) || 0)
if (s.cancelled) return 'cancelled'
if (s.error && !completed) return 'failed'
if (!total || completed + failed < total) return 'running'
if (failed && completed) return 'partial-failed'
if (failed) return 'failed'
return 'completed'
}
// 按任务和变体写入结果:不可变替换,避免重复结果条目。
function upsertGenerationEntry(entries, entry) {
const list = Array.isArray(entries) ? entries : []
if (!entry) return list.slice()
const keep = list.filter((x) => !(x && x.promptId === entry.promptId && x.vi === entry.vi))
return keep.concat([entry])
}
// 将任务条目展平为图库结果:统一标签,不修改输入数据。
function flattenGenerationEntries(entries) {
const out = []
for (const entry of (Array.isArray(entries) ? entries : [])) {
for (const item of (entry && Array.isArray(entry.items) ? entry.items : [])) out.push({ ...item, label: (entry && entry.label) || '', snapshot: item && item.snapshot ? item.snapshot : (entry && entry.snapshot ? entry.snapshot : null) })
}
return out
}
// 生成归档边界:图库索引/缩略图属于旁路缓存,不能阻塞生成结果和画布保存。
// v3.26.61:每张结果在生成过程中已由 wArchiveEntryNow 逐张入库(图库要「出图即见」),
// 这里只补剩下没归档的(失败条目/兜底路径),不再整批重写一遍 —— 否则同一张图会入两次库。
async function archiveGenerationResults(entries, refresh) {
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) { /* 插件钩子异常不得影响结果归档 */ }
}
// 归档 → 刷新 → 自动下载串行:自动下载必须等本批原图写进图库(out_orig_)后再跑,才谈得上「从本地字节复制」。
Promise.resolve().then(async () => {
// 只有「自动下载」开启时才等归档完成:它要从本地原图复制,必须等 out_orig_ 落盘;
// 没开就保持后台异步归档,避免出图到图库可点开的时间被拖长。
const needArchiveWait = !!(wAutoSaver && typeof wAutoSaver.enabled === 'function' && wAutoSaver.enabled())
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)
}
// 统一生成响应:将不同 API 形态归一为结果项数组,保留最小兼容字段。
function normalizeGenerationResult(response, job) {
const raw = Array.isArray(response) ? response : (response && Array.isArray(response.data) ? response.data : [response])
const list = raw.filter(Boolean)
if (!list.length) return [{ ok: false, error: '服务返回空结果', errorType: 'empty', job }]
return list.map((item) => {
if (typeof item === 'string') return { ok: true, url: item, job }
if (item && item.ok === false) return { ...item, ok: false, job }
if (item && item.url && /^https?:\/\//i.test(String(item.url).trim())) return { ...item, url: String(item.url).trim(), ok: item.ok !== false, job }
if (item && (item.b64_json || item.data)) return { ok: false, error: '上游返回了 Base64,而不是 URL;已拒绝保存', errorType: 'url-only', job }
if (item && item.error) return { ...item, ok: false, error: String(item.error), errorType: item.errorType || 'unknown', job }
return { ok: false, error: '服务返回无效结果', errorType: 'invalid', job }
})
}
// 纯并发调度器:负责队列、并发上限、取消和回调;请求细节由 executeJob 注入。
function runGenerationJobs(jobs, options) {
const external = typeof window !== 'undefined' && window.IWBGenerationScheduler
if (external && typeof external.run === 'function') return external.run(jobs, options)
const list = Array.isArray(jobs) ? jobs : []
const opt = options || {}
const concurrency = Math.max(1, Number(opt.concurrency) || 1)
const signal = opt.signal
const results = new Array(list.length)
let cursor = 0, completed = 0, cancelled = false
const cancelledError = () => { const e = new Error('任务已取消'); e.name = 'AbortError'; return e }
const worker = async () => {
while (true) {
if (signal && signal.aborted) { cancelled = true; throw cancelledError() }
const index = cursor++
if (index >= list.length) return
const job = list[index]
opt.onStart && opt.onStart(job, index)
try {
const value = await opt.executeJob(job, index)
results[index] = { ok: true, value, job }
completed++
opt.onItemDone && opt.onItemDone(value, job, index, completed, list.length)
} catch (error) {
results[index] = { ok: false, error, job }
opt.onItemError && opt.onItemError(error, job, index, completed, list.length)
if (opt.stopOnError) throw error
}
}
}
const count = Math.min(concurrency, Math.max(1, list.length))
return Promise.all(Array.from({ length: count }, () => worker())).then(() => {
if (signal && signal.aborted) cancelled = true
const summary = { results, completed, total: list.length, cancelled }
opt.onComplete && opt.onComplete(summary)
return summary
}).catch((error) => {
if (error && error.name === 'AbortError') cancelled = true
const summary = { results, completed, total: list.length, cancelled, error }
opt.onComplete && opt.onComplete(summary)
throw error
})
}
// ---------- 图片压缩(v2 §2.4:前端 Canvas 压缩,保持零依赖) ----------
// 超阈值才压缩:最长边 maxEdge、质量 quality、格式 format(keep 保持原格式 / jpeg 统一转 JPEG)
// 图片压缩用 Web Worker + OffscreenCanvas 在独立线程重采样:保存/上传时压缩不占主线程,避免压缩大图阻塞节点操作。
// Worker 脚本与生命周期已收编到 src/image-compress.js(P2-10);单文件模式(未加载 src 模块)回退为「不可用」空实现:
// 该环境无 Worker/OffscreenCanvas ⇒ available() 恒 false,compressDataUrl 直接走主线程压缩,永不调用 compress(),与收编前一致。
const CompressWorker = (typeof window !== 'undefined' && window.IWBImageCompress && typeof window.IWBImageCompress.createWorkerManager === 'function')
? window.IWBImageCompress.createWorkerManager()
: { available() { return false }, compress() { return Promise.reject(new Error('compress module unavailable')) }, dispose() {} }
if (typeof window !== 'undefined') { try { window.addEventListener('pagehide', () => CompressWorker.dispose(), { once: true }) } catch (e) { /* ignore */ } }
// 页面隐藏/卸载时释放有界 objectURL 缓存(尚未被 FIFO 驱逐的条目),避免残留 blob 引用
if (typeof window !== 'undefined') { try { window.addEventListener('pagehide', () => wObjUrlClear(), { once: true }) } catch (e) { /* ignore */ } }
// ── 图片编解码与压缩调度:已并入 src/image-compress.js(P1 拆分批 6,2026-10-28)──────
// 迁出 6 个函数(113 行):estimateBytes / wBlobFromDataUrl / wImgBlobToDataUrl /
// withDecodedImage / mainThreadCompress / compressDataUrl。
// 该模块原本只收编了 Worker(P2-10),文件头当时写明「主线程回退与 compressDataUrl 仍留在 app.js」——
// 现在有了 create(deps) 范式,这一条遗留补上了。
// CompressWorker 用 **getter 注入**:它在本行之后才创建(且 wImportImage 也在用),
// 直接传值会踩 TDZ,也会诱使模块自建第二个 manager(available() 语义会分裂)。
// 迁移前做过等价性验证:15 组用例(dataURL 编解码 / 非 data: 与非法输入 / 解码失败兜底 /
// 跳过压缩分支 / <img> 兜底 / window.__IWB_COMPRESS_LAST__ 诊断标记)输出完全一致。
const _imgCompress = (() => {
const M = (typeof window !== 'undefined' && window.IWBImageCompress) || null
if (!M || typeof M.create !== 'function') return null
try {
return M.create({ getCompressWorker: () => CompressWorker })
} catch (e) {
// 依赖缺失属于构建/加载错误,必须显式暴露,不静默降级
try { console.error('[iwb][image-compress] 初始化失败:', e && e.message) } catch (e2) {}
return null
}
})()
function _imgCompressFn(name) {
const fn = _imgCompress && _imgCompress[name]
if (typeof fn !== 'function') throw new Error('[iwb][image-compress] 模块未就绪: ' + name)
return fn
}
const estimateBytes = (dataUrl) => _imgCompressFn('estimateBytes')(dataUrl)
const wBlobFromDataUrl = (src) => _imgCompressFn('wBlobFromDataUrl')(src)
const wImgBlobToDataUrl = (blob) => _imgCompressFn('wImgBlobToDataUrl')(blob)
const withDecodedImage = (srcOrBlob, fn) => _imgCompressFn('withDecodedImage')(srcOrBlob, fn)
const mainThreadCompress = (dataUrl, c, cb) => _imgCompressFn('mainThreadCompress')(dataUrl, c, cb)
const compressDataUrl = (dataUrl, comp, cb) => _imgCompressFn('compressDataUrl')(dataUrl, comp, cb)
// 主线程 fallback:不支持 OffscreenCanvas/Worker 时仍能压缩。
// 支持 createImageBitmap 时统一走解码头(bitmap.close() 明确释放,未压缩位图不滞留堆里)。
async function uploadRefToImageHost(dataUrlOrRef, config, name) {
const ih = (config && config.imageTransfer && config.imageTransfer.imageHost) || {}
const type = ih.type || 'imgbb'
// C3 第2步:入参可能是 {__blob}/{__cache}/{__idb} 引用 —— 先按需解析成 dataURL(用完即弃,不驻留)
const dataUrl = (dataUrlOrRef && typeof dataUrlOrRef === 'object') ? await wImgRefDataUrl(dataUrlOrRef) : dataUrlOrRef
if (!dataUrl || String(dataUrl).indexOf('data:') !== 0) throw new Error('只有本地图片可以转为在线链接')
const raw = String(dataUrl).split(',')[1] || ''
if (!raw) throw new Error('本地图片数据为空,请重新上传图片')
if (type === 'imgbb') {
const key = ih.imgbb && ih.imgbb.key
if (!key) throw new Error('请先在设置 → 图片传输中填写 ImgBB API Key')
const form = new FormData(); form.append('key', key); form.append('image', raw)
const resp = await fetch('https://api.imgbb.com/1/upload', { method: 'POST', body: form })
const json = await resp.json().catch(() => null)
if (!resp.ok || !json || !json.success || !json.data || !json.data.url) throw new Error((json && json.error && json.error.message) || 'ImgBB 上传失败')
return json.data.url
}
if (type === 'github') {
const gh = ih.github || {}
if (!gh.owner || !gh.repo || !gh.token) throw new Error('请先在设置 → 图片传输中填写 GitHub 用户名、仓库和 Token')
const file = String(gh.dir || 'tmp-refs').replace(/^\/+|\/+$/g, '') + '/' + Date.now() + '-' + String(name || 'reference.png').replace(/[^a-zA-Z0-9._-]/g, '_')
const endpoint = 'https://api.github.com/repos/' + encodeURIComponent(gh.owner) + '/' + encodeURIComponent(gh.repo) + '/contents/' + file.split('/').map(encodeURIComponent).join('/')
const resp = await fetch(endpoint, { method: 'PUT', headers: { Authorization: 'Bearer ' + gh.token, Accept: 'application/vnd.github+json', 'Content-Type': 'application/json' }, body: JSON.stringify({ message: 'upload reference image', content: raw, branch: gh.branch || 'main' }) })
const json = await resp.json().catch(() => null)
if (!resp.ok || !json || !json.content || !json.content.download_url) throw new Error((json && json.message) || 'GitHub 上传失败')
return json.content.download_url
}
throw new Error('暂不支持该图库')
}
// v3.87.37:存量重压(由 15s 采样周期驱动,每次最多 1 张)
const wRecompressTried = new Set()
let _wRecompressBusy = false
function wRecompressTick(deps) {
try {
// v3.87.40 **紧急停用(数据安全)**:存量重压属于"后台异步改写画板数据",
// 压缩需 100~500ms,其间用户的编辑会被随后的 commitCanvas(旧快照) 覆盖;
// 若压缩结果异常还可能写坏图片字段。用户反馈"画布崩溃后图片全部消失",高度怀疑与此有关。
// 在实现安全版本(冲突检测 + 仅在完全空闲且用户无未保存编辑时逐字段提交 + 可回滚)之前,
// 一律不执行。**不要在没有更新 122-1 契约的情况下重新启用。**
// eslint-disable-next-line no-constant-condition -- 故意恒真:安全停用开关(见上,勿删)
if (true) return
const D = deps || {}
if (_wRecompressBusy) return
if (lsGet(W_RECOMPRESS_FLAG, false)) return
if (D.busy && D.busy()) return // 正在拖拽/缩放/交互时不改数据
const hits = wCollectBigImages(D.nodes && D.nodes(), 2.5 * 1048576).filter((h) => !wRecompressTried.has(h.nodeId + '|' + h.path))
if (!hits.length) { lsSet(W_RECOMPRESS_FLAG, true); console.info('[iwb] 存量图片重压:完成(无剩余大图)'); return }
const hit = hits[0]
const node = (D.nodes() || []).find((n) => n && n.id === hit.nodeId)
const orig = wGetByPath(node && node.data, hit.path)
if (typeof orig !== 'string') { wRecompressTried.add(hit.nodeId + '|' + hit.path); return }
_wRecompressBusy = true
const mb = (x) => Math.round(String(x).length / 1048576 * 10) / 10
console.info('[iwb] 存量图片重压:处理 ' + hit.nodeId + ' ' + hit.path + ' ' + mb(orig) + 'MB(剩余 ' + hits.length + ')')
// 原图先写进 Cache(万一需要可回退;同一个 URL 可重复取回)
try { iwbCacheWrite(orig) } catch (e) { /* ignore */ }
compressDataUrl(orig, Object.assign({}, compressConf(D.config && D.config()) || {}, { enabled: true, force: true, maxMB: 0, maxEdge: 1600, quality: 0.85 }), (out) => {
try {
if (typeof out === 'string' && out.length && out.length < orig.length * 0.8) {
const next = (D.nodes() || []).map((n) => {
if (!n || n.id !== hit.nodeId) return n
const data = Object.assign({}, n.data)
wSetByPath(data, hit.path, out)
return Object.assign({}, n, { data: data })
})
if (D.commit) D.commit(next)
console.info('[iwb] 存量图片重压:完成 ' + hit.nodeId + ' ' + mb(orig) + 'MB → ' + mb(out) + 'MB')
} else {
console.info('[iwb] 存量图片重压:收益不足,保留原图 ' + hit.nodeId + ' ' + hit.path)
}
} catch (e) { /* ignore */ }
wRecompressTried.add(hit.nodeId + '|' + hit.path)
_wRecompressBusy = false
})
} catch (e) { _wRecompressBusy = false }
}
// v3.87.38:显示层把大 dataURL **渐进**换成 Cache 虚拟 URL(B1 的 ①)。
// 设计要点:
// - **不改节点数据** ⇒ 生成路径(发送给模型的参考图)完全不受影响,零回归风险;
// - 先原样返回 dataURL(显示绝不中断),同时异步写入 Cache(命中时几乎零成本);
// - 写入完成后本会话内 cacheDoneUrls 命中 ⇒ 后续渲染改用 /__iwb_cache__/<hash>(几十字节);
// - Cache 不可用(隐私模式)自动退回 dataURL,功能不降级。
// /__iwb_cache__/<hash> 只有 Service Worker 能直出(sw.js 的 fetch 拦截命中 Cache Storage 才返回)。
// SW 未接管时(首次安装窗口 / 清站点数据后 / 被策略拦截)该 URL 走网络 → 404 → <img> onError → 节点缩略图永久空白。
// 与 wResolveImg(v3.87.64 弃用 SW 虚拟路径)同因:无 controller 绝不返回该 URL。
function wCacheUrlServable() {
try { return typeof navigator !== 'undefined' && !!navigator.serviceWorker && !!navigator.serviceWorker.controller } catch (e) { return false }
}
function wThumbSrc(v) {
// C3:图片引用({__blob}/{__cache})先解析成显示 URL,绝不把对象 String() 成 "[object Object]"
if (v && typeof v === 'object') v = wResolveImg(v)
const s = String(v == null ? '' : v)
if (s.indexOf('data:') !== 0) return s
try {
const u = wCacheKeyOf(s)
if (u && cacheDoneUrls.has(u) && wCacheUrlServable()) return u
iwbCacheWrite(s).then(() => {}).catch(() => {})
return s
} catch (e) { return s }
}
// v3.87.41:**安全版**一次性压缩(替代被停用的后台迁移,见 v3.87.40 的数据安全说明)
// 与后台版的区别:**用户可见 + 全屏遮罩(期间无法编辑)** ⇒ 不存在"异步窗口内编辑被覆盖"的竞态。
// 设计:首次打开且存在 >2.5MB 的图时自动跑一次;逐张压缩、每张重新读取画板、原图先入 Cache(可回退)、
// 收益 <20% 保留原值、每张只试一次、完成后写标记只跑一次。
const W_SAFE_COMPRESS_FLAG = 'iwb_safe_compress_v2'
let _wSafeCompressBusy = false
function wSafeCompressStart(deps) {
try {
if (_wSafeCompressBusy || lsGet(W_SAFE_COMPRESS_FLAG, false)) return
const D = deps || {}
const nodesNow = () => (D.nodes ? D.nodes() : []) || []
const first = wCollectBigImages(nodesNow(), 2.5 * 1048576)
if (!first.length) { lsSet(W_SAFE_COMPRESS_FLAG, true); return }
_wSafeCompressBusy = true
const total = first.length
let done = 0, mbBefore = 0, mbAfter = 0
let ov = null, msgEl = null
try {
ov = document.createElement('div')
ov.id = 'iwb-safe-compress'
ov.style.cssText = 'position:fixed;inset:0;z-index:2147483000;background:rgba(0,0,0,.38);display:flex;align-items:center;justify-content:center;color:#fff;font:14px/1.6 system-ui,sans-serif;-webkit-backdrop-filter:blur(2px);backdrop-filter:blur(2px)'
const bx = document.createElement('div')
bx.style.cssText = 'background:rgba(20,20,20,.93);padding:18px 24px;border-radius:12px;text-align:center;min-width:300px;box-shadow:0 10px 40px rgba(0,0,0,.4)'
bx.innerHTML = '<div style="font-weight:600;margin-bottom:8px">正在压缩画板图片(此期间请勿操作)</div>' +
'<div id="iwb-safe-compress-msg" style="opacity:.85">准备中…</div>' +
'<div style="opacity:.6;font-size:12px;margin-top:8px">原图已保留在本地缓存,可回退;压缩只影响画布内的显示副本</div>'
ov.appendChild(bx); document.body.appendChild(ov)
msgEl = document.getElementById('iwb-safe-compress-msg')
} catch (e) { /* 遮罩失败也要继续(但仍不允许并跑) */ }
const finish = (reason) => {
try { if (ov && ov.parentNode) ov.parentNode.removeChild(ov) } catch (e) { /* ignore */ }
_wSafeCompressBusy = false
lsSet(W_SAFE_COMPRESS_FLAG, true)
try {
console.info('[iwb] 画板图片压缩完成(' + (reason || 'ok') + '):' + done + ' 张,' +
(Math.round(mbBefore * 10) / 10) + 'MB → ' + (Math.round(mbAfter * 10) / 10) + 'MB')
} catch (e) { /* ignore */ }
}
const step = () => {
const list = wCollectBigImages(nodesNow(), 2.5 * 1048576).filter((h) => !wRecompressTried.has(h.nodeId + '|' + h.path))
if (!list.length) return finish('done')
const hit = list[0]
const node = nodesNow().find((n) => n && n.id === hit.nodeId)
const orig = wGetByPath(node && node.data, hit.path)
if (typeof orig !== 'string') { wRecompressTried.add(hit.nodeId + '|' + hit.path); setTimeout(step, 0); return }
const mb = (x) => Math.round(String(x).length / 1048576 * 10) / 10
if (msgEl) msgEl.textContent = '第 ' + (done + 1) + ' / ' + total + ' 张 · ' + mb(orig) + 'MB'
try { iwbCacheWrite(orig) } catch (e) { /* 原图入 Cache(可回退),失败不影响压缩 */ }
const conf = Object.assign({}, (compressConf(D.config ? D.config() : null) || {}), { enabled: true, force: true, maxMB: 0, maxEdge: 1600, quality: 0.85 })
compressDataUrl(orig, conf, (out) => {
try {
if (typeof out === 'string' && out.length && out.length < orig.length * 0.8) {
const next = nodesNow().map((n) => {
if (!n || n.id !== hit.nodeId) return n
const data = Object.assign({}, n.data)
wSetByPath(data, hit.path, out)
return Object.assign({}, n, { data: data })
})
if (D.commit) D.commit(next)
mbBefore += orig.length / 1048576; mbAfter += out.length / 1048576
}
} catch (e) { /* ignore */ }
wRecompressTried.add(hit.nodeId + '|' + hit.path)
done++
setTimeout(step, 30) // 让出事件循环,遮罩期间也不阻塞 UI 绘制
})
}
setTimeout(step, 60)
} catch (e) { _wSafeCompressBusy = false }
}
function compressConf(config) {
let c = config && config.imageTransfer && config.imageTransfer.compression
// v3.0.x 导入图片修复(§13.34 同等水平):调用方常传的是**公开配置** —— Canvas 里的 `config` 来自
// `api('config')` ⇒ `wCfgPublic()`,而 `wCfgPublic().imageTransfer` **只有 mode/maxRefs/imageHost,
// 没有 compression 字段** ⇒ 这里拿到 undefined ⇒ compressDataUrl 进入 `maxMB=0 ⇒ skipOpt` 分支**直接返回原图**。
// 实测(4K 图拖入,v3.0.1+b44c17e):节点里落的是 9,321,127 字符的**原图** base64,`__IWB_COMPRESS_LAST__` 恒为 null。
// 修法:形状不匹配时回退到**运行时归一化配置**(`wRawCfg().imageTransfer.compression`,含默认值与 v3.87.40 收紧),
// 让"调用方传了不同形状的配置"再也不会退化成"静默不压缩"。
if (!c) {
try {
const raw = wRawCfg()
c = raw && raw.imageTransfer && raw.imageTransfer.compression
} catch (e) { c = null }
}
if (!c) return c
// v3.87.40:画布图片安全上限。历史默认(maxMB 8 / maxEdge 2048 / quality 0.9 / format keep)**几乎等于不压缩**:
// "超阈值才压缩" + PNG 保持 PNG ⇒ 一张 2048² PNG ≈ 6–10MB,6 张图就是 50MB 画板常驻;
// 而移动节点/缩放/保存都会反复"经过"这批数据 ⇒ 叠加 V8 惰性 GC 就出现 GB 级瞬时台阶(实测 +1.5~2.2GB)。
// 这里只收紧"仍是最宽松档"的配置(用户显式改过的定制档原样不动),并且**不改 format**(保住 PNG 透明)。
const loose = Number(c.maxMB) >= 8 && Number(c.maxEdge) >= 2048 && c.format === 'keep' && Number(c.quality) >= 0.9
return loose ? Object.assign({}, c, { maxMB: 1.5, maxEdge: 1600, quality: 0.85 }) : c
}
// ==== v3.0.x 导入图片唯一收口(§13.34)====
// 症状(用户实测 v3.0.1+b44c17e,4K 图**导入画布**:此前只测过生成/图库路径):堆骤增、变卡。
// 诊断:base64MB 0 → 48.8MB,而 comp.boardsMB 仍 0.3MB ⇒ 引用化机制本身没问题,
// 是**导入这条路径**把图留在实时画布节点里(落盘的引用形态是对的,实时内存里的不是)。
// 根因(三条,均已实测复现,见 tests/iwb-import-4k.spec.js 与源码契约 143-1…147-1):
// ① `compressConf(公开配置)` = undefined ⇒ 压缩整条链路被静默跳过(4K 9.3MB 原图直入节点);
// ② 导入结果无论压缩与否都是一个**裸 dataURL 字符串**写进 node.data.data,从不引用化;
// ③ 解码失败时 `withDecodedImage` 吞掉异常且**不回调** ⇒ 压缩回调死等 ⇒ 导入**静默丢失**
// (此前被 ① 掩盖:从不压缩 ⇒ 从不进这条路径;已在 mainThreadCompress 补 `<img>` 兜底)。
// 修法(三步,缺一不可;全部复用既有管线,**不新造**第二套 objectURL 生命周期):
// ① 压缩到**显示尺寸**:长边 ≤ IMPORT_MAX_EDGE(1600)、force 强制、`format` 保持 ⇒ 保住 PNG 透明;
// ② 立即引用化:只经**唯一入口** `wImgRefWrite`({__blob} IDB 主通道 → {__cache} 兜底);
// ③ 小图(≤3000 字符)不值得写库,直接内联;写库两条通道都失败时**可见告警**(绝不静默);
// ④ 兜底:宿主**没有可靠解码器**(Worker/OffscreenCanvas 与 createImageBitmap 都没有)或压缩超时 ⇒
// 跳过几何压缩、直接用原始字节走引用化(内存目标同样达成:节点里是引用不是 base64),
// 并给出可见提示 —— 绝不出现"回调永不触发 ⇒ 导入静默丢失"。
const IMPORT_MAX_EDGE = 1600
const IMPORT_INLINE_MAX = 3000 // 与 isBigDataUrl 同阈值:≤3000 字符的图直接内联,不写库
const IMPORT_COMPRESS_TIMEOUT_MS = 12000 // > CompressWorker 自身 8s 超时,避免抢先中断合法的 worker→主线程回退
const wImportNoticeSink = { fn: null } // 画布挂载时注入 setNotice:保证任何调用点失败都**可见**
function wImportNotice(payload) {
try { if (typeof wImportNoticeSink.fn === 'function') wImportNoticeSink.fn(payload) } catch (e) { /* ignore */ }
}
// 通用通知槽(2026-10-20):供**模块层**(Workbench 之外)代码把「用户该知道的失败」送达 UI。
// 动机:wLog 写日志失败时,此前只能静默 —— 用户以为一切正常,实际诊断日志已瞎。
// 机制与 wImportNotice 相同(画布挂载时注入 setNotice),但语义更通用、类型分开(err/warn)。
const wGlobalNoticeSink = { fn: null }
function wLogNotice(text, type) {
try { if (typeof wGlobalNoticeSink.fn === 'function') wGlobalNoticeSink.fn({ type: type || 'err', text: String(text || '') }) } catch (e) { /* ignore */ }
}
function wImportReport(opts, payload) {
const msg = String((payload && payload.text) || '导入图片失败')
const soft = !!(payload && (payload.warn || payload.ok))
try { if (soft) console.warn('[iwb] 导入图片:' + msg); else console.error('[iwb] 导入图片:' + msg) } catch (e) { /* ignore */ }
// 硬失败:优先走调用点自己的提示通道,没有则走全局通道(两者都不可用 ⇒ 至少 console 已留痕)
if (!soft) {
if (opts && typeof opts.onError === 'function') { try { opts.onError(msg, payload) } catch (e) { /* ignore */ } return }
wImportNotice({ type: 'err', text: msg }); return
}
// 软告警(已导入但有降级):全局通道置为 ok 样式,避免把"成功但降级"显示成失败
if (typeof wImportNoticeSink.fn === 'function') { wImportNotice({ type: 'ok', text: msg }); return }
if (opts && typeof opts.onError === 'function') { try { opts.onError(msg, payload) } catch (e) { /* ignore */ } }
}
// 把「用户提供的图片字节」变成可直接写进节点的形态:压缩后的**引用**(大图)/ 小图内联 / 失败。
// cb({ ok, data, ref, before, after, error }):
// data = 要写进 `node.data.data` 的值({__blob}/{__cache} 引用,或 ≤3000 字符的小图 dataURL)
// ref = 引用对象(内联/失败时为 null);before/after = 压缩前/后的字符数(诊断与契约用)
function wImportImage(dataUrl, opts, cb) {
const o = opts || {}
const call = (patch) => { try { cb(patch) } catch (e) { /* ignore */ } }
if (typeof dataUrl !== 'string' || dataUrl.indexOf('data:') !== 0) {
const p = { ok: false, error: 'unsupported-input', text: '导入失败:不支持的图片来源(只接受本地图片字节)' }
wImportReport(o, p); call(p); return
}
const before = dataUrl.length
// 落地:小图内联;大图只经**唯一入口** wImgRefWrite 引用化({__blob} 主通道 → {__cache} 兜底)
const finalize = (out) => {
const after = (typeof out === 'string') ? out.length : before
if (!out) { const p = { ok: false, error: 'empty-output', text: '导入失败:图片字节为空', before: before }; wImportReport(o, p); call(p); return }
if (after <= IMPORT_INLINE_MAX) { call({ ok: true, data: out, ref: null, before: before, after: after }); return }
const onWriteFailed = (code) => {
// 两条通道都失败(配额/隐私模式):保留图本身(功能不降级),但**必须可见**,绝不静默
const p = {
ok: true, warn: true, data: out, ref: null, before: before, after: after, error: code,
text: '图片已导入,但本地缓存写入失败(刷新后可能丢失,请尽快导出画布)',
}
wImportReport(o, p); call(p)
}
Promise.resolve().then(() => wImgRefWrite(out)).then((ref) => {
if (ref) { call({ ok: true, data: ref, ref: ref, before: before, after: after }); return }
onWriteFailed('ref-write-failed')
}).catch(() => { onWriteFailed('ref-write-throw') })
}
// ④ 可靠解码器探测:compressDataUrl 在"无 Worker/OffscreenCanvas 且无 createImageBitmap"时会退到
// `<img>` 兜底路径;某些宿主该路径既不 onload 也不 onerror ⇒ 回调永不触发(实测 jsdom 即如此,
// Chrome 在极端 OOM/损坏字节下也可能)。此时直接按原始字节导入(仍是引用,内存安全)。
const canResize = CompressWorker.available() || (typeof createImageBitmap === 'function')
// ⑤ GIF **不做几何压缩**(canvas 重采样只留第 1 帧 ⇒ 动画丢失);SVG 已在上一步转成 PNG。
// 同样走 finalize ⇒ 大图照样引用化(节点里仍是引用而非 base64)。
const srcMime = (String(dataUrl).match(/^data:([^;,]*)/) || [])[1] || ''
// v3.24.64:SVG 参考图先光栅化成 PNG(用户 2026-11-11 裁定:上游模型接口不认 SVG)。
// 转完递归走同一条压缩/引用化管线,不新造第二套落地逻辑;光栅化失败才按原字节导入(不丢用户操作)。
if (/^image\/svg\+xml$/i.test(srcMime) && ImageFormat && ImageFormat.svgToPngDataUrl) {
ImageFormat.svgToPngDataUrl(dataUrl, { maxEdge: IMPORT_MAX_EDGE }).then((png) => {
if (png) wImportImage(png, o, cb)
else { wImportReport(o, { ok: true, warn: true, text: 'SVG 参考图无法转换为 PNG,已按原文件导入', before: before }); finalize(dataUrl) }
})
return
}
// 保留原图(2026-11-26 相册):显式要求时不压缩,直接把原始字节引用化(分辨率不损失)
if (o.keepOriginal) { finalize(dataUrl); return }
const noResizeMime = /^image\/(gif)$/i.test(srcMime)
if (!canResize || noResizeMime) { finalize(dataUrl); return }
let settled = false
const once = (out) => { if (settled) return; settled = true; finalize(out) }
const timer = setTimeout(() => {
if (settled) return
settled = true
wImportReport(o, { ok: true, warn: true, text: '图片压缩超时,已按原图导入(显示与导出正常)', before: before })
finalize(dataUrl)
}, IMPORT_COMPRESS_TIMEOUT_MS)
let conf = null
try { conf = compressConf(wRawCfg()) } catch (e) { conf = null }
// 强制压缩到显示尺寸:`maxMB:0 + force` ⇒ 不走「超阈值才压缩」的跳过分支(那正是 4K 原图直入节点的入口)
const cap = Object.assign({}, conf || {}, {
enabled: true,
force: true,
maxMB: 0,
maxEdge: Math.min(IMPORT_MAX_EDGE, Math.max(1, Number(conf && conf.maxEdge) || IMPORT_MAX_EDGE)),
})
compressDataUrl(dataUrl, cap, (out) => {
try { clearTimeout(timer) } catch (e) { /* ignore */ }
if (typeof out !== 'string' || out.indexOf('data:') !== 0) {
// 压缩失败但原图可用:仍按原图导入(引用化),而不是丢弃用户这次操作
settled = true
wImportReport(o, { ok: true, warn: true, text: '图片压缩失败,已按原图导入(显示与导出正常)', before: before })
finalize(dataUrl); return
}
once(out)
})
}
// 文本框随内容自动长高(自适应节点时);固定高度节点由 flex 接管
function autoGrow(el) {
if (!el) return
el.style.height = 'auto'
el.style.height = Math.max(56, el.scrollHeight) + 'px'
}
// ---------- result image ----------
// 外部 UI 模块优先;单文件模式保留等价 fallback。
// 结果图组件唯一实现在 src/ui-components.js(导出 IWBResultImg)。
// 2026-10-28 P0:原 ui-canvas-view.js 里那份"完整版"是**死分支**(它第一行就 return ExternalResultImg),
// 已删除;这里直接指向唯一实现,少一层间接。
const ResultImg = (typeof window !== 'undefined' && window.IWBResultImg) || null
// 复制图片到剪贴板失败分类:跨域 / 浏览器不支持剪贴板图片 / 图片格式无法转换
function wCopyError(kind, detail) {
const e = new Error(detail)
e.iwbCopyKind = kind
return e
}
// 「跨域限制」:远程 http(s) 源取不到二进制
const W_COPY_HINT = {
cors: '跨域限制:无法读取该远程图片,请改用「下载」或本地图库里的同一张图',
unsupported: '当前浏览器不支持剪贴板图片,请改用「下载」',
format: '图片格式无法转换,请改用「下载」',
}
// 任意图片输入(Blob / dataURL / objectURL / 远程 URL)→ 一定是 image/png 的 Blob。
// 剪贴板只稳定支持 image/png:写 image/jpeg 在 Chromium 会直接抛错(JPEG 源必然复制失败),
// 所以这里统一「取 Blob → createImageBitmap 解码 → canvas.toBlob('image/png')」。
// 取源优先级由调用方保证:本地已解析源(objectURL / IDB / dataURL)优先,远程 http(s) 只作最后回退。
async function wImageBlobToPng(srcOrBlob) {
const s0 = (srcOrBlob && typeof Blob !== 'undefined' && srcOrBlob instanceof Blob) ? '' : String(srcOrBlob == null ? '' : srcOrBlob)
if (!srcOrBlob || (!s0 && !(srcOrBlob instanceof Blob))) throw wCopyError('format', W_COPY_HINT.format)
// 关键:data: 与 blob: 都不能用 fetch —— 线上 CSP 是 connect-src 'self' https:,
// fetch(data:...) 与 fetch(blob:...) 都会被拦(Chromium 实测原文见 _headers 注释与工程规范),
// 表现为「点复制毫无反应 / 提示图片格式无法转换」。本地测试服务器此前不解析 _headers,所以只在线上复现。
// 这里统一走 wBlobFromSrc:data: 手工解码、blob: 从 Blob 注册表直接拿回,都不经过网络。
const blob = await wBlobFromSrc(srcOrBlob)
if (!blob) {
// blob: 取不到 = 图片本身读不出来(可能已被 revoke);http(s) 取不到 = 跨域
const local = s0.indexOf('blob:') === 0
throw local ? wCopyError('format', W_COPY_HINT.format) : wCopyError('cors', W_COPY_HINT.cors)
}
if (blob.type === 'image/png') return blob
// v3.24.65:SVG **必定**解不了 createImageBitmap(Chromium 实测 "The source image could not be
// decoded.",有无固有尺寸都一样)⇒ 此前大图预览 / 图库的「复制」碰上 SVG 100% 报「图片格式无法转换」。
// 改用 <img>+canvas 光栅化,再把 dataURL 手工解码成 Blob(fetch(data:) 会被线上 CSP 拦)。
if (/^image\/svg\+xml/i.test(blob.type)) {
const src2 = s0 || wRegisterBlobUrl(blob)
const pngUrl = (ImageFormat && ImageFormat.svgToPngDataUrl) ? await ImageFormat.svgToPngDataUrl(src2, { maxEdge: 2048 }) : null
const svgPng = pngUrl ? await wBlobFromDataUrl(pngUrl) : null
if (!svgPng || svgPng.type !== 'image/png') throw wCopyError('format', W_COPY_HINT.format)
return svgPng
}
// 非 PNG(JPEG/WebP…)统一重编码为 PNG;复用统一解码头,finally 里关闭 bitmap
const png = await withDecodedImage(blob, async (bitmap) => {
if (!bitmap) return null
try {
const canvas = document.createElement('canvas')
canvas.width = Math.max(1, bitmap.width || 1)
canvas.height = Math.max(1, bitmap.height || 1)
const ctx = canvas.getContext('2d')
if (!ctx) return null
ctx.drawImage(bitmap, 0, 0)
return await new Promise((resolve) => {
try { canvas.toBlob((b) => resolve(b || null), 'image/png') } catch (e) { resolve(null) }
})
} catch (e) { return null }
})
if (!png || png.type !== 'image/png') throw wCopyError('format', W_COPY_HINT.format)
return png
}
// 全应用唯一「复制图片到剪贴板」实现:预览复制与图库条目复制都走这里,避免两份实现只改一处。
async function copyImageToClipboard(srcOrBlob) {
if (!srcOrBlob) throw wCopyError('format', W_COPY_HINT.format)
if (!navigator.clipboard || typeof navigator.clipboard.write !== 'function' || typeof ClipboardItem === 'undefined') {
// 桌面端兜底:WKWebView 里 ClipboardItem 常不可用,改走原生 arboard 写图片
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
if (D && D.clipboardWriteImage) {
const okNative = await D.clipboardWriteImage(srcOrBlob)
if (okNative) return srcOrBlob
}
throw wCopyError('unsupported', W_COPY_HINT.unsupported)
}
// 先转 PNG 再写剪贴板(任何输入都产出 image/png)
const png = await wImageBlobToPng(srcOrBlob)
try {
await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })])
} catch (err) {
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
if (D && D.clipboardWriteImage) {
const okNative = await D.clipboardWriteImage(png)
if (okNative) return png
}
const msg = String((err && err.message) || err)
// 没有写权限(页面失焦/未授权)也归为「浏览器不支持剪贴板图片」一类,附浏览器原文便于排查
throw wCopyError('unsupported', W_COPY_HINT.unsupported + '(' + msg + ')')
}
return png
}
// 预计剩余时间:基于平均单张耗时 × 剩余张数 / 并发窗口
function etaText(p, concurrency) {
const left = Math.max(0, (p.total || 0) - (p.done || 0))
const avg = p.avgMs || 0
if (p.done <= 0 || !left || !avg) return ''
const secs = Math.round((avg / 1000) * left / (concurrency || GEN_CONCURRENCY_DEFAULT))
if (secs < 60) return ' · 预计还需约 ' + secs + 's'
const m = Math.floor(secs / 60), s2 = secs % 60
return ' · 预计还需约 ' + (m ? m + ' 分' : '') + (s2 ? (m ? ' ' : '') + s2 + 's' : '')
}
// 时长格式(任务条/输出节点共用):<60s → "48s";<1h → "1分12s";否则 "1时05分"
function fmtDur(ms) {
const total = Math.max(0, Math.round((Number(ms) || 0) / 1000))
if (total < 60) return total + 's'
const m = Math.floor(total / 60), rs = total % 60
if (m < 60) return m + '分' + (rs ? rs + 's' : '')
const h = Math.floor(m / 60), rm = m % 60
return h + '时' + String(rm).padStart(2, '0') + '分'
}
// ---------- 内存护栏:有界 objectURL 缓存 + 统一解码头 + 并发闸门 ----------
// 有界 objectURL 缓存(对标 opentu character-avatar-cache-service):上限 50,FIFO 驱逐时立即 revoke,
// 避免「解析出来的原图 objectURL 用完没人管」长期占住堆外内存与 blob 引用。
const W_OBJURL_MAX = 50
const wObjUrlCache = new Map()
// objectURL → 原 Blob 注册表(与 wObjUrlCache 同步 FIFO 驱逐)。
// 动机:线上 CSP 是 connect-src 'self' https:,**fetch(blob:...) 也会被拦**
// ("Refused to connect to 'blob:...' ... connect-src 'self' https:",Chromium 实测),
// 所以凡是我们自己 createObjectURL 出来的图,都必须能取回原 Blob,不能靠 fetch 绕回来。
const W_BLOBREF_MAX = 50
const wBlobRefCache = new Map()
function wBlobRefDrop(url) {
if (!url) return
const b = wBlobRefCache.get(url)
if (b !== undefined) wBlobRefCache.delete(url)
}
function wBlobRefPut(url, blob) {
if (!url || !blob) return url
wBlobRefDrop(url)
while (wBlobRefCache.size >= W_BLOBREF_MAX) {
const oldest = wBlobRefCache.keys().next().value
if (oldest === undefined) break
wBlobRefCache.delete(oldest)
}
wBlobRefCache.set(url, blob)
return url
}
// 自建 objectURL 的统一入口:先注册 Blob 再返回 URL(拿不回 Blob 的 objectURL 一律不要用这个入口)
function wRegisterBlobUrl(blob) {
let url = ''
try { url = URL.createObjectURL(blob) } catch (e) { return '' }
wBlobRefPut(url, blob)
return url
}
function wBlobRefGet(url) {
const s = String(url || '')
if (!s) return null
const b = wBlobRefCache.get(s)
return (b && typeof b.arrayBuffer === 'function') ? b : null
}
function wObjUrlPut(key, url) {
if (!key || !url) return url
const prev = wObjUrlCache.get(key)
if (prev !== undefined) {
wObjUrlCache.delete(key)
if (prev !== url) { try { URL.revokeObjectURL(prev) } catch (e) { /* ignore */ } wBlobRefDrop(prev) }
}
while (wObjUrlCache.size >= W_OBJURL_MAX) {
const oldest = wObjUrlCache.keys().next().value
if (oldest === undefined) break
const oldUrl = wObjUrlCache.get(oldest)
wObjUrlCache.delete(oldest)
if (oldUrl && oldUrl !== url) { try { URL.revokeObjectURL(oldUrl) } catch (e) { /* ignore */ } wBlobRefDrop(oldUrl) }
}
wObjUrlCache.set(key, url)
return url
}
function wObjUrlClear() {
for (const u of wObjUrlCache.values()) { try { URL.revokeObjectURL(u) } catch (e) { /* ignore */ } wBlobRefDrop(u) }
wObjUrlCache.clear()
wBlobRefCache.clear()
}
// base64 dataURL → Blob:堆里不再保留解码后的二进制;调用方拿到 Blob 后可立即放开原字符串。
// 关键:绝不能用 fetch 取 data: URL —— 线上 CSP 是 connect-src 'self' https:,
// 会直接拦掉 fetch(data:...)("Refused to connect because it violates ... Content Security Policy");
// 旧实现「先 fetch 再回退 atob」在线上每次都先产生一次 CSP 违规。这里纯手工解码,不经过网络。
// 返回 null = 不是 data: URL 或解码失败(调用方负责区分「本就不该走这里」与「格式坏了」)。
// 统一「拿图片二进制」入口:data: → 手工解码(不碰网络,绕开 CSP);
// blob: → 先查自建 objectURL 注册表(命中即拿回原 Blob,零解码),查不到才 fetch 兜底;
// http(s) → fetch。
// 任何可能收到 dataURL / objectURL 的取 Blob 路径都应该走这里,别再各自 fetch(src)。
// 成功返回 Blob;失败/不支持的 scheme 返回 null(调用方按场景决定回退或报错)。
async function wBlobFromSrc(src) {
if (src && typeof Blob !== 'undefined' && src instanceof Blob) return src
const s = String(src == null ? '' : src)
if (!s) return null
if (s.indexOf('data:') === 0) return await wBlobFromDataUrl(s)
if (s.indexOf('blob:') === 0) {
const known = wBlobRefGet(s)
if (known) return known
// C3:本会话图片引用解析出的 objectURL —— wBlobRefCache 被 FIFO 驱逐后仍能凭引用回 IDB/Cache 取回原 Blob
// (线上 CSP connect-src 'self' https: 会拦 fetch(blob:),所以这一步不能只靠下面的 fetch 兜底)
const imgRef = wImgRefByUrl.get(s)
if (imgRef) {
const got = await wImgRefDataUrl(imgRef)
const b = got ? await wBlobFromDataUrl(got) : null
if (b) { wBlobRefPut(s, b); return b }
}
// 非本模块创建的 objectURL(或注册表已驱逐):fetch(blob:) 在线上 CSP 下会被拦,这里只作兜底尝试
try { const r = await fetch(s); if (r && r.ok) return await r.blob() } catch (e) { /* CSP 拦截 / 已 revoke → null */ }
return null
}
if (/^https?:/i.test(s)) {
try { const r = await fetch(s); if (r && r.ok) return await r.blob() } catch (e) { /* 跨域/网络失败 → null */ }
return null
}
return null
}
// 统一解码头:createImageBitmap → 交给 fn → finally 关闭 bitmap + revoke 临时 objectURL,
// 从源头杜绝「解出来用完不管」的 decode 泄漏(未压缩位图是堆里最大的一块)。
// 注意:createImageBitmap 只接受 Blob/Canvas/ImageData 等,不接受 URL 字符串——dataURL 必须先转 Blob。
// 通用并发闸门:items 逐个过 fn,最多 limit 个在飞(自动下载 / 批量补缩略图等)
async function runWithConcurrency(items, limit, fn) {
const list = Array.isArray(items) ? items : []
const max = Math.max(1, Math.floor(Number(limit) || 1))
let cursor = 0
const worker = async () => {
while (cursor < list.length) {
const i = cursor++
try { await fn(list[i], i) } catch (e) { /* 单张失败不影响其余 */ }
}
}
const runners = []
for (let i = 0; i < Math.min(max, list.length); i++) runners.push(worker())
await Promise.all(runners)
return list.length
}
// 跨域图片安全下载:<a download> 对跨域 URL 无效(浏览器会导航而非下载)。
// fetch → blob → objectURL(同源)后触发下载;CORS 受限时退回新窗口打开原图。
// 定义在模块顶层:renderBodyInner 是顶层函数(组件外),组件内的下载点与节点内下载共用。
// v3.87.34:轻量提示(模块顶层用,不依赖组件状态)
const wDownloadToast = (text) => {
try {
const d = document.createElement('div')
d.textContent = text
d.style.cssText = 'position:fixed;left:50%;bottom:28px;transform:translateX(-50%);z-index:9999;background:rgba(20,20,20,.92);color:#fff;padding:8px 14px;border-radius:8px;font-size:13px;max-width:80vw;box-shadow:0 6px 20px rgba(0,0,0,.35)'
document.body.appendChild(d)
setTimeout(() => { try { d.remove() } catch (e) { /* ignore */ } }, 4600)
} catch (e) { /* ignore */ }
}
// 下载(所有入口共用)。豆包/火山 TOS 等图床**不发 CORS 头** ⇒ 直连 fetch 必失败,
// 因此链路为:① 直连 → ② 本地已归档原图 → ③ 图片代理(带 CORS)→ ④ 新标签打开兜底。
if (typeof window !== 'undefined') window.__IWB_E2E_DOWNLOAD__ = (u, n) => downloadUrl(u, n) // e2e:下载链路钩子
const downloadUrl = async (url, name) => {
if (!url) return
const su = String(url)
// v3.24.64:后缀跟着**真实格式**走(上游已会返回 .svg,而 8 个调用点全都硬编码 'image.png')。
// 统一在这里纠正两次:进 URL 阶段按地址后缀判一次(CORS 失败、走 IDB/新标签时也生效),
// 拿到字节后按 blob.type 再判一次(服务端 Content-Type 最准)。判不出格式时原样返回旧名。
const nameOf = (mime) => (ImageFormat && ImageFormat.fileNameFor) ? ImageFormat.fileNameFor(su, name, mime) : (name || 'image.png')
// v3.24.65:`blob:` 地址字符串里没有任何格式线索(只有 uuid)⇒ 图库/大图预览/输出缩略图
// 传进来的都是本模块自建的 objectURL,从 Blob 注册表取回 type 再判,否则这三处永远落回 .png。
const ownBlob = (su.indexOf('blob:') === 0) ? wBlobRefGet(su) : null
let outName = nameOf(ownBlob ? ownBlob.type : '')
const clickDownload = (href) => {
const a = document.createElement('a')
a.href = href
a.download = outName
document.body.appendChild(a)
a.click(); a.remove()
}
const downloadBlob = (blob) => {
if (blob && blob.type) outName = nameOf(blob.type)
// 桌面端:替换原来的 <a download>,弹系统「另存为」后 fs 写二进制
if (wIsTauri()) {
wSaveBlobNative(blob, outName, '保存图片')
.then((ok) => { if (ok) wDownloadToast('已保存:' + outName) })
.catch((e) => wDownloadToast('保存失败:' + ((e && e.message) || e)))
return
}
const obj = URL.createObjectURL(blob)
clickDownload(obj)
setTimeout(() => URL.revokeObjectURL(obj), 5000)
}
// data URL / blob: URL(同源,已被浏览器解析过):直接用 <a download>。
// 注意 blob: 也必须走这条路:线上 CSP connect-src 'self' https: 会拦掉 fetch(blob:...)。
if (su.indexOf('data:') === 0 || su.indexOf('blob:') === 0) {
// 桌面端没有「浏览器下载目录」这回事 ⇒ 先取回字节,再走原生另存为
if (wIsTauri()) { try { downloadBlob(await (await fetch(url)).blob()); return } catch (e) { /* 落到后面的兜底 */ } }
else { clickDownload(url); return }
}
// ① 直连(图床允许跨域时最快、最保真)
try {
const resp = await fetch(url, { mode: 'cors' })
if (!resp.ok) throw new Error('HTTP ' + resp.status)
downloadBlob(await resp.blob())
return
} catch (e) { /* 跨域/403:继续兜底 */ }
// ② 本地已归档原图(此前抓取成功过才有;CORS 图床为空)
try {
const idx = lsGet(OUT_KEY, [])
const hit = (idx || []).find((x) => x && String(x.url) === su)
const key = hit && (hit.origIdb || (IDB_ORIG_PREFIX + String(hit.name || '')))
if (key) {
const v = await IDB.get(key).catch(() => null)
if (v) {
if (typeof v === 'string') downloadBlob(await (await fetch(v)).blob())
else if (v instanceof Blob) downloadBlob(v)
else if (v && v.size) downloadBlob(new Blob([v]))
else throw new Error('empty')
return
}
}
} catch (e) { /* 继续兜底 */ }
// ③ 原生 HTTP 兜底(Rust 侧请求,不受 CORS 限制)
// 本项目是桌面客户端,没有服务端同源代理(旧的 functions/api/img.js 已随网页版删除)
try {
if (wIsTauri()) {
const r2 = await wTauri.http.fetch(su)
if (r2.ok) { downloadBlob(await r2.blob()); wDownloadToast('已通过原生 HTTP 取图保存'); return }
}
} catch (e) { /* 继续兜底 */ }
// ④ 最后兜底:新标签打开(右键/长按另存)——绝不静默失败
try {
try { window.IWBUIShell ? window.IWBUIShell.openExternal(su) : window.open(su, '_blank', 'noopener') } catch (e) { /* ignore */ }
wDownloadToast('该图床不支持直接下载,已在新标签打开图片:请右键「图片另存为」')
} catch (e) {
wDownloadToast('下载失败:' + ((e && e.message) || '未知原因'))
}
}
// ---------- node body ----------
// 输出节点的紧凑进度行:一行内自适应宽度(完整信息放 title 悬停提示,不再撑破节点)
const outProgUI = (p, concurrency) => {
if (!p) return null
const total = Number(p.total) || 0
const done = Math.min(total, Math.max(0, Number(p.done) || 0))
const left = Math.max(0, total - done)
const eta = etaText({ ...p, done, total }, concurrency).replace(/^ · /, '')
const waited = Math.max(0, Number(p.waitMs) || 0)
const title = '生成中 · ' + (Number(p.groups) || 1) + ' 组 · 共 ' + total + ' 张 · 已完成 ' + done + ' 张 · 剩余 ' + left + ' 张'
+ (waited >= 1500 ? ' · 已等 ' + fmtDur(waited) : '') + (eta ? ' · ' + eta : '')
return el('div', { className: 'iwb-out-prog iwb-out-generation-status', title },
el('span', { className: 'iwb-generation-spinner', 'aria-hidden': 'true' }),
el('span', { className: 'iwb-out-prog-count' }, done + '/' + total),
el('span', { className: 'iwb-out-prog-time' },
(waited >= 1500 ? '已等 ' + fmtDur(waited) : '生成中') + (eta ? ' · ' + eta : ''),
),
)
}
// gen 节点参数区(memo 化:拖动时 node.data/config 不变则跳过重建,对齐参考项目拆分思路)
// 「模型设置」面板(2026-10-30):服务商 / 分组 / 模型 三个低频控件收进面板(src/ui-gen-config-panel.js)
const GenConfigPanel = (typeof window !== 'undefined' && window.IWBUIGenConfigPanel && window.IWBUIGenConfigPanel.GenConfigPanel) || null, UiGenCfgModule = (typeof window !== 'undefined' && window.IWBUIGenConfigPanel) || null
// 背景色「悬停预览」:只改节点 DOM(data-bg / 类),不写数据、不进撤销栈;点色块才真正落库
const bgPreviewEls = []
const previewNodeBg = (ids, bg) => {
(ids || []).forEach((id) => {
const el0 = document.querySelector('.iwb-node[data-node-id="' + id + '"]')
if (!el0) return
if (!bgPreviewEls.some((r) => r.el === el0)) {
bgPreviewEls.push({ el: el0, bg: el0.getAttribute('data-bg'), cls: el0.classList.contains('iwb-node-bg-custom') })
}
if (bg) { el0.setAttribute('data-bg', bg); el0.classList.add('iwb-node-bg-custom') }
else { el0.removeAttribute('data-bg'); el0.classList.remove('iwb-node-bg-custom') }
})
}
const endNodeBgPreview = () => {
bgPreviewEls.forEach((r) => {
if (r.bg) r.el.setAttribute('data-bg', r.bg)
else r.el.removeAttribute('data-bg')
r.el.classList.toggle('iwb-node-bg-custom', r.cls)
})
bgPreviewEls.length = 0
}
// 工具栏加节点:算「当前视口中心」当找位种子(模块级;Workbench 只做一行装配,避免组件变长)
const tbCenterSeed = (type, refs) => {
const c = document.querySelector('.iwb-canvas')
const wl = document.querySelector('.iwb-world')
if (!c || !c.clientWidth) return null
const m = wl && /translate\((-?[\d.]+)px,\s*(-?[\d.]+)px\)\s*scale\(([\d.]+)\)/.exec(wl.style.transform || '')
const vx = m ? Number(m[1]) : 0, vy = m ? Number(m[2]) : 0, sc = m ? Number(m[3]) : 1
const hEst = (refs.nodes || []).filter((n) => n.type === type).map((n) => refs.measuredH[n.id] || n.h).find((v) => v > 0) || Math.min(nodeTypeH(type), 120)
return { x: (c.clientWidth / 2 - vx) / sc, y: (c.clientHeight / 2 - vy) / sc + (nodeTypeH(type) - hEst) / 2, w: c.clientWidth, h: c.clientHeight }
}
const GenParams = React.memo(function GenParams(props) {
const { nodeId, data, config, onUpdate } = props
const stop = (e) => e.stopPropagation()
const d = data || {}
const cfg = config || { providers: [] }
// fields:渲染哪些参数。默认与生图节点完全一致(三个 pick + 尺寸汇总条);
// 分层节点传 ['provider','keyGroup','model'] —— 复用同一个组件,宽度/字号/气泡行为自动统一。
const fields = Array.isArray(props.fields) && props.fields.length ? props.fields : ['provider', 'keyGroup', 'model', 'summary']
const show = (k) => fields.indexOf(k) >= 0
const providers = cfg.providers || []
const curProvider = providers.find((p) => p.id === d.provider) || providers[0] || { id: '', keys: [] }
const keyGroups = curProvider.keys || []
const DEFAULT_MODELS = ['gpt-image-2', 'gpt-image-2-vip']
// modelPool:模型选项来源。默认 = 当前服务商的 models(生图节点);
// 分层节点传 layerModels,从而与生图模型清单隔离(规范 §13.26)。
const modelPool = Array.isArray(props.modelPool) ? props.modelPool : (Array.isArray(curProvider.models) ? curProvider.models : [])
const visibleModels = []
for (const m of modelPool) if (m && m.visible) visibleModels.push(m.name)
const modelOpts = visibleModels.length
? visibleModels.map((n) => ({ value: n, label: n }))
: DEFAULT_MODELS.map((n) => ({ value: n, label: n }))
const modelAvailable = !curProvider || !d.model || !modelPool.length || modelPool.some((m) => m.name === d.model && m.visible !== false)
if (d.model && !visibleModels.includes(d.model) && !DEFAULT_MODELS.includes(d.model)) modelOpts.push({ value: d.model, label: d.model + '(自定义)' })
const provOpts = providers.map((p) => ({ value: p.id, label: p.name || p.id }))
const keyOpts = keyGroups.map((k) => ({ value: k.id, label: k.name || k.id }))
const ratioPresets = (config && config.canvas && Array.isArray(config.canvas.sizePresets) && config.canvas.sizePresets.length) ? config.canvas.sizePresets : RATIOS
// 显示名用 label(可改),value 只作标识(不可改)——改名前二者是同一个值,改名就会丢焦点。
const ratioOpts = ratioPresets.map((r) => el('option', { key: r.value, value: r.value }, presetDisplayName(r)))
const curRatio = d.ratio || ratioOfSize(d.size) || 'auto'
const curRes = RES_MAP[d.res] || resOfSize(d.size) || '1K'
const curRatioAuto = curRatio === 'auto'
const resOpts = RES_KEYS.map((k) => el('option', { key: k, value: k }, k))
const cell = (label, control) => el('div', { className: 'iwb-gen-cell', title: label }, control)
// —— 尺寸:显示「实际会提交给服务商的尺寸」,可直接改 → 进入自定义尺寸模式
// (激活既有的 custom/customSize 字段:standardSizeOf 会优先返回它)。
// 改比例/清晰度会退出自定义并刷新这里的数字;「16 倍数对齐」只作用于自定义尺寸
// (内置 33 个预设尺寸本身已全部是 16 的倍数,所以对预设没有任何影响)。
const derivedSize = standardSizeOf(d)
const dm = /^(\d+)x(\d+)$/.exec(String(derivedSize || '').trim())
const [sizeW, setSizeW] = React.useState(dm ? dm[1] : '')
const [sizeH, setSizeH] = React.useState(dm ? dm[2] : '')
React.useEffect(() => {
const m = /^(\d+)x(\d+)$/.exec(String(standardSizeOf(d) || '').trim())
if (m) { setSizeW(m[1]); setSizeH(m[2]) }
}, [derivedSize])
const align16 = d.align16 === true
const isCustom = !!(d.custom && String(d.customSize || '').trim())
const customErr = isCustom ? sizeCheck(d.customSize) : null
const commitSize = () => {
let w = Math.round(Number(sizeW) || 0)
let h = Math.round(Number(sizeH) || 0)
if (align16) { w = snap16(w); h = snap16(h) }
if (!(w > 0 && h > 0)) {
// 清空/非法 → 回到当前预设尺寸,绝不写坏数据
const m = /^(\d+)x(\d+)$/.exec(String(standardSizeOf(d) || '').trim())
if (m) { setSizeW(m[1]); setSizeH(m[2]) }
return
}
const next = w + 'x' + h
if (align16) { setSizeW(String(w)); setSizeH(String(h)) }
if (isCustom && next === String(d.customSize || '')) return
onUpdate({ custom: true, customSize: next, size: next })
}
const numProps = { className: 'iwb-input iwb-size-num', type: 'number', min: 16, max: 3840, step: 16, onPointerDown: stop, onKeyDown: (e) => { if (e.key === 'Enter') { e.preventDefault(); commitSize() } }, onBlur: commitSize }
const qualityNow = qualityOf(d)
// 模型不支持质量 / 渠道拒绝过 → 实际发送的是「自动」,汇总条必须如实显示(否则用户以为选了高档)
const qualityUnsupported = !supportsQualityOf(cfg, d) || isQualityUnsupported(d.provider, d.model)
const [panelOpen, setPanelOpen] = React.useState(false)
const [anchor, setAnchor] = React.useState(null)
// 服务商 / 分组 / 模型 改为自绘气泡:由组件内 state 管理「哪个在打开」(值 { kind, anchor }),
// 不用模块级变量,节点卸载即随之消失。再点同一个触发器 = 收起。
// 「模型设置」面板(2026-10-30):服务商 / 分组 / 模型 三个低频控件收进面板,
// 节点参数行只留「模型 + 尺寸」——原来 4 个控件挤在一行且不换行,节点只能靠 480px 宽硬撑。
const [cfgOpen, setCfgOpen] = React.useState(false)
const [cfgAnchor, setCfgAnchor] = React.useState(null)
const toggleCfg = (e) => {
e.stopPropagation()
if (cfgOpen) { setCfgOpen(false); return }
const r = e.currentTarget.getBoundingClientRect()
setCfgAnchor({ left: r.left, right: r.right, top: r.top, bottom: r.bottom })
setPanelOpen(false) // 两个浮层互斥:开模型设置就关掉图像设置(2026-10-31 用户反馈)
setCfgOpen(true)
}
const pickLabel = (list, v, fb) => { const hit = (list || []).find((o) => o.value === v); return hit ? hit.label : fb }
// 模型清单规则(可见项 / 缺省兜底 / 自定义追加)与原来一致,不在这里改动
const curKey = keyGroups.find((k) => k.id === d.keyGroup) || null
// 厂商提示(尺寸/质量怎么发)曾挂在已删除的信息行上 ⇒ 挪到「尺寸」按钮 title(它讲的正是尺寸)
const vendorHint = (() => {
try {
const Sh = (typeof window !== 'undefined' && window.IWBGenerationRequestShape) || null
if (!Sh) return ''
const prov2 = (cfg.providers || []).find((x) => x && x.id === d.provider)
const me2 = prov2 && (prov2.models || []).find((m) => String((m && m.name) || m) === String(d.model || ''))
const k2 = Sh.resolveKind(d.model, prov2 && prov2.kind, prov2.modelRules, me2 && me2.kind)
if (k2 === 'openai') return ''
return k2 === 'gemini' ? '尺寸按「比例 + K 档」发送(不发像素);质量即分辨率档' : k2 === 'doubao' ? '尺寸按「K 档或像素」发送;比例=自动时发 K 档' : '使用自定义请求体模板'
} catch (e) { return '' }
})()
return el('div', { className: 'iwb-gen-settings' },
el('div', { className: 'iwb-gen-row' },
show('model') ? cell('模型', el('button', {
className: 'iwb-btn iwb-btn-sm iwb-pick iwb-pick-genmodel' + (modelAvailable ? '' : ' iwb-input-err'), type: 'button',
title: (modelAvailable ? '当前模型' : '当前模型已删除或隐藏,请重新选择') + ':' + String(d.model || '')
+ ' · 服务商:' + String(curProvider.name || curProvider.id || '未选') + ' · 分组:' + (curKey ? String(curKey.name || curKey.id) : '无分组'),
onClick: toggleCfg, onPointerDown: stop,
}, el('span', { className: 'iwb-pick-name' }, pickLabel(modelOpts, d.model, d.model || '选择模型')), el('span', { className: 'iwb-pick-caret' }, I('chevronDown')))) : null,
show('summary') ? el('button', {
className: 'iwb-btn iwb-btn-sm iwb-gen-summary',
title: '图像设置:尺寸 / 分辨率 / 比例 / 质量' + (vendorHint ? '|' + vendorHint : '') + (qualityUnsupported ? '(当前模型不支持质量档位或渠道拒绝过,已按「自动」发送)' : ''),
onClick: (e) => { const r = e.currentTarget.getBoundingClientRect(); setAnchor({ left: r.left, right: r.right, top: r.top, bottom: r.bottom }); setCfgOpen(false); setPanelOpen(true) },
onPointerDown: stop,
},
(curRatio === 'auto' ? '自动' : ((ratioPresets.find((x) => x.value === curRatio) || {}).label || curRatio)) + ' · ' + (curRatioAuto ? '自动' : curRes) + ' · ' + qualityLabelOf(qualityUnsupported ? 'auto' : qualityNow) , el('span', { className: 'iwb-pick-caret' }, I('chevronDown'))) : null,
),
panelOpen ? el(ImageSettingsPanel, { nodeId, data: d, config: cfg, onUpdate, anchor, onClose: () => setPanelOpen(false) }) : null,
// 「模型设置」面板:服务商 / 分组 / 模型(低频操作,收进面板后节点行只剩模型 + 尺寸)
cfgOpen && GenConfigPanel ? el(GenConfigPanel, {
anchor: cfgAnchor,
placePanel: placePopover,
providers,
keyGroups,
modelOpts,
curProviderId: curProvider.id || '',
curKeyGroup: d.keyGroup || '',
curModel: d.model || '',
modelAvailable,
onClose: () => setCfgOpen(false),
// 切服务商 ⇒ 分组重置为该服务商第一个 key(原 pick 逻辑原样保留)
onPickProvider: (pid) => { const pp = providers.find((x) => x.id === pid); onUpdate({ provider: pid, keyGroup: (pp && pp.keys && pp.keys[0] && pp.keys[0].id) || '' }) },
onPickGroup: (kid) => onUpdate({ keyGroup: kid }),
onPickModel: (m) => { onUpdate({ model: m }); setCfgOpen(false) },
}) : null,
)
}, (a, b) => a.data === b.data && a.config === b.config && a.nodeId === b.nodeId)
// 尺寸取整(共用):就近取整到 16 的倍数,并钳在 [16, 3840](3840 本身就是 16 的倍数)。
// 节点内的尺寸行与图像设置浮层共用同一份,避免两处实现漂移。
function snap16(v) { return Math.max(16, Math.min(3840, Math.round((Number(v) || 0) / 16) * 16 || 16)) }
// 贴元素浮层的共用定位(ImageSettingsPanel 与 PickerBubble 两处复用,避免两份实现漂移):
// 横向左对齐触发元素并在超出右边界时钳位;默认向上弹出(面板底边 = 触发元素顶边 - 8),
// 上方放不下再向下翻;两个方向都放不下时夹在视口内。定位用 viewport 坐标(fixed),
// 与画布缩放/平移无关。
function placePopover(base, panelEl, vw, vh) {
if (!base) return null
const w = (panelEl && panelEl.offsetWidth) || 380
let x = Number(base.left) || 0
if (x + w + 8 > vw) x = Math.max(8, vw - w - 8)
const h = (panelEl && panelEl.offsetHeight) || 440
// 默认向上弹出(面板底边 = 触发元素顶边 - 8);上方放不下再向下翻
let y = (Number(base.top) || 0) - h - 8
if (y < 8) {
const down = (Number(base.bottom) || 0) + 8
y = (down + h + 8 <= vh) ? down : Math.max(8, vh - h - 8)
}
return { x, y }
}
// 通用选择气泡(服务商 / 分组 / 模型 共用):触发器在节点内,气泡 portal 到 body。
// 与 ImageSettingsPanel 共用 placePopover 定位(默认向上、横向钳位),样式同为一套 popover 面板。
// 不加搜索框(用户第四轮明确);点选项即选中并关闭;点面板外 / Esc 关闭。
// ---- v3.87.6 崩溃可观测性:错误边界 + 规模估算 ----
// 渲染期异常不再整页白屏:顶层(scope=app)给整页兜底;节点级(compact)只坏一个节点,画布继续可用。
// 说明:renderBody 原本只有同步 try/catch,兜不住子组件(GenParams / ImageSettingsPanel / PickerBubble 等)的渲染异常。
class WErrorBoundary extends React.Component {
constructor(props) { super(props); this.state = { error: null }; this.retry = this.retry.bind(this) }
static getDerivedStateFromError(error) { return { error } }
componentDidCatch(error, info) {
try {
if (CrashLog && typeof CrashLog.record === 'function') CrashLog.record('boundary', {
scope: 'react:' + String((this.props && this.props.scope) || 'unknown'),
nodeId: (this.props && this.props.nodeId) || '',
message: (error && error.message) || String(error),
stack: (error && error.stack) || '',
version: APP_VERSION,
extra: { componentStack: String((info && info.componentStack) || '').slice(0, 800) },
})
} catch (e) { /* 记录失败不影响兜底 UI */ }
}
retry() { this.setState({ error: null }) }
render() {
if (!this.state.error) return this.props.children
const msg = String((this.state.error && this.state.error.message) || this.state.error || '未知错误')
if (this.props && this.props.compact) {
return el('div', { className: 'iwb-node-body iwb-err', title: msg },
'渲染错误:' + msg,
el('button', { className: 'iwb-btn iwb-btn-sm iwb-crash-retry', onClick: this.retry }, '重试渲染'),
)
}
return el('div', { className: 'iwb-crash-screen' },
el('div', { className: 'iwb-crash-card' },
el('div', { className: 'iwb-crash-title' }, '界面出错了(已自动记录,可尝试恢复)'),
el('div', { className: 'iwb-crash-msg' }, msg),
el('div', { className: 'iwb-crash-actions' },
el('button', { className: 'iwb-btn iwb-btn-primary', onClick: this.retry }, '尝试恢复'),
el('button', { className: 'iwb-btn', onClick: () => { try { location.reload() } catch (e) { /* ignore */ } } }, '重新加载页面'),
el('button', { className: 'iwb-btn', title: '复制错误记录与内存采样(不含 Key、提示词和图片)', onClick: (ev) => { let t = '{}'; try { const rep = CrashLog ? CrashLog.report({ version: APP_VERSION }) : {}; try { rep.storageSelfCheck = wStorageSelfCheck() } catch (e) { rep.storageSelfCheck = { error: String((e && e.message) || e) } } t = JSON.stringify(rep, null, 2) } catch (e) { /* ignore */ } const cp = (typeof window !== 'undefined' && window.IWBClipboardCopy) || null; if (cp) cp.copyWithButton(t, ev && ev.currentTarget) } }, '复制诊断信息'),
),
el('div', { className: 'iwb-hint' }, '完整记录在「设置 → 诊断」里,可导出 JSON'),
),
)
}
}
// ── v3.87.7 显示层缩略图:画布上只解码小图,原图只在放大/导出/备份时读 ──
// 只对**本地已有数据**(base64/dataURL)生成小图(同源,无 CORS 风险);远程 URL 原样返回
// (跨域图无法安全缩放,浏览器也会因 canvas 污染拒绝 toDataURL)。
// 首帧仍用原图(不会闪空图),小图就绪后由 wThumbBump 触发一次 re-render 换成小图。
// v3.26.118(内存优先,用户裁定):640 → 512。
// 画布节点宽 320,按 dpr=2 需要 640;但实测 fit 视图下只需 ~160 设备像素,640 是 4 倍过采样。
// 128 张图时解码位图 200MB → 128MB(每张 1.6MB → 1.05MB)。放大超过 2× 仍由 ORIG_HARD_CAP 切原图,不会更糊。
const DISPLAY_THUMB_MAX = 512
const DISPLAY_THUMB_CACHE_MAX = 300
const displayThumbs = new Map()
const displayThumbPending = new Set()
// v3.26.121:LOD 小档(256)。只进内存、不落盘(落盘会与 512 档共用同一文件名而互相覆盖)。
const DISPLAY_THUMB_SMALL = 256
const DISPLAY_THUMB_SMALL_CACHE_MAX = 200
const displayThumbsSm = new Map()
const displayThumbSmPending = new Set()
let wThumbBump = null
// v3.26.121:整棵进程树 RSS(MB),由 Workbench 的 4s 轮询写入;0 = 未知(浏览器环境没有这个能力)
let wProcRssMB = 0
// v3.87.49(丙方案 C6):cacheURL 约 45 字符、短远端 URL 也常 <64 ⇒ 此前一律跳过缩略 ✗。
// 现改为:长串用"长度+首尾采样"当 key;短的 cacheURL/http URL 直接用整串当 key;其余短串(小图/空)跳过。
function wDisplayThumbKey(v) {
if (typeof v !== 'string' || !v) return ''
if (v.length > 64) return v.length + '|' + v.slice(0, 24) + '|' + v.slice(-24)
if (v.indexOf('/__iwb_cache__/') >= 0 || /^https?:/i.test(v) || v.indexOf('blob:') === 0) return v
return ''
}
// ── v3.25.73:缩略图 key / 按需切原图 / 入库预热(逻辑在 src/image-thumb-pick.js)──
// 说明见模块头:引用图用 ref:<b:sha|c:key> 作稳定 key(跨会话命中),
// 并按「屏幕需要的像素」决定用缩略图还是原图(参考 infinite-canvas 的 pickImageSource)。
const ThumbPick = (function () {
const M = (typeof window !== 'undefined') ? window.IWBImageThumbPick : null
if (!M || typeof M.create !== 'function') return null
try {
return M.create({
cache: displayThumbs,
max: DISPLAY_THUMB_MAX,
smallCache: displayThumbsSm,
smallMax: DISPLAY_THUMB_SMALL,
smallQueue: (key, v) => { if (ThumbGenSm) ThumbGenSm.queue(key, v) },
refKeyOf: wImgRefKey,
refByUrl: wImgRefByUrl,
rawKeyOf: wDisplayThumbKey,
resolveImg: wResolveImg,
queue: (key, v) => { if (ThumbGen) ThumbGen.queue(key, v) },
})
} catch (e) { return null }
})()
let wScaleNow = 1
function wSetScaleNow (v) { const n = Number(v); if (Number.isFinite(n) && n > 0) wScaleNow = n }
function wDisplayThumbKeyOf (v) { return ThumbPick ? ThumbPick.keyOf(v) : '' }
function wImgSrcForNode (v, renderedLongEdge) { return ThumbPick ? ThumbPick.srcForNode(v, renderedLongEdge, wScaleNow) : ((v && typeof v === 'object') ? (wResolveImg(v) || '') : String(v || '')) }
function wPrimeDisplayThumbForRef (ref, dataUrl) { return ThumbPick ? ThumbPick.prime(ref, dataUrl) : false }
// v3.25.80:旧的「1024 预览派生」已并入 768 显示缩略图(两套解码=两份内存)。
// 保留同名入口做直通,调用点不改;真正的缩略由 image-display-thumb + ThumbPick 负责。
function wPreviewUrlOf (v) { return v }
function wPreviewRevokeAll () { /* 直通后没有独立 objectURL 需要回收 */ }
// 显示缩略图落盘(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
}
// 缩略图生成队列已抽到 src/image-display-thumb.js(并发上限 + 空闲启动),下面装配。
function wSaveDisplayThumb (key, payload) {
const F = wStoreMod()
if (!F || !key || !payload) return
if (displayThumbSaved.has(key) || displayThumbSaved.size > 2000) return
displayThumbSaved.add(key)
wSha256(String(key)).then(function (hex) {
const h = hex.slice(0, 16)
try {
// v3.25.73:Blob(WebP)走二进制写盘;老路径的 dataURL 仍兼容
if (typeof Blob !== 'undefined' && payload instanceof Blob) {
if (typeof F.writeDisplayThumbBlob === 'function') F.writeDisplayThumbBlob(h, payload)
} else if (typeof F.writeDisplayThumb === 'function') {
F.writeDisplayThumb(h, payload)
}
} catch (e) { /* ignore */ }
}).catch(function () { /* ignore */ })
}
async function wPreloadDisplayThumbs (nodes) {
const F = wStoreMod()
if (!F || !Array.isArray(nodes) || !nodes.length) return 0
const jobs = [], seen = new Set()
for (const n of nodes) {
const d = n && n.data
if (!d) continue
const stable = wDisplayThumbKeyOf(d.data)
const v = wResolveImg(d.data) || wResolveImg(d.url)
if (!v || typeof v !== 'string' || v.indexOf('data:') === 0) continue
const key = stable || wDisplayThumbKey(v)
if (!key || displayThumbs.has(key) || seen.has(key)) continue
seen.add(key)
jobs.push({ key: key, v: v })
if (jobs.length >= DISPLAY_THUMB_HASH_MAX) break
}
let n = 0
for (const job of jobs) {
const key = job.key
try {
const hex = await wSha256(String(key))
const h16 = hex.slice(0, 16)
let url = ''
if (typeof F.readDisplayThumbUrl === 'function') {
try { url = await F.readDisplayThumbUrl(h16) } catch (e) { url = '' }
}
if (!url) url = await F.readDisplayThumb(h16)
if (url) { displayThumbs.set(key, url); displayThumbSaved.add(key); n++ }
else if (typeof wImgSrcForNode === 'function') {
try { wImgSrcForNode(job.v, 320) } catch (e) { /* 排队生成(v3.26.111:补齐磁盘缺失的缩略图) */ }
}
} catch (e) { /* 单张失败忽略 */ }
}
if (n && typeof wThumbBump === 'function') { try { wThumbBump() } catch (e) { /* ignore */ } }
return n
}
// 缩略图队列(v3.25.67):并发上限 + 空闲启动,逻辑在 src/image-display-thumb.js
// v3.26.134:图库缩略图空闲预热的进度(模块级,诊断与组件共用)
const wPrewarmState = { busy: false, done: 0, total: 0, forN: -1 }
// v3.26.126:诊断页的"明细"一次取齐(分进程 footprint + 解码账本 + 缩略图磁盘)
async function wDiagDetail () {
const out = { breakdown: null, decode: null, thumbs: null }
try {
const T = (typeof window !== 'undefined') ? window.__TAURI__ : null
const inv = T && T.core && T.core.invoke
if (typeof inv === 'function') out.breakdown = await inv('app_memory_breakdown').catch(() => null)
} catch (e) { /* ignore */ }
try {
const F = wStoreMod()
out.decode = (F && typeof F.decodeStats === 'function') ? F.decodeStats() : null
out.thumbs = (F && typeof F.thumbStats === 'function') ? await F.thumbStats() : null
// v3.26.129:插件源读数 —— 加载器到底读的哪个目录、拿到什么版本、有没有报错
const pi = { dir: (F && typeof F.dir === 'function') ? F.dir() : '', n: 0, dirs: 0, list: '', err: '' }
try {
if (F && F.plugins && typeof F.plugins.manifest === 'function') {
const m = await F.plugins.manifest()
const arr = Array.isArray(m) ? m : []
pi.n = arr.length
pi.list = arr.map((e) => String((e && e.id) || '?') + '@' + String((e && e.version) || '?')).join(' ')
}
if (F && F.plugins && typeof F.plugins.listDirs === 'function') {
const ds = await F.plugins.listDirs()
pi.dirs = Array.isArray(ds) ? ds.length : 0
}
} catch (e2) { pi.err = String((e2 && e2.message) || e2) }
out.plugins = pi
out.gallery = (wGallerySync && typeof wGallerySync.thumbStats === 'function') ? wGallerySync.thumbStats() : null
out.prewarm = { busy: !!wPrewarmState.busy, done: wPrewarmState.done, total: wPrewarmState.total }
} catch (e) { /* ignore */ }
return out
}
// ── v3.26.124 图片策略 v2:L0 thumb / L1 preview / L2 original ──
// 目的:把所有"取整幅原图再自己缩放"的路径收回到宿主,统一走原生 tier。
function wRefPartsOf (v) {
if (!v || typeof v !== 'object') return null
if (typeof v.__blob === 'string' && v.__blob) return { kind: 'blob', key: v.__blob }
if (typeof v.__file === 'string' && v.__file) return { kind: 'file', key: v.__file }
return null
}
// 确保存在指定长边的 tier,返回 { url, h16, max }
async function wEnsureTier (v, max) {
try {
const F = wStoreMod()
if (!F || typeof F.makeDisplayThumb !== 'function') return null
const p = wRefPartsOf(v)
if (!p) return null
const m = Math.max(64, Number(max) || 320)
const refKey = 'ref:' + (p.kind === 'blob' ? 'b:' : 'f:') + p.key
const h16 = String(await wSha256(refKey)).slice(0, 16)
const r = p.kind === 'blob'
? await F.makeDisplayThumb(h16, p.key, m)
: (typeof F.makeDisplayThumbFromPath === 'function' ? await F.makeDisplayThumbFromPath(h16, p.key, m) : null)
if (!r || !r.url) return null
return { url: r.url, h16: h16, max: m }
} catch (e) { return null }
}
// L0:小图 URL(网格/卡片/封面)
async function wPluginThumb (v, opts) {
const max = Math.max(64, Number(opts && opts.max) || 320)
try {
if (typeof v === 'string') {
if (/^https?:/i.test(v)) return v
const F = wStoreMod()
if (F && typeof F.resizeDataUrl === 'function' && v.indexOf('data:') === 0 && v.length > 200 * 1024) {
const small = await F.resizeDataUrl(v, max)
if (small) return small
}
return v
}
const t = await wEnsureTier(v, max)
return (t && t.url) || ''
} catch (e) { return '' }
}
// L1:预览(dataURL,封顶 max 长边);拿不到就退回原图,保证功能不降级
async function wPluginPreview (v, opts) {
const max = Math.max(256, Number(opts && opts.max) || 2048)
try {
if (typeof v === 'string') {
const F0 = wStoreMod()
if (F0 && typeof F0.resizeDataUrl === 'function' && v.indexOf('data:') === 0) {
const small = await F0.resizeDataUrl(v, max)
if (small) return { ok: true, dataUrl: small, max: max }
}
return { ok: !!v, dataUrl: v, max: 0 }
}
const t = await wEnsureTier(v, max)
const F = wStoreMod()
if (t && F && typeof F.readDisplayThumb === 'function') {
const d = await F.readDisplayThumb(t.h16, max)
if (d) return { ok: true, dataUrl: d, max: max }
}
const raw = await wImgRefDataUrl(v)
return { ok: !!raw, dataUrl: raw || '', max: 0 }
} catch (e) { return { ok: false, dataUrl: '', max: 0 } }
}
// L2:原图(显式、单张)
async function wPluginOriginal (v) {
try {
const d = await wImgRefDataUrl(v)
return { ok: !!d, dataUrl: d || '' }
} catch (e) { return { ok: false, dataUrl: '' } }
}
function wPluginDecodeBudget () {
try { const F = wStoreMod(); return (F && typeof F.decodeStats === 'function') ? F.decodeStats() : { active: 0, peak: 0, total: 0 } } catch (e) { return { active: 0, peak: 0, total: 0 } }
}
// 给"只拿到 dataURL"的调用方用:原生缩一档(避免 WebKit 整幅解码)
async function wShrinkDataUrl (dataUrl, max) {
try {
const F = wStoreMod()
if (F && typeof F.resizeDataUrl === 'function') return await F.resizeDataUrl(dataUrl, max)
} catch (e) { /* ignore */ }
return ''
}
// v3.26.123:原生缩略图入口(桌面端)。key 形如 ref:b:<blobKey> ⇒ 让 Rust 按目标尺寸
// 解码/缩放/编码,返回 objectURL;失败返回 ''(调用方退回 JS 解码路径)。
function wNativeThumb (key, max) {
const F = wStoreMod()
if (!F || typeof F.makeDisplayThumb !== 'function') return Promise.resolve('')
const m = /^ref:b:(.+)$/.exec(String(key || ''))
if (!m) return Promise.resolve('')
return Promise.resolve(wSha256(String(key)))
.then((hex) => F.makeDisplayThumb(String(hex).slice(0, 16), m[1], max))
.then((r) => (r && r.url) || '')
.catch(() => '')
}
const ThumbGen = (function () {
const M = (typeof window !== 'undefined') ? window.IWBImageDisplayThumb : null
if (!M || typeof M.create !== 'function') return null
try {
return M.create({
max: DISPLAY_THUMB_MAX,
cacheMax: DISPLAY_THUMB_CACHE_MAX,
nativeThumb: wNativeThumb,
cache: displayThumbs,
pending: displayThumbPending,
concurrency: 2, // v3.26.118:4 → 2。每次「图库进一张图」的解码尖峰减半(用户实测:一进图就冒一下)
save: (key, url) => wSaveDisplayThumb(key, url),
bump: () => { try { if (typeof wThumbBump === 'function') wThumbBump() } catch (e) { /* ignore */ } },
isTransient: (v) => /\/__iwb_cache__\//.test(String(v)),
})
} catch (e) { return null }
})()
// v3.26.121:小档缩略图队列(256,纯内存)。命中率靠 fit 视图常驻,落盘只给 512 档。
const ThumbGenSm = (function () {
const M = (typeof window !== 'undefined') ? window.IWBImageDisplayThumb : null
if (!M || typeof M.create !== 'function') return null
try {
return M.create({
max: DISPLAY_THUMB_SMALL,
cacheMax: DISPLAY_THUMB_SMALL_CACHE_MAX,
nativeThumb: wNativeThumb,
cache: displayThumbsSm,
pending: displayThumbSmPending,
concurrency: 2,
bump: () => { try { if (typeof wThumbBump === 'function') wThumbBump() } catch (e) { /* ignore */ } },
isTransient: (v) => /\/__iwb_cache__\//.test(String(v)),
})
} catch (e) { return null }
})()
function wDisplayThumbOf(v) {
// C3:结果项 / 图片节点的 data 可能是引用对象(hydrate 直出)→ 先解析成显示 URL
const stableKey = wDisplayThumbKeyOf(v)
if (v && typeof v === 'object') v = wResolveImg(v)
// v3.24.64:SVG 直接透传原地址(<img> 原生渲染矢量,绝不 innerHTML 内联脚本)。
// 既省掉必失败的跨域代理解码,也避免把矢量压成 ≤768 的 JPEG(小字/线条发糊)。
if (ImageFormat && ImageFormat.isSvg && ImageFormat.isSvg(v)) return v
const key = stableKey || wDisplayThumbKey(v)
// v3.87.62(丙方案§13③):空值返回 null(React 省略属性),避免 <img src=""> 空请求 ✗
if (!key) return (v === '' || v === null || v === undefined) ? null : v
const hit = displayThumbs.get(key) || displayThumbsSm.get(key)
if (hit) return hit
if (ThumbGen) ThumbGen.queue(key, v)
return (typeof v === 'string' && v.indexOf('data:') === 0 && v.length > 524288) ? null : v // 超大 dataURL 绝不进 src(图库宫格 111 张原图 = 260MB,v3.26.113)
}
// 估算"当前进程里的图片字节数":只读字符串长度,不复制数据(内存采样用)
function wEstimateImageBytes(nodes) {
let total = 0
const add = (v) => {
if (!v) return
if (typeof v === 'string') { if (v.length > 3000 || v.indexOf('data:') === 0) total += v.length; return }
if (Array.isArray(v)) { for (const x of v) add(x); return }
if (typeof v === 'object') { add(v.data); add(v.url); add(v.thumb); add(v.result); add(v.results) }
}
for (const n of (nodes || [])) { const d = n && n.data; if (!d) continue; add(d.data); add(d.url); add(d.result) }
return total
}
// v3.87.18 内存构成探针:把"能测到的结构"逐个量成 MB,用于定位"堆 GB 级 vs 统计只有几十 MB"的缺口。
function wStrBytesOf(v, budget) {
let n = 0
const limit = budget || 40 * 1048576
const scan = (x) => {
if (n > limit) return
if (typeof x === 'string') { n += x.length; return }
if (Array.isArray(x)) { for (const y of x) { if (n > limit) return; scan(y) } return }
if (x && typeof x === 'object') { for (const k in x) { if (n > limit) return; scan(x[k]) } }
}
scan(v)
return n
}
const wMB = (n) => Math.round((Number(n) || 0) / 104857.6) / 10
// v3.26.117:把「哪几个节点在内存里抱着大字符串」直接点名。
// 背景:画板对象 42.5MB 而 wEstimateImageBytes 只认 10.5MB ⇒ 同一份大图在节点数据里被多处持有;
// 没有节点级明细只能靠猜。这里只统计长度、不复制字符串(15s 采一次,开销可忽略)。
function wNodeStringStats(nodes, maxN) {
const rows = []
const walk = (v, path, acc) => {
if (v === null || v === undefined) return
if (typeof v === 'string') { acc.sum += v.length; if (v.length > acc.max) { acc.max = v.length; acc.path = path } ; return }
if (Array.isArray(v)) { for (let i = 0; i < v.length && i < 500; i++) walk(v[i], path + '[' + i + ']', acc); return }
if (typeof v === 'object') { for (const k in v) walk(v[k], path ? (path + '.' + k) : k, acc) }
}
for (const n of (nodes || [])) {
const acc = { sum: 0, max: 0, path: '' }
walk(n && n.data, 'data', acc)
if (acc.sum >= 200 * 1024) rows.push({ id: String((n && n.id) || '?'), type: String((n && n.type) || '?'), kb: Math.round(acc.sum / 1024), big: Math.round(acc.max / 1024), path: acc.path || '' })
}
rows.sort((a, b) => b.kb - a.kb)
return rows.slice(0, Math.max(1, Number(maxN) || 3)).map((r) => r.id + '|' + r.type + '|' + r.kb + 'KB|' + r.path + '|' + r.big + 'KB')
}
function wMemoryComposition(refs) {
const out = {}
// v3.87.21:原来 40MB 上限会把真相截断(实测一直显示 41.4 = 刚好撞上限)→ 提到 2GB;
// 并列出"占地最大的 3 块画板",直接看是不是画板在内存里抱着大图。
try {
out.boardsMB = wMB(wStrBytesOf((refs && refs.workspaces) || [], 2048 * 1048576))
const list = ((refs && refs.workspaces) || []).map((w) => ({ id: (w && w.id) || '?', mb: wMB(wStrBytesOf([w], 2048 * 1048576)) }))
list.sort((a, b) => b.mb - a.mb)
out.topBoards = list.slice(0, 3).map((x) => x.id.slice(-8) + ':' + x.mb + 'MB')
out.hydrated = list.filter((x) => x.mb > 3).length
} catch (e) { out.boardsMB = -1 }
// v3.26.117:活动画板的节点级明细(点名谁抱着大字符串)+ 图片字节缓存口径
try { out.nodeBigSamples = wNodeStringStats((refs && refs.nodes) || [], 3).join(' ; ') } catch (e) { out.nodeBigSamples = '' }
try { const S = wImageBlobStore(); const st = S && typeof S.stats === 'function' ? S.stats() : null; out.blobCacheN = st ? st.blobCacheSize : -1; out.blobCacheMB = st ? wMB(st.blobCacheBytes) : -1; out.blobCacheMaxMB = st ? wMB(st.blobCacheByteMax) : -1 } catch (e) { out.blobCacheMB = -1 }
try { out.objUrls = wImgUrlByRef.size; out.blobRefN = wBlobRefCache.size } catch (e) { out.objUrls = -1 }
// v3.26.119:本会话读不出来的旧 {__cache} 引用数(桌面端无 SW 直出 ⇒ 这些图会一直显示占位)
try { out.deadRefs = (typeof window !== 'undefined' && window.IWBImageCacheMigrate && typeof window.IWBImageCacheMigrate.failedCount === 'function') ? window.IWBImageCacheMigrate.failedCount() : 0 } catch (e) { out.deadRefs = -1 }
try { const h = (refs && refs.history) || {}; const st = h.stack || []; out.historyMB = wMB(wStrBytesOf(st, 2048 * 1048576)); out.historyDepth = st.length } catch (e) { out.historyMB = -1 }
try { out.tasksMB = wMB(wStrBytesOf((refs && refs.tasks) || [])) } catch (e) { out.tasksMB = -1 }
try { out.genRuns = refs && refs.genRuns ? refs.genRuns.size : 0; out.genRunsMB = wMB(wStrBytesOf(refs && refs.genRuns ? Array.from(refs.genRuns.values()) : [])) } catch (e) { out.genRunsMB = -1 }
try { out.thumbsMB = wMB(wStrBytesOf(Array.from(outThumbCache.values()))) } catch (e) { out.thumbsMB = -1 }
// 计数(objectURL 只有几十字符,按字符串量永远是 0 —— 这两行才是缓存的真实规模)
try { out.galleryThumbN = outThumbCache.size } catch (e) { out.galleryThumbN = -1 }
try { out.displayThumbsN = displayThumbs.size } catch (e) { out.displayThumbsN = -1 }
try { out.smThumbsN = displayThumbsSm.size } catch (e) { out.smThumbsN = -1 }
// v3.26.121:整棵进程树 RSS 真值(MB)。0 = 非桌面端或还没采到。
try { out.procRssMB = wProcRssMB } catch (e) { out.procRssMB = 0 }
// v3.26.111:DOM 里 <img> 的来源分布 —— data: 说明图片被内联成 base64 常驻(最贵),blob: 才是正常态
// v3.26.119:解码位图按每张 <img> 的 min(自然尺寸, 渲染尺寸×dpr) 统计。
// 原来一律按 512 缩略图估(低报),改成自然尺寸又会对 2016×2688 的远程原图高报 10 倍。
try {
let dn = 0, bn = 0, db = 0, big = 0, mx = 0, bmp = 0, bmpN = 0
const dprNow = (typeof devicePixelRatio === 'number' && devicePixelRatio > 0) ? devicePixelRatio : 1
const smp = []
const ims = (typeof document !== 'undefined' && document.images) ? document.images : []
for (let i = 0; i < ims.length; i++) {
const el = ims[i]
const u = String(el.currentSrc || el.src || '')
if (u.length > mx) mx = u.length
if (u.indexOf('data:') === 0) { dn++; db += u.length; if (u.length > 500000) { big++; if (smp.length < 3) { const h = el.closest && el.closest('[data-node-id]'); smp.push(((h && h.getAttribute('data-node-id')) || '?') + '|' + Math.round(u.length / 1024) + 'KB|' + String(el.className || '').slice(0, 14)) } } } else if (u.indexOf('blob:') === 0) bn++
// 解码尺寸取 min(图片自然尺寸, 屏幕渲染尺寸×dpr):Chromium 对大图会按显示尺寸解码,
// 直接用 naturalWidth 会把 100 张 2016×2688 的图算成 2GB(高报 10 倍),反过来只按缩略图算又会低报。
const nw = Number(el.naturalWidth) || 0, nh = Number(el.naturalHeight) || 0
const rw = Number(el.clientWidth) || 0, rh = Number(el.clientHeight) || 0
if (nw > 0 && nh > 0) {
const dw = rw > 0 ? Math.min(nw, Math.round(rw * dprNow)) : nw
const dh = rh > 0 ? Math.min(nh, Math.round(rh * dprNow)) : nh
bmp += dw * dh * 4; bmpN++
}
}
out.imgDataN = dn; out.imgBlobN = bn; out.imgDataMB = wMB(db); out.imgBigN = big; out.imgMaxKB = Math.round(mx / 1024); out.imgBigSample = smp.join(' ; ')
out.bmpMB = wMB(bmp); out.bmpN = bmpN
} catch (e) { out.imgDataN = -1 }
try { out.displayThumbsMB = wMB(wStrBytesOf(Array.from(displayThumbs.values()))) } catch (e) { out.displayThumbsMB = -1 }
try { out.groupsMB = wMB(wStrBytesOf(((refs && refs.groupSnapshots) || (refs && refs.savedGroups)) || [])) } catch (e) { out.groupsMB = -1 }
try { out.clipboardMB = wMB(wStrBytesOf(lsRawGet('iwb_clipboard', '') || '')) } catch (e) { out.clipboardMB = -1 }
try { out.domImgs = (typeof document !== 'undefined' && document.images) ? document.images.length : 0 } catch (e) { out.domImgs = -1 }
// v3.26.127:DOM 规模。面板开着时元素数会成倍增长,而 WebKit malloc 与它强相关
//(实测主窗口 WebKit malloc 348MB,节点只有 29 个 ⇒ 大头在插件面板的 DOM)。
try {
out.domEls = (typeof document !== 'undefined' && document.getElementsByTagName) ? document.getElementsByTagName('*').length : -1
out.dockEls = (typeof document !== 'undefined' && document.querySelectorAll) ? document.querySelectorAll('.iwb-dock *').length : -1
out.cardEls = (typeof document !== 'undefined' && document.querySelectorAll) ? document.querySelectorAll('.iwb-history-item').length : -1
} catch (e) { out.domEls = -1 }
// v3.26.118:估算「整个渲染进程大概占多少」—— 任务管理器里那个数字的对齐口径。
// = JS 堆 + 图片字节缓存(Blob 后备存储) + 解码位图(按每张 <img> 的自然尺寸,v3.26.119 起)。
// 护栏用它而不是只用 JS 堆:106 张图时堆只有 20MB,位图却有 200MB+,只看堆等于看不见。
try {
const heapNow = (typeof performance !== 'undefined' && performance.memory) ? (Number(performance.memory.usedJSHeapSize) || 0) / 1048576 : 0
const blobNow = (out.blobCacheMB > 0) ? out.blobCacheMB : 0
const bmpNow = (out.bmpMB > 0) ? out.bmpMB : ((out.domImgs > 0) ? (out.domImgs * DISPLAY_THUMB_MAX * DISPLAY_THUMB_MAX * 4) / 1048576 : 0)
out.procEstMB = Math.round(heapNow + blobNow + bmpNow)
} catch (e) { out.procEstMB = -1 }
return out
}
function wDiagStats(nodes, boards) {
return {
nodes: (nodes || []).length,
boards: (boards || []).filter((w) => w && !w.deleted).length,
images: (typeof document !== 'undefined' && document.images) ? document.images.length : 0,
base64Bytes: wEstimateImageBytes(nodes),
}
}
// e2e 专用:验证错误边界(只有显式设置 window.__IWB_E2E_BOOM__ 时才抛;生产环境永不设置)
function E2EBoomProbe() {
if (typeof window !== 'undefined' && window.__IWB_E2E_BOOM__) throw new Error('e2e boundary boom')
return null
}
// ── v3.87.11 局部化文本输入 ──
// 问题:提示词 textarea 是受控输入,每个字符都 onUpdate → 更新全局 store → 整棵界面重渲染
// (用户实测 46 节点画布打字明显卡顿)。改法:打字只更新组件内部 state,
// **静止 350ms 或失焦**才写回 store;外部值变化(撤销/重做/切画板/程序化写入)时同步回来。
const LocalTextField = React.memo(function LocalTextField(props) {
const toStr = (v) => (v === undefined || v === null) ? '' : String(v)
const [local, setLocal] = React.useState(toStr(props.value))
const committed = React.useRef(toStr(props.value))
const latest = React.useRef(toStr(props.value))
const timer = React.useRef(null)
React.useEffect(() => {
const v = toStr(props.value)
// 只在"外部值 ≠ 我们上次提交的值"时同步(避免打字过程中被自己的写回覆盖/抢焦点)
if (v !== committed.current) { committed.current = v; latest.current = v; setLocal(v) }
}, [props.value])
React.useEffect(() => () => { if (timer.current) clearTimeout(timer.current) }, [])
const commit = (v) => {
if (v === committed.current) return
committed.current = v
try { if (typeof props.onCommit === 'function') props.onCommit(v) } catch (e) { /* ignore */ }
}
const onChange = (e) => {
const v = e.target.value
latest.current = v
setLocal(v) // 只动本地 state(不碰全局 store)
if (typeof props.onInput === 'function') { try { props.onInput(e) } catch (err) { /* ignore */ } }
if (timer.current) clearTimeout(timer.current)
timer.current = setTimeout(() => { timer.current = null; commit(latest.current) }, 350)
}
const onBlur = (e) => {
if (timer.current) { clearTimeout(timer.current); timer.current = null }
commit(latest.current) // 失焦一定落定
if (typeof props.onBlur === 'function') props.onBlur(e)
}
const common = {
className: props.className,
placeholder: props.placeholder,
readOnly: props.readOnly,
value: local,
onChange,
onBlur,
onFocus: props.onFocus,
onPointerDown: props.onPointerDown,
onKeyDown: props.onKeyDown,
spellCheck: props.spellCheck,
ref: (el0) => { if (el0 && typeof props.refEl === 'function') props.refEl(el0) },
}
return props.textarea ? el('textarea', common, null) : el('input', Object.assign({ type: props.type || 'text' }, common, null), null)
})
// 图像设置浮层(方案 A):质量 / 尺寸(W↔H + 16 倍数对齐) / 分辨率 / 宽高比网格。
// 复用 app 既有的 iwb-modal 体系(遮罩 + 居中 + 头部关闭),保证与其它弹窗观感一致;
// 节点内的服务商/分组/模型为自绘气泡触发器(v3.86.7 起不再用原生 select)。
const ImageSettingsPanel = React.memo(function ImageSettingsPanel(props) {
const { nodeId, data, config, onUpdate, onClose, anchor } = props
const d = data || {}
const stop = (e) => e.stopPropagation()
// 贴节点浮出的定位(方案 A 改为 popover 形态):定位逻辑抽到模块级 placePopover,
// 与 PickerBubble 共用(默认向上、横向钳位、上方不足向下翻),避免两份实现漂移。
// 定位用 viewport 坐标(fixed),与画布缩放/平移无关。
const panelRef = React.useRef(null)
const [pos, setPos] = React.useState(null) // null = 未定位:先隐藏,避免首帧在左上角闪一下
React.useLayoutEffect(() => { // layout effect:浏览器绘制前定位,用户看不到中间态
if (!anchor) return
const place = () => {
// 优先以「节点本身」为锚点:比触发按钮更稳定(按钮可能因换行/溢出而位置出人意料)。
const p = placePopover(anchor, panelRef.current, window.innerWidth, window.innerHeight)
if (p) setPos(p)
}
place()
window.addEventListener('resize', place)
return () => window.removeEventListener('resize', place)
}, [anchor])
// 点面板外关闭(用捕获阶段 pointerdown)。触发按钮本身排除,否则会「先关后开」看起来没反应。
React.useEffect(() => {
const onDown = (e) => {
const el0 = panelRef.current
const t = e.target
if (el0 && t && el0.contains(t)) return
if (t && t.closest && t.closest('.iwb-gen-summary')) return
onClose()
}
document.addEventListener('pointerdown', onDown, true)
return () => document.removeEventListener('pointerdown', onDown, true)
}, [onClose])
const ratioPresets = (config && config.canvas && Array.isArray(config.canvas.sizePresets) && config.canvas.sizePresets.length) ? config.canvas.sizePresets : RATIOS
const curRatio = d.ratio || ratioOfSize(d.size) || 'auto'
const curRes = RES_MAP[d.res] || resOfSize(d.size) || '1K'
const curRatioAuto = curRatio === 'auto'
const derivedSize = standardSizeOf(d)
const dm = /^(\d+)x(\d+)$/.exec(String(derivedSize || '').trim())
const [sizeW, setSizeW] = React.useState(dm ? dm[1] : '')
const [sizeH, setSizeH] = React.useState(dm ? dm[2] : '')
React.useEffect(() => {
const m = /^(\d+)x(\d+)$/.exec(String(standardSizeOf(d) || '').trim())
if (m) { setSizeW(m[1]); setSizeH(m[2]) }
}, [derivedSize])
React.useEffect(() => {
const onKey = (e) => { if (e.key === 'Escape') { e.preventDefault(); onClose() } }
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const align16 = d.align16 === true
const isCustom = !!(d.custom && String(d.customSize || '').trim())
const customErr = isCustom ? sizeCheck(d.customSize) : null
const pxCount = (() => { const m = /^(\d+)x(\d+)$/.exec(String(d.customSize || '').trim()); return m ? Number(m[1]) * Number(m[2]) : 0 })()
// 下限只作提示(不阻止提交):本项目渠道实测支持更小的整数尺寸,硬卡下限会把原来可用的尺寸变成不可用。
const pxTiny = isCustom && !customErr && pxCount > 0 && pxCount < 655360
const commitSize = () => {
let w = Math.round(Number(sizeW) || 0)
let h = Math.round(Number(sizeH) || 0)
if (align16) { w = snap16(w); h = snap16(h) }
if (!(w > 0 && h > 0)) { const m = /^(\d+)x(\d+)$/.exec(String(standardSizeOf(d) || '').trim()); if (m) { setSizeW(m[1]); setSizeH(m[2]) } return }
const next = w + 'x' + h
if (align16) { setSizeW(String(w)); setSizeH(String(h)) }
if (isCustom && next === String(d.customSize || '')) return
onUpdate({ custom: true, customSize: next, size: next })
}
const numProps = { className: 'iwb-input iwb-set-num', type: 'number', min: 16, max: 3840, step: 16, onPointerDown: stop, onKeyDown: (e) => { if (e.key === 'Enter') { e.preventDefault(); commitSize() } }, onBlur: commitSize }
const pickRatio = (r) => {
if (r === 'auto') { onUpdate({ ratio: 'auto', size: 'auto', custom: false, customSize: '' }); return }
const sz = (ratioPresets.find((x) => x.value === r) || {}).sizes || {}
onUpdate({ ratio: r, size: sz[curRes] || sz['1K'], custom: false, customSize: '' })
}
const pickRes = (k) => {
const sz = (ratioPresets.find((x) => x.value === curRatio) || {}).sizes || {}
onUpdate({ res: k, size: sz[k] || sz['1K'], custom: false, customSize: '' })
}
const qualityNow = qualityOf(d)
// 模型能力:不支持时档位整体禁用(恒按「自动」发送),勾选入口在「设置 → 生图服务」
const qualityOk = supportsQualityOf(config, d)
const qualityRejectedHere = qualityOk && isQualityUnsupported(d.provider, d.model)
const qualityTitleOf = (lv) => {
if (lv.value === 'auto') return '不发送 quality 参数(最兼容,默认)'
if (!qualityOk) return '当前模型未标记为支持质量:不发送该参数;可在「设置 → 生图服务」里勾选启用'
if (lv.value === 'xhigh' || lv.value === 'max') return '发送 quality=' + lv.value + '(档位越高越慢、通常计费越高;部分渠道不支持会自动降级,也可能被静默忽略)'
return '发送 quality=' + lv.value
}
const chip = (key, label, active, onClick, title, disabled) => el('button', { key, type: 'button', disabled: !!disabled, title, className: 'iwb-chip iwb-chip-line' + (active ? ' iwb-chip-line-on' : ''), onClick, onPointerDown: stop }, label)
return ReactDOM.createPortal(
el('div', { className: 'iwb-pop-anchor', style: { left: (pos ? pos.x : 0) + 'px', top: (pos ? pos.y : 0) + 'px', visibility: pos ? 'visible' : 'hidden' }, onWheel: (e) => e.stopPropagation() },
el('div', { ref: panelRef, className: 'iwb-pop iwb-image-settings', onPointerDown: stop },
el('div', { className: 'iwb-pop-head' },
el('span', { className: 'iwb-pop-title' }, '图像设置'),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '关闭', onClick: onClose }, I('x')),
),
el('div', { className: 'iwb-pop-body' },
el('div', { className: 'iwb-setgroup' },
el('div', { className: 'iwb-setlabel' }, '质量'),
el('div', { className: 'iwb-setrow' }, QUALITY_LEVELS.map((lv) => chip('q-' + lv.value, lv.label, qualityOk && qualityNow === lv.value, () => onUpdate({ quality: lv.value }), qualityTitleOf(lv), lv.value !== 'auto' && !qualityOk))),
qualityOk ? null : el('div', { className: 'iwb-hint' }, '当前模型不支持质量档位(已按「自动」发送)· 可在「设置 → 生图服务」里勾选启用'),
qualityRejectedHere ? el('div', { className: 'iwb-hint' }, '该渠道拒绝了 quality 参数,已按「自动」发送;可在设置里取消勾选以免每次白试') : null,
),
el('div', { className: 'iwb-setgroup' },
el('div', { className: 'iwb-sethd' },
el('div', { className: 'iwb-setlabel' }, '尺寸'),
el('label', { className: 'iwb-check iwb-setalign', title: '开启后自定义尺寸会在失焦/回车时就近取整到 16 的倍数;内置预设尺寸本身都已是 16 的倍数,不受影响' },
'16 倍数对齐', el('input', { type: 'checkbox', checked: align16, onChange: (e) => onUpdate({ align16: e.target.checked }), onPointerDown: stop }, null))),
el('div', { className: 'iwb-setrow' },
el('input', Object.assign({}, numProps, { value: sizeW, title: '宽(手动修改即切换为自定义尺寸)', placeholder: '宽', onChange: (e) => setSizeW(e.target.value.replace(/[^0-9]/g, '')) })),
el('span', { className: 'iwb-setx' }, '↔'),
el('input', Object.assign({}, numProps, { value: sizeH, title: '高(手动修改即切换为自定义尺寸)', placeholder: '高', onChange: (e) => setSizeH(e.target.value.replace(/[^0-9]/g, '')) })),
customErr ? el('span', { className: 'iwb-seterr', title: customErr }, '尺寸无效')
: (pxTiny ? el('span', { className: 'iwb-sethint', title: '像素总量低于 655360,部分渠道可能拒绝(本项目不阻止提交)' }, '偏小')
: (isCustom ? el('span', { className: 'iwb-sethint' }, '自定义') : null)))),
el('div', { className: 'iwb-setgroup' },
el('div', { className: 'iwb-setlabel' }, '分辨率'),
el('div', { className: 'iwb-setrow' },
['1K', '2K', '4K'].map((k) => chip('r-' + k, k, !curRatioAuto && curRes === k, () => pickRes(k), '按比例预设查表得到像素尺寸', curRatioAuto)),
chip('r-auto', '自动', curRatioAuto, () => pickRatio('auto'), '不指定比例与档位,交由渠道决定'))),
el('div', { className: 'iwb-setgroup' },
el('div', { className: 'iwb-setlabel' }, '宽高比'),
el('div', { className: 'iwb-setrow' }, ratioPresets.map((r) => {
// 纯文字 chip;内置比例默认只显示比例值(不显示中文),自定义比例显示其名称
const label = r.value === 'auto' ? '自动' : presetDisplayName(r)
return chip('a-' + r.value, label, curRatio === r.value, () => pickRatio(r.value), label)
}))),
),
)),
document.body)
})
// 节点体模块的依赖注入(一次性、幂等)。
// ⚠️ 必须在**渲染节点体之前**完成 —— LOD 轻量体(IWNodeBodies.lodBody)也要用 el / wResolveImg 等,
// 而它在 renderBody 的分支里**先于** renderBodyInner 执行(v3.24.78 踩过:注入还留在 renderBodyInner 里
// ⇒ lodBody 里 `el` 是 undefined ⇒ 抛错被 || 接住 ⇒ 全部退回纯占位,等于 lite 档从未生效)。
function ensureNodeBodiesInjected() {
if (!IWNodeBodies || IWNodeBodies.__iwbInjected) return
try {
IWNodeBodies.inject({ el, I, LocalTextField, autoGrow, nodePreviewRefsV2, nodeInheritOf, combineSourcePairs, isPluginTypeId,
orderedUniqueRefNodes, uploadRefToImageHost, wDisplayThumbOf, wImgSrcForNode, wImportImage, wPreviewUrlOf, wRawCfg, wResolveImg,
wThumbSrc, downloadUrl, wResolveOutputSrc, isImageProducer, outProgUI, outThumbCache,
wPluginNodeVariants, wPluginVariantMeta, isBatchSrc, batchSrcText, compareCanvasTextOrder,
GenParams, RATIOS, RES_KEYS, RES_MAP, cachedGenerationTasks, classifyErr, fmtDur, presetDisplayName,
ratioOfSize, resOfSize, taskStallEndMs, wDedupeTaskIds, React, ReactDOM })
IWNodeBodies.__iwbInjected = true
} catch (e) { /* 注入失败:继续用内置分支 */ }
}
// ── 插件节点体的稳定容器(2026-11-14)───────────────────────────────────────
// 插件是经典脚本 IIFE(无 import/export),拿不到 React,它的 render 只能自己造 DOM。
// 所以契约特意区分:内置类型的 `render(node, props)` 返回 React 元素(vDOM),
// 插件类型的 `render(node, props, host)` 是**往 host 这个真实 DOM 里画**。
//
// 为什么必须夹这一层:直接 `return nt.render(node, props)` 的话,React 每次重渲染都看到
// 一棵全新的 DOM 树,于是把旧节点整块替换掉 —— 样式节点 24 个变量输入框里敲一个字就失焦
// (每敲一次 = 一次 onUpdate = 一次重渲染 = 一次 DOM 重建)。这里把 host 固定下来,
// React 只负责这个 div 本身,内部由插件自己增量更新。
function PluginDomBody(props) {
const hostRef = React.useRef(null)
// 无依赖数组:每次渲染后都调一次。插件拿到最新 node/props 后自己做 diff(输入框正在编辑时
// 不要覆盖 value,那是插件侧的责任),宿主不猜插件需要什么数据。
React.useEffect(() => {
const host = hostRef.current
if (!host) return
try { props.renderFn(props.node, props.inner, host) } catch (e) {
// 插件停用后旧画布仍会调用它的 render(dispose 只摘变体表,NODE_TYPES 里那条还在)。
// 渲染失败降级成一行可读文本,绝不让整块画布白屏。
try {
host.textContent = ''
const tip = document.createElement('div')
tip.className = 'iwb-hint'
tip.textContent = '插件节点渲染失败:' + String((e && e.message) || e)
host.appendChild(tip)
} catch (e2) { /* ignore */ }
}
})
// 卸载时给插件一次清理机会(它可能挂了 window/document 级监听,例如内容高度自适应)
React.useEffect(() => () => {
const host = hostRef.current
if (host && typeof props.renderFn.dispose === 'function') { try { props.renderFn.dispose(host) } catch (e) { /* ignore */ } }
}, [])
return el('div', { className: 'iwb-node-body iwb-plugin-node-body', ref: hostRef })
}
function renderBodyInner(node, props) {
// 节点体渲染已按类型搬到 src/ui-node-bodies.js(2026-10-29)。
// 依赖用 inject 注入一次(抽成 ensureNodeBodiesInjected,见其注释);注入失败则退回下面的内置分支(gen/layer 仍在 app.js)。
ensureNodeBodiesInjected()
const nt = NODE_TYPES.get(node.type)
if (nt && typeof nt.render === 'function') return el(PluginDomBody, { key: 'plugin-dom', node: node, inner: props, renderFn: nt.render })
const onUpdate = props.onUpdate
const busy = props.busy
const progress = props.progress || {}
const h = (node.h || nodeTypeH(node.type))
const stop = (e) => e.stopPropagation()
// 参考图缩略图统一渲染:有图显示图片,无图时展示等尺寸「警告」占位框,保证序号(1,2,…)与所有来源一致。
const refMini = (rn, idx) => {
const src = wThumbSrc((rn.data && (wResolveImg(rn.data.data) || rn.data.url)) || '')
return el('div', { key: rn.id, className: 'iwb-refmini' + (src ? '' : ' iwb-refmini-empty') },
el('span', { className: 'iwb-refmini-idx' }, String(idx + 1)),
src
? el('img', { className: 'iwb-task-ref', loading: 'lazy', decoding: 'async', src: wPreviewUrlOf(wDisplayThumbOf(src)), draggable: false, title: '图 ' + (idx + 1) + '(点击放大)',
// v3.87.47(丙方案):预览必须拿**原图源**(此前传显示 src,放大是糊的)
onClick: () => props.onPreview && props.onPreview((rn.data && (wResolveImg(rn.data.data) || rn.data.url)) || src) })
: el('span', { className: 'iwb-refmini-warn', title: '图片(空)', 'aria-label': '图片为空' },
el('svg', { viewBox: '0 0 24 24', width: 18, height: 18, 'aria-hidden': 'true' },
el('rect', { x: '4', y: '4', width: '16', height: '16', rx: '3', fill: 'currentColor' }),
el('path', { d: 'M12 7.2a1.1 1.1 0 0 1 1.1 1.1v4.2a1.1 1.1 0 1 1-2.2 0V8.3A1.1 1.1 0 0 1 12 7.2zM12 15.4a1.25 1.25 0 1 1 0 2.5 1.25 1.25 0 0 1 0-2.5z', fill: '#fff' }),
),
),
)
}
// 已迁到模块的分支:按下发类型分派(plugin 类型含 plugin:<id>:<variant> 形式)
if (IWNodeBodies) {
const nk = (node.type === 'plugin' || isPluginTypeId(node.type)) ? 'plugin' : node.type
const nf = IWNodeBodies[nk]
if (typeof nf === 'function') return nf(node, props, { onUpdate, busy, progress, h, stop, refMini })
}
if (node.type === 'layer') {
const d = node.data || {}
const cfg = props.config || { providers: [] }
const providers = cfg.providers || []
const curProvider = providers.find((p) => p.id === d.provider) || providers[0] || { id: '', keys: [] }
const rows = Array.isArray(d.layers) ? d.layers : []
const busyKey = node.id + '::layer'
const running = !!busy[busyKey]
const prog = progress[busyKey]
const inputs = layerInputsOf(node, props.nodes || [], props.edges || [])
const expertText = String(inputs.text || '').trim()
const promptText = expertText || buildLayerPrompt(rows)
const filledRows = rows.filter((l) => l && String(l.name || '').trim())
const szParam = layerSizeParam(d.sizeParam)
const builtinModel = String(d.model || '').toLowerCase() === BUILTIN_LAYER_MODEL.toLowerCase()
const billable = layerBillableCount(rows)
const yuan = layerEstimateYuan(rows, szParam)
const setLayers = (next) => onUpdate(node.id, { layers: next })
const rowPatch = (i, patch) => setLayers(rows.map((r, k) => (k === i ? { ...r, ...patch } : r)))
const commitName = (i, v) => { const nm = String(v || '').trim(); if (nm !== String((rows[i] && rows[i].name) || '').trim()) rowPatch(i, { name: nm }) }
const commitBbox = (i, v) => {
const t = String(v || '').trim()
if (!t) { rowPatch(i, { bbox: null }); return }
const nums = t.split(/[\s,,x×]+/).filter(Boolean).map(Number).filter((n) => Number.isFinite(n))
if (nums.length !== 4) { props.onNotice && props.onNotice('区域格式应为 x1 y1 x2 y2(4 个数字,原图像素坐标)'); return }
rowPatch(i, { bbox: nums.map((n) => Math.max(0, Math.round(n))) })
}
const addRow = () => setLayers(rows.concat([{ id: uid('L'), name: '', bbox: null }]))
const removeRow = (i) => setLayers(rows.filter((_, k) => k !== i))
const rowEls = rows.map((l, i) => el('div', { className: 'iwb-layer-row', key: l.id || ('L' + i) },
el('span', { className: 'iwb-layer-idx', title: '第 ' + (i + 1) + ' 层' }, String(i + 1)),
el('input', {
className: 'iwb-input iwb-layer-name', defaultValue: l.name || '', placeholder: '图层名称(如 文字标题层)',
title: '图层名会原样出现在返回结果的 name 字段里',
onPointerDown: stop, onBlur: (e) => commitName(i, e.target.value), onKeyDown: (e) => { if (e.key === 'Enter') e.target.blur() },
}),
el('input', {
className: 'iwb-input iwb-layer-bbox', defaultValue: l.bbox ? l.bbox.join(' ') : '', placeholder: '区域(可选) x1 y1 x2 y2',
title: '可选:限定该层的区域,格式 x1 y1 x2 y2(原图像素坐标);留空则由模型自动判断',
onPointerDown: stop, onBlur: (e) => commitBbox(i, e.target.value), onKeyDown: (e) => { if (e.key === 'Enter') e.target.blur() },
}),
el('button', { className: 'iwb-btn iwb-btn-sm iwb-layer-del', title: '删除该层', 'aria-label': '删除该层', onPointerDown: stop, onClick: () => removeRow(i) }, '×'),
))
// 结果:与生图同构的 data.result([{promptId,label,items}]),这里展平后按 z 从底到顶展示
const resultGroups = Array.isArray(d.result) ? d.result : []
const layerItems = []
for (const g of resultGroups) for (const it of (Array.isArray(g && g.items) ? g.items : [])) if (it && it.ok && it.url) layerItems.push(it)
layerItems.sort((a, b) => (Number(a.zIndex) || 0) - (Number(b.zIndex) || 0))
const resultEls = layerItems.map((it, i) => el('div', { className: 'iwb-layer-item', key: String(it.url).slice(-24) + i },
el('img', { className: 'iwb-layer-thumb', src: wPreviewUrlOf(wDisplayThumbOf(it.url)), loading: 'lazy', draggable: false, title: '点击放大:' + (it.name || ''), onClick: () => props.onPreview && props.onPreview(it.url) }),
el('div', { className: 'iwb-layer-meta' },
el('div', { className: 'iwb-layer-itemname', title: it.description || it.name || '' }, String(it.name || '图层')),
el('div', { className: 'iwb-layer-itemsub' }, 'z=' + (Number(it.zIndex) || 0) + (it.size ? (' · ' + it.size) : '') + (it.bbox ? (' · 区域 ' + it.bbox.absolute.join(',')) : '')),
),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '下载该图层', onPointerDown: stop, onClick: () => downloadUrl(it.url, String(it.name || 'layer').replace(/[\\/:*?"<>|]/g, '_') + '.png') }, '下载'),
))
return el('div', { className: 'iwb-node-body iwb-layer-body' },
// 参数行复用生图节点的同一个组件(fields 只给三项,不含尺寸汇总条):
// 宽度按内容自适应、长模型名省略号 + title 显示全名(拉宽节点即可完整显示),样式与生图节点统一。
el(GenParams, {
nodeId: node.id, data: d, config: cfg, onUpdate: (patch) => onUpdate(node.id, patch),
fields: ['provider', 'keyGroup', 'model'],
modelPool: layerModelPoolOf(curProvider),
}),
!builtinModel ? el('div', { className: 'iwb-layer-warn' }, '当前分层模型不是内置的 doubao-seedream-5-0-pro-260628:分层参数与计费方式未经实测,请自行验证') : null,
el('div', { className: 'iwb-layer-prefix', title: '固定指令前缀:统一它才能稳定拿到图层,而不是被当成普通图片编辑' }, LAYER_PROMPT_PREFIX),
el('div', { className: 'iwb-layer-rows' }, rowEls.length ? rowEls : el('div', { className: 'iwb-err' }, '请至少填写一层')),
el('div', { className: 'iwb-layer-actions' },
el('button', { className: 'iwb-btn iwb-btn-sm', title: '添加一层(每层一张图,费用线性增长)', onPointerDown: stop, onClick: addRow }, '+ 加一层'),
el('span', { className: 'iwb-layer-sub' }, '模板:'),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '海报 / 设计稿', onPointerDown: stop, onClick: () => setLayers([{ id: uid('L'), name: '背景装饰层', bbox: null }, { id: uid('L'), name: '主体视觉层', bbox: null }, { id: uid('L'), name: '文字标题层', bbox: null }]) }, '海报'),
el('button', { className: 'iwb-btn iwb-btn-sm', title: 'UI 稿', onPointerDown: stop, onClick: () => setLayers([{ id: uid('L'), name: '背景层', bbox: null }, { id: uid('L'), name: '组件层', bbox: null }, { id: uid('L'), name: '文字层', bbox: null }, { id: uid('L'), name: '图标层', bbox: null }]) }, 'UI 稿'),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '插画', onPointerDown: stop, onClick: () => setLayers([{ id: uid('L'), name: '远景背景层', bbox: null }, { id: uid('L'), name: '人物层', bbox: null }, { id: uid('L'), name: '前景装饰层', bbox: null }]) }, '插画'),
),
el('div', { className: 'iwb-layer-tier' },
LAYER_SIZE_KEYS.map((k) => el('button', {
key: k, type: 'button', onPointerDown: stop,
className: 'iwb-chip iwb-chip-line' + (szParam === k ? ' iwb-chip-line-on' : ''),
title: (k === '1K' ? '最低价档:图层约 1152×864' : '图层约 2368×1776,单价翻倍') + (builtinModel ? '' : '(该档位单价未经实测)'),
onClick: () => onUpdate(node.id, { sizeParam: k }),
}, k + (builtinModel ? (' · ' + layerPriceText(k) + '/层') : ''))),
),
builtinModel
? el('div', { className: 'iwb-layer-cost' }, '预计 ' + billable + ' 张 × ' + layerPriceText(szParam) + ' ≈ ¥' + yuan.toFixed(2) + '(含 1 张底层合成图;按实际返回张数结算)')
: el('div', { className: 'iwb-layer-cost' }, '预计 ' + billable + ' 张(含 1 张底层合成图);该模型的单价以服务商为准,未实测'),
el('div', { className: 'iwb-layer-prompt', title: promptText }, expertText ? ('提示词来自已连接的文本节点,已覆盖清单:' + promptText) : (promptText || '(请至少填写一层)')),
(!inputs.refCount && !running) ? el('div', { className: 'iwb-err' }, '请连接「图片」节点:分层需要 1 张图') : null,
inputs.refCount > 1 ? el('div', { className: 'iwb-layer-warn' }, '已连接 ' + inputs.refCount + ' 张图,分层只使用第 1 张(多传会额外计费且对分层无意义)') : null,
el('div', { className: 'iwb-layer-actions' },
el('button', { className: 'iwb-btn iwb-btn-sm iwb-layer-run', disabled: running || !filledRows.length || !inputs.refCount, title: '运行分层(按返回张数计费)', onPointerDown: stop, onClick: () => props.onRunLayer && props.onRunLayer(node.id) }, running ? '分层中…' : '运行分层'),
running ? el('span', { className: 'iwb-layer-sub' }, '正在等待图层(不会重复提交)…') : null,
),
layerItems.length ? el('div', { className: 'iwb-layer-results' },
el('div', { className: 'iwb-layer-resulttitle' }, '结果 ' + layerItems.length + ' 张(自底层向上)'),
resultEls,
) : null,
)
}
return el('div', { className: 'iwb-node-body' }, '未知节点类型')
}
function renderBody(node, props) {
// e2e 探针(仅 __IWB_E2E__):统计**完整**节点体渲染次数(LOD 轻量体不计 —— v3.24.78 起它也走 renderBody,
// 但它只是一个 div/img,把它算进"重建次数"会让探针失去"是否逐帧重建全部节点体"的原意)
if (typeof window !== 'undefined' && window.__IWB_E2E__ === true && !props.lodLow) window.__IWB_E2E_BODY_RENDERS__ = (window.__IWB_E2E_BODY_RENDERS__ || 0) + 1
let inner = null
try {
// LOD:'' / 'lite' / 'plain'(判据见 IWBCanvasGeometry.lodModeOf)。注入必须已就绪,见 ensureNodeBodiesInjected。
ensureNodeBodiesInjected()
inner = (props.lodLow && IWNodeBodies && typeof IWNodeBodies.lodBody === 'function') ? IWNodeBodies.lodBody(node, props.lodLow) : renderBodyInner(node, props)
} catch (e) {
try { if (CrashLog && typeof CrashLog.record === 'function') CrashLog.record('render-sync', { scope: 'renderBody:' + String((node && node.type) || ''), nodeId: (node && node.id) || '', message: String((e && e.message) || e), stack: (e && e.stack) || '', version: APP_VERSION }) } catch (x) { /* ignore */ }
return el('div', { className: 'iwb-node-body iwb-err' }, '渲染错误:' + String((e && e.message) || e))
}
// 子组件(参数气泡 / 图像设置浮层等)的渲染异常交给边界:只坏这个节点,画布其余部分继续可用
return el(WErrorBoundary, { scope: 'node:' + String((node && node.type) || ''), nodeId: (node && node.id) || '', compact: true }, inner)
}
// ---------- node card ----------
// NodeCard 的「粘贴按钮」曾裸用 Workbench 内的 refs.pasteOnce(模块级没有 refs)⇒ 运行期 ReferenceError。
// 用模块级单例槽复现原意:全局只保留一个待命 paste 监听,避免反复点击后一次粘贴插入多张。
const W_NODECARD_PASTE_ONCE = { once: null }
// ── 节点卡已收编到 src/ui-node-card.js(结构优化 step-5,2026-10-28)
const _nc = (typeof window !== 'undefined' && window.IWBUINodeCard) || null
if (!_nc || typeof _nc.inject !== 'function') throw new Error('[iwb][app] 模块未就绪: ui-node-card')
const NodeCard = _nc.NodeCard
// 性能:NodeCard memo 化——比较函数忽略不稳定的函数 prop(行为由 refs/setState 决定),
// 只对数据级变化触发重渲染(node/选中/测量/自身 busy·progress/连线目标/画布数据)
const EMPTY_OBJ = {}
// ── 连线几何族:已并入 src/canvas-geometry.js(P1 拆分批 3,2026-10-28)─────────────
// 迁出 areNodeEqual(NodeCard 的 memo 比较器)与 computeEdgePath(连线贝塞尔路径)。
// 该模块原有无依赖的 connectReasonOf / distToSeg 保持不变;新增的这 2 个需要注入:
// nodeTypeH / nodeWidth(节点默认高宽,读 NODE_TYPES / NODE_W 常量表 —— 表被边界守门冻结,不搬)
// isBatchSrc / batchPortTop(批量节点判定与端口定位,来自 src/canvas-text.js)
// 迁移前做过等价性验证:13 组用例(拖拽/缩放窗口放宽比较、batch 端口定位、路径缓存命中)输出完全一致。
const _wGeom = (() => {
const G = (typeof window !== 'undefined' && window.IWBCanvasGeometry) || null
if (!G || typeof G.create !== 'function') return null
try {
return G.create({ nodeTypeH, nodeWidth, isBatchSrc, batchPortTop, compareCanvasTextOrder })
} catch (e) {
// 依赖缺失属于构建/加载错误,必须显式暴露,不静默降级
try { console.error('[iwb][canvas-geometry] 初始化失败:', e && e.message) } catch (e2) {}
return null
}
})()
function _geomFn(name) {
const fn = _wGeom && _wGeom[name]
if (typeof fn !== 'function') throw new Error('[iwb][canvas-geometry] 模块未就绪: ' + name)
return fn
}
const areNodeEqual = (prev, next) => _geomFn('areNodeEqual')(prev, next)
const computeEdgePath = (ed, graph, nodeMap, measuredH, pathCache) => _geomFn('computeEdgePath')(ed, graph, nodeMap, measuredH, pathCache)
const NodeCardMemo = React.memo(NodeCard, areNodeEqual)
// ---------- 连线渲染:memo 化(借鉴参考项目 ConnectionPath)----------
// 拖动节点时只有相连的边因 src/dst 引用变化而重算,其余边跳过渲染。
const EdgePath = _mod.EdgePath
const EdgePathMemo = React.memo(EdgePath, (a, b) => a.ed === b.ed && a.src === b.src && a.dst === b.dst && a.focusNodeId === b.focusNodeId && a.selEdge === b.selEdge && a.edgeHover === b.edgeHover && ((a.src.type === 'batch' || a.dst.type === 'batch') ? (a.graph === b.graph && a.nodeMap === b.nodeMap) : true) && a.srcH === b.srcH && a.dstH === b.dstH)
// ---------- minimap(memo + 拖动定位:节点点阵用 useMemo 复用仅视口变化时重建;拖动视图用 rAF 节流保证流畅) ----------
const Minimap = _mod.Minimap
const MinimapMemo = React.memo(Minimap)
// ---------- 底栏工具栏(memo:节点拖拽时 sel/派生状态不变 → 跳过重渲;动作全部用稳定 useCallback 读 refs) ----------
// 编组 / 取消编组 / 收藏 3 个按钮已移除(编组与取消编组改由多选节点组气泡 + Ctrl+G / Ctrl+Shift+G + 命令面板提供;
// 收藏由节点组气泡提供);适应视图改为本栏最右侧独立一格的图标按钮(快捷键 Shift+F 保留,
// 「双击画布空白 = 适应视图」已移除)。
const ToolbarBottom = _mod.ToolbarBottom
const ToolbarBottomMemo = React.memo(ToolbarBottom)
// ---------- 统一居中改名/命名弹窗(复用 .iwb-rename-modal 样式;首页/画布共用) ----------
function useTextDialog() {
const [modal, setModal] = React.useState(null)
const open = (o) => setModal({ title: o.title || '重命名', value: o.value != null ? String(o.value) : '', placeholder: o.placeholder || '', okText: o.okText || '确定', onSubmit: o.onSubmit })
const close = () => setModal(null)
const setValue = (v) => setModal((m) => (m ? { ...m, value: v } : m))
return { modal, open, close, setValue }
}
function TextDialog({ modal, onChange, onClose }) {
if (!modal) return null
const submit = () => { const v = (modal.value || '').trim(); if (!v) return; const fn = modal.onSubmit; onClose(); fn && fn(v) }
return ReactDOM.createPortal(el('div', { className: 'iwb-modal-mask', onWheel: (e) => e.stopPropagation(), onPointerDown: (e) => { if (e.target === e.currentTarget) onClose() } },
el('div', { className: 'iwb-modal iwb-rename-modal' },
el('div', { className: 'iwb-modal-head' }, el('span', null, modal.title)),
el('div', { className: 'iwb-modal-body' }, el('input', { className: 'iwb-input iwb-rename-input', value: modal.value, autoFocus: true, onFocus: (e) => e.target.select(), placeholder: modal.placeholder, onChange: (e) => onChange(e.target.value), onKeyDown: (e) => { if (e.key === 'Enter') submit(); if (e.key === 'Escape') onClose() } })),
el('div', { className: 'iwb-modal-foot' },
el('button', { className: 'iwb-btn', onClick: onClose }, '取消'),
el('button', { className: 'iwb-btn iwb-btn-primary', onClick: submit }, modal.okText || '确定'),
),
),
), document.body)
}
// ---------- settings modal(v2 P3:4-Tab:生图服务 / LLM 服务 / 图片传输 / 通用) ----------
// ── 设置面板已收编到 src/ui-settings-modal.js(结构优化 step-4,2026-10-28)
const _sm = (typeof window !== 'undefined' && window.IWBUISettingsModal) || null
if (!_sm || typeof _sm.inject !== 'function') throw new Error('[iwb][app] 模块未就绪: ui-settings-modal')
const SettingsModal = _sm.SettingsModal
function dedupeBy(items, keyOf) {
const seen = new Set(); const out = []
for (const item of Array.isArray(items) ? items : []) { const key = keyOf(item); if (seen.has(key)) continue; seen.add(key); out.push(item) }
return out
}
// SHA-256(备份校验;crypto.subtle 不可用时 FNV-1a 降级)
async function wSha256(str) {
try {
if (typeof crypto !== 'undefined' && crypto.subtle && typeof TextEncoder !== 'undefined') {
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(str))
return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, '0')).join('')
}
} catch (e) { /* fallthrough */ }
let hash = 2166136261
for (let i = 0; i < str.length; i++) { hash ^= str.charCodeAt(i); hash = Math.imul(hash, 16777619) }
return 'fnv1a-' + (hash >>> 0).toString(16)
}
// ── ZIP 读写族:已独立为 src/storage-zip.js(P1 拆分批 5,2026-10-28)──────────────
// 迁出 140 行(W_ZIP_SIG_* 常量、wZipParseEntries、wZipReadEntry、wOpenZipBlob、W_CRC_TABLE、
// wCrc32Chunk、wDosDateTime、wCreateStoreZip)。CRC 表 / DOS 时间 / 签名常量成为模块内部实现。
// 该模块零外部依赖(只用 TextEncoder/Blob/DataView/DecompressionStream 等原生能力)⇒ 直接对象导出。
// 迁移前做过等价性验证:14 组用例(写→读往返、新实现写旧实现读、STORE 直取、非法字节抛错)完全一致。
// ⚠️ 注意 wCreateStoreZip 用 new Date() 编 DOS 时间 ⇒ 输出字节非确定,比对请走「写→读往返」。
const StorageZip = (typeof window !== 'undefined' && window.IWBStorageZip) || null
const _zipFn = (name) => {
const fn = StorageZip && StorageZip[name]
if (typeof fn !== 'function') throw new Error('[iwb][storage-zip] 模块未就绪: ' + name)
return fn
}
const wZipParseEntries = (buf) => _zipFn('wZipParseEntries')(buf)
const wZipReadEntry = (zip, entry) => _zipFn('wZipReadEntry')(zip, entry)
const wOpenZipBlob = (blob) => _zipFn('wOpenZipBlob')(blob)
const wCreateStoreZip = () => _zipFn('wCreateStoreZip')()
function wDownloadBlob(blob, name) {
// 备份/导出统一走同一个出口:桌面端弹系统另存为,网页端仍用 <a download>
wSaveBlob(blob, name)
}
// v3.26.119:三个导出调用点原来写的是 `window.__IWB_SAVE_BLOB__` —— 那个全局**从来没被定义过**
//(早就被顶层 `wSaveBlob` 取代了,调用点没跟着改)⇒「导出诊断 JSON」「导出节点组」在桌面端
// 必然抛 TypeError,用户看到的是「导出失败」。现在统一走顶层 wSaveBlob。
function wSanitizeFileName(name) {
return String(name || 'img').replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').replace(/\s+/g, ' ').trim() || 'img'
}
function backupChecksumPayload(data) {
const out = Object.assign({}, data || {})
// 图片 / 插件文件(v3.26.59)的**字节**不进校验和:它们分别走 images/ 与 plugin-files/ 目录,
// ZIP 与 JSON 兜底两种形态下字段名不同(images/imagesData、pluginFiles/pluginFilesData),
// 不排除就会出现「同一份数据换个打包形态 ⇒ 校验和不一致」的假报错。
delete out.checksum; delete out.imagesData; delete out.images; delete out.pluginFiles; delete out.pluginFilesData
return out
}
function backupImageManifest(data) {
return Array.isArray(data && data.images) ? data.images : []
}
function normalizeBackup(data) {
const migrated = StorageMigrations && StorageMigrations.migrateBackup ? StorageMigrations.migrateBackup(data) : { ok: true, value: data }
if (!migrated.ok) throw new Error(migrated.error || '备份版本不受支持')
data = migrated.value
const items = data.items || {}
const out = Object.assign({}, data, { version: 2, schemaVersion: SchemaVersions.backup, items: {} })
if (items.prompts) {
const ps = dedupeBy(items.prompts.prompts, (p) => p.id || [p.name, p.text, p.group].join('|'))
out.items.prompts = Object.assign({}, items.prompts, { prompts: ps, groups: dedupeBy(items.prompts.groups, (g) => g.id || g.name) })
}
if (items.nodeGroups) out.items.nodeGroups = Object.assign({}, items.nodeGroups, { groups: dedupeBy(items.nodeGroups.groups, (g) => g.id || [g.name, JSON.stringify(g.nodes || g.memberIds || [])].join('|')), groupGroups: dedupeBy(items.nodeGroups.groupGroups, (g) => g.id || g.name) })
if (items.workspaces) {
const ws = dedupeBy(items.workspaces.workspaces, (w) => w.id || w.name).map((w) => {
const nodes = dedupeBy(w.nodes, (n) => n.id)
const ids = new Set(nodes.map((n) => n.id))
const edges = dedupeBy(w.edges, (e) => [e.from, e.to, e.batchSrcId || ''].join('|')).filter((e) => ids.has(e.from) && ids.has(e.to))
return Object.assign({}, w, { nodes, edges })
})
out.items.workspaces = Object.assign({}, items.workspaces, { workspaces: ws, activeId: ws.some((w) => w.id === items.workspaces.activeId) ? items.workspaces.activeId : (ws[0] && ws[0].id) || '' })
}
if (items.outputs) out.items.outputs = dedupeBy(items.outputs, (f) => f.url || f.name || JSON.stringify(f))
// v3.0.5 修复("备份里的设置还原不回来"的**第二个**根因):上面四个 if 是白名单式拷贝,
// `items.config` 从来没被带进 `out.items` ⇒ 还原界面里「设置」永远解析不出来(`!!nd.items.config === false`),
// `if (restoreSel.config && items.config)` 恒不成立 ⇒ **勾了「设置」也永远不会恢复**(与导出缺字段是两个独立缺陷)。
// 修法:非白名单项(含 config 及以后新增的任何备份项)一律原样保留,不再逐个白名单。
for (const k of Object.keys(items)) {
if (k === 'prompts' || k === 'nodeGroups' || k === 'workspaces' || k === 'outputs') continue
out.items[k] = items[k]
}
return out
}
// ---------- 数据备份与恢复(可勾选数据项,方便换机/转移) ----------
// ── 备份/还原弹窗已收编到 src/ui-backup-modal.js(结构优化 step-6,2026-10-28)
const _bm = (typeof window !== 'undefined' && window.IWBUIBackupModal) || null
if (!_bm || typeof _bm.inject !== 'function') throw new Error('[iwb][app] 模块未就绪: ui-backup-modal')
const BackupModal = _bm.BackupModal
// 拖线建节点菜单(2026-10-30):从输出端口拖到空白处松手 → 弹「引用该节点生成」
const ConnectMenuMod = (typeof window !== 'undefined' && window.IWBUIConnectMenu) || null
const ConnectMenu = ConnectMenuMod && ConnectMenuMod.ConnectMenu ? ConnectMenuMod.ConnectMenu : null
// ---------- 提示词库(v3:独立面板;编辑弹窗居中;插入/变体仅图标;编辑/删除仅管理模式) ----------
// 提示词分组:独立列表优先;缺失(旧数据)时从 prompts 推导
function promptGroupsOf(prompts, existing) {
if (existing && existing.length) return existing
const seen = []
for (const p of (prompts || [])) {
const g = String((p && p.group) || '').trim()
if (g && !seen.some((x) => x.name === g)) seen.push({ id: g, name: g })
}
return seen
}
const DockArea = (typeof window !== 'undefined') ? window.IWBDockArea : null
// 画布标签条(阶段一组件化 2026-11-07):纯展示组件,回调与快照值经 props 注入
const WorkspaceTabs = (props) => window.IWBUIWorkspaceTabs(Object.assign({ I }, props))
// 应用外壳 UI(阶段一组件化):画布顶栏 / 产品导航,纯展示
const IWWorkbenchHooks = (typeof window !== 'undefined' && window.IWBWorkbenchHooks) || { useViewportPersistence: () => ({}) }
const CanvasTopBar = (props) => window.IWBUICanvasTopBar(Object.assign({ I }, props))
const ProductNav = (props) => window.IWBUIProductNav(Object.assign({ I }, props))
// 一级导航(v3.25.59):最左 52px 纯图标栏,替换原 wsrail 槽位
const NavRail = (typeof window !== 'undefined' && window.IWBUINavRail) ? window.IWBUINavRail : null
// 快捷键弹窗内容(分区罗列 + 折叠说明)
const HotkeyHelp = (typeof window !== 'undefined' && window.IWBUIHotkeyHelp) ? window.IWBUIHotkeyHelp.HotkeyHelp : null
// 插件整页(复用设置里的插件管理块;页面壳在 src/ui-plugin-page.js)
const PluginsPage = (typeof window !== 'undefined') ? window.IWBUIPluginPage : null
// 依赖注入点:放在 Workbench 之前 —— 此处 ICONS / computeEdgePath / downloadUrl / IDB 等全部已定义。
_mod.inject({
ICONS, IDB, computeEdgePath, copyImageToClipboard, downloadUrl,
nodeTypeColor, nodeTypeH, nodeWidth, wBlobFromDataUrl, wRegisterBlobUrl,
})
// 设置面板依赖注入
_sm.inject({
APP_VERSION, BUILTIN_LAYER_MODEL, CrashLog, GEN_CONCURRENCY_DEFAULT, GEN_CONCURRENCY_MAX,
GEN_CONCURRENCY_MIN, HOTKEY_DEFAULTS, I, PluginHost, RATIOS, RES_KEYS, TASK_STALL_END_MAX,
TASK_STALL_END_MIN, W_SHAPE_KINDS, api, applyTheme, fmtStorage, imageFolderApi, initTheme,
localStorageBytes, modelSupportsQuality, storeOutputThumb, uid, wEnsurePluginLoaded,
wNormalizeImageModels, wNormalizeLayerModels, wPrivateToolsOn, wRuntimePlugins, wShapeProviderFields,
})
_nc.inject({
I, NODE_H, W_NODECARD_PASTE_ONCE, batchPortTop, isBatchSrc, isImageProducer,
nodeTypeColor, nodeTypeH, nodeTypeHasPort, nodeTypeIcon, nodeTypeTitle, nodeWidth,
renderBody, wImportImage, wResolveImgAsync,
})
_bm.inject({
W_KEEP,
IDB,
IMG_BLOB_PREFIX,
get ImageBlobStore() { return wImageBlobStore() },
ModularBackupStore,
SchemaVersions,
StorageContract,
api,
backupChecksumPayload,
backupImageManifest,
hydrateGroupSnapshot,
iwbCacheRead,
mapGroupsSeq,
normalizeBackup,
prepareGroupSnapshotForStorage,
wBackupConfig,
wBlobFromDataUrl,
wCfgHasPlaintextKeys,
wCreateStoreZip,
wDownloadBlob,
wImgBlobToDataUrl,
wIsBlobRef,
wLog,
wOpenZipBlob,
wSanitizeFileName,
wSha256,
withoutGenerationResults,
})
// 节点改名弹窗(2026-10-30:气泡压住标题后,改名的正式入口;还保留"双击标题"给未选中的情况)
function wRenameNodeDialog(node, td, updateNode) {
if (!node || !td || typeof td.open !== 'function' || typeof updateNode !== 'function') return
const cur = (node.data && node.data.title && String(node.data.title).trim()) || nodeTypeTitle(node.type)
td.open({ title: '重命名节点', value: cur, placeholder: '节点标题', onSubmit: (v) => updateNode(node.id, { title: String(v == null ? '' : v).trim() }) })
}
// 气泡上的「服务商 · 分组」标签(配置/分层节点):节点本体不再常显这行信息(2026-10-30 用户要求简约)
function floatbarMetaLabel(cfg, node) {
try {
if (!node || (node.type !== 'gen' && node.type !== 'layer')) return ''
const d = node.data || {}
const pr = ((cfg && cfg.providers) || []).find((x) => x && x.id === d.provider)
if (!pr) return ''
const k = (pr.keys || []).find((x) => x && x.id === d.keyGroup)
return String(pr.name || pr.id || '') + ' · ' + (k ? String(k.name || k.id) : '无分组')
} catch (e) { return '' }
}
// 覆盖式替换图片前备份原图:优先保留已有 orig,其次 data,最后 url。返回 updateNode patch。
function origImagePatch(prev, dataUrl) {
const orig = (prev && prev.orig) || (prev && typeof prev.data === 'string' && /^data:/i.test(prev.data) ? prev.data : '') || (prev && typeof prev.url === 'string' ? prev.url : '')
return orig ? { data: String(dataUrl), url: '', orig } : { data: String(dataUrl), url: '' }
}
function Workbench() {
// runtime-workbench-logic 模块的 app.js 模块级依赖:渲染前注入一次(常量/纯函数,无陈旧值风险)
if (IWWorkbenchLogic && !IWWorkbenchLogic.__iwbInjected) {
try {
IWWorkbenchLogic.inject({
GEN_HARD_TIMEOUT_MIN, GEN_HARD_TIMEOUT_MS, GEN_TIMEOUT_MS, NODE_W, RuntimeExecutionContext, RuntimeRunContext,
api, apiErrorMessage, archiveGenerationResults, bcNotify, buildGenerationTasks, classifyErr,
createGenerationJobs, createGenerationResultEntry, createGenerationSnapshot, deriveGenerationRunStatus, downloadUrl, expandPromptVars,
generationConcurrency, generationRunCleanupKeys, iwError, iwErrorFrom, iwbDebugCounter, normalizeGenerationResult,
playDoneSound, prepareBrowserNotifications, resumeVariantPlan, runGenerationJobs, runWithConcurrency, sizeCheck,
standardSizeOf, upsertGenerationEntry, wLog, wRawCfg, wResolveRefArgs,
DEFAULTS, NODE_TYPES, buildLayerPrompt, isImageProducer, layerImageValue, layerInputsOf,
layerPriceOf, layerSizeParam, nodeTypeH, nodeWidth, notifyBrowserGenerationDone, uiZoom,
uid, wImgRefDataUrl, ImageFormat, wBlobFromSrc, wImgBlobToDataUrl,
CrashLog, StorageMigrations,
selfSaveAt: { get: () => wLastSelfSaveAt, set: (v) => { wLastSelfSaveAt = v } },
})
IWWorkbenchLogic.__iwbInjected = true
} catch (e) { /* 注入失败时模块内符号为 undefined,会立即在调用处暴露(不静默) */ }
}
const [nodes, setNodes] = useState([])
const [edges, setEdges] = useState([])
// 画布视口持久化:刷新后恢复上次的缩放/平移位置(不触发自适应)
const [viewport, setViewport] = useState(() => {
try {
const v = lsGet('iwb_viewport', null)
if (v && typeof v.x === 'number' && typeof v.y === 'number' && typeof v.scale === 'number' && v.scale >= 0.01 && v.scale <= 3) return v
} catch (e) { /* ignore */ }
return { x: 40, y: 30, scale: 1 }
})
const [sel, setSel] = useState([])
// 画布工具(2026-10-31):'select'=拖动框选(默认);'pan'=抓手,空白左键拖=平移。仅会话内有效(不持久化)
const [tool, setTool] = useState('select')
const selRef = useRef([]) // 选择实时镜像(拖动/框选读最新值,避免闭包过期)
selRef.current = sel
// 节点组改名:双击操作栏组名进入就地编辑(与节点标题栏一致)
const [editingGroupId, setEditingGroupId] = useState(null)
const [groupNameDraft, setGroupNameDraft] = useState('')
const [selEdge, setSelEdge] = useState(null)
const [hoverEdgeId, setHoverEdgeId] = useState(null)
const canvasV3On = !!(typeof window !== 'undefined' && window.IWBCanvasV3 && window.IWBCanvasV3.isEnabled && window.IWBCanvasV3.isEnabled())
const canvasV3Types = (canvasV3On && window.IWBCanvasV3 && Array.isArray(window.IWBCanvasV3.TYPES)) ? window.IWBCanvasV3.TYPES : ['ref']
const canvasV3TypeOf = (n) => {
const t = n && n.type
return !!t && (canvasV3Types.indexOf(t) >= 0 || t === 'plugin' || t.indexOf('plugin:') === 0)
}
const v3HitAtClient = (clientX, clientY) => {
if (!canvasV3On || !canvasEl.el || !refs.viewport) return null
const rect = canvasEl.el.getBoundingClientRect()
const z = uiZoom()
const vp = refs.viewport
const wx = (clientX / z - rect.left / z - vp.x) / vp.scale
const wy = (clientY / z - rect.top / z - vp.y) / vp.scale
return IWCanvasV3Hit.hitNode(refs.nodes, wx, wy, { isType: canvasV3TypeOf, widthOf: nodeWidth, heightOf: hOf, portRadiusWorld: 10 / vp.scale, wantPorts: true })
}
const [conn, setConn] = useState(null)
const [connTarget, setConnTarget] = useState(null)
const [ctxMenu, setCtxMenu] = useState(null)
// 拖线松手在空白处时待选的新节点菜单:{ fromId, batchSrcId, wx, wy, sx, sy, options }
const [connMenu, setConnMenu] = useState(null)
const ctxMenuRef = useRef(null)
// 右键菜单定位:渲染后测量实际高度,视口底部越界时上移(避免靠下右键被遮挡显示不全)
useLayoutEffect(() => {
if (ctxMenu && ctxMenuRef.current) {
const h = ctxMenuRef.current.offsetHeight
const maxTop = (window.innerHeight || 800) - h - 8
ctxMenuRef.current.style.top = Math.max(8, Math.min(ctxMenu.y, maxTop)) + 'px'
}
}, [ctxMenu])
const [busy, setBusy] = useState({})
const [progress, setProgress] = useState({})
const [edgeHover, setEdgeHover] = useState(null)
// 通知通道(阶段二 2026-11-07):notice/toast/showToast + 两条 sink 均在 src/ui-workbench-hooks.js
const { notice, setNotice, toast, showToast } = IWWorkbenchHooks.useNotifications({ sinks: [{ obj: wImportNoticeSink, defaultText: '导入图片失败' }, { obj: wGlobalNoticeSink }] })
const [server, setServer] = useState({ ok: false })
const [config, setConfig] = useState({ providers: [] })
const [prompts, setPrompts] = useState([])
const [promptGroups, setPromptGroups] = useState([])
const [loaded, setLoaded] = useState(false)
const [splashDone, setSplashDone] = useState(false)
// 加载完成后淡出动画并移除加载遮罩
useEffect(() => { if (loaded) { const t = setTimeout(() => setSplashDone(true), 750); return () => clearTimeout(t) } }, [loaded])
const [saveState, setSaveState] = useState('idle')
const [saveRecovery, setSaveRecovery] = useState(() => LocalStore.get('iwb_web_save_recovery', null))
const [storageHealth, setStorageHealth] = useState(null)
// 持久化存储状态(2026-11-07):非持久 = 浏览器空间紧张时可能被直接清掉。逻辑在 src hook 内
const storagePersist = IWWorkbenchHooks.useStoragePersist(3000)
// 自动备份(2026-11-07):30s 后若距上次 ≥24h 就快照 localStorage → IDB,保留 7 份
// 桌面端不做自动快照(数据已经落盘在资料目录);网页版保持原行为
const autoBackupKit = IWWorkbenchHooks.useAutoBackup(wFileStoreOn() ? 0 : 30000)
const [settingOpen, setSettingOpen] = useState(false)
const [settingTabReq, setSettingTabReq] = useState('general') // 2026-11-25 用户裁定:默认落「通用」;外部要直达某页时用 openSettings('backup'|'diag')
const openSettings = (tab) => { setSettingTabReq(tab || 'general'); setSettingOpen(true) }
// v3.87.26:顶部栏实时信息(内存/规模)。注意**不能在 useState 惰性初始值里读 refs**
// (那时 refs 还没声明 → TDZ 异常会被 catch 吞掉,chip 永远不显示)→ 挂载后再算,
// 之后由 15 秒内存采样持续刷新。
const [memUi, setMemUi] = useState(null)
const refreshMemUi = () => {
try {
const st = wDiagStats(refs.nodes || [], refs.workspaces || []) || {}
const mm = (CrashLog && typeof CrashLog.memoryNow === 'function') ? CrashLog.memoryNow() : null
if (mm) setMemUi({ usedMB: mm.usedMB || 0, limitMB: mm.limitMB || 0, ratio: mm.ratio || 0, nodes: st.nodes || 0, boards: st.boards || 0, images: st.images || 0, base64MB: Math.round((st.base64Bytes || 0) / 1048576) })
} catch (e) { /* 顶部栏信息失败不影响主流程 */ }
}
useEffect(() => {
refreshMemUi()
// v3.87.27:进入画板/切换画板后再补刷两次(原只在挂载时取 → 那时画板还没加载,节点/板/图 全是 0)。
// 刻意不用 [loaded, activeWsId] 依赖:它们在组件里声明得更晚,effect 依赖数组会先求值 → TDZ 崩页面。
const t1 = setTimeout(refreshMemUi, 1500)
const t2 = setTimeout(refreshMemUi, 6000)
return () => { clearTimeout(t1); clearTimeout(t2) }
}, [])
const [drawerOpen, setDrawerOpenRaw] = useState(() => { try { return lsRawGet('iwb_drawer_open', null) !== '0' } catch (e) { return true } }); const setDrawerOpen = (v) => { setDrawerOpenRaw(v); try { lsRawSet('iwb_drawer_open', v ? '1' : '0') } catch (e) { /* ignore */ } } // 库面板开合状态持久化:刷新后保持上次开关(2026-11-03);读写失败回退「关闭」,不阻断启动
const [drawerTab, setDrawerTabRaw] = useState(() => { try { return lsRawGet('iwb_drawer_tab', '') || 'history' } catch (e) { return 'prompts' } }); const setDrawerTab = (v) => { setDrawerTabRaw(v); try { lsRawSet('iwb_drawer_tab', String(v)) } catch (e) { /* ignore */ } ; try { window.dispatchEvent(new CustomEvent('iwb:dock-activate', { detail: { side: 'right', id: v === 'history' ? 'gallery' : 'prompts' } })) } catch (e) { /* ignore */ } } // 库面板当前标签持久化:刷新后停在上次的 tab(2026-11-03)
const [enteringWs, setEnteringWs] = useState(false) // 进入画布编辑器的加载动画
const [outputs, setOutputs] = useState([])
const [outputsInfo, setOutputsInfo] = useState(null)
const [helpOpen, setHelpOpen] = useState(false)
const [helpMode, setHelpMode] = useState('keys') // 'keys'=只列快捷键;'help'=展开「更多操作说明」
const [resumePrompt, setResumePrompt] = useState(null) // 上次生成中断的任务(刷新后可续跑)
const [pluginRev, setPluginRev] = useState(0)
React.useEffect(() => {
if (!PluginHost || typeof PluginHost.on !== 'function') return undefined
return PluginHost.on(() => setPluginRev((v) => v + 1))
}, [])
React.useEffect(() => {
wPluginCanvasBridge = {
getNodes: () => refs.nodes.map((n) => ({ id: n.id, type: n.type, x: n.x, y: n.y, data: n.data || {} })),
getSelectedNode: () => {
const id = selRef.current && selRef.current[0]
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, opts) => {
const n = refs.nodes.find((x) => x.id === id)
if (!n || !wGallerySync) return null
const img = await wGallerySync.nodeImageOf(n, { writeRef: (src) => wImgRefWrite(src), onLocalRef: (ref) => updateNode(n.id, { localRef: ref }) })
// v3.26.124:插件只要能看/能预览时,给**缩过的**图,别让它整幅解码原图
const max = Math.max(64, Number(opts && opts.max) || 0)
if (!img || !max) return img
try {
const src = img.localRef || img.url || img.dataUrl
if (src && typeof src === 'object') { const t = await wEnsureTier(src, max); if (t) { const d = await wPluginPreview(src, { max }); if (d && d.ok) return Object.assign({}, img, { dataUrl: d.dataUrl, capped: max }) } }
else if (typeof src === 'string' && src.indexOf('data:') === 0) { const s2 = await wShrinkDataUrl(src, max); if (s2) return Object.assign({}, img, { dataUrl: s2, capped: max }) }
} catch (e) { /* ignore */ }
return img
},
createNode: (type, x, y, data) => {
// 插件节点传的是变体 id(web/style…):不在 NODE_TYPES 里,交给 addPluginNode 拼出 plugin:<插件>:<变体>
if (!NODE_TYPES.has(type)) return addPluginNode(type, x, y, data) || null
const spot = (CanvasGeometry && CanvasGeometry.wantsDefaultSpot(x, y)) ? findSpot(type) : placeAtDrop(type, x, y)
const node = { id: uid('n'), type, x: spot.x, y: spot.y, data: Object.assign({}, cloneNodeDefaults(type), data || {}) }
commitCanvas(refs.nodes.concat([node]), undefined, undefined)
return node.id
},
// 屏幕坐标 → 世界坐标:供插件「按住按钮拖到画布上松手」建节点(2026-11-02)。
// 读 .iwb-world 的实时 transform 与 .iwb-canvas 的 rect —— 与 tbCenterSeed 同一套口径,
// 不用 refs.viewport(渲染落后一拍时换算会偏)。换算本身是纯函数,在 canvas-geometry。
screenToWorld: (clientX, clientY) => {
const c = document.querySelector('.iwb-canvas')
if (!c || !c.clientWidth) return null
const wl = document.querySelector('.iwb-world')
const t = (CanvasGeometry && CanvasGeometry.parseWorldTransform) ? CanvasGeometry.parseWorldTransform(wl && wl.style ? wl.style.transform : '') : null
return CanvasGeometry.clientToWorld(clientX, clientY, c.getBoundingClientRect(), t || refs.viewport)
},
createImageNode: (payload) => {
const src = payload && payload.dataUrl
if (!src || !/^data:/i.test(String(src))) return null
const at = payload || {}
// 与 createNode 同一套坐标语义:给了有限坐标就用它(拖拽松手点,压住节点时就近吸附),否则走 findSpot 找位
const spot = (CanvasGeometry && CanvasGeometry.wantsDefaultSpot(at.x, at.y)) ? findSpot('ref') : placeAtDrop('ref', at.x, at.y)
const node = { id: uid('n'), type: 'ref', x: spot.x, y: spot.y, data: { url: '', data: String(src), name: String((payload && payload.name) || 'plugin.png'), localName: null } }
commitCanvas(refs.nodes.concat([node]), undefined, undefined)
return node.id
},
setNodeImage: (id, dataUrl) => {
if (!/^data:/i.test(String(dataUrl || ''))) return false
const t = refs.nodes.find((x) => x.id === id); if (!t) return false
updateNode(id, origImagePatch(t.data || {}, String(dataUrl))); return true
},
saveNodeImage: (id, dataUrl) => (IWWorkbenchLogic ? IWWorkbenchLogic.saveNodeImage({ refs, commitCanvas, saveNow, readWorkspace: () => WorkspaceStore.read(null), activeWsId: () => activeWsIdRef.current || activeWsId, origPatch: origImagePatch }, id, dataUrl) : Promise.resolve({ ok: false, error: '画布能力未就绪' })),
}
return () => { wPluginCanvasBridge = null }
}, [])
const [layoutLocked, setLayoutLocked] = useState(false)
const [wsMoreOpen, setWsMoreOpen] = useState(false) // 顶部 ⋯ 三点菜单(展开态)
const [wsMorePos, setWsMorePos] = useState({ top: 0, left: 0 }) // 三点菜单 fixed 定位
// 画布编辑页:标题双击重命名 + 返回按钮
const [canTitleEdit, setCanTitleEdit] = useState(false)
const [canTitleName, setCanTitleName] = useState('')
// 统一改名弹窗(居中,复用 .iwb-rename-modal 样式):{ title, value, placeholder, okText, onSubmit }
const td = useTextDialog()
const outputRequestSeq = useRef(0)
// 图库插入尺寸档(v3.25.18 工单 ⑤):原图 / 2k / 1k / 0.5k,记忆上次选择
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)。事实口径:它只把 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)
try { return _imgCompressFn('toMaxEdge')(dataUrl, INSERT_K[kk], 0.9).catch(() => dataUrl) } catch (e) { return Promise.resolve(dataUrl) }
}
const [boxSel, setBoxSel] = useState(null)
const [preview, setPreview] = useState(null)
const [swUpdate, setSwUpdate] = useState(false) // 检测到新版本(Service Worker 更新)
const swRegRef = useRef(null)
const swConfirmedRef = useRef(false)
// 注册 Service Worker 以检测「新版本」→ 顶部提示 → 一键刷新更新(学 opentu 的 PWA 机制)
useEffect(() => {
// 桌面端不注册 SW:本地端没有 HTTP 服务、也不需要离线缓存,注册只会 404 并拖慢启动
if (wFileStoreOn()) return
if (typeof navigator === 'undefined' || !navigator.serviceWorker) return
try {
navigator.serviceWorker.register('/sw.js').then((registration) => {
swRegRef.current = registration
const mayUpdate = () => { if (registration.waiting) setSwUpdate(true) }
mayUpdate()
registration.addEventListener('updatefound', () => {
const w = registration.installing
if (w) w.addEventListener('statechange', () => { if (w.state === 'installed' && navigator.serviceWorker.controller) setSwUpdate(true) })
})
}).catch(() => { /* SW 不可用则忽略 */ })
navigator.serviceWorker.addEventListener('controllerchange', () => { if (swConfirmedRef.current) { try { location.reload() } catch (e) { /* ignore */ } } })
} catch (e) { /* ignore */ }
return () => {}
}, [])
const swUpdateConfirm = () => { swConfirmedRef.current = true; const w = swRegRef.current && swRegRef.current.waiting; if (w) { try { w.postMessage({ type: 'SKIP_WAITING' }) } catch (e) { /* ignore */ } } setSwUpdate(false) }
const [tick, setTick] = useState(0)
const [canvasSize, setCanvasSize] = useState({ w: 0, h: 0 })
const [canvasEl] = useState(() => ({ el: null }))
const [groups, setGroups] = useState([])
const [savedGroups, setSavedGroups] = useState([])
const [nodeGroupGroups, setNodeGroupGroups] = useState([])
const [workspaces, setWorkspaces] = useState([])
// 导出备份提醒(2026-11-07):>14 天没导出磁盘备份就轻提示(自动备份防不了清站点数据)
// 注意:必须声明在 workspaces 之后 —— 参数在调用点求值,提前引用会 TDZ
const exportRemind = IWWorkbenchHooks.useExportReminder({ days: 14, hasData: (workspaces || []).length > 0 })
const [activeWsId, setActiveWsId] = useState(null)
// v3.87.10:打字感知——输入期间暂停"历史引用化清扫"与"落盘",停止输入后恢复
useEffect(() => {
const onInput = (e) => {
const t = e && e.target
if (!t || !t.tagName) return
const isText = t.tagName === 'TEXTAREA' || (t.tagName === 'INPUT' && !/^(checkbox|radio|range|file|color|button|submit)$/i.test(String(t.type || 'text')))
if (!isText) return
if (historyStore) historyStore.noteTyping()
if (refs.typingTimer) clearTimeout(refs.typingTimer)
refs.typingTimer = setTimeout(() => { if (historyStore) historyStore.clearTyping(); try { if (historyStore) historyStore.schedule() } catch (err) { /* ignore */ } }, 1700)
}
document.addEventListener('input', onInput, true)
return () => { document.removeEventListener('input', onInput, true); if (refs.typingTimer) clearTimeout(refs.typingTimer) }
}, [])
const [thumbRev, setThumbRev] = React.useState(0) // v3.87.7:显示缩略图就绪后触发一次 re-render(必须在 Workbench 内)
useEffect(() => { wThumbBump = () => setThumbRev((v) => v + 1); return () => { wThumbBump = null } }, [])
// 启动维护(v3.25.80):8 秒后做缩略图封顶 + legacy 未引用清理;同时启动远程参考图本地缓存。
useEffect(() => {
const RC = (typeof window !== 'undefined') ? window.IWBImageRemoteCache : null
const stop = (RC && typeof RC.attach === 'function')
? RC.attach({ getState: () => ({ enabled: !!(loaded && shellView === 'canvas'), nodes: (refs && refs.nodes) || [] }), writeRef: (u) => wImgRefWrite(u), updateNode: (id, patch) => updateNode(id, patch) })
: null
const timer = setTimeout(() => {
try { const F = wStoreMod(); if (F && typeof F.maintain === 'function') F.maintain({ maxMB: 300, keep: wCollectRefImageNames(workspaces) }).catch(() => { /* ignore */ }) } catch (e) { /* ignore */ }
}, 8000)
return () => { if (timer) clearTimeout(timer); if (typeof stop === 'function') stop() }
}, [])
// 外观实时预览(v3.25.76):设置面板每改一个外观项都会派发该事件,
// 这里只 bump 一次渲染,让网格贴图按新的间距/颜色/样式重新生成。
useEffect(() => {
const onAppearance = () => { try { setThumbRev((v) => v + 1) } catch (e) { /* ignore */ } }
window.addEventListener('iwb:appearance', onAppearance)
return () => window.removeEventListener('iwb:appearance', onAppearance)
}, [])
// 2026-11-14:插件节点体(render)异步注册完成后重画一次 —— 否则存档里的插件节点会一直停在
// 首帧的兜底体(hint + 纯文本),看起来像「样式节点只剩一段文本」。
const [typesRev, setTypesRev] = React.useState(0)
useEffect(() => subscribeNodeTypesRev(() => setTypesRev((v) => v + 1)), [])
// C3:把撤销历史栈登记给模块层 —— 孤儿回收需要知道历史快照里还钉着哪些图片字节
useEffect(() => {
wHistoryNodesGetter = () => refs.history
return () => { wHistoryNodesGetter = null }
}, [])
// e2e 探针(仅 __IWB_E2E__ === true 时暴露;生产不挂载):撤销历史 / 画布节点 / 往节点注入大图
useEffect(() => {
if (typeof window === 'undefined' || window.__IWB_E2E__ !== true) return undefined
window.__IWB_E2E_HISTORY__ = () => refs.history
window.__IWB_E2E_CANVAS__ = () => refs.nodes
// 直接把大图 base64 注入内存中的节点(模拟用户上传的原图;绕开 localStorage 配额 —— 这正是 OOM 现场)
window.__IWB_E2E_SETREF__ = (nodeId, value) => {
try {
const id = String(nodeId || '')
// C3:允许直接注入引用对象({__idb}/{__cache}/{__blob}),用于验证引用迁移/显示链路
const v = (value && typeof value === 'object') ? value : String(value || '')
const next = refs.nodes.map((n) => (n.id === id ? { ...n, data: { ...n.data, data: v } } : n))
commitCanvas(next, refs.edges, refs.groups)
return true
} catch (e) { return false }
}
// v3.0.4(B):手动触发**恰好一次** pushHistory,用于「快照字节从 MB 级降到 KB 级」的可测量契约
// (走用户可见的编辑路径也能触发,但无法保证"恰好一次")。返回快照入栈后的历史栈长度。
window.__IWB_E2E_PUSH_HISTORY__ = () => {
try { pushHistory() } catch (e) { return -1 }
return (refs.history && refs.history.stack) ? refs.history.stack.length : -1
}
return () => { try { delete window.__IWB_E2E_HISTORY__; delete window.__IWB_E2E_CANVAS__; delete window.__IWB_E2E_SETREF__; delete window.__IWB_E2E_PUSH_HISTORY__ } catch (e) { /* ignore */ } }
}, [])
const [shellView, setShellView] = useState(() => { try { return lsRawGet('iwb_shell_view', null) === 'canvas' ? 'canvas' : 'home' } catch (e) { return 'home' } }) // landing=首页说明,home=我的画布,canvas=无限画布;刷新时恢复上次所在的视图
// 记住当前视图;刷新后在画布编辑器则恢复到画布编辑器(画布库则仍回画布库)
useEffect(() => { try { lsRawSet('iwb_shell_view', shellView) } catch (e) { /* ignore */ } }, [shellView])
const [homeSelectedWs, setHomeSelectedWs] = useState([])
const [homeManage, setHomeManage] = useState(false) // 我的画布:批量管理模式(卡片点击选中)
const [homeView, setHomeView] = useState('recent') // 我的画布库:视图(recent/starred/none/cat:NAME/trash)
const [homeSearch, setHomeSearch] = useState('') // 我的画布库:搜索画布名
const [catPick, setCatPick] = useState(null) // 分类选择器:{mode:'card',id} 或 {mode:'batch'}
const [homeMenuOpen, setHomeMenuOpen] = useState(false) // 画布库侧栏 ≡ 菜单
const [homeMenuPos, setHomeMenuPos] = useState({ top: 0, left: 0 })
const activeWsIdRef = useRef(null)
activeWsIdRef.current = activeWsId
const shellViewRef = useRef(shellView)
shellViewRef.current = shellView // 渲染期镜像(生成结束回调读实时视图,同 activeWsIdRef 模式)
const layoutLockKey = (id) => 'iwb_layout_locked_' + (id || 'default')
useEffect(() => { if (activeWsId) setLayoutLocked(!!lsGet(layoutLockKey(activeWsId), false)) }, [activeWsId])
// 当前工作台持久化(刷新恢复同一工作台)
useEffect(() => { if (activeWsId) { try { lsRawSet('iwb_ws_active', activeWsId) } catch (e) { /* ignore */ } } }, [activeWsId])
// S12:打开的标签列表(浏览器式标签条)——持久化到 iwb_tabs_open(⚠️ 不用 iwb_ws_ 前缀,避开画布 key 空间)
const [openTabs, setOpenTabs] = useState(() => {
try { const arr = lsGet('iwb_tabs_open', []); return Array.isArray(arr) ? arr.filter((x) => typeof x === 'string' && x) : [] } catch (e) { return [] }
})
useEffect(() => { try { lsSet('iwb_tabs_open', openTabs) } catch (e) { /* ignore */ } }, [openTabs])
const openTabsRef = useRef(openTabs)
openTabsRef.current = openTabs // 渲染期镜像(mount effect / 释放语义用,同 activeWsIdRef 模式)
// S16/§3.7 回退契约:iwb_tabs_open 缺失/指向已删画布 → 首次加载完成后一次性校准
// (陈旧 id 清掉;清完为空则用 activeId 开一个标签)。只跑一次——之后用户主动关光标签不会被重新种回。
const tabsReconciledRef = useRef(false)
useEffect(() => {
if (tabsReconciledRef.current || !loaded || !workspaces || !workspaces.length) return
tabsReconciledRef.current = true
setOpenTabs((prev) => {
const live = new Set(workspaces.filter((w) => w && !w.deleted).map((w) => w.id))
const valid = (prev || []).filter((x) => live.has(x))
if (valid.length) return valid
const seed = (activeWsId && live.has(activeWsId)) ? activeWsId : (((workspaces.find((w) => w && !w.deleted)) || workspaces[0] || {}).id)
return seed ? [seed] : []
})
}, [loaded, workspaces])
// 打开/激活某个标签:不在列表则追加(S12)
const openTab = (wsId) => { if (!wsId) return; setOpenTabs((prev) => prev.includes(wsId) ? prev : prev.concat([wsId])) }
// 关闭标签:移除 + 释放 session/画板;关的是激活标签则先切到相邻(无则回首页)
const closeTab = async (wsId) => {
if (!wsId) return
const sess = sessionsStore.get(wsId)
const nm = (((refs.workspaces || workspaces).find((w) => w.id === wsId)) || {}).name || '未命名画布'
if (sess && sess.dirty) { // S13:有未保存修改 → 确认后先保存再关
if (!(await window.IWBUIConfirm.askOrNative('「' + nm + '」有未保存修改,关闭前将先保存。确定关闭?', { title: '关闭画布', okText: '关闭并保存' }))) return
try {
const list = (refs.workspaces || workspaces).map((w) => (w.id === wsId ? { ...w, nodes: sess.nodes, edges: sess.edges, groups: sess.groups, lastUsed: Date.now() } : w))
refs.workspaces = list; setWorkspaces(list); persistWs(list, activeWsId); sess.dirty = false
} catch (e) { /* 保存失败仍允许关闭(数据已在 session 里同步过) */ }
}
const idx = openTabs.indexOf(wsId)
const wasActive = wsId === activeWsId && shellView === 'canvas'
setOpenTabs((prev) => prev.filter((x) => x !== wsId))
// 关激活标签:先完成视图切换(switchWs/goHome 会把该画布最新数据同步回列表),再释放
const releaseClosed = () => {
try { wReleaseImgUrlsForSession(wsId) } catch (e) { /* ignore */ }
try { sessionsStore.drop(wsId) } catch (e) { /* ignore */ }
try { // S14:关闭即降级该画板(已不在打开标签里)
const entry = wLoadedBoards.find((x) => x && x.id === wsId)
if (entry) {
if (typeof window !== 'undefined' && window.__IWB_E2E__ === true) window.__IWB_E2E_UNHYDRATES__ = (window.__IWB_E2E_UNHYDRATES__ || 0) + 1
const live = (refs.workspaces || []).find((x) => x && x.id === wsId) || entry.w
wUnhydrateWorkspace(live)
wLoadedBoards.splice(wLoadedBoards.indexOf(entry), 1)
}
} catch (e) { /* ignore */ }
}
if (wasActive) {
const remaining = openTabs.filter((x) => x !== wsId)
if (remaining.length) { const nextId = remaining[Math.max(0, idx - 1)] || remaining[0]; if (nextId) { switchWs(nextId); releaseClosed(); return } }
goHome(); releaseClosed(); return
}
releaseClosed()
}
const [wsRev, setWsRev] = useState(null) // workspaces 版本戳(乐观锁:防多窗口/多设备覆盖)
const [wsRenameId, setWsRenameId] = useState(null)
const [wsRenameName, setWsRenameName] = useState('')
// 左右栏展开/收起持久化(刷新恢复)
const [theme, setTheme] = useState(() => initTheme())
const toggleTheme = () => { const t = theme === 'dark' ? 'light' : 'dark'; setTheme(t); applyTheme(t) }
// 界面模式(Tab 切换纯画布/缩进)已于 v3.24.8 移除:它会把标签栏与底部工具栏整体隐藏,
// 而 Tab 同时是浏览器切焦点的默认键,误按即表现为「界面坏了」。历史遗留的 localStorage 键
// iwb_ui_mode 现在无人读取,忽略即可(下次清站点数据会自然消失)。
const [refs] = useState(() => ({
drag: null, resize: null, connFrom: null, pan: null, box: null, bodyDown: null, spaceDown: false,
nodes: [], edges: [], groups: [], savedGroups: [], viewport: null, measuredH: {}, outputs: [],
nodeMap: new Map(),
history: { stack: [], idx: -1 },
clipboardGraph: null,
// 底栏「适应视图」按钮需要 memo 友好的稳定回调 → 每渲染把最新 fitView 挂到这里
fitViewRef: null,
zoomAnim: null, zoomByRef: null,
combinePushed: {},
batchPushed: {},
promptLibrary: [],
runningRuns: new Set(),
runWorkspaces: new Map(),
genScheduler: { active: 0, queue: [], external: null },
skipInitialPersistence: true,
// 跨渲染稳定的计时器句柄:用 per-render 的局部 let 会清不掉上一次渲染设下的定时器
toastTimer: null, saveTimer: null, typingTimer: null,
// Ctrl+Shift+V 的按下时间窗:吞掉浏览器随后派发的 paste(Chrome 会以纯文本形式触发)
pasteGroupUntil: 0,
// 粘贴通道时间戳(2026-11-26):pasteKeyAt = 本次 ⌘V 按下;pasteEventAt = 真收到 paste;
// pasteSwallowUntil = 主动粘贴刚落地,吞掉重复事件。三条一起保证「一次按键只贴一份」。
pasteKeyAt: 0, pasteEventAt: 0, pasteSwallowUntil: 0,
// 本机系统剪贴板是否可信(复制时写成功=true / 写失败=false;失败后 ⌘V 只认应用内剪贴板)
sysClipOk: null,
// 内部剪贴板「复制过但已过期」(readClipboardGraph 维护):用于把静默失败变成一句提示
clipExpired: false,
// ── 多画布 Session(S1:结构落地;行为改造在 S5–S6;Pilot 2 第二片容器外置到 sessionsStore)──
// D1:打开标签的画布,session 是唯一工作副本;refs 始终指向激活 session 的数据。
// 会话容器(Map + LRU + 激活 id + 驱逐策略)收编到 src/workspace-sessions-store.js;
// 实例挂这里惰性创建一次(**必须跨渲染稳定**,否则每渲染重建会丢会话 → 持久化断裂)。
sessionsStore: null,
}))
// ── CanvasSession 工厂与管理(S1)──
// 每个最近访问的画布保有一个 CanvasSession(工作副本),refs 始终指向激活 session。
// 有界 LRU(上限 W_SESSION_MAX=5,超出时驱逐最旧的非激活 session)已收编到 src/workspace-sessions-store.js
// (数据仍在 refs.workspaces 列表里,不丢;S5 切换时从 session 恢复,S6 同步时按 wsId 合并)。
// 会话容器持有 Map/LRU/激活 id —— 实例必须跨渲染稳定(与 refs 同寿命),否则每渲染重建会丢会话。
if (!refs.sessionsStore) {
refs.sessionsStore = (typeof window !== 'undefined' && window.IWBSessionsStore && typeof window.IWBSessionsStore.create === 'function')
? window.IWBSessionsStore.create({
makeSession: (id) => makeCanvasSession(id),
onEvict: (id) => wReleaseImgUrlsForSession(id), // 驱逐前回调:回收该 session 的 objectURL(不影响其它 session)
log: (evt, id) => wLog('sessions', String(evt || '') + ' ' + String(id || '')),
})
: null
}
const sessionsStore = refs.sessionsStore
// ── Session 管理(makeCanvasSession / syncActiveSession / openSession / ensureSessionFor /
// composeWorkspaceList / refreshSessionsFromList)已外移到
// src/runtime-workbench-logic.js.createWorkbenchSessions(2026-11-06)
let s3aCache = null
const s3aCmd = () => s3aCache || (s3aCache = IWWorkbenchLogic.createWorkbenchSessions({ APP_VERSION, edges, groups, nodes, refs, sel, selEdge, sessionsStore, viewport, wCollectImgRefKeys, wReleaseImgUrls, workspaces }))
const makeCanvasSession = (...a) => s3aCmd().makeCanvasSession(...a)
const syncActiveSession = (...a) => s3aCmd().syncActiveSession(...a)
const wReleaseImgUrlsForSession = (...a) => s3aCmd().wReleaseImgUrlsForSession(...a)
const openSession = (...a) => s3aCmd().openSession(...a)
const ensureSessionFor = (...a) => s3aCmd().ensureSessionFor(...a)
const composeWorkspaceList = (...a) => s3aCmd().composeWorkspaceList(...a)
const refreshSessionsFromList = (...a) => s3aCmd().refreshSessionsFromList(...a)
const acquireGenSlot = () => new Promise((resolve, reject) => {
const scheduler = refs.genScheduler
const limit = generationConcurrency(refs.config)
const external = typeof window !== 'undefined' && window.IWBGenerationScheduler
const grant = () => {
scheduler.active++
const finish = (externalRelease) => {
let released = false
resolve(() => {
if (released) return
released = true
scheduler.active--
if (externalRelease) externalRelease()
const next = scheduler.queue.shift()
if (next) next()
})
}
if (external && typeof external.createScheduler === 'function') {
if (!scheduler.external) scheduler.external = external.createScheduler({ concurrency: 16 })
scheduler.external.acquire().then(finish).catch((error) => {
scheduler.active--
const next = scheduler.queue.shift()
if (next) next()
reject(error)
})
} else finish(null)
}
if (scheduler.active < limit) grant()
else scheduler.queue.push(grant)
})
const runLockConflicts = (nodeId, taskPromptId) => {
const prefix = nodeId + '::'
if (taskPromptId) return refs.runningRuns.has(prefix + 'all') || refs.runningRuns.has(prefix + taskPromptId)
for (const key of refs.runningRuns) if (key.indexOf(prefix) === 0) return true
return false
}
// 节点启用/停用(M 键):停用节点不参与执行(生成/组合/润色/批量),视觉半透明
const toggleEnabled = (ids) => {
const list = (ids && ids.length ? ids : sel).filter((id) => refs.nodes.some((n) => n.id === id))
if (!list.length) { showToast('请先选择节点,再按 M 启用/停用', 'err'); return }
const allDisabled = list.every((id) => { const n = refs.nodes.find((x) => x.id === id); return n && n.data && n.data.enabled === false })
const next = allDisabled // 全停用 → 全部启用;否则 → 全部停用
for (const id of list) {
if (!next) cancelRunsFor(id) // 停用节点:取消其进行中的生成请求(不白耗额度)
updateNode(id, { enabled: next })
}
showToast(next ? '已启用 ' + list.length + ' 个节点(参与执行)' : '已停用 ' + list.length + ' 个节点(不参与执行)')
saveDebounced() // 持久化启用状态(等 updateNode 渲染提交后保存,避免存旧值)
}
refs.nodes = nodes
refs.nodeMap = new Map(nodes.map((n) => [n.id, n]))
refs.edges = edges
refs.groups = groups
refs.workspaces = workspaces
refs.outputs = outputs
refs.savedGroups = savedGroups
refs.promptLibrary = prompts
refs.connTarget = connTarget
refs.viewport = viewport
syncActiveSession() // S1:每渲染把 refs 写回激活 session(session 是工作副本)
wSessionsRef = { keys: () => sessionsStore.ids(), forEach: (fn) => sessionsStore.ids().forEach((id) => fn(sessionsStore.get(id), id)) } // S4:模块级只读视图(不外泄可变 Map),wEvictLoadedBoards / IDB 清理据此保护打开画布的画板
// 视口变化持久化(刷新恢复,不触发自适应)。
// 防抖落盘:平移/缩放每帧只更新 state,不每帧同步写 localStorage(sync setItem 会阻塞主线程导致卡顿);
// 手势停顿 300ms 后才写一次;离开页面前 beforeunload 兜底落盘最新视口。
// 视口持久化 hooks(阶段二 2026-11-07):从 Workbench 抽到 src/ui-workbench-hooks.js
// 变量名保持不变 ⇒ 下游 viewportRef / activeWsRef / flushViewport 的调用点零改动
const { viewportRef, activeWsRef, flushViewport } = IWWorkbenchHooks.useViewportPersistence(activeWsId, viewport)
// 自动下载的提示回调(模块级装配拿不到组件闭包,这里挂到全局槽)
try { window.__iwbAutoToast__ = (msg, type) => setNotice({ type: type === 'err' ? 'err' : 'ok', text: msg }) } catch (e) { /* ignore */ }
refs.config = config
// 外观:配置到位/切换主题时把画布底色与主题色写到 :root(放在 config 同步之后,
// 否则首屏拿不到配置,改完颜色要重启才生效)
useEffect(() => { const f = () => { try { applyAppearance(config) } catch (e) { /* ignore */ } }; f(); window.addEventListener('iwb:theme-change', f); return () => window.removeEventListener('iwb:theme-change', f) }, [config, theme])
useEffect(() => {
let alive = true
// 启动时一次性迁移历史 localStorage 里的 base64 大图到 IndexedDB(释放空间,治撑爆)
try { wMigrateLegacyCanvasBase64() } catch (e) { /* ignore */ }
// 清理已下线功能(Pinterest 在线参考图库)的本地残留键
try { wCleanRemovedFeatureKeys() } catch (e) { /* ignore */ }
const runHealthCheck = () => storageHealthCheck()
const reportHealthError = (error) => { RuntimeMetrics.add('storageFailureCount'); return error }
const healthPromise = RuntimeBoundary && typeof RuntimeBoundary.safeAsync === 'function'
? RuntimeBoundary.safeAsync(runHealthCheck, { ok: false, localStorage: false, indexedDB: false, bytes: 0, issues: [iwError('storage', '存储检查失败')] }, reportHealthError)
: Promise.resolve(runHealthCheck())
Promise.resolve(healthPromise).then((value) => { if (alive) setStorageHealth(value) }).catch((error) => { reportHealthError(error); if (alive) setStorageHealth({ ok: false, localStorage: false, indexedDB: false, bytes: 0, issues: [iwError('storage', '存储检查失败')] }) })
return () => { alive = false }
}, [])
// 生成中断恢复持久化:进行中任务进度落 localStorage,刷新后提示可续跑(跳过已完成张)
const persistRuns = () => {
try {
if (!refs.genRuns || !refs.genRuns.size) { lsRemove('iwb_web_running'); return }
const runs = Array.from(refs.genRuns.values()).map((r) => ({ runId: r.runId || '', nodeId: r.nodeId, workspaceId: r.workspaceId || '', label: r.label, total: r.total, done: r.done, failed: r.failed || 0, status: r.status || 'running', runtimeState: RuntimeRecord ? RuntimeRecord.fromLegacy({ state: r.status || 'running' }).state : (r.status || 'running'), startedAt: r.startedAt || 0, updatedAt: Date.now(), retryCount: Math.max(0, Number(r.retryCount) || 0), jobs: Array.isArray(r.jobs) ? r.jobs.map((j) => ({ promptId: j.promptId, variantIndex: j.variantIndex, state: j.state, error: j.error || '', runId: j.runId || r.runId || '', retryCount: Math.max(0, Number(j.retryCount) || 0) })) : [] }))
lsSet('iwb_web_running', { at: Date.now(), runs })
} catch (e) { /* ignore */ }
}
const diagnosticsRunState = (value) => {
const state = String(value || '')
if (!GenerationState) return state || 'unknown'
if (GenerationState.states.indexOf(state) >= 0) return state
return state === 'partial-failed' ? 'failed' : (state || 'unknown')
}
// v3.87.6:诊断文本统一在这里构建(下载 / 复制 / 设置里的「诊断」页共用一份),
// 额外带上崩溃记录 + 内存采样 + 操作面包屑(都不含 Key、提示词与图片本体)。
const buildRuntimeDiagnosticsText = (tasks, meta) => {
const crash = (CrashLog && typeof CrashLog.report === 'function')
? CrashLog.report({ version: APP_VERSION, commit: (meta && meta.commit) || 'unknown', context: { workspaceId: activeWsId, nodeCount: refs.nodes.length, stats: wDiagStats(refs.nodes, refs.workspaces) } })
: null
return RuntimeDiagnostics.toJson({ version: APP_VERSION, commit: (meta && meta.commit) || 'unknown', workspaceId: activeWsId, nodeCount: refs.nodes.length, tasks, storage: storageHealth, lifecycle: RuntimeLifecycle, scheduler: { stats: () => ({ active: Number(refs.genScheduler.active) || 0, queued: refs.genScheduler.queue.length }) }, metrics: RuntimeMetrics && typeof RuntimeMetrics.snapshot === 'function' ? RuntimeMetrics.snapshot() : undefined, crash })
}
const exportRuntimeDiagnostics = () => {
if (!RuntimeDiagnostics || typeof RuntimeDiagnostics.toJson !== 'function') { setNotice({ type: 'err', text: '当前环境不支持运行诊断导出' }); return }
try {
const tasks = []
if (refs.genRuns) refs.genRuns.forEach((run, runKey) => {
const jobs = Array.isArray(run.jobs) ? run.jobs : []
if (jobs.length) jobs.forEach((job, index) => tasks.push({ id: runKey + ':' + index, runId: job.runId || run.runId || '', nodeId: run.nodeId, state: diagnosticsRunState(job.state || run.status), retryCount: job.retryCount || run.retryCount || 0, progress: { done: job.state === 'completed' ? 1 : 0, total: 1 }, error: job.error ? { category: 'generation', code: 'job-failed', retryable: true } : undefined }))
else tasks.push({ id: runKey, runId: run.runId || '', nodeId: run.nodeId, state: diagnosticsRunState(run.status), retryCount: run.retryCount || 0, progress: { done: Number(run.done) || 0, total: Number(run.total) || 0 } })
})
const meta = (typeof window !== 'undefined' && window.__IWB_BUILD_META__) || {}
const text = buildRuntimeDiagnosticsText(tasks, meta)
const blob = new Blob([text], { type: 'application/json' })
const fileName = 'image-workbench-diagnostics-' + new Date().toISOString().slice(0, 10) + '.json'
// 统一出口:桌面端原生另存为,网页端 <a download>
wSaveBlob(blob, fileName)
showToast('已导出运行诊断(不含 Key、提示词和图片)')
} catch (e) { setNotice({ type: 'err', text: '诊断导出失败:' + String((e && e.message) || e) }) }
}
// 生成取消族(cancelRunsFor / cancelRun / cancelTaskJobs)已搬到 src/runtime-workbench-logic.js
// (2026-11-16 棘轮腾位):三者只碰 refs 的三张句柄表 + 三个 setter,注入面最小。
// 每次渲染重建一次(与原 const 语义一致);refs 是同一个可变对象,不会陈旧。
const { cancelRunsFor, cancelTaskJobs, cancelRun } = IWWorkbenchLogic.createCancelActions({ refs, persistRuns, setBusy, setProgress, setNotice })
// 继续上次中断的生成(跳过已完成任务;找不到节点则忽略)
// resumeRuns 已搬到 src/runtime-workbench-logic.js(2026-10-29)
const resumeRuns = () => IWWorkbenchLogic.resumeRuns({ activeWsId, activeWsIdRef, loadWsInto, refs, resumePrompt, runNode, sessionsStore, setNotice, setResumePrompt, switchWs, workspaces })
const activeWsName = () => {
const w = workspaces.find((x) => x.id === activeWsId)
return (w && w.name) || '工作台'
}
const saveRecoveryKey = 'iwb_web_save_recovery'
const rememberSaveRecovery = (snapshot, error, wsId) => {
const recovery = { at: Date.now(), snapshot, error: iwErrorFrom(error, 'storage'), wsId: wsId || sessionsStore.getActiveId() || '' } // S7:记录归属画布
refs.saveRecovery = recovery
LocalStore.set(saveRecoveryKey, recovery)
setSaveRecovery(recovery)
return recovery
}
const clearSaveRecovery = () => {
refs.saveRecovery = null
LocalStore.remove(saveRecoveryKey)
setSaveRecovery(null)
}
const retrySaveRecovery = () => {
if (!refs.saveRecovery) return
const r = refs.saveRecovery
saveNow({ nodes: r.snapshot.nodes, edges: r.snapshot.edges, groups: r.snapshot.groups })
}
// saveNow 已搬到 src/workbench-logic.js(2026-10-29):每次调用现取闭包值,不会有陈旧闭包。
const saveNow = async (override, requestedWsId) => IWWorkbenchLogic.saveNow({ activeWsId, activeWsIdRef, applyLatest, clearSaveRecovery, composeWorkspaceList, edges, groups, nodes, refs, rememberSaveRecovery, saveDebounced, server, sessionsStore, setNotice, setSaveState, setWorkspaces, setWsRev, workspaces, wsRev, wsRevRef }, override, requestedWsId)
// 统一画布 Store:所有节点/连线/分组写入都经过同一快照边界。
// refs 是实时读模型,React state 是渲染投影,saveNow 只接收同一份快照,避免异步 setState 竞态。
const ExternalCanvasStore = typeof window !== 'undefined' && window.IWBCanvasStore
const CanvasStoreCore = ExternalCanvasStore && typeof ExternalCanvasStore.create === 'function'
? ExternalCanvasStore.create({ initialState: { nodes, edges, groups } })
: null
const CanvasStore = {
snapshot() {
return CanvasStoreCore ? CanvasStoreCore.getState() : { nodes: refs.nodes, edges: refs.edges, groups: refs.groups }
},
replace(nextNodes, nextEdges, nextGroups, options) {
// 未显式传入的部分一律取 refs(实时读模型),不能取 this.snapshot():
// CanvasStoreCore 每次渲染都会重建,任何被「挂载期闭包」捕获的旧 core 都携带着
// 页面载入时的 edges/groups,会把用户之后的增删改回滚进 refs 并落盘。
const snapshot = {
nodes: nextNodes !== undefined ? nextNodes : refs.nodes,
edges: nextEdges !== undefined ? nextEdges : refs.edges,
groups: nextGroups !== undefined ? nextGroups : refs.groups,
}
if (CanvasStoreCore) CanvasStoreCore.replace(snapshot, { persist: !options || options.persist !== false })
refs.nodes = snapshot.nodes
refs.edges = snapshot.edges
refs.groups = snapshot.groups
if (nextNodes !== undefined) setNodes(snapshot.nodes)
if (nextEdges !== undefined) setEdges(snapshot.edges)
if (nextGroups !== undefined) setGroups(snapshot.groups)
if (!options || options.persist !== false) saveDebounced(snapshot)
return snapshot
},
updateNodes(updater, options) {
const next = typeof updater === 'function' ? updater(refs.nodes) : updater
return this.replace(next, undefined, undefined, options)
},
updateNodePositions(positionMap, options) {
const map = positionMap || {}
let changed = false
const next = refs.nodes.map((n) => {
const pos = map[n.id]
if (!pos || (n.x === pos.x && n.y === pos.y)) return n
changed = true
return Object.assign({}, n, { x: pos.x, y: pos.y })
})
// 网格吸附时多个指针帧常落在相同坐标;不触发无意义的全画布渲染。
return changed ? this.replace(next, undefined, undefined, options) : this.snapshot()
},
updateEdges(updater, options) {
const next = typeof updater === 'function' ? updater(refs.edges) : updater
return this.replace(undefined, next, undefined, options)
},
updateGroups(updater, options) {
const next = typeof updater === 'function' ? updater(refs.groups) : updater
return this.replace(undefined, undefined, next, options)
},
}
const commitCanvas = (nextNodes, nextEdges, nextGroups) => {
iwbDebugCounter('commitCanvas', {
nodes: nextNodes !== undefined ? nextNodes.length : refs.nodes.length,
edges: nextEdges !== undefined ? nextEdges.length : refs.edges.length,
groups: nextGroups !== undefined ? nextGroups.length : refs.groups.length,
})
return CanvasStore.replace(nextNodes, nextEdges, nextGroups)
}
const saveDebounced = (snapshot) => {
iwbDebugCounter('saveDebounced', { explicit: !!snapshot })
clearTimeout(refs.saveTimer)
refs.savePending = true // 有待保存修改:刷新/关闭前兜底同步保存(防 700ms 内刷新丢失)
// 画布任意变更(含拖动/输入等高频操作)都合并到一次保存;snapshot 取最后一次触发时的状态
// v3.87.10:打字期间把落盘再往后推(输入中序列化 43 块画板会明显卡顿;本来就是停顿才落盘,这里更从容)
const delay = (historyStore && historyStore.isTyping()) ? 2600 : 1500
refs.saveTimer = setTimeout(() => { refs.savePending = false; snapshot ? saveNow(snapshot) : saveNow() }, delay) // 懒保存:停顿才落盘;刷新/关闭前 flush 兜底不丢
}
// 刷新/关闭前兜底:有待保存修改或保存中 → 同步写 localStorage(Web 数据层本地存储,
// 直接落盘不依赖 async POST,保证刷新不丢)
useEffect(() => {
const flush = () => {
if (!(refs.savePending || refs.saving)) return
if (refs.saveTimer != null) { clearTimeout(refs.saveTimer); refs.saveTimer = null }
try {
const wsId = activeWsIdRef.current || activeWsId
// S7:合成所有打开 session 的工作副本(D1),并逐节点深拷贝 data
// (stripBigDataUrlsSync 就地替换引用,不能污染 session 内存态)
const list = composeWorkspaceList().map((w) => ({
...w,
nodes: ((w && w.nodes) || []).map((n) => ({ ...n, data: Object.assign({}, (n && n.data) || {}) })),
edges: (w && w.edges) ? w.edges.slice() : [],
groups: (w && w.groups) ? w.groups.slice() : [],
}))
// 同步剥离大 dataURL → IDB 引用:localStorage 只落轻量数据,刷新/关闭不因 5MB 配额整份丢失
// (IDB 里的大图由保存路径用相同确定性 key 写入;若防抖窗口内尚未写入,仅该张图缺,其余完好)
stripBigDataUrlsSync(list, true) // best-effort 同步写 IDB:防抖窗口内刷新也不丢图
const ok = WorkspaceStore.write({ schemaVersion: SchemaVersions.workspace, workspaces: list, activeId: wsId, rev: ((WorkspaceStore.read(null) || {}).rev || 0) + 1 }) // rev 递增:其它标签页靠轮询它感知这次兜底落盘(与 wApi('workspaces') 的 prev.rev + 1 一致)
if (!ok) rememberSaveRecovery({ nodes: refs.nodes, edges: refs.edges, groups: refs.groups }, iwError('storage', '离开页面前的本地保存失败'), wsId)
} catch (e) { /* 容量超限忽略 */ }
}
const confirmLeave = (e) => {
flush()
if (!refs.saveRecovery) return
e.preventDefault()
e.returnValue = '当前画布尚未安全保存,离开后可从恢复记录重试保存。'
return e.returnValue
}
const onVis = () => { if (document.visibilityState === 'hidden') flush() }
window.addEventListener('beforeunload', confirmLeave)
window.addEventListener('pagehide', flush)
window.addEventListener('visibilitychange', onVis)
return () => { window.removeEventListener('beforeunload', confirmLeave); window.removeEventListener('pagehide', flush); window.removeEventListener('visibilitychange', onVis) }
}, [])
// ── 画布编辑命令集(撤销历史 / 节点编辑 / 分组 / 新增定位 / 图库刷新)已外移到
// src/runtime-workbench-logic.js.createWorkbenchCommands(2026-11-06)。
// 位置保持原位:消费方都在其后,避免渲染期提前访问。
let wbCmdCache = null
const wbCmd = () => wbCmdCache || (wbCmdCache = IWWorkbenchLogic.createWorkbenchCommands({ APP_VERSION, CLIPBOARD_KEY, CLIPBOARD_TTL_MS, CanvasGeometry, CanvasHistory, CanvasOps, CanvasStore, DEFAULTS, IDB, NODE_H, NODE_HEAD_H, NODE_W, api, cacheDoneUrls, cancelRunsFor, canvasEl, canvasSize, cloneNodeDefaults, commitCanvas, containsBigDataUrl, edges, groupPadOf, groups, hOf, hasGroupPad, hasNodeTitle, hydrateGroupSnapshot, isBigDataUrl, isImageProducer, nodeGroupGroups, nodeTypeH, nodeWidth, nodes, outputRequestSeq, outputs, pluginTypeId, prepareGroupSnapshotForStorage, promptGroups, prompts, refs, saveNow, selRef, sessionsStore, setNodeGroupGroups, setNotice, setOutputs, setOutputsInfo, setPromptGroups, setPrompts, setSavedGroups, setSel, setSelEdge, setViewport, showToast, stripBigValueSync, uid, wBoardNeedsHydrate, wCacheKeyOf, wClipDrop, wClipReadLs, wClipValid, wEnsureImgUrl, wHydrateWorkspace, wImportImage, wUnhydrateWorkspace, CanvasActions, CanvasNodeFactory, wPluginNodeVariants, onSweptE2E: (n) => { if (typeof window !== 'undefined' && window.__IWB_E2E__ === true) window.__IWB_E2E_SWEPT__ = n }, onNodeUpdateE2E: () => { if (typeof window !== 'undefined' && window.__IWB_E2E__ === true) window.__IWB_E2E_UPDATES__ = (window.__IWB_E2E_UPDATES__ || 0) + 1 } }))
const historyStore = new Proxy({}, { get: (_t, k) => { const v = wbCmd().historyStore; const f = v[k]; return typeof f === 'function' ? f.bind(v) : f } })
const { historySnapHasBigImage, historySnapshotBytes } = CanvasHistory // 块外仍被引用的历史判据
const HISTORY_IMG_REF_FIELDS = (...a) => wbCmd().HISTORY_IMG_REF_FIELDS(...a)
const historyRefUsable = (...a) => wbCmd().historyRefUsable(...a)
const historyRefData = (...a) => wbCmd().historyRefData(...a)
const historyRawSnapshot = (...a) => wbCmd().historyRawSnapshot(...a)
const pushHistory = (...a) => wbCmd().pushHistory(...a)
const pushHistoryDebounced = (...a) => wbCmd().pushHistoryDebounced(...a)
const restore = (...a) => wbCmd().restore(...a)
const undo = (...a) => wbCmd().undo(...a)
const redo = (...a) => wbCmd().redo(...a)
const UNDO_KEYS = (...a) => wbCmd().UNDO_KEYS(...a)
const updateNode = (...a) => wbCmd().updateNode(...a)
const clearGenResults = (...a) => wbCmd().clearGenResults(...a)
const deleteNodes = (...a) => wbCmd().deleteNodes(...a)
const deleteEdge = (...a) => wbCmd().deleteEdge(...a)
const copyOffset = (...a) => wbCmd().copyOffset(...a)
const duplicateNodes = (...a) => wbCmd().duplicateNodes(...a)
const floatbarRefPaste = (...a) => wbCmd().floatbarRefPaste(...a)
const outResultUrls = (...a) => wbCmd().outResultUrls(...a)
const copyNodes = (...a) => wbCmd().copyNodes(...a)
const stageClip = (...a) => wbCmd().stageClip(...a)
const pasteGraph = (...a) => wbCmd().pasteGraph(...a)
const readClipboardGraph = (...a) => wbCmd().readClipboardGraph(...a)
const pasteCopiedNodes = (...a) => wbCmd().pasteCopiedNodes(...a)
const clearClipboard = (...a) => wbCmd().clearClipboard(...a)
const cutNodes = (...a) => wbCmd().cutNodes(...a)
const groupOf = (...a) => wbCmd().groupOf(...a)
const makeGroup = (...a) => wbCmd().makeGroup(...a)
const ungroup = (...a) => wbCmd().ungroup(...a)
const ungroupNode = (...a) => wbCmd().ungroupNode(...a)
const joinGroupOf = (...a) => wbCmd().joinGroupOf(...a)
const renameGroup = (...a) => wbCmd().renameGroup(...a)
const duplicateGroup = (...a) => wbCmd().duplicateGroup(...a)
const saveGroupSnapshot = (...a) => wbCmd().saveGroupSnapshot(...a)
const saveSelectionAsGroup = (...a) => wbCmd().saveSelectionAsGroup(...a)
const instantiateGroup = (...a) => wbCmd().instantiateGroup(...a)
const loadSavedGroups = (...a) => wbCmd().loadSavedGroups(...a)
const findSpot = (...a) => wbCmd().findSpot(...a)
const placeAtDrop = (...a) => wbCmd().placeAtDrop(...a)
const addNode = (...a) => wbCmd().addNode(...a)
const addPluginNode = (...a) => wbCmd().addPluginNode(...a)
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 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))
if (prep.remoteOnly) showToast('已插入 ' + added.length + ' 张(其中 ' + prep.remoteOnly + ' 张取不到本地字节,按原链接插入,可能无法标注)', 'err')
else showToast('已插入 ' + added.length + ' 张到画布')
return added.length
}
const loadDemo = (...a) => wbCmd().loadDemo(...a)
const doFit = (...a) => wbCmd().doFit(...a)
// 节点数据规范化(含旧版迁移)—— 纯逻辑,已收编到 src/canvas-normalize.js(P2-9 第一片)
const { normalizeNodes, normalizeEdges, normalizeGroups, migrateGenTaskIds } = CanvasNormalize
const loadWsInto = (w, noFit) => {
const id = (w && (w.id || w.wsId)) || '' // S5:兼容 workspace 与 session 两种形态
const ns = normalizeNodes(w && w.nodes)
if (GenerationResults) GenerationResults.warmThumbs(ns, (k) => outThumbCache.has(k), (idb, url) => { IDB.get(idb).then((v) => { if (typeof v === 'string' && v.length > 20) { outThumbCacheSet(url, v); if (wThumbBump) wThumbBump() } }).catch(() => {}) })
const es = normalizeEdges(w && w.edges, new Set(ns.map((n) => n.id)))
const gs = normalizeGroups(w && w.groups)
if (migrateGenTaskIds(ns, es)) { CanvasStore.replace(ns, es, gs, { persist: false }); saveNow() } // 迁移后同步 refs 再保存(saveNow 读统一 Store 快照)
else CanvasStore.replace(ns, es, gs, { persist: false })
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(不再全局清空)
if (historyStore) { historyStore.setActive(refs.history); historyStore.discardPending() } // 切画板:丢弃未入栈的防抖快照(避免旧板快照串到新板)
refs.historyWsId = id // v3.87.8:跨画板恢复守卫与快照标记用
// 同步刷新(noFit)保留已测量高度(否则节点尺寸跳变 → 端口/连线错位);
// 切换工作台只裁剪掉不属于新画板的 id(原地删键,为什么不能整表清空见 pruneMeasured 注释)
if (!noFit && CanvasGeometry) CanvasGeometry.pruneMeasured(refs.measuredH, ns)
// 同步刷新(noFit)不重置视口,避免画布漂移动画;切换工作台/首次加载保持适应视图
if (ns.length && !noFit) {
// S5:优先 session 视口(内存态,比 localStorage 新),再 localStorage 兜底,最后 doFit
const sessVp = sess && sess.viewport
if (sessVp && typeof sessVp.scale === 'number') setViewport(sessVp)
else {
let savedVp = null
try { savedVp = lsGet('iwb_viewport_' + id, null) } catch (e) { /* ignore */ }
if (savedVp && typeof savedVp.scale === 'number') setViewport(savedVp)
else doFit(ns)
}
}
setTimeout(() => { refs.syncing = false }, 1200)
}
// 工作区列表写回族(persistWs / duplicateWs)已搬到 src/runtime-workbench-logic.js(2026-11-16 棘轮腾位)。
// 每渲染重建一次,语义与原 const 一致;activeWsId/wsRev 取当次渲染值,与原来闭包捕获的完全一样。
// uniqueWsCopyName 不在 app.js 留包装:模块内只有 duplicateWs 用,直接在下面传箭头,少一个中间层。
const { persistWs, duplicateWs } = IWWorkbenchLogic.createWorkspaceListActions({
refs, workspaces, activeWsId, wsRev, composeWorkspaceList, api, GenerationResults, CrashLog, APP_VERSION,
setWsRev, bcNotify, setWorkspaces, uid, showToast,
uniqueWsCopyName: (list, base) => WorkspaceList.uniqueCopyName(list, base),
})
// 我的画布:批量模式切换选中 / 设置画布分类
const toggleHomeSel = (id) => setHomeSelectedWs((xs) => (xs.includes(id) ? xs.filter((x) => x !== id) : xs.concat([id])))
const setWsCategory = (id, cat) => { const list = WorkspaceList.assignCategory(refs.workspaces || workspaces, id, cat); setWorkspaces(list); persistWs(list, activeWsId) }
const batchAssignCategory = (ids, cat) => { const list = WorkspaceList.assignCategory(refs.workspaces || workspaces, ids, cat); setWorkspaces(list); persistWs(list, activeWsId) }
const toggleStarWs = (id) => { const list = WorkspaceList.toggleStar(refs.workspaces || workspaces, id); setWorkspaces(list); persistWs(list, activeWsId) }
// 回收站:软删 / 恢复 / 彻底删除 / 清空
const trashWs = (id) => { const list = WorkspaceList.setDeleted(refs.workspaces || workspaces, id, true); setWorkspaces(list); persistWs(list, activeWsId) }
const restoreWs = (id) => { const list = WorkspaceList.setDeleted(refs.workspaces || workspaces, id, false); setWorkspaces(list); persistWs(list, activeWsId) }
// 回收站的删除语义(彻底删除 / 清空)已收编到 src/workspace-purge.js(v3.24.76):
// 它必须同时清标签 / session / 装载画板 —— 这段过去只写在一段没人调用的 deleteWs 里。
const purgeApi = () => IWBWorkspacePurge.create({
WorkspaceList, refs, workspaces, openTabs, setOpenTabs, sessionsStore, loadedBoards: wLoadedBoards,
releaseImgUrlsForSession: wReleaseImgUrlsForSession, purgeIntent: wPurgeIntent, setWorkspaces, persistWs, showToast,
activeWsId, setActiveWsId, loadWsInto, hydrateAndReload,
})
const purgeWs = (id) => purgeApi().purgeWs(id)
const emptyTrash = () => purgeApi().emptyTrash()
// 分类聚合(含空分类,localStorage)+ 新建/重命名
const catExtras = (() => { try { const v = lsGet('iwb_home_cats', []); return Array.isArray(v) ? v.filter(Boolean) : [] } catch (e) { /* ignore */ } return [] })()
const wsCategories = WorkspaceList.categories(refs.workspaces || workspaces, catExtras)
const addCategory = () => { td.open({ title: '新建分类', placeholder: '新分类名称', onSubmit: (nm) => { const next = Array.from(new Set([...catExtras, nm])); try { lsSet('iwb_home_cats', next) } catch (e) { /* ignore */ } setHomeView('cat:' + nm) } }) }
const renameCategory = (oldName) => { if (!isCatView) return; const cur = homeView.slice(4); td.open({ title: '重命名分类', value: cur, onSubmit: (nn) => { if (nn === cur) return; const list = (refs.workspaces || workspaces).map((w) => (w.category === cur ? { ...w, category: nn } : w)); setWorkspaces(list); persistWs(list, activeWsId); const next = Array.from(new Set([...(refs.workspaces || workspaces).filter((w) => !w.deleted).map((w) => (w || {}).category).filter(Boolean), ...catExtras, nn])).map((c) => (c === cur ? nn : c)); try { lsSet('iwb_home_cats', next) } catch (e) { /* ignore */ } setHomeView('cat:' + nn) } }) }
// 右侧标题:分类名 / 最近使用 / 收藏 / 未分类 / 回收站
const isCatView = homeView.indexOf('cat:') === 0
const homeTitle = homeView === 'recent' ? '最近使用' : homeView === 'starred' ? '收藏' : homeView === 'none' ? '未分类' : homeView === 'trash' ? '回收站' : (isCatView ? homeView.slice(4) : '画布库')
// 视图过滤(纯逻辑收编到 src/workspace-list.js)
const shownWs = WorkspaceList.filterView(refs.workspaces || workspaces, { view: homeView, search: homeSearch })
// 侧栏计数:最近使用/收藏/未分类/各分类/回收站(纯逻辑收编到 src/workspace-list.js)
const sideCounts = WorkspaceList.counts(refs.workspaces || workspaces)
const sideCatCount = (c) => WorkspaceList.countInCategory(refs.workspaces || workspaces, c)
// 按需 hydrate:只解析目标画板的大图(其余画布保持 {__idb}/{__cache} 引用形态),
// 解析完成后用真实图片重载画布(noFit=true 保留视口)。切画布 / 跨标签同步都走这里。
const hydrateBoardInto = (id, listArg) => {
const list = listArg || refs.workspaces || workspaces || []
const target = list.find((w) => w.id === id)
if (!target) return Promise.resolve(null)
if (!wBoardNeedsHydrate(target)) { wTouchLoadedBoard(id, target); return Promise.resolve(target) }
return wLoadBoard(target, list).catch(() => target)
}
// v3.87.17:离开画布视图(回「我的画布」/首页)时降回引用释放图片内存。
// S14(多标签):只释放"不在打开标签里"的画布——打开标签的 hydrate/objectURL 保留(切回即用、不闪黑图);
// 关闭标签时由 closeTab 单独释放该画板。
useEffect(() => {
if (shellView === 'canvas') {
const id = activeWsIdRef.current
if (id && !wLoadedBoards.some((it) => it && it.id === id)) { try { hydrateAndReload(id, refs.workspaces) } catch (e) { /* ignore */ } }
return
}
const openSet = new Set(openTabsRef.current || [])
const list = (refs.workspaces || []).slice()
const survivors = []
for (const it of wLoadedBoards.slice()) {
if (it && openSet.has(it.id)) { survivors.push(it); continue } // S14:打开标签保留
const live = list.find((x) => x && x.id === it.id) || it.w
if (typeof window !== 'undefined' && window.__IWB_E2E__ === true) window.__IWB_E2E_UNHYDRATES__ = (window.__IWB_E2E_UNHYDRATES__ || 0) + 1
try { wUnhydrateWorkspace(live) } catch (e) { /* 降级失败不影响视图切换 */ }
}
wLoadedBoards.length = 0
for (const it of survivors) wLoadedBoards.push(it)
// C3/S14:只回收"不在打开标签里"的 objectURL(打开标签的图保持可用;字节仍在 IDB/Cache)
try {
const keepKeys = new Set()
for (const sid of openSet) {
const s = sessionsStore.get(sid)
// 刚刷新过页面时活动画布的 session 还没建(S1 的会话是在"打开画布"这个动作里创建的)
// ⇒ 回落读装载列表里的那份,否则打开标签的图会被当孤儿回收(切回时静默重解析一次)。
const ns = s ? (s.nodes || []) : (((refs.workspaces || []).find((x) => x && x.id === sid) || {}).nodes || [])
wCollectImgRefKeys({ nodes: ns }, keepKeys)
}
const toRelease = Array.from(wImgUrlByRef.keys()).filter((k) => !keepKeys.has(k))
if (toRelease.length) wReleaseImgUrls(toRelease)
} catch (e) { /* 回收失败不影响视图切换 */ }
}, [shellView])
const hydrateAndReload = (id, listArg) => {
if (typeof window !== 'undefined' && window.__IWB_E2E__ === true) window.__IWB_E2E_HYDRATE_RELOADS__ = (window.__IWB_E2E_HYDRATE_RELOADS__ || 0) + 1
hydrateBoardInto(id, listArg).then((w) => {
if (!w || wBoardNeedsHydrate(w)) return
if (activeWsIdRef.current !== id) return
loadWsInto(w, true)
}).catch(() => { /* hydrate 失败保留引用形态 */ })
}
// 打开画布编辑器:无论是否已激活都进入编辑器;已激活时不重复切换数据
const openCanvasEditor = (id) => {
const target = workspaces.find((w) => w.id === id)
if (!target) return
if (refs.wsDoneHints) delete refs.wsDoneHints[id] // 切到该画布:结果已可见,清掉完成态圆点
setShellView('canvas'); setDrawerOpen(false); setEnteringWs(true)
if (id !== activeWsId) {
syncActiveSession() // S5:确保当前 session 是最新
const cur = { id: activeWsId, name: activeWsName(), nodes: activeWsData().nodes, edges: activeWsData().edges, groups: activeWsData().groups }
const list = WorkspaceList.upsert(refs.workspaces || workspaces, activeWsId, cur)
refs.workspaces = list
setWorkspaces(list)
}
// S5:从 session 加载(而非列表),保住未保存的编辑(D1:session 是工作副本)
const sess = ensureSessionFor(id, target)
setActiveWsId(id); openTab(id) // S12:打开即成为标签
// 先用引用形态渲染画布结构(节点/连线立即出现),大图解析完成后无闪烁重载
loadWsInto({ id, name: target.name, nodes: sess.nodes, edges: sess.edges, groups: sess.groups })
// 记录"最近使用"
const touched = (refs.workspaces || workspaces).map((w) => (w.id === id ? { ...w, lastUsed: Date.now() } : w))
refs.workspaces = touched; setWorkspaces(touched)
window.setTimeout(() => setEnteringWs(false), 400)
persistWs(touched, id)
hydrateAndReload(id, touched)
}
// 返回画布库:把当前画布最新内容同步回 workspaces 状态,避免卡片计数/内容停留在旧数据
const syncActiveWs = () => {
if (!activeWsId) return
const cur = { id: activeWsId, name: activeWsName(), nodes: refs.nodes, edges: refs.edges, groups: refs.groups }
const list = WorkspaceList.upsert(refs.workspaces || workspaces, activeWsId, cur)
refs.workspaces = list; setWorkspaces(list)
}
// 画布数据源:正处编辑用 refs(实时),返回后 refs 已释放则回退到 workspaces 状态
const activeWsData = () => {
if (refs.nodes.length) return { nodes: refs.nodes, edges: refs.edges, groups: refs.groups }
const w = (workspaces || []).find((x) => x.id === activeWsId)
return { nodes: (w && w.nodes) || [], edges: (w && w.edges) || [], groups: (w && w.groups) || [] }
}
const goHome = () => {
setCanTitleEdit(false)
syncActiveWs()
setWsMoreOpen(false); setDrawerOpen(false); setShellView('home')
}
const switchWs = (id) => {
if (refs.wsDoneHints) delete refs.wsDoneHints[id] // 切到该画布:结果已可见,清掉完成态圆点
if (id === activeWsId) { openTab(id); setShellView('canvas'); setEnteringWs(true); window.setTimeout(() => setEnteringWs(false), 200); return } // openTab:激活画布的标签可能已被关掉(重新点开要回标签条)
syncActiveSession() // S5:确保当前 session 是最新(再保险;每次渲染已同步)
const cur = { id: activeWsId, name: activeWsName(), nodes: activeWsData().nodes, edges: activeWsData().edges, groups: activeWsData().groups }
const list = WorkspaceList.upsert(refs.workspaces || workspaces, activeWsId, cur)
refs.workspaces = list
setWorkspaces(list)
const target = list.find((w) => w.id === id)
if (!target) return
// S5:从 session 加载(而非列表),保住未保存的编辑(D1:session 是工作副本)
const sess = ensureSessionFor(id, target)
setActiveWsId(id); openTab(id); setShellView('canvas') // 切换标签:session 数据在内存,瞬时切换(不走 enteringWs 动画)
loadWsInto({ id, name: target.name, nodes: sess.nodes, edges: sess.edges, groups: sess.groups })
persistWs(list, id)
hydrateAndReload(id, list)
}
const newWs = () => {
const cur = { id: activeWsId, name: activeWsName(), nodes: activeWsData().nodes, edges: activeWsData().edges, groups: activeWsData().groups }
const list = WorkspaceList.upsert(workspaces, activeWsId, cur).concat([{ id: uid('ws'), name: '工作台 ' + (workspaces.length + 1), nodes: [], edges: [], groups: [], category: homeView.indexOf('cat:') === 0 ? homeView.slice(4) : '', starred: false, deleted: false, lastUsed: Date.now() }])
refs.workspaces = list
setWorkspaces(list)
const target = list[list.length - 1]
setActiveWsId(target.id); openTab(target.id) // S13:新建即成为标签(修复:点+后标签栏不及时显示)
setShellView('canvas'); setEnteringWs(true); loadWsInto(target); window.setTimeout(() => setEnteringWs(false), 400)
persistWs(list, target.id)
}
const renameWs = (id, name) => {
const nm = (name || '').trim()
if (!nm) { setWsRenameId(null); return }
const list = WorkspaceList.rename(workspaces, id, nm)
setWorkspaces(list)
setWsRenameId(null)
persistWs(list, id)
}
// ctx 在 **effect 执行时** 求值(渲染期求值会撞后声明 const 的 TDZ)
// v3.26.117:把活动画板里的大 base64 就地引用化(写盘成功才替换,失败原样保留)。
// 这是「内存上来不下降」里最不该存在的一块:节点里躺着 10MB 的 dataURL,保存时又被整份复制进画板列表。
async function wRefActiveBoardNow() {
const list = (refs && refs.nodes) || []
let changed = 0
const next = []
for (const n of list) {
if (!n || !n.data || !containsBigDataUrl(n.data)) { next.push(n); continue }
try {
const d = await wRefValueAsync(n.data, n.id || 'n', 'data')
if (d && d !== n.data) { next.push(Object.assign({}, n, { data: d })); changed++ } else next.push(n)
} catch (e) { next.push(n) }
}
if (changed) { try { commitCanvas(next, refs.edges, refs.groups) } catch (e) { /* ignore */ } }
return changed
}
// v3.26.117:真正的「回收」(用户症状:内存上来后不下降)。四步都是可重建的缓存或可反推的引用形态,绝不删用户数据。
async function wReclaimMemoryNow(reason, opts) {
const mb = (x) => Math.round((Number(x) || 0) / 104857.6) / 10
const heapMB = () => { try { return (typeof performance !== 'undefined' && performance.memory) ? mb(performance.memory.usedJSHeapSize) : -1 } catch (e) { return -1 } }
const before = heapMB()
const freed = { history: 0, thumbs: 0, blobs: 0, boards: 0, refs: 0 }
// ① 撤销历史(纯内存快照)
try { const st = (refs && refs.history && refs.history.stack) || []; freed.history = st.length; if (st.length) { refs.history = { stack: [], idx: -1 }; if (historyStore) historyStore.setActive(refs.history) } } catch (e) { /* ignore */ }
// ② 非活动画板降回引用形态 + 回收它们的 objectURL(字节仍在磁盘/IDB)
try {
const keep = [activeWsIdRef && activeWsIdRef.current]
const n0 = wLoadedBoards.length
await wEvictLoadedBoards(keep, refs.workspaces, 1, true)
freed.boards = Math.max(0, n0 - wLoadedBoards.length)
} catch (e) { /* ignore */ }
// ③ 活动画板里的大 base64 就地引用化
try { freed.refs = await wRefActiveBoardNow() } catch (e) { /* ignore */ }
// ④ 图片字节缓存压到 0 + 缩略图缓存清空(都可由磁盘/IDB 重建)
try { const S = wImageBlobStore(); if (S && typeof S.trim === 'function') freed.blobs = S.trim(0) } catch (e) { /* ignore */ }
// 自动回收保留显示缩略图(清了会立刻触发可见图片重载);手动回收才清。
if (!opts || !opts.keepThumbs) {
try { freed.thumbs = displayThumbs.size; displayThumbs.clear() } catch (e) { /* ignore */ }
try { outThumbCache.clear() } catch (e) { /* ignore */ }
}
try { if (typeof wThumbBump === 'function') wThumbBump() } catch (e) { /* ignore */ }
const after = heapMB()
try {
if (CrashLog && typeof CrashLog.record === 'function') CrashLog.record('mem-reclaim', { scope: 'memory', message: '内存回收 ' + (before < 0 ? '—' : before + 'MB → ' + after + 'MB') + (reason ? '(' + reason + ')' : ''), version: APP_VERSION, extra: { freed: freed, before: before, after: after } })
} catch (e) { /* ignore */ }
return { before: before, after: after, freed: freed }
}
const bootCtx = () => ({ APP_VERSION, CanvasStore, CrashLog, RuntimeMetrics, RuntimeRecovery, W_PURGE_ORIG_FLAG, activeWsIdRef, api, commitCanvas, displayThumbs, doFit, historySnapshotBytes, historyStore, hydrateAndReload, loadDemo, loadSavedGroups, lsGet, lsRawGet, lsRawSet, lsRemove, lsSet, migrateGenTaskIds, normalizeEdges, normalizeGroups, normalizeNodes, openTab, openTabsRef, outThumbCache, refreshOutputs, refs, setActiveWsId, setConfig, setLoaded, setMemUi, setPromptGroups, setPrompts, setResumePrompt, setServer, setWorkspaces, setWsRev, showToast, wDiagStats, wEvictLoadedBoards, wLoadedBoards, wMemoryComposition, wPreloadDisplayThumbs, wPurgeOutputOriginals, wReclaimMemoryNow, wSafeCompressStart })
IWBBootLoad.useBootLoad(bootCtx)
// ── 自动同步(applyLatest / syncOnce / 轮询 + BroadcastChannel)已外移到 src/runtime-workbench-logic.js(2026-11-06)──
const wsRevRef = useRef(null), wsAppliedRevRef = useRef(null) // 后者=已应用过的服务端 rev(同一 rev 不重复重载/水合)
wsRevRef.current = wsRev
// ctx 在**调用时**求值(不能渲染期 Object.assign:后定义的 const 会撞 TDZ)
const syncCtx = () => ({ refs, api, WorkspaceList, GenerationResults, CrashLog, RuntimeChannel, sessionsStore, activeWsIdRef, activeWsName, wsRevRef, wsAppliedRevRef, setWsRev, setWorkspaces, setActiveWsId, setSaveState, refreshSessionsFromList, loadWsInto, hydrateAndReload, APP_VERSION, isSyncPaused: () => wSyncPaused, lastSelfSaveAt: () => wLastSelfSaveAt, saveNow, onSyncApplied: () => { if (typeof window !== 'undefined' && window.__IWB_E2E__ === true) window.__IWB_E2E_SYNC_APPLY__ = (window.__IWB_E2E_SYNC_APPLY__ || 0) + 1 } })
const applyLatest = (r) => IWWorkbenchLogic.applyLatestSync(syncCtx(), r)
const syncOnce = () => IWWorkbenchLogic.syncOnceNow(syncCtx())
useEffect(() => { if (!loaded) return; return IWWorkbenchLogic.startSyncPolling(syncCtx()) }, [loaded])
useEffect(() => {
iwbDebugCounter('canvasEffect', { nodes: nodes.length, edges: edges.length, groups: groups.length })
// 文案组合节点:来源拼接 → 更新自身 combined → 推送下游 textout(无 combine 节点时跳过遍历)
if (nodes.some((x) => x.type === 'combine')) for (const cn of nodes) {
if (cn.type !== 'combine') continue
if (cn.data && cn.data.enabled === false) {
// 停用组合节点:文本与图片一样不透传——清除其曾推送到下游 textout 的文本
for (const e of edges) {
if (e.from !== cn.id) continue
const dst = nodes.find((n) => n.id === e.to)
if (!dst || dst.type !== 'textout') continue
const pkey = cn.id + '::' + dst.id
if (refs.combinePushed[pkey] !== undefined) {
if ((dst.data.text || '') === refs.combinePushed[pkey]) updateNode(dst.id, { text: '' })
delete refs.combinePushed[pkey]
}
}
continue
}
// 按入边遍历:连接(batch)边只取该边对应来源的文本(不展开全部)
// 方案1:组合文本按「真实文本源」坐标统一排序——relay 透明穿透(转发文本按提示词自身坐标参与排序),
// 拖动中继不再改变组合里的文案顺序;图片仍按自身 X 全局排序(见任务构建 sortByPosition)。
const pairs = []
for (const inE of edges) {
if (inE.to !== cn.id) continue
const srcN = nodes.find((n) => n.id === inE.from)
if (!srcN || (srcN.data && srcN.data.enabled === false)) continue // 停用来源:不参与组合
pairs.push.apply(pairs, combineSourcePairs(srcN, inE, edges, nodes))
}
pairs.sort((a, b) => compareCanvasTextOrder(a.n, b.n))
const texts = pairs.map((p) => p.text)
const csep = (cn.data && cn.data.sep) || RuntimeConstants.combineSep || ', ' // 组合分隔符按节点值,缺省逗号
const cex = String((cn.data && cn.data.extra) || '').trim()
const cpos = (cn.data && cn.data.extraPos) === 'before' ? 'before' : 'after'
const body = texts.join(csep)
const ctext = cpos === 'before'
? (cex ? cex + (body ? csep : '') + body : body)
: body + (cex ? (body ? csep : '') + cex : '')
// 来源全部停用/为空时也把 combined 清空(否则旧文本残留 → 生图仍按旧文本建任务)
if ((cn.data.combined || '') !== ctext) updateNode(cn.id, { combined: ctext })
for (const e of edges) {
if (e.from !== cn.id) continue
const dst = nodes.find((n) => n.id === e.to)
if (!dst || dst.type !== 'textout') continue
if (dst.data && dst.data.enabled === false) continue // 停用 textout:不推送组合文本
const pkey = cn.id + '::' + dst.id
if (refs.combinePushed[pkey] !== ctext && (dst.data.text || '') !== ctext) updateNode(dst.id, { text: ctext })
refs.combinePushed[pkey] = ctext
}
}
// 批量加文案:手动连接的 batch→textout 边同步对应来源的文本(无 batch 节点时跳过遍历)
if (nodes.some((x) => x.type === 'batch')) for (const bn of nodes) {
if (bn.type !== 'batch') continue
if (bn.data && bn.data.enabled === false) {
// 停用连接节点:文本与图片一样不透传——清除其曾推送到下游 textout 的文本
for (const e of edges) {
if (e.from !== bn.id) continue
const dst = nodes.find((n) => n.id === e.to)
if (!dst || dst.type !== 'textout') continue
const pkey = bn.id + '::' + dst.id
if (refs.batchPushed[pkey] !== undefined) {
if ((dst.data.text || '') === refs.batchPushed[pkey]) updateNode(dst.id, { text: '' })
delete refs.batchPushed[pkey]
}
}
continue
}
const bsrcs = edges.filter((e) => e.to === bn.id).map((e) => nodes.find((n) => n.id === e.from)).filter((n) => isBatchSrc(n, edges, nodes) && !(n.data && n.data.enabled === false)).slice().sort((a, b) => (a.y - b.y) || (a.x - b.x))
if (!bsrcs.length) continue
const textOf = (src) => batchJoinedText(bn.data, batchSrcText(src, edges, nodes))
for (const e of edges) {
if (e.from !== bn.id) continue
const dst = nodes.find((n) => n.id === e.to)
if (!dst || dst.type !== 'textout') continue
const src = e.batchSrcId ? bsrcs.find((s) => s.id === e.batchSrcId) : bsrcs[0]
if (!src) continue
const text = textOf(src)
if (text && (dst.data.text || '') !== text) updateNode(dst.id, { text })
refs.batchPushed[bn.id + '::' + dst.id] = text
}
}
// 输出节点过窄自动加宽(窄节点无法展示分组横向布局)。
// 必须写顶层 w:nodeWidth 读 n.w;updateNode({w}) 会把 w 并进 data.w,导致 n.w 恒为 264、
// 条件永不满足 → 节点每次变更都再触发本 effect,造成无限自动保存 + CPU 负担。
let outWidened = false
const outNext = refs.nodes.map((n) => {
if (n.type === 'out' && (n.w || NODE_W) < 420) { outWidened = true; iwbDebugCounter('outputWiden', { id: n.id, width: n.w || NODE_W }); return { ...n, w: 420 } }
return n
})
if (outWidened) commitCanvas(outNext, undefined, undefined)
if (loaded && !(refs.syncing)) {
if (refs.skipInitialPersistence) refs.skipInitialPersistence = false
else saveDebounced()
} else if (refs.savePending) {
// 下面的 cleanup 会取消已排定的保存定时器,而此刻又不能落盘(尚未 loaded,或正在应用远端同步)。
// 必须把这次保存重新排上,否则用户的改动会被静默丢弃。
// 刻意不传快照:到点保存的是实时 refs,绝不会把载入前/同步前的旧数据写回去。
saveDebounced()
}
// 画布整体变更时取消「待保存」定时器(避免把陈旧快照写回,例如 sync 刚应用远端数据);
// 撤销历史由 pushHistoryDebounced 自己防抖合并,这里不能一并清掉,否则最后一次编辑不会入栈。
return () => { clearTimeout(refs.saveTimer); refs.saveTimer = null }
}, [nodes, edges, groups, loaded])
// wheel 缩放 + 画布尺寸跟随(逻辑在 src/runtime-workbench-logic.js.startCanvasZoomAndSize)
useEffect(() => IWWorkbenchLogic.startCanvasZoomAndSize({ canvasEl, refs, setViewport, setCanvasSize, applyViewportDom }), [])
// 选中集合锚点 / 节点是否在组内(公式已外移到 src/runtime-workbench-logic.js)
const viewMetricCtx = () => ({ refs, nodeWidth, hOf, floatbarLift, hasNodeTitle })
const nodeInGroup = (n) => IWWorkbenchLogic.nodeInGroupOf(viewMetricCtx(), n)
const selAnchorOf = (selIds, nodesArr) => IWWorkbenchLogic.selAnchorOf(viewMetricCtx(), selIds, nodesArr)
// pointer & key handlers
// ⋯ 三点菜单:点击菜单外关闭(逻辑在 src/runtime-workbench-logic.js.startWsMoreOutside)
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, 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])
// v2 §7:LLM 润色(自动写回下游文案输出节点;脏链在生图/全部运行时自动先润色)
// runLLM 已搬到 src/runtime-workbench-logic.js(2026-10-29)
const runLLM = async (nodeId) => IWWorkbenchLogic.runLLM({ ensurePolished, nodes, refs, saveNow, setBusy, setNotice, updateNode }, nodeId)
// 生图前确保上游 LLM 链已润色(逻辑在 src/runtime-workbench-logic.js.ensurePolished)
const ensurePolished = (genId) => IWWorkbenchLogic.ensurePolished({ refs, runLLM }, genId)
// 画布运行上下文(保存快照 / 取运行节点 / 合并写回)已外移到 src/runtime-workbench-logic.js(2026-11-06)
const runCtx = () => ({ refs, GenerationResults, api, activeWsIdRef, activeWsId, wsRev, setWsRev, bcNotify, setWorkspaces, CanvasStore })
const saveWorkspaceSnapshot = (workspaceId, override) => IWWorkbenchLogic.saveWorkspaceSnapshot(runCtx(), workspaceId, override)
const runWorkspaceNodes = (workspaceId) => IWWorkbenchLogic.runWorkspaceNodes(runCtx(), workspaceId)
const commitRunNodes = (workspaceId, nextNodes) => IWWorkbenchLogic.commitRunNodes(runCtx(), workspaceId, nextNodes)
// finishGenerationRun 已搬到 src/runtime-workbench-logic.js(2026-10-29)
const finishGenerationRun = (state) => IWWorkbenchLogic.finishGenerationRun({ activeWsIdRef, commitRunNodes, nodes, persistRuns, refs, saveNow, saveWorkspaceSnapshot, setBusy, setProgress, shellViewRef }, state)
// 只结束某一个任务(批量生成中也支持):中断该任务名下所有在飞请求,同批其他任务继续跑
// 分层运行(与生图 runNode 平行):复用同一套运行锁 / 取消控制器 / 跨工作台写回 / 图库归档。
// 不做任务卡那套(清单在节点内),一次调用产出一组图层。
// runLayerNode 已搬到 src/runtime-workbench-logic.js(2026-10-29)
const runLayerNode = async (nodeId) => IWWorkbenchLogic.runLayerNode({ activeWsId, activeWsIdRef, commitRunNodes, groups, refreshOutputs, refs, runWorkspaceNodes, setBusy, setNotice, setProgress }, nodeId)
// 产图节点的统一运行入口:按类型分派(生图走任务卡那套,分层走单次调用)
const runProducer = (nodeId, taskPromptId, onDone, opts) => {
const n = refs.nodes.find((x) => x.id === nodeId)
if (!n) return
// 分层是「一次调用出一组图层」,没有任务卡/变体概念,因此忽略 gen 专属参数
return n.type === 'layer' ? runLayerNode(nodeId) : runNode(nodeId, taskPromptId, onDone, opts)
}
// runNode 已搬到 src/workbench-logic.js(2026-10-29):每次调用现取闭包值,不会有陈旧闭包。
// 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)
// 输出面板「出图」:并发运行全部来源生图节点(每张完成推进汇总进度,不影响其他生图节点)
const runOutSources = async (outId) => {
const out = refs.nodes.find((n) => n.id === outId)
if (!out) return
const gens = refs.edges.filter((e) => e.to === outId).map((e) => refs.nodes.find((n) => n.id === e.from)).filter((n) => isImageProducer(n) && !(n.data && n.data.enabled === false))
if (!gens.length) return
prepareBrowserNotifications()
const busyKey = outId + '::out'
setBusy((b) => ({ ...b, [busyKey]: true }))
setNotice(null)
const totalCount = gens.reduce((n, g) => n + taskCountOf(g), 0)
let done = 0
const tick = setInterval(() => {
setProgress((p) => { const c = p[busyKey]; if (!c) return p; return { ...p, [busyKey]: { ...c, waitMs: Date.now() - c.t0 } } })
}, 1000)
setProgress((p) => ({ ...p, [busyKey]: { done: 0, total: totalCount, groups: gens.length, cur: 0, waitMs: 0, t0: Date.now() } }))
try {
await Promise.all(gens.map((g) => runProducer(g.id, null, (n, ms) => {
done += n
setProgress((p) => {
const c = p[busyKey] || { done: 0, total: totalCount, waitMs: 0 }
const cn = c.n || 0
const avg = (c.avgMs || 0) * cn + (ms || 0)
return { ...p, [busyKey]: { ...c, done, cur: done, waitMs: 0, t0: Date.now(), avgMs: (cn ? avg / (cn + 1) : (ms || 0)), n: cn + 1 } }
})
}, { suppressBrowserNotification: true })))
const fails = done < totalCount
if (fails) setNotice({ type: 'err', text: '出图完成但失败 ' + (totalCount - done) + ' 张(共 ' + totalCount + ' 张,详见各生图节点任务卡错误区)' })
else setNotice({ type: 'ok', text: '✓ 出图完成(' + done + ' 张)' })
notifyBrowserGenerationDone({ total: totalCount, failed: Math.max(0, totalCount - done) })
} catch (e) {
setNotice({ type: 'err', text: String((e && e.message) || e) })
} finally {
clearInterval(tick)
setBusy((b) => ({ ...b, [busyKey]: false }))
setProgress((p) => { const np = { ...p }; delete np[busyKey]; return np })
saveNow()
}
}
const fitView = () => doFit(refs.nodes)
// 供 memo 化的底栏按钮调用(每个渲染刷新引用,回调本身保持稳定):适应视图 / 缩放
refs.fitViewRef = fitView
// 停靠栏就绪/变化时:若当前视口还是「自动适应」的产物(用户没手动缩放/平移),按新占位重新适应一次。
// 动机:启动 doFit 可能早于停靠栏挂载(--iwb-dock-l 首帧为空)⇒ 节点被栏盖住。
React.useEffect(() => {
const onInsets = () => {
if (!refs.nodes || !refs.nodes.length) return
if (!refs.viewport || refs.viewport !== refs.lastAutoFit) return
doFit(refs.nodes)
}
window.addEventListener('iwb:dock-insets', onInsets)
return () => window.removeEventListener('iwb:dock-insets', onInsets)
}, [])
refs.zoomByRef = (dir) => setViewport((v) => (CanvasGeometry ? CanvasGeometry.zoomStep(v, dir, canvasSize.w, canvasSize.h) : v)) // 档位/锚点/上下限见 zoomStep(纯函数,可单测)
const fitSelection = () => {
const nodes = refs.nodes.filter((n) => sel.includes(n.id))
if (!nodes.length) return showToast('请先选择要适配的节点', 'err')
// 选中节点适应当前窗口并居中:让选中节点的包围盒中心落在可视区中心
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
for (const n of nodes) { minX = Math.min(minX, n.x); minY = Math.min(minY, n.y); maxX = Math.max(maxX, n.x + nodeWidth(n)); maxY = Math.max(maxY, n.y + hOf(n)) }
// 标题带在节点外框上方:纳入包围盒(居中适配时自动为其留出空间)
const topNode = nodes.find((n) => n.y === minY)
if (hasNodeTitle(topNode)) minY -= NODE_HEAD_H
const railEl = document.querySelector('.iwb-navrail')
const railW = railEl ? railEl.getBoundingClientRect().width : 0
const libEl = document.querySelector('.iwb-lib')
const libW = (libEl && libEl.getBoundingClientRect().width > 0) ? libEl.getBoundingClientRect().width : 0
const vw = Math.max(120, window.innerWidth - railW - libW - 56)
const vh = window.innerHeight - 56
const scale = Math.max(0.01, Math.min(1.3, Math.min(vw / Math.max(1, maxX - minX), vh / Math.max(1, maxY - minY))))
const cx = (minX + maxX) / 2, cy = (minY + maxY) / 2
setViewport({ x: vw / 2 - cx * scale, y: vh / 2 - cy * scale, scale })
showToast('选中节点已居中适应')
}
// 微调选区:整体吸附到网格;仅在发生重叠时做最小避让,保留原有顺序。
const refineSelection = () => {
if (layoutLocked) return showToast('自动布局已锁定,请先解锁', 'err')
const ids = new Set(sel)
const selected = refs.nodes.filter((n) => ids.has(n.id))
if (!selected.length) return showToast('请先选择要微调的节点', 'err')
const minX = Math.min(...selected.map((n) => n.x)), minY = Math.min(...selected.map((n) => n.y))
const grid = 28
const dx = Math.round(minX / grid) * grid - minX, dy = Math.round(minY / grid) * grid - minY
const next = refs.nodes.map((n) => ids.has(n.id) ? { ...n, x: n.x + dx, y: n.y + dy } : n)
const moving = next.filter((n) => ids.has(n.id)).sort((a, b) => (a.y - b.y) || (a.x - b.x))
const placed = []
for (const n of moving) {
for (const p of placed) {
const overlap = n.x < p.x + nodeWidth(p) && n.x + nodeWidth(n) > p.x && n.y < p.y + hOf(p) && n.y + hOf(n) > p.y
if (overlap) n.x = p.x + nodeWidth(p) + 48
}
placed.push(n)
}
const changed = next.some((n) => { const old = refs.nodes.find((x) => x.id === n.id); return old && (old.x !== n.x || old.y !== n.y) })
if (!changed) return showToast('选中节点已经整齐且没有重叠')
pushHistory()
CanvasStore.replace(next, undefined, undefined, { persist: false })
saveNow({ nodes: next })
showToast('已微调选中节点(保留顺序并消除重叠)')
}
const convertCanvasLocalRefs = async () => {
const targets = refs.nodes.filter((n) => n.type === 'ref' && n.data && n.data.data && !n.data.url)
if (!targets.length) { setNotice({ type: 'ok', text: '当前画布没有需要转换的本地图片' }); return }
if (!(await window.IWBUIConfirm.askOrNative('将转换当前画布中的 ' + targets.length + ' 张本地图片(输出节点生成结果不会处理),继续吗?', { title: '批量转在线链接' }))) return
if (!(await window.IWBUIConfirm.askOrNative('确认开始批量上传吗?上传后这些图片会替换为在线链接,通常无法自动撤回。', { title: '确认上传', okText: '开始上传' }))) return
let ok = 0; const errors = []
for (const n of targets) {
try {
const url = await uploadRefToImageHost(n.data.data, wRawCfg(), n.data.name)
updateNode(n.id, { url, data: null, localName: null, name: url.split('/').pop() || '在线图片' })
ok++
} catch (e) { errors.push((n.data.name || n.id) + ':' + String((e && e.message) || e)) }
}
setNotice({ type: errors.length ? 'err' : 'ok', text: '已转换 ' + ok + '/' + targets.length + ' 张图片' + (errors.length ? ';失败:' + errors.join(';') : '') })
}
// v2 P8:画布导出 / 导入 .iwb.json(校验、二次确认防覆盖)
// exportCanvas moved to src/runtime-workbench-logic.js.createWBExportCanvas (2026-11-06)
let wbxExportCanvas = null
const exportCanvas = (...a) => (wbxExportCanvas || (wbxExportCanvas = IWWorkbenchLogic.createWBExportCanvas({ SchemaVersions, activeWsId, edges, groups, nodes, refs, setNotice, td, wResolveImagesForExport, withoutGenerationResults, workspaces }))).exportCanvas(...a)
const exportSelectedGroup = () => {
if (!sel.length) { setNotice({ type: 'err', text: '请先选择要导出的节点' }); return }
const suggested = '节点组-' + new Date().toISOString().slice(0, 10)
td.open({ title: '导出节点组', value: suggested, okText: '导出', onSubmit: async (nm) => {
const safeName = String(nm).trim().replace(/[\\/:*?"<>|]/g, '_') || suggested
const ids = new Set(sel)
const completeGroups = refs.groups.filter((g) => g.memberIds && g.memberIds.length && g.memberIds.every((id) => ids.has(id))).map((g) => ({ ...g, memberIds: g.memberIds.slice() }))
const selectedNodes = refs.nodes.filter((n) => ids.has(n.id))
const selectedEdges = refs.edges.filter((e) => ids.has(e.from) && ids.has(e.to)).map((e) => ({ ...e }))
const exportedGroupPad = (() => { const g = refs.groups.find((x) => x.memberIds && x.memberIds.length === ids.size && x.memberIds.every((id) => ids.has(id))); return g && hasGroupPad(groupPadOf(g)) ? groupPadOf(g) : null })()
// C3 第2步:节点组导出同样要自带字节(按需解析,不写回画布)
const nodesForExport = await wResolveImagesForExport(withoutGenerationResults({ nodes: selectedNodes }).nodes)
const data = { app: 'image-workbench', version: 2, schemaVersion: SchemaVersions.canvas, exportType: 'group', exportedAt: new Date().toISOString(), exportSummary: { nodes: selectedNodes.length, edges: selectedEdges.length, groups: completeGroups.length }, group: Object.assign({ id: uid('g'), name: safeName, memberIds: sel.slice() }, exportedGroupPad ? { pad: exportedGroupPad } : null), groups: completeGroups, nodes: nodesForExport, edges: selectedEdges }
try {
const blob = new Blob([JSON.stringify(data, null, 1)], { type: 'application/json' })
const outName = safeName.replace(/\\.iwb\\.json$/i, '') + '.iwb.json'
// 统一出口:桌面端弹系统另存为,网页端仍走 <a download>
wSaveBlob(blob, outName)
setNotice({ type: 'ok', text: '已导出节点组:' + outName })
} catch (e) { setNotice({ type: 'err', text: '导出节点组失败:' + String((e && e.message) || e) }) }
} })
}
// importCanvasFile 已搬到 src/runtime-workbench-logic.js(2026-10-29)
const importCanvasFile = (file, fromDrop, dropX, dropY) => IWWorkbenchLogic.importCanvasFile({ canvasSize, commitCanvas, pushHistory, refs, setNotice, setSel }, file, fromDrop, dropX, dropY)
// 网格样式:优先用 src/canvas-grid.js 的贴图(平移只走 transform,不重绘点阵)
// v3.25.74:改为读取外观设置(网格点大小/间距/颜色/开关)—— 之前硬编码 28/1.2,
// 导致设置里的「网格点大小 / 网格间距 / 显示网格」全部失效(用户反馈)。
const readGridOpts = () => {
if (typeof getComputedStyle !== 'function' || typeof document === 'undefined') return { base: 22, dot: 1.4, color: 'rgba(120,128,140,0.55)', on: true }
try {
const cs = getComputedStyle(document.documentElement)
const gap = parseFloat(cs.getPropertyValue('--iwb-grid-gap')) || 22
const dot = parseFloat(cs.getPropertyValue('--iwb-grid-size')) || 1.4
const col = (cs.getPropertyValue('--iwb-grid-dot') || '').trim() || 'rgba(120,128,140,0.55)'
const onv = parseFloat(cs.getPropertyValue('--iwb-grid-on'))
const style = (document.documentElement.getAttribute('data-iwb-grid') || 'dots')
return { base: Math.max(8, gap), dot: Math.max(0.5, dot), color: col, on: !(onv === 0) && style !== 'blank', style }
} catch (e) { return { base: 22, dot: 1.4, color: 'rgba(120,128,140,0.55)', on: true } }
}
refs.gridOpts = readGridOpts()
const gridStyleOf = (x, y, scale) => {
const o = refs.gridOpts || { base: 22, dot: 1.4, color: 'rgba(120,128,140,0.55)', on: true }
if (!o.on) return { display: 'none' }
const G = (typeof window !== 'undefined') ? window.IWBCanvasGrid : null
const st = G && typeof G.styleOf === 'function' ? G.styleOf(x, y, scale, o) : null
if (st) return st
return { backgroundSize: (o.base * scale) + 'px ' + (o.base * scale) + 'px', backgroundPosition: x + 'px ' + y + 'px' }
}
// v3.25.68(借鉴 tldraw 的相机机制):手势期间只改 .iwb-world 的 transform,
// 不 setViewport ⇒ 不触发 React 重渲染 ⇒ 世界层不被标记为脏,WebKit 不必整层重栅格化。
// 松手/停止滚轮后再提交一次 state,保证与 React 渲染值一致。
const applyViewportDom = (x, y, scale) => {
CanvasGeometry.applyViewportDom(canvasEl.el, canvasSize, x, y, scale, refs.gridOpts)
// 边线/节点 canvas:手势期间命令式重画,避免等 React
try { if (typeof refs.edgeCanvasDraw === 'function') refs.edgeCanvasDraw(x, y, scale) } catch (e) { /* ignore */ }
try { if (typeof refs.nodeCanvasDraw === 'function') refs.nodeCanvasDraw(x, y, scale) } catch (e) { /* ignore */ }
}
// LOD 滞回状态:plain 在 <15% 进入、>18% 退出(用 ref 保存,不触发额外渲染)
if (refs.lodPlain === undefined) refs.lodPlain = false
if (!refs.lodPlain && viewport.scale < 0.15) refs.lodPlain = true
else if (refs.lodPlain && viewport.scale > 0.18) refs.lodPlain = false
const lodViewport = (n) => (refs.lodPlain ? { x: viewport.x, y: viewport.y, scale: 0.1 } : viewport)
// v3.25.71:设置里可关闭「低缩放简化」(默认开)。关掉后任何缩放都渲染完整体。
const wLodEnabled = () => !(config && config.canvas && config.canvas.lodLowZoom === false)
const hOf = (n) => refs.measuredH[n.id] || n.h || nodeTypeH(n.type)
// 双击节点标题栏:平滑居中放大该节点
const zoomToNode = (id) => {
const n = refs.nodes.find((x) => x.id === id)
if (!n) return
const cw = canvasSize.w || 800, ch = canvasSize.h || 600
const nw = nodeWidth(n), nh = hOf(n)
const cx = n.x + nw / 2, cy = n.y + nh / 2
const targetScale = Math.min(2.5, Math.max(0.8, Math.min(cw, ch) * 0.62 / Math.max(nw, nh)))
const target = { x: cw / 2 - cx * targetScale, y: ch / 2 - cy * targetScale, scale: targetScale }
if (refs.zoomAnim) { cancelAnimationFrame(refs.zoomAnim); refs.zoomAnim = null }
const from = refs.viewport || { x: 0, y: 0, scale: 1 }
const t0 = performance.now()
const dur = 220
const step = (t) => {
const k = Math.min(1, (t - t0) / dur)
const e = 1 - Math.pow(1 - k, 3)
setViewport({ x: from.x + (target.x - from.x) * e, y: from.y + (target.y - from.y) * e, scale: from.scale + (target.scale - from.scale) * e })
if (k < 1) refs.zoomAnim = requestAnimationFrame(step)
else refs.zoomAnim = null
}
refs.zoomAnim = requestAnimationFrame(step)
}
// 连线合法性:同时返回原因,供拖动连接时给出可理解的反馈。(决策表已收编到 src/canvas-geometry.js,P2-9)
const connectReason = (fromId, toId) => {
const src = refs.nodeMap.get(fromId)
const dst = refs.nodeMap.get(toId)
if (!src || !dst) return '节点不存在'
if (fromId === toId) return '不能连接节点自身'
return CanvasGeometry.connectReasonOf(src, dst, refs.edges.some((e) => e.from === fromId && e.to === toId), isImageProducer)
}
const canConnect = (fromId, toId) => !connectReason(fromId, toId)
// 点到线段距离(连线插入吸附检测)
const distToSeg = CanvasGeometry.distToSeg
const edgeEndpoints = (ed) => {
const src = refs.nodeMap.get(ed.from)
const dst = refs.nodeMap.get(ed.to)
if (!src || !dst) return null
const x1 = src.x + nodeWidth(src), y1 = src.y + hOf(src) / 2
const y2 = dst.y + (dst.type === 'prompt' ? Math.max(46, hOf(dst) * 0.3) : hOf(dst) / 2)
return { x1, y1, x2: dst.x, y2 }
}
// 目标节点入端口的世界坐标(用于吸附)
const inPortWorld = (node) => {
const h = hOf(node)
const inY = node.type === 'prompt' ? Math.max(46, h * 0.3) : h / 2
return { x: node.x, y: node.y + inY }
}
// 连线路径缓存:按端点位置/高度/类型生成 key,位置未变时复用(拖动/重渲染时避免重复计算)
// 跨 render 保留连线路径缓存;key 已包含位置、尺寸和端口信息,节点变化时自然生成新 key。
// 这样拖动过程中即使 React 重渲染,也不会把整个缓存重新创建。
// 图形索引缓存:仅当节点/连线引用变化时重建,避免拖动帧重复建图索引。
const graphCache = refs.graphCache || (refs.graphCache = { nodes: null, edges: null, index: null })
if (graphCache.nodes !== refs.nodes || graphCache.edges !== refs.edges) {
graphCache.nodes = refs.nodes; graphCache.edges = refs.edges
graphCache.index = createTaskGraphIndex(refs.nodes, refs.edges)
}
const edgePathCache = refs.edgePathCache || (refs.edgePathCache = new Map())
// 派生数据缓存:busy/progress 按节点索引,避免拖动时对每个节点做 O(n²) 过滤(参考项目 useMemo 思路)
const nodeDerived = React.useMemo(() => {
const busyById = new Map(), progById = new Map(), srcBusyById = new Map(), srcProgById = new Map()
for (const k in busy) { const id = k.split('::')[0]; let m = busyById.get(id); if (!m) { m = {}; busyById.set(id, m) } m[k] = busy[k] }
for (const k in progress) { const id = k.split('::')[0]; let m = progById.get(id); if (!m) { m = {}; progById.set(id, m) } m[k] = progress[k] }
// out 节点的来源 busy/progress:按 out 节点聚合其输入源(ref/prompt 等)的实时状态
const srcByOut = new Map()
for (const e of edges) {
if (!e || !e.to) continue
const outId = e.to
const srcId = e.from
if (!srcByOut.has(outId)) srcByOut.set(outId, new Set())
srcByOut.get(outId).add(srcId)
}
for (const [outId, srcIds] of srcByOut) {
let sb = EMPTY_OBJ, sp = EMPTY_OBJ
for (const sid of srcIds) {
for (const k in busy) { if (!busy[k] || k !== sid && !k.startsWith(sid + '::')) continue; if (sb === EMPTY_OBJ) sb = {}; sb[k] = true }
for (const k in progress) { if (!progress[k] || k !== sid && !k.startsWith(sid + '::')) continue; if (sp === EMPTY_OBJ) sp = {}; sp[k] = progress[k] }
}
if (sb !== EMPTY_OBJ) srcBusyById.set(outId, sb)
if (sp !== EMPTY_OBJ) srcProgById.set(outId, sp)
}
return { busyById, progById, srcBusyById, srcProgById }
}, [busy, progress, edges])
// 节点回调稳定化(参考项目 useCallback 思路):拖动时引用稳定,降低 re-render 开销
const nodeOnMeasure = React.useCallback((id, h) => {
const prev = refs.measuredH[id]
if (prev && Math.abs(prev - h) < 2) return
refs.measuredH[id] = h
setTick((t) => t + 1)
}, [])
const nodeOnSelect = React.useCallback((id) => { setSel([id]); setSelEdge(null) }, [])
const nodeOnPreview = React.useCallback((src, list, idx) => setPreview({ list: (list && list.length ? list : [src]), idx: idx || 0 }), [])
const outThumbsFor = React.useCallback((node) => {
try { return (IWNodeBodies && typeof IWNodeBodies.outThumbUrlsOf === 'function') ? IWNodeBodies.outThumbUrlsOf(node, nodes, edges) : [] } catch (e) { return [] }
}, [nodes, edges])
const previewRefNode = React.useCallback((node) => {
const raw = (node && node.data && (node.data.data || node.data.url)) || ''
if (!raw) return
wResolveImgAsync(raw).then((src) => { if (src) nodeOnPreview(src, [src], 0) }).catch(() => { /* ignore */ })
}, [nodeOnPreview])
// batch 节点来源缓存:替代每帧对每条边做 filter+some(拖动时复用)
const batchSourcesMap = React.useMemo(() => {
const m = new Map()
for (const e of edges) {
if (!e || !e.to) continue
const dst = refs.nodeMap.get(e.to)
const src = refs.nodeMap.get(e.from)
if (!dst || !src || dst.type !== 'batch' || !isBatchSrc(src, edges, nodes)) continue
if (!m.has(dst.id)) m.set(dst.id, [])
if (!m.get(dst.id).some((n) => n.id === src.id)) m.get(dst.id).push(src)
}
for (const list of m.values()) list.sort(compareCanvasTextOrder)
return m
}, [edges, nodes])
// 视口裁剪:大画布只渲染可见节点/连线/组(jsdom 无实际画布尺寸时全渲染,兼容测试)
// 视口裁剪矩形(useMemo:拖动时 viewport 不变则复用,避免每帧算除法)
// 视口裁剪:宽边距 240(纯文本节点),带图节点 80 —— 见 CanvasGeometry.cullRectsOf 注释
const cullRects = React.useMemo(() => CanvasGeometry.cullRectsOf(canvasSize, viewport), [canvasSize.w, canvasSize.h, viewport.x, viewport.y, viewport.scale])
const nodeVisible = (n) => CanvasGeometry.nodeVisibleIn(n, cullRects, { drag: refs.drag, resize: refs.resize, sel: sel, pan: !!refs.pan, widthOf: nodeWidth, heightOf: hOf })
const visibleIds = new Set(nodes.filter(nodeVisible).map((n) => n.id))
try { wSetScaleNow(viewport.scale) } catch (e) { /* ignore */ }
// 进程内存(v3.25.74):状态栏显示,便于对比优化前后的内存占用(4s 轮询,窗口隐藏时不拉)
const [memMb, setMemMb] = React.useState(0)
useEffect(() => {
let alive = true
let timer = null
const tick = () => {
if (!alive) return
if (typeof document !== 'undefined' && document.hidden) { timer = setTimeout(tick, 8000); return }
Promise.resolve().then(() => {
const T = (typeof window !== 'undefined') ? window.__TAURI__ : null
const inv = T && T.core && T.core.invoke
if (typeof inv !== 'function') return 0
return inv('app_memory_mb').catch(() => 0)
}).then((v) => { if (!alive) return; const n = Number(v) || 0; if (n > 0) setMemMb(n) }).catch(() => {}).then(() => {
// v3.26.121:再取一次「整棵进程树」的 RSS(WebView2 的 renderer/GPU 是独立进程,
// 上面的 app_memory_mb 只看主进程)。这是诊断页与任务管理器对齐的唯一真值来源。
try {
const T2 = (typeof window !== 'undefined') ? window.__TAURI__ : null
const inv2 = T2 && T2.core && T2.core.invoke
if (typeof inv2 === 'function') {
Promise.resolve(inv2('app_memory_tree_mb')).then((v2) => { const n2 = Number(v2) || 0; if (n2 > 0) wProcRssMB = n2 }).catch(() => {})
}
} catch (e) { /* ignore */ }
if (alive) timer = setTimeout(tick, 4000)
})
}
timer = setTimeout(tick, 1200)
return () => { alive = false; if (timer) clearTimeout(timer) }
}, [])
// v3.26.134:图库缩略图空闲预热(实现抽在 src/ui-workbench-hooks.js,这里只做装配)
IWWorkbenchHooks.useGalleryPrewarm({ len: outputs.length, list: () => outputs, refs, storage: () => wStoreMod(), state: wPrewarmState })
const scaleText = Math.round(viewport.scale * 100) + '%'
const saveText = saveState === 'saving' ? '正在保存' : saveState === 'saved' ? '保存成功' : saveState === 'error' ? '保存失败' : ''
const connecting = !!conn
const edgeEls = []
const focusNodeId = sel.length === 1 ? sel[0] : null
const edgeGraph = graphCache.index
for (const ed of edges) {
if (!visibleIds.has(ed.from) && !visibleIds.has(ed.to)) continue
const srcN = refs.nodeMap.get(ed.from), dstN = refs.nodeMap.get(ed.to)
if (!srcN || !dstN) continue
edgeEls.push(el(EdgePathMemo, {
key: ed.id,
ed, src: srcN, dst: dstN, srcH: hOf(srcN), dstH: hOf(dstN), // 端点高度显式传数字:measuredH 原地修改,memo 浅比较检不出(否则新节点连线端点错位)
graph: edgeGraph, nodeMap: refs.nodeMap, measuredH: refs.measuredH, pathCache: refs.edgePathCache,
focusNodeId,
selEdge,
edgeHover,
visual: false,
onHover: (id) => setHoverEdgeId(id || null),
onSelect: (id) => { setSelEdge(id); setSel([]) },
onDelete: (id) => deleteEdge(id),
}))
}
let tempD = ''
if (conn) {
const src = refs.nodes.find((n) => n.id === conn.from)
if (src) {
let x1 = src.x + nodeWidth(src), y1 = src.y + (hOf(src)) / 2
if (refs.connFrom && refs.connFrom.portPos) { x1 = refs.connFrom.portPos.x; y1 = refs.connFrom.portPos.y }
let x2 = conn.x, y2 = conn.y
if (conn.reverse) {
// 反向拖拽:线从鼠标出发,连到该节点的**输入口**
const inP = inPortWorld(src)
x1 = conn.x
y1 = conn.y
x2 = inP.x
y2 = inP.y
}
const dx = Math.max(40, (x2 - x1) / 2)
tempD = 'M ' + x1 + ' ' + y1 + ' C ' + (x1 + dx) + ' ' + y1 + ', ' + (x2 - dx) + ' ' + y2 + ', ' + x2 + ' ' + y2
}
}
// ---------- 节点组容器(v3.84.0:外框留白 + 框内可拖 + 可调大小)----------
// ① 外框内边距 GROUP_PAD_TOP/X/BOTTOM:顶部足够容纳「节点标题带 + 操作栏」,不再与组标题抢位置
// ② 框内空白处按下 = 整组拖动(节点在框之上,点中节点仍是节点自己的拖拽/编辑)
// ③ 8 个把角/边手柄 = 调整外框(只放大:在基础内边距之上追加额外留白 g.pad,最小 0 = 纯自适应)
// 组容器本身不拦截成员节点事件(节点在 groupEls 之后渲染,永远在上层)
const groupElById = (gid) => (canvasEl.el ? canvasEl.el.querySelector('[data-group-id="' + gid + '"]') : null)
const groupMembersOf = (g) => (g && g.memberIds ? g.memberIds.map((id) => refs.nodes.find((n) => n && n.id === id)).filter(Boolean) : [])
// 拖动/缩放中的命令式外框更新(与节点拖动一致:只改 DOM,不 setState)
const applyGroupBoxVisual = (gid, pad) => {
const g = refs.groups.find((x) => x && x.id === gid)
if (!g) return
const members = groupMembersOf(g)
if (members.length < 2) return
const box = groupBoxOf(members, hOf, pad)
const elG = groupElById(gid)
if (elG) {
elG.style.left = box.x + 'px'; elG.style.top = box.y + 'px'
elG.style.width = box.w + 'px'; elG.style.height = box.h + 'px'
}
refs.groupPadLive = refs.groupPadLive || {}
refs.groupPadLive[gid] = pad
}
// pointer & key handlers(逻辑在 src/ui-canvas-pointer.js.useCanvasPointer,2026-11-26 收编)
if (IWCanvasPointer && !IWCanvasPointer.__iwbInjected) {
IWCanvasPointer.inject({ e2e: (typeof window !== 'undefined' && window.__IWB_E2E__ === true), createRafBatcher, nodeWidth, computeEdgePath, groupBoxOf, groupPadOf, floatbarPlace, uiZoom, groupPadFromDrag, NODE_W, uid, ConnectMenuMod, ConnectMenu, nodeTypeH, NODE_TYPES, CanvasGeometry, isImageProducer, wPrivateToolsOn, withGroupPad, CanvasOps, wImportImage, HOTKEY_DEFAULTS, hotkeyMatches, IWNodeBodies, wRenameNodeDialog, RuntimeLifecycle })
IWCanvasPointer.__iwbInjected = true
}
IWCanvasPointer.useCanvasPointer({ refs, hOf, canvasEl, groupMembersOf, groupElById, sel, selAnchorOf, setTick, setSel, setBoxSel, applyViewportDom, applyGroupBoxVisual, CanvasStore, canConnect, edgeEndpoints, distToSeg, setEdgeHover, connectReason, inPortWorld, setConn, setConnTarget, saveNow, setConnMenu, clearGenResults, setViewport, pushHistory, commitCanvas, settingOpen, drawerOpen, drawerTab, helpOpen, wsMoreOpen, ctxMenu, connMenu, readClipboardGraph, pasteCopiedNodes, pasteGraph, stageClip, copyNodes, selRef, activeWsIdRef, activeWsId, findSpot, setNotice, showToast, setDrawerOpen, conn, setCtxMenu, setWsMoreOpen, setSettingOpen, tool, setTool, setSelEdge, exportCanvas, setHelpOpen, fitSelection, refineSelection, fitView, toggleEnabled, makeGroup, groupOf, ungroup, undo, redo, cutNodes, duplicateNodes, selEdge, deleteEdge, deleteNodes, updateNode, td })
// 节点 → 组 反查(拖动跟随时用,避免每帧 O(groups×members) 扫描)
refs.nodeGroupMap = (() => {
const m = new Map()
for (const g of groups) for (const id of (g.memberIds || [])) m.set(id, g.id)
return m
})()
const GROUP_HANDLES = [['nw', 'iwb-gh-nw'], ['n', 'iwb-gh-n'], ['ne', 'iwb-gh-ne'], ['e', 'iwb-gh-e'], ['se', 'iwb-gh-se'], ['s', 'iwb-gh-s'], ['sw', 'iwb-gh-sw'], ['w', 'iwb-gh-w']]
const groupEls = []
for (const g of groups) {
if (!g.memberIds.some((id) => visibleIds.has(id))) continue
const members = groupMembersOf(g)
if (members.length < 2) continue
const gPad = groupPadOf(g)
const box = groupBoxOf(members, hOf, gPad)
const gSel = g.memberIds.length && g.memberIds.every((id) => sel.includes(id))
// 操作栏拖动:与「框内空白处」共用同一套延迟激活(阈值 4px),避免纯点击污染撤销历史
const armGroupDrag = (e) => {
if (e.button !== 0 || refs.spaceDown) return // 中键 / 空格 = 画布平移,放行给画布
e.stopPropagation()
const start = {}
for (const m of members) start[m.id] = { x: m.x, y: m.y }
refs.groupDown = { start, sx: e.clientX / uiZoom(), sy: e.clientY / uiZoom() }
refs.selFromGroup = true; setSel(g.memberIds.slice()) // 全选来自「按下组」→ 后续点成员降级为单选(否则得先点空白清选)
}
// 框内按下:操作栏/手柄自己处理,其余(框内空白)整体拖动
const onGroupBodyDown = (e) => {
const t = e.target
if (t && t.closest && t.closest('.iwb-group-bar, .iwb-group-handle')) return
armGroupDrag(e)
}
const startGroupResize = (dir) => (e) => {
if (e.button !== 0 || refs.spaceDown) return
e.stopPropagation()
refs.groupResize = { groupId: g.id, dir, gx: e.clientX / uiZoom(), gy: e.clientY / uiZoom(), base: gPad }
refs.selFromGroup = true; setSel(g.memberIds.slice())
}
groupEls.push(el('div', {
key: g.id,
'data-group-id': g.id,
className: 'iwb-group' + (gSel ? ' iwb-group-sel' : ''),
style: { left: box.x, top: box.y, width: box.w, height: box.h },
onPointerDown: onGroupBodyDown,
},
el('div', { className: 'iwb-group-bar', onPointerDown: armGroupDrag },
editingGroupId === g.id
? el('input', {
className: 'iwb-group-name-input',
value: groupNameDraft,
autoFocus: true,
placeholder: '节点组名称',
onFocus: (e) => e.target.select(),
// 输入框内的指针事件不得冒泡到操作栏(否则会启动整组拖动/重选)
onPointerDown: (e) => e.stopPropagation(),
onClick: (e) => e.stopPropagation(),
onDoubleClick: (e) => e.stopPropagation(),
onChange: (e) => setGroupNameDraft(e.target.value),
onKeyDown: (e) => {
if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); renameGroup(g.id, groupNameDraft); setEditingGroupId(null) }
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); setGroupNameDraft(''); setEditingGroupId(null) }
},
onBlur: () => { if (editingGroupId === g.id) { renameGroup(g.id, groupNameDraft); setEditingGroupId(null) } },
}, null)
: el('span', { className: 'iwb-group-name', title: '单击全选组内节点 · 双击修改组名 · 拖动操作栏或框内空白处可整体移动(收藏 / 复制 / 解组在多选气泡上)', onClick: (e) => { e.stopPropagation(); refs.selFromGroup = true; setSel(g.memberIds.slice()) }, onDoubleClick: (e) => { e.stopPropagation(); setGroupNameDraft(g.name || '分组'); setEditingGroupId(g.id) } }, I('group'), g.name || '分组', el('span', { className: 'iwb-group-count' }, members.length + ' 节点')),
),
...GROUP_HANDLES.map(([dir, cls]) => el('div', { key: dir, className: 'iwb-group-handle ' + cls, 'data-dir': dir, title: '拖动调整节点组外框大小', onPointerDown: startGroupResize(dir) }, null)),
))
}
const nodeEls = IWBCanvasNodes.buildNodeEls({
CanvasGeometry, CanvasStore, EMPTY_OBJ, NODE_W, NodeCardMemo, addRefFromUrl, batchPortTop, batchSourcesMap, canConnect, cancelRun, config, connTarget, canvasV3On, canvasV3Types, canvasV3TypeOf,
defaultNodeBoxWidth, deleteNodes, duplicateNodes, edges, el, generationConcurrency, hOf, inPortWorld, isBatchSrc, lodViewport, nodeDerived, nodeOnMeasure, nodeOnPreview, previewRefNode,
nodeOnSelect, nodeTypeH, nodeWidth, nodes, pushHistory, refs, runLLM, runLayerNode, runNode, runOutSources, saveNow, sel, selRef,
setConn, setConnTarget, setNotice, setSel, taskCountOf, thumbRev, typesRev, uiZoom, uid, updateNode, visibleIds, wLodEnabled, zoomToNode,
})
// Key/服务状态:仅异常时显示(逻辑在 src/runtime-workbench-logic.js.keyAnomalyOf)
const keyAnomaly = IWWorkbenchLogic.keyAnomalyOf(config)
// 传到底栏/菜单时**必须带上 icon / toolbar**(2026-11-26):此前只透传 id/title/defaults/run,
// 插件注册的图标与入口范围在这一步被丢掉 ⇒ 底栏仍全是拼图、隐藏项仍出现。
const pluginNodeVariants = React.useMemo(() => wPluginNodeVariants.map((v) => ({ id: v.id, title: v.title, defaults: v.defaults, run: v.run, icon: v.icon, toolbar: v.toolbar })), [pluginRev])
const pluginNodeActionItems = React.useMemo(() => wPluginNodeActions.map((a) => ({ id: a.id, title: a.title, icon: a.icon, appliesTo: a.appliesTo, run: a.run })), [pluginRev])
// 左侧综合工具栏(v3.3:顶部「无限画布」标题 / 工作台分区 / 底部 文件·设置·帮助)
// S12/S13:统一常驻标签栏(首页+画布视图都显示,对齐 Figma 式浏览器标签)
// 最左固定"首页"图标标签 → 画布库;中间画布标签 → 切换;最右 + 新建
// 方案A:每对标签之间一条同款竖线分隔(.iwb-tab-sep,与首页线同规格)
// 先过滤失效 id:标签若为空洞(已删画板)会跳过渲染,避免出现相邻双线
const tabIds = WorkspaceList.liveTabIds(workspaces, openTabs)
const tabstripEl = el(WorkspaceTabs, {
tabIds,
workspaces,
activeWsId,
shellView,
genRuns: refs.genRuns,
wsDoneHints: refs.wsDoneHints,
goHome,
switchWs,
closeTab,
newWs,
})
// 顶栏/工作台导航:不依赖节点坐标,节点拖拽时其依赖值不变 → memo 跳过重渲,缩小拖拽 re-render 范围(参考项目方式)
const topbarEl = shellView === 'canvas'
? el(CanvasTopBar, {
canTitleEdit,
canTitleName,
setCanTitleName,
setCanTitleEdit,
activeWsId,
workspaces,
renameWs,
IS_BROWSER_MODE,
server,
keyAnomaly,
scaleText,
nodes,
edges,
memUi,
setSettingTabReq,
setSettingOpen: openSettings,
saveState,
saveText,
memMb,
notice,
busy,
progress,
theme,
toggleTheme,
saveNow,
showToast,
drawerOpen,
setDrawerOpen,
setDrawerTab,
setWsMorePos,
setWsMoreOpen,
})
: (shellView === 'plugins' ? null : el(ProductNav, { shellView, setShellView, setSettingOpen: openSettings, setHelpOpen, toggleTheme, theme }))
// 底栏工具栏:稳定动作(useCallback 读 refs/selRef) + 派生状态(拖拽时不变化) → React.memo 跳过重渲,缩小拖拽 re-render 范围
// 工具栏编组/取消编组按钮已移除;多选节点组气泡的禁用态直接用 sel / groupOf 判定,故不再需要派生 canGroup/canUngroup。
const tbOnAdd = React.useCallback((t) => addNode(t, null, null, tbCenterSeed(t, refs)), [])
// 插件节点从底栏「插件节点」下拉创建(2026-11-26):右键菜单里有,但藏得深;底栏是主入口,必须能到
const tbOnAddPlugin = React.useCallback((id) => addPluginNode(id, null, null), [])
const tbOnOpenPrompts = React.useCallback(() => { setDrawerTab('prompts'); setDrawerOpen(true) }, [])
const tbOnFavorite = React.useCallback(() => { const ids = selRef.current; const ttlD = ids.map((id) => refs.nodes.find((n) => n.id === id)).filter((n) => n && n.data && n.data.title && String(n.data.title).trim()).map((n) => n.data.title)[0]; td.open({ title: '收藏选中节点为节点组', value: ttlD || ('节点组 ' + (refs.savedGroups.length + 1)), onSubmit: (nm) => saveSelectionAsGroup(ids, nm) }) }, [])
// 适应视图 / 缩放:稳定 useCallback(读 refs.*Ref,不闭包实现)→ 不破坏 ToolbarBottomMemo 的 memo
const tbOnFitView = React.useCallback(() => { if (refs.fitViewRef) refs.fitViewRef() }, []), tbOnZoom = React.useCallback((d) => { if (refs.zoomByRef) refs.zoomByRef(d) }, [])
const tbOnTool = React.useCallback((t) => { refs.pan = null; setTool(t === 'pan' ? 'pan' : 'select') }, []) // 切工具时中断排队中的平移
// 小地图定位:稳定 useCallback(canvasSize 仅尺寸变化时才重建),配合 MinimapMemo 拖拽视图不整壳重渲
const mmOnJump = React.useCallback((wx, wy) => {
const vw = canvasSize.w || 800, vh = canvasSize.h || 600
setViewport((v) => ({ ...v, x: vw / 2 - wx * v.scale, y: vh / 2 - wy * v.scale }))
}, [canvasSize])
// ---- 左右停靠面板(v3.25.35)----
// 提示词库插件(promptlib):数据仍由宿主持有,插件只拿读写/插入/复制能力
if (window.IWBPluginPromptLib) {
window.IWBPluginPromptLib.setImpl({
list: () => ({ prompts: refs.promptLibrary || [], groups: promptGroupsOf(refs.promptLibrary || [], promptGroups) }),
save: (payload) => {
const list = (payload && Array.isArray(payload.prompts)) ? payload.prompts : []
const gs = (payload && Array.isArray(payload.groups)) ? payload.groups : []
setPrompts(list)
setPromptGroups(gs)
try { lsSet('iwb_lib_groups_cache', gs) } catch (e) { /* 分组缓存失败不影响保存 */ }
return Promise.resolve(api('prompts', { prompts: list })).then((r) => {
window.IWBPluginPromptLib.emit('save')
if (r && r.ok === false) return { ok: false, error: (r && r.error) || '提示词库保存失败,请重试' }
return { ok: true }
}).catch(() => ({ ok: false, error: '提示词库保存失败,请重试' }))
},
insert: (text, name) => {
const id = uid('n')
const spot = CanvasGeometry.promptCenterSpot(wPluginCanvasBridge, 280, 120) || findSpot('prompt')
commitCanvas(refs.nodes.concat([{ id, type: 'prompt', x: spot.x, y: spot.y, data: { text: text || '', title: name || '' } }]), undefined, undefined)
setSel([id])
setNotice({ type: 'ok', text: '已插入提示词:' + (name || '') })
return { ok: true }
},
// v3.26.1:把提示词封面插入画布(逻辑在 wPromptInsertImage,Workbench 只做装配)
insertImage: (cover, name) => wPromptInsertImage({
insertRefNode: (data, nm, w) => {
const id = uid('n')
const spot = CanvasGeometry.promptCenterSpot(wPluginCanvasBridge, w || 280, 180) || findSpot('ref')
commitCanvas(refs.nodes.concat([{ id, type: 'ref', x: spot.x, y: spot.y, w: w || 280, data: { data: data, name: nm } }]), undefined, undefined)
setSel([id])
setNotice({ type: 'ok', text: '已插入封面图片' })
showToast('已插入封面图片')
},
}, cover, name),
copy: (text) => {
// 统一走 IWBClipboardCopy(2026-11-24):插件拿到的失败原因由门面归一
const C = (typeof window !== 'undefined') ? window.IWBClipboardCopy : null
if (!C || typeof C.copyText !== 'function') return { ok: false, error: '剪贴板不可用' }
return C.copyText(String(text || '')).then((ok) => ok ? { ok: true } : { ok: false, error: '浏览器拒绝了剪贴板写入(需窗口有焦点)' })
},
notify: (text, type) => { setNotice({ type: type === 'err' ? 'err' : 'ok', text: String(text || '') }); showToast(String(text || ''), type) }, paste: () => window.IWBDesktopHelpers.clipboardReadText(),
// v3.25.97:提示词封面 —— 图片走宿主内容寻址存储(images/plugin/prompt/),条目只存 ref。
putCover: (u) => wPromptCoverCtl().put(u),
coverUrl: (r) => wPromptCoverCtl().url(r),
removeCover: () => ({ ok: true }),
})
}
if (window.IWBPluginGallery) window.IWBPluginGallery.setImpl({
list: (o) => window.IWBPluginGallery.query(outputs, o),
// 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('') }, galleryThumbUrl: (h) => { const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null; return (F && typeof F.galleryThumbUrl === 'function') ? F.galleryThumbUrl(h) : Promise.resolve('') }, galleryThumbOf: (f, max) => { const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null; return (F && typeof F.galleryThumbOfEntry === 'function') ? F.galleryThumbOfEntry(f, max) : 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 = []
let n = 0
for (const f of (outputs || [])) {
if (names.indexOf(f.name) < 0) continue
let done = false
for (let i = 0; i < 3 && !done; i++) {
try { const src = await wResolveOutputSrc(f); if (src) { downloadUrl(src, f.name); done = true } } catch (e) { /* 网络抖动:重试 */ }
if (!done) await new Promise((r) => setTimeout(r, 300 + i * 400))
}
if (done) n++; else failed.push(f.name)
}
return { ok: failed.length === 0, count: n, failed: failed }
},
insert: async (names, o) => ({ ok: true, inserted: await insertOutputsToCanvas((outputs || []).filter((f) => names.indexOf(f.name) >= 0), (o && o.insertK) || '1k') }),
remove: async (names) => { const n = await deleteOutputs(names); return { ok: n > 0, removed: n } }, openFolder: () => window.IWBDesktopHelpers.openGalleryDir(), backfill: (names) => { const want = Array.isArray(names) ? names : []; const hits = (outputs || []).filter((f) => want.indexOf(f.name) >= 0); return Promise.all(hits.map((f) => storeOutputThumb(f, true))).then((rs) => ({ ok: rs.filter(Boolean).length, count: rs.filter(Boolean).length, failed: hits.filter((f, i) => !rs[i]).map((f) => f.name) })) },
})
// 节点组库插件(grouplib):数据仍由宿主持有,插件只拿读写/实例化能力
if (window.IWBPluginGroupLib) {
window.IWBPluginGroupLib.setImpl({
list: () => ({ groups: refs.savedGroups || [], groupGroups: refs.nodeGroupGroups || [] }),
save: (payload) => {
const groups = (payload && Array.isArray(payload.groups)) ? payload.groups : []
const groupGroups = (payload && Array.isArray(payload.groupGroups)) ? payload.groupGroups : []
setSavedGroups(groups)
setNodeGroupGroups(groupGroups)
return Promise.resolve(wSaveGroups(groups, groupGroups)).then((r) => { window.IWBPluginGroupLib.emit('save'); return r || { ok: true } })
},
remove: (id) => {
const groups = (refs.savedGroups || []).filter((g) => g.id !== id)
setSavedGroups(groups)
return Promise.resolve(wSaveGroups(groups, refs.nodeGroupGroups || [])).then((r) => { window.IWBPluginGroupLib.emit('remove'); return r || { ok: true } })
},
instantiate: (id) => {
const snap = (refs.savedGroups || []).find((g) => g.id === id)
if (!snap) return { ok: false, error: '节点组不存在' }
const vw = canvasSize.w || 800, vh = canvasSize.h || 600
const wx = ((vw / 2) - viewport.x) / (viewport.scale || 1)
const wy = ((vh / 2) - viewport.y) / (viewport.scale || 1)
return Promise.resolve(instantiateGroup(snap, wx, wy)).then(() => ({ ok: true }))
},
notify: (text, type) => { setNotice({ type: type === 'err' ? 'err' : 'ok', text: String(text || '') }); showToast(String(text || ''), type) },
})
}
// v3.25.82:停靠栏面板清单(按插件启用过滤)在 src/ui-dock-panels.js
const dockPanels = (typeof window !== 'undefined' && window.IWBUIDockPanels)
? window.IWBUIDockPanels.build(PluginHost, wPluginPanels)
: {}
return el('div', { className: 'iwb-overlay' + (shellView === 'landing' ? ' iwb-view-landing' : shellView === 'home' ? ' iwb-view-home' : (shellView === 'plugins' ? ' iwb-view-plugins' : ' iwb-view-canvas')) + (drawerOpen ? ' drawer-open' : '') + ((nodes.length && loaded) ? ' has-minimap' : '') },
// 页面加载动画(真实进度条:src/ui-splash.js + src/boot-progress.js,加载完成后淡出)
!splashDone && window.IWBUISplash ? el(window.IWBUISplash.Splash, { fade: loaded, icon: I('palette') }) : null,
shellView === 'home' ? el('div', { className: 'iwb-home-panel' },
el('div', { className: 'iwb-home-side' },
el('div', { className: 'iwb-home-side-head' }, el('span', null, '无限画布'),
),
el('div', { className: 'iwb-home-search' }, el('input', { className: 'iwb-input', placeholder: '搜索画布…', value: homeSearch, onChange: (e) => setHomeSearch(e.target.value) })),
el('div', { className: 'iwb-home-side-nav' },
el('button', { className: 'iwb-home-side-item' + (homeView === 'recent' ? ' active' : ''), onClick: () => setHomeView('recent') }, I('palette'), el('span', null, '最近使用'), el('span', { className: 'iwb-home-side-count' }, sideCounts.recent)),
el('button', { className: 'iwb-home-side-item' + (homeView === 'starred' ? ' active' : ''), onClick: () => setHomeView('starred') }, I('star'), el('span', null, '收藏'), el('span', { className: 'iwb-home-side-count' }, sideCounts.starred)),
),
el('div', { className: 'iwb-home-side-cats' },
el('button', { className: 'iwb-home-side-item' + (homeView === 'none' ? ' active' : ''), onClick: () => setHomeView('none') }, I('folder'), el('span', null, '未分类'), el('span', { className: 'iwb-home-side-count' }, sideCounts.none)),
wsCategories.map((c) => el('button', { key: c, className: 'iwb-home-side-item' + (homeView === 'cat:' + c ? ' active' : ''), onClick: () => setHomeView('cat:' + c) }, I('folder'), el('span', null, c), el('span', { className: 'iwb-home-side-count' }, sideCatCount(c)))),
el('button', { className: 'iwb-home-side-item iwb-home-side-add', onClick: addCategory }, I('plus'), el('span', null, '新建分类')),
),
el('div', { className: 'iwb-home-side-trash' },
el('button', { className: 'iwb-home-side-item' + (homeView === 'trash' ? ' active' : ''), onClick: () => setHomeView('trash') }, I('trash'), el('span', null, '回收站'), el('span', { className: 'iwb-home-side-count' }, sideCounts.trash)),
),
// 底部 设置/帮助/皮肤 已并入最左一级导航(v3.25.60 去重)
),
el('div', { className: 'iwb-home-main' },
el('div', { className: 'iwb-home-main-head' },
el('span', { className: 'iwb-home-main-title' }, homeTitle),
isCatView ? el('button', { className: 'iwb-btn iwb-btn-sm', title: '重命名分类', onClick: () => renameCategory(homeView) }, I('edit')) : null,
el('span', { className: 'iwb-drawer-spacer' }, null),
el('div', { className: 'iwb-home-actions' },
el('button', { className: 'iwb-btn' + (homeManage ? ' iwb-btn-primary' : ''), onClick: () => { setHomeManage((v) => !v); if (homeManage) setHomeSelectedWs([]) } }, homeManage ? '退出批量' : '批量管理'),
el('button', { className: 'iwb-btn', disabled: !homeSelectedWs.length, onClick: () => { const old = activeWsId; Promise.all(homeSelectedWs.map((id) => hydrateBoardInto(id))).then(() => { homeSelectedWs.forEach((id) => { setActiveWsId(id); loadWsInto(workspaces.find((w) => w.id === id), true); exportCanvas(); setActiveWsId(old) }) }).catch((e) => { setActiveWsId(old); setNotice({ type: 'err', text: '导出选中失败:' + ((e && e.message) || e) }) }) } }, I('download'), '导出选中'),
homeView === 'trash' ? el('button', { className: 'iwb-btn', onClick: async () => { if (!(await window.IWBUIConfirm.askOrNative('确定清空回收站?将彻底删除回收站中的全部画布。', { title: '清空回收站', okText: '清空' }))) return; emptyTrash() } }, I('trash'), '清空回收站') : null,
homeSelectedWs.length ? el('button', { className: 'iwb-btn', onClick: async () => { if (!(await window.IWBUIConfirm.askOrNative(homeView === 'trash' ? '确定彻底删除选中的画布?此操作不可恢复。' : '确定删除选中的画布?(移入回收站)', { title: '删除画布', okText: '删除' }))) return; homeSelectedWs.forEach((id) => (homeView === 'trash' ? purgeWs(id) : trashWs(id))); setHomeSelectedWs([]) } }, I('trash'), '删除选中') : null,
homeSelectedWs.length ? el('button', { className: 'iwb-btn', onClick: () => setCatPick({ mode: 'batch' }) }, I('tag'), '批量分类') : null,
catPick && catPick.mode === 'batch' ? el('select', { className: 'iwb-home-cat-select', value: '', onChange: (e) => { const v = e.target.value; if (v === '__new') { td.open({ title: '新建分类', placeholder: '新分类名称', onSubmit: (nm) => batchAssignCategory(homeSelectedWs, nm) }) } else batchAssignCategory(homeSelectedWs, v); setCatPick(null); setHomeSelectedWs([]) } }, el('option', { value: '' }, '选择分类…'), wsCategories.map((c) => el('option', { key: c, value: c }, c)), el('option', { value: '__new' }, '+ 新建分类…')) : null,
el('label', { className: 'iwb-btn' }, el('input', { type: 'file', accept: '.json,application/json', style: { display: 'none' }, onChange: (e) => { importCanvasFile(e.target.files && e.target.files[0]); e.target.value = '' } }), I('download'), '导入画布'),
el('button', { className: 'iwb-btn iwb-btn-primary', onClick: () => { newWs(); setShellView('canvas') } }, I('plus'), '新建画布'),
),
),
(() => {
// v3.1.0:移除「当前画布卡」常驻高亮(默认总有卡被选中的伪选中态);选中态仅批量管理模式出现
const homeCard = (w) => el('div', { key: w.id, className: 'iwb-home-card' + (homeManage ? ' iwb-manage' : '') + (homeSelectedWs.includes(w.id) ? ' iwb-home-card-selected' : ''), onClick: () => { if (homeManage) toggleHomeSel(w.id); else setHomeSelectedWs([w.id]) }, onDoubleClick: () => { if (!homeManage) openCanvasEditor(w.id) } },
el('div', { className: 'iwb-home-card-top' },
el('span', { className: 'iwb-home-card-title', title: '双击打开画布' }, el('strong', null, w.name || '未命名画布')),
),
el('div', { className: 'iwb-home-card-meta' },
el('span', { className: 'iwb-home-card-meta-text' }, ((w.nodes || []).length) + ' 个节点 · ' + ((w.edges || []).length) + ' 条连线'),
),
el('div', { className: 'iwb-home-card-foot' },
catPick && catPick.mode === 'card' && catPick.id === w.id
? el('select', { className: 'iwb-home-cat-select', value: w.category || '', onChange: (e) => { const v = e.target.value; if (v === '__new') { td.open({ title: '新建分类', placeholder: '新分类名称', onSubmit: (nm) => setWsCategory(w.id, nm) }); setCatPick(null) } else { setWsCategory(w.id, v); setCatPick(null) } }, onBlur: () => setCatPick(null), onClick: (e) => e.stopPropagation() }, el('option', { value: '' }, '未分类'), wsCategories.map((c) => el('option', { key: c, value: c }, c)), el('option', { value: '__new' }, '+ 新建分类…'))
: el('button', { className: 'iwb-home-card-cat' + (w.category ? '' : ' iwb-home-card-cat-empty'), title: '设置分类', onClick: (e) => { e.stopPropagation(); setCatPick({ mode: 'card', id: w.id }) } }, w.category || '未分类'),
el('div', { className: 'iwb-home-card-actions' },
homeView === 'trash'
? [
el('button', { title: '恢复画布', onClick: (e) => { e.stopPropagation(); restoreWs(w.id) } }, I('refresh')),
el('button', { title: '彻底删除', onClick: async (e) => { e.stopPropagation(); if (!(await window.IWBUIConfirm.askOrNative('确定彻底删除画布「' + (w.name || '未命名画布') + '」?此操作不可恢复。', { title: '彻底删除', okText: '删除' }))) return; purgeWs(w.id) } }, I('trash')),
]
: [
el('button', { title: '创建副本', onClick: (e) => { e.stopPropagation(); duplicateWs(w.id) } }, I('copy')),
el('button', { title: '重命名画布', onClick: (e) => { e.stopPropagation(); setWsRenameId(w.id); setWsRenameName(w.name || '') } }, I('edit')),
el('button', { className: 'iwb-home-card-star' + (w.starred ? ' on' : ''), title: w.starred ? '取消收藏' : '收藏', onClick: (e) => { e.stopPropagation(); toggleStarWs(w.id) } }, I('star')),
],
),
),
)
if (homeView === 'recent' && shownWs.length) {
const d0 = new Date(); d0.setHours(0, 0, 0, 0); const today0 = d0.getTime()
const bands = [['今天', today0], ['昨天', today0 - 86400e3], ['近一周', today0 - 7 * 86400e3], ['更早', -1]]
const secs = bands.map(([lbl, min]) => ({ lbl, min, items: [] }))
for (const w of shownWs) { const t = Number(w.lastUsed) || 0; const s = secs.find((x) => t >= x.min); if (s) s.items.push(w) }
return el('div', { className: 'iwb-home-grid' }, secs.flatMap((s) => s.items.length ? [el('div', { key: 'sec_' + s.lbl, className: 'iwb-home-sec-head' }, s.lbl + '(' + s.items.length + ')'), ...s.items.map(homeCard)] : []))
}
return el('div', { className: 'iwb-home-grid' }, shownWs.length ? shownWs.map(homeCard) : el('div', { className: 'iwb-home-empty' }, homeView === 'trash' ? '回收站为空' : '没有画布,点击「新建画布」开始。'))
})(),
),
) : null,
wsRenameId ? ReactDOM.createPortal(el('div', { className: 'iwb-modal-mask', onWheel: (e) => e.stopPropagation(), onPointerDown: (e) => { if (e.target === e.currentTarget) setWsRenameId(null) } },
el('div', { className: 'iwb-modal iwb-rename-modal' },
el('div', { className: 'iwb-modal-head' }, el('span', null, '重命名画布')),
el('div', { className: 'iwb-modal-body' }, el('input', { className: 'iwb-input iwb-rename-input', value: wsRenameName, autoFocus: true, onFocus: (e) => e.target.select(), onChange: (e) => setWsRenameName(e.target.value), onKeyDown: (e) => { if (e.key === 'Enter') renameWs(wsRenameId, wsRenameName); if (e.key === 'Escape') setWsRenameId(null) } })),
el('div', { className: 'iwb-modal-foot' },
el('button', { className: 'iwb-btn', onClick: () => setWsRenameId(null) }, '取消'),
el('button', { className: 'iwb-btn iwb-btn-primary', onClick: () => renameWs(wsRenameId, wsRenameName) }, '确定'),
),
),
), document.body) : null,
el(TextDialog, { modal: td.modal, onChange: td.setValue, onClose: td.close }),
homeMenuOpen ? ReactDOM.createPortal(el('div', { className: 'iwb-home-menu-mask', onPointerDown: (e) => { if (e.target === e.currentTarget) setHomeMenuOpen(false) } },
el('div', { className: 'iwb-home-menu', style: homeMenuPos },
el('button', { className: 'iwb-home-menu-item', onClick: () => { setHomeMenuOpen(false); openSettings() } }, I('settings'), el('span', null, '设置')),
el('a', { className: 'iwb-home-menu-item', href: 'https://github.com/malongan/image-workbench-web', target: '_blank', rel: 'noopener', onClick: () => setHomeMenuOpen(false) }, I('github'), el('span', null, '项目主页')),
el('div', { className: 'iwb-home-menu-ver' }, '版本 ' + APP_VERSION),
),
), document.body) : null,
// 一级导航(v3.25.59):替换原 wsrail。52px 纯图标,占同一槽位,不额外挤占画布。
NavRail ? el(NavRail, {
I,
logoIcon: 'brand',
view: shellView === 'plugins' ? 'plugins' : (shellView === 'home' ? 'home' : 'canvas'),
skinIcon: theme === 'dark' ? 'sun' : 'moon',
onHome: () => { setShellView('home'); try { goHome() } catch (e) { /* ignore */ } },
onCanvas: () => setShellView('canvas'),
onPlugins: () => setShellView('plugins'),
onHelp: () => { setHelpMode('help'); setHelpOpen(true) },
onHotkeys: () => { setHelpMode('keys'); setHelpOpen(true) },
onSkin: () => { try { toggleTheme() } catch (e) { /* ignore */ } },
onSettings: openSettings,
appVersion: APP_VERSION,
}) : null,
shellView === 'canvas' && enteringWs ? el('div', { className: 'iwb-enter-loading' }, el('div', { className: 'iwb-enter-spinner' }, null), el('div', { className: 'iwb-enter-text' }, '正在打开画布…')) : null,
// 插件整页(v3.25.59):主组「插件」图标进入;返回回到画布
shellView === 'plugins' ? (PluginsPage
? el(PluginsPage, { I, PluginHost, wRuntimePlugins, wEnsurePluginLoaded, Sections: window.IWBUISettingsSections, onBack: () => setShellView('canvas') })
: el('div', { className: 'iwb-plugin-page' }, el('div', { className: 'iwb-plugin-page-head' }, '插件页未就绪'))) : null,
tabstripEl, // S12:顶部标签条(在顶栏上方)
topbarEl,
el('div', {
className: 'iwb-canvas' + (shellView !== 'canvas' ? ' iwb-canvas-hidden' : '') + (connecting ? ' iwb-connecting' : '') + (refs.drag ? ' iwb-dragging' : '') + (tool === 'pan' ? ' iwb-tool-pan' : ''),
ref: (el0) => { canvasEl.el = el0 },
onContextMenu: (e) => {
// 右键中断未完成的节点体点按,避免残留 bodyDown 被后续 pointermove 误激活
refs.bodyDown = null
// 弹窗/面板等画布之外层级的元素上右键:不激活画布菜单,保留浏览器默认右键菜单(粘贴/复制等)
const t0 = e.target
if (t0 && t0.closest && t0.closest('.iwb-modal-mask, .iwb-fullmask, .iwb-fullpanel, .iwb-ctxmask, .iwb-drawer, .iwb-toolbar, .iwb-rightrail, .iwb-navrail, .iwb-plugin-page, .iwb-statusbar, .iwb-minimap, .iwb-hint-bottom, .iwb-lib, .iwb-lib-embedded, .iwb-history, .iwb-history-embedded, .iwb-ctxmenu')) return
e.preventDefault()
// 计算右键位置的世界坐标,并命中目标节点(未选中则选中它)
let cRect = null
if (canvasEl.el) cRect = canvasEl.el.getBoundingClientRect()
const z2 = uiZoom()
const cLeft = cRect ? cRect.left / z2 : 0
const cTop = cRect ? cRect.top / z2 : 0
const vp = refs.viewport || { x: 0, y: 0, scale: 1 }
const wx = (e.clientX / z2 - cLeft - vp.x) / vp.scale
const wy = (e.clientY / z2 - cTop - vp.y) / vp.scale
let targetId = null
try {
const el = document.elementFromPoint(e.clientX, e.clientY)
const nd = el && el.closest ? el.closest('.iwb-node') : null
if (nd && nd.dataset && nd.dataset.nodeId) targetId = nd.dataset.nodeId
} catch (err) { /* ignore */ }
if (!targetId && canvasV3On) {
const hp = v3HitAtClient(e.clientX, e.clientY)
if (hp) targetId = hp.node.id
}
if (targetId && !sel.includes(targetId)) setSel([targetId])
setCtxMenu({ x: e.clientX, y: e.clientY, wx, wy, targetId })
},
onDoubleClick: (e) => {
// Canvas V3:未选中 ref 没有 DOM,双击命中后直接开预览。
if (canvasV3On) {
const hit = v3HitAtClient(e.clientX, e.clientY)
if (hit) {
e.preventDefault(); e.stopPropagation()
if (hit.node.type === 'ref') previewRefNode(hit.node)
else setSel([hit.node.id])
return
}
}
// 双击画布空白不再做任何事(原「双击空白 = 适应视图」已移除,改为底栏最右「适应视图」按钮 + Shift+F)。
// 「双击节点标题栏 = 居中放大该节点」由节点自身处理,这里只负责排除,不去抢节点/操作栏/面板上的双击。
const t0 = e.target
// 注意:.iwb-group 本身不排除(外框 pointer-events:auto),组框内空白双击同样为无操作;
// 只排除节点、操作栏与缩放手柄等有自身交互的元素。
if (t0 && t0.closest && t0.closest('.iwb-node, .iwb-group-bar, .iwb-group-handle, .iwb-edge, .iwb-toolbar, .iwb-drawer, .iwb-lib, .iwb-lib-embedded, .iwb-history, .iwb-history-embedded, .iwb-rightrail, .iwb-fullmask, .iwb-fullpanel, .iwb-navrail, .iwb-plugin-page, .iwb-minimap, .iwb-statusbar, .iwb-hint-bottom')) return
// 保留「真实框选拖动(位移>8px)后 600ms 内屏蔽 dblclick」判定:框选收尾时浏览器可能补发一次 dblclick,
// 该判定同时守住节点标题栏双击(居中放大)不被框选残留误吞(见下方 lastBoxMove 记账处)。
// 纯点击/双击不受影响。
if (refs.lastBoxMove && Date.now() - refs.lastBoxMove < 600) return
},
onPointerDown: (e) => {
// 中键按住拖动 = 平移画布(不触发框选,阻止浏览器自动滚动)
if (e.button === 1) {
e.preventDefault()
refs.pan = { sx: e.clientX / uiZoom(), sy: e.clientY / uiZoom(), vx: viewport.x, vy: viewport.y }
setSel([])
setSelEdge(null)
setTick((t) => t + 1) // 让 nodeVisible(pan=true) 先挂载全部节点,避免平移中途空白
return
}
if (e.button !== 0) return
// 工具栏 / 侧栏 / 面板 / 小地图上的交互不触发画布空白行为(否则点击面板按钮会关掉面板)
// 真模态(设置/备份/确认/右键遮罩)才整体拦画布;库面板 .iwb-fullmask 是可拖可连的浮窗,画布露在它外面仍要能框选(面板内起手由下面 target 判定兜住)
if (typeof document !== 'undefined' && document.querySelector && document.querySelector('.iwb-modal-mask, .iwb-ctxmask')) return
const t0 = e.target
if (t0 && t0.closest && (t0.closest('.iwb-toolbar') || t0.closest('.iwb-lib') || t0.closest('.iwb-lib-embedded') || t0.closest('.iwb-drawer') || t0.closest('.iwb-history') || t0.closest('.iwb-history-embedded') || t0.closest('.iwb-rightrail') || t0.closest('.iwb-fullmask') || t0.closest('.iwb-fullpanel') || t0.closest('.iwb-minimap') || t0.closest('.iwb-navrail, .iwb-plugin-page') || t0.closest('.iwb-statusbar') || t0.closest('.iwb-hint-bottom') || t0.closest('.iwb-modal-mask') || t0.closest('.iwb-modal') || t0.closest('.iwb-cpick-pop'))) return
// Canvas V3:未选中 ref 没有 DOM,先在画布层做命中;选中/端口仍走现有逻辑。
if (canvasV3On && e.button === 0 && !refs.spaceDown && tool !== 'pan') {
const t1 = e.target
const overDomNode = !!(t1 && t1.closest && t1.closest('.iwb-node, .iwb-port, .iwb-resize, .iwb-group, .iwb-group-bar, .iwb-toolbar, .iwb-drawer, .iwb-lib, .iwb-rightrail, .iwb-navrail, .iwb-plugin-page, .iwb-statusbar, .iwb-minimap'))
if (!overDomNode) {
const hit = v3HitAtClient(e.clientX, e.clientY)
if (hit) {
e.preventDefault()
e.stopPropagation()
const nd = hit.node
if (hit.port === 'in') {
const inP = inPortWorld(nd)
refs.connFrom = { nodeId: nd.id, reverse: true, portPos: inP }
setConnTarget(null); setConn({ from: nd.id, x: inP.x, y: inP.y, reverse: true }); return
}
if (hit.port === 'out') {
refs.connFrom = { nodeId: nd.id, portPos: { x: nd.x + nodeWidth(nd), y: nd.y + hOf(nd) / 2 } }
setConnTarget(null); return
}
const curSel = selRef.current
const ids = (e.shiftKey || e.metaKey || e.ctrlKey)
? (curSel.includes(nd.id) ? curSel.filter((x) => x !== nd.id) : curSel.concat([nd.id]))
: (curSel.includes(nd.id) ? curSel.slice() : [nd.id])
const start = {}
for (const x of refs.nodes) if (ids.includes(x.id)) start[x.id] = { x: x.x, y: x.y }
refs.bodyDown = { id: nd.id, ids, start, sx: e.clientX / uiZoom(), sy: e.clientY / uiZoom(), active: false }
setSel(ids)
return
}
}
}
// 平移画布:按住空格(临时)或选中抓手工具(持续);默认 = 框选节点
if (refs.spaceDown || tool === 'pan') {
refs.pan = { sx: e.clientX / uiZoom(), sy: e.clientY / uiZoom(), vx: viewport.x, vy: viewport.y }
setSel([])
setSelEdge(null)
setTick((t) => t + 1) // 同上:平移期间先挂载全部节点
return
}
refs.box = { x0: e.clientX / uiZoom(), y0: e.clientY / uiZoom(), x1: e.clientX / uiZoom(), y1: e.clientY / uiZoom(), mode: e.altKey ? 'toggle' : (e.shiftKey ? 'add' : 'replace'), baseSel: selRef.current.slice() }
setSelEdge(null)
if (!e.shiftKey && !e.altKey) setSel([])
},
},
el('div', { className: 'iwb-grid', 'aria-hidden': 'true', 'data-gap': '', style: gridStyleOf(viewport.x, viewport.y, viewport.scale) }, null),
boxSel ? el('div', {
className: 'iwb-boxsel',
style: {
left: Math.min(boxSel.x0, boxSel.x1),
top: Math.min(boxSel.y0, boxSel.y1),
width: Math.abs(boxSel.x1 - boxSel.x0),
height: Math.abs(boxSel.y1 - boxSel.y0),
},
}, null) : null,
((sel && sel.length) ? (sel.length > 1
? (() => { // 多选:显示「节点组」气泡(编组/取消编组/导出/收藏/复制/剪切/删除)
const gAnchor = selAnchorOf(sel, refs.nodes || nodes)
if (!gAnchor) return null
const gGroup = sel.map((id) => groupOf(id)).find(Boolean) || null
const gPlace = floatbarPlace(gAnchor.minY, gAnchor.maxY, gAnchor.lift, viewport)
return el('div', { className: 'iwb-node-floatbar iwb-node-floatbar-group' + (gPlace.below ? ' iwb-node-floatbar-below' : ''), onPointerDown: (e) => e.stopPropagation(), style: { left: viewport.x + gAnchor.cx * viewport.scale, top: gPlace.top, '--iwb-fb-k': String(gPlace.k) } },
el('span', { className: 'iwb-node-floatbar-title', title: '多选节点组' }, '节点组(' + sel.length + ')'),
// v3.24.29:选区里只要有节点已在组内(组内多选 / 组内全选 / 跨组多选)就隐藏「编组」——
// 组内已经成组,再点编组只会在旧组之上叠一个新组(节点同时属于两个组 = 脏数据)。
UiGenCfgModule && UiGenCfgModule.NodeBgPalette ? el(UiGenCfgModule.NodeBgPalette, { key: 'bgc', current: '', onPreview: (bg) => previewNodeBg(sel, bg), onPreviewEnd: endNodeBgPreview, onPick: (bg) => { sel.slice().forEach((nid) => updateNode(nid, { bg })) } }) : null,
sel.some((id) => groupOf(id)) ? null : el('button', { 'aria-label': '编组', 'data-tip': '编组', onClick: (e) => { e.stopPropagation(); makeGroup() } }, I('group')),
el('button', { 'aria-label': '解组', 'data-tip': '解组', disabled: !gGroup, onClick: (e) => { e.stopPropagation(); if (gGroup) ungroup(gGroup.id) } }, I('ungroup')),
el('button', { 'aria-label': '导出', 'data-tip': '导出', onClick: (e) => { e.stopPropagation(); exportSelectedGroup() } }, I('download')),
el('button', { 'aria-label': '收藏', 'data-tip': '收藏', onClick: (e) => { e.stopPropagation(); tbOnFavorite() } }, I('star')),
el('button', { 'aria-label': '复制', 'data-tip': '复制', onClick: (e) => { e.stopPropagation(); copyNodes(sel.slice()) } }, I('copy')),
el('button', { 'aria-label': '剪切', 'data-tip': '剪切', onClick: (e) => { e.stopPropagation(); cutNodes(sel.slice()) } }, I('cut')),
// 2026-11-09:删除按钮回到气泡(用户 2026-10-30 曾要求移除防误删,现确认恢复;hover 亮红)。
// 放最右 = 破坏性操作不与高频按钮相邻;deleteNodes 内部会 cancelRunsFor + pushHistory ⇒ 可 Ctrl+Z 撤销。
el('button', { className: 'iwb-fb-del', 'aria-label': '删除', 'data-tip': '删除选中(Delete)', onClick: (e) => { e.stopPropagation(); deleteNodes(sel.slice()) } }, I('trash')),
)
})()
: (() => { const sn = (refs.nodes || nodes).find((n) => n && n.id === sel[0]); if (!sn) return null; const title = (sn.data && sn.data.title) || (nodeTypeTitle(sn.type)); const metaLabel = floatbarMetaLabel(wRawCfg(), sn); const pl = floatbarPlace(sn.y, sn.y + hOf(sn), floatbarLift(hasNodeTitle(sn), nodeInGroup(sn), true), viewport); return el('div', { className: 'iwb-node-floatbar' + (pl.below ? ' iwb-node-floatbar-below' : ''), onPointerDown: (e) => e.stopPropagation(), style: { left: viewport.x + (sn.x + nodeWidth(sn) / 2) * viewport.scale, top: pl.top, '--iwb-fb-k': String(pl.k) } }, metaLabel ? el('span', { className: 'iwb-node-floatbar-title', title: '当前服务商 · Key 分组' }, metaLabel) : null,
UiGenCfgModule && UiGenCfgModule.NodeBgPalette ? el(UiGenCfgModule.NodeBgPalette, { key: 'bgc', current: (sn.data && sn.data.bg) || '', onPreview: (bg) => previewNodeBg([sn.id], bg), onPreviewEnd: endNodeBgPreview, onPick: (bg) => updateNode(sn.id, { bg }) }) : null,
groupOf(sn.id) ? el('button', { 'aria-label': '解组', 'data-tip': '移出节点组', onClick: (e) => { e.stopPropagation(); ungroupNode(sn.id) } }, I('ungroup')) : null,
// 未编组且与某个分组相连 ⇒「并入分组」(多个相连组时取成员最多的)
!groupOf(sn.id) && IWWorkbenchLogic.connectedGroupIdsOf(refs, sn.id).length ? el('button', { 'aria-label': '并入分组', 'data-tip': '并入分组', onClick: (e) => { e.stopPropagation(); joinGroupOf(sn.id) } }, I('group')) : null,
sn.type === 'prompt' ? el('button', { 'aria-label': '放大编辑', 'data-tip': '放大编辑', onClick: (e) => { e.stopPropagation(); if (IWNodeBodies && IWNodeBodies.openPromptExpand) IWNodeBodies.openPromptExpand({ value: (sn.data && sn.data.text) || '', onCommit: (v) => updateNode(sn.id, { text: v }) }) } }, I('maximize')) : null,
el('button', { 'aria-label': '改名', 'data-tip': '改名', onClick: (e) => { e.stopPropagation(); wRenameNodeDialog(sn, td, updateNode) } }, I('edit')),
el('button', { 'aria-label': '复制', 'data-tip': '复制', onClick: (e) => { e.stopPropagation(); duplicateNodes(sel) } }, I('copy')),
sn.type === 'ref' ? el('label', { 'aria-label': '替换', 'data-tip': '替换', onPointerDown: (e) => e.stopPropagation() }, I('upload'), el('input', { type: 'file', accept: 'image/*', style: { display: 'none' }, onChange: (e) => { const f = e.target.files && e.target.files[0]; if (!f) return; try { const rd = new FileReader(); rd.onload = () => wImportImage(rd.result, { onError: (msg) => setNotice({ type: 'err', text: msg }) }, (r) => { if (!r || !r.ok || !r.data) return; updateNode(sn.id, { data: r.data, name: f.name, localName: null, url: '' }) }); rd.onerror = () => setNotice({ type: 'err', text: '读取图片文件失败:' + String(f.name || '') }); rd.readAsDataURL(f) } catch (err) { console.error(err) } } }, null)) : null,
sn.type === 'ref' ? el('button', { 'aria-label': '粘贴', 'data-tip': '粘贴', onClick: (e) => { e.stopPropagation(); floatbarRefPaste(sn.id) }, onPointerDown: (e) => e.stopPropagation() }, I('paste')) : null,
sn.type === 'out' ? (() => { const uout = outResultUrls(sn.id); return el('button', { 'aria-label': '下载', 'data-tip': '下载', disabled: !uout.length, onClick: (e) => { e.stopPropagation(); uout.forEach((u, i) => setTimeout(() => downloadUrl(u, 'image-' + String(i + 1).padStart(3, '0') + '.png'), i * 350)) } }, I('download')) })() : null,
...pluginNodeActionItems.filter((a) => !a.appliesTo || a.appliesTo({ id: sn.id, type: sn.type, data: sn.data || {} })).map((a) => el('button', {
key: 'plug_' + a.id, className: 'iwb-node-floatbar-plugin', title: a.title, 'data-tip': a.title,
onPointerDown: (e) => e.stopPropagation(),
onClick: (e) => {
e.stopPropagation()
const fail = (err) => setNotice({ type: 'err', text: '插件动作失败:' + String((err && err.message) || err) })
try {
const r = a.run({ id: sn.id, type: sn.type, name: String((sn.data && (sn.data.name || sn.data.title)) || '') })
if (r && typeof r.then === 'function') r.catch(fail)
} catch (err) { fail(err) }
},
}, I(a.icon || 'star'))),
// 2026-11-09:单节点气泡同样恢复删除(放最右,理由同多选气泡)。
el('button', { className: 'iwb-fb-del', 'aria-label': '删除', 'data-tip': '删除', onClick: (e) => { e.stopPropagation(); deleteNodes([sn.id]) } }, I('trash')),
) })()) : null),
// 边线视觉层:canvas 绘制,避免 SVG 在 WKWebView 每帧重栅格化。
el(IWBCanvasEdges.EdgeCanvas, {
edges, graph: edgeGraph, nodeMap: refs.nodeMap, measuredH: refs.measuredH, pathCache: refs.edgePathCache,
computeEdgePath, viewport, selEdge, focusNodeId, edgeHover, hoverEdgeId, tempD, connTarget,
onReady: (fn) => { refs.edgeCanvasDraw = fn },
}),
// Canvas V3:未选中的 ref 节点卡片/图片画在 canvas;DOM 只保留 hit proxy。
canvasV3On ? el(IWCanvasV3NodeLayer.CanvasNodeLayer, {
nodes: nodes.filter((n) => visibleIds.has(n.id)), viewport, sel, types: canvasV3Types, isType: canvasV3TypeOf,
widthOf: nodeWidth, heightOf: hOf, outThumbsFor,
imageFor: (node, raw) => { try { return wImgSrcForNode(raw, 320) || '' } catch (e) { return '' } },
onReady: (fn) => { refs.nodeCanvasDraw = fn },
}) : null,
// 透明 hit path:选择/双击/悬停仍走 SVG(canvas pointer-events:none)。
el('svg', Object.assign({ className: 'iwb-edges' }, CanvasGeometry.edgeLayerProps(canvasSize)),
el('g', { className: 'iwb-edge-world', transform: CanvasGeometry.edgeGroupTransform(viewport) }, edgeEls)),
el('div', {
className: 'iwb-world',
style: { transform: 'translate(' + viewport.x + 'px, ' + viewport.y + 'px) scale(' + viewport.scale + ')' },
},
groupEls,
nodeEls,
),
el(ToolbarBottomMemo, { onAdd: tbOnAdd, onAddPlugin: tbOnAddPlugin, pluginVariants: pluginNodeVariants, onOpenPrompts: tbOnOpenPrompts, onFitView: tbOnFitView, onZoom: tbOnZoom, tool, onTool: tbOnTool }),
saveRecovery ? el('div', { className: 'iwb-resume-bar iwb-save-recovery-bar' },
el('span', { className: 'iwb-resume-text' }, '有一份未安全保存的画布快照:' + ((saveRecovery.error && saveRecovery.error.message) || '保存失败')),
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: retrySaveRecovery }, '重试保存'),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '仅删除恢复提示,不会修改当前画布', onClick: clearSaveRecovery }, '忽略'),
) : null,
storageHealth && !storageHealth.ok ? el('div', { className: 'iwb-resume-bar iwb-save-recovery-bar' },
el('span', { className: 'iwb-resume-text' }, '存储检查异常:' + storageHealth.issues.map((x) => x.message).join(';')),
) : null,
exportRemind.show ? el('div', { className: 'iwb-resume-bar iwb-save-recovery-bar' },
el('span', { className: 'iwb-resume-text' }, '距上次导出备份已 ' + exportRemind.ageDays + ' 天,建议导出一份存到磁盘'),
el('button', { className: 'iwb-btn iwb-btn-sm iwb-btn-primary', title: '打开「设置 → 备份与还原」', onClick: () => { openSettings('backup'); exportRemind.dismiss() } }, '去导出'),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '今天不再提示', onClick: () => exportRemind.dismiss() }, '知道了'),
) : null,
swUpdate ? el('div', { className: 'iwb-resume-bar iwb-update-bar' },
el('span', { className: 'iwb-resume-text' }, '发现新版本可用,点击立即更新到最新版。'),
el('button', { className: 'iwb-btn iwb-btn-sm iwb-btn-primary', title: '更新到新版本并刷新页面', onClick: swUpdateConfirm }, '立即更新'),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '稍后手动刷新', onClick: () => setSwUpdate(false) }, '忽略'),
) : null,
// 上次生成中断横幅:刷新后**仅提示、不自动重跑**(自动重跑=立刻新增扣费);居中展示,点「继续生成」才重新提交请求。
(resumePrompt && resumePrompt.runs && resumePrompt.runs.length) ? (() => {
const runs = resumePrompt.runs
const pendingTotal = runs.reduce((n, r) => n + (r.pending || 0), 0)
const awaitingTotal = runs.reduce((n, r) => n + (r.awaitingN || 0), 0)
const hasRecoverable = runs.some((r) => r && r.status === 'recoverable')
return el('div', { className: 'iwb-resume-bar iwb-resume-center' },
el('span', { className: 'iwb-resume-text' }, '上次生成中断:' + pendingTotal + ' 张图未完成(已完成的结果已保留,不会重复扣费)'),
el('span', { className: 'iwb-resume-warning' }, '继续生成会重新提交请求、再次计费;已中断的请求也可能已产生费用。' + (awaitingTotal > 0 ? '其中 ' + awaitingTotal + ' 张结果未知(可能已在服务商侧完成),不会自动重提。' : '')),
el('div', { className: 'iwb-resume-actions' },
// 视觉层级:默认「不推荐继续生成」(可能重复计费)→ 继续用灰色、取消用黑色主色;
// 全部是「结果未知(awaiting-result)」时左按钮弱化为只做知悉确认(resumeRuns 内会跳过重提)
hasRecoverable
? el('button', { className: 'iwb-btn iwb-btn-sm', title: '重新提交未完成的生成请求(会再次计费)', onClick: resumeRuns }, '▶ 继续生成(再次计费)')
: el('button', { className: 'iwb-btn iwb-btn-sm', title: '结果未知的任务不会自动重提(避免重复计费)', onClick: resumeRuns }, '知道了'),
el('button', { className: 'iwb-btn iwb-btn-sm iwb-btn-primary', title: '取消这次续跑:未完成的张不再生成,不产生新费用', onClick: () => { setResumePrompt(null); try { lsRemove('iwb_web_running') } catch (e) { /* ignore */ } } }, '取消生成'),
),
)
})() : null,
(nodes.length && loaded) ? el(MinimapMemo, {
nodes,
viewport,
canvasSize,
measuredH: refs.measuredH,
measuredT: tick,
onJump: mmOnJump,
}) : null,
(shellView === 'canvas' && DockArea) ? el(DockArea, { panels: dockPanels, renderIcon: I, storageKey: 'iwb.dock.v1', PluginHost,
pluginMount: (id, panelId) => { const p = panelId ? wPluginPanels.find((x) => x.pluginId === id && x.id === panelId) : wPluginPanels.find((x) => x.pluginId === id || x.id === id + '-panel'); return p ? p.mount : null },
rightOpen: drawerOpen, onRightOpen: (v) => setDrawerOpen(v),
defaults: { left: { open: true, w: 318, list: ['groups', 'browser', 'styles'], active: 'browser' }, right: { open: true, w: 330, list: ['prompts', 'gallery'], active: 'gallery' } },
onReject: (msg) => showToast(msg, 'err') }) : null,
settingOpen ? ReactDOM.createPortal(el(SettingsModal, {
pluginIcon: (pid) => resolvePluginIcon(pid),
initialTab: settingTabReq,
BackupModal: BackupModal,
onSaveNow: saveNow,
config,
diagStats: () => wDiagStats(refs.nodes, refs.workspaces),
diagExtras: () => ({ persist: storagePersist, swallowed: (RuntimeMetrics && RuntimeMetrics.snapshot) ? RuntimeMetrics.snapshot() : null, procRssMB: wProcRssMB, layers: !!(document && document.documentElement && document.documentElement.dataset.layers === 'on'), canvasV3: !!(window && window.IWBCanvasV3 && window.IWBCanvasV3.isEnabled && window.IWBCanvasV3.isEnabled()), canvasV3Stats: (window && window.IWBCanvasV3 && window.IWBCanvasV3.stats) ? window.IWBCanvasV3.stats() : null, noblur: (document && document.documentElement && document.documentElement.dataset.noblur === 'on'), dom: (function () { try { return { els: document.getElementsByTagName('*').length, dock: document.querySelectorAll('.iwb-dock *').length, cards: document.querySelectorAll('.iwb-history-item').length } } catch (e) { return null } })() }), // v3.26.121 RSS + v3.26.127 DOM 规模 // 持久化 + 被忽略错误(2026-11-07)
...autoBackupKit, // autoBackup / autoBackupSave / autoBackupRestore / autoBackupRefresh
diagText: () => buildRuntimeDiagnosticsText([], (typeof window !== 'undefined' && window.__IWB_BUILD_META__) || {}),
onExportDiag: () => exportRuntimeDiagnostics(),
onClose: () => setSettingOpen(false),
onSaved: () => {
api('config').then((r) => { if (r && Array.isArray(r.providers)) setConfig(r) }).catch(() => {})
},
onRefreshOutputs: () => refreshOutputs(100), onStorageAudit: () => wStorageAudit(), onReclaimOrphans: async () => { await wReclaimOrphansNow(); return await wStorageAudit() },
// v3.26.117:手动「立即回收内存」(诊断页按钮)。只清可重建的缓存与可反推的引用形态。
onReclaimMemory: () => wReclaimMemoryNow('manual'),
onDiagDetail: () => wDiagDetail(),
// v3.26.136:合成层常驻提升开关(立即生效,改完看「进程实测」对比)
onToggleLayers: (on) => { try { document.documentElement.dataset.layers = on ? 'on' : 'off'; lsSet('iwb_layers_on', !!on) } catch (e) { /* ignore */ } },
onToggleCanvasV3: (on) => { try { if (window.IWBCanvasV3) window.IWBCanvasV3.setEnabled(!!on) } catch (e) { /* ignore */ } },
onToggleNoBlur: (on) => { try { if (on) document.documentElement.dataset.noblur = 'on'; else delete document.documentElement.dataset.noblur; lsSet('iwb_noblur_on', !!on) } catch (e) { /* ignore */ } },
}), document.body) : null,
helpOpen ? ReactDOM.createPortal(el('div', { className: 'iwb-modal-mask', onWheel: (e) => e.stopPropagation(), onPointerDown: (e) => { if (e.target === e.currentTarget) setHelpOpen(false) } },
el('div', { className: 'iwb-modal iwb-modal-sm iwb-help-modal' },
el('div', { className: 'iwb-modal-head' },
el('span', { className: 'iwb-toolbar-title' }, helpMode === 'help' ? '操作帮助' : '快捷键'),
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => setHelpOpen(false) }, '✕'),
),
el('div', { className: 'iwb-modal-body iwb-help', onWheel: (e) => e.stopPropagation() },
HotkeyHelp
? el(HotkeyHelp, { mode: helpMode === 'help' ? 'help' : 'keys', hotkeys: (config && config.canvas && config.canvas.hotkeys) || {}, defaults: HOTKEY_DEFAULTS })
: el('div', { className: 'iwb-hint' }, '快捷键模块未就绪'),
),
),
), document.body) : null,
// 自定义右键菜单(屏蔽浏览器默认菜单)
connMenu && ConnectMenu ? el(ConnectMenu, { direction: connMenu.direction, options: connMenu.options, sx: connMenu.sx, sy: connMenu.sy, renderIcon: (t) => I(nodeTypeIcon(t) || 'star'), onPick: (type) => { const pm = connMenu; setConnMenu(null); ConnectMenuMod.pick({ direction: pm.direction, type, wx: pm.wx, wy: pm.wy, fromId: pm.fromId, toId: pm.toId, batchSrcId: pm.batchSrcId, defaults: DEFAULTS, uid, createNode: (t, sp, d, u) => CanvasNodeFactory.createNode(t, sp, d, u), nodes: refs.nodes, edges: refs.edges, pushHistory, commitCanvas, setSel, saveNow }) }, onClose: () => setConnMenu(null) }) : null,
ctxMenu ? el('div', { className: 'iwb-ctxmask', onPointerDown: (e) => { if (e.target === e.currentTarget) setCtxMenu(null) }, onContextMenu: (e) => { e.preventDefault(); setCtxMenu(null) } },
el('div', { className: 'iwb-ctxmenu iwb-ctx-noclip', ref: ctxMenuRef, style: { left: Math.min(ctxMenu.x, (window.innerWidth || 1200) - 210), top: Math.min(ctxMenu.y, (window.innerHeight || 800) - 320) }, onPointerDown: (e) => e.stopPropagation(), onContextMenu: (e) => e.stopPropagation() },
el('div', { className: 'iwb-ctx-title' }, '添加节点'),
[['prompt', '提示词', I('file-text')], ['ref', '图片', I('ref')], ['textout', '文本', I('textout')], ['combine', '组合', I('server-plus')], ['batch', '连接', I('batch')], ['relay', '中继', I('circle-dot')], ['gen', '配置', I('gen')], ...(wPrivateToolsOn ? [['llm', '润色', I('llm')], ['layer', '分层', I('layer')]] : []), ['out', '输出', I('presentation')]].map(([t, label, ic]) => el('button', { key: t, className: 'iwb-ctx-item', onClick: () => { addNode(t, Math.round(ctxMenu.wx - NODE_W / 2), Math.round(ctxMenu.wy - 20)); setCtxMenu(null) } }, ic, el('span', { className: 'iwb-btn-text' }, label))),
// 插件节点单独成组(2026-11-19 用户要求):与内置节点之间加分割线 + 组标题,
// 不再挤在「输出」后面让用户以为也是内置类型。插件停用/未装时整组(含分隔线)不渲染。
...(pluginNodeVariants.some((v) => !ctxSkippedVariant(v)) ? [el('div', { key: 'plug-sep', className: 'iwb-ctx-sep' }, null), el('div', { key: 'plug-title', className: 'iwb-ctx-title' }, '插件节点'), ...pluginNodeVariants.filter((v) => !ctxSkippedVariant(v)).map((v) => el('button', { key: 'plugin-node-' + v.id, className: 'iwb-ctx-item', onClick: () => { addPluginNode(v.id, Math.round(ctxMenu.wx - NODE_W / 2), Math.round(ctxMenu.wy - 20)); setCtxMenu(null) } }, I(v.icon || 'puzzle'), el('span', { className: 'iwb-btn-text' }, String(v.title || v.id))))] : []),
el('div', { className: 'iwb-ctx-sep' }, null),
// 两组收进二级菜单(2026-11-19 用户要求:一级 18 项太长)。入口是普通 button:
// hover / 键盘 Tab / 点击获得焦点都会用 :focus-within 展开,条目与原来完全一致。
(() => { const canPaste = !!readClipboardGraph(); return el('div', { className: 'iwb-ctx-subwrap' }, el('button', { className: 'iwb-ctx-item' }, I('copy'), el('span', { className: 'iwb-btn-text' }, sel.length ? '选中操作' : '画布操作'), el('i', { className: 'iwb-ctx-arrow' }, '▸')),
el('div', { className: 'iwb-ctxmenu iwb-ctx-sub' },
sel.length ? el('button', { className: 'iwb-ctx-item', onClick: () => { duplicateNodes(sel); setCtxMenu(null) } }, I('copy'), el('span', { className: 'iwb-btn-text' }, '复制选中(⌘D)')) : null, sel.length ? el('button', { className: 'iwb-ctx-item', onClick: () => { exportSelectedGroup(); setCtxMenu(null) } }, I('upload'), el('span', { className: 'iwb-btn-text' }, '导出选中节点组')) : null,
(sel.length && groups.some((x) => x.memberIds.length && x.memberIds.every((id) => sel.includes(id)))) ? el('button', { className: 'iwb-ctx-item', onClick: () => { const gg = groups.find((x) => x.memberIds.length && x.memberIds.every((id) => sel.includes(id))); if (gg) saveGroupSnapshot(gg); setCtxMenu(null) } }, I('star'), el('span', { className: 'iwb-btn-text' }, '收藏节点组')) : null, sel.length ? el('button', { className: 'iwb-ctx-item', onClick: () => { const ttlD = sel.map((id) => refs.nodes.find((n) => n.id === id)).filter((n) => n && n.data && n.data.title && String(n.data.title).trim()).map((n) => n.data.title)[0]; setCtxMenu(null); td.open({ title: '收藏选中节点为节点组', value: ttlD || ('节点组 ' + (savedGroups.length + 1)), onSubmit: (nm) => saveSelectionAsGroup(sel, nm) }) } }, I('star'), el('span', { className: 'iwb-btn-text' }, '收藏选中节点')) : null,
sel.length ? el('button', { className: 'iwb-ctx-item iwb-ctx-danger', onClick: () => { deleteNodes(sel); setCtxMenu(null) } }, I('x'), el('span', { className: 'iwb-btn-text' }, '删除选中(Delete)')) : null,
el('div', { className: 'iwb-ctx-sep' }, null),
el('button', { className: 'iwb-ctx-item', disabled: !canPaste, onClick: () => { pasteCopiedNodes(); setCtxMenu(null) } }, I('paste'), el('span', { className: 'iwb-btn-text' }, '粘贴节点组')), el('button', { className: 'iwb-ctx-item', disabled: !canPaste, onClick: () => { clearClipboard(); setCtxMenu(null) } }, I('x'), el('span', { className: 'iwb-btn-text' }, '清空剪贴板')),
)) })(),
(() => {
const tgt = ctxMenu.targetId ? refs.nodes.find((n) => n.id === ctxMenu.targetId) : null
if (!tgt) return null
const items = []
if (isImageProducer(tgt)) items.push(el('button', { key: 'run', className: 'iwb-ctx-item', onClick: () => { runProducer(tgt.id); setCtxMenu(null) } }, I('run'), el('span', { className: 'iwb-btn-text' }, tgt.type === 'layer' ? '运行该分层' : '运行该生图')))
if (tgt.type === 'llm') items.push(el('button', { key: 'pol', className: 'iwb-ctx-item', onClick: () => { runLLM(tgt.id); setCtxMenu(null) } }, I('llm'), el('span', { className: 'iwb-btn-text' }, '▶ 润色')))
if (tgt.type === 'ref' && tgt.data && typeof tgt.data.orig === 'string' && tgt.data.orig) items.push(el('button', { key: 'restore-orig', className: 'iwb-ctx-item', onClick: () => { pushHistory(); updateNode(tgt.id, { data: tgt.data.orig, url: '', orig: '' }); setCtxMenu(null) } }, I('undo'), el('span', { className: 'iwb-btn-text' }, '还原替换前原图')))
items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) => { const rc = e && e.currentTarget ? e.currentTarget.getBoundingClientRect() : null; setCtxMenu(null); if (UiGenCfgModule && UiGenCfgModule.openNodeBgPalette) UiGenCfgModule.openNodeBgPalette({ current: (tgt.data && tgt.data.bg) || '', anchorRect: rc, onPreview: (bg) => previewNodeBg([tgt.id], bg), onPreviewEnd: endNodeBgPreview, onPick: (bg) => updateNode(tgt.id, { bg }) }) } }, I('palette'), el('span', { className: 'iwb-btn-text' }, '背景色')), el('button', { key: 'ren', className: 'iwb-ctx-item', onClick: () => { setCtxMenu(null); wRenameNodeDialog(tgt, td, updateNode) } }, I('edit'), el('span', { className: 'iwb-btn-text' }, '重命名节点')), el('button', { key: 'del', className: 'iwb-ctx-item iwb-ctx-danger', onClick: () => { deleteNodes([tgt.id]); setCtxMenu(null) } }, I('x'), el('span', { className: 'iwb-btn-text' }, '删除该节点')))
// 子菜单默认向上展开(底对齐入口):两组入口都在一级菜单下半区,向下会顶出视口
return el('div', { className: 'iwb-ctx-subwrap' }, el('button', { className: 'iwb-ctx-item' }, I('edit'), el('span', { className: 'iwb-btn-text' }, '该节点'), el('i', { className: 'iwb-ctx-arrow' }, '▸')), el('div', { className: 'iwb-ctxmenu iwb-ctx-sub' }, items))
})(),
// 插件命令(v3.26.109 恢复渲染):由 ctx.commands.register 注册,插件停用即消失
wPluginCommands.filter((c) => !ctxSkippedCommand(c)).length ? el('div', { className: 'iwb-ctx-sep' }, null) : null,
...wPluginCommands.filter((c) => !ctxSkippedCommand(c)).map((c) => el('button', { key: 'pcmd_' + c.id, className: 'iwb-ctx-item iwb-ctx-plugin', onClick: () => { setCtxMenu(null); try { const r = c.run(); if (r && typeof r.catch === 'function') r.catch(() => {}) } catch (e) { setNotice({ type: 'err', text: '插件命令失败:' + String((e && e.message) || e) }) } } }, I(c.icon || 'puzzle'), el('span', { className: 'iwb-btn-text' }, c.title))),
el('div', { className: 'iwb-ctx-sep' }, null),
),
) : null,
toast ? ReactDOM.createPortal(el('div', { className: 'iwb-toast iwb-toast-' + toast.type }, toast.text), document.body) : null, // portal 到 body:.iwb-overlay 是堆叠上下文,内联再高也压不过弹窗(见 tests/overlay-layer-test.js)
preview ? ReactDOM.createPortal(el(ImagePreview, { list: (typeof preview === 'string' ? [preview] : preview.list), idx: (typeof preview === 'string' ? 0 : preview.idx), onNav: (i) => setPreview({ list: (typeof preview === 'string' ? [preview] : preview.list), idx: i }), onClose: () => setPreview(null), onFlash: (t, ty) => setNotice({ type: ty === 'err' ? 'err' : 'ok', text: t }) }), document.body) : null,
),
)
}
// 图片预览:list 条目可以是「已解析的 src 字符串」(画布节点预览),
// 也可以是图库条目的引用对象 { __gallery, name, origIdb, idb, url, thumb }。
// 引用条目只在轮到它时才解析原图(相邻 ±1 预取),解析结果是有界 objectURL,关闭/切换即 revoke ——
// 不再把整库原图 base64 一次性读进堆(原来 200 张 = +427MB 且不回落)。
// 节点体渲染模块(按节点类型分派的各分支;2026-10-29 从 renderBodyInner 搬出)
const IWNodeBodies = (typeof window !== 'undefined' && window.IWBNodeBodies) || null
// Workbench 内大逻辑单元(runNode / saveNow 等;2026-10-29 搬出)
const IWWorkbenchLogic = (typeof window !== 'undefined' && window.IWBWorkbenchLogic) || null
const IWCanvasPointer = (typeof window !== 'undefined' && window.IWBCanvasPointer) || null
const ImagePreview = _mod.ImagePreview
// 私有开关必须在首次渲染前读一次(渲染时用它决定入口是否出现);
// 监听 hashchange:在同一个标签页里粘 #iwb-tools=… 也能生效(下一次 re-render 即读到新值)。
wReadPrivateTools()
if (typeof window !== 'undefined') window.addEventListener('hashchange', () => { wReadPrivateTools() })
// 崩溃可观测性:先装全局钩子(window.onerror / unhandledrejection),再由错误边界补齐渲染期异常
if (CrashLog && typeof CrashLog.install === 'function') {
CrashLog.install(() => {
const c = (typeof window !== 'undefined' && window.__IWB_DIAG_CTX__) || {}
return { version: APP_VERSION, boardId: c.boardId || '', nodeId: c.nodeId || '' }
})
}
// 插件宿主:插件在模块加载期完成注册,这里只补运行时依赖(本地状态存取 + 日志),并按已启用项激活。
// A2 运行时插件加载:读同源 /plugins/index.json(KV 提供)→ 动态插 <script src="/plugins/<file>"> →
// 插件自我注册。同源脚本本就被 CSP script-src 'self' 允许 ⇒ 不放宽 CSP、不重编译主包。
// 按需下载:启动只下载「已启用」的远程插件;未启用的记为 idle、不下载,等用户在插件管理里勾选时再加载。
// 单条远程插件的下载+激活(启动批量加载与按需加载共用):注入脚本(SRI 强制校验)→ 自我注册 → 持久化开关已开则激活。
// 加载实现已抽到 src/runtime-plugin-loader.js(app.js 只做装配)
function wPluginLoader () {
return (typeof window !== 'undefined') ? window.IWBRuntimePluginLoader : null
}
function wPluginSource () {
const L = wPluginLoader()
return (L && typeof L.source === 'function') ? L.source() : null
}
// 市场实现已抽到 src/runtime-plugin-market.js
function wMarketMod () {
return (typeof window !== 'undefined') ? window.IWBRuntimePluginMarket : null
}
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
}
async function wLoadPluginEntry (record) {
const L = wPluginLoader()
if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false }
return L.loadBuiltin(record)
}
async function wLoadExternalPluginEntry (record) {
const L = wPluginLoader()
if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false }
return L.loadExternal(record)
}
async function wLoadLocalPluginEntry (record) {
const L = wPluginLoader()
if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false }
return L.loadLocal(record)
}
// 按需加载(插件管理里勾选 idle 行):下载脚本 → 注册 → 显式启用;失败时返回错误供 UI 回滚勾选并提示。
async function wEnsurePluginLoaded(id) {
const record = wRuntimePlugins.find((r) => r.id === id)
if (!record) return { ok: false, error: '远程插件清单里没有:' + id }
if (record.status === 'loaded') return { ok: true }
if (!record.integrity) return { ok: false, error: record.error || 'integrity 缺失(拒绝加载)' }
const loaded = await wLoadPluginEntry(record)
if (!loaded) return { ok: false, error: record.error || '脚本已加载但插件未注册' }
const r = PluginHost && typeof PluginHost.setEnabled === 'function' ? PluginHost.setEnabled(id, true) : null
return r && r.ok ? { ok: true } : { ok: false, error: (r && r.error) || '启用失败' }
}
// 后台预热市场索引:设置页打开时直接命中缓存(网络慢也不影响首屏)
function wWarmMarketCache() {
try {
setTimeout(function () {
try { const p = wMarketList(); if (p && typeof p.catch === 'function') p.catch(function () { /* 离线也正常 */ }) } catch (e) { /* ignore */ }
}, 2500)
} catch (e) { /* ignore */ }
}
async function wLoadRuntimePlugins() {
if (typeof fetch !== 'function' || typeof document === 'undefined') return
// 内置清单(随包)先读;外部清单(<资料目录>/plugins/)只覆盖同 id 的条目 —— 合并而非替换
let builtin = []
try {
const resp = await fetch('/plugins/index.json', { cache: 'no-store' })
if (resp.ok) {
const j = await resp.json()
builtin = Array.isArray(j) ? j : (Array.isArray(j && j.plugins) ? j.plugins : [])
}
} catch (e) { /* 内置读不到就只看外部 */ }
let ext = []
try {
const src = wPluginSource()
if (src) ext = await src.manifest()
} catch (e) { /* 外部清单读到一半失败:忽略 */ }
const byId = new Map(builtin.map((e) => [String((e && e.id) || ''), Object.assign({}, e, { source: 'builtin' })]))
// 开发者模式:<资料目录>/plugins/local/<id>/plugin.js(未签名,仅本地调试用)
try {
const devRaw = lsGet('iwb_plugin_dev', false)
const devOn = devRaw === true || devRaw === 'true' || devRaw === 1 || devRaw === '1'
const lsrc = wPluginSource()
if (devOn && lsrc && typeof lsrc.listLocal === 'function') {
const locals = await lsrc.listLocal()
try { lsSet('iwb_plugin_dev_count', (locals || []).length) } catch (e1) { /* probe */ }
for (const l of locals) { if (l && l.id) byId.set(String(l.id), { id: String(l.id), file: 'plugin.js', version: 'dev', source: 'local', code: l.code }) }
}
} catch (e) { /* 开发者模式读取失败不影响启动 */ }
const VC = (a, b) => { const L = wPluginLoader(); return (L && L.compareVersions) ? L.compareVersions(a, b) : 0 }
for (const e of ext) { const id = String((e && e.id) || ''); if (id) { const cur = byId.get(id); if (!cur || VC(e.version, cur.version) >= 0) byId.set(id, Object.assign({}, e, { source: 'external' })) } }
// 目录插件(v3.25.41):扫描 <资料目录>/plugins/*/manifest.json;与单文件同 id 时目录优先
try { const L0 = wPluginLoader(); if (L0 && L0.listFolderEntries) for (const e of await L0.listFolderEntries()) { const cur = byId.get(e.id); if (!cur || (L0.compareVersions && L0.compareVersions(e.version, cur.version) >= 0)) byId.set(e.id, e) } } catch (e2) { /* 目录扫描失败不影响内置加载 */ }
// 关键:加载前先快照「用户关掉过哪些插件」,加载过程绝不能覆盖这个状态
let persistedState = {}
try {
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
if (F && typeof F.ready === 'function') { try { await F.ready({ wizard: false }) } catch (e) { /* 已就绪 */ } }
const v = lsGet('iwb_plugins', {})
persistedState = (v && typeof v === 'object') ? v : {}
} catch (e) { persistedState = {} }
const manifest = Array.from(byId.values())
if (!manifest.length) return
const list = Array.isArray(manifest) ? manifest : (manifest && Array.isArray(manifest.plugins) ? manifest.plugins : [])
const ordered = list.slice().sort((a, b) => String((a && a.id) || '').localeCompare(String((b && b.id) || '')))
const pending = [] // 已启用插件的加载 Promise:循环内全部同步 append 后再并行等待(执行顺序由 script.async=false 保证)
for (const entry of ordered) {
const id = String((entry && entry.id) || '')
const file = String((entry && entry.file) || '')
const isExt = (entry && entry.source) === 'external'
const isLocalEntry = (entry && entry.source) === 'local'
const dir = String((entry && entry.dir) || '')
const mainName = String((entry && entry.main) || 'main.js')
const record = { id, dir, main: mainName, style: String((entry && entry.style) || ''), hashes: (entry && entry.files) || null, file: dir ? dir + '/' + mainName : file, version: (entry && entry.version) || '', status: 'loading', error: null, code: (entry && entry.code) || '', source: isExt ? 'external' : ((entry && entry.source === 'local') ? 'local' : 'builtin') }
wRuntimePlugins.push(record)
if (!id) { record.status = 'bad-entry'; continue }
if (dir) {
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{1,63}$/.test(dir) || !/^[A-Za-z0-9._-]+\.js$/.test(mainName)) { record.status = 'bad-entry'; record.error = '目录或入口名不合法'; continue }
if (!record.hashes || !record.hashes[mainName]) { record.status = 'bad-entry'; record.error = '缺少文件哈希(拒绝加载)'; continue }
const LF = wPluginLoader(); if (PluginHost && LF && LF.loadFolder) pending.push(LF.loadFolder(record)); else record.status = 'idle'
continue
}
if (!/^[A-Za-z0-9._-]+$/.test(file)) { record.status = 'bad-entry'; continue }
const integrity = String((entry && entry.integrity) || '')
// fail-closed:无 integrity 声明即拒绝加载(清单由 KV 发布脚本生成、必带 integrity;缺失视为不可信)
if (!integrity && !isLocalEntry) { record.status = 'bad-entry'; record.error = 'integrity 缺失(拒绝加载)'; continue }
if (integrity && !/^sha(256|384|512)-[A-Za-z0-9+/]{40,}={0,2}$/.test(integrity)) { record.status = 'bad-entry'; record.error = 'integrity 格式不合法'; continue }
record.integrity = integrity
// 只下载已启用的;未启用记 idle(不注入脚本),插件管理里勾选时经 wEnsurePluginLoaded 按需下载
// 收进 pending 而非逐个 await:wLoadPluginEntry 在首个 await 前已 append ⇒ 并发抓取;async=false 保证执行顺序不变(冷启动 3 RTT → 1)
// 本地开发插件默认启用(没有持久化状态,不应被当作已关闭的插件)
// 一律加载脚本(注册 ≠ 启用):脚本注册后才能被开关随时启停;
// 之前按 enabled 预筛,导致状态里残留 false 的插件永远进不了注册表,开关也打不开。
if (PluginHost) pending.push(isLocalEntry ? wLoadLocalPluginEntry(record) : (isExt ? wLoadExternalPluginEntry(record) : wLoadPluginEntry(record)))
else record.status = 'idle'
}
await Promise.all(pending)
// 脚本都注册了:把持久化里明确关掉的插件停用(其余保持启用)
try {
const st = persistedState || {}
for (const r of (wRuntimePlugins || [])) {
if (!r || r.status !== 'loaded') continue
const rec = st[r.id]
// 没有持久化记录 ⇒ 默认启用(修复:首次安装/清空存储后插件永远不激活,面板显示"未加载")
const want = !rec || rec.enabled !== false
if (!PluginHost || typeof PluginHost.setEnabled !== 'function') continue
// 注意:插件是在 init() 之后才注册的,init 的"激活已启用项"覆盖不到它们。
// 所以这里对 want=true 一律再 setEnabled(true)(activate 幂等:已激活会返回 already),
// 否则会出现"开关显示已启用、实际没跑工厂函数"的假启用状态。
if (want) PluginHost.setEnabled(r.id, true)
else if (typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(r.id)) PluginHost.setEnabled(r.id, false)
}
} catch (e) { /* 状态应用失败不影响加载 */ }
try { lsSet('iwb_plugin_load_status', JSON.stringify(wRuntimePlugins.map((r) => ({ id: r.id, status: r.status, source: r.source, error: r.error || '' })))) } catch (e2) { /* probe */ }
try { if (PluginHost && typeof PluginHost.emit === 'function') PluginHost.emit('runtime-plugins-loaded') } catch (e) { /* 通知失败不影响启动 */ }
}
if (PluginHost && typeof PluginHost.init === 'function') {
try {
PluginHost.init({
onActivate: (id) => { const L = wPluginLoader(); if (L && L.applyStyleFor) L.applyStyleFor(id) },
onDeactivate: (id) => { const L = wPluginLoader(); if (L && L.removeStyle) L.removeStyle(id) },
readState: () => { const v = lsGet('iwb_plugins', {}); return v && typeof v === 'object' ? v : {} },
writeState: (state) => { lsSet('iwb_plugins', state) },
log: () => { try { wLog.apply(null, arguments) } catch (e) { /* ignore */ } },
capabilities: {
gallery: () => ((typeof window !== 'undefined' && window.IWBPluginGallery) ? window.IWBPluginGallery.api() : {}),
grouplib: () => ((typeof window !== 'undefined' && window.IWBPluginGroupLib) ? window.IWBPluginGroupLib.api() : {}),
promptlib: () => ((typeof window !== 'undefined' && window.IWBPluginPromptLib) ? window.IWBPluginPromptLib.api() : {}),
// 插件文件能力(v3.26.36):沙箱目录 plugin-data/<id>/files,供插件自持图片
// 插件图片能力(2026-11-26):相册需要「只引用本地文件」+「把字节写进宿主存储」两条
images: (ctx) => {
const M = (typeof window !== 'undefined' && window.IWBPluginApiImages) ? window.IWBPluginApiImages : null
const F = wFileRefMod()
if (!M || !F) return { canReference: () => false }
return M.create({
fileRef: F,
importDataUrl: (url, opts) => new Promise((resolve) => { try { wImportImage(url, opts || {}, (p) => resolve(p || { ok: false, error: 'import-failed' })) } catch (e) { resolve({ ok: false, error: 'import-threw' }) } }),
readDataUrl: (v) => (typeof v === 'string' ? Promise.resolve(v) : wImgRefDataUrl(v)),
thumbUrlOf: (v) => wDisplayThumbOf(v),
thumbFor: (v, o) => wPluginThumb(v, o),
previewFor: (v, o) => wPluginPreview(v, o),
originalFor: (v) => wPluginOriginal(v),
budgetOf: () => wPluginDecodeBudget(),
})(ctx)
},
files: (ctx) => {
const F = (typeof window !== 'undefined' && window.IWBStorageFile) ? window.IWBStorageFile.pluginFiles : null
const need = () => { if (!F) throw new Error('文件能力未就绪(资料目录尚未初始化)'); return F }
return {
put: (name, dataUrl) => need().put(ctx.id, name, dataUrl),
get: (name) => need().get(ctx.id, name),
list: () => need().list(ctx.id),
remove: (name) => need().remove(ctx.id, name),
stat: () => need().stat(ctx.id),
dir: () => need().dir(ctx.id),
}
},
commands: (ctx) => {
const owned = []
return {
register: (cmd) => {
if (!cmd || typeof cmd.run !== 'function') return false
const entry = { id: String(ctx.id) + ':' + String(cmd.id || owned.length), pluginId: ctx.id, title: String(cmd.title || cmd.id || ''), icon: pluginIconOf(ctx.id) || cmd.icon, run: cmd.run }
wPluginCommands.push(entry)
owned.push(entry)
return true
},
dispose: () => {
for (const entry of owned.splice(0)) {
const index = wPluginCommands.indexOf(entry)
if (index >= 0) wPluginCommands.splice(index, 1)
}
},
}
},
nodeTypes: (ctx) => {
const owned = []
return {
register: (variant) => {
if (!variant || !variant.id || !variant.title) return false
// 2026-11-14:变体可以自定义节点体 / 端口 / 初始高度(首个使用方 = style-source 的样式节点)。
// 透传之前这里把 ports 写死 {in:true,out:true}、height 写死 200、render 直接丢掉 ——
// 插件节点因此永远是「标题 + 一个 textarea + 运行按钮」,也永远关不掉入端口。
// ports 是硬需求:样式节点一旦被连了入边,兜底分支就会用上游文本顶掉它自己渲染的提示词。
const ports = (variant.ports && typeof variant.ports === 'object')
? { in: !!variant.ports.in, out: !!variant.ports.out }
: { in: true, out: true }
const height = Number.isFinite(variant.height) ? variant.height : 200
const color = (typeof variant.color === 'string' && variant.color) ? variant.color : '#969696'
const entry = { id: String(variant.id), title: String(variant.title), defaults: variant.defaults || {}, run: typeof variant.run === 'function' ? variant.run : null, pluginId: ctx.id, icon: resolvePluginIcon(ctx.id, variant.icon), toolbar: (variant.toolbar === 'hide' || PLUGIN_TOOLBAR_HIDE[ctx.id]) ? 'hide' : 'show', w: Number.isFinite(variant.width) ? variant.width : undefined }
wPluginNodeVariants.push(entry)
owned.push(entry)
wPluginVariantMeta.set(entry.id, { id: entry.id, title: entry.title, defaults: entry.defaults, pluginId: ctx.id, ports: ports, height: height })
registerNodeType({ id: pluginTypeId(ctx.id, entry.id), title: entry.title, defaults: entry.defaults, height: height, color: color, hasTitle: true, producer: false, ports: ports, icon: entry.icon, run: entry.run, render: typeof variant.render === 'function' ? variant.render : null })
try {
const meta = ctx.storage && typeof ctx.storage.namespace === 'function' ? ctx.storage.namespace('__nodeTypes') : null
if (meta) meta.set(entry.id, { id: entry.id, title: entry.title, defaults: entry.defaults, ports: ports, height: height })
} catch (e) { /* F1b:元数据持久化失败不阻断注册 */ }
return true
},
dispose: () => {
for (const entry of owned.splice(0)) {
const index = wPluginNodeVariants.indexOf(entry)
if (index >= 0) wPluginNodeVariants.splice(index, 1)
}
},
}
},
panels: (ctx) => {
const owned = []
return {
registerPanel: (panel) => {
if (!panel || !panel.id || !panel.title || typeof panel.mount !== 'function') return false
// v3.26.11:同一插件重复注册同一 id 时**替换**而不是追加(否则停靠栏会越点越多)
for (let i = wPluginPanels.length - 1; i >= 0; i--) {
const e = wPluginPanels[i]
if (e && e.pluginId === ctx.id && e.id === String(panel.id)) wPluginPanels.splice(i, 1)
}
const entry = { id: String(panel.id), title: String(panel.title), icon: pluginIconOf(ctx.id) || panel.icon, mount: panel.mount, pluginId: ctx.id, side: panel.side === 'left' ? 'left' : 'right' }
wPluginPanels.push(entry)
owned.push(entry)
return true
},
dispose: () => {
for (const entry of owned.splice(0)) {
const index = wPluginPanels.indexOf(entry)
if (index >= 0) wPluginPanels.splice(index, 1)
}
},
}
},
generationHooks: (ctx) => {
const owned = []
return {
use: (hooks) => {
if (!hooks || typeof hooks !== 'object') return false
const before = typeof hooks.beforeRequest === 'function' ? hooks.beforeRequest : null
const after = typeof hooks.afterResult === 'function' ? hooks.afterResult : null
if (!before && !after) return false
const entry = { beforeRequest: before, afterResult: after, pluginId: ctx.id }
wPluginGenHooks.push(entry)
owned.push(entry)
return true
},
dispose: () => {
for (const entry of owned.splice(0)) {
const index = wPluginGenHooks.indexOf(entry)
if (index >= 0) wPluginGenHooks.splice(index, 1)
}
},
}
},
providers: (ctx) => {
const owned = []
return {
register: (spec) => {
if (!spec || !spec.id || !spec.baseUrl) return false
if (wPluginProviders.some((p) => p.id === spec.id)) return false
const provider = {
id: String(spec.id),
name: String(spec.name || spec.id),
baseUrl: (_wCfgShape && _wCfgShape.normalizeEndpointBase) ? _wCfgShape.normalizeEndpointBase(spec.baseUrl) : String(spec.baseUrl || '').trim(),
kind: spec.kind,
genPath: spec.genPath,
editPath: spec.editPath,
models: Array.isArray(spec.models) ? spec.models : [],
keys: [{ id: 'plugin-key', value: String(spec.key || '') }],
pluginId: ctx.id,
}
wPluginProviders.push(provider)
owned.push(provider)
return true
},
dispose: () => {
for (const entry of owned.splice(0)) {
const index = wPluginProviders.indexOf(entry)
if (index >= 0) wPluginProviders.splice(index, 1)
}
},
}
},
canvas: () => ({
getNodes: () => (wPluginCanvasBridge ? wPluginCanvasBridge.getNodes() : []),
listNodeTypes: () => [...NODE_TYPES.keys()],
getSelectedNode: () => (wPluginCanvasBridge ? wPluginCanvasBridge.getSelectedNode() : null),
getNodeImage: async (id, opts) => (wPluginCanvasBridge ? wPluginCanvasBridge.getNodeImage(id, opts) : null),
// 只读坐标换算:插件拖拽插入时把「松手点」换成世界坐标(不给插件 viewport,避免它自己算偏)
screenToWorld: (clientX, clientY) => (wPluginCanvasBridge ? wPluginCanvasBridge.screenToWorld(clientX, clientY) : null),
}),
canvasWrite: () => ({
createNode: (type, x, y, data) => (wPluginCanvasBridge ? wPluginCanvasBridge.createNode(type, x, y, data) : null),
createImageNode: (payload) => (wPluginCanvasBridge ? wPluginCanvasBridge.createImageNode(payload) : null),
setNodeImage: (id, dataUrl) => (wPluginCanvasBridge ? wPluginCanvasBridge.setNodeImage(id, dataUrl) : false),
saveNodeImage: (id, dataUrl) => (wPluginCanvasBridge ? wPluginCanvasBridge.saveNodeImage(id, dataUrl) : Promise.resolve({ ok: false, error: '画布能力未就绪' })),
}),
nodeActions: (ctx) => {
const owned = []
return {
register: (action) => {
if (!action || !action.id || !action.title || typeof action.run !== 'function') return false
if (wPluginNodeActions.some((a) => a.id === action.id)) return false
const entry = { id: String(action.id), title: String(action.title), icon: pluginIconOf(ctx.id) || action.icon, appliesTo: typeof action.appliesTo === 'function' ? action.appliesTo : null, run: action.run, pluginId: ctx.id }
wPluginNodeActions.push(entry)
owned.push(entry)
return true
},
dispose: () => {
for (const entry of owned.splice(0)) {
const index = wPluginNodeActions.indexOf(entry)
if (index >= 0) wPluginNodeActions.splice(index, 1)
}
},
}
},
},
})
} catch (e) { /* 插件宿主初始化失败不得影响应用启动 */ }
// F2:把持久化的变体元数据预注册到渲染回退表 —— 插件停用/未加载/换设备时旧插件节点仍可渲染标题
try {
const st = lsGet('iwb_plugins', {}) || {}
for (const pid of Object.keys(st)) {
const rec = st[pid]
const nt = rec && rec.data && rec.data.__nodeTypes
if (!nt || typeof nt !== 'object') continue
for (const vid of Object.keys(nt)) {
const m = nt[vid]
if (!m || !m.id) continue
// ports / height 也要跟着持久化元数据恢复(2026-11-14):插件脚本是异步下载的,
// 冷启动这段预注册先跑,此时若还按 {in:true} 注册,样式节点会先亮出一个**入端口**,
// 用户在这几百毫秒里连上去就会让上游文本顶掉它自己渲染的提示词。
const mPorts = (m.ports && typeof m.ports === 'object') ? { in: !!m.ports.in, out: !!m.ports.out } : { in: true, out: true }
const mHeight = Number.isFinite(m.height) ? m.height : 200
if (!wPluginVariantMeta.has(String(m.id))) wPluginVariantMeta.set(String(m.id), { id: String(m.id), title: String(m.title || m.id), defaults: m.defaults || {}, pluginId: pid, restored: true, ports: mPorts, height: mHeight })
registerNodeType({ id: pluginTypeId(pid, m.id), title: String(m.title || m.id), defaults: m.defaults || {}, height: mHeight, color: '#969696', hasTitle: true, producer: false, ports: mPorts })
}
}
} catch (e) { /* 预注册失败不影响启动 */ }
wLoadRuntimePlugins()
wWarmMarketCache()
}
// 桌面端关闭图库定时清理(设置里已去掉该项):0 = 不限,避免老图被静默删掉
try {
if (wFileStoreOn() && lsGet('iwb_retention_off_v1', false) !== true) {
const rawCfg = LocalStore.get(StorageContract.localKeys.config, null)
if (rawCfg && typeof rawCfg === 'object') {
rawCfg.outputsRetention = Object.assign({}, rawCfg.outputsRetention, { enabled: false, maxDays: 0, maxFiles: 0 })
lsSet(StorageContract.localKeys.config, rawCfg)
}
lsSet('iwb_retention_off_v1', true)
}
} catch (e) { /* ignore */ }
// 历史内联图 → 文件引用(只跑一次;让 data.json 从几百 KB 掉回几十 KB)
try { await wMigrateInlineImages() } catch (e) { /* ignore */ }
ReactDOM.createRoot(document.getElementById('root')).render(el(WErrorBoundary, { scope: 'app' }, el(E2EBoomProbe, null), el(Workbench, null)))
})()