dsh-ris-ide 1.7.2 → 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 (79) hide show
  1. package/README.md +43 -4
  2. package/bin/check-listing.mjs +247 -0
  3. package/bin/proxy-janitor.mjs +183 -0
  4. package/bin/risd.mjs +287 -0
  5. package/bin/run-with-log.ps1 +43 -5
  6. package/lib/client-codemirror.js +92 -66
  7. package/lib/client.js +774 -89
  8. package/lib/index.js +2256 -21
  9. package/lib/janitor.js +377 -0
  10. package/lib/proxy.js +1577 -0
  11. package/lib/proxybridge-bundle.js +798 -0
  12. package/lib/redirector.js +2558 -0
  13. package/lib/risd/build.js +91 -0
  14. package/lib/risd/debug.js +374 -0
  15. package/lib/risd/git.js +207 -0
  16. package/lib/risd/leases.js +124 -0
  17. package/lib/risd/lifecycle.js +148 -0
  18. package/lib/risd/log.js +59 -0
  19. package/lib/risd/ping.js +94 -0
  20. package/lib/risd/programs.js +348 -0
  21. package/lib/risd/server.js +1478 -0
  22. package/lib/risd/state.js +137 -0
  23. package/lib/risd/ui.js +1705 -0
  24. package/lib/risd/view.js +79 -0
  25. package/lib/risd-client.js +282 -0
  26. package/lib/standalone/window.html +14 -16
  27. package/lib/startup.js +114 -0
  28. package/package.json +7 -2
  29. package/skills/dsh-ris-ide-debug/SKILL.md +37 -2
  30. package/test/client-build.test.mjs +113 -0
  31. package/test/client-viewer.test.mjs +314 -20
  32. package/test/companion.test.mjs +65 -0
  33. package/test/dsh-origin.test.mjs +140 -0
  34. package/test/dsh-window-refresh.test.mjs +100 -0
  35. package/test/harness.test.mjs +9 -0
  36. package/test/host-noloop.test.mjs +74 -0
  37. package/test/host-tail.test.mjs +54 -5
  38. package/test/host-window.test.mjs +4 -4
  39. package/test/inherit-engine.test.mjs +175 -0
  40. package/test/install-phase.test.mjs +36 -0
  41. package/test/janitor.test.mjs +172 -0
  42. package/test/lifecycle.test.mjs +109 -0
  43. package/test/merge-owners.test.mjs +155 -0
  44. package/test/proxy-restart.test.mjs +37 -0
  45. package/test/proxy-route.test.mjs +599 -0
  46. package/test/proxy-window.test.mjs +45 -0
  47. package/test/proxy.test.mjs +914 -0
  48. package/test/proxybridge-bundle.test.mjs +687 -0
  49. package/test/redirector-bundle.test.mjs +391 -0
  50. package/test/redirector.test.mjs +571 -0
  51. package/test/risd-api.test.mjs +470 -0
  52. package/test/risd-bridge-degrade.test.mjs +101 -0
  53. package/test/risd-build.test.mjs +20 -0
  54. package/test/risd-cli-home.test.mjs +50 -0
  55. package/test/risd-client.test.mjs +130 -0
  56. package/test/risd-debug.test.mjs +261 -0
  57. package/test/risd-election.test.mjs +104 -0
  58. package/test/risd-engine.test.mjs +132 -0
  59. package/test/risd-entry.test.mjs +118 -0
  60. package/test/risd-git.test.mjs +109 -0
  61. package/test/risd-handoff.test.mjs +116 -0
  62. package/test/risd-heal.test.mjs +50 -0
  63. package/test/risd-helpers.mjs +108 -0
  64. package/test/risd-host-p2.test.mjs +147 -0
  65. package/test/risd-janitor-guard.test.mjs +46 -0
  66. package/test/risd-lease.test.mjs +83 -0
  67. package/test/risd-lifecycle.test.mjs +210 -0
  68. package/test/risd-log-follow.test.mjs +227 -0
  69. package/test/risd-mode.test.mjs +161 -0
  70. package/test/risd-ping.test.mjs +99 -0
  71. package/test/risd-programs.test.mjs +169 -0
  72. package/test/risd-review-p2.test.mjs +217 -0
  73. package/test/risd-shutdown.test.mjs +97 -0
  74. package/test/risd-teardown.test.mjs +87 -0
  75. package/test/risd-tools.test.mjs +211 -0
  76. package/test/risd-ui.test.mjs +445 -0
  77. package/test/risd-write.test.mjs +170 -0
  78. package/test/startup-reconcile.test.mjs +100 -0
  79. package/test/windows.test.mjs +37 -2
