@milabench/bujang 0.1.1 → 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,89 @@
1
+ import React from 'react';
2
+ import { Badge, Box, Card, Heading, HStack, Link, Table, Text } from '@chakra-ui/react';
3
+ import { useQuery } from '@tanstack/react-query';
4
+ import { LuDownload, LuExternalLink, LuFileText } from 'react-icons/lu';
5
+ import { getJobArtifacts, jobArtifactUrl } from '../api';
6
+ import type { ApiError, JobArtifacts } from '../types';
7
+
8
+ const formatSize = (bytes: number) => {
9
+ if (bytes < 1024) return `${bytes} B`;
10
+ const units = ['KB', 'MB', 'GB', 'TB'];
11
+ let value = bytes / 1024;
12
+ let unit = 0;
13
+ while (value >= 1024 && unit < units.length - 1) {
14
+ value /= 1024;
15
+ unit += 1;
16
+ }
17
+ return `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit]}`;
18
+ };
19
+
20
+ /**
21
+ * The reports and other files of a job's results/ and output/ folders, delivered by the server:
22
+ * an HTML report opens in a new tab (its images and scripts load next to it), the rest downloads.
23
+ * Nothing is shown when the job has none.
24
+ */
25
+ export const JobArtifactsCard: React.FC<{ jrJobId: string }> = ({ jrJobId }) => {
26
+ const { data, error } = useQuery<JobArtifacts, ApiError>({
27
+ queryKey: ['bujang-job-artifacts', jrJobId],
28
+ queryFn: () => getJobArtifacts(jrJobId),
29
+ staleTime: 30_000,
30
+ retry: false,
31
+ });
32
+ if (error || !data || data.files.length === 0) return null;
33
+
34
+ return (
35
+ <Card.Root bg="var(--color-bg-card)" border="1px solid" borderColor="var(--color-border)">
36
+ <Card.Header pb={0}>
37
+ <HStack justify="space-between" flexWrap="wrap" gap={2}>
38
+ <Heading size="md">Reports & artifacts</Heading>
39
+ <Text fontSize="xs" color="var(--color-text-muted)">
40
+ {data.folders.map((f) => `${f}/`).join(', ')} of the job folder
41
+ {data.sandboxed ? ' · reports run sandboxed' : ''}
42
+ {data.truncated ? ' · first files only' : ''}
43
+ </Text>
44
+ </HStack>
45
+ </Card.Header>
46
+ <Card.Body>
47
+ <Table.Root size="sm" variant="line">
48
+ <Table.Body>
49
+ {data.files.map((file) => {
50
+ const url = jobArtifactUrl(jrJobId, file.path);
51
+ return (
52
+ <Table.Row key={file.path} borderColor="var(--color-border)">
53
+ <Table.Cell borderColor="var(--color-border)">
54
+ <HStack gap={2}>
55
+ {file.report && <LuFileText />}
56
+ <Link
57
+ href={url}
58
+ target="_blank"
59
+ rel="noopener noreferrer"
60
+ fontFamily="mono"
61
+ fontSize="sm"
62
+ color="var(--color-primary)"
63
+ {...(file.report ? {} : { download: file.path.split('/').pop() })}
64
+ >
65
+ {file.path}
66
+ </Link>
67
+ {file.report && <Badge size="sm" colorPalette="blue">report</Badge>}
68
+ </HStack>
69
+ </Table.Cell>
70
+ <Table.Cell borderColor="var(--color-border)" color="var(--color-text-muted)" fontSize="xs" whiteSpace="nowrap">
71
+ {formatSize(file.size)}
72
+ </Table.Cell>
73
+ <Table.Cell borderColor="var(--color-border)" color="var(--color-text-muted)" fontSize="xs" whiteSpace="nowrap">
74
+ {new Date(file.mtime * 1000).toLocaleString()}
75
+ </Table.Cell>
76
+ <Table.Cell borderColor="var(--color-border)" textAlign="end">
77
+ <Box as="span" color="var(--color-text-muted)" title={file.report ? 'Open in a new tab' : 'Download'}>
78
+ {file.report ? <LuExternalLink /> : <LuDownload />}
79
+ </Box>
80
+ </Table.Cell>
81
+ </Table.Row>
82
+ );
83
+ })}
84
+ </Table.Body>
85
+ </Table.Root>
86
+ </Card.Body>
87
+ </Card.Root>
88
+ );
89
+ };
@@ -2,6 +2,7 @@ import React, { useState } from 'react';
2
2
  import { useParams, useNavigate, Link } from 'react-router-dom';
