dsh-ris-ide 1.8.1 → 1.8.2

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 (47) hide show
  1. package/README.md +2 -2
  2. package/lib/client.js +311 -72
  3. package/lib/debug/vendor/README.md +14 -0
  4. package/lib/debug/vendor/jdwp/client.js +9 -4
  5. package/lib/debug/vendor/src/jdwp/client.ts +12 -5
  6. package/lib/index.js +794 -48
  7. package/lib/redirector.js +42 -2
  8. package/lib/risd/lifecycle.js +9 -3
  9. package/lib/risd/server.js +308 -13
  10. package/lib/risd/ui.js +149 -112
  11. package/lib/risd-client.js +4 -1
  12. package/lib/startup.js +27 -7
  13. package/package.json +2 -2
  14. package/test/client-viewer.test.mjs +188 -95
  15. package/test/clipboard.test.mjs +259 -0
  16. package/test/debug-engine.test.mjs +3 -1
  17. package/test/dsh-origin.test.mjs +4 -11
  18. package/test/dsh-window-refresh.test.mjs +166 -1
  19. package/test/harness.test.mjs +1 -1
  20. package/test/helpers/cmd.mjs +29 -0
  21. package/test/helpers/tgz.mjs +71 -0
  22. package/test/host-search.test.mjs +18 -11
  23. package/test/host-tail.test.mjs +119 -24
  24. package/test/proxy-route.test.mjs +61 -0
  25. package/test/proxy-window.test.mjs +5 -0
  26. package/test/proxy.test.mjs +13 -1
  27. package/test/proxybridge-bundle.test.mjs +1 -59
  28. package/test/redirector-bundle.test.mjs +21 -67
  29. package/test/redirector.test.mjs +41 -4
  30. package/test/risd-api.test.mjs +81 -28
  31. package/test/risd-bridge-degrade.test.mjs +3 -29
  32. package/test/risd-engine.test.mjs +13 -50
  33. package/test/risd-entry.test.mjs +0 -37
  34. package/test/risd-follow-start.test.mjs +101 -0
  35. package/test/risd-git.test.mjs +7 -5
  36. package/test/risd-handoff.test.mjs +6 -50
  37. package/test/risd-helpers.mjs +150 -3
  38. package/test/risd-host-p2.test.mjs +2 -30
  39. package/test/risd-lifecycle.test.mjs +25 -0
  40. package/test/risd-programs.test.mjs +4 -34
  41. package/test/risd-review-p2.test.mjs +0 -13
  42. package/test/risd-shutdown.test.mjs +5 -38
  43. package/test/risd-teardown.test.mjs +8 -27
  44. package/test/risd-ui.test.mjs +169 -13
  45. package/test/risd-write.test.mjs +2 -1
  46. package/test/startup-reconcile.test.mjs +44 -8
  47. package/test/proxy-restart.test.mjs +0 -39
@@ -5,44 +5,25 @@
5
5
  */
6
6
  import assert from 'node:assert/strict'
7
7
  import test from 'node:test'
8
- import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
8
+ import { existsSync, mkdtempSync, rmSync } from 'node:fs'
9
9
  import { tmpdir } from 'node:os'
10
10
  import { join } from 'node:path'
11
- import { RISD_API_VERSION } from '../lib/risd/state.js'
12
- import { makeHome, removeHome, sleep, startRisdProcess } from './risd-helpers.mjs'
13
-
14
- function headers(state) {
15
- return { authorization: `Bearer ${state.token}`, 'x-risd-api-version': String(RISD_API_VERSION), 'content-type': 'application/json' }
16
- }
17
-
18
- // Teardown is 300ms debounce + engine stop (5s grace) + bridge/git attempts; on a
19
- // loaded machine (full suite, four files in parallel) that can exceed 8s even when
20
- // the behaviour is correct, so the waits are generous on purpose.
21
- async function waitFor(fn, timeoutMs = 15000) {
22
- const deadline = Date.now() + timeoutMs
23
- while (Date.now() < deadline) {
24
- if (await fn()) return true
25
- await sleep(120)
26
- }
27
- return false
28
- }
11
+ // The waits are deliberately generous: teardown is 300ms debounce + engine stop
12
+ // (5s grace) + bridge/git attempts, so `waitFor`'s 15s default is the floor.
13
+ import { makeHome, pickPort, removeHome, risdHeaders, sleep, startRisdProcess, waitFor, writeEngineFixture } from './risd-helpers.mjs'
29
14
 
