dsh-ris-ide 1.7.3 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +21 -7
  2. package/bin/proxy-janitor.mjs +106 -11
  3. package/bin/risd.mjs +284 -0
  4. package/bin/run-with-log.ps1 +43 -5
  5. package/lib/client.js +609 -1178
  6. package/lib/index.js +1124 -55
  7. package/lib/janitor.js +106 -15
  8. package/lib/proxy.js +86 -7
  9. package/lib/proxybridge-bundle.js +798 -0
  10. package/lib/proxybridge-health.js +206 -0
  11. package/lib/redirector.js +1615 -115
  12. package/lib/risd/build.js +91 -0
  13. package/lib/risd/debug.js +374 -0
  14. package/lib/risd/git.js +207 -0
  15. package/lib/risd/leases.js +124 -0
  16. package/lib/risd/lifecycle.js +148 -0
  17. package/lib/risd/log.js +59 -0
  18. package/lib/risd/ping.js +94 -0
  19. package/lib/risd/programs.js +348 -0
  20. package/lib/risd/server.js +1919 -0
  21. package/lib/risd/state.js +137 -0
  22. package/lib/risd/ui.js +1989 -0
  23. package/lib/risd/view.js +79 -0
  24. package/lib/risd-client.js +282 -0
  25. package/lib/standalone/window.html +14 -16
  26. package/lib/startup.js +114 -0
  27. package/package.json +4 -1
  28. package/test/client-build.test.mjs +113 -0
  29. package/test/client-viewer.test.mjs +279 -227
  30. package/test/dsh-origin.test.mjs +140 -0
  31. package/test/dsh-window-refresh.test.mjs +100 -0
  32. package/test/harness.test.mjs +9 -0
  33. package/test/host-noloop.test.mjs +74 -0
  34. package/test/host-tail.test.mjs +21 -4
  35. package/test/host-window.test.mjs +4 -4
  36. package/test/janitor.test.mjs +29 -1
  37. package/test/lifecycle.test.mjs +26 -5
  38. package/test/merge-owners.test.mjs +155 -0
  39. package/test/proxy-restart.test.mjs +39 -0
  40. package/test/proxy-window.test.mjs +45 -0
  41. package/test/proxy.test.mjs +41 -0
  42. package/test/proxybridge-bundle.test.mjs +687 -0
  43. package/test/proxybridge-health.test.mjs +116 -0
  44. package/test/redirector-bundle.test.mjs +391 -0
  45. package/test/redirector.test.mjs +413 -10
  46. package/test/risd-api.test.mjs +514 -0
  47. package/test/risd-bridge-degrade.test.mjs +101 -0
  48. package/test/risd-build.test.mjs +20 -0
  49. package/test/risd-cli-home.test.mjs +50 -0
  50. package/test/risd-client.test.mjs +130 -0
  51. package/test/risd-debug.test.mjs +261 -0
  52. package/test/risd-election.test.mjs +104 -0
  53. package/test/risd-engine.test.mjs +132 -0
  54. package/test/risd-entry.test.mjs +118 -0
  55. package/test/risd-git.test.mjs +109 -0
  56. package/test/risd-handoff.test.mjs +116 -0
  57. package/test/risd-heal.test.mjs +50 -0
  58. package/test/risd-helpers.mjs +108 -0
  59. package/test/risd-host-p2.test.mjs +147 -0
  60. package/test/risd-janitor-guard.test.mjs +46 -0
  61. package/test/risd-lease.test.mjs +83 -0
  62. package/test/risd-lifecycle.test.mjs +210 -0
  63. package/test/risd-log-follow.test.mjs +227 -0
  64. package/test/risd-mode.test.mjs +161 -0
  65. package/test/risd-ping.test.mjs +99 -0
  66. package/test/risd-programs.test.mjs +169 -0
  67. package/test/risd-restart.test.mjs +104 -0
  68. package/test/risd-review-p2.test.mjs +217 -0
  69. package/test/risd-shutdown.test.mjs +97 -0
  70. package/test/risd-teardown.test.mjs +87 -0
  71. package/test/risd-tools.test.mjs +211 -0
  72. package/test/risd-ui.test.mjs +607 -0
  73. package/test/risd-write.test.mjs +170 -0
  74. package/test/startup-reconcile.test.mjs +100 -0
  75. package/test/windows.test.mjs +37 -2
