dsh-ris-ide 1.8.1 → 1.8.3

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 (50) hide show
  1. package/README.md +2 -2
  2. package/lib/client.js +569 -98
  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 +963 -64
  7. package/lib/redirector.js +76 -4
  8. package/lib/risd/lifecycle.js +54 -10
  9. package/lib/risd/ping.js +136 -17
  10. package/lib/risd/server.js +424 -22
  11. package/lib/risd/ui.js +218 -129
  12. package/lib/risd-client.js +4 -1
  13. package/lib/startup.js +27 -7
  14. package/package.json +2 -2
  15. package/test/client-viewer.test.mjs +268 -93
  16. package/test/clipboard.test.mjs +259 -0
  17. package/test/debug-engine.test.mjs +3 -1
  18. package/test/dsh-origin.test.mjs +4 -11
  19. package/test/dsh-window-refresh.test.mjs +166 -1
  20. package/test/harness.test.mjs +1 -1
  21. package/test/helpers/cmd.mjs +29 -0
  22. package/test/helpers/tgz.mjs +71 -0
  23. package/test/host-search.test.mjs +18 -11
  24. package/test/host-tail.test.mjs +190 -25
  25. package/test/proxy-route.test.mjs +61 -0
  26. package/test/proxy-window.test.mjs +5 -0
  27. package/test/proxy.test.mjs +40 -11
  28. package/test/proxybridge-bundle.test.mjs +1 -59
  29. package/test/redirector-bundle.test.mjs +21 -67
  30. package/test/redirector.test.mjs +71 -4
  31. package/test/risd-api.test.mjs +83 -29
  32. package/test/risd-bridge-degrade.test.mjs +3 -29
  33. package/test/risd-cli-home.test.mjs +41 -4
  34. package/test/risd-engine.test.mjs +13 -50
  35. package/test/risd-entry.test.mjs +0 -37
  36. package/test/risd-follow-start.test.mjs +102 -0
  37. package/test/risd-git.test.mjs +7 -5
  38. package/test/risd-handoff.test.mjs +6 -50
  39. package/test/risd-helpers.mjs +150 -3
  40. package/test/risd-host-p2.test.mjs +2 -30
  41. package/test/risd-lifecycle.test.mjs +203 -33
  42. package/test/risd-ping.test.mjs +77 -1
  43. package/test/risd-programs.test.mjs +4 -34
  44. package/test/risd-review-p2.test.mjs +0 -13
  45. package/test/risd-shutdown.test.mjs +5 -38
  46. package/test/risd-teardown.test.mjs +8 -27
  47. package/test/risd-ui.test.mjs +205 -14
  48. package/test/risd-write.test.mjs +2 -1
  49. package/test/startup-reconcile.test.mjs +44 -8
  50. package/test/proxy-restart.test.mjs +0 -39
@@ -622,26 +622,43 @@ test('SOCKS5: a split domain reply is never accepted before it is complete', asy
622
622
  Buffer.from([0x00, 80]),
623
623
  ])
624
624
  let fragmentSent = false
625
+ // Read the promise state at the exact instant the tail is written: four bytes
626
+ // are a header fragment, not a reply. The old `length < 4` guard (and the NaN
627
+ // successor that replaced it) resolved right there and leaked the remaining
628
+ // handshake bytes into the tunnel as garbage.
629
+ //
630
+ // Deliberately NOT a sleep-then-assert: that version compared the state 25 ms
631
+ // after the fragment against a timer writing the tail 80 ms later, so on a
632
+ // throttled CI pod the loop stalled past both deadlines and the tail landed
633
+ // before the assertion — it reported `resolved` where it expected `pending`
634
+ // (m05789) with a correct parser, because the check raced the very delay it
635
+ // relied on. Reading the state inside the timer callback cannot race: microtasks
636
+ // drain before the next timer, so a settlement caused by the fragment (or by
637
+ // anything else that already arrived) has run by the time this line executes.
638
+ let whenTailSent = null
639
+ let settledWith = 'pending'
625
640
  const socks = await scriptedSocks((client) => {
626
641
  socksHandshake(client, () => {
627
642
  client.write(reply.subarray(0, 4))
628
643
  fragmentSent = true
629
- setTimeout(() => client.write(reply.subarray(4)), 80)
644
+ setTimeout(() => {
645
+ whenTailSent = settledWith
646
+ if (!client.destroyed) client.write(reply.subarray(4))
647
+ }, 80)
630
648
  })
631
649
  })
632
650
  let upstream = null
