dsh-remote-vs 0.18.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client/api.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  type RemoteForwardState,
21
21
  type RemoteHostSummary,
22
22
  type RemoteListenPortsResult,
23
+ type RemoteMetricsResult,
23
24
  type RemotePluginMeta,
24
25
  type RemoteProbe,
25
26
  type RemoteRead,
@@ -606,6 +607,21 @@ export const api = {
606
607
  */
607
608
  listenPorts: (alias: string) =>
608
609
  call<RemoteListenPortsResult>(`${REMOTE_API.listenPorts}?alias=${encodeURIComponent(alias)}`),
610
+ /**
611
+ * One host's live metrics sample.
612
+ *
613
+ * `refresh` bypasses the Host's few-second reuse window (manual refresh).
614
+ * The route always answers one entry for `alias`; a host that disappeared
615
+ * between the panel's host list and this call is a normal 404.
616
+ */
617
+ hostMetrics: (alias: string, refresh = false) =>
618
+ call<RemoteMetricsResult>(
619
+ `${REMOTE_API.metrics}?alias=${encodeURIComponent(alias)}${refresh ? '&refresh=1' : ''}`,
620
+ ).then((result) => {
621
+ const metrics = result.hosts.find(host => host.alias === alias) ?? result.hosts[0]
622
+ if (metrics === undefined) throw new RemoteApiError(502, `no metrics for ${alias}`)
623
+ return metrics
624
+ }),
609
625
  // -- git (over the exec route; parsed in the browser, no host changes)
610
626
  // Timeouts come from the effective setting: status/log on a huge cold tree
611
627
  // routinely exceed the old fixed 120 s, and the client deadline used to cut
@@ -72,6 +72,7 @@ const zh: Record<string, string> = {
72
72
  'tab.files': '文件',
73
73
  'tab.terminal': '终端',
74
74
  'tab.ports': '端口',
75
+ 'tab.monitor': '监控',
75
76
  'tab.remote': '远程',
76
77
  'tab.remoteDesc': '远端文件、终端与 Git',
77
78
  'hosts.title': '远程主机',
@@ -638,6 +639,47 @@ const zh: Record<string, string> = {
638
639
  'ports.restoreFailed': '{count} 条已保存的转发规则未能恢复:本地端口可能被占用,或已超过每台主机的规则上限。',
639
640
  'ports.forgetFailed': '移除这些规则',
640
641
  'ports.remoteHostHint': '目标地址由远端主机拨号,可访问远端内网;本地监听只绑定 127.0.0.1。',
642
+ // -- 主机监控(侧栏「监控」页):仅 Linux 提供完整指标;可见时 5s 采样
643
+ 'monitor.selectScope': '选择监控范围',
644
+ 'monitor.scopeCurrent': '当前主机',
645
+ 'monitor.scopeAll': '全部主机',
646
+ 'monitor.refresh': '立即刷新',
647
+ 'monitor.pause': '暂停自动刷新',
648
+ 'monitor.resume': '继续自动刷新',
649
+ 'monitor.paused': '自动刷新已暂停,仍可手动刷新。',
650
+ 'monitor.loading': '正在采样…',
651
+ 'monitor.noHosts': '还没有主机,请先去「设置 → 远程主机」配置。',
652
+ 'monitor.noHost': '没有可监控的主机。',
653
+ 'monitor.noData': '还没有采样数据',
654
+ 'monitor.warming': '首次采样中',
655
+ 'monitor.unknown': '—',
656
+ 'monitor.justNow': '刚刚更新',
657
+ 'monitor.updatedAgo': '{age}前更新',
658
+ 'monitor.stateOk': '正常',
659
+ 'monitor.stateUnknown': '未知',
660
+ 'monitor.stateError': '采样失败',
661
+ 'monitor.reason': '原因:{reason}',
662
+ 'monitor.cpu': 'CPU',
663
+ 'monitor.ram': '内存',
664
+ 'monitor.disk': '磁盘',
665
+ 'monitor.temp': '温度',
666
+ 'monitor.uptime': '运行时长',
667
+ 'monitor.load': '负载 1/5/15',
668
+ 'monitor.net': '网络',
669
+ 'monitor.cores': '{count} 核',
670
+ 'monitor.cpuHistory': 'CPU 历史',
671
+ 'monitor.memHistory': '内存历史',
672
+ 'monitor.netHistory': '网络历史',
673
+ 'monitor.tempHistory': '温度历史',
674
+ 'monitor.allSummary': '{ok}/{total} 台主机采样正常',
675
+ 'monitor.inspect': '查看这台主机',
676
+ 'monitor.settings': '刷新设置',
677
+ 'monitor.interval': '刷新间隔',
678
+ 'monitor.intervalHint': '仅在面板可见时按此间隔采样;默认 5 秒。',
679
+ 'monitor.interval5': '5 秒',
680
+ 'monitor.interval10': '10 秒',
681
+ 'monitor.interval30': '30 秒',
682
+ 'monitor.linuxOnly': '完整指标来自 Linux /proc;其他平台显示为未知。',
641
683
  }
642
684
 
643
685
  const en: Record<string, string> = {
@@ -645,6 +687,7 @@ const en: Record<string, string> = {
645
687
  'tab.files': 'Files',
646
688
  'tab.terminal': 'Terminal',
647
689
  'tab.ports': 'Ports',
690
+ 'tab.monitor': 'Monitor',
648
691
  'tab.remote': 'Remote',
649
692
  'tab.remoteDesc': 'Remote files, terminal and Git',
650
693
  'hosts.title': 'Remote hosts',
@@ -1211,6 +1254,47 @@ const en: Record<string, string> = {
1211
1254
  'ports.restoreFailed': '{count} saved forward(s) could not be restored — the local port may be taken, or the per-host rule limit reached.',
1212
1255
  'ports.forgetFailed': 'Forget these rules',
1213
1256
  'ports.remoteHostHint': 'The target is dialed from the remote host, so it can reach that host’s private network; the local listener binds 127.0.0.1 only.',
1257
+ // -- host monitor (sidebar "Monitor" view): full metrics on Linux; 5 s while visible
1258
+ 'monitor.selectScope': 'Select the hosts to monitor',
1259
+ 'monitor.scopeCurrent': 'Current host',
1260
+ 'monitor.scopeAll': 'All hosts',
1261
+ 'monitor.refresh': 'Refresh now',
1262
+ 'monitor.pause': 'Pause auto refresh',
1263
+ 'monitor.resume': 'Resume auto refresh',
1264
+ 'monitor.paused': 'Auto refresh is paused; manual refresh still works.',
1265
+ 'monitor.loading': 'Sampling…',
1266
+ 'monitor.noHosts': 'No hosts yet. Configure one under Settings → Remote hosts first.',
1267
+ 'monitor.noHost': 'No host to monitor.',
1268
+ 'monitor.noData': 'No sample yet',
1269
+ 'monitor.warming': 'First sample in progress',
1270
+ 'monitor.unknown': '—',
1271
+ 'monitor.justNow': 'Updated just now',
1272
+ 'monitor.updatedAgo': 'Updated {age} ago',
1273
+ 'monitor.stateOk': 'Healthy',
1274
+ 'monitor.stateUnknown': 'Unknown',
1275
+ 'monitor.stateError': 'Sample failed',
1276
+ 'monitor.reason': 'Reason: {reason}',
1277
+ 'monitor.cpu': 'CPU',
1278
+ 'monitor.ram': 'Memory',
1279
+ 'monitor.disk': 'Disk',
1280
+ 'monitor.temp': 'Temp',
1281
+ 'monitor.uptime': 'Uptime',
1282
+ 'monitor.load': 'Load 1/5/15',
1283
+ 'monitor.net': 'Network',
1284
+ 'monitor.cores': '{count} cores',
1285
+ 'monitor.cpuHistory': 'CPU history',
1286
+ 'monitor.memHistory': 'Memory history',
1287
+ 'monitor.netHistory': 'Network history',
1288
+ 'monitor.tempHistory': 'Temperature history',
1289
+ 'monitor.allSummary': '{ok}/{total} hosts sampling normally',
1290
+ 'monitor.inspect': 'Inspect this host',
1291
+ 'monitor.settings': 'Refresh settings',
1292
+ 'monitor.interval': 'Refresh interval',
1293
+ 'monitor.intervalHint': 'Sampling runs only while the panel is visible; 5 s by default.',
1294
+ 'monitor.interval5': '5 s',
1295
+ 'monitor.interval10': '10 s',
1296
+ 'monitor.interval30': '30 s',
1297
+ 'monitor.linuxOnly': 'Full metrics come from Linux /proc; other platforms show unknown.',
1214
1298
  }
1215
1299
 
1216
1300
  export type Lang = 'zh' | 'en'
@@ -0,0 +1,242 @@
1
+ /**
2
+ * Pure model for the host monitor panel.
3
+ *
4
+ * Kept free of React and DOM so the node gate can drive it: history windows,
5
+ * sparkline geometry, number formatting and the health tone all live here.
6
+ * The panel only renders what these functions return.
7
+ *
8
+ * Honesty rules carried by this module:
9
+ * - a null measurement is never formatted as a number (the panel shows "—");
10
+ * - a flat series still draws a line (a flat 30 °C history is a real answer,
11
+ * not "no data");
12
+ * - history windows are bounded (`HISTORY_POINTS`), so a panel left open for
13
+ * hours cannot grow the page's memory.
14
+ */
15
+ import type { RemoteHostMetrics } from '../protocol.ts'
16
+
17
+ /** How many samples one sparkline keeps (5 s poll → 5 minutes). */
18
+ export const HISTORY_POINTS = 60
19
+
20
+ /** One host's rolling history, oldest first. */
21
+ export interface MetricHistory {
22
+ cpu: number[]
23
+ mem: number[]
24
+ netRx: number[]
25
+ netTx: number[]
26
+ temp: number[]
27
+ }
28
+
29
+ /** A fresh, empty window (a new array each call: the panel owns its history). */
30
+ export function emptyHistory(): MetricHistory {
31
+ return { cpu: [], mem: [], netRx: [], netTx: [], temp: [] }
32
+ }
33
+
34
+ /**
35
+ * The snapshot the panel shows when a request failed before the Host answered.
36
+ *
37
+ * Every value is null on purpose: an HTTP failure is not "0% CPU", and the
38
+ * reason line says what actually happened.
39
+ */
40
+ export function placeholderMetrics(
41
+ alias: string,
42
+ state: 'unknown' | 'error',
43
+ reason: string,
44
+ sampledAt = Date.now(),
45
+ ): RemoteHostMetrics {
46
+ return {
47
+ alias,
48
+ state,
49
+ reason,
50
+ sampledAt,
51
+ kernel: null,
52
+ cpuCores: null,
53
+ cpuModel: null,
54
+ ip: null,
55
+ uptimeSeconds: null,
56
+ load1: null,
57
+ load5: null,
58
+ load15: null,
59
+ cpuPercent: null,
60
+ memUsedBytes: null,
61
+ memTotalBytes: null,
62
+ memPercent: null,
63
+ diskUsedBytes: null,
64
+ diskTotalBytes: null,
65
+ diskPercent: null,
66
+ temperatureC: null,
67
+ netRxBps: null,
68
+ netTxBps: null,
69
+ }
70
+ }
71
+
72
+ /** Append one sample, dropping the oldest past `HISTORY_POINTS` (identity when unchanged). */
73
+ export function pushPoint(points: number[], value: number | null): number[] {
74
+ if (value === null || !Number.isFinite(value)) return points
75
+ const next = [...points, value]
76
+ if (next.length > HISTORY_POINTS) next.splice(0, next.length - HISTORY_POINTS)
77
+ return next
78
+ }
79
+
80
+ /** One metrics answer → the next history (same object when nothing changed). */
81
+ export function appendMetrics(history: MetricHistory, metrics: RemoteHostMetrics): MetricHistory {
82
+ const cpu = pushPoint(history.cpu, metrics.cpuPercent)
83
+ const mem = pushPoint(history.mem, metrics.memPercent)
84
+ const netRx = pushPoint(history.netRx, metrics.netRxBps)
85
+ const netTx = pushPoint(history.netTx, metrics.netTxBps)
86
+ const temp = pushPoint(history.temp, metrics.temperatureC)
87
+ if (cpu === history.cpu && mem === history.mem && netRx === history.netRx
88
+ && netTx === history.netTx && temp === history.temp) return history
89
+ return { cpu, mem, netRx, netTx, temp }
90
+ }
91
+
92
+ function round2(value: number): number {
93
+ return Math.round(value * 100) / 100
94
+ }
95
+
96
+ /** One shared y-domain for two series (so RX and TX are comparable). */
97
+ export interface SparkDomain {
98
+ min: number
99
+ max: number
100
+ }
101
+
102
+ /**
103
+ * The y-domain covering BOTH series.
104
+ *
105
+ * Two series drawn on independent auto-scales look identical even when one is
106
+ * 100× the other (the RX/TX bug this exists to prevent). Null when neither
107
+ * series has a finite value.
108
+ */
109
+ export function combineDomain(first: readonly number[], second: readonly number[] = []): SparkDomain | undefined {
110
+ const all = [...first, ...second].filter(value => Number.isFinite(value))
111
+ if (all.length === 0) return undefined
112
+ let min = Math.min(...all)
113
+ let max = Math.max(...all)
114
+ if (min === max) {
115
+ min -= 1
116
+ max += 1
117
+ }
118
+ return { min, max }
119
+ }
120
+
121
+ /**
122
+ * SVG path for a sparkline inside a `width × height` viewBox.
123
+ *
124
+ * The y axis is auto-scaled to the window's own min/max unless `domain` is
125
+ * supplied; a flat window draws a line through the middle instead of dividing
126
+ * by zero. A one-point window draws a dot-sized path on the right edge (the
127
+ * line grows as samples arrive). Returns '' only when there is no finite value
128
+ * at all.
129
+ */
130
+ export function sparklinePath(
131
+ values: readonly number[],
132
+ width: number,
133
+ height: number,
134
+ domain?: SparkDomain,
135
+ ): string {
136
+ const points = values.filter(value => Number.isFinite(value))
137
+ if (points.length === 0 || width <= 0 || height <= 0) return ''
138
+ let min = domain === undefined ? Math.min(...points) : domain.min
139
+ let max = domain === undefined ? Math.max(...points) : domain.max
140
+ if (max === min) {
141
+ // A flat series is a real answer: centre it instead of collapsing to a
142
+ // division by zero (which used to render a blank chart).
143
+ min -= 1
144
+ max += 1
145
+ }
146
+ const step = points.length === 1 ? 0 : width / (points.length - 1)
147
+ const coordinates = points.map((value, index) => {
148
+ const x = points.length === 1 ? width : index * step
149
+ const ratio = 1 - (value - min) / (max - min)
150
+ const y = Math.max(0, Math.min(height, ratio * height))
151
+ return `${round2(x)},${round2(y)}`
152
+ })
153
+ return `M${coordinates.join('L')}`
154
+ }
155
+
156
+ const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'] as const
157
+
158
+ /** `1536` → `1.5 KB`; `0` stays `0 B` (bytes are integers, not fractions). */
159
+ export function formatBytes(bytes: number): string {
160
+ if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'
161
+ let value = bytes
162
+ let unit = 0
163
+ while (value >= 1024 && unit < BYTE_UNITS.length - 1) {
164
+ value /= 1024
165
+ unit += 1
166
+ }
167
+ if (unit === 0) return `${Math.round(value)} ${BYTE_UNITS[unit]}`
168
+ return `${value >= 100 ? Math.round(value) : Math.round(value * 10) / 10} ${BYTE_UNITS[unit]}`
169
+ }
170
+
171
+ /** Trim a scaled capacity to one decimal below 100 (the sub line must stay short). */
172
+ function scaledCapacity(bytes: number): { value: number; unit: string } {
173
+ let value = bytes
174
+ let unit = 0
175
+ while (value >= 1024 && unit < BYTE_UNITS.length - 1) {
176
+ value /= 1024
177
+ unit += 1
178
+ }
179
+ return { value, unit: BYTE_UNITS[unit] }
180
+ }
181
+
182
+ /**
183
+ * `used / total` in ONE unit, for a tile's sub line.
184
+ *
185
+ * `formatBytes` on each side doubles the unit ("5.1 GB / 16 GB"), which is
186
+ * longer than the narrow tile can show and gets ellipsised exactly where the
187
+ * capacity matters. This picks the total's unit for both numbers.
188
+ */
189
+ export function formatCapacity(usedBytes: number, totalBytes: number): string {
190
+ if (!Number.isFinite(usedBytes) || !Number.isFinite(totalBytes) || totalBytes <= 0) return ''
191
+ const total = scaledCapacity(totalBytes)
192
+ const unitIndex = BYTE_UNITS.indexOf(total.unit as (typeof BYTE_UNITS)[number])
193
+ const factor = 1024 ** unitIndex
194
+ const usedValue = usedBytes / factor
195
+ const trim = (value: number): string =>
196
+ value >= 100 ? String(Math.round(value)) : String(Math.round(value * 10) / 10)
197
+ return `${trim(usedValue)} / ${trim(total.value)} ${total.unit}`
198
+ }
199
+
200
+ /** `42.4` → `42%`. Percentages are whole numbers in this panel. */
201
+ export function formatPercent(value: number): string {
202
+ return `${Math.round(value)}%`
203
+ }
204
+
205
+ /** `1536` B/s → `1.5 KB/s`. */
206
+ export function formatRate(bytesPerSecond: number): string {
207
+ return `${formatBytes(bytesPerSecond)}/s`
208
+ }
209
+
210
+ /** `3600 * 26 + 120` → `1d 2h`; short so it fits a narrow tile. */
211
+ export function formatUptime(seconds: number): string {
212
+ const total = Math.floor(seconds)
213
+ if (!Number.isFinite(total) || total <= 0) return '—'
214
+ const days = Math.floor(total / 86400)
215
+ const hours = Math.floor((total % 86400) / 3600)
216
+ const minutes = Math.floor((total % 3600) / 60)
217
+ if (days > 0) return `${days}d ${hours}h`
218
+ if (hours > 0) return `${hours}h ${minutes}m`
219
+ return `${minutes}m`
220
+ }
221
+
222
+ /** `42.1` → `42.1 °C`. */
223
+ export function formatTemperature(celsius: number): string {
224
+ return `${Math.round(celsius * 10) / 10} °C`
225
+ }
226
+
227
+ /** Age of a sample, short form for "updated … ago" (`12s`, `3m`, `2h`). */
228
+ export function formatAgeShort(ms: number): string {
229
+ const seconds = Math.max(0, Math.floor(ms / 1000))
230
+ if (seconds < 60) return `${seconds}s`
231
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m`
232
+ return `${Math.floor(seconds / 3600)}h`
233
+ }
234
+
235
+ export type MetricTone = 'ok' | 'warn' | 'hot'
236
+
237
+ /** Bar tone: quiet below 75%, amber 75–89%, red from 90%. */
238
+ export function metricTone(percent: number | null): MetricTone {
239
+ if (percent === null || !Number.isFinite(percent) || percent < 75) return 'ok'
240
+ if (percent < 90) return 'warn'
241
+ return 'hot'
242
+ }
@@ -219,7 +219,7 @@ interface State {
219
219
  }
220
220
 
221
221
  /** The sidebar rail destinations. */
222
- export type RailView = 'explorer' | 'search' | 'scm' | 'history' | 'editor' | 'terminal' | 'ports' | 'workspaces'
222
+ export type RailView = 'explorer' | 'search' | 'scm' | 'history' | 'editor' | 'terminal' | 'ports' | 'monitor' | 'workspaces'
223
223
 
224
224
  /** One "search this folder" request coming from the tree. */
225
225
  export interface SearchRequest {
@@ -415,7 +415,7 @@ function readStoredView(): RailView {
415
415
  try {
416
416
  const saved = localStorage.getItem(VIEW_KEY)
417
417
  if (saved === 'explorer' || saved === 'search' || saved === 'scm' || saved === 'history'
418
- || saved === 'editor' || saved === 'terminal' || saved === 'ports' || saved === 'workspaces') {
418
+ || saved === 'editor' || saved === 'terminal' || saved === 'ports' || saved === 'monitor' || saved === 'workspaces') {
419
419
  return saved
420
420
  }
421
421
  } catch {