dsh-ris-ide 1.8.1 → 1.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +2 -2
  2. package/lib/client.js +311 -72
  3. package/lib/debug/vendor/README.md +14 -0
  4. package/lib/debug/vendor/jdwp/client.js +9 -4
  5. package/lib/debug/vendor/src/jdwp/client.ts +12 -5
  6. package/lib/index.js +794 -48
  7. package/lib/redirector.js +42 -2
  8. package/lib/risd/lifecycle.js +9 -3
  9. package/lib/risd/server.js +308 -13
  10. package/lib/risd/ui.js +149 -112
  11. package/lib/risd-client.js +4 -1
  12. package/lib/startup.js +27 -7
  13. package/package.json +2 -2
  14. package/test/client-viewer.test.mjs +188 -95
  15. package/test/clipboard.test.mjs +259 -0
  16. package/test/debug-engine.test.mjs +3 -1
  17. package/test/dsh-origin.test.mjs +4 -11
  18. package/test/dsh-window-refresh.test.mjs +166 -1
  19. package/test/harness.test.mjs +1 -1
  20. package/test/helpers/cmd.mjs +29 -0
  21. package/test/helpers/tgz.mjs +71 -0
  22. package/test/host-search.test.mjs +18 -11
  23. package/test/host-tail.test.mjs +119 -24
  24. package/test/proxy-route.test.mjs +61 -0
  25. package/test/proxy-window.test.mjs +5 -0
  26. package/test/proxy.test.mjs +13 -1
  27. package/test/proxybridge-bundle.test.mjs +1 -59
  28. package/test/redirector-bundle.test.mjs +21 -67
  29. package/test/redirector.test.mjs +41 -4
  30. package/test/risd-api.test.mjs +81 -28
  31. package/test/risd-bridge-degrade.test.mjs +3 -29
  32. package/test/risd-engine.test.mjs +13 -50
  33. package/test/risd-entry.test.mjs +0 -37
  34. package/test/risd-follow-start.test.mjs +101 -0
  35. package/test/risd-git.test.mjs +7 -5
  36. package/test/risd-handoff.test.mjs +6 -50
  37. package/test/risd-helpers.mjs +150 -3
  38. package/test/risd-host-p2.test.mjs +2 -30
  39. package/test/risd-lifecycle.test.mjs +25 -0
  40. package/test/risd-programs.test.mjs +4 -34
  41. package/test/risd-review-p2.test.mjs +0 -13
  42. package/test/risd-shutdown.test.mjs +5 -38
  43. package/test/risd-teardown.test.mjs +8 -27
  44. package/test/risd-ui.test.mjs +169 -13
  45. package/test/risd-write.test.mjs +2 -1
  46. package/test/startup-reconcile.test.mjs +44 -8
  47. package/test/proxy-restart.test.mjs +0 -39
