Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Command Center (MCC)8 * File : apps/web/src/features/jobs/JobsScreen.tsx9 * Module : features10 * Repository : https://git.spboucher.ai/maclustr-command-center11 * Project Website : https://clustr.spboucher.ai12 * Created : 2026-11-1813 * Last Modified : 2026-11-1814 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142"use client";43import Link from "next/link";44import { useRouter } from "next/navigation";45import { useQueryClient } from "@tanstack/react-query";46import { Suspense, useState } from "react";47import { apiDelete, apiPatch, type ApiQuery, type Schemas } from "@/api/client";48import { invalidatePaths, useApiList, useApiQuery } from "@/api/query";49import { CommitField, When, useUrlState } from "@/features/services/url";50import { NodeLink, useNodeOptions } from "@/features/shared/nodes";51import { useI18n } from "@/i18n";52import { Page, RequirePermission } from "@/shell/AppShell";53import { useSession } from "@/shell/session";54import { Badge, Button, Combobox, ConfirmDialog, DataStamp, DataTable, EmptyState, ErrorState, IconButton, LoadMore, Meter, Observed, QueryBoundary, SelectField, SkeletonRows, StateDot, TabPanel, Tabs, Tooltip, jobTone, useErrorMessage, useToast, type Column, type IconName } from "@/ui";55import { ScheduleDialog, SubmitJobDialog } from "./forms";5657type Job = Schemas["Job"];58type Schedule = Schemas["JobSchedule"];59const STATES = ["queued", "running", "succeeded", "failed", "cancelled", "timed_out"] as const;60const TABS = ["jobs", "schedules", "templates"] as const;61type Tab = (typeof TABS)[number];6263export const jobIcon = (s: Schemas["JobState"]): IconName => (s === "queued" ? "clock" : s === "running" ? "running" : s === "succeeded" ? "ok" : s === "cancelled" ? "offline" : "critical");6465export function JobProgress({ job }: { job: Job }) {66 const { t, fmt } = useI18n();67 if (job.progress === undefined) return <span className="mcc-unmeasured">{t("jobs.progressNone")}</span>;68 const pct = job.progress * 100;69 return <Meter value={pct} label={t("jobs.col.progress")} text={fmt.percent(pct)} tone={job.state === "failed" || job.state === "timed_out" ? "critical" : job.state === "succeeded" ? "ok" : "info"} />;70}7172function JobsTab({ onSubmit }: { onSubmit: () => void }) {73 const { t } = useI18n();74 const { can } = useSession();75 const url = useUrlState();76 const nodes = useNodeOptions();77 const state = STATES.find((s) => s === url.get("state"));78 const query: ApiQuery<"/jobs"> = { limit: 100, ...(state ? { state } : {}), ...(url.get("template") ? { template: url.get("template") } : {}), ...(url.get("node") ? { node_id: url.get("node") } : {}) };79 const list = useApiList("/jobs", { query }, { refetchInterval: 30_000 });80 const filtered = !!state || url.get("template") !== "" || url.get("node") !== "";81 const columns: Column<Job>[] = [82 { id: "template", header: t("jobs.template"), sortValue: (j) => j.template, cell: (j) => <Link href={`/jobs/${j.id}`} className="rowlink mono">{j.template}</Link> },83 { id: "state", header: t("common.state"), sortValue: (j) => j.state, cell: (j) => <StateDot tone={jobTone(j.state)} icon={jobIcon(j.state)} label={t(`states.job.${j.state}`)} /> },84 { id: "progress", header: t("jobs.col.progress"), sortValue: (j) => j.progress, cell: (j) => <div className="job-progress"><JobProgress job={j} /></div>, hide: "sm" },85 { id: "node", header: t("common.node"), sortValue: (j) => j.node_alias, cell: (j) => (j.node_id ? <NodeLink id={j.node_id} alias={j.node_alias} /> : <span className="faint">{t("jobs.notPlaced")}</span>) },86 { id: "owner", header: t("jobs.col.owner"), sortValue: (j) => j.owner_display_name, cell: (j) => j.owner_display_name ?? <span className="faint">{j.schedule_id ? t("jobs.ownerSchedule") : t("common.unknown")}</span>, hide: "md" },87 { id: "attempt", header: t("jobs.col.attempt"), align: "right", sortValue: (j) => j.attempt, cell: (j) => `${j.attempt} / ${j.max_attempts}`, hide: "sm" },88 { id: "created", header: t("common.created"), sortValue: (j) => j.created_at, cell: (j) => <When at={j.created_at} /> },89 { id: "started", header: t("jobs.col.started"), sortValue: (j) => j.started_at, cell: (j) => (j.started_at ? <When at={j.started_at} /> : <span className="faint">{t("jobs.notYet")}</span>), hide: "md" },90 { id: "finished", header: t("jobs.col.finished"), sortValue: (j) => j.finished_at, cell: (j) => (j.finished_at ? <When at={j.finished_at} /> : <span className="faint">{t("jobs.notYet")}</span>), hide: "md" },91 ];92 return (93 <>94 <div className="row-between">95 <div className="toolbar" role="search" aria-label={t("jobs.filters")}>96 <SelectField label={t("common.state")} value={state ?? ""} onChange={(v) => url.set({ state: v })} options={[{ value: "", label: t("common.all") }, ...STATES.map((s) => ({ value: s, label: t(`states.job.${s}`) }))]} />97 <CommitField label={t("jobs.template")} value={url.get("template")} onCommit={(v) => url.set({ template: v })} mono />98 <div className="svc-node-filter"><Combobox label={t("common.node")} options={nodes.options} value={url.get("node") || null} onChange={(v) => url.set({ node: v })} placeholder={t("common.all")} /></div>99 {filtered ? <Button variant="ghost" icon="close" onClick={() => url.clear(["state", "template", "node"])}>{t("common.reset")}</Button> : null}100 </div>101 <DataStamp at={list.ready ? list.updatedAt : undefined} />102 </div>103 {list.error && !list.ready ? <ErrorState error={list.error} onRetry={list.refetch} /> : !list.ready ? <SkeletonRows /> : (104 <>105 {list.error ? <ErrorState error={list.error} onRetry={list.refetch} compact /> : null}106 <DataTable caption={t("jobs.tab.jobs")} columns={columns} rows={list.items} rowKey={(j) => j.id} initialSort={{ id: "created", dir: "desc" }}107 empty={<EmptyState compact icon="jobs" title={filtered ? t("jobs.empty.filteredTitle") : t("jobs.empty.title")} actions={can("jobs.submit") && !filtered ? <Button icon="play" onClick={onSubmit}>{t("jobs.submit.open")}</Button> : undefined}>{filtered ? t("jobs.empty.filteredBody") : t("jobs.empty.body")}</EmptyState>} />108 <LoadMore hasMore={list.hasMore} loading={list.loadingMore} onMore={list.loadMore} />109 </>110 )}111 </>112 );113}114115function SchedulesTab() {116 const { t, fmt } = useI18n();117 const { can } = useSession();118 const qc = useQueryClient();119 const toast = useToast();120 const explain = useErrorMessage();121 const list = useApiList("/job-schedules", { query: { limit: 100 } });122 const [dialog, setDialog] = useState<{ kind: "create" } | { kind: "edit"; schedule: Schedule } | { kind: "delete"; schedule: Schedule } | null>(null);123 const [busy, setBusy] = useState<string | null>(null);124 const writable = can("jobs.submit");125126 const mutate = async (id: string, fn: () => Promise<unknown>, done: string) => {127 setBusy(id);128 try {129 await fn();130 await invalidatePaths(qc, "/job-schedules");131 toast({ tone: "ok", title: done });132 setDialog(null);133 } catch (e) {134 toast({ tone: "critical", ...explain(e) });135 } finally {136 setBusy(null);137 }138 };139140 const columns: Column<Schedule>[] = [141 { id: "name", header: t("common.name"), sortValue: (s) => s.name, cell: (s) => <strong>{s.name}</strong> },142 { id: "template", header: t("jobs.template"), sortValue: (s) => s.template, mono: true, cell: (s) => s.template },143 { id: "every", header: t("jobs.schedule.every"), sortValue: (s) => s.every_seconds, cell: (s) => t("jobs.schedule.everyValue", { interval: fmt.duration(s.every_seconds) }) },144 { id: "enabled", header: t("common.state"), sortValue: (s) => (s.enabled ? 1 : 0), cell: (s) => (s.enabled ? <StateDot tone="ok" label={t("jobs.schedule.on")} /> : <StateDot tone="offline" label={t("jobs.schedule.off")} />) },145 { id: "next", header: t("jobs.schedule.next"), sortValue: (s) => s.next_run_at, cell: (s) => (s.enabled ? <When at={s.next_run_at} /> : <span className="faint">{t("jobs.schedule.paused")}</span>), hide: "sm" },146 { id: "last", header: t("jobs.schedule.last"), sortValue: (s) => s.last_run_at, cell: (s) => (s.last_run_at ? <When at={s.last_run_at} /> : <span className="faint">{t("common.never")}</span>), hide: "md" },147 { id: "runs", header: t("jobs.schedule.runs"), cell: (s) => <Link href={`/jobs?template=${encodeURIComponent(s.template)}`}>{t("jobs.schedule.viewRuns")}</Link>, hide: "md" },148 ...(writable ? [{149 id: "actions", header: t("common.actions"), srOnlyHeader: true, shrink: true,150 cell: (s: Schedule) => (151 <span className="row gap-2">152 <Button size="sm" loading={busy === s.id} onClick={() => void mutate(s.id, () => apiPatch("/job-schedules/{id}", { path: { id: s.id }, body: { enabled: !s.enabled } }), s.enabled ? t("jobs.schedule.disabled") : t("jobs.schedule.enabledDone"))}>{s.enabled ? t("jobs.schedule.disable") : t("jobs.schedule.enable")}</Button>153 <IconButton size="sm" icon="edit" label={t("jobs.schedule.editLabel", { name: s.name })} onClick={() => setDialog({ kind: "edit", schedule: s })} />154 <IconButton size="sm" icon="trash" label={t("jobs.schedule.deleteLabel", { name: s.name })} onClick={() => setDialog({ kind: "delete", schedule: s })} />155 </span>156 ),157 } satisfies Column<Schedule>] : []),158 ];159160 return (161 <>162 <div className="row-between">163 <p className="muted">{t("jobs.schedule.intro")}</p>164 <div className="row-wrap">165 <DataStamp at={list.ready ? list.updatedAt : undefined} />166 {writable ? <Button icon="plus" onClick={() => setDialog({ kind: "create" })} data-testid="schedule-create">{t("jobs.schedule.create")}</Button> : <Tooltip focusable content={t("errors.forbidden.bodyPermission", { permission: "jobs.submit" })}><Button icon="plus" disabled>{t("jobs.schedule.create")}</Button></Tooltip>}167 </div>168 </div>169 {list.error && !list.ready ? <ErrorState error={list.error} onRetry={list.refetch} /> : !list.ready ? <SkeletonRows rows={4} /> : (170 <>171 <DataTable caption={t("jobs.tab.schedules")} columns={columns} rows={list.items} rowKey={(s) => s.id} initialSort={{ id: "name", dir: "asc" }}172 empty={<EmptyState compact icon="clock" title={t("jobs.schedule.emptyTitle")}>{t("jobs.schedule.emptyBody")}</EmptyState>} />173 <LoadMore hasMore={list.hasMore} loading={list.loadingMore} onMore={list.loadMore} />174 </>175 )}176 {dialog?.kind === "create" ? <ScheduleDialog onClose={() => setDialog(null)} /> : null}177 {dialog?.kind === "edit" ? <ScheduleDialog key={dialog.schedule.id} schedule={dialog.schedule} onClose={() => setDialog(null)} /> : null}178 <ConfirmDialog open={dialog?.kind === "delete"} danger busy={busy !== null} onClose={() => setDialog(null)} title={t("jobs.schedule.deleteTitle")} confirmLabel={t("common.delete")}179 body={dialog?.kind === "delete" ? t("jobs.schedule.deleteBody", { name: dialog.schedule.name }) : undefined}180 onConfirm={() => { if (dialog?.kind === "delete") { const s = dialog.schedule; void mutate(s.id, () => apiDelete("/job-schedules/{id}", { path: { id: s.id } }), t("common.deleted")); } }} />181 </>182 );183}184185function TemplatesTab({ onUse }: { onUse: (name: string) => void }) {186 const { t, fmt } = useI18n();187 const { can } = useSession();188 const q = useApiQuery("/job-templates");189 type T = Schemas["JobTemplate"];190 const columns: Column<T>[] = [191 { id: "title", header: t("common.name"), sortValue: (x) => x.title, cell: (x) => <span className="stack-sm"><strong>{x.title}</strong><span className="mono faint">{x.name}</span></span> },192 { id: "desc", header: t("common.description"), cell: (x) => <span className="muted">{x.description}</span>, hide: "sm" },193 { id: "avail", header: t("jobs.tpl.availability"), sortValue: (x) => (x.available ? 1 : 0), cell: (x) => (x.available ? <Badge tone="ok">{t("jobs.tpl.available")}</Badge> : <Badge tone="offline">{t("jobs.templateUnavailable")}</Badge>) },194 { id: "nodes", header: t("jobs.tpl.nodes"), cell: (x) => <Observed value={x.node_ids}>{(v) => t("jobs.tpl.nodeCount", { count: v.length })}</Observed>, hide: "md" },195 { id: "timeout", header: t("jobs.tpl.timeout"), align: "right", sortValue: (x) => x.timeout_s, cell: (x) => fmt.duration(x.timeout_s), hide: "md" },196 { id: "attempts", header: t("jobs.maxAttempts"), align: "right", sortValue: (x) => x.max_attempts, cell: (x) => x.max_attempts, hide: "md" },197 ...(can("jobs.submit") ? [{ id: "use", header: t("common.actions"), srOnlyHeader: true, shrink: true, cell: (x: T) => <Button size="sm" icon="play" disabled={!x.available} onClick={() => onUse(x.name)}>{t("jobs.tpl.use")}</Button> } satisfies Column<T>] : []),198 ];199 return (200 <QueryBoundary query={q} skeleton={<SkeletonRows rows={4} />}>201 {(d) => (202 <>203 <div className="row-between"><p className="muted">{t("jobs.tpl.intro")}</p><DataStamp at={q.dataUpdatedAt} /></div>204 <DataTable caption={t("jobs.tab.templates")} columns={columns} rows={d.items} rowKey={(x) => x.name} initialSort={{ id: "title", dir: "asc" }} empty={<EmptyState compact icon="jobs" title={t("jobs.tpl.emptyTitle")}>{t("jobs.tpl.emptyBody")}</EmptyState>} />205 </>206 )}207 </QueryBoundary>208 );209}210211function Inner() {212 const { t } = useI18n();213 const { can } = useSession();214 const router = useRouter();215 const url = useUrlState();216 const tab: Tab = TABS.find((x) => x === url.get("tab")) ?? "jobs";217 const [submit, setSubmit] = useState<{ template?: string } | null>(null);218 return (219 <Page title={t("jobs.title")} sub={t("jobs.sub")}220 actions={can("jobs.submit") ? <Button variant="primary" icon="play" onClick={() => setSubmit({})} data-testid="job-submit-open">{t("jobs.submit.open")}</Button> : <Tooltip focusable placement="end" content={t("errors.forbidden.bodyPermission", { permission: "jobs.submit" })}><Button icon="play" disabled>{t("jobs.submit.open")}</Button></Tooltip>}>221 <div data-testid="screen-jobs" className="stack-lg">222 <Tabs label={t("jobs.title")} idPrefix="jobs" value={tab} onChange={(v) => url.set({ tab: v === "jobs" ? null : v })} tabs={TABS.map((id) => ({ id, label: t(`jobs.tab.${id}`) }))} />223 <TabPanel idPrefix="jobs" id={tab}>224 {tab === "jobs" ? <JobsTab onSubmit={() => setSubmit({})} /> : tab === "schedules" ? <SchedulesTab /> : <TemplatesTab onUse={(name) => setSubmit({ template: name })} />}225 </TabPanel>226 {submit ? <SubmitJobDialog {...(submit.template ? { initialTemplate: submit.template } : {})} onClose={() => setSubmit(null)} onCreated={(job) => { setSubmit(null); router.push(`/jobs/${job.id}`); }} /> : null}227 </div>228 </Page>229 );230}231232export function JobsScreen() {233 return (234 <RequirePermission permission="jobs.read">235 <Suspense fallback={null}><Inner /></Suspense>236 </RequirePermission>237 );238}239