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.
@@ -29,9 +29,9 @@ import { BUNDLE_URLS, MAX_TGZ_BYTES, ensureBundle, installDir, installFromTgz, i
29
29
  // module keeps loading (and verification stays disabled) if they are absent.
30
30
  import * as bundleApi from '../proxybridge-bundle.js'
31
31
  import { armJanitor, disarmJanitor, janitorStatus, markJanitorHandoff } from '../janitor.js'
32
- import { reloadRedirectorsWithProfile, redirectorStatusCached, startRedirectors, stopRedirector, writeHeartbeat } from '../redirector.js'
32
+ import { bundledBundleDir, posixToWindowsPath, readElevationState, REDIRECTOR_PID_FILENAMES, REDIRECTOR_PID_FILENAME, redirectorCommand, redirectorHome, redirectorProfilePath, redirectorStatusAsync, redirectorStatusCached, reloadRedirectorsWithProfile, startRedirectors, stopRedirector, windowsBundleDir, writeHeartbeat } from '../redirector.js'
33
33
  import { risdConfigRevision, risdProxyView } from './view.js'
34
- import { clearGitProxy, reconcileGitProxy, syncGitProxy } from './git.js'
34
+ import { clearGitProxy, readGitProxyState, reconcileGitProxy, syncGitProxy } from './git.js'
35
35
  import { findProgram, listPrograms, readProgramLog, restartProgramByKey, startLogFollow, startProgramByKey, stopProgramByKey } from './programs.js'
36
36
  import { reconcileStartupLeftovers } from '../startup.js'
37
37
  import { createDebugEngine } from './debug.js'
@@ -40,6 +40,7 @@ import { risdUiHtml } from './ui.js'
40
40
  import { pingSocks } from './ping.js'
41
41
  import { buildStamp } from './build.js'
42
42
  import { DebugError, debugErrorStatus } from '../debug/engine.js'
43
+ import { createHealthCache } from '../proxybridge-health.js'
43
44
 
44
45
  /** Request bodies are tiny JSON objects; anything bigger is a bug or an attack. */
45
46
  export const RISD_MAX_BODY_BYTES = 64 * 1024
@@ -149,6 +150,20 @@ function readBodyBytes(req, limit, timeoutMs = RISD_BODY_TIMEOUT_MS) {
149
150
  })
150
151
  }
151
152
 
153
+ /**
154
+ * True when this Linux is WSL with Windows interop: the only case where a Windows
155
+ * bridge side exists (m12029). `/proc/sys/kernel/osrelease` carries "microsoft"
156
+ * under WSL2; a native kernel never does.
157
+ */
158
+ function isWslHost() {
159
+ if (process.platform !== 'linux') return false
160
+ try {
161
+ return readFileSync('/proc/sys/kernel/osrelease', 'utf8').toLowerCase().includes('microsoft')
162
+ } catch {
163
+ return false
164
+ }
165
+ }
166
+
152
167
  /** One download at a time; the page polls GET /v1/proxybridge for the outcome. */
153
168
  let bundleDownload = null
154
169
  let bundleDownloadResult = null
@@ -324,22 +339,134 @@ let restarting = false
324
339
  /** The CLI entry of this package: `bin/risd.mjs` (server.js lives in lib/risd/). */
325
340
  const RISD_CLI_PATH = fileURLToPath(new URL('../../bin/risd.mjs', import.meta.url))
326
341
 