package/lib/redirector.js CHANGED
@@ -58,6 +58,17 @@ export const REDIRECTOR_PID_FILENAMES = Object.freeze({
58
58
  export const REDIRECTOR_LOG_FILENAME = 'proxybridge.log'
59
59
  /** Substring of the redirector's command line, used to verify a pid is ours. */
60
60
  export const REDIRECTOR_MARKER = 'ProxyBridge'
61
+
62
+ /**
63
+ * Test seam for `windowsPathOf` (not a product feature).
64
+ *
65
+ * A host that is not WSL has no `wslpath` and no Windows side, so the Windows
66
+ * spelling of a Linux path cannot be computed there at all — and the tests that
67
+ * assert the shape of that spelling could only ever run on a WSL machine. The
68
+ * seam lets them inject the mapping instead, so CI (plain Linux) keeps the
69
+ * coverage; production leaves it `null` and always asks `wslpath`.
70
+ */
71
+ let windowsPathTranslator = null
61
72
  /** Profile rules are per-connection decisions, so TCP+UDP is the useful default. */
62
73
  const PROFILE_VERSION = '1.0'
63
74
 
@@ -2072,7 +2083,7 @@ export async function killWindowsCliProcesses(options = {}) {
2072
2083
  * On Windows the launch itself elevates (UAC), so the command is the exe; on Linux
2073
2084
  * the whole thing is a `sudo`. In WSL the Windows command must be translated: a
2074
2085
  * `/mnt/...` path does not exist in the Windows namespace.
2075
- * @param {{cliPath: string, profilePath: string, verbose?: number, platform?: string}} options - inputs.
2086
+ * @param {{cliPath: string, profilePath: string, verbose?: number, platform?: string, translate?: boolean}} options - inputs. `translate` overrides "may this machine spell paths the Windows way" (defaults to `platform === 'win32' && engineSide() === 'wsl'`); tests on a plain-Linux host pass `true`.
2076
2087
  * @returns {{command: string, args: string[], display: string, needsElevation: boolean}} runnable plan.
2077
2088
  */
2078
2089
  export function redirectorCommand(options = {}) {
@@ -2082,7 +2093,9 @@ export function redirectorCommand(options = {}) {
2082
2093
  // one look the same — the exact ambiguity that cost us an hour of guessing.
2083
2094
  const verbose = Number.isInteger(options.verbose) ? options.verbose : 2
2084
2095
  const args = ['--profile', String(options.profilePath ?? ''), '--verbose', String(verbose)]
2085
- const translate = platform === 'win32' && engineSide() === 'wsl'
2096
+ const translate = typeof options.translate === 'boolean'
2097
+ ? options.translate
2098
+ : platform === 'win32' && engineSide() === 'wsl'
2086
2099
  const exe = translate ? windowsPathOf(String(options.cliPath ?? '')) : String(options.cliPath ?? '')
2087
2100
  const shownArgs = translate ? windowsArgsOf(args) : args
2088
2101
  const quote = (value) => (/[ \t]/.test(value) === true ? `"${value}"` : value)
@@ -2653,6 +2666,7 @@ export function clearRedirectorPid(side) {
2653
2666
  * @returns {{pid: number, source: string, side: string, local: {pid: number, source: string}, windows: {pid: number, source: string}}} discovery result; `pid` is the first live hit.
2654
2667
  */
2655
2668
  export function detectRunningRedirector() {
2669
+ if (probesStubbed()) return emptyDetection()
2656
2670
  migrateLegacyPidFile()
2657
2671
  const local = detectSide('local')
2658
2672
  const windows = detectSide('windows')
@@ -2666,6 +2680,26 @@ export function detectRunningRedirector() {
2666
2680
  }
2667
2681
  }
2668
2682
 
2683
+ /**
2684
+ * Is the machine-probing test stub switched on?
2685
+ *
2686
+ * `__test.setProbeHooks` only reaches this process, but the risd tests run the
2687
+ * daemon as a CHILD process, and its save path calls `redirectorStatusCached()`
2688
+ * after every write. Two cold PowerShell probes cost ~8 s on WSL, so each save in
2689
+ * those files waited for an answer that the test must not depend on (whether the
2690
+ * developer's own ProxyBridge happens to be running) — and adoption could even
2691
+ * stomp the real pidfiles. The child inherits `DSH_RIS_IDE_STUB_PROBES=1` from
2692
+ * `test/risd-helpers.mjs`; production never sets it.
2693
+ */
2694
+ function probesStubbed() {
2695
+ return process.env.DSH_RIS_IDE_STUB_PROBES === '1'
2696
+ }
2697
+
2698
+ /** The "nothing is running" shape both stubbed detectors return. */
2699
+ function emptyDetection() {
2700
+ return { pid: 0, source: '', side: '', local: { pid: 0, source: '' }, windows: { pid: 0, source: '' } }
2701
+ }
2702
+
2669
2703
  /** @returns {object|null} discovery hit for one side. */
2670
2704
  function detectSide(side) {
2671
2705
  const record = redirectorPidRecord(side)
@@ -2690,6 +2724,7 @@ function detectSide(side) {
2690
2724
 
2691
2725
  /** Async variant of {@link detectRunningRedirector}: safe to call from HTTP routes. */
2692
2726
  export async function detectRunningRedirectorAsync() {
2727
+ if (probesStubbed()) return emptyDetection()
2693
2728
  migrateLegacyPidFile()
2694
2729
  const record = redirectorPidRecord('local')
2695
2730
  const local = record.pid > 0 && await pidAliveOnAsync(record.pid, 'local')
@@ -3490,6 +3525,10 @@ export function windowsPathOf(path, options = {}) {
3490
3525
  // answer with a \\wsl.localhost\… share that Windows cannot open).
3491
3526
  const mounted = /^\/mnt\/([A-Za-z])\/(.*)$/.exec(text)
3492
3527
  if (mounted !== null) return `${mounted[1].toUpperCase()}:\\${mounted[2].replace(/\//g, '\\')}`
3528
+ if (windowsPathTranslator !== null) {
3529
+ const injected = windowsPathTranslator(text)
3530
+ if (typeof injected === 'string' && injected !== '') return injected
3531
+ }
3493
3532
  const converted = spawnSyncText('wslpath', ['-w', text], 4000).trim()
3494
3533
  if (converted !== '' && /^[A-Za-z]:[\\/]|^\\\\/.test(converted)) return converted
3495
3534
  if (options.mustConvert === true) {
@@ -3527,6 +3566,7 @@ function spawnSyncText(command, args, timeoutMs) {
3527
3566
 
3528
3567
  export const __test = {
3529
3568
  PROFILE_VERSION,
3569
+ setWindowsPathTranslator: (fn) => { windowsPathTranslator = typeof fn === 'function' ? fn : null },
3530
3570
  bundledBundleDir,
3531
3571
  bundleCacheInstalled,
3532
3572
  ensureBundleReady,
@@ -7,6 +7,11 @@
7
7
  // proxy follows dsh (its lease keeps the tunnel alive) and programs/debug keep
8
8
  // running when the last dsh window closes, because the maintenance page can be the
9
9
  // only UI on the machine.
10
+ //
11
+ // Following dsh is two-sided: with `proxy.followDsh` on, the engine starts when a
12
+ // dsh attaches and the tunnel is torn down when the last one leaves. The start half
13
+ // is never an elevation request — an automatic start must not pop a password dialog
14
+ // (m13910) — so a bridge that needs root is only reported on the page.
10
15
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
11
16
  import { join } from 'node:path'
12
17
 
@@ -16,7 +21,7 @@ export const LIFECYCLE_FILENAME = 'risd-lifecycle.json'
16
21
  /** The four resources the page lets you tune, in page order. */
17
22
  export const LIFECYCLE_RESOURCES = ['daemon', 'proxy', 'programs', 'debug']
18
23
 
19
- /** Defaults: only `followDsh` exists; following the daemon is always on. */
24
+ /** Defaults: everything follows dsh except programs/debug, which outlive the window. */
20
25
  export const LIFECYCLE_DEFAULTS = {
21
26
  daemon: { followDsh: true },
22
27
  proxy: { followDsh: true },
@@ -60,10 +65,11 @@ export function normalizeLifecycle(input) {
60
65
  value[resource] = Object.assign({}, defaults)
61
66
  continue
62
67
  }
68
+ const allowed = Object.keys(defaults)
63
69
  for (const key of Object.keys(given)) {
64
- if (key === 'followDsh' || FORCED_KEYS.includes(key)) continue
70
+ if (allowed.includes(key) || FORCED_KEYS.includes(key)) continue
65
71
  // Silently ignoring an unknown key made a typo look saved (review A2-P2-5).
66
- errors.push(`${resource}.${key} 不是可配置项(只能配置 followDsh)`)
72
+ errors.push(`${resource}.${key} 不是可配置项(只能配置 ${allowed.join('/')})`)
67
73
  }
68
74
  for (const key of FORCED_KEYS) {
69
75
  if (given[key] !== undefined) {
@@ -16,7 +16,8 @@
16
16
  */
17
17
  import { spawn } from 'node:child_process'
18
18
  import { createServer, request } from 'node:http'
19
- import { existsSync, readFileSync, statSync } from 'node:fs'
19
+ import { request as httpsRequest } from 'node:https'
20
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
20
21
  import { isAbsolute, join, win32 } from 'node:path'
21
22
  import { timingSafeEqual } from 'node:crypto'
22
23
  import { fileURLToPath } from 'node:url'
@@ -31,6 +32,7 @@ import * as bundleApi from '../proxybridge-bundle.js'
31
32
  import { armJanitor, disarmJanitor, janitorStatus, markJanitorHandoff } from '../janitor.js'
32
33
  import { bundledBundleDir, posixToWindowsPath, readElevationState, REDIRECTOR_PID_FILENAMES, REDIRECTOR_PID_FILENAME, redirectorCommand, redirectorHome, redirectorProfilePath, redirectorStatusAsync, redirectorStatusCached, reloadRedirectorsWithProfile, startRedirectors, stopRedirector, windowsBundleDir, writeHeartbeat } from '../redirector.js'
33
34
  import { risdConfigRevision, risdProxyView } from './view.js'
35
+ import { buildProfile } from '../redirector.js'
34
36
  import { clearGitProxy, readGitProxyState, reconcileGitProxy, syncGitProxy } from './git.js'
35
37
  import { findProgram, listPrograms, readProgramLog, restartProgramByKey, startLogFollow, startProgramByKey, stopProgramByKey } from './programs.js'
36
38
  import { reconcileStartupLeftovers } from '../startup.js'
@@ -61,6 +63,10 @@ const DSH_WINDOW_LIVE_MS = 5 * 60_000
61
63
  /** Remembered windows older than this are pruned; between the two they show as
62
64
  * "未活跃" but stay selectable (m08268: clicking one may still open the IDE). */
63
65
  const DSH_WINDOW_RETAIN_MS = 7 * 24 * 60 * 60_000
66
+ /** Cap on the sidebar mirror: a machine with hundreds of workspaces must not make the
67
+ * page huge (the plugin caps its own snapshot at DSH_WINDOW_MAX_WORKSPACES = 50). */
68
+ const DSH_WORKSPACES_MAX = 100
69
+
64
70
 
65
71
  /** The daemon's own page is only for the local browser (no DNS rebinding). */
66
72
  export function isLoopbackHost(req) {
@@ -82,6 +88,165 @@ export function isLoopbackOrigin(origin) {
82
88
  }
83
89
  }
84
90
 
91
+ /** How long one direct sidebar probe may take before that candidate is skipped. */
92
+ const DSH_PROBE_TIMEOUT_MS = 600
93
+ /** Cap on the hosts probed for one answer: a few live dsh instances, not a scan. */
94
+ const DSH_PROBE_MAX_CANDIDATES = 4
95
+ /** Where each running plugin advertises its own origin (one file per pid). */
96
+ const DSH_INSTANCE_DIRNAME = 'instances'
97
+
98
+ /**
99
+ * Turn a sidebar snapshot into panel rows. Sidebar order is the user's order, so the
100
+ * panel order is the sidebar order; a workspace is identified by its PATH (a rename
101
+ * keeps the path and changes only the label), and a matching remembered window
102
+ * supplies that workspace's origin, sessionId and liveness.
103
+ * @param {Array} sidebar - workspace entries (document or direct probe).
104
+ * @param {Array} windows - remembered windows, already filtered and sorted.
105
+ * @param {string} origin - loopback origin to embed a workspace nobody opened.
106
+ * @returns {Array} rows, possibly empty.
107
+ */
108
+ function dshSidebarRows(sidebar, windows, origin) {
109
+ const rows = []
110
+ const remembered = new Map(windows.map((row) => [row.cwd, row]))
111
+ const seen = new Set()
112
+ for (const entry of sidebar) {
113
+ if (rows.length >= DSH_WORKSPACES_MAX) break
114
+ if (entry === null || typeof entry !== 'object') continue
115
+ const cwd = typeof entry.cwd === 'string' && isAbsolute(entry.cwd) ? entry.cwd : ''
116
+ if (cwd === '' || seen.has(cwd)) continue
117
+ seen.add(cwd)
118
+ const window = remembered.get(cwd)
119
+ if (window !== undefined) remembered.delete(cwd)
120
+ const title = typeof entry.title === 'string' ? entry.title : ''
121
+ const sessionId = typeof entry.sessionId === 'string' && entry.sessionId !== ''
122
+ ? entry.sessionId
123
+ : (window === undefined ? '' : window.sessionId)
124
+ rows.push({
125
+ cwd,
126
+ title: title !== '' ? title : (window === undefined ? '' : window.title),
127
+ sessionId,
128
+ url: window === undefined ? origin : window.url,
129
+ // A listed workspace is reachable even when nobody opened the IDE for it: it is
130
+ // not a remembered window, so it gets no "未活跃" label and no TTL of its own —
131
+ // the snapshot's freshness is the gate.
132
+ ageMs: window === undefined ? DSH_WINDOW_RETAIN_MS : window.ageMs,
133
+ live: window === undefined ? true : window.live,
134
+ // Whether the workspace has a live session right now; the page only hints with
135
+ // it, the row stays selectable either way (m00186).
136
+ ...(typeof entry.active === 'boolean' ? { active: entry.active } : {}),
137
+ ...(window === undefined ? { source: 'workspace' } : {}),
138
+ })
139
+ }
140
+ // Remembered windows whose workspace has left the sidebar still open: the user may
141
+ // be mid-session there, so they stay listed (as 未活跃 once stale).
142
+ for (const window of remembered.values()) rows.push(window)
143
+ return rows
144
+ }
145
+
146
+ /**
147
+ * Loopback origins worth asking for a snapshot (m00186): the shared document's
148
+ * origin, every remembered window's origin, then the per-pid instance files (newest
149
+ * first). Only an instance file younger than the live window names a live process.
150
+ * @param {string} home - daemon home (holds `dsh-window.json` and `instances/`).
151
+ * @param {number} now - epoch ms.
152
+ * @param {string} documentOrigin - origin the shared document advertises.
153
+ * @param {Array} windows - usable remembered windows.
154
+ * @returns {string[]} distinct loopback origins, capped.
155
+ */
156
+ function dshProbeCandidates(home, now, documentOrigin, windows) {
157
+ const candidates = []
158
+ const seen = new Set()
159
+ const push = (origin) => {
160
+ if (typeof origin !== 'string' || origin === '' || !isLoopbackOrigin(origin)) return
161
+ if (seen.has(origin) || candidates.length >= DSH_PROBE_MAX_CANDIDATES) return
162
+ seen.add(origin)
163
+ candidates.push(origin)
164
+ }
165
+ push(documentOrigin)
166
+ for (const row of windows) push(row.url)
167
+ const advertised = []
168
+ let names = []
169
+ try {
170
+ names = readdirSync(join(home, DSH_INSTANCE_DIRNAME))
171
+ } catch { /* older plugin: no instance files */ }
172
+ for (const name of names) {
173
+ if (!/^dsh-\d+\.json$/.test(name)) continue
174
+ try {
175
+ const parsed = JSON.parse(readFileSync(join(home, DSH_INSTANCE_DIRNAME, name), 'utf8'))
176
+ const at = Date.parse(String(parsed?.at ?? ''))
177
+ // A file from a dead process (or a reused pid) must not be probed; a timestamp
178
+ // far in the future is junk for the same reason as in the window rows.
179
+ if (!Number.isFinite(at) || now - at > DSH_WINDOW_LIVE_MS || at > now + 5 * 60_000) continue
180
+ advertised.push({ url: parsed?.url, at })
181
+ } catch { /* half-written file: not a candidate */ }
182
+ }
183
+ advertised.sort((a, b) => b.at - a.at)
184
+ for (const row of advertised) push(row.url)
185
+ return candidates
186
+ }
187
+
188
+ /**
189
+ * Ask one live dsh for `GET /dsh-ris-ide/workspaces` (m00186). Never throws and never
190
+ * blocks longer than the probe timeout: a dead candidate is just a `null`.
191
+ * @param {string} origin - loopback http(s) origin.
192
+ * @returns {Promise<object|null>} the plugin's answer, or null.
193
+ */
194
+ function probeDshWorkspaces(origin) {
195
+ return new Promise((resolveProbe) => {
196
+ let target
197
+ try {
198
+ target = new URL('/dsh-ris-ide/workspaces', origin)
199
+ } catch {
200
+ resolveProbe(null)
201
+ return
202
+ }
203
+ let settled = false
204
+ const finish = (value) => {
205
+ if (settled) return
206
+ settled = true
207
+ resolveProbe(value)
208
+ }
209
+ const client = target.protocol === 'https:' ? httpsRequest : request
210
+ const probe = client(target, {
211
+ method: 'GET',
212
+ timeout: DSH_PROBE_TIMEOUT_MS,
213
+ // dsh may serve TLS with a certificate this machine signed itself; the origin
214
+ // came from our own state files, not from the network, so trust it here.
215
+ ...(target.protocol === 'https:' ? { rejectUnauthorized: false } : {}),
216
+ }, (response) => {
217
+ if (response.statusCode !== 200) {
218
+ response.resume()
219
+ finish(null)
220
+ return
221
+ }
222
+ let body = ''
223
+ response.setEncoding('utf8')
224
+ response.on('data', (chunk) => {
225
+ if (body.length > 512 * 1024) {
226
+ probe.destroy()
227
+ finish(null)
228
+ return
229
+ }
230
+ body += chunk
231
+ })
232
+ response.on('end', () => {
233
+ try {
234
+ finish(JSON.parse(body))
235
+ } catch {
236
+ finish(null)
237
+ }
238
+ })
239
+ response.on('error', () => finish(null))
240
+ })
241
+ probe.on('timeout', () => {
242
+ probe.destroy()
243
+ finish(null)
244
+ })
245
+ probe.on('error', () => finish(null))
246
+ probe.end()
247
+ })
248
+ }
249
+
85
250
  function json(res, status, payload) {
86
251
  const body = `${JSON.stringify(payload)}\n`
87
252
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(body) })
@@ -508,14 +673,26 @@ export async function startRisd({ home, port = DEFAULT_RISD_PORT, version = '0.0
508
673
  try { await stopProxy(cwd) } catch { /* best effort */ }
509
674
  }
510
675
  }
676
+ // Promise of the in-flight 「跟随 dsh」 start (null when idle). Declared here because
677
+ // scheduleTeardown reads it; the start half is defined further down, next to the
678
+ // engine helpers.
679
+ let followStarting = null
511
680
  function scheduleTeardown() {
512
681
  if (leases.count() > 0) return
513
- if (engineCwd === null && heartbeat === null) return
682
+ // A start triggered by the lease that just left may still be in flight; its
683
+ // finally re-schedules teardown once engineCwd is known.
684
+ if (engineCwd === null && heartbeat === null && followStarting === null) return
514
685
  if (teardownTimer !== null) return
515
686
  teardownTimer = setTimeout(() => {
516
687
  teardownTimer = null
517
688
  void (async () => {
518
689
  if (leases.count() > 0) return // someone came back
690
+ // Let a pending start land first: tearing down with engineCwd still null
691
+ // would skip stopProxy and leave an orphan engine nobody owns (m13960).
692
+ if (followStarting !== null) {
693
+ await followStarting.catch(() => {})
694
+ if (leases.count() > 0) return
695
+ }
519
696
  // Per-resource policy: "follow dsh" stops it with the last window; the
520
697
  // daemon-owned ones stay until the daemon itself stops (or forever).
521
698
  if (lifecycle.debug.followDsh === true) await debug.stopAll().catch(() => {})
@@ -653,6 +830,51 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
653
830
  engineOp = run.then(() => undefined, () => undefined)
654
831
  return run
655
832
  }
833
+ // 「代理引擎跟随 dsh」的启动半边(m13950):与拆除共用**租约**这一条链路——
834
+ // 拆除看 leases.count() 归零,启动看第一份租约到达,两边读同一个
835
+ // lifecycle.proxy.followDsh,所以不会出现「启动跟了、停止没跟」的错位。
836
+ // 自动启动永不 interactive:dsh 接入的副作用不许弹密码框(m13910),需要 root
837
+ // 的桥接只在页面组件卡里提示。失败被吞掉并留给页面,那里还有显式按钮。
838
+ function followStartForLease(cwd) {
839
+ if (lifecycle.proxy.followDsh !== true) return Promise.resolve({ action: 'skipped', reason: 'not-following-dsh' })
840
+ if (followStarting !== null) return Promise.resolve({ action: 'skipped', reason: 'starting' })
841
+ if (engineSummary().state === 'running') return Promise.resolve({ action: 'skipped', reason: 'running' })
842
+ // The in-flight promise stays reachable: teardown must be able to wait for a
843
+ // start that the departing lease itself kicked off (see scheduleTeardown).
844
+ const work = (async () => {
845
+ // The lease may have left between the signal and this line (window closed
846
+ // during the round-trip): do not spawn an engine for nobody.
847
+ if (leases.count() === 0) return { action: 'skipped', reason: 'no-lease' }
848
+ const where = typeof cwd === 'string' && isAbsolute(cwd) && existsSync(cwd) ? cwd : home
849
+ const status = await proxyStatus(where)
850
+ // No actionable row means the engine would listen for nobody: following dsh is
851
+ // a policy, not a reason to spawn a process.
852
+ if (buildProfile(status.config).rules.length === 0) return { action: 'skipped', reason: 'no-rules' }
853
+ if (leases.count() === 0) return { action: 'skipped', reason: 'no-lease' }
854
+ const result = await serializeEngine(async () => {
855
+ const engine = await startProxy(where)
856
+ const redirector = await serializeBridge(() => startRedirectors({ interactive: false }))
857
+ noteBridgeStart(redirector)
858
+ if (redirector.running === true || (Array.isArray(redirector.started) && redirector.started.length > 0)) {
859
+ bridgeReloadState = { at: Date.now(), ok: true, note: '' }
860
+ }
861
+ const git = await syncGitProxy({ cwd: where, enabled: true })
862
+ if (engine.ok === true) {
863
+ engineCwd = where
864
+ cancelIdleExit()
865
+ }
866
+ return Object.assign({}, engine, { redirector, git })
867
+ })
868
+ return { action: result.ok === true ? 'started' : 'failed', result }
869
+ })()
870
+ followStarting = work.finally(() => {
871
+ followStarting = null
872
+ // The lease that started this may already be gone: let the teardown path run
873
+ // now that engineCwd is known (it skips while a start is pending).
874
+ if (leases.count() === 0) scheduleTeardown()
875
+ })
876
+ return followStarting
877
+ }
656
878
  // Program start/stop share one queue so two clicks cannot spawn the same row twice.
657
879
  let programOp = Promise.resolve()
658
880
  // Bridge (ProxyBridge) operations are serialized too (E8): a rule reload and a
@@ -760,13 +982,21 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
760
982
  }
761
983
 
762
984
  if (path === '/v1/dsh' && method === 'GET') {
763
- // Which workspaces have a live dsh window? The plugin keeps dsh-window.json
764
- // as an upserted list (origin + sessionId per workspace), so one daemon page
765
- // can switch between workspaces' IDE instead of opening one page per cwd.
985
+ // What should the page's workspace panel list, and what is each one called?
986
+ // The plugin keeps dsh-window.json as an upserted list (origin + sessionId per
987
+ // workspace) AND, since m13800, the sidebar's workspace list with its titles
988
+ // (title is what a rename changes; the path never moves). Both halves are read
989
+ // here so the panel mirrors the dsh sidebar instead of guessing from folders.
766
990
  let windows = []
991
+ let sidebar = []
992
+ let documentOrigin = ''
993
+ let documentAt = Number.NaN
767
994
  try {
768
995
  const parsed = JSON.parse(readFileSync(join(home, DSH_WINDOW_FILENAME), 'utf8'))
769
996
  if (Array.isArray(parsed?.windows)) windows = parsed.windows
997
+ if (Array.isArray(parsed?.workspaces)) sidebar = parsed.workspaces
998
+ if (typeof parsed?.url === 'string') documentOrigin = parsed.url
999
+ documentAt = Date.parse(String(parsed?.at ?? ''))
770
1000
  } catch { /* absent or rotated away: no dsh */ }
771
1001
  const now = Date.now()
772
1002
  let droppedAt = 0
@@ -775,7 +1005,7 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
775
1005
  // The page hands this URL to window.open(); anything but a loopback
776
1006
  // http(s) origin would let a crafted dsh-window.json point the IDE tab
777
1007
  // somewhere else (review A-P2-10).
778
- .filter((row) => /^https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?(?:\/|$)/i.test(row.url))
1008
+ .filter((row) => isLoopbackOrigin(row.url))
779
1009
  .map((row) => {
780
1010
  const at = Date.parse(String(row.at ?? ''))
781
1011
  // A timestamp far in the future made `now - at` clamp to 0, so the row
@@ -791,6 +1021,10 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
791
1021
  return {
792
1022
  cwd: typeof row.cwd === 'string' ? row.cwd : '',
793
1023
  sessionId: typeof row.sessionId === 'string' ? row.sessionId : '',
1024
+ // The sidebar title the plugin resolved for this path (m13800). '' when
1025
+ // the host has no workspace registry (older dsh): the page then falls
1026
+ // back to the folder name it always used.
1027
+ title: typeof row.title === 'string' ? row.title : '',
794
1028
  url: row.url,
795
1029
  ageMs: Number.isFinite(at) && !future ? Math.max(0, now - at) : DSH_WINDOW_RETAIN_MS + 1,
796
1030
  }
@@ -800,18 +1034,58 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
800
1034
  // Live entries first, then most-recently-seen: the first row is the one an
801
1035
  // iframe deep link opens by default.
802
1036
  .sort((a, b) => (a.live === b.live ? a.ageMs - b.ageMs : a.live ? -1 : 1))
803
- if (live.length === 0) {
804
- return json(res, 200, { ok: true, available: false, windows: [], dropped: droppedAt, reason: 'dsh 未运行(没有记住的工作区窗口)' })
1037
+ const origin = isLoopbackOrigin(documentOrigin)
1038
+ ? documentOrigin
1039
+ : (live.length > 0 ? live[0].url : '')
1040
+ // The sidebar snapshot is only as fresh as its writer: dsh writes it on every
1041
+ // request and every refresh tick, so a document older than the retain window
1042
+ // means dsh is gone and the list is stale. Rows of remembered windows are
1043
+ // then the only truth (and they age out on their own).
1044
+ const sidebarFresh = Number.isFinite(documentAt)
1045
+ && documentAt <= now + 5 * 60_000
1046
+ && now - documentAt <= DSH_WINDOW_RETAIN_MS
1047
+ let rows = []
1048
+ if (sidebarFresh && sidebar.length > 0 && origin !== '') {
1049
+ rows = dshSidebarRows(sidebar, live, origin)
1050
+ } else {
1051
+ rows.push(...live)
1052
+ }
1053
+ // Direct fallback (m00186): the shared document can be missing, unreadable or
1054
+ // last written by a different dsh instance while a host on this machine is
1055
+ // alive. Each running plugin advertises its origin under `instances/`, so ask
1056
+ // the hosts themselves instead of telling the user dsh is not running.
1057
+ let known = sidebar.length
1058
+ if (rows.length === 0) {
1059
+ for (const candidate of dshProbeCandidates(home, now, documentOrigin, live)) {
1060
+ const snapshot = await probeDshWorkspaces(candidate)
1061
+ if (snapshot === null) continue
1062
+ const probedOrigin = isLoopbackOrigin(snapshot?.url) ? snapshot.url : candidate
1063
+ const probedSidebar = Array.isArray(snapshot?.workspaces) ? snapshot.workspaces : []
1064
+ const probedRows = dshSidebarRows(probedSidebar, [], probedOrigin)
1065
+ if (probedRows.length === 0) continue
1066
+ rows = probedRows
1067
+ known = Math.max(known, probedSidebar.length)
1068
+ break
1069
+ }
1070
+ }
1071
+ if (rows.length === 0) {
1072
+ // "No dsh" and "dsh is there but nothing usable arrived" are different: the
1073
+ // page can only name a count in the second case (m00186).
1074
+ const reason = known > 0
1075
+ ? `已发现 ${known} 个 dsh 工作区,但没有可用的 IDE 地址(dsh 可能刚启动,稍后会自动重试)`
1076
+ : 'dsh 未运行(没有记住的工作区窗口,也没有侧栏快照)'
1077
+ return json(res, 200, { ok: true, available: false, windows: [], dropped: droppedAt, knownWorkspaces: known, reason })
805
1078
  }
806
- const newest = live[0]
1079
+ const newest = rows[0]
807
1080
  return json(res, 200, {
808
1081
  ok: true,
809
1082
  available: true,
810
1083
  url: newest.url,
811
1084
  sessionId: newest.sessionId,
812
1085
  cwd: newest.cwd,
813
- windows: live,
1086
+ windows: rows,
814
1087
  dropped: droppedAt,
1088
+ knownWorkspaces: rows.length,
815
1089
  })
816
1090
  }
817
1091
 
@@ -1085,11 +1359,17 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
1085
1359
  bridgeReloadState = { at: Date.now(), ok: false, note }
1086
1360
  }
1087
1361
  }
1362
+ // A save does not start anything (m13920): it only reloads an enforcement
1363
+ // that is already running, so the note must not promise a restart the daemon
1364
+ // will not perform.
1365
+ const bridgeWasRunning = redirectorStatusCached().running === true
1088
1366
  setImmediate(() => { switchEnforcement().catch(() => {}) })
1089
1367
  return json(res, 200, {
1090
1368
  ok: true,
1091
1369
  revision: risdConfigRevision(written),
1092
- reloadNote: '规则已保存;系统层拦截正在后台按新规则重启',
1370
+ reloadNote: bridgeWasRunning
1371
+ ? '规则已保存;系统层拦截正在后台按新规则重启'
1372
+ : '规则已保存;引擎未启动,保存不会启动它',
1093
1373
  git,
1094
1374
  })
1095
1375
  }
@@ -1102,12 +1382,20 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
1102
1382
  if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
1103
1383
  const action = typeof parsed.action === 'string' ? parsed.action : 'status'
1104
1384
  const gitHost = typeof parsed.gitHost === 'string' ? parsed.gitHost : undefined
1385
+ // Only a click may raise a system password dialog (review B-P0-2): the
1386
+ // auto-start that follows a save calls the same route, and an implicit
1387
+ // action must never pop one (m13910).
1388
+ const interactive = parsed.interactive === true
1389
+ // Enforcement came up (or was already up): the stale "could not reload"
1390
+ // note is history, and leaving it made the restart button outlive its cause.
1391
+ const clearBridgeNote = () => { bridgeReloadState = { at: Date.now(), ok: true, note: '' } }
1105
1392
  let result
1106
1393
  if (action === 'start') {
1107
1394
  result = await serializeEngine(async () => {
1108
1395
  const engine = await startProxy(cwd)
1109
- const redirector = await serializeBridge(() => startRedirectors({ interactive: true }))
1396
+ const redirector = await serializeBridge(() => startRedirectors({ interactive }))
1110
1397
  noteBridgeStart(redirector)
1398
+ if (redirector.running === true || (Array.isArray(redirector.started) && redirector.started.length > 0)) clearBridgeNote()
1111
1399
  const git = await syncGitProxy({ cwd, host: gitHost, enabled: true })
1112
1400
  if (engine.ok === true) {
1113
1401
  engineCwd = cwd
@@ -1152,8 +1440,9 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
1152
1440
  result = await serializeBridge(async () => {
1153
1441
  const stopped = await stopRedirector()
1154
1442
  await new Promise((resolve) => setTimeout(resolve, 300))
1155
- const started = await startRedirectors({ interactive: true })
1443
+ const started = await startRedirectors({ interactive })
1156
1444
  noteBridgeStart(started)
1445
+ if (started.running === true || (Array.isArray(started.started) && started.started.length > 0)) clearBridgeNote()
1157
1446
  return {
1158
1447
  stopped,
1159
1448
  started: started.started ?? [],
@@ -1349,6 +1638,12 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
1349
1638
  const sessionId = parsed.sessionId === undefined ? null : String(parsed.sessionId)
1350
1639
  cancelIdleExit()
1351
1640
  const lease = leases.acquire({ ownerPid, sessionId, cwd })
1641
+ // The start half of 「跟随 dsh」: the policy is read when the lease arrives,
1642
+ // the same signal the teardown watches. Off the response path (starting the
1643
+ // engine costs seconds), and never interactive.
1644
+ if (lifecycle.proxy.followDsh === true && engineSummary().state !== 'running') {
1645
+ setImmediate(() => { followStartForLease(lease.cwd).catch(() => {}) })
1646
+ }
1352
1647
  return json(res, 200, { ok: true, lease })
1353
1648
  }
1354
1649