dsh-ris-ide 1.7.3 → 1.8.0

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 (72) hide show
  1. package/README.md +19 -7
  2. package/bin/proxy-janitor.mjs +106 -11
  3. package/bin/risd.mjs +287 -0
  4. package/bin/run-with-log.ps1 +43 -5
  5. package/lib/client.js +515 -1152
  6. package/lib/index.js +1124 -55
  7. package/lib/janitor.js +106 -15
  8. package/lib/proxy.js +86 -7
  9. package/lib/proxybridge-bundle.js +798 -0
  10. package/lib/redirector.js +484 -35
  11. package/lib/risd/build.js +91 -0
  12. package/lib/risd/debug.js +374 -0
  13. package/lib/risd/git.js +207 -0
  14. package/lib/risd/leases.js +124 -0
  15. package/lib/risd/lifecycle.js +148 -0
  16. package/lib/risd/log.js +59 -0
  17. package/lib/risd/ping.js +94 -0
  18. package/lib/risd/programs.js +348 -0
  19. package/lib/risd/server.js +1478 -0
  20. package/lib/risd/state.js +137 -0
  21. package/lib/risd/ui.js +1705 -0
  22. package/lib/risd/view.js +79 -0
  23. package/lib/risd-client.js +282 -0
  24. package/lib/standalone/window.html +14 -16
  25. package/lib/startup.js +114 -0
  26. package/package.json +4 -1
  27. package/test/client-build.test.mjs +113 -0
  28. package/test/client-viewer.test.mjs +166 -200
  29. package/test/dsh-origin.test.mjs +140 -0
  30. package/test/dsh-window-refresh.test.mjs +100 -0
  31. package/test/harness.test.mjs +9 -0
  32. package/test/host-noloop.test.mjs +74 -0
  33. package/test/host-tail.test.mjs +21 -4
  34. package/test/host-window.test.mjs +4 -4
  35. package/test/janitor.test.mjs +29 -1
  36. package/test/lifecycle.test.mjs +26 -5
  37. package/test/merge-owners.test.mjs +155 -0
  38. package/test/proxy-restart.test.mjs +37 -0
  39. package/test/proxy-window.test.mjs +45 -0
  40. package/test/proxy.test.mjs +41 -0
  41. package/test/proxybridge-bundle.test.mjs +687 -0
  42. package/test/redirector-bundle.test.mjs +391 -0
  43. package/test/redirector.test.mjs +59 -9
  44. package/test/risd-api.test.mjs +470 -0
  45. package/test/risd-bridge-degrade.test.mjs +101 -0
  46. package/test/risd-build.test.mjs +20 -0
  47. package/test/risd-cli-home.test.mjs +50 -0
  48. package/test/risd-client.test.mjs +130 -0
  49. package/test/risd-debug.test.mjs +261 -0
  50. package/test/risd-election.test.mjs +104 -0
  51. package/test/risd-engine.test.mjs +132 -0
  52. package/test/risd-entry.test.mjs +118 -0
  53. package/test/risd-git.test.mjs +109 -0
  54. package/test/risd-handoff.test.mjs +116 -0
  55. package/test/risd-heal.test.mjs +50 -0
  56. package/test/risd-helpers.mjs +108 -0
  57. package/test/risd-host-p2.test.mjs +147 -0
  58. package/test/risd-janitor-guard.test.mjs +46 -0
  59. package/test/risd-lease.test.mjs +83 -0
  60. package/test/risd-lifecycle.test.mjs +210 -0
  61. package/test/risd-log-follow.test.mjs +227 -0
  62. package/test/risd-mode.test.mjs +161 -0
  63. package/test/risd-ping.test.mjs +99 -0
  64. package/test/risd-programs.test.mjs +169 -0
  65. package/test/risd-review-p2.test.mjs +217 -0
  66. package/test/risd-shutdown.test.mjs +97 -0
  67. package/test/risd-teardown.test.mjs +87 -0
  68. package/test/risd-tools.test.mjs +211 -0
  69. package/test/risd-ui.test.mjs +445 -0
  70. package/test/risd-write.test.mjs +170 -0
  71. package/test/startup-reconcile.test.mjs +100 -0
  72. package/test/windows.test.mjs +37 -2
