@milabench/bujang 0.1.9 → 0.1.11

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,584 @@
1
+ import React, { useEffect, useMemo, useState } from 'react';
2
+ import { Badge, Box, Button, Code, Grid, HStack, Heading, Link, NativeSelect, Spinner, Table, Text, VStack } from '@chakra-ui/react';
3
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
4
+ import { Link as RouterLink, useLocation, useNavigate } from 'react-router-dom';
5
+ import {
6
+ LuArrowLeft,
7
+ LuArrowRight,
8
+ LuBot,
9
+ LuBrush,
10
+ LuCalendarClock,
11
+ LuCheck,
12
+ LuFlag,
13
+ LuFolder,
14
+ LuKeyRound,
15
+ LuList,
16
+ LuPlug,
17
+ LuRocket,
18
+ LuSend,
19
+ LuTerminal,
20
+ LuWorkflow,
21
+ } from 'react-icons/lu';
22
+ import {
23
+ getAgentSessions,
24
+ getSettings,
25
+ getSlurmClusters,
26
+ getSlurmJobStatusSimple,
27
+ getSlurmPersistedJobs,
28
+ getSlurmProfiles,
29
+ getSlurmTemplateContent,
30
+ getSshConnections,
31
+ getSshSettings,
32
+ submitSlurmJob,
33
+ } from '../api';
34
+ import type { SlurmCluster } from '../api';
35
+ import type { AgentSession, ApiError, PersitedJobInfo, SettingsInfo, SlurmJobSubmitResponse, SshConnections, SshSettings } from '../types';
36
+ import { LinkableCard, Steps } from '../components/LinkableCard';
37
+ import { MasterBadge, SSH_CONNECTIONS_KEY, SshConnectDialog, isConnected, useSshConnectGate } from '../components/SshConnectDialog';
38
+ import { McpHelp } from './AgentActivityView';
39
+ import { FoldersCard, SecretsCard, SETTINGS_KEY, SshCard } from './SettingsView';
40
+ import { useBujangPaths } from '../context';
41
+ import { usePageTitle } from '../hooks/usePageTitle';
42
+ import { toaster } from '../toast';
43
+
44
+ const errorMessage = (error: unknown) => (error as ApiError)?.message || String(error);
45
+
46
+ const inputStyle = {
47
+ bg: 'var(--color-input-bg)',
48
+ borderColor: 'var(--color-input-border)',
49
+ color: 'var(--color-text)',
50
+ } as const;
51
+
52
+ /** The steps the user went past with Next (the steps bujang cannot check by itself) */
53
+ const SEEN_KEY = 'bujang-setup-seen';
54
+
55
+ function loadSeen(): string[] {
56
+ try {
57
+ const parsed = JSON.parse(localStorage.getItem(SEEN_KEY) || '[]');
58
+ return Array.isArray(parsed) ? parsed : [];
59
+ } catch {
60
+ return [];
61
+ }
62
+ }
63
+
64
+ function saveSeen(seen: string[]): void {
65
+ try {
66
+ localStorage.setItem(SEEN_KEY, JSON.stringify(seen));
67
+ } catch {
68
+ // storage unavailable: the checkmarks last for this page only
69
+ }
70
+ }
71
+
72
+ type StepId = 'welcome' | 'folders' | 'ssh' | 'connect' | 'first-job' | 'secrets' | 'mcp' | 'next';
73
+
74
+ interface StepDef {
75
+ id: StepId;
76
+ label: string;
77
+ icon: React.ReactNode;
78
+ optional?: boolean;
79
+ }
80
+
81
+ /** The steps, in order; their ids are the URL hashes (/setup#ssh) and match the Settings card ids */
82
+ const STEPS: StepDef[] = [
83
+ { id: 'welcome', label: 'Welcome', icon: <LuRocket /> },
84
+ { id: 'folders', label: 'Folders', icon: <LuFolder /> },
85
+ { id: 'ssh', label: 'SSH config', icon: <LuTerminal /> },
86
+ { id: 'connect', label: 'Connect', icon: <LuPlug /> },
87
+ { id: 'first-job', label: 'First job', icon: <LuSend /> },
88
+ { id: 'secrets', label: 'Secrets', icon: <LuKeyRound />, optional: true },
89
+ { id: 'mcp', label: 'Agents (MCP)', icon: <LuBot />, optional: true },
90
+ { id: 'next', label: 'Next steps', icon: <LuFlag /> },
91
+ ];
92
+
93
+ const isStep = (id: string): id is StepId => STEPS.some(s => s.id === id);
94
+
95
+ // ─── Steps without a Settings card ──────────────────────────────────
96
+
97
+ const WelcomeStep: React.FC<{ info: SettingsInfo }> = ({ info }) => {
98
+ const g = info.general;
99
+ return (
100
+ <LinkableCard id="welcome" icon={<LuRocket />} title="Welcome to bujang">
101
+ <Text fontSize="sm" color="var(--color-text)">
102
+ bujang submits your jobs to Slurm clusters over ssh, keeps a copy of each job folder on this
103
+ machine (logs, outputs) and lets agents run jobs through its MCP endpoint. This guide walks
104
+ through the setup, one step at a time; each step can be skipped and done later from Settings.
105
+ </Text>
106
+ <Steps
107
+ steps={[
108
+ { title: 'Folders', body: 'where the jobs are kept, here and on the clusters' },
109
+ { title: 'SSH config', body: 'the ssh entries of the clusters, written into your ssh config' },
110
+ { title: 'Connect', body: 'log in once (two-factor prompts included): bujang reuses the connection' },
111
+ { title: 'First job', body: 'submit a hello world job and watch it come back' },
112
+ { title: 'Secrets and agents (optional)', body: 'values for your scripts, an agent connected over MCP' },
113
+ ]}
114
+ />
115
+ <Box fontSize="sm" color="var(--color-text-muted)">
116
+ {g.clusters.length > 0 ? (
117
+ <>Clusters configured: {g.clusters.map(c => <Badge key={c} mr={1} variant="subtle">{c}</Badge>)}</>
118
+ ) : (
119
+ <>No cluster is configured yet: a plugin or <Code fontSize="xs">bujang init</Code> adds them.</>
120
+ )}
121
+ </Box>
122
+ {!info.writable && (
123
+ <Text fontSize="sm" color="var(--color-status-pending)">
124
+ This server is read-only ({info.read_only_reason || 'settings cannot be edited here'}): the steps show
125
+ what is set, the changes go through <Code fontSize="xs">bujang init</Code> / <Code fontSize="xs">bujang ssh</Code>.
126
+ </Text>
127
+ )}
128
+ </LinkableCard>
129
+ );
130
+ };
131
+
132
+ const ConnectStep: React.FC<{ connections?: SshConnections; isLoading: boolean }> = ({ connections, isLoading }) => {
133
+ const [cluster, setCluster] = useState<string | null>(null);
134
+ const [open, setOpen] = useState(false);
135
+ const queryClient = useQueryClient();
136
+ const logins = (connections?.hosts || []).filter(h => h.login_node);
137
+
138
+ const connect = (name: string | null) => { setCluster(name); setOpen(true); };
139
+
140
+ return (
141
+ <LinkableCard
142
+ id="connect"
143
+ icon={<LuPlug />}
144
+ title="Connect to the clusters"
145
+ subtitle="bujang opens one shared ssh connection per cluster (ControlMaster) and runs every ssh, rsync and squeue through it."
146
+ >
147
+ <Steps
148
+ steps={[
149
+ { title: 'Connect', body: 'Click Connect next to a cluster: ssh starts on the server.' },
150
+ {
151
+ title: 'Answer the prompts',
152
+ body: 'A two-factor passcode, a password or a new host key: they show up in the dialog, answer them there.',
153
+ },
154
+ { title: 'Done', body: 'The connection stays open: the jobs of that cluster sync without asking again.' },
155
+ ]}
156
+ />
157
+ {isLoading && <Spinner />}
158
+ {connections && !connections.writable && (
159
+ <Text fontSize="sm" color="var(--color-text-muted)">
160
+ {connections.read_only_reason || 'Logins cannot be started from this server'}: run{' '}
161
+ <Code fontSize="xs">ssh &lt;host&gt;</Code> once in a terminal instead.
162
+ </Text>
163
+ )}
164
+ {connections && logins.length === 0 && (
165
+ <Text fontSize="sm" color="var(--color-text-muted)">No cluster to connect to (only local clusters).</Text>
166
+ )}
167
+ {logins.length > 0 && (
168
+ <Table.Root size="sm" variant="outline">
169
+ <Table.Header>
170
+ <Table.Row>
171
+ <Table.ColumnHeader>Cluster</Table.ColumnHeader>
172
+ <Table.ColumnHeader>Host</Table.ColumnHeader>
173
+ <Table.ColumnHeader>State</Table.ColumnHeader>
174
+ <Table.ColumnHeader />
175
+ </Table.Row>
176
+ </Table.Header>
177
+ <Table.Body>
178
+ {logins.map(h => (
179
+ <Table.Row key={h.host}>
180
+ <Table.Cell fontWeight="semibold">{h.cluster}</Table.Cell>
181
+ <Table.Cell fontFamily="mono" fontSize="xs">{h.host}</Table.Cell>
182
+ <Table.Cell><MasterBadge connection={h} /></Table.Cell>
183
+ <Table.Cell textAlign="end">
184
+ {!isConnected(h) && connections?.writable && (
185
+ <Button size="xs" colorPalette="blue" onClick={() => connect(h.cluster)}>
186
+ <LuPlug /> Connect
187
+ </Button>
188
+ )}
189
+ </Table.Cell>
190
+ </Table.Row>
191
+ ))}
192
+ </Table.Body>
193
+ </Table.Root>
194
+ )}
195
+ <SshConnectDialog
196
+ open={open}
197
+ cluster={cluster}
198
+ purpose="reconnect"
199
+ onClose={() => { setOpen(false); setCluster(null); }}
200
+ onConnected={() => {
201
+ setOpen(false);
202
+ setCluster(null);
203
+ queryClient.invalidateQueries({ queryKey: SSH_CONNECTIONS_KEY });
204
+ }}
205
+ />
206
+ </LinkableCard>
207
+ );
208
+ };
209
+
210
+ const FIRST_TEMPLATE = 'hello_world.sh';
211
+ const DONE_STATES = ['COMPLETED', 'FAILED', 'CANCELLED', 'TIMEOUT', 'OUT_OF_MEMORY', 'NODE_FAIL'];
212
+
213
+ const FirstJobStep: React.FC<{ info: SettingsInfo; jobCount?: number }> = ({ info, jobCount }) => {
214
+ const paths = useBujangPaths();
215
+ const queryClient = useQueryClient();
216
+ const [cluster, setCluster] = useState('');
217
+ const [profile, setProfile] = useState('');
218
+ const [submitted, setSubmitted] = useState<SlurmJobSubmitResponse | null>(null);
219
+
220
+ const { data: clusters } = useQuery<SlurmCluster[]>({ queryKey: ['slurm-clusters'], queryFn: getSlurmClusters, staleTime: 600000 });
221
+ const { data: profiles } = useQuery({
222
+ queryKey: ['slurm-profiles'],
223
+ queryFn: getSlurmProfiles,
224
+ staleTime: 300000,
225
+ select: (ps) => ps.filter(p => p.executor !== 'ssh'),
226
+ });
227
+ const { data: script, error: scriptError } = useQuery({
228
+ queryKey: ['slurm-template', FIRST_TEMPLATE],
229
+ queryFn: () => getSlurmTemplateContent(FIRST_TEMPLATE),
230
+ staleTime: 600000,
231
+ retry: false,
232
+ });
233
+
234
+ useEffect(() => {
235
+ if (!cluster && clusters?.length) {
236
+ setCluster(info.general.default_cluster && clusters.some(c => c.name === info.general.default_cluster)
237
+ ? info.general.default_cluster
238
+ : clusters[0].name);
239
+ }
240
+ }, [clusters, cluster, info.general.default_cluster]);
241
+
242
+ // the profiles of this cluster, and those of no cluster in particular
243
+ const choices = useMemo(() => (profiles || []).filter(p => !p.cluster || p.cluster === cluster), [profiles, cluster]);
244
+ useEffect(() => {
245
+ if (profile && !choices.some(p => p.name === profile)) setProfile('');
246
+ }, [choices, profile]);
247
+
248
+ const gate = useSshConnectGate();
249
+ const submit = useMutation({
250
+ mutationFn: submitSlurmJob,
251
+ onSuccess: (out) => {
252
+ setSubmitted(out);
253
+ queryClient.invalidateQueries({ queryKey: ['slurm-jobs'] });
254
+ queryClient.invalidateQueries({ queryKey: ['slurm-persisted-jobs'] });
255
+ },
256
+ onError: (error) => toaster.create({ title: 'Submission failed', description: errorMessage(error), type: 'error', closable: true }),
257
+ });
258
+
259
+ const { data: status } = useQuery({
260
+ queryKey: ['setup-first-job', submitted?.jr_job_id, submitted?.job_id],
261
+ queryFn: () => getSlurmJobStatusSimple(submitted!.jr_job_id!, String(submitted!.job_id)),
262
+ enabled: !!submitted?.jr_job_id && !!submitted?.job_id,
263
+ refetchInterval: (q) => (q.state.data && DONE_STATES.some(s => q.state.data!.status.toUpperCase().startsWith(s)) ? false : 5000),
264
+ });
265
+
266
+ const go = () => {
267
+ const sbatch_args = choices.find(p => p.name === profile)?.sbatch_args || [];
268
+ const request = { script: script || '', job_name: 'hello-world', cluster, sbatch_args };
269
+ gate.ensure(cluster, () => submit.mutate(request));
270
+ };
271
+
272
+ const submitPage = `${paths.submitJob()}?${new URLSearchParams({ cluster, template: FIRST_TEMPLATE, ...(profile ? { profile } : {}) })}`;
273
+
274
+ return (
275
+ <LinkableCard
276
+ id="first-job"
277
+ icon={<LuSend />}
278
+ title="Submit a first job"
279
+ subtitle={<>The built-in <Code fontSize="xs">{FIRST_TEMPLATE}</Code>: one core for five minutes, writes <Code fontSize="xs">output/hello.txt</Code>.</>}
280
+ >
281
+ <Text fontSize="sm" color="var(--color-text)">
282
+ Pick a cluster and, if it needs an account or a partition, a profile that sets them. bujang uploads the
283
+ script to the cluster, runs <Code fontSize="xs">sbatch</Code>, then brings the job folder back here.
284
+ </Text>
285
+ <HStack gap={3} wrap="wrap" align="end">
286
+ <Box>
287
+ <Text fontSize="xs" color="var(--color-text-muted)" mb={1}>Cluster</Text>
288
+ <NativeSelect.Root size="sm" w="200px">
289
+ <NativeSelect.Field {...inputStyle} value={cluster} onChange={(e) => setCluster(e.target.value)}>
290
+ {(clusters || []).map(c => <option key={c.name} value={c.name}>{c.name}</option>)}
291
+ </NativeSelect.Field>
292
+ <NativeSelect.Indicator />
293
+ </NativeSelect.Root>
294
+ </Box>
295
+ <Box>
296
+ <Text fontSize="xs" color="var(--color-text-muted)" mb={1}>Profile</Text>
297
+ <NativeSelect.Root size="sm" w="240px">
298
+ <NativeSelect.Field {...inputStyle} value={profile} onChange={(e) => setProfile(e.target.value)}>
299
+ <option value="">none (the script's #SBATCH lines)</option>
300
+ {choices.map(p => <option key={p.name} value={p.name}>{p.name}</option>)}
301
+ </NativeSelect.Field>
302
+ <NativeSelect.Indicator />
303
+ </NativeSelect.Root>
304
+ </Box>
305
+ <Button size="sm" colorPalette="blue" disabled={!cluster || !script} loading={submit.isPending} onClick={go}>
306
+ <LuSend /> Submit
307
+ </Button>
308
+ <Link asChild fontSize="sm" color="var(--color-link, var(--color-primary))">
309
+ <RouterLink to={submitPage}>or open it in the submit page</RouterLink>
310
+ </Link>
311
+ </HStack>
312
+ {clusters && clusters.length === 0 && (
313
+ <Text fontSize="sm" color="var(--color-status-pending)">
314
+ No cluster is configured: add one with a plugin or <Code fontSize="xs">bujang init</Code>, then come back.
315
+ </Text>
316
+ )}
317
+ {scriptError && (
318
+ <Text fontSize="sm" color="var(--color-status-failed)">
319
+ Cannot load {FIRST_TEMPLATE}: {errorMessage(scriptError)}
320
+ </Text>
321
+ )}
322
+ {submitted && (
323
+ <Box borderWidth="1px" borderColor="var(--color-border)" borderRadius="md" p={3}>
324
+ {submitted.success === false || submitted.error ? (
325
+ <Text fontSize="sm" color="var(--color-status-failed)">{submitted.error || submitted.message || 'The submission failed.'}</Text>
326
+ ) : (
327
+ <HStack gap={3} wrap="wrap" fontSize="sm">
328
+ <Text color="var(--color-text)">Submitted: Slurm job <Code fontSize="xs">{submitted.job_id}</Code></Text>
329
+ {status ? <Badge colorPalette={status.status.toUpperCase().startsWith('COMPLETED') ? 'green' : 'blue'}>{status.status}</Badge> : <Spinner size="xs" />}
330
+ {submitted.jr_job_id && (
331
+ <Link asChild color="var(--color-link, var(--color-primary))">
332
+ <RouterLink to={paths.jobDetails(submitted.job_id || 0, submitted.jr_job_id)}>open the job</RouterLink>
333
+ </Link>
334
+ )}
335
+ </HStack>
336
+ )}
337
+ </Box>
338
+ )}
339
+ {!submitted && jobCount !== undefined && jobCount > 0 && (
340
+ <Text fontSize="sm" color="var(--color-text-muted)">
341
+ You already have {jobCount} job{jobCount > 1 ? 's' : ''}: this step is done, submit another one if you like.
342
+ </Text>
343
+ )}
344
+ {gate.dialog}
345
+ </LinkableCard>
346
+ );
347
+ };
348
+
349
+ const McpStep: React.FC<{ sessions?: AgentSession[] }> = ({ sessions }) => {
350
+ const paths = useBujangPaths();
351
+ return (
352
+ <LinkableCard
353
+ id="mcp"
354
+ icon={<LuBot />}
355
+ title="Connect an agent (MCP)"
356
+ subtitle="Agents (Claude Code, other MCP clients) list, submit and watch jobs through the MCP endpoint of this server."
357
+ >
358
+ <Steps
359
+ steps={[
360
+ { title: 'Add the server to your agent', body: 'Run the command below (Claude Code), or give the URL to your MCP client.' },
361
+ { title: 'Name the agent', body: <>Change <Code fontSize="xs">my-agent</Code>: the name shows on the jobs it submits.</> },
362
+ { title: 'Ask it something', body: '"list my bujang jobs": its first call shows up below.' },
363
+ ]}
364
+ />
365
+ <McpHelp />
366
+ {sessions && sessions.length > 0 ? (
367
+ <HStack gap={2} fontSize="sm" wrap="wrap">
368
+ <Badge colorPalette="green">connected</Badge>
369
+ <Text color="var(--color-text)">
370
+ {sessions.length} agent session{sessions.length > 1 ? 's' : ''}, last: <b>{sessions[0].agent}</b>.
371
+ </Text>
372
+ <Link asChild color="var(--color-link, var(--color-primary))">
373
+ <RouterLink to={paths.agent()}>Agent Activity</RouterLink>
374
+ </Link>
375
+ </HStack>
376
+ ) : (
377
+ <HStack gap={2} fontSize="sm" color="var(--color-text-muted)">
378
+ <Spinner size="xs" />
379
+ <Text>Waiting for the first call of an agent…</Text>
380
+ </HStack>
381
+ )}
382
+ </LinkableCard>
383
+ );
384
+ };
385
+
386
+ const NextStep: React.FC = () => {
387
+ const paths = useBujangPaths();
388
+ const links: { to: string; icon: React.ReactNode; label: string; body: string }[] = [
389
+ { to: paths.jobs(), icon: <LuList />, label: 'Jobs', body: 'every job, its logs, outputs and state' },
390
+ { to: paths.submitJob(), icon: <LuSend />, label: 'Submit Job', body: 'scripts, profiles, attachments, script arguments' },
391
+ { to: paths.pipelines(), icon: <LuWorkflow />, label: 'Pipelines', body: 'chain jobs: one step uses the outputs of the previous' },
392
+ { to: paths.scheduled(), icon: <LuCalendarClock />, label: 'Scheduled Jobs', body: 'run a script on a cron schedule' },
393
+ { to: paths.janitor(), icon: <LuBrush />, label: 'Janitor', body: 'background syncs, cleanups, the archive' },
394
+ ];
395
+ return (
396
+ <LinkableCard id="next" icon={<LuFlag />} title="You are set up">
397
+ <Text fontSize="sm" color="var(--color-text)">Everything here stays editable in Settings. Where to go from here:</Text>
398
+ <Grid templateColumns={{ base: '1fr', md: 'repeat(2, minmax(0, 1fr))' }} gap={3}>
399
+ {links.map(l => (
400
+ <RouterLink key={l.label} to={l.to}>
401
+ <Box borderWidth="1px" borderColor="var(--color-border)" borderRadius="md" p={3} _hover={{ bg: 'var(--color-bg-hover)' }} h="100%">
402
+ <HStack gap={2} color="var(--color-text)" fontWeight="semibold" fontSize="sm">{l.icon}<Text>{l.label}</Text></HStack>
403
+ <Text fontSize="xs" color="var(--color-text-muted)" mt={1}>{l.body}</Text>
404
+ </Box>
405
+ </RouterLink>
406
+ ))}
407
+ </Grid>
408
+ </LinkableCard>
409
+ );
410
+ };
411
+
412
+ // ─── Step list ──────────────────────────────────────────────────────
413
+
414
+ const StepList: React.FC<{ current: StepId; done: Record<StepId, boolean>; onSelect: (id: StepId) => void }> = ({ current, done, onSelect }) => (
415
+ <VStack as="ol" align="stretch" gap={1} listStyleType="none" m={0} p={0}>
416
+ {STEPS.map((step, i) => {
417
+ const active = step.id === current;
418
+ return (
419
+ <li key={step.id}>
420
+ <HStack
421
+ as="button"
422
+ w="100%"
423
+ gap={3}
424
+ px={3}
425
+ py={2}
426
+ borderRadius="md"
427
+ textAlign="left"
428
+ bg={active ? 'var(--color-bg-hover)' : 'transparent'}
429
+ _hover={{ bg: 'var(--color-bg-hover)' }}
430
+ onClick={() => onSelect(step.id)}
431
+ aria-current={active ? 'step' : undefined}
432
+ >
433
+ <Box
434
+ flexShrink={0}
435
+ w="22px"
436
+ h="22px"
437
+ borderRadius="full"
438
+ fontSize="xs"
439
+ fontWeight="bold"
440
+ display="flex"
441
+ alignItems="center"
442
+ justifyContent="center"
443
+ bg={done[step.id] ? 'var(--color-status-running)' : active ? 'var(--color-primary)' : 'transparent'}
444
+ color={done[step.id] || active ? 'white' : 'var(--color-text-muted)'}
445
+ borderWidth={done[step.id] || active ? 0 : '1px'}
446
+ borderColor="var(--color-border)"
447
+ >
448
+ {done[step.id] ? <LuCheck /> : i + 1}
449
+ </Box>
450
+ <Box minW={0}>
451
+ <Text fontSize="sm" fontWeight={active ? 'semibold' : 'normal'} color={active ? 'var(--color-primary)' : 'var(--color-text)'} truncate>
452
+ {step.label}
453
+ </Text>
454
+ {step.optional && <Text fontSize="2xs" color="var(--color-text-muted)">optional</Text>}
455
+ </Box>
456
+ </HStack>
457
+ </li>
458
+ );
459
+ })}
460
+ </VStack>
461
+ );
462
+
463
+ // ─── Page ───────────────────────────────────────────────────────────
464
+
465
+ /**
466
+ * First-time setup, one step at a time: folders, the ssh config of the clusters, a login, a first job,
467
+ * secrets, an agent over MCP. Each step reuses the Settings card of the same id; the step list checks
468
+ * what bujang can see by itself (ssh entries installed, a connection open, a job, an agent session).
469
+ */
470
+ export const SetupView: React.FC = () => {
471
+ usePageTitle('Setup');
472
+ const location = useLocation();
473
+ const navigate = useNavigate();
474
+ const hash = decodeURIComponent(location.hash.slice(1));
475
+ const current: StepId = isStep(hash) ? hash : 'welcome';
476
+ const index = STEPS.findIndex(s => s.id === current);
477
+ const [seen, setSeen] = useState<string[]>(loadSeen);
478
+
479
+ const { data: info, isLoading, error } = useQuery<SettingsInfo>({ queryKey: SETTINGS_KEY, queryFn: getSettings });
480
+ // same key as the SSH card with the default file: installing there updates the checkmark here
481
+ const { data: ssh } = useQuery<SshSettings>({ queryKey: ['bujang-settings-ssh', ''], queryFn: () => getSshSettings(undefined) });
482
+ const { data: connections, isLoading: connectionsLoading } = useQuery<SshConnections>({
483
+ queryKey: SSH_CONNECTIONS_KEY,
484
+ queryFn: () => getSshConnections(),
485
+ refetchInterval: current === 'connect' ? 10000 : 60000,
486
+ refetchOnWindowFocus: false,
487
+ retry: false,
488
+ });
489
+ const { data: jobs } = useQuery<PersitedJobInfo[]>({
490
+ queryKey: ['slurm-persisted-jobs'],
491
+ queryFn: getSlurmPersistedJobs,
492
+ staleTime: 30000,
493
+ refetchOnWindowFocus: false,
494
+ });
495
+ const { data: sessions } = useQuery<AgentSession[]>({
496
+ queryKey: ['agent-sessions'],
497
+ queryFn: getAgentSessions,
498
+ refetchInterval: current === 'mcp' ? 5000 : false,
499
+ retry: false,
500
+ });
501
+
502
+ const logins = (connections?.hosts || []).filter(h => h.login_node);
503
+ const done: Record<StepId, boolean> = {
504
+ welcome: seen.includes('welcome'),
505
+ folders: seen.includes('folders') || !!info?.user_file.exists,
506
+ ssh: !!ssh && ssh.plugins.length > 0 && ssh.plugins.every(p => p.installed && p.up_to_date !== false),
507
+ connect: logins.length > 0 && logins.some(isConnected),
508
+ 'first-job': (jobs?.length ?? 0) > 0,
509
+ secrets: seen.includes('secrets'),
510
+ mcp: (sessions?.length ?? 0) > 0,
511
+ next: false,
512
+ };
513
+
514
+ const goTo = (id: StepId) => navigate({ pathname: location.pathname, hash: id === 'welcome' ? '' : id });
515
+ const next = () => {
516
+ if (!seen.includes(current)) {
517
+ const updated = [...seen, current];
518
+ setSeen(updated);
519
+ saveSeen(updated);
520
+ }
521
+ if (index < STEPS.length - 1) goTo(STEPS[index + 1].id);
522
+ };
523
+ const restart = () => { setSeen([]); saveSeen([]); goTo('welcome'); };
524
+
525
+ // a new step starts at the top of the page
526
+ useEffect(() => { document.querySelector('main')?.scrollTo({ top: 0 }); }, [current]);
527
+
528
+ const doneCount = STEPS.filter(s => s.id !== 'next' && done[s.id]).length;
529
+
530
+ const content = info && (() => {
531
+ switch (current) {
532
+ case 'welcome': return <WelcomeStep info={info} />;
533
+ case 'folders': return <FoldersCard info={info} />;
534
+ case 'ssh': return <SshCard info={info} />;
535
+ case 'connect': return <ConnectStep connections={connections} isLoading={connectionsLoading} />;
536
+ case 'first-job': return <FirstJobStep info={info} jobCount={jobs?.length} />;
537
+ case 'secrets': return <SecretsCard writable={info.writable} />;
538
+ case 'mcp': return <McpStep sessions={sessions} />;
539
+ case 'next': return <NextStep />;
540
+ }
541
+ })();
542
+
543
+ return (
544
+ <Box p={6} maxW="1200px">
545
+ <HStack mb={2} gap={3} color="var(--color-text)">
546
+ <LuRocket size={24} />
547
+ <Heading size="lg">Setup</Heading>
548
+ <Badge variant="subtle" colorPalette={doneCount === STEPS.length - 1 ? 'green' : 'gray'}>
549
+ {doneCount} / {STEPS.length - 1} done
550
+ </Badge>
551
+ </HStack>
552
+ <Text mb={6} color="var(--color-text-muted)">
553
+ A guided first setup. Come back any time: the checkmarks follow what is actually configured.
554
+ </Text>
555
+ {isLoading && <Spinner />}
556
+ {error && <Text color="var(--color-status-failed)">{errorMessage(error)}</Text>}
557
+ {info && (
558
+ <Grid templateColumns={{ base: '1fr', md: '200px minmax(0, 1fr)' }} gap={6} alignItems="start">
559
+ <Box position={{ md: 'sticky' }} top={{ md: 4 }}>
560
+ <StepList current={current} done={done} onSelect={goTo} />
561
+ <Button size="xs" variant="ghost" mt={3} color="var(--color-text-muted)" onClick={restart}>
562
+ Start over
563
+ </Button>
564
+ </Box>
565
+ <VStack align="stretch" gap={4} minW={0}>
566
+ {content}
567
+ <HStack justify="space-between">
568
+ <Button size="sm" variant="outline" disabled={index === 0} onClick={() => goTo(STEPS[index - 1].id)}>
569
+ <LuArrowLeft /> Back
570
+ </Button>
571
+ {index < STEPS.length - 1 && (
572
+ <Button size="sm" colorPalette="blue" onClick={next}>
573
+ {STEPS[index].optional && !done[current] ? 'Skip' : 'Next'} <LuArrowRight />
574
+ </Button>
575
+ )}
576
+ </HStack>
577
+ </VStack>
578
+ </Grid>
579
+ )}
580
+ </Box>
581
+ );
582
+ };
583
+
584
+ export default SetupView;