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,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,217 @@
1
+ /**
2
+ * Regressions for the P2 findings of the 2026-11-09 expert review that live on
3
+ * the daemon's HTTP surface (A report) plus the client/log helpers.
4
+ *
5
+ * Each case names the finding it pins (A-P2-x) so a future reader can trace it
6
+ * back to work/reviews/20261109-risd/A-daemon-core.md.
7
+ */
8
+ import assert from 'node:assert/strict'
9
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
10
+ import { request } from 'node:http'
11
+ import { tmpdir } from 'node:os'
12
+ import { join } from 'node:path'
13
+ import test, { after } from 'node:test'
14
+ import { looksAbsolutePath, startRisd } from '../lib/risd/server.js'
15
+ import { createRisdLogger, risdLogPath } from '../lib/risd/log.js'
16
+ import { reconcileStartupLeftovers } from '../lib/startup.js'
17
+ import { ensureRisd } from '../lib/risd-client.js'
18
+ import { RISD_API_VERSION, risdStatePath, writeRisdState } from '../lib/risd/state.js'
19
+ import { makeHome, removeHome, runRisdCli, sleep, startRisdProcess } from './risd-helpers.mjs'
20
+ import { pidAlive } from '../lib/proxy.js'
21
+
22
+ const homes = []
23
+ function home() {
24
+ const dir = makeHome('risd-p2-')
25
+ homes.push(dir)
26
+ return dir
27
+ }
28
+ after(() => {
29
+ for (const dir of homes) removeHome(dir)
30
+ })
31
+
32
+ function httpJson(port, path, { method = 'GET', body = null, raw = null, token = null } = {}) {
33
+ return new Promise((resolve) => {
34
+ const payload = raw !== null ? raw : body === null ? null : JSON.stringify(body)
35
+ const req = request({
36
+ host: '127.0.0.1',
37
+ port,
38
+ path,
39
+ method,
40
+ headers: {
41
+ ...(payload === null ? {} : { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) }),
42
+ ...(token === null ? {} : { authorization: `Bearer ${token}`, 'x-risd-api-version': String(RISD_API_VERSION) }),
43
+ },
44
+ }, (res) => {
45
+ const chunks = []
46
+ res.on('data', (chunk) => chunks.push(chunk))
47
+ res.on('end', () => {
48
+ const text = Buffer.concat(chunks).toString('utf8')
49
+ let parsed = null
50
+ try { parsed = JSON.parse(text) } catch { /* not json */ }
51
+ resolve({ status: res.statusCode, body: parsed, text })
52
+ })
53
+ })
54
+ req.on('error', (error) => resolve({ status: 0, body: null, text: '', error: String(error.message) }))
55
+ if (payload !== null) req.write(payload)
56
+ req.end()
57
+ })
58
+ }
59
+
60
+ test('absolute paths are recognised on both platforms (A-P1-3)', () => {
61
+ assert.equal(looksAbsolutePath('/tmp/demo'), true)
62
+ assert.equal(looksAbsolutePath('C:\\work\\demo'), true)
63
+ assert.equal(looksAbsolutePath('\\\\server\\share\\demo'), true)
64
+ assert.equal(looksAbsolutePath('relative/demo'), false)
65
+ assert.equal(looksAbsolutePath(''), false)
66
+ assert.equal(looksAbsolutePath(null), false)
67
+ })
68
+
69
+ test('an oversized body gets a 413 answer instead of a broken socket (A-P2-6)', async () => {
70
+ const started = await startRisdProcess({ home: home() })
71
+ try {
72
+ const huge = JSON.stringify({ action: 'start', cwd: '/tmp', pad: 'x'.repeat(70 * 1024) })
73
+ const response = await httpJson(started.state.port, '/v1/leases', {
74
+ method: 'POST',
75
+ raw: huge,
76
+ token: started.state.token,
77
+ })
78
+ assert.equal(response.status, 413)
79
+ assert.equal(response.body?.code, 'too-large')
80
+ } finally {
81
+ await started.stop()
82
+ }
83
+ })
84
+
85
+ test('/v1/config reports real values only (A-P2-3)', async () => {
86
+ const started = await startRisdProcess({ home: home() })
87
+ try {
88
+ const response = await httpJson(started.state.port, '/v1/config', { token: started.state.token })
89
+ assert.equal(response.status, 200)
90
+ assert.equal(response.body.idleExitMs, 10 * 60 * 1000)
91
+ assert.equal(response.body.engineRestart, undefined)
92
+ assert.ok(response.body.lifecycle)
93
+ } finally {
94
+ await started.stop()
95
+ }
96
+ })
97
+
98
+ test('/v1/dsh ignores windows whose url is not a loopback http(s) origin (A-P2-10)', async () => {
99
+ const dir = home()
100
+ const started = await startRisdProcess({ home: dir })
101
+ try {
102
+ writeFileSync(join(dir, 'dsh-window.json'), JSON.stringify({
103
+ windows: [
104
+ { url: 'https://evil.example.com', sessionId: 's-evil', cwd: '/tmp/evil', at: new Date().toISOString() },
105
+ { url: `http://127.0.0.1:${started.state.port}`, sessionId: 's-ok', cwd: '/tmp/demo-workspace', at: new Date().toISOString() },
106
+ ],
107
+ }), { mode: 0o600 })
108
+ const response = await httpJson(started.state.port, '/v1/dsh', { token: started.state.token })
109
+ assert.equal(response.status, 200)
110
+ assert.deepEqual(response.body.windows.map((row) => row.sessionId), ['s-ok'])
111
+ } finally {
112
+ await started.stop()
113
+ }
114
+ })
115
+
116
+ test('a conflicting write reports the current view (A-P2-1)', async () => {
117
+ const dir = home()
118
+ const started = await startRisdProcess({ home: dir })
119
+ try {
120
+ const auth = { token: started.state.token }
121
+ const current = await httpJson(started.state.port, '/v1/proxy', auth)
122
+ assert.equal(current.status, 200)
123
+ const stale = await httpJson(started.state.port, '/v1/proxy', {
124
+ ...auth,
125
+ method: 'POST',
126
+ body: {
127
+ cwd: '/tmp',
128
+ revision: 'definitely-stale',
129
+ config: { socks: { host: '127.0.0.1', port: 1 }, listenPort: 11081, rules: [] },
130
+ },
131
+ })
132
+ assert.equal(stale.status, 409)
133
+ assert.equal(stale.body?.conflict, true)
134
+ assert.ok(stale.body?.view, 'the 409 must carry a fresh view')
135
+ assert.equal(typeof stale.body.view.revision, 'string')
136
+ } finally {
137
+ await started.stop()
138
+ }
139
+ })
140
+
141
+ test('the log creates its home directory (A-P2-12)', () => {
142
+ const base = home()
143
+ const missing = join(base, 'nested', 'home')
144
+ const logger = createRisdLogger(missing)
145
+ logger.info('hello')
146
+ assert.equal(existsSync(risdLogPath(missing)), true)
147
+ assert.match(readFileSync(risdLogPath(missing), 'utf8'), /hello/)
148
+ })
149
+
150
+ test('startup reconcile keeps the state file of the daemon asking (A-P1-5)', async () => {
151
+ const dir = home()
152
+ const previousHome = process.env.DSH_RIS_IDE_PROXY_HOME
153
+ process.env.DSH_RIS_IDE_PROXY_HOME = dir
154
+ try {
155
+ const port = 55999
156
+ writeRisdState({ pid: process.pid, port, token: 'x'.repeat(64), apiVersion: RISD_API_VERSION, version: 'test', startedAt: new Date().toISOString() }, dir)
157
+ await reconcileStartupLeftovers({ ownPid: process.pid })
158
+ assert.equal(existsSync(risdStatePath(dir)), true, 'own risd.json must survive')
159
+ await reconcileStartupLeftovers({ ownPid: 1 })
160
+ assert.equal(existsSync(risdStatePath(dir)), false, 'a stale risd.json from another pid is removed')
161
+ } finally {
162
+ if (previousHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
163
+ else process.env.DSH_RIS_IDE_PROXY_HOME = previousHome
164
+ }
165
+ })
166
+
167
+ test('a daemon that exits early reports why (A-P2-13)', async () => {
168
+ const dir = home()
169
+ const fake = join(mkdtempSync(join(tmpdir(), 'risd-fake-')), 'risd.mjs')
170
+ writeFileSync(fake, "process.stderr.write('port busy\\n'); process.exit(4)\n")
171
+ const ensured = await ensureRisd({ home: dir, spawnPath: fake, timeoutMs: 2000 })
172
+ assert.equal(ensured.ok, false)
173
+ assert.equal(ensured.reason, 'port-busy')
174
+ assert.equal(ensured.exitCode, 4)
175
+ assert.match(String(ensured.error), /port busy/)
176
+ rmSync(join(fake, '..'), { recursive: true, force: true })
177
+ })
178
+
179
+ test('a second home on the same port is refused, not silently shadowed (A-P2-9)', async () => {
180
+ const started = await startRisdProcess({ home: home() })
181
+ try {
182
+ const other = home()
183
+ const second = await startRisd({ home: other, port: started.state.port, version: 'test' })
184
+ assert.equal(second.ok, false)
185
+ assert.equal(second.code, 'home-mismatch')
186
+ assert.equal(second.found, started.home)
187
+ assert.equal(second.home, other)
188
+ } finally {
189
+ await started.stop()
190
+ }
191
+ })
192
+
193
+ test('risd stop waits for the pid, not for the state file (A-P2-7)', async () => {
194
+ const dir = home()
195
+ const started = await startRisdProcess({ home: dir })
196
+ const pid = started.state.pid
197
+ const result = await runRisdCli(['stop', '--home', dir])
198
+ assert.equal(result.code, 0, result.out + result.err)
199
+ assert.match(result.out, /risd: stopped/)
200
+ await sleep(50)
201
+ assert.equal(pidAlive(pid), false)
202
+ })
203
+
204
+ test('/ui is served with frame, sniff and CSP protection (C-P2-5)', async () => {
205
+ const started = await startRisdProcess({ home: home() })
206
+ try {
207
+ const response = await fetch(`http://127.0.0.1:${started.state.port}/ui`)
208
+ assert.equal(response.status, 200)
209
+ assert.equal(response.headers.get('x-frame-options'), 'DENY')
210
+ assert.equal(response.headers.get('x-content-type-options'), 'nosniff')
211
+ const csp = response.headers.get('content-security-policy') ?? ''
212
+ assert.match(csp, /frame-ancestors 'none'/)
213
+ assert.match(csp, /frame-src http:\/\/127\.0\.0\.1:\*/)
214
+ } finally {
215
+ await started.stop()
216
+ }
217
+ })