fix(test1): X 活动流展示账号/文案/媒体,去掉「做完了」废话

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-16 01:01:37 -05:00
parent 04dc572df7
commit 7b3c926bfb
3 changed files with 207 additions and 49 deletions

View File

@ -483,7 +483,7 @@ def list_events(*, limit: int = 30) -> list[dict[str, Any]]:
def status_snapshot() -> dict[str, Any]:
agents = list_agents()
online = [a for a in agents if a.get("online")]
jobs = list_jobs(limit=30)
jobs = list_jobs(limit=80)
accounts = list_accounts(limit=30)
events = list_events(limit=20)
running = sum(1 for j in jobs if str(j.get("status") or "") == "running")

View File

@ -17,6 +17,9 @@ import {
STATUS_ZH,
summarizeJob,
jobMatchesAccount,
normalizeXJob,
feedPreview,
progressLabel,
type XJob,
} from "@/lib/xOps";
import {
@ -99,10 +102,9 @@ export default function XPage() {
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,
}));
const nextJobs: XJob[] = (st?.jobs || []).map((j: XJob & Record<string, unknown>) =>
normalizeXJob(j),
);
setJobs(nextJobs);
setStats(st?.stats || {});
setExtOnline(Boolean(st?.extension_online));
@ -156,7 +158,7 @@ export default function XPage() {
body: JSON.stringify({ kind, params: merged }),
});
if (r?.job) {
setJobs((prev) => [r.job, ...prev.filter((j) => j.id !== r.job.id)]);
setJobs((prev) => [normalizeXJob(r.job), ...prev.filter((j) => j.id !== r.job.id)]);
setSelectedId(r.job.id);
toast.push(`🚀 ${kindLabel(kind)} 已下发`, "ok");
} else {
@ -173,7 +175,7 @@ export default function XPage() {
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)]);
setJobs((prev) => [normalizeXJob(r.job), ...prev.filter((j) => j.id !== r.job.id)]);
toast.push("已请求取消", "ok");
}
} catch (e: unknown) {
@ -331,7 +333,8 @@ export default function XPage() {
<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 || ""}
{progressLabel(active)}
{active.account_username ? ` · @${String(active.account_username).replace(/^@/, "")}` : ""}
</div>
<div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-black/40">
<div
@ -431,8 +434,8 @@ export default function XPage() {
<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">
{filteredJobs.length}
{username ? ` · @${username}` : ""}
{filteredJobs.length}/{accountJobs.length}
{username ? ` · @${username}` : " · 全部账号"}
</span>
</div>
<div className="flex gap-1 border-b border-white/5 px-3 py-2">
@ -457,43 +460,49 @@ export default function XPage() {
</button>
))}
</div>
<div className="max-h-[240px] flex-1 space-y-1 overflow-auto p-2">
<div className="max-h-[320px] 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}` : ""}
filteredJobs.map((j) => {
const prev = feedPreview(j);
return (
<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 flex-1">
<div className="truncate text-xs font-medium text-slate-100">{prev.headline}</div>
<div className="mt-0.5 line-clamp-2 text-[10px] leading-relaxed text-slate-400">
{prev.detail}
</div>
<div className="mt-0.5 text-[9px] text-slate-600">
{j.received_at ? fmtTs(j.received_at) : j.updatedAt || j.createdAt || ""}
{j.id ? ` · ${j.id.slice(0, 8)}` : ""}
</div>
</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);
}}
>
停
</span>
)}
</button>
))
{(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);
}}
>
停
</span>
)}
</button>
);
})
)}
</div>
@ -540,7 +549,14 @@ export default function XPage() {
: "text-orange-200")
}
>
{kindLabel(selected.kind)} · {STATUS_ZH[selected.status || ""] || selected.status}
{feedPreview(selected).headline}
</div>
<div className="mt-1 text-[10px] text-slate-500">
{STATUS_ZH[selected.status || ""] || selected.status}
{selected.account_username
? ` · @${String(selected.account_username).replace(/^@/, "")}`
: ""}
{selected.id ? ` · id ${selected.id.slice(0, 10)}` : ""}
</div>
<pre className="mt-2 whitespace-pre-wrap break-words font-sans text-[11px] leading-relaxed text-slate-300">
{summarizeJob(selected)}

