@milabench/bujang 0.1.17 → 0.1.19

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.
@@ -31,8 +31,13 @@ import {
31
31
  loadPipelineFromFile,
32
32
  runPipelineTemplate,
33
33
  getPipelineRuns,
34
- getPipelineRunStatus
34
+ getPipelineRunStatus,
35
+ getSlurmJobStdoutFull,
36
+ getSlurmJobStderrFull,
37
+ getSlurmJobStdoutSize,
38
+ getSlurmJobStderrSize
35
39
  } from '../api';
40
+ import { LogDisplay } from './LogDisplay';
36
41
  import type {
37
42
  PipelineNode,
38
43
  ApiError,
@@ -134,8 +139,121 @@ const groupSummary = (steps: PipelineRunStep[]): string => {
134
139
  .join(', ');
135
140
  };
136
141
 
142
+ // a step writing its logs (their view refreshes), a step whose job has not started (no logs yet)
143
+ const ACTIVE_STEP_STATES = ['RUNNING', 'COMPLETING', 'CONFIGURING', 'STARTING'];
144
+ const WAITING_STEP_STATES = ['PENDING', 'HELD', 'SUBMITTED'];
145
+
146
+ /** The step shown when none was picked: the running one, else the first that failed */
147
+ const defaultStep = (steps: PipelineRunStep[]): PipelineRunStep | undefined =>
148
+ steps.find((step) => ACTIVE_STEP_STATES.includes(step.state || ''))
149
+ ?? steps.find((step) => stepStateColor(step.state) === 'red');
150
+
151
+ const formatFileSize = (bytes: number): string => {
152
+ if (bytes === 0) return '0 B';
153
+ const k = 1024;
154
+ const sizes = ['B', 'KB', 'MB', 'GB'];
155
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
156
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
157
+ };
158
+
159
+ const DetailField: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (
160
+ <HStack align="flex-start" gap={3} fontSize="xs">
161
+ <Text minW="88px" color="var(--color-text-muted)">{label}</Text>
162
+ <Box fontFamily="mono" color="var(--color-text)" minW={0} wordBreak="break-word">{children}</Box>
163
+ </HStack>
164
+ );
165
+
166
+ /** One step of a run: what it runs, where, and its stdout / stderr */
167
+ const PipelineStepDetails: React.FC<{ step: PipelineRunStep; following: boolean; onFollow: () => void }> = ({ step, following, onFollow }) => {
168
+ const paths = useBujangPaths();
169
+ const state = step.state || 'UNKNOWN';
170
+ const active = ACTIVE_STEP_STATES.includes(state);
171
+ const waiting = WAITING_STEP_STATES.includes(state);
172
+ const slurmJobId = step.executor === 'ssh' ? null : step.slurm_jobid;
173
+ const env = Object.entries(step.env || {});
174
+
175
+ return (
176
+ <VStack align="stretch" gap={3} p={4} borderRadius="md" border="1px solid" borderColor="var(--color-border)" bg="var(--color-bg-page)">
177
+ <HStack gap={3} flexWrap="wrap">
178
+ <Heading size="sm" color="var(--color-text)" fontFamily="mono">{stepName(step.step) || step.job_id}</Heading>
179
+ <Badge colorPalette={stepStateColor(step.state)}>{state}</Badge>
180
+ {step.job_label && <Text fontSize="sm" color="var(--color-text-muted)">{step.job_label}</Text>}
181
+ <Spacer />
182
+ {following ? (
183
+ <Text fontSize="xs" color="var(--color-text-muted)">
184
+ {active ? 'following the running step' : 'no step running: the first that failed'}
185
+ </Text>
186
+ ) : (
187
+ <Button size="xs" variant="outline" onClick={onFollow} borderColor="var(--color-border)" color="var(--color-text)">
188
+ Follow the running step
189
+ </Button>
190
+ )}
191
+ {step.job_id && (
192
+ <Button asChild size="xs" variant="outline" borderColor="var(--color-border)" color="var(--color-text)">
193
+ <RouterLink to={paths.jobLogs(slurmJobId || NO_JOB_ID, step.job_id)}>Open the job page</RouterLink>
194
+ </Button>
195
+ )}
196
+ </HStack>
197
+
198
+ <VStack align="stretch" gap={1}>
199
+ {step.step && <DetailField label="Step">{step.step}</DetailField>}
200
+ <DetailField label="Runs on">
201
+ {step.executor === 'ssh' ? `ssh ${step.host ?? ''}` : `slurm ${step.slurm_jobid ?? '-'}`}
202
+ {step.cluster && <Text as="span" color="var(--color-text-muted)"> on {step.cluster}</Text>}
203
+ </DetailField>
204
+ <DetailField label="Profile">{step.profile}</DetailField>
205
+ <DetailField label="Script">{step.script}</DetailField>
206
+ {step.job_id && <DetailField label="Job folder">{step.job_id}</DetailField>}
207
+ {step.sweep && <DetailField label="Sweep">{step.sweep_key ? `${step.sweep_key}=${step.sweep}` : step.sweep}</DetailField>}
208
+ {step.after && step.after.length > 0 && <DetailField label="After">{step.after.join(', ')}</DetailField>}
209
+ {env.length > 0 && (
210
+ <DetailField label="Environment">
211
+ {env.map(([key, value]) => <Text key={key}>{key}={value}</Text>)}
212
+ </DetailField>
213
+ )}
214
+ </VStack>
215
+
216
+ {!step.job_id ? (
217
+ <Text fontSize="sm" color="var(--color-text-muted)">Not submitted yet: no logs.</Text>
218
+ ) : waiting ? (
219
+ <Text fontSize="sm" color="var(--color-text-muted)">The job has not started yet: no logs.</Text>
220
+ ) : (
221
+ // keyed by job: the logs of another step start from scratch
222
+ <Flex key={step.job_id} gap={4} direction={{ base: 'column', lg: 'row' }} h={{ base: '760px', lg: '440px' }}>
223
+ <LogDisplay
224
+ logType="stdout"
225
+ jrJobId={step.job_id}
226
+ isJobFinished={!active}
227
+ formatFileSize={formatFileSize}
228
+ fetchLogData={getSlurmJobStdoutFull}
229
+ getSlurmJobLogSize={getSlurmJobStdoutSize}
230
+ />
231
+ <LogDisplay
232
+ logType="stderr"
233
+ jrJobId={step.job_id}
234
+ isJobFinished={!active}
235
+ formatFileSize={formatFileSize}
236
+ fetchLogData={getSlurmJobStderrFull}
237
+ getSlurmJobLogSize={getSlurmJobStderrSize}
238
+ />
239
+ </Flex>
240
+ )}
241
+ </VStack>
242
+ );
243
+ };
244
+
137
245
  // Progress of one run: steps with their state and the pipeline log, refreshed until it is over
138
246
  const PipelineRunProgress: React.FC<{ runId: string }> = ({ runId }) => {
247
+ // ?step=<job id>: the step picked in the table; none: the running step (else the first that failed)
248
+ const [params, setParams] = useSearchParams();
249
+ const pickedStep = params.get('step');
250
+ const pickStep = (jobId: string | null) => setParams((current) => {
251
+ const next = new URLSearchParams(current);
252
+ if (jobId) next.set('step', jobId);
253
+ else next.delete('step');
254
+ return next;
255
+ }, { replace: true });
256
+
139
257
  const { data: run, error, dataUpdatedAt, isFetching } = useQuery<PipelineRunStatus, ApiError>({
140
258
  queryKey: ['pipeline-run', runId],
141
259
  queryFn: () => getPipelineRunStatus(runId),
@@ -170,6 +288,9 @@ const PipelineRunProgress: React.FC<{ runId: string }> = ({ runId }) => {
170
288
  }
171
289
 
172
290
  const label = run.status === 'submitted' ? (run.state || 'unknown') : run.status;
291
+ const steps = run.steps ?? [];
292
+ const picked = pickedStep ? steps.find((step) => step.job_id === pickedStep) : undefined;
293
+ const selected = picked ?? defaultStep(steps);
173
294
 
174
295
  return (
175
296
  <VStack align="stretch" gap={4}>
@@ -239,13 +360,27 @@ const PipelineRunProgress: React.FC<{ runId: string }> = ({ runId }) => {
239
360
  if (!step) return null;
240
361
  // in the tree the parents are the rows above: "1.Sizing/0.lynx_sizing" -> "lynx_sizing"
241
362
  const name = row.node ? stepName(step.step) : step.step;
363
+ const isSelected = !!selected && selected === step;
242
364
  return (
243
- <Table.Row key={step.job_id || step.step || index}>
365
+ <Table.Row
366
+ key={step.job_id || step.step || index}
367
+ // the step shown below the table
368
+ bg={isSelected ? 'var(--color-bg-hover)' : undefined}
369
+ boxShadow={isSelected ? 'inset 3px 0 0 var(--color-primary)' : undefined}
370
+ >
244
371
  <Table.Cell fontFamily="mono" fontSize="xs" pl={`${12 + row.depth * 20}px`} whiteSpace="nowrap">
245
372
  {indent}
373
+ {/* the step name shows the step below the table, the job folder opens the job page */}
246
374
  <Tooltip content={step.step} disabled={name === step.step}>
247
- <JobLogsLink jobId={step.job_id} slurmJobId={step.executor === 'ssh' ? null : step.slurm_jobid}>{name}</JobLogsLink>
375
+ {step.job_id ? (
376
+ <Link asChild colorPalette="blue" variant="underline" fontWeight={isSelected ? 'semibold' : undefined}>
377
+ <button type="button" onClick={() => pickStep(step.job_id!)}>{name}</button>
378
+ </Link>
379
+ ) : <Text as="span">{name}</Text>}
248
380
  </Tooltip>
381
+ {step.job_label && (
382
+ <Text as="span" ml={2} fontFamily="body" color="var(--color-text-muted)">{step.job_label}</Text>
383
+ )}
249
384
  </Table.Cell>
250
385
  {sweepKeys.length > 0 && (
251
386
  <Table.Cell fontFamily="mono" fontSize="xs">
@@ -271,6 +406,12 @@ const PipelineRunProgress: React.FC<{ runId: string }> = ({ runId }) => {
271
406
  </Table.Root>
272
407
  )}
273
408
 
409
+ {selected ? (
410
+ <PipelineStepDetails step={selected} following={!picked} onFollow={() => pickStep(null)} />
411
+ ) : steps.length > 0 && (
412
+ <Text fontSize="xs" color="var(--color-text-muted)">Select a step to see its details and its logs.</Text>
413
+ )}
414
+
274
415
  {run.status === 'submitted' && (
275
416
  <Box>
276
417
  <Text fontWeight="semibold" mb={2} color="var(--color-text)">pipeline.log</Text>
@@ -411,7 +552,7 @@ const PipelineEditor: React.FC<{
411
552
  const RunButton: React.FC<{ name: string; onStarted: (run: PipelineRunResponse) => void; size?: 'xs' | 'sm' | 'md' }> = ({ name, onStarted, size = 'sm' }) => {
412
553
  const queryClient = useQueryClient();
413
554
  const run = useMutation({
414
- mutationFn: runPipelineTemplate,
555
+ mutationFn: (pipeline: string) => runPipelineTemplate(pipeline),
415
556
  onSuccess: (data) => {
416
557
  queryClient.invalidateQueries({ queryKey: ['pipeline-runs'] });
417
558
  toaster.create({ title: `Pipeline ${data.name} started`, description: `Run ${data.run_id}: submitting the jobs`, type: 'info', duration: 4000 });
@@ -0,0 +1,246 @@
1
+ import React, { useState } from 'react';
2
+ import { Link } from 'react-router-dom';
3
+ import { Badge, Box, Button, Code, Heading, HStack, Input, Spinner, Text, VStack } from '@chakra-ui/react';
4
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
5
+ import { LuBot, LuFolderGit2, LuLink, LuPlus, LuRefreshCw, LuTrash2 } from 'react-icons/lu';
6
+ import { getProjects, registerProject, removeProject, syncProjects } from '../api';
7
+ import type { ApiError, Project, ProjectsInfo } from '../types';
8
+ import { LinkableCard, useHashScroll } from '../components/LinkableCard';
9
+ import { Tooltip } from '../components/tooltip';
10
+ import { toaster } from '../toast';
11
+ import { useBujangPaths } from '../context';
12
+ import { usePageTitle } from '../hooks/usePageTitle';
13
+
14
+ const PROJECTS_KEY = ['bujang-projects'];
15
+
16
+ const inputStyle = {
17
+ bg: 'var(--color-input-bg)',
18
+ borderColor: 'var(--color-input-border)',
19
+ color: 'var(--color-text)',
20
+ } as const;
21
+
22
+ const errorMessage = (error: unknown) => (error as ApiError)?.message || String(error);
23
+ const fail = (title: string) => (error: unknown) =>
24
+ toaster.create({ title, description: errorMessage(error), type: 'error', closable: true });
25
+
26
+ /** The last folder of a path, as a project name ("~/work/my repo/" -> "my-repo") */
27
+ function nameFromPath(path: string): string {
28
+ const last = path.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || '';
29
+ return last.replace(/[^A-Za-z0-9._@+=,-]+/g, '-').replace(/^[^A-Za-z0-9]+/, '');
30
+ }
31
+
32
+ const Label: React.FC<{ children: React.ReactNode }> = ({ children }) => (
33
+ <Text fontSize="xs" fontWeight="semibold" color="var(--color-text-muted)" mb={1}>{children}</Text>
34
+ );
35
+
36
+ const RegisterCard: React.FC<{ info: ProjectsInfo }> = ({ info }) => {
37
+ const queryClient = useQueryClient();
38
+ const [path, setPath] = useState('');
39
+ const [name, setName] = useState('');
40
+ const [folder, setFolder] = useState('');
41
+ const register = useMutation({
42
+ mutationFn: () => registerProject({ name: name || nameFromPath(path), path, folder: folder || undefined }),
43
+ onSuccess: (out) => {
44
+ const linked = out.sync?.added?.length ?? 0;
45
+ toaster.create({
46
+ title: `Project ${out.project.name} registered`,
47
+ description: `${out.project.path}/${out.project.folder}${linked ? `: ${linked} jobs linked` : ''}`,
48
+ type: 'success',
49
+ });
50
+ setPath(''); setName(''); setFolder('');
51
+ queryClient.invalidateQueries({ queryKey: PROJECTS_KEY });
52
+ },
53
+ onError: fail('Registration failed'),
54
+ });
55
+ const effectiveName = name || nameFromPath(path);
56
+
57
+ return (
58
+ <LinkableCard id="register" icon={<LuPlus />} title="Register a repository"
59
+ subtitle="bujang makes a folder inside it and links there every job tagged for the project">
60
+ {!info.writable ? (
61
+ <Text fontSize="sm" color="var(--color-text-muted)">
62
+ This server is read-only (the host did not turn editing on): projects are registered from a
63
+ server started with <Code fontSize="xs">bujang serve</Code>, or in <Code fontSize="xs">projects.yaml</Code> of the local cache.
64
+ </Text>
65
+ ) : (
66
+ <VStack align="stretch" gap={3}>
67
+ <HStack gap={3} align="flex-end" wrap="wrap">
68
+ <Box flex="2" minW="260px">
69
+ <Label>Repository path (on the bujang server's machine)</Label>
70
+ <Input {...inputStyle} size="sm" placeholder="/home/me/work/my-repo" value={path}
71
+ onChange={(e) => setPath(e.target.value)} fontFamily="mono" />
72
+ </Box>
73
+ <Box flex="1" minW="160px">
74
+ <Label>Name</Label>
75
+ <Input {...inputStyle} size="sm" placeholder={nameFromPath(path) || 'my-repo'} value={name}
76
+ onChange={(e) => setName(e.target.value)} />
77
+ </Box>
78
+ <Box flex="1" minW="140px">
79
+ <Label>Folder inside the repository</Label>
80
+ <Input {...inputStyle} size="sm" placeholder={info.default_folder} value={folder}
81
+ onChange={(e) => setFolder(e.target.value)} fontFamily="mono" />
82
+ </Box>
83
+ <Button size="sm" colorPalette="blue" disabled={!path.trim() || !effectiveName}
84
+ loading={register.isPending} onClick={() => register.mutate()}>
85
+ <LuPlus /> Register
86
+ </Button>
87
+ </HStack>
88
+ {path.trim() && (
89
+ <Text fontSize="xs" color="var(--color-text-muted)">
90
+ Jobs submitted with <Code fontSize="xs">project="{effectiveName}"</Code> will show in{' '}
91
+ <Code fontSize="xs">{path.replace(/\/+$/, '')}/{folder || info.default_folder}/&lt;job id&gt;</Code>.
92
+ The folder gets a README for the agents working there and a <Code fontSize="xs">.gitignore</Code>.
93
+ </Text>
94
+ )}
95
+ </VStack>
96
+ )}
97
+ </LinkableCard>
98
+ );
99
+ };
100
+
101
+ const ProjectCard: React.FC<{ project: Project; writable: boolean }> = ({ project, writable }) => {
102
+ const paths = useBujangPaths();
103
+ const queryClient = useQueryClient();
104
+ const [confirm, setConfirm] = useState(false);
105
+ const sync = useMutation({
106
+ mutationFn: () => syncProjects(project.name),
107
+ onSuccess: (report) => {
108
+ const r = report[project.name] || {};
109
+ toaster.create({
110
+ title: r.error ? `Cannot link ${project.name}` : `${project.name}: ${r.added?.length ?? 0} links added, ${r.removed?.length ?? 0} removed`,
111
+ description: r.error,
112
+ type: r.error ? 'error' : 'success',
113
+ });
114
+ queryClient.invalidateQueries({ queryKey: PROJECTS_KEY });
115
+ },
116
+ onError: fail('Sync failed'),
117
+ });
118
+ const remove = useMutation({
119
+ mutationFn: () => removeProject(project.name),
120
+ onSuccess: (out) => {
121
+ toaster.create({ title: `Project ${project.name} removed`, description: `${out.removed.length} links removed from the repository`, type: 'success' });
122
+ queryClient.invalidateQueries({ queryKey: PROJECTS_KEY });
123
+ },
124
+ onError: fail('Removal failed'),
125
+ });
126
+ const jobsLink = `${paths.jobs()}?projects=${encodeURIComponent(project.name)}`;
127
+
128
+ return (
129
+ <LinkableCard
130
+ id={`project-${project.name}`}
131
+ icon={<LuFolderGit2 />}
132
+ title={project.name}
133
+ subtitle={<Code fontSize="xs" bg="transparent" color="var(--color-text-muted)" p={0}>{project.path}</Code>}
134
+ actions={
135
+ <HStack gap={1}>
136
+ <Tooltip content="Add the missing links, remove the stale ones" showArrow>
137
+ <Button size="xs" variant="ghost" loading={sync.isPending} onClick={() => sync.mutate()}><LuRefreshCw /> Relink</Button>
138
+ </Tooltip>
139
+ {writable && (confirm ? (
140
+ <>
141
+ <Button size="xs" colorPalette="red" loading={remove.isPending} onClick={() => remove.mutate()}>Remove the links</Button>
142
+ <Button size="xs" variant="ghost" onClick={() => setConfirm(false)}>Cancel</Button>
143
+ </>
144
+ ) : (
145
+ <Tooltip content="Forget the project: its links leave the repository, the jobs stay" showArrow>
146
+ <Button size="xs" variant="ghost" colorPalette="red" onClick={() => setConfirm(true)}><LuTrash2 /></Button>
147
+ </Tooltip>
148
+ ))}
149
+ </HStack>
150
+ }
151
+ >
152
+ <VStack align="stretch" gap={2} fontSize="sm" color="var(--color-text)">
153
+ <HStack gap={2} wrap="wrap">
154
+ {!project.exists && <Badge colorPalette="red">repository missing</Badge>}
155
+ {project.exists && !project.git && <Badge colorPalette="orange" variant="subtle">not a git repository</Badge>}
156
+ <Link to={jobsLink}>
157
+ <Badge variant="outline" cursor="pointer">{project.jobs} jobs</Badge>
158
+ </Link>
159
+ <Badge variant="subtle"><LuLink /> {project.links} links</Badge>
160
+ </HStack>
161
+ <Text color="var(--color-text-muted)">
162
+ Jobs are linked in <Code fontSize="xs">{project.target}</Code>
163
+ </Text>
164
+ <Text color="var(--color-text-muted)">
165
+ Tag a job: <Code fontSize="xs">project="{project.name}"</Code> (MCP <Code fontSize="xs">submit_job</Code> /{' '}
166
+ <Code fontSize="xs">run_pipeline</Code>, the Submit page), or <Code fontSize="xs">export BUJANG_PROJECT={project.name}</Code> in the script.
167
+ </Text>
168
+ </VStack>
169
+ </LinkableCard>
170
+ );
171
+ };
172
+
173
+ const AgentsCard: React.FC<{ argument: string }> = ({ argument }) => (
174
+ <LinkableCard id="agents" icon={<LuBot />} title="Coding agents" subtitle="how an agent working in a repository tags its jobs">
175
+ <VStack align="stretch" gap={2} fontSize="sm" color="var(--color-text-muted)">
176
+ <Text>
177
+ The MCP server tells the agents to call <Code fontSize="xs">list_projects</Code>, compare the paths with their
178
+ working directory, and pass <Code fontSize="xs">project=&lt;name&gt;</Code> to <Code fontSize="xs">submit_job</Code> and{' '}
179
+ <Code fontSize="xs">run_pipeline</Code>. The README bujang puts in the repository folder says the same, for an agent that
180
+ reads the repository first.
181
+ </Text>
182
+ <Text>
183
+ A job script can tag itself with <Code fontSize="xs">export {argument}=&lt;name&gt;</Code>. A pipeline run tagged for a
184
+ project brings its steps (they show inside the run folder). An unknown project name is refused at submission.
185
+ </Text>
186
+ </VStack>
187
+ </LinkableCard>
188
+ );
189
+
190
+ export const ProjectsView: React.FC = () => {
191
+ usePageTitle('Projects');
192
+ const queryClient = useQueryClient();
193
+ const { data, isLoading, error, refetch, isFetching } = useQuery<ProjectsInfo>({
194
+ queryKey: PROJECTS_KEY,
195
+ queryFn: getProjects,
196
+ });
197
+ useHashScroll(!!data);
198
+ const syncAll = useMutation({
199
+ mutationFn: () => syncProjects(),
200
+ onSuccess: (report) => {
201
+ const added = Object.values(report).reduce((n, r) => n + (r.added?.length ?? 0), 0);
202
+ const removed = Object.values(report).reduce((n, r) => n + (r.removed?.length ?? 0), 0);
203
+ toaster.create({ title: `${added} links added, ${removed} removed`, type: 'success' });
204
+ queryClient.invalidateQueries({ queryKey: PROJECTS_KEY });
205
+ },
206
+ onError: fail('Sync failed'),
207
+ });
208
+
209
+ return (
210
+ <Box p={6} maxW="1200px">
211
+ <HStack mb={2} gap={3} color="var(--color-text)" justify="space-between" wrap="wrap">
212
+ <HStack gap={3}>
213
+ <LuFolderGit2 size={24} />
214
+ <Heading size="lg">Projects</Heading>
215
+ </HStack>
216
+ <HStack gap={1}>
217
+ {!!data?.projects.length && (
218
+ <Button size="sm" variant="ghost" loading={syncAll.isPending} onClick={() => syncAll.mutate()}><LuLink /> Relink all</Button>
219
+ )}
220
+ <Button size="sm" variant="ghost" loading={isFetching} onClick={() => refetch()}><LuRefreshCw /> Refresh</Button>
221
+ </HStack>
222
+ </HStack>
223
+ <Text mb={6} color="var(--color-text-muted)">
224
+ Code repositories on this machine. The jobs submitted for a project show inside its repository as links to their
225
+ job folders (logs, <Code fontSize="xs">output/</Code>), so the results sit next to the code that made them.
226
+ </Text>
227
+ {isLoading && <Spinner />}
228
+ {error && <Text color="var(--color-status-failed)">{errorMessage(error)}</Text>}
229
+ {data && (
230
+ <VStack align="stretch" gap={6}>
231
+ {!data.enabled && (
232
+ <Box p={3} borderWidth="1px" borderRadius="md" borderColor="var(--color-status-failed)" color="var(--color-text)" fontSize="sm">
233
+ The <Code fontSize="xs">projects</Code> organizer is not loaded (the <Code fontSize="xs">organizers</Code> setting
234
+ leaves it out): jobs are tagged but nothing is linked into the repositories.
235
+ </Box>
236
+ )}
237
+ <RegisterCard info={data} />
238
+ {data.projects.length === 0
239
+ ? <Text fontSize="sm" color="var(--color-text-muted)" fontStyle="italic">No project registered yet.</Text>
240
+ : data.projects.map(p => <ProjectCard key={p.name} project={p} writable={data.writable} />)}
241
+ <AgentsCard argument={data.argument} />
242
+ </VStack>
243
+ )}
244
+ </Box>
245
+ );
246
+ };
@@ -1,6 +1,6 @@
1
1
  /** Charts of the JSONL data of a job: the chart builder, its Vega-Lite spec, and the chart itself. */
2
2
  import React, { useEffect, useRef, useState } from 'react';
3
- import { Alert, Box } from '@chakra-ui/react';
3
+ import { Alert, Box, HStack, Input, Text } from '@chakra-ui/react';
4
4
  import type { JobData, JobDataField, JobDataRole, OverviewBlock } from '../types';
5
5
  import { useColorMode } from '../hooks/useColorMode';
6
6
 
@@ -140,21 +140,117 @@ export const isDarkPage = () =>
140
140
  typeof document !== 'undefined' &&
141
141
  (document.documentElement.classList.contains('dark') || document.documentElement.dataset.theme === 'dark');
142
142
 
143
+ type Param = { name?: string; value?: unknown; select?: unknown; bind?: { input?: string; options?: unknown; labels?: string[] } };
144
+
145
+ /** The params of a spec with an input. The options of a select can be those of a field of the rows
146
+ * (`options: {field: "epoch"}`), after "all" (null) */
147
+ export const boundParams = (spec: Record<string, unknown>, rows: Record<string, unknown>[], values: Map<string, unknown>): Param[] | undefined => {
148
+ if (!Array.isArray(spec.params)) return undefined;
149
+ return (spec.params as Param[]).map((param) => {
150
+ if (!param.name || !param.bind || typeof param.bind !== 'object' || !param.bind.input) return param;
151
+ let { bind } = param;
152
+ const field = (bind.options as { field?: string } | undefined)?.field;
153
+ let value = values.has(param.name) ? values.get(param.name) : param.value;
154
+ if (typeof field === 'string') {
155
+ const found = [...new Set(rows.map((r) => r[field]).filter((v) => v !== undefined && v !== null))] as (number | string)[];
156
+ found.sort((a, b) => (typeof a === 'number' && typeof b === 'number' ? a - b : String(a).localeCompare(String(b))));
157
+ bind = { ...bind, options: [null, ...found], labels: ['all', ...found.map(String)] };
158
+ if (!found.includes(value as number | string)) value = null;
159
+ }
160
+ return { ...param, bind, value };
161
+ });
162
+ };
163
+
164
+ /** The fields of the x encodings of a spec, those of its layers included */
165
+ const xFields = (spec: unknown, out = new Set<string>()): Set<string> => {
166
+ if (Array.isArray(spec)) spec.forEach((item) => xFields(item, out));
167
+ else if (spec && typeof spec === 'object') {
168
+ const x = (spec as { encoding?: { x?: { field?: unknown } } }).encoding?.x?.field;
169
+ if (typeof x === 'string') out.add(x);
170
+ for (const key of ['layer', 'hconcat', 'vconcat', 'concat', 'spec']) xFields((spec as Record<string, unknown>)[key], out);
171
+ }
172
+ return out;
173
+ };
174
+
175
+ /** The rows without the first `skip` x values of each event of each file. An x the spec computes: their `start`, else their `time` */
176
+ export const skipFirst = <T extends Record<string, unknown>, >(rows: T[], spec: unknown, skip: number): T[] => {
177
+ if (!(skip > 0)) return rows;
178
+ const fields = [...xFields(spec), 'start', 'time'];
179
+ const groups = new Map<string, T[]>();
180
+ rows.forEach((r) => {
181
+ const key = `${r._file ?? ''}|${r.type ?? ''}`;
182
+ const group = groups.get(key);
183
+ if (group) group.push(r); else groups.set(key, [r]);
184
+ });
185
+ const dropped = new Set<T>();
186
+ groups.forEach((group) => {
187
+ const field = fields.find((f) => group.some((r) => typeof r[f] === 'number'));
188
+ if (!field) return;
189
+ const values = [...new Set(group.map((r) => r[field]).filter((v): v is number => typeof v === 'number'))].sort((a, b) => a - b);
190
+ const last = values[Math.min(skip, values.length) - 1];
191
+ group.forEach((r) => { if (typeof r[field] === 'number' && (r[field] as number) <= last) dropped.add(r); });
192
+ });
193
+ return rows.filter((r) => !dropped.has(r));
194
+ };
195
+
196
+ /** The number of first x values a chart leaves out */
197
+ export const SkipInput: React.FC<{ value: number; onChange: (skip: number) => void; onDone?: () => void }> = ({ value, onChange, onDone }) => (
198
+ <HStack gap={1} as="label" title="Leave out the first x values (of each event of each file)">
199
+ <Text fontSize="xs" color="var(--color-text-muted)">skip</Text>
200
+ <Input
201
+ size="2xs"
202
+ w="56px"
203
+ type="number"
204
+ min={0}
205
+ step={1}
206
+ aria-label="First x values left out"
207
+ value={value || ''}
208
+ placeholder="0"
209
+ onChange={(e) => onChange(Math.max(0, Math.floor(Number(e.target.value) || 0)))}
210
+ onBlur={onDone}
211
+ onKeyDown={(e) => { if (e.key === 'Enter') onDone?.(); }}
212
+ />
213
+ </HStack>
214
+ );
215
+
216
+ /** The signals holding the zoom of a spec: those of its interval params bound to the scales (`<param>_<field>`), null: no zoom */
217
+ export const zoomSignals = (spec: Record<string, unknown>): string[] => {
218
+ const encoding = (spec.encoding ?? {}) as Record<string, { field?: string } | undefined>;
219
+ return (Array.isArray(spec.params) ? (spec.params as { name?: string; bind?: unknown; select?: { encodings?: string[] } }[]) : [])
220
+ .filter((p) => p.name && p.bind === 'scales')
221
+ .flatMap((p) => (p.select?.encodings ?? ['x', 'y']).flatMap((channel) => {
222
+ const field = encoding[channel]?.field;
223
+ return field ? [`${p.name}_${field.replace(/\W/g, '_')}`] : [];
224
+ }));
225
+ };
226
+
143
227
  /** A Vega-Lite spec rendered with vega-embed (loaded on first use), `rows` as the dataset "rows" */
144
- export const VegaChart: React.FC<{ spec: Record<string, unknown>; rows: Record<string, unknown>[] }> = ({ spec, rows }) => {
228
+ export const VegaChart: React.FC<{
229
+ spec: Record<string, unknown>;
230
+ rows: Record<string, unknown>[];
231
+ /** where the inputs of the params go, under the chart when absent */
232
+ controls?: HTMLElement | null;
233
+ }> = ({ spec, rows, controls }) => {
145
234
  const ref = useRef<HTMLDivElement>(null);
146
235
  const [error, setError] = useState<string | null>(null);
147
236
  const { colorMode } = useColorMode();
237
+ // what is picked in the inputs of the chart, kept when its rows change
238
+ const picked = useRef(new Map<string, unknown>());
148
239
 
149
240
  useEffect(() => {
150
241
  let cancelled = false;
151
242
  let finalize: (() => void) | undefined;
152
243
  setError(null);
244
+ // one per chart made: an embed that ends too late fills one that is gone
245
+ const inputs = controls ? document.createElement('div') : undefined;
246
+ if (inputs) controls?.replaceChildren(inputs);
153
247
  import('vega-embed')
154
248
  .then(async ({ default: embed }) => {
155
249
  if (cancelled || !ref.current) return;
250
+ const params = boundParams(spec, rows, picked.current);
156
251
  const full = {
157
252
  ...spec,
253
+ ...(params ? { params } : {}),
158
254
  datasets: { ...((spec.datasets as object) || {}), rows },
159
255
  background: 'transparent',
160
256
  };
@@ -163,16 +259,37 @@ export const VegaChart: React.FC<{ spec: Record<string, unknown>; rows: Record<s
163
259
  theme: colorMode === 'dark' || isDarkPage() ? 'dark' : undefined,
164
260
  // canvas: the CSS reset of the page (font: inherit) would restyle the SVG texts Vega measured
165
261
  renderer: 'canvas',
262
+ ...(inputs ? { bind: inputs } : {}),
263
+ });
264
+ if (cancelled) {
265
+ result.finalize();
266
+ return;
267
+ }
268
+ finalize = result.finalize;
269
+ params?.forEach(({ name, bind }) => {
270
+ if (name && bind && typeof bind === 'object' && bind.input) {
271
+ result.view.addSignalListener(name, (_, value) => {
272
+ picked.current.set(name, value);
273
+ // other rows: the zoom on the previous ones would hide them (once the update is over)
274
+ const zoomed = zoomSignals(spec);
275
+ if (!zoomed.length) return;
276
+ window.setTimeout(() => {
277
+ if (cancelled) return;
278
+ zoomed.forEach((signal) => {
279
+ try { result.view.signal(signal, null); } catch { /* not a signal of this chart */ }
280
+ });
281
+ void result.view.runAsync();
282
+ });
283
+ });
284
+ }
166
285
  });
167
- if (cancelled) result.finalize();
168
- else finalize = result.finalize;
169
286
  })
170
287
  .catch((err: unknown) => !cancelled && setError(err instanceof Error ? err.message : String(err)));
171
288
  return () => {
172
289
  cancelled = true;
173
290
  finalize?.();
174
291
  };
175
- }, [spec, rows, colorMode]);
292
+ }, [spec, rows, colorMode, controls]);
176
293
 
177
294
  return (
178
295
  // room for the chart while it loads