@capyclaw/port-sidebar 0.0.0-stage → 1.0.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CapyClaw
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,55 @@
1
- # Temporary Holding Version
1
+ # dsh-port-sidebar
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 在 DSH 右侧边栏**稳定展示一个本机端口页面**:每个会话的右侧边栏都确保存在一个指向该端口的 Browser tab,**切换会话/换话题不消失**;会话切回来时页面保留(不重载,桌面端为原生 webview + keepMounted)。
4
+
5
+ ## 结构
6
+
7
+ ```text
8
+ dsh-port-sidebar/
9
+ ├── package.json # dsh.client(浏览器半声明)+ exports["./client"] + bundle patch
10
+ ├── cordis.patch.yml # 挂载宿主半;config 里改端口
11
+ ├── lib/host.mjs # 宿主半:向 webserver/index-inject 推送 __DSH_PORT_SIDEBAR__ 全局行
12
+ ├── lib/url.mjs # 地址解析(config / 环境变量 / 默认值,纯函数)
13
+ ├── client/client.js # 浏览器半:每个会话确保 Browser tab(手写 __ModuleLoader__ 工厂协议)
14
+ └── test/plugin.test.mjs
15
+ ```
16
+
17
+ ## 安装
18
+
19
+ ```bash
20
+ dsh plugin --profile web add <本目录绝对路径>
21
+ ```
22
+
23
+ 或走 Web 界面:侧边栏「插件」页 → 安装 → 填本目录的本地路径。装完**刷新页面**(注入行在每次 index 渲染时携带,刷新即生效)。
24
+
25
+ ## 注入端口号(每次启动)
26
+
27
+ 优先级从高到低:
28
+
29
+ | 方式 | 示例 |
30
+ |---|---|
31
+ | 环境变量(完整地址) | `DSH_PORT_SIDEBAR_URL=http://127.0.0.1:39500/workbench` |
32
+ | 环境变量(端口) | `DSH_PORT_SIDEBAR_PORT=39500` |
33
+ | cordis.patch.yml 的 `config` | `port: 39600` / `url: …` / `path: /` / `restoreOnBoot: true` |
34
+ | 默认 | `http://127.0.0.1:39600/` |
35
+
36
+ 改完 `cordis.patch.yml` 或环境变量后重启 dsh 并刷新页面即可。
37
+
38
+ ## 行为细节
39
+
40
+ - **每会话一个 tab**:右侧边栏 tab 属于会话;本插件在每次屏上会话变化时确保该会话有指向目标端口的 Browser tab(页面 tab 在目标格内天然去重,不会重复开)。
41
+ - **不劫持**:每个页面加载周期内每个会话只处理一次;你自己开的 Browser tab 之后不会被覆盖导航。目标格内已有 Browser tab 且 `restoreOnBoot: false` 时完全不动它。
42
+ - **restoreOnBoot(默认开)**:应用重启后,恢复出的 Browser tab 只显示地址不自动加载(dsh 的安全设计);本插件对它补一次导航参数,等价于自动点 Restore。设 `false` 保留手动 Restore。
43
+ - **可见性**:目标格内没有 tab 时会新开(右栏随之展开一次);已有 tab 时不抢焦点(`revealIfOpened: false`)。
44
+
45
+ ## 注意
46
+
47
+ - 仅支持 `http/https` 目标(与 Browser tab 类型一致);`https` 页面里嵌 `http` 端口可能被浏览器混合内容策略拦截,桌面客户端(webview)无此问题。
48
+ - 该组合必须挂载右侧边栏(`ui-sidebar-browser` 提供的 `browser` 类型);缺失时插件告警并放弃,不影响启动。
49
+
50
+ ## 测试
51
+
52
+ ```bash
53
+ cd plugins/dsh-port-sidebar
54
+ npm test
55
+ ```
@@ -0,0 +1,438 @@
1
+ /**
2
+ * dsh-port-sidebar 浏览器半。
3
+ *
4
+ * 装载协议与 tsdown 客户端产物一致:`window.__ModuleLoader__.load({ id, factory })`,
5
+ * factory 内以 CJS 组装 Cordis 插件并返回 module.exports。
6
+ *
7
+ * 设计(0.2.0 实测后确定):
8
+ * 本插件注册**自己的**右侧边栏 tab 类型(kind `portSidebar`),正文就是一个指向
9
+ * 目标端口的 iframe。不用借 Browser 类型,因为 Browser 声明了 `multiple: true`,
10
+ * 每次 openTab 都是独立新 tab,且它的导航参数依赖 `navigation.params` 在会话
11
+ * store 就绪的那一刻送达——会话刚切换时容易丢,于是留下空白 tab、也无法区分
12
+ * "我的 tab"和用户自己的浏览器 tab。
13
+ *
14
+ * 自有类型带来三点确定性:
15
+ * 1. 正文自己决定 src,不依赖导航参数,不会丢;
16
+ * 2. kind 唯一 => 关闭回调、清单检查都能精确命中"我这一个";
17
+ * 3. `keepMounted: true`,切 tab/折叠不销毁 iframe,切会话回来页面不重载。
18
+ *
19
+ * 强制保活:默认开启。任何方式关掉(X、关闭命令)都会在关闭回调里立刻重开;
20
+ * 清单变化做兜底。插件不卸载,这个 tab 就关不掉。
21
+ */
22
+ window.__ModuleLoader__.load({ id: '@capyclaw/port-sidebar', factory: (require) => {
23
+ var module = { exports: {} }; var exports = module.exports;
24
+
25
+ /** 本插件在 tab 系统里的实现 id(也是正文/标题插槽的 key)。 */
26
+ var TAB_ID = 'dsh-port-sidebar'
27
+ /** 本插件独占的 tab kind。 */
28
+ var TAB_KIND = 'portSidebar'
29
+ /** tab 标题(未注册标题插槽时的回退文本也用这个)。 */
30
+ var TAB_TITLE = '端口面板'
31
+
32
+ var React = require('react')
33
+
34
+ /**
35
+ * 调优层(进化搜索 NSGA-II 固化的基线):评估器经
36
+ * globalThis.__DSH_PORT_SIDEBAR_TUNING__ 注入基因组逐项覆盖;
37
+ * 生产默认值 = founder 基线,进化必须证明优于现状才能替换。
38
+ */
39
+ var TUNING = (function () {
40
+ var base = {
41
+ /** 补试第 2/3 档延迟(避开 mounted→store 铸造窗口)。 */
42
+ retry2Ms: 200,
43
+ retry3Ms: 1000,
44
+ /** 保活轮询步长。 */
45
+ checkIntervalMs: 300,
46
+ /** 打开互斥窗口:openTab 提交后清单落账前不再发第二次打开。 */
47
+ pendingOpenMs: 800,
48
+ /** 复活节流:同会话两次复活最小间隔。 */
49
+ reviveCooldownMs: 400,
50
+ /** 单会话最大连续失败次数。 */
51
+ maxFailuresPerSession: 5,
52
+ /** 折叠门:侧栏折叠时首次打开是否让位(true=不抢布局)。 */
53
+ collapseGate: true,
54
+ }
55
+ try {
56
+ var evo = globalThis.__DSH_PORT_SIDEBAR_TUNING__
57
+ if (evo && typeof evo === 'object') {
58
+ for (var k in base) {
59
+ if (k in evo && evo[k] !== undefined && evo[k] !== null) base[k] = evo[k]
60
+ }
61
+ }
62
+ } catch (error) { /* 调优注入失败按默认跑 */ }
63
+ return base
64
+ })()
65
+
66
+ /** 一次失效后的补试时刻(毫秒):由调优层前两档组成。 */
67
+ var RETRY_DELAYS_MS = [0, TUNING.retry2Ms, TUNING.retry3Ms]
68
+ /** 单会话最大失败次数:超过后放弃并告警一次(如该组合未挂右侧边栏)。 */
69
+ var MAX_FAILURES_PER_SESSION = TUNING.maxFailuresPerSession
70
+ /** 复活节流:同一会话在此窗口内不重复重开。 */
71
+ var REVIVE_COOLDOWN_MS = TUNING.reviveCooldownMs
72
+ /** 打开互斥:提交 openTab 后清单落账前,不再发第二次打开。 */
73
+ var PENDING_OPEN_MS = TUNING.pendingOpenMs
74
+ /** 保活轮询步长(替代旧 CHECK_INTERVAL_MS 常量)。 */
75
+ var CHECK_INTERVAL_MS = TUNING.checkIntervalMs
76
+
77
+ /** 正文:目标端口的 iframe。背景取页面主题色,消除加载期的白闪。 */
78
+ function createBody(url) {
79
+ var bg = 'transparent'
80
+ try {
81
+ var cs = getComputedStyle(document.body)
82
+ if (cs && cs.backgroundColor && cs.backgroundColor !== 'rgba(0, 0, 0, 0)') bg = cs.backgroundColor
83
+ } catch (error) { /* 拿不到就用透明 */ }
84
+ return function PortSidebarBody() {
85
+ return React.createElement('iframe', {
86
+ src: url,
87
+ title: TAB_TITLE,
88
+ style: { width: '100%', height: '100%', border: '0', display: 'block', background: bg },
89
+ })
90
+ }
91
+ }
92
+
93
+ /** 标题:固定文案,避免显示成内部地址。 */
94
+ function PortSidebarTitle() {
95
+ return React.createElement('span', null, TAB_TITLE)
96
+ }
97
+
98
+ module.exports = {
99
+ name: 'dsh-port-sidebar',
100
+ inject: ['slots', 'sidebarRight', 'sidebarRightTabs'],
101
+ apply: function (ctx) {
102
+ var boot = globalThis.__DSH_PORT_SIDEBAR__
103
+ var url = boot && typeof boot.url === 'string' ? boot.url : undefined
104
+ if (url === undefined) {
105
+ console.warn('[dsh-port-sidebar] 页面未收到 __DSH_PORT_SIDEBAR__,请确认宿主半已加载且目标地址可解析')
106
+ return
107
+ }
108
+ var keepAlive = !(boot && boot.keepAlive === false)
109
+ var sidebar = ctx.sidebarRight
110
+
111
+ /** 强制校正:即使旧 tab 被恢复,iframe 也必须指向注入的 URL(防错实例)。 */
112
+ function enforceUrl() {
113
+ if (disposed) return
114
+ try {
115
+ var frames = document.querySelectorAll('iframe[title="' + TAB_TITLE + '"]')
116
+ for (var i = 0; i < frames.length; i++) {
117
+ var frame = frames[i]
118
+ if (frame.getAttribute('src') !== url) {
119
+ frame.setAttribute('src', url)
120
+ note('force-src')
121
+ }
122
+ }
123
+ } catch (error) { /* DOM 异常忽略 */ }
124
+ }
125
+
126
+ /** 诊断出口:把关键步骤记到全局,便于在页面控制台/自动化里核对。 */
127
+ var diag = { plugin: 'applied', opened: 0, closes: 0, revives: 0, adopted: 0, lastError: null, events: [] }
128
+ globalThis.__DSH_PORT_SIDEBAR_DEBUG__ = diag
129
+ /** 快照(只含原始值,避免自动化读 diag 时的循环引用)。 */
130
+ diag.snapshot = function () {
131
+ var mounted = sidebar.mounted.getSnapshot()
132
+ return {
133
+ mounted: mounted,
134
+ expanded: sidebarExpanded(),
135
+ ensured: Array.from(ensured),
136
+ hasOwnTab: mounted !== undefined ? hasOwnTab(mounted) : null,
137
+ ownTabs: sidebar.openTabs.getSnapshot().filter(function (t) { return t.kind === TAB_KIND }),
138
+ pending: Array.from(pendingOpen.entries()),
139
+ now: Date.now(),
140
+ }
141
+ }
142
+ function note(event) {
143
+ diag.events.push(event + '@' + Date.now())
144
+ if (diag.events.length > 40) diag.events.shift()
145
+ }
146
+
147
+ // 1. 注册类型(只做一次,随 fiber 卸载)
148
+ ctx.effect(function () {
149
+ return ctx.sidebarRightTabs.register({
150
+ id: TAB_ID,
151
+ kind: TAB_KIND,
152
+ // multiple: false (默认) → 每个会话每个 pane 最多一个,openTab 去重
153
+ keepMounted: true,
154
+ priority: 'extension',
155
+ title: function () { return TAB_TITLE },
156
+ })
157
+ }, 'dsh-port-sidebar.type')
158
+
159
+ // 2. 注册正文与标题插槽
160
+ ctx.effect(function () {
161
+ return ctx.slots.inject('sidebar.right.pane.tab', function () {
162
+ return ctx.slots.register({ name: 'sidebar.right.pane.tab', key: TAB_ID }, createBody(url))
163
+ })
164
+ }, 'dsh-port-sidebar.body')
165
+
166
+ ctx.effect(function () {
167
+ return ctx.slots.inject('sidebar.right.pane.tab.title', function () {
168
+ return ctx.slots.register({ name: 'sidebar.right.pane.tab.title', key: TAB_ID }, PortSidebarTitle)
169
+ })
170
+ }, 'dsh-port-sidebar.title')
171
+
172
+ // 3. 保活:每个屏上会话一个自己的 tab,关掉就重开
173
+ /** 已认领过的会话:每会话每个页面生命周期只"首次打开"一次,杜绝清单延迟造成的重复开。 */
174
+ var ensured = new Set()
175
+ /** 会话 → 上次观测到的"有 tab"状态(用于识别关闭)。 */
176
+ var lastHad = new Map()
177
+ var failureCount = new Map()
178
+ var revivedAt = new Map()
179
+ var pendingOpen = new Map()
180
+ var retryTimers = [null, null, null]
181
+ var disposed = false
182
+
183
+ function hasOwnTab(sessionId) {
184
+ return sidebar.openTabs.getSnapshot().some(function (tab) {
185
+ return tab.sessionId === sessionId && tab.kind === TAB_KIND
186
+ })
187
+ }
188
+
189
+
190
+ function isPendingOpen(sessionId) {
191
+ var at = pendingOpen.get(sessionId)
192
+ return at !== undefined && Date.now() - at < PENDING_OPEN_MS
193
+ }
194
+
195
+ /** 侧栏是否展开;拿不到状态时按展开处理(保持旧行为)。 */
196
+ function sidebarExpanded() {
197
+ try {
198
+ return typeof sidebar.isExpanded !== 'function' || sidebar.isExpanded() !== false
199
+ } catch (error) {
200
+ return true
201
+ }
202
+ }
203
+
204
+ /** 避开会话切换的渲染帧:把"动布局"的操作推迟到空闲时机。 */
205
+ function whenIdle(fn) {
206
+ if (typeof requestIdleCallback === 'function') {
207
+ requestIdleCallback(function () { if (!disposed) fn() }, { timeout: 600 })
208
+ } else {
209
+ setTimeout(function () { if (!disposed) fn() }, 120)
210
+ }
211
+ }
212
+
213
+ var idleScheduled = new Set()
214
+ var collapseNoteAt = 0
215
+
216
+ function adopt(sessionId) {
217
+ ensured.add(sessionId)
218
+ diag.adopted = (diag.adopted || 0) + 1
219
+ note('adopt:' + sessionId.slice(0, 12))
220
+ }
221
+
222
+ function openPortTab(sessionId) {
223
+ pendingOpen.set(sessionId, Date.now())
224
+ diag.opened += 1
225
+ note('open:' + sessionId.slice(0, 12))
226
+ // revealIfOpened: true → 如果已有就激活,没有就创建(避免去重静默忽略)
227
+ sidebar.openTab(TAB_KIND, { revealIfOpened: true })
228
+ // 认领:此后本会话不再"首次打开",只允许关闭后复活。
229
+ ensured.add(sessionId)
230
+ }
231
+
232
+ function ensureOnce() {
233
+ var sessionId = sidebar.mounted.getSnapshot()
234
+ if (sessionId === undefined) return
235
+ // 关键:已认领过的会话绝不再"首次打开"(这是重复 tab 的根因)。
236
+ if (ensured.has(sessionId)) return
237
+ if (isPendingOpen(sessionId)) return
238
+ // 收养已存在的自有 tab(冷启动恢复出的那个),纳入保活覆盖。
239
+ if (hasOwnTab(sessionId)) {
240
+ adopt(sessionId)
241
+ return
242
+ }
243
+ var count = failureCount.get(sessionId) || 0
244
+ if (count >= MAX_FAILURES_PER_SESSION) return
245
+ // 优化 #3:侧栏折叠时不抢布局;轮询会在用户展开后补开。
246
+ if (TUNING.collapseGate && !sidebarExpanded()) {
247
+ if (Date.now() - collapseNoteAt > 2000) {
248
+ note('defer:collapsed')
249
+ collapseNoteAt = Date.now()
250
+ }
251
+ return
252
+ }
253
+ // 优化 #2:避开切换帧,放到空闲时机再创建。
254
+ if (idleScheduled.has(sessionId)) return
255
+ idleScheduled.add(sessionId)
256
+ whenIdle(function () {
257
+ idleScheduled.delete(sessionId)
258
+ if (disposed || ensured.has(sessionId)) return
259
+ if (hasOwnTab(sessionId)) {
260
+ adopt(sessionId)
261
+ return
262
+ }
263
+ if (!sidebarExpanded()) return
264
+ try {
265
+ openPortTab(sessionId)
266
+ } catch (error) {
267
+ failureCount.set(sessionId, (failureCount.get(sessionId) || 0) + 1)
268
+ if ((failureCount.get(sessionId) || 0) >= MAX_FAILURES_PER_SESSION) {
269
+ console.warn('[dsh-port-sidebar] 放弃为会话注入 tab(连续失败 ' + failureCount.get(sessionId) + ' 次)', error)
270
+ }
271
+ }
272
+ })
273
+ }
274
+
275
+ function schedule() {
276
+ for (var i = 0; i < RETRY_DELAYS_MS.length; i++) {
277
+ if (retryTimers[i] !== null) continue
278
+ retryTimers[i] = setTimeout(function (tier) {
279
+ return function () {
280
+ retryTimers[tier] = null
281
+ if (disposed) return
282
+ try {
283
+ ensureOnce()
284
+ checkAndRevive()
285
+ } catch (error) {
286
+ console.warn('[dsh-port-sidebar] 注入检查失败', error)
287
+ }
288
+ }
289
+ }(i), RETRY_DELAYS_MS[i])
290
+ }
291
+ }
292
+
293
+ function onInventoryChange() {
294
+ try {
295
+ checkAndRevive()
296
+ } catch (error) {
297
+ console.warn('[dsh-port-sidebar] 保活检查失败', error)
298
+ }
299
+ schedule()
300
+ }
301
+
302
+ // 主保活:纯定时轮询(步长走 TUNING.checkIntervalMs)
303
+ var unregisterClose
304
+ if (typeof sidebar.registerCloseHandler === 'function') {
305
+ try {
306
+ unregisterClose = sidebar.registerCloseHandler(TAB_KIND, function (closedSessionId) {
307
+ diag.closes += 1
308
+ note('close:' + closedSessionId.slice(0, 12))
309
+ // 清理 pending 标记(虽然 handler 可能不会再触发,但初始化时能帮助)
310
+ pendingOpen.delete(closedSessionId)
311
+ })
312
+ } catch (error) {
313
+ diag.lastError = String(error)
314
+ console.warn('[dsh-port-sidebar] 无法注册关闭钩子', error)
315
+ }
316
+ }
317
+
318
+ function checkAndRevive() {
319
+ if (!keepAlive) return
320
+ var now = Date.now()
321
+ if (now - lastCheckTime < CHECK_INTERVAL_MS) return
322
+ lastCheckTime = now
323
+ var mounted = sidebar.mounted.getSnapshot()
324
+ if (mounted === undefined) return
325
+ // 注意:复活不受折叠门限制——"关不掉"是强制契约;折叠门只管首次打开。
326
+
327
+ var hasTab = hasOwnTab(mounted)
328
+ var hasPending = isPendingOpen(mounted)
329
+ var previouslyHad = lastHad.get(mounted) === true
330
+ // 清单是会话级的、权威的;DOM 检查跨会话污染(保留式布局下,
331
+ // 其他会话的隐藏树里也有同名 tab),不能用于关闭判定。
332
+ lastHad.set(mounted, hasTab)
333
+
334
+ // 只复活"我们认领过"的会话:没认领过的交给 ensureOnce 首次打开。
335
+ if (!ensured.has(mounted)) return
336
+
337
+ // 检测关闭:上次有、这次没有 → 让复活立刻生效。
338
+ if (previouslyHad && !hasTab) {
339
+ note('detected-close:' + mounted.slice(0, 12))
340
+ pendingOpen.delete(mounted)
341
+ hasPending = false
342
+ }
343
+
344
+ // pending 过期仍无 tab → 说明上次打开被静默丢弃,允许重试。
345
+ if (hasPending && !hasTab) {
346
+ var pendingAge = now - pendingOpen.get(mounted)
347
+ if (pendingAge > PENDING_OPEN_MS) {
348
+ note('clearStale:' + mounted.slice(0, 12))
349
+ pendingOpen.delete(mounted)
350
+ hasPending = false
351
+ }
352
+ }
353
+
354
+ if (hasTab || hasPending) return
355
+
356
+ var last = revivedAt.get(mounted)
357
+ if (last !== undefined && now - last < REVIVE_COOLDOWN_MS) return
358
+ revivedAt.set(mounted, now)
359
+ diag.revives += 1
360
+ note('revive:' + mounted.slice(0, 12))
361
+ try {
362
+ openPortTab(mounted)
363
+ } catch (error) {
364
+ diag.lastError = String(error)
365
+ note('openFail:' + String(error).slice(0, 40))
366
+ console.warn('[dsh-port-sidebar] 保活重开失败', error)
367
+ }
368
+ }
369
+
370
+ /**
371
+ * 主保活:UI 层拦截。在 capture 阶段吞掉"我们这个 tab"的关闭点击,
372
+ * 让关闭根本不发生(实测 close→revive 会与关闭事务竞态:openTab 落进
373
+ * tab domain 却不渲染,反复重开反而把面板搞没)。键盘关闭命令等
374
+ * 非 click 路径兜不住,由下方轮询复活兜底。
375
+ * 识别方式:按钮带 关闭/close 标签,且位于 [data-dockkit-tab] 内,
376
+ * 该 tab 的 id 与清单里"当前屏上会话的我们这个 kind"的 tabId 一致
377
+ * ——只拦自己的,不碰用户自己开的 tab。
378
+ */
379
+ function guardCloseClicks(event) {
380
+ if (disposed) return
381
+ var target = event.target
382
+ if (!target || typeof target.closest !== 'function') return
383
+ var btn = target.closest('button')
384
+ if (!btn) return
385
+ var label = btn.getAttribute('aria-label') || btn.getAttribute('title') || ''
386
+ if (!/关闭|close/i.test(label)) return
387
+ var tabEl = btn.closest('[data-dockkit-tab]')
388
+ if (!tabEl) return
389
+ var tabId = tabEl.getAttribute('data-dockkit-tab')
390
+ var mounted = sidebar.mounted.getSnapshot()
391
+ if (mounted === undefined) return
392
+ var isMine = sidebar.openTabs.getSnapshot().some(function (t) {
393
+ return t.sessionId === mounted && t.kind === TAB_KIND && t.tabId === tabId
394
+ })
395
+ if (!isMine) return
396
+ event.preventDefault()
397
+ event.stopPropagation()
398
+ diag.blocked = (diag.blocked || 0) + 1
399
+ note('blocked:' + String(tabId))
400
+ }
401
+ document.addEventListener('click', guardCloseClicks, true)
402
+
403
+ // 定时轮询保活(300ms 一次,足够快但不过载);同时兜住"折叠后展开"的补开。
404
+ var urlGuardTimer = setInterval(enforceUrl, 1000)
405
+ enforceUrl()
406
+ var checkTimer = setInterval(function () {
407
+ if (disposed) return
408
+ try {
409
+ ensureOnce()
410
+ checkAndRevive()
411
+ } catch (error) {
412
+ console.warn('[dsh-port-sidebar] 定时保活检查失败', error)
413
+ }
414
+ }, CHECK_INTERVAL_MS)
415
+
416
+ schedule()
417
+ var unsubscribeMounted = sidebar.mounted.subscribe(schedule)
418
+ var unsubscribeTabs = sidebar.openTabs.subscribe(onInventoryChange)
419
+
420
+ ctx.effect(function () {
421
+ return function () {
422
+ disposed = true
423
+ unsubscribeMounted()
424
+ unsubscribeTabs()
425
+ if (typeof unregisterClose === 'function') unregisterClose()
426
+ document.removeEventListener('click', guardCloseClicks, true)
427
+ if (checkTimer !== null) clearInterval(checkTimer)
428
+ if (urlGuardTimer !== null) clearInterval(urlGuardTimer)
429
+ for (var i = 0; i < retryTimers.length; i++) {
430
+ if (retryTimers[i] !== null) clearTimeout(retryTimers[i])
431
+ }
432
+ }
433
+ })
434
+ },
435
+ }
436
+
437
+ return module.exports;
438
+ } });
@@ -0,0 +1,21 @@
1
+ # dsh-port-sidebar bundle patch:把宿主半挂进 Harness。
2
+ #
3
+ # 宿主半(lib/host.mjs)不做 HTTP 服务,只做一件事:订阅 webserver/index-inject,
4
+ # 把目标地址作为 global 行(__DSH_PORT_SIDEBAR__)注入 web 页面开机数据,
5
+ # 浏览器半(client/client.js)读取它并负责侧边栏 tab。
6
+ #
7
+ # 目标地址解析顺序(lib/url.mjs 的 resolveTarget):
8
+ # 1. ctx config.url (由启动器 stack.plugins.configs 注入)
9
+ # 2. DSH_PORT_SIDEBAR_URL
10
+ # 3. ctx config.service → 在 ~/.dsh/services.json 里按服务 id 查
11
+ # 4. ctx config.port / DSH_PORT_SIDEBAR_PORT / host / path 拼出来(默认 39600)
12
+ #
13
+ # 这里用「按服务 id 查 discovery」,因此不写死端口:workbench 端口变了也不用改。
14
+ - insert:
15
+ - id: port-sidebar-host
16
+ name: "@capyclaw/port-sidebar"
17
+ config:
18
+ # 同 DSH mcp-ppt 使用同一 workbench 实例;healthz 守卫拒绝非 ppt-workbench
19
+ service: ppt-workbench
20
+ requireBridge: ppt-workbench
21
+ restoreOnBoot: true
package/lib/host.mjs ADDED
@@ -0,0 +1,71 @@
1
+ /**
2
+ * dsh-port-sidebar 宿主半(Cordis 入口)。
3
+ *
4
+ * 不启动任何 HTTP 服务。唯一的职责:向 web 页面的开机注入表
5
+ * (webserver/index-inject 事件)推送一行 global 数据
6
+ * `__DSH_PORT_SIDEBAR__ = { url, restoreOnBoot }`,浏览器半据此
7
+ * 在右侧边栏为每个会话确保存在指向该端口的 Browser tab。
8
+ *
9
+ * 端口注入方式(优先级从高到低):
10
+ * 1. config.url / 环境变量 DSH_PORT_SIDEBAR_URL(完整地址)
11
+ * 2. config.service → 中间件 discovery(services.json)里该服务的实时 url
12
+ * (服务解耦标准:端口事实归 discovery,不写死)
13
+ * 3. config.port / 环境变量 DSH_PORT_SIDEBAR_PORT(拼 http://127.0.0.1:<port>/)
14
+ * 4. cordis.patch.yml 里的默认 config
15
+ */
16
+ import { resolveTarget } from './url.mjs'
17
+
18
+ export const name = '@capyclaw/port-sidebar'
19
+
20
+ /** 注入到页面的全局变量名(client/client.js 读取同名全局)。 */
21
+ export const BOOT_GLOBAL = '__DSH_PORT_SIDEBAR__'
22
+
23
+ /** 目标健康探测:requireBridge 指定时,目标必须是该 bridge(防止显示错实例)。 */
24
+ const HEALTH_TIMEOUT_MS = 2500
25
+
26
+ async function probeOnce(url, expected) {
27
+ const healthUrl = String(url).replace(/\/+$/, '') + '/healthz'
28
+ const controller = new AbortController()
29
+ const timer = setTimeout(() => controller.abort(), HEALTH_TIMEOUT_MS)
30
+ try {
31
+ const res = await fetch(healthUrl, { signal: controller.signal })
32
+ if (!res.ok) return false
33
+ const body = await res.json()
34
+ return !!body && body.bridge === expected
35
+ } catch {
36
+ return false
37
+ } finally {
38
+ clearTimeout(timer)
39
+ }
40
+ }
41
+
42
+ /* 启动期 workbench 可能比 web 注入晚就绪:有限重试(~4s)后仍不就绪才拒绝注入。 */
43
+ async function probeBridge(url, expected, attempts = 7, delayMs = 600) {
44
+ if (!expected) return true
45
+ for (let i = 0; i < attempts; i++) {
46
+ if (await probeOnce(url, expected)) return true
47
+ if (i < attempts - 1) await new Promise((resolve) => setTimeout(resolve, delayMs))
48
+ }
49
+ return false
50
+ }
51
+
52
+ export async function apply(ctx, config = {}) {
53
+ const target = resolveTarget(config)
54
+ if (target === undefined) {
55
+ console.warn('[dsh-port-sidebar] 启动时未能解析目标端口地址,本次注入不生效')
56
+ return async () => {}
57
+ }
58
+ if (config.requireBridge) {
59
+ const ok = await probeBridge(target.url, String(config.requireBridge))
60
+ if (!ok) {
61
+ console.error(`[dsh-port-sidebar] 目标 ${target.url} 不是 ${config.requireBridge};拒绝注入(避免侧边栏显示错误实例)`)
62
+ return async () => {}
63
+ }
64
+ }
65
+ // 每次收集注入行都会重新 emit(读实时配置,无注册过期问题)。
66
+ ctx.on('webserver/index-inject', (table) => {
67
+ table.push({ kind: 'global', name: BOOT_GLOBAL, value: target })
68
+ })
69
+ console.log(`[dsh-port-sidebar] 侧边栏目标: ${target.url}(bridge=${config.requireBridge || 'any'},restoreOnBoot: ${target.restoreOnBoot})`)
70
+ return async () => {}
71
+ }
package/lib/url.mjs ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * 目标地址解析(纯函数,供 host.mjs 与冒烟测试共用)。
3
+ *
4
+ * 优先级:config.url / 环境变量 URL
5
+ * > config.service → 中间件 discovery(services.json,服务解耦标准:
6
+ * 端口事实归 discovery,不写死)
7
+ * > config.port / 环境变量端口 > 默认 39600。
8
+ * 只接受 http/https;侧边栏 Browser tab 类型本身也只接受这两种协议。
9
+ */
10
+ import fs from 'node:fs'
11
+ import os from 'node:os'
12
+ import path from 'node:path'
13
+
14
+ /** 与 Browser tab 地址解析一致的协议白名单。 */
15
+ const ALLOWED_PROTOCOLS = new Set(['http:', 'https:'])
16
+
17
+ /** 读中间件 discovery 里某服务的 url;文件缺失/无记录/未就绪 → undefined。
18
+ * 口径与 broker 一致:固定用户级 ~/.dsh/services.json(不随 DSH_HOME——
19
+ * broker 与 dsh 可能各持不同 DSH_HOME,discovery 必须是同一张表)。 */
20
+ function discoveryUrl(serviceId, env) {
21
+ const file = env.DSH_DISCOVERY_FILE
22
+ || path.join(os.homedir(), '.dsh', 'services.json')
23
+ try {
24
+ const reg = JSON.parse(fs.readFileSync(file, 'utf8'))
25
+ const row = reg?.services?.[String(serviceId)]
26
+ return typeof row?.url === 'string' && row.state === 'running' ? row.url : undefined
27
+ } catch {
28
+ return undefined
29
+ }
30
+ }
31
+
32
+ /**
33
+ * 从配置与环境变量解析注入目标。
34
+ * @param config - cordis.patch.yml 行 config(url/service/port/host/path/restoreOnBoot)。
35
+ * @param env - 进程环境变量(默认 process.env;测试可注入)。
36
+ * @returns `{ url, restoreOnBoot }`,无法解析出合法地址时为 undefined。
37
+ */
38
+ export function resolveTarget(config = {}, env = process.env) {
39
+ let url = typeof config.url === 'string' && config.url.trim() !== '' ? config.url.trim() : undefined
40
+ if (url === undefined) {
41
+ const envUrl = typeof env.DSH_PORT_SIDEBAR_URL === 'string' && env.DSH_PORT_SIDEBAR_URL.trim() !== ''
42
+ ? env.DSH_PORT_SIDEBAR_URL.trim()
43
+ : undefined
44
+ if (envUrl !== undefined) url = envUrl
45
+ }
46
+ if (url === undefined && typeof config.service === 'string' && config.service.trim() !== '') {
47
+ url = discoveryUrl(config.service.trim(), env)
48
+ }
49
+ if (url === undefined) {
50
+ const port = Number(config.port) > 0
51
+ ? Number(config.port)
52
+ : Number(env.DSH_PORT_SIDEBAR_PORT) > 0 ? Number(env.DSH_PORT_SIDEBAR_PORT) : 39600
53
+ const host = typeof config.host === 'string' && config.host.trim() !== '' ? config.host.trim() : '127.0.0.1'
54
+ const path = typeof config.path === 'string' && config.path !== '' ? config.path : '/'
55
+ url = `http://${host}:${port}${path.startsWith('/') ? path : `/${path}`}`
56
+ }
57
+ let parsed
58
+ try {
59
+ parsed = new URL(url)
60
+ } catch {
61
+ console.warn(`[dsh-port-sidebar] 无法解析目标地址,忽略注入: ${url}`)
62
+ return undefined
63
+ }
64
+ if (!ALLOWED_PROTOCOLS.has(parsed.protocol)) {
65
+ console.warn(`[dsh-port-sidebar] 仅支持 http/https 目标地址,忽略注入: ${url}`)
66
+ return undefined
67
+ }
68
+ const restoreEnv = typeof env.DSH_PORT_SIDEBAR_RESTORE === 'string'
69
+ ? !/^(0|false|off)$/i.test(env.DSH_PORT_SIDEBAR_RESTORE.trim())
70
+ : undefined
71
+ const restoreOnBoot = restoreEnv !== undefined
72
+ ? restoreEnv
73
+ : config.restoreOnBoot !== false
74
+ // 强制保活:关闭后立即重开,除非显式关掉(插件卸载仍然会整体失效)。
75
+ const keepAliveEnv = typeof env.DSH_PORT_SIDEBAR_KEEP_ALIVE === 'string'
76
+ ? !/^(0|false|off)$/i.test(env.DSH_PORT_SIDEBAR_KEEP_ALIVE.trim())
77
+ : undefined
78
+ const keepAlive = keepAliveEnv !== undefined
79
+ ? keepAliveEnv
80
+ : config.keepAlive !== false
81
+ return { url, restoreOnBoot, keepAlive }
82
+ }
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
- {
2
- "name": "@capyclaw/port-sidebar",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@capyclaw/port-sidebar",
3
+ "version": "1.0.1",
4
+ "description": "在 DSH 右侧边栏稳定展示一个本机端口页面:每个会话的侧边栏都确保存在指向该端口的 Browser tab,切换话题不消失。",
5
+ "type": "module",
6
+ "main": "./lib/host.mjs",
7
+ "exports": {
8
+ ".": "./lib/host.mjs",
9
+ "./client": "./client/client.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "dependencies": {
13
+ "dsh-plugin-kit": "^0.2.0"
14
+ },
15
+ "dsh": {
16
+ "bundle": {
17
+ "patch": "./cordis.patch.yml"
18
+ },
19
+ "client": {
20
+ "platform": "web",
21
+ "immediately": true
22
+ },
23
+ "category": "ui",
24
+ "platform": "web"
25
+ },
26
+ "meta": {
27
+ "title": "端口侧边栏",
28
+ "description": "右侧边栏常驻展示指定服务(服务解耦标准:config.service 走中间件 discovery,端口不写死)的界面,切换会话/话题不消失。"
29
+ },
30
+ "files": [
31
+ "lib/",
32
+ "client/",
33
+ "test/",
34
+ "cordis.patch.yml",
35
+ "README.md"
36
+ ],
37
+ "scripts": {
38
+ "test": "node test/plugin.test.mjs"
39
+ },
40
+ "engines": {
41
+ "dsh": "^0.2.0-rc.2",
42
+ "node": ">=18"
43
+ },
44
+ "author": {
45
+ "name": "CapyClaw",
46
+ "url": "https://github.com/capyclaw",
47
+ "email": "support@capyclaw.dev"
48
+ },
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "https://github.com/capyclaw/dsh-plugins",
52
+ "directory": "extensions/official/capyclaw-port-sidebar"
53
+ },
54
+ "bugs": {
55
+ "url": "https://github.com/capyclaw/dsh-plugins/issues"
56
+ },
57
+ "homepage": "https://github.com/capyclaw/dsh-plugins",
58
+ "license": "MIT",
59
+ "publishConfig": {
60
+ "access": "public"
61
+ }
62
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * dsh-port-sidebar 冒烟测试(node:test,无外部依赖)。
3
+ *
4
+ * 覆盖三类契约:
5
+ * 1. 包清单:dsh.client 声明、exports["./client"]、bundle patch、files;
6
+ * 2. 浏览器半:__ModuleLoader__ 装载协议、id 与包名一致、注入面与行为关键路径;
7
+ * 3. 宿主半:地址解析(config/环境变量/协议白名单)与入口形状。
8
+ */
9
+ import test from 'node:test'
10
+ import assert from 'node:assert/strict'
11
+ import { existsSync, readFileSync } from 'node:fs'
12
+ import { fileURLToPath } from 'node:url'
13
+ import { dirname, join, resolve } from 'node:path'
14
+
15
+ const packageDir = resolve(dirname(fileURLToPath(import.meta.url)), '..')
16
+ const readJson = (p) => JSON.parse(readFileSync(p, 'utf8'))
17
+
18
+ test('package.json 声明满足 client-modules 扫描契约', () => {
19
+ const pkg = readJson(join(packageDir, 'package.json'))
20
+ assert.equal(pkg.name, '@capyclaw/port-sidebar')
21
+ assert.equal(pkg.type, 'module')
22
+ assert.equal(pkg.main, './lib/host.mjs')
23
+
24
+ // dsh.client:web 平台 + 开机立即装载
25
+ assert.equal(pkg.dsh.client.platform, 'web')
26
+ assert.equal(pkg.dsh.client.immediately, true)
27
+
28
+ // exports["./client"] 指向真实存在的浏览器半文件(字符串或 { default } 均可)
29
+ const clientExport = pkg.exports['./client']
30
+ const clientRel = typeof clientExport === 'string' ? clientExport : clientExport.default
31
+ assert.equal(typeof clientRel, 'string')
32
+ assert.ok(existsSync(join(packageDir, clientRel)), `浏览器半文件不存在: ${clientRel}`)
33
+
34
+ // bundle patch 与宿主入口真实存在
35
+ assert.ok(readFileSync(join(packageDir, pkg.dsh.bundle.patch), 'utf8').includes('@capyclaw/port-sidebar'))
36
+ assert.ok(readFileSync(join(packageDir, pkg.main), 'utf8').length > 0)
37
+ })
38
+
39
+ test('client.js 遵循 __ModuleLoader__ 装载协议且插件形状正确', () => {
40
+ const pkg = readJson(join(packageDir, 'package.json'))
41
+ const source = readFileSync(join(packageDir, pkg.exports['./client']), 'utf8')
42
+ assert.ok(source.includes('window.__ModuleLoader__.load'), '缺少装载协议调用')
43
+ assert.ok(source.includes(`id: '${pkg.name}'`), 'factory id 必须与包名一致')
44
+ assert.ok(source.includes("inject: ['slots', 'sidebarRight', 'sidebarRightTabs']"), '必须声明注入 slots/sidebarRight/sidebarRightTabs')
45
+ assert.ok(source.includes('return module.exports;'), 'factory 必须返回 module.exports')
46
+ assert.ok(source.includes('__DSH_PORT_SIDEBAR__'), '必须读取宿主半注入的全局')
47
+ assert.ok(source.includes('sidebarRightTabs.register'), '必须注册自有 tab 类型')
48
+ assert.ok(source.includes("kind: TAB_KIND"), '必须使用自有 kind')
49
+ assert.ok(source.includes('registerCloseHandler'), '必须注册关闭钩子做保活')
50
+ assert.ok(source.includes('checkAndRevive'), '必须带保活检查')
51
+ assert.ok(source.includes('hasOwnTab'), '关闭判定必须以会话级清单为权威')
52
+ assert.ok(source.includes('isExpanded'), '折叠时不得抢布局')
53
+ assert.ok(source.includes('guardCloseClicks'), '必须在 UI 层拦截关闭点击')
54
+ assert.ok(source.includes("addEventListener('click', guardCloseClicks, true)"), '拦截必须在 capture 阶段')
55
+ assert.ok(source.includes('ensured.add'), '必须防止重复首次打开')
56
+ assert.ok(source.includes('keepAlive'), '保活必须可配置')
57
+ assert.ok(!/\bimport\s/.test(source), '浏览器半不允许静态 import')
58
+ assert.ok(!/export\s+(default|const|function|let|var)\b/.test(source), '浏览器半不允许 ESM 导出')
59
+ })
60
+
61
+ test('宿主半入口形状正确', async () => {
62
+ const pkg = readJson(join(packageDir, 'package.json'))
63
+ const host = await import(`file://${join(packageDir, pkg.main).replace(/\\/g, '/')}`)
64
+ assert.equal(host.name, pkg.name)
65
+ assert.equal(typeof host.apply, 'function')
66
+ assert.equal(host.BOOT_GLOBAL, '__DSH_PORT_SIDEBAR__')
67
+ })
68
+
69
+ test('resolveTarget:默认 127.0.0.1:39600', async () => {
70
+ const { resolveTarget } = await import('../lib/url.mjs')
71
+ const target = resolveTarget({}, {})
72
+ assert.equal(target.url, 'http://127.0.0.1:39600/')
73
+ assert.equal(target.restoreOnBoot, true)
74
+ })
75
+
76
+ test('resolveTarget:config 优先于环境变量', async () => {
77
+ const { resolveTarget } = await import('../lib/url.mjs')
78
+ const target = resolveTarget({ port: 5000 }, { DSH_PORT_SIDEBAR_PORT: '6000' })
79
+ assert.equal(target.url, 'http://127.0.0.1:5000/')
80
+ assert.equal(
81
+ resolveTarget({ url: 'http://localhost:7000/app' }, { DSH_PORT_SIDEBAR_URL: 'http://x:1/' }).url,
82
+ 'http://localhost:7000/app',
83
+ )
84
+ })
85
+
86
+ test('resolveTarget:环境变量端口生效', async () => {
87
+ const { resolveTarget } = await import('../lib/url.mjs')
88
+ assert.equal(resolveTarget({}, { DSH_PORT_SIDEBAR_PORT: '4173' }).url, 'http://127.0.0.1:4173/')
89
+ })
90
+
91
+ test('resolveTarget:非 http/https 被拒绝', async () => {
92
+ const { resolveTarget } = await import('../lib/url.mjs')
93
+ assert.equal(resolveTarget({ url: 'file:///etc/passwd' }, {}), undefined)
94
+ assert.equal(resolveTarget({ url: 'not a url' }, {}), undefined)
95
+ })
96
+
97
+ test('resolveTarget:restoreOnBoot 可被 config 与环境变量关闭', async () => {
98
+ const { resolveTarget } = await import('../lib/url.mjs')
99
+ assert.equal(resolveTarget({ restoreOnBoot: false }, {}).restoreOnBoot, false)
100
+ assert.equal(resolveTarget({}, { DSH_PORT_SIDEBAR_RESTORE: 'false' }).restoreOnBoot, false)
101
+ assert.equal(resolveTarget({}, { DSH_PORT_SIDEBAR_RESTORE: '0' }).restoreOnBoot, false)
102
+ assert.equal(resolveTarget({ restoreOnBoot: false }, { DSH_PORT_SIDEBAR_RESTORE: 'true' }).restoreOnBoot, true)
103
+ })
104
+
105
+ test('resolveTarget:keepAlive 默认开启,可被 config 与环境变量关闭', async () => {
106
+ const { resolveTarget } = await import('../lib/url.mjs')
107
+ assert.equal(resolveTarget({}, {}).keepAlive, true)
108
+ assert.equal(resolveTarget({ keepAlive: false }, {}).keepAlive, false)
109
+ assert.equal(resolveTarget({}, { DSH_PORT_SIDEBAR_KEEP_ALIVE: 'false' }).keepAlive, false)
110
+ assert.equal(resolveTarget({ keepAlive: false }, { DSH_PORT_SIDEBAR_KEEP_ALIVE: '1' }).keepAlive, true)
111
+ })