3
3
  import { useBujangPaths } from '../context';
4
4
  import { usePageTitle } from '../hooks/usePageTitle';
5
+ import { JobArtifactsCard } from './JobArtifacts';
5
6
  import {
6
7
  Box,
7
8
  Heading,
@@ -294,6 +295,8 @@ export const JobDetailsView: React.FC = () => {
294
295
  </Card.Body>
295
296
  </Card.Root>
296
297
 
298
+ {jrJobId && <JobArtifactsCard jrJobId={jrJobId} />}
299
+
297
300
  {/* Job Details Tabs */}
298
301
  <Card.Root bg="var(--color-bg-card)" border="1px solid" borderColor="var(--color-border)">
299
302
  <Card.Body>
@@ -575,10 +575,10 @@ export const JobSubmissionForm: React.FC<JobSubmissionFormProps> = ({
575
575
  return;
576
576
  }
577
577
 
578
- // No initialData: apply the selection of the URL, else the form defaults, once
579
- // profiles/templates are available.
580
- const defaultProfile = urlSelection.profile ?? (urlSelection.cluster ? '' : '1x8xA100l');
581
- const defaultTemplate = urlSelection.template ?? 'shared_run.sh';
578
+ // No initialData: apply the profile / template the URL selects, once they are loaded.
579
+ // No URL selection: nothing is preselected.
580
+ const defaultProfile = urlSelection.profile ?? '';
581
+ const defaultTemplate = urlSelection.template ?? '';
582
582
 
583
583
  if (!defaultProfileApplied.current && clusterProfiles.some(p => p.name === defaultProfile) && !selectedProfile) {
584
584
  handleProfileSelect(defaultProfile);
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
- import { Link, useNavigate } from 'react-router-dom';
2
+ import { Link, useNavigate, useSearchParams } from 'react-router-dom';
3
3
  import { useBujangPaths } from '../context';
4
4
  import {
5
5
  Box,
@@ -14,6 +14,8 @@ import {
14
14
  Spinner,
15
15
  Alert,
16
16
  IconButton,
17
+ Group,
18
+ NativeSelect,
17
19
  } from '@chakra-ui/react';
18
20
  import { toaster } from '../toast';
19
21
  import { Tooltip } from '../components/tooltip';
@@ -26,6 +28,7 @@ import {
26
28
  LuCircleCheck,
27
29
  LuTriangleAlert,
28
30
  LuClock,
31
+ LuTimer,
29
32
  } from 'react-icons/lu';
30
33
  import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
31
34
  import {
@@ -34,8 +37,11 @@ import {
34
37
  cancelSlurmJob,
35
38
  rerunSlurmJob,
36
39
  getSlurmClusterStatus,
40
+ getOrganizers,
41
+ getSyncStatus,
42
+ syncNow,
37
43
  } from '../api';
38
- import type { SlurmJob, PersitedJobInfo, ApiError } from '../types';
44
+ import type { SlurmJob, PersitedJobInfo, ApiError, OrganizerGroups, SyncStatus } from '../types';
39
45
  import { usePageTitle } from '../hooks/usePageTitle';
40
46
  import { AgentBadge } from './AgentActivityView';
41
47
  import { NO_JOB_ID, NO_JOB_STATE, NO_JR_JOB_ID } from '../constants';
@@ -83,6 +89,69 @@ const getStatusIcon = (status: string) => {
83
89
  }
84
90
  };
85
91
 
92
+ const AUTO_REFRESH_KEY = 'bujang-jobs-auto-refresh';
93
+ const AUTO_REFRESH_MS = 30_000;
94
+
95
+ function readAutoRefresh(): boolean {
96
+ try {
97
+ return localStorage.getItem(AUTO_REFRESH_KEY) === '1';
98
+ } catch {
99
+ return false;
100
+ }
101
+ }
102
+
103
+ /** "12s ago", "3 min ago" */
104
+ const ago = (ts: number | null | undefined, now: number): string => {
105
+ if (!ts) return 'never';
106
+ const s = Math.max(0, Math.round(now / 1000 - ts));
107
+ if (s < 60) return `${s}s ago`;
108
+ if (s < 3600) return `${Math.round(s / 60)} min ago`;
109
+ return `${Math.round(s / 3600)} h ago`;
110
+ };
111
+
112
+ /** "clusters" -> "cluster": the label of an organizer's filter */
113
+ const filterLabel = (name: string) => (name.length > 3 && name.endsWith('s') ? name.slice(0, -1) : name);
114
+
115
+ /** One dropdown per organizer folder (clusters, experiments, ...) with its values; the choice is in the URL */
116
+ const OrganizerFilters: React.FC<{
117
+ organizers: OrganizerGroups[];
118
+ selected: Record<string, string>;
119
+ onChange: (name: string, value: string) => void;
120
+ onClear: () => void;
121
+ }> = ({ organizers, selected, onChange, onClear }) => {
122
+ const shown = organizers.filter((o) => o.groups.length > 0 || selected[o.name]);
123
+ if (shown.length === 0) return null;
124
+ return (
125
+ <HStack gap={4} flexWrap="wrap">
126
+ {shown.map((o) => (
127
+ <HStack key={o.name} gap={2}>
128
+ <Text fontSize="sm" color="var(--color-text-muted)">{filterLabel(o.name)}:</Text>
129
+ <NativeSelect.Root size="sm" w="auto" minW="140px">
130
+ <NativeSelect.Field
131
+ value={selected[o.name] ?? ''}
132
+ onChange={(e) => onChange(o.name, e.target.value)}
133
+ aria-label={`Filter by ${filterLabel(o.name)}`}
134
+ borderColor={selected[o.name] ? 'var(--color-primary)' : undefined}
135
+ >
136
+ <option value="">all</option>
137
+ {o.groups.map((g) => (
138
+ <option key={g.value} value={g.value}>{g.value} ({g.jobs.length})</option>
139
+ ))}
140
+ {selected[o.name] && !o.groups.some((g) => g.value === selected[o.name]) && (
141
+ <option value={selected[o.name]}>{selected[o.name]} (0)</option>
142
+ )}
143
+ </NativeSelect.Field>
144
+ <NativeSelect.Indicator />
145
+ </NativeSelect.Root>
146
+ </HStack>
147
+ ))}
148
+ {Object.keys(selected).length > 0 && (
149
+ <Button size="xs" variant="ghost" onClick={onClear} color="var(--color-text-muted)">Clear filters</Button>
150
+ )}
151
+ </HStack>
152
+ );
153
+ };
154
+
86
155
  export const JobsView: React.FC<JobsViewProps> = () => {
87
156
  usePageTitle('Jobs');
88
157
 
@@ -102,12 +171,24 @@ export const JobsView: React.FC<JobsViewProps> = () => {
102
171
  };
103
172
 
104
173
 
174
+ const [autoRefresh, setAutoRefresh] = React.useState(readAutoRefresh);
175
+ const toggleAutoRefresh = (on: boolean) => {
176
+ try {
177
+ localStorage.setItem(AUTO_REFRESH_KEY, on ? '1' : '0');
178
+ } catch {
179
+ // private mode: for this page only
180
+ }
181
+ setAutoRefresh(on);
182
+ };
183
+ const refetchInterval = autoRefresh ? AUTO_REFRESH_MS : false;
184
+
105
185
  // Queries
106
186
  const { data: activeJobsData, isLoading: activeJobsLoading, error: activeJobsError } = useQuery({
107
187
  queryKey: ['slurm-jobs'],
108
188
  queryFn: getSlurmJobs,
109
189
  refetchOnWindowFocus: false,
110
190
  staleTime: 30000, // Consider data fresh for 30 seconds
191
+ refetchInterval,
111
192
  });
112
193
 
113
194
  const { data: persistedJobsData, isLoading: persistedJobsLoading, error: persistedJobsError } = useQuery<PersitedJobInfo[]>({
@@ -115,6 +196,44 @@ export const JobsView: React.FC<JobsViewProps> = () => {
115
196
  queryFn: getSlurmPersistedJobs,
116
197
  refetchOnWindowFocus: false,
117
198
  staleTime: 30000, // Consider data fresh for 30 seconds
199
+ refetchInterval,
200
+ });
201
+
202
+ const { data: sync } = useQuery<SyncStatus>({
203
+ queryKey: ['bujang-sync'],
204
+ queryFn: getSyncStatus,
205
+ refetchOnWindowFocus: false,
206
+ refetchInterval: 10_000,
207
+ retry: false,
208
+ });
209
+ // re-render the "synced 12s ago" every few seconds
210
+ const [now, setNow] = React.useState(() => Date.now());
211
+ React.useEffect(() => {
212
+ const timer = window.setInterval(() => setNow(Date.now()), 5000);
213
+ return () => window.clearInterval(timer);
214
+ }, []);
215
+
216
+ const refresh = useMutation({
217
+ mutationFn: syncNow,
218
+ onSettled: () => {
219
+ queryClient.invalidateQueries({ queryKey: ['slurm-jobs'] });
220
+ queryClient.invalidateQueries({ queryKey: ['slurm-persisted-jobs'] });
221
+ queryClient.invalidateQueries({ queryKey: ['slurm-cluster-status'] });
222
+ queryClient.invalidateQueries({ queryKey: ['bujang-organizers'] });
223
+ queryClient.invalidateQueries({ queryKey: ['bujang-sync'] });
224
+ },
225
+ onError: (error: ApiError) => {
226
+ toaster.create({ title: 'Sync failed', description: error.message, type: 'error', duration: 6000 });
227
+ },
228
+ });
229
+
230
+ const { data: organizers = [] } = useQuery<OrganizerGroups[]>({
231
+ queryKey: ['bujang-organizers'],
232
+ queryFn: getOrganizers,
233
+ refetchOnWindowFocus: false,
234
+ staleTime: 30000,
235
+ refetchInterval,
236
+ retry: false,
118
237
  });
119
238
 
120
239
  const { data: clusterStatus, isLoading: clusterStatusLoading } = useQuery({
@@ -126,9 +245,45 @@ export const JobsView: React.FC<JobsViewProps> = () => {
126
245
  retry: false, // Don't retry on error to avoid excessive requests when cluster is down
127
246
  });
128
247
 
248
+ // ?clusters=mila&experiments=lr-sweep: the jobs under every chosen value
249
+ const [params, setParams] = useSearchParams();
250
+ const organizerNames = React.useMemo(() => organizers.map((o) => o.name), [organizers]);
251
+ const selected = React.useMemo(() => {
252
+ const out: Record<string, string> = {};
253
+ for (const name of organizerNames) {
254
+ const value = params.get(name);
255
+ if (value) out[name] = value;
256
+ }
257
+ return out;
258
+ }, [params, organizerNames]);
259
+ const allowed = React.useMemo(() => {
260
+ const sets = Object.entries(selected).map(([name, value]) => {
261
+ const group = organizers.find((o) => o.name === name)?.groups.find((g) => g.value === value);
262
+ return new Set<string>(group?.jobs ?? []);
263
+ });
264
+ if (sets.length === 0) return null;
265
+ const [first, ...rest] = sets;
266
+ return new Set<string>([...first].filter((id) => rest.every((set) => set.has(id))));
267
+ }, [selected, organizers]);
268
+ const setFilter = (name: string, value: string) => {
269
+ const next = new URLSearchParams(params);
270
+ if (value) next.set(name, value);
271
+ else next.delete(name);
272
+ setParams(next, { replace: true });
273
+ };
274
+ const clearFilters = () => {
275
+ const next = new URLSearchParams(params);
276
+ organizerNames.forEach((name) => next.delete(name));
277
+ setParams(next, { replace: true });
278
+ };
279
+
129
280
  // Separate active jobs and persisted jobs
130
- const activeJobs = activeJobsData || [];
131
- const persistedJobs = persistedJobsData || [];
281
+ const allActiveJobs = activeJobsData || [];
282
+ const allPersistedJobs = persistedJobsData || [];
283
+ const activeJobs = allowed ? allActiveJobs.filter((job: SlurmJob) => !!job.jr_job_id && allowed.has(job.jr_job_id)) : allActiveJobs;
284
+ const persistedJobs = allowed ? allPersistedJobs.filter((job) => allowed.has(job.name)) : allPersistedJobs;
285
+ const countLabel = (shown: number, total: number) =>
286
+ `${allowed ? `${shown} of ${total}` : shown} ${total === 1 ? 'job' : 'jobs'}`;
132
287
 
133
288
 
134
289
 
@@ -255,7 +410,7 @@ export const JobsView: React.FC<JobsViewProps> = () => {
255
410
  )}
256
411
  </HStack>
257
412
 
258
- <HStack gap={2}>
413
+ <HStack gap={3}>
259
414
  <Button
260
415
  onClick={() => navigate(paths.submitJob())}
261
416
  size="sm"
@@ -268,24 +423,59 @@ export const JobsView: React.FC<JobsViewProps> = () => {
268
423
  Submit New Job
269
424
  </Button>
270
425
 
271
- <Button
272
- variant="outline"
273
- onClick={() => {
274
- queryClient.invalidateQueries({ queryKey: ['slurm-jobs'] });
275
- queryClient.invalidateQueries({ queryKey: ['slurm-persisted-jobs'] });
276
- queryClient.invalidateQueries({ queryKey: ['slurm-cluster-status'] });
277
- }}
278
- loading={activeJobsLoading || persistedJobsLoading || clusterStatusLoading}
279
- size="sm"
280
- fontWeight="medium"
281
- >
282
- <LuRefreshCw style={{ marginRight: '4px', fontSize: '16px' }} />
283
- Refresh
284
- </Button>
426
+ {/* Refresh and its auto refresh toggle as one control; the sync time hangs below it
427
+ (absolute: it does not move the buttons) */}
428
+ <Box position="relative">
429
+ <Group attached>
430
+ <Button
431
+ variant="outline"
432
+ onClick={() => refresh.mutate()}
433
+ title="rsync the clusters with active jobs now"
434
+ loading={refresh.isPending || activeJobsLoading || persistedJobsLoading || clusterStatusLoading}
435
+ size="sm"
436
+ fontWeight="medium"
437
+ >
438
+ <LuRefreshCw style={{ marginRight: '4px', fontSize: '16px' }} />
439
+ Refresh
440
+ </Button>
441
+ <Button
442
+ variant={autoRefresh ? 'solid' : 'outline'}
443
+ bg={autoRefresh ? 'var(--color-primary)' : undefined}
444
+ color={autoRefresh ? 'var(--color-primary-text)' : 'var(--color-text-muted)'}
445
+ _hover={autoRefresh ? { bg: 'var(--color-primary-hover)' } : undefined}
446
+ onClick={() => toggleAutoRefresh(!autoRefresh)}
447
+ aria-pressed={autoRefresh}
448
+ aria-label="Auto refresh every 30 seconds"
449
+ title={autoRefresh ? 'Auto refresh is on (every 30s): click to stop' : 'Refresh the jobs every 30 seconds'}
450
+ size="sm"
451
+ px={2}
452
+ fontWeight="medium"
453
+ >
454
+ <LuTimer style={{ fontSize: '16px' }} />
455
+ 30s
456
+ </Button>
457
+ </Group>
458
+ {sync && (
459
+ <Text
460
+ position="absolute"
461
+ top="100%"
462
+ right={0}
463
+ mt={0.5}
464
+ fontSize="xs"
465
+ color="var(--color-text-muted)"
466
+ whiteSpace="nowrap"
467
+ title={sync.interval ? `The server syncs the clusters with active jobs every ${sync.interval}s` : undefined}
468
+ >
469
+ synced {ago(sync.last ?? sync.scanned, now)}
470
+ </Text>
471
+ )}
472
+ </Box>
285
473
  </HStack>
286
474
  </HStack>
287
475
  </Box>
288
476
 
477
+ <OrganizerFilters organizers={organizers} selected={selected} onChange={setFilter} onClear={clearFilters} />
478
+
289
479
  {/* Active Jobs Table */}
290
480
  <Card.Root
291
481
  bg="var(--color-bg-card)"
@@ -314,7 +504,7 @@ export const JobsView: React.FC<JobsViewProps> = () => {
314
504
  px={2}
315
505
  py={1}
316
506
  >
317
- {activeJobs.length} {activeJobs.length === 1 ? 'job' : 'jobs'}
507
+ {countLabel(activeJobs.length, allActiveJobs.length)}
318
508
  </Badge>
319
509
  </HStack>
320
510
  </Card.Header>
@@ -506,7 +696,7 @@ export const JobsView: React.FC<JobsViewProps> = () => {
506
696
  px={2}
507
697
  py={1}
508
698
  >
509
- {persistedJobs.length} {persistedJobs.length === 1 ? 'job' : 'jobs'}
699
+ {countLabel(persistedJobs.length, allPersistedJobs.length)}
510
700
  </Badge>
511
701
  </HStack>
512
702
  </Card.Header>