dsh-ris-ide 1.7.3 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -7
- package/bin/proxy-janitor.mjs +106 -11
- package/bin/risd.mjs +287 -0
- package/bin/run-with-log.ps1 +43 -5
- package/lib/client.js +515 -1152
- package/lib/index.js +1124 -55
- package/lib/janitor.js +106 -15
- package/lib/proxy.js +86 -7
- package/lib/proxybridge-bundle.js +798 -0
- package/lib/redirector.js +484 -35
- package/lib/risd/build.js +91 -0
- package/lib/risd/debug.js +374 -0
- package/lib/risd/git.js +207 -0
- package/lib/risd/leases.js +124 -0
- package/lib/risd/lifecycle.js +148 -0
- package/lib/risd/log.js +59 -0
- package/lib/risd/ping.js +94 -0
- package/lib/risd/programs.js +348 -0
- package/lib/risd/server.js +1478 -0
- package/lib/risd/state.js +137 -0
- package/lib/risd/ui.js +1705 -0
- package/lib/risd/view.js +79 -0
- package/lib/risd-client.js +282 -0
- package/lib/standalone/window.html +14 -16
- package/lib/startup.js +114 -0
- package/package.json +4 -1
- package/test/client-build.test.mjs +113 -0
- package/test/client-viewer.test.mjs +166 -200
- package/test/dsh-origin.test.mjs +140 -0
- package/test/dsh-window-refresh.test.mjs +100 -0
- package/test/harness.test.mjs +9 -0
- package/test/host-noloop.test.mjs +74 -0
- package/test/host-tail.test.mjs +21 -4
- package/test/host-window.test.mjs +4 -4
- package/test/janitor.test.mjs +29 -1
- package/test/lifecycle.test.mjs +26 -5
- package/test/merge-owners.test.mjs +155 -0
- package/test/proxy-restart.test.mjs +37 -0
- package/test/proxy-window.test.mjs +45 -0
- package/test/proxy.test.mjs +41 -0
- package/test/proxybridge-bundle.test.mjs +687 -0
- package/test/redirector-bundle.test.mjs +391 -0
- package/test/redirector.test.mjs +59 -9
- package/test/risd-api.test.mjs +470 -0
- package/test/risd-bridge-degrade.test.mjs +101 -0
- package/test/risd-build.test.mjs +20 -0
- package/test/risd-cli-home.test.mjs +50 -0
- package/test/risd-client.test.mjs +130 -0
- package/test/risd-debug.test.mjs +261 -0
- package/test/risd-election.test.mjs +104 -0
- package/test/risd-engine.test.mjs +132 -0
- package/test/risd-entry.test.mjs +118 -0
- package/test/risd-git.test.mjs +109 -0
- package/test/risd-handoff.test.mjs +116 -0
- package/test/risd-heal.test.mjs +50 -0
- package/test/risd-helpers.mjs +108 -0
- package/test/risd-host-p2.test.mjs +147 -0
- package/test/risd-janitor-guard.test.mjs +46 -0
- package/test/risd-lease.test.mjs +83 -0
- package/test/risd-lifecycle.test.mjs +210 -0
- package/test/risd-log-follow.test.mjs +227 -0
- package/test/risd-mode.test.mjs +161 -0
- package/test/risd-ping.test.mjs +99 -0
- package/test/risd-programs.test.mjs +169 -0
- package/test/risd-review-p2.test.mjs +217 -0
- package/test/risd-shutdown.test.mjs +97 -0
- package/test/risd-teardown.test.mjs +87 -0
- package/test/risd-tools.test.mjs +211 -0
- package/test/risd-ui.test.mjs +445 -0
- package/test/risd-write.test.mjs +170 -0
- package/test/startup-reconcile.test.mjs +100 -0
- package/test/windows.test.mjs +37 -2
package/lib/index.js
CHANGED
|
@@ -80,7 +80,22 @@ import {
|
|
|
80
80
|
windowsToPosixPath,
|
|
81
81
|
writeHeartbeat,
|
|
82
82
|
} from './redirector.js'
|
|
83
|
-
import { armJanitor, janitorStatus } from './janitor.js'
|
|
83
|
+
import { armJanitor, disarmJanitor, janitorStatus, writeStateAtomic } from './janitor.js'
|
|
84
|
+
import {
|
|
85
|
+
acquireLease,
|
|
86
|
+
debugAction as daemonDebugAction,
|
|
87
|
+
ensureRisd,
|
|
88
|
+
getProxyView,
|
|
89
|
+
probeRisd,
|
|
90
|
+
risdHealth,
|
|
91
|
+
listPrograms as daemonListPrograms,
|
|
92
|
+
programAction as daemonProgramAction,
|
|
93
|
+
proxyAction,
|
|
94
|
+
readProgramLog as daemonReadProgramLog,
|
|
95
|
+
releaseLease,
|
|
96
|
+
saveProxy,
|
|
97
|
+
} from './risd-client.js'
|
|
98
|
+
import { scheduleStartupReconcile } from './startup.js'
|
|
84
99
|
|
|
85
100
|
export const name = 'dsh-ris-ide'
|
|
86
101
|
/**
|
|
@@ -124,6 +139,36 @@ export function pickGitBash(candidates) {
|
|
|
124
139
|
return undefined
|
|
125
140
|
}
|
|
126
141
|
|
|
142
|
+
/** Shell constructs that only a bash/msys shell understands (not cmd.exe). */
|
|
143
|
+
const BASH_DIALECT_RE = /(^|[\s;&|(])(exec|export|unset|source)\s|\$\(|`|\$\{[^}]*\}|\$[A-Z][A-Z0-9_]*\b/
|
|
144
|
+
/**
|
|
145
|
+
* Constructs that mean the command belongs to PowerShell, not bash. `$env:NAME`
|
|
146
|
+
* (the way PowerShell spells an environment variable), `$PSScriptRoot` &
|
|
147
|
+
* friends, `$x = 1` assignments, `-Command`, `.ps1` and an explicit `pwsh`.
|
|
148
|
+
*/
|
|
149
|
+
const POWERSHELL_DIALECT_RE = /\$env:|\$(?:global|script|local|private|using|function|input|args|PSItem|PSScriptRoot|PSEdition|PSVersionTable|LASTEXITCODE|Error|Host|PID)\b|\$[A-Za-z_][A-Za-z0-9_]*\s*=|\b(?:powershell|pwsh)\b|-Command\b|\.ps1\b/i
|
|
150
|
+
/**
|
|
151
|
+
* Whether a custom `startCommand` is written in bash dialect.
|
|
152
|
+
*
|
|
153
|
+
* `runtime=auto` now selects the native PowerShell wrapper on Windows, which runs a
|
|
154
|
+
* custom command through `cmd.exe`. A command with `$(cat ...)`, `exec java` or
|
|
155
|
+
* `$HOME` then dies instantly with no explanation (review A2-P1-2), so the caller
|
|
156
|
+
* uses this to prefer Git Bash when the command needs it.
|
|
157
|
+
*
|
|
158
|
+
* Only *unambiguous* bash signals count: `$(`, backticks, `${...}`, `exec`/`export`
|
|
159
|
+
* and ALL-CAPS `$VAR` (how POSIX spells `$HOME`). Lowercase `$x` and `$env:NAME`
|
|
160
|
+
* are how PowerShell writes its own variables, and `$x = 1` is a PowerShell
|
|
161
|
+
* assignment — treating those as bash sent `pwsh`/`powershell` commands through Git
|
|
162
|
+
* Bash (or failed with `no-bash` when it was missing) (review C3-P1-1).
|
|
163
|
+
* @param {string} command - custom start command (JDWP placeholder already expanded).
|
|
164
|
+
* @returns {boolean} true when a POSIX shell is required.
|
|
165
|
+
*/
|
|
166
|
+
export function isBashDialectCommand(command) {
|
|
167
|
+
if (typeof command !== 'string' || command.trim() === '') return false
|
|
168
|
+
if (POWERSHELL_DIALECT_RE.test(command) === true) return false
|
|
169
|
+
return BASH_DIALECT_RE.test(command)
|
|
170
|
+
}
|
|
171
|
+
|
|
127
172
|
/** Detect a usable Git Bash on this Windows machine (see {@link pickGitBash}). */
|
|
128
173
|
export function detectGitBash() {
|
|
129
174
|
if (!IS_WINDOWS) return undefined
|
|
@@ -139,17 +184,30 @@ export function detectGitBash() {
|
|
|
139
184
|
* @returns `{ runtime: 'bash', bashPath }` or `{ runtime: 'powershell' }`.
|
|
140
185
|
* @throws {TailError} when `bash` is requested but Git Bash is not installed.
|
|
141
186
|
*/
|
|
142
|
-
export function resolveWindowsRuntime(runtime, bashPath) {
|
|
187
|
+
export function resolveWindowsRuntime(runtime, bashPath, { bashDialect = false } = {}) {
|
|
143
188
|
const requested = runtime === 'bash' || runtime === 'powershell' ? runtime : 'auto'
|
|
144
189
|
if (requested === 'powershell') return { runtime: 'powershell' }
|
|
145
|
-
|
|
146
|
-
|
|
190
|
+
if (requested === 'auto' && bashDialect === true) {
|
|
191
|
+
// The command cannot run under cmd.exe: keep the pre-review behaviour for this
|
|
192
|
+
// one program instead of failing at launch (review A2-P1-2).
|
|
193
|
+
const found = bashPath !== undefined ? pickGitBash([bashPath]) : detectGitBash()
|
|
147
194
|
if (found === undefined) {
|
|
148
|
-
throw new TailError('no-bash', '
|
|
195
|
+
throw new TailError('no-bash', '这段 startCommand 是 bash 方言($(…)/exec/$VAR),但没找到 Git Bash:装 Git Bash 或把 runtime 设为 "powershell" 并改写命令', 400)
|
|
149
196
|
}
|
|
150
197
|
return { runtime: 'bash', bashPath: found }
|
|
151
198
|
}
|
|
152
|
-
|
|
199
|
+
// 2026-11-09 Windows review: the Git Bash wrapper receives Windows paths
|
|
200
|
+
// verbatim, and MSYS rewrites/mangles them (`mkdir -p 'C:\x'` creates a file
|
|
201
|
+
// named `C:\x`, `cd 'C:\x'` fails). `auto` used to prefer Git Bash whenever
|
|
202
|
+
// it was installed — i.e. the most common Windows dev box — so the default is
|
|
203
|
+
// now the native PowerShell wrapper (no path translation). `bash` stays
|
|
204
|
+
// available, but only when asked for explicitly.
|
|
205
|
+
if (requested === 'auto') return { runtime: 'powershell' }
|
|
206
|
+
const found = bashPath !== undefined ? pickGitBash([bashPath]) : detectGitBash()
|
|
207
|
+
if (found === undefined) {
|
|
208
|
+
throw new TailError('no-bash', '没有找到 Git Bash(WSL 的 bash.exe 不支持);装 Git Bash 或把 runtime 设成 "powershell"', 400)
|
|
209
|
+
}
|
|
210
|
+
return { runtime: 'bash', bashPath: found }
|
|
153
211
|
}
|
|
154
212
|
/** The Host services this plugin needs: the HTTP route registry and session cwd lookup. */
|
|
155
213
|
export const inject = ['webServer', 'sessions', 'tools']
|
|
@@ -350,6 +408,14 @@ const PROXY_PROGRAMS_PATH = `${ROUTE_PREFIX}/proxy/programs`
|
|
|
350
408
|
* executable that is not running yet, so it is proxied the moment it starts.
|
|
351
409
|
*/
|
|
352
410
|
const PROXY_BROWSE_PATH = `${ROUTE_PREFIX}/proxy/browse`
|
|
411
|
+
/**
|
|
412
|
+
* On-demand daemon start for the IDE button: clicking ⧉ must work even after
|
|
413
|
+
* `risd stop` (or a crash), so the client asks the host to spawn it rather than
|
|
414
|
+
* falling back to the old standalone window.
|
|
415
|
+
*/
|
|
416
|
+
const RISD_ENSURE_PATH = `${ROUTE_PREFIX}/risd/ensure`
|
|
417
|
+
/** Where the page asks which client bundle the host is serving (m09693). */
|
|
418
|
+
const BUILD_PATH = `${ROUTE_PREFIX}/build`
|
|
353
419
|
/** Workspace cache holding extracted sources / decompiled files. */
|
|
354
420
|
export const IDE_CACHE_DIR = `${IDE_STATE_DIR}/cache`
|
|
355
421
|
/** Where the visual settings dialog persists the decompiler jar. */
|
|
@@ -467,14 +533,37 @@ let lifecycle = null
|
|
|
467
533
|
/** Engine left behind by a previous dsh process: `{ pid, owner, detectedAt } | null`. */
|
|
468
534
|
let inheritedEngine = null
|
|
469
535
|
|
|
470
|
-
/**
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
536
|
+
/**
|
|
537
|
+
* Write the watchdog heartbeat now and keep writing it every 3 s.
|
|
538
|
+
*
|
|
539
|
+
* A failed write is NOT harmless: the elevated watchdog tears the bridge down
|
|
540
|
+
* after 20 s without a fresh heartbeat, so the user would see "代理桥接自己没了"
|
|
541
|
+
* with no explanation in the log. Warn once per failure streak (reset on the
|
|
542
|
+
* first successful beat) instead of swallowing it.
|
|
543
|
+
*
|
|
544
|
+
* @param logger - optional `{ warn(message) }` (the host context logger).
|
|
545
|
+
*/
|
|
546
|
+
function startHeartbeat(logger = null) {
|
|
547
|
+
let warned = false
|
|
548
|
+
const beat = () => {
|
|
549
|
+
let ok = false
|
|
550
|
+
try {
|
|
551
|
+
ok = writeHeartbeat() !== false
|
|
552
|
+
} catch {
|
|
553
|
+
ok = false
|
|
554
|
+
}
|
|
555
|
+
if (ok === true) {
|
|
556
|
+
warned = false
|
|
557
|
+
return
|
|
558
|
+
}
|
|
559
|
+
if (warned === true) return
|
|
560
|
+
warned = true
|
|
561
|
+
try {
|
|
562
|
+
logger?.warn?.('[dsh-ris-ide] 心跳写入失败:提权看门狗 20s 后会拆除代理桥接;请检查 ~/.dsh-ris-ide 是否可写(DSH_RIS_IDE_PROXY_HOME)')
|
|
563
|
+
} catch { /* logging must never break the heartbeat */ }
|
|
477
564
|
}
|
|
565
|
+
beat()
|
|
566
|
+
return setInterval(beat, 3000)
|
|
478
567
|
}
|
|
479
568
|
|
|
480
569
|
/**
|
|
@@ -514,9 +603,9 @@ function adoptLeftoverEngine() {
|
|
|
514
603
|
* engine left behind by a previous dsh process.
|
|
515
604
|
* @returns {{beat: NodeJS.Timeout | null, onExit: Function, owner: number}} the state.
|
|
516
605
|
*/
|
|
517
|
-
function ensureLifecycle() {
|
|
606
|
+
function ensureLifecycle(ctx = null) {
|
|
518
607
|
if (lifecycle !== null && lifecycle.owner === process.pid) {
|
|
519
|
-
if (lifecycle.beat === null) lifecycle.beat = startHeartbeat()
|
|
608
|
+
if (lifecycle.beat === null) lifecycle.beat = startHeartbeat(ctx?.logger ?? null)
|
|
520
609
|
return lifecycle
|
|
521
610
|
}
|
|
522
611
|
adoptLeftoverEngine()
|
|
@@ -529,12 +618,58 @@ function ensureLifecycle() {
|
|
|
529
618
|
// closed terminal, where no 'exit' listener runs at all.
|
|
530
619
|
}
|
|
531
620
|
process.once('exit', onExit)
|
|
532
|
-
lifecycle = { beat: startHeartbeat(), onExit, owner: process.pid }
|
|
621
|
+
lifecycle = { beat: startHeartbeat(ctx?.logger ?? null), onExit, owner: process.pid }
|
|
533
622
|
// Idempotent for the same owner; replaces a watcher left watching a dead dsh.
|
|
534
623
|
try { armJanitor({ ownerPid: process.pid }) } catch { /* the watcher is optional */ }
|
|
535
624
|
return lifecycle
|
|
536
625
|
}
|
|
537
626
|
|
|
627
|
+
/**
|
|
628
|
+
* Hand the machine-level lifecycle over to the daemon (daemonMode off → auto).
|
|
629
|
+
*
|
|
630
|
+
* A profile hot reload re-runs this plugin without restarting the process, so the
|
|
631
|
+
* exit hook/heartbeat/janitor installed by an earlier `ensureLifecycle` would keep
|
|
632
|
+
* running and compete with the daemon's own. This is the ONLY place they are
|
|
633
|
+
* removed again — a normal dispose must keep them armed (review P0-2).
|
|
634
|
+
*/
|
|
635
|
+
function releaseLegacyLifecycle() {
|
|
636
|
+
if (lifecycle === null || lifecycle.owner !== process.pid) return
|
|
637
|
+
try { process.removeListener('exit', lifecycle.onExit) } catch { /* ignore */ }
|
|
638
|
+
if (lifecycle.beat !== null) clearInterval(lifecycle.beat)
|
|
639
|
+
try { disarmJanitor() } catch { /* the watcher may not exist */ }
|
|
640
|
+
lifecycle = null
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* Exit hook for an engine THIS plugin had to start in `daemonMode=auto` because the
|
|
645
|
+
* daemon was down (port stolen, spawn failed, version mismatch). The daemon isn't
|
|
646
|
+
* running to own the teardown, and auto mode deliberately installs no lifecycle, so
|
|
647
|
+
* without this the engine, the bridge and the scoped git entry outlive dsh — git
|
|
648
|
+
* then points at a dead tunnel (review C2-P1-3).
|
|
649
|
+
*
|
|
650
|
+
* It never writes a heartbeat or arms a janitor: those stay the daemon's job, and
|
|
651
|
+
* writing them here would re-create the two-owner problem.
|
|
652
|
+
*/
|
|
653
|
+
let localProxyCleanup = null
|
|
654
|
+
function armLocalProxyCleanup() {
|
|
655
|
+
if (localProxyCleanup !== null) return
|
|
656
|
+
// A legacy lifecycle (daemonMode=off) already installs an exit hook that stops the
|
|
657
|
+
// same three layers; a second hook would just run the same sync cleanups twice.
|
|
658
|
+
if (lifecycle !== null) return
|
|
659
|
+
localProxyCleanup = () => {
|
|
660
|
+
try { stopProxySync() } catch { /* best effort while exiting */ }
|
|
661
|
+
try { stopRedirectorSync() } catch { /* best effort while exiting */ }
|
|
662
|
+
try { clearGitProxySync() } catch { /* best effort while exiting */ }
|
|
663
|
+
}
|
|
664
|
+
process.once('exit', localProxyCleanup)
|
|
665
|
+
}
|
|
666
|
+
/** Forget the local fallback cleanup once its engine is gone or the daemon took over. */
|
|
667
|
+
function disarmLocalProxyCleanup() {
|
|
668
|
+
if (localProxyCleanup === null) return
|
|
669
|
+
try { process.removeListener('exit', localProxyCleanup) } catch { /* ignore */ }
|
|
670
|
+
localProxyCleanup = null
|
|
671
|
+
}
|
|
672
|
+
|
|
538
673
|
/**
|
|
539
674
|
* Register this plugin's two routes for its lifetime.
|
|
540
675
|
*
|
|
@@ -561,6 +696,7 @@ export function apply(ctx, config) {
|
|
|
561
696
|
stopGraceMs: clampBytes(config?.stopGraceMs, DEFAULT_STOP_GRACE_MS, MAX_STOP_GRACE_MS),
|
|
562
697
|
runtime: config?.runtime === 'bash' || config?.runtime === 'powershell' ? config.runtime : 'auto',
|
|
563
698
|
bashPath: typeof config?.bashPath === 'string' && config.bashPath !== '' ? config.bashPath : undefined,
|
|
699
|
+
daemonMode: daemonModeEnabled(config) ? 'auto' : 'off',
|
|
564
700
|
}
|
|
565
701
|
ctx.effect(() => ctx.webServer.register({
|
|
566
702
|
kind: 'prefix',
|
|
@@ -584,14 +720,35 @@ export function apply(ctx, config) {
|
|
|
584
720
|
// teardown that removed the exit hook or disarmed the janitor left the detached
|
|
585
721
|
// engine alive with no UI to stop it.
|
|
586
722
|
ctx.effect(() => {
|
|
723
|
+
// The page's workspace list must survive idle windows: only the plugin can ask
|
|
724
|
+
// the host whether a session still exists, so refresh it in both modes (m08228).
|
|
725
|
+
const dshWindowTimer = setInterval(() => { refreshDshWindows(ctx) }, DSH_WINDOW_REFRESH_MS)
|
|
726
|
+
dshWindowTimer.unref?.()
|
|
727
|
+
const stopDshWindows = () => clearInterval(dshWindowTimer)
|
|
728
|
+
// daemonMode=auto: the daemon owns the engine, the heartbeat and the janitor,
|
|
729
|
+
// so the plugin must install none of them. Doing half of it (exit hook without
|
|
730
|
+
// engine ownership, or the reverse) is how Ctrl+C started leaking in the first
|
|
731
|
+
// place; the two halves ship together in Phase 1b P3/P4.
|
|
732
|
+
if (options.daemonMode === 'auto') {
|
|
733
|
+
// Switching off→auto in a hot reload: the daemon now owns the engine, the
|
|
734
|
+
// heartbeat and the janitor, so drop the legacy trio to avoid two owners
|
|
735
|
+
// (review C-P1-6).
|
|
736
|
+
releaseLegacyLifecycle()
|
|
737
|
+
return stopDshWindows
|
|
738
|
+
}
|
|
587
739
|
const adopted = adoptLeftoverEngine()
|
|
588
740
|
if (adopted !== null) {
|
|
589
741
|
try {
|
|
590
742
|
ctx.logger?.warn?.(`[dsh-ris-ide] 接管上一个会话留下的代理引擎(引擎 pid ${adopted.pid},原所有者 pid ${adopted.owner > 0 ? adopted.owner : '未知'})`)
|
|
591
743
|
} catch { /* logging is best effort */ }
|
|
592
744
|
}
|
|
593
|
-
|
|
745
|
+
// Previous runs (and reboots) leave machine-level side effects behind — a git
|
|
746
|
+
// entry pointing at a dead tunnel, a parked ProxyBridgeSvc, a stale pidfile.
|
|
747
|
+
// Reconcile against today's rules/state before the panel can show them.
|
|
748
|
+
scheduleStartupReconcile({ log: (message) => ctx.logger?.warn?.(message) })
|
|
749
|
+
const state = ensureLifecycle(ctx)
|
|
594
750
|
return () => {
|
|
751
|
+
stopDshWindows()
|
|
595
752
|
// Only the heartbeat stops here: its stop is exactly what the elevated bridge
|
|
596
753
|
// watchdog waits for (20 s freshness), and the next apply (a profile hot
|
|
597
754
|
// reload) restarts it in the same second. The exit hook and the janitor stay
|
|
@@ -603,6 +760,14 @@ export function apply(ctx, config) {
|
|
|
603
760
|
}
|
|
604
761
|
}
|
|
605
762
|
}, 'dsh-ris-ide: stop child services on exit')
|
|
763
|
+
// Optional risd bridge (Phase 1a): discovery + lease only. The engine is still
|
|
764
|
+
// ours, so this effect must not stop it — `stopRisdBridge` just releases the
|
|
765
|
+
// lease and lets the daemon's liveness poll do the rest.
|
|
766
|
+
ctx.effect(() => {
|
|
767
|
+
if (options.daemonMode !== 'auto') return () => {}
|
|
768
|
+
startRisdBridge(ctx, undefined)
|
|
769
|
+
return () => stopRisdBridge()
|
|
770
|
+
}, 'dsh-ris-ide: risd lease (optional daemon)')
|
|
606
771
|
}
|
|
607
772
|
|
|
608
773
|
/**
|
|
@@ -614,6 +779,146 @@ export function apply(ctx, config) {
|
|
|
614
779
|
* @param res - Node response face.
|
|
615
780
|
* @param options - `{ maxBytes, restrictToCwd, stopGraceMs }` (see {@link apply}).
|
|
616
781
|
*/
|
|
782
|
+
/** Where the daemon's maintenance page learns our URL(s) + sessionIds (GET /v1/dsh). */
|
|
783
|
+
const DSH_WINDOW_FILENAME = 'dsh-window.json'
|
|
784
|
+
/** Rewrite at most this often; a changed sessionId forces an immediate write. */
|
|
785
|
+
const DSH_WINDOW_THROTTLE_MS = 3000
|
|
786
|
+
/** Keep the list short: the page only needs the workspaces someone is working in. */
|
|
787
|
+
const DSH_WINDOW_MAX_ENTRIES = 8
|
|
788
|
+
let dshWindowNote = { at: 0, host: '', sessionId: '', cwd: '' }
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* Upsert one dsh window record (origin + sessionId per workspace). A daemon page
|
|
792
|
+
* can then offer every workspace's IDE in one window instead of one page per cwd.
|
|
793
|
+
* Loopback Hosts only, best effort, never throws.
|
|
794
|
+
* @param req - the incoming HTTP request.
|
|
795
|
+
*/
|
|
796
|
+
function noteDshWindow(req) {
|
|
797
|
+
// `node --test` runs against the developer's real home unless a test isolates
|
|
798
|
+
// DSH_RIS_IDE_PROXY_HOME. Fake contexts with /tmp workspaces used to collect
|
|
799
|
+
// entries in dsh-window.json and the daemon page listed them as workspaces
|
|
800
|
+
// (m08500), so tests must opt in explicitly.
|
|
801
|
+
if (process.env.NODE_TEST_CONTEXT !== undefined && process.env.DSH_RIS_IDE_WINDOW_NOTE !== '1') return
|
|
802
|
+
// Every other route on this prefix goes through isLoopbackRequest, which also
|
|
803
|
+
// rejects a cross-site Origin. This write feeds the daemon's workspace list, so a
|
|
804
|
+
// random page must not be able to seed it (review C2-P2-4).
|
|
805
|
+
if (!isLoopbackRequest(req)) return
|
|
806
|
+
const host = String(req?.headers?.host ?? '')
|
|
807
|
+
const now = Date.now()
|
|
808
|
+
let sessionId = ''
|
|
809
|
+
let cwd = ''
|
|
810
|
+
try {
|
|
811
|
+
const url = new URL(String(req.url ?? '/'), `http://${host}`)
|
|
812
|
+
sessionId = url.searchParams.get('sessionId') ?? ''
|
|
813
|
+
cwd = url.searchParams.get('cwd') ?? ''
|
|
814
|
+
} catch { /* malformed URL: keep the blanks */ }
|
|
815
|
+
// A request without a workspace cannot be attributed to one; recording it under
|
|
816
|
+
// `existing[0].cwd` replaced some OTHER workspace's window (review C-P1-5).
|
|
817
|
+
if (cwd === '' || !isAbsolute(cwd)) return
|
|
818
|
+
// Only a real dsh window may claim a workspace: its requests always carry
|
|
819
|
+
// ?sessionId=. The `/windows?cwd=` probes from the standalone/maintenance page do
|
|
820
|
+
// not, and inheriting the previous window's id made `/ws-a` open with `/ws-b`'s
|
|
821
|
+
// session and made the liveness check prune the wrong entry (review C2-P1-2).
|
|
822
|
+
if (sessionId === '') return
|
|
823
|
+
// A workspace nobody recorded yet is written immediately (the page needs it, and
|
|
824
|
+
// there are at most DSH_WINDOW_MAX_ENTRIES). Everything already recorded is at
|
|
825
|
+
// most one write per window: two windows alternating requests used to defeat the
|
|
826
|
+
// throttle and write the machine-level file on EVERY request (review C3-P2-6) —
|
|
827
|
+
// inside the window only the in-memory key moves.
|
|
828
|
+
const home = (() => { try { return proxyHomeDir() } catch { return '' } })()
|
|
829
|
+
if (home === '') return
|
|
830
|
+
const path = join(home, DSH_WINDOW_FILENAME)
|
|
831
|
+
let existing = []
|
|
832
|
+
try {
|
|
833
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'))
|
|
834
|
+
if (Array.isArray(parsed?.windows)) existing = parsed.windows
|
|
835
|
+
} catch { /* first write */ }
|
|
836
|
+
const known = existing.some((row) => row !== null && typeof row === 'object'
|
|
837
|
+
&& (row.cwd ?? '') === cwd && (row.sessionId ?? '') === sessionId)
|
|
838
|
+
if (known && now - dshWindowNote.at < DSH_WINDOW_THROTTLE_MS) {
|
|
839
|
+
dshWindowNote = { at: dshWindowNote.at, host, sessionId, cwd }
|
|
840
|
+
return
|
|
841
|
+
}
|
|
842
|
+
dshWindowNote = { at: now, host, sessionId, cwd }
|
|
843
|
+
try {
|
|
844
|
+
mkdirSync(home, { recursive: true, mode: 0o700 })
|
|
845
|
+
const entry = {
|
|
846
|
+
url: `http://${host}`,
|
|
847
|
+
sessionId,
|
|
848
|
+
cwd,
|
|
849
|
+
// Which plugin process wrote this row: another dsh (same home) refreshes and
|
|
850
|
+
// prunes only its own rows (review C2-P2-2).
|
|
851
|
+
ownerPid: process.pid,
|
|
852
|
+
at: new Date(now).toISOString(),
|
|
853
|
+
}
|
|
854
|
+
const windows = existing.filter((row) => row !== null && typeof row === 'object' && (row.cwd ?? '') !== cwd)
|
|
855
|
+
windows.unshift(entry)
|
|
856
|
+
const trimmed = windows.slice(0, DSH_WINDOW_MAX_ENTRIES)
|
|
857
|
+
// Atomic replace: a half-written file reads as "no windows" in the daemon
|
|
858
|
+
// (review C2-P2-1 / A2-P2-17).
|
|
859
|
+
writeStateAtomic(path, { windows: trimmed })
|
|
860
|
+
} catch { /* the daemon page simply greys the IDE tab out */ }
|
|
861
|
+
}
|
|
862
|
+
/** How often the plugin refreshes the liveness of remembered dsh windows. */
|
|
863
|
+
const DSH_WINDOW_REFRESH_MS = 10_000
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* Keep the remembered windows' `at` fresh while dsh still knows their session, so
|
|
867
|
+
* the daemon page lists every workspace that is currently open instead of only the
|
|
868
|
+
* one that happened to hit an endpoint within the freshness window (m08228).
|
|
869
|
+
* The plugin is the only writer of dsh-window.json; a daemon-side timer cannot
|
|
870
|
+
* answer "does this session still exist" because it has no host context.
|
|
871
|
+
* @param ctx - Host context (`ctx.sessions.get(id)`).
|
|
872
|
+
* @returns {{changed:number, windows:number}} how many entries were refreshed.
|
|
873
|
+
*/
|
|
874
|
+
export function refreshDshWindows(ctx) {
|
|
875
|
+
const result = { changed: 0, windows: 0, dropped: 0 }
|
|
876
|
+
try {
|
|
877
|
+
const path = join(proxyHomeDir(), DSH_WINDOW_FILENAME)
|
|
878
|
+
let windows = []
|
|
879
|
+
try {
|
|
880
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'))
|
|
881
|
+
if (Array.isArray(parsed?.windows)) windows = parsed.windows
|
|
882
|
+
} catch { return result }
|
|
883
|
+
if (windows.length === 0) return result
|
|
884
|
+
const now = Date.now()
|
|
885
|
+
const canVerify = typeof ctx?.sessions?.get === 'function'
|
|
886
|
+
let dirty = false
|
|
887
|
+
const next = windows.reduce((out, row) => {
|
|
888
|
+
if (row === null || typeof row !== 'object') return out
|
|
889
|
+
// Another dsh process owns this row (same machine-level home): its own plugin
|
|
890
|
+
// refreshes/prunes it. Deleting it here made two instances erase each other's
|
|
891
|
+
// workspaces (review C2-P2-2). Legacy rows (no ownerPid) are treated as ours;
|
|
892
|
+
// a garbage value must not be read as "someone else's row" (Number('abc') is
|
|
893
|
+
// NaN and used to fall through to the pruning branch, review C3-P2-5).
|
|
894
|
+
const rawOwner = Number(row.ownerPid)
|
|
895
|
+
const ownerPid = Number.isInteger(rawOwner) && rawOwner > 0 ? rawOwner : process.pid
|
|
896
|
+
if (ownerPid !== process.pid) { out.push(row); return out }
|
|
897
|
+
const sessionId = typeof row.sessionId === 'string' ? row.sessionId : ''
|
|
898
|
+
// An empty session id cannot be verified (legacy rows); keep it and let the
|
|
899
|
+
// daemon's retain TTL retire it.
|
|
900
|
+
if (sessionId === '' || !canVerify) { out.push(row); return out }
|
|
901
|
+
const session = ctx.sessions.get(sessionId)
|
|
902
|
+
const sessionCwd = typeof session?.header?.cwd === 'string' ? session.header.cwd : ''
|
|
903
|
+
// "Session exists" is not enough: a session may have been reopened on another
|
|
904
|
+
// workspace, and refreshing the old cwd would keep a wrong row alive.
|
|
905
|
+
if (!session || (sessionCwd !== '' && sessionCwd !== row.cwd)) {
|
|
906
|
+
dirty = true
|
|
907
|
+
result.dropped += 1
|
|
908
|
+
return out
|
|
909
|
+
}
|
|
910
|
+
dirty = true
|
|
911
|
+
result.changed += 1
|
|
912
|
+
out.push(Object.assign({}, row, { at: new Date(now).toISOString() }))
|
|
913
|
+
return out
|
|
914
|
+
}, [])
|
|
915
|
+
// Report the surviving size: the pre-prune number misled callers/tests (review E P2-2).
|
|
916
|
+
result.windows = next.length
|
|
917
|
+
if (dirty) writeStateAtomic(path, { windows: next })
|
|
918
|
+
} catch { /* best effort: the page keeps showing what it last knew */ }
|
|
919
|
+
return result
|
|
920
|
+
}
|
|
921
|
+
|
|
617
922
|
export function handleRequest(ctx, req, res, options) {
|
|
618
923
|
try {
|
|
619
924
|
dispatchRequest(ctx, req, res, options)
|
|
@@ -630,6 +935,7 @@ export function handleRequest(ctx, req, res, options) {
|
|
|
630
935
|
|
|
631
936
|
/** The actual router behind {@link handleRequest}'s exception fence. */
|
|
632
937
|
function dispatchRequest(ctx, req, res, options) {
|
|
938
|
+
noteDshWindow(req)
|
|
633
939
|
const method = req.method ?? 'GET'
|
|
634
940
|
const pathname = requestPathname(req)
|
|
635
941
|
if (pathname === WINDOWS_PATH) {
|
|
@@ -775,6 +1081,10 @@ function dispatchRequest(ctx, req, res, options) {
|
|
|
775
1081
|
return
|
|
776
1082
|
}
|
|
777
1083
|
if (pathname === DEBUGS_PATH) {
|
|
1084
|
+
if (!isLoopbackRequest(req)) {
|
|
1085
|
+
writeJson(res, 403, { ok: false, code: 'forbidden', message: 'this route answers loopback requests only' })
|
|
1086
|
+
return
|
|
1087
|
+
}
|
|
778
1088
|
if (method !== 'GET') {
|
|
779
1089
|
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
780
1090
|
return
|
|
@@ -798,6 +1108,28 @@ function dispatchRequest(ctx, req, res, options) {
|
|
|
798
1108
|
serveSafely(res, () => serveProxy(ctx, req, res, options))
|
|
799
1109
|
return
|
|
800
1110
|
}
|
|
1111
|
+
if (pathname === BUILD_PATH) {
|
|
1112
|
+
if (method !== 'GET') {
|
|
1113
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
1114
|
+
return
|
|
1115
|
+
}
|
|
1116
|
+
// No auth beyond loopback: it names a build, not a secret, and the page that
|
|
1117
|
+
// needs it may be the one asking before it has any other state.
|
|
1118
|
+
if (!isLoopbackRequest(req)) {
|
|
1119
|
+
writeJson(res, 403, { ok: false, code: 'forbidden', message: 'this route answers loopback requests only' })
|
|
1120
|
+
return
|
|
1121
|
+
}
|
|
1122
|
+
writeJson(res, 200, { ok: true, version: PKG_VERSION, build: clientBundleStamp() })
|
|
1123
|
+
return
|
|
1124
|
+
}
|
|
1125
|
+
if (pathname === RISD_ENSURE_PATH) {
|
|
1126
|
+
if (method !== 'POST') {
|
|
1127
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'POST only' })
|
|
1128
|
+
return
|
|
1129
|
+
}
|
|
1130
|
+
serveSafely(res, () => serveRisdEnsure(ctx, req, res, options))
|
|
1131
|
+
return
|
|
1132
|
+
}
|
|
801
1133
|
if (pathname === PROXY_ACTION_PATH) {
|
|
802
1134
|
if (method !== 'POST') {
|
|
803
1135
|
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'POST only' })
|
|
@@ -864,6 +1196,10 @@ function dispatchRequest(ctx, req, res, options) {
|
|
|
864
1196
|
return
|
|
865
1197
|
}
|
|
866
1198
|
if (pathname === OPENS_PATH) {
|
|
1199
|
+
if (!isLoopbackRequest(req)) {
|
|
1200
|
+
writeJson(res, 403, { ok: false, code: 'forbidden', message: 'this route answers loopback requests only' })
|
|
1201
|
+
return
|
|
1202
|
+
}
|
|
867
1203
|
if (method !== 'GET') {
|
|
868
1204
|
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
869
1205
|
return
|
|
@@ -1374,6 +1710,47 @@ function createOrderedPages(rootCount, pageSize, emit, options = {}) {
|
|
|
1374
1710
|
}
|
|
1375
1711
|
}
|
|
1376
1712
|
|
|
1713
|
+
/**
|
|
1714
|
+
* Identify the client bundle this host is serving right now.
|
|
1715
|
+
*
|
|
1716
|
+
* Why a page needs it: plugin bundles are served with `immutable` caching and a
|
|
1717
|
+
* revision-baked path, so an HTTP reload picks up a new build — but a page that
|
|
1718
|
+
* is ALREADY OPEN keeps running the bundle it booted with, which is why a
|
|
1719
|
+
* stylesheet tweak looks like it "needs a hard refresh". The stamp rides the
|
|
1720
|
+
* The stamp rides the stream's `hello` and `/dsh-ris-ide/build`; the page compares
|
|
1721
|
+
* it with the one it booted with and offers a refresh (it never reloads itself: a
|
|
1722
|
+
* reload would throw the conversation view or the IDE window's unsaved buffers
|
|
1723
|
+
* away, review C3-P1-2/P1-3).
|
|
1724
|
+
*
|
|
1725
|
+
* `standalone/window.html` is part of the stamp because the standalone window page
|
|
1726
|
+
* is served from it: its changes must reach the already-open window too. A DSH page
|
|
1727
|
+
* never loads it, so a window-only change makes the DSH hint say "refresh" where a
|
|
1728
|
+
* reload does not actually change the DSH bundle — harmless, and the window page
|
|
1729
|
+
* does pick it up.
|
|
1730
|
+
*
|
|
1731
|
+
* Metadata only (size + mtime): three `statSync` calls per hello is free, while
|
|
1732
|
+
* hashing a multi-megabyte bundle would not be.
|
|
1733
|
+
* @returns {string} 12 hex chars, stable until one of the bundle files changes.
|
|
1734
|
+
*/
|
|
1735
|
+
function clientBundleStamp() {
|
|
1736
|
+
const hash = createHash('sha1')
|
|
1737
|
+
const dir = fileURLToPath(new URL('.', import.meta.url))
|
|
1738
|
+
for (const name of ['client.js', 'client-codemirror.js', 'standalone/window.html']) {
|
|
1739
|
+
hash.update(name)
|
|
1740
|
+
hash.update('\0')
|
|
1741
|
+
try {
|
|
1742
|
+
const info = statSync(join(dir, name))
|
|
1743
|
+
hash.update(`${info.size}:${info.mtimeMs}`)
|
|
1744
|
+
} catch {
|
|
1745
|
+
// A trimmed install still gets a stable stamp; adding the file later
|
|
1746
|
+
// changes it, which is what the page needs to notice.
|
|
1747
|
+
hash.update('absent')
|
|
1748
|
+
}
|
|
1749
|
+
hash.update('\n')
|
|
1750
|
+
}
|
|
1751
|
+
return hash.digest('hex').slice(0, 12)
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1377
1754
|
/**
|
|
1378
1755
|
* Run `worker(root, index)` for every root with at most `concurrency` in flight.
|
|
1379
1756
|
* A worker must handle its own errors — one broken repo must not cancel the rest.
|
|
@@ -4634,6 +5011,9 @@ async function serveStream(ctx, req, res, options) {
|
|
|
4634
5011
|
send('hello', {
|
|
4635
5012
|
ok: true,
|
|
4636
5013
|
version: PKG_VERSION,
|
|
5014
|
+
// Which client bundle this host serves NOW (see clientBundleStamp): a page
|
|
5015
|
+
// that booted an older one reloads itself instead of needing Ctrl+Shift+R.
|
|
5016
|
+
build: clientBundleStamp(),
|
|
4637
5017
|
root: cwd,
|
|
4638
5018
|
topics,
|
|
4639
5019
|
window: windowCwd !== undefined,
|
|
@@ -5442,16 +5822,6 @@ async function proxyView(cwd, gitHost) {
|
|
|
5442
5822
|
const status = await proxyStatus(cwd)
|
|
5443
5823
|
const allow = allowList(status.config)
|
|
5444
5824
|
const git = gitProxyPlan(status.config, { host: gitHost })
|
|
5445
|
-
// One machine, one table: every stored rule is shown, whoever contributed it.
|
|
5446
|
-
// EXCEPT the loopback mapping rows dsh-ris-yds keeps as a fallback: those are an
|
|
5447
|
-
// implementation detail of "no system-level interception", not something the
|
|
5448
|
-
// user configures, so they never reach the dialog (they stay in the file, which
|
|
5449
|
-
// is what the engine and the redirector profile are built from).
|
|
5450
|
-
const own = status.config.rules.filter((rule) => !(rule.source === 'yds' && rule.shadow === true))
|
|
5451
|
-
// Templates only where the machine has no row for that program yet, so the
|
|
5452
|
-
// dialog off a fresh workspace still shows the four starter rows.
|
|
5453
|
-
const covered = new Set(own.map((rule) => programKey(rule.program)))
|
|
5454
|
-
const templates = autoRules(cwd).filter((rule) => !covered.has(programKey(rule.program)))
|
|
5455
5825
|
const watcher = janitorStatus()
|
|
5456
5826
|
// An engine adopted from a PREVIOUS dsh process (see adoptLeftoverEngine): the
|
|
5457
5827
|
// dialog shows a takeover banner with a one-click stop instead of pretending this
|
|
@@ -5470,21 +5840,7 @@ async function proxyView(cwd, gitHost) {
|
|
|
5470
5840
|
workspace: cwd,
|
|
5471
5841
|
socks: status.config.socks,
|
|
5472
5842
|
listenPort: status.config.listenPort,
|
|
5473
|
-
rules:
|
|
5474
|
-
const decorated = decorateProxyRule(rule)
|
|
5475
|
-
// A rule can start its program itself (that is the only way to inject the
|
|
5476
|
-
// tunnel into something we did not launch), so the row shows whether it is
|
|
5477
|
-
// up and where its log is.
|
|
5478
|
-
const service = await readService(proxyRunLogPath(cwd, rule.id)).catch(() => undefined)
|
|
5479
|
-
return Object.assign(decorated, {
|
|
5480
|
-
runnable: decorated.socksCapable && String(rule.program ?? '').trim() !== '',
|
|
5481
|
-
runLogPath: proxyRunLogPath(cwd, rule.id),
|
|
5482
|
-
run: service === undefined ? null : { pid: service.pid, alive: service.alive },
|
|
5483
|
-
})
|
|
5484
|
-
// `template: true` marks a starter row the user has not saved yet: the dialog
|
|
5485
|
-
// shows it, but must NOT write it back (it would turn a suggestion into a stored
|
|
5486
|
-
// rule and the row would then live forever in the shared table).
|
|
5487
|
-
}))).concat(templates.map((rule) => Object.assign(decorateProxyRule(rule), { template: true }))),
|
|
5843
|
+
rules: await proxyRulesView(cwd, status.config),
|
|
5488
5844
|
running: status.running,
|
|
5489
5845
|
pid: status.pid,
|
|
5490
5846
|
listen: status.listen,
|
|
@@ -5500,6 +5856,12 @@ async function proxyView(cwd, gitHost) {
|
|
|
5500
5856
|
// command instead of asking the user to assemble one.
|
|
5501
5857
|
rules: buildProfile(status.config).rules.length,
|
|
5502
5858
|
}),
|
|
5859
|
+
// Where the daemon maintenance page lives (null when daemonMode is off). The
|
|
5860
|
+
// header and console "IDE" buttons open that page instead of the window: it
|
|
5861
|
+
// embeds the IDE and can switch workspace, so one tab covers them all.
|
|
5862
|
+
risd: risdBridge !== null && risdBridge.state !== null
|
|
5863
|
+
? { available: true, url: risdBridge.state.url, port: risdBridge.state.port, apiVersion: risdBridge.state.apiVersion }
|
|
5864
|
+
: { available: false },
|
|
5503
5865
|
// Watchdog state: it is what removes the layers if dsh itself is killed.
|
|
5504
5866
|
janitor: watcher,
|
|
5505
5867
|
// Who owns the child services right now (0 = no watcher state at all).
|
|
@@ -5512,6 +5874,249 @@ async function proxyView(cwd, gitHost) {
|
|
|
5512
5874
|
}
|
|
5513
5875
|
}
|
|
5514
5876
|
|
|
5877
|
+
/**
|
|
5878
|
+
* The rule rows the dialog renders: every stored rule (whoever wrote it), minus
|
|
5879
|
+
* the loopback mapping rows dsh-ris-yds keeps as a fallback — those are an
|
|
5880
|
+
* implementation detail of "no system-level interception", not something the
|
|
5881
|
+
* user configures, so they never reach the dialog (they stay in the file, which
|
|
5882
|
+
* is what the engine and the redirector profile are built from).
|
|
5883
|
+
*
|
|
5884
|
+
* Templates are appended only where the machine has no row for that program
|
|
5885
|
+
* yet, so a fresh workspace still shows the starter rows. `template: true` marks
|
|
5886
|
+
* a starter row the user has not saved: the dialog shows it, but must NOT write
|
|
5887
|
+
* it back (that would turn a suggestion into a stored rule living forever in the
|
|
5888
|
+
* shared table).
|
|
5889
|
+
* @param cwd - workspace the rows are rendered for.
|
|
5890
|
+
* @param config - the normalised machine table.
|
|
5891
|
+
* @returns decorated rows, stored first then templates.
|
|
5892
|
+
*/
|
|
5893
|
+
async function proxyRulesView(cwd, config) {
|
|
5894
|
+
const own = config.rules.filter((rule) => !(rule.source === 'yds' && rule.shadow === true))
|
|
5895
|
+
const covered = new Set(own.map((rule) => programKey(rule.program)))
|
|
5896
|
+
const templates = autoRules(cwd).filter((rule) => !covered.has(programKey(rule.program)))
|
|
5897
|
+
const stored = await Promise.all(own.map(async (rule) => {
|
|
5898
|
+
const decorated = decorateProxyRule(rule)
|
|
5899
|
+
// A rule can start its program itself (that is the only way to inject the
|
|
5900
|
+
// tunnel into something we did not launch), so the row shows whether it is
|
|
5901
|
+
// up and where its log is.
|
|
5902
|
+
const service = await readService(proxyRunLogPath(cwd, rule.id)).catch(() => undefined)
|
|
5903
|
+
return Object.assign(decorated, {
|
|
5904
|
+
runnable: decorated.socksCapable && String(rule.program ?? '').trim() !== '',
|
|
5905
|
+
runLogPath: proxyRunLogPath(cwd, rule.id),
|
|
5906
|
+
run: service === undefined ? null : { pid: service.pid, alive: service.alive },
|
|
5907
|
+
})
|
|
5908
|
+
}))
|
|
5909
|
+
return stored.concat(templates.map((rule) => Object.assign(decorateProxyRule(rule), { template: true })))
|
|
5910
|
+
}
|
|
5911
|
+
|
|
5912
|
+
/**
|
|
5913
|
+
* Phase 1a bridge to risd: the daemon owns the read-only view, the plugin keeps
|
|
5914
|
+
* the parts that need a live process (per-rule run state, the inherited-engine
|
|
5915
|
+
* banner, the bridge status it still starts itself).
|
|
5916
|
+
*
|
|
5917
|
+
* `daemonMode` defaults to `auto` since 1.8.0: the ⧉ button and the tool layer
|
|
5918
|
+
* both want the daemon (it owns the engine, the programs and the page), and the
|
|
5919
|
+
* daemon was opt-in only while it was being built. `daemonMode=off` (config or
|
|
5920
|
+
* `DSH_RISD_MODE=off`) is still the one-word rollback to the pre-1.8 wiring.
|
|
5921
|
+
* @type {{mode: 'off'|'auto', state: object|null, leaseId: string|null, pending: Promise<void>|null, warnedAt: number}|null}
|
|
5922
|
+
*/
|
|
5923
|
+
let risdBridge = null
|
|
5924
|
+
|
|
5925
|
+
function daemonModeEnabled(config) {
|
|
5926
|
+
// 1.8.0 defaults to auto (m07355: the IDE entry always lands on risd-ui). Test
|
|
5927
|
+
// processes keep the historical off default so plugin suites do not spawn real
|
|
5928
|
+
// daemons; an explicit daemonMode/DSH_RISD_MODE still wins over both.
|
|
5929
|
+
//
|
|
5930
|
+
// Only the documented values switch it on. A typo ('of'), a stringified boolean
|
|
5931
|
+
// ('false') or 0 used to enable the daemon silently because the old test was
|
|
5932
|
+
// `value !== 'off'` (review E P2-1); unknown values now mean "off".
|
|
5933
|
+
const fallback = process.env.NODE_TEST_CONTEXT !== undefined && process.env.DSH_RISD_MODE === undefined ? 'off' : 'auto'
|
|
5934
|
+
const value = config?.daemonMode ?? process.env.DSH_RISD_MODE ?? fallback
|
|
5935
|
+
if (value === true || value === 'auto' || value === 'on') return true
|
|
5936
|
+
if (value === '') return true
|
|
5937
|
+
return false
|
|
5938
|
+
}
|
|
5939
|
+
|
|
5940
|
+
/**
|
|
5941
|
+
* Circuit breaker for automatic daemon starts.
|
|
5942
|
+
*
|
|
5943
|
+
* Every auto-start path (the ⧉ button, tool healing) must give up after a few
|
|
5944
|
+
* failures: a daemon that cannot boot (bad home permissions, port stolen by
|
|
5945
|
+
* something that never answers, broken Node install) would otherwise be spawned
|
|
5946
|
+
* again on every click/tool call, each costing the full 5 s health window. After
|
|
5947
|
+
* three failures inside two minutes we stop for five minutes and tell the user
|
|
5948
|
+
* what to run by hand.
|
|
5949
|
+
*/
|
|
5950
|
+
const RISD_HEAL_WINDOW_MS = 2 * 60_000
|
|
5951
|
+
const RISD_HEAL_MAX_ATTEMPTS = 3
|
|
5952
|
+
const RISD_HEAL_COOLDOWN_MS = 5 * 60_000
|
|
5953
|
+
let risdHeal = { attempts: 0, since: 0, blockedUntil: 0, lastError: '' }
|
|
5954
|
+
|
|
5955
|
+
/** @returns true while automatic starts are paused. */
|
|
5956
|
+
export function risdHealBlocked(now = Date.now()) {
|
|
5957
|
+
return now < risdHeal.blockedUntil
|
|
5958
|
+
}
|
|
5959
|
+
|
|
5960
|
+
/** @returns the message shown instead of starting the daemon, or ''. */
|
|
5961
|
+
export function risdHealReason(now = Date.now()) {
|
|
5962
|
+
if (!risdHealBlocked(now)) return ''
|
|
5963
|
+
const seconds = Math.max(1, Math.ceil((risdHeal.blockedUntil - now) / 1000))
|
|
5964
|
+
return `连续 ${RISD_HEAL_MAX_ATTEMPTS} 次自动启动 risd 失败(${risdHeal.lastError || 'unknown'}),${seconds}s 内不再自动唤起;请运行 risd serve 查看原因`
|
|
5965
|
+
}
|
|
5966
|
+
|
|
5967
|
+
/** Count one failed start; the third inside the window trips the breaker. */
|
|
5968
|
+
export function noteRisdHealFailure(error, now = Date.now()) {
|
|
5969
|
+
if (now - risdHeal.since > RISD_HEAL_WINDOW_MS) { risdHeal.attempts = 0; risdHeal.since = now }
|
|
5970
|
+
if (risdHeal.attempts === 0) risdHeal.since = now
|
|
5971
|
+
risdHeal.attempts += 1
|
|
5972
|
+
risdHeal.lastError = String(error ?? '').slice(0, 200)
|
|
5973
|
+
if (risdHeal.attempts >= RISD_HEAL_MAX_ATTEMPTS) {
|
|
5974
|
+
risdHeal.blockedUntil = now + RISD_HEAL_COOLDOWN_MS
|
|
5975
|
+
risdHeal.attempts = 0
|
|
5976
|
+
risdHeal.since = 0
|
|
5977
|
+
}
|
|
5978
|
+
}
|
|
5979
|
+
|
|
5980
|
+
/** A successful start clears the breaker. */
|
|
5981
|
+
export function noteRisdHealSuccess() {
|
|
5982
|
+
risdHeal = { attempts: 0, since: 0, blockedUntil: 0, lastError: '' }
|
|
5983
|
+
}
|
|
5984
|
+
|
|
5985
|
+
function startRisdBridge(ctx, cwd) {
|
|
5986
|
+
risdBridge = { mode: 'auto', state: null, leaseId: null, pending: null, warnedAt: 0 }
|
|
5987
|
+
const bridge = risdBridge
|
|
5988
|
+
bridge.pending = (async () => {
|
|
5989
|
+
const ensured = await ensureRisd({ home: proxyHomeDir() })
|
|
5990
|
+
if (ensured.ok !== true) {
|
|
5991
|
+
try {
|
|
5992
|
+
ctx.logger?.warn?.(`[dsh-ris-ide] risd 不可用(${ensured.reason ?? 'unknown'}),代理视图回退到插件本地`)
|
|
5993
|
+
} catch { /* logging is best effort */ }
|
|
5994
|
+
return
|
|
5995
|
+
}
|
|
5996
|
+
await attachBridgeState(ensured.state, cwd)
|
|
5997
|
+
})().finally(() => {
|
|
5998
|
+
if (bridge === risdBridge) bridge.pending = null
|
|
5999
|
+
})
|
|
6000
|
+
}
|
|
6001
|
+
|
|
6002
|
+
/**
|
|
6003
|
+
* Point the bridge at a live daemon and make sure this window holds a lease.
|
|
6004
|
+
*
|
|
6005
|
+
* Keeping the same function for start / heal / ensure matters: a lease acquired
|
|
6006
|
+
* once survives a single failed request, and a window that keeps its lease is what
|
|
6007
|
+
* `followDsh` uses to decide that dsh is still open (review C-P1-1).
|
|
6008
|
+
* @param state - daemon state from `ensureRisd()`.
|
|
6009
|
+
* @param cwd - workspace for the lease (null before the first session is known).
|
|
6010
|
+
* @returns the same state, for chaining.
|
|
6011
|
+
*/
|
|
6012
|
+
function attachBridgeState(state, cwd = null) {
|
|
6013
|
+
const bridge = risdBridge
|
|
6014
|
+
if (bridge === null || bridge.mode !== 'auto') return state
|
|
6015
|
+
bridge.state = state
|
|
6016
|
+
bridge.degraded = false
|
|
6017
|
+
bridge.lastProbeAt = Date.now()
|
|
6018
|
+
// The daemon owns the engine now: the local fallback hook (armed when the engine
|
|
6019
|
+
// was started behind the daemon's back) must not stop it on dsh exit (review
|
|
6020
|
+
// C3-P2-7).
|
|
6021
|
+
disarmLocalProxyCleanup()
|
|
6022
|
+
if (bridge.leaseId === null) {
|
|
6023
|
+
void acquireLease(state, { ownerPid: process.pid, sessionId: null, cwd: cwd ?? null })
|
|
6024
|
+
.then((lease) => {
|
|
6025
|
+
if (lease.ok === true && lease.body?.lease !== undefined) bridge.leaseId = lease.body.lease.id
|
|
6026
|
+
})
|
|
6027
|
+
.catch(() => { /* the next attach retries */ })
|
|
6028
|
+
}
|
|
6029
|
+
return state
|
|
6030
|
+
}
|
|
6031
|
+
|
|
6032
|
+
/**
|
|
6033
|
+
* The daemon state a writer should use, or null when this process should write
|
|
6034
|
+
* locally.
|
|
6035
|
+
*
|
|
6036
|
+
* A single failed request used to null the pointer permanently and let the plugin
|
|
6037
|
+
* write the machine-wide table behind the daemon's back (review C-P0-2). Now a
|
|
6038
|
+
* missing pointer is a *degraded* state: retry the handshake (throttled), and let
|
|
6039
|
+
* the caller refuse to write locally while the daemon may still be alive.
|
|
6040
|
+
* @param cwd - workspace for the lease.
|
|
6041
|
+
* @returns live daemon state, or null.
|
|
6042
|
+
*/
|
|
6043
|
+
async function risdBridgeState(cwd = null) {
|
|
6044
|
+
const bridge = risdBridge
|
|
6045
|
+
if (bridge === null || bridge.mode !== 'auto') return null
|
|
6046
|
+
if (bridge.pending !== null) {
|
|
6047
|
+
await Promise.race([bridge.pending, new Promise((resolve) => { const timer = setTimeout(resolve, 3000); timer.unref?.() })])
|
|
6048
|
+
}
|
|
6049
|
+
if (bridge.state !== null) return bridge.state
|
|
6050
|
+
if (Date.now() - (bridge.lastProbeAt ?? 0) < 5000) return null
|
|
6051
|
+
bridge.lastProbeAt = Date.now()
|
|
6052
|
+
const ensured = await ensureRisd({ home: proxyHomeDir() }).catch(() => ({ ok: false, reason: 'spawn failed' }))
|
|
6053
|
+
if (ensured.ok !== true) {
|
|
6054
|
+
bridge.degraded = true
|
|
6055
|
+
return null
|
|
6056
|
+
}
|
|
6057
|
+
return attachBridgeState(ensured.state, cwd)
|
|
6058
|
+
}
|
|
6059
|
+
|
|
6060
|
+
function stopRisdBridge() {
|
|
6061
|
+
const bridge = risdBridge
|
|
6062
|
+
if (bridge === null) return
|
|
6063
|
+
// Releasing the lease is all this process owns: the daemon decides what to do
|
|
6064
|
+
// with the engine, and in phase 1a the engine is still ours, so nothing else
|
|
6065
|
+
// may be stopped from here.
|
|
6066
|
+
if (bridge.state !== null && bridge.leaseId !== null) void releaseLease(bridge.state, bridge.leaseId)
|
|
6067
|
+
bridge.state = null
|
|
6068
|
+
bridge.leaseId = null
|
|
6069
|
+
bridge.pending = null
|
|
6070
|
+
risdBridge = null
|
|
6071
|
+
}
|
|
6072
|
+
|
|
6073
|
+
/**
|
|
6074
|
+
* Ask the daemon for the read-only view and dress it up as the plugin's own.
|
|
6075
|
+
* @returns the decorated view, or null when the daemon is off/unreachable (the
|
|
6076
|
+
* caller then falls back to the local `proxyView`).
|
|
6077
|
+
*/
|
|
6078
|
+
async function risdForwardedView(cwd, gitHost) {
|
|
6079
|
+
if (risdBridge === null || risdBridge.mode !== 'auto') return null
|
|
6080
|
+
const bridge = risdBridge
|
|
6081
|
+
if (bridge.state === null) {
|
|
6082
|
+
if (bridge.pending !== null) {
|
|
6083
|
+
await Promise.race([bridge.pending, new Promise((resolve) => setTimeout(resolve, 3000))])
|
|
6084
|
+
}
|
|
6085
|
+
if (bridge.state === null) return null
|
|
6086
|
+
}
|
|
6087
|
+
const base = await getProxyView(bridge.state, cwd)
|
|
6088
|
+
if (base === null || base.ok !== true) {
|
|
6089
|
+
// One failed read does not prove the daemon is gone: mark the bridge degraded,
|
|
6090
|
+
// KEEP the lease (a lost lease makes followDsh tear down tunnels that other
|
|
6091
|
+
// windows still use) and let the next call re-handshake (review C-P0-2).
|
|
6092
|
+
bridge.state = null
|
|
6093
|
+
bridge.degraded = true
|
|
6094
|
+
return null
|
|
6095
|
+
}
|
|
6096
|
+
return mergeRisdView(base, cwd, gitHost)
|
|
6097
|
+
}
|
|
6098
|
+
|
|
6099
|
+
async function mergeRisdView(base, cwd, gitHost) {
|
|
6100
|
+
const config = readProxyConfig(cwd)
|
|
6101
|
+
const watcher = janitorStatus()
|
|
6102
|
+
const inherited = inheritedEngine !== null && inheritedEngine.pid === base.pid ? inheritedEngine : null
|
|
6103
|
+
const redirectorRules = Number.isInteger(base.redirector?.rules) ? base.redirector.rules : buildProfile(config).rules.length
|
|
6104
|
+
return Object.assign({}, base, {
|
|
6105
|
+
risd: risdBridge !== null && risdBridge.state !== null
|
|
6106
|
+
? { available: true, url: risdBridge.state.url, port: risdBridge.state.port, apiVersion: risdBridge.state.apiVersion }
|
|
6107
|
+
: { available: true, url: base.url ?? '', port: base.port ?? 0, apiVersion: base.apiVersion ?? 0 },
|
|
6108
|
+
rules: await proxyRulesView(cwd, config),
|
|
6109
|
+
git: gitProxyPlan(config, { host: gitHost }),
|
|
6110
|
+
redirector: Object.assign(redirectorStatusCached(), { rules: redirectorRules }),
|
|
6111
|
+
janitor: base.janitor ?? watcher,
|
|
6112
|
+
owner: base.owner ?? watcher.owner,
|
|
6113
|
+
inherited: inherited !== null,
|
|
6114
|
+
inheritedPid: inherited === null ? 0 : inherited.pid,
|
|
6115
|
+
inheritedFrom: inherited === null ? 0 : inherited.owner,
|
|
6116
|
+
inheritedSince: inherited === null ? '' : inherited.detectedAt,
|
|
6117
|
+
})
|
|
6118
|
+
}
|
|
6119
|
+
|
|
5515
6120
|
/**
|
|
5516
6121
|
* Where a rule's 启动/停止 button keeps its log.
|
|
5517
6122
|
*
|
|
@@ -5556,6 +6161,64 @@ function proxyRunProgram(cwd, rule) {
|
|
|
5556
6161
|
}
|
|
5557
6162
|
|
|
5558
6163
|
/** `GET` reads the proxy state, `POST` validates + saves the form. */
|
|
6164
|
+
/**
|
|
6165
|
+
* Start the daemon if it is not running and report where its page lives.
|
|
6166
|
+
*
|
|
6167
|
+
* Loopback-only, like every other proxy route: the page it returns is a LAN-less
|
|
6168
|
+
* 127.0.0.1 URL, and spawning a machine-level process is not something a remote
|
|
6169
|
+
* request may trigger.
|
|
6170
|
+
*/
|
|
6171
|
+
async function serveRisdEnsure(ctx, req, res, options) {
|
|
6172
|
+
if (!isLoopbackRequest(req)) {
|
|
6173
|
+
throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
6174
|
+
}
|
|
6175
|
+
// daemonMode=off means the plugin keeps ownership of the engine, the heartbeat
|
|
6176
|
+
// and the janitor. A spawned daemon unconditionally writes its heartbeat and arms
|
|
6177
|
+
// its own janitor, and the janitor REPLACES a watcher owned by a different pid —
|
|
6178
|
+
// so starting one here silently removed the plugin's crash cleanup (dsh crash left
|
|
6179
|
+
// the engine/bridge/git behind) and a daemon crash tore down the engine the plugin
|
|
6180
|
+
// was still using (review C2-P0-1). Off mode therefore keeps the pre-1.8
|
|
6181
|
+
// behaviour: answer "unavailable" and let the caller fall back to the standalone
|
|
6182
|
+
// window. Users who want the maintenance page opt into daemonMode=auto.
|
|
6183
|
+
if (options.daemonMode !== 'auto') {
|
|
6184
|
+
writeJson(res, 200, {
|
|
6185
|
+
ok: false,
|
|
6186
|
+
risd: { available: false, reason: 'daemonMode=off:IDE 请用独立窗口(把 daemonMode 设为 auto 可启用维护页)' },
|
|
6187
|
+
})
|
|
6188
|
+
return
|
|
6189
|
+
}
|
|
6190
|
+
const paused = risdHealReason()
|
|
6191
|
+
if (paused !== '') {
|
|
6192
|
+
writeJson(res, 200, { ok: false, risd: { available: false, reason: paused } })
|
|
6193
|
+
return
|
|
6194
|
+
}
|
|
6195
|
+
const ensured = await ensureRisd({ home: proxyHomeDir() })
|
|
6196
|
+
if (ensured.ok !== true) {
|
|
6197
|
+
// A version mismatch is not a crash: re-spawning the same old daemon cannot
|
|
6198
|
+
// fix it, so it must not spend breaker budget (review C-P2-1).
|
|
6199
|
+
const mismatch = ensured.reason === 'api-mismatch'
|
|
6200
|
+
if (!mismatch) noteRisdHealFailure(ensured.reason ?? 'unavailable')
|
|
6201
|
+
writeJson(res, 200, {
|
|
6202
|
+
ok: false,
|
|
6203
|
+
risd: { available: false, reason: mismatch ? 'risd 版本与插件不一致:请重启 dsh 以启动匹配版本' : (ensured.reason ?? 'unavailable') },
|
|
6204
|
+
})
|
|
6205
|
+
return
|
|
6206
|
+
}
|
|
6207
|
+
noteRisdHealSuccess()
|
|
6208
|
+
const state = ensured.state
|
|
6209
|
+
attachBridgeState(state, null)
|
|
6210
|
+
writeJson(res, 200, {
|
|
6211
|
+
ok: true,
|
|
6212
|
+
spawned: ensured.spawned === true,
|
|
6213
|
+
risd: {
|
|
6214
|
+
available: true,
|
|
6215
|
+
url: `http://127.0.0.1:${state.port}`,
|
|
6216
|
+
port: state.port,
|
|
6217
|
+
apiVersion: state.apiVersion,
|
|
6218
|
+
},
|
|
6219
|
+
})
|
|
6220
|
+
}
|
|
6221
|
+
|
|
5559
6222
|
async function serveProxy(ctx, req, res, options) {
|
|
5560
6223
|
try {
|
|
5561
6224
|
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
@@ -5566,6 +6229,43 @@ async function serveProxy(ctx, req, res, options) {
|
|
|
5566
6229
|
const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
|
|
5567
6230
|
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
5568
6231
|
const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
|
|
6232
|
+
const gitHostBody = typeof body.gitHost === 'string' ? body.gitHost : undefined
|
|
6233
|
+
// Phase 1b P4: when risd owns the proxy, it is also the only writer of the
|
|
6234
|
+
// machine-wide table. Forward the write and let the daemon's CAS reject a
|
|
6235
|
+
// stale form; the view returned to the dialog is still built locally (row
|
|
6236
|
+
// decoration needs this process's program list).
|
|
6237
|
+
const writeState = await risdBridgeState(cwd)
|
|
6238
|
+
if (writeState === null && risdBridge !== null && risdBridge.mode === 'auto') {
|
|
6239
|
+
// The daemon may still be alive: writing the machine-wide table here would
|
|
6240
|
+
// race it (split-brain rules/git). Only a confirmed-absent daemon falls back.
|
|
6241
|
+
const probe = await probeRisd({ home: proxyHomeDir() }).catch(() => ({ usable: false, reason: 'unreachable' }))
|
|
6242
|
+
if (probe.usable === true) {
|
|
6243
|
+
throw new TailError('bad-gateway', 'risd 正在运行但连接未就绪,本次保存未写入:请稍后重试,或在概览停掉 daemon 后重试', 503)
|
|
6244
|
+
}
|
|
6245
|
+
}
|
|
6246
|
+
if (writeState !== null) {
|
|
6247
|
+
const call = await saveProxy(writeState, { cwd, config: body.config, revision: body.revision, gitHost: gitHostBody })
|
|
6248
|
+
if (call.status === 409) {
|
|
6249
|
+
// Two different 409s reach this branch: a stale table (conflict, with
|
|
6250
|
+
// `conflict:true` and a revision) and a version mismatch between plugin
|
|
6251
|
+
// and daemon (`code:'api-mismatch'`, no conflict flag). Only the first is
|
|
6252
|
+
// something the dialog can recover from by reloading; the second needs a
|
|
6253
|
+
// dsh restart, so it keeps design §7.1's 503 instead of being reported as
|
|
6254
|
+
// "someone else changed the rules" (review C-P2-1).
|
|
6255
|
+
if (call.body !== null && call.body.code === 'api-mismatch') {
|
|
6256
|
+
throw new TailError('risd-upgrade-required', `${call.body.message ?? '插件与 risd 版本不一致'}:请重启 dsh,让插件启动匹配版本的 risd`, 503)
|
|
6257
|
+
}
|
|
6258
|
+
const view = await proxyView(cwd, gitHostBody)
|
|
6259
|
+
writeJson(res, 409, Object.assign({}, call.body, { view }))
|
|
6260
|
+
return
|
|
6261
|
+
}
|
|
6262
|
+
if (call.ok !== true) {
|
|
6263
|
+
throw new TailError('bad-gateway', `risd 写入失败:${call.body?.message ?? call.error ?? `HTTP ${call.status}`}`, 502)
|
|
6264
|
+
}
|
|
6265
|
+
const view = await proxyView(cwd, gitHostBody)
|
|
6266
|
+
writeJson(res, 200, Object.assign({}, view, { reloadNote: call.body?.reloadNote ?? '' }))
|
|
6267
|
+
return
|
|
6268
|
+
}
|
|
5569
6269
|
// The dialog shows the WHOLE machine-wide table, so its payload is
|
|
5570
6270
|
// authoritative for the rows a human owns (source user/auto): a row the
|
|
5571
6271
|
// payload no longer carries was deleted. Driven rows (source yds) are owned
|
|
@@ -5604,37 +6304,58 @@ async function serveProxy(ctx, req, res, options) {
|
|
|
5604
6304
|
{ socks: incoming.socks, listenPort: incoming.listenPort, rules: rows, workspace: cwd },
|
|
5605
6305
|
)
|
|
5606
6306
|
writeProxyConfig(cwd, written)
|
|
6307
|
+
// Clean up what the PREVIOUS table applied before the new one takes effect:
|
|
6308
|
+
// the bridge reload below restarts ProxyBridge, but the scoped git entry is
|
|
6309
|
+
// not part of that profile and would otherwise stay on the old host.
|
|
6310
|
+
const git = await reconcileGitProxy(cwd)
|
|
5607
6311
|
// Apply without a manual restart: our own engine watches proxy.json and
|
|
5608
6312
|
// swaps its allow-list/listeners in place; ProxyBridge reads its profile only
|
|
5609
6313
|
// at start, so the elevated watchdog restarts just that process (no UAC, the
|
|
5610
6314
|
// dialog never has to ask the user to stop/start).
|
|
5611
6315
|
const bridge = redirectorStatusCached()
|
|
5612
6316
|
let reloadNote = ''
|
|
6317
|
+
// Revoking is part of switching: ProxyBridge parses its profile only at start,
|
|
6318
|
+
// so a failed reload would leave the OLD rules intercepting while the dialog
|
|
6319
|
+
// reports a successful save. Stop the bridge instead of leaving stale rules.
|
|
6320
|
+
const revoke = async (reason) => {
|
|
6321
|
+
const stopped = await stopRedirector()
|
|
6322
|
+
return `${reason};${stopped.stopped === true
|
|
6323
|
+
? '已停止系统层拦截,避免继续按旧规则代理'
|
|
6324
|
+
: `未能停止系统层拦截(${stopped.reason ?? '未知原因'}),旧规则可能仍在生效`}`
|
|
6325
|
+
}
|
|
5613
6326
|
if (bridge.running === true) {
|
|
5614
6327
|
// ONE call does the whole job: ProxyBridge reads its profile only at start,
|
|
5615
6328
|
// so a reload that does not rewrite the profile would relaunch the OLD rules
|
|
5616
6329
|
// and still report success (that was B3). The helper writes first, then
|
|
5617
6330
|
// restarts, and only claims a side was reloaded when it saw the new pid.
|
|
5618
6331
|
try {
|
|
5619
|
-
|
|
6332
|
+
// Which sides exist per platform is `reloadRedirectorsWithProfile`'s own
|
|
6333
|
+
// default; spelling it out here duplicated that knowledge and would drift
|
|
6334
|
+
// when the default changes (review C3-P2-8).
|
|
6335
|
+
const reload = await reloadRedirectorsWithProfile(cwd)
|
|
5620
6336
|
const done = Array.isArray(reload.reloaded) ? reload.reloaded : []
|
|
5621
6337
|
const skipped = Array.isArray(reload.skipped) ? reload.skipped : []
|
|
5622
6338
|
reloadNote = done.length > 0
|
|
5623
6339
|
? '系统层拦截已按新规则自动重启'
|
|
5624
|
-
: `系统层拦截未重载:${skipped.map((item) => `${item.side}:${item.reason}`).join(';') || reload.reason || '未知原因'}`
|
|
6340
|
+
: await revoke(`系统层拦截未重载:${skipped.map((item) => `${item.side}:${item.reason}`).join(';') || reload.reason || '未知原因'}`)
|
|
5625
6341
|
} catch (error) {
|
|
5626
|
-
reloadNote = `系统层拦截未重载:${error?.message ?? error}`
|
|
6342
|
+
reloadNote = await revoke(`系统层拦截未重载:${error?.message ?? error}`)
|
|
5627
6343
|
}
|
|
5628
6344
|
}
|
|
5629
6345
|
const view = await proxyView(cwd, typeof body.gitHost === 'string' ? body.gitHost : undefined)
|
|
5630
|
-
writeJson(res, 200, Object.assign({}, view, { reloadNote }))
|
|
6346
|
+
writeJson(res, 200, Object.assign({}, view, { reloadNote, git }))
|
|
5631
6347
|
return
|
|
5632
6348
|
}
|
|
5633
6349
|
if (method !== 'GET') throw new TailError('method-not-allowed', 'GET or POST', 405)
|
|
5634
6350
|
const sessionId = url.searchParams.get('sessionId') ?? ''
|
|
5635
6351
|
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
5636
6352
|
const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
|
|
5637
|
-
|
|
6353
|
+
const gitHost = url.searchParams.get('gitHost') ?? undefined
|
|
6354
|
+
// Phase 1a: when risd is opted in and reachable the VIEW comes from the
|
|
6355
|
+
// daemon (single source for config/revision/engine status); the plugin only
|
|
6356
|
+
// decorates it. Any daemon problem falls back to the local view, so the
|
|
6357
|
+
// dialog never breaks because an optional process is down.
|
|
6358
|
+
writeJson(res, 200, (await risdForwardedView(cwd, gitHost)) ?? await proxyView(cwd, gitHost))
|
|
5638
6359
|
} catch (error) {
|
|
5639
6360
|
writeTailError(res, error)
|
|
5640
6361
|
}
|
|
@@ -5754,6 +6475,23 @@ async function syncGitProxy({ cwd, host, enabled }) {
|
|
|
5754
6475
|
return { ok: true, key: plan.key, host: target, windows }
|
|
5755
6476
|
}
|
|
5756
6477
|
|
|
6478
|
+
/**
|
|
6479
|
+
* Re-align the scoped git entry with the table that was just saved.
|
|
6480
|
+
*
|
|
6481
|
+
* Saving rules used to write `proxy.json` and reload the bridge only; the
|
|
6482
|
+
* `git config --global` entry of the PREVIOUS host survived, so removing or
|
|
6483
|
+
* repointing the git rule left every terminal pointed at a dead tunnel. A
|
|
6484
|
+
* surviving git rule wins (syncGitProxy unsets the old key first, and only when
|
|
6485
|
+
* the recorded value is still ours); with no git rule left, ours is cleared.
|
|
6486
|
+
* @param {string} cwd - workspace root.
|
|
6487
|
+
* @returns {Promise<object>} outcome of the sync/clear.
|
|
6488
|
+
*/
|
|
6489
|
+
async function reconcileGitProxy(cwd) {
|
|
6490
|
+
const host = gitRuleHost(cwd)
|
|
6491
|
+
if (host === '') return syncGitProxy({ cwd, enabled: false })
|
|
6492
|
+
return syncGitProxy({ cwd, host, enabled: true })
|
|
6493
|
+
}
|
|
6494
|
+
|
|
5757
6495
|
/** Synchronous git-proxy undo for the exit hook, which cannot await anything. */
|
|
5758
6496
|
function clearGitProxySync() {
|
|
5759
6497
|
const { key } = readGitProxyState()
|
|
@@ -5788,12 +6526,45 @@ async function serveProxyAction(ctx, req, res, options) {
|
|
|
5788
6526
|
const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
|
|
5789
6527
|
const action = typeof body.action === 'string' ? body.action : 'status'
|
|
5790
6528
|
const gitHost = typeof body.gitHost === 'string' ? body.gitHost : undefined
|
|
6529
|
+
// Engine + bridge + git are the daemon's once it owns the proxy; the per-rule
|
|
6530
|
+
// 启动/停止 buttons stay here because they launch a child of THIS process (the
|
|
6531
|
+
// injection only works on a child we spawn ourselves).
|
|
6532
|
+
const daemonActions = new Set(['start', 'stop', 'git-on', 'git-off', 'redirector-sync', 'redirector-start', 'redirector-stop', 'redirector-restart', 'status'])
|
|
6533
|
+
const actionState = await risdBridgeState(cwd)
|
|
6534
|
+
if (actionState === null && risdBridge !== null && risdBridge.mode === 'auto' && daemonActions.has(action)) {
|
|
6535
|
+
const probe = await probeRisd({ home: proxyHomeDir() }).catch(() => ({ usable: false, reason: 'unreachable' }))
|
|
6536
|
+
if (probe.usable === true) {
|
|
6537
|
+
throw new TailError('bad-gateway', `risd 正在运行但连接未就绪,${action} 未执行:请稍后重试`, 503)
|
|
6538
|
+
}
|
|
6539
|
+
}
|
|
6540
|
+
if (actionState !== null && daemonActions.has(action)) {
|
|
6541
|
+
const call = await proxyAction(actionState, { cwd, action, gitHost })
|
|
6542
|
+
if (call.ok !== true) {
|
|
6543
|
+
// No answer at all (network error / timeout) is not a business failure: the
|
|
6544
|
+
// action did not run, and the panel has no second entry point for the engine
|
|
6545
|
+
// any more. Answer 503 + "retry", and re-arm the handshake so the retry can
|
|
6546
|
+
// succeed instead of hitting the same dead socket (review C-P2-8).
|
|
6547
|
+
if (call.status === 0 || call.body === null) {
|
|
6548
|
+
void risdBridgeState(cwd).catch(() => {})
|
|
6549
|
+
throw new TailError('risd-unavailable', `risd 不可用(${call.error ?? 'no answer'}),${action} 未执行:请稍后重试,页面会在下一次重新唤起 daemon`, 503)
|
|
6550
|
+
}
|
|
6551
|
+
throw new TailError('bad-gateway', `risd 操作失败:${call.body?.message ?? call.error ?? `HTTP ${call.status}`}`, 502)
|
|
6552
|
+
}
|
|
6553
|
+
if (action === 'start' || action === 'stop') inheritedEngine = null
|
|
6554
|
+
writeJson(res, 200, Object.assign({ ok: true, action, result: call.body?.result }, await proxyView(cwd, gitHost)))
|
|
6555
|
+
return
|
|
6556
|
+
}
|
|
5791
6557
|
let result
|
|
5792
6558
|
if (action === 'start') {
|
|
5793
6559
|
// One button, three layers: engine (spawned children) + system-level
|
|
5794
6560
|
// interception (everything else, UAC/root is the expected prompt) + the git
|
|
5795
6561
|
// config entry (so a plain `git` and dsh-git inherit the tunnel). Stopping
|
|
5796
6562
|
// undoes all three, and so does the host exit hook.
|
|
6563
|
+
//
|
|
6564
|
+
// Reached only when the daemon is unavailable (otherwise the branch above
|
|
6565
|
+
// answers): this engine is ours, so install the exit hook that auto mode would
|
|
6566
|
+
// otherwise rely on the daemon to provide (review C2-P1-3).
|
|
6567
|
+
armLocalProxyCleanup()
|
|
5797
6568
|
const engine = await startProxy(cwd)
|
|
5798
6569
|
const redirector = await startRedirectors()
|
|
5799
6570
|
const git = await syncGitProxy({ cwd, host: gitHost, enabled: true })
|
|
@@ -5803,6 +6574,7 @@ async function serveProxyAction(ctx, req, res, options) {
|
|
|
5803
6574
|
const git = await syncGitProxy({ cwd, host: gitHost, enabled: false })
|
|
5804
6575
|
const redirector = await stopRedirector()
|
|
5805
6576
|
const stopped = await stopProxy(cwd)
|
|
6577
|
+
disarmLocalProxyCleanup()
|
|
5806
6578
|
// The banner must not come back once the adopted engine is really gone.
|
|
5807
6579
|
if (proxyPid() === null) inheritedEngine = null
|
|
5808
6580
|
result = Object.assign({}, stopped, { redirector, git })
|
|
@@ -5838,6 +6610,17 @@ async function serveProxyAction(ctx, req, res, options) {
|
|
|
5838
6610
|
result = await syncRedirector(cwd, { start: true })
|
|
5839
6611
|
} else if (action === 'redirector-stop') {
|
|
5840
6612
|
result = await stopRedirector()
|
|
6613
|
+
} else if (action === 'redirector-restart') {
|
|
6614
|
+
// Same contract as the daemon: stop, let the profile write settle, start.
|
|
6615
|
+
const stopped = await stopRedirector()
|
|
6616
|
+
await new Promise((resolve) => setTimeout(resolve, 300))
|
|
6617
|
+
const started = await startRedirectors()
|
|
6618
|
+
result = {
|
|
6619
|
+
stopped,
|
|
6620
|
+
started: started.started ?? [],
|
|
6621
|
+
skipped: started.skipped ?? [],
|
|
6622
|
+
running: started.running === true,
|
|
6623
|
+
}
|
|
5841
6624
|
} else if (action !== 'status') {
|
|
5842
6625
|
throw new TailError('bad-request', `unknown proxy action "${action}"`, 400)
|
|
5843
6626
|
}
|
|
@@ -6405,7 +7188,8 @@ export async function startProgram(cwd, logsDir, program, options) {
|
|
|
6405
7188
|
}
|
|
6406
7189
|
let child
|
|
6407
7190
|
if (IS_WINDOWS) {
|
|
6408
|
-
const
|
|
7191
|
+
const customCommand = typeof program.startCommand === 'string' ? program.startCommand.replace(/\s*\$\{JDWP_ARGS\}\s*/g, ' ') : ''
|
|
7192
|
+
const selected = resolveWindowsRuntime(options?.runtime, options?.bashPath, { bashDialect: isBashDialectCommand(customCommand) })
|
|
6409
7193
|
if (selected.runtime === 'bash') {
|
|
6410
7194
|
// Git Bash: same wrapper as Linux, Windows-flavored classpath.
|
|
6411
7195
|
const spec = buildStartSpec(program, { workspace: cwd, logsDir, variant: 'windows-bash', debug: options?.debug })
|
|
@@ -7278,7 +8062,12 @@ async function considerFrontend(workspace, file, programs) {
|
|
|
7278
8062
|
function assignLogNames(programs) {
|
|
7279
8063
|
const used = new Map()
|
|
7280
8064
|
for (const program of programs) {
|
|
7281
|
-
|
|
8065
|
+
// Frontend rows are already named after their own manifest (module.xml / folder),
|
|
8066
|
+
// so prefixing the project only produced names that collided with the backend row
|
|
8067
|
+
// of the same yds module ("yonasset-c-ass-kk-hans" vs. the launcher's row).
|
|
8068
|
+
const base = sanitizeLogName(program.kind === 'frontend'
|
|
8069
|
+
? program.name
|
|
8070
|
+
: `${program.project ? `${program.project}-` : ''}${program.name}`)
|
|
7282
8071
|
const count = used.get(base) ?? 0
|
|
7283
8072
|
used.set(base, count + 1)
|
|
7284
8073
|
program.logName = count === 0 ? base : `${base}-${count + 1}`
|
|
@@ -7347,16 +8136,18 @@ export function buildStartSpec(program, context) {
|
|
|
7347
8136
|
? ` ${jdwpAgentArg(context.debug.port, context.debug.suspend === true)} `
|
|
7348
8137
|
: ' '
|
|
7349
8138
|
const withDebug = custom.replace(/\s*\$\{JDWP_ARGS\}\s*/g, debugArg)
|
|
8139
|
+
const customDir = context.variant === 'windows-bash' ? toMsysPath(program.dir) : program.dir
|
|
7350
8140
|
return {
|
|
7351
|
-
command: /^cd\s/.test(withDebug) ? withDebug : `cd ${quoteShell(
|
|
8141
|
+
command: /^cd\s/.test(withDebug) ? withDebug : `cd ${quoteShell(customDir)} && ${withDebug}`,
|
|
7352
8142
|
cwd: program.dir,
|
|
7353
8143
|
wrapperPath,
|
|
7354
8144
|
env: program.env,
|
|
7355
8145
|
}
|
|
7356
8146
|
}
|
|
7357
8147
|
if (program.kind === 'frontend') {
|
|
8148
|
+
const frontDir = context.variant === 'windows-bash' ? toMsysPath(program.dir) : program.dir
|
|
7358
8149
|
return {
|
|
7359
|
-
command: `cd ${quoteShell(
|
|
8150
|
+
command: `cd ${quoteShell(frontDir)} && exec ${quoteShell(program.packageManager ?? 'npm')} run ${quoteShell(program.script ?? 'dev')}`,
|
|
7360
8151
|
cwd: program.dir,
|
|
7361
8152
|
wrapperPath,
|
|
7362
8153
|
env: program.env,
|
|
@@ -7383,9 +8174,13 @@ export function buildStartSpec(program, context) {
|
|
|
7383
8174
|
const windowsBash = context.variant === 'windows-bash'
|
|
7384
8175
|
const classesDir = windowsBash ? 'target\\classes' : 'target/classes'
|
|
7385
8176
|
const classPathSep = windowsBash ? ';' : ':'
|
|
8177
|
+
// Git Bash runs on Windows but its builtins are POSIX: mkdir/cd need /c/... .
|
|
8178
|
+
// The JVM is a Windows binary, so -D paths stay in Windows spelling.
|
|
8179
|
+
const shellCspDir = windowsBash ? toMsysPath(cspDir) : cspDir
|
|
8180
|
+
const shellDir = windowsBash ? toMsysPath(program.dir) : program.dir
|
|
7386
8181
|
const command = [
|
|
7387
|
-
`mkdir -p ${quoteShell(
|
|
7388
|
-
`cd ${quoteShell(
|
|
8182
|
+
`mkdir -p ${quoteShell(shellCspDir)}`,
|
|
8183
|
+
`cd ${quoteShell(shellDir)}`,
|
|
7389
8184
|
'mvn -Pdev compile',
|
|
7390
8185
|
'mvn -Pdev dependency:build-classpath -Dmdep.includeScope=runtime -Dmdep.outputFile=target/cp.txt',
|
|
7391
8186
|
// `exec` is what makes the wrapper's child BE the JVM, so a stop TERMs the
|
|
@@ -7634,6 +8429,22 @@ export function resolveSpringArgs(program, workspace) {
|
|
|
7634
8429
|
}
|
|
7635
8430
|
|
|
7636
8431
|
/** One shell word, quoted only when it needs to be. */
|
|
8432
|
+
/**
|
|
8433
|
+
* Translate `C:\x\y` into the MSYS spelling `/c/x/y`.
|
|
8434
|
+
*
|
|
8435
|
+
* Only the Git Bash wrapper needs this: the Windows JVM still receives the
|
|
8436
|
+
* original `C:\...` paths for `-D` flags (it cannot read `/c/...`), but the
|
|
8437
|
+
* shell's own `mkdir`/`cd` must see POSIX paths or MSYS treats the drive colon
|
|
8438
|
+
* and backslashes as literal characters.
|
|
8439
|
+
* @param {string} value - a Windows or already-POSIX path.
|
|
8440
|
+
* @returns {string} MSYS path when the input looks like `X:\...`, else the input.
|
|
8441
|
+
*/
|
|
8442
|
+
export function toMsysPath(value) {
|
|
8443
|
+
const match = /^([A-Za-z]):[\\/](.*)$/.exec(String(value ?? ''))
|
|
8444
|
+
if (match === null) return String(value ?? '')
|
|
8445
|
+
return `/${match[1].toLowerCase()}/${match[2].replace(/\\/g, '/')}`
|
|
8446
|
+
}
|
|
8447
|
+
|
|
7637
8448
|
export function quoteShell(value) {
|
|
7638
8449
|
const text = String(value)
|
|
7639
8450
|
if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(text)) return text
|
|
@@ -8329,6 +9140,111 @@ export function registerAgentTools(ctx, options) {
|
|
|
8329
9140
|
}
|
|
8330
9141
|
return { sessionId, cwd: resolveCwd(ctx, sessionId) }
|
|
8331
9142
|
}
|
|
9143
|
+
// ── P4: daemon-first tools ────────────────────────────────────────────────
|
|
9144
|
+
// In daemonMode=auto the engine, the programs and the JDWP sessions belong to
|
|
9145
|
+
// risd, so a tool asks the daemon first. Anything it cannot answer — a stopped
|
|
9146
|
+
// daemon, a stale bridge, an older risd — falls back to the local plugin
|
|
9147
|
+
// implementation, which is exactly what ran before this phase.
|
|
9148
|
+
// A tool call is also a "bring it back" gesture for the daemon: if it crashed
|
|
9149
|
+
// (or the user ran `risd stop`) while dsh is still open, re-spawn it once and
|
|
9150
|
+
// keep using it instead of silently degrading to the plugin-local path. The
|
|
9151
|
+
// hint is what an agent needs when even that fails.
|
|
9152
|
+
const healDaemon = async () => {
|
|
9153
|
+
const bridge = risdBridge
|
|
9154
|
+
if (bridge === null) return null
|
|
9155
|
+
const now = Date.now()
|
|
9156
|
+
if (risdHealBlocked(now)) return null
|
|
9157
|
+
if (now - (fallbackWarnedAt.get('__heal') ?? 0) < 5000) return bridge.state
|
|
9158
|
+
fallbackWarnedAt.set('__heal', now)
|
|
9159
|
+
const ensured = await ensureRisd({ home: proxyHomeDir() }).catch(() => ({ ok: false, reason: 'spawn failed' }))
|
|
9160
|
+
if (ensured.ok !== true) {
|
|
9161
|
+
// A version mismatch is not a failed start: the same mismatched daemon is
|
|
9162
|
+
// still running, and spending breaker budget on it would stop every tool
|
|
9163
|
+
// for five minutes (review C-P2-1).
|
|
9164
|
+
if (ensured.reason === 'api-mismatch') {
|
|
9165
|
+
warnDaemonMismatch()
|
|
9166
|
+
return null
|
|
9167
|
+
}
|
|
9168
|
+
noteRisdHealFailure(ensured.reason ?? 'unknown')
|
|
9169
|
+
return null
|
|
9170
|
+
}
|
|
9171
|
+
noteRisdHealSuccess()
|
|
9172
|
+
return attachBridgeState(ensured.state, null)
|
|
9173
|
+
}
|
|
9174
|
+
const daemonStateForTools = async () => {
|
|
9175
|
+
const bridge = risdBridge
|
|
9176
|
+
if (bridge === null) return null
|
|
9177
|
+
if (bridge.state !== null) {
|
|
9178
|
+
// A daemon can die between two calls while the pointer still looks live.
|
|
9179
|
+
// Probe at most once per 5 s (health is cheap and unauthenticated) so a
|
|
9180
|
+
// half-dead daemon costs one timeout per window instead of one per tool call
|
|
9181
|
+
// (review C-P2-2); a dead one drops the pointer and falls into the heal path.
|
|
9182
|
+
if (Date.now() - (bridge.lastProbeAt ?? 0) < 5000) return bridge.state
|
|
9183
|
+
bridge.lastProbeAt = Date.now()
|
|
9184
|
+
const health = await risdHealth(bridge.state).catch(() => null)
|
|
9185
|
+
if (health !== null && health.ok === true) return bridge.state
|
|
9186
|
+
bridge.state = null
|
|
9187
|
+
bridge.degraded = true
|
|
9188
|
+
}
|
|
9189
|
+
if (bridge.pending !== null) {
|
|
9190
|
+
await Promise.race([
|
|
9191
|
+
bridge.pending,
|
|
9192
|
+
new Promise((resolve) => { const timer = setTimeout(resolve, 3000); timer.unref?.() }),
|
|
9193
|
+
])
|
|
9194
|
+
}
|
|
9195
|
+
if (bridge.state !== null) return bridge.state
|
|
9196
|
+
const healed = await healDaemon()
|
|
9197
|
+
// Silence here was the bug: the tools ran locally while the agent (and the
|
|
9198
|
+
// user) believed the daemon owned the programs/JDWP sessions (review C-P2-2).
|
|
9199
|
+
if (healed === null) warnDaemonFallback()
|
|
9200
|
+
return healed
|
|
9201
|
+
}
|
|
9202
|
+
const warnDaemonFallback = () => {
|
|
9203
|
+
const now = Date.now()
|
|
9204
|
+
if (now - (fallbackWarnedAt.get('__daemon') ?? 0) < 60_000) return
|
|
9205
|
+
fallbackWarnedAt.set('__daemon', now)
|
|
9206
|
+
try {
|
|
9207
|
+
ctx.logger?.warn?.('[dsh-ris-ide] risd 不可用,agent 工具改走插件本地实现:这样启动的程序不在 daemon 的托管范围内(停 daemon 不会停它)')
|
|
9208
|
+
} catch { /* logging is best effort */ }
|
|
9209
|
+
}
|
|
9210
|
+
const warnDaemonMismatch = () => {
|
|
9211
|
+
const now = Date.now()
|
|
9212
|
+
if (now - (fallbackWarnedAt.get('__mismatch') ?? 0) < 60_000) return
|
|
9213
|
+
fallbackWarnedAt.set('__mismatch', now)
|
|
9214
|
+
try {
|
|
9215
|
+
ctx.logger?.warn?.('[dsh-ris-ide] risd 版本与插件不一致(apiVersion 不匹配),工具改走插件本地实现;重启 dsh 会启动匹配版本的 risd')
|
|
9216
|
+
} catch { /* logging is best effort */ }
|
|
9217
|
+
}
|
|
9218
|
+
const fallbackWarnedAt = new Map()
|
|
9219
|
+
const warnFallback = (what, error) => {
|
|
9220
|
+
const now = Date.now()
|
|
9221
|
+
if (now - (fallbackWarnedAt.get(what) ?? 0) < 60_000) return
|
|
9222
|
+
fallbackWarnedAt.set(what, now)
|
|
9223
|
+
try {
|
|
9224
|
+
ctx.logger?.warn?.(`[dsh-ris-ide] ${what} 回退到插件本地实现:${describe(error)}`)
|
|
9225
|
+
} catch { /* logging is best effort */ }
|
|
9226
|
+
}
|
|
9227
|
+
// Resolve *which* program a tool meant, through the daemon's own list: in auto
|
|
9228
|
+
// mode the daemon owns the program registry, so its ids are the reference.
|
|
9229
|
+
const daemonProgramFor = async (daemon, cwd, args) => {
|
|
9230
|
+
const res = await daemonListPrograms(daemon, cwd, {})
|
|
9231
|
+
if (res.ok !== true) throw new Error(`risd /v1/programs ${res.status ?? ''} ${res.error ?? ''}`.trim())
|
|
9232
|
+
const rows = Array.isArray(res.body?.programs) ? res.body.programs : []
|
|
9233
|
+
const wantedId = typeof args?.id === 'string' && args.id !== '' ? args.id : null
|
|
9234
|
+
const wantedName = typeof args?.name === 'string' && args.name !== '' ? args.name : null
|
|
9235
|
+
if (wantedId !== null) return rows.find((row) => row.id === wantedId)
|
|
9236
|
+
if (wantedName === null) return undefined
|
|
9237
|
+
const exact = rows.find((row) => row.logName === wantedName || row.name === wantedName)
|
|
9238
|
+
if (exact !== undefined) return exact
|
|
9239
|
+
const matches = rows.filter((row) => String(row.name ?? '').includes(wantedName) || String(row.logName ?? '').includes(wantedName))
|
|
9240
|
+
return matches.length === 1 ? matches[0] : undefined
|
|
9241
|
+
}
|
|
9242
|
+
const tailFromText = (textValue, lines) => {
|
|
9243
|
+
const all = String(textValue ?? '').split('\n')
|
|
9244
|
+
if (all.length > 0 && all[all.length - 1] === '') all.pop()
|
|
9245
|
+
const count = Math.min(Math.max(Number(lines) || 80, 1), 500)
|
|
9246
|
+
return all.slice(Math.max(0, all.length - count)).join('\n')
|
|
9247
|
+
}
|
|
8332
9248
|
const text = (value) => [{ type: 'text', text: value }]
|
|
8333
9249
|
const LOOSE_OUTPUT = {
|
|
8334
9250
|
type: 'object',
|
|
@@ -8356,6 +9272,23 @@ export function registerAgentTools(ctx, options) {
|
|
|
8356
9272
|
// Plugin upgrade => refresh any skill copy this workspace installed.
|
|
8357
9273
|
kickAutoSync(cwd)
|
|
8358
9274
|
const logsDir = resolvePath(cwd, 'logs', true)
|
|
9275
|
+
const daemon = await daemonStateForTools()
|
|
9276
|
+
if (daemon !== null) {
|
|
9277
|
+
try {
|
|
9278
|
+
const res = await daemonListPrograms(daemon, cwd, { refresh: args?.refresh === true })
|
|
9279
|
+
if (res.ok !== true) throw new Error(`risd /v1/programs ${res.status ?? ''} ${res.error ?? ''}`.trim())
|
|
9280
|
+
const listed = res.body ?? {}
|
|
9281
|
+
let rows = Array.isArray(listed.programs) ? listed.programs : []
|
|
9282
|
+
if (args?.runningOnly === true) rows = rows.filter((program) => program.running?.alive === true)
|
|
9283
|
+
return jsonSafe({
|
|
9284
|
+
ok: true,
|
|
9285
|
+
root: listed.cwd ?? cwd,
|
|
9286
|
+
dir: listed.dir ?? logsDir,
|
|
9287
|
+
programs: programRows(rows),
|
|
9288
|
+
companion: detectCompanionPlugin(cwd),
|
|
9289
|
+
})
|
|
9290
|
+
} catch (error) { warnFallback('ris_dev_programs', error) }
|
|
9291
|
+
}
|
|
8359
9292
|
let programs = await scanPrograms(cwd, logsDir, args?.refresh === true)
|
|
8360
9293
|
if (args?.runningOnly === true) programs = programs.filter((program) => program.running?.alive === true)
|
|
8361
9294
|
return jsonSafe({
|
|
@@ -8388,6 +9321,21 @@ export function registerAgentTools(ctx, options) {
|
|
|
8388
9321
|
exec?.signal?.throwIfAborted?.()
|
|
8389
9322
|
const { cwd } = scopeOf(exec)
|
|
8390
9323
|
const logsDir = resolvePath(cwd, 'logs', true)
|
|
9324
|
+
const daemon = await daemonStateForTools()
|
|
9325
|
+
if (daemon !== null) {
|
|
9326
|
+
try {
|
|
9327
|
+
const remote = await daemonProgramFor(daemon, cwd, args)
|
|
9328
|
+
if (remote === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
|
|
9329
|
+
const res = await daemonProgramAction(daemon, { cwd, action: 'start', id: remote.id })
|
|
9330
|
+
if (res.ok !== true) throw new Error(`risd start ${res.status ?? ''} ${res.error ?? ''}`.trim())
|
|
9331
|
+
const body = res.body ?? {}
|
|
9332
|
+
return jsonSafe({
|
|
9333
|
+
ok: true,
|
|
9334
|
+
alreadyRunning: body.alreadyRunning === true,
|
|
9335
|
+
program: programRow(body.program ?? remote),
|
|
9336
|
+
})
|
|
9337
|
+
} catch (error) { warnFallback('ris_dev_start', error) }
|
|
9338
|
+
}
|
|
8391
9339
|
const program = resolveProgramRef(await scanPrograms(cwd, logsDir, false), args)
|
|
8392
9340
|
if (program === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
|
|
8393
9341
|
const result = await startProgram(cwd, logsDir, program, options)
|
|
@@ -8417,8 +9365,19 @@ export function registerAgentTools(ctx, options) {
|
|
|
8417
9365
|
exec?.signal?.throwIfAborted?.()
|
|
8418
9366
|
const { cwd } = scopeOf(exec)
|
|
8419
9367
|
const logsDir = resolvePath(cwd, 'logs', true)
|
|
9368
|
+
const pathAddressed = typeof args?.path === 'string' && args.path !== ''
|
|
9369
|
+
const daemon = await daemonStateForTools()
|
|
9370
|
+
if (daemon !== null && !pathAddressed) {
|
|
9371
|
+
try {
|
|
9372
|
+
const remote = await daemonProgramFor(daemon, cwd, args)
|
|
9373
|
+
if (remote === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
|
|
9374
|
+
const res = await daemonProgramAction(daemon, { cwd, action: 'stop', id: remote.id })
|
|
9375
|
+
if (res.ok !== true) throw new Error(`risd stop ${res.status ?? ''} ${res.error ?? ''}`.trim())
|
|
9376
|
+
return jsonSafe(Object.assign({ ok: true, path: res.body?.path ?? remote.logPath }, res.body ?? {}))
|
|
9377
|
+
} catch (error) { warnFallback('ris_dev_stop', error) }
|
|
9378
|
+
}
|
|
8420
9379
|
let logPath
|
|
8421
|
-
if (
|
|
9380
|
+
if (pathAddressed) {
|
|
8422
9381
|
logPath = resolvePath(cwd, args.path, options?.restrictToCwd === true)
|
|
8423
9382
|
} else {
|
|
8424
9383
|
const program = resolveProgramRef(await scanPrograms(cwd, logsDir, false), args)
|
|
@@ -8450,9 +9409,32 @@ export function registerAgentTools(ctx, options) {
|
|
|
8450
9409
|
exec?.signal?.throwIfAborted?.()
|
|
8451
9410
|
const { sessionId, cwd } = scopeOf(exec)
|
|
8452
9411
|
const logsDir = resolvePath(cwd, 'logs', true)
|
|
9412
|
+
const pathAddressed = typeof args?.path === 'string' && args.path !== ''
|
|
9413
|
+
const daemon = await daemonStateForTools()
|
|
9414
|
+
if (daemon !== null && !pathAddressed) {
|
|
9415
|
+
try {
|
|
9416
|
+
const remote = await daemonProgramFor(daemon, cwd, args)
|
|
9417
|
+
if (remote === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
|
|
9418
|
+
const res = await daemonReadProgramLog(daemon, { cwd, id: remote.id, bytes: 256 * 1024 })
|
|
9419
|
+
if (res.ok !== true) throw new Error(`risd log ${res.status ?? ''} ${res.error ?? ''}`.trim())
|
|
9420
|
+
const body = res.body ?? {}
|
|
9421
|
+
const logPath = body.path ?? remote.logPath
|
|
9422
|
+
const opened = args?.open !== false
|
|
9423
|
+
if (opened) enqueueOpen({ sessionId, cwd, logPath, title: `${remote.name} 日志` })
|
|
9424
|
+
return jsonSafe({
|
|
9425
|
+
ok: true,
|
|
9426
|
+
path: logPath,
|
|
9427
|
+
exists: body.exists !== false,
|
|
9428
|
+
running: body.running === true,
|
|
9429
|
+
opened,
|
|
9430
|
+
pid: body.pid ?? null,
|
|
9431
|
+
content: tailFromText(body.text, args?.lines),
|
|
9432
|
+
})
|
|
9433
|
+
} catch (error) { warnFallback('ris_dev_logs', error) }
|
|
9434
|
+
}
|
|
8453
9435
|
let logPath
|
|
8454
9436
|
let title
|
|
8455
|
-
if (
|
|
9437
|
+
if (pathAddressed) {
|
|
8456
9438
|
logPath = resolvePath(cwd, args.path, options?.restrictToCwd === true)
|
|
8457
9439
|
title = basename(logPath)
|
|
8458
9440
|
} else {
|
|
@@ -8541,6 +9523,23 @@ export function registerAgentTools(ctx, options) {
|
|
|
8541
9523
|
exec?.signal?.throwIfAborted?.()
|
|
8542
9524
|
const { cwd } = scopeOf(exec)
|
|
8543
9525
|
const logsDir = resolvePath(cwd, 'logs', true)
|
|
9526
|
+
const daemon = await daemonStateForTools()
|
|
9527
|
+
if (daemon !== null) {
|
|
9528
|
+
try {
|
|
9529
|
+
const remote = await daemonProgramFor(daemon, cwd, args)
|
|
9530
|
+
if (remote === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
|
|
9531
|
+
const res = await daemonProgramAction(daemon, { cwd, action: 'restart', id: remote.id })
|
|
9532
|
+
if (res.ok !== true) throw new Error(`risd restart ${res.status ?? ''} ${res.error ?? ''}`.trim())
|
|
9533
|
+
const body = res.body ?? {}
|
|
9534
|
+
return jsonSafe({
|
|
9535
|
+
ok: true,
|
|
9536
|
+
restarted: body.restarted === true,
|
|
9537
|
+
stopped: body.stopped ?? null,
|
|
9538
|
+
alreadyRunning: body.alreadyRunning === true,
|
|
9539
|
+
program: programRow(body.program ?? remote),
|
|
9540
|
+
})
|
|
9541
|
+
} catch (error) { warnFallback('ris_dev_restart', error) }
|
|
9542
|
+
}
|
|
8544
9543
|
const program = resolveProgramRef(await scanPrograms(cwd, logsDir, false), args)
|
|
8545
9544
|
if (program === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
|
|
8546
9545
|
if (program.kind === 'instance') throw new TailError('not-startable', 'this row is a log of an instance started outside the panel', 400)
|
|
@@ -8615,6 +9614,63 @@ export function registerAgentTools(ctx, options) {
|
|
|
8615
9614
|
}
|
|
8616
9615
|
return (await findProgram()).logPath
|
|
8617
9616
|
}
|
|
9617
|
+
// P4: in auto mode the JDWP session lives in risd. Forward everything the
|
|
9618
|
+
// daemon owns — "open" is UI-only and stays here, and a path-addressed call
|
|
9619
|
+
// keeps the local session (the daemon resolves programs by id).
|
|
9620
|
+
const daemon = await daemonStateForTools()
|
|
9621
|
+
const pathAddressed = typeof args?.path === 'string' && args.path !== ''
|
|
9622
|
+
if (daemon !== null && action !== 'open' && !pathAddressed) {
|
|
9623
|
+
if (action === 'state') {
|
|
9624
|
+
try {
|
|
9625
|
+
const program = await daemonProgramFor(daemon, cwd, args)
|
|
9626
|
+
if (program === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
|
|
9627
|
+
const statusRes = await daemonDebugAction(daemon, { action: 'status', cwd, id: program.id, sessionId })
|
|
9628
|
+
if (statusRes.ok !== true) throw new Error(`risd debug ${statusRes.status ?? ''} ${statusRes.error ?? ''}`.trim())
|
|
9629
|
+
const statusBody = statusRes.body ?? {}
|
|
9630
|
+
const breakpointsRes = await daemonDebugAction(daemon, { action: 'breakpoints', cwd, id: program.id, sessionId })
|
|
9631
|
+
const breakpointsBody = breakpointsRes.ok === true ? (breakpointsRes.body ?? {}) : {}
|
|
9632
|
+
const pending = statusBody?.pendingBreakpoints ?? statusBody?.pending ?? 0
|
|
9633
|
+
return jsonSafe({
|
|
9634
|
+
ok: true,
|
|
9635
|
+
program: programRow(program),
|
|
9636
|
+
running: program.running ?? null,
|
|
9637
|
+
debuggable: program.kind === 'spring',
|
|
9638
|
+
debug: statusBody,
|
|
9639
|
+
breakpoints: breakpointsBody?.breakpoints ?? [],
|
|
9640
|
+
pendingBreakpoints: typeof pending === 'number' ? pending : 0,
|
|
9641
|
+
})
|
|
9642
|
+
} catch (error) { warnFallback('ris_dev_debug', error) }
|
|
9643
|
+
}
|
|
9644
|
+
const mapped = {
|
|
9645
|
+
start: 'start', stop: 'detach', status: 'status', poll: 'events',
|
|
9646
|
+
breakpoints: 'breakpoints', breakpoint_add: 'breakpoint-add',
|
|
9647
|
+
breakpoint_remove: 'breakpoint-remove', breakpoint_clear: 'breakpoint-clear',
|
|
9648
|
+
threads: 'threads', stack: 'stack', variables: 'variables',
|
|
9649
|
+
step: 'step', resume: 'resume', pause: 'pause',
|
|
9650
|
+
}[action]
|
|
9651
|
+
if (mapped !== undefined) {
|
|
9652
|
+
try {
|
|
9653
|
+
const program = await daemonProgramFor(daemon, cwd, args)
|
|
9654
|
+
if (program === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
|
|
9655
|
+
const res = await daemonDebugAction(daemon, Object.assign({
|
|
9656
|
+
action: mapped, cwd, id: program.id, sessionId,
|
|
9657
|
+
}, {
|
|
9658
|
+
className: args?.className,
|
|
9659
|
+
line: args?.line,
|
|
9660
|
+
suspendPolicy: args?.suspendPolicy,
|
|
9661
|
+
requestId: args?.requestId,
|
|
9662
|
+
threadId: args?.threadId,
|
|
9663
|
+
frameIndex: args?.frameIndex,
|
|
9664
|
+
max: args?.max,
|
|
9665
|
+
kind: args?.kind,
|
|
9666
|
+
since: args?.since,
|
|
9667
|
+
suspend: args?.suspend,
|
|
9668
|
+
}))
|
|
9669
|
+
if (res.ok !== true) throw new Error(`risd debug ${res.status ?? ''} ${res.error ?? ''}`.trim())
|
|
9670
|
+
return jsonSafe(Object.assign({ ok: true }, res.body ?? {}))
|
|
9671
|
+
} catch (error) { warnFallback('ris_dev_debug', error) }
|
|
9672
|
+
}
|
|
9673
|
+
}
|
|
8618
9674
|
try {
|
|
8619
9675
|
if (action === 'state') {
|
|
8620
9676
|
// One call that answers "can I debug this, and from what?" before anything
|
|
@@ -9062,13 +10118,21 @@ function renderLogs(value) {
|
|
|
9062
10118
|
|
|
9063
10119
|
/** Test-only surface: the pure pieces, exercised without a live profile. */
|
|
9064
10120
|
export const __test = {
|
|
10121
|
+
// P4 tests: pretend the plugin is attached to a daemon without booting one.
|
|
10122
|
+
setRisdBridge: (bridge) => { risdBridge = bridge },
|
|
9065
10123
|
resolvePath,
|
|
10124
|
+
refreshDshWindows,
|
|
9066
10125
|
detectCompanionPlugin,
|
|
9067
10126
|
renderProgramList,
|
|
9068
10127
|
windowsProgramNames,
|
|
9069
10128
|
resetWindowsProgramCache,
|
|
9070
10129
|
// Proxy rules + engine (the dialog's three routes).
|
|
9071
10130
|
PROXY_PATH,
|
|
10131
|
+
RISD_ENSURE_PATH,
|
|
10132
|
+
risdHealBlocked,
|
|
10133
|
+
risdHealReason,
|
|
10134
|
+
noteRisdHealFailure,
|
|
10135
|
+
noteRisdHealSuccess,
|
|
9072
10136
|
PROXY_ACTION_PATH,
|
|
9073
10137
|
buildProfile,
|
|
9074
10138
|
PROXY_PROGRAMS_PATH,
|
|
@@ -9082,6 +10146,10 @@ export const __test = {
|
|
|
9082
10146
|
// Process-wide child-service lifecycle (exit hook + heartbeat + janitor), and the
|
|
9083
10147
|
// adoption of an engine left behind by a previous dsh process.
|
|
9084
10148
|
ensureLifecycle,
|
|
10149
|
+
armLocalProxyCleanup,
|
|
10150
|
+
disarmLocalProxyCleanup,
|
|
10151
|
+
isBashDialectCommand,
|
|
10152
|
+
startHeartbeat,
|
|
9085
10153
|
adoptLeftoverEngine,
|
|
9086
10154
|
decorateProxyRule,
|
|
9087
10155
|
// The bundled skill + its installer (idempotent, target-aware).
|
|
@@ -9242,6 +10310,7 @@ export const __test = {
|
|
|
9242
10310
|
windowsCommandLine,
|
|
9243
10311
|
taskkillTree,
|
|
9244
10312
|
windowsStartSpec,
|
|
10313
|
+
toMsysPath,
|
|
9245
10314
|
logUrl,
|
|
9246
10315
|
logStatus,
|
|
9247
10316
|
programStatus,
|