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 ; case 'failed': return ; case 'running': return ; case 'stopped': return ; case 'interrupted': return ; case 'pending': return ; } }; // Jobs data — each list panel polls independently (cheap for a single user). const useJobsData = () => { const client = useClient(); const [jobs, setJobs] = useState([]); const [isLoading, setIsLoading] = useState(true); const load = useCallback( () => client.get('/jobs').then((d) => { setJobs(d); setIsLoading(false); }).catch(() => setIsLoading(false)), [client], ); useEffect(() => { load(); const timer = setInterval(load, 2500); return () => clearInterval(timer); }, [load]); const cancel = useCallback( (ev: MouseEvent, id: string) => { ev.stopPropagation(); client.post(`/jobs/${id}/stop`, {}).then(() => load()).catch(() => {}); }, [client, load], ); return { jobs, isLoading, cancel }; }; type JobRowProps = { job: JobSummary; onCancel: (ev: MouseEvent, id: string) => void }; const JobRow = ({ job, onCancel }: JobRowProps) => { const navigate = useNavigate(); const { id: activeId } = useParams<{ id: string }>(); const cancellable = job.status === 'running' || job.status === 'pending'; return ( navigate(`/jobs/${job.id}`)} className="flex-1 min-w-0 text-left px-4 py-2.5 flex items-center gap-3 cursor-pointer"> {job.taskName} {formatDate(job.createdAt)} {job.error && {job.error}} {cancellable && ( onCancel(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" > )} ); }; const PanelHeader = ({ children }: { children: ReactNode }) => ( {children} ); // Top-left panel: running first, then the FIFO queue (oldest pending on top — next to run). const ActiveJobsPanel = () => { const { jobs, isLoading, cancel } = useJobsData(); const active = [ ...jobs.filter((j) => j.status === 'running'), ...jobs.filter((j) => j.status === 'pending').sort((a, b) => +new Date(a.createdAt) - +new Date(b.createdAt)), ]; return ( Running & Queued {active.length > 0 && {active.length}} {isLoading ? ( Loading… ) : active.length === 0 ? ( Nothing running ) : ( active.map((job) => ) )} ); }; // Bottom-left panel: finished / failed / stopped, newest first, searchable. const HistoryJobsPanel = () => { const { jobs, isLoading, cancel } = useJobsData(); const [search, setSearch] = useState(''); const history = jobs .filter((j) => j.status !== 'running' && j.status !== 'pending') .filter((j) => { if (!search) return true; const q = search.toLowerCase(); return j.taskName.toLowerCase().includes(q) || j.taskDirName.toLowerCase().includes(q) || j.status.includes(q); }); return ( History setSearch(ev.target.value)} className="w-full pl-8 pr-3 py-1 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" /> {isLoading ? ( Loading… ) : history.length === 0 ? ( {search ? 'No matches' : 'No finished jobs'} ) : ( history.map((job) => ) )} ); }; // ── 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(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 ( Select a job ); } if (mode === null) { return ( ); } if (mode === 'notfound') { return ( Job not found. ); } // Pipeline detail brings its own full chrome; the script terminal gets a card background here. if (mode === 'script') { return ( ); } return ; }; // Left column = two stacked panels (Active over History) with a resizable divider, like /email's // reader/chat split. Right column = the detail. const JOBS_LAYOUT: LayoutNode = { type: 'group', id: 'jobs-root', direction: 'horizontal', children: [ { node: { type: 'group', id: 'jobs-left', direction: 'vertical', children: [ { node: { type: 'panel', id: 'jobs-active', appType: null }, size: 68 }, { node: { type: 'panel', id: 'jobs-history', appType: null }, size: 32 }, ], }, size: 32, }, { node: { type: 'panel', id: 'job-detail', appType: null }, size: 68 }, ], }; const PANEL_COMPONENTS: PanelComponents = { 'jobs-active': ActiveJobsPanel, 'jobs-history': HistoryJobsPanel, 'job-detail': JobDetailPanel, }; // One page for /jobs and /jobs/:id — master (list) + detail, resizable like /chat. export const JobsPage = () => { const [layout, setLayout] = useState(JOBS_LAYOUT); return ( ); };