dsh-remote-vs 0.16.0 → 0.17.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.
@@ -0,0 +1,850 @@
1
+ /**
2
+ * Ports view: the `ssh -L` tunnels this client owns, plus a way to make more.
3
+ *
4
+ * Why a panel instead of a hidden command: a forward the panel does not show is
5
+ * invisible state. The listener lives in the HOST process, so closing the
6
+ * sidebar, switching hosts or reloading the page must not look like "the tunnel
7
+ * is gone" while it still holds a local port. The list is therefore the Host's
8
+ * own answer (a local-only read, polled), the rules the user created are
9
+ * remembered by the BROWSER, and a reload restores them — the listener belongs
10
+ * to the Host, the memory of why it exists belongs here.
11
+ *
12
+ * Two costs shape the polling: the forward list is a local JSON read (cheap, so
13
+ * every 4 s while visible), whereas the listening-port probe runs a remote
14
+ * command (`ss`/`netstat`) and is therefore rare: on mount, on an explicit
15
+ * refresh, and once every 30 s.
16
+ */
17
+ import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
18
+ import type {
19
+ RemoteForwardState,
20
+ RemoteHostSummary,
21
+ RemoteListenPort,
22
+ RemoteListenPortsResult,
23
+ } from '../protocol.ts'
24
+ import { RemoteApiError, api } from './api.ts'
25
+ import { optionStyle } from './ui.tsx'
26
+ import {
27
+ IconButton,
28
+ IconCopy,
29
+ IconRefresh,
30
+ IconStop,
31
+ copyText,
32
+ toast,
33
+ } from './vsc/kit.tsx'
34
+
35
+ const ALIAS_KEY = 'dsh-remote-vs.ports.alias'
36
+ const RULES_KEY = 'dsh-remote-vs.portForwards'
37
+
38
+ /** Local forward list: one loopback JSON call into the Host, no SSH. */
39
+ const FORWARDS_POLL_MS = 4_000
40
+ /** Listening ports: one remote exec, so this stays deliberately rare. */
41
+ const LISTEN_POLL_MS = 30_000
42
+ /**
43
+ * The remote target a rule dials by default.
44
+ *
45
+ * `ssh -L` connects to the remote host first and then dials the target FROM
46
+ * there, so the remote host's own loopback is where its services listen. The
47
+ * same reasoning makes this the target for a one-click "forward this listening
48
+ * port": a discovered `0.0.0.0` / `::` / `*` bind address is not a dialable
49
+ * address at all.
50
+ */
51
+ const DEFAULT_REMOTE_HOST = '127.0.0.1'
52
+
53
+ /**
54
+ * The remote address one discovered listener should be dialed at.
55
+ *
56
+ * A wildcard bind (`0.0.0.0` / `::` / `*`) is not a dialable address, and the
57
+ * remote host's own loopback is what every such listener accepts; a socket
58
+ * bound to a CONCRETE address (a specific interface address) must be dialed at
59
+ * that address, because the loopback would simply not be listening there.
60
+ */
61
+ function reachableHost(addr: string): string {
62
+ const bare = addr.startsWith('[') && addr.endsWith(']') ? addr.slice(1, -1) : addr
63
+ // A v4 wildcard is reachable on the remote loopback; a v6 wildcard is NOT the
64
+ // same address — a V6ONLY listener does not accept 127.0.0.1, so `::` is
65
+ // dialed at `::1` (still loopback, still reachable for a dual-stack bind).
66
+ if (bare === '' || bare === '*' || bare === '0.0.0.0') return DEFAULT_REMOTE_HOST
67
+ if (bare === '::') return '::1'
68
+ if (bare === '127.0.0.1') return DEFAULT_REMOTE_HOST
69
+ return bare
70
+ }
71
+
72
+ /** True for an integer port in range; `allowAuto` admits the 0 "assign one" case. */
73
+ function isPort(value: unknown, allowAuto = false): value is number {
74
+ if (typeof value !== 'number' || !Number.isInteger(value)) return false
75
+ if (value > 65535) return false
76
+ return value >= (allowAuto ? 0 : 1)
77
+ }
78
+
79
+ /** Parse one port typed into the form; `undefined` for anything invalid. */
80
+ function parsePort(text: string): number | undefined {
81
+ const trimmed = text.trim()
82
+ // Digits only: `parseInt` would happily turn "80abc" into 80.
83
+ if (!/^\d{1,5}$/.test(trimmed)) return undefined
84
+ const value = Number(trimmed)
85
+ return isPort(value) ? value : undefined
86
+ }
87
+
88
+ function errorText(error: unknown): string {
89
+ return error instanceof RemoteApiError ? error.message : String(error)
90
+ }
91
+
92
+ /**
93
+ * `addr:port`, bracketing an IPv6 literal.
94
+ *
95
+ * The Host's parser strips the brackets from `[::]:22` (the conventional
96
+ * spelling for display), so joining naively would print `:::22` — which reads
97
+ * as a malformed address rather than as "port 22 on every v6 interface".
98
+ */
99
+ function hostPort(addr: string, port: number): string {
100
+ return addr.includes(':') ? `[${addr}]:${port}` : `${addr}:${port}`
101
+ }
102
+
103
+ function readAlias(): string {
104
+ try {
105
+ return localStorage.getItem(ALIAS_KEY) ?? ''
106
+ } catch {
107
+ return ''
108
+ }
109
+ }
110
+
111
+ /** One saved rule: what the user asked for, not what the OS granted. */
112
+ interface StoredRule {
113
+ remoteHost: string
114
+ remotePort: number
115
+ /** 0 means "let the OS assign one", exactly as the request carried it. */
116
+ localPort: number
117
+ }
118
+
119
+ type StoredRules = Record<string, StoredRule[]>
120
+
121
+ /**
122
+ * Read the remembered rules, discarding anything that is not a valid rule.
123
+ *
124
+ * localStorage is shared with older builds and with the user's devtools, so a
125
+ * malformed entry must cost that entry — never the whole list, and never a
126
+ * `POST` built from garbage.
127
+ */
128
+ function readRules(): StoredRules {
129
+ let parsed: unknown
130
+ try {
131
+ const raw = localStorage.getItem(RULES_KEY)
132
+ if (raw === null) return {}
133
+ parsed = JSON.parse(raw)
134
+ } catch {
135
+ return {}
136
+ }
137
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return {}
138
+ const out: StoredRules = {}
139
+ for (const [alias, rows] of Object.entries(parsed as Record<string, unknown>)) {
140
+ if (!Array.isArray(rows)) continue
141
+ const rules: StoredRule[] = []
142
+ for (const row of rows) {
143
+ if (typeof row !== 'object' || row === null) continue
144
+ const { remoteHost, remotePort, localPort } = row as {
145
+ remoteHost?: unknown
146
+ remotePort?: unknown
147
+ localPort?: unknown
148
+ }
149
+ if (typeof remoteHost !== 'string' || remoteHost === '') continue
150
+ if (!isPort(remotePort) || !isPort(localPort, true)) continue
151
+ rules.push({ remoteHost, remotePort, localPort })
152
+ }
153
+ if (rules.length > 0) out[alias] = rules
154
+ }
155
+ return out
156
+ }
157
+
158
+ function writeRules(rules: StoredRules): void {
159
+ try {
160
+ localStorage.setItem(RULES_KEY, JSON.stringify(rules))
161
+ } catch {
162
+ // Private mode: the tunnels still work for this session, they just do not
163
+ // survive a reload — which is the honest degraded behaviour.
164
+ }
165
+ }
166
+
167
+ /** Remember one rule so the next mount can restore it. */
168
+ function rememberRule(alias: string, rule: StoredRule): void {
169
+ const all = readRules()
170
+ const rows = all[alias] ?? []
171
+ const duplicate = rows.some(row =>
172
+ row.remoteHost === rule.remoteHost
173
+ && row.remotePort === rule.remotePort
174
+ && row.localPort === rule.localPort)
175
+ if (duplicate) return
176
+ all[alias] = [...rows, rule]
177
+ writeRules(all)
178
+ }
179
+
180
+ /**
181
+ * Drop the saved rule behind one live forward.
182
+ *
183
+ * The id cannot be recomputed here for an auto-assigned port: the request said
184
+ * "any", the Host answered with a number, so the saved rule's `localPort` is 0
185
+ * while `forward.localPort` is real. Match the exact rule first, then the
186
+ * auto-assign one, and remove exactly ONE line — a user may legitimately hold
187
+ * two rules for the same remote port on two different local ports.
188
+ */
189
+ function forgetRule(alias: string, forward: RemoteForwardState): void {
190
+ const all = readRules()
191
+ const rows = all[alias] ?? []
192
+ const sameTarget = (row: StoredRule): boolean =>
193
+ row.remoteHost === forward.remoteHost && row.remotePort === forward.remotePort
194
+ const exact = rows.findIndex(row => sameTarget(row) && row.localPort === forward.localPort)
195
+ const auto = rows.findIndex(row => sameTarget(row) && row.localPort === 0)
196
+ const index = exact >= 0 ? exact : auto
197
+ if (index < 0) return
198
+ const next = rows.filter((_row, at) => at !== index)
199
+ if (next.length === 0) delete all[alias]
200
+ else all[alias] = next
201
+ writeRules(all)
202
+ }
203
+
204
+ /**
205
+ * Drop one SAVED rule that never became a live forward.
206
+ *
207
+ * A restore can fail for reasons that do not go away by themselves (a fixed
208
+ * local port now taken by another app, the per-alias rule ceiling): such a rule
209
+ * has no live row to press "stop" on, so without this the banner would retry it
210
+ * — and reappear — on every mount with no way out.
211
+ */
212
+ function forgetStoredRule(alias: string, rule: StoredRule): void {
213
+ const all = readRules()
214
+ const rows = all[alias] ?? []
215
+ const index = rows.findIndex(row =>
216
+ row.remoteHost === rule.remoteHost
217
+ && row.remotePort === rule.remotePort
218
+ && row.localPort === rule.localPort)
219
+ if (index < 0) return
220
+ const next = rows.filter((_row, at) => at !== index)
221
+ if (next.length === 0) delete all[alias]
222
+ else all[alias] = next
223
+ writeRules(all)
224
+ }
225
+
226
+ /**
227
+ * Merge freshly created forwards into the rendered list.
228
+ *
229
+ * The 4 s poll REPLACES the list with the Host's truth, so a just-started rule
230
+ * is shown immediately here and every list read that started before it is
231
+ * invalidated by the caller (see `adoptForward`); otherwise a poll that left
232
+ * before the POST landed would briefly erase the row the user just created.
233
+ */
234
+ function mergeForwards(
235
+ previous: RemoteForwardState[] | undefined,
236
+ added: readonly RemoteForwardState[],
237
+ ): RemoteForwardState[] {
238
+ const merged = [...(previous ?? [])]
239
+ for (const forward of added) {
240
+ const index = merged.findIndex(item => item.id === forward.id)
241
+ if (index >= 0) merged[index] = forward
242
+ else merged.push(forward)
243
+ }
244
+ return merged
245
+ }
246
+
247
+ /**
248
+ * Rail icon: a plug. Kept here rather than in `vsc/kit.tsx` because it is the
249
+ * only screen that draws one, and the shared icon set is a curated list.
250
+ */
251
+ export function IconPlug(props: { size?: number }): ReactNode {
252
+ const size = props.size ?? 16
253
+ return (
254
+ <svg
255
+ width={size}
256
+ height={size}
257
+ viewBox="0 0 16 16"
258
+ fill="none"
259
+ stroke="currentColor"
260
+ strokeWidth="1.4"
261
+ strokeLinecap="round"
262
+ strokeLinejoin="round"
263
+ aria-hidden="true"
264
+ >
265
+ <path d="M6 1.8v2.4M10 1.8v2.4" />
266
+ <path d="M4 4.2h8v2a4 4 0 0 1-4 4 4 4 0 0 1-4-4Z" />
267
+ <path d="M8 10.2v4" />
268
+ </svg>
269
+ )
270
+ }
271
+
272
+ /** Local "leaves the page" mark for the open-in-browser link. */
273
+ function IconExternal(props: { size?: number }): ReactNode {
274
+ const size = props.size ?? 14
275
+ return (
276
+ <svg
277
+ width={size}
278
+ height={size}
279
+ viewBox="0 0 16 16"
280
+ fill="none"
281
+ stroke="currentColor"
282
+ strokeWidth="1.4"
283
+ strokeLinecap="round"
284
+ strokeLinejoin="round"
285
+ aria-hidden="true"
286
+ >
287
+ <path d="M6.6 3.4H3.4v9.2h9.2V9.4" />
288
+ <path d="M9.2 2.6h4.2v4.2M13.4 2.6 8 8" />
289
+ </svg>
290
+ )
291
+ }
292
+
293
+ export function PortsView(props: {
294
+ t: (key: string) => string
295
+ hosts: RemoteHostSummary[]
296
+ visible: boolean
297
+ }): ReactNode {
298
+ const t = props.t
299
+ const [alias, setAlias] = useState<string>(readAlias)
300
+ const [forwards, setForwards] = useState<RemoteForwardState[] | undefined>(undefined)
301
+ const [forwardError, setForwardError] = useState<string | undefined>(undefined)
302
+ const [listen, setListen] = useState<RemoteListenPortsResult | undefined>(undefined)
303
+ const [listenError, setListenError] = useState<string | undefined>(undefined)
304
+ /** Rules that failed to come back after a reload (shown, never silently dropped). */
305
+ const [restoreFailed, setRestoreFailed] = useState<StoredRule[]>([])
306
+ /** The form's own failure, or a one-click forward's — one banner, one place. */
307
+ const [actionError, setActionError] = useState<string | undefined>(undefined)
308
+ /**
309
+ * What is in flight, keyed ('form', 'refresh', a forward id or a discovered
310
+ * row). A Set, not one string: a second action must neither hide the first
311
+ * one's spinner nor re-enable its button when it settles.
312
+ */
313
+ const [busy, setBusy] = useState<ReadonlySet<string>>(() => new Set())
314
+ const [remoteHost, setRemoteHost] = useState<string>(DEFAULT_REMOTE_HOST)
315
+ const [remotePort, setRemotePort] = useState<string>('')
316
+ const [localPort, setLocalPort] = useState<string>('')
317
+
318
+ const markBusy = useCallback((key: string): void => {
319
+ setBusy((previous) => {
320
+ if (previous.has(key)) return previous
321
+ const next = new Set(previous)
322
+ next.add(key)
323
+ return next
324
+ })
325
+ }, [])
326
+ const clearBusy = useCallback((key: string): void => {
327
+ setBusy((previous) => {
328
+ if (!previous.has(key)) return previous
329
+ const next = new Set(previous)
330
+ next.delete(key)
331
+ return next
332
+ })
333
+ }, [])
334
+
335
+ const effectiveAlias = (alias !== '' && props.hosts.some(host => host.alias === alias))
336
+ ? alias
337
+ : (props.hosts[0]?.alias ?? '')
338
+
339
+ /**
340
+ * Async answers must not land after unmount, and a host switch must not let
341
+ * the previous host's answer win a race against the new one. `alive` covers
342
+ * the first; the two sequence refs below cover the second.
343
+ */
344
+ const alive = useRef(true)
345
+ useEffect(() => {
346
+ alive.current = true
347
+ return () => {
348
+ alive.current = false
349
+ }
350
+ }, [])
351
+
352
+ const forwardSeq = useRef(0)
353
+ const listenSeq = useRef(0)
354
+ /**
355
+ * The alias the panel is on NOW, for async code.
356
+ *
357
+ * The restore loop below is the one path that keeps working across a host
358
+ * switch (each POST is already in flight); without this mirror it could adopt
359
+ * another host's forward into the visible list. A ref, not the state, because
360
+ * the loop must see the CURRENT pick, not the one captured when it started.
361
+ */
362
+ const aliasRef = useRef(effectiveAlias)
363
+ aliasRef.current = effectiveAlias
364
+
365
+ // Remember the host the user last looked at, exactly like the terminal panel.
366
+ useEffect(() => {
367
+ try {
368
+ localStorage.setItem(ALIAS_KEY, effectiveAlias)
369
+ } catch {
370
+ // Ignore: the picker still works, the choice just does not survive.
371
+ }
372
+ }, [effectiveAlias])
373
+
374
+ const reloadForwards = useCallback(async (host: string): Promise<void> => {
375
+ if (host === '') return
376
+ const seq = ++forwardSeq.current
377
+ try {
378
+ const list = await api.forwards(host)
379
+ if (!alive.current || seq !== forwardSeq.current) return
380
+ setForwards(list)
381
+ setForwardError(undefined)
382
+ } catch (error) {
383
+ if (!alive.current || seq !== forwardSeq.current) return
384
+ setForwardError(errorText(error))
385
+ }
386
+ }, [])
387
+
388
+ const loadListen = useCallback(async (host: string): Promise<void> => {
389
+ if (host === '') return
390
+ const seq = ++listenSeq.current
391
+ try {
392
+ const result = await api.listenPorts(host)
393
+ if (!alive.current || seq !== listenSeq.current) return
394
+ setListen(result)
395
+ setListenError(undefined)
396
+ } catch (error) {
397
+ if (!alive.current || seq !== listenSeq.current) return
398
+ setListenError(errorText(error))
399
+ }
400
+ }, [])
401
+
402
+ /**
403
+ * A host switch starts from a blank slate.
404
+ *
405
+ * The previous host's forwards and ports are not this host's anything: showing
406
+ * them under the new picker would invite the user to stop a tunnel they did
407
+ * not see. They are re-fetched immediately by the effects below.
408
+ */
409
+ useEffect(() => {
410
+ setForwards(undefined)
411
+ setForwardError(undefined)
412
+ setListen(undefined)
413
+ setListenError(undefined)
414
+ setRestoreFailed([])
415
+ setActionError(undefined)
416
+ }, [effectiveAlias])
417
+
418
+ // Forward list: cheap local read, so it follows visibility every 4 s.
419
+ useEffect(() => {
420
+ if (!props.visible || effectiveAlias === '') return
421
+ void reloadForwards(effectiveAlias)
422
+ const timer = window.setInterval(() => {
423
+ if (document.hidden) return
424
+ void reloadForwards(effectiveAlias)
425
+ }, FORWARDS_POLL_MS)
426
+ return () => {
427
+ // Invalidate a read that is still in flight, so it cannot land after the
428
+ // panel stopped caring about this host.
429
+ forwardSeq.current += 1
430
+ window.clearInterval(timer)
431
+ }
432
+ }, [props.visible, effectiveAlias, reloadForwards])
433
+
434
+ // Listening ports: one remote exec, so mount/refresh/30 s only.
435
+ useEffect(() => {
436
+ if (!props.visible || effectiveAlias === '') return
437
+ void loadListen(effectiveAlias)
438
+ const timer = window.setInterval(() => {
439
+ if (document.hidden) return
440
+ void loadListen(effectiveAlias)
441
+ }, LISTEN_POLL_MS)
442
+ return () => {
443
+ listenSeq.current += 1
444
+ window.clearInterval(timer)
445
+ }
446
+ }, [props.visible, effectiveAlias, loadListen])
447
+
448
+ /**
449
+ * Show a just-created forward at once.
450
+ *
451
+ * Bumping the sequence invalidates a list read that left before the POST
452
+ * landed: without it the 4 s poll could resolve with a list that predates the
453
+ * new rule and erase the row for a full interval.
454
+ */
455
+ const adoptForward = useCallback((forward: RemoteForwardState): void => {
456
+ forwardSeq.current += 1
457
+ // A forward created for a host the user has since left must not appear in
458
+ // the new host's list (the restore loop is the only caller that can outlive
459
+ // the switch).
460
+ if (alive.current && forward.alias === aliasRef.current) {
461
+ setForwards(previous => mergeForwards(previous, [forward]))
462
+ }
463
+ }, [])
464
+
465
+ /**
466
+ * Restore the remembered rules for one host, once per mount.
467
+ *
468
+ * Once per host per mount, not on every visibility flip: a forward that fails
469
+ * (the remote port is closed) would otherwise be retried on every rail switch,
470
+ * costing an SSH channel each time and re-raising the same banner. The rules
471
+ * are posted IN ORDER because the Host is the one place that knows whether a
472
+ * local port is free — a parallel burst would race for the same port.
473
+ *
474
+ * The live list is read FIRST: reloading the page does not restart the Host,
475
+ * so tunnels from before the reload are usually still listening and must not be
476
+ * reported as "could not be restored" (a duplicate start is rejected).
477
+ */
478
+ const restored = useRef<Set<string>>(new Set())
479
+ useEffect(() => {
480
+ if (!props.visible || effectiveAlias === '') return
481
+ if (restored.current.has(effectiveAlias)) return
482
+ restored.current.add(effectiveAlias)
483
+ const rules = readRules()[effectiveAlias] ?? []
484
+ if (rules.length === 0) return
485
+ const host = effectiveAlias
486
+ void (async () => {
487
+ let live: RemoteForwardState[] = []
488
+ try {
489
+ live = await api.forwards(host)
490
+ if (!alive.current || aliasRef.current !== host) return
491
+ setForwards(previous => mergeForwards(previous, live))
492
+ } catch {
493
+ // "Cannot read the live list" is treated as "unknown": a duplicate start
494
+ // is rejected by the Host and counted like any other restore failure.
495
+ }
496
+ const failed: StoredRule[] = []
497
+ for (const rule of rules) {
498
+ if (!alive.current || aliasRef.current !== host) return
499
+ const already = live.some(item =>
500
+ item.remoteHost === rule.remoteHost
501
+ && item.remotePort === rule.remotePort
502
+ && (rule.localPort === 0 || item.localPort === rule.localPort))
503
+ if (already) continue
504
+ try {
505
+ const forward = await api.startForward({
506
+ alias: host,
507
+ remoteHost: rule.remoteHost,
508
+ remotePort: rule.remotePort,
509
+ localPort: rule.localPort,
510
+ })
511
+ adoptForward(forward)
512
+ } catch {
513
+ failed.push(rule)
514
+ }
515
+ }
516
+ if (failed.length > 0 && alive.current && aliasRef.current === host) setRestoreFailed(failed)
517
+ })()
518
+ }, [props.visible, effectiveAlias, adoptForward])
519
+
520
+ const refresh = async (): Promise<void> => {
521
+ if (effectiveAlias === '') return
522
+ markBusy('refresh')
523
+ try {
524
+ // Both loaders own their request token and error state, so a failure in
525
+ // one never hides the answer of the other, and neither rejects.
526
+ await Promise.all([reloadForwards(effectiveAlias), loadListen(effectiveAlias)])
527
+ } finally {
528
+ if (alive.current) clearBusy('refresh')
529
+ }
530
+ }
531
+
532
+ const startManual = async (): Promise<void> => {
533
+ if (effectiveAlias === '') return
534
+ const targetPort = parsePort(remotePort)
535
+ if (targetPort === undefined) {
536
+ setActionError(t('ports.badPort'))
537
+ return
538
+ }
539
+ const trimmedLocal = localPort.trim()
540
+ const requestedLocal = trimmedLocal === '' ? 0 : parsePort(trimmedLocal)
541
+ if (requestedLocal === undefined) {
542
+ setActionError(t('ports.badPort'))
543
+ return
544
+ }
545
+ const targetHost = remoteHost.trim() === '' ? DEFAULT_REMOTE_HOST : remoteHost.trim()
546
+ markBusy('form')
547
+ try {
548
+ const forward = await api.startForward({
549
+ alias: effectiveAlias,
550
+ remoteHost: targetHost,
551
+ remotePort: targetPort,
552
+ localPort: requestedLocal,
553
+ })
554
+ adoptForward(forward)
555
+ rememberRule(effectiveAlias, { remoteHost: targetHost, remotePort: targetPort, localPort: requestedLocal })
556
+ setActionError(undefined)
557
+ // The host is rarely changed between rules; the volatile ports are cleared
558
+ // so a second rule never inherits the first one's numbers by accident.
559
+ setRemotePort('')
560
+ setLocalPort('')
561
+ } catch (error) {
562
+ if (alive.current) setActionError(errorText(error))
563
+ } finally {
564
+ if (alive.current) clearBusy('form')
565
+ }
566
+ }
567
+
568
+ /** One-click forward of a discovered port; the local port is auto-assigned. */
569
+ const forwardDiscovered = async (port: RemoteListenPort): Promise<void> => {
570
+ if (effectiveAlias === '') return
571
+ const remoteHost = reachableHost(port.addr)
572
+ const busyId = `listen:${port.addr}:${port.port}`
573
+ markBusy(busyId)
574
+ try {
575
+ const forward = await api.startForward({
576
+ alias: effectiveAlias,
577
+ remoteHost,
578
+ remotePort: port.port,
579
+ localPort: 0,
580
+ })
581
+ adoptForward(forward)
582
+ rememberRule(effectiveAlias, { remoteHost, remotePort: port.port, localPort: 0 })
583
+ setActionError(undefined)
584
+ } catch (error) {
585
+ if (alive.current) setActionError(errorText(error))
586
+ } finally {
587
+ if (alive.current) clearBusy(busyId)
588
+ }
589
+ }
590
+
591
+ const stop = async (forward: RemoteForwardState): Promise<void> => {
592
+ markBusy(forward.id)
593
+ try {
594
+ await api.stopForward(forward.id)
595
+ // Drop the row here as well as on the next poll, and invalidate reads that
596
+ // were taken while the forward was still alive.
597
+ forwardSeq.current += 1
598
+ if (alive.current) setForwards(previous => (previous ?? []).filter(item => item.id !== forward.id))
599
+ forgetRule(forward.alias, forward)
600
+ setActionError(undefined)
601
+ } catch (error) {
602
+ if (alive.current) setActionError(errorText(error))
603
+ } finally {
604
+ if (alive.current) clearBusy(forward.id)
605
+ }
606
+ }
607
+
608
+ const stateLabel = (forward: RemoteForwardState): string =>
609
+ forward.state === 'error' ? t('ports.stateError') : t('ports.stateListening')
610
+
611
+ const renderForwards = (): ReactNode => {
612
+ // No host, no list: the banner above already says what to do, and a spinner
613
+ // that can never finish would contradict it.
614
+ if (effectiveAlias === '') return null
615
+ if (forwards === undefined) {
616
+ // A failed FIRST load is explained by the banner; "loading" next to it
617
+ // would be two answers to one question.
618
+ if (forwardError !== undefined) return null
619
+ return <div className="rvs-empty">{t('common.loading')}</div>
620
+ }
621
+ if (forwards.length === 0) return <div className="rvs-empty">{t('ports.emptyForwards')}</div>
622
+ return forwards.map((forward) => {
623
+ const label = stateLabel(forward)
624
+ return (
625
+ <div key={forward.id} className="rvs-ports-row">
626
+ <div className="rvs-ports-line">
627
+ <span className={`rvs-ports-dot ${forward.state}`} role="img" aria-label={label} title={label} />
628
+ <span className="rvs-ports-addr" title={`${hostPort(forward.remoteHost, forward.remotePort)} → ${forward.localUrl}`}>
629
+ {hostPort(forward.remoteHost, forward.remotePort)} → {forward.localUrl}
630
+ </span>
631
+ </div>
632
+ {forward.lastError !== undefined && <div className="rvs-ports-err">{forward.lastError}</div>}
633
+ <div className="rvs-ports-actions">
634
+ <span className="rvs-ports-conn">
635
+ {t('ports.connections').replace('{count}', String(forward.connections))}
636
+ </span>
637
+ <span style={{ flex: 1 }} />
638
+ <IconButton title={t('ports.copyUrl')} onClick={() => { void copyText(forward.localUrl).then(() => toast(t('ports.copied'))) }}>
639
+ <IconCopy size={13} />
640
+ </IconButton>
641
+ {/* A forward is only useful if it is reachable from the browser, so
642
+ "open" is a normal link: no window.open, no opener hand-off. */}
643
+ <a
644
+ className="rvs-hbtn rvs-ports-open"
645
+ href={forward.localUrl}
646
+ target="_blank"
647
+ rel="noopener noreferrer"
648
+ title={t('ports.open')}
649
+ aria-label={t('ports.open')}
650
+ >
651
+ <IconExternal size={13} />
652
+ </a>
653
+ <IconButton
654
+ title={t('ports.stop')}
655
+ danger
656
+ disabled={busy.has(forward.id)}
657
+ onClick={() => { void stop(forward) }}
658
+ >
659
+ <IconStop size={13} />
660
+ </IconButton>
661
+ </div>
662
+ </div>
663
+ )
664
+ })
665
+ }
666
+
667
+ /** The "what did the probe find" half of the listening section. */
668
+ const listenBody = (result: RemoteListenPortsResult): ReactNode => {
669
+ // `none`/`unknown` are "cannot enumerate", never "nothing is listening" —
670
+ // a blank list would read as a clean bill of health the probe cannot give.
671
+ if (result.tool === 'none') {
672
+ return (
673
+ <div className="rvs-empty">
674
+ {t('ports.listenUnavailable')}
675
+ {result.error !== undefined && <div className="rvs-ports-hint">{result.error}</div>}
676
+ </div>
677
+ )
678
+ }
679
+ if (result.tool === 'unknown') {
680
+ return (
681
+ <div className="rvs-empty">
682
+ {t('ports.listenUnknown')}
683
+ {result.error !== undefined && <div className="rvs-ports-hint">{result.error}</div>}
684
+ </div>
685
+ )
686
+ }
687
+ if (result.ports.length === 0) return <div className="rvs-empty">{t('ports.emptyListen')}</div>
688
+ return (
689
+ <>
690
+ {result.ports.map((port) => {
691
+ const busyId = `listen:${port.addr}:${port.port}`
692
+ return (
693
+ <div key={`${port.addr}:${port.port}`} className="rvs-ports-row">
694
+ <div className="rvs-ports-line">
695
+ <span className="rvs-ports-addr">{hostPort(port.addr, port.port)}</span>
696
+ {port.process !== undefined && <span className="rvs-ports-proc" title={port.process}>{port.process}</span>}
697
+ </div>
698
+ <div className="rvs-ports-actions">
699
+ <span style={{ flex: 1 }} />
700
+ <button
701
+ type="button"
702
+ className="rvs-chip"
703
+ disabled={busy.has(busyId)}
704
+ onClick={() => { void forwardDiscovered(port) }}
705
+ >
706
+ {t('ports.forward')}
707
+ </button>
708
+ </div>
709
+ </div>
710
+ )
711
+ })}
712
+ {result.error !== undefined && <div className="rvs-ports-hint">{result.error}</div>}
713
+ </>
714
+ )
715
+ }
716
+
717
+ const renderListen = (): ReactNode => {
718
+ if (effectiveAlias === '') return null
719
+ if (listen === undefined) {
720
+ if (listenError !== undefined) return <div className="rvs-banner error">{listenError}</div>
721
+ return <div className="rvs-empty">{t('common.loading')}</div>
722
+ }
723
+ return (
724
+ <>
725
+ {listenBody(listen)}
726
+ {/* A stale list is still evidence, so a failed REFRESH is reported under
727
+ it instead of replacing what the last probe actually saw. */}
728
+ {listenError !== undefined && <div className="rvs-ports-hint">{listenError}</div>}
729
+ </>
730
+ )
731
+ }
732
+
733
+ return (
734
+ <div className="rvs-pane grow">
735
+ <div className="rvs-header">
736
+ <span className="rvs-title">{t('tab.ports')}</span>
737
+ <select
738
+ className="rvs-select"
739
+ value={effectiveAlias}
740
+ onChange={(e) => setAlias(e.target.value)}
741
+ disabled={props.hosts.length === 0}
742
+ title={t('ports.selectHost')}
743
+ style={{ flex: 1, minWidth: 90 }}
744
+ >
745
+ {props.hosts.map(host => (
746
+ <option key={host.alias} value={host.alias} style={optionStyle}>
747
+ {host.alias} ({host.user}@{host.host})
748
+ </option>
749
+ ))}
750
+ </select>
751
+ <IconButton
752
+ title={t('ports.refresh')}
753
+ onClick={() => { void refresh() }}
754
+ disabled={effectiveAlias === '' || busy.has('refresh')}
755
+ >
756
+ <IconRefresh size={14} />
757
+ </IconButton>
758
+ </div>
759
+
760
+ {props.hosts.length === 0 && <div className="rvs-banner warn">{t('ports.noHosts')}</div>}
761
+ {forwardError !== undefined && <div className="rvs-banner error">{forwardError}</div>}
762
+ {restoreFailed.length > 0 && (
763
+ <div className="rvs-banner warn rvs-ports-restore">
764
+ <span>{t('ports.restoreFailed').replace('{count}', String(restoreFailed.length))}</span>
765
+ <button
766
+ type="button"
767
+ className="rvs-chip"
768
+ onClick={() => {
769
+ // These rules have no live row to stop from, so forgetting them is
770
+ // the only way to stop the retry/banner cycle on every mount.
771
+ for (const rule of restoreFailed) forgetStoredRule(effectiveAlias, rule)
772
+ setRestoreFailed([])
773
+ }}
774
+ >
775
+ {t('ports.forgetFailed')}
776
+ </button>
777
+ </div>
778
+ )}
779
+
780
+ <div className="rvs-ports-body">
781
+ <form
782
+ className="rvs-ports-form"
783
+ onSubmit={(event) => {
784
+ event.preventDefault()
785
+ void startManual()
786
+ }}
787
+ >
788
+ <div className="rvs-ports-hint">{t('ports.remoteHostHint')}</div>
789
+ <label className="rvs-ports-field">
790
+ <span className="rvs-ports-label">{t('ports.remoteHost')}</span>
791
+ <input
792
+ className="rvs-input rvs-ports-input"
793
+ value={remoteHost}
794
+ spellCheck={false}
795
+ autoComplete="off"
796
+ onChange={(e) => setRemoteHost(e.target.value)}
797
+ />
798
+ </label>
799
+ <label className="rvs-ports-field">
800
+ <span className="rvs-ports-label">{t('ports.remotePort')}</span>
801
+ <input
802
+ className="rvs-input rvs-ports-input"
803
+ value={remotePort}
804
+ inputMode="numeric"
805
+ spellCheck={false}
806
+ autoComplete="off"
807
+ placeholder="5432"
808
+ onChange={(e) => setRemotePort(e.target.value)}
809
+ />
810
+ </label>
811
+ <label className="rvs-ports-field">
812
+ <span className="rvs-ports-label">{t('ports.localPort')}</span>
813
+ <input
814
+ className="rvs-input rvs-ports-input"
815
+ value={localPort}
816
+ inputMode="numeric"
817
+ spellCheck={false}
818
+ autoComplete="off"
819
+ onChange={(e) => setLocalPort(e.target.value)}
820
+ />
821
+ </label>
822
+ <div className="rvs-ports-form-actions">
823
+ <button
824
+ type="submit"
825
+ className="rvs-chip primary"
826
+ disabled={effectiveAlias === '' || busy.has('form')}
827
+ >
828
+ {t('ports.add')}
829
+ </button>
830
+ </div>
831
+ </form>
832
+
833
+ {actionError !== undefined && <div className="rvs-banner error">{actionError}</div>}
834
+
835
+ <div className="rvs-ports-section">
836
+ <div className="rvs-ports-sec-head">
837
+ {t('ports.active')}
838
+ {forwards !== undefined && <span className="rvs-ports-count">{forwards.length}</span>}
839
+ </div>
840
+ {renderForwards()}
841
+ </div>
842
+
843
+ <div className="rvs-ports-section">
844
+ <div className="rvs-ports-sec-head">{t('ports.listening')}</div>
845
+ {renderListen()}
846
+ </div>
847
+ </div>
848
+ </div>
849
+ )
850
+ }