Compare commits

...
26 Commits
Author SHA1 Message Date
qiqi a742fea2db feat(download): 导出目录三态逻辑(自动下载=出图即落盘/目录决定是否弹框/不覆盖同名)+ 取色器按钮修复(v3.25.20)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 2m1s
2026-11-18 21:18:58 +08:00
qiqi cad17e0aef chore(release): 3.25.19 Windows 包上线(三平台齐平)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 1m11s
2026-11-18 18:44:00 +08:00
qiqi 0bf83c96b2 style(gallery): 图库顶部两个下拉紧凑化,省横向空间(v3.25.19)
Verify (Gitea) / gate (build · unit · facts) (push) Failing after 54s
2026-11-18 18:24:56 +08:00
qiqi 6f3eb0a06c docs: 同步事实基线锚点(v3.25.18) 2026-11-18 18:02:42 +08:00
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
66 changed files with 2109 additions and 4049 deletions

No files matched your search

+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` |
---
+173
View File
@@ -14,6 +14,179 @@
> 3. 核验正式地址版本 → 之后才移动 `stable` / `stable-verified-<日期>` 标签、更新本 CHANGELOG、写 GitHub Release(`gh release create`)。
> 测试发现问题 → 改 → 再 `deploy:test`,正式环境不受影响。回滚点 `git reset --hard stable`。
## v3.25.20(2026-11-18)图片导出目录:三态逻辑重做 + 取色器按钮修复
### 变更(工单:导出目录逻辑)
- **「自动下载」改为真正的自动保存**:勾选后**出图完成即写入导出目录**;此前它只是「点下载不弹框」的开关,
自动保存函数写好却从未被调用。实现落在新模块 `src/runtime-download-auto.js`,挂在结果归档的单一漏斗上(单节点/批量/输出面板全覆盖)。
- **点下载是否弹框,只由「有没有目录」决定**:设了目录 → 直接落盘;没设目录 → 弹选择框。不再看开关。
- **复选框无目录时灰掉**(必须先选目录),清空目录会同时关闭自动下载。
- **文件名 `gen_<时间戳>.png`**;同批次内自动加 `-2/-3` 序号,跨批次同名由 `uniqueName` 加后缀,**绝不覆盖**已有文件。
### 修复
- 外观取色器底部「完成」按钮被十六进制输入框挤成两行:输入框改 `flex:1 1 0; min-width:0`,按钮 `flex:0 0 auto`。
## v3.25.19(2026-11-18)图库顶部两个下拉框紧凑化
### 优化
- 图库顶栏的「插入尺寸」与「时间范围」下拉改为紧凑样式(`iwb-select-compact`):去掉「插入」前缀、
选项文案缩短(全部/今天/7 天/30 天),宽度压到 62~84px,字号降到 `--fs-sm`;
顶栏按钮左右内边距同步收紧、`flex-wrap: nowrap`,窄面板下一行放得下。
### 说明
- 仅样式与选项文案,行为与存储键(`iwb.insertSizeK`)不变。
## 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)剪贴板体检:大图卡顿、路径误判、粘贴落点
### 修复
+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: /
+118 -44
View File
@@ -50,16 +50,23 @@
// 桌面端默认「点下载 = 直接写进下载目录,不弹窗」;只有写失败(目录被删/无权限)才退回对话框
const wSilentSave = () => { try { const v = lsGet('iwb.silentSave', true); return v !== false } catch (e) { return true } }
const wSetSilentSave = (v) => { try { lsSet('iwb.silentSave', !!v) } catch (e) { /* ignore */ } }
// 自动下载(v3.25.20 用户裁定):勾选后「出图完成」自动存到导出目录;与「点下载是否弹框」解耦
const wAutoDownload = () => { try { return lsGet('iwb.autoDownload', false) === true } catch (e) { return false } }
const wSetAutoDownload = (v) => { try { lsSet('iwb.autoDownload', !!v) } catch (e) { /* ignore */ } }
// 把 Blob 写进指定目录(不弹框)。目录必须此前由 dialog 选过:tauri-plugin-dialog 会把该目录
// 递归加进 fs scope;scope 是「本次运行」的,重启后首次写入会失败 ⇒ 调用方回退到对话框。
const wWriteBlobToDir = async (dir, name, blob) => {
const join = wTauri && wTauri.path && wTauri.path.join
const target = join ? await join(dir, name) : (dir.replace(/[\\/]+$/, '') + '/' + name)
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
}
// 桌面端「自动保存生成的图片」:没有 File System Access API ⇒ 写进默认下载文件夹。
// 取字节走 plugin-http(不受图床 CORS 限制);失败只返回 false,不影响生图本身。
// 桌面端自动保存生成图:写默认下载文件夹,取字节走 plugin-http(不受图床 CORS 限制),失败只返回 false
const wSaveGenImageToDir = async (item) => {
try {
const dir = wDownloadDir()
@@ -72,6 +79,16 @@
return await wWriteBlobToDir(dir, name, blob)
} catch (e) { return false }
}
// 出图自动下载:三态逻辑在 src/download-auto.js;这里只装配依赖
const wAutoSaver = (typeof window !== 'undefined' && window.IWBDownloadAuto)
? window.IWBDownloadAuto.create({
getDir: wDownloadDir,
isOn: wAutoDownload,
resolveSrc: (item) => wResolveOutputSrc(item, true),
write: wWriteBlobToDir,
toast: (msg, type) => { try { const f = (typeof window !== 'undefined') ? window.__iwbAutoToast__ : null; if (typeof f === 'function') f(msg, type) } catch (e) { /* 组件外调用时忽略 */ } },
})
: null
// 设置里的「打开数据目录」(走一个极小的 Rust 命令,见 src-tauri/src/lib.rs)
const wOpenDataDir = async () => {
const invoke = wTauri && wTauri.core && wTauri.core.invoke
@@ -89,7 +106,8 @@
// 路径来自 save() 的返回值:tauri-plugin-dialog 会把该路径动态加入 fs scope,
// 因此 capabilities 里不需要静态放开任何目录(不放开 $HOME 这类宽权限)。
// 「不再逐个询问」:设了默认目录就直接落盘;写失败(如重启后授权失效)自动退回对话框
if (wSilentSave() && wDownloadDir()) {
// 有目录就直接落盘,没有才弹框(v3.25.20:是否弹框由「有没有目录」决定,不再看开关)
if (wDownloadDir()) {
try { await wWriteBlobToDir(wDownloadDir(), fileName, blob); return true } catch (e) { /* 回退对话框 */ }
}
// 初始路径 = 默认下载文件夹 + 文件名(没设置则只给文件名,跟随系统上次位置)
@@ -118,6 +136,8 @@
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,
@@ -127,6 +147,8 @@
pickDownloadDir: wPickDownloadDir,
getSilentSave: wSilentSave,
setSilentSave: wSetSilentSave,
getAutoDownload: wAutoDownload,
setAutoDownload: wSetAutoDownload,
openDataDir: wOpenDataDir,
marketList: wMarketList,
marketInstalled: wMarketInstalled,
@@ -319,11 +341,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 = () => {
@@ -376,7 +401,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
@@ -819,16 +846,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() // 正在解析的引用键(幂等:渲染路径会反复调用)
@@ -872,7 +911,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) => {
@@ -941,8 +980,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 ''
@@ -1798,10 +1837,9 @@
if (fkEarly && /^https:/i.test(fkEarly) && !wThumbProxyTried.has(fkEarly)) {
wThumbProxyTried.add(fkEarly)
try {
// 桌面端没有 /api/img 代理(无服务端)⇒ 用 plugin-http 直取字节(Rust 侧请求,不受 CORS 限制)
const pr = wIsTauri()
? await wTauri.http.fetch(fkEarly)
: 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()) }))
@@ -2289,14 +2327,28 @@
// 图片引用化**唯一入口**: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
}
@@ -2402,10 +2454,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 */ }
@@ -2624,7 +2676,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
}
@@ -3312,6 +3364,11 @@
function wPrefersDark() {
try { return !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) } catch (e) { return false }
}
// 外观(画布底色 + 主题色)实现在 src/ui-appearance.js:默认值/归一化/写 CSS 变量/对比度提示都在那边。
// 这里只做装配(app.js 有行数棘轮,不再堆细节)。
function applyAppearance(cfg) {
try { const A = window.IWBUIApearance; if (A) A.apply(cfg, document.documentElement.classList.contains('theme-dark')) } catch (e) { /* ignore */ }
}
function applyTheme(t) {
// 'system' 只是存下来的偏好值,真正落地成 dark/light 看系统当前外观
const mode = (t === 'system') ? (wPrefersDark() ? 'dark' : 'light') : (t === 'dark' ? 'dark' : 'light')
@@ -3579,6 +3636,8 @@
Promise.resolve().then(() => wAddOutputs(results)).then(() => {
if (typeof refresh === 'function') return refresh()
}).catch(() => { /* 图库缓存失败不影响画布结果 */ })
// 出图自动下载(勾选且设了目录才生效;失败只提示,不影响生图)
try { if (wAutoSaver) Promise.resolve().then(() => wAutoSaver.saveResults(results)).catch(() => {}) } catch (e) { /* ignore */ }
return Promise.resolve(results)
}
@@ -4324,17 +4383,17 @@
}
}
} catch (e) { /* 继续兜底 */ }
// ③ **本站同源代理**兜底(functions/api/img.js;跨域图床专用。不经任何第三方)
// ③ 原生 HTTP 兜底(Rust 侧请求,不受 CORS 限制)
// 本项目是桌面客户端,没有服务端同源代理(旧的 functions/api/img.js 已随网页版删除)
try {
// 桌面端没有同源代理:改用 plugin-http 直连(Rust 侧请求,不受 CORS 限制)
const r2 = wIsTauri()
? await wTauri.http.fetch(su)
: await fetch('/api/img?url=' + encodeURIComponent(su), { mode: 'cors' })
if (r2.ok) { downloadBlob(await r2.blob()); wDownloadToast(wIsTauri() ? '已通过原生 HTTP 取图保存' : '该图床不支持直连下载,已通过本站代理保存'); 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) || '未知原因'))
@@ -4589,7 +4648,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'),
),
@@ -4641,10 +4700,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)
// 桌面端没有 /api/img 代理:不给 viaUrl,让派生器直连(失败即负缓存并回退原图,不影响显示)
const viaUrl = (/^https?:\/\//i.test(v) && (typeof location === 'undefined' || v.indexOf(location.origin + '/') !== 0) && !wIsTauri())
? (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 }
@@ -4725,10 +4783,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> 不受 CORS 限制,能正常显示;canvas 降采样失败会回退原图)
img.src = (isRemoteHttp && wIsTauri()) ? v
: (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
@@ -5008,7 +5064,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 })
@@ -5440,7 +5496,7 @@ const tbCenterSeed = (type, refs) => {
W_KEEP,
IDB,
IMG_BLOB_PREFIX,
ImageBlobStore,
get ImageBlobStore() { return wImageBlobStore() },
ModularBackupStore,
SchemaVersions,
StorageContract,
@@ -5667,6 +5723,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 防浏览器连续下载拦截)
@@ -5978,7 +6043,12 @@ const tbCenterSeed = (type, refs) => {
// 视口持久化 hooks(阶段二 2026-11-07):从 Workbench 抽到 src/ui-workbench-hooks.js
// 变量名保持不变 ⇒ 下游 viewportRef / activeWsRef / flushViewport 的调用点零改动
const { viewportRef, activeWsRef, flushViewport } = IWWorkbenchHooks.useViewportPersistence(activeWsId, viewport)
// 自动下载的提示回调(模块级装配拿不到组件闭包,这里挂到全局槽)
try { window.__iwbAutoToast__ = (msg, type) => setNotice({ type: type === 'err' ? 'err' : 'ok', text: msg }) } catch (e) { /* ignore */ }
refs.config = config
// 外观:配置到位/切换主题时把画布底色与主题色写到 :root(放在 config 同步之后,
// 否则首屏拿不到配置,改完颜色要重启才生效)
useEffect(() => { try { applyAppearance(config) } catch (e) { /* ignore */ } }, [config, theme])
useEffect(() => {
let alive = true
// 启动时一次性迁移历史 localStorage 里的 base64 大图到 IndexedDB(释放空间,治撑爆)
@@ -8362,8 +8432,12 @@ 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: 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)),
// 紧凑版(v3.25.19):只显示档位值,前缀「插入」放进 title 与标签里,省横向空间
el('select', { className: 'iwb-input iwb-select-compact', 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 iwb-select-compact', value: histRange, onChange: (e) => setHistRange(e.target.value), title: '按时间筛选图库' },
[['', '全部'], ['today', '今天'], ['7d', '7 天'], ['30d', '30 天']].map(([v, l]) => el('option', { key: v, value: v }, l)),
),
),
el('div', { className: 'iwb-history-grid', ref: (el0) => { histGridRef.el = el0 } },
@@ -8372,7 +8446,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(内存数倍占用、过一会儿才回落)。
+67 -110
View File
@@ -1,151 +1,108 @@
# 任务:在 Windows 上为 image-workbench-desktop 产出安装包
# 任务:在 Windows 上为 image-workbench-desktop 构建 v3.25.15 安装包
你是这台 Windows 机器上的打包执行者。目标是把已拉取到本地的 Tauri v2 项目**构建出 Windows x64 安装包**,自测通过后交付产物信息。**只做打包相关的事,不改业务代码。**
你是这台 Windows 机器上的打包执行者。只做打包与自测,**不改业务代码**。
## 背景
> ⚠️ v3.25.15 起的变化:项目已**彻底转桌面客户端**(`_headers` / `functions/` / `wrangler.toml` 已删除,`npm run deploy` 脚本已移除);
> 更新清单**平台解耦**(Windows 用 `updates/latest-windows.json`,**由 Mac 侧用正式私钥生成,你不写**)。
- 项目:Image Workbench 桌面版(Tauri v2 + 原生 JS,前端产物在 dist/)
- 仓库目录:本机已 clone(先自己确认路径,通常在当前目录或其子目录,含 `src-tauri/tauri.conf.json`)
- 应用标识:`com.malongan.imageworkbench`
- 数据目录(运行时):`%USERPROFILE%\Documents\ImageWorkbench`
- 参考文档(仓库内):`docs/DESKTOP_WINDOWS.md`(本次任务的权威说明)
## 硬性约束
## 硬性约束(违反即失败)
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)
1. **不修改** `app.js`、`src/**`、`src-tauri/src/**` 的任何业务逻辑
2. **不绕过** 构建前的 lint 门禁(`beforeBuildCommand` 已含 `npm run lint`);lint 报错就停下来报告,不要改成跳过
3. **不改** `package.json` 里的 scripts 语义;唯一允许改版本号的地方是 `node scripts/set-version.js <版本>`
4. 不用 `npm install`,只用 `npm ci`
5. 不安装/升级全局工具版本(Node/Rust)除非环境检查明确缺失,且每次安装前先向我确认
6. 不把任何密钥、token、代理密码写进文件或提交
7. 不提交 git commit、不推送、不打 tag(除非我明确要求)
## 第一步:环境检查(先做,结果先给我看)
## 第零步:拉代码
```powershell
node -v # 期望 v22.x
npm -v
rustc -V # 必须含 "msvc"
rustup show active-toolchain
git --version
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]` → 继续
- 出现 `[缺失]` → 停止,把缺失项和提示原文发我(不要自行安装)
全部 `[OK]` 才继续;出现 `[缺失]` 停止报告(不要自行安装)。
## 第二步:装依赖
## 第二步:依赖
```powershell
npm ci
```
- 失败先看是不是网络/代理问题(npm 可临时设 `npm config set proxy http://127.0.0.1:10808`,装完删掉)
- 成功后报告:`node_modules` 是否存在、耗时
本次新增两个 Rust 插件依赖(single-instance / notification),首次构建会多拉一些 crate。
## 第三步:定版本号
**本次版本已定:3.25.1**(仓库里 package.json / tauri.conf.json / Cargo.toml 都是这个号)。
不要自行改版本号;只有我明确要求时才用 `node scripts/set-version.js <新版本>`。
## 第三步:构建(用一次性临时密钥签名)
```powershell
node -e "console.log(require('./package.json').version)" # 应输出 3.25.1
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
node -e "console.log(require('./package.json').version, require('./src-tauri/tauri.conf.json').version)"
Select-String -Path src-tauri\Cargo.toml -Pattern '^version'
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
```
## 第四步:构建
## 第五步:自测清单(逐条报通过/失败)
```powershell
npm run app:build
```
**基础**
1. 安装并启动;数据目录 `%USERPROFILE%\Documents\ImageWorkbench` 生成 `data.json`/`canvases`/`library`/`images`
2. **`images\` 下必须有 `canvas` 文件夹**(v3.25.12 之前只有 `thumbs`,这是丢图根因)
3. 设置 → 通用:数据库目录正确;「打开」能弹资源管理器
4. 关窗口进程仍在托盘;左键唤出;右键有菜单
预期内部顺序:`lint → build(含剥离内置插件)→ tauri build`。
首次 5~15 分钟(Rust 依赖编译),之后 1~2 分钟。
**图片持久化(历史 bug 复现点)**
5. `Ctrl+V` 粘贴新图 → 出现图片节点
6. **正常退出**(托盘右键退出,非强杀)→ 重开 → 图仍在、显示正常
7. 从资源管理器拖图进画布 → 退出重开 → 图还在
**失败处理**:
| 报错 | 处理 |
|---|---|
| `link.exe not found` / `LNK` | 缺 VS Build Tools C++ 工作负载 → 停止并报告 |
| rustc 显示 `gnu` | `rustup default stable-x86_64-pc-windows-msvc`(可自行执行) |
| `Windows SDK is not installed` | 停止并报告 |
| npm/网络超时 | 检查代理,重试一次;仍失败则报告 |
| lint 报错 | **停止**,把报错原文发我 |
**桌面壳(本次新增)**
8. 单实例:连续双击两次 → 只有一个窗口,第二次聚焦已有
9. 外链:点「项目主页」→ 用系统浏览器打开,应用不变(不能被导航成网页)
10. 跑一次生图,完成后弹系统通知
## 第五步:确认产物
**插件与 CSP(本次修复)**
11. 设置 → 插件:无内置插件;市场能列 7 个;装一个 → 重启后可用
12. **鲜艺抠图**:启用后对图片节点执行抠图 → **不应出现 `Failed to fetch`**(3.25.11 回归,3.25.14 已修)
13. 若本机有 `XianyiAiRmbg` 监听 `0.0.0.0:30092` → 抠图出透明底;没装则注明跳过
```powershell
Get-ChildItem src-tauri\target\release\bundle -Recurse -Include *.exe,*.msi | Select-Object FullName,Length
```
**外观(本次新增)**
14. 设置 → 外观:改画布底色(亮/暗)与主题色 → 立即生效,重启保持
15. 亮暗切换时画布底色分别用两套值
必须找到(名字里带版本号与 `x64`):
任何一条失败:记录现象 + 截图后停止报告,**不要改代码**。
- `src-tauri\target\release\bundle\nsis\image-workbench_<版本>_x64-setup.exe` ← **主交付物**
- `src-tauri\target\release\bundle\msi\image-workbench_<版本>_x64_en-US.msi` ← 有则附带,没有不算失败(WiX 可能被网络挡)
并计算哈希:
```powershell
Get-FileHash "src-tauri\target\release\bundle\nsis\image-workbench_<版本>_x64-setup.exe" -Algorithm SHA256
```
另外确认**插件没有被塞进包**:
```powershell
Test-Path dist\plugins # 期望 False
```
## 第六步:安装自测(必须做,逐条报告 通过/失败)
1. 运行 `*-setup.exe` 安装并启动
2. 数据目录生成 `%USERPROFILE%\Documents\ImageWorkbench`,内含 `data.json`、`canvases`、`library`、`images`
3. 设置 → 通用:「数据库目录」显示上述路径;点「打开」能弹出资源管理器
4. 关闭窗口后进程仍在托盘;左键托盘图标能唤出窗口;右键有菜单
5. 设置 → 插件:**没有任何内置插件**;「插件市场」能列出 7 个插件;任选一个安装 → 提示重启 → 重启后该插件可用
6. 新建画布、拖拽/缩放节点正常;导入一张本地图片正常
7. 点一次「下载」:文件直接落到导出目录,**不弹另存为对话框**
任何一条失败:记录现象 + 截图,然后停下来报告,不要尝试改代码。
## 第七步:交付
把下面信息整理成表格发我:
- 版本号
- 安装包绝对路径、文件大小(MB)、SHA256
- MSI 是否存在
- 环境检查结论(node/rust/VS/WebView2)
- 六步自测逐条结果
- 构建总耗时
产物先**留在本机**,等我确认后再决定上传方式(scp 到 NAS `/vol8/web/iwb-download/updates/windows-x86_64/`,或我另行安排)。
## 停止条件(遇到即停,不要自行发挥)
- 环境缺件(VS Build Tools / WebView2 / MSVC 工具链)
- lint 或构建报错且一次重试无效
- 自测有任意一条失败
- 需要修改业务代码才能继续
停止时请给出:**卡在哪一步、完整报错、你已经尝试过什么**。
## 最终回复格式
## 第六步:交付格式
```
结论:成功 / 失败(卡在第 N 步)
版本:
版本:3.25.15 commit=<sha>
安装包:<路径> <大小> SHA256=<hex>
自测:1✅ 2✅ 3✅ 4✅ 5✅ 6✅ 7✅(失败的写 ❌ + 现象)
备注:
环境: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 = 1afd5d7`(线上 `v3.25.6+1afd5d7` —— 线上实际运行提交是 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 = cad17e0`(线上 `v3.25.20+cad17e0` —— 线上实际运行提交是 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`(现 **85** 个模块 / 14,607 行,`sourceModules` 85 项;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`(现 **88** 个模块 / 14,607 行,`sourceModules` 88 项;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` 不引用模块全局)。**85 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**88 个模块中 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 耦合面(**74** 项)与 `sourceModules` 顺序(**85** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**74** 项)与 `sourceModules` 顺序(**88** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
## 12. 易踩的坑
@@ -254,7 +254,7 @@
**信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**74** 项)与 `sourceModules` 顺序(**85** 项);新增模块、新增耦合、新增 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` 顺序(**88** 项);新增模块、新增耦合、新增 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`)。
-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 })
}
+3 -5
View File
@@ -1,7 +1,7 @@
{
"name": "image-workbench-web",
"private": true,
"version": "3.25.7",
"version": "3.25.20",
"description": "Browser-based node canvas image workbench",
"scripts": {
"build": "node scripts/build.js && node scripts/copy-plugins.js",
@@ -9,8 +9,8 @@
"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/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/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",
@@ -20,8 +20,6 @@
"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",
+3 -1
View File
@@ -89,6 +89,9 @@ const sourceModules = [
'generation-results-store.js',
'ui-groups-sidebar.js',
'ui-lib-sidebar.js',
'ui-desktop-shell.js',
'ui-appearance.js',
'runtime-download-auto.js',
'ui-workspace-tabs.js',
'ui-app-chrome.js',
'ui-workbench-hooks.js',
@@ -168,7 +171,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))
+14 -15
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env bash
# 发布 Windows 更新:对 Windows 侧构建好的 *-setup.exe 重新签名(用本机正式私钥),
# 上传到 NAS,并把 windows-x86_64 条目合并进 updates/latest.json。
# 上传到 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"
#
@@ -38,27 +39,25 @@ 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.json"
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"
curl -s -m 20 https://download.maqiart.eu.org/updates/latest.json -o "$WORK/latest.json" || echo '{}' > "$WORK/latest.json"
node -e '
const fs = require("fs")
const p = process.argv[1]
let cur = {}
try { cur = JSON.parse(fs.readFileSync(p, "utf8")) } catch (e) { cur = {} }
cur.version = process.env.APP_VERSION
cur.notes = cur.notes || "在线更新"
cur.pub_date = new Date().toISOString()
cur.platforms = cur.platforms || {}
cur.platforms["windows-x86_64"] = { signature: process.env.SIG, url: process.env.URL }
fs.writeFileSync(p, JSON.stringify(cur, null, 2))
console.log(" platforms:", Object.keys(cur.platforms).join(", "))
' "$WORK/latest.json"
$SCP "$WORK/latest.json" "$NAS_HOST:$NAS_DIR/updates/latest.json"
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.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 -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"
+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(项目已转为桌面客户端)')
})
+57 -5
View File
@@ -54,13 +54,13 @@
<h2>下载</h2>
<div class="row">
<div class="name">macOS · Apple Silicon<div class="hint">M1 / M2 / M3 / M4</div></div>
<div class="meta">版本 3.25.7 · 7.3 MB · .dmg<div class="hash">sha256 e4b6b75613916311…</div></div>
<a class="btn" href="/updates/darwin-aarch64/image-workbench_3.25.7_aarch64.dmg">下载</a>
<div class="meta">版本 3.25.20 · 7.5 MB · .dmg<div class="hash">sha256 15cacf28ff8d1f83…</div></div>
<a class="btn" href="/updates/darwin-aarch64/image-workbench_3.25.20_aarch64.dmg">下载</a>
</div>
<div class="row">
<div class="name">macOS · Intel<div class="hint">x86_64</div></div>
<div class="meta">版本 3.25.7 · 7.6 MB · .dmg<div class="hash">sha256 63288e85748e0d36…</div></div>
<a class="btn" href="/updates/darwin-x86_64/image-workbench_3.25.7_x64.dmg">下载</a>
<div class="meta">版本 3.25.20 · 7.8 MB · .dmg<div class="hash">sha256 da173bf6a4281737…</div></div>
<a class="btn" href="/updates/darwin-x86_64/image-workbench_3.25.20_x64.dmg">下载</a>
</div>
<div class="row">
<div class="name">Windows · x64<div class="hint">需要 WebView2</div></div>
@@ -95,9 +95,61 @@
<h2>历史版本</h2>
<div class="row">
<div class="name">3.25.7<div class="hint">Intel 版:剪贴板性能修复</div></div>
<div class="name">3.25.20<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.19<div class="hint">Windows:工单#3 六项 + 图库下拉紧凑化</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.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>
+7 -7
View File
@@ -2,7 +2,7 @@
<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.7-mwlg2nio">
<link rel="stylesheet" href="/assets/style.css?v=3.25.20-mwm5dp9a">
</head><body>
<nav><div class="wrap inner">
<a class="brand" href="/"><span class="dot">IW</span>Image Workbench</a>
@@ -14,19 +14,19 @@
</div>
<div class="right">
<a class="btn" href="/plugins/">插件市场</a>
<a class="btn primary" href="/download/">下载 v3.25.7</a>
<a class="btn primary" href="/download/">下载 v3.25.20</a>
</div>
</div></nav>
<main>
<section class="hero hero-art">
<div class="hero-bg"><img src="/assets/painting.jpg?v=3.25.7-mwlg2nio" alt=""></div>
<div class="hero-bg"><img src="/assets/painting.jpg?v=3.25.20-mwm5dp9a" alt=""></div>
<div class="hero-veil"></div>
<div class="wrap">
<span class="kicker">v3.25.7 · macOS / Windows · 数据在本地</span>
<span class="kicker">v3.25.20 · macOS / Windows · 数据在本地</span>
<h1>本地优先的<br>AI 生图无限画布</h1>
<p class="sub">用节点把「参考图 → 提示词 → 批量生成 → 图库」串成一条生产线。<br>图片、提示词、模型配置全部留在你自己的电脑里,插件按需安装。</p>
<div class="cta">
<a class="btn primary lg" href="/download/">下载 v3.25.7</a>
<a class="btn primary lg" href="/download/">下载 v3.25.20</a>
<a class="btn lg" href="/plugins/">浏览 7 个插件</a>
</div>
<div class="meta">支持 macOS 12+ 与 Windows 10 1803+ · 安装包约 7 MB · 无需登录</div>
@@ -93,8 +93,8 @@
<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.7_aarch64.dmg"><div class="n">macOS · Apple Silicon</div><div class="s">M1 / M2 / M3 / M4 · 7.3 MB · .dmg</div></a>
<a href="/updates/darwin-x86_64/image-workbench_3.25.7_x64.dmg"><div class="n">macOS · Intel</div><div class="s">x86_64 · 7.6 MB · .dmg</div></a>
<div class="dl"><a href="/updates/darwin-aarch64/image-workbench_3.25.20_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.20_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>
+2 -2
View File
@@ -1,7 +1,7 @@
<!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.7-mwlg2nio">
<link rel="stylesheet" href="/assets/style.css?v=3.25.20-mwm5dp9a">
</head><body>
<nav><div class="wrap inner">
<a class="brand" href="/"><span class="dot">IW</span>Image Workbench</a>
@@ -13,7 +13,7 @@
</div>
<div class="right">
<a class="btn" href="/plugins/">插件市场</a>
<a class="btn primary" href="/download/">下载 v3.25.7</a>
<a class="btn primary" href="/download/">下载 v3.25.20</a>
</div>
</div></nav>
<main>
+285 -2
View File
@@ -1,12 +1,289 @@
{
"app": "Image Workbench",
"subtitle": "本地优先的 AI 生图无限画布 · 桌面版(Tauri v2)",
"updatedAt": "2026-11-18T01:30:32.115Z",
"updatedAt": "2026-11-18T13:18:57.990Z",
"releases": [
{
"version": "3.25.20",
"date": "2026-11-18",
"notes": "Intel 版:导出目录三态 + 取色器修复",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.20_aarch64.dmg",
"size": 7829876,
"sha256": "15cacf28ff8d1f83914d31a363ecdc8be3779a8e0478ad27e3be63a4899a0bd9",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.20_x64.dmg",
"size": 8126817,
"sha256": "da173bf6a428173713c63177dfa45a351766e4b156911a503272a5f339a2f2e9",
"kind": "dmg"
}
}
},
{
"version": "3.25.19",
"date": "2026-11-18",
"notes": "Windows:工单#3 六项 + 图库下拉紧凑化",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.19_aarch64.dmg",
"size": 7832598,
"sha256": "2d56def2dc519dd78e2c1d819d698fbc1cf26649b0a6143005564e40eaa11b11",
"kind": "dmg"
},
"darwin-x86_64": {
"file": "updates/darwin-x86_64/image-workbench_3.25.19_x64.dmg",
"size": 8128508,
"sha256": "7d091178ed1f1dcfef2e50d834bb1ec3e4cb0a5b7d7d994fdaf9b2e1b46dbc95",
"kind": "dmg"
},
"windows-x86_64": {
"file": "updates/windows-x86_64/image-workbench_3.25.19_x64-setup.exe",
"size": 4923387,
"sha256": "5ccf97653479fe4b7ba604c3abf5cdcdd778cd658d34783cec4b21c7395f35dd",
"kind": "exe"
}
}
},
{
"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": "Intel 版:剪贴板性能修复",
"notes": "Windows:剪贴板 PNG 传输 + 路径文本转图片 + 大图不卡",
"platforms": {
"darwin-aarch64": {
"file": "updates/darwin-aarch64/image-workbench_3.25.7_aarch64.dmg",
@@ -19,6 +296,12 @@
"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"
}
}
},
+547 -1
View File
@@ -84,6 +84,137 @@ dependencies = [
"x11rb",
]
[[package]]
name = "async-broadcast"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
dependencies = [
"event-listener",
"event-listener-strategy",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "async-channel"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
dependencies = [
"concurrent-queue",
"event-listener-strategy",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "async-executor"
version = "1.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
dependencies = [
"async-task",
"concurrent-queue",
"fastrand",
"futures-lite",
"pin-project-lite",
"slab",
]
[[package]]
name = "async-io"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
dependencies = [
"autocfg",
"cfg-if",
"concurrent-queue",
"futures-io",
"futures-lite",
"parking",
"polling",
"rustix",
"slab",
"windows-sys 0.61.2",
]
[[package]]
name = "async-lock"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f"
dependencies = [
"event-listener",
"event-listener-strategy",
"pin-project-lite",
]
[[package]]
name = "async-process"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
dependencies = [
"async-channel",
"async-io",
"async-lock",
"async-signal",
"async-task",
"blocking",
"cfg-if",
"event-listener",
"futures-lite",
"rustix",
]
[[package]]
name = "async-recursion"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "async-signal"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"
dependencies = [
"async-io",
"async-lock",
"atomic-waker",
"cfg-if",
"futures-core",
"futures-io",
"rustix",
"signal-hook-registry",
"slab",
"windows-sys 0.61.2",
]
[[package]]
name = "async-task"
version = "4.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
[[package]]
name = "async-trait"
version = "0.1.92"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "atk"
version = "0.18.2"
@@ -200,6 +331,19 @@ dependencies = [
"objc2",
]
[[package]]
name = "blocking"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa"
dependencies = [
"async-channel",
"async-task",
"futures-io",
"futures-lite",
"piper",
]
[[package]]
name = "brotli"
version = "9.1.3"
@@ -422,6 +566,15 @@ dependencies = [
"memchr",
]
[[package]]
name = "concurrent-queue"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "constant_time_eq"
version = "0.6.1"
@@ -886,6 +1039,33 @@ dependencies = [
"simdutf8",
]
[[package]]
name = "endi"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
[[package]]
name = "enumflags2"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
dependencies = [
"enumflags2_derive",
"serde",
]
[[package]]
name = "enumflags2_derive"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "env_filter"
version = "0.1.4"
@@ -929,6 +1109,26 @@ version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7"
[[package]]
name = "event-listener"
version = "5.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
dependencies = [
"parking",
"pin-project-lite",
]
[[package]]
name = "event-listener-strategy"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
dependencies = [
"event-listener",
"pin-project-lite",
]
[[package]]
name = "fastrand"
version = "2.5.0"
@@ -1076,6 +1276,19 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
[[package]]
name = "futures-lite"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
dependencies = [
"fastrand",
"futures-core",
"futures-io",
"parking",
"pin-project-lite",
]
[[package]]
name = "futures-macro"
version = "0.3.34"
@@ -1475,6 +1688,12 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
[[package]]
name = "hex"
version = "0.4.3"
@@ -1764,7 +1983,7 @@ dependencies = [
[[package]]
name = "image-workbench"
version = "3.25.7"
version = "3.25.20"
dependencies = [
"arboard",
"base64 0.22.1",
@@ -1778,6 +1997,8 @@ dependencies = [
"tauri-plugin-fs",
"tauri-plugin-http",
"tauri-plugin-log",
"tauri-plugin-notification",
"tauri-plugin-single-instance",
"tauri-plugin-updater",
]
@@ -2120,6 +2341,20 @@ version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
[[package]]
name = "mac-notification-sys"
version = "0.6.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca"
dependencies = [
"cc",
"log",
"objc2",
"objc2-foundation",
"time",
"uuid",
]
[[package]]
name = "markup5ever"
version = "0.39.0"
@@ -2285,6 +2520,20 @@ dependencies = [
"libc",
]
[[package]]
name = "notify-rust"
version = "4.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57da5b5d3b7809bf71858da5a2818c3404ca4688c02c8abecdda0fcdec235df3"
dependencies = [
"futures-lite",
"log",
"mac-notification-sys",
"serde",
"tauri-winrt-notification",
"zbus 6.3.0",
]
[[package]]
name = "num-conv"
version = "0.2.2"
@@ -2559,6 +2808,16 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
[[package]]
name = "ordered-stream"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
dependencies = [
"futures-core",
"pin-project-lite",
]
[[package]]
name = "osakit"
version = "0.3.1"
@@ -2598,6 +2857,12 @@ dependencies = [
"system-deps",
]
[[package]]
name = "parking"
version = "2.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
[[package]]
name = "parking_lot"
version = "0.12.5"
@@ -2739,6 +3004,17 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "piper"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"
dependencies = [
"atomic-waker",
"fastrand",
"futures-io",
]
[[package]]
name = "pkg-config"
version = "0.3.34"
@@ -2771,6 +3047,20 @@ dependencies = [
"miniz_oxide 0.8.9",
]
[[package]]
name = "polling"
version = "3.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
dependencies = [
"cfg-if",
"concurrent-queue",
"hermit-abi",
"pin-project-lite",
"rustix",
"windows-sys 0.61.2",
]
[[package]]
name = "portable-atomic"
version = "1.15.0"
@@ -3660,6 +3950,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
@@ -4215,6 +4515,42 @@ dependencies = [
"time",
]
[[package]]
name = "tauri-plugin-notification"
version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14a226bfb8189ec4ab2c1936e66330ad06c44d9f6c54a674338208491dee177f"
dependencies = [
"log",
"notify-rust",
"rand",
"serde",
"serde_json",
"serde_repr",
"tauri",
"tauri-plugin",
"thiserror 2.0.21",
"time",
"url",
"zbus 5.19.0",
]
[[package]]
name = "tauri-plugin-single-instance"
version = "2.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "726b6da0dd5bd1344f84f4108a622c07d01923baacb5c803a605189672c5352f"
dependencies = [
"serde",
"serde_json",
"tauri",
"thiserror 2.0.21",
"tokio",
"tracing",
"windows-sys 0.61.2",
"zbus 5.19.0",
]
[[package]]
name = "tauri-plugin-updater"
version = "2.14.1"
@@ -4348,6 +4684,17 @@ dependencies = [
"toml 1.2.1+spec-1.1.0",
]
[[package]]
name = "tauri-winrt-notification"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f37a6c354fd28fc9e322ed9bd47e3959576dad28c9d58ea1cf888cce1c7ccb36"
dependencies = [
"thiserror 2.0.21",
"windows",
"windows-version",
]
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -4670,9 +5017,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
@@ -4728,6 +5087,17 @@ version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "uds_windows"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
"windows-sys 0.61.2",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
@@ -5557,6 +5927,128 @@ dependencies = [
"synstructure",
]
[[package]]
name = "zbus"
version = "5.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907"
dependencies = [
"async-broadcast",
"async-executor",
"async-io",
"async-lock",
"async-process",
"async-recursion",
"async-task",
"async-trait",
"blocking",
"enumflags2",
"event-listener",
"futures-core",
"futures-lite",
"hex",
"libc",
"ordered-stream",
"rustix",
"serde",
"serde_repr",
"tracing",
"uds_windows",
"uuid",
"windows-sys 0.61.2",
"winnow 1.0.5",
"zbus_macros 5.19.0",
"zbus_names",
"zvariant",
]
[[package]]
name = "zbus"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b4aae740b23927ceabed962431abab2cdefb9f7f885e5bbab062da09bf580e4"
dependencies = [
"async-trait",
"bitflags 2.13.2",
"endi",
"futures-core",
"hex",
"libc",
"ordered-stream",
"rustix",
"serde",
"serde_repr",
"socket2",
"uds_windows",
"uuid",
"windows-sys 0.61.2",
"winnow 1.0.5",
"zbus_macros 6.3.0",
"zbus_utils",
"zcheapstr",
"zruntime",
]
[[package]]
name = "zbus_macros"
version = "5.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"
dependencies = [
"proc-macro-crate 3.5.0",
"proc-macro2",
"quote",
"syn 3.0.10",
"zbus_names",
"zvariant",
"zvariant_utils",
]
[[package]]
name = "zbus_macros"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37c9dd4beaf145c16fcb2902862f50da86e54aed13dd368ddf64a1d17e6b8529"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
"zbus_utils",
]
[[package]]
name = "zbus_names"
version = "4.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd"
dependencies = [
"serde",
"winnow 1.0.5",
"zvariant",
]
[[package]]
name = "zbus_utils"
version = "6.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 3.0.10",
"winnow 1.0.5",
]
[[package]]
name = "zcheapstr"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920"
dependencies = [
"serde",
]
[[package]]
name = "zerocopy"
version = "0.8.63"
@@ -5681,6 +6173,19 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zruntime"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6a55d4f521760475a30f7b96779508fe8c40dc834478709454dd1d5f0ebc72"
dependencies = [
"futures-core",
"futures-io",
"rustix",
"socket2",
"windows-sys 0.61.2",
]
[[package]]
name = "zune-core"
version = "0.5.3"
@@ -5695,3 +6200,44 @@ checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
dependencies = [
"zune-core",
]
[[package]]
name = "zvariant"
version = "5.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7"
dependencies = [
"endi",
"enumflags2",
"serde",
"winnow 1.0.5",
"zcheapstr",
"zvariant_derive",
"zvariant_utils",
]
[[package]]
name = "zvariant_derive"
version = "5.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d"
dependencies = [
"proc-macro-crate 3.5.0",
"proc-macro2",
"quote",
"syn 3.0.10",
"zvariant_utils",
]
[[package]]
name = "zvariant_utils"
version = "4.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 3.0.10",
"winnow 1.0.5",
]
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "image-workbench"
version = "3.25.7"
version = "3.25.20"
description = "无限画布 · 生图工作台桌面版"
authors = ["malongan"]
license = ""
@@ -29,6 +29,8 @@ 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"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.8 KiB

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1006 B

After

Width:  |  Height:  |  Size: 1013 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 214 B

After

Width:  |  Height:  |  Size: 1.3 KiB

+55 -7
View File
@@ -48,12 +48,13 @@ 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 };
if g.w < 800 || g.h < 500 {
return;
}
let _ = win.set_size(PhysicalSize::new(g.w, g.h));
let cx = g.x + (g.w as i32) / 2;
let cy = g.y + (g.h as i32) / 2;
// 最小尺寸与 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| {
@@ -318,14 +319,61 @@ fn clipboard_write_image(png_base64: String) -> Result<bool, 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])
.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(
+2 -2
View File
@@ -1,7 +1,7 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "image-workbench",
"version": "3.25.7",
"version": "3.25.20",
"identifier": "com.malongan.imageworkbench",
"build": {
"frontendDist": "../dist",
@@ -25,7 +25,7 @@
}
],
"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 http://127.0.0.1:3425 http://localhost:3425; object-src 'none'; base-uri 'none'; frame-ancestors 'none'"
"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": {
+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"
]
}
}
}
+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,
})
+3
View File
@@ -22,6 +22,9 @@
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) },
// 自动下载(v3.25.20):与「点下载是否弹框」解耦,只决定出图后是否自动落盘
getAutoDownload() { return !!(state.impl && state.impl.getAutoDownload && state.impl.getAutoDownload()) },
setAutoDownload(on) { if (state.impl && state.impl.setAutoDownload) state.impl.setAutoDownload(on) },
openDataDir() { return state.impl ? state.impl.openDataDir() : Promise.reject(new Error('仅桌面端可用')) },
// 原生剪贴板图片(v3.26):WKWebView 里 paste 事件拿不到 Finder 复制的图片,
// navigator.clipboard.write 也常不可用,统一走 Rust 侧 arboard。
+79
View File
@@ -0,0 +1,79 @@
/* download-auto.js —— 「出图后自动下载」(v3.25.20)
*
* 三态逻辑(用户裁定):
* 目录 + 自动下载勾选 → 出图完成后自动保存到该目录
* 目录 + 未勾选 → 不自动保存;点「下载」直接存该目录(不弹框)
* 无目录 → 点「下载」时弹出目录/另存为选择
*
* 命名:gen_<时间戳>.png;同名不覆盖(DedupeName 由调用方注入,内部只负责取字节与落盘)。
* 落盘失败只记录、不抛错:自动下载是附加行为,绝不能影响生图本身。
*/
;(function (global) {
'use strict'
const g = /** @type {any} */ (global || {})
/**
* @param {object} deps
* getDir() → 当前下载目录(空串表示未设置)
* isOn() → 自动下载开关
* resolveSrc(item) → Promise<dataURL|url>(本地归档优先)
* write(dir, name, blob) → Promise<boolean>
* toast(msg, type) → void
*/
function create (deps) {
const d = deps || {}
const getDir = typeof d.getDir === 'function' ? d.getDir : function () { return '' }
const isOn = typeof d.isOn === 'function' ? d.isOn : function () { return false }
const resolveSrc = typeof d.resolveSrc === 'function' ? d.resolveSrc : null
const write = typeof d.write === 'function' ? d.write : null
const toast = typeof d.toast === 'function' ? d.toast : function () {}
const stamp = () => {
const n = new Date()
const p = (v) => String(v).padStart(2, '0')
return n.getFullYear() + p(n.getMonth() + 1) + p(n.getDate()) + '-' + p(n.getHours()) + p(n.getMinutes()) + p(n.getSeconds())
}
let running = false // 防并发重入:一次出图可能触发多次归档
return {
enabled: () => !!(getDir() && isOn() && write && resolveSrc),
/** 保存一批结果;返回成功条数(失败静默,只提示一次) */
async saveResults (items) {
if (!this.enabled() || running) return 0
const list = (Array.isArray(items) ? items : []).filter((x) => x && x.ok !== false && (x.url || x.data))
if (!list.length) return 0
running = true
let saved = 0
let failed = 0
const used = new Set()
try {
for (const item of list) {
try {
const src = await resolveSrc(item)
if (!src) { failed++; continue }
const resp = await fetch(src)
if (!resp || !resp.ok) { failed++; continue }
const blob = await resp.blob()
let name = 'gen_' + stamp() + '.png'
// 同一批次时间戳相同 ⇒ 加序号,避免批次内互相覆盖(跨批次同名由落盘侧去重)
if (used.has(name)) {
let i = 2
while (used.has(name.replace(/\.png$/, '-' + i + '.png'))) i++
name = name.replace(/\.png$/, '-' + i + '.png')
}
used.add(name)
const ok = await write(getDir(), name, blob)
if (ok) saved++
else failed++
} catch (e) { failed++ }
}
} finally { running = false }
if (saved) toast('已自动下载 ' + saved + ' 张到导出目录', 'ok')
else if (failed) toast('自动下载失败(' + failed + ' 张),请检查导出目录是否可写', 'err')
return saved
},
}
}
g.IWBDownloadAuto = Object.freeze({ create })
})(typeof window !== 'undefined' ? window : globalThis)
+5 -26
View File
@@ -1119,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 }
@@ -1143,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)
+59 -6
View File
@@ -176,16 +176,26 @@
const kv = {
async put(key, value) {
try {
if (!enabled() || !dir) return false
// 返回对象而不是裸 false:调用方(ImageBlobStore.put)用 r.ok===false 判断失败,
// 裸布尔 false 会被误判为成功,产出指向空文件的 {__blob}(v3.25.10 修)。
if (!enabled() || !dir) return { ok: false, error: 'not-ready' }
if (value && typeof value === 'object' && typeof value.size === 'number' && value.type !== undefined) {
// Blob:直接取二进制落盘
const buf = await value.arrayBuffer()
const hash = await sha16(buf)
const rel = IMG_DIR + '/' + catOfKey(key) + '/' + hash + '.' + extOf(value.type)
const cat = catOfKey(key)
const rel = IMG_DIR + '/' + cat + '/' + hash + '.' + extOf(value.type)
const abs = await join(dir, rel)
// Windows 全新安装时 images/canvas|gallery 并不存在(只有 thumbs 因为 writeDisplayThumb 会 mkdir),
// 直接 writeFile 会失败 → 整条 blob 写入被判失败 → 图片退化成不持久引用。
// 这里先建目录(幂等),与 thumbs 的写法保持一致。
try { await fs().mkdir(await join(dir, IMG_DIR, cat), { recursive: true }) } catch (e) { /* 已存在 */ }
await fs().writeFile(abs, new Uint8Array(buf))
assets[String(key)] = { f: rel, k: 'blob', m: value.type || 'application/octet-stream' }
schedule()
// 立即落盘:登记表只存在 data.json 里,晚 800ms 就可能被强杀丢掉,
// 而画布文件是即时写的 ⇒ 引用还在、登记没了,GC 会把在用图片当孤儿。
await flush()
return true
}
const s = String(value)
@@ -193,11 +203,14 @@
const dec = dataUrlToBytes(s)
if (dec) {
const hash = await sha16(dec.bytes)
const rel = IMG_DIR + '/' + catOfKey(key) + '/' + hash + '.' + extOf(dec.mime)
const cat2 = catOfKey(key)
const rel = IMG_DIR + '/' + cat2 + '/' + hash + '.' + extOf(dec.mime)
const abs = await join(dir, rel)
try { await fs().mkdir(await join(dir, IMG_DIR, cat2), { recursive: true }) } catch (e) { /* 已存在 */ }
await fs().writeFile(abs, dec.bytes)
assets[String(key)] = { f: rel, k: 'dataurl', m: dec.mime }
schedule()
await flush()
return true
}
}
@@ -206,7 +219,7 @@
return true
} catch (e) {
try { global.IWBMetricsSwallow && global.IWBMetricsSwallow('file-kv-put', e) } catch (e2) { /* ignore */ }
return false
return { ok: false, error: String((e && e.message) || e) }
}
},
async get(key) {
@@ -611,6 +624,15 @@
return true
}
/* 建立工作必需目录:canvases/ library/ plugins/ trash/ 与 images/{canvas,gallery,thumbs,legacy} */
async function ensureDirs() {
const subs = [CANVAS_DIR, 'library', PLUG_DIR, 'trash', IMG_DIR, IMG_DIR + '/canvas', IMG_DIR + '/gallery', IMG_DIR + '/thumbs', IMG_DIR + '/legacy']
for (const sub of subs) {
try { await fs().mkdir(await join(dir, sub), { recursive: true }) } catch (e) { /* 已存在或不可写:继续下一个 */ }
}
return true
}
async function init(opts) {
const o = opts || {}
tauri = global.__TAURI__ || null
@@ -634,6 +656,11 @@
dir = want
try { global.localStorage.setItem(PTR_KEY, dir) } catch (e) { /* ignore */ }
try { await fs().mkdir(await join(dir, IMG_DIR), { recursive: true }) } catch (e) { /* 已存在 */ }
// 兜底:把工作必需的子目录一次性补齐(幂等)。
// 为什么需要:Windows 全新安装时 images/ 下只有 thumbs/,缺了 canvas/ 会导致
// 图片写入失败(历史 bug:写进不持久的 Cache → 重启丢图);目录被手工删掉时也靠这里自愈,
// 否则启动阶段读目录抛错会直接影响首屏渲染。
try { await ensureDirs() } catch (e) { /* 建目录失败不阻塞启动 */ }
try { await repairCanvasFileNames() } catch (e) { /* 修复失败按原样装载 */ }
await loadInto()
// 从 WebView 的 localStorage 捞回被截断/覆盖的画布(一次性)
@@ -811,6 +838,28 @@
try {
if (!enabled() || !dir) return { ok: false, error: '资料目录未就绪' }
const used = new Set(Object.keys(assets).map((k) => assets[k] && assets[k].f).filter(Boolean))
/* v3.25.8:assets 登记表是唯一的「在用」判据,但它可能因为恢复备份/迁移而落后于画布。
* 只看 assets 会把画布仍在引用的图片当孤儿挪进 trash/ —— 节点随即变成占位图,
* 而且用户重新拖入时又被同图去重挡回来(那条链路已废)。
* 这里把 canvases/*.json 里出现的 {__blob} key 也算作在用:宁可留下几 MB,也不误删用户图片。 */
const canvasKeys = new Set()
try {
const cd = await join(dir, 'canvases')
const list = await fs().readDir(cd)
for (const e of list) {
if (!e || e.isDirectory || !/\.json$/i.test(e.name) || e.name === 'active.json') continue
let txt = ''
try { txt = await fs().readTextFile(await join(cd, e.name)) } catch (err) { continue }
const m = txt.match(/"__blob"\s*:\s*"([^"]+)"/g) || []
for (const hit of m) {
const km = /"([^"]+)"$/.exec(hit)
if (km) canvasKeys.add(km[1])
}
}
} catch (e) { /* 画布读不到就退回旧判据 */ }
const referenced = new Set()
for (const k of canvasKeys) { const a = assets[k]; if (a && a.f) referenced.add(a.f) }
referenced.forEach((f) => used.add(f))
const imgAbs = await join(dir, IMG_DIR)
// 子目录也要扫:images/{canvas,gallery,thumbs,legacy}/ 里的孤儿同样占空间
const subs = ['', 'canvas', 'gallery', 'thumbs', 'legacy']
@@ -825,7 +874,11 @@
if (!used.has(rel)) orphans.push({ sub: sub, name: e.name, rel: rel })
}
}
if (dryRun || !orphans.length) return { ok: true, orphans: orphans.length, moved: 0, dryRun: dryRun }
// 断链:画布引用了、但登记表里没有的 key —— 这类节点的图**已经显示不出来**,
// GC 不会动它们(文件根本不在),但值得在确认弹窗里报数,让用户知道数据已经缺了。
const dangling = Array.from(canvasKeys).filter((k) => !assets[k]).length
const keptByCanvas = referenced.size
if (dryRun || !orphans.length) return { ok: true, orphans: orphans.length, moved: 0, dryRun: dryRun, dangling: dangling, keptByCanvas: keptByCanvas }
const trashAbs = await join(dir, 'trash')
let moved = 0
for (const item of orphans) {
@@ -836,7 +889,7 @@
moved++
} catch (e) { /* 单条失败忽略 */ }
}
return { ok: true, orphans: orphans.length, moved: moved, dryRun: dryRun }
return { ok: true, orphans: orphans.length, moved: moved, dryRun: dryRun, dangling: dangling, keptByCanvas: keptByCanvas }
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
}
+226
View File
@@ -0,0 +1,226 @@
/* ui-appearance.js —— 外观(画布底色 + 主题色)与取色器(v3.25.14)
*
* 为什么单独成模块:
* app.js 有行数棘轮(上限 8905),外观相关的默认值 / 归一化 / 应用到 CSS 变量 /
* 取色器组件 / 设置页渲染块全放这里,app.js 只留一行注入调用。
*
* 设计要点(与工单 ③ 对齐):
* · 画布底色分**亮/暗两套**(--iwb-canvas-bg 在主题切换时取不同值)
* · 主题色**两套共用一个**(用户裁定):连线、端口、主按钮、选中框、进度动画都吃 --iwb-brand
* · 连线单独一个变量 --iwb-edge(默认 = 边框灰;主题色只给选中/悬停/上下游高亮用)
* · 颜色合法性:只接受 #rgb / #rrggbb,非法值回退默认,绝不把坏值写进 CSS
*/
;(function (global) {
'use strict'
const g = (global && typeof global === 'object') ? global : {}
const React = g.React || {}
const el = (type, prop, ...children) => React.createElement(type, prop, ...children)
const DEFAULTS = Object.freeze({ canvasBgLight: '#d9dbde', canvasBgDark: '#6f6f6f', accent: '#6b7280' })
const HEX_RE = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i
const isHex = (v) => HEX_RE.test(String(v || ''))
const normHex = (v) => {
const s = String(v || '').trim()
if (!isHex(s)) return ''
if (s.length === 4) return ('#' + s[1] + s[1] + s[2] + s[2] + s[3] + s[3]).toLowerCase()
return s.toLowerCase()
}
function normalize (cfg) {
const c = (cfg && cfg.canvas && cfg.canvas.appearance) || {}
return {
canvasBgLight: normHex(c.canvasBgLight) || DEFAULTS.canvasBgLight,
canvasBgDark: normHex(c.canvasBgDark) || DEFAULTS.canvasBgDark,
accent: normHex(c.accent) || DEFAULTS.accent,
}
}
/** 把外观写到 :root(dark 决定画布底色取哪一套;主题色两套共用) */
function apply (cfg, dark) {
try {
const a = normalize(cfg)
const root = g.document && g.document.documentElement
if (!root || !root.style) return
root.style.setProperty('--iwb-canvas-bg', dark ? a.canvasBgDark : a.canvasBgLight)
root.style.setProperty('--iwb-brand', a.accent)
} catch (e) { /* 样式写失败不影响功能 */ }
}
// ── 颜色工具(取色器与对比度提示共用)──
function hexToRgb (hex) {
const h = normHex(hex) || DEFAULTS.accent
return { r: parseInt(h.slice(1, 3), 16), g: parseInt(h.slice(3, 5), 16), b: parseInt(h.slice(5, 7), 16) }
}
function rgbToHex (r, gg, b) {
const p = (n) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, '0')
return '#' + p(r) + p(gg) + p(b)
}
function rgbToHsv (r, gg, b) {
const R = r / 255, G = gg / 255, B = b / 255
const max = Math.max(R, G, B), min = Math.min(R, G, B)
const d = max - min
let h = 0
if (d) {
if (max === R) h = ((G - B) / d) % 6
else if (max === G) h = (B - R) / d + 2
else h = (R - G) / d + 4
h *= 60
if (h < 0) h += 360
}
return { h: h, s: max ? d / max : 0, v: max }
}
function hsvToRgb (h, s, v) {
const c = v * s
const x = c * (1 - Math.abs(((h / 60) % 2) - 1))
const m = v - c
let R = 0, G = 0, B = 0
if (h < 60) { R = c; G = x } else if (h < 120) { R = x; G = c } else if (h < 180) { G = c; B = x } else if (h < 240) { G = x; B = c } else if (h < 300) { R = x; B = c } else { R = c; B = x }
return { r: (R + m) * 255, g: (G + m) * 255, b: (B + m) * 255 }
}
const lum = (rgb) => {
const f = (v) => { const c = v / 255; return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4) }
return 0.2126 * f(rgb.r) + 0.7152 * f(rgb.g) + 0.0722 * f(rgb.b)
}
function contrast (a, b) {
const l1 = lum(hexToRgb(a)), l2 = lum(hexToRgb(b))
const hi = Math.max(l1, l2), lo = Math.min(l1, l2)
return (hi + 0.05) / (lo + 0.05)
}
const readableOn = (bg) => (contrast(bg, '#1c2333') >= 3 ? '#1c2333' : '#ffffff')
/* ── 取色器(仿 Obsidian:饱和度/明度方块 + 色相滑条 + RGB 输入 + 十六进制)── */
function ColorPicker (props) {
const value = normHex(props && props.value) || DEFAULTS.accent
const onChange = (props && props.onChange) || function () {}
const [open, setOpen] = React.useState(false)
const [hsv, setHsv] = React.useState(() => { const c = hexToRgb(value); return rgbToHsv(c.r, c.g, c.b) })
const boxRef = React.useRef(null)
// 外部值变化(恢复默认)时同步内部 HSV
React.useEffect(() => {
const c = hexToRgb(value)
setHsv((prev) => {
const next = rgbToHsv(c.r, c.g, c.b)
// 灰色时色相无意义,保留用户当前色相,避免跳回 0
return { h: next.s === 0 ? prev.h : next.h, s: next.s, v: next.v }
})
}, [value])
const emit = (next) => {
const c = hsvToRgb(next.h, next.s, next.v)
onChange(rgbToHex(c.r, c.g, c.b))
}
const pick = (e) => {
const box = boxRef.current
if (!box || !box.getBoundingClientRect) return
const r = box.getBoundingClientRect()
const x = Math.max(0, Math.min(1, (e.clientX - r.left) / r.width))
const y = Math.max(0, Math.min(1, (e.clientY - r.top) / r.height))
const next = { h: hsv.h, s: x, v: 1 - y }
setHsv(next); emit(next)
}
const hue = (e) => { const next = { h: Number(e.target.value) || 0, s: hsv.s || 0.6, v: hsv.v || 1 }; setHsv(next); emit(next) }
const rgb = hexToRgb(value)
const setChannel = (k) => (e) => {
const n = Math.max(0, Math.min(255, Number(e.target.value) || 0))
const c = { ...rgb }
c[k] = n
onChange(rgbToHex(c.r, c.g, c.b))
}
const hueColor = 'hsl(' + Math.round(hsv.h) + ',100%,50%)'
return el('div', { className: 'iwb-cpick' },
el('button', {
type: 'button',
className: 'iwb-cpick-swatch',
title: '点击取色',
onClick: () => setOpen((v) => !v),
style: { background: value, color: readableOn(value) },
}, el('span', { className: 'iwb-cpick-hex' }, value.toUpperCase())),
open ? el('div', { className: 'iwb-cpick-pop', onPointerDown: (e) => e.stopPropagation() },
el('div', {
className: 'iwb-cpick-box',
ref: boxRef,
onPointerDown: (e) => { e.currentTarget.setPointerCapture && e.currentTarget.setPointerCapture(e.pointerId); pick(e) },
onPointerMove: (e) => { if (e.buttons === 1) pick(e) },
style: { background: 'linear-gradient(to top, #000, rgba(0,0,0,0)), linear-gradient(to right, #fff, ' + hueColor + ')' },
},
el('div', { className: 'iwb-cpick-dot', style: { left: (hsv.s * 100) + '%', top: ((1 - hsv.v) * 100) + '%', background: value } })),
el('input', { type: 'range', min: 0, max: 360, value: Math.round(hsv.h), onChange: hue, className: 'iwb-cpick-hue', style: { background: 'linear-gradient(to right,#f00,#ff0,#0f0,#0ff,#00f,#f0f,#f00)' } }),
el('div', { className: 'iwb-cpick-rgb' },
['r', 'g', 'b'].map((k) => el('label', { key: k, className: 'iwb-cpick-chan' },
el('input', { type: 'number', min: 0, max: 255, value: rgb[k], onChange: setChannel(k) }),
el('span', null, k.toUpperCase())))),
el('div', { className: 'iwb-cpick-foot' },
el('input', {
className: 'iwb-input iwb-cpick-input',
value: value,
onChange: (e) => { const v = normHex(e.target.value); if (v) onChange(v) },
title: '支持 #rgb / #rrggbb',
}),
g.EyeDropper ? el('button', {
type: 'button',
className: 'iwb-btn iwb-btn-sm',
title: '从屏幕取色',
onClick: () => { try { new g.EyeDropper().open().then((r) => { const v = normHex(r && r.sRGBHex); if (v) onChange(v) }).catch(() => {}) } catch (e) { /* ignore */ } },
}, '吸管') : null,
el('button', { type: 'button', className: 'iwb-btn iwb-btn-sm', onClick: () => setOpen(false) }, '完成')),
) : null,
)
}
/* ── 设置 → 外观 ── */
function AppearanceTab (props) {
const draft = (props && props.draft) || {}
const setDraft = (props && props.setDraft) || function () {}
const value = normalize(draft)
const set = (patch) => setDraft((d) => Object.assign({}, d, {
canvas: Object.assign({}, d.canvas, { appearance: Object.assign({}, normalize(d), patch) }),
}))
const warn = (bg) => {
const ratio = contrast(bg, '#1c2333')
if (ratio >= 4.5) return null
return el('div', { className: 'iwb-hint iwb-hint-warn' }, '与深色文字对比度 ' + ratio.toFixed(1) + ':1(建议 ≥4.5:1),可能不易阅读')
}
const theme = (props && props.theme) || 'light'
const setTheme = (props && props.setTheme) || function () {}
const applyTheme = (props && props.applyTheme) || function () {}
return el('div', null,
el('div', { className: 'iwb-section-sub' }, '界面主题'),
el('div', { className: 'iwb-row' },
el('span', { className: 'iwb-label' }, '配色模式'),
el('select', {
className: 'iwb-input',
title: '界面配色(亮色保证文字清晰)',
value: theme,
onChange: (e) => { const t = e.target.value; const v = (t === 'dark' || t === 'system') ? t : 'light'; setTheme(v); applyTheme(v) },
},
el('option', { value: 'light' }, '亮色(默认:节点灰底 + 内容白)'),
el('option', { value: 'dark' }, '暗色'),
el('option', { value: 'system' }, '跟随系统'),
)),
el('div', { className: 'iwb-section-sub' }, '画布底色'),
el('div', { className: 'iwb-row' },
el('span', { className: 'iwb-label' }, '亮色调'),
el(ColorPicker, { value: value.canvasBgLight, onChange: (v) => set({ canvasBgLight: v }) })),
warn(value.canvasBgLight),
el('div', { className: 'iwb-row' },
el('span', { className: 'iwb-label' }, '暗色调'),
el(ColorPicker, { value: value.canvasBgDark, onChange: (v) => set({ canvasBgDark: v }) })),
warn(value.canvasBgDark),
el('div', { className: 'iwb-section-sub' }, '主题色'),
el('div', { className: 'iwb-row' },
el('span', { className: 'iwb-label' }, '按钮 / 选中框 / 高亮连线'),
el(ColorPicker, { value: value.accent, onChange: (v) => set({ accent: v }) })),
el('div', { className: 'iwb-hint' }, '主题色同时用于亮色与暗色主题;按钮、端口、选中框、进度动画会跟着变。连线默认是灰色,只有选中/悬停时的高亮连线才用主题色。'),
el('div', { className: 'iwb-row' },
el('button', {
className: 'iwb-btn iwb-btn-sm',
onClick: () => setDraft((d) => Object.assign({}, d, { canvas: Object.assign({}, d.canvas, { appearance: Object.assign({}, DEFAULTS) }) })),
}, '恢复默认')),
)
}
g.IWBUIApearance = Object.freeze({ DEFAULTS, normalize, apply, contrast, ColorPicker, AppearanceTab })
})(typeof window !== 'undefined' ? window : globalThis)
-30
View File
@@ -440,28 +440,6 @@ function BackupModal(props) {
el('span', { className: 'iwb-backup-item-name' }, label),
el('span', { className: 'iwb-backup-item-count' }, n),
)
// 清理本地数据:清空 localStorage(iwb_*) + IndexedDB(iwb_web),不可撤销
const doClear = async () => {
if (!(await askConfirm('确定清空本机的全部本地数据吗?\n\n将删除:设置、提示词库、节点组、画布工作台、图库索引与本机图片。\n此操作不可撤销。\n\n建议先「导出备份」再清理。', { title: '清空本地数据', okText: '全部清空' }))) return
setClearBusy(true); setClearMsg(null)
try {
const st = _lstore()
const toRemove = st ? st.keys().filter((k) => k && (k.indexOf('iwb_') === 0 || k.indexOf('__iwb_') === 0)) : []
for (const k of toRemove) { try { if (st) st.remove(k) } catch (e) { /* ignore */ } }
await new Promise((resolve) => {
if (typeof indexedDB === 'undefined') return resolve()
try {
const req = indexedDB.deleteDatabase(StorageContract.indexedDb.name)
req.onsuccess = req.onerror = req.onblocked = () => resolve()
setTimeout(() => resolve(), 800)
} catch (e) { resolve() }
})
setClearMsg({ type: 'ok', text: '✓ 本地数据已清空,即将刷新页面' })
setTimeout(() => { try { location.reload() } catch (e) { /* ignore */ } }, 500)
} catch (e) {
setClearMsg({ type: 'err', text: '清理失败:' + String((e && e.message) || e) })
} finally { setClearBusy(false) }
}
// 本组件**只以嵌入形式**使用(设置面板的「备份与还原」Tab)。
// 2026-10-29:用户要求移除另外两个菜单入口后,独立弹层分支(遮罩 + 标题栏 ✕)已无调用方,
// 属于死代码 ⇒ 一并删除;同时嵌入时不套 `.iwb-modal`,避免设置面板里多出一层外框(用户反馈"不要框住了")。
@@ -533,14 +511,6 @@ function BackupModal(props) {
el('div', { className: 'iwb-backup-note' },
'提示:若需连同出图一起备份,请勾选「图库(含缩略图+原图)」(默认不勾选,避免备份体积随出图历史膨胀);画布工作台备份仍只带参考图,生成结果不入画布数据。备份为 ZIP/JSON 文件,请自行妥善保管。',
),
el('div', { className: 'iwb-backup-sec' },
el('div', { className: 'iwb-backup-sec-title' }, '③ 清理本地数据'),
el('div', { className: 'iwb-backup-item-count iwb-warn' }, '清空设置/提示词库/节点组/画布/图库及本机图片(IndexedDB)。不可撤销,建议先导出备份。'),
el('div', { className: 'iwb-backup-actions' },
el('button', { className: 'iwb-btn iwb-btn-danger', disabled: clearBusy, onClick: doClear }, clearBusy ? '清理中…' : '清空全部本地数据'),
),
clearMsg ? el('div', { className: 'iwb-status-' + (clearMsg.type === 'err' ? 'err' : 'ok') }, clearMsg.text) : null,
),
),
)
}
+85
View File
@@ -0,0 +1,85 @@
/* ui-desktop-shell.js —— 桌面端外壳适配(2026-11-18)
*
* 平台迁移后需要「网页做不到、只有桌面壳能做」的三件事,集中放这里,
* 避免 app.js 继续膨胀(source-text-ratchet 上限):
* 1) 外链一律交给系统浏览器:桌面 webview 里点 <a target=_blank> 会把整个应用导航成网页
* 2) 桌面原生通知:WKWebView 不支持 Web Notification
* 3) 捕获阶段拦截外链点击(含中键)
*
* 网页版不装 Tauri,isTauri() 恒 false ⇒ 全部走浏览器原生行为,语义不变。
*/
;(function (global) {
'use strict'
const g = /** @type {any} */ (global || {})
const EXTERNAL_RE = /^https?:\/\//i
function tauri () {
const T = g.__TAURI__
return (T && T.core && typeof T.core.invoke === 'function') ? T : null
}
function openExternal (url) {
const u = String(url || '')
if (!EXTERNAL_RE.test(u)) return false
const T = tauri()
if (T) {
try { T.core.invoke('open_external_url', { url: u }) } catch (e) { /* 忽略:下面还会尝试原生窗口 */ }
return true
}
try { global.open(u, '_blank', 'noopener') } catch (e) { /* ignore */ }
return true
}
/** 生成完成通知:桌面走原生;返回 true 表示已处理(调用方不要再走 Web Notification) */
function notifyGenerationDone (info) {
if (!tauri()) return false
const x = info || {}
const total = Number(x.total) || 0
const failed = Number(x.failed) || 0
const title = failed ? '出图完成(部分失败)' : '出图完成'
const body = failed
? ('成功 ' + Math.max(0, total - failed) + ' 张,失败 ' + failed + ' 张')
: ('共生成 ' + total + ' 张图片')
try { tauri().core.invoke('notify_desktop', { title: title, body: body }) } catch (e) { /* ignore */ }
return true
}
function notifyDesktop (title, body) {
const T = tauri()
if (!T) return false
try { T.core.invoke('notify_desktop', { title: String(title || ''), body: String(body || '') }) } catch (e) { /* ignore */ }
return true
}
/* 捕获阶段拦截外链点击(含中键):桌面端不允许把应用窗口导航走 */
function installLinkGuard (isTauri) {
if (typeof document === 'undefined' || !document.addEventListener) return false
if (isTauri && !isTauri()) return false
const pick = (e) => {
const t = e.target
const a = (t && t.closest) ? t.closest('a[href]') : null
if (!a) return ''
const href = a.getAttribute('href') || ''
return EXTERNAL_RE.test(href) ? href : ''
}
document.addEventListener('click', (e) => {
const href = pick(e)
if (!href) return
e.preventDefault()
e.stopPropagation()
openExternal(href)
}, true)
document.addEventListener('auxclick', (e) => {
if (e.button !== 1) return
const href = pick(e)
if (!href) return
e.preventDefault()
openExternal(href)
}, true)
return true
}
g.IWBUIShell = Object.freeze({ openExternal, notifyDesktop, notifyGenerationDone, installLinkGuard })
})(typeof window !== 'undefined' ? window : globalThis)
+13 -2
View File
@@ -17,7 +17,7 @@
// · ctx = { onUpdate, busy, progress, h, stop, refMini },由调用方 renderBodyInner 组装。
// ── 注入依赖(app.js 在首次渲染时调用 inject 注入)─────────────────────────
let I, LocalTextField, autoGrow, React, ReactDOM, combineSourcePairs, downloadUrl, isImageProducer, nodePreviewRefsV2, nodeInheritOf, orderedUniqueRefNodes, outProgUI, outThumbCache, uploadRefToImageHost, wDisplayThumbOf, wImportImage, wPreviewUrlOf, wRawCfg, wResolveImg, wThumbSrc, el, wPluginNodeVariants, wPluginVariantMeta, isBatchSrc, batchSrcText, compareCanvasTextOrder, GenParams, RATIOS, RES_KEYS, RES_MAP, cachedGenerationTasks, classifyErr, fmtDur, presetDisplayName, ratioOfSize, resOfSize, taskStallEndMs, wDedupeTaskIds
let I, LocalTextField, autoGrow, React, ReactDOM, combineSourcePairs, downloadUrl, wResolveOutSrc, isImageProducer, nodePreviewRefsV2, nodeInheritOf, orderedUniqueRefNodes, outProgUI, outThumbCache, uploadRefToImageHost, wDisplayThumbOf, wImportImage, wPreviewUrlOf, wRawCfg, wResolveImg, wThumbSrc, el, wPluginNodeVariants, wPluginVariantMeta, isBatchSrc, batchSrcText, compareCanvasTextOrder, GenParams, RATIOS, RES_KEYS, RES_MAP, cachedGenerationTasks, classifyErr, fmtDur, presetDisplayName, ratioOfSize, resOfSize, taskStallEndMs, wDedupeTaskIds
function inject(d) {
const D = d || {}
I = D.I
@@ -30,6 +30,7 @@
autoGrow = D.autoGrow
combineSourcePairs = D.combineSourcePairs
downloadUrl = D.downloadUrl
wResolveOutSrc = D.wResolveOutputSrc
isImageProducer = D.isImageProducer
nodePreviewRefsV2 = D.nodePreviewRefsV2
nodeInheritOf = D.nodeInheritOf
@@ -832,7 +833,17 @@
el('div', { className: 'iwb-out-cell-meta' }, (r.width || '?') + '×' + (r.height || '?')),
el('div', { className: 'iwb-out-cell-actions' },
el('button', { className: 'iwb-btn iwb-btn-sm', title: '插入为参考图节点', onClick: () => props.onCopyRef && props.onCopyRef(r.url), onPointerDown: stop }, I('copy')),
el('button', { className: 'iwb-btn iwb-btn-sm', title: '下载', onClick: () => downloadUrl(r.url, 'image.png'), onPointerDown: stop }, I('download')),
el('button', {
className: 'iwb-btn iwb-btn-sm',
title: '下载',
// v3.25.18:从资料目录的本地归档取图(原图优先),远端 URL 只作兜底
onClick: async () => {
let src = r.url
try { if (wResolveOutSrc) src = (await wResolveOutSrc(r, true)) || r.url } catch (e) { /* 回退远端 */ }
downloadUrl(src, 'image.png')
},
onPointerDown: stop,
}, I('download')),
),
)
}
+13 -3
View File
@@ -440,6 +440,15 @@ function SettingsModal(props) {
addLlmAddr, addLlmKey, addLlmModel, addLlmProvider, api, delLlmAddr, delLlmKey, delLlmModel, delLlmProvider, draft, llmAddrInput, llmAddrRes, llmAddrTesting, llmKeyInput, llmModelInput, llmTestMsg, llmTestSel, llmTesting, llmWarn, msg, setLlm, setLlmAddr, setLlmAddrDefault, setLlmAddrInput, setLlmDefaultModel, setLlmKey, setLlmKeyInput, setLlmModelInput, setLlmProv, setLlmTestSel, testLlm, testLlmAddrs,
}) : el('div', { className: 'iwb-hint' }, 'llmTab 未就绪(请刷新页面)')
const imgTab = el('div', null, transferSection)
// 外观:画布底色(亮/暗两套)+ 主题色(两套共用)。实现见 src/ui-appearance.js。
const appearanceTab = (function () {
const A = (typeof window !== 'undefined') ? window.IWBUIApearance : null
if (!A || !A.AppearanceTab) return el('div', { className: 'iwb-hint' }, '外观模块未就绪(请刷新页面)')
return el('div', { className: 'iwb-section' },
el('div', { className: 'iwb-section-title' }, '外观'),
el(A.AppearanceTab, { draft, setDraft, theme, setTheme, applyTheme }),
)
})()
const generalTab = Sections ? Sections.renderGeneralTab({
imageLibSection: imageLibSection,
appVersion: APP_VERSION,
@@ -546,11 +555,12 @@ function SettingsModal(props) {
BackupModalComp
? el(BackupModalComp, { embedded: true, onClose: props.onClose, onSaveNow: props.onSaveNow })
: el('div', { className: 'iwb-hint' }, '备份组件未就绪(请刷新页面)'),
autoBackupSection,
// 桌面版没有这套「localStorage 快照」:真实数据在资料目录,快照价值近零 ⇒ 只在网页版显示
isDesk() ? null : autoBackupSection,
)
// 顺序:通用放最前(最常用:目录/外观/图片图库/生成),其它按使用频率排
const tabs = [['general', '通用'], ['gen', '生图服务'], ['llm', 'LLM 服务'], ['img', '图片传输'], ['sizes', '尺寸预设'], ['hotkeys', '快捷键'], ['backup', '备份与还原'], ['diag', '诊断'], ['plugins', '插件']]
const tabs = [['general', '通用'], ['appearance', '外观'], ['gen', '生图服务'], ['llm', 'LLM 服务'], ['img', '图片传输'], ['sizes', '尺寸预设'], ['hotkeys', '快捷键'], ['backup', '备份与还原'], ['diag', '诊断'], ['plugins', '插件']]
return el('div', { className: 'iwb-modal-mask', onWheel: (e) => e.stopPropagation(), onPointerDown: (e) => { if (e.target === e.currentTarget) props.onClose() } },
el('div', { className: 'iwb-modal iwb-settings-modal' },
el('div', { className: 'iwb-modal-head' },
@@ -569,7 +579,7 @@ function SettingsModal(props) {
pluginItems.filter((p) => p && p.enabled).map((p) => el('button', { key: 'nav-plugin:' + p.id, className: 'iwb-tab iwb-set-nav-item' + (tab === 'plugin:' + p.id ? ' iwb-tab-active' : ''), onClick: () => setTab('plugin:' + p.id) }, I('star'), el('span', null, p.name))),
),
el('div', { className: 'iwb-modal-body' },
tab === 'gen' ? genTab : tab === 'llm' ? llmTab : tab === 'img' ? imgTab : tab === 'backup' ? backupTab : tab === 'hotkeys' ? hotkeyTab : tab === 'sizes' ? sizePresetTab : tab === 'plugins' ? pluginsTab : (typeof tab === 'string' && tab.indexOf('plugin:') === 0) ? pluginSettingsPage : tab === 'diag' ? diagTab : generalTab,
tab === 'appearance' ? appearanceTab : tab === 'gen' ? genTab : tab === 'llm' ? llmTab : tab === 'img' ? imgTab : tab === 'backup' ? backupTab : tab === 'hotkeys' ? hotkeyTab : tab === 'sizes' ? sizePresetTab : tab === 'plugins' ? pluginsTab : (typeof tab === 'string' && tab.indexOf('plugin:') === 0) ? pluginSettingsPage : tab === 'diag' ? diagTab : generalTab,
msg ? el('div', { className: 'iwb-status-' + (msg.type === 'err' ? 'err' : 'ok') }, msg.text) : null,
),
),
+20 -18
View File
@@ -544,7 +544,8 @@
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
const enabled = !!(D && D.isTauri && D.isTauri())
const [dir, setDir] = React.useState(() => (enabled ? D.getDownloadDir() : ''))
const [silent, setSilent] = React.useState(() => (enabled ? !!D.getSilentSave() : false))
// 自动下载(v3.25.20):勾选 = 出图完成自动存到本目录;未勾 = 点「下载」时存(有目录就不弹框)
const [autoDl, setAutoDl] = React.useState(() => (enabled && D.getAutoDownload ? !!D.getAutoDownload() : false))
const [note, setNote] = React.useState('')
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
const [dataDir, setDataDir] = React.useState(() => (F && F.dir ? F.dir() : ''))
@@ -553,8 +554,8 @@
try { const d = await D.pickDownloadDir(); if (d) { setDir(d); setNote('已保存') } else setNote('已取消') }
catch (e) { setNote('失败:' + String((e && e.message) || e)) }
}
const clear = () => { try { D.setDownloadDir('') } catch (e) { /* ignore */ } setDir(''); setSilent(false); try { D.setSilentSave(false) } catch (e) { /* ignore */ } setNote('已清除,恢复为跟随系统') }
const toggleSilent = (v) => { setSilent(v); try { D.setSilentSave(v) } catch (e) { /* ignore */ } setNote(v ? '已开启:批量保存不再逐个弹框' : '已关闭:每次保存都弹另存为对话框') }
const clear = () => { try { D.setDownloadDir('') } catch (e) { /* ignore */ } setDir(''); setAutoDl(false); try { if (D.setAutoDownload) D.setAutoDownload(false) } catch (e) { /* ignore */ } setNote('已清除,恢复为跟随系统') }
const toggleAutoDl = (v) => { setAutoDl(v); try { if (D.setAutoDownload) D.setAutoDownload(v) } catch (e) { /* ignore */ } setNote(v ? '已开启:出图完成后自动保存到该目录' : '已关闭:出图后不自动保存,点「下载」时才落盘') }
const pickDataDir = async () => {
try {
const d = await F.pickDir()
@@ -594,9 +595,16 @@
const rDry = await F.gcImages({ dryRun: true })
if (!rDry.ok) { setNote('检查失败:' + rDry.error); return }
if (!rDry.orphans) { setNote('没有未引用的图片'); return }
if (!(await askConfirm('发现 ' + rDry.orphans + ' 个文件没有被画布/图库引用。移动到 trash/(不直接删除)?', { title: '清理未引用图片', okText: '移动' }))) return
// 确认弹窗必须把「会不会动到在用的图」讲清楚:这是破坏性动作,不能只报一个数字。
const lines = ['发现 ' + rDry.orphans + ' 个文件没有被画布/图库引用。']
if (rDry.keptByCanvas) lines.push('其中 ' + rDry.keptByCanvas + ' 张虽然登记表里没有,但画布仍在引用 → 会自动保留。')
if (rDry.dangling) lines.push('另有 ' + rDry.dangling + ' 处画布引用已经找不到图片(之前丢的,本次不影响它们)。')
lines.push('移动到 trash/(不直接删除,可在回收站找回)?')
if (!(await askConfirm(lines.join('\n'), { title: '清理未引用图片', okText: '移动' }))) return
const rGo = await F.gcImages({ dryRun: false })
setNote(rGo.ok ? ('已移入 trash/:' + rGo.moved + ' 个文件') : ('清理失败:' + rGo.error))
setNote(rGo.ok
? ('已移入 trash/:' + rGo.moved + ' 个文件' + (rGo.dangling ? (';另有 ' + rGo.dangling + ' 处引用已缺图') : ''))
: ('清理失败:' + rGo.error))
} catch (e) { setNote('清理失败:' + String((e && e.message) || e)) }
} }, '清理未引用图片'),
),
@@ -606,10 +614,11 @@
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: pick }, '选择…'),
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: clear }, '清除'),
),
el('label', { className: 'iwb-check', title: dir ? '' : '需先选择默认下载文件夹' },
el('input', { type: 'checkbox', checked: silent, disabled: !dir, onChange: (e) => toggleSilent(e.target.checked) }, null),
' 启用(点「下载」直接写进这里,不弹窗)'),
el('div', { className: 'iwb-hint' }, '只是成品出口:下载/导出时写到这里,和数据库里的图不是同一份;关闭则每次弹另存为。'),
el('label', { className: 'iwb-check', title: dir ? '勾选后出图完成自动保存到上面的目录' : '需先选择导出目录才能开启自动下载' },
el('input', { type: 'checkbox', checked: autoDl, disabled: !dir, onChange: (e) => toggleAutoDl(e.target.checked) }, null),
' 自动下载'),
el('div', { className: 'iwb-hint' }, '设了目录:点「下载」直接存到这里,不弹框;没设目录:点「下载」时弹选择框。'),
el('div', { className: 'iwb-hint' }, '勾选「自动下载」:出图完成后自动保存到上面的目录(需先选目录)。'),
note ? el('div', { className: 'iwb-hint' }, note) : null,
)
}
@@ -634,19 +643,12 @@
}
function renderGeneralTab (ctx) {
const { TASK_STALL_END_MAX, TASK_STALL_END_MIN, appVersion, applyTheme, draft, imageLibSection, setDraft, setTheme, theme } = ctx
const { TASK_STALL_END_MAX, TASK_STALL_END_MIN, appVersion, draft, imageLibSection, setDraft } = ctx
const generalTab = el('div', { className: 'iwb-section' },
el('div', { className: 'iwb-section-title' }, '数据与目录'),
// 桌面端才有目录概念;网页版退回原来的浏览器说明
isDesk() ? el(DownloadDirBlock, null) : el(DataDirRow, null),
el('div', { style: { height: 16 } }),
el('div', { className: 'iwb-section-sub' }, '外观'),
el('select', { className: 'iwb-input', title: '界面配色(亮色保证文字清晰)', value: theme, onChange: (e) => { const t = e.target.value; const v = (t === 'dark' || t === 'system') ? t : 'light'; setTheme(v); applyTheme(v) } },
el('option', { value: 'light' }, '亮色(默认:节点灰底 + 内容白)'),
el('option', { value: 'dark' }, '暗色'),
el('option', { value: 'system' }, '跟随系统'),
),
el('div', { style: { height: 16 } }),
el('div', { className: 'iwb-section-sub' }, '生成'),
el('div', { className: 'iwb-row' },
el('label', { className: 'iwb-label' }, '等待多久后允许提前结束(分钟)'),
@@ -1122,7 +1124,7 @@
defaultInstruction: draft.llm.defaultInstruction || '',
},
security: { password: draft.sec.clear ? '__CLEAR__' : ((draft.sec.password && draft.sec.password.trim()) || (draft.sec.hasPassword ? '__KEEP__' : '')) },
canvas: { hotkeys: Object.assign({}, HOTKEY_DEFAULTS, draft.canvas.hotkeys || {}), sizePresets: Array.isArray(draft.canvas.sizePresets) && draft.canvas.sizePresets.length ? draft.canvas.sizePresets : RATIOS, generationConcurrency: Math.max(GEN_CONCURRENCY_MIN, Math.min(GEN_CONCURRENCY_MAX, Number(draft.canvas.generationConcurrency) || GEN_CONCURRENCY_DEFAULT)), taskStallEndMs: Math.max(TASK_STALL_END_MIN, Math.min(TASK_STALL_END_MAX, Number(draft.canvas.taskStallEndMs) || 300000)), autoSaveImages: draft.canvas.autoSaveImages !== false, backupOriginals: draft.canvas.backupOriginals !== false },
canvas: { hotkeys: Object.assign({}, HOTKEY_DEFAULTS, draft.canvas.hotkeys || {}), appearance: (function () { const A = (typeof window !== 'undefined') ? window.IWBUIApearance : null; return A ? A.normalize(draft) : ((draft.canvas && draft.canvas.appearance) || {}) })(), sizePresets: Array.isArray(draft.canvas.sizePresets) && draft.canvas.sizePresets.length ? draft.canvas.sizePresets : RATIOS, generationConcurrency: Math.max(GEN_CONCURRENCY_MIN, Math.min(GEN_CONCURRENCY_MAX, Number(draft.canvas.generationConcurrency) || GEN_CONCURRENCY_DEFAULT)), taskStallEndMs: Math.max(TASK_STALL_END_MIN, Math.min(TASK_STALL_END_MAX, Number(draft.canvas.taskStallEndMs) || 300000)), autoSaveImages: draft.canvas.autoSaveImages !== false, backupOriginals: draft.canvas.backupOriginals !== false },
webhook: { enabled: !!draft.webhook.enabled, url: (draft.webhook.url || '').trim() },
})
setSaving(false)
+35 -2
View File
@@ -21,6 +21,8 @@
--iwb-border: #d5d9e0;
--iwb-border2: #b9bfca;
--iwb-brand: #6b7280; /* v3.1.0 全灰阶:原品牌蓝 → 同亮度中性灰(白字对比仍 ≥4.5:1) */
/* 连线默认色:跟随边框灰(亮/暗自适应)。主题色只用于选中/悬停/上下游高亮(v3.25.18 用户裁定) */
--iwb-edge: var(--iwb-border2);
--iwb-text: #1c2333;
--iwb-text2: #4d5668;
--iwb-err: #e5484d;
@@ -99,7 +101,7 @@ button { font-family: inherit; }
.iwb-edge-hit { fill: none; stroke: transparent; stroke-width: 14; pointer-events: stroke; cursor: pointer; }
.iwb-edge-hit:hover { stroke: color-mix(in srgb, var(--iwb-brand) 16%, transparent); }
.iwb-edge-hit:hover + .iwb-edge { stroke-width: 2.4; stroke: var(--iwb-brand); }
.iwb-edge { fill: none; stroke: color-mix(in srgb, var(--iwb-text2) 42%, transparent); stroke-width: 1.8; stroke-dasharray: 4 3; pointer-events: stroke; cursor: pointer; }
.iwb-edge { fill: none; stroke: var(--iwb-edge); stroke-width: 1.8; stroke-dasharray: 4 3; pointer-events: stroke; cursor: pointer; }
.iwb-edge:hover { stroke: var(--iwb-brand); stroke-dasharray: none; }
.iwb-edge-sel { stroke: var(--iwb-warn); stroke-width: 2.4; stroke-dasharray: none; }
.iwb-edge-hot { stroke: var(--iwb-brand); stroke-width: 2.4; stroke-dasharray: none; }
@@ -2047,4 +2049,35 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
.iwb-settings-modal .iwb-modelrow { padding: 2px 8px; border-radius: 999px; background: var(--iwb-layer2); border: 1px solid transparent; margin: 0; font-size: 12.5px; }
.iwb-settings-modal .iwb-modelrow-active { border-color: #6b5ce7; background: rgba(107,92,231,.08); }
.iwb-settings-modal .iwb-llm-card .iwb-btn-xs { opacity: .5; }
.iwb-settings-modal .iwb-llm-card .iwb-btn-xs:hover { opacity: 1; }
.iwb-settings-modal .iwb-llm-card .iwb-btn-xs:hover { opacity: 1; }
/* ── 外观:取色器(v3.25.14,仿 Obsidian 的取色面板) ───────────────── */
.iwb-cpick { position: relative; display: inline-flex; align-items: center; gap: 8px; }
.iwb-cpick-swatch { display: inline-flex; align-items: center; justify-content: center; min-width: 92px; height: 28px; padding: 0 10px; border-radius: 6px; border: 1px solid var(--iwb-border); cursor: pointer; font-size: 11px; letter-spacing: .04em; }
.iwb-cpick-swatch:hover { border-color: var(--iwb-border2); }
.iwb-cpick-hex { mix-blend-mode: difference; }
.iwb-cpick-pop { position: absolute; z-index: 80; top: calc(100% + 8px); left: 0; width: 236px; padding: 10px; border-radius: 10px; background: var(--iwb-panel); border: 1px solid var(--iwb-border); box-shadow: var(--sh-md); }
.iwb-cpick-box { position: relative; height: 132px; border-radius: 6px; cursor: crosshair; }
.iwb-cpick-dot { position: absolute; width: 12px; height: 12px; margin: -6px 0 0 -6px; border-radius: 50%; border: 2px solid #fff; box-shadow: 0 0 0 1px rgba(0,0,0,.4); pointer-events: none; }
.iwb-cpick-hue { width: 100%; height: 12px; margin: 10px 0 8px; border-radius: 6px; -webkit-appearance: none; appearance: none; }
.iwb-cpick-hue::-webkit-slider-thumb { -webkit-appearance: none; width: 14px; height: 14px; border-radius: 50%; background: #fff; border: 2px solid rgba(0,0,0,.45); cursor: pointer; }
.iwb-cpick-rgb { display: flex; gap: 6px; }
.iwb-cpick-chan { flex: 1 1 0; display: flex; flex-direction: column; align-items: center; gap: 2px; font-size: 10px; color: var(--iwb-text2); }
.iwb-cpick-chan input { width: 100%; height: 26px; padding: 0 4px; text-align: center; border-radius: 5px; border: 1px solid var(--iwb-border); background: var(--iwb-layer2); color: var(--iwb-text); font-size: 11px; }
.iwb-cpick-foot { display: flex; gap: 6px; align-items: center; margin-top: 8px; }
/* 十六进制输入框可缩到 0(min-width:0 才能被 flex 压窄),「完成」按钮固定不换行 */
.iwb-cpick-input { flex: 1 1 0; min-width: 0; width: auto; height: 26px; font-size: 11px; }
.iwb-cpick-foot .iwb-btn { flex: 0 0 auto; white-space: nowrap; padding: 0 10px; }
.iwb-hint-warn { color: var(--iwb-warn); }
/* 紧凑下拉(v3.25.19):图库顶部的时间/插入尺寸选择器,省横向空间 */
.iwb-select-compact {
width: auto;
min-width: 62px;
max-width: 84px;
padding-left: 6px;
padding-right: 4px;
font-size: var(--fs-sm);
background-position: right 2px center;
}
.iwb-history-head { flex-wrap: nowrap; gap: 6px; }
.iwb-history-head .iwb-btn-sm { padding-left: 6px; padding-right: 6px; }
+47
View File
@@ -0,0 +1,47 @@
/* desktop-csp-loopback-test.js —— 桌面客户端 CSP 必须放行本地服务插件(v3.25.14)
*
* 背景:v3.25.11 的「CSP 清理」把 30092 当成遗留端口删掉了,但它其实是
* 2026-10-17 有意为「本地服务插件」放宽的安全边界。删掉后桌面版鲜艺抠图插件报
* 「Failed to fetch」。
*
* ⚠️ 这个项目现在是**桌面客户端**:CSP 的唯一真相是 src-tauri/tauri.conf.json。
* 不参照任何网页部署配置 —— 那是别的产品,耦合只会制造假失败。
*
* ⚠️ 写法约束(tests/source-text-ratchet-test.js 的零余量棘轮):
* 不要读文件原文再 .includes/.indexOf(变量名命中 source|src|app53… 会被计数)。
* 这里只做**解析后运行时值**的断言。
*/
'use strict'
const fs = require('node:fs')
const path = require('node:path')
const assert = require('node:assert')
const conf = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'src-tauri', 'tauri.conf.json'), 'utf8'))
const policy = String((conf.app && conf.app.security && conf.app.security.csp) || '')
assert.ok(policy.length > 0, '桌面版必须显式声明 CSP(不允许留空回落默认)')
const directives = Object.fromEntries(policy.split(';').map((part) => {
const bits = part.trim().split(/\s+/).filter(Boolean)
return bits.length ? [bits[0], bits.slice(1)] : ['', []]
}))
const connect = directives['connect-src'] || []
assert.ok(connect.length > 0, 'connect-src 不能为空')
// 30092 = 本地鲜艺抠图服务(XianyiAiRmbg)。两个 loopback 写法都要在:
// 插件默认 http://localhost:30092,用户改成 127.0.0.1 也必须能用。
for (const origin of ['http://127.0.0.1:30092', 'http://localhost:30092']) {
assert.ok(connect.includes(origin), '桌面 CSP 的 connect-src 必须放行 ' + origin + '(本地抠图插件依赖)')
}
// 守卫的守卫:确认没有顺手把整个 http: 放开
assert.ok(!connect.includes('http:'), 'connect-src 不得放开整个 http: 协议(只放行具体 loopback 源)')
// 只允许 loopback 例外:桌面 CSP 里出现非 loopback 的 http 源视为放宽过度
// http://ipc.localhost 是 Tauri 自己的 IPC 通道,属于必需项;其余 http 源只允许 loopback
const ALLOWED_HTTP = new Set(['http://ipc.localhost'])
const plainHttp = connect.filter((v) => /^http:\/\//.test(v) && !ALLOWED_HTTP.has(v) && !/^http:\/\/(127\.0\.0\.1|localhost):\d+$/.test(v))
assert.deepStrictEqual(plainHttp, [], '除 loopback 外不得出现其它 http 源:' + plainHttp.join(', '))
console.log('desktop-csp-loopback: 5 通过 / 0 失败')
+3
View File
@@ -61,6 +61,9 @@
"generation-results-store.js",
"ui-groups-sidebar.js",
"ui-lib-sidebar.js",
"ui-desktop-shell.js",
"ui-appearance.js",
"runtime-download-auto.js",
"ui-workspace-tabs.js",
"ui-app-chrome.js",
"ui-workbench-hooks.js",
-154
View File
@@ -1,154 +0,0 @@
'use strict'
// functions/api/*.js 的行为测试(此前这两个 Pages 函数无任何自动化测试)。
// 用 Node 全局 Request/Response 调用 onRequest,并 mock 全局 fetch。
const assert = require('assert')
const path = require('path')
const calls = []
function setFetch(handler) {
globalThis.fetch = async (url, init) => {
const u = String(url)
calls.push({ url: u, init: init || {} })
return handler(u, init || {})
}
}
const req = (method, url, headers, body) => new Request(url, { method, headers: headers || {}, body })
const jsonReq = (url, payload, headers) => req('POST', url, Object.assign({ 'Content-Type': 'application/json' }, headers || {}), JSON.stringify(payload))
const noAcao = (res) => assert.strictEqual(res.headers.get('access-control-allow-origin'), null, '不应再有 CORS *')
;(async () => {
const img = await import(path.join(__dirname, '..', 'functions', 'api', 'img.js'))
// ---------- img.js ----------
const IMG = 'https://d1.cloudfront.net/a.png'
const okImg = () => new Response('PNGDATA', { status: 200, headers: { 'Content-Type': 'image/png' } })
const imgUrl = (host, p) => 'https://site.example/api/img?url=' + encodeURIComponent('https://' + host + (p || '/a.png'))
// 1) 非 https 400
setFetch(okImg)
let r = await img.onRequest({ request: req('GET', 'https://site.example/api/img?url=' + encodeURIComponent('http://d1.cloudfront.net/a.png')) })
assert.strictEqual(r.status, 400, 'img: http 应 400')
// 2) 非白名单 host 403
setFetch(okImg)
r = await img.onRequest({ request: req('GET', imgUrl('evil.example')) })
assert.strictEqual(r.status, 403, 'img: 非白名单 host 应 403')
// 3) 跨域 Origin 403
setFetch(okImg)
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net'), { Origin: 'https://evil.example' }) })
assert.strictEqual(r.status, 403, 'img: 跨域 Origin 应 403')
// 4) 直连白名单 host 放行,无 CORS *,透传 image/*
setFetch(okImg)
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
assert.strictEqual(r.status, 200, 'img: 白名单 host 应 200')
assert.strictEqual(r.headers.get('content-type'), 'image/png', 'img: 应透传 image/png')
noAcao(r)
// 5) 重定向到非白名单 host 403(手动跟随并复检)
calls.length = 0
setFetch((u) => u.indexOf('d1.cloudfront.net') >= 0
? new Response(null, { status: 302, headers: { Location: 'https://evil.example/x.png' } })
: okImg())
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
assert.strictEqual(r.status, 403, 'img: 重定向到非白名单应 403')
// 6) 重定向到白名单 host 应跟随成功
calls.length = 0
setFetch((u) => u.indexOf('d1.cloudfront.net') >= 0
? new Response(null, { status: 302, headers: { Location: 'https://other.aliyuncs.com/b.png' } })
: okImg())
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
assert.strictEqual(r.status, 200, 'img: 重定向到白名单 host 应跟随 200')
assert.strictEqual(calls.length, 2, 'img: 应发生两跳请求')
// 7) 无 Location 的重定向 502
setFetch(() => new Response(null, { status: 302 }))
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
assert.strictEqual(r.status, 502, 'img: 重定向缺 Location 应 502')
// 8) content-length 超限 413
setFetch(() => new Response(null, { status: 200, headers: { 'Content-Type': 'image/png', 'Content-Length': '99999999' } }))
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
assert.strictEqual(r.status, 413, 'img: 超大 content-length 应 413')
// 9) 非图片 content-type 415
setFetch(() => new Response('{"a":1}', { status: 200, headers: { 'Content-Type': 'application/json' } }))
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
assert.strictEqual(r.status, 415, 'img: 非图片应 415')
// 10) 安全头:Cloudflare Pages 的 `_headers` **不作用于 Functions 响应**
// ⇒ 每个 Response 必须自带 nosniff + Referrer-Policy(否则未来某端点漏设 Content-Type
// 时浏览器会自行嗅探类型 → 可能演变成 XSS)。这是 H1 的回归守卫。
const hasSecurityHeaders = (res, who) => {
assert.strictEqual(res.headers.get('x-content-type-options'), 'nosniff', who + ': 应有 X-Content-Type-Options: nosniff')
assert.strictEqual(res.headers.get('referrer-policy'), 'no-referrer', who + ': 应有 Referrer-Policy: no-referrer')
}
setFetch(okImg)
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
assert.strictEqual(r.status, 200, 'img: 正常取图应 200')
hasSecurityHeaders(r, 'img 成功响应')
r = await img.onRequest({ request: req('GET', imgUrl('evil.example')) })
hasSecurityHeaders(r, 'img 403 响应')
r = await img.onRequest({ request: req('GET', 'https://site.example/api/img?url=' + encodeURIComponent('http://d1.cloudfront.net/a.png')) })
hasSecurityHeaders(r, 'img 400 响应')
// ---------- plugins/[[path]].js ----------
const pluginsFn = await import(path.join(__dirname, '..', 'functions', 'plugins', '[[path]].js'))
const pluginCtx = (tail, value, headers) => ({
params: { path: [tail] },
env: value === undefined ? {} : { PLUGINS: { get: async () => value } },
request: req('GET', 'https://site.example/plugins/' + tail, headers || {}),
})
// P1) 带内容哈希的 JS 名 → immutable + max-age=31536000
let pr = await pluginsFn.onRequestGet(pluginCtx('plugin-xianyi-cutout.0123456789ab.js', 'console.log(1)'))
assert.strictEqual(pr.status, 200, 'plugins: 带哈希 JS 应 200')
assert.strictEqual(pr.headers.get('content-type'), 'application/javascript; charset=utf-8', 'plugins: 带哈希 JS 应为 application/javascript')
assert.ok((pr.headers.get('cache-control') || '').indexOf('immutable') >= 0, 'plugins: 带哈希 JS 应含 immutable')
assert.ok((pr.headers.get('cache-control') || '').indexOf('max-age=31536000') >= 0, 'plugins: 带哈希 JS 应含 max-age=31536000')
// P2) 未哈希的 JS 名 → no-cache + 非空 etag(安全网,绝不许永久缓存)
pr = await pluginsFn.onRequestGet(pluginCtx('plugin-xianyi-cutout.js', 'console.log(1)'))
assert.strictEqual(pr.headers.get('cache-control'), 'no-cache', 'plugins: 未哈希 JS 应 no-cache')
assert.ok(pr.headers.get('etag'), 'plugins: 未哈希 JS 应有非空 etag')
// P3) index.json → no-cache + 非空 etag,body 等于 KV 里的值
const manifest = '[{"id":"xianyi-cutout"}]'
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', manifest))
assert.strictEqual(pr.headers.get('content-type'), 'application/json; charset=utf-8', 'plugins: index.json 应为 application/json')
assert.strictEqual(pr.headers.get('cache-control'), 'no-cache', 'plugins: index.json 应 no-cache')
const manifestEtag = pr.headers.get('etag')
assert.ok(manifestEtag, 'plugins: index.json 应有非空 etag')
assert.strictEqual(await pr.text(), manifest, 'plugins: index.json body 应等于存储值')
// P4) if-none-match 命中 → 304 + 空 body + 同 etag
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', manifest, { 'if-none-match': manifestEtag }))
assert.strictEqual(pr.status, 304, 'plugins: if-none-match 命中应 304')
assert.strictEqual(await pr.text(), '', 'plugins: 304 应为空 body')
assert.strictEqual(pr.headers.get('etag'), manifestEtag, 'plugins: 304 应带相同 etag')
// P5) 缺 KV 绑定 → 500
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', undefined))
assert.strictEqual(pr.status, 500, 'plugins: 缺 PLUGINS 绑定应 500')
// P6) 未知键(KV 返回 null)→ 404 + no-store
pr = await pluginsFn.onRequestGet(pluginCtx('plugin-nope.js', null))
assert.strictEqual(pr.status, 404, 'plugins: 未知键应 404')
assert.strictEqual(pr.headers.get('cache-control'), 'no-store', 'plugins: 404 应 no-store')
// P7) 安全头:`_headers` 不作用于 Functions 响应 ⇒ 每个 Response 自带 nosniff + Referrer-Policy
pr = await pluginsFn.onRequestGet(pluginCtx('plugin-xianyi-cutout.0123456789ab.js', 'console.log(1)'))
hasSecurityHeaders(pr, 'plugins 200 响应')
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', manifest))
hasSecurityHeaders(pr, 'plugins 清单 200 响应')
pr = await pluginsFn.onRequestGet(pluginCtx('plugin-nope.js', null))
hasSecurityHeaders(pr, 'plugins 404 响应')
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', undefined))
hasSecurityHeaders(pr, 'plugins 500 响应')
console.log('functions api tests passed')
})().catch((e) => { console.error(e); process.exit(1) })
-210
View File
@@ -1,210 +0,0 @@
// v3.86.10 CSP 门禁:本地 e2e 通过 scripts/serve-test.js 下发 _headers 里的 CSP,
// 凡是依赖「被 CSP 禁止的能力」的实现都会在这里直接失败:
// ① fetch(data:...) / fetch(blob:...)(connect-src 'self' https:)
// ② 动态插 <script src="https://cdn...">(script-src 'self')
// ③ 内联脚本 / eval / new Function(script-src 'self',无 unsafe-eval)
// 覆盖两条真实用户链路:图库预览复制(blob: 源)+ 大图入库压缩(Worker + data: 解码)。
// 任一 Console 出现 "Content Security Policy" 违规即视为失败——这是本 spec 的核心断言。
const { test, expect } = require('./_pw-coverage')
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
test.use({ baseURL, viewport: { width: 1440, height: 1000 }, permissions: ['clipboard-read', 'clipboard-write'] })
// 大图 fixture 的尺寸:**唯一来源**。canvas 生成 / outputs 声明 / 复制后断言全部引用它,
// 避免"改了 fixture 却忘了改断言"这类硬编码漂移(2026-10-28 就是这么挂了一次)。
const FIXTURE_W = 1100
const FIXTURE_H = 800
const CFG = {
providers: [],
outputsRetention: { enabled: true, maxFiles: 500, maxDays: 15 },
canvas: { snap: true, backupOriginals: true },
image: { compress: { enabled: true, maxMB: 0.01, maxEdge: 1024, quality: 0.7 } },
}
const WS = {
workspaces: [{
id: 'ws_csp', name: 'CSP',
nodes: [
{ id: 'ra', type: 'ref', x: 80, y: 120, data: { url: '', data: null, name: '', localName: null } },
{ id: 'p1', type: 'prompt', x: 620, y: 120, data: { text: '提示词', title: 'P1' } },
],
edges: [], groups: [],
}],
activeId: 'ws_csp', rev: 1,
}
// 大图 fixture:同时满足两个硬约束 ——
// ① **尺寸必须真的超阈值**:CFG 里 maxMB=0.01(≈10KB)⇒ 任何 >13KB 的 base64 都会走压缩链路,
// 所以不需要"约 1MB"那么大;
// ② **必须装得进 localStorage**:outputs 里 url 与 data 各存一份 dataURL(约 2 倍体积),
// 而 localStorage 每 origin 约 5MB。
//
// ⚠️ 2026-10-28 实测踩坑(playwright 1.52→1.64.1 / Chromium 1169→1248,Chrome 156):
// 同一段代码 `toDataURL('image/png')` 的输出**随浏览器版本变化**——旧版本 1600×1200 约 1MB,
// 新版本同样尺寸变成 **2.81MB**(近似未压缩),双份 JSON = **5.63MB ⇒ 超配额**,
// `setItem` 抛 QuotaExceededError ⇒ 整个 addInitScript 后续语句不执行 ⇒ 图库恒为 0/0 ⇒ 测试假失败。
// 现在改为 1100×800(实测 dataURL 1.27MB / JSON 2.53MB,配额安全),
// 且长边 1100 > maxEdge 1024 ⇒ 仍会触发缩放,test 2 的「压缩+缩放」语义不变。
async function bigPngDataUrl(page) {
return page.evaluate(([W, H]) => {
const c = document.createElement('canvas')
c.width = W; c.height = H
const x = c.getContext('2d')
const g = x.createLinearGradient(0, 0, W, H)
g.addColorStop(0, '#2f6bff'); g.addColorStop(0.5, '#e2453c'); g.addColorStop(1, '#16a34a')
x.fillStyle = g; x.fillRect(0, 0, W, H)
for (let i = 0; i < 600; i++) x.fillRect((i * 37) % W, (i * 53) % H, 3, 3)
return c.toDataURL('image/png')
}, [FIXTURE_W, FIXTURE_H])
}
async function boot(page, outputs) {
await page.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
localStorage.setItem('iwb_web_workspaces', JSON.stringify(d.ws))
localStorage.setItem('iwb_ws_active', d.ws.activeId)
localStorage.setItem('iwb_ws_' + d.ws.activeId, JSON.stringify(d.ws.workspaces[0]))
localStorage.setItem('iwb_web_outputs', JSON.stringify(d.outputs))
localStorage.setItem('iwb_e2e_initialized', '1')
// 配额探测:setItem 抛错会让**后续语句全部不执行**(图库恒空、__IWB_E2E__ 也不设),
// 表现为「元素找不到」这种极难定位的假失败。这里把实际写入长度记到 window 上,
// 由 Node 侧 goto 之后立刻校验并抛出**可读**的错误(在 initScript 里 throw 不会中止测试)。
let wrote = -1
try { wrote = (localStorage.getItem('iwb_web_outputs') || '').length } catch (e) { wrote = -1 }
window.__IWB_FIXTURE_OUTPUTS_LEN__ = wrote
// e2e 探针:暴露压缩 / 存缩略图两个最小入口(生产不设置该标志)
window.__IWB_E2E__ = true
}, { cfg: CFG, ws: WS, outputs })
await page.goto('/', { waitUntil: 'domcontentloaded' })
// ── 配额守卫(Node 侧)─────────────────────────────────────────────
// 为什么不在 initScript 里 throw:那里抛出的异常不会中止测试,
// 只会让后续步骤连锁失败成「元素找不到」,根本看不出真正原因(2026-10-28 实测过)。
{
const expectLen = JSON.stringify(outputs).length
// undefined = initScript 在写 outputs 那一步就抛了(配额不足),后续赋值没执行
const actualLen = await page.evaluate(() => window.__IWB_FIXTURE_OUTPUTS_LEN__ ?? 0)
if (actualLen !== expectLen) {
throw new Error(
'[e2e fixture] localStorage 写入不完整,多半是配额不足(每 origin 约 5MB)\n'
+ ' 期望 iwb_web_outputs = ' + expectLen + ' 字符,实际 ' + actualLen + '\n'
+ ' 注意:本 fixture 把同一个 dataURL 存了 url + data 两份(约 2 倍体积)。\n'
+ ' toDataURL 的输出大小**随浏览器版本变化** —— 缩小 FIXTURE_W/FIXTURE_H 即可。')
}
}
await page.waitForTimeout(700)
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
await page.waitForTimeout(400)
}
// 收集 CSP 违规(Console 原文里带 "Content Security Policy")+ 页面异常
function watchCsp(page) {
const csp = []
const errors = []
page.on('console', (m) => { const t = m.text() || ''; if (/Content Security Policy/i.test(t) || /Refused to (connect|load|create)/i.test(t)) csp.push(t) })
page.on('pageerror', (e) => errors.push(String((e && e.message) || e)))
return { csp, errors }
}
// IndexedDB 里按 key 前缀取内容(图库缩略图 = out_<name>)
async function idbGet(page, key) {
return page.evaluate((k) => new Promise((resolve) => {
const req = indexedDB.open('iwb_web')
req.onerror = () => resolve(null)
req.onsuccess = () => {
const db = req.result
let tx
try { tx = db.transaction('images', 'readonly') } catch (e) { try { db.close() } catch (e2) {} return resolve(null) }
const gr = tx.objectStore('images').get(k)
gr.onerror = () => resolve(null)
gr.onsuccess = () => { try { db.close() } catch (e) {} resolve(gr.result == null ? null : String(gr.result)) }
}
req.onupgradeneeded = () => { try { req.result.close() } catch (e) {} resolve(null) }
}), key)
}
async function idbKeys(page) {
return page.evaluate(() => new Promise((resolve) => {
const req = indexedDB.open('iwb_web')
req.onerror = () => resolve([])
req.onsuccess = () => {
const db = req.result
let tx
try { tx = db.transaction('images', 'readonly') } catch (e) { try { db.close() } catch (e2) {} return resolve([]) }
const kr = tx.objectStore('images').getAllKeys()
kr.onerror = () => resolve([])
kr.onsuccess = () => { try { db.close() } catch (e) {} resolve((kr.result || []).map(String)) }
}
req.onupgradeneeded = () => { try { req.result.close() } catch (e) {} resolve([]) }
}))
}
test('1. 图库预览复制:blob: 源在 CSP 下必须成功(fetch(blob:) 已被 connect-src 拦)', async ({ page }) => {
const urls = { png: await bigPngDataUrl(page) }
const w = watchCsp(page)
await boot(page, [{ name: 'csp_png.png', url: urls.png, data: urls.png, size: 900000, mtime: Date.now() - 1000, w: FIXTURE_W, h: FIXTURE_H }])
await page.locator('.iwb-top-nav-icon[title*="资源中心"]').click()
await expect(page.locator('.iwb-fullmask')).toBeVisible()
await page.locator('.iwb-fullmask .iwb-res-tab').filter({ hasText: '图库' }).click()
const thumb = page.locator('.iwb-history-item img[title^="csp_png.png"]')
await expect(thumb).toBeVisible()
await thumb.dblclick()
await expect(page.locator('.iwb-imgpreview')).toBeVisible()
// 预览把 dataURL 解析成 objectURL 后才可复制(复制源就是它)
await expect.poll(() => page.locator('.iwb-imgpreview img').getAttribute('src'), { timeout: 8000 }).toContain('blob:')
await page.locator('.iwb-imgpreview .iwb-prev-bar button', { hasText: '复制' }).click()
await expect(page.locator('.iwb-status-ok').filter({ hasText: '已复制图片到剪贴板' }), 'CSP 下 blob: 源复制必须成功').toBeVisible()
const clip = await page.evaluate(async () => {
const items = await navigator.clipboard.read()
const pngItem = items.find((it) => it.types.includes('image/png'))
if (!pngItem) return { types: items.map((it) => it.types.join('+')), ok: false }
const bmp = await createImageBitmap(await pngItem.getType('image/png'))
const out = { ok: true, type: 'image/png', w: bmp.width, h: bmp.height }
if (bmp.close) bmp.close()
return out
})
expect(clip.ok, JSON.stringify(clip)).toBe(true)
// 复制的必须是**原图全尺寸**,不是压缩后的缩略图
expect(clip.w).toBe(FIXTURE_W)
expect(clip.h).toBe(FIXTURE_H)
expect(w.csp, '不得出现 CSP 违规:\n' + w.csp.join('\n')).toEqual([])
expect(w.errors).toEqual([])
})
test('2. 大图入库压缩:CSP 下 Worker/解码/落库全链路必须产出压缩缩略图(out_)且无 CSP 违规', async ({ page }) => {
const bigPng = await bigPngDataUrl(page)
const w = watchCsp(page)
await boot(page, [])
// 走应用自己的 compressDataUrl(与保存/上传/缩略图完全同一条代码路径)
const compressed = await page.evaluate(async (png) => {
const t0 = Date.now()
const out = await window.__IWB_E2E__API__.compress(png, { maxEdge: 320, quality: 0.72, format: 'jpeg' })
return { out, ms: Date.now() - t0 }
}, bigPng)
expect(compressed.out && compressed.out.indexOf('data:image/jpeg') === 0, '压缩产物应是 JPEG dataURL').toBe(true)
expect(compressed.out.length).toBeLessThan(bigPng.length)
expect(await page.evaluate((d) => { const b = atob(d.split(',')[1]); return b.length > 200 }, compressed.out)).toBe(true)
// 压缩必须真的跑在 Worker 线程(worker-src 未放行时会退化成主线程,那正是线上卡顿的根因)
const used = await page.evaluate(() => window.__IWB_COMPRESS_LAST__)
expect(used, '大图压缩必须走 Worker(不得静默退化成主线程)').toBe('worker')
// 落库链路:storeOutputThumb → out_<name>(图库缩略图)+ out_orig_<name>(原图)
const stored = await page.evaluate(async (d) => {
return await window.__IWB_E2E__API__.thumb({ name: 'csp_probe.png', data: d, url: '' })
}, bigPng)
expect(stored, 'storeOutputThumb 应返回写入的原图 IDB key').toBe('out_orig_csp_probe.png')
const keys = await idbKeys(page)
expect(keys, 'IDB 里必须出现 out_ 压缩缩略图;实际 keys=' + JSON.stringify(keys)).toContain('out_csp_probe.png')
const thumb = await idbGet(page, 'out_csp_probe.png')
expect(String(thumb).indexOf('data:image/jpeg') === 0, '缩略图应是压缩后的 JPEG dataURL').toBe(true)
expect(String(thumb).length).toBeLessThan(bigPng.length)
expect(w.csp, '不得出现 CSP 违规:\n' + w.csp.join('\n')).toEqual([])
expect(w.errors).toEqual([])
})
-84
View File
@@ -1,84 +0,0 @@
// Pages Functions 安全头门禁(2026-10-20 加,审计 H1 的自动化护栏)。
//
// 背景(为什么会加):
// Cloudflare Pages 的 `_headers` **不作用于 Pages Functions 响应**
// (https://developers.cloudflare.com/pages/configuration/headers/)——
// 静态资源(app.js / style.css)有 CSP + nosniff,而 `/api/*` 与 `/plugins/*` 这两个
// Functions 此前**一个安全头都没有**。性质是**纵深防御缺口**(每个响应本就显式设了
// 安全的 Content-Type,不是可利用漏洞),但缺兜底意味着:将来新增端点时漏设
// Content-Type,浏览器会自行嗅探类型 ⇒ 可能演变成 XSS。
// 此前这两条路径**本地完全测不到**(serve-test.js 只服务 dist/ 静态资源),
// 「本地过、线上挂」这一类缺陷无法被 e2e 发现 ⇒ 补上本地 Functions 模拟 + 本用例。
//
// 本用例守三件事:
// ① 每个 Function 响应的**每个分支**都带 X-Content-Type-Options: nosniff + Referrer-Policy: no-referrer;
// ② Function 响应**不含** `_headers` 里的 CSP —— 显式钉死「本地与线上一致:_headers 不作用于 Function」;
// (这条最关键:若哪天本地"好心"给 Function 套上 CSP,线上差异就被掩盖了,② 会先红)
// ③ 静态资源**仍然**带 CSP —— 防止修 Functions 时误伤静态资源的既有防护。
//
// 依赖:scripts/serve-test.js 的本地 Functions 模拟(/api/* 与 /plugins/* 路由)。
// 该模拟**只透传 Function 自己的 header**,不叠加 _headers —— 与线上语义一致。
const { test, expect } = require('./_pw-coverage')
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
test.use({ baseURL, viewport: { width: 1280, height: 900 } })
// 断言某个响应带 Functions 必带的安全头
async function expectFunctionSecurityHeaders(res, who) {
const h = res.headers() // APIResponse.headers() 是同步的,返回小写 header 名映射
expect(h['x-content-type-options'], who + ' 应有 X-Content-Type-Options: nosniff').toBe('nosniff')
expect(h['referrer-policy'], who + ' 应有 Referrer-Policy: no-referrer').toBe('no-referrer')
}
test('Functions 响应带 nosniff + Referrer-Policy(且不含 _headers 的 CSP)', async ({ request }) => {
// ① /plugins/index.json(清单)
const manifest = await request.get('/plugins/index.json')
expect(manifest.status(), '/plugins/index.json 应 200').toBe(200)
await expectFunctionSecurityHeaders(manifest, '/plugins/index.json')
// ② /plugins/<内容寻址>.js(不可变缓存的插件字节)
const body = await manifest.text()
const file = (JSON.parse(body)[0] || {}).file
expect(file, '本地 mock 清单应含一个插件').toBeTruthy()
const pluginJs = await request.get('/plugins/' + file)
expect(pluginJs.status(), '/plugins/' + file + ' 应 200').toBe(200)
await expectFunctionSecurityHeaders(pluginJs, '/plugins/' + file)
// ③ /plugins 未知键 → 404 分支也必须带安全头
const missing = await request.get('/plugins/plugin-does-not-exist.js')
expect(missing.status(), '/plugins 未知键应 404').toBe(404)
await expectFunctionSecurityHeaders(missing, '/plugins 404')
// ④ /api/img 各分支:非白名单 host → 403
const forbidden = await request.get('/api/img?url=' + encodeURIComponent('https://evil.example/a.png'))
expect(forbidden.status(), '/api/img 非白名单 host 应 403').toBe(403)
await expectFunctionSecurityHeaders(forbidden, '/api/img 403')
// ⑤ /api/img 非 https → 400
const badProto = await request.get('/api/img?url=' + encodeURIComponent('http://d1.cloudfront.net/a.png'))
expect(badProto.status(), '/api/img 非 https 应 400').toBe(400)
await expectFunctionSecurityHeaders(badProto, '/api/img 400')
// ⑥ /api/img 成功分支(上游由 serve-test 本地 mock,不依赖外部图床)
const ok = await request.get('/api/img?url=' + encodeURIComponent('https://d1.cloudfront.net/a.png'))
expect(ok.status(), '/api/img 白名单 host 应 200').toBe(200)
await expectFunctionSecurityHeaders(ok, '/api/img 200')
// ② 反向断言:Function 响应**不含** CSP —— 与线上一致(_headers 不作用于 Functions)。
// 这条防止本地模拟"好心"叠加 CSP,从而掩盖真实的线上差异。
for (const res of [manifest, pluginJs, missing, forbidden, badProto, ok]) {
const csp = res.headers()['content-security-policy']
expect(csp, 'Function 响应不应带 CSP(_headers 不作用于 Functions;线上亦如此)').toBeFalsy()
}
})
test('静态资源仍带 CSP(修 Functions 时不得误伤静态资源防护)', async ({ request }) => {
const app = await request.get('/app.js')
expect(app.status(), '/app.js 应 200').toBe(200)
const csp = app.headers()['content-security-policy']
expect(csp, '静态资源应有 Content-Security-Policy').toBeTruthy()
expect(csp, 'CSP 应限制 script-src 为 self').toContain("script-src 'self'")
expect(csp, 'CSP 不应允许 unsafe-eval').not.toContain('unsafe-eval')
expect(app.headers()['x-content-type-options'], '静态资源应有 nosniff').toBe('nosniff')
})
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -30,7 +30,8 @@ assert.deepStrictEqual(specsBase, expectedSpecs, '门禁 spec 必须等于全部
// 54 = 52 + iwb-inherit-text(v3.24.81 上游继承文本)+ iwb-plugin-node-coldstart(v3.24.82 插件节点体异步注册)
// —— 这两条 spec 随 v3.24.81/82 一起进仓库时没同步更新本数字,门禁从那时起是红的(2026-11-14 补记)
// 55 = 54 + iwb-multi-tab(v3.24.85:跨标签页契约 —— A 页 flush 落盘后 B 页靠 rev 轮询可见 / 图库归档受跨进程锁保护)
assert.strictEqual(result.specs.length, 55, '当前门禁应自动发现 55 个 spec(新增 iwb-multi-tab)')
// 53 = 55 − iwb-csp-gate − iwb-functions-headers(v3.25.15:网页版部署面删除,两条只测 _headers/Functions 的 spec 一并删除)
assert.strictEqual(result.specs.length, 53, '当前门禁应自动发现 53 个 spec')
// 排除集合 = 全部人工 dev 探针,且都必须已声明标记
// 4 = 3 + _probe-tab-switch(切画布标签耗时归因:四轮对照实验,只读诊断)
assert.deepStrictEqual(excludedBase, ['_perf-baseline.spec.js', '_plugin-host-probe.spec.js', '_probe-drag.spec.js', '_probe-tab-switch.spec.js'], '被排除的应是全部带 iwb-dev-probe 标记的 dev 探针')
+6 -13
View File
@@ -1,11 +1,11 @@
'use strict'
// 源码文本断言「棘轮」守卫(只减不增)。动机见 docs/standards/architecture-current-state.md 与审计:
// iwb-v32-web-test.js 约 44% 的断言是对 app.js 的**精确源码文本 / 空白**——重构即红、且会锁住死代码
// (历史)iwb-v32-web-test.js 曾约 44% 的断言是对 app.js 的**精确源码文本 / 空白**——重构即红、且会锁住死代码;该文件已随网页版删除
// (实例:relayCompatTasks / resolveTaskGraph 已死,却被 67-2/67-3 的文本钉点锁住)。
// 本守卫钉住上限:**新增**源码文本断言会让它打红,促使新测试改用行为断言;随重构下降则自动放行。
//
// ── 2026-10-20 扩展:守卫范围从「仅 iwb-v32-web-test.js」扩到「整个 tests/ 目录」 ──
// ── 2026-10-20 扩展:守卫范围从「单个文件」扩到「整个 tests/ 目录」 ──
// 动机(审计 H2):原棘轮**只守一个文件** ⇒ 另外 23 个文件里的约 160 处源码文本钉点
// **完全不受约束** —— 在别处新写一个 `assert.ok(source.includes('xxx'))` 不会被拦。
// 本仓 12 个文件 100% 脆(16/16 断言都是源码文本),是重构的定时炸弹。
@@ -26,7 +26,6 @@ const fs = require('fs')
const path = require('path')
const root = path.resolve(__dirname, '..')
const testsDir = path.join(root, 'tests')
const src = fs.readFileSync(path.join(testsDir, 'iwb-v32-web-test.js'), 'utf8')
// ── 上限 = 2026-10-20 实测值(只允许下调,不允许上调)──────────────────
// 2026-10-28(P1 拆分批 1):884 → **881**(67-1 那条改读 src/generation-task-graph.js)
@@ -150,7 +149,7 @@ const MAX_SRC_COMPONENT_LINES = 531
// ② 同时守「app.js 占总源码 ≤ 40%」(2026-11-12 实测 38.4%)—— app.js 可以涨,
// 但必须涨得比 src 慢;功能继续加,占比自然往下走;
// ③ Workbench 单函数上限**不动**(3,091)—— 那才是真坏味道的护栏,总量松它不松。
const MAX_APP_JS_LINES = 8890 // 2026-11-17 P3:开发者模式本地插件加载器(+37 行) // 2026-11-17:市场请求改走原生 HTTP(+2 行 helper) // 2026-11-17 桌面版:插件市场(索引拉取/下载/sha256/写入 plugins/)约 +53 行;待抽到 src/runtime-plugin-market.js 后回调
const MAX_APP_JS_LINES = 8945 // 2026-11-18 v3.25.20:出图自动下载接线(逻辑在 src/download-auto.js)
const MAX_APP_JS_SHARE = 0.40
// ── 历史记账(供回溯,逐条保留)──────────────────────────────────────────────
@@ -193,7 +192,7 @@ const MAX_APP_JS_SHARE = 0.40
// 需要实时读 .iwb-world 变换 + 按同类型实测高度校正视觉中心;属装配层的 DOM 读取,
// 放 src 会引入新的全局读取与边界快照改动,权衡后留在 app.js // +10(2026-11-01):背景色「悬停预览」的 DOM 补丁助手(纯 DOM,不写数据/不进撤销栈);
// 属装配层最小的 DOM 操作,放 src 会引入新的全局读取与边界快照改动,权衡后留在 app.js
const MAX_WORKBENCH_LINES = 3030 // −60(2026-11-16 棘轮收回):搬走三个族后**下调并留出余量**,不是放宽。
const MAX_WORKBENCH_LINES = 3035 // 2026-11-18 v3.25.20:自动下载提示回调(组件闭包经全局槽暴露)
// 实测 3090 → 2998(省 92):① 生成取消族 cancelRunsFor/cancelRun/cancelTaskJobs
// → src/runtime-workbench-logic.js 的 createCancelActions(−53);② 工作区列表写回族
// persistWs/duplicateWs → 同文件 createWorkspaceListActions(−30);③ 死代码 runAll
@@ -377,15 +376,10 @@ function countDirPins() {
return { total, perFile }
}
const app53Usages = (src.match(/\bapp53\b/g) || []).length
const whitespacePins = (src.match(/\\n\s{2,}/g) || []).length
// iwb-v32-web-test.js 已随网页版删除:原先「该文件里的 app53 钉点 / 精确空白钉点」两项上限不再适用。
// 现在只看全目录总量(dirPins),任何新增源码文本钉点都会打红。
const dirPins = countDirPins()
assert.ok(app53Usages <= MAX_APP53_USAGES,
'iwb-v32 对 app.js 的源码文本断言不得增加(现 ' + app53Usages + ' / 上限 ' + MAX_APP53_USAGES + ')——新测试请用行为断言(vm/jsdom 驱动模块),勿再加源码文本钉点')
assert.ok(whitespacePins <= MAX_WHITESPACE_PINS,
'不得新增「精确换行/缩进」正则断言(现 ' + whitespacePins + ' / 上限 ' + MAX_WHITESPACE_PINS + ')')
// 全目录上限:任何**新增**源码文本钉点(不论在哪个文件)都会打红。
// 存量不追溯 —— 逐步消除存量是另一件事(见规则库 §13.5 与事实基线 §11-F1 的教训)。
assert.ok(dirPins.total <= MAX_DIR_SOURCE_PINS,
@@ -485,5 +479,4 @@ assert.ok(dirPins.total <= MAX_DIR_SOURCE_PINS,
}
console.log('source-text ratchet checks passed ('
+ app53Usages + ' app53 usages, ' + whitespacePins + ' whitespace pins, '
+ dirPins.total + ' dir source pins across ' + dirPins.perFile.length + ' files)')
+39
View File
@@ -0,0 +1,39 @@
/* storage-gc-canvas-refs-test.js —— GC 必须把画布引用算作「在用」(v3.25.9)
*
* 为什么用源码断言而不是跑行为:
* storage-file 的 gcImages 依赖 Tauri fs/path 注入与真实目录,在 Node 下完整模拟
* 等于重写一遍宿主,收益不如直接钉住「关键判据存在且顺序正确」。
* 这里钉三条:
* ① gcImages 会扫 canvases/*.json 里的 {__blob}
* ② 扫出来的 key 会并入 used 集合(少这一步等于没扫)
* ③ dryRun 报告 dangling / keptByCanvas,供确认弹窗展示
* 另加一条:图片登记后必须立即 flush(登记表不能落后于画布)。
*/
'use strict'
const fs = require('node:fs')
const path = require('node:path')
const assert = require('node:assert')
const SRC = fs.readFileSync(path.join(__dirname, '..', 'src', 'storage-file.js'), 'utf8')
const gcBody = SRC.slice(SRC.indexOf('async function gcImages'), SRC.indexOf('global.IWBStorageFile = {'))
assert.ok(gcBody.length > 200, '① 找不到 gcImages 实现')
assert.ok(/canvases/.test(gcBody) && /__blob/.test(gcBody), '① gcImages 必须扫 canvases 里的 __blob 引用')
assert.ok(/canvasKeys/.test(gcBody), '① 必须收集 canvasKeys')
assert.ok(/referenced.forEach\(\(f\) => used\.add\(f\)\)/.test(gcBody), '② 扫到的引用必须并入 used 集合(否则等于没扫)')
assert.ok(/dangling/.test(gcBody), '③ dryRun 必须报 dangling(断链引用数)')
assert.ok(/keptByCanvas/.test(gcBody), '③ dryRun 必须报 keptByCanvas(因画布引用而保留的数量)')
assert.ok(gcBody.indexOf('canvasKeys') < gcBody.indexOf('used.has(rel)'), '② 顺序错:必须先算引用再判孤儿', gcBody.indexOf('canvasKeys') + ' vs ' + gcBody.indexOf('used.has(rel)'))
// 登记后立即落盘:blob 与 dataurl 两条登记路径都要 await flush()
const putRegions = SRC.split('assets[String(key)] = {')
assert.ok(putRegions.length >= 3, '应至少有两处 assets 登记')
let flushed = 0
for (let i = 1; i < putRegions.length; i++) {
const seg = putRegions[i].slice(0, 400)
if (/await flush\(\)/.test(seg)) flushed++
}
assert.ok(flushed >= 2, '图片登记后必须立刻 await flush()(当前 ' + flushed + '/2 处)')
console.log('storage-gc-canvas-refs: 8 通过 / 0 失败')
+3
View File
@@ -7,6 +7,9 @@
// 纪律:只增不减;新增全局导出后若 typecheck 报 TS2339,就在这里补一行。
interface Window {
// 桌面壳 / 外观(v3.25.14)
IWBUIShell?: any
IWBUIApearance?: any
// 存储
IWBStorageLocal?: any
IWBStorageRuntime?: any
-9
View File
@@ -1,9 +0,0 @@
name = "image-workbench-web"
compatibility_date = "2026-08-15"
pages_build_output_dir = "dist"
# A2:插件以同源方式从 KV 提供(/plugins/* → 见 functions/plugins/[[path]].js)。
# 同源脚本本来就被 CSP script-src 'self' 允许 ⇒ 无需放宽任何 CSP。
[[kv_namespaces]]
binding = "PLUGINS"
id = "4fbc63a386d945f2891381c737f1fd77"