@@ -0,0 +1,140 @@
1
+ // The plugin's half of the daemon page's IDE tab: it records the browser's origin
2
+ // plus the current dsh sessionId into `dsh-window.json`, per workspace, so one
3
+ // daemon page can embed the IDE of every workspace someone has open.
4
+ //
5
+ // Only loopback Hosts are recorded (the daemon page itself is loopback-only too).
6
+ import assert from 'node:assert/strict'
7
+ import { createServer, request } from 'node:http'
8
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
9
+ import { tmpdir } from 'node:os'
10
+ import { join } from 'node:path'
11
+ import { after, before, test } from 'node:test'
12
+ import { handleRequest } from '../lib/index.js'
13
+
14
+ let home
15
+ let workspace
16
+ let server
17
+ let port
18
+
19
+ before(async () => {
20
+ home = mkdtempSync(join(tmpdir(), 'dsh-origin-home-'))
21
+ workspace = mkdtempSync(join(tmpdir(), 'dsh-origin-ws-'))
22
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
23
+ process.env.DSH_RIS_IDE_WINDOW_NOTE = '1'
24
+ server = createServer((req, res) => {
25
+ handleRequest({ sessions: { get: () => ({ header: { cwd: workspace } }) } }, req, res, { maxBytes: 1024, restrictToCwd: false })
26
+ })
27
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
28
+ port = server.address().port
29
+ })
30
+
31
+ after(async () => {
32
+ await new Promise((resolve) => server.close(resolve))
33
+ delete process.env.DSH_RIS_IDE_PROXY_HOME
34
+ delete process.env.DSH_RIS_IDE_WINDOW_NOTE
35
+ rmSync(home, { recursive: true, force: true })
36
+ rmSync(workspace, { recursive: true, force: true })
37
+ })
38
+
39
+ function get(path, host) {
40
+ return new Promise((resolve) => {
41
+ const call = request({ host: '127.0.0.1', port, path, method: 'GET', headers: { host: host ?? `127.0.0.1:${port}` } }, (res) => {
42
+ res.resume()
43
+ res.on('end', () => resolve(res.statusCode))
44
+ })
45
+ call.on('error', () => resolve(0))
46
+ call.end()
47
+ })
48
+ }
49
+
50
+ function readWindows() {
51
+ const file = join(home, 'dsh-window.json')
52
+ if (!existsSync(file)) return null
53
+ return JSON.parse(readFileSync(file, 'utf8')).windows
54
+ }
55
+
56
+ test('a loopback request records the dsh origin and session per workspace', async () => {
57
+ const status = await get(`/dsh-ris-ide/windows?sessionId=sess-1&cwd=${encodeURIComponent(workspace)}`)
58
+ assert.equal(status, 200)
59
+ const windows = readWindows()
60
+ assert.ok(Array.isArray(windows), 'dsh-window.json must hold a windows array')
61
+ assert.equal(windows.length, 1)
62
+ assert.equal(windows[0].url, `http://127.0.0.1:${port}`)
63
+ assert.equal(windows[0].sessionId, 'sess-1')
64
+ assert.equal(windows[0].cwd, workspace)
65
+ })
66
+
67
+ test('a probe without a dsh session is not recorded as a workspace', async () => {
68
+ // `/windows?cwd=` probes come from the standalone/maintenance page and carry no
69
+ // session. Inheriting the previous window's id opened the IDE with the wrong
70
+ // session and made the liveness check prune the wrong entry (C2-P1-2).
71
+ const before = readWindows().length
72
+ const status = await get(`/dsh-ris-ide/windows?cwd=${encodeURIComponent(workspace)}`)
73
+ assert.equal(status, 200)
74
+ const after = readWindows()
75
+ assert.equal(after.length, before, 'nothing may be recorded without a sessionId')
76
+ assert.ok(after.every((row) => row.sessionId !== ''), 'every stored row names a real session')
77
+ })
78
+
79
+ test('a non-loopback Host is not recorded', async () => {
80
+ const before = readWindows().length
81
+ const status = await get(`/dsh-ris-ide/windows?sessionId=sess-evil&cwd=${encodeURIComponent(workspace)}`, 'evil.example:80')
82
+ assert.equal(status, 403)
83
+ assert.equal(readWindows().length, before, 'a foreign origin cannot seed the IDE list')
84
+ })
85
+
86
+ test('a second workspace upserts instead of replacing the list', async () => {
87
+ const other = mkdtempSync(join(tmpdir(), 'dsh-origin-ws2-'))
88
+ try {
89
+ const status = await get(`/dsh-ris-ide/windows?sessionId=sess-2&cwd=${encodeURIComponent(other)}`)
90
+ assert.equal(status, 200)
91
+ const windows = readWindows()
92
+ assert.equal(windows.length, 2, 'both workspaces are listed')
93
+ assert.deepEqual(windows.map((row) => row.sessionId).sort(), ['sess-1', 'sess-2'])
94
+ // A brand-new workspace is written immediately. Re-recording one that is already
95
+ // there is throttled to one write per 3 s (review C3-P2-6), so the order of the
96
+ // second call below is not promised — only that nothing duplicates.
97
+ const statusAgain = await get(`/dsh-ris-ide/windows?sessionId=sess-1&cwd=${encodeURIComponent(workspace)}`)
98
+ assert.equal(statusAgain, 200)
99
+ const after = readWindows()
100
+ assert.equal(after.length, 2, 'the same workspace must not duplicate')
101
+ assert.deepEqual(after.map((row) => row.cwd).sort(), [workspace, other].sort())
102
+ } finally {
103
+ rmSync(other, { recursive: true, force: true })
104
+ }
105
+ })
106
+
107
+ test('alternating known workspaces does not write on every request', async () => {
108
+ // Two dsh windows take turns hitting the plugin; each request used to rewrite the
109
+ // machine-level file (~one synchronous read+write per request). Now an already
110
+ // recorded workspace inside the 3 s window only moves the in-memory key.
111
+ const rows = readWindows()
112
+ // One request first: either it writes (the window had expired) or it is already
113
+ // inside the window — both leave the throttle armed for the loop below.
114
+ await get(`/dsh-ris-ide/windows?sessionId=${rows[0].sessionId}&cwd=${encodeURIComponent(rows[0].cwd)}`)
115
+ const before = readFileSync(join(home, 'dsh-window.json'), 'utf8')
116
+ for (const row of rows) {
117
+ await get(`/dsh-ris-ide/windows?sessionId=${row.sessionId}&cwd=${encodeURIComponent(row.cwd)}`)
118
+ }
119
+ const after = readFileSync(join(home, 'dsh-window.json'), 'utf8')
120
+ assert.equal(after, before, 'nothing was rewritten inside the throttle window')
121
+ })
122
+
123
+ test('a non-loopback Host header records nothing', async () => {
124
+ const before = readWindows()
125
+ // The route itself may refuse a non-loopback Host (403); recording must not happen either way.
126
+ const status = await get('/dsh-ris-ide/windows?sessionId=sess-evil', 'evil.example.com')
127
+ assert.ok(status === 200 || status === 403, `unexpected status ${status}`)
128
+ const after = readWindows()
129
+ assert.equal(JSON.stringify(after), JSON.stringify(before))
130
+ })
131
+
132
+ test('a request without a workspace does not replace another workspace entry', async () => {
133
+ // Review C-P1-5: the empty-cwd entry used `existing[0].cwd` as its key, so a
134
+ // bare /dsh-ris-ide/proxy call overwrote somebody else's window entry.
135
+ const before = readWindows()
136
+ const status = await get('/dsh-ris-ide/proxy?sessionId=sess-3')
137
+ assert.equal(status, 200)
138
+ const after = readWindows()
139
+ assert.deepEqual(after.map((row) => row.cwd), before.map((row) => row.cwd), 'the list is unchanged')
140
+ })
@@ -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')
@@ -406,7 +409,9 @@ test('the stop route terminates a real run-with-log.sh service end to end', asyn
406
409
  // The wrapper writes its exit banner just before it exits; under a loaded
407
410
  // parallel test run the read can win the race, so poll briefly.
408
411
  let banner = ''
409
- for (let attempt = 0; attempt < 40; attempt += 1) {
412
+ // Generous budget: the wrapper is bash that has to reap `sleep`, trap TERM
413
+ // and write the banner, and the full test run keeps several files in flight.
414
+ for (let attempt = 0; attempt < 400; attempt += 1) {
410
415
  banner = await readFile(log, 'utf8')
411
416
  if (/stoptest exited/.test(banner)) break
412
417
  await new Promise((resolve) => setTimeout(resolve, 50))
@@ -417,7 +422,7 @@ test('the stop route terminates a real run-with-log.sh service end to end', asyn
417
422
  } finally {
418
423
  if (wrapper.exitCode === null && wrapper.signalCode === null) wrapper.kill('SIGKILL')
419
424
  }
420
- })
425
+ }, { maxBytes: HARD_MAX_BYTES, restrictToCwd: false, stopGraceMs: 15000, minFreeMemoryBytes: 1 })
421
426
  })
