dsh-rig 0.1.4 → 0.1.5

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,21 @@
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.5] - 2026-11-21
7
+
8
+ ### Fixed
9
+
10
+ - **面板里显示不出实验室**(`dsh web authentication required`):`/frame` 的 302 现在把主机名换成
11
+ **本次请求的主机名**。原因:实验室登录是「token → 303 换成 `SameSite=Strict` 的 HttpOnly cookie → 再请求 `/`」,
12
+ 宿主页面若是 `localhost:xxx` 而重定向到 `127.0.0.1:46xxx`,iframe 就跨站了,那颗 cookie 存不下。
13
+ 同一份代码 A/B 实测:页面 `127.0.0.1` 正常、页面 `localhost` 退回鉴权页;修完后两者都正常。
14
+ - **两个宿主进程互相吞实验室**:`labs.json` 的写盘改成「锁 → 读盘 → 合并 → 写」。
15
+ 桌面版与 web 版同时开着时,各自持一份内存状态、谁后写谁赢 —— 实测丢过一条记录。
16
+ 现在盘上有、内存没有的会留着;每条实验室带 `hostId`,不是本进程管的在面板里只读;
17
+ 老记录没有 `hostId` 的按「自己的」处理,升级不会把人锁在门外。
18
+ - `load()` 的裸 `catch` 会把任何异常(包括漏 import 的 `ReferenceError`)吞成「0 个实验室」:
19
+ 现在只有文件不存在才算空,其它错误如实上报并说明原因。
20
+
6
21
  ## [0.1.4] - 2026-11-21
7
22
 
8
23
  ### Added
package/README.md CHANGED
@@ -114,6 +114,12 @@ dsh plugin --profile web add dsh-rig
114
114
  - 换 DSH 版本目前只能切到**已装**的版本(安装新版本的入口还没做)。
115
115
  - 「派活给实验室里的智能体」与「施工过程可视化」还没做——现在靠你在解锁态下自己输入,或让智能体用 `lab_ui` 去点。
116
116
  - 无头浏览器会开一个本地调试端口;它随实验室起停、只在授权期间存在,但这是「模拟点击」这条路的固有代价。
117
+ - 内嵌视口曾经在「宿主页面与实验室主机名不同」时停在「dsh web authentication required」(0.1.5 已修):
118
+ 实验室的登录是「token → 303 换成 `SameSite=Strict` 的 HttpOnly cookie → 再请求 `/`」,
119
+ 而 `localhost:xxx` 与 `127.0.0.1:46xxx` 不同站,iframe 里那颗 cookie 存不下。
120
+ 现在 `/frame` 的 302 会把主机名换成本次请求的主机名,两者同站。
121
+ - 桌面版与 web 版同时开着时共用同一份 `labs.json`——0.1.5 起写盘带锁并**读盘合并**,
122
+ 两边建的实验室都留着;不是本进程管的会标成只读。
117
123
 
118
124
  ## 许可
119
125
 
package/docs/DESIGN.md CHANGED
@@ -67,3 +67,30 @@
67
67
  4. 服务端:`plugin_lab` 驾驶校验(拒绝文案带占用者 id)
68
68
  5. SSE 单例 + `open-lab` 自动展开
69
69
  6. 发 `0.1.4`;之后 `0.2.0` = `desktop` 运行时
