dsh-ris-ide 1.8.0 → 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.
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Daemon restart helpers (review A4-P2-5/P2-6/P2-7).
3
+ *
4
+ * `POST /v1/restart` cannot be exercised end-to-end from a unit test without
5
+ * replacing the real daemon, so the two pieces that carry the behaviour are tested
6
+ * directly: the successor argv (port + pid identity) and the wait that keeps a
7
+ * successor from stealing the port or waiting on a reused pid.
8
+ */
9
+ import assert from 'node:assert/strict'
10
+ import test from 'node:test'
11
+ import { spawn } from 'node:child_process'
12
+ import { __test, readStartTime, successorArgs, waitForPidExit } from '../lib/risd/server.js'
13
+
14
+ /** Spawn a detached-ish node child that lives for `ms`; returns {child, done}. */
15
+ function liveChild(ms) {
16
+ const child = spawn(process.execPath, ['-e', `setTimeout(() => {}, ${ms})`], { stdio: 'ignore' })
17
+ const done = new Promise((resolve) => child.once('exit', resolve))
18
+ return { child, done }
19
+ }
20
+
21
+ test('the successor keeps the port the daemon actually bound and the pid identity (A4-P2-6/A4-P2-5)', () => {
22
+ const argv = successorArgs({ pid: 4321, port: 11082, startTime: '987654' })
23
+ assert.equal(argv[1], 'serve', 'the CLI is asked to serve')
24
+ assert.deepEqual(argv.slice(2, 4), ['--wait-pid', '4321'], 'it waits for this daemon pid')
25
+ assert.deepEqual(argv.slice(argv.indexOf('--port'), argv.indexOf('--port') + 2), ['--port', '11082'], 'it binds the same port, not the default')
26
+ assert.deepEqual(argv.slice(argv.indexOf('--wait-start'), argv.indexOf('--wait-start') + 2), ['--wait-start', '987654'], 'it carries the start time that proves the pid identity')
27
+
28
+ const defaulted = successorArgs({ pid: 7, port: 0, startTime: '' })
29
+ assert.equal(defaulted.includes('--port'), false, 'port 0 means "let the OS choose", never --port 0')
30
+ assert.equal(defaulted.includes('--wait-start'), false, 'no start time on platforms without /proc')
31
+ assert.deepEqual(defaulted.slice(2, 4), ['--wait-pid', '7'])
32
+ })
33
+
34
+ test('waitForPidExit resolves as soon as the predecessor exits', async (t) => {
35
+ const { child, done } = liveChild(400)
36
+ t.after(() => child.kill('SIGKILL'))
37
+ const startedAt = Date.now()
38
+ const result = await waitForPidExit(child.pid, 5000)
39
+ const elapsed = Date.now() - startedAt
40
+ assert.deepEqual(result, { ok: true, timedOut: false })
41
+ assert.ok(elapsed >= 50, `waited at least one poll tick (${elapsed}ms)`)
42
+ await done
43
+ })
44
+
45
+ test('a reused pid is treated as exited instead of waited on (A4-P2-5)', async (t) => {
46
+ if (process.platform !== 'linux') return t.skip('start times come from /proc')
47
+ const { child } = liveChild(10_000)
48
+ t.after(() => child.kill('SIGKILL'))
49
+ const startedAt = Date.now()
50
+ // '1' is a valid-looking start time but cannot match this fresh child.
51
+ const result = await waitForPidExit(child.pid, 5000, '1')
52
+ const elapsed = Date.now() - startedAt
53
+ assert.deepEqual(result, { ok: true, timedOut: false }, 'a different start time proves the old process is gone')
54
+ assert.ok(elapsed < 1500, `did not wait for the unrelated process to exit (${elapsed}ms)`)
55
+ })
56
+
57
+ test('a live pid with the matching start time makes waitForPidExit time out (A4-P2-5)', async (t) => {
58
+ if (process.platform !== 'linux') return t.skip('start times come from /proc')
59
+ const startTime = readStartTime(process.pid)
60
+ assert.match(startTime, /^\d+$/, '/proc/<pid>/stat exposes a numeric start time')
61
+ const startedAt = Date.now()
62
+ const result = await waitForPidExit(process.pid, 150, startTime)
63
+ const elapsed = Date.now() - startedAt
64
+ assert.deepEqual(result, { ok: false, timedOut: true })
65
+ assert.ok(elapsed >= 150, `honoured the deadline (${elapsed}ms)`)
66
+ })
67
+
68
+ test('without a start time the wait falls back to kill(0) and still times out', async (t) => {
69
+ const { child } = liveChild(10_000)
70
+ t.after(() => child.kill('SIGKILL'))
71
+ const result = await waitForPidExit(child.pid, 200, '')
72
+ assert.deepEqual(result, { ok: false, timedOut: true })
73
+ })
74
+
75
+ test('a failed successor spawn clears restarting so a retry can work (A4-P2-7)', (t) => {
76
+ const original = __test.restartHooks.spawn
77
+ t.after(() => { __test.restartHooks.spawn = original; __test.setRestarting(false) })
78
+ __test.restartHooks.spawn = () => { throw new Error('spawn EACCES') }
79
+ __test.setRestarting(true)
80
+ const child = __test.spawnRestartSuccessor(11082)
81
+ assert.equal(child, null)
82
+ assert.equal(__test.isRestarting(), false, 'the next POST must be able to try again')
83
+ })
84
+
85
+ test('the spawned successor carries the live port and a dying child clears restarting (A4-P2-6/A4-P2-7)', (t) => {
86
+ const original = __test.restartHooks.spawn
87
+ const handlers = {}
88
+ const fake = { unref() {}, once(event, fn) { handlers[event] = fn; return this } }
89
+ const calls = []
90
+ t.after(() => { __test.restartHooks.spawn = original; __test.setRestarting(false) })
91
+ __test.restartHooks.spawn = (...args) => { calls.push(args); return fake }
92
+ __test.setRestarting(true)
93
+ assert.equal(__test.spawnRestartSuccessor(11082), fake)
94
+ assert.equal(__test.isRestarting(), true, 'a pending successor keeps the restart flag set')
95
+ const argv = calls[0][1]
96
+ assert.equal(argv[1], 'serve')
97
+ assert.ok(argv.includes('--wait-pid'), 'the successor waits for this pid')
98
+ assert.deepEqual(argv.slice(argv.indexOf('--port'), argv.indexOf('--port') + 2), ['--port', '11082'], 'the successor binds the port this daemon actually bound')
99
+ handlers.error(new Error('ENOENT'))
100
+ assert.equal(__test.isRestarting(), false, 'a spawn error must not leave the daemon marked as restarting')
101
+ __test.setRestarting(true)
102
+ handlers.exit(3, null)
103
+ assert.equal(__test.isRestarting(), false, 'a successor exiting non-zero must not leave the daemon marked as restarting')
104
+ })
@@ -150,6 +150,36 @@ test('the IDE tab drops the toolbar and names workspaces by folder', async () =>
150
150
  assert.match(html, /function uploadBundle/, 'the upload posts the picked file')
151
151
  assert.match(html, /\/v1\/proxybridge\/upload/, 'the upload route is called')
152
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)')
153
183
  // SOCKS reachability chip (m09120 ②): the proxy row shows live connectivity.