@@ -0,0 +1,607 @@
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
+ // Component health (m11828/m11838/m11863): files + runnable per side, probed only
154
+ // while the engine runs; a bridge left intercepting without the engine is a fault.
155
+ assert.match(html, /id="bridge-health-pill"/, 'the card carries a health pill')
156
+ assert.match(html, /id="bridge-health-text"/, 'health is a single line, not a per-side table (m12313)')
157
+ assert.doesNotMatch(html, /bridge-health-recheck/, 'no manual re-check button: the card polls (m12313)')
158
+ assert.doesNotMatch(html, /bridge-health-list/, 'no per-side file/version list (m12313)')
159
+ assert.doesNotMatch(html, /function sideHealthLine/, 'sides are folded into one sentence')
160
+ assert.match(html, /\/v1\/proxybridge\/health/, 'the health route is called')
161
+ assert.match(html, /setInterval\(function \(\) \{ void loadHealth\(false\) \}, 10000\)/, 'health is re-checked on a timer (m12313)')
162
+ assert.match(html, /function syncHealthTimer/, 'the timer follows tab visibility')
163
+ assert.match(html, /\.then\(function \(\) \{ return loadHealth\(true\); \}\)/, 'a toggle re-probes health (engine state changed)')
164
+ assert.match(html, /代理引擎已停止,系统层拦截仍在运行/, 'engine stopped + bridge running is called out')
165
+ assert.match(html, /function stopStrayBridge/, 'the stray bridge can be stopped from the card')
166
+ assert.match(html, /id="bridge-health-elevate"/, 'the card offers a one-click elevation attempt (m12606)')
167
+ assert.match(html, /function elevateBridge/, 'the attempt reports sudo/pkexec outcome in the banner')
168
+ assert.match(html, /el\('bridge-health-elevate'\)\.onclick = elevateBridge/)
169
+ // The elevation note lives in the component card and clears itself (m12923).
170
+ assert.match(html, /id="bridge-elevate-note"/, 'the component card owns the elevation note')
171
+ assert.match(html, /function renderElevateNote\(health\)/)
172
+ assert.match(html, /elevations\[side\] && elevations\[side\]\.active === true/)
173
+ assert.match(html, /note\.seenActive === true && active === false/)
174
+ assert.match(html, /stray\.linux === true \|\| stray\.windows === true/, 'stray is decided per side')
175
+ assert.match(html, /applicable !== false/, 'only sides that exist on this host are described')
176
+ assert.match(html, /id="bridge-health-more"/, 'the long explanation is collapsed under 说明 (m12508)')
177
+ assert.match(html, /已降级/, 'a missing side is described as degraded, not as an error')
178
+ assert.match(html, /degrade\.command/, 'the details name the sudo command even with no start attempt (m12359)')
179
+ assert.match(html, /degrade\.jvmArgs/, 'the details explain the JVM/env fallback (m12486)')
180
+ assert.match(html, /degrade\.git/, 'git is part of the degraded path too (m12567)')
181
+ assert.match(html, /程序名称\/路径/, 'the first rule column is the program name or path (m12163)')
182
+ assert.match(html, /拦截未启动/, 'engine up without interception is a transient state, not a green check (m12046)')
183
+ // SOCKS reachability chip (m09120 ②): the proxy row shows live connectivity.
184
+ assert.match(html, /id="proxy-ping"/, 'the SOCKS row carries a status chip')
185
+ assert.match(html, /function refreshPing/, 'the chip is refreshed, not written once')
186
+ assert.match(html, /setInterval\(refreshPing, 10000\)/, 'probing is periodic')
187
+ assert.match(html, /queuePing/, 'editing host/port re-probes before saving')
188
+ assert.match(html, /function workspaceLabel/, 'workspaces are labelled by folder name')
189
+ assert.match(html, /parts\.slice\(-2\)\.join\('\/'\)/, 'collisions use the parent folder')
190
+ assert.match(html, /focusIdeFrame\(\)/, 'outside clicks send focus back into the iframe')
191
+ })
192
+
193
+ test('re-opening the IDE tab keeps the iframe document (unsaved edits survive)', async () => {
194
+ // Review C-P0-1: showTab('ide') used to call loadIde(), which wiped ide-body and
195
+ // rebuilt the iframe — silently losing unsaved editor content, the debugger
196
+ // selection and the scroll position on the most common interaction ("look at the
197
+ // proxy tab, come back").
198
+ const page = await call(daemon.state, '/ui', { token: null })
199
+ assert.match(page.text, /function refreshIdeWindows\(\)/)
200
+ assert.match(page.text, /if \(frame\.getAttribute\('src'\) !== url\) frame\.src = url/)
201
+ assert.match(page.text, /if \(name === 'ide'\) \{ if \(el\('ide-frame'\)\) refreshIdeWindows\(\); else loadIde\(\); \}/)
202
+ assert.match(page.text, /function ensureIdeFrame\(\)/)
203
+ // The rebuild of #ide-body is exactly what must not happen any more.
204
+ assert.doesNotMatch(page.text, /el\('ide-body'\)\.innerHTML = ''/)
205
+ })
206
+
207
+ test('the proxy tab edits global rules without a workspace picker', async () => {
208
+ const page = await call(daemon.state, '/ui', { token: null })
209
+ const html = page.text
210
+ assert.doesNotMatch(html, /id="proxy-cwd"/, 'rules are machine-wide: no workspace input')
211
+ assert.match(html, /全局规则:按机器生效、不区分工作区/)
212
+ assert.match(html, /id="bridge-restart" hidden/, 'the restart button only shows when it is needed')
213
+ assert.match(html, /为什么要重启/, 'its tooltip explains the reason')
214
+ assert.match(html, /setBridgeStale/)
215
+ })
216
+
217
+ test('the overview stop button is just 停止', async () => {
218
+ const page = await call(daemon.state, '/ui', { token: null })
219
+ assert.match(page.text, /id="daemon-stop">停止</)
220
+ assert.doesNotMatch(page.text, /停止 daemon</)
221
+ })
222
+
223
+ test('the proxy tab reports the restart result and keeps a 409 visible', async () => {
224
+ const page = await call(daemon.state, '/ui', { token: null })
225
+ // C-P1-3: the action result is nested under `result`; reading the envelope made
226
+ // every successful restart look like "需要提权".
227
+ assert.match(page.text, /var result = \(response && response\.result\) \|\| \{\}/)
228
+ // C-P1-4: reload first, then show the conflict (the reload rewrites the banner).
229
+ assert.match(page.text, /if \(error\.status === 409\) \{[\s\S]{0,900}loadProxyTab\(\)\.then/)
230
+ // A 409 caused by our own in-flight write retries once instead of showing the
231
+ // user a conflict they cannot resolve (m10304 auto-save serialisation).
232
+ assert.match(page.text, /options\.retried !== true/)
233
+ assert.match(page.text, /saveRules\(\{ auto: auto, retried: true \}\)/)
234
+ })
235
+
236
+ test('values that reach the markup are escaped, including pill/banner classes (review C-P2-4)', async () => {
237
+ // rule.source comes from proxy.json, which any plugin/editor can write; it lands in
238
+ // a class attribute on a page that carries the daemon token.
239
+ const page = await call(daemon.state, '/ui', { token: null })
240
+ assert.match(page.text, /function pill\(text, cls\) \{ return '<span class="pill ' \+ esc\(cls \|\| ''\) \+ '">' \+ esc\(text\) \+ '<\/span>'; \}/)
241
+ assert.match(page.text, /var shape = kind === 'err' \|\| kind === 'warn' \|\| kind === 'ok' \? kind : 'warn';/)
242
+ assert.match(page.text, /'<div class="banner ' \+ shape \+ '">' \+ esc\(text\) \+ '<\/div>'/)
243
+ })
244
+
245
+ test('the log tail and the window poll only run where they are seen (review C-P2-3)', async () => {
246
+ const page = await call(daemon.state, '/ui', { token: null })
247
+ // The 2 s tail follows the pane, the tab and the visibility, not just the toggle.
248
+ assert.match(page.text, /function syncLogTimer\(\)/)
249
+ assert.match(page.text, /var wanted = state\.logOn === true && state\.tab === 'proxy' && document\.hidden !== true;/)
250
+ assert.match(page.text, /document\.addEventListener\('visibilitychange', function \(\) \{ syncLogTimer\(\); syncPingTimer\(\); syncHealthTimer\(\); \}\)/)
251
+ // The 4 s poll skips the proxy tab (it does not read the window list) and a hidden page.
252
+ assert.match(page.text, /if \(state\.tab === 'ide' \|\| state\.tab === 'overview'\) syncDshTab\(\);/)
253
+ assert.doesNotMatch(page.text, /if \(!document\.hidden\) syncDshTab\(\);/)
254
+ // Typing into the lifecycle form must not be undone by the refresh loop.
255
+ assert.match(page.text, /if \(state\.lifecycleDirty === true\) return Promise\.resolve\(state\.lifecycle \|\| null\);/)
256
+ assert.match(page.text, /el\('lifecycle-rows'\)\.addEventListener\('change'/)
257
+ assert.match(page.text, /state\.lifecycleDirty = false;/)
258
+ })
259
+
260
+ test('the embedded IDE gets its own window-lock name (review C-P2-6)', async () => {
261
+ const page = await call(daemon.state, '/ui', { token: null })
262
+ // A fixed name made the rebuilt iframe race the previous document's Web Lock and
263
+ // flash 「RIS-IDE 已在另一个窗口打开」 — and the standalone window's own name was the
264
+ // same string, so the two could take each other's lock.
265
+ assert.match(page.text, /var IDE_WNAME = 'risd-ide-' \+ Math\.random\(\)\.toString\(36\)\.slice\(2, 8\);/)
266
+ assert.match(page.text, /'&wname=' \+ encodeURIComponent\(IDE_WNAME\)/)
267
+ assert.doesNotMatch(page.text, /&wname=risd-ide'/)
268
+ })
269
+
270
+ test('a disabled IDE tab is refused before the view is shown (review C-P2-9)', async () => {
271
+ const page = await call(daemon.state, '/ui', { token: null })
272
+ // The old order made #view-ide visible and then returned on the disabled tab.
273
+ const body = page.text.slice(page.text.indexOf('function showTab(name)'))
274
+ const guard = body.indexOf("if (ideTab && ideTab.disabled) return")
275
+ const assignment = body.indexOf('state.tab = name;')
276
+ assert.ok(guard > 0 && assignment > guard, 'the disabled check must come before state.tab/visibility')
277
+ })
278
+
279
+ test('a failed engine stop explains itself on the overview (review C-P2-8)', async () => {
280
+ const page = await call(daemon.state, '/ui', { token: null })
281
+ assert.match(page.text, /id="overview-banner"/)
282
+ assert.match(page.text, /\(running \? '停止' : '启动'\) \+ '代理引擎失败:' \+ error\.message/)
283
+ // The toggle names the retry and the escape hatch instead of a bare alert().
284
+ assert.match(page.text, /可以再点一次重试;仍不行就停掉守护进程/)
285
+ })
286
+
287
+ test('GET /v1/proxy works without a cwd (the rule table is machine-wide)', async () => {
288
+ const response = await call(daemon.state, '/v1/proxy')
289
+ assert.equal(response.status, 200)
290
+ assert.equal(response.body.ok, true)
291
+ assert.ok(Array.isArray(response.body.rules), 'rules come back even when no workspace is named')
292
+ })
293
+
294
+ test('the overview offers lifecycle settings for daemon, proxy, programs and debug', async () => {
295
+ const page = await call(daemon.state, '/ui', { token: null })
296
+ assert.equal(page.status, 200)
297
+ assert.match(page.text, /生命周期/)
298
+ assert.match(page.text, /id="lifecycle-save"/)
299
+ assert.equal(page.text.includes('followDaemon'), false, 'following the daemon is forced, not configurable')
300
+ for (const key of ['daemon.followDsh', 'proxy.followDsh', 'programs.followDsh', 'debug.followDsh']) {
301
+ assert.ok(page.text.includes(`data-life="${key}"`), `missing checkbox ${key}`)
302
+ }
303
+ assert.match(page.text, /loadLifecycle/)
304
+ assert.match(page.text, /v1\/config/)
305
+ })
306
+
307
+ test('the maintenance page is served to loopback and carries the token inline', async () => {
308
+ const res = await call(daemon.state, '/ui', { token: null })
309
+ assert.equal(res.status, 200)
310
+ assert.match(res.text, /risd — 本机代理与程序维护/)
311
+ assert.ok(res.text.includes(daemon.state.token), 'the page must carry the token it uses for its own calls')
312
+ for (const title of ['概览', '代理', 'IDE', '守护进程', '代理运行状态', '运行中的项目', '调试中的进程', '规则表']) {
313
+ assert.ok(res.text.includes(title), `missing section: ${title}`)
314
+ }
315
+ // The header is just "risd" + centered tabs (IDE · 代理 · 概览): the daemon
316
+ // status moved into the overview row, so no meta text is left up there.
317
+ assert.doesNotMatch(res.text, /id="meta"/, 'no status text in the header')
318
+ assert.match(res.text, /<nav role="tablist"[^>]*>\s*<button role="tab" data-tab="ide"/, 'IDE is the first tab')
319
+ assert.ok(res.text.indexOf('data-tab="ide"') < res.text.indexOf('data-tab="proxy"'), 'IDE before 代理')
320
+ assert.ok(res.text.indexOf('data-tab="proxy"') < res.text.indexOf('data-tab="overview"'), '代理 before 概览')
321
+ // IDE is full-bleed (no card padding) and has a collapsible workspace panel.
322
+ assert.match(res.text, /\.view\[hidden\] \{ display:none !important; \}/)
323
+ assert.match(res.text, /id="ide-side"/)
324
+ assert.match(res.text, /id="ide-side-toggle"/)
325
+ assert.match(res.text, /id="view-ide" hidden>\s*<div class="ide-layout">/, 'IDE view is a layout, not a card')
326
+ // The page still accepts ?tab= (deep links/tests); switching workspace moves focus into the iframe.
327
+ assert.match(res.text, /get\('tab'\)/)
328
+ assert.match(res.text, /frame\.focus\(\)/)
329
+ // One engine button whose label is the next action (m10585): 启动 while down,
330
+ // 停止 while it runs. The old pair of buttons is gone.
331
+ assert.match(res.text, /id="engine-toggle" disabled>启动/, 'the overview can start the engine')
332
+ assert.match(res.text, /id="proxy-engine-toggle" disabled>启动/, 'the proxy tab has the same toggle')
333
+ assert.match(res.text, /engineToggle\.textContent = running \? '停止' : '启动'/)
334
+ // Starting can wait on sudo/UAC for seconds: the button says which half is running
335
+ // and refuses a second click instead of looking dead (m11279).
336
+ assert.match(res.text, /var engineBusy = false;/)
337
+ assert.match(res.text, /if \(engineBusy\) return;/)
338
+ assert.match(res.text, /button\.setAttribute\('aria-busy', 'true'\)/)
339
+ assert.match(res.text, /engineBusyAction === 'stop' \? '停止中…' : '启动中…'/)
340
+ assert.match(res.text, /button\.removeAttribute\('aria-busy'\)/)
341
+ assert.match(res.text, /if \(engineBusy\) \{\s+paintEngineButtons\(\);/, 'the 4s refresh must not repaint over the busy label')
342
+ assert.match(res.text, /button\[aria-busy="true"\] \{ opacity:\.7; cursor:progress; \}/)
343
+ assert.doesNotMatch(res.text, /id="engine-start"/, 'the separate start button is gone')
344
+ assert.doesNotMatch(res.text, /id="engine-stop"/, 'the separate stop button is gone')
345
+ // The rule table has no 读取/保存 buttons: editing is the save (m10585).
346
+ assert.doesNotMatch(res.text, /id="proxy-reload"/)
347
+ assert.doesNotMatch(res.text, /id="proxy-save"/)
348
+ // Stopping the daemon is an overview row now, not a header button: the header
349
+ // only carries the tabs.
350
+ assert.match(res.text, /id="daemon-stop"/, 'the daemon row owns the stop button')
351
+ assert.doesNotMatch(res.text, /id="shutdown"/, 'no header-level close button any more')
352
+ })
353
+
354
+ test('the maintenance page refuses a non-loopback Host header (DNS rebinding)', async () => {
355
+ const res = await call(daemon.state, '/ui', { token: null, host: 'evil.example.com' })
356
+ assert.equal(res.status, 403)
357
+ assert.equal(res.body.code, 'forbidden')
358
+ })
359
+
360
+ test('the API refuses a foreign Host or Origin (no DNS rebinding / CORS)', async () => {
361
+ const rebinding = await call(daemon.state, '/v1/health', { token: null, host: 'evil.example.com' })
362
+ assert.equal(rebinding.status, 403)
363
+ // Same loopback Host, but a page on another origin is probing the port.
364
+ const crossOrigin = await new Promise((resolve) => {
365
+ const req = request({ host: '127.0.0.1', port: daemon.state.port, path: '/v1/health', timeout: 5000,
366
+ headers: { host: `127.0.0.1:${daemon.state.port}`, origin: 'https://evil.example.com' } }, (res) => {
367
+ res.resume()
368
+ res.on('end', () => resolve(res.statusCode))
369
+ })
370
+ req.on('error', () => resolve(0))
371
+ req.end()
372
+ })
373
+ assert.equal(crossOrigin, 403)
374
+ })
375
+
376
+ test('GET /v1/dsh keeps quiet workspaces and marks them non-live (m08268)', async () => {
377
+ const file = join(daemon.home, 'dsh-window.json')
378
+ writeFileSync(file, `${JSON.stringify({ windows: [
379
+ { url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-a', sessionId: 's-a', at: new Date().toISOString() },
380
+ { url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-b', sessionId: 's-b', at: new Date(Date.now() - 10 * 60_000).toISOString() },
381
+ { url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-old', sessionId: 's-old', at: new Date(Date.now() - 30 * 24 * 3600_000).toISOString() },
382
+ ] })}\n`)
383
+ const res = await call(daemon.state, '/v1/dsh')
384
+ assert.equal(res.status, 200)
385
+ assert.equal(res.body.available, true)
386
+ // The 60s-old workspace stays selectable, the month-old one is pruned.
387
+ assert.deepEqual(res.body.windows.map((row) => row.cwd), ['/tmp/ws-a', '/tmp/ws-b'])
388
+ assert.deepEqual(res.body.windows.map((row) => row.live), [true, false])
389
+ assert.equal(res.body.windows[0].sessionId, 's-a')
390
+ assert.equal(res.body.url, 'http://127.0.0.1:3080')
391
+ })
392
+
393
+ test('GET /v1/dsh greys the IDE tab out when no window is live', async () => {
394
+ writeFileSync(join(daemon.home, 'dsh-window.json'), `${JSON.stringify({ windows: [] })}\n`)
395
+ const res = await call(daemon.state, '/v1/dsh')
396
+ assert.equal(res.status, 200)
397
+ assert.equal(res.body.available, false)
398
+ assert.match(String(res.body.reason), /dsh 未运行/)
399
+ })
400
+
401
+ test('the API is still authenticated (the page just carries the token)', async () => {
402
+ const res = await call(daemon.state, '/v1/workspaces', { token: null })
403
+ assert.equal(res.status, 401)
404
+ })
405
+
406
+ test('workspaces the daemon has served are offered to the page', async () => {
407
+ const before = await call(daemon.state, '/v1/workspaces')
408
+ assert.ok(Array.isArray(before.body.workspaces))
409
+ const status = await call(daemon.state, `/v1/status?cwd=${encodeURIComponent(workspace)}`)
410
+ assert.equal(status.status, 200)
411
+ const after = await call(daemon.state, '/v1/workspaces')
412
+ assert.ok(after.body.workspaces.includes(workspace), `expected ${workspace} in ${JSON.stringify(after.body.workspaces)}`)
413
+ })
414
+
415
+ test('the proxy log tail is readable (empty when the engine never ran)', async () => {
416
+ const res = await call(daemon.state, '/v1/proxy/log?bytes=4096')
417
+ assert.equal(res.status, 200)
418
+ assert.match(res.body.path, /proxy-forward\.log$/)
419
+ assert.equal(typeof res.body.text, 'string')
420
+ })
421
+
422
+ test('debug status works for a stopped program and breakpoints persist on disk', async () => {
423
+ const status = await call(daemon.state, '/v1/debug', {
424
+ method: 'POST',
425
+ body: { action: 'status', cwd: workspace, id: 'demo' },
426
+ })
427
+ assert.equal(status.status, 200)
428
+ assert.equal(status.body.program.id, 'demo')
429
+ assert.equal(status.body.attached, false)
430
+
431
+ const added = await call(daemon.state, '/v1/debug', {
432
+ method: 'POST',
433
+ body: { action: 'breakpoint-add', cwd: workspace, id: 'demo', className: 'cn.com.ris.Demo', line: 42, sessionId: 's1' },
434
+ })
435
+ assert.equal(added.status, 200)
436
+ assert.equal(added.body.pending, true)
437
+
438
+ const listed = await call(daemon.state, '/v1/debug', {
439
+ method: 'POST',
440
+ body: { action: 'breakpoints', cwd: workspace, id: 'demo' },
441
+ })
442
+ assert.equal(listed.body.breakpoints.length, 1)
443
+ assert.equal(listed.body.breakpoints[0].className, 'cn.com.ris.Demo')
444
+
445
+ const saved = JSON.parse(await (await import('node:fs/promises')).readFile(join(daemon.state.home, 'risd-debug.json'), 'utf8'))
446
+ const entries = Object.values(saved.breakpoints).flat()
447
+ assert.equal(entries.length, 1)
448
+ assert.equal(entries[0].line, 42)
449
+
450
+ const sessions = await call(daemon.state, '/v1/debug', { method: 'POST', body: { action: 'sessions' } })
451
+ assert.equal(sessions.status, 200)
452
+ assert.ok(Array.isArray(sessions.body.sessions))
453
+ })
454
+
455
+ test('unknown programs and unknown actions are reported, not swallowed', async () => {
456
+ const unknown = await call(daemon.state, '/v1/debug', {
457
+ method: 'POST',
458
+ body: { action: 'status', cwd: workspace, id: 'nope' },
459
+ })
460
+ assert.equal(unknown.status, 404)
461
+ const bad = await call(daemon.state, '/v1/debug', {
462
+ method: 'POST',
463
+ body: { action: 'warp', cwd: workspace, id: 'demo' },
464
+ })
465
+ assert.equal(bad.status, 400)
466
+ })
467
+
468
+ test('a stale debug record is listed and can be cleared from the page (D3)', async () => {
469
+ // The page used to render only live sessions, so a breakpoint set kept on disk
470
+ // after a dead daemon had no UI affordance to drop it.
471
+ const ui = readFileSync(new URL('../lib/risd/ui.js', import.meta.url), 'utf8')
472
+ assert.match(ui, /var stale = body\.stale \|\| \[\]/)
473
+ assert.match(ui, /data-forget-debug=/)
474
+ assert.match(ui, /action: 'forget'/)
475
+ })
476
+
477
+ // ── the page's own handlers, run against a minimal DOM stub ───────────────────
478
+ // The maintenance page is a single inline script; compiling it with stubs lets the
479
+ // tests drive real handlers (button state, guards) instead of only grepping the
480
+ // source. The stub answers every element id with the same shape, and the script is
481
+ // patched right before its closing `})();` so the tests can reach the handlers.
482
+ function loadPageProbe(script) {
483
+ const elements = new Map()
484
+ const calls = { fetch: 0 }
485
+ function fakeEl(id) {
486
+ return {
487
+ id, hidden: false, disabled: false, textContent: '', innerHTML: '', value: '', checked: false,
488
+ title: '', className: '', style: {}, dataset: {},
489
+ classList: { add() {}, remove() {}, toggle() {}, contains() { return false }, replace() {}, remove() {} },
490
+ addEventListener() {}, removeEventListener() {}, appendChild() {}, removeChild() {}, remove() {},
491
+ setAttribute() {}, getAttribute() { return null }, removeAttribute() {}, focus() {}, blur() {},
492
+ querySelector() { return fakeEl(`${id}:q`) }, querySelectorAll() { return [] },
493
+ getBoundingClientRect() { return { top: 0, left: 0, width: 0, height: 0, bottom: 0, right: 0 } },
494
+ scrollIntoView() {}, scrollTop: 0, scrollHeight: 0, offsetHeight: 0,
495
+ }
496
+ }
497
+ const getById = (id) => {
498
+ if (!elements.has(id)) elements.set(id, fakeEl(id))
499
+ return elements.get(id)
500
+ }
501
+ const document = {
502
+ hidden: false,
503
+ title: '',
504
+ getElementById: getById,
505
+ querySelector: (selector) => getById(`sel:${selector}`),
506
+ querySelectorAll: () => [],
507
+ createElement: (tag) => fakeEl(tag),
508
+ addEventListener() {},
509
+ removeEventListener() {},
510
+ body: fakeEl('body'),
511
+ documentElement: fakeEl('html'),
512
+ }
513
+ const win = {
514
+ addEventListener() {},
515
+ removeEventListener() {},
516
+ confirm: () => true,
517
+ open: () => null,
518
+ matchMedia: () => ({ matches: false, addListener() {}, addEventListener() {} }),
519
+ location: { reload() {} },
520
+ }
521
+ const storage = { getItem: () => null, setItem() {}, removeItem() {}, key: () => null, length: 0 }
522
+ const fetch = () => {
523
+ calls.fetch += 1
524
+ return Promise.reject(new Error('offline'))
525
+ }
526
+ const patched = script.replace(
527
+ /\}\)\(\);\s*$/,
528
+ '; globalThis.__pageProbe = { state: state, renderHealth: renderHealth, stopStrayBridge: stopStrayBridge, driftSaveThenReload: driftSaveThenReload }; })();',
529
+ )
530
+ const run = new Function('document', 'window', 'localStorage', 'fetch', 'setInterval', 'clearInterval', 'setTimeout', 'location', patched)
531
+ run(document, win, storage, fetch, () => 0, () => {}, () => 0, win.location)
532
+ calls.fetch = 0 // the page's own bootstrap probes /v1/health + /v1/dsh
533
+ return { page: globalThis.__pageProbe, el: getById, calls, window: win }
534
+ }
535
+
536
+ async function pageProbe() {
537
+ const page = await call(daemon.state, '/ui', { token: null })
538
+ const script = [...page.text.matchAll(/<script>([\s\S]*?)<\/script>/g)][0][1]
539
+ try {
540
+ return loadPageProbe(script)
541
+ } finally {
542
+ globalThis.__pageProbe = undefined
543
+ }
544
+ }
545
+
546
+ test('the health card keeps its buttons disabled while a request is in flight', async () => {
547
+ const probe = await pageProbe()
548
+ probe.page.state.stopBusy = true
549
+ probe.page.state.elevateBusy = true
550
+ probe.page.renderHealth({
551
+ ok: true,
552
+ engineRunning: true,
553
+ sides: { linux: { applicable: true } },
554
+ interception: { linux: false, windows: false },
555
+ stray: { linux: true, windows: false },
556
+ })
557
+ assert.equal(probe.el('bridge-health-stop').disabled, true, 'the stop button stays disabled')
558
+ assert.equal(probe.el('bridge-health-elevate').disabled, true, 'the elevate button stays disabled')
559
+
560
+ probe.page.state.stopBusy = false
561
+ probe.page.state.elevateBusy = false
562
+ probe.page.renderHealth({
563
+ ok: true,
564
+ engineRunning: true,
565
+ sides: { linux: { applicable: true } },
566
+ interception: { linux: false },
567
+ stray: { linux: false, windows: false },
568
+ })
569
+ assert.equal(probe.el('bridge-health-stop').disabled, false, 'idle renders re-enable the stop button')
570
+ assert.equal(probe.el('bridge-health-elevate').disabled, false, 'idle renders re-enable the elevate button')
571
+ assert.equal(probe.el('bridge-health-elevate').textContent, '提权启动', 'the label is restored when idle')
572
+ })
573
+
574
+ test('a second click while a health action is in flight is ignored', async () => {
575
+ const probe = await pageProbe()
576
+ probe.page.state.stopBusy = true
577
+ probe.page.stopStrayBridge()
578
+ assert.equal(probe.calls.fetch, 0, 'the duplicate stop never reaches the daemon')
579
+ })
580
+
581
+ test('the drift reload respects unsaved proxy rules', async () => {
582
+ const probe = await pageProbe()
583
+ probe.page.state.proxyDirty = true
584
+ probe.window.confirm = () => false
585
+ probe.page.driftSaveThenReload()
586
+ assert.equal(probe.calls.fetch, 0, 'refusing the confirm aborts before saving/reloading')
587
+ })
588
+
589
+ test('the elevation warning is written after the proxy refresh', async () => {
590
+ const source = readFileSync(new URL('../lib/risd/ui.js', import.meta.url), 'utf8')
591
+ const slice = source.slice(source.indexOf('function toggleProxyEngine('), source.indexOf("el('engine-toggle').onclick"))
592
+ const refreshAt = slice.indexOf('loadProxyTab()')
593
+ const warnAt = slice.indexOf("host.innerHTML = banner('warn', warn)")
594
+ assert.ok(refreshAt >= 0, 'the engine toggle refreshes the proxy tab')
595
+ assert.ok(warnAt > refreshAt, 'the elevation warning is written after loadProxyTab cleared the banner')
596
+ assert.doesNotMatch(slice, /if \(skipped\.length > 0\) \{\n\s+host\.innerHTML/, 'no warning is written before the refresh')
597
+ })
598
+
599
+ test('the drift path confirms unsaved lifecycle settings too', async () => {
600
+ const source = readFileSync(new URL('../lib/risd/ui.js', import.meta.url), 'utf8')
601
+ const saveAt = source.indexOf('function driftSaveThenReload()')
602
+ const save = source.slice(saveAt, saveAt + 1600)
603
+ assert.match(save, /proxyDirty === true && window\.confirm\('代理规则还没保存,刷新会丢失'\)/)
604
+ assert.match(save, /lifecycleDirty === true && window\.confirm\('生命周期设置还没保存,刷新会丢失'\)/)
605
+ const restart = source.slice(source.indexOf('function restartDaemonThenReload()'), source.indexOf('function reloadPage()'))
606
+ assert.match(restart, /lifecycleDirty === true && window\.confirm\('生命周期设置还没保存,重启并刷新会丢失'\)/)
607
+ })