dsh-ris-ide 1.8.2 → 1.8.4

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/lib/index.js CHANGED
@@ -218,6 +218,8 @@ const TAIL_PATH = `${ROUTE_PREFIX}/tail`
218
218
  const STOP_PATH = `${ROUTE_PREFIX}/stop`
219
219
  const INSTANCES_PATH = `${ROUTE_PREFIX}/instances`
220
220
  const PROGRAMS_PATH = `${ROUTE_PREFIX}/programs`
221
+ /** Where a program's browser URL is resolved (dev server first, yds' injecting proxy second). */
222
+ const OPEN_TARGET_PATH = `${ROUTE_PREFIX}/open-target`
221
223
  /**
222
224
  * Server-sent events for what the panel otherwise polls: `programs` (the console
223
225
  * rows) and `tail` (one log file, pushed as it grows). One long-lived response per
@@ -1428,6 +1430,14 @@ function dispatchRequest(ctx, req, res, options) {
1428
1430
  serveSafely(res, () => servePrograms(ctx, req, res, options))
1429
1431
  return
1430
1432
  }
1433
+ if (pathname === OPEN_TARGET_PATH) {
1434
+ if (method !== 'GET') {
1435
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
1436
+ return
1437
+ }
1438
+ serveSafely(res, () => serveOpenTarget(ctx, req, res, options))
1439
+ return
1440
+ }
1431
1441
  if (pathname === START_PATH) {
1432
1442
  if (method !== 'POST') {
1433
1443
  writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'POST only' })
@@ -1583,16 +1593,51 @@ function dispatchRequest(ctx, req, res, options) {
1583
1593
  }
1584
1594
 
1585
1595
  /**
1586
- * True once a `git` spawn failed with ENOENT: a bare machine may not have git,
1587
- * and the plugin must still list/search files instead of showing an empty tree.
1596
+ * When the plugin stops trusting `git` (epoch ms; 0 = git is fine).
1597
+ *
1598
+ * A spawn error with ENOENT does NOT prove git is missing: node reports a
1599
+ * missing executable and a DELETED cwd identically (`error.path === 'git'`,
1600
+ * `errno === -2`). The plugin runs git inside tree folders, so one folder
1601
+ * deleted mid-command used to latch a module-level boolean forever — from then
1602
+ * on every tree answered `git:false`, the .gitignore filter was off and its
1603
+ * toggle greyed out, with no way back short of restarting dsh.
1604
+ * A failed spawn now only starts a short quarantine and a probe run from a
1605
+ * directory that always exists has to confirm the binary really is gone; any
1606
+ * later successful git command clears the verdict immediately.
1588
1607
  */
1589
- let gitMissing = false
1608
+ let gitMissingUntil = 0
1609
+
1610
+ /** How long one confirmed "git is absent" verdict is trusted before re-trying. */
1611
+ const GIT_MISSING_TTL_MS = 60_000
1612
+
1613
+ /** Whether git is currently assumed to be absent (the .gitignore filter is off). */
1614
+ function gitUnavailable() {
1615
+ return Date.now() < gitMissingUntil
1616
+ }
1590
1617
 
1591
1618
  /** Whether a spawn/exec error means the executable itself is absent. */
1592
1619
  function isMissingExecutable(error) {
1593
1620
  return error !== undefined && error !== null && (error.code === 'ENOENT' || error.errno === -2)
1594
1621
  }
1595
1622
 
1623
+ /**
1624
+ * A git spawn failed with ENOENT: decide whether git itself is gone.
1625
+ *
1626
+ * The probe runs from `tmpdir()` — a cwd that exists even when the tree folder
1627
+ * that triggered the failure does not. If git answers there, the failure was
1628
+ * the caller's cwd and git stays trusted.
1629
+ */
1630
+ function noteGitSpawnFailure() {
1631
+ const probe = spawnSync('git', ['--version'], { cwd: tmpdir(), windowsHide: true, timeout: 4000, stdio: 'ignore' })
1632
+ const missing = probe.error !== undefined ? isMissingExecutable(probe.error) : probe.status !== 0
1633
+ if (missing) gitMissingUntil = Date.now() + GIT_MISSING_TTL_MS
1634
+ }
1635
+
1636
+ /** A git command answered: git is usable wherever the last failure came from. */
1637
+ function noteGitSuccess() {
1638
+ gitMissingUntil = 0
1639
+ }
1640
+
1596
1641
  /** Run one git command and return its stdout (rejects on a non-zero exit). */
