@milabench/bujang 0.1.15 → 0.1.17

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.
@@ -1,10 +1,12 @@
1
1
  /** The panels of a job's Overview layout: the log view and the charts, and the bar saying where the layout comes from. */
2
- import React, { useMemo, useState } from 'react';
3
- import { Alert, Badge, Box, Button, Card, Code, HStack, Input, Spinner, Text, VStack, Wrap } from '@chakra-ui/react';
4
- import { useQuery } from '@tanstack/react-query';
5
- import { LuArrowDown, LuArrowUp, LuX } from 'react-icons/lu';
6
- import { getJobDataRows } from '../api';
7
- import type { ApiError, JobData, JobOverviewLayout, OverviewLayout, OverviewPanel } from '../types';
2
+ import React, { createContext, useContext, useEffect, useMemo, useState } from 'react';
3
+ import { Alert, Badge, Box, Button, Card, Code, Dialog, Flex, HStack, Input, NativeSelect, Spinner, Table, Text, VStack, Wrap } from '@chakra-ui/react';
4
+ import { useQueries, useQuery } from '@tanstack/react-query';
5
+ import { LuArrowDown, LuArrowLeft, LuArrowRight, LuArrowUp, LuChevronDown, LuChevronRight, LuColumns2, LuDownload, LuExternalLink, LuFile, LuFolder, LuPlus, LuSettings, LuX } from 'react-icons/lu';
6
+ import { getJobArtifacts, getJobDataRows, jobArtifactUrl } from '../api';
7
+ import type { ApiError, ColumnsPanel, JobArtifacts, JobData, JobOverviewLayout, OverviewBlock, OverviewLayout, OverviewPanel, StatName, StatsMetric } from '../types';
8
+ import { MonacoEditor } from '../components/MonacoEditor';
9
+ import { formatSize } from './JobArtifacts';
8
10
  import {
9
11
  FILE_FIELDS,
10
12
  ROW_LIMIT,
@@ -14,6 +16,7 @@ import {
14
16
  filesWithEvent,
15
17
  guessBuilder,
16
18
  mergeFields,
19
+ panelEvents,
17
20
  panelFiles,
18
21
  specFields,
19
22
  } from './dataCharts';
@@ -27,6 +30,19 @@ const splitFiles = (files?: string) => {
27
30
  return list.length ? list : undefined;
28
31
  };
29
32
 
33
+ /** The panels read the files of one rank only */
34
+ const OneRank = createContext(false);
35
+
36
+ /** The files a panel asks the rows of: those of its patterns (all: undefined), of the picked rank when there is one */
37
+ const useQueryFiles = (files: JobData['files'], patterns?: string): string[] | undefined => {
38
+ const oneRank = useContext(OneRank);
39
+ return useMemo(() => {
40
+ if (!oneRank) return splitFiles(patterns);
41
+ const paths = panelFiles(files, patterns).map((f) => f.path);
42
+ return paths.length ? paths : ['-']; // no file: not all of them
43
+ }, [oneRank, files, patterns]);
44
+ };
45
+
30
46
  const levelColor = (level: string) => {
31
47
  if (/^(error|critical|fatal)$/i.test(level)) return 'var(--color-status-failed)';
32
48
  if (/^warn/i.test(level)) return 'var(--color-status-pending)';
@@ -40,16 +56,38 @@ const clock = (time: unknown) => {
40
56
  return Number.isNaN(d.getTime()) ? '' : d.toLocaleTimeString([], { hour12: false });
41
57
  };
42
58
 
43
- /** Title, kind and (when editing) the move / remove buttons of a panel */
59
+ type ChartBlock = Extract<OverviewBlock, { kind: 'chart' }>;
60
+
61
+ /** What can be done with a block of the layout; the moves are absent where they lead nowhere */
62
+ interface BlockActions {
63
+ editing: boolean;
64
+ onMove: (by: number) => void;
65
+ onRemove: () => void;
66
+ /** to the column on the left / right */
67
+ onShift?: (by: number) => void;
68
+ /** put the block in the first of two columns */
69
+ onSplit?: () => void;
70
+ onChange: (block: OverviewBlock) => void;
71
+ /** an editor of the block opens or closes */
72
+ onEditor: (open: boolean) => void;
73
+ }
74
+
75
+ /** Whether the editor of a block is open, told to the page */
76
+ const useEditor = (onEditor: (open: boolean) => void): [boolean, (open: boolean) => void] => {
77
+ const [open, setOpen] = useState(false);
78
+ return [open, (next) => { setOpen(next); onEditor(next); }];
79
+ };
80
+
81
+ /** Title, kind, the gear of a chart and (when editing) the move / remove buttons of a block */
44
82
  const PanelFrame: React.FC<{
45
83
  title: string;
46
84
  kind: string;
47
85
  info?: React.ReactNode;
48
- editing: boolean;
49
- onMove: (by: number) => void;
50
- onRemove: () => void;
86
+ actions: BlockActions;
87
+ onSettings?: () => void;
88
+ settingsTitle?: string;
51
89
  children: React.ReactNode;
52
- }> = ({ title, kind, info, editing, onMove, onRemove, children }) => (
90
+ }> = ({ title, kind, info, actions: { editing, onMove, onRemove, onShift, onSplit }, onSettings, settingsTitle = 'Edit the Vega-Lite spec', children }) => (
53
91
  <Card.Root {...cardProps}>
54
92
  <Card.Header py={2}>
55
93
  <HStack justify="space-between">
@@ -58,32 +96,59 @@ const PanelFrame: React.FC<{
58
96
  <Badge size="xs" variant="subtle">{kind}</Badge>
59
97
  <HStack gap={2} fontSize="xs" color="var(--color-text-muted)">{info}</HStack>
60
98
  </HStack>
61
- {editing && (
62
- <HStack gap={0}>
63
- <Button size="2xs" variant="ghost" onClick={() => onMove(-1)} title="Move up"><LuArrowUp /></Button>
64
- <Button size="2xs" variant="ghost" onClick={() => onMove(1)} title="Move down"><LuArrowDown /></Button>
65
- <Button size="2xs" variant="ghost" onClick={onRemove} title="Remove from the layout"><LuX /></Button>
66
- </HStack>
67
- )}
99
+ <HStack gap={0}>
100
+ {onSettings && (
101
+ <Button size="2xs" variant="ghost" onClick={onSettings} title={settingsTitle} aria-label={settingsTitle}>
102
+ <LuSettings />
103
+ </Button>
104
+ )}
105
+ {editing && (
106
+ <>
107
+ {onShift && (
108
+ <>
109
+ <Button size="2xs" variant="ghost" onClick={() => onShift(-1)} title="To the column on the left"><LuArrowLeft /></Button>
110
+ <Button size="2xs" variant="ghost" onClick={() => onShift(1)} title="To the column on the right"><LuArrowRight /></Button>
111
+ </>
112
+ )}
113
+ {onSplit && (
114
+ <Button size="2xs" variant="ghost" onClick={onSplit} title="Split into two columns"><LuColumns2 /></Button>
115
+ )}
116
+ <Button size="2xs" variant="ghost" onClick={() => onMove(-1)} title="Move up"><LuArrowUp /></Button>
117
+ <Button size="2xs" variant="ghost" onClick={() => onMove(1)} title="Move down"><LuArrowDown /></Button>
118
+ <Button size="2xs" variant="ghost" onClick={onRemove} title="Remove from the layout"><LuX /></Button>
119
+ </>
120
+ )}
121
+ </HStack>
68
122
  </HStack>
69
123
  </Card.Header>
70
124
  <Card.Body pt={0}>{children}</Card.Body>
71
125
  </Card.Root>
72
126
  );
73
127
 
74
- type PanelProps<K extends OverviewPanel['kind']> = {
128
+ type PanelProps<K extends OverviewBlock['kind']> = {
75
129
  jrJobId: string;
76
130
  files: JobData['files'];
77
- panel: Extract<OverviewPanel, { kind: K }>;
78
- editing: boolean;
79
- onMove: (by: number) => void;
80
- onRemove: () => void;
131
+ panel: Extract<OverviewBlock, { kind: K }>;
132
+ actions: BlockActions;
81
133
  };
82
134
 
83
- /** The log view: the rows of role `log` (the `logging` records of the job) */
84
- export const LogPanel: React.FC<PanelProps<'logs'>> = ({ jrJobId, panel, editing, onMove, onRemove }) => {
85
- const query = { roles: ['log' as const], files: splitFiles(panel.files), limit: LOG_LIMIT };
86
- const { data: rows, isFetching, error } = useQuery<Record<string, unknown>[], ApiError>({
135
+ /** The event types shown at first: a type with more rows (the timings of each batch) is a click away */
136
+ const EVENTS_SHOWN = 500;
137
+
138
+ /** The keys of a row around the values of its event */
139
+ const ROW_KEYS = new Set(['time', 'type', '_file', '_name']);
140
+
141
+ const eventText = (row: Record<string, unknown>) =>
142
+ Object.entries(row)
143
+ .filter(([key]) => !ROW_KEYS.has(key))
144
+ .map(([key, value]) => `${key}=${typeof value === 'number' && !Number.isInteger(value) ? +(Math.abs(value) < 1e5 ? value.toPrecision(6) : value.toFixed(3)) : typeof value === 'object' ? JSON.stringify(value) : String(value)}`)
145
+ .join(' ');
146
+
147
+ /** The log view: the rows of role `log` (the `logging` records of the job), and its events when asked */
148
+ export const LogPanel: React.FC<PanelProps<'logs'>> = ({ jrJobId, files, panel, actions }) => {
149
+ const queryFiles = useQueryFiles(files, panel.files);
150
+ const query = { roles: ['log' as const], files: queryFiles, limit: LOG_LIMIT };
151
+ const { data: rows, isFetching, error: logError } = useQuery<Record<string, unknown>[], ApiError>({
87
152
  queryKey: ['bujang-job-data-rows', jrJobId, query],
88
153
  queryFn: () => getJobDataRows(jrJobId, query),
89
154
  staleTime: 30_000,
@@ -96,24 +161,51 @@ export const LogPanel: React.FC<PanelProps<'logs'>> = ({ jrJobId, panel, editing
96
161
  const [levels, setLevels] = useState<string[] | null>(panel.levels ?? null);
97
162
  const [search, setSearch] = useState('');
98
163
  const [open, setOpen] = useState<number | null>(null);
164
+
165
+ // the events: their types, and the rows of those picked
166
+ const [withEvents, setWithEvents] = useState(false);
167
+ const types = useMemo(() => {
168
+ const counts = new Map<string, number>();
169
+ panelFiles(files, panel.files).forEach((f) => f.events?.forEach((e) => {
170
+ if (e.role !== 'log' && e.event) counts.set(e.event, (counts.get(e.event) || 0) + e.count);
171
+ }));
172
+ return [...counts.entries()];
173
+ }, [files, panel.files]);
174
+ const [pickedTypes, setPickedTypes] = useState<string[] | null>(null);
175
+ const activeTypes = pickedTypes ?? types.filter(([, count]) => count <= EVENTS_SHOWN).map(([type]) => type);
176
+ const eventQuery = { events: activeTypes, files: queryFiles, limit: LOG_LIMIT };
177
+ const eventsOn = withEvents && activeTypes.length > 0;
178
+ const { data: eventRows, isFetching: eventsFetching, error: eventError } = useQuery<Record<string, unknown>[], ApiError>({
179
+ queryKey: ['bujang-job-data-rows', jrJobId, eventQuery],
180
+ queryFn: () => getJobDataRows(jrJobId, eventQuery),
181
+ enabled: eventsOn,
182
+ staleTime: 30_000,
183
+ placeholderData: (previous) => previous,
184
+ });
185
+ const error = logError ?? eventError;
186
+
187
+ const all = useMemo(() => {
188
+ const logs = (rows || [])
189
+ .filter((r) => levels === null || levels.includes(String(r.level ?? '')))
190
+ .map((row) => ({ row, event: false, text: `${row.logger ?? ''} ${row.message ?? ''}` }));
191
+ const events = (eventsOn ? eventRows || [] : []).map((row) => ({ row, event: true, text: `${row.type ?? ''} ${eventText(row)}` }));
192
+ return [...logs, ...events].sort((a, b) => (Number(a.row.time) || 0) - (Number(b.row.time) || 0));
193
+ }, [rows, levels, eventsOn, eventRows]);
99
194
  const shown = useMemo(() => {
100
195
  const needle = search.trim().toLowerCase();
101
- return (rows || [])
102
- .filter((r) => levels === null || levels.includes(String(r.level ?? '')))
103
- .filter((r) => !needle || `${r.logger ?? ''} ${r.message ?? ''}`.toLowerCase().includes(needle))
104
- .sort((a, b) => (Number(a.time) || 0) - (Number(b.time) || 0));
105
- }, [rows, levels, search]);
196
+ return needle ? all.filter((item) => item.text.toLowerCase().includes(needle)) : all;
197
+ }, [all, search]);
198
+ const total = (rows?.length || 0) + (eventsOn ? eventRows?.length || 0 : 0);
199
+ const truncated = (rows?.length || 0) >= LOG_LIMIT || (eventsOn && (eventRows?.length || 0) >= LOG_LIMIT);
106
200
 
107
201
  return (
108
202
  <PanelFrame
109
203
  title={panel.title || 'Logs'}
110
204
  kind="logs"
111
- editing={editing}
112
- onMove={onMove}
113
- onRemove={onRemove}
205
+ actions={actions}
114
206
  info={<>
115
- {isFetching && <Spinner size="xs" />}
116
- {rows && <Text>{shown.length} / {rows.length}{rows.length >= LOG_LIMIT ? '+' : ''} records</Text>}
207
+ {(isFetching || eventsFetching) && <Spinner size="xs" />}
208
+ {rows && <Text>{shown.length} / {total}{truncated ? '+' : ''} records</Text>}
117
209
  </>}
118
210
  >
119
211
  <Wrap gap={1} mb={2} align="center">
@@ -134,18 +226,46 @@ export const LogPanel: React.FC<PanelProps<'logs'>> = ({ jrJobId, panel, editing
134
226
  );
135
227
  })}
136
228
  {levels !== null && <Button size="2xs" variant="ghost" onClick={() => setLevels(null)}>all levels</Button>}
137
- <Input size="xs" w="220px" placeholder="search logger / message" value={search} onChange={(e) => setSearch(e.target.value)} />
229
+ {types.length > 0 && (
230
+ <Button
231
+ size="2xs"
232
+ variant={withEvents ? 'solid' : 'outline'}
233
+ aria-pressed={withEvents}
234
+ onClick={() => setWithEvents(!withEvents)}
235
+ title="Show the events of the job among the messages"
236
+ >
237
+ events
238
+ </Button>
239
+ )}
240
+ <Input size="xs" w="220px" placeholder={withEvents ? 'search messages / events' : 'search logger / message'} value={search} onChange={(e) => setSearch(e.target.value)} />
138
241
  </Wrap>
242
+ {withEvents && (
243
+ <Wrap gap={1} mb={2} align="center">
244
+ {types.map(([type, count]) => {
245
+ const on = activeTypes.includes(type);
246
+ return (
247
+ <Button
248
+ key={type}
249
+ size="2xs"
250
+ variant={on ? 'subtle' : 'outline'}
251
+ onClick={() => setPickedTypes(on ? activeTypes.filter((t) => t !== type) : [...activeTypes, type])}
252
+ >
253
+ {type} <Badge size="xs" variant="subtle">{count}</Badge>
254
+ </Button>
255
+ );
256
+ })}
257
+ </Wrap>
258
+ )}
139
259
  {error && (
140
260
  <Alert.Root status="error" mb={2}><Alert.Indicator /><Alert.Description>{error.message}</Alert.Description></Alert.Root>
141
261
  )}
142
- {rows && !rows.length && (
262
+ {rows && !rows.length && !eventsOn && (
143
263
  <Text fontSize="sm" color="var(--color-text-muted)">
144
- No log records. A job writes them with <Code>bujang.logs.setup_jsonl()</Code>.
264
+ No log records. A job writes them with <Code>bujang.instrumentation.setup_jsonl()</Code>.
145
265
  </Text>
146
266
  )}
147
267
  <Box maxH="360px" overflowY="auto" fontFamily="mono" fontSize="xs">
148
- {shown.map((r, i) => (
268
+ {shown.map(({ row: r, event }, i) => (
149
269
  <Box
150
270
  key={i}
151
271
  py="1px"
@@ -156,10 +276,18 @@ export const LogPanel: React.FC<PanelProps<'logs'>> = ({ jrJobId, panel, editing
156
276
  >
157
277
  <HStack gap={2} align="start">
158
278
  <Text color="var(--color-text-muted)" flexShrink={0}>{clock(r.time)}</Text>
159
- <Text color={levelColor(String(r.level ?? ''))} w="60px" flexShrink={0}>{String(r.level ?? '')}</Text>
160
- <Text color="var(--color-text-muted)" flexShrink={0}>{String(r.logger ?? '')}</Text>
279
+ <Text
280
+ color={event ? 'var(--color-primary)' : levelColor(String(r.level ?? ''))}
281
+ w="60px"
282
+ flexShrink={0}
283
+ truncate
284
+ title={event ? String(r.type ?? '') : undefined}
285
+ >
286
+ {String((event ? r.type : r.level) ?? '')}
287
+ </Text>
288
+ {!event && <Text color="var(--color-text-muted)" flexShrink={0}>{String(r.logger ?? '')}</Text>}
161
289
  <Text whiteSpace="pre-wrap" wordBreak="break-word">
162
- {String(r.message ?? '')}{r.exception ? ' ▸' : ''}
290
+ {event ? eventText(r) : String(r.message ?? '')}{r.exception ? ' ▸' : ''}
163
291
  </Text>
164
292
  </HStack>
165
293
  {open === i && !!r.exception && (
@@ -172,8 +300,494 @@ export const LogPanel: React.FC<PanelProps<'logs'>> = ({ jrJobId, panel, editing
172
300
  );
173
301
  };
174
302
 
175
- /** A chart of an event: the panel's Vega-Lite spec, else its builder fields, else guessed ones */
176
- export const ChartPanel: React.FC<PanelProps<'chart'>> = ({ jrJobId, files, panel, editing, onMove, onRemove }) => {
303
+ /** Media shown before "show more" */
304
+ const MEDIA_PAGE = 24;
305
+ const isMedia = (type: string) => /^(image|audio|video)\//.test(type);
306
+
307
+ /** The images, sounds and videos of the artifact folders (output/, results/, ...) */
308
+ export const ArtifactPanel: React.FC<PanelProps<'artifacts'>> = ({ jrJobId, panel, actions }) => {
309
+ const { data, isFetching, error } = useQuery<JobArtifacts, ApiError>({
310
+ queryKey: ['bujang-job-artifacts', jrJobId],
311
+ queryFn: () => getJobArtifacts(jrJobId),
312
+ staleTime: 30_000,
313
+ retry: false,
314
+ });
315
+ const [shown, setShown] = useState(MEDIA_PAGE);
316
+ const [patterns, setPatterns] = useState(panel.files ?? '');
317
+ const media = useMemo(
318
+ () => panelFiles((data?.files || []).filter((f) => isMedia(f.media_type)), panel.files),
319
+ [data, panel.files],
320
+ );
321
+ const setFiles = () => {
322
+ const { files: _files, ...rest } = panel;
323
+ const value = patterns.trim();
324
+ if (value !== (panel.files ?? '')) actions.onChange(value ? { ...rest, files: value } : rest);
325
+ };
326
+ return (
327
+ <PanelFrame
328
+ title={panel.title || 'Artifacts'}
329
+ kind="artifacts"
330
+ actions={actions}
331
+ info={<>
332
+ {isFetching && <Spinner size="xs" />}
333
+ {data && <Text>{media.length} file{media.length === 1 ? '' : 's'}{data.truncated ? ' (first files only)' : ''}</Text>}
334
+ </>}
335
+ >
336
+ {actions.editing && (
337
+ <Input
338
+ size="xs"
339
+ maxW="320px"
340
+ mb={2}
341
+ placeholder="files: paths or globs (output/*.png), all when empty"
342
+ value={patterns}
343
+ onChange={(e) => setPatterns(e.target.value)}
344
+ onBlur={setFiles}
345
+ onKeyDown={(e) => { if (e.key === 'Enter') setFiles(); }}
346
+ />
347
+ )}
348
+ {error && (
349
+ <Alert.Root status="error" mb={2}><Alert.Indicator /><Alert.Description>{error.message}</Alert.Description></Alert.Root>
350
+ )}
351
+ {data && !media.length && (
352
+ <Text fontSize="sm" color="var(--color-text-muted)">
353
+ No image, sound or video in {panel.files ? <Code>{panel.files}</Code> : data.folders.map((f) => `${f}/`).join(', ')} of this job.
354
+ </Text>
355
+ )}
356
+ <Flex gap={3} wrap="wrap" align="start">
357
+ {media.slice(0, shown).map((f) => {
358
+ const url = jobArtifactUrl(jrJobId, f.path);
359
+ const type = f.media_type.split('/')[0];
360
+ return (
361
+ <Box key={f.path} flex="1 1 220px" maxW={media.length === 1 ? '100%' : '480px'} minW={0}>
362
+ {type === 'image' && (
363
+ <a href={url} target="_blank" rel="noopener noreferrer">
364
+ <img src={url} alt={f.path} loading="lazy" style={{ maxWidth: '100%', maxHeight: 360 }} />
365
+ </a>
366
+ )}
367
+ {type === 'audio' && <audio src={url} controls preload="metadata" style={{ width: '100%' }} />}
368
+ {type === 'video' && <video src={url} controls preload="metadata" style={{ maxWidth: '100%', maxHeight: 360 }} />}
369
+ <Text fontSize="xs" fontFamily="mono" color="var(--color-text-muted)" wordBreak="break-all">{f.path}</Text>
370
+ </Box>
371
+ );
372
+ })}
373
+ </Flex>
374
+ {media.length > shown && (
375
+ <Button size="xs" variant="outline" mt={3} onClick={() => setShown(shown + MEDIA_PAGE)}>
376
+ Show more ({media.length - shown})
377
+ </Button>
378
+ )}
379
+ </PanelFrame>
380
+ );
381
+ };
382
+
383
+ type ArtifactFile = JobArtifacts['files'][number];
384
+
385
+ interface TreeFolder {
386
+ folders: Map<string, TreeFolder>;
387
+ files: { name: string; file: ArtifactFile }[];
388
+ }
389
+
390
+ const treeOf = (files: ArtifactFile[]): TreeFolder => {
391
+ const root: TreeFolder = { folders: new Map(), files: [] };
392
+ files.forEach((file) => {
393
+ const parts = file.path.split('/');
394
+ const name = parts.pop() as string;
395
+ let folder = root;
396
+ parts.forEach((part) => {
397
+ let next = folder.folders.get(part);
398
+ if (!next) folder.folders.set(part, (next = { folders: new Map(), files: [] }));
399
+ folder = next;
400
+ });
401
+ folder.files.push({ name, file });
402
+ });
403
+ return root;
404
+ };
405
+
406
+ const filesIn = (folder: TreeFolder): ArtifactFile[] =>
407
+ [...folder.files.map((f) => f.file), ...[...folder.folders.values()].flatMap(filesIn)];
408
+
409
+ /** A folder of the tree, and what is in it (the top ones are open) */
410
+ const FolderRows: React.FC<{ jrJobId: string; name: string; folder: TreeFolder; depth: number }> = ({ jrJobId, name, folder, depth }) => {
411
+ const [open, setOpen] = useState(depth === 0);
412
+ const inside = useMemo(() => filesIn(folder), [folder]);
413
+ const indent = `${depth * 20}px`;
414
+ return (
415
+ <>
416
+ <HStack
417
+ as="button"
418
+ gap={2}
419
+ w="100%"
420
+ pl={indent}
421
+ py="2px"
422
+ cursor="pointer"
423
+ aria-expanded={open}
424
+ _hover={{ bg: 'var(--color-bg-hover)' }}
425
+ onClick={() => setOpen(!open)}
426
+ >
427
+ {open ? <LuChevronDown /> : <LuChevronRight />}
428
+ <LuFolder />
429
+ <Text>{name}/</Text>
430
+ <Text color="var(--color-text-muted)">
431
+ {inside.length} file{inside.length === 1 ? '' : 's'} · {formatSize(inside.reduce((sum, f) => sum + f.size, 0))}
432
+ </Text>
433
+ </HStack>
434
+ {open && (
435
+ <>
436
+ {[...folder.folders.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([child, value]) => (
437
+ <FolderRows key={child} jrJobId={jrJobId} name={child} folder={value} depth={depth + 1} />
438
+ ))}
439
+ {[...folder.files].sort((a, b) => a.name.localeCompare(b.name)).map(({ name: fileName, file }) => {
440
+ const url = jobArtifactUrl(jrJobId, file.path);
441
+ return (
442
+ <HStack key={file.path} gap={2} pl={`${(depth + 1) * 20 + 4}px`} py="2px" _hover={{ bg: 'var(--color-bg-hover)' }}>
443
+ <LuFile />
444
+ <a href={url} download={fileName} title={`Download ${file.path}`} style={{ color: 'var(--color-primary)', wordBreak: 'break-all' }}>
445
+ {fileName}
446
+ </a>
447
+ <Text color="var(--color-text-muted)" flexShrink={0}>{formatSize(file.size)}</Text>
448
+ <HStack gap={3} ml="auto" pr={2} flexShrink={0} color="var(--color-text-muted)">
449
+ <Text>{new Date(file.mtime * 1000).toLocaleString()}</Text>
450
+ <a href={url} target="_blank" rel="noopener noreferrer" title="Open in a new tab"><LuExternalLink /></a>
451
+ <a href={url} download={fileName} title="Download"><LuDownload /></a>
452
+ </HStack>
453
+ </HStack>
454
+ );
455
+ })}
456
+ </>
457
+ )}
458
+ </>
459
+ );
460
+ };
461
+
462
+ /** The tree of the artifact folders (output/, results/, ...), its files to download */
463
+ export const FilesPanel: React.FC<PanelProps<'files'>> = ({ jrJobId, panel, actions }) => {
464
+ const { data, isFetching, error } = useQuery<JobArtifacts, ApiError>({
465
+ queryKey: ['bujang-job-artifacts', jrJobId],
466
+ queryFn: () => getJobArtifacts(jrJobId),
467
+ staleTime: 30_000,
468
+ retry: false,
469
+ });
470
+ const tree = useMemo(() => treeOf(data?.files || []), [data]);
471
+ return (
472
+ <PanelFrame
473
+ title={panel.title || 'Files'}
474
+ kind="files"
475
+ actions={actions}
476
+ info={<>
477
+ {isFetching && <Spinner size="xs" />}
478
+ {data && <Text>{data.files.length} file{data.files.length === 1 ? '' : 's'}{data.truncated ? ' (first files only)' : ''}</Text>}
479
+ </>}
480
+ >
481
+ {error && (
482
+ <Alert.Root status="error" mb={2}><Alert.Indicator /><Alert.Description>{error.message}</Alert.Description></Alert.Root>
483
+ )}
484
+ {data && !data.files.length && (
485
+ <Text fontSize="sm" color="var(--color-text-muted)">
486
+ No file in {data.folders.map((f) => `${f}/`).join(', ')} of this job.
487
+ </Text>
488
+ )}
489
+ <Box maxH="420px" overflowY="auto" fontFamily="mono" fontSize="xs">
490
+ {[...tree.folders.entries()].map(([name, folder]) => (
491
+ <FolderRows key={name} jrJobId={jrJobId} name={name} folder={folder} depth={0} />
492
+ ))}
493
+ </Box>
494
+ </PanelFrame>
495
+ );
496
+ };
497
+
498
+ /** The value of a dotted field of a row */
499
+ const valueOf = (row: Record<string, unknown>, field: string): unknown =>
500
+ field in row
501
+ ? row[field]
502
+ : field.split('.').reduce<unknown>((v, key) => (v && typeof v === 'object' ? (v as Record<string, unknown>)[key] : undefined), row);
503
+
504
+ type Stats = Record<StatName, number>;
505
+
506
+ /** Every statistic, and those shown by default */
507
+ const ALL_STATS: StatName[] = ['total', 'busy', 'count', 'mean', 'std', 'min', 'median', 'p95', 'p99', 'max'];
508
+ const STATS: StatName[] = ['count', 'mean', 'std', 'min', 'median', 'p95', 'p99', 'max'];
509
+
510
+ const STAT_HELP: Partial<Record<StatName, string>> = {
511
+ total: 'sum of the values',
512
+ busy: 'total over the time from the first start to the last end of these rows',
513
+ };
514
+
515
+ const splitBy = (by: string | undefined) => (by ?? '').split(',').map((f) => f.trim()).filter(Boolean);
516
+
517
+ const isNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
518
+
519
+ /** The statistics of some numbers (std of a sample, percentiles interpolated), `busy` over the window of their rows; null without any */
520
+ const statsOf = (values: number[], window: number): Stats | null => {
521
+ const n = values.length;
522
+ if (!n) return null;
523
+ const sorted = [...values].sort((a, b) => a - b);
524
+ const quantile = (q: number) => {
525
+ const at = (n - 1) * q;
526
+ const low = Math.floor(at);
527
+ const high = Math.min(low + 1, n - 1);
528
+ return sorted[low] + (sorted[high] - sorted[low]) * (at - low);
529
+ };
530
+ const total = values.reduce((sum, v) => sum + v, 0);
531
+ const mean = total / n;
532
+ const std = n > 1 ? Math.sqrt(values.reduce((sum, v) => sum + (v - mean) ** 2, 0) / (n - 1)) : NaN;
533
+ return { total, busy: n > 1 && window > 0 ? total / window : NaN, count: n, mean, std, min: sorted[0], median: quantile(0.5), p95: quantile(0.95), p99: quantile(0.99), max: sorted[n - 1] };
534
+ };
535
+
536
+ const formatShare = (value: number) => (Number.isFinite(value) ? `${(100 * value).toFixed(1)}%` : '—');
537
+
538
+ const formatStat = (value: number) => {
539
+ if (!Number.isFinite(value)) return '—';
540
+ if (Number.isInteger(value)) return value.toLocaleString();
541
+ const size = Math.abs(value);
542
+ if (size >= 1000) return value.toLocaleString(undefined, { maximumFractionDigits: 1 });
543
+ return size !== 0 && size < 1e-3 ? value.toExponential(3) : String(+value.toPrecision(5));
544
+ };
545
+
546
+ /** The table rows of a metric: one, or one per value of its `by` fields, the largest total first */
547
+ const metricRows = (m: StatsMetric, rows: Record<string, unknown>[]): { label: string | null; stats: Stats | null }[] => {
548
+ const by = splitBy(m.by);
549
+ const groups = new Map<string, Record<string, unknown>[]>();
550
+ rows.forEach((r) => {
551
+ if (!isNumber(valueOf(r, m.field))) return;
552
+ const label = by.map((f) => valueOf(r, f)).filter((v) => v !== undefined && v !== null).join(' ');
553
+ const group = groups.get(label);
554
+ if (group) group.push(r); else groups.set(label, [r]);
555
+ });
556
+ if (!by.length && !groups.size) return [{ label: null, stats: null }];
557
+ return [...groups.entries()]
558
+ .map(([label, group]) => {
559
+ let first = Infinity;
560
+ let last = -Infinity;
561
+ group.forEach((r) => {
562
+ const start = valueOf(r, 'start');
563
+ const end = valueOf(r, 'end');
564
+ if (isNumber(start)) first = Math.min(first, start);
565
+ if (isNumber(end)) last = Math.max(last, end);
566
+ });
567
+ const stats = statsOf(group.map((r) => valueOf(r, m.field) as number), last - first);
568
+ return { label: by.length ? label || '(none)' : null, stats };
569
+ })
570
+ .sort((a, b) => (b.stats?.total ?? 0) - (a.stats?.total ?? 0));
571
+ };
572
+
573
+ /** A table of the statistics of number fields, picked with its gear */
574
+ export const StatsPanel: React.FC<PanelProps<'stats'>> = ({ jrJobId, files, panel, actions }) => {
575
+ const metrics = useMemo(() => panel.metrics ?? [], [panel.metrics]);
576
+ const show = panel.show?.length ? panel.show : STATS;
577
+ const queryFiles = useQueryFiles(files);
578
+ const [open, setOpen] = useEditor(actions.onEditor);
579
+ // a query per event, of the fields it needs
580
+ const events = useMemo(() => [...new Set(metrics.map((m) => m.event))], [metrics]);
581
+ const results = useQueries({
582
+ queries: events.map((event) => {
583
+ const query = {
584
+ files: queryFiles,
585
+ events: event ? [event] : undefined,
586
+ fields: [...new Set([
587
+ ...metrics.filter((m) => m.event === event).flatMap((m) => [m.field, ...splitBy(m.by)]),
588
+ ...(show.includes('busy') ? ['start', 'end'] : []),
589
+ ])],
590
+ limit: ROW_LIMIT,
591
+ };
592
+ return {
593
+ queryKey: ['bujang-job-data-rows', jrJobId, query],
594
+ queryFn: () => getJobDataRows(jrJobId, query),
595
+ staleTime: 30_000,
596
+ };
597
+ }),
598
+ });
599
+ const error = results.find((r) => r.error)?.error as ApiError | undefined;
600
+ const rowsOf = (event: string) => results[events.indexOf(event)]?.data;
601
+ const truncated = results.some((r) => (r.data?.length ?? 0) >= ROW_LIMIT);
602
+
603
+ return (
604
+ <PanelFrame
605
+ title={panel.title || 'Stats'}
606
+ kind="stats"
607
+ actions={actions}
608
+ onSettings={() => setOpen(true)}
609
+ settingsTitle="Pick the fields of the stats"
610
+ info={<>
611
+ {results.some((r) => r.isFetching) && <Spinner size="xs" />}
612
+ {truncated && <Text>first {ROW_LIMIT} rows only</Text>}
613
+ </>}
614
+ >
615
+ {error && (
616
+ <Alert.Root status="error" mb={2}><Alert.Indicator /><Alert.Description>{error.message}</Alert.Description></Alert.Root>
617
+ )}
618
+ {!metrics.length && (
619
+ <HStack gap={3}>
620
+ <Text fontSize="sm" color="var(--color-text-muted)">No field picked.</Text>
621
+ <Button size="xs" variant="outline" onClick={() => setOpen(true)}><LuSettings /> Configure</Button>
622
+ </HStack>
623
+ )}
624
+ {metrics.length > 0 && (
625
+ <Box overflowX="auto">
626
+ <Table.Root size="sm" variant="line">
627
+ <Table.Header>
628
+ <Table.Row>
629
+ <Table.ColumnHeader>field</Table.ColumnHeader>
630
+ {show.map((name) => <Table.ColumnHeader key={name} textAlign="end" title={STAT_HELP[name]}>{name}</Table.ColumnHeader>)}
631
+ </Table.Row>
632
+ </Table.Header>
633
+ <Table.Body>
634
+ {metrics.map((m, i) => {
635
+ const rows = rowsOf(m.event);
636
+ const lines = rows ? metricRows(m, rows) : [{ label: null, stats: null }];
637
+ return lines.map(({ label, stats }) => (
638
+ <Table.Row key={`${i}:${m.event}:${m.field}:${label ?? ''}`}>
639
+ <Table.Cell fontFamily="mono" fontSize="xs" whiteSpace="nowrap" title={`${m.field} of the ${m.event || 'records'} rows`}>
640
+ {label !== null
641
+ ? <>{m.title ? `${m.title} ` : ''}{label}</>
642
+ : m.title || <>{m.field} <Text as="span" color="var(--color-text-muted)">{m.event}</Text></>}
643
+ </Table.Cell>
644
+ {show.map((name) => (
645
+ <Table.Cell key={name} fontFamily="mono" fontSize="xs" textAlign="end">
646
+ {stats ? (name === 'busy' ? formatShare(stats.busy) : formatStat(stats[name])) : rows ? '—' : ''}
647
+ </Table.Cell>
648
+ ))}
649
+ </Table.Row>
650
+ ));
651
+ })}
652
+ </Table.Body>
653
+ </Table.Root>
654
+ </Box>
655
+ )}
656
+ {open && (
657
+ <StatsEditor
658
+ files={files}
659
+ panel={panel}
660
+ onClose={() => setOpen(false)}
661
+ onApply={(next) => { setOpen(false); actions.onChange(next); }}
662
+ />
663
+ )}
664
+ </PanelFrame>
665
+ );
666
+ };
667
+
668
+ /** The fields of a stats block (its gear): the number fields of every event, and a title for the picked ones */
669
+ const StatsEditor: React.FC<{
670
+ files: JobData['files'];
671
+ panel: Extract<OverviewBlock, { kind: 'stats' }>;
672
+ onClose: () => void;
673
+ onApply: (panel: OverviewBlock) => void;
674
+ }> = ({ files, panel, onClose, onApply }) => {
675
+ const [title, setTitle] = useState(panel.title ?? '');
676
+ const [metrics, setMetrics] = useState<StatsMetric[]>(panel.metrics ?? []);
677
+ const [show, setShow] = useState<StatName[]>(panel.show?.length ? panel.show : STATS);
678
+ const fields = useMemo(() => {
679
+ const events = [...new Set(files.flatMap((f) => f.events?.map((e) => e.event) || []))];
680
+ return events
681
+ .map((event) => ({ event, names: mergeFields(files, event).filter((f) => f.type === 'number').map((f) => f.name) }))
682
+ .filter((e) => e.names.length);
683
+ }, [files]);
684
+ const same = (m: StatsMetric, event: string, field: string) => m.event === event && m.field === field;
685
+ const toggle = (event: string, field: string) => setMetrics(
686
+ metrics.some((m) => same(m, event, field))
687
+ ? metrics.filter((m) => !same(m, event, field))
688
+ : [...metrics, { event, field }],
689
+ );
690
+ const edit = (i: number, key: 'title' | 'by', value: string) => setMetrics(metrics.map((m, k) => {
691
+ if (k !== i) return m;
692
+ const next = { ...m, [key]: value };
693
+ if (!value) delete next[key];
694
+ return next;
695
+ }));
696
+
697
+ return (
698
+ <Dialog.Root open onOpenChange={(d) => { if (!d.open) onClose(); }} size="xl" closeOnInteractOutside={false}>
699
+ <Dialog.Backdrop />
700
+ <Dialog.Positioner>
701
+ <Dialog.Content className="bujang-dialog" maxH="88vh" display="flex" flexDirection="column">
702
+ <Dialog.Header py={3} px={4} borderBottom="1px solid" borderColor="var(--color-border)">
703
+ <Dialog.Title fontSize="md" color="var(--color-text)">Stats</Dialog.Title>
704
+ </Dialog.Header>
705
+ <Dialog.Body p={4} flex={1} minH={0} overflowY="auto">
706
+ <VStack align="stretch" gap={4}>
707
+ <VStack align="stretch" gap={0}>
708
+ <Text fontSize="xs" color="var(--color-text-muted)">title</Text>
709
+ <Input size="sm" w="260px" value={title} onChange={(e) => setTitle(e.target.value)} />
710
+ </VStack>
711
+ {fields.map(({ event, names }) => (
712
+ <Box key={event || '(records)'}>
713
+ <Text fontSize="xs" color="var(--color-text-muted)" mb={1}>{event || '(records)'}</Text>
714
+ <Wrap gap={1}>
715
+ {names.map((name) => (
716
+ <Button
717
+ key={name}
718
+ size="2xs"
719
+ variant={metrics.some((m) => same(m, event, name)) ? 'solid' : 'outline'}
720
+ onClick={() => toggle(event, name)}
721
+ >
722
+ {name}
723
+ </Button>
724
+ ))}
725
+ </Wrap>
726
+ </Box>
727
+ ))}
728
+ <Box>
729
+ <Text fontSize="xs" color="var(--color-text-muted)" mb={1}>statistics</Text>
730
+ <Wrap gap={1}>
731
+ {ALL_STATS.map((name) => (
732
+ <Button
733
+ key={name}
734
+ size="2xs"
735
+ title={STAT_HELP[name]}
736
+ variant={show.includes(name) ? 'solid' : 'outline'}
737
+ onClick={() => setShow(ALL_STATS.filter((s) => (s === name ? !show.includes(s) : show.includes(s))))}
738
+ >
739
+ {name}
740
+ </Button>
741
+ ))}
742
+ </Wrap>
743
+ </Box>
744
+ {metrics.length > 0 && (
745
+ <Box>
746
+ <Text fontSize="xs" color="var(--color-text-muted)" mb={1}>rows of the table, their names, and the fields to split them by</Text>
747
+ <VStack align="stretch" gap={1}>
748
+ {metrics.map((m, i) => (
749
+ <HStack key={`${m.event}:${m.field}`} gap={2}>
750
+ <Text fontSize="xs" fontFamily="mono" w="260px" truncate title={`${m.event} ${m.field}`}>
751
+ {m.field} <Text as="span" color="var(--color-text-muted)">{m.event}</Text>
752
+ </Text>
753
+ <Input size="xs" w="220px" placeholder={m.field} value={m.title ?? ''} onChange={(e) => edit(i, 'title', e.target.value)} />
754
+ <Input size="xs" w="180px" placeholder="by: name,worker" title="Comma separated fields: a row per value of them" value={m.by ?? ''} onChange={(e) => edit(i, 'by', e.target.value)} />
755
+ <Button size="2xs" variant="ghost" title="Move up" onClick={() => setMetrics(swapped(metrics, i, -1) ?? metrics)}><LuArrowUp /></Button>
756
+ <Button size="2xs" variant="ghost" title="Move down" onClick={() => setMetrics(swapped(metrics, i, 1) ?? metrics)}><LuArrowDown /></Button>
757
+ <Button size="2xs" variant="ghost" title="Remove" onClick={() => setMetrics(without(metrics, i))}><LuX /></Button>
758
+ </HStack>
759
+ ))}
760
+ </VStack>
761
+ </Box>
762
+ )}
763
+ </VStack>
764
+ </Dialog.Body>
765
+ <Dialog.Footer py={3} px={4} borderTop="1px solid" borderColor="var(--color-border)">
766
+ <Text fontSize="xs" color="var(--color-text-muted)" mr="auto">Applied to the layout of this page: save the layout to keep it.</Text>
767
+ <Button size="sm" variant="outline" onClick={onClose}>Cancel</Button>
768
+ <Button
769
+ size="sm"
770
+ onClick={() => onApply({
771
+ kind: 'stats',
772
+ ...(title.trim() ? { title: title.trim() } : {}),
773
+ metrics,
774
+ ...(show.length && show.join() !== STATS.join() ? { show } : {}),
775
+ })}
776
+ bg="var(--color-primary)"
777
+ color="var(--color-primary-text)"
778
+ _hover={{ bg: 'var(--color-primary-hover)' }}
779
+ >
780
+ Apply
781
+ </Button>
782
+ </Dialog.Footer>
783
+ </Dialog.Content>
784
+ </Dialog.Positioner>
785
+ </Dialog.Root>
786
+ );
787
+ };
788
+
789
+ /** The spec of a chart (the panel's, else of its builder fields, else of guessed ones) and its rows */
790
+ const useChart = (jrJobId: string, files: JobData['files'], panel: ChartBlock) => {
177
791
  const event = panel.event ?? '';
178
792
  const used = useMemo(() => panelFiles(files, panel.files), [files, panel.files]);
179
793
  const fields = useMemo(() => mergeFields(used, event), [used, event]);
@@ -187,6 +801,7 @@ export const ChartPanel: React.FC<PanelProps<'chart'>> = ({ jrJobId, files, pane
187
801
  return builder ? buildSpec(builder, fieldMap) : null;
188
802
  }, [panel.spec, builder, fieldMap]);
189
803
 
804
+ const queryFiles = useQueryFiles(files, panel.files);
190
805
  const query = useMemo(() => {
191
806
  // a built chart: only its fields, only the rows having its x and y; a spec: whole rows
192
807
  const wanted = builder && spec ? [...specFields(spec)].filter((f) => !f.startsWith('_') && fieldMap.has(f)) : [];
@@ -194,13 +809,13 @@ export const ChartPanel: React.FC<PanelProps<'chart'>> = ({ jrJobId, files, pane
194
809
  ? [builder.x, builder.yAggregate === 'count' ? '' : builder.y].filter((f) => f && !f.startsWith('_') && fieldMap.has(f))
195
810
  : [];
196
811
  return {
197
- files: splitFiles(panel.files),
198
- events: event ? [event] : undefined,
812
+ files: queryFiles,
813
+ events: event ? panelEvents(event) : undefined,
199
814
  fields: wanted.length ? wanted : undefined,
200
815
  require: required.length ? required : undefined,
201
816
  limit: ROW_LIMIT,
202
817
  };
203
- }, [builder, spec, fieldMap, panel.files, event]);
818
+ }, [builder, spec, fieldMap, queryFiles, event]);
204
819
  const ready = !!spec && fields.length > 0;
205
820
  const { data: rows, isFetching, error } = useQuery<Record<string, unknown>[], ApiError>({
206
821
  queryKey: ['bujang-job-data-rows', jrJobId, query],
@@ -209,43 +824,222 @@ export const ChartPanel: React.FC<PanelProps<'chart'>> = ({ jrJobId, files, pane
209
824
  staleTime: 30_000,
210
825
  placeholderData: (previous) => previous,
211
826
  });
827
+ return { event, spec, fields, ready, rows, isFetching, error };
828
+ };
212
829
 
830
+ /** The chart of a block, or why there is none */
831
+ const ChartView: React.FC<{ chart: ReturnType<typeof useChart>; files?: string }> = ({ chart, files }) => (
832
+ <>
833
+ {!chart.fields.length && (
834
+ <Text fontSize="sm" color="var(--color-text-muted)">
835
+ No <Code>{chart.event || 'records'}</Code> rows in {files ? <Code>{files}</Code> : 'the data files'} of this job.
836
+ </Text>
837
+ )}
838
+ {chart.error && (
839
+ <Alert.Root status="error" mb={2}><Alert.Indicator /><Alert.Description>{chart.error.message}</Alert.Description></Alert.Root>
840
+ )}
841
+ {chart.ready && chart.spec && chart.rows && <VegaChart spec={chart.spec} rows={chart.rows} />}
842
+ </>
843
+ );
844
+
845
+ /** A chart of one or several events */
846
+ export const ChartPanel: React.FC<PanelProps<'chart'>> = ({ jrJobId, files, panel, actions }) => {
847
+ const chart = useChart(jrJobId, files, panel);
848
+ const [open, setOpen] = useEditor(actions.onEditor);
849
+ const { event, rows, isFetching } = chart;
213
850
  return (
214
851
  <PanelFrame
215
852
  title={panel.title || event || 'records'}
216
853
  kind={event ? `chart · ${event}` : 'chart'}
217
- editing={editing}
218
- onMove={onMove}
219
- onRemove={onRemove}
854
+ actions={actions}
855
+ onSettings={() => setOpen(true)}
220
856
  info={<>
221
857
  {isFetching && <Spinner size="xs" />}
222
858
  {rows && <Text>{rows.length}{rows.length >= ROW_LIMIT ? '+' : ''} rows</Text>}
223
859
  </>}
224
860
  >
225
- {!fields.length && (
226
- <Text fontSize="sm" color="var(--color-text-muted)">
227
- No <Code>{event || 'records'}</Code> rows in {panel.files ? <Code>{panel.files}</Code> : 'the data files'} of this job.
228
- </Text>
861
+ <ChartView chart={chart} files={panel.files} />
862
+ {open && (
863
+ <ChartEditor
864
+ jrJobId={jrJobId}
865
+ files={files}
866
+ panel={panel}
867
+ spec={chart.spec}
868
+ onClose={() => setOpen(false)}
869
+ onApply={(next) => { setOpen(false); actions.onChange(next); }}
870
+ />
229
871
  )}
230
- {error && (
231
- <Alert.Root status="error" mb={2}><Alert.Indicator /><Alert.Description>{error.message}</Alert.Description></Alert.Root>
232
- )}
233
- {ready && rows && <VegaChart spec={spec} rows={rows} />}
234
872
  </PanelFrame>
235
873
  );
236
874
  };
237
875
 
876
+ const specText = (spec: Record<string, unknown> | null) => JSON.stringify(spec ?? {}, null, 2);
877
+
878
+ /** The Vega-Lite editor of a chart (its gear): the title, the events, the files and the spec, with a preview */
879
+ const ChartEditor: React.FC<{
880
+ jrJobId: string;
881
+ files: JobData['files'];
882
+ panel: ChartBlock;
883
+ /** the spec drawn now */
884
+ spec: Record<string, unknown> | null;
885
+ onClose: () => void;
886
+ onApply: (panel: ChartBlock) => void;
887
+ }> = ({ jrJobId, files, panel, spec, onClose, onApply }) => {
888
+ const [title, setTitle] = useState(panel.title ?? '');
889
+ const [event, setEvent] = useState(panel.event ?? '');
890
+ const [paths, setPaths] = useState(panel.files ?? '');
891
+ const initialText = useMemo(() => specText(spec), []); // eslint-disable-line react-hooks/exhaustive-deps
892
+ const [text, setText] = useState(initialText);
893
+
894
+ const { parsed, problem } = useMemo(() => {
895
+ try {
896
+ const value: unknown = JSON.parse(text);
897
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return { parsed: null, problem: 'expected a JSON object' };
898
+ return { parsed: value as Record<string, unknown>, problem: null };
899
+ } catch (err) {
900
+ return { parsed: null, problem: err instanceof Error ? err.message : String(err) };
901
+ }
902
+ }, [text]);
903
+ // the preview follows the typing with a delay, and keeps the last spec that parses
904
+ const [preview, setPreview] = useState({ spec: parsed ?? {}, event, files: paths });
905
+ useEffect(() => {
906
+ if (!parsed) return undefined;
907
+ const timer = window.setTimeout(() => setPreview({ spec: parsed, event, files: paths }), 400);
908
+ return () => window.clearTimeout(timer);
909
+ }, [parsed, event, paths]);
910
+ const draft = useMemo<ChartBlock>(
911
+ () => ({ kind: 'chart', event: preview.event, files: preview.files || undefined, spec: preview.spec }),
912
+ [preview],
913
+ );
914
+ const chart = useChart(jrJobId, files, draft);
915
+
916
+ const known = useMemo(
917
+ () => [...new Set(files.flatMap((f) => f.events?.map((e) => e.event) || []))].filter(Boolean),
918
+ [files],
919
+ );
920
+ const picked = panelEvents(event).filter(Boolean);
921
+ const toggle = (name: string) =>
922
+ setEvent((picked.includes(name) ? picked.filter((e) => e !== name) : [...picked, name]).join(','));
923
+
924
+ const apply = () => {
925
+ if (!parsed) return;
926
+ const { title: _title, event: _event, files: _files, spec: _spec, ...fields } = panel;
927
+ onApply({
928
+ // a spec left as drawn: the builder fields of the panel stay
929
+ ...(text === initialText && !panel.spec ? fields : { kind: 'chart' as const, spec: parsed }),
930
+ ...(title.trim() ? { title: title.trim() } : {}),
931
+ event,
932
+ ...(paths.trim() ? { files: paths.trim() } : {}),
933
+ });
934
+ };
935
+
936
+ return (
937
+ <Dialog.Root
938
+ open
939
+ onOpenChange={(d) => { if (!d.open) onClose(); }}
940
+ size="cover"
941
+ // Escape closes Monaco's own widgets
942
+ closeOnEscape={false}
943
+ closeOnInteractOutside={false}
944
+ >
945
+ <Dialog.Backdrop />
946
+ <Dialog.Positioner>
947
+ <Dialog.Content className="bujang-dialog" maxW="1500px" h="min(860px, 92vh)" display="flex" flexDirection="column">
948
+ <Dialog.Header py={3} px={4} borderBottom="1px solid" borderColor="var(--color-border)">
949
+ <Dialog.Title fontSize="md" color="var(--color-text)">Vega-Lite chart</Dialog.Title>
950
+ </Dialog.Header>
951
+ <Dialog.Body p={4} flex={1} minH={0} overflowY="auto">
952
+ <Wrap gap={3} mb={3} align="end">
953
+ <VStack align="stretch" gap={0}>
954
+ <Text fontSize="xs" color="var(--color-text-muted)">title</Text>
955
+ <Input size="sm" w="220px" value={title} onChange={(e) => setTitle(e.target.value)} />
956
+ </VStack>
957
+ <VStack align="stretch" gap={0}>
958
+ <Text fontSize="xs" color="var(--color-text-muted)">files (paths or globs, all when empty)</Text>
959
+ <Input size="sm" w="260px" placeholder="output/*.jsonl" value={paths} onChange={(e) => setPaths(e.target.value)} />
960
+ </VStack>
961
+ <VStack align="stretch" gap={0}>
962
+ <Text fontSize="xs" color="var(--color-text-muted)">events (the rows have theirs as "type")</Text>
963
+ <Wrap gap={1}>
964
+ {[...new Set([...known, ...picked])].map((name) => (
965
+ <Button key={name} size="xs" variant={picked.includes(name) ? 'solid' : 'outline'} onClick={() => toggle(name)}>
966
+ {name}
967
+ </Button>
968
+ ))}
969
+ </Wrap>
970
+ </VStack>
971
+ </Wrap>
972
+ <Flex gap={4} direction={{ base: 'column', lg: 'row' }}>
973
+ <Box flex="1" minW={0}>
974
+ <Text fontSize="xs" color="var(--color-text-muted)" mb={1}>Vega-Lite spec (data: the dataset "rows")</Text>
975
+ <MonacoEditor value={text} onChange={setText} language="json" height="480px" />
976
+ {problem && <Text fontSize="xs" color="var(--color-status-failed)" mt={1}>{problem}</Text>}
977
+ </Box>
978
+ <Box flex="1" minW={0}>
979
+ <HStack gap={2} mb={1} fontSize="xs" color="var(--color-text-muted)">
980
+ <Text>Preview</Text>
981
+ {chart.isFetching && <Spinner size="xs" />}
982
+ {chart.rows && <Text>{chart.rows.length} rows</Text>}
983
+ </HStack>
984
+ <ChartView chart={chart} files={preview.files} />
985
+ <Text fontSize="xs" color="var(--color-text-muted)" mt={2}>
986
+ Fields: {chart.fields.map((f) => f.name).join(', ') || '—'}
987
+ </Text>
988
+ </Box>
989
+ </Flex>
990
+ </Dialog.Body>
991
+ <Dialog.Footer py={3} px={4} borderTop="1px solid" borderColor="var(--color-border)">
992
+ <Text fontSize="xs" color="var(--color-text-muted)" mr="auto">Applied to the layout of this page: save the layout to keep it.</Text>
993
+ <Button size="sm" variant="outline" onClick={onClose}>Cancel</Button>
994
+ <Button
995
+ size="sm"
996
+ onClick={apply}
997
+ disabled={!parsed}
998
+ bg="var(--color-primary)"
999
+ color="var(--color-primary-text)"
1000
+ _hover={{ bg: 'var(--color-primary-hover)' }}
1001
+ >
1002
+ Apply
1003
+ </Button>
1004
+ </Dialog.Footer>
1005
+ </Dialog.Content>
1006
+ </Dialog.Positioner>
1007
+ </Dialog.Root>
1008
+ );
1009
+ };
1010
+
238
1011
  const SOURCE_TEXT: Record<JobOverviewLayout['source']['kind'], string> = {
239
1012
  experiment: 'saved for the experiment',
240
1013
  script: 'saved for the script',
1014
+ file: 'from the file',
241
1015
  plugin: 'from the plugin',
242
1016
  setting: 'the default layout (settings)',
243
1017
  default: 'the built-in layout',
244
1018
  };
245
1019
 
246
- /** Where the layout comes from, and the buttons to edit, save and reset it */
1020
+ /** The layout shown: the one of the job, or the built-in explorer of its data */
1021
+ export type OverviewView = 'job' | 'explore';
1022
+
1023
+ type LayoutSource = JobOverviewLayout['source'];
1024
+
1025
+ export const layoutKeyOf = (source: LayoutSource) => `${source.kind}:${source.name ?? ''}`;
1026
+
1027
+ /** A layout in the list: the name of its file, or what it was saved for */
1028
+ const layoutLabel = ({ kind, name }: LayoutSource) => {
1029
+ if (kind === 'default') return 'Built-in';
1030
+ if (kind === 'setting') return 'Default (settings)';
1031
+ if (kind === 'file') return (name ?? '').split('/').pop();
1032
+ return `${kind}: ${name}`;
1033
+ };
1034
+
1035
+ /** The choice of the layout, where it comes from, and the buttons to edit, save and reset it */
247
1036
  export const LayoutBar: React.FC<{
248
1037
  found: JobOverviewLayout;
1038
+ /** where the layout shown comes from */
1039
+ source: LayoutSource;
1040
+ view: OverviewView;
1041
+ /** `layout`: the key of the layout to show */
1042
+ onView: (view: OverviewView, layout?: string) => void;
249
1043
  dirty: boolean;
250
1044
  editing: boolean;
251
1045
  saving: boolean;
@@ -253,8 +1047,8 @@ export const LayoutBar: React.FC<{
253
1047
  onSave: (target: 'experiment' | 'script' | 'default') => void;
254
1048
  onDiscard: () => void;
255
1049
  onReset: () => void;
256
- }> = ({ found, dirty, editing, saving, onEdit, onSave, onDiscard, onReset }) => {
257
- const { source, keys } = found;
1050
+ }> = ({ found, source, view, onView, dirty, editing, saving, onEdit, onSave, onDiscard, onReset }) => {
1051
+ const { keys } = found;
258
1052
  const saved = source.kind === 'experiment' || source.kind === 'script';
259
1053
  return (
260
1054
  <Card.Root {...cardProps}>
@@ -262,15 +1056,34 @@ export const LayoutBar: React.FC<{
262
1056
  <Wrap gap={2} align="center" justify="space-between">
263
1057
  <HStack gap={2} fontSize="sm">
264
1058
  <Text fontWeight="semibold">Layout</Text>
1059
+ <NativeSelect.Root size="xs" w="220px">
1060
+ <NativeSelect.Field
1061
+ value={view === 'explore' ? 'explore' : layoutKeyOf(source)}
1062
+ onChange={(e) => (e.target.value === 'explore' ? onView('explore') : onView('job', e.target.value))}
1063
+ aria-label="Layout"
1064
+ >
1065
+ {found.layouts.map((entry, i) => (
1066
+ <option key={layoutKeyOf(entry.source)} value={layoutKeyOf(entry.source)}>
1067
+ {entry.label ?? layoutLabel(entry.source)}{i === 0 ? ' (this job)' : ''}
1068
+ </option>
1069
+ ))}
1070
+ <option value="explore">Explore data</option>
1071
+ </NativeSelect.Field>
1072
+ <NativeSelect.Indicator />
1073
+ </NativeSelect.Root>
265
1074
  <Text color="var(--color-text-muted)">
266
- {SOURCE_TEXT[source.kind]} {source.name && <Code>{source.name}</Code>}
1075
+ {view === 'job'
1076
+ ? <>{SOURCE_TEXT[source.kind]} {source.name && <Code>{source.name}</Code>}</>
1077
+ : 'plot the data of the job, and add the charts to its layout'}
267
1078
  </Text>
268
1079
  {dirty && <Badge size="xs" colorPalette="orange">not saved</Badge>}
269
1080
  </HStack>
270
1081
  <Wrap gap={1}>
271
- <Button size="xs" variant={editing ? 'solid' : 'outline'} onClick={() => onEdit(!editing)}>
272
- {editing ? 'Done' : 'Edit'}
273
- </Button>
1082
+ {view === 'job' && (
1083
+ <Button size="xs" variant={editing ? 'solid' : 'outline'} onClick={() => onEdit(!editing)}>
1084
+ {editing ? 'Done' : 'Edit'}
1085
+ </Button>
1086
+ )}
274
1087
  {dirty && (
275
1088
  <>
276
1089
  {keys.experiment && (
@@ -290,7 +1103,7 @@ export const LayoutBar: React.FC<{
290
1103
  <Button size="xs" variant="ghost" onClick={onDiscard}>Discard</Button>
291
1104
  </>
292
1105
  )}
293
- {saved && !dirty && (
1106
+ {view === 'job' && saved && !dirty && (
294
1107
  <Button size="xs" variant="ghost" loading={saving} onClick={onReset}
295
1108
  title={`Remove the layout saved for the ${source.kind} ${source.name}`}>
296
1109
  Reset
@@ -303,39 +1116,190 @@ export const LayoutBar: React.FC<{
303
1116
  );
304
1117
  };
305
1118
 
1119
+ /** A new Vega-Lite block: the first plotted event of the job, its fields guessed */
1120
+ const newChart = (files: JobData['files']): OverviewBlock => {
1121
+ const events = files.flatMap((f) => f.events || []);
1122
+ const event = (events.find((e) => e.role === 'metric') ?? events[0])?.event ?? '';
1123
+ const fields = mergeFields(files, event);
1124
+ const map = new Map([...fields, ...FILE_FIELDS].map((f) => [f.name, f]));
1125
+ const spec = buildSpec(guessBuilder(fields, filesWithEvent(files, event).length > 1), map);
1126
+ return { kind: 'chart', title: 'Vega-Lite', event, spec };
1127
+ };
1128
+
1129
+ /** `list` with the items i and i + by exchanged; null when there is no i + by */
1130
+ const swapped = <T, >(list: T[], i: number, by: number): T[] | null => {
1131
+ const j = i + by;
1132
+ if (j < 0 || j >= list.length) return null;
1133
+ const out = [...list];
1134
+ [out[i], out[j]] = [out[j], out[i]];
1135
+ return out;
1136
+ };
1137
+
1138
+ const replaced = <T, >(list: T[], i: number, item: T): T[] => list.map((x, k) => (k === i ? item : x));
1139
+ const without = <T, >(list: T[], i: number): T[] => list.filter((_, k) => k !== i);
1140
+
1141
+ const AddButtons: React.FC<{ files: JobData['files']; blocks: OverviewBlock[]; onAdd: (block: OverviewBlock) => void; children?: React.ReactNode }> = ({ files, blocks, onAdd, children }) => (
1142
+ <Wrap gap={1}>
1143
+ <Button size="2xs" variant="outline" onClick={() => onAdd(newChart(files))}><LuPlus /> Vega-Lite</Button>
1144
+ {blocks.map((block) => (
1145
+ <Button key={block.title} size="2xs" variant="outline" onClick={() => onAdd(block)}>
1146
+ <LuPlus /> {block.title}
1147
+ </Button>
1148
+ ))}
1149
+ <Button size="2xs" variant="outline" onClick={() => onAdd({ kind: 'artifacts', title: 'Artifacts' })}><LuPlus /> Artifacts</Button>
1150
+ <Button size="2xs" variant="outline" onClick={() => onAdd({ kind: 'files', title: 'Files' })}><LuPlus /> Files</Button>
1151
+ <Button size="2xs" variant="outline" onClick={() => onAdd({ kind: 'stats', title: 'Stats' })}><LuPlus /> Stats</Button>
1152
+ <Button size="2xs" variant="outline" onClick={() => onAdd({ kind: 'logs', title: 'Logs' })}><LuPlus /> Logs</Button>
1153
+ {children}
1154
+ </Wrap>
1155
+ );
1156
+
1157
+ /** Most columns of a columns panel (MAX_COLUMNS of the server) */
1158
+ const MAX_COLUMNS = 6;
1159
+
306
1160
  /** The panels of a layout */
307
1161
  export const LayoutPanels: React.FC<{
308
1162
  jrJobId: string;
1163
+ /** those of the picked rank with `oneRank` */
309
1164
  files: JobData['files'];
1165
+ oneRank: boolean;
310
1166
  layout: OverviewLayout;
1167
+ /** the charts of the built-in layout */
1168
+ available: OverviewBlock[];
311
1169
  editing: boolean;
312
1170
  onChange: (layout: OverviewLayout) => void;
313
- }> = ({ jrJobId, files, layout, editing, onChange }) => {
314
- const move = (i: number, by: number) => {
315
- const j = i + by;
316
- if (j < 0 || j >= layout.panels.length) return;
317
- const panels = [...layout.panels];
318
- [panels[i], panels[j]] = [panels[j], panels[i]];
319
- onChange({ panels });
1171
+ onEditor: (open: boolean) => void;
1172
+ }> = ({ jrJobId, files, oneRank, layout, available, editing, onChange, onEditor }) => {
1173
+ const { panels } = layout;
1174
+ const setPanels = (next: OverviewPanel[] | null) => next && onChange({ panels: next });
1175
+ // without widths: the same for all
1176
+ const setColumns = (i: number, columns: OverviewBlock[][], widths?: number[]) => setPanels(replaced(panels, i, {
1177
+ kind: 'columns',
1178
+ columns,
1179
+ ...(widths && widths.some((w) => w !== widths[0]) ? { widths } : {}),
1180
+ }));
1181
+
1182
+ const block = (panel: OverviewBlock, key: string, actions: BlockActions) => {
1183
+ // a block edited or moved starts again (its filters, its rows)
1184
+ const id = `${key}:${JSON.stringify(panel)}`;
1185
+ if (panel.kind === 'artifacts') {
1186
+ return <ArtifactPanel key={id} jrJobId={jrJobId} files={files} panel={panel} actions={actions} />;
1187
+ }
1188
+ if (panel.kind === 'stats') {
1189
+ return <StatsPanel key={id} jrJobId={jrJobId} files={files} panel={panel} actions={actions} />;
1190
+ }
1191
+ if (panel.kind === 'files') {
1192
+ return <FilesPanel key={id} jrJobId={jrJobId} files={files} panel={panel} actions={actions} />;
1193
+ }
1194
+ return panel.kind === 'logs'
1195
+ ? <LogPanel key={id} jrJobId={jrJobId} files={files} panel={panel} actions={actions} />
1196
+ : <ChartPanel key={id} jrJobId={jrJobId} files={files} panel={panel} actions={actions} />;
320
1197
  };
321
- const remove = (i: number) => onChange({ panels: layout.panels.filter((_, k) => k !== i) });
322
- if (!layout.panels.length) {
1198
+
1199
+ const columnsPanel = ({ columns, widths: given }: ColumnsPanel, i: number) => {
1200
+ const widths = given ?? columns.map(() => 1);
323
1201
  return (
324
- <Text fontSize="sm" color="var(--color-text-muted)">
325
- The layout has no panel: add charts from the explorer below.
326
- </Text>
1202
+ <Box
1203
+ key={`columns-${i}`}
1204
+ {...(editing ? { border: '1px dashed', borderColor: 'var(--color-border)', borderRadius: 'md', p: 2 } : {})}
1205
+ >
1206
+ {editing && (
1207
+ <HStack justify="space-between" mb={2}>
1208
+ <HStack gap={2}>
1209
+ <Text fontSize="xs" color="var(--color-text-muted)">{columns.length} column{columns.length > 1 ? 's' : ''}</Text>
1210
+ <Button size="2xs" variant="outline" disabled={columns.length >= MAX_COLUMNS} onClick={() => setColumns(i, [...columns, []], [...widths, 1])}>
1211
+ <LuPlus /> Column
1212
+ </Button>
1213
+ </HStack>
1214
+ <HStack gap={0}>
1215
+ <Button size="2xs" variant="ghost" onClick={() => setPanels(swapped(panels, i, -1))} title="Move up"><LuArrowUp /></Button>
1216
+ <Button size="2xs" variant="ghost" onClick={() => setPanels(swapped(panels, i, 1))} title="Move down"><LuArrowDown /></Button>
1217
+ <Button size="2xs" variant="ghost" onClick={() => setPanels(without(panels, i))} title="Remove the columns and their blocks">
1218
+ <LuX />
1219
+ </Button>
1220
+ </HStack>
1221
+ </HStack>
1222
+ )}
1223
+ {/* one under the other on a narrow page */}
1224
+ <Flex gap={4} direction={{ base: 'column', lg: 'row' }} align="stretch">
1225
+ {columns.map((blocks, c) => {
1226
+ const setColumn = (next: OverviewBlock[] | null) => next && setColumns(i, replaced(columns, c, next), widths);
1227
+ return (
1228
+ <VStack key={c} flex={{ base: '1', lg: `${widths[c]} 1 0` }} minW={0} align="stretch" gap={4}>
1229
+ {blocks.map((panel, b) => block(panel, `${i}.${c}.${b}`, {
1230
+ editing,
1231
+ onEditor,
1232
+ onMove: (by) => setColumn(swapped(blocks, b, by)),
1233
+ onRemove: () => setColumn(without(blocks, b)),
1234
+ onShift: (by) => {
1235
+ if (!columns[c + by]) return;
1236
+ setColumns(i, columns.map((list, k) => {
1237
+ if (k === c) return without(list, b);
1238
+ return k === c + by ? [...list, panel] : list;
1239
+ }), widths);
1240
+ },
1241
+ onChange: (next) => setColumn(replaced(blocks, b, next)),
1242
+ }))}
1243
+ {editing && (
1244
+ <HStack justify="space-between">
1245
+ <AddButtons files={files} blocks={available} onAdd={(added) => setColumn([...blocks, added])} />
1246
+ {columns.length > 1 && (
1247
+ <HStack gap={1} flexShrink={0}>
1248
+ <NativeSelect.Root size="xs" w="90px" title="Width of the column, relative to the others">
1249
+ <NativeSelect.Field
1250
+ value={String(widths[c])}
1251
+ onChange={(e) => setColumns(i, columns, replaced(widths, c, Number(e.target.value)))}
1252
+ >
1253
+ {[...new Set([1, 2, 3, 4, widths[c]])].sort((a, b) => a - b).map((w) => (
1254
+ <option key={w} value={w}>width {w}</option>
1255
+ ))}
1256
+ </NativeSelect.Field>
1257
+ </NativeSelect.Root>
1258
+ <Button size="2xs" variant="ghost" onClick={() => setColumns(i, without(columns, c), without(widths, c))} title="Remove the column and its blocks">
1259
+ <LuX /> Column
1260
+ </Button>
1261
+ </HStack>
1262
+ )}
1263
+ </HStack>
1264
+ )}
1265
+ </VStack>
1266
+ );
1267
+ })}
1268
+ </Flex>
1269
+ </Box>
327
1270
  );
328
- }
1271
+ };
1272
+
329
1273
  return (
1274
+ <OneRank.Provider value={oneRank}>
330
1275
  <VStack align="stretch" gap={4}>
331
- {layout.panels.map((panel, i) => {
332
- const props = { jrJobId, files, editing, onMove: (by: number) => move(i, by), onRemove: () => remove(i) };
333
- // a panel edited or moved starts again (its filters, its rows)
334
- const key = `${i}:${JSON.stringify(panel)}`;
335
- return panel.kind === 'logs'
336
- ? <LogPanel key={key} {...props} panel={panel} />
337
- : <ChartPanel key={key} {...props} panel={panel} />;
338
- })}
1276
+ {!panels.length && (
1277
+ <Text fontSize="sm" color="var(--color-text-muted)">
1278
+ The layout has no panel: add some with Edit, or charts from the Explore data layout.
1279
+ </Text>
1280
+ )}
1281
+ {panels.map((panel, i) => (
1282
+ panel.kind === 'columns'
1283
+ ? columnsPanel(panel, i)
1284
+ : block(panel, String(i), {
1285
+ editing,
1286
+ onEditor,
1287
+ onMove: (by) => setPanels(swapped(panels, i, by)),
1288
+ onRemove: () => setPanels(without(panels, i)),
1289
+ onSplit: () => setColumns(i, [[panel], []]),
1290
+ onChange: (next) => setPanels(replaced(panels, i, next)),
1291
+ })
1292
+ ))}
1293
+ {editing && (
1294
+ <AddButtons files={files} blocks={available} onAdd={(added) => setPanels([...panels, added])}>
1295
+ {[2, 3].map((n) => (
1296
+ <Button key={n} size="2xs" variant="outline" onClick={() => setPanels([...panels, { kind: 'columns', columns: Array.from({ length: n }, () => []) }])}>
1297
+ <LuPlus /> {n} columns
1298
+ </Button>
1299
+ ))}
1300
+ </AddButtons>
1301
+ )}
339
1302
  </VStack>
1303
+ </OneRank.Provider>
340
1304
  );
341
1305
  };