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:
@@ -13,7 +13,7 @@ interface Variant {
|
||||
}
|
||||
|
||||
/**
|
||||
* Drafts or rewrites the caption with Claude. The chosen text only fills the
|
||||
* Drafts or rewrites the caption with Codex CLI. The chosen text only fills the
|
||||
* editor — saving and approval stay exactly as for hand-written posts.
|
||||
*/
|
||||
export function CaptionAssistant({
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
"use client";
|
||||
/* eslint-disable @next/next/no-img-element -- generated image URLs, not optimisable */
|
||||
import { withBase } from "@/lib/base-path";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Icon } from "./Icon";
|
||||
import { Notice } from "./ui";
|
||||
import { IMAGE_PROMPT_MAX, IMAGE_SIZES, type ImageSizeKey } from "@/lib/ai/image-shared";
|
||||
// (server-only helpers live in lib/ai/image.ts — never import that file here)
|
||||
|
||||
async function post(body: Record<string, unknown>): Promise<{ ok: true; data: Record<string, unknown> } | { ok: false; error: string }> {
|
||||
const res = await fetch(withBase("/api/ai/image"), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
}).catch(() => null);
|
||||
const data = res ? await res.json().catch(() => ({})) : {};
|
||||
if (!res?.ok) return { ok: false, error: (data.error as string) ?? "AI ทำงานไม่สำเร็จ ลองใหม่อีกครั้ง" };
|
||||
return { ok: true, data };
|
||||
}
|
||||
|
||||
/**
|
||||
* Two explicit steps: AI drafts an image prompt the user can edit, then a
|
||||
* second press makes the image. The chosen image only fills the editor —
|
||||
* saving and approval stay exactly as for an uploaded picture.
|
||||
*/
|
||||
export function ImageAssistant({
|
||||
pageId,
|
||||
initialIdea,
|
||||
hasImage,
|
||||
onUse,
|
||||
}: {
|
||||
pageId: string;
|
||||
initialIdea: string;
|
||||
hasImage: boolean;
|
||||
onUse: (url: string) => void;
|
||||
}) {
|
||||
const [hasPrompt, setHasPrompt] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [idea, setIdea] = useState("");
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [size, setSize] = useState<ImageSizeKey>("square");
|
||||
const [result, setResult] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState<"prompt" | "generate" | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [profileMissing, setProfileMissing] = useState(false);
|
||||
|
||||
async function draftPrompt() {
|
||||
setBusy("prompt");
|
||||
setError(null);
|
||||
const r = await post({ action: "prompt", pageId, description: idea });
|
||||
setBusy(null);
|
||||
if (!r.ok) return setError(r.error);
|
||||
setPrompt(String(r.data.prompt ?? ""));
|
||||
setHasPrompt(true);
|
||||
setProfileMissing(Boolean(r.data.profileMissing));
|
||||
}
|
||||
|
||||
async function makeImage() {
|
||||
setBusy("generate");
|
||||
setError(null);
|
||||
const r = await post({ action: "generate", pageId, prompt, size });
|
||||
setBusy(null);
|
||||
if (!r.ok) return setError(r.error);
|
||||
setResult(String(r.data.url ?? ""));
|
||||
}
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<button
|
||||
aria-expanded={false}
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm self-start"
|
||||
onClick={() => {
|
||||
setIdea((cur) => cur || initialIdea.slice(0, 1000));
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
<Icon name="sparkle" size={15} /> ให้ AI สร้างรูป
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section aria-busy={busy !== null} className="rounded-[12px] border border-line bg-board p-3.5 flex flex-col gap-3" aria-label="ผู้ช่วยสร้างรูป">
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon name="sparkle" size={16} />
|
||||
<b className="text-[14px]">ให้ AI สร้างรูป</b>
|
||||
<button type="button" className="btn btn-ghost btn-sm ml-auto" disabled={busy !== null} onClick={() => setOpen(false)} aria-label="ปิดผู้ช่วยสร้างรูป">
|
||||
<Icon name="x" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<label className="field">
|
||||
<span>อยากได้รูปแบบไหน</span>
|
||||
<textarea
|
||||
className="textarea"
|
||||
rows={2}
|
||||
autoFocus
|
||||
disabled={busy !== null}
|
||||
maxLength={1000}
|
||||
value={idea}
|
||||
onChange={(e) => setIdea(e.target.value)}
|
||||
placeholder="เช่น เค้กช็อกโกแลตบนโต๊ะไม้ แสงธรรมชาติจากหน้าต่าง โทนอบอุ่น"
|
||||
/>
|
||||
</label>
|
||||
<div>
|
||||
<button type="button" className="btn btn-primary btn-sm" disabled={busy !== null || !idea.trim()} onClick={draftPrompt}>
|
||||
<Icon name="sparkle" size={14} /> {busy === "prompt" ? "AI กำลังร่างพรอมต์…" : prompt ? "ร่างพรอมต์ใหม่" : "ร่างพรอมต์ให้"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{hasPrompt && (
|
||||
<>
|
||||
<label className="field">
|
||||
<span className="flex">
|
||||
พรอมต์สร้างรูป (แก้ได้) <span className="ml-auto num text-ink-4">{prompt.length.toLocaleString("th-TH")}</span>
|
||||
</span>
|
||||
<textarea className="textarea" disabled={busy !== null} rows={6} maxLength={IMAGE_PROMPT_MAX} value={prompt} onChange={(e) => setPrompt(e.target.value)} />
|
||||
</label>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{(Object.keys(IMAGE_SIZES) as ImageSizeKey[]).map((k) => (
|
||||
<button key={k} type="button" className="chip" aria-pressed={size === k} disabled={busy !== null} onClick={() => setSize(k)}>
|
||||
{IMAGE_SIZES[k].label}
|
||||
</button>
|
||||
))}
|
||||
<button type="button" className="btn btn-primary btn-sm ml-auto" disabled={busy !== null || !prompt.trim()} onClick={makeImage}>
|
||||
<Icon name="image" size={14} /> {busy === "generate" ? "กำลังสร้างรูป… (ราว 30–60 วินาที)" : result ? "สร้างใหม่" : "สร้างรูป"}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{busy && <p role="status" className="text-[12px] text-ink-3">{busy === "prompt" ? "กำลังร่างพรอมต์…" : "กำลังสร้างรูป กรุณารอสักครู่…"}</p>}
|
||||
{error && <div role="alert"><Notice tone="red">{error}</Notice></div>}
|
||||
{profileMissing && (
|
||||
<p className="text-[12px] text-ink-3">
|
||||
ยังไม่มีโปรไฟล์ร้าน — <Link href="/profile" className="underline">ตั้งไว้</Link> แล้วพรอมต์จะตรงกับร้านมากขึ้น
|
||||
</p>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<div className="rounded-[10px] border border-line bg-paper p-2 flex flex-col gap-2">
|
||||
<img src={result} alt="รูปที่ AI สร้าง" className="w-full max-h-[320px] object-contain rounded-[6px] bg-board" />
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-sm"
|
||||
disabled={busy !== null}
|
||||
onClick={() => {
|
||||
if (hasImage && !window.confirm("แทนที่รูปเดิมของโพสต์ด้วยรูปนี้?")) return;
|
||||
onUse(result);
|
||||
setResult(null);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<Icon name="check" size={14} /> ใช้รูปนี้
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost btn-sm" disabled={busy !== null} onClick={() => setResult(null)}>
|
||||
ทิ้ง
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-[11px] text-ink-4">รูปจาก AI — ตรวจให้ตรงกับสินค้าจริงก่อนส่งอนุมัติ · พรอมต์จะถูกส่งไปสร้างรูปผ่านเว็บ ChatGPT บนเครื่อง worker</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import { roleAtLeast } from "@/lib/auth/roles";
|
||||
import { bkkMidnight } from "@/lib/board";
|
||||
import { Icon } from "./Icon";
|
||||
import { CaptionAssistant } from "./CaptionAssistant";
|
||||
import { ImageAssistant } from "./ImageAssistant";
|
||||
import { PostGenerationQueue } from "./PostGenerationQueue";
|
||||
import { PostCheck } from "./PostCheck";
|
||||
import { PageAvatar } from "./PageAvatar";
|
||||
import { formatDateTime, Notice, StatusPill } from "./ui";
|
||||
@@ -264,6 +266,8 @@ export function PostEditor({
|
||||
<small className="text-ink-3">เว้นว่างเพื่อเลือกวันภายหลัง · อนุมัติก่อน แล้วเลือกเวลาเผยแพร่</small>
|
||||
</label>}
|
||||
|
||||
{!post && canEdit && pageId && <PostGenerationQueue key={pageId} pageId={pageId} targets={targets} plannedDay={plannedDay} initialTopic={initialDraft?.topic || title} />}
|
||||
|
||||
{canEdit && pageId && (
|
||||
<CaptionAssistant
|
||||
pageId={pageId}
|
||||
@@ -307,6 +311,9 @@ export function PostEditor({
|
||||
{busy === "upload" ? "กำลังอัปโหลด…" : "เลือกรูป"}
|
||||
</button>
|
||||
)}
|
||||
{canEdit && pageId && (
|
||||
<ImageAssistant key={pageId} pageId={pageId} initialIdea={title || caption} hasImage={Boolean(imageUrl)} onUse={(url) => { setImageUrl(url); setAiAssisted(true); }} />
|
||||
)}
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="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>
|
||||
);
|
||||
}
|
||||
@@ -106,7 +106,7 @@ export function ProfileForm({
|
||||
<button type="submit" className="btn btn-primary" disabled={busy !== null}>
|
||||
{busy === "save" ? "กำลังบันทึก…" : "บันทึกโปรไฟล์"}
|
||||
</button>
|
||||
<p className="text-[12px] text-ink-4 flex-1 min-w-[220px]">ข้อมูลนี้และโพสต์ของเพจจะถูกส่งไปให้ AI (Anthropic) ประมวลผลตอนใช้ผู้ช่วย AI</p>
|
||||
<p className="text-[12px] text-ink-4 flex-1 min-w-[220px]">ข้อมูลนี้และโพสต์ของเพจจะถูกส่งไปให้ Codex ประมวลผลตอนใช้ผู้ช่วย AI</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user