@milabench/bujang 0.1.15 → 0.1.16

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