1597
1642
  function runGit(args, cwd, input) {
1598
1643
  return new Promise((resolvePromise, rejectPromise) => {
@@ -1603,7 +1648,7 @@ function runGit(args, cwd, input) {
1603
1648
  child.stdout?.on('data', (chunk) => { stdout += chunk.toString('utf8') })
1604
1649
  child.stderr?.on('data', (chunk) => { if (stderr.length < 8192) stderr += chunk.toString('utf8') })
1605
1650
  child.on('error', (error) => {
1606
- if (isMissingExecutable(error)) gitMissing = true
1651
+ if (isMissingExecutable(error)) noteGitSpawnFailure()
1607
1652
  if (!settled) { settled = true; rejectPromise(error) }
1608
1653
  })
1609
1654
  if (input !== undefined) {
@@ -1614,8 +1659,10 @@ function runGit(args, cwd, input) {
1614
1659
  settled = true
1615
1660
  // `git check-ignore` exits 1 when nothing matched, and `git grep` exits 1
1616
1661
  // when the pattern has no match; both are valid answers, not failures.
1617
- if (code === 0 || (code === 1 && (args[0] === 'check-ignore' || args[0] === 'grep'))) resolvePromise(stdout)
1618
- else rejectPromise(new Error(stderr || `git exited with ${code}`))
1662
+ if (code === 0 || (code === 1 && (args[0] === 'check-ignore' || args[0] === 'grep'))) {
1663
+ noteGitSuccess()
1664
+ resolvePromise(stdout)
1665
+ } else rejectPromise(new Error(stderr || `git exited with ${code}`))
1619
1666
  })
1620
1667
  })
1621
1668
  }
@@ -1871,7 +1918,7 @@ async function searchWorkspaceContent(cwd, query, limit, perFile) {
1871
1918
  const needle = String(query ?? '')
1872
1919
  const roots = await searchRoots(cwd)
1873
1920
  if (needle === '') return { hits: [], truncated: false, roots, files: 0 }
1874
- if (roots.length === 0 || gitMissing) {
1921
+ if (roots.length === 0 || gitUnavailable()) {
1875
1922
  return { ...await searchContentRaw(cwd, needle, limit, perFile), roots }
1876
1923
  }
1877
1924
  const hits = []
@@ -1884,7 +1931,7 @@ async function searchWorkspaceContent(cwd, query, limit, perFile) {
1884
1931
  } catch {
1885
1932
  // A root whose git call failed is not fatal (and git may have disappeared
1886
1933
  // mid-search): fall back to the filesystem walk for the whole request.
1887
- if (gitMissing) return { ...await searchContentRaw(cwd, needle, limit, perFile), roots }
1934
+ if (gitUnavailable()) return { ...await searchContentRaw(cwd, needle, limit, perFile), roots }
1888
1935
  continue
1889
1936
  }
1890
1937
  for (const raw of stdout.split('\n')) {
@@ -1965,7 +2012,7 @@ function streamGitStdout(args, cwd, onText, stream) {
1965
2012
  else rejectPromise(error)
1966
2013
  }
1967
2014
  child.on('error', (error) => {
1968
- if (isMissingExecutable(error)) gitMissing = true
2015
+ if (isMissingExecutable(error)) noteGitSpawnFailure()
1969
2016
  settle(error)
1970
2017
  })
1971
2018
  child.on('close', (code) => {
@@ -1973,7 +2020,7 @@ function streamGitStdout(args, cwd, onText, stream) {
1973
2020
  // error: treating it as one made every fallback walk the whole root again.
1974
2021
  if (child.killed === true) settle(undefined)
1975
2022
  else if (stream !== undefined && stream.aborted === true) settle(undefined)
1976
- else if (code === 0 || code === 1) settle(undefined)
2023
+ else if (code === 0 || code === 1) { noteGitSuccess(); settle(undefined) }
1977
2024
  else settle(new Error(stderr || `git exited with ${code}`))
1978
2025
  })
1979
2026
  })
@@ -2163,7 +2210,7 @@ async function searchWorkspaceFilesStream(cwd, roots, query, options) {
2163
2210
  if (needle !== '' && path.toLowerCase().indexOf(needle) === -1) return
2164
2211
  emitter.push(index, [path])
2165
2212
  }
2166
- if (roots.length === 0 || gitMissing === true) {
2213
+ if (roots.length === 0 || gitUnavailable()) {
2167
2214
  // No repo anywhere (or no git binary): walk and page the fallback listing.
2168
2215
  const all = await listRawFiles(cwd)
2169
2216
  const matches = []
@@ -2227,7 +2274,7 @@ async function searchWorkspaceContentStream(cwd, roots, query, options) {
2227
2274
  paths.add(hit.path)
2228
2275
  emitter.push(index, [hit])
2229
2276
  }
2230
- if (roots.length === 0 || gitMissing === true) {
2277
+ if (roots.length === 0 || gitUnavailable()) {
2231
2278
  const fallback = await searchContentRaw(cwd, needle, limit, perFile)
2232
2279
  const hits = fallback.hits
2233
2280
  for (let offset = 0; offset < hits.length; offset += pageSize) onPage(hits.slice(offset, offset + pageSize))
@@ -2546,7 +2593,7 @@ async function findGitRoot(from, stopAt) {
2546
2593
  async function repoAllowedPaths(root) {
2547
2594
  // No git installed (or a broken repo): return undefined so callers fall back to
2548
2595
  // "the filesystem is the whitelist" instead of hiding every file.
2549
- if (gitMissing) return undefined
2596
+ if (gitUnavailable()) return undefined
2550
2597
  const cached = TREE_ALLOWED_CACHE.get(root)
2551
2598
  if (cached !== undefined && Date.now() - cached.at < TREE_ALLOWED_TTL_MS) return cached.value
2552
2599
  const files = new Set()
@@ -2826,7 +2873,7 @@ async function listIdeTree(target, cwd, options) {
2826
2873
  // `git`: a repo (and a working git) is behind this path; `filtered`: the
2827
2874
  // listing currently applies .gitignore. The client's title-bar toggle reads
2828
2875
  // both (no git → nothing to toggle; git → default ON).
2829
- git: repo !== undefined && gitMissing !== true,
2876
+ git: repo !== undefined && gitUnavailable() !== true,
2830
2877
  filtered: allowed !== undefined,
2831
2878
  }
2832
2879
  }
@@ -3919,6 +3966,147 @@ function describe(error) {
3919
3966
  * @param res - Node response face.
3920
3967
  * @param options - `{ restrictToCwd }` (see {@link apply}).
3921
3968
  */
3969
+ /**
3970
+ * Resolve the URL "open in browser" should use for one program.
3971
+ *
3972
+ * The dev-server URL the program printed into its own log (webpack/vite always do)
3973
+ * is the answer. dsh-ris-yds may then wrap it — but ONLY when the program is one of
3974
+ * the yds front-ends the workspace declares, and it is told which one (m00555);
3975
+ * otherwise the page opens directly (m00462). A missing/failing yds plugin never
3976
+ * blocks the button: ris-ide keeps working without it.
3977
+ */
3978
+ async function serveOpenTarget(ctx, req, res, options) {
3979
+ try {
3980
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
3981
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
3982
+ const sessionId = url.searchParams.get('sessionId') ?? ''
3983
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
3984
+ const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd'))
3985
+ const rawDir = url.searchParams.get('dir')
3986
+ const logsDir = resolvePath(cwd, typeof rawDir === 'string' && rawDir !== '' ? rawDir : 'logs', true)
3987
+ const wanted = { id: url.searchParams.get('id') ?? '', name: url.searchParams.get('name') ?? '' }
3988
+ let program = await findProgramById(cwd, logsDir, wanted)
3989
+ if (program === null) throw new TailError('not-found', `没有找到程序「${wanted.id || wanted.name}」,刷新程序列表后再试`, 404)
3990
+ const devUrl = await logUrl(program.logPath)
3991
+ if (devUrl === undefined) {
3992
+ writeJson(res, 200, {
3993
+ ok: false,
3994
+ code: 'no-url',
3995
+ message: '这个程序还没打印出访问地址:先启动它,日志里出现 Local: http://localhost:<端口> 后再点',
3996
+ })
3997
+ return
3998
+ }
3999
+ // The 🌐 button opens the dev-server page the program printed. That page is
4000
+ // enough on its own; dsh-ris-yds is asked ONLY for a program that IS a yds
4001
+ // frontend, and it is told WHICH frontend: `yds.webConfig` declares one entry
4002
+ // per front-end project with its own port, and injecting another entry's rules
4003
+ // opens a page that talks to the wrong dev server (m00555). A plain npm app, a
4004
+ // spring program, or an unlisted frontend opens directly — no proxy, no
4005
+ // private browser (m00462), and a yds refusal is not an error.
4006
+ const frontend = program.kind === 'frontend' ? await ydsFrontendOf(req, cwd, program) : null
4007
+ if (frontend !== null) {
4008
+ const wrapped = await askYdsToWrap(req, cwd, devUrl, frontend)
4009
+ if (wrapped !== null && wrapped.ok === true && typeof wrapped.url === 'string') {
4010
+ writeJson(res, 200, { ...wrapped, source: 'yds' })
4011
+ return
4012
+ }
4013
+ }
4014
+ writeJson(res, 200, { ok: true, url: devUrl, source: 'dev-server' })
4015
+ } catch (error) {
4016
+ writeTailError(res, error)
4017
+ }
4018
+ }
4019
+
4020
+ /** One program by id (config first, then a scan): the browser URL lives on its log. */
4021
+ async function findProgramById(cwd, logsDir, ref) {
4022
+ const config = await readProgramConfig(cwd)
4023
+ if (config.exists === true && config.entries.length > 0) {
4024
+ const fromConfig = programsFromConfigEntries(cwd, config.entries, config.defaults)
4025
+ const hit = resolveProgramRef(await decoratePrograms(cwd, logsDir, fromConfig), ref)
4026
+ if (hit !== undefined) return hit
4027
+ }
4028
+ const scanned = await scanPrograms(cwd, logsDir, false).catch(() => [])
4029
+ return resolveProgramRef(scanned, ref) ?? null
4030
+ }
4031
+
4032
+ /**
4033
+ * The yds front-end project identity of one program, or null when it is not one.
4034
+ *
4035
+ * `yds.webConfig` is keyed by the front-end project's directory name, and the
4036
+ * program's own directory basename is that project. Asking the probe first keeps
4037
+ * the rule honest: a plain npm app, the backend module, or a frontend the
4038
+ * workspace never declared as a yds frontend must NOT be proxied at all.
4039
+ * @returns {Promise<{code: string, name: string, relDir: string}|null>}
4040
+ */
4041
+ async function ydsFrontendOf(req, cwd, program) {
4042
+ const dir = typeof program.dir === 'string' ? program.dir : ''
4043
+ if (dir === '') return null
4044
+ const code = basename(dir)
4045
+ if (code === '') return null
4046
+ const probe = await askYdsProbe(req, cwd)
4047
+ if (probe === null || probe.yds !== true) return null
4048
+ const frontends = Array.isArray(probe.frontends) ? probe.frontends : []
4049
+ if (frontends.indexOf(code) === -1) return null
4050
+ return {
4051
+ code,
4052
+ name: typeof program.name === 'string' && program.name !== '' ? program.name : code,
4053
+ relDir: typeof program.relDir === 'string' ? program.relDir : '',
4054
+ }
4055
+ }
4056
+
4057
+ /** One short JSON answer from a sibling plugin route, or null when it is not there. */
4058
+ async function askPluginJson(req, path, timeoutMs) {
4059
+ const host = typeof req.headers.host === 'string' ? req.headers.host : ''
4060
+ if (host === '') return null
4061
+ const controller = new AbortController()
4062
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
4063
+ try {
4064
+ const response = await fetch(`http://${host}${path}`, {
4065
+ headers: { accept: 'application/json' },
4066
+ signal: controller.signal,
4067
+ })
4068
+ if (response.status === 404) return null
4069
+ const parsed = await response.json().catch(() => null)
4070
+ return parsed === null || typeof parsed !== 'object' ? null : parsed
4071
+ } catch {
4072
+ return null
4073
+ } finally {
4074
+ clearTimeout(timer)
4075
+ }
4076
+ }
4077
+
4078
+ /** Ask dsh-ris-yds which front-ends this workspace declares (`null` = plugin absent). */
4079
+ async function askYdsProbe(req, cwd) {
4080
+ return askPluginJson(req, `/dsh-ris-yds/probe?workspace=${encodeURIComponent(cwd)}`, 5000)
4081
+ }
4082
+
4083
+ /**
4084
+ * Ask dsh-ris-yds to serve this URL through its injecting proxy for ONE frontend.
4085
+ * @param {object} frontend - `{code, name, relDir}` of the yds front-end program.
4086
+ * @returns {Promise<object|null>} the yds answer, or null when the plugin is absent.
4087
+ */
4088
+ async function askYdsToWrap(req, cwd, devUrl, frontend) {
4089
+ const host = typeof req.headers.host === 'string' ? req.headers.host : ''
4090
+ if (host === '') return null
4091
+ const controller = new AbortController()
4092
+ const timer = setTimeout(() => controller.abort(), 5000)
4093
+ try {
4094
+ const response = await fetch(`http://${host}/dsh-ris-yds/open`, {
4095
+ method: 'POST',
4096
+ headers: { 'content-type': 'application/json' },
4097
+ body: JSON.stringify({ workspace: cwd, devUrl, frontend }),
4098
+ signal: controller.signal,
4099
+ })
4100
+ if (response.status === 404) return null
4101
+ const parsed = await response.json().catch(() => null)
4102
+ return parsed === null ? null : parsed
4103
+ } catch {
4104
+ return null
4105
+ } finally {
4106
+ clearTimeout(timer)
4107
+ }
4108
+ }
4109
+
3922
4110
  async function servePrograms(ctx, req, res, options) {
3923
4111
  try {
3924
4112
  if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
@@ -10571,12 +10759,27 @@ function hasRef(ref) {
10571
10759
  }
10572
10760
 
10573
10761
  /** The localhost URL a dev server wrote into its log, when it did. */
10762
+ /**
10763
+ * The dev server address a program printed in its log.
10764
+ *
10765
+ * Only LOCAL addresses count: the point is to open the page this program serves,
10766
+ * and picking up a gateway URL from the same line (MDF prints the Java address
10767
+ * next to the node one) would open the wrong site. Hosts like 0.0.0.0 and the
10768
+ * `<HOST地址>` placeholder some scaffolds print are rewritten to 127.0.0.1,
10769
+ * because the browser must dial a concrete loopback address (m03945).
10770
+ */
10574
10771
  async function logUrl(logPath) {
10575
10772
  if (!existsSync(logPath)) return undefined
10576
10773
  const tail = await readTail(logPath, 16 * 1024).catch(() => undefined)
10577
10774
  if (tail === undefined || typeof tail.content !== 'string') return undefined
10578
- const matches = tail.content.match(/https?:\/\/localhost:\d+[^\s)"']*/g)
10579
- return matches === null || matches.length === 0 ? undefined : matches[matches.length - 1]
10775
+ // eslint-disable-next-line no-control-regex
10776
+ const text = tail.content.replace(/\u001b\[[0-9;]*m/g, '')
10777
+ const pattern = /https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\]|\[::\]|<[^>\s]{1,40}>):\d+[^\s)"',。;]*/gi
10778
+ const matches = text.match(pattern)
10779
+ if (matches === null || matches.length === 0) return undefined
10780
+ const last = matches[matches.length - 1]
10781
+ // A wildcard/placeholder host is a listening address, not a dialable one.
10782
+ return last.replace(/^(https?):\/\/(?:0\.0\.0\.0|\[::\]|<[^>]+>|\[::1\]):/i, '$1://127.0.0.1:')
10580
10783
  }
10581
10784
 
10582
10785
  /** Status of one log path (a program's fixed log, or an ad-hoc instance log). */
@@ -10949,6 +11152,10 @@ export const __test = {
10949
11152
  findGitRoot,
10950
11153
  repoAllowedPaths,
10951
11154
  listIdeTree,
11155
+ // git availability is a quarantine, not a latch (m03193)
11156
+ gitUnavailable,
11157
+ noteGitSpawnFailure,
11158
+ noteGitSuccess,
10952
11159
  serveTree,
10953
11160
  bundledSkillPath,
10954
11161
  findProjectRoot,
@@ -11132,6 +11339,7 @@ export const __test = {
11132
11339
  MAX_PROGRAMS,
11133
11340
  MAX_INSTANCES,
11134
11341
  ROUTE_PREFIX,
11342
+ OPEN_TARGET_PATH,
11135
11343
  DEFAULT_BYTES,
11136
11344
  HARD_MAX_BYTES,
11137
11345
  FS_WRITE_MAX_BODY_BYTES,
package/lib/redirector.js CHANGED
@@ -1357,8 +1357,7 @@ export async function startRedirector(options = {}) {
1357
1357
  return { started: true, pid: child.pid, side, command: plan.display }
1358
1358
  }
1359
1359
  // Passwordless sudo only: asking for a password from a web route would hang.
1360
- const probe = spawnSync('sudo', ['-n', 'true'], { encoding: 'utf8', timeout: 4000, windowsHide: true })
1361
- if (probe.status === 0) {
1360
+ if (sudoPasswordless(options) === true) {
1362
1361
  const child = spawn('sudo', ['-n', found.path, ...plan.args], { detached: true, stdio: 'ignore' })
1363
1362
  child.unref()
1364
1363
  // `sudo` is a supervisor, not the CLI: recording its pid made a later stop kill
@@ -2280,6 +2279,37 @@ export function hasElevation() {
2280
2279
  return typeof process.getuid === 'function' && process.getuid() === 0
2281
2280
  }
2282
2281
 
2282
+ /**
2283
+ * Does this box let us run `sudo -n` without a password?
2284
+ *
2285
+ * The answer is cached for a few minutes: sudo writes an audit line to the journal
2286
+ * on every call — success *and* failure — and the reconciler retries a background
2287
+ * start every minute, so a box without passwordless sudo used to fill its journal
2288
+ * with one "a password is required" line per minute (m03761). A user-initiated
2289
+ * start (`interactive`) always asks fresh: the user may have just added NOPASSWD,
2290
+ * and it is the one attempt where waiting for the answer is expected.
2291
+ *
2292
+ * The probe runs in the user's home directory on purpose: dsh inherits the cwd it
2293
+ * was launched from, and on WSL that is often `/mnt/c/WINDOWS/system32`, which then
2294
+ * shows up as `PWD=` in the sudo audit line (and in any relative path the probe
2295
+ * touches). Nothing about the probe depends on the caller's cwd.
2296
+ *
2297
+ * @param {{interactive?: boolean}} [options] - `interactive` bypasses the cache.
2298
+ * @returns {boolean} true when sudo needs no password.
2299
+ */
2300
+ const SUDO_PROBE_TTL_MS = 5 * 60 * 1000
2301
+ let sudoProbeCache = null
2302
+ export function sudoPasswordless(options = {}) {
2303
+ const now = Date.now()
2304
+ if (options.interactive !== true && sudoProbeCache !== null && now - sudoProbeCache.at < SUDO_PROBE_TTL_MS) {
2305
+ return sudoProbeCache.ok
2306
+ }
2307
+ const probe = spawnSync('sudo', ['-n', 'true'], { encoding: 'utf8', timeout: 4000, windowsHide: true, cwd: homedir() })
2308
+ const ok = probe.status === 0
2309
+ sudoProbeCache = { ok, at: now }
2310
+ return ok
2311
+ }
2312
+
2283
2313
  /**
2284
2314
  * Live Windows CLI pids, cached for a few seconds.
2285
2315
  *
@@ -3566,6 +3596,8 @@ function spawnSyncText(command, args, timeoutMs) {
3566
3596
 
3567
3597
  export const __test = {
3568
3598
  PROFILE_VERSION,
3599
+ sudoPasswordless,
3600
+ resetSudoProbe: () => { sudoProbeCache = null },
3569
3601
  setWindowsPathTranslator: (fn) => { windowsPathTranslator = typeof fn === 'function' ? fn : null },
3570
3602
  bundledBundleDir,
3571
3603
  bundleCacheInstalled,
@@ -8,10 +8,22 @@
8
8
  // running when the last dsh window closes, because the maintenance page can be the
9
9
  // only UI on the machine.
10
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.
11
+ // Following dsh is two-sided (m03397): `startWithDsh` runs the resource when a dsh
12
+ // attaches, `stopWithDsh` releases it when the last one leaves. The two halves are
13
+ // separate switches because they answer different questions ("start my programs
14
+ // when I open the IDE" vs "do not kill them when I close it"). What each start half
15
+ // can mean is a property of the resource, so the page greys out what cannot exist:
16
+ // - daemon: the start half is FORCED. dsh asks for the daemon on demand; letting it
17
+ // be switched off would leave a plugin with no supervisor to talk to.
18
+ // - proxy: both halves are real (a lease starts the engine, teardown stops it).
19
+ // - programs: the start half restores the programs that were still running when
20
+ // this daemon last exited (`risd-programs-last.json`), because a program is
21
+ // started per workspace and only the daemon knows what was live.
22
+ // - debug: there is nothing to auto-start (a JDWP session belongs to a page), so
23
+ // only the stop half exists.
24
+ //
25
+ // The start half is never an elevation request — an automatic start must not pop a
26
+ // password dialog (m13910) — so a bridge that needs root is only reported on the page.
15
27
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
16
28
  import { join } from 'node:path'
17
29
 
@@ -23,15 +35,20 @@ export const LIFECYCLE_RESOURCES = ['daemon', 'proxy', 'programs', 'debug']
23
35
 
24
36
  /** Defaults: everything follows dsh except programs/debug, which outlive the window. */
25
37
  export const LIFECYCLE_DEFAULTS = {
26
- daemon: { followDsh: true },
27
- proxy: { followDsh: true },
28
- programs: { followDsh: false },
29
- debug: { followDsh: false },
38
+ daemon: { startWithDsh: true, stopWithDsh: true },
39
+ proxy: { startWithDsh: true, stopWithDsh: true },
40
+ programs: { startWithDsh: false, stopWithDsh: false },
41
+ debug: { stopWithDsh: false },
30
42
  }
31
43
 
32
44
  /** Keys that used to be configurable and are now forced (m07741). */
33
45
  const FORCED_KEYS = ['followDaemon']
34
46
 
47
+ /** Resources whose start half is forced on (see the module comment). */
48
+ const FORCED_START = ['daemon']
49
+
50
+ const FORCED_DAEMON_START = 'daemon.startWithDsh 不可配置:dsh 需要时按需拉起守护进程(强制)'
51
+
35
52
  /** @param home - daemon home directory. */
36
53
  export function lifecyclePath(home) {
37
54
  return join(home, LIFECYCLE_FILENAME)
@@ -66,23 +83,44 @@ export function normalizeLifecycle(input) {
66
83
  continue
67
84
  }
68
85
  const allowed = Object.keys(defaults)
86
+ // The pre-m03397 file (and any older API caller) has ONE switch per resource:
87
+ // `followDsh` governed both halves, so it migrates to both. An explicit half in
88
+ // the same payload wins — that is how a caller moves one half at a time.
89
+ let legacyFollow
90
+ if (given.followDsh !== undefined) {
91
+ legacyFollow = bool(given.followDsh)
92
+ if (legacyFollow === undefined) errors.push(`${resource}.followDsh 必须是 true/false`)
93
+ }
69
94
  for (const key of Object.keys(given)) {
70
- if (allowed.includes(key) || FORCED_KEYS.includes(key)) continue
95
+ if (key === 'followDsh' || allowed.includes(key) || FORCED_KEYS.includes(key)) continue
71
96
  // Silently ignoring an unknown key made a typo look saved (review A2-P2-5).
72
97
  errors.push(`${resource}.${key} 不是可配置项(只能配置 ${allowed.join('/')})`)
73
98
  }
74
99
  for (const key of FORCED_KEYS) {
75
100
  if (given[key] !== undefined) {
76
- errors.push(`${resource}.${key} 不再支持:所有资源强制跟随 daemon(只能配置 followDsh)`)
101
+ errors.push(`${resource}.${key} 不再支持:所有资源强制跟随 daemon(只能配置 ${allowed.join('/')})`)
77
102
  }
78
103
  }
79
104
  const merged = Object.assign({}, defaults)
80
- for (const key of Object.keys(defaults)) {
81
- const parsed = bool(given[key])
105
+ for (const key of allowed) {
82
106
  if (given[key] === undefined) continue
107
+ const parsed = bool(given[key])
83
108
  if (parsed === undefined) { errors.push(`${resource}.${key} 必须是 true/false`); continue }
109
+ // The daemon's start half is forced on: a plugin that cannot ask for a daemon
110
+ // has no supervisor at all (see the module comment).
111
+ if (FORCED_START.includes(resource) && key === 'startWithDsh' && parsed !== true) {
112
+ errors.push(FORCED_DAEMON_START)
113
+ continue
114
+ }
84
115
  merged[key] = parsed
85
116
  }
117
+ if (legacyFollow !== undefined) {
118
+ for (const key of allowed) {
119
+ if (given[key] !== undefined) continue
120
+ if (FORCED_START.includes(resource) && key === 'startWithDsh') continue
121
+ merged[key] = legacyFollow
122
+ }
123
+ }
86
124
  value[resource] = merged
87
125
  }
88
126
  return { value, errors, changed: errors.length === 0 }