dsh-ris-ide 1.8.5 → 1.8.7

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.
@@ -0,0 +1,251 @@
1
+ /**
2
+ * The proxy service state machine: SOCKS probe → 待启动 → start, and 60 s of a dead
3
+ * upstream while running → stop → 待启动.
4
+ *
5
+ * Timers are recorded, not fired: each test drives `proxyLifecycleTick()` by hand so
6
+ * the assertions do not race wall-clock waits. `probe` / `startEngine` / `syncGit`
7
+ * are injected for the same reason — the point is the decisions, not the side effects.
8
+ */
9
+ import assert from 'node:assert/strict'
10
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
11
+ import { tmpdir } from 'node:os'
12
+ import { join } from 'node:path'
13
+ import { afterEach, beforeEach, test } from 'node:test'
14
+
15
+ const HOME = mkdtempSync(join(tmpdir(), 'dsh-ris-ide-lifecycle-'))
16
+ process.env.DSH_RIS_IDE_PROXY_HOME = HOME
17
+
18
+ const {
19
+ PHASE_PENDING,
20
+ PHASE_RUNNING,
21
+ PHASE_STOPPED,
22
+ proxyLifecycleTick,
23
+ proxyServiceSnapshot,
24
+ proxyStatePath,
25
+ readProxyServiceState,
26
+ releaseProxyLifecycle,
27
+ resetProxyLifecycle,
28
+ configureProxyLifecycle,
29
+ startProxyService,
30
+ stopProxyService,
31
+ } = await import('../lib/proxy-lifecycle.js')
32
+
33
+ /** One fake world: clock, probe answer, engine pid, bridge/git call log, timers. */
34
+ function world(options = {}) {
35
+ const state = {
36
+ now: 1_000_000,
37
+ probe: options.probe ?? { ok: true },
38
+ pid: options.pid ?? null,
39
+ alive: new Set(options.alive ?? []),
40
+ engineStarts: 0,
41
+ engineStops: 0,
42
+ bridgeStarts: 0,
43
+ bridgeStops: 0,
44
+ git: [],
45
+ armed: [],
46
+ config: options.config ?? { socks: { host: 'socks.example', port: 1080 }, rules: [] },
47
+ }
48
+ configureProxyLifecycle({
49
+ now: () => state.now,
50
+ probe: async () => state.probe,
51
+ readConfig: () => state.config,
52
+ readPid: () => state.pid,
53
+ isAlive: (pid) => state.alive.has(pid),
54
+ startEngine: async () => {
55
+ state.engineStarts += 1
56
+ state.pid = 4242
57
+ state.alive.add(4242)
58
+ return { ok: true, pid: 4242 }
59
+ },
60
+ stopEngine: async () => {
61
+ state.engineStops += 1
62
+ state.alive.delete(state.pid)
63
+ state.pid = null
64
+ return { ok: true }
65
+ },
66
+ startBridge: async () => {
67
+ state.bridgeStarts += 1
68
+ return { started: [], skipped: [], running: true }
69
+ },
70
+ stopBridge: async () => {
71
+ state.bridgeStops += 1
72
+ return { ok: true }
73
+ },
74
+ timers: {
75
+ setTimeout: (fn, ms) => {
76
+ state.armed.push({ fn, ms })
77
+ return { unref() {} }
78
+ },
79
+ clearTimeout: () => {},
80
+ },
81
+ })
82
+ state.syncGit = async (plan) => {
83
+ state.git.push(plan)
84
+ return { ok: true }
85
+ }
86
+ state.start = (extra = {}) => startProxyService(Object.assign({ cwd: '/w', syncGit: state.syncGit }, extra))
87
+ state.stop = (extra = {}) => stopProxyService(Object.assign({ cwd: '/w', syncGit: state.syncGit }, extra))
88
+ /** Forward the clock by `ms` and run one probe cycle at the new time. */
89
+ state.advance = async (ms) => {
90
+ state.now += ms
91
+ return proxyLifecycleTick()
92
+ }
93
+ return state
94
+ }
95
+
96
+ function persisted() {
97
+ return JSON.parse(readFileSync(proxyStatePath(), 'utf8'))
98
+ }
99
+
100
+ beforeEach(() => {
101
+ resetProxyLifecycle()
102
+ rmSync(join(HOME, 'proxy-state.json'), { force: true })
103
+ })
104
+
105
+ afterEach(() => {
106
+ resetProxyLifecycle()
107
+ })
108
+
109
+ test('a start whose SOCKS is unreachable parks in 待启动 and spawns nothing', async () => {
110
+ const w = world({ probe: { ok: false, error: 'ECONNREFUSED' } })
111
+ const started = await w.start()
112
+ assert.equal(started.phase, PHASE_PENDING)
113
+ assert.equal(started.waiting, true)
114
+ assert.match(started.reason, /已进入待启动/)
115
+ assert.equal(w.engineStarts, 0, 'no engine behind an upstream that cannot be reached')
116
+ assert.equal(w.bridgeStarts, 0)
117
+ assert.equal(w.git.length, 0)
118
+ assert.equal(w.armed.at(-1).ms, 5000, 'the watcher polls every 5 s while waiting')
119
+ assert.equal(proxyServiceSnapshot().phase, PHASE_PENDING)
120
+ assert.match(proxyServiceSnapshot().socksError, /ECONNREFUSED/)
121
+ const file = persisted()
122
+ assert.equal(file.phase, PHASE_PENDING)
123
+ assert.equal(file.owner, process.pid)
124
+ assert.equal(file.cwd, '/w')
125
+ })
126
+
127
+ test('the watcher brings the engine up as soon as SOCKS answers', async () => {
128
+ const w = world({ probe: { ok: false, error: 'EHOSTUNREACH' } })
129
+ await w.start()
130
+ w.probe = { ok: true }
131
+ const snapshot = await w.advance(5000)
132
+ assert.equal(snapshot.phase, PHASE_RUNNING)
133
+ assert.equal(w.engineStarts, 1)
134
+ assert.equal(w.bridgeStarts, 1, 'the bridge follows the service')
135
+ assert.deepEqual(w.git, [{ cwd: '/w', host: '', enabled: true }])
136
+ assert.equal(w.armed.at(-1).ms, 10000, 'the running loop probes every 10 s')
137
+ assert.equal(persisted().phase, PHASE_RUNNING)
138
+ assert.equal(persisted().pid, 4242)
139
+ })
140
+
141
+ test('an engine that loses SOCKS keeps running through the grace, then stops and waits', async () => {
142
+ const w = world()
143
+ await w.start()
144
+ assert.equal(w.engineStarts, 1)
145
+ w.probe = { ok: false, error: 'ETIMEDOUT' }
146
+ // The first failure only starts the clock; six more cycles reach the 60 s mark.
147
+ for (let cycle = 0; cycle < 6; cycle += 1) {
148
+ const snapshot = await w.advance(10000)
149
+ assert.equal(snapshot.phase, PHASE_RUNNING, `still running after ${(cycle + 1) * 10}s of a blip`)
150
+ assert.equal(w.engineStops, 0)
151
+ assert.equal(snapshot.downSince !== null, true)
152
+ }
153
+ const snapshot = await w.advance(10000)
154
+ assert.equal(snapshot.phase, PHASE_PENDING, '60 s of a dead upstream parks the service')
155
+ assert.equal(w.engineStops, 1)
156
+ assert.equal(w.bridgeStops, 1)
157
+ assert.deepEqual(w.git.at(-1), { cwd: '/w', host: '', enabled: false }, 'git entry goes away with the engine')
158
+ assert.match(snapshot.reason, /连续 60 秒不通/)
159
+ assert.equal(w.armed.at(-1).ms, 5000)
160
+ })
161
+
162
+ test('a recovering upstream inside the grace never stops the engine', async () => {
163
+ const w = world()
164
+ await w.start()
165
+ w.probe = { ok: false, error: 'ETIMEDOUT' }
166
+ await w.advance(10000)
167
+ await w.advance(10000)
168
+ w.probe = { ok: true }
169
+ const snapshot = await w.advance(10000)
170
+ assert.equal(snapshot.phase, PHASE_RUNNING)
171
+ assert.equal(snapshot.downSince, null)
172
+ assert.equal(w.engineStops, 0)
173
+ })
174
+
175
+ test('stopping while 待启动 cancels the wait and records stopped', async () => {
176
+ const w = world({ probe: { ok: false, error: 'ECONNREFUSED' } })
177
+ await w.start()
178
+ const stopped = await w.stop()
179
+ assert.equal(stopped.phase, PHASE_STOPPED)
180
+ assert.equal(persisted().phase, PHASE_STOPPED)
181
+ assert.equal(persisted().reason, '已停止')
182
+ w.probe = { ok: true }
183
+ // Nothing is watching any more: a later probe must not resurrect the engine.
184
+ await w.advance(5000)
185
+ assert.equal(w.engineStarts, 0)
186
+ })
187
+
188
+ test('an engine that exited on its own stops the service instead of probing forever', async () => {
189
+ const w = world()
190
+ await w.start()
191
+ assert.equal(w.engineStarts, 1)
192
+ w.pid = null
193
+ w.alive.clear()
194
+ const snapshot = await w.advance(10000)
195
+ assert.equal(snapshot.phase, PHASE_STOPPED)
196
+ assert.match(snapshot.reason, /代理引擎已退出/)
197
+ assert.equal(w.bridgeStops, 1)
198
+ assert.deepEqual(w.git.at(-1), { cwd: '/w', host: '', enabled: false })
199
+ })
200
+
201
+ test('starting over a running engine adopts it instead of spawning a second one', async () => {
202
+ const w = world({ pid: 7777, alive: [7777] })
203
+ const started = await w.start()
204
+ assert.equal(started.phase, PHASE_RUNNING)
205
+ assert.equal(started.alreadyRunning, true)
206
+ assert.equal(w.engineStarts, 0)
207
+ assert.equal(w.bridgeStarts, 0)
208
+ })
209
+
210
+ test('an unconfigured upstream is refused instead of waiting forever', async () => {
211
+ const w = world({ config: { socks: { host: '', port: 0 }, rules: [] } })
212
+ const started = await w.start()
213
+ assert.equal(started.ok, false)
214
+ assert.equal(started.phase, PHASE_STOPPED)
215
+ assert.match(started.error, /未配置上游 SOCKS 地址/)
216
+ assert.equal(w.engineStarts, 0, 'the engine cannot be armed without an upstream')
217
+ assert.equal(w.armed.length, 0, 'nothing will configure itself: no watcher')
218
+ assert.equal(proxyServiceSnapshot().phase, PHASE_STOPPED)
219
+ })
220
+
221
+ test('a wait does not outlive the process that owns it', async () => {
222
+ const w = world({ probe: { ok: false, error: 'ECONNREFUSED' } })
223
+ await w.start()
224
+ // Another process reading the file: the owner is gone, so 待启动 is history.
225
+ const file = persisted()
226
+ writeFileSync(proxyStatePath(), JSON.stringify(Object.assign({}, file, { owner: 999999 })))
227
+ resetProxyLifecycle()
228
+ const snapshot = proxyServiceSnapshot()
229
+ assert.equal(snapshot.phase, PHASE_STOPPED)
230
+ assert.equal(snapshot.watching, false)
231
+ })
232
+
233
+ test('releaseProxyLifecycle records the exit instead of leaving a live wait', async () => {
234
+ const w = world({ probe: { ok: false, error: 'ECONNREFUSED' } })
235
+ await w.start()
236
+ releaseProxyLifecycle()
237
+ assert.equal(readProxyServiceState().phase, PHASE_STOPPED)
238
+ assert.match(readProxyServiceState().reason, /等待已随进程退出结束/)
239
+ })
240
+
241
+ test('the phase listener hears each transition once', async () => {
242
+ const w = world({ probe: { ok: false, error: 'ECONNREFUSED' } })
243
+ const seen = []
244
+ const { setProxyPhaseListener } = await import('../lib/proxy-lifecycle.js')
245
+ setProxyPhaseListener((snapshot) => seen.push(snapshot.phase))
246
+ await w.start()
247
+ w.probe = { ok: true }
248
+ await w.advance(5000)
249
+ await w.stop()
250
+ assert.deepEqual(seen, [PHASE_PENDING, PHASE_RUNNING, PHASE_STOPPED])
251
+ })
@@ -33,6 +33,7 @@ import {
33
33
  parsePortSpec,
34
34
  pidAlive,
35
35
  pidIsProxy,
36
+ probeSocks,
36
37
  programKey,
37
38
  PROXY_MARKER,
38
39
  proxyConfigPath,
@@ -941,3 +942,50 @@ test('a driven rule keeps its per-workspace owners across a config round trip',
941
942
  const plain = normalizeConfig({ rules: [{ id: 'p', program: 'git', hosts: '*', ports: '*' }] })
942
943
  assert.equal(plain.rules[0].owners, undefined)
943
944
  })
