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 ;
}
};
const SectionLabel = ({ children }: { children: ReactNode }) => (
{children}
);
// ── 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([]);
const [search, setSearch] = useState('');
const [isLoading, setIsLoading] = useState(true);
const load = useCallback(
() => client.get('/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 (
{cancellable && (
)}
);
};
return (
{isLoading ? (
Loading…
) : (
{/* Active (running + queued) — top 70% */}
Running & Queued{active.length ? ` · ${active.length}` : ''}
{active.length === 0 ? (
Nothing running
) : (
active.map(renderRow)
)}
{/* History — bottom 30% */}
History
{history.length === 0 ? (
{search ? 'No matches' : 'No finished jobs'}
) : (
history.map(renderRow)
)}
)}
);
};
// ── 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 ;
};
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(JOBS_LAYOUT);
return (
);
};