View File

@ -9,14 +9,133 @@ export type XJob = {
progress_current?: number;
progress_total?: number;
progress_message?: string;
progress?: { current?: number; total?: number; message?: string };
error?: string;
received_at?: number;
job_updated_at?: string;
job_created_at?: string;
createdAt?: string;
updatedAt?: string;
result?: Record<string, unknown>;
params?: Record<string, unknown>;
result_json?: string;
params_json?: string;
};
/** Extension often sends useless "做完了" — hide from humans. */
const NOISE_PROGRESS = /^(做完了|失败|排队中|启动中…?|启动中|Web 任务领取)$/i;
export function normalizeXJob(raw: XJob & Record<string, unknown>): XJob {
const progress =
raw.progress && typeof raw.progress === "object"
? (raw.progress as { current?: number; total?: number; message?: string })
: undefined;
let params = raw.params && typeof raw.params === "object" ? raw.params : undefined;
if (!params && raw.params_json) {
try {
params = JSON.parse(String(raw.params_json)) as Record<string, unknown>;
} catch {
params = {};
}
}
let result = raw.result && typeof raw.result === "object" ? raw.result : undefined;
if (!result && raw.result_json) {
try {
result = JSON.parse(String(raw.result_json)) as Record<string, unknown>;
} catch {
result = {};
}
}
return {
...raw,
params: params || {},
result: result || {},
progress_current: Number(raw.progress_current ?? progress?.current ?? 0),
progress_total: Number(raw.progress_total ?? progress?.total ?? 0),
progress_message: String(raw.progress_message || progress?.message || ""),
};
}
export function progressLabel(job: XJob): string {
const msg = String(job.progress_message || "").trim();
if (msg && !NOISE_PROGRESS.test(msg)) return msg;
return STATUS_ZH[job.status || ""] || job.status || "";
}
function mediaCountOf(job: XJob): number {
const r = jobResult(job);
const params = job.params && typeof job.params === "object" ? job.params : {};
const fromResult = Number(r.mediaCount ?? 0);
if (fromResult > 0) return fromResult;
const urls = Array.isArray(params.mediaUrls) ? params.mediaUrls.length : 0;
const media = Array.isArray(params.media) ? params.media.length : 0;
const keys = Array.isArray(r.mediaKeys) ? (r.mediaKeys as unknown[]).length : 0;
return urls || media || keys || 0;
}
function postTextOf(job: XJob): string {
const r = jobResult(job);
const params = job.params && typeof job.params === "object" ? job.params : {};
return String(r.text || r.composerSnapshot || params.text || "").trim();
}
/** One-line / two-line preview for activity feed (human readable). */
export function feedPreview(job: XJob): { headline: string; detail: string } {
const kind = job.kind || "";
const name = kindLabel(kind);
const acct = jobAccountHandle(job);
const acctBit = acct ? `@${acct}` : "";
const st = progressLabel(job);
const r = jobResult(job);
const params = job.params && typeof job.params === "object" ? job.params : {};
if (job.status === "failed" || job.status === "cancelled") {
const err = String(job.error || "未知原因").replace(/\s+/g, " ").slice(0, 80);
return {
headline: `${name}${acctBit ? ` · ${acctBit}` : ""}`,
detail: `${STATUS_ZH[job.status] || job.status} · ${err}`,
};
}
if (kind === "engage.post" || kind === "engage.reply" || kind === "engage.quote") {
const text = postTextOf(job).replace(/\s+/g, " ");
const nMedia = mediaCountOf(job);
const mediaBit = nMedia > 0 ? ` · 媒体×${nMedia}` : "";
const snippet = text ? `「${text.slice(0, 56)}${text.length > 56 ? "…" : ""}」` : "(无正文记录)";
return {
headline: `${name}${acctBit ? ` · ${acctBit}` : ""}${mediaBit}`,
detail: `${st} · ${snippet}`,
};
}
if (kind === "engage.like" || kind === "engage.unlike" || kind === "engage.follow") {
const n =
kind === "engage.like"
? r.liked
: kind === "engage.unlike"
? r.unliked
: r.followed;
return {
headline: `${name}${acctBit ? ` · ${acctBit}` : ""}`,
detail: job.status === "completed" ? `${st} · 数量 ${n ?? 0}` : st,
};
}
if (kind.startsWith("scrape.") || kind.startsWith("cleanup.") || kind.startsWith("monitor.")) {
const tip = summarizeJob(job).split("\n")[0] || st;
return {
headline: `${name}${acctBit ? ` · ${acctBit}` : ""}`,
detail: tip.slice(0, 90),
};
}
const q = String(params.query || params.username || params.statusUrl || "").trim();
return {
headline: `${name}${acctBit ? ` · ${acctBit}` : ""}`,
detail: q ? `${st} · ${q.slice(0, 60)}` : st,
};
}
export const STATUS_ZH: Record<string, string> = {
queued: "排队中",
running: "进行中",
@ -133,7 +252,7 @@ export function summarizeJob(job: XJob): string {
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 || ""] || "进行中";
const msg = progressLabel(job);
if ((job.progress_total || 0) > 1) {
return `${msg}(${job.progress_current || 0}/${job.progress_total})`;
}
@ -141,6 +260,7 @@ export function summarizeJob(job: XJob): string {
}
const r = jobResult(job);
const kind = job.kind || "";
const params = job.params && typeof job.params === "object" ? job.params : {};
if (kind === "cleanup.non_followers") {
const non = (r.nonFollowers as Array<{ username: string }>) || [];
@ -176,11 +296,33 @@ export function summarizeJob(job: XJob): string {
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.like") return `点赞完成:${r.liked ?? 0}${r.requested != null ? `(目标 ${r.requested})` : ""}`;
if (kind === "engage.unlike") return `取消点赞:${r.unliked ?? 0}${r.requested != null ? `(目标 ${r.requested})` : ""}`;
if (kind === "engage.follow") {
const users = (r.users as string[]) || [];
return (
`关注完成:${r.followed ?? users.length ?? 0}${r.requested != null ? `(目标 ${r.requested})` : ""}` +
(users.length ? `\n` + users.slice(0, 40).map((u) => `@${u}`).join("\n") : "")
);
}
if (kind === "engage.post" || kind === "engage.reply" || kind === "engage.quote") {
return `${name}成功\n\n${r.text || job.params?.text || ""}`;
const text = postTextOf(job);
const acct = jobAccountHandle(job);
const nMedia = mediaCountOf(job);
const tip =
kind === "engage.post" ? "发帖成功" : kind === "engage.reply" ? "回复成功" : "引用成功";
const lines = [tip];
if (acct) lines.push(`账号:@${acct}`);
if (nMedia > 0) lines.push(`媒体:${nMedia} 个附件`);
const clipId = String(params.xClipJobId || "").trim();
if (clipId) lines.push(`切片任务:${clipId.slice(0, 8)}…`);
const url = String(r.url || r.statusUrl || params.statusUrl || "").trim();
if (url) lines.push(`链接:${url}`);
const when = String(r.postedAt || r.finishedAt || "").trim();
if (when) lines.push(`时间:${when}`);
lines.push("");
lines.push(text || "(没有正文记录 — 请检查发帖参数)");
return lines.join("\n");
}
if (kind === "monitor.snapshot_followers" || kind === "monitor.snapshot_following") {
const n = ((r.usernames as string[]) || []).length;