feat(test1): X 按账号隔离展示任务与切片数据

切换顶部账号后,任务流/结果/统计与切片列表按该账号过滤;新建任务写入 account。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-15 08:29:17 -05:00
parent 4d85eb6f8d
commit b0706b351b
8 changed files with 192 additions and 33 deletions

View File

@ -494,6 +494,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"x_clips_delete_clip_after_post": True,
"x_clips_daily_max": 20,
"x_clips_caption_template": "{anchor}",
"x_clips_account_username": "",
"tiktok_auto_retry_failed": False,
"tiktok_auto_retry_max_attempts": 3,
"tiktok_auto_retry_interval_sec": 300,

View File

@ -1005,6 +1005,8 @@ async def x_clips_settings_update(body: dict[str, Any] | None = None) -> dict[st
raise HTTPException(400, "daily_max 无效") from None
if "x_clips_caption_template" in raw:
patch["x_clips_caption_template"] = str(raw.get("x_clips_caption_template") or "").strip()[:200] or "{anchor}"
if "x_clips_account_username" in raw:
patch["x_clips_account_username"] = str(raw.get("x_clips_account_username") or "").strip().lstrip("@")[:80]
if "x_clips_trigger" in raw:
t = str(raw.get("x_clips_trigger") or "tagged").strip().lower()
if t not in {"tagged", "all", "favorite"}:
@ -1083,6 +1085,7 @@ async def x_clips_jobs_list(
push_date: str = "",
session_id: str = "",
room_id: str = "",
account_username: str = "",
limit: int = Query(50, ge=1, le=500),
offset: int = Query(0, ge=0),
) -> dict[str, Any]:
@ -1094,6 +1097,7 @@ async def x_clips_jobs_list(
push_date=push_date,
session_id=session_id,
room_id=room_id,
account_username=account_username,
limit=limit,
offset=offset,
)

View File

@ -203,16 +203,24 @@ def upsert_job(agent_id: str, job: dict[str, Any]) -> dict[str, Any] | None:
result = job.get("result")
account_username = ""
if isinstance(result, dict):
account_username = str(result.get("account") or "").strip()
account_username = str(result.get("account") or result.get("username") or "").strip().lstrip("@")
incoming_params = job.get("params") if isinstance(job.get("params"), dict) else {}
if not account_username:
account_username = str(incoming_params.get("username") or "").strip().lstrip("@")
if not account_username:
account_username = str(job.get("account_username") or job.get("accountUsername") or "").strip().lstrip("@")
account_id = str(job.get("accountId") or job.get("account_id") or "").strip()
if not account_id and account_username:
account_id = f"x:{account_username}"
now = time.time()
with _lock:
conn = _connect()
try:
ensure_x2_tables(conn)
existing = conn.execute("SELECT params_json FROM x2_jobs WHERE id = ?", (jid,)).fetchone()
existing = conn.execute(
"SELECT params_json, account_username, account_id FROM x2_jobs WHERE id = ?",
(jid,),
).fetchone()
params_to_store = incoming_params
if not params_to_store and existing:
try:
@ -221,6 +229,13 @@ def upsert_job(agent_id: str, job: dict[str, Any]) -> dict[str, Any] | None:
params_to_store = {}
if not isinstance(params_to_store, dict):
params_to_store = {}
# Never wipe account attribution on partial updates from extension
if existing and not account_username:
account_username = str(existing["account_username"] or "").strip().lstrip("@")
if existing and not account_id:
account_id = str(existing["account_id"] or "").strip()
if not account_id and account_username:
account_id = f"x:{account_username}"
conn.execute(
"""
INSERT INTO x2_jobs(
@ -232,8 +247,14 @@ def upsert_job(agent_id: str, job: dict[str, Any]) -> dict[str, Any] | None:
agent_id=excluded.agent_id,
kind=excluded.kind,
status=excluded.status,
account_id=excluded.account_id,
account_username=excluded.account_username,
account_id=CASE
WHEN excluded.account_id != '' THEN excluded.account_id
ELSE x2_jobs.account_id
END,
account_username=CASE
WHEN excluded.account_username != '' THEN excluded.account_username
ELSE x2_jobs.account_username
END,
progress_current=excluded.progress_current,
progress_total=excluded.progress_total,
progress_message=excluded.progress_message,
@ -249,7 +270,7 @@ def upsert_job(agent_id: str, job: dict[str, Any]) -> dict[str, Any] | None:
aid,
str(job.get("kind") or ""),
str(job.get("status") or ""),
str(job.get("accountId") or job.get("account_id") or ""),
account_id,
account_username,
int(progress.get("current") or 0),
int(progress.get("total") or 0),
@ -557,19 +578,23 @@ def create_web_job(
k = str(kind or "").strip()
if not k:
raise ValueError("缺少 kind")
p = dict(params or {})
account_username = str(p.get("username") or "").strip().lstrip("@")
jid = f"web_{uuid.uuid4().hex[:16]}"
now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
job = {
"id": jid,
"kind": k,
"status": "queued",
"params": params or {},
"params": p,
"account_username": account_username,
"accountId": f"x:{account_username}" if account_username else "",
"progress": {"current": 0, "total": 1, "message": "排队等待插件领取"},
"createdAt": now_iso,
"updatedAt": now_iso,
}
row = upsert_job(str(agent_id or "").strip() or "web", job)
add_event(str(agent_id or "web"), "job.queued", f"{k} 已入队", {"job_id": jid})
add_event(str(agent_id or "web"), "job.queued", f"{k} 已入队", {"job_id": jid, "account": account_username})
return _job_to_client(row or job)

View File

@ -35,6 +35,7 @@ def ensure_x_clips_tables(conn: sqlite3.Connection) -> None:
media_url TEXT NOT NULL DEFAULT '',
x2_job_id TEXT NOT NULL DEFAULT '',
tweet_id TEXT NOT NULL DEFAULT '',
account_username TEXT NOT NULL DEFAULT '',
error TEXT NOT NULL DEFAULT '',
push_date TEXT NOT NULL DEFAULT '',
upload_at REAL NOT NULL DEFAULT 0,
@ -46,6 +47,9 @@ def ensure_x_clips_tables(conn: sqlite3.Connection) -> None:
)
"""
)
cols = {r[1] for r in conn.execute("PRAGMA table_info(x_clip_jobs)").fetchall()}
if "account_username" not in cols:
conn.execute("ALTER TABLE x_clip_jobs ADD COLUMN account_username TEXT NOT NULL DEFAULT ''")
conn.execute("CREATE INDEX IF NOT EXISTS idx_x_clip_jobs_status ON x_clip_jobs(status, created_at)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_x_clip_jobs_date ON x_clip_jobs(push_date, status)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_x_clip_jobs_room_day ON x_clip_jobs(room_id, push_date, status)")
@ -118,11 +122,13 @@ def create_x_clip_job(
anchor_name: str = "",
stream_url: str = "",
push_date: str = "",
account_username: str = "",
) -> dict[str, Any] | None:
now = time.time()
jid = str(uuid.uuid4())
day = push_date or push_date_from_ts(now)
rid = str(room_id or "").strip()
acct = str(account_username or "").strip().lstrip("@")
with _lock:
conn = _connect()
try:
@ -144,9 +150,9 @@ def create_x_clip_job(
INSERT INTO x_clip_jobs(
id, session_id, room_pk, room_id, source_url, anchor_name, stream_url,
status, clip_path, clip_seconds, caption, media_key, media_url, x2_job_id,
tweet_id, error, push_date, upload_at, attempts,
tweet_id, account_username, error, push_date, upload_at, attempts,
created_at, updated_at, started_at, finished_at
) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', '', 0, '', '', '', '', '', '', ?, 0, 0, ?, ?, 0, 0)
) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', '', 0, '', '', '', '', '', ?, '', ?, 0, 0, ?, ?, 0, 0)
""",
(
jid,
@ -156,6 +162,7 @@ def create_x_clip_job(
source_url,
anchor_name,
stream_url,
acct,
day,
now,
now,
@ -177,6 +184,7 @@ def update_x_clip_job(job_id: str, **fields: Any) -> dict[str, Any] | None:
"media_url",
"x2_job_id",
"tweet_id",
"account_username",
"error",
"stream_url",
"attempts",
@ -226,6 +234,7 @@ def list_x_clip_jobs(
push_date: str = "",
session_id: str = "",
room_id: str = "",
account_username: str = "",
limit: int = 100,
offset: int = 0,
) -> dict[str, Any]:
@ -247,6 +256,10 @@ def list_x_clip_jobs(
if room_id.strip():
clauses.append("room_id = ?")
params.append(room_id.strip())
acct = account_username.strip().lstrip("@")
if acct:
clauses.append("LOWER(account_username) = LOWER(?)")
params.append(acct)
where = (" WHERE " + " AND ".join(clauses)) if clauses else ""
total = int(
conn.execute(f"SELECT COUNT(*) AS c FROM x_clip_jobs{where}", params).fetchone()["c"] or 0

View File

@ -95,6 +95,7 @@ def _enqueue_job(
if x_clips_db.has_x_clip_job_for_room_day(room_id, day):
return None
sid = str((session or {}).get("id") or room.get("active_session_id") or "")
acct = str(settings.get("x_clips_account_username") or "").strip().lstrip("@")
job = x_clips_db.create_x_clip_job(
session_id=sid,
room_pk=str(room.get("id") or (session or {}).get("room_pk") or ""),
@ -105,6 +106,7 @@ def _enqueue_job(
),
stream_url=str(stream_url or ""),
push_date=day,
account_username=acct,
)
if not job:
return None
@ -250,6 +252,7 @@ class XClipsPipeline:
"x_clips_tag": cfg.get("x_clips_tag") or "x",
"x_clips_daily_max": x_clips_db.x_clips_daily_max(cfg),
"x_clips_caption_template": cfg.get("x_clips_caption_template") or "{anchor}",
"x_clips_account_username": str(cfg.get("x_clips_account_username") or "").strip().lstrip("@"),
"x_clips_live_sample": bool(cfg.get("x_clips_live_sample", True)),
"x_clips_live_sample_interval_sec": int(cfg.get("x_clips_live_sample_interval_sec") or 180),
"x_clips_live_sample_batch": int(cfg.get("x_clips_live_sample_batch") or 1),
@ -490,6 +493,12 @@ class XClipsPipeline:
caption = build_caption(job, cfg)
if not caption:
raise ValueError("文案模板结果为空")
acct = (
str(job.get("account_username") or "").strip().lstrip("@")
or str(cfg.get("x_clips_account_username") or "").strip().lstrip("@")
)
if acct and str(job.get("account_username") or "").strip().lstrip("@") != acct:
x_clips_db.update_x_clip_job(jid, account_username=acct)
media_url = str(job.get("media_url") or "").strip()
media_key = str(job.get("media_key") or "").strip()
clip = str(job.get("clip_path") or "").strip()
@ -520,7 +529,12 @@ class XClipsPipeline:
x2_job = await asyncio.to_thread(
x2_db.create_web_job,
"engage.post",
{"text": caption, "mediaUrls": [media_item], "xClipJobId": jid},
{
"text": caption,
"mediaUrls": [media_item],
"xClipJobId": jid,
**({"username": acct} if acct else {}),
},
)
x2_id = str(x2_job.get("id") or "")
if not x2_id:

View File

@ -59,7 +59,13 @@ const STATUS_ZH: Record<string, string> = {
skipped: "已跳过",
};
export function ClipsPanel({ toast }: { toast: (msg: string, kind?: "ok" | "err") => void }) {
export function ClipsPanel({
toast,
accountUsername = "",
}: {
toast: (msg: string, kind?: "ok" | "err") => void;
accountUsername?: string;
}) {
const [st, setSt] = useState<Status | null>(null);
const [jobs, setJobs] = useState<XClipJob[]>([]);
const [busy, setBusy] = useState(false);
@ -73,9 +79,11 @@ export function ClipsPanel({ toast }: { toast: (msg: string, kind?: "ok" | "err"
const load = useCallback(async () => {
try {
const iso = todayBeijingISO();
const acct = (accountUsername || "").trim().replace(/^@/, "");
const q = acct ? `&account_username=${encodeURIComponent(acct)}` : "";
const [status, jobData] = await Promise.all([
fetchJson("/api/x-clips/status"),
fetchJson(`/api/x-clips/jobs?push_date=${iso}&limit=40`),
fetchJson(`/api/x-clips/jobs?push_date=${iso}&limit=40${q}`),
]);
setSt(status || null);
const s = status?.settings || {};
@ -89,7 +97,16 @@ export function ClipsPanel({ toast }: { toast: (msg: string, kind?: "ok" | "err"
} catch (e) {
toast((e as Error).message || "加载失败", "err");
}
}, [toast]);
}, [toast, accountUsername]);
// Bind clip pipeline to the account selected in the X header
useEffect(() => {
const acct = (accountUsername || "").trim().replace(/^@/, "");
void fetchJson("/api/x-clips/settings", {
method: "POST",
body: JSON.stringify({ x_clips_account_username: acct }),
}).catch(() => {});
}, [accountUsername]);
useEffect(() => {
void load();
@ -122,7 +139,10 @@ export function ClipsPanel({ toast }: { toast: (msg: string, kind?: "ok" | "err"
直播切片发帖
</h3>
<p className={sub}>
独立流水线:抖音在播取样 → 录 10–15 秒 → S3 → 插件文字+视频发帖。与 Shorts / TikTok 完全隔离。
独立流水线:抖音在播取样 → 录 10–15 秒 → S3 → 插件文字+视频发帖。
{accountUsername
? ` 当前账号 @${accountUsername.replace(/^@/, "")}(任务/发帖按账号隔离)`
: " 请先在顶部选择账号,否则任务不按账号隔离"}
</p>
</div>
<div className="flex flex-wrap gap-2">
@ -279,7 +299,7 @@ export function ClipsPanel({ toast }: { toast: (msg: string, kind?: "ok" | "err"
<div className={panel}>
<div className="mb-2 flex items-center justify-between">
<h3 className={title}>今日任务</h3>
<h3 className={title}>今日任务{accountUsername ? ` · @${accountUsername.replace(/^@/, "")}` : ""}</h3>
<span className="text-[10px] text-slate-500">{jobs.length} 条</span>
</div>
{jobs.length === 0 ? (

View File

@ -16,6 +16,7 @@ import {
nonFollowersFromJob,
STATUS_ZH,
summarizeJob,
jobMatchesAccount,
type XJob,
} from "@/lib/xOps";
import {
@ -66,6 +67,24 @@ export default function XPage() {
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) setUsername(saved);
} catch {
/* ignore */
}
}, []);
useEffect(() => {
try {
if (username) window.localStorage.setItem("x2_selected_account", username);
else window.localStorage.removeItem("x2_selected_account");
} catch {
/* ignore */
}
}, [username]);
const [limit, setLimit] = useState(80);
const [minD, setMinD] = useState(2000);
const [maxD, setMaxD] = useState(5000);
@ -90,8 +109,14 @@ export default function XPage() {
setExtOnline(Boolean(st?.extension_online));
const accs: X2Account[] = st?.accounts || [];
setUsername((cur) => {
if (cur) return cur;
return accs[0]?.username ? String(accs[0].username) : "";
if (cur && accs.some((a) => String(a.username || "") === cur)) return cur;
try {
const saved = window.localStorage.getItem("x2_selected_account") || "";
if (saved && accs.some((a) => String(a.username || "") === saved)) return saved;
} catch {
/* ignore */
}
return accs[0]?.username ? String(accs[0].username) : cur || "";
});
} catch (e: unknown) {
toast.push((e as Error)?.message || "加载失败", "err");
@ -111,8 +136,13 @@ export default function XPage() {
if (!extOnline) {
toast.push("插件未在线:请加载扩展并打开本页完成自动配对", "err");
}
const handle = username.trim().replace(/^@/, "");
if (!handle && accounts.length > 0) {
toast.push("请先在顶部选择要操作的账号", "err");
return;
}
const merged = {
...(username.trim() ? { username: username.trim().replace(/^@/, "") } : {}),
...(handle ? { username: handle } : {}),
export: "none",
...params,
};
@ -134,7 +164,7 @@ export default function XPage() {
toast.push((e as Error)?.message || "创建失败", "err");
}
},
[extOnline, toast, username],
[extOnline, toast, username, accounts.length],
);
const cancelJob = async (id: string) => {
@ -149,32 +179,49 @@ export default function XPage() {
}
};
const accountJobs = useMemo(
() => jobs.filter((j) => jobMatchesAccount(j, username)),
[jobs, username],
);
const selected = useMemo(
() => jobs.find((j) => j.id === selectedId) || jobs[0] || null,
[jobs, selectedId],
() => accountJobs.find((j) => j.id === selectedId) || accountJobs[0] || null,
[accountJobs, selectedId],
);
const filteredJobs = useMemo(() => {
return jobs.filter((j) => {
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;
});
}, [jobs, feedFilter]);
}, [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 jobs) {
for (const j of accountJobs) {
const list = nonFollowersFromJob(j);
if (list.length) return list;
}
return [] as string[];
}, [jobs]);
}, [accountJobs]);
const recentResults = useMemo(
() =>
jobs
accountJobs
.filter((j) => j.status === "completed" || j.status === "failed" || j.status === "cancelled")
.slice(0, 5)
.map((j) => ({
@ -183,10 +230,10 @@ export default function XPage() {
status: j.status,
summary: summarizeJob(j),
})),
[jobs],
[accountJobs],
);
const active = jobs.find((j) => j.status === "running" || j.status === "queued");
const active = accountJobs.find((j) => j.status === "running" || j.status === "queued");
const pct = active
? Math.min(
100,
@ -252,9 +299,12 @@ export default function XPage() {
<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)}
onChange={(e) => {
setUsername(e.target.value);
setSelectedId(null);
}}
>
<option value="">插件当前号</option>
<option value="">全部账号</option>
{accounts.map((a) => (
<option key={a.id} value={a.username || ""}>
@{a.username}
@ -324,6 +374,9 @@ export default function XPage() {
<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 className="mt-1 truncate text-slate-400">
当前 {username ? `@${username}` : "全部"}
</div>
</div>
</aside>
@ -339,7 +392,7 @@ export default function XPage() {
{...common}
extOnline={extOnline}
accountsN={accounts.length}
stats={stats}
stats={username ? accountStats : stats}
onGo={(id) => setTab(id as TabId)}
lastKind={lastJob?.kind}
likeN={likeN}
@ -350,7 +403,7 @@ export default function XPage() {
}}
/>
) : null}
{tab === "clips" ? <ClipsPanel toast={(m, k) => toast.push(m, k)} /> : null}
{tab === "clips" ? <ClipsPanel toast={(m, k) => toast.push(m, k)} accountUsername={username} /> : null}
{tab === "cleanup" ? (
<CleanupPanel
{...common}
@ -375,7 +428,10 @@ export default function XPage() {
<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>
<span className="rounded-full bg-white/5 px-2 py-0.5 text-[10px] text-slate-400">
{filteredJobs.length}
{username ? ` · @${username}` : ""}
</span>
</div>
<div className="flex gap-1 border-b border-white/5 px-3 py-2">
{(

View File

@ -5,6 +5,7 @@ export type XJob = {
kind?: string;
status?: string;
account_username?: string;
accountId?: string;
progress_current?: number;
progress_total?: number;
progress_message?: string;
@ -101,6 +102,31 @@ export function jobResult(job: XJob): Record<string, unknown> {
return {};
}
/** Owning X account for a job (who ran / was targeted as actor). */
export function jobAccountHandle(job: XJob): string {
const fromField = String(job.account_username || "").trim().replace(/^@/, "");
if (fromField) return fromField.toLowerCase();
const params = job.params && typeof job.params === "object" ? job.params : {};
const fromParams = String(params.username || "").trim().replace(/^@/, "");
if (fromParams) return fromParams.toLowerCase();
const r = jobResult(job);
const fromResult = String(r.account || r.username || "").trim().replace(/^@/, "");
return fromResult.toLowerCase();
}
/** Filter jobs by selected account. Empty selected = show all. */
export function jobMatchesAccount(job: XJob, selectedUsername: string): boolean {
const sel = String(selectedUsername || "")
.trim()
.replace(/^@/, "")
.toLowerCase();
if (!sel) return true;
const own = jobAccountHandle(job);
// Unattributed legacy jobs: hide when a specific account is selected
if (!own) return false;
return own === sel;
}
export function summarizeJob(job: XJob): string {
const name = kindLabel(job.kind);
if (job.status === "failed") return `${name}没做成\n原因:${job.error || "未知错误"}`;