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
+260
View File
@@ -0,0 +1,260 @@
import "dotenv/config";
import assert from "node:assert/strict";
import { randomBytes, createHash, createCipheriv, scryptSync } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { spawn } from "node:child_process";
import { PrismaClient } from "@prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
import sharp from "sharp";
import { chromium } from "playwright";
const privateDir = path.resolve(".data/e2e");
const outputDir = path.resolve("output/automation/e2e");
const configFile = path.join(privateDir, "runtime.json");
await mkdir(privateDir, { recursive: true });
await mkdir(outputDir, { recursive: true });
if (process.argv.includes("--prepare")) {
const databaseUrl = (await readFile(path.join(privateDir, "databaseUrl.txt"), "utf8")).trim();
assert.ok(["localhost", "127.0.0.1"].includes(new URL(databaseUrl).hostname), "Test database must be local");
const config = {
DATABASE_URL: databaseUrl,
SESSION_SECRET: randomBytes(48).toString("hex"),
TOKEN_ENCRYPTION_KEY: randomBytes(32).toString("hex"),
UPLOAD_DIR: path.join(privateDir, "uploads"),
NEXT_PUBLIC_APP_URL: "http://localhost:3107",
NEXT_PUBLIC_BASE_PATH: "",
};
await writeFile(configFile, JSON.stringify(config, null, 2));
const migration = spawn(process.execPath, [path.resolve("node_modules/prisma/build/index.js"), "migrate", "deploy"], {
env: { ...process.env, ...config }, windowsHide: true, stdio: ["ignore", "pipe", "pipe"],
});
let diagnostic = "";
migration.stdout.on("data", (data) => { diagnostic += data; });
migration.stderr.on("data", (data) => { diagnostic += data; });
const exit = await new Promise((resolve, reject) => { migration.once("close", resolve); migration.once("error", reject); });
await writeFile(path.join(privateDir, "migration.log"), diagnostic);
assert.equal(exit, 0, "Test migration failed; inspect .data/e2e/migration.log");
console.log("Isolated test configuration and existing migrations prepared.");
process.exit(0);
}
const config = JSON.parse(await readFile(configFile, "utf8"));
const base = config.NEXT_PUBLIC_APP_URL;
const prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString: config.DATABASE_URL }) });
const resume = process.argv.includes("--resume");
const report = resume ? JSON.parse(await readFile(path.join(outputDir, "result.json"), "utf8")) : { runId: `e2e-${Date.now()}`, startedAt: new Date().toISOString(), syntheticData: true, appUrl: base, steps: [] };
const runId = report.runId;
report.status = "running";
const checkpoint = async () => writeFile(path.join(outputDir, "result.json"), JSON.stringify(report, null, 2));
const step = async (name, work) => {
console.log(`Starting ${name}`);
const started = Date.now();
try {
const value = await work();
report.steps.push({ name, status: "passed", seconds: Math.round((Date.now() - started) / 1000) });
await checkpoint();
console.log(`Passed ${name}`);
return value;
} catch (error) {
report.steps.push({ name, status: "failed", error: error.message });
await checkpoint();
throw error;
}
};
async function request(route, body, cookie, method = "POST") {
const response = await fetch(`${base}${route}`, {
method, headers: { ...(body ? { "Content-Type": "application/json" } : {}), ...(cookie ? { Cookie: cookie } : {}) },
...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(290_000),
});
const data = await response.json();
return { response, data };
}
function requireStatus(result, expected) {
assert.equal(result.response.status, expected, JSON.stringify(result.data));
return result.data;
}
const profile = {
business: "ร้านทดสอบ ‘แก้วฟ้า คาเฟ่’ เป็นข้อมูลสมมติสำหรับทดสอบระบบ ขายลาเต้ร้อนแก้วเซรามิกสีฟ้า 75 บาท และครัวซองต์เนยชิ้นละ 85 บาท ร้านมีโต๊ะไม้ริมหน้าต่าง บรรยากาศแสงธรรมชาติ รับประทานที่ร้าน ไม่มีบริการส่งและยังไม่มีโปรโมชั่น",
audience: "คนวัยทำงานอายุ 25–40 ปี ที่ชอบกาแฟและมุมพักผ่อนเรียบง่าย",
tone: "ภาษาไทยอบอุ่น เป็นกันเอง กระชับ ไม่กล่าวอ้างเกินจริง ใช้ emoji ได้เล็กน้อย",
avoid: "ห้ามแต่งส่วนลด รีวิว ที่อยู่ เวลาเปิดปิด เบอร์โทร คุณประโยชน์ต่อสุขภาพ หรืออ้างว่าเป็นร้านจริง ห้ามใส่โลโก้และตัวอักษรลงในภาพ",
cta: "ทักแชทเพจเพื่อสอบถามเมนู",
};
try {
await step("app-health", async () => requireStatus(await request("/api/health", null, null, "GET"), 200));
const fixtures = resume ? null : await step("local-fixtures", async () => {
const salt = randomBytes(16);
const password = randomBytes(24).toString("base64url");
const passwordHash = `scrypt:${salt.toString("hex")}:${scryptSync(password, salt, 64).toString("hex")}`;
const users = {};
for (const role of ["manager", "viewer", "outsider"]) {
users[role] = await prisma.user.create({ data: { email: `${runId}-${role}@pagiva-e2e.test`, name: `E2E ${role}`, passwordHash } });
}
const iv = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", createHash("sha256").update(config.TOKEN_ENCRYPTION_KEY).digest(), iv);
const ciphertext = Buffer.concat([cipher.update("synthetic-test-token-never-send-to-meta"), cipher.final()]);
const tokenCipher = ["v1", iv.toString("base64url"), cipher.getAuthTag().toString("base64url"), ciphertext.toString("base64url")].join(":");
const page = await prisma.page.create({ data: {
name: "[E2E สมมติ] แก้วฟ้า คาเฟ่", fbPageId: runId, tokenCipher,
members: { create: [{ userId: users.manager.id, role: "MANAGER" }, { userId: users.viewer.id, role: "VIEWER" }] },
} });
await prisma.auditLog.create({ data: { pageId: page.id, actorId: users.manager.id, actorLabel: "E2E manager", action: "E2E_FIXTURE_CREATED", detail: { synthetic: true, runId } } });
await writeFile(path.join(privateDir, "credentials.json"), JSON.stringify({ runId, users, password, pageId: page.id }, null, 2));
return { page, users, password };
});
const savedFixtures = resume ? JSON.parse(await readFile(path.join(privateDir, "credentials.json"), "utf8")) : null;
const currentFixtures = fixtures || { ...savedFixtures, page: { id: savedFixtures.pageId } };
assert.equal(resume ? savedFixtures.runId : runId, runId, "Resume fixtures must belong to the same run");
report.pageId = currentFixtures.page.id;
report.profile = profile;
const cookies = await step("real-login", async () => {
const result = {};
for (const role of ["manager", "viewer", "outsider"]) {
const login = await request("/api/auth/login", { email: currentFixtures.users[role].email, password: currentFixtures.password });
requireStatus(login, 200);
result[role] = login.response.headers.getSetCookie().find((value) => value.startsWith("pm_session=")).split(";")[0];
}
await writeFile(path.join(privateDir, "manager-cookie.txt"), result.manager);
return result;
});
const pageId = currentFixtures.page.id;
await step("page-authorization", async () => {
const body = { pageId, action: "prompt", description: "Test" };
const previousUsage = await prisma.aiUsage.count({ where: { pageId } });
requireStatus(await request("/api/ai/image", body), 401);
requireStatus(await request("/api/ai/image", body, cookies.outsider), 404);
requireStatus(await request("/api/ai/image", body, cookies.viewer), 403);
assert.equal(await prisma.aiUsage.count({ where: { pageId } }), previousUsage);
});
await step("save-complete-shop-profile", async () => requireStatus(await request(`/api/pages/${pageId}/profile`, profile, cookies.manager, "PUT"), 200));
report.plan = (resume && report.plan) || await step("codex-week-plan", async () => {
const result = requireStatus(await request("/api/ai/week-plan", { pageId, week: "2026-11-23", count: 3, goal: "แนะนำลาเต้ร้อน 75 บาท ครัวซองต์ 85 บาท และบรรยากาศโต๊ะไม้ริมหน้าต่าง ไม่ทำโปรโมชั่น" }, cookies.manager), 200);
assert.equal(result.posts.length, 3);
assert.equal(result.profileMissing, false);
return result.posts;
});
report.captions = (resume && report.captions) || await step("codex-caption", async () => {
const result = requireStatus(await request("/api/ai/caption", { pageId, targets: ["FACEBOOK"], topic: "แนะนำลาเต้ร้อน 75 บาทและครัวซองต์เนย 85 บาท บนโต๊ะไม้ริมหน้าต่าง พร้อมชวนทักแชทเพจ" }, cookies.manager), 200);
assert.equal(result.variants.length, 3);
assert.equal(result.profileMissing, false);
return result.variants;
});
report.selectedCaption = report.captions[0].caption;
report.imagePrompt = (resume && report.imagePrompt) || await step("codex-image-prompt", async () => {
const result = requireStatus(await request("/api/ai/image", { pageId, action: "prompt", description: "ภาพถ่ายสินค้า ลาเต้ร้อนในแก้วเซรามิกสีฟ้าและครัวซองต์เนยหนึ่งชิ้นบนจานสีขาว วางบนโต๊ะไม้ริมหน้าต่าง แสงเช้าอบอุ่น ไม่มีคน ไม่มีตัวอักษร ไม่มีโลโก้ สำหรับโพสต์แนะนำเมนู" }, cookies.manager), 200);
assert.equal(result.profileMissing, false);
assert.ok(result.prompt.length > 100);
return result.prompt;
});
await checkpoint();
report.imageUrl = (resume && report.imageUrl) || await step("chatgpt-extension-image-through-app", async () => {
const result = requireStatus(await request("/api/ai/image", { pageId, action: "generate", prompt: report.imagePrompt, size: "square" }, cookies.manager), 200);
assert.equal(new URL(result.url).host, new URL(base).host);
return result.url;
});
await step("download-verify-actual-image", async () => {
const response = await fetch(report.imageUrl);
assert.equal(response.status, 200);
assert.match(response.headers.get("content-type"), /image\/jpeg/);
const bytes = Buffer.from(await response.arrayBuffer());
const metadata = await sharp(bytes).metadata();
assert.equal(metadata.width, 1024);
assert.equal(metadata.height, 1024);
assert.equal(metadata.format, "jpeg");
report.image = { width: metadata.width, height: metadata.height, bytes: bytes.length, sha256: createHash("sha256").update(bytes).digest("hex"), file: "image.jpg" };
await writeFile(path.join(outputDir, "image.jpg"), bytes);
});
report.review = (resume && report.review) || await step("codex-review-caption", async () => requireStatus(await request("/api/ai/check", { pageId, caption: report.selectedCaption, targets: ["FACEBOOK"], hasImage: true }, cookies.manager), 200));
report.post = (resume && report.post) || await step("save-draft-with-generated-image", async () => {
const result = requireStatus(await request("/api/posts", { pageId, title: "[E2E] ลาเต้และครัวซองต์ริมหน้าต่าง", caption: report.selectedCaption, imageBlobUrl: report.imageUrl, targets: ["FACEBOOK"], plannedAt: "2026-11-23T03:00:00.000Z", aiAssisted: true }, cookies.manager), 201);
assert.equal(result.post.status, "DRAFT");
assert.equal(result.post.aiAssisted, true);
assert.equal(result.post.imageBlobUrl, report.imageUrl);
return { id: result.post.id, title: result.post.title, status: result.post.status, aiAssisted: result.post.aiAssisted, targets: result.post.targets, plannedAt: result.post.plannedAt };
});
await step("verify-persistence-usage-and-audit", async () => {
const post = await prisma.post.findUniqueOrThrow({ where: { id: report.post.id } });
assert.equal(post.fbPostId, null);
assert.equal(post.igMediaId, null);
assert.equal(post.scheduledPublishAt, null);
assert.equal(post.status, "DRAFT");
report.post = { ...report.post, targets: post.targets, plannedAt: post.plannedAt, scheduledPublishAt: post.scheduledPublishAt };
report.usage = await prisma.aiUsage.groupBy({ by: ["kind"], where: { pageId }, _count: true });
assert.ok(report.usage.some((item) => item.kind === "image" && item._count === 1));
report.audit = await prisma.auditLog.findMany({ where: { pageId }, select: { action: true, detail: true, createdAt: true }, orderBy: { createdAt: "asc" } });
assert.ok(report.audit.some((item) => item.action === "PAGE_PROFILE_SAVED"));
assert.ok(report.audit.some((item) => item.action === "POST_CREATED" && item.detail?.aiAssisted));
const loaded = requireStatus(await request(`/api/posts?pageId=${pageId}`, null, cookies.manager, "GET"), 200);
assert.ok(loaded.posts.some((item) => item.id === report.post.id));
report.postUrl = `${base}/posts/${post.id}`;
});
await step("render-editor-desktop-and-mobile", async () => {
const browser = await chromium.launch({ channel: "chrome", headless: true });
try {
const context = await browser.newContext({ viewport: { width: 1440, height: 1100 } });
const login = await context.request.post(`${base}/api/auth/login`, { data: { email: currentFixtures.users.manager.email, password: currentFixtures.password } });
assert.equal(login.status(), 200);
const page = await context.newPage();
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.goto(report.postUrl, { waitUntil: "networkidle" });
assert.ok(page.url().includes(`/posts/${report.post.id}`), "Editor must load after real browser login");
await page.waitForFunction((caption) => [...document.querySelectorAll("textarea")].some((item) => item.value === caption), report.selectedCaption);
const image = page.locator(`img[src="${report.imageUrl}"]`).first();
await image.waitFor({ state: "visible" });
await page.waitForFunction((url) => [...document.images].some((item) => item.src === url && item.complete && item.naturalWidth === 1024), report.imageUrl);
await page.screenshot({ path: path.join(outputDir, "editor-desktop.png"), fullPage: true });
await page.setViewportSize({ width: 390, height: 844 });
await page.screenshot({ path: path.join(outputDir, "editor-mobile.png"), fullPage: true });
assert.deepEqual(errors, []);
report.ui = { editorUrl: page.url(), imageLoaded: true, javascriptErrors: errors, screenshots: ["editor-desktop.png", "editor-mobile.png"] };
} finally { await browser.close(); }
});
report.finalChecks = Object.values(Object.fromEntries(report.steps.map((item) => [item.name, item])));
assert.ok(report.finalChecks.every((item) => item.status === "passed"));
report.status = "passed";
report.finishedAt = new Date().toISOString();
await checkpoint();
const readable = [
"ผลทดสอบ PAGIVA ตั้งแต่ข้อมูลร้านจนถึงรูปภาพ — ข้อมูลร้านทั้งหมดเป็นข้อมูลสมมติ",
`Run: ${runId}`,
`ผล: ${report.status} (${report.finalChecks.length} ขั้นตอนผ่าน)`,
"\n1. ข้อมูลร้าน",
...Object.entries(profile).map(([key, value]) => `${key}: ${value}`),
"\n2. แผนโพสต์",
...report.plan.map((post) => `${post.day} — ${post.title} (${post.pillar})\n${post.caption}\n`),
"\n3. Caption ทางเลือก",
...report.captions.map((variant) => `${variant.angle}\n${variant.caption}\n`),
"\n4. Caption ที่เลือก",
report.selectedCaption,
"\n5. พรอมต์ภาพที่ Codex สร้างและส่งเข้า ChatGPT extension",
report.imagePrompt,
"\n6. ภาพที่ได้",
`ไฟล์: image.jpg (${report.image.width} × ${report.image.height}, ${report.image.bytes} bytes)`,
`URL ในระบบทดสอบ: ${report.imageUrl}`,
"\n7. ผลตรวจ caption",
report.review.summary,
...report.review.issues.map((issue) => `${issue.level}: ${issue.problem} → ${issue.suggestion}`),
"\n8. โพสต์ที่บันทึก",
`${report.post.title} — ${report.post.status} — AI assisted: ${report.post.aiAssisted}`,
`ช่องทาง: ${report.post.targets.join(", ")}; วันที่วางแผน: ${report.post.plannedAt}; ยังไม่ตั้งเวลาเผยแพร่`,
`Editor: ${report.postUrl}`,
"\n9. การตรวจสอบ",
...report.finalChecks.map((check) => `${check.name}: ${check.status}`),
"\nภาพหน้า editor: editor-desktop.png, editor-mobile.png",
"รายละเอียดและประวัติการทดสอบซ้ำ: result.json",
"ทดสอบกับ DB local และเพจสมมติเท่านั้น ไม่ได้ส่งโพสต์ออก Facebook/Instagram",
].join("\n");
await writeFile(path.join(outputDir, "report.txt"), readable);
console.log(`Full AI flow passed. Results: ${path.join(outputDir, "result.json")}`);
} catch (error) {
report.status = "failed";
await checkpoint();
console.error(error);
process.exitCode = 1;
} finally {
await prisma.$disconnect();
}