dsh-ris-ide 1.8.1 → 1.8.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.
Files changed (47) hide show
  1. package/README.md +2 -2
  2. package/lib/client.js +311 -72
  3. package/lib/debug/vendor/README.md +14 -0
  4. package/lib/debug/vendor/jdwp/client.js +9 -4
  5. package/lib/debug/vendor/src/jdwp/client.ts +12 -5
  6. package/lib/index.js +794 -48
  7. package/lib/redirector.js +42 -2
  8. package/lib/risd/lifecycle.js +9 -3
  9. package/lib/risd/server.js +308 -13
  10. package/lib/risd/ui.js +149 -112
  11. package/lib/risd-client.js +4 -1
  12. package/lib/startup.js +27 -7
  13. package/package.json +2 -2
  14. package/test/client-viewer.test.mjs +188 -95
  15. package/test/clipboard.test.mjs +259 -0
  16. package/test/debug-engine.test.mjs +3 -1
  17. package/test/dsh-origin.test.mjs +4 -11
  18. package/test/dsh-window-refresh.test.mjs +166 -1
  19. package/test/harness.test.mjs +1 -1
  20. package/test/helpers/cmd.mjs +29 -0
  21. package/test/helpers/tgz.mjs +71 -0
  22. package/test/host-search.test.mjs +18 -11
  23. package/test/host-tail.test.mjs +119 -24
  24. package/test/proxy-route.test.mjs +61 -0
  25. package/test/proxy-window.test.mjs +5 -0
  26. package/test/proxy.test.mjs +13 -1
  27. package/test/proxybridge-bundle.test.mjs +1 -59
  28. package/test/redirector-bundle.test.mjs +21 -67
  29. package/test/redirector.test.mjs +41 -4
  30. package/test/risd-api.test.mjs +81 -28
  31. package/test/risd-bridge-degrade.test.mjs +3 -29
  32. package/test/risd-engine.test.mjs +13 -50
  33. package/test/risd-entry.test.mjs +0 -37
  34. package/test/risd-follow-start.test.mjs +101 -0
  35. package/test/risd-git.test.mjs +7 -5
  36. package/test/risd-handoff.test.mjs +6 -50
  37. package/test/risd-helpers.mjs +150 -3
  38. package/test/risd-host-p2.test.mjs +2 -30
  39. package/test/risd-lifecycle.test.mjs +25 -0
  40. package/test/risd-programs.test.mjs +4 -34
  41. package/test/risd-review-p2.test.mjs +0 -13
  42. package/test/risd-shutdown.test.mjs +5 -38
  43. package/test/risd-teardown.test.mjs +8 -27
  44. package/test/risd-ui.test.mjs +169 -13
  45. package/test/risd-write.test.mjs +2 -1
  46. package/test/startup-reconcile.test.mjs +44 -8
  47. package/test/proxy-restart.test.mjs +0 -39
