dsh-ris-ide 1.7.3 → 1.8.1

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 (75) hide show
  1. package/README.md +21 -7
  2. package/bin/proxy-janitor.mjs +106 -11
  3. package/bin/risd.mjs +284 -0
  4. package/bin/run-with-log.ps1 +43 -5
  5. package/lib/client.js +609 -1178
  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/proxybridge-health.js +206 -0
  11. package/lib/redirector.js +1615 -115
  12. package/lib/risd/build.js +91 -0
  13. package/lib/risd/debug.js +374 -0
  14. package/lib/risd/git.js +207 -0
  15. package/lib/risd/leases.js +124 -0
  16. package/lib/risd/lifecycle.js +148 -0
  17. package/lib/risd/log.js +59 -0
  18. package/lib/risd/ping.js +94 -0
  19. package/lib/risd/programs.js +348 -0
  20. package/lib/risd/server.js +1919 -0
  21. package/lib/risd/state.js +137 -0
  22. package/lib/risd/ui.js +1989 -0
  23. package/lib/risd/view.js +79 -0
  24. package/lib/risd-client.js +282 -0
  25. package/lib/standalone/window.html +14 -16
  26. package/lib/startup.js +114 -0
  27. package/package.json +4 -1
  28. package/test/client-build.test.mjs +113 -0
  29. package/test/client-viewer.test.mjs +279 -227
  30. package/test/dsh-origin.test.mjs +140 -0
  31. package/test/dsh-window-refresh.test.mjs +100 -0
  32. package/test/harness.test.mjs +9 -0
  33. package/test/host-noloop.test.mjs +74 -0
  34. package/test/host-tail.test.mjs +21 -4
  35. package/test/host-window.test.mjs +4 -4
  36. package/test/janitor.test.mjs +29 -1
  37. package/test/lifecycle.test.mjs +26 -5
  38. package/test/merge-owners.test.mjs +155 -0
  39. package/test/proxy-restart.test.mjs +39 -0
  40. package/test/proxy-window.test.mjs +45 -0
  41. package/test/proxy.test.mjs +41 -0
  42. package/test/proxybridge-bundle.test.mjs +687 -0
  43. package/test/proxybridge-health.test.mjs +116 -0
  44. package/test/redirector-bundle.test.mjs +391 -0
  45. package/test/redirector.test.mjs +413 -10
  46. package/test/risd-api.test.mjs +514 -0
  47. package/test/risd-bridge-degrade.test.mjs +101 -0
  48. package/test/risd-build.test.mjs +20 -0
  49. package/test/risd-cli-home.test.mjs +50 -0
  50. package/test/risd-client.test.mjs +130 -0
  51. package/test/risd-debug.test.mjs +261 -0
  52. package/test/risd-election.test.mjs +104 -0
  53. package/test/risd-engine.test.mjs +132 -0
  54. package/test/risd-entry.test.mjs +118 -0
  55. package/test/risd-git.test.mjs +109 -0
  56. package/test/risd-handoff.test.mjs +116 -0
  57. package/test/risd-heal.test.mjs +50 -0
  58. package/test/risd-helpers.mjs +108 -0
  59. package/test/risd-host-p2.test.mjs +147 -0
  60. package/test/risd-janitor-guard.test.mjs +46 -0
  61. package/test/risd-lease.test.mjs +83 -0
  62. package/test/risd-lifecycle.test.mjs +210 -0
  63. package/test/risd-log-follow.test.mjs +227 -0
  64. package/test/risd-mode.test.mjs +161 -0
  65. package/test/risd-ping.test.mjs +99 -0
  66. package/test/risd-programs.test.mjs +169 -0
  67. package/test/risd-restart.test.mjs +104 -0
  68. package/test/risd-review-p2.test.mjs +217 -0
  69. package/test/risd-shutdown.test.mjs +97 -0
  70. package/test/risd-teardown.test.mjs +87 -0
  71. package/test/risd-tools.test.mjs +211 -0
  72. package/test/risd-ui.test.mjs +607 -0
  73. package/test/risd-write.test.mjs +170 -0
  74. package/test/startup-reconcile.test.mjs +100 -0
  75. package/test/windows.test.mjs +37 -2
