Compare commits

...
129 Commits
Author SHA1 Message Date
qiqi 1f833c5222 feat(ui): 工单#3 六项(连线默认灰/备份瘦身/下载统一+重名保护/主题迁入外观/图库插入尺寸档/输出下载走本地)v3.25.18
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 56s
2026-11-18 18:01:57 +08:00
qiqi f136601869 docs: 同步事实基线锚点(v3.25.17) 2026-11-18 17:24:44 +08:00
qiqi 3ecd07ef3c fix(icon): macOS 26 灰底(改不透明满幅源)+ 托盘换新 IW 挖空符号(v3.25.17)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 46s
2026-11-18 17:23:59 +08:00
qiqi 3eed42d43d docs: 同步事实基线锚点(v3.25.16) 2026-11-18 17:08:21 +08:00
qiqi dbbd558160 feat(icon): 更换应用图标为黑底圆角 + 白色 W(满幅 1024 源,mac/win 全套重生成)v3.25.16
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 58s
2026-11-18 17:07:39 +08:00
qiqi eec99144f3 chore(release): 3.25.15 Windows 包上线(三平台齐平,清单解耦生效)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 54s
2026-11-18 16:09:14 +08:00
qiqi 3a4ebc2eb3 docs: 更新 Windows 构建提示词到 v3.25.15(桌面客户端口径 + 16 条自测) 2026-11-18 15:41:02 +08:00
qiqi 84c2c10c0c docs: 同步事实基线锚点(v3.25.15) 2026-11-18 15:36:07 +08:00
qiqi cb6dcd1813 chore: 彻底转桌面客户端,删除网页版部署面(_headers/functions/wrangler + 相关 spec);更新清单平台解耦(v3.25.15)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m33s
2026-11-18 15:35:13 +08:00
qiqi 3fcc003738 test(csp): 桌面 CSP 守卫只断言桌面配置,不与网页 _headers 挂钩(本项目是桌面客户端)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m43s
2026-11-18 15:10:41 +08:00
qiqi 856e34a3f0 fix(csp): 桌面版重新放行 30092(修鲜艺抠图/批量导出)+ 门禁测试;feat(ui): 外观 tab(画布底色/主题色)(v3.25.14)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 10s
2026-11-18 14:56:23 +08:00
qiqi 1a0998b1d4 chore(release): 3.25.13 Windows 包上线(三平台齐平)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m27s
2026-11-18 13:48:35 +08:00
qiqi cf93080d17 fix(storage): 启动时补齐工作子目录(windows 全新安装缺 images/canvas → 写图失败;目录缺失也避免白屏)v3.25.13
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m25s
2026-11-18 13:42:09 +08:00
qiqi 1ffe067e12 fix(image): 写 blob 前确保 images/<cat> 目录存在(Windows 全新安装缺目录 → 写失败 → 退 Cache → 重启丢图);桌面端不再回退不持久的 Cache Storage(v3.25.12)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m53s
2026-11-18 13:34:27 +08:00
qiqi 58d8d9c43a chore(release): 3.25.11 Windows 包上线(三平台齐平)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 2m39s
2026-11-18 13:19:59 +08:00
qiqi 0e15e29c18 fix(desktop): 单实例 + 外链走系统浏览器 + 原生通知 + 窗口下限 + 按平台产物 + CSP 清理(v3.25.11)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m37s
2026-11-18 13:09:42 +08:00
qiqi d8c8717826 fix(image): 图片字节写不进磁盘的根因(blob 存储绑定未就绪运行时 + kv.put 裸 false 当成功)v3.25.10
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m29s
2026-11-18 12:50:44 +08:00
qiqi 9e400e2348 fix(image): 惰性绑定 ImageBlobStore(避免绑定到未就绪运行时)+ kv.put 失败返回对象(裸 false 会被当成成功,产出空引用) 2026-11-18 12:46:34 +08:00
qiqi 2f9a326159 chore(release): 3.25.9 Windows 包上线(三平台齐平)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m29s
2026-11-18 12:32:31 +08:00
qiqi 56b5f49646 fix(storage): 图片登记后立即落盘;GC 确认弹窗报出保留/断链数量(P0,v3.25.9)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m27s
2026-11-18 12:13:32 +08:00
qiqi 49b419251e fix(images): 拖入同图不再被去重拦掉(可重复添加);gcImages 计入画布引用,避免误删在用图片(v3.25.8)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m12s
2026-11-18 11:43:32 +08:00
qiqi 57fc63dc10 chore(release): 3.25.7 Windows 包上线(三平台 latest.json 齐备)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m30s
2026-11-18 09:46:16 +08:00
qiqi 36276455ea fix(clipboard): PNG 传输替代裸 RGBA;路径文本转图片;serde camelCase 修原生读图失效;节点组粘贴落点(v3.25.7)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m12s
2026-11-18 09:31:30 +08:00
qiqi 1afd5d7521 feat(paste): 库面板打开不再关闭也不拦粘贴;落点避开面板;同图允许重复粘贴(v3.25.6)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m11s
2026-11-18 07:36:28 +08:00
qiqi 22ecd268cf fix(clipboard): 库面板打开时不再拦掉粘贴(先关面板再落节点);更新对应单测(v3.25.5)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m6s
2026-11-18 07:26:36 +08:00
qiqi 0c39873a1a fix(clipboard): WKWebView 无 clipboard.write 时写纯文本摘要兜底,粘贴按摘要匹配回节点组;更新 74-4/74-8 断言语义(v3.25.4)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m6s
2026-11-18 07:14:57 +08:00
qiqi fa7c866457 chore(release): 3.25.3 Windows 包上线(三平台签名齐备,latest.json 含 windows-x86_64)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m6s
2026-11-18 06:37:42 +08:00
qiqi fc199776d9 chore(release): 加 publish-windows-update.sh(Windows 安装包本机重签名 + latest.json 合并)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m6s
2026-11-18 06:35:54 +08:00
qiqi 91ab3511ea chore(release): 3.25.3 剪贴板修复(应用菜单 + 原生图片读写)+ 站点/更新源
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m27s
2026-11-17 22:09:11 +08:00
qiqi 576d24f163 feat(clipboard): macOS 应用菜单 + 原生剪贴板图片读写(arboard),修复桌面端复制/粘贴图片、粘贴文本为节点失效
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 2m37s
2026-11-17 22:04:49 +08:00
qiqi 9283e76f1a chore(plugins): 同步标注插件 1.20.6(反白修正)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m46s
2026-11-17 21:05:26 +08:00
qiqi 13a34073bd chore(plugins): 同步标注插件 1.20.5(反白公式修正)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 3m11s
2026-11-17 20:53:11 +08:00
qiqi aff77cef75 chore(plugins): 同步标注插件 1.20.4
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 2m12s
2026-11-17 20:48:38 +08:00
qiqi ac62c3bfbc chore(plugins): 同步标注插件 1.20.3(快速效果兜底)+ 市场产物
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 3m38s
2026-11-17 20:37:57 +08:00
qiqi 8e0697d4cd style(site): 首屏白纱减淡(96%→86% / 94%→84%),让油画色彩多透出来
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 2m54s
2026-11-17 20:30:45 +08:00
qiqi 2fb9511f8b style(site): 去掉首屏下方重复的油彩色带,改为自然过渡到内容区
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m34s
2026-11-17 20:28:08 +08:00
qiqi fbdaf48377 feat(site): 首页主视觉换成油画(AI 生成),加白纱/颗粒/缓慢缩放/滚动入场/视差;资源加时间戳防缓存
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m56s
2026-11-17 20:24:22 +08:00
qiqi 99480bf9c5 feat(site): 新首页 + 下载页 + 插件页(统一导航/页脚,参考 open-design 风格)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m42s
2026-11-17 20:07:16 +08:00
qiqi 2ad699b64d docs(site): 下载页补 macOS 首次打开说明(未公证,右键打开或清 quarantine)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 2m0s
2026-11-17 19:51:29 +08:00
qiqi fabe8d7aa1 chore(release): 3.25.2 Windows 安装包上线(三平台齐发)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m21s
2026-11-17 18:13:25 +08:00
qiqi 2eacf5a81d chore(release): 3.25.2 下载页双架构 + latest.json 已上线
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m20s
2026-11-17 17:51:17 +08:00
qiqi fb20c97996 docs(facts): 基线锚点同步到 3.25.2
Verify (Gitea) / gate (build · unit · facts) (push) Canceled after 29s
2026-11-17 17:50:47 +08:00
qiqi 67a46dd03d feat(update): 接入 Tauri Updater(check_update/install_update + 签名产物 + latest.json 发布脚本)3.25.2 2026-11-17 17:47:05 +08:00
qiqi fe4a64f98b chore(plugins): 同步标注插件 1.20.2(指针自愈)+ 市场重建
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m38s
2026-11-17 17:24:21 +08:00
qiqi 78f8057384 chore(plugins): 同步标注插件 1.20.2(指针状态自愈)+ 市场产物重建
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m21s
2026-11-17 17:21:25 +08:00
qiqi ea5aa77b9c fix(plugins): 启动后对已启用插件补一次 activate(此前只注册不激活,开关显示开但插件没跑)+ 启动预热市场缓存
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m42s
2026-11-17 17:09:42 +08:00
qiqi f2c634ff38 fix(canvas): 没有上游样式节点的提示词/文本节点不再显示「已固定 / 恢复跟随」(避免误点清空手写文案)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m19s
2026-11-17 17:02:40 +08:00
qiqi 9623d932f7 feat(plugins): 关闭的插件从侧边导航消失;插件面板本地优先渲染 + 市场列表缓存(秒开)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m26s
2026-11-17 16:55:28 +08:00
qiqi b7eb9f8c28 fix(plugins): 读开关状态前先等待文件存储就绪 + 无记录不再强写启用;关闭状态跨重启保持
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m22s
2026-11-17 16:51:06 +08:00
qiqi 5dba56363a fix(plugins): 加载阶段不再写启用状态;启动时先快照用户开关再双向应用(关掉的插件重启后保持关闭)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m21s
2026-11-17 16:47:18 +08:00
qiqi d83f7f5eef fix(plugins): 启动一律加载脚本(注册≠启用),加载后按持久化状态激活;修「关闭后再也打不开/未加载」
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m22s
2026-11-17 16:43:49 +08:00
qiqi 9b24749481 fix(plugins): 未注册默认启用 + 开关直接加载 + 加载成功回写启用 + 全部启用;插件详情页改扁平行;市场请求双通道
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 3m49s
2026-11-17 16:39:26 +08:00
qiqi 371f114d69 fix(plugins): 未注册插件默认启用 + 开关直接加载(运行时启用)+ 加载成功自愈启用状态 + 全部启用按钮 + 市场请求双通道回退
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 35s
2026-11-17 16:34:16 +08:00
qiqi 06d8551107 style(llm): 渠道卡片去外框改分区+细分隔线,长说明移到悬停提示,模型改圆角胶囊
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m17s
2026-11-17 16:22:18 +08:00
qiqi 0bc49d4eab style(plugins): 市场卡片更紧凑(安装/移除移到右上角、缩小内边距与标签间距、去掉底部空档)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m12s
2026-11-17 16:19:44 +08:00
qiqi 39d7c9e086 style(plugins): 市场卡片等高对齐(徽章移到标题行、描述两行截断、按钮固定底部右侧)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 38s
2026-11-17 16:16:43 +08:00
qiqi 5aeb354043 feat(plugins): 管理页显示加载错误原因 + 「复制诊断」(清单/运行时状态/错误)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m13s
2026-11-17 16:13:25 +08:00
qiqi 9fa45ff7b0 fix(plugins): 设置行去边框盒子改细分隔线 + 市场页展示全部插件并支持 全部/已安装/未安装 筛选(标签筛选与搜索分离)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 2m33s
2026-11-17 16:09:41 +08:00
qiqi 1ac0877f30 feat(plugins): 插件设置拆成两页(管理页=横向列表+开关 / 市场页=卡片墙安装),对齐 Obsidian 交互
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m32s
2026-11-17 16:04:49 +08:00
qiqi 398500b952 feat(plugins): 设置内插件市场改成卡片墙(图标/标签/状态/安装按钮),与 market 页同一套视觉
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 2m38s
2026-11-17 15:59:08 +08:00
qiqi e2253e56c2 feat(market): 插件市场展示页(卡片墙 + 搜索 + 标签筛选),meta 补 icon/color/tags
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m55s
2026-11-17 15:55:55 +08:00
qiqi 67c6128d61 fix(site): 下载页 Intel 平台键改为 darwin-x86_64(对齐 releases.json / Tauri 平台名)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m22s
2026-11-17 15:48:09 +08:00
qiqi 3bd6b4d9ff chore(release): 3.25.1 补 Intel Mac 包(darwin-x86_64)
Verify (Gitea) / gate (build · unit · facts) (push) Canceled after 36s
2026-11-17 15:47:32 +08:00
qiqi 56a159486b docs(win): 固定本次 Windows 打包版本为 3.25.1 + 发布 3.25.1 mac 包(releases.json/下载页)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m49s
2026-11-17 15:43:02 +08:00
qiqi 4aa0e6affe docs(facts): 基线锚点同步到 3.25.1
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m34s
2026-11-17 15:38:41 +08:00
qiqi 3f2eb03fe3 chore(release): 3.25.1(性能与数据卫生优化) 2026-11-17 15:37:33 +08:00
qiqi 3bbf1ea85d perf(image): 图库清单去 base64(367KB→1.6KB,按 thumbHash 读文件)+ 画布显示缩略图 768px 落盘
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m36s
2026-11-17 15:36:20 +08:00
qiqi e9a6402373 chore(log): _boot.log 超过 256KB 只保留最后 64KB(窗口多屏恢复已有中心点校验,无需改)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 2m0s
2026-11-17 15:17:12 +08:00
qiqi ce575d2640 refactor(app): 插件加载/市场/备份抽成 src 模块(app.js 8880→8764 行);备份包含插件
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m31s
2026-11-17 15:14:46 +08:00
qiqi 0ec11bfca8 perf(storage): gcImages 递归子目录 + trash 30 天轮转(本机清出 20.2MB 未引用图片)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m58s
2026-11-17 15:08:23 +08:00
qiqi 942d4068ea chore(release): 3.25.0 发布(dmg + 下载页 + CHANGELOG)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 2m51s
2026-11-17 14:26:34 +08:00
qiqi 9d0e57c29e chore(release): 3.25.0(应用无内置插件 + 市场安装 + 页内确认) 2026-11-17 14:19:41 +08:00
qiqi 2e19d89df2 docs(win): 给打包 AI 的执行提示词(环境检查/构建/自测/交付格式/停止条件) 2026-11-17 14:17:02 +08:00
qiqi 4b5f14141b docs(win): Windows 出包手把手 + scripts/set-version.js(三处版本号统一)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m23s
2026-11-17 13:55:07 +08:00
qiqi 49b8cb3abd feat(plugins): P3 开发者模式(plugins/local/<id>/plugin.js 免签名加载)+ SDK 文档与示例插件
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m22s
2026-11-17 13:47:30 +08:00
qiqi 1008370733 fix(ui): 剩余 window.confirm 全部改为页内确认(画布/提示词/分组/节点任务/设置/诊断),桌面端不再阻塞 WebView
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m39s
2026-11-17 13:20:39 +08:00
qiqi dd15a7d45f fix(ui): 页内确认框替代阻塞式 window.confirm(设置/备份/诊断 6 处);打包前强制 lint(防未定义变量再溜进包)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m29s
2026-11-17 13:06:57 +08:00
qiqi a625faab17 feat(plugins): 应用不再内置插件(打包时剥离 dist/plugins),插件全部从市场安装到资料目录
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 48s
2026-11-17 12:50:48 +08:00
qiqi b433653944 style(plugins): 插件行改为标题行+右侧操作(省纵向空间),计数区分 已安装/市场/可安装
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 45s
2026-11-17 12:44:58 +08:00
qiqi 499d29a8a0 fix(plugins): 插件默认启用(recordOf 默认 enabled:true),修「装了插件但列表为空/不能用」
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 44s
2026-11-17 12:38:52 +08:00
qiqi 3aa8b77d2c fix(plugins): 补 DesktopPluginsTab 的 restart 状态(上一版误加到旧组件,点插件报 Can't find variable)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m19s
2026-11-17 12:33:25 +08:00
qiqi 6426b9db37 fix(plugins): 安装后不再用 window.confirm(原生弹窗会卡住 WebView),改为页内「立即重启」
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 43s
2026-11-17 12:13:34 +08:00
qiqi 6d2ccce1ba refactor(plugins): 桌面端插件页改为 Obsidian 式布局(搜索 + 已安装开关/设置 + 市场可安装),去掉遗留远程行
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m13s
2026-11-17 12:09:11 +08:00
qiqi 8d57c26fe5 feat(plugins): 内置同版本显示「内置已提供」而非重复安装
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m13s
2026-11-17 12:04:36 +08:00
qiqi 59b79d54a3 refactor(plugins): 市场列表与已装插件合并为一张表(启停/设置/安装更新同排),去掉重复区块
Verify (Gitea) / gate (build · unit · facts) (push) Canceled after 1m0s
2026-11-17 12:03:32 +08:00
qiqi 09d4284d81 fix(plugins): 市场请求改走原生 HTTP(绕开 WebView 的 CORS/代理限制)+ http 允许市场域名
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 45s
2026-11-17 11:58:09 +08:00
qiqi 51bc9c581a feat(plugins): P2 插件市场(market 索引生成 + 应用内安装/更新/卸载,sha256 校验写 plugins/)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m10s
2026-11-17 11:49:34 +08:00
qiqi c1b9328978 feat(plugins): 从插件源仓同步产物(幂等脚本)+ 桌面端标签改为「已加载」不再说远程
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m40s
2026-11-17 11:38:32 +08:00
qiqi 5da4f255d8 feat(plugins): P1 插件外置(<资料目录>/plugins 覆盖内置、sha256 校验、blob 注入、来源标签);CSP 放行 blob:
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m11s
2026-11-17 11:29:47 +08:00
qiqi 2626c663c3 feat(release): 一键发布脚本(构建 dmg → hash → 更新 releases.json → 生成页面 → 上传 NAS → 校验)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m24s
2026-11-17 11:21:40 +08:00
qiqi 10741accdb feat(release): 下载页生成器 + releases.json(无框线列表、版本号数据化、平台缺失置灰)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m10s
2026-11-17 11:14:59 +08:00
qiqi 8b834f915e fix(ci): 对齐上游事实守门(契约 key / 缩略图断言 / 架构文档计数 / 运行时依赖声明)
Verify (Gitea) / gate (build · unit · facts) (push) Successful in 1m14s
2026-11-17 10:56:27 +08:00
qiqi 6ea4ff6678 ci(gitea): 先 build 再 verify:ci(部分契约检查读 dist 产物) 2026-11-17 10:39:44 +08:00
qiqi f2f22249bb test(ratchet): app.js 上限 8700→8720(桌面版下载语义改动,理由见注释)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m20s
2026-11-17 10:36:38 +08:00
qiqi 3389bc4f17 test(guard): 桌面存储镜像层纳入棘轮(11→17),非 storage-* 模块仍禁止直调
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 51s
2026-11-17 10:34:50 +08:00
qiqi 7ba5b830f2 fix(types): 补 __IWB_UPDATE__ 声明
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 31s
2026-11-17 10:33:13 +08:00
qiqi 945fcf0dff fix(types): 补齐图库 item 字段与 __TAURI__ 声明,修复 CI 类型检查
Verify (Gitea) / gate (build · unit · facts) (push) Canceled after 7s
2026-11-17 10:33:04 +08:00
qiqi 888c6d3dfc fix(types): 补 IWBStorageFile / IWBDesktop 全局声明(修复 CI 类型检查)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 30s
2026-11-17 10:32:25 +08:00
qiqi 43fd803291 docs(site): 下载页首版(由发布脚本后续生成)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 26s
2026-11-17 10:31:00 +08:00
qiqi f443dc64d6 ci(gitea): 工作流改名避免与 GitHub 版同名冲突 2026-11-17 10:25:07 +08:00
qiqi 927b725373 ci(gitea): 增加 Gitea Actions 门禁(runs-on linux,NAS runner) 2026-11-17 10:23:57 +08:00
qiqi d0c3edf352 feat(settings): 通用页加「版本与更新」+ 在线更新方案文档(A/B/C 三方案与配置清单)
Verify Web / e2e (Playwright) (push) Skipped
Verify Web / gate (build · lint · unit · facts) (push) Canceled after 0s
2026-11-17 09:17:05 +08:00
qiqi b3a30c7ad7 fix(settings): 恢复被误删的 backfillOutputOriginals(点设置报 Can't find variable) 2026-11-17 09:12:33 +08:00
qiqi d0d2d9587c refactor(settings): 通用置顶;删除「图片保存」页(并入通用,去掉定时清理);设置面板少框线多留白 2026-11-17 09:09:10 +08:00
qiqi ade1bbfda7 docs: 记录桌面端存储改造的 10 个踩坑与铁律 + 存储改动检查清单 2026-11-17 09:00:12 +08:00
qiqi 857acd30d3 fix(settings): 下载目录授权不再覆盖 data-dir.txt(数据库目录显示/打开错位) 2026-11-17 08:57:37 +08:00
qiqi ada8916fd6 fix(storage): 从 WebView localStorage 一次性捞回被截断的画布(957→1337 节点,空画布归零) 2026-11-17 08:49:18 +08:00
qiqi 8725e65fcd fix(storage): 画布文件名少了 2 个字符导致键对不上(节点显示为空);加一次性文件名修复 2026-11-17 08:44:19 +08:00
qiqi b193dc38ff feat(settings): 目录设置重构(数据库/图片导出 + 切换/转移)+ 去掉并发与 Webhook + 分组间距 2026-11-17 08:40:58 +08:00
qiqi 88428ca5ff fix(gallery): 图库清单回填缩略图(修复「图片已丢失」) 2026-11-17 08:29:18 +08:00
qiqi 99f676f460 fix(storage): 图库清单改为 library/gallery/index.json;迁移改为先写后删 + 清单自愈重建 2026-11-17 07:48:44 +08:00
qiqi a0f88bf306 feat(storage): images 按来源分二级目录(canvas/gallery/thumbs/legacy)+ 下载改为按需落盘不弹窗 + 缩略图 512 2026-11-17 07:45:31 +08:00
qiqi 5025a70ff9 feat(storage): 资源库按分类单独成文件(library/prompts|groups|gallery.json) 2026-11-17 07:01:58 +08:00
qiqi b20dbc9ad7 fix(settings): 「打开数据目录」改为打开资料目录,文案不再提 localStorage/IndexedDB 2026-11-17 06:52:13 +08:00
qiqi 21a32c0fe3 feat(desktop): 每张画布单独成文件(canvases/<id>.json)+ 托盘左键直接唤出窗口 2026-11-17 06:45:59 +08:00
qiqi 2b8bcbb74c fix(desktop): 关闭浏览器专有兜底(SW 注册 / Cache 虚拟路径 / 5MB 告警 / 自动快照)+ 隐藏与失焦时强制刷盘 2026-11-17 06:38:27 +08:00
qiqi f0ee2c1c61 feat(storage): 清理未引用图片(移入 trash/,不直接删) 2026-11-16 22:23:10 +08:00
qiqi 586b5aaf9b feat(storage): 去内联 base64(阈值 3000)+ 首启目录向导 + 资料目录切换 2026-11-16 22:17:46 +08:00
qiqi 135589cd6f feat(storage): 资料目录落盘(data.json + images/ 内容寻址)+ IndexedDB 图片一次性迁移 2026-11-16 22:02:55 +08:00
qiqi eadd5f3d65 feat(desktop): 系统托盘 + 窗口记忆 + 主题跟随系统 + 数据目录入口;设置面板去浏览器语义(A/B/C 组改动) 2026-11-16 21:09:14 +08:00
qiqi 90c29920c0 fix(desktop): 画布尺寸改 ResizeObserver(放大窗口不再裁切)+ 新增默认下载文件夹设置 2026-11-16 20:34:21 +08:00
qiqi 8a5d846617 docs: 补本机实测记录(探针数据 + 未覆盖项) 2026-11-16 18:56:15 +08:00
qiqi 883cb11ba4 chore: 去掉移动端图标产物,桌面仓库只留桌面资源 2026-11-16 18:56:03 +08:00
qiqi cddbd1f8eb feat(tauri): 完成桌面端迁移(原生另存为 + plugin-http 取图 + 插件静态化 + 中文注释) 2026-11-16 18:52:30 +08:00
qiqi 4709ec05f2 docs: 补同步脚本行为说明与演练结论 2026-11-16 18:36:56 +08:00
qiqi 10da67fa1e fix(sync): --finish 改为前移主线(无共同祖先时 merge 不可用),并留回滚分支 2026-11-16 18:36:31 +08:00
qiqi 80a1e3b48c fix(sync): 变量后紧跟中文时用 定界(macOS bash 3.2 会把高位字节吞进变量名) 2026-11-16 18:35:55 +08:00
qiqi ed3234b277 docs: 记录上游基线/桌面侧差异清单 + scripts/sync-upstream.sh 同步脚本 2026-11-16 18:35:13 +08:00
qiqi 0138b4b534 feat(tauri): 增加 Tauri v2 壳层(dialog/fs/http 三插件,无自定义命令) 2026-11-16 18:33:06 +08:00
132 changed files with 30302 additions and 4120 deletions

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
name: Verify (Gitea)
# Gitea Actions(自托管 NAS runner)用的门禁:只跑构建/单测/事实守门,
# 与 GitHub 版 .github/workflows/verify.yml 等价,但用 runner 自有 node:22 镜像,不装 setup-node。
on:
push:
branches: [main]
paths-ignore:
- '**/*.md'
- 'docs/**'
- '.gitea/**'
workflow_dispatch:
concurrency:
group: verify-${{ github.ref }}
cancel-in-progress: true
jobs:
gate:
name: gate (build · unit · facts)
runs-on: linux
timeout-minutes: 20
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- run: node -v && npm -v
- run: npm ci
- run: npm run build
- run: npm run verify:ci
+8
View File
@@ -14,3 +14,11 @@ coverage/
# 其他 agent 的本地记忆目录(不入库)
.workbuddy/
# 桌面版本地构建缓存(sandbox 内 npm cache 只能落在仓库里)
.npm-cache/
.cargo-home/
release/
# 插件市场产物(由 scripts/gen-market.js 生成,发布时 scp 上传)
market/
+5
View File
@@ -0,0 +1,5 @@
{
"nodes": [],
"edges": [],
"groups": []
}
+3
View File
@@ -0,0 +1,3 @@
{
"activeCanvas": "Main"
}
+1
View File
@@ -0,0 +1 @@
d5f99457be773e1ababd4048814ac1c224f4f629
+1 -1
View File
@@ -447,7 +447,7 @@
| 拆 `app.js` 但不处理钉点 | 一次红几百条,无法定位问题 |
| 重排 529 个 tag | 代价大、收益小;已用 CHANGELOG 说明缓解 |
| 用 `c8` / `nyc` 量本仓覆盖率 | **实测不可用**:src 模块用 `window.eval()` 加载(无脚本名),V8 无从归属。见规则库 §13.42 |
| 删除生产 CSP 里的 `127.0.0.1:30092` | **不是残留**,是 2026-10-17 有意为「本地服务插件」做的安全边界调整(`CHANGELOG:226`、事实基线 §265-267) |
| 删除生产 CSP 里的 `127.0.0.1:30092` | **不是残留**,是 2026-10-17 有意为「本地服务插件」做的安全边界调整(`CHANGELOG:226`、事实基线 §265-267)。**桌面客户端的 CSP 以 `tauri.conf.json` 为准**(本项目是桌面客户端,`_headers` 属旧网页部署、不约束桌面);v3.25.11 误删导致插件挂,见 `tests/desktop-csp-loopback-test.js` |
---
+271
View File
@@ -14,6 +14,277 @@
> 3. 核验正式地址版本 → 之后才移动 `stable` / `stable-verified-<日期>` 标签、更新本 CHANGELOG、写 GitHub Release(`gh release create`)。
> 测试发现问题 → 改 → 再 `deploy:test`,正式环境不受影响。回滚点 `git reset --hard stable`。
## v3.25.18(2026-11-18)工单 #3:连线配色 / 备份瘦身 / 下载统一 / 图库插入尺寸档
### 修复与调整
- **连线默认改灰色**(工单 ①):`--iwb-edge` 默认取 `--iwb-border2`(亮暗自适应);主题色只用于按钮、
选中框、端口与「选中节点的上下游高亮连线」。外观应用时不再把连线强写成主题色。
- **备份页瘦身**(工单 ②):桌面版移除「清理本地数据」(它只清 localStorage,删不到资料目录,还会被启动自愈救回,
属误导功能)与「本地自动备份」区块(桌面数据在资料目录,localStorage 快照价值近零)。网页版行为不变。
- **下载语义统一**(工单 ③):开关改名为「自动下载」并重写说明;新增**重名保护**(同名自动加 -1/-2 后缀,
批量下载不再互相覆盖);文案明确设了目录 + 开启后所有下载入口都直接落盘。
- **主题选择迁入外观 tab**(工单 ④):通用页的「外观」子块与配色下拉迁到「设置 → 外观」作为第一项。
- **图库插入尺寸档**(工单 ⑤):图库顶部新增下拉(原图 / 2K / 1K / 0.5K,默认 1K,记忆上次选择),
插入画布时按档位等比压缩(`src/image-compress.js` 新增 `toMaxEdge`),避免把 4K 原图塞进画布。
- **输出节点下载走本地**(工单 ⑥):输出结果的单图「下载」改为从资料目录的本地归档取图(原图优先),
远端 URL 只作兜底;与图库下载、大图预览下载行为一致。
## v3.25.17(2026-11-18)图标细节:去掉系统灰底 + 新托盘符号
### 修复
- **macOS Dock/启动台的灰色底衬**:macOS 26 对「带透明圆角」的旧式 .icns 会把图形缩进到系统底衬里,
表现为黑图标外面套一圈浅灰。改为**不透明满幅**源图(黑底铺满整张 1024)后,系统直接把自己的圆角遮罩
套上去 ⇒ 图标变成纯黑到边,灰圈消失。
- **托盘图标换成新 IW 符号**:白底版的 IW 做**挖空**处理(圆角方块填充、W 镂空),符合 macOS 模板图规范
(纯黑 + alpha,系统自动明暗反转)。
### 说明
- `icon.icns` / 各尺寸 PNG 取自不透明满幅;`icon.ico` 仍取透明圆角版(Windows 侧圆角更好看)。
- 仅图标资源变更,无功能改动。
## v3.25.16(2026-11-18)更换应用图标
### 变更
- 应用图标换成新版(黑底圆角 + 白色 W),覆盖 macOS `.icns` / Windows `.ico` / 各尺寸 PNG 与 Store Logo。
- 图标源为 1024px,内容满幅(不留内边距);托盘图标(`tray-template.png`)保持不变。
- 随 `npx tauri icon` 一并清理了用不到的 `android/`、`ios/` 目录。
### 说明
- 仅图标变更,无功能改动;mac 已发布,Windows 包在下次构建时自带新图标。
## v3.25.15(2026-11-18)彻底转桌面客户端:删除网页版部署面
### 变更
- **删除网页版部署产物**:`_headers`、`functions/`(`api/img.js`、`plugins/[[path]].js`)、`wrangler.toml`,
以及只测它们的 `tests/iwb-csp-gate.spec.js`、`tests/iwb-functions-headers.spec.js`、`tests/functions-api-test.js`、`tests/iwb-v32-web-test.js`。
- **`scripts/serve-test.js` 退化为纯静态服务器**:不再解析 `_headers`、不再模拟 Pages Functions。
- **`app.js` 清除网页代理分支**:图床下载 ③ 兜底、缩略图兜底、预览派生 `viaUrl`、显示缩略图 4 处 `/api/img` 全部删除,桌面端只走原生 HTTP。
- **更新清单平台解耦**:`tauri.windows.conf.json` 的 updater 指向 `updates/latest-windows.json`;
`publish-windows-update.sh` 改写独立清单,mac 发版不再丢弃 Windows 条目。
- **README / docs/RELEASES.md** 改为桌面客户端口径。
### 说明
- Windows 客户端 **需要在 3.25.15 手动装一次**(旧版的 updater 仍指向 `latest.json`),之后自动更新走独立清单。
## v3.25.14(2026-11-18)桌面 CSP 回归修复(鲜艺抠图)+ 外观 tab
### 修复
- **桌面版 CSP 重新放行本地服务**:v3.25.11 的「CSP 清理」把 `http://127.0.0.1:30092` /
`http://localhost:30092` 当遗留端口删掉,但它是 2026-10-17 有意为「本地服务插件」放宽的边界。
后果:桌面版鲜艺抠图插件与批量导出的「走本地抠图」报 `Failed to fetch`,网页版正常(两份 CSP 互不相干)。
- **补门禁**:新增 `tests/desktop-csp-loopback-test.js`(运行时值断言,避开源码钉点棘轮),
钉住「桌面 CSP 必须放行 30092」与「两份 CSP 的 loopback 例外不得漂移」。
### 新增
- **设置 → 外观**:画布底色(亮/暗两套)+ 主题色(两套共用),取色器仿 Obsidian(SVH 方块 + 色相条 + RGB + 十六进制)。
连线、端口、主按钮、选中框、进度动画统一吃 `--iwb-brand`;连线单独 `--iwb-edge`。
实现落在 `src/ui-appearance.js`,`makeSave` 白名单已同步(否则保存即丢)。
## v3.25.13(2026-11-18)启动兜底:工作子目录缺失时自动补齐
### 修复
- 启动时 `ensureDirs()` 补齐 `canvases/`、`library/`、`plugins/`、`trash/` 与
`images/{canvas,gallery,thumbs,legacy}`(幂等)。
- 为什么需要:Windows 全新安装缺 `images/canvas` 导致写图失败;目录被手工删掉时
启动阶段读目录抛错会让首屏白屏(实测遇到过一次)。
### 验证
把 `images/` 与 `library/` 整个删掉再启动 → 目录全部自动重建、应用正常渲染。
## v3.25.12(2026-11-18)Windows 丢图根因:images/canvas 目录不存在
### 根因
Windows 全新安装的资料目录里 `images/` 只有 `thumbs/`(缩略图 writer 会自己 mkdir),
**没有 `canvas/` 与 `gallery/`**。`kv.put` 写 blob 前不建目录 ⇒ `writeFile` 失败 ⇒
blob 写入被判失败 ⇒ 退化到 Cache Storage(`{__cache}`)⇒ WebView2 重启后解析不到 ⇒ 图没了。
mac 上之所以正常:老数据里 `images/canvas` 早就被迁移脚本建好了。
### 修复
- `kv.put` 的 blob / dataURL 两条分支写盘前 `mkdir(images/<cat>, {recursive:true})`(幂等)。
- 桌面端**不再回退 Cache Storage**:失败就让调用方把字节内联进画布,宁可画布变大也不丢图。
### 验证
把 mac 上的 `images/canvas` 整个移走模拟全新安装 → 粘贴一张图:
修前:目录不重建、assets 不变;修后:目录自动重建、`assets 52→53`、目录里出现 1 个文件。
## v3.25.11(2026-11-18)桌面迁移体检:单实例 / 外链 / 原生通知 / 窗口下限
### 修复
- **单实例**:加 `tauri-plugin-single-instance`,第二次启动只聚焦已有窗口。
多实例同时写同一个资料目录会把 data.json 与 canvases 写成不一致状态(这两天查的图片丢失就是这类)。
- **外链不再把应用导航走**:捕获阶段拦截 `a[href^=http]`(含中键)+ `window.open` 兜底改走
`open_external_url` 命令,由系统浏览器打开(新模块 `src/ui-desktop-shell.js`)。
- **桌面原生通知**:WKWebView 不支持 Web Notification,出图完成提醒改走 `notify_desktop`。
- **窗口尺寸下限**:恢复几何时 clamp 到 1024×640(与 minWidth/minHeight 对齐);
实测过 1051×488 的窗口,该尺寸下画布渲染空白。
- **按平台产物**:新增 `tauri.macos.conf.json`(app+dmg)与 `tauri.windows.conf.json`(nsis),
Windows 不再顺带构建不受更新器支持的 msi。
- **CSP 清理**:移除遗留的开发端口(30092 / 3425)。
## v3.25.10(2026-11-18)图片粘贴后重启丢失:根因是 blob 存储绑定错运行时
### 修复
- **ImageBlobStore 惰性绑定**:原来在模块初始化时就 `create({ idb: IDB })`,那一刻资料目录尚未就绪,
绑到的是浏览器/空实现运行时 ⇒ 图片字节写进了不会落盘的地方,画布里只留 `{__blob}` 引用,
重启后解析不到 → 节点变占位图。现在按当前 runtime 懒绑定并按实例缓存。
- **kv.put 失败可识别**:资料目录未就绪时返回裸 `false`,调用方用 `r.ok === false` 判断,
`false.ok` 是 undefined ⇒ 被当成成功,产出指向空文件的引用。现在返回 `{ ok: false, error }`。
### 验证(实测)
- 修复前:粘贴一张图 → `assets` 47→47、`images/canvas` 26→26(字节没落盘)
- 修复后:粘贴一张图 → `assets` 47→48、`images/canvas` 26→27,节点为 `{__blob}`
- 重启应用后:同一节点仍在、图片正常显示
## v3.25.9(2026-11-18)P0:图片登记表不再落后于画布 + 清理前交代清楚
### 修复
- **登记表立即落盘**:图片写入 `images/` 后,`assets` 登记(在 data.json 里)原来是 800ms debounce,
进程被强杀/崩溃时登记丢掉、画布引用还在 ⇒ GC 会把在用图片当孤儿。现在登记后立刻 `flush()`。
- **清理确认弹窗报数**:除了「N 个未被引用」,还会显示「其中 M 张因画布引用自动保留」与
「另有 K 处引用已缺图」,避免用户在不了解后果的情况下按确认。
### 新增
- 单测 `tests/storage-gc-canvas-refs-test.js`:钉住「GC 必须扫画布引用并并入 used 集合」与「登记后必须 flush」。
## v3.25.8(2026-11-18)拖入同图被拦 + 图片节点变占位图
### 修复
- **拖入同一张图被去重拦掉**:命中旧节点后不写 blob、只选中它,于是「图片数据缺失 → 重新拖入」
这条唯一自愈路径被堵死。现在拖入一律新建节点并重写 blob,旧节点也会跟着恢复。
- **图片清理误删在用图片**:`gcImages` 只信 `assets` 登记表;登记表落后于画布时,
画布仍在引用的图片会被当孤儿挪进 trash/,节点随即变成占位图。现在把 `canvases/*.json`
里的 `{__blob}` 也计入在用集合。
## v3.25.7(2026-11-18)剪贴板体检:大图卡顿、路径误判、粘贴落点
### 修复
- **大图剪贴板卡顿**:原先 IPC 传裸 RGBA(12MP 照片 46MB → base64 62MB)。
改为传 PNG:读方向由 Rust 编码,写方向直接把 Blob 的 PNG 字节发过去,体积降到几 MB。
- **Finder「复制图片」被当成文本粘贴**:macOS 复制图片时常同时给 file:// 文本,
classify 会落进文本分支贴出「路径提示词节点」。现在路径样式的文本先问原生剪贴板要图片。
- **原生读图一直失效**:Rust 结构体字段是 `png_base64`,前端读的是 `pngBase64`,取不到值。
结构体加 `#[serde(rename_all = "camelCase")]`,前端两种写法都兼容。
- **节点组粘贴落点**:Ctrl+V 贴节点/节点组也走 `safeSeed`,面板打开时不会被遮住。
### 清理
- 删除已废弃的 `rejectDup` 与 `pasteCtx.closeLibrary`(粘贴不再关闭库面板)。
## v3.25.6(2026-11-18)粘贴语义修正:不关库面板、贴鼠标处、允许同图重复
### 变更
- 库面板(资源抽屉 / 资源中心)打开时**不再关闭它**,粘贴照常生效。
- 落点:指针在画布可见区 → 贴指针位置;指针压在面板上 → 自动挪到面板旁,不再出现「贴了但被遮住」。
- 同一张图**允许重复粘贴**(粘贴是显式动作,被同图去重挡掉像「按键没反应」)。
同图去重仍保留给拖拽/批量导入等被动路径。
## v3.25.5(2026-11-18)库面板打开时粘贴失效
### 修复
- 打开左侧资源抽屉 / 资源中心后,Ctrl+V 完全不响应:`overlayOpen()` 把库面板当成模态浮层,
在 paste 入口直接 return。
- 现在拆成两层判断:**真模态**(设置/帮助/右键菜单/连接菜单/放大编辑)仍不接管;
**库面板**改为「先关面板再粘贴」(`pasteCtx.closeLibrary`),落点可见、不再出现「贴了但看不见」。
- 库面板无法关闭时(老调用方)退回旧行为,不会静默吞掉粘贴。
- 快捷键兜底也补上模态判断,设置面板打开时不会偷贴图片。
## v3.25.4(2026-11-18)复制节点贴不回来:剪贴板兜底修复
### 修复
- **WKWebView 没有 `navigator.clipboard.write`** 时,`clipboard-graph.write()` 直接 return false,
等于什么都没写进系统剪贴板 → Ctrl+C 之后 Ctrl+V 只能贴出「剪贴板里没有可粘贴的内容」。
现在:写不了富文本就写**纯文本摘要**(navigator.writeText → 再退 Rust arboard),
同时记住「这份摘要属于哪个 clip」;粘贴时按摘要**精确匹配**,命中就贴回节点组。
- 新增 Rust 命令 `clipboard_write_text` / `clipboard_read_text`(arboard),Windows 同样可用。
### 验证
- 单测 `tests/clipboard-graph-fallback-test.js`:无 `clipboard.write` 场景下能写原生文本且能匹配回 clip。
## v3.25.3(2026-11-17)桌面端剪贴板修复:复制/粘贴图片、粘贴文本为节点
> **状态:✅ 已发布** macOS 双架构 + Windows。
### 修复
- **Cmd+C/Cmd+V 完全失效**:macOS 上 Tauri 应用没有应用菜单时,系统快捷键不会进入 WebView。
现在补上 `Menu::default`(撤销/剪切/复制/粘贴/全选),文本粘贴为节点恢复正常。
- **粘贴图片(Finder / 网页)**:WKWebView 的 paste 事件拿不到 Finder 复制的图片。
新增 Rust 命令 `clipboard_read_image`(arboard),paste 无图时主动读系统剪贴板;
另加 160ms 兜底:快捷键按下后没有 paste 事件也会尝试读图。
- **复制图片到系统剪贴板**:`navigator.clipboard.write` / `ClipboardItem` 在 WKWebView 常不可用,
新增 `clipboard_write_image` 原生兜底,预览复制与图库复制都走它。
### 新增模块
- `src/clipboard-native.js`:RGBA ⇄ PNG Blob 转换与原生剪贴板调用(网页版自动不可用)。
## v3.25.2(2026-11-17)在线更新上线:应用内「检查更新 → 立即更新 → 自动重启」
> **状态:✅ 已发布** 双架构签名产物 + `latest.json` 更新源。
### 新增
- **Tauri Updater 接入**:`tauri-plugin-updater` + `check_update`/`install_update` 两条 Rust 命令;
设置 → 通用 → 版本与更新 里可检查、下载、安装并自动重启。
- **签名发布**:`bundle.createUpdaterArtifacts` + minisign 密钥;`.app.tar.gz` 与 `.sig` 由
`scripts/publish-update.sh` 一键产出并上传,同时生成双平台 `latest.json`。
- **文档**:`docs/DESKTOP_UPDATE.md`(发布流程、密钥管理、故障排查)。
### 修复
- 标注插件 v1.20.2:丢失 `mouseup` 后自动收笔 + 失焦/指针取消复位,修「画一次后画布不响应」。
## v3.25.1(2026-11-17)性能与数据卫生:回收 20.2MB 垃圾图片 + 图库清单去 base64(223 倍)+ 备份含插件
> **状态:代码已合并** 分支 `main`。Windows 安装包基于本版本构建。
### 性能 / 体积
- **图库清单去 base64**:`library/gallery/index.json` 367,887 → **1,646 字节**(只留 `thumbHash`,缩略图按需从 `images/thumbs/` 读)。
- **画布显示缩略图落盘**:768px 派生结果写 `images/thumbs/<sha16>_768.jpg`,启动预读命中,省掉重复 4K 解码。
- **`gcImages` 递归子目录**:此前只扫 `images/` 根目录,`canvas/gallery/thumbs/legacy` 里的孤儿永远清不掉。本机首跑回收 **20.2 MB**(21 个无引用文件)。
- **`trash/` 30 天轮转**:清理只是移进 trash,现在超过 30 天自动删除。
### 数据卫生
- 清除 7 个坏画布文件(早期文件名少 2 字符的残留:`active.json` / `wsve.json` 等),画布 49 → 42(1341 节点完好)。
- `assets` ↔ 文件一致性校验:0 缺失。
### 备份 / 结构
- **备份包含插件**:导出带 `items.plugins`(清单 + 源码),恢复写回 `<资料目录>/plugins/` 并合并清单 —— 换机不再丢插件。
- **app.js 瘦身**:插件加载 / 市场 / 备份抽成 `src/runtime-plugin-loader.js`、`runtime-plugin-market.js`、`runtime-plugin-backup.js`。
- **`_boot.log` 轮转**:超过 256KB 只保留最后 64KB。
### 已验证
- `verify:ci` exit 0(658 通过 / 0 新增失败)
- 真实启动:5 个外部插件全部 `loaded`
- 图库 7/7 条目可解析到缩略图文件,清单 `data` 字段全空
## v3.25.0(2026-11-17)桌面版:应用不再内置插件 + 插件市场 + 页内确认(替代原生 confirm)
> **状态:✅ 已出 macOS 安装包(dmg)** 分支 `main`,bump 提交 `9d0e57c`。
> 说明:本版聚焦桌面端(Tauri)。Web 版行为不变。
### 变更
- **应用不再内置插件**:打包时剥离 `dist/plugins/`,插件全部从市场安装到 `<资料目录>/plugins/`(安装包 16.67 → 16.50 MB,包内已核实无 `plugin-*.js`)。
- **插件市场(P2)**:`market.maqiart.eu.org` 提供索引与产物;应用内可安装/更新/卸载,下载后校验 sha256 再写盘;已装清单以资料目录的 `plugins/index.json` 为准。
- **开发者模式(P3)**:`plugins/local/<id>/plugin.js` 免签名加载(仅开关打开时),配 SDK 文档与示例插件。
- **页内确认替代 `window.confirm`**:桌面端原生确认框会阻塞 WKWebView 主线程导致界面卡死;全部 20 处调用改为页内确认层(网页端仍用原生)。
- **插件默认启用**:`recordOf` 默认 `enabled: true`,修复“装了插件但列表为空/不可用”。
- **打包门禁**:`beforeBuildCommand` 增加 `npm run lint`,未定义变量等问题在出包前拦截。
- **下载页与发布脚本**:`download.maqiart.eu.org` 由 `scripts/gen-release-page.js` 从 `releases.json` 生成;`scripts/release.sh` 一键构建→算 hash→上传→校验。
- **设置面板重构**:通用置顶、目录/导出拆分、去掉并发与 Webhook、少框线;新增版本与更新区块。
### 修复
- 画布文件名少 2 字符导致键对不上(节点显示为空);从 WebView localStorage 一次性捞回 12 个画布(957 → 1337 节点)。
- 图库清单迁移“先删后写”丢失清单;改为先写后删 + 自愈重建 + 缩略图回填。
- 保存到下载目录被 fs scope 拦下;启动时补授权下载目录,且不再覆盖 `data-dir.txt`。
## v3.24.85(2026-11-16)代码体检收口:棘轮收回腾出 32 行余量 + 图库索引 4 条绕过锁的写路径收口 + 文档数字校准
> **状态:✅ 已发正式站(2026-11-16)** `v3.24.85+7df9dc4`(bump 提交 `4be78c0`、文档提交 `7df9dc4`)。
+2 -2
View File
@@ -22,7 +22,7 @@
|---|---|
| Node | **22**(CI 用 22,本地同版本最省事) |
| 安装 | `npm ci` |
| 运行时依赖 | **无**(`dependencies` 为空)—— 只有 devDependencies |
| 运行时依赖 | 桌面版有 3 个 Tauri 插件(`@tauri-apps/plugin-dialog` / `-fs` / `-http`);Web 版仍无运行时依赖 |
| 浏览器测试 | Playwright Chromium:`npx playwright install --with-deps chromium` |
---
@@ -41,7 +41,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 100 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
test:unit 101 个单测文件(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)
+133
View File
@@ -0,0 +1,133 @@
# 构建与打包(桌面版)
## 一、依赖
| 项 | 版本 | 说明 |
|---|---|---|
| Node.js | ≥ 20 | 前端构建(esbuild 逐文件压缩 + 拼接) |
| Rust | ≥ 1.90 | Tauri 后端;macOS 用默认 toolchain,Windows 必须 **MSVC** |
| Xcode CLT | — | 仅 macOS:`xcode-select --install` |
| VS Build Tools | 2019/2022 + 「使用 C++ 的桌面开发」 | 仅 Windows |
| WebView2 Runtime | — | Windows 10 需安装;Win11 自带 |
## 二、日常命令
```bash
npm ci # 首次
npm run build # 只出前端 dist/(含运行时插件)
npm run app:dev # 开发(启动前自动 build,改完源码需手动再 build)
npm run app:build # 打包当前平台(mac:.app + .dmg;Win:.exe + .msi)
```
首次 `app:build` 要编译 ~250 个 Rust crate,约 2–5 分钟;之后增量很快。
> 本机(沙箱)里 cargo/npm 的缓存目录被限制在仓库内,所以 build 时用
> `CARGO_HOME=$PWD/.cargo-home npm_config_cache=$PWD/.npm-cache`;
> 在你自己的机器上不需要,直接用默认缓存即可。
## 三、产物位置
| 平台 | 路径 |
|---|---|
| macOS | `src-tauri/target/release/bundle/macos/image-workbench.app` |
| macOS dmg | `src-tauri/target/release/bundle/dmg/image-workbench_3.24.85_*.dmg` |
| Windows msi | `src-tauri/target/release/bundle/msi/*.msi` |
| Windows exe(setup) | `src-tauri/target/release/bundle/nsis/*-setup.exe` |
## 四、Windows 打包(只能在 Windows 上做)
Tauri 不支持从 macOS 交叉编译 Windows 产物,必须在 Windows 机器上跑:
```powershell
# 1) 一次性环境(有 winget 的话)
winget install OpenJS.NodeJS.LTS
winget install Rustlang.Rustup
winget install Microsoft.VisualStudio.2022.BuildTools --override "--quiet --add Microsoft.VisualStudio.Workload.VCTools"
winget install Microsoft.EdgeWebView2Runtime
# 2) 确认 Rust 走的是 MSVC
rustup default stable-msvc
rustc -V
# 3) 构建
git clone <本仓库地址> image-workbench-desktop
cd image-workbench-desktop
npm ci
npm run app:build
```
产物在 `src-tauri\target\release\bundle\` 下的 `msi\` 与 `nsis` 目录。
常见坑:
- `link.exe not found` → VS Build Tools 没装「使用 C++ 的桌面开发」工作负载
- 中文路径 / 空格路径可能让 NSIS 失败 → 仓库放在 `C:\work\` 这类纯英文路径
- 没签名 → SmartScreen 会提示「未知发布者」,点「更多信息 → 仍要运行」
## 五、签名与分发(本次不做)
macOS 未签名:首次打开要 **右键 → 打开**(或在「系统设置 → 隐私与安全性」里放行)。
Windows 未签名:SmartScreen 提示,仅影响首次运行体验。
要正式分发再考虑 Apple Developer ID / Windows 代码签名证书,与本次迁移无关。
## 六、插件资源的来路
网页版插件由 Cloudflare KV 在 `/plugins/*` 提供;桌面版没有服务端,所以把
**发布产物**(`plugins/runtime/*.js`,文件名带内容哈希)随仓库带走,构建后由
`scripts/copy-plugins.js` 拷进 `dist/plugins/`。每个文件的 SHA-256 与
`plugins/index.json` 里的 `integrity` 一致(已校验)。
升级插件时:换掉 `plugins/runtime/` 里的文件 + 同步 `plugins/index.json` 即可,代码不用动。
## 七、本机实测记录(2026-11-16,macOS arm64)
构建产物:`image-workbench.app` 16.1 MB,已在 macOS 启动并渲染出完整界面。
在打包产物里注入一次性探针(用完即删,未进最终包)读到的运行时事实:
| 检查项 | 实测值 | 含义 |
|---|---|---|
| 页面 origin | `tauri://localhost` | 与网页版 `https://` 不同,所以 `/api/*` 这类同源后端全部不存在 |
| `window.__TAURI__` | 存在,keys 含 app/core/event/window… | withGlobalTauri 生效 |
| `dialog` / `fs` / `http` | true / true / true | 三个插件的前端 API 都挂上了 ⇒ 另存为链路可用 |
| `__TAURI_INTERNALS__.invoke` | true | IPC 通道正常(CSP 没拦) |
| `isSecureContext` | true | crypto.subtle、clipboard 这类安全上下文 API 不会降级 |
| `/plugins/index.json` | HTTP 200,1283 B | 插件静态化成功,桌面端有插件清单 |
| 插件 SRI 加载实测 | `blank-canvas` 加载 OK、已注册 yes | 用 `integrity` + `crossOrigin` 的真实注入方式验证通过 |
未能在本机自动验证的一项:**点「保存图片」弹系统另存为**。原因是要点开画布里的输出节点才能触发,
属于 GUI 交互,自动化会打断你当前桌面。这段逻辑本身已具备(三个 API 都在),请手工点一次确认。
## 八、桌面壳层新增能力(2026-11-16 后)
| 能力 | 行为 | 实现 |
|---|---|---|
| 系统托盘 | 菜单栏/托盘出现图标;点「关闭」不再退出,收进托盘,后台生图继续跑 | `src-tauri/src/lib.rs` 的 `build_tray` + `on_window_event`(`tray-icon` feature) |
| 托盘菜单 | 显示主窗口 / 隐藏到托盘 / 退出 | 同上(「退出」才真正结束进程) |
| 窗口记忆 | 退出或收进托盘时记住大小与位置,下次启动恢复;换过显示器则只恢复尺寸 | `window-geom.json` 存在 app config 目录 |
| 打开数据目录 | 设置 → 通用 → 「打开数据目录」 | 一个极简 Rust 命令 `open_app_data_dir`(不改任何权限) |
| 主题跟随系统 | 设置 → 通用 → 主题 → 「跟随系统」,系统切换实时生效 | `matchMedia('(prefers-color-scheme: dark)')` |
Rust 侧一共只有一个自定义命令(打开数据目录),其余全部是官方插件 + 框架能力,权限没有放宽。
## 九、回归状态
- `npm run test:unit`:全绿(含 architecture-boundary-guard 的冻结快照,已按规矩重生成)
- 桌面端桥统一走 `src/runtime-desktop-bridge.js`(src 不反向引用 app.js 的全局,边界守卫不报红)
## 十、资料目录(数据落盘)
```
~/Documents/ImageWorkbench/
├── data.json 所有 localStorage 键(设置/提示词/画布/分组/图库索引),原子写(.tmp → rename)
├── images/ 所有图片字节,内容寻址 images/<sha256前16>.<ext>,同图只存一份
├── migrated.flag 旧 IndexedDB 图片迁移完成标记
└── _boot.log 启动/迁移日志(排障用)
```
- 启动:`grant_dir` 重新授权目录 → 读 data.json 进内存 → 之后同步读写内存、800ms 防抖异步落盘
- 图片:`{__blob}` 引用指向 `images/`,不再有 base64(唯一残留是设置里的形状模板缩略图 ~8KB)
- 换机器:设置 → 通用 → 资料目录 → 切换… → 指到旧目录,窗口重载后即接管
- 注意:Tauri fs 默认禁止 dotfile,标记/锁文件不能用 `.xxx` 命名
+128
View File
@@ -0,0 +1,128 @@
# 桌面版(Tauri v2)与上游网页版的关系
本仓库是 **image-workbench-web 的独立 fork**:代码完整复制一份,长期独立维护,
不跟随上游自动更新,但**保留同步上游 bug 修复的能力**。
## 一、溯源(重要,别删)
| 项 | 值 |
|---|---|
| 上游仓库 | https://github.com/malongan/image-workbench-web |
| fork 基线 commit | `d5f9945` |
| fork 基线树哈希 | `72e37a2a2726569648a6b5e1ae5de37835b5258d` |
| 复制方式 | `git archive HEAD \| tar -x`(只含被 git 跟踪的文件,不含 .git/node_modules/dist) |
| 一致性验证 | 本仓库首个提交 `0c7850c` 的树哈希与上游 `d5f9945` **完全相同** ⇒ 复制零丢失、零改动 |
这两个哈希就是「同步」的锚点:第一个提交 = 上游原样,之后的提交 = 桌面侧差异。
## 二、桌面侧差异清单(同步时唯一需要人工关注的部分)
除 `src-tauri/`(纯新增,不会冲突)外,业务代码只改了这些地方:
| # | 文件 | 位置 | 改了什么 |
|---|---|---|---|
| P1 | `app.js` | 文件顶部 | 新增「桌面端适配层」:`wIsTauri()` / `wSaveBlobNative()` / `window.__IWB_SAVE_BLOB__` |
| P2 | `app.js` | 输出缩略图归档 | 桌面端用 `plugin-http` 取字节,替代 `/api/img` 代理 |
| P3 | `app.js` | `downloadUrl` 内 `downloadBlob` | 桌面端弹系统「另存为」,`fs.writeFile` 写 Uint8Array |
| P4 | `app.js` | `downloadUrl` 的 `data:`/`blob:` 分支 | 桌面端先取 Blob 再走原生保存(`<a download>` 在桌面无效) |
| P5 | `app.js` | `downloadUrl` 第③段代理兜底 | 桌面端换 `plugin-http` 直连 |
| P6 | `app.js` | 预览派生 `viaUrl` | 桌面端不拼代理地址,直连(失败则负缓存回退原图) |
| P7 | `app.js` | 显示缩略图 `img.src` | 桌面端直接用原地址 |
| P8 | `app.js` | `wDownloadBlob`(备份 zip 等) | 统一走 `__IWB_SAVE_BLOB__` |
| P9 | `app.js` | 运行诊断导出 | 同上 |
| P10 | `app.js` | 节点组导出 | 同上 |
| P11 | `src/runtime-workbench-logic.js` | 画布导出 `.iwb.json` | 同上 |
| P12 | `src/runtime-workbench-logic.js` | `startCanvasZoomAndSize` | **修 bug**:resize 监听绑在 `<div>` 上永不触发 ⇒ 改 ResizeObserver,画布随窗口/侧栏变化重算 |
| P13 | `app.js` + `src/ui-settings-sections.js` | 保存链路 / 通用设置 | 新增「默认下载文件夹」设置(仅桌面端渲染,网页版自动隐藏) |
| P14 | `src-tauri/src/lib.rs` | Rust 壳层 | 系统托盘(关闭=收进托盘)、窗口大小位置记忆、`open_app_data_dir` 一个极简命令 |
| P15 | `app.js` | 主题 | 增加「跟随系统」,系统外观切换实时生效 |
| P16 | `app.js` | 自动保存生成的图片 | 桌面端没有 File System Access API ⇒ 改为写入默认下载文件夹(plugin-http 取字节) |
| P17 | `app.js` + 设置面板 | 保存链路 | 「批量保存不再逐个弹框」(互斥:会话内授权失效时自动回退对话框) |
| P18 | 设置面板各页 | 文案 | 去掉浏览器语义(localStorage 5MB / CORS / KV / 标签页 / 刷新),桌面端显示对应真实含义 |
| P19 | 新增 `src/storage-file.js` | 存储底座 | 资料目录:data.json(全部 localStorage 键)+ images/<sha16>.<ext>(图片字节);启动装载 → 内存 → 异步原子落盘;IndexedDB 旧图片一次性迁移 |
| P20 | `src-tauri/src/lib.rs` | 命令 | `grant_dir`:把资料目录加进本次运行的 fs scope(fs 授权是会话级,重启由此补授权) |
| P21 | `app.js` | 保存阈值 | 内联图片阈值 16384 → 3000(>3KB 的 dataURL 一律转 `{__blob}` 引用);并加一次性迁移 `wMigrateInlineImages` |
| P22 | `src/storage-file.js` + 设置面板 | 目录管理 | 首启向导(默认目录 / 选已有目录)+ 设置里「资料目录 → 切换…」(切换前刷盘,之后重载窗口) |
新增的配套文件(都不碰业务逻辑):
| 路径 | 作用 |
|---|---|
| `src-tauri/` | 壳层:conf / capabilities / lib.rs(只注册 dialog、fs、http 三个官方插件,零自定义命令) |
| `plugins/runtime/*.js` | 7 个运行时插件的发布产物(从线上抓取,SHA-256 与 `plugins/index.json` 逐一校验通过) |
| `scripts/copy-plugins.js` | 构建后把插件拷进 `dist/plugins/`(网页版由 KV 提供,桌面端只能随包) |
| `scripts/sync-upstream.sh` + `.upstream-base` | 同步机制 |
| `package.json` | 加 `@tauri-apps/*` 依赖、`tauri`/`app:dev`/`app:build` 脚本,`build` 链上 copy-plugins |
**红线:除上表外不要再改业务代码。** 差异每多一处,以后同步冲突的概率就高一分。
## 三、日常怎么同步上游的 bug 修复
因为 fork 时没有带 git 历史(`git archive`),两边的提交历史**没有共同祖先**,
此时 `git merge upstream/main` 不可用(会被当成两棵无关的树硬拼,冲突满天飞)。
所以第一次用「差异重放」:把桌面侧差异做成补丁,贴到新的上游版本上。
**同步成功一次之后,本仓库就与上游共享历史了,之后可以直接 `git merge upstream/main`。**
```bash
# 0) 一次性:确认 upstream remote 指向上游(也可以指向飞牛 Gitea 的镜像)
git remote add upstream https://github.com/malongan/image-workbench-web.git
# 1) 先看上游有什么新东西(只读,不改任何文件)
./scripts/sync-upstream.sh
# 2) 真同步:自动开 sync/<日期> 分支,把桌面侧差异贴到最新上游上
./scripts/sync-upstream.sh --apply
# 3) 看结果;有冲突就手工改(冲突只会出现在上表那几个位置)
git diff # 核对上游修复是否进来、桌面改动是否还在
git status
# 4) 确认无误:并入 main,并把基线前移(下次只差增量)
./scripts/sync-upstream.sh --finish
```
脚本行为说明:
- `--apply` 会新建 `sync/<日期>` 分支,**不动 main**,可以反复试。
- `--finish` 把 main 前移到这个分支,并自动留下回滚点 `backup/pre-sync-<日期>`。
- `--finish` 之后 `upstream-base` 指向上游那个 commit,所以 `git diff upstream-base..HEAD` 永远只剩桌面侧改动。
- 有冲突时脚本不会硬来:留冲突标记 + 列出文件,人工改完再 `--finish`。
- 演练证据(2026-11-16):模拟上游两次 bugfix,一次走脚本、一次走原生 `git merge`,
上游修复都进来了,`src-tauri/` 与 package.json 改动都保留,零冲突。
同步后的验证要点:
```bash
git log --oneline upstream-base..HEAD # 应只剩桌面侧提交
npm run build && npm run test:unit # 业务回归
npm run tauri dev # 另存为功能回归
```
## 四、也可以走「只拿某几个提交」的路子
上游某个 bug 修复很急、但整体版本不想跟:
```bash
git fetch upstream main
git log --oneline upstream/main -- app.js | head # 找到那条修复
git cherry-pick <sha> # 会失败:无共同祖先时 cherry-pick 也依赖 base
# ⇒ 更可靠的做法:手工看 `git show <sha> -- app.js` 的内容,照抄那几行
```
结论:**按文件抄单点修复永远可行**(这正是保留上游 remote 的意义);
整版本升级走上面的 `sync-upstream.sh`。
## 五、如果哪天想彻底断开
删掉 `upstream` remote、`upstream-base` tag、`.upstream-base` 文件、`scripts/sync-upstream.sh` 即可,
仓库本身不会因此坏掉——它已经是一份完整、可独立构建的源码。
## 六、桌面版与网页版的已知行为差异
| 项 | 网页版 | 桌面版 |
|---|---|---|
| 保存图片 | `<a download>` 落到浏览器下载目录 | 弹系统「另存为」对话框,用户选路径 |
| 批量下载 | 连续 N 个文件静默落盘 | 连续弹 N 次另存为对话框 |
| 跨域图床取图 | 走服务端 `/api/img` 同源代理 | 走 `plugin-http`(Rust 侧请求,不受 CORS 限制) |
| 运行时插件 | 从 `/plugins/*` 拉取(KV 托管) | 同上,需本地静态化或后续另做方案 |
| Service Worker / PWA | 有 | 无(不注册) |
| 数据存储 | 浏览器 localStorage + IndexedDB | 桌面端独立空库,可用备份 zip 导入 |
+13 -19
View File
@@ -1,9 +1,6 @@
# 🎨 生图工作台 Web 版(Cloudflare Pages 免费部署)
# 🎨 生图工作台(桌面客户端)
**在线访问:https://iwb.maqiart.eu.org**(自定义域名,Cloudflare 免费 HTTPS)
基于 **OpenAI 兼容生图 API** 的节点式图形化生图工作台,纯前端实现(Cloudflare Pages 免费托管)。
基于 **OpenAI 兼容生图 API** 的节点式图形化生图工作台。**Tauri v2 桌面客户端**(macOS / Windows),数据全部落在本机资料目录。
- **零后端**:数据保存在浏览器(localStorage + IndexedDB),图片生成直连兼容 API;Tuzi 生图固定使用 generations、要求 URL 响应,参考图允许公网 URL 与本地 Base64,且不自动重试
- 与独立版功能一致:无限画布、节点连线、文生图/图生图、参数设置(比例/分辨率对齐接口)、提示词库、节点组收藏、图库、右键菜单、双击聚焦/适应视图、标注节点等
@@ -13,7 +10,7 @@
- 稳定性边界:保存失败会保留恢复快照并支持重试,离页前执行本地兜底;启动时检查 localStorage/IndexedDB 可用性并显示异常。
- 构建:`npm run build` 用 **esbuild 压缩打包**(单 `dist/app.js` = `src/` 模块按序拼接 + `app.js`,另有压缩 `style.css`;`dist/` 不再有 `src/`),并生成带 Git commit 元数据的 `dist/version.json`。
- 测试:`npm test` 运行 jsdom 契约测试,`npm run test:e2e` 构建后启动本地静态服务器并运行 Playwright Chromium 测试;`npm run verify` 执行完整验证。
- 发布:`npm run deploy` 仅在完整验证通过后,将 `dist/` 上传到 Cloudflare Pages。
- 发布:`./scripts/publish-update.sh <版本>` 构建 macOS 双架构并写更新清单;Windows 用 `./scripts/publish-windows-update.sh <setup.exe>` 重签并写独立清单(`latest-windows.json`)。
## 第三方许可
@@ -29,27 +26,24 @@
**想知道「这个项目还有什么待办」** → [`BACKLOG.md`](BACKLOG.md)(唯一入口:优先级 + 证据链接 + 明确不做的项)。
## 部署到 Cloudflare Pages(免费)
## 构建与发布(桌面客户端)
### 本地手动发布(本仓库方式)
> 已从网页版迁移为桌面客户端,**不再部署 Cloudflare Pages**(`_headers` / `functions/` / `wrangler.toml` 已删除)。
```bash
npm ci
npm run deploy # 正式站(--branch main)
npm run deploy:test # 测试站(--branch test)
npm run build # 前端产物 dist/(esbuild 压缩)
npx tauri build # 桌面安装包(macOS: .app + dmg / Windows: nsis)
```
`npm run deploy` 会先跑完整 `verify`,通过后再把 `dist/` 上传到 Cloudflare Pages。
| 平台 | 命令 | 产物 |
| --- | --- | --- |
| macOS | `./scripts/publish-update.sh <版本>` | `updates/latest.json` + 双架构 dmg / app.tar.gz |
| Windows | `./scripts/publish-windows-update.sh <setup.exe>` | `updates/latest-windows.json`(平台独立) |
### CI(只验证,不部署)
两个平台的更新清单**完全解耦**:mac 发版不影响 Windows 版本号,反之亦然。
`.github/workflows/verify.yml` 在**推送到 `main` 与向 `main` 开 PR** 时执行验证门禁,分两个 job:`gate`(`npm ci` + `npm run verify:ci` = 构建 + 校验 + lint + 单测 + 事实守卫)与 `e2e`(Playwright + `npm run test:e2e`),**不自动部署**。
发布配置位于 `wrangler.toml`,Cloudflare Pages 输出目录固定为 `dist/`。部署前生成的 `version.json` 可用于确认线上版本和 Git commit。
### 绑定自定义域名(可选)
Pages 项目 → **Custom domains** → 添加域名(免费 HTTPS 自动签发)。
CI:`.github/workflows/verify.yml` 在推送 `main` 与向 `main` 开 PR 时执行 `npm run verify:ci`。
## 使用前配置
-9
View File
@@ -1,9 +0,0 @@
/*
X-Content-Type-Options: nosniff
Referrer-Policy: no-referrer
Permissions-Policy: camera=(), microphone=(), geolocation=()
Content-Security-Policy: default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' https: data: blob:; connect-src 'self' https: http://127.0.0.1:30092 http://localhost:30092 http://127.0.0.1:3425 http://localhost:3425; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
/sw.js
Cache-Control: no-cache, no-store, must-revalidate
Service-Worker-Allowed: /
+499 -84
View File
@@ -2,17 +2,160 @@
* 依赖: vendor/react + vendor/react-dom(离线 UMD)
* 后端 API: /api/config /api/generate /api/graph /api/prompts /api/outputs
*/
(function () {
(async function () {
'use strict'
// 桌面端:启动时先把「资料目录」读进内存(异步),之后所有同步存储调用都走内存 + 异步落盘。
// 网页版没有 IWBStorageFile ⇒ 这段整体跳过,行为与原来完全一致。
try {
if (typeof window !== 'undefined' && window.IWBStorageFile && window.IWBStorageFile.enabled()) {
await window.IWBStorageFile.ready()
}
} catch (e) { console.error('[iwb][file-store] 启动装载失败,回退浏览器存储', e) }
const el = React.createElement
const { useState, useEffect, useLayoutEffect, useRef } = React
// 生成结果精简/合并模块(src/generation-results-store.js)。⚠️ 必须在 IIFE 最顶部取:
// 页面加载时就会跑一次保存,声明若在后面会命中 TDZ(异常被 catch 吞掉 ⇒ 落盘退回未精简的 result)。
const GenerationResults = (typeof window !== 'undefined' && window.IWBGenerationResults) || null
// ========== 桌面端(Tauri v2)适配层 ==========
// 仅在 Tauri 内生效:网页版没有 window.__TAURI__ ⇒ 所有分支都走原逻辑,行为零变化。
// 用 withGlobalTauri 注入的官方 API(无需打包器),权限仍由 src-tauri/capabilities 约束。
const wTauri = (typeof window !== 'undefined' && window.__TAURI__) ? window.__TAURI__ : null
const wIsTauri = () => !!(wTauri && wTauri.core)
// ── 默认下载文件夹(桌面端专属设置,存本地;网页版没有这个概念)─────────────
const wDownloadDir = () => {
try { const v = lsGet('iwb.downloadDir', ''); return typeof v === 'string' ? v : '' } catch (e) { return '' }
}
const wSetDownloadDir = (dir) => { try { lsSet('iwb.downloadDir', String(dir || '')) } catch (e) { /* ignore */ } }
// 让用户选一个目录(dialog.open 的 directory 模式;未设置时另存为跟随系统记忆)
const wPickDownloadDir = async () => {
const openDlg = wTauri && wTauri.dialog && wTauri.dialog.open
if (!openDlg) throw new Error('Tauri 对话框不可用')
const dir = await openDlg({ directory: true, multiple: false, title: '选择默认下载文件夹' })
if (!dir) return ''
wSetDownloadDir(dir)
return dir
}
// 拼出「另存为」的初始路径:有默认目录就用目录+文件名,没有就只给文件名
const wDefaultSavePath = async (fileName) => {
const dir = wDownloadDir()
if (!dir) return fileName
const join = wTauri && wTauri.path && wTauri.path.join
try {
if (join) return await join(dir, fileName)
return dir.replace(/[\\/]+$/, '') + '/' + fileName
} catch (e) { return fileName }
}
// 「保存时不再逐个询问」:勾选后,已设默认下载文件夹的情况下直接写盘(批量导出不再弹 N 次框)
// 桌面端默认「点下载 = 直接写进下载目录,不弹窗」;只有写失败(目录被删/无权限)才退回对话框
const wSilentSave = () => { try { const v = lsGet('iwb.silentSave', true); return v !== false } catch (e) { return true } }
const wSetSilentSave = (v) => { try { lsSet('iwb.silentSave', !!v) } catch (e) { /* ignore */ } }
// 把 Blob 写进指定目录(不弹框)。目录必须此前由 dialog 选过:tauri-plugin-dialog 会把该目录
// 递归加进 fs scope;scope 是「本次运行」的,重启后首次写入会失败 ⇒ 调用方回退到对话框。
const wWriteBlobToDir = async (dir, name, blob) => {
const join = wTauri && wTauri.path && wTauri.path.join
let finalName = name // 重名保护见 src/image-format.js 的 uniqueName(v3.25.18)
try {
const U = (typeof window !== 'undefined' && window.IWBImageFormat && window.IWBImageFormat.uniqueName) ? window.IWBImageFormat.uniqueName : null
if (U) finalName = await U(dir, name, join, wTauri && wTauri.fs && wTauri.fs.exists)
} catch (e) { /* 探测失败按原名写 */ }
const target = join ? await join(dir, finalName) : (dir.replace(/[\\/]+$/, '') + '/' + finalName)
await wTauri.fs.writeFile(target, new Uint8Array(await blob.arrayBuffer()))
return true
}
// 桌面端自动保存生成图:写默认下载文件夹,取字节走 plugin-http(不受图床 CORS 限制),失败只返回 false
const wSaveGenImageToDir = async (item) => {
try {
const dir = wDownloadDir()
if (!dir || !item || !item.url) return false
const resp = await wTauri.http.fetch(item.url)
if (!resp || !resp.ok) return false
const blob = await resp.blob()
const base = wSanitizeFileName(item.name || ('gen_' + Date.now()))
const name = (ImageFormat && ImageFormat.fileNameFor) ? ImageFormat.fileNameFor(item.url, base, blob.type) : base
return await wWriteBlobToDir(dir, name, blob)
} catch (e) { return false }
}
// 设置里的「打开数据目录」(走一个极小的 Rust 命令,见 src-tauri/src/lib.rs)
const wOpenDataDir = async () => {
const invoke = wTauri && wTauri.core && wTauri.core.invoke
if (!invoke) throw new Error('Tauri 不可用')
return await invoke('open_app_data_dir')
}
// 桌面端保存二进制:弹系统「另存为」→ fs 直接写 Uint8Array。
// 刻意不经 base64:Blob → arrayBuffer → Uint8Array,省掉一次全量编码/解码。
const wSaveBlobNative = async (blob, name, title) => {
const save = wTauri && wTauri.dialog && wTauri.dialog.save
const writeFile = wTauri && wTauri.fs && wTauri.fs.writeFile
if (!save || !writeFile) throw new Error('Tauri 保存接口不可用(检查 dialog/fs 插件是否初始化)')
const fileName = String(name || 'image.png')
const ext = (fileName.split('.').pop() || 'png').toLowerCase()
// 路径来自 save() 的返回值:tauri-plugin-dialog 会把该路径动态加入 fs scope,
// 因此 capabilities 里不需要静态放开任何目录(不放开 $HOME 这类宽权限)。
// 「不再逐个询问」:设了默认目录就直接落盘;写失败(如重启后授权失效)自动退回对话框
if (wSilentSave() && wDownloadDir()) {
try { await wWriteBlobToDir(wDownloadDir(), fileName, blob); return true } catch (e) { /* 回退对话框 */ }
}
// 初始路径 = 默认下载文件夹 + 文件名(没设置则只给文件名,跟随系统上次位置)
const defaultPath = await wDefaultSavePath(fileName)
const path = await save({ title: title || '保存', defaultPath, filters: [{ name: ext.toUpperCase() + ' 文件', extensions: [ext] }] })
if (!path) return false
await writeFile(path, new Uint8Array(await blob.arrayBuffer()))
return true
}
// 统一保存出口:桌面端交系统另存为,网页端沿用 <a download>。
// 挂到 window 供 IIFE 深处的导出/诊断/备份复用,避免到处写分支。
const wSaveBlob = (blob, name) => {
if (wIsTauri()) return wSaveBlobNative(blob, name).catch((e) => { console.error('[iwb][tauri] 保存失败', e) })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url; a.download = name
document.body.appendChild(a); a.click(); a.remove()
setTimeout(() => URL.revokeObjectURL(url), 5000)
}
// 把桌面端能力登记到 src/desktop-bridge.js(src 不得反向引用 app.js 的 window 全局,
// architecture-boundary-guard 会红;这里只做注入,设置面板/导出逻辑统一走 IWBDesktop)
// 桌面端统一确认入口:页内确认(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 */ }
if (typeof window !== 'undefined' && window.IWBDesktop && window.IWBDesktop.configure) {
window.IWBDesktop.configure({
isTauri: wIsTauri,
saveBlob: wSaveBlob,
getDownloadDir: wDownloadDir,
setDownloadDir: wSetDownloadDir,
pickDownloadDir: wPickDownloadDir,
getSilentSave: wSilentSave,
setSilentSave: wSetSilentSave,
openDataDir: wOpenDataDir,
marketList: wMarketList,
marketInstalled: wMarketInstalled,
marketInstall: wMarketInstall,
marketUninstall: wMarketUninstall,
clipboardReadImage: (window.IWBNativeClipboard || {}).readImage,
clipboardWriteImage: (window.IWBNativeClipboard || {}).writeImage,
})
}
// ========== 浏览器本地模式(Cloudflare Pages 免费版)==========
// 数据层:localStorage + IndexedDB;网络层:直连兼容 API(CORS 已验证允许)
function storageRuntime() { return typeof window !== 'undefined' && window.IWBStorageRuntime }
// 桌面端(资料目录)是否生效:一堆"浏览器专有"的兜底要按它关掉
function wFileStoreOn() {
try { const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null; return !!(F && F.enabled && F.enabled()) } catch (e) { return false }
}
function storageRuntime() {
if (typeof window === 'undefined') return false
// 桌面端:资料目录就绪后一律走文件底座(内存表 + 异步落盘);否则用原来的 localStorage 实现
const fileStore = window.IWBStorageFile
if (fileStore && fileStore.enabled && fileStore.enabled()) return fileStore.runtime
return window.IWBStorageRuntime
}
function lsGet(k, fb) {
const runtime = storageRuntime()
if (runtime) return runtime.get(k, fb)
@@ -77,7 +220,7 @@
// 统一的本地存储适配器:业务层不直接依赖 JSON 序列化细节。
const SchemaVersions = Object.assign({ workspace: 1, canvas: 1, backup: 2, groups: 1 }, StorageContract.schema || {})
const ModularLocalStore = typeof window !== 'undefined' && window.IWBStorageLocal && typeof window.IWBStorageLocal.create === 'function'
? window.IWBStorageLocal.create({ storage: window.localStorage })
? window.IWBStorageLocal.create({ storage: (typeof window !== 'undefined' && window.IWBStorageFile && window.IWBStorageFile.enabled()) ? window.IWBStorageFile.storage() : window.localStorage })
: null
const unwrapStorageResult = (value, fallback) => value && value.ok === false ? fallback : (value && value.ok === true && Object.prototype.hasOwnProperty.call(value, 'value') ? value.value : value)
const LocalStore = {
@@ -124,7 +267,7 @@
if (typeof state !== 'object' || state === null) return state
const bytes = Number(state.bytes) || 0
// localStorage ~5MB;接近 80% 即预警,避免「画布未保存、空间不足」忽然出现
if (bytes > 4 * 1024 * 1024) {
if (!wFileStoreOn() && bytes > 4 * 1024 * 1024) {
const issues = Array.isArray(state.issues) ? state.issues.slice() : []
issues.push(iwError('storage', '本地存储空间将满(localStorage 已用 ' + fmtStorage(bytes) + ' / 约5MB),建议导出备份后清理图库/不用的画布'))
return Object.assign({}, state, { issues })
@@ -143,7 +286,7 @@
if (typeof indexedDB !== 'undefined') out.indexedDB = true
else out.issues.push(iwError('storage', 'IndexedDB 不可用'))
out.ok = out.localStorage && out.indexedDB
if (out.bytes > 4 * 1024 * 1024) out.issues.push(iwError('storage', '本地存储空间将满(localStorage 已用 ' + fmtStorage(out.bytes) + ' / 约5MB),建议导出备份后清理图库/不用的画布'))
if (!wFileStoreOn() && out.bytes > 4 * 1024 * 1024) out.issues.push(iwError('storage', '本地存储空间将满(localStorage 已用 ' + fmtStorage(out.bytes) + ' / 约5MB),建议导出备份后清理图库/不用的画布'))
return out
}
// localStorage 当前占用字节(UTF-16 计,用于设置页展示;不含 IndexedDB)
@@ -182,11 +325,14 @@
// 浏览器总通知:权限只在用户点击生图后的首次运行时请求;不支持/拒绝权限时静默降级。
let browserNotificationPermissionPromise = null
function prepareBrowserNotifications() {
if (wIsTauri()) return // 桌面端用原生通知,不需要网页权限
const N = typeof window !== 'undefined' && window.Notification
if (!N || typeof N.requestPermission !== 'function' || N.permission !== 'default' || browserNotificationPermissionPromise) return
try { browserNotificationPermissionPromise = N.requestPermission().catch(() => 'denied') } catch (e) { browserNotificationPermissionPromise = Promise.resolve('denied') }
}
function notifyBrowserGenerationDone(info) {
// 桌面端没有 Web Notification:交给桌面壳模块发原生通知
try { if (window.IWBUIShell && window.IWBUIShell.notifyGenerationDone(info)) return } catch (e) { /* ignore */ }
const N = typeof window !== 'undefined' && window.Notification
if (!N) return
const emit = () => {
@@ -239,7 +385,9 @@
compression: { enabled: true, maxMB: 8, maxEdge: 2048, quality: 0.9, format: 'keep' },
}
const W_DEF_RETENTION = { enabled: true, maxFiles: 500, maxDays: 15 }
const W_DEF_CANVAS = { generationConcurrency: 4, taskStallEndMs: 300000, autoSaveImages: true, backupOriginals: true }
// 默认外观在 src/ui-appearance.js(DEFAULTS);这里只放引用,避免两处默认值漂移
const W_DEF_APPEARANCE = (window.IWBUIApearance && window.IWBUIApearance.DEFAULTS) || { canvasBgLight: '#d9dbde', canvasBgDark: '#6f6f6f', accent: '#6b7280' }
const W_DEF_CANVAS = { generationConcurrency: 4, taskStallEndMs: 300000, autoSaveImages: true, backupOriginals: true, appearance: W_DEF_APPEARANCE }
// 任务条「结束」按钮出现的阈值:默认 5 分钟。判据是「该任务距上一次进展的时长」,
// 而不是任务总时长 —— 多个变体(如 3 张)正常跑 6 分钟也不会误报"卡住"。
const TASK_STALL_END_MIN = 60000
@@ -682,16 +830,28 @@
// objectURL **单一归属**:一律由 wRegisterBlobUrl 创建并登记(拿得回原 Blob,绕开 CSP 对 fetch(blob:) 的拦截),
// 由 wImgUrlByRef 台账回收;**不调用** ImageBlobStore.resolveUrl/revokeAll —— 否则同一张图会有两套 URL
// 与两套回收时机(§8.2「不要两套并用」)。实例只在顶层创建一次,绝不在渲染路径里重复 create。
const ImageBlobStore = (function () {
/* v3.25.10:**惰性绑定**运行时。
* 原来在模块初始化时就 create({ idb: IDB }):那一刻资料目录可能还没就绪,
* IDB 拿到的是浏览器/空实现运行时,于是图片字节写进了「不会落盘」的地方 ——
* 画布里留下 {__blob} 引用,images/ 里没有文件、data.json 里没有登记;
* 重启后引用解析不到 → 图片节点变占位图(用户实测)。现在按当前 runtime 懒绑定并按实例缓存。 */
let wImageBlobStoreCache = null
let wImageBlobStoreRuntime = null
function wImageBlobStore() {
try {
if (typeof window === 'undefined') return null
const Lib = window.IWBImageBlobStore
if (!Lib || typeof Lib.create !== 'function') return null
if (!IDB || typeof IDB.put !== 'function' || typeof IDB.get !== 'function') return null
return Lib.create({ idb: IDB })
const rt = storageRuntime()
const idb = rt && rt.indexedDb
if (!idb || typeof idb.put !== 'function') return null
if (wImageBlobStoreCache && wImageBlobStoreRuntime === idb) return wImageBlobStoreCache
wImageBlobStoreCache = Lib.create({ idb: idb })
wImageBlobStoreRuntime = idb
return wImageBlobStoreCache
} catch (e) { return null }
})()
const IMG_BLOB_PREFIX = (ImageBlobStore && ImageBlobStore.PREFIX) ? String(ImageBlobStore.PREFIX) : 'imgblob_'
}
const IMG_BLOB_PREFIX = (function () { try { const S = wImageBlobStore(); return (S && S.PREFIX) ? String(S.PREFIX) : 'imgblob_' } catch (e) { return 'imgblob_' } })()
const wImgUrlByRef = new Map() // 引用键('b:'+blobKey / 'c:'+cacheUrl)→ objectURL
const wImgRefByUrl = new Map() // objectURL → 原引用对象(wBlobRefCache 被 FIFO 驱逐后仍能取回字节)
const wImgUrlPending = new Set() // 正在解析的引用键(幂等:渲染路径会反复调用)
@@ -735,7 +895,7 @@
if (wImgUrlByRef.has(key) || wImgUrlPending.has(key) || wImgUrlFailed.has(key)) return
wImgUrlPending.add(key)
const job = wIsBlobRef(v)
? (ImageBlobStore ? ImageBlobStore.getBlob(v.__blob) : Promise.resolve(null))
? (wImageBlobStore() ? wImageBlobStore().getBlob(v.__blob) : Promise.resolve(null))
: iwbCacheBlob(v.__cache)
// 解析 Promise 存进 wImgUrlPendingPromise ⇒ 供 wResolveImgAsync 等待(预览类操作需要 URL 字符串)
const p = Promise.resolve(job).then((blob) => {
@@ -804,8 +964,8 @@
async function wImgRefDataUrl(v) {
if (typeof v === 'string') return v
if (wIsBlobRef(v)) {
if (!ImageBlobStore) return ''
try { return await ImageBlobStore.resolveDataUrl(v.__blob) } catch (e) { return '' }
if (!wImageBlobStore()) return ''
try { return await wImageBlobStore().resolveDataUrl(v.__blob) } catch (e) { return '' }
}
if (wIsCacheRef(v)) { try { return (await iwbCacheRead(v.__cache)) || '' } catch (e) { return '' } }
return ''
@@ -866,6 +1026,9 @@
}
const cacheDoneUrls = new Set()
async function iwbCacheWrite(base64) {
// 桌面端:Cache Storage 的虚拟路径 /__iwb_cache__/* 靠 Service Worker 直出,而桌面不注册 SW
// ⇒ 这条兜底只会产生"裂图"。直接判失败,让调用方保留原值/走文件通道。
if (wFileStoreOn()) return null
try {
if (typeof caches === 'undefined' || typeof caches.open !== 'function' || !base64 || String(base64).indexOf('data:') !== 0) return null
const url = wCacheKeyOf(base64)
@@ -1516,7 +1679,7 @@
const RuntimeConstants = (typeof window !== 'undefined' && window.IWBRuntimeConstants) || { outputLimit: 10000, galleryRanges: {} }
const GalleryHydration = typeof window !== 'undefined' && window.IWBGalleryHydration
const galleryHydrator = GalleryHydration && typeof GalleryHydration.create === 'function'
? GalleryHydration.create({ get: (key) => IDB.get(key) })
? GalleryHydration.create({ get: (key) => IDB.get(key), thumb: (hash) => { const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null; return (F && typeof F.galleryThumb === 'function') ? F.galleryThumb(hash) : Promise.resolve('') } })
: null
const ModularOutputStore = typeof window !== 'undefined' && window.IWBStorageOutputs && ModularLocalStore && ModularIndexedStore
? window.IWBStorageOutputs.create({ local: ModularLocalStore, indexedDb: ModularIndexedStore, key: OUT_KEY, prefix: 'out_', limit: RuntimeConstants.outputLimit, hydrate: galleryHydrator && ((items) => galleryHydrator.hydrate(items)) })
@@ -1552,6 +1715,9 @@
return true
}
async function imageFolderSaveItem(item, thumb) {
// 桌面端:**不再「出图就下载」**。下载是用户主动动作(输出节点/图库的下载按钮),
// 自动保存到文件夹会让用户目录里堆满不想要的图 ⇒ 这里直接视为「不做任何事」。
if (wIsTauri()) return false
if (!imageFolderHandle || !item || !item.url || typeof fetch !== 'function') return false
try {
const dirs = await imageFolderEnsureDirs()
@@ -1655,7 +1821,9 @@
if (fkEarly && /^https:/i.test(fkEarly) && !wThumbProxyTried.has(fkEarly)) {
wThumbProxyTried.add(fkEarly)
try {
const pr = await fetch('/api/img?url=' + encodeURIComponent(fkEarly), { mode: 'cors' })
// 桌面客户端:用 plugin-http 直取字节(Rust 侧请求,不受 CORS 限制)
if (!wIsTauri()) { if (fkEarly) wThumbFail.add(fkEarly); return null }
const pr = await wTauri.http.fetch(fkEarly)
// v3.87.52(丙方案 C5):交给 wRegisterBlobUrl(入参是 Blob,内部创建并登记 objectURL),
// 避免此前的"创建了 blob URL 却不登记、不回收"✗
if (pr.ok) return storeOutputThumb(Object.assign({}, item, { url: wRegisterBlobUrl(await pr.blob()) }))
@@ -2143,17 +2311,47 @@
// 图片引用化**唯一入口**:wSanitizeWs(画布保存)与 wRefValueAsync(收藏快照 / LRU 反 hydrate)都只经这里产出引用。
// 失败回退链:{__blob}(IDB Blob 主通道)→ {__cache}(Cache Storage 兜底)→ null(调用方自行兜底,绝不抛错打断保存)。
// 只有 ImageBlobStore.put 明确 r.ok===true 且带 key 才返回 {__blob},绝不产出「引用指向不存在的字节」。
// 存储自检(桌面迁移排查用):把“字节到底能不能落盘”变成可复制的事实
function wStorageSelfCheck() {
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
const st = (F && typeof F.stats === 'function') ? F.stats() : null
return {
tauri: wIsTauri(), fileEnabled: wFileStoreOn(), dir: (st && st.dir) || '',
assets: (st && st.images) || 0, memKeys: (st && st.keys) || 0,
blobStore: !!wImageBlobStore(), cryptoSubtle: !!(typeof crypto !== 'undefined' && crypto.subtle),
caches: (typeof caches !== 'undefined'),
}
}
async function wImgRefWrite(dataUrl) {
if (W_IMG_BLOB_PRIMARY && ImageBlobStore) {
if (W_IMG_BLOB_PRIMARY && wImageBlobStore()) {
try {
const r = await ImageBlobStore.put(dataUrl)
const r = await wImageBlobStore().put(dataUrl)
if (r && r.ok && r.key) return { __blob: String(r.key) }
if (r && r.ok === false) swallow('image', new Error(r.error || 'blob-put-failed'))
} catch (e) { swallow('image', e) } // 落 Blob 失败(配额/环境不支持)→ 回退 Cache,但计数留痕
}
// 桌面端不回退 Cache Storage:WebView2 重启后 {__cache} 解析不到(mac 上正常),
// 回退等于“写成功但图没了”。失败就让调用方把字节内联进画布。
if (wIsTauri()) return null
const c = await iwbCacheWrite(dataUrl)
return (c && c.__cache) ? c : null
}
// 一次性迁移(桌面版):把历史画布里内联的 dataURL 图转成 {__blob} 引用。
// 只在资料目录生效时跑,跑完打标记;之后保存画布本就会走同一规则。
async function wMigrateInlineImages() {
try {
const fileRuntime = (typeof window !== 'undefined' && window.IWBStorageFile && window.IWBStorageFile.enabled && window.IWBStorageFile.enabled())
? window.IWBStorageFile.runtime : null
if (!fileRuntime || storageRuntime() !== fileRuntime) return
if (lsGet('iwb_inline2blob_v2', false) === true) return
const raw = lsGet(StorageContract.localKeys.workspaces, null)
if (!raw || !Array.isArray(raw.workspaces)) { lsSet('iwb_inline2blob_v2', true); return }
const slim = await wSanitizeWs(raw)
lsSet(StorageContract.localKeys.workspaces, slim)
lsSet('iwb_inline2blob_v2', true)
} catch (e) { /* 迁移失败不影响启动,下次再试 */ }
}
async function wSanitizeWs(ws) {
// 2026-11-03:**不再剥离**生成结果,改为「精简后落盘」——只留 url/宽高/idb + 任务标识,
// 丢掉每条结果上挂的 job(含任务提示词全文、参考图引用数组)与 snapshot。
@@ -2172,7 +2370,8 @@
// 节点图片不再压缩(v3.87.1 去掉「保存画布时压缩节点图片」):原图原样保留,
// 只把超过阈值的 dataURL 转成引用(新写入走 IDB Blob {__blob},失败回退 Cache Storage {__cache})。
// 无论缓存成功与否,都必须把当前值写回 d[f](否则压缩结果丢失、退回原图)。
if (!isBigDataUrl(v) || String(v).length < 16384) { d[f] = v; continue }
// 2026-11-16(桌面版):阈值从 16384 降到 isBigDataUrl 的 3000 ⇒ 3K~16K 这批内联图也转引用。
// 文件落盘后 base64 没有存在意义(+33% 体积、每次渲染要解码),统一走 images/ 下的文件。
// C3 第3步:引用化只经唯一入口 —— 优先 IDB Blob({__blob}),失败自动回退 Cache({__cache})。
const ref = await wImgRefWrite(v)
// 两条通道都失败(配额/隐私模式):用确定性缓存键引用兜底,而不是把压缩后仍≥16KB 的 base64 塞回画布。
@@ -2239,10 +2438,10 @@
let raw = null
try { raw = await IDB.get(key) } catch (e) { raw = null }
if (!raw || typeof raw !== 'string' || raw.indexOf('data:') !== 0) return ref
if (ImageBlobStore) {
if (wImageBlobStore()) {
try {
const r = await ImageBlobStore.put(raw)
if (r && r.ok && r.key) { const out = ImageBlobStore.refOf(r.key); wEnsureImgUrl(out); return out }
const r = await wImageBlobStore().put(raw)
if (r && r.ok && r.key) { const out = wImageBlobStore().refOf(r.key); wEnsureImgUrl(out); return out }
} catch (e) { /* 落 BlobStore 失败 → 退回 Cache 引用 */ }
}
try { const c = await iwbCacheWrite(raw); if (c && c.__cache) { wEnsureImgUrl(c); return c } } catch (e) { /* ignore */ }
@@ -2461,7 +2660,7 @@
if (k.indexOf(IMG_BLOB_PREFIX) === 0) {
if (!keep.has(k)) {
wReleaseImgUrls(['b:' + k])
try { if (ImageBlobStore) { const okDel = await ImageBlobStore.del(k); if (okDel === false) swallow('image', new Error('blob-del-failed')) } else await IDB.del(k) } catch (e) { swallow('image', e) }
try { if (wImageBlobStore()) { const okDel = await wImageBlobStore().del(k); if (okDel === false) swallow('image', new Error('blob-del-failed')) } else await IDB.del(k) } catch (e) { swallow('image', e) }
}
continue
}
@@ -3145,15 +3344,30 @@
folder: '<path d="M4 4h6l2 2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/>',
clock: '<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>',
}
// 主题:亮色(默认)/ 暗色(手动切换,localStorage 记忆)
// 主题:亮色(默认)/ 暗色 / 跟随系统(后两者写 localStorage 记忆)
function wPrefersDark() {
try { return !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) } catch (e) { return false }
}
// 外观(画布底色 + 主题色)实现在 src/ui-appearance.js:默认值/归一化/写 CSS 变量/对比度提示都在那边。
// 这里只做装配(app.js 有行数棘轮,不再堆细节)。
function applyAppearance(cfg) {
try { const A = window.IWBUIApearance; if (A) A.apply(cfg, document.documentElement.classList.contains('theme-dark')) } catch (e) { /* ignore */ }
}
function applyTheme(t) {
document.documentElement.classList.toggle('theme-dark', t === 'dark')
try { lsRawSet('iwb_theme', t === 'dark' ? 'dark' : 'light') } catch (e) { /* ignore */ }
// 'system' 只是存下来的偏好值,真正落地成 dark/light 看系统当前外观
const mode = (t === 'system') ? (wPrefersDark() ? 'dark' : 'light') : (t === 'dark' ? 'dark' : 'light')
document.documentElement.classList.toggle('theme-dark', mode === 'dark')
try { lsRawSet('iwb_theme', t === 'system' ? 'system' : mode) } catch (e) { /* ignore */ }
}
function initTheme() {
let t = 'light'
try { if (lsRawGet('iwb_theme', null) === 'dark') t = 'dark' } catch (e) { /* ignore */ }
try { const s = lsRawGet('iwb_theme', null); if (s === 'dark' || s === 'system') t = s } catch (e) { /* ignore */ }
applyTheme(t)
// 跟随系统时,系统外观切换要实时反映(不用重开窗口)
try {
const mq = window.matchMedia('(prefers-color-scheme: dark)')
if (mq && mq.addEventListener) mq.addEventListener('change', () => { try { if (lsRawGet('iwb_theme', null) === 'system') applyTheme('system') } catch (e) { /* ignore */ } })
} catch (e) { /* ignore */ }
return t
}
initTheme()
@@ -3317,9 +3531,16 @@
// 为空 = 跟随上游,节点体把上游文本显示出来(改一个字就落进自己的 data.text)。
function nodeInheritOf(node, nodesArr, edgesArr) {
const own = String((node && node.data && node.data.text) || '').trim()
if (own) return { text: '', sourceNodeId: '', more: 0, own: true }
const info = inheritedTextOf(node && node.id, nodesArr, edgesArr)
return { text: String(info.text || ''), sourceNodeId: String(info.sourceNodeId || ''), more: Number(info.more) || 0, own: false }
// 关键:先查上游。没有上游就根本没有「继承/已固定」这回事(用户是纯手写)
const info = inheritedTextOf(node && node.id, nodesArr, edgesArr) || {}
const hasUpstream = !!(info.sourceNodeId || String(info.text || '').trim())
const base = {
sourceNodeId: String(info.sourceNodeId || ''),
more: Number(info.more) || 0,
hasUpstream: hasUpstream,
}
if (own) return Object.assign({ text: '', own: true }, base)
return Object.assign({ text: String(info.text || ''), own: false }, base)
}
// 纯任务构建器:只根据节点图构造 prompt/参考图任务,不修改 state、不发送请求。
@@ -3905,6 +4126,12 @@
async function copyImageToClipboard(srcOrBlob) {
if (!srcOrBlob) throw wCopyError('format', W_COPY_HINT.format)
if (!navigator.clipboard || typeof navigator.clipboard.write !== 'function' || typeof ClipboardItem === 'undefined') {
// 桌面端兜底:WKWebView 里 ClipboardItem 常不可用,改走原生 arboard 写图片
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
if (D && D.clipboardWriteImage) {
const okNative = await D.clipboardWriteImage(srcOrBlob)
if (okNative) return srcOrBlob
}
throw wCopyError('unsupported', W_COPY_HINT.unsupported)
}
// 先转 PNG 再写剪贴板(任何输入都产出 image/png)
@@ -3912,6 +4139,11 @@
try {
await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })])
} catch (err) {
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
if (D && D.clipboardWriteImage) {
const okNative = await D.clipboardWriteImage(png)
if (okNative) return png
}
const msg = String((err && err.message) || err)
// 没有写权限(页面失焦/未授权)也归为「浏览器不支持剪贴板图片」一类,附浏览器原文便于排查
throw wCopyError('unsupported', W_COPY_HINT.unsupported + '(' + msg + ')')
@@ -4092,13 +4324,24 @@
}
const downloadBlob = (blob) => {
if (blob && blob.type) outName = nameOf(blob.type)
// 桌面端:替换原来的 <a download>,弹系统「另存为」后 fs 写二进制
if (wIsTauri()) {
wSaveBlobNative(blob, outName, '保存图片')
.then((ok) => { if (ok) wDownloadToast('已保存:' + outName) })
.catch((e) => wDownloadToast('保存失败:' + ((e && e.message) || e)))
return
}
const obj = URL.createObjectURL(blob)
clickDownload(obj)
setTimeout(() => URL.revokeObjectURL(obj), 5000)
}
// data URL / blob: URL(同源,已被浏览器解析过):直接用 <a download>。
// 注意 blob: 也必须走这条路:线上 CSP connect-src 'self' https: 会拦掉 fetch(blob:...)。
if (su.indexOf('data:') === 0 || su.indexOf('blob:') === 0) { clickDownload(url); return }
if (su.indexOf('data:') === 0 || su.indexOf('blob:') === 0) {
// 桌面端没有「浏览器下载目录」这回事 ⇒ 先取回字节,再走原生另存为
if (wIsTauri()) { try { downloadBlob(await (await fetch(url)).blob()); return } catch (e) { /* 落到后面的兜底 */ } }
else { clickDownload(url); return }
}
// ① 直连(图床允许跨域时最快、最保真)
try {
const resp = await fetch(url, { mode: 'cors' })
@@ -4122,14 +4365,17 @@
}
}
} catch (e) { /* 继续兜底 */ }
// ③ **本站同源代理**兜底(functions/api/img.js;跨域图床专用。不经任何第三方)
// ③ 原生 HTTP 兜底(Rust 侧请求,不受 CORS 限制)
// 本项目是桌面客户端,没有服务端同源代理(旧的 functions/api/img.js 已随网页版删除)
try {
const r2 = await fetch('/api/img?url=' + encodeURIComponent(su), { mode: 'cors' })
if (r2.ok) { downloadBlob(await r2.blob()); wDownloadToast('该图床不支持直连下载,已通过本站代理保存'); return }
if (wIsTauri()) {
const r2 = await wTauri.http.fetch(su)
if (r2.ok) { downloadBlob(await r2.blob()); wDownloadToast('已通过原生 HTTP 取图保存'); return }
}
} catch (e) { /* 继续兜底 */ }
// ④ 最后兜底:新标签打开(右键/长按另存)——绝不静默失败
try {
window.open(su, '_blank', 'noopener')
try { window.IWBUIShell ? window.IWBUIShell.openExternal(su) : window.open(su, '_blank', 'noopener') } catch (e) { /* ignore */ }
wDownloadToast('该图床不支持直接下载,已在新标签打开图片:请右键「图片另存为」')
} catch (e) {
wDownloadToast('下载失败:' + ((e && e.message) || '未知原因'))
@@ -4384,7 +4630,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 { t = CrashLog ? JSON.stringify(CrashLog.report({ version: APP_VERSION }), 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); else { try { navigator.clipboard.writeText(t) } catch (e) { /* ignore */ } } } }, '复制诊断信息'),
),
el('div', { className: 'iwb-hint' }, '完整记录在「设置 → 诊断」里,可导出 JSON'),
),
@@ -4436,9 +4682,9 @@ const tbCenterSeed = (type, refs) => {
const Derive = (typeof window !== 'undefined') ? window.IWBImagePreviewDerive : null
if (!Derive || typeof Derive.create !== 'function' || typeof document === 'undefined') return v
previewPending.add(key)
// 跨域图必须走同源代理(否则 fetch 必失败 ⇒ 负缓存后等于没做 ✗,见 §8.3 坑 2)
const viaUrl = (/^https?:\/\//i.test(v) && (typeof location === 'undefined' || v.indexOf(location.origin + '/') !== 0))
? (location.origin + '/api/img?url=' + encodeURIComponent(v)) : undefined
// 桌面客户端没有同源代理(旧的 functions/api/img.js 已随网页版删除)⇒ 派生器直连;
// 跨域失败即负缓存并回退原图,不影响显示。
const viaUrl = undefined
let inst = null
try { inst = Derive.create({ maxEdge: PREVIEW_MAX_EDGE, quality: 0.82 }) } catch (e) { inst = null }
if (!inst || typeof inst.deriveUrl !== 'function') { previewPending.delete(key); wPreviewPick(key, v); return v }
@@ -4457,6 +4703,48 @@ const tbCenterSeed = (type, refs) => {
previewUrls.clear(); previewPending.clear()
}
// 显示缩略图落盘(768px):下次启动直接读文件,不用再解码原图
const DISPLAY_THUMB_HASH_MAX = 512
const displayThumbSaved = new Set()
function wStoreMod () {
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
return (F && typeof F.readDisplayThumb === 'function') ? F : null
}
function wSaveDisplayThumb (key, dataUrl) {
const F = wStoreMod()
if (!F || !key || !dataUrl) return
if (displayThumbSaved.has(key) || displayThumbSaved.size > 2000) return
displayThumbSaved.add(key)
wSha256(String(key)).then(function (hex) {
try { F.writeDisplayThumb(hex.slice(0, 16), dataUrl) } catch (e) { /* ignore */ }
}).catch(function () { /* ignore */ })
}
async function wPreloadDisplayThumbs (nodes) {
const F = wStoreMod()
if (!F || !Array.isArray(nodes) || !nodes.length) return 0
const keys = []
for (const n of nodes) {
const d = n && n.data
if (!d) continue
const v = wResolveImg(d.data) || d.url
if (!v || typeof v !== 'string' || v.indexOf('data:') === 0) continue
const key = wDisplayThumbKey(v)
if (!key || displayThumbs.has(key) || keys.indexOf(key) >= 0) continue
keys.push(key)
if (keys.length >= DISPLAY_THUMB_HASH_MAX) break
}
let n = 0
for (const key of keys) {
try {
const hex = await wSha256(String(key))
const dataUrl = await F.readDisplayThumb(hex.slice(0, 16))
if (dataUrl) { displayThumbs.set(key, dataUrl); displayThumbSaved.add(key); n++ }
} catch (e) { /* 单张失败忽略 */ }
}
if (n && typeof wThumbBump === 'function') { try { wThumbBump() } catch (e) { /* ignore */ } }
return n
}
function wDisplayThumbOf(v) {
// C3:结果项 / 图片节点的 data 可能是引用对象(hydrate 直出)→ 先解析成显示 URL
if (v && typeof v === 'object') v = wResolveImg(v)
@@ -4477,8 +4765,8 @@ const tbCenterSeed = (type, refs) => {
if (displayThumbs.size >= DISPLAY_THUMB_CACHE_MAX) { const first = displayThumbs.keys().next().value; if (first !== undefined) displayThumbs.delete(first) }
displayThumbs.set(key, val)
}
const isRemoteHttp = /^https?:\/\//i.test(v) && (typeof location === 'undefined' || v.indexOf(location.origin + '/') !== 0)
img.src = isRemoteHttp ? (location.origin + '/api/img?url=' + encodeURIComponent(v)) : v
// 桌面客户端没有同源代理:直接给原地址(<img> 不受 CORS 限制,能正常显示;canvas 降采样失败会回退原图)
img.src = v
img.onload = () => {
try {
const iw = img.naturalWidth || 0, ih = img.naturalHeight || 0
@@ -4491,6 +4779,7 @@ const tbCenterSeed = (type, refs) => {
const small = cv.toDataURL('image/jpeg', 0.78)
if (displayThumbs.size >= DISPLAY_THUMB_CACHE_MAX) { const first = displayThumbs.keys().next().value; if (first !== undefined) displayThumbs.delete(first) }
wRememberThumb(small)
try { wSaveDisplayThumb(key, small) } catch (e) { /* ignore */ }
displayThumbPending.delete(key)
if (typeof wThumbBump === 'function') { try { wThumbBump() } catch (e) { /* ignore */ } }
} catch (e) { displayThumbPending.delete(key); wRememberThumb(v) } // 失败也记下:不再每次渲染重复解码整图
@@ -4757,7 +5046,7 @@ const tbCenterSeed = (type, refs) => {
try {
IWNodeBodies.inject({ el, I, LocalTextField, autoGrow, nodePreviewRefsV2, nodeInheritOf, combineSourcePairs, isPluginTypeId,
orderedUniqueRefNodes, uploadRefToImageHost, wDisplayThumbOf, wImportImage, wPreviewUrlOf, wRawCfg, wResolveImg,
wThumbSrc, downloadUrl, isImageProducer, outProgUI, outThumbCache,
wThumbSrc, downloadUrl, wResolveOutputSrc, isImageProducer, outProgUI, outThumbCache,
wPluginNodeVariants, wPluginVariantMeta, isBatchSrc, batchSrcText, compareCanvasTextOrder,
GenParams, RATIOS, RES_KEYS, RES_MAP, cachedGenerationTasks, classifyErr, fmtDur, presetDisplayName,
ratioOfSize, resOfSize, taskStallEndMs, wDedupeTaskIds, React, ReactDOM })
@@ -5074,6 +5363,8 @@ const tbCenterSeed = (type, refs) => {
const wOpenZipBlob = (blob) => _zipFn('wOpenZipBlob')(blob)
const wCreateStoreZip = () => _zipFn('wCreateStoreZip')()
function wDownloadBlob(blob, name) {
// 备份/导出统一走同一个出口:桌面端弹系统另存为,网页端仍用 <a download>
if (typeof window !== 'undefined' && window.__IWB_SAVE_BLOB__) { window.__IWB_SAVE_BLOB__(blob, name); return }
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = name
@@ -5187,7 +5478,7 @@ const tbCenterSeed = (type, refs) => {
W_KEEP,
IDB,
IMG_BLOB_PREFIX,
ImageBlobStore,
get ImageBlobStore() { return wImageBlobStore() },
ModularBackupStore,
SchemaVersions,
StorageContract,
@@ -5302,7 +5593,8 @@ const tbCenterSeed = (type, refs) => {
// 持久化存储状态(2026-11-07):非持久 = 浏览器空间紧张时可能被直接清掉。逻辑在 src hook 内
const storagePersist = IWWorkbenchHooks.useStoragePersist(3000)
// 自动备份(2026-11-07):30s 后若距上次 ≥24h 就快照 localStorage → IDB,保留 7 份
const autoBackupKit = IWWorkbenchHooks.useAutoBackup(30000)
// 桌面端不做自动快照(数据已经落盘在资料目录);网页版保持原行为
const autoBackupKit = IWWorkbenchHooks.useAutoBackup(wFileStoreOn() ? 0 : 30000)
const [settingOpen, setSettingOpen] = useState(false)
const [settingTabReq, setSettingTabReq] = useState('gen') // v3.87.26:外部点击"内存"时直接打开诊断页
// v3.87.26:顶部栏实时信息(内存/规模)。注意**不能在 useState 惰性初始值里读 refs**
@@ -5413,6 +5705,15 @@ const tbCenterSeed = (type, refs) => {
const td = useTextDialog()
const outputRequestSeq = useRef(0)
const [histSel, setHistSel] = useState([])
// 图库插入尺寸档(v3.25.18 工单 ⑤):原图 / 2k / 1k / 0.5k,记忆上次选择
const INSERT_K = { orig: 0, '2k': 2048, '1k': 1024, '0.5k': 512 }
const [insertK, setInsertK] = useState(() => { try { const v = lsGet('iwb.insertSizeK', '1k'); return INSERT_K[v] === undefined ? '1k' : v } catch (e) { return '1k' } })
const setInsertKPersist = (v) => { setInsertK(v); try { lsSet('iwb.insertSizeK', v) } catch (e) { /* ignore */ } }
// 按选中档位压缩插入图(算法在 src/image-compress.js 的 toMaxEdge)
const shrinkForInsert = (dataUrl) => {
if (insertK === 'orig') return Promise.resolve(dataUrl)
try { return _imgCompressFn('toMaxEdge')(dataUrl, INSERT_K[insertK], 0.9).catch(() => dataUrl) } catch (e) { return Promise.resolve(dataUrl) }
}
const selectAllHistory = () => setHistSel(histFiltered.map((f) => f.name))
const invertHistorySelection = () => setHistSel(histFiltered.filter((f) => !histSel.includes(f.name)).map((f) => f.name))
// 下载选中的图片:逐个取本地原图/缩略图并触发下载(间隔 220ms 防浏览器连续下载拦截)
@@ -5432,6 +5733,8 @@ const tbCenterSeed = (type, refs) => {
const swConfirmedRef = useRef(false)
// 注册 Service Worker 以检测「新版本」→ 顶部提示 → 一键刷新更新(学 opentu 的 PWA 机制)
useEffect(() => {
// 桌面端不注册 SW:本地端没有 HTTP 服务、也不需要离线缓存,注册只会 404 并拖慢启动
if (wFileStoreOn()) return
if (typeof navigator === 'undefined' || !navigator.serviceWorker) return
try {
navigator.serviceWorker.register('/sw.js').then((registration) => {
@@ -5550,12 +5853,12 @@ const tbCenterSeed = (type, refs) => {
// 打开/激活某个标签:不在列表则追加(S12)
const openTab = (wsId) => { if (!wsId) return; setOpenTabs((prev) => prev.includes(wsId) ? prev : prev.concat([wsId])) }
// 关闭标签:移除 + 释放 session/画板;关的是激活标签则先切到相邻(无则回首页)
const closeTab = (wsId) => {
const closeTab = async (wsId) => {
if (!wsId) return
const sess = sessionsStore.get(wsId)
const nm = (((refs.workspaces || workspaces).find((w) => w.id === wsId)) || {}).name || '未命名画布'
if (sess && sess.dirty) { // S13:有未保存修改 → 确认后先保存再关
if (!window.confirm('「' + nm + '」有未保存修改,关闭前将先保存。确定关闭?')) return
if (!(await wConfirm('「' + 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
@@ -5723,6 +6026,9 @@ const tbCenterSeed = (type, refs) => {
// 变量名保持不变 ⇒ 下游 viewportRef / activeWsRef / flushViewport 的调用点零改动
const { viewportRef, activeWsRef, flushViewport } = IWWorkbenchHooks.useViewportPersistence(activeWsId, viewport)
refs.config = config
// 外观:配置到位/切换主题时把画布底色与主题色写到 :root(放在 config 同步之后,
// 否则首屏拿不到配置,改完颜色要重启才生效)
useEffect(() => { try { applyAppearance(config) } catch (e) { /* ignore */ } }, [config, theme])
useEffect(() => {
let alive = true
// 启动时一次性迁移历史 localStorage 里的 base64 大图到 IndexedDB(释放空间,治撑爆)
@@ -5770,7 +6076,10 @@ const tbCenterSeed = (type, refs) => {
})
const meta = (typeof window !== 'undefined' && window.__IWB_BUILD_META__) || {}
const text = buildRuntimeDiagnosticsText(tasks, meta)
const blob = new Blob([text], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'image-workbench-diagnostics-' + new Date().toISOString().slice(0, 10) + '.json'; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(url), 5000)
const blob = new Blob([text], { type: 'application/json' })
const fileName = 'image-workbench-diagnostics-' + new Date().toISOString().slice(0, 10) + '.json'
// 统一出口:桌面端原生另存为,网页端 <a download>
window.__IWB_SAVE_BLOB__(blob, fileName)
showToast('已导出运行诊断(不含 Key、提示词和图片)')
} catch (e) { setNotice({ type: 'err', text: '诊断导出失败:' + String((e && e.message) || e) }) }
}
@@ -5977,6 +6286,8 @@ const tbCenterSeed = (type, refs) => {
refs.syncing = true // 切换/同步载入不触发自动保存(避免轮询-保存死循环)
setSel([]); setSelEdge(null)
openSession(id) // S3:先激活 session,再从它加载历史(session 化)
// 显示缩略图预热(768px 文件已存在就直接命中,省掉一次 4K 解码)
try { setTimeout(function () { wPreloadDisplayThumbs(ns).catch(function () { /* ignore */ }) }, 0) } catch (e) { /* ignore */ }
const sess = sessionsStore.get(id)
if (sess) { sess.nodes = ns; sess.edges = es; sess.groups = gs; sess.dirty = false } // S6:装载即同步 session 并清脏(装载不算本地编辑)
refs.history = (sess && sess.history) ? sess.history : { stack: [], idx: -1 } // S3:历史随 session(不再全局清空)
@@ -6940,6 +7251,8 @@ const tbCenterSeed = (type, refs) => {
wsId: activeWsId, activeWsId: () => activeWsIdRef.current || activeWsId, nodes: () => refs.nodes,
uid, findSpot, nodeW: (ty) => nodeWidth({ type: ty }), nodeH: (ty) => nodeTypeH(ty),
pushHistory, commitCanvas, setSel, setNotice, importImage: wImportImage,
readNativeImage: (typeof window !== 'undefined' && window.IWBDesktop && window.IWBDesktop.clipboardReadImage) ? () => window.IWBDesktop.clipboardReadImage() : null,
closeLibrary: () => { setDrawerOpen(false) },
})
const onKey = (e) => {
const t = e.target, C = window.IWBClipboardCopy, hasTxt = C && C.hasTextSelection
@@ -7032,11 +7345,14 @@ const tbCenterSeed = (type, refs) => {
const onPaste = (e) => {
const t = e.target, editable = !!(t && t.tagName && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable))
refs.pasteProbe = 0 // 收到真实 paste → 取消「系统剪贴板为空」的提示
refs.pasteStamp = (refs.pasteStamp || 0) + 1
const mod = (typeof window !== 'undefined' && window.IWBClipboardPaste) || null
if (mod) mod.handle(e, pasteCtx(), editable)
}
window.addEventListener('keydown', onKey)
window.addEventListener('keyup', onKeyUp)
const pasteModEarly = (typeof window !== 'undefined' && window.IWBClipboardPaste) || null
if (pasteModEarly && pasteModEarly.bindHotkeyFallback) pasteModEarly.bindHotkeyFallback(pasteCtx)
window.addEventListener('paste', onPaste)
window.addEventListener('blur', onBlur)
return () => {
@@ -7184,8 +7500,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 (!window.confirm('将转换当前画布中的 ' + targets.length + ' 张本地图片(输出节点生成结果不会处理),继续吗?')) return
if (!window.confirm('确认开始批量上传吗?上传后这些图片会替换为在线链接,通常无法自动撤回。')) return
if (!(await wConfirm('将转换当前画布中的 ' + targets.length + ' 张本地图片(输出节点生成结果不会处理),继续吗?', { title: '批量转在线链接' }))) return
if (!(await wConfirm('确认开始批量上传吗?上传后这些图片会替换为在线链接,通常无法自动撤回。', { title: '确认上传', okText: '开始上传' }))) return
let ok = 0; const errors = []
for (const n of targets) {
try {
@@ -7213,7 +7529,13 @@ const tbCenterSeed = (type, refs) => {
// C3 第2步:节点组导出同样要自带字节(按需解析,不写回画布)
const nodesForExport = await wResolveImagesForExport(withoutGenerationResults({ nodes: selectedNodes }).nodes)
const data = { app: 'image-workbench', version: 2, schemaVersion: SchemaVersions.canvas, exportType: 'group', exportedAt: new Date().toISOString(), exportSummary: { nodes: selectedNodes.length, edges: selectedEdges.length, groups: completeGroups.length }, group: Object.assign({ id: uid('g'), name: safeName, memberIds: sel.slice() }, exportedGroupPad ? { pad: exportedGroupPad } : null), groups: completeGroups, nodes: nodesForExport, edges: selectedEdges }
try { const blob = new Blob([JSON.stringify(data, null, 1)], { type: 'application/json' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = safeName.replace(/\\.iwb\\.json$/i, '') + '.iwb.json'; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(a.href), 5000); setNotice({ type: 'ok', text: '已导出节点组:' + a.download }) } catch (e) { setNotice({ type: 'err', text: '导出节点组失败:' + String((e && e.message) || e) }) }
try {
const blob = new Blob([JSON.stringify(data, null, 1)], { type: 'application/json' })
const outName = safeName.replace(/\\.iwb\\.json$/i, '') + '.iwb.json'
// 统一出口:桌面端弹系统另存为,网页端仍走 <a download>
window.__IWB_SAVE_BLOB__(blob, outName)
setNotice({ type: 'ok', text: '已导出节点组:' + outName })
} catch (e) { setNotice({ type: 'err', text: '导出节点组失败:' + String((e && e.message) || e) }) }
} })
}
// importCanvasFile 已搬到 src/runtime-workbench-logic.js(2026-10-29)
@@ -7740,8 +8062,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: () => { if (!window.confirm('确定清空回收站?将彻底删除回收站中的全部画布。')) return; emptyTrash() } }, I('trash'), '清空回收站') : null,
homeSelectedWs.length ? el('button', { className: 'iwb-btn', onClick: () => { if (!window.confirm(homeView === 'trash' ? '确定彻底删除选中的画布?此操作不可恢复。' : '确定删除选中的画布?(移入回收站)')) 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 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,
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'), '导入画布'),
@@ -7765,7 +8087,7 @@ const tbCenterSeed = (type, refs) => {
homeView === 'trash'
? [
el('button', { title: '恢复画布', onClick: (e) => { e.stopPropagation(); restoreWs(w.id) } }, I('refresh')),
el('button', { title: '彻底删除', onClick: (e) => { e.stopPropagation(); if (!window.confirm('确定彻底删除画布「' + (w.name || '未命名画布') + '」?此操作不可恢复。')) return; purgeWs(w.id) } }, I('trash')),
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: (e) => { e.stopPropagation(); duplicateWs(w.id) } }, I('copy')),
@@ -8090,6 +8412,9 @@ const tbCenterSeed = (type, refs) => {
el('button', { className: 'iwb-btn iwb-btn-sm', title: '下载选中的图片到本地', onClick: downloadHistorySelected }, '下载'),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '清除选择', onClick: () => setHistSel([]) }, '清除'),
) : null,
el('select', { className: 'iwb-input', style: { maxWidth: 118 }, value: insertK, onChange: (e) => setInsertKPersist(e.target.value), title: '插入画布时的图片尺寸:原图最清晰但最大,2k/1k/0.5k 会等比压到对应边长' },
[['orig', '原图'], ['2k', '2K'], ['1k', '1K'], ['0.5k', '0.5K']].map(([v, l]) => el('option', { key: v, value: v }, '插入 ' + l)),
),
el('select', { className: 'iwb-input', style: { maxWidth: 130 }, value: histRange, onChange: (e) => setHistRange(e.target.value), title: '时间范围' },
[['', '全部时间'], ['today', '今天'], ['7d', '近 7 天'], ['30d', '近 30 天']].map(([v, l]) => el('option', { key: v, value: v }, l)),
),
@@ -8100,7 +8425,7 @@ const tbCenterSeed = (type, refs) => {
((f.data || f.url)) ? el('img', { src: wDisplayThumbOf((f.data || f.url) || ''), loading: 'lazy', style: { aspectRatio: (f.w && f.h) ? String(f.w) + ' / ' + String(f.h) : '1 / 1' }, title: f.name + '(单击单选 · Shift+单击多选 · 双击放大 · 拖到画布=参考图节点)', draggable: true, onDragStart: (e) => { try { e.dataTransfer.setData('application/x-iwb-localref', (f.data || f.url) || f.name); e.dataTransfer.setData('application/x-iwb-gallery-orig', f.name); e.dataTransfer.effectAllowed = 'copy' } catch (err) { /* ignore */ } }, onClick: (e) => { if (e && e.shiftKey) setHistSel((prev) => prev.includes(f.name) ? prev.filter((n) => n !== f.name) : [...prev, f.name]); else setHistSel([f.name]) }, onDoubleClick: () => { setPreview({ list: outputs.map((x) => ({ __gallery: true, name: x.name, origIdb: x.origIdb, idb: x.idb, url: x.url, thumb: x.data || null })), idx: Math.max(0, outputs.findIndex((x) => x.name === f.name)) }) } }) : el('div', { className: 'iwb-history-missing' }, '图片已丢失'),
null,
el('div', { className: 'iwb-history-actions' },
el('button', { className: 'iwb-btn iwb-btn-sm', title: '插入到画布(参考图节点)', onClick: async (e) => { e.stopPropagation(); const src0 = await wbCmd().refSrcOf(await wResolveOutputSrc(f), (msg) => showToast(msg, 'err')); const spot = findSpot('ref'); const id = uid('n'); // 2026-10-20(审计 N1):插入时**立即引用化**,不要把整张图 base64 塞进画布。
el('button', { className: 'iwb-btn iwb-btn-sm', title: '插入到画布(参考图节点)', onClick: async (e) => { e.stopPropagation(); let src0 = await wbCmd().refSrcOf(await wResolveOutputSrc(f), (msg) => showToast(msg, 'err')); if (typeof src0 === 'string' && src0.indexOf('data:') === 0) src0 = await shrinkForInsert(src0); const spot = findSpot('ref'); const id = uid('n'); // 2026-10-20(审计 N1):插入时**立即引用化**,不要把整张图 base64 塞进画布。
// 原症状:插入时 data.url = 完整 base64(4K 约 10MB)⇒ 画布内存里多一份整图;
// 刷新后又被 wSanitizeWs 换成 {__blob} 引用(用户看到的「状态变了」),
// 且刷新时还要把 base64 再转回 Blob(内存数倍占用、过一会儿才回落)。
@@ -8256,29 +8581,42 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
// 插件自我注册。同源脚本本就被 CSP script-src 'self' 允许 ⇒ 不放宽 CSP、不重编译主包。
// 按需下载:启动只下载「已启用」的远程插件;未启用的记为 idle、不下载,等用户在插件管理里勾选时再加载。
// 单条远程插件的下载+激活(启动批量加载与按需加载共用):注入脚本(SRI 强制校验)→ 自我注册 → 持久化开关已开则激活。
async function wLoadPluginEntry(record) {
record.status = 'loading'
const integrity = record.integrity
try {
await new Promise((resolve, reject) => {
const script = document.createElement('script')
script.src = '/plugins/' + record.file
script.async = false
if (integrity) { script.integrity = integrity; script.crossOrigin = 'anonymous' }
script.onload = () => resolve()
script.onerror = () => reject(new Error(integrity ? '脚本完整性校验失败(integrity 不符或加载失败)' : '脚本加载失败'))
document.head.appendChild(script)
})
const registered = PluginHost && typeof PluginHost.list === 'function' && PluginHost.list().some((p) => p.id === record.id)
record.status = registered ? 'loaded' : 'not-registered'
if (registered && typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(record.id)) PluginHost.setEnabled(record.id, true)
return record.status === 'loaded'
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
// 加载实现已抽到 src/runtime-plugin-loader.js(app.js 只做装配)
function wPluginLoader () {
return (typeof window !== 'undefined') ? window.IWBRuntimePluginLoader : null
}
function wPluginSource () {
const L = wPluginLoader()
return (L && typeof L.source === 'function') ? L.source() : null
}
// 市场实现已抽到 src/runtime-plugin-market.js
function wMarketMod () {
return (typeof window !== 'undefined') ? window.IWBRuntimePluginMarket : null
}
async function wMarketList () { const M = wMarketMod(); return M ? M.list() : [] }
async function wMarketInstalled () { const M = wMarketMod(); return M ? M.installed() : [] }
async function wMarketInstall (id) { const M = wMarketMod(); return M ? M.install(id) : { ok: false, error: '市场模块未就绪' } }
async function wMarketUninstall (id) { const M = wMarketMod(); return M ? M.uninstall(id) : { ok: false, error: '市场模块未就绪' } }
async function wVerifyPluginCode (code, integrity) {
const L = wPluginLoader()
return (L && typeof L.verifyCode === 'function') ? L.verifyCode(code, integrity) : false
}
async function wLoadPluginEntry (record) {
const L = wPluginLoader()
if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false }
return L.loadBuiltin(record)
}
async function wLoadExternalPluginEntry (record) {
const L = wPluginLoader()
if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false }
return L.loadExternal(record)
}
async function wLoadLocalPluginEntry (record) {
const L = wPluginLoader()
if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false }
return L.loadLocal(record)
}
// 按需加载(插件管理里勾选 idle 行):下载脚本 → 注册 → 显式启用;失败时返回错误供 UI 回滚勾选并提示。
async function wEnsurePluginLoaded(id) {
const record = wRuntimePlugins.find((r) => r.id === id)
@@ -8290,34 +8628,96 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
const r = PluginHost && typeof PluginHost.setEnabled === 'function' ? PluginHost.setEnabled(id, true) : null
return r && r.ok ? { ok: true } : { ok: false, error: (r && r.error) || '启用失败' }
}
// 后台预热市场索引:设置页打开时直接命中缓存(网络慢也不影响首屏)
function wWarmMarketCache() {
try {
setTimeout(function () {
try { const p = wMarketList(); if (p && typeof p.catch === 'function') p.catch(function () { /* 离线也正常 */ }) } catch (e) { /* ignore */ }
}, 2500)
} catch (e) { /* ignore */ }
}
async function wLoadRuntimePlugins() {
if (typeof fetch !== 'function' || typeof document === 'undefined') return
let manifest = null
// 内置清单(随包)先读;外部清单(<资料目录>/plugins/)只覆盖同 id 的条目 —— 合并而非替换
let builtin = []
try {
const resp = await fetch('/plugins/index.json', { cache: 'no-store' })
if (!resp.ok) return
manifest = await resp.json()
} catch (e) { return }
if (resp.ok) {
const j = await resp.json()
builtin = Array.isArray(j) ? j : (Array.isArray(j && j.plugins) ? j.plugins : [])
}
} catch (e) { /* 内置读不到就只看外部 */ }
let ext = []
try {
const src = wPluginSource()
if (src) ext = await src.manifest()
} catch (e) { /* 外部清单读到一半失败:忽略 */ }
const byId = new Map(builtin.map((e) => [String((e && e.id) || ''), Object.assign({}, e, { source: 'builtin' })]))
// 开发者模式:<资料目录>/plugins/local/<id>/plugin.js(未签名,仅本地调试用)
try {
const devRaw = lsGet('iwb_plugin_dev', false)
const devOn = devRaw === true || devRaw === 'true' || devRaw === 1 || devRaw === '1'
const lsrc = wPluginSource()
if (devOn && lsrc && typeof lsrc.listLocal === 'function') {
const locals = await lsrc.listLocal()
try { lsSet('iwb_plugin_dev_count', (locals || []).length) } catch (e1) { /* probe */ }
for (const l of locals) { if (l && l.id) byId.set(String(l.id), { id: String(l.id), file: 'plugin.js', version: 'dev', source: 'local', code: l.code }) }
}
} catch (e) { /* 开发者模式读取失败不影响启动 */ }
for (const e of ext) { const id = String((e && e.id) || ''); if (id) byId.set(id, Object.assign({}, e, { source: 'external' })) }
// 关键:加载前先快照「用户关掉过哪些插件」,加载过程绝不能覆盖这个状态
let persistedState = {}
try {
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
if (F && typeof F.ready === 'function') { try { await F.ready({ wizard: false }) } catch (e) { /* 已就绪 */ } }
const v = lsGet('iwb_plugins', {})
persistedState = (v && typeof v === 'object') ? v : {}
} catch (e) { persistedState = {} }
const manifest = Array.from(byId.values())
if (!manifest.length) return
const list = Array.isArray(manifest) ? manifest : (manifest && Array.isArray(manifest.plugins) ? manifest.plugins : [])
const ordered = list.slice().sort((a, b) => String((a && a.id) || '').localeCompare(String((b && b.id) || '')))
const pending = [] // 已启用插件的加载 Promise:循环内全部同步 append 后再并行等待(执行顺序由 script.async=false 保证)
for (const entry of ordered) {
const id = String((entry && entry.id) || '')
const file = String((entry && entry.file) || '')
const record = { id, file, version: (entry && entry.version) || '', status: 'loading', error: null }
const isExt = (entry && entry.source) === 'external'
const isLocalEntry = (entry && entry.source) === 'local'
const record = { id, file, version: (entry && entry.version) || '', status: 'loading', error: null, code: (entry && entry.code) || '', source: isExt ? 'external' : ((entry && entry.source === 'local') ? 'local' : 'builtin') }
wRuntimePlugins.push(record)
if (!id || !/^[A-Za-z0-9._-]+$/.test(file)) { record.status = 'bad-entry'; continue }
const integrity = String((entry && entry.integrity) || '')
// fail-closed:无 integrity 声明即拒绝加载(清单由 KV 发布脚本生成、必带 integrity;缺失视为不可信)
if (!integrity) { record.status = 'bad-entry'; record.error = 'integrity 缺失(拒绝加载)'; continue }
if (!/^sha(256|384|512)-[A-Za-z0-9+/]{40,}={0,2}$/.test(integrity)) { record.status = 'bad-entry'; record.error = 'integrity 格式不合法'; continue }
if (!integrity && !isLocalEntry) { record.status = 'bad-entry'; record.error = 'integrity 缺失(拒绝加载)'; continue }
if (integrity && !/^sha(256|384|512)-[A-Za-z0-9+/]{40,}={0,2}$/.test(integrity)) { record.status = 'bad-entry'; record.error = 'integrity 格式不合法'; continue }
record.integrity = integrity
// 只下载已启用的;未启用记 idle(不注入脚本),插件管理里勾选时经 wEnsurePluginLoaded 按需下载
// 收进 pending 而非逐个 await:wLoadPluginEntry 在首个 await 前已 append ⇒ 并发抓取;async=false 保证执行顺序不变(冷启动 3 RTT → 1)
if (PluginHost && typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(id)) pending.push(wLoadPluginEntry(record))
// 本地开发插件默认启用(没有持久化状态,不应被当作已关闭的插件)
// 一律加载脚本(注册 ≠ 启用):脚本注册后才能被开关随时启停;
// 之前按 enabled 预筛,导致状态里残留 false 的插件永远进不了注册表,开关也打不开。
if (PluginHost) pending.push(isLocalEntry ? wLoadLocalPluginEntry(record) : (isExt ? wLoadExternalPluginEntry(record) : wLoadPluginEntry(record)))
else record.status = 'idle'
}
await Promise.all(pending)
// 脚本都注册了:把持久化里明确关掉的插件停用(其余保持启用)
try {
const st = persistedState || {}
for (const r of (wRuntimePlugins || [])) {
if (!r || r.status !== 'loaded') continue
const rec = st[r.id]
if (!rec) continue
const want = rec.enabled !== false
if (!PluginHost || typeof PluginHost.setEnabled !== 'function') continue
// 注意:插件是在 init() 之后才注册的,init 的"激活已启用项"覆盖不到它们。
// 所以这里对 want=true 一律再 setEnabled(true)(activate 幂等:已激活会返回 already),
// 否则会出现"开关显示已启用、实际没跑工厂函数"的假启用状态。
if (want) PluginHost.setEnabled(r.id, true)
else if (typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(r.id)) PluginHost.setEnabled(r.id, false)
}
} catch (e) { /* 状态应用失败不影响加载 */ }
try { lsSet('iwb_plugin_load_status', JSON.stringify(wRuntimePlugins.map((r) => ({ id: r.id, status: r.status, source: r.source, error: r.error || '' })))) } catch (e2) { /* probe */ }
try { if (PluginHost && typeof PluginHost.emit === 'function') PluginHost.emit('runtime-plugins-loaded') } catch (e) { /* 通知失败不影响启动 */ }
}
@@ -8503,6 +8903,21 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
}
} catch (e) { /* 预注册失败不影响启动 */ }
wLoadRuntimePlugins()
wWarmMarketCache()
}
// 桌面端关闭图库定时清理(设置里已去掉该项):0 = 不限,避免老图被静默删掉
try {
if (wFileStoreOn() && lsGet('iwb_retention_off_v1', false) !== true) {
const rawCfg = LocalStore.get(StorageContract.localKeys.config, null)
if (rawCfg && typeof rawCfg === 'object') {
rawCfg.outputsRetention = Object.assign({}, rawCfg.outputsRetention, { enabled: false, maxDays: 0, maxFiles: 0 })
lsSet(StorageContract.localKeys.config, rawCfg)
}
lsSet('iwb_retention_off_v1', true)
}
} catch (e) { /* ignore */ }
// 历史内联图 → 文件引用(只跑一次;让 data.json 从几百 KB 掉回几十 KB)
try { await wMigrateInlineImages() } catch (e) { /* ignore */ }
ReactDOM.createRoot(document.getElementById('root')).render(el(WErrorBoundary, { scope: 'app' }, el(E2EBoomProbe, null), el(Workbench, null)))
})()
+129
View File
@@ -0,0 +1,129 @@
# 桌面端存储改造:踩坑与铁律(2026-11-17)
> 本文记录把「浏览器存储」改成「本地资料目录」过程中真实发生过的故障。
> **每一条都写清:症状 → 根因 → 修法 → 铁律**。以后动存储相关代码前先读这篇。
---
## 一、故障清单(按严重度)
### P1 画布节点全部显示为空(最严重,数据"看起来"丢了)
- **症状**:画布卡片显示「0 个节点」,打开画布空白;`canvases/` 里出现 413 个畸形文件名(`01`、`0141` …)
- **根因**:拆分画布文件时用 `k.slice(9)` 取文件名,但 `'iwb_ws_'` 长度是 **7**,不是 9 ⇒ 文件名少了开头 2 个字符(`ws`)
- 装载时用「`iwb_ws_` + 文件名」还原键 ⇒ 和真实键对不上 ⇒ 读不到数据
- 更糟:**每次启动都会再截断 2 个字符并覆盖原文件**(读错→按错键写回),越开越乱
- **修法**:前缀长度用常量 `WS_PREFIX.length`;一次性按文件内容里的 `id` 字段把文件名改回 `<id>.json`;再从 WebView 的 localStorage 捞回节点更多的版本(957 → 1337 节点,空画布归零)
- **铁律**:
1. **禁止魔法数字**取 key 前缀,统一 `k.slice(PREFIX.length)`
2. 拆文件/改布局后**必须读回校验**(键对得上、节点数一致),对不上不许继续
### P2 迁移「先删后写」导致图库清单丢失
- **症状**:图库 7 张全显示「图片已丢失」
- **根因**:把 `library/gallery.json` 迁到 `library/gallery/index.json` 时,代码是**先删旧文件、后写新文件**;新版本第一次启动删掉旧的、还没写新的,清单就没了
- **修法**:改成「先写新位置 → 写成功后才删旧」;并加自愈(清单缺失时从 `assets` 的 `out_*` 键反推重建);再把缩略图回填进 `data` 字段
- **铁律**:**迁移永远是"复制 → 校验 → 删旧",任何"先删"都是事故**
### P3 复用带副作用的命令,覆盖了配置
- **症状**:设置里「数据库目录」显示成下载目录 `/Users/qiqi/Documents/image`,「打开」也跳错地方
- **根因**:启动时给下载目录补授权,复用了 `grant_dir`;而 `grant_dir` 会把传入路径写进 `data-dir.txt`(记录资料目录用)⇒ 下载目录的路径把记录覆盖了
- **修法**:`grant_dir` 加 `record: Option<bool>`,下载目录传 `false`;界面路径不再被「打开」的返回值覆盖
- **铁律**:**复用命令前先确认它的副作用**;"记录状态"和"执行动作"要分开
### P4 把异步 `join()` 当路径用
- **症状**:`data.json.tmp` 写出了 762KB,但 `data.json` 永远不存在;无报错
- **根因**:`const target = join(dir, DATA_FILE)` 拿到的是 **Promise**,被当成路径传给 `writeTextFile` / `rename`,两边都抛错且被 catch 吞掉
- **修法**:`await join(...)`;catch 里补日志
- **铁律**:**路径拼接一律 await**;写盘失败必须留痕,不许静默
### P5 Tauri fs 权限是「命令级」,不是「路径级」
- **症状**:目录已授权,但写文件一律 `forbidden path`
- **根因**:`fs:allow-write-file` 不覆盖 `writeTextFile`;`writeTextFile` / `readTextFile` 各有独立权限(`fs:allow-write-text-file` / `fs:allow-read-text-file`)
- **修法**:capabilities 里补齐实际用到的每个命令
- **铁律**:**用什么 API 就加什么权限**;`fs` 的每个命令是一个独立开关
### P6 dotfile 默认被拒
- **症状**:`.migrated` 标记读不到,迁移每次重跑
- **根因**:Tauri fs 默认禁止访问点文件/点目录(防误操作 `.ssh` 之类)
- **修法**:标记文件改名 `migrated.flag`(不含点)
- **铁律**:**资料目录里不放点文件**;需要标记就用 `xxx.flag`
### P7 惰性注入的 `__TAURI__` 判断过早
- **症状**:文件存储的初始化根本没跑,数据一个都没落盘
- **根因**:`enabled()` 里判断的是模块内变量 `tauri`,而它要等 `init()` 才赋值 ⇒ 入口条件恒为 false
- **修法**:`tk()` 惰性读取 `global.__TAURI__`,所有判断都经过它
- **铁律**:**全局注入对象一律惰性读取**,不要在模块加载期就断言存在
### P8 同步 API 遇异步 IO(架构约束)
- **症状**:把存储底座换成文件后,全部同步读写代码无法直接迁移
- **根因**:localStorage 是同步的,文件 IO 是异步的;业务层 63 处同步调用不能改
- **修法**:**启动时全量读入内存 → 运行时同步读写内存 → 800ms 防抖异步落盘**(关窗/隐藏/失焦时强制 flush)
- **铁律**:**同步契约 + 异步持久化**用"内存镜像"桥接,不要把异步往下传导
### P9 图库清单重建时没带缩略图
- **症状**:图库 7 张全「图片已丢失」
- **根因**:渲染条件是 `f.data || f.url`;重建清单只填了 `name/时间/idb/origIdb`,两个都是空
- **修法**:一次性回填——按 `idb` 读 `images/thumbs/<hash>.jpg` 写进 `data`(限制 96KB 以内防清单膨胀)
- **铁律**:**重建清单必须同时重建"渲染所依赖的字段"**,否则等于没修
### P10 语义变化没同步:从"出图就下载"改成"点下载才下载"
- **症状**:用户目录堆满不想要的图
- **根因**:网页版的「自动保存生成的图片」语义是"出图即下载",桌面端沿用
- **修法**:桌面端关闭自动下载;下载目录改为「用户点下载才写入、不弹窗」;自动下载开关在桌面端隐藏
- **铁律**:**改环境时必须重审"自动化动作"**,桌面端的默认行为应更保守
---
## 二、数据恢复的关键做法(这次救了 12 个画布)
> 迁移时**只复制、不清源**。WebView 的 localStorage 一直留着迁移前的原始数据,
> 所以出事后可以按「文件节点数 vs localStorage 节点数,谁多取谁」恢复。
**铁律:任何一次数据搬迁,源数据至少保留到"用户确认新位置一切正常"为止。**
---
## 三、以后动存储的强制检查清单
改动前:
1. 记录基线:画布数 / 节点总数 / assets 条数 / `images/` 四类文件数 / `library` 文件数
改动后(每次):
2. 启动 → **读回**:`data.json` 里的画布数、每个画布文件的节点数、`assets` 与文件的对应
3. 对账:与基线逐项比对,**数量只许增不许减**
4. 抽查:打开 1 个画布看节点、图库看 7 张、点一次下载看是否落盘
5. 检查目录结构:`canvases/` `library/gallery/` `images/{canvas,gallery,thumbs,legacy}`
6. 检查 flag:`migrated.flag` `migrated-v2.flag` `canvases-fixed.flag` `gallery-thumbs.flag` `recovered-from-browser.flag`
7. 对不上 → **立即回滚**(保留旧目录/旧文件),不许继续往下做
---
## 四、目前已实现的数据结构(供对照)
```
ImageWorkbench/
├── data.json 设置(含 Key)/主题/杂项 + assets 映射 + 旧格式 keys
├── canvases/<id>.json 一画布一文件(内容是画布 JSON,含 id 字段)
├── library/
│ ├── prompts.json
│ ├── groups.json
│ ├── group-groups.json
│ └── gallery/index.json 图库清单(含 data 缩略图)
├── images/
│ ├── canvas/ imgblob_* 画布节点图
│ ├── gallery/ out_orig_* 图库原图
│ ├── thumbs/ out_* 缩略图(可再生)
│ └── legacy/ 旧 __cache__ 绝对 URL 键
└── *.flag 一次性迁移标记
```
+66
View File
@@ -0,0 +1,66 @@
# 在线更新(Tauri Updater)
> 目标:用户装过一次之后,以后新版本在应用内点「检查更新」即可升级,不用再手动下载 dmg。
## 一、已经配好的东西
| 组件 | 位置 | 说明 |
|---|---|---|
| 更新插件 | `src-tauri/Cargo.toml` → `tauri-plugin-updater` | Rust 侧用 `UpdaterExt` |
| 更新源 | `src-tauri/tauri.conf.json` → `plugins.updater.endpoints` | `https://download.maqiart.eu.org/updates/latest.json` |
| 签名公钥 | 同上 `plugins.updater.pubkey` | 私钥在 `~/.config/iwb-updater.key`(**务必备份**) |
| 产物开关 | `bundle.createUpdaterArtifacts: true` | 构建 app 时额外产出 `.app.tar.gz` + `.sig` |
| Rust 命令 | `check_update` / `install_update` | 前端通过 `__TAURI__.core.invoke` 调用 |
| 前端入口 | 设置 → 通用 → 版本与更新 | 「检查更新」→「立即更新」→ 自动重启 |
## 二、发新版本(一条命令)
```bash
./scripts/publish-update.sh 3.25.3 # 改版本 + 双架构签名构建 + 上传 + 生成 latest.json
```
脚本会做四件事:
1. `npx tauri build --bundles app,dmg`(arm64,带签名)
2. `npx tauri build --target x86_64-apple-darwin --bundles app,dmg`(Intel,带签名)
3. 上传 `*.app.tar.gz` / `.sig` / `.dmg` 到 NAS `updates/darwin-{aarch64,x86_64}/`
4. 生成并上传 `updates/latest.json`(两个平台各自带 signature + url)
## 三、latest.json 格式(脚本自动生成)
```json
{
"version": "3.25.2",
"notes": "更新说明",
"pub_date": "2026-11-17T09:43:08.117Z",
"platforms": {
"darwin-aarch64": { "signature": "<.sig 内容>", "url": "https://.../image-workbench_3.25.2_aarch64.app.tar.gz" },
"darwin-x86_64": { "signature": "<.sig 内容>", "url": "https://.../image-workbench_3.25.2_x64.app.tar.gz" }
}
}
```
⚠️ **两个平台都要有**:缺哪个平台,那个平台的用户就永远「已是最新」。
## 四、用户侧流程
1. 装过任一 3.25.2+ 版本(这是第一个带更新器的版本)
2. 设置 → 通用 → 版本与更新 → **检查更新**
3. 有新版本 → 显示版本号与说明 → 点「立即更新」
4. 自动下载、校验签名、替换、重启(数据目录不受影响)
## 五、注意
- **私钥丢了就不能再发更新**(签名对不上,所有旧客户端会拒绝安装)。备份 `~/.config/iwb-updater.key`
- 公钥写在 `tauri.conf.json` 里进了仓库;私钥**绝不能**进仓库
- macOS 未做 notarization:更新替换后仍是未签名 app,首次打开可能仍要右键→打开
- Windows 将来出包时,在 latest.json 里加 `windows-x86_64`,并在 `bundle.targets` 里用 `nsis`(msi 不支持 updater)
- Cloudflare 会缓存 404:新文件名第一次访问可能短暂 404,换文件名(内容变即哈希变)即可绕过
## 六、首次接入清单(已完成 2026-11-17)
- [x] 生成密钥对(`tauri signer generate`),公钥进 config,私钥留本机
- [x] 加 `tauri-plugin-updater`,注册 `check_update` / `install_update`
- [x] `createUpdaterArtifacts: true`
- [x] 构建 3.25.2(arm + Intel)并发布 latest.json
- [ ] 用户实测:装 3.25.2 后,3.25.3 发布时能一键更新(待验证)
+127
View File
@@ -0,0 +1,127 @@
# Windows 出包步骤(手把手)
> **本版要打的版本:3.25.1**(仓库里已经是这个号,直接构建,不要再改)
>
> 确认命令:node -e "console.log(require('./package.json').version)" → 应输出 3.25.1
>
> 产物名:image-workbench_3.25.1_x64-setup.exe / image-workbench_3.25.1_x64_en-US.msi
> 目标:在一台 Windows 机器上,从 Gitea 拉代码 → 打出安装包 → 自测 → 把产物回传到 NAS。
## 0. 前置检查
- Windows 10 1803+ 或 Windows 11,**x64**
- 磁盘 ≥ 5 GB 空闲(Rust 编译产物较大)
- 有本地管理员权限(装 Visual Studio Build Tools 需要)
## 1. 安装工具链(一次性)
| 工具 | 命令 / 说明 |
|---|---|
| Git | `winget install Git.Git` |
| Node.js LTS(22) | `winget install OpenJS.NodeJS.LTS` |
| Rust | `winget install Rustlang.Rustup` 然后 `rustup default stable-x86_64-pc-windows-msvc` |
| **VS Build Tools 2022** | 勾选「**使用 C++ 的桌面开发**」(MSVC v143 + Windows SDK)——**最容易漏** |
| WebView2 Runtime | Win11 自带;Win10 没有就装 Evergreen |
自检:
```powershell
cd image-workbench-desktop
powershell -ExecutionPolicy Bypass -File scripts\windows-check.ps1
```
全部 `[OK]` 再做下一步。Rust 那行不能出现 `gnu`(必须 msvc)。
## 2. 取代码
```powershell
git clone https://git.maqiart.eu.org/malongan/image-workbench-desktop.git # 公网(公开库)
# 或内网/Tailscale:git clone http://192.168.100.185:3000/malongan/image-workbench-desktop.git
```
建议放 `C:\work\image-workbench-desktop`(避开长路径/中文路径)。
## 3. 安装依赖
```powershell
cd C:\work\image-workbench-desktop
npm ci
```
用 `npm ci`,不要 `npm install`。卡住就换 registry 或配代理。
## 4. 设版本号(三处必须一致)
```powershell
node scripts/set-version.js 3.25.0
```
同时改 `package.json` / `src-tauri/tauri.conf.json` / `src-tauri/Cargo.toml`。
版本必须比线上大,否则以后接自动更新时客户端不认。
## 5. 出包
```powershell
npm run app:build
```
内部顺序:`lint → build → 剥离内置插件 → tauri build`(lint 不过就不出包,故意的)。
产物:
| 文件 | 用途 |
|---|---|
| `src-tauri\target\release\bundle\nsis\image-workbench_3.25.0_x64-setup.exe` | **主推**(当前用户安装,免管理员) |
| `src-tauri\target\release\bundle\msi\image-workbench_3.25.0_x64_en-US.msi` | 企业环境用 |
| `src-tauri\target\release\image-workbench.exe` | 免安装单文件(目标机需 WebView2) |
首次构建 5~15 分钟,之后增量 1~2 分钟。
## 6. 自测(必须过)
1. 安装 → 启动
2. 数据目录生成:`%USERPROFILE%\Documents\ImageWorkbench`(data.json / canvases / library / images)
3. 设置→通用:「数据库目录」路径正确,「打开」能弹资源管理器
4. 关窗进程留托盘;左键托盘唤窗口;右键有菜单
5. 设置→插件:**无内置插件**;市场列 7 个;装一个 → 重启后可用
6. 画布新建/拖拽/缩放正常;导入图片正常
7. 点「下载」→ 直接落到导出目录,不弹另存为
## 7. 把产物传回来
**A. 传 NAS(局域网/Tailscale)**
```powershell
scp "src-tauri\target\release\bundle\nsis\image-workbench_3.25.0_x64-setup.exe" malongan@192.168.100.185:/vol8/web/iwb-download/updates/windows-x86_64/
```
**B. 传 Gitea Releases**(公开库匿名可下载)
**C. 发我**:我上传 NAS 并更新 `releases.json` 与下载页
## 8. 常见错误
| 报错 | 原因 | 解决 |
|---|---|---|
| `link.exe not found` | 没装 VS Build Tools C++ 工作负载 | 重装并勾「使用 C++ 的桌面开发」 |
| rustc 显示 `gnu` | 默认工具链错 | `rustup default stable-x86_64-pc-windows-msvc` |
| `Windows SDK is not installed` | SDK 缺失 | Build Tools 勾 Windows SDK |
| 启动报 WebView2 错误 | 缺运行时 | 装 Evergreen Runtime |
| `npm ci` 超时/证书 | 网络 | 换 registry / 配 proxy |
| 编译文件被占用 | 杀软扫描 target | 排除 `src-tauri\target` |
| 路径过长 | 目录太深 | 放 `C:\work\`;`git config --system core.longpaths true` |
| beforeBuildCommand lint 失败 | 代码有未定义变量 | 修代码,别绕过门禁 |
## 9. 当前状态
- **自动更新未启用**(updater 未装)⇒ Windows 包只能手动下载安装
- 下载页 Windows 位置现在显示「暂未提供」;传回后我加一条 `windows-x86_64` 就自动出现
- 插件不随包:新机器是零插件,需从市场装
## 10. 一句话流程
```
装工具 → git clone → npm ci → node scripts/set-version.js x.y.z
→ npm run app:build → 自测 7 条 → 传回 NAS/Gitea → 我更新下载页
```
+75
View File
@@ -0,0 +1,75 @@
# 插件 SDK(P3)
> 桌面版插件**全部从市场安装**,不再随应用发布。本文写给"想自己写插件"的人。
## 1. 两种插件来源
| 来源 | 位置 | 要求 |
|---|---|---|
| 市场(官方/社区) | `<资料目录>/plugins/*.js` + `plugins/index.json` | 清单带 `integrity`(sha256),加载时校验 |
| 本地开发(开发者模式) | `<资料目录>/plugins/local/<id>/plugin.js` | **不校验签名**,需在设置里打开「开发者模式」 |
资料目录默认 `~/Documents/ImageWorkbench`(macOS)。
## 2. 最小插件
一个文件即可,格式为 IIFE,向 `window.IWBPluginHost` 注册:
```js
;(function (global) {
'use strict'
global.IWBPluginHost.register({
id: 'hello-world', // 唯一 id(小写字母/数字/连字符)
name: '示例插件',
version: '0.1.0',
apiVersion: 1, // 宿主 API 版本,当前为 1
capabilities: ['nodeActions', 'canvas'],
}, function (ctx) {
ctx.nodeActions.register({
id: 'hello-world-count',
title: '示例:数一下节点',
icon: 'sparkles',
appliesTo: function (node) { return !!(node && node.type === 'ref') },
run: function () { console.log('节点数', ctx.canvas.getNodes().length); return true },
})
return { dispose: function () {} }
})
})(typeof window !== 'undefined' ? window : globalThis)
```
完整可运行版本见仓库 `examples/plugin-hello/plugin.js`。
## 3. 能力(capabilities)
| 能力 | 作用 |
|---|---|
| `nodeActions` | 给节点右键/工具条加自定义动作 |
| `canvas` | 只读访问画布(`getNodes` 等) |
| `canvasWrite` | 写画布(`setNodeImage` 等),**必须同时声明** |
| `events` | 订阅宿主事件 |
| `storage` | 插件私有持久化(按插件 id 隔离) |
未声明的能力在 `ctx` 上是 undefined,调用会抛错。
## 4. 本地开发流程
1. 建目录:`<资料目录>/plugins/local/<你的插件 id>/plugin.js`
2. 设置 → 插件 → 勾选「**开发者模式**」
3. 重启应用(插件在启动时加载)
4. 改完代码后再重启一次即可重新加载
> 开发者模式关闭时,`plugins/local/` 下的插件**不会被加载**(避免误执行未签名代码)。
## 5. 发布到市场
1. 把插件文件放进插件源仓 `iwb-plugins-desktop/<id>/src/index.js`
2. 在桌面仓跑同步:`node scripts/sync-plugins-from-repo.js`
3. 生成市场:`node scripts/gen-market.js`
4. 把 `market/` 上传到 NAS `/vol8/web/iwb-market/`
## 6. 注意事项
- **不要用 `alert` / `confirm` / `prompt`**:桌面端会阻塞 WebView(宿主已全部改页内确认)
- 插件与宿主同源,能读到画布数据 ⇒ 只装可信插件
- 插件 id 冲突会被拒绝注册(先注册者生效)
- `dispose` 里清理你自己加的 DOM/定时器/监听器
+108
View File
@@ -0,0 +1,108 @@
# 任务:在 Windows 上为 image-workbench-desktop 构建 v3.25.15 安装包
你是这台 Windows 机器上的打包执行者。只做打包与自测,**不改业务代码**。
> ⚠️ v3.25.15 起的变化:项目已**彻底转桌面客户端**(`_headers` / `functions/` / `wrangler.toml` 已删除,`npm run deploy` 脚本已移除);
> 更新清单**平台解耦**(Windows 用 `updates/latest-windows.json`,**由 Mac 侧用正式私钥生成,你不写**)。
## 硬性约束
1. 不改 `app.js` / `src/**` / `src-tauri/src/**` / `style.css` 的业务逻辑
2. 不绕过 lint 门禁;报错就停下报告
3. 不用 `npm install`,只用 `npm ci`;版本已定 **3.25.15**,不要改
4. 不 commit / 不 push / 不打 tag / 不跑任何 `scripts/publish-*.sh`
5. 不改 `src-tauri/tauri.windows.conf.json`(产物已锁 `nsis`,不要 msi)
## 第零步:拉代码
```powershell
git fetch --all --tags; git checkout main; git pull --ff-only
git rev-parse --short HEAD # 必须是 84c2c10 或其后代
node -e "console.log(require('./package.json').version)" # 必须 3.25.15
```
## 第一步:环境检查
```powershell
node -v; npm -v; rustc -V; rustup show active-toolchain
powershell -ExecutionPolicy Bypass -File scripts\windows-check.ps1
```
全部 `[OK]` 才继续;出现 `[缺失]` 停止报告(不要自行安装)。
## 第二步:依赖
```powershell
npm ci
```
本次新增两个 Rust 插件依赖(single-instance / notification),首次构建会多拉一些 crate。
## 第三步:构建(用一次性临时密钥签名)
```powershell
npx tauri signer generate -w "$env:TEMP\iwb-tmp.key" --password ""
$env:TAURI_SIGNING_PRIVATE_KEY = Get-Content "$env:TEMP\iwb-tmp.key" -Raw
$env:TAURI_SIGNING_PRIVATE_KEY_PASSWORD = ""
npx tauri build
Remove-Item "$env:TEMP\iwb-tmp.key" -Force
```
> 产出的 `.sig` 是临时密钥签的,**我会在 Mac 上用正式私钥重签**,你附上即可。
## 第四步:确认产物
```powershell
Get-ChildItem src-tauri\target\release\bundle -Recurse -Include *.exe,*.sig | Select FullName,Length
Get-FileHash "src-tauri\target\release\bundle\nsis\image-workbench_3.25.15_x64-setup.exe" -Algorithm SHA256
Test-Path dist\plugins # 期望 False
Test-Path _headers # 期望 False
Test-Path functions # 期望 False
```
## 第五步:自测清单(逐条报通过/失败)
**基础**
1. 安装并启动;数据目录 `%USERPROFILE%\Documents\ImageWorkbench` 生成 `data.json`/`canvases`/`library`/`images`
2. **`images\` 下必须有 `canvas` 文件夹**(v3.25.12 之前只有 `thumbs`,这是丢图根因)
3. 设置 → 通用:数据库目录正确;「打开」能弹资源管理器
4. 关窗口进程仍在托盘;左键唤出;右键有菜单
**图片持久化(历史 bug 复现点)**
5. `Ctrl+V` 粘贴新图 → 出现图片节点
6. **正常退出**(托盘右键退出,非强杀)→ 重开 → 图仍在、显示正常
7. 从资源管理器拖图进画布 → 退出重开 → 图还在
**桌面壳(本次新增)**
8. 单实例:连续双击两次 → 只有一个窗口,第二次聚焦已有
9. 外链:点「项目主页」→ 用系统浏览器打开,应用不变(不能被导航成网页)
10. 跑一次生图,完成后弹系统通知
**插件与 CSP(本次修复)**
11. 设置 → 插件:无内置插件;市场能列 7 个;装一个 → 重启后可用
12. **鲜艺抠图**:启用后对图片节点执行抠图 → **不应出现 `Failed to fetch`**(3.25.11 回归,3.25.14 已修)
13. 若本机有 `XianyiAiRmbg` 监听 `0.0.0.0:30092` → 抠图出透明底;没装则注明跳过
**外观(本次新增)**
14. 设置 → 外观:改画布底色(亮/暗)与主题色 → 立即生效,重启保持
15. 亮暗切换时画布底色分别用两套值
任何一条失败:记录现象 + 截图后停止报告,**不要改代码**。
## 第六步:交付格式
```
结论:成功 / 失败(卡在第 N 步)
版本:3.25.15 commit=<sha>
安装包:<路径> <大小> SHA256=<hex>
环境:node= rust= VS= WebView2=
自测:1✅ … 15✅(失败写 ❌ + 现象)
耗时:
```
产物留在本机;**不要**上传 NAS、**不要**写 `latest-windows.json`(我在 Mac 侧做)。
## 停止条件
commit 不对 / 环境缺件 / 构建报错一次重试无效 / 自测有失败 / 需要改业务代码 —— 遇到即停,
报告「卡在哪一步 + 完整报错 + 已尝试过什么」。
+2 -2
View File
@@ -278,7 +278,7 @@ npm run deploy # 部署到正式站
IWB_VERIFY_STRICT=1 node scripts/verify-release.js
```
> ⚠️ `npm run deploy` = `verify` + `wrangler pages deploy`,**不含 git push**。
> ⚠️ 本项目已转桌面客户端:**不再用 `wrangler pages deploy`**,发版走 `./scripts/publish-update.sh`(macOS)/ `./scripts/publish-windows-update.sh`(Windows)。
> 回滚时**不要**把旧代码 push 到 main(会污染历史);用 `checkout` 部署即可,
> 部署完 `git checkout main` 回到主干。
@@ -408,7 +408,7 @@ git checkout refactor-step-3
git checkout stable-v3.24.5 && npm ci && npm run verify:ci && npm run deploy
# 层 4:看部署历史,用 dashboard 或 API 切回旧 deployment
npx wrangler pages deployment list --project-name image-workbench-web
# 桌面端没有「线上部署列表」:版本清单在 NAS 的 /vol8/web/iwb-download/updates/
```
### 7.2 铁律
+10 -6
View File
@@ -1,7 +1,7 @@
# 现状架构与性能事实基线(image-workbench-web)
> **本文档是什么**:现状**事实快照**,不是规范。用途:任何性能 / 内存 / 存储相关改动,先对齐这里的现实,避免把已经调好的东西改坏。
> 日期 **2026-10-20**(**2026-11-16 复算 · v3.24.85**)| 基线(**最近一次 bump 版本的提交**,不是主干 HEAD)`main = 4be78c0`(线上 `v3.24.85+7df9dc4` —— 线上实际运行提交是 docs 提交 `7df9dc4`,bump 提交为 `4be78c0`;2026-11-16 已发**测试站 + 正式站**,三地址一致 + `IWB_VERIFY_STRICT=1` 通过。v3.24.85 是「代码体检收口」(棘轮收回 Workbench 3090→2998 + 图库索引 4 条绕过锁的写路径收口到 `mutate` + 文档数字校准),`stable` / `stable-v3.24.85` / `stable-verified-2026-11-16` 均指向 `7df9dc4`。上一条 —— 2026-11-14 发**测试站 + 正式站** `https://test.image-workbench-web.pages.dev`:**v3.24.84 修「生图节点连了 3 条上游只出 1 个任务」**(任务 id 与去重基准改用新字段 `ownerNodeId`=本节点自己,不再用随继承冒泡的 `sourceNodeId` ⇒ 连几条线就几个任务;`relay` 仍归约到真实文本来源,同一来源多路径抵达只算一次)。上一条 v3.24.83:**修「插件节点冷启动退化成一段文本」**(插件节点体是异步注册的,`registerNodeType` 在 `render` 由无变有时自增 `NODE_TYPES_REV`,`NodeCard` 比它 ⇒ 注册那一刻重建一次;`canvas-normalize` 按命名规则把 `plugin:<id>:<variant>` 认作已知类型,不再降级成 `plugin` 并写回存档);配套插件 `style-source` 1.3.2 把节点体样式改为**脚本执行时注入**(此前只在面板 `mount()` 注入 ⇒ 从存档直接进画布时节点无样式、缩略图按原图铺满)。上一条 v3.24.82 同批:提示词/文本节点**显示上游继承文本**(自己 `data.text` 为空时把上游那段话显示在框里,改一个字即接管,另有「恢复跟随」清空回跟随;多路上游按 Y 轴取第一条)+ 修 `nodeRefsOf` 的 textout 分支只认 llm/batch/combine 上游导致「样式 → 文本 → 分层」丢参考图;再上一条 v3.24.81:① 插件节点可自定义节点体(`render(node, props, host)` 画真实 DOM,宿主不每帧重建 ⇒ 输入框不失焦);② 节点自带参考图(`data.refOn/refUrl` ⇒ 任务图里补伪参考图,坐标取节点自身 ⇒ 仍参与「图片按 X 轴排序」);③ 连线白名单按 `data.outKind === 'prompt'` 归一化,7 条规则一次放行,内置节点行为逐字不变。上一条 v3.24.80 = 离开页面的兜底保存不递增 rev(2026-11-14 07:20 补发 —— 首发 11-13 23:25 撞 Cloudflare Workers API 事故 `503 no healthy upstream`,期间正式站保持在 `v3.24.79+8598a57` 未动)。v3.24.83 的 bump 提交即 `0a27a42`(v3.24.82 为 `ef6cf42`、v3.24.81 为 `dba71e3`);主干 HEAD 会继续前进,见 [`RELEASES.md`](../RELEASES.md))| 历史分支 `refactor/architecture` / `feat/multi-canvas-tabs` / `refactor/state-store` 已于 2026-10-20 清理(内容均已并入 main,归档标签 `archive/*`),本文**计数类事实**已按 main HEAD 复算。
> 日期 **2026-10-20**(**2026-11-16 复算 · v3.24.85**)| 基线(**最近一次 bump 版本的提交**,不是主干 HEAD)`main = f136601`(线上 `v3.25.18+f136601` —— 线上实际运行提交是 docs 提交 `7df9dc4`,bump 提交为 `4be78c0`;2026-11-16 已发**测试站 + 正式站**,三地址一致 + `IWB_VERIFY_STRICT=1` 通过。v3.24.85 是「代码体检收口」(棘轮收回 Workbench 3090→2998 + 图库索引 4 条绕过锁的写路径收口到 `mutate` + 文档数字校准),`stable` / `stable-v3.24.85` / `stable-verified-2026-11-16` 均指向 `7df9dc4`。上一条 —— 2026-11-14 发**测试站 + 正式站** `https://test.image-workbench-web.pages.dev`:**v3.24.84 修「生图节点连了 3 条上游只出 1 个任务」**(任务 id 与去重基准改用新字段 `ownerNodeId`=本节点自己,不再用随继承冒泡的 `sourceNodeId` ⇒ 连几条线就几个任务;`relay` 仍归约到真实文本来源,同一来源多路径抵达只算一次)。上一条 v3.24.83:**修「插件节点冷启动退化成一段文本」**(插件节点体是异步注册的,`registerNodeType` 在 `render` 由无变有时自增 `NODE_TYPES_REV`,`NodeCard` 比它 ⇒ 注册那一刻重建一次;`canvas-normalize` 按命名规则把 `plugin:<id>:<variant>` 认作已知类型,不再降级成 `plugin` 并写回存档);配套插件 `style-source` 1.3.2 把节点体样式改为**脚本执行时注入**(此前只在面板 `mount()` 注入 ⇒ 从存档直接进画布时节点无样式、缩略图按原图铺满)。上一条 v3.24.82 同批:提示词/文本节点**显示上游继承文本**(自己 `data.text` 为空时把上游那段话显示在框里,改一个字即接管,另有「恢复跟随」清空回跟随;多路上游按 Y 轴取第一条)+ 修 `nodeRefsOf` 的 textout 分支只认 llm/batch/combine 上游导致「样式 → 文本 → 分层」丢参考图;再上一条 v3.24.81:① 插件节点可自定义节点体(`render(node, props, host)` 画真实 DOM,宿主不每帧重建 ⇒ 输入框不失焦);② 节点自带参考图(`data.refOn/refUrl` ⇒ 任务图里补伪参考图,坐标取节点自身 ⇒ 仍参与「图片按 X 轴排序」);③ 连线白名单按 `data.outKind === 'prompt'` 归一化,7 条规则一次放行,内置节点行为逐字不变。上一条 v3.24.80 = 离开页面的兜底保存不递增 rev(2026-11-14 07:20 补发 —— 首发 11-13 23:25 撞 Cloudflare Workers API 事故 `503 no healthy upstream`,期间正式站保持在 `v3.24.79+8598a57` 未动)。v3.24.83 的 bump 提交即 `0a27a42`(v3.24.82 为 `ef6cf42`、v3.24.81 为 `dba71e3`);主干 HEAD 会继续前进,见 [`RELEASES.md`](../RELEASES.md))| 历史分支 `refactor/architecture` / `feat/multi-canvas-tabs` / `refactor/state-store` 已于 2026-10-20 清理(内容均已并入 main,归档标签 `archive/*`),本文**计数类事实**已按 main HEAD 复算。
<!-- 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`(现 **78** 个模块 / 14,607 行,`sourceModules` 78 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。
- `app.js` = 单 IIFE **8,508 行**(**双层预算**:绝对上限 8,700 / 占总源码 ≤ 40%,现 **36.8%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,998 行**(上限 **3,030**,余量 32;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **87** 个模块 / 14,607 行,`sourceModules` 87 项;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. 门禁与环境现状
@@ -31,7 +31,7 @@
|---|---|---|
| 单测基线 | **658 通过 / 0 新增失败 / 2 已知环境差异**(2026-11-12 v3.24.76 实测;660 −2 = 94-5~7 三条钉点换成一条消费方契约) | (A) `npm test` 实测(`tests/iwb-v32-web-test.js`) |
| e2e | spec 文件 **59** 个(**55** 个进门禁 + 4 个 dev 探针 `_perf-baseline` / `_plugin-host-probe` / `_probe-drag` / `_probe-tab-switch`) | (A) `tests/` 计数 + `scripts/list-e2e-specs.js` |
| e2e 用例数 | **200 条**(2026-11-16 实测:55 个进门禁 spec 内 `test()` 总数)(历史:115 → v3.24.18 **143** → v3.24.19 **147** → v3.24.21 **151** → F2 改名 1 条 **152** → 抓手工具 2 条 **154** → v3.24.44 输出顺序 2 条 **166** → v3.24.47 同步去重 `iwb-sync-dedupe` 1 条 **167** → v3.24.67 **179** → v3.24.68 **183** → v3.24.69 **184** → v3.24.70 **186** → v3.24.74 **187**(新增「拖入 PDF 给提示 + MIME 空 PNG 仍能导入」)→ v3.24.75 **188**(新增「同一张图连粘两次只建一个节点」)→ v3.24.76 **191**(新增 `iwb-tabs-release` 3 条:回首页不降级 / 关标签先保存再关 / 彻底删除连带关标签)→ v3.24.77 **194**(新增 `iwb-lod` 3 条:fit 大画布必须全 LOD / 放大后必须恢复 / 常规画布不 LOD)→ v3.24.78 **196**(`iwb-lod` 3 → 5 条:新增「lite 档必须画出代表图/首行文字」与「缩到 15% 以下才退成 plain」)→ v3.24.82 **197**(新增 `iwb-inherit-text` 1 条:提示词/文本节点显示上游继承文本、改字接管、恢复跟随)→ v3.24.83 **198**(新增 `iwb-plugin-node-coldstart` 1 条:插件脚本晚到 1.2s,存档里的插件节点必须自动切回插件节点体,且类型不被降级成 `plugin`)→ v3.24.79 **196 不变**(测速修复的守门落在 jsdom 单测 `provider-ping-test.js`,e2e 无新增)→ v3.24.85 **200**(新增 `iwb-multi-tab` 2 条:A 页 flush 落盘后 B 页必须靠 rev 轮询看到改动;B 页持锁期间 A 页图库归档必须挂起);早期 99 → 115 的逐版链条见 `docs/history/coverage-baseline-2026-10-27.md`) | (A) `tests/*.spec.js` 计数 + `scripts/list-e2e-specs.js` |
| e2e 用例数 | **200 条**(2026-11-16 实测:55 个进门禁 spec 内 `test()` 总数;v3.25.15 删除网页版部署面后为 **53** 个进门禁 —— `iwb-csp-gate` / `iwb-functions-headers` 随 `_headers`、`functions/` 一起移除)(历史:115 → v3.24.18 **143** → v3.24.19 **147** → v3.24.21 **151** → F2 改名 1 条 **152** → 抓手工具 2 条 **154** → v3.24.44 输出顺序 2 条 **166** → v3.24.47 同步去重 `iwb-sync-dedupe` 1 条 **167** → v3.24.67 **179** → v3.24.68 **183** → v3.24.69 **184** → v3.24.70 **186** → v3.24.74 **187**(新增「拖入 PDF 给提示 + MIME 空 PNG 仍能导入」)→ v3.24.75 **188**(新增「同一张图连粘两次只建一个节点」)→ v3.24.76 **191**(新增 `iwb-tabs-release` 3 条:回首页不降级 / 关标签先保存再关 / 彻底删除连带关标签)→ v3.24.77 **194**(新增 `iwb-lod` 3 条:fit 大画布必须全 LOD / 放大后必须恢复 / 常规画布不 LOD)→ v3.24.78 **196**(`iwb-lod` 3 → 5 条:新增「lite 档必须画出代表图/首行文字」与「缩到 15% 以下才退成 plain」)→ v3.24.82 **197**(新增 `iwb-inherit-text` 1 条:提示词/文本节点显示上游继承文本、改字接管、恢复跟随)→ v3.24.83 **198**(新增 `iwb-plugin-node-coldstart` 1 条:插件脚本晚到 1.2s,存档里的插件节点必须自动切回插件节点体,且类型不被降级成 `plugin`)→ v3.24.79 **196 不变**(测速修复的守门落在 jsdom 单测 `provider-ping-test.js`,e2e 无新增)→ v3.24.85 **200**(新增 `iwb-multi-tab` 2 条:A 页 flush 落盘后 B 页必须靠 rev 轮询看到改动;B 页持锁期间 A 页图库归档必须挂起);早期 99 → 115 的逐版链条见 `docs/history/coverage-baseline-2026-10-27.md`) | (A) `tests/*.spec.js` 计数 + `scripts/list-e2e-specs.js` |
| CI | `.github/workflows/verify.yml`:**push(main) + PR(→main) + 手动** 触发,两个 job(`gate` = `verify:ci`;`e2e` = `test:e2e`),只验证不部署 | (A) |
| 部署 | `npm run deploy` = `verify` + `wrangler pages deploy dist --branch main`;**内含全量 verify,不得绕过** | (A) `package.json:16` |
| 部署环境 | 本机 wrangler 为 OAuth 登录 → **不能设 `CI=true`**(用 `unset CI` + `WRANGLER_SEND_METRICS=false`) | (A) 本轮发布实测 |
@@ -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` 不引用模块全局)。**78 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**87 个模块中 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 耦合面(**68** 项)与 `sourceModules` 顺序(**78** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**74** 项)与 `sourceModules` 顺序(**87** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
## 12. 易踩的坑
@@ -254,7 +254,7 @@
**信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**68** 项)与 `sourceModules` 顺序(**78** 项);新增模块、新增耦合、新增 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 耦合面」(**74** 项)与 `sourceModules` 顺序(**87** 项);新增模块、新增耦合、新增 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 规则三的同一失败模式)。
@@ -270,6 +270,10 @@
**CSP 最小放宽(2026-10-17,为本地服务插件)**:`_headers` 的 `connect-src` 由 `'self' https:` 扩为 `'self' https: http://127.0.0.1:30092 http://localhost:30092`。
- **动机**:页面内插件(非浏览器扩展)受页面 CSP 约束;调用本机服务必须放行 loopback。**只放行这一个固定端口**,不放宽到任意 `http:`、不放开脚本域、不引入 `unsafe-eval`。
- **边界**:插件若把服务地址改到别的 host/端口会被 CSP 拦(属预期)。页面因此可以向本机 30092 发请求 —— 这是**有意的安全边界调整**,与"插件是可信代码"的模型一致。
- **桌面客户端 CSP 的唯一定义处是 `src-tauri/tauri.conf.json` 的 `app.security.csp`**(v3.25.14 补记)。
本项目是桌面客户端,`_headers` 属于旧的网页部署、不参与桌面行为,**两者不做一致性约束**。
v3.25.11 的「CSP 清理」误判 30092 为遗留端口删掉 ⇒ 桌面版鲜艺抠图插件 `Failed to fetch`。
现由 `tests/desktop-csp-loopback-test.js` 钉住(只断言桌面 CSP 的运行时值,避免源码钉点棘轮)。
**鲜艺抠图插件(2026-10-17 起改为 A2 运行时插件,`dist` 不再内置)**:源码已迁出主仓到独立插件仓(`iwb-plugins`),经 Cloudflare Function `functions/plugins/[[path]].js` + KV(binding `PLUGINS`)**同源运行时加载**(同源 ⇒ CSP 零改动);主包**已不含** `src/plugin-xianyi-cutout.js`。功能:右键命令「抠图:选中节点」→ `POST {apiUrl}/rmbg?crop=`(`application/octet-stream` + 原始字节)→ 结果 PNG 写回为新的参考图节点(`<原名>_cutout.png`)。契约对齐 `iwb-plaus` v3.1.3 的 `background.js`(二进制进 / PNG 字节出;无 token、无 JSON),但**补齐了原版缺失的超时**(`AbortController` + 可配 `timeoutMs`)。设置项:`apiUrl` / `crop` / `timeoutMs`。尚未提供的能力面(若日后需要):插件只读「选中节点」与按 id 取节点图(`canvas` 目前只有 `getNodes` / `listNodeTypes`)。
+40
View File
@@ -0,0 +1,40 @@
// 示例插件(P3 SDK 模板):把本文件放到
// <资料目录>/plugins/local/hello-world/plugin.js
// 然后在 设置 → 插件 → 打开「开发者模式」,重启应用即可生效。
//
// 契约:调用 window.IWBPluginHost.register(manifest, factory)
// manifest: { id, name, version, apiVersion, capabilities }
// factory(ctx): 注册入口;返回 { dispose } 供停用/卸载时清理
;(function (global) {
'use strict'
global.IWBPluginHost.register({
id: 'hello-world',
name: '示例插件',
version: '0.1.0',
apiVersion: 1,
capabilities: ['nodeActions', 'canvas'],
}, function (ctx) {
// 读取当前画布节点(只读)
function countNodes () {
try {
return (ctx.canvas && typeof ctx.canvas.getNodes === 'function') ? ctx.canvas.getNodes().length : 0
} catch (e) { return -1 }
}
// 注册一个节点右键动作:只在参考图/输出节点上出现
ctx.nodeActions.register({
id: 'hello-world-count',
title: '示例:数一下节点',
icon: 'sparkles',
appliesTo: function (node) { return !!(node && (node.type === 'ref' || node.type === 'out')) },
run: function () {
// 注意:桌面端不要用 alert/confirm(会阻塞 WebView),用 console 或宿主提供的 UI
console.log('[hello-world] 当前画布节点数:' + countNodes())
return true
},
})
return { dispose: function () { /* 清理定时器/监听器 */ } }
})
})(typeof window !== 'undefined' ? window : globalThis)
-108
View File
@@ -1,108 +0,0 @@
// Cloudflare Pages Function:**第一方**图片代理(同源 /api/img)。
// 目的:豆包(火山 TOS)等图床**不返回 CORS 头**,浏览器无法 fetch ⇒ 下载、缩略图归档、
// 本地原图备份全部拿不到字节。经本站代理转发后由本站给出 CORS 头,前端即可正常读取。
// 用法:GET /api/img?url=<encodeURIComponent(https 图片地址)>
//
// 安全边界(H2 加固):
// - 仅接受**同源**调用:若请求带 Origin 头,其 host 必须与本站一致。
// - 仅 https、仅允许常见图片/对象存储域名(避免成为开放代理/SSRF),仅透传 image/* 响应。
// - **手动跟随重定向**:每一跳都对目标 host 重新做白名单校验(原实现 redirect:'follow' 只校验初始
// host,可被 302 逃逸到任意主机),并限制跳数。
// - **响应大小上限**:先看 content-length,超限即拒;无 content-length 时按流裁剪(防超大响应耗尽配额)。
// - 不再返回 Access-Control-Allow-Origin: *(同源调用本就不需要 CORS)。
export function onRequest(context) {
return handle(context.request)
}
const ALLOW_HOSTS = [
/(^|\.)volces\.com$/i, // 火山引擎 / TOS(豆包 Seedream 图床)
/(^|\.)aliyuncs\.com$/i, // 阿里云 OSS(tuzi 文档示例图床)
/(^|\.)myqcloud\.com$/i, // 腾讯云 COS
/(^|\.)qiniucdn\.com$/i,
/(^|\.)cloudfront\.net$/i,
/(^|\.)googleusercontent\.com$/i,
/(^|\.)openai\.org$/i,
/(^|\.)oaistatic\.com$/i,
/(^|\.)blob\.core\.windows\.net$/i,
]
const MAX_BYTES = 25 * 1024 * 1024 // 单张图片上限 25MB(生成图远小于此;防超大响应)
const MAX_REDIRECTS = 3
// 安全头(2026-10-20 加,H1):Cloudflare Pages 的 `_headers` **不作用于 Functions 响应**
// (https://developers.cloudflare.com/pages/configuration/headers/)⇒ 静态资源有 CSP/nosniff,
// 而本函数(及 plugins 函数)原本**一个安全头都没有**。这不是可利用漏洞(每个响应都显式
// 设了 Content-Type),但属于纵深防御缺口:将来若有端点返回用户影响的内容且漏设 Content-Type,
// 浏览器会自行嗅探类型 ⇒ 可能演变成 XSS。故在**每个** Response 显式补齐 nosniff + Referrer-Policy。
const SECURITY_HEADERS = {
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
}
function hdr() {
return Object.assign({ 'Content-Type': 'text/plain; charset=utf-8' }, SECURITY_HEADERS)
}
function plain(msg, status) {
return new Response(msg, { status, headers: hdr() })
}
function sameOrigin(request) {
const origin = request.headers.get('Origin')
if (!origin || origin === 'null') return true
try { return new URL(origin).host === new URL(request.url).host } catch (e) { return false }
}
function hostAllowed(u) {
return ALLOW_HOSTS.some((re) => re.test(u.hostname))
}
function capStream(stream, max) {
let seen = 0
return stream.pipeThrough(new TransformStream({
transform(chunk, controller) {
seen += chunk && chunk.byteLength ? chunk.byteLength : 0
if (seen > max) { controller.error(new Error('response too large')); return }
controller.enqueue(chunk)
},
}))
}
async function handle(request) {
if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: hdr() })
if (request.method !== 'GET') return plain('仅支持 GET', 405)
if (!sameOrigin(request)) return plain('仅允许同源调用', 403)
let target
try {
const raw = String(new URL(request.url).searchParams.get('url') || '')
target = new URL(raw)
} catch (e) { return plain('缺少或非法的 url 参数', 400) }
if (target.protocol !== 'https:') return plain('仅支持 https 图片地址', 400)
if (!hostAllowed(target)) return plain('该图床未在允许列表中:' + target.hostname, 403)
try {
// 手动跟随重定向:每一跳都对 host 重新校验,逃逸即拒。
let upstream = null
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
upstream = await fetch(target.toString(), { headers: { Accept: 'image/*' }, redirect: 'manual' })
const status = upstream.status
const isRedirect = status >= 300 && status < 400
if (!isRedirect) break
const location = upstream.headers.get('Location')
if (!location) return plain('上游重定向缺少 Location', 502)
if (hop === MAX_REDIRECTS) return plain('重定向次数过多', 508)
let next
try { next = new URL(location, target) } catch (e) { return plain('上游重定向地址非法', 502) }
if (next.protocol !== 'https:') return plain('重定向目标非 https', 403)
if (!hostAllowed(next)) return plain('重定向目标未在允许列表中:' + next.hostname, 403)
target = next
}
if (!upstream || !upstream.ok) return plain('上游返回 ' + (upstream ? upstream.status : '0'), 502)
const ct = String(upstream.headers.get('content-type') || '')
if (ct && ct.toLowerCase().indexOf('image/') !== 0) return plain('上游不是图片(' + ct + ')', 415)
const len = Number(upstream.headers.get('content-length'))
if (Number.isFinite(len) && len > MAX_BYTES) return plain('图片过大(超过 ' + MAX_BYTES + ' 字节)', 413)
const headers = new Headers()
headers.set('Content-Type', ct || 'image/png')
headers.set('Cache-Control', 'private, max-age=600')
for (const [k, v] of Object.entries(SECURITY_HEADERS)) headers.set(k, v)
const body = upstream.body && !(Number.isFinite(len) && len <= MAX_BYTES) ? capStream(upstream.body, MAX_BYTES) : upstream.body
return new Response(body, { status: 200, headers })
} catch (e) {
return plain('代理失败:' + ((e && e.message) || 'unknown'), 502)
}
}
-74
View File
@@ -1,74 +0,0 @@
// /plugins/* → 从 KV(binding: PLUGINS)以**同源**方式提供插件文件。
// 同源脚本本就被页面 CSP(script-src 'self')允许 ⇒ 无需放宽 CSP、无需 unsafe-eval、无需重新部署 app.js。
// KV 键约定:plugins/index.json(清单)+ plugins/<file>(每个插件一个文件)。
//
// 缓存策略(按 basename 分流):
// - plugin-<id>.<hash12>.js(内容寻址,发布脚本生成)→ public, max-age=31536000, immutable(字节永不变 ⇒ 可永久缓存)
// - 其他 .js(历史遗留未哈希文件)→ no-cache + ETag(安全网:绝不许被永久缓存)
// - .json(清单)→ no-cache + ETag;if-none-match 命中 → 304 空 body
// - 其他扩展名 / 404 / 500 → no-store
// ETag 为 (value, basename) 的确定性纯函数:FNV-1a 32bit(同步、廉价),hex 后加双引号。
const JS_CT = 'application/javascript; charset=utf-8'
const JSON_CT = 'application/json; charset=utf-8'
// 安全头(2026-10-20 加,H1):Cloudflare Pages 的 `_headers` **不作用于 Functions 响应**
// (https://developers.cloudflare.com/pages/configuration/headers/)⇒ 静态资源有 CSP/nosniff,
// 而本函数原本**一个安全头都没有**。插件字节虽同源且有 SRI 校验,但缺 nosniff 意味着
// 万一将来 KV 里的内容类型异常,浏览器可能自行嗅探 ⇒ 补齐纵深防御。
const SECURITY_HEADERS = { 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer' }
const ERROR_HEADERS = Object.assign({ 'content-type': JSON_CT, 'cache-control': 'no-store' }, SECURITY_HEADERS)
const NO_STORE_HEADERS = Object.assign({ 'content-type': JS_CT, 'cache-control': 'no-store' }, SECURITY_HEADERS)
const IMMUTABLE_JS_RE = /^plugin-[a-z0-9-]+\.[0-9a-f]{12}\.js$/
// FNV-1a 32-bit(对 UTF-16 code unit 序列):同步、确定、够用于 ETag 指纹
const fnv1a32 = (s) => {
let h = 0x811c9dc5
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i)
h = Math.imul(h, 0x01000193)
}
return (h >>> 0).toString(16).padStart(8, '0')
}
const etagOf = (value, base) => '"' + fnv1a32(base + '\n' + value) + '"'
export async function onRequestGet(context) {
const { params, env } = context
const parts = Array.isArray(params.path) ? params.path : [params.path].filter(Boolean)
const tail = parts.join('/') || 'index.json'
const key = 'plugins/' + tail
const base = tail.slice(tail.lastIndexOf('/') + 1)
if (!env || !env.PLUGINS) {
return new Response(JSON.stringify({ error: 'PLUGINS KV 未绑定' }), { status: 500, headers: ERROR_HEADERS })
}
const value = await env.PLUGINS.get(key)
if (value === null) return new Response('not found', { status: 404, headers: Object.assign({ 'cache-control': 'no-store' }, SECURITY_HEADERS) })
// A) 内容寻址的插件 JS:内容变 ⇒ 文件名变 ⇒ 可 immutable 永久缓存
if (IMMUTABLE_JS_RE.test(base)) {
return new Response(value, {
headers: Object.assign({ 'content-type': JS_CT, 'cache-control': 'public, max-age=31536000, immutable' }, SECURITY_HEADERS),
})
}
// B) 未哈希 .js 与 .json(清单):no-cache + ETag,每次回源校验,命中即 304
if (base.endsWith('.js') || base.endsWith('.json')) {
const etag = etagOf(value, base)
const headers = Object.assign({
'content-type': base.endsWith('.json') ? JSON_CT : JS_CT,
'cache-control': 'no-cache',
etag,
}, SECURITY_HEADERS)
const inm = context.request && context.request.headers && context.request.headers.get('if-none-match')
if (inm === etag) return new Response(null, { status: 304, headers })
return new Response(value, { headers })
}
// 其他扩展名:保持 no-store
return new Response(value, { headers: NO_STORE_HEADERS })
}
+275
View File
@@ -7,8 +7,14 @@
"": {
"name": "image-workbench-web",
"version": "3.24.85",
"dependencies": {
"@tauri-apps/plugin-dialog": "^2.8.4",
"@tauri-apps/plugin-fs": "^2.7.1",
"@tauri-apps/plugin-http": "^2.9.0"
},
"devDependencies": {
"@playwright/test": "^1.64.1",
"@tauri-apps/cli": "^2.12.4",
"esbuild": "0.28.2",
"eslint": "^10.13.0",
"globals": "^17.13.0",
@@ -825,6 +831,275 @@
"node": ">=20"
}
},
"node_modules/@tauri-apps/api": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.12.4.tgz",
"integrity": "sha512-pVmfis+4zT8H0Qhp3xPZx9Ju7kpzvA6rr/PSJPyuwfvucTQ8sVt61NYU9KMkK703UFlYadFmjKA4HhybOtN0gg==",
"license": "Apache-2.0 OR MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/tauri"
}
},
"node_modules/@tauri-apps/cli": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.4.tgz",
"integrity": "sha512-JI9bHfudSRJikGOrjbXEm6RjzzvmKuLc+JixB1NE8hNzQkNlCCIC3pTES3uypkR9lxHrsbxzcnSwhI2IxBQphw==",
"dev": true,
"license": "Apache-2.0 OR MIT",
"bin": {
"tauri": "tauri.js"
},
"engines": {
"node": ">= 10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/tauri"
},
"optionalDependencies": {
"@tauri-apps/cli-darwin-arm64": "2.12.4",
"@tauri-apps/cli-darwin-x64": "2.12.4",
"@tauri-apps/cli-linux-arm-gnueabihf": "2.12.4",
"@tauri-apps/cli-linux-arm64-gnu": "2.12.4",
"@tauri-apps/cli-linux-arm64-musl": "2.12.4",
"@tauri-apps/cli-linux-riscv64-gnu": "2.12.4",
"@tauri-apps/cli-linux-x64-gnu": "2.12.4",
"@tauri-apps/cli-linux-x64-musl": "2.12.4",
"@tauri-apps/cli-win32-arm64-msvc": "2.12.4",
"@tauri-apps/cli-win32-ia32-msvc": "2.12.4",
"@tauri-apps/cli-win32-x64-msvc": "2.12.4"
}
},
"node_modules/@tauri-apps/cli-darwin-arm64": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.4.tgz",
"integrity": "sha512-OxqKSckIkoJ6vX2AjifIJpTasFC0Hbdoo7gEiCmAjauABO3U8m2MRsLWe+QTiBwDx1mIrvgA+rvI7tvDnbnHVg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-darwin-x64": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.4.tgz",
"integrity": "sha512-fz76/77wMMJOaaUN6n3CybRG0P/MTEjjqYk81mGPyhi9m6Ue5T+LWBnJP/AkPooNatBPI2vtulGqomyMJ44lCQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-arm-gnueabihf": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.4.tgz",
"integrity": "sha512-K0w8Bof6Lt8QKLAYhRy0yy36ZH5iA/35VuSOvnxyjvCUZ+A3JKsUTlALviH/sVgAlisaPzzmeJSH8XOn4Q2HBA==",
"cpu": [
"arm"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-arm64-gnu": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.4.tgz",
"integrity": "sha512-j5rOnjmRUwWrm1oosf0zBYl4D+fqydgUROFCk0hvKZxvbTT8SOERes0QB7rBV/XWNy+kM6pCKzb3oSm2sRglzg==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-arm64-musl": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.4.tgz",
"integrity": "sha512-aOue3Fy6Jb7+oWcfAVUsVHfeTybSCt2CZoU06aO4jv4d2Ks/KnaTPwMAK3CLEduGOvBLY1lbBBrIyomqLLH5Sg==",
"cpu": [
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-riscv64-gnu": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.4.tgz",
"integrity": "sha512-Fx6GShY/RvST+t6LMlTHAwd66+1tEaAAGrnU7cysVfaiRP1BKng5Vl6rVmO6rSLOA1Sp1dRzNYM4f0OWQGb7qA==",
"cpu": [
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-x64-gnu": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.4.tgz",
"integrity": "sha512-tNzZSa79Z1nRpHxEpQ38lsAFpKlFlYvoXzjTV+lRRn/zSf3wrdUC3wnLcq2XEadchPu4ttK0zivhYzr+XGD19Q==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-linux-x64-musl": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.4.tgz",
"integrity": "sha512-jmZ1pr0xEqUhuEusWtt9Yt+GF6lCnGHUmIL+KIknpbjK/XQ2qkhDBhaxK/JMHM2A8dAacVXCxXJk2EXpwhQUfA==",
"cpu": [
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-win32-arm64-msvc": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.4.tgz",
"integrity": "sha512-fGo8pgEHZxdSYgZ/J98m1usJ7NHKmKbq7k6uT0x1rpOq6Bg2YVzzpaAblWk710f5LHYBJIL5QIFS5IrD+4gmTg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-win32-ia32-msvc": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.4.tgz",
"integrity": "sha512-ezl8sQIcjYsye3TUnTH5VcWmWzccZASlQm7hlZt0dYyj1XD0qpVW47u2xYVrIKui0F8uQv/7QGZixdWiClBsbg==",
"cpu": [
"ia32"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/cli-win32-x64-msvc": {
"version": "2.12.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.4.tgz",
"integrity": "sha512-DJhDeCqjLDNMWYFy7ZS8cfeAHX2RK0RbQMLiA3bMVVkXRDJ4NBYiHriGqsUhsr9iG41aTb+dJGkFPmPw1gWwVw==",
"cpu": [
"x64"
],
"dev": true,
"license": "Apache-2.0 OR MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@tauri-apps/plugin-dialog": {
"version": "2.8.4",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-dialog/-/plugin-dialog-2.8.4.tgz",
"integrity": "sha512-+6ZOiXenOaxXwb8qCbBPdT2jX2cFPaVVHGIskrpmJLpmWj+qKRTD6X/z9x7hTdSQn7NedcoXCkWGej4a7dC4lw==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.12.0"
}
},
"node_modules/@tauri-apps/plugin-fs": {
"version": "2.7.1",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-fs/-/plugin-fs-2.7.1.tgz",
"integrity": "sha512-4TBVjpi/q8PuNzjpkAc2iBGXMTLjOrAyfTiiOL8ORaJCZJRG3tjzmQ4sqs2CMG75FvLyRkOkERfP7AyY4iBNwQ==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.12.0"
}
},
"node_modules/@tauri-apps/plugin-http": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/@tauri-apps/plugin-http/-/plugin-http-2.9.0.tgz",
"integrity": "sha512-q3HTsbyFk3E9H4slJr+egd6KdRF2Fn4BoZFGI3ZHb7PBT9snlsOOlZC5L4Q1+AlDDd6OHdf/KTM6DNUJ0RNMEQ==",
"license": "MIT OR Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.12.0"
}
},
"node_modules/@types/esrecurse": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
+15 -7
View File
@@ -1,13 +1,16 @@
{
"name": "image-workbench-web",
"private": true,
"version": "3.24.85",
"version": "3.25.18",
"description": "Browser-based node canvas image workbench",
"scripts": {
"build": "node scripts/build.js",
"build": "node scripts/build.js && node scripts/copy-plugins.js",
"tauri": "tauri",
"app:dev": "tauri dev",
"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 && node tests/iwb-v32-web-test.js",
"test:unit": "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-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/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/architecture-boundary-guard-test.js && node tests/plugin-host-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/ui-groups-sidebar-test.js && node tests/ui-lib-sidebar-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/functions-api-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/ui-workbench-hooks-test.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/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/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/ui-groups-sidebar-test.js && node tests/ui-lib-sidebar-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/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/ui-workbench-hooks-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",
@@ -17,21 +20,26 @@
"test:e2e:local": "node scripts/serve-test.js",
"verify:ci": "npm run build && node --check app.js && node --check dist/app.js && node scripts/check-dist.js && 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",
"deploy": "npm run verify && npx --yes wrangler@4 pages deploy dist --project-name image-workbench-web --branch main",
"deploy:test": "npm run verify && npx --yes wrangler@4 pages deploy dist --project-name image-workbench-web --branch test",
"verify:release": "node scripts/verify-release.js",
"coverage:e2e": "node scripts/coverage-e2e.js",
"sync:facts": "node scripts/sync-facts.js",
"sync:facts:write": "node scripts/sync-facts.js --write",
"typecheck": "tsc -p tsconfig.json"
"typecheck": "tsc -p tsconfig.json",
"release:desktop": "bash scripts/release.sh"
},
"devDependencies": {
"@playwright/test": "^1.64.1",
"@tauri-apps/cli": "^2.12.4",
"esbuild": "0.28.2",
"eslint": "^10.13.0",
"globals": "^17.13.0",
"jsdom": "^24.1.3",
"playwright": "^1.64.1",
"typescript": "^5.9.3"
},
"dependencies": {
"@tauri-apps/plugin-dialog": "^2.8.4",
"@tauri-apps/plugin-fs": "^2.7.1",
"@tauri-apps/plugin-http": "^2.9.0"
}
}
+3 -3
View File
@@ -13,9 +13,9 @@
},
{
"id": "image-annotate",
"file": "plugin-image-annotate.86ccc161901c.js",
"version": "1.20.1",
"integrity": "sha256-hszBYZAc1qcloGHrWhXG9Z3Zc/qq0emOnlMNPUar3Pc="
"file": "plugin-image-annotate.7a865c7c353c.js",
"version": "1.20.6",
"integrity": "sha256-eoZcfDU8P7yqxVGorrWs0b9iTKJfEE25b85JPDCEsk8="
},
{
"id": "image-vectorize",
+79
View File
@@ -0,0 +1,79 @@
{
"batch-export": {
"name": "批量出图",
"desc": "资源中心勾选节点,串行批量生成并打包 ZIP 下载",
"author": "official",
"icon": "🗂️",
"color": "#e8f0fe",
"tags": [
"出图",
"批处理"
]
},
"blank-canvas": {
"name": "空白画布",
"desc": "新建空白画布节点,用于分区分组",
"author": "official",
"icon": "⬜",
"color": "#eef2f6",
"tags": [
"画布",
"效率"
]
},
"image-annotate": {
"name": "标注 / 修图",
"desc": "在画布内标注、涂抹、局部重绘",
"author": "official",
"icon": "🖌️",
"color": "#fdeaea",
"tags": [
"修图",
"标注"
]
},
"image-vectorize": {
"name": "位图转矢量",
"desc": "把位图转成 SVG 矢量路径",
"author": "official",
"icon": "✒️",
"color": "#eaf3ea",
"tags": [
"转换",
"矢量"
]
},
"style-source": {
"name": "风格库",
"desc": "风格提示词库与一键套用",
"author": "official",
"icon": "🎨",
"color": "#fdf0e6",
"tags": [
"提示词",
"风格"
]
},
"white-bg-800": {
"name": "白底图",
"desc": "批量生成电商白底图(800px)",
"author": "official",
"icon": "🧾",
"color": "#eef7fb",
"tags": [
"电商",
"出图"
]
},
"xianyi-cutout": {
"name": "鲜艺抠图",
"desc": "接入鲜艺抠图模型的一键去背景",
"author": "official",
"icon": "✂️",
"color": "#f3eafd",
"tags": [
"抠图",
"去背景"
]
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,137 @@
// iwb-plugin: 空白画布 —— 给「空白的参考图节点」填入指定尺寸(1K)的纯白图片,作为插图/标注的起点。
// 移植自 iwb-plaus 仓库 iwb-cutout-extension:src/content.js 的 BLANK_RATIOS / performBlankCanvas / showBlankMenu。
// 有意差异:只保留 1K 档(上游菜单实际也只用 1K);只填当前节点(不新建);不联动编辑器。
;(function (global) {
'use strict'
// 与宿主 app.js 的 RATIOS 表 1K 档逐字一致。插件不能 import 宿主内部,故照抄数值;
// 上游扩展也是这么做的(BLANK_RATIOS 抄自宿主)。
var SIZES = [
{ label: '1:1 方形', w: 1024, h: 1024 },
{ label: '2:3 竖版', w: 832, h: 1248 },
{ label: '3:2 横版', w: 1248, h: 832 },
{ label: '3:4 竖版', w: 880, h: 1168 },
{ label: '4:3 横版', w: 1184, h: 880 },
{ label: '4:5 竖版', w: 912, h: 1136 },
{ label: '5:4 横版', w: 1136, h: 896 },
{ label: '9:16 竖版', w: 768, h: 1360 },
{ label: '16:9 横版', w: 1360, h: 752 },
{ label: '21:9 超宽', w: 1552, h: 656 },
{ label: '9:21 超宽竖版', w: 656, h: 1520 },
]
var CSS = [
'.iwb-blankcanvas-menu{position:fixed;left:50%;top:64px;transform:translateX(-50%);z-index:2147483000;',
'width:312px;padding:10px;border-radius:10px;box-sizing:border-box;',
'background:var(--iwb-panel,#fff);color:var(--iwb-text,#1c2333);',
'border:1px solid var(--iwb-border,#d5d9e0);box-shadow:0 12px 32px rgba(0,0,0,.28);',
'font:12px/1.4 system-ui,-apple-system,"PingFang SC",sans-serif}',
'.iwb-blankcanvas-title{font-weight:600;margin:2px 2px 8px}',
'.iwb-blankcanvas-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:6px}',
'.iwb-blankcanvas-item{display:flex;flex-direction:column;align-items:center;gap:2px;padding:8px 4px;',
'border-radius:8px;border:1px solid var(--iwb-border,#d5d9e0);background:var(--iwb-layer,#f0f1f4);',
'color:inherit;font:inherit;cursor:pointer}',
'.iwb-blankcanvas-item:hover{background:var(--iwb-layer2,#fff)}',
'.iwb-blankcanvas-item b{font-weight:600}',
'.iwb-blankcanvas-item i{font-style:normal;font-size:11px;color:var(--iwb-text2,#4d5668)}',
].join('')
global.IWBPluginHost.register({
id: 'blank-canvas',
name: '空白画布',
version: '1.0.0',
apiVersion: 1,
capabilities: ['nodeActions', 'canvas', 'canvasWrite'],
}, function (ctx) {
var STYLE_ID = 'iwb-blankcanvas-style'
var menuEl = null
var outsideHandler = null
function injectStyle() {
if (document.getElementById(STYLE_ID)) return
var style = document.createElement('style')
style.id = STYLE_ID
style.textContent = CSS
;(document.head || document.documentElement).appendChild(style)
}
// 与上游 isEmptyRefNode 等价:ref 节点且既无本地数据也无 URL({__blob}/{__cache} 引用是对象,天然为真)
function isEmptyImageNode(node) {
if (!node || node.type !== 'ref') return false
var d = node.data || {}
return !d.data && !d.url
}
function whitePng(w, h) {
var canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
var ctx2d = canvas.getContext('2d')
ctx2d.fillStyle = '#ffffff'
ctx2d.fillRect(0, 0, w, h)
return canvas.toDataURL('image/png')
}
function closeMenu() {
if (menuEl && menuEl.parentNode) menuEl.parentNode.removeChild(menuEl)
menuEl = null
if (outsideHandler) { document.removeEventListener('pointerdown', outsideHandler, true); outsideHandler = null }
document.removeEventListener('keydown', onKeyDown, true)
}
function onKeyDown(e) { if (e.key === 'Escape') closeMenu() }
function apply(nodeId, w, h) {
var nodes = (ctx.canvas && typeof ctx.canvas.getNodes === 'function') ? ctx.canvas.getNodes() : []
var target = null
for (var i = 0; i < nodes.length; i++) if (nodes[i] && nodes[i].id === nodeId) target = nodes[i]
if (!target || !isEmptyImageNode(target)) throw new Error('该节点不是空白的图片节点')
// 宿主把 canvasWrite 的 API 合并进 ctx.canvas(plugin-host.js 的 CAPABILITY_API_KEYS)⇒ 写接口在 ctx.canvas 上
if (!ctx.canvas.setNodeImage(nodeId, whitePng(w, h))) throw new Error('写入节点失败')
}
function openMenu(nodeId) {
injectStyle()
closeMenu()
var menu = document.createElement('div')
menu.className = 'iwb-blankcanvas-menu'
var title = document.createElement('div')
title.className = 'iwb-blankcanvas-title'
title.textContent = '创建空白画布(1K)'
menu.appendChild(title)
var grid = document.createElement('div')
grid.className = 'iwb-blankcanvas-grid'
SIZES.forEach(function (size) {
var btn = document.createElement('button')
btn.type = 'button'
btn.className = 'iwb-blankcanvas-item'
btn.setAttribute('data-size', size.w + 'x' + size.h)
btn.innerHTML = '<b>' + size.label + '</b><i>' + size.w + '×' + size.h + '</i>'
btn.addEventListener('pointerdown', function (e) { e.stopPropagation() })
btn.addEventListener('click', function (e) {
e.stopPropagation()
e.preventDefault()
closeMenu()
apply(nodeId, size.w, size.h)
})
grid.appendChild(btn)
})
menu.appendChild(grid)
document.body.appendChild(menu)
menuEl = menu
outsideHandler = function (e) { if (!menuEl || !menuEl.contains(e.target)) closeMenu() }
document.addEventListener('pointerdown', outsideHandler, true)
document.addEventListener('keydown', onKeyDown, true)
}
ctx.nodeActions.register({
id: 'blank-canvas-open',
title: '空白画布',
icon: 'plus',
appliesTo: function (node) { return isEmptyImageNode(node) },
run: function (node) { openMenu(node.id); return true },
})
return { dispose: closeMenu }
})
})(typeof window !== 'undefined' ? window : globalThis)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,313 @@
// iwb-plugin: 白底图 —— 把选中节点的图等比缩放、居中合成到正方形画布,按设置的格式/质量/体积上限编码,
// 输出 <name>_<size>x<size>.<ext>(默认 800×800 白底 jpeg,≤500KB;可开双版本一次出透明 PNG + 白底 JPG)。
// 移植自 iwb-plaus 仓库 iwb-cutout-extension:src/shared/image-math.js 的 fitRect + src/content.js 的 makeWhiteBgImage / performWhiteBg;
// 几何与合成算法逐字对齐上游,只有宿主胶水(IWBPluginHost 注册 / ctx 调用)与导出编码是新写的。
;(function (global) {
'use strict'
// 上游 shared/image-math.js 的 clamp
function clamp(v, min, max) {
return Math.max(min, Math.min(max, v))
}
// 上游 shared/image-math.js 的 fitRect:内容最长边 = min(boxW, boxH) * ratio,等比缩放并居中(不裁剪)
function fitRect(srcW, srcH, boxW, boxH, ratio) {
if (!(srcW > 0) || !(srcH > 0) || !(boxW > 0) || !(boxH > 0)) {
return { x: 0, y: 0, w: 0, h: 0, scale: 0 }
}
var r = Math.max(0.01, Math.min(1, ratio))
var maxLen = Math.min(boxW, boxH) * r
var scale = Math.min(maxLen / srcW, maxLen / srcH)
var w = srcW * scale
var h = srcH * scale
return { x: (boxW - w) / 2, y: (boxH - h) / 2, w: w, h: h, scale: scale }
}
function loadImage(src) {
return new Promise(function (resolve, reject) {
var img = new Image()
img.onload = function () { resolve(img) }
img.onerror = function () { reject(new Error('图片解码失败')) }
img.src = src
})
}
// ---------- 编码 ----------
// png 无损(无质量参数);jpeg/webp 有损且有质量参数;webp 另外保留 alpha。
var FORMATS = {
png: { mime: 'image/png', ext: 'png', lossy: false, alpha: true },
jpeg: { mime: 'image/jpeg', ext: 'jpg', lossy: true, alpha: false },
webp: { mime: 'image/webp', ext: 'webp', lossy: true, alpha: true },
}
// toBlob 的 blob.type 才是真实产出格式(浏览器不支持 webp 时会静默回退 png),命名按它走。
var TYPE_EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' }
// 双版本固定产出:透明 PNG(无损、保 alpha)+ 白底 JPG(有损、体积可控)—— 电商平台两种图都要。
// png 那种允许超上限(透明图是必需产物,PNG 无压缩参数,压不下去只能照常输出并记日志)。
var DUAL_TARGETS = [
{ format: 'png', transparent: true, allowOversize: true },
{ format: 'jpeg', transparent: false, allowOversize: false },
]
// 导出格式设置是 text 输入框(宿主设置面板只有 text/number/boolean),这里做容错归一化。
function normalizeFormat(raw) {
var s = String(raw === undefined || raw === null ? '' : raw).trim().toLowerCase().replace(/^\./, '')
if (s === 'jpg' || s === 'jpeg' || s === 'jpe') return 'jpeg'
if (s === 'png' || s === 'webp') return s
return ''
}
// dataURL 的字节数(仅在 canvas.toBlob 缺失时的退路;正常路径用 blob.size,精确且无 base64 开销)
function dataUrlBytes(url) {
var s = String(url || '')
var comma = s.indexOf(',')
if (comma < 0) return 0
var body = s.length - comma - 1
var pad = s.charAt(s.length - 1) === '=' ? (s.charAt(s.length - 2) === '=' ? 2 : 1) : 0
return Math.max(0, Math.floor(body * 3 / 4) - pad)
}
function blobToDataUrl(blob) {
return new Promise(function (resolve, reject) {
var reader = new FileReader()
reader.onload = function () { resolve(String(reader.result || '')) }
reader.onerror = function () { reject(reader.error || new Error('读取编码结果失败')) }
reader.readAsDataURL(blob)
})
}
// 编码一次,产出 { dataUrl, size, type }
function encodeOnce(canvas, mime, quality) {
return new Promise(function (resolve, reject) {
if (typeof canvas.toBlob !== 'function') {
var url = canvas.toDataURL(mime, quality)
resolve({ dataUrl: url, size: dataUrlBytes(url), type: mime })
return
}
try {
canvas.toBlob(function (blob) {
if (!blob) { reject(new Error('图片编码失败')); return }
blobToDataUrl(blob).then(function (dataUrl) {
resolve({ dataUrl: dataUrl, size: blob.size, type: String(blob.type || mime) })
}, reject)
}, mime, quality)
} catch (error) {
reject(error)
}
})
}
function kb(bytes) {
return (Math.round(bytes / 1024 * 10) / 10) + 'KB'
}
// 体积上限:先按用户质量编码;超限就有损格式向下二分找「能进上限的最高质量」。
// 有损质量下限固定 0.2:再低画质不可用,此时报错而不是偷偷改边长(800×800 是硬规范)。
var MIN_QUALITY = 0.2
async function encodeWithLimit(canvas, format, quality, maxBytes) {
var spec = FORMATS[format]
var first = await encodeOnce(canvas, spec.mime, quality)
if (!maxBytes || first.size <= maxBytes) return first
if (!spec.lossy) {
throw new Error(
'PNG 体积 ' + kb(first.size) + ' 超过上限 ' + kb(maxBytes) +
':浏览器导出 PNG 无法调压缩级别 —— 请把「导出格式」改成 jpeg / webp,或调大「体积上限」'
)
}
var floor = await encodeOnce(canvas, spec.mime, MIN_QUALITY)
if (floor.size > maxBytes) {
throw new Error(
'已压到质量 20 仍有 ' + kb(floor.size) + ',超过上限 ' + kb(maxBytes) +
':请调小「大图边长」或调大「体积上限」'
)
}
var lo = MIN_QUALITY
var hi = quality
var pick = floor
for (var i = 0; i < 6 && hi - lo > 0.01; i++) {
var mid = (lo + hi) / 2
var cur = await encodeOnce(canvas, spec.mime, mid)
if (cur.size <= maxBytes) {
pick = cur
lo = mid
} else {
hi = mid
}
}
return pick
}
global.IWBPluginHost.register({
id: 'white-bg-800',
name: '白底图',
version: '1.2.1',
apiVersion: 1,
capabilities: ['commands', 'canvas', 'canvasWrite', 'nodeActions'],
settings: {
bgSize: { type: 'number', label: '大图边长(像素)', desc: '默认 800;允许 64–4096,越界自动夹取。', default: 800 },
ratioPct: { type: 'number', label: '内容占比(%)', desc: '内容等比缩放后占边长的百分比,默认 80(=640/800,电商主图规范);允许 10–100。', default: 80 },
dual: { type: 'boolean', label: '双版本(透明 PNG + 白底 JPG)', desc: '开启=一次生成两个节点:透明底 PNG + 白底 JPG,各一份。此时「导出格式」「透明底」不生效,「覆盖原节点」被忽略(双版本总是新建)。', default: false },
format: { type: 'text', label: '导出格式(单版本)', desc: '填 png / jpeg / webp(jpg 也认),默认 jpeg。png 无损但无压缩参数,体积可能超限。双版本开启时此项不生效。', default: 'jpeg' },
quality: { type: 'number', label: '压缩质量(1–100)', desc: '仅 jpeg / webp 生效,默认 82;超过体积上限时自动向下调(最低 20)。', default: 82 },
maxKB: { type: 'number', label: '体积上限(KB)', desc: '默认 500;填 0 或负数=不限制。按编码后的文件字节数判定。', default: 500 },
transparent: { type: 'boolean', label: '透明底(单版本)', desc: '关闭(默认)=填白底;开启=保留透明通道(jpeg 不支持,会自动改填白底)。双版本开启时此项不生效。', default: false },
replace: { type: 'boolean', label: '覆盖原节点', desc: '关闭(默认)=新建参考图节点;开启=覆盖当前节点。双版本开启时忽略此项。', default: false },
},
}, function (ctx) {
const NO_IMAGE = '该节点没有可编码的图片(请选中带图的参考图或输出节点)'
const REMOTE_FAIL = '远程图片无法读取(可能被跨域限制):请先转存为本地位图'
// 取图:dataUrl 直接赋给 img.src(img-src 放行 data:,不污染画布);
// 绝不对 data: URL 发网络请求 —— 宿主 CSP connect-src 不含 data:,必被拦(姊妹插件 image-annotate 踩过并修掉的坑)。
// 远程 url 才走 fetch,转成 blob: URL 再解码(blob: 同样不污染画布)。
async function resolveImage(nodeId) {
const image = await ctx.canvas.getNodeImage(nodeId)
if (!image) throw new Error(NO_IMAGE)
if (image.dataUrl) return loadImage(image.dataUrl)
if (!image.url) throw new Error(NO_IMAGE)
let resp
try {
resp = await global.fetch(image.url)
} catch (e) {
throw new Error(REMOTE_FAIL)
}
if (!resp.ok) throw new Error(REMOTE_FAIL)
const objUrl = URL.createObjectURL(await resp.blob())
try {
return await loadImage(objUrl)
} catch (e) {
throw new Error(REMOTE_FAIL)
} finally {
URL.revokeObjectURL(objUrl)
}
}
// 合成(对齐上游 makeWhiteBgImage):正方形画布,白底或透明底,fitRect 等比缩放居中、不裁剪
function composeCanvas(img, size, ratio, transparent) {
const canvas = document.createElement('canvas')
canvas.width = size
canvas.height = size
const ctx2d = canvas.getContext('2d')
if (!transparent) {
ctx2d.fillStyle = '#ffffff'
ctx2d.fillRect(0, 0, size, size)
}
const rect = fitRect(img.naturalWidth || img.width, img.naturalHeight || img.height, size, size, ratio)
ctx2d.drawImage(img, rect.x, rect.y, rect.w, rect.h)
return canvas
}
// allowOversize 只给双版本的透明 PNG 用:透明图是必需产物,PNG 又无压缩参数,
// 超限也只能照常输出(记日志),不能因为一个版本超限就让另一个版本也出不来。
async function encodeTarget(canvas, format, quality, maxBytes, allowOversize) {
if (allowOversize && !FORMATS[format].lossy) {
const res = await encodeOnce(canvas, FORMATS[format].mime, 1)
if (maxBytes && res.size > maxBytes) {
ctx.log('white-bg: 透明 PNG 为 ' + kb(res.size) + ',超过上限 ' + kb(maxBytes) + '(PNG 无压缩参数,已照常输出)')
}
return res
}
return encodeWithLimit(canvas, format, quality, maxBytes)
}
// 命名用真实边长与真实编码格式(上游 autoWhiteBg 分支硬编码 _800x800 是 bug,这里按夹取后的实际边长命名;
// 扩展名同理取 blob.type —— 浏览器不支持 webp 时会回退 png,不能照抄设置值)
function outName(base, size, encoded, format) {
const ext = TYPE_EXT[encoded.type] || FORMATS[format].ext
return base + '_' + size + 'x' + size + '.' + ext
}
function readNumeric(key, fallback, min, max) {
return clamp(Number(ctx.settings.get(key)) || fallback, min, max)
}
async function runOne(nodeId, nodeName) {
const img = await resolveImage(nodeId)
// 宿主可能把数值设置存成字符串,统一强转再夹取
const size = Math.round(readNumeric('bgSize', 800, 64, 4096))
const ratio = readNumeric('ratioPct', 80, 10, 100) / 100
const quality = readNumeric('quality', 82, 1, 100) / 100
const maxKB = Number(ctx.settings.get('maxKB'))
const maxBytes = Number.isFinite(maxKB) && maxKB > 0 ? Math.round(maxKB * 1024) : 0
const dual = Boolean(ctx.settings.get('dual'))
const replace = Boolean(ctx.settings.get('replace'))
const base = String(nodeName || 'image').replace(/\.[^.]+$/, '') || 'image'
let targets
if (dual) {
// 双版本下「覆盖原节点」没意义(两个版本只能覆盖一个位置),按文档忽略并留痕
if (replace) ctx.log('white-bg: 双版本模式总是新建节点,「覆盖原节点」已忽略')
targets = DUAL_TARGETS
} else {
const rawFormat = ctx.settings.get('format')
let format = normalizeFormat(rawFormat)
if (!format) {
ctx.log('white-bg: 未知导出格式 ' + JSON.stringify(String(rawFormat)) + ',回退 jpeg(可选 png / jpeg / webp)')
format = 'jpeg'
}
// 透明底与不支持的格式冲突:jpeg 没有 alpha 通道,用它画透明底会变成黑块 —— 强制填白并留痕。
const wantsTransparent = Boolean(ctx.settings.get('transparent'))
const transparent = wantsTransparent && FORMATS[format].alpha
if (wantsTransparent && !FORMATS[format].alpha) {
ctx.log('white-bg: ' + format + ' 不支持透明通道,已自动改填白底')
}
targets = [{ format: format, transparent: transparent, allowOversize: false }]
}
const made = []
const errors = []
for (const target of targets) {
try {
const canvas = composeCanvas(img, size, ratio, target.transparent)
const encoded = await encodeTarget(canvas, target.format, quality, maxBytes, target.allowOversize)
const name = outName(base, size, encoded, target.format)
if (replace && !dual) {
if (!ctx.canvas.setNodeImage(nodeId, encoded.dataUrl)) throw new Error('写回画布失败')
made.push('覆盖当前节点')
} else {
const created = ctx.canvas.createImageNode({ dataUrl: encoded.dataUrl, name: name })
if (!created) throw new Error('写回画布失败')
made.push(name)
}
ctx.log('white-bg: ' + name + ' ' + kb(encoded.size))
} catch (error) {
errors.push(error && error.message ? error.message : String(error))
}
}
if (!made.length && errors.length) throw new Error(errors[0])
// 部分成功:节点已经建好了,但要把失败原因说清楚(宿主只把 throw 显示成红色提示,这是唯一通道)
if (errors.length) throw new Error(errors.join(';') + '(已生成:' + made.join('、') + ')')
return dual ? made : (replace ? true : made[0])
}
ctx.nodeActions.register({
id: 'white-bg-node',
title: '白底图',
icon: 'vector-square',
appliesTo: function (node) { return Boolean(node) && node.type === 'ref' },
run: function (node) { return runOne(node.id, node.name) },
})
ctx.commands.register({
id: 'white-bg-selected',
title: '白底图:选中节点',
icon: 'vector-square',
run: function () {
const selected = ctx.canvas.getSelectedNode()
if (!selected) return Promise.reject(new Error('请先选中一个带图的节点'))
return runOne(selected.id, selected.name)
},
})
return {}
})
})(typeof window !== 'undefined' ? window : globalThis)
@@ -0,0 +1,107 @@
// iwb-plugin: 鲜艺抠图 —— 调用本机抠图服务(POST {apiUrl}/rmbg?crop=)把选中节点的图抠成透明底,写回为新的参考图节点。
// 契约来源:iwb-plaus v3.1.3 的 background.js(二进制进、PNG 字节出,无 token/无 JSON)。
;(function (global) {
'use strict'
var DEFAULT_API = 'http://localhost:30092'
var DEFAULT_TIMEOUT = 120000
function toPositive(v, fallback) {
var n = Number(v)
return Number.isFinite(n) && n > 0 ? n : fallback
}
function trimUrl(v) {
return String(v || DEFAULT_API).trim().replace(/\/+$/, '') || DEFAULT_API
}
function base64ToBytes(dataUrl) {
var s = String(dataUrl || '')
var comma = s.indexOf(',')
var bin = global.atob(comma >= 0 ? s.slice(comma + 1) : s)
var out = new Uint8Array(bin.length)
for (var i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
return out
}
function bytesToDataUrl(buffer) {
var bytes = new Uint8Array(buffer)
var chunk = 0x8000
var text = ''
for (var i = 0; i < bytes.length; i += chunk) {
text += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk))
}
return 'data:image/png;base64,' + global.btoa(text)
}
global.IWBPluginHost.register({
id: 'xianyi-cutout',
name: '鲜艺抠图',
version: '1.0.3',
apiVersion: 1,
capabilities: ['commands', 'canvas', 'canvasWrite', 'nodeActions'],
settings: {
apiUrl: { type: 'text', label: '本地服务地址', desc: 'CSP 仅放行 127.0.0.1 / localhost 的 30092 端口;改到别的 host 或端口会被拦。', default: DEFAULT_API },
crop: { type: 'boolean', label: '抠图后裁掉多余透明像素', desc: '对应接口的 crop 参数,默认开启。', default: true },
timeoutMs: { type: 'number', label: '超时(毫秒)', desc: '原扩展没有超时;这里补上,避免服务无响应时永久挂起。', default: DEFAULT_TIMEOUT },
},
}, function (ctx) {
async function cutoutOne(nodeId) {
const image = await ctx.canvas.getNodeImage(nodeId)
if (!image || !image.dataUrl) throw new Error('该节点没有可编码的图片(请选中带图的参考图或输出节点)')
const apiUrl = trimUrl(ctx.settings.get('apiUrl'))
const crop = ctx.settings.get('crop') ? 'true' : 'false'
const timeoutMs = toPositive(ctx.settings.get('timeoutMs'), DEFAULT_TIMEOUT)
const controller = typeof global.AbortController === 'function' ? new global.AbortController() : null
const timer = controller ? global.setTimeout(function () { try { controller.abort() } catch (e) { /* ignore */ } }, timeoutMs) : null
let response
try {
response = await global.fetch(apiUrl + '/rmbg?crop=' + crop, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: base64ToBytes(image.dataUrl),
signal: controller ? controller.signal : undefined,
})
} catch (e) {
throw new Error('连不上本地抠图服务(' + apiUrl + '):' + String((e && e.message) || e))
} finally {
if (timer) global.clearTimeout(timer)
}
if (!response.ok) {
const detail = await response.text().catch(function () { return '' })
throw new Error('抠图服务返回 ' + response.status + (detail ? ':' + String(detail).slice(0, 120) : ''))
}
const dataUrl = bytesToDataUrl(await response.arrayBuffer())
const selected = ctx.canvas.getSelectedNode()
const base = String((selected && selected.name) || 'image').replace(/\.[^.]+$/, '') || 'image'
const created = ctx.canvas.createImageNode({ dataUrl: dataUrl, name: base + '_cutout.png' })
if (!created) throw new Error('写回画布失败')
return created
}
ctx.commands.register({
id: 'cutout-selected',
title: '抠图:选中节点',
icon: 'scissors',
run: function () {
const selected = ctx.canvas.getSelectedNode()
if (!selected) return Promise.reject(new Error('请先选中一个带图的节点'))
return cutoutOne(selected.id)
},
})
ctx.nodeActions.register({
id: 'cutout-node',
title: '抠图',
icon: 'scissors',
appliesTo: function (node) { return Boolean(node) && node.type === 'ref' },
run: function (node) { return cutoutOne(node.id) },
})
return {}
})
})(typeof window !== 'undefined' ? window : globalThis)
+9 -1
View File
@@ -27,6 +27,7 @@ fs.mkdirSync(path.join(dist, 'vendor'), { recursive: true })
// 顺序即加载序(各模块通过 window.IWB* 在运行时互相依赖),切勿排序/改动
const sourceModules = [
'runtime-desktop-bridge.js',
'image-format.js',
'image-admit.js',
'image-dedupe.js',
@@ -35,12 +36,14 @@ const sourceModules = [
'clipboard-paste.js',
'clipboard-copy.js',
'clipboard-paste-once.js',
'clipboard-native.js',
'generation-size-policy.js',
'generation-request-shape.js',
'image-preview-derive.js',
'canvas-actions.js',
'canvas-node-factory.js',
'storage-contract.js',
'storage-file.js',
'storage-runtime.js',
'storage-migrations.js',
'storage-result.js',
@@ -86,6 +89,8 @@ const sourceModules = [
'generation-results-store.js',
'ui-groups-sidebar.js',
'ui-lib-sidebar.js',
'ui-desktop-shell.js',
'ui-appearance.js',
'ui-workspace-tabs.js',
'ui-app-chrome.js',
'ui-workbench-hooks.js',
@@ -95,7 +100,11 @@ const sourceModules = [
'workspace-list.js',
'workspace-purge.js',
'generation-provider-ping.js',
'runtime-plugin-loader.js',
'runtime-plugin-market.js',
'runtime-plugin-backup.js',
'ui-canvas-view.js',
'ui-confirm.js',
'ui-settings-sections.js',
'ui-settings-tab-diag.js',
'ui-settings-modal.js',
@@ -161,7 +170,6 @@ const minifiedCss = transformSync(fs.readFileSync(path.join(root, 'style.css'),
fs.writeFileSync(path.join(dist, 'style.css'), minifiedCss)
fs.copyFileSync(path.join(root, 'favicon.svg'), path.join(dist, 'favicon.svg'))
fs.copyFileSync(path.join(root, '_headers'), path.join(dist, '_headers'))
// PWA(2026-11-07):可安装 —— manifest + 图标(iOS 额外要 apple-touch-icon 的 PNG)
for (const f of ['manifest.webmanifest', 'icon-192.png', 'icon-512.png', 'apple-touch-icon.png']) {
fs.copyFileSync(path.join(root, f), path.join(dist, f))
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env node
'use strict'
// 桌面版专用:把 plugins/runtime/ 下的运行时插件拷进 dist/plugins/。
// 网页版插件由 Cloudflare KV 在 /plugins/* 提供;桌面端没有服务端,只能随包发布。
// 刻意不改 scripts/build.js(上游文件),单独一步执行,保持桌面侧差异最小。
const fs = require('fs')
const path = require('path')
const root = path.resolve(__dirname, '..')
const src = path.join(root, 'plugins', 'runtime')
const dst = path.join(root, 'dist', 'plugins')
if (!fs.existsSync(src)) {
console.error('[copy-plugins] 缺少 plugins/runtime,无法打包运行时插件')
process.exit(1)
}
fs.mkdirSync(dst, { recursive: true })
let count = 0
for (const name of fs.readdirSync(src)) {
fs.copyFileSync(path.join(src, name), path.join(dst, name))
count++
}
// 索引与插件文件必须同源同包:应用按 index.json 里的 filename 去 /plugins/ 取
fs.copyFileSync(path.join(root, 'plugins', 'index.json'), path.join(dst, 'index.json'))
console.log('[copy-plugins] 已拷入 ' + count + ' 个插件 → dist/plugins/')
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env node
'use strict'
// 生成插件市场展示页:market/index.json → market.html(纯静态,无后端)
// 设计目标:与下载页同一套视觉;卡片墙 + 搜索 + 标签筛选;「安装」只在应用内做,这里只展示。
const fs = require('fs')
const path = require('path')
const root = path.resolve(__dirname, '..')
const index = JSON.parse(fs.readFileSync(path.join(root, 'market', 'index.json'), 'utf8'))
const list = Array.isArray(index.plugins) ? index.plugins : []
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
const tags = []
for (const p of list) for (const t of (p.tags || [])) if (tags.indexOf(t) < 0) tags.push(t)
const kb = (n) => n >= 1024 * 1024 ? (n / 1048576).toFixed(1) + ' MB' : Math.max(1, Math.round(n / 1024)) + ' KB'
const card = (p) => `
<article class="card" data-name="${esc((p.name + ' ' + p.id + ' ' + p.desc + ' ' + (p.tags || []).join(' ')).toLowerCase())}" data-tags="${esc((p.tags || []).join(','))}">
<div class="card-head">
<span class="avatar" style="background:${esc(p.color || '#eef2f6')}">${esc(p.icon || '◻')}</span>
<div class="card-title">
<h3>${esc(p.name)}</h3>
<div class="sub">${esc(p.author === 'official' ? '官方' : p.author)} · v${esc(p.version)} · ${kb(p.size || 0)}</div>
</div>
</div>
<p class="desc">${esc(p.desc)}</p>
<div class="tags">${(p.tags || []).map((t) => `<span class="tag">${esc(t)}</span>`).join('')}</div>
</article>`
const html = `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>插件市场 · Image Workbench</title>
<style>
:root { --fg:#1a1a1a; --fg2:#6b6b6b; --line:#ececec; --bg:#fff; --chip:#f4f4f4; }
@media (prefers-color-scheme: dark) {
:root { --fg:#f2f2f2; --fg2:#9a9a9a; --line:#2a2a2a; --bg:#111; --chip:#1d1d1d; }
}
* { box-sizing:border-box; }
body { margin:0; background:var(--bg); color:var(--fg); font:15px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; }
.wrap { max-width:1080px; margin:0 auto; padding:56px 24px 80px; }
header h1 { font-size:28px; margin:0 0 6px; letter-spacing:-.02em; }
header p { margin:0; color:var(--fg2); font-size:14px; }
.toolbar { display:flex; gap:12px; margin:28px 0 18px; flex-wrap:wrap; align-items:center; }
input[type=search] { flex:1 1 260px; min-width:220px; padding:10px 14px; border:1px solid var(--line); border-radius:10px; background:var(--bg); color:var(--fg); font-size:14px; outline:none; }
input[type=search]:focus { border-color:#111; }
.chips { display:flex; gap:8px; flex-wrap:wrap; }
.chip { padding:6px 12px; border:1px solid var(--line); border-radius:999px; background:transparent; color:var(--fg2); font-size:13px; cursor:pointer; }
.chip.on { background:#111; color:#fff; border-color:#111; }
@media (prefers-color-scheme: dark) { .chip.on { background:#f2f2f2; color:#111; border-color:#f2f2f2; } }
.grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(300px,1fr)); gap:16px; }
.card { border:1px solid var(--line); border-radius:14px; padding:18px; display:flex; flex-direction:column; gap:12px; }
.card-head { display:flex; gap:12px; align-items:center; }
.avatar { width:44px; height:44px; border-radius:12px; display:flex; align-items:center; justify-content:center; font-size:22px; flex:0 0 44px; }
.card-title h3 { margin:0; font-size:16px; font-weight:600; }
.card-title .sub { color:var(--fg2); font-size:12.5px; margin-top:2px; }
.desc { margin:0; color:var(--fg2); font-size:13.5px; min-height:42px; }
.tags { display:flex; gap:6px; flex-wrap:wrap; margin-top:auto; }
.tag { padding:2px 9px; border-radius:999px; background:var(--chip); color:var(--fg2); font-size:12px; }
.empty { color:var(--fg2); padding:40px 0; text-align:center; }
footer { margin-top:40px; color:var(--fg2); font-size:13px; border-top:1px solid var(--line); padding-top:18px; }
code { background:var(--chip); padding:1px 6px; border-radius:6px; font-size:12.5px; }
</style>
</head>
<body>
<div class="wrap">
<header>
<h1>插件市场</h1>
<p>Image Workbench 插件 · 共 <b>${list.length}</b> 个 · 在应用内「设置 → 插件」安装</p>
</header>
<div class="toolbar">
<input id="q" type="search" placeholder="搜索插件,例如:出图、抠图、矢量…" autocomplete="off">
<div class="chips" id="chips">
<button class="chip on" data-tag="">全部</button>
${tags.map((t) => `<button class="chip" data-tag="${esc(t)}">${esc(t)}</button>`).join('')}
</div>
</div>
<div class="grid" id="grid">${list.map(card).join('')}</div>
<div class="empty" id="empty" hidden>没有匹配的插件</div>
<footer>
安装方式:应用内 <code>设置 → 插件 → 可安装(市场)</code> 点「安装」,重启后生效。<br>
插件目录:<code>~/Documents/ImageWorkbench/plugins/</code>(Windows:<code>%USERPROFILE%\\Documents\\ImageWorkbench\\plugins\\</code>)
</footer>
</div>
<script>
var q = document.getElementById('q')
var grid = document.getElementById('grid')
var empty = document.getElementById('empty')
var chips = document.getElementById('chips')
var activeTag = ''
function apply () {
var kw = (q.value || '').trim().toLowerCase()
var shown = 0
Array.prototype.forEach.call(grid.children, function (el) {
var okKw = !kw || el.dataset.name.indexOf(kw) >= 0
var okTag = !activeTag || (',' + el.dataset.tags + ',').indexOf(',' + activeTag + ',') >= 0
var ok = okKw && okTag
el.hidden = !ok
if (ok) shown++
})
empty.hidden = shown > 0
}
q.addEventListener('input', apply)
chips.addEventListener('click', function (e) {
var b = e.target.closest('.chip')
if (!b) return
Array.prototype.forEach.call(chips.children, function (x) { x.classList.remove('on') })
b.classList.add('on')
activeTag = b.dataset.tag || ''
apply()
})
</script>
</body>
</html>
`
fs.writeFileSync(path.join(root, 'market', 'index.html'), html)
console.log('market/index.html 已生成(' + list.length + ' 个插件 / ' + tags.length + ' 个标签)')
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env node
'use strict'
// 生成插件市场索引:plugins/index.json + plugins/meta.json → market/index.json + market/plugins/*
// 产物用于 market.maqiart.eu.org(纯静态)。
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
const root = path.resolve(__dirname, '..')
const man = JSON.parse(fs.readFileSync(path.join(root, 'plugins', 'index.json'), 'utf8'))
const meta = JSON.parse(fs.readFileSync(path.join(root, 'plugins', 'meta.json'), 'utf8'))
const out = path.join(root, 'market')
fs.mkdirSync(path.join(out, 'plugins'), { recursive: true })
const sha = (buf) => crypto.createHash('sha256').update(buf)
const plugins = []
for (const e of man) {
const src = path.join(root, 'plugins', 'runtime', e.file)
if (!fs.existsSync(src)) { console.warn('缺少产物:' + e.file); continue }
const buf = fs.readFileSync(src)
fs.writeFileSync(path.join(out, 'plugins', e.file), buf)
const m = meta[e.id] || {}
plugins.push({
id: e.id, name: m.name || e.id, desc: m.desc || '', author: m.author || 'official', icon: m.icon || '', color: m.color || '', tags: Array.isArray(m.tags) ? m.tags : [],
version: e.version, apiVersion: 1,
file: 'plugins/' + e.file,
size: buf.length,
sha256: sha(buf).digest('hex'),
integrity: 'sha256-' + sha(buf).digest('base64'),
})
}
const index = { version: 1, updatedAt: new Date().toISOString(), plugins: plugins }
fs.writeFileSync(path.join(out, 'index.json'), JSON.stringify(index, null, 2) + '\n')
console.log('market/index.json:' + plugins.length + ' 个插件')
for (const p of plugins) console.log(' ' + p.id.padEnd(16) + p.version.padEnd(8) + (p.size + ' B'))
+156
View File
@@ -0,0 +1,156 @@
#!/usr/bin/env node
'use strict'
// 下载页生成器:site/releases.json → site/index.html
// 只做纯静态输出(无外链、无框架),部署到 NAS 的 nginx 静态目录。
const fs = require('fs')
const path = require('path')
const root = path.resolve(__dirname, '..')
const inFile = process.argv[2] || path.join(root, 'site', 'releases.json')
const outFile = process.argv[3] || path.join(root, 'site', 'download', 'index.html')
const data = JSON.parse(fs.readFileSync(inFile, 'utf8'))
const PLATFORMS = [
{ key: 'darwin-aarch64', label: 'macOS · Apple Silicon', hint: 'M1 / M2 / M3 / M4' },
{ key: 'darwin-x86_64', label: 'macOS · Intel', hint: 'x86_64' },
{ key: 'windows-x86_64', label: 'Windows · x64', hint: '需要 WebView2' },
]
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
const fmtSize = (n) => (!n ? '' : (n / 1048576).toFixed(1) + ' MB')
function platformRow (rel, p) {
const item = rel && rel.platforms ? rel.platforms[p.key] : null
const meta = item
? '版本 ' + esc(rel.version) + ' · ' + fmtSize(item.size) + ' · .' + esc(item.kind || 'dmg')
: ''
const action = item
? '<a class="btn" href="/' + esc(item.file) + '">下载</a>'
: '<span class="muted">暂未提供</span>'
const hash = item && item.sha256
? '<div class="hash">sha256 ' + esc(item.sha256.slice(0, 16)) + '…</div>'
: ''
return ' <div class="row">\n' +
' <div class="name">' + esc(p.label) + '<div class="hint">' + esc(p.hint) + '</div></div>\n' +
' <div class="meta">' + meta + hash + '</div>\n' +
' ' + action + '\n' +
' </div>'
}
const latest = data.releases && data.releases[0]
const history = (data.releases || []).map((r) => {
const avail = Object.keys(r.platforms || {}).map((k) => {
const p = PLATFORMS.find((x) => x.key === k)
return p ? p.label : k
})
return ' <div class="row">\n' +
' <div class="name">' + esc(r.version) + (r.notes ? '<div class="hint">' + esc(r.notes) + '</div>' : '') + '</div>\n' +
' <div class="meta">' + esc(r.date || '') + '<div class="hint">' + esc(avail.join(' / ') || '—') + '</div></div>\n' +
' </div>'
}).join('\n')
const html = `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>${esc(data.app)} · 下载</title>
<link rel="stylesheet" href="/assets/style.css?v=" + encodeURIComponent(latest.version + '-' + Date.now().toString(36)) + "">
<style>
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}
.dlwrap{max-width:760px;margin:0 auto;padding:48px 0 64px}
h1{font-size:27px;margin:0 0 6px;letter-spacing:-.01em}
.sub{color:var(--muted);margin:0 0 34px}
h2{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);font-weight:600;margin:38px 0 2px}
.row{display:flex;align-items:center;gap:16px;padding:15px 0;border-bottom:1px solid var(--line)}
.row:first-of-type{border-top:1px solid var(--line)}
.name{flex:1 1 auto;font-weight:550}
.hint{color:var(--muted);font-size:12.5px;font-weight:400;margin-top:2px}
.meta{flex:0 0 auto;text-align:right;color:var(--muted);font-size:13px}
.hash{font-size:11.5px;opacity:.75;margin-top:2px;font-variant-numeric:tabular-nums}
.btn{flex:0 0 auto;font-size:13px;padding:7px 18px;border-radius:8px;background:var(--brand);color:var(--bg);text-decoration:none}
.btn:hover{opacity:.88}
.muted{flex:0 0 auto;font-size:13px;color:var(--muted);opacity:.7}
.foot{margin-top:46px;color:var(--muted);font-size:12.5px;line-height:1.8}
.foot a{color:inherit}
code{font-size:12.5px}
.steps{margin:6px 0 0;padding-left:22px;color:var(--fg2);font-size:13.5px;line-height:1.9}
.steps li{margin:2px 0}
.steps b{color:var(--fg);font-weight:600}
pre.cmd{margin:10px 0 0;padding:10px 12px;background:var(--bg2);border:1px solid var(--line);border-radius:8px;overflow-x:auto}
pre.cmd code{font-size:12px;color:var(--fg)}
.note{margin:10px 0 0;color:var(--muted);font-size:12.5px;line-height:1.8}
</style>
</head>
<body>
<nav><div class="wrap inner">
<a class="brand" href="/"><span class="dot">IW</span>Image Workbench</a>
<div class="links">
<a href="/">首页</a>
<a href="/download/" class="on">下载</a>
<a href="/plugins/">插件</a>
<a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码</a>
</div>
<div class="right">
<a class="btn" href="/plugins/">插件市场</a>
<a class="btn primary" href="/download/">下载</a>
</div>
</div></nav>
<div class="wrap"><div class="dlwrap">
<h1>${esc(data.app)}</h1>
<p class="sub">${esc(data.subtitle || '')}</p>
<h2>下载</h2>
${PLATFORMS.map((p) => platformRow(latest, p)).join('\n')}
<h2>系统要求</h2>
<div class="row">
<div class="name">macOS 12 及以上 / Windows 10 1803 及以上(含 WebView2)
<div class="hint">数据全部保存在本地目录 <code>~/Documents/ImageWorkbench</code>,可整目录备份与迁移。</div>
</div>
</div>
<h2>安装步骤(macOS)</h2>
<ol class="steps">
<li>下载上面的 <b>.dmg</b>(Apple 芯片选 Apple Silicon;老 Intel 机器选 Intel)。</li>
<li>双击打开 dmg,把 <b>Image Workbench</b> 图标拖进「应用程序」文件夹。</li>
<li>第一次启动:打开「应用程序」,<b>右键点图标 → 打开</b>,弹窗里再点一次「打开」。</li>
<li>如果提示「已损坏」或「无法验证开发者」:打开「终端」,粘贴执行下面这条命令,然后重新打开应用。</li>
</ol>
<pre class="cmd"><code>xattr -dr com.apple.quarantine "/Applications/image-workbench.app"</code></pre>
<p class="note">说明:安装包未做 Apple 公证($99/年开发者账号),所以第一次需要手动放行;这一步只做一次。<br>
之后有新版本时,应用内 <b>设置 → 通用 → 版本与更新 → 检查更新</b> 就能一键升级,不用再下载安装包。</p>
<h2>安装步骤(Windows)</h2>
<ol class="steps">
<li>下载 <b>.exe</b>(NSIS 安装包,按当前用户安装,不需要管理员权限)。</li>
<li>双击运行;若出现「Windows 已保护你的电脑」,点「更多信息 → 仍要运行」。</li>
<li>安装完成后从开始菜单启动;数据在 <code>%USERPROFILE%\Documents\ImageWorkbench</code>。</li>
</ol>
<h2>历史版本</h2>
${history}
<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> · 更新于 ${esc((data.updatedAt || '').slice(0, 10))}
</div>
</div></div>
<footer><div class="wrap">
<div class="cols">
<div><div style="color:#fff;font-weight:640;margin-bottom:8px">Image Workbench</div>
<div style="font-size:13px;line-height:1.8">本地优先的 AI 生图无限画布。图片、提示词与模型配置全部留在你自己的电脑里。</div></div>
<div><h4>产品</h4><a href="/">首页</a><a href="/download/">下载</a><a href="/plugins/">插件市场</a></div>
<div><h4>资源</h4><a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码仓库</a><a href="https://git.maqiart.eu.org/malongan/iwb-plugins-desktop" target="_blank" rel="noopener">插件仓库</a><a href="/updates/latest.json" target="_blank" rel="noopener">更新源</a></div>
<div><h4>说明</h4><a href="/download/">安装步骤</a><a href="/plugins/">插件安装</a></div>
</div>
<div class="copy"><span>© Image Workbench</span><span>数据保存在本地 · 不上传任何图片</span></div>
</div></footer>
</body>
</html>
`
fs.mkdirSync(path.dirname(outFile), { recursive: true })
fs.writeFileSync(outFile, html)
console.log('已生成 ' + path.relative(root, outFile) + '(' + data.releases.length + ' 个版本 / ' + Object.keys((latest && latest.platforms) || {}).length + ' 个平台)')
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env node
'use strict'
// 站点生成器:用 site/_home.tpl.html 与 site/_plugins.tpl.html 渲染首页 / 插件页,
// 数据来自 site/releases.json(版本)与 market/index.json(插件)。
const fs = require('fs')
const path = require('path')
const root = path.resolve(__dirname, '..')
const site = path.join(root, 'site')
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
const mb = (n) => (Number(n) / 1048576).toFixed(1) + ' MB'
const data = JSON.parse(fs.readFileSync(path.join(site, 'releases.json'), 'utf8'))
const rel = Array.isArray(data.releases) ? data.releases.slice() : (Array.isArray(data) ? data.slice() : [])
rel.sort((a, b) => String(b.version).localeCompare(String(a.version), undefined, { numeric: true }))
const latest = rel[0] || { version: '', platforms: {} }
const V = esc(latest.version)
const STAMP = encodeURIComponent(V + '-' + Date.now().toString(36))
const marketFile = path.join(root, 'market', 'index.json')
const market = fs.existsSync(marketFile) ? JSON.parse(fs.readFileSync(marketFile, 'utf8')) : { plugins: [] }
const plugins = Array.isArray(market.plugins) ? market.plugins : []
const nav = (active) => [
'<nav><div class="wrap inner">',
' <a class="brand" href="/"><span class="dot">IW</span>Image Workbench</a>',
' <div class="links">',
' <a href="/"' + (active === 'home' ? ' class="on"' : '') + '>首页</a>',
' <a href="/download/"' + (active === 'download' ? ' class="on"' : '') + '>下载</a>',
' <a href="/plugins/"' + (active === 'plugins' ? ' class="on"' : '') + '>插件</a>',
' <a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码</a>',
' </div>',
' <div class="right">',
' <a class="btn" href="/plugins/">插件市场</a>',
' <a class="btn primary" href="/download/">下载 v' + V + '</a>',
' </div>',
'</div></nav>',
].join('\n')
const footer = [
'<footer><div class="wrap">',
' <div class="cols">',
' <div><div style="color:#fff;font-weight:640;margin-bottom:8px">Image Workbench</div>',
' <div style="font-size:13px;line-height:1.8">本地优先的 AI 生图无限画布。图片、提示词与模型配置全部留在你自己的电脑里。</div></div>',
' <div><h4>产品</h4><a href="/">首页</a><a href="/download/">下载</a><a href="/plugins/">插件市场</a></div>',
' <div><h4>资源</h4><a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码仓库</a><a href="https://git.maqiart.eu.org/malongan/iwb-plugins-desktop" target="_blank" rel="noopener">插件仓库</a><a href="/updates/latest.json" target="_blank" rel="noopener">更新源</a></div>',
' <div><h4>说明</h4><a href="/download/">安装步骤</a><a href="/plugins/">插件安装</a></div>',
' </div>',
' <div class="copy"><span>© ' + new Date().getFullYear() + ' Image Workbench</span><span>数据保存在本地 · 不上传任何图片</span></div>',
'</div></footer>',
].join('\n')
const card = (p) => [
' <div class="pcard" data-name="' + esc((p.name + ' ' + p.id + ' ' + (p.desc || '') + ' ' + (p.tags || []).join(' ')).toLowerCase()) + '" data-tags="' + esc((p.tags || []).join(',')) + '">',
' <div class="head"><span class="av" style="background:' + esc(p.color || '#eef2f6') + '">' + esc(p.icon || '◻') + '</span>',
' <div><div class="nm">' + esc(p.name || p.id) + '</div><div class="ver">v' + esc(p.version || '') + ' · ' + esc(p.author === 'official' ? '官方' : (p.author || '')) + '</div></div></div>',
' <div class="desc">' + esc(p.desc || '') + '</div>',
' <div class="tags">' + (p.tags || []).map((t) => '<span class="tag">' + esc(t) + '</span>').join('') + '</div>',
' </div>',
].join('\n')
const feats = [
['💻', '#eef2ff', '本地优先', '图片与数据保存在 ~/Documents/ImageWorkbench,不经服务器中转;可整目录备份、迁移到新电脑。'],
['🕸️', '#fff7ed', '节点式无限画布', '参考图 → 提示词 → 生成 → 图库,用连线把工作流串起来;一张画布容纳整条生产线。'],
['🧩', '#ecfdf5', '插件按需安装', '应用本体不含插件,需要什么装什么;可随时启停,关闭后入口自动隐藏。'],
]
const featCards = feats.map((f) => [
' <div class="card"><div class="ico" style="background:' + f[1] + '">' + f[0] + '</div>',
' <h3>' + f[2] + '</h3><p>' + f[3] + '</p></div>',
].join('\n')).join('\n')
const dlCards = [
['darwin-aarch64', 'macOS · Apple Silicon', 'M1 / M2 / M3 / M4'],
['darwin-x86_64', 'macOS · Intel', 'x86_64'],
['windows-x86_64', 'Windows · x64', '需要 WebView2'],
].map(([key, label, hint]) => {
const p = (latest.platforms || {})[key]
if (!p) return '<div class="none"><div class="n">' + label + '</div><div class="s">暂未提供</div></div>'
return '<a href="/' + esc(p.file) + '"><div class="n">' + label + '</div><div class="s">' + hint + ' · ' + mb(p.size) + ' · .' + esc(String(p.file).split('.').pop()) + '</div></a>'
}).join('\n ')
const tags = []
for (const p of plugins) for (const t of (p.tags || [])) if (tags.indexOf(t) < 0) tags.push(t)
const tagChips = tags.map((t) => '<button class="tag" data-tag="' + esc(t) + '" style="cursor:pointer;padding:5px 12px">' + esc(t) + '</button>').join('\n ')
function render(tpl, map) {
let out = fs.readFileSync(path.join(site, tpl), 'utf8')
for (const k of Object.keys(map)) out = out.split('<!--' + k + '-->').join(map[k])
return out
}
let home = render('_home.tpl.html', {
NAV: nav('home'),
FOOTER: footer,
VERSION: V,
PLUGIN_COUNT: String(plugins.length),
FEAT_CARDS: featCards,
PLUGIN_CARDS: plugins.slice(0, 6).map((p) => card(p).replace(/^\s+/, ' ')).join('\n'),
DL_CARDS: dlCards,
})
home = home.replace('/assets/style.css', '/assets/style.css?v=' + STAMP).replace('/assets/painting.jpg', '/assets/painting.jpg?v=' + STAMP)
fs.writeFileSync(path.join(site, 'index.html'), home)
let pluginsPage = render('_plugins.tpl.html', {
NAV: nav('plugins'),
FOOTER: footer,
PLUGIN_COUNT: String(plugins.length),
TAG_CHIPS: tagChips,
PLUGIN_CARDS: plugins.map(card).join('\n'),
})
fs.mkdirSync(path.join(site, 'plugins'), { recursive: true })
pluginsPage = pluginsPage.replace('/assets/style.css', '/assets/style.css?v=' + STAMP)
fs.writeFileSync(path.join(site, 'plugins', 'index.html'), pluginsPage)
fs.writeFileSync(path.join(site, 'plugins-index.json'), JSON.stringify(market, null, 2) + '\n')
console.log('站点已生成:首页 / 插件页(' + plugins.length + ' 个插件,' + tags.length + ' 个标签,版本 v' + V + ')')
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env bash
# 发布在线更新:签名构建(双架构)+ 上传产物 + 生成 latest.json
#
# 用法:
# ./scripts/publish-update.sh # 用 package.json 的版本
# ./scripts/publish-update.sh 3.25.3 # 先改版本再发布(等价于 set-version + 本脚本)
#
# 依赖:
# · 签名私钥:~/.config/iwb-updater.key(TAURI_SIGNING_PRIVATE_KEY)
# · 公钥已写进 src-tauri/tauri.conf.json → plugins.updater.pubkey
# · NAS 可 ssh(~/.ssh/id_ed25519_fnos)
#
# 产物:
# <target>/bundle/macos/image-workbench.app.tar.gz(.sig) ← 更新器用
# <target>/bundle/dmg/*.dmg ← 官网下载用
# https://download.maqiart.eu.org/updates/latest.json ← 更新源
set -euo pipefail
cd "$(dirname "$0")/.."
[ $# -ge 1 ] && node scripts/set-version.js "$1"
V=$(node -e "console.log(require('./package.json').version)")
KEY="${TAURI_SIGNING_PRIVATE_KEY:-$HOME/.config/iwb-updater.key}"
export TAURI_SIGNING_PRIVATE_KEY="$KEY"
export TAURI_SIGNING_PRIVATE_KEY_PASSWORD="${TAURI_SIGNING_PRIVATE_KEY_PASSWORD:-}"
export CARGO_HOME="${CARGO_HOME:-$PWD/.cargo-home}"
NAS_HOST="${NAS_HOST:-malongan@192.168.100.185}"
NAS_DIR="${NAS_DIR:-/vol8/web/iwb-download}"
SSH_KEY="${SSH_KEY:-$HOME/.ssh/id_ed25519_fnos}"
SCP="scp -i $SSH_KEY -o BatchMode=yes"
echo "== 1/4 构建 arm64(app + dmg,含签名)"
npx tauri build --bundles app,dmg >/dev/null
echo "== 2/4 构建 x86_64(app + dmg,含签名)"
npx tauri build --target x86_64-apple-darwin --bundles app,dmg >/dev/null
ARM="src-tauri/target/release/bundle"
INT="src-tauri/target/x86_64-apple-darwin/release/bundle"
echo "== 3/4 上传产物"
TMP=$(mktemp -d)
cp "$ARM/macos/image-workbench.app.tar.gz" "$TMP/image-workbench_${V}_aarch64.app.tar.gz"
cp "$ARM/macos/image-workbench.app.tar.gz.sig" "$TMP/image-workbench_${V}_aarch64.app.tar.gz.sig"
cp "$INT/macos/image-workbench.app.tar.gz" "$TMP/image-workbench_${V}_x64.app.tar.gz"
cp "$INT/macos/image-workbench.app.tar.gz.sig" "$TMP/image-workbench_${V}_x64.app.tar.gz.sig"
$SCP "$TMP"/*.app.tar.gz* "$NAS_HOST:$NAS_DIR/updates/darwin-aarch64/" 2>/dev/null || true
$SCP "$TMP/image-workbench_${V}_aarch64.app.tar.gz" "$TMP/image-workbench_${V}_aarch64.app.tar.gz.sig" "$NAS_HOST:$NAS_DIR/updates/darwin-aarch64/"
$SCP "$TMP/image-workbench_${V}_x64.app.tar.gz" "$TMP/image-workbench_${V}_x64.app.tar.gz.sig" "$NAS_HOST:$NAS_DIR/updates/darwin-x86_64/"
$SCP "$ARM/dmg/image-workbench_${V}_aarch64.dmg" "$NAS_HOST:$NAS_DIR/updates/darwin-aarch64/"
$SCP "$INT/dmg/image-workbench_${V}_x64.dmg" "$NAS_HOST:$NAS_DIR/updates/darwin-x86_64/"
echo "== 4/4 生成 latest.json"
export SIG_ARM="$(cat "$ARM/macos/image-workbench.app.tar.gz.sig")"
export SIG_INT="$(cat "$INT/macos/image-workbench.app.tar.gz.sig")"
export UPD_VERSION="$V"
# Windows 包单独构建:全局 version 提升后,旧 windows 条目会变成「声明新版本、实际旧安装包」,
# 客户端会因 app-version 绑定不一致而拒绝安装。所以每次发布 mac 时明确提示并丢弃过期的非 darwin 条目,
# 等 Windows 包跟上再用 publish-windows-update.sh 合并回来。
curl -s -m 20 https://download.maqiart.eu.org/updates/latest.json -o /tmp/iwb-latest-prev.json 2>/dev/null || echo '{}' > /tmp/iwb-latest-prev.json
node -e '
const fs = require("fs")
let prev = {}
try { prev = JSON.parse(fs.readFileSync("/tmp/iwb-latest-prev.json", "utf8")) } catch (e) { prev = {} }
const stale = (prev.platforms ? Object.keys(prev.platforms) : []).filter(function (k) { return k.indexOf("darwin-") !== 0 && prev.version !== process.env.UPD_VERSION })
if (stale.length) console.log("将丢弃过期的非 darwin 平台条目:" + stale.join(","))
'
node -e '
const fs = require("fs")
const v = process.env.UPD_VERSION
const j = {
version: v,
notes: process.env.UPD_NOTES || "",
pub_date: new Date().toISOString(),
platforms: {
"darwin-aarch64": { signature: process.env.SIG_ARM, url: "https://download.maqiart.eu.org/updates/darwin-aarch64/image-workbench_" + v + "_aarch64.app.tar.gz" },
"darwin-x86_64": { signature: process.env.SIG_INT, url: "https://download.maqiart.eu.org/updates/darwin-x86_64/image-workbench_" + v + "_x64.app.tar.gz" },
},
}
fs.writeFileSync("/tmp/iwb-latest.json", JSON.stringify(j, null, 2))
console.log("latest.json -> v" + v)
'
$SCP /tmp/iwb-latest.json "$NAS_HOST:$NAS_DIR/updates/latest.json"
ssh -i "$SSH_KEY" -o BatchMode=yes "$NAS_HOST" "chmod -R a+rX $NAS_DIR"
echo "== 完成:https://download.maqiart.eu.org/updates/latest.json"
curl -s -m 15 https://download.maqiart.eu.org/updates/latest.json | head -c 200; echo
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
# 发布 Windows 更新:对 Windows 侧构建好的 *-setup.exe 重新签名(用本机正式私钥),
# 上传到 NAS,并写入 **独立** 的 updates/latest-windows.json(v3.25.15 起平台解耦:
# mac 的 latest.json 与 Windows 的 latest-windows.json 互不影响)。
#
# 用法:./scripts/publish-windows-update.sh "/path/to/image-workbench_3.25.3_x64-setup.exe"
#
# 背景(Tauri v2):Windows 的更新产物就是安装包本体 + 同名 .sig,没有 v1 的 *.nsis.zip。
# Windows 机器只需把 setup.exe 发过来,签名与发布都在本机完成,私钥不外传。
set -euo pipefail
cd "$(dirname "$0")/.."
EXE_IN="${1:?用法: publish-windows-update.sh <setup.exe 路径>}"
[ -f "$EXE_IN" ] || { echo "找不到文件:$EXE_IN"; exit 1; }
V=$(node -e "console.log(require('./package.json').version)")
KEY="${TAURI_SIGNING_PRIVATE_KEY:-$HOME/.config/iwb-updater.key}"
NAS_HOST="${NAS_HOST:-malongan@192.168.100.185}"
NAS_DIR="${NAS_DIR:-/vol8/web/iwb-download}"
SSH_KEY="${SSH_KEY:-$HOME/.ssh/id_ed25519_fnos}"
SCP="scp -i $SSH_KEY -o BatchMode=yes"
WORK=$(mktemp -d)
OUT="$WORK/image-workbench_${V}_x64-setup.exe"
cp "$EXE_IN" "$OUT"
echo "== 1/4 校验文件"
SIZE=$(stat -f%z "$OUT")
SHA=$(shasum -a 256 "$OUT" | awk '{print $1}')
echo " $OUT"
echo " size=$SIZE sha256=$SHA"
echo "== 2/4 用正式私钥签名"
npx tauri signer sign -f "$KEY" -p "${TAURI_SIGNING_PRIVATE_KEY_PASSWORD:-}" --app-version "$V" "$OUT" >/dev/null
SIG_FILE="$OUT.sig"
[ -f "$SIG_FILE" ] || { echo "签名失败:没有产出 $SIG_FILE"; exit 1; }
echo " .sig $(wc -c < "$SIG_FILE" | tr -d ' ') 字节"
echo "== 3/4 上传到 NAS"
ssh -i "$SSH_KEY" -o BatchMode=yes "$NAS_HOST" "mkdir -p $NAS_DIR/updates/windows-x86_64"
$SCP "$OUT" "$SIG_FILE" "$NAS_HOST:$NAS_DIR/updates/windows-x86_64/"
echo "== 4/4 写 latest-windows.json(平台独立)"
SIG=$(cat "$SIG_FILE")
URL="https://download.maqiart.eu.org/updates/windows-x86_64/image-workbench_${V}_x64-setup.exe"
export SIG URL APP_VERSION="$V"
node -e '
const fs = require("fs")
const p = process.argv[1]
const doc = {
version: process.env.APP_VERSION,
notes: process.env.NOTES || "在线更新",
pub_date: new Date().toISOString(),
platforms: { "windows-x86_64": { signature: process.env.SIG, url: process.env.URL } },
}
fs.writeFileSync(p, JSON.stringify(doc, null, 2))
console.log(" version", doc.version)
' "$WORK/latest-windows.json"
$SCP "$WORK/latest-windows.json" "$NAS_HOST:$NAS_DIR/updates/latest-windows.json"
ssh -i "$SSH_KEY" -o BatchMode=yes "$NAS_HOST" "chmod -R a+rX $NAS_DIR"
echo "== 完成"
curl -s -m 20 https://download.maqiart.eu.org/updates/latest-windows.json | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const j=JSON.parse(s);console.log("version",j.version);for(const k of Object.keys(j.platforms))console.log(" -",k,"sig",(j.platforms[k].signature||"").length,"bytes")})'
curl -s -o /dev/null -m 60 -w "exe:%{http_code} size:%{size_download}\n" "$URL"
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
# 桌面版一键发布:构建 dmg → 算 hash → 更新 releases.json → 生成页面 → 上传 NAS → 校验
set -euo pipefail
cd "$(dirname "$0")/.."
NAS_HOST="${NAS_HOST:-192.168.100.185}"
NAS_USER="${NAS_USER:-malongan}"
NAS_DIR="${NAS_DIR:-/vol8/web/iwb-download}"
SSH_KEY="${SSH_KEY:-$HOME/.ssh/id_ed25519_fnos}"
PLATFORM="${PLATFORM:-darwin-aarch64}"
SKIP_BUILD=0
NOTES=""
while [ $# -gt 0 ]; do
case "$1" in
--skip-build) SKIP_BUILD=1; shift ;;
--notes) NOTES="$2"; shift 2 ;;
*) echo "未知参数:$1"; exit 1 ;;
esac
done
VERSION=$(node -e "console.log(require('./src-tauri/tauri.conf.json').version)")
echo "版本:$VERSION"
if [ "$SKIP_BUILD" -eq 0 ]; then
echo "→ 构建 dmg…"
npx tauri build --bundles dmg
fi
DMG=$(ls -t src-tauri/target/release/bundle/dmg/*.dmg 2>/dev/null | head -1 || true)
if [ -z "$DMG" ]; then echo "找不到 dmg,先跑一次完整构建"; exit 1; fi
echo "产物:$DMG"
SIZE=$(stat -f%z "$DMG")
SHA=$(shasum -a 256 "$DMG" | awk '{print $1}')
BASE=$(basename "$DMG")
REMOTE_REL="updates/$PLATFORM/$BASE"
EXTRA=""
if [ -n "$NOTES" ]; then EXTRA="--notes $NOTES"; fi
node scripts/update-releases.js --version "$VERSION" --platform "$PLATFORM" \
--file "$REMOTE_REL" --size "$SIZE" --sha256 "$SHA" $EXTRA
node scripts/gen-release-page.js
echo "→ 上传到 ${NAS_USER}@${NAS_HOST}:$NAS_DIR"
ssh -i "$SSH_KEY" -o BatchMode=yes "${NAS_USER}@${NAS_HOST}" "mkdir -p $NAS_DIR/updates/$PLATFORM"
scp -i "$SSH_KEY" -o BatchMode=yes "$DMG" "${NAS_USER}@${NAS_HOST}:$NAS_DIR/updates/$PLATFORM/" >/dev/null
scp -i "$SSH_KEY" -o BatchMode=yes site/releases.json site/index.html "${NAS_USER}@${NAS_HOST}:$NAS_DIR/" >/dev/null
ssh -i "$SSH_KEY" -o BatchMode=yes "${NAS_USER}@${NAS_HOST}" "chmod -R a+rX $NAS_DIR"
echo "→ 校验公网"
CODE=$(curl -s -o /dev/null -m 20 -w '%{http_code}' "https://download.maqiart.eu.org/$REMOTE_REL")
SIZE2=$(curl -s -o /dev/null -m 40 -w '%{size_download}' "https://download.maqiart.eu.org/$REMOTE_REL")
echo " 页面 $(curl -s -o /dev/null -m 12 -w '%{http_code}' https://download.maqiart.eu.org/) 包 $CODE 远端 $SIZE2 B / 本地 $SIZE B"
[ "$CODE" = "200" ] && [ "$SIZE2" = "$SIZE" ] || { echo "✗ 校验失败"; exit 1; }
echo "✓ 发布完成:https://download.maqiart.eu.org/"
+52 -225
View File
@@ -1,238 +1,65 @@
/* serve-test.js —— e2e 用的本地静态服务器(v3.25.15 起脱离网页部署)
*
* 历史:本项目早期同时发布网页版(Cloudflare Pages),这个脚本会解析 `_headers` 下发 CSP、
* 并模拟 Pages Functions(/api/img、/plugins/*)。**现在是桌面客户端项目**,那些部署面已删除,
* 因此这里只保留「能跑 e2e」的最小职责:把 dist/ 当静态目录伺服。
*
* 桌面端的 CSP 由 src-tauri/tauri.conf.json 决定,e2e 不模拟 webview 的 CSP(要验就装真包)。
* 用法:node scripts/serve-test.js(IWB_LOCAL_PORT 可改端口,默认 8787)
*/
'use strict'
const http = require('http')
const fs = require('fs')
const path = require('path')
const cp = require('child_process')
const http = require('node:http')
const fs = require('node:fs')
const path = require('node:path')
const root = path.resolve(__dirname, '..')
const dist = path.join(root, 'dist')
const port = Number(process.env.IWB_LOCAL_PORT || 8787)
const mime = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.png': 'image/png', '.svg': 'image/svg+xml' }
// ---------- _headers → 响应头(本地 e2e 与 Cloudflare Pages 保持一致) ----------
// 动机:线上 CSP 是 connect-src 'self' https:,会拦掉 fetch(data:...) / CDN <script> / blob: Worker。
// 本地服务器原先不解析 _headers,这类「本地过、线上挂」的缺陷永远抓不到。这里把 _headers 的
// 路径分组按 Cloudflare Pages 语义应用到响应头(/* 组作用于所有响应,其它组按前缀/通配匹配)。
// 健壮性:_headers 缺失或解析不出任何分组时**不注入**并打印一行提示,绝不让服务器启动失败。
function parseHeaderGroups(text) {
const groups = []
let current = null
for (const raw of String(text == null ? '' : text).split(/\r?\n/)) {
const line = raw.replace(/\s+$/, '')
if (!line.trim() || /^\s*#/.test(line)) continue
if (/^\s/.test(line)) {
if (!current) continue // 缩进行但没有归属路径 → 忽略
const i = line.indexOf(':')
if (i <= 0) continue
const name = line.slice(0, i).trim()
const value = line.slice(i + 1).trim().replace(/[\r\n]+/g, ' ') // 防响应头注入
if (name) current.headers.push([name, value])
continue
}
current = { path: line.trim(), headers: [] }
groups.push(current)
}
return groups
}
// Cloudflare Pages 匹配规则(够用即可):/* 与 * 全局;/a/* 前缀;其余精确匹配。
function headerGroupMatches(pattern, pathname) {
const p = String(pattern || '').trim()
if (!p || p === '*' || p === '/*') return true
if (p.endsWith('*')) return pathname.indexOf(p.slice(0, -1)) === 0
return p === pathname
}
function loadHeaderGroups() {
const candidates = [path.join(root, '_headers'), path.join(dist, '_headers')]
for (const file of candidates) {
try {
if (!fs.existsSync(file)) continue
const groups = parseHeaderGroups(fs.readFileSync(file, 'utf8')).filter((g) => g.headers.length)
if (groups.length) return { groups, file }
} catch (e) { /* 换下一个候选 */ }
}
return null
}
const loaded = loadHeaderGroups()
const headerGroups = loaded ? loaded.groups : []
const cspApplied = headerGroups.some((g) => g.headers.some(([n]) => n.toLowerCase() === 'content-security-policy'))
if (loaded) {
console.log(`[serve-test] 已从 ${path.relative(root, loaded.file) || '_headers'} 注入响应头分组 ${headerGroups.length} 个${cspApplied ? '(含 Content-Security-Policy,本地与线上 CSP 一致)' : '(未解析到 CSP)'}`)
} else {
console.log('[serve-test] 未找到/无法解析 _headers:本次不注入任何安全响应头(本地环境与线上不一致,CSP 类缺陷不会被拦住)')
}
function securityHeadersFor(pathname, base) {
const out = Object.assign({}, base)
for (const group of headerGroups) {
if (!headerGroupMatches(group.path, pathname)) continue
for (const [name, value] of group.headers) out[name] = value // 后匹配的覆盖先匹配的(与 Pages 的后者优先一致)
}
return out
}
// ---------- Pages Functions 本地模拟(2026-10-20 加,审计 H1 的护栏) ----------
//
// 动机:Cloudflare Pages 的 `_headers` **不作用于 Functions 响应**
// (https://developers.cloudflare.com/pages/configuration/headers/)—— 静态资源有 CSP/nosniff,
// 而 `/api/*` 与 `/plugins/*`(Pages Functions)**一个安全头都没有**,此前线上与本地都测不到。
// 本文件原先只服务 dist/ 静态资源 ⇒ 「本地过、线上挂」这一类缺陷**无法被 e2e 发现**。
//
// 忠实度原则(重要):Function 响应**只带 Function 自己返回的 header**,
// **绝不叠加 `_headers`** —— 线上就是这样,本地若"好心"加上 CSP 就永远测不出真实差异。
// 测试 tests/iwb-functions-headers.spec.js 用反向断言把这一点钉死。
//
// 模拟范围刻意最小:只做「Cloudflare context 形状」+「Response → Node 响应」两件事,
// 不模拟 Pages 的路由匹配、缓存、边缘网络等 —— 那些不属于本项目能控的范围。
const FUNCTION_ROUTES = [
{ prefix: '/api/img', file: 'functions/api/img.js', entry: 'onRequest' },
{ prefix: '/plugins', file: 'functions/plugins/[[path]].js', entry: 'onRequestGet' },
]
// 上游 mock(默认开):/api/img 会真的去请求外部图床(豆包/阿里云…),
// 那会让 e2e 变慢且依赖外部可达性 ⇒ 默认把上游 fetch 换成本地假图片。
// 关闭:IWB_MOCK_UPSTREAM=0(需要真连上游时用)。
const MOCK_UPSTREAM = process.env.IWB_MOCK_UPSTREAM !== '0'
// 插件 KV 的本地替身:内存 Map,内容寻址的插件文件用可预测的假字节。
const MOCK_PLUGIN_BYTES = '/* mock plugin */\n'
function mockKv() {
const store = new Map([
['plugins/index.json', JSON.stringify([{ id: 'mock-plugin', file: 'plugin-mock-plugin.0123456789ab.js', version: '1.0.0', integrity: 'sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' }])],
['plugins/plugin-mock-plugin.0123456789ab.js', MOCK_PLUGIN_BYTES],
])
return { get: async (key) => (store.has(key) ? store.get(key) : null) }
}
async function readRequestBody(req) {
if (req.method === 'GET' || req.method === 'HEAD') return undefined
const chunks = []
for await (const c of req) chunks.push(c)
return Buffer.concat(chunks)
}
const functionModules = new Map()
async function loadFunctionModule(file) {
if (functionModules.has(file)) return functionModules.get(file)
const mod = await import(path.join(root, file))
functionModules.set(file, mod)
return mod
}
// Function 响应 → Node 响应:**只透传 Function 自己的 header**(不叠加 _headers,见上方忠实度原则)
async function sendFunctionResponse(res, fnRes) {
const headers = {}
for (const [name, value] of fnRes.headers.entries()) headers[name] = value
const body = fnRes.status === 204 || fnRes.status === 304 ? Buffer.alloc(0) : Buffer.from(await fnRes.arrayBuffer())
res.writeHead(fnRes.status, headers)
res.end(body)
}
async function handleFunction(req, res, pathname) {
const route = FUNCTION_ROUTES.find((r) => pathname === r.prefix || pathname.indexOf(r.prefix + '/') === 0)
if (!route) return false
try {
const mod = await loadFunctionModule(route.file)
const fn = mod[route.entry]
if (typeof fn !== 'function') throw new Error('入口未导出: ' + route.entry)
// 构造 Request(POST 需要 body)
const url = new URL(req.url, 'http://127.0.0.1')
const body = await readRequestBody(req)
const request = new Request(url.toString(), {
method: req.method,
headers: Object.entries(req.headers).reduce((acc, [k, v]) => { if (typeof v === 'string') acc[k] = v; return acc }, {}),
body: body && body.length ? body : undefined,
})
const ctx = {
params: { path: pathname.slice(route.prefix.length).split('/').filter(Boolean) },
env: { PLUGINS: mockKv() },
request,
}
// 上游 mock:把 Function 内部的 fetch 换成本地假响应(仅 /api/img 会用到)
const fnRes = await withMockedUpstream(async () => {
return await fn(ctx)
})
await sendFunctionResponse(res, fnRes)
} catch (e) {
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
res.end('function error: ' + String((e && e.message) || e))
}
return true
}
// 上游 mock 实现:把 fetch 指向白名单图床的请求替换为一张 1x1 PNG。
// 仅在 MOCK_UPSTREAM 开启时生效;不影响真实部署(线上跑的是 Cloudflare Functions)。
async function withMockedUpstream(fn) {
if (!MOCK_UPSTREAM) return fn()
const realFetch = globalThis.fetch
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')
globalThis.fetch = async (input, init) => {
const u = String(typeof input === 'string' ? input : (input && input.url) || input)
// 非上游请求(如本地自取)放行
if (!/^https?:\/\//i.test(u)) return realFetch(input, init)
return new Response(PNG, { status: 200, headers: { 'Content-Type': 'image/png', 'Content-Length': String(PNG.length) } })
}
try {
return await fn()
} finally {
globalThis.fetch = realFetch
}
const mime = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.webp': 'image/webp',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.woff2': 'font/woff2',
'.map': 'application/json; charset=utf-8',
}
const server = http.createServer((req, res) => {
const clean = decodeURIComponent((req.url || '/').split('?')[0])
// Pages Functions 优先(/api/* 与 /plugins/*):它们**不套用 _headers**,与线上一致
handleFunction(req, res, clean).then((handled) => {
if (handled) return
const file = path.resolve(dist, clean === '/' ? 'index.html' : '.' + clean)
if (!file.startsWith(dist + path.sep)) { res.writeHead(403, securityHeadersFor(clean, {})); return res.end('forbidden') }
fs.readFile(file, (err, data) => {
if (err) { res.writeHead(404, securityHeadersFor(clean, {})); return res.end('not found') }
const headers = securityHeadersFor(clean, { 'content-type': mime[path.extname(file)] || 'application/octet-stream' })
res.writeHead(200, headers)
res.end(data)
})
}).catch(() => {
if (!res.headersSent) { res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }) }
res.end('server error')
})
})
server.listen(port, '127.0.0.1', () => {
const cli = require.resolve('@playwright/test/cli')
// iwb-csp-gate.spec.js 是 CSP 门禁:它依赖本服务器下发的 _headers(尤其 Content-Security-Policy),
// 覆盖「blob: 源复制」与「大图压缩落库」两条真实链路,必须留在门禁里。
// 默认跑全部门禁 spec;调试时可用 IWB_E2E_SPECS(逗号分隔)只跑指定文件,避免每次都全量。
// iwb-import-4k.spec.js = 「导入图片(粘贴/拖放/上传)」路径契约(4K 导入 ⇒ 立即引用化 + 压缩到显示尺寸),
// 用户实测的真实缺陷驱动,必须留在门禁里(否则该路径会再次退化成"原图 base64 直入节点")。
// iwb-backup-config.spec.js = 「备份/还原里的设置完整性与往返一致」契约(用户实测:设置还原不回来),
// 覆盖导出源必须是真实设置、withKeys 两个方向、__KEEP__ 语义与未知字段保留,必须留在门禁里。
// iwb-duplicate-ws.spec.js = 「创建副本不丢连线 + 副本名唯一」契约(用户实测:复制画布丢连线、连续复制同名),
// 覆盖 画布→连线→回库→复制→打开副本 的真实链路,必须留在门禁里。
// iwb-resume-reload.spec.js = 「生图中刷新不丢需求」契约(用户实测:刷新后续跑横幅不出现),
// 覆盖 在途请求→刷新被标 failed→启动过滤 failed→recoverable→横幅→点继续重新发起 的链路,必须留在门禁里。
// iwb-tab-dot.spec.js = 「标签条圆点状态色」契约(用户需求:生成完成=绿、失败=红、切到画布清除)。
// iwb-resume-scope.spec.js = 「续跑范围不放大」契约(用户实测:单任务中断刷新后其他未启动任务也被新建→计划外计费)。
// iwb-resume-variants.spec.js = 「多变体只补缺张」契约(用户实测:4 变体完成 2 张后整任务被跳过,缺张永不补;继续只补缺失变体)。
const specOverride = String(process.env.IWB_E2E_SPECS || '').split(',').map((x) => x.trim()).filter(Boolean)
// 门禁 spec 不再手工维护:交给 scripts/list-e2e-specs.js 自动发现 tests/*.spec.js。
// 排除规则只有一条——下划线前缀(_*.spec.js = dev 探针),且该探针必须自带 iwb-dev-probe 标记,
// 否则 discoverSpecs 会抛错。"忘了把新 spec 加进清单"这种静默漏跑从此不可能发生。
let specs = specOverride
if (specs.length) {
console.log(`[serve-test] 使用 IWB_E2E_SPECS 覆盖:${specs.length} 个 spec`)
} else {
const discovered = require('./list-e2e-specs').discoverSpecs(path.join(root, 'tests'))
specs = discovered.specs
console.log(`[serve-test] 自动发现门禁 spec ${specs.length} 个${discovered.excluded.length ? `(排除 dev 探针 ${discovered.excluded.length}:${discovered.excluded.map((f) => path.basename(f)).join('、')})` : ''}`)
let pathname = '/'
try { pathname = decodeURIComponent(new URL(req.url, 'http://127.0.0.1').pathname) } catch (e) { pathname = '/' }
if (pathname.endsWith('/')) pathname += 'index.html'
let file = path.join(dist, pathname)
// 目录穿越防护:只允许 servicedir 内的文件
if (!file.startsWith(dist + path.sep)) {
res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' })
res.end('forbidden')
return
}
const child = cp.spawn(process.execPath, [cli, 'test'].concat(specs), {
cwd: root,
stdio: 'inherit',
env: { ...process.env, IWB_BASE_URL: `http://127.0.0.1:${port}` },
fs.stat(file, (err, st) => {
if (err || !st.isFile()) {
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
res.end('not found')
return
}
res.writeHead(200, {
'content-type': mime[path.extname(file)] || 'application/octet-stream',
'cache-control': 'no-store',
})
fs.createReadStream(file).pipe(res)
})
child.on('exit', (code) => { server.close(() => process.exit(code == null ? 1 : code)) })
})
server.listen(port, () => {
console.log('[serve-test] serving ' + path.relative(process.cwd(), dist) + ' at http://127.0.0.1:' + port)
console.log('[serve-test] 纯静态:不再注入 _headers / 不再模拟 Pages Functions(项目已转为桌面客户端)')
})
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env node
'use strict'
// 统一改版本号:package.json / src-tauri/tauri.conf.json / src-tauri/Cargo.toml
// 用法:node scripts/set-version.js 3.25.0 (三个文件必须一致,否则发布/更新判断会错)
const fs = require('fs')
const path = require('path')
const root = path.resolve(__dirname, '..')
const v = String(process.argv[2] || '').trim()
if (!/^\d+\.\d+\.\d+/.test(v)) { console.error('用法: node scripts/set-version.js 3.25.0'); process.exit(1) }
const pkgPath = path.join(root, 'package.json')
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
pkg.version = v
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n')
const confPath = path.join(root, 'src-tauri', 'tauri.conf.json')
const conf = JSON.parse(fs.readFileSync(confPath, 'utf8'))
conf.version = v
fs.writeFileSync(confPath, JSON.stringify(conf, null, 2) + '\n')
const cargoPath = path.join(root, 'src-tauri', 'Cargo.toml')
let cargo = fs.readFileSync(cargoPath, 'utf8')
cargo = cargo.replace(/^version = "[^"]*"/m, 'version = "' + v + '"')
fs.writeFileSync(cargoPath, cargo)
console.log('版本已设为 ' + v + '(package.json / tauri.conf.json / Cargo.toml)')
console.log('提示:改完记得提交,并在发版时打 tag;CHANGELOG 若维护也要同步。')
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env node
'use strict'
// 桌面版打包前清掉 dist/plugins/:插件不再随应用发布,全部从市场安装到 <资料目录>/plugins/。
// 保留 plugins/ 目录本身是给 scripts/gen-market.js(市场产物)用的,不进安装包。
const fs = require('fs')
const path = require('path')
const dir = path.resolve(__dirname, '..', 'dist', 'plugins')
if (fs.existsSync(dir)) {
fs.rmSync(dir, { recursive: true, force: true })
console.log('[strip-plugins] 已移除 dist/plugins(插件改由市场安装)')
} else {
console.log('[strip-plugins] dist/plugins 不存在,跳过')
}
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env node
'use strict'
// 从插件源仓同步产物到本仓 plugins/runtime/ 并重建 plugins/index.json(内容寻址 + SRI)。
// 用法:node scripts/sync-plugins-from-repo.mjs [源仓路径,默认 ../iwb-plugins-desktop]
// 幂等:内容不变时生成完全相同的文件名与清单(可直接用 git diff 验证)。
const fs = require('fs')
const path = require('path')
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', 'image-annotate', 'image-vectorize', 'style-source', 'white-bg-800', 'xianyi-cutout']
const sha = (buf) => crypto.createHash('sha256').update(buf).digest()
const shaHex = (buf) => sha(buf).toString('hex')
const sri = (buf) => 'sha256-' + sha(buf).toString('base64')
if (!fs.existsSync(srcRoot)) { console.error('找不到插件源仓:' + srcRoot); process.exit(1) }
fs.mkdirSync(outDir, { recursive: true })
const manifest = []
let copied = 0, changed = 0
for (const id of IDS) {
const artifact = path.join(srcRoot, id, 'src', 'index.js')
if (!fs.existsSync(artifact)) { console.warn('跳过 ' + id + '(无 ' + artifact + ')'); continue }
const buf = fs.readFileSync(artifact)
const name = 'plugin-' + id + '.' + shaHex(buf).slice(0, 12) + '.js'
const pkg = JSON.parse(fs.readFileSync(path.join(srcRoot, id, 'package.json'), 'utf8'))
for (const old of fs.readdirSync(outDir)) {
if (old.indexOf('plugin-' + id + '.') === 0 && old !== name) { fs.unlinkSync(path.join(outDir, old)); changed++ }
}
const target = path.join(outDir, name)
if (!fs.existsSync(target) || shaHex(fs.readFileSync(target)) !== shaHex(buf)) { fs.writeFileSync(target, buf); copied++ }
manifest.push({ id: id, file: name, version: pkg.version, integrity: sri(buf) })
console.log(id.padEnd(16), pkg.version.padEnd(8), name)
}
fs.writeFileSync(path.join(root, 'plugins', 'index.json'), JSON.stringify(manifest, null, 2) + '\n')
console.log('完成:' + manifest.length + ' 个插件,新写入 ' + copied + ' 个,清理旧产物 ' + changed + ' 个')
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────
# 从上游 image-workbench-web 同步 bug 修复到本仓库(桌面版)
#
# 为什么不是直接 git merge:
# 本仓库 fork 时只导出了文件(git archive),**与上游没有共同提交历史**,
# 没有共同祖先时 merge 会退化成「两棵无关的树硬拼」,冲突满天飞。
# 所以这里用「差异重放」:
# 1) 算本仓库相对基线 tag(upstream-base) 的全部差异 → 一个补丁
# 2) 以新的上游提交为起点开分支,用三段合并(--3way)把补丁贴上去
# 3) 上游没碰过的行自动合并;上游改过同一行的地方留冲突标记,人工看一眼
# 4) --finish 把主线前移到该分支。**第一次同步之后,本仓库就与上游共享历史了**,
# 以后可以直接 git merge upstream/main(脚本仍然可用,二者等价)。
#
# 用法:
# ./scripts/sync-upstream.sh # 只看上游有哪些新提交,不改任何东西
# ./scripts/sync-upstream.sh --apply # 真同步,产出 sync/<日期> 分支(不动主线)
# ./scripts/sync-upstream.sh --finish # 人工确认无误后:主线前移 + 基线推进
# ─────────────────────────────────────────────────────────────
set -eo pipefail
REMOTE="${UPSTREAM_REMOTE:-upstream}" # 上游 remote 名(默认 upstream)
BRANCH="${UPSTREAM_BRANCH:-main}" # 上游分支
BASE_TAG="upstream-base" # 基线 tag(指向上游那个 commit)
PATCH=".git/desktop-delta.patch" # 桌面侧差异补丁(不进版本库)
TARGET="${TARGET_BRANCH:-main}" # 主线分支名
MODE="${1:-check}"
cd "$(git rev-parse --show-toplevel)" # 一律在仓库根执行
# 上游基线 commit 号单独存文件:两边没有共同历史时 rev-list 没法直接数。
[ -f .upstream-base ] || { echo "缺少 .upstream-base(记录上游基线 commit)"; exit 1; }
UP_BASE="$(tr -d '[:space:]' < .upstream-base)"
echo "拉取上游 ${REMOTE}/${BRANCH} ..."
git fetch --quiet "${REMOTE}" "${BRANCH}"
NEW="$(git rev-parse "${REMOTE}/${BRANCH}")"
if [ "${UP_BASE}" = "${NEW}" ]; then
echo "已是最新(基线 ${UP_BASE:0:7}),无需同步"; exit 0
fi
echo "上游基线:${UP_BASE}"
echo "上游最新:$(git log -1 --format='%h %s' "${NEW}")"
echo "新增提交:$(git rev-list --count "${UP_BASE}..${NEW}" 2>/dev/null || echo '?') 个"
echo "---- 新提交(最多 50 条)----"
git log --oneline -n 50 "${UP_BASE}..${NEW}"
case "${MODE}" in
check|"")
echo ""
echo "(只读检查,未做任何修改。确认后加 --apply 执行同步)"
exit 0
;;
--apply|apply)
# 1) 桌面侧差异(--binary 必须加:图标等二进制文件否则无法重放)
git diff --binary "${BASE_TAG}..HEAD" > "${PATCH}"
echo ""
echo "桌面侧差异补丁:$(wc -c < "${PATCH}") 字节"
# 2) 以新上游为起点开分支(此时工作树 = 上游新版)
STAMP="$(date +%Y%m%d-%H%M)"
git checkout -q -b "sync/${STAMP}" "${NEW}"
# 3) 三段合并把桌面差异贴回去;有冲突也继续,交给人工
set +e
git apply --3way --whitespace=nowarn "${PATCH}"
RC=$?
set -e
if [ "${RC}" != "0" ]; then
echo ""
echo "!! 有冲突,需手工处理:"
git status --porcelain | grep -E '^(UU|AA|DU|UD|AU|UA)' || true
echo " 处理完:git add -A && git commit,再执行 $0 --finish"
else
git add -A
git -c user.name=qiqi -c user.email=qiqi@local commit -q \
-m "chore(sync): 重放桌面侧差异到上游 $(git rev-parse --short "${NEW}")"
echo ""
echo "同步完成,改动已提交在 sync/${STAMP}。核对后执行:$0 --finish"
fi
exit 0
;;
--finish|finish)
CUR="$(git rev-parse --abbrev-ref HEAD)"
case "${CUR}" in sync/*) ;; *) echo "请先切到 sync/* 分支再 --finish"; exit 1;; esac
if [ -n "$(git diff --name-only --diff-filter=U)" ]; then
echo "还有未解决的冲突,先处理干净"; exit 1
fi
if grep -rqI '^<<<<<<< ' --exclude-dir=node_modules --exclude-dir=.git . ; then
echo "仍有冲突标记未清理"; exit 1
fi
STAMP="$(date +%Y%m%d-%H%M)"
OLD="$(git rev-parse "${TARGET}")"
# 回滚点:同步前的主线位置
git branch -f "backup/pre-sync-${STAMP}" "${OLD}"
git checkout -q "${TARGET}"
# 主线内容前移到「上游最新 + 桌面差异」;历史里因此带上了上游提交
git reset --hard -q "${CUR}"
# 基线 tag 指向**上游那个 commit**(它是本次提交的父提交)⇒ 差异仍然只有桌面侧改动
git tag -f "${BASE_TAG}" "$(git rev-parse "${REMOTE}/${BRANCH}")" >/dev/null
git rev-parse "${REMOTE}/${BRANCH}" > .upstream-base
git add .upstream-base
git -c user.name=qiqi -c user.email=qiqi@local commit -q \
-m "chore(sync): 上游基线推进到 $(git rev-parse --short "${REMOTE}/${BRANCH}")"
echo ""
echo "主线 ${TARGET} 已前移,基线 ${BASE_TAG} = $(git rev-parse --short "${BASE_TAG}")"
echo "回滚点分支:backup/pre-sync-${STAMP}"
echo "桌面侧差异行数:$(git diff --stat "${BASE_TAG}..HEAD" | tail -1)"
;;
*)
echo "未知参数:${MODE}(可用:--apply / --finish)"; exit 1
;;
esac
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env node
'use strict'
// 更新 site/releases.json 的一条平台记录(发布脚本调用;也可手工跑)
const fs = require('fs')
const path = require('path')
const root = path.resolve(__dirname, '..')
const file = path.join(root, 'site', 'releases.json')
const args = {}
for (let i = 2; i < process.argv.length; i += 2) args[process.argv[i].replace(/^--/, '')] = process.argv[i + 1]
for (const k of ['version', 'platform', 'file', 'size', 'sha256']) {
if (!args[k]) { console.error('缺少参数 --' + k); process.exit(1) }
}
const data = JSON.parse(fs.readFileSync(file, 'utf8'))
data.releases = data.releases || []
let rel = data.releases.find((r) => r.version === args.version)
if (!rel) {
rel = { version: args.version, date: args.date || new Date().toISOString().slice(0, 10), notes: args.notes || '', platforms: {} }
data.releases.unshift(rel)
}
if (args.notes) rel.notes = args.notes
if (args.date) rel.date = args.date
rel.platforms = rel.platforms || {}
rel.platforms[args.platform] = {
file: args.file,
size: Number(args.size),
sha256: args.sha256,
kind: path.extname(args.file).replace('.', '') || 'bin',
}
data.updatedAt = new Date().toISOString()
fs.writeFileSync(file, JSON.stringify(data, null, 2) + '\n')
console.log('releases.json 已更新:' + args.version + ' / ' + args.platform)
+38
View File
@@ -0,0 +1,38 @@
<#
一次性环境检查(Windows)。不自动安装任何东西,只报告缺什么。
用法:右键「使用 PowerShell 运行」,或 powershell -ExecutionPolicy Bypass -File scripts\windows-check.ps1
#>
$ErrorActionPreference = 'Continue'
function Show($name, $ok, $hint) {
if ($ok) { Write-Host ("[OK] " + $name) -ForegroundColor Green }
else { Write-Host ("[缺失] " + $name + " -> " + $hint) -ForegroundColor Yellow }
}
# Node
$node = (Get-Command node -ErrorAction SilentlyContinue)
Show "Node.js" ($null -ne $node) "winget install OpenJS.NodeJS.LTS"
# Rust
$rustc = (Get-Command rustc -ErrorAction SilentlyContinue)
Show "Rust (rustc)" ($null -ne $rustc) "winget install Rustlang.Rustup"
if ($rustc) {
$v = (& rustc -V) -join ' '
Write-Host (" " + $v)
if ($v -notmatch 'msvc') {
Write-Host " [!] 当前工具链不是 MSVC,请执行: rustup default stable-msvc" -ForegroundColor Yellow
}
}
# MSVC 链接器
$link = Get-ChildItem "C:\Program Files (x86)\Microsoft Visual Studio" -Recurse -Filter link.exe -ErrorAction SilentlyContinue | Select-Object -First 1
Show "MSVC Build Tools (link.exe)" ($null -ne $link) "安装 VS 2022 Build Tools 并勾选「使用 C++ 的桌面开发」"
# WebView2
$wv = Get-ItemProperty "HKLM:\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" -ErrorAction SilentlyContinue
Show "WebView2 Runtime" ($null -ne $wv) "winget install Microsoft.EdgeWebView2Runtime(Win11 一般自带)"
Write-Host ""
Write-Host "全部 OK 后执行:" -ForegroundColor Cyan
Write-Host " npm ci"
Write-Host " npm run app:build"
+82
View File
@@ -0,0 +1,82 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Image Workbench · 本地优先的 AI 生图工作台</title>
<meta name="description" content="本地优先的 AI 生图无限画布:节点式工作流、插件按需安装、数据全部留在本机。">
<link rel="stylesheet" href="/assets/style.css">
</head><body>
<!--NAV-->
<main>
<section class="hero hero-art">
<div class="hero-bg"><img src="/assets/painting.jpg" alt=""></div>
<div class="hero-veil"></div>
<div class="wrap">
<span class="kicker">v<!--VERSION--> · macOS / Windows · 数据在本地</span>
<h1>本地优先的<br>AI 生图无限画布</h1>
<p class="sub">用节点把「参考图 → 提示词 → 批量生成 → 图库」串成一条生产线。<br>图片、提示词、模型配置全部留在你自己的电脑里,插件按需安装。</p>
<div class="cta">
<a class="btn primary lg" href="/download/">下载 v<!--VERSION--></a>
<a class="btn lg" href="/plugins/">浏览 <!--PLUGIN_COUNT--> 个插件</a>
</div>
<div class="meta">支持 macOS 12+ 与 Windows 10 1803+ · 安装包约 7 MB · 无需登录</div>
</div></section>
<section class="section"><div class="wrap">
<h2>为「一个人跑完整条产线」而做</h2>
<p class="lead">不做又一个在线生图站点。它活在你的桌面上,把生图、修图、批量、图库和插件放在同一张画布上。</p>
<div class="grid c3">
<!--FEAT_CARDS-->
</div>
</div></section>
<section class="section"><div class="wrap">
<h2>插件:本体不带,需要的自己装</h2>
<p class="lead">应用本体不再内置插件。设置里打开市场,点「安装」,重启即可用;不需要的点一下就能关掉。</p>
<div class="grid c3">
<!--PLUGIN_CARDS-->
</div>
<div style="margin-top:22px"><a class="btn" href="/plugins/">查看全部 <!--PLUGIN_COUNT--> 个插件</a></div>
</div></section>
<section class="section"><div class="wrap">
<h2>下载 Image Workbench</h2>
<p class="lead">选你的平台。装过一次之后,以后在应用内「设置 → 通用 → 版本与更新」就能一键升级。</p>
<div class="dl"><!--DL_CARDS--></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>
</main>
<!--FOOTER-->
</body></html>
<script>
(function () {
var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches
var targets = [].slice.call(document.querySelectorAll('.section h2, .section p.lead, .card, .pcard, .dl a'))
targets.forEach(function (el) { el.classList.add('reveal') })
if (!reduce && 'IntersectionObserver' in window) {
var io = new IntersectionObserver(function (entries) {
entries.forEach(function (e) {
if (!e.isIntersecting) return
var el = e.target
var idx = targets.indexOf(el) % 4
el.style.transitionDelay = (idx * 60) + 'ms'
el.classList.add('in')
io.unobserve(el)
})
}, { rootMargin: '0px 0px -8% 0px', threshold: 0.12 })
targets.forEach(function (el) { io.observe(el) })
} else { targets.forEach(function (el) { el.classList.add('in') }) }
var art = document.querySelector('.art-frame')
if (art && !reduce) {
var raf = 0
var onScroll = function () {
if (raf) return
raf = requestAnimationFrame(function () {
raf = 0
var y = Math.min(1, Math.max(0, window.scrollY / 700))
art.style.transform = 'translate3d(0,' + (y * -14) + 'px,0)'
})
}
window.addEventListener('scroll', onScroll, { passive: true }); onScroll()
}
})()
</script>
+45
View File
@@ -0,0 +1,45 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>插件市场 · Image Workbench</title>
<link rel="stylesheet" href="/assets/style.css">
</head><body>
<!--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">共 <!--PLUGIN_COUNT--> 个插件。安装方式:应用内 <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>
<!--TAG_CHIPS-->
</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">
<!--PLUGIN_CARDS-->
</div>
<div class="note" style="margin-top:26px">插件安装后会写进你的资料目录 <code>~/Documents/ImageWorkbench/plugins/</code>;卸载只删插件文件,不动画布与图库。</div>
</div></section>
</main>
<!--FOOTER-->
<script>
var q = document.getElementById('q'), list = document.getElementById('list'), chips = document.getElementById('chips'), activeTag = ''
function apply () {
var kw = (q.value || '').trim().toLowerCase()
Array.prototype.forEach.call(list.children, function (el) {
var okKw = !kw || el.dataset.name.indexOf(kw) >= 0
var okTag = !activeTag || (',' + el.dataset.tags + ',').indexOf(',' + activeTag + ',') >= 0
var ok = okKw && okTag
el.style.display = ok ? '' : 'none'
})
}
q.addEventListener('input', apply)
chips.addEventListener('click', function (e) {
var b = e.target.closest('button[data-tag]'); if (!b) return
Array.prototype.forEach.call(chips.children, function (x) { x.style.background = ''; x.style.color = ''; x.style.borderColor = 'transparent' })
b.style.background = '#111'; b.style.color = '#fff'; b.style.borderColor = '#111'
activeTag = b.dataset.tag || ''
apply()
})
</script>
</body></html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 382 KiB

+141
View File
@@ -0,0 +1,141 @@
:root{--fg:#111;--muted:#6b7280;--line:#ebebeb;--soft:#f7f7f8;--radius:16px}
*{box-sizing:border-box}
html,body{margin:0;padding:0}
body{background:#fff;color:var(--fg);font:15px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;-webkit-font-smoothing:antialiased}
a{color:inherit;text-decoration:none}
.wrap{max-width:1120px;margin:0 auto;padding:0 24px}
nav{position:sticky;top:0;z-index:50;background:rgba(255,255,255,.82);backdrop-filter:saturate(1.6) blur(12px);border-bottom:1px solid var(--line)}
nav .inner{display:flex;align-items:center;gap:26px;height:60px}
nav .brand{display:flex;align-items:center;gap:9px;font-weight:650;letter-spacing:-.01em}
nav .brand .dot{width:22px;height:22px;border-radius:6px;background:#111;color:#fff;display:inline-flex;align-items:center;justify-content:center;font-size:10px;font-weight:700}
nav .links{display:flex;gap:20px;margin-left:8px;color:var(--muted);font-size:14px}
nav .links a:hover{color:var(--fg)}
nav .links a.on{color:var(--fg)}
nav .right{margin-left:auto;display:flex;align-items:center;gap:10px}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;height:38px;padding:0 18px;border-radius:10px;border:1px solid var(--line);background:#fff;color:var(--fg);font-size:14px;font-weight:550;cursor:pointer;transition:.15s}
.btn:hover{border-color:#d4d4d4;background:#fafafa}
.btn.primary{background:#111;color:#fff;border-color:#111}
.btn.primary:hover{background:#000}
.btn.lg{height:44px;padding:0 22px;font-size:15px}
.hero{padding:84px 0 20px;text-align:center}
.kicker{display:inline-flex;align-items:center;gap:8px;padding:5px 12px;border:1px solid var(--line);border-radius:999px;color:var(--muted);font-size:12.5px}
.hero h1{font-size:56px;line-height:1.08;letter-spacing:-.03em;margin:22px 0 0;font-weight:700}
.hero p.sub{max-width:660px;margin:20px auto 0;color:var(--muted);font-size:17px;line-height:1.75}
.hero .cta{display:flex;gap:12px;justify-content:center;margin-top:30px;flex-wrap:wrap}
.hero .meta{margin-top:16px;color:#9ca3af;font-size:12.5px}
.shot{margin:40px 0 0;padding:0 0 64px}
.shot img{width:100%;display:block;border-radius:var(--radius);border:1px solid var(--line);box-shadow:0 30px 70px -30px rgba(15,23,42,.35)}
.section{padding:72px 0;border-top:1px solid var(--line)}
.section h2{font-size:30px;letter-spacing:-.02em;margin:0 0 8px;font-weight:680}
.section p.lead{color:var(--muted);margin:0 0 34px;max-width:660px}
.grid{display:grid;gap:16px}
.grid.c3{grid-template-columns:repeat(3,1fr)}
.grid.c2{grid-template-columns:repeat(2,1fr)}
.card{border:1px solid var(--line);border-radius:var(--radius);padding:22px;background:#fff}
.card h3{margin:0 0 6px;font-size:16px;font-weight:650}
.card p{margin:0;color:var(--muted);font-size:13.5px;line-height:1.7}
.card .ico{width:34px;height:34px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px;margin-bottom:14px}
.pcard{display:flex;flex-direction:column;gap:8px;border:1px solid var(--line);border-radius:14px;padding:18px;background:#fff}
.pcard .head{display:flex;gap:10px;align-items:center}
.pcard .av{width:34px;height:34px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:17px;flex:0 0 34px}
.pcard .nm{font-weight:640;font-size:14.5px}
.pcard .ver{color:var(--muted);font-size:12px;margin-top:1px}
.pcard .desc{color:var(--muted);font-size:13px;line-height:1.65;flex:1 1 auto}
.tags{display:flex;gap:6px;flex-wrap:wrap}
.tag{padding:1px 8px;border-radius:999px;background:var(--soft);color:var(--muted);font-size:11.5px;border:1px solid transparent;font-family:inherit}
.dl{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}
.dl a{border:1px solid var(--line);border-radius:14px;padding:18px;display:flex;flex-direction:column;gap:4px;transition:.15s}
.dl a:hover{border-color:#d4d4d4;background:#fafafa}
.dl .n{font-weight:640}
.dl .s{color:var(--muted);font-size:12.5px}
.dl .none{border:1px solid var(--line);border-radius:14px;padding:18px;display:flex;flex-direction:column;gap:4px;opacity:.55}
footer{background:#0b0b0c;color:#9ca3af;padding:52px 0 40px}
footer .cols{display:grid;grid-template-columns:2fr 1fr 1fr 1fr;gap:24px}
footer h4{color:#fff;font-size:13px;margin:0 0 10px;font-weight:600}
footer a{display:block;color:#9ca3af;font-size:13px;margin:6px 0}
footer a:hover{color:#fff}
footer .copy{border-top:1px solid #1f1f22;margin-top:34px;padding-top:18px;font-size:12px;color:#6b7280;display:flex;justify-content:space-between;flex-wrap:wrap;gap:8px}
.steps{margin:6px 0 0;padding-left:20px;color:var(--muted);font-size:13.5px;line-height:1.9}
.steps b{color:var(--fg)}
pre.cmd{margin:10px 0 0;padding:10px 12px;background:var(--soft);border:1px solid var(--line);border-radius:8px;overflow-x:auto}
pre.cmd code{font-size:12.5px}
.note{margin:10px 0 0;color:var(--muted);font-size:12.5px;line-height:1.8}
@media(max-width:900px){.hero h1{font-size:38px}.grid.c3,.dl{grid-template-columns:1fr 1fr}footer .cols{grid-template-columns:1fr 1fr}}
@media(max-width:600px){.grid.c3,.grid.c2,.dl{grid-template-columns:1fr}nav .links{display:none}}
/* ── 油画主视觉 + 特效 ───────────────────────────────── */
.artwrap{position:relative;max-width:1120px;margin:26px auto 0;padding:0 24px 72px}
.art-glow{position:absolute;inset:-40px 0 auto 0;height:520px;pointer-events:none;
background:
radial-gradient(46% 60% at 22% 40%, rgba(255,178,92,.28), transparent 70%),
radial-gradient(40% 55% at 78% 30%, rgba(58,120,140,.22), transparent 70%),
radial-gradient(60% 70% at 50% 0%, rgba(255,214,150,.35), transparent 72%);
filter:blur(10px);opacity:.9;animation:glowPulse 12s ease-in-out infinite alternate}
.art-frame{position:relative;border-radius:22px;overflow:hidden;border:1px solid var(--line);
box-shadow:0 40px 90px -40px rgba(15,23,42,.45)}
.art-frame .art{display:block;width:100%;height:auto;transform:scale(1.02);animation:kenburns 28s ease-in-out infinite alternate}
.art-frame .grain{position:absolute;inset:0;pointer-events:none;opacity:.14;mix-blend-mode:multiply;
background-image:url("data:image/svg+xml;utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='.55'/%3E%3C/svg%3E")}
.art-frame:after{content:"";position:absolute;inset:0;pointer-events:none;border-radius:22px;box-shadow:inset 0 0 120px rgba(120,80,30,.16)}
@keyframes kenburns{from{transform:scale(1.02) translate3d(0,0,0)}to{transform:scale(1.08) translate3d(-1.2%,-1%,0)}}
@keyframes glowPulse{from{opacity:.72;transform:translateY(0)}to{opacity:1;transform:translateY(-10px)}}
@keyframes rise{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.hero h1,.hero p.sub,.hero .cta,.hero .meta,.hero .kicker{animation:rise .7s cubic-bezier(.22,.61,.36,1) both}
.hero h1{animation-delay:.04s}.hero p.sub{animation-delay:.1s}.hero .cta{animation-delay:.16s}.hero .meta{animation-delay:.22s}
.artwrap{animation:rise .9s cubic-bezier(.22,.61,.36,1) .18s both}
.card,.pcard,.dl a{transition:transform .18s ease, box-shadow .18s ease, border-color .18s ease}
.card:hover,.pcard:hover{transform:translateY(-3px);box-shadow:0 16px 40px -24px rgba(15,23,42,.38);border-color:#dcdcdc}
.dl a:hover{transform:translateY(-2px);box-shadow:0 16px 40px -24px rgba(15,23,42,.35)}
.section h2:after{content:"";display:block;width:36px;height:3px;border-radius:2px;margin-top:12px;background:linear-gradient(90deg,#e8a735,#3a788c)}
@media (prefers-reduced-motion:reduce){
.hero h1,.hero p.sub,.hero .cta,.hero .meta,.hero .kicker,.artwrap,.art-frame .art,.art-glow{animation:none!important}
.card:hover,.pcard:hover,.dl a:hover{transform:none}
}
/* 主视觉改为宽幅裁切:突出画面中段的油彩笔触 */
.art-frame{aspect-ratio:auto}
.art-frame .art{width:100%;height:clamp(300px,40vw,540px);object-fit:cover;object-position:50% 62%}
.art-frame:before{content:"";position:absolute;left:0;right:0;bottom:0;height:38%;pointer-events:none;z-index:2;
background:linear-gradient(to top, rgba(255,255,255,.92), rgba(255,255,255,.35) 45%, transparent)}
/* ── 滚动入场 + 视差 ───────────────────────────────── */
.reveal{opacity:0;transform:translateY(18px);transition:opacity .7s cubic-bezier(.22,.61,.36,1),transform .7s cubic-bezier(.22,.61,.36,1)}
.reveal.in{opacity:1;transform:none}
.section h2.reveal.in:after{animation:barIn .7s ease both}
@keyframes barIn{from{width:0}to{width:36px}}
.art-frame{will-change:transform}
@media (prefers-reduced-motion:reduce){.reveal{opacity:1;transform:none;transition:none}}
/* 首屏露出更多油彩:裁切位置上移 + 收紧 hero 间距 */
.hero{padding:64px 0 8px}
.art-frame .art{object-position:50% 34%}
.artwrap{margin-top:14px}
/* ── 首屏:油画做背景(白纱压一层,保证文字可读) ─────────── */
.hero-art{position:relative;padding:76px 0 96px;overflow:hidden}
.hero-bg{position:absolute;inset:0;z-index:0;overflow:hidden}
.hero-bg img{width:100%;height:100%;object-fit:cover;object-position:50% 58%;transform:scale(1.06);animation:kenburns 30s ease-in-out infinite alternate;filter:saturate(1.05)}
.hero-veil{position:absolute;inset:0;z-index:1;
background:
radial-gradient(70% 60% at 50% 38%, rgba(255,255,255,.92) 0%, rgba(255,255,255,.72) 42%, rgba(255,255,255,.1) 100%),
linear-gradient(180deg, rgba(255,255,255,.92) 0%, rgba(255,255,255,.55) 46%, rgba(255,255,255,.28) 72%, #fff 100%)}
.hero-art .wrap{position:relative;z-index:2}
.art-strip{position:relative;height:150px;overflow:hidden;border-top:1px solid var(--line);border-bottom:1px solid var(--line);
background:url('/assets/painting.jpg') center 62%/cover no-repeat}
.art-strip:after{content:"";position:absolute;inset:0;background:linear-gradient(180deg,rgba(255,255,255,.85),rgba(255,255,255,.15) 40%,rgba(255,255,255,.85))}
.art-strip .grain{position:absolute;inset:0;opacity:.12;mix-blend-mode:multiply;
background-image:url("data:image/svg+xml;utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='.55'/%3E%3C/svg%3E")}
/* 可读性微调:背景轻微模糊 + 更强的白纱,meta 加深 */
.hero-bg img{filter:blur(1.5px) saturate(1.05)}
.hero-veil{background:
radial-gradient(62% 58% at 50% 40%, rgba(255,255,255,.96) 0%, rgba(255,255,255,.86) 46%, rgba(255,255,255,.32) 100%),
linear-gradient(180deg, rgba(255,255,255,.94) 0%, rgba(255,255,255,.66) 50%, rgba(255,255,255,.35) 76%, #fff 100%)}
.hero .meta{color:#6b7280}
.hero-art{padding:72px 0 84px}
/* 头图白纱减淡:让油画色彩多透出来一点(文字仍保持可读) */
.hero-bg img{filter:blur(1px) saturate(1.06)}
.hero-veil{background:
radial-gradient(62% 58% at 50% 40%, rgba(255,255,255,.86) 0%, rgba(255,255,255,.70) 46%, rgba(255,255,255,.16) 100%),
linear-gradient(180deg, rgba(255,255,255,.84) 0%, rgba(255,255,255,.52) 50%, rgba(255,255,255,.20) 76%, #fff 100%)}
+194
View File
@@ -0,0 +1,194 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Image Workbench · 下载</title>
<link rel="stylesheet" href="/assets/style.css?v=" + encodeURIComponent(latest.version + '-' + Date.now().toString(36)) + "">
<style>
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}
.dlwrap{max-width:760px;margin:0 auto;padding:48px 0 64px}
h1{font-size:27px;margin:0 0 6px;letter-spacing:-.01em}
.sub{color:var(--muted);margin:0 0 34px}
h2{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);font-weight:600;margin:38px 0 2px}
.row{display:flex;align-items:center;gap:16px;padding:15px 0;border-bottom:1px solid var(--line)}
.row:first-of-type{border-top:1px solid var(--line)}
.name{flex:1 1 auto;font-weight:550}
.hint{color:var(--muted);font-size:12.5px;font-weight:400;margin-top:2px}
.meta{flex:0 0 auto;text-align:right;color:var(--muted);font-size:13px}
.hash{font-size:11.5px;opacity:.75;margin-top:2px;font-variant-numeric:tabular-nums}
.btn{flex:0 0 auto;font-size:13px;padding:7px 18px;border-radius:8px;background:var(--brand);color:var(--bg);text-decoration:none}
.btn:hover{opacity:.88}
.muted{flex:0 0 auto;font-size:13px;color:var(--muted);opacity:.7}
.foot{margin-top:46px;color:var(--muted);font-size:12.5px;line-height:1.8}
.foot a{color:inherit}
code{font-size:12.5px}
.steps{margin:6px 0 0;padding-left:22px;color:var(--fg2);font-size:13.5px;line-height:1.9}
.steps li{margin:2px 0}
.steps b{color:var(--fg);font-weight:600}
pre.cmd{margin:10px 0 0;padding:10px 12px;background:var(--bg2);border:1px solid var(--line);border-radius:8px;overflow-x:auto}
pre.cmd code{font-size:12px;color:var(--fg)}
.note{margin:10px 0 0;color:var(--muted);font-size:12.5px;line-height:1.8}
</style>
</head>
<body>
<nav><div class="wrap inner">
<a class="brand" href="/"><span class="dot">IW</span>Image Workbench</a>
<div class="links">
<a href="/">首页</a>
<a href="/download/" class="on">下载</a>
<a href="/plugins/">插件</a>
<a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码</a>
</div>
<div class="right">
<a class="btn" href="/plugins/">插件市场</a>
<a class="btn primary" href="/download/">下载</a>
</div>
</div></nav>
<div class="wrap"><div class="dlwrap">
<h1>Image Workbench</h1>
<p class="sub">本地优先的 AI 生图无限画布 · 桌面版(Tauri v2)</p>
<h2>下载</h2>
<div class="row">
<div class="name">macOS · Apple Silicon<div class="hint">M1 / M2 / M3 / M4</div></div>
<div class="meta">版本 3.25.18 · 7.5 MB · .dmg<div class="hash">sha256 a603a033a91afa5b…</div></div>
<a class="btn" href="/updates/darwin-aarch64/image-workbench_3.25.18_aarch64.dmg">下载</a>
</div>
<div class="row">
<div class="name">macOS · Intel<div class="hint">x86_64</div></div>
<div class="meta">版本 3.25.18 · 7.8 MB · .dmg<div class="hash">sha256 35b1b4a2acaea713…</div></div>
<a class="btn" href="/updates/darwin-x86_64/image-workbench_3.25.18_x64.dmg">下载</a>
</div>
<div class="row">
<div class="name">Windows · x64<div class="hint">需要 WebView2</div></div>
<div class="meta"></div>
<span class="muted">暂未提供</span>
</div>
<h2>系统要求</h2>
<div class="row">
<div class="name">macOS 12 及以上 / Windows 10 1803 及以上(含 WebView2)
<div class="hint">数据全部保存在本地目录 <code>~/Documents/ImageWorkbench</code>,可整目录备份与迁移。</div>
</div>
</div>
<h2>安装步骤(macOS)</h2>
<ol class="steps">
<li>下载上面的 <b>.dmg</b>(Apple 芯片选 Apple Silicon;老 Intel 机器选 Intel)。</li>
<li>双击打开 dmg,把 <b>Image Workbench</b> 图标拖进「应用程序」文件夹。</li>
<li>第一次启动:打开「应用程序」,<b>右键点图标 → 打开</b>,弹窗里再点一次「打开」。</li>
<li>如果提示「已损坏」或「无法验证开发者」:打开「终端」,粘贴执行下面这条命令,然后重新打开应用。</li>
</ol>
<pre class="cmd"><code>xattr -dr com.apple.quarantine "/Applications/image-workbench.app"</code></pre>
<p class="note">说明:安装包未做 Apple 公证($99/年开发者账号),所以第一次需要手动放行;这一步只做一次。<br>
之后有新版本时,应用内 <b>设置 → 通用 → 版本与更新 → 检查更新</b> 就能一键升级,不用再下载安装包。</p>
<h2>安装步骤(Windows)</h2>
<ol class="steps">
<li>下载 <b>.exe</b>(NSIS 安装包,按当前用户安装,不需要管理员权限)。</li>
<li>双击运行;若出现「Windows 已保护你的电脑」,点「更多信息 → 仍要运行」。</li>
<li>安装完成后从开始菜单启动;数据在 <code>%USERPROFILE%DocumentsImageWorkbench</code>。</li>
</ol>
<h2>历史版本</h2>
<div class="row">
<div class="name">3.25.18<div class="hint">Intel 版:工单#3 六项</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.25.17<div class="hint">Intel 版:图标细节修正</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.25.16<div class="hint">Intel 版:新图标</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.25.15<div class="hint">Windows:桌面客户端版(网页部署面移除 + 独立更新清单)</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
</div>
<div class="row">
<div class="name">3.25.14<div class="hint">Intel 版:CSP 修复 + 外观 tab</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.25.13<div class="hint">Windows:图片目录自愈 + 启动补齐工作目录(修丢图)</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
</div>
<div class="row">
<div class="name">3.25.12<div class="hint">Intel 版:图片目录自愈 + 不回退 Cache</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.25.11<div class="hint">Windows:单实例 + 外链系统浏览器 + 原生通知 + 窗口下限 + 仅 nsis 产物</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
</div>
<div class="row">
<div class="name">3.25.10<div class="hint">Intel 版:图片持久化修复</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.25.9<div class="hint">Windows:图片登记立即落盘 + 清理前报数</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
</div>
<div class="row">
<div class="name">3.25.8<div class="hint">Intel 版:同图导入与图片清理修复</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.25.7<div class="hint">Windows:剪贴板 PNG 传输 + 路径文本转图片 + 大图不卡</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
</div>
<div class="row">
<div class="name">3.25.6<div class="hint">Intel 版:粘贴语义修正</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.25.5<div class="hint">Intel 版:库面板粘贴修复</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.25.4<div class="hint">Intel 版:剪贴板兜底</div></div>
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.25.3<div class="hint">Windows:剪贴板修复(Cmd+C/V、粘贴图片/文本、复制图片)+ 可自动更新</div></div>
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
</div>
<div class="row">
<div class="name">3.25.2<div class="hint">Windows:无内置插件 + 市场安装 + 页内确认 + 在线更新(首次需手动安装)</div></div>
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
</div>
<div class="row">
<div class="name">3.25.1<div class="hint">Intel Mac 版:性能与数据卫生(图库清单去 base64、缩略图落盘、回收 20.2MB)</div></div>
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
</div>
<div class="row">
<div class="name">3.25.0<div class="hint">应用不再内置插件(全部从市场安装);页内确认替代原生 confirm;插件市场与开发者模式</div></div>
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon</div></div>
</div>
<div class="row">
<div class="name">3.24.85<div class="hint">每张画布单独成文件、资源库分类、设置面板重构、下载改为按需落盘</div></div>
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon</div></div>
</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-18
</div>
</div></div>
<footer><div class="wrap">
<div class="cols">
<div><div style="color:#fff;font-weight:640;margin-bottom:8px">Image Workbench</div>
<div style="font-size:13px;line-height:1.8">本地优先的 AI 生图无限画布。图片、提示词与模型配置全部留在你自己的电脑里。</div></div>
<div><h4>产品</h4><a href="/">首页</a><a href="/download/">下载</a><a href="/plugins/">插件市场</a></div>
<div><h4>资源</h4><a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码仓库</a><a href="https://git.maqiart.eu.org/malongan/iwb-plugins-desktop" target="_blank" rel="noopener">插件仓库</a><a href="/updates/latest.json" target="_blank" rel="noopener">更新源</a></div>
<div><h4>说明</h4><a href="/download/">安装步骤</a><a href="/plugins/">插件安装</a></div>
</div>
<div class="copy"><span>© Image Workbench</span><span>数据保存在本地 · 不上传任何图片</span></div>
</div></footer>
</body>
</html>
+145
View File
@@ -0,0 +1,145 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Image Workbench · 本地优先的 AI 生图工作台</title>
<meta name="description" content="本地优先的 AI 生图无限画布:节点式工作流、插件按需安装、数据全部留在本机。">
<link rel="stylesheet" href="/assets/style.css?v=3.25.18-mwlycbyo">
</head><body>
<nav><div class="wrap inner">
<a class="brand" href="/"><span class="dot">IW</span>Image Workbench</a>
<div class="links">
<a href="/" class="on">首页</a>
<a href="/download/">下载</a>
<a href="/plugins/">插件</a>
<a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码</a>
</div>
<div class="right">
<a class="btn" href="/plugins/">插件市场</a>
<a class="btn primary" href="/download/">下载 v3.25.18</a>
</div>
</div></nav>
<main>
<section class="hero hero-art">
<div class="hero-bg"><img src="/assets/painting.jpg?v=3.25.18-mwlycbyo" alt=""></div>
<div class="hero-veil"></div>
<div class="wrap">
<span class="kicker">v3.25.18 · macOS / Windows · 数据在本地</span>
<h1>本地优先的<br>AI 生图无限画布</h1>
<p class="sub">用节点把「参考图 → 提示词 → 批量生成 → 图库」串成一条生产线。<br>图片、提示词、模型配置全部留在你自己的电脑里,插件按需安装。</p>
<div class="cta">
<a class="btn primary lg" href="/download/">下载 v3.25.18</a>
<a class="btn lg" href="/plugins/">浏览 7 个插件</a>
</div>
<div class="meta">支持 macOS 12+ 与 Windows 10 1803+ · 安装包约 7 MB · 无需登录</div>
</div></section>
<section class="section"><div class="wrap">
<h2>为「一个人跑完整条产线」而做</h2>
<p class="lead">不做又一个在线生图站点。它活在你的桌面上,把生图、修图、批量、图库和插件放在同一张画布上。</p>
<div class="grid c3">
<div class="card"><div class="ico" style="background:#eef2ff">💻</div>
<h3>本地优先</h3><p>图片与数据保存在 ~/Documents/ImageWorkbench,不经服务器中转;可整目录备份、迁移到新电脑。</p></div>
<div class="card"><div class="ico" style="background:#fff7ed">🕸️</div>
<h3>节点式无限画布</h3><p>参考图 → 提示词 → 生成 → 图库,用连线把工作流串起来;一张画布容纳整条生产线。</p></div>
<div class="card"><div class="ico" style="background:#ecfdf5">🧩</div>
<h3>插件按需安装</h3><p>应用本体不含插件,需要什么装什么;可随时启停,关闭后入口自动隐藏。</p></div>
</div>
</div></section>
<section class="section"><div class="wrap">
<h2>插件:本体不带,需要的自己装</h2>
<p class="lead">应用本体不再内置插件。设置里打开市场,点「安装」,重启即可用;不需要的点一下就能关掉。</p>
<div class="grid c3">
<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.0 · 官方</div></div></div>
<div class="desc">资源中心勾选节点,串行批量生成并打包 ZIP 下载</div>
<div class="tags"><span class="tag">出图</span><span class="tag">批处理</span></div>
</div>
<div class="pcard" data-name="空白画布 blank-canvas 新建空白画布节点,用于分区分组 画布 效率" data-tags="画布,效率">
<div class="head"><span class="av" style="background:#eef2f6">⬜</span>
<div><div class="nm">空白画布</div><div class="ver">v1.0.0 · 官方</div></div></div>
<div class="desc">新建空白画布节点,用于分区分组</div>
<div class="tags"><span class="tag">画布</span><span class="tag">效率</span></div>
</div>
<div class="pcard" data-name="标注 / 修图 image-annotate 在画布内标注、涂抹、局部重绘 修图 标注" data-tags="修图,标注">
<div class="head"><span class="av" style="background:#fdeaea">🖌️</span>
<div><div class="nm">标注 / 修图</div><div class="ver">v1.20.6 · 官方</div></div></div>
<div class="desc">在画布内标注、涂抹、局部重绘</div>
<div class="tags"><span class="tag">修图</span><span class="tag">标注</span></div>
</div>
<div class="pcard" data-name="位图转矢量 image-vectorize 把位图转成 svg 矢量路径 转换 矢量" data-tags="转换,矢量">
<div class="head"><span class="av" style="background:#eaf3ea">✒️</span>
<div><div class="nm">位图转矢量</div><div class="ver">v0.4.2 · 官方</div></div></div>
<div class="desc">把位图转成 SVG 矢量路径</div>
<div class="tags"><span class="tag">转换</span><span class="tag">矢量</span></div>
</div>
<div class="pcard" data-name="风格库 style-source 风格提示词库与一键套用 提示词 风格" data-tags="提示词,风格">
<div class="head"><span class="av" style="background:#fdf0e6">🎨</span>
<div><div class="nm">风格库</div><div class="ver">v1.3.2 · 官方</div></div></div>
<div class="desc">风格提示词库与一键套用</div>
<div class="tags"><span class="tag">提示词</span><span class="tag">风格</span></div>
</div>
<div class="pcard" data-name="白底图 white-bg-800 批量生成电商白底图(800px) 电商 出图" data-tags="电商,出图">
<div class="head"><span class="av" style="background:#eef7fb">🧾</span>
<div><div class="nm">白底图</div><div class="ver">v1.2.1 · 官方</div></div></div>
<div class="desc">批量生成电商白底图(800px)</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/">查看全部 7 个插件</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.25.18_aarch64.dmg"><div class="n">macOS · Apple Silicon</div><div class="s">M1 / M2 / M3 / M4 · 7.5 MB · .dmg</div></a>
<a href="/updates/darwin-x86_64/image-workbench_3.25.18_x64.dmg"><div class="n">macOS · Intel</div><div class="s">x86_64 · 7.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>
</main>
<footer><div class="wrap">
<div class="cols">
<div><div style="color:#fff;font-weight:640;margin-bottom:8px">Image Workbench</div>
<div style="font-size:13px;line-height:1.8">本地优先的 AI 生图无限画布。图片、提示词与模型配置全部留在你自己的电脑里。</div></div>
<div><h4>产品</h4><a href="/">首页</a><a href="/download/">下载</a><a href="/plugins/">插件市场</a></div>
<div><h4>资源</h4><a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码仓库</a><a href="https://git.maqiart.eu.org/malongan/iwb-plugins-desktop" target="_blank" rel="noopener">插件仓库</a><a href="/updates/latest.json" target="_blank" rel="noopener">更新源</a></div>
<div><h4>说明</h4><a href="/download/">安装步骤</a><a href="/plugins/">插件安装</a></div>
</div>
<div class="copy"><span>© 2026 Image Workbench</span><span>数据保存在本地 · 不上传任何图片</span></div>
</div></footer>
</body></html>
<script>
(function () {
var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches
var targets = [].slice.call(document.querySelectorAll('.section h2, .section p.lead, .card, .pcard, .dl a'))
targets.forEach(function (el) { el.classList.add('reveal') })
if (!reduce && 'IntersectionObserver' in window) {
var io = new IntersectionObserver(function (entries) {
entries.forEach(function (e) {
if (!e.isIntersecting) return
var el = e.target
var idx = targets.indexOf(el) % 4
el.style.transitionDelay = (idx * 60) + 'ms'
el.classList.add('in')
io.unobserve(el)
})
}, { rootMargin: '0px 0px -8% 0px', threshold: 0.12 })
targets.forEach(function (el) { io.observe(el) })
} else { targets.forEach(function (el) { el.classList.add('in') }) }
var art = document.querySelector('.art-frame')
if (art && !reduce) {
var raf = 0
var onScroll = function () {
if (raf) return
raf = requestAnimationFrame(function () {
raf = 0
var y = Math.min(1, Math.max(0, window.scrollY / 700))
art.style.transform = 'translate3d(0,' + (y * -14) + 'px,0)'
})
}
window.addEventListener('scroll', onScroll, { passive: true }); onScroll()
}
})()
</script>
+132
View File
@@ -0,0 +1,132 @@
{
"version": 1,
"updatedAt": "2026-11-17T13:04:29.617Z",
"plugins": [
{
"id": "batch-export",
"name": "批量出图",
"desc": "资源中心勾选节点,串行批量生成并打包 ZIP 下载",
"author": "official",
"icon": "🗂️",
"color": "#e8f0fe",
"tags": [
"出图",
"批处理"
],
"version": "1.2.0",
"apiVersion": 1,
"file": "plugins/plugin-batch-export.b7d13ba66cf9.js",
"size": 44329,
"sha256": "b7d13ba66cf97ff65e94305328183a1a3b5a45b0393f3a63f77f6b7b46795389",
"integrity": "sha256-t9E7pmz5f/ZelDBTKBg6GjtaRbA5Pzpj939re0Z5U4k="
},
{
"id": "blank-canvas",
"name": "空白画布",
"desc": "新建空白画布节点,用于分区分组",
"author": "official",
"icon": "⬜",
"color": "#eef2f6",
"tags": [
"画布",
"效率"
],
"version": "1.0.0",
"apiVersion": 1,
"file": "plugins/plugin-blank-canvas.67763893fa99.js",
"size": 6094,
"sha256": "67763893fa99c8fe1d8bcf640426f5bbc576abd35bcdc84c910b7b08f79964f9",
"integrity": "sha256-Z3Y4k/qZyP4di89kBCb1u8V2q9NbzchMkQt7CPeZZPk="
},
{
"id": "image-annotate",
"name": "标注 / 修图",
"desc": "在画布内标注、涂抹、局部重绘",
"author": "official",
"icon": "🖌️",
"color": "#fdeaea",
"tags": [
"修图",
"标注"
],
"version": "1.20.6",
"apiVersion": 1,
"file": "plugins/plugin-image-annotate.7a865c7c353c.js",
"size": 461523,
"sha256": "7a865c7c353c3fbcaac551a8aeb5acd1bf624ca25f104db96fce493c3084b24f",
"integrity": "sha256-eoZcfDU8P7yqxVGorrWs0b9iTKJfEE25b85JPDCEsk8="
},
{
"id": "image-vectorize",
"name": "位图转矢量",
"desc": "把位图转成 SVG 矢量路径",
"author": "official",
"icon": "✒️",
"color": "#eaf3ea",
"tags": [
"转换",
"矢量"
],
"version": "0.4.2",
"apiVersion": 1,
"file": "plugins/plugin-image-vectorize.03b5fc850c34.js",
"size": 144780,
"sha256": "03b5fc850c34ddc0996bafc367798fb60aecc9bb23b92990dd5ccc59ed74bfc9",
"integrity": "sha256-A7X8hQw03cCZa6/DZ3mPtgrsybsjuSmQ3VzMWe10v8k="
},
{
"id": "style-source",
"name": "风格库",
"desc": "风格提示词库与一键套用",
"author": "official",
"icon": "🎨",
"color": "#fdf0e6",
"tags": [
"提示词",
"风格"
],
"version": "1.3.2",
"apiVersion": 1,
"file": "plugins/plugin-style-source.ee7168565a44.js",
"size": 69925,
"sha256": "ee7168565a44d49daaf300f62d5c7a106e60fba29a9e4888ff8bfd9abd2e3178",
"integrity": "sha256-7nFoVlpE1J2q8wD2LVx6EG5g+6KankiI/4v9mr0uMXg="
},
{
"id": "white-bg-800",
"name": "白底图",
"desc": "批量生成电商白底图(800px)",
"author": "official",
"icon": "🧾",
"color": "#eef7fb",
"tags": [
"电商",
"出图"
],
"version": "1.2.1",
"apiVersion": 1,
"file": "plugins/plugin-white-bg-800.a5a92f045c0d.js",
"size": 14957,
"sha256": "a5a92f045c0d4046b205562019b2a6354afd14aa92375b78559d48f2ce9b74ee",
"integrity": "sha256-pakvBFwNQEayBVYgGbKmNUr9FKqSN1t4VZ1I8s6bdO4="
},
{
"id": "xianyi-cutout",
"name": "鲜艺抠图",
"desc": "接入鲜艺抠图模型的一键去背景",
"author": "official",
"icon": "✂️",
"color": "#f3eafd",
"tags": [
"抠图",
"去背景"
],
"version": "1.0.3",
"apiVersion": 1,
"file": "plugins/plugin-xianyi-cutout.79c8c47dfc61.js",
"size": 4488,
"sha256": "79c8c47dfc6187b8af2688763e7f63034bb26867ccefbf135ed76d3745d6e24d",
"integrity": "sha256-ecjEffxhh7ivJoh2Pn9jA0uyaGfM778TXtdtN0XW4k0="
}
]
}
+119
View File
@@ -0,0 +1,119 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>插件市场 · Image Workbench</title>
<link rel="stylesheet" href="/assets/style.css?v=3.25.18-mwlycbyo">
</head><body>
<nav><div class="wrap inner">
<a class="brand" href="/"><span class="dot">IW</span>Image Workbench</a>
<div class="links">
<a href="/">首页</a>
<a href="/download/">下载</a>
<a href="/plugins/" class="on">插件</a>
<a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码</a>
</div>
<div class="right">
<a class="btn" href="/plugins/">插件市场</a>
<a class="btn primary" href="/download/">下载 v3.25.18</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">共 7 个插件。安装方式:应用内 <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>
<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>
</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="批量出图 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.0 · 官方</div></div></div>
<div class="desc">资源中心勾选节点,串行批量生成并打包 ZIP 下载</div>
<div class="tags"><span class="tag">出图</span><span class="tag">批处理</span></div>
</div>
<div class="pcard" data-name="空白画布 blank-canvas 新建空白画布节点,用于分区分组 画布 效率" data-tags="画布,效率">
<div class="head"><span class="av" style="background:#eef2f6">⬜</span>
<div><div class="nm">空白画布</div><div class="ver">v1.0.0 · 官方</div></div></div>
<div class="desc">新建空白画布节点,用于分区分组</div>
<div class="tags"><span class="tag">画布</span><span class="tag">效率</span></div>
</div>
<div class="pcard" data-name="标注 / 修图 image-annotate 在画布内标注、涂抹、局部重绘 修图 标注" data-tags="修图,标注">
<div class="head"><span class="av" style="background:#fdeaea">🖌️</span>
<div><div class="nm">标注 / 修图</div><div class="ver">v1.20.6 · 官方</div></div></div>
<div class="desc">在画布内标注、涂抹、局部重绘</div>
<div class="tags"><span class="tag">修图</span><span class="tag">标注</span></div>
</div>
<div class="pcard" data-name="位图转矢量 image-vectorize 把位图转成 svg 矢量路径 转换 矢量" data-tags="转换,矢量">
<div class="head"><span class="av" style="background:#eaf3ea">✒️</span>
<div><div class="nm">位图转矢量</div><div class="ver">v0.4.2 · 官方</div></div></div>
<div class="desc">把位图转成 SVG 矢量路径</div>
<div class="tags"><span class="tag">转换</span><span class="tag">矢量</span></div>
</div>
<div class="pcard" data-name="风格库 style-source 风格提示词库与一键套用 提示词 风格" data-tags="提示词,风格">
<div class="head"><span class="av" style="background:#fdf0e6">🎨</span>
<div><div class="nm">风格库</div><div class="ver">v1.3.2 · 官方</div></div></div>
<div class="desc">风格提示词库与一键套用</div>
<div class="tags"><span class="tag">提示词</span><span class="tag">风格</span></div>
</div>
<div class="pcard" data-name="白底图 white-bg-800 批量生成电商白底图(800px) 电商 出图" data-tags="电商,出图">
<div class="head"><span class="av" style="background:#eef7fb">🧾</span>
<div><div class="nm">白底图</div><div class="ver">v1.2.1 · 官方</div></div></div>
<div class="desc">批量生成电商白底图(800px)</div>
<div class="tags"><span class="tag">电商</span><span class="tag">出图</span></div>
</div>
<div class="pcard" data-name="鲜艺抠图 xianyi-cutout 接入鲜艺抠图模型的一键去背景 抠图 去背景" data-tags="抠图,去背景">
<div class="head"><span class="av" style="background:#f3eafd">✂️</span>
<div><div class="nm">鲜艺抠图</div><div class="ver">v1.0.3 · 官方</div></div></div>
<div class="desc">接入鲜艺抠图模型的一键去背景</div>
<div class="tags"><span class="tag">抠图</span><span class="tag">去背景</span></div>
</div>
</div>
<div class="note" style="margin-top:26px">插件安装后会写进你的资料目录 <code>~/Documents/ImageWorkbench/plugins/</code>;卸载只删插件文件,不动画布与图库。</div>
</div></section>
</main>
<footer><div class="wrap">
<div class="cols">
<div><div style="color:#fff;font-weight:640;margin-bottom:8px">Image Workbench</div>
<div style="font-size:13px;line-height:1.8">本地优先的 AI 生图无限画布。图片、提示词与模型配置全部留在你自己的电脑里。</div></div>
<div><h4>产品</h4><a href="/">首页</a><a href="/download/">下载</a><a href="/plugins/">插件市场</a></div>
<div><h4>资源</h4><a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码仓库</a><a href="https://git.maqiart.eu.org/malongan/iwb-plugins-desktop" target="_blank" rel="noopener">插件仓库</a><a href="/updates/latest.json" target="_blank" rel="noopener">更新源</a></div>
<div><h4>说明</h4><a href="/download/">安装步骤</a><a href="/plugins/">插件安装</a></div>
</div>
<div class="copy"><span>© 2026 Image Workbench</span><span>数据保存在本地 · 不上传任何图片</span></div>
</div></footer>
<script>
var q = document.getElementById('q'), list = document.getElementById('list'), chips = document.getElementById('chips'), activeTag = ''
function apply () {
var kw = (q.value || '').trim().toLowerCase()
Array.prototype.forEach.call(list.children, function (el) {
var okKw = !kw || el.dataset.name.indexOf(kw) >= 0
var okTag = !activeTag || (',' + el.dataset.tags + ',').indexOf(',' + activeTag + ',') >= 0
var ok = okKw && okTag
el.style.display = ok ? '' : 'none'
})
}
q.addEventListener('input', apply)
chips.addEventListener('click', function (e) {
var b = e.target.closest('button[data-tag]'); if (!b) return
Array.prototype.forEach.call(chips.children, function (x) { x.style.background = ''; x.style.color = ''; x.style.borderColor = 'transparent' })
b.style.background = '#111'; b.style.color = '#fff'; b.style.borderColor = '#111'
activeTag = b.dataset.tag || ''
apply()
})
</script>
</body></html>
+417
View File
@@ -0,0 +1,417 @@
{
"app": "Image Workbench",
"subtitle": "本地优先的 AI 生图无限画布 · 桌面版(Tauri v2)",
"updatedAt": "2026-11-18T10:01:56.791Z",
"releases": [
{
"version": "3.25.18",
"date": "2026-11-18",
"notes": "Intel 版:工单#3 六项",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.18_aarch64.dmg",
"size": 7832387,
"sha256": "a603a033a91afa5b3f941ba4912ad24e424f031d230a0b5a158695512161b0fb",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.18_x64.dmg",
"size": 8131102,
"sha256": "35b1b4a2acaea7134209e433b23d70bbc0d56d1ad149b80e5f0758afc2e6ef89",
"kind": "dmg"
}
}
},
{
"version": "3.25.17",
"date": "2026-11-18",
"notes": "Intel 版:图标细节修正",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.17_aarch64.dmg",
"size": 7827715,
"sha256": "b0eb338adafbbcba3355ae7fc669be5456a11174d2c2e2bd2d289426665c39ec",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.17_x64.dmg",
"size": 8127899,
"sha256": "543cd456ef75211172795da38c166ccb29dce42254d599f3d442b6ce641a4753",
"kind": "dmg"
}
}
},
{
"version": "3.25.16",
"date": "2026-11-18",
"notes": "Intel 版:新图标",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.16_aarch64.dmg",
"size": 7876955,
"sha256": "fdc3e93711d765022c4725340bbbb0cbac33ef0c854d2547b9a036f1b13d8e10",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.16_x64.dmg",
"size": 8174517,
"sha256": "f0948b377b9bd872b206227f46d21e81927914350d538e9ac16c4699da31850e",
"kind": "dmg"
}
}
},
{
"version": "3.25.15",
"date": "2026-11-18",
"notes": "Windows:桌面客户端版(网页部署面移除 + 独立更新清单)",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.15_aarch64.dmg",
"size": 7935920,
"sha256": "b256cc50733e10307afdc18454b567965dc5c85ce60342424feedb2815a2af54",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.15_x64.dmg",
"size": 8233792,
"sha256": "8b1c0c38b2981b6272ed22a77f73cc145c5e2c0152ec8bd8e2ee3958f15792d1",
"kind": "dmg"
},
"windows-x86_64": {
"file": "updates/windows-x86_64/image-workbench_3.25.15_x64-setup.exe",
"size": 4911427,
"sha256": "030dc4660880d494c92052d97b2e23ee0dbf178261550cb3b232631cfd9b48f3",
"kind": "exe"
}
}
},
{
"version": "3.25.14",
"date": "2026-11-18",
"notes": "Intel 版:CSP 修复 + 外观 tab",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.14_aarch64.dmg",
"size": 7936466,
"sha256": "87e908b98900ff1b48cb70344d14c17b37149c8dd9716d53361d12fbf509c096",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.14_x64.dmg",
"size": 8237874,
"sha256": "2cfadfad91399c53b1b2fbf42d0c0ac521b0ebaec1ee481911c9af3d15c3bbba",
"kind": "dmg"
}
}
},
{
"version": "3.25.13",
"date": "2026-11-18",
"notes": "Windows:图片目录自愈 + 启动补齐工作目录(修丢图)",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.13_aarch64.dmg",
"size": 7935763,
"sha256": "863a5ff87a1debc0baf2dbe5033d8313c90649a6f48577408a23846d2b106e23",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.13_x64.dmg",
"size": 8235328,
"sha256": "25b4ad7237058ddd06d2a8f361114304ff03a37dd841d8c54a31d9d9e4d7d0e6",
"kind": "dmg"
},
"windows-x86_64": {
"file": "updates/windows-x86_64/image-workbench_3.25.13_x64-setup.exe",
"size": 4912010,
"sha256": "669b1dfa58c4785c11c906b70e2cb4319d2743a40c1b7b9b4dbd8e9ceaf4f47c",
"kind": "exe"
}
}
},
{
"version": "3.25.12",
"date": "2026-11-18",
"notes": "Intel 版:图片目录自愈 + 不回退 Cache",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.12_aarch64.dmg",
"size": 7935223,
"sha256": "ddea5bf24ddfab943afce8d4a9eeb744c09fd15a204d0c359149025ecda4c0d8",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.12_x64.dmg",
"size": 8232027,
"sha256": "87d69fb85ce19c5e7993cf02ee35568352f0c6c4b026892e0a0d49e1505aa432",
"kind": "dmg"
}
}
},
{
"version": "3.25.11",
"date": "2026-11-18",
"notes": "Windows:单实例 + 外链系统浏览器 + 原生通知 + 窗口下限 + 仅 nsis 产物",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.11_aarch64.dmg",
"size": 7931660,
"sha256": "4d6d589d87b5a463310d73bd84da06186e2a291e536e75fadcce047cb2f86c49",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.11_x64.dmg",
"size": 8234268,
"sha256": "13ccf3b80e0162524c1d73cdae96c914288adcb5649b7d082d260649123d4970",
"kind": "dmg"
},
"windows-x86_64": {
"file": "updates/windows-x86_64/image-workbench_3.25.11_x64-setup.exe",
"size": 4905095,
"sha256": "17702145cff43a02a4e7b50cdccded050d44819a9d6b80b539ae8997c7f4f0d4",
"kind": "exe"
}
}
},
{
"version": "3.25.10",
"date": "2026-11-18",
"notes": "Intel 版:图片持久化修复",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.10_aarch64.dmg",
"size": 7671575,
"sha256": "1882ed66713df4cfd0839a6d5220e717c297d31b050bfcbfb45efff33e660e61",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.10_x64.dmg",
"size": 7978877,
"sha256": "bca63766b951756228d513b1dc6d6c9e76d8bc5c4cc898171a24178b9f2e23ff",
"kind": "dmg"
}
}
},
{
"version": "3.25.9",
"date": "2026-11-18",
"notes": "Windows:图片登记立即落盘 + 清理前报数",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.9_aarch64.dmg",
"size": 7674858,
"sha256": "030b18cc29dd8f5e65b1906ef141a99ea34daadfacf827c10b75a2b0c957c94a",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.9_x64.dmg",
"size": 7977320,
"sha256": "06fd92df7fa6adf762d62450338f2f005c7c77cc9379bda4feaf49f27791f191",
"kind": "dmg"
},
"windows-x86_64": {
"file": "updates/windows-x86_64/image-workbench_3.25.9_x64-setup.exe",
"size": 4771479,
"sha256": "d065e2a00eb59aeb55d101d9c22d39fb1298833b3782403379a72041ceb78230",
"kind": "exe"
}
}
},
{
"version": "3.25.8",
"date": "2026-11-18",
"notes": "Intel 版:同图导入与图片清理修复",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.8_aarch64.dmg",
"size": 7673011,
"sha256": "a3f6293d099f5624705138a342a8e95517e9e9bf1c7a8f88e84a573e9fd87955",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.8_x64.dmg",
"size": 7978802,
"sha256": "5716570a8d6bed248df66e2b1d82946265df2d5293c23753e3b2ae4ee3a810d9",
"kind": "dmg"
}
}
},
{
"version": "3.25.7",
"date": "2026-11-18",
"notes": "Windows:剪贴板 PNG 传输 + 路径文本转图片 + 大图不卡",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.7_aarch64.dmg",
"size": 7669562,
"sha256": "e4b6b7561391631130a91f0dd408ac03823f5c46963c3a7e5464a75210935af6",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.7_x64.dmg",
"size": 7978666,
"sha256": "63288e85748e0d360afae76009e6e44a668b9755b270883387380774468a4f33",
"kind": "dmg"
},
"windows-x86_64": {
"file": "updates/windows-x86_64/image-workbench_3.25.7_x64-setup.exe",
"size": 4776945,
"sha256": "7ada5360e52ddd0c1f0a00d124c00612b5a03a34a6c8e128e74178cda8e52a2d",
"kind": "exe"
}
}
},
{
"version": "3.25.6",
"date": "2026-11-18",
"notes": "Intel 版:粘贴语义修正",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.6_aarch64.dmg",
"size": 7657949,
"sha256": "e92264a47106317b7125184ace097873d3c85cede9668137a7392b355e2afa3c",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.6_x64.dmg",
"size": 7942814,
"sha256": "88e143e4e76849226d24dadd8c7ec7f53a3940399cc5173df68330645fa7a33a",
"kind": "dmg"
}
}
},
{
"version": "3.25.5",
"date": "2026-11-18",
"notes": "Intel 版:库面板粘贴修复",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.5_aarch64.dmg",
"size": 7657153,
"sha256": "1506b4ab5b77df7d98bf69fe29de586abbbdcc36f4a01163c8d86e3a75093c0d",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.5_x64.dmg",
"size": 7944240,
"sha256": "97b05edd949987669bfd57b97bc55379d9d0eb676914401e006046632148a352",
"kind": "dmg"
}
}
},
{
"version": "3.25.4",
"date": "2026-11-18",
"notes": "Intel 版:剪贴板兜底",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.4_aarch64.dmg",
"size": 7658606,
"sha256": "0c02574f197fac4839bf937390425786ec872b36d9f8c529f122ee1349e855af",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.4_x64.dmg",
"size": 7940457,
"sha256": "f04664f6e051ae20e07bfb073ff675bbb83493f791ff4651120cdd00e9b0e103",
"kind": "dmg"
}
}
},
{
"version": "3.25.3",
"date": "2026-11-17",
"notes": "Windows:剪贴板修复(Cmd+C/V、粘贴图片/文本、复制图片)+ 可自动更新",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.3_aarch64.dmg",
"size": 7654670,
"sha256": "fd05bf1a186574c611b166693b05a7531e5ec932bbc7cf75391bcd44a0c9eb5f",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.3_x64.dmg",
"size": 7938826,
"sha256": "00388a79069f9a78c48d491f366f73f1ee1500468f9970c8f657e25eb7c4e786",
"kind": "dmg"
},
"windows-x86_64": {
"file": "updates/windows-x86_64/image-workbench_3.25.3_x64-setup.exe",
"size": 4749572,
"sha256": "e2a8cedc3aaaf61528edcf58c648079f618051cb6a4cf655b346315ad6424ba4",
"kind": "exe"
}
}
},
{
"version": "3.25.2",
"date": "2026-11-17",
"notes": "Windows:无内置插件 + 市场安装 + 页内确认 + 在线更新(首次需手动安装)",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.2_aarch64.dmg",
"size": 7360220,
"sha256": "6fb859f2e24d765308a6a97b3c72912d361eb71afb12ec385f2d72cef9cfef2e",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.2_x64.dmg",
"size": 7626433,
"sha256": "07027d97cffde7c0c46b65b2ec875a9fd4dfbdce4494d937e93d46169f61b3f8",
"kind": "dmg"
},
"windows-x86_64": {
"file": "updates/windows-x86_64/image-workbench_3.25.2_x64-setup.exe",
"size": 4681055,
"sha256": "dda001a15e4aa8b25ef6200936884f5d78783309338a9979aadc175c8cc965af",
"kind": "exe"
}
}
},
{
"version": "3.25.1",
"date": "2026-11-17",
"notes": "Intel Mac 版:性能与数据卫生(图库清单去 base64、缩略图落盘、回收 20.2MB)",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.1_aarch64.dmg",
"size": 6545041,
"sha256": "5b711840b36a10ba2983ad48923c662897d25e55ea30de9fb7ea944694648124",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.1_x64.dmg",
"size": 6772292,
"sha256": "7863e4a3257d15a42d698ca79d0edbfb86496f20e67be7389c1de498c01f471b",
"kind": "dmg"
}
}
},
{
"version": "3.25.0",
"date": "2026-11-17",
"notes": "应用不再内置插件(全部从市场安装);页内确认替代原生 confirm;插件市场与开发者模式",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.0_aarch64.dmg",
"size": 6545729,
"sha256": "60d88875b86a4673aa1420fdeea5efda4f37298c61df8a02e7a09ced8ebc834c",
"kind": "dmg"
}
}
},
{
"version": "3.24.85",
"date": "2026-11-17",
"notes": "每张画布单独成文件、资源库分类、设置面板重构、下载改为按需落盘",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.24.85_aarch64.dmg",
"size": 6711472,
"sha256": "4a37725309fb414cfe75143b745d3ad694dd17649ee1b020e21209907ea0ff1e",
"kind": "dmg"
}
}
}
]
}
+4
View File
@@ -0,0 +1,4 @@
# Generated by Cargo
# will have compiled files and executables
/target/
/gen/schemas
+6243
View File
File diff suppressed because it is too large. Load diff
+36
View File
@@ -0,0 +1,36 @@
[package]
name = "image-workbench"
version = "3.25.18"
description = "无限画布 · 生图工作台桌面版"
authors = ["malongan"]
license = ""
repository = ""
edition = "2024"
rust-version = "1.90"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "image_workbench_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2.7.4", features = [] }
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
log = "0.4"
# tray-icon:系统托盘(关闭窗口收进托盘而不是退出)
# tray-icon:系统托盘;image-png:托盘用单色 PNG 模板图标
tauri = { version = "2.12.5", features = ["tray-icon", "image-png"] }
tauri-plugin-log = "2"
tauri-plugin-dialog = "2"
tauri-plugin-fs = "2"
tauri-plugin-http = "2"
tauri-plugin-updater = "2"
tauri-plugin-single-instance = "2"
tauri-plugin-notification = "2"
arboard = "3"
image = { version = "0.25", default-features = false, features = ["png"] }
base64 = "0.22"
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
+63
View File
@@ -0,0 +1,63 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "主窗口最小能力集:资料目录读写(路径运行时授权)+ 原生另存为 + 白名单取图",
"windows": [
"main"
],
"permissions": [
"fs:allow-write-text-file",
"fs:allow-read-text-file",
"core:default",
"dialog:default",
"fs:allow-read-file",
"fs:allow-write-file",
"fs:allow-read-dir",
"fs:allow-mkdir",
"fs:allow-remove",
"fs:allow-rename",
"fs:allow-stat",
"fs:allow-exists",
{
"identifier": "http:default",
"allow": [
{
"url": "https://*.volces.com/**"
},
{
"url": "https://*.aliyuncs.com/**"
},
{
"url": "https://*.myqcloud.com/**"
},
{
"url": "https://*.qiniucdn.com/**"
},
{
"url": "https://*.cloudfront.net/**"
},
{
"url": "https://*.googleusercontent.com/**"
},
{
"url": "https://*.openai.org/**"
},
{
"url": "https://*.oaistatic.com/**"
},
{
"url": "https://*.blob.core.windows.net/**"
},
{
"url": "https://market.maqiart.eu.org/**"
},
{
"url": "https://download.maqiart.eu.org/**"
},
{
"url": "https://git.maqiart.eu.org/**"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1013 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

+421
View File
@@ -0,0 +1,421 @@
use std::sync::atomic::{AtomicBool, Ordering};
use tauri::menu::{Menu, MenuItem};
use tauri::tray::TrayIconBuilder;
use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, WebviewWindow, WindowEvent};
use tauri_plugin_fs::FsExt; // 提供 fs_scope():运行时给「资料目录」授权
// 「是否正在真正退出」:托盘菜单的「退出」或 Cmd+Q 才会置位,
// 其余情况点窗口关闭按钮只是收进托盘,进程继续跑(后台生图不中断)。
static QUITTING: AtomicBool = AtomicBool::new(false);
#[derive(serde::Serialize, serde::Deserialize, Clone, Default)]
struct WindowGeom {
x: i32,
y: i32,
w: u32,
h: u32,
}
fn geom_file(app: &AppHandle) -> Option<std::path::PathBuf> {
app.path()
.app_config_dir()
.ok()
.map(|d| d.join("window-geom.json"))
}
// 只在窗口处于普通状态时记录:最大化/全屏时的尺寸不是用户想恢复的那个尺寸
fn save_geom(win: &WebviewWindow) {
if win.is_maximized().unwrap_or(false) || win.is_fullscreen().unwrap_or(false) {
return;
}
let (Ok(size), Ok(pos)) = (win.inner_size(), win.outer_position()) else {
return;
};
let g = WindowGeom { x: pos.x, y: pos.y, w: size.width, h: size.height };
let app = win.app_handle();
if let Some(p) = geom_file(app) {
if let Some(dir) = p.parent() {
let _ = std::fs::create_dir_all(dir);
}
if let Ok(txt) = serde_json::to_string(&g) {
let _ = std::fs::write(p, txt);
}
}
}
// 恢复上次窗口大小与位置;中心点不在任何显示器内就只恢复尺寸(换过显示器不至于把窗口丢到屏幕外)
fn restore_geom(win: &WebviewWindow, app: &AppHandle) {
let Some(p) = geom_file(app) else { return };
let Ok(txt) = std::fs::read_to_string(p) else { return };
let Ok(g) = serde_json::from_str::<WindowGeom>(&txt) else { return };
// 最小尺寸与 tauri.conf.json 的 minWidth/minHeight 对齐:否则会恢复出一个
// 比窗口下限还小的窗口(实测 1051x488 时画布渲染成空白)
let w = g.w.max(1024);
let h = g.h.max(640);
let _ = win.set_size(PhysicalSize::new(w, h));
let cx = g.x + (w as i32) / 2;
let cy = g.y + (h as i32) / 2;
let visible = win
.available_monitors()
.map(|ms| {
ms.iter().any(|m| {
let mp = m.position();
let ms = m.size();
cx >= mp.x && cx <= mp.x + ms.width as i32 && cy >= mp.y && cy <= mp.y + ms.height as i32
})
})
.unwrap_or(false);
if visible {
let _ = win.set_position(PhysicalPosition::new(g.x, g.y));
}
}
fn show_main(app: &AppHandle) {
if let Some(w) = app.get_webview_window("main") {
let _ = w.show();
let _ = w.unminimize();
let _ = w.set_focus();
}
}
// 系统托盘:左键(macOS:点图标出菜单)+ 菜单「显示主窗口 / 隐藏到托盘 / 退出」
fn build_tray(app: &AppHandle) -> tauri::Result<()> {
let show = MenuItem::with_id(app, "show", "显示主窗口", true, None::<&str>)?;
let hide = MenuItem::with_id(app, "hide", "隐藏到托盘", true, None::<&str>)?;
let quit = MenuItem::with_id(app, "quit", "退出", true, None::<&str>)?;
let menu = Menu::with_items(app, &[&show, &hide, &quit])?;
let mut builder = TrayIconBuilder::with_id("main")
.tooltip("无限画布")
.menu(&menu)
// 左键 = 直接唤出主窗口(不用再点一次菜单);右键才出菜单(显示/隐藏/退出)
.show_menu_on_left_click(false)
.on_menu_event(|app, e| match e.id().as_ref() {
"show" => show_main(app),
"hide" => {
if let Some(w) = app.get_webview_window("main") {
let _ = w.hide();
}
}
"quit" => {
QUITTING.store(true, Ordering::SeqCst);
app.exit(0);
}
_ => {}
});
// 所有平台统一:左键点图标 = 显示/聚焦主窗口(macOS 也照做,菜单改到右键)
builder = builder.on_tray_icon_event(|tray, event| {
if let tauri::tray::TrayIconEvent::Click { button: tauri::tray::MouseButton::Left, button_state: tauri::tray::MouseButtonState::Up, .. } = event {
show_main(tray.app_handle());
}
});
// 菜单栏用单色模板图标(macOS 会随浅色/深色菜单栏自动反色,看着才像原生)
match tauri::image::Image::from_bytes(include_bytes!("../icons/tray-template.png")) {
Ok(ic) => builder = builder.icon(ic).icon_as_template(true),
Err(_) => {
if let Some(icon) = app.default_window_icon().cloned() {
builder = builder.icon(icon);
}
}
}
builder.build(app)?;
Ok(())
}
// 把「资料目录」加进本次运行的 fs scope。
// 为什么需要它:tauri-plugin-fs 的路径白名单是**运行时**的,重启就没了;而资料目录是用户
// 在设置里选的、存在应用配置里 ⇒ 启动时由这里重新授权一次,之后 fs 插件的读写才允许。
#[tauri::command]
fn grant_dir(app: AppHandle, dir: String, record: Option<bool>) -> Result<String, String> {
let p = std::path::PathBuf::from(&dir);
if !p.is_absolute() {
return Err("资料目录必须是绝对路径".into());
}
std::fs::create_dir_all(&p).map_err(|e| e.to_string())?;
app.fs_scope()
.allow_directory(&p, true)
.map_err(|e| e.to_string())?;
// 只有「资料目录」才记进配置(record 默认 true);下载目录等传 record=false,
// 否则会把 data-dir.txt 覆盖成别的目录,导致「打开」跳到错误位置。
if record.unwrap_or(true) {
if let Ok(cfg) = app.path().app_config_dir() {
let _ = std::fs::create_dir_all(&cfg);
let _ = std::fs::write(cfg.join("data-dir.txt"), p.to_string_lossy().as_bytes());
}
}
Ok(p.to_string_lossy().to_string())
}
// 递归复制整个资料目录(「转移」用:整库搬到新位置,成功后再切换指针)
#[tauri::command]
fn copy_tree(src: String, dst: String) -> Result<u64, String> {
fn walk(from: &std::path::Path, to: &std::path::Path, n: &mut u64) -> std::io::Result<()> {
std::fs::create_dir_all(to)?;
for e in std::fs::read_dir(from)? {
let e = e?;
let name = e.file_name();
if name.to_string_lossy() == "trash" { continue } // 回收站不搬
let f = e.path();
let t = to.join(&name);
if e.file_type()?.is_dir() { walk(&f, &t, n)? } else { std::fs::copy(&f, &t)?; *n += 1 }
}
Ok(())
}
let s = std::path::PathBuf::from(&src);
let d = std::path::PathBuf::from(&dst);
if !s.is_dir() { return Err("源目录不存在".into()) }
if d.starts_with(&s) { return Err("目标不能放在源目录里面".into()) }
if d.exists() && std::fs::read_dir(&d).map(|mut i| i.next().is_some()).unwrap_or(false) {
return Err("目标目录不是空目录".into())
}
std::fs::create_dir_all(&d).map_err(|e| e.to_string())?;
let mut n = 0u64;
walk(&s, &d, &mut n).map_err(|e| e.to_string())?;
Ok(n)
}
// 打开应用数据目录(设置里的「打开数据目录」按钮用;macOS 访达 / Windows 资源管理器 / Linux xdg-open)
#[tauri::command]
fn open_app_data_dir(app: AppHandle) -> Result<String, String> {
// 资料目录(用户选的那个)优先;没设置过才退回应用私有目录
let recorded = app
.path()
.app_config_dir()
.ok()
.and_then(|c| std::fs::read_to_string(c.join("data-dir.txt")).ok())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty() && std::path::Path::new(s).exists());
let dir = match recorded {
Some(p) => std::path::PathBuf::from(p),
None => app.path().app_data_dir().map_err(|e| e.to_string())?,
};
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let path = dir.to_string_lossy().to_string();
#[cfg(target_os = "macos")]
let cmd = "open";
#[cfg(target_os = "windows")]
let cmd = "explorer";
#[cfg(target_os = "linux")]
let cmd = "xdg-open";
std::process::Command::new(cmd)
.arg(&dir)
.spawn()
.map_err(|e| e.to_string())?;
Ok(path)
}
use tauri_plugin_updater::UpdaterExt;
#[tauri::command]
fn clipboard_write_text(text: String) -> Result<bool, String> {
let mut cb = Clipboard::new().map_err(|e| e.to_string())?;
cb.set_text(text).map_err(|e| e.to_string())?;
Ok(true)
}
#[tauri::command]
fn clipboard_read_text() -> Result<String, String> {
let mut cb = Clipboard::new().map_err(|e| e.to_string())?;
Ok(cb.get_text().unwrap_or_default())
}
#[tauri::command]
async fn check_update(app: tauri::AppHandle) -> Result<Option<serde_json::Value>, String> {
let updater = app.updater().map_err(|e| e.to_string())?;
match updater.check().await {
Ok(Some(update)) => Ok(Some(serde_json::json!({
"version": update.version,
"currentVersion": update.current_version,
"notes": update.body.unwrap_or_default(),
"date": update.date.map(|d| d.to_string()).unwrap_or_default()
}))),
Ok(None) => Ok(None),
Err(e) => Err(e.to_string()),
}
}
#[tauri::command]
async fn install_update(app: tauri::AppHandle) -> Result<bool, String> {
let updater = app.updater().map_err(|e| e.to_string())?;
let found = updater.check().await.map_err(|e| e.to_string())?;
let Some(update) = found else { return Ok(false) };
update
.download_and_install(|_chunk, _total| {}, || {})
.await
.map_err(|e| e.to_string())?;
app.restart();
}
use arboard::Clipboard;
fn b64_encode(bytes: &[u8]) -> String {
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(bytes)
}
fn b64_decode(s: &str) -> Result<Vec<u8>, String> {
use base64::Engine;
base64::engine::general_purpose::STANDARD
.decode(s.as_bytes())
.map_err(|e| e.to_string())
}
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct ClipImagePayload {
width: u32,
height: u32,
png_base64: String,
}
/// 读系统剪贴板图片 → PNG(base64)
///
/// 为什么返回 PNG 而不是裸 RGBA:12MP 照片的 RGBA 是 46MB,base64 后 62MB,
/// 穿过 IPC 会卡住前端好几秒;PNG 通常只有几 MB。
#[tauri::command]
fn clipboard_read_image() -> Result<Option<ClipImagePayload>, String> {
let mut cb = Clipboard::new().map_err(|e| e.to_string())?;
let img = match cb.get_image() {
Ok(v) => v,
Err(_) => return Ok(None),
};
let w = img.width as u32;
let h = img.height as u32;
if w == 0 || h == 0 {
return Ok(None);
}
let raw = img.bytes.into_owned();
let buf = image::RgbaImage::from_raw(w, h, raw)
.ok_or_else(|| "剪贴板图片像素数据不完整".to_string())?;
let mut png: Vec<u8> = Vec::new();
{
use image::ImageEncoder;
let enc = image::codecs::png::PngEncoder::new(&mut png);
enc.write_image(buf.as_raw(), w, h, image::ExtendedColorType::Rgba8)
.map_err(|e| e.to_string())?;
}
Ok(Some(ClipImagePayload {
width: w,
height: h,
png_base64: b64_encode(&png),
}))
}
/// 把 PNG(base64)写进系统剪贴板
#[tauri::command]
fn clipboard_write_image(png_base64: String) -> Result<bool, String> {
let bytes = b64_decode(&png_base64)?;
let img = image::load_from_memory(&bytes).map_err(|e| e.to_string())?.to_rgba8();
let (w, h) = (img.width() as usize, img.height() as usize);
let mut cb = Clipboard::new().map_err(|e| e.to_string())?;
cb.set_image(arboard::ImageData {
width: w,
height: h,
bytes: std::borrow::Cow::Owned(img.into_raw()),
})
.map_err(|e| e.to_string())?;
Ok(true)
}
fn open_external(url: &str) -> Result<(), String> {
#[cfg(target_os = "macos")]
{
std::process::Command::new("open").arg(url).spawn().map(|_| ()).map_err(|e| e.to_string())
}
#[cfg(target_os = "windows")]
{
std::process::Command::new("cmd")
.args(["/C", "start", "", url])
.spawn()
.map(|_| ())
.map_err(|e| e.to_string())
}
#[cfg(all(unix, not(target_os = "macos")))]
{
std::process::Command::new("xdg-open").arg(url).spawn().map(|_| ()).map_err(|e| e.to_string())
}
}
#[tauri::command]
fn open_external_url(url: String) -> Result<bool, String> {
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err("只允许 http/https".into());
}
open_external(&url)?;
Ok(true)
}
#[tauri::command]
fn notify_desktop(app: tauri::AppHandle, title: String, body: String) -> Result<bool, String> {
use tauri_plugin_notification::NotificationExt;
match app.notification().builder().title(title).body(body).show() {
Ok(_) => Ok(true),
Err(e) => Err(e.to_string()),
}
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let app = tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
// 第二次启动:聚焦已有窗口(多实例同时写同一个资料目录会把 data.json 写坏)
if let Some(w) = app.get_webview_window("main") {
let _ = w.show();
let _ = w.unminimize();
let _ = w.set_focus();
}
}))
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_http::init())
.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, grant_dir, copy_tree, check_update, install_update, clipboard_read_image, clipboard_write_image, clipboard_write_text, clipboard_read_text, open_external_url, notify_desktop])
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
}
// 恢复上次窗口大小/位置
if let Some(win) = app.get_webview_window("main") {
restore_geom(&win, app.handle());
}
build_tray(app.handle())?;
// macOS 必须有应用菜单,否则 Cmd+C / Cmd+V / Cmd+X 根本不会进 WebView(Tauri 已知问题)
#[cfg(target_os = "macos")]
{
let menu = tauri::menu::Menu::default(app.handle())?;
app.set_menu(menu)?;
}
Ok(())
})
// 点关闭按钮 ⇒ 记住窗口尺寸后收进托盘(不退出,后台任务继续)
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
if !QUITTING.load(Ordering::SeqCst) {
if let Some(w) = window.app_handle().get_webview_window("main") {
save_geom(&w);
}
api.prevent_close();
let _ = window.hide();
}
}
})
.build(tauri::generate_context!())
.expect("error while building tauri application");
app.run(|app_handle, event| {
// Cmd+Q / 系统退出时也把当前窗口尺寸落盘
if let tauri::RunEvent::ExitRequested { .. } = event {
if let Some(w) = app_handle.get_webview_window("main") {
save_geom(&w);
}
}
});
}
+6
View File
@@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
image_workbench_lib::run();
}
+54
View File
@@ -0,0 +1,54 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "image-workbench",
"version": "3.25.18",
"identifier": "com.malongan.imageworkbench",
"build": {
"frontendDist": "../dist",
"beforeDevCommand": "npm run build",
"beforeBuildCommand": "npm run lint && npm run build && node scripts/strip-plugins.js"
},
"app": {
"withGlobalTauri": true,
"windows": [
{
"label": "main",
"title": "无限画布",
"width": 1440,
"height": 900,
"minWidth": 1024,
"minHeight": 640,
"resizable": true,
"fullscreen": false,
"center": true,
"dragDropEnabled": false
}
],
"security": {
"csp": "default-src 'self'; script-src 'self' blob:; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost https: blob: data: http://127.0.0.1:30092 http://localhost:30092; object-src 'none'; base-uri 'none'; frame-ancestors 'none'"
}
},
"bundle": {
"active": true,
"targets": "all",
"category": "GraphicsAndDesign",
"shortDescription": "无限画布 · 生图工作台",
"longDescription": "节点式无限画布,本地编排与生成图片,支持系统原生另存为。",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/[email protected]",
"icons/icon.icns",
"icons/icon.ico"
],
"createUpdaterArtifacts": true
},
"plugins": {
"updater": {
"endpoints": [
"https://download.maqiart.eu.org/updates/latest.json"
],
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDE3QUU1N0QwQUM5RjE1RjEKUldUeEZaK3MwRmV1RnhjNVhhSlhaSHkvbVRXNDdscHpOa0s0VHF4NHBBQVJBdDQ0dEVlck5FeEsK"
}
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"bundle": {
"targets": [
"app",
"dmg"
]
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"bundle": {
"targets": [
"nsis"
]
},
"plugins": {
"updater": {
"endpoints": [
"https://download.maqiart.eu.org/updates/latest-windows.json"
]
}
}
}
+42 -12
View File
@@ -102,20 +102,50 @@
/* 写系统剪贴板。返回 Promise<boolean>:false 表示这个环境写不了
* (非 HTTPS / 老浏览器 / 无 ClipboardItem)→ 调用方降级到内部剪贴板 + Ctrl+Shift+V。
* 绝不 reject:复制是高频动作,不能因为剪贴板权限在控制台刷错误。 */
/* 桌面端兜底:WKWebView 里 ClipboardItem 写 text/html 常失败(返回 false),
* 于是复制节点等于「什么都没写」,Ctrl+V 会贴出上一次的文本。
* 这里改成:写不了富文本就写纯文本摘要,并记住这份摘要属于哪个 clip。
* 粘贴侧用 matchPlain() 精确比对(文字完全相等才算命中),不会把用户随手复制的文本误判成节点。 */
let lastPlain = null
function notePlain(plain, clip) {
lastPlain = { plain: str(plain), clip: clip || null, at: Date.now() }
}
function matchPlain(text) {
if (!lastPlain || !lastPlain.clip) return null
if (Date.now() - lastPlain.at > 10 * 60 * 1000) return null
return str(text) === lastPlain.plain ? lastPlain.clip : null
}
function write(clip) {
const plain = plainFor(clip)
const cb = (g.navigator && g.navigator.clipboard) || null
// 先记账:即使写剪贴板失败,内部匹配(matchPlain)也能让 Ctrl+V 贴回节点组
notePlain(plain, clip)
try {
const cb = g.navigator && g.navigator.clipboard
if (!cb || typeof cb.write !== 'function') return Promise.resolve(false)
if (typeof g.ClipboardItem !== 'function' || typeof g.Blob !== 'function') return Promise.resolve(false)
const html = htmlFor(clip)
const plain = plainFor(clip)
const item = new g.ClipboardItem({
'text/html': new g.Blob([html], { type: 'text/html' }),
'text/plain': new g.Blob([plain], { type: 'text/plain' }),
})
return Promise.resolve(cb.write([item])).then(() => true).catch(() => false)
} catch (e) { return Promise.resolve(false) }
if (cb && typeof cb.write === 'function' && typeof g.ClipboardItem === 'function' && typeof g.Blob === 'function') {
const item = new g.ClipboardItem({
'text/html': new g.Blob([htmlFor(clip)], { type: 'text/html' }),
'text/plain': new g.Blob([plain], { type: 'text/plain' }),
})
return Promise.resolve(cb.write([item])).then(() => true).catch(() => writePlainFallback(cb, plain, clip))
}
} catch (e) { /* 落到纯文本兜底 */ }
// WKWebView:没有 clipboard.write ⇒ 直接走纯文本兜底(旧实现这里直接 return false,等于什么都没写)
return writePlainFallback(cb, plain, clip)
}
g.IWBClipboardGraph = Object.freeze({ MARK, encodeText, decodeText, htmlFor, plainFor, decode, write })
/** 纯文本兜底:优先 navigator.clipboard.writeText,再退到 Rust arboard */
function writePlainFallback(cb, plain, clip) {
notePlain(plain, clip)
const T = g.__TAURI__
if (cb && typeof cb.writeText === 'function') {
return Promise.resolve(cb.writeText(plain)).then(() => true).catch(() => writeNativeText(T, plain))
}
return writeNativeText(T, plain)
}
function writeNativeText(T, plain) {
if (!T || !T.core || typeof T.core.invoke !== 'function') return Promise.resolve(false)
return Promise.resolve(T.core.invoke('clipboard_write_text', { text: str(plain) })).then(() => true).catch(() => false)
}
g.IWBClipboardGraph = Object.freeze({ MARK, encodeText, decodeText, htmlFor, plainFor, decode, write, matchPlain })
})(typeof window !== 'undefined' ? window : globalThis)
+74
View File
@@ -0,0 +1,74 @@
/* clipboard-native.js —— 桌面端原生剪贴板(2026-11-18)
*
* 为什么单独一个模块:
* WKWebView 的 paste 事件拿不到「从 Finder/预览复制的图片」,
* navigator.clipboard.write([ClipboardItem]) 在部分 macOS 版本也不可用。
* 图片读写统一走 Rust 侧 arboard(命令 clipboard_read_image / clipboard_write_image)。
*
* 为什么 IPC 传 PNG 而不是裸 RGBA:
* 12MP 照片的 RGBA 是 46MB,base64 后 62MB,穿过 IPC 会卡住前端好几秒;
* PNG 通常只有几 MB。读方向由 Rust 编码 PNG,写方向直接把 Blob 的 PNG 字节发过去。
*/
;(function (global) {
'use strict'
function tauri() {
const T = global && global.__TAURI__
return (T && T.core && typeof T.core.invoke === 'function') ? T : null
}
function b64FromU8(u8) {
let s = ''
const CH = 0x8000
for (let i = 0; i < u8.length; i += CH) s += String.fromCharCode.apply(null, u8.subarray(i, i + CH))
return global.btoa(s)
}
function u8FromB64(b64) {
const s = global.atob(b64)
const u8 = new Uint8Array(s.length)
for (let i = 0; i < s.length; i++) u8[i] = s.charCodeAt(i)
return u8
}
/** Blob/File → PNG Blob(其它格式统一转一次,避免写进剪贴板后别人贴出来是 HEIC) */
function toPngBlob(blobOrFile) {
if (blobOrFile && blobOrFile.type === 'image/png') return Promise.resolve(blobOrFile)
const C = global.IWBImageBlob
if (C && typeof C.toPng === 'function') return Promise.resolve(C.toPng(blobOrFile))
return Promise.resolve(blobOrFile)
}
/** 读系统剪贴板里的图片 → PNG File(读不到返回 null) */
async function readImage() {
const T = tauri()
if (!T) return null
try {
const r = await T.core.invoke('clipboard_read_image')
const b64 = r && (r.pngBase64 || r.png_base64)
if (!b64) return null
const u8 = u8FromB64(b64)
const blob = new global.Blob([u8], { type: 'image/png' })
const name = 'clipboard-' + Date.now() + '.png'
try { return new global.File([blob], name, { type: 'image/png' }) } catch (e) {
const named = /** @type {any} */ (blob)
named.name = name
return named
}
} catch (e) { return null }
}
/** 把图片写进系统剪贴板(Blob/File 均可) */
async function writeImage(blobOrFile) {
const T = tauri()
if (!T || !blobOrFile) return false
try {
const png = await toPngBlob(blobOrFile)
const buf = new Uint8Array(await png.arrayBuffer())
await T.core.invoke('clipboard_write_image', { pngBase64: b64FromU8(buf) })
return true
} catch (e) { return false }
}
global.IWBNativeClipboard = Object.freeze({ readImage, writeImage, available: () => !!tauri() })
})(typeof window !== 'undefined' ? window : globalThis)
+115 -40
View File
@@ -25,13 +25,23 @@
/* 浮层打开时不接管画布粘贴:用户看不见画布,粘出来的节点会被盖住,
* 关掉浮层才发现多了一堆。优先读 state(ctx.ui),补一刀 DOM 判定覆盖放大编辑/插件面板。 */
function overlayOpen(ui) {
if (ui && (ui.settingOpen || ui.drawerOpen || ui.helpOpen || ui.wsMoreOpen || ui.ctxMenu || ui.connMenu)) return true
try {
return !!document.querySelector('.iwb-md-expand, .iwb-fullmask')
} catch (e) { return false }
/* 真模态:粘贴会落到用户看不见的画布上,直接不接管。 */
function modalOpen(ui) {
if (ui && (ui.settingOpen || ui.helpOpen || ui.wsMoreOpen || ui.ctxMenu || ui.connMenu)) return true
try { return !!document.querySelector('.iwb-md-expand') } catch (e) { return false }
}
/* 库面板(左侧资源抽屉 / 资源中心全屏):**不再禁止粘贴**。
* 旧行为是「浮层打开时不接管」,用户实测反馈「打开库面板粘贴就失效」,因为这两块面板
* 常驻打开、并不阻断画布操作(拖拽/连线都还能用),只有粘贴被单独拦掉,像 bug。
* 现在的取舍:粘贴前先把库面板关掉(调用方注入 closeLibrary),让落点可见、不产生「贴了
* 但看不见」的困惑;调用方没注入就退回旧行为(不接管)。 */
function libraryOpen(ui) {
if (ui && ui.drawerOpen) return true
try { return !!document.querySelector('.iwb-fullmask') } catch (e) { return false }
}
const overlayOpen = (ui) => modalOpen(ui) || libraryOpen(ui)
const nameOf = (f, i) => str(f && f.name) || ('pasted-' + (i + 1) + '.png')
/* ── 粘贴落点跟随指针(v3.24.69,用户裁定)───────────────────────────────
@@ -70,6 +80,10 @@
let hit = null
try { hit = document.elementFromPoint ? document.elementFromPoint(ptr.x, ptr.y) : null } catch (e) { hit = null }
if (hit && hit !== el && el.contains && !el.contains(hit)) return null
// 面板本身可能挂在画布子树里(左抽屉),单独再判一次
try {
if (hit && hit.closest && hit.closest('.iwb-fullmask, .iwb-lib, .iwb-lib-embedded, .iwb-drawer, .iwb-fullpanel')) return null
} catch (e) { /* ignore */ }
const vp = (ctx && ctx.refs && ctx.refs.viewport) || { x: 0, y: 0, scale: 1 }
const G = g.IWBCanvasGeometry
const w = (G && typeof G.clientToWorld === 'function')
@@ -120,42 +134,43 @@
* (prompt 216 vs 实测 ~90)⇒ 贴出来的节点视觉中心恒定偏上 63px。改成左上角之后
* 落点不再依赖任何高度估算:高度只决定"往下延伸多少"。
* ctx.findSpot(type, seed, opts) 的 opts.corner === 'tl' 就是这件事的开关。 */
const spotOf = (ctx, type) => ctx.findSpot(type, anchor(ctx) || undefined, { corner: 'tl' })
/* 同图去重(v3.24.75):把这一批里画布上**已有**的图剔掉,只排布剩下的。
* 返回 { kept, dupIds, dupCount }:
* dupIds —— 命中的已有节点 id(用来"选中原节点",用户才知道东西在哪)
* dupCount —— 连同一批内部的重复也算上(粘两张一样的图时,第二张没有"原节点"可选中)
* 判据与语义边界见 src/image-dedupe.js(远程链接、复制节点组都**不**去重)。 */
function rejectDup(items, ctx) {
const D = g.IWBImageDedupe
if (!D || typeof D.index !== 'function') return { kept: items, dupIds: [], dupCount: 0 }
const idx = D.index(ctx.nodes())
const seen = new Set()
const kept = []
const dupIds = []
for (let i = 0; i < items.length; i++) {
const v = items[i].data
const k = idx.keyOf(v)
const hitId = k ? idx.hit(v) : ''
if (hitId) { if (dupIds.indexOf(hitId) < 0) dupIds.push(hitId); continue }
if (k && seen.has(k)) continue // 同一批里的重复:没有原节点可指,只计数
if (k) seen.add(k)
kept.push(items[i])
/* 指针不在画布上(停在面板/工具栏)时的兜底落点:
* 取视口中心,若中心被库面板盖住就往面板旁边挪,避免「贴了但看不见」。 */
function safeSeed(ctx) {
const box = boxOf(ctx)
if (!box) return null
const r = box.r
let movedOut = false
let cx = r.left + r.width / 2
const cy = r.top + r.height / 2
let moved = false
let rects = []
try { rects = Array.prototype.slice.call(document.querySelectorAll('.iwb-fullmask, .iwb-lib, .iwb-drawer, .iwb-lib-embedded')) } catch (e) { rects = [] }
for (let i = 0; i < rects.length; i++) {
const pr = rects[i].getBoundingClientRect ? rects[i].getBoundingClientRect() : null
if (!pr || !pr.width) continue
if (cx < pr.left || cx > pr.right || cy < pr.top || cy > pr.bottom) continue
if (pr.right + 90 < r.right) cx = pr.right + 90
else if (pr.left - 90 > r.left) cx = pr.left - 90
movedOut = true
break
}
return { kept: kept, dupIds: dupIds, dupCount: items.length - kept.length }
// 中心没被面板挡住 ⇒ 返回 null,交回 findSpot 的原行为
if (!movedOut) return null
const vp = (ctx && ctx.refs && ctx.refs.viewport) || { x: 0, y: 0, scale: 1 }
const G = g.IWBCanvasGeometry
const w = (G && typeof G.clientToWorld === 'function')
? G.clientToWorld(cx, cy, r, vp)
: { x: (cx - r.left - (vp.x || 0)) / (vp.scale || 1), y: (cy - r.top - (vp.y || 0)) / (vp.scale || 1) }
return (Number.isFinite(w.x) && Number.isFinite(w.y)) ? { x: Math.round(w.x), y: Math.round(w.y) } : null
}
const spotOf = (ctx, type) => ctx.findSpot(type, anchor(ctx) || safeSeed(ctx) || undefined, { corner: 'tl' })
function addRefs(items, ctx, label) {
if (ctx.wsId !== ctx.activeWsId()) { ctx.setNotice({ type: 'err', text: '工作台已切换,已取消粘贴图片' }); return }
const dedup = rejectDup(items, ctx)
if (!dedup.kept.length) {
// 一张都没落:**必须**说清发生了什么并把原节点选中,否则用户看到的是「按了没反应」。
if (dedup.dupIds.length) ctx.setSel(dedup.dupIds)
ctx.setNotice({ type: 'ok', text: '这 ' + dedup.dupCount + ' 张图已经在画布上了' + (dedup.dupIds.length ? '(已选中原来的节点)' : '') + ',没有重复粘贴' })
return
}
items = dedup.kept
// v3.25.6(用户裁定):同一张图允许重复粘贴 —— 粘贴是显式动作,被去重挡掉像「按键没反应」。
// 同图去重仍服务于「拖拽 / 批量导入」等被动路径(src/image-dedupe.js 的其它调用方)。
if (!items || !items.length) return
const stepX = ctx.nodeW('ref') + 24
const stepY = ctx.nodeH('ref') + 24
let base = spotOf(ctx, 'ref')
@@ -177,7 +192,7 @@
ctx.pushHistory()
ctx.commitCanvas(ctx.nodes().concat(made), undefined, undefined)
ctx.setSel(made.map((n) => n.id))
ctx.setNotice({ type: 'ok', text: label + (dedup.dupCount ? '(跳过 ' + dedup.dupCount + ' 张重复的)' : '') })
ctx.setNotice({ type: 'ok', text: label })
}
/* 多图:并行导入、**一次落盘** —— 撤销一次就回到粘之前(旧实现分 N 次 commit 要按 N 次) */
@@ -250,14 +265,16 @@
}
return false
}
if (overlayOpen(ctx.ui)) return false
if (modalOpen(ctx.ui)) return false
// 库面板(资源抽屉 / 资源中心)不做任何拦截:用户明确要求「粘贴不要关闭库面板」。
// 落点问题交给 anchor(指针在画布可见区就贴指针处)与 safeSeed(指针压在面板上时挪开)。
if (c.kind === 'graph') {
// 复制节点时已把节点组写进系统剪贴板(text/html 带标记)→ 这里直接贴,不用再记 Ctrl+Shift+V。
e.preventDefault()
// 先摘掉「粘贴替换」的待命监听:此刻用户要贴的是节点组,不是替换某张参考图。
// 不摘的话,点过「粘贴替换」按钮后再贴节点组,会把那张图顺手替换掉(v3.24.67 修过一次同类问题)。
try { const PO = g.IWBPasteOnce; if (PO) PO.disarm() } catch (err) { /* ignore */ }
if (!ctx.pasteGraph(c.clip, anchor(ctx))) ctx.setNotice({ type: 'err', text: '粘贴节点组失败:剪贴板内容无法识别' })
if (!ctx.pasteGraph(c.clip, anchor(ctx) || safeSeed(ctx))) ctx.setNotice({ type: 'err', text: '粘贴节点组失败:剪贴板内容无法识别' })
return true
}
if (c.kind === 'empty') {
@@ -266,6 +283,16 @@
// 复制只进了内部那份;用户从旧版本带过来的复制内容也靠它。
// 每个 paste 事件独立处理 → 连按 N 次贴 N 份,不会像旧的定时器方案那样只贴一份。
e.preventDefault()
// 桌面端:Finder/预览复制的图片在 WKWebView 的 paste 事件里读不到,先问原生剪贴板
if (typeof ctx.readNativeImage === 'function') {
ctx.setNotice({ type: 'info', text: '正在读取剪贴板图片…' })
ctx.readNativeImage().then((f) => {
if (f) { pasteImages([f], ctx); ctx.setNotice(null) }
else if (ctx.pasteCopiedNodes()) { ctx.setNotice(null) }
else ctx.setNotice({ type: 'err', text: ctx.refs.clipExpired ? '内部剪贴板已过期(10 分钟),请重新复制节点' : '剪贴板里没有可粘贴的内容' })
})
return true
}
if (ctx.pasteCopiedNodes()) return true
ctx.setNotice({
type: 'err',
@@ -280,6 +307,10 @@
// 用户没法照着做(他粘的可能本来就是 PNG,只是 MIME 没填)。
const A = g.IWBImageAdmit
const list = c.files || []
if (typeof ctx.readNativeImage === 'function') {
ctx.readNativeImage().then((f) => { if (f) { pasteImages([f], ctx); ctx.setNotice(null) } })
return true
}
const why = (A && typeof A.why === 'function' && list[0]) ? A.why(list[0])
: ('暂不支持粘贴文件(' + ((list[0] && list[0].name) || '该文件') + ')')
ctx.setNotice({ type: 'err', text: (why || '暂不支持粘贴该文件') + (list.length > 1 ? '(另有 ' + (list.length - 1) + ' 个文件未处理)' : '') })
@@ -300,6 +331,26 @@
createRefFromUrl(c.text.trim(), ctx)
return true
}
// 桌面端:Finder/预览里「复制图片」经常同时给出 file:// 文本,classify 会当成普通文本,
// 结果贴出来是一个写着路径的提示词节点。这里遇到路径样式的文本先问原生剪贴板要图片。
const looksPath = /^(file:\/\/|\/|[A-Za-z]:[\/])/.test(c.text.trim())
if (looksPath && typeof ctx.readNativeImage === 'function') {
e.preventDefault()
ctx.readNativeImage().then((f) => {
if (f) pasteImages([f], ctx)
else createPrompt(c.text, ctx)
})
return true
}
// 桌面端:复制节点写不进 text/html 时会退化成「纯文本摘要 + 记住的 clip」。
// 文字与刚才写的摘要完全一致 ⇒ 认为用户贴的是节点组,而不是新提示词。
const G = g.IWBClipboardGraph
const matched = (G && typeof G.matchPlain === 'function') ? G.matchPlain(c.text) : null
if (matched) {
e.preventDefault()
try { const PO = g.IWBPasteOnce; if (PO) PO.disarm() } catch (err) { /* ignore */ }
if (ctx.pasteGraph(matched, anchor(ctx) || safeSeed(ctx))) return true
}
e.preventDefault()
createPrompt(c.text, ctx)
return true
@@ -325,5 +376,29 @@ function probe(ctx) {
}, 420)
}
g.IWBClipboardPaste = Object.freeze({ handle, probe, overlayOpen, anchor })
/* Cmd/Ctrl+V 兜底(桌面端):菜单缺失或 WebView 不派发 paste 时,160ms 内没收到
* 真实 paste 事件就主动读一次原生剪贴板图片。getCtx 由 app.js 注入(懒取,避免闭包过期)。 */
let hotkeyBound = false
function bindHotkeyFallback(getCtx) {
if (hotkeyBound || typeof window === 'undefined') return
hotkeyBound = true
window.addEventListener('keydown', (e) => {
if (!(e.metaKey || e.ctrlKey) || e.shiftKey || e.altKey) return
if (String(e.key || '').toLowerCase() !== 'v') return
const t = /** @type {any} */ (e.target)
if (t && t.tagName && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return
const D = g.IWBDesktop
if (!D || !D.clipboardReadImage) return
const ctx = (typeof getCtx === 'function') ? getCtx() : null
if (ctx && modalOpen(ctx.ui)) return
const stamp = ctx && ctx.refs ? (ctx.refs.pasteStamp || 0) : 0
setTimeout(() => {
const now = ctx && ctx.refs ? (ctx.refs.pasteStamp || 0) : 0
if (now !== stamp) return
D.clipboardReadImage().then((f) => { if (f) pasteImages([f], ctx) })
}, 160)
})
}
g.IWBClipboardPaste = Object.freeze({ handle, probe, overlayOpen, modalOpen, libraryOpen, anchor, bindHotkeyFallback, pasteFiles: (files, ctx) => pasteImages(files || [], ctx) })
})(typeof window !== 'undefined' ? window : globalThis)
+8 -1
View File
@@ -4,6 +4,8 @@
function createHydrator(options) {
const opt = options || {}
const get = typeof opt.get === 'function' ? opt.get : (() => Promise.resolve(null))
// 文件存储:清单只留 thumbHash,缩略图按需从 images/thumbs/ 读
const thumb = typeof opt.thumb === 'function' ? opt.thumb : null
let sequence = 0
let disposed = false
async function hydrate(items, requestId) {
@@ -11,7 +13,12 @@
if (id > sequence) sequence = id
const list = Array.isArray(items) ? items : []
const values = await Promise.all(list.map(async (item) => {
if (!item || !item.idb) return item
if (!item) return item
if (item.data) return item
if (thumb && item.thumbHash) {
try { const v = await thumb(item.thumbHash); if (v) return Object.assign({}, item, { data: v }) } catch (e) { /* 读文件失败退回 idb */ }
}
if (!item.idb) return item
try {
const value = await get(item.idb)
return value == null ? item : Object.assign({}, item, { data: value })
+13 -1
View File
@@ -192,7 +192,19 @@
mainThreadCompress(dataUrl, c, cb)
}
return { estimateBytes, wBlobFromDataUrl, wImgBlobToDataUrl, withDecodedImage, mainThreadCompress, compressDataUrl }
/** 把 dataURL 等比缩到 maxEdge 以内(Promise,8s 超时兜底返回原图)。
* 用途:图库「插入」的尺寸档(原图/2k/1k/0.5k)—— 传原图到画布太重,按档位先压。 */
function toMaxEdge (dataUrl, maxEdge, quality) {
return new Promise((resolve) => {
if (!dataUrl || String(dataUrl).indexOf('data:') !== 0) { resolve(dataUrl); return }
let done = false
const fin = (out) => { if (!done) { done = true; resolve(out || dataUrl) } }
try { compressDataUrl(dataUrl, { force: true, maxEdge: Number(maxEdge) || 2048, quality: Number(quality) || 0.9 }, fin) } catch (e) { fin(dataUrl) }
setTimeout(() => fin(dataUrl), 8000)
})
}
return { estimateBytes, wBlobFromDataUrl, wImgBlobToDataUrl, withDecodedImage, mainThreadCompress, compressDataUrl, toMaxEdge }
}
global.IWBImageCompress = Object.freeze({ WORKER_CODE, createWorkerManager, create })
+22
View File
@@ -105,6 +105,27 @@
return (m ? raw.slice(0, -m[0].length) : raw) + '.' + want
}
/** 重名保护(v3.25.18):目标目录里已有同名文件时,自动加 -1/-2 … 后缀。
* 为什么需要:批量下载同名图以前是「后写覆盖前写」,最后只剩一张。
* existsFn(path) → Promise<boolean>;joinFn(dir, name) → path。任一缺失则按原名返回。 */
async function uniqueName (dir, name, joinFn, existsFn) {
const raw = strOf(name) || 'image.png'
if (!joinFn || !existsFn) return raw
const dot = raw.lastIndexOf('.')
const stem = dot > 0 ? raw.slice(0, dot) : raw
const ext = dot > 0 ? raw.slice(dot) : ''
try {
const first = await joinFn(dir, raw)
if (!(await existsFn(first))) return raw
for (let i = 1; i < 1000; i++) {
const cand = stem + '-' + i + ext
const p = await joinFn(dir, cand)
if (!(await existsFn(p))) return cand
}
} catch (e) { /* 探测失败就按原名写,交给写盘报错 */ }
return raw
}
// SVG 文本里的固有尺寸(<svg width/height> 或 viewBox)。只认纯数字/px,判不出返回 null。
function svgSizeOf(text) {
const s = strOf(text)
@@ -192,6 +213,7 @@
extOf,
isSvg,
fileNameFor,
uniqueName,
svgSizeOf,
svgToPngDataUrl,
})
+7 -3
View File
@@ -38,7 +38,8 @@
function recordOf(id) {
const current = state[id]
if (current && typeof current === 'object') return current
const created = { enabled: false, settings: {}, data: {} }
// 默认启用:插件随包发布即应可用;只有用户显式关掉才写 enabled:false
const created = { enabled: true, settings: {}, data: {} }
state[id] = created
return created
}
@@ -228,8 +229,11 @@
function isEnabled(id) {
if (plugins.has(id)) return Boolean(recordOf(id).enabled)
// 未注册:直接读持久化开关(不得走 recordOf——那会为陌生 id 创建 state 条目)
return Boolean(state[id] && state[id].enabled)
// 未注册:有持久化记录就按记录;**没有记录 ⇒ 默认启用**
// (否则启动早期 state 还没读到时,所有插件都会被判成「已停用」而进 idle)
const rec = state[id]
if (!rec) return true
return Boolean(rec.enabled)
}
function init(nextDeps) {
+38
View File
@@ -0,0 +1,38 @@
/* runtime-desktop-bridge.js —— 桌面端(Tauri)能力桥(2026-11-16)
*
* 为什么单独一个模块:
* src/*.js 不允许反向引用 app.js 定义的 window 全局(architecture-boundary-guard 会红)。
* 而「原生另存为 / 默认下载文件夹 / 打开数据目录」的实现必须在 app.js 的保存链路里。
* 所以这里只做**登记 + 转发**:app.js 启动时 configure() 注入实现,其它模块只认 IWBDesktop。
*
* 网页版:不会 configure ⇒ ready() 为 false ⇒ 各模块据此隐藏桌面专属 UI,行为与原来完全一致。
*/
;(function (global) {
'use strict'
const state = { impl: null }
const bridge = {
// app.js 启动时调用一次,注入真实实现
configure(impl) { state.impl = impl || null },
ready() { return !!state.impl },
isTauri() { return !!(state.impl && state.impl.isTauri()) },
// 保存 Blob:桌面端走原生另存为/静默写盘,网页端由 app.js 内部回退到 <a download>
saveBlob(blob, name) { return state.impl ? state.impl.saveBlob(blob, name) : undefined },
getDownloadDir() { return state.impl ? state.impl.getDownloadDir() : '' },
setDownloadDir(dir) { if (state.impl) state.impl.setDownloadDir(dir) },
pickDownloadDir() { return state.impl ? state.impl.pickDownloadDir() : Promise.resolve('') },
getSilentSave() { return !!(state.impl && state.impl.getSilentSave()) },
setSilentSave(on) { if (state.impl) state.impl.setSilentSave(on) },
openDataDir() { return state.impl ? state.impl.openDataDir() : Promise.reject(new Error('仅桌面端可用')) },
// 原生剪贴板图片(v3.26):WKWebView 里 paste 事件拿不到 Finder 复制的图片,
// navigator.clipboard.write 也常不可用,统一走 Rust 侧 arboard。
clipboardReadImage() { return state.impl && state.impl.clipboardReadImage ? state.impl.clipboardReadImage() : Promise.resolve(null) },
clipboardWriteImage(blob) { return state.impl && state.impl.clipboardWriteImage ? state.impl.clipboardWriteImage(blob) : Promise.resolve(false) },
market: {
list() { return state.impl && state.impl.marketList ? state.impl.marketList() : Promise.resolve([]) },
installed() { return state.impl && state.impl.marketInstalled ? state.impl.marketInstalled() : Promise.resolve([]) },
install(id) { return state.impl && state.impl.marketInstall ? state.impl.marketInstall(id) : Promise.resolve({ ok: false, error: '仅桌面端可用' }) },
uninstall(id) { return state.impl && state.impl.marketUninstall ? state.impl.marketUninstall(id) : Promise.resolve({ ok: false, error: '仅桌面端可用' }) },
},
}
global.IWBDesktop = bridge
})(typeof window !== 'undefined' ? window : globalThis)
+52
View File
@@ -0,0 +1,52 @@
/* runtime-plugin-backup.js —— 插件进出备份
*
* 备份里带上插件清单与源码(体积很小),换机器恢复后不必重装。
* collect() → [{ id, version, file, integrity, code }]
* restore(v) → 写回 <资料目录>/plugins/ 并合并清单(备份里没有的插件保留)
*/
;(function (global) {
'use strict'
function store () {
const F = global.IWBStorageFile || null
return (F && F.plugins) ? F.plugins : null
}
async function collect () {
const s = store()
if (!s) return []
let list = []
try { list = await s.manifest() } catch (e) { return [] }
const out = []
for (const e of (Array.isArray(list) ? list : [])) {
if (!e || !e.id || !e.file) continue
try {
const text = await s.read(e.file)
out.push({ id: e.id, version: e.version || '', file: e.file, integrity: e.integrity || '', code: String(text || '') })
} catch (err) { /* 单个插件读失败不影响其它 */ }
}
return out
}
async function restore (list) {
const s = store()
if (!s || !Array.isArray(list) || !list.length) return 0
let cur = []
try { cur = await s.manifest() } catch (e) { cur = [] }
const byId = new Map((Array.isArray(cur) ? cur : []).map(function (e) { return [String(e && e.id), e] }))
let n = 0
for (const p of list) {
if (!p || !p.id || !p.file) continue
if (!/^[A-Za-z0-9._-]+$/.test(String(p.file))) continue
try {
await s.write(String(p.file), String(p.code || ''))
byId.set(String(p.id), { id: String(p.id), file: String(p.file), version: String(p.version || ''), integrity: String(p.integrity || '') })
n++
} catch (err) { /* 单个失败忽略 */ }
}
try { await s.write('index.json', JSON.stringify(Array.from(byId.values()))) } catch (e) { /* ignore */ }
return n
}
global.IWBRuntimePluginBackup = { collect: collect, restore: restore }
})(typeof window !== 'undefined' ? window : globalThis)
+121
View File
@@ -0,0 +1,121 @@
/* runtime-plugin-loader.js —— 插件脚本加载(内置 / 外部 / 本地开发)
*
* 从 app.js 抽出来:app.js 只做装配,加载细节在这里。
* 三个入口都返回 boolean,并把状态写回传进来的 record(status/error),供插件面板展示。
* · loadBuiltin :同源 /plugins/<file>,走 SRI(integrity 强制校验)
* · loadExternal :<资料目录>/plugins/<file>,先读文本 → WebCrypto 校验 sha256 → blob 注入
* · loadLocal :开发者模式,code 已在内存里(免签名),blob 注入
*/
;(function (global) {
'use strict'
function host () {
return global.IWBPluginHost || null
}
// 外部插件源(<资料目录>/plugins/ 的读写封装)
function source () {
const F = global.IWBStorageFile || null
return (F && F.plugins && typeof F.plugins.read === 'function') ? F.plugins : null
}
async function verifyCode (code, integrity) {
if (!integrity) return false
const expect = String(integrity).replace(/^sha256-/, '')
const buf = await global.crypto.subtle.digest('SHA-256', new global.TextEncoder().encode(code))
const u8 = new Uint8Array(buf)
let bin = ''
for (let i = 0; i < u8.length; i++) bin += String.fromCharCode(u8[i])
return global.btoa(bin) === expect
}
// 注入一段脚本并等它执行完(插件在加载期自我注册)
function inject (attrs) {
return new Promise(function (resolve, reject) {
const script = global.document.createElement('script')
script.src = attrs.src
script.async = false
if (attrs.integrity) { script.integrity = attrs.integrity; script.crossOrigin = 'anonymous' }
script.onload = function () { resolve() }
script.onerror = function () { reject(new Error(attrs.error || '脚本加载失败')) }
global.document.head.appendChild(script)
})
}
function markResult (record) {
const H = host()
const registered = !!(H && typeof H.list === 'function' && H.list().some(function (p) { return p.id === record.id }))
record.status = registered ? 'loaded' : 'not-registered'
// 不在加载阶段写启用状态:否则会把用户关掉的插件又打开
// (启用/停用由 app.js 加载完成后按持久化状态统一应用)
return record.status === 'loaded'
}
async function loadBuiltin (record) {
record.status = 'loading'
const integrity = record.integrity
try {
await inject({
src: '/plugins/' + record.file,
integrity: integrity,
error: integrity ? '脚本完整性校验失败(integrity 不符或加载失败)' : '脚本加载失败'
})
return markResult(record)
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
}
async function loadExternal (record) {
record.status = 'loading'
const src = source()
if (!src) { record.status = 'error'; record.error = '外部插件不可用'; return false }
try {
const code = await src.read(record.file)
if (record.integrity) {
const ok = await verifyCode(code, record.integrity)
if (!ok) throw new Error('完整性校验失败(外部插件)')
}
const url = global.URL.createObjectURL(new global.Blob([code], { type: 'text/javascript' }))
try {
await inject({ src: url, error: '外部插件脚本执行失败' })
} finally {
setTimeout(function () { try { global.URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000)
}
return markResult(record)
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
}
async function loadLocal (record) {
record.status = 'loading'
try {
const code = String(record.code || '')
if (!code) throw new Error('插件源码为空')
const url = global.URL.createObjectURL(new global.Blob([code], { type: 'text/javascript' }))
try {
await inject({ src: url, error: '本地插件脚本执行失败' })
} finally {
setTimeout(function () { try { global.URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000)
}
return markResult(record)
} catch (err) {
record.status = 'error'
record.error = String((err && err.message) || err)
return false
}
}
global.IWBRuntimePluginLoader = {
source: source,
verifyCode: verifyCode,
loadBuiltin: loadBuiltin,
loadExternal: loadExternal,
loadLocal: loadLocal
}
})(typeof window !== 'undefined' ? window : globalThis)
+102
View File
@@ -0,0 +1,102 @@
/* runtime-plugin-market.js —— 插件市场(下载 / 校验 / 安装 / 卸载)
*
* 索引:https://market.maqiart.eu.org/index.json,产物同域 plugin-<id>.<hash>.js
* 落点:<资料目录>/plugins/(清单 index.json + 插件文件)
* 校验:市场索引里的 sha256(hex)与下载文本比对,不符直接拒绝
*/
;(function (global) {
'use strict'
const MARKET_URL = 'https://market.maqiart.eu.org/index.json'
function store () {
const F = global.IWBStorageFile || null
return (F && F.plugins) ? F.plugins : null
}
// 桌面端优先走 Tauri 原生 HTTP(WKWebView 在代理/fake-IP 环境下 fetch 会 Load failed);
// 原生失败时再退回 WebView fetch(有些 Windows 公司网络/代理只放行后者),两个错误都带上,便于定位。
async function marketFetch (url) {
const T = (global.__TAURI__ && global.__TAURI__.http) ? global.__TAURI__.http : null
let nativeErr = ''
if (T && typeof T.fetch === 'function') {
try { return await T.fetch(url) } catch (e) { nativeErr = String((e && e.message) || e) }
}
try {
return await global.fetch(url, { cache: 'no-store' })
} catch (e2) {
const webErr = String((e2 && e2.message) || e2)
throw new Error('无法访问 ' + url + (nativeErr ? ('(原生 HTTP:' + nativeErr + ')') : '') + '(网页请求:' + webErr + ')')
}
}
// 本地缓存:上次成功拉到的市场列表(毫秒级出图,后台再刷新)
const CACHE_KEY = 'iwb_market_cache'
function localStore () {
const L = global.IWBStorageLocal || null
return (L && typeof L.getStore === 'function') ? L.getStore() : null
}
function cached () {
try {
const st = localStore()
if (!st) return null
const v = st.get(CACHE_KEY)
return (Array.isArray(v) && v.length) ? v : null
} catch (e) { return null }
}
function saveCache (list) {
try { const st = localStore(); if (st && Array.isArray(list) && list.length) st.set(CACHE_KEY, list) } catch (e) { /* ignore */ }
}
async function list () {
const resp = await marketFetch(MARKET_URL)
if (!resp.ok) throw new Error('市场不可达:HTTP ' + resp.status)
const j = await resp.json()
const items = Array.isArray(j && j.plugins) ? j.plugins : []
saveCache(items)
return items
}
async function installed () {
const s = store()
if (!s) return []
return await s.manifest()
}
async function install (id) {
try {
const items = await list()
const item = items.find(function (p) { return p && p.id === id })
if (!item) return { ok: false, error: '市场里没有这个插件' }
const base = MARKET_URL.replace(/index\.json$/, '')
const resp = await marketFetch(base + item.file)
if (!resp.ok) throw new Error('下载失败:HTTP ' + resp.status)
const text = await resp.text()
const buf = await global.crypto.subtle.digest('SHA-256', new global.TextEncoder().encode(text))
const hex = Array.from(new Uint8Array(buf)).map(function (b) { return b.toString(16).padStart(2, '0') }).join('')
if (item.sha256 && hex !== item.sha256) return { ok: false, error: '校验失败(sha256 不符)' }
const s = store()
if (!s) return { ok: false, error: '外部插件目录不可用' }
const file = String(item.file).split('/').pop()
await s.write(file, text)
const cur = await s.manifest()
const next = cur.filter(function (p) { return p && p.id !== id }).concat([{ id: id, file: file, version: item.version, integrity: item.integrity }])
await s.write('index.json', JSON.stringify(next, null, 2) + '\n')
return { ok: true, restart: true, file: file }
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
}
async function uninstall (id) {
try {
const s = store()
if (!s) return { ok: false, error: '外部插件目录不可用' }
const cur = await s.manifest()
const hit = cur.find(function (p) { return p && p.id === id })
const next = cur.filter(function (p) { return p && p.id !== id })
await s.write('index.json', JSON.stringify(next, null, 2) + '\n')
if (hit && hit.file) await s.remove(hit.file)
return { ok: true, restart: true }
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
}
global.IWBRuntimePluginMarket = { list: list, cached: cached, installed: installed, install: install, uninstall: uninstall }
})(typeof window !== 'undefined' ? window : globalThis)
+46 -35
View File
@@ -1,3 +1,10 @@
// 确认统一走页内确认(桌面端),网页端保持原生 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
@@ -841,14 +848,14 @@
const { canvasSize, commitCanvas, pushHistory, refs, setNotice, setSel } = ctx
if (!file) return
const rd = new FileReader()
rd.onload = () => {
rd.onload = async () => {
try {
const parsed = JSON.parse(/** @type {string} */ (rd.result))
const migrated = StorageMigrations && StorageMigrations.migrateCanvas ? StorageMigrations.migrateCanvas(parsed) : { ok: true, value: parsed }
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 && !window.confirm('导入将替换当前画布(' + refs.nodes.length + ' 个节点),确定继续?')) return
if (refs.nodes.length && !fromDrop && !(await askConfirm('导入将替换当前画布(' + 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')
@@ -1112,22 +1119,10 @@
// 而 MIME 没填的 PNG 反倒被静默丢掉(Windows 资源管理器就这行为)。
const A = global.IWBImageAdmit
const refused = []
/* 同图去重(v3.24.75):拖进来的字节与画布上已有图片一致时不再建节点。
* 判据见 src/image-dedupe.js —— 只认本地图片字节,URL / 复制节点组都不参与。
* 多条命中合并成一条提示(拖 5 张重复图不该刷 5 条),并选中已有节点把位置指出来。 */
const D = global.IWBImageDedupe
const idx = (D && typeof D.index === 'function') ? D.index(refs.nodes) : null
const dupNames = []
const dupIds = []
const flushDups = () => {
if (!dupNames.length) return
const ns = dupNames.splice(0, dupNames.length)
const ids = dupIds.splice(0, dupIds.length)
if (ids.length) setSel(ids)
setNotice({ type: 'ok', text: ns.length === 1
? ('「' + ns[0] + '」已经在画布上了,没有重复导入' + (ids.length ? '(已选中原来的节点)' : ''))
: (ns.length + ' 张图已经在画布上了,没有重复导入' + (ids.length ? '(已选中原来的节点)' : '')) })
}
/* v3.25.8(用户裁定):拖入同一张图**允许重复添加**,不再走同图去重。
* 去重曾经挡住「图片节点数据缺失后重新拖入」这条唯一的自愈路径:命中已有节点 →
* 不写 blob → 那个节点依旧是空图。现在每次都正常导入并新建节点,顺带把丢失的
* blob 按同一个内容 key 重新写回磁盘(旧节点也就跟着恢复了)。 */
for (const f of files) {
const verdict = (A && typeof A.of === 'function') ? A.of(f) : ((f.type && f.type.indexOf('image/') === 0) ? 'image' : 'other')
if (verdict !== 'image') { refused.push(f); continue }
@@ -1136,16 +1131,7 @@
// 拖放与粘贴共用导入唯一收口(压缩到 ≤1600 + 立即引用化)
rd.onload = () => wImportImage(rd.result, { onError: (msg) => setNotice({ type: 'err', text: msg }) }, (r) => {
if (!r || !r.ok || !r.data) return
const hitId = idx ? idx.hit(r.data) : ''
if (hitId) {
dupNames.push(String(f.name || '图片'))
if (dupIds.indexOf(hitId) < 0) dupIds.push(hitId)
clearTimeout(refs.dupNoticeTimer)
refs.dupNoticeTimer = setTimeout(flushDups, 260)
return
}
const nid = mk({ url: '', data: r.data, name: f.name })
if (idx) idx.add(r.data, nid)
mk({ url: '', data: r.data, name: f.name })
})
rd.onerror = () => setNotice({ type: 'err', text: '读取拖入的图片失败:' + String(f.name || '') })
rd.readAsDataURL(f)
@@ -1206,11 +1192,28 @@
})
}
el0.addEventListener('wheel', onWheel, { passive: false })
const ro = () => { if (el0.clientWidth) setCanvasSize({ w: el0.clientWidth, h: el0.clientHeight }) }
// 画布尺寸跟随容器真实尺寸。
// ⚠️ 2026-11-16 修复:旧实现把 resize 监听绑在 el0 上,但 <div> 永远不会派发 resize 事件
// ⇒ 只有 mount 那一次量到尺寸;把窗口放大后画布仍是旧尺寸,超出部分直接看不到
// (网页端靠刷新能绕过,桌面端没有刷新入口 ⇒ 暴露成"放大后内容被裁"的 bug)。
// 改为 ResizeObserver,窗口缩放、侧栏展开/收起都会重算。
let lastW = 0, lastH = 0
const ro = () => {
const w = el0.clientWidth, h = el0.clientHeight
if (!w || (w === lastW && h === lastH)) return // 尺寸没变就不 setState,避免观察器抖动引发重渲循环
lastW = w; lastH = h
setCanvasSize({ w, h })
}
ro()
// resize 事件已足够(含窗口变化与侧栏展开);不再用 1500ms 轮询
el0.addEventListener('resize', ro)
return () => { el0.removeEventListener('wheel', onWheel); el0.removeEventListener('resize', ro); try { clearTimeout(refs.zoomTimer) } catch (e2) { /* ignore */ } }
let observer = null
if (typeof ResizeObserver === 'function') { observer = new ResizeObserver(ro); observer.observe(el0) }
else window.addEventListener('resize', ro) // 老环境兜底:window 的 resize 是真会派发的
return () => {
el0.removeEventListener('wheel', onWheel)
if (observer) { try { observer.disconnect() } catch (e2) { /* ignore */ } }
else window.removeEventListener('resize', ro)
try { clearTimeout(refs.zoomTimer) } catch (e2) { /* ignore */ }
}
}
// ⋯ 三点菜单:点击菜单外任意处(含画布空白)关闭;返回 cleanup
@@ -2165,9 +2168,17 @@
edges: refs.edges.slice(), groups: refs.groups.map((g) => ({ ...g, memberIds: g.memberIds.slice() })),
}
try {
const blob = new Blob([JSON.stringify(data, null, 1)], { type: 'application/json' }); const a = document.createElement('a')
a.href = URL.createObjectURL(blob); a.download = safeName.replace(/\.iwb\.json$/i, '') + '.iwb.json'; document.body.appendChild(a); a.click(); document.body.removeChild(a)
setTimeout(() => URL.revokeObjectURL(a.href), 5000); setNotice({ type: 'ok', text: '已导出画布:' + a.download })
const blob = new Blob([JSON.stringify(data, null, 1)], { type: 'application/json' })
const outName = safeName.replace(/\.iwb\.json$/i, '') + '.iwb.json'
// 统一出口:桌面端弹系统另存为(原生),网页端仍走 <a download>
const bridge = (typeof window !== 'undefined') ? window.IWBDesktop : null
if (bridge && bridge.ready && bridge.ready()) bridge.saveBlob(blob, outName)
else {
const a = document.createElement('a')
a.href = URL.createObjectURL(blob); a.download = outName; document.body.appendChild(a); a.click(); document.body.removeChild(a)
setTimeout(() => URL.revokeObjectURL(a.href), 5000)
}
setNotice({ type: 'ok', text: '已导出画布:' + outName })
} catch (e) { setNotice({ type: 'err', text: '导出失败:' + String((e && e.message) || e) }) }
} })
return { exportCanvas } // 包装方按对象取用
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more