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
+226
View File
@@ -0,0 +1,226 @@
import "dotenv/config";
import assert from "node:assert/strict";
import { randomUUID, randomBytes, createCipheriv, createHash } from "node:crypto";
import { readFile, writeFile, mkdir } from "node:fs/promises";
import path from "node:path";
import { spawn } from "node:child_process";
import { chromium } from "playwright";
import { PrismaClient } from "@prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
import sharp from "sharp";
import pm2 from "pm2";
const config = JSON.parse(await readFile(".data/queue/runtime.json", "utf8"));
const credentials = JSON.parse(await readFile(".data/e2e/credentials.json", "utf8"));
const previous = JSON.parse(await readFile("output/automation/e2e/result.json", "utf8"));
const base = config.NEXT_PUBLIC_APP_URL;
assert.ok(["localhost", "127.0.0.1"].includes(new URL(config.DATABASE_URL).hostname));
const prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString: config.DATABASE_URL }) });
const directory = path.resolve("output/automation/queue");
await mkdir(directory, { recursive: true });
const report = { runId: `queue-${Date.now()}`, startedAt: new Date().toISOString(), checks: [], observations: [] };
const checkpoint = async () => writeFile(path.join(directory, "result.json"), JSON.stringify(report, null, 2));
async function check(name, work) {
console.log(`Starting ${name}`);
const start = Date.now();
try {
const value = await work();
report.checks.push({ name, status: "passed", seconds: Math.round((Date.now() - start) / 1000) });
await checkpoint(); console.log(`Passed ${name}`); return value;
} catch (error) {
report.checks.push({ name, status: "failed", error: error.message });
await checkpoint(); throw error;
}
}
async function api(route, body, cookie, method = "POST", secret) {
const response = await fetch(`${base}${route}`, {
method, headers: { ...(body ? { "Content-Type": "application/json" } : {}), ...(cookie ? { Cookie: cookie } : {}), ...(secret ? { Authorization: `Bearer ${secret}` } : {}) },
...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(930_000),
});
return { status: response.status, data: await response.json() };
}
function status(result, expected) { assert.equal(result.status, expected, JSON.stringify(result.data)); return result.data; }
async function login(role) {
const response = await fetch(`${base}/api/auth/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: credentials.users[role].email, password: credentials.password }) });
assert.equal(response.status, 200);
return response.headers.getSetCookie().find((value) => value.startsWith("pm_session=")).split(";")[0];
}
function startWorker() {
const child = spawn(process.execPath, ["scripts/post-generation-worker.mjs"], { env: { ...process.env, POST_QUEUE_APP_URL: base, POST_QUEUE_SECRET: config.POST_QUEUE_SECRET }, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
child.stdout.on("data", (data) => process.stdout.write(data));
child.stderr.on("data", (data) => process.stderr.write(data));
return child;
}
let worker, browser, restorePm2 = false, pm2Connected = false;
const pm2Call = (method, ...args) => new Promise((resolve, reject) => pm2[method](...args, (error, value) => error ? reject(error) : resolve(value)));
try {
await pm2Call("connect"); pm2Connected = true;
const processes = await pm2Call("list");
const managed = processes.find((item) => item.name === "page-post-generation" && item.pm2_env.status === "online");
if (managed) {
assert.equal(path.resolve(managed.pm2_env.pm_cwd).toLowerCase(), process.cwd().toLowerCase(), "Do not stop a worker belonging to another workspace");
assert.equal((process.env.POST_QUEUE_APP_URL || "").replace(/\/+$/, ""), base, "Managed worker must target the local test app");
await pm2Call("stop", "page-post-generation"); restorePm2 = true;
}
const cookies = { manager: await login("manager"), viewer: await login("viewer"), outsider: await login("outsider") };
const page = await check("isolated-queue-fixture", async () => {
const iv = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", createHash("sha256").update(config.TOKEN_ENCRYPTION_KEY).digest(), iv);
const bytes = Buffer.concat([cipher.update("e2e-queue-no-graph-token"), cipher.final()]);
const tokenCipher = ["v1", iv.toString("base64url"), cipher.getAuthTag().toString("base64url"), bytes.toString("base64url")].join(":");
const fixture = await prisma.page.create({ data: {
fbPageId: report.runId, name: "[E2E คิวสมมติ] แก้วฟ้า คาเฟ่", tokenCipher,
profile: { create: previous.profile }, members: { create: [{ userId: credentials.users.manager.id, role: "MANAGER" }, { userId: credentials.users.viewer.id, role: "VIEWER" }] },
} });
report.pageId = fixture.id;
return fixture;
});
const payload = (topic) => ({ pageId: page.id, topic, requestKey: randomUUID(), targets: ["FACEBOOK"], plannedDay: "2026-11-24" });
await check("queue-authentication-and-membership", async () => {
const body = payload("ทดสอบสิทธิ์");
status(await api("/api/ai/post-jobs", body), 401);
status(await api("/api/ai/post-jobs", body, cookies.outsider), 404);
status(await api("/api/ai/post-jobs", body, cookies.viewer), 403);
status(await api(`/api/ai/post-jobs?pageId=${page.id}`, null, cookies.outsider, "GET"), 404);
status(await api("/api/cron/post-generation", null, cookies.manager), 401);
status(await api("/api/cron/post-generation", null, null, "POST", "wrong-secret"), 401);
assert.equal(await prisma.postGenerationJob.count({ where: { pageId: page.id } }), 0);
});
browser = await chromium.launch({ channel: "chrome", headless: true });
const context = await browser.newContext({ viewport: { width: 1440, height: 1100 } });
const loggedIn = await context.request.post(`${base}/api/auth/login`, { data: { email: credentials.users.manager.email, password: credentials.password } });
assert.equal(loggedIn.status(), 200);
let tab = await context.newPage();
const topicA = "แนะนำลาเต้ร้อนราคา 75 บาทในแก้วเซรามิกสีฟ้าบนโต๊ะไม้ริมหน้าต่าง แสงเช้า ไม่มีตัวอักษรหรือโลโก้ในภาพ";
const first = await check("browser-click-enqueues-immediately", async () => {
await tab.goto(`${base}/posts/new`, { waitUntil: "networkidle" });
await tab.locator("select").first().selectOption(page.id);
await tab.getByRole("textbox", { name: "หัวข้อโพสต์ที่จะเข้าคิว" }).fill(topicA);
const pending = tab.waitForResponse((response) => response.url().endsWith("/api/ai/post-jobs") && response.request().method() === "POST");
const start = Date.now();
await tab.getByRole("button", { name: "เข้าคิวสร้างโพสต์", exact: true }).dblclick();
const response = await pending;
assert.equal(response.status(), 202);
report.enqueueMilliseconds = Date.now() - start;
assert.ok(report.enqueueMilliseconds < 5000, "Enqueue must not wait for generation");
report.firstRequest = response.request().postDataJSON();
const data = await response.json();
assert.equal(data.job.status, "QUEUED");
await tab.screenshot({ path: path.join(directory, "queued-desktop.png"), fullPage: true });
return data.job;
});
await check("idempotent-concurrent-double-click", async () => {
const responses = await Promise.all(Array.from({ length: 4 }, () => api("/api/ai/post-jobs", report.firstRequest, cookies.manager)));
for (const response of responses) assert.equal(status(response, 200).job.id, first.id);
assert.equal(await prisma.postGenerationJob.count({ where: { pageId: page.id } }), 1);
const changed = await api("/api/ai/post-jobs", { ...report.firstRequest, topic: "different topic" }, cookies.manager);
assert.equal(changed.status, 400);
});
await check("queue-survives-browser-close-and-reopen", async () => {
await tab.close(); tab = await context.newPage();
await tab.goto(`${base}/posts/new`, { waitUntil: "networkidle" });
await tab.locator("select").first().selectOption(page.id);
await tab.getByText(topicA, { exact: true }).waitFor();
});
const second = status(await api("/api/ai/post-jobs", payload("แนะนำครัวซองต์เนยชิ้นละ 85 บาทบนจานขาว โต๊ะไม้ริมหน้าต่าง ภาพมีครัวซองต์ชิ้นเดียว ไม่มีกาแฟ ไม่มีตัวอักษรหรือโลโก้"), cookies.manager), 202).job;
const cancel = status(await api("/api/ai/post-jobs", payload("งานสำหรับยกเลิก ไม่ต้องสร้างจริง"), cookies.manager), 202).job;
const stale = status(await api("/api/ai/post-jobs", payload("งานจำลอง worker หยุด ไม่ต้องสร้างจริง"), cookies.manager), 202).job;
await prisma.pageMember.create({ data: { pageId: page.id, userId: credentials.users.outsider.id, role: "EDITOR" } });
const revoked = status(await api("/api/ai/post-jobs", payload("งานทดสอบเพิกถอนสิทธิ์ ไม่ต้องสร้างจริง"), cookies.outsider), 202).job;
await check("queue-limit-and-cancellation", async () => {
assert.equal((await api("/api/ai/post-jobs", payload("ต้องไม่ถูกเพิ่มเมื่อครบ 5 งาน"), cookies.manager)).status, 400);
status(await api(`/api/ai/post-jobs/${cancel.id}`, null, cookies.manager, "DELETE"), 200);
status(await api(`/api/ai/post-jobs/${cancel.id}`, null, cookies.manager, "DELETE"), 409);
status(await api(`/api/ai/post-jobs/${first.id}`, null, cookies.outsider, "GET"), 200);
await prisma.pageMember.delete({ where: { userId_pageId: { userId: credentials.users.outsider.id, pageId: page.id } } });
status(await api(`/api/ai/post-jobs/${first.id}`, null, cookies.outsider, "GET"), 404);
await prisma.postGenerationJob.update({ where: { id: stale.id }, data: { status: "RUNNING", startedAt: new Date(Date.now() - 30 * 60_000), heartbeatAt: new Date(Date.now() - 30 * 60_000) } });
});
report.jobIds = { first: first.id, second: second.id, cancel: cancel.id, stale: stale.id, revoked: revoked.id };
await checkpoint();
worker = startWorker();
let restarted = false;
const deadline = Date.now() + 14 * 60_000;
const last = {};
await check("live-fifo-generation-worker-restart-and-single-claim", async () => {
while (Date.now() < deadline) {
const jobs = await prisma.postGenerationJob.findMany({ where: { pageId: page.id }, orderBy: { createdAt: "asc" } });
assert.ok(jobs.filter((job) => job.status === "RUNNING").length <= 1);
for (const job of jobs) {
const current = `${job.status}:${job.stage}`;
if (last[job.id] !== current) { report.observations.push({ jobId: job.id, status: job.status, stage: job.stage, at: new Date().toISOString() }); last[job.id] = current; console.log(`${job.id}: ${current}`); await checkpoint(); }
}
const running = jobs.find((job) => job.id === first.id && job.status === "RUNNING");
if (running && !restarted) {
worker.kill(); worker = startWorker(); restarted = true;
const claims = await Promise.all([api("/api/cron/post-generation", null, null, "POST", config.POST_QUEUE_SECRET), api("/api/cron/post-generation", null, null, "POST", config.POST_QUEUE_SECRET)]);
for (const claim of claims) assert.equal(status(claim, 200).processed, false);
status(await api(`/api/ai/post-jobs/${first.id}`, null, cookies.manager, "DELETE"), 409);
}
if (jobs.every((job) => ["COMPLETED", "FAILED", "CANCELLED"].includes(job.status))) break;
await new Promise((resolve) => setTimeout(resolve, 2000));
}
assert.ok(restarted, "A running worker must have been restarted");
const a = await prisma.postGenerationJob.findUniqueOrThrow({ where: { id: first.id } });
const b = await prisma.postGenerationJob.findUniqueOrThrow({ where: { id: second.id } });
report.jobs = [a, b].map((job) => ({ id: job.id, status: job.status, error: job.error, topic: job.topic, postId: job.postId, imageUrl: job.imageBlobUrl, content: job.captionResult, createdAt: job.createdAt, startedAt: job.startedAt, finishedAt: job.finishedAt, waitSeconds: job.startedAt ? Math.round((job.startedAt - job.createdAt) / 1000) : null, processingSeconds: job.finishedAt && job.startedAt ? Math.round((job.finishedAt - job.startedAt) / 1000) : null, totalSeconds: job.finishedAt ? Math.round((job.finishedAt - job.createdAt) / 1000) : null }));
assert.equal(a.status, "COMPLETED", a.error || "First job did not complete");
assert.equal(b.status, "COMPLETED", b.error || "Second job did not complete");
assert.ok(b.startedAt >= a.finishedAt, "FIFO jobs must not overlap");
assert.equal((await prisma.postGenerationJob.findUniqueOrThrow({ where: { id: stale.id } })).status, "FAILED");
assert.equal((await prisma.postGenerationJob.findUniqueOrThrow({ where: { id: revoked.id } })).status, "FAILED");
assert.equal((await prisma.postGenerationJob.findUniqueOrThrow({ where: { id: cancel.id } })).status, "CANCELLED");
});
await check("verify-new-images-drafts-usage-audit-and-ui", async () => {
for (let i = 0; i < report.jobs.length; i++) {
const job = report.jobs[i];
const response = await fetch(job.imageUrl);
assert.equal(response.status, 200);
const bytes = Buffer.from(await response.arrayBuffer());
const meta = await sharp(bytes).metadata();
assert.equal(meta.width, 1024); assert.equal(meta.height, 1024); assert.equal(meta.format, "jpeg");
job.sha256 = createHash("sha256").update(bytes).digest("hex");
await writeFile(path.join(directory, `job-${i + 1}.jpg`), bytes);
const post = await prisma.post.findUniqueOrThrow({ where: { id: job.postId } });
assert.equal(post.status, "DRAFT"); assert.equal(post.aiAssisted, true);
assert.equal(post.imageBlobUrl, job.imageUrl); assert.equal(post.fbPostId, null); assert.equal(post.scheduledPublishAt, null);
}
assert.notEqual(report.jobs[0].sha256, report.jobs[1].sha256);
assert.equal(await prisma.post.count({ where: { pageId: page.id } }), 2);
assert.equal(await prisma.aiUsage.count({ where: { pageId: page.id, kind: "post-generation" } }), 2);
assert.equal(await prisma.aiUsage.count({ where: { pageId: page.id, kind: "image" } }), 2);
report.audit = await prisma.auditLog.findMany({ where: { pageId: page.id }, select: { action: true, detail: true, createdAt: true }, orderBy: { createdAt: "asc" } });
for (const action of ["AI_POST_QUEUED", "AI_POST_STARTED", "AI_POST_COMPLETED", "AI_POST_FAILED", "AI_POST_CANCELLED", "POST_CREATED"]) assert.ok(report.audit.some((row) => row.action === action));
await tab.reload({ waitUntil: "networkidle" });
await tab.getByRole("link", { name: "เปิดฉบับร่าง" }).first().waitFor();
assert.equal(await tab.getByRole("link", { name: "เปิดฉบับร่าง" }).count(), 2);
await tab.screenshot({ path: path.join(directory, "completed-desktop.png"), fullPage: true });
await tab.setViewportSize({ width: 390, height: 844 });
await tab.screenshot({ path: path.join(directory, "completed-mobile.png"), fullPage: true });
await tab.goto(`${base}/posts/${report.jobs[0].postId}`, { waitUntil: "networkidle" });
await tab.locator(`img[src="${report.jobs[0].imageUrl}"]`).first().waitFor();
await tab.screenshot({ path: path.join(directory, "draft-mobile.png"), fullPage: true });
});
report.status = "passed";
report.finishedAt = new Date().toISOString();
await checkpoint();
const summary = ["ผลทดสอบคิวสร้างโพสต์ AI — ข้อมูลร้านสมมติ", `รับงานจากปุ่มบนเว็บ: ${report.enqueueMilliseconds} ms`, ...report.jobs.map((job, index) => `งาน ${index + 1}: รอคิว ${job.waitSeconds} วินาที / ทำงาน ${job.processingSeconds} วินาที / รวม ${job.totalSeconds} วินาที\nหัวข้อ: ${job.topic}\nCaption: ${job.content.caption}\nPrompt: ${job.content.imagePrompt}\nโพสต์: ${base}/posts/${job.postId}\nภาพ: job-${index + 1}.jpg\n`), "ผลตรวจ:", ...report.checks.map((item) => `${item.name}: ${item.status}`), "ฉบับร่าง 2 โพสต์ ไม่ได้เผยแพร่ Facebook/Instagram"].join("\n");
await writeFile(path.join(directory, "report.txt"), summary);
console.log(summary);
} catch (error) {
report.status = "failed"; await checkpoint(); console.error(error); process.exitCode = 1;
} finally {
worker?.kill(); await browser?.close();
if (report.status !== "passed" && report.pageId) {
await prisma.$transaction(async (tx) => {
const abandoned = await tx.postGenerationJob.findMany({ where: { pageId: report.pageId, status: "QUEUED" }, select: { id: true } });
for (const job of abandoned) {
const changed = await tx.postGenerationJob.updateMany({ where: { id: job.id, status: "QUEUED" }, data: { status: "CANCELLED", stage: "cancelled", finishedAt: new Date() } });
if (changed.count) await tx.auditLog.create({ data: { pageId: report.pageId, actorLabel: "E2E cleanup", action: "AI_POST_CANCELLED", detail: { jobId: job.id, reason: "aborted-test" } } });
}
});
}
await prisma.$disconnect();
if (restorePm2) await pm2Call("restart", "page-post-generation");
if (pm2Connected) pm2.disconnect();
}