From 4c691b5ddef4f31e9274bc3d3b446d85384a601c Mon Sep 17 00:00:00 2001 From: Loma Bot Ops Date: Mon, 23 Nov 2026 15:36:52 +0700 Subject: [PATCH] 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 --- docs/AI-AUTOMATION.md | 1 + scripts/chatgpt-chrome.ps1 | 2 +- scripts/check-post-queue-progress.mjs | 64 ++++++++++++++++++++++++++ scripts/check-post-queue.mjs | 18 +++++++- src/components/PostGenerationQueue.tsx | 7 ++- src/lib/ai/post-queue-shared.ts | 9 +++- 6 files changed, 97 insertions(+), 4 deletions(-) create mode 100644 scripts/check-post-queue-progress.mjs diff --git a/docs/AI-AUTOMATION.md b/docs/AI-AUTOMATION.md index c607834..edd9aeb 100644 --- a/docs/AI-AUTOMATION.md +++ b/docs/AI-AUTOMATION.md @@ -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 diff --git a/scripts/chatgpt-chrome.ps1 b/scripts/chatgpt-chrome.ps1 index 53cc3a9..92f8d57 100644 --- a/scripts/chatgpt-chrome.ps1 +++ b/scripts/chatgpt-chrome.ps1 @@ -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) diff --git a/scripts/check-post-queue-progress.mjs b/scripts/check-post-queue-progress.mjs new file mode 100644 index 0000000..b4e379d --- /dev/null +++ b/scripts/check-post-queue-progress.mjs @@ -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(); +} diff --git a/scripts/check-post-queue.mjs b/scripts/check-post-queue.mjs index ff8a3a0..8005603 100644 --- a/scripts/check-post-queue.mjs +++ b/scripts/check-post-queue.mjs @@ -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 }); diff --git a/src/components/PostGenerationQueue.tsx b/src/components/PostGenerationQueue.tsx index c6d5779..3d69e10 100644 --- a/src/components/PostGenerationQueue.tsx +++ b/src/components/PostGenerationQueue.tsx @@ -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 &&

ยังอัปเดตคิวไม่ได้ ระบบกำลังลองเชื่อมต่อใหม่ งานที่รับไว้ยังอยู่ในคิว

} {jobs.length > 0 && <>

งานล่าสุดของเพจนี้

+

เปอร์เซ็นต์อิงตามขั้นตอน อาจคงที่ระหว่างรอสร้างภาพ