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, Square, Trash2, } from 'lucide-react'; import { WorkspaceLayout } from 'officerdev'; import type { LayoutNode, PanelComponents } from 'officerdev'; import { useClient } from 'hooks/useClient'; import { useDashboardState } from 'state/useDashboardState'; import { Card } from '@/components/Card'; import { ScriptJobDetail } from './ScriptJobDetail'; import { DownloadJobDetail } from './DownloadJobDetail'; import { PipelineJobDetail } from './JobDetail'; type JobSummary = { id: string; mode: string; taskDirName: string; taskName: string; status: 'pending' | 'running' | 'completed' | 'failed' | 'stopped' | 'interrupted'; exitCode: number | null; target: string | null; totalCost: { inputTokens: number; outputTokens: number; totalUSD: number } | null; createdAt: string; error: string | null; }; const basename = (p: string | null) => (p ? p.replace(/\/+$/, '').split('/').pop() || p : 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]); // Running → stop; queued/finished → delete the row. Then refresh. const act = useCallback( (ev: MouseEvent, job: JobSummary) => { ev.stopPropagation(); const req = job.status === 'running' ? client.post(`/jobs/${job.id}/stop`, {}) : client.delete(`/jobs/${job.id}`); req.then(() => load()).catch(() => {}); }, [client, load], ); const clearHistory = useCallback(() => { client .delete('/jobs/history') .then(() => load()) .catch(() => {}); }, [client, load]); return { jobs, isLoading, act, clearHistory }; }; type JobRowProps = { job: JobSummary; onAction: (ev: MouseEvent, job: JobSummary) => void }; const JobRow = ({ job, onAction }: JobRowProps) => { const navigate = useNavigate(); const { id: activeId } = useParams<{ id: string }>(); const isRunning = job.status === 'running'; const target = basename(job.target); return (
); }; 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, act } = 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, act, clearHistory } = 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" />
{history.length > 0 && ( )}
{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 + download progress get a card here. if (mode === 'script') { return (
); } if (mode === 'download') { 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, }; // Guard the persisted layout against a stale shape (e.g. panel ids changed in a later build): the panels // render from PANEL_COMPONENTS by id, so a layout whose panel ids don't match ours would render blanks. // If it doesn't line up exactly, fall back to the default rather than trust the saved node. const collectPanelIds = (node: LayoutNode, acc: Set): Set => { if (node.type === 'panel') acc.add(node.id); else for (const child of node.children) collectPanelIds(child.node, acc); return acc; }; const matchesPanelSet = (node: LayoutNode): boolean => { const ids = collectPanelIds(node, new Set()); const expected = Object.keys(PANEL_COMPONENTS); return ids.size === expected.length && expected.every((id) => ids.has(id)); }; // One page for /jobs and /jobs/:id — master (list) + detail, resizable like /chat. The layout is // persisted per-user via useDashboardState (screens/ namespace), so pane sizes survive reloads. export const JobsPage = () => { const { value, setValue } = useDashboardState('screens/jobs', JOBS_LAYOUT); const layout = matchesPanelSet(value) ? value : JOBS_LAYOUT; return (
); };