@capyclaw/browser-suite 0.2.38 → 0.2.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/composition.lock.json +23 -23
  2. package/contract/browser-contract.json +1 -1
  3. package/dsh-suite.json +26 -16
  4. package/node_modules/@capyclaw/asset-service/dsh-suite.json +1 -1
  5. package/node_modules/@capyclaw/asset-service/package.json +1 -1
  6. package/node_modules/@capyclaw/asset-service/src/index.mjs +4 -3
  7. package/node_modules/@capyclaw/browser-skill-api/contract/browser-contract.json +1 -1
  8. package/node_modules/@capyclaw/browser-skill-api/package.json +1 -1
  9. package/node_modules/@capyclaw/browser-skill-api/skills/browser-api/references/tool-contract.md +1 -1
  10. package/node_modules/@capyclaw/browser-skill-browser/contract/browser-contract.json +1 -1
  11. package/node_modules/@capyclaw/browser-skill-browser/package.json +1 -1
  12. package/node_modules/@capyclaw/browser-skill-ops/contract/browser-contract.json +1 -1
  13. package/node_modules/@capyclaw/browser-skill-ops/package.json +1 -1
  14. package/node_modules/@capyclaw/browser-workbench/contract/browser-contract.json +1 -1
  15. package/node_modules/@capyclaw/browser-workbench/package.json +7 -7
  16. package/node_modules/@capyclaw/browser-workbench/plugin.mjs +13 -1
  17. package/node_modules/@capyclaw/browser-workbench/server/activate-log.mjs +66 -0
  18. package/node_modules/@capyclaw/browser-workbench/server/contract.mjs +1 -1
  19. package/node_modules/@capyclaw/browser-workbench/server/embedded-host.mjs +13 -1
  20. package/node_modules/@capyclaw/browser-workbench/server/engine.mjs +11 -4
  21. package/node_modules/@capyclaw/browser-workbench/server/routes/api.mjs +2 -2
  22. package/node_modules/@capyclaw/browser-workbench/server/shared/SHARED_MANIFEST.json +4 -4
  23. package/node_modules/@capyclaw/browser-workbench/ui/app.js +87 -10
  24. package/node_modules/@capyclaw/document-workbench/package.json +6 -3
  25. package/node_modules/@capyclaw/document-workbench/src/client/index.mjs +56 -3
  26. package/node_modules/@capyclaw/document-workbench/src/client/visibility.mjs +112 -0
  27. package/node_modules/@capyclaw/document-workbench/src/model/manifest.mjs +6 -4
  28. package/node_modules/@capyclaw/document-workbench/src/model/ops.mjs +7 -2
  29. package/node_modules/@capyclaw/document-workbench/src/session/index.mjs +8 -0
  30. package/node_modules/@capyclaw/document-workbench/src/store/file-backend.mjs +17 -10
  31. package/node_modules/@capyclaw/document-workbench/src/store/projection.mjs +39 -0
  32. package/node_modules/@capyclaw/document-workbench/src/testing/index.mjs +14 -11
  33. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  34. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +3 -1
  35. package/node_modules/@capyclaw/foundation/abi/index.mjs +15 -0
  36. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  37. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +21 -4
  38. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +5 -1
  39. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +5 -2
  40. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +4 -0
  41. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +13 -3
  42. package/node_modules/@capyclaw/foundation/package.json +1 -1
  43. package/node_modules/@capyclaw/plugin-kit/package.json +3 -1
  44. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +5 -2
  45. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  46. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  47. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +13 -5
  48. package/node_modules/@capyclaw/portal/package.json +1 -1
  49. package/node_modules/@capyclaw/service-broker/README.md +1 -1
  50. package/node_modules/@capyclaw/service-broker/lib/host.mjs +11 -6
  51. package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +13 -5
  52. package/node_modules/@capyclaw/service-broker/package.json +1 -1
  53. package/node_modules/@capyclaw/service-host/dsh-suite.json +1 -1
  54. package/node_modules/@capyclaw/service-host/package.json +1 -1
  55. package/node_modules/@capyclaw/service-host/src/index.mjs +13 -22
  56. package/node_modules/@capyclaw/tool-host/dsh-suite.json +1 -1
  57. package/node_modules/@capyclaw/tool-host/lib/host.mjs +15 -4
  58. package/node_modules/@capyclaw/tool-host/package.json +1 -1
  59. package/node_modules/@capyclaw/tool-host/src/index.mjs +19 -5
  60. package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +71 -3
  61. package/package.json +12 -12
@@ -27,6 +27,7 @@
27
27
  lastFrameAt: 0,
28
28
  hasFrame: false,
29
29
  fallbackTimer: null,
30
+ hintTimer: null,
30
31
  statusBusy: false,
31
32
  tabsSig: null,
32
33
  }
@@ -81,12 +82,15 @@
81
82
  els.placeholder.hidden = true
82
83
  els.frame.classList.add('on')
83
84
  els.hint.hidden = false
84
- /* 提示只在第一帧后露 5 秒,之后让位给画面本身。 */
85
- setTimeout(function () { els.hint.hidden = true }, 5000)
85
+ /* 提示只在第一帧后露 5 秒,之后让位给画面本身。句柄存起来,hideFrame 时取消,
86
+ 避免画面已隐藏后旧定时器又把 hint 状态改回去(竞态)。 */
87
+ if (state.hintTimer) clearTimeout(state.hintTimer)
88
+ state.hintTimer = setTimeout(function () { els.hint.hidden = true; state.hintTimer = null }, 5000)
86
89
  }