633
651
  try {
634
- let settledWith = 'pending'
635
652
  const pending = connectSocks({ host: '127.0.0.1', port: socks.port }, 'example.com', 80)
636
653
  pending.then((socket) => { upstream = socket; settledWith = 'resolved' }, () => { settledWith = 'rejected' })
637
- for (let attempt = 0; attempt < 100 && fragmentSent !== true; attempt += 1) await sleep(5)
638
- await sleep(25)
639
- // Four bytes are a header fragment, not a reply. The old `length < 4` guard
640
- // (and the NaN successor that replaced it) resolved right here and leaked
641
- // the remaining handshake bytes into the tunnel as garbage.
642
- assert.equal(settledWith, 'pending')
643
- await pending
644
- assert.equal(settledWith, 'resolved')
654
+ for (let attempt = 0; attempt < 200 && fragmentSent !== true; attempt += 1) await sleep(5)
655
+ assert.equal(fragmentSent, true, 'the scripted server never saw the CONNECT request')
656
+ const settled = await Promise.race([
657
+ pending.then(() => 'resolved', () => 'rejected'),
658
+ sleep(2000).then(() => 'timed-out'),
659
+ ])
660
+ assert.equal(whenTailSent, 'pending', 'the four-byte fragment must not settle the promise')
661
+ assert.equal(settled, 'resolved')
645
662
  } finally {
646
663
  upstream?.destroy()
647
664
  await socks.close()
@@ -828,7 +845,12 @@ test('engine pid: a dead pidfile is cleared', () => {
828
845
  test('engine pid: a marker-carrying process is reused and stoppable', async () => {
829
846
  const dir = mkdtempSync(join(tmpdir(), 'ris-ide-pid-'))
830
847
  mkdirSync(proxyHomeDir(), { recursive: true })
831
- const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 60000)', `--marker=${PROXY_MARKER}`], { stdio: 'ignore' })
848
+ // `node -e CODE --marker=X` is read as a NODE OPTION, not as a script argument:
849
+ // node prints "bad option: --marker=…" and exits immediately, so the child was
850
+ // only sometimes seen alive in /proc (this test failed ~half the time on CI while
851
+ // passing locally). `--` ends option parsing, so the marker reaches the child's
852
+ // argv — and the child stays alive for the 60 s of its setTimeout.
853
+ const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 60000)', '--', `--marker=${PROXY_MARKER}`], { stdio: 'ignore' })
832
854
  let exited = false
833
855
  child.once('exit', () => { exited = true })
834
856
  try {
@@ -840,6 +862,10 @@ test('engine pid: a marker-carrying process is reused and stoppable', async () =
840
862
  assert.equal(ready, true, 'the test child must look like the engine (marker in argv)')
841
863
  writeFileSync(proxyPidPath(), String(child.pid))
842
864
  assert.equal(proxyPid(dir), child.pid)
865
+ // Re-check right before the reuse call: if the child died in between, `startProxy`
866
+ // would see a stale/absent pidfile and try to spawn a REAL engine — leaving it
867
+ // running and binding the loopback ports after the test (that is what hung CI).
868
+ assert.equal(pidIsProxy(child.pid), true, 'the test child must still be alive before the reuse check')
843
869
  const started = await startProxy(dir, { config: normalizeConfig({}) })
844
870
  assert.equal(started.alreadyRunning, true)
845
871
  assert.equal(started.pid, child.pid)
@@ -847,6 +873,9 @@ test('engine pid: a marker-carrying process is reused and stoppable', async () =
847
873
  for (let attempt = 0; attempt < 100 && exited !== true; attempt += 1) await sleep(20)
848
874
  assert.equal(exited, true)
849
875
  } finally {
876
+ // If the reuse path was missed, `startProxy` may have spawned a real engine and
877
+ // left it owning 127.0.0.1:11081 — kill whatever the pidfile names, then the child.
878
+ try { await stopProxy(dir, { graceMs: 3000 }) } catch { /* nothing to stop */ }
850
879
  try { child.kill('SIGKILL') } catch { /* already gone */ }
851
880
  rmSync(proxyPidPath(), { force: true })
852
881
  rmSync(dir, { recursive: true, force: true })
@@ -22,8 +22,8 @@ import {
22
22
  import { tmpdir } from 'node:os'
23
23
  import { dirname, join } from 'node:path'
24
24
  import test from 'node:test'
25
- import { gzipSync } from 'node:zlib'
26
25
 
26
+ import { fileContent, fetchServing, makeTgz } from './helpers/tgz.mjs'
27
27
  import {
28
28
  BUNDLE_SHA256,
29
29
  BUNDLE_URLS,
@@ -56,47 +56,8 @@ const LAYOUT = [
56
56
  'windows/WinDivert64.sys',
57
57
  ]
58
58
 
59
- const fileContent = (rel) => `fixture bytes for ${rel}\n`
60
59
  const shaOf = (bytes) => createHash('sha256').update(bytes).digest('hex')
61
60
 
62
- /** Octal field: width-1 digits + NUL, as ustar spells numbers. */
63
- const octalField = (value, width) => `${value.toString(8).padStart(width - 1, '0')}\0`
64
-
65
- function tarHeader(name, size, { mode = 0o644, type = '0', linkname = '' } = {}) {
66
- const header = Buffer.alloc(512, 0)
67
- const encoded = Buffer.from(name, 'utf8')
68
- assert.ok(encoded.length <= 100, `fixture name too long: ${name}`)
69
- encoded.copy(header, 0)
70
- header.write(octalField(mode, 8), 100, 'ascii')
71
- header.write(octalField(0, 8), 108, 'ascii') // uid
72
- header.write(octalField(0, 8), 116, 'ascii') // gid
73
- header.write(octalField(size, 12), 124, 'ascii')
74
- header.write(octalField(0, 12), 136, 'ascii') // mtime
75
- header.write(' ', 148, 'ascii') // checksum placeholder
76
- header.write(type, 156, 'ascii')
77
- header.write(linkname < 101 ? linkname : linkname.slice(0, 100), 157, 'ascii')
78
- header.write('ustar\0', 257, 'ascii')
79
- header.write('00', 263, 'ascii')
80
- let sum = 0
81
- for (const byte of header) sum += byte
82
- header.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 'ascii')
83
- return header
84
- }
85
-
86
- /** Build a real `.tgz` from `{name, content?, mode?, type?, linkname?}` entries. */
87
- function makeTgz(entries, { prefix = '' } = {}) {
88
- const chunks = []
89
- for (const entry of entries) {
90
- const content = Buffer.from(entry.content ?? fileContent(entry.name))
91
- chunks.push(tarHeader(`${prefix}${entry.name}`, content.length, entry))
92
- chunks.push(content)
93
- const pad = (512 - (content.length % 512)) % 512
94
- if (pad > 0) chunks.push(Buffer.alloc(pad))
95
- }
96
- chunks.push(Buffer.alloc(1024)) // end-of-archive: two zero blocks
97
- return gzipSync(Buffer.concat(chunks))
98
- }
99
-
100
61
  const bundleTgz = (extra = []) => makeTgz([
101
62
  ...LAYOUT.map((rel) => ({
102
63
  name: rel,
@@ -106,25 +67,6 @@ const bundleTgz = (extra = []) => makeTgz([
106
67
  ...extra,
107
68
  ])
108
69
 
109
- /**
110
- * `fetch` stand-in serving one body; `calls` counts invocations.
111
- * `url` mimics `Response.url` after redirects; `headers` mimics the header bag.
112
- */
113
- function fetchServing(body, options = {}) {
114
- const calls = { count: 0 }
115
- const impl = async (requested) => {
116
- calls.count += 1
117
- return {
118
- ok: true,
119
- status: 200,
120
- url: options.url ?? requested,
121
- headers: options.headers ?? { get: () => null },
122
- arrayBuffer: async () => body.buffer.slice(body.byteOffset, body.byteOffset + body.length),
123
- }
124
- }
125
- return { impl, calls }
126
- }
127
-
128
70
  function tempHome() {
129
71
  return mkdtempSync(join(tmpdir(), 'ris-ide-bundle-home-'))
130
72
  }
@@ -14,8 +14,8 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync,
14
14
  import { tmpdir } from 'node:os'
15
15
  import { join } from 'node:path'
16
16
  import test from 'node:test'
17
- import { gzipSync } from 'node:zlib'
18
17
 
18
+ import { fileContent, fetchServing, makeTgz } from './helpers/tgz.mjs'
19
19
  import { DEFAULT_BUNDLE_URL, bundleLayout, installDir, installFromTgz, isInstalled } from '../lib/proxybridge-bundle.js'
20
20
 
21
21
  const home = mkdtempSync(join(tmpdir(), 'ris-redirector-home-'))
@@ -36,42 +36,6 @@ const {
36
36
  const BUNDLE = bundleLayout()
37
37
  const WINDOWS_FILES = ['ProxyBridge_CLI.exe', 'ProxyBridgeCore.dll', 'WinDivert.dll', 'WinDivert64.sys']
38
38
  const LICENCES = ['NOTICE.md', 'LICENSE-ProxyBridge.txt']
39
- const fileContent = (rel) => `fixture bytes for ${rel}\n`
40
-
41
- /** Octal field: width-1 digits + NUL, as ustar spells numbers. */
42
- const octalField = (value, width) => `${value.toString(8).padStart(width - 1, '0')}\0`
43
-
44
- function tarHeader(name, size, { mode = 0o644 } = {}) {
45
- const header = Buffer.alloc(512, 0)
46
- Buffer.from(name, 'utf8').copy(header, 0)
47
- header.write(octalField(mode, 8), 100, 'ascii')
48
- header.write(octalField(0, 8), 108, 'ascii')
49
- header.write(octalField(0, 8), 116, 'ascii')
50
- header.write(octalField(size, 12), 124, 'ascii')
51
- header.write(octalField(0, 12), 136, 'ascii')
52
- header.write(' ', 148, 'ascii')
53
- header.write('0', 156, 'ascii')
54
- header.write('ustar\0', 257, 'ascii')
55
- header.write('00', 263, 'ascii')
56
- let sum = 0
57
- for (const byte of header) sum += byte
58
- header.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 'ascii')
59
- return header
60
- }
61
-
62
- /** Build a real `.tgz` from `{name, content, mode}` entries. */
63
- function makeTgz(entries) {
64
- const chunks = []
65
- for (const entry of entries) {
66
- const content = Buffer.from(entry.content)
67
- chunks.push(tarHeader(entry.name, content.length, entry))
68
- chunks.push(content)
69
- const pad = (512 - (content.length % 512)) % 512
70
- if (pad > 0) chunks.push(Buffer.alloc(pad))
71
- }
72
- chunks.push(Buffer.alloc(1024))
73
- return gzipSync(Buffer.concat(chunks))
74
- }
75
39
 
76
40
  const bundleTgz = () => makeTgz(BUNDLE.map((rel) => ({
77
41
  name: rel,
@@ -79,20 +43,6 @@ const bundleTgz = () => makeTgz(BUNDLE.map((rel) => ({
79
43
  mode: /\.(exe|dll|sys|so)$|ProxyBridge$/.test(rel) === true ? 0o755 : 0o644,
80
44
  })))
81
45
 
82
- /** `fetch` stand-in serving one body; records every URL it was asked for. */
83
- function fetchServing(body) {
84
- const calls = { urls: [] }
85
- const impl = async (url) => {
86
- calls.urls.push(String(url))
87
- return {
88
- ok: true,
89
- status: 200,
90
- arrayBuffer: async () => body.buffer.slice(body.byteOffset, body.byteOffset + body.length),
91
- }
92
- }
93
- return { impl, calls }
94
- }
95
-
96
46
  const installFixture = () => {
97
47
  // A fresh machine starts with no cache; every test proves its own precondition.
98
48
  rmSync(join(home, 'proxybridge'), { recursive: true, force: true })
@@ -277,7 +227,11 @@ test('a failed materialisation is not cached: the next call retries', () => {
277
227
  }
278
228
  })
279
229
 
280
- test('ensureBundleReady downloads into the proxy home and reuses the cache', async () => {
230
+ test('ensureBundleReady is a thin wrapper over the bundle install', async () => {
231
+ // The download/cache/failure semantics themselves are covered by the bundle
232
+ // module tests; here we pin only what this wrapper owns: it downloads into the
233
+ // machine-level proxy home, forwards the machine settings, maps the outcome for
234
+ // the dialog (fromCache/url/error/hint) and never throws.
281
235
  rmSync(join(home, 'proxybridge'), { recursive: true, force: true })
282
236
  __test.clearProbeCaches()
283
237
  delete process.env.DSH_RIS_IDE_PROXYBRIDGE_URL
@@ -285,38 +239,38 @@ test('ensureBundleReady downloads into the proxy home and reuses the cache', asy
285
239
  const first = await ensureBundleReady({ fetchImpl: impl })
286
240
  assert.equal(first.ok, true)
287
241
  assert.equal(first.fromCache, false)
288
- assert.equal(first.dir, installDir(home))
242
+ assert.equal(first.dir, installDir(home), 'the download lands in proxyHomeDir(), not a caller path')
289
243
  assert.equal(first.url, DEFAULT_BUNDLE_URL)
290
244
  assert.equal(isInstalled(installDir(home)), true)
291
245
  const second = await ensureBundleReady({ fetchImpl: impl })
292
246
  assert.equal(second.ok, true)
293
247
  assert.equal(second.fromCache, true, 'the cache must be reused without another request')
248
+ assert.equal(second.dir, first.dir)
294
249
  assert.equal(calls.urls.length, 1)
295
- })
296
250
 
297
- test('ensureBundleReady never throws on a download failure', async () => {
251
+ // A failed download is a value, not a throw, and the wrapper passes the bundle
252
+ // error/hint through to the dialog.
298
253
  rmSync(join(home, 'proxybridge'), { recursive: true, force: true })
299
254
  __test.clearProbeCaches()
300
255
  const failing = async () => ({ ok: false, status: 502, arrayBuffer: async () => new ArrayBuffer(0) })
301
- const result = await ensureBundleReady({ fetchImpl: failing })
302
- assert.equal(result.ok, false)
303
- assert.match(String(result.error), /HTTP 502/)
304
- assert.match(String(result.hint), /检查网络/)
305
- })
306
-
307
- test('the env override beats settings for ensureBundleReady (one resolver, same as the daemon)', async () => {
256
+ const failed = await ensureBundleReady({ fetchImpl: failing })
257
+ assert.equal(failed.ok, false)
258
+ assert.match(String(failed.error), /HTTP 502/)
259
+ assert.match(String(failed.hint), /检查网络/)
260
+
261
+ // The wrapper reads settings.json and forwards it, but URL resolution lives only
262
+ // in `resolveBundleUrls` (env → settings → mirrors), so redirector-side and
263
+ // daemon-side installs agree (review A3-P2-1).
308
264
  rmSync(join(home, 'proxybridge'), { recursive: true, force: true })
309
265
  __test.clearProbeCaches()
310
266
  const settingsPath = join(home, 'settings.json')
311
267
  writeFileSync(settingsPath, JSON.stringify({ proxybridgeUrl: 'https://mirror.example/ris-proxy.tgz' }))
312
268
  process.env.DSH_RIS_IDE_PROXYBRIDGE_URL = 'https://env.example/ris-proxy.tgz'
313
- const { impl, calls } = fetchServing(bundleTgz())
269
+ const envFetch = fetchServing(bundleTgz())
314
270
  try {
315
- const result = await ensureBundleReady({ fetchImpl: impl })
271
+ const result = await ensureBundleReady({ fetchImpl: envFetch.impl })
316
272
  assert.equal(result.ok, true)
317
- // URL resolution lives only in `resolveBundleUrls` (env → settings → mirrors),
318
- // so redirector-side and daemon-side installs agree (review A3-P2-1).
319
- assert.deepEqual(calls.urls, ['https://env.example/ris-proxy.tgz'])
273
+ assert.deepEqual(envFetch.calls.urls, ['https://env.example/ris-proxy.tgz'])
320
274
  } finally {
321
275
  delete process.env.DSH_RIS_IDE_PROXYBRIDGE_URL
322
276
  rmSync(settingsPath, { force: true })
@@ -10,13 +10,43 @@ import assert from 'node:assert/strict'
10
10
  import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, mkdirSync } from 'node:fs'
11
11
  import { tmpdir } from 'node:os'
12
12
  import { join } from 'node:path'
13
- import test from 'node:test'
13
+ import test, { after } from 'node:test'
14
+
15
+ import { engineSide } from '../lib/proxy.js'
16
+ import { HAS_WSLPATH, skipWithout } from './helpers/cmd.mjs'
14
17
 
15
18
  const home = mkdtempSync(join(tmpdir(), 'ris-redirector-home-'))
16
19
  process.env.DSH_RIS_IDE_PROXY_HOME = home
17
20
 
21
+ // `spawnDetachedText` unrefs its timeout and its child on purpose (a launcher that
22
+ // outlives its caller must not hold the daemon open). Those handles can be the ONLY
23
+ // thing a waiting test has, and on node 20/22 the test runner keeps no handle of its
24
+ // own: the loop runs dry, the pending `await` never settles and every later test in
25
+ // the file is cancelled with "Promise resolution is still pending but the event loop
26
+ // has already resolved". node 24 happens to keep the runner referenced, which is why
27
+ // this only failed in CI. Hold ONE referenced timer for the file; the after hook
28
+ // releases it so the runner can still exit.
29
+ const keepLoopAlive = setInterval(() => { /* keep the loop referenced (see above) */ }, 1000)
30
+ after(() => clearInterval(keepLoopAlive))
31
+
18
32
  const { __test } = await import('../lib/redirector.js')
19
33
 
34
+ /**
35
+ * CI runs this suite on a plain Linux host (a k8s pod): no WSL, no `wslpath`, no
36
+ * Windows side — so `windowsPathOf` cannot answer there and the two watchdog
37
+ * tests could only ever run on a developer's WSL machine. On such a host we
38
+ * inject the mapping the WSL box would have produced; production still asks
39
+ * `wslpath` (`test/redirector.test.mjs` is the only caller of this seam).
40
+ */
41
+ const WSL_DISTRO = 'Ubuntu'
42
+ if (engineSide() !== 'wsl') {
43
+ __test.setWindowsPathTranslator((path) => {
44
+ const text = String(path)
45
+ if (text.startsWith('/') !== true) return ''
46
+ return `\\\\wsl.localhost\\${WSL_DISTRO}${text.replace(/\//g, '\\')}`
47
+ })
48
+ }
49
+
20
50
  /**
21
51
  * Every probe that could reach the real Windows side is stubbed for the whole
22
52
  * file. A test run must never enumerate, kill or elevate the user's actual
@@ -31,7 +61,7 @@ const BASE_HOOKS = {
31
61
  taskkill: () => 'ERROR: Access is denied.',
32
62
  }
33
63
  __test.setProbeHooks(BASE_HOOKS)
34
- process.on('exit', () => __test.resetProbeHooks())
64
+ process.on('exit', () => { __test.resetProbeHooks(); __test.setWindowsPathTranslator(null) })
35
65
  /** Use one extra stub for a single test, then fall back to the safe defaults. */
36
66
  const useHooks = (hooks) => {
37
67
  __test.resetProbeHooks()
@@ -66,6 +96,10 @@ test('a Windows command line never carries a WSL-only /mnt path', async () => {
66
96
  cliPath: '/mnt/x/Program Files/ProxyBridge/ProxyBridge_CLI.exe',
67
97
  profilePath: profile,
68
98
  platform: 'win32',
99
+ // The translation rule is what is under test here, not whether THIS machine
100
+ // has a Windows side: on a plain-Linux CI host `engineSide()` is 'linux' and
101
+ // the default gate would keep `/mnt` in the command line.
102
+ translate: true,
69
103
  })
70
104
  assert.equal(plan.display.includes('/mnt/'), false, 'no mnt path may survive in the Windows command')
71
105
  assert.ok(plan.display.includes('X:\\Program Files'), 'the executable must be spelled the Windows way')
@@ -298,7 +332,10 @@ test('the old single pid file is migrated to the side it names (M1)', () => {
298
332
  __test.clearRedirectorPid()
299
333
  })
300
334
 
301
- test('the parked-service state has ONE path shared by writer and watchdog (B2)', async () => {
335
+ // 纯 Linux(Jenkins 裸镜像)用上面的接缝;WSL 上必须真有 wslpath 才能算 Windows 路径。
336
+ const WINDOWS_SIDE = engineSide() !== 'wsl' || HAS_WSLPATH
337
+
338
+ test('the parked-service state has ONE path shared by writer and watchdog (B2)', { skip: skipWithout(WINDOWS_SIDE, 'wslpath') }, async () => {
302
339
  process.env.DSH_RIS_IDE_PROXY_HOME = home
303
340
  const mod = await import('../lib/redirector.js')
304
341
  const canonical = __test.serviceStatePath()
@@ -541,7 +578,7 @@ test('the heartbeat ages out and the stop signals round-trip', async () => {
541
578
  }
542
579
  })
543
580
 
544
- test('the elevated watchdog script carries the rules it needs to tear down', async () => {
581
+ test('the elevated watchdog script carries the rules it needs to tear down', { skip: skipWithout(WINDOWS_SIDE, 'wslpath') }, async () => {
545
582
  const tmpHome = mkdtempSync(join(tmpdir(), 'wd-'))
546
583
  process.env.DSH_RIS_IDE_PROXY_HOME = tmpHome
547
584
  const mod = await import('../lib/redirector.js')
@@ -922,3 +959,33 @@ test('readElevationState treats options.home as the PROXY home (server.js contra
922
959
  rmSync(home, { recursive: true, force: true })
923
960
  }
924
961
  })
962
+
963
+ test('the sudo probe is cached between background attempts (m03761)', { skip: process.platform === 'win32' ? 'no sudo on Windows' : false }, () => {
964
+ // A real `sudo -n true` writes a journal line on every call — including the
965
+ // failures. The reconciler retries a background start every minute, so on a box
966
+ // without passwordless sudo that used to be one audit line per minute. Pinned
967
+ // here with a fake `sudo` on PATH that records each invocation.
968
+ const bin = mkdtempSync(join(tmpdir(), 'ris-sudo-'))
969
+ const calls = join(bin, 'calls.log')
970
+ // `printf`, not `echo "$@"`: the args start with `-n`, which echo takes as
971
+ // "no trailing newline" — the invocations would then concatenate into one line
972
+ // and the counter would never move.
973
+ writeFileSync(join(bin, 'sudo'), `#!/bin/sh\nprintf '[%s]\\n' "$*" >> "${calls}"\nexit 1\n`, { mode: 0o755 })
974
+ chmodSync(join(bin, 'sudo'), 0o755)
975
+ const previousPath = process.env.PATH
976
+ const count = () => (existsSync(calls) ? readFileSync(calls, 'utf8').trim().split('\n').filter((line) => line !== '').length : 0)
977
+ process.env.PATH = bin
978
+ try {
979
+ __test.resetSudoProbe()
980
+ assert.equal(__test.sudoPasswordless(), false, 'the fake sudo never succeeds')
981
+ assert.equal(count(), 1)
982
+ assert.equal(__test.sudoPasswordless(), false, 'the cached answer is reused')
983
+ assert.equal(count(), 1, 'a background retry must not spawn sudo again')
984
+ __test.sudoPasswordless({ interactive: true })
985
+ assert.equal(count(), 2, 'a user-initiated start asks fresh (NOPASSWD may be new)')
986
+ } finally {
987
+ process.env.PATH = previousPath
988
+ __test.resetSudoProbe()
989
+ rmSync(bin, { recursive: true, force: true })
990
+ }
991
+ })
@@ -9,13 +9,13 @@
9
9
  */
10
10
  import assert from 'node:assert/strict'
11
11
  import test from 'node:test'
12
- import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
12
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
13
+ import { createServer } from 'node:http'
13
14
  import { join } from 'node:path'
14
15
  import { tmpdir } from 'node:os'
15
16
  import { createHash } from 'node:crypto'
16
17
  import { gzipSync } from 'node:zlib'
17
18
  import { RISD_API_VERSION, risdStatePath } from '../lib/risd/state.js'
18
- import { successorArgs } from '../lib/risd/server.js'
19
19
  import { bundleLayout } from '../lib/proxybridge-bundle.js'
20
20
  import { readProxyConfig } from '../lib/proxy.js'
21
21
  import { risdConfigRevision } from '../lib/risd/view.js'
@@ -191,18 +191,21 @@ test('the payload is the whole table: rows it leaves out are retired (m10585)',
191
191
  }), null, 2)}\n`, { mode: 0o600 })
192
192
  const view = await (await call(state, `/v1/proxy?cwd=${encodeURIComponent(ws)}`)).json()
193
193
  const userRule = view.rules.find((rule) => rule.id === 'r1')
194
+ // A row the stored table never had proves the upsert direction too (it used to
195
+ // live in a separate test, risd-api:'a sent row is upserted…').
196
+ const newRow = { id: 'kept-1', program: 'java', hosts: '10.0.0.*', ports: '*', enabled: true, source: 'yds' }
194
197
  const saved = await call(state, '/v1/proxy', {
195
198
  method: 'POST',
196
199
  body: {
197
200
  cwd: ws,
198
- config: { socks: view.socks, listenPort: view.listenPort, rules: [userRule] },
201
+ config: { socks: view.socks, listenPort: view.listenPort, rules: [userRule, newRow] },
199
202
  revision: view.revision,
200
203
  },
201
204
  })
202
205
  assert.equal(saved.status, 200)
203
206
  const after = await (await call(state, `/v1/proxy?cwd=${encodeURIComponent(ws)}`)).json()
204
- assert.deepEqual(after.rules.map((rule) => rule.id).sort(), ['r1'],
205
- 'only the rows in the payload survive')
207
+ assert.deepEqual(after.rules.map((rule) => rule.id).sort(), ['kept-1', 'r1'],
208
+ 'the sent row is inserted, and only the rows in the payload survive')
206
209
  })
207
210
 
208
211
  test('the ping route probes the configured SOCKS upstream and honours overrides', async (t) => {
@@ -271,10 +274,6 @@ test('the ProxyBridge bundle card reports status and rejects a bad upload', asyn
271
274
  // A forced probe while stopped still must not spawn anything (nothing to judge).
272
275
  const forced = await (await call(state, '/v1/proxybridge/health?force=1')).json()
273
276
  assert.equal(forced.checked, false)
274
- // The reconciler probes the bridge only when there is something to reconcile:
275
- // a stopped engine with no pid file must not spawn PowerShell on every poll.
276
- assert.match(readFileSync(new URL('../lib/risd/server.js', import.meta.url), 'utf8'), /engineStopped === true && hasBridgePidFiles\(\) !== true\) return/)
277
-
278
277
  // A non-tar body is answered with a reason, not a crash or a half-installed dir.
279
278
  const bad = await fetch(`${state.url}/v1/proxybridge/upload`, {
280
279
  method: 'POST',
@@ -325,7 +324,8 @@ test('config reports the decided policy and only accepts a lifecycle body', asyn
325
324
  assert.equal(body.idleExitMs, 600000)
326
325
  // The daemon has no restart supervisor; advertising one was a lie (review A-P2-3).
327
326
  assert.equal(body.engineRestart, undefined)
328
- assert.equal(body.lifecycle.daemon.followDsh, true)
327
+ assert.equal(body.lifecycle.daemon.stopWithDsh, true)
328
+ assert.equal(body.lifecycle.daemon.startWithDsh, true, 'the daemon start half is forced on')
329
329
 
330
330
  // POST exists for the lifecycle settings only: no body = bad request, and the
331
331
  // response says what is missing instead of pretending to be read-only.
@@ -409,17 +409,76 @@ test('/v1/dsh drops unusable `at` values and counts them (review A3-P2-6)', asyn
409
409
  assert.equal(body.dropped, 3, 'every unusable timestamp is reported, not silently pruned')
410
410
  })
411
411
 
412
- test('a sent row is upserted and a row left out is retired (no source exceptions)', async (t) => {
413
- const { home, state } = await startFixture(t)
414
- const view = await (await call(state, `/v1/proxy?cwd=${encodeURIComponent(home)}`)).json()
415
- const row = { id: 'kept-1', program: 'java', hosts: '10.0.0.*', ports: '*', enabled: true, source: 'yds' }
416
- const saved = await call(state, '/v1/proxy', {
417
- method: 'POST',
418
- body: { cwd: home, config: { socks: view.socks, listenPort: view.listenPort, rules: [row] }, revision: view.revision },
412
+ test('/v1/dsh probes a live host when no usable snapshot exists (m00186)', async (t) => {
413
+ // The daemon cannot read dsh's own API (its launch token lives in dsh's memory), so
414
+ // the plugin advertises one `instances/dsh-<pid>.json` per running host. When the
415
+ // shared document is missing or unusable, the daemon must ask that host directly
416
+ // instead of concluding "dsh is not running".
417
+ const home = makeHome('risd-dsh-probe-')
418
+ const saved = process.env.DSH_RIS_IDE_PROXY_HOME
419
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
420
+ t.after(() => {
421
+ if (saved === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
422
+ else process.env.DSH_RIS_IDE_PROXY_HOME = saved
423
+ removeHome(home)
419
424
  })
420
- assert.equal(saved.status, 200)
421
- const after = await (await call(state, `/v1/proxy?cwd=${encodeURIComponent(home)}`)).json()
422
- assert.deepEqual(after.rules.map((rule) => rule.id), ['kept-1'])
425
+ const plugin = createServer((req, res) => {
426
+ if (req.url !== '/dsh-ris-ide/workspaces') {
427
+ res.writeHead(404)
428
+ res.end()
429
+ return
430
+ }
431
+ res.writeHead(200, { 'content-type': 'application/json' })
432
+ res.end(JSON.stringify({
433
+ ok: true,
434
+ url: `http://127.0.0.1:${plugin.address().port}`,
435
+ at: new Date().toISOString(),
436
+ workspaces: [{ cwd: '/tmp/ws-probe', title: 'probed', sessionId: 's-probe', active: true }],
437
+ }))
438
+ })
439
+ await new Promise((resolve) => plugin.listen(0, '127.0.0.1', resolve))
440
+ t.after(() => new Promise((resolve) => plugin.close(resolve)))
441
+ const origin = `http://127.0.0.1:${plugin.address().port}`
442
+ mkdirSync(join(home, 'instances'), { recursive: true })
443
+ writeFileSync(join(home, 'instances', 'dsh-424242.json'), `${JSON.stringify({
444
+ pid: 424242,
445
+ url: origin,
446
+ at: new Date().toISOString(),
447
+ })}\n`)
448
+ const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
449
+ t.after(() => daemon.stop())
450
+ const body = await (await call(daemon.state, '/v1/dsh')).json()
451
+ assert.equal(body.available, true, 'a live instance file is enough to find the host')
452
+ assert.equal(body.url, origin)
453
+ assert.deepEqual(body.windows.map((row) => [row.cwd, row.title, row.sessionId, row.source, row.active]), [
454
+ ['/tmp/ws-probe', 'probed', 's-probe', 'workspace', true],
455
+ ])
456
+ assert.equal(body.knownWorkspaces, 1)
457
+ })
458
+
459
+ test('/v1/dsh names how many workspaces it found when no origin is usable (m00186)', async (t) => {
460
+ // "dsh is not running" and "dsh reported workspaces but no origin to embed" are
461
+ // different answers: the page can only show the count in the second case.
462
+ const home = makeHome('risd-dsh-known-')
463
+ const saved = process.env.DSH_RIS_IDE_PROXY_HOME
464
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
465
+ t.after(() => {
466
+ if (saved === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
467
+ else process.env.DSH_RIS_IDE_PROXY_HOME = saved
468
+ removeHome(home)
469
+ })
470
+ const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
471
+ t.after(() => daemon.stop())
472
+ writeFileSync(join(home, 'dsh-window.json'), `${JSON.stringify({
473
+ windows: [],
474
+ workspaces: [{ cwd: '/tmp/ws-a', title: 'alpha' }, { cwd: '/tmp/ws-b', title: 'beta' }],
475
+ at: new Date().toISOString(),
476
+ })}\n`)
477
+ const body = await (await call(daemon.state, '/v1/dsh')).json()
478
+ assert.equal(body.available, false)
479
+ assert.deepEqual(body.windows, [])
480
+ assert.equal(body.knownWorkspaces, 2)
481
+ assert.match(String(body.reason), /已发现 2 个 dsh 工作区/)
423
482
  })
424
483
 
425
484
  test('an upload whose digest is not the pinned one is rejected (review B-P0-1)', async (t) => {
@@ -491,14 +550,6 @@ test('a restart request hands over to a successor that waits for this pid (m1142
491
550
  assert.match(server, /spawnRestartSuccessor\(actualPort\)\n\s*if \(onShutdown !== null\) onShutdown\(true\)/, 'the restart path spawns the successor with the live port then hands off')
492
551
  // A4-P2-6: the successor keeps the port this daemon actually bound; A4-P2-5: it
493
552
  // also carries the predecessor identity so a reused pid is not waited on.
494
- const argv = successorArgs({ pid: 4321, port: 11082, startTime: '987654' })
495
- assert.equal(argv[1], 'serve')
496
- assert.deepEqual(argv.slice(2, 4), ['--wait-pid', '4321'])
497
- assert.deepEqual(argv.slice(argv.indexOf('--port'), argv.indexOf('--port') + 2), ['--port', '11082'])
498
- assert.deepEqual(argv.slice(argv.indexOf('--wait-start'), argv.indexOf('--wait-start') + 2), ['--wait-start', '987654'])
499
- const noPort = successorArgs({ pid: 7, port: 0, startTime: '' })
500
- assert.equal(noPort.includes('--port'), false, 'port 0 means "let the OS choose", never --port 0')
501
- assert.equal(noPort.includes('--wait-start'), false)
502
553
  const cli = readFileSync(new URL('../bin/risd.mjs', import.meta.url), 'utf8')
503
554
  assert.match(cli, /arg === '--wait-pid'/, 'the CLI understands --wait-pid')
504
555
  assert.match(cli, /arg === '--wait-start'/, 'the CLI understands the pid identity hint')
@@ -507,7 +558,10 @@ test('a restart request hands over to a successor that waits for this pid (m1142
507
558
 
508
559
  test('the daemon only prompts on a user-initiated start and files elevation state per side (review B-P0-2/B-P1-1)', async () => {
509
560
  const source = readFileSync(new URL('../lib/risd/server.js', import.meta.url), 'utf8')
510
- assert.match(source, /const redirector = await serializeBridge\(\(\) => startRedirectors\(\{ interactive: true \}\)\)/)
561
+ assert.match(source, /const interactive = parsed\.interactive === true/, 'the flag is opt-in: saving rules and dsh starting never ask for a password')
562
+ assert.match(source, /const redirector = await serializeBridge\(\(\) => startRedirectors\(\{ interactive \}\)\)/)
563
+ const plugin = readFileSync(new URL('../lib/index.js', import.meta.url), 'utf8')
564
+ assert.match(plugin, /const interactive = body\.interactive === true/, 'the plugin forwards the explicit-click flag')
511
565
  const reconcile = source.indexOf('startRedirectors({ sides: missing, interactive: false })')
512
566
  assert.ok(reconcile > 0, 'the reconciler starts without an interactive prompt')
513
567
  assert.match(source, /linux: readElevationState\('local', \{ home \}\)/, 'the elevation file is named after the side that writes it')