dsh-remote-go 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,24 +1,40 @@
1
1
  /**
2
2
  * The connect pipeline: SSH -> probe -> managed Node -> plan -> adopt/conflict -> preflight -> start -> tunnel -> verify; the step order is the behavior and every step is injected.
3
3
  */
4
- import { REMOTE_START_TIMEOUT_MS, SSH_READY_TIMEOUT_MS, TUNNEL_PROBE_TIMEOUT_MS } from './constants.js'
5
- import { errors, toErrorView } from './errors.js'
4
+ import {
5
+ REMOTE_REATTACH_ATTEMPTS,
6
+ REMOTE_REATTACH_INTERVAL_MS,
7
+ REMOTE_REPAIR_BACKOFF_MAX_MS,
8
+ REMOTE_REPAIR_BACKOFF_MS,
9
+ REMOTE_START_TIMEOUT_MS,
10
+ SSH_READY_TIMEOUT_MS,
11
+ TUNNEL_PROBE_TIMEOUT_MS,
12
+ } from './constants.js'
13
+ import { beginConnectLog } from './connect-log.js'
14
+ import { errors, RemoteGoError, toErrorView } from './errors.js'
6
15
  import { runtimeOf } from './host-registry.js'
7
16
  import {
17
+ beginLinkWork,
8
18
  cancelIdleStop,
19
+ cancelLinkWork,
9
20
  cancelReconnect,
10
21
  closeTunnel,
11
22
  disconnectHost,
12
23
  disposeSsh,
24
+ endLinkWork,
25
+ isLinkWorkCurrent,
13
26
  scheduleReconnect,
27
+ startRemoteHeartbeat,
28
+ stopRemoteHeartbeat,
14
29
  teardownRuntime,
15
30
  } from './host-lifecycle.js'
16
31
  import { findKnownHostEntries, parseKnownHosts } from './known-hosts.js'
17
- import { remoteLayout } from './layout.js'
32
+ import { layoutForRuntime } from './layout.js'
18
33
  import { applyManagedNodeFacts, managedNodeVersionFromEngine } from './node-runtime.js'
19
- import { askConflict, requestHostKey } from './prompts.js'
34
+ import { askConflict, cancelConflict, cancelHostKeyPrompt, requestHostKey } from './prompts.js'
35
+ import { buildRunRegistryRecord, commandMatchesProfile } from './remote-web.js'
20
36
  import { resolveDestination } from './ssh-config.js'
21
- import { isPid, messageOf, nowIso } from './util.js'
37
+ import { isPid, messageOf, nowIso, sleep } from './util.js'
22
38
  import { normalizeVersion, versionsEqual } from './version.js'
23
39
 
