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,445 @@
1
+ // The daemon's own maintenance page + the endpoints it needs.
2
+ //
3
+ // Why this exists: with daemonMode=auto the daemon may own the proxy engine, running
4
+ // programs (JVMs) and a JDWP session when no dsh is open. Without a page, "no dsh"
5
+ // would also mean "no way to stop anything" — the page is deliberately loopback-only
6
+ // and carries the token inline, because whoever can load it can read risd.json.
7
+ import assert from 'node:assert/strict'
8
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
9
+ import { request } from 'node:http'
10
+ import { tmpdir } from 'node:os'
11
+ import { join } from 'node:path'
12
+ import { after, before, test } from 'node:test'
13
+ import { startRisdProcess } from './risd-helpers.mjs'
14
+
15
+ let daemon
16
+ let workspace
17
+
18
+ function call(state, path, { method = 'GET', body, host, token } = {}) {
19
+ return new Promise((resolve) => {
20
+ const payload = body === undefined ? '' : JSON.stringify(body)
21
+ const headers = Object.assign(
22
+ { host: host ?? `127.0.0.1:${state.port}`, 'x-risd-api-version': '1' },
23
+ token === null ? {} : { authorization: `Bearer ${token ?? state.token}` },
24
+ payload === '' ? {} : { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) },
25
+ )
26
+ const req = request({ host: '127.0.0.1', port: state.port, path, method, timeout: 8000, headers }, (res) => {
27
+ let text = ''
28
+ res.setEncoding('utf8')
29
+ res.on('data', (chunk) => { text += chunk })
30
+ res.on('end', () => {
31
+ let parsed = null
32
+ try { parsed = JSON.parse(text) } catch { parsed = null }
33
+ resolve({ status: res.statusCode, text, body: parsed })
34
+ })
35
+ })
36
+ req.on('error', (error) => resolve({ status: 0, text: '', body: { error: String(error?.message) } }))
37
+ if (payload !== '') req.write(payload)
38
+ req.end()
39
+ })
40
+ }
41
+
42
+ before(async () => {
43
+ workspace = mkdtempSync(join(tmpdir(), 'risd-ui-ws-'))
44
+ mkdirSync(join(workspace, '.dsh-ris-ide'), { recursive: true })
45
+ writeFileSync(join(workspace, '.dsh-ris-ide', 'config.json'), `${JSON.stringify({
46
+ version: 1,
47
+ defaults: {},
48
+ programs: [{
49
+ id: 'demo', name: 'demo', kind: 'custom', dir: workspace, relDir: '.', project: '',
50
+ logName: 'demo', logPath: join(workspace, 'logs', 'demo.log'), startCommand: 'true',
51
+ }],
52
+ }, null, 2)}\n`)
53
+ mkdirSync(join(workspace, 'logs'), { recursive: true })
54
+ writeFileSync(join(workspace, 'logs', 'demo.log'), 'hello\n')
55
+ daemon = await startRisdProcess({ port: 0 })
56
+ })
57
+
58
+ after(async () => {
59
+ await daemon?.stop()
60
+ rmSync(workspace, { recursive: true, force: true })
61
+ })
62
+
63
+ test('the inline page script is syntactically valid', async () => {
64
+ // A missing comma in the state literal used to kill the whole script, leaving
65
+ // the page rendered but dead (every checkbox unchecked, no error visible).
66
+ const page = await call(daemon.state, '/ui', { token: null })
67
+ assert.equal(page.status, 200)
68
+ const scripts = [...page.text.matchAll(/<script>([\s\S]*?)<\/script>/g)]
69
+ assert.ok(scripts.length > 0, 'page has an inline script')
70
+ for (const match of scripts) new Function(match[1]) // SyntaxError would fail the test
71
+ })
72
+
73
+ test('the IDE tab drops the toolbar and names workspaces by folder', async () => {
74
+ const page = await call(daemon.state, '/ui', { token: null })
75
+ const html = page.text
76
+ assert.doesNotMatch(html, /ide-toolbar/, 'no toolbar row')
77
+ assert.doesNotMatch(html, /新窗口打开/, 'no new-window button')
78
+ assert.doesNotMatch(html, /id="ide-open"|id="ide-retry"|id="ide-hint"/)
79
+ // The panel toggle moved into the header (icon only, fixed at the left); the
80
+ // sidebar head and the floating expand chip are gone (m07956 ①).
81
+ assert.match(html, /<header>\s*<button[^>]*id="ide-side-toggle"[^>]*>›<\/button>\s*<h1>risd<\/h1>/, 'header owns the panel toggle, left of the brand')
82
+ assert.match(html, /class="side-toggle"/)
83
+ assert.doesNotMatch(html, /ide-side-head|id="ide-side-show"|class="ide-expand"/)
84
+ // The panel starts collapsed and remembers an explicit 'on' only (m08228).
85
+ assert.match(html, /getItem\('risd\.ideSide'\) === 'on'/, 'the panel is collapsed unless the user expanded it')
86
+ assert.doesNotMatch(html, /getItem\('risd\.ideSide'\) !== 'off'/)
87
+ assert.match(html, /(未活跃)/, 'non-live workspaces stay listed and are labelled')
88
+ assert.match(html, /id="ide-stale-close"/, 'the stale hint can be dismissed')
89
+ assert.match(html, /state\.staleDismissed\[state\.cwd/, 'dismissal is remembered per workspace')
90
+ assert.match(html, /toggle\.textContent = visible \? '‹' : '›'/, 'one control covers collapse and expand')
91
+ assert.match(html, /toggle\.setAttribute\('aria-expanded'/)
92
+ assert.match(html, /toggle\.disabled = el\('view-ide'\)\.hidden/, 'the toggle is inert outside the IDE pane')
93
+ assert.match(html, /flex:0 0 208px/, 'workspace panel is a little narrower')
94
+ // Page-code drift (m09693): a daemon module edit does NOT reach a reloaded page
95
+ // (Node caches the module graph), so the page compares the stamp it was rendered
96
+ // with against /v1/health's `loaded` (a restarted daemon => reload itself) and
97
+ // `disk` (edited but not restarted => a restart hint, not a silent stale UI).
98
+ assert.match(html, /id="ui-drift"/, 'the page owns a drift hint')
99
+ // m11445: an empty banner wrapper still participates in the flex column gap, which
100
+ // pushed the 概览 page 14px lower than 代理设置.
101
+ assert.match(html, /#overview-banner:empty, #proxy-banner:empty \{ display:none; \}/, 'empty banners stop taking a gap slot')
102
+ assert.match(html, /var PAGE_BUILD = /, 'the rendered page knows which code it runs')
103
+ assert.match(html, /body\.uiBuild\.loaded !== PAGE_BUILD/, 'a restarted daemon is detected from the code stamp')
104
+ assert.match(html, /build\.disk !== build\.loaded/, 'a rebuilt-but-not-restarted daemon is called out')
105
+ // Review C3-P1-3: the banner says "refresh", it does not reload by itself (the
106
+ // proxy rule table may be mid-edit), and a restarted daemon is noticed even when
107
+ // its code did not change, because the page's token died with it.
108
+ assert.match(html, /location\.reload\(\);\s*return;/, 'a stale page reloads itself')
109
+ assert.match(html, /var safe = count === 0 && state\.proxyDirty !== true && state\.lifecycleDirty !== true/, 'reload never loses work')
110
+ assert.match(html, /id="ui-drift-reload"/, 'the drift banner offers the refresh button')
111
+ // m11421: 「插件版本已更新」时刷新按钮变成「重启并刷新」——光刷新只会再拿到
112
+ // 旧代码(daemon 的模块图在内存里),所以按钮先 POST /v1/restart 再等新实例。
113
+ assert.match(html, /var driftMode = 'reload';/, 'the banner remembers whether a restart is needed')
114
+ assert.match(html, /插件版本已更新,点「重启并刷新」后生效/, 'a rebuilt daemon asks for restart+reload, not a bare reload')
115
+ assert.match(html, /driftMode === 'restart' \? '重启并刷新' : '刷新'/, 'the action label follows the drift mode')
116
+ assert.match(html, /api\('\/v1\/restart', \{ method: 'POST' \}\)/, 'the button restarts the daemon through its endpoint')
117
+ assert.match(html, /body\.instance !== previous/, 'the page waits for a new daemon instance before reloading')
118
+ assert.match(html, /function restartDaemonThenReload/, 'restart+reload saves the IDE buffers first')
119
+ assert.match(html, /if \(driftMode === 'restart'\) \{ restartDaemon\(\); return; \}/, 'save-all continues into the restart')
120
+ // m10900: the tabs are 开发环境 / 代理设置, the reload path asks the embedded IDE
121
+ // whether anything is unsaved, and the banner can save all of it first.
122
+ assert.match(html, /data-tab="ide" aria-selected="false">开发环境</, 'the IDE tab is called 开发环境')
123
+ assert.match(html, /data-tab="proxy" aria-selected="false">代理设置</, 'the proxy tab is called 代理设置')
124
+ assert.match(html, /id="ui-drift-save"/, 'the drift banner can offer 保存所有文件')
125
+ assert.match(html, /function askIdeDirty/, 'the page asks the iframe instead of guessing')
126
+ assert.match(html, /dsh-ris-ide:probe-dirty/, 'the probe has a named protocol')
127
+ assert.match(html, /dsh-ris-ide:save-all/, 'the save-all request has a named protocol')
128
+ assert.match(html, /function setDriftSave/, 'the save-all button appears only when something is unsaved')
129
+ // m10900: a shortcut/toolbar reload keeps the tab and the workspace.
130
+ assert.match(html, /var TAB_STORAGE = 'risd\.tab'/, 'the last tab lives under one storage key')
131
+ assert.match(html, /localStorage\.getItem\(TAB_STORAGE\)/, 'the last tab is restored')
132
+ assert.match(html, /localStorage\.setItem\(TAB_STORAGE, name\)/, 'switching tabs remembers the new one')
133
+ assert.match(html, /PAGE_INSTANCE = /, 'the page knows which daemon process rendered it')
134
+ assert.match(html, /body\.instance !== PAGE_INSTANCE/, 'a restarted daemon invalidates the page token')
135
+ assert.match(html, /PAGE_BUILD && body\.uiBuild && body\.uiBuild\.loaded && body\.uiBuild\.loaded !== PAGE_BUILD/, 'a rebuilt daemon is noticed too')
136
+ assert.match(html, /status === 401 && driftMessage\.indexOf\('未保存'\)/, 'a dead token is surfaced instead of failing silently, without clobbering the unsaved-buffers message')
137
+ assert.match(html, /state\.proxyDirty === true && window\.confirm\('代理规则还没保存,刷新会丢失'\)/, 'unsaved rules are protected')
138
+ assert.match(html, /state\.proxyDirty = true/, 'editing the rule table marks it dirty')
139
+ // Review C3-P2-9/P2-12: an unset SOCKS host is "未配置" (neutral), not a red
140
+ // failure; a failed download keeps the manual URLs. m10585: once installed the
141
+ // card only reports the file count — no download/upload buttons.
142
+ assert.match(html, /result\.configured === false/, 'no SOCKS host is a neutral state')
143
+ assert.match(html, /lastBundleUrls/, 'the card remembers the mirror URLs across renders')
144
+ assert.match(html, /button\.hidden = installed/, 'an installed bundle hides the download button')
145
+ assert.match(html, /upload\.hidden = installed/, 'an installed bundle hides the upload button')
146
+ assert.match(html, /'已安装 · 文件 ' \+ \(status\.files \|\| \[\]\)\.length \+ ' 个'/, 'the card reports the file count only')
147
+ // ProxyBridge bundle card (m09120 ③): download-on-demand, upload fallback, URL shown.
148
+ assert.match(html, /id="bridge-download"/, 'the proxy tab offers a download button')
149
+ assert.match(html, /id="bridge-upload"/, 'a failed download can be replaced by a manual upload')
150
+ assert.match(html, /function uploadBundle/, 'the upload posts the picked file')
151
+ assert.match(html, /\/v1\/proxybridge\/upload/, 'the upload route is called')
152
+ assert.match(html, /loadBundle\(\)/, 'the card refreshes with the tab, not once at load')
153
+ // SOCKS reachability chip (m09120 ②): the proxy row shows live connectivity.
154
+ assert.match(html, /id="proxy-ping"/, 'the SOCKS row carries a status chip')
155
+ assert.match(html, /function refreshPing/, 'the chip is refreshed, not written once')
156
+ assert.match(html, /setInterval\(refreshPing, 10000\)/, 'probing is periodic')
157
+ assert.match(html, /queuePing/, 'editing host/port re-probes before saving')
158
+ assert.match(html, /function workspaceLabel/, 'workspaces are labelled by folder name')
159
+ assert.match(html, /parts\.slice\(-2\)\.join\('\/'\)/, 'collisions use the parent folder')
160
+ assert.match(html, /focusIdeFrame\(\)/, 'outside clicks send focus back into the iframe')
161
+ })
162
+
163
+ test('re-opening the IDE tab keeps the iframe document (unsaved edits survive)', async () => {
164
+ // Review C-P0-1: showTab('ide') used to call loadIde(), which wiped ide-body and
165
+ // rebuilt the iframe — silently losing unsaved editor content, the debugger
166
+ // selection and the scroll position on the most common interaction ("look at the
167
+ // proxy tab, come back").
168
+ const page = await call(daemon.state, '/ui', { token: null })
169
+ assert.match(page.text, /function refreshIdeWindows\(\)/)
170
+ assert.match(page.text, /if \(frame\.getAttribute\('src'\) !== url\) frame\.src = url/)
171
+ assert.match(page.text, /if \(name === 'ide'\) \{ if \(el\('ide-frame'\)\) refreshIdeWindows\(\); else loadIde\(\); \}/)
172
+ assert.match(page.text, /function ensureIdeFrame\(\)/)
173
+ // The rebuild of #ide-body is exactly what must not happen any more.
174
+ assert.doesNotMatch(page.text, /el\('ide-body'\)\.innerHTML = ''/)
175
+ })
176
+
177
+ test('the proxy tab edits global rules without a workspace picker', async () => {
178
+ const page = await call(daemon.state, '/ui', { token: null })
179
+ const html = page.text
180
+ assert.doesNotMatch(html, /id="proxy-cwd"/, 'rules are machine-wide: no workspace input')
181
+ assert.match(html, /全局规则:按机器生效、不区分工作区/)
182
+ assert.match(html, /id="bridge-restart" hidden/, 'the restart button only shows when it is needed')
183
+ assert.match(html, /为什么要重启/, 'its tooltip explains the reason')
184
+ assert.match(html, /setBridgeStale/)
185
+ })
186
+
187
+ test('the overview stop button is just 停止', async () => {
188
+ const page = await call(daemon.state, '/ui', { token: null })
189
+ assert.match(page.text, /id="daemon-stop">停止</)
190
+ assert.doesNotMatch(page.text, /停止 daemon</)
191
+ })
192
+
193
+ test('the proxy tab reports the restart result and keeps a 409 visible', async () => {
194
+ const page = await call(daemon.state, '/ui', { token: null })
195
+ // C-P1-3: the action result is nested under `result`; reading the envelope made
196
+ // every successful restart look like "需要提权".
197
+ assert.match(page.text, /var result = \(response && response\.result\) \|\| \{\}/)
198
+ // C-P1-4: reload first, then show the conflict (the reload rewrites the banner).
199
+ assert.match(page.text, /if \(error\.status === 409\) \{[\s\S]{0,900}loadProxyTab\(\)\.then/)
200
+ // A 409 caused by our own in-flight write retries once instead of showing the
201
+ // user a conflict they cannot resolve (m10304 auto-save serialisation).
202
+ assert.match(page.text, /options\.retried !== true/)
203
+ assert.match(page.text, /saveRules\(\{ auto: auto, retried: true \}\)/)
204
+ })
205
+
206
+ test('values that reach the markup are escaped, including pill/banner classes (review C-P2-4)', async () => {
207
+ // rule.source comes from proxy.json, which any plugin/editor can write; it lands in
208
+ // a class attribute on a page that carries the daemon token.
209
+ const page = await call(daemon.state, '/ui', { token: null })
210
+ assert.match(page.text, /function pill\(text, cls\) \{ return '<span class="pill ' \+ esc\(cls \|\| ''\) \+ '">' \+ esc\(text\) \+ '<\/span>'; \}/)
211
+ assert.match(page.text, /var shape = kind === 'err' \|\| kind === 'warn' \|\| kind === 'ok' \? kind : 'warn';/)
212
+ assert.match(page.text, /'<div class="banner ' \+ shape \+ '">' \+ esc\(text\) \+ '<\/div>'/)
213
+ })
214
+
215
+ test('the log tail and the window poll only run where they are seen (review C-P2-3)', async () => {
216
+ const page = await call(daemon.state, '/ui', { token: null })
217
+ // The 2 s tail follows the pane, the tab and the visibility, not just the toggle.
218
+ assert.match(page.text, /function syncLogTimer\(\)/)
219
+ assert.match(page.text, /var wanted = state\.logOn === true && state\.tab === 'proxy' && document\.hidden !== true;/)
220
+ assert.match(page.text, /document\.addEventListener\('visibilitychange', function \(\) \{ syncLogTimer\(\); syncPingTimer\(\); \}\)/)
221
+ // The 4 s poll skips the proxy tab (it does not read the window list) and a hidden page.
222
+ assert.match(page.text, /if \(state\.tab === 'ide' \|\| state\.tab === 'overview'\) syncDshTab\(\);/)
223
+ assert.doesNotMatch(page.text, /if \(!document\.hidden\) syncDshTab\(\);/)
224
+ // Typing into the lifecycle form must not be undone by the refresh loop.
225
+ assert.match(page.text, /if \(state\.lifecycleDirty === true\) return Promise\.resolve\(state\.lifecycle \|\| null\);/)
226
+ assert.match(page.text, /el\('lifecycle-rows'\)\.addEventListener\('change'/)
227
+ assert.match(page.text, /state\.lifecycleDirty = false;/)
228
+ })
229
+
230
+ test('the embedded IDE gets its own window-lock name (review C-P2-6)', async () => {
231
+ const page = await call(daemon.state, '/ui', { token: null })
232
+ // A fixed name made the rebuilt iframe race the previous document's Web Lock and
233
+ // flash 「RIS-IDE 已在另一个窗口打开」 — and the standalone window's own name was the
234
+ // same string, so the two could take each other's lock.
235
+ assert.match(page.text, /var IDE_WNAME = 'risd-ide-' \+ Math\.random\(\)\.toString\(36\)\.slice\(2, 8\);/)
236
+ assert.match(page.text, /'&wname=' \+ encodeURIComponent\(IDE_WNAME\)/)
237
+ assert.doesNotMatch(page.text, /&wname=risd-ide'/)
238
+ })
239
+
240
+ test('a disabled IDE tab is refused before the view is shown (review C-P2-9)', async () => {
241
+ const page = await call(daemon.state, '/ui', { token: null })
242
+ // The old order made #view-ide visible and then returned on the disabled tab.
243
+ const body = page.text.slice(page.text.indexOf('function showTab(name)'))
244
+ const guard = body.indexOf("if (ideTab && ideTab.disabled) return")
245
+ const assignment = body.indexOf('state.tab = name;')
246
+ assert.ok(guard > 0 && assignment > guard, 'the disabled check must come before state.tab/visibility')
247
+ })
248
+
249
+ test('a failed engine stop explains itself on the overview (review C-P2-8)', async () => {
250
+ const page = await call(daemon.state, '/ui', { token: null })
251
+ assert.match(page.text, /id="overview-banner"/)
252
+ assert.match(page.text, /\(running \? '停止' : '启动'\) \+ '代理引擎失败:' \+ error\.message/)
253
+ // The toggle names the retry and the escape hatch instead of a bare alert().
254
+ assert.match(page.text, /可以再点一次重试;仍不行就停掉守护进程/)
255
+ })
256
+
257
+ test('GET /v1/proxy works without a cwd (the rule table is machine-wide)', async () => {
258
+ const response = await call(daemon.state, '/v1/proxy')
259
+ assert.equal(response.status, 200)
260
+ assert.equal(response.body.ok, true)
261
+ assert.ok(Array.isArray(response.body.rules), 'rules come back even when no workspace is named')
262
+ })
263
+
264
+ test('the overview offers lifecycle settings for daemon, proxy, programs and debug', async () => {
265
+ const page = await call(daemon.state, '/ui', { token: null })
266
+ assert.equal(page.status, 200)
267
+ assert.match(page.text, /生命周期/)
268
+ assert.match(page.text, /id="lifecycle-save"/)
269
+ assert.equal(page.text.includes('followDaemon'), false, 'following the daemon is forced, not configurable')
270
+ for (const key of ['daemon.followDsh', 'proxy.followDsh', 'programs.followDsh', 'debug.followDsh']) {
271
+ assert.ok(page.text.includes(`data-life="${key}"`), `missing checkbox ${key}`)
272
+ }
273
+ assert.match(page.text, /loadLifecycle/)
274
+ assert.match(page.text, /v1\/config/)
275
+ })
276
+
277
+ test('the maintenance page is served to loopback and carries the token inline', async () => {
278
+ const res = await call(daemon.state, '/ui', { token: null })
279
+ assert.equal(res.status, 200)
280
+ assert.match(res.text, /risd — 本机代理与程序维护/)
281
+ assert.ok(res.text.includes(daemon.state.token), 'the page must carry the token it uses for its own calls')
282
+ for (const title of ['概览', '代理', 'IDE', '守护进程', '代理运行状态', '运行中的项目', '调试中的进程', '规则表']) {
283
+ assert.ok(res.text.includes(title), `missing section: ${title}`)
284
+ }
285
+ // The header is just "risd" + centered tabs (IDE · 代理 · 概览): the daemon
286
+ // status moved into the overview row, so no meta text is left up there.
287
+ assert.doesNotMatch(res.text, /id="meta"/, 'no status text in the header')
288
+ assert.match(res.text, /<nav role="tablist"[^>]*>\s*<button role="tab" data-tab="ide"/, 'IDE is the first tab')
289
+ assert.ok(res.text.indexOf('data-tab="ide"') < res.text.indexOf('data-tab="proxy"'), 'IDE before 代理')
290
+ assert.ok(res.text.indexOf('data-tab="proxy"') < res.text.indexOf('data-tab="overview"'), '代理 before 概览')
291
+ // IDE is full-bleed (no card padding) and has a collapsible workspace panel.
292
+ assert.match(res.text, /\.view\[hidden\] \{ display:none !important; \}/)
293
+ assert.match(res.text, /id="ide-side"/)
294
+ assert.match(res.text, /id="ide-side-toggle"/)
295
+ assert.match(res.text, /id="view-ide" hidden>\s*<div class="ide-layout">/, 'IDE view is a layout, not a card')
296
+ // The page still accepts ?tab= (deep links/tests); switching workspace moves focus into the iframe.
297
+ assert.match(res.text, /get\('tab'\)/)
298
+ assert.match(res.text, /frame\.focus\(\)/)
299
+ // One engine button whose label is the next action (m10585): 启动 while down,
300
+ // 停止 while it runs. The old pair of buttons is gone.
301
+ assert.match(res.text, /id="engine-toggle" disabled>启动/, 'the overview can start the engine')
302
+ assert.match(res.text, /id="proxy-engine-toggle" disabled>启动/, 'the proxy tab has the same toggle')
303
+ assert.match(res.text, /engineToggle\.textContent = running \? '停止' : '启动'/)
304
+ // Starting can wait on sudo/UAC for seconds: the button says which half is running
305
+ // and refuses a second click instead of looking dead (m11279).
306
+ assert.match(res.text, /var engineBusy = false;/)
307
+ assert.match(res.text, /if \(engineBusy\) return;/)
308
+ assert.match(res.text, /button\.setAttribute\('aria-busy', 'true'\)/)
309
+ assert.match(res.text, /engineBusyAction === 'stop' \? '停止中…' : '启动中…'/)
310
+ assert.match(res.text, /button\.removeAttribute\('aria-busy'\)/)
311
+ assert.match(res.text, /if \(engineBusy\) \{\s+paintEngineButtons\(\);/, 'the 4s refresh must not repaint over the busy label')
312
+ assert.match(res.text, /button\[aria-busy="true"\] \{ opacity:\.7; cursor:progress; \}/)
313
+ assert.doesNotMatch(res.text, /id="engine-start"/, 'the separate start button is gone')
314
+ assert.doesNotMatch(res.text, /id="engine-stop"/, 'the separate stop button is gone')
315
+ // The rule table has no 读取/保存 buttons: editing is the save (m10585).
316
+ assert.doesNotMatch(res.text, /id="proxy-reload"/)
317
+ assert.doesNotMatch(res.text, /id="proxy-save"/)
318
+ // Stopping the daemon is an overview row now, not a header button: the header
319
+ // only carries the tabs.
320
+ assert.match(res.text, /id="daemon-stop"/, 'the daemon row owns the stop button')
321
+ assert.doesNotMatch(res.text, /id="shutdown"/, 'no header-level close button any more')
322
+ })
323
+
324
+ test('the maintenance page refuses a non-loopback Host header (DNS rebinding)', async () => {
325
+ const res = await call(daemon.state, '/ui', { token: null, host: 'evil.example.com' })
326
+ assert.equal(res.status, 403)
327
+ assert.equal(res.body.code, 'forbidden')
328
+ })
329
+
330
+ test('the API refuses a foreign Host or Origin (no DNS rebinding / CORS)', async () => {
331
+ const rebinding = await call(daemon.state, '/v1/health', { token: null, host: 'evil.example.com' })
332
+ assert.equal(rebinding.status, 403)
333
+ // Same loopback Host, but a page on another origin is probing the port.
334
+ const crossOrigin = await new Promise((resolve) => {
335
+ const req = request({ host: '127.0.0.1', port: daemon.state.port, path: '/v1/health', timeout: 5000,
336
+ headers: { host: `127.0.0.1:${daemon.state.port}`, origin: 'https://evil.example.com' } }, (res) => {
337
+ res.resume()
338
+ res.on('end', () => resolve(res.statusCode))
339
+ })
340
+ req.on('error', () => resolve(0))
341
+ req.end()
342
+ })
343
+ assert.equal(crossOrigin, 403)
344
+ })
345
+
346
+ test('GET /v1/dsh keeps quiet workspaces and marks them non-live (m08268)', async () => {
347
+ const file = join(daemon.home, 'dsh-window.json')
348
+ writeFileSync(file, `${JSON.stringify({ windows: [
349
+ { url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-a', sessionId: 's-a', at: new Date().toISOString() },
350
+ { url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-b', sessionId: 's-b', at: new Date(Date.now() - 10 * 60_000).toISOString() },
351
+ { url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-old', sessionId: 's-old', at: new Date(Date.now() - 30 * 24 * 3600_000).toISOString() },
352
+ ] })}\n`)
353
+ const res = await call(daemon.state, '/v1/dsh')
354
+ assert.equal(res.status, 200)
355
+ assert.equal(res.body.available, true)
356
+ // The 60s-old workspace stays selectable, the month-old one is pruned.
357
+ assert.deepEqual(res.body.windows.map((row) => row.cwd), ['/tmp/ws-a', '/tmp/ws-b'])
358
+ assert.deepEqual(res.body.windows.map((row) => row.live), [true, false])
359
+ assert.equal(res.body.windows[0].sessionId, 's-a')
360
+ assert.equal(res.body.url, 'http://127.0.0.1:3080')
361
+ })
362
+
363
+ test('GET /v1/dsh greys the IDE tab out when no window is live', async () => {
364
+ writeFileSync(join(daemon.home, 'dsh-window.json'), `${JSON.stringify({ windows: [] })}\n`)
365
+ const res = await call(daemon.state, '/v1/dsh')
366
+ assert.equal(res.status, 200)
367
+ assert.equal(res.body.available, false)
368
+ assert.match(String(res.body.reason), /dsh 未运行/)
369
+ })
370
+
371
+ test('the API is still authenticated (the page just carries the token)', async () => {
372
+ const res = await call(daemon.state, '/v1/workspaces', { token: null })
373
+ assert.equal(res.status, 401)
374
+ })
375
+
376
+ test('workspaces the daemon has served are offered to the page', async () => {
377
+ const before = await call(daemon.state, '/v1/workspaces')
378
+ assert.ok(Array.isArray(before.body.workspaces))
379
+ const status = await call(daemon.state, `/v1/status?cwd=${encodeURIComponent(workspace)}`)
380
+ assert.equal(status.status, 200)
381
+ const after = await call(daemon.state, '/v1/workspaces')
382
+ assert.ok(after.body.workspaces.includes(workspace), `expected ${workspace} in ${JSON.stringify(after.body.workspaces)}`)
383
+ })
384
+
385
+ test('the proxy log tail is readable (empty when the engine never ran)', async () => {
386
+ const res = await call(daemon.state, '/v1/proxy/log?bytes=4096')
387
+ assert.equal(res.status, 200)
388
+ assert.match(res.body.path, /proxy-forward\.log$/)
389
+ assert.equal(typeof res.body.text, 'string')
390
+ })
391
+
392
+ test('debug status works for a stopped program and breakpoints persist on disk', async () => {
393
+ const status = await call(daemon.state, '/v1/debug', {
394
+ method: 'POST',
395
+ body: { action: 'status', cwd: workspace, id: 'demo' },
396
+ })
397
+ assert.equal(status.status, 200)
398
+ assert.equal(status.body.program.id, 'demo')
399
+ assert.equal(status.body.attached, false)
400
+
401
+ const added = await call(daemon.state, '/v1/debug', {
402
+ method: 'POST',
403
+ body: { action: 'breakpoint-add', cwd: workspace, id: 'demo', className: 'cn.com.ris.Demo', line: 42, sessionId: 's1' },
404
+ })
405
+ assert.equal(added.status, 200)
406
+ assert.equal(added.body.pending, true)
407
+
408
+ const listed = await call(daemon.state, '/v1/debug', {
409
+ method: 'POST',
410
+ body: { action: 'breakpoints', cwd: workspace, id: 'demo' },
411
+ })
412
+ assert.equal(listed.body.breakpoints.length, 1)
413
+ assert.equal(listed.body.breakpoints[0].className, 'cn.com.ris.Demo')
414
+
415
+ const saved = JSON.parse(await (await import('node:fs/promises')).readFile(join(daemon.state.home, 'risd-debug.json'), 'utf8'))
416
+ const entries = Object.values(saved.breakpoints).flat()
417
+ assert.equal(entries.length, 1)
418
+ assert.equal(entries[0].line, 42)
419
+
420
+ const sessions = await call(daemon.state, '/v1/debug', { method: 'POST', body: { action: 'sessions' } })
421
+ assert.equal(sessions.status, 200)
422
+ assert.ok(Array.isArray(sessions.body.sessions))
423
+ })
424
+
425
+ test('unknown programs and unknown actions are reported, not swallowed', async () => {
426
+ const unknown = await call(daemon.state, '/v1/debug', {
427
+ method: 'POST',
428
+ body: { action: 'status', cwd: workspace, id: 'nope' },
429
+ })
430
+ assert.equal(unknown.status, 404)
431
+ const bad = await call(daemon.state, '/v1/debug', {
432
+ method: 'POST',
433
+ body: { action: 'warp', cwd: workspace, id: 'demo' },
434
+ })
435
+ assert.equal(bad.status, 400)
436
+ })
437
+
438
+ test('a stale debug record is listed and can be cleared from the page (D3)', async () => {
439
+ // The page used to render only live sessions, so a breakpoint set kept on disk
440
+ // after a dead daemon had no UI affordance to drop it.
441
+ const ui = readFileSync(new URL('../lib/risd/ui.js', import.meta.url), 'utf8')
442
+ assert.match(ui, /var stale = body\.stale \|\| \[\]/)
443
+ assert.match(ui, /data-forget-debug=/)
444
+ assert.match(ui, /action: 'forget'/)
445
+ })
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Phase 1b P4: the daemon is the only writer of the machine-wide rule table.
3
+ *
4
+ * The acceptance that matters here is the one the old plugin-side CAS only
5
+ * approximated: two windows posting the same base revision must not both win, and
6
+ * the loser must be told the revision that IS current (so it can reload instead of
7
+ * guessing). The daemon also serves the same injection the engine would produce —
8
+ * one implementation, two callers.
9
+ */
10
+ import assert from 'node:assert/strict'
11
+ import test from 'node:test'
12
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
13
+ import { tmpdir } from 'node:os'
14
+ import { join } from 'node:path'
15
+ import { spawnSync } from 'node:child_process'
16
+ import { RISD_API_VERSION } from '../lib/risd/state.js'
17
+ import { readProxyConfig } from '../lib/proxy.js'
18
+ import { risdConfigRevision } from '../lib/risd/view.js'
19
+ import { makeHome, removeHome, startRisdProcess } from './risd-helpers.mjs'
20
+
21
+ const FIXTURE = {
22
+ socks: { host: 'proxy.example.com', port: 10080 },
23
+ listenPort: 11081,
24
+ rules: [
25
+ { id: 'keep', program: 'git', hosts: 'git.example.com', ports: '*', enabled: true, shadow: false, source: 'user', workspace: '/tmp/ws' },
26
+ { id: 'direct-java', program: 'java', hosts: '172.20.235.*', ports: '*', enabled: true, shadow: false, source: 'user', workspace: '/tmp/ws', direct: true },
27
+ ],
28
+ shadows: [],
29
+ }
30
+
31
+ function call(state, path, { method = 'GET', body = undefined } = {}) {
32
+ const headers = {
33
+ authorization: `Bearer ${state.token}`,
34
+ 'x-risd-api-version': String(RISD_API_VERSION),
35
+ }
36
+ if (body !== undefined) headers['content-type'] = 'application/json'
37
+ return fetch(`${state.url}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) })
38
+ }
39
+
40
+ async function startFixture(t) {
41
+ const home = makeHome('risd-write-')
42
+ const saved = process.env.DSH_RIS_IDE_PROXY_HOME
43
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
44
+ t.after(() => {
45
+ if (saved === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
46
+ else process.env.DSH_RIS_IDE_PROXY_HOME = saved
47
+ removeHome(home)
48
+ })
49
+ writeFileSync(join(home, 'proxy.json'), `${JSON.stringify(FIXTURE, null, 2)}\n`, { mode: 0o600 })
50
+ const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
51
+ t.after(() => daemon.stop())
52
+ // The daemon refuses a cwd that does not exist (a write for a deleted workspace
53
+ // would create rules nobody asked for), so the fixture owns a real one.
54
+ const cwd = mkdtempSync(join(tmpdir(), 'risd-write-ws-'))
55
+ t.after(() => rmSync(cwd, { recursive: true, force: true }))
56
+ return { home, state: daemon.state, cwd }
57
+ }
58
+
59
+ function rowsFor(id, program) {
60
+ return [{ id, program, hosts: 'example.test', ports: '*', enabled: true, shadow: false, source: 'user' }]
61
+ }
62
+
63
+ test('two concurrent writes: exactly one wins, the loser gets 409 with the live revision', async (t) => {
64
+ const { home, state, cwd } = await startFixture(t)
65
+ const base = risdConfigRevision(readProxyConfig(cwd))
66
+ assert.equal(base, risdConfigRevision(FIXTURE), 'fixture revision is the one clients see')
67
+
68
+ const [a, b] = await Promise.all([
69
+ call(state, '/v1/proxy', { method: 'POST', body: { cwd, revision: base, config: { socks: FIXTURE.socks, listenPort: 11081, rules: rowsFor('write-a', 'node') } } }),
70
+ call(state, '/v1/proxy', { method: 'POST', body: { cwd, revision: base, config: { socks: FIXTURE.socks, listenPort: 11081, rules: rowsFor('write-b', 'curl') } } }),
71
+ ])
72
+ const statuses = [a.status, b.status].sort()
73
+ assert.deepEqual(statuses, [200, 409], 'one write, one conflict')
74
+
75
+ const loser = a.status === 409 ? a : b
76
+ const conflict = await loser.json()
77
+ assert.equal(conflict.ok, false)
78
+ assert.equal(conflict.conflict, true)
79
+ assert.equal(conflict.code, 'conflict')
80
+ assert.equal(conflict.message, '规则表已在别处被修改,本次改动未写入')
81
+ assert.equal(conflict.revision, risdConfigRevision(readProxyConfig(cwd)), 'the conflict names the current revision')
82
+
83
+ const onDisk = JSON.parse(readFileSync(join(home, 'proxy.json'), 'utf8'))
84
+ const ids = onDisk.rules.map((rule) => rule.id)
85
+ assert.equal(ids.filter((id) => id === 'write-a' || id === 'write-b').length, 1, 'exactly one new row landed')
86
+ // The incoming table is authoritative for non-yds rows (that is how the panel's
87
+ // full-table save works), so fixture rows absent from it are retired on purpose.
88
+ assert.equal(ids.includes('keep'), false, 'the losing table did not leak its rows')
89
+ })
90
+
91
+ test('a stale revision never lands, and an empty one is the deliberate force path', async (t) => {
92
+ const { cwd, state } = await startFixture(t)
93
+ const stale = await call(state, '/v1/proxy', {
94
+ method: 'POST',
95
+ body: { cwd, revision: '000000000000', config: { socks: FIXTURE.socks, listenPort: 11081, rules: rowsFor('stale', 'node') } },
96
+ })
97
+ assert.equal(stale.status, 409)
98
+ assert.equal((await stale.json()).revision, risdConfigRevision(readProxyConfig(cwd)))
99
+
100
+ const forced = await call(state, '/v1/proxy', {
101
+ method: 'POST',
102
+ body: { cwd, revision: '', config: { socks: FIXTURE.socks, listenPort: 11081, rules: rowsFor('forced', 'node') } },
103
+ })
104
+ assert.equal(forced.status, 200)
105
+ assert.ok(readProxyConfig(cwd).rules.some((rule) => rule.id === 'forced'))
106
+ })
107
+
108
+ test('injection is the same object the engine would inject (direct vs allow-list)', async (t) => {
109
+ const { cwd, state } = await startFixture(t)
110
+
111
+ const allowed = await call(state, `/v1/injection?cwd=${encodeURIComponent(cwd)}&program=git`)
112
+ assert.equal(allowed.status, 200)
113
+ const allow = await allowed.json()
114
+ assert.equal(allow.ok, true)
115
+ assert.equal(allow.injection.direct, false)
116
+ assert.equal(allow.injection.httpProxyUrl, 'http://127.0.0.1:11081')
117
+ assert.equal(allow.injection.env.HTTP_PROXY, 'http://127.0.0.1:11081')
118
+ assert.equal(allow.injection.env.NO_PROXY, 'localhost,127.0.0.1,::1')
119
+ assert.ok(allow.injection.jvmArgs.includes('-Dhttp.proxyPort=11081'))
120
+ assert.equal(allow.injection.jvmArgs.some((arg) => arg.startsWith('-DsocksProxyHost=')), false)
121
+
122
+ const direct = await call(state, `/v1/injection?cwd=${encodeURIComponent(cwd)}&program=java`)
123
+ const bypass = await direct.json()
124
+ assert.equal(bypass.injection.direct, true)
125
+ assert.equal(bypass.injection.jvmArgs[0], '-DsocksProxyHost=proxy.example.com')
126
+ assert.equal(bypass.injection.env.ALL_PROXY, 'socks5h://proxy.example.com:10080')
127
+
128
+ const missing = await call(state, `/v1/injection?cwd=${encodeURIComponent(cwd)}&program=node`)
129
+ assert.equal(missing.status, 200)
130
+ assert.equal((await missing.json()).injection, null, 'no enabled rule for node → nothing injected')
131
+ })
132
+
133
+ test('a save re-points the scoped git entry instead of hiding the old host', async (t) => {
134
+ const home = makeHome('risd-git-save-')
135
+ const gitconfig = join(home, 'gitconfig')
136
+ writeFileSync(gitconfig, '')
137
+ const savedHome = process.env.DSH_RIS_IDE_PROXY_HOME
138
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
139
+ const rules = (host) => [{ id: 'yds-git', program: 'git', hosts: host, ports: '*', enabled: true, shadow: false, source: 'user' }]
140
+ const table = (host) => ({ socks: { host: '127.0.0.1', port: 1080 }, listenPort: 11081, rules: rules(host), shadows: [] })
141
+ writeFileSync(join(home, 'proxy.json'), `${JSON.stringify(table('git-old.example'), null, 2)}\n`, { mode: 0o600 })
142
+ const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home, GIT_CONFIG_GLOBAL: gitconfig } })
143
+ const cwd = mkdtempSync(join(tmpdir(), 'risd-git-save-ws-'))
144
+ t.after(() => {
145
+ daemon.stop()
146
+ rmSync(cwd, { recursive: true, force: true })
147
+ if (savedHome === undefined) delete process.env.DSH_RIS_IDE_PROXY_HOME
148
+ else process.env.DSH_RIS_IDE_PROXY_HOME = savedHome
149
+ removeHome(home)
150
+ })
151
+ const value = (key) => {
152
+ const out = spawnSync('git', ['config', '--global', '--get', key], {
153
+ encoding: 'utf8',
154
+ windowsHide: true,
155
+ env: Object.assign({}, process.env, { GIT_CONFIG_GLOBAL: gitconfig }),
156
+ })
157
+ return String(out.stdout ?? '').trim()
158
+ }
159
+
160
+ const first = await call(daemon.state, '/v1/proxy', { method: 'POST', body: { cwd, revision: '', config: table('git-old.example') } })
161
+ assert.equal(first.status, 200)
162
+ assert.equal(value('http.https://git-old.example/.proxy'), 'socks5h://127.0.0.1:1080')
163
+
164
+ const second = await call(daemon.state, '/v1/proxy', { method: 'POST', body: { cwd, revision: '', config: table('git-new.example') } })
165
+ assert.equal(second.status, 200)
166
+ const body = await second.json()
167
+ assert.equal(body.git?.host, 'git-new.example', 'the save reports the host it applied')
168
+ assert.equal(value('http.https://git-old.example/.proxy'), '', 'the old host entry must be removed, not left behind')
169
+ assert.equal(value('http.https://git-new.example/.proxy'), 'socks5h://127.0.0.1:1080')
170
+ })