fix(clipboard): mac ⌘C/⌘V 一条命令贴一切(copy 事件主通道 + keydown 主动粘贴)

mac 的 WKWebView 只在第一响应者可编辑时派发 paste 事件;Menu::default() 的 Edit>Copy/Paste
又永远 enabled,所以「焦点在输入框/有选区」时 keydown 到不了 JS —— 复制节点组静默失败、
⌘V 只剩一句「请按 Ctrl+Shift+V」。本次把两条通道都换掉:

- 复制:DOM copy 事件里同步 clipboardData.setData(text/html 带标记 + text/plain 摘要),
  keydown 留 80ms 兜底,Workbench 卸载时摘监听(否则回首页 ⌘C 会复制旧画布)。
- 粘贴:⌘V keydown 主动粘贴,指针在画布即接管,逐级降级(系统剪贴板富读取 → 原生文本
  → 原生图片 → 应用内剪贴板);150ms 内等到 paste 事件就让给事件通道,一次按键只贴一份。
- 输入框内:指针在画布 → 改贴画布;只有「N 个节点」摘要 → 拦下不进输入框;
  带提示词全文 → 放行原生。
- 标记双写注释 + data-iwb-graph 属性(WKWebView 会剥注释);decode 两处都找。
- 未选中节点复制、复制/粘贴失败都有提示;notice 的 err/info 5.2s 自动消失。

门禁:clipboard-graph 56 项 / clipboard-paste 100 项,e2e 用例 5、19 按新语义更新
(e2e 已知红与基线一致:7 条,均为无头环境剪贴板限制)。
This commit is contained in:
qiqi committed 2026-11-26 12:45:56 +08:00
1 parent 9c27a8178b
commit 18eaeb96f2
11 files changed
+573 -131

No files matched your search