24
40
  function describeTarget(entry) {
@@ -27,6 +43,88 @@ function describeTarget(entry) {
27
43
  return `${user}${entry.address || '?'}${port}`
28
44
  }
29
45
 
46
+ /** The bilingual detail of "the transport this step needed is gone". */
47
+ const SSH_CLOSED_DETAIL = {
48
+ zh: 'SSH 连接已断开,本次操作没有完成;如果主机仍在线,重连即可继续。',
49
+ en: 'SSH connection is not open; the transport closed before this step finished. Reconnect to continue.',
50
+ }
51
+
52
+ /**
53
+ * Internal marker: a pipeline step ran after the user (or the host process) took the link
54
+ * away. It is not a connection failure, so it never reaches the Client as an error.
55
+ */
56
+ class LinkCancelled extends Error {
57
+ constructor(reason) {
58
+ super(`connect aborted: ${reason}`)
59
+ this.name = 'LinkCancelled'
60
+ this.code = 'link-cancelled'
61
+ }
62
+ }
63
+
64
+ /** Whether the link is no longer wanted: disconnect, host removal, teardown or shutdown. */
65
+ function linkTaken(ctx, runtime) {
66
+ return (
67
+ ctx.state.disposed === true ||
68
+ runtime.closing === true ||
69
+ runtime.desired !== 'connected' ||
70
+ !ctx.state.runtimes.has(runtime.id)
71
+ )
72
+ }
73
+
74
+ /** Throw unless this attempt may still write state (H4). */
75
+ function assertStillWanted(ctx, runtime) {
76
+ if (linkTaken(ctx, runtime)) throw new LinkCancelled('the link is no longer wanted')
77
+ }
78
+
79
+ /** Throw a typed transport error unless the SSH transport is still open (H3). */
80
+ function assertTransportOpen(runtime) {
81
+ if (runtime.ssh?.connected !== true) {
82
+ throw errors.network(SSH_CLOSED_DETAIL, { technical: 'reason=ssh-closed' })
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Classify a pipeline failure. A step that raced the transport going away must read as a
88
+ * dropped connection (`network`, retryable), never as a bare `internal` error or as a key
89
+ * decision the user never made (H3).
90
+ * @param {object} runtime - host runtime.
91
+ * @param {unknown} error - the thrown value.
92
+ * @returns {object} the Client-facing error view.
93
+ */
94
+ function normalizeConnectFailure(runtime, error) {
95
+ const view = toErrorView(error)
96
+ if (runtime.transportLost === true && runtime.ssh?.connected !== true) {
97
+ // A prompt parked on the transport was resolved by the close itself: the user made no
98
+ // decision, so this must not read as "confirm the host key" / "a manual DSH is running".
99
+ if (view.code === 'host-key-unknown' || view.code === 'remote-dsh-running') {
100
+ return toErrorView(
101
+ errors.network(SSH_CLOSED_DETAIL, {
102
+ technical: `reason=ssh-closed phase-code=${view.code}`,
103
+ }),
104
+ )
105
+ }
106
+ }
107
+ if (runtime.ssh?.connected === true) {
108
+ if (
109
+ !(error instanceof RemoteGoError) &&
110
+ /\b(?:not open|closed|ECONNRESET|EPIPE|Channel closed)\b/i.test(String(error?.message ?? ''))
111
+ ) {
112
+ return toErrorView(
113
+ errors.network(SSH_CLOSED_DETAIL, { technical: `reason=ssh-closed cause=${error?.message ?? error}` }),
114
+ )
115
+ }
116
+ return view
117
+ }
118
+ if (view.code === 'internal' || view.code === 'remote-dsh-missing' || view.code === 'remote-node-install-failed') {
119
+ return toErrorView(
120
+ errors.network(SSH_CLOSED_DETAIL, {
121
+ technical: `reason=ssh-closed phase-code=${view.code} cause=${error instanceof Error ? error.message : String(error ?? '')}`,
122
+ }),
123
+ )
124
+ }
125
+ return view
126
+ }
127
+
30
128
  /**
31
129
  * Accept a connect request: apply the one-time inputs, stop any pending retry,
32
130
  * and start the pipeline in the background. Progress travels on `state`.
@@ -35,15 +133,33 @@ export async function startConnect(ctx, id, options = {}) {
35
133
  await ctx.init()
36
134
  const runtime = runtimeOf(ctx, id)
37
135
  if (runtime.connectPromise) return { accepted: false, reason: 'already-connecting' }
136
+ if (runtime.linkBusy !== null) return { accepted: false, reason: 'already-restarting' }
38
137
  if (runtime.status === 'connected' && runtime.ssh?.connected) return { accepted: false, reason: 'already-connected' }
39
- runtime.password = options.password ?? runtime.password
40
- // A password the user asked to remember is written to the credential store the
41
- // moment it is known, so a failed first attempt still leaves it available.
42
- if (options.rememberPassword === true && typeof runtime.password === 'string' && runtime.password !== '') {
43
- runtime.savePassword = true
44
- }
138
+ // A new connect owns the link from here on: any pending one-shot action is stale.
139
+ cancelLinkWork(runtime)
140
+ // An idle host keeps a timer that would stop the remote web; connecting again makes that
141
+ // policy stale (the timer used to fire into a live link: review blocker 1).
142
+ cancelIdleStop(runtime)
143
+ stopRemoteHeartbeat(runtime)
144
+ runtime.alongsidePids = []
145
+ const typedPassword = typeof options.password === 'string' && options.password !== '' ? options.password : null
146
+ if (typedPassword !== null) runtime.password = typedPassword
147
+ // Remembering is the default for a password the user just typed (`POST /hosts/:id/connect`
148
+ // treats an absent `rememberPassword` as true). An explicit false means "this connection
149
+ // only" and also forgets a previously saved record, so an unchecked box cannot leave a stale
150
+ // secret behind. A retry or auto-reconnect carries no password of its own and must not
151
+ // re-save what the store already holds.
152
+ runtime.savePassword = typedPassword !== null && options.rememberPassword !== false
153
+ runtime.forgetPassword = typedPassword !== null && options.rememberPassword === false
45
154
  runtime.desired = 'connected'
46
155
  cancelReconnect(runtime)
156
+ // A user-initiated connect gets a fresh retry budget and a fresh prompt history; a retry
157
+ // that the pipeline schedules itself must keep the budget it already spent (H2).
158
+ runtime.reconnectAttempts = 0
159
+ runtime.connectCancelled = false
160
+ // This connection starts its own log: the previous attempt's lines are gone before the
161
+ // first line of this one, so the panel and a copied log only ever show the live attempt.
162
+ beginConnectLog(runtime)
47
163
  ctx.progress.log(
48
164
  runtime,
49
165
  'info',
@@ -51,17 +167,39 @@ export async function startConnect(ctx, id, options = {}) {
51
167
  runtime.entry.jumpHost ? `, jump=${runtime.entry.jumpHost}` : ''
52
168
  })`,
53
169
  )
54
- runtime.connectPromise = connectPipeline(ctx, runtime).finally(() => {
55
- runtime.connectPromise = null
56
- })
170
+ startConnectPromise(ctx, runtime)
57
171
  return { accepted: true }
58
172
  }
59
173
 
174
+ /**
175
+ * Start the pipeline in the background and make sure its promise never rejects: a listener
176
+ * or a step outside the pipeline's own error handling must not become an unhandled
177
+ * rejection that Node reports as a process-level failure (L).
178
+ * @param {object} ctx - service context.
179
+ * @param {object} runtime - host runtime.
180
+ */
181
+ function startConnectPromise(ctx, runtime) {
182
+ const run = connectPipeline(ctx, runtime).catch((error) => {
183
+ ctx.progress.log(runtime, 'debug', 'connect pipeline stopped outside its error path:', messageOf(error))
184
+ })
185
+ runtime.connectPromise = run
186
+ void run.finally(() => {
187
+ if (runtime.connectPromise === run) runtime.connectPromise = null
188
+ })
189
+ }
190
+
60
191
  /** Drop the current link and connect again from scratch (the "Reconnect" button). */
61
192
  export async function reconnectHost(ctx, runtime) {
62
193
  await disconnectHost(ctx, runtime, { stopRemote: false })
63
194
  cancelIdleStop(runtime)
64
195
  await disposeSsh(runtime)
196
+ // A one-shot action cancelled by the disconnect resolves after its transport is gone; it
197
+ // can no longer write state, but letting it settle keeps the old code out of the new run.
198
+ await Promise.allSettled(
199
+ [runtime.restartPromise, runtime.reattachPromise].filter(
200
+ (promise) => promise && typeof promise.then === 'function',
201
+ ),
202
+ )
65
203
  return startConnect(ctx, runtime.id, {})
66
204
  }
67
205
 
@@ -72,24 +210,76 @@ export async function reconnectHost(ctx, runtime) {
72
210
  async function reconnectNow(ctx, runtime) {
73
211
  if (ctx.state.disposed || runtime.desired !== 'connected') return
74
212
  await disposeSsh(runtime)
75
- runtime.connectPromise = connectPipeline(ctx, runtime).finally(() => {
76
- runtime.connectPromise = null
213
+ // A dropped link's retry is a new connection too: start from a clean log.
214
+ beginConnectLog(runtime)
215
+ startConnectPromise(ctx, runtime)
216
+ }
217
+
218
+ /** A timer callback that starts a retry: report a throw instead of leaving it unhandled (L). */
219
+ function retryNow(ctx, runtime) {
220
+ void reconnectNow(ctx, runtime).catch((error) => {
221
+ ctx.progress.log(runtime, 'warn', 'the automatic retry could not start:', messageOf(error))
77
222
  })
78
223
  }
79
224
 
225
+ /**
226
+ * Watch a transport that is still being dialled. `SshConnection` attaches its client `close`
227
+ * handling before the handshake, so a transport that dies while a host-key prompt is parked
228
+ * reaches this listener: the prompt is settled at once (instead of waiting for its timeout)
229
+ * and the loss is recorded so the pipeline classifies the failure as a dropped link, not a
230
+ * key decision (H3/M1).
231
+ * @param {object} runtime - host runtime.
232
+ * @param {object} ssh - the transport that was just created.
233
+ */
234
+ function watchHandshakeTransport(runtime, ssh) {
235
+ if (!ssh || typeof ssh.on !== 'function') return
236
+ ssh.on('close', () => {
237
+ // A transport this runtime no longer dials (replaced, or disposed before a new attempt)
238
+ // is not a lost link: its close is the teardown itself.
239
+ if (runtime.ssh !== ssh && runtime.jumpSsh !== ssh) return
240
+ if (runtime.closing || runtime.desired !== 'connected') return
241
+ runtime.transportLost = true
242
+ cancelHostKeyPrompt(runtime)
243
+ })
244
+ }
245
+
246
+ /**
247
+ * Watch the transport that carries this connection. Attached as soon as the SSH session is
248
+ * open (not only when the remote UI is ready): a drop during probe/bootstrap is still a
249
+ * lost link and must be retried like any other (H3).
250
+ */
80
251
  function attachDisconnectHandler(ctx, runtime) {
81
252
  const ssh = runtime.ssh
82
253
  if (!ssh) return
83
254
  ssh.on('close', () => {
84
- if (runtime.closing || runtime.desired !== 'connected' || runtime.status !== 'connected') return
85
- runtime.status = 'disconnected'
86
- runtime.phase = null
87
- runtime.remote.uiReady = false
88
- runtime.remote.localPort = null
89
- runtime.progress = { code: 'reconnecting', params: { attempt: runtime.reconnectAttempts + 1 } }
90
- ctx.emitState()
91
- void closeTunnel(runtime)
92
- scheduleReconnect(ctx, runtime, () => void reconnectNow(ctx, runtime))
255
+ if (runtime.closing || runtime.desired !== 'connected') return
256
+ // A newer transport already owns the link; this one is the previous attempt's.
257
+ if (runtime.ssh !== ssh) return
258
+ runtime.transportLost = true
259
+ // A one-shot link action rides the same transport: losing it is the same event as a
260
+ // dropped connection, and the action that was in flight must not write state any more.
261
+ const live = runtime.status === 'connected' || runtime.linkBusy !== null
262
+ const inFlight = runtime.connectPromise !== null
263
+ if (!live && !inFlight) return
264
+ cancelLinkWork(runtime)
265
+ stopRemoteHeartbeat(runtime)
266
+ // A prompt parked on this transport can never be answered: resolve it now.
267
+ cancelHostKeyPrompt(runtime)
268
+ cancelConflict(runtime)
269
+ if (live) {
270
+ runtime.status = 'disconnected'
271
+ runtime.phase = null
272
+ runtime.remote.uiReady = false
273
+ runtime.remote.localPort = null
274
+ runtime.progress = { code: 'reconnecting', params: { attempt: runtime.reconnectAttempts + 1 } }
275
+ ctx.emitState()
276
+ void closeTunnel(runtime)
277
+ scheduleReconnect(ctx, runtime, () => retryNow(ctx, runtime))
278
+ return
279
+ }
280
+ // The pipeline that owns the in-flight connect reports the drop as `network` and
281
+ // schedules the retry from one place, so it is not counted twice here (H2/H3).
282
+ ctx.progress.log(runtime, 'warn', 'the SSH transport closed while the connection was being set up')
93
283
  })
94
284
  }
95
285
 
@@ -116,32 +306,56 @@ async function resolveTargetForRuntime(ctx, runtime) {
116
306
  }
117
307
  }
118
308
 
119
- /** Open the transport: direct, or through a jump host with a forwarded stream. */
309
+ /**
310
+ * Open the transport: direct, or through a jump host with a forwarded stream.
311
+ *
312
+ * The jump host and the target are separate security contexts. Each one gets its own
313
+ * options — its own policy, its own pin and its own `onHostKey` role — so a key confirmed
314
+ * for one can never be checked against, or written into, the other (B1).
315
+ */
120
316
  async function openTransport(ctx, runtime, target) {
121
317
  const settings = ctx.settings()
122
- const buildOptions = (resolved, sock) => ({
123
- host: resolved.host,
124
- port: resolved.port ?? 22,
125
- username: resolved.username ?? resolved.user ?? null,
126
- // The key path expands against the *user* home (`~/.ssh/...`), never against
127
- // DSH_HOME, so the SSH layer needs to know which one that is.
128
- home: ctx.userHome(),
129
- auth: {
130
- type: runtime.entry.auth?.type ?? 'key',
131
- keyPath: runtime.entry.auth?.keyPath ?? null,
132
- password: runtime.password ?? null,
133
- },
134
- identityFiles: resolved.identityFiles ?? [],
135
- hostKeyPolicy: runtime.entry.hostKeyPolicy ?? settings.hostKeyPolicy,
136
- pinnedFingerprint: runtime.entry.pinnedFingerprint ?? null,
137
- knownHostFingerprints: resolved.knownFingerprints ?? [],
138
- acceptUnknownHostKey: false,
139
- readyTimeoutMs: settings.connectTimeoutSec * 1000 || SSH_READY_TIMEOUT_MS,
140
- ...(sock ? { sock } : {}),
141
- onHostKey: (info) => requestHostKey(ctx, runtime, info),
318
+ const auth = () => ({
319
+ type: runtime.entry.auth?.type ?? 'key',
320
+ keyPath: runtime.entry.auth?.keyPath ?? null,
321
+ password: runtime.password ?? null,
142
322
  })
323
+ const buildOptions = (resolved, role, sock) => {
324
+ const isJump = role === 'jump'
325
+ // A per-host policy and pin describe the saved target. A jump host only obeys the
326
+ // global policy and, at most, a pin remembered for this session (it is not persisted).
327
+ const hostKeyPolicy = isJump ? settings.hostKeyPolicy : (runtime.entry.hostKeyPolicy ?? settings.hostKeyPolicy)
328
+ const resolvedPort = resolved.port ?? 22
329
+ const jumpPinMatches =
330
+ isJump &&
331
+ runtime.jumpFingerprint?.host === resolved.host &&
332
+ (Number(runtime.jumpFingerprint?.port) || 22) === resolvedPort
333
+ const pinnedFingerprint = isJump
334
+ ? jumpPinMatches
335
+ ? (runtime.jumpFingerprint?.pinned ?? null)
336
+ : null
337
+ : (runtime.entry.pinnedFingerprint ?? null)
338
+ return {
339
+ host: resolved.host,
340
+ port: resolvedPort,
341
+ username: resolved.username ?? resolved.user ?? null,
342
+ // The key path expands against the *user* home (`~/.ssh/...`), never against
343
+ // DSH_HOME, so the SSH layer needs to know which one that is.
344
+ home: ctx.userHome(),
345
+ auth: auth(),
346
+ identityFiles: resolved.identityFiles ?? [],
347
+ hostKeyPolicy,
348
+ pinnedFingerprint,
349
+ knownHostFingerprints: resolved.knownFingerprints ?? [],
350
+ acceptUnknownHostKey: false,
351
+ readyTimeoutMs: settings.connectTimeoutSec * 1000 || SSH_READY_TIMEOUT_MS,
352
+ ...(sock ? { sock } : {}),
353
+ onHostKey: (info) => requestHostKey(ctx, runtime, info, { role, host: resolved.host, port: resolvedPort }),
354
+ }
355
+ }
143
356
  if (!target.jumpHost) {
144
- runtime.ssh = ctx.deps.sshFactory(buildOptions(target))
357
+ runtime.ssh = ctx.deps.sshFactory(buildOptions(target, 'target'))
358
+ watchHandshakeTransport(runtime, runtime.ssh)
145
359
  ctx.progress.phase(runtime, 'ssh', 'ssh-connecting', { host: target.host })
146
360
  captureFingerprint(ctx, runtime, await runtime.ssh.connect())
147
361
  return
@@ -156,11 +370,28 @@ async function openTransport(ctx, runtime, target) {
156
370
  target.jumpHost.port ?? 22,
157
371
  ).map((item) => item.fingerprint),
158
372
  }
159
- runtime.jumpSsh = ctx.deps.sshFactory(buildOptions(jumpTarget))
373
+ // An edited `jumpHost` is a different machine: a pin remembered for the previous jump host
374
+ // must not make the new one fail as `host-key-changed` (review blocker 3).
375
+ const rememberedJump = runtime.jumpFingerprint
376
+ const rememberedJumpPort = (Number(rememberedJump?.port) || 22) === (jumpTarget.port ?? 22)
377
+ if (rememberedJump !== null && (!rememberedJumpPort || rememberedJump.host !== jumpTarget.host)) {
378
+ ctx.progress.log(
379
+ runtime,
380
+ 'info',
381
+ `the jump host changed (${rememberedJump.host ?? 'unknown'} -> ${jumpTarget.host}); forgetting its previous host key`,
382
+ )
383
+ runtime.jumpFingerprint = null
384
+ }
385
+ runtime.jumpSsh = ctx.deps.sshFactory(buildOptions(jumpTarget, 'jump'))
386
+ watchHandshakeTransport(runtime, runtime.jumpSsh)
160
387
  await runtime.jumpSsh.connect()
388
+ // The jump host's key is settled (its own context above); from here the fingerprint the host
389
+ // card describes is the target's, which `captureFingerprint` fills once it answers.
390
+ runtime.fingerprint = null
161
391
  ctx.progress.phase(runtime, 'ssh', 'ssh-connecting', { host: target.host, via: target.jumpHost.host })
162
392
  const stream = await runtime.jumpSsh.forwardOut(target.host, target.port ?? 22)
163
- runtime.ssh = ctx.deps.sshFactory(buildOptions(target, stream))
393
+ runtime.ssh = ctx.deps.sshFactory(buildOptions(target, 'target', stream))
394
+ watchHandshakeTransport(runtime, runtime.ssh)
164
395
  captureFingerprint(ctx, runtime, await runtime.ssh.connect())
165
396
  }
166
397
 
@@ -187,9 +418,12 @@ function captureFingerprint(ctx, runtime, info) {
187
418
  /**
188
419
  * Warn when the remote already runs a DSH this plugin did not start, and let the
189
420
  * user decide: stop it, keep it alongside, or cancel.
421
+ * @returns {Promise<'stop' | 'alongside' | null>} the decision, or null when no prompt was needed.
190
422
  */
191
- async function resolveForeignConflict(ctx, runtime, layout, profile) {
192
- const ignorePids = []
423
+ async function resolveForeignConflict(ctx, runtime, layout, profile, options = {}) {
424
+ // Processes the user already chose to keep alongside this connection are not asked
425
+ // about again (a local restart must not turn that choice into a prompt every time).
426
+ const ignorePids = (Array.isArray(options.ignoredPids) ? options.ignoredPids : []).filter((pid) => isPid(pid))
193
427
  try {
194
428
  const registry = await ctx.deps.readRegistry(runtime.ssh, layout)
195
429
  const pid = Number(registry?.pid)
@@ -199,28 +433,56 @@ async function resolveForeignConflict(ctx, runtime, layout, profile) {
199
433
  ctx.progress.log(runtime, 'debug', 'foreign DSH: registry read failed:', messageOf(error))
200
434
  }
201
435
  const found = await ctx.deps.findForeign(runtime.ssh, { ignorePids })
436
+ const processes = found.ok === true && Array.isArray(found.processes) ? [...found.processes] : []
437
+ // The registry-named instance is normally ignored by the scan (it is this connection's own
438
+ // process). When the caller cannot stop it - a pid a re-attach discovered - it still must be
439
+ // put in front of the user: a second instance must never start silently next to it. Merge it
440
+ // before failing open on a scan error: its identity came from /proc, not from the scan.
441
+ const known = options.knownProcess
442
+ const knownPid = Number(known?.pid)
443
+ // A pid the user already chose to keep alongside is never asked about again; the
444
+ // registry-named pid, however, must be shown when it could not be stopped.
445
+ const keptAlongside = (Array.isArray(options.ignoredPids) ? options.ignoredPids : []).map(Number)
446
+ if (
447
+ isPid(knownPid) &&
448
+ !keptAlongside.includes(knownPid) &&
449
+ !processes.some((entry) => Number(entry?.pid) === knownPid)
450
+ ) {
451
+ processes.push({
452
+ pid: knownPid,
453
+ command: typeof known.command === 'string' && known.command !== '' ? known.command : `dsh --profile ${profile}`,
454
+ })
455
+ }
202
456
  if (found.ok !== true) {
203
457
  ctx.progress.log(runtime, 'debug', 'foreign DSH: scan failed:', found.reason ?? found.technical ?? 'unknown')
204
- return
458
+ // A broken scan must never allow a silent second instance: with a known live process we
459
+ // still ask; with nothing known there is nothing to conflict with (the old behavior).
460
+ if (processes.length === 0) return null
205
461
  }
206
- if (found.processes.length === 0) return
207
- const pidList = found.processes.map((entry) => `pid ${entry.pid}`).join(', ')
462
+ if (processes.length === 0) return null
463
+ const pidList = processes.map((entry) => `pid ${entry.pid}`).join(', ')
208
464
  ctx.progress.log(
209
465
  runtime,
210
466
  'warn',
211
- `foreign DSH on the remote: ${found.processes.length} process(es) sharing this ~/.dsh (${pidList})`,
467
+ `foreign DSH on the remote: ${processes.length} process(es) sharing this ~/.dsh (${pidList})`,
212
468
  )
213
469
 
214
- const decision = await askConflict(ctx, runtime, found.processes)
215
- if (decision.action === 'cancel') throw errors.remoteDshRunning()
470
+ const decision = await askConflict(ctx, runtime, processes)
471
+ if (decision.action === 'cancel') {
472
+ // The user said no: retrying would ask the same question again.
473
+ runtime.connectCancelled = true
474
+ throw errors.remoteDshRunning()
475
+ }
216
476
  if (decision.action === 'alongside') {
477
+ runtime.alongsidePids = processes.map((entry) => entry.pid).filter((pid) => isPid(pid))
217
478
  runtime.warning = {
218
479
  zh: '远端已有手工启动的 DSH;已按你的选择并存运行,两者共享 ~/.dsh,请避免同时操作同一会话。',
219
480
  en: 'A manually started DSH is already running; it was kept as you chose. Both share ~/.dsh, so avoid editing the same session in both.',
220
481
  }
221
- return
482
+ runtime.warningSource = 'alongside'
483
+ return 'alongside'
222
484
  }
223
- const stopped = await ctx.deps.stopForeign(runtime.ssh, found.processes)
485
+ const stopped = await ctx.deps.stopForeign(runtime.ssh, processes)
224
486
  if (stopped.ok !== true) {
225
487
  throw errors.remoteDshRunning(
226
488
  {
@@ -232,18 +494,365 @@ async function resolveForeignConflict(ctx, runtime, layout, profile) {
232
494
  },
233
495
  )
234
496
  }
235
- ctx.progress.log(runtime, 'info', `stopped ${found.processes.length} manual remote DSH process(es)`)
497
+ runtime.alongsidePids = []
498
+ ctx.progress.log(runtime, 'info', `stopped ${processes.length} manual remote DSH process(es)`)
499
+ return 'stop'
500
+ }
501
+
502
+ /** Open the loopback tunnel for one remote port; tunnel-level failures feed the liveness confirmation. */
503
+ async function openTunnelFor(ctx, runtime, remotePort) {
504
+ // Never hand the tunnel factory a missing transport: a listener created with no SSH channel
505
+ // would crash the host process on the first connection (see tunnel.js's own guard).
506
+ assertTransportOpen(runtime)
507
+ if (!isPid(remotePort) || remotePort > 65535) {
508
+ throw errors.internal(new Error(`invalid remote port for the tunnel: ${remotePort}`))
509
+ }
510
+ const onError = () => ctx.noteRemoteUnreachable?.(runtime, 'tunnel')
511
+ const tunnel = await ctx.deps.tunnelFactory({ ssh: runtime.ssh, remotePort, onError })
512
+ const localPort = Number(tunnel?.localPort)
513
+ if (!Number.isInteger(localPort) || !isPid(localPort) || localPort > 65535) {
514
+ try {
515
+ await tunnel?.close?.()
516
+ } catch {}
517
+ throw errors.internal(new Error(`the tunnel factory returned no usable local port (${tunnel?.localPort})`))
518
+ }
519
+ // The listener was created while the caller awaited the factory: a disconnect or a host
520
+ // removal in that window must close it instead of publishing it (H4).
521
+ try {
522
+ assertStillWanted(ctx, runtime)
523
+ assertTransportOpen(runtime)
524
+ } catch (error) {
525
+ try {
526
+ await tunnel.close()
527
+ } catch {}
528
+ throw error
529
+ }
530
+ runtime.tunnel = tunnel
531
+ runtime.remote.localPort = localPort
532
+ ctx.progress.log(runtime, 'info', `tunnel open: 127.0.0.1:${localPort} -> 127.0.0.1:${remotePort}`)
533
+ return tunnel
534
+ }
535
+
536
+ /**
537
+ * Record a pid this connection is allowed to stop later: it must have been launched by the
538
+ * plugin's own start script (or adopted from a `launch` registry record) and its `/proc`
539
+ * identity must show this DSH home and profile. Anything that fails this check is still
540
+ * hosted and displayed, but never signalled.
541
+ */
542
+ async function rememberLaunched(ctx, runtime, pid, layout, profile) {
543
+ if (!isPid(pid)) return null
544
+ if (!(runtime.launched instanceof Map)) runtime.launched = new Map()
545
+ const identity = await ctx.deps.processIdentity(runtime.ssh, pid)
546
+ if (identity.ok !== true) {
547
+ ctx.progress.log(
548
+ runtime,
549
+ 'debug',
550
+ `launch: pid ${pid} identity unreadable (${identity.reason}); it will not be stopped`,
551
+ )
552
+ return null
553
+ }
554
+ if (identity.dshHome !== '' && identity.dshHome !== layout.dshHome) {
555
+ ctx.progress.log(runtime, 'debug', `launch: pid ${pid} runs with another DSH_HOME; it will not be stopped`)
556
+ return null
557
+ }
558
+ if (!commandMatchesProfile(identity.command, profile)) {
559
+ ctx.progress.log(runtime, 'debug', `launch: pid ${pid} does not run profile ${profile}; it will not be stopped`)
560
+ return null
561
+ }
562
+ const record = {
563
+ startTime: identity.startTime,
564
+ command: identity.command,
565
+ dshHome: identity.dshHome,
566
+ }
567
+ runtime.launched.set(pid, record)
568
+ runtime.bound = { pid, startTime: identity.startTime, origin: 'launch' }
569
+ return record
570
+ }
571
+
572
+ /**
573
+ * Remember the remote web this connection is bound to without granting restart kill rights.
574
+ * A re-attach (or the adoption of a re-attached record) names a process this plugin did not
575
+ * launch: a restart must leave it running, but the user's explicit "Stop remote DSH" may stop
576
+ * exactly this pid. The identity recorded here is what that action re-proves before signalling.
577
+ * @param {object} ctx - service context.
578
+ * @param {object} runtime - host runtime with a live transport.
579
+ * @param {number} pid - the bound remote web pid.
580
+ * @param {object} layout - remote layout.
581
+ * @param {string} profile - remote DSH profile.
582
+ * @param {'launch'|'reattach'} origin - how this connection came to host the process.
583
+ * @returns {Promise<object|null>} the recorded binding, or null when it cannot be proven.
584
+ */
585
+ async function rememberBound(ctx, runtime, pid, layout, profile, origin) {
586
+ if (!isPid(pid)) return null
587
+ const identity = await ctx.deps.processIdentity(runtime.ssh, pid)
588
+ if (identity.ok !== true) {
589
+ ctx.progress.log(
590
+ runtime,
591
+ 'debug',
592
+ `bind: pid ${pid} identity unreadable (${identity.reason}); it will not be stopped on request`,
593
+ )
594
+ return null
595
+ }
596
+ if (identity.dshHome !== '' && identity.dshHome !== layout.dshHome) {
597
+ ctx.progress.log(runtime, 'debug', `bind: pid ${pid} runs with another DSH_HOME; it cannot be stopped here`)
598
+ return null
599
+ }
600
+ if (!commandMatchesProfile(identity.command, profile)) {
601
+ ctx.progress.log(runtime, 'debug', `bind: pid ${pid} does not run profile ${profile}; it cannot be stopped here`)
602
+ return null
603
+ }
604
+ runtime.bound = { pid, startTime: identity.startTime, origin }
605
+ return runtime.bound
606
+ }
607
+
608
+ /**
609
+ * The only gate that authorizes a kill. All three must hold: the registry names the pid,
610
+ * this connection launched it, and `/proc` still proves the same process (kernel start time)
611
+ * with the same home and profile. A reused pid, an adopted-only pid, or a process kept
612
+ * alongside therefore never gets stopped silently.
613
+ */
614
+ async function killAuthorized(ctx, runtime, pid, layout, profile) {
615
+ const record = runtime.launched instanceof Map ? runtime.launched.get(pid) : undefined
616
+ if (!record) return { ok: false, reason: 'not-launched-by-this-connection' }
617
+ if ((Array.isArray(runtime.alongsidePids) ? runtime.alongsidePids : []).includes(pid)) {
618
+ return { ok: false, reason: 'kept-alongside' }
619
+ }
620
+ const identity = await ctx.deps.processIdentity(runtime.ssh, pid)
621
+ if (identity.ok !== true) return { ok: false, reason: `identity-${identity.reason}` }
622
+ if (identity.startTime !== record.startTime) return { ok: false, reason: 'pid-reused' }
623
+ if (identity.dshHome !== '' && identity.dshHome !== layout.dshHome) {
624
+ return { ok: false, reason: 'dsh-home-mismatch' }
625
+ }
626
+ if (!commandMatchesProfile(identity.command, profile)) return { ok: false, reason: 'profile-mismatch' }
627
+ return { ok: true }
628
+ }
629
+
630
+ /**
631
+ * Rebuild the local listener for a host whose remote UI answers the SSH probe but whose
632
+ * proxied requests fail: the tunnel, not the remote, is what broke. Single-flight per host and
633
+ * owned by a link-work token, like restart/reattach: a disconnect, host removal or shutdown
634
+ * cancels it and the caller waits for `runtime.tunnelRepair` before tearing down.
635
+ *
636
+ * The replacement is created before the old listener closes, so there is no window without a
637
+ * listener. Its local port is a new random one, so `viewRev` is bumped: the carrier refetches
638
+ * `GET /hosts/:id/open` and navigates again (the desktop guest's URL is the loopback origin).
639
+ * Existing WebSockets/downloads are dropped by closing the old listener - documented.
640
+ *
641
+ * @param {object} ctx - service context.
642
+ * @param {object} runtime - connected host runtime.
643
+ * @returns {Promise<{ ok: boolean, reason?: string }>} whether the listener was rebuilt.
644
+ */
645
+ export async function repairTunnel(ctx, runtime) {
646
+ if (
647
+ ctx.state.disposed === true ||
648
+ runtime.desired !== 'connected' ||
649
+ runtime.status !== 'connected' ||
650
+ runtime.linkBusy !== null ||
651
+ runtime.tunnel === null
652
+ ) {
653
+ return { ok: false, reason: 'not-watchable' }
654
+ }
655
+ if (runtime.ssh?.connected !== true) return { ok: false, reason: 'no-transport' }
656
+ if (runtime.tunnelRepair) return runtime.tunnelRepair
657
+ if (Date.now() < (Number(runtime.nextTunnelRepairAt) || 0)) {
658
+ return { ok: false, reason: 'backoff' }
659
+ }
660
+ const port = runtime.remote.port
661
+ const previous = runtime.tunnel
662
+ const token = beginLinkWork(runtime, 'repair')
663
+ const stillCurrent = () =>
664
+ isLinkWorkCurrent(runtime, token) &&
665
+ ctx.state.disposed !== true &&
666
+ runtime.desired === 'connected' &&
667
+ runtime.status === 'connected' &&
668
+ runtime.ssh?.connected === true
669
+ let created = null
670
+ let work = null
671
+ let settled = null
672
+ work = (async () => {
673
+ try {
674
+ if (runtime.ssh?.connected !== true) throw errors.internal(new Error('the SSH transport is gone'))
675
+ if (!isPid(port) || port > 65535) throw errors.internal(new Error(`invalid remote port for the tunnel: ${port}`))
676
+ const next = await ctx.deps.tunnelFactory({
677
+ ssh: runtime.ssh,
678
+ remotePort: port,
679
+ onError: () => ctx.noteRemoteUnreachable?.(runtime, 'tunnel'),
680
+ })
681
+ created = next
682
+ const nextPort = Number(next?.localPort)
683
+ if (!Number.isInteger(nextPort) || !isPid(nextPort) || nextPort > 65535) {
684
+ throw errors.internal(new Error(`the rebuilt tunnel has no usable local port (${next?.localPort})`))
685
+ }
686
+ if (!stillCurrent()) return { ok: false, reason: 'cancelled' }
687
+ // Publish the replacement before closing the old listener: no no-listener window.
688
+ runtime.tunnel = next
689
+ runtime.remote.localPort = nextPort
690
+ try {
691
+ await previous.close()
692
+ } catch {
693
+ // swallow-ok: the old listener could already be gone; the new one is what matters
694
+ }
695
+ if (!stillCurrent()) return { ok: false, reason: 'cancelled' }
696
+ // The local port changed, so the carrier's view of the host did too.
697
+ runtime.remote.viewRev = (Number(runtime.remote.viewRev) || 0) + 1
698
+ ctx.progress.log(
699
+ runtime,
700
+ 'info',
701
+ `tunnel rebuilt after a failed request (remote port ${port}, local port ${previous.localPort} -> ${nextPort})`,
702
+ )
703
+ runtime.tunnelRepairFailures = 0
704
+ runtime.nextTunnelRepairAt = 0
705
+ ctx.emitState()
706
+ return { ok: true }
707
+ } catch (error) {
708
+ // swallow-ok: a failed rebuild is a typed, retryable reason (with backoff) for the caller;
709
+ // the old listener is still serving, so this is not a connection failure.
710
+ runtime.tunnelRepairFailures = (Number(runtime.tunnelRepairFailures) || 0) + 1
711
+ const backoff = Math.min(
712
+ REMOTE_REPAIR_BACKOFF_MAX_MS,
713
+ REMOTE_REPAIR_BACKOFF_MS * 2 ** (runtime.tunnelRepairFailures - 1),
714
+ )
715
+ runtime.nextTunnelRepairAt = Date.now() + backoff
716
+ ctx.progress.log(runtime, 'warn', 'tunnel rebuild failed:', messageOf(error))
717
+ return { ok: false, reason: 'rebuild-failed' }
718
+ } finally {
719
+ // A listener this rebuild created must never outlive it: on a cancelled token (or if it
720
+ // was never published) close it here, and clear the view only when it owned the slot.
721
+ if (created !== null && (!isLinkWorkCurrent(runtime, token) || runtime.tunnel !== created)) {
722
+ if (runtime.tunnel === created) {
723
+ runtime.tunnel = null
724
+ runtime.remote.localPort = null
725
+ }
726
+ try {
727
+ await created.close()
728
+ } catch {}
729
+ }
730
+ endLinkWork(runtime, token)
731
+ }
732
+ })()
733
+ settled = work.finally(() => {
734
+ if (runtime.tunnelRepair === settled) runtime.tunnelRepair = null
735
+ })
736
+ runtime.tunnelRepair = settled
737
+ return settled
738
+ }
739
+
740
+ /** Prove the remote UI answers through the new tunnel and exchange this launch's token. */
741
+ async function verifyRemoteUi(ctx, runtime, port, token, localPort) {
742
+ const tunnelPort = Number(localPort)
743
+ if (!Number.isInteger(tunnelPort) || !isPid(tunnelPort) || tunnelPort > 65535) {
744
+ throw errors.internal(new Error(`the tunnel has no local port to verify (${localPort ?? 'none'})`))
745
+ }
746
+ ctx.progress.log(runtime, 'debug', `verifying the remote UI on 127.0.0.1:${tunnelPort}`)
747
+ const ui = await ctx.deps.waitUi(runtime.ssh, port, { attempts: 20, intervalMs: 500 })
748
+ // The probe retries for up to ten seconds: the user may have cancelled in that window, and
749
+ // the token exchange must not touch the (possibly closed) tunnel after it (H4).
750
+ assertStillWanted(ctx, runtime)
751
+ assertTransportOpen(runtime)
752
+ if (!ui.ok) {
753
+ throw errors.remoteUiUnreachable({
754
+ zh: `远端 DSH 的本地 127.0.0.1:${port} 没有响应(HTTP ${ui.status ?? '无'})。`,
755
+ en: `The remote DSH on 127.0.0.1:${port} did not respond (HTTP ${ui.status ?? 'none'}).`,
756
+ })
757
+ }
758
+ ctx.progress.log(runtime, 'debug', `remote UI answered HTTP ${ui.status}; exchanging the launch token`)
759
+ const exchange = await ctx.deps.exchange(tunnelPort, token, {
760
+ timeoutMs: TUNNEL_PROBE_TIMEOUT_MS,
761
+ })
762
+ runtime.exchange = exchange
763
+ if (!exchange.ok) {
764
+ throw errors.remoteUiUnreachable({
765
+ zh: `本地隧道完成了 token 交换,但远端界面返回 HTTP ${exchange.status}(首次状态 ${exchange.firstStatus})。`,
766
+ en: `The tunnel exchanged the token but the remote UI answered HTTP ${exchange.status} (first ${exchange.firstStatus}).`,
767
+ })
768
+ }
769
+ return exchange
770
+ }
771
+
772
+ /** Publish the connected state and start watching the remote for its own restarts. */
773
+ function markConnected(ctx, runtime) {
774
+ // A live link is not idle: no idle-stop timer may survive the attach (review blocker 1).
775
+ cancelIdleStop(runtime)
776
+ // Only a success resets the retry budget: a failed attempt must spend it (H2).
777
+ runtime.reconnectAttempts = 0
778
+ runtime.connectCancelled = false
779
+ runtime.status = 'connected'
780
+ runtime.phase = 'ready'
781
+ runtime.progress = { code: 'ready' }
782
+ runtime.error = null
783
+ runtime.remote.uiReady = true
784
+ // Every attach invalidates the previous launch URL / cookie: the Client re-navigates its carrier.
785
+ runtime.remote.viewRev = (Number(runtime.remote.viewRev) || 0) + 1
786
+ // A fresh attach is a new listener budget: an old rebuild failure must not keep it in backoff.
787
+ runtime.tunnelRepairFailures = 0
788
+ runtime.nextTunnelRepairAt = 0
789
+ // A successful attach makes a previous "stop not confirmed" warning stale. An alongside
790
+ // warning keeps describing a process that is still running, so it is not cleared here.
791
+ if (runtime.warningSource === 'restart-stop') {
792
+ runtime.warning = null
793
+ runtime.warningSource = null
794
+ }
795
+ startRemoteHeartbeat(ctx, runtime)
796
+ ctx.emitState()
797
+ }
798
+
799
+ /** Bounded diagnostics trail of restarts and re-attached ports (never sent to the client). */
800
+ function recordRestart(runtime, entry) {
801
+ const history = Array.isArray(runtime.restarts) ? runtime.restarts : []
802
+ history.push({ at: nowIso(), ...entry })
803
+ runtime.restarts = history.slice(-10)
804
+ }
805
+
806
+ /**
807
+ * Persist (or forget) the SSH password now that the transport accepted it. Doing this right
808
+ * after the handshake rather than after `connected` keeps a credential the server already
809
+ * proved even when a later bootstrap step fails, so the next attempt does not ask again.
810
+ * @param {object} ctx - service context.
811
+ * @param {object} runtime - host runtime.
812
+ * @param {(level: string, ...args: unknown[]) => void} log - connect log writer.
813
+ */
814
+ async function settlePasswordStorage(ctx, runtime, log) {
815
+ const save = runtime.savePassword === true
816
+ const forget = runtime.forgetPassword === true
817
+ runtime.savePassword = false
818
+ runtime.forgetPassword = false
819
+ if (!ctx.secrets || typeof runtime.password !== 'string' || runtime.password === '') return
820
+ if (save) {
821
+ runtime.passwordSaved = await ctx.secrets.set(runtime.id, runtime.password)
822
+ if (runtime.passwordSaved) log('debug', 'saved the SSH password in the credential store')
823
+ else log('warn', 'could not save the SSH password in the credential store')
824
+ return
825
+ }
826
+ if (forget) {
827
+ const removed = await ctx.secrets.remove(runtime.id)
828
+ runtime.passwordSaved = !removed
829
+ }
236
830
  }
237
831
 
238
832
  async function connectPipeline(ctx, runtime) {
239
833
  const log = (level, ...args) => ctx.progress.log(runtime, level, ...args)
240
834
  const phase = (name, code, params) => ctx.progress.phase(runtime, name, code, params)
241
835
  runtime.closing = false
242
- runtime.reconnectAttempts = 0
836
+ // NOTE: `reconnectAttempts` is deliberately NOT reset here. A retry re-enters this function
837
+ // and must keep spending the budget `scheduleReconnect` counts; only a user-initiated
838
+ // connect (startConnect) and a successful attach reset it (H2).
839
+ runtime.transportLost = false
840
+ runtime.alongsidePids = []
841
+ // Kill rights belong to this connection: a fresh connect starts with no launched pids.
842
+ runtime.launched = new Map()
843
+ runtime.bound = null
844
+ runtime.tunnelRepairFailures = 0
845
+ runtime.nextTunnelRepairAt = 0
846
+ stopRemoteHeartbeat(runtime)
243
847
  ctx.progress.set(runtime, { status: 'connecting', error: null, warning: null })
244
848
  let remoteStarted = false
849
+ let layout = null
850
+ // Whether the SSH transport ever came up during this attempt: a link that was up and then
851
+ // dropped is a connection event and is retried like one (H3).
852
+ let transportUp = false
245
853
  try {
246
854
  const target = await resolveTargetForRuntime(ctx, runtime)
855
+ assertStillWanted(ctx, runtime)
247
856
  const viaJump = target.jumpHost ? ` via ${target.jumpHost.host}` : ''
248
857
  log('debug', `target resolved: ${target.username ?? '(default)'}@${target.host}:${target.port}${viaJump}`)
249
858
  // A password-auth host may have one remembered: load it before the transport
@@ -254,18 +863,38 @@ async function connectPipeline(ctx, runtime) {
254
863
  runtime.password = remembered
255
864
  runtime.passwordSaved = true
256
865
  }
866
+ assertStillWanted(ctx, runtime)
257
867
  }
258
868
  phase('ssh', 'ssh-connecting', { host: runtime.entry.name })
869
+ // An idle host keeps its SSH session for a fast resume; this attempt replaces it, so the
870
+ // old one is released here instead of being overwritten (and leaked) by openTransport.
871
+ if (runtime.ssh !== null || runtime.jumpSsh !== null) {
872
+ log('debug', 'releasing the transport kept by the idle policy before dialling again')
873
+ await disposeSsh(runtime)
874
+ assertStillWanted(ctx, runtime)
875
+ }
259
876
  await openTransport(ctx, runtime, target)
877
+ // The transport is the link from here on: a drop during probe/bootstrap is a lost
878
+ // connection too, so the close handler is attached before the remaining steps (H3).
879
+ attachDisconnectHandler(ctx, runtime)
880
+ assertStillWanted(ctx, runtime)
881
+ assertTransportOpen(runtime)
882
+ transportUp = true
260
883
  log(
261
884
  'info',
262
885
  `SSH connected to ${target.host}:${target.port} as ${target.username ?? '(default)'} (fingerprint ${
263
886
  runtime.fingerprint?.sha256 ?? 'unknown'
264
887
  })`,
265
888
  )
889
+ // SSH accepted the credential: this is the point the password is proven, before any
890
+ // bootstrap step can fail and force the user to type it again.
891
+ await settlePasswordStorage(ctx, runtime, log)
892
+ assertStillWanted(ctx, runtime)
266
893
 
267
894
  phase('probe', 'probing')
268
895
  let facts = await ctx.deps.probe(runtime.ssh)
896
+ assertStillWanted(ctx, runtime)
897
+ assertTransportOpen(runtime)
269
898
  const freeGb = Math.round(Number(facts.diskFreeKb ?? 0) / 1_048_576)
270
899
  log(
271
900
  'debug',
@@ -279,7 +908,9 @@ async function connectPipeline(ctx, runtime) {
279
908
  // There is no system fallback on purpose, so this failure is the connection's.
280
909
  const profile = ctx.settings().bootstrap.profile
281
910
  const managedVersion = managedNodeVersionFromEngine(ctx.engineNodeRange())
282
- const nodeLayout = remoteLayout(facts.home)
911
+ // A probe that did not report $HOME cannot address the remote layout: `remoteLayout`
912
+ // throws instead of building a literal-tilde path (H1).
913
+ const nodeLayout = layoutForRuntime({ facts })
283
914
  log('info', `managed Node: expecting v${managedVersion} in ${nodeLayout.nodeDir}`)
284
915
  const managed = await ctx.deps.ensureNode(runtime.ssh, {
285
916
  facts,
@@ -287,6 +918,8 @@ async function connectPipeline(ctx, runtime) {
287
918
  version: managedVersion,
288
919
  onProgress: (event) => ctx.progress.nodeProgress(runtime, event),
289
920
  })
921
+ assertStillWanted(ctx, runtime)
922
+ assertTransportOpen(runtime)
290
923
  facts = applyManagedNodeFacts(facts, managed)
291
924
  log(
292
925
  'info',
@@ -304,7 +937,7 @@ async function connectPipeline(ctx, runtime) {
304
937
  log('info', `runtime plan ${plan.level}: ${plan.reason.en}`)
305
938
 
306
939
  phase('start', 'starting-remote', { level: plan.level })
307
- const layout = remoteLayout(runtime.facts?.home ?? null)
940
+ layout = layoutForRuntime(runtime)
308
941
  let webInfo = null
309
942
  // Adopt an instance left running by a previous local process (keep-alive).
310
943
  // Checked before the npx preflight: an adoptable instance should not require
@@ -315,7 +948,12 @@ async function connectPipeline(ctx, runtime) {
315
948
  if (adopted && (!adoptedVersion || versionsEqual(adoptedVersion, targetVersion))) {
316
949
  webInfo = { ...adopted, logPath: layout.logFile, startedAt: nowIso(), rawLine: '' }
317
950
  log('info', `adopted running remote web pid=${adopted.pid} port=${adopted.port}`)
318
- } else if (adopted) {
951
+ // Only a record written by a launch script proves the process is ours to stop; a
952
+ // re-attached record is hosted, not owned (B1). It is still the instance this
953
+ // connection is bound to, so the explicit "Stop remote DSH" may stop it by identity.
954
+ if (adopted.origin !== 'reattach') await rememberLaunched(ctx, runtime, adopted.pid, layout, profile)
955
+ else await rememberBound(ctx, runtime, adopted.pid, layout, profile, 'reattach')
956
+ } else if (adopted && adopted.origin !== 'reattach') {
319
957
  log(
320
958
  'info',
321
959
  `running remote web version ${adoptedVersion} != ${targetVersion}; stopping it and starting a matching instance`,
@@ -327,19 +965,30 @@ async function connectPipeline(ctx, runtime) {
327
965
  } catch (error) {
328
966
  log('warn', 'could not stop the stale remote web:', messageOf(error))
329
967
  }
968
+ } else if (adopted) {
969
+ log(
970
+ 'warn',
971
+ `running remote web version ${adoptedVersion} != ${targetVersion}, but it was only re-attached; leaving it running`,
972
+ )
330
973
  } else {
331
974
  log('debug', 'adopt: no running remote web to reuse')
332
975
  }
333
976
  } catch (error) {
334
977
  log('debug', 'adopt check failed:', messageOf(error))
335
978
  }
979
+ assertStillWanted(ctx, runtime)
980
+ assertTransportOpen(runtime)
336
981
  if (!webInfo) {
337
982
  // The registry row we refused to adopt (stale launch marker, unresponsive
338
983
  // HTTP, ...) still names a process on this ~/.dsh profile. Starting a second
339
- // one would let two clients write the same session files.
984
+ // one would let two clients write the same session files. A record written by a
985
+ // re-attach names a process this plugin did not launch, so it is never stopped here.
340
986
  const leftover = await ctx.deps.readRegistry(runtime.ssh, layout)
987
+ assertStillWanted(ctx, runtime)
341
988
  const leftoverPid = Number(leftover?.pid ?? 0)
342
- if (leftover?.dshHome === layout.dshHome && leftover?.profile === profile && isPid(leftoverPid)) {
989
+ if (leftover?.origin === 'reattach') {
990
+ log('info', `leaving a re-attached remote web instance alone (pid ${leftoverPid || 'unknown'})`)
991
+ } else if (leftover?.dshHome === layout.dshHome && leftover?.profile === profile && isPid(leftoverPid)) {
343
992
  try {
344
993
  await ctx.deps.stopWeb(runtime.ssh, layout, { pid: leftoverPid })
345
994
  log('info', `stopped a non-adoptable remote web instance pid=${leftoverPid}`)
@@ -348,6 +997,8 @@ async function connectPipeline(ctx, runtime) {
348
997
  }
349
998
  }
350
999
  await resolveForeignConflict(ctx, runtime, layout, profile)
1000
+ assertStillWanted(ctx, runtime)
1001
+ assertTransportOpen(runtime)
351
1002
  phase('bootstrap', 'bootstrapping', { level: plan.level })
352
1003
  // Resolve the exact package in the foreground first: a cold npx download
353
1004
  // belongs in the connect error, not in a detached process that only leaves a
@@ -356,6 +1007,8 @@ async function connectPipeline(ctx, runtime) {
356
1007
  const onStdout = ctx.progress.bootstrapReporter(runtime, plan.start.targetVersion)
357
1008
  const onStderr = ctx.progress.bootstrapReporter(runtime, plan.start.targetVersion)
358
1009
  await ctx.deps.preflight(runtime.ssh, plan, { onStdout, onStderr })
1010
+ assertStillWanted(ctx, runtime)
1011
+ assertTransportOpen(runtime)
359
1012
  log('info', `npx preflight ready: @deepseek-ai/dsh@${plan.start.targetVersion}`)
360
1013
  phase('start', 'starting-remote', { level: plan.level })
361
1014
  webInfo = await ctx.deps.startWeb(runtime.ssh, {
@@ -367,6 +1020,8 @@ async function connectPipeline(ctx, runtime) {
367
1020
  })
368
1021
  log('info', `remote DSH started: pid ${webInfo.pid ?? '?'}, port ${webInfo.port}`)
369
1022
  }
1023
+ assertStillWanted(ctx, runtime)
1024
+ assertTransportOpen(runtime)
370
1025
  if (webInfo.browserCarrier === 'patched') {
371
1026
  log(
372
1027
  'info',
@@ -374,6 +1029,10 @@ async function connectPipeline(ctx, runtime) {
374
1029
  )
375
1030
  }
376
1031
  remoteStarted = true
1032
+ // Only the instance launched by this connection's start script may be stopped later;
1033
+ // an adopted one was already recorded above only when its record proves a launch.
1034
+ if (webInfo.adopted !== true) await rememberLaunched(ctx, runtime, webInfo.pid, layout, profile)
1035
+ assertStillWanted(ctx, runtime)
377
1036
  runtime.token = webInfo.token
378
1037
  runtime.remote = {
379
1038
  version: targetVersion,
@@ -387,68 +1046,63 @@ async function connectPipeline(ctx, runtime) {
387
1046
  nodeVersion: facts.nodeVersion,
388
1047
  nodeSource: 'managed',
389
1048
  startedAt: webInfo.startedAt ?? nowIso(),
1049
+ viewRev: Number(runtime.remote.viewRev) || 0,
390
1050
  }
391
1051
 
392
1052
  phase('tunnel', 'tunneling')
393
- runtime.tunnel = await ctx.deps.tunnelFactory({ ssh: runtime.ssh, remotePort: webInfo.port })
394
- runtime.remote.localPort = runtime.tunnel.localPort
395
- log('info', `tunnel open: 127.0.0.1:${runtime.tunnel.localPort} -> 127.0.0.1:${webInfo.port}`)
1053
+ const tunnel = await openTunnelFor(ctx, runtime, webInfo.port)
1054
+ assertStillWanted(ctx, runtime)
396
1055
 
397
1056
  phase('verifying', 'verifying')
398
- log('debug', `verifying the remote UI on 127.0.0.1:${webInfo.port}`)
399
- const ui = await ctx.deps.waitUi(runtime.ssh, webInfo.port, { attempts: 20, intervalMs: 500 })
400
- if (!ui.ok) {
401
- throw errors.remoteUiUnreachable({
402
- zh: `远端 DSH 的本地 127.0.0.1:${webInfo.port} 没有响应(HTTP ${ui.status ?? '无'})。`,
403
- en: `The remote DSH on 127.0.0.1:${webInfo.port} did not respond (HTTP ${ui.status ?? 'none'}).`,
404
- })
405
- }
406
- log('debug', `remote UI answered HTTP ${ui.status}; exchanging the launch token`)
407
- const exchange = await ctx.deps.exchange(runtime.tunnel.localPort, webInfo.token, {
408
- timeoutMs: TUNNEL_PROBE_TIMEOUT_MS,
409
- })
410
- runtime.exchange = exchange
411
- if (!exchange.ok) {
412
- throw errors.remoteUiUnreachable({
413
- zh: `本地隧道完成了 token 交换,但远端界面返回 HTTP ${exchange.status}(首次状态 ${exchange.firstStatus})。`,
414
- en: `The tunnel exchanged the token but the remote UI answered HTTP ${exchange.status} (first ${exchange.firstStatus}).`,
415
- })
416
- }
417
- // X-Frame-Options / CSP no longer matter: the remote UI is rendered by the
418
- // desktop guest, not embedded in a frame, so a page that refuses framing is
419
- // still a perfectly usable remote host.
1057
+ await verifyRemoteUi(ctx, runtime, webInfo.port, webInfo.token, tunnel.localPort)
1058
+ assertStillWanted(ctx, runtime)
1059
+ assertTransportOpen(runtime)
1060
+ // The remote UI is reachable both ways: the desktop half hands the loopback origin to a
1061
+ // Chromium guest, and the browser half frames it through the same-origin proxy (which strips
1062
+ // any X-Frame-Options). Either way this exchange proves the launch token works.
420
1063
  runtime.remote.uiReady = true
421
1064
  await ctx.store.patchHost(runtime.id, { lastOpenedAt: nowIso() })
1065
+ // The store write is an await: the user may have disconnected or deleted the host while
1066
+ // it was in flight, and a late write must not resurrect the link (H4).
1067
+ assertStillWanted(ctx, runtime)
1068
+ assertTransportOpen(runtime)
422
1069
  runtime.entry = ctx.store.getHost(runtime.id) ?? runtime.entry
423
- if (ctx.settings().saveTokens) await ctx.store.saveToken(runtime.id, webInfo.token)
424
- // Remember the password now that it is proven, if the user asked for that.
425
- if (runtime.savePassword === true && typeof runtime.password === 'string' && ctx.secrets) {
426
- runtime.passwordSaved = await ctx.secrets.set(runtime.id, runtime.password)
427
- }
428
- runtime.status = 'connected'
429
- runtime.phase = 'ready'
430
- runtime.progress = { code: 'ready' }
431
- runtime.error = null
1070
+ if (ctx.settings().saveTokens) {
1071
+ await ctx.store.saveToken(runtime.id, webInfo.token)
1072
+ assertStillWanted(ctx, runtime)
1073
+ }
1074
+ // Last gate before publishing: never report a connected host that the user just removed
1075
+ // or disconnected (H4), and never dereference a tunnel this pipeline no longer owns.
1076
+ assertStillWanted(ctx, runtime)
1077
+ assertTransportOpen(runtime)
432
1078
  ctx.state.activeHostId = runtime.id
433
- attachDisconnectHandler(ctx, runtime)
434
- ctx.emitState()
435
- log('info', `connected: remote ${runtime.remote.version} on 127.0.0.1:${runtime.tunnel.localPort}`)
1079
+ markConnected(ctx, runtime)
1080
+ const localPort = runtime.tunnel?.localPort ?? runtime.remote.localPort ?? '?'
1081
+ log('info', `connected: remote ${runtime.remote.version} on 127.0.0.1:${localPort}`)
436
1082
  } catch (error) {
437
- const view = toErrorView(error)
438
- if (runtime.desired !== 'connected') {
439
- // A user-initiated disconnect/teardown resolved a pending prompt (or closed
440
- // the window) while the pipeline was in flight: this is not a failure.
1083
+ // Phase is cleared with the status; capture it first so the log says where it stopped.
1084
+ const failedPhase = runtime.phase
1085
+ // The transport was up earlier in this attempt and is gone now: the link dropped, which
1086
+ // is what the retry policy exists for, even while the remote was still being set up (H3).
1087
+ const droppedTransport = runtime.transportLost === true || (transportUp === true && runtime.ssh?.connected !== true)
1088
+ const cancelled = error instanceof LinkCancelled || linkTaken(ctx, runtime)
1089
+ if (cancelled) {
1090
+ // A user-initiated disconnect/teardown (or a host removal) resolved a pending prompt or
1091
+ // cancelled the link while the pipeline was in flight: this is not a failure.
441
1092
  runtime.error = null
442
1093
  runtime.status = 'disconnected'
443
1094
  runtime.phase = null
444
1095
  runtime.progress = null
445
1096
  log('info', 'connect cancelled by disconnect')
446
1097
  } else {
1098
+ const view = normalizeConnectFailure(runtime, error)
447
1099
  runtime.error = view
448
1100
  runtime.status = 'error'
449
1101
  runtime.phase = null
450
1102
  runtime.progress = null
451
- log('warn', `connect failed: ${view.code}`, messageOf(error))
1103
+ // The log has to explain the failure on its own: every line the card shows, plus the
1104
+ // redacted technical detail (and the remote log tail for a failed remote start).
1105
+ ctx.progress.logFailure(runtime, view, { phase: failedPhase })
452
1106
  }
453
1107
  runtime.remote.uiReady = false
454
1108
  runtime.remote.localPort = null
@@ -456,8 +1110,791 @@ async function connectPipeline(ctx, runtime) {
456
1110
  stopRemote: remoteStarted && runtime.entry.keepAlive === 'stop',
457
1111
  keepRemote: remoteStarted && runtime.entry.keepAlive !== 'stop',
458
1112
  })
1113
+ // One place decides whether a failed attempt is retried, and the budget lives in
1114
+ // `scheduleReconnect` (H2). A user's "no" (host-key/conflict prompt) is final, and a
1115
+ // first manual connect that never reached the remote is reported instead of looping.
1116
+ if (!cancelled) {
1117
+ const retryable = runtime.error?.retryable !== false && runtime.connectCancelled !== true
1118
+ const repairAttempt = (Number(runtime.reconnectAttempts) || 0) > 0
1119
+ runtime.connectCancelled = false
1120
+ if (retryable && (repairAttempt || droppedTransport)) scheduleConnectRetry(ctx, runtime)
1121
+ }
459
1122
  ctx.emitState()
460
1123
  } finally {
461
1124
  runtime.connectPromise = null
462
1125
  }
463
1126
  }
1127
+
1128
+ /**
1129
+ * Arm the next automatic attempt after a failed connect/reconnect; `scheduleReconnect`
1130
+ * owns the settings gate and the attempt budget, so a spent budget is reported once.
1131
+ * @param {object} ctx - service context.
1132
+ * @param {object} runtime - host runtime.
1133
+ */
1134
+ function scheduleConnectRetry(ctx, runtime) {
1135
+ if (ctx.state.disposed === true || runtime.desired !== 'connected') return
1136
+ if (!runtime.entry.autoReconnect || !ctx.settings().autoReconnect.enabled) return
1137
+ scheduleReconnect(ctx, runtime, () => retryNow(ctx, runtime))
1138
+ }
1139
+
1140
+ async function readRegistryQuietly(ctx, runtime, layout) {
1141
+ try {
1142
+ return await ctx.deps.readRegistry(runtime.ssh, layout)
1143
+ } catch (error) {
1144
+ // swallow-ok: registry absence only means the restart cannot attribute the running pid
1145
+ ctx.progress.log(runtime, 'debug', 'restart: registry read failed:', messageOf(error))
1146
+ return null
1147
+ }
1148
+ }
1149
+
1150
+ /**
1151
+ * Recompute the launch plan from the probe facts the connection already recorded. A
1152
+ * restart reuses the same managed Node, profile and pinned version, so `[ssh]`,
1153
+ * `[probe]` and `[bootstrap]` are deliberately not run again.
1154
+ */
1155
+ function planForRuntime(ctx, runtime, profile) {
1156
+ const facts = runtime.facts
1157
+ const targetVersion = ctx.localVersion()
1158
+ if (!facts || !targetVersion) {
1159
+ throw errors.internal(new Error('the connected host has no recorded probe facts or local version'))
1160
+ }
1161
+ return { plan: ctx.deps.plan({ facts, targetVersion, profile }), targetVersion, facts }
1162
+ }
1163
+
1164
+ /** Put a host back into its connected state without pretending the launch URL changed. */
1165
+ function resumeConnected(ctx, runtime) {
1166
+ // A late action must never resurrect a link that was torn down or replaced while it waited:
1167
+ // the token is checked by callers, and these are the other three proofs that it still exists.
1168
+ if (runtime.desired !== 'connected' || runtime.ssh?.connected !== true || runtime.tunnel === null) return false
1169
+ runtime.status = 'connected'
1170
+ runtime.phase = 'ready'
1171
+ runtime.progress = { code: 'ready' }
1172
+ runtime.error = null
1173
+ runtime.remote.uiReady = true
1174
+ startRemoteHeartbeat(ctx, runtime)
1175
+ ctx.emitState()
1176
+ return true
1177
+ }
1178
+
1179
+ /**
1180
+ * Restart the managed remote web on the same SSH transport: stop the pid the run
1181
+ * registry names, `[start]` again on the same plan, rebuild the tunnel for the new
1182
+ * random port and verify. `[ssh]` / `[probe]` / `[bootstrap]` are not re-run, so a
1183
+ * password or host-key prompt can never appear here.
1184
+ *
1185
+ * Only the instance this connection launched is stopped; a process the plugin did
1186
+ * not start goes through the ordinary conflict prompt instead of being killed.
1187
+ *
1188
+ * Available while connected, and also from the `remote-unreachable` error state: that
1189
+ * state deliberately keeps the SSH transport so the user can restart exactly when a
1190
+ * remote re-attach found nothing to adopt (docs/design.md §5.6).
1191
+ *
1192
+ * @param {object} ctx - service context.
1193
+ * @param {object} runtime - host runtime with a live transport.
1194
+ * @returns {Promise<{ accepted: boolean, reason?: string }>} whether the restart started.
1195
+ */
1196
+ export async function restartHost(ctx, runtime) {
1197
+ await ctx.init()
1198
+ if (runtime.connectPromise || runtime.linkBusy !== null) return { accepted: false, reason: 'busy' }
1199
+ const connected = runtime.status === 'connected' && runtime.ssh?.connected === true && runtime.tunnel !== null
1200
+ const recoverable =
1201
+ runtime.status === 'error' &&
1202
+ runtime.error?.code === 'remote-unreachable' &&
1203
+ runtime.ssh?.connected === true &&
1204
+ runtime.facts !== null
1205
+ if (!connected && !recoverable) {
1206
+ throw errors.restartUnavailable()
1207
+ }
1208
+ const token = beginLinkWork(runtime, 'restart')
1209
+ const work = runRestart(ctx, runtime, token)
1210
+ runtime.restartPromise = work
1211
+ void work.finally(() => {
1212
+ endLinkWork(runtime, token)
1213
+ if (runtime.restartPromise === work) runtime.restartPromise = null
1214
+ })
1215
+ return { accepted: true }
1216
+ }
1217
+
1218
+ async function runRestart(ctx, runtime, token) {
1219
+ const log = (level, ...args) => ctx.progress.log(runtime, level, ...args)
1220
+ const phase = (name, code, params) => ctx.progress.phase(runtime, name, code, params)
1221
+ const layout = layoutForRuntime(runtime)
1222
+ const profile = runtime.remote.profile ?? ctx.settings().bootstrap.profile
1223
+ const previousPort = runtime.remote.port
1224
+ // Restarting from the remote-unreachable error state has no tunnel to keep.
1225
+ const hadTunnel = runtime.tunnel !== null
1226
+ let killable = false
1227
+ let stoppedOwn = false
1228
+ let started = false
1229
+ let tunnelCreated = false
1230
+ try {
1231
+ stopRemoteHeartbeat(runtime)
1232
+ cancelIdleStop(runtime)
1233
+ log('info', `restart requested (pid=${runtime.remote.pid ?? 'unknown'}, remote port=${previousPort ?? 'unknown'})`)
1234
+ ctx.progress.set(runtime, { status: 'connecting', error: null, phase: 'start' })
1235
+ phase('start', 'restarting-remote', { pid: Number(runtime.remote.pid) || 0, port: Number(previousPort) || 0 })
1236
+
1237
+ // Whether the running pid is ours to stop needs three independent proofs: the registry
1238
+ // names it, this connection launched it, and /proc still shows the same process. A pid that
1239
+ // a re-attach discovered (or one kept alongside) is hosted, never killed.
1240
+ const registry = await readRegistryQuietly(ctx, runtime, layout)
1241
+ const managedPid = Number(runtime.remote.pid ?? 0)
1242
+ const registeredPid = Number(registry?.pid ?? 0)
1243
+ const registered =
1244
+ registry !== null &&
1245
+ registry.dshHome === layout.dshHome &&
1246
+ registry.profile === profile &&
1247
+ isPid(managedPid) &&
1248
+ registeredPid === managedPid
1249
+ if (registered) {
1250
+ const verdict = await killAuthorized(ctx, runtime, managedPid, layout, profile)
1251
+ killable = verdict.ok === true
1252
+ if (!killable) {
1253
+ log(
1254
+ 'warn',
1255
+ `restart: not stopping pid ${managedPid} (${verdict.reason}); only a process this connection launched is stopped`,
1256
+ )
1257
+ }
1258
+ } else {
1259
+ log(
1260
+ 'warn',
1261
+ `restart: the run registry does not name this connection's pid (${
1262
+ isPid(managedPid) ? managedPid : 'unknown'
1263
+ }); leaving the running instance alone`,
1264
+ )
1265
+ }
1266
+ // A live instance this connection cannot stop and did not launch (typically the pid a
1267
+ // re-attach discovered) still occupies this ~/.dsh + profile. It goes through the conflict
1268
+ // prompt: restarting must never start a second instance silently next to it
1269
+ // (docs/design.md §5.5). Pids this connection launched are its own current instance; the
1270
+ // registry mismatch is the caller's existing "leave it alone" behavior, not a foreign one.
1271
+ let knownProcess = null
1272
+ const launchedHere = runtime.launched instanceof Map && runtime.launched.has(managedPid)
1273
+ if (!killable && !launchedHere && isPid(managedPid) && runtime.ssh?.connected === true) {
1274
+ const identity = await ctx.deps.processIdentity(runtime.ssh, managedPid)
1275
+ if (identity.ok === true) {
1276
+ const sameHome = identity.dshHome === '' || identity.dshHome === layout.dshHome
1277
+ if (sameHome && commandMatchesProfile(identity.command, profile)) {
1278
+ knownProcess = { pid: managedPid, command: identity.command }
1279
+ }
1280
+ } else if (identity.reason === 'unreadable') {
1281
+ // Alive but not provable: asking is safer than starting a second instance.
1282
+ knownProcess = { pid: managedPid, command: `dsh --profile ${profile}` }
1283
+ }
1284
+ }
1285
+ if (!isLinkWorkCurrent(runtime, token)) return
1286
+
1287
+ // Ask about foreign instances BEFORE anything is stopped: cancelling the prompt must not
1288
+ // destroy the instance the user is currently connected to (docs/design.md §5.5).
1289
+ const decision = await resolveForeignConflict(ctx, runtime, layout, profile, {
1290
+ ignoredPids: Array.isArray(runtime.alongsidePids) ? runtime.alongsidePids : [],
1291
+ knownProcess,
1292
+ })
1293
+ if (!isLinkWorkCurrent(runtime, token)) return
1294
+ // The prompt stopped the instance this connection was attached to: the old attachment is
1295
+ // gone, so a later failure must not "resume" it.
1296
+ if (decision === 'stop') stoppedOwn = true
1297
+
1298
+ if (killable) {
1299
+ const stopped = await ctx.deps.stopWeb(runtime.ssh, layout, { pid: managedPid })
1300
+ // A stop can take seconds; the link may have been dropped or replaced in the meantime.
1301
+ // A late action must not write warning/connected state on top of that.
1302
+ if (!isLinkWorkCurrent(runtime, token)) return
1303
+ stoppedOwn = stopped?.ok === true
1304
+ if (stoppedOwn) {
1305
+ log('info', `restart: stopped the managed remote web pid=${managedPid}`)
1306
+ if (runtime.launched instanceof Map) runtime.launched.delete(managedPid)
1307
+ } else {
1308
+ // Never start a second instance next to one whose stop was not confirmed. The old
1309
+ // tunnel is still open, so the host stays usable and the user can retry.
1310
+ runtime.warning = {
1311
+ zh: '远端受管 DSH 没有确认停止,本次没有启动新实例;请稍后重试,或先断开再重连。',
1312
+ en: 'The managed remote DSH did not confirm its stop, so no new instance was started; retry shortly, or disconnect and reconnect.',
1313
+ }
1314
+ runtime.warningSource = 'restart-stop'
1315
+ log(
1316
+ 'warn',
1317
+ `restart: the managed remote web did not confirm its stop; not launching a second instance (${
1318
+ String(stopped?.output ?? '').slice(0, 300) || 'no output'
1319
+ })`,
1320
+ )
1321
+ if (resumeConnected(ctx, runtime)) return
1322
+ // The link changed under us, or there was no tunnel to keep (restart from the error
1323
+ // state): never publish a fake "connected" state; explain instead of staying stuck.
1324
+ if (isLinkWorkCurrent(runtime, token) && runtime.status === 'connecting') {
1325
+ const view = toErrorView(
1326
+ errors.restartUnavailable({
1327
+ zh: '远端受管 DSH 没有确认停止,本次没有启动新实例;请稍后重试。',
1328
+ en: 'The managed remote DSH did not confirm its stop, so no new instance was started; retry shortly.',
1329
+ }),
1330
+ )
1331
+ runtime.error = view
1332
+ runtime.status = 'error'
1333
+ runtime.phase = null
1334
+ runtime.progress = null
1335
+ runtime.remote.uiReady = false
1336
+ ctx.progress.logFailure(runtime, view, { phase: 'start' })
1337
+ ctx.emitState()
1338
+ }
1339
+ return
1340
+ }
1341
+ }
1342
+ if (!isLinkWorkCurrent(runtime, token)) return
1343
+
1344
+ const { plan, targetVersion, facts } = planForRuntime(ctx, runtime, profile)
1345
+ phase('start', 'restarting-remote', { level: plan.level })
1346
+ log('info', `restart: launching @deepseek-ai/dsh@${plan.start.targetVersion} with profile ${profile}`)
1347
+ const webInfo = await ctx.deps.startWeb(runtime.ssh, {
1348
+ plan,
1349
+ layout,
1350
+ profile,
1351
+ timeoutMs: REMOTE_START_TIMEOUT_MS,
1352
+ onLine: (line) => log('debug', `remote: ${line}`),
1353
+ })
1354
+ started = true
1355
+ if (!isLinkWorkCurrent(runtime, token)) return
1356
+ await rememberLaunched(ctx, runtime, webInfo.pid, layout, profile)
1357
+ if (webInfo.browserCarrier === 'patched') {
1358
+ log(
1359
+ 'info',
1360
+ 'the remote profile disables api-remotes (browser Remote-Event carrier); re-enabled it for this launch',
1361
+ )
1362
+ }
1363
+ log('info', `restart: remote DSH started pid ${webInfo.pid ?? '?'}, port ${webInfo.port}`)
1364
+
1365
+ const record = buildRunRegistryRecord({
1366
+ pid: webInfo.pid,
1367
+ port: webInfo.port,
1368
+ version: targetVersion,
1369
+ profile,
1370
+ dshHome: layout.dshHome,
1371
+ startedAt: webInfo.startedAt,
1372
+ })
1373
+ const written = await ctx.deps.writeRegistry(runtime.ssh, layout, record)
1374
+ if (written.ok === true) log('info', `restart: run registry refreshed (pid ${record.pid}, port ${record.port})`)
1375
+ else log('warn', 'restart: the run registry could not be refreshed:', written.output)
1376
+ if (!isLinkWorkCurrent(runtime, token)) return
1377
+
1378
+ // The remote picked a random port again, so the old tunnel points at a dead port.
1379
+ phase('tunnel', 'tunneling')
1380
+ await closeTunnel(runtime)
1381
+ runtime.token = webInfo.token
1382
+ runtime.remote = {
1383
+ ...runtime.remote,
1384
+ version: targetVersion,
1385
+ uiReady: false,
1386
+ localPort: null,
1387
+ port: webInfo.port,
1388
+ pid: webInfo.pid ?? null,
1389
+ dshHome: layout.dshHome,
1390
+ profile,
1391
+ bootstrapLevel: plan.level,
1392
+ nodeVersion: facts.nodeVersion,
1393
+ nodeSource: 'managed',
1394
+ startedAt: webInfo.startedAt ?? nowIso(),
1395
+ }
1396
+ const tunnel = await openTunnelFor(ctx, runtime, webInfo.port)
1397
+ tunnelCreated = true
1398
+ if (!isLinkWorkCurrent(runtime, token)) return
1399
+
1400
+ phase('verifying', 'verifying')
1401
+ await verifyRemoteUi(ctx, runtime, webInfo.port, webInfo.token, tunnel.localPort)
1402
+ if (!isLinkWorkCurrent(runtime, token)) return
1403
+ if (ctx.settings().saveTokens) await ctx.store.saveToken(runtime.id, webInfo.token)
1404
+ if (!isLinkWorkCurrent(runtime, token)) return
1405
+ recordRestart(runtime, {
1406
+ kind: 'local-restart',
1407
+ fromPort: previousPort,
1408
+ toPort: webInfo.port,
1409
+ pid: webInfo.pid ?? null,
1410
+ })
1411
+ markConnected(ctx, runtime)
1412
+ log(
1413
+ 'info',
1414
+ `restart: connected again on 127.0.0.1:${runtime.tunnel?.localPort ?? tunnel.localPort} (remote port ${previousPort} -> ${webInfo.port})`,
1415
+ )
1416
+ } catch (error) {
1417
+ if (!isLinkWorkCurrent(runtime, token)) {
1418
+ log('debug', 'restart aborted: the link was replaced by a disconnect or reconnect')
1419
+ return
1420
+ }
1421
+ // Nothing this connection owned was stopped, so the previous attachment is still
1422
+ // valid: cancelling a conflict prompt (or a failed relaunch) keeps the host usable.
1423
+ if (!stoppedOwn && !started && hadTunnel && runtime.ssh?.connected === true && runtime.tunnel !== null) {
1424
+ log('warn', `restart cancelled: ${messageOf(error)}; keeping the current remote instance`)
1425
+ resumeConnected(ctx, runtime)
1426
+ return
1427
+ }
1428
+ const view =
1429
+ error instanceof LinkCancelled
1430
+ ? toErrorView(errors.network(SSH_CLOSED_DETAIL, { technical: 'reason=ssh-closed during restart' }))
1431
+ : toErrorView(error)
1432
+ // Phase is cleared with the status; capture it first so the log says where it stopped.
1433
+ const failedPhase = runtime.phase
1434
+ runtime.error = view
1435
+ runtime.status = 'error'
1436
+ runtime.phase = null
1437
+ runtime.progress = null
1438
+ runtime.remote.uiReady = false
1439
+ runtime.remote.localPort = null
1440
+ // #68: a failed restart explains itself (phase, code, reason, hints, redacted details).
1441
+ ctx.progress.logFailure(runtime, view, { phase: failedPhase })
1442
+ await teardownRuntime(ctx, runtime, { stopRemote: started && runtime.entry.keepAlive === 'stop' })
1443
+ ctx.emitState()
1444
+ } finally {
1445
+ // A listener this action created must never outlive the action: a disconnect (or a host
1446
+ // removal) during the rebuild would otherwise leave it open with a disposed SSH channel.
1447
+ if (tunnelCreated && !isLinkWorkCurrent(runtime, token)) await closeTunnel(runtime)
1448
+ endLinkWork(runtime, token)
1449
+ }
1450
+ }
1451
+
1452
+ /**
1453
+ * The explicit "stop remote DSH" authorization. A restart must never stop a process this
1454
+ * plugin did not launch; here the user is pointing at the instance this connection is bound
1455
+ * to, so a re-attached pid is stoppable too - with the same `/proc` proofs, re-read now:
1456
+ *
1457
+ * - the pid must be the one this connection is bound to (`remote.pid`);
1458
+ * - it must stay out of `alongsidePids` (the user asked to keep it);
1459
+ * - this connection must have recorded it: launched it, or bound to it after a re-attach;
1460
+ * - `run/web.json` must still name that pid with the same DSH home and profile;
1461
+ * - `/proc/<pid>` must still be the same process (kernel start time), same home, same profile.
1462
+ *
1463
+ * A pid that is already gone is not an error for this action: the caller clears the stale
1464
+ * registry and releases the link, which is exactly what "stop" means in that state.
1465
+ *
1466
+ * @param {object} ctx - service context.
1467
+ * @param {object} runtime - connected (or remote-unreachable) host runtime.
1468
+ * @param {number} pid - the bound remote web pid.
1469
+ * @param {object} layout - remote layout.
1470
+ * @param {string} profile - remote DSH profile.
1471
+ * @returns {Promise<{ ok: true } | { ok: false, reason: string }>} the verdict.
1472
+ */
1473
+ async function closeAuthorized(ctx, runtime, pid, layout, profile) {
1474
+ if (!isPid(pid)) return { ok: false, reason: 'pid-unknown' }
1475
+ if (Number(runtime.remote.pid) !== pid) return { ok: false, reason: 'not-the-bound-instance' }
1476
+ if ((Array.isArray(runtime.alongsidePids) ? runtime.alongsidePids : []).includes(pid)) {
1477
+ return { ok: false, reason: 'kept-alongside' }
1478
+ }
1479
+ const launched = runtime.launched instanceof Map ? runtime.launched.get(pid) : undefined
1480
+ const bound = runtime.bound !== null && Number(runtime.bound?.pid) === pid ? runtime.bound : null
1481
+ const proof = launched ?? bound
1482
+ if (!proof) return { ok: false, reason: 'not-launched-by-this-connection' }
1483
+ const registry = await readRegistryQuietly(ctx, runtime, layout)
1484
+ const registered =
1485
+ registry !== null &&
1486
+ registry.dshHome === layout.dshHome &&
1487
+ registry.profile === profile &&
1488
+ Number(registry.pid) === pid
1489
+ if (!registered) return { ok: false, reason: 'registry-mismatch' }
1490
+ const identity = await ctx.deps.processIdentity(runtime.ssh, pid)
1491
+ if (identity.ok !== true) {
1492
+ // The process is gone: there is nothing to signal, only a stale registry to clear.
1493
+ if (identity.reason === 'missing') return { ok: false, reason: 'identity-missing' }
1494
+ return { ok: false, reason: `identity-${identity.reason}` }
1495
+ }
1496
+ if (typeof proof.startTime === 'string' && identity.startTime !== proof.startTime) {
1497
+ return { ok: false, reason: 'pid-reused' }
1498
+ }
1499
+ if (identity.dshHome !== '' && identity.dshHome !== layout.dshHome) {
1500
+ return { ok: false, reason: 'dsh-home-mismatch' }
1501
+ }
1502
+ if (!commandMatchesProfile(identity.command, profile)) return { ok: false, reason: 'profile-mismatch' }
1503
+ return { ok: true }
1504
+ }
1505
+
1506
+ /** Why the explicit stop refused, as the bilingual `ErrorView.detail` the Client renders. */
1507
+ function describeStopRefusal(reason, pid) {
1508
+ const target = isPid(pid) ? `pid ${pid}` : 'pid unknown'
1509
+ switch (reason) {
1510
+ case 'kept-alongside':
1511
+ return {
1512
+ zh: `远端进程 ${target} 是你在冲突提示里选择「保留」的实例,不会被停止。`,
1513
+ en: `The remote process ${target} is the one you chose to keep alongside; it will not be stopped.`,
1514
+ }
1515
+ case 'not-launched-by-this-connection':
1516
+ case 'not-the-bound-instance':
1517
+ return {
1518
+ zh: '远端进程不是本连接启动或接管的实例,无法证明归属,因此没有停止它;可以点「重连」。',
1519
+ en: 'The remote process is not the instance this connection launched or took over, so its ownership cannot be proven and it was not stopped; use Reconnect.',
1520
+ }
1521
+ case 'registry-mismatch':
1522
+ return {
1523
+ zh: '远端 run/web.json 没有命名本连接的进程(或读不到),无法证明归属,因此没有停止它。',
1524
+ en: 'The remote run/web.json does not name this connection\u2019s process (or could not be read), so ownership cannot be proven and nothing was stopped.',
1525
+ }
1526
+ case 'pid-reused':
1527
+ return {
1528
+ zh: '这个 pid 已被另一个进程复用,不是本连接启动的 DSH;没有停止它。',
1529
+ en: 'This pid was reused by another process, not the DSH this connection launched; nothing was stopped.',
1530
+ }
1531
+ case 'dsh-home-mismatch':
1532
+ case 'profile-mismatch':
1533
+ return {
1534
+ zh: '远端进程的 DSH home / profile 与本连接不一致,没有停止它。',
1535
+ en: 'The remote process runs a different DSH home / profile than this connection; nothing was stopped.',
1536
+ }
1537
+ case 'pid-unknown':
1538
+ return {
1539
+ zh: '本连接没有记录远端 DSH 的 pid,无法定位要停止的进程。',
1540
+ en: 'This connection has no recorded remote DSH pid, so there is no process to stop.',
1541
+ }
1542
+ default:
1543
+ return {
1544
+ zh: `无法读取远端进程 ${target} 的身份(${reason}),没有停止它。`,
1545
+ en: `The identity of the remote process ${target} could not be proven (${reason}), so nothing was stopped.`,
1546
+ }
1547
+ }
1548
+ }
1549
+
1550
+ /**
1551
+ * Stop the remote DSH this connection manages, then release the link: the tunnel closes,
1552
+ * the SSH session is released and the host lands on `disconnected` (settings and credentials
1553
+ * kept, no automatic reconnect) so the card offers Reconnect again. `run/web.json` is removed
1554
+ * by the stop itself, so the next connect starts a clean instance instead of raising the
1555
+ * "a manually started DSH is already running" conflict.
1556
+ *
1557
+ * Unlike the disconnect action this never kills a pid without an ownership proof: it reuses
1558
+ * the restart's `/proc` identity rules and additionally accepts the re-attached pid this
1559
+ * connection is bound to (docs/design.md §5.7). Available while connected and in the
1560
+ * `remote-unreachable` error state, which keeps the SSH session on purpose.
1561
+ *
1562
+ * @param {object} ctx - service context.
1563
+ * @param {object} runtime - host runtime.
1564
+ * @returns {Promise<{ ok: true, pid: number | null }>} the stopped pid (null when already gone).
1565
+ */
1566
+ export async function stopRemoteHost(ctx, runtime) {
1567
+ await ctx.init()
1568
+ if (runtime.connectPromise || runtime.linkBusy !== null) {
1569
+ throw errors.stopRemoteUnavailable(
1570
+ {
1571
+ zh: '这台主机正在执行另一个连接动作,请等它结束后再关闭远端 DSH。',
1572
+ en: 'This host is busy with another link action; wait for it to finish before stopping the remote DSH.',
1573
+ },
1574
+ { technical: 'reason=link-busy' },
1575
+ )
1576
+ }
1577
+ const connected = runtime.status === 'connected' && runtime.ssh?.connected === true && runtime.tunnel !== null
1578
+ const recoverable =
1579
+ runtime.status === 'error' &&
1580
+ runtime.error?.code === 'remote-unreachable' &&
1581
+ runtime.ssh?.connected === true &&
1582
+ runtime.facts !== null
1583
+ if (!connected && !recoverable) throw errors.stopRemoteUnavailable()
1584
+ const token = beginLinkWork(runtime, 'stop')
1585
+ const previous = {
1586
+ status: runtime.status,
1587
+ phase: runtime.phase,
1588
+ progress: runtime.progress,
1589
+ error: runtime.error,
1590
+ uiReady: runtime.remote.uiReady,
1591
+ localPort: runtime.remote.localPort,
1592
+ }
1593
+ try {
1594
+ return await runStopRemote(ctx, runtime, token)
1595
+ } catch (error) {
1596
+ const view = toErrorView(error)
1597
+ const phase = typeof runtime.phase === 'string' ? runtime.phase : previous.phase
1598
+ if (isLinkWorkCurrent(runtime, token)) {
1599
+ if (!restoreStopState(ctx, runtime, previous) && runtime.status === 'connecting') {
1600
+ // The transport went away (or the link was replaced) while the stop was failing:
1601
+ // never publish a fake "connected" state, publish the coded failure instead.
1602
+ runtime.error = view
1603
+ runtime.status = 'error'
1604
+ runtime.phase = null
1605
+ runtime.progress = null
1606
+ runtime.remote.uiReady = false
1607
+ runtime.remote.localPort = null
1608
+ ctx.emitState()
1609
+ }
1610
+ // The failure explains itself in the log too (phase, code, reason, hints, details).
1611
+ ctx.progress.logFailure(runtime, view, { phase, label: STOP_FAILED_LABEL })
1612
+ }
1613
+ throw error
1614
+ } finally {
1615
+ endLinkWork(runtime, token)
1616
+ }
1617
+ }
1618
+
1619
+ /** The first log line a refused/failed stop prints; `logFailure` owns the rest. */
1620
+ const STOP_FAILED_LABEL = {
1621
+ zh: '关闭远端 DSH 失败',
1622
+ en: 'Stopping the remote DSH failed',
1623
+ }
1624
+
1625
+ /** Put a host back the way it was when a stop did not happen. */
1626
+ function restoreStopState(ctx, runtime, previous) {
1627
+ if (previous.status === 'error') {
1628
+ runtime.status = 'error'
1629
+ runtime.error = previous.error
1630
+ runtime.phase = previous.phase
1631
+ runtime.progress = previous.progress
1632
+ runtime.remote.uiReady = previous.uiReady === true
1633
+ runtime.remote.localPort = previous.localPort ?? null
1634
+ ctx.emitState()
1635
+ return true
1636
+ }
1637
+ // `resumeConnected` refuses to stage a connected state on a link that went away (or was
1638
+ // replaced) while the stop was failing; the caller reports the coded failure instead.
1639
+ return resumeConnected(ctx, runtime)
1640
+ }
1641
+
1642
+ async function runStopRemote(ctx, runtime, token) {
1643
+ const log = (level, ...args) => ctx.progress.log(runtime, level, ...args)
1644
+ const phase = (name, code, params) => ctx.progress.phase(runtime, name, code, params)
1645
+ const layout = layoutForRuntime(runtime)
1646
+ const profile = runtime.remote.profile ?? ctx.settings().bootstrap.profile
1647
+ const pid = Number(runtime.remote.pid ?? 0)
1648
+ const port = Number(runtime.remote.port ?? 0)
1649
+ log(
1650
+ 'info',
1651
+ `stop remote requested (pid=${isPid(pid) ? pid : 'unknown'}, remote port=${isPid(port) ? port : 'unknown'})`,
1652
+ )
1653
+ // One-shot link action: the card shows a progress line and no other action may interleave.
1654
+ stopRemoteHeartbeat(runtime)
1655
+ cancelReconnect(runtime)
1656
+ cancelIdleStop(runtime)
1657
+ ctx.progress.set(runtime, { status: 'connecting', error: null, phase: 'start' })
1658
+ phase('start', 'stopping-remote', {
1659
+ pid: isPid(pid) ? pid : 0,
1660
+ port: isPid(port) ? port : 0,
1661
+ })
1662
+
1663
+ const verdict = await closeAuthorized(ctx, runtime, pid, layout, profile)
1664
+ if (!isLinkWorkCurrent(runtime, token)) {
1665
+ log('debug', 'stop remote aborted: the link was replaced by a disconnect or reconnect')
1666
+ return { ok: true, pid: null }
1667
+ }
1668
+ if (verdict.ok !== true && verdict.reason !== 'identity-missing') {
1669
+ throw errors.stopRemoteUnavailable(describeStopRefusal(verdict.reason, pid), {
1670
+ technical: `reason=${verdict.reason} pid=${isPid(pid) ? pid : 'unknown'}`,
1671
+ })
1672
+ }
1673
+
1674
+ if (verdict.reason === 'identity-missing') {
1675
+ // Nothing to signal: the process is already gone. Only its stale record remains, and it
1676
+ // must go away or the next connect would try to stop/adopt a dead pid.
1677
+ log('info', `stop remote: the bound remote process pid=${pid} is already gone; clearing its run registry`)
1678
+ const cleared = await ctx.deps.clearRegistry(runtime.ssh, layout)
1679
+ if (cleared?.ok !== true) {
1680
+ log('warn', 'stop remote: the stale run registry could not be cleared:', cleared?.output ?? 'no output')
1681
+ }
1682
+ } else {
1683
+ const stopped = await ctx.deps.stopWeb(runtime.ssh, layout, { pid })
1684
+ if (stopped?.ok !== true) {
1685
+ throw errors.stopRemoteUnavailable(
1686
+ {
1687
+ zh: '远端 DSH 进程没有报告干净停止;连接保持原样,可以重试或点「重连」。',
1688
+ en: 'The remote DSH process did not report a clean stop; the connection is unchanged, so retry or use Reconnect.',
1689
+ },
1690
+ { technical: String(stopped?.output ?? '').slice(0, 1200) || 'no output' },
1691
+ )
1692
+ }
1693
+ log('info', `stop remote: stopped the managed remote web pid=${pid}`)
1694
+ if (runtime.launched instanceof Map) runtime.launched.delete(pid)
1695
+ }
1696
+ if (!isLinkWorkCurrent(runtime, token)) {
1697
+ log('debug', 'stop remote: the link was replaced after the stop; leaving the state to that action')
1698
+ return { ok: true, pid: isPid(pid) ? pid : null }
1699
+ }
1700
+ runtime.bound = null
1701
+ // Reuse the single teardown path; `stopped` keeps the idle policy from arming a second stop.
1702
+ await disconnectHost(ctx, runtime, { stopRemote: false, stopped: true })
1703
+ runtime.bound = null
1704
+ log('info', 'stop remote: the remote DSH is stopped; the host is kept and can be reconnected')
1705
+ return { ok: true, pid: isPid(pid) ? pid : null }
1706
+ }
1707
+
1708
+ /**
1709
+ * Re-attach to a remote web that restarted on its own (plugin-market update, supervisor,
1710
+ * remote reboot): re-read the real pid/port, refresh `run/web.json`, rebuild the tunnel,
1711
+ * take the new launch token and verify. The SSH session and the host entry are untouched.
1712
+ *
1713
+ * @param {object} ctx - service context.
1714
+ * @param {object} runtime - host runtime the watchdog decided is unreachable.
1715
+ * @param {{ reason?: string, source?: string }} [info] - why the re-attach was requested.
1716
+ * @returns {Promise<{ accepted: boolean, reason?: string }>} whether the re-attach started.
1717
+ */
1718
+ export async function reattachHost(ctx, runtime, info = {}) {
1719
+ if (runtime.status !== 'connected' || runtime.ssh?.connected !== true || runtime.tunnel === null) {
1720
+ return { accepted: false, reason: 'not-connected' }
1721
+ }
1722
+ if (runtime.connectPromise || runtime.linkBusy !== null) return { accepted: false, reason: 'busy' }
1723
+ const token = beginLinkWork(runtime, 'reattach')
1724
+ const work = runReattach(ctx, runtime, info, token)
1725
+ runtime.reattachPromise = work
1726
+ void work.finally(() => {
1727
+ endLinkWork(runtime, token)
1728
+ if (runtime.reattachPromise === work) runtime.reattachPromise = null
1729
+ })
1730
+ return { accepted: true }
1731
+ }
1732
+
1733
+ async function runReattach(ctx, runtime, info, token) {
1734
+ const log = (level, ...args) => ctx.progress.log(runtime, level, ...args)
1735
+ const phase = (name, code, params) => ctx.progress.phase(runtime, name, code, params)
1736
+ const layout = layoutForRuntime(runtime)
1737
+ const profile = runtime.remote.profile ?? ctx.settings().bootstrap.profile
1738
+ const fromPort = runtime.remote.port
1739
+ const reason = typeof info?.reason === 'string' && info.reason !== '' ? info.reason : 'remote-unreachable'
1740
+ let tunnelCreated = false
1741
+ try {
1742
+ stopRemoteHeartbeat(runtime)
1743
+ cancelReconnect(runtime)
1744
+ cancelIdleStop(runtime)
1745
+ log('info', `remote restart suspected: ${reason}; re-reading the remote state`)
1746
+ ctx.progress.set(runtime, { status: 'connecting', error: null, phase: 'start' })
1747
+ phase('start', 'restarting-remote', { reason })
1748
+
1749
+ // A restart takes a moment to print its new readiness line: retry before giving up.
1750
+ const attempts = Math.max(1, Number(ctx.timers.reattachAttempts) || REMOTE_REATTACH_ATTEMPTS)
1751
+ const intervalMs = Math.max(0, Number(ctx.timers.reattachIntervalMs ?? REMOTE_REATTACH_INTERVAL_MS) || 0)
1752
+ let resolved = null
1753
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
1754
+ if (!isLinkWorkCurrent(runtime, token)) return
1755
+ resolved = await ctx.deps.resolveRemote(runtime.ssh, layout, { profile })
1756
+ if (resolved?.ok === true) break
1757
+ log(
1758
+ 'debug',
1759
+ `re-attach: remote state not ready yet (${resolved?.reason ?? 'unreadable'}), attempt ${attempt}/${attempts}`,
1760
+ )
1761
+ if (attempt < attempts && intervalMs > 0) await sleep(intervalMs)
1762
+ }
1763
+ if (!isLinkWorkCurrent(runtime, token)) return
1764
+ if (!resolved || resolved.ok !== true) {
1765
+ const detail =
1766
+ resolved?.reason === 'no-token'
1767
+ ? {
1768
+ zh: '远端 DSH 仍在运行,但它这次重启没有留下可用的 launch token,无法自动重新挂载;请点「重启」或「重连」。',
1769
+ en: 'The remote DSH is still running, but its restart left no usable launch token, so it cannot be re-attached; use "Restart" or Reconnect.',
1770
+ }
1771
+ : {
1772
+ zh: `远端 DSH 重启后没有找到可以重新挂载的实例(${resolved?.reason ?? 'unreadable'});主机与配置已保留。`,
1773
+ en: `No re-attachable remote DSH instance was found after the restart (${
1774
+ resolved?.reason ?? 'unreadable'
1775
+ }); the host and its settings are kept.`,
1776
+ }
1777
+ throw errors.remoteUnreachable(detail, {
1778
+ technical: `reason=${resolved?.reason ?? 'unknown'} fromPort=${fromPort ?? 'unknown'}`,
1779
+ })
1780
+ }
1781
+ // A takeover needs the new launch token: a real DSH rejects `/?token=` and a cookie-less
1782
+ // request, so an empty token can never be treated as success (B4).
1783
+ if (typeof resolved.token !== 'string' || resolved.token === '') {
1784
+ throw errors.remoteUnreachable(
1785
+ {
1786
+ zh: '远端 DSH 重启后没有留下可用的 launch token,无法自动重新挂载;请点「重启」或「重连」。',
1787
+ en: 'The restarted remote DSH left no usable launch token, so it cannot be re-attached; use "Restart" or Reconnect.',
1788
+ },
1789
+ { technical: `reason=no-token source=${resolved.source ?? 'unknown'} port=${resolved.port ?? 'unknown'}` },
1790
+ )
1791
+ }
1792
+ const targetVersion = ctx.localVersion()
1793
+ const remoteVersion =
1794
+ typeof resolved.version === 'string' && resolved.version !== '' ? normalizeVersion(resolved.version) : null
1795
+ if (remoteVersion && targetVersion && !versionsEqual(remoteVersion, targetVersion)) {
1796
+ // A different DSH under the same ~/.dsh would show a UI that does not match this machine;
1797
+ // the user's remedy is the explicit restart, which launches the pinned version.
1798
+ throw errors.versionMismatch(targetVersion, remoteVersion)
1799
+ }
1800
+ if (remoteVersion === null) {
1801
+ log(
1802
+ 'warn',
1803
+ 're-attach: the running DSH version could not be proven; keeping it unknown, not assuming the local one',
1804
+ )
1805
+ }
1806
+ // The pid that actually listens may differ from the wrapper this connection launched (npx
1807
+ // spawns the DSH). Keep the kill right only for the pid we are now attached to.
1808
+ if (runtime.launched instanceof Map) {
1809
+ for (const pid of [...runtime.launched.keys()]) {
1810
+ if (pid !== resolved.pid) runtime.launched.delete(pid)
1811
+ }
1812
+ }
1813
+ log(
1814
+ 'info',
1815
+ `re-attach: found remote web pid=${resolved.pid} port=${resolved.port} (source=${resolved.source}); refreshing the run registry`,
1816
+ )
1817
+ const record = buildRunRegistryRecord({
1818
+ pid: resolved.pid,
1819
+ port: resolved.port,
1820
+ // Never launder an unproven version into the registry.
1821
+ version: remoteVersion ?? '',
1822
+ profile,
1823
+ dshHome: layout.dshHome,
1824
+ origin: 'reattach',
1825
+ })
1826
+ const written = await ctx.deps.writeRegistry(runtime.ssh, layout, record)
1827
+ if (written.ok === true) log('info', `re-attach: run registry refreshed (pid ${record.pid}, port ${record.port})`)
1828
+ else log('warn', 're-attach: the run registry could not be refreshed:', written.output)
1829
+ if (!isLinkWorkCurrent(runtime, token)) return
1830
+
1831
+ phase('tunnel', 'tunneling')
1832
+ await closeTunnel(runtime)
1833
+ runtime.token = resolved.token
1834
+ runtime.remote = {
1835
+ ...runtime.remote,
1836
+ version: remoteVersion,
1837
+ uiReady: false,
1838
+ localPort: null,
1839
+ port: resolved.port,
1840
+ pid: resolved.pid,
1841
+ dshHome: resolved.dshHome ?? layout.dshHome,
1842
+ profile: resolved.profile ?? profile,
1843
+ startedAt: nowIso(),
1844
+ }
1845
+ const tunnel = await openTunnelFor(ctx, runtime, resolved.port)
1846
+ tunnelCreated = true
1847
+ if (!isLinkWorkCurrent(runtime, token)) return
1848
+
1849
+ phase('verifying', 'verifying')
1850
+ await verifyRemoteUi(ctx, runtime, resolved.port, resolved.token, tunnel.localPort)
1851
+ if (!isLinkWorkCurrent(runtime, token)) return
1852
+ if (ctx.settings().saveTokens) await ctx.store.saveToken(runtime.id, resolved.token)
1853
+ if (!isLinkWorkCurrent(runtime, token)) return
1854
+ // The re-attached instance is now the one this connection is bound to. It stays out of
1855
+ // `launched` (a restart must not kill it), but the explicit stop action may end exactly it.
1856
+ await rememberBound(ctx, runtime, resolved.pid, layout, profile, 'reattach')
1857
+ if (!isLinkWorkCurrent(runtime, token)) return
1858
+ recordRestart(runtime, {
1859
+ kind: 'remote-reattach',
1860
+ fromPort,
1861
+ toPort: resolved.port,
1862
+ pid: resolved.pid,
1863
+ reason,
1864
+ source: resolved.source,
1865
+ })
1866
+ markConnected(ctx, runtime)
1867
+ log(
1868
+ 'info',
1869
+ `re-attached: remote ${runtime.remote.version ?? 'version unknown'} on 127.0.0.1:${
1870
+ runtime.tunnel?.localPort ?? tunnel.localPort
1871
+ } (remote port ${fromPort} -> ${resolved.port})`,
1872
+ )
1873
+ } catch (error) {
1874
+ if (!isLinkWorkCurrent(runtime, token)) {
1875
+ log('debug', 're-attach aborted: the link was replaced by a disconnect or reconnect')
1876
+ return
1877
+ }
1878
+ const view =
1879
+ error instanceof LinkCancelled
1880
+ ? toErrorView(errors.network(SSH_CLOSED_DETAIL, { technical: 'reason=ssh-closed during re-attach' }))
1881
+ : toErrorView(error)
1882
+ // Phase is cleared with the status; capture it first so the log says where it stopped.
1883
+ const failedPhase = runtime.phase
1884
+ runtime.error = view
1885
+ runtime.status = 'error'
1886
+ runtime.phase = null
1887
+ runtime.progress = null
1888
+ runtime.remote.uiReady = false
1889
+ runtime.remote.localPort = null
1890
+ await closeTunnel(runtime)
1891
+ stopRemoteHeartbeat(runtime)
1892
+ // #68: a failed re-attach explains itself (phase, code, reason, hints, redacted details).
1893
+ ctx.progress.logFailure(runtime, view, { phase: failedPhase })
1894
+ ctx.emitState()
1895
+ } finally {
1896
+ // A listener this action created must never outlive the action (see runRestart).
1897
+ if (tunnelCreated && !isLinkWorkCurrent(runtime, token)) await closeTunnel(runtime)
1898
+ endLinkWork(runtime, token)
1899
+ }
1900
+ }