@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,779 @@
1
+ import React, { useEffect, useMemo, useState } from 'react';
2
+ import {
3
+ Badge,
4
+ Box,
5
+ Button,
6
+ Code,
7
+ Dialog,
8
+ Field,
9
+ Flex,
10
+ HStack,
11
+ IconButton,
12
+ Input,
13
+ NativeSelect,
14
+ Tabs,
15
+ Text,
16
+ Textarea,
17
+ VStack,
18
+ } from '@chakra-ui/react';
19
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
20
+ import { LuPlus, LuTrash2 } from 'react-icons/lu';
21
+ import { getSlurmTemplateContent, saveSlurmProfile, saveSlurmTemplate } from '../api';
22
+ import type { ApiError, PipelineNode, PipelineTemplatePayload, SlurmProfile } from '../types';
23
+ import { MonacoEditor } from '../components/MonacoEditor';
24
+ import { toaster } from '../toast';
25
+ import { groupSweepKey, sweepValue } from './PipelineGraph';
26
+
27
+ /**
28
+ * A pipeline file (`{ type: 'pipeline', name, description, definition, job_id }`); the older
29
+ * `pipelineName` / `rootNode` fields are read for template files written before the server format.
30
+ */
31
+ export interface PipelineTemplateFileData {
32
+ type?: string;
33
+ name?: string;
34
+ description?: string;
35
+ definition?: PipelineNode;
36
+ job_id?: string | null;
37
+ pipelineName?: string;
38
+ rootNode?: unknown;
39
+ }
40
+
41
+ // Profile names repeat between clusters and between the node types of a cluster (1-gpu, 4-gpu, ...):
42
+ // jobs reference "<cluster>/<node>/<name>" ("<cluster>/<name>" for profiles without a node type)
43
+ const profileKey = (profile?: SlurmProfile): string => {
44
+ if (!profile) return '';
45
+ const cluster = profile.cluster || 'mila';
46
+ return profile.node ? `${cluster}/${profile.node}/${profile.name}` : `${cluster}/${profile.name}`;
47
+ };
48
+
49
+ // A shorter key ("example-cpu", "<cluster>/<name>") is the first matching profile (the backend does the same)
50
+ const findProfile = (value: string | undefined, profiles: SlurmProfile[]): SlurmProfile | undefined => {
51
+ if (!value) return undefined;
52
+ const parts = value.split('/');
53
+ const name = parts[parts.length - 1];
54
+ const cluster = parts.length > 1 ? parts[0] : undefined;
55
+ const node = parts.length > 2 ? parts[1] : undefined;
56
+ return profiles.find((p) =>
57
+ p.name === name
58
+ && (cluster === undefined || (p.cluster || 'mila') === cluster)
59
+ && (node === undefined || p.node === node));
60
+ };
61
+
62
+ const profileLabel = (p: SlurmProfile) =>
63
+ `${p.cluster || 'mila'} / ${p.name}${p.node ? ` (${p.node})` : ''}${p.executor === 'ssh' ? ' - ssh' : ''}`;
64
+
65
+ type Path = number[];
66
+ type NodeType = PipelineNode['type'];
67
+
68
+ const samePath = (a: Path | null, b: Path) => !!a && a.length === b.length && a.every((v, i) => v === b[i]);
69
+
70
+ const nodeAt = (root: PipelineNode, path: Path): PipelineNode | undefined => {
71
+ let node: PipelineNode | undefined = root;
72
+ for (const i of path) node = node && node.type !== 'job' ? node.jobs[i] : undefined;
73
+ return node;
74
+ };
75
+
76
+ /** `root` with the node at `path` replaced by fn(node) (null removes it) */
77
+ const updateAt = (root: PipelineNode, path: Path, fn: (node: PipelineNode) => PipelineNode | null): PipelineNode => {
78
+ if (path.length === 0) return fn(root) ?? root;
79
+ if (root.type === 'job') return root;
80
+ const [head, ...rest] = path;
81
+ const jobs = root.jobs.flatMap((child, i) => {
82
+ if (i !== head) return [child];
83
+ const next = rest.length ? updateAt(child, rest, fn) : fn(child);
84
+ return next ? [next] : [];
85
+ });
86
+ return { ...root, jobs };
87
+ };
88
+
89
+ const scriptStem = (script: string) => (script.split('/').pop() || script).replace(/\.[^.]*$/, '');
90
+
91
+ const nodeName = (node: PipelineNode) => (node.type === 'job' ? (node.script ? scriptStem(node.script) : '') : node.name);
92
+
93
+ /** What is missing before saving, null when the pipeline can be saved */
94
+ const problem = (node: PipelineNode): string | null => {
95
+ if (node.type === 'job') {
96
+ if (!node.script) return 'a job has no script';
97
+ if (!node.profile) return `${scriptStem(node.script)} has no resources`;
98
+ return null;
99
+ }
100
+ if (!node.name.trim()) return `a ${node.type} group has no name`;
101
+ for (const child of node.jobs) {
102
+ const p = problem(child);
103
+ if (p) return p;
104
+ }
105
+ return null;
106
+ };
107
+
108
+ const changeType = (node: PipelineNode, type: NodeType, fallback: { script: string; profile: string }): PipelineNode => {
109
+ if (type === node.type) return node;
110
+ if (type === 'job') {
111
+ // a group becomes its first job (or a new one)
112
+ const first = node.type !== 'job' ? node.jobs.find((j) => j.type === 'job') : undefined;
113
+ return first ?? { type: 'job', script: fallback.script, profile: fallback.profile };
114
+ }
115
+ if (node.type === 'job') return { type, name: scriptStem(node.script) || type, jobs: [node] };
116
+ return { ...node, type };
117
+ };
118
+
119
+ const TYPE_LABEL: Record<NodeType, string> = { job: 'Job', sequential: 'Sequential', parallel: 'Parallel' };
120
+ const TYPE_COLOR: Record<NodeType, string> = {
121
+ job: 'var(--color-pipeline-job-border)',
122
+ sequential: 'var(--color-pipeline-seq-border)',
123
+ parallel: 'var(--color-pipeline-par-border)',
124
+ };
125
+ const INDENT = 12;
126
+
127
+ /** What the pointer is on: a node (row) or its delete button; the rows of its subtree are tinted */
128
+ type Hover = { path: Path; mode: 'row' | 'delete' } | null;
129
+ const isWithin = (path: Path, root: Path) => root.length <= path.length && root.every((v, i) => v === path[i]);
130
+ const DELETE_TINT = 'rgba(229, 62, 62, 0.16)';
131
+ const GROUP_TINT = 'rgba(49, 130, 206, 0.08)';
132
+
133
+ /** The tint of a row of the subtree at `path`: red when it is about to be deleted, light for a hovered group */
134
+ const hoverTint = (hover: Hover, path: Path, root: PipelineNode): string | undefined => {
135
+ if (!hover || !isWithin(path, hover.path)) return undefined;
136
+ if (hover.mode === 'delete') return DELETE_TINT;
137
+ return nodeAt(root, hover.path)?.type !== 'job' ? GROUP_TINT : undefined;
138
+ };
139
+
140
+ const TypeSelect: React.FC<{ value: NodeType; onChange: (t: NodeType) => void }> = ({ value, onChange }) => (
141
+ <NativeSelect.Root size="xs" w="100px" flexShrink={0} onClick={(e) => e.stopPropagation()}>
142
+ <NativeSelect.Field
143
+ value={value}
144
+ onChange={(e) => onChange(e.target.value as NodeType)}
145
+ borderColor={TYPE_COLOR[value]}
146
+ fontWeight="semibold"
147
+ fontSize="11px"
148
+ h="22px"
149
+ ps={1.5}
150
+ pe={5}
151
+ aria-label="Node type"
152
+ >
153
+ <option value="job">{TYPE_LABEL.job}</option>
154
+ <option value="sequential">{TYPE_LABEL.sequential}</option>
155
+ <option value="parallel">{TYPE_LABEL.parallel}</option>
156
+ </NativeSelect.Field>
157
+ <NativeSelect.Indicator boxSize="3" />
158
+ </NativeSelect.Root>
159
+ );
160
+
161
+ /** One node of the tree and, for a group, its children then a dummy row that adds a step at the end */
162
+ const TreeRows: React.FC<{
163
+ node: PipelineNode;
164
+ path: Path;
165
+ /** "1." for the steps of a sequential group, a dot for those of a parallel one */
166
+ marker?: string;
167
+ selected: Path | null;
168
+ onSelect: (path: Path) => void;
169
+ onType: (path: Path, type: NodeType) => void;
170
+ onDelete: (path: Path) => void;
171
+ onAdd: (path: Path) => void;
172
+ root: PipelineNode;
173
+ hover: Hover;
174
+ onHover: (hover: Hover) => void;
175
+ /** the sweep variable of the nearest parallel group above: its value names a job */
176
+ sweepKey?: string;
177
+ }> = ({ node, path, marker, selected, onSelect, onType, onDelete, onAdd, root, hover, onHover, sweepKey }) => {
178
+ const depth = path.length;
179
+ const isSelected = samePath(selected, path);
180
+ const swept = node.type === 'job' ? sweepValue(node.env, sweepKey) : undefined;
181
+ const name = swept ?? nodeName(node);
182
+ const childSweep = groupSweepKey(node) || sweepKey;
183
+ const tint = hoverTint(hover, path, root);
184
+ const deleting = hover?.mode === 'delete' && !!tint;
185
+ return (
186
+ <>
187
+ <HStack
188
+ gap={2}
189
+ h="30px"
190
+ pl={`${depth * INDENT + 2}px`}
191
+ pr={1}
192
+ cursor="pointer"
193
+ bg={tint ?? (isSelected ? 'var(--color-bg-hover)' : undefined)}
194
+ borderLeft="3px solid"
195
+ borderLeftColor={isSelected ? 'var(--color-primary)' : 'transparent'}
196
+ _hover={tint ? undefined : { bg: 'var(--color-bg-hover)' }}
197
+ onMouseEnter={() => onHover({ path, mode: 'row' })}
198
+ onClick={() => onSelect(path)}
199
+ role="treeitem"
200
+ aria-selected={isSelected}
201
+ >
202
+ {marker !== undefined && (
203
+ <Text w="16px" flexShrink={0} whiteSpace="nowrap" textAlign="right" fontSize="xs" fontFamily="mono" color="var(--color-text-muted)">
204
+ {marker}
205
+ </Text>
206
+ )}
207
+ <TypeSelect value={node.type} onChange={(t) => onType(path, t)} />
208
+ <Text
209
+ flex={1}
210
+ minW={0}
211
+ truncate
212
+ fontSize="sm"
213
+ color={name ? 'var(--color-text)' : 'var(--color-text-muted)'}
214
+ textDecoration={deleting ? 'line-through' : undefined}
215
+ >
216
+ {name || 'no script'}
217
+ {swept && node.type === 'job' && node.script && (
218
+ <Text as="span" color="var(--color-text-muted)"> · {scriptStem(node.script)}</Text>
219
+ )}
220
+ </Text>
221
+ {depth > 0 && (
222
+ <IconButton
223
+ aria-label="Remove"
224
+ title="Remove"
225
+ size="2xs"
226
+ variant="ghost"
227
+ color="var(--color-text-muted)"
228
+ _hover={{ color: 'red.500', bg: 'transparent' }}
229
+ onMouseEnter={() => onHover({ path, mode: 'delete' })}
230
+ onMouseLeave={() => onHover({ path, mode: 'row' })}
231
+ onClick={(e) => { e.stopPropagation(); onHover(null); onDelete(path); }}
232
+ >
233
+ <LuTrash2 />
234
+ </IconButton>
235
+ )}
236
+ </HStack>
237
+ {node.type !== 'job' && (
238
+ <>
239
+ {node.jobs.map((child, i) => (
240
+ <TreeRows
241
+ key={i}
242
+ node={child}
243
+ path={[...path, i]}
244
+ marker={node.type === 'sequential' ? `${i + 1}.` : '•'}
245
+ selected={selected}
246
+ onSelect={onSelect}
247
+ onType={onType}
248
+ onDelete={onDelete}
249
+ onAdd={onAdd}
250
+ root={root}
251
+ hover={hover}
252
+ onHover={onHover}
253
+ sweepKey={childSweep}
254
+ />
255
+ ))}
256
+ <Box
257
+ h="28px"
258
+ pl={`${(depth + 1) * INDENT + 2 + 3 + 16 + 8}px`}
259
+ display="flex"
260
+ alignItems="center"
261
+ bg={tint}
262
+ // the [+] adds to this group: show which one
263
+ onMouseEnter={() => onHover({ path, mode: 'row' })}
264
+ >
265
+ <IconButton
266
+ aria-label={`Add a step to ${node.name || node.type}`}
267
+ title={`Add a step to ${node.name || node.type}`}
268
+ size="2xs"
269
+ variant="outline"
270
+ borderStyle="dashed"
271
+ borderColor="var(--color-border)"
272
+ color="var(--color-text-muted)"
273
+ _hover={{ color: 'var(--color-primary)', borderColor: 'var(--color-primary)' }}
274
+ onClick={() => onAdd(path)}
275
+ >
276
+ <LuPlus />
277
+ </IconButton>
278
+ </Box>
279
+ </>
280
+ )}
281
+ </>
282
+ );
283
+ };
284
+
285
+ const PaneLabel: React.FC<{ children: React.ReactNode }> = ({ children }) => (
286
+ <Text fontSize="xs" fontWeight="semibold" textTransform="uppercase" letterSpacing="wide" color="var(--color-text-muted)">{children}</Text>
287
+ );
288
+
289
+ /** The arguments of a script: the `export NAME=value` lines of its `# ---- Arguments` section (with the
290
+ * comment above each), the same as the job submission form and the server read */
291
+ interface ScriptArgument { name: string; value: string; comment: string }
292
+
293
+ const scriptArguments = (script: string): ScriptArgument[] => {
294
+ const lines = script.split('\n');
295
+ const begin = lines.findIndex((l) => /^#\s*-+\s*Arguments\s*$/.test(l));
296
+ if (begin < 0) return [];
297
+ const out: ScriptArgument[] = [];
298
+ for (let i = begin + 1; i < lines.length; i++) {
299
+ const line = lines[i];
300
+ if (line.startsWith('# {START}')) break;
301
+ const m = /^export\s+([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
302
+ if (!m || m[2].includes('$')) continue;
303
+ let value = m[2].trim();
304
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1);
305
+ const above = lines[i - 1] ?? '';
306
+ out.push({ name: m[1], value, comment: above.startsWith('# ') && !/^#\s*-+/.test(above) ? above.slice(2) : '' });
307
+ }
308
+ return out;
309
+ };
310
+
311
+ type JobNode = Extract<PipelineNode, { type: 'job' }>;
312
+
313
+ /** Values of this step: the script's arguments (default as placeholder) and other variables, kept in its "env" */
314
+ const ArgumentsTab: React.FC<{ job: JobNode; content?: string; onChange: (job: JobNode) => void }> = ({ job, content, onChange }) => {
315
+ const args = useMemo(() => scriptArguments(content ?? ''), [content]);
316
+ const env = job.env ?? {};
317
+ const others = Object.keys(env).filter((k) => !args.some((a) => a.name === k));
318
+ const [newName, setNewName] = useState('');
319
+
320
+ const set = (name: string, value: string | null) => {
321
+ const next = { ...env };
322
+ if (value === null) delete next[name];
323
+ else next[name] = value;
324
+ const { env: _old, ...rest } = job;
325
+ void _old;
326
+ onChange(Object.keys(next).length ? { ...rest, env: next } : rest);
327
+ };
328
+
329
+ return (
330
+ <VStack align="stretch" gap={3}>
331
+ <Text fontSize="xs" color="var(--color-text-muted)">
332
+ For this step only (saved in the pipeline, as its env). Empty: the value of the script.
333
+ </Text>
334
+ {content === undefined && <Text fontSize="sm" color="var(--color-text-muted)">Loading the script...</Text>}
335
+ {content !== undefined && args.length === 0 && (
336
+ <Text fontSize="sm" color="var(--color-text-muted)">The script has no `# ---- Arguments` section.</Text>
337
+ )}
338
+ {args.map((a) => (
339
+ <Box key={a.name}>
340
+ <HStack gap={2}>
341
+ <Text w="150px" flexShrink={0} fontFamily="mono" fontSize="sm" color="var(--color-text)" truncate title={a.name}>{a.name}</Text>
342
+ <Input
343
+ size="sm"
344
+ fontFamily="mono"
345
+ value={env[a.name] ?? ''}
346
+ placeholder={a.value}
347
+ onChange={(e) => set(a.name, e.target.value === '' ? null : e.target.value)}
348
+ borderColor={env[a.name] !== undefined ? 'var(--color-primary)' : undefined}
349
+ />
350
+ </HStack>
351
+ {a.comment && <Text fontSize="xs" color="var(--color-text-muted)" pl="158px" mt={0.5}>{a.comment}</Text>}
352
+ </Box>
353
+ ))}
354
+ {others.length > 0 && <PaneLabel>Other variables (exported before the script)</PaneLabel>}
355
+ {others.map((name) => (
356
+ <HStack key={name} gap={2}>
357
+ <Text w="150px" flexShrink={0} fontFamily="mono" fontSize="sm" color="var(--color-text)" truncate title={name}>{name}</Text>
358
+ <Input size="sm" fontFamily="mono" value={env[name]} onChange={(e) => set(name, e.target.value)} />
359
+ <IconButton aria-label={`Remove ${name}`} size="xs" variant="ghost" color="var(--color-text-muted)" onClick={() => set(name, null)}>
360
+ <LuTrash2 />
361
+ </IconButton>
362
+ </HStack>
363
+ ))}
364
+ <HStack gap={2}>
365
+ <Input
366
+ size="sm"
367
+ w="150px"
368
+ fontFamily="mono"
369
+ placeholder="NEW_VARIABLE"
370
+ value={newName}
371
+ onChange={(e) => setNewName(e.target.value.toUpperCase().replace(/[^A-Z0-9_]/g, ''))}
372
+ />
373
+ <Button
374
+ size="xs"
375
+ variant="outline"
376
+ disabled={!/^[A-Z_][A-Z0-9_]*$/.test(newName) || newName in env}
377
+ onClick={() => { set(newName, ''); setNewName(''); }}
378
+ >
379
+ <LuPlus /> Variable
380
+ </Button>
381
+ </HStack>
382
+ </VStack>
383
+ );
384
+ };
385
+
386
+ /** The profile of the step: its sbatch arguments, saved in the user's profiles file (shared by every job using it) */
387
+ const ResourcesTab: React.FC<{ job: JobNode; profile?: SlurmProfile; onChange: (job: JobNode) => void }> = ({ job, profile, onChange }) => {
388
+ const queryClient = useQueryClient();
389
+ const [args, setArgs] = useState((profile?.sbatch_args ?? []).join('\n'));
390
+ const [name, setName] = useState(profile?.node ? `${profile.name}-custom` : profile?.name ?? '');
391
+ useEffect(() => {
392
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- another profile picked: start from it
393
+ setArgs((profile?.sbatch_args ?? []).join('\n'));
394
+ setName(profile?.node ? `${profile.name}-custom` : profile?.name ?? '');
395
+ }, [profile]);
396
+
397
+ const save = useMutation({
398
+ mutationFn: saveSlurmProfile,
399
+ onSuccess: async (_, request) => {
400
+ await queryClient.invalidateQueries({ queryKey: ['slurm-profiles'] });
401
+ if (!profile || request.name !== profile.name) onChange({ ...job, profile: `${request.cluster}/${request.name}` });
402
+ toaster.create({ title: `Profile ${request.name} saved`, type: 'success', duration: 3000 });
403
+ },
404
+ onError: (error: ApiError) => toaster.create({ title: 'Failed to save the profile', description: error.message, type: 'error' }),
405
+ });
406
+
407
+ if (!profile) return <Text fontSize="sm" color="var(--color-text-muted)">Pick resources first.</Text>;
408
+ const lines = args.split('\n').map((l) => l.trim()).filter(Boolean);
409
+ const unchanged = name === profile.name && lines.join('\n') === profile.sbatch_args.join('\n');
410
+ const nodeProfile = !!profile.node && name === profile.name;
411
+
412
+ return (
413
+ <VStack align="stretch" gap={3}>
414
+ <Text fontSize="xs" color="var(--color-text-muted)">
415
+ Shared: every job and pipeline using {profile.cluster || 'mila'}/{profile.name} gets these. Save under a
416
+ new name to change this step only.
417
+ </Text>
418
+ {profile.description && <Text fontSize="sm" color="var(--color-text-muted)">{profile.description}</Text>}
419
+ <Field.Root>
420
+ <Field.Label fontSize="xs">sbatch arguments, one per line</Field.Label>
421
+ <Textarea size="sm" fontFamily="mono" rows={Math.max(4, lines.length + 1)} value={args} onChange={(e) => setArgs(e.target.value)} />
422
+ </Field.Root>
423
+ <HStack gap={2} align="flex-end">
424
+ <Field.Root w="220px" invalid={nodeProfile}>
425
+ <Field.Label fontSize="xs">Profile name ({profile.cluster || 'mila'})</Field.Label>
426
+ <Input size="sm" value={name} onChange={(e) => setName(e.target.value.trim())} />
427
+ </Field.Root>
428
+ <Button
429
+ size="sm"
430
+ variant="outline"
431
+ disabled={!name || unchanged || nodeProfile || lines.length === 0}
432
+ loading={save.isPending}
433
+ onClick={() => save.mutate({ name, cluster: profile.cluster || 'mila', sbatch_args: lines })}
434
+ >
435
+ {name === profile.name ? 'Save profile' : 'Save as new profile'}
436
+ </Button>
437
+ </HStack>
438
+ {nodeProfile && (
439
+ <Text fontSize="xs" color="var(--color-text-muted)">
440
+ {profile.name} comes from the node types of {profile.cluster}: save it under another name.
441
+ </Text>
442
+ )}
443
+ </VStack>
444
+ );
445
+ };
446
+
447
+ /** The script file: shared by every step and pipeline using it */
448
+ const ScriptTab: React.FC<{ script: string; content?: string; usedBy: number }> = ({ script, content, usedBy }) => {
449
+ const queryClient = useQueryClient();
450
+ const [text, setText] = useState(content ?? '');
451
+ useEffect(() => {
452
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- the file arrives after the tab opens, or another script is picked
453
+ setText(content ?? '');
454
+ }, [content, script]);
455
+
456
+ const save = useMutation({
457
+ mutationFn: saveSlurmTemplate,
458
+ onSuccess: () => {
459
+ queryClient.invalidateQueries({ queryKey: ['slurm-template-content', script] });
460
+ toaster.create({ title: `${script} saved`, type: 'success', duration: 3000 });
461
+ },
462
+ onError: (error: ApiError) => toaster.create({ title: `Failed to save ${script}`, description: error.message, type: 'error' }),
463
+ });
464
+
465
+ if (content === undefined) return <Text fontSize="sm" color="var(--color-text-muted)">Loading {script}...</Text>;
466
+ return (
467
+ <Flex direction="column" gap={2} h="100%" minH={0}>
468
+ <HStack gap={2}>
469
+ <Text fontSize="xs" color="var(--color-text-muted)" flex={1}>
470
+ Shared file: {usedBy > 1 ? `${usedBy} steps of this pipeline use it` : 'this step uses it'}, other pipelines and jobs may too.
471
+ </Text>
472
+ {text !== content && <Button size="xs" variant="ghost" onClick={() => setText(content)}>Revert</Button>}
473
+ <Button
474
+ size="xs"
475
+ variant="outline"
476
+ disabled={text === content}
477
+ loading={save.isPending}
478
+ onClick={() => save.mutate({ name: script, content: text })}
479
+ >
480
+ Save script
481
+ </Button>
482
+ </HStack>
483
+ <Box flex={1} minH="240px">
484
+ <MonacoEditor value={text} onChange={setText} height="100%" />
485
+ </Box>
486
+ </Flex>
487
+ );
488
+ };
489
+
490
+ /** The selected job: script and resources pickers, then its arguments, its profile and its script */
491
+ const JobPane: React.FC<{
492
+ job: JobNode;
493
+ profiles: SlurmProfile[];
494
+ templates: string[];
495
+ usedBy: number;
496
+ onChange: (job: JobNode) => void;
497
+ }> = ({ job, profiles, templates, usedBy, onChange }) => {
498
+ const profile = findProfile(job.profile, profiles);
499
+ const selectedProfile = profile ? profileKey(profile) : job.profile;
500
+ const scripts = templates.includes(job.script) || !job.script ? templates : [job.script, ...templates];
501
+ const [tab, setTab] = useState('arguments');
502
+ const { data: content } = useQuery({
503
+ queryKey: ['slurm-template-content', job.script],
504
+ queryFn: () => getSlurmTemplateContent(job.script),
505
+ enabled: !!job.script,
506
+ retry: false,
507
+ staleTime: 30_000,
508
+ });
509
+
510
+ return (
511
+ <Flex direction="column" gap={3} h="100%" minH={0}>
512
+ <HStack gap={3} align="flex-end" flexWrap="wrap">
513
+ <Field.Root flex="1 1 220px">
514
+ <Field.Label fontSize="xs">Script</Field.Label>
515
+ <NativeSelect.Root size="sm">
516
+ <NativeSelect.Field value={job.script} onChange={(e) => onChange({ ...job, script: e.target.value })}>
517
+ {!job.script && <option value="">pick a script</option>}
518
+ {scripts.map((s) => <option key={s} value={s}>{s}</option>)}
519
+ </NativeSelect.Field>
520
+ <NativeSelect.Indicator />
521
+ </NativeSelect.Root>
522
+ </Field.Root>
523
+ <Field.Root flex="1 1 220px">
524
+ <Field.Label fontSize="xs">Resources</Field.Label>
525
+ <NativeSelect.Root size="sm">
526
+ <NativeSelect.Field
527
+ value={selectedProfile}
528
+ // an unchanged profile keeps how the file wrote it ("example-cpu": the default cluster)
529
+ onChange={(e) => onChange({ ...job, profile: e.target.value })}
530
+ >
531
+ {!job.profile && <option value="">pick resources</option>}
532
+ {job.profile && !profile && <option value={job.profile}>{job.profile} (unknown)</option>}
533
+ {profiles.map((p) => <option key={profileKey(p)} value={profileKey(p)}>{profileLabel(p)}</option>)}
534
+ </NativeSelect.Field>
535
+ <NativeSelect.Indicator />
536
+ </NativeSelect.Root>
537
+ </Field.Root>
538
+ </HStack>
539
+ {profile && profile.sbatch_args.length > 0 && (
540
+ <HStack gap={1} flexWrap="wrap">
541
+ {profile.sbatch_args.map((arg) => <Code key={arg} size="sm">{arg}</Code>)}
542
+ {job.proxy !== undefined && <Badge size="sm" variant="outline">proxy: {String(job.proxy)}</Badge>}
543
+ </HStack>
544
+ )}
545
+
546
+ <Tabs.Root value={tab} onValueChange={(e) => setTab(e.value)} size="sm" variant="line" display="flex" flexDirection="column" flex={1} minH={0}>
547
+ <Tabs.List>
548
+ <Tabs.Trigger value="arguments">
549
+ Arguments{job.env && Object.keys(job.env).length ? ` (${Object.keys(job.env).length})` : ''}
550
+ </Tabs.Trigger>
551
+ <Tabs.Trigger value="resources">Resources</Tabs.Trigger>
552
+ <Tabs.Trigger value="script">Script</Tabs.Trigger>
553
+ </Tabs.List>
554
+ <Tabs.Content value="arguments" flex={1} minH={0} overflow="auto" pt={3}>
555
+ <ArgumentsTab job={job} content={job.script ? content : ''} onChange={onChange} />
556
+ </Tabs.Content>
557
+ <Tabs.Content value="resources" flex={1} minH={0} overflow="auto" pt={3}>
558
+ <ResourcesTab job={job} profile={profile} onChange={onChange} />
559
+ </Tabs.Content>
560
+ <Tabs.Content value="script" flex={1} minH={0} pt={3} display={tab === 'script' ? 'flex' : undefined} flexDirection="column">
561
+ {job.script
562
+ ? <ScriptTab key={job.script} script={job.script} content={content} usedBy={usedBy} />
563
+ : <Text fontSize="sm" color="var(--color-text-muted)">Pick a script first.</Text>}
564
+ </Tabs.Content>
565
+ </Tabs.Root>
566
+ </Flex>
567
+ );
568
+ };
569
+
570
+ const GroupPane: React.FC<{
571
+ group: Exclude<PipelineNode, { type: 'job' }>;
572
+ isRoot: boolean;
573
+ onChange: (group: Exclude<PipelineNode, { type: 'job' }>) => void;
574
+ }> = ({ group, isRoot, onChange }) => (
575
+ <VStack align="stretch" gap={4}>
576
+ <Field.Root>
577
+ <Field.Label fontSize="xs">{group.type === 'sequential' ? 'Sequential' : 'Parallel'} group name</Field.Label>
578
+ <Input size="sm" value={group.name} onChange={(e) => onChange({ ...group, name: e.target.value })} />
579
+ </Field.Root>
580
+ {group.type === 'parallel' && (
581
+ <Field.Root>
582
+ <Field.Label fontSize="xs">Sweep variable (optional)</Field.Label>
583
+ <Input
584
+ size="sm"
585
+ fontFamily="mono"
586
+ placeholder="ARGS"
587
+ value={group.sweep ?? ''}
588
+ onChange={(e) => {
589
+ const sweep = e.target.value.toUpperCase().replace(/[^A-Z0-9_]/g, '');
590
+ const { sweep: _old, ...rest } = group;
591
+ onChange(sweep ? { ...rest, sweep } : rest);
592
+ }}
593
+ />
594
+ <Field.HelperText fontSize="xs">
595
+ The env variable that tells its steps apart: the steps are shown by its value instead of their script.
596
+ Empty: the variable every step sets to another value, if there is one{groupSweepKey(group) && !group.sweep ? ` (${groupSweepKey(group)})` : ''}.
597
+ </Field.HelperText>
598
+ </Field.Root>
599
+ )}
600
+ <Text fontSize="sm" color="var(--color-text-muted)">
601
+ {group.type === 'sequential'
602
+ ? 'Its steps run one after the other: each waits for the previous one to succeed (afterok).'
603
+ : 'Its steps start together, after what comes before the group. The step after the group waits for all of them.'}
604
+ {isRoot ? ' This is the top of the pipeline.' : ''}
605
+ </Text>
606
+ <Text fontSize="sm" color="var(--color-text-muted)">
607
+ {group.jobs.length} {group.jobs.length === 1 ? 'step' : 'steps'}: add one with the + row at its end, pick a row to edit it.
608
+ </Text>
609
+ </VStack>
610
+ );
611
+
612
+ const countScript = (node: PipelineNode, script: string): number =>
613
+ node.type === 'job' ? Number(node.script === script) : node.jobs.reduce((n, c) => n + countScript(c, script), 0);
614
+
615
+ const EMPTY_ROOT: PipelineNode = { type: 'sequential', name: 'main', jobs: [] };
616
+
617
+ /** The pipeline editor: a compact tree on the left, the selected step on the right */
618
+ export const PipelineBuilder: React.FC<{
619
+ isOpen: boolean;
620
+ onClose: () => void;
621
+ profiles: SlurmProfile[];
622
+ templates: string[];
623
+ loadedTemplateData?: PipelineTemplateFileData | null;
624
+ onSaveTemplate: (data: PipelineTemplatePayload) => void;
625
+ }> = ({ isOpen, onClose, profiles, templates, loadedTemplateData, onSaveTemplate }) => {
626
+ const [name, setName] = useState(loadedTemplateData?.name || loadedTemplateData?.pipelineName || '');
627
+ const [description, setDescription] = useState(loadedTemplateData?.description || '');
628
+ const [root, setRoot] = useState<PipelineNode>(loadedTemplateData?.definition ?? EMPTY_ROOT);
629
+ const [selected, setSelected] = useState<Path | null>([]);
630
+ const [hover, setHover] = useState<Hover>(null);
631
+
632
+ // the dialog is mounted while open: start from the pipeline it opened with
633
+ useEffect(() => {
634
+ if (!loadedTemplateData) return;
635
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- the pipeline arrives after the first render when it is still loading
636
+ setName(loadedTemplateData.name || loadedTemplateData.pipelineName || '');
637
+ setDescription(loadedTemplateData.description || '');
638
+ if (loadedTemplateData.definition) setRoot(loadedTemplateData.definition);
639
+ }, [loadedTemplateData]);
640
+
641
+ const selectedNode = selected ? nodeAt(root, selected) : undefined;
642
+ const issue = useMemo(() => problem(root), [root]);
643
+
644
+ // a new job takes the resources of the job before it, else the first profile
645
+ const fallbackFor = (group: PipelineNode) => {
646
+ const jobs = group.type !== 'job' ? group.jobs.filter((j) => j.type === 'job') : [];
647
+ const last = jobs[jobs.length - 1];
648
+ return {
649
+ script: templates[0] || '',
650
+ profile: last && last.type === 'job' ? last.profile : profileKey(profiles[0]),
651
+ };
652
+ };
653
+
654
+ const onAdd = (path: Path) => {
655
+ const group = nodeAt(root, path);
656
+ if (!group || group.type === 'job') return;
657
+ const job: PipelineNode = { type: 'job', ...fallbackFor(group) };
658
+ setRoot(updateAt(root, path, (g) => (g.type === 'job' ? g : { ...g, jobs: [...g.jobs, job] })));
659
+ setSelected([...path, group.jobs.length]);
660
+ };
661
+ const onDelete = (path: Path) => {
662
+ setRoot(updateAt(root, path, () => null));
663
+ setSelected(path.slice(0, -1));
664
+ };
665
+ const onType = (path: Path, type: NodeType) => {
666
+ const node = nodeAt(root, path);
667
+ if (!node) return;
668
+ if (type === 'job' && node.type !== 'job' && node.jobs.length > 1
669
+ && !window.confirm(`Turn ${node.name} into a job? Its ${node.jobs.length} steps are removed, the first job is kept.`)) {
670
+ return;
671
+ }
672
+ setRoot(updateAt(root, path, (n) => changeType(n, type, fallbackFor(n))));
673
+ setSelected(path);
674
+ };
675
+ const replaceSelected = (node: PipelineNode) => {
676
+ if (selected) setRoot(updateAt(root, selected, () => node));
677
+ };
678
+
679
+ const save = () => {
680
+ if (!name || issue) return;
681
+ onSaveTemplate({
682
+ name,
683
+ type: 'pipeline',
684
+ ...(description.trim() ? { description: description.trim() } : {}),
685
+ definition: root,
686
+ job_id: null,
687
+ });
688
+ onClose();
689
+ };
690
+
691
+ return (
692
+ <Dialog.Root open={isOpen} onOpenChange={(details) => { if (!details.open) onClose(); }} size="cover">
693
+ <Dialog.Backdrop />
694
+ <Dialog.Positioner>
695
+ <Dialog.Content maxW="1100px" h="min(760px, 90vh)" display="flex" flexDirection="column">
696
+ <Dialog.Header py={3} px={4} borderBottom="1px solid" borderColor="var(--color-border)">
697
+ <HStack gap={3} w="100%" pr={8} align="flex-start">
698
+ <Input
699
+ size="sm"
700
+ w="240px"
701
+ flexShrink={0}
702
+ value={name}
703
+ onChange={(e) => setName(e.target.value)}
704
+ placeholder="Pipeline name"
705
+ fontWeight="semibold"
706
+ aria-label="Pipeline name"
707
+ />
708
+ <Input
709
+ size="sm"
710
+ flex={1}
711
+ value={description}
712
+ onChange={(e) => setDescription(e.target.value)}
713
+ placeholder="Description: what it does, what to change before running it"
714
+ aria-label="Description"
715
+ title={description}
716
+ />
717
+ </HStack>
718
+ <Dialog.CloseTrigger />
719
+ </Dialog.Header>
720
+ <Dialog.Body p={0} flex={1} minH={0} display="flex">
721
+ <Box
722
+ w="360px"
723
+ flexShrink={0}
724
+ borderRight="1px solid"
725
+ borderColor="var(--color-border)"
726
+ overflowY="auto"
727
+ py={1}
728
+ onMouseLeave={() => setHover(null)}
729
+ role="tree"
730
+ >
731
+ <TreeRows
732
+ node={root}
733
+ path={[]}
734
+ selected={selected}
735
+ onSelect={setSelected}
736
+ onType={onType}
737
+ onDelete={onDelete}
738
+ onAdd={onAdd}
739
+ root={root}
740
+ hover={hover}
741
+ onHover={setHover}
742
+ />
743
+ </Box>
744
+ <Box flex={1} minW={0} p={4} overflow="auto">
745
+ {selectedNode?.type === 'job' ? (
746
+ <JobPane
747
+ key={selected?.join('.')}
748
+ job={selectedNode}
749
+ profiles={profiles}
750
+ templates={templates}
751
+ usedBy={countScript(root, selectedNode.script)}
752
+ onChange={replaceSelected}
753
+ />
754
+ ) : selectedNode ? (
755
+ <GroupPane group={selectedNode} isRoot={selected?.length === 0} onChange={replaceSelected} />
756
+ ) : (
757
+ <Text color="var(--color-text-muted)" fontSize="sm">Pick a step on the left.</Text>
758
+ )}
759
+ </Box>
760
+ </Dialog.Body>
761
+ <Dialog.Footer py={3} px={4} borderTop="1px solid" borderColor="var(--color-border)">
762
+ {issue && <Text fontSize="sm" color="var(--color-text-muted)" mr="auto">Before saving: {issue}</Text>}
763
+ <Button variant="ghost" size="sm" onClick={onClose} color="var(--color-text)">Cancel</Button>
764
+ <Button
765
+ size="sm"
766
+ onClick={save}
767
+ disabled={!name || !!issue}
768
+ bg="var(--color-primary)"
769
+ color="var(--color-primary-text)"
770
+ _hover={{ bg: 'var(--color-primary-hover)' }}
771
+ >
772
+ Save Pipeline
773
+ </Button>
774
+ </Dialog.Footer>
775
+ </Dialog.Content>
776
+ </Dialog.Positioner>
777
+ </Dialog.Root>
778
+ );
779
+ };