feat: 重做 Web /x 为完整 X2 Ops 控制台

三栏布局对齐 Electron;清理/采集/互动/监控能力对齐插件 popup。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-15 00:53:59 -05:00
parent 57690bd286
commit 9c63b2d0cc
3 changed files with 1393 additions and 483 deletions

View File

@ -0,0 +1,807 @@
"use client";
import {
Download,
Heart,
Radar,
UserMinus,
UserPlus,
} from "lucide-react";
import { useMemo, useState } from "react";
import {
buildAdvancedSearch,
estimateEta,
parseHandles,
} from "@/lib/xOps";
export type CreateJobFn = (kind: string, params?: Record<string, unknown>) => Promise<void>;
const panel =
"rounded-2xl border border-white/10 bg-gradient-to-b from-white/[0.07] to-black/30 p-4 shadow-[0_8px_32px_rgba(0,0,0,0.25)]";
const title = "text-sm font-semibold text-white";
const sub = "mt-0.5 text-[11px] text-slate-400";
const field = "mt-1 w-full rounded-xl border border-white/10 bg-black/45 px-3 py-2 text-sm text-slate-100 outline-none focus:border-orange-400/50";
const label = "block text-[11px] text-slate-400";
const btn =
"inline-flex items-center justify-center gap-1.5 rounded-xl px-3 py-2 text-xs font-semibold transition hover:-translate-y-0.5";
const primary = `${btn} bg-gradient-to-br from-orange-400 to-rose-500 text-[#1a1210] shadow-lg shadow-orange-500/20`;
const ghost = `${btn} border border-white/10 bg-white/5 text-slate-200 hover:bg-white/10`;
const danger = `${btn} border border-rose-400/40 bg-rose-500/15 text-rose-100`;
const chip = "rounded-lg border border-white/10 bg-white/5 px-2.5 py-1 text-[11px] text-slate-300 hover:bg-white/10";
const chipOn = "rounded-lg border border-orange-400/40 bg-orange-400/15 px-2.5 py-1 text-[11px] text-orange-100";
const actionCard =
"rounded-2xl border border-white/10 bg-black/35 p-3.5 text-left transition hover:-translate-y-1 hover:border-orange-400/35 hover:bg-black/50";
type Common = {
createJob: CreateJobFn;
toast: (msg: string, kind?: "ok" | "err") => void;
username: string;
setUsername: (v: string) => void;
limit: number;
setLimit: (n: number) => void;
minD: number;
setMinD: (n: number) => void;
maxD: number;
setMaxD: (n: number) => void;
};
export function WorkbenchPanel({
createJob,
extOnline,
accountsN,
stats,
onGo,
lastKind,
rerun,
likeN,
}: Common & {
extOnline: boolean;
accountsN: number;
stats: Record<string, number>;
onGo: (id: string) => void;
lastKind?: string;
rerun: () => void;
likeN: number;
}) {
return (
<div className="space-y-4">
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
{[
["扩展状态", extOnline ? "已连接" : "未连接", extOnline ? "text-emerald-300" : "text-amber-300", "Chrome 插件链路"],
["账号数", String(accountsN), "text-white", "已同步账号"],
["已完成", String(stats.completed ?? 0), "text-emerald-200", "成功任务"],
["进行中", String(stats.running ?? 0), "text-orange-200", `排队 ${stats.queued ?? 0} · 失败 ${stats.failed ?? 0}`],
].map(([k, v, c, s]) => (
<div key={k} className={panel}>
<div className="text-[11px] text-slate-500">{k}</div>
<div className={`mt-1 font-display text-2xl ${c}`}>{v}</div>
<div className="mt-1 text-[11px] text-slate-500">{s}</div>
</div>
))}
</div>
{!extOnline ? (
<div className="rounded-2xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-xs leading-relaxed text-amber-50">
<b>扩展未连接</b>
<div className="mt-1 text-amber-100/80">
加载 <code className="text-amber-50">extensions/dylive-helper/dist</code>
,登录本站并打开本页即可自动配对。插件 X 页签仍可独立操作。
</div>
</div>
) : null}
<div className={panel}>
<div className="mb-3 flex items-start justify-between gap-2">
<div>
<h3 className={title}>快捷入口</h3>
<p className={sub}>常用能力一键跳转或直接下发</p>
</div>
<button type="button" className={ghost} disabled={!lastKind} onClick={rerun}>
重跑上次
</button>
</div>
<div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
{(
[
["cleanup", "🧹", "扫描不互关", "找出没回关的人"],
["scrape", "📥", "采集数据", "画像 / 搜索 / 书签"],
["engage", "⚡", "互动增长", "赞 · 关 · 回 · 转推"],
["monitor", "📡", "粉丝监控", "掉粉 / 新粉对比"],
["jobs", "📋", "任务与结果", "队列 · 大白话结果"],
] as const
).map(([id, ico, t, d]) => (
<button key={id} type="button" className={actionCard} onClick={() => onGo(id)}>
<div className="text-lg">{ico}</div>
<div className="mt-1 text-sm font-semibold text-white">{t}</div>
<div className="mt-0.5 text-[11px] text-slate-500">{d}</div>
</button>
))}
<button
type="button"
className={actionCard}
onClick={() => void createJob("engage.like", { limit: likeN })}
>
<div className="text-lg">❤️</div>
<div className="mt-1 text-sm font-semibold text-white">快速点赞</div>
<div className="mt-0.5 text-[11px] text-slate-500">当前页可见 · {likeN} 条</div>
</button>
</div>
</div>
</div>
);
}
export function CleanupPanel({
createJob,
toast,
limit,
setLimit,
minD,
setMinD,
maxD,
setMaxD,
cleanupList,
setCleanupList,
lastNonFollowers,
}: Common & {
cleanupList: string;
setCleanupList: (v: string) => void;
lastNonFollowers: string[];
}) {
const [onlyNon, setOnlyNon] = useState(true);
const n = useMemo(() => parseHandles(cleanupList).length, [cleanupList]);
return (
<div className="space-y-4">
<div className={panel}>
<h3 className={title}>🧹 不互关扫描</h3>
<p className={sub}>对比关注与粉丝,找出没回关的人;结果可填入下方取关名单</p>
<div className="mt-3 flex flex-wrap gap-2">
{[50, 100, 200, 500].map((v) => (
<button key={v} type="button" className={limit === v ? chipOn : chip} onClick={() => setLimit(v)}>
{v === 50 ? "快扫 50" : v === 500 ? "深扫 500" : v}
</button>
))}
</div>
<div className="mt-3 flex flex-wrap items-end gap-2">
<label className={label}>
采样上限
<input type="number" className={field} style={{ width: 120 }} value={limit} onChange={(e) => setLimit(Number(e.target.value))} />
</label>
<button type="button" className={primary} onClick={() => void createJob("cleanup.non_followers", { limit })}>
扫描不互关
</button>
</div>
</div>
<div className="grid gap-4 lg:grid-cols-2">
<div className={panel}>
<div className="flex items-start justify-between gap-2">
<div>
<h3 className={title}>👋 精确取关</h3>
<p className={sub}>粘贴名单,带随机间隔限速执行</p>
</div>
<span className="text-[11px] text-slate-500">{n ? `${n} 人 · ${estimateEta(n, minD, maxD)}` : "名单为空"}</span>
</div>
<textarea
className={`${field} mt-3 min-h-[140px] font-mono text-xs`}
value={cleanupList}
onChange={(e) => setCleanupList(e.target.value)}
placeholder="每行一个用户名,支持逗号/空格分隔"
/>
<div className="mt-2 flex flex-wrap gap-2">
<label className={label}>
最小间隔 ms
<input type="number" className={field} style={{ width: 110 }} value={minD} onChange={(e) => setMinD(Number(e.target.value))} />
</label>
<label className={label}>
最大间隔 ms
<input type="number" className={field} style={{ width: 110 }} value={maxD} onChange={(e) => setMaxD(Number(e.target.value))} />
</label>
</div>
<div className="mt-3 flex flex-wrap gap-2">
<button
type="button"
className={danger}
onClick={() => {
const usernames = parseHandles(cleanupList);
if (!usernames.length) return toast("名单为空", "err");
if (!confirm(`确认限速取关 ${usernames.length} 人?\n预计 ${estimateEta(usernames.length, minD, maxD)}`)) return;
void createJob("cleanup.unfollow", { usernames, minDelayMs: minD, maxDelayMs: maxD });
}}
>
<UserMinus className="h-3.5 w-3.5" /> 限速取关
</button>
<button
type="button"
className={ghost}
onClick={() => {
setCleanupList(lastNonFollowers.join("\n"));
toast(lastNonFollowers.length ? `已填入 ${lastNonFollowers.length} 人` : "还没有扫描结果", lastNonFollowers.length ? "ok" : "err");
}}
>
填入上次扫描
</button>
<button type="button" className={ghost} onClick={() => setCleanupList("")}>
清空名单
</button>
<button
type="button"
className={ghost}
onClick={async () => {
try {
const text = await navigator.clipboard.readText();
const handles = parseHandles(text);
if (!handles.length) return toast("剪贴板没有用户名", "err");
setCleanupList(handles.join("\n"));
toast(`已粘贴 ${handles.length} 人`, "ok");
} catch {
toast("无法读取剪贴板", "err");
}
}}
>
从剪贴板粘贴
</button>
</div>
</div>
<div className="space-y-4">
<div className={panel}>
<h3 className={title}>✂️ 可见页快速取关</h3>
<p className={sub}>打开 Following,滚动点「正在关注」。默认识别互关并跳过</p>
<label className={`${label} mt-3 flex items-center gap-2`}>
<input type="checkbox" checked={onlyNon} onChange={(e) => setOnlyNon(e.target.checked)} />
仅取关没回关的
</label>
<button
type="button"
className={`${danger} mt-3`}
onClick={() => {
if (!confirm(`确认限速取关最多 ${limit} 人?\n模式:${onlyNon ? "仅非互关" : "可见全部"}`)) return;
void createJob("cleanup.unfollow_visible", {
limit,
onlyNonFollowers: onlyNon,
minDelayMs: minD,
maxDelayMs: maxD,
});
}}
>
<UserMinus className="h-3.5 w-3.5" /> 开始可见取关
</button>
</div>
<div className={panel}>
<h3 className={title}>🔇 静音 / 🚫 屏蔽</h3>
<p className={sub}>使用上方名单逐个打开主页执行(限速),屏蔽请谨慎</p>
<div className="mt-3 flex flex-wrap gap-2">
{(
[
["cleanup.mute", "🔇 批量静音", false],
["cleanup.unmute", "🔔 取消静音", false],
["cleanup.block", "🚫 批量屏蔽", true],
["cleanup.unblock", "✅ 取消屏蔽", false],
] as const
).map(([kind, labelText, heavy]) => (
<button
key={kind}
type="button"
className={heavy ? danger : ghost}
onClick={() => {
const usernames = parseHandles(cleanupList);
if (!usernames.length) return toast("名单为空", "err");
if (!confirm(`确认对 ${usernames.length} 人执行:${labelText}?`)) return;
void createJob(kind, { usernames, minDelayMs: minD, maxDelayMs: maxD });
}}
>
{labelText}
</button>
))}
</div>
</div>
</div>
</div>
</div>
);
}
export function ScrapePanel({ createJob, toast, username, setUsername, limit, setLimit }: Common) {
const [query, setQuery] = useState("");
const [hashtag, setHashtag] = useState("");
const [likersUrl, setLikersUrl] = useState("");
const [threadUrl, setThreadUrl] = useState("");
const [listUrl, setListUrl] = useState("");
const [retweetersUrl, setRetweetersUrl] = useState("");
const [quotesUrl, setQuotesUrl] = useState("");
const [compareList, setCompareList] = useState("");
const [advFrom, setAdvFrom] = useState("");
const [advSince, setAdvSince] = useState("");
const [advUntil, setAdvUntil] = useState("");
const [advMinFaves, setAdvMinFaves] = useState(0);
const [advMedia, setAdvMedia] = useState(false);
const [advNoReplies, setAdvNoReplies] = useState(false);
const base = () => ({
limit,
...(username.trim() ? { username: username.trim().replace(/^@/, "") } : {}),
});
return (
<div className="space-y-4">
<div className={panel}>
<h3 className={title}>📥 数据采集</h3>
<p className={sub}>画像、关注、粉丝、推文语料 — 目标为空则用插件当前登录号</p>
<div className="mt-3 grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
{(
[
["scrape.profile", "👤", "锁定画像", "粉丝 · 关注 · 简介"],
["scrape.following", "➡️", "抓取 Following", "关注图谱"],
["scrape.followers", "⬅️", "抓取 Followers", "粉丝图谱"],
["scrape.tweets", "🧵", "抽取推文语料", "时间线文本"],
] as const
).map(([kind, ico, t, d]) => (
<button key={kind} type="button" className={actionCard} onClick={() => void createJob(kind, base())}>
<div className="flex items-center gap-1 text-base">
{ico} <Download className="h-3.5 w-3.5 text-orange-300" />
</div>
<div className="mt-1 text-sm font-semibold text-white">{t}</div>
<div className="text-[11px] text-slate-500">{d}</div>
</button>
))}
</div>
<div className="mt-3 flex flex-wrap gap-2">
{[50, 100, 300].map((v) => (
<button key={v} type="button" className={limit === v ? chipOn : chip} onClick={() => setLimit(v)}>
{v}
</button>
))}
</div>
<div className="mt-3 flex flex-wrap gap-2">
<label className={label}>
条数
<input type="number" className={field} style={{ width: 100 }} value={limit} onChange={(e) => setLimit(Number(e.target.value))} />
</label>
<label className={`${label} min-w-[180px] flex-1`}>
覆盖用户名(可空)
<input className={field} value={username} onChange={(e) => setUsername(e.target.value)} placeholder="可选" />
</label>
</div>
</div>
<div className="grid gap-4 lg:grid-cols-2">
<div className={panel}>
<h3 className={title}>🔎 关键词搜索推文</h3>
<p className={sub}>打开搜索页实时流并采集</p>
<label className={`${label} mt-3`}>
关键词
<input className={field} value={query} onChange={(e) => setQuery(e.target.value)} placeholder="brand OR #hashtag" />
</label>
<details className="mt-2">
<summary className="cursor-pointer text-[11px] text-slate-500">高级搜索运算符</summary>
<div className="mt-2 grid gap-2 sm:grid-cols-2">
<label className={label}>from:<input className={field} value={advFrom} onChange={(e) => setAdvFrom(e.target.value)} /></label>
<label className={label}>最少赞<input type="number" className={field} value={advMinFaves} onChange={(e) => setAdvMinFaves(Number(e.target.value))} /></label>
<label className={label}>since<input className={field} value={advSince} onChange={(e) => setAdvSince(e.target.value)} placeholder="2024-01-01" /></label>
<label className={label}>until<input className={field} value={advUntil} onChange={(e) => setAdvUntil(e.target.value)} placeholder="2024-12-31" /></label>
</div>
<div className="mt-2 flex gap-4 text-[11px] text-slate-400">
<label className="flex items-center gap-1"><input type="checkbox" checked={advMedia} onChange={(e) => setAdvMedia(e.target.checked)} />仅媒体</label>
<label className="flex items-center gap-1"><input type="checkbox" checked={advNoReplies} onChange={(e) => setAdvNoReplies(e.target.checked)} />排除回复</label>
</div>
</details>
<button
type="button"
className={`${primary} mt-3`}
onClick={() => {
const q = buildAdvancedSearch({
keywords: query,
from: advFrom,
since: advSince || undefined,
until: advUntil || undefined,
minFaves: advMinFaves || undefined,
onlyMedia: advMedia,
filterReplies: advNoReplies,
});
if (!q) return toast("先填关键词", "err");
void createJob("scrape.search", { query: q, limit });
}}
>
开始搜索采集
</button>
</div>
<div className={panel}>
<h3 className={title}>🔖 书签 · 🎬 媒体 · 🏠 首页</h3>
<p className={sub}>快捷采集入口</p>
<div className="mt-3 flex flex-wrap gap-2">
<button type="button" className={primary} onClick={() => void createJob("scrape.bookmarks", { limit })}>导出我的书签</button>
<button
type="button"
className={ghost}
onClick={() => void createJob("scrape.media", { ...base(), ...(query.trim() ? { query: query.trim() } : {}) })}
>
提取媒体
</button>
<button type="button" className={ghost} onClick={() => void createJob("scrape.home", { limit })}>首页时间线</button>
<button type="button" className={ghost} onClick={() => void createJob("scrape.mentions", { limit })}>提及</button>
<button type="button" className={ghost} onClick={() => void createJob("scrape.notifications", { limit })}>抓通知</button>
<button
type="button"
className={ghost}
onClick={() => {
const u = username.trim().replace(/^@/, "");
if (!u) return toast("先填用户名", "err");
void createJob("scrape.with_replies", { username: u, limit });
}}
>
含回复
</button>
<button
type="button"
className={ghost}
onClick={() => {
const u = username.trim().replace(/^@/, "");
if (!u) return toast("先填用户名", "err");
void createJob("scrape.likes", { username: u, limit });
}}
>
点赞时间线
</button>
</div>
</div>
</div>
<div className="grid gap-4 lg:grid-cols-2">
<div className={panel}>
<h3 className={title}>👏 点赞用户 · 🪢 推文串</h3>
<label className={`${label} mt-3`}>
推文链接(点赞用户)
<input className={field} value={likersUrl} onChange={(e) => setLikersUrl(e.target.value)} placeholder="https://x.com/…/status/…" />
</label>
<button
type="button"
className={`${primary} mt-2`}
onClick={() => {
if (!likersUrl.includes("/status/")) return toast("先填推文链接", "err");
void createJob("scrape.likers", { statusUrl: likersUrl.trim(), limit });
}}
>
采集点赞用户
</button>
<label className={`${label} mt-3`}>
推文链接(线程)
<input className={field} value={threadUrl} onChange={(e) => setThreadUrl(e.target.value)} placeholder="https://x.com/…/status/…" />
</label>
<button
type="button"
className={`${ghost} mt-2`}
onClick={() => {
if (!threadUrl.includes("/status/")) return toast("先填推文链接", "err");
void createJob("scrape.thread", { statusUrl: threadUrl.trim(), limit });
}}
>
采集线程
</button>
</div>
<div className={panel}>
<h3 className={title}>#️⃣ 话题 · 👥 搜人 · 列表</h3>
<label className={`${label} mt-3`}>
话题标签
<input className={field} value={hashtag} onChange={(e) => setHashtag(e.target.value)} placeholder="AI 或 #AI" />
</label>
<div className="mt-2 flex flex-wrap gap-2">
<button
type="button"
className={primary}
onClick={() => {
const tag = (hashtag.trim() || query.trim()).replace(/^#/, "");
if (!tag) return toast("先填话题或关键词", "err");
void createJob("scrape.hashtag", { hashtag: tag, limit });
}}
>
抓话题
</button>
<button
type="button"
className={ghost}
onClick={() => {
const q = (query.trim() || hashtag.trim()).replace(/^#/, "");
if (!q) return toast("先填关键词", "err");
void createJob("scrape.people", { query: q, limit });
}}
>
搜人
</button>
</div>
<label className={`${label} mt-3`}>
列表链接
<input className={field} value={listUrl} onChange={(e) => setListUrl(e.target.value)} placeholder="https://x.com/i/lists/…" />
</label>
<button
type="button"
className={`${ghost} mt-2`}
onClick={() => {
if (!listUrl.trim()) return toast("先填列表链接", "err");
void createJob("scrape.list", { listUrl: listUrl.trim(), limit });
}}
>
采集列表成员
</button>
</div>
</div>
<div className="grid gap-4 lg:grid-cols-2">
<div className={panel}>
<h3 className={title}>🔁 转推 / 引用用户</h3>
<label className={`${label} mt-3`}>
转推用户(推文链接)
<input className={field} value={retweetersUrl} onChange={(e) => setRetweetersUrl(e.target.value)} />
</label>
<button
type="button"
className={`${ghost} mt-2`}
onClick={() => {
if (!retweetersUrl.includes("/status/")) return toast("先填链接", "err");
void createJob("scrape.retweeters", { statusUrl: retweetersUrl.trim(), limit });
}}
>
采集转推用户
</button>
<label className={`${label} mt-3`}>
引用用户(推文链接)
<input className={field} value={quotesUrl} onChange={(e) => setQuotesUrl(e.target.value)} />
</label>
<button
type="button"
className={`${ghost} mt-2`}
onClick={() => {
if (!quotesUrl.includes("/status/")) return toast("先填链接", "err");
void createJob("scrape.quotes", { statusUrl: quotesUrl.trim(), limit });
}}
>
采集引用用户
</button>
</div>
<div className={panel}>
<h3 className={title}>📊 对比账号画像</h3>
<p className={sub}>至少 2 个用户名,按粉丝排序</p>
<textarea className={`${field} mt-3 min-h-[88px] font-mono text-xs`} value={compareList} onChange={(e) => setCompareList(e.target.value)} placeholder={"elonmusk\nOpenAI"} />
<button
type="button"
className={`${primary} mt-2`}
onClick={() => {
const list = parseHandles(compareList);
if (list.length < 2) return toast("至少 2 个账号", "err");
void createJob("analyze.profiles", { usernames: list });
}}
>
开始对比
</button>
<button
type="button"
className={`${ghost} mt-2`}
onClick={() => {
const u = username.trim().replace(/^@/, "");
if (!u) return toast("先填用户名", "err");
void createJob("analyze.tweets", { username: u, limit });
}}
>
📈 推文表现分析
</button>
</div>
</div>
</div>
);
}
export function EngagePanel({
createJob,
toast,
username,
minD,
maxD,
likeN,
setLikeN,
followN,
setFollowN,
}: Common & { likeN: number; setLikeN: (n: number) => void; followN: number; setFollowN: (n: number) => void }) {
const [unlike, setUnlike] = useState(15);
const [kw, setKw] = useState("");
const [followList, setFollowList] = useState("");
const [text, setText] = useState("");
const [statusUrl, setStatusUrl] = useState("");
const [replyText, setReplyText] = useState("");
const [quoteText, setQuoteText] = useState("");
const [growthQuery, setGrowthQuery] = useState("");
const [gLike, setGLike] = useState(10);
const [gFollow, setGFollow] = useState(5);
const [gReply, setGReply] = useState(0);
const [gReplyText, setGReplyText] = useState("");
return (
<div className="space-y-4">
<div className={panel}>
<h3 className={title}>⚡ 互动</h3>
<p className={sub}>点赞、关注、发帖、回复、转推都会带随机间隔 · 当前 @{username || "插件登录号"}</p>
<div className="mt-3 grid gap-3 sm:grid-cols-3">
<div className="rounded-xl border border-white/10 bg-black/30 p-3">
<div className="text-[11px] text-slate-500">间隔</div>
<div className="mt-1 text-lg text-orange-200">{minD}-{maxD} <span className="text-xs">ms</span></div>
</div>
<div className="rounded-xl border border-white/10 bg-black/30 p-3">
<div className="text-[11px] text-slate-500">点赞目标</div>
<div className="mt-1 text-lg text-white">{likeN} · {estimateEta(likeN, minD, maxD)}</div>
</div>
<div className="rounded-xl border border-white/10 bg-black/30 p-3">
<div className="text-[11px] text-slate-500">关注目标</div>
<div className="mt-1 text-lg text-white">{followN} · {estimateEta(followN, minD, maxD)}</div>
</div>
</div>
</div>
<div className="grid gap-4 lg:grid-cols-2">
<div className={panel}>
<h3 className={title}>❤️ 点赞</h3>
<p className={sub}>当前页可见,或按关键词搜后再赞</p>
<label className={`${label} mt-3`}>数量<input type="number" className={field} value={likeN} onChange={(e) => setLikeN(Number(e.target.value))} /></label>
<label className={`${label} mt-2`}>关键词(可空)<input className={field} value={kw} onChange={(e) => setKw(e.target.value)} /></label>
<button type="button" className={`${primary} mt-3`} onClick={() => void createJob("engage.like", { limit: likeN, ...(kw.trim() ? { query: kw.trim() } : {}) })}>
<Heart className="h-3.5 w-3.5" /> 开始点赞
</button>
<div className="mt-3 flex flex-wrap items-end gap-2">
<label className={label}>取消点赞数<input type="number" className={field} style={{ width: 100 }} value={unlike} onChange={(e) => setUnlike(Number(e.target.value))} /></label>
<button type="button" className={ghost} onClick={() => void createJob("engage.unlike", { limit: unlike, ...(kw.trim() ? { query: kw.trim() } : {}) })}>💔 取消点赞</button>
</div>
</div>
<div className={panel}>
<h3 className={title}>➕ 关注</h3>
<p className={sub}>当前页,或搜用户后再关</p>
<label className={`${label} mt-3`}>数量<input type="number" className={field} value={followN} onChange={(e) => setFollowN(Number(e.target.value))} /></label>
<button type="button" className={`${primary} mt-3`} onClick={() => void createJob("engage.follow", { limit: followN, ...(kw.trim() ? { query: kw.trim() } : {}) })}>
<UserPlus className="h-3.5 w-3.5" /> 开始关注
</button>
<label className={`${label} mt-3`}>或按名单关注<textarea className={`${field} min-h-[72px] font-mono text-xs`} value={followList} onChange={(e) => setFollowList(e.target.value)} /></label>
<button
type="button"
className={`${ghost} mt-2`}
onClick={() => {
const usernames = parseHandles(followList);
if (!usernames.length) return toast("名单为空", "err");
void createJob("engage.follow", { usernames, minDelayMs: minD, maxDelayMs: maxD });
}}
>
按名单关注
</button>
</div>
</div>
<div className="grid gap-4 lg:grid-cols-2">
<div className={panel}>
<h3 className={title}>✍️ 发帖</h3>
<textarea className={`${field} mt-3 min-h-[100px]`} value={text} onChange={(e) => setText(e.target.value)} placeholder="说点什么…" />
<button
type="button"
className={`${primary} mt-2`}
onClick={() => {
if (!text.trim()) return toast("内容为空", "err");
void createJob("engage.post", { text: text.trim() });
}}
>
发帖
</button>
</div>
<div className={panel}>
<h3 className={title}>💬 回复 / 转推 / 引用 / 收藏</h3>
<label className={`${label} mt-3`}>推文链接<input className={field} value={statusUrl} onChange={(e) => setStatusUrl(e.target.value)} placeholder="https://x.com/…/status/…" /></label>
<label className={`${label} mt-2`}>回复内容<input className={field} value={replyText} onChange={(e) => setReplyText(e.target.value)} /></label>
<label className={`${label} mt-2`}>引用文案<input className={field} value={quoteText} onChange={(e) => setQuoteText(e.target.value)} /></label>
<div className="mt-3 flex flex-wrap gap-2">
<button
type="button"
className={primary}
onClick={() => {
if (!statusUrl.trim() || !replyText.trim()) return toast("链接和回复都要填", "err");
void createJob("engage.reply", { statusUrl: statusUrl.trim(), text: replyText.trim() });
}}
>
回复
</button>
<button type="button" className={ghost} onClick={() => { if (!statusUrl.trim()) return toast("先填链接", "err"); void createJob("engage.retweet", { statusUrl: statusUrl.trim() }); }}>转推</button>
<button type="button" className={ghost} onClick={() => { if (!statusUrl.trim() || !quoteText.trim()) return toast("链接和引用文案都要", "err"); void createJob("engage.quote", { statusUrl: statusUrl.trim(), text: quoteText.trim() }); }}>引用</button>
<button type="button" className={ghost} onClick={() => { if (!statusUrl.trim()) return toast("先填链接", "err"); void createJob("engage.bookmark", { statusUrl: statusUrl.trim() }); }}>📌 收藏</button>
<button type="button" className={ghost} onClick={() => { if (!statusUrl.trim()) return toast("先填链接", "err"); void createJob("engage.copy_link", { statusUrl: statusUrl.trim() }); }}>🔗 复制链接</button>
</div>
</div>
</div>
<div className={panel}>
<h3 className={title}>🌱 增长</h3>
<p className={sub}>搜关键词后批量赞/关,或刷首页互动</p>
<div className="mt-3 flex flex-wrap gap-2">
<label className={`${label} min-w-[200px] flex-1`}>增长关键词<input className={field} value={growthQuery} onChange={(e) => setGrowthQuery(e.target.value)} /></label>
<label className={label}>赞<input type="number" className={field} style={{ width: 80 }} value={gLike} onChange={(e) => setGLike(Number(e.target.value))} /></label>
<label className={label}>关<input type="number" className={field} style={{ width: 80 }} value={gFollow} onChange={(e) => setGFollow(Number(e.target.value))} /></label>
<label className={label}>回<input type="number" className={field} style={{ width: 80 }} value={gReply} onChange={(e) => setGReply(Number(e.target.value))} /></label>
</div>
{gReply > 0 ? (
<label className={`${label} mt-2`}>回复模板<input className={field} value={gReplyText} onChange={(e) => setGReplyText(e.target.value)} /></label>
) : null}
<div className="mt-3 flex flex-wrap gap-2">
<button
type="button"
className={primary}
onClick={() => {
if (!growthQuery.trim()) return toast("先填关键词", "err");
void createJob("growth.engage", {
query: growthQuery.trim(),
likeLimit: gLike,
followLimit: gFollow,
replyLimit: gReply,
...(gReplyText.trim() ? { replyText: gReplyText.trim() } : {}),
});
}}
>
关键词增长
</button>
<button
type="button"
className={ghost}
onClick={() =>
void createJob("growth.home", {
likeLimit: gLike,
followLimit: gFollow,
replyLimit: gReply,
...(gReplyText.trim() ? { replyText: gReplyText.trim() } : {}),
})
}
>
首页互动
</button>
</div>
</div>
</div>
);
}
export function MonitorPanel({ createJob, limit, setLimit }: Common) {
return (
<div className="space-y-4">
<div className={panel}>
<h3 className={title}>📡 粉丝监控</h3>
<p className={sub}>第一次存基线,之后对比新粉 / 掉粉(由插件在 x.com 采集)</p>
<div className="mt-3 flex flex-wrap items-end gap-2">
<label className={label}>
快照深度
<input type="number" className={field} style={{ width: 120 }} value={limit} onChange={(e) => setLimit(Number(e.target.value))} />
</label>
<button type="button" className={primary} onClick={() => void createJob("monitor.snapshot_followers", { limit })}>
<Radar className="h-3.5 w-3.5" /> 捕获粉丝快照
</button>
<button type="button" className={ghost} onClick={() => void createJob("monitor.snapshot_following", { limit })}>
👀 捕获关注快照
</button>
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className={panel}>
<h3 className={title}>说明</h3>
<div className="mt-2 space-y-2 text-xs text-slate-400">
<div className="rounded-lg border border-white/5 bg-black/30 px-3 py-2">新粉 = 新关注你的人</div>
<div className="rounded-lg border border-white/5 bg-black/30 px-3 py-2">掉粉 = 取消关注你的人</div>
<div className="rounded-lg border border-white/5 bg-black/30 px-3 py-2">建议隔几小时再拍一次对比</div>
</div>
</div>
<div className={panel}>
<h3 className={title}>推荐流程</h3>
<div className="mt-2 space-y-2 text-xs text-slate-400">
<div className="rounded-lg border border-white/5 bg-black/30 px-3 py-2">1. 先捕获粉丝快照</div>
<div className="rounded-lg border border-white/5 bg-black/30 px-3 py-2">2. 过一段时间再拍一次</div>
<div className="rounded-lg border border-white/5 bg-black/30 px-3 py-2">3. 在右侧结果看 diff</div>
</div>
</div>
</div>
</div>
);
}

View File

@ -1,13 +1,32 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { RefreshCw, Square } from "lucide-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,
type XJob,
} from "@/lib/xOps";
import {
CleanupPanel,
EngagePanel,
MonitorPanel,
ScrapePanel,
WorkbenchPanel,
} from "./XOpsPanels";
type TabId = "workbench" | "cleanup" | "scrape" | "engage" | "jobs";
type TabId = "workbench" | "cleanup" | "scrape" | "engage" | "monitor" | "jobs";
type X2Agent = {
id: string;
@ -21,146 +40,110 @@ type X2Account = {
id: string;
username?: string;
display_name?: string;
avatar_url?: string;
last_seen_at?: string;
};
type X2Job = {
id: string;
kind?: string;
status?: string;
account_username?: string;
progress_current?: number;
progress_total?: number;
progress_message?: string;
error?: string;
received_at?: number;
job_updated_at?: string;
result?: Record<string, unknown>;
params?: Record<string, unknown>;
};
const TABS: { id: TabId; label: string }[] = [
{ id: "workbench", label: "工作台" },
{ id: "cleanup", label: "清理" },
{ id: "scrape", label: "采集" },
{ id: "engage", label: "互动" },
{ id: "jobs", label: "任务" },
const NAV: { id: TabId; emoji: string; label: string }[] = [
{ id: "workbench", emoji: "🏠", label: "工作台" },
{ id: "cleanup", emoji: "🧹", label: "清理" },
{ id: "scrape", emoji: "📥", label: "采集" },
{ id: "engage", emoji: "⚡", label: "互动" },
{ id: "monitor", emoji: "📡", label: "监控" },
{ id: "jobs", emoji: "📋", label: "任务" },
];
const STATUS_ZH: Record<string, string> = {
queued: "排队",
running: "执行中",
completed: "完成",
failed: "失败",
cancelled: "已取消",
};
function kindLabel(kind?: string) {
const m: Record<string, string> = {
"cleanup.non_followers": "不互关扫描",
"cleanup.unfollow": "限速取关",
"cleanup.unfollow_visible": "可见取关",
"scrape.profile": "画像",
"scrape.following": "关注列表",
"scrape.followers": "粉丝列表",
"scrape.tweets": "推文",
"scrape.search": "搜索",
"scrape.home": "首页",
"scrape.notifications": "通知",
"engage.like": "点赞",
"engage.follow": "关注",
"engage.post": "发帖",
"engage.reply": "回复",
"engage.retweet": "转推",
};
return (kind && m[kind]) || kind || "任务";
}
export default function XPage() {
const toast = useToast();
const [tab, setTab] = useState<TabId>("workbench");
const [loading, setLoading] = useState(true);
const [agents, setAgents] = useState<X2Agent[]>([]);
const [accounts, setAccounts] = useState<X2Account[]>([]);
const [jobs, setJobs] = useState<X2Job[]>([]);
const [jobs, setJobs] = useState<XJob[]>([]);
const [stats, setStats] = useState<Record<string, number>>({});
const [extOnline, setExtOnline] = useState(false);
const [username, setUsername] = useState("");
const [limit, setLimit] = useState(80);
const [query, setQuery] = useState("");
const [cleanupList, setCleanupList] = useState("");
const [minD, setMinD] = useState(2000);
const [maxD, setMaxD] = useState(5000);
const [likeN, setLikeN] = useState(10);
const [followN, setFollowN] = useState(5);
const [postText, setPostText] = useState("");
const [statusUrl, setStatusUrl] = useState("");
const [replyText, setReplyText] = useState("");
const [cleanupList, setCleanupList] = useState("");
const [selectedId, setSelectedId] = useState<string | null>(null);
const [feedFilter, setFeedFilter] = useState<"all" | "active" | "completed" | "failed">("all");
const [lastJob, setLastJob] = useState<{ kind: string; params: Record<string, unknown> } | null>(null);
const load = useCallback(async () => {
try {
const st = await fetchJson("/api/x2/status");
setAgents(st?.agents || []);
setAccounts(st?.accounts || []);
setJobs(st?.jobs || []);
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 || [];
if (!username && accs[0]?.username) setUsername(String(accs[0].username));
} catch (e: any) {
toast.push(e?.message || "加载失败", "err");
setUsername((cur) => {
if (cur) return cur;
return accs[0]?.username ? String(accs[0].username) : "";
});
} catch (e: unknown) {
toast.push((e as Error)?.message || "加载失败", "err");
} finally {
setLoading(false);
}
}, [toast, username]);
}, [toast]);
useEffect(() => {
void load();
const t = setInterval(() => void load(), 4000);
const t = setInterval(() => void load(), 3500);
return () => clearInterval(t);
}, [load]);
const createJob = async (kind: string, params: Record<string, unknown> = {}) => {
if (!extOnline) {
toast.push("插件未在线:请加载 dylive Helper,并打开本站任意页完成自动配对", "err");
}
try {
const createJob = useCallback(
async (kind: string, params: Record<string, unknown> = {}) => {
if (!extOnline) {
toast.push("插件未在线:请加载扩展并打开本页完成自动配对", "err");
}
const merged = {
...(username.trim() ? { username: username.trim().replace(/^@/, "") } : {}),
export: "none",
...params,
};
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");
setTab("jobs");
} else {
toast.push("创建失败", "err");
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");
}
} catch (e: any) {
toast.push(e?.message || "创建失败", "err");
}
};
},
[extOnline, toast, username],
);
const cancelJob = async (id: string) => {
try {
const r = await fetchJson(`/api/x2/jobs/${encodeURIComponent(id)}/cancel`, {
method: "POST",
});
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: any) {
toast.push(e?.message || "取消失败", "err");
} catch (e: unknown) {
toast.push((e as Error)?.message || "取消失败", "err");
}
};
@ -169,423 +152,345 @@ export default function XPage() {
[jobs, selectedId],
);
const field =
"mt-1 w-full rounded-lg border border-white/10 bg-black/40 px-3 py-2 text-sm text-slate-100";
const btnPrimary =
"rounded-lg bg-cyan-600/90 px-3 py-2 text-xs font-medium text-white hover:bg-cyan-500";
const btnGhost =
"rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-300 hover:bg-white/10";
const panel = "rounded-2xl border border-white/10 bg-black/25 p-4";
const filteredJobs = useMemo(() => {
return jobs.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;
});
}, [jobs, feedFilter]);
const lastNonFollowers = useMemo(() => {
for (const j of jobs) {
const list = nonFollowersFromJob(j);
if (list.length) return list;
}
return [] as string[];
}, [jobs]);
const active = jobs.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 (
<Shell>
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-display text-xl font-semibold text-white sm:text-2xl">X Ops</h2>
<p className="mt-1 text-sm text-slate-400">
Web 下发任务 · Chrome 插件在浏览器执行(插件 popup 仍可独立操作)
</p>
</div>
<button type="button" onClick={() => void load()} className={btnGhost}>
<RefreshCw className={`mr-1 inline h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
刷新
</button>
</div>
<div className="mb-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
{[
["插件", extOnline ? "在线" : "离线", extOnline ? "text-emerald-300" : "text-amber-300"],
["账号", String(stats.accounts ?? accounts.length), "text-white"],
["排队/执行", `${stats.queued ?? 0} / ${stats.running ?? 0}`, "text-white"],
["完成/失败", `${stats.completed ?? 0} / ${stats.failed ?? 0}`, "text-white"],
].map(([k, v, c]) => (
<div key={k} className="rounded-xl border border-white/10 bg-black/25 p-3">
<div className="text-[11px] text-slate-500">{k}</div>
<div className={`mt-1 font-display text-2xl ${c}`}>{v}</div>
</div>
))}
</div>
{!extOnline ? (
<div className="mb-4 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-xs text-amber-100">
插件未在线。加载 <code className="text-amber-50">extensions/dylive-helper/dist</code>
,登录本站并打开本页即可<strong className="font-medium">自动配对</strong>
(无需在插件里手填 Token)。X 页签功能仍可在插件内独立使用。
</div>
) : null}
<div className="mb-3 flex flex-wrap gap-2">
<label className="text-xs text-slate-400">
目标账号
<input
className={field}
style={{ width: 180 }}
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder={accounts[0]?.username || "可空=当前登录"}
list="x-accs"
/>
<datalist id="x-accs">
{accounts.map((a) => (
<option key={a.id} value={a.username || ""} />
))}
</datalist>
</label>
<label className="text-xs text-slate-400">
条数
<input
type="number"
className={field}
style={{ width: 100 }}
value={limit}
onChange={(e) => setLimit(Number(e.target.value) || 80)}
/>
</label>
</div>
<nav className="mb-4 flex flex-wrap gap-1">
{TABS.map((t) => (
<button
key={t.id}
type="button"
onClick={() => setTab(t.id)}
className={
"rounded-lg px-3 py-2 text-xs font-medium " +
(tab === t.id
? "bg-white/15 text-white"
: "bg-white/5 text-slate-400 hover:bg-white/10")
}
>
{t.label}
</button>
))}
</nav>
{tab === "workbench" ? (
<div className="grid gap-4 lg:grid-cols-2">
<section className={panel}>
<h3 className="text-sm font-medium text-slate-100">快捷下发</h3>
<p className="mt-1 text-[11px] text-slate-500">与插件 X 页签同类能力,由 Web 入队、插件领取执行</p>
<div className="mt-3 grid grid-cols-2 gap-2">
{(
[
["cleanup.non_followers", "扫描不互关"],
["scrape.profile", "画像"],
["scrape.followers", "粉丝"],
["scrape.tweets", "推文"],
["scrape.home", "首页时间线"],
["engage.like", "可见点赞"],
] as const
).map(([kind, label]) => (
<button
key={kind}
type="button"
className={btnPrimary}
onClick={() =>
void createJob(kind, {
limit: kind.startsWith("engage") ? likeN : limit,
})
}
>
{label}
</button>
))}
<div className="relative mb-3 overflow-hidden rounded-3xl border border-white/10 bg-black/30 p-4 sm:p-5">
<div
className="pointer-events-none absolute -left-10 -top-16 h-40 w-40 rounded-full bg-orange-400/20 blur-3xl"
aria-hidden
/>
<div
className="pointer-events-none absolute -right-8 top-0 h-36 w-36 rounded-full bg-teal-400/15 blur-3xl"
aria-hidden
/>
<div className="relative flex flex-wrap items-start justify-between gap-3">
<div className="flex items-start gap-3">
<div className="flex h-12 w-12 items-center justify-center rounded-2xl border border-orange-400/30 bg-gradient-to-br from-orange-400/20 to-rose-500/10 text-2xl text-white shadow-lg shadow-orange-500/10">
𝕏
</div>
</section>
<section className={panel}>
<h3 className="text-sm font-medium text-slate-100">Agent</h3>
{agents.length === 0 ? (
<p className="mt-2 text-xs text-slate-500">等待插件心跳…</p>
) : (
<ul className="mt-2 space-y-2 text-xs text-slate-300">
{agents.map((a) => (
<li key={a.id} className="flex justify-between gap-2 border-b border-white/5 pb-2">
<span>
{a.label || a.id}
{a.extension_connected ? " · 扩展" : ""}
</span>
<span className={a.online ? "text-emerald-300" : "text-slate-500"}>
{a.online ? "在线" : "离线"}
{a.last_seen_at ? ` · ${fmtTs(a.last_seen_at)}` : ""}
</span>
</li>
<div>
<div className="text-[11px] uppercase tracking-[0.18em] text-orange-200/70">X2 Ops</div>
<h2 className="font-display text-2xl font-semibold text-white">X 运营控制台</h2>
<p className="mt-1 max-w-xl text-sm text-slate-400">
Web 下发 · 插件在浏览器执行 · 与 Electron / 插件 popup 同级能力
</p>
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
<span
className={
"inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-[11px] font-semibold " +
(extOnline
? "border-emerald-400/30 bg-emerald-500/10 text-emerald-200"
: "border-amber-400/30 bg-amber-500/10 text-amber-100")
}
>
<span className={"h-1.5 w-1.5 rounded-full " + (extOnline ? "bg-emerald-300" : "bg-amber-300")} />
{extOnline ? "插件已连接" : "插件离线"}
</span>
<label className="text-[11px] text-slate-400">
账号
<select
className="ml-1 rounded-lg border border-white/10 bg-black/50 px-2 py-1.5 text-xs text-slate-100"
value={username}
onChange={(e) => setUsername(e.target.value)}
>
<option value="">插件当前号</option>
{accounts.map((a) => (
<option key={a.id} value={a.username || ""}>
@{a.username}
{a.display_name ? ` · ${a.display_name}` : ""}
</option>
))}
</ul>
)}
</section>
</div>
) : null}
{tab === "cleanup" ? (
<div className="grid gap-4 lg:grid-cols-2">
<section className={panel}>
<h3 className="text-sm font-medium text-slate-100">不互关扫描</h3>
</select>
</label>
<button
type="button"
className={`${btnPrimary} mt-3`}
onClick={() => void createJob("cleanup.non_followers", { limit })}
onClick={() => void load()}
className="inline-flex items-center gap-1.5 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-300 hover:bg-white/10"
>
扫描
<RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
刷新
</button>
</section>
<section className={panel}>
<h3 className="text-sm font-medium text-slate-100">限速取关</h3>
<textarea
className={`${field} min-h-[120px] font-mono text-xs`}
placeholder="每行一个用户名"
value={cleanupList}
onChange={(e) => setCleanupList(e.target.value)}
/>
<div className="mt-2 flex flex-wrap gap-2">
<input
type="number"
className={field}
style={{ width: 110 }}
value={minD}
onChange={(e) => setMinD(Number(e.target.value))}
title="最小间隔 ms"
/>
<input
type="number"
className={field}
style={{ width: 110 }}
value={maxD}
onChange={(e) => setMaxD(Number(e.target.value))}
title="最大间隔 ms"
/>
<button
type="button"
className="rounded-lg border border-rose-500/40 bg-rose-500/15 px-3 py-2 text-xs text-rose-100"
onClick={() => {
const usernames = cleanupList
.split(/[\n,,\s]+/)
.map((s) => s.replace(/^@/, "").trim())
.filter(Boolean);
if (!usernames.length) return toast.push("名单为空", "err");
if (!confirm(`确认取关 ${usernames.length} 人?`)) return;
void createJob("cleanup.unfollow", {
usernames,
minDelayMs: minD,
maxDelayMs: maxD,
});
}}
>
开始取关
</button>
</div>
</section>
</div>
</div>
) : null}
{tab === "scrape" ? (
<section className={panel}>
<h3 className="text-sm font-medium text-slate-100">数据采集</h3>
<label className="mt-3 block text-xs text-slate-400">
搜索词
<input className={field} value={query} onChange={(e) => setQuery(e.target.value)} />
</label>
<div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-3">
{active ? (
<div className="relative mt-4 flex flex-wrap items-center gap-3 rounded-2xl border border-orange-400/25 bg-orange-500/10 px-3 py-2.5">
<div className="min-w-0 flex-1">
<div className="text-xs font-semibold text-orange-50">{kindLabel(active.kind)}</div>
<div className="truncate text-[11px] text-orange-100/70">
{STATUS_ZH[active.status || ""] || active.status} · {active.progress_message || ""}
</div>
<div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-black/40">
<div
className="h-full rounded-full bg-gradient-to-r from-orange-400 to-rose-400 transition-all"
style={{ width: `${pct}%` }}
/>
</div>
</div>
<button
type="button"
className="inline-flex items-center gap-1 rounded-lg border border-white/15 px-2.5 py-1.5 text-[11px] text-slate-100"
onClick={() => void cancelJob(active.id)}
>
<Square className="h-3 w-3" /> 停止
</button>
</div>
) : null}
</div>
<div className="grid gap-4 xl:grid-cols-[200px_minmax(0,1fr)_320px]">
{/* left nav */}
<aside className="rounded-3xl border border-white/10 bg-black/25 p-3">
<div className="mb-2 px-2 text-[10px] uppercase tracking-[0.16em] text-slate-500">导航</div>
<nav className="space-y-1">
{NAV.map((item) => (
<button
key={item.id}
type="button"
onClick={() => setTab(item.id)}
className={
"flex w-full items-center gap-2 rounded-xl px-3 py-2.5 text-left text-sm transition " +
(tab === item.id
? "bg-gradient-to-r from-orange-400/20 to-transparent text-white ring-1 ring-orange-400/30"
: "text-slate-400 hover:bg-white/5 hover:text-slate-200")
}
>
<span className="text-base">{item.emoji}</span>
<span className="font-medium">{item.label}</span>
</button>
))}
</nav>
<div className="mt-4 border-t border-white/5 pt-3 px-2 text-[11px] text-slate-500">
<div>Agent {agents.filter((a) => a.online).length}/{agents.length}</div>
<div className="mt-1">账号 {accounts.length}</div>
</div>
</aside>
{/* main */}
<main className="min-w-0">
<div className="mb-3">
<div className="text-[11px] text-slate-500">X Ops / {crumb?.label}</div>
<h3 className="font-display text-xl text-white">{crumb?.emoji} {crumb?.label}</h3>
</div>
{tab === "workbench" ? (
<WorkbenchPanel
{...common}
extOnline={extOnline}
accountsN={accounts.length}
stats={stats}
onGo={(id) => setTab(id as TabId)}
lastKind={lastJob?.kind}
likeN={likeN}
rerun={() => {
if (!lastJob) return toast.push("没有上次任务", "err");
void createJob(lastJob.kind, lastJob.params);
}}
/>
) : null}
{tab === "cleanup" ? (
<CleanupPanel
{...common}
cleanupList={cleanupList}
setCleanupList={setCleanupList}
lastNonFollowers={lastNonFollowers}
/>
) : null}
{tab === "scrape" ? <ScrapePanel {...common} /> : null}
{tab === "engage" ? (
<EngagePanel {...common} likeN={likeN} setLikeN={setLikeN} followN={followN} setFollowN={setFollowN} />
) : null}
{tab === "monitor" ? <MonitorPanel {...common} /> : null}
{tab === "jobs" ? (
<div className="rounded-2xl border border-white/10 bg-black/25 p-4 text-sm text-slate-400">
任务流与结果请看右侧面板。也可在清理页一键填入扫描名单。
</div>
) : null}
</main>
{/* right sidepane */}
<aside className="flex min-h-[520px] flex-col rounded-3xl border border-white/10 bg-black/30">
<div className="flex items-center justify-between border-b border-white/5 px-4 py-3">
<h3 className="text-sm font-semibold text-white">活动流</h3>
<span className="rounded-full bg-white/5 px-2 py-0.5 text-[10px] text-slate-400">{jobs.length}</span>
</div>
<div className="flex gap-1 border-b border-white/5 px-3 py-2">
{(
[
["scrape.profile", "画像"],
["scrape.following", "关注"],
["scrape.followers", "粉丝"],
["scrape.tweets", "推文"],
["scrape.home", "首页"],
["scrape.notifications", "通知"],
["scrape.bookmarks", "书签"],
["all", "全部"],
["active", "进行"],
["completed", "完成"],
["failed", "失败"],
] as const
).map(([kind, label]) => (
).map(([id, label]) => (
<button
key={kind}
key={id}
type="button"
className={btnPrimary}
onClick={() => void createJob(kind, { limit })}
onClick={() => setFeedFilter(id)}
className={
"rounded-lg px-2 py-1 text-[11px] " +
(feedFilter === id ? "bg-white/15 text-white" : "text-slate-500 hover:bg-white/5")
}
>
{label}
</button>
))}
<button
type="button"
className={btnGhost}
onClick={() => {
if (!query.trim()) return toast.push("先填搜索词", "err");
void createJob("scrape.search", { query: query.trim(), limit });
}}
>
搜索推文
</button>
</div>
</section>
) : null}
{tab === "engage" ? (
<section className={panel}>
<h3 className="text-sm font-medium text-slate-100">互动</h3>
<div className="mt-3 flex flex-wrap gap-2">
<label className="text-xs text-slate-400">
点赞数
<input
type="number"
className={field}
style={{ width: 90 }}
value={likeN}
onChange={(e) => setLikeN(Number(e.target.value))}
/>
</label>
<label className="text-xs text-slate-400">
关注数
<input
type="number"
className={field}
style={{ width: 90 }}
value={followN}
onChange={(e) => setFollowN(Number(e.target.value))}
/>
</label>
<button
type="button"
className={btnPrimary}
onClick={() => void createJob("engage.like", { limit: likeN })}
>
点赞
</button>
<button
type="button"
className={btnPrimary}
onClick={() => void createJob("engage.follow", { limit: followN })}
>
关注
</button>
</div>
<label className="mt-3 block text-xs text-slate-400">
发帖
<textarea
className={`${field} min-h-[72px]`}
value={postText}
onChange={(e) => setPostText(e.target.value)}
/>
</label>
<button
type="button"
className={`${btnPrimary} mt-2`}
onClick={() => {
if (!postText.trim()) return toast.push("内容为空", "err");
void createJob("engage.post", { text: postText.trim() });
}}
>
发帖
</button>
<label className="mt-3 block text-xs text-slate-400">
推文链接
<input className={field} value={statusUrl} onChange={(e) => setStatusUrl(e.target.value)} />
</label>
<label className="mt-2 block text-xs text-slate-400">
回复内容
<input className={field} value={replyText} onChange={(e) => setReplyText(e.target.value)} />
</label>
<div className="mt-2 flex gap-2">
<button
type="button"
className={btnPrimary}
onClick={() => {
if (!statusUrl.trim() || !replyText.trim()) return toast.push("链接和回复都要填", "err");
void createJob("engage.reply", {
statusUrl: statusUrl.trim(),
text: replyText.trim(),
});
}}
>
回复
</button>
<button
type="button"
className={btnGhost}
onClick={() => {
if (!statusUrl.trim()) return toast.push("先填链接", "err");
void createJob("engage.retweet", { statusUrl: statusUrl.trim() });
}}
>
转推
</button>
</div>
</section>
) : null}
{tab === "jobs" || selected ? (
<div className={`grid gap-4 lg:grid-cols-2 ${tab === "jobs" ? "" : "mt-4"}`}>
{(tab === "jobs" || true) && tab === "jobs" ? (
<section className={panel}>
<h3 className="mb-2 text-sm font-medium text-slate-100">任务队列</h3>
<div className="max-h-[420px] space-y-2 overflow-auto">
{jobs.length === 0 ? (
<p className="text-xs text-slate-500">暂无任务</p>
) : (
jobs.map((j) => (
<button
key={j.id}
type="button"
onClick={() => setSelectedId(j.id)}
className={
"flex w-full items-start justify-between gap-2 rounded-lg border px-3 py-2 text-left text-xs " +
(selected?.id === j.id
? "border-cyan-500/40 bg-cyan-500/10"
: "border-white/10 bg-black/20")
}
<div className="max-h-[240px] flex-1 space-y-1 overflow-auto p-2">
{filteredJobs.length === 0 ? (
<div className="px-2 py-6 text-center text-[11px] text-slate-500">还没有操作记录</div>
) : (
filteredJobs.map((j) => (
<button
key={j.id}
type="button"
onClick={() => setSelectedId(j.id)}
className={
"flex w-full items-start justify-between gap-2 rounded-xl border px-2.5 py-2 text-left transition " +
(selected?.id === j.id
? "border-orange-400/35 bg-orange-500/10"
: "border-transparent hover:bg-white/5")
}
>
<div className="min-w-0">
<div className="truncate text-xs font-medium text-slate-100">{kindLabel(j.kind)}</div>
<div className="truncate text-[10px] text-slate-500">
{STATUS_ZH[j.status || ""] || j.status}
{j.progress_message ? ` · ${j.progress_message}` : ""}
</div>
</div>
{(j.status === "running" || j.status === "queued") && (
<span
role="button"
className="shrink-0 text-[10px] text-rose-300"
onClick={(e) => {
e.stopPropagation();
void cancelJob(j.id);
}}
>
<div>
<div className="text-slate-100">{kindLabel(j.kind)}</div>
<div className="text-slate-500">
{STATUS_ZH[j.status || ""] || j.status} · {j.progress_message || ""}
</div>
</div>
{(j.status === "running" || j.status === "queued") && (
<span
role="button"
className="inline-flex items-center gap-1 text-rose-300"
onClick={(e) => {
e.stopPropagation();
void cancelJob(j.id);
}}
>
<Square className="h-3 w-3" /> 取消
</span>
)}
</button>
))
)}
</div>
</section>
) : null}
{tab === "jobs" ? (
<section className={panel}>
<h3 className="text-sm font-medium text-slate-100">结果</h3>
{!selected ? (
<p className="mt-2 text-xs text-slate-500">点选左侧任务</p>
) : (
<pre className="mt-2 max-h-[420px] overflow-auto whitespace-pre-wrap break-words rounded-lg bg-black/40 p-3 font-mono text-[11px] text-slate-300">
{JSON.stringify(
{
id: selected.id,
kind: selected.kind,
status: selected.status,
error: selected.error,
progress: {
current: selected.progress_current,
total: selected.progress_total,
message: selected.progress_message,
},
result: selected.result,
},
null,
2,
停
</span>
)}
</button>
))
)}
</div>
<div className="flex items-center justify-between border-y border-white/5 px-4 py-2.5">
<h3 className="inline-flex items-center gap-1.5 text-sm font-semibold text-white">
<Activity className="h-3.5 w-3.5 text-orange-300" /> 看结果
</h3>
<div className="flex gap-1">
{selected && (selected.status === "running" || selected.status === "queued") ? (
<button
type="button"
className="rounded-lg border border-white/10 px-2 py-1 text-[10px] text-slate-300"
onClick={() => void cancelJob(selected.id)}
>
<Square className="mr-0.5 inline h-2.5 w-2.5" />
停止
</button>
) : null}
<button
type="button"
className="rounded-lg border border-white/10 px-2 py-1 text-[10px] text-slate-300"
onClick={() => {
if (!selected) return toast.push("先点一条任务", "err");
void navigator.clipboard.writeText(summarizeJob(selected)).then(() => toast.push("已复制", "ok"));
}}
>
<Copy className="mr-0.5 inline h-2.5 w-2.5" />
复制
</button>
</div>
</div>
<div className="min-h-[180px] flex-1 overflow-auto p-3">
{!selected ? (
<div className="text-[11px] text-slate-500">点上面开始一项操作,这里会用大白话告诉你结果</div>
) : (
<>
<div
className={
"text-xs font-semibold " +
(selected.status === "completed"
? "text-emerald-300"
: selected.status === "failed" || selected.status === "cancelled"
? "text-rose-300"
: "text-orange-200")
}
>
{kindLabel(selected.kind)} · {STATUS_ZH[selected.status || ""] || selected.status}
</div>
<pre className="mt-2 whitespace-pre-wrap break-words font-sans text-[11px] leading-relaxed text-slate-300">
{summarizeJob(selected)}
</pre>
)}
</section>
) : null}
</div>
) : null}
{selected.kind === "cleanup.non_followers" && selected.status === "completed" ? (
<button
type="button"
className="mt-3 rounded-xl border border-orange-400/30 bg-orange-500/10 px-3 py-2 text-[11px] text-orange-100"
onClick={() => {
const list = nonFollowersFromJob(selected);
setCleanupList(list.join("\n"));
setTab("cleanup");
toast.push(`已填入 ${list.length} 人到取关名单`, "ok");
}}
>
填入清理名单并打开清理页
</button>
) : null}
{selected.received_at ? (
<div className="mt-3 text-[10px] text-slate-600">{fmtTs(selected.received_at)}</div>
) : null}
</>
)}
</div>
</aside>
</div>
</Shell>
);
}

198
frontend/src/lib/xOps.ts Normal file
View File

@ -0,0 +1,198 @@
/** Shared helpers for Web X Ops console (aligned with X2 popup/Electron). */
export type XJob = {
id: string;
kind?: string;
status?: string;
account_username?: string;
progress_current?: number;
progress_total?: number;
progress_message?: string;
error?: string;
received_at?: number;
job_updated_at?: string;
result?: Record<string, unknown>;
params?: Record<string, unknown>;
result_json?: string;
};
export const STATUS_ZH: Record<string, string> = {
queued: "排队中",
running: "进行中",
completed: "已完成",
failed: "出错了",
cancelled: "已取消",
paused: "已暂停",
};
export const KIND_LABEL: Record<string, string> = {
"cleanup.non_followers": "不互关扫描",
"cleanup.unfollow": "限速取关",
"cleanup.unfollow_visible": "可见取关",
"cleanup.mute": "批量静音",
"cleanup.unmute": "取消静音",
"cleanup.block": "批量屏蔽",
"cleanup.unblock": "取消屏蔽",
"scrape.profile": "锁定画像",
"scrape.following": "抓取 Following",
"scrape.followers": "抓取 Followers",
"scrape.tweets": "抽取推文",
"scrape.search": "搜索推文",
"scrape.bookmarks": "导出书签",
"scrape.media": "提取媒体",
"scrape.likers": "点赞用户",
"scrape.thread": "推文串",
"scrape.likes": "点赞时间线",
"scrape.list": "列表成员",
"scrape.hashtag": "话题标签",
"scrape.people": "搜人",
"scrape.notifications": "通知",
"scrape.home": "首页时间线",
"scrape.mentions": "提及",
"scrape.with_replies": "含回复",
"scrape.retweeters": "转推用户",
"scrape.quotes": "引用用户",
"engage.like": "点赞",
"engage.unlike": "取消点赞",
"engage.follow": "关注",
"engage.post": "发帖",
"engage.reply": "回复",
"engage.retweet": "转推",
"engage.quote": "引用",
"engage.bookmark": "收藏",
"engage.copy_link": "复制链接",
"growth.engage": "关键词增长",
"growth.home": "首页互动",
"monitor.snapshot_followers": "粉丝快照",
"monitor.snapshot_following": "关注快照",
"analyze.profiles": "对比画像",
"analyze.tweets": "推文表现",
"content.tech_news": "科技新闻",
};
export function kindLabel(kind?: string) {
return (kind && KIND_LABEL[kind]) || kind || "任务";
}
export function parseHandles(raw: string) {
return raw
.split(/[\n,,\s]+/)
.map((s) => s.replace(/^@/, "").trim())
.filter(Boolean);
}
export function estimateEta(n: number, minMs = 2000, maxMs = 5000) {
if (!n) return "—";
const avg = (minMs + maxMs) / 2;
const sec = Math.round((n * avg) / 1000);
if (sec < 60) return `约 ${sec} 秒`;
return `约 ${Math.round(sec / 60)} 分钟`;
}
export function jobResult(job: XJob): Record<string, unknown> {
if (job.result && typeof job.result === "object") return job.result;
if (job.result_json) {
try {
return JSON.parse(job.result_json) as Record<string, unknown>;
} catch {
return {};
}
}
return {};
}
export function summarizeJob(job: XJob): string {
const name = kindLabel(job.kind);
if (job.status === "failed") return `${name}没做成\n原因:${job.error || "未知错误"}`;
if (job.status === "cancelled") return `${name}已取消`;
if (job.status !== "completed") {
const msg = job.progress_message || STATUS_ZH[job.status || ""] || "进行中";
if ((job.progress_total || 0) > 1) {
return `${msg}(${job.progress_current || 0}/${job.progress_total})`;
}
return msg;
}
const r = jobResult(job);
const kind = job.kind || "";
if (kind === "cleanup.non_followers") {
const non = (r.nonFollowers as Array<{ username: string }>) || [];
return (
`扫描完成:有 ${non.length} 人没回关你\n(关注 ${r.followingCount},粉丝 ${r.followersCount})\n` +
non
.slice(0, 60)
.map((u) => `@${u.username}`)
.join("\n") +
(non.length > 60 ? `\n…还有 ${non.length - 60} 人` : "")
);
}
if (kind === "scrape.profile") {
return `${r.name || r.username}(@${r.username})\n粉丝 ${r.followersCount} · 关注 ${r.followingCount}\n${r.bio || "暂无简介"}`;
}
if (kind === "scrape.following" || kind === "scrape.followers" || kind === "scrape.people" || kind === "scrape.likers" || kind === "scrape.retweeters" || kind === "scrape.quotes" || kind === "scrape.list") {
const users = (r.users as Array<{ username: string }>) || [];
return `抓到 ${users.length} 人\n` + users.slice(0, 80).map((u) => `@${u.username}`).join("\n");
}
if (kind.startsWith("scrape.") || kind === "analyze.tweets") {
const tweets = (r.tweets as Array<{ text?: string }>) || [];
if (tweets.length) {
return (
`${name}:${tweets.length} 条\n` +
tweets
.slice(0, 25)
.map((t) => t.text || "")
.join("\n——\n")
);
}
}
if (kind === "cleanup.unfollow" || kind === "cleanup.unfollow_visible") {
const u = (r.unfollowed as string[]) || [];
return `取关完成:成功 ${u.length}\n` + u.map((x) => `@${x}`).join("\n");
}
if (kind === "engage.like") return `点赞完成:${r.liked ?? 0}`;
if (kind === "engage.unlike") return `取消点赞:${r.unliked ?? 0}`;
if (kind === "engage.follow") return `关注完成:${r.followed ?? 0}`;
if (kind === "engage.post" || kind === "engage.reply" || kind === "engage.quote") {
return `${name}成功\n\n${r.text || job.params?.text || ""}`;
}
if (kind === "monitor.snapshot_followers" || kind === "monitor.snapshot_following") {
const n = ((r.usernames as string[]) || []).length;
const diff = r.diff as { gained?: string[]; lost?: string[]; newlyFollowed?: string[]; unfollowed?: string[] } | undefined;
if (!diff) return `已记下 ${n} 人,下次再拍就能对比`;
return `新粉/新关 ${diff.gained?.length || diff.newlyFollowed?.length || 0} · 掉粉/取关 ${diff.lost?.length || diff.unfollowed?.length || 0}`;
}
if (kind === "growth.engage" || kind === "growth.home") {
return `${name}:赞 ${r.liked ?? 0} · 关 ${r.followed ?? 0} · 回 ${r.replied ?? 0}`;
}
try {
return JSON.stringify(r, null, 2).slice(0, 4000);
} catch {
return `${name}已完成`;
}
}
export function nonFollowersFromJob(job: XJob | null): string[] {
if (!job || job.kind !== "cleanup.non_followers" || job.status !== "completed") return [];
const r = jobResult(job);
return ((r.nonFollowers as Array<{ username: string }>) || []).map((u) => u.username);
}
export function buildAdvancedSearch(opts: {
keywords: string;
from?: string;
since?: string;
until?: string;
minFaves?: number;
onlyMedia?: boolean;
filterReplies?: boolean;
}) {
const parts: string[] = [];
if (opts.keywords.trim()) parts.push(opts.keywords.trim());
if (opts.from?.trim()) parts.push(`from:${opts.from.trim().replace(/^@/, "")}`);
if (opts.since) parts.push(`since:${opts.since}`);
if (opts.until) parts.push(`until:${opts.until}`);
if (opts.minFaves) parts.push(`min_faves:${opts.minFaves}`);
if (opts.onlyMedia) parts.push("filter:media");
if (opts.filterReplies) parts.push("-filter:replies");
return parts.join(" ").trim();
}