dsh-ris-ide 1.7.1 → 1.7.3
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 +29 -2
- package/bin/check-listing.mjs +247 -0
- package/bin/proxy-janitor.mjs +88 -0
- package/lib/client-codemirror.js +110 -66
- package/lib/client.js +1809 -70
- package/lib/index.js +1638 -11
- package/lib/janitor.js +286 -0
- package/lib/proxy.js +1498 -0
- package/lib/redirector.js +2109 -0
- package/package.json +4 -2
- package/skills/dsh-ris-ide-debug/SKILL.md +37 -2
- package/test/client-viewer.test.mjs +622 -6
- package/test/companion.test.mjs +65 -0
- package/test/host-search.test.mjs +125 -1
- package/test/host-tail.test.mjs +95 -1
- package/test/inherit-engine.test.mjs +175 -0
- package/test/install-phase.test.mjs +36 -0
- package/test/janitor.test.mjs +144 -0
- package/test/lifecycle.test.mjs +88 -0
- package/test/proxy-route.test.mjs +599 -0
- package/test/proxy.test.mjs +873 -0
- package/test/redirector.test.mjs +521 -0
package/lib/index.js
CHANGED
|
@@ -51,11 +51,11 @@
|
|
|
51
51
|
* @module dsh-ris-ide
|
|
52
52
|
*/
|
|
53
53
|
import { appendFile, copyFile, cp, link, lstat, mkdir, open, readdir, readFile, readlink, rename, rm, stat, symlink, truncate, writeFile } from 'node:fs/promises'
|
|
54
|
-
import { createReadStream, createWriteStream, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
54
|
+
import { closeSync, createReadStream, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
55
55
|
import { watch } from 'node:fs'
|
|
56
56
|
import { createHash } from 'node:crypto'
|
|
57
|
-
import { spawn } from 'node:child_process'
|
|
58
|
-
import { homedir } from 'node:os'
|
|
57
|
+
import { spawn, spawnSync } from 'node:child_process'
|
|
58
|
+
import { homedir, tmpdir } from 'node:os'
|
|
59
59
|
import { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve, sep, parse } from 'node:path'
|
|
60
60
|
import { fileURLToPath } from 'node:url'
|
|
61
61
|
import { pipeline } from 'node:stream/promises'
|
|
@@ -65,6 +65,22 @@ import {
|
|
|
65
65
|
createDebugSessions, DebugError, debugErrorStatus, jdwpAgentArg, allocateDebugPort, waitForTcp,
|
|
66
66
|
waitForJdwpListening, toJsonSafe,
|
|
67
67
|
} from './debug/engine.js'
|
|
68
|
+
import { allowList, autoRules, engineSide, gitProxyPlan, injectionFor, isSocksCapableProgram, mergeConfigs, parseHostSpec, parsePortSpec, programKey, proxyConfigPath, proxyHomeDir, proxyPid, proxyStatus, readProxyConfig, ruleEffectiveness, runWindowsGitConfig, startProxy, stopProxy, stopProxySync, writeProxyConfig } from './proxy.js'
|
|
69
|
+
import {
|
|
70
|
+
buildProfile,
|
|
71
|
+
redirectorCommand,
|
|
72
|
+
localRedirectorRunning,
|
|
73
|
+
redirectorStatus,
|
|
74
|
+
redirectorStatusCached,
|
|
75
|
+
reloadRedirectorsWithProfile,
|
|
76
|
+
startRedirectors,
|
|
77
|
+
stopRedirector,
|
|
78
|
+
posixToWindowsPath,
|
|
79
|
+
syncRedirector,
|
|
80
|
+
windowsToPosixPath,
|
|
81
|
+
writeHeartbeat,
|
|
82
|
+
} from './redirector.js'
|
|
83
|
+
import { armJanitor, janitorStatus } from './janitor.js'
|
|
68
84
|
|
|
69
85
|
export const name = 'dsh-ris-ide'
|
|
70
86
|
/**
|
|
@@ -266,6 +282,25 @@ const SEARCH_PATH = `${ROUTE_PREFIX}/search`
|
|
|
266
282
|
* a plain filesystem walk when there is no git (or git is not installed).
|
|
267
283
|
*/
|
|
268
284
|
const CONTENT_SEARCH_PATH = `${ROUTE_PREFIX}/search-content`
|
|
285
|
+
/**
|
|
286
|
+
* Streaming twins of the two searches: ONE NDJSON response, one frame per page,
|
|
287
|
+
* so the dropdown paints the first matches while the other repo roots are still
|
|
288
|
+
* being listed. The non-streaming routes stay (compatibility + fallback when a
|
|
289
|
+
* browser lacks readable streams).
|
|
290
|
+
*/
|
|
291
|
+
const SEARCH_STREAM_PATH = `${ROUTE_PREFIX}/search/stream`
|
|
292
|
+
const CONTENT_SEARCH_STREAM_PATH = `${ROUTE_PREFIX}/search-content/stream`
|
|
293
|
+
/** Rows per streamed page when the client does not ask for a size. */
|
|
294
|
+
export const SEARCH_STREAM_PAGE_DEFAULT = 40
|
|
295
|
+
/** Largest page a client may ask for. */
|
|
296
|
+
export const SEARCH_STREAM_PAGE_MAX = 500
|
|
297
|
+
/**
|
|
298
|
+
* How many repo roots may run `git` at the same time. The roots are independent
|
|
299
|
+
* processes and this workspace has 32 of them: sequential `ls-files` measured
|
|
300
|
+
* 1.0 s, the same calls with all roots in flight 0.09 s — the wall clock is
|
|
301
|
+
* spawn latency, not file count, so running them together is the whole fix.
|
|
302
|
+
*/
|
|
303
|
+
export const SEARCH_STREAM_CONCURRENCY = 6
|
|
269
304
|
/**
|
|
270
305
|
* Run ONE Maven test (`-Dtest=<name>`) in one module and keep its console in
|
|
271
306
|
* memory, so the IDE can start it and poll without a fake terminal.
|
|
@@ -300,6 +335,21 @@ const DEBUGS_PATH = `${ROUTE_PREFIX}/debugs`
|
|
|
300
335
|
const DEBUG_SOURCE_PATH = `${ROUTE_PREFIX}/debug/source`
|
|
301
336
|
/** Read/write the IDE-specific settings kept in `.dsh-ris-ide/settings.json`. */
|
|
302
337
|
const SETTINGS_PATH = `${ROUTE_PREFIX}/settings`
|
|
338
|
+
/**
|
|
339
|
+
* Proxy rules + engine control.
|
|
340
|
+
* `GET` reports the stored rules (with per-row parse diagnostics) and whether the
|
|
341
|
+
* tunnel engine is up; `POST` saves the form; `/action` starts/stops the engine
|
|
342
|
+
* and writes the scoped git config.
|
|
343
|
+
*/
|
|
344
|
+
const PROXY_PATH = `${ROUTE_PREFIX}/proxy`
|
|
345
|
+
const PROXY_ACTION_PATH = `${ROUTE_PREFIX}/proxy/action`
|
|
346
|
+
/** Program picker for the rules table: this OS, plus Windows when reachable. */
|
|
347
|
+
const PROXY_PROGRAMS_PATH = `${ROUTE_PREFIX}/proxy/programs`
|
|
348
|
+
/**
|
|
349
|
+
* File browser for the rules table's 「固定程序」 source: a rule can name an
|
|
350
|
+
* executable that is not running yet, so it is proxied the moment it starts.
|
|
351
|
+
*/
|
|
352
|
+
const PROXY_BROWSE_PATH = `${ROUTE_PREFIX}/proxy/browse`
|
|
303
353
|
/** Workspace cache holding extracted sources / decompiled files. */
|
|
304
354
|
export const IDE_CACHE_DIR = `${IDE_STATE_DIR}/cache`
|
|
305
355
|
/** Where the visual settings dialog persists the decompiler jar. */
|
|
@@ -377,6 +427,13 @@ const DEFAULT_STOP_GRACE_MS = 5000
|
|
|
377
427
|
const MAX_STOP_GRACE_MS = 60000
|
|
378
428
|
/** Cap on one JSON request body (the stop request carries two short strings). */
|
|
379
429
|
const MAX_BODY_BYTES = 64 * 1024
|
|
430
|
+
/**
|
|
431
|
+
* Cap on one `POST /fs/write` body: an editor save carries the WHOLE file, so the
|
|
432
|
+
* generic 64 KB JSON cap rejected every save of a file above ~64 KB ("request body
|
|
433
|
+
* too large"). Text edits are opened whole below `FS_MAX_TEXT_BYTES` (512 KB) and
|
|
434
|
+
* chunked above it, so 8 MB covers every editable document with room to spare.
|
|
435
|
+
*/
|
|
436
|
+
const FS_WRITE_MAX_BODY_BYTES = 8 * 1024 * 1024
|
|
380
437
|
|
|
381
438
|
/** One routable failure with a machine code and an HTTP status. */
|
|
382
439
|
export class TailError extends Error {
|
|
@@ -393,6 +450,91 @@ export class TailError extends Error {
|
|
|
393
450
|
}
|
|
394
451
|
}
|
|
395
452
|
|
|
453
|
+
/**
|
|
454
|
+
* Process-wide lifecycle for the detached child services (proxy engine, redirector,
|
|
455
|
+
* git proxy, janitor).
|
|
456
|
+
*
|
|
457
|
+
* The child services outlive any one plugin effect: dsh disposes the fiber tree and
|
|
458
|
+
* only then calls `process.exit()`, so the synchronous `exit` listener is the last
|
|
459
|
+
* chance to stop them. That listener — and the detached janitor that covers
|
|
460
|
+
* SIGKILL/crash/closed-terminal — must NOT be removed by the effect teardown.
|
|
461
|
+
* Removing them was the Ctrl+C leak: the hook was already gone when `process.exit()`
|
|
462
|
+
* ran, so the engine kept routing with no UI left to stop it. Living here also makes
|
|
463
|
+
* a profile hot reload harmless: the listener is installed once per process and a
|
|
464
|
+
* heartbeat stopped by the teardown is simply restarted.
|
|
465
|
+
*/
|
|
466
|
+
let lifecycle = null
|
|
467
|
+
/** Engine left behind by a previous dsh process: `{ pid, owner, detectedAt } | null`. */
|
|
468
|
+
let inheritedEngine = null
|
|
469
|
+
|
|
470
|
+
/** Write the watchdog heartbeat now and keep writing it every 3 s. */
|
|
471
|
+
function startHeartbeat() {
|
|
472
|
+
try {
|
|
473
|
+
writeHeartbeat()
|
|
474
|
+
return setInterval(() => { try { writeHeartbeat() } catch { /* the next tick retries */ } }, 3000)
|
|
475
|
+
} catch {
|
|
476
|
+
return null
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Adopt an engine whose dsh is gone (`proxy.pid` alive, no watcher of ours).
|
|
482
|
+
*
|
|
483
|
+
* The pidfile is machine-wide, so an engine with a RUNNING janitor already has an
|
|
484
|
+
* owner on this machine: either another dsh (multi-instance case — leave it alone)
|
|
485
|
+
* or the watcher that is about to clean up after a crash. An engine with no watcher
|
|
486
|
+
* can only have survived the pre-fix teardown — take it over and report it, instead
|
|
487
|
+
* of letting it run invisibly or spawning a second one.
|
|
488
|
+
* @returns {{pid: number, owner: number, detectedAt: string} | null} the adopted engine.
|
|
489
|
+
*/
|
|
490
|
+
function adoptLeftoverEngine() {
|
|
491
|
+
try {
|
|
492
|
+
const pid = proxyPid()
|
|
493
|
+
if (pid === null || pid <= 0) {
|
|
494
|
+
inheritedEngine = null
|
|
495
|
+
return null
|
|
496
|
+
}
|
|
497
|
+
if (inheritedEngine !== null && inheritedEngine.pid === pid) return inheritedEngine
|
|
498
|
+
const watcher = janitorStatus()
|
|
499
|
+
if (watcher.owner === process.pid) {
|
|
500
|
+
// Ours already (e.g. a hot reload): not "left behind".
|
|
501
|
+
inheritedEngine = null
|
|
502
|
+
return null
|
|
503
|
+
}
|
|
504
|
+
if (watcher.running === true) return inheritedEngine
|
|
505
|
+
inheritedEngine = { pid, owner: watcher.owner, detectedAt: new Date().toISOString() }
|
|
506
|
+
return inheritedEngine
|
|
507
|
+
} catch {
|
|
508
|
+
return inheritedEngine
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Install (once per process) the exit hook, heartbeat and janitor, and adopt an
|
|
514
|
+
* engine left behind by a previous dsh process.
|
|
515
|
+
* @returns {{beat: NodeJS.Timeout | null, onExit: Function, owner: number}} the state.
|
|
516
|
+
*/
|
|
517
|
+
function ensureLifecycle() {
|
|
518
|
+
if (lifecycle !== null && lifecycle.owner === process.pid) {
|
|
519
|
+
if (lifecycle.beat === null) lifecycle.beat = startHeartbeat()
|
|
520
|
+
return lifecycle
|
|
521
|
+
}
|
|
522
|
+
adoptLeftoverEngine()
|
|
523
|
+
const onExit = () => {
|
|
524
|
+
try { stopProxySync() } catch { /* best effort while exiting */ }
|
|
525
|
+
try { stopRedirectorSync() } catch { /* best effort while exiting */ }
|
|
526
|
+
try { clearGitProxySync() } catch { /* best effort while exiting */ }
|
|
527
|
+
// Deliberately NO disarmJanitor(): the watcher must see our pid disappear and
|
|
528
|
+
// clean up itself — it is the only path that survives SIGKILL, a crash or a
|
|
529
|
+
// closed terminal, where no 'exit' listener runs at all.
|
|
530
|
+
}
|
|
531
|
+
process.once('exit', onExit)
|
|
532
|
+
lifecycle = { beat: startHeartbeat(), onExit, owner: process.pid }
|
|
533
|
+
// Idempotent for the same owner; replaces a watcher left watching a dead dsh.
|
|
534
|
+
try { armJanitor({ ownerPid: process.pid }) } catch { /* the watcher is optional */ }
|
|
535
|
+
return lifecycle
|
|
536
|
+
}
|
|
537
|
+
|
|
396
538
|
/**
|
|
397
539
|
* Register this plugin's two routes for its lifetime.
|
|
398
540
|
*
|
|
@@ -437,6 +579,30 @@ export function apply(ctx, config) {
|
|
|
437
579
|
}, LOG_ROTATE_INTERVAL_MS)
|
|
438
580
|
return () => clearInterval(timer)
|
|
439
581
|
}, 'dsh-ris-ide: log rotation')
|
|
582
|
+
// Child services belong to the PROCESS, not to this effect (see ensureLifecycle):
|
|
583
|
+
// dsh disposes the fiber tree first and calls process.exit() afterwards, so a
|
|
584
|
+
// teardown that removed the exit hook or disarmed the janitor left the detached
|
|
585
|
+
// engine alive with no UI to stop it.
|
|
586
|
+
ctx.effect(() => {
|
|
587
|
+
const adopted = adoptLeftoverEngine()
|
|
588
|
+
if (adopted !== null) {
|
|
589
|
+
try {
|
|
590
|
+
ctx.logger?.warn?.(`[dsh-ris-ide] 接管上一个会话留下的代理引擎(引擎 pid ${adopted.pid},原所有者 pid ${adopted.owner > 0 ? adopted.owner : '未知'})`)
|
|
591
|
+
} catch { /* logging is best effort */ }
|
|
592
|
+
}
|
|
593
|
+
const state = ensureLifecycle()
|
|
594
|
+
return () => {
|
|
595
|
+
// Only the heartbeat stops here: its stop is exactly what the elevated bridge
|
|
596
|
+
// watchdog waits for (20 s freshness), and the next apply (a profile hot
|
|
597
|
+
// reload) restarts it in the same second. The exit hook and the janitor stay
|
|
598
|
+
// armed — they are the guards for process.exit(), SIGKILL, a crash and a
|
|
599
|
+
// closed terminal.
|
|
600
|
+
if (state.beat !== null) {
|
|
601
|
+
clearInterval(state.beat)
|
|
602
|
+
state.beat = null
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
}, 'dsh-ris-ide: stop child services on exit')
|
|
440
606
|
}
|
|
441
607
|
|
|
442
608
|
/**
|
|
@@ -628,6 +794,34 @@ function dispatchRequest(ctx, req, res, options) {
|
|
|
628
794
|
serveSafely(res, () => serveDebugSource(ctx, req, res, options))
|
|
629
795
|
return
|
|
630
796
|
}
|
|
797
|
+
if (pathname === PROXY_PATH) {
|
|
798
|
+
serveSafely(res, () => serveProxy(ctx, req, res, options))
|
|
799
|
+
return
|
|
800
|
+
}
|
|
801
|
+
if (pathname === PROXY_ACTION_PATH) {
|
|
802
|
+
if (method !== 'POST') {
|
|
803
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'POST only' })
|
|
804
|
+
return
|
|
805
|
+
}
|
|
806
|
+
serveSafely(res, () => serveProxyAction(ctx, req, res, options))
|
|
807
|
+
return
|
|
808
|
+
}
|
|
809
|
+
if (pathname === PROXY_PROGRAMS_PATH) {
|
|
810
|
+
if (method !== 'GET') {
|
|
811
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
812
|
+
return
|
|
813
|
+
}
|
|
814
|
+
serveSafely(res, () => serveProxyPrograms(ctx, req, res, options))
|
|
815
|
+
return
|
|
816
|
+
}
|
|
817
|
+
if (pathname === PROXY_BROWSE_PATH) {
|
|
818
|
+
if (method !== 'GET') {
|
|
819
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
820
|
+
return
|
|
821
|
+
}
|
|
822
|
+
serveSafely(res, () => serveProxyBrowse(ctx, req, res, options))
|
|
823
|
+
return
|
|
824
|
+
}
|
|
631
825
|
if (pathname === SETTINGS_PATH) {
|
|
632
826
|
serveSafely(res, () => serveSettings(ctx, req, res, options))
|
|
633
827
|
return
|
|
@@ -660,6 +854,15 @@ function dispatchRequest(ctx, req, res, options) {
|
|
|
660
854
|
serveSafely(res, () => serveContentSearch(ctx, req, res, options))
|
|
661
855
|
return
|
|
662
856
|
}
|
|
857
|
+
if (pathname === SEARCH_STREAM_PATH || pathname === CONTENT_SEARCH_STREAM_PATH) {
|
|
858
|
+
if (method !== 'GET') {
|
|
859
|
+
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
860
|
+
return
|
|
861
|
+
}
|
|
862
|
+
// Not serveSafely: the handler streams and owns its own error frames.
|
|
863
|
+
void serveSearchStream(ctx, req, res, options, pathname === CONTENT_SEARCH_STREAM_PATH)
|
|
864
|
+
return
|
|
865
|
+
}
|
|
663
866
|
if (pathname === OPENS_PATH) {
|
|
664
867
|
if (method !== 'GET') {
|
|
665
868
|
writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
|
|
@@ -1031,6 +1234,355 @@ async function serveContentSearch(ctx, req, res, options) {
|
|
|
1031
1234
|
}
|
|
1032
1235
|
}
|
|
1033
1236
|
|
|
1237
|
+
/**
|
|
1238
|
+
* Spawn one git command and hand its stdout to `onText` as it arrives — the
|
|
1239
|
+
* streaming twin of {@link runGit}. `git grep`/`git ls-files` exit 1 for "no
|
|
1240
|
+
* match", which is an answer, not a failure. A client that navigated away leaves
|
|
1241
|
+
* `stream.aborted` set: the child is killed and no more text is delivered.
|
|
1242
|
+
* @param args - git arguments.
|
|
1243
|
+
* @param cwd - working directory (one repo root).
|
|
1244
|
+
* @param onText - called with each stdout chunk.
|
|
1245
|
+
* @param stream - `{ aborted, children }` control object (see serveSearchStream).
|
|
1246
|
+
* @returns {Promise<void>} resolves when the child is gone.
|
|
1247
|
+
*/
|
|
1248
|
+
function streamGitStdout(args, cwd, onText, stream) {
|
|
1249
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
1250
|
+
const child = spawn('git', args, { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
1251
|
+
if (stream !== undefined) stream.children.add(child)
|
|
1252
|
+
let stderr = ''
|
|
1253
|
+
let settled = false
|
|
1254
|
+
child.stdout?.setEncoding('utf8')
|
|
1255
|
+
child.stdout?.on('data', (chunk) => {
|
|
1256
|
+
if (stream !== undefined && stream.aborted === true) return
|
|
1257
|
+
onText(chunk)
|
|
1258
|
+
})
|
|
1259
|
+
child.stderr?.on('data', (chunk) => { if (stderr.length < 8192) stderr += chunk.toString('utf8') })
|
|
1260
|
+
const settle = (error) => {
|
|
1261
|
+
if (settled) return
|
|
1262
|
+
settled = true
|
|
1263
|
+
if (stream !== undefined) stream.children.delete(child)
|
|
1264
|
+
if (error === undefined) resolvePromise()
|
|
1265
|
+
else rejectPromise(error)
|
|
1266
|
+
}
|
|
1267
|
+
child.on('error', (error) => {
|
|
1268
|
+
if (isMissingExecutable(error)) gitMissing = true
|
|
1269
|
+
settle(error)
|
|
1270
|
+
})
|
|
1271
|
+
child.on('close', (code) => {
|
|
1272
|
+
// Killed on purpose (row budget spent / client gone) is an ANSWER, not an
|
|
1273
|
+
// error: treating it as one made every fallback walk the whole root again.
|
|
1274
|
+
if (child.killed === true) settle(undefined)
|
|
1275
|
+
else if (stream !== undefined && stream.aborted === true) settle(undefined)
|
|
1276
|
+
else if (code === 0 || code === 1) settle(undefined)
|
|
1277
|
+
else settle(new Error(stderr || `git exited with ${code}`))
|
|
1278
|
+
})
|
|
1279
|
+
})
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
/**
|
|
1283
|
+
* SIGTERM every git child of one streamed search. Called when the row budget is
|
|
1284
|
+
* spent (nobody waits for the rest) and when the client disconnects.
|
|
1285
|
+
* @param stream - `{ children: Set<ChildProcess> }`, or undefined in unit tests.
|
|
1286
|
+
*/
|
|
1287
|
+
function killStreamChildren(stream) {
|
|
1288
|
+
if (stream === undefined || stream === null) return
|
|
1289
|
+
for (const child of stream.children) {
|
|
1290
|
+
try { child.kill('SIGTERM') } catch { /* already gone */ }
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
/**
|
|
1295
|
+
* Emit streamed matches in ROOT ORDER while the roots are searched concurrently.
|
|
1296
|
+
*
|
|
1297
|
+
* The sequential search visits the workspace root first and then the child repos
|
|
1298
|
+
* alphabetically; buffering per root and only flushing the head root keeps that
|
|
1299
|
+
* ranking exactly, so pages never reshuffle the dropdown. A page leaves as soon
|
|
1300
|
+
* as `pageSize` rows of the emitting root are buffered — the first page therefore
|
|
1301
|
+
* arrives after the fastest root instead of after the slowest.
|
|
1302
|
+
*
|
|
1303
|
+
* `maxItems` (the caller's `limit`) is counted on the EMITTED order, not on the
|
|
1304
|
+
* arrival order: roots answer concurrently, so a root late in the ranking must
|
|
1305
|
+
* not steal the budget from an earlier one. Hitting it closes the emitter and
|
|
1306
|
+
* fires `onFull` (the caller kills the git children there).
|
|
1307
|
+
* @param rootCount - number of roots (one buffer each).
|
|
1308
|
+
* @param pageSize - rows per emitted page.
|
|
1309
|
+
* @param emit - receives one page (non-empty array).
|
|
1310
|
+
* @param [options] - `{ maxItems, onFull }`.
|
|
1311
|
+
* @returns `{ push, finish, close, isClosed, isFull, total }`.
|
|
1312
|
+
*/
|
|
1313
|
+
function createOrderedPages(rootCount, pageSize, emit, options = {}) {
|
|
1314
|
+
const maxItems = Number.isFinite(options.maxItems) && options.maxItems > 0 ? options.maxItems : Infinity
|
|
1315
|
+
const onFull = typeof options.onFull === 'function' ? options.onFull : () => {}
|
|
1316
|
+
const buffers = []
|
|
1317
|
+
const finished = []
|
|
1318
|
+
for (let index = 0; index < rootCount; index += 1) { buffers.push([]); finished.push(false) }
|
|
1319
|
+
let head = 0
|
|
1320
|
+
let total = 0
|
|
1321
|
+
let full = false
|
|
1322
|
+
let closed = false
|
|
1323
|
+
/** Deliver `items` as pages, never more than the remaining budget. */
|
|
1324
|
+
function deliver(items) {
|
|
1325
|
+
let offset = 0
|
|
1326
|
+
while (offset < items.length && full !== true) {
|
|
1327
|
+
const take = Math.min(pageSize, items.length - offset, maxItems - total)
|
|
1328
|
+
if (take <= 0) break
|
|
1329
|
+
const page = items.slice(offset, offset + take)
|
|
1330
|
+
offset += take
|
|
1331
|
+
total += take
|
|
1332
|
+
emit(page)
|
|
1333
|
+
if (total >= maxItems) full = true
|
|
1334
|
+
}
|
|
1335
|
+
if (full === true && closed !== true) {
|
|
1336
|
+
closed = true
|
|
1337
|
+
onFull()
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
function flush() {
|
|
1341
|
+
while (!closed && head < rootCount) {
|
|
1342
|
+
const buffer = buffers[head]
|
|
1343
|
+
while (buffer.length >= pageSize) deliver(buffer.splice(0, pageSize))
|
|
1344
|
+
if (finished[head] !== true) return
|
|
1345
|
+
if (buffer.length > 0) deliver(buffer.splice(0, buffer.length))
|
|
1346
|
+
head += 1
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
return {
|
|
1350
|
+
push(index, items) {
|
|
1351
|
+
if (closed) return
|
|
1352
|
+
const buffer = buffers[index]
|
|
1353
|
+
for (const item of items) buffer.push(item)
|
|
1354
|
+
flush()
|
|
1355
|
+
},
|
|
1356
|
+
finish(index) {
|
|
1357
|
+
if (closed) return
|
|
1358
|
+
finished[index] = true
|
|
1359
|
+
flush()
|
|
1360
|
+
},
|
|
1361
|
+
close() {
|
|
1362
|
+
if (closed) return
|
|
1363
|
+
// Abort path: flush what was already accepted (in root order) so a caller
|
|
1364
|
+
// that closed early still sees the rows it asked for, then stop.
|
|
1365
|
+
for (let index = head; index < rootCount; index += 1) {
|
|
1366
|
+
const buffer = buffers[index]
|
|
1367
|
+
while (buffer.length > 0 && full !== true) deliver(buffer.splice(0, Math.min(pageSize, buffer.length)))
|
|
1368
|
+
}
|
|
1369
|
+
closed = true
|
|
1370
|
+
},
|
|
1371
|
+
isClosed() { return closed },
|
|
1372
|
+
isFull() { return full },
|
|
1373
|
+
total() { return total },
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
/**
|
|
1378
|
+
* Run `worker(root, index)` for every root with at most `concurrency` in flight.
|
|
1379
|
+
* A worker must handle its own errors — one broken repo must not cancel the rest.
|
|
1380
|
+
* @param roots - repo roots.
|
|
1381
|
+
* @param concurrency - maximum simultaneous workers.
|
|
1382
|
+
* @param worker - async `(root, index)`.
|
|
1383
|
+
* @returns {Promise<void>} resolves when every root was visited.
|
|
1384
|
+
*/
|
|
1385
|
+
async function forEachRootInParallel(roots, concurrency, worker) {
|
|
1386
|
+
let next = 0
|
|
1387
|
+
async function lane() {
|
|
1388
|
+
while (next < roots.length) {
|
|
1389
|
+
const index = next
|
|
1390
|
+
next += 1
|
|
1391
|
+
await worker(roots[index], index)
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
const lanes = []
|
|
1395
|
+
const width = Math.max(1, Math.min(concurrency, roots.length))
|
|
1396
|
+
for (let index = 0; index < width; index += 1) lanes.push(lane())
|
|
1397
|
+
await Promise.all(lanes)
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
/**
|
|
1401
|
+
* Streaming filename search: the same matches, ignore rules and ordering as
|
|
1402
|
+
* {@link searchWorkspaceFiles}, delivered page by page while the roots are
|
|
1403
|
+
* listed in parallel.
|
|
1404
|
+
* @param cwd - workspace root (only for the no-git fallback).
|
|
1405
|
+
* @param roots - repo roots from {@link searchRoots}.
|
|
1406
|
+
* @param query - case-insensitive substring of the path or basename.
|
|
1407
|
+
* @param options - `{ limit, pageSize, onPage, stream }`.
|
|
1408
|
+
* @returns `{ files, count, truncated }` when the walk is complete.
|
|
1409
|
+
*/
|
|
1410
|
+
async function searchWorkspaceFilesStream(cwd, roots, query, options) {
|
|
1411
|
+
const { limit, pageSize, onPage, stream } = options
|
|
1412
|
+
const needle = String(query ?? '').toLowerCase()
|
|
1413
|
+
let files = 0
|
|
1414
|
+
let truncated = false
|
|
1415
|
+
// The `limit` is counted on the EMITTED (root-ordered) rows: see createOrderedPages.
|
|
1416
|
+
const emitter = createOrderedPages(roots.length, pageSize, onPage, {
|
|
1417
|
+
maxItems: limit,
|
|
1418
|
+
onFull: () => { truncated = true; killStreamChildren(stream) },
|
|
1419
|
+
})
|
|
1420
|
+
const take = (index, path) => {
|
|
1421
|
+
files += 1
|
|
1422
|
+
if (needle !== '' && path.toLowerCase().indexOf(needle) === -1) return
|
|
1423
|
+
emitter.push(index, [path])
|
|
1424
|
+
}
|
|
1425
|
+
if (roots.length === 0 || gitMissing === true) {
|
|
1426
|
+
// No repo anywhere (or no git binary): walk and page the fallback listing.
|
|
1427
|
+
const all = await listRawFiles(cwd)
|
|
1428
|
+
const matches = []
|
|
1429
|
+
for (const path of all) {
|
|
1430
|
+
files += 1
|
|
1431
|
+
if (needle !== '' && path.toLowerCase().indexOf(needle) === -1) continue
|
|
1432
|
+
matches.push(path)
|
|
1433
|
+
if (matches.length >= limit) { truncated = true; break }
|
|
1434
|
+
}
|
|
1435
|
+
for (let offset = 0; offset < matches.length; offset += pageSize) onPage(matches.slice(offset, offset + pageSize))
|
|
1436
|
+
return { files, count: matches.length, truncated }
|
|
1437
|
+
}
|
|
1438
|
+
await forEachRootInParallel(roots, SEARCH_STREAM_CONCURRENCY, async (root, index) => {
|
|
1439
|
+
if (emitter.isClosed()) { emitter.finish(index); return }
|
|
1440
|
+
let rest = ''
|
|
1441
|
+
const consume = (relativePath) => {
|
|
1442
|
+
if (relativePath === '' || emitter.isClosed()) return
|
|
1443
|
+
take(index, join(root, relativePath))
|
|
1444
|
+
}
|
|
1445
|
+
try {
|
|
1446
|
+
await streamGitStdout(['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--'], root, (chunk) => {
|
|
1447
|
+
const parts = `${rest}${chunk}`.split('\0')
|
|
1448
|
+
rest = parts.pop() ?? ''
|
|
1449
|
+
for (const relativePath of parts) consume(relativePath)
|
|
1450
|
+
}, stream)
|
|
1451
|
+
} catch {
|
|
1452
|
+
// git disappeared mid-search: walking this root keeps the answer usable.
|
|
1453
|
+
const all = await listRawFiles(root)
|
|
1454
|
+
for (const path of all) {
|
|
1455
|
+
if (emitter.isClosed()) break
|
|
1456
|
+
take(index, path)
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
consume(rest)
|
|
1460
|
+
emitter.finish(index)
|
|
1461
|
+
})
|
|
1462
|
+
return { files, count: emitter.total(), truncated }
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
/**
|
|
1466
|
+
* Streaming content search: one `git grep` per repo root, run in parallel, with
|
|
1467
|
+
* the same literal matching / per-file cap / ordering as
|
|
1468
|
+
* {@link searchWorkspaceContent}.
|
|
1469
|
+
* @param cwd - workspace root (fallback walk).
|
|
1470
|
+
* @param roots - repo roots.
|
|
1471
|
+
* @param query - literal text.
|
|
1472
|
+
* @param options - `{ limit, perFile, pageSize, onPage, stream }`.
|
|
1473
|
+
* @returns `{ files, count, truncated }` when every root answered.
|
|
1474
|
+
*/
|
|
1475
|
+
async function searchWorkspaceContentStream(cwd, roots, query, options) {
|
|
1476
|
+
const { limit, perFile, pageSize, onPage, stream } = options
|
|
1477
|
+
const needle = String(query ?? '')
|
|
1478
|
+
const paths = new Set()
|
|
1479
|
+
let truncated = false
|
|
1480
|
+
// Same rule as the filename search: the limit applies to the emitted root order.
|
|
1481
|
+
const emitter = createOrderedPages(roots.length, pageSize, onPage, {
|
|
1482
|
+
maxItems: limit,
|
|
1483
|
+
onFull: () => { truncated = true; killStreamChildren(stream) },
|
|
1484
|
+
})
|
|
1485
|
+
const take = (index, hit) => {
|
|
1486
|
+
paths.add(hit.path)
|
|
1487
|
+
emitter.push(index, [hit])
|
|
1488
|
+
}
|
|
1489
|
+
if (roots.length === 0 || gitMissing === true) {
|
|
1490
|
+
const fallback = await searchContentRaw(cwd, needle, limit, perFile)
|
|
1491
|
+
const hits = fallback.hits
|
|
1492
|
+
for (let offset = 0; offset < hits.length; offset += pageSize) onPage(hits.slice(offset, offset + pageSize))
|
|
1493
|
+
return { files: fallback.files, count: hits.length, truncated: fallback.truncated }
|
|
1494
|
+
}
|
|
1495
|
+
await forEachRootInParallel(roots, SEARCH_STREAM_CONCURRENCY, async (root, index) => {
|
|
1496
|
+
if (emitter.isClosed()) { emitter.finish(index); return }
|
|
1497
|
+
let rest = ''
|
|
1498
|
+
const consume = (raw) => {
|
|
1499
|
+
if (raw === '' || emitter.isClosed()) return
|
|
1500
|
+
const hit = parseGitGrepLine(root, raw)
|
|
1501
|
+
if (hit !== undefined) take(index, hit)
|
|
1502
|
+
}
|
|
1503
|
+
try {
|
|
1504
|
+
await streamGitStdout(['grep', '-n', '-I', '--no-color', '-F', '-m', String(perFile), '-e', needle, '--'], root, (chunk) => {
|
|
1505
|
+
const lines = `${rest}${chunk}`.split('\n')
|
|
1506
|
+
rest = lines.pop() ?? ''
|
|
1507
|
+
for (const raw of lines) consume(raw)
|
|
1508
|
+
}, stream)
|
|
1509
|
+
} catch {
|
|
1510
|
+
// A failing root is skipped, never fatal (same rule as the batch search).
|
|
1511
|
+
}
|
|
1512
|
+
consume(rest)
|
|
1513
|
+
emitter.finish(index)
|
|
1514
|
+
})
|
|
1515
|
+
return { files: paths.size, count: emitter.total(), truncated }
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
/**
|
|
1519
|
+
* One STREAMED search: NDJSON frames over a chunked response.
|
|
1520
|
+
*
|
|
1521
|
+
* Frames: `{type:'start',root,roots}` then `{type:'page',items:[...]}` (one per
|
|
1522
|
+
* page, in root order) and finally `{type:'done',files,matches,truncated}` —
|
|
1523
|
+
* or `{type:'error',code,message}` when the search failed after the headers.
|
|
1524
|
+
* A client disconnect aborts the git children of this request.
|
|
1525
|
+
* @param ctx - Host context (session cwd lookup).
|
|
1526
|
+
* @param req - Node request face.
|
|
1527
|
+
* @param res - Node response face.
|
|
1528
|
+
* @param options - `{ restrictToCwd }` (see {@link apply}).
|
|
1529
|
+
* @param content - `true` for content hits, `false` for filenames.
|
|
1530
|
+
*/
|
|
1531
|
+
async function serveSearchStream(ctx, req, res, options, content) {
|
|
1532
|
+
let finished = false
|
|
1533
|
+
const stream = { aborted: false, children: new Set() }
|
|
1534
|
+
const write = (payload) => {
|
|
1535
|
+
if (finished === true || res.writableEnded === true) return
|
|
1536
|
+
res.write(`${JSON.stringify(payload)}\n`)
|
|
1537
|
+
}
|
|
1538
|
+
const finish = (payload) => {
|
|
1539
|
+
if (finished === true) return
|
|
1540
|
+
finished = true
|
|
1541
|
+
if (res.writableEnded === true) return
|
|
1542
|
+
res.end(`${JSON.stringify(payload)}\n`)
|
|
1543
|
+
}
|
|
1544
|
+
try {
|
|
1545
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
1546
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
1547
|
+
const sessionId = url.searchParams.get('sessionId') ?? ''
|
|
1548
|
+
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
1549
|
+
const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd'))
|
|
1550
|
+
const query = url.searchParams.get('q') ?? ''
|
|
1551
|
+
if (content && query.trim() === '') throw new TailError('bad-request', 'q (the text to search for) is required', 400)
|
|
1552
|
+
const rawLimit = Number(url.searchParams.get('limit') ?? '300')
|
|
1553
|
+
const limit = content
|
|
1554
|
+
? (Number.isFinite(rawLimit) ? Math.min(Math.max(1, Math.floor(rawLimit)), CONTENT_SEARCH_MAX_HITS) : 300)
|
|
1555
|
+
: (Number.isFinite(rawLimit) ? Math.min(Math.max(1, Math.floor(rawLimit)), 2000) : 300)
|
|
1556
|
+
const rawPerFile = Number(url.searchParams.get('perFile') ?? '8')
|
|
1557
|
+
const perFile = Number.isFinite(rawPerFile) ? Math.min(Math.max(1, Math.floor(rawPerFile)), CONTENT_SEARCH_MAX_PER_FILE) : 8
|
|
1558
|
+
const rawPageSize = Number(url.searchParams.get('pageSize') ?? String(SEARCH_STREAM_PAGE_DEFAULT))
|
|
1559
|
+
const pageSize = Number.isFinite(rawPageSize) ? Math.min(Math.max(1, Math.floor(rawPageSize)), SEARCH_STREAM_PAGE_MAX) : SEARCH_STREAM_PAGE_DEFAULT
|
|
1560
|
+
const roots = await searchRoots(cwd)
|
|
1561
|
+
res.writeHead(200, {
|
|
1562
|
+
'content-type': 'application/x-ndjson; charset=utf-8',
|
|
1563
|
+
'cache-control': 'no-store',
|
|
1564
|
+
'x-accel-buffering': 'no',
|
|
1565
|
+
})
|
|
1566
|
+
res.on('close', () => {
|
|
1567
|
+
if (finished === true) return
|
|
1568
|
+
stream.aborted = true
|
|
1569
|
+
for (const child of stream.children) {
|
|
1570
|
+
try { child.kill('SIGTERM') } catch { /* already gone */ }
|
|
1571
|
+
}
|
|
1572
|
+
})
|
|
1573
|
+
write({ type: 'start', root: cwd, repoCount: roots.length })
|
|
1574
|
+
const onPage = (items) => write({ type: 'page', items })
|
|
1575
|
+
const result = content
|
|
1576
|
+
? await searchWorkspaceContentStream(cwd, roots, query, { limit, perFile, pageSize, onPage, stream })
|
|
1577
|
+
: await searchWorkspaceFilesStream(cwd, roots, query, { limit, pageSize, onPage, stream })
|
|
1578
|
+
finish({ type: 'done', files: result.files, matches: result.count, truncated: result.truncated })
|
|
1579
|
+
} catch (error) {
|
|
1580
|
+
if (finished === true) return
|
|
1581
|
+
if (res.writableEnded !== true && res.headersSent !== true) { writeTailError(res, error); return }
|
|
1582
|
+
finish({ type: 'error', code: error?.code ?? 'error', message: error?.message ?? 'search failed' })
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1034
1586
|
/** Cache of one repo root's allowed file paths (gitignore-aware), 5s TTL. */
|
|
1035
1587
|
const TREE_ALLOWED_CACHE = new Map()
|
|
1036
1588
|
/** Repo listing caches invalidated in the last second (coalesces save storms). */
|
|
@@ -1486,6 +2038,10 @@ async function listIdeTree(target, cwd, options) {
|
|
|
1486
2038
|
const ignoredDirs = await ignoredTreeDirs(repo ?? '', unknownDirs)
|
|
1487
2039
|
const entries = []
|
|
1488
2040
|
for (const dirent of dirents) {
|
|
2041
|
+
// A chunked save stages the document in `<file>.dsh-ris-ide-saving` next to
|
|
2042
|
+
// its target (same directory ⇒ the rename is atomic). It exists for a few
|
|
2043
|
+
// milliseconds, and after a crash it may linger: never show it as a tree row.
|
|
2044
|
+
if (dirent.name.endsWith(FS_WRITE_TEMP_SUFFIX)) continue
|
|
1489
2045
|
// `.dsh-ris-ide/` holds the undo trash, the dependency-source cache and the
|
|
1490
2046
|
// clipboard staging batches: implementation details, never tree rows — and
|
|
1491
2047
|
// hidden in BOTH filter modes, like the trash row it replaced.
|
|
@@ -2197,12 +2753,12 @@ function delay(ms) {
|
|
|
2197
2753
|
* @param req - Node request face (async iterable).
|
|
2198
2754
|
* @returns the parsed object (empty object for an empty body).
|
|
2199
2755
|
*/
|
|
2200
|
-
async function readJsonBody(req) {
|
|
2756
|
+
async function readJsonBody(req, limitBytes = MAX_BODY_BYTES, tooLargeMessage = 'request body too large') {
|
|
2201
2757
|
let size = 0
|
|
2202
2758
|
const chunks = []
|
|
2203
2759
|
for await (const chunk of req) {
|
|
2204
2760
|
size += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.length
|
|
2205
|
-
if (size >
|
|
2761
|
+
if (size > limitBytes) throw new TailError('bad-request', tooLargeMessage, 413)
|
|
2206
2762
|
chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)
|
|
2207
2763
|
}
|
|
2208
2764
|
if (size === 0) return {}
|
|
@@ -3657,6 +4213,42 @@ async function serveTextWindow(res, target, info, url) {
|
|
|
3657
4213
|
writeJson(res, 200, { ok: true, kind: 'text-window', offset: from, next, eof: next >= info.size, size: info.size, mtimeMs: info.mtimeMs, text })
|
|
3658
4214
|
}
|
|
3659
4215
|
|
|
4216
|
+
/** Suffix of the sibling file a chunked save is staged in before the rename. */
|
|
4217
|
+
const FS_WRITE_TEMP_SUFFIX = '.dsh-ris-ide-saving'
|
|
4218
|
+
|
|
4219
|
+
/**
|
|
4220
|
+
* Write ONE chunk of a chunked `POST /fs/write`.
|
|
4221
|
+
*
|
|
4222
|
+
* The chunks land in `<target>.dsh-ris-ide-saving` at their byte offset (so a
|
|
4223
|
+
* retried chunk overwrites itself instead of appending twice) and only the chunk
|
|
4224
|
+
* with `final !== false` truncates to `offset + bytes` and renames the temp file
|
|
4225
|
+
* over the target. A reader therefore sees the old file or the new one, never a
|
|
4226
|
+
* half-written mixed document, and a failed save leaves the target untouched.
|
|
4227
|
+
*
|
|
4228
|
+
* @param target - absolute path the editor is saving.
|
|
4229
|
+
* @param body - `{content, offset, final}` from the request.
|
|
4230
|
+
*/
|
|
4231
|
+
async function writeChunk(target, body) {
|
|
4232
|
+
const offset = body.offset
|
|
4233
|
+
if (!Number.isInteger(offset) || offset < 0) throw new TailError('bad-request', 'offset must be a non-negative integer', 400)
|
|
4234
|
+
const buffer = Buffer.from(body.content, 'utf8')
|
|
4235
|
+
const staging = `${target}${FS_WRITE_TEMP_SUFFIX}`
|
|
4236
|
+
if (offset === 0) await writeFile(staging, '')
|
|
4237
|
+
// Chunks must be contiguous: a lost chunk would otherwise leave zero bytes in
|
|
4238
|
+
// the middle of the document, which is worse than refusing the save.
|
|
4239
|
+
const present = offset === 0 ? { size: 0 } : await stat(staging).catch(() => undefined)
|
|
4240
|
+
if (present === undefined) throw new TailError('chunk-out-of-order', 'the previous chunk never arrived; save again', 409)
|
|
4241
|
+
if (present.size !== offset) throw new TailError('chunk-out-of-order', 'a chunk is missing; save again', 409)
|
|
4242
|
+
const handle = await open(staging, 'r+')
|
|
4243
|
+
try {
|
|
4244
|
+
await handle.write(buffer, 0, buffer.length, offset)
|
|
4245
|
+
if (body.final !== false) await handle.truncate(offset + buffer.length)
|
|
4246
|
+
} finally {
|
|
4247
|
+
await handle.close()
|
|
4248
|
+
}
|
|
4249
|
+
if (body.final !== false) await rename(staging, target)
|
|
4250
|
+
}
|
|
4251
|
+
|
|
3660
4252
|
/**
|
|
3661
4253
|
* The IDE's own workspace file API — no `dsh-better-sidebar` involved.
|
|
3662
4254
|
*
|
|
@@ -3664,6 +4256,9 @@ async function serveTextWindow(res, target, info, url) {
|
|
|
3664
4256
|
* or `{ok:true, kind:'binary'|'too-large', size, message}` (the caller decides
|
|
3665
4257
|
* how to render those).
|
|
3666
4258
|
* - `POST /fs/write` `{sessionId, path, cwd?, content}` → `{ok, mtimeMs}`.
|
|
4259
|
+
* With `{offset, final}` it is ONE CHUNK of a chunked save: the bytes are written
|
|
4260
|
+
* at `offset` into a sibling temp file and the LAST chunk renames it over the
|
|
4261
|
+
* target, so a save is never seen half-written and has no practical size cap.
|
|
3667
4262
|
* - `GET /fs/file?sessionId&path` → raw bytes with the media content-type.
|
|
3668
4263
|
*
|
|
3669
4264
|
* All three are loopback-fenced and resolve the path exactly like `/tail` does.
|
|
@@ -3674,7 +4269,12 @@ async function serveFs(ctx, req, res, options) {
|
|
|
3674
4269
|
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
3675
4270
|
const pathname = url.pathname
|
|
3676
4271
|
if (pathname === FS_WRITE_PATH) {
|
|
3677
|
-
|
|
4272
|
+
// A save carries the entire document: give this one route its own (much
|
|
4273
|
+
// larger) cap and say so in Chinese when even that is exceeded.
|
|
4274
|
+
const writeCap = typeof options?.maxWriteBytes === 'number' && options.maxWriteBytes > 0
|
|
4275
|
+
? options.maxWriteBytes
|
|
4276
|
+
: FS_WRITE_MAX_BODY_BYTES
|
|
4277
|
+
const body = await readJsonBody(req, writeCap, `文件太大(超过 ${Math.floor(writeCap / (1024 * 1024))} MB),不能在这里保存;请改用其他编辑器`)
|
|
3678
4278
|
const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
|
|
3679
4279
|
const raw = typeof body.path === 'string' ? body.path : ''
|
|
3680
4280
|
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
@@ -3684,6 +4284,21 @@ async function serveFs(ctx, req, res, options) {
|
|
|
3684
4284
|
const target = resolvePath(cwd, raw, options?.restrictToCwd === true)
|
|
3685
4285
|
const info = await stat(target).catch(() => undefined)
|
|
3686
4286
|
if (info !== undefined && !info.isFile()) throw new TailError('not-a-file', `"${target}" is not a regular file`, 400)
|
|
4287
|
+
// Chunked saves are marked by `offset`; every other request keeps the old
|
|
4288
|
+
// one-shot behaviour. Both paths end with a rename-free / rename-based
|
|
4289
|
+
// write of exactly the bytes the editor held.
|
|
4290
|
+
if (typeof body.offset === 'number' && Number.isFinite(body.offset)) {
|
|
4291
|
+
await writeChunk(target, body)
|
|
4292
|
+
const afterChunk = await stat(target).catch(() => undefined)
|
|
4293
|
+
writeJson(res, 200, {
|
|
4294
|
+
ok: true,
|
|
4295
|
+
path: target,
|
|
4296
|
+
chunked: true,
|
|
4297
|
+
final: body.final !== false,
|
|
4298
|
+
mtimeMs: afterChunk === undefined ? undefined : afterChunk.mtimeMs,
|
|
4299
|
+
})
|
|
4300
|
+
return
|
|
4301
|
+
}
|
|
3687
4302
|
await writeFile(target, body.content, 'utf8')
|
|
3688
4303
|
const after = await stat(target).catch(() => undefined)
|
|
3689
4304
|
writeJson(res, 200, { ok: true, path: target, mtimeMs: after === undefined ? undefined : after.mtimeMs })
|
|
@@ -4718,6 +5333,785 @@ async function serveSettings(ctx, req, res, options) {
|
|
|
4718
5333
|
}
|
|
4719
5334
|
}
|
|
4720
5335
|
|
|
5336
|
+
|
|
5337
|
+
/**
|
|
5338
|
+
* Short, stable fingerprint of the machine-wide table.
|
|
5339
|
+
*
|
|
5340
|
+
* The dialog posts the WHOLE table, so two windows (or two people) editing at once
|
|
5341
|
+
* would silently overwrite each other: whoever saves last wins and the other row is
|
|
5342
|
+
* gone with no error. The fingerprint travels with the write, so a stale payload is
|
|
5343
|
+
* refused (409) instead of applied.
|
|
5344
|
+
* @param config - a normalised proxy config.
|
|
5345
|
+
* @returns a 12-char hex fingerprint of everything the dialog can change.
|
|
5346
|
+
*/
|
|
5347
|
+
export function configRevision(config) {
|
|
5348
|
+
const view = {
|
|
5349
|
+
socks: [String(config?.socks?.host ?? ''), Number(config?.socks?.port ?? 0)],
|
|
5350
|
+
listenPort: Number(config?.listenPort ?? 0),
|
|
5351
|
+
rules: (Array.isArray(config?.rules) ? config.rules : []).map((rule) => [
|
|
5352
|
+
String(rule.id ?? ''),
|
|
5353
|
+
String(rule.program ?? ''),
|
|
5354
|
+
String(rule.hosts ?? ''),
|
|
5355
|
+
String(rule.ports ?? ''),
|
|
5356
|
+
rule.enabled === true,
|
|
5357
|
+
rule.shadow === true,
|
|
5358
|
+
String(rule.source ?? ''),
|
|
5359
|
+
]),
|
|
5360
|
+
}
|
|
5361
|
+
return createHash('sha1').update(JSON.stringify(view)).digest('hex').slice(0, 12)
|
|
5362
|
+
}
|
|
5363
|
+
|
|
5364
|
+
/**
|
|
5365
|
+
* One stored rule, decorated with what the engine will actually make of it: the
|
|
5366
|
+
* parsed host patterns / ports plus the fragments it rejected, so the dialog can
|
|
5367
|
+
* flag a typo instead of silently dropping a destination.
|
|
5368
|
+
* @param rule - a rule from the normalised config.
|
|
5369
|
+
* @returns the rule plus `hostsParsed|hostsInvalid|portsParsed|portsInvalid`.
|
|
5370
|
+
*/
|
|
5371
|
+
function decorateProxyRule(rule) {
|
|
5372
|
+
const hosts = parseHostSpec(rule.hosts)
|
|
5373
|
+
const ports = parsePortSpec(rule.ports)
|
|
5374
|
+
// A shadow is a loopback LISTENER, so it needs ports it can actually bind: `*`
|
|
5375
|
+
// parses to port 0 ("any port"), which must not make a rule sweepable here.
|
|
5376
|
+
const bindable = ports.ports.filter((port) => port > 0)
|
|
5377
|
+
const shadowable = hosts.patterns.length > 0 && hosts.patterns.every((pattern) => /^\d{1,3}(\.\d{1,3}){3}$/.test(pattern)) && bindable.length > 0
|
|
5378
|
+
const socksCapable = isSocksCapableProgram(rule.program)
|
|
5379
|
+
const verdict = ruleEffectiveness(rule)
|
|
5380
|
+
return Object.assign({}, rule, {
|
|
5381
|
+
hostsParsed: hosts.patterns,
|
|
5382
|
+
hostsInvalid: hosts.invalid,
|
|
5383
|
+
portsParsed: ports.ports,
|
|
5384
|
+
portsInvalid: ports.invalid,
|
|
5385
|
+
// What the rule can do is NOT the same for both mechanisms: only a literal
|
|
5386
|
+
// IPv4 destination can be pre-bound on a loopback port, and a wildcard can
|
|
5387
|
+
// only be matched per connection (the CONNECT proxy).
|
|
5388
|
+
shadowable,
|
|
5389
|
+
// Which mechanism this program actually needs — the dialog shows it and the
|
|
5390
|
+
// engine defaults the mapping flag from it (SOCKS-aware programs need none,
|
|
5391
|
+
// everything else can only reach the tunnel through a mapped port).
|
|
5392
|
+
socksCapable,
|
|
5393
|
+
autoShadow: shadowable && !socksCapable,
|
|
5394
|
+
// A rule applies only when enabled AND program/IP/port are all explicit
|
|
5395
|
+
// (`*` spells "everything"); the dialog marks the others instead of letting a
|
|
5396
|
+
// half-written row look active.
|
|
5397
|
+
effective: verdict.effective,
|
|
5398
|
+
ineffectiveReason: verdict.reason,
|
|
5399
|
+
// The rule table is machine-wide (ProxyBridge hooks the kernel and matches
|
|
5400
|
+
// processes), so a row's workspace is provenance only: the dialog shows it
|
|
5401
|
+
// as「来源」 and never treats it as a boundary.
|
|
5402
|
+
origin: rule.workspace === '' ? '' : basename(rule.workspace),
|
|
5403
|
+
})
|
|
5404
|
+
}
|
|
5405
|
+
|
|
5406
|
+
/** Companion-plugin hints: `dsh-ris-yds` assists YonBIP/YMS development (local
|
|
5407
|
+
* runtime, intranet access, development config). Only the capabilities are
|
|
5408
|
+
* named here — never its internals, and never the tools it happens to patch.
|
|
5409
|
+
* We only RECOMMEND it when the workspace really looks like a YMS project: the
|
|
5410
|
+
* two plugins stay usable standalone, so this must never turn into a
|
|
5411
|
+
* requirement (and it must never guess on a plain Java/Vue repo). */
|
|
5412
|
+
function detectCompanionPlugin(cwd) {
|
|
5413
|
+
const evidence = []
|
|
5414
|
+
try {
|
|
5415
|
+
if (existsSync(join(cwd, 'yms-home'))) evidence.push('yms-home/')
|
|
5416
|
+
if (existsSync(join(cwd, '.dsh-ris-yds'))) evidence.push('.dsh-ris-yds/')
|
|
5417
|
+
if (evidence.length === 0) {
|
|
5418
|
+
const settings = join(cwd, '.vscode', 'settings.json')
|
|
5419
|
+
if (existsSync(settings) && readFileSync(settings, 'utf8').includes('"yds.')) {
|
|
5420
|
+
evidence.push('.vscode/settings.json (yds.*)')
|
|
5421
|
+
}
|
|
5422
|
+
}
|
|
5423
|
+
} catch {
|
|
5424
|
+
// Detection is best effort: an unreadable workspace simply gets no hint.
|
|
5425
|
+
}
|
|
5426
|
+
if (evidence.length === 0) return null
|
|
5427
|
+
return {
|
|
5428
|
+
plugin: 'dsh-ris-yds',
|
|
5429
|
+
detected: evidence.join(', '),
|
|
5430
|
+
hint: '检测到 YonBIP/YMS 工程:dsh-ris-yds 提供本地运行 YMS、访问内网资源、准备开发配置等辅助开发能力(可选,不装不影响本插件)。',
|
|
5431
|
+
}
|
|
5432
|
+
}
|
|
5433
|
+
|
|
5434
|
+
/**
|
|
5435
|
+
* The whole proxy state the dialog needs, in ONE round trip: rules (decorated),
|
|
5436
|
+
* upstream address, engine state, and the scoped git entry it would write.
|
|
5437
|
+
* @param cwd - workspace directory.
|
|
5438
|
+
* @param gitHost - optional host to narrow the git entry to.
|
|
5439
|
+
* @returns a JSON-safe view.
|
|
5440
|
+
*/
|
|
5441
|
+
async function proxyView(cwd, gitHost) {
|
|
5442
|
+
const status = await proxyStatus(cwd)
|
|
5443
|
+
const allow = allowList(status.config)
|
|
5444
|
+
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
|
+
const watcher = janitorStatus()
|
|
5456
|
+
// An engine adopted from a PREVIOUS dsh process (see adoptLeftoverEngine): the
|
|
5457
|
+
// dialog shows a takeover banner with a one-click stop instead of pretending this
|
|
5458
|
+
// session started it. The flag is dropped as soon as that engine is gone.
|
|
5459
|
+
const inherited = inheritedEngine !== null && inheritedEngine.pid === status.pid ? inheritedEngine : null
|
|
5460
|
+
return {
|
|
5461
|
+
ok: true,
|
|
5462
|
+
side: engineSide(),
|
|
5463
|
+
// The dialog sends this back with its save, so a table edited in another window
|
|
5464
|
+
// is refused instead of silently overwritten.
|
|
5465
|
+
revision: configRevision(status.config),
|
|
5466
|
+
// ONE engine and ONE config per machine: the path is not workspace-derived.
|
|
5467
|
+
configPath: proxyConfigPath(),
|
|
5468
|
+
home: proxyHomeDir(),
|
|
5469
|
+
shared: true,
|
|
5470
|
+
workspace: cwd,
|
|
5471
|
+
socks: status.config.socks,
|
|
5472
|
+
listenPort: status.config.listenPort,
|
|
5473
|
+
rules: (await Promise.all(status.config.rules.map(async (rule) => {
|
|
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 }))),
|
|
5488
|
+
running: status.running,
|
|
5489
|
+
pid: status.pid,
|
|
5490
|
+
listen: status.listen,
|
|
5491
|
+
logPath: status.logPath,
|
|
5492
|
+
socksUrl: status.socksUrl,
|
|
5493
|
+
allow,
|
|
5494
|
+
git,
|
|
5495
|
+
// ProxyBridge is the PRIMARY path (kernel hook, matches by process name, so
|
|
5496
|
+
// it covers programs we never launched); the engine's loopback mappings and
|
|
5497
|
+
// the spawn-time injection remain as the fallback when it is not running.
|
|
5498
|
+
redirector: Object.assign(redirectorStatusCached(), {
|
|
5499
|
+
// What the CLI would be told to do, so the dialog can show the exact
|
|
5500
|
+
// command instead of asking the user to assemble one.
|
|
5501
|
+
rules: buildProfile(status.config).rules.length,
|
|
5502
|
+
}),
|
|
5503
|
+
// Watchdog state: it is what removes the layers if dsh itself is killed.
|
|
5504
|
+
janitor: watcher,
|
|
5505
|
+
// Who owns the child services right now (0 = no watcher state at all).
|
|
5506
|
+
owner: watcher.owner,
|
|
5507
|
+
// Takeover of a leftover engine (pid + the dsh that started it, 0 = unknown).
|
|
5508
|
+
inherited: inherited !== null,
|
|
5509
|
+
inheritedPid: inherited === null ? 0 : inherited.pid,
|
|
5510
|
+
inheritedFrom: inherited === null ? 0 : inherited.owner,
|
|
5511
|
+
inheritedSince: inherited === null ? '' : inherited.detectedAt,
|
|
5512
|
+
}
|
|
5513
|
+
}
|
|
5514
|
+
|
|
5515
|
+
/**
|
|
5516
|
+
* Where a rule's 启动/停止 button keeps its log.
|
|
5517
|
+
*
|
|
5518
|
+
* A separate directory, not `.dsh-ris-ide/logs`: those logs are scanned as panel
|
|
5519
|
+
* rows, and a program we started only to proxy it should not appear as a third
|
|
5520
|
+
* copy of itself in the program list.
|
|
5521
|
+
* @param cwd - workspace the rule belongs to.
|
|
5522
|
+
* @param ruleId - the rule's id (already validated as a plain string).
|
|
5523
|
+
* @returns absolute log path.
|
|
5524
|
+
*/
|
|
5525
|
+
function proxyRunLogPath(cwd, ruleId) {
|
|
5526
|
+
const slug = String(ruleId).replace(/[^A-Za-z0-9._-]+/g, '_').slice(0, 80)
|
|
5527
|
+
return join(cwd, '.dsh-ris-ide', 'proxy-run', `${slug}.log`)
|
|
5528
|
+
}
|
|
5529
|
+
|
|
5530
|
+
/**
|
|
5531
|
+
* Build the program row `startProgram` needs, out of one rule.
|
|
5532
|
+
*
|
|
5533
|
+
* The row is synthesised rather than scanned: the dialog's rule is the source of
|
|
5534
|
+
* truth (it names an absolute executable or a bare program on PATH), and the
|
|
5535
|
+
* start path only has to know how to run it under the wrapper.
|
|
5536
|
+
* @param cwd - workspace (log location + default working directory).
|
|
5537
|
+
* @param rule - one decorated proxy rule.
|
|
5538
|
+
* @returns the program row.
|
|
5539
|
+
*/
|
|
5540
|
+
function proxyRunProgram(cwd, rule) {
|
|
5541
|
+
const logPath = proxyRunLogPath(cwd, rule.id)
|
|
5542
|
+
const command = String(rule.program ?? '').trim()
|
|
5543
|
+
return {
|
|
5544
|
+
id: `proxy-run:${rule.id}`,
|
|
5545
|
+
name: programKey(command) || 'program',
|
|
5546
|
+
dir: cwd,
|
|
5547
|
+
// Absolute paths and bare names both work; quote so a path with spaces stays
|
|
5548
|
+
// one argument for the shell wrapper.
|
|
5549
|
+
startCommand: quoteShell(command),
|
|
5550
|
+
logName: basename(logPath, '.log'),
|
|
5551
|
+
logPath,
|
|
5552
|
+
stopGraceMs: 5000,
|
|
5553
|
+
running: null,
|
|
5554
|
+
kind: 'custom',
|
|
5555
|
+
}
|
|
5556
|
+
}
|
|
5557
|
+
|
|
5558
|
+
/** `GET` reads the proxy state, `POST` validates + saves the form. */
|
|
5559
|
+
async function serveProxy(ctx, req, res, options) {
|
|
5560
|
+
try {
|
|
5561
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
5562
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
5563
|
+
const method = req.method ?? 'GET'
|
|
5564
|
+
if (method === 'POST') {
|
|
5565
|
+
const body = await readJsonBody(req)
|
|
5566
|
+
const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
|
|
5567
|
+
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
5568
|
+
const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
|
|
5569
|
+
// The dialog shows the WHOLE machine-wide table, so its payload is
|
|
5570
|
+
// authoritative for the rows a human owns (source user/auto): a row the
|
|
5571
|
+
// payload no longer carries was deleted. Driven rows (source yds) are owned
|
|
5572
|
+
// by the bridge, which upserts them by id and retires them itself.
|
|
5573
|
+
const incoming = body.config !== null && typeof body.config === 'object' ? body.config : {}
|
|
5574
|
+
const stored = readProxyConfig(cwd)
|
|
5575
|
+
// Optimistic concurrency: the payload names the table it was rendered from.
|
|
5576
|
+
// An empty/absent revision is accepted (the CLI writes without one), but a
|
|
5577
|
+
// MISMATCH means someone else changed the table in between — refuse and hand
|
|
5578
|
+
// the current view back, so the dialog reloads instead of dropping their rows.
|
|
5579
|
+
const baseRevision = typeof body.revision === 'string' ? body.revision.trim() : ''
|
|
5580
|
+
const currentRevision = configRevision(stored)
|
|
5581
|
+
if (baseRevision !== '' && baseRevision !== currentRevision) {
|
|
5582
|
+
const view = await proxyView(cwd)
|
|
5583
|
+
writeJson(res, 409, {
|
|
5584
|
+
ok: false,
|
|
5585
|
+
conflict: true,
|
|
5586
|
+
code: 'conflict',
|
|
5587
|
+
message: '规则表已在别处被修改,本次改动未写入',
|
|
5588
|
+
revision: currentRevision,
|
|
5589
|
+
view,
|
|
5590
|
+
})
|
|
5591
|
+
return
|
|
5592
|
+
}
|
|
5593
|
+
const rows = Array.isArray(incoming.rules)
|
|
5594
|
+
? incoming.rules
|
|
5595
|
+
.filter((rule) => rule !== null && typeof rule === 'object')
|
|
5596
|
+
.map((rule) => Object.assign({}, rule, { workspace: rule.workspace ?? cwd }))
|
|
5597
|
+
: []
|
|
5598
|
+
const keptIds = new Set(rows.map((rule) => String(rule.id ?? '')))
|
|
5599
|
+
const retired = stored.rules
|
|
5600
|
+
.filter((rule) => rule.source !== 'yds' && !keptIds.has(rule.id))
|
|
5601
|
+
.map((rule) => rule.id)
|
|
5602
|
+
const written = mergeConfigs(
|
|
5603
|
+
Object.assign({}, stored, { rules: stored.rules.filter((rule) => !retired.includes(rule.id)) }),
|
|
5604
|
+
{ socks: incoming.socks, listenPort: incoming.listenPort, rules: rows, workspace: cwd },
|
|
5605
|
+
)
|
|
5606
|
+
writeProxyConfig(cwd, written)
|
|
5607
|
+
// Apply without a manual restart: our own engine watches proxy.json and
|
|
5608
|
+
// swaps its allow-list/listeners in place; ProxyBridge reads its profile only
|
|
5609
|
+
// at start, so the elevated watchdog restarts just that process (no UAC, the
|
|
5610
|
+
// dialog never has to ask the user to stop/start).
|
|
5611
|
+
const bridge = redirectorStatusCached()
|
|
5612
|
+
let reloadNote = ''
|
|
5613
|
+
if (bridge.running === true) {
|
|
5614
|
+
// ONE call does the whole job: ProxyBridge reads its profile only at start,
|
|
5615
|
+
// so a reload that does not rewrite the profile would relaunch the OLD rules
|
|
5616
|
+
// and still report success (that was B3). The helper writes first, then
|
|
5617
|
+
// restarts, and only claims a side was reloaded when it saw the new pid.
|
|
5618
|
+
try {
|
|
5619
|
+
const reload = await reloadRedirectorsWithProfile(cwd, { sides: ['windows', 'local'] })
|
|
5620
|
+
const done = Array.isArray(reload.reloaded) ? reload.reloaded : []
|
|
5621
|
+
const skipped = Array.isArray(reload.skipped) ? reload.skipped : []
|
|
5622
|
+
reloadNote = done.length > 0
|
|
5623
|
+
? '系统层拦截已按新规则自动重启'
|
|
5624
|
+
: `系统层拦截未重载:${skipped.map((item) => `${item.side}:${item.reason}`).join(';') || reload.reason || '未知原因'}`
|
|
5625
|
+
} catch (error) {
|
|
5626
|
+
reloadNote = `系统层拦截未重载:${error?.message ?? error}`
|
|
5627
|
+
}
|
|
5628
|
+
}
|
|
5629
|
+
const view = await proxyView(cwd, typeof body.gitHost === 'string' ? body.gitHost : undefined)
|
|
5630
|
+
writeJson(res, 200, Object.assign({}, view, { reloadNote }))
|
|
5631
|
+
return
|
|
5632
|
+
}
|
|
5633
|
+
if (method !== 'GET') throw new TailError('method-not-allowed', 'GET or POST', 405)
|
|
5634
|
+
const sessionId = url.searchParams.get('sessionId') ?? ''
|
|
5635
|
+
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
5636
|
+
const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
|
|
5637
|
+
writeJson(res, 200, await proxyView(cwd, url.searchParams.get('gitHost') ?? undefined))
|
|
5638
|
+
} catch (error) {
|
|
5639
|
+
writeTailError(res, error)
|
|
5640
|
+
}
|
|
5641
|
+
}
|
|
5642
|
+
|
|
5643
|
+
/**
|
|
5644
|
+
* Where the git proxy we wrote is remembered.
|
|
5645
|
+
*
|
|
5646
|
+
* `stop` (and the exit hook) must undo EXACTLY what `start` wrote: the key is
|
|
5647
|
+
* host-scoped when the repo has an origin, global otherwise, and clearing the
|
|
5648
|
+
* wrong one would either leave a dangling proxy or stomp the user's own setting.
|
|
5649
|
+
* @returns {string} absolute path of the state file.
|
|
5650
|
+
*/
|
|
5651
|
+
function gitProxyStatePath() {
|
|
5652
|
+
return join(proxyHomeDir(), 'git-proxy.json')
|
|
5653
|
+
}
|
|
5654
|
+
|
|
5655
|
+
/** @returns {{key: string, host: string}} the entry start wrote, or empty strings. */
|
|
5656
|
+
function readGitProxyState() {
|
|
5657
|
+
try {
|
|
5658
|
+
const raw = JSON.parse(readFileSync(gitProxyStatePath(), 'utf8'))
|
|
5659
|
+
return {
|
|
5660
|
+
key: typeof raw?.key === 'string' ? raw.key : '',
|
|
5661
|
+
host: typeof raw?.host === 'string' ? raw.host : '',
|
|
5662
|
+
}
|
|
5663
|
+
} catch {
|
|
5664
|
+
return { key: '', host: '' }
|
|
5665
|
+
}
|
|
5666
|
+
}
|
|
5667
|
+
|
|
5668
|
+
/**
|
|
5669
|
+
* Remember (or forget) the git proxy entry.
|
|
5670
|
+
* @param {{key: string, host: string}|null} state - null clears the file.
|
|
5671
|
+
*/
|
|
5672
|
+
function writeGitProxyState(state) {
|
|
5673
|
+
const path = gitProxyStatePath()
|
|
5674
|
+
if (state === null) {
|
|
5675
|
+
try { rmSync(path, { force: true }) } catch { /* nothing to clear */ }
|
|
5676
|
+
return
|
|
5677
|
+
}
|
|
5678
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
5679
|
+
writeFileSync(path, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 })
|
|
5680
|
+
}
|
|
5681
|
+
|
|
5682
|
+
/**
|
|
5683
|
+
* Host of the workspace's `origin` remote, so the proxy entry is scoped to one
|
|
5684
|
+
* server instead of being a machine-wide `http.proxy`.
|
|
5685
|
+
* @param {string} cwd - workspace root.
|
|
5686
|
+
* @returns {string} hostname, or '' when there is no readable remote.
|
|
5687
|
+
*/
|
|
5688
|
+
function gitOriginHost(cwd) {
|
|
5689
|
+
const out = spawnSync('git', ['-C', cwd, 'config', '--get', 'remote.origin.url'], {
|
|
5690
|
+
encoding: 'utf8', windowsHide: true, timeout: 4000,
|
|
5691
|
+
})
|
|
5692
|
+
if (out.status !== 0 || typeof out.stdout !== 'string') return ''
|
|
5693
|
+
try { return new URL(out.stdout.trim()).host } catch { return '' }
|
|
5694
|
+
}
|
|
5695
|
+
|
|
5696
|
+
/**
|
|
5697
|
+
* Host of the enabled `git` rule, if the table declares one.
|
|
5698
|
+
*
|
|
5699
|
+
* This is the user's own statement of "git goes to this server" (yds writes it
|
|
5700
|
+
* from `git.url`), so it outranks the workspace's `origin` — a mirror or a
|
|
5701
|
+
* proxy-fronted clone must not decide where git may tunnel to.
|
|
5702
|
+
* @param {string} cwd - workspace root (only used to find the shared config).
|
|
5703
|
+
* @returns {string} the first host pattern, or ''.
|
|
5704
|
+
*/
|
|
5705
|
+
function gitRuleHost(cwd) {
|
|
5706
|
+
const rules = readProxyConfig(cwd).rules
|
|
5707
|
+
for (const rule of rules) {
|
|
5708
|
+
if (rule.enabled !== true) continue
|
|
5709
|
+
if (programKey(rule.program) !== 'git') continue
|
|
5710
|
+
const first = String(rule.hosts ?? '').split(',')[0].trim()
|
|
5711
|
+
if (first !== '') return first
|
|
5712
|
+
}
|
|
5713
|
+
return ''
|
|
5714
|
+
}
|
|
5715
|
+
|
|
5716
|
+
/**
|
|
5717
|
+
* Write or clear the git proxy that belongs to the running tunnel.
|
|
5718
|
+
*
|
|
5719
|
+
* git reads this from its own config, so a plain `git` command in any terminal —
|
|
5720
|
+
* and the dsh-git plugin — goes through the tunnel without a per-command flag.
|
|
5721
|
+
* @param {{cwd: string, host?: string, enabled: boolean}} options - target and direction.
|
|
5722
|
+
* @returns {Promise<{ok: boolean, key?: string, error?: string}>} outcome.
|
|
5723
|
+
*/
|
|
5724
|
+
async function syncGitProxy({ cwd, host, enabled }) {
|
|
5725
|
+
const previous = readGitProxyState()
|
|
5726
|
+
if (enabled !== true) {
|
|
5727
|
+
const key = previous.key
|
|
5728
|
+
if (key === '') return { ok: true, key: '' }
|
|
5729
|
+
const cleared = await runGitConfig(['--unset', key])
|
|
5730
|
+
const windowsCleared = runWindowsGitConfig(['--unset', key])
|
|
5731
|
+
writeGitProxyState(null)
|
|
5732
|
+
return { ok: true, key, cleared: cleared.ok === true, windowsCleared: windowsCleared.ok === true }
|
|
5733
|
+
}
|
|
5734
|
+
// Precedence: an explicit host, then the table's own git rule, then whatever we
|
|
5735
|
+
// wrote last time, and only then the repo's origin (a mirror is not a target).
|
|
5736
|
+
const target = (typeof host === 'string' && host !== '')
|
|
5737
|
+
? host
|
|
5738
|
+
: (gitRuleHost(cwd) || (previous.host !== '' ? previous.host : gitOriginHost(cwd)))
|
|
5739
|
+
if (target === '') return { ok: false, error: '没有 git 规则也没有 origin,无法确定代理作用域', key: '' }
|
|
5740
|
+
// A stale entry for another host would keep a dead proxy alive for that remote.
|
|
5741
|
+
if (previous.key !== '' && previous.host !== '' && previous.host !== target) {
|
|
5742
|
+
await runGitConfig(['--unset', previous.key])
|
|
5743
|
+
writeGitProxyState(null)
|
|
5744
|
+
}
|
|
5745
|
+
const plan = gitProxyPlan(readProxyConfig(cwd), { host: target, enabled: true })
|
|
5746
|
+
if (plan.value === '') return { ok: false, error: '没有可用的 SOCKS 地址', key: plan.key }
|
|
5747
|
+
const written = await runGitConfig([plan.key, plan.value])
|
|
5748
|
+
if (written.ok !== true) return { ok: false, error: written.error, key: plan.key }
|
|
5749
|
+
// The Windows-side git reads its own config file AND cannot resolve the internal
|
|
5750
|
+
// host (its DNS knows nothing about gitlab.hanslaser.com), so socks5h has to be in
|
|
5751
|
+
// that file too — otherwise YonCode's git fails before any interception can happen.
|
|
5752
|
+
const windows = runWindowsGitConfig([plan.key, plan.value])
|
|
5753
|
+
writeGitProxyState({ key: plan.key, host: target, windows: windows.ok === true })
|
|
5754
|
+
return { ok: true, key: plan.key, host: target, windows }
|
|
5755
|
+
}
|
|
5756
|
+
|
|
5757
|
+
/** Synchronous git-proxy undo for the exit hook, which cannot await anything. */
|
|
5758
|
+
function clearGitProxySync() {
|
|
5759
|
+
const { key } = readGitProxyState()
|
|
5760
|
+
if (key === '') return
|
|
5761
|
+
try { spawnSync('git', ['config', '--global', '--unset', key], { windowsHide: true, timeout: 4000 }) } catch { /* best effort */ }
|
|
5762
|
+
// Same undo on the Windows side: leaving a dead socks address there breaks git for
|
|
5763
|
+
// every Windows tool until someone notices.
|
|
5764
|
+
try { runWindowsGitConfig(['--unset', key]) } catch { /* best effort */ }
|
|
5765
|
+
writeGitProxyState(null)
|
|
5766
|
+
}
|
|
5767
|
+
|
|
5768
|
+
/** Run one `git config --global` mutation; a missing git is a reported no-op. */
|
|
5769
|
+
function runGitConfig(args) {
|
|
5770
|
+
return new Promise((resolvePromise) => {
|
|
5771
|
+
const child = spawn('git', ['config', '--global', ...args], { windowsHide: true })
|
|
5772
|
+
let stderr = ''
|
|
5773
|
+
let settled = false
|
|
5774
|
+
const done = (result) => { if (!settled) { settled = true; resolvePromise(result) } }
|
|
5775
|
+
child.stderr?.on('data', (chunk) => { if (stderr.length < 4096) stderr += chunk.toString('utf8') })
|
|
5776
|
+
child.on('error', (error) => done({ ok: false, error: isMissingExecutable(error) ? '本机没有安装 git' : String(error?.message ?? error) }))
|
|
5777
|
+
child.on('close', (code) => done(code === 0 ? { ok: true } : { ok: false, error: stderr.trim() || `git exited with ${code}` }))
|
|
5778
|
+
})
|
|
5779
|
+
}
|
|
5780
|
+
|
|
5781
|
+
/** Start/stop the engine and write/clear the scoped git proxy entry. */
|
|
5782
|
+
async function serveProxyAction(ctx, req, res, options) {
|
|
5783
|
+
try {
|
|
5784
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
5785
|
+
const body = await readJsonBody(req)
|
|
5786
|
+
const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
|
|
5787
|
+
if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
|
|
5788
|
+
const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
|
|
5789
|
+
const action = typeof body.action === 'string' ? body.action : 'status'
|
|
5790
|
+
const gitHost = typeof body.gitHost === 'string' ? body.gitHost : undefined
|
|
5791
|
+
let result
|
|
5792
|
+
if (action === 'start') {
|
|
5793
|
+
// One button, three layers: engine (spawned children) + system-level
|
|
5794
|
+
// interception (everything else, UAC/root is the expected prompt) + the git
|
|
5795
|
+
// config entry (so a plain `git` and dsh-git inherit the tunnel). Stopping
|
|
5796
|
+
// undoes all three, and so does the host exit hook.
|
|
5797
|
+
const engine = await startProxy(cwd)
|
|
5798
|
+
const redirector = await startRedirectors()
|
|
5799
|
+
const git = await syncGitProxy({ cwd, host: gitHost, enabled: true })
|
|
5800
|
+
if (engine.ok === true) inheritedEngine = null
|
|
5801
|
+
result = Object.assign({}, engine, { redirector, git })
|
|
5802
|
+
} else if (action === 'stop') {
|
|
5803
|
+
const git = await syncGitProxy({ cwd, host: gitHost, enabled: false })
|
|
5804
|
+
const redirector = await stopRedirector()
|
|
5805
|
+
const stopped = await stopProxy(cwd)
|
|
5806
|
+
// The banner must not come back once the adopted engine is really gone.
|
|
5807
|
+
if (proxyPid() === null) inheritedEngine = null
|
|
5808
|
+
result = Object.assign({}, stopped, { redirector, git })
|
|
5809
|
+
} else if (action === 'git-on' || action === 'git-off') {
|
|
5810
|
+
const plan = gitProxyPlan(readProxyConfig(cwd), { host: gitHost, enabled: action === 'git-on' })
|
|
5811
|
+
result = action === 'git-on'
|
|
5812
|
+
? Object.assign({ key: plan.key, value: plan.value }, await runGitConfig([plan.key, plan.value]))
|
|
5813
|
+
: Object.assign({ key: plan.key }, await runGitConfig(['--unset', plan.key]))
|
|
5814
|
+
} else if (action === 'run' || action === 'run-stop') {
|
|
5815
|
+
// Start/stop the rule's program OURSELVES: injection only works on a child
|
|
5816
|
+
// process, so "配置好规则 → 点启动" is the only way to proxy a program that
|
|
5817
|
+
// the user would otherwise launch by hand.
|
|
5818
|
+
const ruleId = typeof body.ruleId === 'string' ? body.ruleId : ''
|
|
5819
|
+
if (ruleId === '') throw new TailError('bad-request', 'ruleId is required', 400)
|
|
5820
|
+
const rule = readProxyConfig(cwd).rules.find((item) => item.id === ruleId)
|
|
5821
|
+
if (rule === undefined) throw new TailError('bad-request', `没有规则 ${ruleId}`, 404)
|
|
5822
|
+
const program = proxyRunProgram(cwd, rule)
|
|
5823
|
+
if (action === 'run-stop') {
|
|
5824
|
+
result = await stopLogPath(program.logPath, options?.stopGraceMs ?? DEFAULT_STOP_GRACE_MS)
|
|
5825
|
+
} else {
|
|
5826
|
+
if (rule.enabled !== true) throw new TailError('bad-request', '规则未启用,启动后不会走代理', 400)
|
|
5827
|
+
if (String(rule.program ?? '').trim() === '') throw new TailError('bad-request', '规则还没选程序', 400)
|
|
5828
|
+
if (!isSocksCapableProgram(rule.program)) throw new TailError('bad-request', `${programKey(rule.program)} 不支持 SOCKS,只能走 127.0.0.1 映射`, 400)
|
|
5829
|
+
const started = await startProgram(cwd, dirname(program.logPath), program, options)
|
|
5830
|
+
result = { started: started.alreadyRunning !== true, program: started.program?.logPath ?? program.logPath }
|
|
5831
|
+
}
|
|
5832
|
+
} else if (action === 'redirector-sync') {
|
|
5833
|
+
// Export the machine-wide table as a ProxyBridge profile and report the
|
|
5834
|
+
// exact command. Starting it needs root/UAC, which a web route cannot ask
|
|
5835
|
+
// for, so the command is returned for the user (or an agent with rights).
|
|
5836
|
+
result = await syncRedirector(cwd, { start: false })
|
|
5837
|
+
} else if (action === 'redirector-start') {
|
|
5838
|
+
result = await syncRedirector(cwd, { start: true })
|
|
5839
|
+
} else if (action === 'redirector-stop') {
|
|
5840
|
+
result = await stopRedirector()
|
|
5841
|
+
} else if (action !== 'status') {
|
|
5842
|
+
throw new TailError('bad-request', `unknown proxy action "${action}"`, 400)
|
|
5843
|
+
}
|
|
5844
|
+
writeJson(res, 200, Object.assign({ ok: true, action, result }, await proxyView(cwd, gitHost)))
|
|
5845
|
+
} catch (error) {
|
|
5846
|
+
writeTailError(res, error)
|
|
5847
|
+
}
|
|
5848
|
+
}
|
|
5849
|
+
|
|
5850
|
+
/**
|
|
5851
|
+
* Programs the rule table offers in its picker.
|
|
5852
|
+
*
|
|
5853
|
+
* Deliberately SOCKS-aware programs only: a rule other than these cannot be
|
|
5854
|
+
* proxied by injection (its only route is a 127.0.0.1 listener, which needs no
|
|
5855
|
+
* picker entry), so offering them would promise something we cannot deliver.
|
|
5856
|
+
*/
|
|
5857
|
+
const PROXY_PROGRAM_SUGGESTIONS = ['java', 'javaw', 'mvn', 'git', 'node', 'npm', 'curl', 'python', 'python3']
|
|
5858
|
+
|
|
5859
|
+
/** Distinct program names of the processes on THIS side of the OS boundary. */
|
|
5860
|
+
function localProgramNames() {
|
|
5861
|
+
const names = new Set()
|
|
5862
|
+
if (IS_WINDOWS) return names
|
|
5863
|
+
try {
|
|
5864
|
+
for (const entry of readdirSync('/proc')) {
|
|
5865
|
+
if (!/^\d+$/.test(entry)) continue
|
|
5866
|
+
try {
|
|
5867
|
+
const commandLine = readFileSync(`/proc/${entry}/cmdline`, 'utf8')
|
|
5868
|
+
const first = commandLine.split('\0')[0]
|
|
5869
|
+
if (first !== '') names.add(basename(first))
|
|
5870
|
+
} catch { /* the process exited between readdir and read */ }
|
|
5871
|
+
}
|
|
5872
|
+
} catch { /* no /proc: the suggestions still make the picker usable */ }
|
|
5873
|
+
return names
|
|
5874
|
+
}
|
|
5875
|
+
|
|
5876
|
+
/** Program names of the WINDOWS side, via PowerShell (interop may be off). */
|
|
5877
|
+
function windowsProgramNames() {
|
|
5878
|
+
// A cold PowerShell start is 3s here and worse under load: the old 4s budget made
|
|
5879
|
+
// the picker silently drop every Windows entry. Cache it and give it room.
|
|
5880
|
+
const cached = windowsProgramCache
|
|
5881
|
+
if (cached !== null && Date.now() - cached.at < WINDOWS_PROGRAM_TTL_MS) return Promise.resolve(new Set(cached.names))
|
|
5882
|
+
return new Promise((resolvePromise) => {
|
|
5883
|
+
const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
|
|
5884
|
+
'Get-Process | Select-Object -ExpandProperty ProcessName -Unique'], { windowsHide: true })
|
|
5885
|
+
let stdout = ''
|
|
5886
|
+
let settled = false
|
|
5887
|
+
const done = (names) => { if (!settled) { settled = true; resolvePromise(names) } }
|
|
5888
|
+
child.stdout?.on('data', (chunk) => { if (stdout.length < 200000) stdout += chunk.toString('utf8') })
|
|
5889
|
+
child.on('error', () => done(new Set()))
|
|
5890
|
+
child.on('timeout', () => done(new Set()))
|
|
5891
|
+
child.on('close', () => {
|
|
5892
|
+
const names = new Set(stdout.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== ''))
|
|
5893
|
+
if (names.size > 0) windowsProgramCache = { at: Date.now(), names: [...names] }
|
|
5894
|
+
done(names)
|
|
5895
|
+
})
|
|
5896
|
+
setTimeout(() => done(new Set()), TIMEOUT_WINDOWS_PROGRAMS_MS).unref?.()
|
|
5897
|
+
})
|
|
5898
|
+
}
|
|
5899
|
+
|
|
5900
|
+
/** Last successful Windows process list (the probe is too slow to repeat per open). */
|
|
5901
|
+
let windowsProgramCache = null
|
|
5902
|
+
|
|
5903
|
+
/** Drop the cached Windows process list (tests, or after a program was installed). */
|
|
5904
|
+
export function resetWindowsProgramCache() {
|
|
5905
|
+
windowsProgramCache = null
|
|
5906
|
+
}
|
|
5907
|
+
/** How long a successful Windows process list stays usable. */
|
|
5908
|
+
const WINDOWS_PROGRAM_TTL_MS = 20000
|
|
5909
|
+
/** Budget for one PowerShell process listing (cold start alone is ~3s). */
|
|
5910
|
+
const TIMEOUT_WINDOWS_PROGRAMS_MS = 12000
|
|
5911
|
+
|
|
5912
|
+
/** `GET` the program picker's candidates (this side + Windows when reachable). */
|
|
5913
|
+
/**
|
|
5914
|
+
* List one directory for the rules table's 「固定程序」 browser.
|
|
5915
|
+
*
|
|
5916
|
+
* A rule can point at an executable that is not running yet, so the panel needs
|
|
5917
|
+
* a way to pick an absolute path — by hand typing it is error-prone, and the
|
|
5918
|
+
* workspace tree only covers one root. Directories come first; files are limited
|
|
5919
|
+
* to things that can plausibly be programs (executable bit, or a known suffix),
|
|
5920
|
+
* so a build output directory does not bury the java.exe the user came for.
|
|
5921
|
+
* @param ctx - host context.
|
|
5922
|
+
* @param req - `?path=<dir>`; missing means the platform temp/home root.
|
|
5923
|
+
* @param res - JSON response.
|
|
5924
|
+
* @param options - host options.
|
|
5925
|
+
*/
|
|
5926
|
+
async function serveProxyBrowse(ctx, req, res, options) {
|
|
5927
|
+
try {
|
|
5928
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
5929
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
5930
|
+
const sessionId = url.searchParams.get('sessionId') ?? ''
|
|
5931
|
+
const clientCwd = url.searchParams.get('cwd') ?? ''
|
|
5932
|
+
// Two file systems can hold the same rule's program: the host's own (posix) and,
|
|
5933
|
+
// from WSL, the Windows one under /mnt. `side` says which spelling the UI uses.
|
|
5934
|
+
const side = url.searchParams.get('side') === 'windows' || (IS_WINDOWS && url.searchParams.get('side') !== 'local')
|
|
5935
|
+
? 'windows'
|
|
5936
|
+
: 'local'
|
|
5937
|
+
const requested = url.searchParams.get('path') ?? ''
|
|
5938
|
+
const windowsRoots = side === 'windows' ? windowsBrowseRoots() : []
|
|
5939
|
+
// Translate the UI's spelling into something readdir understands. Keeping the
|
|
5940
|
+
// original in `display` is what lets a click write back `D:\…` instead of `/mnt/d/…`.
|
|
5941
|
+
let target
|
|
5942
|
+
let display
|
|
5943
|
+
if (side === 'windows') {
|
|
5944
|
+
const asWindows = requested !== '' && /^[A-Za-z]:[\\/]/.test(requested)
|
|
5945
|
+
const asPosix = requested.startsWith('/mnt/')
|
|
5946
|
+
if (asWindows === true) {
|
|
5947
|
+
target = windowsToPosixPath(requested)
|
|
5948
|
+
display = requested.replace(/\//g, '\\').replace(/\\+$/, '') || requested
|
|
5949
|
+
} else if (asPosix === true) {
|
|
5950
|
+
target = requested
|
|
5951
|
+
display = posixToWindowsPath(requested)
|
|
5952
|
+
} else if (requested === '') {
|
|
5953
|
+
const first = windowsRoots[0]
|
|
5954
|
+
if (first === undefined) throw new TailError('bad-request', '这台机器上没有可浏览的 Windows 盘(/mnt/<盘> 不存在)', 400)
|
|
5955
|
+
target = windowsToPosixPath(first.path)
|
|
5956
|
+
display = first.path
|
|
5957
|
+
} else {
|
|
5958
|
+
throw new TailError('bad-request', `Windows 侧需要盘符路径(如 D:\\Program Files):${requested}`, 400)
|
|
5959
|
+
}
|
|
5960
|
+
} else {
|
|
5961
|
+
// Only the host side needs a session cwd; the Windows side is absolute by nature
|
|
5962
|
+
// and must keep working when the caller has no session (CLI, tests).
|
|
5963
|
+
const root = resolveCwd(ctx, sessionId, clientCwd)
|
|
5964
|
+
target = requested === '' ? root : resolve(root, expandHome(requested))
|
|
5965
|
+
display = target
|
|
5966
|
+
}
|
|
5967
|
+
if (target === '') throw new TailError('bad-request', `无法解析路径:${requested}`, 400)
|
|
5968
|
+
|
|
5969
|
+
let entries
|
|
5970
|
+
try {
|
|
5971
|
+
entries = await readdir(target, { withFileTypes: true })
|
|
5972
|
+
} catch (error) {
|
|
5973
|
+
throw new TailError('bad-request', `无法读取目录 ${display}:${error?.code ?? error}`, 400)
|
|
5974
|
+
}
|
|
5975
|
+
const dirs = []
|
|
5976
|
+
const files = []
|
|
5977
|
+
for (const entry of entries) {
|
|
5978
|
+
if (entry.name === 'node_modules' || entry.name === '.git' || entry.name.startsWith('$')) continue
|
|
5979
|
+
const full = join(target, entry.name)
|
|
5980
|
+
const shown = side === 'windows' ? posixToWindowsPath(full) : full
|
|
5981
|
+
if (entry.isDirectory()) {
|
|
5982
|
+
dirs.push({ name: entry.name, path: shown })
|
|
5983
|
+
continue
|
|
5984
|
+
}
|
|
5985
|
+
if (!entry.isFile()) continue
|
|
5986
|
+
// On /mnt every Windows file carries the exec bit (drvfs), so the mode fallback
|
|
5987
|
+
// would list DLLs and logs; there only the suffix list is meaningful.
|
|
5988
|
+
const looksProgram = side === 'windows'
|
|
5989
|
+
? PROGRAM_SUFFIXES.some((suffix) => entry.name.toLowerCase().endsWith(suffix))
|
|
5990
|
+
: isProgramFile(full, entry.name)
|
|
5991
|
+
if (looksProgram) files.push({ name: entry.name, path: shown })
|
|
5992
|
+
}
|
|
5993
|
+
dirs.sort((a, b) => a.name.localeCompare(b.name))
|
|
5994
|
+
files.sort((a, b) => a.name.localeCompare(b.name))
|
|
5995
|
+
const parentTarget = dirname(target) === target ? null : dirname(target)
|
|
5996
|
+
writeJson(res, 200, {
|
|
5997
|
+
ok: true,
|
|
5998
|
+
side,
|
|
5999
|
+
path: display,
|
|
6000
|
+
parent: parentTarget === null ? null : (side === 'windows' ? posixToWindowsPath(parentTarget) : parentTarget),
|
|
6001
|
+
roots: side === 'windows' ? windowsRoots : browseRoots(),
|
|
6002
|
+
dirs: dirs.slice(0, 300),
|
|
6003
|
+
files: files.slice(0, 300),
|
|
6004
|
+
})
|
|
6005
|
+
} catch (error) {
|
|
6006
|
+
writeTailError(res, error)
|
|
6007
|
+
}
|
|
6008
|
+
}
|
|
6009
|
+
|
|
6010
|
+
/**
|
|
6011
|
+
* Quick-jump roots for the Windows side of the picker (opened from WSL via /mnt).
|
|
6012
|
+
* @returns {Array<{name: string, path: string}>} roots with WINDOWS paths.
|
|
6013
|
+
*/
|
|
6014
|
+
function windowsBrowseRoots() {
|
|
6015
|
+
const roots = []
|
|
6016
|
+
const seen = new Set()
|
|
6017
|
+
const push = (name, posix) => {
|
|
6018
|
+
if (existsSync(posix) !== true || seen.has(posix)) return
|
|
6019
|
+
seen.add(posix)
|
|
6020
|
+
roots.push({ name, path: posixToWindowsPath(posix) })
|
|
6021
|
+
}
|
|
6022
|
+
for (const letter of ['c', 'd', 'e', 'f']) push(`Windows ${letter.toUpperCase()}:`, `/mnt/${letter}`)
|
|
6023
|
+
for (const letter of ['c', 'd']) {
|
|
6024
|
+
push(`${letter.toUpperCase()}:\\Program Files`, `/mnt/${letter}/Program Files`)
|
|
6025
|
+
push(`${letter.toUpperCase()}:\\YonCode`, `/mnt/${letter}/Program Files/YonCode`)
|
|
6026
|
+
push(`${letter.toUpperCase()}:\\Git`, `/mnt/${letter}/Program Files/Git`)
|
|
6027
|
+
}
|
|
6028
|
+
return roots
|
|
6029
|
+
}
|
|
6030
|
+
|
|
6031
|
+
/** Names that look like a launchable program, for the browse listing. */
|
|
6032
|
+
function isProgramFile(fullPath, name) {
|
|
6033
|
+
const lower = name.toLowerCase()
|
|
6034
|
+
if (PROGRAM_SUFFIXES.some((suffix) => lower.endsWith(suffix))) return true
|
|
6035
|
+
try {
|
|
6036
|
+
// POSIX marks executables with a mode bit; Windows has no such bit and is
|
|
6037
|
+
// covered by the suffix list above.
|
|
6038
|
+
return (statSync(fullPath).mode & 0o111) !== 0
|
|
6039
|
+
} catch {
|
|
6040
|
+
return false
|
|
6041
|
+
}
|
|
6042
|
+
}
|
|
6043
|
+
|
|
6044
|
+
/** Suffixes the file browser always shows (plus anything with an exec bit). */
|
|
6045
|
+
const PROGRAM_SUFFIXES = ['.exe', '.cmd', '.bat', '.ps1', '.jar', '.sh', '.bin', '.mjs', '.cjs']
|
|
6046
|
+
|
|
6047
|
+
/** Quick-jump roots offered by the file browser. */
|
|
6048
|
+
function browseRoots() {
|
|
6049
|
+
// The tree starts at the two things a program path can live under, and nothing
|
|
6050
|
+
// else: the filesystem root (every path is reachable from it) and, on WSL, the
|
|
6051
|
+
// Windows disks. Workspace/home/temp shortcuts only pushed the real start down.
|
|
6052
|
+
const roots = []
|
|
6053
|
+
if (IS_WINDOWS) {
|
|
6054
|
+
for (const letter of ['C', 'D', 'E']) {
|
|
6055
|
+
if (existsSync(`${letter}:\\`) === true) roots.push({ name: `磁盘 ${letter}:`, path: `${letter}:\\` })
|
|
6056
|
+
}
|
|
6057
|
+
return roots
|
|
6058
|
+
}
|
|
6059
|
+
roots.push({ name: '根路径 /', path: '/' })
|
|
6060
|
+
for (const letter of ['c', 'd']) {
|
|
6061
|
+
if (existsSync(`/mnt/${letter}`) === true) roots.push({ name: `Windows ${letter.toUpperCase()}:`, path: `/mnt/${letter}` })
|
|
6062
|
+
}
|
|
6063
|
+
return roots
|
|
6064
|
+
}
|
|
6065
|
+
|
|
6066
|
+
async function serveProxyPrograms(ctx, req, res, options) {
|
|
6067
|
+
try {
|
|
6068
|
+
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
6069
|
+
const url = new URL(req.url ?? '/', 'http://dsh.internal')
|
|
6070
|
+
const side = engineSide()
|
|
6071
|
+
// On Windows the local side IS the Windows side; inside WSL both sides are
|
|
6072
|
+
// reachable (the picker must offer navicat.exe even though the engine runs in
|
|
6073
|
+
// the Linux side), so the Windows probe runs on either branch.
|
|
6074
|
+
// Only programs we can actually proxy are listed: injecting the tunnel means
|
|
6075
|
+
// setting a SOCKS address (env or JVM flag), and a program that has no SOCKS
|
|
6076
|
+
// client cannot be helped that way.
|
|
6077
|
+
const capable = (names) => names
|
|
6078
|
+
.filter((name) => isSocksCapableProgram(name))
|
|
6079
|
+
.map((name) => ({ name, side: engineSide() }))
|
|
6080
|
+
const local = IS_WINDOWS
|
|
6081
|
+
? capable([...await windowsProgramNames()].map((name) => (name.endsWith('.exe') ? name : `${name}.exe`)))
|
|
6082
|
+
.map((item) => ({ ...item, side: 'windows' }))
|
|
6083
|
+
: capable([...localProgramNames()])
|
|
6084
|
+
let remote = []
|
|
6085
|
+
if (!IS_WINDOWS) {
|
|
6086
|
+
const names = await windowsProgramNames()
|
|
6087
|
+
if (names.size > 0) {
|
|
6088
|
+
remote = capable([...names].map((name) => (name.endsWith('.exe') ? name : `${name}.exe`)))
|
|
6089
|
+
.map((item) => ({ ...item, side: 'windows' }))
|
|
6090
|
+
}
|
|
6091
|
+
}
|
|
6092
|
+
const suggested = PROXY_PROGRAM_SUGGESTIONS.map((name) => ({ name, side, suggested: true }))
|
|
6093
|
+
const seen = new Set()
|
|
6094
|
+
const programs = []
|
|
6095
|
+
for (const item of [...local, ...remote, ...suggested]) {
|
|
6096
|
+
const key = `${item.side}:${item.name.toLowerCase()}`
|
|
6097
|
+
if (seen.has(key)) continue
|
|
6098
|
+
seen.add(key)
|
|
6099
|
+
programs.push(item)
|
|
6100
|
+
}
|
|
6101
|
+
programs.sort((a, b) => Number(b.suggested === true) - Number(a.suggested === true) || a.name.localeCompare(b.name))
|
|
6102
|
+
writeJson(res, 200, {
|
|
6103
|
+
ok: true,
|
|
6104
|
+
side,
|
|
6105
|
+
// Why the list is short: a program without a SOCKS client can only use a
|
|
6106
|
+
// 127.0.0.1 listener, and those need no entry here.
|
|
6107
|
+
note: '只列出支持 SOCKS 的程序(java/git/node/curl 等);其它程序只能靠 127.0.0.1 同端口映射,无需在此选择。',
|
|
6108
|
+
programs: programs.slice(0, 400),
|
|
6109
|
+
})
|
|
6110
|
+
} catch (error) {
|
|
6111
|
+
writeTailError(res, error)
|
|
6112
|
+
}
|
|
6113
|
+
}
|
|
6114
|
+
|
|
4721
6115
|
async function serveDebug(ctx, req, res, options) {
|
|
4722
6116
|
try {
|
|
4723
6117
|
if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
|
|
@@ -4899,6 +6293,80 @@ async function serveStart(ctx, req, res, options) {
|
|
|
4899
6293
|
* @param options - `{ stopGraceMs }`.
|
|
4900
6294
|
* @returns `{ alreadyRunning, program }`.
|
|
4901
6295
|
*/
|
|
6296
|
+
/**
|
|
6297
|
+
* Decide whether a program needs its dependencies installed before it can run.
|
|
6298
|
+
*
|
|
6299
|
+
* A freshly cloned frontend has no `node_modules`, and the failure it produces
|
|
6300
|
+
* (`cross-env: not found`, `vite: not found`) looks like a broken command rather
|
|
6301
|
+
* than a missing install. Installing up front — with the output going into the same
|
|
6302
|
+
* log the panel already tails — turns that into a visible, self-healing step.
|
|
6303
|
+
* @param {string} cwd - program working directory.
|
|
6304
|
+
* @returns {{pm: string, args: string[], dir: string}|null} plan, or null when the
|
|
6305
|
+
* directory has no package.json or already has dependencies.
|
|
6306
|
+
*/
|
|
6307
|
+
export function installPlanFor(cwd) {
|
|
6308
|
+
try {
|
|
6309
|
+
if (!existsSync(join(cwd, 'package.json'))) return null
|
|
6310
|
+
const modules = join(cwd, 'node_modules')
|
|
6311
|
+
if (existsSync(modules)) {
|
|
6312
|
+
const entries = readdirSync(modules)
|
|
6313
|
+
// An empty node_modules is what a killed install leaves behind.
|
|
6314
|
+
if (entries.length > 0) return null
|
|
6315
|
+
}
|
|
6316
|
+
const has = (name) => existsSync(join(cwd, name))
|
|
6317
|
+
const pm = has('pnpm-lock.yaml') ? 'pnpm' : (has('yarn.lock') ? 'yarn' : 'npm')
|
|
6318
|
+
const args = pm === 'npm' ? ['install', '--no-audit', '--no-fund'] : ['install']
|
|
6319
|
+
return { pm, args, dir: cwd }
|
|
6320
|
+
} catch {
|
|
6321
|
+
return null
|
|
6322
|
+
}
|
|
6323
|
+
}
|
|
6324
|
+
|
|
6325
|
+
/**
|
|
6326
|
+
* Run the install phase with its output appended to the program log.
|
|
6327
|
+
*
|
|
6328
|
+
* The proxy environment is stripped on purpose: npm's own traffic goes to a
|
|
6329
|
+
* registry (often a loopback mirror), and an injected ALL_PROXY would send that
|
|
6330
|
+
* through the tunnel where the allow list refuses it.
|
|
6331
|
+
* @param {object} plan - from {@link installPlanFor}.
|
|
6332
|
+
* @param {object} env - base environment.
|
|
6333
|
+
* @param {string} logPath - log the panel tails.
|
|
6334
|
+
* @param {number} timeoutMs - cap for a cold install.
|
|
6335
|
+
* @returns {Promise<{ok: boolean, ms: number, pm: string, error?: string}>} outcome.
|
|
6336
|
+
*/
|
|
6337
|
+
export function runInstallPhase(plan, env, logPath, timeoutMs = 1200000) {
|
|
6338
|
+
const clean = Object.assign({}, env)
|
|
6339
|
+
for (const key of Object.keys(clean)) {
|
|
6340
|
+
if (/^(ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|NO_PROXY|all_proxy|http_proxy|https_proxy|no_proxy)$/.test(key)) delete clean[key]
|
|
6341
|
+
}
|
|
6342
|
+
const fd = openSync(logPath, 'a')
|
|
6343
|
+
const started = Date.now()
|
|
6344
|
+
return new Promise((resolvePromise) => {
|
|
6345
|
+
const child = spawn(plan.pm, plan.args, {
|
|
6346
|
+
cwd: plan.dir, env: clean, stdio: ['ignore', fd, fd], shell: IS_WINDOWS, windowsHide: true,
|
|
6347
|
+
})
|
|
6348
|
+
let settled = false
|
|
6349
|
+
const done = (result) => {
|
|
6350
|
+
if (settled) return
|
|
6351
|
+
settled = true
|
|
6352
|
+
try { closeSync(fd) } catch { /* already closed */ }
|
|
6353
|
+
resolvePromise(result)
|
|
6354
|
+
}
|
|
6355
|
+
const timer = setTimeout(() => {
|
|
6356
|
+
try { child.kill('SIGKILL') } catch { /* gone already */ }
|
|
6357
|
+
done({ ok: false, ms: Date.now() - started, pm: plan.pm, error: `安装超时(${Math.round(timeoutMs / 1000)}s)` })
|
|
6358
|
+
}, timeoutMs)
|
|
6359
|
+
child.on('error', (error) => {
|
|
6360
|
+
clearTimeout(timer)
|
|
6361
|
+
done({ ok: false, ms: Date.now() - started, pm: plan.pm, error: isMissingExecutable(error) ? `本机没有安装 ${plan.pm}` : String(error?.message ?? error) })
|
|
6362
|
+
})
|
|
6363
|
+
child.on('close', (code) => {
|
|
6364
|
+
clearTimeout(timer)
|
|
6365
|
+
done(code === 0 ? { ok: true, ms: Date.now() - started, pm: plan.pm } : { ok: false, ms: Date.now() - started, pm: plan.pm, error: `${plan.pm} install exited with ${code}` })
|
|
6366
|
+
})
|
|
6367
|
+
})
|
|
6368
|
+
}
|
|
6369
|
+
|
|
4902
6370
|
export async function startProgram(cwd, logsDir, program, options) {
|
|
4903
6371
|
if (options?.debug === undefined) await debugSessions.detach(program.logPath)
|
|
4904
6372
|
if (program.kind === 'instance') {
|
|
@@ -4917,6 +6385,24 @@ export async function startProgram(cwd, logsDir, program, options) {
|
|
|
4917
6385
|
const childEnv = Object.assign({}, process.env, { DSH_LOG_DIR: logsDir }, {
|
|
4918
6386
|
DSH_STOP_GRACE_MS: String(clampBytes(graceMs, DEFAULT_STOP_GRACE_MS, MAX_STOP_GRACE_MS)),
|
|
4919
6387
|
})
|
|
6388
|
+
// A rule can name this program: inject the proxy at launch, so "配好规则再启动"
|
|
6389
|
+
// actually proxies it (Java reads JAVA_TOOL_OPTIONS, node/curl read ALL_PROXY).
|
|
6390
|
+
// Programs started outside this panel cannot be intercepted — they rely on the
|
|
6391
|
+
// 127.0.0.1 shadow listeners instead.
|
|
6392
|
+
Object.assign(childEnv, proxyEnvFor(program, cwd))
|
|
6393
|
+
// Dependencies first: a missing node_modules would otherwise surface as
|
|
6394
|
+
// "cross-env: not found" and look like the entry itself is broken.
|
|
6395
|
+
const installPlan = options?.skipInstall === true ? null : installPlanFor(cwd)
|
|
6396
|
+
if (installPlan !== null) {
|
|
6397
|
+
const header = `--- 初始化:${installPlan.pm} ${installPlan.args.join(' ')}(node_modules 缺失)---\n`
|
|
6398
|
+
await appendFile(program.logPath, header, 'utf8').catch(() => {})
|
|
6399
|
+
const init = await runInstallPhase(installPlan, childEnv, program.logPath, options?.installTimeoutMs)
|
|
6400
|
+
const summary = init.ok === true
|
|
6401
|
+
? `--- 初始化完成:${init.pm} install(${Math.round(init.ms / 1000)}s)---\n`
|
|
6402
|
+
: `--- 初始化失败:${init.pm} install(${init.error ?? '未知原因'}),见上方输出 ---\n`
|
|
6403
|
+
await appendFile(program.logPath, summary, 'utf8').catch(() => {})
|
|
6404
|
+
if (init.ok !== true) throw new TailError('init-failed', `依赖安装失败:${init.error ?? '未知原因'}(日志:${program.logPath})`, 502)
|
|
6405
|
+
}
|
|
4920
6406
|
let child
|
|
4921
6407
|
if (IS_WINDOWS) {
|
|
4922
6408
|
const selected = resolveWindowsRuntime(options?.runtime, options?.bashPath)
|
|
@@ -4971,6 +6457,67 @@ export async function startProgram(cwd, logsDir, program, options) {
|
|
|
4971
6457
|
}
|
|
4972
6458
|
}
|
|
4973
6459
|
|
|
6460
|
+
/**
|
|
6461
|
+
* Environment a started program needs to use the workspace proxy.
|
|
6462
|
+
*
|
|
6463
|
+
* Matches the program against the enabled rules: a rule that names a bare
|
|
6464
|
+
* program (`java`, `git`) matches any process with that basename, whatever its
|
|
6465
|
+
* path; a rule that names a path only matches that executable. The path is
|
|
6466
|
+
* therefore optional — it buys precision, not reach.
|
|
6467
|
+
* injection that fits that program. Returns `{}` when no rule matches or the
|
|
6468
|
+
* workspace has no upstream — a silent no-op rather than an error, because most
|
|
6469
|
+
* programs have no rule and must start exactly as before.
|
|
6470
|
+
* @param program - one row from {@link scanPrograms}.
|
|
6471
|
+
* @param cwd - workspace the program is launched from (the shared proxy config
|
|
6472
|
+
* only uses it to identify which rules belong to this workspace).
|
|
6473
|
+
* @returns environment overlay for the child process.
|
|
6474
|
+
*/
|
|
6475
|
+
function proxyEnvFor(program, cwd) {
|
|
6476
|
+
// A Windows-side redirector cannot see a process this side spawns, so only the
|
|
6477
|
+
// local hook may disable injection ("covered twice" was the old, wrong test).
|
|
6478
|
+
try {
|
|
6479
|
+
const config = readProxyConfig(cwd)
|
|
6480
|
+
if (config.socks.host === '' || config.socks.port === 0) return {}
|
|
6481
|
+
// ProxyBridge is the primary path when the LOCAL hook is up: it already
|
|
6482
|
+
// redirects this side's connections at the socket layer, so adding env/JVM
|
|
6483
|
+
// options on top would only stack two proxies. A Windows-side redirector does
|
|
6484
|
+
// NOT count — it hooks the Windows stack and cannot see a process this side
|
|
6485
|
+
// spawns, which is exactly the WSL + YonCode split.
|
|
6486
|
+
if (localRedirectorRunning()) return {}
|
|
6487
|
+
const names = new Set()
|
|
6488
|
+
const paths = new Set()
|
|
6489
|
+
for (const candidate of [program?.name, program?.command, program?.exe, program?.id]) {
|
|
6490
|
+
if (typeof candidate !== 'string' || candidate === '') continue
|
|
6491
|
+
names.add(programKey(candidate))
|
|
6492
|
+
if (candidate.includes('/') || candidate.includes('\\')) paths.add(candidate.replace(/\\/g, '/').toLowerCase())
|
|
6493
|
+
}
|
|
6494
|
+
const matchRule = (spec) => {
|
|
6495
|
+
if (typeof spec !== 'string' || spec === '') return false
|
|
6496
|
+
const isPath = spec.includes('/') || spec.includes('\\')
|
|
6497
|
+
if (!isPath) return names.has(programKey(spec))
|
|
6498
|
+
// A path rule is precise: it matches that executable only. When we do not
|
|
6499
|
+
// know the launched path, fall back to the basename so the rule is not
|
|
6500
|
+
// silently dead (the panel often launches by name, e.g. `java`).
|
|
6501
|
+
if (paths.size === 0) return names.has(programKey(spec))
|
|
6502
|
+
return paths.has(spec.replace(/\\/g, '/').toLowerCase())
|
|
6503
|
+
}
|
|
6504
|
+
const rule = config.rules.find((item) => item.enabled && matchRule(item.program))
|
|
6505
|
+
if (rule === undefined) return {}
|
|
6506
|
+
const injection = injectionFor(programKey(rule.program), config, { side: engineSide() })
|
|
6507
|
+
const env = Object.assign({}, injection?.env ?? {})
|
|
6508
|
+
const jvmArgs = Array.isArray(injection?.jvmArgs) ? injection.jvmArgs : []
|
|
6509
|
+
// Careful: an existing JAVA_TOOL_OPTIONS must be kept (it may carry the
|
|
6510
|
+
// user's own -Xmx); the proxy options are appended.
|
|
6511
|
+
if (jvmArgs.length > 0) {
|
|
6512
|
+
const previous = typeof process.env.JAVA_TOOL_OPTIONS === 'string' ? process.env.JAVA_TOOL_OPTIONS.trim() : ''
|
|
6513
|
+
env.JAVA_TOOL_OPTIONS = [previous, jvmArgs.join(' ')].filter((part) => part !== '').join(' ')
|
|
6514
|
+
}
|
|
6515
|
+
return env
|
|
6516
|
+
} catch {
|
|
6517
|
+
return {}
|
|
6518
|
+
}
|
|
6519
|
+
}
|
|
6520
|
+
|
|
4974
6521
|
/**
|
|
4975
6522
|
* Start one program in debug mode: stop it if needed, restart it with the JDWP
|
|
4976
6523
|
* agent on a free loopback port, wait for the port, then attach.
|
|
@@ -5665,6 +7212,29 @@ async function considerSpring(workspace, file, programs, launch) {
|
|
|
5665
7212
|
}
|
|
5666
7213
|
|
|
5667
7214
|
/** Record one frontend program when its manifest has a dev-ish script. */
|
|
7215
|
+
/**
|
|
7216
|
+
* YonBIP module manifest of a frontend directory (`module.xml` beside package.json).
|
|
7217
|
+
*
|
|
7218
|
+
* This is a yds/MDF convention: the deployed module name lives in `module.xml`, while
|
|
7219
|
+
* `package.json`'s `name` is often the *backend* domainKey — so a row named after the
|
|
7220
|
+
* package would read exactly like the java program's row. Only projects that ship a
|
|
7221
|
+
* module.xml are affected; a plain npm project keeps its package name.
|
|
7222
|
+
* @param dir - frontend project directory.
|
|
7223
|
+
* @returns `{ present, name }`; `name` is `''` when the manifest names nothing.
|
|
7224
|
+
*/
|
|
7225
|
+
async function moduleXmlManifest(dir) {
|
|
7226
|
+
const text = await readTextIfSmall(join(dir, 'module.xml'))
|
|
7227
|
+
if (text === undefined) return { present: false, name: '' }
|
|
7228
|
+
const match = /<module\b[^>]*\sname\s*=\s*"([^"]*)"/.exec(text)
|
|
7229
|
+
return { present: true, name: match === null ? '' : match[1].trim() }
|
|
7230
|
+
}
|
|
7231
|
+
|
|
7232
|
+
/** Row name for a frontend: module.xml → folder (yds), else package.json → folder. */
|
|
7233
|
+
function nameOfFrontend(manifest, manifestXml, dir) {
|
|
7234
|
+
if (manifestXml.present === true) return manifestXml.name !== '' ? manifestXml.name : basename(dir)
|
|
7235
|
+
return typeof manifest.name === 'string' && manifest.name !== '' ? manifest.name : basename(dir)
|
|
7236
|
+
}
|
|
7237
|
+
|
|
5668
7238
|
async function considerFrontend(workspace, file, programs) {
|
|
5669
7239
|
const dir = dirname(file)
|
|
5670
7240
|
const text = await readTextIfSmall(file)
|
|
@@ -5681,13 +7251,17 @@ async function considerFrontend(workspace, file, programs) {
|
|
|
5681
7251
|
if (scripts === undefined) return
|
|
5682
7252
|
const script = ['dev', 'start', 'serve'].find((key) => typeof scripts[key] === 'string' && scripts[key].trim() !== '')
|
|
5683
7253
|
if (script === undefined) return
|
|
7254
|
+
const manifestXml = await moduleXmlManifest(dir)
|
|
5684
7255
|
const relDir = relative(workspace, dir) || '.'
|
|
5685
7256
|
const id = `frontend:${relDir}#${script}`
|
|
5686
7257
|
if (programs.has(id)) return
|
|
5687
7258
|
programs.set(id, {
|
|
5688
7259
|
id,
|
|
5689
7260
|
kind: 'frontend',
|
|
5690
|
-
|
|
7261
|
+
// yds project (it has module.xml): name after the manifest, else the folder —
|
|
7262
|
+
// `package.json`'s name there is the domainKey and collides with the java row.
|
|
7263
|
+
// A plain npm project has no module.xml and keeps its package name.
|
|
7264
|
+
name: nameOfFrontend(manifest, manifestXml, dir),
|
|
5691
7265
|
project: projectOf(relDir, workspace),
|
|
5692
7266
|
dir,
|
|
5693
7267
|
relDir,
|
|
@@ -6282,7 +7856,12 @@ export function findConfigEntryIndex(entries, candidate, used) {
|
|
|
6282
7856
|
&& (entry.kind === undefined || entry.kind === candidate.kind))
|
|
6283
7857
|
if (byDir !== -1) return byDir
|
|
6284
7858
|
}
|
|
6285
|
-
|
|
7859
|
+
// Name is the last resort, and only within the same kind: two different kinds can
|
|
7860
|
+
// legitimately share a name (a yds project's package.json name equals its java
|
|
7861
|
+
// module), and matching across kinds made an update copy a launcher's startCommand
|
|
7862
|
+
// onto an unrelated frontend row — and then drop the launcher itself.
|
|
7863
|
+
return entries.findIndex((entry, at) => free(at) && entry.name === candidate.name
|
|
7864
|
+
&& (entry.kind === undefined || candidate.kind === undefined || entry.kind === candidate.kind))
|
|
6286
7865
|
}
|
|
6287
7866
|
|
|
6288
7867
|
/**
|
|
@@ -6779,7 +8358,14 @@ export function registerAgentTools(ctx, options) {
|
|
|
6779
8358
|
const logsDir = resolvePath(cwd, 'logs', true)
|
|
6780
8359
|
let programs = await scanPrograms(cwd, logsDir, args?.refresh === true)
|
|
6781
8360
|
if (args?.runningOnly === true) programs = programs.filter((program) => program.running?.alive === true)
|
|
6782
|
-
return jsonSafe({
|
|
8361
|
+
return jsonSafe({
|
|
8362
|
+
ok: true,
|
|
8363
|
+
root: cwd,
|
|
8364
|
+
dir: logsDir,
|
|
8365
|
+
programs: programRows(programs),
|
|
8366
|
+
// Only a real YMS workspace gets a hint; null keeps the payload clean.
|
|
8367
|
+
companion: detectCompanionPlugin(cwd),
|
|
8368
|
+
})
|
|
6783
8369
|
},
|
|
6784
8370
|
})
|
|
6785
8371
|
|
|
@@ -7307,13 +8893,19 @@ function describeRef(ref) {
|
|
|
7307
8893
|
/** Render one program list for the model. */
|
|
7308
8894
|
function renderProgramList(value) {
|
|
7309
8895
|
const programs = Array.isArray(value?.programs) ? value.programs : []
|
|
7310
|
-
|
|
8896
|
+
const companion = value?.companion
|
|
8897
|
+
// The hint is additive: the list itself (and the tool result) stays usable
|
|
8898
|
+
// when the companion plugin is not installed.
|
|
8899
|
+
const hint = companion !== undefined && companion !== null
|
|
8900
|
+
? `\nOptional companion plugin: ${companion.plugin} (detected ${companion.detected}) — ${companion.hint}`
|
|
8901
|
+
: ''
|
|
8902
|
+
if (programs.length === 0) return `No runnable programs under ${value?.root ?? '?'}.${hint}`
|
|
7311
8903
|
const lines = [`${programs.length} program(s) under ${value.root} (logs: ${value.dir}):`]
|
|
7312
8904
|
for (const program of programs) {
|
|
7313
8905
|
lines.push(`- ${program.running ? '[running]' : '[stopped]'} ${program.name} (${program.kind}) id=${program.id}`)
|
|
7314
8906
|
lines.push(` dir=${program.dir}${program.mainClass ? ` main=${program.mainClass}` : ''}${program.script ? ` script=${program.script}` : ''} log=${program.logPath}`)
|
|
7315
8907
|
}
|
|
7316
|
-
return lines.join('\n')
|
|
8908
|
+
return lines.join('\n') + hint
|
|
7317
8909
|
}
|
|
7318
8910
|
|
|
7319
8911
|
/** Render one start result for the model. */
|
|
@@ -7471,6 +9063,27 @@ function renderLogs(value) {
|
|
|
7471
9063
|
/** Test-only surface: the pure pieces, exercised without a live profile. */
|
|
7472
9064
|
export const __test = {
|
|
7473
9065
|
resolvePath,
|
|
9066
|
+
detectCompanionPlugin,
|
|
9067
|
+
renderProgramList,
|
|
9068
|
+
windowsProgramNames,
|
|
9069
|
+
resetWindowsProgramCache,
|
|
9070
|
+
// Proxy rules + engine (the dialog's three routes).
|
|
9071
|
+
PROXY_PATH,
|
|
9072
|
+
PROXY_ACTION_PATH,
|
|
9073
|
+
buildProfile,
|
|
9074
|
+
PROXY_PROGRAMS_PATH,
|
|
9075
|
+
PROXY_BROWSE_PATH,
|
|
9076
|
+
serveProxy,
|
|
9077
|
+
serveProxyAction,
|
|
9078
|
+
serveProxyPrograms,
|
|
9079
|
+
serveProxyBrowse,
|
|
9080
|
+
proxyEnvFor,
|
|
9081
|
+
proxyView,
|
|
9082
|
+
// Process-wide child-service lifecycle (exit hook + heartbeat + janitor), and the
|
|
9083
|
+
// adoption of an engine left behind by a previous dsh process.
|
|
9084
|
+
ensureLifecycle,
|
|
9085
|
+
adoptLeftoverEngine,
|
|
9086
|
+
decorateProxyRule,
|
|
7474
9087
|
// The bundled skill + its installer (idempotent, target-aware).
|
|
7475
9088
|
SKILL_NAME,
|
|
7476
9089
|
PKG_VERSION,
|
|
@@ -7501,6 +9114,17 @@ export const __test = {
|
|
|
7501
9114
|
CONTENT_SEARCH_PATH,
|
|
7502
9115
|
searchWorkspaceContent,
|
|
7503
9116
|
serveContentSearch,
|
|
9117
|
+
// streamed (paged) variants: NDJSON frames while the repo roots are searched in parallel
|
|
9118
|
+
SEARCH_STREAM_PATH,
|
|
9119
|
+
CONTENT_SEARCH_STREAM_PATH,
|
|
9120
|
+
SEARCH_STREAM_PAGE_DEFAULT,
|
|
9121
|
+
SEARCH_STREAM_PAGE_MAX,
|
|
9122
|
+
SEARCH_STREAM_CONCURRENCY,
|
|
9123
|
+
searchWorkspaceFilesStream,
|
|
9124
|
+
searchWorkspaceContentStream,
|
|
9125
|
+
serveSearchStream,
|
|
9126
|
+
createOrderedPages,
|
|
9127
|
+
streamGitStdout,
|
|
7504
9128
|
// one-module `mvn test` runner (poll the console through GET ?id=)
|
|
7505
9129
|
RUN_TEST_PATH,
|
|
7506
9130
|
serveRunTestStart,
|
|
@@ -7695,6 +9319,9 @@ export const __test = {
|
|
|
7695
9319
|
ROUTE_PREFIX,
|
|
7696
9320
|
DEFAULT_BYTES,
|
|
7697
9321
|
HARD_MAX_BYTES,
|
|
9322
|
+
FS_WRITE_MAX_BODY_BYTES,
|
|
9323
|
+
FS_WRITE_TEMP_SUFFIX,
|
|
9324
|
+
writeChunk,
|
|
7698
9325
|
MIN_BYTES,
|
|
7699
9326
|
PID_SUFFIX,
|
|
7700
9327
|
DEFAULT_STOP_GRACE_MS,
|