SPB Git

Repository Public

JobDetail.tsx 10.3 KB 177 lines tsx

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/JobDetail.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 { useQueryClient } from "@tanstack/react-query";45import { useState } from "react";46import { apiPost, type Schemas } from "@/api/client";47import { invalidatePaths, useApiQuery } from "@/api/query";48import { When } from "@/features/services/url";49import { useActionOutput } from "@/features/services/useActionOutput";50import { NodeLink } from "@/features/shared/nodes";51import { useI18n } from "@/i18n";52import { Page, RequirePermission } from "@/shell/AppShell";53import { useEvent } from "@/shell/realtime";54import { useSession } from "@/shell/session";55import { Banner, Button, ConfirmDialog, DataStamp, EmptyState, ErrorState, KeyValue, LogView, QueryBoundary, StateDot, Tag, jobTone, useErrorMessage, useToast } from "@/ui";56import { JobProgress, jobIcon } from "./JobsScreen";5758type Job = Schemas["Job"];59const DONE: readonly Schemas["JobState"][] = ["succeeded", "failed", "cancelled", "timed_out"];6061export function JobDetail({ id }: { id: string }) {62  const { t } = useI18n();63  const qc = useQueryClient();64  const q = useApiQuery("/jobs/{id}", { path: { id } }, { refetchInterval: (query) => (query.state.data && DONE.includes(query.state.data.state) ? false : 5000) });65  useEvent("job.changed", (e) => {66    if (e.job_id === id) void invalidatePaths(qc, "/jobs");67  });68  return (69    <RequirePermission permission="jobs.read">70      <Page title={q.data ? q.data.template : t("jobs.detail.title")} sub={<span className="mono">{id}</span>} actions={<DataStamp at={q.data ? q.dataUpdatedAt : undefined} />}>71        <div data-testid="screen-job-detail" className="stack-lg">72          <QueryBoundary query={q}>{(job) => <Body job={job} />}</QueryBoundary>73        </div>74      </Page>75    </RequirePermission>76  );77}7879function Json({ value, label }: { value: Record<string, unknown> | undefined; label: string }) {80  const { t } = useI18n();81  if (!value || Object.keys(value).length === 0) return <span className="faint">{t("jobs.detail.none")}</span>;82  return <pre className="mcc-log job-json" tabIndex={0} aria-label={label}>{JSON.stringify(value, null, 2)}</pre>;83}8485function Body({ job }: { job: Job }) {86  const { t, fmt } = useI18n();87  const { can } = useSession();88  const qc = useQueryClient();89  const toast = useToast();90  const explain = useErrorMessage();91  const [confirm, setConfirm] = useState(false);92  const [busy, setBusy] = useState(false);93  const live = !DONE.includes(job.state);94  const placement = [job.placement.site ? `${t("jobs.placement.site")}: ${job.placement.site}` : null, job.placement.role ? `${t("jobs.placement.role")}: ${job.placement.role}` : null].filter(Boolean);9596  const cancel = async () => {97    setBusy(true);98    try {99      await apiPost("/jobs/{id}/cancel", { path: { id: job.id } });100      await invalidatePaths(qc, "/jobs");101      toast({ tone: "ok", title: t("jobs.detail.cancelSent") });102      setConfirm(false);103    } catch (e) {104      toast({ tone: "critical", ...explain(e) });105    } finally {106      setBusy(false);107    }108  };109110  return (111    <>112      <div className="row-between">113        <div className="row-wrap" role="status" aria-live="polite" data-testid="job-state" data-state={job.state}>114          <StateDot tone={jobTone(job.state)} icon={jobIcon(job.state)} label={t(`states.job.${job.state}`)} />115          <span className="muted num">{t("jobs.detail.attempt", { attempt: job.attempt, max: job.max_attempts })}</span>116          {job.next_attempt_at ? <span className="muted">{t("jobs.detail.nextAttempt")} <When at={job.next_attempt_at} /></span> : null}117        </div>118        {live && can("jobs.submit") ? <Button icon="stop" onClick={() => setConfirm(true)} data-testid="job-cancel">{t("jobs.detail.cancel")}</Button> : null}119      </div>120      {job.error ? <Banner tone="critical" role="alert"><span className="pre">{job.error}</span></Banner> : null}121122      <section className="section" aria-labelledby="job-progress-h">123        <h2 id="job-progress-h">{t("jobs.col.progress")}</h2>124        <div className="job-progress wide"><JobProgress job={job} /></div>125        {job.progress === undefined ? <p className="mcc-hint">{t("jobs.progressNoneHint")}</p> : null}126      </section>127128      <div className="cols-2">129        <section className="section" aria-labelledby="job-run-h">130          <h2 id="job-run-h">{t("jobs.detail.execution")}</h2>131          <KeyValue items={[132            { label: t("jobs.template"), value: <span className="mono">{job.template}</span> },133            { label: t("common.node"), value: job.node_id ? <NodeLink id={job.node_id} alias={job.node_alias} /> : <span className="faint">{t("jobs.notPlaced")}</span> },134            { label: t("jobs.col.owner"), value: job.owner_display_name ?? <span className="faint">{job.schedule_id ? t("jobs.ownerSchedule") : t("common.unknown")}</span> },135            { label: t("common.created"), value: <span className="num">{fmt.dateTime(job.created_at, { seconds: true })}</span> },136            { label: t("jobs.col.started"), value: job.started_at ? <span className="num">{fmt.dateTime(job.started_at, { seconds: true })}</span> : <span className="faint">{t("jobs.notYet")}</span> },137            { label: t("jobs.col.finished"), value: job.finished_at ? <span className="num">{fmt.dateTime(job.finished_at, { seconds: true })}</span> : <span className="faint">{t("jobs.notYet")}</span> },138            ...(job.started_at && job.finished_at ? [{ label: t("jobs.detail.duration"), value: fmt.duration((Date.parse(job.finished_at) - Date.parse(job.started_at)) / 1000) }] : []),139            { label: t("jobs.placement.title"), value: job.placement.node_id || placement.length > 0 || job.placement.tags?.length ? (140              <span className="row-wrap">{job.placement.node_id ? <NodeLink id={job.placement.node_id} alias={job.placement.node_id === job.node_id ? job.node_alias : undefined} /> : null}{placement.map((p) => <span key={p}>{p}</span>)}{job.placement.tags?.map((x) => <Tag key={x}>{x}</Tag>)}</span>141            ) : <span className="faint">{t("jobs.placement.anyNode")}</span> },142            { label: t("jobs.dependsOn"), value: job.depends_on.length > 0 ? <ul className="stack-sm">{job.depends_on.map((d) => <li key={d}><Link href={`/jobs/${d}`} className="mono">{d}</Link></li>)}</ul> : <span className="faint">{t("jobs.detail.none")}</span> },143            ...(job.schedule_id ? [{ label: t("jobs.detail.schedule"), value: <Link href="/jobs?tab=schedules" className="mono">{job.schedule_id}</Link> }] : []),144            ...(job.action_id ? [{ label: t("jobs.detail.action"), value: <Link href={`/actions/${job.action_id}`} className="mono">{job.action_id}</Link> }] : []),145          ]} />146        </section>147        <section className="section" aria-labelledby="job-data-h">148          <h2 id="job-data-h">{t("jobs.detail.data")}</h2>149          <div className="stack-sm"><h3>{t("jobs.params")}</h3><Json value={job.params} label={t("jobs.params")} /></div>150          <div className="stack-sm"><h3>{t("jobs.detail.result")}</h3>{job.result ? <Json value={job.result} label={t("jobs.detail.result")} /> : <span className="faint">{live ? t("jobs.notYet") : t("jobs.detail.noResult")}</span>}</div>151          <div className="stack-sm"><h3>{t("jobs.detail.usage")}</h3>{job.usage ? <Json value={job.usage} label={t("jobs.detail.usage")} /> : <span className="mcc-unmeasured">{t("jobs.detail.usageNone")}</span>}</div>152        </section>153      </div>154155      <section className="section" aria-labelledby="job-out-h" data-testid="job-output">156        <div className="section-head"><h2 id="job-out-h">{t("jobs.detail.output")}</h2>{job.action_id ? <Link href={`/actions/${job.action_id}`}>{t("jobs.detail.openAction")}</Link> : null}</div>157        {job.action_id ? <Output key={job.action_id} actionId={job.action_id} live={live} /> : <EmptyState compact icon="terminal" title={t("jobs.detail.noActionTitle")}>{t("jobs.detail.noActionBody")}</EmptyState>}158      </section>159160      <ConfirmDialog open={confirm} danger busy={busy} onClose={() => setConfirm(false)} onConfirm={() => void cancel()} title={t("jobs.detail.cancelTitle")} body={t("jobs.detail.cancelBody")} confirmLabel={t("jobs.detail.cancel")} />161    </>162  );163}164165function Output({ actionId, live }: { actionId: string; live: boolean }) {166  const { t } = useI18n();167  const { can } = useSession();168  const out = useActionOutput(actionId, live && can("actions.read"));169  if (!can("actions.read")) return <Banner tone="offline" icon="denied">{t("errors.forbidden.bodyPermission", { permission: "actions.read" })}</Banner>;170  return (171    <>172      {out.error && out.lines.length === 0 ? <ErrorState error={out.error} compact /> : null}173      <LogView lines={out.lines} label={t("jobs.detail.output")} truncated={out.truncated} empty={<EmptyState compact icon="terminal" title={live ? t("jobs.detail.noOutputYet") : t("jobs.detail.noOutput")} />} />174    </>175  );176}177
Files main
Menu

Theme