dsh-ris-ide 1.7.3 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +19 -7
  2. package/bin/proxy-janitor.mjs +106 -11
  3. package/bin/risd.mjs +287 -0
  4. package/bin/run-with-log.ps1 +43 -5
  5. package/lib/client.js +515 -1152
  6. package/lib/index.js +1124 -55
  7. package/lib/janitor.js +106 -15
  8. package/lib/proxy.js +86 -7
  9. package/lib/proxybridge-bundle.js +798 -0
  10. package/lib/redirector.js +484 -35
  11. package/lib/risd/build.js +91 -0
  12. package/lib/risd/debug.js +374 -0
  13. package/lib/risd/git.js +207 -0
  14. package/lib/risd/leases.js +124 -0
  15. package/lib/risd/lifecycle.js +148 -0
  16. package/lib/risd/log.js +59 -0
  17. package/lib/risd/ping.js +94 -0
  18. package/lib/risd/programs.js +348 -0
  19. package/lib/risd/server.js +1478 -0
  20. package/lib/risd/state.js +137 -0
  21. package/lib/risd/ui.js +1705 -0
  22. package/lib/risd/view.js +79 -0
  23. package/lib/risd-client.js +282 -0
  24. package/lib/standalone/window.html +14 -16
  25. package/lib/startup.js +114 -0
  26. package/package.json +4 -1
  27. package/test/client-build.test.mjs +113 -0
  28. package/test/client-viewer.test.mjs +166 -200
  29. package/test/dsh-origin.test.mjs +140 -0
  30. package/test/dsh-window-refresh.test.mjs +100 -0
  31. package/test/harness.test.mjs +9 -0
  32. package/test/host-noloop.test.mjs +74 -0
  33. package/test/host-tail.test.mjs +21 -4
  34. package/test/host-window.test.mjs +4 -4
  35. package/test/janitor.test.mjs +29 -1
  36. package/test/lifecycle.test.mjs +26 -5
  37. package/test/merge-owners.test.mjs +155 -0
  38. package/test/proxy-restart.test.mjs +37 -0
  39. package/test/proxy-window.test.mjs +45 -0
  40. package/test/proxy.test.mjs +41 -0
  41. package/test/proxybridge-bundle.test.mjs +687 -0
  42. package/test/redirector-bundle.test.mjs +391 -0
  43. package/test/redirector.test.mjs +59 -9
  44. package/test/risd-api.test.mjs +470 -0
  45. package/test/risd-bridge-degrade.test.mjs +101 -0
  46. package/test/risd-build.test.mjs +20 -0
  47. package/test/risd-cli-home.test.mjs +50 -0
  48. package/test/risd-client.test.mjs +130 -0
  49. package/test/risd-debug.test.mjs +261 -0
  50. package/test/risd-election.test.mjs +104 -0
  51. package/test/risd-engine.test.mjs +132 -0
  52. package/test/risd-entry.test.mjs +118 -0
  53. package/test/risd-git.test.mjs +109 -0
  54. package/test/risd-handoff.test.mjs +116 -0
  55. package/test/risd-heal.test.mjs +50 -0
  56. package/test/risd-helpers.mjs +108 -0
  57. package/test/risd-host-p2.test.mjs +147 -0
  58. package/test/risd-janitor-guard.test.mjs +46 -0
  59. package/test/risd-lease.test.mjs +83 -0
  60. package/test/risd-lifecycle.test.mjs +210 -0
  61. package/test/risd-log-follow.test.mjs +227 -0
  62. package/test/risd-mode.test.mjs +161 -0
  63. package/test/risd-ping.test.mjs +99 -0
  64. package/test/risd-programs.test.mjs +169 -0
  65. package/test/risd-review-p2.test.mjs +217 -0
  66. package/test/risd-shutdown.test.mjs +97 -0
  67. package/test/risd-teardown.test.mjs +87 -0
  68. package/test/risd-tools.test.mjs +211 -0
  69. package/test/risd-ui.test.mjs +445 -0
  70. package/test/risd-write.test.mjs +170 -0
  71. package/test/startup-reconcile.test.mjs +100 -0
  72. package/test/windows.test.mjs +37 -2