342
+ /**
343
+ * Linux process start time — field 22 of `/proc/<pid>/stat`, an opaque tick count.
344
+ *
345
+ * A pid alone is not an identity: after a restart the OS may hand the same number
346
+ * to an unrelated process, and `kill(pid, 0)` would then wait on the wrong one
347
+ * (review A4-P2-5). The start time is the cheap identity check the kernel offers.
348
+ *
349
+ * @param {number|string} pid - process id to inspect.
350
+ * @returns {string} decimal ticks, or '' when `/proc` is unavailable (non-Linux).
351
+ */
352
+ export function readStartTime(pid) {
353
+ try {
354
+ const stat = readFileSync(`/proc/${Number(pid)}/stat`, 'utf8')
355
+ // `comm` is in parentheses and may itself contain spaces/parentheses.
356
+ const close = stat.lastIndexOf(')')
357
+ if (close < 0) return ''
358
+ const token = stat.slice(close + 2).split(' ')[19]
359
+ return typeof token === 'string' && /^\d+$/.test(token) ? token : ''
360
+ } catch {
361
+ return ''
362
+ }
363
+ }
364
+
365
+ /**
366
+ * Resolve once `pid` is gone, or once its start time proves the pid was reused.
367
+ *
368
+ * Never throws: a successor must not die because the predecessor's pid file or
369
+ * `/proc` vanished mid-wait. `timedOut` tells the caller whether the deadline (not
370
+ * the exit) ended the wait so it can log that the handover raced the shutdown.
371
+ *
372
+ * @param {number} pid - predecessor pid.
373
+ * @param {number} timeoutMs - upper bound on the wait.
374
+ * @param {string} [expectedStartTime] - predecessor start time; '' = no identity check.
375
+ * @returns {Promise<{ok: boolean, timedOut: boolean}>} outcome, never a rejection.
376
+ */
377
+ export function waitForPidExit(pid, timeoutMs, expectedStartTime = '') {
378
+ const expected = typeof expectedStartTime === 'string' ? expectedStartTime : ''
379
+ const deadline = Date.now() + timeoutMs
380
+ return new Promise((resolve) => {
381
+ const tick = () => {
382
+ let alive = true
383
+ try { process.kill(pid, 0) } catch (error) { alive = error.code === 'EPERM' }
384
+ // A live pid with a different start time is somebody else: the process we
385
+ // care about has exited (review A4-P2-5).
386
+ if (alive === true && expected !== '') {
387
+ const current = readStartTime(pid)
388
+ if (current !== '' && current !== expected) alive = false
389
+ }
390
+ if (alive !== true) { resolve({ ok: true, timedOut: false }); return }
391
+ if (Date.now() > deadline) { resolve({ ok: false, timedOut: true }); return }
392
+ setTimeout(tick, 100)
393
+ }
394
+ tick()
395
+ })
396
+ }
397
+
398
+ /**
399
+ * Arguments for the successor CLI spawned by `POST /v1/restart`.
400
+ *
401
+ * Exported for the restart test: a successor without `--port` would bind the
402
+ * default port even when this daemon was started elsewhere, and the page polls
403
+ * the original origin forever (review A4-P2-6). `--wait-start` carries this
404
+ * process's identity so the successor does not wait on a reused pid (A4-P2-5).
405
+ *
406
+ * @param {{pid?: number, port?: number, startTime?: string}} [options] - predecessor identity.
407
+ * @returns {string[]} argv tail (`bin/risd.mjs serve …`).
408
+ */
409
+ export function successorArgs({ pid = process.pid, port = 0, startTime = '' } = {}) {
410
+ const args = [RISD_CLI_PATH, 'serve', '--wait-pid', String(pid)]
411
+ // The actual bound port, not the requested one: `--port 0` asks the OS to pick.
412
+ if (Number.isInteger(port) && port > 0) args.push('--port', String(port))
413
+ if (typeof startTime === 'string' && /^\d+$/.test(startTime)) args.push('--wait-start', startTime)
414
+ return args
415
+ }
416
+
327
417
  /**
328
418
  * Spawn the successor that takes over after this process exits. Detached+unref'd
329
419
  * so it outlives the HTTP server, and `--wait-pid` keeps it from racing us for the
330
- * port. A failure here is deliberately silent: the page's health poll times out
331
- * and tells the user to restart by hand.
420
+ * port.
421
+ *
422
+ * `restarting` is reset when the spawn itself fails or the child dies before it
423
+ * takes over (review A4-P2-7): otherwise every later POST would answer 200 and do
424
+ * nothing, and the only symptom would be the page's 30 s timeout.
425
+ *
426
+ * @param {number} [port] - port this daemon actually bound (A4-P2-6).
427
+ * @returns {import('node:child_process').ChildProcess|null} the child, or null.
332
428
  */
