"use client"; import { useCallback, useEffect, useMemo, useState } from "react"; import { Activity, Copy, RefreshCw, Square, } from "lucide-react"; import { Shell } from "@/components/Shell"; import { useToast } from "@/components/Toast"; import { fetchJson, fmtTs } from "@/lib/api"; import { kindLabel, nonFollowersFromJob, STATUS_ZH, summarizeJob, jobMatchesAccount, type XJob, } from "@/lib/xOps"; import { CleanupPanel, EngagePanel, MonitorPanel, ScrapePanel, WorkbenchPanel, } from "./XOpsPanels"; import { ClipsPanel } from "./ClipsPanel"; type TabId = "workbench" | "clips" | "cleanup" | "scrape" | "engage" | "monitor" | "jobs"; type X2Agent = { id: string; label?: string; online?: boolean; extension_connected?: boolean; last_seen_at?: number; }; type X2Account = { id: string; username?: string; display_name?: string; avatar_url?: string; last_seen_at?: string; }; const NAV: { id: TabId; emoji: string; label: string }[] = [ { id: "workbench", emoji: "🏠", label: "工作台" }, { id: "clips", emoji: "🎬", label: "切片发帖" }, { id: "cleanup", emoji: "🧹", label: "清理" }, { id: "scrape", emoji: "📥", label: "采集" }, { id: "engage", emoji: "⚡", label: "互动" }, { id: "monitor", emoji: "📡", label: "监控" }, { id: "jobs", emoji: "📋", label: "任务" }, ]; export default function XPage() { const toast = useToast(); const [tab, setTab] = useState("workbench"); const [loading, setLoading] = useState(true); const [agents, setAgents] = useState([]); const [accounts, setAccounts] = useState([]); const [jobs, setJobs] = useState([]); const [stats, setStats] = useState>({}); const [extOnline, setExtOnline] = useState(false); const [username, setUsername] = useState(""); // Persist selected account across reloads ("" = 全部账号) useEffect(() => { try { const saved = window.localStorage.getItem("x2_selected_account"); if (saved !== null) setUsername(saved); } catch { /* ignore */ } }, []); useEffect(() => { try { window.localStorage.setItem("x2_selected_account", username); } catch { /* ignore */ } }, [username]); const [limit, setLimit] = useState(80); const [minD, setMinD] = useState(2000); const [maxD, setMaxD] = useState(5000); const [likeN, setLikeN] = useState(10); const [followN, setFollowN] = useState(5); const [cleanupList, setCleanupList] = useState(""); const [selectedId, setSelectedId] = useState(null); const [feedFilter, setFeedFilter] = useState<"all" | "active" | "completed" | "failed">("all"); const [lastJob, setLastJob] = useState<{ kind: string; params: Record } | null>(null); const load = useCallback(async () => { try { const st = await fetchJson("/api/x2/status"); setAgents(st?.agents || []); setAccounts(st?.accounts || []); const nextJobs: XJob[] = (st?.jobs || []).map((j: XJob & { result?: unknown }) => ({ ...j, result: j.result || undefined, })); setJobs(nextJobs); setStats(st?.stats || {}); setExtOnline(Boolean(st?.extension_online)); const accs: X2Account[] = st?.accounts || []; setUsername((cur) => { if (cur && accs.some((a) => String(a.username || "") === cur)) return cur; try { const saved = window.localStorage.getItem("x2_selected_account"); // Explicit empty string means「全部账号」 if (saved === "") return ""; if (saved && accs.some((a) => String(a.username || "") === saved)) return saved; } catch { /* ignore */ } // Default: 全部账号 — never hide history by auto-picking first account return cur || ""; }); } catch (e: unknown) { toast.push((e as Error)?.message || "加载失败", "err"); } finally { setLoading(false); } }, [toast]); useEffect(() => { void load(); const t = setInterval(() => void load(), 3500); return () => clearInterval(t); }, [load]); const createJob = useCallback( async (kind: string, params: Record = {}) => { if (!extOnline) { toast.push("插件未在线:请加载扩展并打开本页完成自动配对", "err"); } const handle = username.trim().replace(/^@/, ""); if (!handle && accounts.length > 0) { toast.push("请先在顶部选择要操作的账号", "err"); return; } const merged = { ...(handle ? { username: handle } : {}), export: "none", ...params, }; setLastJob({ kind, params: merged }); try { const r = await fetchJson("/api/x2/jobs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ kind, params: merged }), }); if (r?.job) { setJobs((prev) => [r.job, ...prev.filter((j) => j.id !== r.job.id)]); setSelectedId(r.job.id); toast.push(`🚀 ${kindLabel(kind)} 已下发`, "ok"); } else { toast.push("创建失败", "err"); } } catch (e: unknown) { toast.push((e as Error)?.message || "创建失败", "err"); } }, [extOnline, toast, username, accounts.length], ); const cancelJob = async (id: string) => { try { const r = await fetchJson(`/api/x2/jobs/${encodeURIComponent(id)}/cancel`, { method: "POST" }); if (r?.job) { setJobs((prev) => [r.job, ...prev.filter((j) => j.id !== r.job.id)]); toast.push("已请求取消", "ok"); } } catch (e: unknown) { toast.push((e as Error)?.message || "取消失败", "err"); } }; const accountJobs = useMemo( () => jobs.filter((j) => jobMatchesAccount(j, username)), [jobs, username], ); const selected = useMemo( () => accountJobs.find((j) => j.id === selectedId) || accountJobs[0] || null, [accountJobs, selectedId], ); const filteredJobs = useMemo(() => { return accountJobs.filter((j) => { const s = j.status || ""; if (feedFilter === "active") return s === "running" || s === "queued"; if (feedFilter === "completed") return s === "completed"; if (feedFilter === "failed") return s === "failed" || s === "cancelled"; return true; }); }, [accountJobs, feedFilter]); const accountStats = useMemo(() => { const out = { completed: 0, running: 0, queued: 0, failed: 0 }; for (const j of accountJobs) { const s = j.status || ""; if (s === "completed") out.completed += 1; else if (s === "running") out.running += 1; else if (s === "queued") out.queued += 1; else if (s === "failed" || s === "cancelled") out.failed += 1; } return out; }, [accountJobs]); const lastNonFollowers = useMemo(() => { for (const j of accountJobs) { const list = nonFollowersFromJob(j); if (list.length) return list; } return [] as string[]; }, [accountJobs]); const recentResults = useMemo( () => accountJobs .filter((j) => j.status === "completed" || j.status === "failed" || j.status === "cancelled") .slice(0, 5) .map((j) => ({ id: j.id, kind: kindLabel(j.kind), status: j.status, summary: summarizeJob(j), })), [accountJobs], ); const active = accountJobs.find((j) => j.status === "running" || j.status === "queued"); const pct = active ? Math.min( 100, Math.round( ((active.progress_current || 0) / Math.max(1, active.progress_total || 1)) * 100, ), ) : 0; const common = { createJob, toast: (msg: string, kind?: "ok" | "err") => toast.push(msg, kind || "ok"), username, setUsername, limit, setLimit, minD, setMinD, maxD, setMaxD, }; const crumb = NAV.find((n) => n.id === tab); return (
𝕏
X2 Ops

X 运营控制台

Web 下发 · 插件在浏览器执行 · 与 Electron / 插件 popup 同级能力

{extOnline ? "插件已连接" : "插件离线"}
{active ? (
{kindLabel(active.kind)}
{STATUS_ZH[active.status || ""] || active.status} · {active.progress_message || ""}
) : null}
{/* left nav */} {/* main */}
X Ops / {crumb?.label}

{crumb?.emoji} {crumb?.label}

{tab === "workbench" ? ( setTab(id as TabId)} lastKind={lastJob?.kind} likeN={likeN} recentResults={recentResults} rerun={() => { if (!lastJob) return toast.push("没有上次任务", "err"); void createJob(lastJob.kind, lastJob.params); }} /> ) : null} {tab === "clips" ? toast.push(m, k)} accountUsername={username} /> : null} {tab === "cleanup" ? ( ) : null} {tab === "scrape" ? : null} {tab === "engage" ? ( ) : null} {tab === "monitor" ? : null} {tab === "jobs" ? (
任务流与结果请看右侧面板。也可在清理页一键填入扫描名单。
) : null}
{/* right sidepane */}
); }