diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 65da0f5..613fed9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -105,8 +105,8 @@ IWB_WRITE_BOUNDARY_SNAPSHOT=1 node tests/architecture-boundary-guard-test.js # | 守卫 | 位置 | 现在的上限 | |---|---|---| -| `app.js` 总行数 | `tests/source-text-ratchet-test.js` `MAX_APP_JS_LINES` | **9,146**(另守「占总源码 ≤ 40%」,见 `MAX_APP_JS_SHARE`) | -| `Workbench()` 行数 | 同上 `MAX_WORKBENCH_LINES` | **2,533** | +| `app.js` 总行数 | `tests/source-text-ratchet-test.js` `MAX_APP_JS_LINES` | **9,309**(另守「占总源码 ≤ 40%」,见 `MAX_APP_JS_SHARE`) | +| `Workbench()` 行数 | 同上 `MAX_WORKBENCH_LINES` | **2,652** | | 单组件行数(不含 Workbench)| 同上 `MAX_APP_COMPONENT_LINES` | **423** | 三条都是**只减不增**。确需在 app.js 增长时,必须**同步上调上限并在 commit 里写理由**(等于显式记账,不会悄悄发生)。 diff --git a/app.js b/app.js index a564aba..ec9b494 100644 --- a/app.js +++ b/app.js @@ -237,6 +237,7 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct // 与 wPluginNodeVariants(菜单/运行用,仅"已激活"变体)分开,故不影响启停语义。 const wPluginVariantMeta = new Map() const wPluginPanels = [] + const wPluginPages = [] // 插件整页(pages 能力):{id,title,icon,mount,pluginId} const wPluginGenHooks = [] const wPluginProviders = [] let wPluginCanvasBridge = null @@ -417,7 +418,7 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct // 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, newBadgeSec: 120, appearance: W_DEF_APPEARANCE } + const W_DEF_CANVAS = { generationConcurrency: 4, taskStallEndMs: 300000, autoSaveImages: true, backupOriginals: true, lodLowZoom: true, newBadgeSec: 120, taskQueueMax: 500, appearance: W_DEF_APPEARANCE } // 任务条「结束」按钮出现的阈值:默认 5 分钟。判据是「该任务距上一次进展的时长」, // 而不是任务总时长 —— 多个变体(如 3 张)正常跑 6 分钟也不会误报"卡住"。 const TASK_STALL_END_MIN = 60000 @@ -3701,6 +3702,7 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct settings: '', help: '', download: '', + queue: '', upload: '', save: '', github: '', @@ -6117,6 +6119,22 @@ const tbCenterSeed = (type, refs) => { // 快捷键弹窗内容(分区罗列 + 折叠说明) const HotkeyHelp = (typeof window !== 'undefined' && window.IWBUIHotkeyHelp) ? window.IWBUIHotkeyHelp.HotkeyHelp : null // 插件整页(复用设置里的插件管理块;页面壳在 src/ui-plugin-page.js) + // 插件整页容器(pages 能力):把 host DOM 交给插件 mount,离开/禁用时清理。 + const PluginPageHost = (props) => { + const page = props && props.page + const hostRef = React.useRef(null) + React.useEffect(() => { + const host = hostRef.current + if (!host || !page || typeof page.mount !== 'function') return undefined + let cleanup = null + try { cleanup = page.mount(host) } catch (e) { try { host.textContent = '插件页面加载失败:' + String((e && e.message) || e) } catch (e2) { /* ignore */ } } + return () => { try { if (typeof cleanup === 'function') cleanup(); else host.innerHTML = '' } catch (e) { /* ignore */ } } + }, [page]) + return el('div', { className: 'iwb-plugin-page iwb-plugin-page-custom' }, + el('div', { className: 'iwb-plugin-page-head' }, el('span', { className: 'iwb-plugin-page-title' }, (page && page.title) || '任务队列')), + el('div', { className: 'iwb-plugin-page-body', ref: hostRef }), + ) + } const PluginsPage = (typeof window !== 'undefined') ? window.IWBUIPluginPage : null @@ -6377,7 +6395,8 @@ const tbCenterSeed = (type, refs) => { // 结果落地队列(2026-12-02):出图后后台把远程图下到本地,节点/图库不再直连 CDN。 React.useEffect(() => { if (!window.IWBImageIngest || !window.IWBImageIngestStore) return undefined - const store = window.IWBImageIngestStore.createStore({ get: (k) => lsGet(k, null), set: (k, v) => lsSet(k, v) }) + const store = window.IWBImageIngestStore.createStore({ get: (k) => lsGet(k, null), set: (k, v) => lsSet(k, v), max: () => { try { return Number(wRawCfg().canvas.taskQueueMax) || 500 } catch (e) { return 500 } } }) + window.__iwbIngestStore = store const view = window.IWBImageIngestStore.createView() window.IWBImageIngestView = view const ing = window.IWBImageIngest.create({ @@ -6388,6 +6407,7 @@ const tbCenterSeed = (type, refs) => { removeEntry: (id) => store.remove(id), onEvent: (kind, e) => { const patch = Object.assign({}, e) + try { if (window.IWBPluginQueue) window.IWBPluginQueue.emit(kind) } catch (eQ) { /* ignore */ } if (e && e.ref) { try { patch.localUrl = wResolveImg(e.ref) || '' } catch (err) { patch.localUrl = '' } // 首次 ready 时 objectURL 可能还没建好:异步解析完成后再补一次视图,确保节点真的切到本地 @@ -6435,7 +6455,7 @@ const tbCenterSeed = (type, refs) => { // 用户切回来通常就是「图该出来了」的时刻,成本与操作频率同阶,闲置时零开销。 const onFocusReconcile = () => { try { wIngestReconcile() } catch (eR2) { /* ignore */ } } try { window.addEventListener('focus', onFocusReconcile) } catch (eR3) { /* ignore */ } - return () => { window.__iwbIngest = null; try { window.removeEventListener('focus', onFocusReconcile) } catch (eR4) { /* ignore */ } } + return () => { window.__iwbIngest = null; window.__iwbIngestStore = null; try { window.removeEventListener('focus', onFocusReconcile) } catch (eR4) { /* ignore */ } } }, []) const [layoutLocked, setLayoutLocked] = useState(false) const [wsMoreOpen, setWsMoreOpen] = useState(false) // 顶部 ⋯ 三点菜单(展开态) @@ -6563,6 +6583,13 @@ const tbCenterSeed = (type, refs) => { 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=无限画布;刷新时恢复上次所在的视图 + const [pluginPage, setPluginPage] = useState(null) // 插件整页:{pluginId,pageId};仅 pages 能力注册的页面 + // 插件被禁用/页面被移除时,若正停在该页,回到画布(避免空白页) + React.useEffect(() => { + if (!pluginPage) return + const ok = wPluginPages.some((p) => p.pluginId === pluginPage.pluginId && p.id === pluginPage.pageId) + if (!ok) { setPluginPage(null); setShellView('canvas') } + }, [pluginRev, pluginPage]) // 记住当前视图;刷新后在画布编辑器则恢复到画布编辑器(画布库则仍回画布库) useEffect(() => { try { lsRawSet('iwb_shell_view', shellView) } catch (e) { /* ignore */ } }, [shellView]) const [homeSelectedWs, setHomeSelectedWs] = useState([]) @@ -8245,6 +8272,109 @@ const tbCenterSeed = (type, refs) => { 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) })) }, }) + // 任务队列插件(queue):账本/下载/落地/定位/上限全部在宿主,插件只做视图。 + if (window.IWBPluginQueue) { + const qList = () => { try { return window.__iwbIngest ? window.__iwbIngest.list() : [] } catch (e) { return [] } } + const qEntry = (id) => qList().find((x) => x.id === id) || null + const qView = (url) => { try { return (window.IWBImageIngestView && typeof window.IWBImageIngestView.get === 'function') ? window.IWBImageIngestView.get(url) : null } catch (e) { return null } } + const qMapStatus = (s) => s === 'ready' ? 'ok' : (s === 'failed' ? 'fail' : ((s === 'queued' || s === 'downloading') ? 'down' : 'only')) + window.IWBPluginQueue.setImpl({ + list: (o) => { + const opt = o || {} + const want = String(opt.status || '') + const limit = Math.max(1, Math.min(5000, Number(opt.limit) || 500)) + const q = String(opt.query || '').toLowerCase() + let items = qList().map((e) => { + const v = qView(e.url) + const meta = e.meta || {} + return { + id: e.id, url: e.url, status: e.status, kind: qMapStatus(e.status), + progress: Number(e.progress) || 0, bytes: Number(e.bytes) || 0, + w: Number(e.w) || 0, h: Number(e.h) || 0, error: String(e.lastError || ''), + retries: Number(e.retries) || 0, createdAt: Number(e.createdAt) || 0, updatedAt: Number(e.updatedAt) || 0, + meta, + thumbUrl: (v && v.localUrl) ? v.localUrl : '', + } + }) + if (want && want !== 'all') items = items.filter((x) => x.kind === want) + if (q) items = items.filter((x) => (String(x.meta.prompt || '') + ' ' + String(x.meta.boardName || '') + ' ' + String(x.url || '')).toLowerCase().indexOf(q) >= 0) + items.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0)) + return { items: items.slice(0, limit), total: items.length } + }, + retry: (id) => { try { return window.__iwbIngest ? window.__iwbIngest.retry(id) : null } catch (e) { return null } }, + land: async (id) => { + const e = qEntry(id) + if (!e) return { ok: false, error: 'record-missing' } + if (!/^https?:/i.test(String(e.url || ''))) return { ok: false, error: 'no-url' } + const idx = lsGet(OUT_KEY, []) || [] + const row = idx.find((f) => f && String(f.url) === String(e.url)) + if (row && (row.orig === 'ok' || row.origIdb)) return { ok: true, already: true } + if (!row) { + try { await wAddOutputs([{ ok: true, url: e.url, width: e.w, height: e.h, label: String((e.meta && e.meta.prompt) || '') }], {}) } catch (e1) { /* ignore */ } + } + try { window.__iwbIngest.enqueue({ url: e.url, source: 'task-queue', w: e.w, h: e.h, meta: e.meta }) } catch (e2) { /* ignore */ } + const hit = (lsGet(OUT_KEY, []) || []).find((f) => f && String(f.url) === String(e.url)) + const v = qView(e.url) + if (hit && v && v.ref) { try { wIngestOrigFromRef(hit.name, e.url, v.ref) } catch (e3) { /* ignore */ } } + try { wIngestLog('queue-land url=' + String(e.url).slice(0, 60)) } catch (e4) { /* ignore */ } + return { ok: true } + }, + preview: (id) => { + const all = qList().filter((x) => x && x.url) + const idx = all.findIndex((x) => x.id === id) + if (idx < 0) return { ok: false, error: 'record-missing' } + const list = all.map((x) => { + const v = qView(x.url) + return { url: (v && v.localUrl) ? v.localUrl : x.url, w: Number(x.w) || 0, h: Number(x.h) || 0, name: String((x.meta && x.meta.prompt) || '') } + }) + setPreview({ list, idx }) + return { ok: true } + }, + copyLink: (id) => { + const e = qEntry(id) + if (!e || !e.url) return { ok: false, error: 'record-missing' } + const C = (typeof window !== 'undefined') ? window.IWBClipboardCopy : null + if (!C || typeof C.copyText !== 'function') return { ok: false, error: 'clipboard-unavailable' } + return C.copyText(String(e.url)).then((ok) => ok ? { ok: true } : { ok: false, error: 'copy-failed' }) + }, + locate: (id) => { + const e = qEntry(id) + const meta = (e && e.meta) || {} + const bid = String(meta.boardId || '') + const nid = String(meta.nodeId || '') + if (!bid || !nid) return Promise.resolve({ ok: false, error: 'missing-meta' }) + const pick = (n) => new Promise((resolve) => { + const hit = (refs.nodes || []).find((x) => x.id === nid) + if (hit) { try { setSel([nid]) } catch (e1) { /* ignore */ } ; resolve({ ok: true }); return } + if (n < 10) { setTimeout(() => { pick(n + 1).then(resolve) }, 200); return } + resolve({ ok: false, error: 'node-missing' }) + }) + const target = (refs.workspaces || []).find((w) => w.id === bid) + if (!target) return Promise.resolve({ ok: false, error: 'board-missing' }) + if (bid !== activeWsId) { try { switchWs(bid) } catch (e2) { /* ignore */ } } + return pick(0) + }, + stats: () => { + const out = { total: 0, ok: 0, down: 0, fail: 0, only: 0 } + for (const e of qList()) { out.total++; const k = qMapStatus(e.status); if (out[k] !== undefined) out[k]++ } + return out + }, + clear: () => { try { return window.__iwbIngest ? window.__iwbIngest.clearFinished() : 0 } catch (e) { return 0 } }, + getLimit: () => { try { return Math.max(100, Math.min(5000, Number(wRawCfg().canvas.taskQueueMax) || 500)) } catch (e) { return 500 } }, + setLimit: (n) => { + const v = Math.max(100, Math.min(5000, Math.round(Number(n) || 500))) + try { + const stored = wRawStoredCfg() + const next = Object.assign({}, stored, { canvas: Object.assign({}, stored.canvas || {}, { taskQueueMax: v }) }) + LocalStore.set(StorageContract.localKeys.config, next) + if (window.__iwbIngestStore && typeof window.__iwbIngestStore.trim === 'function') window.__iwbIngestStore.trim() + else { const S = window.IWBImageIngestStore; if (S) S.createStore({ get: (k) => lsGet(k, null), set: (k, x) => lsSet(k, x), max: () => v }).trim() } + } catch (e) { /* ignore */ } + try { if (window.IWBPluginQueue) window.IWBPluginQueue.emit('limit') } catch (e2) { /* ignore */ } + return { ok: true, limit: v } + }, + }) + } // 节点组库插件(grouplib):数据仍由宿主持有,插件只拿读写/实例化能力 if (window.IWBPluginGroupLib) { window.IWBPluginGroupLib.setImpl({ @@ -8375,6 +8505,9 @@ const tbCenterSeed = (type, refs) => { I, logoIcon: 'brand', view: shellView === 'plugins' ? 'plugins' : (shellView === 'home' ? 'home' : 'canvas'), + pages: wPluginPages.slice(), + activePage: pluginPage ? (pluginPage.pluginId + ':' + pluginPage.pageId) : '', + onPage: (pid, id) => { setPluginPage({ pluginId: pid, pageId: id }); setShellView('page') }, skinIcon: theme === 'dark' ? 'sun' : 'moon', onHome: () => { setShellView('home'); try { goHome() } catch (e) { /* ignore */ } }, onCanvas: () => setShellView('canvas'), @@ -8390,6 +8523,10 @@ const tbCenterSeed = (type, refs) => { 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, + shellView === 'page' && pluginPage ? (() => { + const page = wPluginPages.find((p) => p.pluginId === pluginPage.pluginId && p.id === pluginPage.pageId) + return page ? el(PluginPageHost, { key: page.pluginId + ':' + page.id, page }) : null + })() : null, tabstripEl, // S12:顶部标签条(在顶栏上方) topbarEl, el('div', { @@ -8913,6 +9050,7 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) => log: () => { try { wLog.apply(null, arguments) } catch (e) { /* ignore */ } }, capabilities: { gallery: () => ((typeof window !== 'undefined' && window.IWBPluginGallery) ? window.IWBPluginGallery.api() : {}), + queue: () => ((typeof window !== 'undefined' && window.IWBPluginQueue) ? window.IWBPluginQueue.api() : {}), grouplib: () => ((typeof window !== 'undefined' && window.IWBPluginGroupLib) ? window.IWBPluginGroupLib.api() : {}), promptlib: () => ((typeof window !== 'undefined' && window.IWBPluginPromptLib) ? window.IWBPluginPromptLib.api() : {}), // 插件文件能力(v3.26.36):沙箱目录 plugin-data//files,供插件自持图片 @@ -8944,6 +9082,31 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) => dir: () => need().dir(ctx.id), } }, + pages: (ctx) => { + const owned = [] + const changed = () => { try { if (PluginHost && typeof PluginHost.emit === 'function') PluginHost.emit('plugin-pages-changed') } catch (e) { /* ignore */ } } + return { + registerPage: (page) => { + if (!page || !page.id || !page.title || typeof page.mount !== 'function') return false + for (let i = wPluginPages.length - 1; i >= 0; i--) { + const e = wPluginPages[i] + if (e && e.pluginId === ctx.id && e.id === String(page.id)) wPluginPages.splice(i, 1) + } + const entry = { id: String(page.id), title: String(page.title), icon: pluginIconOf(ctx.id) || page.icon || 'queue', mount: page.mount, pluginId: ctx.id } + wPluginPages.push(entry) + owned.push(entry) + changed() + return true + }, + dispose: () => { + for (const entry of owned.splice(0)) { + const i = wPluginPages.indexOf(entry) + if (i >= 0) wPluginPages.splice(i, 1) + } + changed() + }, + } + }, commands: (ctx) => { const owned = [] return { diff --git a/docs/standards/architecture-current-state.md b/docs/standards/architecture-current-state.md index acca5c4..6676ffa 100644 --- a/docs/standards/architecture-current-state.md +++ b/docs/standards/architecture-current-state.md @@ -22,7 +22,7 @@ - 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob__`** (A) `app.js:2143`;`{__cache}`(Cache Storage)为兜底;\`ref_\`(`app.js` 内定义的 `IDB_REF_PREFIX = 'ref_'`)为 legacy 形态 (A)。 - 大图判定:`isBigDataUrl` = `data:` 且 `length > 3000` (A) `app.js:2018`;**画布保存保留阈值** `< 16384` 才原样保留 (A) `app.js:2182`。**两处阈值并存,含义不同**。 - 单测是**源码契约测试**:`tests/` 目录共 **493** 处源码文本钉点(`source.includes` / `source.indexOf` / `/re/.test(source)`),分布在 **20** 个文件(其中 `iwb-v32-web-test.js` 一个就占 **407**)→ **结构性重构会先打红测试**。**该数字已由 `tests/source-text-ratchet-test.js` 的「只减不增」棘轮守门**(2026-10-20 起守卫范围从 1 个文件扩到全目录:新增任何一处源码文本钉点都会打红)。**2026-11-12 复算**(`npm run audit:pins`,v3.24.76):二分 STRUCT **417** / NAME **76**;形态 **POS 403 / NEG 87 / COUNT 3**;难度 **易 62 / 中 316 / 难 115**。钉点减法第一批(v3.24.72)把 **537 → 505**:8 条探针钉点改为「门禁内 spec 是否真的读该计数器」、5 条改为运行时断言(生产态 `window` 上无探针)、10 条改为 DOM 断言(质量档位禁用 / 传输页无三模式按钮 / 模型项 title)、4 条改为运行时对象断言(健康检查两域、策略对象冻结)、其余 9 条有同文件 DOM 等价断言或仅剩 NEG。第二批(v3.24.76)把 **505 → 493**:94-5~7 三条「多标签释放语义」(10 处正则)换成 `tests/iwb-tabs-release.spec.js` 的 3 条真 e2e,剩 1 条「消费方契约」(断言该 spec 在门禁内且 spec 源码真的读两个探针);另 2 条 `wPurgeIntent.add` 钉点改为读 `src/workspace-purge.js`。**这一批一换就查出 3 个真缺陷**(objectURL 从未释放 / 彻底删除留孤儿标签 · session / 刷新后误回收打开标签的图)—— 见 CHANGELOG v3.24.76。 -- `app.js` = 单 IIFE **9,146 行**(**双层预算**:绝对上限 9,146 / 占总源码 ≤ 40%,现 **26.0%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,533 行**(上限 **2,533**,余量 0;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **127** 个模块 / 26,082 行,`sourceModules` 127 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 +- `app.js` = 单 IIFE **9,309 行**(**双层预算**:绝对上限 9,309 / 占总源码 ≤ 40%,现 **26.2%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,652 行**(上限 **2,652**,余量 0;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **128** 个模块 / 26,184 行,`sourceModules` 128 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。 - 门禁:`npm run verify` = `verify:ci`(`build` → `node --check app.js` → `node --check dist/app.js` → `check-dist.js` → `lint`(ESLint 正确性规则,`src/` + `app.js`,P4-16a)→ `test:unit` → `test` → `test:facts`)+ `test:e2e` (A) `package.json`。 ## 1.5 内存基线(2026-11-30,v3.26.115,Windows / WebView2 实测) @@ -192,7 +192,7 @@ - 同一张图被 3 个节点引用、hydrate 成 3 个不同 objectURL 时,preview/display 缓存各自 miss → 重复解码(与 F2 相邻)。 - **F10|`refs.genScheduler` 是桩** (A) → 未接线,暂无运行时影响(P3)。 - **F11|已建但未接线的模块层(2026-10-17 接线审计;2026-10-18 复核更正)** (A) - - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**127 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 + - **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**128 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。 - **仅被测试引用(9 模块 + 2 导出)**:`canvas-domain`、`generation-retry`、`generation-service`、`runtime-recovery-runner`、`runtime-state-bridge`、`runtime-store`、`storage-reconcile`、`storage-result`、`workspace-service`;导出 `IWBStorageHealthFactory`、`IWBPluginHostFactory`。(`storage-result` 是**存储层共享结果类型**,被 6 个存储模块读取,**非死代码**;`runtime-store` 为状态模型 epic 地基。) - **app.js 零引用(1 模块 + 3 导出)**:模块 `generation-controller`;导出 `IWBRuntimeMetricsFactory`、`IWBStorageRuntimeFactory`、`IWBUIComponents`。`canvas-relations` 已随 `06cf211` 删除(本文档早前把它列为"唯一可删者",实际已删)。零引用证据 = `grep -rn "<名字>" .`(排除 `node_modules|dist|vendor|test-results`)**只命中其自身赋值行**。 - **半接线 / 未接线**:`IWBRuntimeStateBridge` **无 app.js 引用(仅测试)**;`IWBRuntimeRunContext` **已接线**(`runNode` 读取运行上下文);`IWBGenerationController` 是完整但**从未被调用**的工厂;`ModularWorkspaceStore`(`app.js` 内)是 `storage-workspace` 的**预留接线 seam**(当前无下游使用,保留);`window.IWBImageFolder` 自注册后读回(装载路径)。 @@ -208,7 +208,7 @@ | `storage-reconcile` | 存储对账(`createReconciler`/`check`) | 内联对账 | 存储层收口 | | `runtime-recovery-runner` | 执行恢复候选(`candidate`/`valid`/`run`) | 内联恢复 | 断点恢复 | | `canvas-domain` | 画布域模型(`commit`/`updateNode`/`deleteNodes`…) | `CanvasStore` 那一套 | Workbench 解耦(P2-9) | - - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**106** 项)与 `sourceModules` 顺序(**127** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 + - **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**107** 项)与 `sourceModules` 顺序(**128** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。 ## 12. 易踩的坑 @@ -279,7 +279,7 @@ **信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。 -**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**106** 项)与 `sourceModules` 顺序(**127** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。 +**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**107** 项)与 `sourceModules` 顺序(**128** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。 **关键陷阱**:`normalizeNodes`(现位于 `src/canvas-normalize.js`)会**静默丢弃**不在 `NODE_H` 里的节点类型 ⇒ 新增节点类型必须先登记 `NODE_H`,否则节点一刷新就消失(§13.27 规则三的同一失败模式)。 diff --git a/plugins/index.json b/plugins/index.json index d50fb8a..15028da 100644 --- a/plugins/index.json +++ b/plugins/index.json @@ -96,5 +96,16 @@ "file": "plugin-xianyi-cutout.f7898f6e0fe9.js", "version": "1.0.4", "integrity": "sha256-94mPbg/p+Pikvfkc59u+U4wPJ+45jc46JTlNptVZIB0=" + }, + { + "id": "taskqueue", + "dir": "taskqueue", + "main": "main.js", + "style": "styles.css", + "version": "1.0.0", + "files": { + "main.js": "d851da3572c34b89561277ecfc7635dc0e20d6d78c4427c60fe662e4f1b75531", + "styles.css": "eba20885ccd0120cae494a04ca8ff3e92b67766f6d7ed89270e6426a9553bbb6" + } } ] diff --git a/plugins/meta.json b/plugins/meta.json index 4a31a15..4d95a9e 100644 --- a/plugins/meta.json +++ b/plugins/meta.json @@ -140,5 +140,16 @@ "批量", "出图" ] + }, + "taskqueue": { + "name": "任务队列", + "desc": "全局生图记录:链接/状态/画布节点;下载落地图库、重试、复制链接、定位节点(数据由宿主保存)", + "author": "official", + "icon": "⏳", + "color": "#eef6f6", + "tags": [ + "工具", + "记录" + ] } } diff --git a/plugins/taskqueue/main.js b/plugins/taskqueue/main.js new file mode 100644 index 0000000..809ce0a --- /dev/null +++ b/plugins/taskqueue/main.js @@ -0,0 +1,214 @@ +// iwb-plugin: 任务队列 —— 左栏整页 +// +// 数据全部在宿主:账本(image-ingest-store)、下载/重试(image-ingest)、落地图库、定位节点、记录上限。 +// 插件只做视图与手动操作;禁用插件时宿主仍记账(上限内)。 +;(function (global) { + 'use strict' + if (!global.IWBPluginHost) return + + var PAGE_ID = 'taskqueue-page' + var TABS = [['all', '全部'], ['ok', '已完成'], ['down', '下载中'], ['fail', '失败'], ['only', '仅记录']] + var STATUS = { ok: '已完成', down: '下载中', fail: '失败', only: '仅记录' } + var LIMITS = [200, 500, 1000, 2000, 5000] + + function el (tag, attrs) { + var node = document.createElement(tag) + if (attrs) { + for (var k in attrs) { + if (!Object.prototype.hasOwnProperty.call(attrs, k)) continue + var v = attrs[k] + if (v === null || v === undefined) continue + if (k === 'class') node.className = v + else if (k === 'text') node.textContent = v + else if (k === 'style') node.setAttribute('style', v) + else node.setAttribute(k, v) + } + } + for (var i = 2; i < arguments.length; i++) append(node, arguments[i]) + return node + } + function append (node, v) { + if (v === null || v === undefined || v === false) return + if (Array.isArray(v)) { for (var i = 0; i < v.length; i++) append(node, v[i]); return } + node.appendChild(typeof v === 'string' ? document.createTextNode(v) : v) + } + function clear (node) { while (node.firstChild) node.removeChild(node.firstChild) } + function fmtTime (ms) { + var d = new Date(Number(ms) || 0) + if (!isFinite(d.getTime())) return '' + var p = function (n) { return (n < 10 ? '0' : '') + n } + return p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes()) + } + function fmtSize (w, h) { return (w > 0 && h > 0) ? (w + '×' + h) : '' } + + function mount (host, ctx) { + clear(host) + host.classList.add('iwb-plugin-node-body', 'iwb-tq') + var state = { filter: 'all', limit: 500, items: [], total: 0, loading: true, msg: '' } + var timer = 0 + var unsub = function () {} + + var head = el('div', { class: 'iwb-tq-head' }) + var sub = el('div', { class: 'iwb-tq-sub', text: '全局生图记录 · 数据由宿主保存,插件关闭也继续记录' }) + var tools = el('div', { class: 'iwb-tq-tools' }) + var limitSel = el('select', { class: 'iwb-input iwb-tq-limit', 'aria-label': '记录上限' }) + for (var li = 0; li < LIMITS.length; li++) limitSel.appendChild(el('option', { value: String(LIMITS[li]), text: String(LIMITS[li]) + ' 条' })) + var clearBtn = el('button', { class: 'iwb-btn iwb-btn-sm iwb-tq-ghost', text: '清空记录' }) + var refreshBtn = el('button', { class: 'iwb-btn iwb-btn-sm iwb-tq-ghost', text: '刷新' }) + tools.appendChild(el('span', { class: 'iwb-tq-tool-lbl', text: '记录上限' })) + tools.appendChild(limitSel) + tools.appendChild(clearBtn) + tools.appendChild(refreshBtn) + append(head, [sub, tools]) + + var tabs = el('div', { class: 'iwb-tq-tabs' }) + var tabEls = {} + for (var ti = 0; ti < TABS.length; ti++) { + var key = TABS[ti][0] + var t = el('button', { class: 'iwb-tq-tab' + (key === 'all' ? ' on' : ''), 'data-k': key }, + el('span', { text: TABS[ti][1] }), el('span', { class: 'iwb-tq-n', text: '0' })) + tabEls[key] = t + tabs.appendChild(t) + } + var list = el('div', { class: 'iwb-tq-list' }) + var foot = el('div', { class: 'iwb-tq-foot' }) + append(host, [head, tabs, list, foot]) + + function setMsg (m) { state.msg = m || ''; renderFoot() } + function renderFoot () { + clear(foot) + append(foot, [ + el('span', { text: '记录只保留链接与本机状态;上限内自动淘汰最旧记录,不影响 images/gallery 里的文件。' }), + el('span', { class: 'iwb-tq-hint', text: state.msg || '点击「下载」= 落地到图库(图库会自动刷新出现)' }), + ]) + } + + function setCounts (stats) { + var s = stats || {} + var map = { all: s.total || 0, ok: s.ok || 0, down: s.down || 0, fail: s.fail || 0, only: s.only || 0 } + for (var k in tabEls) { + var n = tabEls[k].querySelector('.iwb-tq-n') + if (n) n.textContent = String(map[k] || 0) + } + } + + function thumbOf (it) { + if (it.thumbUrl) return el('img', { class: 'iwb-tq-img', src: it.thumbUrl, alt: '', draggable: 'false' }) + return el('div', { class: 'iwb-tq-ph' }, + el('svg', { viewBox: '0 0 24 24', width: '20', height: '20', fill: 'none', stroke: 'currentColor', 'stroke-width': '1.6', 'aria-hidden': 'true' }, + el('path', { d: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4' }), + el('polyline', { points: '7 10 12 15 17 10' }), + el('line', { x1: '12', x2: '12', y1: '15', y2: '3' })), + el('span', { text: '仅记录' })) + } + + function badgeOf (it) { + var label = STATUS[it.kind] || '记录' + if (it.kind === 'down' && it.progress > 0) label = '下载中 ' + Math.round(it.progress * 100) + '%' + return el('span', { class: 'iwb-tq-badge ' + (it.kind || ''), text: label }) + } + + function btn (label, cls, onClick) { + var b = el('button', { class: 'iwb-btn iwb-btn-sm iwb-tq-btn' + (cls ? ' ' + cls : ''), text: label }) + b.addEventListener('click', function (e) { e.stopPropagation(); onClick(b) }) + return b + } + + function rowOf (it) { + var meta = it.meta || {} + var thumb = el('div', { class: 'iwb-tq-thumb', title: '点击预览' }, thumbOf(it)) + thumb.addEventListener('click', function () { ctx.queue.preview(it.id) }) + var line1 = el('div', { class: 'iwb-tq-line1' }, el('span', { class: 'iwb-tq-name', text: String(meta.prompt || '生成结果') }), badgeOf(it)) + var bits = [] + if (meta.boardName) bits.push(meta.boardName) + if (it.createdAt) bits.push(fmtTime(it.createdAt)) + var sz = fmtSize(it.w, it.h); if (sz) bits.push(sz) + if (meta.model) bits.push(meta.model) + var metaLine = el('div', { class: 'iwb-tq-meta', text: bits.join(' · ') }) + var main = el('div', { class: 'iwb-tq-main' }, line1, metaLine) + if (it.kind === 'fail' && it.error) main.appendChild(el('div', { class: 'iwb-tq-err', text: it.error + (it.retries ? (' · 已重试 ' + it.retries + ' 次') : '') })) + var acts = el('div', { class: 'iwb-tq-actions' }) + if (it.kind === 'ok') acts.appendChild(el('button', { class: 'iwb-btn iwb-btn-sm iwb-tq-btn', text: '已在图库', disabled: 'disabled' })) + else if (it.kind === 'down') acts.appendChild(el('button', { class: 'iwb-btn iwb-btn-sm iwb-tq-btn', text: '下载中…', disabled: 'disabled' })) + else if (it.kind === 'fail') acts.appendChild(btn('重试', 'iwb-tq-primary', function () { ctx.queue.retry(it.id); setMsg('已重新排队'); schedule() })) + else acts.appendChild(btn('下载', 'iwb-tq-primary', function (b) { b.disabled = true; ctx.queue.land(it.id).then(function (r) { b.disabled = false; setMsg(r && r.already ? '已在图库' : (r && r.ok ? '已加入落地队列,图库会自动刷新' : '下载失败')) ; schedule() }) })) + acts.appendChild(btn('复制原始链接', '', function () { ctx.queue.copyLink(it.id).then(function (r) { setMsg(r && r.ok ? '链接已复制' : '复制失败') }) })) + var loc = btn('定位', '', function (b) { b.disabled = true; ctx.queue.locate(it.id).then(function (r) { b.disabled = false; setMsg(r && r.ok ? '已定位到节点' : ({ 'board-missing': '画布已删除', 'node-missing': '节点已删除', 'missing-meta': '没有定位信息' }[r && r.error] || '定位失败')) }) }) + if (!(meta.boardId && meta.nodeId)) { loc.disabled = true; loc.title = '没有画布/节点信息' } + acts.appendChild(loc) + return el('div', { class: 'iwb-tq-row ' + (it.kind || '') }, thumb, main, acts) + } + + function renderList () { + clear(list) + if (!state.items.length) { + list.appendChild(el('div', { class: 'iwb-tq-empty', text: state.loading ? '加载中…' : '暂无记录 · 生成后会自动出现在这里' })) + return + } + for (var i = 0; i < state.items.length; i++) list.appendChild(rowOf(state.items[i])) + } + + function load () { + state.loading = true + renderList() + Promise.all([ + ctx.queue.list({ status: state.filter, limit: state.limit }), + ctx.queue.stats(), + ctx.queue.getLimit(), + ]).then(function (rs) { + var r = rs[0] || {} + state.items = Array.isArray(r.items) ? r.items : [] + state.total = Number(r.total) || state.items.length + state.loading = false + setCounts(rs[1]) + var lim = Number(rs[2]) || 500 + if (LIMITS.indexOf(lim) < 0) lim = 500 + limitSel.value = String(lim) + state.limit = lim + renderList() + }).catch(function () { + state.loading = false; state.items = []; renderList(); setMsg('加载失败') + }) + } + function schedule () { clearTimeout(timer); timer = setTimeout(load, 250) } + + for (var k in tabEls) (function (key) { + tabEls[key].addEventListener('click', function () { + state.filter = key + for (var kk in tabEls) tabEls[kk].classList.toggle('on', kk === key) + load() + }) + })(k) + limitSel.addEventListener('change', function () { + var n = Number(limitSel.value) || 500 + state.limit = n + ctx.queue.setLimit(n).then(function () { setMsg('记录上限已改为 ' + n) ; load() }) + }) + clearBtn.addEventListener('click', function () { + if (!global.confirm('清空已完成/失败的记录?不会删除图库文件。')) return + ctx.queue.clear().then(function () { setMsg('已清空记录'); load() }) + }) + refreshBtn.addEventListener('click', function () { load() }) + + renderFoot() + load() + try { unsub = ctx.queue.onChanged(schedule) || function () {} } catch (e) { unsub = function () {} } + return function () { clearTimeout(timer); try { unsub() } catch (e) { /* ignore */ } } + } + + global.IWBPluginHost.register({ + id: 'taskqueue', + name: '任务队列', + version: '1.0.0', + apiVersion: 1, + capabilities: ['pages', 'queue'], + }, function (ctx) { + ctx.ui.registerPage({ + id: PAGE_ID, + title: '任务队列', + icon: 'queue', + mount: function (host) { return mount(host, ctx) }, + }) + return {} + }) +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/plugins/taskqueue/manifest.json b/plugins/taskqueue/manifest.json new file mode 100644 index 0000000..6fead08 --- /dev/null +++ b/plugins/taskqueue/manifest.json @@ -0,0 +1,19 @@ +{ + "id": "taskqueue", + "name": "任务队列", + "version": "1.0.0", + "apiVersion": 1, + "main": "main.js", + "style": "styles.css", + "description": "全局生图记录:链接/状态/画布节点;下载落地图库、重试、复制链接、定位节点(数据由宿主保存)", + "author": "official", + "icon": "⏳", + "tags": [ + "工具", + "记录" + ], + "files": { + "main.js": "d851da3572c34b89561277ecfc7635dc0e20d6d78c4427c60fe662e4f1b75531", + "styles.css": "eba20885ccd0120cae494a04ca8ff3e92b67766f6d7ed89270e6426a9553bbb6" + } +} diff --git a/plugins/taskqueue/styles.css b/plugins/taskqueue/styles.css new file mode 100644 index 0000000..40b243e --- /dev/null +++ b/plugins/taskqueue/styles.css @@ -0,0 +1,39 @@ +/* 任务队列页(插件)—— 颜色/字号/圆角/间距全部走宿主 token;结构尺寸允许字面量。 */ +.iwb-tq { display: flex; flex-direction: column; min-height: 100%; gap: var(--iwb-space-10); } +.iwb-tq-head { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--iwb-space-16); flex-wrap: wrap; } +.iwb-tq-sub { color: var(--iwb-text2); font-size: var(--iwb-font-sm); } +.iwb-tq-tools { display: flex; align-items: center; gap: var(--iwb-space-8); } +.iwb-tq-tool-lbl { font-size: var(--iwb-font-sm); color: var(--iwb-text2); } +.iwb-tq-limit { height: 28px; padding: 0 var(--iwb-space-8); } +.iwb-tq-ghost { background: var(--iwb-panel); } +.iwb-tq-tabs { display: flex; gap: var(--iwb-space-4); border-bottom: 1px solid var(--iwb-border); } +.iwb-tq-tab { display: inline-flex; align-items: center; gap: var(--iwb-space-6); padding: var(--iwb-space-6) var(--iwb-space-10); border: 0; background: transparent; color: var(--iwb-text2); font: inherit; font-size: var(--iwb-font-sm); border-radius: var(--iwb-radius-card) var(--iwb-radius-card) 0 0; cursor: pointer; } +.iwb-tq-tab:hover { color: var(--iwb-text); background: var(--iwb-hover); } +.iwb-tq-tab.on { color: var(--iwb-accent-on-surface); background: var(--iwb-accent-tint); } +.iwb-tq-n { font-size: var(--iwb-font-2xs); line-height: 15px; padding: 0 var(--iwb-space-6); border-radius: var(--iwb-radius-full); border: 1px solid var(--iwb-border); color: var(--iwb-text2); } +.iwb-tq-tab.on .iwb-tq-n { border-color: var(--iwb-accent-on-surface); color: var(--iwb-accent-on-surface); background: transparent; } +.iwb-tq-list { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; gap: var(--iwb-space-8); } +.iwb-tq-row { display: grid; grid-template-columns: 96px minmax(0,1fr) auto; gap: var(--iwb-space-12); align-items: center; padding: var(--iwb-space-10); background: var(--iwb-panel); border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-card); } +.iwb-tq-row:hover { border-color: var(--iwb-hover-border); } +.iwb-tq-row.fail { border-color: var(--iwb-err-bd); background: color-mix(in srgb, var(--iwb-err) 9%, var(--iwb-panel)); } +.iwb-tq-thumb { width: 96px; height: 64px; border-radius: var(--iwb-radius-control); border: 1px solid var(--iwb-border); background: var(--iwb-layer2); overflow: hidden; display: grid; place-items: center; cursor: zoom-in; position: relative; } +.iwb-tq-img { width: 100%; height: 100%; object-fit: cover; display: block; } +.iwb-tq-ph { display: grid; place-items: center; gap: var(--iwb-space-2); color: var(--iwb-text2); font-size: var(--iwb-font-2xs); } +.iwb-tq-ph svg { width: 20px; height: 20px; } +.iwb-tq-main { min-width: 0; display: flex; flex-direction: column; gap: var(--iwb-space-4); } +.iwb-tq-line1 { display: flex; align-items: center; gap: var(--iwb-space-8); min-width: 0; } +.iwb-tq-name { font-size: var(--iwb-font-base); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.iwb-tq-badge { flex: 0 0 auto; height: 18px; line-height: 18px; padding: 0 var(--iwb-space-8); border-radius: var(--iwb-radius-full); border: 1px solid var(--iwb-border2); background: var(--iwb-layer); color: var(--iwb-text2); font-size: var(--iwb-font-2xs); } +.iwb-tq-badge.ok { color: var(--iwb-ok); border-color: var(--iwb-ok-bd); background: var(--iwb-ok-bg); } +.iwb-tq-badge.fail { color: var(--iwb-err); border-color: var(--iwb-err-bd); background: var(--iwb-err-bg); } +.iwb-tq-badge.only { color: var(--iwb-warn); border-color: var(--iwb-warn-bd); background: var(--iwb-warn-bg); } +.iwb-tq-meta { font-size: var(--iwb-font-sm); color: var(--iwb-text2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.iwb-tq-err { font-size: var(--iwb-font-xs); color: var(--iwb-err); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.iwb-tq-actions { display: flex; align-items: center; gap: var(--iwb-space-6); flex-wrap: wrap; justify-content: flex-end; } +.iwb-tq-btn { white-space: nowrap; } +.iwb-tq-btn.iwb-tq-primary { background: var(--iwb-brand); color: var(--iwb-on-brand); border-color: var(--iwb-brand); } +.iwb-tq-btn.iwb-tq-primary:hover { filter: brightness(1.05); } +.iwb-tq-empty { padding: var(--iwb-space-32); text-align: center; color: var(--iwb-text2); font-size: var(--iwb-font-sm); } +.iwb-tq-foot { display: flex; justify-content: space-between; gap: var(--iwb-space-12); color: var(--iwb-text2); font-size: var(--iwb-font-xs); } +.iwb-tq-hint { color: var(--iwb-text-dim); } +@media (max-width: 900px) { .iwb-tq-row { grid-template-columns: 72px minmax(0,1fr); } .iwb-tq-actions { grid-column: 2; justify-content: flex-start; } .iwb-tq-thumb { width: 72px; height: 50px; } } diff --git a/scripts/build.js b/scripts/build.js index 26200ee..e491654 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -84,6 +84,7 @@ const sourceModules = [ 'ui-components.js', 'plugin-data.js', 'plugin-api-gallery.js', + 'plugin-api-queue.js', 'plugin-api-grouplib.js', 'plugin-api-promptlib.js', 'plugin-host.js', diff --git a/scripts/sync-plugins-from-repo.js b/scripts/sync-plugins-from-repo.js index dc59680..925bfba 100644 --- a/scripts/sync-plugins-from-repo.js +++ b/scripts/sync-plugins-from-repo.js @@ -10,7 +10,7 @@ const crypto = require('crypto') const root = path.resolve(__dirname, '..') const srcRoot = process.argv[2] ? path.resolve(process.argv[2]) : path.resolve(root, '..', 'iwb-plugins-desktop') const outDir = path.join(root, 'plugins', 'runtime') -const IDS = ['album', 'batch-export', 'blank-canvas', 'browser', 'gallery', 'grouplib', 'promptlib', 'image-annotate', 'image-vectorize', 'sticky', 'style-source', 'white-bg-800', 'xianyi-cutout'] +const IDS = ['album', 'batch-export', 'blank-canvas', 'browser', 'gallery', 'grouplib', 'promptlib', 'image-annotate', 'image-vectorize', 'sticky', 'style-source', 'white-bg-800', 'xianyi-cutout', 'taskqueue'] // v3.25.41(M1):目录化插件试点 —— 这些 id 产出 /{manifest.json,main.js},其余仍是单文件(双轨兼容) // ⚠️ 2026-11-20 修正:桌面包不随包发插件(scripts/strip-plugins.js),插件只能从市场装, // 而市场目前只支持单文件 ⇒ 目录形态暂不用于生产插件,等 M3(zip 安装)落地再启用。 diff --git a/src/image-ingest-store.js b/src/image-ingest-store.js index e4c7dc6..30c7ea2 100644 --- a/src/image-ingest-store.js +++ b/src/image-ingest-store.js @@ -18,6 +18,13 @@ const d = deps || {} const lsGet = typeof d.get === 'function' ? d.get : () => null const lsSet = typeof d.set === 'function' ? d.set : () => {} + // 2026-12-03:上限由宿主配置注入(默认 500,范围 100~5000);插件只读/改配置。 + const maxOf = () => { + let n = 500 + try { n = typeof d.max === 'function' ? d.max() : (Number(d.max) || 500) } catch (e) { n = 500 } + n = Math.round(Number(n) || 500) + return Math.max(1, Math.min(5000, n)) + } let cache = null function load () { @@ -33,10 +40,11 @@ const at = arr.findIndex((x) => x.id === entry.id) if (at >= 0) arr[at] = entry else arr.push(entry) - if (arr.length > MAX) { + const max = maxOf() + if (arr.length > max) { // 淘汰最旧的非 pinned 记录(pinned = 被画布/图库引用) const drop = arr.filter((x) => !x.pinned).sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0)) - while (arr.length > MAX && drop.length) { + while (arr.length > max && drop.length) { const victim = drop.shift() const i = arr.indexOf(victim) if (i >= 0) arr.splice(i, 1) @@ -51,7 +59,23 @@ try { lsSet(KEY, arr) } catch (e) { /* ignore */ } } function list () { return load().slice() } - return { load, save, remove, list, KEY, MAX } + // 立即按当前上限裁剪(改设置后调用;只删记录,不删图片) + function trim () { + const arr = load() + const max = maxOf() + if (arr.length <= max) return 0 + const drop = arr.filter((x) => !x.pinned).sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0)) + let removed = 0 + while (arr.length > max && drop.length) { + const victim = drop.shift() + const i = arr.indexOf(victim) + if (i >= 0) { arr.splice(i, 1); removed++ } + } + if (removed) { try { lsSet(KEY, arr) } catch (e) { /* ignore */ } } + return removed + } + function clear () { cache = []; try { lsSet(KEY, []) } catch (e) { /* ignore */ } } + return { load, save, remove, list, trim, clear, KEY, MAX } } // 视图:url → { status, localUrl, bytes, error };订阅者用于 React 重渲染 diff --git a/src/image-ingest.js b/src/image-ingest.js index 47272ba..be51eb8 100644 --- a/src/image-ingest.js +++ b/src/image-ingest.js @@ -200,6 +200,20 @@ return publicView(e) } + // 清空已结束的记录(ready/failed/link-only);进行中的保留(正在下载/排队),避免清掉在飞任务。 + function clearFinished () { + let n = 0 + for (const [id, e] of Array.from(entries.entries())) { + if (e.status === STATE.READY || e.status === STATE.FAILED || e.status === STATE.LINK_ONLY) { + entries.delete(id) + try { if (typeof d.removeEntry === 'function') d.removeEntry(id) } catch (err) { /* ignore */ } + n++ + } + } + if (n) emit('cleared', { count: n }) + return n + } + function remove (id) { const at = queue.indexOf(id) if (at >= 0) queue.splice(at, 1) @@ -233,7 +247,7 @@ return publicView(e) } - return { enqueue, retry, cancel, release, remove, get, list, stats, restore, markMissing, STATE } + return { enqueue, retry, cancel, release, remove, clearFinished, get, list, stats, restore, markMissing, STATE } } // 带进度的取字节:流式读 body,按 content-length 报百分比;拿不到长度就只报已收字节。 diff --git a/src/plugin-api-queue.js b/src/plugin-api-queue.js new file mode 100644 index 0000000..de72569 --- /dev/null +++ b/src/plugin-api-queue.js @@ -0,0 +1,47 @@ +/* plugin-api-queue.js —— 宿主「任务队列」能力(2026-12-03) + * + * 插件只是一个视图:账本、下载、落地、定位、记录上限全部在宿主。 + * 与 gallery 能力同构:setImpl 由 Workbench 每次渲染注入,插件拿到稳定代理。 + */ +;(function (global) { + 'use strict' + + let impl = null + const listeners = [] + + function setImpl (next) { impl = (next && typeof next === 'object') ? next : null } + + function call (name) { + return function () { + const fn = impl && impl[name] + if (typeof fn !== 'function') return Promise.reject(new Error('任务队列能力未就绪')) + try { return Promise.resolve(fn.apply(null, arguments)) } catch (e) { return Promise.reject(e) } + } + } + + function emit (reason) { + for (const fn of listeners.slice()) { + try { fn(reason || 'changed') } catch (e) { /* 插件回调异常不影响宿主 */ } + } + } + + const API = { + list: call('list'), + retry: call('retry'), + land: call('land'), + preview: call('preview'), + copyLink: call('copyLink'), + locate: call('locate'), + stats: call('stats'), + clear: call('clear'), + getLimit: call('getLimit'), + setLimit: call('setLimit'), + onChanged: function (fn) { + if (typeof fn !== 'function') return function () {} + listeners.push(fn) + return function () { const i = listeners.indexOf(fn); if (i >= 0) listeners.splice(i, 1) } + }, + } + + global.IWBPluginQueue = { setImpl, api: function () { return API }, emit } +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/src/plugin-host.js b/src/plugin-host.js index 8c3eb96..2ca6f24 100644 --- a/src/plugin-host.js +++ b/src/plugin-host.js @@ -4,8 +4,8 @@ const API_VERSION = 1 const ID_PATTERN = /^[a-z][a-z0-9-]{2,31}$/ const REQUIRED_FIELDS = ['id', 'name', 'version', 'apiVersion', 'capabilities'] - const CAPABILITIES = ['panels', 'commands', 'nodeTypes', 'generationHooks', 'providers', 'canvas', 'canvasWrite', 'nodeActions', 'gallery', 'grouplib', 'promptlib', 'files', 'images'] - const CAPABILITY_API_KEYS = { panels: 'ui', commands: 'commands', nodeTypes: 'nodes', generationHooks: 'generation', providers: 'providers', canvas: 'canvas', canvasWrite: 'canvas', nodeActions: 'nodeActions', gallery: 'gallery', grouplib: 'grouplib', promptlib: 'promptlib', files: 'files', images: 'images' } + const CAPABILITIES = ['panels', 'commands', 'nodeTypes', 'generationHooks', 'providers', 'canvas', 'canvasWrite', 'nodeActions', 'gallery', 'grouplib', 'promptlib', 'files', 'images', 'queue', 'pages'] + const CAPABILITY_API_KEYS = { panels: 'ui', commands: 'commands', nodeTypes: 'nodes', generationHooks: 'generation', providers: 'providers', canvas: 'canvas', canvasWrite: 'canvas', nodeActions: 'nodeActions', gallery: 'gallery', grouplib: 'grouplib', promptlib: 'promptlib', files: 'files', images: 'images', queue: 'queue', pages: 'ui' } function createPluginHost(options) { const opt = options || {} diff --git a/src/runtime-workbench-logic.js b/src/runtime-workbench-logic.js index a6cb6da..2161283 100644 --- a/src/runtime-workbench-logic.js +++ b/src/runtime-workbench-logic.js @@ -240,7 +240,18 @@ const cur = gn && Array.isArray(gn.data.result) ? gn.data.result : [] const nextResult = upsertGenerationEntry(cur, entry) // 2026-12-02:每张结果落地就入队(这里是「结果写进节点数据」的唯一入口,批量/恢复都经过它) - try { if (global.__iwbIngest && entry && entry.url) global.__iwbIngest.enqueue({ url: entry.url, source: 'gen', w: entry.width, h: entry.height }) } catch (eI) { /* 落地失败不得影响出图 */ } + // 2026-12-03:带 meta(画布/节点/提示词/模型/尺寸),任务队列页据此跨画布展示与定位。 + const _ws0 = (refs.workspaces || []).find((w) => w.id === runWorkspaceId) + const _meta = { + boardId: runWorkspaceId, + boardName: String((_ws0 && _ws0.name) || ''), + nodeId, + prompt: String((entry && (entry.taskTitle || entry.label)) || '').slice(0, 200), + model: String((node && node.data && node.data.model) || ''), + size: size || ((entry && entry.width && entry.height) ? (entry.width + 'x' + entry.height) : ''), + at: Number(entry && entry.at) || Date.now(), + } + try { if (global.__iwbIngest && entry && entry.url) global.__iwbIngest.enqueue({ url: entry.url, source: 'gen', w: entry.width, h: entry.height, meta: _meta }) } catch (eI) { /* 落地失败不得影响出图 */ } genLatest = baseNodes.map((n) => (n.id === nodeId ? { ...n, data: { ...(n.data || {}), result: nextResult } } : n)) genLatest = commitRunNodes(runWorkspaceId, genLatest) } diff --git a/src/storage-file.js b/src/storage-file.js index 6c09c15..04fb72b 100644 --- a/src/storage-file.js +++ b/src/storage-file.js @@ -63,6 +63,7 @@ iwb_web_groups: 'groups.json', // 节点组 iwb_web_groupgroups: 'group-groups.json', // 节点组的分组树 iwb_web_outputs: 'gallery/index.json', // 图库清单(图片字节仍在 images/gallery/,按 hash 引用) + iwb_ingest_idx: 'task-queue/index.json', // 任务队列账本(全局生成记录;不随设置/画布一起写) } const libFileOf = (k) => LIB_FILES[k] || '' const dirtyWs = new Set() diff --git a/src/ui-nav-rail.js b/src/ui-nav-rail.js index f4e9fc6..c40ae4b 100644 --- a/src/ui-nav-rail.js +++ b/src/ui-nav-rail.js @@ -77,6 +77,9 @@ const onHome = props.onHome const onCanvas = props.onCanvas const onPlugins = props.onPlugins + const pages = Array.isArray(props.pages) ? props.pages : [] + const activePage = String(props.activePage || '') + const onPage = props.onPage const onHelp = props.onHelp const onHotkeys = props.onHotkeys const onSkin = props.onSkin @@ -195,6 +198,7 @@ item('home', 'home', '首页(画布库)', view === 'home', onHome), item('canvas', 'layer', '列表(画布工作区)', view === 'canvas', onCanvas), item('plugins', 'box', '插件', view === 'plugins', onPlugins), + pages.map((p) => item('pg:' + p.pluginId + ':' + p.id, p.icon || 'queue', p.title, activePage === (p.pluginId + ':' + p.id), () => { if (typeof onPage === 'function') onPage(p.pluginId, p.id) })), ), el('div', { className: 'iwb-navrail-spacer' }), el('div', { className: 'iwb-navrail-group' }, diff --git a/tests/fixtures/iwb-app-global-reads.json b/tests/fixtures/iwb-app-global-reads.json index 103a1d4..d64a186 100644 --- a/tests/fixtures/iwb-app-global-reads.json +++ b/tests/fixtures/iwb-app-global-reads.json @@ -51,6 +51,7 @@ "IWBPluginGroupLib", "IWBPluginHost", "IWBPluginPromptLib", + "IWBPluginQueue", "IWBPromptCover", "IWBProviderPing", "IWBResultImg", diff --git a/tests/fixtures/iwb-source-modules-order.json b/tests/fixtures/iwb-source-modules-order.json index bab9df6..f9fa701 100644 --- a/tests/fixtures/iwb-source-modules-order.json +++ b/tests/fixtures/iwb-source-modules-order.json @@ -56,6 +56,7 @@ "ui-components.js", "plugin-data.js", "plugin-api-gallery.js", + "plugin-api-queue.js", "plugin-api-grouplib.js", "plugin-api-promptlib.js", "plugin-host.js", diff --git a/tests/plugin-host-test.js b/tests/plugin-host-test.js index 56b6c6f..97be823 100644 --- a/tests/plugin-host-test.js +++ b/tests/plugin-host-test.js @@ -13,7 +13,7 @@ vm.runInNewContext(source, sandbox) const host0 = sandbox.IWBPluginHost assert.ok(Number.isInteger(host0.apiVersion) && host0.apiVersion >= 1, 'apiVersion 必须是正整数') assert.ok(Array.isArray(host0.capabilities) && host0.capabilities.length >= 7, '能力清单应非空') -assert.strictEqual(host0.capabilities.slice().sort().join(','), 'canvas,canvasWrite,commands,files,gallery,generationHooks,grouplib,images,nodeActions,nodeTypes,panels,promptlib,providers') +assert.strictEqual(host0.capabilities.slice().sort().join(','), 'canvas,canvasWrite,commands,files,gallery,generationHooks,grouplib,images,nodeActions,nodeTypes,pages,panels,promptlib,providers,queue') const manifest = (over) => Object.assign({ id: 'demo-plugin', name: 'Demo', version: '1.0.0', apiVersion: 1, capabilities: [] }, over) const stateOf = (ids) => { diff --git a/tests/source-text-ratchet-test.js b/tests/source-text-ratchet-test.js index f4283c0..306e013 100644 --- a/tests/source-text-ratchet-test.js +++ b/tests/source-text-ratchet-test.js @@ -130,7 +130,7 @@ const MAX_SRC_COMPONENT_LINES = 531 // 2026-12-02 纳入记账基线(此前 // −1(122→121)2026-12-02:插件画布桥新增 IWBPluginCanvasBridge(+1),同时删掉两个从未被引用的工厂导出 // IWBStorageRuntimeFactory / IWBRuntimeMetricsFactory(−2,实例导出 IWBStorageRuntime / IWBRuntimeMetrics 仍在用)。 // 新增模块请先看能不能挂到已有命名空间;确需新增则同批下调基线。 -const MAX_SRC_GLOBALS = 123 // 2026-12-02 +1(122→123):新增 IWBImageIngestStore(持久化+状态视图),与 ingest 执行器分属两层 // 2026-12-02 +1(121→122):新增 IWBImageIngest(结果落地管线);此前删掉 2 个死工厂导出,净额相对峰值 123 仍为 −1 +const MAX_SRC_GLOBALS = 124 // 2026-12-03 +1(123→124):新增 IWBPluginQueue(任务队列能力桥,与 gallery 同构)。之后只减不增。 // ── app.js 总行数 & Workbench 行数棘轮(只减不增)──────────────────────────── // 动机(2026-10-29 用户提问"以后新功能会不会还往 app.js 里加"): // 上面的 MAX_APP_COMPONENT_LINES **明确跳过 Workbench**,而且此前**没有** app.js 总行数守卫 @@ -175,7 +175,7 @@ const MAX_SRC_GLOBALS = 123 // 2026-12-02 +1(122→123):新增 IWBImageI // · 图标解析统一(右键菜单 + 设置页走同一解析器,2 行) +2 // 通用件(pick/grant/stat/readDataUrl/readBlob/参数校验)全部在 src/image-file-ref.js // 与 src/plugin-api-images.js,app.js 只做装配。 -const MAX_APP_JS_LINES = 9146 // +56(9,090→9,146)2026-12-03:图库一致性快修(add 按 url 幂等 / 批末等归档队列排空 / 面板打开自愈 / markOk 前校验落盘),逻辑仍在 app.js 的图库存储段。之后只减不增。 +const MAX_APP_JS_LINES = 9309 // +162(9,146→9,308)2026-12-03:任务队列(queue/pages 能力 + 整页容器 + 左栏入口 + land/preview/locate/limit 装配)。之后只减不增。 const MAX_APP_JS_SHARE = 0.40 // ── 历史记账(供回溯,逐条保留)────────────────────────────────────────────── @@ -218,7 +218,7 @@ const MAX_APP_JS_SHARE = 0.40 // 需要实时读 .iwb-world 变换 + 按同类型实测高度校正视觉中心;属装配层的 DOM 读取, // 放 src 会引入新的全局读取与边界快照改动,权衡后留在 app.js // +10(2026-11-01):背景色「悬停预览」的 DOM 补丁助手(纯 DOM,不写数据/不进撤销栈); // 属装配层最小的 DOM 操作,放 src 会引入新的全局读取与边界快照改动,权衡后留在 app.js -const MAX_WORKBENCH_LINES = 2533 // -19(2,552→2,533)2026-12-02:同上——fetchBytes 适配器整块移入 src/image-ingest.js(createFetchBytes),Workbench 只留一行装配。之后只减不增。 +const MAX_WORKBENCH_LINES = 2652 // +118(2,533→2,651)2026-12-03:同上(任务队列 queue/pages 装配与页面容器)。之后只减不增。 // 2026-11-18 v3.25.21:模态层指针守卫(2 行) // 实测 3090 → 2998(省 92):① 生成取消族 cancelRunsFor/cancelRun/cancelTaskJobs // → src/runtime-workbench-logic.js 的 createCancelActions(−53);② 工作区列表写回族