Files
platform/src/apps/officer-web/Screens/Dashboard/Jobs/JobsPage.tsx
T

234 lines
9.4 KiB
TypeScript

import { useState, useEffect, useCallback, type ReactNode, type MouseEvent } from 'react';
import { useParams, useNavigate } from 'react-router';
import { Search, CheckCircle2, AlertCircle, Clock, Loader2, StopCircle, AlertTriangle, Inbox, X } from 'lucide-react';
import { WorkspaceLayout } from 'officerdev';
import type { LayoutNode, PanelComponents } from 'officerdev';
import { useClient } from 'hooks/useClient';
import { Card } from '@/components/Card';
import { ScriptJobDetail } from './ScriptJobDetail';
import { PipelineJobDetail } from './JobDetail';
type JobSummary = {
id: string;
mode: string;
taskDirName: string;
taskName: string;
status: 'pending' | 'running' | 'completed' | 'failed' | 'stopped' | 'interrupted';
exitCode: number | null;
totalCost: { inputTokens: number; outputTokens: number; totalUSD: number } | null;
createdAt: string;
error: string | null;
};
const formatDate = (iso: string) =>
new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
const StatusIcon = ({ status }: { status: JobSummary['status'] }) => {
switch (status) {
case 'completed': return <CheckCircle2 className="h-4 w-4 text-green-500 shrink-0" />;
case 'failed': return <AlertCircle className="h-4 w-4 text-red-500 shrink-0" />;
case 'running': return <Loader2 className="h-4 w-4 text-blue-500 shrink-0 animate-spin" />;
case 'stopped': return <StopCircle className="h-4 w-4 text-amber-500 shrink-0" />;
case 'interrupted': return <AlertTriangle className="h-4 w-4 text-amber-500 shrink-0" />;
case 'pending': return <Clock className="h-4 w-4 text-duck-dark/40 shrink-0" />;
}
};
const SectionLabel = ({ children }: { children: ReactNode }) => (
<div className="px-3 py-1.5 text-[10px] font-semibold uppercase tracking-wide text-duck-dark/40 bg-duck-dark/[0.03] border-b border-duck-dark/10 shrink-0">
{children}
</div>
);
// ── Left panel: the jobs list (polls so running/queued statuses stay fresh) ──
const JobsListPanel = () => {
const client = useClient();
const navigate = useNavigate();
const { id: activeId } = useParams<{ id: string }>();
const [jobs, setJobs] = useState<JobSummary[]>([]);
const [search, setSearch] = useState('');
const [isLoading, setIsLoading] = useState(true);
const load = useCallback(
() => client.get<JobSummary[]>('/jobs').then((data) => { setJobs(data); setIsLoading(false); }).catch(() => setIsLoading(false)),
[client],
);
useEffect(() => {
load();
const timer = setInterval(load, 2500);
return () => clearInterval(timer);
}, [load]);
// Stop a running job / remove a queued one, then refresh immediately.
const cancel = (ev: MouseEvent, id: string) => {
ev.stopPropagation();
client.post(`/jobs/${id}/stop`, {}).then(() => load()).catch(() => {});
};
const filtered = search
? jobs.filter((j) => {
const q = search.toLowerCase();
return j.taskName.toLowerCase().includes(q) || j.taskDirName.toLowerCase().includes(q) || j.status.includes(q);
})
: jobs;
// Active = running first, then the FIFO queue (oldest pending on top — next to run). History = the
// rest (already newest-first from the API).
const active = [
...filtered.filter((j) => j.status === 'running'),
...filtered.filter((j) => j.status === 'pending').sort((a, b) => +new Date(a.createdAt) - +new Date(b.createdAt)),
];
const history = filtered.filter((j) => j.status !== 'running' && j.status !== 'pending');
const renderRow = (job: JobSummary) => {
const cancellable = job.status === 'running' || job.status === 'pending';
return (
<div
key={job.id}
className={`group w-full border-b border-duck-dark/5 flex items-center transition-colors ${
job.id === activeId ? 'bg-duck-teal/10' : 'hover:bg-duck-dark/5'
}`}
>
<button onClick={() => navigate(`/jobs/${job.id}`)} className="flex-1 min-w-0 text-left px-4 py-2.5 flex items-center gap-3 cursor-pointer">
<StatusIcon status={job.status} />
<div className="flex-1 min-w-0">
<span className="text-sm font-medium text-duck-dark truncate block">{job.taskName}</span>
<div className="flex items-center gap-2 mt-0.5">
<span className="text-xs text-duck-dark/50">{formatDate(job.createdAt)}</span>
{job.error && <span className="text-xs text-red-500 truncate max-w-[180px]">{job.error}</span>}
</div>
</div>
</button>
{cancellable && (
<button
onClick={(ev) => cancel(ev, job.id)}
title={job.status === 'pending' ? 'Remove from queue' : 'Stop'}
className="shrink-0 mr-2 p-1.5 rounded-md text-duck-dark/40 hover:text-red-500 hover:bg-red-500/10 md:opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
>
<X className="h-4 w-4" />
</button>
)}
</div>
);
};
return (
<div className="h-full p-2">
<Card className="h-full flex flex-col overflow-hidden">
<div className="p-3 border-b border-duck-dark/10 flex items-center gap-3 shrink-0">
<h2 className="text-sm font-semibold text-duck-dark shrink-0">Jobs</h2>
<div className="relative flex-1">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-duck-dark/40" />
<input
type="text"
placeholder="Search…"
value={search}
onChange={(ev) => setSearch(ev.target.value)}
className="w-full pl-8 pr-3 py-1.5 text-sm rounded-md border border-duck-dark/15 bg-background/60 text-duck-dark placeholder:text-duck-dark/30 focus:outline-none focus:ring-1 focus:ring-duck-teal/40"
/>
</div>
</div>
{isLoading ? (
<div className="flex-1 flex items-center justify-center text-duck-dark/30 text-sm">Loading</div>
) : (
<div className="flex-1 min-h-0 flex flex-col">
{/* Active (running + queued) — top 70% */}
<div className="flex-[7] min-h-0 flex flex-col border-b border-duck-dark/10">
<SectionLabel>Running &amp; Queued{active.length ? ` · ${active.length}` : ''}</SectionLabel>
<div className="flex-1 overflow-y-auto">
{active.length === 0 ? (
<div className="flex items-center justify-center h-full min-h-16 text-duck-dark/30 text-xs">Nothing running</div>
) : (
active.map(renderRow)
)}
</div>
</div>
{/* History — bottom 30% */}
<div className="flex-[3] min-h-0 flex flex-col">
<SectionLabel>History</SectionLabel>
<div className="flex-1 overflow-y-auto">
{history.length === 0 ? (
<div className="flex items-center justify-center h-full min-h-16 text-duck-dark/30 text-xs">{search ? 'No matches' : 'No finished jobs'}</div>
) : (
history.map(renderRow)
)}
</div>
</div>
</div>
)}
</Card>
</div>
);
};
// ── Right panel: the selected job's detail, by mode (script terminal / pipeline steps) ──
const JobDetailPanel = () => {
const { id } = useParams<{ id: string }>();
const client = useClient();
const [mode, setMode] = useState<string | null>(null);
useEffect(() => {
if (!id) { setMode(null); return; }
setMode(null);
client.get<{ mode?: string }>(`/jobs/${id}`).then((j) => setMode(j.mode ?? 'pipeline')).catch(() => setMode('notfound'));
}, [id]);
if (!id) {
return (
<div className="h-full p-2">
<Card className="h-full flex flex-col items-center justify-center gap-2 text-duck-dark/30">
<Inbox className="h-8 w-8" />
<span className="text-sm">Select a job</span>
</Card>
</div>
);
}
if (mode === null) {
return (
<div className="h-full p-2">
<Card className="h-full flex items-center justify-center text-duck-dark/40"><Loader2 className="h-5 w-5 animate-spin" /></Card>
</div>
);
}
if (mode === 'notfound') {
return (
<div className="h-full p-2">
<Card className="h-full flex items-center justify-center text-duck-dark/50 text-sm">Job not found.</Card>
</div>
);
}
// Pipeline detail brings its own full chrome; the script terminal gets a card background here.
if (mode === 'script') {
return (
<div className="h-full p-2">
<Card className="h-full flex flex-col overflow-hidden"><ScriptJobDetail key={id} /></Card>
</div>
);
}
return <PipelineJobDetail key={id} />;
};
const JOBS_LAYOUT: LayoutNode = {
type: 'group',
id: 'jobs-root',
direction: 'horizontal',
children: [
{ node: { type: 'panel', id: 'jobs-list', appType: null }, size: 32 },
{ node: { type: 'panel', id: 'job-detail', appType: null }, size: 68 },
],
};
const PANEL_COMPONENTS: PanelComponents = { 'jobs-list': JobsListPanel, 'job-detail': JobDetailPanel };
// One page for /jobs and /jobs/:id — master (list) + detail, resizable like /chat.
export const JobsPage = () => {
const [layout, setLayout] = useState<LayoutNode>(JOBS_LAYOUT);
return (
<div className="h-full w-full">
<WorkspaceLayout layout={layout} onLayoutChange={setLayout} components={PANEL_COMPONENTS} noHeader />
</div>
);
};