70
+
71
+ ## 七、待办(按优先级)
72
+
73
+ ### 1. 内嵌视口的主机名不一致(0.1.4 缺陷,0.1.5 已修)
74
+
75
+ 症状:桌面版面板里 iframe 停在 `dsh web authentication required; reopen the URL printed by dsh web.`
76
+
77
+ **已确认的机制**(`localhost` / `127.0.0.1` 两个页面 iframe 同一个实验室,A/B 对照):
78
+
79
+ - 实验室的登录是 `?token=` → **303** + `Set-Cookie: dsh-auth-<token 哈希>=…; HttpOnly; SameSite=Strict` → 再请求 `/`。
80
+ curl 不带 cookie jar 时照样 401 —— 换成 cookie 这一步是必需的;
81
+ - 页面在 `127.0.0.1:8099`、实验室在 `127.0.0.1:46000` → **正常显示**;
82
+ - 页面在 `localhost:8099`、实验室在 `127.0.0.1:46000` → **退回鉴权页**。
83
+ 两者不同站,`SameSite=Strict` 的 cookie 在 iframe 里存不下;
84
+ - 实验室**不校验 `Host`**(`localhost:46000` 与 `127.0.0.1:46000` 都回 303),所以换主机名没有副作用。
85
+
86
+ **修法**:`/frame` 的 302 用本次请求的 `Host` 主机名替换实验室地址的主机名,让 iframe 与宿主页面同站。
87
+ 验证走同一条 A/B:页面用 `localhost` 打开宿主、面板里实验室正常渲染。
88
+
89
+ ### 2. 跨进程共用 `labs.json`(0.1.5 已修)
90
+
91
+ 写盘加锁(`labs.json.lock`,陈旧锁按 mtime 打破)+ 读盘合并(`lib/lab/merge.js`),
92
+ 每个 lab 带 `hostId`,别人创建的在界面上只读。见 `lib/lab/state-store.js`。
93
+
94
+ ### 3. `desktop` 运行时
95
+
96
+ 实验室跑成真桌面壳(`--profile desktop` 的 Electron 实例),而不是 `dsh web`。
package/lib/client.js CHANGED
@@ -37,7 +37,7 @@ window.__ModuleLoader__.load({
37
37
  cancel: '取消', back: '返回', hostVersion: '跟随宿主', ok: '知道了',
38
38
  },
39
39
  status: { created: '未启动', starting: '启动中', running: '运行中', stopped: '已停止', crashed: '已崩溃' },
40
- owner: { me: '本会话', free: '空闲', other: '会话', freeTitle: '没有会话在驾驶它' },
40
+ owner: { me: '本会话', free: '空闲', other: '会话', freeTitle: '没有会话在驾驶它', foreign: '由另一个宿主进程管理:只能看,动不了' },
41
41
  lock: { on: '已锁定', off: '可介入', hint: '锁定只挡输入,不是安全边界' },
42
42
  agent: {
43
43
  on: '智能体可操作', off: '智能体未授权', noBackend: '本机没有可用浏览器后端',
@@ -384,7 +384,9 @@ window.__ModuleLoader__.load({
384
384
  const status = lab ? lab.status : 'created'
385
385
  const live = status === 'running' || status === 'starting'
386
386
  // 没有 lab、没有会话 id(拿不到身份)、或主人就是自己 → 都算「我能动」。
387
- const mine = !lab || !lab.ownerSessionId || sessionId === '' || lab.ownerSessionId === sessionId
387
+ // foreign = 这条实验室是**另一个宿主进程**(比如桌面版与 web 版同时开着)建的:只能看。
388
+ const foreign = Boolean(lab && lab.foreign)
389
+ const mine = !foreign && (!lab || !lab.ownerSessionId || sessionId === '' || lab.ownerSessionId === sessionId)
388
390
  const canView = Boolean(lab && lab.url)
389
391
  // iframe 指向宿主的稳定入口而不是实验室裸地址:它每次重启都换端口与 token,
390
392
  // 直连会让面板卡在 `dsh web authentication required`(2026-11-21 撞上过一次)。
@@ -467,7 +469,7 @@ window.__ModuleLoader__.load({
467
469
  h('span', { style: S.dot(view.connected ? 'var(--dsw-alias-state-success-primary)' : 'var(--dsw-alias-state-idle-primary)'), title: view.connected ? T.conn.on : T.conn.off })),
468
470
  lab
469
471
  ? h('div', { style: S.band },
470
- h(Btn, { tone: primary.tone, disabled: busy !== '' || (!mine && false), onClick: primary.run, title: primary.label }, primary.label),
472
+ h(Btn, { tone: primary.tone, disabled: busy !== '' || primary.disabled === true, onClick: primary.run, title: primary.title || primary.label }, primary.label),
471
473
  h(Btn, { disabled: menu === 'more' || confirming, onClick: () => setMenu(menu === 'more' ? '' : 'more'), title: T.act.more }, '⋯'),
472
474
  h('span', { style: S.grow }),
473
475
  h('span', { style: S.meta }, lab.port ? `:${lab.port}` : lab.version === 'host' ? T.act.hostVersion : lab.version))
@@ -53,7 +53,25 @@ const readBody = (req) =>
53
53
  })
54
54
 
55
55
  /**
56
- * SSE:面板挂一条长连接,状态与日志都从这条推。
56
+ * 把实验室地址的主机名换成本次请求的主机名(`localhost` ↔ `127.0.0.1`)。
57
+ *
58
+ * 为的是让 iframe 与宿主**同站**:实验室的登录 cookie 是 `SameSite=Strict`,跨站时存不下,
59
+ * 页面就退回 "dsh web authentication required"。实验室不校验 Host,换名字不影响它。
60
+ * 端口与 token 保持实验室那份;IPv6 字面量与可疑 Host 一律原样返回,别把地址改坏。
61
+ */
62
+ function sameHostUrl(labUrl, inboundHost) {
63
+ const host = String(inboundHost || '').replace(/:\d+$/u, '')
64
+ if (host === '' || host.includes(':') || !/^[A-Za-z0-9.-]+$/u.test(host)) return labUrl
65
+ try {
66
+ const target = new URL(labUrl)
67
+ target.hostname = host
68
+ return target.toString()
69
+ } catch {
70
+ return labUrl
71
+ }
72
+ }
73
+
74
+ /** SSE:面板挂一条长连接,状态与日志都从这条推。
57
75
  * `describe` 由 mountRoutes 传进来(补占用者标题)—— 它是**模块级函数**,看不到 mountRoutes 里的闭包,
58
76
  * 2026-11-21 直接引用外层变量,结果宿主启动就 `ReferenceError: describe is not defined` 整机起不来。
59
77
  */
@@ -108,9 +126,14 @@ export function mountRoutes(ctx, { supervisor, versions, frameSig, titleOf }) {
108
126
  * 现在 iframe 指向 `/dsh-rig/api/frame?id=…&sig=…`,由宿主**每次现查**实验室的真地址再 302,
109
127
  * 于是「端口变了」「token 轮换了」「面板状态旧了一拍」都不再能把它带偏。
110
128
  *
111
- * 它不是安全边界(同机进程本来就能伪造请求头),只是让 UI 不会拿着过期地址。
129
+ * **主机名要用请求里的那个**(2026-11-21 二次真机定位):实验室的登录是「token → 303 换成
130
+ * `SameSite=Strict` 的 HttpOnly cookie → 再请求 /」。宿主页面若是 `localhost:xxx` 而这里硬写
131
+ * `127.0.0.1:46xxx`,iframe 就跨站了 —— Strict cookie 存不下,页面退回鉴权提示。
132
+ * 实测同一份代码:页面 `127.0.0.1` 能显示、页面 `localhost` 不能。实验室不校验 Host,换个名字没副作用。
133
+ *
134
+ * 它不是安全边界(同机进程本来就能伪造请求头),只是让 UI 不会拿着过期地址、也不会被同站判定卡住。
112
135
  */
113
- const frameRoute = (res, url) => {
136
+ const frameRoute = (req, res, url) => {
114
137
  const id = url.searchParams.get('id') || ''
115
138
  const sig = url.searchParams.get('sig') || ''
116
139
  if (sig !== frameSig) {
@@ -127,7 +150,7 @@ export function mountRoutes(ctx, { supervisor, versions, frameSig, titleOf }) {
127
150
  return
128
151
  }
129
152
  // 302 到**此刻**的真地址:端口与 token 每次重启都会变,这里现查现给。
130
- res.writeHead(302, { location: lab.url, 'cache-control': 'no-store' })
153
+ res.writeHead(302, { location: sameHostUrl(lab.url, req.headers.host), 'cache-control': 'no-store' })
131
154
  res.end()
132
155
  }
133
156
 
@@ -157,7 +180,7 @@ export function mountRoutes(ctx, { supervisor, versions, frameSig, titleOf }) {
157
180
 
158
181
  // iframe 导航**带不了自定义请求头**,所以这一条必须放在头校验之前。
159
182
  if (tail === '/frame') {
160
- frameRoute(res, url)
183
+ frameRoute(req, res, url)
161
184
  return
162
185
  }
163
186
 
@@ -0,0 +1,47 @@
1
+ /**
2
+ * dsh-rig · `labs.json` 跨进程合并(纯逻辑)
3
+ *
4
+ * 为什么会需要它:桌面版和 web 版可能**同时**装着这个插件,两个宿主进程共用同一份
5
+ * `labs.json`,但各自持有一份内存状态。谁后写谁赢 —— 2026-11-21 实测发生过一次:
6
+ * 另一端的一次保存把这一端刚建的实验室记录整条抹掉了。
7
+ *
8
+ * 规则只有三条:
9
+ * 1. 盘上有的、内存里没有的 → **留着**(那是别的宿主进程管的实验室,不该被我写没);
10
+ * 2. 两边都有的同一个 id → 用内存那份(我管的那条以我为准);
11
+ * 3. 内存里有、盘上没有的 → 追加(我新建的)。
12
+ *
13
+ * 不解决的部分(要更大改动):两个进程同时 `create` 可能撞 id —— 那一步在写盘锁里做,
14
+ * 见 `state-store.js`。这里只算「合并成什么样」,不碰文件。
15
+ */
16
+ import { emptyState } from './registry.js'
17
+
18
+ /**
19
+ * @param {object} disk 盘上的状态(`{schemaVersion, labs}`)
20
+ * @param {object} ours 本进程的状态
21
+ * @returns {object} 合并后的状态(新对象,不改入参)
22
+ */
23
+ export function mergeStates(disk, ours) {
24
+ const mine = new Map((ours?.labs || []).map((lab) => [lab.id, lab]))
25
+ const seen = new Set()
26
+ const labs = []
27
+ for (const lab of disk?.labs || []) {
28
+ seen.add(lab.id)
29
+ labs.push(mine.get(lab.id) || lab)
30
+ }
31
+ for (const lab of ours?.labs || []) {
32
+ if (!seen.has(lab.id)) labs.push(lab)
33
+ }
34
+ const base = disk && Number.isInteger(disk.schemaVersion) ? disk : emptyState()
35
+ return { schemaVersion: base.schemaVersion, labs }
36
+ }
37
+
38
+ /**
39
+ * 这条实验室是不是**别的宿主进程**管的(只能看、不能驱动)。
40
+ * 老记录没有 `hostId`(0.1.4 之前写的)—— 当作「自己的」,否则升级完就把用户锁在门外了。
41
+ * @param {object} lab 实验室记录
42
+ * @param {string} hostId 本进程身份
43
+ * @returns {boolean}
44
+ */
45
+ export function isForeign(lab, hostId) {
46
+ return Boolean(lab && lab.hostId && hostId && lab.hostId !== hostId)
47
+ }
@@ -40,6 +40,7 @@ export function parseState(text) {
40
40
  port: Number.isInteger(lab.port) && lab.port > 0 ? lab.port : null,
41
41
  ownerSessionId: typeof lab.ownerSessionId === 'string' ? lab.ownerSessionId : null,
42
42
  ownerSince: typeof lab.ownerSince === 'string' ? lab.ownerSince : null,
43
+ hostId: typeof lab.hostId === 'string' ? lab.hostId : null,
43
44
  createdAt: typeof lab.createdAt === 'string' ? lab.createdAt : null,
44
45
  }))
45
46
  return { state: { schemaVersion: SCHEMA_VERSION, labs }, problem: null }
@@ -65,6 +66,7 @@ export function addLab(state, lab) {
65
66
  port: Number.isInteger(lab.port) && lab.port > 0 ? lab.port : null,
66
67
  ownerSessionId: typeof lab.ownerSessionId === 'string' ? lab.ownerSessionId : null,
67
68
  ownerSince: typeof lab.ownerSince === 'string' ? lab.ownerSince : null,
69
+ hostId: typeof lab.hostId === 'string' ? lab.hostId : null,
68
70
  createdAt: lab.createdAt || new Date().toISOString(),
69
71
  })
70
72
  return state
@@ -93,5 +95,6 @@ export function describeLab(lab, runtime) {
93
95
  exit: live.exit || null,
94
96
  ownerSessionId: lab.ownerSessionId || null,
95
97
  ownerSince: lab.ownerSince || null,
98
+ hostId: lab.hostId || null,
96
99
  }
97
100
  }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * dsh-rig · `labs.json` 的读写(IO 层 · 唯一写这个是它)
3
+ *
4
+ * 以前这一步写在 supervisor 里:读一次、写一次,各自为政。桌面版和 web 版同时装着插件时,
5
+ * 两个进程共用同一份文件,谁后写谁赢 —— 另一端刚建的实验室记录会被这一端的旧内存状态抹掉。
6
+ *
7
+ * 现在的做法是「**锁 → 读盘 → 合并 → 写**」:
8
+ * - 锁用 `labs.json.lock`(`wx` 打开,独占);持有者崩了留下的死锁按 mtime 判陈旧后打破;
9
+ * - 合并规则在 `merge.js`(纯逻辑,可单测);
10
+ * - 写仍然是「临时文件 + rename」,保证读到的是完整 JSON,不会读到半截。
11
+ *
12
+ * 分工:这个模块只认文件与锁,不认识实验室;状态怎么解释归 `registry.js`。
13
+ */
14
+ import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
15
+ import { emptyState, parseState, serializeState } from './registry.js'
16
+ import { mergeStates } from './merge.js'
17
+
18
+ const LOCK_RETRY_MS = 25
19
+ const LOCK_TIMEOUT_MS = 4_000
20
+ /** 锁文件比这还旧 = 持锁的进程已经没了(正常持锁只有毫秒级)。 */
21
+ const LOCK_STALE_MS = 10_000
22
+
23
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
24
+
25
+ export class LabStateStore {
26
+ #file
27
+ #log
28
+
29
+ /**
30
+ * @param {{file: string, log?: (line: string) => void}} options `file` 是 `labs.json` 的绝对路径
31
+ */
32
+ constructor(options) {
33
+ this.#file = options.file
34
+ this.#log = typeof options.log === 'function' ? options.log : () => {}
35
+ }
36
+
37
+ get file() {
38
+ return this.#file
39
+ }
40
+
41
+ /**
42
+ * 读盘。读不到 / 坏了都降级成空状态并说明原因(绝不让插件起不来)。
43
+ * @returns {Promise<{state: object, problem: string|null}>}
44
+ */
45
+ async load() {
46
+ try {
47
+ const text = await readFile(this.#file, 'utf8')
48
+ return parseState(text)
49
+ } catch (err) {
50
+ if (err && err.code === 'ENOENT') return { state: emptyState(), problem: null }
51
+ return { state: emptyState(), problem: String((err && err.message) || err) }
52
+ }
53
+ }
54
+
55
+ /**
56
+ * 合并落盘:拿锁 → 读盘 → 与 `ours` 合并 → 写。
57
+ * @param {object} ours 本进程的状态(以它为准的那部分)
58
+ * @returns {Promise<object>} 合并后的状态(调用方应当拿它替换内存状态)
59
+ */
60
+ async save(ours) {
61
+ await mkdir(this.#dirOr('.', this.#file), { recursive: true })
62
+ return this.#withLock(async () => {
63
+ const { state: disk } = await this.load()
64
+ const merged = mergeStates(disk, ours)
65
+ await this.#write(merged)
66
+ return merged
67
+ })
68
+ }
69
+
70
+ /**
71
+ * 单独读一次并与内存合并(`create` 之前刷新 id 用)。
72
+ * @param {object} ours 本进程状态
73
+ * @returns {Promise<object>} 合并结果(不写盘)
74
+ */
75
+ async refresh(ours) {
76
+ const { state: disk } = await this.load()
77
+ return mergeStates(disk, ours)
78
+ }
79
+
80
+ #dirOr(fallback, file) {
81
+ const cut = Math.max(file.lastIndexOf('/'), file.lastIndexOf('\\'))
82
+ return cut > 0 ? file.slice(0, cut) : fallback
83
+ }
84
+
85
+ async #write(state) {
86
+ const tmp = `${this.#file}.tmp`
87
+ await writeFile(tmp, serializeState(state), 'utf8')
88
+ await rename(tmp, this.#file)
89
+ }
90
+
91
+ async #withLock(fn) {
92
+ const lockPath = `${this.#file}.lock`
93
+ const deadline = Date.now() + LOCK_TIMEOUT_MS
94
+ for (;;) {
95
+ try {
96
+ const handle = await open(lockPath, 'wx')
97
+ try {
98
+ await handle.writeFile(`${process.pid} ${new Date().toISOString()}`, 'utf8')
99
+ } finally {
100
+ await handle.close()
101
+ }
102
+ break
103
+ } catch (err) {
104
+ if (!err || err.code !== 'EEXIST') throw err
105
+ const stale = await this.#isStale(lockPath)
106
+ if (stale) {
107
+ this.#log(`[dsh-rig] 发现陈旧的 labs.json 锁(${lockPath}),清掉重试`)
108
+ await rm(lockPath, { force: true })
109
+ continue
110
+ }
111
+ if (Date.now() > deadline) {
112
+ throw new Error('labs.json 被另一个宿主进程锁着,等超时了 —— 稍后重试')
113
+ }
114
+ await sleep(LOCK_RETRY_MS)
115
+ }
116
+ }
117
+ try {
118
+ return await fn()
119
+ } finally {
120
+ await rm(lockPath, { force: true })
121
+ }
122
+ }
123
+
124
+ async #isStale(lockPath) {
125
+ try {
126
+ const info = await stat(lockPath)
127
+ return Date.now() - info.mtimeMs > LOCK_STALE_MS
128
+ } catch {
129
+ // 锁刚好被别人放掉了:当作不陈旧,下一轮会自己拿到
130
+ return false
131
+ }
132
+ }
133
+ }
@@ -1,11 +1,12 @@
1
1
  /**
2
- * dsh-rig · 进程看管(IO 层 · 唯一写盘点)
2
+ * dsh-rig · 进程看管(IO 层)
3
3
  *
4
4
  * 只做三件事:把它拉起来、看着它、把它收干净。拼命令在 spawn-plan.js、判隔离在 naming.js、日志在 log-buffer.js、
5
- * 瞬时状态在 runtime.js、端口在 port.js、探针在 probe.js、界面驱动在 ui-session.js、版本在 versioning.js。
5
+ * 瞬时状态在 runtime.js、端口在 port.js、探针在 probe.js、界面驱动在 ui-session.js、落盘与跨进程合并在 state-store.js。
6
6
  * 刻意不做常驻健康轮询(「卡住」和「在忙」长得一样);不持久化 token / pid(端口固定并落盘,为了 origin 稳定)。
7
7
  */