+3 -3
View File
@@ -40,7 +40,7 @@ build esbuild 打包到 dist/(单 dist/app.js = src/ 模块按序
node --check app.js 与 dist/app.js 语法
check-dist.js 产物体检
lint ESLint(src/ + app.js,正确性规则)
test:unit 131 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
test:unit 132 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
test relay-task-graph-fixture + iwb-v32-web-test
test:facts 事实基线守门(见 §5)
typecheck 渐进类型检查(tsc --noEmit;范围 = src/*.js,不含 app.js)
@@ -102,8 +102,8 @@ IWB_WRITE_BOUNDARY_SNAPSHOT=1 node tests/architecture-boundary-guard-test.js #
| 守卫 | 位置 | 现在的上限 |
|---|---|---|
| `app.js` 总行数 | `tests/source-text-ratchet-test.js` `MAX_APP_JS_LINES` | **9,190**(另守「占总源码 ≤ 40%」,见 `MAX_APP_JS_SHARE`) |
| `Workbench()` 行数 | 同上 `MAX_WORKBENCH_LINES` | **3,046** |
| `app.js` 总行数 | `tests/source-text-ratchet-test.js` `MAX_APP_JS_LINES` | **9,205**(另守「占总源码 ≤ 40%」,见 `MAX_APP_JS_SHARE`) |
| `Workbench()` 行数 | 同上 `MAX_WORKBENCH_LINES` | **3,060** |
| 单组件行数(不含 Workbench)| 同上 `MAX_APP_COMPONENT_LINES` | **423** |
三条都是**只减不增**。确需在 app.js 增长时,必须**同步上调上限并在 commit 里写理由**(等于显式记账,不会悄悄发生)。
+27 -12
View File
@@ -6116,8 +6116,11 @@ const tbCenterSeed = (type, refs) => {
toastTimer: null, saveTimer: null, typingTimer: null,
// Ctrl+Shift+V 的按下时间窗:吞掉浏览器随后派发的 paste(Chrome 会以纯文本形式触发)
pasteGroupUntil: 0,
// Ctrl+V 探测标记(src/clipboard-paste.js probe):等到真实 paste 就清零,否则给「请用 Ctrl+Shift+V」提示
pasteProbe: 0,
// 粘贴通道时间戳(2026-11-26):pasteKeyAt = 本次 ⌘V 按下;pasteEventAt = 真收到 paste;
// pasteSwallowUntil = 主动粘贴刚落地,吞掉重复事件。三条一起保证「一次按键只贴一份」。
pasteKeyAt: 0, pasteEventAt: 0, pasteSwallowUntil: 0,
// 本机系统剪贴板是否可信(复制时写成功=true / 写失败=false;失败后 ⌘V 只认应用内剪贴板)
sysClipOk: null,
// 内部剪贴板「复制过但已过期」(readClipboardGraph 维护):用于把静默失败变成一句提示
clipExpired: false,
// ── 多画布 Session(S1:结构落地;行为改造在 S5–S6;Pilot 2 第二片容器外置到 sessionsStore)──
@@ -6448,6 +6451,7 @@ const tbCenterSeed = (type, refs) => {
const floatbarRefPaste = (...a) => wbCmd().floatbarRefPaste(...a)
const outResultUrls = (...a) => wbCmd().outResultUrls(...a)
const copyNodes = (...a) => wbCmd().copyNodes(...a)
const stageClip = (...a) => wbCmd().stageClip(...a)
const pasteGraph = (...a) => wbCmd().pasteGraph(...a)
const readClipboardGraph = (...a) => wbCmd().readClipboardGraph(...a)
const pasteCopiedNodes = (...a) => wbCmd().pasteCopiedNodes(...a)
@@ -7456,10 +7460,15 @@ const tbCenterSeed = (type, refs) => {
// 这里只把 Workbench 闭包依赖递过去(每次调用现取,避免陈旧闭包)。
const pasteCtx = () => ({
refs, ui: { settingOpen, drawerOpen, helpOpen, wsMoreOpen, ctxMenu, connMenu }, readClipboardGraph, pasteCopiedNodes, pasteGraph,
// 复制侧(DOM copy 事件)要用:选中集合取实时镜像(渲染闭包的 sel 可能是框选前的空数组)
stageClip, copyNodes, ids: () => selRef.current, clipboardOf: (list) => CanvasOps.clipboardOf(refs.nodes, refs.edges, refs.groups, list),
hasTextSelection: (el) => !!((typeof window !== 'undefined' && window.IWBClipboardCopy) ? window.IWBClipboardCopy.hasTextSelection(el) : null),
markSys: (ok) => { refs.sysClipOk = !!ok },
wsId: activeWsIdRef.current || activeWsId, activeWsId: () => activeWsIdRef.current || activeWsId, nodes: () => refs.nodes,
uid, findSpot, nodeW: (ty) => nodeWidth({ type: ty }), nodeH: (ty) => nodeTypeH(ty),
pushHistory, commitCanvas, setSel, setNotice, showToast, importImage: wImportImage,
readNativeImage: (typeof window !== 'undefined' && window.IWBDesktop && window.IWBDesktop.clipboardReadImage) ? () => window.IWBDesktop.clipboardReadImage() : null,
readNativeText: (typeof window !== 'undefined' && window.IWBDesktop && window.IWBDesktop.clipboardReadText) ? () => window.IWBDesktop.clipboardReadText().then((r) => ((r && r.ok) ? r.text : '')).catch(() => '') : null,
closeLibrary: () => { setDrawerOpen(false) },
})
const onKey = (e) => {
@@ -7493,19 +7502,21 @@ const tbCenterSeed = (type, refs) => {
if (hit('ungroup')) { e.preventDefault(); const g = sel.map((id) => groupOf(id)).find(Boolean); if (g) ungroup(g.id); return }
if (hit('undo')) { e.preventDefault(); undo(); return }
if (hit('redo')) { e.preventDefault(); redo(); return }
if (hit('copy')) { if (sel.length && !(hasTxt && hasTxt(t)) && copyNodes(sel)) e.preventDefault(); return }
// 复制不再在这里做:mac 上 ⌘C 常被原生菜单 Edit>Copy 接管,keydown 到不了 JS(静默失败)。
// 现在统一由 DOM copy 事件处理(src/clipboard-graph.js 的 bindCopy,同步 clipboardData),
// 这里只保留"不 preventDefault"——prevent 反而会取消原生复制动作、连 copy 事件都不派发。
if (hit('copy')) return
if (hit('cut')) { if (sel.length && !(hasTxt && hasTxt(t)) && cutNodes(sel)) e.preventDefault(); return }
// Ctrl+Shift+V:永远粘贴内部节点组剪贴板(不受系统剪贴板内容影响)。
// 必须先于 Ctrl+V 分支判断,让 Ctrl+Shift+V 不被 Ctrl+V 语义吃掉;
// 同时设一个时间窗,吞掉浏览器为 Ctrl+Shift+V 派发的「纯文本 paste」(Chrome 行为)。
if (hit('pasteGroup')) { e.preventDefault(); refs.pasteGroupUntil = Date.now() + 800; pasteCopiedNodes(); return }
if (hit('paste')) {
// v3.24.67:Ctrl+V 只认系统剪贴板,节点组一律 Ctrl+Shift+V(用户裁定的心智模型)。
// 旧实现在这里挂 300ms 定时器回退贴节点组,且用递增 token 只让最后一次执行 ——
// 「复制一份、80ms 内连按 3 次 Ctrl+V」因此只贴出 1 份。定时器已删除;
// 现在只在一直没有 paste 事件时给一句说明(probe),不代替用户粘贴任何东西。
// 2026-11-26:⌘V 不再只"探测 + 提示"。桌面端(mac)焦点不在输入框时根本不派发 paste
// 事件,旧实现只能提示"请按 Ctrl+Shift+V"。现在这里直接**主动粘贴**(指针在画布才接管):
// 先让原生走(有 paste 事件的平台照旧),150ms 内没等到事件才自己读剪贴板。
const mod = (typeof window !== 'undefined' && window.IWBClipboardPaste) || null
if (mod) mod.probe(pasteCtx())
if (mod && mod.pasteFromKey) mod.pasteFromKey(pasteCtx())
return
}
if (hit('duplicate')) { e.preventDefault(); duplicateNodes(sel); return }
@@ -7545,15 +7556,16 @@ const tbCenterSeed = (type, refs) => {
// 替换参考图只保留显式入口(节点头「粘贴图片替换」/ 气泡按钮 / 上传),且必须可撤销。
const onPaste = (e) => {
const t = e.target, editable = !!(t && t.tagName && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable))
refs.pasteProbe = 0 // 收到真实 paste → 取消「系统剪贴板为空」的提示
refs.pasteEventAt = Date.now() // 真收到 paste → 主动粘贴那条定时器不再重复读剪贴板
const mod = (typeof window !== 'undefined' && window.IWBClipboardPaste) || null
// pasteStamp 只在**真正被消费**时自增(桌面端 keydown 兜底靠它判断);无条件自增会让被忽略的 paste 也挡住兜底。
// pasteStamp 只在**真正被消费**时自增(其它模块靠它判断这次 paste 有没有被处理)。
if (mod && mod.handle(e, pasteCtx(), editable)) refs.pasteStamp = (refs.pasteStamp || 0) + 1
}
window.addEventListener('keydown', onKey)
window.addEventListener('keyup', onKeyUp)
const pasteModEarly = (typeof window !== 'undefined' && window.IWBClipboardPaste) || null
if (pasteModEarly && pasteModEarly.bindHotkeyFallback) pasteModEarly.bindHotkeyFallback(pasteCtx)
// 复制主通道(2026-11-26):DOM copy 事件 + keydown 兜底,见 src/clipboard-graph.js
const copyMod = (typeof window !== 'undefined' && window.IWBClipboardGraph) || null
if (copyMod && copyMod.bindCopy) copyMod.bindCopy(pasteCtx)
window.addEventListener('paste', onPaste)
window.addEventListener('blur', onBlur)
return () => {
@@ -7567,6 +7579,9 @@ const tbCenterSeed = (type, refs) => {
window.removeEventListener('keyup', onKeyUp)
window.removeEventListener('paste', onPaste)
window.removeEventListener('blur', onBlur)
// 复制通道绑在 window 上(不在 lifecycle 里):卸载时必须显式摘掉,否则回到首页后
// ⌘C 仍会拿已卸载那份 refs 去复制旧画布的选中节点。
if (copyMod && copyMod.unbindCopy) copyMod.unbindCopy()
}
}, [sel, selEdge, settingOpen, drawerOpen, drawerTab, wsMoreOpen, ctxMenu, connMenu, helpOpen])
+1 -1
View File
@@ -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 **9,190 行**(**双层预算**:绝对上限 9,190 / 占总源码 ≤ 40%,现 **29.5%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **3,045 行**(上限 **3,046**,余量 1;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **112** 个模块 / 21,985 行,`sourceModules` 112 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。
- `app.js` = 单 IIFE **9,205 行**(**双层预算**:绝对上限 9,205 / 占总源码 ≤ 40%,现 **29.2%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **3,060 行**(上限 **3,060**,余量 0;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **112** 个模块 / 22,266 行,`sourceModules` 112 项;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. 门禁与环境现状
+150 -14
View File
@@ -66,6 +66,11 @@
return nodes.length + ' 个节点' + gname
}
/* 标记写两份(2026-11-26):
* ① HTML 注释 —— Chromium 侧实测原样保留,粘到别的应用也不显示;
* ② `data-iwb-graph` 属性 —— WKWebView(mac 桌面端)在写/读剪贴板时会过一遍 HTML 清洗,
* 注释被整段丢掉(实测写入 208 B、读回 414 B、标记消失),属性值能活下来。
* 两份带的是同一串 base64,谁活着都能解出来;decode() 两个位置都找。 */
function htmlFor(clip) {
const payload = JSON.stringify({
app: clip && clip.app,
@@ -76,7 +81,33 @@
groups: (clip && clip.groups) || [],
})
const head = plainFor(clip)
return '<!--' + MARK + encodeText(payload) + '--><div>' + esc(head.slice(0, 200)) + '</div>'
const b64 = encodeText(payload)
return '<!--' + MARK + b64 + '--><div data-iwb-graph="' + b64 + '">' + esc(head.slice(0, 200)) + '</div>'
}
// 属性形态的标记(引号单双都认:不同应用回写 HTML 时引号风格不一致)
function b64FromAttr(s) {
const m = /data-iwb-graph\s*=\s*("([^"]*)"|'([^']*)')/i.exec(s)
if (!m) return ''
return str(m[2] != null ? m[2] : m[3]).replace(/[^A-Za-z0-9+/=]/g, '')
}
function b64FromComment(s) {
const i = s.indexOf(MARK)
if (i < 0) return ''
const start = i + MARK.length
const end = s.indexOf('-->', start)
const raw = (end > start ? s.slice(start, end) : s.slice(start))
return raw.replace(/[^A-Za-z0-9+/=]/g, '')
}
function parseB64(b64) {
if (!b64) return null
try {
const obj = JSON.parse(decodeText(b64))
if (!obj || !Array.isArray(obj.nodes) || !obj.nodes.length) return null
return obj
} catch (e) { return null }
}
/* 从 text/html 里把 clip 取回来。找不到标记、base64 坏掉、JSON 坏掉、nodes 为空
@@ -85,18 +116,27 @@
* 定位标记,不能假设它以注释开头。 */
function decode(html) {
const s = str(html)
const i = s.indexOf(MARK)
if (i < 0) return null
const start = i + MARK.length
const end = s.indexOf('-->', start)
const raw = (end > start ? s.slice(start, end) : s.slice(start))
const b64 = raw.replace(/[^A-Za-z0-9+/=]/g, '')
if (!b64) return null
try {
const obj = JSON.parse(decodeText(b64))
if (!obj || !Array.isArray(obj.nodes) || !obj.nodes.length) return null
return obj
} catch (e) { return null }
return parseB64(b64FromComment(s)) || parseB64(b64FromAttr(s))
}
/* 在 DOM `copy` 事件里**同步**写系统剪贴板(2026-11-26 起这是复制的主通道)。
*
* 为什么不用 navigator.clipboard.write:它是异步的,在 WKWebView 里写 text/html 经常被拒,
* 失败后只能降级成"纯文本摘要 + matchPlain 全等比对"(脆);而且 mac 上 ⌘C 被原生菜单
* Edit>Copy 接管时,keydown 根本到不了 JS,异步那条链路连触发都没有。
* clipboardData.setData 由用户手势直接授权、同步生效,Chromium / WKWebView 都可用。
*
* 同时 notePlain():即使 text/html 被清洗掉,粘贴侧还能靠"纯文本摘要全等"认回节点组。 */
function writeToEvent(e, clip) {
const dt = e && e.clipboardData
if (!dt || typeof dt.setData !== 'function') return false
const plain = plainFor(clip)
let ok = true
try { dt.setData('text/plain', plain) } catch (err) { ok = false }
try { dt.setData('text/html', htmlFor(clip)) } catch (err) { ok = false }
// 即使 setData 抛错也记账:内部剪贴板与 matchPlain 仍能让 ⌘V 贴回来
notePlain(plain, clip)
return ok
}
/* 写系统剪贴板。返回 Promise<boolean>:false 表示这个环境写不了
@@ -147,5 +187,101 @@
return Promise.resolve(T.core.invoke('clipboard_write_text', { text: str(plain) })).then(() => true).catch(() => false)
}
g.IWBClipboardGraph = Object.freeze({ MARK, encodeText, decodeText, htmlFor, plainFor, decode, write, matchPlain })
/* 复制主通道:DOM `copy` 事件(2026-11-26)。
*
* 旧实现只有 keydown 一条路(app.js 的 `hit('copy')`)。mac 桌面端 `Menu::default()` 的
* Edit>Copy 绑的是 `copy:` 且 `setAutoenablesItems(false)` 永远 enabled —— 只要第一响应者
* 认为"有东西可复制"(可编辑焦点 / 文本选区),AppKit 直接处理掉,keydown 到不了 JS,
* 于是"复制节点组"静默失败:没有提示、系统剪贴板没内容,用户觉得是随机 bug。
*
* 改法:复制统一由 `copy` 事件驱动(原生菜单处理的复制同样会派发这个事件),
* keydown 只保留一个兜底定时器(个别 WebView 不派发 copy 事件时才用旧异步链路)。
* 判定顺序:有文本选区 → 让原生复制文字;没选中节点 → 让原生走(并说一句没东西可复制,
* 否则又是一次"按了没反应")。
*/
let copyCtxOf = null // 最新的取值函数(Workbench 重挂载后必须换成本次渲染的)
let copyBound = null // { onCopy, onKey }:已注册的处理函数,供 unbindCopy 摘除
function bindCopy(getCtx) {
if (typeof getCtx === 'function') copyCtxOf = getCtx
if (copyBound || typeof window === 'undefined' || !window.addEventListener) return
let handledAt = 0
const ctxNow = () => (copyCtxOf ? copyCtxOf() : null)
function selOf(ctx) {
try { const ids = ctx.ids && ctx.ids(); return Array.isArray(ids) ? ids : [] } catch (e) { return [] }
}
function textSelected(ctx, el) {
const C = g.IWBClipboardCopy
try {
if (C && typeof C.hasTextSelection === 'function') return !!C.hasTextSelection(el)
} catch (e) { /* ignore */ }
return false
}
const onCopy = (e) => {
const ctx = ctxNow()
if (!ctx) return
handledAt = Date.now()
const ids = selOf(ctx)
const t = e && e.target
if (textSelected(ctx, t)) return // 用户要复制文字 → 原生
if (!ids.length) {
// 没选中节点、也没选中文字:原生复制是空操作。明确说一句,别让用户以为按键坏了。
if (ctx.setNotice) ctx.setNotice({ type: 'err', text: '没有可复制的节点:先在画布上选中或框选节点' })
return
}
let clip = null
try { clip = ctx.clipboardOf ? ctx.clipboardOf(ids) : null } catch (err) { clip = null }
if (!clip) {
if (ctx.setNotice) ctx.setNotice({ type: 'err', text: '选中的节点无法复制(可能还在加载)' })
return
}
const wrote = writeToEvent(e, clip)
if (wrote) {
try { e.preventDefault() } catch (err) { /* ignore */ }
if (ctx.markSys) ctx.markSys(true)
if (ctx.stageClip) ctx.stageClip(clip)
return
}
// setData 不可用(极端环境):让原生走,同时用旧异步链路补写系统剪贴板
if (ctx.copyNodes) ctx.copyNodes(ids)
}
/* keydown 兜底:copy 事件没派发时(不派发 `copy` 的 WebView / 焦点在 iframe),
* 按旧链路再复制一次。keydown 里**不 preventDefault** —— 一 prevent 就取消了原生复制动作,
* `copy` 事件反而不会派发。
* 80ms 而不是 0:copy 事件由浏览器在 keydown 的默认动作里同步派发,正常都在 10ms 内到;
* 留 80ms 是给"事件稍晚一点"的环境,同时保证「⌘C 之后立刻 ⌘V」时剪贴板已经写好
* (旧实现没有延迟,但那条路在 mac 上根本走不到 —— 参见 bindCopy 顶部注释)。 */
const onKey = (e) => {
if (!(e.metaKey || e.ctrlKey) || e.shiftKey || e.altKey) return
if (String(e.key || '').toLowerCase() !== 'c') return
const ctx = ctxNow()
if (!ctx) return
const at = Date.now()
setTimeout(() => {
if (handledAt >= at) return // copy 事件已经处理过
const ids = selOf(ctx)
if (!ids.length) return
if (textSelected(ctx, e.target)) return
if (ctx.copyNodes) ctx.copyNodes(ids)
}, 80)
}
window.addEventListener('copy', onCopy, true)
window.addEventListener('keydown', onKey, true)
copyBound = { onCopy, onKey }
}
/* 摘掉监听(Workbench 卸载 / 依赖变化时由 app.js 调用)。
* 不摘会出事:关掉画布回到首页后 ⌘C 仍走这条路,闭包里是**已经卸载的那份 refs** ——
* 会去复制旧画布上"当时的选中节点",用户在首页按一次 ⌘C 就莫名其妙改了剪贴板。 */
function unbindCopy() {
if (!copyBound) return
try { window.removeEventListener('copy', copyBound.onCopy, true) } catch (e) { /* ignore */ }
try { window.removeEventListener('keydown', copyBound.onKey, true) } catch (e) { /* ignore */ }
copyBound = null
}
g.IWBClipboardGraph = Object.freeze({ MARK, encodeText, decodeText, htmlFor, plainFor, decode, write, writeToEvent, matchPlain, bindCopy, unbindCopy })
})(typeof window !== 'undefined' ? window : globalThis)
+176 -50
View File
@@ -2,6 +2,14 @@
*
* 分工:src/clipboard-kind.js 判定「剪贴板里是什么」,本模块只负责「落成什么」。
*
* 2026-11-26 通道重写(桌面端 mac 对不上号的真因):
* mac 的 WKWebView 只在「第一响应者可编辑」时派发 paste 事件;焦点在画布/body 时 ⌘V
* 只有 keydown。旧实现把 Ctrl+V 做成「等 paste 事件 + 弹一句请按 Ctrl+Shift+V」,
* 于是节点组在 mac 上等于没有 Ctrl+V 通路。现在:
* · paste 事件仍是**首选通道**(有真实 clipboardData,保真度最高);
* · keydown ⌘V 由 pasteFromKey() 接管:指针在画布就主动读剪贴板(富读取 → 原生文本 →
* 原生图片 → 内部剪贴板),150ms 内等到 paste 事件就让给事件通道,一次按键只贴一份。
*
* 语义(用户 2026-11-11 二次裁定的心智模型:**一个键贴所有**):
* · Ctrl+C 复制节点/节点组时,除了内部剪贴板,还会把节点组写进**系统剪贴板**
* (text/html 带 iwb:graph 标记,见 src/clipboard-graph.js)。因此 Ctrl+V 能直接贴节点组,
@@ -284,13 +292,156 @@
ctx.setNotice({ type: 'ok', text: truncated ? '已粘贴文本为提示词节点(超长已截断到 5000 字)' : '已粘贴文本为提示词节点' })
}
/* ── 焦点 / 鼠标:谁决定「这次粘贴归谁」(2026-11-26)─────────────────────────
* 桌面端(mac WKWebView)只有第一响应者可编辑时才会派发 paste 事件;焦点在画布/body 时
* ⌘V 只到 keydown。而产品语义是「指哪贴哪」—— 落点看指针(anchor),那接管权也该看指针,
* 不能一边用鼠标定落点、一边用键盘焦点决定"能不能贴"。
* 规则:指针在画布上 → 这次粘贴归画布(接管);指针不在画布且焦点在输入框 → 放行原生。
*/
function isEditableEl(el) {
if (!el) return false
const tag = el.tagName
return !!(tag && (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT')) || !!el.isContentEditable
}
function activeEl() {
try { return (typeof document !== 'undefined') ? document.activeElement : null } catch (e) { return null }
}
function blurActive() {
try {
const a = /** @type {any} */ (activeEl())
if (a && typeof a.blur === 'function') a.blur()
} catch (e) { /* ignore */ }
}
// 合成一个「只有文本 / 只有文件」的剪贴板事件,把读取结果交回 handle() 分流
function fakeEvent(text, files) {
const list = files || []
const ev = {
clipboardData: {
items: list.map((f) => ({ kind: 'file', type: (f && f.type) || '', getAsFile: () => f })),
files: list,
getData: (t) => (t === 'text/plain' ? str(text) : ''),
},
defaultPrevented: false,
preventDefault() { ev.defaultPrevented = true },
}
return ev
}
/* 系统剪贴板富读取(只有 Chromium / 有权限时可用)。WKWebView 常常直接 reject,
* 所以调用方必须准备好「原生文本 + 原生图片 + 内部剪贴板」三级降级。 */
function readSystemClip() {
return new Promise((resolve) => {
const cb = g.navigator && g.navigator.clipboard
if (!cb || typeof cb.read !== 'function') { resolve(null); return }
let p = null
try { p = cb.read() } catch (e) { resolve(null); return }
if (!p || typeof p.then !== 'function') { resolve(null); return }
p.then((items) => {
const out = { html: '', text: '', files: [] }
const todos = []
for (const it of (items || [])) {
const types = Array.isArray(it && it.types) ? it.types : []
if (types.indexOf('text/html') >= 0) todos.push(it.getType('text/html').then((b) => b.text()).then((v) => { out.html = str(v) }).catch(() => {}))
if (types.indexOf('text/plain') >= 0) todos.push(it.getType('text/plain').then((b) => b.text()).then((v) => { out.text = str(v) }).catch(() => {}))
const img = types.find((t) => str(t).indexOf('image/') === 0)
if (img) todos.push(it.getType(img).then((blob) => {
try { out.files.push(new g.File([blob], 'clipboard-' + Date.now() + '.png', { type: img })) } catch (e) { out.files.push(blob) }
}).catch(() => {}))
}
Promise.all(todos).then(() => resolve(out)).catch(() => resolve(out))
}).catch(() => resolve(null))
})
}
function failText(ctx) {
if (ctx.refs.clipExpired) return '内部剪贴板已过期(10 分钟),请重新复制节点'
return nativeReason() || '剪贴板里没有可粘贴的内容:复制图片 / 文本,或先在画布上选中节点复制'
}
/* 系统剪贴板读不出内容时的最后两级:原生图片(Rust arboard)→ 内部剪贴板。 */
function fallbackRead(ctx) {
const img = (typeof ctx.readNativeImage === 'function')
? Promise.resolve().then(() => ctx.readNativeImage()).catch(() => null)
: Promise.resolve(null)
return img.then((f) => {
if (f) { pasteImages([f], ctx); done(ctx); return }
if (ctx.pasteCopiedNodes()) { ctx.setNotice(null); done(ctx); return }
ctx.setNotice({ type: 'err', text: failText(ctx) })
})
}
/* ⌘V 主动粘贴(keydown,2026-11-26)。
*
* 返回 true = 这次按下由画布接管(调用方无需再做什么);false = 放行原生(往输入框里粘文本)。
*
* 为什么不在这里 preventDefault:一 prevent 就取消了原生粘贴动作,有 paste 事件的平台
* (Windows / WebView2)反而收不到那次**带真实 clipboardData** 的 paste 事件。所以策略是
* 「先让原生走,150ms 内没等到 paste 事件才自己读」—— 两条通道互不打架:
* · 有 paste 事件 → handle() 用 clipboardData(保真度最高,连 text/html 标记都在)
* · 没 paste 事件(mac 无编辑焦点)→ 这里主动读:系统剪贴板富读取 → 原生文本 → 原生图片 → 内部
*/
function pasteFromKey(ctx) {
if (!ctx) return false
if (modalOpen(ctx.ui)) return false
const editable = isEditableEl(activeEl())
// 焦点在输入框里 → 一律放行原生:用户正在打字,⌘V 的语义是「把文字粘进这里」。
// (要贴节点组的话,paste 事件里还有一次机会:指针在画布上就改贴到画布,见 handle())
if (editable) return false
const at = Date.now()
ctx.refs.pasteKeyAt = at
ctx.refs.pasteEventAt = 0
setTimeout(() => {
if (ctx.refs.pasteKeyAt !== at) return // 又按了一次,交给最新那次
if (ctx.refs.pasteEventAt && ctx.refs.pasteEventAt >= at) return // paste 事件已处理
readSystemClip().then((sys) => {
if (ctx.refs.pasteEventAt && ctx.refs.pasteEventAt >= at) return
const G = g.IWBClipboardGraph
if (sys && sys.html) {
const clip = (G && typeof G.decode === 'function') ? G.decode(sys.html) : null
if (clip && ctx.pasteGraph(clip, anchor(ctx) || safeSeed(ctx))) { done(ctx); return }
}
if (sys && sys.files && sys.files.length) { pasteImages(sys.files, ctx); done(ctx); return }
if (sys && sys.text) {
const ev = fakeEvent(sys.text, [])
if (handle(ev, ctx, false)) { done(ctx); return }
}
// 原生文本(桌面端 arboard)。剪贴板内容是「上次我们自己写进去的摘要」时,
// matchPlain 会在 handle() 里把节点组认回来 —— 这是 mac 上 ⌘V 贴节点组的关键一条。
const textP = (typeof ctx.readNativeText === 'function')
? Promise.resolve().then(() => ctx.readNativeText()).catch(() => '')
: Promise.resolve('')
textP.then((t) => {
const text = str(t)
// 上次写系统剪贴板失败(refs.sysClipOk === false)时,剪贴板里是**别人的旧内容**,
// 不能当成本次粘的内容;直接走内部剪贴板。
if (text && ctx.refs.sysClipOk !== false) {
if (handle(fakeEvent(text, []), ctx, false)) { done(ctx); return }
}
fallbackRead(ctx)
})
})
}, 150)
return true
}
// 同步通道真的落了东西 → 记一个短窗口,吞掉紧随其后的重复 paste 事件
function done(ctx) {
ctx.refs.pasteDoneAt = Date.now()
ctx.refs.pasteSwallowUntil = Date.now() + 400
}
/* 主入口。返回 true = 已消费这次 paste。
* ctx 见 app.js 里 pasteCtx():refs / ui / readClipboardGraph / pasteCopiedNodes / pasteGraph /
* wsId / activeWsId() / nodes() / uid / findSpot / nodeW / nodeH /
* pushHistory / commitCanvas / setSel / setNotice / importImage
* editable = 焦点在 input/textarea/contenteditable 里(提示词节点内、设置项、放大编辑浮层…) */
function handle(e, ctx, editable) {
// Ctrl+Shift+V 之后浏览器可能再派发一次「纯文本 paste」(Chrome 行为)→ 在这一窗口内吞掉
// 主动粘贴(keydown 通道)刚落地 → 吞掉紧随其后的同一次 paste 事件,避免贴两份
if (ctx.refs.pasteSwallowUntil && Date.now() < ctx.refs.pasteSwallowUntil) {
e.preventDefault()
return true
}
if (ctx.refs.pasteGroupUntil && Date.now() < ctx.refs.pasteGroupUntil) {
ctx.refs.pasteGroupUntil = 0
e.preventDefault()
@@ -303,8 +454,26 @@
// 输入框里:文本 / 链接照样走浏览器原生粘贴(这里**不**接管、不 preventDefault),
// 但节点组、非图片文件原来会被**静默吞掉** —— 用户以为粘上了,其实什么都没发生。
if (c.kind === 'graph') {
ctx.setNotice({ type: 'err', text: '输入框里不能粘贴节点;先点一下画布空白处再按 Ctrl+V' })
return false
/* 焦点在输入框里粘「复制的节点组」,分三种情形:
* ① 指针在画布上 → 这是「贴到画布」的意图:接管,blur 掉焦点、贴到指针处。
* 这条正是用户报的那个坑(焦点卡在提示词框里,点节点内空白也不会掉焦点)。
* ② 指针不在画布、剪贴板里带着**提示词全文** → 放行原生,用户拿到那段文字
* (复制提示词贴到另一个输入框是正经用法,拦掉等于把功能做没了)。
* ③ 指针不在画布、只有「N 个节点」摘要 → preventDefault。旧实现只提示不拦,
* 摘要会被原生粘贴**打进输入框**,把用户的提示词改掉(实测追加了"1 个节点")。 */
if (anchor(ctx) !== null) {
e.preventDefault()
blurActive()
try { const PO = g.IWBPasteOnce; if (PO) PO.disarm() } catch (err) { /* ignore */ }
if (!ctx.pasteGraph(c.clip, anchor(ctx) || safeSeed(ctx))) ctx.setNotice({ type: 'err', text: '粘贴节点组失败:剪贴板内容无法识别' })
return true
}
const nodes = (c.clip && Array.isArray(c.clip.nodes)) ? c.clip.nodes : []
const hasText = nodes.some((n) => n && n.type === 'prompt' && n.data && typeof n.data.text === 'string' && n.data.text.trim())
if (hasText) return false
e.preventDefault()
ctx.setNotice({ type: 'err', text: '节点组不能粘进输入框:把鼠标移到画布上再按 ⌘V(或右键 → 粘贴节点组)' })
return true
}
if (c.kind === 'image') {
// 2026-11-25(用户反馈「有时候报错贴不进去」):焦点还留在提示词节点的 textarea /
@@ -316,8 +485,9 @@
return true
}
if (c.kind === 'files') {
ctx.setNotice({ type: 'err', text: '暂不支持把文件粘进输入框;先点一下画布空白处再粘贴' })
return false
e.preventDefault()
ctx.setNotice({ type: 'err', text: '文件不能粘进输入框:把鼠标移到画布上再粘贴' })
return true
}
return false
}
@@ -440,49 +610,5 @@
return true
}
/* Ctrl+V 按下后若一直没等到 paste 事件,说明浏览器认为系统剪贴板是空的 ——
* 正常情况下复制节点会把节点组写进系统剪贴板,不该走到这里;走到这里只有一种原因:
* 这台环境**写不进系统剪贴板**(老浏览器 / 非 HTTPS / file:// 打开),复制只落了内部那份。
*
* 这里**只提示、不代替用户粘贴**:旧实现靠 300ms 定时器在这儿回退粘贴,递增 token 只让
* 最后一次生效,「复制一份、连按 3 次 Ctrl+V 只贴出 1 份」就是这么来的。 */
function probe(ctx) {
const t0 = Date.now()
ctx.refs.pasteProbe = t0
setTimeout(() => {
if (ctx.refs.pasteProbe !== t0) return
if (ctx.refs.pasteGroupUntil && Date.now() < ctx.refs.pasteGroupUntil) return
if (ctx.readClipboardGraph()) {
ctx.setNotice({ type: 'ok', text: '这台环境写不进系统剪贴板,粘贴节点请按 Ctrl+Shift+V' })
return
}
if (ctx.refs.clipExpired) ctx.setNotice({ type: 'err', text: '内部剪贴板已过期(10 分钟),请重新复制节点' })
}, 420)
}
/* Cmd/Ctrl+V 兜底(桌面端):菜单缺失或 WebView 不派发 paste 时,160ms 内没收到
* 真实 paste 事件就主动读一次原生剪贴板图片。getCtx 由 app.js 注入(懒取,避免闭包过期)。 */
let hotkeyBound = false
function bindHotkeyFallback(getCtx) {
if (hotkeyBound || typeof window === 'undefined') return
hotkeyBound = true
window.addEventListener('keydown', (e) => {
if (!(e.metaKey || e.ctrlKey) || e.shiftKey || e.altKey) return
if (String(e.key || '').toLowerCase() !== 'v') return
const t = /** @type {any} */ (e.target)
if (t && t.tagName && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return
const D = g.IWBDesktop
if (!D || !D.clipboardReadImage) return
const ctx = (typeof getCtx === 'function') ? getCtx() : null
if (ctx && modalOpen(ctx.ui)) return
const stamp = ctx && ctx.refs ? (ctx.refs.pasteStamp || 0) : 0
setTimeout(() => {
const now = ctx && ctx.refs ? (ctx.refs.pasteStamp || 0) : 0
if (now !== stamp) return
D.clipboardReadImage().then((f) => { if (f) pasteImages([f], ctx) })
}, 160)
})
}
g.IWBClipboardPaste = Object.freeze({ handle, probe, overlayOpen, modalOpen, libraryOpen, anchor, bindHotkeyFallback, pasteFiles: (files, ctx) => pasteImages(files || [], ctx) })
g.IWBClipboardPaste = Object.freeze({ handle, pasteFromKey, readSystemClip, overlayOpen, modalOpen, libraryOpen, anchor, pasteFiles: (files, ctx) => pasteImages(files || [], ctx) })
})(typeof window !== 'undefined' ? window : globalThis)
+18 -8
View File
@@ -1828,23 +1828,33 @@
// 引用只在**本机同源**有效:粘到另一个浏览器 / 另一台电脑,节点结构能还原但图是空的。
// ④ 带 at 时间戳 + 内部剪贴板 TTL(见 CLIPBOARD_TTL_MS);系统剪贴板不设 TTL(用户清空即止)。
// 注意:stripBigValueSync 返回新的对象树,不会污染内存里 refs.nodes 的节点数据。
// 落一份到「应用内剪贴板」(内存 + localStorage)+ 一句成功提示。
// 2026-11-26 抽出来给 DOM copy 事件用:那条通道已经把节点组同步写进系统剪贴板了,
// 不需要再走 gc.write(异步、WKWebView 常失败、而且会覆盖掉系统剪贴板里的 html 标记)。
const stageClip = (clip) => {
if (!clip || !Array.isArray(clip.nodes) || !clip.nodes.length) return false
refs.clipboardGraph = clip
try { const st = _lstore(); if (st) st.set(CLIPBOARD_KEY, clip) } catch (e) { /* 配额超限:内存版仍可用 */ }
setNotice({ type: 'ok', text: '已复制 ' + clip.nodes.length + ' 个节点' })
return true
}
const copyNodes = (ids) => {
const clip = CanvasOps.clipboardOf(refs.nodes, refs.edges, refs.groups, ids)
if (!clip) return false
refs.clipboardGraph = clip
try { const st = _lstore(); if (st) st.set(CLIPBOARD_KEY, clip) } catch (e) { /* 配额超限:内存版仍可用 */ }
// v3.24.68 统一剪贴板:同时写**系统剪贴板**(text/html 带标记 + text/plain 人话摘要),
// Ctrl+V 才能直接贴节点组,不必再记 Ctrl+Shift+V(它降级为后门)。
// 异步发起、不阻塞、不抛错;写不进去(老浏览器 / 非 HTTPS / file:// 打开)就降级并说明。
stageClip(clip)
// v3.24.68 统一剪贴板:同时写**系统剪贴板**(text/html 带标记 + text/plain 人话摘要)。
// 2026-11-26 起主通道是 DOM copy 事件(src/clipboard-graph.js 的 writeToEvent,同步、必成),
// 这里只服务"copy 事件没派发"的兜底路径(异步、WKWebView 常被拒)。
// 写失败必须记住(refs.sysClipOk=false):否则 ⌘V 会去读系统剪贴板里的**别人的旧内容**。
try {
const gc = global.IWBClipboardGraph
if (gc) {
gc.write(clip).then((ok) => {
if (!ok) setNotice({ type: 'err', text: '系统剪贴板不可写,粘贴节点请用 Ctrl+Shift+V' })
refs.sysClipOk = !!ok
if (!ok) setNotice({ type: 'err', text: '系统剪贴板不可写,节点已存入应用内剪贴板(⌘V 仍可粘贴)' })
})
}
} catch (e) { /* 写剪贴板失败绝不影响复制本身:内部那份已经写好了 */ }
setNotice({ type: 'ok', text: '已复制 ' + clip.nodes.length + ' 个节点' })
return true
}
// pasteGraph 已搬到 src/runtime-workbench-logic.js(2026-10-29)
@@ -2191,7 +2201,7 @@
setViewport({ x: railW + 28 - minX * scale, y: 28 - minY * scale, scale })
}
return { historyStore, HISTORY_IMG_REF_FIELDS, historyRefUsable, historyRefData, historyRawSnapshot, pushHistory, pushHistoryDebounced, restore, undo, redo, addPromptToLibrary, UNDO_KEYS, updateNode, clearGenResults, deleteNodes, deleteEdge, copyOffset, duplicateNodes, floatbarRefPaste, outResultUrls, copyNodes, pasteGraph, readClipboardGraph, pasteCopiedNodes, clearClipboard, cutNodes, groupOf, makeGroup, ungroup, joinGroupOf, renameGroup, duplicateGroup, saveGroupSnapshot, saveSelectionAsGroup, instantiateGroup, loadSavedGroups, findSpot, placeAtDrop, addNode, addPluginNode, addRefFromUrl, refSrcOf, refreshOutputs, deleteOutputs, loadDemo, doFit }
return { historyStore, HISTORY_IMG_REF_FIELDS, historyRefUsable, historyRefData, historyRawSnapshot, pushHistory, pushHistoryDebounced, restore, undo, redo, addPromptToLibrary, UNDO_KEYS, updateNode, clearGenResults, deleteNodes, deleteEdge, copyOffset, duplicateNodes, floatbarRefPaste, outResultUrls, stageClip, copyNodes, pasteGraph, readClipboardGraph, pasteCopiedNodes, clearClipboard, cutNodes, groupOf, makeGroup, ungroup, joinGroupOf, renameGroup, duplicateGroup, saveGroupSnapshot, saveSelectionAsGroup, instantiateGroup, loadSavedGroups, findSpot, placeAtDrop, addNode, addPluginNode, addRefFromUrl, refSrcOf, refreshOutputs, deleteOutputs, loadDemo, doFit }
}
// ── createWorkbenchSessions(2026-11-06 从 Workbench 外移;行为逐字保留)──────────────
function createWorkbenchSessions(ctx) {
+10 -1
View File
@@ -56,9 +56,18 @@
* 返回:notice / setNotice / toast / setToast / showToast
*/
function useNotifications (opts) {
const [notice, setNotice] = useState(null)
const [notice, setNoticeState] = useState(null)
const [toast, setToast] = useState(null)
const toastTimer = useRef(null)
const noticeTimer = useRef(null)
/* 错误/进行中提示 5.2s 自动收(2026-11-26)。
* 旧行为只有 toast 会消失,notice 会一直挂在状态栏 —— 粘贴失败那句"剪贴板里没有可粘贴的内容"
* 粘在顶部不动,用户过一会儿再看会以为功能坏了。成功提示(ok)保持常驻,它是"最后一次操作结果"。 */
const setNotice = (n) => {
clearTimeout(noticeTimer.current)
setNoticeState(n)
if (n && n.type && n.type !== 'ok') noticeTimer.current = setTimeout(() => setNoticeState(null), 5200)
}
const showToast = (text, type) => {
clearTimeout(toastTimer.current)
setToast({ text, type: type || 'ok' })
+28 -9
View File
@@ -276,9 +276,10 @@ test('5. TTL:11 分钟前的内部剪贴板不粘贴且被删除', async ({ pa
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await W.waitCanvasOpen(page)
const before = await page.locator('.iwb-node').count()
// v3.24.67:Ctrl+V 不再有 300ms 回退;改由 probe(~420ms)读一次剪贴板,读到过期即清理并提示。
// 因此这里等「条目被清掉」这个条件成立,而不是等固定毫秒。
// 注意:**不往系统剪贴板写内容** —— 有内容时浏览器会派发真实 paste,probe 就不会跑了。
// 2026-11-26:⌘V 现在会**主动读系统剪贴板**(mac 上没有编辑焦点时不会派发 paste 事件,
// 这是唯一通路),而系统剪贴板按设计不设 TTL(用户清空即止)。所以先把它清空 ——
// 否则测的就不是「内部剪贴板过期」,而是「系统剪贴板里还有内容」。
await page.evaluate(() => navigator.clipboard.writeText(''))
await page.keyboard.press('Control+v')
await W.poll(page, () => page.evaluate(() => localStorage.getItem('iwb_clipboard')), { timeout: 8000 }).toBeNull()
const after = await page.locator('.iwb-node').count()
@@ -669,8 +670,10 @@ test('18. 焦点在节点输入框里按 Ctrl+C 仍能复制节点(旧实现
expect(errors).toEqual([])
})
test('19. 焦点在节点输入框里粘「复制的节点」→ 明确提示,不落节点(旧实现纯静默)', async ({ page }) => {
test('19. 焦点在节点输入框里粘节点组:带提示词→粘文字;只有摘要→拦下且不污染输入框', async ({ page }) => {
await boot(page, workspace)
// 情形 A(v3.24.70 的原始诉求):复制的是**带提示词**的节点组 → 粘进输入框应该得到那段提示词文字。
// 2026-11-26 改口径:这类粘贴放行原生(拦掉等于把「复制提示词贴到别处」这个用法做没了)。
await page.keyboard.press('Control+a')
await page.keyboard.press('Control+c')
await waitGraphInClipboard(page)
@@ -678,11 +681,27 @@ test('19. 焦点在节点输入框里粘「复制的节点」→ 明确提示,
await url.click()
const before = await page.locator('.iwb-node').count()
await realPaste(page)
// 提示必须出现:旧实现连提示都没有,用户只能看到「什么都没发生」
await W.poll(page, () => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-status-item')).map((x) => String(x.textContent || '')).join(' | ')), { timeout: 8000 }).toContain('画布空白处')
const after = await page.locator('.iwb-node').count()
console.log('[check19] nodes ' + before + ' -> ' + after + '(输入框里不落节点)')
expect(after).toBe(before)
await page.waitForTimeout(400)
const val = await url.inputValue()
console.log('[check19] 带提示词 → 输入框 = ' + JSON.stringify(val))
expect(val).toBe('画布A 提示词')
expect(await page.locator('.iwb-node').count()).toBe(before)
// 情形 B(本次修的缺陷):复制的只有图片节点,摘要退化成「1 个节点」。
// 旧实现只弹提示不拦,摘要被原生粘贴打进输入框,把用户的提示词改掉了。
await url.fill('')
await clearSelection(page)
await page.locator('.iwb-node').nth(1).click()
await W.waitSelectedCount(page, 1)
await page.keyboard.press('Control+c')
await page.waitForTimeout(400)
await url.click()
await realPaste(page)
await W.poll(page, () => statusText(page), { timeout: 8000 }).toContain('画布')
const val2 = await url.inputValue()
console.log('[check19] 只有摘要 → 输入框 = ' + JSON.stringify(val2) + ';提示 = ' + JSON.stringify(await statusText(page)))
expect(val2).toBe('')
expect(await page.locator('.iwb-node').count()).toBe(before)
expect(errors).toEqual([])
})
+73
View File
@@ -137,6 +137,79 @@ eq('标记没闭合(被截断)仍尽力解出', (G.decode('<!--iwb:graph:v1:
eq('写入同步抛错 → false(不抛)', await G4.write(mkClip()), false)
}
// ---- ⑧ 双标记 + copy 事件通道(2026-11-26)----
// 背景:WKWebView 写/读剪贴板时会剥掉 HTML 注释 ⇒ 只剩 data-iwb-graph 属性可用;
// 复制改由 DOM copy 事件同步写 clipboardData(mac 上 ⌘C 被原生菜单接管时 keydown 到不了 JS)。
{
const c = mkClip()
const html = G.htmlFor(c)
ok('htmlFor 同时写了注释标记与 data-iwb-graph 属性', html.indexOf('iwb:graph:v1:') >= 0 && html.indexOf('data-iwb-graph=') >= 0)
const attrOnly = html.replace(/<!--[\s\S]*?-->/, '') // 模拟 WebKit 把注释剥掉
ok('注释被剥掉后属性仍能解回', !!G.decode(attrOnly))
eq('属性解回的节点数一致', (G.decode(attrOnly) || {}).nodes ? G.decode(attrOnly).nodes.length : -1, 2)
eq('属性用单引号包裹也能解', !!G.decode(html.replace(/data-iwb-graph="[^"]*"/, (m) => m.replace(/"/g, "'"))), true)
eq('没有标记 → null', G.decode('<div>普通网页</div>'), null)
}
{
const c = mkClip()
const dt = { data: {}, setData(k, v) { this.data[k] = v } }
const ev = { clipboardData: dt, defaultPrevented: false, preventDefault() { ev.defaultPrevented = true } }
eq('writeToEvent 返回 true', G.writeToEvent(ev, c), true)
ok('写了 text/html(带标记)', String(dt.data['text/html']).indexOf('iwb:graph:v1:') >= 0)
eq('写了 text/plain(人话摘要,不是裸 JSON)', dt.data['text/plain'], G.plainFor(c))
eq('writeToEvent 不碰 preventDefault(交给调用方)', ev.defaultPrevented, false)
eq('没有 clipboardData → false(不抛)', G.writeToEvent({}, c), false)
}
{
// bindCopy:注册 copy 监听,事件里同步写剪贴板 + 落内部剪贴板
const b = { h: {}, addEventListener(t, fn) { (b.h[t] = b.h[t] || []).push(fn) }, removeEventListener(t, fn) { const a = b.h[t] || []; const i = a.indexOf(fn); if (i >= 0) a.splice(i, 1) } }
new Function('window', 'globalThis', SRC)(b, b)
let staged = null
let notice = null
let sysOk = null
const ctx = {
ids: () => ['n1', 'n2'],
clipboardOf: () => mkClip(),
stageClip: (c) => { staged = c; notice = { type: 'ok', text: '已复制 ' + c.nodes.length + ' 个节点' }; return true },
setNotice: (n) => { notice = n },
markSys: (ok) => { sysOk = ok },
hasTextSelection: () => false,
}
let current = ctx
b.IWBClipboardGraph.bindCopy(() => current)
const fire = (ev) => (b.h.copy || []).forEach((fn) => fn(ev))
const dt = { data: {}, setData(k, v) { this.data[k] = v } }
const ev = { target: {}, clipboardData: dt, defaultPrevented: false, preventDefault() { ev.defaultPrevented = true } }
fire(ev)
ok('copy 事件:同步写进 clipboardData', String(dt.data['text/html']).indexOf('iwb:graph:v1:') >= 0)
eq('copy 事件:preventDefault(不覆盖用户其它剪贴板内容)', ev.defaultPrevented, true)
eq('copy 事件:内部剪贴板也落了一份', !!staged, true)
eq('copy 事件:标记系统剪贴板可写', sysOk, true)
ok('copy 事件:提示已复制', !!notice && String(notice.text).indexOf('已复制') >= 0)
// 有文本选区 → 让原生复制文字(不许抢)
staged = null
current = Object.assign({}, ctx, { hasTextSelection: () => true })
const ev2 = { target: {}, clipboardData: { setData() { throw new Error('不该写剪贴板') } }, defaultPrevented: false, preventDefault() { ev2.defaultPrevented = true } }
fire(ev2)
eq('有文本选区 → 不写剪贴板(原生复制文字)', staged, null)
eq('有文本选区 → 不 preventDefault', ev2.defaultPrevented, false)
// 没选中节点 → 说一句,别静默
notice = null
current = Object.assign({}, ctx, { ids: () => [] })
fire({ target: {}, clipboardData: { setData() {} }, defaultPrevented: false, preventDefault() {} })
ok('没选中节点 → 提示没有可复制的内容', !!notice && String(notice.text).indexOf('没有可复制') >= 0)
// 解绑后必须真的摘掉监听(否则回到首页按 ⌘C 会去复制已卸载那份 refs)
b.IWBClipboardGraph.unbindCopy()
staged = null
current = ctx
fire({ target: {}, clipboardData: { setData() { staged = 'wrote' } }, defaultPrevented: false, preventDefault() {} })
eq('unbindCopy 之后 copy 事件不再被处理', staged, null)
// 重新绑定可以恢复(Workbench 重挂载)
b.IWBClipboardGraph.bindCopy(() => current)
fire({ target: {}, clipboardData: { setData() {} }, defaultPrevented: false, preventDefault() {} })
eq('重新 bindCopy 后恢复处理', !!staged, true)
}
console.log('\n' + (fail ? '❌' : '✅') + ' clipboard-graph: ' + pass + ' passed, ' + fail + ' failed')
if (fail) process.exit(1)
})()
+84 -31
View File
@@ -40,7 +40,7 @@ function makeCtx(over) {
const log = []
let nodes = [{ id: 'seed', type: 'prompt', x: 0, y: 0, data: { text: 'seed' } }]
const ctx = {
refs: { pasteGroupUntil: 0, pasteProbe: 0, clipExpired: false },
refs: { pasteGroupUntil: 0, pasteSwallowUntil: 0, clipExpired: false },
ui: {},
readClipboardGraph: () => null,
pasteCopiedNodes: () => { log.push('pasteGroup'); return true },
@@ -55,7 +55,7 @@ function makeCtx(over) {
pushHistory: () => log.push('history'),
commitCanvas: (next) => { nodes = next; log.push('commit:' + next.length) },
setSel: (ids) => log.push('sel:' + ids.length),
setNotice: (n) => log.push('notice:' + n.type + ':' + n.text),
setNotice: (n) => log.push(n ? ('notice:' + n.type + ':' + n.text) : 'notice:null'),
importImage: (u, opts, cb) => cb({ ok: true, data: 'data:image/png;base64,AAAA' }),
}
return Object.assign(ctx, over || {}, { log })
@@ -112,7 +112,7 @@ function makeCtx(over) {
ok('空剪贴板 + 内部也空 → 提示「没有可粘贴的内容」', ctx.log.some((x) => x.indexOf('没有可粘贴的内容') > 0))
}
{ // 过期要说清是过期,而不是「没有内容」
const ctx = makeCtx({ pasteCopiedNodes: () => false, refs: { pasteGroupUntil: 0, pasteProbe: 0, clipExpired: true } })
const ctx = makeCtx({ pasteCopiedNodes: () => false, refs: { pasteGroupUntil: 0, pasteSwallowUntil: 0, clipExpired: true } })
P.handle(pasteEv({}), ctx)
ok('空剪贴板 + 内部已过期 → 提示重新复制', ctx.log.some((x) => x.indexOf('已过期') > 0))
}
@@ -245,16 +245,26 @@ function makeCtx(over) {
ok('输入框内粘文件 → 也给提示(不再静默)', ctx.log.some((x) => x.indexOf('输入框') > 0))
}
{
// 焦点在输入框里粘「刚复制的节点组」—— 旧实现完全静默(剪贴板里还带着 text/plain 摘要,
// 用户很容易以为会贴出提示词)。v3.24.70:必须给一句「先点一下画布空白处」。
// 焦点在输入框、指针也不在画布、剪贴板里只有「N 个节点」摘要。
// 2026-11-26 改口径:旧实现只提示不改行为 → 摘要(text/plain)被原生粘贴打进输入框,污染提示词。
// 现在必须 preventDefault(一点摘要都不许落进输入框),并指路「鼠标移到画布上再按 ⌘V」。
const ctx = makeCtx()
const html = win.IWBClipboardGraph.htmlFor({ app: 'image-workbench', type: 'iwb-clipboard', at: Date.now(), nodes: [{ id: 'r1', type: 'ref', x: 0, y: 0, data: {} }], edges: [], groups: [] })
const ev = pasteEv({ html, text: '1 个节点' })
eq('输入框内粘摘要 → 消费这次 paste', P.handle(ev, ctx, true), true)
eq('输入框内粘摘要 → preventDefault(摘要不许落进输入框)', ev.defaultPrevented, true)
ok('输入框内粘摘要 → 提示「鼠标移到画布上」', ctx.log.some((x) => x.indexOf('notice:err') === 0 && x.indexOf('画布') > 0))
eq('输入框内粘摘要 → 不贴节点组', ctx.log.filter((x) => x.indexOf('pasteGraph') === 0).length, 0)
eq('输入框内粘摘要 → 不落节点', ctx.log.filter((x) => x.startsWith('commit')).length, 0)
}
{
// 剪贴板里带着提示词全文 → 放行原生(复制提示词贴进另一个输入框是正经用法)
const ctx = makeCtx()
const html = win.IWBClipboardGraph.htmlFor({ app: 'image-workbench', type: 'iwb-clipboard', at: Date.now(), nodes: [{ id: 'n1', type: 'prompt', x: 0, y: 0, data: { text: 'hello' } }], edges: [], groups: [] })
const ev = pasteEv({ html, text: 'hello' })
eq('输入框内粘节点组 → 不接管', P.handle(ev, ctx, true), false)
eq('输入框内粘节点组 → 不 preventDefault', ev.defaultPrevented, false)
ok('输入框内粘节点组 → 明确提示「先点一下画布空白处」', ctx.log.some((x) => x.indexOf('notice:err') === 0 && x.indexOf('画布空白处') > 0))
eq('输入框内粘节点组 → 不贴节点组', ctx.log.filter((x) => x.indexOf('pasteGraph') === 0).length, 0)
eq('输入框内粘节点组 → 不落节点', ctx.log.filter((x) => x.startsWith('commit')).length, 0)
eq('输入框内粘「带提示词的节点」→ 不接管(原生贴文字)', P.handle(ev, ctx, true), false)
eq('输入框内粘「带提示词的节点」→ 不 preventDefault', ev.defaultPrevented, false)
eq('输入框内粘「带提示词的节点」→ 不落节点', ctx.log.filter((x) => x.startsWith('commit')).length, 0)
}
{
// 画布上(editable=false)同样的图片必须照常建节点 —— 证明 editable 只影响输入框这一路
@@ -263,33 +273,53 @@ function makeCtx(over) {
eq('画布上(editable=false)图片链接照常建 ref', P.handle(ev, ctx, false), true)
}
// ---- ⑧ probe:Ctrl+V 一直没等到 paste 事件时说清楚 ----
// ---- ⑧ ⌘V 主动粘贴(2026-11-26 keydown 通道)----
// 背景:mac 上焦点不在输入框时根本不会派发 paste 事件(只有 keydown),旧实现只弹一句
// 「请按 Ctrl+Shift+V」。现在 keydown 直接接管:先让原生走(150ms 内等到 paste 就交给 handle),
// 等不到才自己读剪贴板 —— 顺序是 富读取 → 原生文本 → 原生图片 → 内部剪贴板。
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
;(async () => {
{
const ctx = makeCtx({ readClipboardGraph: () => ({ nodes: [{ id: 'a' }], edges: [], groups: [] }) })
P.probe(ctx)
await sleep(520)
ok('probe:内部剪贴板有内容 → 提示改用 Ctrl+Shift+V',
ctx.log.some((x) => x.indexOf('Ctrl+Shift+V') > 0))
eq('probe:只提示,不代替用户粘贴', ctx.log.filter((x) => x === 'pasteGroup').length, 0)
// 指针不在画布、没有编辑焦点 → 仍然接管(否则 mac 上 ⌘V 又变成"没反应")
const ctx = makeCtx()
eq('pasteFromKey:无编辑焦点 → 接管', P.pasteFromKey(ctx), true)
await sleep(200)
eq('pasteFromKey:没等到 paste 事件 → 回退贴内部剪贴板', ctx.log.filter((x) => x === 'pasteGroup').length, 1)
}
{
const ctx = makeCtx({
refs: { pasteGroupUntil: 0, pasteProbe: 0, clipExpired: true },
readClipboardGraph: () => null,
})
P.probe(ctx)
await sleep(520)
ok('probe:内部剪贴板已过期 → 提示重新复制', ctx.log.some((x) => x.indexOf('已过期') > 0))
// 有 paste 事件(Windows / WebView2)→ 定时器不许再贴一次
const ctx = makeCtx()
P.pasteFromKey(ctx)
ctx.refs.pasteEventAt = Date.now()
await sleep(220)
eq('pasteFromKey:paste 事件已处理 → 不重复贴', ctx.log.filter((x) => x === 'pasteGroup').length, 0)
}
{
// 真实 paste 到达会把 pasteProbe 清零 → probe 不该再提示
const ctx = makeCtx({ readClipboardGraph: () => ({ nodes: [{ id: 'a' }] }) })
P.probe(ctx)
ctx.refs.pasteProbe = 0
await sleep(520)
eq('probe:收到真实 paste 后静默', ctx.log.length, 0)
// 浮层打开 → 不接管,交回原生
const ctx = makeCtx({ ui: { settingOpen: true } })
eq('pasteFromKey:设置面板开着 → 不接管', P.pasteFromKey(ctx), false)
await sleep(200)
eq('pasteFromKey:不接管时什么也不做', ctx.log.length, 0)
}
{
// 内部剪贴板也空 → 明确提示,且文案不再教用户"点空白处"
const ctx = makeCtx({ pasteCopiedNodes: () => false })
P.pasteFromKey(ctx)
await sleep(220)
const msgs = ctx.log.map(String).join(' | ')
ok('pasteFromKey:全空 → 有错误提示', /notice:err/.test(msgs))
ok('pasteFromKey:提示不再说「先点一下画布空白处」', msgs.indexOf('画布空白处') < 0)
}
{
// 主动粘贴刚落地 → 紧随其后的同一次 paste 事件必须被吞掉(否则贴两份)
const ctx = makeCtx()
P.pasteFromKey(ctx)
await sleep(220)
eq('主动粘贴已落地(内部剪贴板)', ctx.log.filter((x) => x === 'pasteGroup').length, 1)
const ev = pasteEv({ text: 'hello' })
eq('主动粘贴后 400ms 内的重复 paste → 被吞掉', P.handle(ev, ctx), true)
eq('被吞掉的 paste → preventDefault', ev.defaultPrevented, true)
eq('被吞掉的 paste → 不落节点', ctx.log.filter((x) => x.startsWith('commit')).length, 0)
}
// ---- ⑥ 粘贴落点跟随指针(v3.24.69 用户裁定:粘贴要跟鼠标)----
@@ -311,7 +341,7 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const calls = []
const ctxOf = () => makeCtx({
canvasEl,
refs: { pasteGroupUntil: 0, pasteProbe: 0, clipExpired: false, viewport: { x: 0, y: 0, scale: 1 } },
refs: { pasteGroupUntil: 0, pasteSwallowUntil: 0, clipExpired: false, viewport: { x: 0, y: 0, scale: 1 } },
findSpot: (type, seed, opts) => { calls.push({ type, seed, opts }); return { x: 100, y: 200 } },
pasteGraph: (clip, at2) => { calls.push({ graph: clip, at: at2 }); return true },
})
@@ -334,6 +364,29 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
eq('指针在画布外 → seed 为 undefined(退回视口中心)', calls.find((c) => c.type === 'prompt').seed, undefined)
}
// ── 焦点在输入框 + 指针在画布:节点组必须改贴到画布(2026-11-26)────────────
// 用户实测的坑:复制节点 → 点了一下节点内的空白(宿主 preventDefault,焦点没走)→ ⌘V 没反应。
// 现在由 paste 事件在「指针在画布」时接管:blur + 贴到指针处。
{
const rect = { left: 100, top: 50, width: 800, height: 600, right: 900, bottom: 650 }
const canvasEl = { el: { getBoundingClientRect: () => rect } }
const fire = (x, y) => (win.h.pointermove || []).forEach((fn) => fn({ clientX: x, clientY: y }))
const baseRefs = { pasteGroupUntil: 0, pasteSwallowUntil: 0, clipExpired: false, viewport: { x: 0, y: 0, scale: 1 } }
fire(500, 350)
const calls = []
const ctx = makeCtx({ canvasEl, refs: Object.assign({}, baseRefs), pasteGraph: (clip, at) => { calls.push({ clip, at }); return true } })
const clip = { nodes: [{ id: 'r1', type: 'ref', x: 0, y: 0, data: {} }], edges: [], groups: [] }
const ev = pasteEv({ html: win.IWBClipboardGraph.htmlFor(clip), text: '1 个节点' })
eq('输入框内 + 指针在画布 → 接管这次 paste', P.handle(ev, ctx, true), true)
eq('输入框内 + 指针在画布 → preventDefault(摘要不落输入框)', ev.defaultPrevented, true)
eq('输入框内 + 指针在画布 → 贴到指针处', JSON.stringify(calls[0] && calls[0].at), '{"x":400,"y":300}')
// 指针不在画布:回到上面那条「拦下摘要 + 指路」的行为
fire(10, 10)
const ctx2 = makeCtx({ canvasEl, refs: Object.assign({}, baseRefs) })
eq('指针移出画布 → 只拦不贴', P.handle(pasteEv({ html: win.IWBClipboardGraph.htmlFor(clip), text: '1 个节点' }), ctx2, true), true)
eq('指针移出画布 → 不贴节点组', ctx2.log.filter((x) => x.indexOf('pasteGraph') === 0).length, 0)
}
// ── 同图去重(v3.24.75)────────────────────────────────────────────────────
// 判据与语义边界见 src/image-dedupe.js:只认本地图片字节,URL 与复制节点组不参与。
// 这里测分发层的取舍(该拦的拦、该落的落、提示必须说清);真实的"压缩后字节指纹"
+3 -2
View File
@@ -170,7 +170,7 @@ const MAX_SRC_COMPONENT_LINES = 531
// · 图标解析统一(右键菜单 + 设置页走同一解析器,2 行) +2
// 通用件(pick/grant/stat/readDataUrl/readBlob/参数校验)全部在 src/image-file-ref.js
// 与 src/plugin-api-images.js,app.js 只做装配。
const MAX_APP_JS_LINES = 9190 // +1(2026-11-26 相册外部路径重启复授权装配;逻辑在 src/image-file-ref.js) // +5(2026-11-26 标注覆盖保存:桌面端不再生成死 __cache(4 行)+ 插件 saveNodeImage 装配(1 行);事务逻辑在 src/runtime-workbench-logic.js)
const MAX_APP_JS_LINES = 9205 // +15(2026-11-26 复制/粘贴通道重写:DOM copy 事件装配、pasteCtx 增补实时选择/剪贴板读写、⌘V 改为主动粘贴;逻辑在 src/clipboard-graph.js 的 bindCopy 与 src/clipboard-paste.js 的 pasteFromKey) // +1(2026-11-26 相册外部路径重启复授权装配;逻辑在 src/image-file-ref.js) // +5(2026-11-26 标注覆盖保存:桌面端不再生成死 __cache(4 行)+ 插件 saveNodeImage 装配(1 行);事务逻辑在 src/runtime-workbench-logic.js)
const MAX_APP_JS_SHARE = 0.40
// ── 历史记账(供回溯,逐条保留)──────────────────────────────────────────────
@@ -213,7 +213,8 @@ 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 = 3046 // 2026-11-18 v3.25.21:模态层指针守卫(2 行)
const MAX_WORKBENCH_LINES = 3060 // 2026-11-26 复制/粘贴通道重写(+14:refs 新增粘贴时间戳/系统剪贴板可信标记、pasteCtx 增补 ids/clipboardOf/stageClip/readNativeText、bindCopy 装配)
// 2026-11-18 v3.25.21:模态层指针守卫(2 行)
// 实测 3090 → 2998(省 92):① 生成取消族 cancelRunsFor/cancelRun/cancelTaskJobs
// → src/runtime-workbench-logic.js 的 createCancelActions(−53);② 工作区列表写回族
// persistWs/duplicateWs → 同文件 createWorkspaceListActions(−30);③ 死代码 runAll