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 -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 });