@@ -0,0 +1,100 @@
1
+ // The plugin is the only writer of dsh-window.json, so it must also keep the
2
+ // entries fresh while dsh still knows their session (m08228). Without this the
3
+ // daemon page would list only the workspace that happened to call an endpoint
4
+ // inside the freshness window.
5
+ import assert from 'node:assert/strict'
6
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
7
+ import { tmpdir } from 'node:os'
8
+ import { join } from 'node:path'
9
+ import { after, before, test } from 'node:test'
10
+ import { __test } from '../lib/index.js'
11
+
12
+ let home
13
+
14
+ before(() => {
15
+ home = mkdtempSync(join(tmpdir(), 'dsh-window-refresh-'))
16
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
17
+ })
18
+
19
+ after(() => {
20
+ delete process.env.DSH_RIS_IDE_PROXY_HOME
21
+ rmSync(home, { recursive: true, force: true })
22
+ })
23
+
24
+ function writeWindows(windows) {
25
+ writeFileSync(join(home, 'dsh-window.json'), `${JSON.stringify({ windows })}\n`, { mode: 0o600 })
26
+ }
27
+
28
+ function readWindows() {
29
+ return JSON.parse(readFileSync(join(home, 'dsh-window.json'), 'utf8')).windows
30
+ }
31
+
32
+ test('a session dsh still knows is refreshed, a gone one is dropped', () => {
33
+ const old = new Date(Date.now() - 10 * 60_000).toISOString()
34
+ writeWindows([
35
+ { url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-a', sessionId: 's-live', at: old },
36
+ { url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-b', sessionId: 's-gone', at: old },
37
+ ])
38
+ const result = __test.refreshDshWindows({
39
+ sessions: { get: (id) => (id === 's-live' ? { header: { cwd: '/tmp/ws-a' } } : null) },
40
+ })
41
+ // `windows` counts what SURVIVES: the pre-prune number misled callers (E P2-2).
42
+ assert.deepEqual(result, { changed: 1, windows: 1, dropped: 1 })
43
+ const rewritten = readWindows()
44
+ assert.equal(rewritten.length, 1)
45
+ assert.equal(rewritten[0].sessionId, 's-live')
46
+ assert.notEqual(rewritten[0].at, old, 'the live session is refreshed')
47
+ })
48
+
49
+ test('entries whose session dsh dropped are pruned', () => {
50
+ const old = new Date(Date.now() - 10 * 60_000).toISOString()
51
+ writeWindows([{ url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-b', sessionId: 's-gone', at: old }])
52
+ const result = __test.refreshDshWindows({ sessions: { get: () => null } })
53
+ assert.deepEqual(result, { changed: 0, windows: 0, dropped: 1 })
54
+ assert.deepEqual(readWindows(), [])
55
+ })
56
+
57
+ test('an entry without a session id is kept (nothing to verify)', () => {
58
+ const old = new Date(Date.now() - 10 * 60_000).toISOString()
59
+ writeWindows([{ url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-c', at: old }])
60
+ assert.deepEqual(__test.refreshDshWindows({ sessions: { get: () => null } }), { changed: 0, windows: 1, dropped: 0 })
61
+ assert.equal(readWindows().length, 1)
62
+ })
63
+
64
+ test('a missing window list is a no-op', () => {
65
+ rmSync(join(home, 'dsh-window.json'), { force: true })
66
+ assert.deepEqual(__test.refreshDshWindows({ sessions: { get: () => ({}) } }), { changed: 0, windows: 0, dropped: 0 })
67
+ })
68
+
69
+ test("another dsh instance's rows are left alone", () => {
70
+ // The home is machine-wide: two dsh processes share dsh-window.json, and each may
71
+ // only vouch for sessions IT knows. A row stamped with a foreign ownerPid must
72
+ // survive even though this process cannot resolve its sessionId (review C2-P2-2).
73
+ const old = new Date(Date.now() - 10 * 60_000).toISOString()
74
+ writeWindows([
75
+ { url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-other', sessionId: 's-foreign', ownerPid: 999999, at: old },
76
+ ])
77
+ assert.deepEqual(__test.refreshDshWindows({ sessions: { get: () => null } }), { changed: 0, windows: 1, dropped: 0 })
78
+ assert.equal(readWindows()[0].sessionId, 's-foreign')
79
+ })
80
+
81
+ test('a garbage ownerPid makes the row ours, not somebody else\'s', () => {
82
+ // Number('abc') is NaN: the old test treated that as "non-finite, not a foreign
83
+ // owner" and pruned the row as if it were ours-but-unknown. It must at least go
84
+ // through the same ownership check as a legacy row (no ownerPid) — review C3-P2-5.
85
+ const old = new Date(Date.now() - 10 * 60_000).toISOString()
86
+ writeWindows([{ url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-garbage', sessionId: 's-garbage', ownerPid: 'abc', at: old }])
87
+ const result = __test.refreshDshWindows({
88
+ sessions: { get: (id) => (id === 's-garbage' ? { header: { cwd: '/tmp/ws-garbage' } } : null) },
89
+ })
90
+ assert.deepEqual(result, { changed: 1, windows: 1, dropped: 0 }, 'the known session is refreshed')
91
+ assert.notEqual(readWindows()[0].at, old)
92
+ })
93
+
94
+ test('a session that reopened on another workspace drops the stale row', () => {
95
+ const old = new Date(Date.now() - 10 * 60_000).toISOString()
96
+ writeWindows([{ url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-moved', sessionId: 's-moved', at: old }])
97
+ const result = __test.refreshDshWindows({ sessions: { get: () => ({ header: { cwd: '/tmp/ws-new' } }) } })
98
+ assert.deepEqual(result, { changed: 0, windows: 0, dropped: 1 })
99
+ assert.deepEqual(readWindows(), [])
100
+ })
@@ -76,6 +76,15 @@ test('npm test needs no install and no network', async () => {
76
76
  assert.ok(pkg.devDependencies['react-dom'], 'react-dom is a devDependency (public registry)')
77
77
  })
78
78
 
79
+ test('spawned daemons cannot edit the machine git config', async () => {
80
+ // `git config --global` follows HOME/GIT_CONFIG_GLOBAL. A fixture that starts the
81
+ // daemon with a git rule would otherwise rewrite the developer's ~/.gitconfig
82
+ // (this happened once: a real `git.example.com` proxy entry appeared).
83
+ const text = await readFile(join(ROOT, 'test/risd-helpers.mjs'), 'utf8')
84
+ assert.match(text, /GIT_CONFIG_GLOBAL: join\(home, '\.gitconfig'\)/, 'the spawn helper pins GIT_CONFIG_GLOBAL into the temp home')
85
+ assert.match(text, /HOME: home/, 'the spawn helper pins HOME into the temp home')
86
+ })
87
+
79
88
  test('test files import only builtins and relative modules', async () => {
80
89
  const dir = join(ROOT, 'test')
81
90
  const offenders = []
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The two inline "GUI side" routes (`/opens`, `/debugs`) are for the page served on
3
+ * this machine, not for the LAN: like the other host routes they must refuse a
4
+ * request whose Host authority is not loopback, or whose Origin does not match it.
5
+ * A browser on another origin (or a DNS-rebinding attacker) must not be able to
6
+ * read the pending-open stack or the debug-session list.
7
+ */
8
+ import assert from 'node:assert/strict'
9
+ import { createServer, request as httpRequest } from 'node:http'
10
+ import { mkdtempSync } from 'node:fs'
11
+ import { tmpdir } from 'node:os'
12
+ import { join } from 'node:path'
13
+ import { test } from 'node:test'
14
+
15
+ const home = mkdtempSync(join(tmpdir(), 'ris-noloop-'))
16
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
17
+
18
+ const { __test } = await import('../lib/index.js')
19
+ const { handleRequest, OPENS_PATH, DEBUGS_PATH } = __test
20
+
21
+ async function withServer(run) {
22
+ const server = createServer((req, res) => { handleRequest({ sessions: { get: () => undefined } }, req, res, { maxBytes: 1024, restrictToCwd: false }) })
23
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
24
+ const port = server.address().port
25
+ try {
26
+ return await run({ port })
27
+ } finally {
28
+ await new Promise((resolve) => server.close(resolve))
29
+ }
30
+ }
31
+
32
+ /** One GET with arbitrary Host/Origin headers; resolves `{ status, body }`. */
33
+ function get(port, path, headers) {
34
+ return new Promise((resolve, reject) => {
35
+ const call = httpRequest({ host: '127.0.0.1', port, method: 'GET', path, headers }, (response) => {
36
+ let body = ''
37
+ response.setEncoding('utf8')
38
+ response.on('data', (chunk) => { body += chunk })
39
+ response.on('end', () => resolve({ status: response.statusCode, body }))
40
+ })
41
+ call.on('error', reject)
42
+ call.end()
43
+ })
44
+ }
45
+
46
+ test('GUI-side routes refuse a non-loopback Host', async () => {
47
+ await withServer(async ({ port }) => {
48
+ for (const path of [OPENS_PATH, DEBUGS_PATH]) {
49
+ const foreignHost = await get(port, path, { host: 'evil.example' })
50
+ assert.equal(foreignHost.status, 403, `${path} must refuse a foreign Host`)
51
+ assert.equal(JSON.parse(foreignHost.body).code, 'forbidden')
52
+ }
53
+ })
54
+ })
55
+
56
+ test('GUI-side routes refuse a non-loopback Origin even with a loopback Host', async () => {
57
+ await withServer(async ({ port }) => {
58
+ for (const path of [OPENS_PATH, DEBUGS_PATH]) {
59
+ const foreignOrigin = await get(port, path, { host: `127.0.0.1:${port}`, origin: 'http://evil.example' })
60
+ assert.equal(foreignOrigin.status, 403, `${path} must refuse a foreign Origin`)
61
+ }
62
+ })
63
+ })
64
+
65
+ test('GUI-side routes still answer a same-origin loopback request', async () => {
66
+ await withServer(async ({ port }) => {
67
+ const opens = await get(port, OPENS_PATH, { host: `127.0.0.1:${port}` })
68
+ assert.equal(opens.status, 200)
69
+ assert.equal(JSON.parse(opens.body).ok, true)
70
+ const debugs = await get(port, DEBUGS_PATH, { host: `127.0.0.1:${port}`, origin: `http://127.0.0.1:${port}` })
71
+ assert.equal(debugs.status, 200)
72
+ assert.equal(JSON.parse(debugs.body).ok, true)
73
+ })
74
+ })
@@ -381,6 +381,9 @@ test('the stop route answers no-service without a pidfile and refuses a foreign
381
381
  })
382
382
 
383
383
  test('the stop route terminates a real run-with-log.sh service end to end', async () => {
384
+ // Generous TERM→KILL grace: under the full parallel suite the wrapper can take
385
+ // longer than 5 s to trap TERM, reap `sleep` and write its exit banner; a 5 s
386
+ // grace SIGKILLs it first and the banner assertion below then fails.
384
387
  await withServer(async ({ base, cwd }) => {
385
388
  const logDir = join(cwd, 'logs')
386
389
  const log = join(logDir, 'stoptest.log')
@@ -419,7 +422,7 @@ test('the stop route terminates a real run-with-log.sh service end to end', asyn
419
422
  } finally {
420
423
  if (wrapper.exitCode === null && wrapper.signalCode === null) wrapper.kill('SIGKILL')
421
424
  }
422
- })
425
+ }, { maxBytes: HARD_MAX_BYTES, restrictToCwd: false, stopGraceMs: 15000, minFreeMemoryBytes: 1 })
423
426
  })
424
427
 
425
428
  test('listInstances finds a real run-with-log.sh service and reports it verified', async () => {
@@ -542,6 +545,9 @@ test('a frontend row is named after module.xml, not the package.json domainKey',
542
545
  const frontend = programs.filter((p) => p.kind === 'frontend')
543
546
  assert.equal(frontend.length, 1)
544
547
  assert.equal(frontend[0].name, 'c-ass-kk-hans-fe')
548
+ // logName follows the row name: the "<project>-" prefix made this row collide
549
+ // with the backend (launcher) row that owns the same log/pidfile.
550
+ assert.equal(frontend[0].logName, 'c-ass-kk-hans-fe')
545
551
  })
546
552
 
547
553
  test('scanPrograms finds Spring Boot entries and frontend manifests, and skips node_modules', async () => {
@@ -568,6 +574,7 @@ test('scanPrograms finds Spring Boot entries and frontend manifests, and skips n
568
574
  assert.equal(frontend[0].dir, uiDir)
569
575
  // No module.xml: a plain npm project keeps its package.json name.
570
576
  assert.equal(frontend[0].name, 'demo-ui')
577
+ assert.equal(frontend[0].logName, 'demo-ui', 'a frontend log name is its own name, not "<project>-<name>"')
571
578
  assert.equal(frontend[0].script, 'dev')
572
579
  assert.equal(frontend[0].packageManager, 'pnpm', 'inferred from pnpm-lock.yaml')
573
580
  })
@@ -1435,10 +1442,12 @@ test('the Git Bash runtime is detected and can be requested explicitly', async (
1435
1442
  assert.equal(pickGitBash([wslBash, gitBash]), gitBash)
1436
1443
  assert.equal(pickGitBash([join(dir, 'missing', 'bash.exe')]), undefined)
1437
1444
 
1438
- // auto: bash when found, PowerShell when not
1439
- assert.deepEqual(resolveWindowsRuntime('auto', gitBash), { runtime: 'bash', bashPath: gitBash })
1445
+ // auto: native PowerShell even when Git Bash is installed — MSYS rewrites the
1446
+ // Windows paths the bash wrapper passes to `mkdir`/`cd` (2026-11-09 Windows review).
1447
+ assert.deepEqual(resolveWindowsRuntime('auto', gitBash), { runtime: 'powershell' })
1440
1448
  assert.deepEqual(resolveWindowsRuntime('powershell', gitBash), { runtime: 'powershell' })
1441
- // explicit bash must fail loudly when it is not installed
1449
+ // bash stays opt-in, and must fail loudly when it is not installed
1450
+ assert.deepEqual(resolveWindowsRuntime('bash', gitBash), { runtime: 'bash', bashPath: gitBash })
1442
1451
  assert.throws(() => resolveWindowsRuntime('bash', join(dir, 'missing', 'bash.exe')), /Git Bash/)
1443
1452
  })
1444
1453
 
@@ -1446,6 +1455,14 @@ test('the windows-bash command keeps the POSIX wrapper but uses a Windows classp
1446
1455
  const program = { kind: 'spring', dir: 'C:\\ws\\ris\\m1', mainClass: 'a.B', args: ['--x'], logName: 'm1' }
1447
1456
  const spec = buildStartSpec(program, { workspace: 'C:\\ws', logsDir: 'C:\\ws\\logs', variant: 'windows-bash' })
1448
1457
  assert.match(spec.command, /-cp "target\\classes;\$\(cat target\/cp\.txt\)" a\.B --x$/)
1458
+ // Git Bash builtins are POSIX: paths handed to mkdir/cd must be /c/... form,
1459
+ // otherwise MSYS creates a file literally named `C:\ws\...`.
1460
+ // (cspDir is resolved with path.resolve first, so on a Linux runner its prefix is
1461
+ // the test cwd — the tail is what proves the conversion happened.)
1462
+ assert.match(spec.command, /^mkdir -p '[^']*\/csp'/)
1463
+ assert.match(spec.command, /&& cd \/c\/ws\/ris\/m1/)
1464
+ // The JVM is a Windows binary: -D paths stay in Windows spelling.
1465
+ assert.match(spec.command, /-DJM\.LOG\.PATH='C:\\ws\\logs'/)
1449
1466
  assert.match(spec.command, /exec java -DJM\.LOG\.PATH=/)
1450
1467
  // ...while a plain POSIX build keeps ':' and target/classes
1451
1468
  const posix = buildStartSpec(program, { workspace: '/w', logsDir: '/w/logs' })
@@ -61,10 +61,10 @@ test('the standalone window page is a self-contained HTML document', async () =>
61
61
  assert.ok(appAt > vendorAt, 'the browser half loads after React')
62
62
  assert.match(page.body, /__ModuleLoader__/, 'the page shims the module loader')
63
63
  assert.match(page.body, /mountStandalone/, 'and calls the standalone mount entry')
64
- // Script-opened windows may size themselves: the page fills the work area so
65
- // the IDE opens "maximized" even when the opener size is clamped.
66
- assert.match(page.body, /window\.moveTo\(0, 0\)/, 'the page repositions itself to the screen origin')
67
- assert.match(page.body, /window\.resizeTo\(window\.screen\.availWidth, window\.screen\.availHeight\)/, 'and fills the work area')
64
+ // A normal browser window: the page must NOT try to move or resize itself
65
+ // (script resizing is ignored in tabs and was only there for the old popup).
66
+ assert.doesNotMatch(page.body, /window\.moveTo\(/, 'no self-repositioning')
67
+ assert.doesNotMatch(page.body, /window\.resizeTo\(/, 'no self-resizing')
68
68
  } finally {
69
69
  await host.close()
70
70
  }
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import assert from 'node:assert/strict'
7
7
  import { spawn } from 'node:child_process'
8
- import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
8
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
9
9
  import { tmpdir } from 'node:os'
10
10
  import { join } from 'node:path'
11
11
  import { test } from 'node:test'
@@ -22,6 +22,7 @@ const {
22
22
  janitorStatePath,
23
23
  janitorStatus,
24
24
  pendingSideEffects,
25
+ removeOwnJanitorState,
25
26
  } = await import('../lib/janitor.js')
26
27
 
27
28
  /** A process that stays alive until we kill it (stands in for dsh). */
@@ -142,3 +143,30 @@ test('the watcher cleans up and exits once its owner is gone', async () => {
142
143
  assert.match(log, /已退出,开始清理/)
143
144
  assert.match(log, /清理完成/)
144
145
  })
146
+
147
+ test('disarming never signals a stranger that inherited the watcher pid (B-P2-9)', async () => {
148
+ const stranger = fakeOwner()
149
+ try {
150
+ writeFileSync(janitorStatePath(), `${JSON.stringify({ pid: stranger.pid, owner: 12345, log: '' })}\n`, { mode: 0o600 })
151
+ const result = disarmJanitor()
152
+ assert.equal(result.stopped, false, 'a pid that is not a proxy-janitor is left alone')
153
+ await new Promise((resolve) => setTimeout(resolve, 300))
154
+ assert.equal(stranger.exitCode, null, 'the unrelated process is still running')
155
+ assert.equal(existsSync(janitorStatePath()), false, 'the stale state file is still removed')
156
+ } finally {
157
+ stranger.kill('SIGKILL')
158
+ rmSync(janitorStatePath(), { force: true })
159
+ }
160
+ })
161
+
162
+ test('the watcher only removes a state file it wrote itself (B-P2-9)', () => {
163
+ writeFileSync(janitorStatePath(), `${JSON.stringify({ pid: 424242, owner: 1, log: '' })}\n`, { mode: 0o600 })
164
+ try {
165
+ assert.equal(removeOwnJanitorState(999), false)
166
+ assert.equal(existsSync(janitorStatePath()), true, 'a successor watcher file is not deleted')
167
+ assert.equal(removeOwnJanitorState(424242), true)
168
+ assert.equal(existsSync(janitorStatePath()), false)
169
+ } finally {
170
+ rmSync(janitorStatePath(), { force: true })
171
+ }
172
+ })
@@ -10,7 +10,7 @@
10
10
  * neither stacks exit listeners nor leaves the heartbeat dead.
11
11
  */
12
12
  import assert from 'node:assert/strict'
13
- import { existsSync, mkdtempSync, rmSync } from 'node:fs'
13
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
14
14
  import { tmpdir } from 'node:os'
15
15
  import { join } from 'node:path'
16
16
  import { after, test } from 'node:test'
@@ -18,7 +18,7 @@ import { after, test } from 'node:test'
18
18
  const home = mkdtempSync(join(tmpdir(), 'ris-lifecycle-'))
19
19
  process.env.DSH_RIS_IDE_PROXY_HOME = home
20
20
 
21
- const { apply } = await import('../lib/index.js')
21
+ const { apply, __test } = await import('../lib/index.js')
22
22
  const { janitorStatePath, janitorStatus, disarmJanitor } = await import('../lib/janitor.js')
23
23
  const { heartbeatPath } = await import('../lib/redirector.js')
24
24
 
@@ -52,7 +52,7 @@ after(() => {
52
52
  test('a disposed plugin keeps the exit hook and the watcher armed', () => {
53
53
  const before = process.listenerCount('exit')
54
54
  const ctx = fakeCtx()
55
- apply(ctx, {})
55
+ apply(ctx, { daemonMode: 'off' })
56
56
  assert.ok(process.listenerCount('exit') > before, 'apply must install the exit hook')
57
57
  const armed = janitorStatus()
58
58
  assert.equal(armed.running, true, 'apply must arm the janitor')
@@ -69,7 +69,7 @@ test('a disposed plugin keeps the exit hook and the watcher armed', () => {
69
69
  const installed = process.listenerCount('exit')
70
70
  // Re-applying (a profile hot reload runs every effect again) reuses the hook.
71
71
  const reload = fakeCtx()
72
- apply(reload, {})
72
+ apply(reload, { daemonMode: 'off' })
73
73
  assert.equal(process.listenerCount('exit'), installed, 'a hot reload must not stack exit hooks')
74
74
  assert.equal(existsSync(heartbeatPath()), true, 'the heartbeat is rebuilt after the teardown stopped it')
75
75
  reload.dispose()
@@ -81,8 +81,29 @@ test('three apply/dispose cycles add no exit listeners at all', () => {
81
81
  const before = process.listenerCount('exit')
82
82
  for (let index = 0; index < 3; index += 1) {
83
83
  const ctx = fakeCtx()
84
- apply(ctx, {})
84
+ apply(ctx, { daemonMode: 'off' })
85
85
  ctx.dispose()
86
86
  }
87
87
  assert.equal(process.listenerCount('exit'), before)
88
88
  })
89
+
90
+ test('a failed heartbeat write warns once instead of failing silently', () => {
91
+ const warns = []
92
+ const saved = process.env.DSH_RIS_IDE_PROXY_HOME
93
+ // A regular file where a directory is expected makes mkdir() fail fast (ENOTDIR),
94
+ // so writeHeartbeat() reports false — the same code path as a read-only home.
95
+ const blocker = join(home, 'heartbeat-blocker')
96
+ writeFileSync(blocker, 'not a directory\n')
97
+ process.env.DSH_RIS_IDE_PROXY_HOME = join(blocker, 'home')
98
+ let beat = null
99
+ try {
100
+ beat = __test.startHeartbeat({ warn: (message) => warns.push(message) })
101
+ } finally {
102
+ if (saved === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
103
+ else process.env.DSH_RIS_IDE_PROXY_HOME = saved
104
+ }
105
+ if (beat !== null) clearInterval(beat)
106
+ assert.equal(warns.length, 1, 'the first failed write warns exactly once')
107
+ assert.match(warns[0], /心跳写入失败/)
108
+ assert.match(warns[0], /20s/)
109
+ })
@@ -0,0 +1,155 @@
1
+ /**
2
+ * `mergeConfigs` must preserve a rule's per-workspace `owners` map.
3
+ *
4
+ * `yds` writes the map and later withdraws only its own endpoints from it. The
5
+ * read path (`normalizeConfig`) already kept it; the daemon write path rebuilt each
6
+ * row from a fixed field list and dropped it, so one config round trip broke
7
+ * `yds stop` (review B-P0-2 / D-P0-1). These tests pin the write path.
8
+ */
9
+ import assert from 'node:assert/strict'
10
+ import test from 'node:test'
11
+
12
+ import { mergeConfigs, normalizeConfig, normalizeOwners } from '../lib/proxy.js'
13
+
14
+ // The canonical (normalized) shape: hosts/ports are comma strings.
15
+ const ydsOwners = () => ({
16
+ '/ws/a': { program: 'java', hosts: '10.0.0.1', ports: '3306', enabled: true, shadow: false, direct: false },
17
+ })
18
+
19
+ /** A stored table: one driven (`yds`) row with owners, one user row. */
20
+ function storedConfig() {
21
+ return normalizeConfig({
22
+ socks: { host: '127.0.0.1', port: 1080 },
23
+ listenPort: 7890,
24
+ rules: [
25
+ {
26
+ id: 'yds-java',
27
+ label: 'YonCode java',
28
+ program: 'java',
29
+ hosts: '10.0.0.1',
30
+ ports: '3306',
31
+ enabled: true,
32
+ source: 'yds',
33
+ workspace: '/ws/a',
34
+ owners: ydsOwners(),
35
+ },
36
+ { id: 'user-curl', program: 'curl', hosts: '10.0.0.2', ports: '80', enabled: true, source: 'user', workspace: '/ws/b' },
37
+ ],
38
+ shadows: [],
39
+ })
40
+ }
41
+
42
+ const row = (config, id) => config.rules.find((item) => item.id === id)
43
+
44
+ test('a driven row keeps its owners across the write path when the patch restates them', () => {
45
+ const merged = mergeConfigs(storedConfig(), {
46
+ replaceRulesFrom: 'yds',
47
+ rules: [{
48
+ id: 'yds-java',
49
+ program: 'java',
50
+ hosts: '10.0.0.7',
51
+ ports: '3306',
52
+ enabled: true,
53
+ source: 'yds',
54
+ owners: {
55
+ '/ws/a': { program: 'java', hosts: ['10.0.0.7'], ports: ['3306'], enabled: true },
56
+ '/ws/c': { program: 'java', hosts: ['10.0.0.7'], ports: ['3306'], enabled: true },
57
+ },
58
+ }],
59
+ })
60
+ const owners = row(merged, 'yds-java').owners
61
+ assert.deepEqual(Object.keys(owners).sort(), ['/ws/a', '/ws/c'])
62
+ assert.equal(owners['/ws/a'].hosts, '10.0.0.7', 'arrays are stored as the canonical comma string')
63
+ assert.equal(owners['/ws/a'].program, 'java')
64
+ })
65
+
66
+ test('a whole-source replacement does not inherit owners the patch does not restate', () => {
67
+ const merged = mergeConfigs(storedConfig(), {
68
+ replaceRulesFrom: 'yds',
69
+ rules: [{ id: 'yds-java', program: 'java', hosts: '10.0.0.3', ports: '3306', enabled: true, source: 'yds' }],
70
+ })
71
+ assert.equal(row(merged, 'yds-java').owners, undefined, 'the replacement is a delete-and-recreate, not an edit')
72
+ })
73
+
74
+ test('editing a different row never loses the driven row owners', () => {
75
+ const merged = mergeConfigs(storedConfig(), {
76
+ rules: [{ id: 'user-curl', program: 'curl', hosts: '10.0.0.2', ports: '81', enabled: true, source: 'user' }],
77
+ })
78
+ assert.equal(row(merged, 'user-curl').ports, '81')
79
+ assert.deepEqual(row(merged, 'yds-java').owners, ydsOwners())
80
+ })
81
+
82
+ test('editing the driven row without restating owners inherits the stored map', () => {
83
+ const merged = mergeConfigs(storedConfig(), {
84
+ rules: [{ id: 'yds-java', program: 'java', hosts: '10.0.0.9', ports: '3306', enabled: true, source: 'yds' }],
85
+ })
86
+ assert.equal(row(merged, 'yds-java').hosts, '10.0.0.9')
87
+ assert.deepEqual(row(merged, 'yds-java').owners, ydsOwners(), 'a plain edit is not a withdrawal')
88
+ })
89
+
90
+ test('normalizeOwners whitelists the known fields and drops unusable entries', () => {
91
+ assert.equal(normalizeOwners(null), undefined)
92
+ assert.equal(normalizeOwners([]), undefined)
93
+ assert.equal(normalizeOwners({}), undefined)
94
+ assert.equal(normalizeOwners({ '/ws/x': {} }), undefined, 'an entry without a program is dropped')
95
+ assert.equal(normalizeOwners({ '/ws/x': { program: ' ' } }), undefined)
96
+ assert.equal(normalizeOwners({ '/ws/x': 'nope' }), undefined)
97
+ assert.deepEqual(
98
+ normalizeOwners({ '/ws/x': { program: ' java ', hosts: '1.2.3.4', ports: ['80', '443'], enabled: 1, extra: 'dropped' } }),
99
+ { '/ws/x': { program: 'java', hosts: '1.2.3.4', ports: '80,443', enabled: false, shadow: false, direct: false } },
100
+ )
101
+ })
102
+
103
+ // --- yds upgrade contract (D 段已提交 d305fd5) -----------------------------
104
+ // 1. Rows migrated from before owners existed are filed under the reserved
105
+ // `<legacy>` bucket: it is not a workspace path, so nothing may normalise or
106
+ // drop it, and a workspace stop must never withdraw it.
107
+ test('the reserved <legacy> owner bucket survives both write paths untouched', () => {
108
+ const legacy = { program: 'java', hosts: ['10.0.0.1'], ports: ['3306'], enabled: true }
109
+ const stored = normalizeConfig({
110
+ socks: { host: '127.0.0.1', port: 1080 },
111
+ listenPort: 7890,
112
+ rules: [{ id: 'yds-java', program: 'java', hosts: '10.0.0.1', ports: '3306', enabled: true, source: 'yds', workspace: '/ws/a', owners: { '<legacy>': legacy } }],
113
+ shadows: [],
114
+ })
115
+ assert.deepEqual(Object.keys(row(stored, 'yds-java').owners), ['<legacy>'])
116
+
117
+ const edited = mergeConfigs(stored, {
118
+ rules: [{ id: 'yds-java', program: 'java', hosts: '10.0.0.2', ports: '3306', enabled: true, source: 'yds' }],
119
+ })
120
+ assert.deepEqual(row(edited, 'yds-java').owners, {
121
+ '<legacy>': { program: 'java', hosts: '10.0.0.1', ports: '3306', enabled: true, shadow: false, direct: false },
122
+ })
123
+
124
+ const replaced = mergeConfigs(stored, {
125
+ replaceRulesFrom: 'yds',
126
+ rules: [{ id: 'yds-java', program: 'java', hosts: '10.0.0.2', ports: '3306', enabled: true, source: 'yds', owners: { '<legacy>': legacy } }],
127
+ })
128
+ assert.deepEqual(Object.keys(row(replaced, 'yds-java').owners), ['<legacy>'])
129
+ })
130
+
131
+ // 2. A slug conflict makes the driver suffix the id with a short hash; the id is
132
+ // the dedupe key (`yds\0id`) and must be stored verbatim.
133
+ test('a hashed driven id is preserved verbatim (dedupe key is the id itself)', () => {
134
+ const merged = mergeConfigs(storedConfig(), {
135
+ replaceRulesFrom: 'yds',
136
+ rules: [{ id: 'yds-java-1a2b3c', program: 'java', hosts: '10.0.0.1', ports: '3306', enabled: true, source: 'yds' }],
137
+ })
138
+ const driven = merged.rules.filter((item) => item.source === 'yds')
139
+ assert.deepEqual(driven.map((item) => item.id), ['yds-java-1a2b3c'])
140
+ })
141
+
142
+ // 3. The driver's POST /v1/proxy no longer sends `shadows`; a missing field must
143
+ // keep the stored fallback listeners rather than silently dropping them.
144
+ test('a patch without shadows keeps the stored fallback listeners', () => {
145
+ const stored = normalizeConfig({
146
+ socks: { host: '127.0.0.1', port: 1080 },
147
+ listenPort: 7890,
148
+ rules: [{ id: 'user-curl', program: 'curl', hosts: '10.0.0.2', ports: '80', enabled: true, source: 'user' }],
149
+ shadows: [{ host: '10.0.0.5', port: 3306 }],
150
+ })
151
+ const merged = mergeConfigs(stored, {
152
+ rules: [{ id: 'user-curl', program: 'curl', hosts: '10.0.0.2', ports: '80', enabled: true, source: 'user' }],
153
+ })
154
+ assert.deepEqual(merged.shadows, [{ host: '10.0.0.5', port: 3306, localPort: 3306 }])
155
+ })
@@ -0,0 +1,37 @@
1
+ // The bridge parses its profile when it starts, so a rule-table save can leave old
2
+ // rules intercepting. The daemon page therefore offers "restart bridge" right next
3
+ // to that warning, and both the daemon and the plugin must understand the action.
4
+ import { test } from 'node:test'
5
+ import assert from 'node:assert/strict'
6
+ import { readFileSync } from 'node:fs'
7
+
8
+ const read = (file) => readFileSync(new URL(`../${file}`, import.meta.url), 'utf8')
9
+
10
+ test('the daemon page offers a restart button next to a stale-bridge note', () => {
11
+ const ui = read('lib/risd/ui.js')
12
+ assert.match(ui, /id="bridge-restart"/)
13
+ // The button only appears for notes that say the bridge did not take the new rules.
14
+ assert.match(ui, /未重载\|旧规则/)
15
+ assert.match(ui, /'为什么要重启:'/)
16
+ assert.match(ui, /redirector-restart/)
17
+ })
18
+
19
+ test('the daemon restarts the bridge: stop, settle, start from the new profile', () => {
20
+ const server = read('lib/risd/server.js')
21
+ const at = server.indexOf("action === 'redirector-restart'")
22
+ assert.ok(at > 0, 'daemon must handle redirector-restart')
23
+ const block = server.slice(at, at + 600)
24
+ assert.match(block, /await stopRedirector\(\)/)
25
+ assert.match(block, /setTimeout\(resolve, 300\)/)
26
+ assert.match(block, /await startRedirectors\(\)/)
27
+ })
28
+
29
+ test('the plugin forwards the restart action to the daemon and can run it itself', () => {
30
+ const index = read('lib/index.js')
31
+ assert.match(index, /'redirector-restart'/)
32
+ const at = index.indexOf("action === 'redirector-restart'")
33
+ assert.ok(at > 0, 'plugin must handle redirector-restart locally')
34
+ const block = index.slice(at, at + 400)
35
+ assert.match(block, /await stopRedirector\(\)/)
36
+ assert.match(block, /await startRedirectors\(\)/)
37
+ })
@@ -0,0 +1,45 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { readFileSync } from 'node:fs'
4
+
5
+ const client = readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
6
+ const page = readFileSync(new URL('../lib/standalone/window.html', import.meta.url), 'utf8')
7
+
8
+ test('the panel no longer opens a proxy dialog at all', () => {
9
+ // Proxy rules live on the risd page (a machine-level resource, editable without
10
+ // dsh); both console shapes lost their 🌐, so nothing in the plugin opens the
11
+ // in-panel dialog or the standalone proxy window any more.
12
+ assert.doesNotMatch(client, /data-action': 'compact-proxy'/)
13
+ assert.doesNotMatch(client, /setProxyOpen\(true\)|setCompactProxyOpen\(true\)/)
14
+ assert.doesNotMatch(client, /focus-ack/)
15
+ })
16
+
17
+ test('the dead proxy-window opener and its polling hook are gone (review C-P2-7)', () => {
18
+ // These had no caller left once the 🌐 buttons went: keeping them meant a second
19
+ // way to open a proxy document and a second poll of /dsh-ris-ide/proxy that
20
+ // nobody consumed.
21
+ assert.doesNotMatch(client, /openProxyWindow/)
22
+ assert.doesNotMatch(client, /proxyWindowHandles|proxyWindowNameFor/)
23
+ assert.doesNotMatch(client, /proxyRunWatch|proxyRunKey|refreshProxyRun|useProxyRunning/)
24
+ // Nothing in the panel builds a view=proxy URL any more, and the component that
25
+ // rendered it is deleted (D4).
26
+ assert.doesNotMatch(client, /set\('view', 'proxy'\)/)
27
+ assert.doesNotMatch(client, /opts\.view === 'proxy'/)
28
+ })
29
+
30
+ test('the window page no longer forwards the dead `view` parameter', () => {
31
+ // The proxy-only window went with the dialog (D4); keeping the parameter alive
32
+ // meant the page and the client disagreed about a mode nobody could reach.
33
+ assert.doesNotMatch(page, /params\.get\('view'\)/)
34
+ assert.doesNotMatch(page, /view: view,/)
35
+ // D4 deleted the in-panel ProxyDialog together with its standalone rendering.
36
+ assert.doesNotMatch(client, /opts\.view === 'proxy'/)
37
+ assert.doesNotMatch(client, /standalone: true,/)
38
+ })
39
+
40
+ test('no panel button reflects engine state any more', () => {
41
+ // The grey/blue 🌐 indicator went with the buttons; engine state is shown in the
42
+ // risd page's overview instead.
43
+ assert.doesNotMatch(client, /color: proxyRunning === true/)
44
+ assert.doesNotMatch(client, /useProxyRunning\(\{ sessionId: sessionId, cwd: cwd \}\)/)
45
+ })