Files
image-workbench-desktop/src/ui-settings-tab-diag.js
T
qiqi 7b1164febb feat(plugin): 插件数据层 M2 —— ctx.data(原子写 + 串行队列 + 旧数据迁移)v3.25.42
- 新增 src/plugin-data.js:read/write/patch/remove/size;桌面落 plugin-data/<id>.json(tmp+rename),
  同一插件读写串行排队,maxBytes 上限(默认 2MiB/最高 16MiB)超限抛错且不破坏已有数据
- storage-file 增加 pluginData 命名空间(read/write/remove/list)
- stripLegacy:宿主 init 前同步暂存 iwb_plugins[id].data,插件首次 read 时落盘并清暂存
- 备份携带 items.pluginData 并支持恢复;存储体检显示「插件数据 N 个 / X KB」
- 非桌面环境走 IWBStorageLocal 门面 → 内存兜底(仅测试)
- 新增 tests/plugin-data-test.js(串行/上限/迁移/备份)
2026-11-20 09:27:53 +08:00

159 lines
15 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.
/* 设置 · 诊断页(自 src/ui-settings-modal.js 抽出,2026-11-10)
*
* 抽取原因:SettingsModal 已 1144 行,其中诊断页 117 行、依赖 8 个 —— 是唯一
* "体积大且边界干净"的块。抽出的收益是给后续继续拆 tab 立一个样板。
*
* 约定:不持有状态,全部依赖经 ctx 显式传入(宿主负责传入稳定引用)。
* ctx.CrashLog / ctx.APP_VERSION / ctx._lstore —— 模块级设施
* ctx.setDiagRev / ctx.setMsg —— 触发重渲染 / 提示
* ctx.comp / ctx.reclaimOrphans / ctx.runStorageAudit —— 存储体检与回收
* ctx.storageAudit / ctx.storageAuditBusy —— 体检结果与忙碌态
* ctx.props —— SettingsModal 的 props(diagStats/diagText/onExportDiag)
*/
// 确认统一走页内确认(桌面端),网页端保持原生 confirm
function askConfirm (text, opts) {
const C = (typeof window !== 'undefined') ? window.IWBUIConfirm : null
if (C && typeof C.askOrNative === 'function') return C.askOrNative(text, opts)
return Promise.resolve(window.confirm(String(text)))
}
;(function (global) {
'use strict'
const React = global.React || {}
const el = (type, prop, ...children) => React.createElement(type, prop, ...children)
function renderDiagTab (ctx) {
const { CrashLog, APP_VERSION, _lstore, setDiagRev, setMsg, comp, reclaimOrphans, runStorageAudit, storageAudit, storageAuditBusy, props } = ctx
const reload = () => { if (CrashLog && CrashLog.load) CrashLog.load(); setDiagRev((v) => v + 1) }
const entries = (CrashLog && CrashLog.entries) ? CrashLog.entries().slice().reverse() : []
const samples = (CrashLog && CrashLog.samples) ? CrashLog.samples().slice().reverse() : []
const crumbs = (CrashLog && CrashLog.breadcrumbs) ? CrashLog.breadcrumbs().slice().reverse() : []
const mem = (CrashLog && CrashLog.memoryNow) ? CrashLog.memoryNow() : null
// 注意:SettingsModal 是独立组件,refs / setNotice 都属于 Workbench 作用域 → 一律走 props
const stat = (typeof props.diagStats === 'function') ? props.diagStats() : { nodes: 0, boards: 0, images: 0, base64Bytes: 0 }
const extras = (typeof props.diagExtras === 'function') ? (props.diagExtras() || {}) : {}
const fmtKB = (n) => (Number(n) || 0) >= 1024 ? (Math.round((Number(n) / 1024) * 10) / 10) + 'MB' : Math.round(Number(n) || 0) + 'KB'
// v3.24.67:旧实现在 writeText() 之后**不 await 也不 catch**,下一行无条件提示「已复制」——
// 权限被拒 / 非 https / 浏览器不给写剪贴板时是**假成功**,用户以为拿到了其实没有。
const copyDiag = async () => {
let text = ''
try {
text = (typeof props.diagText === 'function') ? props.diagText() : JSON.stringify(CrashLog ? CrashLog.report({ version: APP_VERSION }) : {}, null, 2)
} catch (e) { setMsg({ type: 'err', text: '生成诊断信息失败:' + String((e && e.message) || e) }); return }
if (!(navigator.clipboard && navigator.clipboard.writeText)) { setMsg({ type: 'err', text: '当前环境不支持复制,请用「导出 JSON」' }); return }
try {
await navigator.clipboard.writeText(text)
setMsg({ type: 'ok', text: '诊断信息已复制到剪贴板' })
} catch (e) {
setMsg({ type: 'err', text: '复制失败:' + String((e && e.message) || e) + ';请改用「导出 JSON」' })
}
}
// ── 孤儿画板找回(v3.87.8)──
// 症状:崩溃/异常返回后某块画板"从列表里消失"(其它画板还在)。索引条目可能丢了,
// 但**画板本体键 iwb_ws_<id> 往往还在**(保存时分开写)→ 扫出来即可一键补回,只增不减。
let orphanRows = []
try {
const st = _lstore()
const idx = (st ? st.get('iwb_web_workspaces', null) : null) || { workspaces: [] }
const known = new Set(((idx && idx.workspaces) || []).map((w) => String((w && w.id) || '')))
for (const k of (st ? st.keys() : [])) {
if (!k || k.indexOf('iwb_ws_') !== 0 || k.indexOf('iwb_ws_bak_') === 0) continue
const id = k.slice('iwb_ws_'.length)
if (!id || id === 'active' || id === 'expanded' || known.has(id)) continue
let board = null
try { board = st ? st.get(k, null) : null } catch (e) { board = null }
if (!board || !Array.isArray(board.nodes)) continue
orphanRows.push({ id, key: k, name: String(board.name || id), nodes: board.nodes.length })
}
} catch (e) { orphanRows = [] }
const restoreOrphan = async (row) => {
try {
if (!(await askConfirm('把「' + row.name + '」(' + row.nodes + ' 个节点)补回画布列表?恢复后会重新加载页面。', { title: '找回画布', okText: '补回' }))) return
const st = _lstore()
const idx = (st ? st.get('iwb_web_workspaces', null) : null) || { workspaces: [], activeId: '', rev: 0 }
const board = st ? st.get(row.key, null) : null
if (!board) { setMsg({ type: 'err', text: '该画板数据不可读' }); return }
board.id = row.id
if (!board.name) board.name = row.name
idx.workspaces = ((idx.workspaces || []).filter((w) => w && String(w.id) !== row.id)).concat([board])
if (!idx.activeId) idx.activeId = row.id
idx.rev = (Number(idx.rev) || 0) + 1
if (st) st.set('iwb_web_workspaces', idx)
if (CrashLog && CrashLog.breadcrumb) CrashLog.breadcrumb('board-restore-orphan', row.id + ' nodes=' + row.nodes)
location.reload()
} catch (e) { setMsg({ type: 'err', text: '找回失败:' + String((e && e.message) || e) }) }
}
return el('div', { className: 'iwb-section' },
el('div', { className: 'iwb-section-title' }, '运行诊断'),
el('div', { className: 'iwb-hint' }, '用于排查「崩溃 / 内存占用高 / 界面出错」。记录只存在本机(localStorage),不含 Key、提示词和图片本体;进程/标签页意外结束后重开仍能看到崩溃前的记录。'),
el('div', { className: 'iwb-row' },
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => { setDiagRev((v) => v + 1) } }, '刷新'),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '复制完整诊断 JSON(含崩溃记录与内存采样)', onClick: copyDiag }, '复制诊断 JSON'),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '导出完整诊断 JSON(下载文件)', onClick: () => { if (typeof props.onExportDiag === 'function') props.onExportDiag(); else setMsg({ type: 'err', text: '当前环境不支持诊断导出' }) } }, '导出 JSON'),
el('button', { className: 'iwb-btn iwb-btn-sm iwb-btn-danger', title: '清空本机的崩溃记录、内存采样与操作面包屑', onClick: async () => { if (await askConfirm('清空本机诊断记录?', { title: '清空诊断记录', okText: '清空' })) { if (CrashLog && CrashLog.clear) CrashLog.clear(); reload() } } }, '清空记录'),
),
el('div', { className: 'iwb-row' },
el('span', { className: 'iwb-diag-kv' }, '版本 ' + APP_VERSION),
el('span', { className: 'iwb-diag-kv' }, '内存 ' + (mem ? (mem.usedMB + 'MB / ' + mem.limitMB + 'MB(' + Math.round(mem.ratio * 100) + '%)') : '当前环境不提供')),
el('span', { className: 'iwb-diag-kv' }, '节点 ' + stat.nodes + ' · 画板 ' + stat.boards + ' · DOM 图片 ' + stat.images),
el('span', { className: 'iwb-diag-kv' }, '内存中图片约 ' + fmtKB(stat.base64Bytes / 1024)),
// 持久化存储 + 被忽略错误(2026-11-07):前者决定"会不会被浏览器清掉",后者决定"改了没生效"能不能查
el('span', { className: 'iwb-diag-kv', title: '持久化存储:授权后系统不会因空间紧张自行清除本应用数据(仍可被手动清除)' },
'存储持久化 ' + ((extras.persist && extras.persist.status) === 'granted' ? '已授权 ✅'
: (extras.persist && extras.persist.status) === 'denied' ? '未授予(可能被清)'
: (extras.persist && extras.persist.status) === 'unsupported' ? '当前环境不支持' : '检测中…')),
(extras.persist && extras.persist.quota) ? el('span', { className: 'iwb-diag-kv', title: '当前环境给本应用的存储配额(navigator.storage.estimate);已用接近总量时保存会开始失败' },
'存储配额 ' + Math.round((extras.persist.usage || 0) / 1048576) + '/' + Math.round(extras.persist.quota / 1048576) + 'MB') : null,
extras.swallowed ? el('span', { className: 'iwb-diag-kv', title: '关键路径(保存/图片写入/数据迁移)被忽略的错误次数;明细见下方操作面包屑 swallow:*' },
'已忽略错误 ' + (extras.swallowed.swallowedErrorCount || 0) + ' 次'
+ ((extras.swallowed.saveFailureCount || extras.swallowed.imageWriteFailureCount || extras.swallowed.migrationFailureCount)
? '(保存 ' + (extras.swallowed.saveFailureCount || 0) + ' / 图片 ' + (extras.swallowed.imageWriteFailureCount || 0) + ' / 迁移 ' + (extras.swallowed.migrationFailureCount || 0) + ')'
: '')) : null,
),
el('div', { className: 'iwb-section-sub' }, '存储体检(只读)'),
el('div', { className: 'iwb-hint' }, '检查 IndexedDB 图片字节与图库索引是否一致(悬空索引 / 孤儿字节)。「安全回收」只删未被任何画板 / 剪贴板 / 收藏组 / 历史 / 图库引用的字节,绝不删活引用。'),
el('div', { className: 'iwb-row' },
el('button', { className: 'iwb-btn iwb-btn-sm', disabled: !!storageAuditBusy, onClick: runStorageAudit }, storageAuditBusy ? '处理中…' : '存储体检'),
el('button', { className: 'iwb-btn iwb-btn-sm', disabled: !!storageAuditBusy, onClick: reclaimOrphans }, '安全回收孤儿'),
),
storageAudit ? el('div', { className: 'iwb-diag-list' },
el('div', { className: 'iwb-diag-item' },
el('div', { className: 'iwb-diag-head' }, 'IDB 图片键 ' + storageAudit.total + '(blob ' + storageAudit.counts.blob + ' / ref ' + storageAudit.counts.ref + ' / out ' + storageAudit.counts.out + ' / orig ' + storageAudit.counts.orig + ' / 其它 ' + storageAudit.counts.other + ')'),
el('div', { className: 'iwb-diag-extra' }, '图库索引 ' + storageAudit.outputsIndexSize + ' 条 · 悬空索引 ' + storageAudit.danglingOutputIndex + ' · 孤儿输出字节 ' + storageAudit.orphanOutputBytes),
),
storageAudit.pluginDataCount !== undefined ? el('div', { className: 'iwb-diag-item' },
el('div', { className: 'iwb-diag-head' }, '插件数据 ' + storageAudit.pluginDataCount + ' 个 · ' + Math.round((storageAudit.pluginDataBytes || 0) / 1024) + ' KB'),
el('div', { className: 'iwb-diag-extra' }, '存放于资料目录 plugin-data/(与插件代码分离,卸载插件默认保留)'),
) : null,
) : el('div', { className: 'iwb-hint' }, '点「存储体检」查看一致性;发现悬空 / 孤儿再决定是否回收。'),
el('div', { className: 'iwb-section-sub' }, '画板找回(索引里没有、但本体还在 · ' + orphanRows.length + ' 个)'),
orphanRows.length ? el('div', { className: 'iwb-diag-list' }, orphanRows.map((row, i) => el('div', { key: 'or' + i, className: 'iwb-diag-item' },
el('div', { className: 'iwb-diag-head' }, row.name + ' · ' + row.nodes + ' 个节点 · ' + row.id),
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => restoreOrphan(row) }, '找回此画板'),
))) : el('div', { className: 'iwb-hint' }, '没有发现丢失的画板 ✅'),
el('div', { className: 'iwb-section-sub' }, '崩溃 / 错误记录(最近 ' + entries.length + ' 条 · 上限 ' + ((CrashLog && CrashLog.limits && CrashLog.limits.entries) || 20) + ')'),
entries.length ? el('div', { className: 'iwb-diag-list' }, entries.map((e, i) => el('div', { key: 'e' + i, className: 'iwb-diag-item' },
el('div', { className: 'iwb-diag-head' }, (e.time || '').replace('T', ' ').slice(0, 19) + ' · ' + (e.kind || '') + ' · ' + (e.scope || '')),
el('div', { className: 'iwb-diag-msg' }, (e.message || '') + (e.nodeId ? ('(节点 ' + e.nodeId + ')') : '') + (e.memory ? (' · 堆 ' + e.memory.usedMB + 'MB/' + e.memory.limitMB + 'MB') : '')),
e.extra && (e.extra.componentStack || e.extra.source || e.extra.base64MB !== undefined) ? el('div', { className: 'iwb-diag-extra' }, [e.extra.source, e.extra.line ? ('L' + e.extra.line) : '', e.extra.nodes !== undefined ? ('节点 ' + e.extra.nodes) : '', e.extra.images !== undefined ? ('图片 ' + e.extra.images) : '', e.extra.base64MB !== undefined ? ('内存图片 ' + e.extra.base64MB + 'MB') : ''].filter(Boolean).join(' · ') || String(e.extra.componentStack || '').slice(0, 200)) : null,
))) : el('div', { className: 'iwb-hint' }, '暂无记录 ✅'),
el('div', { className: 'iwb-section-sub' }, '内存 / 规模采样(每 15 秒一条 · 最近 ' + samples.length + ' 条)'),
samples.length ? el('div', { className: 'iwb-diag-list' }, samples.slice(0, 20).map((sm, i) => el('div', { key: 's' + i, className: 'iwb-diag-item' },
el('div', { className: 'iwb-diag-head' }, (sm.time || '').replace('T', ' ').slice(11, 19) + ' · 堆 ' + ((sm.memory && sm.memory.usedMB) || 0) + 'MB/' + ((sm.memory && sm.memory.limitMB) || 0) + 'MB'),
el('div', { className: 'iwb-diag-extra' }, '节点 ' + sm.nodes + ' · 画板 ' + sm.boards + ' · DOM 图片 ' + sm.images + ' · 内存图片 ' + (sm.base64MB || 0) + 'MB · localStorage ' + (sm.localKB || 0) + 'KB'
+ (sm.history ? (' · 历史 ' + sm.history.depth + '份/' + (sm.history.bytesMB || 0) + 'MB(扫 ' + (sm.history.swept || 0) + ')') : '')
+ (sm.maps ? (' · genRuns ' + sm.maps.genRuns + '·缩略图 ' + sm.maps.thumbs + '/' + sm.maps.displayThumbs + '·装载画板 ' + sm.maps.loadedBoards) : '')
+ (sm.comp && sm.comp.topBoards ? (' · 最大板 ' + sm.comp.topBoards.join(' ') + ' · 含水板 ' + sm.comp.hydrated) : '')
+ (sm.comp ? (' · 构成 画板 ' + sm.comp.boardsMB + 'MB/历史 ' + (sm.comp.historyMB || 0) + 'MB/任务 ' + (sm.comp.tasksMB || 0) + 'MB/运行 ' + (sm.comp.genRunsMB || 0) + 'MB/缩略 ' + ((sm.comp.thumbsMB || 0) + (sm.comp.displayThumbsMB || 0)) + 'MB/剪贴 ' + (sm.comp.clipboardMB || 0) + 'MB') : '')),
))) : el('div', { className: 'iwb-hint' }, '暂无采样(每 15 秒采一次,稍等即可)'),
el('div', { className: 'iwb-section-sub' }, '操作面包屑(崩溃前最后做了什么)'),
crumbs.length ? el('div', { className: 'iwb-diag-list' }, crumbs.map((b, i) => el('div', { key: 'b' + i, className: 'iwb-diag-item' },
el('div', { className: 'iwb-diag-head' }, (b.time || '').replace('T', ' ').slice(11, 19) + ' · ' + (b.kind || '')),
el('div', { className: 'iwb-diag-extra' }, b.detail || ''),
))) : el('div', { className: 'iwb-hint' }, '暂无操作记录'),
)
}
global.IWBUISettingsTabDiag = { renderDiagTab }
})(typeof window !== 'undefined' ? window : globalThis)