422
427
 
423
428
  test('listInstances finds a real run-with-log.sh service and reports it verified', async () => {
@@ -529,6 +534,22 @@ async function makeStartableFixture() {
529
534
  return { root }
530
535
  }
531
536
 
537
+ test('a frontend row is named after module.xml, not the package.json domainKey', async () => {
538
+ const root = await mkdtemp(join(tmpdir(), 'dsh-ris-ide-fe-'))
539
+ const dir = join(root, 'my-fe')
540
+ await mkdir(dir, { recursive: true })
541
+ // MDF projects keep the backend domainKey in package.json — that is the collision.
542
+ await writeFile(join(dir, 'package.json'), JSON.stringify({ name: 'c-ass-kk-hans', scripts: { dev: 'vite' } }))
543
+ await writeFile(join(dir, 'module.xml'), '<module name="c-ass-kk-hans-fe" description="前端"><nginx_mode>mdf</nginx_mode></module>')
544
+ const programs = await scanPrograms(root, join(root, 'logs'), true)
545
+ const frontend = programs.filter((p) => p.kind === 'frontend')
546
+ assert.equal(frontend.length, 1)
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')
551
+ })
552
+
532
553
  test('scanPrograms finds Spring Boot entries and frontend manifests, and skips node_modules', async () => {
533
554
  const { root, moduleDir, uiDir } = await makeProgramFixture()
534
555
  const logsDir = join(root, 'logs')
@@ -551,7 +572,9 @@ test('scanPrograms finds Spring Boot entries and frontend manifests, and skips n
551
572
  `--spring.config.additional-location=file:${join(root, 'local.yml')}`,
552
573
  ])
553
574
  assert.equal(frontend[0].dir, uiDir)
575
+ // No module.xml: a plain npm project keeps its package.json name.
554
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>"')
555
578
  assert.equal(frontend[0].script, 'dev')
556
579
  assert.equal(frontend[0].packageManager, 'pnpm', 'inferred from pnpm-lock.yaml')
557
580
  })
@@ -1419,10 +1442,12 @@ test('the Git Bash runtime is detected and can be requested explicitly', async (
1419
1442
  assert.equal(pickGitBash([wslBash, gitBash]), gitBash)
1420
1443
  assert.equal(pickGitBash([join(dir, 'missing', 'bash.exe')]), undefined)
1421
1444
 
1422
- // auto: bash when found, PowerShell when not
1423
- 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' })
1424
1448
  assert.deepEqual(resolveWindowsRuntime('powershell', gitBash), { runtime: 'powershell' })
1425
- // 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 })
1426
1451
  assert.throws(() => resolveWindowsRuntime('bash', join(dir, 'missing', 'bash.exe')), /Git Bash/)
1427
1452
  })
1428
1453
 
@@ -1430,6 +1455,14 @@ test('the windows-bash command keeps the POSIX wrapper but uses a Windows classp
1430
1455
  const program = { kind: 'spring', dir: 'C:\\ws\\ris\\m1', mainClass: 'a.B', args: ['--x'], logName: 'm1' }
1431
1456
  const spec = buildStartSpec(program, { workspace: 'C:\\ws', logsDir: 'C:\\ws\\logs', variant: 'windows-bash' })
1432
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'/)
1433
1466
  assert.match(spec.command, /exec java -DJM\.LOG\.PATH=/)
1434
1467
  // ...while a plain POSIX build keeps ':' and target/classes
1435
1468
  const posix = buildStartSpec(program, { workspace: '/w', logsDir: '/w/logs' })
@@ -3021,3 +3054,19 @@ test('fs/window pages a large file and never splits a multi-byte character', asy
3021
3054
  assert.equal(__test.utf8CompleteLength(Buffer.from('ab中', 'utf8')), 5)
3022
3055
  assert.equal(__test.utf8CompleteLength(Buffer.alloc(0)), 0)
3023
3056
  })
3057
+
3058
+ test('a same-named row of another kind is not taken over by an update', () => {
3059
+ // A yds project: the launcher row is `spring`, the discovered frontend row carries
3060
+ // the package.json name — an update must not move the launcher's startCommand onto
3061
+ // the frontend row (that would delete the only way to start the backend).
3062
+ const next = { version: 1, defaults: { jvmArgs: [] }, programs: [
3063
+ { id: 'frontend:fe#start', name: 'c-ass-kk-hans', kind: 'frontend', dir: 'fe', script: 'start' },
3064
+ ] }
3065
+ const oldEntries = [
3066
+ { name: 'c-ass-kk-hans', kind: 'spring', dir: '.', startCommand: 'node x/bin/yds.js start' },
3067
+ ]
3068
+ const merged = mergeConfigDocuments(next, oldEntries, '/ws')
3069
+ assert.equal(merged.programs.length, 2, 'the launcher stays a separate row')
3070
+ assert.equal(merged.programs[0].startCommand, undefined, 'the frontend row keeps its own launch path')
3071
+ assert.equal(merged.programs[1].startCommand, 'node x/bin/yds.js start')
3072
+ })
@@ -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
  }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * An engine left behind by a previous dsh process (the Ctrl+C leak under the old
3
+ * teardown) must be adopted and reported as inherited, not ignored or duplicated.
4
+ *
5
+ * A live janitor means the machine already has an owner for that engine (another
6
+ * dsh, or a watcher about to clean up after a crash) — that engine must NOT be
7
+ * claimed as ours.
8
+ */
9
+ import assert from 'node:assert/strict'
10
+ import { spawn } from 'node:child_process'
11
+ import { existsSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'
12
+ import { connect, createServer } from 'node:net'
13
+ import { tmpdir } from 'node:os'
14
+ import { join } from 'node:path'
15
+ import { fileURLToPath } from 'node:url'
16
+ import { after, test } from 'node:test'
17
+
18
+ const home = mkdtempSync(join(tmpdir(), 'ris-inherit-'))
19
+ const workspace = mkdtempSync(join(tmpdir(), 'ris-inherit-ws-'))
20
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
21
+
22
+ const { __test } = await import('../lib/index.js')
23
+ const { proxyPid, proxyPidPath } = await import('../lib/proxy.js')
24
+ const { janitorStatePath, disarmJanitor } = await import('../lib/janitor.js')
25
+
26
+ const PROXY = fileURLToPath(new URL('../lib/proxy.js', import.meta.url))
27
+ const MARKER = 'dsh-ris-ide-proxy'
28
+ /** @type {import('node:child_process').ChildProcess | null} */
29
+ let engine = null
30
+
31
+ /** @returns {Promise<number>} a port the OS says is free right now. */
32
+ function freePort() {
33
+ return new Promise((resolve) => {
34
+ const server = createServer()
35
+ server.listen(0, '127.0.0.1', () => {
36
+ const { port } = server.address()
37
+ server.close(() => resolve(port))
38
+ })
39
+ })
40
+ }
41
+
42
+ /**
43
+ * Resolve once something accepts a TCP connection on the port.
44
+ * @param {number} port the port to probe.
45
+ * @param {{attempts?: number, interval?: number}} [options] budget.
46
+ * @returns {Promise<boolean>} whether the port accepted a connection.
47
+ */
48
+ function waitForPort(port, { attempts = 60, interval = 100 } = {}) {
49
+ return new Promise((resolve) => {
50
+ let tries = 0
51
+ const attempt = () => {
52
+ const socket = connect({ host: '127.0.0.1', port })
53
+ socket.once('connect', () => { socket.destroy(); resolve(true) })
54
+ socket.once('error', () => {
55
+ socket.destroy()
56
+ tries += 1
57
+ if (tries >= attempts) resolve(false)
58
+ else setTimeout(attempt, interval)
59
+ })
60
+ }
61
+ attempt()
62
+ })
63
+ }
64
+
65
+ /**
66
+ * Poll a predicate until it holds (or the attempts run out).
67
+ * @param {() => boolean} predicate the condition.
68
+ * @param {{attempts?: number, interval?: number}} [options] budget.
69
+ * @returns {Promise<boolean>} whether it held.
70
+ */
71
+ function waitFor(predicate, { attempts = 120, interval = 100 } = {}) {
72
+ return new Promise((resolve) => {
73
+ let tries = 0
74
+ const timer = setInterval(() => {
75
+ tries += 1
76
+ if (predicate()) {
77
+ clearInterval(timer)
78
+ resolve(true)
79
+ } else if (tries >= attempts) {
80
+ clearInterval(timer)
81
+ resolve(false)
82
+ }
83
+ }, interval)
84
+ })
85
+ }
86
+
87
+ /**
88
+ * Spawn a detached engine exactly the way startProxy does, and publish its pidfile.
89
+ * @returns {Promise<{child: import('node:child_process').ChildProcess, port: number}>} the child and its port.
90
+ */
91
+ async function spawnOrphanEngine() {
92
+ const port = await freePort()
93
+ writeFileSync(join(home, 'proxy.json'), JSON.stringify({
94
+ listenPort: port,
95
+ socks: { host: '10.3.91.121', port: 1080 },
96
+ rules: [],
97
+ shadows: [],
98
+ }))
99
+ const child = spawn(process.execPath, [PROXY, '--cwd', workspace, 'serve', `--marker=${MARKER}`], {
100
+ detached: true, stdio: 'ignore', windowsHide: true,
101
+ })
102
+ child.unref()
103
+ writeFileSync(proxyPidPath(), String(child.pid))
104
+ return { child, port }
105
+ }
106
+
107
+ /**
108
+ * Kill a spawned engine (SIGTERM is enough; it exits within the poll budget).
109
+ * @param {import('node:child_process').ChildProcess} child the engine.
110
+ * @returns {Promise<void>} settles when it is gone.
111
+ */
112
+ async function killEngine(child) {
113
+ if (child.exitCode === null) {
114
+ try { child.kill('SIGTERM') } catch { /* already gone */ }
115
+ await waitFor(() => child.exitCode !== null, { attempts: 50, interval: 100 })
116
+ }
117
+ }
118
+
119
+ after(async () => {
120
+ if (engine !== null) await killEngine(engine)
121
+ disarmJanitor()
122
+ rmSync(home, { recursive: true, force: true })
123
+ rmSync(workspace, { recursive: true, force: true })
124
+ })
125
+
126
+ test('an engine with no watcher is adopted and shown as inherited', async () => {
127
+ // The pre-fix crash path: process.exit() killed dsh, the detached engine kept
128
+ // running, and no janitor state survived to name its owner.
129
+ rmSync(janitorStatePath(), { force: true })
130
+ const spawned = await spawnOrphanEngine()
131
+ engine = spawned.child
132
+ const ready = await waitForPort(spawned.port)
133
+ assert.equal(ready, true, 'the engine should start listening in the temp home')
134
+ assert.equal(await waitFor(() => proxyPid() === engine.pid), true, 'the pidfile must identify the engine')
135
+
136
+ const adopted = __test.adoptLeftoverEngine()
137
+ assert.notEqual(adopted, null, 'an engine with no watcher must be adopted')
138
+ assert.equal(adopted.pid, engine.pid)
139
+
140
+ const view = await __test.proxyView(workspace)
141
+ assert.equal(view.running, true, 'the adopted engine is the running one')
142
+ assert.equal(view.inherited, true, 'the dialog must mark it as inherited')
143
+ assert.equal(view.inheritedPid, engine.pid)
144
+ assert.equal(view.inheritedFrom, 0, 'no watcher state means the old dsh pid is unknown')
145
+ assert.equal(view.owner, 0, 'nothing owns it before this process arms the watcher')
146
+ })
147
+
148
+ test('the banner disappears once the adopted engine is gone', async () => {
149
+ assert.notEqual(engine, null)
150
+ await killEngine(engine)
151
+ rmSync(proxyPidPath(), { force: true })
152
+ assert.equal(__test.adoptLeftoverEngine(), null, 'a dead engine is nothing to inherit')
153
+ const view = await __test.proxyView(workspace)
154
+ assert.equal(view.inherited, false)
155
+ })
156
+
157
+ test('a live watcher means the engine has an owner and must not be claimed', async () => {
158
+ const spawned = await spawnOrphanEngine()
159
+ engine = spawned.child
160
+ assert.equal(await waitForPort(spawned.port), true, 'the engine should start listening')
161
+ assert.equal(await waitFor(() => proxyPid() === engine.pid), true, 'the pidfile must identify the engine')
162
+ // A watcher exists and is alive, but it watches a dead dsh: this is the
163
+ // crash-in-progress case — the engine is about to be cleaned up, not ours.
164
+ writeFileSync(janitorStatePath(), JSON.stringify({
165
+ // The watcher pid must be a live process that is NOT us: disarmJanitor() in the
166
+ // teardown would SIGTERM its own test runner otherwise.
167
+ pid: engine.pid,
168
+ owner: 999999,
169
+ log: join(home, 'janitor.log'),
170
+ }))
171
+ assert.equal(__test.adoptLeftoverEngine(), null, 'a live watcher is not ours to take over')
172
+ const view = await __test.proxyView(workspace)
173
+ assert.equal(view.inherited, false, 'the dialog must not claim an engine another watcher owns')
174
+ rmSync(janitorStatePath(), { force: true })
175
+ })