Move AI to Codex CLI + ChatGPT browser workers with a durable post queue

Text generation now runs through a PM2 automation worker (codex exec) and
images through the ChatGPT Chrome extension, replacing the Anthropic API.
generateStructured keeps its signature; results are Zod-validated on the web
side and the worker is reached with a bearer secret.

- AI image assistant in the post editor: editable prompt step, then image
  (square or 3:2 only, since Instagram rejects 2:3), stored via putBlob
- Full-post queue (PostGenerationJob + migration): enqueue returns 202, FIFO
  claim under an advisory lock, heartbeat, stale-job failure, per-user
  request key, cancel while QUEUED; output is always a DRAFT with audit rows
- Separate 10 images/page/day quota; text quota excludes images
- Worker reports Codex usage-limit as 429 with a clear Thai message
- Docs: AI-AUTOMATION.md, ARCHITECTURE/README/.env.example updated

Known gap: the live FIFO queue check (scripts/check-post-queue.mjs) has not
passed yet; the last run hit the Codex account usage limit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Loma Bot Ops
2026-11-22 21:52:09 +07:00
parent 4a673ebb28
commit 6994ba1a4e
41 changed files with 2007 additions and 113 deletions
+114
View File
@@ -0,0 +1,114 @@
"use client";
import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { withBase } from "@/lib/base-path";
import { POST_JOB_STAGE, POST_JOB_STATUS, type PostJobView } from "@/lib/ai/post-queue-shared";
import { Icon } from "./Icon";
import { Notice } from "./ui";
function duration(job: PostJobView): string {
if (!job.finishedAt) return "";
const seconds = Math.max(0, Math.round((new Date(job.finishedAt).getTime() - new Date(job.createdAt).getTime()) / 1000));
return `${Math.floor(seconds / 60)} นาที ${seconds % 60} วินาที`;
}
/** Server-persisted jobs are rediscovered after reload; the browser never executes the pipeline. */
export function PostGenerationQueue({ pageId, targets, plannedDay, initialTopic }: {
pageId: string; targets: ("FACEBOOK" | "INSTAGRAM")[]; plannedDay: string; initialTopic: string;
}) {
const [topic, setTopic] = useState(initialTopic.slice(0, 1000));
const [jobs, setJobs] = useState<PostJobView[]>([]);
const [busy, setBusy] = useState(false);
const [cancelling, setCancelling] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [pollError, setPollError] = useState(false);
const [message, setMessage] = useState("");
const requestKey = useRef<string | null>(null);
useEffect(() => {
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout>;
async function refresh() {
try {
const response = await fetch(withBase(`/api/ai/post-jobs?pageId=${encodeURIComponent(pageId)}`), { signal: controller.signal, cache: "no-store" });
if (!response.ok) throw new Error("Queue unavailable");
const data = await response.json();
if (!controller.signal.aborted) { setJobs(data.jobs); setPollError(false); }
} catch {
if (!controller.signal.aborted) setPollError(true);
} finally {
if (!controller.signal.aborted) timer = setTimeout(refresh, 3000);
}
}
void refresh();
return () => { controller.abort(); clearTimeout(timer); };
}, [pageId]);
async function enqueue() {
if (busy) return;
setBusy(true); setError(null); setMessage("");
requestKey.current ??= crypto.randomUUID();
try {
const response = await fetch(withBase("/api/ai/post-jobs"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, requestKey: requestKey.current, topic, targets, plannedDay }) });
const data = await response.json();
if (!response.ok) { if (response.status < 500) requestKey.current = null; throw new Error(data.error || "เพิ่มคิวไม่สำเร็จ"); }
setJobs((current) => [data.job, ...current.filter((job) => job.id !== data.job.id)]);
setTopic("");
requestKey.current = null;
setMessage("รับงานเข้าคิวแล้ว กลับมาหน้านี้เพื่อติดตามและเปิดฉบับร่างเมื่อพร้อมได้");
} catch (failure) { setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้ กรุณาลองอีกครั้ง"); }
finally { setBusy(false); }
}
async function cancel(id: string) {
setCancelling(id); setError(null);
try {
const response = await fetch(withBase(`/api/ai/post-jobs/${id}`), { method: "DELETE" });
const data = await response.json();
if (!response.ok) throw new Error(data.error || "ยกเลิกไม่สำเร็จ");
setJobs((current) => current.map((job) => job.id === id ? { ...job, status: "CANCELLED" } : job));
setMessage("ยกเลิกงานที่รอคิวแล้ว");
} catch (failure) { setError(failure instanceof Error ? failure.message : "เชื่อมต่อไม่ได้ กรุณาลองอีกครั้ง"); }
finally { setCancelling(null); }
}
return (
<section aria-label="คิวสร้างโพสต์ด้วย AI" className="border border-line rounded-xl p-4 flex flex-col gap-3 bg-board">
<h3 className="font-semibold text-[15px]">สร้างทั้งโพสต์ด้วย AI</h3>
<p className="text-[13px] text-ink-2">ให้ Codex เขียนเนื้อหาและ ChatGPT สร้างภาพ แล้วบันทึกเป็นฉบับร่างรอคุณตรวจ ปิดหน้านี้แล้วกลับมาดูคิวได้</p>
<label className="field">
<span>หัวข้อโพสต์ที่จะเข้าคิว</span>
<textarea className="textarea" rows={2} value={topic} disabled={busy} maxLength={1000} onChange={(event) => { setTopic(event.target.value); requestKey.current = null; }} placeholder="เช่น แนะนำเมนูใหม่ พร้อมราคาและจุดเด่นที่ต้องการสื่อ" />
</label>
<p className="text-[12px] text-ink-2">ฉบับร่างสำหรับ {targets.length ? targets.map((target) => target === "FACEBOOK" ? "Facebook" : "Instagram").join(" + ") : "ยังไม่ได้เลือกช่องทาง"}{plannedDay ? ` · วันวางแผน ${plannedDay}` : " · ยังไม่วางวัน"}</p>
<div className="flex flex-wrap gap-2 items-center">
<button type="button" className="btn btn-primary btn-sm" disabled={busy || !topic.trim() || targets.length === 0} onClick={enqueue}>
<Icon name="sparkle" size={15} /> {busy ? "กำลังรับงาน…" : "เข้าคิวสร้างโพสต์"}
</button>
<Link href="/profile" prefetch={false} onClick={() => { document.cookie = `pm_page=${encodeURIComponent(pageId)}; path=/; max-age=31536000; samesite=lax`; }} className="text-[12px] underline text-ink-2">ตรวจข้อมูลร้านก่อนสร้าง</Link>
</div>
{message && <p role="status" className="text-[13px] text-ink-2">{message}</p>}
{error && <Notice tone="red">{error}</Notice>}
{pollError && <p role="status" className="text-[12px] text-ink-2">ยังอัปเดตคิวไม่ได้ ระบบกำลังลองเชื่อมต่อใหม่ งานที่รับไว้ยังอยู่ในคิว</p>}
{jobs.length > 0 && <>
<h4 className="font-semibold text-[13px] pt-2">งานล่าสุดของเพจนี้</h4>
<ul className="divide-y divide-line" aria-label="รายการคิวสร้างโพสต์">
{jobs.map((job) => <li key={job.id} className="py-3 flex flex-col gap-1.5">
<div className="flex flex-wrap items-start gap-2">
<span className="font-medium text-[13px] flex-1 min-w-0 break-words">{job.topic}</span>
<span role="status" className="text-[12px] text-ink-2">{POST_JOB_STATUS[job.status]}</span>
</div>
{job.status === "RUNNING" && <p role="status" className="text-[12px] text-ink-2">{POST_JOB_STAGE[job.stage] || "กำลังทำงาน"}</p>}
{job.error && <p className="text-[12px] text-danger-ink">{job.error}</p>}
{job.status === "COMPLETED" && <div className="flex flex-wrap items-center gap-3">
{job.postId ? <Link href={`/posts/${job.postId}`} className="underline text-[13px] font-medium">เปิดฉบับร่าง</Link> : <span className="text-[12px]">ฉบับร่างถูกลบแล้ว</span>}
<span className="text-[12px] text-ink-2">รวมเวลารอคิว {duration(job)}</span>
</div>}
{job.status === "QUEUED" && <button type="button" className="btn btn-ghost btn-sm self-start" disabled={cancelling === job.id} onClick={() => cancel(job.id)}>{cancelling === job.id ? "กำลังยกเลิก…" : "ยกเลิกคิวนี้"}</button>}
</li>)}
</ul>
</>}
</section>
);
}