87
90
 
88
91
  function hideFrame() {
89
92
  state.hasFrame = false
93
+ if (state.hintTimer) { clearTimeout(state.hintTimer); state.hintTimer = null }
90
94
  els.frame.classList.remove('on')
91
95
  els.frame.removeAttribute('src')
92
96
  els.placeholder.hidden = false
@@ -107,6 +111,9 @@
107
111
 
108
112
  function connectLive() {
109
113
  if (live) return
114
+ /* 渲染面挂起时不建帧订阅:SSE 关闭使 watching=frameSubs.size 归零,
115
+ * 引擎可空闲回收(标准 §5 的期望行为)。恢复前台由 startRenderLoops 重开。 */
116
+ if (renderSuspended) return
110
117
  if (typeof EventSource !== 'function') { startFallback(); return }
111
118
  try {
112
119
  live = new EventSource(apiPath('/api/live'))
@@ -126,6 +133,7 @@
126
133
  /* SSE 被中间层吃掉(或桌面 webview 不支持)时,退回 1.2s 截图,至少还能看。 */
127
134
  function startFallback() {
128
135
  if (state.fallbackTimer !== null) return
136
+ if (renderSuspended) return
129
137
  state.fallbackTimer = setInterval(function () {
130
138
  if (!state.running) return
131
139
  fetch(apiPath('/api/screenshot')).then(function (r) {
@@ -148,6 +156,72 @@
148
156
  state.fallbackTimer = null
149
157
  }
150
158
 
159
+ /* ---------- 表面可见性(渲染面生命周期,标准 §2/§5) ---------- */
160
+ /* 本 UI 无构建、原样拷贝部署(build-plugin.mjs 的 copyDirs),不能 import 共享包,
161
+ * 故内联一个最小 visibility 订阅器(纯订阅,无桥)。协议常量真源:
162
+ * C/packages/capyclaw-foundation/abi/visibility.mjs —— 改那边必须同步这里。
163
+ * iframe 内 document.hidden 只反映顶层 tab,被宿主藏起来不触发 visibilitychange,
164
+ * 表面可见性只能由宿主 postMessage 告知;hidden 必须挂起渲染面。 */
165
+ var VISIBILITY_MESSAGE = 'capyclaw:workbench:visibility'
166
+ var VISIBILITY_ACK_MESSAGE = 'capyclaw:workbench:visibility-ack'
167
+ var VISIBILITY_STATES = ['foreground', 'background', 'hidden', 'detached']
168
+
169
+ var renderSuspended = false
170
+ var statusTimer = null
171
+ var watchdogTimer = null
172
+
173
+ /* watchdog:SSE 断流超过 3s 且浏览器在跑 → 退回截图轮询。 */
174
+ function watchdogTick() {
175
+ if (!state.running) { stopFallback(); return }
176
+ if (state.fallbackTimer !== null) return
177
+ if (Date.now() - state.lastFrameAt > 3000) startFallback()
178
+ }
179
+
180
+ /* 渲染面循环的唯一起停点:句柄 null-guard,快速切换不会叠出重复定时器。
181
+ * 起 = 状态轮询 + SSE 看门狗 + 帧订阅(SSE,无 SSE 时兜底截屏)。 */
182
+ function startRenderLoops() {
183
+ if (statusTimer === null) statusTimer = setInterval(pollStatus, 2000)
184
+ if (watchdogTimer === null) watchdogTimer = setInterval(watchdogTick, 2000)
185
+ connectLive()
186
+ }
187
+
188
+ /* 停 = 状态轮询 + SSE 看门狗 + 兜底截屏 + 帧订阅全清。SSE 关闭使
189
+ * watching=frameSubs.size 归零 → 引擎可空闲回收(期望行为,标准 §5)。 */
190
+ function stopRenderLoops() {
191
+ if (statusTimer !== null) { clearInterval(statusTimer); statusTimer = null }
192
+ if (watchdogTimer !== null) { clearInterval(watchdogTimer); watchdogTimer = null }
193
+ stopFallback()
194
+ if (live) { try { live.close() } catch (e) { /* ignore */ } live = null }
195
+ }
196
+
197
+ /* 幂等:同态重复消息不重启/重停。hidden/detached 挂起渲染面;
198
+ * foreground/background 恢复(background 只是失焦、仍可见,渲染面保持运转)。 */
199
+ function setRenderVisibility(next) {
200
+ var suspend = next === 'hidden' || next === 'detached'
201
+ if (suspend === renderSuspended) return
202
+ renderSuspended = suspend
203
+ if (suspend) { stopRenderLoops(); return }
204
+ startRenderLoops()
205
+ /* 回前台立即补一次状态:隐藏期间引擎可能已被空闲回收,
206
+ * 靠这次 pollStatus 的 restorable→resume 把上次的页面找回来。 */
207
+ pollStatus()
208
+ }
209
+
210
+ function onVisibilityMessage(event) {
211
+ /* 只认同源宿主(浮标/portal 与本页同 origin);跨源消息一律丢弃。 */
212
+ if (event.origin !== location.origin) return
213
+ var data = event.data
214
+ if (!data || data.type !== VISIBILITY_MESSAGE) return
215
+ if (VISIBILITY_STATES.indexOf(data.state) === -1) return
216
+ setRenderVisibility(data.state)
217
+ try {
218
+ if (event.source) {
219
+ event.source.postMessage({ type: VISIBILITY_ACK_MESSAGE, state: data.state, sid: data.sid }, event.origin)
220
+ }
221
+ } catch (e) { /* 宿主已关闭等场景忽略 */ }
222
+ }
223
+ window.addEventListener('message', onVisibilityMessage)
224
+
151
225
  /* ---------- 坐标映射与输入回放 ---------- */
152
226
 
153
227
  /** object-fit: contain 的内容框 → 页面 CSS 像素坐标。 */
@@ -433,15 +507,18 @@
433
507
  .catch(function () { /* 恢复失败不阻塞工作台 */ })
434
508
  }
435
509
  })
436
- setInterval(pollStatus, 2000)
437
- /* watchdog:SSE 断流超过 3s 且浏览器在跑 → 退回截图轮询。 */
438
- setInterval(function () {
439
- if (!state.running) { stopFallback(); return }
440
- if (state.fallbackTimer !== null) return
441
- if (Date.now() - state.lastFrameAt > 3000) startFallback()
442
- }, 2000)
510
+ /* 渲染面循环统一由 startRenderLoops 起(状态轮询 2s + SSE 看门狗 2s + 帧订阅),
511
+ * 宿主 visibility 消息 hidden 时经 stopRenderLoops 全停、foreground 时重建。 */
512
+ startRenderLoops()
513
+
514
+ /* 真实卸载:清渲染面循环并摘订阅监听(新增定时器/监听皆可清理);
515
+ * bfcache 冻结(persisted)保持原样——定时器被冻结而非销毁,恢复时自会续跑。 */
516
+ window.addEventListener('pagehide', function (event) {
517
+ if (event && event.persisted) return
518
+ stopRenderLoops()
519
+ window.removeEventListener('message', onVisibilityMessage)
520
+ })
443
521
 
444
- connectLive()
445
522
  // 提示条:画面出现后第一次点击就藏起来
446
523
  els.frame.addEventListener('focus', function () { els.hint.hidden = true }, { once: true })
447
524
  })()
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/document-workbench",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "通用文档工作台框架:版本化文档会话、命令注册、桥路由、浏览器编辑器客户端与截图协议。",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -13,16 +13,19 @@
13
13
  "./ops": "./src/ops/index.mjs",
14
14
  "./bridge": "./src/bridge/index.mjs",
15
15
  "./client": "./src/client/index.mjs",
16
+ "./client/visibility": "./src/client/visibility.mjs",
16
17
  "./screenshot": "./src/client/screenshot.mjs",
17
18
  "./testing": "./src/testing/index.mjs",
18
19
  "./package.json": "./package.json",
19
- "./store/file-backend": "./src/store/file-backend.mjs"
20
+ "./store/file-backend": "./src/store/file-backend.mjs",
21
+ "./store/projection": "./src/store/projection.mjs"
20
22
  },
21
23
  "publishConfig": {
22
24
  "access": "public"
23
25
  },
24
26
  "dependencies": {
25
- "@capyclaw/plugin-kit": "^0.2.0"
27
+ "@capyclaw/plugin-kit": "^0.2.0",
28
+ "@capyclaw/foundation": "^0.1.1"
26
29
  },
27
30
  "files": [
28
31
  "src/",
@@ -11,13 +11,27 @@
11
11
  * 一条不变量替代散落的自觉检查,漏检也不会污染共享画面。
12
12
  * D 确定性停机——stop() 可 await(排水在飞 pump/shoot),调用方确知旧 client 安静后
13
13
  * 再 restore 新会话,取代「睡 3.5s 再 re-assert」的补丁。
14
+ *
15
+ * 表面生命周期(docs/SURFACE-LIFECYCLE-STANDARD.md P2/P3):本客户端的桥接/仲裁面
16
+ * (claimLoop / pump / 心跳 / pushState)永远在线、与可见性无关,绝不节流;新增的
17
+ * 可见性订阅只把宿主信号转成 onVisibility 回调,由编辑器适配器挂起渲染面。
14
18
  */
15
19
 
20
+ import { createVisibilitySubscriber } from './visibility.mjs'
21
+ /* 心跳节奏单一真源(P2-13b):与 plugin-kit heartbeat-worker 同拍,消除 4s/3s 漂移。
22
+ * 该常量模块零依赖、browser-safe,可被本客户端 bundle 直接 import。 */
23
+ import { HEARTBEAT_INTERVAL_MS } from '@capyclaw/plugin-kit/editor/heartbeat'
24
+
25
+ /* 订阅器连同协议常量一并透出,消费者从 /client 一个入口即可拿到。 */
26
+ export { createVisibilitySubscriber } from './visibility.mjs'
27
+
16
28
  const DEFAULTS = {
17
29
  pollTimeoutSec: 3,
18
30
  claimRetryMs: 800,
19
31
  activeClaimRetryMs: 1500,
20
- heartbeatMs: 3000,
32
+ /* 心跳间隔取 plugin-kit 单一真源 HEARTBEAT_INTERVAL_MS(3s),与 heartbeat-worker.js
33
+ * 的 setInterval 字面量同拍(worker 侧由 plugin-kit drift 测试钉死,防再次漂移)。 */
34
+ heartbeatMs: HEARTBEAT_INTERVAL_MS,
21
35
  stateDebounceMs: 800,
22
36
  errorRetryMs: 500,
23
37
  shotIdleMs: 3000,
@@ -61,6 +75,9 @@ export function createEditorClient({
61
75
  intervals = {},
62
76
  onStatus = () => {},
63
77
  onNote = () => {},
78
+ /* 渲染面可见性回调(标准 §4):宿主信号 → 适配器挂起/恢复渲染。
79
+ * 只影响渲染面;桥接面节奏不受它驱动(P2/P3)。 */
80
+ onVisibility = () => {},
64
81
  } = {}) {
65
82
  if (typeof api !== 'function') throw new Error('createEditorClient 需要 api(path, init)')
66
83
  if (!adapter || typeof adapter.load !== 'function' || typeof adapter.dump !== 'function') {
@@ -99,6 +116,10 @@ export function createEditorClient({
99
116
  wakeFlag: false,
100
117
  wakeResolve: null,
101
118
  wakeListeners: [],
119
+ /* 渲染面可见性(标准 §3/§4):初始 foreground,宿主信号驱动迁移。
120
+ * 订阅器在 claimLoop 注册唤醒监听处创建并 start,stop() 一并摘除。 */
121
+ visibilityState: 'foreground',
122
+ visibilitySubscriber: null,
102
123
  /* A:结构化取消——stop 即 abort,在飞请求立刻 reject。 */
103
124
  abort: new AbortController(),
104
125
  /* D:可 await 停机排水——记录在飞 pump/shoot 任务,stop 等它们 settle。 */
@@ -251,7 +272,9 @@ export function createEditorClient({
251
272
  /* 影子不监听单例 storage 事件(它不写单例键,也不因 GUI 写键而待命);
252
273
  * 影子的待命/让位一律由租约状态驱动。 */
253
274
  if (!shadow && storage && typeof window !== 'undefined' && window.addEventListener) {
254
- window.addEventListener('storage', (event) => {
275
+ /* 登记进 st.wakeListeners:stop() 统一摘除。就地换会话反复 create/stop 时
276
+ * 匿名监听会连同整个 st(含截图缓存)泄漏在 window 上。 */
277
+ const onSingleton = (event) => {
255
278
  if (event.key === st.singletonKey && event.newValue && event.newValue !== st.clientId) {
256
279
  if (st.active) {
257
280
  st.active = false
@@ -260,7 +283,9 @@ export function createEditorClient({
260
283
  note('')
261
284
  }
262
285
  }
263
- })
286
+ }
287
+ window.addEventListener('storage', onSingleton)
288
+ st.wakeListeners.push([window, 'storage', onSingleton])
264
289
  }
265
290
 
266
291
  /* 网络恢复 / 回到前台 / 标签页重新可见时立即唤醒重试,不等满退避间隔。
@@ -277,6 +302,23 @@ export function createEditorClient({
277
302
  st.wakeListeners.push([document, 'visibilitychange', onVisible])
278
303
  }
279
304
 
305
+ /* 渲染面可见性订阅(标准 §4 信号通道):宿主 postMessage → onVisibility,
306
+ * 编辑器适配器据此挂起/恢复渲染。上面的 online/focus/visibilitychange 只是
307
+ * 桥接面的「回来即唤醒重连」,与表面可见性正交,两者互不替代。
308
+ *
309
+ * P2/P3 边界:本订阅【只】驱动渲染面。claimLoop 的 claim 重试、pump 长轮询、
310
+ * 心跳(Worker 4s / 主线程降级 3s)、pushState 防抖 800ms 在任何可见性状态
311
+ * 下都保持原节奏——隐藏绝不释放租约、绝不打断 AI 写入(标准 §5 桥接面列)。 */
312
+ if (!st.visibilitySubscriber) {
313
+ st.visibilitySubscriber = createVisibilitySubscriber({
314
+ onState: (state) => {
315
+ st.visibilityState = state
316
+ onVisibility(state)
317
+ },
318
+ })
319
+ st.visibilitySubscriber.start()
320
+ }
321
+
280
322
  /* 从第一刻就开始看内容:待命窗口也要跟上,不能等抢到租约才第一次读。
281
323
  * pump() 自己幂等(st.pumping 守着),activate() 里再调一次是空操作;
282
324
  * 写、截图、回执仍然只由 active 窗口做。 */
@@ -587,6 +629,14 @@ export function createEditorClient({
587
629
  try { target.removeEventListener(type, handler) } catch { /* ignore */ }
588
630
  }
589
631
  st.wakeListeners = []
632
+ /* 渲染面订阅对称拆卸(P6):摘除 message/visibilitychange 监听,不泄漏。 */
633
+ try { st.visibilitySubscriber?.stop() } catch { /* ignore */ }
634
+ st.visibilitySubscriber = null
635
+ /* 单例键只进不出会让 localStorage 键随会话数无界累积(ppt 每会话一个键)。
636
+ * 停用时若键仍归本 client 所有则删除;归别的窗口则不动。 */
637
+ if (!shadow && storage) {
638
+ try { if (storage.getItem(st.singletonKey) === st.clientId) storage.removeItem(st.singletonKey) } catch { /* quota / privacy mode */ }
639
+ }
590
640
  wake()
591
641
  try { st.unsubscribe?.() } catch { /* ignore */ }
592
642
  st.unsubscribe = null
@@ -601,6 +651,9 @@ export function createEditorClient({
601
651
 
602
652
  return {
603
653
  state: st,
654
+ /* 渲染面当前可见性(标准 §3):foreground/background/hidden/detached。
655
+ * 只读投影;迁移由宿主信号驱动,桥接面不读它来节流。 */
656
+ get visibilityState() { return st.visibilityState },
604
657
  claim,
605
658
  ensureLinked,
606
659
  restore,
@@ -0,0 +1,112 @@
1
+ /**
2
+ * iframe 侧可见性订阅器(表面生命周期标准 §4 统一信号通道)。
3
+ *
4
+ * 宿主(portal-hud + window-kit)是表面可见性的唯一真源:iframe 被宿主
5
+ * display:none 时,iframe 内部 document.hidden 并不改变(它只跟随顶层 tab),
6
+ * 所以「被藏起来」只能由宿主经 postMessage 显式告知。本订阅器把宿主信号
7
+ * 转成 onState 回调,交给编辑器适配器去挂起/恢复渲染面。
8
+ *
9
+ * 平面边界(标准 P2/P3):本模块只服务渲染面。桥接/仲裁面(claimLoop /
10
+ * pump / 心跳 / pushState)与权威/数据面永远在线、与可见性无关——订阅器
11
+ * 不持有也不节流任何桥接定时器。
12
+ *
13
+ * 协议常量唯一真源在 @capyclaw/foundation/abi(visibility.mjs),这里只
14
+ * import + re-export,绝不私设第二份。该 ABI 层是纯 JS(无 node:* 依赖),
15
+ * 保持本文件 browser-safe,可随编辑器客户端一起打进前端 bundle。
16
+ */
17
+ import {
18
+ SURFACE_LIFECYCLE_VERSION,
19
+ VISIBILITY_ACK_MESSAGE,
20
+ VISIBILITY_DEFAULTS,
21
+ VISIBILITY_MESSAGE,
22
+ VISIBILITY_STATES,
23
+ isVisibilityState,
24
+ normalizeVisibilityState,
25
+ } from '@capyclaw/foundation/abi'
26
+
27
+ /* 顺带 re-export 协议常量,消费者不必再记一遍 foundation 的子路径。 */
28
+ export {
29
+ SURFACE_LIFECYCLE_VERSION,
30
+ VISIBILITY_ACK_MESSAGE,
31
+ VISIBILITY_DEFAULTS,
32
+ VISIBILITY_MESSAGE,
33
+ VISIBILITY_STATES,
34
+ isVisibilityState,
35
+ normalizeVisibilityState,
36
+ }
37
+
38
+ /**
39
+ * 创建可见性订阅器。
40
+ * @param {object} [opts]
41
+ * @param {(state: string, data?: object) => void} [opts.onState] 状态迁移回调(渲染面据此挂起/恢复)
42
+ * @param {Window} [opts.win] 目标窗口,默认 globalThis.window(Node 下缺省则 start 为空操作)
43
+ * @param {boolean} [opts.sendAck] 是否向宿主回执(默认 true;独立打开兜底路径永远无 ack)
44
+ * @returns {{ start: () => void, stop: () => void, readonly state: string }}
45
+ */
46
+ export function createVisibilitySubscriber({ onState = () => {}, win = globalThis.window, sendAck = true } = {}) {
47
+ /* 初始前台:宁可多渲染,不可假挂起(与 normalizeVisibilityState 的兜底同向)。 */
48
+ let state = 'foreground'
49
+ let started = false
50
+ /* 登记所有监听,stop() 统一摘除(对称装填/拆卸 P6,不泄漏)。 */
51
+ const listeners = []
52
+
53
+ /* 状态迁移:只在变化时更新内部 state 并回调,避免重复信号抖动渲染面。 */
54
+ const transition = (next, data) => {
55
+ if (next === state) return
56
+ state = next
57
+ onState(state, data)
58
+ }
59
+
60
+ /* 宿主 → iframe 的可见性信号:同源 + 协议类型双重校验后才认。 */
61
+ const onMessage = (event) => {
62
+ const origin = win && win.location && win.location.origin
63
+ if (event.origin !== origin) return /* 跨源消息一律忽略 */
64
+ const data = event.data
65
+ if (!data || data.type !== VISIBILITY_MESSAGE) return /* 换会话等其他消息正交,不碰 */
66
+ const next = normalizeVisibilityState(data.state) /* 非法/缺省 → foreground */
67
+ transition(next, data)
68
+ /* 回执无条件发(即使状态未变):宿主靠 ack 确认页面响应了信号,
69
+ * 超过 visibilityAckTimeoutMs 没回执会被判半挂起(标准 §4 兜底)。 */
70
+ if (sendAck && event.source) {
71
+ event.source.postMessage({ type: VISIBILITY_ACK_MESSAGE, state, sid: data.sid }, event.origin)
72
+ }
73
+ }
74
+
75
+ /* 独立打开(非嵌入)兜底:没有宿主下发信号,退回 tab 级 visibilitychange。
76
+ * 注意这只是「顶层 tab 可见性」,不是表面可见性——嵌入时绝不走这条路。 */
77
+ const onDocVisibility = () => {
78
+ const doc = win && win.document
79
+ transition(doc && doc.hidden ? 'hidden' : 'foreground')
80
+ }
81
+
82
+ function start() {
83
+ if (started || !win || typeof win.addEventListener !== 'function') return
84
+ started = true
85
+ win.addEventListener('message', onMessage)
86
+ listeners.push([win, 'message', onMessage])
87
+ /* win.parent === win ⇔ 顶层独立打开;嵌入(parent !== win)时宿主才是
88
+ * 真源,忽略自身 visibilitychange 作为表面状态(标准 §4 禁止项)。 */
89
+ if (win.parent === win) {
90
+ const doc = win.document
91
+ if (doc && typeof doc.addEventListener === 'function') {
92
+ doc.addEventListener('visibilitychange', onDocVisibility)
93
+ listeners.push([doc, 'visibilitychange', onDocVisibility])
94
+ }
95
+ }
96
+ }
97
+
98
+ function stop() {
99
+ if (!started) return /* 幂等:重复 stop / 未 start 都安全 */
100
+ started = false
101
+ for (const [target, type, handler] of listeners) {
102
+ try { target.removeEventListener(type, handler) } catch { /* ignore */ }
103
+ }
104
+ listeners.length = 0
105
+ }
106
+
107
+ return {
108
+ start,
109
+ stop,
110
+ get state() { return state },
111
+ }
112
+ }
@@ -6,7 +6,8 @@
6
6
  * 就能得到统一的清单;工具只认清单,不认具体引擎。
7
7
  *
8
8
  * schema:
9
- * pages(doc) → 页面数组(默认 doc.pages / doc.slides / doc.deck.slides / [doc])
9
+ * pages(doc) → 页面数组(默认 doc.pages / 数组本身 / [doc];业务形状如
10
+ * PPT 的 deck.slides 由套件经 schema.pages 显式声明,内核不猜)
10
11
  * pageId(page, index) → 页面 ID(默认 page.id / 'p{index}')
11
12
  * nodes(page, pageIndex) → 该页顶层节点数组(默认 page.elements / page.children / 空)
12
13
  * children(node) → 子节点数组(分组、表格单元格;缺省无嵌套)
@@ -21,12 +22,13 @@ import { nodePath } from './ids.mjs'
21
22
 
22
23
  const isObj = (value) => !!value && typeof value === 'object' && !Array.isArray(value)
23
24
 
24
- function defaultPages(doc) {
25
+ /** 默认分页:只认形状无关的通用信封(数组本身 / doc.pages / 单对象当一页)。
26
+ * 业务形状(PPT 的 slides / deck.slides 等)由套件适配层经 schema.pages 显式传入,
27
+ * 内核不再猜测——见 infrastructure-review-2026-11-23 M5。导出供 ops 复用同一语义。 */
28
+ export function defaultPages(doc) {
25
29
  if (Array.isArray(doc)) return doc
26
30
  if (!isObj(doc)) return []
27
31
  if (Array.isArray(doc.pages)) return doc.pages
28
- if (Array.isArray(doc.slides)) return doc.slides
29
- if (isObj(doc.deck) && Array.isArray(doc.deck.slides)) return doc.deck.slides
30
32
  return [doc]
31
33
  }
32
34
 
@@ -7,6 +7,7 @@
7
7
  * 也可以直接用 applyPlan 做纯树改写(工具侧无引擎也能跑,便于测试)。
8
8
  */
9
9
  import { locate } from './locate.mjs'
10
+ import { defaultPages } from './manifest.mjs'
10
11
 
11
12
  const isObj = (value) => !!value && typeof value === 'object' && !Array.isArray(value)
12
13
 
@@ -59,7 +60,9 @@ export function planEdit(manifest, edits) {
59
60
  function listAt(doc, schema, path) {
60
61
  const parsed = parsePath(path)
61
62
  if (!parsed) return null
62
- const pagesOf = schema.pages || ((d) => (Array.isArray(d?.pages) ? d.pages : Array.isArray(d?.slides) ? d.slides : d?.deck?.slides || [d]))
63
+ /* 默认分页与 buildManifest 同一语义(通用信封,不猜业务形状);
64
+ * PPT 的 slides/deck.slides 解释由套件经 schema.pages 显式传入。 */
65
+ const pagesOf = schema.pages || defaultPages
63
66
  const nodesOf = schema.nodes || ((p) => (Array.isArray(p?.elements) ? p.elements : Array.isArray(p?.children) ? p.children : []))
64
67
  const childrenOf = typeof schema.children === 'function' ? schema.children : () => null
65
68
  const page = pagesOf(doc)?.[parsed.page]
@@ -117,7 +120,9 @@ export function applyPlan(doc, plan, schema = {}) {
117
120
  const skipped = []
118
121
  for (const op of plan) {
119
122
  if (op.op === 'insert') {
120
- const pagesOf = schema.pages || ((d) => (Array.isArray(d?.pages) ? d.pages : Array.isArray(d?.slides) ? d.slides : d?.deck?.slides))
123
+ /* 与 listAt/buildManifest 共用 defaultPages(含 [doc] 兜底):
124
+ * 单对象文档(无 pages 包裹)的 insert 也能落到默认页。 */
125
+ const pagesOf = schema.pages || defaultPages
121
126
  const nodesOf = schema.nodes || ((p) => (Array.isArray(p?.elements) ? p.elements : p.children || []))
122
127
  const page = pagesOf(next)?.[op.page]
123
128
  if (!page) { skipped.push({ op, reason: 'NO_PAGE' }); continue }
@@ -3,6 +3,8 @@
3
3
  * owner 租约组合成稳定的 DocumentSession API。
4
4
  *
5
5
  * 领域文档放在 documentKey 下;summary/onApplied 由调用方提供。
6
+ * shape(可选形状标签,如 'ppt.deck')随 checkpoint 写入,供套件投影识别;
7
+ * checkpoint 列表的业务字段由 backend 的 project 声明叠加,内核只回通用信封。
6
8
  */
7
9
  import {
8
10
  applyAck, applyPush, applyServer, applyShotRequest, applyShotResult,
@@ -41,6 +43,7 @@ export class DocumentSession {
41
43
  checkpointDocument = null,
42
44
  stateCompact = true,
43
45
  pendingTtl = PENDING_TTL,
46
+ shape = null,
44
47
  } = {}) {
45
48
  if (!backend) throw new Error('DocumentSession 需要 backend')
46
49
  this.backend = backend
@@ -51,6 +54,9 @@ export class DocumentSession {
51
54
  this.checkpointDocument = checkpointDocument
52
55
  this.stateCompact = stateCompact !== false
53
56
  this.pendingTtl = Number(pendingTtl) || PENDING_TTL
57
+ /* 形状标签(如 'ppt.deck'):写进 checkpoint payload 供套件投影识别新格式;
58
+ * 缺省不写(旧格式不变),旧 payload 无标签时套件 projector 按键名兜底。 */
59
+ this.shape = typeof shape === 'string' && shape ? shape : null
54
60
  this.dir = backend.dir || ''
55
61
  this.file = backend.file || ''
56
62
  this.journalFile = backend.journalFile || ''
@@ -251,6 +257,8 @@ export class DocumentSession {
251
257
  seq: this.doc.seq | 0,
252
258
  appliedSeq: this.doc.applied_seq | 0,
253
259
  pending,
260
+ /* 通用信封 + 形状标签:业务形状的解释归套件投影,内核只记录标签。 */
261
+ ...(this.shape ? { shape: this.shape } : {}),
254
262
  ...summary,
255
263
  title: this.doc.title || summary.title || '',
256
264
  [this.documentKey]: this.doc[this.documentKey]
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import fs from 'node:fs'
9
9
  import path from 'node:path'
10
+ import { projectCheckpoint } from './projection.mjs'
10
11
 
11
12
  export class FileStateBackend {
12
13
  /* journalMaxBytes 默认 512KB 由 NSGA-II 进化搜索固化(evolution/,2026-11-01):
@@ -18,7 +19,7 @@ export class FileStateBackend {
18
19
  * document-workbench 每个编辑批次会写 2 次状态——节流到每 16 次写一次 fsync,
19
20
  * 把该链路成本从 ~3.6ms/批降到 ~1.5ms/批;checkpoint 仍强制 fsync(里程碑语义)。
20
21
  * 设为 1 恢复「每次写都 fsync」的旧行为;设为 0 则完全不做 fsync。 */
21
- constructor(file, { initialDoc = {}, journalMaxBytes = 512 * 1024, fsyncEvery = 16 } = {}) {
22
+ constructor(file, { initialDoc = {}, journalMaxBytes = 512 * 1024, fsyncEvery = 16, project = null } = {}) {
22
23
  if (!file) throw new Error('FileStateBackend 需要 file')
23
24
  this.file = file
24
25
  this.dir = path.dirname(file)
@@ -27,6 +28,9 @@ export class FileStateBackend {
27
28
  this.initialDoc = initialDoc
28
29
  this.journalMaxBytes = Math.max(64 * 1024, Number(journalMaxBytes) || 512 * 1024)
29
30
  this.fsyncEvery = Math.max(0, Number(fsyncEvery) || 0)
31
+ /* checkpoint 列表的套件投影(形状声明):内核默认只回通用信封,
32
+ * PPT 的 slides/title 等业务字段由套件适配层显式传入(见 projection.mjs)。 */
33
+ this.project = typeof project === 'function' ? project : null
30
34
  this._writeCount = 0
31
35
  /** 最近一次读状态失败的原因;ENOENT 不算错误。 */
32
36
  this.lastStateError = null
@@ -128,17 +132,20 @@ export class FileStateBackend {
128
132
  .filter((name) => name.endsWith('.json'))
129
133
  .map((name) => {
130
134
  try {
131
- const payload = JSON.parse(fs.readFileSync(path.join(this.checkpointDir, name), 'utf8'))
132
- return {
133
- name: payload.name,
134
- seq: payload.seq,
135
- appliedSeq: payload.appliedSeq,
136
- pending: !!payload.pending,
137
- title: payload.title,
138
- slides: payload.slides,
135
+ const file = path.join(this.checkpointDir, name)
136
+ const raw = fs.readFileSync(file, 'utf8')
137
+ const parsed = JSON.parse(raw)
138
+ const payload = parsed && typeof parsed === 'object' ? parsed : {}
139
+ /* 通用信封(V2-5):不解析 payload 内部业务形状;
140
+ * seq/slides 等扩展字段由 this.project(套件声明)叠加。 */
141
+ const base = {
142
+ name: payload.name ?? name.slice(0, -5),
143
+ ts: fs.statSync(file).mtimeMs,
139
144
  createdAt: payload.createdAt,
140
- meta: payload.meta || {},
145
+ size: Buffer.byteLength(raw, 'utf8'),
146
+ meta: payload.meta && typeof payload.meta === 'object' ? payload.meta : {},
141
147
  }
148
+ return projectCheckpoint(payload, base, this.project)
142
149
  } catch { return null }
143
150
  })
144
151
  .filter(Boolean)
@@ -0,0 +1,39 @@
1
+ /**
2
+ * checkpoint 列表投影:通用信封 + 套件声明(M5 / checkpoint 投影通用化)。
3
+ *
4
+ * 内核只产出形状无关的通用信封 {name, ts, createdAt, size, meta}
5
+ * (work-store STANDARD V2-5:不解析 payload 内部业务形状);
6
+ * 会话协议字段(seq/appliedSeq/pending/title)在这里作为可选组合助手提供,
7
+ * 业务形状(如 PPT 的 slides)由套件适配层显式声明 project(payload, base)
8
+ * 并传给 backend——内核不硬编码任何套件名词。
9
+ *
10
+ * 旧 checkpoint 的 payload 原样保留(readCheckpoint 仍返回全量),
11
+ * 套件 projector 负责兼容读取历史形状,无需迁移数据。
12
+ */
13
+
14
+ /**
15
+ * 会话协议字段(形状无关):payload 里实际存在才附带,不造零值。
16
+ * 兼容旧 payload 的 applied_seq 蛇形命名;pending 兼容布尔与数组(取条数)。
17
+ */
18
+ export function sessionCheckpointFields(payload) {
19
+ const out = {}
20
+ if (!payload || typeof payload !== 'object') return out
21
+ if ('seq' in payload) out.seq = payload.seq | 0
22
+ const applied = payload.appliedSeq ?? payload.applied_seq
23
+ if (applied != null) out.appliedSeq = applied | 0
24
+ if ('pending' in payload) {
25
+ out.pending = Array.isArray(payload.pending) ? payload.pending.length : !!payload.pending
26
+ }
27
+ if (typeof payload.title === 'string' && payload.title) out.title = payload.title
28
+ return out
29
+ }
30
+
31
+ /**
32
+ * 合并套件投影:project(payload, base) 返回扩展字段,叠加到通用信封上。
33
+ * project 缺省或返回非对象时原样返回 base(内核默认 = 纯通用信封)。
34
+ */
35
+ export function projectCheckpoint(payload, base, project) {
36
+ if (typeof project !== 'function') return base
37
+ const extra = project(payload, base)
38
+ return extra && typeof extra === 'object' ? { ...base, ...extra } : base
39
+ }
@@ -1,6 +1,7 @@
1
1
  /** 测试工具:内存 backend 与 fake editor adapter,供框架自身和消费者做一致性测试。 */
2
+ import { projectCheckpoint } from '../store/projection.mjs'
2
3
 
3
- export function createMemoryBackend({ initialDoc = {} } = {}) {
4
+ export function createMemoryBackend({ initialDoc = {}, project = null } = {}) {
4
5
  let state = null
5
6
  const journal = []
6
7
  const checkpoints = new Map()
@@ -27,16 +28,18 @@ export function createMemoryBackend({ initialDoc = {} } = {}) {
27
28
  },
28
29
  listCheckpoints() {
29
30
  return [...checkpoints.values()]
30
- .map((payload) => ({
31
- name: payload.name,
32
- seq: payload.seq,
33
- appliedSeq: payload.appliedSeq,
34
- pending: !!payload.pending,
35
- title: payload.title,
36
- slides: payload.slides,
37
- createdAt: payload.createdAt,
38
- meta: payload.meta || {},
39
- }))
31
+ .map((raw) => {
32
+ const payload = raw && typeof raw === 'object' ? raw : {}
33
+ /* 通用信封(V2-5):业务字段由 project(套件声明)叠加,与 FileStateBackend 同契约。 */
34
+ const base = {
35
+ name: payload.name,
36
+ ts: Date.parse(payload.createdAt) || 0,
37
+ createdAt: payload.createdAt,
38
+ size: Buffer.byteLength(JSON.stringify(raw ?? null), 'utf8'),
39
+ meta: payload.meta && typeof payload.meta === 'object' ? payload.meta : {},
40
+ }
41
+ return projectCheckpoint(payload, base, project)
42
+ })
40
43
  .sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
41
44
  },
42
45
  readCheckpoint(name) {
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 资产引用契约的单一真源(公共 ABI 常量)。
3
+ *
4
+ * 互操作标准里资产有两副面孔,前缀在这里定义一次,内核门面与资产服务都引用它,
5
+ * 避免「路由实现」与「URL 门面」各写一份 '/assets/' 而漂移:
6
+ * - 字节仓 HTTP 路由前缀 ASSET_URL_PREFIX = '/assets/' (asset-service 挂 GET/HEAD)
7
+ * - 结构化正文里的引用前缀 ASSET_REF_PREFIX = '@asset/' (work-store 信封/正文只存引用)
8
+ *
9
+ * 这是契约常量,不是宿主服务名——放 ABI 层,应用与驱动都可 import。
10
+ */
11
+
12
+ /** 资产字节仓的 HTTP 路由前缀(asset-service 实现,内核 os.assets.url 复用)。 */
13
+ export const ASSET_URL_PREFIX = '/assets/'
14
+
15
+ /** 结构化正文/产物信封里的内容寻址引用前缀(@asset/<sha256>)。 */
16
+ export const ASSET_REF_PREFIX = '@asset/'
17
+
18
+ /** 由资产 id 生成可加载 URL:/assets/<id>(id 做 URI 编码)。 */
19
+ export function assetUrl(id) {
20
+ return `${ASSET_URL_PREFIX}${encodeURIComponent(String(id))}`
21
+ }
22
+
23
+ /** 由资产 id 生成规范引用:@asset/<id>。 */
24
+ export function assetRef(id) {
25
+ return `${ASSET_REF_PREFIX}${String(id)}`
26
+ }