@capyclaw/session-tabs 0.4.0 → 0.9.0

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 (27) hide show
  1. package/README.md +15 -14
  2. package/client/client.js +478 -300
  3. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  4. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +3 -1
  5. package/node_modules/@capyclaw/foundation/abi/index.mjs +15 -0
  6. package/node_modules/@capyclaw/foundation/abi/loader.mjs +8 -1
  7. package/node_modules/@capyclaw/foundation/abi/spec.mjs +5 -2
  8. package/node_modules/@capyclaw/foundation/abi/version.mjs +63 -5
  9. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  10. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +21 -4
  11. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +11 -10
  12. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +8 -1
  13. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +5 -1
  14. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +5 -2
  15. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +4 -0
  16. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +29 -2
  17. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +13 -3
  18. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +31 -3
  19. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +12 -2
  20. package/node_modules/@capyclaw/foundation/package.json +1 -1
  21. package/node_modules/@capyclaw/plugin-kit/package.json +3 -1
  22. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +5 -2
  23. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  24. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +3 -82
  25. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  26. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +13 -5
  27. package/package.json +3 -3
package/client/client.js CHANGED
@@ -1,300 +1,478 @@
1
- /*
2
- * @capyclaw/session-tabs 浏览器半:薄 UI(浏览器式会话标签条)。
3
- *
4
- * 单一职责:本插件只负责"呈现与用户意图",不做任何会话管理——
5
- * 会话保活/心跳/受管集合/判活状态全部来自唯一接口 ctx.sessionKeeper
6
- * (@capyclaw/session-keeper)。本插件不读 ctx.sessions.list、不订阅
7
- * api-session/status、不持久化标签序、不持有 retain 引用。
8
- * 仅保留三类本地 presentation 状态:待确认关闭(pendingClose)、失败提示(notice)、
9
- * 乐观切换目标(switchTo)。
10
- * 用户意图翻译:open⇒uiWorkspace.openSession+keeper.manage;create⇒uiWorkspace.startSession;
11
- * close⇒keeper.unmanage(运行中先主题化确认并 sessions.using(...).cancel())。
12
- * 放置:经 ctx.captionExtra(@capyclaw/caption-map 预留栏位挂载锚)acquire 一枚 mount
13
- * 节点,用 react-dom/client createRoot 挂进去;锚缺席/让位时不渲染、不崩页。
14
- * 切换体验(v0.3 起无任何附加图层):宿主 openSession 同步换选择,历史拉取/渲染在
15
- * 视图内异步完成。点击标签只做立即乐观高亮(switchTo),主区完全交给宿主自己的
16
- * 默认背景/加载态——不盖遮罩、不存快照、不挂观察器、不挡任何点击(用户明确要求)。
17
- * 宿主 activeId 跟上点击目标后乐观态自动清除。
18
- */
19
- window.__ModuleLoader__.load({
20
- id: '@capyclaw/session-tabs',
21
- factory: function (require) {
22
- var module = { exports: {} }
23
- var React = require('react')
24
- var ReactDOM = require('react-dom/client')
25
- var e = React.createElement
26
-
27
- /* ================= 本地 presentation 状态(pendingClose/notice/switchTo) ================= */
28
- function createLocal() {
29
- var listeners = []
30
- var state = { pendingClose: null, notice: null, switchTo: null }
31
- function emit() { state = Object.assign({}, state); listeners.forEach(function (fn) { fn() }) }
32
- return {
33
- getState: function () { return state },
34
- subscribe: function (fn) { listeners.push(fn); return function () { listeners = listeners.filter(function (x) { return x !== fn }) } },
35
- setPending: function (id) { state.pendingClose = id; emit() },
36
- setNotice: function (msg) { state.notice = msg; emit() },
37
- setSwitchTo: function (id) { if (state.switchTo === id) return; state.switchTo = id; emit() }
38
- }
39
- }
40
-
41
- /* ================= 用户意图翻译(只经 keeper + 宿主 UI/停止 API) ================= */
42
- function createBridge(ctx, keeper, local) {
43
- var noticeTimer = null
44
- var pendingOpen = null /* {id,cancel}:latest-wins,连点只保留最后一次宿主交换 */
45
- var disposed = false
46
- function notifyFail() {
47
- local.setNotice('停止会话失败,标签已保留。')
48
- if (noticeTimer) clearTimeout(noticeTimer)
49
- noticeTimer = setTimeout(function () { noticeTimer = null; local.setNotice(null) }, 4000)
50
- }
51
- function cancelPending() {
52
- if (pendingOpen) { pendingOpen.cancel(); pendingOpen = null }
53
- }
54
- /* paint-first(Chrome 式点击手感的关键):高亮在点击任务里进 DOM、由浏览器先画出来;
55
- 宿主 openSession+manage 是同步换选择+重建视图的重活,推迟到两帧之后再做——
56
- 否则高亮要等宿主重活干完才画得出来,点击就"卡"。双 rAF 保证中间至少画过一帧
57
- 带高亮的画面;无 rAF 的环境降级 setTimeout。连点取消上一次未执行的交换。 */
58
- function scheduleHost(id) {
59
- cancelPending()
60
- var done = false
61
- var handles = []
62
- function run() {
63
- if (done || disposed) return
64
- done = true
65
- pendingOpen = null
66
- try { ctx.uiWorkspace.openSession(id) } catch (err) {}
67
- keeper.manage(id)
68
- }
69
- var raf = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : null
70
- var caf = typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame : null
71
- if (raf) handles.push(raf(function () { handles.push(raf(run)) }))
72
- else handles.push(setTimeout(run, 0))
73
- pendingOpen = {
74
- id: id,
75
- cancel: function () {
76
- done = true
77
- handles.forEach(function (h) { try { (caf || clearTimeout)(h) } catch (err) {} })
78
- }
79
- }
80
- }
81
- function open(id) {
82
- if (disposed) return
83
- /* 点当前标签=零操作(Chrome 同款):不重复触发宿主换选择/重建。 */
84
- if (keeper.getState().activeId === id && !pendingOpen) { local.setSwitchTo(null); return }
85
- local.setSwitchTo(id) /* 乐观高亮立即进 DOM,先画 */
86
- if (pendingOpen && pendingOpen.id === id) return
87
- scheduleHost(id)
88
- }
89
- function create() { try { ctx.uiWorkspace.startSession() } catch (err) {} }
90
- function closeNow(id) {
91
- var st = keeper.getState()
92
- var wasActive = st.activeId === id
93
- var idx = st.ids.indexOf(id)
94
- var neighbor = st.ids[idx + 1] || st.ids[idx - 1] || null
95
- keeper.unmanage(id)
96
- if (wasActive) { if (neighbor) open(neighbor); else create() }
97
- }
98
- return {
99
- open: open,
100
- create: create,
101
- requestClose: function (id) {
102
- var info = keeper.getState().sessions[id]
103
- if (info && info.running) local.setPending(id)
104
- else closeNow(id)
105
- },
106
- confirmClose: function () {
107
- var id = local.getState().pendingClose
108
- local.setPending(null)
109
- if (!id) return
110
- var pr = null
111
- try {
112
- pr = ctx.sessions.using(id, { source: 'controllerOperation' }, function (ref) { return ref.binding.session.cancel() })
113
- } catch (err) {}
114
- if (pr && typeof pr.then === 'function') {
115
- pr.then(function (res) {
116
- if (res && res.ok === false) notifyFail()
117
- else closeNow(id)
118
- }).catch(function () { notifyFail() })
119
- } else closeNow(id)
120
- },
121
- dispose: function () {
122
- disposed = true
123
- cancelPending()
124
- if (noticeTimer) { clearTimeout(noticeTimer); noticeTimer = null }
125
- }
126
- }
127
- }
128
-
129
- /* ================= 纯视图 ================= */
130
- var CSS = [
131
- '.cst-top{display:flex;align-items:center;box-sizing:border-box;height:28px;max-width:100%;min-width:0;',
132
- ' background:transparent;border:none;-webkit-app-region:no-drag;}',
133
- '.cst-tab,.cst-close,.cst-new,.cst-mask{-webkit-app-region:no-drag;}',
134
- '.cst-scroll{display:flex;align-items:center;gap:2px;flex:1 1 auto;min-width:0;overflow-x:auto;overflow-y:hidden;scrollbar-width:thin;}',
135
- '.cst-scroll::-webkit-scrollbar{height:4px}.cst-scroll::-webkit-scrollbar-thumb{background:var(--dsw-alias-border-l3,rgba(127,127,127,.3));border-radius:2px}',
136
- '.cst-tab{display:inline-flex;align-items:center;gap:5px;flex:0 1 140px;min-width:56px;max-width:160px;height:24px;',
137
- ' padding:0 4px 0 8px;border-radius:6px;box-sizing:border-box;cursor:pointer;',
138
- ' font-size:12px;line-height:1;color:var(--dsw-alias-label-secondary,inherit);background:transparent;border:1px solid transparent;}',
139
- '.cst-tab:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12));color:var(--dsw-alias-label-primary,inherit);}',
140
- '.cst-tab.cst-active{background:var(--dsw-alias-interactive-bg-active,rgba(127,127,127,.16));color:var(--dsw-alias-label-primary,inherit);border-color:var(--dsw-alias-border-l3,rgba(127,127,127,.25));}',
141
- '.cst-tab.cst-missing{opacity:.45;}',
142
- '.cst-tab.cst-stalled .cst-spin{border-top-color:var(--dsw-alias-state-warn-primary,#f5a524);}',
143
- '.cst-tab:focus-visible,.cst-close:focus-visible,.cst-new:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#3b82f6);outline-offset:-2px;}',
144
- '.cst-title{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}',
145
- '.cst-close{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border:none;border-radius:5px;background:transparent;color:inherit;cursor:pointer;font-size:12px;line-height:1;padding:0;opacity:.7;}',
146
- '.cst-close:hover{opacity:1;background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.2));}',
147
- '.cst-spin{flex:0 0 auto;width:11px;height:11px;border-radius:50%;box-sizing:border-box;border:1.5px solid var(--dsw-alias-border-l3,rgba(127,127,127,.35));border-top-color:var(--dsw-alias-state-business-primary,#3b82f6);animation:cst-rot .8s linear infinite;}',
148
- '@keyframes cst-rot{to{transform:rotate(360deg)}}',
149
- '@media (prefers-reduced-motion: reduce){.cst-spin{animation:none;}}',
150
- '.cst-new{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;align-self:center;margin-left:2px;border:none;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary,inherit);cursor:pointer;font-size:14px;line-height:1;padding:0;}',
151
- '.cst-new:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.15));color:var(--dsw-alias-label-primary,inherit);}',
152
- '.cst-empty{align-self:center;font-size:11px;color:var(--dsw-alias-label-tertiary,inherit);opacity:.7;padding:0 4px;white-space:nowrap;}',
153
- '.cst-mask{position:fixed;inset:0;z-index:1600;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.35);pointer-events:auto;}',
154
- '.cst-modal{width:320px;max-width:80vw;border-radius:12px;padding:16px;box-sizing:border-box;background:var(--dsw-alias-bg-base,#fff);color:var(--dsw-alias-label-primary,#222);border:1px solid var(--dsw-alias-border-l3,rgba(127,127,127,.25));box-shadow:0 8px 32px rgba(0,0,0,.25);}',
155
- '.cst-modal h3{margin:0 0 8px;font-size:14px;}',
156
- '.cst-modal p{margin:0 0 16px;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary,#666);word-break:break-all;}',
157
- '.cst-modal .row{display:flex;justify-content:flex-end;gap:8px;}',
158
- '.cst-btn{border:1px solid var(--dsw-alias-border-l3,rgba(127,127,127,.3));border-radius:8px;padding:6px 12px;font-size:12px;cursor:pointer;background:transparent;color:inherit;}',
159
- '.cst-btn.danger{background:var(--dsw-alias-state-business-primary,#3b82f6);border-color:transparent;color:#fff;}',
160
- '.cst-notice{position:fixed;top:calc(var(--dsh-windows-titlebar-height,var(--dsh-frame-top-clearance,40px)) + 8px);left:50%;transform:translateX(-50%);',
161
- ' z-index:1600;max-width:80vw;padding:8px 14px;border-radius:8px;box-sizing:border-box;pointer-events:none;',
162
- ' font-size:12px;line-height:1.5;background:var(--dsw-alias-bg-overlay,#fff);color:var(--dsw-alias-label-primary,#222);',
163
- ' border:1px solid var(--dsw-alias-state-error-primary,#e5484d);box-shadow:0 4px 16px rgba(0,0,0,.2);}'
164
- ].join('\n')
165
-
166
- function makeTopBarView(keeper, local, bridge, menus) {
167
- return function TopBarView() {
168
- var tick = React.useState(0)
169
- var setTick = tick[1]
170
- var ks = keeper.getState()
171
- var ls = local.getState()
172
- React.useEffect(function () {
173
- var unK = keeper.subscribe(function () { setTick(function (t) { return t + 1 }) })
174
- var unL = local.subscribe(function () { setTick(function (t) { return t + 1 }) })
175
- return function () { unK(); unL() }
176
- }, [keeper, local])
177
- React.useEffect(function () {
178
- var style = document.createElement('style')
179
- style.id = 'cst-css'
180
- style.textContent = CSS
181
- document.head.appendChild(style)
182
- return function () { if (style.parentNode) style.parentNode.removeChild(style) }
183
- }, [])
184
- React.useEffect(function () {
185
- var act = document.querySelector('.cst-tab.cst-active')
186
- if (act && act.scrollIntoView) act.scrollIntoView({ block: 'nearest', inline: 'nearest' })
187
- }, [ks.activeId, ls.switchTo, ks.ids.length])
188
-
189
- function onKey(ev, id, idx) {
190
- var k = ev.key
191
- if (k === 'Enter' || k === ' ') { ev.preventDefault(); bridge.open(id) }
192
- else if (k === 'Delete' || k === 'Backspace') { ev.preventDefault(); bridge.requestClose(id) }
193
- else if (k === 'ContextMenu' || (ev.shiftKey && k === 'F10')) {
194
- ev.preventDefault()
195
- var r = ev.currentTarget.getBoundingClientRect()
196
- openMenu(id, (keeper.getState().sessions[id] || {}).title || '会话', r.left, r.bottom)
197
- }
198
- else if (k === 'ArrowRight' || k === 'ArrowLeft') {
199
- ev.preventDefault()
200
- var tabs = document.querySelectorAll('.cst-tab')
201
- var n = tabs[idx + (k === 'ArrowRight' ? 1 : -1)]
202
- if (n) n.focus()
203
- }
204
- }
205
-
206
- /* 右键/菜单键 ⇒ 复用宿主会话右键菜单(与工作区侧栏同一组贡献,不复制菜单项)。 */
207
- function openMenu(id, title, x, y) {
208
- if (menus && menus.open) menus.open({ kind: 'session', value: { sessionId: id, displayTitle: title } }, { x: x, y: y })
209
- }
210
-
211
- /* 乐观高亮:宿主 activeId 未跟上时先亮点击目标;跟上后 switchTo 被清。 */
212
- var switching = ls.switchTo && ls.switchTo !== ks.activeId ? ls.switchTo : null
213
- var tabs = ks.ids.map(function (id, idx) {
214
- var info = ks.sessions[id] || {}
215
- var active = id === ks.activeId || id === ls.switchTo
216
- var running = !!info.running
217
- var missing = info.status === 'missing'
218
- var stalled = info.status === 'stalled'
219
- var title = info.title || '会话'
220
- var suffix = running ? '(运行中)' : stalled ? '(疑似停滞)' : missing ? '(已消失)' : ''
221
- return e('div', {
222
- key: id,
223
- className: 'cst-tab' + (active ? ' cst-active' : '') + (missing ? ' cst-missing' : '') + (stalled ? ' cst-stalled' : '') + (id === switching ? ' cst-switching' : ''),
224
- role: 'tab', tabIndex: 0,
225
- 'aria-selected': active, 'aria-busy': id === switching ? true : undefined,
226
- title: title + suffix,
227
- onClick: function () { bridge.open(id) },
228
- onContextMenu: function (ev) { ev.preventDefault(); ev.stopPropagation(); openMenu(id, title, ev.clientX, ev.clientY) },
229
- onKeyDown: function (ev) { onKey(ev, id, idx) }
230
- },
231
- (running || id === switching) ? e('span', { className: 'cst-spin', 'aria-hidden': true }) : null,
232
- e('span', { className: 'cst-title' }, title),
233
- e('button', {
234
- className: 'cst-close', tabIndex: -1, 'aria-label': '关闭标签 ' + title,
235
- title: running ? '停止并关闭' : missing ? '移除标签' : '关闭标签',
236
- onClick: function (ev) { ev.stopPropagation(); bridge.requestClose(id) }
237
- }, '×')
238
- )
239
- })
240
- var scroll = e('div', { className: 'cst-scroll' }, tabs.length ? tabs : [e('span', { key: '__e', className: 'cst-empty' }, ks.phase === 'ready' ? '没有打开的会话' : '加载中…')])
241
- var bar = e('div', { className: 'cst-top', role: 'tablist' }, scroll,
242
- e('button', { className: 'cst-new', 'aria-label': '新建会话', title: '新建会话(当前/最近工作区)', onClick: function () { bridge.create() } }, '+'))
243
-
244
- var modal = null
245
- if (ls.pendingClose) {
246
- var pTitle = (ks.sessions[ls.pendingClose] || {}).title || '会话'
247
- modal = e('div', { className: 'cst-mask', onClick: function () { local.setPending(null) } },
248
- e('div', { className: 'cst-modal', role: 'dialog', 'aria-modal': true, onClick: function (ev) { ev.stopPropagation() } },
249
- e('h3', null, '停止并关闭标签?'),
250
- e('p', null, '「' + pTitle + '」正在运行。关闭标签将停止它正在进行的任务。'),
251
- e('div', { className: 'row' },
252
- e('button', { className: 'cst-btn', onClick: function () { local.setPending(null) } }, '取消'),
253
- e('button', { className: 'cst-btn danger', onClick: function () { bridge.confirmClose() } }, '停止并关闭'))))
254
- }
255
- var notice = ls.notice ? e('div', { className: 'cst-notice', role: 'alert' }, ls.notice) : null
256
- return e(React.Fragment, null, bar, modal, notice)
257
- }
258
- }
259
-
260
- /* ================= 装配 ================= */
261
- var api = {
262
- name: '@capyclaw/session-tabs',
263
- inject: ['uiWorkspace', 'sessions', 'sessionKeeper', 'captionExtra', 'contextMenus'],
264
- apply: function (ctx) {
265
- var keeper = ctx.sessionKeeper
266
- var anchor = ctx.captionExtra
267
- var local = createLocal()
268
- var bridge = createBridge(ctx, keeper, local)
269
- var View = makeTopBarView(keeper, local, bridge, ctx.contextMenus)
270
- /* 宿主选择跟上点击目标后清乐观高亮。 */
271
- var unSwitch = keeper.subscribe(function () {
272
- var sw = local.getState().switchTo
273
- if (sw && keeper.getState().activeId === sw) local.setSwitchTo(null)
274
- })
275
- /* 挂载锚同步:mount 节点出现/消失/重建时重挂 React 根;缺席则不渲染。 */
276
- var root = null
277
- var rootEl = null
278
- function sync() {
279
- var el = anchor.getMount()
280
- if (el === rootEl) return
281
- if (root) { root.unmount(); root = null }
282
- rootEl = el
283
- if (el) { root = ReactDOM.createRoot(el); root.render(e(View)) }
284
- }
285
- anchor.acquire()
286
- var unSub = anchor.subscribe(sync)
287
- sync()
288
- return function () {
289
- unSub()
290
- unSwitch()
291
- if (root) { root.unmount(); root = null; rootEl = null }
292
- anchor.release()
293
- bridge.dispose()
294
- }
295
- }
296
- }
297
- module.exports = api
298
- return module.exports
299
- }
300
- })
1
+ /*
2
+ * @capyclaw/session-tabs 浏览器半:薄 UI(浏览器式会话标签条)。
3
+ *
4
+ * 单一职责:本插件只负责"呈现与用户意图",不做任何会话管理——
5
+ * 会话保活/心跳/受管集合/判活状态全部来自唯一接口 ctx.sessionKeeper
6
+ * (@capyclaw/session-keeper)。本插件不读 ctx.sessions.list、不订阅
7
+ * api-session/status、不持久化标签序、不持有 retain 引用;
8
+ * 唯一例外:新建时读 ctx.workspaces.list 快照做导航定位(v0.5)。
9
+ * 仅保留五类本地 presentation 状态:待确认关闭(pendingClose)、失败提示(notice)、
10
+ * 乐观切换目标(switchTo)、拖拽源(dragId)、放置提示(dropHint)(v0.8 排序)。
11
+ * 用户意图翻译(规则先行:manage 必带合法来源,keeper 侧白名单闸校验):
12
+ * open⇒uiWorkspace.openSession+keeper.manage(id,'user-open');
13
+ * create⇒sessions.create({workspaceId}) 必新建(v0.5:绕开宿主 startSession 的空白复用,
14
+ * 连点"+"像 Chrome 一样产出彼此独立的新标签;失败回退 startSession)+manage(id,'user-create');
15
+ * close⇒keeper.unmanage(运行中先主题化确认并 sessions.using(...).cancel());
16
+ * 关最后一个标签不再自动新建(自动添加被规则禁止)。
17
+ * 放置:经 ctx.captionExtra(@capyclaw/caption-map 预留栏位挂载锚)acquire 一枚 mount
18
+ * 节点,用 react-dom/client createRoot 挂进去;锚缺席/让位时不渲染、不崩页。
19
+ * 切换体验(v0.3 起无任何附加图层):宿主 openSession 同步换选择,历史拉取/渲染在
20
+ * 视图内异步完成。点击标签只做立即乐观高亮(switchTo),主区完全交给宿主自己的
21
+ * 默认背景/加载态——不盖遮罩、不存快照、不挂观察器、不挡任何点击(用户明确要求)。
22
+ * 宿主 activeId 跟上点击目标后乐观态自动清除。
23
+ * 标签层 spinner 仅指示 running(v0.6 移除切换伴随 spinner,点击无中间态闪烁);
24
+ * 会话等待用户操作(待答问题/审批,keeper 的 awaiting)时改画红色问号。
25
+ * v0.9 输入优先调度(按下即切换、快速响应):
26
+ * ① pointerdown 即激活(Chrome 同款按下即切换,不等抬手;触屏仍走 click 防滚动误触,
27
+ * 关闭按钮/修饰键不抢占);高亮在按下任务里同步进 DOM 先画。
28
+ * ② 双 rAF 让高亮先绘制一帧,随后立即执行宿主切换,不额外等待静置窗口;帧间新点击
29
+ * 取消尚未执行的交换,极快连点只提交最后目标,避免主线程重活抢首次视觉反馈。
30
+ * ③ 激活条滚入视野只调 .cst-scroll 自身 scrollLeft,不再 scrollIntoView 连带祖先容器。
31
+ * v0.8 拖拽排序(Chrome 同款左右拖标签换序):
32
+ * ① HTML5 原生 DnD:draggable 标签 + dragstart/dragover/drop/dragend;dragover 以
33
+ * 中线判 before/after,放置指示画在标签自身 inset box-shadow 与滚动口右缘(end),
34
+ * 零附加图层;拖到空白/「+」区=移到末尾;drop 回自身/取消(Esc)=零排序。
35
+ * ② 序真源在 keeper:drop 与键盘 Alt+←→ 只调 keeper.move(id,toIndex)(keeper 侧
36
+ * 落盘+publish),本插件零持久化不变;触屏无 HTML5 DnD,键盘 Alt+←→ 兜底可达。
37
+ * ③ 拖拽按下仍走 v0.7 pointerdown 即激活(Chrome 拖拽也先激活该标签)。
38
+ */
39
+ window.__ModuleLoader__.load({
40
+ id: '@capyclaw/session-tabs',
41
+ factory: function (require) {
42
+ var React = require('react')
43
+ var ReactDOM = require('react-dom/client')
44
+ var e = React.createElement
45
+
46
+ /* ================= 本地 presentation 状态(pendingClose/notice/switchTo) ================= */
47
+ function createLocal() {
48
+ var listeners = []
49
+ var state = { pendingClose: null, notice: null, switchTo: null, dragId: null, dropHint: null }
50
+ function emit() { state = Object.assign({}, state); listeners.forEach(function (fn) { fn() }) }
51
+ return {
52
+ getState: function () { return state },
53
+ subscribe: function (fn) { listeners.push(fn); return function () { listeners = listeners.filter(function (x) { return x !== fn }) } },
54
+ setPending: function (id) { state.pendingClose = id; emit() },
55
+ setNotice: function (msg) { state.notice = msg; emit() },
56
+ setSwitchTo: function (id) { if (state.switchTo === id) return; state.switchTo = id; emit() },
57
+ /* v0.8 拖拽 presentation:dragover 高频触发,同值不 emit(避免渲染风暴)。 */
58
+ setDrag: function (id) { if (state.dragId === id) return; state.dragId = id; emit() },
59
+ setDropHint: function (h) {
60
+ var p = state.dropHint
61
+ if (p === h) return
62
+ if (p && h && p.overId === h.overId && p.side === h.side) return
63
+ state.dropHint = h; emit()
64
+ }
65
+ }
66
+ }
67
+
68
+ /* ================= 用户意图翻译(只经 keeper + 宿主 UI/停止 API) ================= */
69
+ function createBridge(ctx, keeper, local) {
70
+ var noticeTimer = null
71
+ var pendingOpen = null /* {id,cancel}:latest-wins,连点只保留最后一次宿主交换 */
72
+ var disposed = false
73
+ function notifyFail() {
74
+ local.setNotice('停止会话失败,标签已保留。')
75
+ if (noticeTimer) clearTimeout(noticeTimer)
76
+ noticeTimer = setTimeout(function () { noticeTimer = null; local.setNotice(null) }, 4000)
77
+ }
78
+ function cancelPending() {
79
+ if (pendingOpen) { pendingOpen.cancel(); pendingOpen = null }
80
+ }
81
+ /* paint-first(v0.9):先让乐观高亮绘制一帧,再执行宿主的同步视图切换。
82
+ 双 rAF 期间的新点击仍 latest-wins;单击不再承担人为静置延迟。 */
83
+ function scheduleHost(id) {
84
+ cancelPending()
85
+ var done = false
86
+ var cancels = []
87
+ function run() {
88
+ if (done || disposed) return
89
+ done = true
90
+ pendingOpen = null
91
+ try { ctx.uiWorkspace.openSession(id) } catch (err) {}
92
+ keeper.manage(id, 'user-open')
93
+ }
94
+ function afterPaint() {
95
+ run()
96
+ }
97
+ var raf = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : null
98
+ var caf = typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame : null
99
+ if (raf) {
100
+ var h1 = raf(function () {
101
+ var h2 = raf(afterPaint)
102
+ cancels.push(function () { try { caf(h2) } catch (err) {} })
103
+ })
104
+ cancels.push(function () { try { caf(h1) } catch (err) {} })
105
+ } else {
106
+ var t0 = setTimeout(afterPaint, 0)
107
+ cancels.push(function () { clearTimeout(t0) })
108
+ }
109
+ pendingOpen = {
110
+ id: id,
111
+ cancel: function () {
112
+ done = true
113
+ cancels.forEach(function (fn) { fn() })
114
+ }
115
+ }
116
+ }
117
+ function open(id) {
118
+ if (disposed) return
119
+ /* 点当前标签=零操作(Chrome 同款):不重复触发宿主换选择/重建。 */
120
+ if (keeper.getState().activeId === id && !pendingOpen) { local.setSwitchTo(null); return }
121
+ local.setSwitchTo(id) /* 乐观高亮立即进 DOM,先画 */
122
+ if (pendingOpen && pendingOpen.id === id) return
123
+ scheduleHost(id)
124
+ }
125
+ /* v0.5 独立新建:宿主 startSession 会复用工作区内首个可复用空白,
126
+ 已有空白标签时再点"+"只回到同一空白、不产生新标签。这里绕开复用:
127
+ workspaces.list 仅做导航定位(activeId 所在工作区;无则含最近更新受管会话的
128
+ 工作区;再无则首个工作区),随后 sessions.create({workspaceId}) 不传
129
+ sessionId ⇒ 宿主必新建。成功后 manage 纳入受管集合(标签立即出现)+
130
+ open(paint-first);失败/无工作区回退宿主 startSession,按钮永不卡死。 */
131
+ function targetWorkspace() {
132
+ try {
133
+ var wl = ctx.workspaces && ctx.workspaces.list
134
+ var snap = wl && typeof wl.getSnapshot === 'function' ? wl.getSnapshot() : null
135
+ if (!snap || snap.phase !== 'ready' || !Array.isArray(snap.items) || !snap.items.length) return null
136
+ var st = keeper.getState()
137
+ var i, j, ids
138
+ if (st.activeId) {
139
+ for (i = 0; i < snap.items.length; i++) {
140
+ ids = snap.items[i].sessionIds || []
141
+ if (ids.indexOf(st.activeId) >= 0) return snap.items[i].workspaceId
142
+ }
143
+ }
144
+ var best = null, bestAt = -1
145
+ for (i = 0; i < snap.items.length; i++) {
146
+ ids = snap.items[i].sessionIds || []
147
+ for (j = 0; j < ids.length; j++) {
148
+ var row = st.sessions[ids[j]]
149
+ var at = row && typeof row.updatedAt === 'number' ? row.updatedAt : 0
150
+ if (at > bestAt) { bestAt = at; best = snap.items[i].workspaceId }
151
+ }
152
+ }
153
+ return best || snap.items[0].workspaceId
154
+ } catch (err) { return null }
155
+ }
156
+ function fallbackCreate() { try { ctx.uiWorkspace.startSession() } catch (err) {} }
157
+ function create() {
158
+ if (disposed) return
159
+ var target = targetWorkspace()
160
+ if (!target) { fallbackCreate(); return }
161
+ var pr = null
162
+ try { pr = ctx.sessions.create({ workspaceId: target }) } catch (err) {}
163
+ if (pr && typeof pr.then === 'function') {
164
+ pr.then(function (id) {
165
+ if (disposed || !id) return
166
+ keeper.manage(id, 'user-create')
167
+ open(id)
168
+ }).catch(fallbackCreate)
169
+ } else fallbackCreate()
170
+ }
171
+ function closeNow(id) {
172
+ var st = keeper.getState()
173
+ var wasActive = st.activeId === id
174
+ var idx = st.ids.indexOf(id)
175
+ var neighbor = st.ids[idx + 1] || st.ids[idx - 1] || null
176
+ keeper.unmanage(id)
177
+ /* 规则先行:关最后一个标签不再自动新建会话(那是一种自动添加)。
178
+ 有邻居则切到邻居;无邻居则留空标签条,主视图维持现状,由用户自行点开/新建。 */
179
+ if (wasActive && neighbor) open(neighbor)
180
+ }
181
+ return {
182
+ open: open,
183
+ create: create,
184
+ /* v0.8 排序意图:序真源在 keeper(落盘+publish 在那侧),薄 UI 只翻译。 */
185
+ move: function (id, toIndex) { if (!disposed && typeof keeper.move === 'function') keeper.move(id, toIndex) },
186
+ requestClose: function (id) {
187
+ var info = keeper.getState().sessions[id]
188
+ if (info && info.running) local.setPending(id)
189
+ else closeNow(id)
190
+ },
191
+ confirmClose: function () {
192
+ var id = local.getState().pendingClose
193
+ local.setPending(null)
194
+ if (!id) return
195
+ var pr = null
196
+ try {
197
+ pr = ctx.sessions.using(id, { source: 'controllerOperation' }, function (ref) { return ref.binding.session.cancel() })
198
+ } catch (err) {}
199
+ if (pr && typeof pr.then === 'function') {
200
+ pr.then(function (res) {
201
+ if (res && res.ok === false) notifyFail()
202
+ else closeNow(id)
203
+ }).catch(function () { notifyFail() })
204
+ } else closeNow(id)
205
+ },
206
+ dispose: function () {
207
+ disposed = true
208
+ cancelPending()
209
+ if (noticeTimer) { clearTimeout(noticeTimer); noticeTimer = null }
210
+ }
211
+ }
212
+ }
213
+
214
+ /* ================= 纯视图 ================= */
215
+ var CSS = [
216
+ '.cst-top{display:flex;align-items:center;box-sizing:border-box;height:28px;width:100%;flex:1 1 auto;max-width:100%;min-width:0;',
217
+ ' background:transparent;border:none;}',
218
+ '.cst-tab,.cst-close,.cst-new,.cst-mask{-webkit-app-region:no-drag;}',
219
+ '.cst-scroll{display:flex;align-items:center;gap:2px;flex:1 1 auto;min-width:0;max-width:100%;overflow-x:auto;overflow-y:hidden;scrollbar-width:thin;}',
220
+ '.cst-scroll::-webkit-scrollbar{height:4px}.cst-scroll::-webkit-scrollbar-thumb{background:var(--dsw-alias-border-l3,rgba(127,127,127,.3));border-radius:2px}',
221
+ /* 浏览器式填满+上限:flex-grow 让标签均分剩余宽度向条尾铺开,单标签上限
222
+ 240px(Chrome/Edge 同款),触顶后剩余空间留白;空间不足时等比收缩到
223
+ min-width 后横向滚动(溢出行为不变)。 */
224
+ '.cst-tab{display:inline-flex;align-items:center;gap:5px;flex:1 1 140px;min-width:56px;max-width:240px;height:24px;',
225
+ ' padding:0 4px 0 8px;border-radius:6px;box-sizing:border-box;cursor:pointer;',
226
+ ' font-size:12px;line-height:1;color:var(--dsw-alias-label-secondary,inherit);background:transparent;border:1px solid transparent;}',
227
+ '.cst-tab:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12));color:var(--dsw-alias-label-primary,inherit);}',
228
+ '.cst-tab.cst-active{background:var(--dsw-alias-interactive-bg-active,rgba(127,127,127,.16));color:var(--dsw-alias-label-primary,inherit);border-color:var(--dsw-alias-border-l3,rgba(127,127,127,.25));}',
229
+ '.cst-tab.cst-missing{opacity:.45;}',
230
+ /* v0.8 拖拽排序指示:画在标签/滚动口自身(inset shadow),零附加图层。 */
231
+ '.cst-tab.cst-dragging{opacity:.4;}',
232
+ '.cst-tab.cst-drop-before{box-shadow:inset 2px 0 0 0 var(--dsw-alias-state-business-primary,#3b82f6);}',
233
+ '.cst-tab.cst-drop-after{box-shadow:inset -2px 0 0 0 var(--dsw-alias-state-business-primary,#3b82f6);}',
234
+ '.cst-scroll.cst-drop-end{box-shadow:inset -2px 0 0 0 var(--dsw-alias-state-business-primary,#3b82f6);}',
235
+ /* 橙圈=疑似停滞:同款 spinner 但转速比蓝圈慢三倍(.8s→2.4s/圈),
236
+ 视觉上"转得吃力",与正常运行的快蓝圈一眼可分。 */
237
+ '.cst-tab.cst-stalled .cst-spin{border-top-color:var(--dsw-alias-state-warn-primary,#f5a524);animation-duration:2.4s;}',
238
+ '.cst-tab:focus-visible,.cst-close:focus-visible,.cst-new:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#3b82f6);outline-offset:-2px;}',
239
+ '.cst-title{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}',
240
+ '.cst-close{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border:none;border-radius:5px;background:transparent;color:inherit;cursor:pointer;font-size:12px;line-height:1;padding:0;opacity:.7;}',
241
+ '.cst-close:hover{opacity:1;background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.2));}',
242
+ '.cst-spin{flex:0 0 auto;width:11px;height:11px;border-radius:50%;box-sizing:border-box;border:1.5px solid var(--dsw-alias-border-l3,rgba(127,127,127,.35));border-top-color:var(--dsw-alias-state-business-primary,#3b82f6);animation:cst-rot .8s linear infinite;}',
243
+ '@keyframes cst-rot{to{transform:rotate(360deg)}}',
244
+ '@media (prefers-reduced-motion: reduce){.cst-spin{animation:none;}}',
245
+ /* 等待用户操作(问题/审批待答):红色问号替代转圈,不旋转。 */
246
+ '.cst-alert{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:12px;height:12px;',
247
+ ' color:var(--dsw-alias-state-error-primary,#e5484d);font-size:12px;font-weight:700;line-height:1;}',
248
+ '.cst-new{flex:0 0 auto;position:sticky;right:0;z-index:1;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;align-self:center;margin-left:2px;border:none;border-radius:6px;background:var(--dsw-alias-bg-base,#17181a);color:var(--dsw-alias-label-secondary,inherit);cursor:pointer;font-size:14px;line-height:1;padding:0;}',
249
+ '.cst-new:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.15));color:var(--dsw-alias-label-primary,inherit);}',
250
+ '.cst-empty{align-self:center;font-size:11px;color:var(--dsw-alias-label-tertiary,inherit);opacity:.7;padding:0 4px;white-space:nowrap;}',
251
+ '.cst-mask{position:fixed;inset:0;z-index:1600;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.35);pointer-events:auto;}',
252
+ '.cst-modal{width:320px;max-width:80vw;border-radius:12px;padding:16px;box-sizing:border-box;background:var(--dsw-alias-bg-base,#fff);color:var(--dsw-alias-label-primary,#222);border:1px solid var(--dsw-alias-border-l3,rgba(127,127,127,.25));box-shadow:0 8px 32px rgba(0,0,0,.25);}',
253
+ '.cst-modal h3{margin:0 0 8px;font-size:14px;}',
254
+ '.cst-modal p{margin:0 0 16px;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary,#666);word-break:break-all;}',
255
+ '.cst-modal .row{display:flex;justify-content:flex-end;gap:8px;}',
256
+ '.cst-btn{border:1px solid var(--dsw-alias-border-l3,rgba(127,127,127,.3));border-radius:8px;padding:6px 12px;font-size:12px;cursor:pointer;background:transparent;color:inherit;}',
257
+ '.cst-btn.danger{background:var(--dsw-alias-state-business-primary,#3b82f6);border-color:transparent;color:#fff;}',
258
+ '.cst-notice{position:fixed;top:calc(var(--dsh-windows-titlebar-height,var(--dsh-frame-top-clearance,40px)) + 8px);left:50%;transform:translateX(-50%);',
259
+ ' z-index:1600;max-width:80vw;padding:8px 14px;border-radius:8px;box-sizing:border-box;pointer-events:none;',
260
+ ' font-size:12px;line-height:1.5;background:var(--dsw-alias-bg-overlay,#fff);color:var(--dsw-alias-label-primary,#222);',
261
+ ' border:1px solid var(--dsw-alias-state-error-primary,#e5484d);box-shadow:0 4px 16px rgba(0,0,0,.2);}'
262
+ ].join('\n')
263
+
264
+ function makeTopBarView(keeper, local, bridge, menus) {
265
+ return function TopBarView() {
266
+ var setTick = React.useState(0)[1]
267
+ var ks = keeper.getState()
268
+ var ls = local.getState()
269
+ React.useEffect(function () {
270
+ var unK = keeper.subscribe(function () { setTick(function (t) { return t + 1 }) })
271
+ var unL = local.subscribe(function () { setTick(function (t) { return t + 1 }) })
272
+ return function () { unK(); unL() }
273
+ }, [keeper, local])
274
+ React.useEffect(function () {
275
+ var style = document.createElement('style')
276
+ style.id = 'cst-css'
277
+ style.textContent = CSS
278
+ document.head.appendChild(style)
279
+ return function () { if (style.parentNode) style.parentNode.removeChild(style) }
280
+ }, [])
281
+ React.useEffect(function () {
282
+ /* 只滚标签条自身(scrollLeft),不 scrollIntoView 连带祖先容器/整页——
283
+ 避免每次切换触发外层布局与滚动跳动(v0.7)。 */
284
+ var sc = document.querySelector('.cst-scroll')
285
+ var act = sc && sc.querySelector('.cst-tab.cst-active')
286
+ if (!sc || !act || !sc.getBoundingClientRect) return
287
+ var sr = sc.getBoundingClientRect(), ar = act.getBoundingClientRect()
288
+ var left = ar.left - sr.left + sc.scrollLeft
289
+ var right = left + ar.width
290
+ if (left < sc.scrollLeft) sc.scrollLeft = left - 4
291
+ else if (right > sc.scrollLeft + sc.clientWidth) sc.scrollLeft = right - sc.clientWidth + 4
292
+ }, [ks.activeId, ls.switchTo, ks.ids.length])
293
+
294
+ function onKey(ev, id, idx) {
295
+ var k = ev.key
296
+ if (k === 'Enter' || k === ' ') { ev.preventDefault(); bridge.open(id) }
297
+ else if (k === 'Delete' || k === 'Backspace') { ev.preventDefault(); bridge.requestClose(id) }
298
+ else if (k === 'ContextMenu' || (ev.shiftKey && k === 'F10')) {
299
+ ev.preventDefault()
300
+ var r = ev.currentTarget.getBoundingClientRect()
301
+ openMenu(id, (keeper.getState().sessions[id] || {}).title || '会话', r.left, r.bottom)
302
+ }
303
+ else if (ev.altKey && (k === 'ArrowRight' || k === 'ArrowLeft')) {
304
+ /* v0.8 键盘排序(触屏/无鼠标可达性兜底):与拖拽同一落点 keeper.move。 */
305
+ ev.preventDefault()
306
+ bridge.move(id, idx + (k === 'ArrowRight' ? 1 : -1))
307
+ }
308
+ else if (k === 'ArrowRight' || k === 'ArrowLeft') {
309
+ ev.preventDefault()
310
+ var tabs = document.querySelectorAll('.cst-tab')
311
+ var n = tabs[idx + (k === 'ArrowRight' ? 1 : -1)]
312
+ if (n) n.focus()
313
+ }
314
+ }
315
+
316
+ /* 右键/菜单键 ⇒ 复用宿主会话右键菜单(与工作区侧栏同一组贡献,不复制菜单项)。 */
317
+ function openMenu(id, title, x, y) {
318
+ if (menus && menus.open) menus.open({ kind: 'session', value: { sessionId: id, displayTitle: title } }, { x: x, y: y })
319
+ }
320
+
321
+ /* v0.8 拖拽排序(HTML5 原生 DnD):dragover 以中线判 before/after;drop 换算
322
+ 目标索引(先移除再插入:from<to 时 to--);序变更只经 keeper.move。
323
+ 指示画在标签/滚动口自身(inset shadow),零附加图层。 */
324
+ function dragOverTab(ev, id) {
325
+ if (!ls.dragId || ls.dragId === id) return
326
+ ev.preventDefault()
327
+ ev.stopPropagation()
328
+ var r = ev.currentTarget.getBoundingClientRect()
329
+ var side = ev.clientX < r.left + r.width / 2 ? 'before' : 'after'
330
+ local.setDropHint({ overId: id, side: side })
331
+ }
332
+ function dropOnTab(ev, id, idx) {
333
+ if (!ls.dragId) return
334
+ ev.preventDefault()
335
+ ev.stopPropagation()
336
+ if (ls.dragId !== id) {
337
+ var r = ev.currentTarget.getBoundingClientRect()
338
+ var after = ev.clientX >= r.left + r.width / 2
339
+ var from = ks.ids.indexOf(ls.dragId)
340
+ var to = idx + (after ? 1 : 0)
341
+ if (from >= 0 && from < to) to--
342
+ bridge.move(ls.dragId, to)
343
+ }
344
+ local.setDrag(null); local.setDropHint(null)
345
+ }
346
+ /* 空白/「+」区(非标签目标)⇒ 移到末尾;标签自身的事件已 stopPropagation。 */
347
+ function dragOverEnd(ev) {
348
+ if (!ls.dragId) return
349
+ if (ev.target && ev.target.closest && ev.target.closest('.cst-tab')) return
350
+ ev.preventDefault()
351
+ local.setDropHint({ overId: null, side: 'end' })
352
+ }
353
+ function dropOnEnd(ev) {
354
+ if (!ls.dragId) return
355
+ if (ev.target && ev.target.closest && ev.target.closest('.cst-tab')) return
356
+ ev.preventDefault()
357
+ bridge.move(ls.dragId, ks.ids.length - 1)
358
+ local.setDrag(null); local.setDropHint(null)
359
+ }
360
+
361
+ /* 乐观高亮:宿主 activeId 未跟上时先亮点击目标;跟上后 switchTo 被清。 */
362
+ var switching = ls.switchTo && ls.switchTo !== ks.activeId ? ls.switchTo : null
363
+ var tabs = ks.ids.map(function (id, idx) {
364
+ var info = ks.sessions[id] || {}
365
+ var active = id === ks.activeId || id === ls.switchTo
366
+ var running = !!info.running
367
+ var awaiting = !!info.awaiting
368
+ var missing = info.status === 'missing'
369
+ var stalled = info.status === 'stalled'
370
+ var title = info.title || '会话'
371
+ var suffix = awaiting ? '(等待你的操作)' : running ? '(运行中)' : stalled ? '(疑似停滞)' : missing ? '(已消失)' : ''
372
+ return e('div', {
373
+ key: id,
374
+ className: 'cst-tab' + (active ? ' cst-active' : '') + (missing ? ' cst-missing' : '') + (stalled ? ' cst-stalled' : '') + (id === switching ? ' cst-switching' : '') + (id === ls.dragId ? ' cst-dragging' : '') + (ls.dropHint && ls.dropHint.overId === id ? (ls.dropHint.side === 'before' ? ' cst-drop-before' : ' cst-drop-after') : ''),
375
+ role: 'tab', tabIndex: 0,
376
+ 'aria-selected': active, 'aria-busy': id === switching ? true : undefined,
377
+ title: title + suffix,
378
+ /* v0.8 拖拽排序:原生 DnD;从关闭按钮起拖不进入拖拽。 */
379
+ draggable: true,
380
+ onDragStart: function (ev) {
381
+ if (ev.target && ev.target.closest && ev.target.closest('.cst-close')) { ev.preventDefault(); return }
382
+ if (ev.dataTransfer) { try { ev.dataTransfer.setData('text/plain', id); ev.dataTransfer.effectAllowed = 'move' } catch (err) {} }
383
+ local.setDrag(id)
384
+ },
385
+ onDragOver: function (ev) { dragOverTab(ev, id) },
386
+ onDrop: function (ev) { dropOnTab(ev, id, idx) },
387
+ onDragEnd: function () { local.setDrag(null); local.setDropHint(null) },
388
+ /* v0.7 按下即激活(鼠标/笔):高亮不等抬手,Chrome 同款手感。触屏留给
389
+ click(防滚动横条时误触);关闭按钮/修饰键不抢占。随后的 click 再调
390
+ open 为幂等无操作(同目标不重复调度),键盘 Enter/Space 仍走 click。 */
391
+ onPointerDown: function (ev) {
392
+ if (ev.button !== 0 || ev.pointerType === 'touch') return
393
+ if (ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.altKey) return
394
+ if (ev.target && ev.target.closest && ev.target.closest('.cst-close')) return
395
+ bridge.open(id)
396
+ },
397
+ onClick: function () { bridge.open(id) },
398
+ onContextMenu: function (ev) { ev.preventDefault(); ev.stopPropagation(); openMenu(id, title, ev.clientX, ev.clientY) },
399
+ onKeyDown: function (ev) { onKey(ev, id, idx) }
400
+ },
401
+ /* 等待用户操作(待答问题/审批)⇒ 红色问号,优先于 running 转圈;
402
+ 其余 spinner 仅 running(Chrome 网页加载圈同款语义);切换中不画 spinner——
403
+ 乐观高亮已是足够点击反馈,中间态转圈只会闪一下(Chrome/Edge 无此中间态)。 */
404
+ awaiting ? e('span', { className: 'cst-alert', 'aria-hidden': true }, '?') : null,
405
+ running && !awaiting ? e('span', { className: 'cst-spin', 'aria-hidden': true }) : null,
406
+ e('span', { className: 'cst-title' }, title),
407
+ e('button', {
408
+ className: 'cst-close', tabIndex: -1, 'aria-label': '关闭标签 ' + title,
409
+ title: running ? '停止并关闭' : missing ? '移除标签' : '关闭标签',
410
+ onClick: function (ev) { ev.stopPropagation(); bridge.requestClose(id) }
411
+ }, '×')
412
+ )
413
+ })
414
+ /* 「+」紧跟最后一个标签(Chrome/Edge 同款),不再钉在条尾:作为滚动行
415
+ 最后一个子节点;溢出时 position:sticky;right:0 钉住滚动口右缘保持可见。 */
416
+ var newBtn = e('button', { key: '__n', className: 'cst-new', 'aria-label': '新建会话', title: '新建会话(必新建独立标签)', onClick: function () { bridge.create() } }, '+')
417
+ var scroll = e('div', {
418
+ className: 'cst-scroll' + (ls.dropHint && ls.dropHint.side === 'end' ? ' cst-drop-end' : ''),
419
+ onDragOver: dragOverEnd, onDrop: dropOnEnd
420
+ }, (tabs.length ? tabs : [e('span', { key: '__e', className: 'cst-empty' }, ks.phase === 'ready' ? '没有打开的会话' : '加载中…')]).concat([newBtn]))
421
+ var bar = e('div', { className: 'cst-top', role: 'tablist' }, scroll)
422
+
423
+ var modal = null
424
+ if (ls.pendingClose) {
425
+ var pTitle = (ks.sessions[ls.pendingClose] || {}).title || '会话'
426
+ modal = e('div', { className: 'cst-mask', onClick: function () { local.setPending(null) } },
427
+ e('div', { className: 'cst-modal', role: 'dialog', 'aria-modal': true, onClick: function (ev) { ev.stopPropagation() } },
428
+ e('h3', null, '停止并关闭标签?'),
429
+ e('p', null, '「' + pTitle + '」正在运行。关闭标签将停止它正在进行的任务。'),
430
+ e('div', { className: 'row' },
431
+ e('button', { className: 'cst-btn', onClick: function () { local.setPending(null) } }, '取消'),
432
+ e('button', { className: 'cst-btn danger', onClick: function () { bridge.confirmClose() } }, '停止并关闭'))))
433
+ }
434
+ var notice = ls.notice ? e('div', { className: 'cst-notice', role: 'alert' }, ls.notice) : null
435
+ return e(React.Fragment, null, bar, modal, notice)
436
+ }
437
+ }
438
+
439
+ /* ================= 装配 ================= */
440
+ var api = {
441
+ name: '@capyclaw/session-tabs',
442
+ inject: ['uiWorkspace', 'sessions', 'sessionKeeper', 'captionExtra', 'contextMenus', 'workspaces'],
443
+ apply: function (ctx) {
444
+ var keeper = ctx.sessionKeeper
445
+ var anchor = ctx.captionExtra
446
+ var local = createLocal()
447
+ var bridge = createBridge(ctx, keeper, local)
448
+ var View = makeTopBarView(keeper, local, bridge, ctx.contextMenus)
449
+ /* 宿主选择跟上点击目标后清乐观高亮。 */
450
+ var unSwitch = keeper.subscribe(function () {
451
+ var sw = local.getState().switchTo
452
+ if (sw && keeper.getState().activeId === sw) local.setSwitchTo(null)
453
+ })
454
+ /* 挂载锚同步:mount 节点出现/消失/重建时重挂 React 根;缺席则不渲染。 */
455
+ var root = null
456
+ var rootEl = null
457
+ function sync() {
458
+ var el = anchor.getMount()
459
+ if (el === rootEl) return
460
+ if (root) { root.unmount(); root = null }
461
+ rootEl = el
462
+ if (el) { root = ReactDOM.createRoot(el); root.render(e(View)) }
463
+ }
464
+ anchor.acquire()
465
+ var unSub = anchor.subscribe(sync)
466
+ sync()
467
+ return function () {
468
+ unSub()
469
+ unSwitch()
470
+ if (root) { root.unmount(); root = null; rootEl = null }
471
+ anchor.release()
472
+ bridge.dispose()
473
+ }
474
+ }
475
+ }
476
+ return api
477
+ }
478
+ })