@@ -0,0 +1,79 @@
1
+ /**
2
+ * risd — the read-only proxy view.
3
+ *
4
+ * Phase 1a hands the browser the same picture the plugin used to build itself,
5
+ * minus the parts that need the plugin's program registry (per-rule run state)
6
+ * and its in-process leftovers (`inherited` engine banner). The plugin decorates
7
+ * those locally after forwarding, so `lib/client.js` sees an unchanged shape.
8
+ *
9
+ * Everything here is derived from the same files the engine reads — `proxy.json`,
10
+ * the janitor state, the redirector cache — so the daemon never invents state.
11
+ *
12
+ * @module dsh-risd/view
13
+ */
14
+ import { createHash } from 'node:crypto'
15
+ import { allowList, engineSide, gitProxyPlan, proxyConfigPath, proxyHomeDir, proxyStatus } from '../proxy.js'
16
+ import { janitorStatus } from '../janitor.js'
17
+ import { buildProfile } from '../redirector.js'
18
+
19
+ /**
20
+ * The CAS base the dialog sends back with a save. Mirrors `configRevision` in
21
+ * `lib/index.js` byte for byte (same fields, same order, same 12-char prefix);
22
+ * `test/risd-api.test.mjs` asserts the two agree so a future edit cannot drift.
23
+ * @param config - the normalised config file contents.
24
+ * @returns 12 hex chars.
25
+ */
26
+ export function risdConfigRevision(config) {
27
+ const view = {
28
+ socks: [String(config?.socks?.host ?? ''), Number(config?.socks?.port ?? 0)],
29
+ listenPort: Number(config?.listenPort ?? 0),
30
+ rules: (Array.isArray(config?.rules) ? config.rules : []).map((rule) => [
31
+ String(rule.id ?? ''),
32
+ String(rule.program ?? ''),
33
+ String(rule.hosts ?? ''),
34
+ String(rule.ports ?? ''),
35
+ rule.enabled === true,
36
+ rule.shadow === true,
37
+ String(rule.source ?? ''),
38
+ ]),
39
+ }
40
+ return createHash('sha1').update(JSON.stringify(view)).digest('hex').slice(0, 12)
41
+ }
42
+
43
+ /**
44
+ * @param cwd - workspace the caller asked about.
45
+ * @returns the base view (no rule decorations, no inherited-engine banner).
46
+ */
47
+ export async function risdProxyView(cwd) {
48
+ const status = await proxyStatus(cwd)
49
+ const watcher = janitorStatus()
50
+ return {
51
+ ok: true,
52
+ side: engineSide(),
53
+ revision: risdConfigRevision(status.config),
54
+ configPath: proxyConfigPath(),
55
+ home: proxyHomeDir(),
56
+ shared: true,
57
+ workspace: cwd,
58
+ socks: status.config.socks,
59
+ listenPort: status.config.listenPort,
60
+ // The maintenance page edits the table, so it needs the raw rows; the plugin
61
+ // still decorates its own copy with per-rule run state after forwarding.
62
+ rules: (Array.isArray(status.config.rules) ? status.config.rules : []).map((rule) => Object.assign({}, rule)),
63
+ running: status.running,
64
+ pid: status.pid,
65
+ listen: status.listen,
66
+ logPath: status.logPath,
67
+ socksUrl: status.socksUrl,
68
+ allow: allowList(status.config),
69
+ git: gitProxyPlan(status.config, {}),
70
+ // How many profile rules a sync would emit. Live bridge status is NOT probed
71
+ // here: on WSL that costs seconds (`/mnt/c` exists -> powershell probe), and the
72
+ // plugin already merges its cached status into the forwarded view. The old
73
+ // `managedBy:'plugin'` label outlived Phase 1b, where the daemon took over the
74
+ // bridge lifecycle (review A-P2-4).
75
+ redirector: { managedBy: 'daemon', rules: buildProfile(status.config).rules.length },
76
+ janitor: watcher,
77
+ owner: watcher.owner,
78
+ }
79
+ }
@@ -0,0 +1,282 @@
1
+ /**
2
+ * risd-client — the plugin side of the daemon (Phase 1a: discover, spawn, lease, read).
3
+ *
4
+ * Rules this module keeps:
5
+ * - **Never throws at the caller.** A missing daemon is a normal state, not an
6
+ * error: `ensureRisd` reports `{ ok: false, reason }` and the plugin falls
7
+ * back to its own proxy path.
8
+ * - **Never kills by pid.** Stopping goes through `POST /v1/shutdown`; a stale
9
+ * `risd.json` is only ever overwritten by a daemon that won the port, so the
10
+ * plugin cannot shoot a daemon that replaced the one it remembered.
11
+ * - **One spawn per machine.** A spawn lock (`risd.spawn.lock`, O_EXCL) makes
12
+ * concurrent dsh instances agree on who forks; the loser waits for
13
+ * `risd.json` instead of forking a doomed second daemon.
14
+ *
15
+ * API-shape note: `request()` returns `{ ok, status, body }` where `body` is the
16
+ * parsed JSON payload. `ok` is true only for a 2xx whose payload says `ok:true`,
17
+ * so callers never have to special-case "HTTP 200 that reported a failure".
18
+ *
19
+ * @module dsh-risd/client
20
+ */
21
+ import { spawn } from 'node:child_process'
22
+ import { request } from 'node:http'
23
+ import { fileURLToPath } from 'node:url'
24
+ import { API_VERSION_HEADER } from './risd/server.js'
25
+ import { RISD_API_VERSION, acquireSpawnLock, dropStaleSpawnLock, readRisdState, releaseSpawnLock } from './risd/state.js'
26
+
27
+ /** How long we wait for a freshly spawned daemon to answer health. */
28
+ export const RISD_START_TIMEOUT_MS = 5000
29
+ /** How long a losing spawner waits for the winner's `risd.json`. */
30
+ export const RISD_WAIT_TIMEOUT_MS = 5000
31
+ const REQUEST_TIMEOUT_MS = 2000
32
+
33
+ export const RISD_ENTRY = fileURLToPath(new URL('../bin/risd.mjs', import.meta.url))
34
+
35
+ function sleep(ms) {
36
+ return new Promise((resolve) => setTimeout(resolve, ms))
37
+ }
38
+
39
+ /**
40
+ * Low-level authenticated call.
41
+ * @param state - the `risd.json` contents (needs `url` and `token`).
42
+ * @param path - absolute path under `/v1`.
43
+ * @param options - `{ method, body, timeoutMs }`.
44
+ * @returns `{ ok, status, body, error? }`.
45
+ */
46
+ export async function risdRequest(state, path, { method = 'GET', body = undefined, timeoutMs = REQUEST_TIMEOUT_MS } = {}) {
47
+ if (state === null || typeof state !== 'object' || typeof state.token !== 'string') {
48
+ return { ok: false, status: 0, body: null, error: 'no state' }
49
+ }
50
+ try {
51
+ const response = await fetch(`${state.url}${path}`, {
52
+ method,
53
+ headers: {
54
+ authorization: `Bearer ${state.token}`,
55
+ [API_VERSION_HEADER]: String(RISD_API_VERSION),
56
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
57
+ },
58
+ body: body === undefined ? undefined : JSON.stringify(body),
59
+ signal: AbortSignal.timeout(timeoutMs),
60
+ })
61
+ const text = await response.text()
62
+ let parsed = null
63
+ try {
64
+ parsed = JSON.parse(text)
65
+ } catch {
66
+ parsed = null
67
+ }
68
+ return { ok: response.ok === true && parsed?.ok === true, status: response.status, body: parsed, error: parsed?.message }
69
+ } catch (error) {
70
+ return { ok: false, status: 0, body: null, error: String(error?.message ?? error) }
71
+ }
72
+ }
73
+
74
+ /** Health is unauthenticated, but still needs the state for its base URL. */
75
+ export async function risdHealth(state, { timeoutMs = 1000 } = {}) {
76
+ if (state === null || typeof state !== 'object') return null
77
+ const call = await risdRequest(Object.assign({}, state, { token: '' }), '/v1/health', { timeoutMs })
78
+ return call.body
79
+ }
80
+
81
+ /**
82
+ * Is the state file describing a daemon we can actually talk to, at a version
83
+ * we understand?
84
+ * @returns `{ usable: boolean, reason?, health?, state? }` (`reason` is one of
85
+ * `absent`, `unreachable`, `api-mismatch`).
86
+ */
87
+ export async function probeRisd({ home } = {}) {
88
+ const state = readRisdState(home)
89
+ if (state === null) return { usable: false, reason: 'absent', state: null }
90
+ const health = await risdHealth(state)
91
+ if (health === null || health.ok !== true) return { usable: false, reason: 'unreachable', state, health }
92
+ if (Number(health.apiVersion) !== RISD_API_VERSION) return { usable: false, reason: 'api-mismatch', state, health }
93
+ return { usable: true, state, health }
94
+ }
95
+
96
+ /**
97
+ * Make sure a daemon is running and return its state.
98
+ *
99
+ * @param options - `{ home, timeoutMs, spawnPath, version }`.
100
+ * @returns `{ ok, state?, reason?, spawned? }`.
101
+ */
102
+ export async function ensureRisd({ home, timeoutMs = RISD_START_TIMEOUT_MS, spawnPath = RISD_ENTRY } = {}) {
103
+ const first = await probeRisd({ home })
104
+ if (first.usable) return { ok: true, state: first.state, spawned: false }
105
+ if (first.reason === 'api-mismatch') return { ok: false, reason: 'api-mismatch', state: first.state }
106
+
107
+ dropStaleSpawnLock(home)
108
+ let owned = false
109
+ try {
110
+ owned = acquireSpawnLock(home)
111
+ } catch (error) {
112
+ // The lock is an optimisation, not a precondition: an unwritable home already
113
+ // fails later with a readable 'spawn-timeout'. Never throw out of ensureRisd.
114
+ return { ok: false, reason: 'spawn-failed', error: String(error?.message ?? error) }
115
+ }
116
+ if (!owned) {
117
+ // Another dsh is spawning: wait for its state instead of forking a peer.
118
+ const deadline = Date.now() + Math.min(timeoutMs, RISD_WAIT_TIMEOUT_MS)
119
+ while (Date.now() < deadline) {
120
+ await sleep(100)
121
+ const probe = await probeRisd({ home })
122
+ if (probe.usable) return { ok: true, state: probe.state, spawned: false }
123
+ }
124
+ return { ok: false, reason: 'spawn-timeout' }
125
+ }
126
+
127
+ try {
128
+ const child = spawn(process.execPath, [spawnPath, 'serve', ...(home === undefined ? [] : ['--home', String(home)])], {
129
+ detached: true,
130
+ // Keep stderr so a daemon that exits immediately (port busy, version
131
+ // mismatch, lock held) explains itself instead of surfacing as 'timeout'
132
+ // (review A-P2-13).
133
+ stdio: ['ignore', 'ignore', 'pipe'],
134
+ windowsHide: true,
135
+ })
136
+ let spawnError = ''
137
+ let exitCode = null
138
+ child.on('error', (error) => { spawnError = String(error?.message ?? error) })
139
+ child.stderr?.on('data', (chunk) => { if (spawnError.length < 400) spawnError += String(chunk) })
140
+ child.on('exit', (code) => { exitCode = code })
141
+ child.unref()
142
+ const deadline = Date.now() + timeoutMs
143
+ while (Date.now() < deadline) {
144
+ await sleep(120)
145
+ const probe = await probeRisd({ home })
146
+ if (probe.usable) return { ok: true, state: probe.state, spawned: true }
147
+ if (probe.reason === 'api-mismatch') return { ok: false, reason: 'api-mismatch', state: probe.state }
148
+ if (exitCode !== null) {
149
+ const hint = spawnError.trim().split('\n').filter(Boolean).slice(-3).join(' | ')
150
+ return {
151
+ ok: false,
152
+ reason: exitCode === 3 ? 'api-mismatch' : exitCode === 4 ? 'port-busy' : 'spawn-exited',
153
+ exitCode,
154
+ error: hint || `daemon exited with code ${exitCode}`,
155
+ }
156
+ }
157
+ }
158
+ return { ok: false, reason: 'spawn-timeout', error: spawnError.trim().slice(-400) || undefined }
159
+ } finally {
160
+ releaseSpawnLock(home)
161
+ }
162
+ }
163
+
164
+ /** Create (or refresh) this process's lease. */
165
+ export function acquireLease(state, { ownerPid = process.pid, sessionId = null, cwd = null } = {}) {
166
+ const body = { ownerPid }
167
+ if (typeof sessionId === 'string' && sessionId !== '') body.sessionId = sessionId
168
+ if (typeof cwd === 'string' && cwd !== '') body.cwd = cwd
169
+ return risdRequest(state, '/v1/leases', { method: 'POST', body })
170
+ }
171
+
172
+ /** Release a lease; safe to call from an exit path (no throw, no wait). */
173
+ export function releaseLease(state, id) {
174
+ if (id === undefined || id === null) return Promise.resolve({ ok: true, status: 0, body: null })
175
+ return risdRequest(state, `/v1/leases/${encodeURIComponent(String(id))}`, { method: 'DELETE', timeoutMs: 500 })
176
+ }
177
+
178
+ /** Read the daemon's read-only proxy view for a workspace. */
179
+ export async function getProxyView(state, cwd) {
180
+ const call = await risdRequest(state, `/v1/proxy?cwd=${encodeURIComponent(cwd)}`)
181
+ return call.ok ? call.body : null
182
+ }
183
+
184
+ /** Daemon config (read-only in 1a). */
185
+ export async function getRisdConfig(state) {
186
+ const call = await risdRequest(state, '/v1/config')
187
+ return call.ok ? call.body : null
188
+ }
189
+
190
+ /** Ask the daemon to exit. */
191
+ export function shutdownRisd(state) {
192
+ return risdRequest(state, '/v1/shutdown', { method: 'POST', body: { reason: 'plugin' }, timeoutMs: 1000 })
193
+ }
194
+
195
+ /**
196
+ * Write the machine-wide table through the daemon (Phase 1b P4).
197
+ * @returns the raw `{ ok, status, body }` call so the caller can relay a 409
198
+ * conflict verbatim instead of flattening it into "failed".
199
+ */
200
+ export function saveProxy(state, { cwd, config, revision, gitHost } = {}) {
201
+ const body = { cwd, config }
202
+ if (typeof revision === 'string' && revision !== '') body.revision = revision
203
+ if (typeof gitHost === 'string' && gitHost !== '') body.gitHost = gitHost
204
+ return risdRequest(state, '/v1/proxy', { method: 'POST', body })
205
+ }
206
+
207
+ /** Run one of the three-layer actions (engine + bridge + git) in the daemon. */
208
+ export function proxyAction(state, { cwd, action, gitHost, ruleId } = {}) {
209
+ const body = { cwd, action }
210
+ if (typeof gitHost === 'string' && gitHost !== '') body.gitHost = gitHost
211
+ if (typeof ruleId === 'string' && ruleId !== '') body.ruleId = ruleId
212
+ return risdRequest(state, '/v1/action', { method: 'POST', body })
213
+ }
214
+
215
+ /** Env/args a launched program needs to use the tunnel (parity with the plugin). */
216
+ /** The daemon's program rows (same pipeline as the panel, so ids/logNames match). */
217
+ export async function listPrograms(state, cwd, { dir = '', refresh = false } = {}) {
218
+ const params = new URLSearchParams({ cwd })
219
+ if (dir !== '') params.set('dir', dir)
220
+ if (refresh === true) params.set('refresh', '1')
221
+ return risdRequest(state, `/v1/programs?${params.toString()}`)
222
+ }
223
+
224
+ /** start | stop | restart one program; returns the raw `{ok,status,body}` to relay. */
225
+ export async function programAction(state, { cwd, action, id, dir = '' }) {
226
+ return risdRequest(state, '/v1/programs', {
227
+ method: 'POST',
228
+ body: { cwd, action, id, dir },
229
+ timeoutMs: action === 'start' || action === 'restart' ? 120000 : 15000,
230
+ })
231
+ }
232
+
233
+ /** One log window; pass the previous `nextOffset` to follow. */
234
+ export async function readProgramLog(state, { cwd, id, dir = '', offset = null, bytes = null }) {
235
+ const params = new URLSearchParams({ cwd, id })
236
+ if (dir !== '') params.set('dir', dir)
237
+ if (Number.isFinite(offset)) params.set('offset', String(offset))
238
+ if (Number.isFinite(bytes)) params.set('bytes', String(bytes))
239
+ return risdRequest(state, `/v1/programs/log?${params.toString()}`, { timeoutMs: 10000 })
240
+ }
241
+
242
+ /**
243
+ * Open the SSE log-follow stream and hand the raw response to the caller.
244
+ * The plugin relays the bytes unchanged (SSE headers must survive), so this
245
+ * deliberately returns the `IncomingMessage` instead of parsing frames.
246
+ */
247
+ export function openProgramLogStream(state, { cwd, id, dir = '', offset = null, bytes = null } = {}) {
248
+ const params = new URLSearchParams({ cwd, id })
249
+ if (dir !== '') params.set('dir', dir)
250
+ if (Number.isFinite(offset)) params.set('offset', String(offset))
251
+ if (Number.isFinite(bytes)) params.set('bytes', String(bytes))
252
+ return new Promise((resolve) => {
253
+ const req = request({
254
+ host: '127.0.0.1',
255
+ port: state.port,
256
+ path: `/v1/programs/log/stream?${params.toString()}`,
257
+ method: 'GET',
258
+ headers: {
259
+ authorization: `Bearer ${state.token}`,
260
+ 'x-risd-api-version': String(RISD_API_VERSION),
261
+ accept: 'text/event-stream',
262
+ },
263
+ }, (res) => resolve({ ok: res.statusCode === 200, status: res.statusCode, res, req }))
264
+ req.on('error', (error) => resolve({ ok: false, status: 0, res: null, req: null, error: String(error?.message ?? error) }))
265
+ req.end()
266
+ })
267
+ }
268
+
269
+ /**
270
+ * P4: one JDWP action, verbatim. The daemon owns the sessions and the single
271
+ * owner it tracks; the tool layer only maps its action names onto this one.
272
+ * @param {object} state
273
+ * @param {object} body - {action, cwd, id, ...action arguments, sessionId}
274
+ */
275
+ export function debugAction(state, body) {
276
+ return risdRequest(state, '/v1/debug', { method: 'POST', body, timeoutMs: 120_000 })
277
+ }
278
+
279
+ export async function getInjection(state, cwd, program) {
280
+ const call = await risdRequest(state, `/v1/injection?cwd=${encodeURIComponent(cwd)}&program=${encodeURIComponent(program)}`)
281
+ return call.ok ? call.body : null
282
+ }
@@ -102,10 +102,17 @@
102
102
  text.textContent = 'RIS-IDE 已在另一个窗口打开(一个工作空间只保留一个窗口)。'
