Show milestone progress bar for post generation queue jobs

Add percentage-by-stage progress in the queue UI, a progress rendering
test script, and clearer Chrome focus error details in the ChatGPT worker.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Loma Bot Ops
2026-11-23 15:36:52 +07:00
parent 53d39ae4cd
commit 4c691b5dde
6 changed files with 97 additions and 4 deletions
+1
View File
@@ -46,6 +46,7 @@
- สร้าง caption และพรอมต์ภาพด้วย Codex จากนั้นสร้างภาพผ่าน extension และบันทึก Post เป็น DRAFT พร้อม aiAssisted, AiUsage และ audit ทุก transition ไม่อนุมัติหรือเผยแพร่เอง
- มี heartbeat ทุก 20 วินาที งาน RUNNING ที่ heartbeat หายเกิน 20 นาทีจะเป็น FAILED พร้อมข้อความให้ตรวจสอบก่อนสั่งใหม่ ไม่มี retry สร้างภาพอัตโนมัติหลัง timeout เพื่อไม่ให้เสียโควตาซ้ำ
- หน้าเว็บแสดงเวลารวมจากรับคิวจนเสร็จจริง เวลารอขึ้นกับจำนวนงานก่อนหน้า บัญชี ChatGPT และระยะเวลาสร้างภาพ ไม่รับประกันเวลาเท่ากันทุกงาน
- UI แสดง progress bar และเปอร์เซ็นต์ตาม milestone: รอคิว 0%, เขียนเนื้อหา 10%, สร้างภาพ 50%, บันทึก 90%, สำเร็จ 100% เป็นความคืบหน้าตามขั้นตอน ไม่ใช่เปอร์เซ็นต์การ render จาก ChatGPT และไม่เพิ่มตัวเลขตามเวลาเพื่อจำลองความคืบหน้า
- deploy ต้องรัน `npx prisma migrate deploy` ก่อน และให้ reverse proxy รองรับคำขอ worker ได้นานอย่างน้อย 900 วินาที Browser automation ต้องใช้ desktop session ที่ปลดล็อก
ทดสอบคิว/จับเวลาจริง: `node scripts/check-post-queue.mjs` ใช้ฐาน PostgreSQL local แยกตาม `.data/queue/runtime.json` และบัญชีทดสอบจาก `.data/e2e/credentials.json` ทดสอบกดปุ่มผ่าน browser, กดซ้ำพร้อมกัน, ปิด/เปิดหน้า, ยกเลิก, เพิกถอนสิทธิ์, stale worker, restart worker และสร้างโพสต์พร้อมภาพสองงานตามลำดับ ผลและเวลาอยู่ที่ `output/automation/queue/report.txt` และ `result.json` ไม่ใช้ฐาน production
+1 -1
View File
@@ -23,7 +23,7 @@ function Focus-Chrome {
Start-Sleep -Milliseconds 300
[uint32]$foregroundProcessId = 0
[ChatGptWindow]::GetWindowThreadProcessId([ChatGptWindow]::GetForegroundWindow(),[ref]$foregroundProcessId) | Out-Null
if ($foregroundProcessId -ne $browser.Id) { throw "Chrome could not take foreground focus; refusing to send keystrokes to another application." }
if ($foregroundProcessId -ne $browser.Id) { throw "Chrome could not take foreground focus (target=$($browser.Id), foreground=$foregroundProcessId); refusing to send keystrokes to another application." }
}
function Get-Controls {
$root = [System.Windows.Automation.AutomationElement]::FromHandle($browser.MainWindowHandle)
+64
View File
@@ -0,0 +1,64 @@
import "dotenv/config";
import assert from "node:assert/strict";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { chromium } from "playwright";
import { PrismaClient } from "@prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
// Rendering test only: simulated API responses do not claim or generate real jobs.
const config = JSON.parse(await readFile(".data/queue/runtime.json", "utf8"));
const credentials = JSON.parse(await readFile(".data/e2e/credentials.json", "utf8"));
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: config.DATABASE_URL }) });
const directory = path.resolve("output/automation/queue/progress");
await mkdir(directory, { recursive: true });
let browser;
try {
const completed = await db.postGenerationJob.findFirstOrThrow({ where: { status: "COMPLETED" }, orderBy: { finishedAt: "desc" }, select: { id: true, pageId: true, topic: true, stage: true, status: true, postId: true, error: true, createdAt: true, startedAt: true, finishedAt: true } });
const usageBefore = await db.aiUsage.count();
browser = await chromium.launch({ channel: "chrome", headless: true });
const context = await browser.newContext({ viewport: { width: 1440, height: 1100 } });
const login = await context.request.post(`${config.NEXT_PUBLIC_APP_URL}/api/auth/login`, { data: { email: credentials.users.manager.email, password: credentials.password } });
assert.equal(login.status(), 200);
const page = await context.newPage();
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
let fixture;
const pattern = "**/api/ai/post-jobs?pageId=*";
await page.route(pattern, (route) => route.fulfill({ json: { jobs: [fixture] } }));
const results = [];
for (const [status, stage, expected] of [["QUEUED", "queued", 0], ["RUNNING", "content", 10], ["RUNNING", "image", 50], ["RUNNING", "saving", 90], ["COMPLETED", "completed", 100]]) {
fixture = { ...completed, topic: "ทดสอบเปอร์เซ็นต์ตามขั้นตอน (ข้อมูลจำลองเฉพาะ UI)", status, stage };
await page.goto(`${config.NEXT_PUBLIC_APP_URL}/posts/new`, { waitUntil: "networkidle" });
await page.locator("select").first().selectOption(completed.pageId);
const bar = page.getByRole("progressbar", { name: `ความคืบหน้าของ ${fixture.topic}`, exact: true });
await bar.waitFor({ state: "visible" });
assert.equal(await bar.getAttribute("value"), String(expected));
assert.equal(await bar.getAttribute("max"), "100");
await page.getByText(`${expected}%`, { exact: true }).waitFor();
const ariaText = await bar.getAttribute("aria-valuetext");
assert.ok(ariaText.startsWith(`${expected}%`));
await page.screenshot({ path: path.join(directory, `stage-${expected}.png`), fullPage: true });
if (expected === 50) {
await page.setViewportSize({ width: 390, height: 844 });
await page.screenshot({ path: path.join(directory, "stage-50-mobile.png"), fullPage: true });
await page.setViewportSize({ width: 1440, height: 1100 });
}
results.push({ status, stage, expected, rendered: Number(await bar.getAttribute("value")), ariaText, simulatedRendering: true });
console.log(`Progress UI passed: ${stage} ${expected}%`);
}
await page.unroute(pattern);
await page.reload({ waitUntil: "networkidle" });
await page.locator("select").first().selectOption(completed.pageId);
const real = page.getByRole("progressbar", { name: `ความคืบหน้าของ ${completed.topic}`, exact: true });
await real.waitFor({ state: "visible" });
assert.equal(await real.getAttribute("value"), "100");
await page.screenshot({ path: path.join(directory, "real-completed-job.png"), fullPage: true });
assert.equal(await db.aiUsage.count(), usageBefore, "Rendering tests must not consume AI usage");
assert.deepEqual(errors, []);
await writeFile(path.join(directory, "result.json"), JSON.stringify({ status: "passed", stages: results, verifiedRealCompletedJobId: completed.id, realCompletedPercent: 100, javascriptErrors: errors, aiCalls: 0 }, null, 2));
console.log("Progress UI passed: all five milestones, mobile, real completed job, no AI calls.");
} finally {
await browser?.close();
await db.$disconnect();
}
+17 -1
View File
@@ -59,7 +59,9 @@ try {
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");
const managedUrl = new URL(managed.pm2_env.POST_QUEUE_APP_URL || process.env.POST_QUEUE_APP_URL || "");
assert.ok(["localhost", "127.0.0.1"].includes(managedUrl.hostname), "Never pause a worker targeting a remote app");
assert.equal(await prisma.postGenerationJob.count({ where: { status: { in: ["QUEUED", "RUNNING"] } } }), 0, "Do not interrupt a live queue");
await pm2Call("stop", "page-post-generation"); restorePm2 = true;
}
const cookies = { manager: await login("manager"), viewer: await login("viewer"), outsider: await login("outsider") };
@@ -151,6 +153,18 @@ try {
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 && ["content", "image"].includes(running.stage)) {
const minimum = running.stage === "content" ? 10 : 50;
report.progressScreenshots ??= [];
if (!report.progressScreenshots.includes(minimum)) {
const label = `ความคืบหน้าของ ${topicA}`;
await tab.waitForFunction(({ label, minimum }) => [...document.querySelectorAll("progress")].some((element) => element.getAttribute("aria-label") === label && element.value >= minimum), { label, minimum }, { timeout: 15_000 });
const bar = tab.getByRole("progressbar", { name: label, exact: true });
assert.equal(await bar.getAttribute("max"), "100");
await tab.screenshot({ path: path.join(directory, `running-${minimum}.png`), fullPage: true });
report.progressScreenshots.push(minimum);
}
}
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)]);
@@ -194,6 +208,8 @@ try {
await tab.reload({ waitUntil: "networkidle" });
await tab.getByRole("link", { name: "เปิดฉบับร่าง" }).first().waitFor();
assert.equal(await tab.getByRole("link", { name: "เปิดฉบับร่าง" }).count(), 2);
assert.equal(await tab.getByText("100%", { exact: true }).count(), 2);
for (const bar of await tab.getByRole("progressbar").all()) assert.equal(await bar.getAttribute("value"), "100");
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 });
+6 -1
View File
@@ -3,7 +3,7 @@
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 { POST_JOB_STAGE, POST_JOB_STATUS, postJobProgress, type PostJobView } from "@/lib/ai/post-queue-shared";
import { Icon } from "./Icon";
import { Notice } from "./ui";
@@ -93,12 +93,17 @@ export function PostGenerationQueue({ pageId, targets, plannedDay, initialTopic
{pollError && <p role="status" className="text-[12px] text-ink-2">ยังอัปเดตคิวไม่ได้ ระบบกำลังลองเชื่อมต่อใหม่ งานที่รับไว้ยังอยู่ในคิว</p>}
{jobs.length > 0 && <>
<h4 className="font-semibold text-[13px] pt-2">งานล่าสุดของเพจนี้</h4>
<p className="text-[12px] text-ink-2">เปอร์เซ็นต์อิงตามขั้นตอน อาจคงที่ระหว่างรอสร้างภาพ</p>
<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 !== "CANCELLED" && job.status !== "FAILED" && <div className="flex items-center gap-3">
<progress className="h-2 w-full flex-1 min-w-0 appearance-none overflow-hidden rounded-full bg-line [&::-webkit-progress-bar]:bg-line [&::-webkit-progress-value]:bg-blue [&::-moz-progress-bar]:bg-blue" value={postJobProgress(job)} max={100} aria-label={`ความคืบหน้าของ ${job.topic}`} aria-valuetext={`${postJobProgress(job)}% · ${POST_JOB_STAGE[job.stage] || POST_JOB_STATUS[job.status]}`} />
<span className="text-[12px] font-semibold num text-ink-2">{postJobProgress(job)}%</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">
+8 -1
View File
@@ -7,7 +7,7 @@ export const POST_JOB_STATUS = {
} as const;
export const POST_JOB_STAGE: Record<string, string> = {
queued: "รอ worker รับงาน",
queued: "รอเริ่มสร้างโพสต์",
content: "Codex กำลังเขียนเนื้อหาและพรอมต์ภาพ",
image: "ChatGPT กำลังสร้างภาพ",
saving: "กำลังบันทึกฉบับร่าง",
@@ -24,3 +24,10 @@ export interface PostJobView {
startedAt: string | null;
finishedAt: string | null;
}
/** Milestones, not an estimate of the image model's internal rendering progress. */
export function postJobProgress(job: Pick<PostJobView, "status" | "stage">): number {
if (job.status === "COMPLETED") return 100;
if (job.status === "QUEUED" || job.status === "CANCELLED") return 0;
return ({ content: 10, image: 50, saving: 90 } as Record<string, number>)[job.stage] ?? 0;
}