Compare commits

...
46 Commits
Author SHA1 Message Date
qiqi 98fd50ad91 docs(site): v3.26.72 下载页与更新记录
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 54s
2026-11-25 18:10:04 +08:00
qiqi 1a80fc9c2e docs: 架构现状基线锚点对齐 v3.26.72 2026-11-25 18:05:58 +08:00
qiqi d7a2a173b1 fix: v3.26.72 设置默认通用标签 / 更多菜单被遮罩盖住 / 模型删除按钮默认隐 / 默认模型标识始终可见 2026-11-25 18:04:40 +08:00
qiqi 7bc1ae6ce6 docs(site): v3.26.71 下载页与更新记录
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 40s
2026-11-25 17:30:26 +08:00
qiqi 309d2d7773 feat: v3.26.71 设置默认通用 tab + 左下快捷菜单/升级图标 + 模型行样式 + 默认模型 2026-11-25 17:25:02 +08:00
qiqi 808abbc766 docs(site): v3.26.70 下载页与更新记录
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 52s
2026-11-25 16:28:39 +08:00
qiqi 9b3f2ae6bc docs: 锚点对齐 v3.26.70+90b5780(publish 自动) 2026-11-25 16:25:35 +08:00
qiqi 90b5780ed1 fix(browser): target=_blank 在新窗口请求里原地打开
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m30s
2026-11-25 16:23:53 +08:00
qiqi d7404fe720 chore(plugins): 同步 gallery 1.7.1(底栏三个图标加大)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 57s
- 刷新 / 打开本地目录 / 设置:SVG 14 → 18(--iwb-icon-lg),描边 1.6,
  按钮命中区 20×20 → 28×28,工具组 gap 0 → 4,设置浮层 bottom 34 → 40。
- 浮层层级按 §3.6 从裸 z-index:30 收进 --iwb-z-ctx-menu(91),过 token-lint。
- 市场包 gallery-1.7.1.zip、market 索引/首页、下载站索引与页面同步;
  公网回读版本 1.7.1 且 zip sha256 与索引一致。lint:tokens / test:tokens / test:facts 全过。
2026-11-25 14:16:36 +08:00
qiqi 87276f2473 chore(plugins): 同步 promptlib 1.13.1(变量栏去 i 按钮 + 行间分割线)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 58s
- 变量编辑右栏删掉每行的 i 圆按钮(与整行点击重复),整行点击成为唯一入口;
  展开态由 caret 主色 + 整行 hover 反馈表达。
- 分割线按 design-tokens.md §3.11 的 --iwb-set-divider 公式落在「行与行之间」,
  1px 实线、首行与末行之后都不画;标题下与展开字段前不另画线。
- 市场包 promptlib-1.13.1.zip、market/index.json、市场首页、下载站索引与页面
  全部同步;公网回读索引版本与 zip sha256 一致。
2026-11-25 13:56:05 +08:00
qiqi b1a7bc2345 chore(plugins): 同步 album 1.1.2(看大图支持左右切换)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 54s
- 插件自带全屏查看器:← → / 按钮 / 滚轮循环切换整本相册,点空白或 Esc 退出;
  只解码当前张 + 预取左右各一张,避免整本原图 dataURL 爆内存。
- 保留宿主预览原有的复制(PNG)/ 下载按钮;键盘与滚轮监听在关闭时清理。
- 市场 zip 与下载站索引/页面同步到 1.1.2。
2026-11-25 10:33:49 +08:00
qiqi c8df8c06a7 docs(site): v3.26.69 补 Windows x64 记录
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 50s
2026-11-25 10:18:55 +08:00
qiqi 39458969c0 chore(plugins): 同步 album 1.1.1(点放大镜看大图,hover 预览已删)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 46s
- album 1.1.1:去掉 1.1.0 的节点内 hover 预览层(它盖住放大镜,实测点不到),
  只看大图统一走「点放大镜 → 宿主全屏预览」,点图片外空白或 Esc 自动退出。
- 市场/下载站索引与页面同步到 1.1.1。
2026-11-25 10:08:10 +08:00
qiqi b63e209271 docs(changelog): v3.26.69 记录 + 站点产物(相册 1.1.0 / 修组合节点破图)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 45s
- CHANGELOG 补 v3.26.69 条目(release-records 门禁要求每个 bump 版本有记录)
- site/ 重新生成:首页与下载页显示 3.26.69,插件页 13 个插件
- Cargo.lock 随 set-version 更新
2026-11-25 09:58:11 +08:00
qiqi 8621019ae4 docs: 锚点对齐 v3.26.69+ab54691(publish 自动) 2026-11-25 09:56:00 +08:00
qiqi ab546911ac fix(preview): wResolveImg 认 __file,相册的图在组合节点/参考图里不再破图;内置 album 1.1.0
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 44s
一、预览链根因(用户报「相册的图传到组合节点显示不出内容」)
  wResolveImg 是所有节点预览的唯一入口(图片节点 / 参考图 mini / 组合节点 / 插件节点),
  但它只认 __blob / __cache,遇到相册写的 { __file: 绝对路径 } 就把引用对象原样返回,
  上层 wThumbSrc 里 String(对象) 得到 [object Object] ⇒ img 的 src 就是个坏字符串 ⇒ 破图。
  而 wEnsureImgUrl / wImgRefDataUrl 早就支持读盘 —— 只差这个入口判定,加 wIsFileRef 即可。
  生成不受影响(走 wImgRefDataUrl),所以这个 bug 一直只在「预览」里可见。

二、内置 album 1.1.0(方形宫格 / 清除按钮 / 放大镜 hover 预览 + 点击全屏 / 5 个布局翻页 bug)

三、新增 tests/image-file-ref-preview-test.js(12 项,已接入 test:unit)
  行为断言三种引用键互不冲突 + 源断言 wResolveImg 入口含 __file、四个读盘入口都在。
  这类「入口少一个分支」的漏很难手工发现,钉成断言。

版本 3.26.69(dmg 随发布链重建)
2026-11-25 09:53:09 +08:00
qiqi f59c985c37 docs(site): v3.26.68 补 Windows x64 记录
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 44s
2026-11-25 09:01:53 +08:00
qiqi dcc9f8a781 chore(plugin): 同步 album 1.0.4(节点 outKind 自愈)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 40s
2026-11-25 08:44:34 +08:00
qiqi 85b1d057f4 docs(site): v3.26.68
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 38s
2026-11-25 08:38:15 +08:00
qiqi bebf737724 docs: 锚点对齐 v3.26.68+a62f2ea(publish 自动) 2026-11-25 08:37:39 +08:00
qiqi a62f2ea026 release: v3.26.68 相册体验修复(拼图图标入口/高度稳定/文件夹导入/选中态) 2026-11-25 08:36:26 +08:00
qiqi bf59786a30 docs(site): v3.26.67
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 36s
2026-11-25 08:24:14 +08:00
qiqi d0bc75eab3 docs: 锚点对齐 v3.26.67+ca96707(publish 自动) 2026-11-25 08:23:49 +08:00
qiqi ca9670739f release: v3.26.67 底栏「插件节点」下拉(插件节点入口可见化) 2026-11-25 08:22:25 +08:00
qiqi e35c2e958f feat(market): 上架相册插件 v1.0.0(meta + 市场索引 + zip) 2026-11-25 07:42:10 +08:00
qiqi ebaf030759 docs(site): v3.26.66
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 39s
2026-11-25 07:40:05 +08:00
qiqi ad909fc3e5 docs: 基线锚点对齐 v3.26.66 2026-11-25 07:37:52 +08:00
qiqi c27ba1e801 release: v3.26.66 相册节点 v1 2026-11-25 07:34:40 +08:00
qiqi c06f671921 fix(album): ctx.images 注入失败(fileRef 是对象却按函数校验)+ 任务容器按任务 id 集合重挂载(切模式后任务行不刷新) 2026-11-25 07:34:27 +08:00
qiqi 180456e15b chore(album): 同步 album 插件产物(tokens 化样式) 2026-11-25 07:15:42 +08:00
qiqi e3d2e449e1 feat(album): 相册节点宿主侧——多图源任务展开(一图一任务/批量分批)+组合扇出+ctx.images(引用/导入)+{__file}本地文件引用+保留原图 2026-11-25 07:12:55 +08:00
qiqi 64da475c7f docs(site): v3.26.65 补 Windows x64 记录
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m39s
2026-11-24 23:28:29 +08:00
qiqi fc169d3a0d docs(site): v3.26.65
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m32s
2026-11-24 22:57:13 +08:00
qiqi 6f558a6478 docs: 锚点对齐 v3.26.65+2b35366(publish 自动) 2026-11-24 22:56:31 +08:00
qiqi 2b35366722 release: v3.26.65 生图 API 三处硬伤修复 2026-11-24 22:55:08 +08:00
qiqi c7930e5a01 feat(api): genPath/editPath 生效 + auth 四态(bearer/header/query/none)+ 生图地址回退(结果未知不重提) 2026-11-24 22:55:08 +08:00
qiqi 1839a7460a chore(hygiene): 删死代码(plugin-archive 206 行 / image-preview-derive 449 行 / isTransientApiError)+ e2e 已知红清单与对照脚本 2026-11-24 22:46:41 +08:00
qiqi 0566be9b79 docs(analysis): 本地图片链路 & 生图 API 缺口 + 全局缺陷审计(2026-11-24) 2026-11-24 22:39:06 +08:00
qiqi 890565cfd4 docs(site): v3.26.64
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 2m50s
2026-11-24 22:18:28 +08:00
qiqi b92a30ff9a docs: 锚点对齐 v3.26.64+afe5075(publish 自动) 2026-11-24 22:17:53 +08:00
qiqi afe507557e release: v3.26.64 修复失效 e2e 选择器 2026-11-24 22:16:22 +08:00
qiqi 746fbc1e5e test(e2e): 修 8 个 spec 的失效选择器 .iwb-tab-home(v3.25.62 已删元素)→ 统一走导航「首页」;清死 CSS 与钉点 2026-11-24 22:16:17 +08:00
qiqi 26c5ecff7b docs(site): v3.26.63
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m40s
2026-11-24 21:30:22 +08:00
qiqi 1d571623b0 docs: 锚点对齐 v3.26.63+06e27af(publish 自动) 2026-11-24 21:27:52 +08:00
qiqi 06e27afa1d release: v3.26.63 规则统一 P0 2026-11-24 21:26:20 +08:00
qiqi f520e1a0fd refactor(rules): P0 统一 —— 确认包装 7 份收为 1 份、剪贴板 5 处走门面、棘轮硬数字进 sync-facts + 守卫 2026-11-24 21:26:16 +08:00
95 changed files with 3489 additions and 1406 deletions

No files matched your search

+21 -1
View File
@@ -1,6 +1,6 @@
# 待办清单(BACKLOG)
> **最后更新:2026-11-16** · **线上(正式站与测试站)均为 `v3.24.85+7df9dc4`**
> **最后更新:2026-11-24** · **线上 `v3.26.65`(桌面端,三平台清单分别维护)**
> (v3.24.85 = 代码体检收口:棘轮收回 Workbench 3090→2998(上限降到 3030)+ 图库索引 4 条绕过锁的写路径收口到 `mutate` + 文档数字校准。
> 三地址一致 + `IWB_VERIFY_STRICT=1` 通过,`stable` / `stable-v3.24.85` / `stable-verified-2026-11-16` 均指向 `7df9dc4`;
> 上一版 v3.24.84 = 生图节点连 3 条上游只出 1 个任务 ⇒ 任务身份改用 `ownerNodeId`=直接上游节点,连几条线就几个任务,`relay` 仍归约到真实文本来源(`stable-v3.24.84`→`c8b7543`);
@@ -37,6 +37,26 @@
## 1. P0 — 低风险、可立即做
### 1.2 预览产物按需解码(**重做**,2026-11-24 立)
> **为什么重做**:v3.87.x 的「W2-A 预览产物模块」当时记为「✅ 已接入构建」,但 2026-11-24 复核发现
> `wPreviewUrlOf` 是**恒等函数**(`app.js:4825 return v`),模块从未被调用;模块 + 单测已于 **v3.26.65 删除**
> (见 commit `docs(analysis)` 之后的清理提交,以及 `docs/standards/engineering-rulebook.md` §13.34.6 的更正)。
> 原计划:`docs/archive/plans/opentu-parity-image-memory.md` §W2-A。
- **目标**:预览用图按 1024 长边解码(`createImageBitmap(blob,{resizeWidth})`),用后 `close()`,降低大图预览的峰值内存
- **关键难点**:`wPreviewUrlOf` 是同步返回 URL 的,接线需要异步化(objectURL 生命周期 + 组件卸载释放),
不是「加一行调用」;先量出收益(预览场景峰值内存)再动手
- **验收**:`tests/_perf-baseline.spec.js` 的预览场景峰值下降 ≥20%,且无 objectURL 泄漏(复用现有回收计数探针)
### 1.3 死代码判定口径(**教训**,2026-11-24)
- **「有单测」不等于「有消费者」**:本轮删掉的两个模块(206 + 449 行)都有绿色单测,但生产代码零调用
⇒ 覆盖率虚高。新增模块必须在**同一个 PR 里**接到调用点,否则不合并
- `deadTokens`(32 个)**不要按名字批量删**:其中 `--iwb-plugin-*` 13 个是插件主题契约、`--fs-*`/`--sp-*`/`--rd-*`/`--tr-*` 是 legacy 别名,
`--iwb-surface` 被 ai-chat 插件、`--fs-xs` 被 style-source 插件引用(跨仓)。判死前先 grep 外仓
> **⚠️ 当前 P0 无待办项。** 唯一一条(1.1 钉点还债)已于 2026-10-31 核准**收口暂停**,理由见下。
> 本节保留是为了记住「为什么停下」,不是还欠着活。
+182
View File
@@ -16,6 +16,188 @@
> 3. 核验正式地址版本 → 之后才移动 `stable` / `stable-verified-<日期>` 标签、更新本 CHANGELOG、写 GitHub Release(`gh release create`)。
> 测试发现问题 → 改 → 再 `deploy:test`,正式环境不受影响。回滚点 `git reset --hard stable`。
## v3.26.72(2026-11-25)修 v3.26.71 三处「改了但看不到」
**宿主**
- **设置页打开后仍停在下「生图服务」**:v3.26.71 只改了面板内部默认值,宿主装配处仍显式传 `initialTab: 'gen'`,把默认值盖掉了。现在统一走 `openSettings(tab?)`:不传参即「通用」,只有「去导出」「内存」这类明确入口才直达备份/诊断页。
- **左下角「更多」点开是空的**:菜单 DOM 与内容都在,但用的 `.iwb-ctxmenu` 默认层级 91,被首页 `.iwb-overlay`(100)整页盖住 ⇒ 视觉上像空菜单。现与「右键移动到分组」菜单共用 `--iwb-z-sheet-menu`(270),叠在遮罩之上。
- **模型行垃圾桶默认就显示**:补 `visibility` 双保险(原先只靠 `opacity`),未悬停/未聚焦时彻底不渲染可见像素;悬停或键盘聚焦该行才显形。
- **「默认」标识此前要看运气**:生效值改为「未配置也回退主服务首个可见模型」,于是默认模型下拉、模型行「默认」标识、新建节点预选三处永远指向同一个模型,不再出现「下拉是空的、行上没有标识」。
- 网页版(无 Tauri 桥)不再显示「检查失败:桌面端不可用」,那是预期内不可用而非错误。
**验证**:`verify:ci` 全绿;新增单测覆盖「未配置 ⇒ 回退主服务首个」;默认模型 e2e 2/2 + settings-crud / quality-tier / shape-settings 7/7。
## v3.26.71(2026-11-25)设置体验收口 + 配置节点默认模型
**宿主**
- **设置页默认打开「通用」标签**(此前是「生图服务」):首屏先看全局设置,模型/Key 按需再切。
- **左下角「更多」从空操作改为快捷菜单**:首页 / 插件 / 源码地址 / 版本号 / 检查更新。桌面端挂载即静默检查更新;**发现新版本时 ⋯ 变成圆形上箭头升级图标**,点开菜单首项即可走 Tauri 原地升级(签名校验在 Rust 侧)。
- **模型删除改为行内垃圾桶按钮**:生图模型与分层模型行的「⋯ → 删除模型」两级操作压成一步;内置模型的垃圾桶禁用并带说明;按钮常态隐藏、悬停行才显形防误触。样式沿用设计 token。
- **模型行样式优化**:启用复选框换成圆角开关(保留隐藏 checkbox 兼容既有选择器);质量胶囊去掉外框小方框、只留底色+文字;分层模型行同步。
- **新增「新建配置节点默认模型」**(通用 tab 单独一组):下拉列出所有服务商已启用模型;新建配置节点(工具栏/右键/连线三条路径)统一预选该模型,已有节点不动。默认模型所在行加淡底 + 蓝描边 + 「默认」标识。配置存 `defaultGen{providerId,model,keyGroup}` 随备份走;模型被删/关闭时自动回退主服务首个启用模型;未设置时保留原系统默认。与 LLM 渠道的 `defaultModel` 隔离。
- 配置节点默认模型逻辑落在新模块 `src/generation-default-model.js`,`DEFAULTS.gen` 用 getter 实时读取,宿主只做装配。
**验证**:`verify:ci` 全绿;新增单测 + 2 条 e2e 覆盖默认模型链路,既有 settings-crud / quality-tier / shape-settings 无回归。
## v3.26.70(2026-11-25)修浏览器面板 / 独立窗口里 `target="_blank"` 链接点了没反应
**宿主**
- **接住原生新窗口请求**(用户报障:花瓣「推荐画板」这类卡片点击无反应):`canvas_webview_ensure` 与 `open_browser_window` 都注册 `on_new_window`。此前 wry 的 macOS delegate 在没有 handler 时直接返回 `None`,`window.open` / `target="_blank"` 被静默丢弃,页面没有任何报错。
- 新策略:只放行 `http/https`,返回 `NewWindowResponse::Deny` 禁止弹新窗口,再由 Rust 把 URL 交给**当前 webview 原地导航**。
- 左侧栏浏览器面板与画布网页节点共用同一个子 webview builder,一次修复两处;独立浏览器窗口同步修复。面板地址栏继续由已有 `cwv-page` 事件自动回填,`←` 可回到上一页。
- 不加载 Chrome 扩展;本次只改宿主原生层,不涉及插件版本。
## v3.26.69(2026-11-25)相册 1.1.0(方形宫格 / 一键清空 / 放大镜预览)+ 修「相册的图在组合节点里破图」
**宿主**
- **修组合节点 / 参考图 / 图片节点里相册的图不显示**(用户报障):`wResolveImg` 是所有节点预览的唯一入口,
但它只判 `__blob` / `__cache`。相册只存路径(`{__file:'/abs/a.png'}`,只引用不复制字节),
于是引用对象被原样返回 ⇒ 上层 `wThumbSrc` 里 `String(obj)` 得到 `[object Object]` ⇒ 破图。
`wEnsureImgUrl` / `wImgRefDataUrl` 早就支持 `__file` 读盘,只差入口这一处判定 —— 补 `wIsFileRef` 后
全链恢复(提示词 / 文本节点本身不含图,不受影响)。**生成从来不受影响**,这个 bug 只在预览里可见。
- 新增 `tests/image-file-ref-preview-test.js`(12 项,已进 `test:unit`):三种引用键互不冲突 +
四个读盘入口都在。这类「入口少一个分支」的漏手工很难发现。
**插件 album v1.1.0**
- **宫格固定正方形**(`aspect-ratio:1/1`):此前格子高度由图片比例决定 —— 4 张 16:9 宽图会变成 22px 细条、
竖图撑到 167px,与 `capacityOf()` 按方形算的容量是两套账,最后一行常被裁一半
- **一键清空**(顶栏最右,仅有图时出现):走撤销快照,⌘Z 可整体恢复;不删磁盘上的原文件
- **放大镜预览**:hover 在**节点框内**浮出大图(铺满节点、`pointer-events:none` 不挡点击),
点一下进宿主全屏预览。删除按钮从右下让到右上(原来那个批次角标「1」已删除 —— 顶栏
「N 张 → M 个任务」已经说清楚,是重复信息)
- **选中线 2px → 1px**(用户反馈太粗),失联虚线同步
- 修 **S/M/L 档位反了**:旧值 `{S:64, M:48, L:100}` 里中格比小格还小(每页 30 张 vs 20 张)。
现 64/80/104 ⇒ 300×470 下每页 20 / 12 / 4
- 修 **容量常量与 CSS 不对齐**:GAP 5→4、工具条 27→25、提示行 24→28(宿主全局 `border-box`,
CSS 的 height 已含 padding)。掉 1px 就是「最后一行被裁」
- 修 **跨页拖拽错位**:本页起点该是 `page × 每页容量`,旧代码乘的是「本页格子数」,
而格子数含末尾「+添加」格 ⇒ 第 2 页把 21 号拖到第 2 位会插到全局第 13 位
- 修 **删除任何页都跳回第 1 页**(硬编码 `page:0`)
- 修 **缩略图串味**:键曾是 `路径 || 文件名`,固化后 src 没有路径 ⇒ 不同目录的同名图共用缩略图
- 修 空 `src` 触发对页面 URL 的空请求;空节点仍显示「全部 0 张一页展示」;
网页版「文件夹」按钮 `canReference() || true` 恒真(点了没反应);缩略图预生成补进度
- 新增 `album/tools/harness.mjs`(44 项,此前插件侧零测试),含几何不变量:
35 种节点尺寸 × 3 档 × 有无提示行,算出的容量都装得进可视区
## v3.26.68(2026-11-26)相册插件体验修复(图标入口 / 高度稳定 / 文件夹导入 / 选中态)
**宿主**
- 底栏「插件节点」入口改为**拼图图标按钮 + 弹出列表**(此前是文字下拉,用户要求只留图标)
- 插件节点图标:新增 `puzzle` 图标,插件变体可声明 `icon` 使用
**插件 album v1.0.3**
- **插入后不再慢慢变矮**:高度只取「显式 node.h / 变体默认 470」,不再用 measuredH 回写(否则内容变矮→卡片变矮→越量越矮)
- **文件夹导入修好**:之前把 pick 返回的目录路径直接按图片后缀过滤 ⇒ 全被丢掉(点了没反应);现按目录展开图片(递归 1 层、上限 500 张),新增宿主能力 `ctx.images.listImages`
- **选中态刷新修好**:宫格重建签名加入 `on` 状态,点选/取消立刻可见(此前只更新计数、格子样式不动)
- 样式修正:`--iwb-line`/`--iwb-line-weak` 并不存在 ⇒ 边框改用 `--iwb-border`(之前边框实际是无效声明)
## v3.26.67(2026-11-26)插件节点入口:底栏「插件节点」下拉
> 状态:macOS 双架构待发;Windows 待构建
**为什么**:相册插件装好了,但唯一入口藏在「右键画布 → 添加节点 → 插件节点」,用户找不到(web 版不在考虑范围)。
**改动**
- 画布底栏新增「插件节点」下拉:列出所有已激活插件节点(相册 / 网页 / 提示词模板 / 便利贴 / 样式节点…),选中即插入到视口中央
- 无插件节点时整块不渲染(内置节点入口与布局零变化)
- 插件侧同步清理:移除无效的「资源库面板」实验(宿主的面板槽是硬编码白名单,插件无法新增,见 `src/ui-dock-panels.js`)
**入口(装好相册插件并重启后)**
1. 底栏「插件节点」下拉 → 相册
2. 右键画布空白 → 添加节点 → 插件节点 → 相册
## v3.26.66(2026-11-26)相册节点 v1(宿主持久化 + 插件)
> 状态:macOS 双架构已发;Windows 待构建
**宿主**
- 新增插件能力 `ctx.images`:pick / reference / stat / dataUrl / thumb / importPath / importDataUrl
- 新增 `{__file}` 本地文件引用:节点里只存绝对路径,生成时才读盘转 base64(用完即弃,不复制字节);导出画布时自动内联
- Rust `grant_paths`:对话框选中的外部文件/目录运行时授权 fs scope(不外扩 $HOME)
- 任务图:`outKind:'images'` 多图源节点 → 一图一任务(N 个值)/ 批量(每组 ≤12 张分批);`combine` 对多值子源**扇出**(原有单值行为零变化)
- 连线规则:相册按「图片源」参与连接,自身只收提示词/文本类输入
- 导入支持 `keepOriginal`(跳过 1600 长边压缩)
- 修复:生图节点任务容器按「任务 id 集合」重挂载 —— 多图源节点切换模式后任务行不刷新(React 树已更新、DOM 留旧行)
**插件 album v1.0.0**
- 宫格随节点尺寸实时分页(拖大→一页装更多,装得下自动隐藏分页条;缩小→自动多页),格子按剩余宽度微缩放铺满
- 一图一任务 / 批量两种模式;仅本页参与;拖拽排序;点选/取消;S/M/L 密度
- 选择文件/文件夹 = 只引用(不复制);拖入 = 复制进画布存储;「固化」把引用转存
- 缩略图缓存(256px,~20KB/张);失联检测 + 单格重新定位
- 样式全走 design-tokens(过插件主题契约 + 尺度棘轮)
**测试**
- `tests/album-task-graph-test.js`:14 项(一图一任务 / 批量分批 / 组合扇出 / 停用项跳过 / 普通画布零回归)
- mock Tauri 端到端探针:2 个本地路径 → 只引用入库 → 3 个任务 → 生成请求体带 data:base64
**修复过程中发现并修的真 bug**
- `ctx.images` 注入一直失败:`fileRef` 是模块对象,却被 `need()` 当函数校验 ⇒ 抛错被宿主吞掉、能力整体消失(表现为插件退回文件选择器)
## v3.26.65(2026-11-24)生图 API 三处硬伤修复 + 死代码清理
> 状态:代码完成(macOS 双架构待发;Windows 待构建)
**生图 API(三处「配置里有、代码里没用」)**
- `genPath`/`editPath` 真正生效:此前生图与分层都硬编码 `/images/generations`(`editPath` 零调用点),现统一走 `src/generation-endpoint.js` 的 `joinEndpoint()`
- `auth` 可配:`bearer`(缺省,老配置行为不变)/ `header`(如 `x-api-key`)/ `query`(URL 参数)/ `none`;设置 → 生图服务新增「认证」分组
- `fallbacks` 接入生图:主地址失败且「可安全重试」(5xx / 429 / 连接失败)时换备用地址;**超时与 hard-timeout 绝不换地址**(结果未知,防重复计费)
- 地址循环下沉 `runWithAddresses()`;`app.js` 只做装配(棘轮 9105 → **9134**,逐条记账)
**实测(e2e 探针)**
- `genPath:/custom/gen` → 请求 `https://<base>/v1/custom/gen`
- `auth:{type:header,headerName:x-api-key}` → 请求头 `x-api-key` 且无 `Authorization`
- `auth:{type:query,queryName:key}` → URL 追加 `?key=…`
- 主地址连接失败 → 自动打 fallbacks[0]
**死代码与测试可信度**
- 删除 `src/plugin-archive.js`(206 行,插件 zip 安装已由 market 覆盖)与其单测
- 删除 `src/image-preview-derive.js`(449 行,从未接线:`wPreviewUrlOf` 实为恒等函数)与其单测;更正 3 处「已接入」的假记录,重做项进 BACKLOG §1.2
- 删除 `isTransientApiError`(定义后从未调用)
- 新增 e2e 已知红清单 `tests/fixtures/e2e-known-red.json` + `npm run e2e:known-red`(只有**新增**失败才非零退出)
- 新增 `tests/generation-endpoint-test.js`(端点/鉴权四态/重试判据/地址循环 + 防回退负数断言)
## v3.26.64(2026-11-24)修复 8 个 e2e spec 的失效选择器(.iwb-tab-home)
> 状态:代码完成(macOS 双架构待发;Windows 待构建)
**问题**:标签条里的「首页」房子按钮在 **v3.25.62 已删除**(入口只剩一级导航),但有 **8 个 spec + 2 个探针 + 1 个视觉钉点**仍按 `.iwb-tab-home` 写 —— 这些用例长期在测一个不存在的元素,等于全红,却没人发现。
**修复**
- `tests/_helpers/wait.js` 新增唯一入口:`goHome(page)` / `expectHomeActive(page)` / `HOME_NAV`(选择器只写一处)
- 8 个 spec 改用它:`iwb-tabs-release`(4 处) / `iwb-tab-dot`(2) / `iwb-close-flush` / `iwb-duplicate-ws` / `iwb-home-release` / `iwb-image-memory-parity` / `iwb-memory-history` / `clipboard-audit`(2,含「把鼠标停在画布外」用的中心点)
- 「回首页后首页标签 active」的断言改为「一级导航「首页」带 `on`」(`expectHomeActive`)
- 删掉 3 条无生产者的死 CSS:`.iwb-tab-home` / `.iwb-tab-home.iwb-tab-active` / `.iwb-tab-home .iwb-ic`
- 视觉回归钉点从「首页标签无选中底色」改为「一级导航激活项是墨色底」(语义不变,`background: var(--iwb-text)`)
- `_perf-baseline` / `_probe-tab-switch` / `iwb-canvas-ops` 里「排除 `.iwb-tab-home`」的过滤条件一并删除(已无意义)
- `iwb-stability.spec.js` 默认 baseURL 从**线上站**改为本地 `127.0.0.1:8787`(它此前默认打生产,本地改动根本测不到;也和其它 spec 不一致)
**验证**
- `iwb-tabs-release`(3) + `iwb-tab-dot` + `iwb-duplicate-ws` + `iwb-home-release` = **6 passed**
- `iwb-stability` 的「新建并切换工作台后刷新仍保留」修好后通过(其余 5 条是该 spec 自身的资源中心/拖拽用例,与本次无关)
- `iwb-close-flush` 3 条仍红,但已用 `git stash` 在**改动前**复跑同样失败 → 与本次修复无关
- `verify:ci` 全绿
## v3.26.63(2026-11-24)规则统一 P0:确认入口 / 剪贴板门面 / 文档硬数字守卫
> 状态:代码完成(macOS 双架构待发;Windows 待构建)
**① 确认入口收成 1 份**
- 同一个 5 行 `askConfirm`/`wConfirm` 包装此前复制 **7 份**(app.js + 6 个 src),两种写法;现全部删除,统一调 `IWBUIConfirm.askOrNative`(`src/ui-confirm.js` 唯一实现)
- `window.confirm` 现在只存在于 `src/ui-confirm.js`(网页端行为不变:非 Tauri 仍走原生)
- `src/ui-backup-modal.js` 里「是否有原生 confirm」的判断改为判断门面是否存在
**② 文档硬数字纳入自动校验**
- 新增 `scripts/ratchet-metrics.js`:唯一测量实现(app.js 行数 / Workbench 行数 / src 模块数与行数 / 占比)+ 文档改写规则
- `scripts/sync-facts.js` 新增一步:自动改写 `CONTRIBUTING.md` 与 `docs/standards/architecture-current-state.md` 里的 4 类数字
- `tests/architecture-facts-guard-test.js` 新增 6b:文档数字与代码不一致即红
- **首次运行就修正了 6 处长期漂移**:CONTRIBUTING 的 `MAX_APP_JS_LINES` 写 8,700(真实 9,115,差 415 行)、架构文档 6 项(9,112 行 / 29.9% / Workbench 3,045 / 上限 3,046 / src 21,334 行等)
**③ 剪贴板统一走门面**
- 5 处绕过 `IWBClipboardCopy` 的直连改走门面:诊断页复制、设置页「复制诊断」(原先自带一份 textarea 兜底 = 真重复)、节点 Markdown 编辑器复制、插件 copy 能力、结果图复制链接
- `navigator.clipboard.writeText` 现在只存在于门面自身
**棘轮**:`MAX_APP_JS_LINES` 9115 → **9,105**(实测 9,104,删掉的 8 行不留给下次随便涨)
## v3.26.62(2026-11-24)设计 token 收口:补类别 + L3 进单一源 + 三方一致性守卫
> 状态:代码完成(macOS 双架构已发;Windows 待构建)
+3 -3
View File
@@ -40,7 +40,7 @@ build esbuild 打包到 dist/(单 dist/app.js = src/ 模块按序
node --check app.js 与 dist/app.js 语法
check-dist.js 产物体检
lint ESLint(src/ + app.js,正确性规则)
test:unit 126 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
test:unit 128 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
test relay-task-graph-fixture + iwb-v32-web-test
test:facts 事实基线守门(见 §5)
typecheck 渐进类型检查(tsc --noEmit;范围 = src/*.js,不含 app.js)
@@ -102,8 +102,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` | **8,700**(另守「占总源码 ≤ 40%」,见 `MAX_APP_JS_SHARE`) |
| `Workbench()` 行数 | 同上 `MAX_WORKBENCH_LINES` | **3,997** |
| `app.js` 总行数 | `tests/source-text-ratchet-test.js` `MAX_APP_JS_LINES` | **9,173**(另守「占总源码 ≤ 40%」,见 `MAX_APP_JS_SHARE`) |
| `Workbench()` 行数 | 同上 `MAX_WORKBENCH_LINES` | **3,046** |
| 单组件行数(不含 Workbench)| 同上 `MAX_APP_COMPONENT_LINES` | **423** |
三条都是**只减不增**。确需在 app.js 增长时,必须**同步上调上限并在 commit 里写理由**(等于显式记账,不会悄悄发生)。
+107 -47
View File
@@ -19,6 +19,15 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
// 生成结果精简/合并模块(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__ ⇒ 所有分支都走原逻辑,行为零变化。
@@ -125,12 +134,6 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
}
// 把桌面端能力登记到 src/desktop-bridge.js(src 不得反向引用 app.js 的 window 全局,
// architecture-boundary-guard 会红;这里只做注入,设置面板/导出逻辑统一走 IWBDesktop)
// 桌面端统一确认入口:页内确认(window.confirm 会阻塞 WKWebView 主线程);网页端保持原生
function wConfirm (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)))
}
// 桌面壳适配(外链 / 原生通知 / 链接拦截)落在 src/ui-desktop-shell.js
try { if (window.IWBUIShell) window.IWBUIShell.installLinkGuard(wIsTauri) } catch (e) { /* ignore */ }
@@ -530,6 +533,7 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
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,
}
}
// 磁盘上的**原样**配置对象(未归一化)。用途只有一个:让"未知字段"在写入时不被吃掉。
@@ -638,6 +642,7 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
},
},
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),
@@ -888,9 +893,11 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
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)
@@ -913,7 +920,7 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
wImgUrlPending.add(key)
const job = wIsBlobRef(v)
? (wImageBlobStore() ? wImageBlobStore().getBlob(v.__blob) : Promise.resolve(null))
: iwbCacheBlob(v.__cache)
: (wIsFileRef(v) ? (wFileRefMod() || {}).readBlob(v.__file) : iwbCacheBlob(v.__cache))
// 解析 Promise 存进 wImgUrlPendingPromise ⇒ 供 wResolveImgAsync 等待(预览类操作需要 URL 字符串)
const p = Promise.resolve(job).then((blob) => {
wImgUrlPending.delete(key)
@@ -985,6 +992,8 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
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 ''
}
// 生成参考图参数:在**发请求前**解析成真实字节(本地文件名原样透传,不含字节)
@@ -1008,14 +1017,22 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
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 就用;否则异步解析一次,__cache 首帧先挂 SW 虚拟路径
if (wIsBlobRef(v) || wIsCacheRef(v)) {
// 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)
@@ -1303,8 +1320,28 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
? { 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 baseUrl = (_wCfgShape && _wCfgShape.normalizeEndpointBase) ? _wCfgShape.normalizeEndpointBase(provider.baseUrl) : String(provider.baseUrl || '').trim()
return { provider, key, baseUrl, genPath: provider.genPath || '/images/generations', editPath: provider.editPath || '/images/edits' }
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 || '请求失败')
@@ -1370,8 +1407,11 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
return e ? (typeof e === 'string' ? e : JSON.stringify(e).slice(0, 200)) : 'HTTP 请求失败'
}
async function wGenerate(args) {
const { key, baseUrl, provider } = wResolveKey(args.providerId, args.keyGroupId)
const headers = { Authorization: 'Bearer ' + key.value }
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()
@@ -1431,7 +1471,10 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
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 {
const post = (body) => wFetch(baseUrl + '/images/generations', { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: localCtrl ? localCtrl.signal : (args && args.signal), softTimeout: !!(args && args.softTimeout), onSoftTimeout: args && args.onSoftTimeout }, GEN_TIMEOUT_MS)
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')
@@ -1475,6 +1518,10 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
}
} 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')
@@ -1520,8 +1567,9 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
return m || fallback || '分层请求失败'
}
async function wDecomposeLayers(args) {
const { key, baseUrl } = wResolveKey(args.providerId, args.keyGroupId)
const headers = { Authorization: 'Bearer ' + key.value }
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')
@@ -1548,7 +1596,8 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
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 {
const postLayer = (body) => wFetch(baseUrl + '/images/generations', { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: localCtrl ? localCtrl.signal : (args && args.signal), softTimeout: !!(args && args.softTimeout), onSoftTimeout: args && args.onSoftTimeout }, GEN_TIMEOUT_MS)
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')
@@ -3324,6 +3373,9 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
// 分层(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]) || {}) }
@@ -3406,6 +3458,8 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
// 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"/>',
@@ -3622,9 +3676,6 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
return { cls: 'other', tag: '其他' }
}
function isTransientApiError(e) {
return ['limit', 'server', 'network', 'timeout'].includes(e && e.iwbType)
}
function apiErrorMessage(e) {
return String((e && e.message) || e || '生成失败')
}
@@ -4167,6 +4218,8 @@ try { if (window.IWBMiniMapFit && typeof window.IWBMiniMapFit.install === 'funct
})
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
@@ -4777,7 +4830,7 @@ const tbCenterSeed = (type, refs) => {
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); else { try { navigator.clipboard.writeText(t) } 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'),
),
@@ -5736,7 +5789,8 @@ const tbCenterSeed = (type, refs) => {
// 桌面端不做自动快照(数据已经落盘在资料目录);网页版保持原行为
const autoBackupKit = IWWorkbenchHooks.useAutoBackup(wFileStoreOn() ? 0 : 30000)
const [settingOpen, setSettingOpen] = useState(false)
const [settingTabReq, setSettingTabReq] = useState('gen') // v3.87.26:外部点击"内存"时直接打开诊断页
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 秒内存采样持续刷新。
@@ -5990,7 +6044,7 @@ const tbCenterSeed = (type, refs) => {
const sess = sessionsStore.get(wsId)
const nm = (((refs.workspaces || workspaces).find((w) => w.id === wsId)) || {}).name || '未命名画布'
if (sess && sess.dirty) { // S13:有未保存修改 → 确认后先保存再关
if (!(await wConfirm('「' + nm + '」有未保存修改,关闭前将先保存。确定关闭?', { title: '关闭画布', okText: '关闭并保存' }))) return
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
@@ -7637,8 +7691,8 @@ const tbCenterSeed = (type, refs) => {
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 wConfirm('将转换当前画布中的 ' + targets.length + ' 张本地图片(输出节点生成结果不会处理),继续吗?', { title: '批量转在线链接' }))) return
if (!(await wConfirm('确认开始批量上传吗?上传后这些图片会替换为在线链接,通常无法自动撤回。', { title: '确认上传', okText: '开始上传' }))) 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 {
@@ -8187,7 +8241,7 @@ const tbCenterSeed = (type, refs) => {
edges,
memUi,
setSettingTabReq,
setSettingOpen,
setSettingOpen: openSettings,
saveState,
saveText,
memMb,
@@ -8204,10 +8258,12 @@ const tbCenterSeed = (type, refs) => {
setWsMorePos,
setWsMoreOpen,
})
: (shellView === 'plugins' ? null : el(ProductNav, { shellView, setShellView, setSettingOpen, setHelpOpen, toggleTheme, theme }))
: (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
@@ -8255,11 +8311,10 @@ const tbCenterSeed = (type, refs) => {
},
}, cover, name),
copy: (text) => {
try {
const p = navigator.clipboard && navigator.clipboard.writeText(String(text || ''))
if (p && typeof p.then === 'function') return p.then(() => ({ ok: true })).catch(() => ({ ok: false, error: '浏览器拒绝了剪贴板写入(需窗口有焦点)' }))
return { ok: false, error: '剪贴板不可用' }
} catch (e) { return { ok: false, error: '剪贴板不可用' } }
// 统一走 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。
@@ -8357,8 +8412,8 @@ const tbCenterSeed = (type, refs) => {
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 wConfirm('确定清空回收站?将彻底删除回收站中的全部画布。', { title: '清空回收站', okText: '清空' }))) return; emptyTrash() } }, I('trash'), '清空回收站') : null,
homeSelectedWs.length ? el('button', { className: 'iwb-btn', onClick: async () => { if (!(await wConfirm(homeView === 'trash' ? '确定彻底删除选中的画布?此操作不可恢复。' : '确定删除选中的画布?(移入回收站)', { title: '删除画布', okText: '删除' }))) return; homeSelectedWs.forEach((id) => (homeView === 'trash' ? purgeWs(id) : trashWs(id))); setHomeSelectedWs([]) } }, I('trash'), '删除选中') : null,
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'), '导入画布'),
@@ -8382,7 +8437,7 @@ const tbCenterSeed = (type, refs) => {
homeView === 'trash'
? [
el('button', { title: '恢复画布', onClick: (e) => { e.stopPropagation(); restoreWs(w.id) } }, I('refresh')),
el('button', { title: '彻底删除', onClick: async (e) => { e.stopPropagation(); if (!(await wConfirm('确定彻底删除画布「' + (w.name || '未命名画布') + '」?此操作不可恢复。', { title: '彻底删除', okText: '删除' }))) return; purgeWs(w.id) } }, I('trash')),
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')),
@@ -8416,7 +8471,7 @@ const tbCenterSeed = (type, refs) => {
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); setSettingOpen(true) } }, I('settings'), el('span', null, '设置')),
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),
),
@@ -8433,15 +8488,8 @@ const tbCenterSeed = (type, refs) => {
onHelp: () => { setHelpMode('help'); setHelpOpen(true) },
onHotkeys: () => { setHelpMode('keys'); setHelpOpen(true) },
onSkin: () => { try { toggleTheme() } catch (e) { /* ignore */ } },
onSettings: () => setSettingOpen(true),
onMore: (ev) => {
try {
const r = ev.currentTarget.getBoundingClientRect()
const M = 210
setWsMorePos({ top: Math.min(r.top, (window.innerHeight || 800) - 320), left: Math.min(r.right + 6, (window.innerWidth || 1000) - M - 6) })
} catch (e) { /* ignore */ }
setWsMoreOpen((v) => !v)
},
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):主组「插件」图标进入;返回回到画布
@@ -8585,7 +8633,7 @@ const tbCenterSeed = (type, refs) => {
groupEls,
nodeEls,
),
el(ToolbarBottomMemo, { onAdd: tbOnAdd, onOpenPrompts: tbOnOpenPrompts, onFitView: tbOnFitView, onZoom: tbOnZoom, tool, onTool: tbOnTool }),
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 }, '重试保存'),
@@ -8596,7 +8644,7 @@ const tbCenterSeed = (type, refs) => {
) : 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: () => { setSettingTabReq('backup'); setSettingOpen(true); exportRemind.dismiss() } }, '去导出'),
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' },
@@ -8899,6 +8947,18 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
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),
})(ctx)
},
files: (ctx) => {
const F = (typeof window !== 'undefined' && window.IWBStorageFile) ? window.IWBStorageFile.pluginFiles : null
const need = () => { if (!F) throw new Error('文件能力未就绪(资料目录尚未初始化)'); return F }
+113
View File
@@ -0,0 +1,113 @@
# 全局缺陷审计 · 2026-11-24(`v3.26.64`)
> 上一份:[code-health 2026-11-10](./2026-11-10-code-health.md)。
> 本份是**面向行动**的缺陷清单(不是评分报告):每一条都带可复核证据 + 建议动作 + 验收方式。
> 本地图片与生图 API 的专项分析见 [2026-11-24-local-images-and-api-gaps.md](./2026-11-24-local-images-and-api-gaps.md)。
## 0. 规模与门禁(现状快照)
| 项 | 数值 |
|---|---|
| `app.js` | 9,104 行(单 IIFE 装配层),上限 9,105 |
| └ `Workbench()` | 3,045 行,上限 3,046 |
| `src/` | 109 模块 / 21,181 行 |
| `style.css` | 2,422 行(单文件) |
| `dist/app.js` | 829,591 B |
| 单测(`-test.js`) | 126 个,全部进门禁 |
| e2e(`.spec.js`) | 57 个,52 个进门禁(PR 才跑) |
| 门禁链 | `verify:ci` = build → check-dist → tokens:check → lint:tokens → eslint → test:unit → test → test:facts |
**已经做得好的(不要再提)**:token 三层体系 + 三方一致性守卫、单测孤儿门禁、三条行数棘轮、
插件市场 sha256 全量校验、备份密钥 `__KEEP__` 脱敏、e2e 只挂 PR(省 CI 额度)、文档数字自动同步。
## 1. 死代码与"假绿"(**已在 v3.26.65 处置**)
| # | 问题 | 证据 | 建议 |
|---|---|---|---|
| 1 | `src/plugin-archive.js` **206 行零生产消费**,但有 `tests/plugin-archive-test.js` 绿着 | 全仓无 `IWBPluginArchive` 调用点 | 要么接线(插件包导入导出),要么删模块 + 删测试;**保留"测试绿"最糟** |
| 2 | `src/image-preview-derive.js` **449 行零生产消费**,同样有测试 | 只有自身导出与测试引用 | 同上:确认是规划中功能就加 `// 未接线` 头注释并在 BACKLOG 记账 |
| 3 | `isTransientApiError` 定义后从未调用 | `app.js:3619`(全仓仅此一处) | 做生图重试时激活它,或删除 |
| 4 | `deadTokens` 32 个(定义了没人用的 CSS 变量) | `tests/fixtures/token-baseline.json` | 清理一轮,顺带把基线降到 0 |
> 共性风险:**测试覆盖了死代码 ⇒ 覆盖率虚高**。建议在门禁里加一条"零消费模块清单",新增即红。
**处置结果(v3.26.65)**:
- `src/plugin-archive.js`(206 行)+ 测试 → **删除**(插件 zip 安装已由 `src/runtime-plugin-market.js` 覆盖)
- `src/image-preview-derive.js`(449 行)+ 测试 → **删除**;同时更正 `engineering-rulebook §13.34.6`、
`project-engineering-standards §11.2`、`archive/plans/opentu-parity-image-memory` 里「已接入」的假记录,
重做项登记到 `BACKLOG §1.2`(含难点:`wPreviewUrlOf` 是同步恒等函数,接线需异步化)
- `isTransientApiError` → **删除**(做生图重试时再加回来)
- `deadTokens 32` → **实测后判定不删**:`--iwb-plugin-*` 13 个是插件主题契约、`--fs-*`/`--sp-*`/`--rd-*`/`--tr-*` 是 legacy 别名,
`--iwb-surface`(ai-chat)、`--fs-xs`(style-source)被外仓插件引用;判死口径已写入 `BACKLOG §1.3`
- 已知红清单也一并落地:`tests/fixtures/e2e-known-red.json` + `npm run e2e:known-red`(新增红才非零退出)
## 2. 错误可见性
| # | 问题 | 证据 | 建议 |
|---|---|---|---|
| 5 | **358 处** `catch { /* ignore */ }` | `grep` 全仓统计 | 其中 `storage/outputs/plugin` 关键路径已有 `IWBMetricsSwallow`;把**剩下没有留痕的**分批接入(至少记面包屑) |
| 6 | **17 种** `__IWB_E2E_*` 探针留在生产代码 | `app.js`、`src/*.js` | 已有"生产态不暴露探针"的 e2e 断言;建议统一挂到单一命名空间 + 构建期可选剥离 |
## 3. 测试可信度
| # | 问题 | 证据 | 建议 |
|---|---|---|---|
| 7 | e2e **长期有红**:`iwb-close-flush` 3 条(改动前就红)、`iwb-stability` 5 条(资源中心/拖拽)、`clipboard-audit` 8 条(无头剪贴板权限) | 本轮实测:改动前后失败集合相同 | 给"已知红"建清单并挂 issue 标签;否则门禁信号会被噪声淹没 |
| 8 | **LLM 功能 0 单测、未跑通**(用户确认) | `tests` 无 llm 用例;`wLlm`(`app.js:1637`) | 要么明确标"实验功能"并从 UI 降级,要么补一条最小连通性测试 |
| 9 | 单测以**源码文本钉点**为主(493 处 / 20 文件),重构先红 | `tests/source-text-ratchet-test.js` | 已在做"钉点减法";建议每个新功能**只加行为测试**,不再加文本钉点 |
## 4. 结构与可维护性
| # | 问题 | 证据 | 建议 |
|---|---|---|---|
| 10 | `app.js` 9,104 行 + `Workbench()` 3,045 行,棘轮只防涨 | `tests/source-text-ratchet-test.js` | 每版至少搬走一块(本轮已从 9,112 → 9,104 并把上限收紧到 9,105) |
| 11 | `src/storage-file.js` 1,349 行、`src/runtime-workbench-logic.js` 2,280 行承担多职责 | 行数统计 | 按域拆分(存储:目录/迁移/插件文件/图库索引) |
| 12 | `style.css` 2,422 行单文件 | 行数统计 | 只定规则不动手:新样式写 `src/ui-*.css` 按域拆 |
## 5. 配置与安全
| # | 问题 | 证据 | 建议 |
|---|---|---|---|
| 13 | `PRIVATE_TOOLS_TOKEN = 'malongan'` **硬编码个人暗号**在源码 | `app.js:414` | 隐藏功能可以,但暗号不该是可读个人标识;改成构建期注入或环境变量 |
| 14 | 密钥明文存 `localStorage` | `app.js:548` 脱敏只覆盖导出/展示 | 桌面端可考虑钥匙串(`keytar`/`security`),至少提供"不落盘"选项 |
| 15 | 插件无沙箱(可信代码模型) | `docs/standards/architecture-current-state.md:255` | 设计如此,保持;但市场安装应显示权限清单(当前只有 capabilities 声明,没有用户可读解释) |
## 6. 发布与工程流程
| # | 问题 | 证据 | 建议 |
|---|---|---|---|
| 16 | **Windows 发布需 3 步人肉**:Windows 机构建 → 拷 NAS `_inbox` → 签名 → 再合并 `latest.json` | `scripts/publish-windows-update.sh`、`docs/WIN_BUILD_SPEC.md` | 见下方"流程优化建议" |
| 17 | 插件市场更新靠手工 `sync-plugins-from-repo` + `gen-market` + scp | `scripts/` | 加一条 `npm run release:plugins` 串起来(一条命令) |
| 18 | `publish-update.sh` 里 dmg 路径硬编码 `src-tauri/target/...` | 脚本正文 | 抽 `ARTIFACT_PATHS` 常量,便于换构建目标 |
### 流程优化建议(Windows)
现状是"人肉把 exe 传到 NAS"。可按代价从低到高分三档:
1. **低**:Windows 机构建完直接 `scp` 到 NAS(省掉手动拖拽),我这边仍负责签名合并
2. **中**:NAS 上跑一个小 watcher(inotify + 脚本),发现 `_inbox` 新 exe 自动签名 + 合并 + 通知
3. **高**:Windows 机接 CI(GitHub Actions Windows runner + 自托管签名密钥)
## 7. 产品功能缺口(与用户目标相关)
| # | 问题 | 详见 |
|---|---|---|
| 19 | 本地图片:导入即压缩丢原图、无文件选择/文件夹、进不了图库、无访达打开、无批量处理、清理不可见 | 专项文档 §2 |
| 20 | 生图 API:`genPath/editPath` 死设置、认证固定 Bearer、`fallbacks` 不生效、无重试/key 轮换/限流、插件 provider 选不到 | 专项文档 §3 |
## 8. 建议的优先级(按"投入产出比")
| 级别 | 事项 | 工作量 |
|---|---|---|
| **P0** | 死代码处置(plugin-archive / image-preview-derive / isTransientApiError) | 0.5 天 |
| **P0** | 生图 API 三处硬伤(genPath 生效、auth 可配、fallbacks 接入) | 1~1.5 天 |
| **P1** | 本地图片批 1(原生选择器 + 拖文件夹 + 访达打开 + 节点元信息) | 1~1.5 天 |
| **P1** | 插件配置 API(`config.read/patch` + 插件 provider 进下拉) | 1.5 天 |
| **P2** | 本地图片批 2(保留原图 + 本地图进图库 + 占用面板) | 2~3 天 |
| **P2** | 生图重试/key 轮换/per-provider 限流 | 1.5 天 |
| **P3** | 样式域拆分、Windows 发布自动化、错误留痕补全 | 各 1~2 天 |
## 9. 验收方式(每条都应有机械证据)
- 死代码:`grep` 零消费 + 删除后 `verify:ci` 绿
- API 缺陷:新增单测覆盖 `genPath`/`auth`/`fallbacks` 三条分支
- 本地图片:e2e 一条"选 3 张 + 拖 1 个文件夹 → 画布 4 个节点且原文件名保留"
- 插件配置:`tests/_plugin-host-probe.spec.js` 增加 `config.read` 用例
@@ -0,0 +1,91 @@
# 本地图片链路 & 生图 API 缺口分析 · 2026-11-24(`v3.26.64`)
> 本文记录「本地图片交互 / 本地图片文件处理 / 生图 API 配置」三块的现状与缺口。
> 结论先行:**导入链路做得很扎实,但"原图不留、进不了图库、没有文件选择器"三个结构性缺口,
> 使它还不能当本地图片工作台用;生图 API 有三处"设置了不生效"的硬伤。**
## 1. 本地图片的现状(链路与证据)
统一入口:`wImportImage`(`app.js:4122`),拖放、粘贴、节点替换全部走它。
| 环节 | 现状 | 证据 |
|---|---|---|
| 准入 | 三态:`image` / `blocked`(HEIC/TIFF/PSD/RAW 拒收并给转法)/ `other` | `src/image-admit.js:46` |
| 压缩 | **强制**压到显示尺寸:长边 ≤ `IMPORT_MAX_EDGE`=**1600**、quality 0.85;"最宽松档"自动收紧到 maxMB 1.5 | `app.js:4052`、`app.js:4091`、`app.js:4181` |
| 特殊格式 | GIF 不重采样(保动画);SVG 先光栅化成 PNG 再进同一管线 | `app.js:4164`、`app.js:4157` |
| 落地 | >3000 字符 → 引用化 `wImgRefWrite`(内容哈希 key);小图内联 base64 | `app.js:4134` |
| 去重 | 内容哈希(FNV-1a over dataURL),同图连粘两次只建一个节点 | `src/image-dedupe.js` |
| 磁盘 | `<资料目录>/images/{canvas,gallery,thumbs,legacy}/<sha256前16>.<ext>` | `src/storage-file.js` |
| 兜底 | 压缩超时 12s / 无解码器 → 按原字节导入 + **可见提示**(不静默) | `app.js:4093`、`app.js:4168` |
## 2. 本地图片的 10 个缺口
按"对本地图片工作流的影响"排序:
| # | 缺口 | 证据 | 影响 |
|---|---|---|---|
| 1 | **导入即重编码,原图分辨率被丢弃**(永远 ≤1600 长边,无"保留原图"开关、无原图副本) | `app.js:4091` | 4K 参考图 / 局部重绘 / 细节迁移在最开始就损质 |
| 2 | **没有文件选择器、没有文件夹导入**(入口只有拖放/粘贴;`input[type=file]` 只用于 JSON/备份;无 `webkitGetAsEntry`) | `app.js:8357`、`src/runtime-workbench-logic.js:1045` | 不能批量选图;拖整个文件夹无效 |
| 3 | **本地图片进不了图库**(图库=生成结果仓库 `outputs`+`out_orig_`) | `app.js:1843`、`iwb-plugins-desktop/gallery` 无导入入口 | 不能统一浏览/搜索/批量导出/删除 |
| 4 | **无"在访达中显示 / 用系统程序打开"**(`localName` 导入时多为 null;`open_data_subpath` 已存在但没接到节点) | `app.js:3310`、`src-tauri/src/lib.rs:241` | 想用外部编辑器处理源文件要手动找 |
| 5 | **无批量处理**(转格式/缩放/压缩/重命名/导出原图) | 无对应实现 | 只能靠插件单张处理 |
| 6 | **清理与占用不可见**(trash 30 天自动删、`gcImages` 要手动跑;无占用面板,回收站图片不可恢复) | `src/storage-file.js:919`、`src/storage-file.js:1230` | 磁盘涨了不知道为什么,删错了找不回 |
| 7 | **无文件夹监听**(往目录丢图自动进画布) | 无对应实现 | 常见本地工作流缺失 |
| 8 | **EXIF 与元数据全丢**(导入即 canvas 重编码;导出不写回) | `src/image-compress.js` | 方向/拍摄时间/相机信息损失 |
| 9 | **节点不含图片元信息**(只有 `name`/`localName`/`srcUrl`,无原始文件名/尺寸/字节/来源路径) | `app.js:3310` | 无法按来源/尺寸筛选、无法重定位源文件 |
| 10 | **大文件无硬上限**(只有压缩阈值;>12s 超时或解码失败则原图直入) | `app.js:4168` | 100MB 文件先 base64 膨胀 33% 进内存 |
## 3. 生图 API 的缺陷(排除 LLM)
> **2026-11-24 更新(v3.26.65)**:#1 `genPath/editPath` 生效、#2 `auth` 可配(bearer/header/query/none)、
> #3 `fallbacks` 接入生图(含"结果未知不重试"判据),三条已修并实测通过(见本节末尾「已修证据」)。
| # | 缺陷 | 证据 | 后果 |
|---|---|---|---|
| 1 | `genPath`/`editPath` **是死设置** | UI 有输入框(`src/ui-settings-sections.js:1152`),但生图/分层都硬编码 `/images/generations`(`app.js:1428`、`app.js:1545`),`editPath` 零调用点 | 非标准路径的网关接不了 |
| 2 | **认证固定 Bearer**,无自定义 header/query;归一化白名单也不保留 `headers` | `app.js:1368/1518/1658/1694/1728`;`src/storage-config-shape.js:59` | 需要 `x-api-key`/`api-key` 的中转站接不了 |
| 3 | **`fallbacks` 对生图无效**(LLM 有地址轮询,生图没有) | `app.js:1650` 起(LLM)vs `app.js:1428`(生图) | 主地址挂了整条链路挂 |
| 4 | **无自动重试** | `isTransientApiError`(`app.js:3619`)定义后从未调用 | 429/5xx/网络抖动全要手点 |
| 5 | **无 key 轮换 / 冷却** | `wResolveKey`(`app.js:1290`)只取第一个或指定分组 | 多 key 不能分摊;401 不会换 key |
| 6 | **无 provider 级并发 / 超时** | 全局并发 4(`app.js:399`)、全局 240s 软 / 25min 硬 | 慢 provider 拖住全队列;限流渠道被打爆 |
| 7 | 插件 provider **注册了但选不到** | 下拉只读 `cfg.providers`(`app.js:4588`、`app.js:4602`);`wPluginProviders` 仅在按 id 解析时用(`app.js:1293`) | 插件扩展服务商等于白做 |
| 8 | 插件**读不到** provider/model 配置 | 无只读配置能力(`settings` 是插件私有存储) | "模型看板/一键换模型"必须先让用户重填 |
| 9 | 无"测试连接"(只有地址 ping,不验 key/model) | `api('ping')` → `wPing`(`app.js:1735`) | 配错只能在生图时暴露 |
| 10 | 响应解析写死 `data[0].url` | `app.js:1452` | 非标返回只能靠 custom 模板硬凑 |
**已修证据(v3.26.65,e2e 探针实测)**:
- 自定义路径:配置 `genPath:/custom/gen` ⇒ 请求 URL 为 `https://<base>/v1/custom/gen`
- 自定义鉴权:`auth:{type:"header",headerName:"x-api-key"}` ⇒ 请求头 `x-api-key: sk-…` 且无 `Authorization`;
`auth:{type:"query",queryName:"key"}` ⇒ URL 追加 `?key=…`
- 备用地址:主地址连接失败 ⇒ 自动打 fallbacks[0](`bad.test` → `fake.test` 实测)
- 单测:`tests/generation-endpoint-test.js`(端点拼接 / 鉴权四态 / 重试判据 / 地址循环 + 接线负数断言)
## 4. 建议(按目标排序)
### 批 1 本地图片「进得来、看得见」
1. 原生选择器 `dialog.open({ multiple: true, filters })`(Tauri 已装 `tauri-plugin-dialog`)
2. 拖文件夹导入(`webkitGetAsEntry` 递归 / Tauri 拖放路径)
3. "在访达中显示 / 用默认程序打开"(复用 `open_data_subpath`)
4. 节点补元信息:`origName / origW×origH / bytes / sourcePath / importedAt`
### 批 2 本地图片「管得住」
5. 本地图进图库:`outputs` 索引加 `source:'local'`
6. **保留原图**开关:`imageTransfer.importMode: 'display'|'keep'`,keep 时原图进 `images/orig/`
7. 存储占用面板 + trash 可恢复
8. 批量:转格式 / 缩放 / 压缩 / 导出原图
### 批 3 生图 API 修缺陷
9. `genPath/editPath` 生效 + `auth` 可配(bearer/header/query/none)+ 保留 `headers`
10. `fallbacks` 接入生图 + 按错误分类切换(复刻 LLM 那套)
11. `retry` / `keyPolicy` / `limits` 成为 provider 字段并在设置里可见
12. 插件:`config.read()`、`config.patchProvider()`、插件 provider 进下拉、`images.import/export`
### 批 4(可选)
13. 文件夹监听自动导入
14. EXIF 读取与可选保留
## 5. 不做的事(明确边界)
- 不做云端图床自动托管本地原图(隐私)
- 不引入 i18n(单语言产品)
- 不把压缩改成"永不压缩"(内存教训见 `app.js:4067` 注释:4K 原图直入曾导致 GB 级堆尖峰)
@@ -79,7 +79,7 @@
| **E 复制/快照去 JSON 深拷贝** | ✅ 已上线 | v3.87.45(`86d0076`) |
| **C1 跨域缩略图 + 负缓存** | ✅ 已上线 | v3.87.46(`67e91c1`) |
| 小步:ref 图 lazy/async + 预览传原图 | ✅ 已上线 | v3.87.47(`42c34f9`) |
| **W2-A 预览产物模块**(解码即缩放) | ✅ 已接入构建 | `image-preview-derive.js` 32/32 单测,`1fab0c0` |
| **W2-A 预览产物模块**(解码即缩放) | ⚠️ **实际未接线**(2026-11-24 复核:`wPreviewUrlOf` 是恒等函数,模块零消费)→ 模块与单测已于 v3.26.65 删除 | 重做见 BACKLOG「预览产物按需解码」 |
| W2-B e2e 契约 | 🔄 子 agent 进行中 | — |
| **C6 参考图节点走显示缩略图** | ✅ 已上线 | v3.87.51(`549f3b0`) |
| **C5 objectURL 生命周期收口** | ✅ 已上线 | v3.87.52(`63be3da`) |
@@ -211,7 +211,7 @@ function wPreviewUrlOf(v) {
## 12. 验收状态(Round 24 更新)
**实现层:全部完成并在生产取证** ✓(线上 `v3.87.58+584a3ce`,三地址一致)
- 生产产物核验:`wPreviewUrlOf`×5(1 定义 + 4 接入)· `src/image-preview-derive.js` HTTP 200 且 `resizeWidth/resizeQuality/close` 就位 · `wAwaitCacheWrites`/`wMigrateIdbRef`/`imgblob_`/`wResolveRefArgs`/`wResolveImagesForExport`/`wRegisterBlobUrl` 全部在产物中 · 探针与深拷贝残留 **0**
- 生产产物核验:`wPreviewUrlOf`×5(1 定义 + 4 接入,**均为恒等透传**)· ~~`src/image-preview-derive.js`~~ 已于 v3.26.65 删除(从未被调用) · `wAwaitCacheWrites`/`wMigrateIdbRef`/`imgblob_`/`wResolveRefArgs`/`wResolveImagesForExport`/`wRegisterBlobUrl` 全部在产物中 · 探针与深拷贝残留 **0**
- 门禁:单测 **617 / 0 新增失败 / 5 已知** + e2e **81 passed** + `verify:release` 三地址一致
**Round 26/27 追加修复(均已在线上 `v3.87.62+86ae725`)**
+5 -5
View File
@@ -1,7 +1,7 @@
# 现状架构与性能事实基线(桌面版)
> **本文档是什么**:现状**事实快照**,不是规范。用途:任何性能 / 内存 / 存储相关改动,先对齐这里的现实,避免把已经调好的东西改坏。
> 日期 **2026-10-20**(**2026-11-16 复算 · v3.24.85**)| 基线(**最近一次 bump 版本的提交**,不是主干 HEAD)`main = 433b62a`(线上 `v3.26.62+433b62a` —— 2026-11-24 **图库:出图即入图库 + 插入落本地副本(能标注)**:每张生成完成即归档并通知插件(此前只在整轮结束写一次 ⇒ 生成中图库一直空)、插入取源改本地字节优先并引用化(抓不到才留原链接 + 提示)、`getNodeImage` 补 `data.localRef` 候选(远程缓存命中却仍判「不支持标注」的直接成因)、批量插入改 4 列栅格(旧实现同批全叠一处),逻辑落 `src/gallery-sync.js`,app.js 只装配;上一条 `v3.26.60+cf0e9a0` —— **浮层字号上调一档**:「模型设置」「图像设置」选择项 11→13px、高 22→28、左右内距 6→10、间距 4→6、标题 12→14、面板 328→360,改动全落在 `.iwb-pop` 的 6 个 token(两面板共用一套);上一条 `v3.26.59+e966b34` —— 备份新增 `plugin-files/` 通道,提示词封面换机不再丢;再上一条 2026-11-23 **节点正文文本区修复**:提示词/文本节点正文透明继承卡片底色(白卡片消失)、编辑态三层框(控件 border / 聚焦光晕 / D8 焦点环)全去掉,规范补表面角色三分法与 `node-scope-test` 第 5 条守卫,8 张基线重录;上一条 `v3.26.51+21554b0` —— **M6 延展验证**:插件面板两段六次叠加样式合并重写、133 行新增零裸值;补 `--iwb-font-base`(14px) 第 8 档与亮色状态色调深(对浅页面 2.13 → ≥4.6),对比度守卫 114→138 对;新增 ⑦⑧ 组件夹具基线共 16 张;`batch-export` 1.2.2 状态色走宿主 token、去掉纯蓝主按钮;棘轮基线首次下调。M1–M6 全部完成;上一条 `v3.26.50+cab473c` —— **M5 闸门**:新增 `scripts/token-lint.js`(只查 diff 新增行,CSS 与 JS 内联样式两套判据、四类白名单)+ `tests/design-token-ratchet-test.js`(13 项计数只降不升)+ `tests/theme-contrast-test.js`(亮/暗 × 文字 × 表面 114 对),三条各做一次打红验证后接进 `verify:ci`;顺手把首启动「选择资料目录」弹窗 token 化(全仓最后一个完全未 token 化的界面);上一条 `v3.26.49+1743453` —— **M4-B6 收尾**:`style.css` 剩余 16 处半像素字号全清零(守卫收紧为全文件断言)、`--iwb-control-h` 裁定不扩到全局控件(并排表单 vs 成组紧凑控件);插件主题契约重写,`ALLOW_FILES` 文件级豁免 **6 → 0** —— 改为「私有皮肤 manifest 自声明 `skin` + chroma 强调色判据 + 内容色行内标记」,声明私有皮肤的插件不得引用宿主颜色 token;同步 4 个插件版本,插件侧中性色写死归零;视觉基线 8 张因字号栅格化变化更新,A/B 回退确认非环境噪声;上一条 `v3.26.48+cb9cb9c` —— **M4-B5 节点**:节点卡内部表面统一 `--iwb-field` —— 端口底色从 `#161616`(暗色对卡片差 39 级,一颗黑洞)改 `#494949`(差 12 级),同病灶另 6 处(ref-img/ref-single/upload-link/refmini-empty/task-result-img/node-head:hover)一并改;浮条与任务卡 hover 改 `color-mix(text 10%)`(原来 panel 与 layer2 深色同色,hover 无反馈);字号 12/15/11/13 全归档位、圆角 8/6/5/14 归并、间距 52 处等值 + 13 处 1px 级微调;删 6 个死类名;新增 `tests/node-scope-test.js` 钉「节点内禁用面板表面色」;上一条 `v3.26.47+f5c8174` —— **M4-B4 设置/外观**:新增 `--iwb-control-h`(30px) 修「同行输入框 33px / 按钮 24px」的 9px 落差;设置页正文 14→13、标题 16→15,范围内半像素字号清零;删 21 条死规则(setcell/setgrid/set-row/appear-val 等);新增 `tests/settings-scope-test.js` 钉「控件等高 / 死类名不复现 / 引用的 token 必须存在」;上一条 `v3.26.46+9f29996` —— 2026-11-23 **M4-B3 首页/库**:删 30 条零生产者规则(25 个类名在产物里 0 次)+ 4 条被 specificity 覆盖的死声明,`style.css` 2391→2339 行;首页/库 106 条规则换 token,间距写死 91→5(只剩版心与导航让位的布局值)、字号写死清零,新增 `--iwb-font-display:24px` 第 7 档;验收改为「计算样式逐元素 diff + 12 张基线只首页 2 张变化」;上一条 `v3.26.45+968ff46` —— **M4-B2 浮层层级表 + 阴影四档**:14 档 `--iwb-z-*`(裸 z-index 取值种类 42→31)、`--iwb-elevation-1..4`(浮层 8 种阴影写法→4 档)、`.iwb-pop` 圆角 18→`radius-popover(14)`;修「弹窗里点保存看不到提示」—— 根因不是层级数字而是 `.iwb-overlay` 本身就是堆叠上下文,toast 改为 portal 到 `body`;新增 `tests/overlay-layer-test.js` 钉 9 条顺序约束;上一条 `v3.26.44+846a59b` —— **设计 token 体系重建**:D1–D9 色彩模型改为真正的深色(#121Line truncated
> 日期 **2026-10-20**(**2026-11-16 复算 · v3.24.85**)| 基线(**最近一次 bump 版本的提交**,不是主干 HEAD)`main = d7a2a17`(线上 `v3.26.72+d7a2a17` —— 2026-11-24 **图库:出图即入图库 + 插入落本地副本(能标注)**:每张生成完成即归档并通知插件(此前只在整轮结束写一次 ⇒ 生成中图库一直空)、插入取源改本地字节优先并引用化(抓不到才留原链接 + 提示)、`getNodeImage` 补 `data.localRef` 候选(远程缓存命中却仍判「不支持标注」的直接成因)、批量插入改 4 列栅格(旧实现同批全叠一处),逻辑落 `src/gallery-sync.js`,app.js 只装配;上一条 `v3.26.60+cf0e9a0` —— **浮层字号上调一档**:「模型设置」「图像设置」选择项 11→13px、高 22→28、左右内距 6→10、间距 4→6、标题 12→14、面板 328→360,改动全落在 `.iwb-pop` 的 6 个 token(两面板共用一套);上一条 `v3.26.59+e966b34` —— 备份新增 `plugin-files/` 通道,提示词封面换机不再丢;再上一条 2026-11-23 **节点正文文本区修复**:提示词/文本节点正文透明继承卡片底色(白卡片消失)、编辑态三层框(控件 border / 聚焦光晕 / D8 焦点环)全去掉,规范补表面角色三分法与 `node-scope-test` 第 5 条守卫,8 张基线重录;上一条 `v3.26.51+21554b0` —— **M6 延展验证**:插件面板两段六次叠加样式合并重写、133 行新增零裸值;补 `--iwb-font-base`(14px) 第 8 档与亮色状态色调深(对浅页面 2.13 → ≥4.6),对比度守卫 114→138 对;新增 ⑦⑧ 组件夹具基线共 16 张;`batch-export` 1.2.2 状态色走宿主 token、去掉纯蓝主按钮;棘轮基线首次下调。M1–M6 全部完成;上一条 `v3.26.50+cab473c` —— **M5 闸门**:新增 `scripts/token-lint.js`(只查 diff 新增行,CSS 与 JS 内联样式两套判据、四类白名单)+ `tests/design-token-ratchet-test.js`(13 项计数只降不升)+ `tests/theme-contrast-test.js`(亮/暗 × 文字 × 表面 114 对),三条各做一次打红验证后接进 `verify:ci`;顺手把首启动「选择资料目录」弹窗 token 化(全仓最后一个完全未 token 化的界面);上一条 `v3.26.49+1743453` —— **M4-B6 收尾**:`style.css` 剩余 16 处半像素字号全清零(守卫收紧为全文件断言)、`--iwb-control-h` 裁定不扩到全局控件(并排表单 vs 成组紧凑控件);插件主题契约重写,`ALLOW_FILES` 文件级豁免 **6 → 0** —— 改为「私有皮肤 manifest 自声明 `skin` + chroma 强调色判据 + 内容色行内标记」,声明私有皮肤的插件不得引用宿主颜色 token;同步 4 个插件版本,插件侧中性色写死归零;视觉基线 8 张因字号栅格化变化更新,A/B 回退确认非环境噪声;上一条 `v3.26.48+cb9cb9c` —— **M4-B5 节点**:节点卡内部表面统一 `--iwb-field` —— 端口底色从 `#161616`(暗色对卡片差 39 级,一颗黑洞)改 `#494949`(差 12 级),同病灶另 6 处(ref-img/ref-single/upload-link/refmini-empty/task-result-img/node-head:hover)一并改;浮条与任务卡 hover 改 `color-mix(text 10%)`(原来 panel 与 layer2 深色同色,hover 无反馈);字号 12/15/11/13 全归档位、圆角 8/6/5/14 归并、间距 52 处等值 + 13 处 1px 级微调;删 6 个死类名;新增 `tests/node-scope-test.js` 钉「节点内禁用面板表面色」;上一条 `v3.26.47+f5c8174` —— **M4-B4 设置/外观**:新增 `--iwb-control-h`(30px) 修「同行输入框 33px / 按钮 24px」的 9px 落差;设置页正文 14→13、标题 16→15,范围内半像素字号清零;删 21 条死规则(setcell/setgrid/set-row/appear-val 等);新增 `tests/settings-scope-test.js` 钉「控件等高 / 死类名不复现 / 引用的 token 必须存在」;上一条 `v3.26.46+9f29996` —— 2026-11-23 **M4-B3 首页/库**:删 30 条零生产者规则(25 个类名在产物里 0 次)+ 4 条被 specificity 覆盖的死声明,`style.css` 2391→2339 行;首页/库 106 条规则换 token,间距写死 91→5(只剩版心与导航让位的布局值)、字号写死清零,新增 `--iwb-font-display:24px` 第 7 档;验收改为「计算样式逐元素 diff + 12 张基线只首页 2 张变化」;上一条 `v3.26.45+968ff46` —— **M4-B2 浮层层级表 + 阴影四档**:14 档 `--iwb-z-*`(裸 z-index 取值种类 42→31)、`--iwb-elevation-1..4`(浮层 8 种阴影写法→4 档)、`.iwb-pop` 圆角 18→`radius-popover(14)`;修「弹窗里点保存看不到提示」—— 根因不是层级数字而是 `.iwb-overlay` 本身就是堆叠上下文,toast 改为 portal 到 `body`;新增 `tests/overlay-layer-test.js` 钉 9 条顺序约束;上一条 `v3.26.44+846a59b` —— **设计 token 体系重建**:D1–D9 色彩模型改为真正的深色(#121Line truncated
<!-- 2026-10-28 P1 拆分批 1:新增 src/generation-task-graph.js(5 个任务图纯函数自 app.js 迁出)
⇒ 模块数 60→61、耦合面 51→52、sourceModules 60→61。耦合面只**新增** IWBWTaskGraph,无删除。
2026-10-28 P1 拆分批 2:新增 src/storage-config-shape.js(9 个配置形状纯函数自 app.js 迁出)
@@ -22,7 +22,7 @@
- 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob_<hash>_<len>`** (A) `app.js:2143`;`{__cache}`(Cache Storage)为兜底;\`ref_\`(`app.js` 内定义的 `IDB_REF_PREFIX = 'ref_'`)为 legacy 形态 (A)。
- 大图判定:`isBigDataUrl` = `data:` 且 `length > 3000` (A) `app.js:2018`;**画布保存保留阈值** `< 16384` 才原样保留 (A) `app.js:2182`。**两处阈值并存,含义不同**。
- 单测是**源码契约测试**:`tests/` 目录共 **493** 处源码文本钉点(`source.includes` / `source.indexOf` / `/re/.test(source)`),分布在 **20** 个文件(其中 `iwb-v32-web-test.js` 一个就占 **407**)→ **结构性重构会先打红测试**。**该数字已由 `tests/source-text-ratchet-test.js` 的「只减不增」棘轮守门**(2026-10-20 起守卫范围从 1 个文件扩到全目录:新增任何一处源码文本钉点都会打红)。**2026-11-12 复算**(`npm run audit:pins`,v3.24.76):二分 STRUCT **417** / NAME **76**;形态 **POS 403 / NEG 87 / COUNT 3**;难度 **易 62 / 中 316 / 难 115**。钉点减法第一批(v3.24.72)把 **537 → 505**:8 条探针钉点改为「门禁内 spec 是否真的读该计数器」、5 条改为运行时断言(生产态 `window` 上无探针)、10 条改为 DOM 断言(质量档位禁用 / 传输页无三模式按钮 / 模型项 title)、4 条改为运行时对象断言(健康检查两域、策略对象冻结)、其余 9 条有同文件 DOM 等价断言或仅剩 NEG。第二批(v3.24.76)把 **505 → 493**:94-5~7 三条「多标签释放语义」(10 处正则)换成 `tests/iwb-tabs-release.spec.js` 的 3 条真 e2e,剩 1 条「消费方契约」(断言该 spec 在门禁内且 spec 源码真的读两个探针);另 2 条 `wPurgeIntent.add` 钉点改为读 `src/workspace-purge.js`。**这一批一换就查出 3 个真缺陷**(objectURL 从未释放 / 彻底删除留孤儿标签 · session / 刷新后误回收打开标签的图)—— 见 CHANGELOG v3.24.76。
- `app.js` = 单 IIFE **8,508 行**(**双层预算**:绝对上限 8,700 / 占总源码 ≤ 40%,现 **36.8%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,998 行**(上限 **3,030**,余量 32;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **109** 个模块 / 14,607 行,`sourceModules` 109 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。
- `app.js` = 单 IIFE **9,172 行**(**双层预算**:绝对上限 9,173 / 占总源码 ≤ 40%,现 **30.1%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **3,040 行**(上限 **3,046**,余量 6;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **111** 个模块 / 21,282 行,`sourceModules` 111 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。
- 门禁:`npm run verify` = `verify:ci`(`build` → `node --check app.js` → `node --check dist/app.js` → `check-dist.js` → `lint`(ESLint 正确性规则,`src/` + `app.js`,P4-16a)→ `test:unit` → `test` → `test:facts`)+ `test:e2e` (A) `package.json`。
## 2. 门禁与环境现状
@@ -167,7 +167,7 @@
- 同一张图被 3 个节点引用、hydrate 成 3 个不同 objectURL 时,preview/display 缓存各自 miss → 重复解码(与 F2 相邻)。
- **F10|`refs.genScheduler` 是桩** (A) → 未接线,暂无运行时影响(P3)。
- **F11|已建但未接线的模块层(2026-10-17 接线审计;2026-10-18 复核更正)** (A)
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**109 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**111 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
- **仅被测试引用(9 模块 + 2 导出)**:`canvas-domain`、`generation-retry`、`generation-service`、`runtime-recovery-runner`、`runtime-state-bridge`、`runtime-store`、`storage-reconcile`、`storage-result`、`workspace-service`;导出 `IWBStorageHealthFactory`、`IWBPluginHostFactory`。(`storage-result` 是**存储层共享结果类型**,被 6 个存储模块读取,**非死代码**;`runtime-store` 为状态模型 epic 地基。)
- **app.js 零引用(1 模块 + 3 导出)**:模块 `generation-controller`;导出 `IWBRuntimeMetricsFactory`、`IWBStorageRuntimeFactory`、`IWBUIComponents`。`canvas-relations` 已随 `06cf211` 删除(本文档早前把它列为"唯一可删者",实际已删)。零引用证据 = `grep -rn "<名字>" .`(排除 `node_modules|dist|vendor|test-results`)**只命中其自身赋值行**。
- **半接线 / 未接线**:`IWBRuntimeStateBridge` **无 app.js 引用(仅测试)**;`IWBRuntimeRunContext` **已接线**(`runNode` 读取运行上下文);`IWBGenerationController` 是完整但**从未被调用**的工厂;`ModularWorkspaceStore`(`app.js` 内)是 `storage-workspace` 的**预留接线 seam**(当前无下游使用,保留);`window.IWBImageFolder` 自注册后读回(装载路径)。
@@ -183,7 +183,7 @@
| `storage-reconcile` | 存储对账(`createReconciler`/`check`) | 内联对账 | 存储层收口 |
| `runtime-recovery-runner` | 执行恢复候选(`candidate`/`valid`/`run`) | 内联恢复 | 断点恢复 |
| `canvas-domain` | 画布域模型(`commit`/`updateNode`/`deleteNodes`…) | `CanvasStore` 那一套 | Workbench 解耦(P2-9) |
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**88** 项)与 `sourceModules` 顺序(**109** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**92** 项)与 `sourceModules` 顺序(**111** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
## 12. 易踩的坑
@@ -254,7 +254,7 @@
**信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**88** 项)与 `sourceModules` 顺序(**109** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**92** 项)与 `sourceModules` 顺序(**111** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。
**关键陷阱**:`normalizeNodes`(现位于 `src/canvas-normalize.js`)会**静默丢弃**不在 `NODE_H` 里的节点类型 ⇒ 新增节点类型必须先登记 `NODE_H`,否则节点一刷新就消失(§13.27 规则三的同一失败模式)。
+1 -1
View File
@@ -505,7 +505,7 @@ LRU 上限 + 切画板/离开画布/卸载时回收;`revokeAll()` 幂等。
| 内容 | 位置 |
|---|---|
| 完整执行文档与复盘(§0–§13,含被推翻推断的留档、踩坑清单、验收表) | `docs/archive/plans/opentu-parity-image-memory.md` |
| 预览产物生成器(解码即缩放 + `close()` + objectURL 回收) | `src/image-preview-derive.js`(32/32 单测) |
| ~~预览产物生成器(解码即缩放 + `close()` + objectURL 回收)~~ **已于 v3.26.65 删除**:交付时只做到「模块 + 单测」,从未接到 `wPreviewUrlOf`(实际是恒等函数)—— 属"假绿",重做见 BACKLOG | — |
| 图片字节 Blob 仓库(内容寻址去重) | `src/image-blob-store.js`(9/9 单测) |
| 同源图片代理(跨域取字节唯一通道) | `functions/api/img.js` |
| 内存行为契约 | `tests/iwb-image-memory-parity.spec.js` |
@@ -298,7 +298,7 @@ dist/ += favicon.svg / _headers / THIRD_PARTY_NOTICES.md
| 生成流水线 | `generation-*` | 请求体归一(size-policy / request-shape)、调度、重试、状态、服务、控制器 |
| 画布域 | `canvas-*` | 域对象、节点工厂、动作、关系、store |
| 工作台 / 图库 | `workspace-service`、`gallery-*` | 工作台装配、图库查询与水合 |
| 图片管道 | `image-blob-store`、`image-preview-derive` | Blob 仓库、派生预览(canvas 解码) |
| 图片管道 | `image-blob-store`、`image-compress`、`image-format` | Blob 仓库、压缩(Worker)、格式判定与 SVG 光栅化 |
| UI 组件 | `ui-components` | 通用 UI 片段 |
### 11.3 边界硬规则
@@ -308,7 +308,7 @@ dist/ += favicon.svg / _headers / THIRD_PARTY_NOTICES.md
- **大图只走存储契约**:新写入主通道 `{__blob}`(IndexedDB),`{__cache}` 兜底;**localStorage 只放轻量索引,绝不放放大 base64**(见 §8 与事实基线 §5)。
- **契约测试锁结构**:`tests/*.js` 多为**源码契约测试**(断言 `app.js`/`src/*.js` 原文片段)——改函数签名、移动代码块、增删调用点前**先查是否被断言钉住**;结构性重构会先打红测试。
- **新增模块**:须遵循既有前缀命名,并登记进 `scripts/build.js` 的 `sourceModules` **且顺序正确**。
- 模块按需触碰宿主能力(如 `storage-*` 碰 IndexedDB/localStorage、`image-preview-derive` 碰 canvas、`runtime-crash-log` 碰 window)**属于该层职责**。
- 模块按需触碰宿主能力(如 `storage-*` 碰 IndexedDB/localStorage、`image-compress` 碰 Worker/canvas、`runtime-crash-log` 碰 window)**属于该层职责**。
- **权威写入点唯一**:业务状态与画布 DOM 的**权威**读写只在 `Workbench()` 作用域(`app.js`);`src/*.js` 只经 `window.IWB*` 读写状态。**允许**把**无状态 UI 组件**放进 `src/ui-*.js`(`React` / `el` 从 `global` 解析,仅经 `props` 收数据与回调)——但**禁止**在模块里持有业务状态的权威副本,也**禁止**模块直接查询 / 写画布 DOM。
## 12. 交互与状态契约
+3 -2
View File
@@ -1,7 +1,7 @@
{
"name": "image-workbench-web",
"private": true,
"version": "3.26.62",
"version": "3.26.72",
"description": "Browser-based node canvas image workbench",
"scripts": {
"build": "node scripts/build.js && node scripts/copy-plugins.js",
@@ -10,7 +10,7 @@
"app:build": "tauri build",
"lint": "eslint src app.js",
"test": "node tests/relay-task-graph-fixture-test.js && node tests/plugin-style-node-test.js && node tests/inherit-text-test.js",
"test:unit": "node tests/plugin-archive-test.js && node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js",
"test:unit": "node tests/plugin-files-policy-test.js && node tests/theme-plugin-tokens-test.js && node tests/design-tokens-component-doc-test.js && node tests/theme-static-snapshot-test.js && node tests/overlay-layer-test.js && node tests/settings-scope-test.js && node tests/node-scope-test.js && node tests/appearance-v2-test.js && node tests/image-prompt-cover-test.js && node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/album-task-graph-test.js && node tests/generation-endpoint-test.js && node tests/storage-config-shape-test.js && node tests/generation-default-model-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/gallery-sync-test.js && node tests/image-blob-store-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/plugin-theme-contract-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/native-overlay-park-test.js && node tests/ui-dock-sanitize-test.js && node tests/ui-minimap-fit-test.js && node tests/ui-workbench-hooks-test.js && node tests/plugin-scale-contract-test.js && node tests/design-token-ratchet-test.js && node tests/theme-contrast-test.js && node tests/image-file-ref-preview-test.js",
"test:diagnostics": "node tests/runtime-diagnostics-hotpath-test.js",
"test:facts": "node tests/architecture-facts-guard-test.js && node tests/release-records-test.js",
"plugins:gc": "node scripts/plugins-publish.mjs --gc",
@@ -24,6 +24,7 @@
"test:visual:update": "npx playwright test _visual-tokens --update-snapshots",
"test:e2e": "npm run build && node scripts/serve-test.js",
"test:e2e:local": "node scripts/serve-test.js",
"e2e:known-red": "node scripts/e2e-known-red-report.js",
"verify:ci": "npm run build && node --check app.js && node --check dist/app.js && node scripts/check-dist.js && npm run tokens:check && npm run lint:tokens && npm run lint && npm run typecheck && npm run test:unit && npm test && npm run test:facts",
"verify": "npm run verify:ci && npm run test:e2e",
"verify:release": "node scripts/verify-release.js",
+849
View File
@@ -0,0 +1,849 @@
// 相册节点(2026-11-26,iwb-plugin: album)
//
// 一件事:把「多个图片节点」收成一个节点——宫格装 N 张本地图,接提示词/组合做批量生图。
//
// 三条关键设计(都对宿主有依赖,别在插件里重造):
// ① 只引用不复制:item.src = { __file: '/abs/a.png' };宿主生成时才读盘(ctx.images.reference / dataUrl)
// ② 任务展开由宿主任务图做:data.outKind='images' + data.items,宿主按 albumMode 展开成 N 个任务
// (一图一任务)或分批(批量,每组 ≤12 张);本插件只负责「数据 + 界面」
// ③ 分页容量随节点尺寸实时算:拖大 = 一页装更多(装得下就隐藏分页条),缩小 = 自动多页;
// 只有 data.onlyPage 打开时才把可见区间写进 data.pageRange 交给宿主过滤
;(function (global) {
'use strict'
if (!global.IWBPluginHost) return
// 密度档位 = 目标单元格边长(px)。1.1.0 修正:旧值 {S:64, M:48, L:100} 里 M 比 S 还小,
// 于是「中格」每页装 30 张(比小格的 20 张还多),档位语义是反的。现在 S < M < L 严格递增。
const DENSITY = { S: 64, M: 80, L: 104 }
// ⚠ 下面这一组必须与 styles.css 逐个对齐(换了 box-sizing / padding 就会算错容量 ⇒ 最后一行被裁)。
// 宿主全局 * { box-sizing: border-box },所以 CSS 里写的 height 已含 padding。
const GAP = 4 // .iwb-album-grid 的 gap = --iwb-space-4
const PAD_X = 16 // 宫格左右 padding 合计(.iwb-album-grid 左右各 --iwb-space-8)
const PAD_Y = 8 // 上下 padding 合计(.iwb-album-grid 2px + 6px)
const BAR_H = 26 // 状态栏
const TOOLS_H = 25 // 工具条(padding 2+2 + 按钮 21)
const PAGER_H = 26 // 分页条 / 一页提示条
const HINT_H = 28 // 批量模式提示行(含 margin-bottom 4)
const DEFAULT_H = 470 // 注册时声明的默认高度(与 height 字段保持一致)
const THUMB_EDGE = 256
const THUMB_Q = 0.8
const IMG_EXT = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'avif', 'bmp', 'svg']
const STATE = new WeakMap() // host 元素 → 渲染状态(一个容器一个实例)
// ── 小工具 ──────────────────────────────────────────────
function el (tag, attrs, kids) {
const node = document.createElement(tag)
if (attrs) for (const k in attrs) {
const v = attrs[k]
if (v === null || v === undefined || v === false) continue
if (k === 'className') node.className = v
else if (k === 'text') node.textContent = v
else if (k === 'style' && typeof v === 'object') Object.assign(node.style, v)
else if (k.slice(0, 2) === 'on' && typeof v === 'function') node.addEventListener(k.slice(2).toLowerCase(), v)
else node.setAttribute(k, v === true ? '' : String(v))
}
for (const kid of (Array.isArray(kids) ? kids : (kids ? [kids] : []))) {
if (kid === null || kid === undefined || kid === false) continue
node.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid)
}
return node
}
// 可点击元素:宿主在节点体上的 pointerdown 会启动「拖动节点」,单击事件因此被吞。
// 所有可点击的非 input/button 元素都必须挡住 pointerdown(与 ui-node-bodies 里 stop 的用法一致)。
function onTap (el0, fn) {
el0.addEventListener('pointerdown', (e) => e.stopPropagation())
el0.addEventListener('click', (e) => { e.stopPropagation(); fn(e) })
return el0
}
function hash32 (s) {
let h = 0x811c9dc5
const str = String(s || '')
for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0 }
return ('00000000' + h.toString(16)).slice(-8)
}
const extOf = (p) => { const m = /\.([a-z0-9]{1,5})$/i.exec(String(p || '')); return m ? m[1].toLowerCase() : '' }
const isImagePath = (p) => IMG_EXT.indexOf(extOf(p)) >= 0
const fileRefOf = (src) => (src && typeof src === 'object' && typeof src.__file === 'string') ? src.__file : ''
const nameOf = (p) => String(p || '').replace(/^.*[\\/]/, '')
const str = (v) => (v == null ? '' : String(v))
// ── 缩略图(插件私有缓存,几十 KB/张,不碰画布存储)────────────
const thumbNameOf = (key) => 't-' + hash32(key) + '.jpg'
// 缩略图缓存键(1.1.0 修「串味」):旧实现是 `fileRefOf(src) || it.name`,一旦固化(src 变成
// {__blob})或从别处导入,路径就没了 ⇒ 键退化成纯文件名 ⇒ 不同目录下的 1.png 共用同一张缩略图。
// 现在按引用本身取键:路径 → 路径;blob/cache → 各自 id;dataURL → 内容哈希;只有都没有才退回文件名。
function thumbKeyOf (it) {
const src = (it && it.src) != null ? it.src : it
const path = fileRefOf(src)
if (path) return 'f:' + path
if (src && typeof src === 'object') {
if (typeof src.__blob === 'string' && src.__blob) return 'b:' + src.__blob
if (typeof src.__cache === 'string' && src.__cache) return 'c:' + src.__cache
}
if (typeof src === 'string' && src) {
if (src.length > 4096) return 'd:' + hash32(src.slice(0, 2048) + src.slice(-2048) + ':' + src.length)
return 'd:' + hash32(src)
}
const n = (it && (it.name || it.size)) || ''
return 'n:' + str(n)
}
function makeThumb (dataUrl) {
return new Promise((resolve) => {
try {
const img = new Image()
img.onload = () => {
try {
const scale = Math.min(1, THUMB_EDGE / Math.max(img.naturalWidth || 1, img.naturalHeight || 1))
const w = Math.max(1, Math.round((img.naturalWidth || 1) * scale))
const h = Math.max(1, Math.round((img.naturalHeight || 1) * scale))
const cv = document.createElement('canvas')
cv.width = w; cv.height = h
const c2 = cv.getContext('2d')
c2.drawImage(img, 0, 0, w, h)
resolve(cv.toDataURL('image/jpeg', THUMB_Q))
} catch (e) { resolve('') }
}
img.onerror = () => resolve('')
img.src = dataUrl
} catch (e) { resolve('') }
})
}
// ── 容量:随节点宽高实时算(放大 = 一页装更多)────────────────
function capacityOf (width, height, density, hasHint) {
const target = DENSITY[density] || DENSITY.S
const innerW = Math.max(0, width - 4 - PAD_X)
const innerH = Math.max(0, height - 4 - BAR_H - TOOLS_H - PAGER_H - (hasHint ? HINT_H : 0) - PAD_Y)
const cols = Math.max(1, Math.floor((innerW + GAP) / (target + GAP)))
const cell = Math.floor((innerW - (cols - 1) * GAP) / cols) || target
const rows = Math.max(1, Math.floor((innerH + GAP) / (cell + GAP)))
return { cols, rows, cell: Math.max(20, cell), capacity: Math.max(1, cols * rows) }
}
function measure (host) {
const rect = host.getBoundingClientRect()
return { width: Math.round(rect.width || 0), height: Math.round(rect.height || 0) }
}
// ── 数据读写 ────────────────────────────────────────────
function itemsOf (node) {
const d = (node && node.data) || {}
return Array.isArray(d.items) ? d.items : []
}
function update (props, node, patch, snapshot) {
try { if (snapshot && typeof props.onSnapshot === 'function') props.onSnapshot() } catch (e) { /* 撤销快照失败不影响写入 */ }
try { props.onUpdate(node.id, patch) } catch (e) { /* 宿主不可写时保持只读 */ }
}
// ── 外壳 ────────────────────────────────────────────────
function buildShell (ctx, node, props, host) {
const st = {
nodeId: node.id,
thumbs: new Map(), // key → dataURL(内存缓存)
pending: new Map(), // key → Promise(并发去重:格子挂载和预生成会同时要同一张)
missing: new Set(), // 失联文件的 key
busy: '',
checkedMissing: false,
sig: '',
cap: null, // 最近一次容量计算(拖拽排序换算页码要用)
}
const bar = el('div', { className: 'iwb-album-bar' })
const track = el('span', { className: 'iwb-album-track' }, el('i', null))
const modeLabel = el('label', { className: 'iwb-album-toggle' }, track, document.createTextNode('一图一任务'))
modeLabel.addEventListener('pointerdown', (e) => e.stopPropagation())
modeLabel.addEventListener('click', (e) => {
e.stopPropagation()
// ⚠ 必须读 st.node(每次 sync 更新),不能读 buildShell 捕获的 node ——
// 那是**挂载时**的旧数据,连点两次会一直算出同一个 next(实测:永远停在批量)。
const cur = st.node || node
const d = (cur && cur.data) || {}
const next = d.albumMode === 'batch' ? 'per-image' : 'batch'
update(st.props || props, cur, { albumMode: next })
})
const count = el('span', { className: 'iwb-album-count' })
// 一键清空(2026-11-26 用户需求):只清本节点持有的 items,删源文件与画布存储一概不碰。
// 走 snapshot:true ⇒ ⌘Z 能整批恢复,所以不加二次确认弹窗(多一步点击反而更烦)。
const btnClear = el('button', { className: 'iwb-album-btn iwb-album-clear', title: '清空相册(⌘Z 可撤销;不会删除磁盘上的原文件)' }, '清空')
bar.appendChild(modeLabel); bar.appendChild(count); bar.appendChild(btnClear)
const btnAdd = el('button', { className: 'iwb-album-btn', title: '选择本地图片(桌面端只引用,不复制字节)' }, '+ 添加图片')
const btnDir = el('button', { className: 'iwb-album-btn', title: '按文件夹批量添加' }, '文件夹')
const btnSettle = el('button', { className: 'iwb-album-btn', title: '把引用复制进画布存储(删源文件/分享画布前用)' }, '固化')
const seg = el('span', { className: 'iwb-album-seg' })
const segs = {}
for (const key of ['S', 'M', 'L']) {
const s = onTap(el('span', { title: key === 'S' ? '小格(默认)' : (key === 'M' ? '中格' : '大格') }, key), () => update(st.props || props, st.node || node, { density: key }))
segs[key] = s; seg.appendChild(s)
}
const tools = el('div', { className: 'iwb-album-tools' }, [btnAdd, btnDir, btnSettle, seg])
const hint = el('div', { className: 'iwb-album-hint' })
const grid = el('div', { className: 'iwb-album-grid' })
const empty = el('div', { className: 'iwb-album-empty' }, [
el('div', { className: 'box' }, '+'),
el('div', null, '把图片拖到这里,或点「添加图片」选本地文件'),
el('div', { style: { fontSize: '10px', opacity: '.85' } }, '支持 PNG / JPG / WebP / GIF / AVIF / SVG'),
])
const pager = el('div', { className: 'iwb-album-pager' })
const onepage = el('div', { className: 'iwb-album-onepage' }, '全部图片一页展示')
// 节点内 hover 预览层已于 1.1.1 移除(用户实测:鼠标移到放大镜上时预览层盖住图标,反而点不到)。
// 现在只看大图走「点击放大镜 → 宿主全屏预览(props.onPreview)」,点图片外或 Esc 自动退出。
host.textContent = ''
const root = el('div', { className: 'iwb-album' }, [bar, tools, hint, grid, empty, pager, onepage])
host.appendChild(root)
Object.assign(st, { root, bar, track, count, btnClear, btnAdd, btnDir, btnSettle, segs, grid, empty, pager, onepage, hint })
// 按钮绑定(用闭包里的当前 node/props:每次 sync 会更新 st.node/st.props)
btnAdd.addEventListener('pointerdown', (e) => e.stopPropagation())
btnAdd.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, host, false) })
btnDir.addEventListener('pointerdown', (e) => e.stopPropagation())
btnDir.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, host, true) })
btnSettle.addEventListener('pointerdown', (e) => e.stopPropagation())
btnSettle.addEventListener('click', (e) => { e.stopPropagation(); settleAll(ctx, st) })
btnClear.addEventListener('pointerdown', (e) => e.stopPropagation())
btnClear.addEventListener('click', (e) => { e.stopPropagation(); clearAll(ctx, st) })
// 拖拽入图:桌面端拿不到绝对路径 ⇒ 按「方案 1」复制进画布存储
host.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation() })
host.addEventListener('drop', (e) => {
e.preventDefault(); e.stopPropagation()
const files = Array.from((e.dataTransfer && e.dataTransfer.files) || [])
if (files.length) importDropped(ctx, st, files)
})
return st
}
// ── 同步(宿主每次重渲染都会调用;必须可增量)──────────────────
function sync (ctx, st, node, props) {
st.node = node; st.props = props
const d = (node && node.data) || {}
const items = itemsOf(node)
const density = DENSITY[d.density] ? d.density : 'S'
const mode = d.albumMode === 'batch' ? 'batch' : 'per-image'
// 尺寸来源:**只认显式 node.h 或变体默认高度**(2026-11-26 修"插入后慢慢变矮")。
// ⚠ 绝不能用 props.measuredH / 自身 getBoundingClientRect():插件节点体是内容撑开的,
// 我们按它写回高度 ⇒ 卡片变矮 ⇒ 下次量到更矮 ⇒ 一路缩水。
// 拖拽调整尺寸时宿主会把新高度写进 node.h,那才是权威值。
const measured = measure(st.root)
const cardW = Number(node.w) || measured.width || 300
const cardH = Number(node.h) || DEFAULT_H
const wantH = Math.max(120, Math.round(cardH) - 4) + 'px'
if (st.root.style.height !== wantH) st.root.style.height = wantH
const cap = capacityOf(cardW, cardH, density, mode === 'batch')
st.cap = cap // 拖拽排序换算「本页第 i 格 → 全局第几格」要用(旧代码用格子数,把「+添加」也算进去了)
const pages = Math.max(1, Math.ceil(items.length / cap.capacity))
const page = Math.max(0, Math.min(pages - 1, Number(d.page) || 0))
const from = page * cap.capacity
const to = Math.min(items.length, from + cap.capacity)
const selected = items.filter((it) => it && it.on !== false).length
// 一图一任务开关 / 计数 / 密度高亮 / 固化可用性
st.track.className = 'iwb-album-track' + (mode === 'per-image' ? ' on' : '')
st.count.innerHTML = ''
st.count.appendChild(document.createTextNode('已选 '))
st.count.appendChild(el('b', null, String(selected)))
st.count.appendChild(document.createTextNode('/' + items.length + ' · 每页 ' + cap.capacity))
for (const k in st.segs) st.segs[k].className = (density === k ? 'on' : '')
const hasFileRef = items.some((it) => fileRefOf(it && it.src))
st.btnSettle.style.display = hasFileRef ? '' : 'none'
// 「文件夹」只在能做路径引用的宿主里有意义(桌面端)。旧写法 `canReference() || true` 恒真,
// 于是在网页版点它永远没反应。网页版仍可用「+ 添加图片」走文件选择器。
const canRef = !!(ctx.images && typeof ctx.images.canReference === 'function' && ctx.images.canReference())
st.btnDir.style.display = canRef ? '' : 'none'
st.btnClear.style.display = items.length ? '' : 'none'
if (st.busy) { st.btnAdd.textContent = st.busy } else { st.btnAdd.textContent = '+ 添加图片' }
// 批量模式提示:N 张 → M 个任务(每组 ≤ 12)
if (mode === 'batch' && items.length) {
st.hint.style.display = ''
st.hint.innerHTML = ''
st.hint.appendChild(document.createTextNode('整本一次请求:'))
st.hint.appendChild(el('b', null, items.length + ' 张 → ' + Math.ceil(items.length / 12) + ' 个任务'))
st.hint.appendChild(document.createTextNode('(每组 ≤ 12 张)'))
} else st.hint.style.display = 'none'
// 分页条 / 一页展示
// 空节点不再显示「全部 0 张一页展示」那条灰条(2026-11-26):它压着空态提示,说的还是废话。
const showPager = pages > 1
const showOne = !showPager && items.length > 0
st.pager.style.display = showPager ? '' : 'none'
st.onepage.style.display = showOne ? '' : 'none'
if (showOne) st.onepage.textContent = '全部 ' + items.length + ' 张一页展示 · 无需翻页'
if (showPager) {
st.pager.innerHTML = ''
const pg = el('span', { className: 'iwb-album-pg' })
const prev = onTap(el('span', { title: '上一页' }, '‹'), () => { if (page > 0) update(st.props, st.node, { page: page - 1 }) })
const next = onTap(el('span', { title: '下一页' }, '›'), () => { if (page < pages - 1) update(st.props, st.node, { page: page + 1 }) })
pg.appendChild(prev); pg.appendChild(el('b', null, (page + 1) + '/' + pages)); pg.appendChild(next)
st.pager.appendChild(pg)
const only = el('label', { className: 'iwb-album-mini' }, [
el('span', { className: 'iwb-album-track' + (d.onlyPage === true ? ' on' : '') }, el('i', null)),
document.createTextNode('仅本页参与'),
])
only.addEventListener('pointerdown', (e) => e.stopPropagation())
only.addEventListener('click', (e) => {
e.stopPropagation()
update(st.props, st.node, { onlyPage: !(d.onlyPage === true) })
})
st.pager.appendChild(only)
}
// 仅本页参与:把可见区间写回 data.pageRange(宿主任务图据此过滤;关闭时清掉)
const wantRange = (d.onlyPage === true) ? [from, to] : null
const curRange = Array.isArray(d.pageRange) ? d.pageRange : null
const rangeChanged = (!!wantRange !== !!curRange) || (wantRange && curRange && (wantRange[0] !== curRange[0] || wantRange[1] !== curRange[1]))
if (rangeChanged || (Number(d.page) || 0) !== page) {
update(st.props, st.node, { page: page, pageRange: wantRange })
}
// 宫格(签名不变就不重建:避免每帧重排导致闪烁/丢拖拽态)
const sig = [node.id, density, page, cap.capacity, mode, items.length, d.onlyPage === true ? 1 : 0,
items.map((it) => thumbKeyOf(it) + (it && it.on === false ? ':0' : ':1')).join(','), Array.from(st.missing).join(',')].join('|')
if (sig !== st.sig) {
st.sig = sig
st.grid.innerHTML = ''
st.grid.style.gridTemplateColumns = 'repeat(' + cap.cols + ', 1fr)'
if (!items.length) {
st.grid.style.display = 'none'; st.empty.style.display = ''
} else {
st.grid.style.display = ''; st.empty.style.display = 'none'
for (let i = from; i < to; i++) st.grid.appendChild(cellOf(ctx, st, items[i], i, mode))
if (to - from < cap.capacity) {
const add = el('button', { className: 'iwb-album-cell iwb-album-add', title: '添加图片' }, [el('b', null, '+'), el('span', null, '添加')])
add.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, st.root, false) })
st.grid.appendChild(add)
}
}
} else {
st.grid.style.gridTemplateColumns = 'repeat(' + cap.cols + ', 1fr)'
}
// 失联检测(每个节点一次;文件被移动/删除时给出明确提示)
if (!st.checkedMissing && items.some((it) => fileRefOf(it && it.src))) {
st.checkedMissing = true
checkMissing(ctx, st, items).then((changed) => { if (changed) { st.sig = ''; try { sync(ctx, st, st.node, st.props) } catch (e) { /* ignore */ } } })
}
}
// ── 单元格 ──────────────────────────────────────────────
// 放大镜图标(内联 SVG,CSP 禁外部资源):圆 + 手柄,10px 下仍看得清
function zoomIcon () {
const NS = 'http://www.w3.org/2000/svg'
const mk = (tag, attrs) => {
const n = document.createElementNS(NS, tag)
for (const k in attrs) n.setAttribute(k, attrs[k])
return n
}
const svg = mk('svg', { viewBox: '0 0 24 24', 'aria-hidden': 'true' })
svg.appendChild(mk('circle', { cx: 10, cy: 10, r: 7, fill: 'none', stroke: 'currentColor', 'stroke-width': 2.4 }))
svg.appendChild(mk('path', { d: 'M15.2 15.2 21 21', fill: 'none', stroke: 'currentColor', 'stroke-width': 2.4, 'stroke-linecap': 'round' }))
return svg
}
function cellOf (ctx, st, it, index, mode) {
const src = it && it.src
const path = fileRefOf(src)
const key = thumbKeyOf(it)
const on = !(it && it.on === false)
const missing = path && st.missing.has(path)
const btn = el('button', {
className: 'iwb-album-cell' + (on ? ' sel' : ' off') + (missing ? ' missing' : ''),
title: (it && it.name ? it.name : ('图 ' + (index + 1))) + (missing ? '(文件已不在原位置:点一下重新定位)' : ''),
})
const img = el('img', { alt: '', draggable: 'false' })
const cached = st.thumbs.get(key)
if (cached) img.src = cached
// 不设 img.src = '':空字符串会向页面 URL 发一次请求(控制台 ERR_UNKNOWN_URL_SCHEME)。
// 不设 src 属性时 <img> 什么都不做,缩略图到了再赋上即可。
else loadThumb(ctx, st, it, key).then((url) => { if (url && img.isConnected !== false) img.src = url })
btn.appendChild(img)
btn.appendChild(el('span', { className: 'iwb-album-idx' }, String(index + 1)))
// 批次角标(右上角那个「1」)已删除:顶栏「N 张 → M 个任务」已经说清楚,角标是重复信息,
// 还会和删除按钮抢同一个角。位置让给了 ×。
const del = el('span', { className: 'iwb-album-del', title: '移除(不删除磁盘上的原文件)' }, '×')
del.addEventListener('pointerdown', (e) => e.stopPropagation())
del.addEventListener('click', (e) => {
e.stopPropagation()
const items = itemsOf(st.node).slice()
items.splice(index, 1)
// 删除后留在当前页(旧实现硬编码 page:0,第 2 页删一张直接跳回第 1 页)。
// 只做「页数变少时往回收」,正常情况 page 不动。
const capNow = st.cap || { capacity: 20 }
const pagesNow = Math.max(1, Math.ceil(items.length / capNow.capacity))
const pageNow = Math.max(0, Number((st.node.data || {}).page) || 0)
update(st.props, st.node, { items: items, page: Math.min(pageNow, pagesNow - 1) }, true)
})
btn.appendChild(del)
// 放大镜(右下角):点开插件自带的全屏查看器,可 ← → 切换整本相册(1.1.2)。
// 1.1.1 的 hover 预览已废(那层会盖住放大镜本身)。
const zoom = el('span', { className: 'iwb-album-zoom', title: '查看大图(← → 切换,点击空白处或 Esc 关闭)' }, zoomIcon())
zoom.addEventListener('pointerdown', (e) => e.stopPropagation())
zoom.addEventListener('click', (e) => { e.stopPropagation(); openFull(ctx, st, index) })
btn.appendChild(zoom)
btn.addEventListener('pointerdown', (e) => e.stopPropagation())
btn.addEventListener('click', (e) => {
e.stopPropagation()
if (missing) { relocate(ctx, st, index); return }
const items = itemsOf(st.node).slice()
if (!items[index]) return
items[index] = Object.assign({}, items[index], { on: !on })
update(st.props, st.node, { items })
})
// 拖拽排序
btn.addEventListener('pointerdown', (e) => {
if (e.button !== 0) return
const startX = e.clientX, startY = e.clientY
let moved = false
const target = { index: index }
const onMove = (ev) => {
const dx = ev.clientX - startX, dy = ev.clientY - startY
if (!moved && Math.abs(dx) + Math.abs(dy) < 5) return
moved = true
btn.classList.add('dragging')
const cells = Array.from(st.grid.querySelectorAll('.iwb-album-cell'))
let hit = cells.length - 1
for (let i = 0; i < cells.length; i++) {
const r = cells[i].getBoundingClientRect()
if (ev.clientX < r.left + r.width / 2 + (r.width * 0.1) && ev.clientY < r.bottom && ev.clientX > r.left - r.width) { hit = i; break }
}
cells.forEach((c, i) => c.classList.toggle('dropbefore', i === hit))
target.index = hit
}
const onUp = () => {
document.removeEventListener('pointermove', onMove)
document.removeEventListener('pointerup', onUp)
btn.classList.remove('dragging')
Array.from(st.grid.querySelectorAll('.dropbefore')).forEach((c) => c.classList.remove('dropbefore'))
if (!moved) return
const items = itemsOf(st.node).slice()
// 1.1.0 修跨页错位:本页起点 = page × **每页容量**(旧代码乘的是「本页格子数」,而格子数里
// 还含末尾那个「+添加」格 ⇒ 第 2 页永远算少一格,把 21 号拖到第 2 位会插到全局第 13 位)。
const capNow = st.cap || { capacity: 20 }
const pageNow = Math.max(0, Number((st.node.data || {}).page) || 0)
const pageStart = pageNow * capNow.capacity
const realCount = Math.min(capNow.capacity, Math.max(0, items.length - pageStart))
const srcIndex = index
let dest = pageStart + Math.min(target.index, realCount)
if (dest === srcIndex || dest < 0) return
const [movedItem] = items.splice(srcIndex, 1)
if (dest > srcIndex) dest -= 1
items.splice(Math.max(0, Math.min(items.length, dest)), 0, movedItem)
update(st.props, st.node, { items: items }, true)
}
document.addEventListener('pointermove', onMove)
document.addEventListener('pointerup', onUp)
})
return btn
}
// ── 缩略图取用:内存 → 插件文件 → 现做 ───────────────────
// 并发去重(1.1.0):格子一挂载就各自要缩略图,而 addPaths 又顺序预热一遍 ⇒ 同一张图会被读两次盘。
// 用 pending 表把同 key 的请求合成一个 Promise(否则导入 30 张会解 60 次原图,内存直接翻倍)。
async function loadThumb (ctx, st, it, key) {
if (st.thumbs.has(key)) return st.thumbs.get(key)
const flight = st.pending && st.pending.get(key)
if (flight) return flight
const p = loadThumbInner(ctx, st, it, key).finally(() => { if (st.pending) st.pending.delete(key) })
if (st.pending) st.pending.set(key, p)
return p
}
async function loadThumbInner (ctx, st, it, key) {
if (st.thumbs.has(key)) return st.thumbs.get(key)
const name = thumbNameOf(key)
try {
if (ctx.files) {
const got = await ctx.files.get(name)
if (got && got.ok && got.url) { st.thumbs.set(key, got.url); return got.url }
}
} catch (e) { /* 没缓存就现做 */ }
let dataUrl = ''
const src = it && it.src
try {
if (fileRefOf(src)) dataUrl = await ctx.images.dataUrl(src)
else if (typeof src === 'string') dataUrl = src
else dataUrl = await ctx.images.dataUrl(src)
} catch (e) { dataUrl = '' }
if (!dataUrl) return ''
const thumb = await makeThumb(dataUrl)
if (!thumb) return ''
st.thumbs.set(key, thumb)
// 内存里已经有一张就够本会话用了;写盘失败(配额满)不影响显示
try { if (ctx.files) await ctx.files.put(name, thumb) } catch (e) { /* ignore */ }
return thumb
}
// ── 看大图:插件自带全屏查看器(1.1.2 起支持 ← → 切换)──────────
// 历史:1.1.0 做过「hover 节点内浮大图 + 点击全屏」两套,hover 层把放大镜盖住了 ⇒ 1.1.1 删掉。
// 1.1.2:宿主 props.onPreview 只收「已解析好的 URL 列表」,一本 30 张的相册要左右切换,
// 就得开窗前把 30 张原图全转成 dataURL(几十上百 MB,还可能卡住主线程)。所以改成自建查看器:
// 只解码当前这张 + 预取左右各一张(最多 3 张常驻),切换即时、内存可控。
// 交互沿用宿主那套肌肉记忆:点图片外的空白 / Esc 退出,← → 切换,滚轮也切。
const FS_KEEP = 3 // 同时保留的原图张数(当前 + 左右各一)
function closeViewer (st) {
const v = st && st.viewer
if (!v) return
st.viewer = null
try { window.removeEventListener('keydown', v.onKey, true) } catch (e) { /* ignore */ }
try { window.removeEventListener('wheel', v.onWheel, true) } catch (e) { /* ignore */ }
if (v.root && v.root.parentNode) v.root.parentNode.removeChild(v.root)
}
function openFull (ctx, st, index) {
closeViewer(st)
const items = itemsOf(st.node)
const total = items.length
if (!total) return
const pick = (i) => items[((i % total) + total) % total]
const keyAt = (i) => thumbKeyOf(pick(i))
let cur = Math.max(0, Math.min(total - 1, Number(index) || 0))
let curUrl = '' // 当前显示图的地址(复制/下载用)
let token = 0
const cache = new Map() // key → 原图 URL
const pending = new Map() // key → Promise(预取与切页会同时要同一张)
const img = el('img', { alt: '', draggable: 'false' })
const count = el('span', { className: 'iwb-album-fs-count' })
const name = el('span', { className: 'iwb-album-fs-name' })
const btnCopy = el('button', { className: 'iwb-album-fs-btn', title: '复制当前图片到剪贴板(PNG)' }, '复制')
const btnDl = el('button', { className: 'iwb-album-fs-btn', title: '下载当前图片' }, '下载')
const bar = el('div', { className: 'iwb-album-fs-bar' }, [count, name, btnCopy, btnDl])
const hint = el('div', { className: 'iwb-album-fs-hint' }, '点击空白处或按 Esc 关闭 · ← → 切换')
const btnPrev = el('button', { className: 'iwb-album-fs-nav prev', title: '上一张(←)' }, '‹')
const btnNext = el('button', { className: 'iwb-album-fs-nav next', title: '下一张(→)' }, '›')
const root = el('div', { className: 'iwb-album-fs' + (total > 1 ? '' : ' single') }, [img, btnPrev, btnNext, bar, hint])
// 原图按需读:命中缓存直接用;读盘失败就保持缩略图(不白屏、不报错)
const fullOf = (i) => {
const it = pick(i)
const key = keyAt(i)
if (cache.has(key)) return Promise.resolve(cache.get(key))
const flight = pending.get(key)
if (flight) return flight
if (!ctx.images || typeof ctx.images.dataUrl !== 'function') return Promise.resolve('')
const p = Promise.resolve(ctx.images.dataUrl(it && it.src)).then((u) => {
pending.delete(key)
if (!u) return ''
cache.set(key, u)
// 只留当前 + 左右各一张:4K 图的 dataURL 一张就几 MB,全书缓存直接爆内存
const keep = new Set([keyAt(cur), keyAt(cur + 1), keyAt(cur - 1)])
if (cache.size > FS_KEEP) for (const k of Array.from(cache.keys())) if (!keep.has(k)) cache.delete(k)
return u
}).catch(() => { pending.delete(key); return '' })
pending.set(key, p)
return p
}
const paint = (i) => {
const it = pick(i)
const my = ++token
const cached = cache.get(keyAt(i))
const thumb = st.thumbs.get(keyAt(i)) || ''
// 先用缩略图占位(切换时不会闪一块黑),原图到了再换上;缩略图也还没好就现做
if (cached) { img.src = cached; curUrl = cached }
else if (thumb) { img.src = thumb; curUrl = thumb }
else {
img.removeAttribute('src'); curUrl = ''
loadThumb(ctx, st, it, keyAt(i)).then((u) => { if (u && my === token) { img.src = u; curUrl = u } }).catch(() => {})
}
fullOf(i).then((u) => { if (u && my === token) { img.src = u; curUrl = u } }).catch(() => {})
count.textContent = (i + 1) + ' / ' + total
name.textContent = (it && it.name) || ('图 ' + (i + 1))
if (total > 1) { fullOf(i + 1).catch(() => {}); fullOf(i - 1).catch(() => {}) }
}
const go = (delta) => { cur = ((cur + delta) % total + total) % total; paint(cur) }
const close = () => closeViewer(st)
img.addEventListener('pointerdown', (e) => e.stopPropagation())
img.addEventListener('click', (e) => e.stopPropagation())
for (const [btn, delta] of [[btnPrev, -1], [btnNext, 1]]) {
btn.addEventListener('pointerdown', (e) => e.stopPropagation())
btn.addEventListener('click', (e) => { e.stopPropagation(); go(delta) })
}
// 复制 / 下载:宿主预览层原本有这两个按钮,不能因为换成自建查看器就丢掉
const flash = (msg) => {
hint.textContent = msg
clearTimeout(flash.timer)
flash.timer = setTimeout(() => { hint.textContent = '点击空白处或按 Esc 关闭 · ← → 切换' }, 1800)
}
const toPngBlob = (url) => new Promise((resolve, reject) => {
const im = new Image()
im.onload = () => {
try {
const cv = document.createElement('canvas')
cv.width = im.naturalWidth || 1; cv.height = im.naturalHeight || 1
cv.getContext('2d').drawImage(im, 0, 0)
cv.toBlob((b) => b ? resolve(b) : reject(new Error('toBlob 失败')), 'image/png')
} catch (e) { reject(e) }
}
im.onerror = () => reject(new Error('图片加载失败'))
im.src = url
})
for (const btn of [btnCopy, btnDl]) btn.addEventListener('pointerdown', (e) => e.stopPropagation())
btnDl.addEventListener('click', (e) => {
e.stopPropagation()
if (!curUrl) return
try {
const a = document.createElement('a')
a.href = curUrl
a.download = (pick(cur) && pick(cur).name) || ('image-' + (cur + 1) + '.png')
document.body.appendChild(a); a.click()
if (a.parentNode) a.parentNode.removeChild(a)
} catch (err) { flash('下载失败:' + String((err && err.message) || err)) }
})
btnCopy.addEventListener('click', async (e) => {
e.stopPropagation()
if (!curUrl) return
try {
const png = await toPngBlob(curUrl)
if (navigator.clipboard && typeof navigator.clipboard.write === 'function' && typeof ClipboardItem !== 'undefined') {
await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })])
} else {
// WKWebView 常没有 ClipboardItem ⇒ 走宿主的原生 arboard 通道(与图库预览同一实现)
const D = window.IWBDesktop
if (!D || !D.clipboardWriteImage || !(await D.clipboardWriteImage(png))) throw new Error('当前环境不支持图片剪贴板')
}
flash('已复制图片到剪贴板(PNG)')
} catch (err) { flash('复制失败:' + String((err && err.message) || err)) }
})
// 整个浮层吃掉指针事件:否则点空白会把画布的「取消选中/框选」一起触发
root.addEventListener('pointerdown', (e) => { e.stopPropagation(); if (e.target === root || e.target === bar) close() })
root.addEventListener('click', (e) => e.stopPropagation())
root.addEventListener('pointerup', (e) => e.stopPropagation())
root.addEventListener('dblclick', (e) => e.stopPropagation())
// 键盘:捕获阶段吃掉,避免宿主把 ← → 当成「微调节点」
const onKey = (e) => {
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close() }
else if (e.key === 'ArrowLeft') { e.preventDefault(); e.stopPropagation(); go(-1) }
else if (e.key === 'ArrowRight') { e.preventDefault(); e.stopPropagation(); go(1) }
}
// 滚轮也切(大图查看器的通用手势);40ms 节流,避免一次滑到底翻好几张
let wheelLock = 0
const onWheel = (e) => {
if (total < 2) return
e.preventDefault(); e.stopPropagation()
const now = Date.now()
if (now - wheelLock < 40) return
const d = Math.abs(e.deltaY) > Math.abs(e.deltaX) ? e.deltaY : e.deltaX
if (Math.abs(d) < 2) return
wheelLock = now
go(d > 0 ? 1 : -1)
}
document.body.appendChild(root)
paint(cur)
window.addEventListener('keydown', onKey, true)
window.addEventListener('wheel', onWheel, { passive: false, capture: true })
st.viewer = { root, onKey, onWheel }
}
// ── 一键清空 ────────────────────────────────────────────
function clearAll (ctx, st) {
const items = itemsOf(st.node)
if (!items.length) return
st.thumbs.clear(); st.pending.clear(); st.missing.clear()
st.checkedMissing = false // 清空后再导入要重新做一次失联检测
closeViewer(st) // 正在看大图时清空 ⇒ 先把浮层收掉(别留个没有数据的空查看器)
update(st.props, st.node, { items: [], page: 0, pageRange: null }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
}
// ── 导入:选择器 / 文件夹 / 拖入 / 固化 / 重新定位 ──────────
async function pickFiles (ctx, st, host, directory) {
if (st.busy) return
const items = itemsOf(st.node).slice()
// 桌面端:系统选择器给绝对路径 ⇒ 只引用(不复制字节)
if (ctx.images && ctx.images.canReference()) {
st.busy = '选择中…'; st.sig = ''; sync(ctx, st, st.node, st.props)
try {
const picked = await ctx.images.pick({ multiple: true, directory: !!directory })
st.busy = ''
if (!picked.length) { st.sig = ''; sync(ctx, st, st.node, st.props); return }
// 目录要展开成图片文件:pick 返回目录路径本身不是图片,之前直接过滤 ⇒ 「文件夹」点了没反应
let paths = []
if (directory) {
for (const dir of picked) {
try { const got = await ctx.images.listImages(dir); for (const f of (got || [])) paths.push(f) } catch (e) { /* 单个目录失败不阻断 */ }
}
} else paths = picked.slice()
if (!paths.length) { st.sig = ''; sync(ctx, st, st.node, st.props); return }
await addPaths(ctx, st, paths)
} catch (e) { st.busy = ''; st.sig = ''; sync(ctx, st, st.node, st.props) }
return
}
// 网页版:没有路径 ⇒ 退回文件选择 + 复制进画布存储
const input = document.createElement('input')
input.type = 'file'; input.accept = 'image/*'; input.multiple = true
input.style.display = 'none'
document.body.appendChild(input)
input.addEventListener('change', () => {
const files = Array.from(input.files || [])
document.body.removeChild(input)
if (files.length) importDropped(ctx, st, files)
})
input.click()
}
async function addPaths (ctx, st, paths) {
const list = paths.filter(isImagePath)
const items = itemsOf(st.node).slice()
for (let i = 0; i < list.length; i++) {
st.busy = '导入 ' + (i + 1) + '/' + list.length; st.sig = ''; sync(ctx, st, st.node, st.props)
const ref = await ctx.images.reference(list[i])
if (!ref || !ref.ok) continue
items.push({ src: { __file: ref.item.path }, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime, on: true })
}
st.busy = ''
st.checkedMissing = false // 新图要重新做一次失联检测(否则清空后再导入,检测永远不再跑)
update(st.props, st.node, { items }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
// 顺序预生成缩略图(避免一次读几十张原图造成内存尖峰)。
// 1.1.0:进度写进「+ 添加图片」按钮(旧实现 busy 在这里已经清空 ⇒ 导入 500 张时界面像卡死);
// 只改按钮文字、不重置 sig ⇒ 不触发整块宫格重建(重建 500 次比读盘本身还慢)。
for (let i = 0; i < items.length; i++) {
const it = items[i]
const key = thumbKeyOf(it)
if (!key || st.thumbs.has(key)) continue
st.busy = '缩略图 ' + (i + 1) + '/' + items.length
st.btnAdd.textContent = st.busy
await loadThumb(ctx, st, it, key)
}
st.busy = ''
st.btnAdd.textContent = '+ 添加图片'
st.sig = ''
sync(ctx, st, st.node, st.props)
}
async function importDropped (ctx, st, files) {
const items = itemsOf(st.node).slice()
for (let i = 0; i < files.length; i++) {
const f = files[i]
if (!f || !/^image\//i.test(f.type || '')) continue
st.busy = '复制 ' + (i + 1) + '/' + files.length; st.sig = ''; sync(ctx, st, st.node, st.props)
const dataUrl = await new Promise((resolve) => {
try { const r = new FileReader(); r.onload = () => resolve(String(r.result || '')); r.onerror = () => resolve(''); r.readAsDataURL(f) } catch (e) { resolve('') }
})
if (!dataUrl) continue
let res = null
try { res = await ctx.images.importDataUrl(dataUrl, { keepOriginal: (st.node.data && st.node.data.keepOriginal !== false) }) } catch (e) { res = null }
if (!res || !res.ok) continue
const src = res.ref || res.data
if (!src) continue
const name = f.name || ('图 ' + (items.length + 1))
items.push({ src, name: name, size: f.size || 0, on: true })
const thumb = await makeThumb(dataUrl)
// 键必须和 cellOf / loadThumb 完全一致(thumbKeyOf),否则写进缓存也命中不到
if (thumb) {
const key = thumbKeyOf(items[items.length - 1])
st.thumbs.set(key, thumb)
try { if (ctx.files) await ctx.files.put(thumbNameOf(key), thumb) } catch (e) { /* ignore */ }
}
}
st.busy = ''
st.checkedMissing = false
update(st.props, st.node, { items }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
}
// 固化:把 __file 引用换成宿主存储引用(删源文件/分享画布前用)
async function settleAll (ctx, st) {
const items = itemsOf(st.node).slice()
let done = 0
for (let i = 0; i < items.length; i++) {
const it = items[i]
const path = fileRefOf(it && it.src)
if (!path) continue
st.busy = '固化 ' + (++done) + '…'; st.sig = ''; sync(ctx, st, st.node, st.props)
try {
const res = await ctx.images.importPath(path, { keepOriginal: (st.node.data && st.node.data.keepOriginal !== false) })
if (res && res.ok && (res.ref || res.data)) items[i] = Object.assign({}, it, { src: res.ref || res.data })
} catch (e) { /* 单张失败不打断整批 */ }
}
st.busy = ''
update(st.props, st.node, { items }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
}
async function checkMissing (ctx, st, items) {
let changed = false
for (const it of items) {
const path = fileRefOf(it && it.src)
if (!path) continue
try {
const r = await ctx.images.stat(path)
const missing = !(r && r.ok && r.exists)
if (missing && !st.missing.has(path)) { st.missing.add(path); changed = true }
if (!missing && st.missing.has(path)) { st.missing.delete(path); changed = true }
} catch (e) { /* 检测失败按存在处理 */ }
}
return changed
}
// 失联重定位:点失联格 → 选一张同名/任意图片替换
async function relocate (ctx, st, index) {
if (!ctx.images || !ctx.images.canReference()) return
const items = itemsOf(st.node).slice()
const cur = items[index]
if (!cur) return
const paths = await ctx.images.pick({ multiple: false })
if (!paths || !paths.length) return
const ref = await ctx.images.reference(paths[0])
if (!ref || !ref.ok) return
const oldPath = fileRefOf(cur.src)
st.missing.delete(oldPath)
items[index] = Object.assign({}, cur, { src: { __file: ref.item.path }, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime })
update(st.props, st.node, { items }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
loadThumb(ctx, st, items[index], thumbKeyOf(items[index])).then(() => { st.sig = ''; try { sync(ctx, st, st.node, st.props) } catch (e) { /* ignore */ } })
}
// ── 注册 ────────────────────────────────────────────────
global.IWBPluginHost.register({
id: 'album',
name: '相册',
version: '1.1.2',
apiVersion: 1,
capabilities: ['nodeTypes', 'images', 'files'],
settings: {
keepOriginal: { type: 'boolean', label: '默认保留原图(不压缩)', desc: '开启后导入不进 1600 长边压缩,分辨率不损失(占用更高)。节点内可单独改。', default: true },
},
}, function (ctx) {
ctx.nodes.register({
id: 'album',
title: '相册',
icon: 'puzzle',
width: 300,
height: 470,
ports: { in: true, out: true },
defaults: { outKind: 'images', items: [], albumMode: 'per-image', density: 'S', page: 0, onlyPage: false, keepOriginal: ctx.settings.get('keepOriginal') !== false },
render: function (node, props, host) {
// 自愈(2026-11-26):旧版本/兜底路径建出来的节点可能没有 outKind,
// 那样连线规则会把相册当普通插件节点(只能连中继)。这里补写一次默认值。
try {
const d0 = node && node.data
if (d0 && d0.outKind !== 'images') {
props.onUpdate(node.id, { outKind: 'images', items: Array.isArray(d0.items) ? d0.items : [] })
}
} catch (e) { /* ignore */ }
let st = STATE.get(host)
if (!st || st.nodeId !== node.id) { st = buildShell(ctx, node, props, host); STATE.set(host, st) }
try { sync(ctx, st, node, props) } catch (e) {
// 渲染失败降级成一行可读文本(绝不让整块画布白屏)
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 */ }
}
},
})
return {}
})
})(typeof window !== 'undefined' ? window : globalThis)
+20
View File
@@ -0,0 +1,20 @@
{
"id": "album",
"name": "相册",
"version": "1.1.2",
"apiVersion": 1,
"main": "main.js",
"style": "styles.css",
"description": "一个节点装多张本地图片:宫格随节点尺寸自适应分页,一图一任务 / 批量两种模式,批量生图不用再摆一堆图片节点",
"author": "official",
"icon": "🖼️",
"tags": [
"图片",
"批量",
"出图"
],
"files": {
"main.js": "3e60b95d30bce1b734c3c1a251fa1091b8d54786eb609737f1eec9ffce3d9b22",
"styles.css": "b61e806abee9dd8889aa1a12c8791d428feacab93fac64f89c18c589de390706"
}
}
+82
View File
@@ -0,0 +1,82 @@
/* 相册节点体(2026-11-26)
* 宿主只给一块空容器(.iwb-plugin-node-body),所有排版由这里决定。
* 尺寸全部用像素而不是 rem:节点宽度是可拖拽的(264~600),rem 会跟着宿主字号漂移。
*/
.iwb-album { position: relative; display: flex; flex-direction: column; height: 100%; overflow: hidden; font-size: 11px; color: var(--iwb-node-text); }
.iwb-album-bar, .iwb-album-tools, .iwb-album-pager, .iwb-album-onepage {
display: flex; align-items: center; gap: var(--iwb-space-6); padding: var(--iwb-space-4) var(--iwb-space-8); flex: 0 0 auto;
}
.iwb-album-bar { border-bottom: 1px solid color-mix(in srgb, var(--iwb-border) 55%, transparent); height: 26px; }
.iwb-album-tools { padding-top: var(--iwb-space-2); padding-bottom: var(--iwb-space-2); }
.iwb-album-toggle { display: inline-flex; align-items: center; gap: var(--iwb-space-4); font-size: var(--iwb-font-2xs); color: var(--iwb-node-text2); white-space: nowrap; cursor: pointer; }
.iwb-album-track { width: 22px; height: 12px; border-radius: 999px; background: var(--iwb-border); position: relative; flex: 0 0 auto; transition: background .15s; }
.iwb-album-track i { position: absolute; top: 1.5px; left: 1.5px; width: 9px; height: 9px; border-radius: 50%; background: var(--iwb-panel); transition: left .15s; }
.iwb-album-track.on { background: var(--iwb-brand); }
.iwb-album-track.on i { left: 11.5px; }
.iwb-album-count { margin-left: auto; font-size: var(--iwb-font-2xs); color: var(--iwb-node-text2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.iwb-album-count b { color: var(--iwb-node-text); font-weight: 600; }
.iwb-album-btn { height: 21px; padding: 0 var(--iwb-space-8); border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-chip); background: var(--iwb-panel); color: var(--iwb-node-text2); font-size: var(--iwb-font-2xs); display: inline-flex; align-items: center; gap: var(--iwb-space-4); cursor: pointer; white-space: nowrap; }
.iwb-album-btn:hover { border-color: var(--iwb-brand); color: var(--iwb-node-text); }
.iwb-album-btn.on { border-color: var(--iwb-brand); color: var(--iwb-node-text); }
/* 清空:常驻在顶栏最右,只有相册里有图时才出现。hover 转红是为了和「添加」一类中性操作区分开。 */
.iwb-album-clear { flex: 0 0 auto; padding: 0 var(--iwb-space-6); }
.iwb-album-clear:hover { border-color: #c0392b; color: #c0392b; }
.iwb-album-seg { margin-left: auto; display: inline-flex; border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-chip); overflow: hidden; }
.iwb-album-seg span { width: 21px; height: 21px; display: inline-flex; align-items: center; justify-content: center; font-size: var(--iwb-font-2xs); color: var(--iwb-node-text2); background: var(--iwb-panel); cursor: pointer; }
.iwb-album-seg span.on { background: var(--iwb-brand); color: var(--iwb-on-brand); }
.iwb-album-grid { display: grid; gap: var(--iwb-space-4); padding: var(--iwb-space-2) var(--iwb-space-8) var(--iwb-space-6); overflow: hidden; align-content: start; flex: 1 1 auto; min-height: 0; }
/* 格子固定正方形(2026-11-26):此前高度由图片比例决定 —— 4 张 16:9 宽图会变成 22px 细条、
竖图撑到 167px,和 capacityOf() 按方形算的容量是两套账(最后一行常被裁一半)。
aspect-ratio 让每一格高 = 宽,容量因此可精确预测,宫格也终于整齐。
padding:0 必须显式写:<button> 的 UA 默认内边距会把图顶出边框。 */
.iwb-album-cell { position: relative; aspect-ratio: 1 / 1; padding: 0; border-radius: var(--iwb-radius-chip); overflow: hidden; background: color-mix(in srgb, var(--iwb-border) 55%, transparent); border: 1px solid var(--iwb-border); cursor: grab; }
.iwb-album-cell img { width: 100%; height: 100%; object-fit: cover; display: block; -webkit-user-drag: none; }
.iwb-album-cell.off img { opacity: .38; }
/* 选中线 2px → 1px(用户:太粗)。1px 在浅底上仍分得清「选中」与「描边」。 */
.iwb-album-cell.sel { outline: 1px solid var(--iwb-brand); outline-offset: -1px; }
.iwb-album-cell.missing { outline: 1px dashed #c0392b; outline-offset: -1px; }
.iwb-album-cell.missing::after { content: '失联'; position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: var(--iwb-font-2xs); color: #c0392b; background: rgba(255,255,255,.72); }
.iwb-album-cell.dragging { opacity: .45; }
.iwb-album-cell.dropbefore { box-shadow: -3px 0 0 0 var(--iwb-brand); }
.iwb-album-idx { position: absolute; left: var(--iwb-space-2); top: var(--iwb-space-2); min-width: 14px; height: 14px; padding: 0 var(--iwb-space-4); border-radius: 999px; background: rgba(0,0,0,.55); color: #fff; font-size: var(--iwb-font-2xs); display: flex; align-items: center; justify-content: center; }
/* 批次角标已移除(2026-11-26):顶栏「N 张 → M 个任务」已经说清楚,每格右上角再挂个「1」是重复信息。
位置让给删除按钮:右下角要留给放大镜。 */
.iwb-album-del { position: absolute; right: var(--iwb-space-2); top: var(--iwb-space-2); width: 15px; height: 15px; border-radius: 50%; background: var(--iwb-panel); color: var(--iwb-node-text2); font-size: 11px; line-height: 1; display: flex; align-items: center; justify-content: center; opacity: 0; cursor: pointer; }
.iwb-album-cell:hover .iwb-album-del { opacity: 1; }
/* 放大镜:右下角,hover 才出现(静息态不抢视觉,和 × 一致)。
17px 圆 / 12px 图标:再小镜片就缩成一团白点。
z-index 高于图与角标:1.1.0 时它被节点内预览层(z-index 9)盖住 ⇒ 用户反馈「滑过去就点不到」,
那层已在 1.1.1 删除;这里仍显式抬一层,避免以后再加浮层时重犯。 */
.iwb-album-zoom { position: absolute; right: var(--iwb-space-2); bottom: var(--iwb-space-2); z-index: 3; width: 17px; height: 17px; border-radius: 50%; background: var(--iwb-panel); color: var(--iwb-node-text2); display: flex; align-items: center; justify-content: center; opacity: 0; cursor: zoom-in; transition: opacity .12s; }
.iwb-album-cell:hover .iwb-album-zoom, .iwb-album-cell:focus-within .iwb-album-zoom { opacity: 1; }
.iwb-album-zoom:hover { color: var(--iwb-brand); }
.iwb-album-zoom svg { width: 12px; height: 12px; display: block; }
/* 全屏查看器(1.1.2):挂在 document.body 上,所以是 position: fixed + 自备层级。
810 = 宿主图片预览层(--iwb-z-preview: 800)之上一层,盖住画布但不抢系统弹窗。
为什么不用宿主 onPreview:那个接口只收「已解析好的 URL 列表」,整本相册要一次全转 dataURL。 */
.iwb-album-fs { position: fixed; inset: 0; z-index: 810; display: flex; align-items: center; justify-content: center; background: rgba(10, 12, 18, .92); cursor: zoom-out; }
.iwb-album-fs img { max-width: 92vw; max-height: 88vh; width: auto; height: auto; object-fit: contain; display: block; border-radius: 8px; box-shadow: 0 8px 40px rgba(0, 0, 0, .5); cursor: default; }
.iwb-album-fs-nav { position: fixed; top: 50%; transform: translateY(-50%); width: 46px; height: 64px; padding: 0; border: none; border-radius: 8px; background: rgba(255, 255, 255, .1); color: #fff; font-size: 30px; line-height: 1; display: flex; align-items: center; justify-content: center; cursor: pointer; }
.iwb-album-fs-nav:hover { background: rgba(255, 255, 255, .22); }
.iwb-album-fs-nav.prev { left: 18px; }
.iwb-album-fs-nav.next { right: 18px; }
.iwb-album-fs.single .iwb-album-fs-nav { display: none; }
/* 计数条要放「复制/下载」按钮,所以本身吃事件;点条上空白仍然算点外部(关闭) */
.iwb-album-fs-bar { position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%); display: flex; align-items: center; gap: 10px; max-width: 80vw; padding: 6px 14px; border-radius: 999px; background: rgba(255, 255, 255, .12); color: #fff; font-size: 12px; }
.iwb-album-fs-btn { height: 22px; padding: 0 9px; border: 1px solid rgba(255, 255, 255, .22); border-radius: 999px; background: rgba(255, 255, 255, .08); color: #fff; font-size: 11px; cursor: pointer; flex: 0 0 auto; }
.iwb-album-fs-btn:hover { background: rgba(255, 255, 255, .22); }
.iwb-album-fs-count { font-variant-numeric: tabular-nums; }
.iwb-album-fs-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; opacity: .72; }
.iwb-album-fs-hint { position: fixed; left: 50%; bottom: 6px; transform: translateX(-50%); color: rgba(255, 255, 255, .45); font-size: 11px; white-space: nowrap; pointer-events: none; }
.iwb-album-add { border: 1px dashed var(--iwb-border); background: transparent; color: var(--iwb-node-text2); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--iwb-space-2); font-size: var(--iwb-font-2xs); border-radius: var(--iwb-radius-chip); cursor: pointer; }
.iwb-album-add b { font-size: 15px; line-height: 1; font-weight: 600; }
.iwb-album-pager { border-top: 1px solid color-mix(in srgb, var(--iwb-border) 55%, transparent); height: 26px; }
.iwb-album-onepage { border-top: 1px solid color-mix(in srgb, var(--iwb-border) 55%, transparent); height: 26px; color: var(--iwb-node-text2); font-size: var(--iwb-font-2xs); }
.iwb-album-pg { display: inline-flex; align-items: center; border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-chip); background: var(--iwb-panel); }
.iwb-album-pg span { width: 17px; height: 17px; display: flex; align-items: center; justify-content: center; font-size: var(--iwb-font-2xs); cursor: pointer; color: var(--iwb-node-text2); }
.iwb-album-pg b { font-weight: 600; color: var(--iwb-node-text); padding: 0 2px; font-size: var(--iwb-font-2xs); }
.iwb-album-mini { display: inline-flex; align-items: center; gap: var(--iwb-space-4); margin-left: auto; font-size: var(--iwb-font-2xs); color: var(--iwb-node-text2); white-space: nowrap; }
.iwb-album-hint { margin: 0 8px 4px; padding: 4px 6px; border-radius: var(--iwb-radius-chip); background: rgba(107,114,128,.10); border: 1px solid rgba(107,114,128,.22); color: var(--iwb-node-text2); font-size: var(--iwb-font-2xs); line-height: 1.45; }
.iwb-album-hint b { color: var(--iwb-node-text); }
.iwb-album-empty { flex: 1 1 auto; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--iwb-space-6); color: var(--iwb-node-text2); font-size: 11px; text-align: center; padding: 0 var(--iwb-space-12); }
.iwb-album-empty .box { width: 66px; height: 50px; border: 1.5px dashed var(--iwb-border); border-radius: var(--iwb-radius-chip); display: flex; align-items: center; justify-content: center; font-size: var(--iwb-font-xl); color: var(--iwb-node-text2); }
+8 -4
View File
@@ -47,16 +47,20 @@
function clear (node) { while (node.firstChild) node.removeChild(node.firstChild) }
// v1.4.1:底栏按钮改用图标(窄栏里「刷新/设置」会被挤成竖排两行)
// v1.7.1:14px 在底栏里太小(齿轮细节几乎看不清)。按宿主 design-tokens.md §3.8
// 图标尺寸闭集 14/16/18 取最大档 --iwb-icon-lg(18),描边按规范 1.6;
// 命中区 ≥28×28 由 styles.css 的按钮尺寸兜住(图形放大不等于点击区变大)。
var SVG_NS = 'http://www.w3.org/2000/svg'
var ICON_PX = 18
function iconBtn (label, build, title) {
var b = el('button', { class: 'iwb-btn iwb-btn-sm iwb-gal-icobtn', title: title || label, 'aria-label': label })
var svg = document.createElementNS(SVG_NS, 'svg')
svg.setAttribute('viewBox', '0 0 16 16')
svg.setAttribute('width', '14')
svg.setAttribute('height', '14')
svg.setAttribute('width', String(ICON_PX))
svg.setAttribute('height', String(ICON_PX))
svg.setAttribute('fill', 'none')
svg.setAttribute('stroke', 'currentColor')
svg.setAttribute('stroke-width', '1.5')
svg.setAttribute('stroke-width', '1.6')
svg.setAttribute('stroke-linecap', 'round')
svg.setAttribute('stroke-linejoin', 'round')
svg.setAttribute('aria-hidden', 'true')
@@ -590,7 +594,7 @@
global.IWBPluginHost.register({
id: 'gallery',
name: '图库',
version: '1.7.0',
version: '1.7.1',
apiVersion: 1,
capabilities: ['panels', 'gallery'],
data: { schemaVersion: 1, maxBytes: 65536 },
+3 -3
View File
@@ -1,7 +1,7 @@
{
"id": "gallery",
"name": "图库",
"version": "1.7.0",
"version": "1.7.1",
"apiVersion": 1,
"main": "main.js",
"style": "styles.css",
@@ -13,7 +13,7 @@
"图库"
],
"files": {
"main.js": "77b8e95c06c6811fdee3a832195e2b76bc6197d8bfdf9df0a47a52b6b4dfb38f",
"styles.css": "35ae17de8b0f3bddab9cbef6270cd8bbf5153c9ecf6ed2b4f06216f6fef45b8b"
"main.js": "c4f27a759742720804280a009a802d6955b742b5cc4b81cb29e3c533830e867c",
"styles.css": "1dfd72b60bcaea9c43e103ba9758113efec02b6241d08fa0ab9c75d7848afb55"
}
}
+17 -6
View File
@@ -24,25 +24,36 @@
.iwb-gal-count { font-size: 11px; color: var(--iwb-text2); white-space: nowrap; }
.iwb-gal-sel { font-size: 11px; color: var(--iwb-brand); white-space: nowrap; }
.iwb-gal-status { font-size: 11px; color: var(--iwb-text2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 0 1 auto; max-width: none; }
.iwb-gal-tools { display: flex; align-items: center; gap: 0; flex: 0 0 auto; margin-left: auto; }
/* v1.7.1:图标放大后三个按钮不再紧贴(4px 是 spacing 闭集值) */
.iwb-gal-tools { display: flex; align-items: center; gap: 4px; flex: 0 0 auto; margin-left: auto; }
/* ---- 图标按钮:无外框、无底色,只在悬停时给一点反馈 ---- */
/* ---- 图标按钮:无外框、无底色,只在悬停时给一点反馈 ----
v1.7.1:命中区 20×20 → 28×28(design-tokens.md §3.8「≥28×28」),
图形 14 → var(--iwb-icon-lg) 18;CSS 尺寸覆盖 SVG 的 presentation attribute,
属性里的 18 只作宿主 token 缺失时的兜底。 */
.iwb-gal-foot .iwb-gal-icobtn,
.iwb-gal-foot .iwb-gal-icobtn:hover,
.iwb-gal-foot .iwb-gal-icobtn:active {
width: 20px; height: 20px; min-width: 20px; padding: 0; box-sizing: border-box;
width: 28px; height: 28px; min-width: 28px; padding: 0; box-sizing: border-box;
display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto;
border: 0; box-shadow: none; background: transparent; border-radius: 6px;
color: var(--iwb-text2); line-height: 1; transform: none;
}
.iwb-gal-foot .iwb-gal-icobtn svg { display: block; pointer-events: none; }
.iwb-gal-foot .iwb-gal-icobtn svg {
display: block; pointer-events: none;
width: var(--iwb-icon-lg, 18px); height: var(--iwb-icon-lg, 18px);
}
.iwb-gal-foot .iwb-gal-icobtn:hover { background: var(--iwb-layer2); color: var(--iwb-text); }
.iwb-gal-foot .iwb-gal-icobtn:focus-visible { outline: 2px solid color-mix(in srgb, var(--iwb-brand) 60%, transparent); outline-offset: 1px; }
.iwb-gal-setbtn-on { color: var(--iwb-brand); background: var(--iwb-layer2); }
/* ---- 设置浮层(三个下拉不占前台) ---- */
/* ---- 设置浮层(三个下拉不占前台) ----
bottom 随底栏高度走:底栏 = padding-top 6 + border 1 + 按钮 28,再加容器底 4 → 39,
取 40 让浮层正好停在底栏上沿之外;仍用 34 会被放大后的图标压住。
z-index 按 §3.6 层级表走 --iwb-z-ctx-menu(面板内菜单浮层):原先裸写 30,
这行一改动就被 token-lint 当成新增裸值拦下;91 仍低于 curtain(100)/command(120)。 */
.iwb-gal-settings {
position: absolute; right: 8px; bottom: 34px; z-index: 30; width: 176px; max-width: calc(100% - 16px);
position: absolute; right: 8px; bottom: 40px; z-index: var(--iwb-z-ctx-menu, 91); width: 176px; max-width: calc(100% - 16px);
display: flex; flex-direction: column; gap: 8px; padding: 8px 10px;
background: var(--iwb-layer); border: 1px solid var(--iwb-border); border-radius: 8px;
box-shadow: 0 6px 18px rgba(0, 0, 0, .14);
+17 -6
View File
@@ -1,4 +1,15 @@
[
{
"id": "album",
"dir": "album",
"main": "main.js",
"style": "styles.css",
"version": "1.1.2",
"files": {
"main.js": "3e60b95d30bce1b734c3c1a251fa1091b8d54786eb609737f1eec9ffce3d9b22",
"styles.css": "b61e806abee9dd8889aa1a12c8791d428feacab93fac64f89c18c589de390706"
}
},
{
"id": "batch-export",
"file": "plugin-batch-export.44c13ac8e6d9.js",
@@ -22,10 +33,10 @@
"dir": "gallery",
"main": "main.js",
"style": "styles.css",
"version": "1.7.0",
"version": "1.7.1",
"files": {
"main.js": "77b8e95c06c6811fdee3a832195e2b76bc6197d8bfdf9df0a47a52b6b4dfb38f",
"styles.css": "35ae17de8b0f3bddab9cbef6270cd8bbf5153c9ecf6ed2b4f06216f6fef45b8b"
"main.js": "c4f27a759742720804280a009a802d6955b742b5cc4b81cb29e3c533830e867c",
"styles.css": "1dfd72b60bcaea9c43e103ba9758113efec02b6241d08fa0ab9c75d7848afb55"
}
},
{
@@ -44,10 +55,10 @@
"dir": "promptlib",
"main": "main.js",
"style": "styles.css",
"version": "1.13.0",
"version": "1.13.1",
"files": {
"main.js": "2108d09bd7cd1d96dfeb8499dac7adacbda659b222606f7d072a2bf8cbf5361a",
"styles.css": "e2ba84f2e4251f461e77c78ca39fc2b5022f169cb1a4eae0aa7ef786f28b6863"
"main.js": "720b8aaa040e0310e6c7d7d2fe1ad6ed0a0e437de77d56bf1a2905355c795e13",
"styles.css": "203d61278ad98b2a07053851d0cfb42dd826564e5ae4d068ec950423cd09c46b"
}
},
{
+12
View File
@@ -128,5 +128,17 @@
"标注",
"便签"
]
},
"album": {
"name": "相册",
"desc": "一个节点装多张本地图片:宫格随节点尺寸自适应分页,一图一任务 / 批量两种模式,批量生图不用再摆一堆图片节点",
"author": "official",
"icon": "🖼️",
"color": "#eef2f6",
"tags": [
"图片",
"批量",
"出图"
]
}
}
+4 -4
View File
@@ -1212,11 +1212,11 @@
})
title.title = v.label || v.key
var sum = el('span', { class: 'iwb-plp-vsum', text: summaryOf(v) })
var iBtn = el('button', { class: 'iwb-plp-vi' + (isOpen ? ' is-open' : ''), type: 'button', title: '说明', text: 'i' })
var refreshSum = function () { sum.textContent = summaryOf(v) }
row.appendChild(caret); row.appendChild(title); row.appendChild(sum); row.appendChild(iBtn)
row.appendChild(caret); row.appendChild(title); row.appendChild(sum)
// v1.13.1:整行点击是唯一入口。旧的 i 圆按钮只做「强制展开」,与整行重复,
// 还占掉 22px 把摘要往左挤;展开态由 caret 与 hover 反馈表达。
row.addEventListener('click', function () { open[v.key] = !isOpen; paint() })
iBtn.addEventListener('click', function (e) { e.stopPropagation(); open[v.key] = true; paint() })
item.appendChild(row)
if (isOpen) {
var nameIn = el('input', { class: 'iwb-input iwb-plp-vname', placeholder: '变量名称(节点上最多显示 4 字)' })
@@ -2204,7 +2204,7 @@
global.IWBPluginHost.register({
id: 'promptlib',
name: '提示词库',
version: '1.13.0',
version: '1.13.1',
apiVersion: 1,
capabilities: ['panels', 'promptlib', 'nodeTypes', 'canvas', 'canvasWrite'],
data: { schemaVersion: 3, maxBytes: 4 * 1024 * 1024 },
+3 -3
View File
@@ -1,7 +1,7 @@
{
"id": "promptlib",
"name": "提示词库",
"version": "1.13.0",
"version": "1.13.1",
"apiVersion": 1,
"main": "main.js",
"style": "styles.css",
@@ -13,7 +13,7 @@
"提示词"
],
"files": {
"main.js": "2108d09bd7cd1d96dfeb8499dac7adacbda659b222606f7d072a2bf8cbf5361a",
"styles.css": "e2ba84f2e4251f461e77c78ca39fc2b5022f169cb1a4eae0aa7ef786f28b6863"
"main.js": "720b8aaa040e0310e6c7d7d2fe1ad6ed0a0e437de77d56bf1a2905355c795e13",
"styles.css": "203d61278ad98b2a07053851d0cfb42dd826564e5ae4d068ec950423cd09c46b"
}
}
+12 -8
View File
@@ -416,11 +416,9 @@ body.iwb-plp-dragging, body.iwb-plp-dragging *{user-select:none!important;-webki
.iwb-plp-eright{flex:0 0 auto;width:300px;min-width:190px;max-width:460px;display:flex;flex-direction:column;min-height:0;background:var(--iwb-plugin-surface,#fafbfc);border:1px solid var(--iwb-border,#e6e8ec);border-radius:10px;padding:8px}
.iwb-plp-vars{flex:1 1 auto;min-height:0;display:flex;flex-direction:column}
.iwb-plp-vrows{flex:1 1 auto;min-height:0;overflow:auto}
.iwb-plp-vitem{padding:4px 0;border-bottom:1px dashed var(--iwb-border,#eceef2)}
.iwb-plp-vitem{padding:4px 0}
.iwb-plp-vrow2{display:flex;align-items:center;gap:6px}
.iwb-plp-vname{flex:1 1 auto;min-width:0;height:32px}
.iwb-plp-vi{flex:0 0 auto;width:24px;height:24px;padding:0;border-radius:50%;border:1px solid var(--iwb-border,#dfe3e9);background: var(--iwb-plugin-card, #fff);color: var(--iwb-text-dim, #9aa1ac);font-size:11px;line-height:22px;text-align:center}
.iwb-plp-vi.is-open{background: var(--iwb-plp-accent-soft, #f1ecff);border-color: var(--iwb-plp-accent-border, #d8cbff);color: var(--iwb-plp-accent, #5a3fd0)}
.iwb-plp-vdesc{width:100%;height:28px;margin-top: 6px;border-style:dashed;background: var(--iwb-field, #fbfcfd);font-size: 12px;color: var(--plp-c3, #6b7280)}
/* v1.12.0:变量编辑器折叠两态(收起一行名称+摘要,展开四字段)与内容多行框 */
.iwb-plp-vrow2{cursor:pointer}
@@ -446,13 +444,10 @@ body.iwb-plp-dragging, body.iwb-plp-dragging *{user-select:none!important;-webki
.iwb-plp-dialog .iwb-plp-esplit:hover{background: var(--iwb-plugin-hover, #e7e9ee)}
.iwb-plp-dialog .iwb-plp-esplit::before{content:'';display:block;width:2px;height:30px;border-radius: 6px;background: var(--iwb-plugin-hover, #d7dbe2)}
.iwb-plp-dialog .iwb-plp-eright{background:transparent;border:0;padding:2px 0 0}
.iwb-plp-dialog .iwb-plp-vitem{border:0;padding:2px 0}
.iwb-plp-dialog .iwb-plp-vitem{padding:2px 0}
.iwb-plp-dialog .iwb-plp-vrow2{gap:6px}
.iwb-plp-dialog .iwb-plp-vname{background: var(--iwb-field, #fbfcfd);border: 1px solid var(--iwb-plugin-border, #eceef2);border-radius:8px;height:32px;padding:0 10px;font-size: 13px;color: var(--iwb-text, #33383f)}
.iwb-plp-dialog .iwb-plp-vname:focus{background: var(--iwb-plugin-card, #fff);border-color: var(--iwb-plp-accent-border, #cfc3ff);box-shadow:0 0 0 3px rgba(107,77,255,.08)}
.iwb-plp-dialog .iwb-plp-vi{background:transparent;border:0;color: var(--iwb-text-dim, #aab0ba);width:22px;height:22px;line-height:20px}
.iwb-plp-dialog .iwb-plp-vi:hover{background: var(--iwb-plugin-inset, #eef0f4);color: var(--plp-c3, #6b7280)}
.iwb-plp-dialog .iwb-plp-vi.is-open{background: var(--iwb-plp-accent-soft, #f1ecff);color: var(--iwb-plp-accent, #5a3fd0)}
.iwb-plp-dialog .iwb-plp-vdesc{background: var(--iwb-field, #fbfcfd);border: 1px dashed var(--iwb-plugin-border, #e2e6ec);border-radius: 8px;height:28px;margin-top:4px}
.iwb-plp-dialog .iwb-plp-lrow span{color: var(--iwb-text2, #8a919c);font-size: 12px}
.iwb-plp-dialog .iwb-plp-lrow .iwb-input{background: var(--iwb-field, #fbfcfd);border: 1px solid var(--iwb-plugin-border, #eceef2);border-radius:8px;height:32px}
@@ -464,7 +459,6 @@ body.iwb-plp-dragging, body.iwb-plp-dragging *{user-select:none!important;-webki
.iwb-plp-ewrap .iwb-plp-etext:focus{background:transparent;border:0;box-shadow:none}
.iwb-plp-hl{position:absolute;inset:0;padding:10px 12px;overflow:hidden;white-space:pre-wrap;word-wrap:break-word;font-size:13px;line-height:1.9;color: var(--iwb-text2, #5b6472);pointer-events:none;z-index:0}
.iwb-plp-hlvar{color: var(--iwb-text, #1d2129);font-weight:600}
.iwb-plp-dialog .iwb-plp-vi.is-open{background: var(--iwb-plugin-hover, #eef0f3);color: var(--iwb-text2, #5b6472)}
.iwb-plp-dialog .iwb-plp-vdesc{background:transparent;border: 1px dashed var(--iwb-plugin-border, #dfe3e9)}
.iwb-plp-dvar{background:transparent;color: var(--iwb-text, #1d2129);font-weight:600;padding:0}
.iwb-plp-hres{height:6px;margin: -4px 0 0;cursor:ns-resize;flex:0 0 auto;border-radius: 6px}
@@ -592,3 +586,13 @@ body.iwb-plp-dragging, body.iwb-plp-dragging *{user-select:none!important;-webki
.iwb-plp-dialog .iwb-plp-dvar{color:var(--iwb-plp-accent,#5a3fd0);background:var(--iwb-plp-accent-soft,#f1ecff);border-radius:6px;padding:0 2px}
/* 回滚开关:若真机发现任何点击/光标异常,把下行打开即回到 v1.8.20 纯 textarea 状态。
.iwb-plp-ewrap .iwb-plp-hl{display:none!important} */
/* v1.13.1:变量栏去掉 i 圆按钮,按设计 token 在「行与行之间」画分割线(位置 2)。
依据 design-tokens.md §3.11:--iwb-set-divider 是容器内行间线,首行不画线。
注意该变量只在 .iwb-settings-modal 作用域定义,插件面板不在其中 ⇒ 按同一公式就地兜底,
否则会掉到全强度 --iwb-border(比规范深一档)。暗色下 --iwb-border 自动换值。
用相邻兄弟选择器,首项自然不画、末项之后也没有线;标题下与展开字段前都不另画线,
避免一屏出现三层线。整行 hover + 展开态 caret 接替原来 i 按钮的「可点击」提示。 */
.iwb-plp-vitem + .iwb-plp-vitem{border-top:var(--iwb-bw, 1px) solid var(--iwb-set-divider, color-mix(in srgb, var(--iwb-border) 55%, transparent));padding-top:var(--iwb-space-8)}
.iwb-plp-dialog .iwb-plp-vrow2{padding:0 var(--iwb-space-4)}
.iwb-plp-dialog .iwb-plp-vrow2:hover{background:var(--iwb-plugin-hover);border-radius:var(--iwb-radius-control, var(--iwb-radius-card))}
.iwb-plp-vitem.is-open .iwb-plp-vcaret{color:var(--iwb-plp-accent, var(--iwb-text2))}
+4 -2
View File
@@ -39,7 +39,7 @@ const sourceModules = [
'clipboard-native.js',
'generation-size-policy.js',
'generation-request-shape.js',
'image-preview-derive.js',
'generation-endpoint.js',
'canvas-actions.js',
'canvas-node-factory.js',
'storage-contract.js',
@@ -59,17 +59,18 @@ const sourceModules = [
'runtime-execution-context.js',
'runtime-diagnostic-record.js',
'runtime-metrics.js',
'image-file-ref.js',
'image-blob-store.js',
'runtime-crash-log.js',
'storage-health.js',
'storage-config-shape.js',
'generation-default-model.js',
'storage-indexeddb.js',
'storage-workspace.js',
'storage-groups.js',
'storage-outputs.js',
'storage-backup.js',
'storage-zip.js',
'plugin-archive.js',
'plugin-promptlib-backup.js',
'runtime-constants.js',
'canvas-store.js',
@@ -134,6 +135,7 @@ const sourceModules = [
'ui-connect-menu.js',
'ui-gen-config-panel.js',
'canvas-webview.js',
'plugin-api-images.js',
'plugin-files-policy.js',
'image-prompt-cover.js',
]
+57
View File
@@ -0,0 +1,57 @@
'use strict'
/* e2e 已知红报告(2026-11-24)
*
* 为什么需要:57 个 spec 里有 16 条长期红(环境性 8 + 真缺陷 8),
* 没有清单时「全绿」和「红了」都不可信 —— 新红会被旧红淹没。
*
* 用法:先起测试服,然后
* node scripts/e2e-known-red-report.js 只跑清单内的 spec
* node scripts/e2e-known-red-report.js --all 跑全部 spec(慢,谨慎)
*
* 退出码:0 = 失败数不超过清单(或更少);1 = 出现**新增**失败(需要人看)。
* 注意:本脚本不进 verify:ci(e2e 只在 PR 跑,省 CI 额度)。
*/
const fs = require('fs')
const path = require('path')
const { execFileSync } = require('child_process')
const root = path.resolve(__dirname, '..')
const list = JSON.parse(fs.readFileSync(path.join(root, 'tests', 'fixtures', 'e2e-known-red.json'), 'utf8'))
const only = process.argv.includes('--all') ? null : list.entries.map((e) => e.spec)
function runSpec (spec) {
const args = ['test', spec, '--reporter=line']
try {
const out = execFileSync('npx', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
return { failed: 0, tail: out.trim().split('\n').slice(-2).join(' | ') }
} catch (e) {
const out = String((e && e.stdout) || '') + String((e && e.stderr) || '')
const m = /(\d+) failed/.exec(out)
return { failed: m ? Number(m[1]) : -1, tail: out.trim().split('\n').slice(-2).join(' | ') }
}
}
let worst = 0
const rows = []
const targets = only || fs.readdirSync(path.join(root, 'tests')).filter((f) => f.endsWith('.spec.js')).map((f) => 'tests/' + f)
for (const spec of targets) {
const known = list.entries.find((e) => e.spec === spec)
const r = runSpec(spec)
const allowed = known ? known.knownFailures : 0
const delta = r.failed - allowed
if (delta > 0) worst = Math.max(worst, delta)
rows.push({ spec, failed: r.failed, allowed, delta, kind: known ? known.kind : 'unlisted' })
}
console.log('\ne2e 已知红对照(基线 ' + list.measuredVersion + ' · ' + list.measuredAt + ')\n')
console.log('spec'.padEnd(46) + 'now'.padEnd(6) + 'known'.padEnd(7) + 'delta')
for (const r of rows) {
const mark = r.delta > 0 ? ' ← 新增红' : (r.failed === 0 && r.allowed > 0 ? ' ← 已修复,可移出清单' : '')
console.log(r.spec.padEnd(46) + String(r.failed).padEnd(6) + String(r.allowed).padEnd(7) + (r.delta > 0 ? '+' + r.delta : String(r.delta)) + mark)
}
if (worst > 0) {
console.log('\n有新增失败:请判断是回归还是清单过期(修好后记得删条目)。')
process.exit(1)
}
console.log('\n没有新增失败。')
+99
View File
@@ -0,0 +1,99 @@
'use strict'
/* 行数棘轮指标的**唯一测量实现** + 文档硬数字的**唯一改写/校验规则**(2026-11-24,P0-②)
*
* 为什么需要:MAX_APP_JS_LINES 等上限被抄进 CONTRIBUTING.md 与 architecture-current-state.md,
* 此前**没有任何校验**,实际已漂 415 行(文档写 8,700,真实上限 9,115)。
* sync-facts(改写)与 architecture-facts-guard(断言)若各写一套正则,会出现
* 「同步器说改了、守卫说没改」—— 所以规则只放在这里。
*
* 口径与 tests/source-text-ratchet-test.js 一致(那边是权威断言方)。
*/
const fs = require('fs')
const path = require('path')
const root = path.resolve(__dirname, '..')
const NL = String.fromCharCode(10)
const fmtInt = (n) => Number(n).toLocaleString('en-US')
function readCaps () {
const src = fs.readFileSync(path.join(root, 'tests', 'source-text-ratchet-test.js'), 'utf8')
const num = (name) => {
const m = new RegExp('MAX_' + name + ' = ([0-9.]+)').exec(src)
if (!m) throw new Error('未找到 MAX_' + name + '(棘轮测试改名了?)')
return Number(m[1])
}
return {
appJsLines: num('APP_JS_LINES'),
workbenchLines: num('WORKBENCH_LINES'),
appComponentLines: num('APP_COMPONENT_LINES'),
appJsShare: num('APP_JS_SHARE')
}
}
function measure () {
const appSrc = fs.readFileSync(path.join(root, 'app.js'), 'utf8')
const appLines = appSrc.split(NL).length
const srcDir = path.join(root, 'src')
const srcFiles = fs.readdirSync(srcDir).filter((n) => n.endsWith('.js'))
let srcLines = 0
for (const f of srcFiles) srcLines += fs.readFileSync(path.join(srcDir, f), 'utf8').split(NL).length
// Workbench():按大括号深度找函数结尾(与棘轮测试同一算法)
const lines = appSrc.split(NL)
const start = lines.findIndex((l) => l.startsWith(' function Workbench('))
let wbLines = 0
if (start >= 0) {
let depth = 0, started = false
for (let j = start; j < lines.length; j++) {
for (const ch of lines[j]) {
if (ch === '{') { depth++; started = true } else if (ch === '}') depth--
}
if (started && depth === 0) { wbLines = j - start + 1; break }
}
}
const share = appLines / (appLines + srcLines)
return {
appLines,
srcFiles: srcFiles.length,
srcLines,
workbenchLines: wbLines,
share,
sharePct: (share * 100).toFixed(1),
caps: readCaps()
}
}
/* ── 文档规则:build(m, ...captures) 返回整段替换文本 ── */
const RULES = {
contributing: [
{ key: 'MAX_APP_JS_LINES', re: /`MAX_APP_JS_LINES` \| \*\*[\d,]+\*\*/g, build: (m) => '`MAX_APP_JS_LINES` | **' + fmtInt(m.caps.appJsLines) + '**' },
{ key: 'MAX_WORKBENCH_LINES', re: /`MAX_WORKBENCH_LINES` \| \*\*[\d,]+\*\*/g, build: (m) => '`MAX_WORKBENCH_LINES` | **' + fmtInt(m.caps.workbenchLines) + '**' },
{ key: 'MAX_APP_COMPONENT_LINES', re: /`MAX_APP_COMPONENT_LINES` \| \*\*[\d,]+\*\*/g, build: (m) => '`MAX_APP_COMPONENT_LINES` | **' + fmtInt(m.caps.appComponentLines) + '**' }
],
arch: [
{ key: 'appLines', re: /(`app\.js` = 单 IIFE )\*\*[\d,]+ 行\*\*/g, build: (m, p1) => p1 + '**' + fmtInt(m.appLines) + ' 行**' },
{ key: 'appJsCap', re: /(绝对上限 )[\d,]+/g, build: (m, p1) => p1 + fmtInt(m.caps.appJsLines) },
{ key: 'workbenchLines', re: /(`Workbench\(\)` = )\*\*[\d,]+ 行\*\*/g, build: (m, p1) => p1 + '**' + fmtInt(m.workbenchLines) + ' 行**' },
{ key: 'workbenchCap', re: /((上限 )\*\*[\d,]+\*\*(,余量 )\d+/g, build: (m, p1, p2) => p1 + '**' + fmtInt(m.caps.workbenchLines) + '**' + p2 + String(Math.max(0, m.caps.workbenchLines - m.workbenchLines)) },
{ key: 'sharePct', re: /(现 )\*\*[\d.]+%\*\*(,2026-11-12 起)/g, build: (m, p1, p2) => p1 + '**' + m.sharePct + '%**' + p2 },
{ key: 'srcFiles', re: /(现 )\*\*[\d,]+\*\* 个模块/g, build: (m, p1) => p1 + '**' + fmtInt(m.srcFiles) + '** 个模块' },
{ key: 'srcLines', re: /(个模块 \/ )[\d,]+ 行/g, build: (m, p1) => p1 + fmtInt(m.srcLines) + ' 行' }
]
}
/** 改写文档里的硬数字;返回 { text, changed: [key] }。changed 为空 = 已经一致。 */
function rewriteDoc (kind, text, m) {
const rules = RULES[kind] || []
let out = text
const changed = []
for (const rule of rules) {
const before = out
out = out.replace(rule.re, (all, ...caps) => rule.build(m, ...caps.slice(0, -2)))
if (out !== before) changed.push(rule.key)
}
return { text: out, changed }
}
module.exports = { measure, readCaps, rewriteDoc, RULES, fmtInt }
+25 -3
View File
@@ -85,10 +85,21 @@ for (const [re, rep] of archWant) {
arch = arch.replace(re, rep)
if (arch !== before) archChanged = true
}
// ── ④b 行数棘轮硬数字(2026-11-24,P0-②)──
// 为什么单列一步:CONTRIBUTING / 架构文档里抄着 MAX_APP_JS_LINES 等上限,
// 此前无人校验,实测已漂 415 行。测量与改写规则在 scripts/ratchet-metrics.js
// (守卫 tests/architecture-facts-guard-test.js 用同一份规则断言,口径不会分叉)。
const rm = require('./ratchet-metrics')
const metrics = rm.measure()
const archRatchet = rm.rewriteDoc('arch', arch, metrics)
arch = archRatchet.text
if (archRatchet.changed.length) archChanged = true
if (archChanged) {
diffs.push(' ✗ 架构文档计数过时(可 --write 自动修 4 处)')
diffs.push(' ✗ 架构文档计数/棘轮数字过时(可 --write 自动修;棘轮项:' + (archRatchet.changed.join(', ') || '无') + ')')
if (WRITE) write(archPath, arch)
} else report.push(' · 架构文档计数(一致)')
} else report.push(' · 架构文档计数与棘轮数字(一致)')
// 单测文件数:test:unit 里 node tests/*.js 的个数
const pkg = JSON.parse(read('package.json'))
@@ -98,13 +109,24 @@ const contribPath = 'CONTRIBUTING.md'
let contrib = read(contribPath)
const contribRe = /test:unit {2,}\d+ 个单测文件/
const m = contrib.match(contribRe)
let contribChanged = false
if (m) {
const cur = Number(m[0].match(/(\d+) 个/)[1])
if (cur !== unitCount) {
contribChanged = true
diffs.push(' ✗ CONTRIBUTING 单测文件数: ' + cur + ' → ' + unitCount)
if (WRITE) { write(contribPath, contrib.replace(contribRe, 'test:unit ' + unitCount + ' 个单测文件')); }
contrib = contrib.replace(contribRe, 'test:unit ' + unitCount + ' 个单测文件')
} else report.push(' · CONTRIBUTING 单测文件数: ' + unitCount + '(一致)')
}
// 棘轮上限三个数字(同一份规则,见 scripts/ratchet-metrics.js)
const contribRatchet = rm.rewriteDoc('contributing', contrib, metrics)
if (contribRatchet.changed.length) {
contribChanged = true
diffs.push(' ✗ CONTRIBUTING 棘轮上限过时:' + contribRatchet.changed.join(', '))
}
contrib = contribRatchet.text
if (contribChanged) { if (WRITE) write(contribPath, contrib) }
else report.push(' · CONTRIBUTING 棘轮上限(一致)')
// ── 输出 ──
console.log('\n事实同步器(' + (WRITE ? '写入模式' : 'dry-run') + ')\n')
+1 -1
View File
@@ -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 = ['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']
// v3.25.41(M1):目录化插件试点 —— 这些 id 产出 <id>/{manifest.json,main.js},其余仍是单文件(双轨兼容)
// ⚠️ 2026-11-20 修正:桌面包不随包发插件(scripts/strip-plugins.js),插件只能从市场装,
// 而市场目前只支持单文件 ⇒ 目录形态暂不用于生产插件,等 M3(zip 安装)落地再启用。
+2 -2
View File
@@ -3,7 +3,7 @@
<title>插件开发规范 · Image Workbench</title>
<link rel="icon" href="/assets/favicon.png" type="image/png">
<link rel="apple-touch-icon" href="/assets/logo.png">
<link rel="stylesheet" href="/assets/style.css?v=3.26.62-mwuouzfu">
<link rel="stylesheet" href="/assets/style.css?v=3.26.72-mwvypdt5">
<style>
.devdoc{max-width:860px;margin:0 auto;padding:40px 0 72px;color:var(--ink,#1b1f24);font-size:15px;line-height:1.75}
.devdoc h1{font-size:38px;line-height:1.2;margin:8px 0 18px}
@@ -33,7 +33,7 @@
</div>
<div class="right">
<a class="btn" href="/plugins/">插件市场</a>
<a class="btn primary" href="/download/">下载 v3.26.62</a>
<a class="btn primary" href="/download/">下载 v3.26.72</a>
</div>
</div></nav>
<main>
+45 -5
View File
@@ -57,13 +57,13 @@
<h2>下载</h2>
<div class="row">
<div class="name">macOS · Apple Silicon<div class="hint">M1 / M2 / M3 / M4</div></div>
<div class="meta">版本 3.26.62 · 8.4 MB · .dmg<div class="hash">sha256 5a611553eff11552…</div></div>
<a class="btn" href="/updates/darwin-aarch64/image-workbench_3.26.62_aarch64.dmg?h=5a611553eff1">下载</a>
<div class="meta">版本 3.26.72 · 8.4 MB · .dmg<div class="hash">sha256 22f1570936b2387c…</div></div>
<a class="btn" href="/updates/darwin-aarch64/image-workbench_3.26.72_aarch64.dmg?h=22f1570936b2">下载</a>
</div>
<div class="row">
<div class="name">macOS · Intel<div class="hint">x86_64</div></div>
<div class="meta">版本 3.26.62 · 8.8 MB · .dmg<div class="hash">sha256 4e240818ab18dfb2…</div></div>
<a class="btn" href="/updates/darwin-x86_64/image-workbench_3.26.62_x64.dmg?h=4e240818ab18">下载</a>
<div class="meta">版本 3.26.72 · 8.8 MB · .dmg<div class="hash">sha256 c7750cf048e45e95…</div></div>
<a class="btn" href="/updates/darwin-x86_64/image-workbench_3.26.72_x64.dmg?h=c7750cf048e4">下载</a>
</div>
<div class="row">
<div class="name">Windows · x64<div class="hint">需要 WebView2</div></div>
@@ -97,6 +97,46 @@
</ol>
<h2>历史版本</h2>
<div class="row">
<div class="name">3.26.72<div class="hint">设置默认落通用标签 / 左下更多菜单可正常弹出 / 模型删除按钮默认隐藏 / 默认模型标识始终可见</div></div>
<div class="meta">2026-11-25<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.26.71<div class="hint">设置默认通用 tab / 左下快捷菜单+升级图标 / 模型行样式 / 新建配置节点默认模型</div></div>
<div class="meta">2026-11-25<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.26.70<div class="hint">修浏览器面板/独立窗口中 target=_blank 链接无反应(原地打开)</div></div>
<div class="meta">2026-11-25<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.26.69<div class="hint">相册 1.1.0:方形宫格 / 一键清空 / 放大镜 hover 预览 + 点击全屏;修复相册的图在组合节点与参考图里显示为破图</div></div>
<div class="meta">2026-11-25<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
</div>
<div class="row">
<div class="name">3.26.68</div>
<div class="meta">2026-11-25<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
</div>
<div class="row">
<div class="name">3.26.67</div>
<div class="meta">2026-11-25<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.26.66</div>
<div class="meta">2026-11-24<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.26.65</div>
<div class="meta">2026-11-24<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
</div>
<div class="row">
<div class="name">3.26.64</div>
<div class="meta">2026-11-24<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.26.63</div>
<div class="meta">2026-11-24<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.26.62</div>
<div class="meta">2026-11-24<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
@@ -539,7 +579,7 @@
</div>
<div class="foot">
本页由 <code>scripts/gen-release-page.js</code> 从 releases.json 生成 · 源码 <a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop">git.maqiart.eu.org</a> · 更新于 2026-11-24
本页由 <code>scripts/gen-release-page.js</code> 从 releases.json 生成 · 源码 <a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop">git.maqiart.eu.org</a> · 更新于 2026-11-25
</div>
</div></div>
+16 -16
View File
@@ -4,7 +4,7 @@
<meta name="description" content="本地优先的 AI 生图无限画布:节点式工作流、插件按需安装、数据全部留在本机。">
<link rel="icon" href="/assets/favicon.png" type="image/png">
<link rel="apple-touch-icon" href="/assets/logo.png">
<link rel="stylesheet" href="/assets/style.css?v=3.26.62-mwuouzfu">
<link rel="stylesheet" href="/assets/style.css?v=3.26.72-mwvypdt5">
</head><body>
<nav><div class="wrap inner">
<a class="brand" href="/"><img class="logo" src="/assets/logo.png" alt="" width="26" height="26">Image Workbench</a>
@@ -17,20 +17,20 @@
</div>
<div class="right">
<a class="btn" href="/plugins/">插件市场</a>
<a class="btn primary" href="/download/">下载 v3.26.62</a>
<a class="btn primary" href="/download/">下载 v3.26.72</a>
</div>
</div></nav>
<main>
<section class="hero hero-art">
<div class="hero-bg"><img src="/assets/painting.jpg?v=3.26.62-mwuouzfu" alt=""></div>
<div class="hero-bg"><img src="/assets/painting.jpg?v=3.26.72-mwvypdt5" alt=""></div>
<div class="hero-veil"></div>
<div class="wrap">
<span class="kicker">v3.26.62 · macOS / Windows · 数据在本地</span>
<span class="kicker">v3.26.72 · macOS / Windows · 数据在本地</span>
<h1>本地优先的<br>AI 生图无限画布</h1>
<p class="sub">用节点把「参考图 → 提示词 → 批量生成 → 图库」串成一条生产线。<br>图片、提示词、模型配置全部留在你自己的电脑里,插件按需安装。</p>
<div class="cta">
<a class="btn primary lg" href="/download/">下载 v3.26.62</a>
<a class="btn lg" href="/plugins/">浏览 12 个插件</a>
<a class="btn primary lg" href="/download/">下载 v3.26.72</a>
<a class="btn lg" href="/plugins/">浏览 13 个插件</a>
</div>
<div class="meta">支持 macOS 12+ 与 Windows 10 1803+ · 安装包约 7 MB · 无需登录</div>
</div></section>
@@ -53,6 +53,12 @@
<h2>插件:本体不带,需要的自己装</h2>
<p class="lead">应用本体不再内置插件。设置里打开市场,点「安装」,重启即可用;不需要的点一下就能关掉。</p>
<div class="grid c3">
<div class="pcard" data-name="相册 album 一个节点装多张本地图片:宫格随节点尺寸自适应分页,一图一任务 / 批量两种模式,批量生图不用再摆一堆图片节点 图片 批量 出图" data-tags="图片,批量,出图">
<div class="head"><span class="av" style="background:#eef2f6">🖼️</span>
<div><div class="nm">相册</div><div class="ver">v1.1.2 · 官方</div></div></div>
<div class="desc">一个节点装多张本地图片:宫格随节点尺寸自适应分页,一图一任务 / 批量两种模式,批量生图不用再摆一堆图片节点</div>
<div class="tags"><span class="tag">图片</span><span class="tag">批量</span><span class="tag">出图</span></div>
</div>
<div class="pcard" data-name="批量出图 batch-export 资源中心勾选节点,串行批量生成并打包 zip 下载 出图 批处理" data-tags="出图,批处理">
<div class="head"><span class="av" style="background:#e8f0fe">🗂️</span>
<div><div class="nm">批量出图</div><div class="ver">v1.2.2 · 官方</div></div></div>
@@ -73,7 +79,7 @@
</div>
<div class="pcard" data-name="图库 gallery 右栏图片墙:筛选/多选/双击预览/插入画布/下载/删除(数据由客户端提供) 资源 图库" data-tags="资源,图库">
<div class="head"><span class="av" style="background:#eef2f6">🖼️</span>
<div><div class="nm">图库</div><div class="ver">v1.7.0 · 官方</div></div></div>
<div><div class="nm">图库</div><div class="ver">v1.7.1 · 官方</div></div></div>
<div class="desc">右栏图片墙:筛选/多选/双击预览/插入画布/下载/删除(数据由客户端提供)</div>
<div class="tags"><span class="tag">资源</span><span class="tag">图库</span></div>
</div>
@@ -83,21 +89,15 @@
<div class="desc">左栏收藏的节点组:分组/改名/删除,拖到画布实例化(数据由客户端提供)</div>
<div class="tags"><span class="tag">资源</span><span class="tag">节点组</span></div>
</div>
<div class="pcard" data-name="提示词库 promptlib 右栏提示词列表:搜索/分组/收藏/新建编辑/插入画布/复制(数据由客户端提供) 资源 提示词" data-tags="资源,提示词">
<div class="head"><span class="av" style="background:#eef2f6">📖</span>
<div><div class="nm">提示词库</div><div class="ver">v1.13.0 · 官方</div></div></div>
<div class="desc">右栏提示词列表:搜索/分组/收藏/新建编辑/插入画布/复制(数据由客户端提供)</div>
<div class="tags"><span class="tag">资源</span><span class="tag">提示词</span></div>
</div>
</div>
<div style="margin-top:22px"><a class="btn" href="/plugins/">查看全部 12 个插件</a></div>
<div style="margin-top:22px"><a class="btn" href="/plugins/">查看全部 13 个插件</a></div>
</div></section>
<section class="section"><div class="wrap">
<h2>下载 Image Workbench</h2>
<p class="lead">选你的平台。装过一次之后,以后在应用内「设置 → 通用 → 版本与更新」就能一键升级。</p>
<div class="dl"><a href="/updates/darwin-aarch64/image-workbench_3.26.62_aarch64.dmg?h=5a611553eff1"><div class="n">macOS · Apple Silicon</div><div class="s">M1 / M2 / M3 / M4 · 8.4 MB · .dmg</div></a>
<a href="/updates/darwin-x86_64/image-workbench_3.26.62_x64.dmg?h=4e240818ab18"><div class="n">macOS · Intel</div><div class="s">x86_64 · 8.8 MB · .dmg</div></a>
<div class="dl"><a href="/updates/darwin-aarch64/image-workbench_3.26.72_aarch64.dmg?h=22f1570936b2"><div class="n">macOS · Apple Silicon</div><div class="s">M1 / M2 / M3 / M4 · 8.4 MB · .dmg</div></a>
<a href="/updates/darwin-x86_64/image-workbench_3.26.72_x64.dmg?h=c7750cf048e4"><div class="n">macOS · Intel</div><div class="s">x86_64 · 8.8 MB · .dmg</div></a>
<div class="none"><div class="n">Windows · x64</div><div class="s">暂未提供</div></div></div>
<div style="margin-top:20px;color:#9ca3af;font-size:12.5px">安装包未做 Apple 公证 / Windows 代码签名,首次打开需手动放行一次,细节见 <a href="/download/" style="text-decoration:underline">下载页</a>。</div>
</div></section>
+54 -19
View File
@@ -1,7 +1,42 @@
{
"version": 2,
"updatedAt": "2026-11-24T10:52:45.289Z",
"updatedAt": "2026-11-25T06:15:44.425Z",
"plugins": [
{
"id": "album",
"name": "相册",
"desc": "一个节点装多张本地图片:宫格随节点尺寸自适应分页,一图一任务 / 批量两种模式,批量生图不用再摆一堆图片节点",
"author": "official",
"icon": "🖼️",
"color": "#eef2f6",
"tags": [
"图片",
"批量",
"出图"
],
"version": "1.1.2",
"apiVersion": 1,
"bundle": "plugins/album-1.1.2.zip",
"bundleSize": 58341,
"bundleSha256": "bac290a61a55f49299f018b234f490dce6f3b057c729b3baf4029c49b0a46150",
"files": [
{
"path": "manifest.json",
"sha256": "a959ab40d7090f66285c1dacfd5ef975f5fe2df0ab9cb2abf9f21e18eda9efe8",
"size": 593
},
{
"path": "main.js",
"sha256": "3e60b95d30bce1b734c3c1a251fa1091b8d54786eb609737f1eec9ffce3d9b22",
"size": 46682
},
{
"path": "styles.css",
"sha256": "b61e806abee9dd8889aa1a12c8791d428feacab93fac64f89c18c589de390706",
"size": 10756
}
]
},
{
"id": "batch-export",
"name": "批量出图",
@@ -112,26 +147,26 @@
"资源",
"图库"
],
"version": "1.7.0",
"version": "1.7.1",
"apiVersion": 1,
"bundle": "plugins/gallery-1.7.0.zip",
"bundleSize": 38168,
"bundleSha256": "0289819359794af974f9ac7ac5bb4b1b483cfe8ebb54af4e9bb09325a5292fc0",
"bundle": "plugins/gallery-1.7.1.zip",
"bundleSize": 39338,
"bundleSha256": "9c7182ae46be2dd50a9bf72d15864a525bd6b91d831d617f9cf83e1dee795d27",
"files": [
{
"path": "manifest.json",
"sha256": "923879db7a998af026a1c7d61969ed8dc3045ef9704739365c411baead7520bd",
"sha256": "0109c1fb03524301614e56ec60936e50a5a04641488f74b10630b07651742888",
"size": 526
},
{
"path": "main.js",
"sha256": "77b8e95c06c6811fdee3a832195e2b76bc6197d8bfdf9df0a47a52b6b4dfb38f",
"size": 32137
"sha256": "c4f27a759742720804280a009a802d6955b742b5cc4b81cb29e3c533830e867c",
"size": 32480
},
{
"path": "styles.css",
"sha256": "35ae17de8b0f3bddab9cbef6270cd8bbf5153c9ecf6ed2b4f06216f6fef45b8b",
"size": 5195
"sha256": "1dfd72b60bcaea9c43e103ba9758113efec02b6241d08fa0ab9c75d7848afb55",
"size": 6022
}
]
},
@@ -180,26 +215,26 @@
"资源",
"提示词"
],
"version": "1.13.0",
"version": "1.13.1",
"apiVersion": 1,
"bundle": "plugins/promptlib-1.13.0.zip",
"bundleSize": 184934,
"bundleSha256": "af0116e04312e98d2915dd67a6610082c3593e425e29732004b40dfc0bf8b676",
"bundle": "plugins/promptlib-1.13.1.zip",
"bundleSize": 185072,
"bundleSha256": "574f064df96fab91f612044b30c0ae64dc525ed0b4bef55365fa690ecd4415b4",
"files": [
{
"path": "manifest.json",
"sha256": "9b801ebab1896dd2032a802389b616794632f56846521574225e23e2681600db",
"sha256": "ea9ead4872a0d1ceea910164ed0189445dd0774f31090abbf0b769b818ba4ddc",
"size": 541
},
{
"path": "main.js",
"sha256": "2108d09bd7cd1d96dfeb8499dac7adacbda659b222606f7d072a2bf8cbf5361a",
"size": 138415
"sha256": "720b8aaa040e0310e6c7d7d2fe1ad6ed0a0e437de77d56bf1a2905355c795e13",
"size": 138363
},
{
"path": "styles.css",
"sha256": "e2ba84f2e4251f461e77c78ca39fc2b5022f169cb1a4eae0aa7ef786f28b6863",
"size": 45668
"sha256": "203d61278ad98b2a07053851d0cfb42dd826564e5ae4d068ec950423cd09c46b",
"size": 45858
}
]
},
+14 -6
View File
@@ -3,7 +3,7 @@
<title>插件市场 · Image Workbench</title>
<link rel="icon" href="/assets/favicon.png" type="image/png">
<link rel="apple-touch-icon" href="/assets/logo.png">
<link rel="stylesheet" href="/assets/style.css?v=3.26.62-mwuouzfu">
<link rel="stylesheet" href="/assets/style.css?v=3.26.72-mwvypdt5">
</head><body>
<nav><div class="wrap inner">
<a class="brand" href="/"><img class="logo" src="/assets/logo.png" alt="" width="26" height="26">Image Workbench</a>
@@ -16,18 +16,20 @@
</div>
<div class="right">
<a class="btn" href="/plugins/">插件市场</a>
<a class="btn primary" href="/download/">下载 v3.26.62</a>
<a class="btn primary" href="/download/">下载 v3.26.72</a>
</div>
</div></nav>
<main>
<section class="hero" style="padding:64px 0 8px;text-align:left"><div class="wrap">
<h1 style="font-size:40px;margin:0">插件市场</h1>
<p class="sub" style="margin:14px 0 0;text-align:left;max-width:720px">共 12 个插件。安装方式:应用内 <b>设置 → 插件 → 浏览</b>,点「安装」后重启生效。</p>
<p class="sub" style="margin:14px 0 0;text-align:left;max-width:720px">共 13 个插件。安装方式:应用内 <b>设置 → 插件 → 浏览</b>,点「安装」后重启生效。</p>
</div></section>
<section class="section" style="border-top:0;padding-top:24px"><div class="wrap">
<div style="display:flex;gap:8px;flex-wrap:wrap;margin:0 0 18px" id="chips">
<button class="tag on" data-tag="" style="cursor:pointer;background:#111;color:#fff;border-color:#111;padding:5px 12px">全部</button>
<button class="tag" data-tag="出图" style="cursor:pointer;padding:5px 12px">出图</button>
<button class="tag" data-tag="图片" style="cursor:pointer;padding:5px 12px">图片</button>
<button class="tag" data-tag="批量" style="cursor:pointer;padding:5px 12px">批量</button>
<button class="tag" data-tag="出图" style="cursor:pointer;padding:5px 12px">出图</button>
<button class="tag" data-tag="批处理" style="cursor:pointer;padding:5px 12px">批处理</button>
<button class="tag" data-tag="画布" style="cursor:pointer;padding:5px 12px">画布</button>
<button class="tag" data-tag="效率" style="cursor:pointer;padding:5px 12px">效率</button>
@@ -48,6 +50,12 @@
</div>
<input id="q" placeholder="搜索插件,例如:出图、抠图、矢量…" style="width:100%;max-width:420px;height:40px;padding:0 14px;border:1px solid var(--line);border-radius:10px;font-size:14px;outline:none;margin-bottom:22px">
<div class="grid c3" id="list">
<div class="pcard" data-name="相册 album 一个节点装多张本地图片:宫格随节点尺寸自适应分页,一图一任务 / 批量两种模式,批量生图不用再摆一堆图片节点 图片 批量 出图" data-tags="图片,批量,出图">
<div class="head"><span class="av" style="background:#eef2f6">🖼️</span>
<div><div class="nm">相册</div><div class="ver">v1.1.2 · 官方</div></div></div>
<div class="desc">一个节点装多张本地图片:宫格随节点尺寸自适应分页,一图一任务 / 批量两种模式,批量生图不用再摆一堆图片节点</div>
<div class="tags"><span class="tag">图片</span><span class="tag">批量</span><span class="tag">出图</span></div>
</div>
<div class="pcard" data-name="批量出图 batch-export 资源中心勾选节点,串行批量生成并打包 zip 下载 出图 批处理" data-tags="出图,批处理">
<div class="head"><span class="av" style="background:#e8f0fe">🗂️</span>
<div><div class="nm">批量出图</div><div class="ver">v1.2.2 · 官方</div></div></div>
@@ -68,7 +76,7 @@
</div>
<div class="pcard" data-name="图库 gallery 右栏图片墙:筛选/多选/双击预览/插入画布/下载/删除(数据由客户端提供) 资源 图库" data-tags="资源,图库">
<div class="head"><span class="av" style="background:#eef2f6">🖼️</span>
<div><div class="nm">图库</div><div class="ver">v1.7.0 · 官方</div></div></div>
<div><div class="nm">图库</div><div class="ver">v1.7.1 · 官方</div></div></div>
<div class="desc">右栏图片墙:筛选/多选/双击预览/插入画布/下载/删除(数据由客户端提供)</div>
<div class="tags"><span class="tag">资源</span><span class="tag">图库</span></div>
</div>
@@ -80,7 +88,7 @@
</div>
<div class="pcard" data-name="提示词库 promptlib 右栏提示词列表:搜索/分组/收藏/新建编辑/插入画布/复制(数据由客户端提供) 资源 提示词" data-tags="资源,提示词">
<div class="head"><span class="av" style="background:#eef2f6">📖</span>
<div><div class="nm">提示词库</div><div class="ver">v1.13.0 · 官方</div></div></div>
<div><div class="nm">提示词库</div><div class="ver">v1.13.1 · 官方</div></div></div>
<div class="desc">右栏提示词列表:搜索/分组/收藏/新建编辑/插入画布/复制(数据由客户端提供)</div>
<div class="tags"><span class="tag">资源</span><span class="tag">提示词</span></div>
</div>
+232 -1
View File
@@ -1,8 +1,239 @@
{
"app": "Image Workbench",
"subtitle": "本地优先的 AI 生图无限画布 · 桌面版(Tauri v2)",
"updatedAt": "2026-11-24T12:46:26.452Z",
"updatedAt": "2026-11-25T10:09:47.498Z",
"releases": [
{
"version": "3.26.72",
"date": "2026-11-25",
"notes": "设置默认落通用标签 / 左下更多菜单可正常弹出 / 模型删除按钮默认隐藏 / 默认模型标识始终可见",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.26.72_aarch64.dmg",
"size": 8793414,
"sha256": "22f1570936b2387c64b771616bdecff30143b3f91d421162822cb9a84c416ba5",
"h": "22f1570936b2",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.26.72_x64.dmg",
"size": 9201924,
"sha256": "c7750cf048e45e95f91d6c9965d23f5bb1bcfbea034deae0508b40a430832077",
"h": "c7750cf048e4",
"kind": "dmg"
}
}
},
{
"version": "3.26.71",
"date": "2026-11-25",
"notes": "设置默认通用 tab / 左下快捷菜单+升级图标 / 模型行样式 / 新建配置节点默认模型",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.26.71_aarch64.dmg",
"size": 8790500,
"sha256": "9fd7510d3a0efda1b78f5508207e09b96477f1227036868f147be70d846623e5",
"h": "9fd7510d3a0e",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.26.71_x64.dmg",
"size": 9204632,
"sha256": "469ba89d533d153bf188277ff42294503944e0144c687652395ca5f94c8e6e78",
"h": "469ba89d533d",
"kind": "dmg"
}
}
},
{
"version": "3.26.70",
"date": "2026-11-25",
"notes": "修浏览器面板/独立窗口中 target=_blank 链接无反应(原地打开)",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.26.70_aarch64.dmg",
"size": 8794989,
"sha256": "b8e5bd9bd293796465880a690eb31b75e5de72815f104a55dac44b7c0f0428b4",
"h": "b8e5bd9bd293",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.26.70_x64.dmg",
"size": 9202029,
"sha256": "a24037c72b6d138f05c8580496ba28a85c0dacf5d76544ce441e1ce63a956b0a",
"h": "a24037c72b6d",
"kind": "dmg"
}
}
},
{
"version": "3.26.69",
"date": "2026-11-25",
"notes": "相册 1.1.0:方形宫格 / 一键清空 / 放大镜 hover 预览 + 点击全屏;修复相册的图在组合节点与参考图里显示为破图",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.26.69_aarch64.dmg",
"size": 8792893,
"sha256": "a2e7c95b77b17a488c35853e28a8ba2ba9184490894b6a0adcd9be6c5c7c0963",
"h": "a2e7c95b77b1",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.26.69_x64.dmg",
"size": 9198980,
"sha256": "965196f1fd525c68adbd8f33480e9d9eb6ca6fa64cf6272e82242c9411cde71f",
"h": "965196f1fd52",
"kind": "dmg"
},
"windows-x86_64": {
"file": "updates/windows-x86_64/image-workbench_3.26.69_x64-setup.exe",
"size": 5047113,
"sha256": "9cd82072998f7f1e66ddfca2001d1fa349348609a0a88cabf39f0cf8e6505717",
"h": "9cd82072998f",
"kind": "exe"
}
}
},
{
"version": "3.26.68",
"date": "2026-11-25",
"notes": "",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.26.68_aarch64.dmg",
"size": 8794173,
"sha256": "e292ea2070a7784a88c9b352e085d1dbdf53007f03b196e88185030d70d6838e",
"h": "e292ea2070a7",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.26.68_x64.dmg",
"size": 9201527,
"sha256": "3a704502137ba79e7de85cc6caae1e4a494b1ad8598c27ca6847d9a309cc6f73",
"h": "3a704502137b",
"kind": "dmg"
},
"windows-x86_64": {
"file": "updates/windows-x86_64/image-workbench_3.26.68_x64-setup.exe",
"size": 5042000,
"sha256": "f24945ef7ed51e67d56fa99b93e7b7e48a2bc776f9d39a4eac77aecd313e4925",
"h": "f24945ef7ed5",
"kind": "exe"
}
}
},
{
"version": "3.26.67",
"date": "2026-11-25",
"notes": "",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.26.67_aarch64.dmg",
"size": 8795642,
"sha256": "86a4da63d310e156020dd5d886d891d009714d65619b71b60e6ac8d98c8573c1",
"h": "86a4da63d310",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.26.67_x64.dmg",
"size": 9199623,
"sha256": "7805bbf8e1f7b9259d1cbe40671264186ed5a3251749eccad414eeb54d022c72",
"h": "7805bbf8e1f7",
"kind": "dmg"
}
}
},
{
"version": "3.26.66",
"date": "2026-11-24",
"notes": "",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.26.66_aarch64.dmg",
"size": 8791028,
"sha256": "006c2eb759677551e0be33a6217da9a7f06a3dc5c58de94779b919495141d261",
"h": "006c2eb75967",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.26.66_x64.dmg",
"size": 9204812,
"sha256": "ccd775a42b79d716bc72067a48df0d7cfd5a264f61c4cbaf627b7c76319b9d14",
"h": "ccd775a42b79",
"kind": "dmg"
}
}
},
{
"version": "3.26.65",
"date": "2026-11-24",
"notes": "",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.26.65_aarch64.dmg",
"size": 8796444,
"sha256": "92cb36b5ec3cd67704b4251439f3d87992c2d3ff3e5374f37a7c5842064079de",
"h": "92cb36b5ec3c",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.26.65_x64.dmg",
"size": 9183466,
"sha256": "914195b27b80a57195246b03e1089d2962fa51742dd0de9ab8140cc6993fd24a",
"h": "914195b27b80",
"kind": "dmg"
},
"windows-x86_64": {
"file": "updates/windows-x86_64/image-workbench_3.26.65_x64-setup.exe",
"size": 5011895,
"sha256": "0ff0624e2447e3025b6eacd83a6dab13cc06771914f0a20f0a012a1d32066533",
"h": "0ff0624e2447",
"kind": "exe"
}
}
},
{
"version": "3.26.64",
"date": "2026-11-24",
"notes": "",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.26.64_aarch64.dmg",
"size": 8802792,
"sha256": "8eb46ce43dc22c2fe84b8dc60d50d0fd3ada88c3f8820e55b00d4f4b90e77b95",
"h": "8eb46ce43dc2",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.26.64_x64.dmg",
"size": 9192936,
"sha256": "30cd128a4d5135bfbe85a9e61b4d6de12c5d35b89b798df69f6e8d960ad56e00",
"h": "30cd128a4d51",
"kind": "dmg"
}
}
},
{
"version": "3.26.63",
"date": "2026-11-24",
"notes": "",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.26.63_aarch64.dmg",
"size": 8804160,
"sha256": "f120d77388000a6c98d64937c575cca98965e2b64475563a7e40970d083238fe",
"h": "f120d7738800",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.26.63_x64.dmg",
"size": 9193234,
"sha256": "45b39f572b643cff2b6e9a560887b4747c1e817a701bee982700a405bc0e4fe2",
"h": "45b39f572b64",
"kind": "dmg"
}
}
},
{
"version": "3.26.62",
"date": "2026-11-24",
+1 -1
View File
@@ -1983,7 +1983,7 @@ dependencies = [
[[package]]
name = "image-workbench"
version = "3.26.62"
version = "3.26.72"
dependencies = [
"arboard",
"base64 0.22.1",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "image-workbench"
version = "3.26.62"
version = "3.26.72"
description = "无限画布 · 生图工作台桌面版"
authors = ["malongan"]
license = ""
+69 -1
View File
@@ -1,6 +1,7 @@
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use tauri::menu::{Menu, MenuItem};
use tauri::tray::TrayIconBuilder;
use tauri::webview::NewWindowResponse;
use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, WebviewUrl, WebviewWindowBuilder, WindowEvent};
use tauri_plugin_fs::FsExt; // 提供 fs_scope():运行时给「资料目录」授权
@@ -187,6 +188,29 @@ fn app_memory_mb() -> u64 {
}
}
// 把用户**显式选择**的路径加进本次运行的 fs scope(2026-11-26,相册「只引用本地文件」用)。
// 为什么单独一条命令:dialog 选中的外部图片不在「资料目录」里,fs 插件默认拒绝读写;
// 这里只授权调用方传进来的具体路径,不扩大 $HOME 之类的面。
#[tauri::command]
fn grant_paths(app: AppHandle, paths: Vec<String>) -> Result<Vec<String>, String> {
let mut ok: Vec<String> = Vec::new();
for raw in paths {
let p = std::path::PathBuf::from(&raw);
if !p.is_absolute() {
continue;
}
let granted = if p.is_dir() {
app.fs_scope().allow_directory(&p, true).is_ok()
} else {
app.fs_scope().allow_file(&p).is_ok()
};
if granted {
ok.push(p.to_string_lossy().to_string());
}
}
Ok(ok)
}
#[tauri::command]
fn grant_dir(app: AppHandle, dir: String, record: Option<bool>) -> Result<String, String> {
let p = std::path::PathBuf::from(&dir);
@@ -474,11 +498,24 @@ async fn open_browser_window(app: AppHandle, url: String) -> Result<bool, String
return Ok(true);
}
let app_for_new_window = app.clone();
WebviewWindowBuilder::new(&app, label, WebviewUrl::External(parsed))
.title(&title)
.inner_size(1200.0, 820.0)
.min_inner_size(800.0, 600.0)
.center()
.on_new_window(move |url, _features| {
// 独立浏览器窗口里点画板等 target="_blank" 链接:原地导航,不弹新窗口。
if let Some(url) = new_window_url(url) {
if let Some(win) = app_for_new_window.get_webview_window("browser") {
let _ = win.navigate(url.clone());
if let Some(host) = url.host_str().filter(|h| !h.is_empty()) {
let _ = win.set_title(host);
}
}
}
NewWindowResponse::Deny
})
.build()
.map_err(|e| e.to_string())?;
// 恢复上次浏览器窗口的位置/大小;没有记录时保持上面的居中默认值。
@@ -596,6 +633,17 @@ fn cwv_parse(url: &str) -> Result<url::Url, String> {
Ok(parsed)
}
// 新窗口请求(target="_blank" / window.open)在原生 webview 里默认被静默丢弃:
// wry 的 macOS delegate 没拿到 handler 时直接返回 None,所以用户看到的是「点了没反应」。
// 统一策略:只放行 http/https,并拒绝弹窗,由调用方把 URL 导航到当前页面。
fn new_window_url(url: url::Url) -> Option<url::Url> {
if matches!(url.scheme(), "http" | "https") {
Some(url)
} else {
None
}
}
// 位置 + 尺寸打包成一次 set_bounds 的入参。
//
// ox/oy 是「原生层坐标原点到 DOM 坐标原点」的差值(见 canvas_webview_metrics 的注释)。
@@ -720,6 +768,8 @@ async fn canvas_webview_ensure(
cwv_log(&app, "ensure:fail 取不到 main 窗口的 Window 句柄");
return Err("主窗口不存在".into());
};
let app_for_new_window = app.clone();
let label_for_new_window = label.clone();
let built = window.add_child(
tauri::webview::WebviewBuilder::new(&label, WebviewUrl::External(parsed.clone()))
.on_page_load(|wv, payload| {
@@ -736,6 +786,24 @@ async fn canvas_webview_ensure(
"cwv-page",
serde_json::json!({ "id": id, "kind": kind, "url": payload.url().to_string() }),
);
})
.on_new_window(move |url, _features| {
// 左侧栏面板 / 画布网页节点共用这个 builder:画板详情等新开标签链接
// 统一在当前 webview 原地打开,地址栏由 cwv-page 事件自动回填。
if let Some(url) = new_window_url(url) {
if let Some(wv) = app_for_new_window.get_webview(&label_for_new_window) {
if let Err(e) = wv.navigate(url) {
cwv_log(
&app_for_new_window,
&format!(
"new-window:navigate-err label={} err={}",
label_for_new_window, e
),
);
}
}
}
NewWindowResponse::Deny
}),
tauri::LogicalPosition::new(x + ox, y + oy),
tauri::LogicalSize::new(w.max(2.0), h.max(2.0)),
@@ -918,7 +986,7 @@ pub fn run() {
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.invoke_handler(tauri::generate_handler![open_app_data_dir, open_data_subpath, grant_dir, copy_tree, check_update, install_update, clipboard_read_image, clipboard_write_image, clipboard_write_text, clipboard_read_text, open_external_url, open_browser_window, browser_control, browser_state, canvas_webview_ensure, canvas_webview_bounds, canvas_webview_navigate, canvas_webview_action, canvas_webview_state, canvas_webview_close_all, canvas_webview_metrics, notify_desktop,
.invoke_handler(tauri::generate_handler![open_app_data_dir, open_data_subpath, grant_paths, grant_dir, copy_tree, check_update, install_update, clipboard_read_image, clipboard_write_image, clipboard_write_text, clipboard_read_text, open_external_url, open_browser_window, browser_control, browser_state, canvas_webview_ensure, canvas_webview_bounds, canvas_webview_navigate, canvas_webview_action, canvas_webview_state, canvas_webview_close_all, canvas_webview_metrics, notify_desktop,
app_memory_mb])
.setup(|app| {
if cfg!(debug_assertions) {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "image-workbench",
"version": "3.26.62",
"version": "3.26.72",
"identifier": "com.malongan.imageworkbench",
"build": {
"frontendDist": "../dist",
+5 -1
View File
@@ -27,7 +27,11 @@
// 所以这里做一次归一化:声明了就按 prompt 节点参与下面的规则判定。
// 内置节点没有 outKind 字段 ⇒ 所有规则逐字不变(零回归,现有画布连不上的仍然连不上)。
const srcIsPromptOut = !!(src && src.data && src.data.outKind === 'prompt')
const st = srcIsPromptOut ? 'prompt' : src.type
// 相册(2026-11-26):声明 outKind:'images' ⇒ 下游当作「图片来源」参与规则(能进生图/组合/中继)。
const srcIsImagesOut = !!(src && src.data && src.data.outKind === 'images')
const st = srcIsPromptOut ? 'prompt' : (srcIsImagesOut ? 'ref' : src.type)
// 相册自己只接受文本类输入(提示词/文本/组合/批量/中继):它自带图片,不吃别人的图。
if (dst && dst.data && dst.data.outKind === 'images' && st !== 'prompt' && st !== 'textout' && st !== 'combine' && st !== 'batch' && st !== 'relay' && !srcIsPromptOut) return '相册节点只接受提示词/文本类输入'
// batch 多输出:不同来源端口可连到同一目标;普通节点同对仅一条边
if (src.type !== 'batch' && hasEdge) return '这两个节点已经连接'
// 提示词节点原来只收参考图 / 中继(避免提示词串联);样式节点要能进来做二次编辑,单独放行
+69
View File
@@ -0,0 +1,69 @@
/* default-gen-model.js —— 「新建配置节点默认模型」的纯函数(2026-11-25)
*
* 配置顶层 defaultGen = { providerId, model, keyGroup },决定新建 gen 节点预选的服务商 / 模型 / 密钥组。
* 本模块只算值、不碰 I/O、不碰 DOM;宿主把结果同步到 DEFAULTS.gen 模板即可让三条建节点路径统一生效。
*
* 关键约定:
* ① 生效值始终可算(未配置也回退主服务首个可见模型),保证「默认」标识与新建节点取值一致;
* 一个可用模型都没有时才返回 null,宿主保留 DEFAULTS.gen 硬编码兜底。
* ② 已配置但指向的模型被删 / 关闭可见 ⇒ 同样回退,不会让新建节点失去模型。
* ③ 与 LLM 渠道的 defaultModel 完全隔离,不读不写 llm.*。
*/
;(function (global) {
'use strict'
const norm = (v) => String(v == null ? '' : v).trim()
// 生成候选列表: [{ providerId, model, keyGroup, label }],仅收可见模型(visible !== false)。
function wDefaultGenOptions (cfg) {
const providers = (cfg && Array.isArray(cfg.providers)) ? cfg.providers : []
const out = []
const seen = new Set()
for (const p of providers) {
const pid = norm(p && p.id)
if (!pid) continue
const group = ((p.keys || [])[0] || {}).id || ''
for (const m of (p.models || [])) {
const name = norm(m && (typeof m === 'string' ? m : m.name))
if (!name || (m && typeof m === 'object' && m.visible === false)) continue
const key = pid + '::' + name
if (seen.has(key)) continue
seen.add(key)
out.push({ providerId: pid, model: name, keyGroup: norm(group), label: ((p && p.name) || pid) + ' · ' + name })
}
}
return out
}
// 解析生效值:始终给出「新建节点会用的那个模型」,让设置页与新建行为一致、可解释。
// ① 有效配置 ⇒ 原样用(密钥组缺省时取该服务第一个分组)
// ② 未配置 / 配置的模型被删或被关闭 ⇒ 回退主服务(providers[0])第一个可见模型
// ③ 一个可用模型都没有 ⇒ null(宿主保留 DEFAULTS.gen 的硬编码兜底)
function wResolveDefaultGen (cfg) {
const opts = wDefaultGenOptions(cfg)
if (!opts.length) return null
const d = (cfg && cfg.defaultGen) || {}
const pid = norm(d.providerId)
const model = norm(d.model)
if (pid && model) {
const hit = opts.find((o) => o.providerId === pid && o.model === model)
if (hit) return { providerId: hit.providerId, model: hit.model, keyGroup: norm(d.keyGroup) || hit.keyGroup }
}
const firstPid = norm((((cfg || {}).providers || [])[0] || {}).id)
const fb = (firstPid && opts.find((o) => o.providerId === firstPid)) || opts[0]
return { providerId: fb.providerId, model: fb.model, keyGroup: fb.keyGroup }
}
// 配置保存前的校验/归一化:只接受候选里的有效项;失效项不写入,让读取侧走回退。
function wNormalizeDefaultGen (cfg, incoming) {
const d = (incoming && typeof incoming === 'object') ? incoming : {}
const pid = norm(d.providerId)
const model = norm(d.model)
if (!pid || !model) return null
const opts = wDefaultGenOptions(cfg)
const hit = opts.find((o) => o.providerId === pid && o.model === model)
return hit ? { providerId: hit.providerId, model: hit.model, keyGroup: norm(d.keyGroup) || hit.keyGroup } : null
}
global.IWBDefaultGenModel = { wResolveDefaultGen, wDefaultGenOptions, wNormalizeDefaultGen }
})(typeof window !== 'undefined' ? window : globalThis)
+89
View File
@@ -0,0 +1,89 @@
'use strict'
/* 生图端点与鉴权(2026-11-24,v3.26.65)
*
* 为什么单独成模块:仓库里原来有两处硬伤 ——
* ① 端点写死:`baseUrl + '/images/generations'`(app.js 两处),而配置里的 genPath/editPath
* 只是「存了、显示了、导出到公开配置」,从未参与拼 URL ⇒ 非标准路径的网关接不了;
* ② 鉴权写死:`Authorization: Bearer <key>`(5 处),需要 `x-api-key` / `?key=` 的中转站接不了。
*
* 本模块只做纯字符串/对象运算(不读配置、不发请求),便于 Node 下单测。
* 边界:**不校验 key 是否有效**(那是服务端的事),只负责「按配置拼对」
*/
;(function (global) {
const AUTH_TYPES = ['bearer', 'header', 'query', 'none']
const DEFAULT_PATH = '/images/generations'
const str = (v) => (v == null ? '' : String(v))
// 端点拼接:base 去尾斜杠、path 补首斜杠;path 是绝对 URL 时原样返回(少数网关给整条地址)
function joinEndpoint (base, path) {
const p = str(path).trim() || DEFAULT_PATH
if (/^https?:\/\//i.test(p)) return p
const b = str(base).trim().replace(/\/+$/, '')
const tail = p.charAt(0) === '/' ? p : '/' + p
return b + tail
}
// 鉴权归一:缺省 = bearer(历史行为,不能改默认,否则老配置全挂)
function normalizeAuth (auth) {
const a = (auth && typeof auth === 'object') ? auth : null
const t = a ? str(a.type).trim().toLowerCase() : ''
if (AUTH_TYPES.indexOf(t) < 0) return { type: 'bearer' }
const out = { type: t }
if (t === 'header') out.headerName = str(a.headerName).trim() || 'x-api-key'
if (t === 'query') out.queryName = str(a.queryName).trim() || 'key'
return out
}
// 请求头:head 是调用方已有的头(如 Content-Type),鉴权头叠加在上面
function buildAuthHeaders (auth, keyValue, head) {
const out = Object.assign({}, head || {})
const a = normalizeAuth(auth)
const v = str(keyValue)
if (a.type === 'none' || !v) return out
if (a.type === 'header') { out[a.headerName] = v; return out }
out.Authorization = 'Bearer ' + v
return out
}
// URL 参数鉴权:已有同名参数时覆盖,避免出现两个 key
function applyAuthQuery (url, auth, keyValue) {
const a = normalizeAuth(auth)
const v = str(keyValue)
if (a.type !== 'query' || !v) return url
const u = str(url)
const sep = u.indexOf('?') >= 0 ? '&' : '?'
const re = new RegExp('([?&])' + a.queryName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '=[^&]*')
if (re.test(u)) return u.replace(re, '$1' + a.queryName + '=' + encodeURIComponent(v))
return u + sep + a.queryName + '=' + encodeURIComponent(v)
}
/* 失败后是否换下一个地址重试。判据是「这次失败有没有可能已经出图」:
* · 5xx / 429 / 连接失败 → 服务端没接住或明确拒绝,换地址安全;
* · 参数(400/422) / 鉴权(401/403) → 换地址也一样错,直接抛;
* · 超时 / hard-timeout / 用户取消 → **结果未知**,换地址重提可能重复计费,绝不重试。
*/
function shouldRetryNextAddress (err) {
const t = err && err.iwbType
return t === 'server' || t === 'limit' || t === 'network'
}
/* 地址循环:主地址失败且「可安全重试」时换下一个;结果未知(超时/hard-timeout)绝不重提。
* attempt() 由调用方提供(它负责发请求并解析),onBase(base) 用来把当前地址交给闭包。
* 放这里而不是 app.js:app.js 有行数棘轮,循环属于「请求编排」的通用件。 */
async function runWithAddresses (addrs, attempt, onBase) {
const list = Array.isArray(addrs) && addrs.length ? addrs : ['']
let lastErr = null
for (let i = 0; i < list.length; i++) {
if (typeof onBase === 'function') onBase(list[i])
try { return await attempt() } catch (e) {
lastErr = e
if (!shouldRetryNextAddress(e) || i >= list.length - 1) throw e
}
}
throw lastErr || new Error('请求失败')
}
const API = Object.freeze({ AUTH_TYPES, DEFAULT_PATH, joinEndpoint, normalizeAuth, buildAuthHeaders, applyAuthQuery, shouldRetryNextAddress, runWithAddresses })
if (global) global.IWBGenerationEndpoint = API
})(typeof window !== 'undefined' ? window : (typeof globalThis !== 'undefined' ? globalThis : this))
+61 -2
View File
@@ -71,12 +71,36 @@
// ② 下游 orderedUniqueRefNodes 还要按 id 去重、按画布坐标排序(图片按 X 轴先、Y 轴后),
// 伪节点必须带上宿主节点自己的 x/y,才能排进用户预期的次序。
// id 取 `节点id + ':ref'`:不与任何真图片节点撞名,同一节点在多条链路被重复收集时又能正常去重。
// 相册(2026-11-26,outKind:'images'):一个节点声明多张图。
// data.items = [{ name, src, on? }],src 是 dataURL/URL 字符串或引用对象({__file}/{__blob}/{__cache})。
// 为什么伪装成多个「ref 节点」:下游 refArgsOf / orderedUniqueRefNodes / 去重排序全都只认 ref 节点形状,
// 合成节点带宿主节点的 x/y,才能排进用户预期的次序(与 refOn 那条同一套理由)。
const ALBUM_BATCH_MAX = 12 // 批量模式下每个请求最多带几张(相册模式 B:超过自动分批)
const albumItemsOf = (n) => {
const d = (n && n.data) || {}
if (d.outKind !== 'images' || !Array.isArray(d.items)) return []
const out = []
// 仅本页参与:相册按当前尺寸算出的可见区间写在 data.pageRange = [start, end)(插件维护,宿主只读)
const from = (d.onlyPage === true && Array.isArray(d.pageRange)) ? Math.max(0, Number(d.pageRange[0]) || 0) : 0
const to = (d.onlyPage === true && Array.isArray(d.pageRange)) ? Math.max(from, Number(d.pageRange[1]) || 0) : d.items.length
for (let i = from; i < Math.min(d.items.length, to); i++) {
const it = d.items[i]
if (!it || it.on === false) continue
const src = it.src != null ? it.src : (it.ref != null ? it.ref : it.data)
if (!src) continue
const name = String(it.name || ('图 ' + (i + 1)))
const data = (typeof src === 'string') ? { data: src, name: name } : { url: src, name: name }
out.push({ id: String(n.id) + ':ref:' + i, type: 'ref', x: n.x, y: n.y, w: n.w, h: n.h, data: data })
}
return out
}
const selfRefNodesOf = (n) => {
const d = (n && n.data) || {}
if (d.outKind === 'images') return albumItemsOf(n)
if (d.refOn !== true) return []
const url = String(d.refUrl || '').trim()
if (!url) return []
return [{ id: String(n.id) + ':ref', type: 'ref', x: n.x, y: n.y, w: n.w, h: n.h, data: { url: url, name: String(d.refName || 'style-ref.png') } }]
return [{ id: String(n.id) + ':ref', type: 'ref', x: n.x, y: n.y, w: n.w, h: n.h, data: { url: url, name: String(d.refName || 'style-ref') } }]
}
function createTaskGraphIndex(nodesArr, edgesArr) {
@@ -104,7 +128,27 @@
// 否则「样式节点直连生图」与「样式节点 → 提示词 → 生图」会被认成同一个来源而合并成一个任务。
return base.map((t) => ({ ...t, sourceNodeId: own ? n.id : (t.sourceNodeId || n.id), ownerNodeId: n.id, title: ownTitle || t.title || '', text: own || t.text, refNodes: dedupeTaskRefs((t.refNodes || []).concat(refs)) }))
}
if (n.type === 'combine') { const orderedC = children.slice().sort((a, b) => { const na = graph.byId.get(a.sourceNodeId), nb = graph.byId.get(b.sourceNodeId); return na && nb ? compareCanvasTextOrder(na, nb) : 0 }); return [{ sourceNodeId: n.id, ownerNodeId: n.id, title: String((n.data && n.data.title) || '').trim(), text: own || orderedC.map((t) => t.text).filter(Boolean).join(String((n.data && n.data.sep) || (global.IWBRuntimeConstants && global.IWBRuntimeConstants.combineSep) || ', ')), refNodes: dedupeTaskRefs(orderedC.flatMap((t) => t.refNodes)), diagnostics: { cycles: orderedC.flatMap((t) => (t.diagnostics && t.diagnostics.cycles) || []), disabledSources: [] } }] }
if (n.type === 'combine') {
const orderedC = children.slice().sort((a, b) => { const na = graph.byId.get(a.sourceNodeId), nb = graph.byId.get(b.sourceNodeId); return na && nb ? compareCanvasTextOrder(na, nb) : 0 })
/* 多值子源展开(2026-11-26):相册(一图一任务)接在组合前面时,组合必须**扇出 N 个任务**,
* 否则会被下面那句「永远返回 1 个值」压成「1 个任务 + N 张图」——那正是批量模式的行为,一图一任务会失效。
* 安全边界:只有**恰好一个**来源提供多值时才展开(内置节点永远只返回 1 个值 ⇒ 现有画布零变化);
* 多个多值来源(未定义语义)不猜,退回原来的「压成 1 个」。
*/
const keyOf = (t) => String(t.ownerNodeId || t.sourceNodeId || '')
const bySource = new Map()
for (const t of orderedC) { const k = keyOf(t); if (!bySource.has(k)) bySource.set(k, []); bySource.get(k).push(t) }
const multi = Array.from(bySource.keys()).filter((k) => bySource.get(k).length > 1)
if (multi.length === 1) {
const mk = multi[0]
const sepOf = String((n.data && n.data.sep) || (global.IWBRuntimeConstants && global.IWBRuntimeConstants.combineSep) || ', ')
const picks = bySource.get(mk)
return picks.map((pick, i) => {
const merged = orderedC.map((t) => (keyOf(t) === mk ? pick : t))
return { sourceNodeId: n.id + '#' + i, ownerNodeId: n.id, title: String((n.data && n.data.title) || '').trim(), text: own || merged.map((t) => t.text).filter(Boolean).join(sepOf), refNodes: dedupeTaskRefs(merged.flatMap((t) => t.refNodes)), diagnostics: { cycles: merged.flatMap((t) => (t.diagnostics && t.diagnostics.cycles) || []), disabledSources: [] } }
})
}
return [{ sourceNodeId: n.id, ownerNodeId: n.id, title: String((n.data && n.data.title) || '').trim(), text: own || orderedC.map((t) => t.text).filter(Boolean).join(String((n.data && n.data.sep) || (global.IWBRuntimeConstants && global.IWBRuntimeConstants.combineSep) || ', ')), refNodes: dedupeTaskRefs(orderedC.flatMap((t) => t.refNodes)), diagnostics: { cycles: orderedC.flatMap((t) => (t.diagnostics && t.diagnostics.cycles) || []), disabledSources: [] } }] }
if (n.type === 'batch') { const candidates = incoming.map((e) => graph.byId.get(e.from)).filter((x) => x && isBatchSrc(x, graph.edges, graph.nodes) && !(x.data && x.data.enabled === false)); const selected = ctx.selectedBatchSourceId && candidates.find((x) => x.id === ctx.selectedBatchSourceId); const sources = selected ? [selected] : candidates; return sources.flatMap((src) => resolveNodeTaskValues(src.id, graph, { ...ctx, selectedBatchSourceId: null, stack: next }).map((t) => ({ ...t, text: batchJoinedText(n.data || {}, t.text) }))) }
if (n.type === 'relay') {
const sharedRefs = dedupeTaskRefs(children.filter((t) => !t.text).flatMap((t) => t.refNodes || []))
@@ -124,6 +168,21 @@
// 有上游时也要并(不再直接 return children):端口已关,但旧存档里可能有残留入边,
// 那种情况下「用户勾的示例图」不该因为一条历史连线就消失。
const selfRefs = selfRefNodesOf(n)
// 相册(2026-11-26):多图源 = 多任务。
// · 一图一任务(默认):每张图一个任务值,文本取自身或上游第一段(相机后面的组合/生图照旧)
// · 批量:按 ALBUM_BATCH_MAX 分批,每批一个任务值(一批内多张参考图)
// 只在 outKind:'images' 时生效 ⇒ 其它插件节点 / 内置类型行为逐字不变。
if (n.data && n.data.outKind === 'images' && selfRefs.length) {
const albumText = own || (children.map((t) => t.text).filter(Boolean)[0] || '')
const diag = { cycles: children.flatMap((t) => (t.diagnostics && t.diagnostics.cycles) || []), disabledSources: [] }
const batch = n.data.albumMode === 'batch'
if (!batch) {
return selfRefs.map((r, i) => ({ sourceNodeId: n.id + '#' + i, ownerNodeId: n.id, title: String((n.data && n.data.title) || '').trim(), text: albumText, refNodes: [r], diagnostics: diag }))
}
const groups = []
for (let i = 0; i < selfRefs.length; i += ALBUM_BATCH_MAX) groups.push(selfRefs.slice(i, i + ALBUM_BATCH_MAX))
return groups.map((g, gi) => ({ sourceNodeId: n.id + '#b' + gi, ownerNodeId: n.id, title: String((n.data && n.data.title) || '').trim(), text: albumText, refNodes: g, diagnostics: diag }))
}
if (children.length) {
return selfRefs.length
? children.map((t) => ({ ...t, ownerNodeId: n.id, refNodes: dedupeTaskRefs((t.refNodes || []).concat(selfRefs)) }))
+135
View File
@@ -0,0 +1,135 @@
/* 本地文件图片引用(2026-11-26)
*
* 为什么单独成模块:相册要「只做引用、不复制字节」——节点里只存原文件绝对路径
* ({__file: '/abs/a.png'}),生成/预览时才按需读盘。这样 22 张 4K 图 = 画布 JSON 2.6KB,
* 而不是往 images/canvas/ 复制 176MB。
*
* 边界:
* · 只做「路径 ↔ 字节」这一层,不碰画布/存储/CSS;宿主 app.js 通过 wImgRefDataUrl 等入口调用
* · 非桌面端(网页版)没有 __TAURI__ ⇒ available() false,调用方必须自己降级为复制
* · fs 权限是运行时的:pick() 选完会把路径加进 fs scope(Rust grant_paths),重启后失效需重新选择
*/
;(function (global) {
'use strict'
const g = global || {}
const MIME = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif', avif: 'image/avif', bmp: 'image/bmp', svg: 'image/svg+xml' }
const extOf = (p) => { const m = /\.([a-z0-9]{1,5})$/i.exec(String(p || '')); return m ? m[1].toLowerCase() : '' }
const mimeOf = (p) => MIME[extOf(p)] || 'application/octet-stream'
const nameOf = (p) => String(p || '').replace(/^.*[\\/]/, '')
const is = (v) => !!(v && typeof v === 'object' && !Array.isArray(v) && typeof v.__file === 'string' && v.__file)
const T = () => (typeof window !== 'undefined' ? window.__TAURI__ : null)
const fsApi = () => { const t = T(); return t && t.fs ? t.fs : null }
const available = () => { const f = fsApi(); return !!(f && typeof f.readFile === 'function') }
async function readBytes (path) {
const f = fsApi()
if (!f || !path) return null
try { const u8 = await f.readFile(String(path)); return u8 || null } catch (e) { return null }
}
// 手工 base64(不依赖 FileReader/btoa 的边界行为;Uint8Array → 分块拼,避免超长 apply 爆栈)
function toBase64 (u8) {
const bytes = (u8 && u8.length !== undefined) ? u8 : new Uint8Array(0)
const CHUNK = 0x8000
let bin = ''
for (let i = 0; i < bytes.length; i += CHUNK) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK))
try { return btoa(bin) } catch (e) { return '' }
}
async function readDataUrl (path) {
const u8 = await readBytes(path)
if (!u8 || !u8.length) return ''
const b64 = toBase64(u8)
return b64 ? ('data:' + mimeOf(path) + ';base64,' + b64) : ''
}
async function readBlob (path) {
const u8 = await readBytes(path)
if (!u8 || !u8.length) return null
try { return new Blob([u8], { type: mimeOf(path) }) } catch (e) { return null }
}
// 失联检测:相册打开画布时用它给「图片已不在原位置」的格子打标
async function stat (path) {
const f = fsApi()
if (!f || !path) return { ok: false, exists: false, reason: 'no-fs' }
try {
const exists = (typeof f.exists === 'function') ? await f.exists(String(path)) : true
if (!exists) return { ok: true, exists: false }
const st = (typeof f.stat === 'function') ? await f.stat(String(path)) : null
return { ok: true, exists: true, size: st && Number(st.size) || 0, mtime: st && Number(st.mtime) || 0, name: nameOf(path) }
} catch (e) { return { ok: false, exists: false, reason: 'stat-failed' } }
}
// 把用户选中的路径加进运行时 fs scope(Rust 侧 grant_paths)
async function grant (paths) {
const t = T(); const list = (Array.isArray(paths) ? paths : [paths]).filter((p) => typeof p === 'string' && p)
if (!t || !t.core || typeof t.core.invoke !== 'function' || !list.length) return []
try { return await t.core.invoke('grant_paths', { paths: list }) || [] } catch (e) { return [] }
}
// 系统选择器:返回绝对路径数组(桌面端才有路径;网页版返回空 ⇒ 调用方降级复制)
async function pick (opts) {
const t = T(); const dlg = t && t.dialog
if (!dlg || typeof dlg.open !== 'function') return []
const o = opts || {}
let picked = null
try {
picked = await dlg.open({
multiple: o.multiple !== false,
directory: o.directory === true,
title: String(o.title || (o.directory ? '选择图片文件夹' : '选择图片')),
filters: o.filters || [{ name: '图片', extensions: ['png', 'jpg', 'jpeg', 'webp', 'gif', 'avif', 'bmp', 'svg'] }],
})
} catch (e) { return [] }
if (!picked) return []
const list = Array.isArray(picked) ? picked : [picked]
await grant(list)
return list.filter((p) => typeof p === 'string' && p)
}
// 列目录里的图片(相册「文件夹」导入用):Tauri fs.readDir 只给名字,这里递归拼回绝对路径。
// 深度限 2 层:相册是「一本相册」,不需要把整个硬盘扫一遍。
async function listImages (dir, depth) {
const t = T(); const f = fsApi()
if (!t || !f || typeof f.readDir !== 'function') return []
const root = String(dir || '')
if (!root) return []
const join = (t.path && typeof t.path.join === 'function') ? t.path.join : null
const out = []
const walk = async (cur, d) => {
let entries = []
try { entries = await f.readDir(cur) } catch (e) { return }
for (const ent of (entries || [])) {
const name = String((ent && ent.name) || '')
if (!name || name.charAt(0) === '.') continue
const child = join ? await join(cur, name) : (cur.replace(/[\\/]+$/, '') + '/' + name)
if (ent && ent.isDirectory) { if (d > 0) await walk(child, d - 1); continue }
if (!isImagePath(child)) continue
out.push(child)
if (out.length >= 500) return
}
}
await walk(root, typeof depth === 'number' ? depth : 1)
return out
}
const isImagePath = (p) => {
const m = /\.([a-z0-9]{1,5})$/i.exec(String(p || ''))
const ext = m ? m[1].toLowerCase() : ''
return ['png', 'jpg', 'jpeg', 'webp', 'gif', 'avif', 'bmp', 'svg'].indexOf(ext) >= 0
}
// 单张引用:读 stat 拿元信息(不读字节)——相册导入时用
async function reference (path) {
const p = String(path || '')
if (!p) return { ok: false, reason: 'empty-path' }
const st = await stat(p)
if (!st.ok) return { ok: false, reason: st.reason || 'stat-failed', path: p }
if (!st.exists) return { ok: false, reason: 'not-found', path: p }
return { ok: true, path: p, name: nameOf(p), size: st.size, mtime: st.mtime }
}
const API = Object.freeze({ is, available, mimeOf, nameOf, isImagePath, listImages, readBytes, readDataUrl, readBlob, stat, grant, pick, reference })
global.IWBImageFileRef = API
})(typeof window !== 'undefined' ? window : globalThis)
-449
View File
@@ -1,449 +0,0 @@
/* 预览产物生成器(画布只渲染小预览的关键一环:**解码即缩放**)
*
* 目标:为"画布只渲染小预览"提供派生小图,绝不产出 2160×3840 这类全尺寸位图。
* - 优先 createImageBitmap(blob, { resizeWidth, resizeHeight, resizeQuality:'high' })
* ⇒ 解码阶段就完成重采样,堆里不会出现全尺寸位图。
* 为能传入等比目标尺寸,先读图片头部(PNG/JPEG/GIF/WebP/BMP)拿到原始宽高,
* 或用调用方直接给的 opts.srcWidth/srcHeight。
* - 老浏览器不支持 resizeWidth:退回 createImageBitmap(blob)(或 <img> 全尺寸解码)
* 再由 canvas 缩放;此时 decode 出的位图仍会被 close(),不驻留。
* - 跨域 URL:不保证能直接 fetch(CORS 会失败)⇒ 调用方通过 opts.viaUrl 传同源代理;
* fetch 失败一律返回 { ok:false, error },绝不抛出。
* - 生命周期:deriveUrl 产出的 objectURL 由 revokeAll() 统一回收(幂等);
* bitmap.close?.() 与内部临时 objectURL 的 revoke 都在 finally 里。
*
* 纯 UMD 全局脚本(无 ESM、无打包器);**加载期不碰 DOM/canvas**,
* 因此 Node 下可直接 eval/require 而不报错(只有调用 derive 时才可能因缺能力失败)。
*/
;(function (global) {
'use strict'
const DEFAULT_MAX_EDGE = 1024
const DEFAULT_QUALITY = 0.82
const HEADER_BYTES = 65536 // 头部解析只读前 64KB,避免为量尺寸而整块读入
const g = (global && typeof global === 'object') ? global : {}
// ---- 能力探测(全部惰性;沙箱里 global 参数可能是注入的 box,裸标识符才是真 global)----
function pickCreateImageBitmap() {
try { if (typeof g.createImageBitmap === 'function') return g.createImageBitmap } catch (e) { /* ignore */ }
try { if (typeof createImageBitmap === 'function') return createImageBitmap } catch (e) { /* ignore */ }
return null
}
function pickOffscreenCanvas() {
try { if (typeof g.OffscreenCanvas === 'function') return g.OffscreenCanvas } catch (e) { /* ignore */ }
try { if (typeof OffscreenCanvas === 'function') return OffscreenCanvas } catch (e) { /* ignore */ }
return null
}
function pickDocument() {
try { if (g.document && typeof g.document.createElement === 'function') return g.document } catch (e) { /* ignore */ }
try { if (typeof document !== 'undefined' && document && typeof document.createElement === 'function') return document } catch (e) { /* ignore */ }
return null
}
function pickImage() {
try { if (typeof g.Image === 'function') return g.Image } catch (e) { /* ignore */ }
try { if (typeof Image === 'function') return Image } catch (e) { /* ignore */ }
return null
}
function pickFetch() {
try { if (typeof g.fetch === 'function') return g.fetch } catch (e) { /* ignore */ }
try { if (typeof fetch === 'function') return fetch } catch (e) { /* ignore */ }
return null
}
function pickUrl() {
try { if (g.URL && typeof g.URL.createObjectURL === 'function') return g.URL } catch (e) { /* ignore */ }
try { if (typeof URL !== 'undefined' && URL && typeof URL.createObjectURL === 'function') return URL } catch (e) { /* ignore */ }
return null
}
// ---- 基础工具(无 DOM 依赖,Node 下可用)----
function dataUrlToBlob(dataUrl) {
const s = String(dataUrl || '')
const m = /^data:([^;,]+)?(;base64)?,/.exec(s)
if (!m) return null
const mime = m[1] || 'application/octet-stream'
const body = s.slice(m[0].length)
let bytes
if (m[2]) {
let bin = ''
try { bin = (typeof atob === 'function') ? atob(body) : Buffer.from(body, 'base64').toString('binary') } catch (e) { return null }
bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
} else {
let txt = body
try { txt = decodeURIComponent(body) } catch (e) { /* 已经是明文 */ }
bytes = new Uint8Array(txt.length)
for (let i = 0; i < txt.length; i++) bytes[i] = txt.charCodeAt(i) & 0xff
}
return new Blob([bytes], { type: mime })
}
async function blobToDataUrl(blob) {
const mime = (blob && blob.type) || 'application/octet-stream'
const buf = new Uint8Array(await blob.arrayBuffer())
let bin = ''
const CH = 0x8000
for (let i = 0; i < buf.length; i += CH) bin += String.fromCharCode.apply(null, buf.subarray(i, i + CH))
const b64 = (typeof btoa === 'function') ? btoa(bin) : Buffer.from(buf).toString('base64')
return 'data:' + mime + ';base64,' + b64
}
// 从图片头部字节读原始宽高(不触发解码)。识别不了返回 null。
function imageSizeFromBytes(bytes) {
const b = bytes
if (!b || b.length < 16) return null
const u8 = (i) => b[i] & 0xff
const u16be = (i) => ((b[i] & 0xff) << 8) | (b[i + 1] & 0xff)
const u32be = (i) => (((b[i] & 0xff) << 24) | ((b[i + 1] & 0xff) << 16) | ((b[i + 2] & 0xff) << 8) | (b[i + 3] & 0xff)) >>> 0
const u16le = (i) => (b[i] & 0xff) | ((b[i + 1] & 0xff) << 8)
const u32le = (i) => ((b[i] & 0xff) | ((b[i + 1] & 0xff) << 8) | ((b[i + 2] & 0xff) << 16) | ((b[i + 3] & 0xff) << 24)) >>> 0
// PNG:签名 89 50 4E 47,IHDR 宽高在 16/20
if (u8(0) === 0x89 && u8(1) === 0x50 && u8(2) === 0x4e && u8(3) === 0x47) {
if (b.length < 24) return null
const w = u32be(16), h = u32be(20)
return (w && h) ? { width: w, height: h } : null
}
// GIF:GIF87a / GIF89a,宽高小端
if (u8(0) === 0x47 && u8(1) === 0x49 && u8(2) === 0x46) {
if (b.length < 10) return null
const w = u16le(6), h = u16le(8)
return (w && h) ? { width: w, height: h } : null
}
// BMP:'BM',宽高 int32 小端(高可为负)
if (u8(0) === 0x42 && u8(1) === 0x4d && b.length >= 26) {
const w = Math.abs(u32le(18) | 0), h = Math.abs(u32le(22) | 0)
return (w && h) ? { width: w, height: h } : null
}
// WebP:RIFF....WEBP
if (b.length >= 30 && u8(0) === 0x52 && u8(1) === 0x49 && u8(2) === 0x46 && u8(3) === 0x46 &&
u8(8) === 0x57 && u8(9) === 0x45 && u8(10) === 0x42 && u8(11) === 0x50) {
const fourcc = String.fromCharCode(u8(12), u8(13), u8(14), u8(15))
if (fourcc === 'VP8X') {
const w = 1 + (u8(24) | (u8(25) << 8) | (u8(26) << 16))
const h = 1 + (u8(27) | (u8(28) << 8) | (u8(29) << 16))
return (w && h) ? { width: w, height: h } : null
}
if (fourcc === 'VP8 ') {
const w = u16le(26) & 0x3fff, h = u16le(28) & 0x3fff
return (w && h) ? { width: w, height: h } : null
}
if (fourcc === 'VP8L' && u8(20) === 0x2f) {
const bits = (u8(21) | (u8(22) << 8) | (u8(23) << 16) | (u8(24) << 24)) >>> 0
const w = 1 + (bits & 0x3fff)
const h = 1 + ((bits >>> 14) & 0x3fff)
return (w && h) ? { width: w, height: h } : null
}
return null
}
// JPEG:FF D8 后扫 SOFn
if (u8(0) === 0xff && u8(1) === 0xd8) {
let i = 2
while (i + 9 < b.length) {
if (u8(i) !== 0xff) { i++; continue }
const marker = u8(i + 1)
if (marker === 0xff) { i++; continue }
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9)) { i += 2; continue }
const len = u16be(i + 2)
if (len < 2) break
const isSOF = (marker >= 0xc0 && marker <= 0xcf) && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc
if (isSOF) {
const h = u16be(i + 5), w = u16be(i + 7)
return (w && h) ? { width: w, height: h } : null
}
if (marker === 0xda) break // SOS:后面是压缩数据
i += 2 + len
}
return null
}
return null
}
// 等比目标尺寸:只缩小不放大,长边 ≤ maxEdge
function targetSize(width, height, maxEdge) {
const W = Math.max(1, Math.round(Number(width) || 0))
const H = Math.max(1, Math.round(Number(height) || 0))
const M = Math.max(1, Math.round(Number(maxEdge) || DEFAULT_MAX_EDGE))
const long = Math.max(W, H)
if (!(long > M)) return { width: W, height: H, scaled: false }
const scale = M / long
return { width: Math.max(1, Math.round(W * scale)), height: Math.max(1, Math.round(H * scale)), scaled: true }
}
function normMaxEdge(o) {
const v = Math.round(Number(o && o.maxEdge))
return (v > 0) ? v : DEFAULT_MAX_EDGE
}
function normQuality(o) {
const v = Number(o && o.quality)
return (v > 0 && v <= 1) ? v : DEFAULT_QUALITY
}
function closeBitmap(b) {
try { if (b && typeof b.close === 'function') b.close() } catch (e) { /* ignore */ }
}
function safeRevoke(u) {
if (!u) return
const U = pickUrl()
try { if (U && typeof U.revokeObjectURL === 'function') U.revokeObjectURL(u) } catch (e) { /* ignore */ }
}
async function readHeaderDims(blob) {
try {
const head = (blob && typeof blob.slice === 'function') ? blob.slice(0, HEADER_BYTES) : blob
if (!head || typeof head.arrayBuffer !== 'function') return null
return imageSizeFromBytes(new Uint8Array(await head.arrayBuffer()))
} catch (e) { return null }
}
function makeCanvas(w, h) {
const OC = pickOffscreenCanvas()
if (OC) {
let c = null
try { c = new OC(w, h) } catch (e) { try { c = new OC() } catch (e2) { c = null } }
if (c) {
try { c.width = w; c.height = h } catch (e) { /* ignore */ }
const ctx = (typeof c.getContext === 'function') ? c.getContext('2d') : null
if (ctx) return { canvas: c, ctx: ctx }
}
}
const doc = pickDocument()
if (doc) {
try {
const c = doc.createElement('canvas')
c.width = w; c.height = h
const ctx = (typeof c.getContext === 'function') ? c.getContext('2d') : null
if (ctx) return { canvas: c, ctx: ctx }
} catch (e) { /* ignore */ }
}
return null
}
function canvasToBlob(canvas, type, quality) {
return new Promise((resolve) => {
let settled = false
const done = (b) => { if (!settled) { settled = true; resolve(b || null) } }
try {
if (canvas && typeof canvas.convertToBlob === 'function') {
canvas.convertToBlob({ type: type, quality: quality }).then((b) => done(b), () => done(null))
return
}
if (canvas && typeof canvas.toBlob === 'function') { canvas.toBlob((b) => done(b), type, quality); return }
if (canvas && typeof canvas.toDataURL === 'function') { done(dataUrlToBlob(canvas.toDataURL(type, quality))); return }
} catch (e) { done(null); return }
done(null)
})
}
function loadImage(src) {
return new Promise((resolve) => {
const Img = pickImage()
if (!Img) { resolve(null); return }
try {
const img = new Img()
let settled = false
const done = (v) => { if (!settled) { settled = true; resolve(v) } }
img.onload = () => done(img)
img.onerror = () => done(null)
img.src = src
const timer = setTimeout(() => done(null), 30000)
const _t = /** @type {any} */ (timer); if (_t && typeof _t.unref === 'function') _t.unref()
} catch (e) { resolve(null) }
})
}
function create(options) {
const cfg = options || {}
const urls = new Set() // 已创建、未回收的 objectURL(deriveUrl 产出)
const stats = { created: 0, revoked: 0, live: 0, failed: 0 }
function registerUrl(u) { urls.add(u); stats.created++; stats.live = urls.size }
function revokeOne(u) {
if (!u || !urls.has(u)) return false
safeRevoke(u)
urls.delete(u)
stats.revoked++
stats.live = urls.size
return true
}
// 回收本实例创建的全部 objectURL;幂等(重复调用不会重复计数、不会抛)
function revokeAll() {
let n = 0
urls.forEach((u) => { safeRevoke(u); n++ })
urls.clear()
stats.revoked += n
stats.live = 0
return n
}
function statsOf() { return { created: stats.created, revoked: stats.revoked, live: stats.live, failed: stats.failed } }
// 入参归一 → { ok, blob?, src?, mime? };错误只回 { ok:false, error }
async function resolveInput(input, o) {
if (input == null) return { ok: false, error: 'bad-input' }
if (typeof input === 'object') {
if (typeof input.size === 'number' && typeof input.arrayBuffer === 'function') {
return { ok: true, blob: input, mime: input.type || '', via: 'blob' }
}
if (typeof input.dataUrl === 'string') return resolveInput(input.dataUrl, o)
if (typeof input.url === 'string') input = input.url
else if (typeof input.src === 'string') input = input.src
else return { ok: false, error: 'bad-input' }
}
const s = String(input || '')
if (!s) return { ok: false, error: 'bad-input' }
if (s.indexOf('data:') === 0) {
if (s.indexOf('data:image/') !== 0) return { ok: false, error: 'not-an-image' }
const blob = dataUrlToBlob(s)
return blob ? { ok: true, blob: blob, mime: blob.type || '', via: 'data' } : { ok: false, error: 'bad-data-url' }
}
if (/^https?:\/\//i.test(s)) {
// 跨域直连必失败 → 调用方用 opts.viaUrl 给同源代理;失败不抛,回 { ok:false }
const target = (o && typeof o.viaUrl === 'string' && o.viaUrl) ? o.viaUrl : s
const f = pickFetch()
if (!f) return { ok: false, error: 'no-fetch' }
try {
const res = await f(target)
if (!res || (typeof res.ok === 'boolean' && !res.ok)) return { ok: false, error: 'fetch-failed' }
const blob = await res.blob()
if (!blob || typeof blob.size !== 'number') return { ok: false, error: 'fetch-no-blob' }
return { ok: true, blob: blob, mime: blob.type || '', via: 'url', url: target }
} catch (e) { return { ok: false, error: 'fetch-failed' } }
}
if (/^(blob:|\/|\.\/|\.\.\/)/i.test(s)) return { ok: true, src: s, via: 'src' } // 交给 <img> 兜底
return { ok: false, error: 'unsupported-input' }
}
// 解码(优先缩放发生在解码阶段)。返回 { bitmap } 或 { bitmap:null };不抛。
async function decodeBitmap(blob, o) {
const cib = pickCreateImageBitmap()
if (!cib || !blob) return { bitmap: null }
const maxEdge = normMaxEdge(o)
let dim = null
if (o && Number(o.srcWidth) > 0 && Number(o.srcHeight) > 0) {
dim = { width: Number(o.srcWidth), height: Number(o.srcHeight) }
} else {
dim = await readHeaderDims(blob)
}
if (dim && dim.width > 0 && dim.height > 0) {
const t = targetSize(dim.width, dim.height, maxEdge)
try {
const bmp = await cib(blob, { resizeWidth: t.width, resizeHeight: t.height, resizeQuality: 'high' })
if (bmp) return { bitmap: bmp, resizedAtDecode: true }
} catch (e) { /* 个别实现不接受 resize 选项 → 退回不带选项 */ }
}
try {
const bmp = await cib(blob)
return { bitmap: bmp || null, resizedAtDecode: false }
} catch (e) { return { bitmap: null } }
}
// 编码:把(可能已缩放的)位图画进目标尺寸 canvas → toBlob
async function encodeFromSource(source, w, h, srcMime, o) {
const made = makeCanvas(w, h)
if (!made) return { error: 'no-canvas' }
if (!made.ctx || typeof made.ctx.drawImage !== 'function') return { error: 'no-2d-context' }
try {
made.ctx.drawImage(source, 0, 0, w, h)
const keep = (o && o.format === 'keep')
let outMime = keep ? ((srcMime && /^image\//i.test(srcMime)) ? srcMime : 'image/png') : 'image/jpeg'
const q = normQuality(o)
let blob = await canvasToBlob(made.canvas, outMime, q)
if (!blob && outMime !== 'image/png' && outMime !== 'image/jpeg') {
outMime = 'image/png' // canvas 不支持的 MIME(如 image/webp)→ 保底 PNG
blob = await canvasToBlob(made.canvas, outMime, q)
}
if (!blob) return { error: 'encode-failed' }
let out = blob
if (!out.type) { try { out = new Blob([await blob.arrayBuffer()], { type: outMime }) } catch (e) { /* ignore */ } }
return { blob: out, mime: outMime }
} catch (e) { return { error: 'draw-failed' } }
}
async function derive(input, opts) {
const o = Object.assign({}, cfg, opts || {})
const t0 = Date.now()
let bitmap = null
let tempUrl = ''
try {
const resolved = await resolveInput(input, o)
if (!resolved.ok) { stats.failed++; return { ok: false, error: resolved.error } }
if (resolved.blob) {
const dec = await decodeBitmap(resolved.blob, o)
bitmap = dec.bitmap || null
}
// 兜底:无 createImageBitmap / 解码失败 / 只有 src → <img> 全尺寸解码,再由 canvas 缩放
if (!bitmap) {
let src = resolved.src || ''
if (!src && resolved.blob) {
const U = pickUrl()
if (U && typeof U.createObjectURL === 'function') {
try { src = U.createObjectURL(resolved.blob); tempUrl = src } catch (e) { src = '' }
}
}
if (src) {
const img = await loadImage(src)
if (img) bitmap = img
}
}
if (!bitmap) { stats.failed++; return { ok: false, error: resolved.blob ? 'decode-failed' : 'no-decoder' } }
const bw = Number(bitmap.width) || 1
const bh = Number(bitmap.height) || 1
const t = targetSize(bw, bh, normMaxEdge(o)) // 已解码缩放时为恒等;老环境在此把全尺寸缩下来
const srcMime = resolved.mime || (resolved.blob && resolved.blob.type) || ''
const enc = await encodeFromSource(bitmap, t.width, t.height, srcMime, o)
if (!enc || enc.error) { stats.failed++; return { ok: false, error: (enc && enc.error) || 'encode-failed' } }
const out = {
ok: true,
blob: enc.blob,
width: t.width,
height: t.height,
bytes: (typeof enc.blob.size === 'number') ? enc.blob.size : 0,
ms: Date.now() - t0,
}
if (o.returnDataUrl !== false && o.dataUrl !== false) {
try { out.dataUrl = await blobToDataUrl(enc.blob) } catch (e) { /* 无 base64 能力时不强求 */ }
}
return out
} catch (e) {
stats.failed++
return { ok: false, error: (e && e.message) ? String(e.message) : 'derive-throw' }
} finally {
closeBitmap(bitmap) // 无论成功失败都释放解码位图
if (tempUrl) safeRevoke(tempUrl) // 内部临时 objectURL 立即回收
}
}
// 产出一个可直接喂给 <img src> 的 objectURL;返回 { ok, url, revoke, width, height, bytes, ms }
async function deriveUrl(input, opts) {
const o = Object.assign({}, cfg, opts || {}, { returnDataUrl: false }) // 只要 URL,不必再转 base64
const r = await derive(input, o)
if (!r.ok) return { ok: false, error: r.error }
const U = pickUrl()
if (!U || typeof U.createObjectURL !== 'function') {
stats.failed++
return { ok: false, error: 'no-object-url' }
}
let url = ''
try { url = U.createObjectURL(r.blob) } catch (e) { stats.failed++; return { ok: false, error: 'object-url-failed' } }
registerUrl(url)
return {
ok: true,
url: url,
revoke: () => revokeOne(url),
width: r.width,
height: r.height,
bytes: r.bytes,
ms: r.ms,
}
}
return { derive, deriveUrl, revokeAll, stats: statsOf }
}
global.IWBImagePreviewDerive = Object.freeze({
create,
dataUrlToBlob,
blobToDataUrl,
imageSizeFromBytes,
targetSize,
DEFAULT_MAX_EDGE,
DEFAULT_QUALITY,
})
})(typeof window !== 'undefined' ? window : globalThis)
+73
View File
@@ -0,0 +1,73 @@
/* 插件图片能力:ctx.images(2026-11-26,首个使用方 = 相册节点)
*
* 为什么需要:相册要「只引用本地文件、不复制字节」,同时也要能把拖入/固化时的字节写进宿主存储。
* 插件自己做不到这两件事:
* · 引用:需要 fs scope 授权 + 绝对路径(只有宿主能调 grant_paths / dialog)
* · 落地:需要宿主的唯一收口 wImgRefWrite({__blob} 主通道 + 缩略图预生成)
*
* 本模块只做「参数校验 + 分派」,宿主能力全部经 create(deps) 注入:
* fileRef —— IWBImageFileRef(路径 ↔ 字节,含 pick/grant/stat)
* importDataUrl —— (dataUrl, opts) => Promise<{ok, ref|null, data|null, error?}>(走 wImportImage 唯一收口)
* readDataUrl —— (ref|path) => Promise<string>(http/data/引用对象 → 真实字节)
* thumbUrlOf —— (ref|src) => string(768 显示缩略图,同步)
*/
;(function (global) {
'use strict'
const g = global || {}
const create = (deps) => {
const D = deps || {}
const need = (name) => {
const fn = D[name]
if (typeof fn !== 'function') throw new Error('IWBPluginApiImages 缺少注入依赖: ' + name)
return fn
}
// fileRef 是模块对象(IWBImageFileRef),不是函数 —— 之前误用 need() 当函数校验,
// 抛错被宿主 catch ⇒ ctx.images 整块消失(表现为插件退回文件选择器、只引用不生效)。
const fileRef = D.fileRef
if (!fileRef || typeof fileRef.available !== 'function' || typeof fileRef.pick !== 'function') throw new Error('IWBPluginApiImages 缺少注入依赖: fileRef(需 IWBImageFileRef 模块对象)')
const importDataUrl = need('importDataUrl')
const readDataUrl = need('readDataUrl')
const thumbUrlOf = need('thumbUrlOf')
const str = (v) => (v == null ? '' : String(v))
const IMAGE_EXT = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'avif', 'bmp', 'svg']
const extOf = (p) => { const m = /\.([a-z0-9]{1,5})$/i.exec(str(p)); return m ? m[1].toLowerCase() : '' }
const isImagePath = (p) => IMAGE_EXT.indexOf(extOf(p)) >= 0
return (ctx) => ({
// 是否支持「本地文件引用」(网页版 false ⇒ 插件应退回 importPath/importDataUrl)
canReference: () => fileRef.available(),
// 系统选择器:返回绝对路径数组(桌面端);网页端返回 []
pick: (opts) => fileRef.pick(opts),
// 目录里的图片列表(相册「文件夹」导入):递归 2 层,最多 500 张
listImages: (dir) => fileRef.listImages(dir, 1),
// 单张引用:只读元信息,不复制字节
reference: async (path) => {
if (!isImagePath(path)) return { ok: false, reason: 'not-image' }
const r = await fileRef.reference(path)
return r && r.ok ? { ok: true, item: { path: r.path, name: r.name, size: r.size, mtime: r.mtime } } : { ok: false, reason: (r && r.reason) || 'stat-failed' }
},
// 失联检测(相册打开画布时批量调用)
stat: (path) => fileRef.stat(path),
// 读字节(base64 dataURL):只给「需要预览/上传」的显式场景
dataUrl: (v) => readDataUrl(v),
// 缩略图地址(同步;宿主内部 768 缓存,不解析原图字节)
thumb: (v) => thumbUrlOf(v),
// 把本地文件字节写进宿主存储(拖拽=复制、以及「固化」按钮)
importPath: async (path, opts) => {
if (!isImagePath(path)) return { ok: false, error: 'not-image' }
const url = await fileRef.readDataUrl(path)
if (!url) return { ok: false, error: 'read-failed' }
return importDataUrl(url, opts)
},
// 把任意 dataURL 写进宿主存储
importDataUrl: (dataUrl, opts) => {
if (!/^data:image\//i.test(str(dataUrl))) return Promise.resolve({ ok: false, error: 'not-data-url' })
return importDataUrl(str(dataUrl), opts)
},
})
}
global.IWBPluginApiImages = Object.freeze({ create })
})(typeof window !== 'undefined' ? window : globalThis)
-206
View File
@@ -1,206 +0,0 @@
/* plugin-archive.js —— 插件包 ZIP 打包/解包(浏览器侧)
*
* 为什么要有这一层:
* - 插件包是**外部输入**:ZIP 里可能藏 ../、绝对路径、反斜杠、超限条目(zip 炸弹)。
* 直接把它交给 storage-zip 读写,会把「能不能解」和「该不该解」混在一起;
* 本模块只做准入判断,ZIP 编解码仍全部复用 src/storage-zip.js。
* - 打包与解包共用同一套校验,避免「写的时候放行、读的时候才拦」造成半成品包。
*
* 插件包布局(只允许这几种路径):
* - data.json / meta.json 顶层元数据
* - images/<name>.(jpg|jpeg|png|webp) 图片资源(images/ 下不再允许子目录)
*
* ⚠️ 重名检测不能只看 wOpenZipBlob 的 files 映射:它是普通对象,同名条目会被
* 后一个静默覆盖。所以先用 wZipParseEntries 读中央目录做名字/声明大小/重名预检,
* 再用 wOpenZipBlob 逐条读字节并复核**实际**大小(声明大小可伪造,不能当唯一防线)。
*/
;(function (global) {
'use strict'
const MAX_FILES = 500
const MAX_FILE_BYTES = 16 * 1024 * 1024
const MAX_TOTAL_BYTES = 64 * 1024 * 1024
// 名字过长会写坏 ZIP 的 16 位名称长度字段,也超出常见文件系统上限,直接拒绝。
// 名字被白名单限制为 ASCII,所以字符数即字节数。
const MAX_NAME_LENGTH = 255
const SAFE_NAME_RE = /^[A-Za-z0-9._/-]+$/
const IMAGE_EXT_RE = /\.(?:jpe?g|png|webp)$/i
const IMAGE_DIR = 'images/'
const TOP_FILES = ['data.json', 'meta.json']
// 上限必须可被调用方/测试读取:这些数字就是信任边界,散落在函数里容易被改错。
const limits = Object.freeze({
maxFiles: MAX_FILES,
maxFileBytes: MAX_FILE_BYTES,
maxTotalBytes: MAX_TOTAL_BYTES,
})
function isDirectory (name) {
return name.charAt(name.length - 1) === '/'
}
// 名字是唯一进入 ZIP 的路径,按「明显穿越 → 字符 → 路径段 → 白名单前缀」顺序校验。
// 顺序是刻意的:先报「反斜杠 / .. / 绝对路径」,错误消息才能指向真正原因,
// 而不是笼统地报一句"含非法字符"。
function validateName (name) {
if (typeof name !== 'string' || name.length === 0) throw new Error('文件名必须是非空字符串')
if (name.indexOf('\\') !== -1) throw new Error('文件名不能包含反斜杠:' + name)
for (let i = 0; i < name.length; i++) {
const code = name.charCodeAt(i)
if (code < 0x20 || code === 0x7f) throw new Error('文件名不能包含控制字符:' + JSON.stringify(name))
}
if (name.charAt(0) === '/') throw new Error('文件名不能是绝对路径:' + name)
if (!SAFE_NAME_RE.test(name)) throw new Error('文件名含非法字符(只允许字母数字、-、_、.、/):' + name)
if (name.length > MAX_NAME_LENGTH) {
throw new Error('文件名过长(最多 ' + MAX_NAME_LENGTH + ' 个字符):' + name.slice(0, 64) + '...')
}
const dir = isDirectory(name)
const body = dir ? name.slice(0, -1) : name
if (body.length === 0) throw new Error('文件名不能为空:' + name)
for (const part of body.split('/')) {
if (part === '..') throw new Error('文件名不能包含 .. 路径段:' + name)
if (part === '.' || part === '') throw new Error('文件名包含非法路径段:' + name)
}
if (dir) {
// 只接受 images/ 这一种目录条目;其余目录没有业务含义,放行只会扩大攻击面。
if (body !== 'images') throw new Error('ZIP 只允许 images/ 目录条目:' + name)
return { name, dir: true }
}
if (TOP_FILES.indexOf(name) !== -1) return { name, dir: false }
if (name.indexOf(IMAGE_DIR) !== 0) throw new Error('文件名不在允许的路径内(仅 data.json、meta.json、images/):' + name)
const rest = name.slice(IMAGE_DIR.length)
if (rest.indexOf('/') !== -1) throw new Error('images/ 下不允许再建子目录:' + name)
if (!IMAGE_EXT_RE.test(rest)) throw new Error('图片只允许 .jpg/.jpeg/.png/.webp 后缀:' + name)
return { name, dir: false }
}
function encodeData (data, name) {
if (typeof data === 'string') return new global.TextEncoder().encode(data)
// 用 brand check 而不是 instanceof:模块可能被放在 iframe/vm 等不同 realm 里,
// 跨 realm 的 Uint8Array 用 instanceof 判断会误杀正常输入。
if (Object.prototype.toString.call(data) === '[object Uint8Array]') {
return new global.Uint8Array(data.buffer, data.byteOffset, data.byteLength)
}
throw new Error('文件内容必须是 Uint8Array 或 string:' + name)
}
function storage () {
const S = global.IWBStorageZip
if (!S) throw new Error('ZIP 能力不可用(IWBStorageZip 未加载)')
return S
}
function assertBlob (blob) {
if (!blob || typeof blob.arrayBuffer !== 'function' || typeof blob.size !== 'number') {
throw new Error('解包输入必须是 Blob')
}
}
async function zip (files) {
if (!Array.isArray(files)) throw new Error('打包输入必须是文件数组')
if (files.length > MAX_FILES) throw new Error('文件数超过上限(最多 ' + MAX_FILES + ' 个):' + files.length)
const seen = new Set()
const items = []
let total = 0
// 先把整批文件校验完再动写入器:校验失败时不要留下写了一半的 ZIP。
for (const f of files) {
if (!f || typeof f !== 'object') throw new Error('文件项必须是 { name, data } 对象')
const checked = validateName(f.name)
if (checked.dir) throw new Error('打包列表不能包含目录条目:' + checked.name)
if (seen.has(checked.name)) throw new Error('ZIP 中存在重名条目:' + checked.name)
seen.add(checked.name)
const bytes = encodeData(f.data, checked.name)
if (bytes.byteLength > MAX_FILE_BYTES) throw new Error('单个文件超过上限(16MB):' + checked.name)
total += bytes.byteLength
if (total > MAX_TOTAL_BYTES) throw new Error('文件总大小超过上限(64MB):' + checked.name)
items.push({ name: checked.name, bytes })
}
const S = storage()
if (typeof S.wCreateStoreZip !== 'function') throw new Error('ZIP 写入能力不可用(IWBStorageZip.wCreateStoreZip 缺失)')
const zw = S.wCreateStoreZip()
if (!zw || typeof zw.add !== 'function' || typeof zw.finish !== 'function') throw new Error('ZIP 写入器不可用')
for (const item of items) {
// 每个文件单独一个 Blob:storage-zip 会把 Blob 原样作为 ZIP part,字节不必堆进 JS 堆。
await zw.add(item.name, new global.Blob([item.bytes]))
}
const blob = zw.finish()
if (!blob || typeof blob.arrayBuffer !== 'function') throw new Error('ZIP 写入失败:没有产出 Blob')
return blob
}
// 中央目录预检。返回 null 表示当前客户端没有 wZipParseEntries ——
// 此时只能退化为 files 映射校验(该映射会吞掉重名,属于已知降级)。
async function scanEntries (S, blob) {
if (typeof S.wZipParseEntries !== 'function') return null
let parsed
try {
parsed = S.wZipParseEntries(await blob.arrayBuffer())
} catch (e) {
throw new Error('ZIP 解析失败:' + ((e && e.message) || e))
}
const entries = (parsed && parsed.entries) || []
if (entries.length > MAX_FILES) {
throw new Error('ZIP 条目数超过上限(最多 ' + MAX_FILES + ' 个):' + entries.length)
}
const names = []
const seen = new Set()
let declaredTotal = 0
for (const e of entries) {
const checked = validateName(e && e.name)
if (checked.dir) continue
// 声明大小先卡一道:明显超限的炸弹包不必等读出全部字节才报错。
const rawSize = Number(e.rawSize) || 0
if (rawSize > MAX_FILE_BYTES) throw new Error('解包后单个文件超过上限(16MB):' + checked.name)
declaredTotal += rawSize
if (declaredTotal > MAX_TOTAL_BYTES) throw new Error('解包后总大小超过上限(64MB):' + checked.name)
if (seen.has(checked.name)) throw new Error('ZIP 中存在重名条目:' + checked.name)
seen.add(checked.name)
names.push(checked.name)
}
return names
}
async function unzip (blob) {
assertBlob(blob)
const S = storage()
if (typeof S.wOpenZipBlob !== 'function') throw new Error('ZIP 读取能力不可用(IWBStorageZip.wOpenZipBlob 缺失)')
const parsedNames = await scanEntries(S, blob)
let opened
try {
opened = await S.wOpenZipBlob(blob)
} catch (e) {
throw new Error('ZIP 解析失败:' + ((e && e.message) || e))
}
const map = opened && opened.files
if (!map || typeof map !== 'object') throw new Error('ZIP 打开失败:没有文件表')
let names = parsedNames
if (!names) {
// 降级路径:没有中央目录解析能力时,只能按 files 映射的键校验。
names = Object.keys(map)
if (names.length > MAX_FILES) throw new Error('ZIP 条目数超过上限(最多 ' + MAX_FILES + ' 个):' + names.length)
for (const name of names) validateName(name)
}
const out = []
let total = 0
for (const name of names) {
const entry = (typeof opened.file === 'function') ? opened.file(name) : map[name]
if (!entry || typeof entry.async !== 'function') throw new Error('ZIP 条目读取失败:' + name)
let bytes
try {
bytes = await entry.async('uint8array')
} catch (e) {
throw new Error('ZIP 条目解压失败(' + name + '):' + ((e && e.message) || e))
}
if (!bytes || typeof bytes.byteLength !== 'number') throw new Error('ZIP 条目内容非法:' + name)
// 中央目录里的 rawSize 可以伪造,真实字节数必须再复核一次(zip 炸弹的最终防线)。
if (bytes.byteLength > MAX_FILE_BYTES) throw new Error('解包后单个文件超过上限(16MB):' + name)
total += bytes.byteLength
if (total > MAX_TOTAL_BYTES) throw new Error('解包后总大小超过上限(64MB):' + name)
// 复制一份再交付,避免返回值与 ZIP 内部大 buffer 长期共享(也防止调用方改写源字节)。
out.push({ name, data: new global.Uint8Array(bytes) })
}
return out
}
global.IWBPluginArchive = Object.freeze({ zip, unzip, limits })
})(typeof window !== 'undefined' ? window : globalThis)
+2 -2
View File
@@ -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']
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'}
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' }
function createPluginHost(options) {
const opt = options || {}
+1 -7
View File
@@ -1,10 +1,4 @@
// 确认统一走页内确认(桌面端),网页端保持原生 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 _lstore = () => (typeof global !== 'undefined' && global.IWBStorageLocal && typeof global.IWBStorageLocal.getStore === 'function') ? global.IWBStorageLocal.getStore() : null
@@ -857,7 +851,7 @@
if (!migrated.ok) throw new Error(migrated.error || '画布版本不受支持')
const obj = migrated.value
if (!obj || obj.app !== 'image-workbench' || !Array.isArray(obj.nodes)) throw new Error('文件格式不正确(应为 .iwb.json)')
if (refs.nodes.length && !fromDrop && !(await askConfirm('导入将替换当前画布(' + refs.nodes.length + ' 个节点),确定继续?', { title: '导入画布', okText: '替换' }))) return
if (refs.nodes.length && !fromDrop && !(await window.IWBUIConfirm.askOrNative('导入将替换当前画布(' + refs.nodes.length + ' 个节点),确定继续?', { title: '导入画布', okText: '替换' }))) return
const idMap = {}
const ns = obj.nodes.filter((n) => n && NODE_TYPES.has(n.type)).map((n) => {
const nid = uid('n')
+21 -1
View File
@@ -56,9 +56,29 @@
return str.length <= 8 ? '••••' + str.slice(-2) : str.slice(0, 3) + '••••' + str.slice(-4)
}
// 鉴权方式白名单(2026-11-24,v3.26.65):此前只支持 Bearer,接不了要 x-api-key / URL 参数的中转站。
// 缺省(无 auth 字段)= bearer,保持老配置行为不变。
const AUTH_TYPES = ['bearer', 'header', 'query', 'none']
function wShapeAuth(auth) {
if (!auth || typeof auth !== 'object') return null
const t = String(auth.type || '').trim().toLowerCase()
if (AUTH_TYPES.indexOf(t) < 0) return null
const out = { type: t }
if (t === 'header') {
const hn = String(auth.headerName || '').trim().slice(0, 64)
if (hn) out.headerName = hn
}
if (t === 'query') {
const qn = String(auth.queryName || '').trim().slice(0, 64)
if (qn) out.queryName = qn
}
return out
}
function wShapeProviderFields(pr) {
const out = {}
if (pr && W_SHAPE_KINDS.indexOf(pr.kind) >= 0) out.kind = pr.kind
if (pr) { const a = wShapeAuth(pr.auth); if (a) out.auth = a }
if (pr && pr.requestShape && pr.requestShape.body && typeof pr.requestShape.body === 'object' && !Array.isArray(pr.requestShape.body)) out.requestShape = { body: pr.requestShape.body }
if (pr && Array.isArray(pr.modelRules)) {
const rules = pr.modelRules
@@ -133,7 +153,7 @@
return out
}
return { normalizeEndpointBase, wClone, mergeDeep, wMask, wShapeProviderFields, wNormalizeImageModels, wNormalizeLayerModels, wMigrateLlm, storageResult, wStripDerived }
return { normalizeEndpointBase, wClone, mergeDeep, wMask, wShapeAuth, wShapeProviderFields, wNormalizeImageModels, wNormalizeLayerModels, wMigrateLlm, storageResult, wStripDerived }
}
// 地址归一化(2026-11-05):用户常把「完整接口地址」粘进 Base URL 输入框,而调用方还会再拼一次
+3 -4
View File
@@ -29,7 +29,6 @@
const nodes = props.nodes
const edges = props.edges
const memUi = props.memUi
const setSettingTabReq = props.setSettingTabReq
const setSettingOpen = props.setSettingOpen
const saveState = props.saveState
const saveText = props.saveText
@@ -59,7 +58,7 @@
memUi ? el('button', {
className: 'iwb-status-item iwb-status-mem',
title: '内存占用(点击打开「设置 → 诊断」查看节点/画板/图片构成)',
onClick: () => { setSettingTabReq('diag'); setSettingOpen(true) },
onClick: () => { setSettingOpen('diag') },
}, '内存 ' + memUi.usedMB + '/' + memUi.limitMB + 'MB ' + Math.round((memUi.ratio || 0) * 100) + '%') : null,
saveState !== 'idle' ? el('span', { className: 'iwb-status-item iwb-status-save iwb-status-' + (saveState === 'error' ? 'err' : 'ok') }, saveState === 'saving' ? el('span', { className: 'iwb-save-spinner' }, null) : null, saveText) : null,
(props.memMb && props.memMb > 0) ? el('span', { className: 'iwb-status-item iwb-status-mem', title: '当前进程常驻内存(含画布图片缓存)' }, '内存 ' + props.memMb + 'MB') : null,
@@ -92,7 +91,7 @@
const setWsMoreOpen = props.setWsMoreOpen
return el('div', { className: 'iwb-tab-actions' },
el('button', { className: 'iwb-top-nav-icon', title: '切换主题样式', onClick: toggleTheme }, theme === 'dark' ? I('sun') : I('moon')),
el('button', { className: 'iwb-top-nav-icon', title: '服务与 Key 设置', onClick: () => setSettingOpen(true) }, I('settings')),
el('button', { className: 'iwb-top-nav-icon', title: '服务与 Key 设置', onClick: () => setSettingOpen() }, I('settings')),
el('button', { className: 'iwb-top-nav-icon', title: '更多操作', onClick: (e) => { const r = e.currentTarget.getBoundingClientRect(); setWsMorePos({ top: r.bottom + 6, left: Math.max(6, r.right - 210) }); setWsMoreOpen((v) => !v) } }, I('more')),
)
}
@@ -111,7 +110,7 @@
el('button', { className: 'iwb-product-item' + (shellView === 'landing' ? ' active' : ''), onClick: () => setShellView('landing') }, '首页'),
el('button', { className: 'iwb-product-item' + (shellView === 'home' ? ' active' : ''), onClick: () => setShellView('home') }, '我的画布'),
el('span', { className: 'iwb-product-spacer' }, null),
el('button', { className: 'iwb-product-icon', title: '服务与 Key 设置', onClick: () => setSettingOpen(true) }, I('settings')),
el('button', { className: 'iwb-product-icon', title: '服务与 Key 设置', onClick: () => setSettingOpen() }, I('settings')),
el('button', { className: 'iwb-product-icon', title: '快捷键帮助', onClick: () => setHelpOpen(true) }, I('help')),
el('button', { className: 'iwb-product-icon', title: theme === 'dark' ? '切换到亮色主题' : '切换到暗色主题', onClick: toggleTheme }, theme === 'dark' ? I('sun') : I('moon')),
)
+4 -12
View File
@@ -12,14 +12,6 @@
;(function (global) {
'use strict'
function askConfirm (text, opts) {
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
const native = !!(D && D.isTauri && D.isTauri())
const C = (typeof window !== 'undefined') ? window.IWBUIConfirm : null
if (native && C && typeof C.ask === 'function') return C.ask(Object.assign({ text: text }, opts || {}))
return Promise.resolve(window.confirm(text))
}
// 存储入口收敛(2026-11-06):统一走 IWBStorageLocal 门面,配额/异常集中处理
const _lstore = () => (typeof window !== 'undefined' && window.IWBStorageLocal && typeof window.IWBStorageLocal.getStore === 'function') ? window.IWBStorageLocal.getStore() : null
const React = global.React || {}
@@ -198,8 +190,8 @@ function BackupModal(props) {
const needConfirm = estMB >= 20 || (imgMeta.length + pluginFileMeta.length) >= 20
const sizeText = estMB >= 1 ? ('约 ' + estMB.toFixed(0) + ' MB') : '未记录(按张数估算偏大)'
const countText = imgMeta.length + ' 张图片' + (pluginFileMeta.length ? '(另含 ' + pluginFileMeta.length + ' 个插件文件)' : '')
if (needConfirm && typeof window !== 'undefined' && typeof window.confirm === 'function') {
const okGo = await askConfirm('本次备份包含 ' + countText + ',预计体积 ' + sizeText + '。\n导出期间内存占用会明显上升,图库很大时页面会变慢。\n确定继续导出吗?', { title: '导出备份', okText: '继续导出' })
if (needConfirm && typeof window !== 'undefined' && window.IWBUIConfirm) {
const okGo = await window.IWBUIConfirm.askOrNative('本次备份包含 ' + countText + ',预计体积 ' + sizeText + '。\n导出期间内存占用会明显上升,图库很大时页面会变慢。\n确定继续导出吗?', { title: '导出备份', okText: '继续导出' })
if (!okGo) {
setBkMsg({ type: 'err', text: '已取消导出(' + countText + ' / ' + sizeText + ')' })
return
@@ -385,7 +377,7 @@ function BackupModal(props) {
const items = restoreData.items
const want = Object.keys(restoreSel).filter((k) => restoreSel[k])
if (!want.length) { setRstMsg({ type: 'err', text: '请至少勾选一项要恢复的数据' }); return }
if (!(await askConfirm((restoreMerge ? '将以「合并」方式导入(追加去重,不覆盖已有):' : '将用备份覆盖当前数据:') + want.map((k) => ({ config: '设置', prompts: '提示词库', nodeGroups: '节点组', workspaces: '画布工作台', outputs: '图库(含缩略图+原图)' })[k]).join('、') + '。确定恢复?', { title: '恢复备份', okText: '开始恢复' }))) return
if (!(await window.IWBUIConfirm.askOrNative((restoreMerge ? '将以「合并」方式导入(追加去重,不覆盖已有):' : '将用备份覆盖当前数据:') + want.map((k) => ({ config: '设置', prompts: '提示词库', nodeGroups: '节点组', workspaces: '画布工作台', outputs: '图库(含缩略图+原图)' })[k]).join('、') + '。确定恢复?', { title: '恢复备份', okText: '开始恢复' }))) return
setRstBusy(true); setRstMsg(null)
try {
props.onSaveNow && props.onSaveNow() // 导入前保存当前画布(避免导入后丢失未保存改动)
@@ -482,7 +474,7 @@ function BackupModal(props) {
for (const m of keepMiss) { const t = (m && (m.label || m.path)) || '密钥'; if (uniqLabel.indexOf(t) === -1) uniqLabel.push(t) }
keepWarn = '⚠︎ 有 ' + keepMiss.length + ' 个密钥字段在备份里是「保留本机原值」(__KEEP__),但本机没有对应值,已保持为空:' + uniqLabel.slice(0, 3).join('、') + (uniqLabel.length > 3 ? ' 等 ' + uniqLabel.length + ' 类' : '') + '。请到「服务与 Key 设置」里补填。'
wLog('restore', 'KEEP-MISS:' + keepMiss.map((m) => m && m.path).join(', '))
try { await askConfirm(keepWarn + '\n\n点「确定」继续(恢复已完成,随后刷新页面生效)。', { title: '恢复提示', okText: '知道了', cancelText: '关闭' }) } catch (e) { /* ignore */ }
try { await window.IWBUIConfirm.askOrNative(keepWarn + '\n\n点「确定」继续(恢复已完成,随后刷新页面生效)。', { title: '恢复提示', okText: '知道了', cancelText: '关闭' }) } catch (e) { /* ignore */ }
}
setRstMsg({
type: (imgBad.length || keepWarn) ? 'err' : 'ok',
+39
View File
@@ -106,6 +106,40 @@ function Minimap(props) {
)
}
// 底栏「插件节点」入口:拼图图标 + 点开列出所有插件节点(2026-11-26)
function PluginAddButton(props) {
const [open, setOpen] = useState(false)
const boxRef = useRef(null)
useEffect(() => {
if (!open) return undefined
const onDoc = (e) => { if (boxRef.current && !boxRef.current.contains(e.target)) setOpen(false) }
const onKey = (e) => { if (e.key === 'Escape') setOpen(false) }
document.addEventListener('pointerdown', onDoc, true)
document.addEventListener('keydown', onKey)
return () => { document.removeEventListener('pointerdown', onDoc, true); document.removeEventListener('keydown', onKey) }
}, [open])
const list = Array.isArray(props.variants) ? props.variants : []
return el('span', { className: 'iwb-plugin-add-wrap', ref: boxRef },
el('button', {
className: 'iwb-btn iwb-plugin-add' + (open ? ' iwb-btn-on' : ''),
'data-tip': '插件节点(相册 / 网页 / 样式…)',
'aria-label': '插件节点',
'aria-haspopup': 'menu',
'aria-expanded': open ? 'true' : 'false',
onPointerDown: (e) => e.stopPropagation(),
onClick: () => setOpen((x) => !x),
}, I('puzzle')),
open ? el('div', { className: 'iwb-plugin-add-menu', role: 'menu' },
list.map((pv) => el('button', {
key: pv.id,
className: 'iwb-ctx-item',
role: 'menuitem',
onClick: () => { setOpen(false); if (typeof props.onPick === 'function') props.onPick(pv.id) },
}, I('puzzle'), el('span', { className: 'iwb-btn-text' }, pv.title || pv.id))),
) : null,
)
}
function ToolbarBottom(props) {
const { onAdd, onOpenPrompts, onFitView, onZoom, tool, onTool } = props
// 工具组(2026-10-31):互斥「选择 / 抓手」。抓手 = 空格+左键的固化版(不用按住空格),
@@ -134,6 +168,11 @@ function ToolbarBottom(props) {
el('button', { className: 'iwb-btn', 'data-tip': '中继', onClick: () => onAdd('relay') }, I('circle-dot')),
el('button', { className: 'iwb-btn', 'data-tip': '配置', onClick: () => onAdd('gen') }, I('gen')),
el('button', { className: 'iwb-btn', 'data-tip': '输出', onClick: () => onAdd('out') }, I('presentation')),
// 插件节点入口(2026-11-26):拼图图标按钮 + 弹出列表。
// 不用文字下拉(用户裁定:插件入口只用图标),也不用弹层库:一个按钮 + 一个绝对定位列表即可。
(Array.isArray(props.pluginVariants) && props.pluginVariants.length)
? el(PluginAddButton, { variants: props.pluginVariants, onPick: props.onAddPlugin, I })
: null,
),
// v3.25.82:底栏「资源库」按钮已删(右侧栏/提示词库面板已覆盖该入口,用户裁定)
// 最右侧独立一格:缩放(−/+)+ 适应视图(显示全部节点)。适应与快捷键 Shift+F 等价。
+2 -1
View File
@@ -9,7 +9,8 @@
const item = props.item || {}
const doCopyRef = () => { props.onCopyRef && props.onCopyRef(item.url) }
const doCopyLink = () => {
try { if (global.navigator && global.navigator.clipboard) global.navigator.clipboard.writeText(item.url) } catch (e) { /* ignore */ }
// 统一走 IWBClipboardCopy(2026-11-24)
try { if (global.IWBClipboardCopy) global.IWBClipboardCopy.copyText(item.url) } catch (e) { /* ignore */ }
}
return el('div', {
className: 'iwb-rimg',
+110 -16
View File
@@ -7,12 +7,35 @@
* · 底部组:帮助 / 快捷键 / 皮肤 / 设置 / 更多
* · 选中态 = 深色圆底 + 白色图标;未选中 = 线性图标;悬停 = 浅灰圆底
*
* 纯展示组件:所有回调与当前视图经 props 传入,不读 Workbench 局部状态。
* 2026-11-25:底部「更多」从空操作改为**快捷菜单**(首页 / 插件 / 源码 / 版本号),
* 并在桌面端自动检查更新:有新版本时 ⋯ 变成「圆形上箭头」升级图标,点开菜单首项即可升级。
* 更新检查/安装走 Tauri 的 check_update / install_update(签名校验在 Rust 侧)。
* 全部状态自持于本组件,app.js 不需要新增状态或逻辑。
*/
;(function (global) {
'use strict'
const React = global.React || {}
const ReactDOM = global.ReactDOM || {}
const el = (type, prop, ...children) => React.createElement(type, prop, ...children)
const useState = React.useState
const useEffect = React.useEffect
// 升级图标(圆形内向上箭头):ICONS 在 app.js 里且行数已到棘轮上限,这里内联一份,不动宿主。
const UPGRADE_PATH = '<circle cx="12" cy="12" r="9"/><path d="M12 16V8"/><path d="m8.5 11.5 3.5-3.5 3.5 3.5"/>'
function UpgradeIcon () {
return el('svg', {
className: 'iwb-ic', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true,
dangerouslySetInnerHTML: { __html: UPGRADE_PATH },
}, null)
}
const SOURCE_URL = 'https://github.com/malongan/image-workbench-web'
function invoke (cmd) {
const T = (typeof window !== 'undefined') ? window.__TAURI__ : null
if (!T || !T.core || typeof T.core.invoke !== 'function') return Promise.reject(new Error('桌面端不可用'))
return T.core.invoke(cmd)
}
function IWBUINavRail (props) {
const I = props.I
@@ -24,9 +47,41 @@
const onHotkeys = props.onHotkeys
const onSkin = props.onSkin
const onSettings = props.onSettings
const onMore = props.onMore
const skinIcon = props.skinIcon || 'moon'
const logoIcon = props.logoIcon || 'palette'
const appVersion = props.appVersion || ''
const [moreOpen, setMoreOpen] = useState(false)
const [morePos, setMorePos] = useState(null)
const [update, setUpdate] = useState(null) // null=无更新;{version,...}=有新版本
const [updateMsg, setUpdateMsg] = useState('')
const checkUpdate = () => {
setUpdateMsg('正在检查…')
return invoke('check_update').then((r) => {
setUpdate(r && r.version ? r : null)
setUpdateMsg(r && r.version ? ('发现新版本 v' + r.version) : '已是最新版本')
}).catch((e) => {
setUpdate(null)
const m = String((e && e.message) || e)
// 网页版没有 Tauri 桥,检查更新必然失败;不把这种「预期内不可用」当成错误抛给用户
setUpdateMsg(m.indexOf('桌面端不可用') >= 0 ? '' : '检查失败:' + m)
})
}
// 挂载后静默检查一次(仅桌面端;网页版 invoke 立即 reject,被 catch 吞掉,不留 UI 噪音)
useEffect(() => { checkUpdate() }, [])
const upgrade = () => {
setUpdateMsg('正在下载并安装,完成后会自动重启…')
invoke('install_update').then(() => setUpdateMsg('安装完成,正在重启…'))
.catch((e) => setUpdateMsg('更新失败:' + String((e && e.message) || e)))
}
useEffect(() => {
if (!moreOpen) return undefined
const onDown = (e) => { if (!e.target.closest || !e.target.closest('.iwb-nav-more-menu, .iwb-nav-more-btn')) setMoreOpen(false) }
const onKey = (e) => { if (e.key === 'Escape') setMoreOpen(false) }
document.addEventListener('pointerdown', onDown, true)
document.addEventListener('keydown', onKey, true)
return () => { document.removeEventListener('pointerdown', onDown, true); document.removeEventListener('keydown', onKey, true) }
}, [moreOpen])
const item = (key, iconName, title, active, onClick) => el('button', {
key,
@@ -39,22 +94,61 @@
onClick: (e) => { e.stopPropagation(); if (typeof onClick === 'function') onClick(e) },
}, I(iconName))
return el('nav', { className: 'iwb-navrail', 'aria-label': '一级导航' },
// v3.25.65:品牌 logo 移到顶部画布标签条(用户裁定),导航从图标组开始
el('div', { className: 'iwb-navrail-group' },
// v3.25.62:导航的「首页」保留(这是新版入口),删掉的是标签条里那个旧房子按钮
item('home', 'home', '首页(画布库)', view === 'home', onHome),
item('canvas', 'layer', '列表(画布工作区)', view === 'canvas', onCanvas),
item('plugins', 'box', '插件', view === 'plugins', onPlugins),
const toggleMore = (e) => {
const r = e.currentTarget.getBoundingClientRect()
setMorePos({ left: Math.max(6, r.right + 6), bottom: Math.max(6, global.innerHeight - r.bottom + 6) })
setMoreOpen((v) => !v)
}
const act = (fn) => (e) => { e.stopPropagation(); setMoreOpen(false); if (typeof fn === 'function') fn(e) }
const menuItem = (key, iconNode, text, onClick, cls) => el('button', {
key, type: 'button', className: 'iwb-ctx-item' + (cls ? ' ' + cls : ''), onClick,
}, iconNode, el('span', null, text))
const menu = !moreOpen || !morePos ? null : ReactDOM.createPortal(
el('div', {
className: 'iwb-ctxmenu iwb-nav-more-menu',
style: { left: morePos.left + 'px', bottom: morePos.bottom + 'px' },
onPointerDown: (e) => e.stopPropagation(),
},
update ? menuItem('up', el(UpgradeIcon, null), '升级到 v' + update.version + (update.notes ? ':' + update.notes : ''), act(upgrade), 'iwb-nav-more-up') : null,
menuItem('home', I('home'), '首页', act(onHome)),
menuItem('plugins', I('box'), '插件', act(onPlugins)),
el('a', {
key: 'src', className: 'iwb-ctx-item', href: SOURCE_URL, target: '_blank', rel: 'noopener',
onClick: () => setMoreOpen(false),
}, I('github'), el('span', null, '源码地址')),
el('div', { key: 'ver', className: 'iwb-nav-more-ver' }, '版本 ' + (appVersion || '未知')),
updateMsg ? el('div', { key: 'msg', className: 'iwb-nav-more-ver' }, updateMsg) : null,
!update ? menuItem('check', I('refresh'), '检查更新', act(checkUpdate)) : null,
),
el('div', { className: 'iwb-navrail-spacer' }),
el('div', { className: 'iwb-navrail-group' },
item('help', 'help', '帮助', false, onHelp),
item('hotkeys', 'circle-dot', '快捷键', false, onHotkeys),
item('skin', skinIcon, '切换主题', false, onSkin),
item('settings', 'settings', '设置', false, onSettings),
item('more', 'more', '更多', false, onMore),
global.document.body,
)
return el(React.Fragment, null,
el('nav', { className: 'iwb-navrail', 'aria-label': '一级导航' },
el('div', { className: 'iwb-navrail-group' },
item('home', 'home', '首页(画布库)', view === 'home', onHome),
item('canvas', 'layer', '列表(画布工作区)', view === 'canvas', onCanvas),
item('plugins', 'box', '插件', view === 'plugins', onPlugins),
),
el('div', { className: 'iwb-navrail-spacer' }),
el('div', { className: 'iwb-navrail-group' },
item('help', 'help', '帮助', false, onHelp),
item('hotkeys', 'circle-dot', '快捷键', false, onHotkeys),
item('skin', skinIcon, '切换主题', false, onSkin),
item('settings', 'settings', '设置', false, onSettings),
el('button', {
key: 'more', type: 'button',
className: 'iwb-nav-item iwb-nav-more-btn' + (update ? ' has-update' : '') + (moreOpen ? ' on' : ''),
title: update ? ('发现新版本 v' + update.version + ',点击升级') : '更多',
'aria-label': update ? '发现新版本,点击升级' : '更多',
'aria-expanded': moreOpen ? 'true' : 'false',
onPointerDown: (e) => e.stopPropagation(),
onClick: (e) => { e.stopPropagation(); toggleMore(e) },
}, update ? el(UpgradeIcon, null) : I('more')),
),
),
menu,
)
}
+8 -11
View File
@@ -1,10 +1,4 @@
// 确认统一走页内确认(桌面端),网页端保持原生 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'
@@ -273,9 +267,8 @@
}
const copy = async () => {
const v = readMd()
try { await navigator.clipboard.writeText(v) } catch (e) {
try { const r = editorRef.current; if (r) { const rg = document.createRange(); rg.selectNodeContents(r); const sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(rg); document.execCommand('copy') } } catch (e2) { /* ignore */ }
}
// 复制统一走 IWBClipboardCopy(2026-11-24):降级链在里面,这里不再自造选区+execCommand 兜底
try { await (window.IWBClipboardCopy ? window.IWBClipboardCopy.copyText(v) : Promise.resolve(false)) } catch (e) { /* ignore */ }
setCopied(true)
setTimeout(() => setCopied(false), 1200)
}
@@ -1062,7 +1055,7 @@
title: (taskQueued ? '已排队,等待提交…' : '已提交,正在等待服务商返回(点击可提前结束,需确认)'),
onClick: async () => {
if (!props.onCancel) return
if (!(await askConfirm('该任务仍在等待服务商返回' + (taskQueued ? '(尚未提交)' : '(已 ' + fmtDur(stallMs) + ' 无新进展)') + '。\n\n确定要提前结束这个任务吗?只会停止本任务的等待,不影响同批其他任务;服务商侧可能已生成,是否重试由你决定。', { title: '提前结束任务', okText: '结束' }))) return
if (!(await window.IWBUIConfirm.askOrNative('该任务仍在等待服务商返回' + (taskQueued ? '(尚未提交)' : '(已 ' + fmtDur(stallMs) + ' 无新进展)') + '。\n\n确定要提前结束这个任务吗?只会停止本任务的等待,不影响同批其他任务;服务商侧可能已生成,是否重试由你决定。', { title: '提前结束任务', okText: '结束' }))) return
props.onCancel(node.id, t.id)
},
onPointerDown: stop,
@@ -1101,7 +1094,11 @@
genParams,
!tasks.length ? el('div', { className: 'iwb-err' }, '请连接 提示词节点(或 文本节点,可连多个,每个生成一个任务)') : null,
taskBulkBar,
taskEls.length ? el('div', { className: 'iwb-tasks' }, taskEls) : null,
/* 任务容器按「任务 id 集合」重建(2026-11-26):相册等多图源节点切模式后任务数会变
* (22 → 3),实测宿主此时 React 树已是新任务、DOM 却留着旧行(fiber child=3 / DOM=22,
* 同一 root,不是外部注入)。给容器一个随任务身份变化的 key ⇒ 任务集合一变就重挂载,
* DOM 必然按新列表重建。key 只含 id,不含文本 ⇒ 打字不会重挂载(输入不丢焦点)。 */
taskEls.length ? el('div', { className: 'iwb-tasks', key: 'tasks:' + tasks.map((t) => t.id).join('|') }, taskEls) : null,
)
}
+7 -11
View File
@@ -9,13 +9,6 @@
*
* ⚠️ 依赖清单是用 ESLint 的 no-undef 反推出来的(不是人肉枚举),漏项会被 CI 直接抓到。
*/
// 确认统一走页内确认(桌面端),网页端保持原生 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'
// 存储入口收敛(2026-11-06):统一走 IWBStorageLocal 门面,配额/异常集中处理
@@ -138,7 +131,9 @@ function SetGroup (props) {
}
function SettingsModal(props) {
const [tab, setTab] = useState(props.initialTab || 'gen')
// 2026-11-25:默认落「通用」(用户裁定)——此前默认 gen(生图服务),
// 多数人打开设置是找通用项;initialTab 仍可由宿主显式指定(如顶部「内存」→ 诊断页)。
const [tab, setTab] = useState(props.initialTab || 'general')
// 诊断页「刷新」:重读崩溃记录后需要一个自增值触发重渲染。
// 原来裸用 setDiagRev(从未声明)⇒ 点刷新会 ReferenceError。补上它就是原意。
const [, setDiagRev] = useState(0)
@@ -152,6 +147,7 @@ function SettingsModal(props) {
const it = base.imageTransfer || { mode: 'base64', 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' } }
return {
providers: JSON.parse(JSON.stringify((base.providers || []).map((p) => ({ ...p, models: wNormalizeImageModels(p.models), layerModels: wNormalizeLayerModels(p.layerModels) })))),
defaultGen: base.defaultGen ? JSON.parse(JSON.stringify(base.defaultGen)) : null,
imgbbKey: '',
imgbbMasked: (base.imgbb && base.imgbb.masked) || '',
it: JSON.parse(JSON.stringify(it)),
@@ -311,7 +307,7 @@ function SettingsModal(props) {
if (!cur.some((m) => m && m.name === name)) return
const usedBy = (props.nodes || []).filter((n) => n && n.type === 'layer' && n.data && n.data.model === name && !(n.data && n.data.enabled === false)).length
const warning = usedBy ? '该模型正在被 ' + usedBy + ' 个分层节点使用。删除后这些节点会显示模型不可用。\n\n确定删除「' + name + '」吗?' : '确定删除分层模型「' + name + '」吗?'
if (!(await askConfirm(warning, { title: '删除分层模型', okText: '删除' }))) return
if (!(await window.IWBUIConfirm.askOrNative(warning, { title: '删除分层模型', okText: '删除' }))) return
setProv(pi, { layerModels: wNormalizeLayerModels(cur.filter((m) => !(m && m.name === name))) })
}
const delModel = async (pi, name) => {
@@ -324,7 +320,7 @@ function SettingsModal(props) {
}
const usedBy = (props.nodes || []).filter((n) => n && n.type === 'gen' && n.data && n.data.model === name && !(n.data && n.data.enabled === false)).length
const warning = usedBy ? '该模型正在被 ' + usedBy + ' 个生图节点使用。删除后这些节点将显示模型不可用,需要重新选择。\n\n确定删除「' + name + '」吗?' : '确定删除模型「' + name + '」吗?'
if (!(await askConfirm(warning, { title: '删除模型', okText: '删除' }))) return
if (!(await window.IWBUIConfirm.askOrNative(warning, { title: '删除模型', okText: '删除' }))) return
const models = (p.models || []).filter((m) => m && m.name !== name)
const patch = { models }
if (p.defaultModel === name) {
@@ -560,7 +556,7 @@ function SettingsModal(props) {
try {
const before = storageAudit || ((typeof props.onStorageAudit === 'function') ? await props.onStorageAudit() : null)
const cnt = before ? ('IDB 图片键 ' + before.total + ' 个;悬空输出索引 ' + before.danglingOutputIndex + ';孤儿输出字节 ' + before.orphanOutputBytes + ' 个') : '(未体检)'
if (!(await askConfirm('将执行一次安全孤儿回收:只删除未被任何画板 / 剪贴板 / 收藏组 / 历史 / 图库引用的图片字节(绝不删活引用)。\n\n当前:' + cnt + '\n\n继续?', { title: '孤儿回收', okText: '开始回收' }))) return
if (!(await window.IWBUIConfirm.askOrNative('将执行一次安全孤儿回收:只删除未被任何画板 / 剪贴板 / 收藏组 / 历史 / 图库引用的图片字节(绝不删活引用)。\n\n当前:' + cnt + '\n\n继续?', { title: '孤儿回收', okText: '开始回收' }))) return
const after = (typeof props.onReclaimOrphans === 'function') ? await props.onReclaimOrphans() : null
if (after) setStorageAudit(after)
setMsg({ type: 'ok', text: '已回收孤儿图片字节' + (after ? ('(现存 ' + after.total + ' 个图片键)') : '') })
+85 -37
View File
@@ -100,15 +100,6 @@
)
}
// 桌面端用页内确认(window.confirm 会阻塞 WKWebView 主线程 ⇒ 界面像死机)
function askConfirm (text, opts) {
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
const native = !!(D && D.isTauri && D.isTauri())
const C = (typeof window !== 'undefined') ? window.IWBUIConfirm : null
if (native && C && typeof C.ask === 'function') return C.ask(Object.assign({ text: text }, opts || {}))
return Promise.resolve(window.confirm(text))
}
// 开发者模式开关(走统一存储门面,src 不得直调 localStorage)
function pluginDevStore () {
const L = (typeof window !== 'undefined') ? window.IWBStorageLocal : null
@@ -310,8 +301,8 @@
registered: (pluginItems || []).map(function (p) { return { id: p.id, enabled: p.enabled, compatible: p.compatible } }),
}
const text = JSON.stringify(payload, null, 2)
try { await navigator.clipboard.writeText(text) } catch (e) { try { const ta = document.createElement('textarea'); ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); ta.remove() } catch (e2) { /* ignore */ } }
setMsg('诊断已复制到剪贴板')
const okCopy = await (window.IWBClipboardCopy ? window.IWBClipboardCopy.copyText(text) : Promise.resolve(false))
setMsg(okCopy ? '诊断已复制到剪贴板' : '复制失败(权限被拒或非安全上下文);可用「导出 JSON」')
} catch (e) { setMsg('诊断生成失败:' + String((e && e.message) || e)) }
},
}, '复制诊断'),
@@ -595,7 +586,7 @@ function GSetGroup (props) {
try {
const d = await F.pickDir()
if (!d || d === dataDir) return
if (!(await askConfirm('切换资料目录?\n\n当前数据会先保存到当前目录,然后窗口重载并从新目录装载。\n新目录:' + d, { title: '切换资料目录', okText: '切换' }))) return
if (!(await window.IWBUIConfirm.askOrNative('切换资料目录?\n\n当前数据会先保存到当前目录,然后窗口重载并从新目录装载。\n新目录:' + d, { title: '切换资料目录', okText: '切换' }))) return
await F.switchTo(d)
setDataDir(d); setNote('已切换,正在重载…')
} catch (e) { setNote('切换失败:' + String((e && e.message) || e)) }
@@ -608,7 +599,7 @@ function GSetGroup (props) {
try {
const d = await F.pickDir()
if (!d || d === dataDir) return
if (!(await askConfirm('把整个数据库复制到:\n' + d + '\n\n复制完成后自动切换并重载;原目录会保留,确认无误后可手动删除。\n(图片较多时会花几十秒)', { title: '转移数据库', okText: '开始复制' }))) return
if (!(await window.IWBUIConfirm.askOrNative('把整个数据库复制到:\n' + d + '\n\n复制完成后自动切换并重载;原目录会保留,确认无误后可手动删除。\n(图片较多时会花几十秒)', { title: '转移数据库', okText: '开始复制' }))) return
setNote('正在复制,请稍候…')
await F.migrateTo(d)
} catch (e) { setNote('转移失败:' + String((e && e.message) || e)) }
@@ -641,7 +632,7 @@ function GSetGroup (props) {
if (rDry.keptByCanvas) lines.push('其中 ' + rDry.keptByCanvas + ' 张虽然登记表里没有,但画布仍在引用 → 会自动保留。')
if (rDry.dangling) lines.push('另有 ' + rDry.dangling + ' 处画布引用已经找不到图片(之前丢的,本次不影响它们)。')
lines.push('移动到 trash/(不直接删除,可在回收站找回)?')
if (!(await askConfirm(lines.join('\n'), { title: '清理未引用图片', okText: '移动' }))) return
if (!(await window.IWBUIConfirm.askOrNative(lines.join('\n'), { title: '清理未引用图片', okText: '移动' }))) return
const rGo = await F.gcImages({ dryRun: false })
setNote(rGo.ok
? ('已移入 trash/:' + rGo.moved + ' 个文件' + (rGo.dangling ? (';另有 ' + rGo.dangling + ' 处引用已缺图') : ''))
@@ -696,8 +687,32 @@ function GSetGroup (props) {
function renderGeneralTab (ctx) {
const { TASK_STALL_END_MAX, TASK_STALL_END_MIN, appVersion, draft, imageLibSection, setDraft } = ctx
const DG = (typeof window !== 'undefined' && window.IWBDefaultGenModel) || null
const dgOpts = DG ? DG.wDefaultGenOptions(draft) : []
// 显示的是「生效值」而不是原始配置:未配置/失效时也会指向主服务首个可见模型,
// 与模型行上的「默认」标识、新建节点预选值三处保持一致(2026-11-25)。
const dgEff = DG ? DG.wResolveDefaultGen(draft) : null
const dgVal = dgEff ? dgEff.providerId + '::' + dgEff.model : ''
return el('div', { className: 'iwb-gset-page' },
el(VersionBlock, { version: appVersion }),
el(GSetGroup, { title: '新建配置节点' },
el('div', { className: 'iwb-gset-row' },
el('span', { className: 'iwb-gset-row-label' }, '默认模型'),
el('div', { className: 'iwb-gset-row-ctl' },
el('select', {
className: 'iwb-input', 'aria-label': '新建配置节点默认模型',
value: dgOpts.some((o) => o.providerId + '::' + o.model === dgVal) ? dgVal : '', onChange: (e) => {
const hit = dgOpts.find((o) => o.providerId + '::' + o.model === e.target.value)
setDraft((d) => ({ ...d, defaultGen: hit ? { providerId: hit.providerId, model: hit.model, keyGroup: hit.keyGroup } : null }))
},
},
el('option', { value: '' }, '未设置(用系统默认)'),
dgOpts.map((o) => el('option', { key: o.providerId + '::' + o.model, value: o.providerId + '::' + o.model }, o.label)),
),
),
),
el('div', { className: 'iwb-gset-hint' }, '新建「配置」节点时预选这里选的模型;删除或关闭该模型后自动回退到主服务第一个启用的模型。已有节点不受影响。'),
),
isDesk() ? el(DownloadDirBlock, null) : el(GSetGroup, { title: '数据与目录' }, el(DataDirRow, null),
),
el(GSetGroup, { title: '图片与图库' }, imageLibSection || null,
@@ -881,11 +896,11 @@ function GSetGroup (props) {
el('button', {
className: 'iwb-btn iwb-btn-sm',
onClick: async () => {
const okGo = await askConfirm('用这份备份覆盖当前本机数据?\n\n覆盖后会' + (isDesk() ? '自动重载窗口' : '立即刷新页面') + '。当前数据不会保留,建议先「导出备份」。', { title: '还原自动备份', okText: '还原' })
const okGo = await window.IWBUIConfirm.askOrNative('用这份备份覆盖当前本机数据?\n\n覆盖后会' + (isDesk() ? '自动重载窗口' : '立即刷新页面') + '。当前数据不会保留,建议先「导出备份」。', { title: '还原自动备份', okText: '还原' })
if (!okGo) return
Promise.resolve(props.autoBackupRestore && props.autoBackupRestore(row.name)).then((r) => {
if (r && r.ok) location.reload()
else askConfirm('还原失败:' + ((r && r.error) || '未知错误'), { title: '还原失败', okText: '知道了', cancelText: '关闭' })
else window.IWBUIConfirm.askOrNative('还原失败:' + ((r && r.error) || '未知错误'), { title: '还原失败', okText: '知道了', cancelText: '关闭' })
})
},
}, '还原此份'),
@@ -978,6 +993,8 @@ function GSetGroup (props) {
const { DEFAULT_SHAPE_TPL, I, W_SHAPE_KINDS, addAddr, addKey, addLayerModel, addModel, addProvider, api, delAddr, delKey, delLayerModel, delModel, delProv, draft, layerModelInput, makeProviderDefault, modelInput, modelSupportsQuality, provSel, setAddr, setDefault, setKey, setLayerModelInput, setModelInput, setModelKind, setModelQuality, setProv, setProvSel, setShapeText, shapeText, speed, speedTest, toggleLayerModel, toggleModel, wNormalizeLayerModels, wPrivateToolsOn } = ctx
const provCards = []
const providersAll = draft.providers || []
const DGM = (typeof window !== 'undefined' && window.IWBDefaultGenModel) || null
const dgEff = DGM ? DGM.wResolveDefaultGen(draft) : null
const selectedId = provSel && providersAll.some((p) => p.id === provSel) ? provSel : ((providersAll[0] && providersAll[0].id) || '')
const chips = el('div', { className: 'iwb-prov-chips', role: 'tablist', 'aria-label': '服务商' },
providersAll.map((p, i) => el('button', {
@@ -1070,11 +1087,16 @@ function GSetGroup (props) {
shapeMore,
)
const sp = speed && speed.providerId === p.id ? speed : null
const modelRows = (p.models || []).map((m) => el('div', { key: m.name, className: 'iwb-modelrow' },
el('label', { className: 'iwb-check iwb-modelrow-main', title: m.name + '(勾选=在生图节点下拉里可见)' },
const modelRows = (p.models || []).map((m) => {
const isDefault = !!(dgEff && dgEff.providerId === p.id && dgEff.model === m.name)
return el('div', { key: m.name, className: 'iwb-modelrow' + (isDefault ? ' iwb-modelrow-active iwb-modelrow-default' : '') },
// 2026-11-25:启用改为圆角开关(沿用通用 .iwb-switch),checkbox 仍在 DOM 内(隐藏)以兼容既有选择器。
el('label', { className: 'iwb-switch iwb-modelrow-main', title: m.name + '(开启=在生图节点下拉里可见)' },
el('input', { type: 'checkbox', checked: m.visible !== false, onChange: (e) => toggleModel(pi, m.name, e.target.checked) }, null),
el('span', { className: 'iwb-switch-track' }, el('span', { className: 'iwb-switch-dot' }, null)),
el('span', { className: 'iwb-modelrow-name', title: m.name }, m.name),
),
isDefault ? el('span', { className: 'iwb-modelrow-defmark' }, '默认') : null,
// v3.87.31:「质量」用**胶囊样式**(复选框仍在 DOM 内且可见,兼容既有测试选择器;点亮=支持质量档位)
el('label', {
className: 'iwb-modelrow-q iwb-quality-toggle' + (modelSupportsQuality(p, m.name) ? ' on' : ''),
@@ -1100,30 +1122,34 @@ function GSetGroup (props) {
el('option', { value: 'doubao' }, 'doubao'),
el('option', { value: 'custom' }, 'custom'),
),
el('details', { className: 'iwb-model-more' },
el('summary', { className: 'iwb-model-more-btn', title: '更多操作', 'aria-label': '更多操作 ' + m.name }, '⋯'),
el('div', { className: 'iwb-ctxmenu iwb-model-more-menu' },
m.source !== 'builtin'
? el('button', { className: 'iwb-model-more-del', title: '删除模型', 'aria-label': '删除模型 ' + m.name, onClick: () => delModel(pi, m.name) }, '删除模型')
: el('div', { className: 'iwb-model-more-hint' }, '内置模型不可删除'),
),
),
))
// 2026-11-25:删除从「⋯ 更多」里提到行内垃圾桶按钮(用户裁定)。
// 内置模型保留按钮但禁用,title 说明原因——比藏掉更能解释「为什么不能删」。
el('button', {
type: 'button', className: 'iwb-model-del',
title: m.source === 'builtin' ? '内置模型不可删除' : '删除模型',
'aria-label': '删除模型 ' + m.name,
disabled: m.source === 'builtin',
onPointerDown: (e) => e.stopPropagation(),
onClick: (e) => { e.stopPropagation(); if (m.source !== 'builtin') delModel(pi, m.name) },
}, I('trash')),
)
})
// 分层模型行:结构与生图模型行一致(同一套 .iwb-modellist/.iwb-modelrow 样式);
// 内置项既不能删也不能隐藏(隐藏会让分层节点没有模型可选)。
const layerModelRows = wNormalizeLayerModels(p.layerModels).map((m) => el('div', { key: 'L:' + m.name, className: 'iwb-modelrow' },
el('label', { className: 'iwb-check iwb-modelrow-main' },
el('label', { className: 'iwb-switch iwb-modelrow-main', title: m.source === 'builtin' ? '内置分层模型,始终可用' : '开启=在分层节点里可见' },
el('input', { type: 'checkbox', checked: true, disabled: m.source === 'builtin', onChange: (e) => toggleLayerModel(pi, m.name, e.target.checked) }, null),
el('span', null, m.name),
),
el('details', { className: 'iwb-model-more' },
el('summary', { className: 'iwb-model-more-btn', title: '更多操作', 'aria-label': '更多操作 ' + m.name }, '⋯'),
el('div', { className: 'iwb-ctxmenu iwb-model-more-menu' },
m.source !== 'builtin'
? el('button', { className: 'iwb-model-more-del', title: '删除分层模型', 'aria-label': '删除分层模型 ' + m.name, onClick: () => delLayerModel(pi, m.name) }, '删除分层模型')
: el('div', { className: 'iwb-model-more-hint' }, '内置分层模型不可删除'),
),
el('span', { className: 'iwb-switch-track' }, el('span', { className: 'iwb-switch-dot' }, null)),
el('span', { className: 'iwb-modelrow-name', title: m.name }, m.name),
),
el('button', {
type: 'button', className: 'iwb-model-del',
title: m.source === 'builtin' ? '内置分层模型不可删除' : '删除分层模型',
'aria-label': '删除分层模型 ' + m.name,
disabled: m.source === 'builtin',
onPointerDown: (e) => e.stopPropagation(),
onClick: (e) => { e.stopPropagation(); if (m.source !== 'builtin') delLayerModel(pi, m.name) },
}, I('trash')),
))
provCards.push(el('div', { key: p.id, className: 'iwb-provider-card' },
el(GSetGroup, { title: '服务' },
@@ -1166,6 +1192,26 @@ function GSetGroup (props) {
keyRows,
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => addKey(pi) }, '+ 添加 Key 分组'),
),
// 认证方式(2026-11-24,v3.26.65):此前写死 Authorization: Bearer,接不了要 x-api-key / URL 参数的中转站。
el(GSetGroup, { title: '认证', desc: '缺省 Bearer;部分中转站要自定义 Header 或 URL 参数' },
(() => {
const auth = (p.auth && typeof p.auth === 'object') ? p.auth : { type: 'bearer' }
const t = ['bearer', 'header', 'query', 'none'].indexOf(auth.type) >= 0 ? auth.type : 'bearer'
const setAuth = (patch) => setProv(pi, { auth: Object.assign({ type: t }, auth, patch) })
return el('div', { className: 'iwb-gset-row' },
el('div', { className: 'iwb-gset-row-label' }, '方式'),
el('div', { className: 'iwb-gset-row-ctl' },
el('select', { className: 'iwb-input iwb-grow', 'aria-label': '认证方式', value: t, onChange: (e) => setAuth({ type: e.target.value }) },
el('option', { value: 'bearer' }, 'Bearer(默认)'),
el('option', { value: 'header' }, '自定义 Header'),
el('option', { value: 'query' }, 'URL 参数'),
el('option', { value: 'none' }, '无鉴权'),
),
t === 'header' ? el('input', { className: 'iwb-input iwb-grow', value: auth.headerName || '', placeholder: 'Header 名,如 x-api-key(默认)', onChange: (e) => setAuth({ headerName: e.target.value }) }) : null,
t === 'query' ? el('input', { className: 'iwb-input iwb-grow', value: auth.queryName || '', placeholder: '参数名,如 key(默认)', onChange: (e) => setAuth({ queryName: e.target.value }) }) : null,
),
)
})()),
el(GSetGroup, { title: '请求分类', desc: '决定请求体怎么发尺寸' },
shapeBox,
),
@@ -1262,8 +1308,10 @@ function GSetGroup (props) {
models: wNormalizeImageModels(p.models),
layerModels: wNormalizeLayerModels(p.layerModels),
}, wShapeProviderFields(p)))
const DG = (typeof window !== 'undefined' && window.IWBDefaultGenModel) || null
const res = await api('config', {
providers,
defaultGen: DG ? DG.wNormalizeDefaultGen({ providers }, draft.defaultGen) : (draft.defaultGen || null),
imgbbKey: (draft.imgbbKey && draft.imgbbKey.trim()) || '__KEEP__',
imageTransfer: draft.it,
outputsRetention: draft.retention,
+8 -16
View File
@@ -10,13 +10,6 @@
* 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 || {}
@@ -40,13 +33,12 @@
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」' })
}
// 复制统一走 IWBClipboardCopy(2026-11-24):内含 navigator → textarea+execCommand 的降级链,
// 不再各处自己判断 clipboard 是否可用(那样每处都要复述一份兜底逻辑)。
const C = (typeof window !== 'undefined') ? window.IWBClipboardCopy : null
if (!C || typeof C.copyText !== 'function') { setMsg({ type: 'err', text: '当前环境不支持复制,请用「导出 JSON」' }); return }
const ok = await C.copyText(text)
setMsg(ok ? { type: 'ok', text: '诊断信息已复制到剪贴板' } : { type: 'err', text: '复制失败(权限被拒或非安全上下文);请改用「导出 JSON」' })
}
// ── 孤儿画板找回(v3.87.8)──
// 症状:崩溃/异常返回后某块画板"从列表里消失"(其它画板还在)。索引条目可能丢了,
@@ -68,7 +60,7 @@
} catch (e) { orphanRows = [] }
const restoreOrphan = async (row) => {
try {
if (!(await askConfirm('把「' + row.name + '」(' + row.nodes + ' 个节点)补回画布列表?恢复后会重新加载页面。', { title: '找回画布', okText: '补回' }))) return
if (!(await window.IWBUIConfirm.askOrNative('把「' + 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
@@ -90,7 +82,7 @@
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('button', { className: 'iwb-btn iwb-btn-sm iwb-btn-danger', title: '清空本机的崩溃记录、内存采样与操作面包屑', onClick: async () => { if (await window.IWBUIConfirm.askOrNative('清空本机诊断记录?', { title: '清空诊断记录', okText: '清空' })) { if (CrashLog && CrashLog.clear) CrashLog.clear(); reload() } } }, '清空记录'),
),
el('div', { className: 'iwb-row' },
el('span', { className: 'iwb-diag-kv' }, '版本 ' + APP_VERSION),
+38 -18
View File
@@ -778,7 +778,9 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
.iwb-ctxmask { position: fixed; inset: 0; background: transparent; z-index: var(--iwb-z-ctx); }
.iwb-ctxmenu { position: fixed; min-width: 196px; max-width: 240px; max-height: calc(100vh - 24px); overflow-y: auto; padding: 6px; background: var(--iwb-bg-menu); border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-panel); box-shadow: var(--iwb-elevation-2); z-index: var(--iwb-z-ctx-menu); display: flex; flex-direction: column; gap: 2px; }
/* 提示词/节点组的右键「移动到分组」菜单已 portal 到 body:需高于 .iwb-overlay(z-index:100),否则被应用层盖住 */
.iwb-ctxmenu.iwb-lib-group-menu { z-index: var(--iwb-z-sheet-menu); /* 面板内的 portal 菜单:> sheet、< modal,见 tokens 层级表 */ }
.iwb-ctxmenu.iwb-lib-group-menu,
/* 导航栏「更多」菜单同为挂 body 的 portal 菜单;不并入这条会落到 .iwb-ctxmenu 的 91,被 .iwb-overlay(100) 整页盖住(2026-11-25 实测) */
.iwb-ctxmenu.iwb-nav-more-menu { z-index: var(--iwb-z-sheet-menu); /* 面板内的 portal 菜单:> sheet、< modal,见 tokens 层级表 */ }
.iwb-ctx-title { font-size: var(--iwb-font-2xs); font-weight: 700; color: var(--iwb-text2); letter-spacing: 1px; padding: 6px 10px 2px; text-transform: uppercase; } /*iwb:raw-until=3.28.0*/
.iwb-ctx-item { display: flex; align-items: center; gap: 8px; width: 100%; padding: 7px 10px; border: none; border-radius: 8px; background: transparent; color: var(--iwb-text); font-size: var(--iwb-font-sm); cursor: pointer; text-align: left; }
.iwb-ctx-item .iwb-ic { width: var(--iwb-icon-sm); height: var(--iwb-icon-sm); flex: 0 0 auto; color: var(--iwb-text2); }
@@ -1171,7 +1173,6 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
.theme-dark .iwb-tab-active { background: color-mix(in srgb, var(--iwb-brand) 22%, transparent); }
.iwb-tab:focus-visible { outline: var(--iwb-focus-ring); outline-offset: 1px; }
/* 首页激活胶囊走灰阶(首页整体灰色系;画布标签仍用品牌色) */
.iwb-tab-home.iwb-tab-active { background: transparent; color: var(--iwb-text); }
/* 首页图标与画布标签之间的细分隔线 */
.iwb-tab-sep { flex: 0 0 auto; width: 1px; height: 16px; background: var(--iwb-border); }
.iwb-tab-label { overflow: hidden; text-overflow: ellipsis; }
@@ -1185,8 +1186,6 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
.iwb-tab:hover .iwb-tab-close { opacity: 1; }
.iwb-tab-close:hover { background: color-mix(in srgb, var(--iwb-text2) 16%, transparent); color: var(--iwb-text); }
.iwb-tab-close .iwb-ic { width: 12px; height: 12px; }
.iwb-tab-home { padding: 0 9px; }
.iwb-tab-home .iwb-ic { width: 16px; height: 16px; }
/* 标签条出现时顶栏下移(仅画布视图;覆盖共享 top:0 规则) */
/* 标签条始终顶左对齐(不随左侧栏展开缩进——标签条在最顶层、横跨全宽) */
@@ -1601,11 +1600,13 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
/* v3.87.31 模型清单:名称占位更宽 + 「质量」胶囊开关(与"启用"复选框区分) */
.iwb-modelrow { flex: 1 1 460px; }
.iwb-modelrow-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 120px; }
.iwb-quality-toggle { flex: 0 0 auto; display: inline-flex; align-items: center; gap: 4px; border: 1px solid var(--iwb-border); background: transparent; color: var(--iwb-text-dim); border-radius: 999px; padding: 1px 9px; font: inherit; font-size: 12px; line-height: 18px; cursor: pointer; }
.iwb-quality-toggle input { appearance: none; -webkit-appearance: none; width: 12px; height: 12px; border: 1px solid currentColor; border-radius: 3px; margin: 0; position: relative; }
.iwb-quality-toggle input:checked::after { content: ''; position: absolute; inset: 2px; background: currentColor; border-radius: 1px; }
.iwb-quality-toggle:hover { border-color: var(--iwb-brand); }
.iwb-quality-toggle.on { border-color: var(--iwb-brand); color: var(--iwb-brand-text, var(--iwb-brand)); font-weight: 600; background: color-mix(in srgb, var(--iwb-brand) 12%, transparent); }
/* 2026-11-25:质量去外框复选框,仅用胶囊底色 + 文字区分开关;input 透明覆盖整枚胶囊,
既去掉小方框又保留 DOM 可见尺寸(e2e 的 .check() 依赖元素可点击)。 */
.iwb-quality-toggle { position: relative; flex: 0 0 auto; display: inline-flex; align-items: center; border: 0; background: transparent; color: var(--iwb-text-dim); border-radius: var(--iwb-radius-full); padding: var(--iwb-space-4) var(--iwb-space-10); font: inherit; font-size: var(--iwb-font-sm); line-height: 18px; cursor: pointer; }
.iwb-quality-toggle input { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; margin: 0; cursor: pointer; }
.iwb-settings-modal .iwb-quality-toggle input { width: 100%; height: 100%; border-radius: var(--iwb-radius-full); }
.iwb-quality-toggle:hover { background: var(--iwb-hover); }
.iwb-quality-toggle.on { color: var(--iwb-brand-text, var(--iwb-brand)); font-weight: 600; background: color-mix(in srgb, var(--iwb-brand) 12%, transparent); }
.iwb-shape-hint { flex: 1 1 100%; margin-top: 2px; }
/* v3.87.39 顶部状态栏:加半透明白底 + 背景模糊,避免叠在图片/内容上时文字看不清 */
@@ -2162,6 +2163,11 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
旧暗色是 #e0e0e0 底 + var(--iwb-text) 字,实测 1.3:1(白底白字)。 */
.iwb-nav-item.on { background: var(--iwb-text); color: var(--iwb-bg); }
.iwb-nav-item.on:hover { background: color-mix(in srgb, var(--iwb-text) 88%, var(--iwb-bg)); }
/* 底部「更多」:有新版本时 ⋯ → 圆形上箭头,强调色提示可升级 */
.iwb-nav-more-btn.has-update { color: var(--iwb-brand-text); }
.iwb-nav-more-btn.has-update .iwb-ic { color: var(--iwb-brand-text); }
.iwb-nav-more-up { color: var(--iwb-brand-text); font-weight: 600; }
.iwb-nav-more-ver { padding: var(--iwb-space-6) var(--iwb-space-8); font-size: var(--iwb-font-xs); color: var(--iwb-text2); user-select: none; }
.ws-expanded .iwb-navrail { width: 52px; }
/* ── 插件整页(v3.25.59)──────────────────────────────────────────────── */
@@ -2379,15 +2385,21 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
.iwb-settings-modal .iwb-input,.iwb-settings-modal .iwb-textarea{border-color:var(--iwb-set-input-border)}
.iwb-settings-modal .iwb-input:focus,.iwb-settings-modal .iwb-textarea:focus{border-color:var(--iwb-brand)}
/* 模型行:删除收进「⋯」更多菜单,防误触 */
.iwb-model-more{position:relative;display:inline-flex;flex:0 0 auto}
.iwb-model-more>summary{list-style:none;cursor:pointer;width:24px;height:24px;display:inline-flex;align-items:center;justify-content:center;border-radius:var(--iwb-radius-control);color:var(--iwb-text2);font-size:var(--iwb-font-lg);line-height:1}
.iwb-model-more>summary::-webkit-details-marker{display:none}
.iwb-model-more>summary:hover{background:var(--iwb-hover)}
.iwb-model-more-menu{position:absolute!important;right:0;left:auto;top:calc(100% + var(--iwb-space-4));min-width:132px;max-width:none;max-height:none;overflow:visible;padding:var(--iwb-space-4);border-radius:var(--iwb-radius-control)}
.iwb-model-more-del{width:100%;text-align:left;border:0;background:transparent;color:var(--iwb-err);font-size:var(--iwb-font-sm);padding:var(--iwb-space-6) var(--iwb-space-8);border-radius:var(--iwb-radius-chip);cursor:pointer}
.iwb-model-more-del:hover{background:color-mix(in srgb,var(--iwb-err) 10%,transparent)}
.iwb-model-more-hint{padding:var(--iwb-space-6) var(--iwb-space-8);font-size:var(--iwb-font-xs);color:var(--iwb-text2)}
/* 模型行:启用=圆角开关(复用 .iwb-switch,26×15 小型;checkbox 仍在 DOM 内兼容选择器)。
删除=行内垃圾桶按钮(2026-11-25 用户裁定:取消 ⋯ 菜单,一步到位)。
沿用 iwb-btn-danger 的「悬停才显形」契约,避免误触;内置模型 disabled 常隐。 */
.iwb-modelrow .iwb-switch-track{width:26px;height:15px}
.iwb-modelrow .iwb-switch-dot{width:11px;height:11px;top:2px;left:2px}
.iwb-modelrow .iwb-switch input:checked + .iwb-switch-track .iwb-switch-dot{transform:translateX(11px)}
.iwb-modelrow .iwb-modelrow-main{min-width:0;flex:1 1 auto;gap:var(--iwb-space-8)}
.iwb-modelrow .iwb-modelrow-name{flex:1 1 auto;min-width:0}
.iwb-modelrow-defmark{flex:0 0 auto;font-size:var(--iwb-font-xs);color:var(--iwb-text-dim);border-radius:var(--iwb-radius-full);padding:var(--iwb-space-2) var(--iwb-space-8);background:var(--iwb-layer2)}
.iwb-settings-modal .iwb-modelrow-default{border-color:var(--iwb-brand);background:color-mix(in srgb,var(--iwb-brand) 8%,transparent)}
.iwb-model-del{flex:0 0 auto;width:26px;height:26px;display:inline-flex;align-items:center;justify-content:center;border:0;background:transparent;border-radius:var(--iwb-radius-control);color:var(--iwb-err);cursor:pointer;opacity:0;visibility:hidden;pointer-events:none;transition:opacity .15s ease}
.iwb-modelrow:hover .iwb-model-del,.iwb-modelrow:focus-within .iwb-model-del{opacity:1;visibility:visible;pointer-events:auto}
.iwb-model-del:hover:not(:disabled){background:var(--iwb-err-bg)}
.iwb-model-del .iwb-ic{width:var(--iwb-icon-sm);height:var(--iwb-icon-sm)}
.iwb-model-del:disabled{cursor:default;opacity:0!important;pointer-events:none}
/* 设置页统一:所有分组块间距只允许用 --iwb-set-group-gap */
.iwb-settings-modal .iwb-provider-card{gap:var(--iwb-set-group-gap)}
@@ -2423,3 +2435,11 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
/* 备份页嵌在设置里:去掉内层弹窗的滚动/最大高度,统一由设置 body 滚动 */
.iwb-settings-modal .iwb-backup-embedded .iwb-modal-body{max-height:none;overflow:visible}
/* 底栏「插件节点」下拉(2026-11-26):与相邻 .iwb-btn 同高,只做尺寸/光标微调;颜色沿用工具栏 token */
.iwb-plugin-add-wrap { position: relative; display: inline-flex; }
.iwb-plugin-add { position: relative; }
/* 插件节点列表:与工具栏同色系,向上弹出(底栏贴底,向上才有空间) */
.iwb-plugin-add-menu { position: absolute; left: 50%; bottom: calc(100% + 8px); transform: translateX(-50%); min-width: 168px;
background: var(--iwb-panel); border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-control); box-shadow: var(--iwb-elevation-2);
padding: var(--iwb-space-4); display: flex; flex-direction: column; gap: var(--iwb-space-2); }
+13 -1
View File
@@ -5,6 +5,18 @@ const { expect } = require('@playwright/test')
// 通用轮询:fn 返回布尔/数值/字符串,直到满足期望
const poll = (page, fn, opts) => expect.poll(fn, Object.assign({ timeout: 8000, intervals: [50, 100, 200, 400] }, opts || {}))
// 回画布库(2026-11-24):标签条的房子按钮在 v3.25.62 已删除,入口只剩一级导航的「首页」。
// 4 个 spec 此前还在点旧的 `.iwb-tab-home`(元素根本不存在)⇒ 长期全红。收口到这里,不要再各写选择器。
const HOME_NAV = '.iwb-navrail .iwb-nav-item[aria-label="首页(画布库)"]'
async function goHome (page) {
await page.locator(HOME_NAV).click()
await waitHomeReady(page)
}
// 当前是否停在画布库(一级导航「首页」处于 active;等价于旧断言「首页标签带 iwb-tab-active」)
async function expectHomeActive (page) {
await expect(page.locator(HOME_NAV)).toHaveClass(/\bon\b/)
}
// 首页卡片渲染完成(含"我的画布"卡片)
async function waitHomeReady(page) {
await expect(page.locator('.iwb-home-card:not(.iwb-home-new)').first()).toBeVisible({ timeout: 15000 })
@@ -47,4 +59,4 @@ async function waitForSavedText(page, text, opts) {
return false
}, text), Object.assign({ timeout: 10000 }, opts || {})).toBe(true)
}
module.exports = { waitForSavedText, waitForSaved, poll, waitHomeReady, waitCanvasOpen, waitNodeCount, waitSelectedCount, waitInternalClipboard }
module.exports = { waitForSavedText, waitForSaved, poll, waitHomeReady, waitCanvasOpen, waitNodeCount, waitSelectedCount, waitInternalClipboard, goHome, expectHomeActive, HOME_NAV }
+1 -1
View File
@@ -437,7 +437,7 @@ test('P1 基线:pan / zoom / tab-switch / edges', async ({ page }) => {
// 切 5 标签 ×3 轮
const switchTimes = []
const tabsEls = page.locator('.iwb-tab:not(.iwb-tab-home)')
const tabsEls = page.locator('.iwb-tab')
const tabCount = await tabsEls.count()
if (!LIGHT) {
for (let r = 0; r < 3; r++) {
+2 -2
View File
@@ -76,7 +76,7 @@ test('探针:切标签 × 缩放档位 × 节点数量', async ({ page }) => {
await page.waitForSelector('.iwb-canvas:not(.iwb-canvas-hidden)', { timeout: 30000 })
await page.waitForTimeout(2500)
const tabInfo = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-tab:not(.iwb-tab-home)'))
const tabInfo = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-tab'))
.map((el, idx) => ({ idx, text: (el.textContent || '').trim().slice(0, 20) }))
.filter((t) => t.text !== '+'))
const big = tabInfo.find((t) => t.text === 'MAIN').idx
@@ -101,7 +101,7 @@ test('探针:切标签 × 缩放档位 × 节点数量', async ({ page }) => {
})
const clickTab = (idx) => page.evaluate(async (i) => {
const list = Array.from(document.querySelectorAll('.iwb-tab:not(.iwb-tab-home)')).filter((e) => (e.textContent || '').trim() !== '+')
const list = Array.from(document.querySelectorAll('.iwb-tab')).filter((e) => (e.textContent || '').trim() !== '+')
const el = list[i]
if (!el) return null
const t0 = performance.now()
+2
View File
@@ -450,6 +450,8 @@ async function bootSettings (page, theme) {
}, { cfg: SETTINGS_CFG, theme })
await page.goto('/', { waitUntil: 'domcontentloaded' })
await page.evaluate(() => { const el = document.querySelector('.iwb-nav-item[title="设置"]'); if (el) el.click() })
// 2026-11-25:设置默认落「通用」标签,本基线要的是生图服务页 → 显式切过去
await page.locator('.iwb-settings-modal .iwb-set-nav-item', { hasText: '生图服务' }).first().click()
await expect(page.locator('.iwb-prov-chip').first()).toBeVisible({ timeout: 15000 })
await expect(page.locator('.iwb-provider-card')).toHaveCount(1)
await settle(page)
+113
View File
@@ -0,0 +1,113 @@
'use strict'
/* 相册(outKind:'images')任务图行为(2026-11-26)
*
* 守的是什么:
* · 一图一任务:相册 N 张 → N 个任务,每个只带自己那张图
* · 批量模式:按 ALBUM_BATCH_MAX(12) 分批 → ⌈N/12⌉ 个任务,每批多张参考图
* · 组合扇出:相册接在组合前面时必须变成 N 个任务(否则会被压成 1 个任务 + N 张图)
* · 零回归:没有相册时,ref/组合/中继的任务数逐字不变
*
* 用真实模块 + 最小注入实现(不切片 app.js):依赖全是纯函数,本文件里各写一份等价实现。
*/
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const src = fs.readFileSync(path.join(__dirname, '..', 'src', 'generation-task-graph.js'), 'utf8')
const box = { console }
vm.runInNewContext(src, box)
const TG = box.IWBWTaskGraph
assert.ok(TG && typeof TG.create === 'function', '模块应导出 IWBWTaskGraph.create')
// ── 最小注入依赖(语义与 app.js 一致,但实现从简)──
const byPos = (a, b) => (Number(a.x) - Number(b.x)) || (Number(a.y) - Number(b.y)) || String(a.id).localeCompare(String(b.id))
const dedupeTaskRefs = (list) => { const seen = new Set(), out = []; for (const r of (list || [])) { if (!r || seen.has(r.id)) continue; seen.add(r.id); out.push(r) } return out }
const refArgsOf = (rn) => { const d = (rn && rn.data) || {}; if (d.localName) return [{ type: 'local', name: d.localName }]; if (d.data) return [{ type: 'data', value: d.data, name: d.name || 'ref.png' }]; if (typeof d.url === 'string') return d.url.trim() ? [{ type: 'url', value: d.url.trim() }] : []; if (d.url) return [{ type: 'data', value: d.url, name: d.name || 'ref.png' }]; return [] }
const isBatchSrc = (n) => !!n && (n.type === 'prompt' || n.type === 'textout' || n.type === 'combine' || n.type === 'batch' || (n.data && n.data.outKind === 'prompt'))
const batchJoinedText = (data, base) => String((data && data.combined) || base || '')
const batchSrcText = (n) => String((n && n.data && (n.data.combined || n.data.text)) || '')
const wDedupeTaskIds = (list) => { const seen = new Set(), out = []; for (const t of (list || [])) { if (!t || seen.has(t.id)) continue; seen.add(t.id); out.push(t) } return out }
const tg = TG.create({
sortByPosition: (arr) => arr.slice().sort(byPos),
compareCanvasImageOrder: byPos,
compareCanvasTextOrder: byPos,
dedupeTaskRefs,
isBatchSrc,
batchJoinedText,
wDedupeTaskIds,
refArgsOf,
batchSrcText,
standardSizeOf: () => '1024x1024',
})
const n = (id, type, data, extra) => Object.assign({ id, type, x: Number(id.replace(/\D/g, '')) || 0, y: 0, data: data || {} }, extra || {})
const e = (from, to) => ({ id: from + '>' + to, from, to })
const img = (i) => ({ name: 'img' + i + '.png', src: 'data:image/png;base64,AAA' + i })
const album = (id, count, extra) => n(id, 'plugin:album:album', Object.assign({ outKind: 'images', items: Array.from({ length: count }, (_, i) => img(i + 1)) }, extra || {}))
const gen = n('g9', 'gen', {})
const tasks = (nodes, edges) => tg.buildGenerationTasksV2(gen, nodes.concat([gen]), edges)
let pass = 0, fail = 0
const ok = (name, cond, extra) => { if (cond) { pass++; console.log(' PASS ' + name) } else { fail++; console.log(' FAIL ' + name + (extra ? ' → ' + extra : '')) } }
// ① 一图一任务:相册(3) → 组合 ← 提示词 → 生图 = 3 个任务,各 1 张图 + 同一段文本
{
const nodes = [album('a1', 3), n('p2', 'prompt', { text: '一段提示词' }), n('c3', 'combine', {}), gen]
const out = tasks(nodes, [e('a1', 'c3'), e('p2', 'c3'), e('c3', 'g9')])
ok('一图一任务 = 3 个任务', out.length === 3, '实际 ' + out.length)
ok('每个任务只带 1 张图', out.every((t) => t.refs.length === 1), JSON.stringify(out.map((t) => t.refs.length)))
ok('每个任务都带同一段提示词', out.every((t) => t.text === '一段提示词'), JSON.stringify(out.map((t) => t.text)))
ok('任务 id 互不相同', new Set(out.map((t) => t.id)).size === 3, JSON.stringify(out.map((t) => t.id)))
}
// ② 批量模式:22 张 → 2 个任务(12 + 10)
{
const nodes = [album('a1', 22, { albumMode: 'batch' }), n('c3', 'combine', {}), gen]
const out = tasks(nodes, [e('a1', 'c3'), e('c3', 'g9')])
ok('批量 = 2 个任务', out.length === 2, '实际 ' + out.length)
ok('按 12 张分批:12 + 10', JSON.stringify(out.map((t) => t.refs.length)) === '[12,10]', JSON.stringify(out.map((t) => t.refs.length)))
}
// ③ 组合前面再拼「其他参考图」:每个任务 = 该相册图 + 额外参考图
{
const nodes = [album('a1', 3), n('r4', 'ref', { url: 'https://example.test/extra.png' }), n('c3', 'combine', {}), gen]
const out = tasks(nodes, [e('a1', 'c3'), e('r4', 'c3'), e('c3', 'g9')])
ok('组合扇出后仍是 3 个任务', out.length === 3, '实际 ' + out.length)
ok('每个任务 = 相册图 + 额外参考图(2 张)', out.every((t) => t.refs.length === 2), JSON.stringify(out.map((t) => t.refs.length)))
}
// ④ 相册直连生图(不接组合):一图一任务
{
const nodes = [album('a1', 4), gen]
const out = tasks(nodes, [e('a1', 'g9')])
ok('直连仍是 4 个任务', out.length === 4, '实际 ' + out.length)
}
// ⑤ 零回归:普通 ref + 提示词 → 生图(1 个任务、1 张图)
{
const nodes = [n('p2', 'prompt', { text: 'hello' }), n('r4', 'ref', { url: 'https://example.test/x.png' }), gen]
const out = tasks(nodes, [e('p2', 'g9'), e('r4', 'g9')])
ok('普通画布仍是 1 个任务', out.length === 1, '实际 ' + out.length)
ok('普通画布 refs = 1', out[0].refs.length === 1, JSON.stringify(out[0].refs.length))
}
// ⑥ 零回归:组合(无多值来源)仍是 1 个任务、合并文本与图
{
const nodes = [n('p2', 'prompt', { text: 'a' }), n('t5', 'textout', { text: 'b' }), n('r4', 'ref', { url: 'https://example.test/x.png' }), n('c3', 'combine', {}), gen]
const out = tasks(nodes, [e('p2', 'c3'), e('t5', 'c3'), e('r4', 'c3'), e('c3', 'g9')])
ok('普通组合仍是 1 个任务', out.length === 1, '实际 ' + out.length)
ok('普通组合文本已合并', /a/.test(out[0].text) && /b/.test(out[0].text), out[0].text)
}
// ⑦ 停用(on:false)的相册项不参与
{
const items = [img(1), Object.assign(img(2), { on: false }), img(3)]
const nodes = [n('a1', 'plugin:album:album', { outKind: 'images', items }), gen]
const out = tasks(nodes, [e('a1', 'g9')])
ok('停用的相册项被跳过', out.length === 2, '实际 ' + out.length)
}
console.log('\n===== album 任务图:' + pass + ' 通过 / ' + fail + ' 失败 =====')
process.exit(fail ? 1 : 0)
+1 -1
View File
@@ -236,7 +236,7 @@ console.log('8) 加载期跨模块依赖顺序')
// 判据用**行首缩进**,不用括号深度:本仓 src 模块格式高度统一
// (`;(function (global) {` 开头、顶层语句恰好 2 空格、函数体与对象字面量内部 ≥ 4 空格),
// 缩进判据不需要解析字符串 / 正则 / 模板串。
// 曾用「括号深度 ≤ 1」实现,结果被 src/image-preview-derive.js:306 的
// 曾用「括号深度 ≤ 1」实现,结果被模板字符串里的花括号干扰(历史案例)
// `/^(blob:|\/|\.\.\/)/i` 正则字面量算错平衡(depth = −1)—— 说明按字符扫括号在这类文件上不可靠。
// 已知代价:顶层对象字面量**内部**的加载期读取(缩进 4)不计入;实测当前 0 处,
// 且漏判只会少守一条,不会误红。
+14
View File
@@ -122,6 +122,20 @@ assert('文档 sourceModules 项数 == 快照长度 ' + orderSnapshot.length, fa
assert('文档门禁 spec 数 == 实际 ' + gateSpecCount, factsDoc.includes('**' + gateSpecCount + '** 个进门禁'))
assert('文档门禁链含 test:facts', factsDoc.includes('test:facts'))
// ── 6b. 行数棘轮硬数字(2026-11-24,P0-②)────────────────────────────────────
// 动机:MAX_APP_JS_LINES 等上限被抄进 CONTRIBUTING 与本文档,此前**无人校验**,
// 实测已漂 415 行(文档 8,700 vs 真实 9,115)。规则与测量都在 scripts/ratchet-metrics.js,
// 与 sync-facts 共用一份 —— 避免「同步器说改了、守卫说没改」。
console.log('6b) 棘轮硬数字(文档 == 代码)')
const ratchetMetrics = require(path.join(root, 'scripts', 'ratchet-metrics'))
const measured = ratchetMetrics.measure()
for (const [kind, file] of [['contributing', 'CONTRIBUTING.md'], ['arch', 'docs/standards/architecture-current-state.md']]) {
const text = fs.readFileSync(path.join(root, file), 'utf8')
const res = ratchetMetrics.rewriteDoc(kind, text, measured)
assert(file + ' 的棘轮数字与代码一致', res.changed.length === 0,
'以下数字过时:' + res.changed.join(', ') + ' —— 跑 `node scripts/sync-facts.js --write` 自动修')
}
// ── 7. 基线锚点:文档记录的「基线 SHA + 线上版本」必须与实际一致 ──────────────
// 动机:本文档第 4 行的锚点写着「每次 main 有新提交或线上发版后必须同步」,但此前
// **没有任何机制强制它** —— 事实上它长期停在 `e40d8b4`/v3.20.0(而实际已是 v3.21.0),
+2 -3
View File
@@ -148,15 +148,14 @@ test('1. 画布A 复制 → 切画布B → Ctrl+Shift+V 粘到视口中心且可
const raw = await page.evaluate(() => localStorage.getItem('iwb_clipboard'))
const parsed = JSON.parse(raw)
// 回画布库 → 打开第二张画布(跨画布粘贴)
await page.locator('.iwb-tab-home').click()
await W.waitHomeReady(page)
await W.goHome(page)
console.log('[check1] home cards = ' + (await page.locator('.iwb-home-card:not(.iwb-home-new)').count()))
await page.locator('.iwb-home-card:not(.iwb-home-new)').nth(1).dblclick()
await W.waitCanvasOpen(page)
const nodeB0 = await page.locator('.iwb-node').count()
// v3.24.69 起落点跟指针(见 test 17)。把指针停在画布外的导航按钮上 ⇒ 走 fallback:
// 仍按视口中心贴,这条守的就是「指针不可用时不会贴到看不见的地方」。
const nav = await page.locator('.iwb-tab-home').first().boundingBox()
const nav = await page.locator(W.HOME_NAV).first().boundingBox()
await page.mouse.move(Math.round(nav.x + nav.width / 2), Math.round(nav.y + nav.height / 2))
// v3.24.67:节点/节点组只走 Ctrl+Shift+V(Ctrl+V 不再回退贴节点组 —— 见 test 8)
await realPasteGroup(page)
+32
View File
@@ -0,0 +1,32 @@
{
"$comment": "e2e 已知失败清单(2026-11-24 立)。用途:把「长期红」与「新红」分开,避免门禁信号被噪声淹没。维护:修好一条就删一条;新红由 scripts/e2e-known-red-report.js 报出来。",
"measuredAt": "2026-11-24",
"measuredVersion": "3.26.64",
"baseUrl": {
"clipboard-audit": "http://127.0.0.1:8799",
"default": "http://127.0.0.1:8787"
},
"entries": [
{
"spec": "tests/clipboard-audit.spec.js",
"knownFailures": 8,
"reason": "无头浏览器剪贴板权限受限(navigator.clipboard 读图像需真实前台窗口);用例本身在人工环境可通过",
"kind": "environment",
"since": "2026-11-24 实测"
},
{
"spec": "tests/iwb-close-flush.spec.js",
"knownFailures": 3,
"reason": "flush 语义用例超时;已用 git stash 在改动前复跑,失败数相同 ⇒ 与本轮修复无关,待单独排查",
"kind": "defect",
"since": "2026-11-24 实测"
},
{
"spec": "tests/iwb-stability.spec.js",
"knownFailures": 5,
"reason": "资源中心入口 / 拖拽 / Prompt 刷新等用例选择器或时序失效;与本地图片链路无关",
"kind": "defect",
"since": "2026-11-24 实测"
}
]
}
+4
View File
@@ -9,11 +9,13 @@
"IWBCanvasStore",
"IWBCanvasText",
"IWBCrashLog",
"IWBDefaultGenModel",
"IWBDesktop",
"IWBDesktopHelpers",
"IWBDockArea",
"IWBGalleryHydration",
"IWBGallerySync",
"IWBGenerationEndpoint",
"IWBGenerationRequestShape",
"IWBGenerationResults",
"IWBGenerationScheduler",
@@ -22,12 +24,14 @@
"IWBImageBlobStore",
"IWBImageCompress",
"IWBImageDisplayThumb",
"IWBImageFileRef",
"IWBImageRemoteCache",
"IWBImageThumbPick",
"IWBMetricsSwallow",
"IWBMiniMapFit",
"IWBNativeClipboard",
"IWBNodeBodies",
"IWBPluginApiImages",
"IWBPluginData",
"IWBPluginGallery",
"IWBPluginGroupLib",
+4 -2
View File
@@ -11,7 +11,7 @@
"clipboard-native.js",
"generation-size-policy.js",
"generation-request-shape.js",
"image-preview-derive.js",
"generation-endpoint.js",
"canvas-actions.js",
"canvas-node-factory.js",
"storage-contract.js",
@@ -31,17 +31,18 @@
"runtime-execution-context.js",
"runtime-diagnostic-record.js",
"runtime-metrics.js",
"image-file-ref.js",
"image-blob-store.js",
"runtime-crash-log.js",
"storage-health.js",
"storage-config-shape.js",
"generation-default-model.js",
"storage-indexeddb.js",
"storage-workspace.js",
"storage-groups.js",
"storage-outputs.js",
"storage-backup.js",
"storage-zip.js",
"plugin-archive.js",
"plugin-promptlib-backup.js",
"runtime-constants.js",
"canvas-store.js",
@@ -106,6 +107,7 @@
"ui-connect-menu.js",
"ui-gen-config-panel.js",
"canvas-webview.js",
"plugin-api-images.js",
"plugin-files-policy.js",
"image-prompt-cover.js"
]
+7 -1
View File
@@ -1,3 +1,9 @@
{
"files": {}
"files": {
"plugins/album/styles.css": {
"font": 1,
"radius": 0,
"space": 2
}
}
}
+43
View File
@@ -0,0 +1,43 @@
'use strict'
// src/generation-default-model.js 行为契约(2026-11-25)
// 守的是「新建配置节点默认模型」的三条铁律:有效配置照用 / 未配置与失效都回退主服务首个 / 无模型才 null。
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const root = path.resolve(__dirname, '..')
const box = { console: { log() {}, warn() {}, error() {} } }
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'generation-default-model.js'), 'utf8'), box)
const M = box.IWBDefaultGenModel
assert.ok(M && typeof M.wResolveDefaultGen === 'function', '应导出 IWBDefaultGenModel.wResolveDefaultGen')
const eq = (a, b, msg) => assert.strictEqual(JSON.stringify(a), JSON.stringify(b), msg)
const cfg = {
providers: [
{ id: 'p1', name: '主服务', keys: [{ id: 'k1' }, { id: 'k1b' }], models: [{ name: 'm1', visible: true }, { name: 'm2', visible: false }, { name: 'm1', visible: true }] },
{ id: 'p2', name: '备用', keys: [{ id: 'k2' }], models: [{ name: 'm3', visible: true }] },
],
}
eq(M.wDefaultGenOptions(cfg).map((o) => o.label), ['主服务 · m1', '备用 · m3'], '选项只含可见模型、去重保序,标签=服务名 · 模型名')
eq(M.wResolveDefaultGen(cfg), { providerId: 'p1', model: 'm1', keyGroup: 'k1' }, '未配置 ⇒ 回退主服务首个可见模型(保证「默认」标识始终有指向)')
eq(M.wResolveDefaultGen({ ...cfg, defaultGen: { providerId: 'p2', model: 'm3' } }),
{ providerId: 'p2', model: 'm3', keyGroup: 'k2' }, '有效配置照用,keyGroup 取该服务首个 Key')
eq(M.wResolveDefaultGen({ ...cfg, defaultGen: { providerId: 'p1', model: 'm1', keyGroup: '自定义组' } }),
{ providerId: 'p1', model: 'm1', keyGroup: '自定义组' }, '有效配置保留用户显式 keyGroup')
eq(M.wResolveDefaultGen({ ...cfg, defaultGen: { providerId: 'p1', model: 'm2' } }),
{ providerId: 'p1', model: 'm1', keyGroup: 'k1' }, '配置的模型被关闭 ⇒ 回退主服务首个可见模型')
eq(M.wResolveDefaultGen({ ...cfg, defaultGen: { providerId: 'pX', model: 'gone' } }),
{ providerId: 'p1', model: 'm1', keyGroup: 'k1' }, '服务被删 ⇒ 同样回退主服务首个')
eq(M.wResolveDefaultGen({ providers: [], defaultGen: { providerId: 'p1', model: 'm1' } }), null, '无可用模型 ⇒ null')
eq(M.wNormalizeDefaultGen(cfg, { providerId: 'p2', model: 'm3' }),
{ providerId: 'p2', model: 'm3', keyGroup: 'k2' }, '归一化接受有效项')
eq(M.wNormalizeDefaultGen(cfg, { providerId: 'p1', model: 'm2' }), null, '归一化拒绝不可见模型(让读取侧走回退)')
eq(M.wNormalizeDefaultGen(cfg, null), null, '空值归一化为 null')
console.log('generation-default-model checks passed(有效照用 / 未配置与失效回退 / 无模型为 null / 保存校验)')
+81
View File
@@ -0,0 +1,81 @@
'use strict'
// src/generation-endpoint.js 的行为契约(2026-11-24)
//
// 守的是什么:
// · joinEndpoint —— genPath 必须真正生效(配置项此前是死的),且尾斜杠/绝对地址/空路径都要对
// · buildAuthHeaders —— 缺省必须是 Bearer(老配置不能挂),header/query/none 各走各的
// · applyAuthQuery —— 同名参数覆盖,不能出现两个 key
// · shouldRetryNextAddress —— **结果未知不重试**(超时/hard-timeout),只换 5xx/429/连接失败
const assert = require('assert')
const fs = require('fs')
const path = require('path')
// 仓库风格:src/*.js 是 UMD 全局脚本(不认 CommonJS),测试用沙箱加载
const box = {}
new Function('window', 'globalThis', fs.readFileSync(path.join(__dirname, '..', 'src', 'generation-endpoint.js'), 'utf8'))(box, box)
const E = box.IWBGenerationEndpoint
assert.ok(E && typeof E.joinEndpoint === 'function', 'src/generation-endpoint.js 应导出 IWBGenerationEndpoint')
const eq = (a, b, msg) => assert.strictEqual(JSON.stringify(a), JSON.stringify(b), msg)
// ── joinEndpoint ──
assert.strictEqual(E.joinEndpoint('https://a.test/v1', '/custom/gen'), 'https://a.test/v1/custom/gen', '常规拼接')
assert.strictEqual(E.joinEndpoint('https://a.test/v1/', 'custom/gen'), 'https://a.test/v1/custom/gen', 'base 尾斜杠 + 无首斜杠')
assert.strictEqual(E.joinEndpoint('https://a.test/v1', ''), 'https://a.test/v1/images/generations', '空路径回落默认')
assert.strictEqual(E.joinEndpoint('https://a.test/v1', 'https://b.test/api'), 'https://b.test/api', 'path 是绝对 URL 时原样返回')
assert.strictEqual(E.joinEndpoint('', '/x'), '/x', 'base 为空时至少产出路径')
// ── normalizeAuth ──
eq(E.normalizeAuth(null), { type: 'bearer' }, '缺省=Bearer(老配置行为不变)')
eq(E.normalizeAuth({ type: 'bogus' }), { type: 'bearer' }, '未知类型回落 Bearer')
eq(E.normalizeAuth({ type: 'HEADER', headerName: 'x-api-key' }), { type: 'header', headerName: 'x-api-key' }, 'type 大小写归一')
eq(E.normalizeAuth({ type: 'header' }), { type: 'header', headerName: 'x-api-key' }, 'header 名缺省')
eq(E.normalizeAuth({ type: 'query' }), { type: 'query', queryName: 'key' }, 'query 名缺省')
// ── buildAuthHeaders ──
eq(E.buildAuthHeaders(null, 'sk-1', { 'Content-Type': 'application/json' }), { 'Content-Type': 'application/json', Authorization: 'Bearer sk-1' }, 'Bearer 是缺省')
eq(E.buildAuthHeaders({ type: 'header', headerName: 'x-api-key' }, 'sk-2'), { 'x-api-key': 'sk-2' }, '自定义 header')
eq(E.buildAuthHeaders({ type: 'none' }, 'sk-3'), {}, '无鉴权 不写头')
eq(E.buildAuthHeaders({ type: 'bearer' }, ''), {}, '空 key 不写头(让服务端报 401,而不是发空 Bearer)')
// ── applyAuthQuery ──
assert.strictEqual(E.applyAuthQuery('https://a.test/x', { type: 'query', queryName: 'key' }, 'k 1'), 'https://a.test/x?key=k%201', '新增参数并编码')
assert.strictEqual(E.applyAuthQuery('https://a.test/x?key=old', { type: 'query', queryName: 'key' }, 'new'), 'https://a.test/x?key=new', '同名参数覆盖')
assert.strictEqual(E.applyAuthQuery('https://a.test/x?a=1', { type: 'query', queryName: 'key' }, 'k'), 'https://a.test/x?a=1&key=k', '已有其他参数时用 &')
assert.strictEqual(E.applyAuthQuery('https://a.test/x', { type: 'bearer' }, 'k'), 'https://a.test/x', '非 query 鉴权不改 URL')
// ── shouldRetryNextAddress:结果未知绝不重试 ──
for (const t of ['server', 'limit', 'network']) assert.strictEqual(E.shouldRetryNextAddress({ iwbType: t }), true, t + ' 应换地址')
for (const t of ['param', 'auth', 'permission', 'timeout', 'hard-timeout', 'cancel', 'unknown', undefined]) assert.strictEqual(E.shouldRetryNextAddress({ iwbType: t }), false, String(t) + ' 不应换地址(结果未知/换也没用)')
// ── 接线契约(负数断言):防止有人把端点/鉴权又写死回 app.js ──
// 背景:genPath/auth 曾经「配置里有、代码里没用」,只靠模块单测发现不了这种回归。
const appSrc = fs.readFileSync(path.join(__dirname, '..', 'app.js'), 'utf8')
assert.ok(appSrc.indexOf("baseUrl + '/images/generations'") < 0, 'app.js 不得再硬编码 /images/generations(应用 genPath)')
// 生图/分层两条路径此前是 `const headers = { Authorization: 'Bearer ' + key.value }`;
// LLM 与 /models 探测仍是 Bearer(本次不改),所以只钉「生图那行的旧形状」
assert.ok(!/const headers = \{ Authorization: 'Bearer ' \+ key\.value \}/.test(appSrc), '生图不得再硬编码 Bearer 鉴权(应用 headersOf)')
assert.ok(appSrc.indexOf('urlOf(curBase)') >= 0, '生图请求应经 urlOf() 拼地址')
assert.ok(appSrc.indexOf('headersOf(') >= 0, '生图请求头应经 headersOf() 生成')
assert.ok(appSrc.indexOf('addrs') >= 0, '应使用候补地址列表(fallbacks 生效)')
// ── runWithAddresses:换地址策略的端到端行为 ──
;(async () => {
const seen = []
const addrs = ['https://a.test/v1', 'https://b.test/v1']
let n = 0
const ok = await E.runWithAddresses(addrs, async () => { n++; if (n === 1) { const e = new Error('503'); e.iwbType = 'server'; throw e } return 'done' }, (b) => seen.push(b))
assert.strictEqual(ok, 'done', '第一次失败(5xx)后应换地址并成功')
assert.strictEqual(n, 2, '应尝试两次')
eq(seen, addrs, 'onBase 应按顺序告知当前地址')
let m = 0
await assert.rejects(async () => E.runWithAddresses(addrs, async () => { m++; const e = new Error('timeout'); e.iwbType = 'timeout'; throw e }), /timeout/)
assert.strictEqual(m, 1, '超时属结果未知 ⇒ 只试一次(防重复计费)')
let k = 0
const one = await E.runWithAddresses([], async () => { k++; return 'x' })
assert.strictEqual(one, 'x', '无候选地址时也执行一次(用空 base)')
assert.strictEqual(k, 1, '空列表不循环')
console.log('generation endpoint checks passed(端点拼接 / 鉴权四态 / 地址回退判据 / 地址循环)')
})().catch((e) => { console.error(e); process.exit(1) })
+65
View File
@@ -0,0 +1,65 @@
/* 图片引用 → 预览 URL 的解析链(2026-11-25)
*
* 为什么单独成测试:相册只存 { __file: '/abs/a.png' }(只引用不复制字节),
* 而 wResolveImg 是**所有节点预览**的唯一入口(图片节点、参考图 mini、组合节点预览、插件节点)。
* 它原先只判 __blob / __cache,遇到 __file 就把引用对象原样返回 ⇒ 上层 String(obj) = "[object Object]"
* ⇒ <img src="[object Object]"> 破图:组合节点里相册的图全空,而生成却完全正常
* (生成走 wImgRefDataUrl,那条路早就支持 __file)。这类「入口少一个分支」的漏很难在手工测试里发现,
* 所以把「三种引用都必须被 wResolveImg 认出来」钉成断言。
*/
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const ROOT = path.resolve(__dirname, '..')
const src = fs.readFileSync(path.join(ROOT, 'app.js'), 'utf8')
let n = 0
const ok = (name, cond) => { n++; assert.ok(cond, name); console.log(' PASS ' + name) }
// ── 1) 行为:引用键必须把三种引用区分开 ──────────────────────
const from = src.indexOf(' function wIsBlobRef(v)')
const to = src.indexOf(' // 一张画布上几十张图会在同一帧内陆续解析完成')
assert.ok(from > 0 && to > from, '能定位到引用判定片段')
// wIsFileRef 依赖 wFileRefMod()(模块注入),这里给一个最小实现
const slice = src.slice(from, to)
const sandbox = {
wFileRefMod: () => ({ is: (v) => !!(v && typeof v === 'object' && typeof v.__file === 'string' && v.__file) }),
String, Object, Array,
}
vm.createContext(sandbox)
vm.runInContext(slice + '\n;globalThis.__k = { wIsBlobRef: wIsBlobRef, wIsCacheRef: wIsCacheRef, wIsFileRef: wIsFileRef, wImgRefKey: wImgRefKey }\n', sandbox)
const K = sandbox.__k
ok('__blob 被认成 blob 引用', K.wIsBlobRef({ __blob: 'abc' }) === true)
ok('__cache 被认成 cache 引用', K.wIsCacheRef({ __cache: 'k1' }) === true)
ok('__file 被认成 file 引用(相册的形态)', K.wIsFileRef({ __file: '/a/b.png' }) === true)
ok('三种引用的键前缀互不冲突',
K.wImgRefKey({ __blob: 'x' }) === 'b:x' &&
K.wImgRefKey({ __cache: 'y' }) === 'c:y' &&
K.wImgRefKey({ __file: '/z.png' }) === 'f:/z.png')
// ── 2) 源断言:wResolveImg 的入口必须包含 __file ──────────────
const resolveStart = src.indexOf(' function wResolveImg(v) {')
assert.ok(resolveStart > 0, '能找到 wResolveImg')
// 取函数体前 1200 字符足够覆盖入口判定
const resolveBody = src.slice(resolveStart, resolveStart + 1400)
ok('wResolveImg 入口判定包含 wIsFileRef(漏了就 String 成 "[object Object]")',
/if \(wIsBlobRef\(v\) \|\| wIsCacheRef\(v\) \|\| wIsFileRef\(v\)\)/.test(resolveBody))
ok('wResolveImg 对引用先给 objectURL、未解析时返回空串(绝不返回引用对象本身)',
/const hit = wImgUrlByRef\.get\(wImgRefKey\(v\)\)[\s\S]{0,600}return ''/.test(resolveBody))
ok('wEnsureImgUrl 对 __file 走 readBlob(真正读盘的入口)',
/wIsFileRef\(v\) \? \(wFileRefMod\(\) \|\| \{\}\)\.readBlob\(v\.__file\)/.test(src))
ok('wResolveImgAsync 用 wImgRefKey(双击放大 / 复制图时同样支持 __file)',
/async function wResolveImgAsync\(v\) \{[\s\S]{0,400}const key = wImgRefKey\(v\)/.test(src))
ok('wImgRefDataUrl 支持 __file(生成 / 导出走这条路)',
/if \(wIsFileRef\(v\)\) \{ const M = wFileRefMod\(\); try \{ return \(M && await M\.readDataUrl\(v\.__file\)\)/.test(src))
// ── 3) 所有预览调用点都先经过 wResolveImg(不是裸 String)────
ok('wThumbSrc 对对象先 wResolveImg 再 String',
/function wThumbSrc\(v\) \{[\s\S]{0,300}if \(v && typeof v === 'object'\) v = wResolveImg\(v\)[\s\S]{0,120}String\(v == null \? '' : v\)/.test(src))
ok('组合节点预览用的 nodePreviewRefsV2 + refMini 仍在(相册 ref 伪装成图片节点)',
src.includes('nodePreviewRefsV2:') || src.includes('nodePreviewRefsV2,'))
ok('相册 items 转 ref 节点时对象引用挂到 data.url(宿主 fake ref 的约定)',
fs.readFileSync(path.join(ROOT, 'src/generation-task-graph.js'), 'utf8').includes("(typeof src === 'string') ? { data: src, name: name } : { url: src, name: name }"))
console.log('\n===== 图片引用预览链:' + n + ' 通过 / 0 失败 =====')
+1 -1
View File
@@ -7,7 +7,7 @@ const path = require('path')
const root = path.join(__dirname, '..')
const SRC = fs.readFileSync(path.join(root, 'src/image-format.js'), 'utf8')
const box = {}
new Function('window', 'globalThis', SRC)(box, box) // 与 image-preview-derive-test.js 相同的沙箱加载方式
new Function('window', 'globalThis', SRC)(box, box) // 沙箱加载:只注入 window/globalThis,模块不得依赖宿主其它全局
const F = box.IWBImageFormat
let pass = 0, fail = 0
const ok = (name, cond) => { if (cond) { pass++; console.log(' ✅ ' + name) } else { fail++; console.log(' ❌ ' + name) } }
-189
View File
@@ -1,189 +0,0 @@
// 预览产物生成器(src/image-preview-derive.js)行为测试 —— 独立文件,可异步
// 关键断言:解码阶段就传 resizeWidth/resizeHeight(绝不产全尺寸位图)、bitmap.close 无泄漏、
// revokeAll 幂等、跨域走 opts.viaUrl、失败只回 { ok:false } 不抛。
'use strict'
const fs = require('fs')
const path = require('path')
const root = path.join(__dirname, '..')
const src = fs.readFileSync(path.join(root, 'src/image-preview-derive.js'), 'utf8')
const box = {}
new Function('window', 'globalThis', src)(box, box) // 与 image-blob-store-test.js 相同的沙箱加载方式
const M = box.IWBImagePreviewDerive
let pass = 0, fail = 0
const ok = (name, cond) => { if (cond) { pass++; console.log(' ✅ ' + name) } else { fail++; console.log(' ❌ ' + name) } }
// ---- 构造带真实头部的假 PNG(只给头部,不需要可解码的像素数据)----
function pngHeaderBytes(w, h) {
const b = Buffer.alloc(33)
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(b, 0)
b.writeUInt32BE(13, 8)
b.write('IHDR', 12, 'ascii')
b.writeUInt32BE(w, 16)
b.writeUInt32BE(h, 20)
b[24] = 8; b[25] = 6; b[26] = 0; b[27] = 0; b[28] = 0
return b
}
const pngDataUrl = (w, h) => 'data:image/png;base64,' + pngHeaderBytes(w, h).toString('base64')
// ---- 假解码 / 假 canvas(不产真图)----
const saved = {
cib: globalThis.createImageBitmap,
fetch: globalThis.fetch,
doc: globalThis.document,
oc: globalThis.OffscreenCanvas,
img: globalThis.Image,
revoke: URL.revokeObjectURL,
}
let cibCalls = []
let lastBitmap = null
let canvasCalls = []
let lastCanvas = null
let revokedUrls = []
function installFakeDecode() {
cibCalls = []
globalThis.createImageBitmap = async (blob, opts) => {
cibCalls.push({ blob: blob, opts: opts || null })
const w = (opts && Number(opts.resizeWidth)) || 4000
const h = (opts && Number(opts.resizeHeight)) || 6000
const bmp = { width: w, height: h, closed: false, close: function () { this.closed = true } }
lastBitmap = bmp
return bmp
}
}
function installFakeCanvas() {
canvasCalls = []
delete globalThis.OffscreenCanvas
const mk = () => {
const canvas = {
width: 0, height: 0, type: '', quality: 0,
getContext: () => ({ drawImage: () => { canvas.drawn = true } }),
toBlob: (cb, type, quality) => {
canvas.type = type; canvas.quality = quality
canvasCalls.push({ width: canvas.width, height: canvas.height, type: type, quality: quality })
cb(new Blob([new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])], { type: type }))
},
}
lastCanvas = canvas
return canvas
}
globalThis.document = { createElement: (tag) => (tag === 'canvas' ? mk() : {}) }
}
function restoreEnv() {
const put = (k, v) => { if (v === undefined) { try { delete globalThis[k] } catch (e) { globalThis[k] = undefined } } else globalThis[k] = v }
put('createImageBitmap', saved.cib)
put('fetch', saved.fetch)
put('document', saved.doc)
put('OffscreenCanvas', saved.oc)
put('Image', saved.img)
URL.revokeObjectURL = saved.revoke
}
const d = M.create({})
let r1 = null, rKeep = null, rUrl1 = null, rUrl2 = null, rBig = null
async function main() {
// 1) 模块加载 / 导出
ok('模块加载并导出 IWBImagePreviewDerive', !!M && typeof M === 'object')
ok('导出 { create }', typeof M.create === 'function')
const api = M.create({})
ok('create() 返回完整 API(derive/deriveUrl/revokeAll/stats)',
['derive', 'deriveUrl', 'revokeAll', 'stats'].every((k) => typeof api[k] === 'function'))
ok('初始 stats 为 {created:0,revoked:0,live:0,failed:0}',
api.stats().created === 0 && api.stats().revoked === 0 && api.stats().live === 0 && api.stats().failed === 0)
// 2) 解码即缩放:传入等比且长边 ≤ maxEdge 的 resizeWidth/resizeHeight
installFakeDecode(); installFakeCanvas()
r1 = await d.derive(pngDataUrl(4000, 6000), { maxEdge: 1024 })
const call = cibCalls[0]
ok('createImageBitmap 收到 resizeWidth/resizeHeight',
!!(call && call.opts && typeof call.opts.resizeWidth === 'number' && typeof call.opts.resizeHeight === 'number'))
ok('resizeQuality = high', !!(call && call.opts && call.opts.resizeQuality === 'high'))
const rw = call && call.opts ? call.opts.resizeWidth : 0
const rh = call && call.opts ? call.opts.resizeHeight : 0
ok('长边 ≤ maxEdge(' + rw + '×' + rh + ' ≤ 1024)', Math.max(rw, rh) <= 1024)
ok('等比缩放(4000:6000 比例保持)', Math.abs((rw / rh) - (4000 / 6000)) < 0.01)
ok('未按全尺寸解码(2160×3840 类全尺寸位图不会产生)', rw < 4000 && rh < 6000)
ok('derive 返回 ok + blob + width/height/bytes/ms',
r1.ok === true && !!r1.blob && r1.width === rw && r1.height === rh && r1.bytes > 0 && typeof r1.ms === 'number')
// 3) 无泄漏:bitmap.close 必须被调用
ok('bitmap.close() 被调用(解码位图已释放)', !!lastBitmap && lastBitmap.closed === true)
// 4) format='keep' + PNG 输入 ⇒ 输出 MIME 保持 image/png
rKeep = await d.derive(pngDataUrl(800, 600), { format: 'keep', maxEdge: 1024 })
ok("format='keep' 输出 blob MIME = image/png",
rKeep.ok === true && !!rKeep.blob && rKeep.blob.type === 'image/png')
ok('canvas.toBlob 收到 image/png', !!(lastCanvas && lastCanvas.type === 'image/png'))
ok('dataURL 前缀为 data:image/png', typeof rKeep.dataUrl === 'string' && rKeep.dataUrl.indexOf('data:image/png') === 0)
// 5) fetch 失败 ⇒ { ok:false, error },不抛
const failedBefore = d.stats().failed
globalThis.fetch = async () => { throw new Error('network down') }
let threw = false
let rFail = null
try { rFail = await d.derive('https://cdn.example.com/blocked.png', { maxEdge: 512 }) } catch (e) { threw = true }
ok('fetch 抛错 ⇒ 返回 { ok:false, error } 而非抛出', threw === false && !!rFail && rFail.ok === false && typeof rFail.error === 'string')
ok('失败计入 stats().failed', d.stats().failed === failedBefore + 1)
// 7) http URL 使用 opts.viaUrl(同源代理)
const fetched = []
globalThis.fetch = async (url) => {
fetched.push(url)
return { ok: true, status: 200, blob: async () => new Blob([pngHeaderBytes(1200, 900)], { type: 'image/png' }) }
}
const rVia = await d.derive('https://cdn.example.com/orig.png', { viaUrl: 'https://proxy.example.com/?u=orig.png', maxEdge: 600 })
ok('http 输入使用 opts.viaUrl 作为 fetch 目标',
fetched.length === 1 && fetched[0] === 'https://proxy.example.com/?u=orig.png')
ok('经代理派生结果长边 ≤ maxEdge', rVia.ok === true && Math.max(rVia.width, rVia.height) <= 600)
// 8) 超大图 4000×6000 派生结果 ≤ maxEdge
rBig = await d.derive(pngDataUrl(4000, 6000), { maxEdge: 1024, format: 'jpeg' })
ok('超大图(4000×6000)派生结果 width/height ≤ maxEdge',
rBig.ok === true && rBig.width <= 1024 && rBig.height <= 1024)
ok('超大图长边正好压到 maxEdge(height = 1024)', rBig.height === 1024)
ok('默认 format='+"'jpeg'"+' 时 canvas 收到 image/jpeg', !!(lastCanvas && lastCanvas.type === 'image/jpeg'))
// 6) deriveUrl + revokeAll 幂等
URL.revokeObjectURL = (u) => { revokedUrls.push(u) }
const dUrl = M.create({})
rUrl1 = await dUrl.deriveUrl(pngDataUrl(1000, 500), { maxEdge: 256 })
rUrl2 = await dUrl.deriveUrl(pngDataUrl(1000, 500), { maxEdge: 256 })
ok('deriveUrl 产出 blob: objectURL(含 revoke 句柄)',
rUrl1.ok === true && typeof rUrl1.url === 'string' && rUrl1.url.indexOf('blob:') === 0 && typeof rUrl1.revoke === 'function')
ok('objectURL 已登记(stats().live === 2)', dUrl.stats().live === 2 && dUrl.stats().created === 2)
let revokeThrew = false
try { dUrl.revokeAll(); dUrl.revokeAll() } catch (e) { revokeThrew = true }
ok('revokeAll() 幂等:连续两次不抛', revokeThrew === false)
ok('revokeAll() 后 stats().live === 0', dUrl.stats().live === 0)
ok('revoked 计数为 2(第二次不重复计数)', dUrl.stats().revoked === 2)
ok('URL.revokeObjectURL 真的被调用到两个 URL', revokedUrls.length === 2)
ok('单独 revoke() 幂等且不抛', rUrl1.revoke() === false && dUrl.stats().live === 0)
// 附加:无解码器/无 canvas 环境 ⇒ 只回失败,不抛
const dNo = M.create({})
delete globalThis.createImageBitmap
delete globalThis.document
delete globalThis.Image
delete globalThis.OffscreenCanvas
let noThrew = false
let rNo = null
try { rNo = await dNo.derive(pngDataUrl(4000, 6000), { maxEdge: 256 }) } catch (e) { noThrew = true }
ok('无解码器/无 canvas ⇒ { ok:false } 不抛', noThrew === false && !!rNo && rNo.ok === false && typeof rNo.error === 'string')
ok('失败计入该实例的 stats().failed', dNo.stats().failed === 1 && dNo.stats().live === 0)
// 附加:dataURL 非图片 / 非法输入 ⇒ 优雅失败
installFakeDecode(); installFakeCanvas()
const rBad = await d.derive('data:text/plain;base64,' + Buffer.from('hi').toString('base64'), {})
ok('非图片 dataURL ⇒ { ok:false, error }', rBad.ok === false && typeof rBad.error === 'string')
// 附加:Blob 输入形态
const rBlob = await d.derive(new Blob([pngHeaderBytes(2000, 1000)], { type: 'image/png' }), { maxEdge: 500, format: 'keep' })
ok('支持 Blob 输入(保持 MIME 且长边 ≤ maxEdge)',
rBlob.ok === true && rBlob.blob.type === 'image/png' && Math.max(rBlob.width, rBlob.height) === 500 && rBlob.width === 500)
restoreEnv()
console.log('\n===== image-preview-derive:' + pass + ' 通过 / ' + fail + ' 失败 =====')
process.exit(fail ? 1 : 0)
}
main().catch((e) => { console.error('❌ 测试异常:', e && e.stack || e); process.exit(1) })
+1 -1
View File
@@ -695,7 +695,7 @@ test('⑬ 连接节点来源行与组合节点一致;中继节点改色只染
// ③ 暗色下顶部标签:选中态必须与未选中态有可见差异(用户反馈难区分)
const tabs = await page.evaluate(() => {
const all = Array.from(document.querySelectorAll('.iwb-tabstrip .iwb-tab'))
const act = all.find((t) => t.classList.contains('iwb-tab-active') && !t.classList.contains('iwb-tab-home'))
const act = all.find((t) => t.classList.contains('iwb-tab-active'))
const inact = all.find((t) => !t.classList.contains('iwb-tab-active'))
return { active: act ? getComputedStyle(act).backgroundColor : null, inactive: inact ? getComputedStyle(inact).backgroundColor : null }
})
+2 -2
View File
@@ -3,6 +3,7 @@
// 本用例是 flush 路径优化的回归护栏——原实现逐节点深拷贝 data + 二次全量 strip 被换成
// copyNodeForPersist + WorkspaceStore.writeStripped 后,对外语义必须一字不变。
const { test, expect } = require('./_pw-coverage')
const W = require('./_helpers/wait')
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
test.use({ baseURL, viewport: { width: 1440, height: 1000 } })
const CFG = { providers: [{ id: 'p-a', name: 'A', baseUrl: 'https://a.example/v1', keys: [{ id: 'a-1', name: 'K', value: 'sk' }], models: [{ name: 'gpt-image-2', visible: true }] }], canvas: { snap: true } }
@@ -109,8 +110,7 @@ test('flush 合成所有打开 session:非激活标签的未保存编辑同样
await page.waitForTimeout(1200)
await openCard(page, '甲') // 打开 甲 → 标签 1
await page.waitForTimeout(2000)
await page.locator('.iwb-tab-home').click() // 回画布库(甲 仍是打开但未激活的 session)
await page.waitForTimeout(400)
await W.goHome(page) // 回画布库(甲 仍是打开但未激活的 session)
await openCard(page, '乙') // 打开 乙 → 标签 2,成为激活 session
await page.waitForTimeout(2600)
const wbId = await page.evaluate(() => localStorage.getItem('iwb_ws_active'))
+102
View File
@@ -0,0 +1,102 @@
// 通用 → 新建配置节点「默认模型」:设置 → 保存 → 新建节点预选 → 模型行默认标识(2026-11-25)
const { test, expect } = require('./_pw-coverage')
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
test.use({ baseURL, viewport: { width: 1600, height: 1100 } })
const CFG = {
providers: [{
id: 'p-def', name: '默认服务', baseUrl: 'https://def.example/v1',
keys: [{ id: 'k-1', name: 'K', value: 'sk-test' }],
models: [{ id: 'm-1', name: 'model-alpha' }, { id: 'm-2', name: 'model-beta' }],
}],
canvas: {},
}
const WS = {
workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }],
activeId: 'w1', rev: 1,
}
const readCfg = (page) => page.evaluate(() => {
const raw = localStorage.getItem('iwb_web_cfg')
return raw ? JSON.parse(raw) : {}
})
async function enterCanvas (page, cfg) {
await page.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
localStorage.setItem('iwb_web_workspaces', JSON.stringify(d.ws))
localStorage.setItem('iwb_ws_active', d.ws.activeId)
localStorage.setItem('iwb_ws_w1', JSON.stringify(d.ws.workspaces[0]))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
}, { cfg: cfg || CFG, ws: WS })
await page.goto('/', { waitUntil: 'domcontentloaded' })
await page.waitForTimeout(700)
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
}
test.beforeEach(async ({ page }) => {
const errors = []
page.on('pageerror', (e) => errors.push(String((e && e.message) || e)))
page.__errors = errors
})
test('通用 tab 选默认模型 → 保存 → 新建配置节点预选该模型', async ({ page }) => {
await enterCanvas(page)
// 打开设置(默认就是通用 tab)
await page.locator('.iwb-nav-item[title="设置"]').first().click()
const modal = page.locator('.iwb-settings-modal')
await expect(modal).toBeVisible()
await modal.locator('.iwb-set-nav-item', { hasText: '通用' }).first().click()
// ① 新分组在通用 tab,下拉可选项 = 全部启用模型
const sel = modal.locator('select[aria-label="新建配置节点默认模型"]')
await expect(sel).toBeVisible()
await expect(sel.locator('option')).toHaveCount(3) // 未设置 + 2 模型
await expect(sel.locator('option', { hasText: '默认服务 · model-beta' })).toHaveCount(1)
// ② 选 model-beta → 保存
await sel.selectOption({ label: '默认服务 · model-beta' })
await modal.locator('button:has-text("保存配置")').click()
await expect(modal.getByText('已保存')).toBeVisible()
await expect.poll(async () => {
const c = await readCfg(page)
return c.defaultGen && c.defaultGen.model
}, { timeout: 10000 }).toBe('model-beta')
// ③ 关闭设置 → 新建配置节点 → 模型预选为 model-beta
const closeBtn = page.locator('.iwb-modal-head button[title="关闭"]')
if (await closeBtn.count()) await closeBtn.click()
const canvas = page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')
const box = await canvas.boundingBox()
await canvas.click({ button: 'right', position: { x: Math.round(box.width / 2), y: Math.round(box.height / 2) } })
const ctx = page.locator('.iwb-ctxmenu:not(.iwb-ctx-sub)')
await expect(ctx).toBeVisible({ timeout: 8000 })
const genItem = ctx.locator('.iwb-ctx-item', { hasText: '配置' }).first()
await expect(genItem).toBeVisible({ timeout: 8000 })
await genItem.click()
const pick = page.locator('.iwb-pick-genmodel').first()
await expect(pick).toBeVisible({ timeout: 8000 })
await expect(pick).toContainText('model-beta')
expect(page.__errors, '不应有页面异常').toEqual([])
})
test('默认模型行有「默认」标识且带高亮描边', async ({ page }) => {
await enterCanvas(page, { ...CFG, defaultGen: { providerId: 'p-def', model: 'model-beta', keyGroup: 'k-1' } })
await page.locator('.iwb-nav-item[title="设置"]').first().click()
const modal = page.locator('.iwb-settings-modal')
await modal.locator('.iwb-set-nav-item', { hasText: '生图服务' }).first().click()
await expect(page.locator('.iwb-prov-chip').first()).toBeVisible({ timeout: 10000 })
const rows = page.locator('.iwb-modelrow')
const beta = rows.filter({ hasText: 'model-beta' }).first()
const alpha = rows.filter({ hasText: 'model-alpha' }).first()
await expect(beta.locator('.iwb-modelrow-defmark')).toHaveText('默认')
await expect(beta).toHaveClass(/iwb-modelrow-default/)
await expect(alpha.locator('.iwb-modelrow-defmark')).toHaveCount(0)
})
+2 -2
View File
@@ -48,8 +48,8 @@ test('创建副本保留本次新画连线 + 连续复制副本名唯一', async
const persisted = await page.evaluate(() => { const rec = JSON.parse(localStorage.getItem('iwb_ws_w1') || 'null'); return rec ? (rec.edges || []).length : -1 })
expect(persisted, '新画的连线应已持久化到 iwb_ws_w1').toBe(1)
// 回画布库:常驻标签栏最左「首页」图标标签(.iwb-tab-home)
await page.locator('.iwb-tab-home').click()
// 回画布库:一级导航「首页」(标签条房子按钮 v3.25.62 已删)
await W.goHome(page)
await expect(cardBy(page, '源画布')).toHaveCount(1)
await expect(cardBy(page, '源画布')).toContainText('1 条连线')
+2 -1
View File
@@ -1,6 +1,7 @@
// S14(多标签)离开画布释放语义:打开标签保留 hydrate(切回即用),关闭标签/非打开画布才释放。
// 用行为计数器做契约(不依赖 MB 级数据,避免 localStorage 配额干扰)。
const { test, expect } = require('./_pw-coverage')
const W = require('./_helpers/wait')
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
test.use({ baseURL, viewport: { width: 1440, height: 1000 } })
const CFG = { providers: [{ id: 'p-a', name: 'A', baseUrl: 'https://a.example/v1', keys: [{ id: 'a-1', name: 'K', value: 'sk' }], models: [{ name: 'gpt-image-2', visible: true }] }], canvas: { snap: true } }
@@ -32,7 +33,7 @@ test('离开画布释放、回到画布重新 hydrate', async ({ page }) => {
expect(c0.nodes, '画板应正常打开').toBe(2)
// S14:回「我的画布」→ 打开标签保留 hydrate(不释放,切回即用不闪黑图)
await page.locator('.iwb-tab-home').click() // 标签条「房子」图标
await W.goHome(page) // 一级导航「首页」
await page.waitForTimeout(600)
const c1 = await page.evaluate(() => ({ un: window.__IWB_E2E_UNHYDRATES__ || 0, tabs: JSON.parse(localStorage.getItem('iwb_tabs_open') || '[]') }))
expect(c1.tabs, '打开的画布应在标签条里').toContain('w1')
+1 -2
View File
@@ -318,8 +318,7 @@ test('⑤ 多标签:切走再切回不重新请求(打开标签保留 object
const src0 = await img.evaluate((el) => String(el.currentSrc || el.src))
const proxyAfter = counters.proxy
// 打开第二个画布(Beta)成为第二个标签
await page.locator('.iwb-tab-home').click()
await W.waitHomeReady(page)
await W.goHome(page)
await page.locator('.iwb-home-card:not(.iwb-home-new)').filter({ hasText: 'Beta' }).dblclick()
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
await page.waitForTimeout(300)
+2 -2
View File
@@ -4,6 +4,7 @@
// ③ 撤销仍然可用:恢复到上一状态,且图片(引用)能被 hydrate 回来 —— 内存修复不能牺牲功能
// 运行:npm run build && IWB_BASE_URL=http://127.0.0.1:8787 npx playwright test tests/iwb-memory-history.spec.js
const { test, expect } = require('./_pw-coverage')
const W = require('./_helpers/wait')
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
test.use({ baseURL, viewport: { width: 1440, height: 1000 } })
@@ -244,8 +245,7 @@ test('C3:历史 {__idb} 引用装载时迁移为 {__blob}(imgblob_,IDB Blo
// 等自动保存把 {__idb} 引用落进 localStorage。用轮询替代固定等待:并发(多 worker)下防抖/落盘时序会漂移,固定 2500ms 偶发不够(引用未落盘 → 切走再回来不会触发迁移)
await expect.poll(() => page.evaluate(() => String(localStorage.getItem('iwb_ws_w1') || '').includes('__idb')), { timeout: 15000 }).toBe(true)
// 切回画布库再进画布 → 走 hydrate(迁移 __idb → __blob)
await page.locator('.iwb-tab-home').click()
await page.waitForTimeout(700)
await W.goHome(page)
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
const diag = await page.evaluate(async () => {
+5 -1
View File
@@ -150,9 +150,13 @@ test('设置里手动勾选「质量」并保存:节点即可选档位并发
await seed(page, 'gpt-image-2', CFG_PLAIN)
// 打开设置 → 生图服务:默认**一个都没勾**(含 gpt-image-2.5),勾选完全手动
await page.locator('.iwb-top-nav-icon[title="服务与 Key 设置"]').click()
const nav = page.locator('.iwb-nav-item[title="设置"]')
if (await nav.count() > 0) await nav.first().click()
else await page.locator('[title="服务与 Key 设置"]').first().click()
const modal = page.locator('.iwb-settings-modal')
await expect(modal).toBeVisible()
// 设置默认打开「通用」标签(2026-11-25 用户裁定)→ 显式切到生图服务
await modal.locator('.iwb-set-nav-item', { hasText: '生图服务' }).first().click()
await expect(modal.locator('.iwb-modelrow-q input[aria-label="支持质量 gpt-image-2.5"]')).not.toBeChecked()
const q = modal.locator('.iwb-modelrow-q input[aria-label="支持质量 gpt-image-2"]')
await expect(q).not.toBeChecked()
+5 -3
View File
@@ -7,7 +7,7 @@
//
// 选择器依据实际 DOM(2026-11-10 探针确认):
// · 渠道卡片 .iwb-provider-card;删除渠道 = 文案「删除服务」
// · 模型行 .iwb-modelrow;删除模型 = title「删除模型」(aria-label 带模型名)
// · 模型行 .iwb-modelrow;删除模型 = 行内垃圾桶按钮 title「删除模型」(aria-label 带模型名)
// · 添加模型 = 模型输入框所在行里的按钮(输入框 placeholder「手动添加模型名」)
const { test, expect } = require('./_pw-coverage')
@@ -33,6 +33,8 @@ async function openSettings (page) {
]
for (const c of cands) if (await c.count() > 0) { await c.first().click(); break }
}
// 设置默认打开「通用」标签(2026-11-25 用户裁定)→ 生图服务的用例需显式切过去
await page.locator('.iwb-set-nav-item', { hasText: '生图服务' }).first().click()
await expect(page.locator('.iwb-prov-chip').first()).toBeVisible({ timeout: 10000 })
}
@@ -103,8 +105,8 @@ test('② 模型可新增与删除,且改动会写入配置', async ({ page })
await expect(rows).toHaveCount(2, { timeout: 8000 })
// 删除刚加的 → 回到 1 行
await card.locator('.iwb-model-more-btn').last().click()
await card.locator('[title="删除模型"]').last().click()
// 2026-11-25:删除从 ⋯ 菜单提到行内垃圾桶按钮,一步点掉(内置模型该按钮 disabled,这里取自定义模型的)
await card.locator('button.iwb-model-del[title="删除模型"]').last().click()
await expect(rows).toHaveCount(1, { timeout: 8000 })
// 再加一次并保存 → 配置里应含新模型(同时验证"删了再加"不会把列表搞坏)
+2
View File
@@ -25,6 +25,8 @@ test('设置里可配厂商类型 / 自定义模板 / 模型级覆盖', async ({
expect(opened, '应能找到设置入口').toBe(true)
}
await page.waitForTimeout(700)
// 设置默认打开「通用」标签(2026-11-25 用户裁定)→ 显式切到生图服务
await page.locator('.iwb-set-nav-item', { hasText: '生图服务' }).first().click()
const kindSel = page.locator('select[aria-label="厂商类型"]').first()
await expect(kindSel).toBeVisible()
await expect(kindSel).toHaveValue('openai')
+3 -2
View File
@@ -1,7 +1,8 @@
const { test, expect } = require('./_pw-coverage')
const W = require('./_helpers/wait')
const baseURL = process.env.IWB_BASE_URL || 'https://iwb.maqiart.eu.org'
// 2026-11-24:默认指向本地测试服(此前默认打线上,等于每次跑都在测已部署版本,本地改动测不到)
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
const workspace = {
workspaces: [{ id: 'ws_e2e', name: 'E2E 工作台', nodes: [{ id: 'p_e2e', type: 'prompt', x: 120, y: 120, data: { text: 'E2E prompt', title: '' } }], edges: [], groups: [] }],
@@ -169,7 +170,7 @@ test('新建并切换工作台后刷新仍保留', async ({ page }) => {
await page.reload({ waitUntil: 'domcontentloaded' })
// 刷新后恢复在画布编辑器;返回画布库应看到 2 张画布卡片
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
await page.locator('.iwb-tab-home').click()
await W.goHome(page)
await expect(page.locator('.iwb-home-card')).toHaveCount(2)
})
+3 -2
View File
@@ -2,6 +2,7 @@
// 完成时若正浏览该画布则不记提示;切到该画布即清除(会话内内存态)。
// 运行:npm run build && IWB_E2E_SPECS=tests/iwb-tab-dot.spec.js npm run test:e2e
const { test, expect } = require('./_pw-coverage')
const W = require('./_helpers/wait')
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
test.use({ baseURL, viewport: { width: 1440, height: 1000 } })
@@ -58,7 +59,7 @@ test('生成完成圆点变绿/失败变红,切换画布后清除', async ({ p
const release1 = arm('ok')
await runGen()
await expect.poll(() => reqCount, { timeout: 10000 }).toBe(1)
await page.locator('.iwb-tab-home').click() // 回画布库
await W.goHome(page) // 回画布库
await cardB.dblclick() // 切到画布 B(A 上的生成继续跑)
await page.waitForTimeout(300)
release1() // 放行 A 的生成请求
@@ -73,7 +74,7 @@ test('生成完成圆点变绿/失败变红,切换画布后清除', async ({ p
const release2 = arm('fail')
await runGen()
await expect.poll(() => reqCount, { timeout: 10000 }).toBe(2)
await page.locator('.iwb-tab-home').click()
await W.goHome(page)
await cardB.dblclick()
release2()
await expect(tabA.locator('.iwb-tab-dot-err'), '生成失败后 A 标签应出现红色圆点').toBeVisible({ timeout: 15000 })
+4 -7
View File
@@ -101,8 +101,7 @@ test('1. 回画布库不释放打开标签:画板不降级、objectURL 不回
const base = await counters(page) // 冷启动本身会产生一些回收(卸载/重建),后面一律比增量
// 单个打开标签先回一次首页:这是"打开标签保留"的最小情形
await page.locator('.iwb-tab-home').click()
await W.waitHomeReady(page)
await W.goHome(page)
const c1 = await counters(page)
expect(c1.tabs, '回首页不该把标签弄丢').toContain('w1')
expect(c1.un, '打开标签的画板回首页不降级(S14:切回即用)').toBe(base.un)
@@ -113,8 +112,7 @@ test('1. 回画布库不释放打开标签:画板不降级、objectURL 不回
await W.waitCanvasOpen(page)
await expect(tabBy(page, 'Alpha')).toHaveCount(1)
await expect(tabBy(page, 'Beta')).toHaveCount(1)
await page.locator('.iwb-tab-home').click()
await W.waitHomeReady(page)
await W.goHome(page)
const c2 = await counters(page)
expect(c2.tabs.sort()).toEqual(['w1', 'w2'])
expect(c2.un, '两个标签都打开时回首页仍不降级').toBe(c1.un)
@@ -166,7 +164,7 @@ test('2. 关闭有未保存修改的标签:取消则不动,确认则先保
await tabBy(page, 'Alpha').hover()
await tabBy(page, 'Alpha').locator('.iwb-tab-close').click()
await expect(tabBy(page, 'Alpha'), '确认后标签应消失').toHaveCount(0)
await expect(page.locator('.iwb-tab-home')).toHaveClass(/iwb-tab-active/) // 没有剩余标签 → 回首页
await W.expectHomeActive(page) // 没有剩余标签 → 回首页(标签条房子按钮已删,改判一级导航「首页」active)
await W.poll(page, async () => (await counters(page)).un, { timeout: 8000 }).toBe(before.un + 1)
const afterClose = await counters(page)
expect(afterClose.tabs, 'iwb_tabs_open 不该还留着已关闭的画布').not.toContain('w1')
@@ -188,8 +186,7 @@ test('3. 彻底删除仍开着标签的画布:标签消失、session 释放、
await W.waitCanvasOpen(page)
await hydrateBigImage(page)
const before = await counters(page)
await page.locator('.iwb-tab-home').click()
await W.waitHomeReady(page)
await W.goHome(page)
let mode = 'accept'
page.on('dialog', async (d) => { if (mode === 'accept') await d.accept(); else await d.dismiss() })
+2 -1
View File
@@ -32,7 +32,8 @@ assert.deepStrictEqual(specsBase, expectedSpecs, '门禁 spec 必须等于全部
// 55 = 54 + iwb-multi-tab(v3.24.85:跨标签页契约 —— A 页 flush 落盘后 B 页靠 rev 轮询可见 / 图库归档受跨进程锁保护)
// 53 = 55 − iwb-csp-gate − iwb-functions-headers(v3.25.15:网页版部署面删除,两条只测 _headers/Functions 的 spec 一并删除)
// 52 = 53 − iwb-groups-sidebar(v3.25.56 节点组库改为插件 grouplib,宿主侧栏组件删除,其 e2e 一并移除)
assert.strictEqual(result.specs.length, 52, '当前门禁应自动发现 52 个 spec')
// 53 = 52 + iwb-default-gen-model(v3.26.71:通用 tab 设置新建配置节点默认模型)
assert.strictEqual(result.specs.length, 53, '当前门禁应自动发现 53 个 spec')
// 排除集合 = 全部人工 dev 探针,且都必须已声明标记
// 4 = 3 + _probe-tab-switch(切画布标签耗时归因:四轮对照实验,只读诊断)
// 5 = 4 + _visual-tokens(设计 token 视觉基线:像素受字体/DPR 影响,不入 CI,本地 0 diff 验收用)
+3 -1
View File
@@ -51,7 +51,9 @@ assert.ok(!css.includes('.iwb-rail-tab'), 'v3.27.1:右竖栏页签已删除(
// 迁到 token 后这种断言会红,但它真正要保护的是「卡片标题用 lg 档」这个层级关系。
assert.ok(/\.iwb-home-card-title strong \{[^}]*font-size: var\(--iwb-font-lg\)/.test(css), 'v3.26.46:卡片标题应为 font-lg 档')
// v3.1.0 首页灰色系:蓝 accent 清零(激活项/胶囊/chip/星标全走墨色或灰阶)
assert.ok(/\.iwb-tab-home\.iwb-tab-active \{[^}]*background: transparent/.test(css)) // 首页按钮无选中底色
// 2026-11-24:标签条「首页」按钮 v3.25.62 已删(选择器无生产者),钉点改钉一级导航激活项 ——
// 语义不变:激活项不用品牌色填充,走「墨色底 + 反白字」。
assert.ok(/\.iwb-nav-item\.on \{[^}]*background: var\(--iwb-text\)/.test(css), '一级导航激活项应为墨色底')
assert.ok(/\.iwb-home-card \{[^}]*background: var\(--iwb-bg-menu\)/.test(css)) // v3.26.44:卡片改用浮起层(亮=面板色,暗=比面板亮一档)
assert.ok(!source.includes('iwb-home-card-active')) // 无「默认必有一个选中卡」的伪选中态
assert.ok(!/\.iwb-home-card-cat \{[^}]*iwb-brand/.test(css))
-226
View File
@@ -1,226 +0,0 @@
'use strict'
// src/plugin-archive.js 的行为测试。
//
// 为什么测试要这么细:插件包来自外部,ZIP 解包是这个功能的**信任边界**。
// 路径穿越、非法后缀、重名条目、超限条目(zip 炸弹)只要漏一个,
// 用户点一次"导入插件"就可能把文件写到插件目录之外,或把内存/磁盘打爆。
//
// 用 vm 加载真实模块(IIFE 挂 window),并先加载 src/storage-zip.js ——
// 测试不 mock ZIP 编解码,测的就是线上真实走的那条链路。
// ⚠️ 跨 realm:模块在 vm 里创建对象/数组,原型与本文件不同,
// 所以内容比较统一走 JSON,不能用 deepStrictEqual。
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const root = path.resolve(__dirname, '..')
const sandbox = {
console: { log() {}, warn() {}, error() {} },
TextEncoder, TextDecoder, Blob, DataView, Uint8Array, Uint32Array,
Response, DecompressionStream, Date, Error, Math, String, Number, Array, Object, JSON, Promise, Set, Map, Boolean, isNaN, parseInt,
}
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'storage-zip.js'), 'utf8'), sandbox)
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'plugin-archive.js'), 'utf8'), sandbox)
const Z = sandbox.IWBStorageZip
const A = sandbox.IWBPluginArchive
assert.ok(Z, '应加载 IWBStorageZip(storage-zip.js 是被测模块的真实依赖)')
assert.ok(A, '应导出 IWBPluginArchive')
const eqJson = (a, b, msg) => assert.strictEqual(JSON.stringify(a), JSON.stringify(b), msg)
const eqBytes = (a, b, msg) => eqJson(Array.from(a), Array.from(b), msg)
// 绕过 IWBPluginArchive.zip 的校验,直接用底层写入器造"恶意 ZIP":
// 只有这样才能验证 unzip 自身的防线(真实攻击者也不会经过我们的 zip())。
const rawZip = async (entries) => {
const w = Z.wCreateStoreZip()
for (const [name, data] of entries) await w.add(name, new Blob([data]))
return w.finish()
}
const expectReject = async (fn, pattern, label) => {
let err = null
try { await fn() } catch (e) { err = e }
assert.ok(err, label + ':应 reject,实际却成功了')
assert.ok(pattern.test(String(err && err.message)),
label + ':错误消息应匹配 ' + pattern + ',实际:' + (err && err.message))
}
// 篡改中央目录里的"原始大小"字段:用一个几字节的小 ZIP 模拟声明 16MB/64MB 的炸弹包。
// 这类包不需要真的把大字节读进内存,正好用来单独验证上限判断。
const patchCentralRawSize = async (blob, size) => {
const buf = await blob.arrayBuffer()
const dv = new DataView(buf)
const u8 = new Uint8Array(buf)
const eocd = u8.length - 22
const count = dv.getUint16(eocd + 10, true)
let p = dv.getUint32(eocd + 16, true)
for (let i = 0; i < count; i++) {
assert.strictEqual(dv.getUint32(p, true), 0x02014b50, '中央目录签名应正确')
dv.setUint32(p + 24, size, true) // 中央目录条目 +24 = 原始大小
const nameLen = dv.getUint16(p + 28, true)
const extraLen = dv.getUint16(p + 30, true)
const commentLen = dv.getUint16(p + 32, true)
p += 46 + nameLen + extraLen + commentLen
}
return new Blob([buf])
}
;(async () => {
// ── 1. 导出面与上限常量 ────────────────────────────────────────────────
{
assert.strictEqual(typeof A.zip, 'function', '应导出 zip')
assert.strictEqual(typeof A.unzip, 'function', '应导出 unzip')
assert.ok(A.limits && Object.isFrozen(A.limits), 'limits 应是冻结对象,防止运行期被改松')
assert.strictEqual(A.limits.maxFiles, 500, '条目上限应为 500')
assert.strictEqual(A.limits.maxFileBytes, 16 * 1024 * 1024, '单文件上限应为 16MB')
assert.strictEqual(A.limits.maxTotalBytes, 64 * 1024 * 1024, '总大小上限应为 64MB')
}
// ── 2. 往返:zip → unzip,字节逐一致(含中文内容)────────────────────
{
const binary = new Uint8Array(256)
for (let i = 0; i < binary.length; i++) binary[i] = i
const blob = await A.zip([
{ name: 'data.json', data: JSON.stringify({ title: '中文标题', n: 1 }) },
{ name: 'meta.json', data: '{"version":1}' },
{ name: 'images/a.jpg', data: binary },
])
assert.ok(blob && typeof blob.arrayBuffer === 'function', '应产出 Blob')
assert.strictEqual(blob.type, 'application/zip', 'ZIP 的 MIME 应为 application/zip')
const out = await A.unzip(blob)
eqJson(out.map((x) => x.name), ['data.json', 'meta.json', 'images/a.jpg'], '条目名与顺序应保持')
assert.strictEqual(new TextDecoder().decode(out[0].data), '{"title":"中文标题","n":1}',
'字符串内容按 UTF-8 写入、应原样读回(中文不能乱码)')
eqBytes(out[2].data, binary, '二进制内容应逐字节一致')
assert.strictEqual(Object.prototype.toString.call(out[0].data), '[object Uint8Array]', 'data 应是 Uint8Array')
}
// ── 3. 路径穿越 / 绝对路径 / 反斜杠:打包与解包都必须拒绝 ─────────────
{
const cases = [
['../evil.js', /\.\.|路径段/],
['/abs', /绝对路径/],
['images/../../x', /\.\.|路径段/],
['images\\a.jpg', /反斜杠/],
]
for (const [name, pattern] of cases) {
await expectReject(
() => A.zip([{ name, data: new Uint8Array([1]) }]),
pattern, 'zip 应拒绝 ' + name
)
await expectReject(
async () => A.unzip(await rawZip([[name, new Uint8Array([1])]])),
pattern, 'unzip 应拒绝 ' + name
)
}
}
// ── 4. 非法后缀 / 非白名单路径 / 中文文件名 ───────────────────────────
// 白名单只允许 ASCII 字母数字与 - _ . /,所以中文文件名也应被拒绝
// (中文可以出现在 data.json 的**内容**里,但不能出现在路径里)。
{
await expectReject(
() => A.zip([{ name: 'images/a.gif', data: new Uint8Array([1]) }]),
/后缀.*images\/a\.gif/, 'zip 应拒绝 .gif'
)
await expectReject(
async () => A.unzip(await rawZip([['images/a.gif', new Uint8Array([1])]])),
/后缀.*images\/a\.gif/, 'unzip 应拒绝 .gif'
)
for (const name of ['other/a.jpg', 'data.json.bak', 'images/nested/a.jpg', 'images/中文.jpg', 'images/a']) {
await expectReject(
() => A.zip([{ name, data: new Uint8Array([1]) }]),
/允许的|子目录|后缀|非法字符/, 'zip 应拒绝白名单外名字 ' + name
)
}
}
// ── 5. 重名条目:不能让后一个静默覆盖前一个 ───────────────────────────
// wOpenZipBlob 内部用普通对象存 files,重名会覆盖;所以 unzip 必须先用
// 中央目录预检。这条测试就是防止以后有人把预检"优化"掉。
{
await expectReject(
() => A.zip([
{ name: 'images/dup.jpg', data: new Uint8Array([1]) },
{ name: 'images/dup.jpg', data: new Uint8Array([2]) },
]),
/重名.*images\/dup\.jpg/, 'zip 应拒绝重名'
)
const dup = await rawZip([
['images/dup.jpg', new Uint8Array([1])],
['images/dup.jpg', new Uint8Array([2])],
])
await expectReject(() => A.unzip(dup), /重名.*images\/dup\.jpg/, 'unzip 应拒绝重名条目')
}
// ── 6. 条目数 > 500(打包与解包)──────────────────────────────────────
{
const tooMany = []
for (let i = 0; i < 501; i++) tooMany.push({ name: 'images/n' + i + '.jpg', data: new Uint8Array([1]) })
await expectReject(() => A.zip(tooMany), /500|文件数/, 'zip 应拒绝 501 个文件')
const tooManyRaw = []
for (let i = 0; i < 501; i++) tooManyRaw.push(['images/n' + i + '.jpg', new Uint8Array([1])])
await expectReject(
async () => A.unzip(await rawZip(tooManyRaw)),
/条目数.*500/, 'unzip 应拒绝 501 个条目'
)
}
// ── 7. 单文件 > 16MB:打包侧用真实长度;解包侧用伪造的声明长度 ─────────
{
const oversized = new Uint8Array(A.limits.maxFileBytes + 1)
await expectReject(
() => A.zip([{ name: 'images/big.jpg', data: oversized }]),
/16MB.*images\/big\.jpg/, 'zip 应拒绝 >16MB 的单文件'
)
const one = await rawZip([['images/a.jpg', new Uint8Array([1, 2, 3])]])
const fakeSingle = await patchCentralRawSize(one, A.limits.maxFileBytes + 1)
await expectReject(
async () => A.unzip(fakeSingle),
/16MB.*images\/a\.jpg/, 'unzip 应按声明大小拒绝 >16MB 的单条目(防 zip 炸弹)'
)
}
// ── 8. 总解压 > 64MB(声明值伪造,避免测试真的分配 64MB)─────────────
{
const five = []
for (let i = 0; i < 5; i++) five.push(['images/t' + i + '.jpg', new Uint8Array([1])])
const blob = await rawZip(five)
// 5 × 13MB = 65MB:每个都在 16MB 以内,只有总和超限 → 专门打总大小那条判断。
const fakeTotal = await patchCentralRawSize(blob, 13 * 1024 * 1024)
await expectReject(() => A.unzip(fakeTotal), /总大小.*64MB/, 'unzip 应拒绝解压后总大小 >64MB')
}
// ── 9. 合法目录条目被跳过;非法输入/类型要显式报错 ───────────────────
{
const withDir = await rawZip([
['images/', new Uint8Array(0)],
['images/a.png', new Uint8Array([7, 8])],
])
const out = await A.unzip(withDir)
eqJson(out.map((x) => x.name), ['images/a.png'], 'images/ 目录条目应被跳过,不计入文件')
eqBytes(out[0].data, new Uint8Array([7, 8]), '目录后的文件内容应正常读出')
await expectReject(() => A.zip('not-an-array'), /数组/, 'zip 应拒绝非数组输入')
await expectReject(
() => A.zip([{ name: 'data.json', data: 123 }]),
/Uint8Array 或 string/, 'zip 应拒绝非 Uint8Array/string 的内容'
)
await expectReject(() => A.unzip('not-a-blob'), /Blob/, 'unzip 应拒绝非 Blob 输入')
await expectReject(() => A.unzip(new Blob([new Uint8Array(32)])), /ZIP/, 'unzip 应拒绝非 ZIP 字节')
}
console.log('plugin archive checks passed(往返 + 路径穿越 + 白名单后缀 + 重名 + 条目数/单文件/总大小上限)')
// ⚠️ 显式退出:vm/Blob 可能让事件循环挂着(沿用 storage-zip-test 的处理)。
process.exit(0)
})().catch((e) => {
console.error('plugin archive checks FAILED:', e && e.message)
process.exit(1)
})
+1 -1
View File
@@ -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,nodeActions,nodeTypes,panels,promptlib,providers')
assert.strictEqual(host0.capabilities.slice().sort().join(','), 'canvas,canvasWrite,commands,files,gallery,generationHooks,grouplib,images,nodeActions,nodeTypes,panels,promptlib,providers')
const manifest = (over) => Object.assign({ id: 'demo-plugin', name: 'Demo', version: '1.0.0', apiVersion: 1, capabilities: [] }, over)
const stateOf = (ids) => {
+11 -1
View File
@@ -157,7 +157,17 @@ const MAX_SRC_COMPONENT_LINES = 531
// ② 纠正过时的存储口径注释(用户要求:旧的不准确描述要改掉):图库/缩略图/原图档在桌面端是
// images/thumbs、images/gallery 文件,不是 IndexedDB;「1K 插入档降的是长边像素不是体积」。
// 共 6 行注释,属于事实纠错而非功能代码。
const MAX_APP_JS_LINES = 9115 // 2026-11-24 v3.26.61:图库同步边界抽到 src/gallery-sync.js + 纠错存储口径注释
// 2026-11-26 v3.26.66:9134 → **9159**(+25,相册节点宿主侧接线,逐条记账):
// · {__file} 本地文件引用四处分派(识别/key/字节解析/显示 URL) +4
// · 导出时 items[].src 内联(跨设备可带走) +8
// · ctx.images 能力装配(deps 注入 wImportImage/wImgRefDataUrl/thumb)+13
// · 导入保留原图(keepOriginal 分支,2 行) +2
// · 本地文件模块惰性取用 wFileRefMod(避免跨文件引用脆弱,8 行) +8
// · 底栏「插件节点」下拉接线(回调 + 传参,2 行) +2
// · 底栏换拼图图标入口(puzzle 图标 + 组件接线,2 行) +2
// 通用件(pick/grant/stat/readDataUrl/readBlob/参数校验)全部在 src/image-file-ref.js
// 与 src/plugin-api-images.js,app.js 只做装配。
const MAX_APP_JS_LINES = 9173
const MAX_APP_JS_SHARE = 0.40
// ── 历史记账(供回溯,逐条保留)──────────────────────────────────────────────
+12
View File
@@ -225,4 +225,16 @@ const mig2 = S.wMigrateLlm({ providers: [{ id: 'l0', name: 'a', baseUrl: 'https:
assert.strictEqual(mig2.providers[0].baseUrl, 'https://api.tu-zi.com/v1', 'LLM 渠道 baseUrl 迁移应剥掉接口路径')
assert.strictEqual(mig2.providers[0].fallbacks[0], 'https://b.test/v1', 'LLM 备用地址迁移应剥掉接口路径')
// ── 10. wShapeProviderFields:鉴权方式白名单(2026-11-24,v3.26.65)────────────
// 背景:认证此前写死 Bearer,接不了要 x-api-key / URL 参数的中转站。白名单必须:
// · 无 auth 字段 ⇒ 不写字段(老配置保持"缺省 Bearer"语义,不能凭空插一个 auth)
// · 未知类型 ⇒ 丢弃(不能把拼错的类型写进配置)
// · header/query 的字段名要能存下来,否则 UI 填了也白填
eq(S.wShapeProviderFields({}), {}, "无 auth 时不写字段")
eq(S.wShapeProviderFields({ kind: 'openai', auth: { type: 'header', headerName: 'x-api-key' } }),
{ kind: 'openai', auth: { type: 'header', headerName: 'x-api-key' } }, '自定义 header 要保留')
eq(S.wShapeProviderFields({ auth: { type: 'query', queryName: 'tk' } }), { auth: { type: 'query', queryName: 'tk' } }, 'URL 参数名要保留')
eq(S.wShapeProviderFields({ auth: { type: 'nope' } }), {}, '未知鉴权类型丢弃')
eq(S.wShapeProviderFields({ auth: { type: 'NONE' } }), { auth: { type: 'none' } }, '类型大小写归一')
console.log('storage config shape checks passed(9 个纯函数的行为契约,含深合并与内置模型强制可见)')
+3
View File
@@ -34,6 +34,8 @@ interface Window {
IWBRuntimePluginLoader?: any
IWBRuntimePluginMarket?: any
IWBRuntimePluginBackup?: any
IWBImageFileRef?: any
IWBPluginApiImages?: any
IWBPluginData?: any
IWBPluginRuntime?: any
IWBDesktop?: any
@@ -62,6 +64,7 @@ interface Window {
IWBGenerationSizePolicy?: any
IWBGenerationState?: any
IWBGenerationTaskGraph?: any
IWBDefaultGenModel?: any
IWBGalleryHydration?: any
IWBGalleryQuery?: any
// 运行时