@@ -0,0 +1,161 @@
1
+ /**
2
+ * daemonMode: the plugin can borrow risd for the READ-ONLY proxy view.
3
+ *
4
+ * The engine still belongs to the plugin in Phase 1a — the daemon only serves the
5
+ * table, and a missing/unreachable daemon must fall back to the in-process view
6
+ * without breaking the dialog. These tests pin both halves.
7
+ */
8
+ import assert from 'node:assert/strict'
9
+ import { existsSync, mkdtempSync, rmSync } from 'node:fs'
10
+ import { tmpdir } from 'node:os'
11
+ import { join } from 'node:path'
12
+ import { Readable } from 'node:stream'
13
+ import { after, test } from 'node:test'
14
+
15
+ // Set the isolation env BEFORE the plugin module is imported (it reads the proxy
16
+ // home and the daemon port at call time, but the same home must be used by both).
17
+ const home = mkdtempSync(join(tmpdir(), 'ris-risd-mode-'))
18
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
19
+ process.env.DSH_RISD_PORT = '0'
20
+
21
+ const { apply, __test } = await import('../lib/index.js')
22
+ const { janitorStatus, disarmJanitor } = await import('../lib/janitor.js')
23
+ const { readRisdState, risdStatePath } = await import('../lib/risd/state.js')
24
+ const { shutdownRisd } = await import('../lib/risd-client.js')
25
+ const { removeHome, sleep } = await import('./risd-helpers.mjs')
26
+
27
+ function fakeRes() {
28
+ return {
29
+ status: 0,
30
+ headers: {},
31
+ chunks: [],
32
+ writeHead(status, headers) { this.status = status; this.headers = headers },
33
+ write(chunk) { this.chunks.push(String(chunk)); return true },
34
+ end(chunk) { if (chunk !== undefined) this.chunks.push(String(chunk)) },
35
+ json() { return JSON.parse(this.chunks.join('')) },
36
+ }
37
+ }
38
+
39
+ function fakeReq(method, url) {
40
+ const req = Readable.from([])
41
+ req.method = method
42
+ req.url = url
43
+ req.headers = { host: '127.0.0.1:3080', 'content-type': 'application/json' }
44
+ return req
45
+ }
46
+
47
+ function fakeCtx(cwd) {
48
+ const disposers = []
49
+ return {
50
+ effect(fn) {
51
+ const dispose = fn()
52
+ if (typeof dispose === 'function') disposers.push(dispose)
53
+ },
54
+ webServer: { register: () => () => {} },
55
+ tools: { register: () => {} },
56
+ logger: { warn: () => {} },
57
+ sessions: { get: () => ({ header: { cwd } }) },
58
+ dispose() {
59
+ while (disposers.length > 0) disposers.pop()()
60
+ },
61
+ }
62
+ }
63
+
64
+ async function waitFor(predicate, timeoutMs = 8000) {
65
+ const deadline = Date.now() + timeoutMs
66
+ while (Date.now() < deadline) {
67
+ if (await predicate()) return true
68
+ await sleep(100)
69
+ }
70
+ return false
71
+ }
72
+
73
+ after(async () => {
74
+ const state = readRisdState(home)
75
+ if (state !== null) await shutdownRisd(state)
76
+ disarmJanitor()
77
+ rmSync(home, { recursive: true, force: true })
78
+ })
79
+
80
+ test('daemonMode=off never spawns risd', async () => {
81
+ const dir = mkdtempSync(join(tmpdir(), 'ris-risd-off-'))
82
+ try {
83
+ const ctx = fakeCtx(dir)
84
+ apply(ctx, { daemonMode: 'off' })
85
+ await sleep(400)
86
+ assert.equal(existsSync(risdStatePath(home)), false, 'no daemon state without daemonMode=auto')
87
+
88
+ const res = fakeRes()
89
+ await __test.serveProxy(ctx, fakeReq('GET', '/dsh-ris-ide/proxy?sessionId=s1'), res)
90
+ const body = res.json()
91
+ assert.equal(res.status, 200)
92
+ assert.equal(body.daemon, undefined, 'the local view carries no daemon section')
93
+ assert.equal(body.workspace, dir)
94
+ assert.equal(body.rules.length >= 2, true)
95
+ ctx.dispose()
96
+ } finally {
97
+ rmSync(dir, { recursive: true, force: true })
98
+ }
99
+ })
100
+
101
+ test('daemonMode auto serves the view from risd, then falls back when it dies', async () => {
102
+ const dir = mkdtempSync(join(tmpdir(), 'ris-risd-auto-'))
103
+ try {
104
+ const ctx = fakeCtx(dir)
105
+ apply(ctx, { daemonMode: 'auto' })
106
+
107
+ const up = await waitFor(() => readRisdState(home) !== null)
108
+ assert.equal(up, true, 'daemonMode=auto must spawn risd')
109
+ const state = readRisdState(home)
110
+
111
+ // The view is served by the daemon (it adds the `daemon` section) and the
112
+ // plugin still decorates rules + inherited fields locally.
113
+ let body = null
114
+ const forwarded = await waitFor(async () => {
115
+ const res = fakeRes()
116
+ await __test.serveProxy(ctx, fakeReq('GET', '/dsh-ris-ide/proxy?sessionId=s1'), res)
117
+ const parsed = res.json()
118
+ if (parsed.daemon === undefined) return false
119
+ body = parsed
120
+ return true
121
+ })
122
+ assert.equal(forwarded, true, 'GET must be served by the daemon once it is up')
123
+ assert.equal(body.daemon.pid, state.pid)
124
+ assert.equal(body.workspace, dir)
125
+ assert.equal(Array.isArray(body.rules), true)
126
+ assert.equal(body.rules.length >= 2, true)
127
+ assert.equal(typeof body.inherited, 'boolean')
128
+
129
+ // The lease belongs to this plugin process and survives until dispose.
130
+ const status = await (await fetch(`${state.url}/v1/status?cwd=${encodeURIComponent(dir)}`, {
131
+ headers: { authorization: `Bearer ${state.token}`, 'x-risd-api-version': '1' },
132
+ })).json()
133
+ assert.equal(status.daemon.leases >= 1, true)
134
+
135
+ ctx.dispose()
136
+ assert.equal(await waitFor(async () => {
137
+ const view = await (await fetch(`${state.url}/v1/status?cwd=${encodeURIComponent(dir)}`, {
138
+ headers: { authorization: `Bearer ${state.token}`, 'x-risd-api-version': '1' },
139
+ })).json()
140
+ return view.daemon.leases === 0
141
+ }), true, 'dispose releases the lease (the daemon itself keeps running)')
142
+ assert.equal(readRisdState(home)?.pid, state.pid, 'dispose must NOT stop the daemon')
143
+
144
+ // Kill the daemon: the next GET falls back to the in-process view.
145
+ const kill = await fetch(`${state.url}/v1/shutdown`, {
146
+ method: 'POST',
147
+ headers: { authorization: `Bearer ${state.token}`, 'x-risd-api-version': '1' },
148
+ })
149
+ assert.equal(kill.status, 200)
150
+ await waitFor(() => readRisdState(home) === null)
151
+
152
+ const res = fakeRes()
153
+ await __test.serveProxy(ctx, fakeReq('GET', '/dsh-ris-ide/proxy?sessionId=s1'), res)
154
+ const fallback = res.json()
155
+ assert.equal(res.status, 200)
156
+ assert.equal(fallback.daemon, undefined)
157
+ assert.equal(fallback.workspace, dir)
158
+ } finally {
159
+ rmSync(dir, { recursive: true, force: true })
160
+ }
161
+ })
@@ -0,0 +1,99 @@
1
+ // The proxy tab's reachability chip. It must tell three states apart — a working
2
+ // SOCKS5 upstream, a port that answers but is not SOCKS5, and nothing listening —
3
+ // because the old UI showed "unreachable" only after a failed reload.
4
+ import assert from 'node:assert/strict'
5
+ import { createServer } from 'node:net'
6
+ import test from 'node:test'
7
+
8
+ import { pingSocks } from '../lib/risd/ping.js'
9
+
10
+ /** A server that answers the SOCKS5 greeting with `reply`. */
11
+ function fakeServer(reply) {
12
+ return new Promise((resolve) => {
13
+ const server = createServer((socket) => {
14
+ socket.once('data', () => socket.write(reply))
15
+ })
16
+ server.listen(0, '127.0.0.1', () => resolve({ server, port: server.address().port }))
17
+ })
18
+ }
19
+
20
+ test('a SOCKS5 server that accepts no-auth reports connected with a time', async () => {
21
+ const { server, port } = await fakeServer(Buffer.from([0x05, 0x00]))
22
+ try {
23
+ const result = await pingSocks({ host: '127.0.0.1', port, timeoutMs: 1500 })
24
+ assert.equal(result.ok, true)
25
+ assert.equal(result.socks, true)
26
+ assert.equal(result.host, '127.0.0.1')
27
+ assert.equal(result.port, port)
28
+ assert.ok(Number.isInteger(result.ms) && result.ms >= 0)
29
+ assert.equal(typeof result.at, 'string')
30
+ } finally {
31
+ server.close()
32
+ }
33
+ })
34
+
35
+ test('a port that answers but is not SOCKS5 is amber, not silently fine', async () => {
36
+ const { server, port } = await fakeServer(Buffer.from('HTTP/1.1 400 Bad Request\r\n'))
37
+ try {
38
+ const result = await pingSocks({ host: '127.0.0.1', port, timeoutMs: 1500 })
39
+ assert.equal(result.ok, false)
40
+ assert.equal(result.socks, false)
41
+ assert.match(result.error, /不是 SOCKS5/)
42
+ } finally {
43
+ server.close()
44
+ }
45
+ })
46
+
47
+ test('a SOCKS5 server that demands authentication is reported as requiring it', async () => {
48
+ const { server, port } = await fakeServer(Buffer.from([0x05, 0x02]))
49
+ try {
50
+ const result = await pingSocks({ host: '127.0.0.1', port, timeoutMs: 1500 })
51
+ assert.equal(result.ok, false)
52
+ assert.equal(result.socks, true)
53
+ assert.match(result.error, /认证/)
54
+ } finally {
55
+ server.close()
56
+ }
57
+ })
58
+
59
+ test('nothing listening is a clear "refused" answer, never a throw', async () => {
60
+ // Bind and close to get a port that is almost certainly free.
61
+ const { server, port } = await fakeServer(Buffer.from([0x05, 0x00]))
62
+ await new Promise((resolve) => server.close(resolve))
63
+ const result = await pingSocks({ host: '127.0.0.1', port, timeoutMs: 800 })
64
+ assert.equal(result.ok, false)
65
+ assert.equal(result.socks, false)
66
+ assert.match(result.error, /拒绝|超时|重置|失败/)
67
+ })
68
+
69
+ test('a missing host or a bad port is answered without opening a socket', async () => {
70
+ const empty = await pingSocks({ host: '', port: 1080 })
71
+ assert.equal(empty.ok, false)
72
+ assert.match(empty.error, /未配置/)
73
+
74
+ let opened = 0
75
+ const spy = () => { opened += 1; throw new Error('must not connect') }
76
+ const badPort = await pingSocks({ host: '127.0.0.1', port: 0, connect: spy })
77
+ assert.equal(badPort.ok, false)
78
+ assert.equal(opened, 0)
79
+ })
80
+
81
+ test('a peer that accepts then closes without answering is reported immediately (review A3-P2-2)', async () => {
82
+ // A SOCKS server that dies right after accept used to look identical to a slow
83
+ // one for the full timeout: the chip said 「连接超时」 2 s later. A FIN is an
84
+ // answer, so report it as such.
85
+ const server = createServer((socket) => socket.destroy())
86
+ const port = await new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server.address().port)))
87
+ try {
88
+ const started = Date.now()
89
+ const result = await pingSocks({ host: '127.0.0.1', port, timeoutMs: 2000 })
90
+ const elapsed = Date.now() - started
91
+ assert.equal(result.ok, false)
92
+ assert.equal(result.socks, false)
93
+ assert.match(result.error, /连接被关闭|连接被重置/)
94
+ assert.ok(elapsed < 1200, `a FIN must not wait for the timeout (took ${elapsed} ms)`)
95
+ } finally {
96
+ server.close()
97
+ }
98
+ })
99
+
@@ -0,0 +1,169 @@
1
+ // Daemon-side program supervisor: the panel rows, start/stop, and offset-based log reads.
2
+ // The rows are the same ones the plugin renders (one discovery pipeline), so a program
3
+ // started here keeps running after dsh exits and is visible from another dsh.
4
+ import assert from 'node:assert/strict'
5
+ import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync, rmSync } from 'node:fs'
6
+ import { request } from 'node:http'
7
+ import { tmpdir } from 'node:os'
8
+ import { join } from 'node:path'
9
+ import { after, before, test } from 'node:test'
10
+ import { sleep } from './risd-helpers.mjs'
11
+ import { startRisdProcess } from './risd-helpers.mjs'
12
+
13
+ let daemon
14
+ let workspace
15
+
16
+ function api(state, path, { method = 'GET', body } = {}) {
17
+ return new Promise((resolve) => {
18
+ const payload = body === undefined ? '' : JSON.stringify(body)
19
+ const req = request({
20
+ host: '127.0.0.1',
21
+ port: state.port,
22
+ path,
23
+ method,
24
+ timeout: 8000,
25
+ headers: Object.assign(
26
+ { authorization: `Bearer ${state.token}`, 'x-risd-api-version': '1' },
27
+ payload === '' ? {} : { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) },
28
+ ),
29
+ }, (res) => {
30
+ let text = ''
31
+ res.setEncoding('utf8')
32
+ res.on('data', (chunk) => { text += chunk })
33
+ res.on('end', () => {
34
+ let parsed = null
35
+ try { parsed = JSON.parse(text) } catch { parsed = null }
36
+ resolve({ status: res.statusCode, body: parsed })
37
+ })
38
+ })
39
+ req.on('error', (error) => resolve({ status: 0, body: { error: String(error?.message) } }))
40
+ if (payload !== '') req.write(payload)
41
+ req.end()
42
+ })
43
+ }
44
+
45
+ before(async () => {
46
+ workspace = mkdtempSync(join(tmpdir(), 'risd-programs-ws-'))
47
+ mkdirSync(join(workspace, '.dsh-ris-ide'), { recursive: true })
48
+ // A custom row keeps the test independent of npm/maven: exactly the shape the panel
49
+ // writes for a command it does not discover by itself.
50
+ writeFileSync(join(workspace, '.dsh-ris-ide', 'config.json'), `${JSON.stringify({
51
+ version: 1,
52
+ defaults: {},
53
+ programs: [{
54
+ id: 'demo',
55
+ name: 'demo',
56
+ kind: 'custom',
57
+ dir: workspace,
58
+ relDir: '.',
59
+ project: '',
60
+ logName: 'demo',
61
+ startCommand: `${JSON.stringify(process.execPath)} -e "setInterval(() => {}, 60000)"`,
62
+ stopGraceMs: 3000,
63
+ }],
64
+ }, null, 2)}\n`, 'utf8')
65
+ daemon = await startRisdProcess({ port: 0 })
66
+ })
67
+
68
+ after(async () => {
69
+ if (daemon !== undefined) await daemon.stop()
70
+ if (workspace !== undefined) rmSync(workspace, { recursive: true, force: true })
71
+ })
72
+
73
+ test('GET /v1/programs lists the panel rows from the daemon', async () => {
74
+ const res = await api(daemon.state, `/v1/programs?cwd=${encodeURIComponent(workspace)}`)
75
+ assert.equal(res.status, 200)
76
+ assert.equal(res.body.ok, true)
77
+ const demo = res.body.programs.find((row) => row.id === 'demo')
78
+ assert.ok(demo !== undefined, 'custom row is present')
79
+ assert.equal(demo.logName, 'demo')
80
+ assert.equal(res.body.dir, join(workspace, 'logs'))
81
+ })
82
+
83
+ test('start, stop and restart a program from the daemon', async () => {
84
+ const started = await api(daemon.state, '/v1/programs', { method: 'POST', body: { cwd: workspace, action: 'start', id: 'demo' } })
85
+ assert.equal(started.status, 200)
86
+ assert.equal(started.body.ok, true)
87
+ assert.ok(Number.isInteger(started.body.pid), 'a pid came back')
88
+ await sleep(300)
89
+ const listed = await api(daemon.state, `/v1/programs?cwd=${encodeURIComponent(workspace)}`)
90
+ const demo = listed.body.programs.find((row) => row.id === 'demo')
91
+ assert.equal(demo.running.alive, true)
92
+ assert.equal(existsSync(demo.logPath), true)
93
+
94
+ const restarted = await api(daemon.state, '/v1/programs', { method: 'POST', body: { cwd: workspace, action: 'restart', id: 'demo' } })
95
+ assert.equal(restarted.status, 200)
96
+ assert.equal(restarted.body.ok, true)
97
+ assert.equal(restarted.body.stopped?.stopped, true)
98
+
99
+ const stopped = await api(daemon.state, '/v1/programs', { method: 'POST', body: { cwd: workspace, action: 'stop', id: 'demo' } })
100
+ assert.equal(stopped.status, 200)
101
+ assert.equal(stopped.body.ok, true)
102
+ const afterStop = await api(daemon.state, `/v1/programs?cwd=${encodeURIComponent(workspace)}`)
103
+ const stoppedRow = afterStop.body.programs.find((row) => row.id === 'demo')
104
+ assert.ok(stoppedRow !== undefined, 'row still listed after stop')
105
+ assert.ok(!stoppedRow.running?.alive, 'not running after stop')
106
+ })
107
+
108
+ test('log reads page by byte offset for a follower', async () => {
109
+ const logPath = join(workspace, 'logs', 'demo.log')
110
+ mkdirSync(join(workspace, 'logs'), { recursive: true })
111
+ writeFileSync(logPath, 'first line\n', 'utf8')
112
+ const first = await api(daemon.state, `/v1/programs/log?cwd=${encodeURIComponent(workspace)}&id=demo`)
113
+ assert.equal(first.status, 200)
114
+ assert.equal(first.body.ok, true)
115
+ assert.match(first.body.text, /first line/)
116
+ const offset = first.body.nextOffset
117
+ appendFileSync(logPath, 'second line\n', 'utf8')
118
+ const follow = await api(daemon.state, `/v1/programs/log?cwd=${encodeURIComponent(workspace)}&id=demo&offset=${offset}`)
119
+ assert.equal(follow.status, 200)
120
+ assert.equal(follow.body.text, 'second line\n')
121
+ assert.ok(follow.body.nextOffset > offset)
122
+ })
123
+
124
+ test('an unknown program is a 404 with a readable message', async () => {
125
+ const res = await api(daemon.state, '/v1/programs', { method: 'POST', body: { cwd: workspace, action: 'start', id: 'nope' } })
126
+ assert.equal(res.status, 404)
127
+ assert.equal(res.body.ok, false)
128
+ assert.match(String(res.body.message), /nope/)
129
+ })
130
+
131
+ test('a log read past EOF carries reset so the caller replaces the tail', async () => {
132
+ const logPath = join(workspace, 'logs', 'demo.log')
133
+ mkdirSync(join(workspace, 'logs'), { recursive: true })
134
+ writeFileSync(logPath, 'small\n', 'utf8')
135
+ const res = await api(daemon.state, `/v1/programs/log?cwd=${encodeURIComponent(workspace)}&id=demo&offset=9999`)
136
+ assert.equal(res.status, 200)
137
+ assert.equal(res.body.reset, true)
138
+ assert.equal(res.body.text, 'small\n')
139
+ })
140
+
141
+ test('a name shared by two rows is a 409 instead of the first row', async () => {
142
+ const configPath = join(workspace, '.dsh-ris-ide', 'config.json')
143
+ const original = readFileSync(configPath, 'utf8')
144
+ try {
145
+ writeFileSync(configPath, `${JSON.stringify({
146
+ version: 1,
147
+ defaults: {},
148
+ programs: [
149
+ { id: 'dup-a', name: 'dup', kind: 'custom', dir: workspace, relDir: '.', project: '', logName: 'dup-a', startCommand: 'true' },
150
+ { id: 'dup-b', name: 'dup', kind: 'custom', dir: workspace, relDir: '.', project: '', logName: 'dup-b', startCommand: 'true' },
151
+ { id: 'demo', name: 'demo', kind: 'custom', dir: workspace, relDir: '.', project: '', logName: 'demo', startCommand: 'true' },
152
+ ],
153
+ })}\n`, 'utf8')
154
+ const ambiguous = await api(daemon.state, '/v1/programs', { method: 'POST', body: { cwd: workspace, action: 'start', id: 'dup' } })
155
+ assert.equal(ambiguous.status, 409)
156
+ assert.equal(ambiguous.body.code, 'ambiguous')
157
+ assert.match(String(ambiguous.body.message), /dup-a/)
158
+ assert.match(String(ambiguous.body.message), /dup-b/)
159
+ // The id still resolves, so a disambiguated caller keeps working.
160
+ const logPath = join(workspace, 'logs', 'dup-a.log')
161
+ mkdirSync(join(workspace, 'logs'), { recursive: true })
162
+ writeFileSync(logPath, 'a\n', 'utf8')
163
+ const log = await api(daemon.state, `/v1/programs/log?cwd=${encodeURIComponent(workspace)}&id=dup-a`)
164
+ assert.equal(log.status, 200)
165
+ assert.equal(log.body.text, 'a\n')
166
+ } finally {
167
+ writeFileSync(configPath, original, 'utf8')
168
+ }
169
+ })
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Daemon restart helpers (review A4-P2-5/P2-6/P2-7).
3
+ *
4
+ * `POST /v1/restart` cannot be exercised end-to-end from a unit test without
5
+ * replacing the real daemon, so the two pieces that carry the behaviour are tested
6
+ * directly: the successor argv (port + pid identity) and the wait that keeps a
7
+ * successor from stealing the port or waiting on a reused pid.
8
+ */
9
+ import assert from 'node:assert/strict'
10
+ import test from 'node:test'
11
+ import { spawn } from 'node:child_process'
12
+ import { __test, readStartTime, successorArgs, waitForPidExit } from '../lib/risd/server.js'
13
+
14
+ /** Spawn a detached-ish node child that lives for `ms`; returns {child, done}. */
15
+ function liveChild(ms) {
16
+ const child = spawn(process.execPath, ['-e', `setTimeout(() => {}, ${ms})`], { stdio: 'ignore' })
17
+ const done = new Promise((resolve) => child.once('exit', resolve))
18
+ return { child, done }
19
+ }
20
+
21
+ test('the successor keeps the port the daemon actually bound and the pid identity (A4-P2-6/A4-P2-5)', () => {
22
+ const argv = successorArgs({ pid: 4321, port: 11082, startTime: '987654' })
23
+ assert.equal(argv[1], 'serve', 'the CLI is asked to serve')
24
+ assert.deepEqual(argv.slice(2, 4), ['--wait-pid', '4321'], 'it waits for this daemon pid')
25
+ assert.deepEqual(argv.slice(argv.indexOf('--port'), argv.indexOf('--port') + 2), ['--port', '11082'], 'it binds the same port, not the default')
26
+ assert.deepEqual(argv.slice(argv.indexOf('--wait-start'), argv.indexOf('--wait-start') + 2), ['--wait-start', '987654'], 'it carries the start time that proves the pid identity')
27
+
28
+ const defaulted = successorArgs({ pid: 7, port: 0, startTime: '' })
29
+ assert.equal(defaulted.includes('--port'), false, 'port 0 means "let the OS choose", never --port 0')
30
+ assert.equal(defaulted.includes('--wait-start'), false, 'no start time on platforms without /proc')
31
+ assert.deepEqual(defaulted.slice(2, 4), ['--wait-pid', '7'])
32
+ })
33
+
34
+ test('waitForPidExit resolves as soon as the predecessor exits', async (t) => {
35
+ const { child, done } = liveChild(400)
36
+ t.after(() => child.kill('SIGKILL'))
37
+ const startedAt = Date.now()
38
+ const result = await waitForPidExit(child.pid, 5000)
39
+ const elapsed = Date.now() - startedAt
40
+ assert.deepEqual(result, { ok: true, timedOut: false })
41
+ assert.ok(elapsed >= 50, `waited at least one poll tick (${elapsed}ms)`)
42
+ await done
43
+ })
44
+
45
+ test('a reused pid is treated as exited instead of waited on (A4-P2-5)', async (t) => {
46
+ if (process.platform !== 'linux') return t.skip('start times come from /proc')
47
+ const { child } = liveChild(10_000)
48
+ t.after(() => child.kill('SIGKILL'))
49
+ const startedAt = Date.now()
50
+ // '1' is a valid-looking start time but cannot match this fresh child.
51
+ const result = await waitForPidExit(child.pid, 5000, '1')
52
+ const elapsed = Date.now() - startedAt
53
+ assert.deepEqual(result, { ok: true, timedOut: false }, 'a different start time proves the old process is gone')
54
+ assert.ok(elapsed < 1500, `did not wait for the unrelated process to exit (${elapsed}ms)`)
55
+ })
56
+
57
+ test('a live pid with the matching start time makes waitForPidExit time out (A4-P2-5)', async (t) => {
58
+ if (process.platform !== 'linux') return t.skip('start times come from /proc')
59
+ const startTime = readStartTime(process.pid)
60
+ assert.match(startTime, /^\d+$/, '/proc/<pid>/stat exposes a numeric start time')
61
+ const startedAt = Date.now()
62
+ const result = await waitForPidExit(process.pid, 150, startTime)
63
+ const elapsed = Date.now() - startedAt
64
+ assert.deepEqual(result, { ok: false, timedOut: true })
65
+ assert.ok(elapsed >= 150, `honoured the deadline (${elapsed}ms)`)
66
+ })
67
+
68
+ test('without a start time the wait falls back to kill(0) and still times out', async (t) => {
69
+ const { child } = liveChild(10_000)
70
+ t.after(() => child.kill('SIGKILL'))
71
+ const result = await waitForPidExit(child.pid, 200, '')
72
+ assert.deepEqual(result, { ok: false, timedOut: true })
73
+ })
74
+
75
+ test('a failed successor spawn clears restarting so a retry can work (A4-P2-7)', (t) => {
76
+ const original = __test.restartHooks.spawn
77
+ t.after(() => { __test.restartHooks.spawn = original; __test.setRestarting(false) })
78
+ __test.restartHooks.spawn = () => { throw new Error('spawn EACCES') }
79
+ __test.setRestarting(true)
80
+ const child = __test.spawnRestartSuccessor(11082)
81
+ assert.equal(child, null)
82
+ assert.equal(__test.isRestarting(), false, 'the next POST must be able to try again')
83
+ })
84
+
85
+ test('the spawned successor carries the live port and a dying child clears restarting (A4-P2-6/A4-P2-7)', (t) => {
86
+ const original = __test.restartHooks.spawn
87
+ const handlers = {}
88
+ const fake = { unref() {}, once(event, fn) { handlers[event] = fn; return this } }
89
+ const calls = []
90
+ t.after(() => { __test.restartHooks.spawn = original; __test.setRestarting(false) })
91
+ __test.restartHooks.spawn = (...args) => { calls.push(args); return fake }
92
+ __test.setRestarting(true)
93
+ assert.equal(__test.spawnRestartSuccessor(11082), fake)
94
+ assert.equal(__test.isRestarting(), true, 'a pending successor keeps the restart flag set')
95
+ const argv = calls[0][1]
96
+ assert.equal(argv[1], 'serve')
97
+ assert.ok(argv.includes('--wait-pid'), 'the successor waits for this pid')
98
+ assert.deepEqual(argv.slice(argv.indexOf('--port'), argv.indexOf('--port') + 2), ['--port', '11082'], 'the successor binds the port this daemon actually bound')
99
+ handlers.error(new Error('ENOENT'))
100
+ assert.equal(__test.isRestarting(), false, 'a spawn error must not leave the daemon marked as restarting')
101
+ __test.setRestarting(true)
102
+ handlers.exit(3, null)
103
+ assert.equal(__test.isRestarting(), false, 'a successor exiting non-zero must not leave the daemon marked as restarting')
104
+ })