@milabench/bujang 0.1.7 → 0.1.9

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.
@@ -481,7 +481,8 @@ export const JobLogsView: React.FC<JobLogsViewProps> = () => {
481
481
  } else {
482
482
  toaster.create({
483
483
  title: 'Early Sync Failed',
484
- description: 'Could not sync job results early. Job may not be running or compute node unavailable.',
484
+ description: result.error
485
+ || 'Could not sync job results early. Job may not be running or compute node unavailable.',
485
486
  type: 'warning',
486
487
  duration: 5000,
487
488
  });
@@ -16,11 +16,12 @@ import {
16
16
  Spinner,
17
17
  Icon,
18
18
  } from '@chakra-ui/react';
19
- import { LuCheck, LuX, LuLock, LuCalendar } from 'react-icons/lu';
19
+ import { LuCheck, LuX, LuLock, LuCalendar, LuPaperclip } from 'react-icons/lu';
20
20
  import { toaster } from '../toast';
21
21
  import { MonacoEditor } from '../components/MonacoEditor';
22
22
  import type { MonacoCodeEditor } from '../components/MonacoEditor';
23
23
  import AutocompleteInput from '../components/AutocompleteInput';
24
+ import { useSshConnectGate } from '../components/SshConnectDialog';
24
25
  import { useMutation, useQueryClient } from '@tanstack/react-query';
25
26
  import { useSearchParams } from 'react-router-dom';
26
27
  import {
@@ -30,9 +31,77 @@ import {
30
31
  saveSlurmTemplate,
31
32
  testSlurmSecret,
32
33
  createScheduledJob,
34
+ fileToAttachment,
33
35
  } from '../api';
34
36
  import type { SlurmProfile, SlurmJob, ApiError, ScheduledJob } from '../types';
35
37
 
38
+ const formatSize = (n: number) =>
39
+ n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1024 ** 2).toFixed(1)} MB`;
40
+
41
+ /** Name of an attached file in input/: its path inside a picked folder, else its name */
42
+ const attachmentName = (file: File) => (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
43
+
44
+ /**
45
+ * Files sent with the job: copied to <job folder>/input/ on the cluster before the job starts,
46
+ * the script finds them in $JR_INPUT_DIR.
47
+ */
48
+ const AttachmentsCard: React.FC<{ files: File[]; onChange: (files: File[]) => void }> = ({ files, onChange }) => {
49
+ const fileInput = useRef<HTMLInputElement>(null);
50
+ const folderInput = useRef<HTMLInputElement>(null);
51
+ const add = (list: FileList | null) => {
52
+ if (!list) return;
53
+ const byName = new Map(files.map(f => [attachmentName(f), f]));
54
+ Array.from(list).forEach(f => byName.set(attachmentName(f), f));
55
+ onChange(Array.from(byName.values()));
56
+ };
57
+ const total = files.reduce((n, f) => n + f.size, 0);
58
+ return (
59
+ <Card.Root bg="var(--color-bg-card)" borderWidth="1px" borderColor="var(--color-border)" borderRadius="lg" boxShadow="sm" p={4}>
60
+ <VStack align="stretch" gap={3}>
61
+ <HStack justify="space-between" wrap="wrap" gap={2}>
62
+ <Heading size="sm" fontWeight="semibold" color="var(--color-text)">
63
+ <HStack gap={2}><LuPaperclip /> Attached files</HStack>
64
+ </Heading>
65
+ <HStack gap={2}>
66
+ <Button size="xs" variant="outline" onClick={() => fileInput.current?.click()}>Add files</Button>
67
+ <Button size="xs" variant="outline" onClick={() => folderInput.current?.click()}>Add a folder</Button>
68
+ </HStack>
69
+ </HStack>
70
+ <input ref={fileInput} type="file" multiple hidden onChange={(e) => { add(e.target.files); e.target.value = ''; }} />
71
+ <input
72
+ ref={folderInput}
73
+ type="file"
74
+ multiple
75
+ hidden
76
+ {...({ webkitdirectory: '', directory: '' } as Record<string, string>)}
77
+ onChange={(e) => { add(e.target.files); e.target.value = ''; }}
78
+ />
79
+ <Text fontSize="xs" color="var(--color-text-muted)">
80
+ Copied to <code>input/</code> of the job folder on the cluster before the job starts: the script reads
81
+ them from <code>$JR_INPUT_DIR</code> and writes its results to <code>$JR_OUTPUT_DIR</code>.
82
+ </Text>
83
+ {files.length > 0 && (
84
+ <VStack align="stretch" gap={1}>
85
+ {files.map(f => (
86
+ <HStack key={attachmentName(f)} justify="space-between" fontSize="sm">
87
+ <Text fontFamily="mono" fontSize="xs" color="var(--color-text)" truncate>input/{attachmentName(f)}</Text>
88
+ <HStack gap={2} flexShrink={0}>
89
+ <Text fontSize="xs" color="var(--color-text-muted)">{formatSize(f.size)}</Text>
90
+ <Button size="2xs" variant="ghost" aria-label={`Remove ${attachmentName(f)}`}
91
+ onClick={() => onChange(files.filter(x => x !== f))}>
92
+ <LuX />
93
+ </Button>
94
+ </HStack>
95
+ </HStack>
96
+ ))}
97
+ <Text fontSize="xs" color="var(--color-text-muted)">{files.length} files, {formatSize(total)} in all</Text>
98
+ </VStack>
99
+ )}
100
+ </VStack>
101
+ </Card.Root>
102
+ );
103
+ };
104
+
36
105
  const CRON_PRESETS: { label: string; cron: string }[] = [
37
106
  { label: 'Daily at midnight', cron: '0 0 * * *' },
38
107
  { label: 'Weekly on Sunday at 2am', cron: '0 2 * * 0' },
@@ -111,6 +180,33 @@ interface ClusterOption {
111
180
  ssh: string;
112
181
  }
113
182
 
183
+ /** The last cluster / profile / template picked on the submit page, restored on the next visit */
184
+ const SUBMIT_SELECTION_KEY = 'bujang-submit-selection';
185
+
186
+ interface SavedSelection {
187
+ cluster?: string;
188
+ profile?: string;
189
+ template?: string;
190
+ }
191
+
192
+ function loadSavedSelection(): SavedSelection {
193
+ try {
194
+ const raw = localStorage.getItem(SUBMIT_SELECTION_KEY);
195
+ const parsed = raw ? JSON.parse(raw) : null;
196
+ return parsed && typeof parsed === 'object' ? parsed : {};
197
+ } catch {
198
+ return {};
199
+ }
200
+ }
201
+
202
+ function saveSelection(selection: SavedSelection): void {
203
+ try {
204
+ localStorage.setItem(SUBMIT_SELECTION_KEY, JSON.stringify(selection));
205
+ } catch {
206
+ // storage unavailable (private window, blocked site data): the URL still keeps the selection
207
+ }
208
+ }
209
+
114
210
  interface JobSubmissionFormProps {
115
211
  templates?: string[];
116
212
  profiles: SlurmProfile[];
@@ -135,12 +231,15 @@ export const JobSubmissionForm: React.FC<JobSubmissionFormProps> = ({
135
231
  const queryClient = useQueryClient();
136
232
 
137
233
  const [searchParams, setSearchParams] = useSearchParams();
138
- // read once: the URL is then written from the selection
139
- const [urlSelection] = useState(() => ({
140
- cluster: syncUrl ? searchParams.get('cluster') : null,
141
- profile: syncUrl ? searchParams.get('profile') : null,
142
- template: syncUrl ? searchParams.get('template') : null,
143
- }));
234
+ // read once: the URL is then written from the selection.
235
+ // URL first, then the last selection saved in localStorage, then the defaults.
236
+ const [urlSelection] = useState(() => {
237
+ if (!syncUrl) return { cluster: null, profile: null, template: null };
238
+ const saved = loadSavedSelection();
239
+ const fromUrl = searchParams.has('cluster') || searchParams.has('profile') || searchParams.has('template');
240
+ const pick = (key: keyof SavedSelection) => (fromUrl ? searchParams.get(key) : saved[key] ?? null);
241
+ return { cluster: pick('cluster'), profile: pick('profile'), template: pick('template') };
242
+ });
144
243
 
145
244
  // No form state needed - we'll build the data on-demand from refs
146
245
 
@@ -157,6 +256,9 @@ export const JobSubmissionForm: React.FC<JobSubmissionFormProps> = ({
157
256
  // sbatch arguments without a form field (--gpus, --tmp, ...), space separated
158
257
  const [extraArgs, setExtraArgs] = useState<string>('');
159
258
 
259
+ // Files sent with the job (input/ of the job folder)
260
+ const [attachments, setAttachments] = useState<File[]>([]);
261
+
160
262
  // Schedule state
161
263
  const [scheduleName, setScheduleName] = useState<string>('');
162
264
  const [cronPreset, setCronPreset] = useState<string>(CRON_PRESETS[0].cron);
@@ -165,6 +267,7 @@ export const JobSubmissionForm: React.FC<JobSubmissionFormProps> = ({
165
267
  const effectiveCron = isCustomCron ? cronCustom : cronPreset;
166
268
 
167
269
  // Mutations
270
+ const sshGate = useSshConnectGate();
168
271
  const submitJobMutation = useMutation({
169
272
  mutationFn: submitSlurmJob,
170
273
  onSuccess: (data) => {
@@ -176,6 +279,7 @@ export const JobSubmissionForm: React.FC<JobSubmissionFormProps> = ({
176
279
  });
177
280
  queryClient.invalidateQueries({ queryKey: ['slurm-jobs'] });
178
281
  queryClient.invalidateQueries({ queryKey: ['slurm-persisted-jobs'] });
282
+ setAttachments([]);
179
283
  if (onClose) onClose();
180
284
  },
181
285
  onError: (error: ApiError) => {
@@ -470,14 +574,26 @@ export const JobSubmissionForm: React.FC<JobSubmissionFormProps> = ({
470
574
  return result;
471
575
  };
472
576
 
473
- const handleSubmitJob = () => {
474
- submitJobMutation.mutate({
577
+ const handleSubmitJob = async () => {
578
+ let files;
579
+ try {
580
+ files = attachments.length
581
+ ? await Promise.all(attachments.map(f => fileToAttachment(f, attachmentName(f))))
582
+ : undefined;
583
+ } catch (error) {
584
+ toaster.create({ title: 'Cannot read the attached files', description: String(error), type: 'error', duration: 5000 });
585
+ return;
586
+ }
587
+ const request = {
475
588
  script: editorRef.current?.getValue() || '',
476
589
  job_name: jobNameRef.current?.value || 'bujang_job',
477
590
  cluster: selectedCluster,
478
591
  sbatch_args: _collectSbatchArgs(),
479
592
  script_args: _collectScriptArgs(),
480
- });
593
+ files,
594
+ };
595
+ // a cluster without an open ssh connection (MFA): log in first, then submit
596
+ await sshGate.ensure(selectedCluster, () => submitJobMutation.mutate(request));
481
597
  };
482
598
 
483
599
  const handleSaveScheduled = () => {
@@ -575,8 +691,8 @@ export const JobSubmissionForm: React.FC<JobSubmissionFormProps> = ({
575
691
  return;
576
692
  }
577
693
 
578
- // No initialData: apply the profile / template the URL selects, once they are loaded.
579
- // No URL selection: nothing is preselected.
694
+ // No initialData: apply the profile / template the URL (or the saved selection) picks,
695
+ // once they are loaded. Neither: nothing is preselected.
580
696
  const defaultProfile = urlSelection.profile ?? '';
581
697
  const defaultTemplate = urlSelection.template ?? '';
582
698
 
@@ -591,7 +707,7 @@ export const JobSubmissionForm: React.FC<JobSubmissionFormProps> = ({
591
707
  // eslint-disable-next-line react-hooks/exhaustive-deps -- handleProfileSelect/handleTemplateSelect/selectedProfile/selectedTemplate intentionally excluded: this is a run-once (per initialData/profiles/templates arrival) effect guarded by ref flags; the handlers are recreated every render and adding them (or the state they set) as deps would just cause redundant re-invocations, not additional side effects, but wrapping them in useCallback risks changing their identity semantics elsewhere in this large form -- not worth the risk for a mount-time-only effect.
592
708
  }, [initialData, profiles, templates]);
593
709
 
594
- // Selection -> URL (replace: no history entry per click)
710
+ // Selection -> URL (replace: no history entry per click) and localStorage
595
711
  useEffect(() => {
596
712
  if (!syncUrl) return;
597
713
  setSearchParams((prev) => {
@@ -602,6 +718,12 @@ export const JobSubmissionForm: React.FC<JobSubmissionFormProps> = ({
602
718
  set('template', selectedTemplate);
603
719
  return next;
604
720
  }, { replace: true });
721
+ // don't save while a restored profile / template waits for its list to load: it is still
722
+ // empty, and saving it would wipe the saved selection if the page is left before that
723
+ const profilePending = !selectedProfile && !!urlSelection.profile && !defaultProfileApplied.current;
724
+ const templatePending = !selectedTemplate && !!urlSelection.template && !defaultTemplateApplied.current;
725
+ if (profilePending || templatePending) return;
726
+ saveSelection({ cluster: selectedCluster, profile: selectedProfile, template: selectedTemplate });
605
727
  }, [syncUrl, selectedCluster, selectedProfile, selectedTemplate, setSearchParams]);
606
728
 
607
729
  // Minimal state only for displaying script args section (not for values)
@@ -1157,6 +1279,9 @@ export const JobSubmissionForm: React.FC<JobSubmissionFormProps> = ({
1157
1279
 
1158
1280
  </VStack>
1159
1281
  </Card.Root>
1282
+
1283
+ {/* Files sent with the job */}
1284
+ <AttachmentsCard files={attachments} onChange={setAttachments} />
1160
1285
  </VStack>
1161
1286
 
1162
1287
  {/* Right Column - Script Editor */}
@@ -1267,6 +1392,7 @@ export const JobSubmissionForm: React.FC<JobSubmissionFormProps> = ({
1267
1392
  </Grid>
1268
1393
 
1269
1394
  </VStack>
1395
+ {sshGate.dialog}
1270
1396
  </Box>
1271
1397
  );
1272
1398
  };
@@ -37,7 +37,6 @@ import {
37
37
  getSlurmPersistedJobs,
38
38
  cancelSlurmJob,
39
39
  rerunSlurmJob,
40
- getSlurmClusterStatus,
41
40
  getOrganizers,
42
41
  getSyncStatus,
43
42
  syncNow,
@@ -46,6 +45,7 @@ import { JobImportantStar } from './JobMarks';
46
45
  import type { SlurmJob, PersitedJobInfo, ApiError, OrganizerGroups, SyncStatus } from '../types';
47
46
  import { usePageTitle } from '../hooks/usePageTitle';
48
47
  import { AgentBadge } from './AgentActivityView';
48
+ import { SshConnectButton } from '../components/SshConnectDialog';
49
49
  import { NO_JOB_ID, NO_JOB_STATE, NO_JR_JOB_ID } from '../constants';
50
50
 
51
51
  type JobsViewProps = Record<string, never>;
@@ -238,15 +238,6 @@ export const JobsView: React.FC<JobsViewProps> = () => {
238
238
  retry: false,
239
239
  });
240
240
 
241
- const { data: clusterStatus, isLoading: clusterStatusLoading } = useQuery({
242
- queryKey: ['slurm-cluster-status'],
243
- queryFn: getSlurmClusterStatus,
244
- refetchOnWindowFocus: false,
245
- staleTime: 30000, // Consider data fresh for 30 seconds
246
- refetchInterval: 60000, // Refetch every minute
247
- retry: false, // Don't retry on error to avoid excessive requests when cluster is down
248
- });
249
-
250
241
  // ?clusters=mila&experiments=lr-sweep: the jobs under every chosen value
251
242
  const [params, setParams] = useSearchParams();
252
243
  const organizerNames = React.useMemo(() => organizers.map((o) => o.name), [organizers]);
@@ -364,56 +355,7 @@ export const JobsView: React.FC<JobsViewProps> = () => {
364
355
  <Heading size="xl" fontWeight="bold" color="var(--color-text)">
365
356
  Jobs
366
357
  </Heading>
367
- {clusterStatusLoading ? (
368
- <Tooltip
369
- positioning={{ placement: 'bottom', offset: { mainAxis: 8 } }}
370
- content="Checking cluster status..."
371
- >
372
- <Spinner size="sm" />
373
- </Tooltip>
374
- ) : clusterStatus ? (
375
- <Tooltip
376
- positioning={{ placement: 'bottom', offset: { mainAxis: 8 } }}
377
- content={
378
- clusterStatus.status === 'offline' && clusterStatus.reason
379
- ? `${clusterStatus.reason}`
380
- : clusterStatus.status === 'online'
381
- ? 'Cluster is online and ready to accept jobs'
382
- : 'Cluster status'
383
- }
384
- >
385
- <Badge
386
- colorScheme={clusterStatus.status === 'online' ? 'green' : 'red'}
387
- variant="solid"
388
- fontSize="sm"
389
- px={4}
390
- py={1.5}
391
- borderRadius="full"
392
- cursor="help"
393
- fontWeight="medium"
394
- >
395
- {clusterStatus.status === 'online' ? '✓ Online' : '✗ Offline'}
396
- </Badge>
397
- </Tooltip>
398
- ) : (
399
- <Tooltip
400
- positioning={{ placement: 'bottom', offset: { mainAxis: 8 } }}
401
- content="Unable to determine cluster status"
402
- >
403
- <Badge
404
- colorScheme="gray"
405
- variant="solid"
406
- fontSize="sm"
407
- px={4}
408
- py={1.5}
409
- borderRadius="full"
410
- cursor="help"
411
- fontWeight="medium"
412
- >
413
- Status Unknown
414
- </Badge>
415
- </Tooltip>
416
- )}
358
+ <SshConnectButton />
417
359
  </HStack>
418
360
 
419
361
  <HStack gap={3}>
@@ -437,7 +379,7 @@ export const JobsView: React.FC<JobsViewProps> = () => {
437
379
  variant="outline"
438
380
  onClick={() => refresh.mutate()}
439
381
  title="rsync the clusters with active jobs now"
440
- loading={refresh.isPending || activeJobsLoading || persistedJobsLoading || clusterStatusLoading}
382
+ loading={refresh.isPending || activeJobsLoading || persistedJobsLoading}
441
383
  size="sm"
442
384
  fontWeight="medium"
443
385
  >
@@ -811,6 +753,8 @@ export const JobsView: React.FC<JobsViewProps> = () => {
811
753
  >
812
754
  <Table.Cell pl={6} pr={4}>
813
755
  <HStack gap={2}>
756
+ {/* first thing of the row: the important jobs stand out */}
757
+ <JobImportantStar jrJobId={jrJobId} important={!!persistedJobInfo.important} />
814
758
  <Tooltip
815
759
  positioning={{ placement: 'top', offset: { mainAxis: 8 } }}
816
760
  content={formatDuration(persistedJobInfo.freshness)}
@@ -835,7 +779,6 @@ export const JobsView: React.FC<JobsViewProps> = () => {
835
779
  </Table.Cell>
836
780
  <Table.Cell>
837
781
  <HStack gap={2} flexWrap="wrap">
838
- <JobImportantStar jrJobId={jrJobId} important={!!persistedJobInfo.important} />
839
782
  <Text color="var(--color-text)">{jobName}<AgentBadge tag={persistedJobInfo.agent} /></Text>
840
783
  {(persistedJobInfo.groups || []).map((g) => (
841
784
  <Badge
@@ -160,6 +160,34 @@ export function pipelineMermaid(root: PipelineNode, states: Record<string, strin
160
160
 
161
161
  let mermaidCounter = 0;
162
162
 
163
+ /**
164
+ * Run `fn` with the global AMD `define` hidden.
165
+ *
166
+ * @monaco-editor/react loads Monaco's AMD loader (vs/loader.js), which installs `window.define`.
167
+ * Mermaid bundles fastdom / fastdom-promised, whose UMD wrappers test `typeof define` before
168
+ * `module` and so call an anonymous `define(...)` when it exists. Monaco's loader then throws
169
+ * "Can only have one anonymous define call per script file". It happens only after an editor
170
+ * was opened. Hiding `define` makes them take the CommonJS branch the bundler wrapped them in.
171
+ * Mermaid loads its diagram chunks lazily during render, so render goes inside too.
172
+ */
173
+ let amdHidden = 0;
174
+ let savedDefine: unknown;
175
+ async function withoutAmdDefine<T>(fn: () => Promise<T>): Promise<T> {
176
+ const w = window as unknown as { define?: unknown };
177
+ if (amdHidden++ === 0) {
178
+ savedDefine = w.define;
179
+ w.define = undefined;
180
+ }
181
+ try {
182
+ return await fn();
183
+ } finally {
184
+ if (--amdHidden === 0 && savedDefine !== undefined) {
185
+ w.define = savedDefine;
186
+ savedDefine = undefined;
187
+ }
188
+ }
189
+ }
190
+
163
191
  /** The pipeline graph, rendered by mermaid (loaded on first use) */
164
192
  export const PipelineGraph: React.FC<{ definition: PipelineNode; states?: Record<string, string> }> = ({ definition, states }) => {
165
193
  const { colorMode } = useColorMode();
@@ -173,9 +201,11 @@ export const PipelineGraph: React.FC<{ definition: PipelineNode; states?: Record
173
201
  let cancelled = false;
174
202
  (async () => {
175
203
  try {
176
- const mermaid = (await import('mermaid')).default;
177
- mermaid.initialize({ startOnLoad: false, theme: dark ? 'dark' : 'default', securityLevel: 'strict', flowchart: { htmlLabels: true } });
178
- const { svg: out } = await mermaid.render(`bujang-pipeline-${baseId}-${mermaidCounter++}`, source);
204
+ const { svg: out } = await withoutAmdDefine(async () => {
205
+ const mermaid = (await import('mermaid')).default;
206
+ mermaid.initialize({ startOnLoad: false, theme: dark ? 'dark' : 'default', securityLevel: 'strict', flowchart: { htmlLabels: true } });
207
+ return mermaid.render(`bujang-pipeline-${baseId}-${mermaidCounter++}`, source);
208
+ });
179
209
  if (!cancelled) { setSvg(out); setError(null); }
180
210
  } catch (e) {
181
211
  if (!cancelled) setError((e as Error).message || String(e));