945
+
946
+ /**
947
+ * The service gate: "SOCKS reachable" must mean a SOCKS5 greeting answered, not a
948
+ * TCP handshake. An unrelated listener (including this plugin's own loopback
949
+ * CONNECT proxy) completes the latter and would start an engine nobody can use.
950
+ */
951
+ test('probeSocks: only an answered SOCKS5 greeting counts as reachable', async () => {
952
+ const socks = createServer((client) => {
953
+ client.once('data', (greeting) => {
954
+ assert.equal(greeting[0], 0x05, 'the probe opens with the SOCKS5 greeting')
955
+ client.write(Buffer.from([0x05, 0x00]))
956
+ })
957
+ })
958
+ const http = createServer((client) => {
959
+ client.once('data', () => { client.write('HTTP/1.1 400 Bad Request\r\n') })
960
+ })
961
+ const auth = createServer((client) => {
962
+ client.once('data', () => { client.write(Buffer.from([0x05, 0xff])) })
963
+ })
964
+ for (const server of [socks, http, auth]) await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
965
+ try {
966
+ const ok = await probeSocks({ host: '127.0.0.1', port: socks.address().port }, { timeoutMs: 1000 })
967
+ assert.equal(ok.ok, true)
968
+ assert.equal(ok.socks, true)
969
+
970
+ const notSocks = await probeSocks({ host: '127.0.0.1', port: http.address().port }, { timeoutMs: 1000 })
971
+ assert.equal(notSocks.ok, false)
972
+ assert.equal(notSocks.socks, false)
973
+ assert.match(notSocks.error, /不是 SOCKS5 服务/)
974
+
975
+ const needsAuth = await probeSocks({ host: '127.0.0.1', port: auth.address().port }, { timeoutMs: 1000 })
976
+ assert.equal(needsAuth.ok, false)
977
+ assert.equal(needsAuth.socks, true)
978
+ assert.match(needsAuth.error, /要求认证/)
979
+ } finally {
980
+ for (const server of [socks, http, auth]) server.close()
981
+ }
982
+ })
983
+
984
+ test('probeSocks: a refused port and an unconfigured host fail with a reason', async () => {
985
+ const refused = await probeSocks({ host: '127.0.0.1', port: 1 }, { timeoutMs: 500 })
986
+ assert.equal(refused.ok, false)
987
+ assert.match(refused.error, /ECONNREFUSED/)
988
+ const missing = await probeSocks({ host: '', port: 0 })
989
+ assert.equal(missing.ok, false)
990
+ assert.match(missing.error, /未配置/)
991
+ })
@@ -581,7 +581,10 @@ test('a restart request hands over to a successor that waits for this pid (m1142
581
581
  test('the daemon only prompts on a user-initiated start and files elevation state per side (review B-P0-2/B-P1-1)', async () => {
582
582
  const source = readFileSync(new URL('../lib/risd/server.js', import.meta.url), 'utf8')
583
583
  assert.match(source, /const interactive = parsed\.interactive === true/, 'the flag is opt-in: saving rules and dsh starting never ask for a password')
584
- assert.match(source, /const redirector = await serializeBridge\(\(\) => startRedirectors\(\{ interactive \}\)\)/)
584
+ // The lifecycle now owns the start order; the click's flag still reaches the bridge
585
+ // through `interactive` in the one service call.
586
+ assert.match(source, /startProxyService\(\{\n\s+cwd,\n\s+gitHost,\n\s+interactive,/)
587
+ assert.match(source, /startBridge: \(options\) => serializeBridge\(\(\) => startRedirectors\(options\)\)/)
585
588
  const plugin = readFileSync(new URL('../lib/index.js', import.meta.url), 'utf8')
586
589
  assert.match(plugin, /const interactive = body\.interactive === true/, 'the plugin forwards the explicit-click flag')
587
590
  const reconcile = source.indexOf('startRedirectors({ sides: missing, interactive: false })')
@@ -11,16 +11,18 @@ import { existsSync, mkdtempSync, rmSync } from 'node:fs'
11
11
  import { tmpdir } from 'node:os'
12
12
  import { join } from 'node:path'
13
13
  import { risdStatePath } from '../lib/risd/state.js'
14
- import { makeHome, pickPort, removeHome, risdHeaders, startRisdProcess, waitFor, writeEngineFixture } from './risd-helpers.mjs'
14
+ import { makeHome, pickPort, removeHome, risdHeaders, startFakeSocks, startRisdProcess, waitFor, writeEngineFixture } from './risd-helpers.mjs'
15
15
 
16
16
  test('the daemon starts/stops the engine and reports one pid everywhere', async (t) => {
17
17
  const home = makeHome('risd-engine-')
18
18
  const cwd = mkdtempSync(join(tmpdir(), 'risd-engine-ws-'))
19
- writeEngineFixture(home, pickPort())
19
+ const socks = await startFakeSocks()
20
+ writeEngineFixture(home, pickPort(), { socksPort: socks.port })
20
21
  const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
21
22
  t.after(async () => {
22
23
  await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: risdHeaders(daemon.state), body: JSON.stringify({ action: 'stop', cwd }) }).catch(() => {})
23
24
  await daemon.stop()
25
+ await socks.close()
24
26
  removeHome(home)
25
27
  rmSync(cwd, { recursive: true, force: true })
26
28
  })
@@ -64,11 +66,13 @@ test('the daemon starts/stops the engine and reports one pid everywhere', async
64
66
  test('engine requests are validated and serialized', async (t) => {
65
67
  const home = makeHome('risd-engine-')
66
68
  const cwd = mkdtempSync(join(tmpdir(), 'risd-engine-ws-'))
67
- writeEngineFixture(home, pickPort())
69
+ const socks = await startFakeSocks()
70
+ writeEngineFixture(home, pickPort(), { socksPort: socks.port })
68
71
  const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
69
72
  t.after(async () => {
70
73
  await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: risdHeaders(daemon.state), body: JSON.stringify({ action: 'stop', cwd }) }).catch(() => {})
71
74
  await daemon.stop()
75
+ await socks.close()
72
76
  removeHome(home)
73
77
  rmSync(cwd, { recursive: true, force: true })
74
78
  })
@@ -93,3 +97,41 @@ test('engine requests are validated and serialized', async (t) => {
93
97
  assert.equal(status.running, true)
94
98
  assert.equal(status.pid, first)
95
99
  })
100
+
101
+ test('an unreachable SOCKS parks the daemon start in 待启动, then stop cleans it up', async (t) => {
102
+ const home = makeHome('risd-engine-')
103
+ const cwd = mkdtempSync(join(tmpdir(), 'risd-engine-ws-'))
104
+ // Port 1 is the fixture default: nothing listens, so the service must refuse to
105
+ // spawn an engine and report 待启动 instead of a running pid.
106
+ writeEngineFixture(home, pickPort(), { workspace: cwd })
107
+ const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
108
+ t.after(async () => {
109
+ await daemon.stop()
110
+ rmSync(cwd, { recursive: true, force: true })
111
+ removeHome(home)
112
+ })
113
+
114
+ const started = await (await fetch(`${daemon.state.url}/v1/engine`, {
115
+ method: 'POST',
116
+ headers: risdHeaders(daemon.state),
117
+ body: JSON.stringify({ action: 'start', cwd }),
118
+ })).json()
119
+ assert.equal(started.ok, true)
120
+ assert.equal(started.result.phase, 'pending', JSON.stringify(started.result))
121
+ assert.equal(started.result.waiting, true)
122
+ assert.match(started.result.reason, /待启动/)
123
+ assert.equal(existsSync(join(home, 'proxy.pid')), false, 'no engine behind an unreachable upstream')
124
+
125
+ const read = await (await fetch(`${daemon.state.url}/v1/engine?cwd=${encodeURIComponent(cwd)}`, { headers: risdHeaders(daemon.state) })).json()
126
+ assert.equal(read.engine.running, false)
127
+ assert.equal(read.service.phase, 'pending', 'the wait is visible on the same route')
128
+
129
+ const stopped = await (await fetch(`${daemon.state.url}/v1/engine`, {
130
+ method: 'POST',
131
+ headers: risdHeaders(daemon.state),
132
+ body: JSON.stringify({ action: 'stop', cwd }),
133
+ })).json()
134
+ assert.equal(stopped.result.phase, 'stopped')
135
+ const after = await (await fetch(`${daemon.state.url}/v1/engine?cwd=${encodeURIComponent(cwd)}`, { headers: risdHeaders(daemon.state) })).json()
136
+ assert.equal(after.service.phase, 'stopped')
137
+ })
@@ -64,10 +64,11 @@ test('the start half rides the lease, not a separate route or plugin call', () =
64
64
 
65
65
  const start = server.indexOf('function followStartForLease(')
66
66
  assert.ok(start > 0, 'the start half lives next to the engine helpers')
67
- const startBlock = server.slice(start, start + 2600)
67
+ const startBlock = server.slice(start, start + 3600)
68
68
  assert.match(startBlock, /engineSummary\(\)\.state === 'running'/, 'an engine that is already up is left alone')
69
69
  assert.match(startBlock, /buildProfile\(status\.config\)\.rules\.length === 0/, 'rules decide whether starting is worth it')
70
- assert.match(startBlock, /startRedirectors\(\{ interactive: false \}\)/, 'a startup side effect must never prompt')
70
+ assert.match(startBlock, /interactive: false,/, 'a startup side effect must never prompt')
71
+ assert.match(startBlock, /startProxyService\(\{/, 'the lease start goes through the same SOCKS gate as a click')
71
72
  assert.match(startBlock, /reason: 'no-lease'/, 'a lease that left mid-round-trip must not spawn an engine')
72
73
  // The same promise is awaitable, so teardown can let a departing lease's start land
73
74
  // before it decides what to stop (otherwise engineCwd is still null and the engine
@@ -12,7 +12,7 @@ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
12
12
  import { tmpdir } from 'node:os'
13
13
  import { join } from 'node:path'
14
14
  import { readRisdState } from '../lib/risd/state.js'
15
- import { makeHome, pickPort, pidAlive, removeHome, risdHeaders, startRisdProcess, waitFor, writeEngineFixture } from './risd-helpers.mjs'
15
+ import { makeHome, pickPort, pidAlive, removeHome, risdHeaders, startFakeSocks, startRisdProcess, waitFor, writeEngineFixture } from './risd-helpers.mjs'
16
16
 
17
17
  async function post(state, path, body) {
18
18
  const response = await fetch(`${state.url}${path}`, { method: 'POST', headers: risdHeaders(state), body: JSON.stringify(body) })
@@ -27,9 +27,11 @@ async function get(state, path) {
27
27
  test('a handoff shutdown keeps the engine for the next daemon (same pid)', async (t) => {
28
28
  const home = makeHome('risd-handoff-')
29
29
  const cwd = mkdtempSync(join(tmpdir(), 'risd-handoff-ws-'))
30
+ const socks = await startFakeSocks()
31
+ t.after(async () => { await socks.close() })
30
32
  t.after(() => removeHome(home))
31
33
  t.after(() => rmSync(cwd, { recursive: true, force: true }))
32
- writeEngineFixture(home, pickPort())
34
+ writeEngineFixture(home, pickPort(), { socksPort: socks.port })
33
35
 
34
36
  const first = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
35
37
  const enginePid = await (async () => {
@@ -6,6 +6,7 @@
6
6
  * dir, so the machine-level `~/.dsh-ris-ide` is never read or written.
7
7
  */
8
8
  import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
9
+ import { createServer } from 'node:net'
9
10
  import { tmpdir } from 'node:os'
10
11
  import { join } from 'node:path'
11
12
  import { spawn } from 'node:child_process'
@@ -132,9 +133,9 @@ export function pickPort() {
132
133
  * Write the machine-level `proxy.json` an engine test starts from: one enabled java
133
134
  * rule and a dead SOCKS upstream. `workspace` is the row's owner (default: the home).
134
135
  */
135
- export function writeEngineFixture(home, port, { workspace = home } = {}) {
136
+ export function writeEngineFixture(home, port, { workspace = home, socksPort = 1 } = {}) {
136
137
  writeFileSync(join(home, 'proxy.json'), JSON.stringify({
137
- socks: { host: '127.0.0.1', port: 1, dbPort: 0, redisPort: 0 },
138
+ socks: { host: '127.0.0.1', port: socksPort, dbPort: 0, redisPort: 0 },
138
139
  listenPort: port,
139
140
  rules: [{
140
141
  id: 'rule-1',
@@ -253,3 +254,23 @@ export function api(state, path, { method = 'GET', body } = {}) {
253
254
  req.end()
254
255
  })
255
256
  }
257
+
258
+ /**
259
+ * A SOCKS5 upstream that only answers the greeting (`05 00`).
260
+ *
261
+ * The service refuses to start an engine without a reachable SOCKS host (that is the
262
+ * 待启动 rule), so daemon integration tests need a listener that passes the gate even
263
+ * though nothing in them opens a tunnel.
264
+ *
265
+ * @returns `{ port, close }` — close it after the daemon is gone.
266
+ */
267
+ export async function startFakeSocks() {
268
+ const server = createServer((socket) => {
269
+ socket.on('data', (chunk) => {
270
+ if (chunk.length > 0 && chunk[0] !== 0x05) return
271
+ try { socket.write(Buffer.from([0x05, 0x00])) } catch { /* client gone */ }
272
+ })
273
+ })
274
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
275
+ return { port: server.address().port, close: () => new Promise((resolve) => server.close(resolve)) }
276
+ }
@@ -10,16 +10,18 @@ import { tmpdir } from 'node:os'
10
10
  import { join } from 'node:path'
11
11
  // The waits are deliberately generous: teardown is 300ms debounce + engine stop
12
12
  // (5s grace) + bridge/git attempts, so `waitFor`'s 15s default is the floor.
13
- import { makeHome, pickPort, removeHome, risdHeaders, sleep, startRisdProcess, waitFor, writeEngineFixture } from './risd-helpers.mjs'
13
+ import { makeHome, pickPort, removeHome, risdHeaders, sleep, startFakeSocks, startRisdProcess, waitFor, writeEngineFixture } from './risd-helpers.mjs'
14
14
 
15
15
  async function startFixture(t) {
16
16
  const home = makeHome('risd-teardown-')
17
17
  const cwd = mkdtempSync(join(tmpdir(), 'risd-teardown-ws-'))
18
18
  const port = pickPort()
19
- writeEngineFixture(home, port, { workspace: cwd })
19
+ const socks = await startFakeSocks()
20
+ writeEngineFixture(home, port, { workspace: cwd, socksPort: socks.port })
20
21
  const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
21
22
  t.after(async () => {
22
23
  await daemon.stop()
24
+ await socks.close()
23
25
  removeHome(home)
24
26
  rmSync(cwd, { recursive: true, force: true })
25
27
  })
@@ -177,7 +177,10 @@ test('the IDE tab drops the toolbar and names workspaces by folder', async () =>
177
177
  const engineBlock = html.slice(engineToggleAt, html.indexOf("el('engine-toggle').onclick", engineToggleAt))
178
178
  assert.ok(engineBlock.length > 0, 'the engine toggle block is bounded')
179
179
  assert.doesNotMatch(engineBlock, /interactive/, 'starting or stopping the engine never passes interactive (m05590)')
180
- assert.match(html, /button\.textContent = running \? '停止' : '启动引擎'/, 'the button says it starts the engine, not the whole stack')
180
+ // A 待启动 service (SOCKS not reachable yet) is not running, but "启动" there would
181
+ // only re-arm the same wait: the label names the stop that cancels it.
182
+ assert.match(html, /button\.textContent = running \? '停止' : \(pending \? '取消等待' : '启动引擎'\)/, 'the button says it starts the engine, not the whole stack')
183
+ assert.match(html, /var pending = state\.proxyPhase === 'pending' && running !== true/, 'pending is derived from the service phase, not guessed from the engine pid')
181
184
  assert.doesNotMatch(html, /proxy-start-with-dsh/, 'the follow-dsh lifecycle checkbox is the only policy (m13950)')
182
185
  assert.match(html, /dsh 接入时启动引擎/, 'the lifecycle row describes both halves of following dsh')
183
186
  // The elevation note lives in the component card and clears itself (m12923).
@@ -769,7 +772,9 @@ test('the elevation warning is written after the proxy refresh', async () => {
769
772
  const source = readFileSync(new URL('../lib/risd/ui.js', import.meta.url), 'utf8')
770
773
  const slice = source.slice(source.indexOf('function toggleProxyEngine('), source.indexOf("el('engine-toggle').onclick"))
771
774
  const refreshAt = slice.indexOf('loadProxyTab()')
772
- const warnAt = slice.indexOf("host.innerHTML = banner('warn', warn)")
775
+ // The start/stop outcome may be warn (elevation, 待启动) or err (refused start):
776
+ // either way it is written after loadProxyTab cleared the banner.
777
+ const warnAt = slice.indexOf("host.innerHTML = banner(failedStart ? 'err' : 'warn', warn)")
773
778
  assert.ok(refreshAt >= 0, 'the engine toggle refreshes the proxy tab')
774
779
  assert.ok(warnAt > refreshAt, 'the elevation warning is written after loadProxyTab cleared the banner')
775
780
  assert.doesNotMatch(slice, /if \(skipped\.length > 0\) \{\n\s+host\.innerHTML/, 'no warning is written before the refresh')
@@ -796,3 +801,17 @@ test('the IDE pane keeps its own workspace when dsh switches (m04873)', async ()
796
801
  assert.match(load, /var selected = pickIdeWindow\(windows\)/)
797
802
  assert.doesNotMatch(load, /windows\.filter\(function \(win\) \{ return win\.live !== false; \}\)\[0\] \|\| windows\[0\]/)
798
803
  })
804
+
805
+ test('the proxy phase refreshes by itself without re-rendering the rule table', () => {
806
+ const source = readFileSync(new URL('../lib/risd/ui.js', import.meta.url), 'utf8')
807
+ assert.match(source, /function paintProxyPhase\(\) \{/, 'pill and button painting is its own function')
808
+ assert.match(source, /function refreshProxyPhase\(\) \{/, 'a phase-only refresh exists')
809
+ const refresh = source.slice(source.indexOf('function refreshProxyPhase('))
810
+ const slice = refresh.slice(0, refresh.indexOf('function paintRuleStatus('))
811
+ assert.doesNotMatch(slice, /renderProxyTab\(/, 'the heartbeat must not rebuild the inputs under the cursor')
812
+ assert.match(slice, /if \(phase === state\.proxyPhase && running === state\.proxyRunning\) return/, 'an unchanged phase is a no-op')
813
+ assert.match(slice, /paintProxyPhase\(\);\n\s+paintRuleStatus\(\);/, 'both derived views are repainted together')
814
+ const poll = source.slice(source.indexOf('state.pollTimer = setInterval('))
815
+ assert.match(poll, /if \(state\.tab === 'proxy'\) refreshProxyPhase\(\)/, 'the proxy tab polls its own phase')
816
+ assert.match(source, /var cell = tr\.children\[4\]/, 'rule status is updated in place, not by re-rendering rows')
817
+ })