dsh-ris-ide 1.8.1 → 1.8.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 +2 -2
- package/lib/client.js +569 -98
- package/lib/debug/vendor/README.md +14 -0
- package/lib/debug/vendor/jdwp/client.js +9 -4
- package/lib/debug/vendor/src/jdwp/client.ts +12 -5
- package/lib/index.js +963 -64
- package/lib/redirector.js +76 -4
- package/lib/risd/lifecycle.js +54 -10
- package/lib/risd/ping.js +136 -17
- package/lib/risd/server.js +424 -22
- package/lib/risd/ui.js +218 -129
- package/lib/risd-client.js +4 -1
- package/lib/startup.js +27 -7
- package/package.json +2 -2
- package/test/client-viewer.test.mjs +268 -93
- package/test/clipboard.test.mjs +259 -0
- package/test/debug-engine.test.mjs +3 -1
- package/test/dsh-origin.test.mjs +4 -11
- package/test/dsh-window-refresh.test.mjs +166 -1
- package/test/harness.test.mjs +1 -1
- package/test/helpers/cmd.mjs +29 -0
- package/test/helpers/tgz.mjs +71 -0
- package/test/host-search.test.mjs +18 -11
- package/test/host-tail.test.mjs +190 -25
- package/test/proxy-route.test.mjs +61 -0
- package/test/proxy-window.test.mjs +5 -0
- package/test/proxy.test.mjs +40 -11
- package/test/proxybridge-bundle.test.mjs +1 -59
- package/test/redirector-bundle.test.mjs +21 -67
- package/test/redirector.test.mjs +71 -4
- package/test/risd-api.test.mjs +83 -29
- package/test/risd-bridge-degrade.test.mjs +3 -29
- package/test/risd-cli-home.test.mjs +41 -4
- package/test/risd-engine.test.mjs +13 -50
- package/test/risd-entry.test.mjs +0 -37
- package/test/risd-follow-start.test.mjs +102 -0
- package/test/risd-git.test.mjs +7 -5
- package/test/risd-handoff.test.mjs +6 -50
- package/test/risd-helpers.mjs +150 -3
- package/test/risd-host-p2.test.mjs +2 -30
- package/test/risd-lifecycle.test.mjs +203 -33
- package/test/risd-ping.test.mjs +77 -1
- package/test/risd-programs.test.mjs +4 -34
- package/test/risd-review-p2.test.mjs +0 -13
- package/test/risd-shutdown.test.mjs +5 -38
- package/test/risd-teardown.test.mjs +8 -27
- package/test/risd-ui.test.mjs +205 -14
- package/test/risd-write.test.mjs +2 -1
- package/test/startup-reconcile.test.mjs +44 -8
- package/test/proxy-restart.test.mjs +0 -39
package/lib/risd/server.js
CHANGED
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import { spawn } from 'node:child_process'
|
|
18
18
|
import { createServer, request } from 'node:http'
|
|
19
|
-
import {
|
|
19
|
+
import { request as httpsRequest } from 'node:https'
|
|
20
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
|
|
20
21
|
import { isAbsolute, join, win32 } from 'node:path'
|
|
21
22
|
import { timingSafeEqual } from 'node:crypto'
|
|
22
23
|
import { fileURLToPath } from 'node:url'
|
|
@@ -31,13 +32,14 @@ import * as bundleApi from '../proxybridge-bundle.js'
|
|
|
31
32
|
import { armJanitor, disarmJanitor, janitorStatus, markJanitorHandoff } from '../janitor.js'
|
|
32
33
|
import { bundledBundleDir, posixToWindowsPath, readElevationState, REDIRECTOR_PID_FILENAMES, REDIRECTOR_PID_FILENAME, redirectorCommand, redirectorHome, redirectorProfilePath, redirectorStatusAsync, redirectorStatusCached, reloadRedirectorsWithProfile, startRedirectors, stopRedirector, windowsBundleDir, writeHeartbeat } from '../redirector.js'
|
|
33
34
|
import { risdConfigRevision, risdProxyView } from './view.js'
|
|
35
|
+
import { buildProfile } from '../redirector.js'
|
|
34
36
|
import { clearGitProxy, readGitProxyState, reconcileGitProxy, syncGitProxy } from './git.js'
|
|
35
37
|
import { findProgram, listPrograms, readProgramLog, restartProgramByKey, startLogFollow, startProgramByKey, stopProgramByKey } from './programs.js'
|
|
36
38
|
import { reconcileStartupLeftovers } from '../startup.js'
|
|
37
39
|
import { createDebugEngine } from './debug.js'
|
|
38
40
|
import { mergeLifecycle, readLifecycle, writeLifecycle } from './lifecycle.js'
|
|
39
41
|
import { risdUiHtml } from './ui.js'
|
|
40
|
-
import { pingSocks } from './ping.js'
|
|
42
|
+
import { pingSocks, probeTarget } from './ping.js'
|
|
41
43
|
import { buildStamp } from './build.js'
|
|
42
44
|
import { DebugError, debugErrorStatus } from '../debug/engine.js'
|
|
43
45
|
import { createHealthCache } from '../proxybridge-health.js'
|
|
@@ -61,6 +63,10 @@ const DSH_WINDOW_LIVE_MS = 5 * 60_000
|
|
|
61
63
|
/** Remembered windows older than this are pruned; between the two they show as
|
|
62
64
|
* "未活跃" but stay selectable (m08268: clicking one may still open the IDE). */
|
|
63
65
|
const DSH_WINDOW_RETAIN_MS = 7 * 24 * 60 * 60_000
|
|
66
|
+
/** Cap on the sidebar mirror: a machine with hundreds of workspaces must not make the
|
|
67
|
+
* page huge (the plugin caps its own snapshot at DSH_WINDOW_MAX_WORKSPACES = 50). */
|
|
68
|
+
const DSH_WORKSPACES_MAX = 100
|
|
69
|
+
|
|
64
70
|
|
|
65
71
|
/** The daemon's own page is only for the local browser (no DNS rebinding). */
|
|
66
72
|
export function isLoopbackHost(req) {
|
|
@@ -82,6 +88,165 @@ export function isLoopbackOrigin(origin) {
|
|
|
82
88
|
}
|
|
83
89
|
}
|
|
84
90
|
|
|
91
|
+
/** How long one direct sidebar probe may take before that candidate is skipped. */
|
|
92
|
+
const DSH_PROBE_TIMEOUT_MS = 600
|
|
93
|
+
/** Cap on the hosts probed for one answer: a few live dsh instances, not a scan. */
|
|
94
|
+
const DSH_PROBE_MAX_CANDIDATES = 4
|
|
95
|
+
/** Where each running plugin advertises its own origin (one file per pid). */
|
|
96
|
+
const DSH_INSTANCE_DIRNAME = 'instances'
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Turn a sidebar snapshot into panel rows. Sidebar order is the user's order, so the
|
|
100
|
+
* panel order is the sidebar order; a workspace is identified by its PATH (a rename
|
|
101
|
+
* keeps the path and changes only the label), and a matching remembered window
|
|
102
|
+
* supplies that workspace's origin, sessionId and liveness.
|
|
103
|
+
* @param {Array} sidebar - workspace entries (document or direct probe).
|
|
104
|
+
* @param {Array} windows - remembered windows, already filtered and sorted.
|
|
105
|
+
* @param {string} origin - loopback origin to embed a workspace nobody opened.
|
|
106
|
+
* @returns {Array} rows, possibly empty.
|
|
107
|
+
*/
|
|
108
|
+
function dshSidebarRows(sidebar, windows, origin) {
|
|
109
|
+
const rows = []
|
|
110
|
+
const remembered = new Map(windows.map((row) => [row.cwd, row]))
|
|
111
|
+
const seen = new Set()
|
|
112
|
+
for (const entry of sidebar) {
|
|
113
|
+
if (rows.length >= DSH_WORKSPACES_MAX) break
|
|
114
|
+
if (entry === null || typeof entry !== 'object') continue
|
|
115
|
+
const cwd = typeof entry.cwd === 'string' && isAbsolute(entry.cwd) ? entry.cwd : ''
|
|
116
|
+
if (cwd === '' || seen.has(cwd)) continue
|
|
117
|
+
seen.add(cwd)
|
|
118
|
+
const window = remembered.get(cwd)
|
|
119
|
+
if (window !== undefined) remembered.delete(cwd)
|
|
120
|
+
const title = typeof entry.title === 'string' ? entry.title : ''
|
|
121
|
+
const sessionId = typeof entry.sessionId === 'string' && entry.sessionId !== ''
|
|
122
|
+
? entry.sessionId
|
|
123
|
+
: (window === undefined ? '' : window.sessionId)
|
|
124
|
+
rows.push({
|
|
125
|
+
cwd,
|
|
126
|
+
title: title !== '' ? title : (window === undefined ? '' : window.title),
|
|
127
|
+
sessionId,
|
|
128
|
+
url: window === undefined ? origin : window.url,
|
|
129
|
+
// A listed workspace is reachable even when nobody opened the IDE for it: it is
|
|
130
|
+
// not a remembered window, so it gets no "未活跃" label and no TTL of its own —
|
|
131
|
+
// the snapshot's freshness is the gate.
|
|
132
|
+
ageMs: window === undefined ? DSH_WINDOW_RETAIN_MS : window.ageMs,
|
|
133
|
+
live: window === undefined ? true : window.live,
|
|
134
|
+
// Whether the workspace has a live session right now; the page only hints with
|
|
135
|
+
// it, the row stays selectable either way (m00186).
|
|
136
|
+
...(typeof entry.active === 'boolean' ? { active: entry.active } : {}),
|
|
137
|
+
...(window === undefined ? { source: 'workspace' } : {}),
|
|
138
|
+
})
|
|
139
|
+
}
|
|
140
|
+
// Remembered windows whose workspace has left the sidebar still open: the user may
|
|
141
|
+
// be mid-session there, so they stay listed (as 未活跃 once stale).
|
|
142
|
+
for (const window of remembered.values()) rows.push(window)
|
|
143
|
+
return rows
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Loopback origins worth asking for a snapshot (m00186): the shared document's
|
|
148
|
+
* origin, every remembered window's origin, then the per-pid instance files (newest
|
|
149
|
+
* first). Only an instance file younger than the live window names a live process.
|
|
150
|
+
* @param {string} home - daemon home (holds `dsh-window.json` and `instances/`).
|
|
151
|
+
* @param {number} now - epoch ms.
|
|
152
|
+
* @param {string} documentOrigin - origin the shared document advertises.
|
|
153
|
+
* @param {Array} windows - usable remembered windows.
|
|
154
|
+
* @returns {string[]} distinct loopback origins, capped.
|
|
155
|
+
*/
|
|
156
|
+
function dshProbeCandidates(home, now, documentOrigin, windows) {
|
|
157
|
+
const candidates = []
|
|
158
|
+
const seen = new Set()
|
|
159
|
+
const push = (origin) => {
|
|
160
|
+
if (typeof origin !== 'string' || origin === '' || !isLoopbackOrigin(origin)) return
|
|
161
|
+
if (seen.has(origin) || candidates.length >= DSH_PROBE_MAX_CANDIDATES) return
|
|
162
|
+
seen.add(origin)
|
|
163
|
+
candidates.push(origin)
|
|
164
|
+
}
|
|
165
|
+
push(documentOrigin)
|
|
166
|
+
for (const row of windows) push(row.url)
|
|
167
|
+
const advertised = []
|
|
168
|
+
let names = []
|
|
169
|
+
try {
|
|
170
|
+
names = readdirSync(join(home, DSH_INSTANCE_DIRNAME))
|
|
171
|
+
} catch { /* older plugin: no instance files */ }
|
|
172
|
+
for (const name of names) {
|
|
173
|
+
if (!/^dsh-\d+\.json$/.test(name)) continue
|
|
174
|
+
try {
|
|
175
|
+
const parsed = JSON.parse(readFileSync(join(home, DSH_INSTANCE_DIRNAME, name), 'utf8'))
|
|
176
|
+
const at = Date.parse(String(parsed?.at ?? ''))
|
|
177
|
+
// A file from a dead process (or a reused pid) must not be probed; a timestamp
|
|
178
|
+
// far in the future is junk for the same reason as in the window rows.
|
|
179
|
+
if (!Number.isFinite(at) || now - at > DSH_WINDOW_LIVE_MS || at > now + 5 * 60_000) continue
|
|
180
|
+
advertised.push({ url: parsed?.url, at })
|
|
181
|
+
} catch { /* half-written file: not a candidate */ }
|
|
182
|
+
}
|
|
183
|
+
advertised.sort((a, b) => b.at - a.at)
|
|
184
|
+
for (const row of advertised) push(row.url)
|
|
185
|
+
return candidates
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Ask one live dsh for `GET /dsh-ris-ide/workspaces` (m00186). Never throws and never
|
|
190
|
+
* blocks longer than the probe timeout: a dead candidate is just a `null`.
|
|
191
|
+
* @param {string} origin - loopback http(s) origin.
|
|
192
|
+
* @returns {Promise<object|null>} the plugin's answer, or null.
|
|
193
|
+
*/
|
|
194
|
+
function probeDshWorkspaces(origin) {
|
|
195
|
+
return new Promise((resolveProbe) => {
|
|
196
|
+
let target
|
|
197
|
+
try {
|
|
198
|
+
target = new URL('/dsh-ris-ide/workspaces', origin)
|
|
199
|
+
} catch {
|
|
200
|
+
resolveProbe(null)
|
|
201
|
+
return
|
|
202
|
+
}
|
|
203
|
+
let settled = false
|
|
204
|
+
const finish = (value) => {
|
|
205
|
+
if (settled) return
|
|
206
|
+
settled = true
|
|
207
|
+
resolveProbe(value)
|
|
208
|
+
}
|
|
209
|
+
const client = target.protocol === 'https:' ? httpsRequest : request
|
|
210
|
+
const probe = client(target, {
|
|
211
|
+
method: 'GET',
|
|
212
|
+
timeout: DSH_PROBE_TIMEOUT_MS,
|
|
213
|
+
// dsh may serve TLS with a certificate this machine signed itself; the origin
|
|
214
|
+
// came from our own state files, not from the network, so trust it here.
|
|
215
|
+
...(target.protocol === 'https:' ? { rejectUnauthorized: false } : {}),
|
|
216
|
+
}, (response) => {
|
|
217
|
+
if (response.statusCode !== 200) {
|
|
218
|
+
response.resume()
|
|
219
|
+
finish(null)
|
|
220
|
+
return
|
|
221
|
+
}
|
|
222
|
+
let body = ''
|
|
223
|
+
response.setEncoding('utf8')
|
|
224
|
+
response.on('data', (chunk) => {
|
|
225
|
+
if (body.length > 512 * 1024) {
|
|
226
|
+
probe.destroy()
|
|
227
|
+
finish(null)
|
|
228
|
+
return
|
|
229
|
+
}
|
|
230
|
+
body += chunk
|
|
231
|
+
})
|
|
232
|
+
response.on('end', () => {
|
|
233
|
+
try {
|
|
234
|
+
finish(JSON.parse(body))
|
|
235
|
+
} catch {
|
|
236
|
+
finish(null)
|
|
237
|
+
}
|
|
238
|
+
})
|
|
239
|
+
response.on('error', () => finish(null))
|
|
240
|
+
})
|
|
241
|
+
probe.on('timeout', () => {
|
|
242
|
+
probe.destroy()
|
|
243
|
+
finish(null)
|
|
244
|
+
})
|
|
245
|
+
probe.on('error', () => finish(null))
|
|
246
|
+
probe.end()
|
|
247
|
+
})
|
|
248
|
+
}
|
|
249
|
+
|
|
85
250
|
function json(res, status, payload) {
|
|
86
251
|
const body = `${JSON.stringify(payload)}\n`
|
|
87
252
|
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(body) })
|
|
@@ -508,20 +673,32 @@ export async function startRisd({ home, port = DEFAULT_RISD_PORT, version = '0.0
|
|
|
508
673
|
try { await stopProxy(cwd) } catch { /* best effort */ }
|
|
509
674
|
}
|
|
510
675
|
}
|
|
676
|
+
// Promise of the in-flight 「跟随 dsh」 start (null when idle). Declared here because
|
|
677
|
+
// scheduleTeardown reads it; the start half is defined further down, next to the
|
|
678
|
+
// engine helpers.
|
|
679
|
+
let followStarting = null
|
|
511
680
|
function scheduleTeardown() {
|
|
512
681
|
if (leases.count() > 0) return
|
|
513
|
-
|
|
682
|
+
// A start triggered by the lease that just left may still be in flight; its
|
|
683
|
+
// finally re-schedules teardown once engineCwd is known.
|
|
684
|
+
if (engineCwd === null && heartbeat === null && followStarting === null) return
|
|
514
685
|
if (teardownTimer !== null) return
|
|
515
686
|
teardownTimer = setTimeout(() => {
|
|
516
687
|
teardownTimer = null
|
|
517
688
|
void (async () => {
|
|
518
689
|
if (leases.count() > 0) return // someone came back
|
|
690
|
+
// Let a pending start land first: tearing down with engineCwd still null
|
|
691
|
+
// would skip stopProxy and leave an orphan engine nobody owns (m13960).
|
|
692
|
+
if (followStarting !== null) {
|
|
693
|
+
await followStarting.catch(() => {})
|
|
694
|
+
if (leases.count() > 0) return
|
|
695
|
+
}
|
|
519
696
|
// Per-resource policy: "follow dsh" stops it with the last window; the
|
|
520
697
|
// daemon-owned ones stay until the daemon itself stops (or forever).
|
|
521
|
-
if (lifecycle.debug.
|
|
522
|
-
if (lifecycle.programs.
|
|
698
|
+
if (lifecycle.debug.stopWithDsh === true) await debug.stopAll().catch(() => {})
|
|
699
|
+
if (lifecycle.programs.stopWithDsh === true) await stopAllPrograms()
|
|
523
700
|
const cwd = engineCwd
|
|
524
|
-
if (lifecycle.proxy.
|
|
701
|
+
if (lifecycle.proxy.stopWithDsh === true) {
|
|
525
702
|
await teardownNetwork(cwd)
|
|
526
703
|
if (engineCwd === cwd) engineCwd = null
|
|
527
704
|
}
|
|
@@ -572,14 +749,14 @@ export async function startRisd({ home, port = DEFAULT_RISD_PORT, version = '0.0
|
|
|
572
749
|
}
|
|
573
750
|
function scheduleIdleExit() {
|
|
574
751
|
// "daemon follows dsh = false" means: stay up until someone stops me.
|
|
575
|
-
if (lifecycle.daemon.
|
|
752
|
+
if (lifecycle.daemon.stopWithDsh !== true) return
|
|
576
753
|
if (idleTimer !== null) return
|
|
577
754
|
idleTimer = setTimeout(() => {
|
|
578
755
|
idleTimer = null
|
|
579
756
|
// A daemon opened from the maintenance page has no lease at all, yet may be
|
|
580
757
|
// supervising programs or a debug session: idling out would kill them.
|
|
581
758
|
void hasActiveWork().then((active) => {
|
|
582
|
-
// An owned engine means the network is a service (proxy.
|
|
759
|
+
// An owned engine means the network is a service (proxy.stopWithDsh=false) or
|
|
583
760
|
// somebody is using it without a lease: retiring would tear it down, which
|
|
584
761
|
// is exactly what "follow daemon" promised not to do (review A2-P2-3).
|
|
585
762
|
if (!active && engineCwd === null) return stop()
|
|
@@ -620,6 +797,9 @@ export async function startRisd({ home, port = DEFAULT_RISD_PORT, version = '0.0
|
|
|
620
797
|
}
|
|
621
798
|
} catch { /* the workspace may have vanished */ }
|
|
622
799
|
}
|
|
800
|
+
// Record the now-empty set so a later `programs.startWithDsh` restore does not
|
|
801
|
+
// resurrect what this policy just stopped.
|
|
802
|
+
await saveProgramsSnapshot()
|
|
623
803
|
}
|
|
624
804
|
const startedAt = new Date().toISOString()
|
|
625
805
|
// The daemon code the page will render: captured NOW, because Node caches the
|
|
@@ -653,8 +833,145 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
653
833
|
engineOp = run.then(() => undefined, () => undefined)
|
|
654
834
|
return run
|
|
655
835
|
}
|
|
836
|
+
// 「代理引擎跟随 dsh」的启动半边(m13950 / m03397):与拆除共用**租约**这一条
|
|
837
|
+
// 链路——拆除看 leases.count() 归零(proxy.stopWithDsh),启动看第一份租约到达
|
|
838
|
+
// (proxy.startWithDsh),两边读同一条 lifecycle 的对应半边,所以不会出现
|
|
839
|
+
// 「启动跟了、停止没跟」的错位。
|
|
840
|
+
// 自动启动永不 interactive:dsh 接入的副作用不许弹密码框(m13910),需要 root
|
|
841
|
+
// 的桥接只在页面组件卡里提示。失败被吞掉并留给页面,那里还有显式按钮。
|
|
842
|
+
function followStartForLease(cwd) {
|
|
843
|
+
if (lifecycle.proxy.startWithDsh !== true) return Promise.resolve({ action: 'skipped', reason: 'not-following-dsh' })
|
|
844
|
+
if (followStarting !== null) return Promise.resolve({ action: 'skipped', reason: 'starting' })
|
|
845
|
+
if (engineSummary().state === 'running') return Promise.resolve({ action: 'skipped', reason: 'running' })
|
|
846
|
+
// The in-flight promise stays reachable: teardown must be able to wait for a
|
|
847
|
+
// start that the departing lease itself kicked off (see scheduleTeardown).
|
|
848
|
+
const work = (async () => {
|
|
849
|
+
// The lease may have left between the signal and this line (window closed
|
|
850
|
+
// during the round-trip): do not spawn an engine for nobody.
|
|
851
|
+
if (leases.count() === 0) return { action: 'skipped', reason: 'no-lease' }
|
|
852
|
+
const where = typeof cwd === 'string' && isAbsolute(cwd) && existsSync(cwd) ? cwd : home
|
|
853
|
+
const status = await proxyStatus(where)
|
|
854
|
+
// No actionable row means the engine would listen for nobody: following dsh is
|
|
855
|
+
// a policy, not a reason to spawn a process.
|
|
856
|
+
if (buildProfile(status.config).rules.length === 0) return { action: 'skipped', reason: 'no-rules' }
|
|
857
|
+
if (leases.count() === 0) return { action: 'skipped', reason: 'no-lease' }
|
|
858
|
+
const result = await serializeEngine(async () => {
|
|
859
|
+
const engine = await startProxy(where)
|
|
860
|
+
const redirector = await serializeBridge(() => startRedirectors({ interactive: false }))
|
|
861
|
+
noteBridgeStart(redirector)
|
|
862
|
+
if (redirector.running === true || (Array.isArray(redirector.started) && redirector.started.length > 0)) {
|
|
863
|
+
bridgeReloadState = { at: Date.now(), ok: true, note: '' }
|
|
864
|
+
}
|
|
865
|
+
const git = await syncGitProxy({ cwd: where, enabled: true })
|
|
866
|
+
if (engine.ok === true) {
|
|
867
|
+
engineCwd = where
|
|
868
|
+
cancelIdleExit()
|
|
869
|
+
}
|
|
870
|
+
return Object.assign({}, engine, { redirector, git })
|
|
871
|
+
})
|
|
872
|
+
return { action: result.ok === true ? 'started' : 'failed', result }
|
|
873
|
+
})()
|
|
874
|
+
followStarting = work.finally(() => {
|
|
875
|
+
followStarting = null
|
|
876
|
+
// The lease that started this may already be gone: let the teardown path run
|
|
877
|
+
// now that engineCwd is known (it skips while a start is pending).
|
|
878
|
+
if (leases.count() === 0) scheduleTeardown()
|
|
879
|
+
})
|
|
880
|
+
return followStarting
|
|
881
|
+
}
|
|
656
882
|
// Program start/stop share one queue so two clicks cannot spawn the same row twice.
|
|
657
883
|
let programOp = Promise.resolve()
|
|
884
|
+
|
|
885
|
+
// The programs that were still running when this daemon last wrote its state.
|
|
886
|
+
// `programs.startWithDsh` (m03397) restores them on the first dsh lease: a
|
|
887
|
+
// program is started per workspace and only the daemon knows what was live, so
|
|
888
|
+
// the alternative would be guessing from config — which starts programs the user
|
|
889
|
+
// had just stopped.
|
|
890
|
+
const PROGRAMS_SNAPSHOT_FILENAME = 'risd-programs-last.json'
|
|
891
|
+
/** Absolute path of the snapshot file (daemon home). */
|
|
892
|
+
function programsSnapshotPath() { return join(home, PROGRAMS_SNAPSHOT_FILENAME) }
|
|
893
|
+
/**
|
|
894
|
+
* Read the last snapshot. A broken or foreign file is "nothing was running":
|
|
895
|
+
* restoring a program is a convenience, never a correctness requirement.
|
|
896
|
+
* @returns `{cwd, id, dir}[]`.
|
|
897
|
+
*/
|
|
898
|
+
function readProgramsSnapshot() {
|
|
899
|
+
try {
|
|
900
|
+
const parsed = JSON.parse(readFileSync(programsSnapshotPath(), 'utf8'))
|
|
901
|
+
const rows = Array.isArray(parsed?.programs) ? parsed.programs : []
|
|
902
|
+
return rows
|
|
903
|
+
.filter((row) => typeof row?.cwd === 'string' && isAbsolute(row.cwd) && typeof row.id === 'string' && row.id !== '')
|
|
904
|
+
.map((row) => ({ cwd: row.cwd, id: row.id, dir: typeof row.dir === 'string' ? row.dir : '' }))
|
|
905
|
+
} catch { return [] }
|
|
906
|
+
}
|
|
907
|
+
// Serialized so two program actions cannot write a half-finished snapshot (a
|
|
908
|
+
// restore that reads while a stop is being recorded would resurrect a program).
|
|
909
|
+
let programSnapshotWork = Promise.resolve()
|
|
910
|
+
/** Record what is running right now (atomic write; failures are non-fatal). */
|
|
911
|
+
function saveProgramsSnapshot() {
|
|
912
|
+
const run = programSnapshotWork.then(async () => {
|
|
913
|
+
const rows = []
|
|
914
|
+
const cwds = new Set(workspaces)
|
|
915
|
+
if (typeof engineCwd === 'string' && engineCwd !== '') cwds.add(engineCwd)
|
|
916
|
+
for (const cwd of cwds) {
|
|
917
|
+
if (!existsSync(cwd)) continue
|
|
918
|
+
try {
|
|
919
|
+
const listed = await listPrograms(cwd, {})
|
|
920
|
+
for (const row of listed.programs) {
|
|
921
|
+
if (row.running === null || row.running === undefined || row.running.alive !== true) continue
|
|
922
|
+
rows.push({ cwd, id: row.id, dir: listed.dir })
|
|
923
|
+
}
|
|
924
|
+
} catch { /* a vanished workspace cannot be running anything we know */ }
|
|
925
|
+
}
|
|
926
|
+
try {
|
|
927
|
+
mkdirSync(home, { recursive: true, mode: 0o700 })
|
|
928
|
+
const path = programsSnapshotPath()
|
|
929
|
+
const tmp = `${path}.${process.pid}.tmp`
|
|
930
|
+
writeFileSync(tmp, `${JSON.stringify({ at: new Date().toISOString(), programs: rows }, null, 2)}\n`, { mode: 0o600 })
|
|
931
|
+
renameSync(tmp, path)
|
|
932
|
+
} catch { /* an unwritable home must not fail the program action */ }
|
|
933
|
+
}, () => {})
|
|
934
|
+
programSnapshotWork = run
|
|
935
|
+
return run
|
|
936
|
+
}
|
|
937
|
+
// One restore per daemon instance: a later lease must not undo a manual stop by
|
|
938
|
+
// starting the same programs again.
|
|
939
|
+
let programsRestored = false
|
|
940
|
+
/**
|
|
941
|
+
* Start the programs the snapshot remembers (first lease only).
|
|
942
|
+
* Never interactive and never fatal: a program that cannot start is left to the
|
|
943
|
+
* page, which has the explicit start button and the log that says why.
|
|
944
|
+
* @returns `{action, started, failed}`.
|
|
945
|
+
*/
|
|
946
|
+
async function restoreProgramsForLease() {
|
|
947
|
+
if (programsRestored === true) return { action: 'skipped', reason: 'already-restored' }
|
|
948
|
+
programsRestored = true
|
|
949
|
+
if (lifecycle.programs.startWithDsh !== true) return { action: 'skipped', reason: 'not-following-dsh' }
|
|
950
|
+
const rows = readProgramsSnapshot()
|
|
951
|
+
if (rows.length === 0) return { action: 'skipped', reason: 'nothing-to-restore' }
|
|
952
|
+
const started = []
|
|
953
|
+
const failed = []
|
|
954
|
+
for (const row of rows) {
|
|
955
|
+
// The lease that triggered this may already be gone (a window that opened and
|
|
956
|
+
// closed): starting programs for nobody is exactly the leak teardown avoids.
|
|
957
|
+
if (leases.count() === 0) break
|
|
958
|
+
if (!existsSync(row.cwd)) continue
|
|
959
|
+
try {
|
|
960
|
+
const listed = await listPrograms(row.cwd, { dir: row.dir })
|
|
961
|
+
const live = listed.programs.find((item) => item.id === row.id)
|
|
962
|
+
if (live !== undefined && live.running !== null && live.running !== undefined && live.running.alive === true) continue
|
|
963
|
+
rememberWorkspace(row.cwd)
|
|
964
|
+
const result = await (programOp = programOp.then(
|
|
965
|
+
async () => startProgramByKey(row.cwd, row.id, { dir: row.dir }),
|
|
966
|
+
() => ({ ok: false }),
|
|
967
|
+
))
|
|
968
|
+
if (result !== null && result !== undefined && result.ok === true) started.push(row.id)
|
|
969
|
+
else failed.push(row.id)
|
|
970
|
+
} catch { failed.push(row.id) }
|
|
971
|
+
}
|
|
972
|
+
if (started.length > 0) await saveProgramsSnapshot()
|
|
973
|
+
return { action: 'restored', started, failed }
|
|
974
|
+
}
|
|
658
975
|
// Bridge (ProxyBridge) operations are serialized too (E8): a rule reload and a
|
|
659
976
|
// stop are two single-file handshakes with the elevated watchdog, and running
|
|
660
977
|
// them concurrently can reload a profile the other side is already tearing down.
|
|
@@ -760,13 +1077,21 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
760
1077
|
}
|
|
761
1078
|
|
|
762
1079
|
if (path === '/v1/dsh' && method === 'GET') {
|
|
763
|
-
//
|
|
764
|
-
// as an upserted list (origin + sessionId per
|
|
765
|
-
//
|
|
1080
|
+
// What should the page's workspace panel list, and what is each one called?
|
|
1081
|
+
// The plugin keeps dsh-window.json as an upserted list (origin + sessionId per
|
|
1082
|
+
// workspace) AND, since m13800, the sidebar's workspace list with its titles
|
|
1083
|
+
// (title is what a rename changes; the path never moves). Both halves are read
|
|
1084
|
+
// here so the panel mirrors the dsh sidebar instead of guessing from folders.
|
|
766
1085
|
let windows = []
|
|
1086
|
+
let sidebar = []
|
|
1087
|
+
let documentOrigin = ''
|
|
1088
|
+
let documentAt = Number.NaN
|
|
767
1089
|
try {
|
|
768
1090
|
const parsed = JSON.parse(readFileSync(join(home, DSH_WINDOW_FILENAME), 'utf8'))
|
|
769
1091
|
if (Array.isArray(parsed?.windows)) windows = parsed.windows
|
|
1092
|
+
if (Array.isArray(parsed?.workspaces)) sidebar = parsed.workspaces
|
|
1093
|
+
if (typeof parsed?.url === 'string') documentOrigin = parsed.url
|
|
1094
|
+
documentAt = Date.parse(String(parsed?.at ?? ''))
|
|
770
1095
|
} catch { /* absent or rotated away: no dsh */ }
|
|
771
1096
|
const now = Date.now()
|
|
772
1097
|
let droppedAt = 0
|
|
@@ -775,7 +1100,7 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
775
1100
|
// The page hands this URL to window.open(); anything but a loopback
|
|
776
1101
|
// http(s) origin would let a crafted dsh-window.json point the IDE tab
|
|
777
1102
|
// somewhere else (review A-P2-10).
|
|
778
|
-
.filter((row) =>
|
|
1103
|
+
.filter((row) => isLoopbackOrigin(row.url))
|
|
779
1104
|
.map((row) => {
|
|
780
1105
|
const at = Date.parse(String(row.at ?? ''))
|
|
781
1106
|
// A timestamp far in the future made `now - at` clamp to 0, so the row
|
|
@@ -791,6 +1116,10 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
791
1116
|
return {
|
|
792
1117
|
cwd: typeof row.cwd === 'string' ? row.cwd : '',
|
|
793
1118
|
sessionId: typeof row.sessionId === 'string' ? row.sessionId : '',
|
|
1119
|
+
// The sidebar title the plugin resolved for this path (m13800). '' when
|
|
1120
|
+
// the host has no workspace registry (older dsh): the page then falls
|
|
1121
|
+
// back to the folder name it always used.
|
|
1122
|
+
title: typeof row.title === 'string' ? row.title : '',
|
|
794
1123
|
url: row.url,
|
|
795
1124
|
ageMs: Number.isFinite(at) && !future ? Math.max(0, now - at) : DSH_WINDOW_RETAIN_MS + 1,
|
|
796
1125
|
}
|
|
@@ -800,29 +1129,73 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
800
1129
|
// Live entries first, then most-recently-seen: the first row is the one an
|
|
801
1130
|
// iframe deep link opens by default.
|
|
802
1131
|
.sort((a, b) => (a.live === b.live ? a.ageMs - b.ageMs : a.live ? -1 : 1))
|
|
803
|
-
|
|
804
|
-
|
|
1132
|
+
const origin = isLoopbackOrigin(documentOrigin)
|
|
1133
|
+
? documentOrigin
|
|
1134
|
+
: (live.length > 0 ? live[0].url : '')
|
|
1135
|
+
// The sidebar snapshot is only as fresh as its writer: dsh writes it on every
|
|
1136
|
+
// request and every refresh tick, so a document older than the retain window
|
|
1137
|
+
// means dsh is gone and the list is stale. Rows of remembered windows are
|
|
1138
|
+
// then the only truth (and they age out on their own).
|
|
1139
|
+
const sidebarFresh = Number.isFinite(documentAt)
|
|
1140
|
+
&& documentAt <= now + 5 * 60_000
|
|
1141
|
+
&& now - documentAt <= DSH_WINDOW_RETAIN_MS
|
|
1142
|
+
let rows = []
|
|
1143
|
+
if (sidebarFresh && sidebar.length > 0 && origin !== '') {
|
|
1144
|
+
rows = dshSidebarRows(sidebar, live, origin)
|
|
1145
|
+
} else {
|
|
1146
|
+
rows.push(...live)
|
|
1147
|
+
}
|
|
1148
|
+
// Direct fallback (m00186): the shared document can be missing, unreadable or
|
|
1149
|
+
// last written by a different dsh instance while a host on this machine is
|
|
1150
|
+
// alive. Each running plugin advertises its origin under `instances/`, so ask
|
|
1151
|
+
// the hosts themselves instead of telling the user dsh is not running.
|
|
1152
|
+
let known = sidebar.length
|
|
1153
|
+
if (rows.length === 0) {
|
|
1154
|
+
for (const candidate of dshProbeCandidates(home, now, documentOrigin, live)) {
|
|
1155
|
+
const snapshot = await probeDshWorkspaces(candidate)
|
|
1156
|
+
if (snapshot === null) continue
|
|
1157
|
+
const probedOrigin = isLoopbackOrigin(snapshot?.url) ? snapshot.url : candidate
|
|
1158
|
+
const probedSidebar = Array.isArray(snapshot?.workspaces) ? snapshot.workspaces : []
|
|
1159
|
+
const probedRows = dshSidebarRows(probedSidebar, [], probedOrigin)
|
|
1160
|
+
if (probedRows.length === 0) continue
|
|
1161
|
+
rows = probedRows
|
|
1162
|
+
known = Math.max(known, probedSidebar.length)
|
|
1163
|
+
break
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
if (rows.length === 0) {
|
|
1167
|
+
// "No dsh" and "dsh is there but nothing usable arrived" are different: the
|
|
1168
|
+
// page can only name a count in the second case (m00186).
|
|
1169
|
+
const reason = known > 0
|
|
1170
|
+
? `已发现 ${known} 个 dsh 工作区,但没有可用的 IDE 地址(dsh 可能刚启动,稍后会自动重试)`
|
|
1171
|
+
: 'dsh 未运行(没有记住的工作区窗口,也没有侧栏快照)'
|
|
1172
|
+
return json(res, 200, { ok: true, available: false, windows: [], dropped: droppedAt, knownWorkspaces: known, reason })
|
|
805
1173
|
}
|
|
806
|
-
const newest =
|
|
1174
|
+
const newest = rows[0]
|
|
807
1175
|
return json(res, 200, {
|
|
808
1176
|
ok: true,
|
|
809
1177
|
available: true,
|
|
810
1178
|
url: newest.url,
|
|
811
1179
|
sessionId: newest.sessionId,
|
|
812
1180
|
cwd: newest.cwd,
|
|
813
|
-
windows:
|
|
1181
|
+
windows: rows,
|
|
814
1182
|
dropped: droppedAt,
|
|
1183
|
+
knownWorkspaces: rows.length,
|
|
815
1184
|
})
|
|
816
1185
|
}
|
|
817
1186
|
|
|
818
1187
|
if (path === '/v1/proxy/ping' && method === 'GET') {
|
|
819
1188
|
// Reachability of the configured SOCKS upstream, for the status chip on the
|
|
820
1189
|
// proxy tab. Query overrides let the page test an edited-but-unsaved value.
|
|
821
|
-
const
|
|
1190
|
+
const config = readProxyConfig(url.searchParams.get('cwd') ?? home)
|
|
1191
|
+
const stored = config.socks
|
|
822
1192
|
const host = url.searchParams.get('host') ?? stored.host
|
|
823
1193
|
const rawPort = url.searchParams.get('port')
|
|
824
1194
|
const port = rawPort === null ? stored.port : Number(rawPort)
|
|
825
|
-
|
|
1195
|
+
// m03429: a greeting only proves "something speaks SOCKS5 here". When the
|
|
1196
|
+
// config names a concrete destination, finish the handshake with a real
|
|
1197
|
+
// CONNECT so "usable" means the tunnel actually forwards.
|
|
1198
|
+
const result = await pingSocks({ host, port, target: probeTarget(config) })
|
|
826
1199
|
return json(res, 200, result)
|
|
827
1200
|
}
|
|
828
1201
|
|
|
@@ -1085,11 +1458,17 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
1085
1458
|
bridgeReloadState = { at: Date.now(), ok: false, note }
|
|
1086
1459
|
}
|
|
1087
1460
|
}
|
|
1461
|
+
// A save does not start anything (m13920): it only reloads an enforcement
|
|
1462
|
+
// that is already running, so the note must not promise a restart the daemon
|
|
1463
|
+
// will not perform.
|
|
1464
|
+
const bridgeWasRunning = redirectorStatusCached().running === true
|
|
1088
1465
|
setImmediate(() => { switchEnforcement().catch(() => {}) })
|
|
1089
1466
|
return json(res, 200, {
|
|
1090
1467
|
ok: true,
|
|
1091
1468
|
revision: risdConfigRevision(written),
|
|
1092
|
-
reloadNote:
|
|
1469
|
+
reloadNote: bridgeWasRunning
|
|
1470
|
+
? '规则已保存;系统层拦截正在后台按新规则重启'
|
|
1471
|
+
: '规则已保存;引擎未启动,保存不会启动它',
|
|
1093
1472
|
git,
|
|
1094
1473
|
})
|
|
1095
1474
|
}
|
|
@@ -1102,12 +1481,20 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
1102
1481
|
if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
|
|
1103
1482
|
const action = typeof parsed.action === 'string' ? parsed.action : 'status'
|
|
1104
1483
|
const gitHost = typeof parsed.gitHost === 'string' ? parsed.gitHost : undefined
|
|
1484
|
+
// Only a click may raise a system password dialog (review B-P0-2): the
|
|
1485
|
+
// auto-start that follows a save calls the same route, and an implicit
|
|
1486
|
+
// action must never pop one (m13910).
|
|
1487
|
+
const interactive = parsed.interactive === true
|
|
1488
|
+
// Enforcement came up (or was already up): the stale "could not reload"
|
|
1489
|
+
// note is history, and leaving it made the restart button outlive its cause.
|
|
1490
|
+
const clearBridgeNote = () => { bridgeReloadState = { at: Date.now(), ok: true, note: '' } }
|
|
1105
1491
|
let result
|
|
1106
1492
|
if (action === 'start') {
|
|
1107
1493
|
result = await serializeEngine(async () => {
|
|
1108
1494
|
const engine = await startProxy(cwd)
|
|
1109
|
-
const redirector = await serializeBridge(() => startRedirectors({ interactive
|
|
1495
|
+
const redirector = await serializeBridge(() => startRedirectors({ interactive }))
|
|
1110
1496
|
noteBridgeStart(redirector)
|
|
1497
|
+
if (redirector.running === true || (Array.isArray(redirector.started) && redirector.started.length > 0)) clearBridgeNote()
|
|
1111
1498
|
const git = await syncGitProxy({ cwd, host: gitHost, enabled: true })
|
|
1112
1499
|
if (engine.ok === true) {
|
|
1113
1500
|
engineCwd = cwd
|
|
@@ -1152,8 +1539,9 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
1152
1539
|
result = await serializeBridge(async () => {
|
|
1153
1540
|
const stopped = await stopRedirector()
|
|
1154
1541
|
await new Promise((resolve) => setTimeout(resolve, 300))
|
|
1155
|
-
const started = await startRedirectors({ interactive
|
|
1542
|
+
const started = await startRedirectors({ interactive })
|
|
1156
1543
|
noteBridgeStart(started)
|
|
1544
|
+
if (started.running === true || (Array.isArray(started.started) && started.started.length > 0)) clearBridgeNote()
|
|
1157
1545
|
return {
|
|
1158
1546
|
stopped,
|
|
1159
1547
|
started: started.started ?? [],
|
|
@@ -1218,6 +1606,9 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
1218
1606
|
return fail(res, error?.status ?? 500, error?.code ?? 'program-failed', error?.message ?? String(error))
|
|
1219
1607
|
}
|
|
1220
1608
|
if (result.ok !== true) return fail(res, result.status ?? 500, result.code ?? 'program-failed', result.message ?? 'program operation failed')
|
|
1609
|
+
// Keep `risd-programs-last.json` in step with reality: `programs.startWithDsh`
|
|
1610
|
+
// restores exactly this set on the next dsh attach (m03397).
|
|
1611
|
+
await saveProgramsSnapshot()
|
|
1221
1612
|
return json(res, 200, Object.assign({ ok: true, action }, result))
|
|
1222
1613
|
}
|
|
1223
1614
|
|
|
@@ -1349,6 +1740,17 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
1349
1740
|
const sessionId = parsed.sessionId === undefined ? null : String(parsed.sessionId)
|
|
1350
1741
|
cancelIdleExit()
|
|
1351
1742
|
const lease = leases.acquire({ ownerPid, sessionId, cwd })
|
|
1743
|
+
// The start half of 「跟随 dsh」: the policy is read when the lease arrives,
|
|
1744
|
+
// the same signal the teardown watches. Off the response path (starting the
|
|
1745
|
+
// engine costs seconds), and never interactive.
|
|
1746
|
+
if (lifecycle.proxy.startWithDsh === true && engineSummary().state !== 'running') {
|
|
1747
|
+
setImmediate(() => { followStartForLease(lease.cwd).catch(() => {}) })
|
|
1748
|
+
}
|
|
1749
|
+
// The programs start half (m03397) rides the same signal: the first dsh of
|
|
1750
|
+
// this daemon instance restores what was running when it last went away.
|
|
1751
|
+
if (programsRestored !== true && lifecycle.programs.startWithDsh === true) {
|
|
1752
|
+
setImmediate(() => { restoreProgramsForLease().catch(() => {}) })
|
|
1753
|
+
}
|
|
1352
1754
|
return json(res, 200, { ok: true, lease })
|
|
1353
1755
|
}
|
|
1354
1756
|
|
|
@@ -1387,7 +1789,7 @@ let bridgeReloadState = { at: 0, ok: true, note: '' }
|
|
|
1387
1789
|
lifecycle = written.value
|
|
1388
1790
|
// Re-arm the idle timer with the new policy: turning "follow dsh" off
|
|
1389
1791
|
// must not leave a timer armed from before the change.
|
|
1390
|
-
if (lifecycle.daemon.
|
|
1792
|
+
if (lifecycle.daemon.stopWithDsh !== true) cancelIdleExit()
|
|
1391
1793
|
else if (leases.count() === 0 && engineCwd === null) scheduleIdleExit()
|
|
1392
1794
|
return json(res, 200, { ok: true, lifecycle, configPath: join(home, 'risd-lifecycle.json') })
|
|
1393
1795
|
}
|