@xeplr/ui-jobs 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1230 @@
1
+ import { Fragment, useCallback, useEffect, useMemo, useState } from 'react'
2
+ import { raiseConfirm, raiseSnackbar } from '@xeplr/ui-utils'
3
+ import { relativeTime } from './relativeTime.js'
4
+ import {
5
+ listJobs, listOccurrences, listJobOccurrences, listJobActions, listActiveRuns,
6
+ saveJob, deleteJob, triggerJob, pauseJob, resumeJob, fetchOccurrenceLogs,
7
+ fetchOptions, hasOptionSource
8
+ } from '../api/jobs.js'
9
+ import {
10
+ jobState, STATE_LABELS, describeCron, nextRunLabel, durationLabel,
11
+ latestByJob, prepareJobs, progressLabel, progressStale
12
+ } from './jobsList.js'
13
+ import CronScheduleField from '../components/CronScheduleField.jsx'
14
+ import './Jobs.css'
15
+
16
+ // SCHEDULED JOBS — @xeplr/jobs, in this product's chrome.
17
+ //
18
+ // A job is a registered ACTION plus the inputs to call it with, plus optionally
19
+ // a cron expression. The scheduler picks what is due and hands it to
20
+ // @xeplr/actions; each attempt is recorded as an occurrence.
21
+ //
22
+ // The page shows both halves, because neither is useful alone: a list of jobs
23
+ // with no history cannot tell you a nightly job has been failing for a week,
24
+ // and a list of runs with no jobs cannot tell you what is meant to happen.
25
+ //
26
+ // NOT the same thing as the import history on the Upload page. That is a log of
27
+ // files that were loaded; this is a scheduler.
28
+
29
+ function StatePill({ state }) {
30
+ return <span className={`jb-pill jb-pill--${state}`}>{STATE_LABELS[state] || state}</span>
31
+ }
32
+
33
+ // SIX STATUSES, not three. The executor and the reaper between them write
34
+ // running · success · failed · skipped · timedOut · interrupted, and this used
35
+ // to tone anything that was not success or failed as "busy" — so a job the
36
+ // reaper gave up on, and one abandoned by a deploy, both rendered in the same
37
+ // colour as one that is happily running right now. Three different situations,
38
+ // one appearance, and the two that need attention were the ones disguised.
39
+ const RUN_TONES = {
40
+ success: 'good',
41
+ failed: 'bad',
42
+ timedOut: 'bad',
43
+ interrupted: 'warn',
44
+ skipped: 'warn',
45
+ running: 'busy'
46
+ }
47
+ const RUN_LABELS = {
48
+ timedOut: 'timed out',
49
+ interrupted: 'interrupted',
50
+ skipped: 'skipped'
51
+ }
52
+ const RUN_TITLES = {
53
+ timedOut: 'Ran past its "give up after" and was given up on — the lock was released so the job could run again.',
54
+ interrupted: 'The process shut down while this was running.',
55
+ skipped: 'Not run — the previous occurrence was still going, or the action was not registered.'
56
+ }
57
+
58
+ function RunPill({ status }) {
59
+ return (
60
+ <span className={`jb-pill jb-pill--${RUN_TONES[status] || 'busy'}`} title={RUN_TITLES[status] || undefined}>
61
+ {RUN_LABELS[status] || status}
62
+ </span>
63
+ )
64
+ }
65
+
66
+ /* SVG, not a text glyph.
67
+ *
68
+ * The expander was a '\u203a' rotated 90deg, and a chevron character carries its own
69
+ * side bearings — rotated, that asymmetry becomes a visible lean inside a
70
+ * round button, which no amount of centring the BOX can fix. A path is
71
+ * symmetric about its own viewBox, so it lands where it looks like it should.
72
+ */
73
+ function Icon({ path, size = 16 }) {
74
+ return (
75
+ <svg className="jb-icon" width={size} height={size} viewBox="0 0 24 24" fill="none"
76
+ stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
77
+ aria-hidden="true" focusable="false">
78
+ {path}
79
+ </svg>
80
+ )
81
+ }
82
+
83
+ const ICON_CHEVRON = <polyline points="9 18 15 12 9 6" />
84
+ const ICON_RUN = <><polygon points="6 4 20 12 6 20 6 4" fill="currentColor" stroke="none" /></>
85
+ const ICON_EDIT = <><path d="M12 20h9" /><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" /></>
86
+ const ICON_DELETE = <><polyline points="3 6 5 6 21 6" /><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" /></>
87
+
88
+ /**
89
+ * ONE occurrence's log lines, under its own row.
90
+ *
91
+ * Fetched by referenceId — the occurrenceId — so this package never learns
92
+ * what the action did. Whatever ran wrote its lines under the key it was
93
+ * handed; this asks for that key back.
94
+ *
95
+ * Loaded on OPEN, not with the history: most occurrences are never opened, and
96
+ * a job with fifty runs would otherwise mean fifty log queries to render a
97
+ * table nobody has looked at yet.
98
+ */
99
+ function OccurrenceLogs({ occurrenceId }) {
100
+ const [lines, setLines] = useState(null)
101
+ const [error, setError] = useState(null)
102
+
103
+ useEffect(() => {
104
+ let alive = true
105
+ setError(null)
106
+ fetchOccurrenceLogs(occurrenceId)
107
+ .then((rows) => { if (alive) setLines(rows) })
108
+ // Same rule as the history above: a failed fetch must not render as an
109
+ // empty list, which reads as "this run said nothing".
110
+ .catch((err) => { if (alive) { setLines([]); setError(err.message || 'Could not load the log') } })
111
+ return () => { alive = false }
112
+ }, [occurrenceId])
113
+
114
+ if (lines === null) return <p className="muted jb-runs-note">Loading log…</p>
115
+ if (error) return <p className="jb-run-error jb-runs-note">{error}</p>
116
+ if (!lines.length) {
117
+ return <p className="muted jb-runs-note">This run wrote no log lines.</p>
118
+ }
119
+ return (
120
+ <ul className="jb-log">
121
+ {lines.map((line) => (
122
+ <li key={line.id} className={`jb-log-line jb-log-line--${line.level || 'info'}`}>
123
+ <span className="jb-log-at" title={new Date(line.createdAt).toLocaleString()}>
124
+ {new Date(line.createdAt).toLocaleTimeString()}
125
+ </span>
126
+ <span className="jb-log-msg">{line.message}</span>
127
+ </li>
128
+ ))}
129
+ </ul>
130
+ )
131
+ }
132
+
133
+ /**
134
+ * ONE job's run history, expanded under its row.
135
+ *
136
+ * Fetched when opened rather than taken from the page's own occurrence list.
137
+ * That list is every occurrence of every job (`?limit=0`) and exists to fill
138
+ * one "last run" cell per row; a job on a five-minute cron adds ~105,000 rows
139
+ * a year to it. Asking the server for this job's newest fifty is a bounded
140
+ * question with a bounded answer.
141
+ *
142
+ * Re-fetched on `refreshKey` so that pressing Run now updates the open history
143
+ * instead of leaving it showing the state from before the click.
144
+ */
145
+ function JobRuns({ jobId, refreshKey }) {
146
+ const [runs, setRuns] = useState(null)
147
+ const [error, setError] = useState(null)
148
+ // Which occurrence has its log open. One at a time: two open logs is two
149
+ // scrolling regions competing inside a row that is already an expansion.
150
+ const [openLogId, setOpenLogId] = useState(null)
151
+
152
+ useEffect(() => {
153
+ let alive = true
154
+ setError(null)
155
+ listJobOccurrences(jobId, 50)
156
+ .then((r) => { if (alive) setRuns(r) })
157
+ // A history that fails to load must SAY so. Rendering an empty list
158
+ // would read as "this job has never run", which is a different and much
159
+ // more alarming fact than "we could not fetch it".
160
+ .catch((err) => { if (alive) { setRuns([]); setError(err.message || 'Could not load the run history') } })
161
+ return () => { alive = false }
162
+ }, [jobId, refreshKey])
163
+
164
+ if (runs === null) return <p className="muted jb-runs-note">Loading runs…</p>
165
+ if (error) return <p className="jb-run-error jb-runs-note">{error}</p>
166
+ if (!runs.length) return <p className="muted jb-runs-note">This job has not run yet.</p>
167
+
168
+ return (
169
+ <div className="jb-history">
170
+ <table className="jb-history-table">
171
+ <thead>
172
+ <tr>
173
+ <th>Started</th>
174
+ <th>Outcome</th>
175
+ <th>Took</th>
176
+ <th>Trigger</th>
177
+ <th>Detail</th>
178
+ <th>Log</th>
179
+ </tr>
180
+ </thead>
181
+ <tbody>
182
+ {runs.map((run) => (
183
+ <Fragment key={run.id}>
184
+ <tr>
185
+ {/* Relative for reading, exact on hover — "3 hours ago" is what
186
+ you want 99% of the time and never what you want when
187
+ correlating against another system's timestamps. */}
188
+ <td title={new Date(run.startedAt).toLocaleString()}>
189
+ {relativeTime(run.startedAt, Date.now())}
190
+ </td>
191
+ <td>
192
+ <RunPill status={run.status} />
193
+ {run.retryCount > 0 && (
194
+ <span className="jb-retry" title={`Failed and was retried ${run.retryCount} time(s) within this same occurrence`}>
195
+ +{run.retryCount} retr{run.retryCount === 1 ? 'y' : 'ies'}
196
+ </span>
197
+ )}
198
+ </td>
199
+ <td>{durationLabel(run.durationMs) || <span className="jb-dim">—</span>}</td>
200
+ <td className="jb-dim">{run.triggeredBy?.type || '—'}</td>
201
+ <td>
202
+ {/* A late finish is not an error and must not read as one: the
203
+ work COMPLETED, after the reaper had already given up on
204
+ it. What it means is that "give up after" is set lower than
205
+ this job needs — a setting to change, not a failure to
206
+ investigate. */}
207
+ {run.lateFinish && (
208
+ <span className="jb-late" title={run.lateFinish.note}>
209
+ finished later, after {run.lateFinish.ranForMinutes}m — raise “give up after”
210
+ </span>
211
+ )}
212
+ {run.error && <span className="jb-run-error">{run.error.message || 'Failed'}</span>}
213
+ {!run.error && !run.lateFinish && <span className="jb-dim">—</span>}
214
+ </td>
215
+ <td>
216
+ {/* THE SAME EXPANDER AS THE ROW ABOVE IT. A worded Show/Hide
217
+ button repeated down a column is louder than the column it
218
+ labels, and this table already teaches the chevron idiom
219
+ one row up. */}
220
+ <button type="button"
221
+ className={`jb-log-toggle jb-caret${openLogId === run.id ? ' jb-caret--open' : ''}`}
222
+ aria-expanded={openLogId === run.id}
223
+ title={openLogId === run.id ? 'Hide this run’s log' : 'Show this run’s log'}
224
+ aria-label={openLogId === run.id ? 'Hide this run’s log' : 'Show this run’s log'}
225
+ onClick={() => setOpenLogId((id) => (id === run.id ? null : run.id))}>
226
+ <Icon path={ICON_CHEVRON} size={14} />
227
+ </button>
228
+ </td>
229
+ </tr>
230
+ {openLogId === run.id && (
231
+ <tr className="jb-log-row">
232
+ <td colSpan={6}><OccurrenceLogs occurrenceId={run.id} /></td>
233
+ </tr>
234
+ )}
235
+ </Fragment>
236
+ ))}
237
+ </tbody>
238
+ </table>
239
+ {runs.length === 50 && (
240
+ <p className="muted jb-runs-note">Showing the 50 most recent.</p>
241
+ )}
242
+ </div>
243
+ )
244
+ }
245
+
246
+ // ── the editor's three questions ──────────────────────────────────────────
247
+ //
248
+ // WHAT is it · WHAT does it need · WHEN does it run. In that order, because
249
+ // each one only makes sense once the one before it is answered: the inputs
250
+ // are the chosen action's inputs, and there is no point scheduling something
251
+ // that has not been described.
252
+ //
253
+ // A stepper rather than a wizard. All three are always reachable and Save is
254
+ // always available — someone editing a live job to change its cron should not
255
+ // have to walk past its name and its inputs to get there. The steps are for
256
+ // grouping, not for gatekeeping.
257
+ const STEPS = [
258
+ { key: 'job', label: 'Job', hint: 'What it is, and what it runs' },
259
+ { key: 'inputs', label: 'Inputs', hint: 'What that action needs' },
260
+ { key: 'schedule', label: 'Schedule', hint: 'When, and what if it goes wrong' }
261
+ ]
262
+
263
+ /**
264
+ * Fields a PERSON fills in.
265
+ *
266
+ * `system: true` means the server supplies it just before the action runs —
267
+ * a resolved connection, a dbType read off that connection. Rendering those
268
+ * would be asking somebody to type a password into a form, which is exactly
269
+ * what storing an id instead was for.
270
+ */
271
+ function visibleFields(action) {
272
+ return (action?.inputSchema || []).filter((f) => !f.system)
273
+ }
274
+
275
+ // ── labels ────────────────────────────────────────────────────────────────
276
+ //
277
+ // A schema field name is written for the action's code. Showing it raw put
278
+ // "connectionInfoId", "dbInfoId", "streaming_mode" and "batchSize" in front of
279
+ // people as though those were English.
280
+ //
281
+ // A schema may carry its own `label`; this is the fallback, and it is good
282
+ // enough that most fields will never need one. `Id`/`Info` are suffixes of the
283
+ // storage, not of the thing — you pick a Connection, not a connectionInfoId.
284
+ const LABEL_WORDS = { db: 'Database', sql: 'SQL', url: 'URL', id: 'ID', api: 'API' }
285
+
286
+ function fieldLabel(field) {
287
+ if (field.label) return field.label
288
+ return String(field.name)
289
+ .replace(/Id$/, '')
290
+ .replace(/Info$/, '')
291
+ .replace(/[_-]+/g, ' ')
292
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
293
+ .trim()
294
+ .split(' ')
295
+ .map((w, i) => {
296
+ const known = LABEL_WORDS[w.toLowerCase()]
297
+ if (known) return known
298
+ return i === 0 ? w.charAt(0).toUpperCase() + w.slice(1) : w.toLowerCase()
299
+ })
300
+ .join(' ')
301
+ }
302
+
303
+ /**
304
+ * Split the fields into what you fill in and what you almost never touch.
305
+ *
306
+ * ADVANCED = optional AND already has a default. That is precisely the set
307
+ * where doing nothing is the right answer — batchSize 1000, streaming_mode
308
+ * true — and leaving them inline buried the two fields that actually decide
309
+ * what the job does under six that do not.
310
+ *
311
+ * Collapsed, never hidden: the summary line lists what is in there and what it
312
+ * is currently set to, so nothing is a surprise on the way to Save.
313
+ */
314
+ function splitFields(fields) {
315
+ const primary = []
316
+ const advanced = []
317
+ fields.forEach((f) => {
318
+ if (!f.required && f.default !== undefined) advanced.push(f)
319
+ else primary.push(f)
320
+ })
321
+ return { primary, advanced }
322
+ }
323
+
324
+ /** The control's value: always a string, whatever the declared type. */
325
+ function toFieldValue(value) {
326
+ if (value === undefined || value === null) return ''
327
+ if (typeof value === 'object') return JSON.stringify(value, null, 2)
328
+ return String(value)
329
+ }
330
+
331
+ /**
332
+ * Strings back into the types the action declared — AT SAVE, not per keystroke.
333
+ *
334
+ * The form used to store `e.target.value` for everything, so a `number` field
335
+ * was saved as "1000" and a `boolean` as "true", and @xeplr/schema-handler
336
+ * rejected both at run time: `expected type number, got string`. Every job
337
+ * with a non-string input was unrunnable, and (until the logging fix) failed
338
+ * silently.
339
+ *
340
+ * Converting at save rather than on change matters for the JSON ones: parsing
341
+ * per keystroke destroys half-typed text, because `{"a"` is not valid JSON and
342
+ * never will be until the rest of it is typed.
343
+ */
344
+ function fromFieldValues(action, inputs) {
345
+ const out = {}
346
+ ;(action?.inputSchema || []).forEach((f) => {
347
+ if (f.system) return
348
+ const raw = inputs?.[f.name]
349
+ if (raw === undefined || raw === '') return
350
+ if (typeof raw !== 'string') { out[f.name] = raw; return }
351
+
352
+ if (f.type === 'number') {
353
+ const n = Number(raw)
354
+ out[f.name] = Number.isNaN(n) ? raw : n
355
+ } else if (f.type === 'boolean') {
356
+ out[f.name] = raw === 'true'
357
+ } else if (f.type === 'object' || f.type === 'array') {
358
+ // Left as the typed text if it will not parse. Saving is then refused
359
+ // with the field named, which is a better answer than silently dropping
360
+ // what somebody wrote.
361
+ try { out[f.name] = JSON.parse(raw) } catch (e) { out[f.name] = raw }
362
+ } else {
363
+ out[f.name] = raw
364
+ }
365
+ })
366
+ return out
367
+ }
368
+
369
+ /** Which JSON fields will not parse — named, so Save can say which. */
370
+ function badJson(action, inputs) {
371
+ return (action?.inputSchema || [])
372
+ .filter((f) => !f.system && (f.type === 'object' || f.type === 'array'))
373
+ .filter((f) => {
374
+ const raw = inputs?.[f.name]
375
+ if (typeof raw !== 'string' || raw === '') return false
376
+ try { JSON.parse(raw); return false } catch (e) { return true }
377
+ })
378
+ .map((f) => f.name)
379
+ }
380
+
381
+ /**
382
+ * A field whose choices come from the host — a saved connection, a database.
383
+ *
384
+ * Loads on mount, and again whenever the field it `dependsOn` changes, so
385
+ * choosing a connection narrows the database list instead of offering every
386
+ * database on every connection.
387
+ */
388
+ function RemoteSelect({ field, value, onChange, dependsOnValue }) {
389
+ const [options, setOptions] = useState(null)
390
+ const [failed, setFailed] = useState(false)
391
+ const id = `jb-in-${field.name}`
392
+
393
+ useEffect(() => {
394
+ let alive = true
395
+ // A dependent field cannot be chosen before the thing it depends on is.
396
+ if (field.dependsOn && !dependsOnValue) { setOptions([]); return undefined }
397
+ setFailed(false)
398
+ fetchOptions(field.optionsFrom, field.dependsOn
399
+ ? { name: field.dependsOn, value: dependsOnValue, clientKey: 'connectionId' }
400
+ : null)
401
+ .then((o) => { if (alive) setOptions(o) })
402
+ // SAYS SO rather than showing an empty list. "There are none" and "we
403
+ // could not ask" are different facts, and only one of them is the
404
+ // user's problem to solve.
405
+ .catch(() => { if (alive) { setOptions([]); setFailed(true) } })
406
+ return () => { alive = false }
407
+ }, [field.optionsFrom, field.dependsOn, dependsOnValue])
408
+
409
+ return (
410
+ <div className="jb-field">
411
+ <label htmlFor={id}>
412
+ {fieldLabel(field)}{field.required && <span className="jb-req"> *</span>}
413
+ </label>
414
+ <select id={id} value={value} onChange={(e) => onChange(e.target.value)}
415
+ disabled={Boolean(field.dependsOn) && !dependsOnValue}>
416
+ <option value="">
417
+ {field.dependsOn && !dependsOnValue ? `Choose ${field.dependsOn} first…`
418
+ : options === null ? 'Loading…'
419
+ : options.length ? 'Choose…'
420
+ : 'Nothing to choose from'}
421
+ </option>
422
+ {(options || []).map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
423
+ </select>
424
+ {failed
425
+ ? <span className="jb-help jb-warn">Could not load the list.</span>
426
+ : field.description && <span className="jb-help">{field.description}</span>}
427
+ </div>
428
+ )
429
+ }
430
+
431
+ /** One input, rendered as whatever its declared type actually is. */
432
+ function ActionInput({ field, value, onChange, inputs }) {
433
+ const id = `jb-in-${field.name}`
434
+ const common = { id, value, onChange: (e) => onChange(e.target.value) }
435
+
436
+ // A host-provided list, when the host has one. Without a source configured
437
+ // this falls through to the plain controls below rather than rendering a
438
+ // select nobody can fill.
439
+ if (field.optionsFrom && hasOptionSource(field.optionsFrom)) {
440
+ return (
441
+ <RemoteSelect field={field} value={value} onChange={onChange}
442
+ dependsOnValue={field.dependsOn ? inputs?.[field.dependsOn] : undefined} />
443
+ )
444
+ }
445
+
446
+ let control
447
+ if (Array.isArray(field.options) && field.options.length) {
448
+ // The validator already REFUSES anything outside this list, so a free-text
449
+ // box could only ever produce a run-time rejection.
450
+ control = (
451
+ <select {...common}>
452
+ <option value="">Choose…</option>
453
+ {field.options.map((o) => {
454
+ const val = typeof o === 'object' ? o.value : o
455
+ return <option key={val} value={val}>{typeof o === 'object' ? (o.label || o.value) : o}</option>
456
+ })}
457
+ </select>
458
+ )
459
+ } else if (field.type === 'boolean') {
460
+ control = (
461
+ <select {...common}>
462
+ <option value="">{field.default === undefined ? 'Choose…' : `Default (${field.default})`}</option>
463
+ <option value="true">true</option>
464
+ <option value="false">false</option>
465
+ </select>
466
+ )
467
+ } else if (field.type === 'number') {
468
+ control = <input type="number" {...common} placeholder={field.default !== undefined ? String(field.default) : ''} />
469
+ } else if (field.type === 'object' || field.type === 'array') {
470
+ control = <textarea rows={4} spellCheck="false" {...common} placeholder={field.type === 'array' ? '[]' : '{}'} />
471
+ } else {
472
+ control = <input {...common} placeholder={field.default !== undefined ? String(field.default) : ''} />
473
+ }
474
+
475
+ return (
476
+ <div className={`jb-field${field.type === 'object' || field.type === 'array' ? ' jb-field--wide' : ''}`}>
477
+ <label htmlFor={id}>
478
+ {fieldLabel(field)}{field.required && <span className="jb-req"> *</span>}
479
+ {/* The TYPE is shown only where it changes what you have to type —
480
+ JSON. Everywhere else "· string" was noise on every single row. */}
481
+ {(field.type === 'object' || field.type === 'array') &&
482
+ <span className="jb-type"> · {field.type === 'array' ? 'JSON list' : 'JSON'}</span>}
483
+ </label>
484
+ {control}
485
+ {field.description && <span className="jb-help">{field.description}</span>}
486
+ </div>
487
+ )
488
+ }
489
+
490
+ // The editor. A panel rather than a route: a job is a handful of fields, and a
491
+ // page you navigate to and back from for those is three navigations too many.
492
+ function JobEditor({ job, actions, onCancel, onSaved }) {
493
+ const [draft, setDraft] = useState(() => ({
494
+ name: job?.name || '',
495
+ description: job?.description || '',
496
+ actionName: job?.actionName || '',
497
+ schedule: job?.schedule || '',
498
+ // 'ready' | 'pause' — see xeplr-jobs migrations/0001_jobs.js. Editable
499
+ // HERE and not only from the list, because "write it now, start it later"
500
+ // is a normal thing to want: a job saved from this panel used to go
501
+ // straight to 'ready' and begin running on its next due time, so the only
502
+ // way to author one safely was to save it live and race to pause it.
503
+ // New jobs default to paused for that reason; an existing one keeps
504
+ // whatever it already is.
505
+ status: job?.status || 'pause',
506
+ // datetime-local wants 'YYYY-MM-DDTHH:mm' with no zone or seconds, and the
507
+ // API hands back a full ISO string — so it is trimmed on the way in and
508
+ // turned back into ISO on the way out (see submit).
509
+ startAt: job?.startAt ? String(job.startAt).slice(0, 16) : '',
510
+ retryLimit: job?.retryLimit ?? 0,
511
+ // Empty means "use the default" rather than 0 — 0 would be a tolerance of
512
+ // no minutes, which would time every job out instantly.
513
+ timeoutMinutes: job?.timeoutMinutes ?? '',
514
+ // Held as DISPLAY values (strings), converted back to their declared types
515
+ // at save — see fromFieldValues.
516
+ inputs: Object.fromEntries(
517
+ Object.entries(job?.inputs || {}).map(([k, v]) => [k, toFieldValue(v)])
518
+ )
519
+ }))
520
+ const [saving, setSaving] = useState(false)
521
+ const [step, setStep] = useState(0)
522
+
523
+ const action = actions.find((a) => a.name === draft.actionName) || null
524
+ const patch = (p) => setDraft((d) => ({ ...d, ...p }))
525
+
526
+ async function submit(e) {
527
+ e.preventDefault()
528
+
529
+ // Refused rather than saved with the broken text silently dropped or
530
+ // stored as a string the action will reject at 3am.
531
+ const broken = badJson(action, draft.inputs)
532
+ if (broken.length) {
533
+ setStep(1)
534
+ raiseSnackbar(`Not valid JSON: ${broken.join(', ')}`, { design: 'error' })
535
+ return
536
+ }
537
+
538
+ setSaving(true)
539
+ try {
540
+ await saveJob({
541
+ ...(job?.id ? { id: job.id } : {}),
542
+ name: draft.name.trim() || 'Untitled job',
543
+ description: draft.description || '',
544
+ actionName: draft.actionName,
545
+ // Trimmed to null rather than '': the model treats an absent schedule
546
+ // as manual-only, and an empty string is a cron expression the picker
547
+ // would try to parse.
548
+ schedule: draft.schedule.trim() || null,
549
+ // A job with no schedule is manual-only, so 'ready' vs 'pause' says
550
+ // nothing about it — the picker never looks at it either way. Sent as
551
+ // 'ready' so it does not sit in the list wearing a Paused badge that
552
+ // means nothing.
553
+ status: draft.schedule.trim() ? draft.status : 'ready',
554
+ // Sent as null rather than '' — the picker tests `startAt IS NULL`, and
555
+ // an empty string is not null.
556
+ startAt: draft.startAt ? new Date(draft.startAt).toISOString() : null,
557
+ retryLimit: Number(draft.retryLimit) || 0,
558
+ timeoutMinutes: draft.timeoutMinutes === '' ? null : Number(draft.timeoutMinutes),
559
+ // Converted back to the types the action declared. Sending the raw
560
+ // strings is what made every number/boolean field fail validation.
561
+ inputs: fromFieldValues(action, draft.inputs)
562
+ })
563
+ onSaved()
564
+ } catch (err) {
565
+ raiseSnackbar(err.message || 'Could not save the job', { design: 'error' })
566
+ } finally {
567
+ setSaving(false)
568
+ }
569
+ }
570
+
571
+ const fields = visibleFields(action)
572
+
573
+ return (
574
+ <form className="jb-editor" onSubmit={submit}>
575
+ <h2>{job?.id ? 'Edit job' : 'New job'}</h2>
576
+
577
+ {/* Clickable, always. Nothing is gated behind a step — see STEPS. */}
578
+ <nav className="jb-steps" aria-label="Sections">
579
+ {STEPS.map((s, i) => (
580
+ <button
581
+ key={s.key}
582
+ type="button"
583
+ className={`jb-step${i === step ? ' jb-step--on' : ''}${i < step ? ' jb-step--done' : ''}`}
584
+ aria-current={i === step ? 'step' : undefined}
585
+ onClick={() => setStep(i)}
586
+ >
587
+ <span className="jb-step-n">{i + 1}</span>
588
+ <span className="jb-step-t">{s.label}</span>
589
+ </button>
590
+ ))}
591
+ </nav>
592
+ <p className="jb-step-hint">{STEPS[step].hint}</p>
593
+
594
+ {/* ── 1. What it is, and what it runs ─────────────────────────────── */}
595
+ {step === 0 && (
596
+ <>
597
+ <div className="jb-field">
598
+ <label htmlFor="jb-name">Name</label>
599
+ <input id="jb-name" value={draft.name} placeholder="Nightly refresh"
600
+ onChange={(e) => patch({ name: e.target.value })} />
601
+ </div>
602
+
603
+ <div className="jb-field">
604
+ <label htmlFor="jb-desc">Description</label>
605
+ <input id="jb-desc" value={draft.description} placeholder="What is this for?"
606
+ onChange={(e) => patch({ description: e.target.value })} />
607
+ </div>
608
+
609
+ <div className="jb-field">
610
+ <label htmlFor="jb-action">Action</label>
611
+ <select id="jb-action" value={draft.actionName}
612
+ onChange={(e) => patch({ actionName: e.target.value, inputs: {} })}>
613
+ <option value="">Choose an action…</option>
614
+ {actions.map((a) => <option key={a.name} value={a.name}>{a.name}</option>)}
615
+ </select>
616
+ {action?.description && <span className="jb-help">{action.description}</span>}
617
+ {!actions.length && (
618
+ <span className="jb-help jb-warn">
619
+ No actions are registered on the server, so a job has nothing to run.
620
+ </span>
621
+ )}
622
+ </div>
623
+ </>
624
+ )}
625
+
626
+ {/* ── 2. What that action needs ───────────────────────────────────────
627
+ GENERATED FROM THE REGISTRY'S OWN SCHEMA. A hand-written form per
628
+ action would be a second description of it, and the day the two
629
+ disagree the form collects a field the action ignores. */}
630
+ {step === 1 && (
631
+ <>
632
+ {!action && <p className="muted">Choose an action first — its inputs are its own.</p>}
633
+ {action && !fields.length && (
634
+ <p className="muted">
635
+ <code className="jb-code">{action.name}</code> needs nothing filled in. Straight on to the schedule.
636
+ </p>
637
+ )}
638
+ {action && (() => {
639
+ const { primary, advanced } = splitFields(fields)
640
+ const render = (f) => (
641
+ <ActionInput
642
+ key={f.name}
643
+ field={f}
644
+ inputs={draft.inputs}
645
+ value={draft.inputs?.[f.name] ?? ''}
646
+ onChange={(v) => patch({ inputs: { ...draft.inputs, [f.name]: v } })}
647
+ />
648
+ )
649
+ return (
650
+ <>
651
+ <div className="jb-grid">{primary.map(render)}</div>
652
+ {advanced.length > 0 && (
653
+ /* COLLAPSED, NOT HIDDEN. The summary names every field in
654
+ here and its current value, so closing it never conceals
655
+ something that is about to be saved. */
656
+ <details className="jb-advanced">
657
+ <summary>
658
+ Advanced
659
+ <span className="jb-dim">
660
+ {' — '}
661
+ {advanced.map((f) => `${fieldLabel(f)} ${draft.inputs?.[f.name] ?? f.default}`).join(' · ')}
662
+ </span>
663
+ </summary>
664
+ <div className="jb-grid">{advanced.map(render)}</div>
665
+ </details>
666
+ )}
667
+ </>
668
+ )
669
+ })()}
670
+ </>
671
+ )}
672
+
673
+ {/* ── 3. When, and what if it goes wrong ─────────────────────────── */}
674
+ {step === 2 && (
675
+ <>
676
+ <CronScheduleField id="jb-sched" value={draft.schedule} onChange={(schedule) => patch({ schedule })} />
677
+
678
+ {/* ACTIVE OR PAUSED, decided while writing the job rather than after it
679
+ is already live — "save it, but do not start it yet" is a normal
680
+ thing to want, and without this the only way to author a scheduled
681
+ job was to save it live and race to pause it.
682
+
683
+ ALWAYS SHOWN. It was briefly hidden unless a schedule was set, on the
684
+ grounds that the scheduler never looks at a manual-only job so the
685
+ choice decides nothing. True, but a field that disappears is worse
686
+ than one that is explained: the first thing it did was look missing.
687
+ Disabled instead, saying why. */}
688
+ <div className="jb-field">
689
+ <label htmlFor="jb-status">Status</label>
690
+ <select
691
+ id="jb-status"
692
+ value={draft.schedule.trim() ? draft.status : 'ready'}
693
+ disabled={!draft.schedule.trim()}
694
+ onChange={(e) => patch({ status: e.target.value })}
695
+ >
696
+ <option value="ready">Active — the scheduler runs this when it is due</option>
697
+ <option value="pause">Paused — saved, but nothing runs until you resume it</option>
698
+ </select>
699
+ <span className="jb-help">
700
+ {!draft.schedule.trim()
701
+ ? 'This job has no schedule, so nothing runs it on its own — you trigger it yourself. Set a schedule above to be able to pause it.'
702
+ : draft.status === 'ready'
703
+ ? 'Runs on the schedule above. Pause it any time from the list.'
704
+ : 'Kept exactly as written and left alone. Nothing runs until this is set to Active.'}
705
+ </span>
706
+ </div>
707
+
708
+ {/* START DATE — "every fifteen minutes, but not before January".
709
+ A separate field from the schedule because it answers a different
710
+ question: the schedule says how often, this says not before when. */}
711
+ {draft.schedule.trim() && (
712
+ <div className="jb-field">
713
+ <label htmlFor="jb-startat">Start from</label>
714
+ <input
715
+ id="jb-startat"
716
+ type="datetime-local"
717
+ value={draft.startAt}
718
+ onChange={(e) => patch({ startAt: e.target.value })}
719
+ />
720
+ <span className="jb-help">
721
+ {draft.startAt
722
+ ? 'The schedule is ignored until this moment passes, then runs as normal.'
723
+ : 'Leave empty to start as soon as the schedule says.'}
724
+ </span>
725
+ </div>
726
+ )}
727
+
728
+ {/* RETRY — off by default. An action that failed once usually fails
729
+ again, and silently re-running something that moves data is worse
730
+ than leaving it failed and visible. */}
731
+ <div className="jb-field">
732
+ <label htmlFor="jb-retry">Retry on failure</label>
733
+ <select
734
+ id="jb-retry"
735
+ value={String(draft.retryLimit)}
736
+ onChange={(e) => patch({ retryLimit: Number(e.target.value) })}
737
+ >
738
+ <option value="0">No — leave it failed</option>
739
+ <option value="1">Retry once</option>
740
+ <option value="2">Retry twice</option>
741
+ <option value="3">Retry 3 times</option>
742
+ </select>
743
+ <span className="jb-help">
744
+ {draft.retryLimit > 0
745
+ ? 'Retries happen immediately, within the same run — the history shows one attempt with a retry count, not several runs.'
746
+ : 'A failed run stays failed and is visible in the history.'}
747
+ </span>
748
+ </div>
749
+
750
+ {/* TIMEOUT — the reaper's tolerance. Not a limit on how long the job may
751
+ take; a limit on how long we keep believing a worker that has stopped
752
+ reporting. See reapTimedOut in @xeplr/jobs' scheduler. */}
753
+ <div className="jb-field">
754
+ <label htmlFor="jb-timeout">Give up after</label>
755
+ <input
756
+ id="jb-timeout"
757
+ type="number"
758
+ min="1"
759
+ placeholder="30"
760
+ value={draft.timeoutMinutes}
761
+ onChange={(e) => patch({ timeoutMinutes: e.target.value })}
762
+ />
763
+ <span className="jb-help">
764
+ Minutes. If this job is still running after that, it is marked
765
+ “timed out” and unlocked so it can run again — the worker was most
766
+ likely killed. Leave empty for the default of 30.
767
+ {' '}Set it higher than the job ever legitimately takes.
768
+ </span>
769
+ </div>
770
+ </>
771
+ )}
772
+
773
+ <div className="jb-editor-actions">
774
+ <button type="button" onClick={onCancel}>Cancel</button>
775
+ <span className="jb-editor-nav">
776
+ {step > 0 && <button type="button" onClick={() => setStep(step - 1)}>Back</button>}
777
+ {step < STEPS.length - 1 && (
778
+ <button type="button" onClick={() => setStep(step + 1)} disabled={!draft.actionName}
779
+ title={draft.actionName ? undefined : 'Choose an action first'}>
780
+ Next
781
+ </button>
782
+ )}
783
+ </span>
784
+ {/* AVAILABLE ON EVERY STEP. Changing one job's cron should not mean
785
+ walking past its name and its inputs to reach a button. */}
786
+ <button type="submit" className="jb-primary" disabled={saving || !draft.actionName}>
787
+ {saving ? 'Saving…' : 'Save job'}
788
+ </button>
789
+ </div>
790
+ </form>
791
+ )
792
+ }
793
+
794
+ /**
795
+ * The jobs screen.
796
+ *
797
+ * Everything a HOST supplies is a prop, and all of it is optional — the page
798
+ * renders correctly standalone with none of it. What a host owns is its own
799
+ * chrome (a breadcrumb, a link to a sibling product); what this package owns
800
+ * is jobs.
801
+ *
802
+ * @param {Function} [props.breadcrumb] - the host's breadcrumb component
803
+ * @param {JSX.Element|string} [props.uploadLink] - a link to wherever the host
804
+ * loads files, if it has such a screen
805
+ * @param {JSX.Element} [props.connectLink] - a link to the workflow canvas,
806
+ * for connecting jobs to each other so one starts when another finishes.
807
+ *
808
+ * SUPPLIED BY THE HOST, not imported. This package must not depend on
809
+ * @xeplr/workflow: workflow already calls jobs — over HTTP, at run time, to
810
+ * start a job step — and importing its UI here would close that loop into a
811
+ * circular dependency between two packages that are deliberately installable
812
+ * on their own. Jobs is also the lower of the two: a deployment can have
813
+ * jobs and no workflow, and it should not be made to install one to render
814
+ * its own list.
815
+ *
816
+ * So the host, which is the only thing that knows both are present, passes
817
+ * the link. Omitted, nothing is rendered — the screen is complete without
818
+ * it, exactly as uploadLink is.
819
+ */
820
+ export default function Jobs({ breadcrumb: Breadcrumb, uploadLink, connectLink } = {}) {
821
+ const [jobs, setJobs] = useState(null)
822
+ const [runs, setRuns] = useState([])
823
+ const [actions, setActions] = useState([])
824
+ const [error, setError] = useState(null)
825
+ const [query, setQuery] = useState('')
826
+ const [sort, setSort] = useState('name')
827
+ const [editing, setEditing] = useState(null) // job object, {} for new, null for closed
828
+ const [busyId, setBusyId] = useState(null)
829
+ const [openRuns, setOpenRuns] = useState(null) // jobId whose history is expanded
830
+ // Bumped by anything that creates an occurrence, so an OPEN history refetches
831
+ // rather than sitting there showing the state from before Run now was pressed.
832
+ const [runsVersion, setRunsVersion] = useState(0)
833
+
834
+ const load = useCallback(async () => {
835
+ try {
836
+ const [j, o, a] = await Promise.all([listJobs(), listOccurrences(), listJobActions()])
837
+ setJobs(j)
838
+ setRuns(o)
839
+ setActions(a)
840
+ setError(null)
841
+ } catch (err) {
842
+ setError(err.message || 'Could not load jobs')
843
+ setJobs([])
844
+ }
845
+ }, [])
846
+
847
+ useEffect(() => { load() }, [load])
848
+
849
+ // ── LIVE UPDATES ────────────────────────────────────────────────────────
850
+ //
851
+ // This used to call load() on a timer, which is three requests — the job
852
+ // list, the ACTION CATALOGUE, and every occurrence ever recorded
853
+ // (`limit=0`) — every four seconds for as long as anything was running. On
854
+ // a long movement that is the page re-reading its entire history hundreds of
855
+ // times to discover that one number changed.
856
+ //
857
+ // Now it polls /jobs/active: only what is in flight, bounded by the
858
+ // executor's concurrency cap, with each run's live progress attached.
859
+ //
860
+ // TWO SPEEDS, because there are two different questions:
861
+ //
862
+ // something running 2s — the numbers are moving and are worth
863
+ // watching move.
864
+ // nothing running 15s — nobody has pressed anything, but a CRON job
865
+ // can start on its own and this is what
866
+ // notices. The old gate polled only when a run
867
+ // was ALREADY known about, so a scheduled job
868
+ // starting by itself appeared on the page
869
+ // whenever somebody next reloaded it.
870
+ //
871
+ // And ONE full load() on the edge from "something running" to "nothing
872
+ // running": the small endpoint reports what is in flight, so by definition
873
+ // it says nothing about the run that has just finished, and the final
874
+ // status, duration and output still have to be fetched. Once, on the edge —
875
+ // not every tick.
876
+ //
877
+ // The toggle is for the whole SCREEN rather than per job, because one
878
+ // request already covers every running job. A per-job switch would multiply
879
+ // requests rather than reduce them, and would need somewhere to keep a
880
+ // preference that only affects what a screen looks like.
881
+ const [live, setLive] = useState(true)
882
+ const [active, setActive] = useState([])
883
+
884
+ const anyRunning = active.length > 0 || (jobs || []).some((j) => j.running)
885
+
886
+ useEffect(() => {
887
+ if (!live) return undefined
888
+ let stopped = false
889
+ let sawActive = false
890
+
891
+ const tick = async () => {
892
+ try {
893
+ const rows = await listActiveRuns()
894
+ if (stopped) return
895
+ setActive(rows)
896
+ if (sawActive && rows.length === 0) load() // the edge, one direction only
897
+ sawActive = rows.length > 0
898
+ } catch (err) {
899
+ // A failed poll is not a failed page. The next tick tries again, and a
900
+ // snackbar every two seconds because the network blinked would be
901
+ // worse than the stale number it was warning about.
902
+ }
903
+ }
904
+
905
+ const t = setInterval(tick, anyRunning ? 2000 : 15000)
906
+ tick()
907
+ return () => { stopped = true; clearInterval(t) }
908
+ // Depends on anyRunning as a BOOLEAN, so the interval is rebuilt when the
909
+ // page changes speed rather than every time a row count ticks up.
910
+ // eslint-disable-next-line react-hooks/exhaustive-deps
911
+ }, [live, anyRunning, load])
912
+
913
+ // The live run for each job, so a row can show its progress.
914
+ const activeByJob = useMemo(
915
+ () => Object.fromEntries((active || []).map((o) => [o.jobId, o])),
916
+ [active]
917
+ )
918
+
919
+ const rows = useMemo(() => prepareJobs(jobs || [], { query, sort }), [jobs, query, sort])
920
+ const lastRun = useMemo(() => latestByJob(runs), [runs])
921
+ const recent = useMemo(
922
+ () => runs.slice().sort((a, b) => new Date(b.startedAt) - new Date(a.startedAt)).slice(0, 12),
923
+ [runs]
924
+ )
925
+ const jobsById = useMemo(
926
+ () => Object.fromEntries((jobs || []).map((j) => [j.id, j])),
927
+ [jobs]
928
+ )
929
+
930
+ async function act(id, fn, failure) {
931
+ setBusyId(id)
932
+ try {
933
+ await fn(id)
934
+ await load()
935
+ setRunsVersion((v) => v + 1)
936
+ } catch (err) {
937
+ raiseSnackbar(err.message || failure, { design: 'error' })
938
+ } finally {
939
+ setBusyId(null)
940
+ }
941
+ }
942
+
943
+ async function remove(job) {
944
+ const ok = await raiseConfirm(`Delete "${job.name}"? Its run history stays.`, { design: 'danger' })
945
+ if (!ok) return
946
+ act(job.id, deleteJob, 'Could not delete the job')
947
+ }
948
+
949
+ return (
950
+ <section className="jb-page">
951
+ {/* The host's own breadcrumb, if it has one. Standalone there is
952
+ nothing to navigate back up to, so there is nothing to render —
953
+ which is why this package does not ship one of its own. */}
954
+ {Breadcrumb ? <Breadcrumb items={[{ label: 'Jobs' }]} /> : null}
955
+
956
+ <header className="jb-head">
957
+ <div>
958
+ <h1>Jobs</h1>
959
+ <p className="muted">
960
+ An action, on a schedule. The server runs what is due and records every attempt.
961
+ </p>
962
+ </div>
963
+ <div className="jb-head-tools">
964
+ <input className="jb-search" type="search" value={query} placeholder="Search jobs…"
965
+ aria-label="Search jobs" onChange={(e) => setQuery(e.target.value)} />
966
+ <select className="jb-sort" value={sort} onChange={(e) => setSort(e.target.value)} aria-label="Sort by">
967
+ <option value="name">Name</option>
968
+ <option value="next">Next run</option>
969
+ <option value="action">Action</option>
970
+ </select>
971
+ {/* LIVE UPDATES, for the screen rather than per job — one request
972
+ already covers everything that is running.
973
+
974
+ Checked by default, which it can afford to be: with nothing
975
+ running this polls a small endpoint every fifteen seconds, and
976
+ the alternative was a page somebody had to keep reloading by
977
+ hand. Unchecking it makes the screen completely quiet.
978
+
979
+ The count is here rather than in a row because it is the answer
980
+ to "is anything happening at all", which is the question you ask
981
+ before you go looking for which job. */}
982
+ <label className="jb-live" title={live
983
+ ? 'Refreshing while jobs are running. Uncheck to stop.'
984
+ : 'The page will not refresh itself.'}>
985
+ <input type="checkbox" checked={live} onChange={(e) => setLive(e.target.checked)} />
986
+ <span>Live updates</span>
987
+ {live && active.length > 0 && (
988
+ <span className="jb-live-count">{active.length} running</span>
989
+ )}
990
+ </label>
991
+ {/* Before "+ New job", because connecting jobs is something you do
992
+ to the ones already listed — a secondary action ON this screen's
993
+ content, where the primary one creates more of it. */}
994
+ {connectLink}
995
+ <button type="button" className="jb-primary" onClick={() => setEditing({})}>+ New job</button>
996
+ </div>
997
+ </header>
998
+
999
+ {error && <p className="report-builder-error">{error}</p>}
1000
+ {jobs === null && !error && <p className="muted">Loading…</p>}
1001
+
1002
+ {editing && (
1003
+ <JobEditor
1004
+ job={editing.id ? editing : null}
1005
+ actions={actions}
1006
+ onCancel={() => setEditing(null)}
1007
+ onSaved={() => { setEditing(null); load() }}
1008
+ />
1009
+ )}
1010
+
1011
+ {jobs && jobs.length === 0 && !editing && (
1012
+ <div className="jb-empty">
1013
+ <p className="jb-empty-title">No jobs yet</p>
1014
+ <p className="muted">
1015
+ A job runs one registered action — on a cron, or whenever you press Run.
1016
+ </p>
1017
+ <button type="button" className="jb-primary" onClick={() => setEditing({})}>Create the first one</button>
1018
+ </div>
1019
+ )}
1020
+
1021
+ {jobs && jobs.length > 0 && (
1022
+ <div className="jb-table-wrap">
1023
+ <table className="jb-table">
1024
+ <thead>
1025
+ <tr>
1026
+ <th>Job</th>
1027
+ <th>Action</th>
1028
+ <th>Schedule</th>
1029
+ <th>Next run</th>
1030
+ <th>Last run</th>
1031
+ {/* The toggle is not one of the actions. Pausing is a STATE
1032
+ this job is in — visible at a glance down the column,
1033
+ without reading a button's label to work out which way it
1034
+ currently sits. */}
1035
+ <th>Enabled</th>
1036
+ <th>Actions</th>
1037
+ </tr>
1038
+ </thead>
1039
+ <tbody>
1040
+ {rows.map((job) => {
1041
+ const state = jobState(job)
1042
+ const last = lastRun[job.id]
1043
+ const liveRun = activeByJob[job.id]
1044
+ const busy = busyId === job.id
1045
+ const open = openRuns === job.id
1046
+ return (
1047
+ <Fragment key={job.id}>
1048
+ <tr className={open ? 'jb-row--open' : undefined}>
1049
+ {/* ONE LINE PER ROW, everywhere in this table.
1050
+ Stacked name/description/badge made every row three
1051
+ lines tall, so eight jobs filled a screen and the
1052
+ columns stopped lining up as anything scannable. The
1053
+ description is still here — as the cell's title, where
1054
+ it costs no height. */}
1055
+ <td className="jb-cell-job" title={job.description || job.name}>
1056
+ <span className="jb-name">{job.name}</span>
1057
+ <StatePill state={state} />
1058
+ {/* WHAT IT HAS DONE SO FAR, next to the pill that says it
1059
+ is running. Absent until the first throttled write
1060
+ lands, and absent forever for an action that reports
1061
+ nothing — so "Running" on its own stays a complete
1062
+ answer rather than looking like a number failed to
1063
+ load.
1064
+
1065
+ A count, not a bar: there is no total to divide by
1066
+ (a query source has no row count without running it
1067
+ twice), and a bar would have to invent one. */}
1068
+ {liveRun && progressLabel(liveRun) && (
1069
+ <span
1070
+ className={progressStale(liveRun) ? 'jb-progress jb-progress--stale' : 'jb-progress'}
1071
+ title={progressStale(liveRun)
1072
+ ? 'No update recently — the run may be in a long final write, or the worker may have died.'
1073
+ : `Rows read so far. Last update ${new Date(liveRun.progress.at).toLocaleTimeString()}.`}
1074
+ >
1075
+ {progressLabel(liveRun)}
1076
+ </span>
1077
+ )}
1078
+ </td>
1079
+ <td><code className="jb-code">{job.actionName}</code></td>
1080
+ <td>
1081
+ {/* The phrase reads; the cron is the exact answer you
1082
+ want only when the phrase looks wrong. Title, not a
1083
+ second line. */}
1084
+ {job.schedule
1085
+ ? <span title={job.schedule}>{describeCron(job.schedule) || 'Custom'}</span>
1086
+ : <span className="jb-dim">—</span>}
1087
+ </td>
1088
+ <td>
1089
+ {/* THREE ANSWERS, NOT TWO. This used to show a bare em
1090
+ dash for anything that was not an active job with a
1091
+ next run — so a paused job and a manual-only job
1092
+ looked identical, and both looked like a missing
1093
+ value rather than an explanation.
1094
+
1095
+ A paused job HAS a nextRunAt (the model computes one
1096
+ on save regardless of status), and showing it would
1097
+ be a promise nothing intends to keep. Saying "Paused"
1098
+ is the honest answer: there is no next run, and here
1099
+ is why. */}
1100
+ {!job.schedule
1101
+ ? <span className="jb-dim" title="Manual only — this job has no schedule">—</span>
1102
+ : state === 'paused'
1103
+ ? <span className="jb-dim">Paused</span>
1104
+ : job.nextRunAt
1105
+ ? nextRunLabel(job.nextRunAt, Date.now())
1106
+ : <span className="jb-dim">—</span>}
1107
+ </td>
1108
+ {/* The last run is also the way IN to every run. A history
1109
+ behind a separate button would be a second thing to
1110
+ find; the cell that already answers "how did it go
1111
+ last time" is where somebody asks "and before that?" */}
1112
+ <td>
1113
+ {last ? (
1114
+ <button type="button" className="jb-lastrun jb-lastrun--btn"
1115
+ aria-expanded={open}
1116
+ title={open ? 'Hide this job’s runs' : 'Show this job’s runs'}
1117
+ onClick={() => setOpenRuns(open ? null : job.id)}>
1118
+ <RunPill status={last.status} />
1119
+ <span className="jb-dim">{relativeTime(last.startedAt, Date.now())}</span>
1120
+ <span className={`jb-caret${open ? ' jb-caret--open' : ''}`}>
1121
+ <Icon path={ICON_CHEVRON} size={14} />
1122
+ </span>
1123
+ </button>
1124
+ ) : <span className="jb-dim">never</span>}
1125
+ </td>
1126
+ {/* ON means the scheduler picks this up. A switch rather
1127
+ than a Pause/Resume button because the two buttons
1128
+ showed the ACTION and left the state to be inferred
1129
+ from it — the reverse of what a list is for. A job with
1130
+ no schedule has nothing to enable, so the switch is off
1131
+ and disabled rather than absent, which would leave a
1132
+ hole in the column. */}
1133
+ <td className="jb-row-toggle">
1134
+ <label className="jb-switch"
1135
+ title={!job.schedule
1136
+ ? 'No schedule — there is nothing for the scheduler to pick up'
1137
+ : job.status === 'pause'
1138
+ ? 'Paused — turn on to let the schedule run again'
1139
+ : 'Running on its schedule — turn off to pause it'}>
1140
+ <input type="checkbox" role="switch"
1141
+ checked={Boolean(job.schedule) && job.status !== 'pause'}
1142
+ disabled={busy || !job.schedule}
1143
+ onChange={(e) => act(
1144
+ job.id,
1145
+ e.target.checked ? resumeJob : pauseJob,
1146
+ e.target.checked ? 'Could not resume' : 'Could not pause'
1147
+ )} />
1148
+ <span className="jb-switch-track" aria-hidden="true"><span className="jb-switch-thumb" /></span>
1149
+ <span className="jb-switch-label">
1150
+ {!job.schedule ? 'No schedule' : job.status === 'pause' ? 'Paused' : 'On'}
1151
+ </span>
1152
+ </label>
1153
+ </td>
1154
+ {/* ICONS, with the words moved into title/aria-label.
1155
+ Three labelled buttons per row is a paragraph of text
1156
+ repeated down the page, and it is the widest column in
1157
+ a table whose actual content is the job. The label is
1158
+ still there for anyone who needs it — on hover, and to
1159
+ a screen reader always. */}
1160
+ <td className="jb-row-actions">
1161
+ <button type="button" disabled={busy} title="Run now" aria-label="Run now"
1162
+ onClick={() => act(job.id, triggerJob, 'Could not trigger the job')}>
1163
+ <Icon path={ICON_RUN} size={14} />
1164
+ </button>
1165
+ <button type="button" disabled={busy} title="Edit" aria-label="Edit"
1166
+ onClick={() => setEditing(job)}>
1167
+ <Icon path={ICON_EDIT} />
1168
+ </button>
1169
+ <button type="button" className="jb-danger" disabled={busy}
1170
+ title="Delete" aria-label="Delete" onClick={() => remove(job)}>
1171
+ <Icon path={ICON_DELETE} />
1172
+ </button>
1173
+ </td>
1174
+ </tr>
1175
+ {open && (
1176
+ <tr className="jb-runs-row">
1177
+ <td colSpan={7}>
1178
+ <JobRuns jobId={job.id} refreshKey={runsVersion} />
1179
+ </td>
1180
+ </tr>
1181
+ )}
1182
+ </Fragment>
1183
+ )
1184
+ })}
1185
+ </tbody>
1186
+ </table>
1187
+ {rows.length === 0 && (
1188
+ <div className="jb-empty jb-empty--inline">
1189
+ <p className="muted">Nothing matches “{query}”.</p>
1190
+ <button type="button" onClick={() => setQuery('')}>Clear the search</button>
1191
+ </div>
1192
+ )}
1193
+ </div>
1194
+ )}
1195
+
1196
+ {/* THE HISTORY, on the same page. A list of jobs cannot tell you a
1197
+ nightly job has been failing all week; a list of runs cannot tell you
1198
+ what was meant to happen. Both, or neither is much use. */}
1199
+ {recent.length > 0 && (
1200
+ <>
1201
+ <h2 className="jb-section">Recent runs</h2>
1202
+ <div className="jb-runs">
1203
+ {recent.map((run) => (
1204
+ <div className="jb-run" key={run.id}>
1205
+ <RunPill status={run.status} />
1206
+ <span className="jb-run-name">{jobsById[run.jobId]?.name || 'Deleted job'}</span>
1207
+ <span className="jb-dim">
1208
+ {relativeTime(run.startedAt, Date.now())}
1209
+ {durationLabel(run.durationMs) ? ` · ${durationLabel(run.durationMs)}` : ''}
1210
+ {run.triggeredBy?.type ? ` · ${run.triggeredBy.type}` : ''}
1211
+ </span>
1212
+ {/* The message, not the stack. What went wrong belongs on the
1213
+ row; where it went wrong belongs in the server log. */}
1214
+ {run.error && <span className="jb-run-error">{run.error.message || 'Failed'}</span>}
1215
+ </div>
1216
+ ))}
1217
+ </div>
1218
+ </>
1219
+ )}
1220
+
1221
+ <p className="muted jb-footnote">
1222
+ Loading a file into a table is recorded separately — see{' '}
1223
+ {/* Loading a FILE is a different product and not necessarily present
1224
+ — a host that has one passes a link, and one that does not gets a
1225
+ sentence that still reads correctly without it. */}
1226
+ {uploadLink || 'the upload screen'}.
1227
+ </p>
1228
+ </section>
1229
+ )
1230
+ }