dsh-ssh-compute 0.0.0-stage → 1.2.2

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/client.js ADDED
@@ -0,0 +1,1058 @@
1
+ // dsh-ssh-compute, browser half.
2
+ //
3
+ // A plain hand-written bundle, exactly like the ones DSH ships: no build step,
4
+ // no import/export keywords, no JSX. The page loads it as a script, the module
5
+ // loader hands it a `require`, and the only module it asks for is React.
6
+ //
7
+ // It contributes two things, and nothing else:
8
+ // - `plugins.row.config` / `plugins.bundle.config`: the settings form for this
9
+ // plugin's one row. DSH does not draw a form for a Config schema by itself —
10
+ // a plugin supplies the form and gets `form.state` / `form.mutate` to read
11
+ // and write the row.
12
+ // - `plugins.detail.section`: the server list on this bundle's page, with one
13
+ // test button per server. The ssh call happens on the Host, because a page
14
+ // cannot start a process and should not hold a key.
15
+
16
+ window.__ModuleLoader__.load({
17
+ id: 'dsh-ssh-compute',
18
+ factory: (require) => {
19
+ const React = require('react')
20
+ const h = React.createElement
21
+ const { useCallback, useEffect, useMemo, useState } = React
22
+
23
+ /** This plugin's package name; both the detail slot and the config slot are mounted for every plugin. */
24
+ const PACKAGE = 'dsh-ssh-compute'
25
+ /** The row id this bundle's `cordis.patch.yml` declares; `plugins.row.config` is keyed by it. */
26
+ const ROW_ID = 'dsh-ssh-compute'
27
+ const SERVERS_ROUTE = '/dsh-ssh-compute/servers'
28
+ const TEST_ROUTE = '/dsh-ssh-compute/test'
29
+ const SSH_CONFIG_ROUTE = '/dsh-ssh-compute/ssh-config'
30
+ const LOCALE_NAMESPACE = 'dshSshCompute'
31
+
32
+ /** The scalar settings, in the order the form draws them. */
33
+ const NUMBER_FIELDS = ['connectTimeoutMs', 'commandTimeoutMs', 'logTailLines', 'maxLogBytes', 'listLimit',
34
+ 'maxFileSizeMb', 'minFreeSpaceMb', 'waitTimeoutMs', 'maxRunningJobs', 'reuseIdleSeconds']
35
+ /** Switches, drawn as checkboxes in the same grid. */
36
+ const BOOLEAN_FIELDS = ['guard', 'reuseConnection', 'recordResources']
37
+ const SERVER_FIELDS = [
38
+ { key: 'name', label: 'fieldName', hint: 'hintName' },
39
+ { key: 'host', label: 'fieldHost', hint: 'hintHost' },
40
+ { key: 'user', label: 'fieldUser', hint: undefined },
41
+ { key: 'port', label: 'fieldPort', hint: undefined, number: true },
42
+ { key: 'keyPath', label: 'fieldKeyPath', hint: 'hintKeyPath' },
43
+ { key: 'keyText', label: 'fieldKeyText', hint: 'hintKeyText', multiline: true },
44
+ { key: 'extraArgs', label: 'fieldExtraArgs', hint: 'hintExtraArgs', wide: true },
45
+ ]
46
+
47
+ const en = {
48
+ title: 'Servers',
49
+ intro: 'Each row is one entry from this plugin\'s settings. Test opens one SSH connection and reports what the machine is.',
50
+ remoteRoot: 'Jobs directory',
51
+ noServers: 'No servers configured yet. Add one below, or in the plugin settings.',
52
+ loading: 'Reading the configured servers…',
53
+ loadFailed: 'Could not read the configured servers',
54
+ test: 'Test',
55
+ testing: 'Testing…',
56
+ keyInline: 'key from settings',
57
+ keyConfigured: 'key file',
58
+ keyDetected: 'auto-detected key',
59
+ keyDefault: 'ssh default (no key in ~/.ssh)',
60
+ latency: 'round trip',
61
+ hostname: 'host',
62
+ kernel: 'kernel',
63
+ cpu: 'cpu',
64
+ memory: 'memory',
65
+ load: 'load',
66
+ gpu: 'gpu',
67
+ cores: 'cores',
68
+ megabytes: 'MB',
69
+ unavailable: 'not reported',
70
+
71
+ configLoading: 'Reading this plugin\'s configuration…',
72
+ configUnavailable: 'This DSH does not expose this plugin\'s configuration to the page.',
73
+ configReadOnly: 'The profile does not accept configuration writes.',
74
+ sectionServers: 'Remote servers',
75
+ sectionServersHint: 'The tool\'s `server` argument names one of these. With a single entry it may be omitted.',
76
+ sectionDefaults: 'Defaults',
77
+ sectionDefaultsHint: 'Leave a field empty to fall back to the built-in default.',
78
+ addServer: 'Add a server',
79
+ removeServer: 'Remove',
80
+ importButton: 'Import from ~/.ssh/config',
81
+ importTitle: 'Hosts in your ssh config',
82
+ importHint: 'Read from',
83
+ importLoading: 'Reading the ssh config…',
84
+ importMissing: 'There is no ssh config on this machine.',
85
+ importFailed: 'Could not read the ssh config',
86
+ importEmpty: 'The ssh config has no concrete Host entry to import.',
87
+ importConfirm: 'Import selected',
88
+ importCancel: 'Close',
89
+ importAlready: 'already configured',
90
+ importUnsupported: 'not supported',
91
+ importUnsupportedHint: 'Uses {detail}, which this plugin has no field for; add it by hand if you need it.',
92
+ importBadName: 'The alias has characters this plugin cannot use in a name; rename it by hand.',
93
+ importAdded: 'Added {count} server(s) to the form. Save to apply.',
94
+ emptyServers: 'No server configured. The tool will refuse to run until you add one.',
95
+ fieldName: 'Name',
96
+ fieldHost: 'Address',
97
+ fieldUser: 'User',
98
+ fieldPort: 'Port',
99
+ fieldKeyPath: 'Private key file',
100
+ fieldKeyText: 'Private key contents',
101
+ fieldExtraArgs: 'Extra ssh arguments',
102
+ hintExtraArgs: 'Space-separated, passed straight to ssh, e.g. -J bastion. A value that needs its own spaces cannot be expressed here.',
103
+ fieldMaxFileSizeMb: 'Max file size (MiB)',
104
+ fieldMinFreeSpaceMb: 'Minimum free space (MiB)',
105
+ fieldWaitTimeoutMs: 'Default wait timeout (ms)',
106
+ fieldMaxRunningJobs: 'Jobs per server',
107
+ fieldReuseConnection: 'Reuse ssh connections',
108
+ fieldReuseIdleSeconds: 'Idle reuse (s)',
109
+ fieldRecordResources: 'Record job environment',
110
+ hintName: 'The short name the tool uses, e.g. gpu01.',
111
+ hintHost: 'Hostname or IP address.',
112
+ hintKeyPath: 'Empty: the first key in ~/.ssh, then ssh\'s own default.',
113
+ hintKeyText: 'Paste key material to store it here instead of a file. Higher priority than the path.',
114
+ fieldRemoteRoot: 'Jobs directory',
115
+ fieldGuard: 'Command guard',
116
+ hintGuard: 'Refuse obviously destructive remote commands and uploads into system directories.',
117
+ fieldConnectTimeoutMs: 'Connect timeout (ms)',
118
+ fieldCommandTimeoutMs: 'Command timeout (ms)',
119
+ fieldLogTailLines: 'Log lines in status',
120
+ fieldMaxLogBytes: 'Bytes per log read',
121
+ fieldListLimit: 'Jobs per list',
122
+ save: 'Save',
123
+ saving: 'Saving…',
124
+ discard: 'Discard changes',
125
+ saved: 'Saved. The new settings apply to the next call.',
126
+ saveFailed: 'The Host refused the change.',
127
+ noChanges: 'No changes to save.',
128
+ dirty: 'Unsaved changes',
129
+ summaryServers: 'servers',
130
+ summaryNone: 'no servers configured',
131
+ summaryUnknown: 'configuration not loaded yet',
132
+ }
133
+
134
+ const zh = {
135
+ title: '服务器',
136
+ intro: '每一行是插件设置里的一台服务器。点「测试」会建立一次 SSH 连接,并报告这台机器是什么。',
137
+ remoteRoot: '任务目录',
138
+ noServers: '还没有配置服务器。在下面添加一台,或去插件设置里添加。',
139
+ loading: '正在读取已配置的服务器…',
140
+ loadFailed: '无法读取已配置的服务器',
141
+ test: '测试',
142
+ testing: '测试中…',
143
+ keyInline: '设置里粘贴的私钥',
144
+ keyConfigured: '私钥文件',
145
+ keyDetected: '自动探测的私钥',
146
+ keyDefault: 'ssh 默认(~/.ssh 里没找到私钥)',
147
+ latency: '往返耗时',
148
+ hostname: '主机名',
149
+ kernel: '内核',
150
+ cpu: 'CPU',
151
+ memory: '内存',
152
+ load: '负载',
153
+ gpu: 'GPU',
154
+ cores: '核',
155
+ megabytes: 'MB',
156
+ unavailable: '未报告',
157
+
158
+ configLoading: '正在读取插件的配置…',
159
+ configUnavailable: '这个 DSH 没有把插件配置暴露给页面。',
160
+ configReadOnly: '当前 profile 不接受配置写入。',
161
+ sectionServers: '远程服务器',
162
+ sectionServersHint: '工具的 `server` 参数用这里的名字;只有一台时可省略。',
163
+ sectionDefaults: '默认值',
164
+ sectionDefaultsHint: '留空则使用内置默认值。',
165
+ addServer: '添加服务器',
166
+ removeServer: '删除',
167
+ importButton: '从 ~/.ssh/config 导入',
168
+ importTitle: 'ssh config 里的主机',
169
+ importHint: '读取自',
170
+ importLoading: '正在读取 ssh config…',
171
+ importMissing: '这台机器上没有 ssh config 文件。',
172
+ importFailed: '无法读取 ssh config',
173
+ importEmpty: 'ssh config 里没有可导入的具体 Host。',
174
+ importConfirm: '导入所选',
175
+ importCancel: '关闭',
176
+ importAlready: '已存在',
177
+ importUnsupported: '不支持',
178
+ importUnsupportedHint: '用了 {detail},这个插件没有对应字段;确实需要就手动添加。',
179
+ importBadName: '这个别名的字符不能用作服务器名,需要手动改名。',
180
+ importAdded: '已把 {count} 台服务器加入表单,记得保存。',
181
+ emptyServers: '还没有服务器。添加之前工具会拒绝执行。',
182
+ fieldName: '名称',
183
+ fieldHost: '地址',
184
+ fieldUser: '用户名',
185
+ fieldPort: '端口',
186
+ fieldKeyPath: '私钥文件路径',
187
+ fieldKeyText: '私钥内容',
188
+ fieldExtraArgs: '额外 ssh 参数',
189
+ hintExtraArgs: '空格分隔,原样交给 ssh,例如 -J bastion。本身需要空格的参数无法在这里表达。',
190
+ fieldMaxFileSizeMb: '单文件上限(MiB)',
191
+ fieldMinFreeSpaceMb: '最小可用空间(MiB)',
192
+ fieldWaitTimeoutMs: 'wait 默认超时(毫秒)',
193
+ fieldMaxRunningJobs: '每台服务器并发上限',
194
+ fieldReuseConnection: '复用 ssh 连接',
195
+ fieldReuseIdleSeconds: '复用空闲(秒)',
196
+ fieldRecordResources: '记录任务环境',
197
+ hintName: '工具里引用它的短名字,例如 gpu01。',
198
+ hintHost: '主机名或 IP。',
199
+ hintKeyPath: '留空:先用 ~/.ssh 里的第一个私钥,再交给 ssh 自己的默认行为。',
200
+ hintKeyText: '把私钥内容粘贴到这里代替文件;优先级高于路径。',
201
+ fieldRemoteRoot: '任务目录',
202
+ fieldGuard: '命令护栏',
203
+ hintGuard: '拦截明显破坏性的远端命令,以及往系统目录的上传。',
204
+ fieldConnectTimeoutMs: '连接超时(毫秒)',
205
+ fieldCommandTimeoutMs: '命令超时(毫秒)',
206
+ fieldLogTailLines: 'status 附带日志行数',
207
+ fieldMaxLogBytes: '单次日志字节上限',
208
+ fieldListLimit: 'list 返回任务数',
209
+ save: '保存',
210
+ saving: '保存中…',
211
+ discard: '放弃修改',
212
+ saved: '已保存,下一次调用即生效。',
213
+ saveFailed: 'Host 拒绝了这次修改。',
214
+ noChanges: '没有需要保存的修改。',
215
+ dirty: '有未保存的修改',
216
+ summaryServers: '台服务器',
217
+ summaryNone: '尚未配置服务器',
218
+ summaryUnknown: '配置尚未加载',
219
+ }
220
+
221
+ const CSS = [
222
+ '.dsh-ssh-compute-section { display: flex; flex-direction: column; gap: 12px; }',
223
+ '.dsh-ssh-compute-head { display: flex; flex-direction: column; gap: 4px; }',
224
+ '.dsh-ssh-compute-title { margin: 0; font-size: 14px; font-weight: 600; color: var(--dsw-alias-label-primary); }',
225
+ '.dsh-ssh-compute-hint { margin: 0; font-size: 12px; line-height: 1.5; color: var(--dsw-alias-label-secondary); }',
226
+ '.dsh-ssh-compute-root { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; color: var(--dsw-alias-label-secondary); }',
227
+ '.dsh-ssh-compute-card { border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-1); border-radius: 10px; overflow: hidden; }',
228
+ '.dsh-ssh-compute-row { display: flex; align-items: center; gap: 12px; padding: 10px 12px; }',
229
+ '.dsh-ssh-compute-row + .dsh-ssh-compute-row { border-top: 1px solid var(--dsw-alias-border-l1); }',
230
+ '.dsh-ssh-compute-body { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1; }',
231
+ '.dsh-ssh-compute-name { font-size: 13px; font-weight: 600; color: var(--dsw-alias-label-primary); }',
232
+ '.dsh-ssh-compute-target { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; }',
233
+ '.dsh-ssh-compute-key { font-size: 11px; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; }',
234
+ '.dsh-ssh-compute-button { flex: none; border: 1px solid var(--dsw-alias-border-l2); background: transparent; color: var(--dsw-alias-label-primary); border-radius: 6px; padding: 4px 10px; font-size: 12px; cursor: pointer; }',
235
+ '.dsh-ssh-compute-button:hover:not(:disabled) { border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-brand-primary); }',
236
+ '.dsh-ssh-compute-button:disabled { opacity: 0.55; cursor: default; }',
237
+ '.dsh-ssh-compute-result { margin: 0; padding: 8px 12px; font-size: 12px; line-height: 1.6; color: var(--dsw-alias-label-secondary); border-top: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-2); overflow-wrap: anywhere; }',
238
+ '.dsh-ssh-compute-ok { color: var(--dsw-alias-state-success-primary); }',
239
+ '.dsh-ssh-compute-error { color: var(--dsw-alias-state-error-primary); }',
240
+
241
+ '.dsh-ssh-form { display: flex; flex-direction: column; gap: 20px; }',
242
+ '.dsh-ssh-group { display: flex; flex-direction: column; gap: 4px; }',
243
+ '.dsh-ssh-group + .dsh-ssh-group { margin-top: 4px; }',
244
+ '.dsh-ssh-group-title { margin: 0; font-size: 13px; font-weight: 600; color: var(--dsw-alias-label-primary); }',
245
+ '.dsh-ssh-group-hint { margin: 0 0 8px; font-size: 12px; line-height: 1.5; color: var(--dsw-alias-label-secondary); }',
246
+ '.dsh-ssh-server { border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-1); border-radius: 10px; padding: 12px; display: flex; flex-direction: column; gap: 10px; }',
247
+ '.dsh-ssh-server + .dsh-ssh-server { margin-top: 10px; }',
248
+ '.dsh-ssh-server-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }',
249
+ '.dsh-ssh-server-name { font-size: 12px; font-weight: 600; color: var(--dsw-alias-label-primary); }',
250
+ '.dsh-ssh-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px 12px; }',
251
+ '.dsh-ssh-field { display: flex; flex-direction: column; gap: 3px; min-width: 0; }',
252
+ '.dsh-ssh-field-wide { grid-column: 1 / -1; }',
253
+ '.dsh-ssh-label { font-size: 12px; color: var(--dsw-alias-label-secondary); }',
254
+ '.dsh-ssh-input { width: 100%; box-sizing: border-box; border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); border-radius: 6px; padding: 5px 8px; font-size: 12px; font-family: inherit; }',
255
+ '.dsh-ssh-input:focus { outline: none; border-color: var(--dsw-alias-brand-primary); }',
256
+ '.dsh-ssh-input:disabled { opacity: 0.6; }',
257
+ '.dsh-ssh-textarea { min-height: 64px; resize: vertical; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }',
258
+ '.dsh-ssh-field-hint { font-size: 11px; line-height: 1.5; color: var(--dsw-alias-label-secondary); }',
259
+ '.dsh-ssh-check { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--dsw-alias-label-primary); }',
260
+ '.dsh-ssh-actions { display: flex; align-items: center; gap: 10px; padding-top: 4px; }',
261
+ '.dsh-ssh-primary { border: 1px solid var(--dsw-alias-brand-primary); background: var(--dsw-alias-brand-primary); color: var(--dsw-alias-bg-base); border-radius: 6px; padding: 5px 14px; font-size: 12px; cursor: pointer; }',
262
+ '.dsh-ssh-primary:disabled { opacity: 0.5; cursor: default; }',
263
+ '.dsh-ssh-note { font-size: 12px; line-height: 1.5; }',
264
+ '.dsh-ssh-dirty { margin-left: auto; font-size: 12px; color: var(--dsw-alias-state-warn-primary); }',
265
+ '.dsh-ssh-link { border: none; background: none; padding: 0; font: inherit; font-size: 12px; color: var(--dsw-alias-state-error-primary); cursor: pointer; }',
266
+ '.dsh-ssh-import { border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-2); border-radius: 10px; padding: 12px; display: flex; flex-direction: column; gap: 8px; }',
267
+ '.dsh-ssh-import-list { display: flex; flex-direction: column; gap: 2px; max-height: 320px; overflow-y: auto; }',
268
+ '.dsh-ssh-import-row { display: flex; align-items: flex-start; gap: 10px; padding: 6px 4px; border-radius: 6px; cursor: pointer; }',
269
+ '.dsh-ssh-import-row:hover { background: var(--dsw-alias-bg-layer-1); }',
270
+ '.dsh-ssh-import-blocked { opacity: 0.6; cursor: default; }',
271
+ '.dsh-ssh-import-body { display: flex; flex-direction: column; gap: 1px; min-width: 0; }',
272
+ '.dsh-ssh-import-alias { font-size: 12px; font-weight: 600; color: var(--dsw-alias-label-primary); display: flex; align-items: center; gap: 6px; }',
273
+ '.dsh-ssh-import-tag { font-size: 10px; font-weight: 400; padding: 1px 6px; border-radius: 999px; border: 1px solid var(--dsw-alias-border-l1); color: var(--dsw-alias-label-secondary); }',
274
+ ].join('')
275
+
276
+ /**
277
+ * A slot's translator, or a fallback that keeps the entry renderable.
278
+ *
279
+ * The `locale` registration supplies `t`; if a build ever hands the entry
280
+ * props without it, a thrown error would blank the slot instead of showing
281
+ * untranslated labels, so the fallback reads the English dictionary.
282
+ */
283
+ function translator(translate) {
284
+ if (typeof translate === 'function') return translate
285
+ // The fallback also has to interpolate, because a few strings carry a
286
+ // `{name}` placeholder the host translator would fill.
287
+ return (key, params) => {
288
+ const text = typeof en[key] === 'string' ? en[key] : key
289
+ if (params === undefined) return text
290
+ return text.replace(/\{(\w+)\}/g, (whole, name) => (params[name] === undefined ? whole : String(params[name])))
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Append the picked ssh-config entries to the draft's server list.
296
+ *
297
+ * Pure, so the merge rule is testable without a renderer: an entry is added
298
+ * only when it is ticked, has a name, and does not collide with a name already
299
+ * in the draft (case-insensitively — ssh aliases are case-sensitive, but two
300
+ * cards that differ only in case would be ambiguous in the tool).
301
+ * @param draftServers - the form's current server cards.
302
+ * @param entries - what the Host reported from `~/.ssh/config`.
303
+ * @param picked - alias -> whether the box is ticked.
304
+ * @returns the new list and how many were added.
305
+ */
306
+ function mergeImportedServers(draftServers, entries, picked) {
307
+ const servers = Array.isArray(draftServers) ? draftServers : []
308
+ const taken = new Set(servers.map((server) => String(server.name ?? '').trim().toLowerCase()).filter((name) => name !== ''))
309
+ const added = []
310
+ for (const entry of Array.isArray(entries) ? entries : []) {
311
+ if (picked[entry.alias] !== true) continue
312
+ // Defense in depth: the form disables an unusable row, and the merge
313
+ // refuses it too so a caller cannot import what the Host would drop.
314
+ if (entry.nameOk === false) continue
315
+ if (Array.isArray(entry.unsupported) && entry.unsupported.length > 0) continue
316
+ const name = String(entry.name ?? entry.alias ?? '').trim()
317
+ if (name === '' || taken.has(name.toLowerCase())) continue
318
+ taken.add(name.toLowerCase())
319
+ added.push({
320
+ name,
321
+ host: String(entry.host ?? ''),
322
+ user: String(entry.user ?? ''),
323
+ port: Number(entry.port ?? 22),
324
+ keyPath: String(entry.keyPath ?? ''),
325
+ keyText: '',
326
+ extraArgs: String(entry.extraArgs ?? ''),
327
+ })
328
+ }
329
+ return { servers: [...servers, ...added], added }
330
+ }
331
+
332
+ /** Fetch JSON from one of this plugin's own routes. */
333
+ async function readJson(route, init) {
334
+ const response = await fetch(route, {
335
+ ...init,
336
+ headers: { accept: 'application/json', ...(init?.body === undefined ? {} : { 'content-type': 'application/json' }) },
337
+ })
338
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
339
+ return response.json()
340
+ }
341
+
342
+ /** One label per key source, so a wrong key is visible before the first call. */
343
+ function keyLabel(server, t) {
344
+ if (server.keySource === 'inline') return t('keyInline')
345
+ if (server.keySource === 'default') return t('keyDefault')
346
+ const prefix = server.keySource === 'detected' ? t('keyDetected') : t('keyConfigured')
347
+ return server.keyPath === null || server.keyPath === '' ? prefix : `${prefix}: ${server.keyPath}`
348
+ }
349
+
350
+ /** The facts a probe reported, in reading order. */
351
+ function factList(facts, t) {
352
+ const rows = []
353
+ const push = (label, value) => {
354
+ if (value !== undefined && value !== null && String(value).trim() !== '' && String(value) !== '?') {
355
+ rows.push(`${label} ${value}`)
356
+ }
357
+ }
358
+ push(t('hostname'), facts.hostname)
359
+ push(t('kernel'), facts.kernel)
360
+ push(t('cpu'), facts.cpu === undefined ? undefined : `${facts.cpu} ${t('cores')}`)
361
+ push(t('memory'), facts.mem_mb === undefined ? undefined : `${facts.mem_mb} ${t('megabytes')}`)
362
+ push(t('load'), facts.load)
363
+ push(t('gpu'), facts.gpu === 'none' ? undefined : facts.gpu)
364
+ return rows
365
+ }
366
+
367
+ // ---------------------------------------------------------------- detail page
368
+
369
+ /** No hooks: the guard returns null for every page that is not this bundle's. */
370
+ function ComputeSection(props) {
371
+ const subject = props.subject
372
+ if (subject === undefined || subject === null) return null
373
+ if (subject.kind === 'item') return null
374
+ if (subject.pkg === undefined || subject.pkg === null) return null
375
+ if (subject.pkg.name !== PACKAGE) return null
376
+ return h(DetailServers, { t: translator(props.t), source: props.source })
377
+ }
378
+
379
+ /**
380
+ * The server list, re-mounted whenever the Host publishes a new accepted
381
+ * configuration, so a server saved in the form above appears here without a
382
+ * page reload.
383
+ */
384
+ function DetailServers(props) {
385
+ const source = props.source
386
+ const snapshot = useSnapshot(source)
387
+ return h(ServerList, { t: props.t, key: snapshot?.revision ?? 0 })
388
+ }
389
+
390
+ function ServerList(props) {
391
+ const t = props.t
392
+ const [state, setState] = useState({ status: 'loading', servers: [], remoteRoot: '', problems: [], error: '' })
393
+ const [tests, setTests] = useState({})
394
+
395
+ useEffect(() => {
396
+ let live = true
397
+ readJson(SERVERS_ROUTE)
398
+ .then((value) => {
399
+ if (!live) return
400
+ setState({
401
+ status: 'ready',
402
+ servers: Array.isArray(value?.servers) ? value.servers : [],
403
+ remoteRoot: typeof value?.remoteRoot === 'string' ? value.remoteRoot : '',
404
+ problems: Array.isArray(value?.problems) ? value.problems : [],
405
+ error: '',
406
+ })
407
+ })
408
+ .catch((error) => {
409
+ if (!live) return
410
+ setState({ status: 'failed', servers: [], remoteRoot: '', problems: [], error: String(error?.message ?? error) })
411
+ })
412
+ return () => { live = false }
413
+ }, [])
414
+
415
+ const runTest = useCallback((name) => {
416
+ setTests((current) => ({ ...current, [name]: { busy: true } }))
417
+ readJson(TEST_ROUTE, { method: 'POST', body: JSON.stringify({ name }) })
418
+ .then((value) => setTests((current) => ({ ...current, [name]: { busy: false, value } })))
419
+ .catch((error) => setTests((current) => ({
420
+ ...current,
421
+ [name]: { busy: false, value: { ok: false, error: String(error?.message ?? error) } },
422
+ })))
423
+ }, [])
424
+
425
+ const header = h('div', { className: 'dsh-ssh-compute-head' },
426
+ h('h3', { className: 'dsh-ssh-compute-title' }, t('title')),
427
+ state.remoteRoot === ''
428
+ ? null
429
+ : h('p', { className: 'dsh-ssh-compute-hint' },
430
+ `${t('remoteRoot')}: `,
431
+ h('span', { className: 'dsh-ssh-compute-root' }, `${state.remoteRoot}/<jobId>`)),
432
+ h('p', { className: 'dsh-ssh-compute-hint' }, t('intro')),
433
+ )
434
+
435
+ // Entries the plugin could not use: a server card saved without a host, or a
436
+ // name used twice. The tool skips them, so the page has to say which.
437
+ const problems = (state.problems ?? []).map((problem) => h(
438
+ 'p',
439
+ { key: problem, className: 'dsh-ssh-compute-hint dsh-ssh-compute-error' },
440
+ problem,
441
+ ))
442
+
443
+ if (state.status === 'loading') {
444
+ return h('section', { className: 'dsh-ssh-compute-section', 'aria-label': t('title') },
445
+ header, h('p', { className: 'dsh-ssh-compute-hint' }, t('loading')))
446
+ }
447
+ if (state.status === 'failed') {
448
+ return h('section', { className: 'dsh-ssh-compute-section', 'aria-label': t('title') },
449
+ header,
450
+ h('p', { className: 'dsh-ssh-compute-hint dsh-ssh-compute-error' }, `${t('loadFailed')}: ${state.error}`))
451
+ }
452
+ if (state.servers.length === 0) {
453
+ return h('section', { className: 'dsh-ssh-compute-section', 'aria-label': t('title') },
454
+ header, problems, h('p', { className: 'dsh-ssh-compute-hint' }, t('noServers')))
455
+ }
456
+
457
+ const rows = state.servers.map((server) => {
458
+ const test = tests[server.name]
459
+ const result = test?.value
460
+ const busy = test?.busy === true
461
+ const facts = result?.ok === true && result.facts !== undefined && result.facts !== null
462
+ ? factList(result.facts, t)
463
+ : []
464
+ return h('div', { key: server.name },
465
+ h('div', { className: 'dsh-ssh-compute-row' },
466
+ h('div', { className: 'dsh-ssh-compute-body' },
467
+ h('span', { className: 'dsh-ssh-compute-name' }, server.name),
468
+ h('span', { className: 'dsh-ssh-compute-target' }, `${server.user}@${server.host}:${server.port}`),
469
+ h('span', { className: 'dsh-ssh-compute-key' }, keyLabel(server, t))),
470
+ h('button', {
471
+ type: 'button',
472
+ className: 'dsh-ssh-compute-button',
473
+ disabled: busy,
474
+ onClick: () => runTest(server.name),
475
+ }, busy ? t('testing') : t('test'))),
476
+ result === undefined
477
+ ? null
478
+ : h('p', {
479
+ className: result.ok ? 'dsh-ssh-compute-result dsh-ssh-compute-ok' : 'dsh-ssh-compute-result dsh-ssh-compute-error',
480
+ role: 'status',
481
+ }, result.ok
482
+ ? [`${t('latency')} ${result.durationMs} ms`, ...facts].join(' · ')
483
+ : result.error),
484
+ )
485
+ })
486
+
487
+ return h('section', { className: 'dsh-ssh-compute-section', 'aria-label': t('title') },
488
+ header, problems, h('div', { className: 'dsh-ssh-compute-card' }, rows))
489
+ }
490
+
491
+ // ------------------------------------------------------------- configuration
492
+ //
493
+ // Two slots can show this plugin's configuration and they hand different
494
+ // things in. `plugins.row.config` receives the page's own `form`
495
+ // (`{ state, mutate }`); `plugins.bundle.config` receives only `view`, with
496
+ // no form at all. So the page reads the `configForms` service itself and
497
+ // uses the page's form only when one is supplied — without that, the bundle
498
+ // page would render nothing and the settings would be unreachable from
499
+ // where the user actually lands.
500
+
501
+ /** One form source: read the snapshot, optionally subscribe, write ops. */
502
+ function sourceFromRecord(record) {
503
+ return {
504
+ read: () => record.getSnapshot(),
505
+ subscribe: (listener) => record.subscribe(listener),
506
+ mutate: (ops, revision) => record.mutate(ops, revision),
507
+ }
508
+ }
509
+
510
+ /** A source over the page-supplied form, which has no subscription of its own. */
511
+ function sourceFromProp(form) {
512
+ return {
513
+ read: () => form.state,
514
+ subscribe: undefined,
515
+ mutate: (ops, revision) => form.mutate(ops, revision),
516
+ }
517
+ }
518
+
519
+ /** Follow one source's snapshot; a source without subscribe just reads once. */
520
+ function useSnapshot(source) {
521
+ const [snapshot, setSnapshot] = useState(() => (source === undefined ? undefined : source.read()))
522
+ useEffect(() => {
523
+ if (source === undefined) {
524
+ setSnapshot(undefined)
525
+ return undefined
526
+ }
527
+ setSnapshot(source.read())
528
+ if (typeof source.subscribe !== 'function') return undefined
529
+ return source.subscribe(() => setSnapshot(source.read()))
530
+ }, [source])
531
+ return snapshot
532
+ }
533
+
534
+ /** One text or number input bound to the draft. */
535
+ function Field(props) {
536
+ const { label, hint, value, onChange, disabled, multiline, number, wide } = props
537
+ const className = wide ? 'dsh-ssh-field dsh-ssh-field-wide' : 'dsh-ssh-field'
538
+ const common = {
539
+ className: multiline ? 'dsh-ssh-input dsh-ssh-textarea' : 'dsh-ssh-input',
540
+ value: value === undefined || value === null ? '' : String(value),
541
+ disabled,
542
+ onChange: (event) => onChange(event.target.value),
543
+ spellCheck: false,
544
+ }
545
+ return h('label', { className },
546
+ h('span', { className: 'dsh-ssh-label' }, label),
547
+ multiline
548
+ ? h('textarea', common)
549
+ : h('input', { ...common, type: number ? 'number' : 'text', inputMode: number ? 'numeric' : undefined }),
550
+ hint === undefined ? null : h('span', { className: 'dsh-ssh-field-hint' }, hint))
551
+ }
552
+
553
+ /** The draft a form starts from: the Host's resolved values, defaults filled in. */
554
+ function toDraft(value) {
555
+ const source = value !== null && typeof value === 'object' ? value : {}
556
+ const servers = Array.isArray(source.servers) ? source.servers : []
557
+ return {
558
+ servers: servers.map((entry) => {
559
+ const server = entry !== null && typeof entry === 'object' ? entry : {}
560
+ return {
561
+ name: typeof server.name === 'string' ? server.name : '',
562
+ host: typeof server.host === 'string' ? server.host : '',
563
+ user: typeof server.user === 'string' ? server.user : '',
564
+ port: server.port === undefined || server.port === null ? 22 : server.port,
565
+ keyPath: typeof server.keyPath === 'string' ? server.keyPath : '',
566
+ keyText: typeof server.keyText === 'string' ? server.keyText : '',
567
+ extraArgs: typeof server.extraArgs === 'string' ? server.extraArgs : '',
568
+ }
569
+ }),
570
+ remoteRoot: typeof source.remoteRoot === 'string' ? source.remoteRoot : '',
571
+ guard: source.guard !== false,
572
+ connectTimeoutMs: source.connectTimeoutMs ?? '',
573
+ commandTimeoutMs: source.commandTimeoutMs ?? '',
574
+ logTailLines: source.logTailLines ?? '',
575
+ maxLogBytes: source.maxLogBytes ?? '',
576
+ listLimit: source.listLimit ?? '',
577
+ maxFileSizeMb: source.maxFileSizeMb ?? '',
578
+ minFreeSpaceMb: source.minFreeSpaceMb ?? '',
579
+ waitTimeoutMs: source.waitTimeoutMs ?? '',
580
+ maxRunningJobs: source.maxRunningJobs ?? '',
581
+ reuseIdleSeconds: source.reuseIdleSeconds ?? '',
582
+ reuseConnection: source.reuseConnection !== false,
583
+ recordResources: source.recordResources !== false,
584
+ }
585
+ }
586
+
587
+ /** Whether the draft still matches what the Host holds. */
588
+ function sameDraft(original, draft) {
589
+ // Comparing the ops rather than the drafts keeps the two in step: if the
590
+ // save button is enabled, the save has something to write, and vice versa.
591
+ return toOps(original, draft).length === 0
592
+ }
593
+
594
+ /**
595
+ * The exact shape that is written back for one server entry.
596
+ *
597
+ * The Host validates the array against the schema, so an empty port string or
598
+ * an all-blank optional field must not travel: a single invalid element would
599
+ * make the Host refuse the whole write.
600
+ */
601
+ function canonicalServers(entries) {
602
+ if (!Array.isArray(entries)) return []
603
+ return entries.map((raw) => {
604
+ const server = raw !== null && typeof raw === 'object' ? raw : {}
605
+ const port = Number(server.port ?? 22)
606
+ const entry = {
607
+ name: String(server.name ?? '').trim(),
608
+ host: String(server.host ?? '').trim(),
609
+ user: String(server.user ?? '').trim(),
610
+ port: Number.isInteger(port) && port > 0 && port < 65536 ? port : 22,
611
+ }
612
+ const keyPath = String(server.keyPath ?? '').trim()
613
+ if (keyPath !== '') entry.keyPath = keyPath
614
+ const keyText = String(server.keyText ?? '')
615
+ if (keyText.trim() !== '') entry.keyText = keyText
616
+ const extraArgs = String(server.extraArgs ?? '').trim()
617
+ if (extraArgs !== '') entry.extraArgs = extraArgs
618
+ return entry
619
+ })
620
+ }
621
+
622
+ /** Turn the draft into the Host's ordered field operations. */
623
+ function toOps(original, draft) {
624
+ const source = original !== null && typeof original === 'object' ? original : {}
625
+ const baseline = toDraft(source)
626
+ const ops = []
627
+ const nextServers = canonicalServers(draft.servers)
628
+ if (JSON.stringify(canonicalServers(baseline.servers)) !== JSON.stringify(nextServers)) {
629
+ // One atomically replaced array: a half-edited server list never reaches
630
+ // the Host, and removing the last entry clears the field instead.
631
+ if (nextServers.length === 0) ops.push({ op: 'unset', path: ['servers'] })
632
+ else ops.push({ op: 'set', path: ['servers'], value: nextServers })
633
+ }
634
+ const scalars = ['remoteRoot', ...BOOLEAN_FIELDS, ...NUMBER_FIELDS]
635
+ for (const key of scalars) {
636
+ const before = baseline[key]
637
+ const after = draft[key]
638
+ if (JSON.stringify(before) === JSON.stringify(after)) continue
639
+ if (after === '' || after === undefined || after === null) ops.push({ op: 'unset', path: [key] })
640
+ else ops.push({ op: 'set', path: [key], value: after })
641
+ }
642
+ return ops
643
+ }
644
+
645
+ function ConfigPage(props) {
646
+ const { source, t } = props
647
+ const snapshot = useSnapshot(source)
648
+ const value = snapshot?.value
649
+ const revision = snapshot?.revision
650
+ const [draft, setDraft] = useState(() => toDraft(value))
651
+ const [busy, setBusy] = useState(false)
652
+ const [note, setNote] = useState(undefined)
653
+
654
+ // Re-seed from the Host whenever it publishes a new accepted section, so a
655
+ // saved write, a rejected one, or another window's change is visible.
656
+ // Re-seed the fields, but leave the note alone: a successful save publishes a
657
+ // new section, and clearing here would wipe the "saved" line a moment after
658
+ // it appeared. An edit clears the note through the field handlers instead.
659
+ useEffect(() => {
660
+ setDraft(toDraft(value))
661
+ }, [value, revision])
662
+
663
+ const writable = snapshot?.writable === true
664
+ const disabled = !writable || busy
665
+ const dirty = !sameDraft(value, draft)
666
+
667
+ const patch = (key, value) => {
668
+ setNote(undefined)
669
+ setDraft((current) => ({ ...current, [key]: value }))
670
+ }
671
+ const patchServer = (index, key, value) => (setNote(undefined), setDraft((current) => ({
672
+ ...current,
673
+ servers: current.servers.map((server, position) => (position === index ? { ...server, [key]: value } : server)),
674
+ })))
675
+ const addServer = () => (setNote(undefined), setDraft((current) => ({
676
+ ...current,
677
+ servers: [...current.servers, { name: '', host: '', user: 'root', port: 22, keyPath: '', keyText: '' }],
678
+ })))
679
+ const removeServer = (index) => (setNote(undefined), setDraft((current) => ({
680
+ ...current,
681
+ servers: current.servers.filter((_server, position) => position !== index),
682
+ })))
683
+
684
+ const save = async () => {
685
+ if (source === undefined) return
686
+ const ops = toOps(value, draft)
687
+ if (ops.length === 0) {
688
+ setNote({ ok: true, text: t('noChanges') })
689
+ return
690
+ }
691
+ setBusy(true)
692
+ setNote(undefined)
693
+ try {
694
+ const accepted = await source.mutate(ops, revision)
695
+ setNote(accepted
696
+ ? { ok: true, text: t('saved') }
697
+ : { ok: false, text: t('saveFailed') })
698
+ } catch (error) {
699
+ setNote({ ok: false, text: `${t('saveFailed')} ${String(error?.message ?? error)}` })
700
+ } finally {
701
+ setBusy(false)
702
+ }
703
+ }
704
+
705
+ // ------------------------------------------------------------- ssh config
706
+ //
707
+ // Import is deliberately two steps: the Host reads the file and offers what
708
+ // it found, and only the entries the user ticks are appended to the DRAFT.
709
+ // Nothing is written until the form is saved, so Import is undoable by
710
+ // closing the page.
711
+ const [importer, setImporter] = useState({
712
+ open: false, status: 'idle', path: '', entries: [], problems: [], error: '',
713
+ })
714
+ const [picked, setPicked] = useState({})
715
+
716
+ const openImport = useCallback(async () => {
717
+ setImporter({ open: true, status: 'loading', path: '', entries: [], problems: [], error: '' })
718
+ setPicked({})
719
+ try {
720
+ const found = await readJson(SSH_CONFIG_ROUTE)
721
+ setImporter({
722
+ open: true,
723
+ status: found?.exists === true ? 'ready' : 'missing',
724
+ path: typeof found?.path === 'string' ? found.path : '',
725
+ entries: Array.isArray(found?.entries) ? found.entries : [],
726
+ problems: Array.isArray(found?.problems) ? found.problems : [],
727
+ error: '',
728
+ })
729
+ } catch (error) {
730
+ setImporter({
731
+ open: true, status: 'failed', path: '', entries: [], problems: [],
732
+ error: String(error?.message ?? error),
733
+ })
734
+ }
735
+ }, [])
736
+
737
+ const closeImport = () => {
738
+ setImporter((current) => ({ ...current, open: false }))
739
+ setPicked({})
740
+ }
741
+
742
+ const importSelected = () => {
743
+ const merged = mergeImportedServers(draft.servers, importer.entries, picked)
744
+ if (merged.added.length > 0) {
745
+ setDraft((current) => ({ ...current, servers: merged.servers }))
746
+ setNote({ ok: true, text: t('importAdded', { count: merged.added.length }) })
747
+ }
748
+ closeImport()
749
+ }
750
+
751
+ if (snapshot === undefined) {
752
+ // No record attached yet: the Host may never serve this namespace, or it
753
+ // has not answered. Either way there is nothing to fill in, so say that
754
+ // rather than showing a spinner that can never finish.
755
+ return h('p', { className: 'dsh-ssh-compute-hint dsh-ssh-compute-error' }, t('configUnavailable'))
756
+ }
757
+ if (snapshot.status === 'loading' && value === undefined) {
758
+ return h('p', { className: 'dsh-ssh-compute-hint' }, t('configLoading'))
759
+ }
760
+ if (snapshot.status === 'unavailable') {
761
+ return h('p', { className: 'dsh-ssh-compute-hint dsh-ssh-compute-error' }, t('configUnavailable'))
762
+ }
763
+
764
+ const serverCards = draft.servers.map((server, index) => {
765
+ const title = server.name.trim() === '' ? `${t('fieldName')} ${index + 1}` : server.name.trim()
766
+ const fields = SERVER_FIELDS.map((field) => h(Field, {
767
+ key: field.key,
768
+ label: t(field.label),
769
+ hint: field.hint === undefined ? undefined : t(field.hint),
770
+ value: server[field.key],
771
+ number: field.number === true,
772
+ multiline: field.multiline === true,
773
+ wide: field.multiline === true || field.wide === true,
774
+ disabled,
775
+ onChange: (value) => patchServer(
776
+ index,
777
+ field.key,
778
+ field.number === true ? (value === '' ? '' : Number(value)) : value,
779
+ ),
780
+ }))
781
+ const head = h('div', { className: 'dsh-ssh-server-head' },
782
+ h('span', { className: 'dsh-ssh-server-name' }, title),
783
+ h('button', {
784
+ type: 'button',
785
+ className: 'dsh-ssh-link',
786
+ disabled,
787
+ onClick: () => removeServer(index),
788
+ }, t('removeServer')))
789
+ const grid = h('div', { className: 'dsh-ssh-grid' }, fields)
790
+ return h('div', { className: 'dsh-ssh-server', key: index }, head, grid)
791
+ })
792
+
793
+ const importPanel = importer.open
794
+ ? h('div', { className: 'dsh-ssh-import' },
795
+ h('div', { className: 'dsh-ssh-server-head' },
796
+ h('span', { className: 'dsh-ssh-server-name' }, t('importTitle')),
797
+ h('button', { type: 'button', className: 'dsh-ssh-link', onClick: closeImport }, t('importCancel'))),
798
+ h('p', { className: 'dsh-ssh-field-hint' },
799
+ importer.path === '' ? t('importHint') : `${t('importHint')} ${importer.path}`),
800
+ importer.status === 'loading'
801
+ ? h('p', { className: 'dsh-ssh-compute-hint' }, t('importLoading'))
802
+ : null,
803
+ importer.status === 'missing'
804
+ ? h('p', { className: 'dsh-ssh-compute-hint dsh-ssh-compute-error' }, t('importMissing'))
805
+ : null,
806
+ importer.status === 'failed'
807
+ ? h('p', { className: 'dsh-ssh-compute-hint dsh-ssh-compute-error' }, `${t('importFailed')} ${importer.error}`)
808
+ : null,
809
+ importer.status === 'ready' && importer.entries.length === 0
810
+ ? h('p', { className: 'dsh-ssh-compute-hint' }, t('importEmpty'))
811
+ : null,
812
+ importer.status === 'ready' && importer.entries.length > 0
813
+ ? h('div', { className: 'dsh-ssh-import-list' }, importer.entries.map((entry) => {
814
+ const name = String(entry.name ?? entry.alias ?? '').trim()
815
+ const exists = name !== ''
816
+ && draft.servers.some((server) => server.name.trim().toLowerCase() === name.toLowerCase())
817
+ const unsupported = Array.isArray(entry.unsupported) ? entry.unsupported : []
818
+ const badName = entry.nameOk === false
819
+ const blocked = exists || badName || unsupported.length > 0
820
+ return h('label', {
821
+ key: entry.alias,
822
+ className: blocked ? 'dsh-ssh-import-row dsh-ssh-import-blocked' : 'dsh-ssh-import-row',
823
+ },
824
+ h('input', {
825
+ type: 'checkbox',
826
+ checked: picked[entry.alias] === true,
827
+ disabled: blocked,
828
+ onChange: (event) => setPicked((current) => ({ ...current, [entry.alias]: event.target.checked })),
829
+ }),
830
+ h('span', { className: 'dsh-ssh-import-body' },
831
+ h('span', { className: 'dsh-ssh-import-alias' },
832
+ entry.alias,
833
+ exists ? h('span', { className: 'dsh-ssh-import-tag' }, t('importAlready')) : null,
834
+ !exists && (badName || unsupported.length > 0)
835
+ ? h('span', { className: 'dsh-ssh-import-tag' }, t('importUnsupported'))
836
+ : null),
837
+ h('span', { className: 'dsh-ssh-compute-target' }, `${entry.user}@${entry.host}:${entry.port}`),
838
+ entry.keyPath ? h('span', { className: 'dsh-ssh-compute-key' }, entry.keyPath) : null,
839
+ entry.extraArgs ? h('span', { className: 'dsh-ssh-compute-key' }, `ssh ${entry.extraArgs}`) : null,
840
+ !exists && badName
841
+ ? h('span', { className: 'dsh-ssh-compute-key dsh-ssh-compute-error' }, t('importBadName'))
842
+ : null,
843
+ !exists && !badName && unsupported.length > 0
844
+ ? h('span', { className: 'dsh-ssh-compute-key dsh-ssh-compute-error' },
845
+ t('importUnsupportedHint', { detail: unsupported.join(', ') }))
846
+ : null,
847
+ Array.isArray(entry.notes) && entry.notes.length > 0
848
+ ? h('span', { className: 'dsh-ssh-compute-key' }, entry.notes.join('; '))
849
+ : null))
850
+ }))
851
+ : null,
852
+ importer.problems.length > 0
853
+ ? h('p', { className: 'dsh-ssh-compute-hint' }, importer.problems.join('; '))
854
+ : null,
855
+ importer.status === 'ready' && importer.entries.length > 0
856
+ ? h('div', { className: 'dsh-ssh-actions' },
857
+ h('button', {
858
+ type: 'button',
859
+ className: 'dsh-ssh-primary',
860
+ disabled,
861
+ onClick: importSelected,
862
+ }, t('importConfirm')),
863
+ h('button', { type: 'button', className: 'dsh-ssh-compute-button', onClick: closeImport }, t('importCancel')))
864
+ : null)
865
+ : null
866
+
867
+ const serversGroup = h('div', { className: 'dsh-ssh-group' },
868
+ h('h4', { className: 'dsh-ssh-group-title' }, t('sectionServers')),
869
+ h('p', { className: 'dsh-ssh-group-hint' }, t('sectionServersHint')),
870
+ draft.servers.length === 0
871
+ ? h('p', { className: 'dsh-ssh-compute-hint' }, t('emptyServers'))
872
+ : h('div', null, serverCards),
873
+ h('div', { className: 'dsh-ssh-actions' },
874
+ h('button', {
875
+ type: 'button',
876
+ className: 'dsh-ssh-compute-button',
877
+ disabled,
878
+ onClick: addServer,
879
+ }, t('addServer')),
880
+ h('button', {
881
+ type: 'button',
882
+ className: 'dsh-ssh-compute-button',
883
+ disabled: disabled || importer.status === 'loading',
884
+ onClick: () => { void openImport() },
885
+ }, t('importButton'))),
886
+ importPanel)
887
+
888
+ const defaultsGroup = h('div', { className: 'dsh-ssh-group' },
889
+ h('h4', { className: 'dsh-ssh-group-title' }, t('sectionDefaults')),
890
+ h('p', { className: 'dsh-ssh-group-hint' }, t('sectionDefaultsHint')),
891
+ h('div', { className: 'dsh-ssh-grid' },
892
+ h(Field, {
893
+ label: t('fieldRemoteRoot'),
894
+ value: draft.remoteRoot,
895
+ disabled,
896
+ onChange: (value) => patch('remoteRoot', value),
897
+ }),
898
+ BOOLEAN_FIELDS.map((key) => h('label', {
899
+ key,
900
+ className: 'dsh-ssh-check',
901
+ style: { alignSelf: 'end', paddingBottom: '6px' },
902
+ },
903
+ h('input', {
904
+ type: 'checkbox',
905
+ checked: draft[key] !== false,
906
+ disabled,
907
+ onChange: (event) => patch(key, event.target.checked),
908
+ }),
909
+ h('span', null, t(`field${key.charAt(0).toUpperCase()}${key.slice(1)}`)))),
910
+ NUMBER_FIELDS.map((key) => h(Field, {
911
+ key,
912
+ label: t(`field${key.charAt(0).toUpperCase()}${key.slice(1)}`),
913
+ value: draft[key],
914
+ number: true,
915
+ disabled,
916
+ onChange: (value) => patch(key, value === '' ? '' : Number(value)),
917
+ }))),
918
+ h('p', { className: 'dsh-ssh-compute-hint' }, t('hintGuard')))
919
+
920
+ return h('div', { className: 'dsh-ssh-form' },
921
+ !writable
922
+ ? h('p', { className: 'dsh-ssh-compute-hint dsh-ssh-compute-error' }, t('configReadOnly'))
923
+ : null,
924
+ serversGroup,
925
+ defaultsGroup,
926
+ h('div', { className: 'dsh-ssh-actions' },
927
+ h('button', {
928
+ type: 'button',
929
+ className: 'dsh-ssh-primary',
930
+ disabled: disabled || !dirty,
931
+ onClick: () => { void save() },
932
+ }, busy ? t('saving') : t('save')),
933
+ h('button', {
934
+ type: 'button',
935
+ className: 'dsh-ssh-compute-button',
936
+ disabled: disabled || !dirty,
937
+ onClick: () => { setDraft(toDraft(value)) },
938
+ }, t('discard')),
939
+ note === undefined ? null : h('span', {
940
+ className: note.ok ? 'dsh-ssh-note dsh-ssh-compute-ok' : 'dsh-ssh-note dsh-ssh-compute-error',
941
+ role: 'status',
942
+ }, note.text),
943
+ dirty && note === undefined ? h('span', { className: 'dsh-ssh-dirty' }, t('dirty')) : null))
944
+ }
945
+
946
+ /**
947
+ * The configuration entry. `summary` is the row's one-liner; `page` is the
948
+ * form, and only a page render carries `form`.
949
+ */
950
+ function ConfigEntry(props) {
951
+ const t = translator(props.t)
952
+ const pageForm = props.form
953
+ const recordSource = props.source
954
+ const pageSource = useMemo(() => (pageForm === undefined ? undefined : sourceFromProp(pageForm)), [pageForm])
955
+ const source = pageSource ?? recordSource
956
+ const snapshot = useSnapshot(source)
957
+
958
+ if (props.view === 'summary') {
959
+ const value = snapshot?.value
960
+ if (value === undefined) return t('summaryUnknown')
961
+ const count = Array.isArray(value.servers) ? value.servers.length : 0
962
+ const root = typeof value.remoteRoot === 'string' && value.remoteRoot !== ''
963
+ ? value.remoteRoot
964
+ : '~/dsh-compute'
965
+ return count === 0 ? t('summaryNone') : `${count} ${t('summaryServers')} · ${root}`
966
+ }
967
+ return h(ConfigPage, { source, t })
968
+ }
969
+
970
+ return {
971
+ inject: ['slots', 'locale'],
972
+ // Pure helpers exposed for the offline tests only; the module loader reads
973
+ // `inject` and `apply` and ignores everything else.
974
+ __test: { mergeImportedServers, canonicalServers, toDraft, toOps, sameDraft },
975
+ apply(ctx) {
976
+ ctx.effect(() => ctx.locale.register(LOCALE_NAMESPACE, { en, zh }), 'dsh-ssh-compute: locale')
977
+
978
+ ctx.effect(() => {
979
+ const style = document.createElement('style')
980
+ style.dataset.dshSshCompute = 'true'
981
+ style.textContent = CSS
982
+ document.head.append(style)
983
+ return () => style.remove()
984
+ }, 'dsh-ssh-compute: styles')
985
+
986
+ // The configuration source. The bundle page's slot supplies only `view`,
987
+ // so the page asks `configForms` for this row's form itself; the row page
988
+ // still passes its own `form`, which `ConfigEntry` prefers when present.
989
+ // `configForms` attaches its record ASYNCHRONOUSLY, after this plugin's
990
+ // apply and after the entry may already have rendered. A getter read during
991
+ // render would stay stale in that window and leave the page saying the
992
+ // configuration is unavailable, so the handle below is stable and notifies
993
+ // its subscribers when the record arrives or goes away.
994
+ const configState = { source: undefined, listeners: new Set() }
995
+ const setSource = (next) => {
996
+ configState.source = next
997
+ for (const listener of [...configState.listeners]) {
998
+ try {
999
+ listener()
1000
+ } catch (error) {
1001
+ console.warn('dsh-ssh-compute: a configuration subscriber failed', error)
1002
+ }
1003
+ }
1004
+ }
1005
+ const configSource = {
1006
+ read: () => (configState.source === undefined ? undefined : configState.source.read()),
1007
+ subscribe: (listener) => {
1008
+ configState.listeners.add(listener)
1009
+ return () => { configState.listeners.delete(listener) }
1010
+ },
1011
+ mutate: (ops, revision) => (configState.source === undefined
1012
+ ? Promise.resolve(false)
1013
+ : configState.source.mutate(ops, revision)),
1014
+ }
1015
+ ctx.inject(['configForms'], (inner) => {
1016
+ const configForms = inner.configForms
1017
+ if (configForms === undefined || configForms === null || typeof configForms.get !== 'function') return
1018
+ // A row's namespace is its id; a composed entry may also appear with the
1019
+ // include prefix, so whichever the Host really serves is the one read.
1020
+ const namespaces = [ROW_ID, `include:${ROW_ID}`]
1021
+ const attach = (served) => {
1022
+ const namespace = namespaces.find((candidate) => served.has(candidate)) ?? ROW_ID
1023
+ setSource(sourceFromRecord(configForms.get(namespace)))
1024
+ return () => setSource(undefined)
1025
+ }
1026
+ if (typeof configForms.whileServed === 'function') {
1027
+ const dispose = configForms.whileServed(namespaces, attach)
1028
+ inner.effect(() => dispose, 'dsh-ssh-compute: configuration form')
1029
+ return
1030
+ }
1031
+ attach(new Set([ROW_ID]))
1032
+ })
1033
+
1034
+ // The settings form. Keyed by `<package name>#<row id>`, which is how the
1035
+ // Plugins page addresses one row's configuration and offers its configure
1036
+ // control; the bundle page reads the same form under the package name.
1037
+ ctx.slots.inject('plugins.row.config', () => ctx.slots.register({
1038
+ name: 'plugins.row.config',
1039
+ key: `${PACKAGE}#${ROW_ID}`,
1040
+ locale: LOCALE_NAMESPACE,
1041
+ }, (props) => h(ConfigEntry, { ...props, source: configSource })))
1042
+
1043
+ ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
1044
+ name: 'plugins.bundle.config',
1045
+ key: PACKAGE,
1046
+ locale: LOCALE_NAMESPACE,
1047
+ }, (props) => h(ConfigEntry, { ...props, source: configSource })))
1048
+
1049
+ ctx.slots.inject('plugins.detail.section', () => ctx.slots.register({
1050
+ name: 'plugins.detail.section',
1051
+ id: 'dsh-ssh-compute.servers',
1052
+ order: 60,
1053
+ locale: LOCALE_NAMESPACE,
1054
+ }, (props) => h(ComputeSection, { ...props, source: configSource })))
1055
+ },
1056
+ }
1057
+ },
1058
+ })