@@ -0,0 +1,101 @@
1
+ // 「代理引擎跟随 dsh」 has two halves on ONE signal: the lease. The daemon starts the
2
+ // engine when the first lease arrives and tears it down when the last one leaves, so
3
+ // the two sides read the same lifecycle.proxy.followDsh and cannot disagree (m13950).
4
+ // The automatic path must stay non-interactive: a password dialog cannot be a side
5
+ // effect of dsh starting (m13910) — only a click may ask.
6
+ import assert from 'node:assert/strict'
7
+ import { readFileSync } from 'node:fs'
8
+ import test from 'node:test'
9
+
10
+ import { makeHome, removeHome, sleep, startRisdProcess } from './risd-helpers.mjs'
11
+
12
+ const read = (file) => readFileSync(new URL(`../${file}`, import.meta.url), 'utf8')
13
+
14
+ test('a lease never starts an engine when the policy is off or no rule is actionable', async () => {
15
+ const home = makeHome('risd-follow-')
16
+ const daemon = await startRisdProcess({ home })
17
+ try {
18
+ const { port, token } = daemon.state
19
+ const headers = {
20
+ authorization: `Bearer ${token}`,
21
+ 'x-risd-api-version': '1',
22
+ 'content-type': 'application/json',
23
+ }
24
+ const lease = (cwd) => fetch(`http://127.0.0.1:${port}/v1/leases`, {
25
+ method: 'POST',
26
+ headers,
27
+ body: JSON.stringify({ ownerPid: process.pid, cwd }),
28
+ })
29
+ const save = (body) => fetch(`http://127.0.0.1:${port}/v1/config`, {
30
+ method: 'POST',
31
+ headers,
32
+ body: JSON.stringify(body),
33
+ })
34
+ const engine = async () => {
35
+ const health = await (await fetch(`http://127.0.0.1:${port}/v1/health`)).json()
36
+ return health.engine?.state
37
+ }
38
+
39
+ // Following dsh is the default, but the rule table is empty: no engine.
40
+ assert.equal((await lease(home)).status, 200)
41
+ await sleep(400)
42
+ assert.equal(await engine(), 'stopped', 'an empty table is not a reason to spawn an engine')
43
+
44
+ // Turning the lifecycle off must also turn the start half off.
45
+ assert.equal((await save({ lifecycle: { proxy: { followDsh: false } } })).status, 200)
46
+ assert.equal((await lease(home)).status, 200)
47
+ await sleep(400)
48
+ assert.equal(await engine(), 'stopped', 'a policy that does not follow dsh cannot start it')
49
+ } finally {
50
+ await daemon.stop()
51
+ await sleep(100)
52
+ removeHome(home)
53
+ }
54
+ })
55
+
56
+ test('the start half rides the lease, not a separate route or plugin call', () => {
57
+ const server = read('lib/risd/server.js')
58
+ const leaseAt = server.indexOf("if (path === '/v1/leases')")
59
+ assert.ok(leaseAt > 0)
60
+ const leaseBlock = server.slice(leaseAt, server.indexOf("const leaseMatch", leaseAt))
61
+ assert.match(leaseBlock, /lifecycle\.proxy\.followDsh === true/, 'the same policy the teardown reads')
62
+ assert.match(leaseBlock, /followStartForLease\(lease\.cwd\)/, 'the lease is the start signal')
63
+
64
+ const start = server.indexOf('function followStartForLease(')
65
+ assert.ok(start > 0, 'the start half lives next to the engine helpers')
66
+ const startBlock = server.slice(start, start + 2600)
67
+ assert.match(startBlock, /engineSummary\(\)\.state === 'running'/, 'an engine that is already up is left alone')
68
+ assert.match(startBlock, /buildProfile\(status\.config\)\.rules\.length === 0/, 'rules decide whether starting is worth it')
69
+ assert.match(startBlock, /startRedirectors\(\{ interactive: false \}\)/, 'a startup side effect must never prompt')
70
+ assert.match(startBlock, /reason: 'no-lease'/, 'a lease that left mid-round-trip must not spawn an engine')
71
+ // The same promise is awaitable, so teardown can let a departing lease's start land
72
+ // before it decides what to stop (otherwise engineCwd is still null and the engine
73
+ // is orphaned — m13960).
74
+ assert.match(startBlock, /followStarting = work\.finally/)
75
+ const teardownAt = server.indexOf('function scheduleTeardown()')
76
+ const teardownBlock = server.slice(teardownAt, server.indexOf('const leases = createLeaseRegistry', teardownAt))
77
+ assert.match(teardownBlock, /await followStarting\.catch\(\(\) => \{\}\)/, 'teardown waits for an in-flight start')
78
+ assert.match(teardownBlock, /followStarting === null\) return/, 'a pending start must not suppress the teardown schedule')
79
+ assert.doesNotMatch(server, /'\/v1\/follow-start'/, 'there is no second entry point to keep in sync')
80
+
81
+ // Teardown reads the same key, so "start follows dsh" and "stop follows dsh" are
82
+ // two directions of one policy rather than two switches.
83
+ assert.match(server, /if \(lifecycle\.proxy\.followDsh === true\) \{\n\s+await teardownNetwork\(cwd\)/)
84
+
85
+ assert.doesNotMatch(read('lib/risd-client.js'), /followStartRisd/, 'the plugin does not need a call')
86
+ assert.doesNotMatch(read('lib/index.js'), /followStartRisd/, 'the lease acquired by attachBridgeState is the signal')
87
+ })
88
+
89
+ test('saving the rule table never starts the engine (m13920)', () => {
90
+ const server = read('lib/risd/server.js')
91
+ const at = server.indexOf("path === '/v1/proxy' && method === 'POST'")
92
+ assert.ok(at > 0)
93
+ const block = server.slice(at, server.indexOf("if (path === '/v1/action'", at))
94
+ assert.doesNotMatch(block, /await startProxy\(/, 'a save must not spawn the engine')
95
+ assert.match(block, /switchEnforcement/, 'an already-running bridge is reloaded instead')
96
+
97
+ const ui = read('lib/risd/ui.js')
98
+ assert.doesNotMatch(ui, /function maybeStartProxy/, 'the save-triggered start is gone')
99
+ assert.doesNotMatch(ui, /proxy-start-with-dsh/, 'the policy is the lifecycle checkbox, not a second switch')
100
+ assert.match(ui, /保存不会启动它/, 'the banner names the button instead of starting')
101
+ })
@@ -16,6 +16,8 @@ import { tmpdir } from 'node:os'
16
16
  import { join } from 'node:path'
17
17
  import { spawnSync } from 'node:child_process'
18
18
 
19
+ import { HAS_GIT, skipWithout } from './helpers/cmd.mjs'
20
+
19
21
  const home = mkdtempSync(join(tmpdir(), 'risd-git-home-'))
20
22
  const workspace = mkdtempSync(join(tmpdir(), 'risd-git-ws-'))
21
23
  const globalConfig = join(home, 'gitconfig')
@@ -52,7 +54,7 @@ test.after(() => {
52
54
  rmSync(workspace, { recursive: true, force: true })
53
55
  })
54
56
 
55
- test('a saved table keeps the git entry on the current host', async () => {
57
+ test('a saved table keeps the git entry on the current host', { skip: skipWithout(HAS_GIT, 'git') }, async () => {
56
58
  writeTable('git-a.example')
57
59
  const first = await git.reconcileGitProxy({ cwd: workspace })
58
60
  assert.equal(first.ok, true)
@@ -60,7 +62,7 @@ test('a saved table keeps the git entry on the current host', async () => {
60
62
  assert.equal(readKey(keyFor('git-a.example')), `socks5h://${SOCKS.host}:${SOCKS.port}`)
61
63
  })
62
64
 
63
- test('repointing the git rule unsets the old host and writes the new one', async () => {
65
+ test('repointing the git rule unsets the old host and writes the new one', { skip: skipWithout(HAS_GIT, 'git') }, async () => {
64
66
  writeTable('git-b.example')
65
67
  const second = await git.reconcileGitProxy({ cwd: workspace })
66
68
  assert.equal(second.ok, true)
@@ -69,7 +71,7 @@ test('repointing the git rule unsets the old host and writes the new one', async
69
71
  assert.equal(readKey(keyFor('git-b.example')), `socks5h://${SOCKS.host}:${SOCKS.port}`)
70
72
  })
71
73
 
72
- test('deleting the git rule clears the entry instead of leaving a dead tunnel', async () => {
74
+ test('deleting the git rule clears the entry instead of leaving a dead tunnel', { skip: skipWithout(HAS_GIT, 'git') }, async () => {
73
75
  writeTable('')
74
76
  const cleared = await git.reconcileGitProxy({ cwd: workspace })
75
77
  assert.equal(cleared.ok, true)
@@ -78,7 +80,7 @@ test('deleting the git rule clears the entry instead of leaving a dead tunnel',
78
80
  assert.equal(existsSync(git.gitProxyStatePath()), false, 'bookkeeping must not outlive the entry')
79
81
  })
80
82
 
81
- test('a value somebody else replaced is left alone (E7 ownership)', async () => {
83
+ test('a value somebody else replaced is left alone (E7 ownership)', { skip: skipWithout(HAS_GIT, 'git') }, async () => {
82
84
  writeTable('git-c.example')
83
85
  await git.reconcileGitProxy({ cwd: workspace })
84
86
  assert.equal(readKey(keyFor('git-c.example')), `socks5h://${SOCKS.host}:${SOCKS.port}`)
@@ -91,7 +93,7 @@ test('a value somebody else replaced is left alone (E7 ownership)', async () =>
91
93
  assert.equal(existsSync(git.gitProxyStatePath()), false, 'our bookkeeping is dropped')
92
94
  })
93
95
 
94
- test('disabling the proxy also leaves a foreign git value alone', async () => {
96
+ test('disabling the proxy also leaves a foreign git value alone', { skip: skipWithout(HAS_GIT, 'git') }, async () => {
95
97
  // Review B-P0-1: only clearGitProxy() had the ownership check; the disable and
96
98
  // host-switch paths unset the key directly, so a user's own scoped proxy was
97
99
  // deleted whenever the plugin stopped the tunnel.
@@ -8,66 +8,22 @@
8
8
  */
9
9
  import assert from 'node:assert/strict'
10
10
  import test from 'node:test'
11
- import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
11
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
12
12
  import { tmpdir } from 'node:os'
13
13
  import { join } from 'node:path'
14
- import { RISD_API_VERSION, readRisdState } from '../lib/risd/state.js'
15
- import { makeHome, removeHome, sleep, startRisdProcess } from './risd-helpers.mjs'
16
-
17
- function pickPort() {
18
- return 20000 + Math.floor(Math.random() * 20000)
19
- }
20
-
21
- function writeEngineFixture(home, port) {
22
- writeFileSync(join(home, 'proxy.json'), JSON.stringify({
23
- socks: { host: '127.0.0.1', port: 1, dbPort: 0, redisPort: 0 },
24
- listenPort: port,
25
- rules: [{
26
- id: 'rule-1',
27
- program: 'java',
28
- hosts: ['127.0.0.1'],
29
- ports: ['443'],
30
- enabled: true,
31
- shadow: false,
32
- source: 'user',
33
- workspace: home,
34
- }],
35
- }, null, 2))
36
- }
37
-
38
- function headers(state) {
39
- return { authorization: `Bearer ${state.token}`, 'x-risd-api-version': String(RISD_API_VERSION), 'content-type': 'application/json' }
40
- }
14
+ import { readRisdState } from '../lib/risd/state.js'
15
+ import { makeHome, pickPort, pidAlive, removeHome, risdHeaders, startRisdProcess, waitFor, writeEngineFixture } from './risd-helpers.mjs'
41
16
 
42
17
  async function post(state, path, body) {
43
- const response = await fetch(`${state.url}${path}`, { method: 'POST', headers: headers(state), body: JSON.stringify(body) })
18
+ const response = await fetch(`${state.url}${path}`, { method: 'POST', headers: risdHeaders(state), body: JSON.stringify(body) })
44
19
  return { status: response.status, payload: await response.json().catch(() => ({})) }
45
20
  }
46
21
 
47
22
  async function get(state, path) {
48
- const response = await fetch(`${state.url}${path}`, { headers: headers(state) })
23
+ const response = await fetch(`${state.url}${path}`, { headers: risdHeaders(state) })
49
24
  return { status: response.status, payload: await response.json().catch(() => ({})) }
50
25
  }
51
26
 
52
- async function waitFor(fn, timeoutMs = 15000) {
53
- const deadline = Date.now() + timeoutMs
54
- while (Date.now() < deadline) {
55
- if (await fn()) return true
56
- await sleep(100)
57
- }
58
- return false
59
- }
60
-
61
- function pidAlive(pid) {
62
- if (!Number.isInteger(pid) || pid <= 0) return false
63
- try {
64
- process.kill(pid, 0)
65
- return true
66
- } catch {
67
- return false
68
- }
69
- }
70
-
71
27
  test('a handoff shutdown keeps the engine for the next daemon (same pid)', async (t) => {
72
28
  const home = makeHome('risd-handoff-')
73
29
  const cwd = mkdtempSync(join(tmpdir(), 'risd-handoff-ws-'))
@@ -92,7 +48,7 @@ test('a handoff shutdown keeps the engine for the next daemon (same pid)', async
92
48
  assert.equal(draining.payload.handoff, true)
93
49
  assert.equal(await first.stop(), 0, 'the predecessor exits cleanly')
94
50
  assert.equal(existsSync(join(home, 'risd.json')), true, 'the state note survives a handoff')
95
- const noted = JSON.parse((await import('node:fs')).readFileSync(join(home, 'risd.json'), 'utf8'))
51
+ const noted = JSON.parse(readFileSync(join(home, 'risd.json'), 'utf8'))
96
52
  assert.equal(noted.handoff?.enginePid, enginePid, 'the note names the engine to adopt')
97
53
  assert.equal(noted.handoff?.cwd, cwd)
98
54
  assert.equal(pidAlive(enginePid), true, 'nothing tore the engine down')
@@ -5,12 +5,14 @@
5
5
  * Every test gets its own `DSH_RIS_IDE_PROXY_HOME`-style home under the OS temp
6
6
  * dir, so the machine-level `~/.dsh-ris-ide` is never read or written.
7
7
  */
8
- import { mkdtempSync, rmSync } from 'node:fs'
8
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
9
9
  import { tmpdir } from 'node:os'
10
10
  import { join } from 'node:path'
11
11
  import { spawn } from 'node:child_process'
12
+ import { request } from 'node:http'
13
+ import { Readable } from 'node:stream'
12
14
  import { fileURLToPath } from 'node:url'
13
- import { readRisdState } from '../lib/risd/state.js'
15
+ import { readRisdState, RISD_API_VERSION } from '../lib/risd/state.js'
14
16
 
15
17
  export const RISD_BIN = fileURLToPath(new URL('../bin/risd.mjs', import.meta.url))
16
18
 
@@ -56,6 +58,11 @@ export async function startRisdProcess({ home = makeHome(), port = 0, env = {} }
56
58
  HOME: home,
57
59
  USERPROFILE: home,
58
60
  GIT_CONFIG_GLOBAL: join(home, '.gitconfig'),
61
+ // Answer the two PowerShell probes with "nothing is running" (see
62
+ // `probesStubbed` in lib/redirector.js): a cold `Get-Process` costs ~8 s on WSL
63
+ // and the answer used to be whatever bridge was up on the developer's desktop,
64
+ // so the save paths in these tests were slow AND order-dependent.
65
+ DSH_RIS_IDE_STUB_PROBES: '1',
59
66
  }
60
67
  const child = spawn(process.execPath, [RISD_BIN, 'serve', '--home', home, '--port', String(port)], {
61
68
  stdio: ['ignore', 'pipe', 'pipe'],
@@ -67,7 +74,12 @@ export async function startRisdProcess({ home = makeHome(), port = 0, env = {} }
67
74
  const deadline = Date.now() + 10_000
68
75
  while (Date.now() < deadline) {
69
76
  const state = readRisdState(home)
70
- if (state !== null) {
77
+ // A handoff deliberately leaves the PREDECESSOR's note in place (same home,
78
+ // same port, its token) until the successor rewrites it. Returning that note
79
+ // hands the caller a dead daemon's token: health may answer (it is
80
+ // unauthenticated) while every authenticated route replies 401 — a flake that
81
+ // only shows up when the successor is slow to write its own note.
82
+ if (state !== null && Number(state.pid) === child.pid) {
71
83
  const probe = await health(state.port)
72
84
  if (probe?.ok === true) {
73
85
  return { child, home, state, lines, stop: () => stopRisdProcess(child) }
@@ -106,3 +118,138 @@ export function runRisdCli(args, { env = {} } = {}) {
106
118
  }
107
119
 
108
120
  export { health }
121
+
122
+ // ---------------------------------------------------------------------------
123
+ // Engine fixtures (risd-engine / risd-handoff / risd-teardown had three copies).
124
+ // ---------------------------------------------------------------------------
125
+
126
+ /** A random high port, so parallel test files do not fight over the engine fixtures. */
127
+ export function pickPort() {
128
+ return 20000 + Math.floor(Math.random() * 20000)
129
+ }
130
+
131
+ /**
132
+ * Write the machine-level `proxy.json` an engine test starts from: one enabled java
133
+ * rule and a dead SOCKS upstream. `workspace` is the row's owner (default: the home).
134
+ */
135
+ export function writeEngineFixture(home, port, { workspace = home } = {}) {
136
+ writeFileSync(join(home, 'proxy.json'), JSON.stringify({
137
+ socks: { host: '127.0.0.1', port: 1, dbPort: 0, redisPort: 0 },
138
+ listenPort: port,
139
+ rules: [{
140
+ id: 'rule-1',
141
+ program: 'java',
142
+ hosts: ['127.0.0.1'],
143
+ ports: ['443'],
144
+ enabled: true,
145
+ shadow: false,
146
+ source: 'user',
147
+ workspace,
148
+ }],
149
+ }, null, 2))
150
+ }
151
+
152
+ /** Authorization headers for a daemon started by `startRisdProcess`. */
153
+ export function risdHeaders(state) {
154
+ return { authorization: `Bearer ${state.token}`, 'x-risd-api-version': String(RISD_API_VERSION), 'content-type': 'application/json' }
155
+ }
156
+
157
+ /**
158
+ * Poll `fn` until it returns true. 15 s by default: a teardown is 300 ms debounce +
159
+ * the engine's 5 s grace + bridge/git attempts, which exceeds 8 s on a loaded machine.
160
+ */
161
+ export async function waitFor(fn, timeoutMs = 15000, stepMs = 120) {
162
+ const deadline = Date.now() + timeoutMs
163
+ while (Date.now() < deadline) {
164
+ if (await fn()) return true
165
+ await sleep(stepMs)
166
+ }
167
+ return false
168
+ }
169
+
170
+ /** `kill(0)`: is the process still there? */
171
+ export function pidAlive(pid) {
172
+ if (!Number.isInteger(pid) || pid <= 0) return false
173
+ try {
174
+ process.kill(pid, 0)
175
+ return true
176
+ } catch {
177
+ return false
178
+ }
179
+ }
180
+
181
+ // ---------------------------------------------------------------------------
182
+ // Fake bridge (risd-bridge-degrade / risd-host-p2 had two copies).
183
+ // ---------------------------------------------------------------------------
184
+
185
+ /** Minimal `ServerResponse` stand-in for the `serveProxy`/`serveProxyAction` tests. */
186
+ export function fakeRes() {
187
+ return {
188
+ status: 0,
189
+ chunks: [],
190
+ writeHead(status) { this.status = status },
191
+ write(chunk) { this.chunks.push(String(chunk)); return true },
192
+ end(chunk) { if (chunk !== undefined) this.chunks.push(String(chunk)) },
193
+ json() { return JSON.parse(this.chunks.join('')) },
194
+ }
195
+ }
196
+
197
+ /** Minimal `IncomingMessage` (a Readable) for the same tests. */
198
+ export function fakeReq(method, url, body) {
199
+ const chunks = body === undefined ? [] : [Buffer.from(JSON.stringify(body))]
200
+ const req = Readable.from(chunks)
201
+ req.method = method
202
+ req.url = url
203
+ req.headers = { host: '127.0.0.1:3080', 'content-type': 'application/json' }
204
+ return req
205
+ }
206
+
207
+ /**
208
+ * The in-memory bridge `lib/index.js` hands to `__test.setRisdBridge`; `url: null`
209
+ * means "the pointer was already dropped" (degraded, no daemon).
210
+ */
211
+ export function risdBridge({ url = null, port = 9, token = 'token-x', leaseId = 'lease-x', degraded = false, warnedAt = 0, lastProbeAt = Date.now() } = {}) {
212
+ return {
213
+ mode: 'auto',
214
+ state: url === null ? null : { url, token, apiVersion: RISD_API_VERSION, port },
215
+ leaseId,
216
+ pending: null,
217
+ warnedAt,
218
+ degraded,
219
+ lastProbeAt,
220
+ }
221
+ }
222
+
223
+ // ---------------------------------------------------------------------------
224
+ // JSON client (risd-programs / risd-shutdown had two copies of `api`).
225
+ // ---------------------------------------------------------------------------
226
+
227
+ /** One JSON request against a running daemon; transport errors land as `{status: 0}`. */
228
+ export function api(state, path, { method = 'GET', body } = {}) {
229
+ return new Promise((resolve) => {
230
+ const payload = body === undefined ? '' : JSON.stringify(body)
231
+ const req = request({
232
+ host: '127.0.0.1',
233
+ port: state.port,
234
+ path,
235
+ method,
236
+ timeout: 8000,
237
+ headers: Object.assign(
238
+ { authorization: `Bearer ${state.token}`, 'x-risd-api-version': '1' },
239
+ payload === '' ? {} : { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) },
240
+ ),
241
+ }, (res) => {
242
+ let text = ''
243
+ res.setEncoding('utf8')
244
+ res.on('data', (chunk) => { text += chunk })
245
+ res.on('end', () => {
246
+ let parsed = null
247
+ try { parsed = JSON.parse(text) } catch { parsed = null }
248
+ resolve({ status: res.statusCode, body: parsed })
249
+ })
250
+ })
251
+ req.on('error', (error) => resolve({ status: 0, body: { error: String(error?.message) } }))
252
+ if (payload !== '') req.write(payload)
253
+ req.end()
254
+ })
255
+ }
@@ -12,8 +12,8 @@ import { createServer } from 'node:http'
12
12
  import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
13
13
  import { tmpdir } from 'node:os'
14
14
  import { join } from 'node:path'
15
- import { Readable } from 'node:stream'
16
15
  import test from 'node:test'
16
+ import { fakeReq, fakeRes, risdBridge } from './risd-helpers.mjs'
17
17
 
18
18
  const home = mkdtempSync(join(tmpdir(), 'risd-host-p2-'))
19
19
  const workspace = mkdtempSync(join(tmpdir(), 'risd-host-p2-ws-'))
@@ -22,26 +22,6 @@ process.env.DSH_RIS_IDE_PROXY_HOME = home
22
22
  const { __test } = await import('../lib/index.js')
23
23
  const { RISD_API_VERSION } = await import('../lib/risd/state.js')
24
24
 
25
- function fakeRes() {
26
- return {
27
- status: 0,
28
- chunks: [],
29
- writeHead(status) { this.status = status },
30
- write(chunk) { this.chunks.push(String(chunk)); return true },
31
- end(chunk) { if (chunk !== undefined) this.chunks.push(String(chunk)) },
32
- json() { return JSON.parse(this.chunks.join('')) },
33
- }
34
- }
35
-
36
- function fakeReq(method, url, body) {
37
- const chunks = body === undefined ? [] : [Buffer.from(JSON.stringify(body))]
38
- const req = Readable.from(chunks)
39
- req.method = method
40
- req.url = url
41
- req.headers = { host: '127.0.0.1:3080', 'content-type': 'application/json' }
42
- return req
43
- }
44
-
45
25
  /** A fake daemon that answers /v1/health and hands every other request to `reply`. */
46
26
  async function fakeDaemon(reply) {
47
27
  const server = createServer((req, res) => {
@@ -69,15 +49,7 @@ async function stopServer(server) {
69
49
  }
70
50
 
71
51
  function setBridge(url, port) {
72
- __test.setRisdBridge({
73
- mode: 'auto',
74
- state: { url, token: 'token-x', apiVersion: RISD_API_VERSION, port },
75
- leaseId: 'lease-x',
76
- pending: null,
77
- warnedAt: 0,
78
- degraded: false,
79
- lastProbeAt: Date.now(),
80
- })
52
+ __test.setRisdBridge(risdBridge({ url, port }))
81
53
  }
82
54
 
83
55
  const ctx = { sessions: { get: () => ({ header: { cwd: workspace } }) } }
@@ -25,6 +25,31 @@ test('defaults match the behaviour from before the setting existed', () => {
25
25
  assert.equal(value.proxy.followDsh, true)
26
26
  assert.equal(value.programs.followDsh, false, 'closing the last dsh must not stop JVMs by default')
27
27
  assert.equal(value.debug.followDsh, false)
28
+ assert.equal(value.proxy.followDsh, true, 'the proxy follows dsh out of the box')
29
+ })
30
+
31
+ test('start and stop read the same followDsh knob, and typos are rejected', () => {
32
+ assert.equal(LIFECYCLE_DEFAULTS.proxy.followDsh, true, 'the proxy follows dsh by default')
33
+
34
+ const off = normalizeLifecycle({ proxy: { followDsh: false } })
35
+ assert.deepEqual(off.errors, [])
36
+ assert.equal(off.value.proxy.followDsh, false)
37
+ assert.equal('startWithDsh' in off.value.proxy, false, 'there is no second auto-start switch (m13950)')
38
+
39
+ // The old separate knob is a typo now, not a silently saved setting.
40
+ const unknown = normalizeLifecycle({ proxy: { startWithDsh: true } })
41
+ assert.equal(unknown.changed, false)
42
+ assert.match(unknown.errors.join(';'), /proxy\.startWithDsh 不是可配置项(只能配置 followDsh)/)
43
+
44
+ const bad = normalizeLifecycle({ proxy: { followDsh: 'yes' } })
45
+ assert.equal(bad.changed, false)
46
+ assert.match(bad.errors.join(';'), /proxy\.followDsh 必须是 true\/false/)
47
+
48
+ // A partial save over what is in force keeps the value.
49
+ const current = normalizeLifecycle({ proxy: { followDsh: false } }).value
50
+ const merged = normalizeLifecycle(mergeLifecycle(current, { programs: { followDsh: true } })).value
51
+ assert.equal(merged.proxy.followDsh, false)
52
+ assert.equal(merged.programs.followDsh, true)
28
53
  })
29
54
 
30
55
  test('partial input keeps the untouched defaults and rejects non-booleans', () => {
@@ -3,45 +3,15 @@
3
3
  // started here keeps running after dsh exits and is visible from another dsh.
4
4
  import assert from 'node:assert/strict'
5
5
  import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync, rmSync } from 'node:fs'
6
- import { request } from 'node:http'
7
6
  import { tmpdir } from 'node:os'
8
7
  import { join } from 'node:path'
9
8
  import { after, before, test } from 'node:test'
10
- import { sleep } from './risd-helpers.mjs'
11
- import { startRisdProcess } from './risd-helpers.mjs'
9
+ import { api, sleep, startRisdProcess } from './risd-helpers.mjs'
10
+ import { HAS_BASH, skipWithout } from './helpers/cmd.mjs'
12
11
 
13
12
  let daemon
14
13
  let workspace
15
14
 
16
- function api(state, path, { method = 'GET', body } = {}) {
17
- return new Promise((resolve) => {
18
- const payload = body === undefined ? '' : JSON.stringify(body)
19
- const req = request({
20
- host: '127.0.0.1',
21
- port: state.port,
22
- path,
23
- method,
24
- timeout: 8000,
25
- headers: Object.assign(
26
- { authorization: `Bearer ${state.token}`, 'x-risd-api-version': '1' },
27
- payload === '' ? {} : { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) },
28
- ),
29
- }, (res) => {
30
- let text = ''
31
- res.setEncoding('utf8')
32
- res.on('data', (chunk) => { text += chunk })
33
- res.on('end', () => {
34
- let parsed = null
35
- try { parsed = JSON.parse(text) } catch { parsed = null }
36
- resolve({ status: res.statusCode, body: parsed })
37
- })
38
- })
39
- req.on('error', (error) => resolve({ status: 0, body: { error: String(error?.message) } }))
40
- if (payload !== '') req.write(payload)
41
- req.end()
42
- })
43
- }
44
-
45
15
  before(async () => {
46
16
  workspace = mkdtempSync(join(tmpdir(), 'risd-programs-ws-'))
47
17
  mkdirSync(join(workspace, '.dsh-ris-ide'), { recursive: true })
@@ -80,7 +50,7 @@ test('GET /v1/programs lists the panel rows from the daemon', async () => {
80
50
  assert.equal(res.body.dir, join(workspace, 'logs'))
81
51
  })
82
52
 
83
- test('start, stop and restart a program from the daemon', async () => {
53
+ test('start, stop and restart a program from the daemon', { skip: skipWithout(HAS_BASH, 'bash') }, async () => {
84
54
  const started = await api(daemon.state, '/v1/programs', { method: 'POST', body: { cwd: workspace, action: 'start', id: 'demo' } })
85
55
  assert.equal(started.status, 200)
86
56
  assert.equal(started.body.ok, true)
@@ -121,7 +91,7 @@ test('log reads page by byte offset for a follower', async () => {
121
91
  assert.ok(follow.body.nextOffset > offset)
122
92
  })
123
93
 
124
- test('an unknown program is a 404 with a readable message', async () => {
94
+ test('an unknown program is a 404 with a readable message', { skip: skipWithout(HAS_BASH, 'bash') }, async () => {
125
95
  const res = await api(daemon.state, '/v1/programs', { method: 'POST', body: { cwd: workspace, action: 'start', id: 'nope' } })
126
96
  assert.equal(res.status, 404)
127
97
  assert.equal(res.body.ok, false)
@@ -82,19 +82,6 @@ test('an oversized body gets a 413 answer instead of a broken socket (A-P2-6)',
82
82
  }
83
83
  })
84
84
 
85
- test('/v1/config reports real values only (A-P2-3)', async () => {
86
- const started = await startRisdProcess({ home: home() })
87
- try {
88
- const response = await httpJson(started.state.port, '/v1/config', { token: started.state.token })
89
- assert.equal(response.status, 200)
90
- assert.equal(response.body.idleExitMs, 10 * 60 * 1000)
91
- assert.equal(response.body.engineRestart, undefined)
92
- assert.ok(response.body.lifecycle)
93
- } finally {
94
- await started.stop()
95
- }
96
- })
97
-
98
85
  test('/v1/dsh ignores windows whose url is not a loopback http(s) origin (A-P2-10)', async () => {
99
86
  const dir = home()
100
87
  const started = await startRisdProcess({ home: dir })
@@ -6,48 +6,15 @@
6
6
  // by risd-handoff.test.mjs — it must keep them alive.
7
7
  import assert from 'node:assert/strict'
8
8
  import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
9
- import { request } from 'node:http'
10
9
  import { tmpdir } from 'node:os'
11
10
  import { join } from 'node:path'
12
11
  import { after, before, test } from 'node:test'
13
- import { sleep, startRisdProcess } from './risd-helpers.mjs'
12
+ import { api, pidAlive, sleep, startRisdProcess } from './risd-helpers.mjs'
13
+ import { HAS_BASH, skipWithout } from './helpers/cmd.mjs'
14
14
 
15
15
  let daemon
16
16
  let workspace
17
17
 
18
- function api(state, path, { method = 'GET', body } = {}) {
19
- return new Promise((resolve) => {
20
- const payload = body === undefined ? '' : JSON.stringify(body)
21
- const req = request({
22
- host: '127.0.0.1',
23
- port: state.port,
24
- path,
25
- method,
26
- timeout: 8000,
27
- headers: Object.assign(
28
- { authorization: `Bearer ${state.token}`, 'x-risd-api-version': '1' },
29
- payload === '' ? {} : { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) },
30
- ),
31
- }, (res) => {
32
- let text = ''
33
- res.setEncoding('utf8')
34
- res.on('data', (chunk) => { text += chunk })
35
- res.on('end', () => {
36
- let parsed = null
37
- try { parsed = JSON.parse(text) } catch { parsed = null }
38
- resolve({ status: res.statusCode, body: parsed })
39
- })
40
- })
41
- req.on('error', (error) => resolve({ status: 0, body: { error: String(error?.message) } }))
42
- if (payload !== '') req.write(payload)
43
- req.end()
44
- })
45
- }
46
-
47
- function alive(pid) {
48
- try { process.kill(pid, 0); return true } catch { return false }
49
- }
50
-
51
18
  before(async () => {
52
19
  workspace = mkdtempSync(join(tmpdir(), 'risd-shutdown-ws-'))
53
20
  mkdirSync(join(workspace, '.dsh-ris-ide'), { recursive: true })
@@ -74,7 +41,7 @@ after(async () => {
74
41
  if (workspace !== undefined) rmSync(workspace, { recursive: true, force: true })
75
42
  })
76
43
 
77
- test('shutdown stops the programs it supervises before exiting', async () => {
44
+ test('shutdown stops the programs it supervises before exiting', { skip: skipWithout(HAS_BASH, 'bash') }, async () => {
78
45
  const started = await api(daemon.state, '/v1/programs', {
79
46
  method: 'POST',
80
47
  body: { cwd: workspace, action: 'start', id: 'demo' },
@@ -82,7 +49,7 @@ test('shutdown stops the programs it supervises before exiting', async () => {
82
49
  assert.equal(started.status, 200, JSON.stringify(started.body))
83
50
  const pid = started.body.pid
84
51
  assert.ok(Number.isInteger(pid) && pid > 0, 'the start result carries the wrapper pid')
85
- assert.equal(alive(pid), true, 'the program is running')
52
+ assert.equal(pidAlive(pid), true, 'the program is running')
86
53
 
87
54
  const shutdown = await api(daemon.state, '/v1/shutdown', { method: 'POST', body: { reason: 'test' } })
88
55
  assert.equal(shutdown.status, 200)
@@ -90,7 +57,7 @@ test('shutdown stops the programs it supervises before exiting', async () => {
90
57
  // Give the wrapper's TERM grace a moment, then require the process to be gone.
91
58
  let gone = false
92
59
  for (let attempt = 0; attempt < 60; attempt += 1) {
93
- if (!alive(pid)) { gone = true; break }
60
+ if (!pidAlive(pid)) { gone = true; break }
94
61
  await sleep(200)
95
62
  }
96
63
  assert.equal(gone, true, 'stopping the daemon must not leave the program behind')