154
184
  assert.match(html, /id="proxy-ping"/, 'the SOCKS row carries a status chip')
155
185
  assert.match(html, /function refreshPing/, 'the chip is refreshed, not written once')
@@ -217,7 +247,7 @@ test('the log tail and the window poll only run where they are seen (review C-P2
217
247
  // The 2 s tail follows the pane, the tab and the visibility, not just the toggle.
218
248
  assert.match(page.text, /function syncLogTimer\(\)/)
219
249
  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\(\); \}\)/)
250
+ assert.match(page.text, /document\.addEventListener\('visibilitychange', function \(\) \{ syncLogTimer\(\); syncPingTimer\(\); syncHealthTimer\(\); \}\)/)
221
251
  // The 4 s poll skips the proxy tab (it does not read the window list) and a hidden page.
222
252
  assert.match(page.text, /if \(state\.tab === 'ide' \|\| state\.tab === 'overview'\) syncDshTab\(\);/)
223
253
  assert.doesNotMatch(page.text, /if \(!document\.hidden\) syncDshTab\(\);/)
@@ -443,3 +473,135 @@ test('a stale debug record is listed and can be cleared from the page (D3)', asy
443
473
  assert.match(ui, /data-forget-debug=/)
444
474
  assert.match(ui, /action: 'forget'/)
445
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
+ })