8
- import { mkdir, readFile, writeFile, rename, rm } from 'node:fs/promises'
8
+ import { mkdir, rm } from 'node:fs/promises'
9
+ import { randomBytes } from 'node:crypto'
9
10
  import { join } from 'node:path'
10
11
  import { DEFAULTS, STATUS } from './constants.js'
11
12
  import { labPaths } from './layout.js'
@@ -18,8 +19,10 @@ import { planVersionChange } from './versioning.js'
18
19
  import { copyCredentials, runOnce } from './seed.js'
19
20
  import { attachLines, killTree, spawnChild } from './process.js'
20
21
  import { probeOnce } from './probe.js'
21
- import { addLab, describeLab, emptyState, findLab, parseState, removeLab, serializeState } from './registry.js'
22
+ import { addLab, describeLab, emptyState, findLab, removeLab } from './registry.js'
22
23
  import { createRuntimeTable } from './runtime.js'
24
+ import { LabStateStore } from './state-store.js'
25
+ import { isForeign } from './merge.js'
23
26
  import { UiSessions } from './ui-session.js'
24
27
  import { buildLabReport } from './report.js'
25
28
 
@@ -32,6 +35,8 @@ export class LabSupervisor {
32
35
  #env
33
36
  #log
34
37
  #config
38
+ #store
39
+ #hostId
35
40
  #state = emptyState()
36
41
  #rt
37
42
  #ui
@@ -47,6 +52,8 @@ export class LabSupervisor {
47
52
  this.#env = opts.env || {}
48
53
  this.#log = typeof opts.log === 'function' ? opts.log : () => {}
49
54
  this.#config = { ...DEFAULTS, ...(opts.config || {}) }
55
+ this.#store = new LabStateStore({ file: labPaths(this.#root, null).labsFile, log: (line) => this.#log(line) })
56
+ this.#hostId = randomBytes(6).toString('hex')
50
57
  this.#rt = createRuntimeTable({
51
58
  logRingLines: this.#config.logRingLines,
52
59
  log: (line) => this.#log(line),
@@ -64,33 +71,23 @@ export class LabSupervisor {
64
71
  /** 广播「看这个实验室」:智能体首次驱动时,面板据此自动展开右栏(不抢焦点,每个会话只展开一次)。 */
65
72
  announce(id, sessionId) { this.#rt.emit({ type: 'open-lab', id, sessionId: sessionId || null }) }
66
73
 
67
- // ── 持久状态 ────────────────────────────────────────────────────────
74
+ // ── 持久状态(落盘与跨进程合并都在 state-store 里) ──────────────────
68
75
  async load() {
69
- const { labsFile, root } = labPaths(this.#root, null)
70
- await mkdir(root, { recursive: true })
71
- let text = ''
72
- try {
73
- text = await readFile(labsFile, 'utf8')
74
- } catch {
75
- this.#state = emptyState()
76
- return this.#state
77
- }
78
- const { state, problem } = parseState(text)
76
+ await mkdir(this.#root, { recursive: true })
77
+ const { state, problem } = await this.#store.load()
79
78
  if (problem) this.#log(`[dsh-rig] labs.json 读不出(${problem}),按空状态处理`)
80
79
  this.#state = state
81
80
  return state
82
81
  }
83
82
 
83
+ /** 落盘:锁 → 读盘 → 合并 → 写。别的宿主进程管的实验室不会被这次写抹掉。 */
84
84
  async #save() {
85
- const { labsFile } = labPaths(this.#root, null)
86
- const tmp = `${labsFile}.tmp`
87
- await writeFile(tmp, serializeState(this.#state), 'utf8')
88
- await rename(tmp, labsFile)
85
+ this.#state = await this.#store.save(this.#state)
89
86
  }
90
87
 
91
88
  // ── 读取 ────────────────────────────────────────────────────────────
92
89
  list() {
93
- return this.#state.labs.map((lab) => describeLab(lab, this.#rt.get(lab.id)))
90
+ return this.#state.labs.map((lab) => ({ ...describeLab(lab, this.#rt.get(lab.id)), foreign: isForeign(lab, this.#hostId) }))
94
91
  }
95
92
 
96
93
  get(id) {
@@ -120,20 +117,10 @@ export class LabSupervisor {
120
117
  }
121
118
 
122
119
  diagnostics() {
120
+ const { startTimeoutMs, logRingLines, maxLabs } = this.#config
123
121
  const sample = this.#state.labs[0]
124
- return buildDiagnostics({
125
- labRoot: this.#root,
126
- hostHome: this.#hostHome,
127
- hostProfile: this.#hostProfile,
128
- isElectron: this.#isElectron,
129
- env: this.#env,
130
- limits: {
131
- startTimeoutMs: this.#config.startTimeoutMs,
132
- logRingLines: this.#config.logRingLines,
133
- maxLabs: this.#config.maxLabs,
134
- },
135
- sampleLabHome: sample ? labPaths(this.#root, sample.id).home : null,
136
- })
122
+ const sampleLabHome = sample ? labPaths(this.#root, sample.id).home : null
123
+ return buildDiagnostics({ labRoot: this.#root, hostHome: this.#hostHome, hostProfile: this.#hostProfile, isElectron: this.#isElectron, env: this.#env, limits: { startTimeoutMs, logRingLines, maxLabs }, sampleLabHome })
137
124
  }
138
125
 
139
126
  // ── 界面驱动(让智能体像人一样操作实验室) ──────────────────────────
@@ -169,6 +156,8 @@ export class LabSupervisor {
169
156
  if (this.#state.labs.length >= this.#config.maxLabs) {
170
157
  throw new Error(`最多 ${this.#config.maxLabs} 个实验室;先销毁一个`)
171
158
  }
159
+ // 先把别的宿主进程写进去的实验室合进来,再挑 id —— 否则两边可能各建一个 lab1。
160
+ this.#state = await this.#store.refresh(this.#state)
172
161
  const id = nextLabId(this.#state.labs.map((lab) => lab.id))
173
162
  if (!id) throw new Error('没有可用 id')
174
163
 
@@ -186,6 +175,7 @@ export class LabSupervisor {
186
175
  version: typeof version === 'string' ? version : 'host',
187
176
  profile: profileNameFor(id),
188
177
  port: await pickFreePort(this.#config.basePort + this.#state.labs.length), // 固定端口 = 固定 origin(见 port.js)
178
+ hostId: this.#hostId,
189
179
  createdAt: new Date().toISOString(),
190
180
  }
191
181
  this.#rt.of(id)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-rig",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
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",
@@ -59,7 +59,7 @@
59
59
  "react": "^18.0.0"
60
60
  },
61
61
  "scripts": {
62
- "test": "node --test test/pure.test.mjs test/probe.test.mjs test/structure.test.mjs test/report.test.mjs test/mount.test.mjs test/routes.test.mjs test/ownership.test.mjs",
62
+ "test": "node --test test/pure.test.mjs test/probe.test.mjs test/structure.test.mjs test/report.test.mjs test/mount.test.mjs test/routes.test.mjs test/merge.test.mjs test/ownership.test.mjs",
63
63
  "check:client": "node --check lib/client.js",
64
64
  "check:host": "node --check lib/index.js"
65
65
  },