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
@@ -12,8 +12,8 @@ import { createServer } from 'node:http'
12
12
  import { mkdtempSync, readFileSync, 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-degrade-'))
19
19
  process.env.DSH_RIS_IDE_PROXY_HOME = home
@@ -21,24 +21,6 @@ process.env.DSH_RIS_IDE_PROXY_HOME = home
21
21
  const { __test } = await import('../lib/index.js')
22
22
  const { RISD_API_VERSION } = await import('../lib/risd/state.js')
23
23
 
24
- function fakeRes() {
25
- return {
26
- status: 0,
27
- chunks: [],
28
- writeHead(status) { this.status = status },
29
- write(chunk) { this.chunks.push(String(chunk)); return true },
30
- end(chunk) { if (chunk !== undefined) this.chunks.push(String(chunk)) },
31
- json() { return JSON.parse(this.chunks.join('')) },
32
- }
33
- }
34
- function fakeReq(method, url, body) {
35
- const chunks = body === undefined ? [] : [Buffer.from(JSON.stringify(body))]
36
- const req = Readable.from(chunks)
37
- req.method = method
38
- req.url = url
39
- req.headers = { host: '127.0.0.1:3080', 'content-type': 'application/json' }
40
- return req
41
- }
42
24
 
43
25
  const workspace = mkdtempSync(join(tmpdir(), 'risd-degrade-ws-'))
44
26
  const ctx = { sessions: { get: () => ({ header: { cwd: workspace } }) } }
@@ -50,15 +32,7 @@ test.after(() => {
50
32
  })
51
33
 
52
34
  test('a failed read keeps the lease, marks the bridge degraded and answers locally', async () => {
53
- const bridge = {
54
- mode: 'auto',
55
- state: { url: 'http://127.0.0.1:9', token: 'x', apiVersion: RISD_API_VERSION, port: 9 },
56
- leaseId: 'lease-x',
57
- pending: null,
58
- warnedAt: 0,
59
- degraded: false,
60
- lastProbeAt: Date.now(),
61
- }
35
+ const bridge = risdBridge({ url: 'http://127.0.0.1:9', token: 'x' })
62
36
  __test.setRisdBridge(bridge)
63
37
  const res = fakeRes()
64
38
  await __test.serveProxy(ctx, fakeReq('GET', '/dsh-ris-ide/proxy?sessionId=s1'), res)
@@ -86,7 +60,7 @@ test('a write refuses to go local while the daemon still answers health', async
86
60
  version: '1.8.0', startedAt: new Date().toISOString(), home,
87
61
  url: `http://127.0.0.1:${port}`,
88
62
  }, null, 2)}\n`, { mode: 0o600 })
89
- const bridge = { mode: 'auto', state: null, leaseId: 'lease-x', pending: null, warnedAt: 0, degraded: true, lastProbeAt: Date.now() }
63
+ const bridge = risdBridge({ degraded: true })
90
64
  __test.setRisdBridge(bridge)
91
65
  const before = readFileSync(join(home, 'proxy.json'), 'utf8')
92
66
  const res = fakeRes()
@@ -13,8 +13,47 @@ import { tmpdir } from 'node:os'
13
13
  import { join } from 'node:path'
14
14
  import { spawn } from 'node:child_process'
15
15
  import test from 'node:test'
16
+ import { setTimeout as sleep } from 'node:timers/promises'
16
17
  import { readRisdState } from '../lib/risd/state.js'
17
18
 
19
+ /**
20
+ * SIGTERM, wait until the process is really gone, then remove the temp trees.
21
+ *
22
+ * Deleting straight after `kill` raced the daemon: it kept writing its heartbeat
23
+ * and pid files into `home` while the collector walked the tree, and CI failed in
24
+ * the `after` hook with `EACCES: Directory not empty` (m05845). Waiting for the
25
+ * exit removes the writer; the bounded retry absorbs a last flush already queued.
26
+ * @param {import('node:child_process').ChildProcess} child the daemon we started.
27
+ * @param {string[]} dirs temp trees to delete.
28
+ */
29
+ async function stopAndClean(child, dirs) {
30
+ const gone = () => child.exitCode === null && child.signalCode === null
31
+ if (gone()) {
32
+ const exited = new Promise((resolve) => child.once('exit', resolve))
33
+ try { child.kill('SIGTERM') } catch { /* already gone */ }
34
+ await Promise.race([exited, sleep(5000)])
35
+ }
36
+ if (gone()) {
37
+ const exited = new Promise((resolve) => child.once('exit', resolve))
38
+ try { child.kill('SIGKILL') } catch { /* already gone */ }
39
+ await Promise.race([exited, sleep(2000)])
40
+ }
41
+ for (const dir of dirs) {
42
+ let lastError = null
43
+ for (let attempt = 0; attempt < 20; attempt += 1) {
44
+ try {
45
+ rmSync(dir, { recursive: true, force: true, maxRetries: 2, retryDelay: 50 })
46
+ lastError = null
47
+ break
48
+ } catch (error) {
49
+ lastError = error
50
+ await sleep(50)
51
+ }
52
+ }
53
+ if (lastError !== null) throw lastError
54
+ }
55
+ }
56
+
18
57
  const CLI = new URL('../bin/risd.mjs', import.meta.url).pathname
19
58
 
20
59
  test('a CLI run without --home resolves the machine home from the environment', async (t) => {
@@ -25,10 +64,8 @@ test('a CLI run without --home resolves the machine home from the environment',
25
64
  env: Object.assign({}, process.env, { DSH_RIS_IDE_PROXY_HOME: home, DSH_RISD_PORT: '0' }),
26
65
  stdio: ['ignore', 'pipe', 'pipe'],
27
66
  })
28
- t.after(() => {
29
- child.kill('SIGTERM')
30
- rmSync(home, { recursive: true, force: true })
31
- rmSync(cwd, { recursive: true, force: true })
67
+ t.after(async () => {
68
+ await stopAndClean(child, [home, cwd])
32
69
  })
33
70
  let stderr = ''
34
71
  child.stderr.setEncoding('utf8')
@@ -7,48 +7,11 @@
7
7
  */
8
8
  import assert from 'node:assert/strict'
9
9
  import test from 'node:test'
10
- import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
10
+ import { existsSync, mkdtempSync, rmSync } from 'node:fs'
11
11
  import { tmpdir } from 'node:os'
12
12
  import { join } from 'node:path'
13
- import { RISD_API_VERSION, risdStatePath } from '../lib/risd/state.js'
14
- import { makeHome, removeHome, sleep, startRisdProcess } from './risd-helpers.mjs'
15
-
16
- function pickPort() {
17
- return 20000 + Math.floor(Math.random() * 20000)
18
- }
19
-
20
- function writeEngineFixture(home, port) {
21
- const config = {
22
- socks: { host: '127.0.0.1', port: 1, dbPort: 0, redisPort: 0 },
23
- listenPort: port,
24
- rules: [
25
- {
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
- ],
36
- }
37
- writeFileSync(join(home, 'proxy.json'), JSON.stringify(config, null, 2))
38
- }
39
-
40
- function headers(state) {
41
- return { authorization: `Bearer ${state.token}`, 'x-risd-api-version': String(RISD_API_VERSION), 'content-type': 'application/json' }
42
- }
43
-
44
- async function waitFor(fn, timeoutMs = 8000) {
45
- const deadline = Date.now() + timeoutMs
46
- while (Date.now() < deadline) {
47
- if (await fn()) return true
48
- await sleep(120)
49
- }
50
- return false
51
- }
13
+ import { risdStatePath } from '../lib/risd/state.js'
14
+ import { makeHome, pickPort, removeHome, risdHeaders, startRisdProcess, waitFor, writeEngineFixture } from './risd-helpers.mjs'
52
15
 
53
16
  test('the daemon starts/stops the engine and reports one pid everywhere', async (t) => {
54
17
  const home = makeHome('risd-engine-')
@@ -56,7 +19,7 @@ test('the daemon starts/stops the engine and reports one pid everywhere', async
56
19
  writeEngineFixture(home, pickPort())
57
20
  const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
58
21
  t.after(async () => {
59
- await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: headers(daemon.state), body: JSON.stringify({ action: 'stop', cwd }) }).catch(() => {})
22
+ await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: risdHeaders(daemon.state), body: JSON.stringify({ action: 'stop', cwd }) }).catch(() => {})
60
23
  await daemon.stop()
61
24
  removeHome(home)
62
25
  rmSync(cwd, { recursive: true, force: true })
@@ -64,7 +27,7 @@ test('the daemon starts/stops the engine and reports one pid everywhere', async
64
27
 
65
28
  const started = await fetch(`${daemon.state.url}/v1/engine`, {
66
29
  method: 'POST',
67
- headers: headers(daemon.state),
30
+ headers: risdHeaders(daemon.state),
68
31
  body: JSON.stringify({ action: 'start', cwd }),
69
32
  })
70
33
  const startBody = await started.json()
@@ -75,7 +38,7 @@ test('the daemon starts/stops the engine and reports one pid everywhere', async
75
38
  assert.equal(Number.isInteger(pid) && pid > 0, true)
76
39
  assert.equal(existsSync(join(home, 'proxy.pid')), true, 'the daemon must own the pidfile')
77
40
 
78
- const read = await (await fetch(`${daemon.state.url}/v1/engine?cwd=${encodeURIComponent(cwd)}`, { headers: headers(daemon.state) })).json()
41
+ const read = await (await fetch(`${daemon.state.url}/v1/engine?cwd=${encodeURIComponent(cwd)}`, { headers: risdHeaders(daemon.state) })).json()
79
42
  assert.equal(read.engine.owned, true)
80
43
  assert.equal(read.engine.running, true)
81
44
  assert.equal(read.engine.pid, pid)
@@ -86,14 +49,14 @@ test('the daemon starts/stops the engine and reports one pid everywhere', async
86
49
 
87
50
  const stopped = await (await fetch(`${daemon.state.url}/v1/engine`, {
88
51
  method: 'POST',
89
- headers: headers(daemon.state),
52
+ headers: risdHeaders(daemon.state),
90
53
  body: JSON.stringify({ action: 'stop', cwd }),
91
54
  })).json()
92
55
  assert.equal(stopped.ok, true)
93
56
  assert.equal(stopped.result.stopped, true)
94
57
  assert.equal(await waitFor(() => !existsSync(join(home, 'proxy.pid'))), true)
95
58
 
96
- const after = await (await fetch(`${daemon.state.url}/v1/engine?cwd=${encodeURIComponent(cwd)}`, { headers: headers(daemon.state) })).json()
59
+ const after = await (await fetch(`${daemon.state.url}/v1/engine?cwd=${encodeURIComponent(cwd)}`, { headers: risdHeaders(daemon.state) })).json()
97
60
  assert.equal(after.engine.running, false)
98
61
  assert.equal(after.engine.owned, false)
99
62
  })
@@ -104,15 +67,15 @@ test('engine requests are validated and serialized', async (t) => {
104
67
  writeEngineFixture(home, pickPort())
105
68
  const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
106
69
  t.after(async () => {
107
- await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: headers(daemon.state), body: JSON.stringify({ action: 'stop', cwd }) }).catch(() => {})
70
+ await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: risdHeaders(daemon.state), body: JSON.stringify({ action: 'stop', cwd }) }).catch(() => {})
108
71
  await daemon.stop()
109
72
  removeHome(home)
110
73
  rmSync(cwd, { recursive: true, force: true })
111
74
  })
112
75
 
113
- const bad = await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: headers(daemon.state), body: JSON.stringify({ action: 'restart', cwd }) })
76
+ const bad = await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: risdHeaders(daemon.state), body: JSON.stringify({ action: 'restart', cwd }) })
114
77
  assert.equal(bad.status, 400)
115
- const relative = await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: headers(daemon.state), body: JSON.stringify({ action: 'start', cwd: 'relative/path' }) })
78
+ const relative = await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: risdHeaders(daemon.state), body: JSON.stringify({ action: 'start', cwd: 'relative/path' }) })
116
79
  assert.equal(relative.status, 400)
117
80
  const noAuth = await fetch(`${daemon.state.url}/v1/engine?cwd=/tmp/ws`)
118
81
  assert.equal(noAuth.status, 401)
@@ -120,13 +83,13 @@ test('engine requests are validated and serialized', async (t) => {
120
83
  // Two concurrent presses: both answer, one engine, no duplicate listeners.
121
84
  const [a, b] = await Promise.all(['start', 'start'].map((action) => fetch(`${daemon.state.url}/v1/engine`, {
122
85
  method: 'POST',
123
- headers: headers(daemon.state),
86
+ headers: risdHeaders(daemon.state),
124
87
  body: JSON.stringify({ action, cwd }),
125
88
  }).then((res) => res.json())))
126
89
  assert.equal(a.ok && b.ok, true)
127
90
  const first = a.result.pid || b.result.pid
128
91
  assert.equal(Number.isInteger(first) && first > 0, true)
129
- const status = await (await fetch(`${daemon.state.url}/v1/status?cwd=${encodeURIComponent(cwd)}`, { headers: headers(daemon.state) })).json()
92
+ const status = await (await fetch(`${daemon.state.url}/v1/status?cwd=${encodeURIComponent(cwd)}`, { headers: risdHeaders(daemon.state) })).json()
130
93
  assert.equal(status.running, true)
131
94
  assert.equal(status.pid, first)
132
95
  })
@@ -13,34 +13,12 @@ const host = readFileSync(new URL('../lib/index.js', import.meta.url), 'utf8')
13
13
  const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
14
14
  const bin = readFileSync(new URL('../bin/risd.mjs', import.meta.url), 'utf8')
15
15
 
16
- test('both IDE entry points open the risd page, with the window as fallback', () => {
17
- assert.match(client, /async function openRisdPage\(scope, fallback\)/, 'one shared opener')
18
- // Header ⧉ and the sidebar console ⧉ both go through it.
19
- assert.equal((client.match(/await openRisdPage\(/g) ?? []).length, 2, 'two entry points')
20
- // The page lives on the daemon origin and is reused by tab name.
21
- assert.match(client, /window\.open\(target, 'dsh-risd-ui'\)/)
22
- // The entry point preselects the workspace but does not switch the tab anymore
23
- // (m11345): the maintenance page keeps whatever tab the user was on.
24
- assert.match(client, /\?cwd=' \+ encodeURIComponent\(cwd\) : ''/)
25
- assert.doesNotMatch(client, /'tab=ide' \+/)
26
- assert.match(client, /target = risd\.url \+ '\/ui' \+ query/)
27
- // Without a daemon (daemonMode=off) the old standalone window still works.
28
- assert.ok((client.match(/openStandaloneWindow\(/g) ?? []).length >= 2, 'fallbacks stay in place')
29
- })
30
-
31
16
  test('the host view reports the daemon page address', () => {
32
17
  // proxyView (daemonMode=off ⇒ available:false) and mergeRisdView both carry it.
33
18
  assert.equal((host.match(/risd: risdBridge !== null && risdBridge\.state !== null/g) ?? []).length, 2)
34
19
  assert.match(host, /url: risdBridge\.state\.url, port: risdBridge\.state\.port/)
35
20
  })
36
21
 
37
- test('neither console carries a proxy button any more', () => {
38
- assert.doesNotMatch(client, /consoleConfigActions\.push\(button\('🌐'/, 'console 🌐 removed')
39
- // The sidebar's compact bar lost its 🌐 too: rules live on the risd page.
40
- assert.doesNotMatch(client, /data-action': 'compact-proxy'/)
41
- assert.doesNotMatch(client, /compactProxyOpen/)
42
- })
43
-
44
22
  test('the CLI is `risd`, exposed through package.json', () => {
45
23
  assert.deepEqual(pkg.bin, { risd: 'bin/risd.mjs' })
46
24
  assert.match(bin, /^#!\/usr\/bin\/env node/)
@@ -101,18 +79,3 @@ test('an api-version mismatch is a "restart dsh" answer, not a failed start (C-P
101
79
  // The forward path maps it to design §7.1's 503 instead of reusing the 409 branch.
102
80
  assert.match(host, /new TailError\('risd-upgrade-required'[\s\S]{0,120}503\)/)
103
81
  })
104
-
105
- test('tools probe a half-dead daemon and say when they fell back to local (C-P2-2)', () => {
106
- // A daemon that died between two tool calls used to look healthy forever: every
107
- // call then paid a 2 s timeout and ran locally without a word.
108
- assert.match(host, /const health = await risdHealth\(bridge\.state\)\.catch\(\(\) => null\)/)
109
- assert.match(host, /if \(Date\.now\(\) - \(bridge\.lastProbeAt \?\? 0\) < 5000\) return bridge\.state/)
110
- assert.match(host, /if \(healed === null\) warnDaemonFallback\(\)/)
111
- assert.match(host, /不在 daemon 的托管范围内(停 daemon 不会停它)/)
112
- })
113
-
114
- test('a transport failure on a proxy action says "retry", not "500" (C-P2-8)', () => {
115
- assert.match(host, /if \(call\.status === 0 \|\| call\.body === null\) \{/)
116
- assert.match(host, /new TailError\('risd-unavailable'[\s\S]{0,200}503\)/)
117
- assert.match(host, /void risdBridgeState\(cwd\)\.catch\(\(\) => \{\}\)/)
118
- })
@@ -0,0 +1,102 @@
1
+ // 「代理引擎跟随 dsh」 has two halves on ONE signal: the lease. The daemon starts the
2
+ // engine when the first lease arrives (proxy.startWithDsh) and tears it down when the
3
+ // last one leaves (proxy.stopWithDsh) — two switches, one signal, so the two sides
4
+ // still cannot disagree (m13950 / m03397).
5
+ // The automatic path must stay non-interactive: a password dialog cannot be a side
6
+ // effect of dsh starting (m13910) — only a click may ask.
7
+ import assert from 'node:assert/strict'
8
+ import { readFileSync } from 'node:fs'
9
+ import test from 'node:test'
10
+
11
+ import { makeHome, removeHome, sleep, startRisdProcess } from './risd-helpers.mjs'
12
+
13
+ const read = (file) => readFileSync(new URL(`../${file}`, import.meta.url), 'utf8')
14
+
15
+ test('a lease never starts an engine when the policy is off or no rule is actionable', async () => {
16
+ const home = makeHome('risd-follow-')
17
+ const daemon = await startRisdProcess({ home })
18
+ try {
19
+ const { port, token } = daemon.state
20
+ const headers = {
21
+ authorization: `Bearer ${token}`,
22
+ 'x-risd-api-version': '1',
23
+ 'content-type': 'application/json',
24
+ }
25
+ const lease = (cwd) => fetch(`http://127.0.0.1:${port}/v1/leases`, {
26
+ method: 'POST',
27
+ headers,
28
+ body: JSON.stringify({ ownerPid: process.pid, cwd }),
29
+ })
30
+ const save = (body) => fetch(`http://127.0.0.1:${port}/v1/config`, {
31
+ method: 'POST',
32
+ headers,
33
+ body: JSON.stringify(body),
34
+ })
35
+ const engine = async () => {
36
+ const health = await (await fetch(`http://127.0.0.1:${port}/v1/health`)).json()
37
+ return health.engine?.state
38
+ }
39
+
40
+ // Following dsh is the default, but the rule table is empty: no engine.
41
+ assert.equal((await lease(home)).status, 200)
42
+ await sleep(400)
43
+ assert.equal(await engine(), 'stopped', 'an empty table is not a reason to spawn an engine')
44
+
45
+ // Turning the start half off must stop the lease from spawning anything.
46
+ assert.equal((await save({ lifecycle: { proxy: { startWithDsh: false } } })).status, 200)
47
+ assert.equal((await lease(home)).status, 200)
48
+ await sleep(400)
49
+ assert.equal(await engine(), 'stopped', 'a policy that does not follow dsh cannot start it')
50
+ } finally {
51
+ await daemon.stop()
52
+ await sleep(100)
53
+ removeHome(home)
54
+ }
55
+ })
56
+
57
+ test('the start half rides the lease, not a separate route or plugin call', () => {
58
+ const server = read('lib/risd/server.js')
59
+ const leaseAt = server.indexOf("if (path === '/v1/leases')")
60
+ assert.ok(leaseAt > 0)
61
+ const leaseBlock = server.slice(leaseAt, server.indexOf("const leaseMatch", leaseAt))
62
+ assert.match(leaseBlock, /lifecycle\.proxy\.startWithDsh === true/, 'the start half the policy exposes')
63
+ assert.match(leaseBlock, /followStartForLease\(lease\.cwd\)/, 'the lease is the start signal')
64
+
65
+ const start = server.indexOf('function followStartForLease(')
66
+ assert.ok(start > 0, 'the start half lives next to the engine helpers')
67
+ const startBlock = server.slice(start, start + 2600)
68
+ assert.match(startBlock, /engineSummary\(\)\.state === 'running'/, 'an engine that is already up is left alone')
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')
71
+ assert.match(startBlock, /reason: 'no-lease'/, 'a lease that left mid-round-trip must not spawn an engine')
72
+ // The same promise is awaitable, so teardown can let a departing lease's start land
73
+ // before it decides what to stop (otherwise engineCwd is still null and the engine
74
+ // is orphaned — m13960).
75
+ assert.match(startBlock, /followStarting = work\.finally/)
76
+ const teardownAt = server.indexOf('function scheduleTeardown()')
77
+ const teardownBlock = server.slice(teardownAt, server.indexOf('const leases = createLeaseRegistry', teardownAt))
78
+ assert.match(teardownBlock, /await followStarting\.catch\(\(\) => \{\}\)/, 'teardown waits for an in-flight start')
79
+ assert.match(teardownBlock, /followStarting === null\) return/, 'a pending start must not suppress the teardown schedule')
80
+ assert.doesNotMatch(server, /'\/v1\/follow-start'/, 'there is no second entry point to keep in sync')
81
+
82
+ // Teardown reads the other half of the same resource, so "start follows dsh" and
83
+ // "stop follows dsh" cannot disagree about which resource they describe.
84
+ assert.match(server, /if \(lifecycle\.proxy\.stopWithDsh === true\) \{\n\s+await teardownNetwork\(cwd\)/)
85
+
86
+ assert.doesNotMatch(read('lib/risd-client.js'), /followStartRisd/, 'the plugin does not need a call')
87
+ assert.doesNotMatch(read('lib/index.js'), /followStartRisd/, 'the lease acquired by attachBridgeState is the signal')
88
+ })
89
+
90
+ test('saving the rule table never starts the engine (m13920)', () => {
91
+ const server = read('lib/risd/server.js')
92
+ const at = server.indexOf("path === '/v1/proxy' && method === 'POST'")
93
+ assert.ok(at > 0)
94
+ const block = server.slice(at, server.indexOf("if (path === '/v1/action'", at))
95
+ assert.doesNotMatch(block, /await startProxy\(/, 'a save must not spawn the engine')
96
+ assert.match(block, /switchEnforcement/, 'an already-running bridge is reloaded instead')
97
+
98
+ const ui = read('lib/risd/ui.js')
99
+ assert.doesNotMatch(ui, /function maybeStartProxy/, 'the save-triggered start is gone')
100
+ assert.doesNotMatch(ui, /proxy-start-with-dsh/, 'the policy is the lifecycle checkbox, not a second switch')
101
+ assert.match(ui, /保存不会启动它/, 'the banner names the button instead of starting')
102
+ })
@@ -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')