dsh-rig 0.1.0 → 0.1.2

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/CHANGELOG.md CHANGED
@@ -3,6 +3,24 @@
3
3
  本项目的所有重要改动都会记在这里。格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
4
4
  版本号遵循 [SemVer](https://semver.org/lang/zh-CN/)。
5
5
 
6
+ ## [0.1.2] - 2026-11-21
7
+
8
+ ### Added
9
+
10
+ - `plugin_lab` 新增 `orphans` / `reap`:列出并回收宿主被硬杀后残留的实验室进程
11
+ - HTTP 边新增 `GET /orphans` 与 `POST /orphans/reap`(只列不杀是默认,回收要显式请求)
12
+ - 回收的判据只有一条:命令行带 `--profile rig-<已知 lab>` 但当前没在管理的进程,
13
+ 不按端口或进程名杀
14
+
15
+ ## [0.1.1] - 2026-11-21
16
+
17
+ ### Fixed
18
+
19
+ - 面板内嵌视图在实验室重启后卡在 `dsh web authentication required`:iframe 现在指向宿主的稳定入口
20
+ (每次 302 到实验室当前地址),不再持有会过期的端口与 token
21
+ - 实验室换地址时主动重导航一次内嵌视图(此前只更新状态、不触发重新加载)
22
+ - 事件流安静挂住时面板停在旧状态:新增 25 秒无事件即主动拉一次状态的看门狗
23
+
6
24
  ## [0.1.0] - 2026-11-21
7
25
 
8
26
  第一个可用版本。
package/lib/client.js CHANGED
@@ -188,6 +188,8 @@ window.__ModuleLoader__.load({
188
188
  const [error, setError] = useState('')
189
189
  const [uiMode, setUiMode] = useState(false)
190
190
  const [ui, setUi] = useState(null)
191
+ const [frameSig, setFrameSig] = useState('')
192
+ const [frameGen, setFrameGen] = useState(0)
191
193
 
192
194
  useEffect(() => {
193
195
  const controller = new AbortController()
@@ -204,21 +206,31 @@ window.__ModuleLoader__.load({
204
206
  if (data.diagnostics) setDiagnostics(data.diagnostics)
205
207
  if (typeof data.uiMode === 'boolean') setUiMode(data.uiMode)
206
208
  if (data.ui) setUi(data.ui)
209
+ if (typeof data.frameSig === 'string') setFrameSig(data.frameSig)
207
210
  }
208
211
 
209
212
  const refresh = () => request('/state').then(applyState).catch(() => {})
210
213
 
214
+ let lastEventAt = Date.now()
215
+
211
216
  const applyEvent = (event) => {
217
+ lastEventAt = Date.now()
212
218
  if (event.type === 'snapshot') {
213
219
  setLabs(event.labs || [])
214
220
  if (event.diagnostics) setDiagnostics(event.diagnostics)
215
221
  if (typeof event.uiMode === 'boolean') setUiMode(event.uiMode)
216
222
  if (event.ui) setUi(event.ui)
223
+ if (typeof event.frameSig === 'string') setFrameSig(event.frameSig)
217
224
  } else if (event.type === 'ui-mode') {
218
225
  setUiMode(Boolean(event.enabled))
226
+ } else if (event.type === 'url') {
227
+ // 实验室换了地址(启动/重启):让 iframe 重新走一次稳定入口,拿新 token。
228
+ // 只把 key 绑在入口地址上不够 —— 入口地址本身不变,必须由这次自增触发导航。
229
+ setFrameGen((n) => n + 1)
230
+ refresh()
219
231
  } else if (event.type === 'log') {
220
232
  pushLog(event.id, event.entry)
221
- } else if (event.type === 'status' || event.type === 'url' || event.type === 'labs') {
233
+ } else if (event.type === 'status' || event.type === 'labs') {
222
234
  refresh()
223
235
  }
224
236
  }
@@ -247,13 +259,23 @@ window.__ModuleLoader__.load({
247
259
  })
248
260
  .catch((err) => setError(`拿不到实验室状态:${err && err.message ? err.message : err}(宿主可能没有 HTTP 面)`))
249
261
 
262
+ /**
263
+ * 看门狗:事件流可能**安静地挂住**(不报错、也不再送数据),面板就停在旧状态。
264
+ * 25 秒无事件则主动拉一次状态:不解决根因,但保证「旧一拍」自愈。
265
+ */
266
+ const watchdog = setInterval(() => {
267
+ if (controller.signal.aborted) return
268
+ if (Date.now() - lastEventAt > 25_000) refresh()
269
+ }, 10_000)
270
+
250
271
  return () => {
251
272
  controller.abort()
252
273
  if (retry) clearTimeout(retry)
274
+ clearInterval(watchdog)
253
275
  }
254
276
  }, [])
255
277
 
256
- return { labs, diagnostics, logs, connected, error, setError, uiMode, setUiMode, ui }
278
+ return { labs, diagnostics, logs, connected, error, setError, uiMode, setUiMode, ui, frameSig, frameGen }
257
279
  }
258
280
 
259
281
  // ── 5. 原子组件(只吃 props,不认识 ctx / 网络) ──────────────────
@@ -336,6 +358,8 @@ window.__ModuleLoader__.load({
336
358
  { style: S.viewportWrap },
337
359
  frameUrl
338
360
  ? h('iframe', {
361
+ // key 绑在地址上:地址一变就强制重建 iframe,避免沿用旧文档。
362
+ key: frameUrl,
339
363
  src: frameUrl,
340
364
  style: { ...S.frame, pointerEvents: locked ? 'none' : 'auto' },
341
365
  title: T.panelTitle,
@@ -383,7 +407,7 @@ window.__ModuleLoader__.load({
383
407
 
384
408
  // ── 7. 容器:只做接线(状态 → 组件),不写样式细节 ─────────────
385
409
  function LabPanel() {
386
- const { labs, logs, connected, error, setError, uiMode, setUiMode, ui } = useLabState()
410
+ const { labs, logs, connected, error, setError, uiMode, setUiMode, ui, frameSig, frameGen } = useLabState()
387
411
  const [locked, setLocked] = useState(true)
388
412
  const [busy, setBusy] = useState('')
389
413
  const [nonce, setNonce] = useState(0)
@@ -392,7 +416,10 @@ window.__ModuleLoader__.load({
392
416
  const entries = lab ? logs[lab.id] || [] : []
393
417
  const status = lab ? lab.status : 'created'
394
418
  const live = status === 'running' || status === 'starting'
395
- const frameUrl = lab && lab.url ? `${lab.url}${lab.url.indexOf('?') >= 0 ? '&' : '?'}rig=${nonce}` : null
419
+ // iframe 指向**宿主**的稳定入口而不是实验室裸地址:实验室每次重启都换端口与 token,
420
+ // 直连它时一次重启就让面板卡在 `dsh web authentication required`(2026-11-21 撞上)。
421
+ // 走入口后宿主每次 302 到当前真地址,面板即使旧一拍也不会拿过期 token 去撞 401。
422
+ const frameUrl = lab && frameSig ? `${API}/frame?id=${encodeURIComponent(lab.id)}&sig=${frameSig}&n=${nonce + frameGen}` : null
396
423
 
397
424
  const run = useCallback(
398
425
  async (label, fn) => {
@@ -11,6 +11,7 @@
11
11
  * 这不是强安全边界,是防「别的网页顺手打你的实验室」。真正的边界是「它只在本机」。
12
12
  */
13
13
  import { API_PREFIX } from '../lab/constants.js'
14
+ import { reapOrphans } from '../lab/orphans.js'
14
15
 
15
16
  const MAX_BODY_BYTES = 64 * 1024
16
17
 
@@ -50,7 +51,7 @@ const readBody = (req) =>
50
51
  })
51
52
 
52
53
  /** SSE:面板挂一条长连接,状态与日志都从这条推。 */
53
- function openEventStream(req, res, supervisor) {
54
+ function openEventStream(req, res, supervisor, frameSig) {
54
55
  res.writeHead(200, {
55
56
  'content-type': 'text/event-stream; charset=utf-8',
56
57
  'cache-control': 'no-store',
@@ -66,7 +67,7 @@ function openEventStream(req, res, supervisor) {
66
67
  }
67
68
  void (async () => {
68
69
  const ui = await supervisor.uiAvailable()
69
- send({ type: 'snapshot', labs: supervisor.list(), diagnostics: supervisor.diagnostics(), uiMode: supervisor.uiMode(), ui })
70
+ send({ type: 'snapshot', labs: supervisor.list(), diagnostics: supervisor.diagnostics(), uiMode: supervisor.uiMode(), ui, frameSig })
70
71
  })()
71
72
  const unsubscribe = supervisor.subscribe(send)
72
73
  const heartbeat = setInterval(() => {
@@ -84,27 +85,72 @@ function openEventStream(req, res, supervisor) {
84
85
  res.on('close', cleanup)
85
86
  }
86
87
 
87
- export function mountRoutes(ctx, { supervisor, versions }) {
88
+ export function mountRoutes(ctx, { supervisor, versions, frameSig }) {
89
+ /**
90
+ * iframe 用的稳定入口签名(由组合根生成并传入,路由层不自己造随机数)。
91
+ *
92
+ * 为什么要它:实验室每次重启都会换端口与 token,而 iframe 的 src 一旦写死旧地址,
93
+ * 就会被实验室自己的鉴权打回 401(2026-11-21 第一次真机试用就撞上:
94
+ * 面板里显示 "dsh web authentication required")。
95
+ * 现在 iframe 指向 `/dsh-rig/api/frame?id=…&sig=…`,由宿主**每次现查**实验室的真地址再 302,
96
+ * 于是「端口变了」「token 轮换了」「面板状态旧了一拍」都不再能把它带偏。
97
+ *
98
+ * 它不是安全边界(同机进程本来就能伪造请求头),只是让 UI 不会拿着过期地址。
99
+ */
100
+ const frameRoute = (res, url) => {
101
+ const id = url.searchParams.get('id') || ''
102
+ const sig = url.searchParams.get('sig') || ''
103
+ if (sig !== frameSig) {
104
+ res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' })
105
+ res.end('bad signature')
106
+ return
107
+ }
108
+ const lab = supervisor.get(id)
109
+ if (!lab || !lab.url) {
110
+ res.writeHead(503, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })
111
+ res.end(
112
+ '<!doctype html><meta charset="utf-8"><body style="font:14px system-ui;color:#8a93a5;background:#0f1115;display:flex;align-items:center;justify-content:center;height:100vh;margin:0">实验室未运行 —— 点「启动」后这里会自动接上</body>',
113
+ )
114
+ return
115
+ }
116
+ // 302 到**此刻**的真地址:端口与 token 每次重启都会变,这里现查现给。
117
+ res.writeHead(302, { location: lab.url, 'cache-control': 'no-store' })
118
+ res.end()
119
+ }
120
+
88
121
  return ctx.webServer.register({
89
122
  kind: 'prefix',
90
123
  path: API_PREFIX,
91
124
  async handler(req, res) {
125
+ const url = new URL(req.url || '/', 'http://127.0.0.1')
126
+ const tail = url.pathname.slice(API_PREFIX.length) || '/'
127
+ const method = req.method || 'GET'
128
+
129
+ // iframe 导航**带不了自定义请求头**,所以这一条必须放在头校验之前。
130
+ if (tail === '/frame') {
131
+ frameRoute(res, url)
132
+ return
133
+ }
134
+
92
135
  if (req.headers['x-dsh-rig'] !== '1') {
93
136
  json(res, 403, { error: 'missing x-dsh-rig header' })
94
137
  return
95
138
  }
96
- const url = new URL(req.url || '/', 'http://127.0.0.1')
97
- const tail = url.pathname.slice(API_PREFIX.length) || '/'
98
- const method = req.method || 'GET'
99
139
 
100
140
  try {
101
141
  if (method === 'GET' && tail === '/state') {
102
142
  const ui = await supervisor.uiAvailable()
103
- json(res, 200, { labs: supervisor.list(), diagnostics: supervisor.diagnostics(), ui, uiMode: supervisor.uiMode() })
143
+ json(res, 200, {
144
+ labs: supervisor.list(),
145
+ diagnostics: supervisor.diagnostics(),
146
+ ui,
147
+ uiMode: supervisor.uiMode(),
148
+ frameSig,
149
+ })
104
150
  return
105
151
  }
106
152
  if (method === 'GET' && tail === '/events') {
107
- openEventStream(req, res, supervisor)
153
+ openEventStream(req, res, supervisor, frameSig)
108
154
  return
109
155
  }
110
156
  if (method === 'POST' && tail === '/ui-mode') {
@@ -148,6 +194,19 @@ export function mountRoutes(ctx, { supervisor, versions }) {
148
194
  json(res, 200, { result, labs: supervisor.list() })
149
195
  return
150
196
  }
197
+ // 孤儿实验室:宿主被硬杀时留下的进程。只列不杀,除非显式要求回收。
198
+ if (method === 'GET' && tail === '/orphans') {
199
+ const tracked = supervisor.list().filter((lab) => lab.status === 'running' || lab.status === 'starting')
200
+ const result = await reapOrphans({ trackedProfileNames: tracked.map((lab) => lab.profile), dryRun: true })
201
+ json(res, 200, { orphans: result.found })
202
+ return
203
+ }
204
+ if (method === 'POST' && tail === '/orphans/reap') {
205
+ const tracked = supervisor.list().filter((lab) => lab.status === 'running' || lab.status === 'starting')
206
+ const result = await reapOrphans({ trackedProfileNames: tracked.map((lab) => lab.profile) })
207
+ json(res, 200, result)
208
+ return
209
+ }
151
210
  // 界面驱动:让智能体像人一样看/拍/点/打(面板与工具共用这条)
152
211
  const reportTarget = /^\/labs\/([a-z0-9-]+)\/report$/u.exec(tail)
153
212
  if (method === 'GET' && reportTarget) {
package/lib/index.js CHANGED
@@ -7,6 +7,7 @@
7
7
  *
8
8
  * 日志纪律:`ctx.logger()` 的输出不进 stdout,三级验证看不到。这里一律 `console.log`。
9
9
  */
10
+ import { randomBytes } from 'node:crypto'
10
11
  import { homedir } from 'node:os'
11
12
  import { dirname, join } from 'node:path'
12
13
  import { LabSupervisor } from './lab/supervisor.js'
@@ -62,8 +63,10 @@ export function apply(ctx, config = {}) {
62
63
  `[dsh-rig] host half loaded · stage=${RIG_STAGE} · home=${hostHome} · core=${core.bin ?? '(missing)'}(${core.source}) · electron=${isElectron}`,
63
64
  )
64
65
 
65
- const supervisor = new LabSupervisor({
66
- root,
66
+ // iframe 稳定入口的签名:每次宿主启动换一份,由路由层校验(原因见 http/routes.js 里那段注释)。
67
+ const frameSig = randomBytes(12).toString('hex')
68
+
69
+ const supervisor = new LabSupervisor({ root,
67
70
  hostHome,
68
71
  hostProfile: resolveHostProfile(env),
69
72
  execPath: process.execPath,
@@ -91,7 +94,7 @@ export function apply(ctx, config = {}) {
91
94
 
92
95
  // HTTP 边:没有 webServer 的宿主(headless)直接跳过,不影响别的一半。
93
96
  try {
94
- ctx.inject(['webServer'], (inner) => mountRoutes(inner, { supervisor, versions }))
97
+ ctx.inject(['webServer'], (inner) => mountRoutes(inner, { supervisor, versions, frameSig }))
95
98
  } catch (err) {
96
99
  console.warn(`[dsh-rig] webServer 不可用,面板将拿不到数据:${err?.message ?? err}`)
97
100
  }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * dsh-rig · 孤儿回收(IO 层)
3
+ *
4
+ * 为什么需要它:宿主被硬杀(崩溃、任务管理器结束、`taskkill /F`)时,插件没有机会跑
5
+ * `disposeAll`,于是它派出去的实验室进程会活下来——2026-11-21 桌面版崩过一次之后,
6
+ * 就留下一个 307 MB、还占着端口的实验室进程。
7
+ *
8
+ * 判据只有一条:**命令行里带 `--profile rig-<已知 lab id>` 但我们当前没在管理的进程**,
9
+ * 就是孤儿。不按端口杀、不按进程名杀 —— 那些会误伤。
10
+ *
11
+ * Windows 上没有 `/proc`,只能问 WMI。用固定脚本(不经用户输入拼接),失败返回空数组:
12
+ * 回收是「尽力而为」的事,不该因为它失败就影响插件启动。
13
+ */
14
+ import { execFile } from 'node:child_process'
15
+ import { promisify } from 'node:util'
16
+
17
+ const run = promisify(execFile)
18
+
19
+ /** 只认这些 profile 前缀:与 naming.js 里的 PROFILE_PREFIX 保持一致。 */
20
+ const PROFILE_PATTERN = /--profile\s+(rig-[a-z0-9-]+)/u
21
+
22
+ /**
23
+ * 列出所有跑着 rig 实验室的进程。
24
+ * @returns {Promise<Array<{pid: number, profile: string, cmd: string}>>}
25
+ */
26
+ export async function listLabProcesses() {
27
+ if (process.platform !== 'win32') return []
28
+ const script = [
29
+ '$out = @()',
30
+ 'Get-CimInstance Win32_Process -Filter "Name=\'node.exe\'" | ForEach-Object {',
31
+ ' if ($_.CommandLine -match "--profile rig-") { $out += [pscustomobject]@{ pid = $_.ProcessId; cmd = $_.CommandLine } }',
32
+ '}',
33
+ 'Get-CimInstance Win32_Process -Filter "Name=\'DeepSeek Harness.exe\'" | ForEach-Object {',
34
+ ' if ($_.CommandLine -match "--profile rig-") { $out += [pscustomobject]@{ pid = $_.ProcessId; cmd = $_.CommandLine } }',
35
+ '}',
36
+ '$out | ConvertTo-Json -Compress',
37
+ ].join('\n')
38
+
39
+ try {
40
+ const { stdout } = await run(
41
+ 'pwsh',
42
+ ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],
43
+ { timeout: 20_000, windowsHide: true, maxBuffer: 2 * 1024 * 1024 },
44
+ )
45
+ const text = stdout.trim()
46
+ if (!text || text === 'null') return []
47
+ const parsed = JSON.parse(text)
48
+ const rows = Array.isArray(parsed) ? parsed : [parsed]
49
+ return rows
50
+ .map((row) => {
51
+ const match = PROFILE_PATTERN.exec(String(row.cmd || ''))
52
+ return match ? { pid: Number(row.pid), profile: match[1], cmd: String(row.cmd) } : null
53
+ })
54
+ .filter(Boolean)
55
+ } catch {
56
+ return []
57
+ }
58
+ }
59
+
60
+ /** 杀掉一棵进程树(只用于我们确认过的孤儿 pid)。 */
61
+ export async function killOrphan(pid) {
62
+ if (!Number.isInteger(pid) || pid <= 0) throw new Error(`非法 pid:${pid}`)
63
+ try {
64
+ await run('taskkill', ['/PID', String(pid), '/T', '/F'], { timeout: 15_000, windowsHide: true })
65
+ return true
66
+ } catch {
67
+ return false
68
+ }
69
+ }
70
+
71
+ /**
72
+ * 回收:把「跑着 rig 实验室、但不在 tracked 名单里」的进程杀掉。
73
+ *
74
+ * @param {{trackedProfileNames: string[], dryRun?: boolean}} options
75
+ * @returns {Promise<{found: Array<object>, killed: Array<object>, failed: Array<object>}>}
76
+ */
77
+ export async function reapOrphans({ trackedProfileNames, dryRun = false }) {
78
+ const tracked = new Set(trackedProfileNames || [])
79
+ const all = await listLabProcesses()
80
+ const orphans = all.filter((item) => !tracked.has(item.profile))
81
+ const killed = []
82
+ const failed = []
83
+ if (dryRun) return { found: orphans, killed, failed }
84
+ for (const orphan of orphans) {
85
+ if (await killOrphan(orphan.pid)) killed.push(orphan)
86
+ else failed.push(orphan)
87
+ }
88
+ return { found: orphans, killed, failed }
89
+ }
@@ -14,7 +14,7 @@ import { renderReport } from '../lab/report.js'
14
14
 
15
15
  const text = (s) => [{ type: 'text', text: String(s ?? '') }]
16
16
 
17
- const ACTIONS = ['list', 'create', 'start', 'stop', 'restart', 'destroy', 'status', 'logs', 'report', 'versions', 'set_version']
17
+ const ACTIONS = ['list', 'create', 'start', 'stop', 'restart', 'destroy', 'status', 'logs', 'report', 'versions', 'set_version', 'orphans', 'reap']
18
18
 
19
19
  function renderLab(lab) {
20
20
  const head = `[${lab.id}] ${lab.name} · ${lab.status}${lab.port ? ` · :${lab.port}` : ''}`
@@ -100,6 +100,22 @@ export function createLabTool(supervisor, versionsApi) {
100
100
  )
101
101
  return { ok: true, text: lines.join('\n') }
102
102
  }
103
+ if (action === 'orphans' || action === 'reap') {
104
+ const tracked = supervisor.list().filter((lab) => lab.status === 'running' || lab.status === 'starting')
105
+ const result = await reapOrphans({
106
+ trackedProfileNames: tracked.map((lab) => lab.profile),
107
+ dryRun: action === 'orphans',
108
+ })
109
+ if (result.found.length === 0) return { ok: true, text: '没有残留的实验室进程。' }
110
+ const lines = result.found.map((item) => `${item.pid} · ${item.profile}`)
111
+ if (action === 'orphans') {
112
+ return { ok: true, text: `发现 ${result.found.length} 个残留实验室进程(未处理):\n${lines.join('\n')}\n要清掉就把 action 换成 reap。` }
113
+ }
114
+ return {
115
+ ok: true,
116
+ text: `回收完成:清掉 ${result.killed.length} 个${result.failed.length ? `,失败 ${result.failed.length} 个` : ''}\n${lines.join('\n')}`,
117
+ }
118
+ }
103
119
  if (action === 'set_version') {
104
120
  if (!args?.version) return { ok: false, error: 'set_version 需要 version(host 表示跟随宿主)' }
105
121
  const lab = await supervisor.setVersion(id, String(args.version))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-rig",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Right-sidebar plugin lab for DeepSeek Harness: a real, process-isolated DSH you can start, restart, version-switch, lock or take over — crashes stay inside the lab.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",