30
15
  async function startFixture(t) {
31
16
  const home = makeHome('risd-teardown-')
32
17
  const cwd = mkdtempSync(join(tmpdir(), 'risd-teardown-ws-'))
33
- const port = 20000 + Math.floor(Math.random() * 20000)
34
- writeFileSync(join(home, 'proxy.json'), JSON.stringify({
35
- socks: { host: '127.0.0.1', port: 1, dbPort: 0, redisPort: 0 },
36
- listenPort: port,
37
- rules: [{ id: 'rule-1', program: 'java', hosts: ['127.0.0.1'], ports: ['443'], enabled: true, shadow: false, source: 'user', workspace: cwd }],
38
- }))
18
+ const port = pickPort()
19
+ writeEngineFixture(home, port, { workspace: cwd })
39
20
  const daemon = await startRisdProcess({ home, env: { DSH_RIS_IDE_PROXY_HOME: home } })
40
21
  t.after(async () => {
41
22
  await daemon.stop()
42
23
  removeHome(home)
43
24
  rmSync(cwd, { recursive: true, force: true })
44
25
  })
45
- const h = headers(daemon.state)
26
+ const h = risdHeaders(daemon.state)
46
27
  const startEngine = async () => {
47
28
  const res = await fetch(`${daemon.state.url}/v1/engine`, { method: 'POST', headers: h, body: JSON.stringify({ action: 'start', cwd }) })
48
29
  return res.json()
@@ -79,7 +60,7 @@ test('a dead owner is swept and then the engine is torn down', async (t) => {
79
60
 
80
61
  const orphan = (await import('node:child_process')).spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })
81
62
  t.after(() => orphan.kill('SIGKILL'))
82
- const h = headers(fx.daemon.state)
63
+ const h = risdHeaders(fx.daemon.state)
83
64
  await fetch(`${fx.daemon.state.url}/v1/leases`, { method: 'POST', headers: h, body: JSON.stringify({ ownerPid: orphan.pid, sessionId: 'gone', cwd: fx.cwd }) })
84
65
  orphan.kill('SIGKILL')
85
66
 
@@ -163,9 +163,13 @@ test('the IDE tab drops the toolbar and names workspaces by folder', async () =>
163
163
  assert.match(html, /\.then\(function \(\) \{ return loadHealth\(true\); \}\)/, 'a toggle re-probes health (engine state changed)')
164
164
  assert.match(html, /代理引擎已停止,系统层拦截仍在运行/, 'engine stopped + bridge running is called out')
165
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/)
166
+ assert.match(html, /id="bridge-fix" hidden/, 'the card owns the single enforcement button (m13910)')
167
+ assert.match(html, /function fixBridge/, 'the attempt reports sudo/pkexec outcome in the banner')
168
+ assert.match(html, /el\('bridge-fix'\)\.onclick = fixBridge/)
169
+ assert.match(html, /function paintBridgeFix/, 'state decides the label: start vs restart')
170
+ assert.match(html, /interactive: true/, 'only a click may raise the elevation prompt')
171
+ assert.doesNotMatch(html, /proxy-start-with-dsh/, 'the follow-dsh lifecycle checkbox is the only policy (m13950)')
172
+ assert.match(html, /dsh 接入时启动引擎/, 'the lifecycle row describes both halves of following dsh')
169
173
  // The elevation note lives in the component card and clears itself (m12923).
170
174
  assert.match(html, /id="bridge-elevate-note"/, 'the component card owns the elevation note')
171
175
  assert.match(html, /function renderElevateNote\(health\)/)
@@ -185,7 +189,10 @@ test('the IDE tab drops the toolbar and names workspaces by folder', async () =>
185
189
  assert.match(html, /function refreshPing/, 'the chip is refreshed, not written once')
186
190
  assert.match(html, /setInterval\(refreshPing, 10000\)/, 'probing is periodic')
187
191
  assert.match(html, /queuePing/, 'editing host/port re-probes before saving')
188
- assert.match(html, /function workspaceLabel/, 'workspaces are labelled by folder name')
192
+ assert.match(html, /function workspaceLabel/, 'one label helper decides what a workspace is called')
193
+ assert.match(html, /typeof win\.title === 'string'/, 'the dsh sidebar title wins when the host resolved one (m13800)')
194
+ assert.match(html, /function workspacePathLabel/, 'the folder name stays as the fallback for an older host')
195
+ assert.match(html, /\|' \+ \(typeof win\.title === 'string' \? win\.title : ''\)/, 'a rename alone must repaint the panel')
189
196
  assert.match(html, /parts\.slice\(-2\)\.join\('\/'\)/, 'collisions use the parent folder')
190
197
  assert.match(html, /focusIdeFrame\(\)/, 'outside clicks send focus back into the iframe')
191
198
  })
@@ -209,9 +216,11 @@ test('the proxy tab edits global rules without a workspace picker', async () =>
209
216
  const html = page.text
210
217
  assert.doesNotMatch(html, /id="proxy-cwd"/, 'rules are machine-wide: no workspace input')
211
218
  assert.match(html, /全局规则:按机器生效、不区分工作区/)
212
- assert.match(html, /id="bridge-restart" hidden/, 'the restart button only shows when it is needed')
219
+ assert.doesNotMatch(html, /id="bridge-restart"/, 'the merge moved the restart into the component card (m13910)')
213
220
  assert.match(html, /为什么要重启/, 'its tooltip explains the reason')
214
221
  assert.match(html, /setBridgeStale/)
222
+ assert.match(html, /bridgeStaleReason/, 'the stale reason is state, not a hidden input')
223
+ assert.match(html, /保存不会启动它/, 'a save names the start button instead of starting the engine')
215
224
  })
216
225
 
217
226
  test('the overview stop button is just 停止', async () => {
@@ -295,7 +304,17 @@ test('the overview offers lifecycle settings for daemon, proxy, programs and deb
295
304
  const page = await call(daemon.state, '/ui', { token: null })
296
305
  assert.equal(page.status, 200)
297
306
  assert.match(page.text, /生命周期/)
298
- assert.match(page.text, /id="lifecycle-save"/)
307
+ // Toggling is the save (m13960): no button, no second confirmation step.
308
+ assert.doesNotMatch(page.text, /id="lifecycle-save"/)
309
+ assert.match(page.text, /勾选即自动保存/)
310
+ assert.match(page.text, /el\('lifecycle-rows'\)\.addEventListener\('change', scheduleLifecycleSave\)/)
311
+ assert.match(page.text, /function scheduleLifecycleSave\(\)/)
312
+ assert.match(page.text, /function saveLifecycle\(auto\)/)
313
+ assert.match(page.text, /已自动保存/)
314
+ // A toggle that lands mid-POST must not be undone by refilling the form from the
315
+ // daemon's (older) answer: the queued save carries it instead.
316
+ assert.match(page.text, /var queued = lifecycleQueued === true;/)
317
+ assert.match(page.text, /queued === true \? Promise\.resolve\(\) : loadLifecycle\(\)/)
299
318
  assert.equal(page.text.includes('followDaemon'), false, 'following the daemon is forced, not configurable')
300
319
  for (const key of ['daemon.followDsh', 'proxy.followDsh', 'programs.followDsh', 'debug.followDsh']) {
301
320
  assert.ok(page.text.includes(`data-life="${key}"`), `missing checkbox ${key}`)
@@ -398,6 +417,136 @@ test('GET /v1/dsh greys the IDE tab out when no window is live', async () => {
398
417
  assert.match(String(res.body.reason), /dsh 未运行/)
399
418
  })
400
419
 
420
+ test('a sidebar snapshot with no remembered window still enables the IDE (m00186)', async () => {
421
+ // The plugin now publishes the sidebar (titles + sessions + origin) on its refresh
422
+ // tick even when dsh never served the IDE panel, so `windows` can legitimately be
423
+ // empty while the document proves dsh is alive. The page must offer every workspace
424
+ // instead of greying the tab out — switching workspaces is exactly what it is for.
425
+ const now = new Date().toISOString()
426
+ writeFileSync(join(daemon.home, 'dsh-window.json'), `${JSON.stringify({
427
+ windows: [],
428
+ workspaces: [
429
+ { cwd: '/tmp/ws-a', title: 'alpha', sessionId: 's-a', active: true },
430
+ { cwd: '/tmp/ws-b', title: 'beta', sessionId: '', active: false },
431
+ ],
432
+ url: 'http://127.0.0.1:3080',
433
+ at: now,
434
+ })}\n`)
435
+ const res = await call(daemon.state, '/v1/dsh')
436
+ assert.equal(res.status, 200)
437
+ assert.equal(res.body.available, true, 'the sidebar snapshot is proof dsh is running')
438
+ assert.deepEqual(res.body.windows.map((row) => [row.cwd, row.title, row.live]), [
439
+ ['/tmp/ws-a', 'alpha', true],
440
+ ['/tmp/ws-b', 'beta', true],
441
+ ], 'both workspaces are selectable, in the sidebar order')
442
+ assert.deepEqual(res.body.windows.map((row) => row.source), ['workspace', 'workspace'])
443
+ assert.equal(res.body.windows[0].sessionId, 's-a')
444
+ assert.equal(res.body.windows[1].sessionId, '', 'no session → the window page boots on the cwd')
445
+ assert.deepEqual(res.body.windows.map((row) => row.active), [true, false], 'a workspace without a live session is still listed')
446
+ assert.equal(res.body.url, 'http://127.0.0.1:3080')
447
+ })
448
+
449
+ test('the unavailable hint no longer asks the user to open the IDE panel first (m00186)', async () => {
450
+ // The old note told the user to open the RIS-IDE panel once — that request was the
451
+ // write which happened to seed dsh-window.json. The refresh tick publishes the
452
+ // sidebar by itself now, so promising it would be misleading.
453
+ const page = await call(daemon.state, '/ui', { token: null })
454
+ assert.match(page.text, /启动 dsh(工作区在 dsh 侧栏里)后,这里会自动可用/)
455
+ assert.doesNotMatch(page.text, /打开一次 RIS-IDE 面板/)
456
+ })
457
+
458
+ test('a workspace without a live session stays selectable, labelled 无会话 (m00186)', async () => {
459
+ // Switching workspaces is what the panel is for. A dsh workspace whose session is
460
+ // gone still opens: the window page boots on the cwd when it cannot resolve the
461
+ // session, so the row must not be hidden or disabled.
462
+ const probe = await pageProbe()
463
+ const windows = [
464
+ { cwd: '/tmp/ws-a', title: 'alpha', sessionId: 's-a', url: 'http://127.0.0.1:3080', live: true, active: true },
465
+ { cwd: '/tmp/ws-b', title: 'beta', sessionId: '', url: 'http://127.0.0.1:3080', live: true, active: false },
466
+ ]
467
+ probe.page.renderIde(windows, windows[0])
468
+ const list = probe.el('ide-ws-list').innerHTML
469
+ assert.match(list, /data-cwd="\/tmp\/ws-a"/, 'the live workspace is a button')
470
+ assert.match(list, /data-cwd="\/tmp\/ws-b"/, 'the sessionless workspace is a button too')
471
+ assert.match(list, /alpha/)
472
+ assert.match(list, /beta(无会话)/, 'the label says why it may not resume')
473
+ assert.match(probe.el('ide-frame').src, /cwd=%2Ftmp%2Fws-a&sessionId=s-a/)
474
+ // Selecting the sessionless row must still produce a loadable window URL.
475
+ probe.page.selectIdeWindow(windows, '/tmp/ws-b')
476
+ const src = probe.el('ide-frame').src
477
+ assert.match(src, /cwd=%2Ftmp%2Fws-b/, 'boots on the cwd')
478
+ assert.doesNotMatch(src, /sessionId=/, 'no session to name: the host resolves the cwd instead')
479
+ })
480
+
481
+ test('the unavailable hint names the workspaces dsh did report (m00186)', async () => {
482
+ const probe = await pageProbe()
483
+ probe.page.ideUnavailable({ reason: 'dsh 正在启动', knownWorkspaces: 3 })
484
+ const html = probe.el('ide-msg').innerHTML
485
+ assert.match(html, /IDE 不可用:dsh 正在启动/)
486
+ assert.match(html, /已发现 3 个 dsh 工作区/, 'a count separates "starting" from "not installed"')
487
+ // No count → no dangling parenthesis when the host reported nothing at all.
488
+ probe.page.ideUnavailable({ reason: 'dsh 未运行' })
489
+ assert.doesNotMatch(probe.el('ide-msg').innerHTML, /已发现/)
490
+ })
491
+
492
+ test('GET /v1/dsh mirrors the dsh sidebar: every workspace, labelled by its title (m13800)', async () => {
493
+ // The plugin writes the sidebar snapshot next to the remembered windows. A workspace
494
+ // nobody opened the IDE for still belongs on the page, in the sidebar's own order,
495
+ // and the label is the dsh title — which is exactly what a rename changes.
496
+ const now = new Date().toISOString()
497
+ writeFileSync(join(daemon.home, 'dsh-window.json'), `${JSON.stringify({
498
+ windows: [
499
+ { url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-a', sessionId: 's-a', title: 'alpha', at: now },
500
+ ],
501
+ workspaces: [
502
+ { cwd: '/tmp/ws-a', title: 'alpha', sessionId: 's-a' },
503
+ { cwd: '/tmp/ws-b', title: 'beta', sessionId: '' },
504
+ ],
505
+ url: 'http://127.0.0.1:3080',
506
+ at: now,
507
+ })}\n`)
508
+ const res = await call(daemon.state, '/v1/dsh')
509
+ assert.equal(res.status, 200)
510
+ assert.equal(res.body.available, true)
511
+ assert.deepEqual(res.body.windows.map((row) => [row.cwd, row.title, row.live]), [
512
+ ['/tmp/ws-a', 'alpha', true],
513
+ ['/tmp/ws-b', 'beta', true],
514
+ ], 'sidebar order wins and both rows are selectable')
515
+ assert.equal(res.body.windows[1].source, 'workspace', 'a workspace without a window is not a remembered window')
516
+ assert.equal(res.body.windows[1].url, 'http://127.0.0.1:3080', 'the document origin carries it')
517
+ assert.equal(res.body.url, 'http://127.0.0.1:3080')
518
+ })
519
+
520
+ test('GET /v1/dsh re-labels a renamed workspace without losing it (m13800)', async () => {
521
+ // Rename = title change only: the path is the identity, so the same row comes back
522
+ // with the new label — the page must not fall back to the folder name.
523
+ const now = new Date().toISOString()
524
+ writeFileSync(join(daemon.home, 'dsh-window.json'), `${JSON.stringify({
525
+ windows: [{ url: 'http://127.0.0.1:3080', cwd: '/srv/apps/dzjg/workspace', sessionId: 's-a', title: 'dzjg-new', at: now }],
526
+ workspaces: [{ cwd: '/srv/apps/dzjg/workspace', title: 'dzjg-new', sessionId: 's-a' }],
527
+ url: 'http://127.0.0.1:3080',
528
+ at: now,
529
+ })}\n`)
530
+ const res = await call(daemon.state, '/v1/dsh')
531
+ assert.equal(res.body.windows.length, 1)
532
+ assert.equal(res.body.windows[0].cwd, '/srv/apps/dzjg/workspace', 'the path is untouched')
533
+ assert.equal(res.body.windows[0].title, 'dzjg-new')
534
+ })
535
+
536
+ test('GET /v1/dsh drops a stale sidebar snapshot but keeps fresh windows (m13800)', async () => {
537
+ // The snapshot is only good while its writer is alive: 8 days after the last answer
538
+ // the workspace list is gone, while the remembered window follows its own TTL.
539
+ const old = new Date(Date.now() - 8 * 24 * 3600_000).toISOString()
540
+ writeFileSync(join(daemon.home, 'dsh-window.json'), `${JSON.stringify({
541
+ windows: [{ url: 'http://127.0.0.1:3080', cwd: '/tmp/ws-a', sessionId: 's-a', title: 'alpha', at: new Date().toISOString() }],
542
+ workspaces: [{ cwd: '/tmp/ws-a', title: 'alpha' }, { cwd: '/tmp/ws-gone', title: 'gone' }],
543
+ url: 'http://127.0.0.1:3080',
544
+ at: old,
545
+ })}\n`)
546
+ const res = await call(daemon.state, '/v1/dsh')
547
+ assert.deepEqual(res.body.windows.map((row) => row.cwd), ['/tmp/ws-a'])
548
+ })
549
+
401
550
  test('the API is still authenticated (the page just carries the token)', async () => {
402
551
  const res = await call(daemon.state, '/v1/workspaces', { token: null })
403
552
  assert.equal(res.status, 401)
@@ -525,7 +674,7 @@ function loadPageProbe(script) {
525
674
  }
526
675
  const patched = script.replace(
527
676
  /\}\)\(\);\s*$/,
528
- '; globalThis.__pageProbe = { state: state, renderHealth: renderHealth, stopStrayBridge: stopStrayBridge, driftSaveThenReload: driftSaveThenReload }; })();',
677
+ '; globalThis.__pageProbe = { state: state, renderHealth: renderHealth, stopStrayBridge: stopStrayBridge, driftSaveThenReload: driftSaveThenReload, paintBridgeFix: paintBridgeFix, fixBridge: fixBridge, renderIde: renderIde, ideUnavailable: ideUnavailable, selectIdeWindow: selectIdeWindow }; })();',
529
678
  )
530
679
  const run = new Function('document', 'window', 'localStorage', 'fetch', 'setInterval', 'clearInterval', 'setTimeout', 'location', patched)
531
680
  run(document, win, storage, fetch, () => 0, () => {}, () => 0, win.location)
@@ -543,10 +692,10 @@ async function pageProbe() {
543
692
  }
544
693
  }
545
694
 
546
- test('the health card keeps its buttons disabled while a request is in flight', async () => {
695
+ test('the enforcement button stays disabled while a request is in flight', async () => {
547
696
  const probe = await pageProbe()
548
697
  probe.page.state.stopBusy = true
549
- probe.page.state.elevateBusy = true
698
+ probe.page.state.fixBusy = true
550
699
  probe.page.renderHealth({
551
700
  ok: true,
552
701
  engineRunning: true,
@@ -555,10 +704,10 @@ test('the health card keeps its buttons disabled while a request is in flight',
555
704
  stray: { linux: true, windows: false },
556
705
  })
557
706
  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')
707
+ assert.equal(probe.el('bridge-fix').disabled, true, 'the enforcement button stays disabled')
559
708
 
560
709
  probe.page.state.stopBusy = false
561
- probe.page.state.elevateBusy = false
710
+ probe.page.state.fixBusy = false
562
711
  probe.page.renderHealth({
563
712
  ok: true,
564
713
  engineRunning: true,
@@ -567,8 +716,15 @@ test('the health card keeps its buttons disabled while a request is in flight',
567
716
  stray: { linux: false, windows: false },
568
717
  })
569
718
  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')
719
+ assert.equal(probe.el('bridge-fix').disabled, false, 'idle renders re-enable the enforcement button')
720
+ assert.equal(probe.el('bridge-fix').textContent, '启动系统层拦截(可能提权)', 'a missing side starts')
721
+
722
+ // A stale reload wins over the missing side: the click must stop the old profile
723
+ // before it starts the new one, so the label says restart (m13910).
724
+ probe.page.state.bridgeStaleReason = '规则未重载'
725
+ probe.page.paintBridgeFix()
726
+ assert.equal(probe.el('bridge-fix').textContent, '重启系统层拦截(可能提权)')
727
+ assert.match(probe.el('bridge-fix').title, /为什么要重启/)
572
728
  })
573
729
 
574
730
  test('a second click while a health action is in flight is ignored', async () => {
@@ -17,6 +17,7 @@ import { RISD_API_VERSION } from '../lib/risd/state.js'
17
17
  import { readProxyConfig } from '../lib/proxy.js'
18
18
  import { risdConfigRevision } from '../lib/risd/view.js'
19
19
  import { makeHome, removeHome, startRisdProcess } from './risd-helpers.mjs'
20
+ import { HAS_GIT, skipWithout } from './helpers/cmd.mjs'
20
21
 
21
22
  const FIXTURE = {
22
23
  socks: { host: 'proxy.example.com', port: 10080 },
@@ -130,7 +131,7 @@ test('injection is the same object the engine would inject (direct vs allow-list
130
131
  assert.equal((await missing.json()).injection, null, 'no enabled rule for node → nothing injected')
131
132
  })
132
133
 
133
- test('a save re-points the scoped git entry instead of hiding the old host', async (t) => {
134
+ test('a save re-points the scoped git entry instead of hiding the old host', { skip: skipWithout(HAS_GIT, 'git') }, async (t) => {
134
135
  const home = makeHome('risd-git-save-')
135
136
  const gitconfig = join(home, 'gitconfig')
136
137
  writeFileSync(gitconfig, '')
@@ -9,11 +9,24 @@ import { tmpdir } from 'node:os'
9
9
  import { join } from 'node:path'
10
10
  import { after, before, test } from 'node:test'
11
11
  import { reconcileStartupLeftovers } from '../lib/startup.js'
12
+ import { HAS_GIT, skipWithout } from './helpers/cmd.mjs'
12
13
 
13
14
  let root
14
15
  let home
15
16
  let gitConfig
16
17
 
18
+ // The bridge probes are injected, never real: `redirectorStatusCached()` spawns
19
+ // PowerShell on WSL (seconds) and answers differently depending on whether the
20
+ // developer's own bridge is running, and `restoreWindowsService()` really runs
21
+ // `Set-Service`/`Start-Service`. A test that let both run was slow, flaky, and
22
+ // could restart the machine's ProxyBridgeSvc.
23
+ const idleBridge = { status: () => ({ running: false }), restore: () => ({ restored: false, reason: '未停止过服务' }) }
24
+
25
+ /** Reconcile with the bridge probes stubbed; `extra` overrides them per test. */
26
+ function reconcile(extra = {}) {
27
+ return reconcileStartupLeftovers(Object.assign({}, idleBridge, extra))
28
+ }
29
+
17
30
  function git(args) {
18
31
  const res = spawnSync('git', args, { encoding: 'utf8', env: process.env })
19
32
  assert.equal(res.status, 0, `git ${args.join(' ')}: ${res.stderr}`)
@@ -49,27 +62,27 @@ after(() => {
49
62
  })
50
63
 
51
64
  test('a clean machine is a no-op', async () => {
52
- const result = await reconcileStartupLeftovers()
65
+ const result = await reconcile()
53
66
  assert.equal(result.ok, true)
54
67
  assert.deepEqual(result.notes, [])
55
68
  })
56
69
 
57
- test('a git entry from a dead engine is removed (it is ours)', async () => {
70
+ test('a git entry from a dead engine is removed (it is ours)', { skip: skipWithout(HAS_GIT, 'git') }, async () => {
58
71
  const key = 'http.https://git.example.com/.proxy'
59
72
  const value = 'socks5h://10.0.0.1:1080'
60
73
  writeGitState({ key, host: 'git.example.com', value })
61
74
  git(['config', '--global', key, value])
62
- const result = await reconcileStartupLeftovers()
75
+ const result = await reconcile()
63
76
  assert.ok(result.notes.some((note) => /git 代理/.test(note)), result.notes.join('; '))
64
77
  assert.equal(gitGet(key), '')
65
78
  assert.equal(existsSync(join(home, 'git-proxy.json')), false, 'state file is gone')
66
79
  })
67
80
 
68
- test('a foreign git value is left alone', async () => {
81
+ test('a foreign git value is left alone', { skip: skipWithout(HAS_GIT, 'git') }, async () => {
69
82
  const key = 'http.https://other.example.com/.proxy'
70
83
  writeGitState({ key, host: 'other.example.com', value: 'socks5h://10.0.0.1:1080' })
71
84
  git(['config', '--global', key, 'http://corp-proxy:3128'])
72
- const result = await reconcileStartupLeftovers()
85
+ const result = await reconcile()
73
86
  assert.ok(result.notes.some((note) => /保留了/.test(note)), result.notes.join('; '))
74
87
  assert.equal(gitGet(key), 'http://corp-proxy:3128')
75
88
  })
@@ -77,7 +90,7 @@ test('a foreign git value is left alone', async () => {
77
90
  test('a stale pidfile and a dead risd.json are cleared', async () => {
78
91
  writeFileSync(join(home, 'proxy.pid'), '999999\n', 'utf8')
79
92
  writeFileSync(join(home, 'risd.json'), `${JSON.stringify({ pid: 999999, port: 1, token: 'x', apiVersion: 1 })}\n`, 'utf8')
80
- const result = await reconcileStartupLeftovers()
93
+ const result = await reconcile()
81
94
  assert.equal(existsSync(join(home, 'proxy.pid')), false, 'stale pidfile removed')
82
95
  assert.equal(existsSync(join(home, 'risd.json')), false, 'dead daemon state removed')
83
96
  assert.ok(result.notes.length >= 2, result.notes.join('; '))
@@ -89,12 +102,35 @@ test('a parked ProxyBridgeSvc is restored and its state cleared', async () => {
89
102
  writeFileSync(join(dir, 'proxybridge-service.json'), `${JSON.stringify({
90
103
  at: Date.now(), stoppedByUs: true, originalStartType: 'Automatic', parkedOnManual: true,
91
104
  })}\n`, 'utf8')
92
- const result = await reconcileStartupLeftovers()
105
+ let restores = 0
106
+ const result = await reconcile({ restore: () => { restores += 1; return { restored: true } } })
107
+ assert.equal(restores, 1, 'a parked service is restored exactly once')
93
108
  assert.ok(result.notes.some((note) => /ProxyBridgeSvc/.test(note)), result.notes.join('; '))
94
109
  assert.equal(existsSync(join(dir, 'proxybridge-service.json')), false, 'service state cleared')
95
110
  })
96
111
 
97
- test('the git config file is only touched for our own entries', () => {
112
+ test('a parked service is left alone while the bridge is still running', async () => {
113
+ // The restore only makes sense after a reboot: a bridge that is up right now owns
114
+ // the service, and stopping it under the bridge would fight the driver for
115
+ // WinDivert. This branch is why the same test used to pass or fail depending on
116
+ // whether the developer's ProxyBridge happened to be running.
117
+ const dir = join(home, 'proxybridge')
118
+ mkdirSync(dir, { recursive: true })
119
+ writeFileSync(join(dir, 'proxybridge-service.json'), `${JSON.stringify({
120
+ at: Date.now(), stoppedByUs: true, originalStartType: 'Automatic', parkedOnManual: true,
121
+ })}\n`, 'utf8')
122
+ let restores = 0
123
+ const result = await reconcile({
124
+ status: () => ({ running: true }),
125
+ restore: () => { restores += 1; return { restored: true } },
126
+ })
127
+ assert.equal(restores, 0, 'a running bridge keeps its service')
128
+ assert.equal(result.notes.some((note) => /ProxyBridgeSvc/.test(note)), false, result.notes.join('; '))
129
+ assert.equal(existsSync(join(dir, 'proxybridge-service.json')), true, 'state kept for the next start')
130
+ rmSync(join(dir, 'proxybridge-service.json'), { force: true })
131
+ })
132
+
133
+ test('the git config file is only touched for our own entries', { skip: skipWithout(HAS_GIT, 'git') }, () => {
98
134
  const text = readFileSync(gitConfig, 'utf8')
99
135
  assert.doesNotMatch(text, /git\.example\.com/)
100
136
  })
@@ -1,39 +0,0 @@
1
- // The bridge parses its profile when it starts, so a rule-table save can leave old
2
- // rules intercepting. The daemon page therefore offers "restart bridge" right next
3
- // to that warning, and both the daemon and the plugin must understand the action.
4
- import { test } from 'node:test'
5
- import assert from 'node:assert/strict'
6
- import { readFileSync } from 'node:fs'
7
-
8
- const read = (file) => readFileSync(new URL(`../${file}`, import.meta.url), 'utf8')
9
-
10
- test('the daemon page offers a restart button next to a stale-bridge note', () => {
11
- const ui = read('lib/risd/ui.js')
12
- assert.match(ui, /id="bridge-restart"/)
13
- // The button only appears for notes that say the bridge did not take the new rules.
14
- assert.match(ui, /未重载\|旧规则/)
15
- assert.match(ui, /'为什么要重启:'/)
16
- assert.match(ui, /redirector-restart/)
17
- })
18
-
19
- test('the daemon restarts the bridge: stop, settle, start from the new profile', () => {
20
- const server = read('lib/risd/server.js')
21
- const at = server.indexOf("action === 'redirector-restart'")
22
- assert.ok(at > 0, 'daemon must handle redirector-restart')
23
- const block = server.slice(at, at + 600)
24
- assert.match(block, /await stopRedirector\(\)/)
25
- assert.match(block, /setTimeout\(resolve, 300\)/)
26
- // A page-triggered restart may prompt (it is the user asking); background
27
- // reconcilers must not (review B-P0-2).
28
- assert.match(block, /await startRedirectors\(\{ interactive: true \}\)/)
29
- })
30
-
31
- test('the plugin forwards the restart action to the daemon and can run it itself', () => {
32
- const index = read('lib/index.js')
33
- assert.match(index, /'redirector-restart'/)
34
- const at = index.indexOf("action === 'redirector-restart'")
35
- assert.ok(at > 0, 'plugin must handle redirector-restart locally')
36
- const block = index.slice(at, at + 400)
37
- assert.match(block, /await stopRedirector\(\)/)
38
- assert.match(block, /await startRedirectors\(\)/)
39
- })