103
103
  var row = document.createElement('div')
104
104
  row.style.marginTop = '10px'
105
- row.appendChild(button('关闭这个窗口', function () {
106
- nudgeHolder()
107
- try { window.close() } catch (error) { /* already gone */ }
108
- }))
105
+ // Inside the maintenance page's iframe close() is refused (only a
106
+ // script-opened window may close itself), so the "close this window" offer
107
+ // would be a dead button there (review, D3). Keep only the takeover path.
108
+ var embedded = false
109
+ try { embedded = window.self !== window.top } catch (error) { embedded = false }
110
+ if (!embedded) {
111
+ row.appendChild(button('关闭这个窗口', function () {
112
+ nudgeHolder()
113
+ try { window.close() } catch (error) { /* already gone */ }
114
+ }))
115
+ }
109
116
  row.appendChild(button('关闭旧窗口,在这里打开', function () {
110
117
  text.textContent = '正在关闭旧窗口…'
111
118
  row.textContent = ''
@@ -264,24 +271,15 @@
264
271
  fail((error && error.message) || String(error))
265
272
  return
266
273
  }
267
- // Fill the screen's work area = "maximized" for a script-opened window: the
268
- // opener asks for it, but browsers sometimes clamp popup sizes, and a window
269
- // opened by same-origin script may size itself. Never fatal — if the browser
270
- // refuses, the window keeps the size the opener requested.
271
- try {
272
- if (window.screen && typeof window.screen.availWidth === 'number' && window.screen.availWidth > 0) {
273
- window.moveTo(0, 0)
274
- window.resizeTo(window.screen.availWidth, window.screen.availHeight)
275
- }
276
- } catch (error) {
277
- /* keep the opener size */
278
- }
279
274
  var params = new URLSearchParams(window.location.search)
280
275
  var sessionId = params.get('sessionId') || ''
281
276
  var cwd = params.get('cwd') || ''
282
277
  var programId = params.get('programId') || ''
283
278
  // `debug=1` (the compact panel's 🐞 button) starts the JDWP session on arrival.
284
279
  var debug = params.get('debug') === '1'
280
+ // `view` used to select the proxy-only window. The proxy dialog was removed in
281
+ // 1.8.0 (the daemon page owns proxy rules now) and the client ignores the
282
+ // parameter, so the windows that still pass it are the only legacy users.
285
283
  document.title = 'RIS-IDE' + (cwd === '' ? '' : ' — ' + cwd)
286
284
  if (typeof client.mountStandalone !== 'function') { fail('客户端脚本版本太旧'); return }
287
285
  Promise.resolve(client.mountStandalone(root, {
package/lib/startup.js ADDED
@@ -0,0 +1,114 @@
1
+ // Startup reconciliation: things we left on the machine last time that no longer
2
+ // match the current configuration.
3
+ //
4
+ // Why this exists (2026-11-08): the proxy's on-disk side effects outlive the process
5
+ // that created them. `git config --global http.https://<host>/.proxy` survives a
6
+ // reboot (a dead tunnel makes every git/IDE fetch to that host fail), and the Windows
7
+ // `ProxyBridgeSvc` may still be parked on Manual (we park it so the SCM does not
8
+ // resurrect it mid-session). After a reboot nothing runs any more, so no teardown
9
+ // ever restored those two; the next start has to reconcile instead of trusting that
10
+ // the previous process cleaned up.
11
+ //
12
+ // Rules: only undo what is provably ours (recorded value / `socks5h://` heuristic),
13
+ // never touch a foreign value, and only when the owner (engine / bridge) is gone.
14
+ // @module dsh-ris-ide/startup
15
+ import { existsSync, rmSync } from 'node:fs'
16
+ import { proxyPid, proxyPidPath, proxyStatus, readProxyConfig } from './proxy.js'
17
+ import { reloadFailedPath, readWindowsServiceState, redirectorStatusCached, restoreWindowsService } from './redirector.js'
18
+ import { clearGitProxy, enabledGitRuleHost, readGitProxyState, syncGitProxy } from './risd/git.js'
19
+ import { readRisdState, removeRisdState } from './risd/state.js'
20
+ import { risdHealth } from './risd-client.js'
21
+
22
+ /**
23
+ * Bring the machine back in line with the current rules.
24
+ *
25
+ * @param {{cwd?: string, log?: (message: string) => void}} [options] - workspace
26
+ * hint (only used to resolve legacy paths) and a logger.
27
+ * @returns {Promise<{ok: boolean, notes: string[]}>} what was cleaned (empty = clean).
28
+ */
29
+ export async function reconcileStartupLeftovers({ cwd = '', log = () => {}, ownPid = null } = {}) {
30
+ const notes = []
31
+ const note = (message) => {
32
+ notes.push(message)
33
+ log(`[dsh-ris-ide] 启动对账:${message}`)
34
+ }
35
+
36
+ const gitState = readGitProxyState()
37
+ if (gitState.key !== '') {
38
+ const engineRunning = (await proxyStatus(cwd)).running === true
39
+ const ruleHost = enabledGitRuleHost(readProxyConfig(cwd))
40
+ if (engineRunning !== true) {
41
+ const cleared = await clearGitProxy()
42
+ if (cleared.skipped === 'foreign-value') {
43
+ note(`保留了不是本插件写入的 git 代理(${gitState.key} = ${cleared.current ?? '?'})`)
44
+ } else {
45
+ note(`引擎未运行,已清掉遗留的 git 代理 ${gitState.key}`)
46
+ }
47
+ } else if (ruleHost === '') {
48
+ const cleared = await clearGitProxy()
49
+ note(cleared.skipped === 'foreign-value'
50
+ ? `保留了不是本插件写入的 git 代理(${gitState.key})`
51
+ : `规则表已没有 git 规则,已清掉遗留的 git 代理 ${gitState.key}`)
52
+ } else if (gitState.host !== ruleHost) {
53
+ const synced = await syncGitProxy({ cwd, host: ruleHost, enabled: true })
54
+ note(synced.ok === true
55
+ ? `git 代理已改指当前规则 ${ruleHost}(原 ${gitState.host || '未知'})`
56
+ : `git 代理改指 ${ruleHost} 失败:${synced.error ?? '未知原因'}`)
57
+ }
58
+ }
59
+
60
+ // A pidfile kept from the last run is harmless to the engine code (it verifies
61
+ // the marker before trusting a pid), but it makes the panel show a phantom
62
+ // owner; if nothing is answering, the file no longer describes reality.
63
+ const pidPath = proxyPidPath()
64
+ const hadPidFile = existsSync(pidPath)
65
+ // `proxyPid()` already drops a pidfile whose pid does not carry our marker; keep
66
+ // the note so the user knows the phantom owner is gone rather than unexplained.
67
+ if (proxyPid() === null && hadPidFile) {
68
+ rmSync(pidPath, { force: true })
69
+ note('清掉了失效的代理 pidfile(引擎未运行)')
70
+ }
71
+
72
+ // Same for `risd.json`: a daemon state file whose port no longer answers makes
73
+ // the plugin believe a daemon exists (and then fail every forward with 502).
74
+ const daemonState = readRisdState()
75
+ if (daemonState !== null && Number(daemonState.pid) !== Number(ownPid)) {
76
+ // Never probe/remove our OWN state: a daemon reconciles its startup leftovers
77
+ // while it is still warming up, and a 400 ms self-request can fail under load;
78
+ // deleting risd.json then orphaned the daemon (review A-P1-5).
79
+ const alive = await risdHealth(daemonState, { timeoutMs: 400 })
80
+ if (alive?.ok !== true) {
81
+ removeRisdState()
82
+ note(`清掉了失效的 risd.json(daemon ${daemonState.port} 未应答)`)
83
+ }
84
+ }
85
+
86
+ // A reload failure marker from the previous run describes a bridge that is not
87
+ // running any more; keeping it makes the panel warn about nothing.
88
+ if (existsSync(reloadFailedPath()) && redirectorStatusCached().running !== true) {
89
+ rmSync(reloadFailedPath(), { force: true })
90
+ note('清掉了上次遗留的桥接重载失败标记')
91
+ }
92
+
93
+ const serviceState = readWindowsServiceState()
94
+ if (serviceState !== null && serviceState.stoppedByUs === true) {
95
+ if (redirectorStatusCached().running !== true) {
96
+ const restored = restoreWindowsService()
97
+ note(restored.restored === true
98
+ ? '已恢复上次被停用的 ProxyBridgeSvc'
99
+ : `ProxyBridgeSvc 未能自动恢复:${restored.reason ?? '未知原因'}(可手动把启动类型改回 Automatic)`)
100
+ }
101
+ }
102
+
103
+ return { ok: true, notes }
104
+ }
105
+
106
+ /**
107
+ * The same check but never throwing and never blocking startup.
108
+ * @param {object} [options] - forwarded to {@link reconcileStartupLeftovers}.
109
+ */
110
+ export function scheduleStartupReconcile(options = {}) {
111
+ void reconcileStartupLeftovers(options).catch((error) => {
112
+ try { options.log?.(`[dsh-ris-ide] 启动对账失败:${error?.message ?? error}`) } catch { /* logging must not throw */ }
113
+ })
114
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ris-ide",
3
- "version": "1.7.3",
3
+ "version": "1.8.0",
4
4
  "license": "MIT",
5
5
  "description": "RIS-IDE local dev panel for the DSH web GUI: live log tail, one-click start/stop of workspace programs, JDWP debugging, file tree + editor, and a standalone IDE window that carries no session history. · DSH 右侧栏本地开发面板:日志实时跟随、一键启停本地程序、Java 断点调试、文件树与编辑器、独立 IDE 窗口。",
6
6
  "keywords": [
@@ -27,6 +27,9 @@
27
27
  },
28
28
  "type": "module",
29
29
  "main": "lib/index.js",
30
+ "bin": {
31
+ "risd": "bin/risd.mjs"
32
+ },
30
33
  "exports": {
31
34
  ".": "./lib/index.js",
32
35
  "./client": "./lib/client.js",
@@ -0,0 +1,113 @@
1
+ // Stale-UI handshake (m09693): the plugin tells an open page which client bundle
2
+ // the host serves now, so a page that booted an older one can reload itself instead
3
+ // of relying on the user pressing Ctrl+Shift+R.
4
+ //
5
+ // The daemon half (its own module graph) lives in test/risd-api.test.mjs and
6
+ // test/risd-ui.test.mjs; this file covers the host route plus the client hook.
7
+ import assert from 'node:assert/strict'
8
+ import { createServer, request } from 'node:http'
9
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
10
+ import { tmpdir } from 'node:os'
11
+ import { join } from 'node:path'
12
+ import { after, before, test } from 'node:test'
13
+ import { handleRequest } from '../lib/index.js'
14
+
15
+ let home
16
+ let workspace
17
+ let server
18
+ let port
19
+
20
+ before(async () => {
21
+ home = mkdtempSync(join(tmpdir(), 'dsh-build-home-'))
22
+ workspace = mkdtempSync(join(tmpdir(), 'dsh-build-ws-'))
23
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
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
+ rmSync(home, { recursive: true, force: true })
35
+ rmSync(workspace, { recursive: true, force: true })
36
+ })
37
+
38
+ function getJson(path, host) {
39
+ return new Promise((resolve) => {
40
+ const call = request({ host: '127.0.0.1', port, path, method: 'GET', headers: { host: host ?? `127.0.0.1:${port}` } }, (res) => {
41
+ let text = ''
42
+ res.setEncoding('utf8')
43
+ res.on('data', (chunk) => { text += chunk })
44
+ res.on('end', () => {
45
+ let body = null
46
+ try { body = JSON.parse(text) } catch { body = null }
47
+ resolve({ status: res.statusCode, body })
48
+ })
49
+ })
50
+ call.on('error', () => resolve({ status: 0, body: null }))
51
+ call.end()
52
+ })
53
+ }
54
+
55
+ test('GET /dsh-ris-ide/build names the client bundle being served', async () => {
56
+ const { status, body } = await getJson('/dsh-ris-ide/build')
57
+ assert.equal(status, 200)
58
+ assert.equal(body.ok, true)
59
+ assert.match(body.build, /^[0-9a-f]{12}$/, 'a stable 12-hex stamp, not a raw mtime')
60
+ })
61
+
62
+ test('the stamp is stable while the bundle does not change', async () => {
63
+ // A page takes its FIRST answer as the baseline; a stamp that wobbled between two
64
+ // requests would make every page reload itself in a loop.
65
+ const first = await getJson('/dsh-ris-ide/build')
66
+ const second = await getJson('/dsh-ris-ide/build')
67
+ assert.equal(first.body.build, second.body.build)
68
+ })
69
+
70
+ test('a non-loopback Host cannot read the build stamp', async () => {
71
+ const { status } = await getJson('/dsh-ris-ide/build', 'evil.example')
72
+ assert.equal(status, 403)
73
+ })
74
+
75
+ test('the build route is read-only', async () => {
76
+ const status = await new Promise((resolve) => {
77
+ const call = request({ host: '127.0.0.1', port, path: '/dsh-ris-ide/build', method: 'POST', headers: { host: `127.0.0.1:${port}` } }, (res) => {
78
+ res.resume()
79
+ res.on('end', () => resolve(res.statusCode))
80
+ })
81
+ call.on('error', () => resolve(0))
82
+ call.end()
83
+ })
84
+ assert.equal(status, 405)
85
+ })
86
+
87
+ test('a stale page offers a refresh and never reloads itself', () => {
88
+ // Source-level assertions: both lives of this watcher (stream hello and the
89
+ // slow poll) must compare against the SAME baseline, otherwise a page could
90
+ // "notice" its own seed and raise a hint for nothing. Reloading is a user
91
+ // action — an automatic reload would throw away the IDE window's unsaved
92
+ // buffers (review C3-P1-2), so the watcher must not navigate by itself.
93
+ const source = readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
94
+ const watcher = source.slice(source.indexOf('function watchClientBuild()'), source.indexOf('function selectProgram'))
95
+ assert.match(watcher, /function watchClientBuild\(\)/)
96
+ assert.match(watcher, /pageBuildId === null/)
97
+ assert.match(watcher, /note\(payload\.build\)/, 'the stream hello carries the stamp')
98
+ assert.match(watcher, /routeUrl\('dsh-ris-ide\/build'\)/, 'the baseline is seeded before the hello arrives')
99
+ assert.doesNotMatch(watcher, /location\.reload\(\)/, 'no self-reload: it would drop unsaved editor buffers')
100
+ assert.match(watcher, /showStaleBuildNotice\(build\)/, 'the bar names the build it warns about')
101
+ assert.match(watcher, /BUILD_POLL_MS/, 'a foreground page re-asks on a slow timer')
102
+ assert.match(watcher, /setInterval\(pollBuild, BUILD_POLL_MS\)/)
103
+ assert.match(watcher, /addEventListener\('focus', pollBuild\)/, 'coming back to the tab also re-checks')
104
+ assert.match(watcher, /staleNoticeDismissedFor/, 'a dismissed hint stays closed for that build')
105
+ })
106
+
107
+ test('the stale-build bar carries a refresh button', () => {
108
+ const source = readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
109
+ const notice = source.slice(source.indexOf('function showStaleBuildNotice'), source.indexOf('function watchClientBuild'))
110
+ assert.match(notice, /textContent = '刷新'/)
111
+ assert.match(notice, /location\.reload\(\)/, 'the reload happens only when the user clicks it')
112
+ assert.match(notice, /staleNoticeDismissedFor = staleNoticeBuild/)
113
+ })