333
- function spawnRestartSuccessor() {
429
+ /** Test hook (see `__test`): how the successor is spawned. */
430
+ const restartHooks = { spawn }
431
+
432
+ function spawnRestartSuccessor(port = 0) {
433
+ let child = null
334
434
  try {
335
- const child = spawn(process.execPath, [RISD_CLI_PATH, 'serve', '--wait-pid', String(process.pid)], {
435
+ child = restartHooks.spawn(process.execPath, successorArgs({ pid: process.pid, port, startTime: readStartTime(process.pid) }), {
336
436
  detached: true,
337
437
  stdio: 'ignore',
338
438
  env: process.env,
339
439
  cwd: process.cwd(),
340
440
  })
341
441
  child.unref()
342
- } catch { /* the page reports the timeout */ }
442
+ } catch (error) {
443
+ restarting = false
444
+ try { process.stderr.write(`[dsh-ris-ide] 重启失败:无法启动后继进程(${error?.message ?? error})\n`) } catch { /* ignore */ }
445
+ return null
446
+ }
447
+ child.once('error', (error) => {
448
+ restarting = false
449
+ try { process.stderr.write(`[dsh-ris-ide] 重启失败:后继进程出错(${error?.message ?? error})\n`) } catch { /* ignore */ }
450
+ })
451
+ child.once('exit', (code, signal) => {
452
+ restarting = false
453
+ if (signal === null && code !== 0) {
454
+ try { process.stderr.write(`[dsh-ris-ide] 重启后继进程提前退出(code ${code});请手动重启或重试\n`) } catch { /* ignore */ }
455
+ }
456
+ })
457
+ return child
458
+ }
459
+
460
+ /**
461
+ * Test seams for the restart path (same idea as redirector's `probeHooks`): the
462
+ * route itself cannot be exercised without spawning a real successor, so the spawn
463
+ * and the `restarting` flag are exposed here and never touched by production code.
464
+ */
465
+ export const __test = {
466
+ restartHooks,
467
+ setRestarting(value) { restarting = value === true },
468
+ isRestarting() { return restarting === true },
469
+ spawnRestartSuccessor,
343
470
  }
344
471
 
345
472
  /**
@@ -368,7 +495,15 @@ export async function startRisd({ home, port = DEFAULT_RISD_PORT, version = '0.0
368
495
  */
369
496
  async function teardownNetwork(cwd) {
370
497
  try { await clearGitProxy() } catch { /* best effort */ }
371
- try { await serializeBridge(() => stopRedirector()) } catch { /* best effort */ }
498
+ // Only a bridge this proxy home recorded is ours to stop. Without a pid file the
499
+ // probe spawns PowerShell (seconds on WSL) and delays `risd stop` for an
500
+ // interception that cannot exist here (fixture daemons, plugin-only runs).
501
+ if (hasBridgePidFiles() === true) {
502
+ try { await serializeBridge(() => stopRedirector()) } catch { /* best effort */ }
503
+ // Nothing is intercepting anymore: drop the last start report so the card does
504
+ // not show a component that is gone (review A4-P2-8).
505
+ lastBridgeStart = null
506
+ }
372
507
  if (cwd !== null) {
373
508
  try { await stopProxy(cwd) } catch { /* best effort */ }
374
509
  }
@@ -695,6 +830,63 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
695
830
  return json(res, 200, proxyBridgeStatus())
696
831
  }
697
832
 
833
+ if (path === '/v1/proxybridge/health' && method === 'GET') {
834
+ const summary = engineSummary()
835
+ // Only a *known* stopped engine may skip the component check. `unknown` means
836
+ // the pidfile could not be read — not that nothing is running (review A4-P2-9).
837
+ const engineStopped = summary.state === 'stopped'
838
+ const engineRunning = summary.state === 'running'
839
+ const bridge = await redirectorStatusAsync()
840
+ const interception = { linux: bridge.runningLocal === true, windows: bridge.runningWindows === true }
841
+ // m11863: engine stopped + interception running is a misconfiguration, not a
842
+ // health result — nothing would answer the redirected connections.
843
+ const stray = { linux: engineStopped === true && interception.linux, windows: engineStopped === true && interception.windows }
844
+ if (engineStopped === true) {
845
+ // m11838: a stopped engine means nobody is using the component, so probing
846
+ // binaries (and spawning PowerShell) would only produce red noise. This
847
+ // route stays read-only: starting/stopping the component is the reconciler's
848
+ // single decision (review A4-P2-7), so a health poll cannot race a teardown
849
+ // or spin an elevation prompt of its own.
850
+ return json(res, 200, { ok: null, checked: false, engineRunning: false, engineState: summary.state, interception, elevations: elevationState(), stray, lastStart: lastBridgeStart, commands: bridgeCommands(), degrade: bridgeDegrade(), at: new Date().toISOString() })
851
+ }
852
+ // Probe the copy Windows actually runs (%LOCALAPPDATA%), not the Linux cache:
853
+ // Windows cannot launch an exe from the Linux filesystem (m11828).
854
+ let windowsExe = ''
855
+ let windowsApplicable = false
856
+ let windowsPrepared = false
857
+ try {
858
+ if (process.platform === 'win32') {
859
+ // Native Windows runs the bundle in place (review A4-P1-1): there is no
860
+ // Linux cache to copy from and no materialisation step at all.
861
+ const exe = join(bundleApi.installDir(home), 'windows', 'ProxyBridge_CLI.exe')
862
+ windowsApplicable = true
863
+ windowsPrepared = existsSync(exe)
864
+ if (windowsPrepared === true) windowsExe = exe
865
+ } else if (isWslHost() === true) {
866
+ // WSL is the only non-Windows host that can run the Windows bridge; the
867
+ // copy Windows actually executes lives under %LOCALAPPDATA% (m11828).
868
+ const dir = windowsBundleDir()
869
+ if (typeof dir === 'string' && dir !== '') {
870
+ windowsApplicable = true
871
+ windowsPrepared = existsSync(join(dir, 'ProxyBridge_CLI.exe'))
872
+ if (windowsPrepared === true) windowsExe = posixToWindowsPath(join(dir, 'ProxyBridge_CLI.exe'))
873
+ }
874
+ }
875
+ } catch { /* the card then says "本机没有 Windows 侧" instead of a wrong failure */ }
876
+ const health = await bridgeHealth.get({
877
+ home,
878
+ // `unknown` is not "not running": only claim an engine state we know
879
+ // (review A4-P2-9).
880
+ engineRunning: engineRunning === true,
881
+ force: url.searchParams.get('force') === '1',
882
+ windowsExe,
883
+ windowsApplicable,
884
+ windowsPrepared,
885
+ linuxApplicable: process.platform !== 'win32',
886
+ })
887
+ return json(res, 200, Object.assign({}, health, { engineState: summary.state, interception, elevations: elevationState(), stray, lastStart: lastBridgeStart, commands: bridgeCommands(), degrade: bridgeDegrade() }))
888
+ }
889
+
698
890
  if (path === '/v1/proxybridge/download' && method === 'POST') {
699
891
  // Fetching/installing the component is user-visible work: keep the daemon
700
892
  // from idling out from under the page while it runs (review A3-P2-3).
@@ -914,7 +1106,8 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
914
1106
  if (action === 'start') {
915
1107
  result = await serializeEngine(async () => {
916
1108
  const engine = await startProxy(cwd)
917
- const redirector = await serializeBridge(() => startRedirectors())
1109
+ const redirector = await serializeBridge(() => startRedirectors({ interactive: true }))
1110
+ noteBridgeStart(redirector)
918
1111
  const git = await syncGitProxy({ cwd, host: gitHost, enabled: true })
919
1112
  if (engine.ok === true) {
920
1113
  engineCwd = cwd
@@ -926,6 +1119,9 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
926
1119
  result = await serializeEngine(async () => {
927
1120
  const git = await syncGitProxy({ cwd, host: gitHost, enabled: false })
928
1121
  const redirector = await serializeBridge(() => stopRedirector())
1122
+ // The card must not keep describing a component we just stopped
1123
+ // (review A4-P2-8).
1124
+ lastBridgeStart = null
929
1125
  const stopped = await stopProxy(cwd)
930
1126
  if (stopped.ok === true) {
931
1127
  engineCwd = null
@@ -949,13 +1145,15 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
949
1145
  result = await serializeBridge(() => syncRedirector(cwd, { start: action === 'redirector-start' }))
950
1146
  } else if (action === 'redirector-stop') {
951
1147
  result = await serializeBridge(() => stopRedirector())
1148
+ lastBridgeStart = null
952
1149
  } else if (action === 'redirector-restart') {
953
1150
  // Stop first so nothing keeps intercepting with the parsed-at-start profile,
954
1151
  // then start again from the profile written by the save that requested this.
955
1152
  result = await serializeBridge(async () => {
956
1153
  const stopped = await stopRedirector()
957
1154
  await new Promise((resolve) => setTimeout(resolve, 300))
958
- const started = await startRedirectors()
1155
+ const started = await startRedirectors({ interactive: true })
1156
+ noteBridgeStart(started)
959
1157
  return {
960
1158
  stopped,
961
1159
  started: started.started ?? [],
@@ -1218,7 +1416,7 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
1218
1416
  json(res, 200, { ok: true, restarting: true, pid: process.pid })
1219
1417
  if (!already) {
1220
1418
  setImmediate(() => {
1221
- spawnRestartSuccessor()
1419
+ spawnRestartSuccessor(actualPort)
1222
1420
  if (onShutdown !== null) onShutdown(true)
1223
1421
  })
1224
1422
  }
@@ -1258,6 +1456,113 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
1258
1456
  server.keepAliveTimeout = 1000
1259
1457
 
1260
1458
  let engineInherited = false
1459
+ // Component health probes spawn a process per side: cache the snapshot for 30 s
1460
+ // and let the card's「重新检查」force it (m11828).
1461
+ const bridgeHealth = createHealthCache()
1462
+ // Minimum gap between automatic start/stop attempts (m12046/m12053): a missing
1463
+ // elevation must not retry on every poll, and the supervisor is only a safety net.
1464
+ const BRIDGE_PULL_INTERVAL_MS = 60_000
1465
+ /** How often the supervisor re-checks the engine ⇔ component pairing (m12060). */
1466
+ const BRIDGE_RECONCILE_MS = 15_000
1467
+ let lastBridgePullAt = 0
1468
+ let lastBridgeStopAt = 0
1469
+ let reconciling = false
1470
+ // m12359: when a side cannot start (Linux needs root), the CLI prints the exact
1471
+ // command to paste. Remember the last attempt so the health card can show it.
1472
+ let lastBridgeStart = null
1473
+ /**
1474
+ * The exact command a user can paste to start a side by hand.
1475
+ *
1476
+ * The health card needs it even when this process never attempted a start (the
1477
+ * bridge may already be running on one side, so no attempt was made): without it
1478
+ * the panel just says 「需要提权」 and never tells the user what to run (m12359).
1479
+ * @returns {{linux?: string, windows?: string}} display commands, empty when unknown.
1480
+ */
1481
+ /**
1482
+ * Whether the elevation terminal for each side is still open. The helper script
1483
+ * owns a state file for exactly that lifetime (m12923).
1484
+ * @returns {{linux: object, windows: object}} per-side state.
1485
+ */
1486
+ function elevationState() {
1487
+ return {
1488
+ linux: readElevationState('local', { home }),
1489
+ windows: readElevationState('windows', { home }),
1490
+ }
1491
+ }
1492
+
1493
+ function bridgeCommands() {
1494
+ try {
1495
+ const base = bundledBundleDir()
1496
+ const profilePath = redirectorProfilePath()
1497
+ return {
1498
+ linux: redirectorCommand({ cliPath: join(base, 'linux', 'ProxyBridge'), profilePath }).display,
1499
+ }
1500
+ } catch { return {} }
1501
+ }
1502
+ /**
1503
+ * The degraded path used when the OS-level component cannot run (m12486).
1504
+ *
1505
+ * Without root the Linux side cannot intercept; launchers can still give a program
1506
+ * the local CONNECT listener through env vars and JVM args. Programs that cannot be
1507
+ * told a proxy address (JDBC drivers, Navicat…) only work through an interception
1508
+ * layer, so the same payload carries the command to start one.
1509
+ * @returns {{httpProxyUrl: string, jvmArgs: string[], env: Record<string,string>, note: string}} degraded plan.
1510
+ */
1511
+ function bridgeDegrade() {
1512
+ let listenPort = 11081
1513
+ try {
1514
+ const stored = readProxyConfig(home)
1515
+ if (Number.isInteger(stored.listenPort) && stored.listenPort > 0) listenPort = stored.listenPort
1516
+ } catch { /* default */ }
1517
+ const url = `http://127.0.0.1:${listenPort}`
1518
+ let command = ''
1519
+ try {
1520
+ command = redirectorCommand({ cliPath: join(bundledBundleDir(), 'linux', 'ProxyBridge'), profilePath: redirectorProfilePath() }).display
1521
+ } catch { /* the card then only shows the degraded plan */ }
1522
+ // git is the third degraded path (m12567): the daemon writes the global
1523
+ // `http.<host>.proxy` entry itself, so git/maven/npm-style clients that honour it
1524
+ // keep working without the OS-level component.
1525
+ let socksUrl = ''
1526
+ try {
1527
+ const socks = readProxyConfig(home).socks
1528
+ if (socks.host !== '' && socks.port > 0) socksUrl = `socks5h://${socks.host}:${socks.port}`
1529
+ } catch { /* keep it empty */ }
1530
+ let git = null
1531
+ try {
1532
+ const state = readGitProxyState()
1533
+ if (state.host !== '' && state.value !== '') git = { host: state.host, key: state.key, value: state.value }
1534
+ } catch { /* no git proxy written yet */ }
1535
+ return {
1536
+ httpProxyUrl: url,
1537
+ command,
1538
+ jvmArgs: [
1539
+ '-Dhttp.proxyHost=127.0.0.1',
1540
+ `-Dhttp.proxyPort=${listenPort}`,
1541
+ '-Dhttps.proxyHost=127.0.0.1',
1542
+ `-Dhttps.proxyPort=${listenPort}`,
1543
+ '-Dhttp.nonProxyHosts=localhost|127.*|[::1]',
1544
+ ],
1545
+ env: { ALL_PROXY: url, HTTP_PROXY: url, HTTPS_PROXY: url, NO_PROXY: 'localhost,127.0.0.1,::1' },
1546
+ socksUrl,
1547
+ git,
1548
+ note: '降级:JVM 程序用下面的 -D 参数、能读环境变量的程序用 ALL_PROXY;JDBC/Navicat 这类无法注入代理的程序只能靠系统层拦截',
1549
+ }
1550
+ }
1551
+ /**
1552
+ * Remember one bridge start attempt for the health card.
1553
+ * @param {{started?: object[], skipped?: object[], running?: boolean}} started - `startRedirectors()` outcome.
1554
+ */
1555
+ function noteBridgeStart(started) {
1556
+ if (!started || typeof started !== 'object') return
1557
+ lastBridgeStart = {
1558
+ at: new Date().toISOString(),
1559
+ started: Array.isArray(started.started) ? started.started.map((item) => ({ side: item.side, pid: item.pid })) : [],
1560
+ skipped: Array.isArray(started.skipped)
1561
+ ? started.skipped.map((item) => ({ side: item.side, reason: item.reason, command: item.command }))
1562
+ : [],
1563
+ running: started.running === true,
1564
+ }
1565
+ }
1261
1566
 
1262
1567
  function engineSummary() {
1263
1568
  // `owned` means "this daemon has started the engine during its lifetime"; a
@@ -1373,10 +1678,142 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
1373
1678
  // Run the startup reconcile through the engine queue: it touches the engine
1374
1679
  // pidfile and a user's /v1/action may already be in flight. Own pid is passed so
1375
1680
  // the reconcile can never delete the state file of this very daemon.
1376
- void serializeEngine(() => reconcileStartupLeftovers({
1377
- ownPid: process.pid,
1378
- log: (message) => { try { process.stdout.write(`${message}\n`) } catch { /* ignore */ } },
1379
- })).catch(() => {})
1681
+ /**
1682
+ * True when some ProxyBridge side left a pid file in this proxy home: the only
1683
+ * situation where a stopped engine can still have a live component (m12053).
1684
+ * Pure filesystem checks — no probing.
1685
+ */
1686
+ function hasBridgePidFiles() {
1687
+ try {
1688
+ const names = [REDIRECTOR_PID_FILENAME, REDIRECTOR_PID_FILENAMES.local, REDIRECTOR_PID_FILENAMES.windows]
1689
+ return names.some((name) => existsSync(join(redirectorHome(), name)))
1690
+ } catch {
1691
+ return false
1692
+ }
1693
+ }
1694
+
1695
+ /**
1696
+ * Component sides this host can actually run (review A4-P2-7).
1697
+ *
1698
+ * Native Windows runs only the Windows CLI, Linux only the Linux one, and WSL can
1699
+ * run both — the Windows side only when the bundle has a Windows-addressable
1700
+ * target (%LOCALAPPDATA%). Used to decide *which* side is missing instead of the
1701
+ * old "both sides down" test, which left a half-started bridge alone forever.
1702
+ *
1703
+ * @returns {Array<'local'|'windows'>} side names, in start order.
1704
+ */
1705
+ function bridgeApplicableSides() {
1706
+ try {
1707
+ if (process.platform === 'win32') return ['windows']
1708
+ const sides = ['local']
1709
+ if (isWslHost() === true && String(windowsBundleDir() ?? '') !== '') sides.push('windows')
1710
+ return sides
1711
+ } catch {
1712
+ return ['local']
1713
+ }
1714
+ }
1715
+
1716
+ /**
1717
+ * Keep the engine and the system-layer component consistent (m12060).
1718
+ *
1719
+ * One place decides both directions, because the pairs that otherwise drift are
1720
+ * many: an inherited engine after a dsh crash, a CLI that died while the engine
1721
+ * kept running, a manual stop of either side, a crash of the engine itself. Start
1722
+ * and stop stay serialized through serializeBridge, and an elevation failure is
1723
+ * retried at most once per minute so a page left open cannot spin UAC prompts.
1724
+ *
1725
+ * @param {string} reason - where the reconcile came from (log/debug only).
1726
+ * @returns {Promise<void>} resolves when the attempt is over (best effort).
1727
+ */
1728
+ async function reconcileEngineBridge(reason) {
1729
+ if (reconciling === true) return
1730
+ if (stopping === true) return
1731
+ reconciling = true
1732
+ try {
1733
+ const engine = engineSummary()
1734
+ // `unknown` means the pidfile could not be read — not that nothing is running
1735
+ // (review A4-P2-9): doing nothing is the only safe answer.
1736
+ if (engine.state === 'unknown') return
1737
+ const engineRunning = engine.state === 'running'
1738
+ const engineStopped = engine.state === 'stopped'
1739
+ // Cheap gate first: probing the bridge (WSL: PowerShell, ~3 s) must not run on
1740
+ // every startup/poll when there is nothing to reconcile. A pid file is the
1741
+ // evidence that a component may be left behind after a crash (m12046/m12053).
1742
+ if (engineStopped === true && hasBridgePidFiles() !== true) return
1743
+ // Async probe: a spawnSync here would block the whole daemon (and every request
1744
+ // queued behind it) for the duration of the Windows PowerShell probe.
1745
+ const bridge = await redirectorStatusAsync()
1746
+ // Stopping may have begun while the probe ran: do not start/stop a bridge the
1747
+ // teardown is about to handle.
1748
+ if (stopping === true) return
1749
+ if (engineRunning === true) {
1750
+ // Only the sides this host can run matter; a half-started bridge (one side
1751
+ // up, one skipped) must still be completed (review A4-P2-7).
1752
+ const missing = bridgeApplicableSides().filter((side) => (side === 'windows' ? bridge.runningWindows !== true : bridge.runningLocal !== true))
1753
+ if (missing.length === 0) return
1754
+ if (Date.now() - lastBridgePullAt < BRIDGE_PULL_INTERVAL_MS) return
1755
+ lastBridgePullAt = Date.now()
1756
+ // Never prompt for elevation from a background pass: the page owns that.
1757
+ const started = await serializeBridge(() => startRedirectors({ sides: missing, interactive: false }))
1758
+ noteBridgeStart(started)
1759
+ const failed = (Array.isArray(started?.skipped) ? started.skipped : []).filter((item) => missing.includes(item.side))
1760
+ if (failed.length > 0) {
1761
+ const why = failed.map((item) => `${item.side}:${item.reason}`).join(';')
1762
+ process.stdout.write(`[dsh-ris-ide] 代理引擎已运行但系统层拦截未启动(${reason}):${why}\n`)
1763
+ }
1764
+ } else if (engineStopped === true && bridge.running === true) {
1765
+ if (Date.now() - lastBridgeStopAt < BRIDGE_PULL_INTERVAL_MS) return
1766
+ lastBridgeStopAt = Date.now()
1767
+ process.stdout.write(`[dsh-ris-ide] 代理引擎未运行:停止系统层拦截(${reason}),避免把连接转发到已关闭的端口\n`)
1768
+ await serializeBridge(() => stopRedirector())
1769
+ lastBridgeStart = null
1770
+ }
1771
+ } catch { /* elevation missing: the page shows the reason; the timer retries later */ } finally {
1772
+ reconciling = false
1773
+ }
1774
+ }
1775
+ const bridgeSupervisor = setInterval(() => { void reconcileEngineBridge('timer') }, BRIDGE_RECONCILE_MS)
1776
+ bridgeSupervisor.unref?.()
1777
+
1778
+ void serializeEngine(async () => {
1779
+ await reconcileStartupLeftovers({
1780
+ ownPid: process.pid,
1781
+ log: (message) => { try { process.stdout.write(`${message}\n`) } catch { /* ignore */ } },
1782
+ })
1783
+ // m12046/m12053/m12060: one invariant, enforced from one place — the engine and
1784
+ // the component run together. Startup, health polling and the supervisor all call
1785
+ // this, so "engine up ⇒ component up" and "engine down ⇒ component down" cannot
1786
+ // drift apart (an inherited engine, a crashed CLI, a manual stop all converge).
1787
+ // Deliberately not awaited: probing the bridge costs seconds on WSL (PowerShell)
1788
+ // and `/ready` must not wait for a component that is usually absent. The
1789
+ // supervisor re-checks in 15 s, so a missed first pass self-heals.
1790
+ setImmediate(() => { void reconcileEngineBridge('startup') })
1791
+
1792
+ // Invariant (m11863): the component must not keep intercepting once the proxy
1793
+ // engine is gone — every redirected connection would be sent to a dead listener
1794
+ // and fail in a way that looks like the network broke. The engine can be absent
1795
+ // at startup (previous dsh stopped it, plugin fallback never ran); the bridge
1796
+ // may still be alive from an earlier session, so reap it here.
1797
+ // Only a bridge this proxy home recorded is ours to reap: a machine-wide CLI with
1798
+ // another profile (or a fixture daemon with an empty home) is not. And never block
1799
+ // `/ready` on the probe — on WSL it spawns PowerShell.
1800
+ // Serialized with every other bridge mutation so a user's start/stop cannot be
1801
+ // interleaved with this reap, and guarded by `stopping` so a shutdown that began
1802
+ // meanwhile is not undone by a late stop (review A4-P2-7 / startup-reap).
1803
+ setImmediate(() => {
1804
+ void serializeBridge(async () => {
1805
+ if (stopping === true) return
1806
+ if (proxyPid() !== null) return
1807
+ if (hasBridgePidFiles() !== true) return
1808
+ try {
1809
+ if ((await redirectorStatusAsync()).running !== true) return
1810
+ process.stdout.write('[dsh-ris-ide] 代理引擎未运行:停止系统层拦截,避免把连接转发到已关闭的端口\n')
1811
+ await stopRedirector()
1812
+ lastBridgeStart = null
1813
+ } catch { /* best effort: the next stop click retries with elevation */ }
1814
+ })
1815
+ })
1816
+ }).catch(() => {})
1380
1817
 
1381
1818
  let stopping = false
1382
1819
  /**
@@ -1389,6 +1826,7 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
1389
1826
  stopping = true
1390
1827
  const handoff = options?.handoff === true
1391
1828
  cancelIdleExit()
1829
+ clearInterval(bridgeSupervisor)
1392
1830
  if (heartbeat !== null) {
1393
1831
  clearInterval(heartbeat)
1394
1832
  heartbeat = null
@@ -1453,6 +1891,9 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
1453
1891
  new Promise((resolve) => { const timer = setTimeout(resolve, teardownTimeoutMs); timer.unref?.() }),
1454
1892
  ])
1455
1893
  engineCwd = null
1894
+ // Nothing is supervised anymore; the card must not keep a stale start report
1895
+ // (review A4-P2-8). This is also the fallback when teardown was skipped.
1896
+ lastBridgeStart = null
1456
1897
  server.closeIdleConnections?.()
1457
1898
  await new Promise((resolve) => {
1458
1899
  const timer = setTimeout(() => {