@milabench/bujang 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,910 @@
1
+ import React, { useEffect, useMemo, useState } from 'react';
2
+ import {
3
+ Box,
4
+ VStack,
5
+ HStack,
6
+ Heading,
7
+ Text,
8
+ Button,
9
+ Badge,
10
+ Table,
11
+ Spinner,
12
+ Card,
13
+ Grid,
14
+ Code,
15
+ Input,
16
+ Field,
17
+ NativeSelect,
18
+ Checkbox,
19
+ Alert,
20
+ } from '@chakra-ui/react';
21
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
22
+ import {
23
+ LuDatabase,
24
+ LuFolder,
25
+ LuInfo,
26
+ LuKeyRound,
27
+ LuLock,
28
+ LuPlugZap,
29
+ LuSettings,
30
+ LuTerminal,
31
+ LuTrash2,
32
+ } from 'react-icons/lu';
33
+ import {
34
+ deleteSlurmSecret,
35
+ getSettings,
36
+ getSettingsSecrets,
37
+ getSshSettings,
38
+ installSshConfig,
39
+ planSshConfig,
40
+ removeSshConfig,
41
+ setSlurmSecret,
42
+ testSshConnections,
43
+ updateSettings,
44
+ } from '../api';
45
+ import type {
46
+ ApiError,
47
+ SettingsField,
48
+ SettingsInfo,
49
+ SettingsOrigin,
50
+ SettingsSecrets,
51
+ SshCheckResult,
52
+ SshPlan,
53
+ SshPluginStatus,
54
+ SshSettings,
55
+ SshTestResponse,
56
+ } from '../types';
57
+ import { toaster } from '../toast';
58
+ import { Tooltip } from '../components/tooltip';
59
+ import { usePageTitle } from '../hooks/usePageTitle';
60
+
61
+ const SETTINGS_KEY = ['bujang-settings'];
62
+
63
+ const inputStyle = {
64
+ bg: 'var(--color-input-bg)',
65
+ borderColor: 'var(--color-input-border)',
66
+ color: 'var(--color-text)',
67
+ } as const;
68
+
69
+ const errorMessage = (error: unknown) => (error as ApiError)?.message || String(error);
70
+
71
+ const fail = (title: string) => (error: unknown) =>
72
+ toaster.create({ title, description: errorMessage(error), type: 'error', closable: true });
73
+
74
+ // ─── Layout pieces ──────────────────────────────────────────────────
75
+
76
+ const Section: React.FC<{
77
+ icon: React.ReactNode;
78
+ title: string;
79
+ subtitle?: React.ReactNode;
80
+ actions?: React.ReactNode;
81
+ children: React.ReactNode;
82
+ }> = ({ icon, title, subtitle, actions, children }) => (
83
+ <Card.Root bg="var(--color-bg-card)" border="1px solid" borderColor="var(--color-border)">
84
+ <Card.Header pb={2}>
85
+ <HStack justify="space-between" align="start" gap={4} wrap="wrap">
86
+ <VStack align="start" gap={1}>
87
+ <HStack gap={2} color="var(--color-text)">
88
+ {icon}
89
+ <Heading size="md">{title}</Heading>
90
+ </HStack>
91
+ {subtitle && <Text fontSize="sm" color="var(--color-text-muted)">{subtitle}</Text>}
92
+ </VStack>
93
+ {actions}
94
+ </HStack>
95
+ </Card.Header>
96
+ <Card.Body pt={2}>
97
+ <VStack align="stretch" gap={4}>{children}</VStack>
98
+ </Card.Body>
99
+ </Card.Root>
100
+ );
101
+
102
+ /** Label / value rows */
103
+ const KV: React.FC<{ rows: [string, React.ReactNode][] }> = ({ rows }) => (
104
+ <Grid templateColumns={{ base: '1fr', md: '200px 1fr' }} columnGap={4} rowGap={2}>
105
+ {rows.map(([label, value]) => (
106
+ <React.Fragment key={label}>
107
+ <Text fontSize="sm" fontWeight="semibold" color="var(--color-text-muted)">{label}</Text>
108
+ <Box fontSize="sm" color="var(--color-text)" minW={0} wordBreak="break-all">{value}</Box>
109
+ </React.Fragment>
110
+ ))}
111
+ </Grid>
112
+ );
113
+
114
+ const Mono: React.FC<{ children: React.ReactNode }> = ({ children }) => (
115
+ <Code fontSize="xs" bg="var(--color-bg-stripe)" color="var(--color-text)" wordBreak="break-all">{children}</Code>
116
+ );
117
+
118
+ const SubHeading: React.FC<{ children: React.ReactNode }> = ({ children }) => (
119
+ <Text fontSize="sm" fontWeight="semibold" color="var(--color-text)">{children}</Text>
120
+ );
121
+
122
+ function originLabel(origin: SettingsOrigin): string {
123
+ switch (origin.kind) {
124
+ case 'env': return `env ${origin.name}`;
125
+ case 'default': return 'default';
126
+ case 'code': return 'set in code';
127
+ case 'workdir': return 'workdir';
128
+ case 'plugin': return `plugin ${origin.name}`;
129
+ case 'explicit': return 'host config';
130
+ case 'defaults': return 'built-in';
131
+ default: return `${origin.kind} ${origin.name}`;
132
+ }
133
+ }
134
+
135
+ const OriginBadge: React.FC<{ origin: SettingsOrigin }> = ({ origin }) => {
136
+ const palette = origin.kind === 'env' ? 'orange' : origin.kind === 'plugin' ? 'purple' : origin.kind === 'user' ? 'blue' : 'gray';
137
+ const badge = <Badge size="sm" colorPalette={palette} variant="subtle">{originLabel(origin)}</Badge>;
138
+ return origin.path ? <Tooltip content={origin.path} showArrow>{badge}</Tooltip> : badge;
139
+ };
140
+
141
+ /** Badges of an editable field: origin, env override, restart needed */
142
+ const FieldBadges: React.FC<{ field: SettingsField; fileLabel?: string }> = ({ field }) => (
143
+ <HStack gap={1} wrap="wrap">
144
+ <OriginBadge origin={field.origin} />
145
+ {field.env && (
146
+ <Tooltip content={`${field.env} is set: it wins over the user file`} showArrow>
147
+ <Badge size="sm" colorPalette="orange">{field.env} overrides the file</Badge>
148
+ </Tooltip>
149
+ )}
150
+ {field.restart && <Badge size="sm" variant="outline">applies at startup</Badge>}
151
+ {field.pending && <Badge size="sm" colorPalette="yellow">restart needed</Badge>}
152
+ </HStack>
153
+ );
154
+
155
+ const ReadOnlyNote: React.FC<{ reason: string | null }> = ({ reason }) => (
156
+ <Alert.Root status="info" variant="subtle" borderRadius="md">
157
+ <Alert.Indicator><LuLock /></Alert.Indicator>
158
+ <Alert.Content>
159
+ <Alert.Title>Read-only</Alert.Title>
160
+ <Alert.Description fontSize="sm">
161
+ {reason || 'This server does not allow editing the settings.'} The values below are what the server
162
+ uses; change them with <Code fontSize="xs">bujang init</Code>, <Code fontSize="xs">bujang ssh</Code> or
163
+ in the host's configuration.
164
+ </Alert.Description>
165
+ </Alert.Content>
166
+ </Alert.Root>
167
+ );
168
+
169
+ // ─── General ────────────────────────────────────────────────────────
170
+
171
+ const GeneralCard: React.FC<{ info: SettingsInfo }> = ({ info }) => {
172
+ const g = info.general;
173
+ const mcp = g.mcp;
174
+ let mcpText: React.ReactNode;
175
+ if (mcp.mounted) mcpText = <Mono>{`${window.location.origin}${mcp.path || '/mcp'}`}</Mono>;
176
+ else if (mcp.url) mcpText = <Mono>{mcp.url}</Mono>;
177
+ else if (mcp.disabled) mcpText = <Text>off (<Mono>--no-mcp</Mono>)</Text>;
178
+ else mcpText = <Text color="var(--color-text-muted)">not served by this app</Text>;
179
+ return (
180
+ <Section icon={<LuInfo />} title="General">
181
+ <KV
182
+ rows={[
183
+ ['bujang version', <Mono key="v">{g.version}</Mono>],
184
+ [
185
+ 'Plugins',
186
+ g.plugins.length ? (
187
+ <HStack gap={1} wrap="wrap">
188
+ {g.plugins.map(p => (
189
+ <Badge key={p.name} colorPalette="purple" variant="subtle">
190
+ {p.name}{p.version ? ` ${p.version}` : ''}{p.ssh_config ? ' · ssh config' : ''}
191
+ </Badge>
192
+ ))}
193
+ </HStack>
194
+ ) : <Text color="var(--color-text-muted)">none</Text>,
195
+ ],
196
+ ['Default cluster', g.default_cluster ? <Mono>{g.default_cluster}</Mono> : '—'],
197
+ ['Clusters', g.clusters.length ? g.clusters.join(', ') : '—'],
198
+ ['MCP endpoint', mcpText],
199
+ [
200
+ 'Server',
201
+ g.server.standalone
202
+ ? <Text>bujang serve, listening on <Mono>{g.server.host || '?'}</Mono></Text>
203
+ : <Text color="var(--color-text-muted)">embedded in the host app</Text>,
204
+ ],
205
+ ]}
206
+ />
207
+ </Section>
208
+ );
209
+ };
210
+
211
+ // ─── Folders ────────────────────────────────────────────────────────
212
+
213
+ const FoldersCard: React.FC<{ info: SettingsInfo }> = ({ info }) => {
214
+ const queryClient = useQueryClient();
215
+ const { local_cache, workdir } = info.fields;
216
+ const initial = useMemo(
217
+ () => ({ local_cache: local_cache.file ?? local_cache.value ?? '', workdir: workdir.file ?? workdir.value ?? '' }),
218
+ [local_cache, workdir],
219
+ );
220
+ const [values, setValues] = useState(initial);
221
+ useEffect(() => setValues(initial), [initial]);
222
+
223
+ const save = useMutation({
224
+ mutationFn: () => {
225
+ const changed: Record<string, string> = {};
226
+ if (values.local_cache !== initial.local_cache) changed.local_cache = values.local_cache;
227
+ if (values.workdir !== initial.workdir) changed.workdir = values.workdir;
228
+ return updateSettings(changed);
229
+ },
230
+ onSuccess: (out) => {
231
+ queryClient.setQueryData(SETTINGS_KEY, out.settings);
232
+ const notes = [
233
+ out.applied.length ? `applied now: ${out.applied.join(', ')}` : '',
234
+ out.restart.length ? `restart the server for: ${out.restart.join(', ')}` : '',
235
+ ].filter(Boolean);
236
+ toaster.create({ title: `Saved to ${out.written?.path ?? 'the user file'}`, description: notes.join('; '), type: 'success' });
237
+ },
238
+ onError: fail('Could not save the folders'),
239
+ });
240
+
241
+ const editable = info.writable && !!info.user_file.path;
242
+ const dirty = values.local_cache !== initial.local_cache || values.workdir !== initial.workdir;
243
+
244
+ const row = (key: 'local_cache' | 'workdir', label: string, help: string) => {
245
+ const field = info.fields[key];
246
+ return (
247
+ <Field.Root>
248
+ <HStack justify="space-between" w="100%" wrap="wrap" gap={2}>
249
+ <Field.Label mb={0} color="var(--color-text)">{label}</Field.Label>
250
+ <FieldBadges field={field} />
251
+ </HStack>
252
+ <Input
253
+ {...inputStyle}
254
+ size="sm"
255
+ fontFamily="mono"
256
+ value={values[key]}
257
+ disabled={!editable}
258
+ onChange={(e) => setValues(v => ({ ...v, [key]: e.target.value }))}
259
+ />
260
+ <Field.HelperText color="var(--color-text-muted)">
261
+ {help}
262
+ {field.file !== null && field.file !== field.value && (
263
+ <> Running with <Mono>{field.value}</Mono>.</>
264
+ )}
265
+ {field.overridden && field.origin.kind !== 'env' && (
266
+ <> The user file has no effect: {originLabel(field.origin)} sets it.</>
267
+ )}
268
+ </Field.HelperText>
269
+ </Field.Root>
270
+ );
271
+ };
272
+
273
+ return (
274
+ <Section
275
+ icon={<LuFolder />}
276
+ title="Folders"
277
+ subtitle={<>Saved to the user file, like <Code fontSize="xs">bujang init</Code>.</>}
278
+ >
279
+ {row('local_cache', 'Job folder (local_cache)', 'Where the jobs are mirrored on this machine (logs, outputs, database, secrets).')}
280
+ {row('workdir', 'Default remote workdir (workdir)', 'Job folders on the clusters that do not set their own remote_folder.')}
281
+ {editable && (
282
+ <HStack>
283
+ <Button size="sm" colorPalette="blue" disabled={!dirty} loading={save.isPending} onClick={() => save.mutate()}>
284
+ Save
285
+ </Button>
286
+ <Button size="sm" variant="ghost" disabled={!dirty} onClick={() => setValues(initial)}>Reset</Button>
287
+ </HStack>
288
+ )}
289
+
290
+ <KV
291
+ rows={[
292
+ [
293
+ 'User config file',
294
+ info.user_file.path
295
+ ? <HStack gap={2} wrap="wrap"><Mono>{info.user_file.path}</Mono>{!info.user_file.exists && <Badge size="sm">not created yet</Badge>}</HStack>
296
+ : <Text color="var(--color-text-muted)">turned off (user_config_dir is empty)</Text>,
297
+ ],
298
+ ['Secrets file', <Mono key="s">{info.secrets_file}</Mono>],
299
+ ]}
300
+ />
301
+ {info.user_file.error && <Text fontSize="sm" color="var(--color-status-failed)">{info.user_file.error}</Text>}
302
+
303
+ <Box>
304
+ <SubHeading>Remote folder of each cluster</SubHeading>
305
+ <Table.Root size="sm" variant="outline" mt={2}>
306
+ <Table.Header>
307
+ <Table.Row>
308
+ <Table.ColumnHeader>Cluster</Table.ColumnHeader>
309
+ <Table.ColumnHeader>ssh alias</Table.ColumnHeader>
310
+ <Table.ColumnHeader>remote_folder</Table.ColumnHeader>
311
+ <Table.ColumnHeader>From</Table.ColumnHeader>
312
+ </Table.Row>
313
+ </Table.Header>
314
+ <Table.Body>
315
+ {info.clusters.map(c => (
316
+ <Table.Row key={c.name}>
317
+ <Table.Cell fontWeight="semibold">{c.name}</Table.Cell>
318
+ <Table.Cell fontFamily="mono" fontSize="xs">{c.ssh}</Table.Cell>
319
+ <Table.Cell fontFamily="mono" fontSize="xs">{c.remote_folder}</Table.Cell>
320
+ <Table.Cell><OriginBadge origin={c.origin} /></Table.Cell>
321
+ </Table.Row>
322
+ ))}
323
+ </Table.Body>
324
+ </Table.Root>
325
+ </Box>
326
+
327
+ <Box>
328
+ <SubHeading>Config sources (merge order, later wins)</SubHeading>
329
+ <VStack align="stretch" gap={1} mt={2}>
330
+ {info.sources.sources.map((s, i) => (
331
+ <HStack key={`${s.name}-${i}`} gap={2} fontSize="sm" minW={0}>
332
+ <Badge size="sm" variant="subtle" colorPalette={s.kind === 'plugin' ? 'purple' : s.kind === 'user' ? 'blue' : 'gray'}>
333
+ {s.kind}
334
+ </Badge>
335
+ <Text color="var(--color-text)" flexShrink={0}>{s.name}</Text>
336
+ {s.path && <Text fontFamily="mono" fontSize="xs" color="var(--color-text-muted)" truncate>{s.path}</Text>}
337
+ </HStack>
338
+ ))}
339
+ </VStack>
340
+ </Box>
341
+ </Section>
342
+ );
343
+ };
344
+
345
+ // ─── Database ───────────────────────────────────────────────────────
346
+
347
+ const DatabaseCard: React.FC<{ info: SettingsInfo }> = ({ info }) => {
348
+ const queryClient = useQueryClient();
349
+ const db = info.database;
350
+ const field = info.fields.database_url;
351
+ const initial = field.file ?? '';
352
+ const [url, setUrl] = useState(initial);
353
+ useEffect(() => setUrl(initial), [initial]);
354
+
355
+ const save = useMutation({
356
+ mutationFn: (value: string | null) => updateSettings({ database_url: value }),
357
+ onSuccess: (out) => {
358
+ queryClient.setQueryData(SETTINGS_KEY, out.settings);
359
+ toaster.create({
360
+ title: 'Database URL saved',
361
+ description: out.restart.length ? 'Restart the server to use it.' : 'It is overridden: see the badges.',
362
+ type: 'success',
363
+ });
364
+ },
365
+ onError: fail('Could not save the database URL'),
366
+ });
367
+
368
+ const editable = info.writable && db.editable && field.editable;
369
+ const backend = db.backend === 'sqlite'
370
+ ? <Text>sqlite, file <Mono>{db.sqlite_path || ':memory:'}</Mono></Text>
371
+ : db.backend
372
+ ? <Text>{db.backend}{db.host ? <> on <Mono>{db.host}</Mono></> : null}{db.name ? <>, database <Mono>{db.name}</Mono></> : null}</Text>
373
+ : '—';
374
+
375
+ return (
376
+ <Section
377
+ icon={<LuDatabase />}
378
+ title="Database"
379
+ subtitle="Scheduled jobs and their runs. Job folders do not depend on it."
380
+ >
381
+ <KV
382
+ rows={[
383
+ ['URL', db.url ? <Mono>{db.url}</Mono> : <Text color="var(--color-text-muted)">no database (scheduled jobs off)</Text>],
384
+ ['Backend', backend],
385
+ [
386
+ 'Provided by',
387
+ db.host_provided
388
+ ? <HStack gap={2}><Badge colorPalette="purple">host app</Badge><Text fontSize="sm" color="var(--color-text-muted)">passed in code ({db.kind}), not editable</Text></HStack>
389
+ : <FieldBadges field={field} />,
390
+ ],
391
+ ]}
392
+ />
393
+ {db.error && <Text fontSize="sm" color="var(--color-status-failed)">{db.error}</Text>}
394
+ {db.tables.length > 0 && (
395
+ <Table.Root size="sm" variant="outline" maxW="480px">
396
+ <Table.Header>
397
+ <Table.Row>
398
+ <Table.ColumnHeader>Table</Table.ColumnHeader>
399
+ <Table.ColumnHeader textAlign="end">Rows</Table.ColumnHeader>
400
+ </Table.Row>
401
+ </Table.Header>
402
+ <Table.Body>
403
+ {db.tables.map(t => (
404
+ <Table.Row key={t.name}>
405
+ <Table.Cell fontFamily="mono" fontSize="xs">{t.name}</Table.Cell>
406
+ <Table.Cell textAlign="end">{t.exists ? t.rows ?? '?' : <Badge size="sm">not created</Badge>}</Table.Cell>
407
+ </Table.Row>
408
+ ))}
409
+ </Table.Body>
410
+ </Table.Root>
411
+ )}
412
+ {!db.host_provided && (
413
+ <Field.Root>
414
+ <Field.Label color="var(--color-text)">database_url in the user file</Field.Label>
415
+ <HStack w="100%">
416
+ <Input
417
+ {...inputStyle}
418
+ size="sm"
419
+ fontFamily="mono"
420
+ placeholder="empty: sqlite in the job folder"
421
+ value={url}
422
+ disabled={!editable}
423
+ onChange={(e) => setUrl(e.target.value)}
424
+ />
425
+ {editable && (
426
+ <>
427
+ <Button size="sm" colorPalette="blue" disabled={url === initial} loading={save.isPending}
428
+ onClick={() => save.mutate(url.trim() ? url : null)}>
429
+ Save
430
+ </Button>
431
+ {initial && (
432
+ <Button size="sm" variant="outline" loading={save.isPending} onClick={() => save.mutate(null)}>
433
+ Use the default
434
+ </Button>
435
+ )}
436
+ </>
437
+ )}
438
+ </HStack>
439
+ <Field.HelperText color="var(--color-text-muted)">
440
+ Read at startup: restart the server after a change. The password is never shown (***).
441
+ </Field.HelperText>
442
+ </Field.Root>
443
+ )}
444
+ </Section>
445
+ );
446
+ };
447
+
448
+ // ─── SSH ────────────────────────────────────────────────────────────
449
+
450
+ const DiffView: React.FC<{ diff: string }> = ({ diff }) => (
451
+ <Box
452
+ as="pre"
453
+ fontFamily="mono"
454
+ fontSize="xs"
455
+ p={3}
456
+ borderWidth="1px"
457
+ borderColor="var(--color-border)"
458
+ borderRadius="md"
459
+ bg="var(--color-log-stdout-bg)"
460
+ color="var(--color-log-stdout-text)"
461
+ maxH="420px"
462
+ overflow="auto"
463
+ whiteSpace="pre"
464
+ >
465
+ {diff.split('\n').map((line, i) => {
466
+ const color = line.startsWith('+++') || line.startsWith('---')
467
+ ? 'var(--color-text-muted)'
468
+ : line.startsWith('+') ? 'var(--color-status-running)'
469
+ : line.startsWith('-') ? 'var(--color-status-failed)'
470
+ : line.startsWith('@@') ? 'var(--color-primary)'
471
+ : undefined;
472
+ return <Box as="span" key={i} display="block" color={color}>{line || ' '}</Box>;
473
+ })}
474
+ </Box>
475
+ );
476
+
477
+ const PluginBlock: React.FC<{
478
+ plugin: SshPluginStatus;
479
+ file: string;
480
+ writable: boolean;
481
+ onChanged: () => void;
482
+ }> = ({ plugin, file, writable, onChanged }) => {
483
+ const [values, setValues] = useState<Record<string, string>>(plugin.values);
484
+ const [dedupe, setDedupe] = useState(false);
485
+ const [plan, setPlan] = useState<SshPlan | null>(null);
486
+ useEffect(() => { setValues(plugin.values); setPlan(null); }, [plugin, file]);
487
+
488
+ const request = (action: 'install' | 'remove') => ({
489
+ file,
490
+ plugins: [plugin.name],
491
+ ...(action === 'install' ? { values, dedupe } : {}),
492
+ });
493
+
494
+ const preview = useMutation({
495
+ mutationFn: (action: 'install' | 'remove') => planSshConfig({ ...request(action), action }),
496
+ onSuccess: setPlan,
497
+ onError: fail('Preview failed'),
498
+ });
499
+ const apply = useMutation({
500
+ mutationFn: (p: SshPlan) =>
501
+ (p.action === 'install' ? installSshConfig : removeSshConfig)({ ...request(p.action), base: p.base }),
502
+ onSuccess: (out) => {
503
+ setPlan(null);
504
+ onChanged();
505
+ toaster.create({
506
+ title: out.written ? `${out.action === 'install' ? 'Installed' : 'Removed'} bujang:${plugin.name}` : 'Nothing to change',
507
+ description: [out.backup ? `backup: ${out.backup}` : '', ...(out.alias_failures || []).map(f => `ssh -G ${f}`)].filter(Boolean).join('\n'),
508
+ type: out.alias_failures?.length ? 'warning' : 'success',
509
+ closable: true,
510
+ });
511
+ },
512
+ onError: fail('Could not write the ssh config'),
513
+ });
514
+
515
+ const missing = plugin.placeholders.filter(p => !values[p]?.trim());
516
+ const status = plugin.installed
517
+ ? plugin.up_to_date
518
+ ? <Badge colorPalette="green">installed {plugin.installed_version}</Badge>
519
+ : <Badge colorPalette="yellow">installed {plugin.installed_version}, update available</Badge>
520
+ : <Badge>not installed</Badge>;
521
+
522
+ return (
523
+ <Box borderWidth="1px" borderColor="var(--color-border)" borderRadius="md" p={4}>
524
+ <VStack align="stretch" gap={3}>
525
+ <HStack justify="space-between" wrap="wrap" gap={2}>
526
+ <HStack gap={2}>
527
+ <Text fontWeight="semibold" color="var(--color-text)">{plugin.name}</Text>
528
+ {plugin.version && <Text fontSize="sm" color="var(--color-text-muted)">{plugin.version}</Text>}
529
+ {status}
530
+ {plugin.line && <Text fontSize="xs" color="var(--color-text-muted)">line {plugin.line}</Text>}
531
+ </HStack>
532
+ <Text fontSize="xs" color="var(--color-text-muted)">hosts: {plugin.aliases.join(', ') || '—'}</Text>
533
+ </HStack>
534
+
535
+ {plugin.duplicates > 0 && (
536
+ <Text fontSize="sm" color="var(--color-status-pending)">
537
+ {plugin.duplicates} more bujang:{plugin.name} block(s) in the file: dedupe removes them.
538
+ </Text>
539
+ )}
540
+ {plugin.conflicts.length > 0 && (
541
+ <Box>
542
+ <Text fontSize="sm" color="var(--color-text)">
543
+ Entries outside the block define the same hosts; ssh uses the first value it finds:
544
+ </Text>
545
+ {plugin.conflicts.map(c => (
546
+ <Text key={`${c.line}-${c.alias}`} fontSize="xs" fontFamily="mono" color="var(--color-text-muted)">
547
+ line {c.line}: {c.text}
548
+ </Text>
549
+ ))}
550
+ </Box>
551
+ )}
552
+
553
+ {plugin.placeholders.length > 0 && (
554
+ <Grid templateColumns={{ base: '1fr', md: 'repeat(2, minmax(0, 1fr))' }} gap={3}>
555
+ {plugin.placeholders.map(name => (
556
+ <Field.Root key={name}>
557
+ <Field.Label fontFamily="mono" fontSize="xs" color="var(--color-text)">{name}</Field.Label>
558
+ <Input
559
+ {...inputStyle}
560
+ size="sm"
561
+ value={values[name] ?? ''}
562
+ disabled={!writable}
563
+ placeholder="one word"
564
+ onChange={(e) => { setValues(v => ({ ...v, [name]: e.target.value.trim() })); setPlan(null); }}
565
+ />
566
+ </Field.Root>
567
+ ))}
568
+ </Grid>
569
+ )}
570
+
571
+ <HStack gap={3} wrap="wrap">
572
+ <Checkbox.Root checked={dedupe} onCheckedChange={(e) => { setDedupe(!!e.checked); setPlan(null); }}>
573
+ <Checkbox.HiddenInput />
574
+ <Checkbox.Control />
575
+ <Checkbox.Label color="var(--color-text)" fontSize="sm">
576
+ Dedupe: drop the older Host entries for these hosts
577
+ </Checkbox.Label>
578
+ </Checkbox.Root>
579
+ </HStack>
580
+
581
+ <HStack gap={2} wrap="wrap">
582
+ <Button size="sm" colorPalette="blue" variant="outline" disabled={missing.length > 0}
583
+ loading={preview.isPending && preview.variables === 'install'} onClick={() => preview.mutate('install')}>
584
+ Preview {plugin.installed ? 'update' : 'install'}
585
+ </Button>
586
+ {plugin.installed && (
587
+ <Button size="sm" colorPalette="red" variant="outline"
588
+ loading={preview.isPending && preview.variables === 'remove'} onClick={() => preview.mutate('remove')}>
589
+ Preview remove
590
+ </Button>
591
+ )}
592
+ {missing.length > 0 && (
593
+ <Text fontSize="xs" color="var(--color-text-muted)">values needed: {missing.join(', ')}</Text>
594
+ )}
595
+ </HStack>
596
+
597
+ {plan && (
598
+ <VStack align="stretch" gap={2}>
599
+ {plan.messages.map(m => <Text key={m} fontSize="sm" color="var(--color-text)">{m}</Text>)}
600
+ {plan.warnings.map(w => <Text key={w} fontSize="sm" color="var(--color-status-pending)">warning: {w}</Text>)}
601
+ {plan.changed ? <DiffView diff={plan.diff} /> : <Text fontSize="sm" color="var(--color-text-muted)">{plan.file}: up to date, nothing to write.</Text>}
602
+ <HStack gap={2}>
603
+ {plan.changed && (
604
+ <Tooltip content={writable ? `Back up ${plan.file}, then write it` : 'Read-only server'} showArrow>
605
+ <Button size="sm" colorPalette={plan.action === 'remove' ? 'red' : 'blue'} disabled={!writable}
606
+ loading={apply.isPending} onClick={() => apply.mutate(plan)}>
607
+ Apply {plan.action}
608
+ </Button>
609
+ </Tooltip>
610
+ )}
611
+ <Button size="sm" variant="ghost" onClick={() => setPlan(null)}>Cancel</Button>
612
+ {plan.changed && <Text fontSize="xs" color="var(--color-text-muted)">The file is backed up first (.bujang-&lt;date&gt;.bak).</Text>}
613
+ </HStack>
614
+ </VStack>
615
+ )}
616
+ </VStack>
617
+ </Box>
618
+ );
619
+ };
620
+
621
+ const SSH_COLORS: Record<string, string> = { ok: 'green', auth: 'orange', hostkey: 'orange', timeout: 'yellow', jump: 'orange' };
622
+
623
+ const SshResults: React.FC<{ results: SshCheckResult[] }> = ({ results }) => (
624
+ <Box overflowX="auto">
625
+ <Table.Root size="sm" variant="outline">
626
+ <Table.Header>
627
+ <Table.Row>
628
+ {['Host', 'Cluster', 'ssh', 'Master', 'Slurm', 'Workdir', 'Latency'].map(h => (
629
+ <Table.ColumnHeader key={h}>{h}</Table.ColumnHeader>
630
+ ))}
631
+ </Table.Row>
632
+ </Table.Header>
633
+ <Table.Body>
634
+ {results.map(r => (
635
+ <React.Fragment key={r.host}>
636
+ <Table.Row>
637
+ <Table.Cell fontFamily="mono" fontSize="xs">{r.host}</Table.Cell>
638
+ <Table.Cell>{r.cluster}</Table.Cell>
639
+ <Table.Cell><Badge colorPalette={SSH_COLORS[r.ssh] || 'red'}>{r.ssh}</Badge></Table.Cell>
640
+ <Table.Cell fontSize="xs">{r.master}</Table.Cell>
641
+ <Table.Cell fontSize="xs">{r.slurm}</Table.Cell>
642
+ <Table.Cell fontSize="xs">{r.workdir}</Table.Cell>
643
+ <Table.Cell fontSize="xs">{r.latency != null ? `${Math.round(r.latency * 1000)} ms` : '—'}</Table.Cell>
644
+ </Table.Row>
645
+ {(r.message || r.hints.length > 0) && (
646
+ <Table.Row>
647
+ <Table.Cell colSpan={7} pt={0} borderTopWidth={0}>
648
+ {r.message && <Text fontSize="xs" color={r.ok ? 'var(--color-text-muted)' : 'var(--color-status-failed)'}>{r.message}</Text>}
649
+ {r.hints.map(h => <Text key={h} fontSize="xs" color="var(--color-text-muted)">hint: {h}</Text>)}
650
+ </Table.Cell>
651
+ </Table.Row>
652
+ )}
653
+ </React.Fragment>
654
+ ))}
655
+ </Table.Body>
656
+ </Table.Root>
657
+ </Box>
658
+ );
659
+
660
+ const SshCard: React.FC<{ info: SettingsInfo }> = ({ info }) => {
661
+ const [fileInput, setFileInput] = useState('');
662
+ const [file, setFile] = useState('');
663
+ const [cluster, setCluster] = useState('');
664
+ const [timeout, setTimeoutValue] = useState(10);
665
+
666
+ const { data: ssh, isLoading, error, refetch } = useQuery<SshSettings>({
667
+ queryKey: ['bujang-settings-ssh', file],
668
+ queryFn: () => getSshSettings(file || undefined),
669
+ });
670
+ useEffect(() => { if (ssh && !fileInput) setFileInput(ssh.file); }, [ssh, fileInput]);
671
+
672
+ const test = useMutation<SshTestResponse>({
673
+ mutationFn: () => testSshConnections({ clusters: cluster ? [cluster] : [], timeout, file: file || undefined }),
674
+ onError: fail('The connection test failed'),
675
+ });
676
+
677
+ return (
678
+ <Section
679
+ icon={<LuTerminal />}
680
+ title="SSH"
681
+ subtitle={<>The ssh config entries the plugins ship, like <Code fontSize="xs">bujang ssh</Code>.</>}
682
+ >
683
+ <Field.Root>
684
+ <Field.Label color="var(--color-text)">ssh config file</Field.Label>
685
+ <HStack w="100%">
686
+ <Input {...inputStyle} size="sm" fontFamily="mono" value={fileInput} onChange={(e) => setFileInput(e.target.value)}
687
+ onKeyDown={(e) => { if (e.key === 'Enter') setFile(fileInput); }} />
688
+ <Button size="sm" variant="outline" onClick={() => setFile(fileInput)}>Load</Button>
689
+ {ssh && fileInput !== ssh.default_file && (
690
+ <Button size="sm" variant="ghost" onClick={() => { setFileInput(ssh.default_file); setFile(''); }}>Default</Button>
691
+ )}
692
+ </HStack>
693
+ {ssh && !ssh.exists && <Field.HelperText color="var(--color-text-muted)">The file does not exist yet: install creates it (mode 0600).</Field.HelperText>}
694
+ </Field.Root>
695
+
696
+ {isLoading && <Spinner />}
697
+ {error && <Text fontSize="sm" color="var(--color-status-failed)">{errorMessage(error)}</Text>}
698
+ {ssh?.error && <Text fontSize="sm" color="var(--color-status-failed)">{ssh.error}</Text>}
699
+ {ssh && ssh.plugins.length === 0 && (
700
+ <Text fontSize="sm" color="var(--color-text-muted)">No loaded plugin ships an ssh config.</Text>
701
+ )}
702
+ {ssh?.plugins.map(p => (
703
+ <PluginBlock key={p.name} plugin={p} file={ssh.file} writable={info.writable} onChanged={() => refetch()} />
704
+ ))}
705
+ {ssh && ssh.other_blocks.length > 0 && (
706
+ <Text fontSize="sm" color="var(--color-text-muted)">
707
+ Other bujang blocks in the file (plugins not loaded): {ssh.other_blocks.map(b => b.name).join(', ')}
708
+ </Text>
709
+ )}
710
+
711
+ <Box borderTopWidth="1px" borderColor="var(--color-border)" pt={4}>
712
+ <SubHeading>Test the connections</SubHeading>
713
+ <Text fontSize="sm" color="var(--color-text-muted)" mb={3}>
714
+ Read only and never prompts (BatchMode): on clusters with MFA, run <Code fontSize="xs">ssh &lt;alias&gt;</Code> once
715
+ in a terminal first.
716
+ </Text>
717
+ <HStack gap={2} wrap="wrap">
718
+ <NativeSelect.Root size="sm" w="200px">
719
+ <NativeSelect.Field {...inputStyle} value={cluster} onChange={(e) => setCluster(e.target.value)}>
720
+ <option value="">All clusters</option>
721
+ {info.general.clusters.map(c => <option key={c} value={c}>{c}</option>)}
722
+ </NativeSelect.Field>
723
+ <NativeSelect.Indicator />
724
+ </NativeSelect.Root>
725
+ <HStack gap={1}>
726
+ <Text fontSize="sm" color="var(--color-text-muted)">timeout</Text>
727
+ <Input {...inputStyle} size="sm" type="number" w="70px" min={1} max={60} value={timeout}
728
+ onChange={(e) => setTimeoutValue(Math.min(60, Math.max(1, Number(e.target.value) || 10)))} />
729
+ <Text fontSize="sm" color="var(--color-text-muted)">s</Text>
730
+ </HStack>
731
+ <Button size="sm" colorPalette="blue" loading={test.isPending} loadingText="Testing" onClick={() => test.mutate()}>
732
+ <LuPlugZap /> Test
733
+ </Button>
734
+ </HStack>
735
+ {test.data && (
736
+ <Box mt={3}>
737
+ <Text fontSize="sm" mb={2} color={test.data.ok ? 'var(--color-status-running)' : 'var(--color-status-failed)'}>
738
+ {test.data.ok ? 'Every host passes.' : 'Some hosts fail: see the hints.'}
739
+ </Text>
740
+ <SshResults results={test.data.results} />
741
+ </Box>
742
+ )}
743
+ </Box>
744
+ </Section>
745
+ );
746
+ };
747
+
748
+ // ─── Secrets ────────────────────────────────────────────────────────
749
+
750
+ const SECRET_NAME = /^\w+$/;
751
+
752
+ const SecretsCard: React.FC<{ writable: boolean }> = ({ writable }) => {
753
+ const queryClient = useQueryClient();
754
+ const { data, isLoading, error } = useQuery<SettingsSecrets>({
755
+ queryKey: ['bujang-settings-secrets'],
756
+ queryFn: getSettingsSecrets,
757
+ });
758
+ const [name, setName] = useState('');
759
+ const [value, setValue] = useState('');
760
+ const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
761
+ const refresh = () => queryClient.invalidateQueries({ queryKey: ['bujang-settings-secrets'] });
762
+
763
+ const save = useMutation({
764
+ mutationFn: () => setSlurmSecret(name, value),
765
+ onSuccess: () => {
766
+ toaster.create({ title: `Saved ${name}`, description: `Use it as {{ secrets.${name} }}`, type: 'success' });
767
+ setName('');
768
+ setValue('');
769
+ refresh();
770
+ },
771
+ onError: fail('Could not save the secret'),
772
+ });
773
+ const remove = useMutation({
774
+ mutationFn: (n: string) => deleteSlurmSecret(n),
775
+ onSuccess: (_, n) => { toaster.create({ title: `Deleted ${n}`, type: 'success' }); setConfirmDelete(null); refresh(); },
776
+ onError: fail('Could not delete the secret'),
777
+ });
778
+
779
+ const exists = !!data?.secrets.some(s => s.name === name);
780
+ const validName = SECRET_NAME.test(name);
781
+
782
+ return (
783
+ <Section
784
+ icon={<LuKeyRound />}
785
+ title="Secrets"
786
+ subtitle={<>Used in job scripts as <Code fontSize="xs">{'{{ secrets.NAME }}'}</Code>. Values are never shown.</>}
787
+ >
788
+ {isLoading && <Spinner />}
789
+ {error && <Text fontSize="sm" color="var(--color-status-failed)">{errorMessage(error)}</Text>}
790
+ {data && !writable && data.editable && (
791
+ <Text fontSize="sm" color="var(--color-text-muted)">
792
+ Secrets stay editable on a read-only server: they use the /secrets routes the host already serves.
793
+ </Text>
794
+ )}
795
+ {data && (
796
+ <>
797
+ <KV
798
+ rows={[
799
+ ['File', data.file ? <Mono>{data.file}</Mono> : <Text color="var(--color-text-muted)">secrets.toml (edit it by hand)</Text>],
800
+ [
801
+ 'Lookup order',
802
+ <HStack key="p" gap={1} wrap="wrap">
803
+ {data.providers.map(p => (
804
+ <Badge key={p.name} size="sm" variant={p.available ? 'subtle' : 'outline'}>{p.kind}</Badge>
805
+ ))}
806
+ </HStack>,
807
+ ],
808
+ ]}
809
+ />
810
+ {data.secrets.length === 0 ? (
811
+ <Text fontSize="sm" color="var(--color-text-muted)" fontStyle="italic">No secret yet.</Text>
812
+ ) : (
813
+ <Table.Root size="sm" variant="outline">
814
+ <Table.Header>
815
+ <Table.Row>
816
+ <Table.ColumnHeader>Name</Table.ColumnHeader>
817
+ <Table.ColumnHeader>Source</Table.ColumnHeader>
818
+ <Table.ColumnHeader />
819
+ </Table.Row>
820
+ </Table.Header>
821
+ <Table.Body>
822
+ {data.secrets.map(s => (
823
+ <Table.Row key={s.name}>
824
+ <Table.Cell fontFamily="mono" fontSize="xs">{s.name}</Table.Cell>
825
+ <Table.Cell>
826
+ <HStack gap={1}>
827
+ <Badge size="sm" variant="subtle">{s.source}</Badge>
828
+ {s.env_shadowed && (
829
+ <Tooltip content={`The environment variable ${s.name} is set: it wins over the file`} showArrow>
830
+ <Badge size="sm" colorPalette="orange">env shadows it</Badge>
831
+ </Tooltip>
832
+ )}
833
+ </HStack>
834
+ </Table.Cell>
835
+ <Table.Cell textAlign="end">
836
+ {data.editable && s.source === 'file' && (
837
+ confirmDelete === s.name ? (
838
+ <HStack gap={1} justify="end">
839
+ <Button size="xs" colorPalette="red" loading={remove.isPending} onClick={() => remove.mutate(s.name)}>Delete</Button>
840
+ <Button size="xs" variant="ghost" onClick={() => setConfirmDelete(null)}>Cancel</Button>
841
+ </HStack>
842
+ ) : (
843
+ <Button size="xs" variant="ghost" aria-label={`Delete ${s.name}`} onClick={() => setConfirmDelete(s.name)}>
844
+ <LuTrash2 />
845
+ </Button>
846
+ )
847
+ )}
848
+ </Table.Cell>
849
+ </Table.Row>
850
+ ))}
851
+ </Table.Body>
852
+ </Table.Root>
853
+ )}
854
+ {data.editable && (
855
+ <Box as="form" onSubmit={(e: React.FormEvent) => { e.preventDefault(); if (validName && value) save.mutate(); }}>
856
+ <SubHeading>Add or replace</SubHeading>
857
+ <HStack gap={2} mt={2} wrap="wrap" align="start">
858
+ <Input {...inputStyle} size="sm" w="220px" fontFamily="mono" placeholder="NAME (letters, digits, _)"
859
+ value={name} onChange={(e) => setName(e.target.value.trim())} autoComplete="off" />
860
+ <Input {...inputStyle} size="sm" w="260px" type="password" placeholder="value" value={value}
861
+ onChange={(e) => setValue(e.target.value)} autoComplete="new-password" />
862
+ <Button size="sm" colorPalette="blue" type="submit" disabled={!validName || !value} loading={save.isPending}>
863
+ {exists ? 'Replace' : 'Add'}
864
+ </Button>
865
+ </HStack>
866
+ {name && !validName && <Text fontSize="xs" mt={1} color="var(--color-status-failed)">letters, digits and _ only</Text>}
867
+ {exists && <Text fontSize="xs" mt={1} color="var(--color-text-muted)">{name} exists: its value is replaced.</Text>}
868
+ </Box>
869
+ )}
870
+ </>
871
+ )}
872
+ </Section>
873
+ );
874
+ };
875
+
876
+ // ─── Page ───────────────────────────────────────────────────────────
877
+
878
+ export const SettingsView: React.FC = () => {
879
+ usePageTitle('Settings');
880
+ const { data: info, isLoading, error } = useQuery<SettingsInfo>({ queryKey: SETTINGS_KEY, queryFn: getSettings });
881
+
882
+ return (
883
+ <Box p={6} maxW="1100px">
884
+ <HStack mb={2} gap={3} color="var(--color-text)">
885
+ <LuSettings size={24} />
886
+ <Heading size="lg">Settings</Heading>
887
+ {info && (info.writable
888
+ ? <Badge colorPalette="green" variant="subtle">editable</Badge>
889
+ : <Badge variant="outline"><LuLock /> read-only</Badge>)}
890
+ </HStack>
891
+ <Text mb={6} color="var(--color-text-muted)">
892
+ Where bujang keeps the jobs, its database, the ssh setup of the clusters and the secrets of the scripts.
893
+ </Text>
894
+ {isLoading && <Spinner />}
895
+ {error && <Text color="var(--color-status-failed)">{errorMessage(error)}</Text>}
896
+ {info && (
897
+ <VStack align="stretch" gap={6}>
898
+ {!info.writable && <ReadOnlyNote reason={info.read_only_reason} />}
899
+ <GeneralCard info={info} />
900
+ <FoldersCard info={info} />
901
+ <DatabaseCard info={info} />
902
+ <SshCard info={info} />
903
+ <SecretsCard writable={info.writable} />
904
+ </VStack>
905
+ )}
906
+ </Box>
907
+ );
908
+ };
909
+
910
+ export default SettingsView;