6994ba1a4e
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>
80 lines
3.8 KiB
JavaScript
80 lines
3.8 KiB
JavaScript
import assert from "node:assert/strict";
|
|
import { readFileSync } from "node:fs";
|
|
import ts from "typescript";
|
|
|
|
// Run the real route and provider code with isolated dependencies, without API charges or a database.
|
|
function load(file, dependencies) {
|
|
const source = readFileSync(new URL(file, import.meta.url), "utf8");
|
|
const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText;
|
|
const exports = {};
|
|
new Function("exports", "require", compiled)(exports, (name) => {
|
|
assert.ok(name in dependencies, `Unexpected dependency: ${name}`);
|
|
return dependencies[name];
|
|
});
|
|
return exports;
|
|
}
|
|
class UserFacingError extends Error {}
|
|
const shared = load("../src/lib/ai/image-shared.ts", {});
|
|
let count = 0;
|
|
let allowed = true;
|
|
let generated = 0;
|
|
let stored = 0;
|
|
let recorded = 0;
|
|
const prisma = {
|
|
aiUsage: { count: async () => count, create: async () => { recorded++; } },
|
|
page: { findUnique: async () => ({ profile: null }) },
|
|
};
|
|
let automationCalls = 0;
|
|
const provider = load("../src/lib/ai/image.ts", {
|
|
"@/lib/db": { prisma },
|
|
"@/lib/facebook/client": { UserFacingError },
|
|
"./image-shared": shared,
|
|
"./automation": { runAutomation: async (body) => { automationCalls++; assert.equal(body.kind, "image"); return { b64: Buffer.from("image").toString("base64") }; } },
|
|
});
|
|
const { POST } = load("../src/app/api/ai/image/route.ts", {
|
|
"next/server": { NextResponse: { json: (data, init) => Response.json(data, init) } },
|
|
"zod/v4": await import("zod/v4"),
|
|
"@/lib/base-path": { appUrl: (origin) => origin },
|
|
"@/lib/db": { prisma },
|
|
"@/lib/auth/user": { requirePageAction: async (pageId, action) => {
|
|
assert.equal(pageId, "page-a");
|
|
assert.equal(action, "editPost");
|
|
return allowed ? { ok: true, user: { id: "user-a" } } : { ok: false, response: Response.json({}, { status: 404 }) };
|
|
} },
|
|
"@/lib/http": { readJson: (req) => req.json(), str: (v) => typeof v === "string" ? v : "", errorResponse: () => Response.json({}, { status: 400 }) },
|
|
"@/lib/facebook/client": { UserFacingError },
|
|
"@/lib/ai/claude": { generateStructured: async () => ({ prompt: "Soft natural light, a cake on a wooden table." }) },
|
|
"@/lib/ai/shared": { profilePrompt: () => "" },
|
|
"@/lib/ai/image-shared": shared,
|
|
"@/lib/ai/image": { assertImageQuota: provider.assertImageQuota, generateImage: async () => {
|
|
generated++;
|
|
return { bytes: Buffer.from("image"), contentType: "image/jpeg", inputTokens: 1, outputTokens: 2 };
|
|
} },
|
|
"@/lib/storage/blob": { putBlob: async () => { stored++; return { url: "https://example.test/image.jpg" }; } },
|
|
});
|
|
const request = (body) => POST(new Request("https://example.test/api/ai/image", {
|
|
method: "POST", body: JSON.stringify({ pageId: "page-a", ...body }),
|
|
}));
|
|
const valid = { action: "generate", prompt: "A cake", size: "square" };
|
|
allowed = false;
|
|
assert.equal((await request(valid)).status, 404);
|
|
allowed = true;
|
|
for (const body of [
|
|
{ ...valid, size: "__proto__" }, { ...valid, size: "portrait" },
|
|
{ ...valid, prompt: " " }, { ...valid, prompt: "x".repeat(4001) },
|
|
{ action: "prompt", description: "x".repeat(1001) }, { action: "unknown" },
|
|
]) assert.equal((await request(body)).status, 400);
|
|
count = 10;
|
|
assert.equal((await request(valid)).status, 400);
|
|
assert.equal(generated, 0);
|
|
count = 9;
|
|
assert.equal((await request(valid)).status, 200);
|
|
assert.deepEqual([generated, stored, recorded], [1, 1, 1]);
|
|
const prompt = await (await request({ action: "prompt", description: "Cake" })).json();
|
|
assert.equal(prompt.profileMissing, true);
|
|
assert.ok(prompt.prompt);
|
|
|
|
assert.equal((await provider.generateImage("Cake", "landscape")).bytes.toString(), "image");
|
|
assert.equal(automationCalls, 1);
|
|
console.log("AI image checks passed: page authorization, input validation, quota, storage, usage, browser-worker bridge.");
|