fix: detect X daily post limit and pause auto-post

Extension reads the 'You've hit the daily post limit' banner and fails the job instead of reporting success. Backend then disables x_clips_auto_post, skips remaining scheduled clips, and cancels queued engage.post jobs.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-20 06:53:14 -05:00
parent dd2931af86
commit f63dbb78b3
4 changed files with 169 additions and 1 deletions

View File

@ -718,3 +718,29 @@ def list_cancel_requested(agent_id: str = "") -> list[str]:
return [str(r[0]) for r in rows]
finally:
conn.close()
def cancel_queued_engage_posts(*, reason: str = "x_daily_post_limit") -> int:
"""Cancel all queued (and soft-stuck startup) engage.post jobs."""
err = str(reason or "x_daily_post_limit")[:800]
now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
with _lock:
conn = _connect()
try:
ensure_x2_tables(conn)
cur = conn.execute(
"""
UPDATE x2_jobs
SET status = 'cancelled',
error = ?,
progress_message = ?,
job_updated_at = ?
WHERE kind = 'engage.post'
AND status IN ('queued', 'running')
""",
(err, "X 日发帖上限", now_iso),
)
conn.commit()
return int(cur.rowcount or 0)
finally:
conn.close()

View File

@ -507,3 +507,32 @@ def x_clips_stats(push_date: str = "") -> dict[str, Any]:
}
finally:
conn.close()
def skip_remaining_scheduled_for_day(
push_date: str = "",
*,
reason: str = "x_daily_post_limit",
) -> int:
"""Mark today's scheduled (not yet dispatched) clip jobs as skipped."""
day = push_date or push_date_from_ts(time.time())
now = time.time()
err = str(reason or "x_daily_post_limit")[:500]
with _lock:
conn = _connect()
try:
ensure_x_clips_tables(conn)
cur = conn.execute(
"""
UPDATE x_clip_jobs
SET status = 'skipped', error = ?, finished_at = ?, updated_at = ?
WHERE push_date = ?
AND status IN ('scheduled', 'recorded', 'pending')
AND IFNULL(x2_job_id, '') = ''
""",
(err, now, now, day),
)
conn.commit()
return int(cur.rowcount or 0)
finally:
conn.close()

View File

@ -21,6 +21,23 @@ from .timeutil import push_date_from_ts
from .x_clips_schedule import pick_upload_at, schedule_board
def is_x_daily_post_limit(err: str) -> bool:
"""True when X UI / extension reports free-tier daily post cap."""
text = str(err or "")
low = text.lower()
needles = (
"x_daily_post_limit",
"daily post limit",
"hit the daily post limit",
"subscribe to premium for higher limits",
"每日发帖上限",
"发帖次数已达上限",
"发帖已达上限",
"今日发帖上限",
)
return any(n in low or n in text for n in needles)
def _room_tags(room: dict[str, Any]) -> list[str]:
tags = room.get("tags") or []
if isinstance(tags, str):
@ -626,6 +643,35 @@ class XClipsPipeline:
error=err,
finished_at=time.time(),
)
if is_x_daily_post_limit(err):
self._on_x_daily_post_limit(err)
def _on_x_daily_post_limit(self, err: str) -> None:
"""Pause auto-post, skip remaining clips today, cancel queued engage.post."""
try:
db.update_settings_map({"x_clips_auto_post": False})
except Exception:
pass
skipped = 0
cancelled = 0
try:
skipped = x_clips_db.skip_remaining_scheduled_for_day(reason="x_daily_post_limit")
except Exception:
pass
try:
cancelled = x2_db.cancel_queued_engage_posts(reason="x_daily_post_limit")
except Exception:
pass
self.last_error = "X 每日发帖上限,已暂停自动发帖"
try:
db.add_event(
kind="x_clips",
level="error",
message=f"X 触发每日发帖上限,已暂停自动发帖(跳过 {skipped},取消队列 {cancelled})",
meta={"error": str(err)[:240], "skipped": skipped, "cancelled": cancelled},
)
except Exception:
pass
@staticmethod
def _delete_clip(path: str) -> None:

View File

@ -1180,6 +1180,44 @@ async function clearComposer(box: HTMLElement): Promise<void> {
await sleep(80);
}
/** X free-tier daily post cap banner inside composer / toast. */
function readXDailyPostLimitError(): string | null {
const needles = [
/you've hit the daily post limit/i,
/hit the daily post limit/i,
/daily post limit/i,
/subscribe to premium for higher limits/i,
/upgrade to unlock/i,
/达到.?每日.?发帖.?上限/,
/今日发帖.?上限/,
/发帖次数已达上限/,
/发帖已达上限/,
];
const roots: HTMLElement[] = [];
const dialog = document.querySelector('[role="dialog"]') as HTMLElement | null;
if (dialog) roots.push(dialog);
roots.push(document.body);
for (const root of roots) {
const text = String(root.innerText || root.textContent || "");
for (const re of needles) {
if (re.test(text)) {
return "X_DAILY_POST_LIMIT: You've hit the daily post limit";
}
}
}
for (const el of document.querySelectorAll(
'[role="alert"], [data-testid="toast"], [data-testid="error"]',
)) {
const text = String((el as HTMLElement).innerText || el.textContent || "");
for (const re of needles) {
if (re.test(text)) {
return "X_DAILY_POST_LIMIT: You've hit the daily post limit";
}
}
}
return null;
}
function readComposerOverBy(): number | null {
// X shows remaining (or negative overage) near the toolbar when close to / over limit
const root =
@ -1347,11 +1385,16 @@ async function postTweet(
finalCaption = captionOnly(finalRaw);
}
const limitBefore = readXDailyPostLimitError();
if (limitBefore) throw new Error(limitBefore);
const btn = (document.querySelector('[data-testid="tweetButton"]') ||
document.querySelector('[data-testid="tweetButtonInline"]')) as
| HTMLButtonElement
| null;
if (!btn || btn.getAttribute("aria-disabled") === "true" || btn.disabled) {
const limBtn = readXDailyPostLimitError();
if (limBtn) throw new Error(limBtn);
const over2 = readComposerOverBy();
throw new Error(
over2
@ -1360,7 +1403,31 @@ async function postTweet(
);
}
btn.click();
await sleep(mediaList.some((m) => m.mime.startsWith("video/")) ? 4000 : 1600);
const waitMs = mediaList.some((m) => m.mime.startsWith("video/")) ? 5500 : 2800;
const deadline = Date.now() + waitMs;
while (Date.now() < deadline) {
const lim = readXDailyPostLimitError();
if (lim) throw new Error(lim);
await sleep(350);
}
const limAfter = readXDailyPostLimitError();
if (limAfter) throw new Error(limAfter);
// Composer still open with Post button + our caption → post likely rejected
const stillBox = findTweetComposeBox();
const stillBtn = (document.querySelector('[data-testid="tweetButton"]') ||
document.querySelector('[data-testid="tweetButtonInline"]')) as
| HTMLButtonElement
| null;
if (stillBox && stillBtn && !stillBtn.disabled) {
const still = captionOnly(composerPlain(stillBox));
if (still && captionMatchToken(still, token)) {
const limStill = readXDailyPostLimitError();
if (limStill) throw new Error(limStill);
throw new Error("发帖未确认成功(编辑框仍在,可能被 X 拦截)");
}
}
return {
ok: true,
text: body,