mirror of
https://github.com/Dasemu/chatgpt-imagegen-mcp.git
synced 2026-11-26 23:36:26 +00:00
feat: retry transient chatgpt.com failures in a fresh chat
Timeouts, UI glitches, text-only replies and browser errors get up to CHATGPT_RETRIES extra attempts with a growing pause; a crashed browser is relaunched. Usage limits, lost sessions and refusals still fail at once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d751acfe63
commit
f7e7148135
7 files changed
+83
-15
No files matched your search
@@ -33,6 +33,10 @@ CHATGPT_USER_AGENT=
|
||||
CHATGPT_LOCALE=es-ES
|
||||
CHATGPT_TURN_TIMEOUT_SECONDS=600
|
||||
CHATGPT_IMAGE_TIMEOUT_SECONDS=180
|
||||
# Extra attempts (each in a new chat) for transient failures: timeouts, UI glitches, browser errors
|
||||
CHATGPT_RETRIES=2
|
||||
# Backoff base between attempts (multiplied by the attempt number)
|
||||
CHATGPT_RETRY_DELAY_SECONDS=15
|
||||
CHATGPT_BROWSER_IDLE_CLOSE_MINUTES=10
|
||||
# Random pause between generations, in seconds (min..max)
|
||||
CHATGPT_MIN_INTERVAL_SECONDS=30
|
||||
|
||||
@@ -20,6 +20,8 @@ MCP client ──POST /mcp──▶ tools.ts ──▶ JobManager (serial queue,
|
||||
6. Wait for a new image outside the user message, at least 256 px per side, fully loaded, with a `src` that stays the same for 3 polls and no "creating image" text. ChatGPT shows blurred partial previews first, so the first image seen is not the final one.
|
||||
7. Download it through the browser request context (it carries the session cookies), validate size and format, store it as `<generationId>-<index>.<ext>`.
|
||||
|
||||
Transient failures (`TURN_TIMED_OUT`, `UI_CHANGED`, `NO_IMAGE_RETURNED`, `BROWSER_ERROR`, generic ChatGPT errors) are retried up to `CHATGPT_RETRIES` times, each in a new chat with a growing pause (`CHATGPT_RETRY_DELAY_SECONDS × attempt`); a crashed browser is relaunched first. Usage limits, lost sessions and content-policy refusals fail immediately. The final error message says how many attempts were made.
|
||||
|
||||
`image_count > 1` repeats this in a new chat per image. Every job runs alone because the profile can only be used by one browser.
|
||||
|
||||
## Lineage
|
||||
|
||||
@@ -9,6 +9,8 @@ export interface ChatGptConfig {
|
||||
locale: string;
|
||||
turnTimeoutMs: number;
|
||||
imageTimeoutMs: number;
|
||||
retries: number;
|
||||
retryDelayMs: number;
|
||||
browserIdleCloseMs: number;
|
||||
diagnosticsDir: string;
|
||||
maxDiagnostics: number;
|
||||
@@ -24,6 +26,8 @@ export function loadChatGptConfig(env: NodeJS.ProcessEnv = process.env): ChatGpt
|
||||
locale: env.CHATGPT_LOCALE || "es-ES",
|
||||
turnTimeoutMs: (Number(env.CHATGPT_TURN_TIMEOUT_SECONDS) || 600) * 1000,
|
||||
imageTimeoutMs: (Number(env.CHATGPT_IMAGE_TIMEOUT_SECONDS) || 180) * 1000,
|
||||
retries: env.CHATGPT_RETRIES === undefined || env.CHATGPT_RETRIES === "" ? 2 : Math.max(0, Math.floor(Number(env.CHATGPT_RETRIES)) || 0),
|
||||
retryDelayMs: (Number(env.CHATGPT_RETRY_DELAY_SECONDS) || 15) * 1000,
|
||||
browserIdleCloseMs: (Number(env.CHATGPT_BROWSER_IDLE_CLOSE_MINUTES) || 10) * 60 * 1000,
|
||||
diagnosticsDir: path.resolve(env.DIAGNOSTICS_DIR || "diagnostics"),
|
||||
maxDiagnostics: Number(env.MAX_DIAGNOSTICS) || 10,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { JobError } from "../types.js";
|
||||
|
||||
export class ImageGenerationError extends Error {
|
||||
constructor(message: string, readonly code = "GENERATION_FAILED") {
|
||||
super(message);
|
||||
@@ -30,3 +32,22 @@ export class TurnTimedOut extends ImageGenerationError {
|
||||
super(message, "TURN_TIMED_OUT");
|
||||
}
|
||||
}
|
||||
|
||||
/** Codes worth another attempt in a fresh chat before the job is reported as failed. */
|
||||
export const IN_SERVER_RETRY_CODES = new Set(["TURN_TIMED_OUT", "GENERATION_FAILED", "NO_IMAGE_RETURNED", "UI_CHANGED", "BROWSER_ERROR"]);
|
||||
|
||||
/** Browser-level failures after which the context should be relaunched. */
|
||||
export function isBrowserCrash(error: unknown): boolean {
|
||||
return /Target page, context or browser has been closed|Browser has been closed|browser has disconnected/i.test(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
|
||||
export function toJobError(error: unknown): JobError {
|
||||
const message = (error instanceof Error ? error.message : String(error)).slice(0, 2000);
|
||||
if (error instanceof ImageGenerationError) {
|
||||
const retryable = ["USAGE_LIMIT_REACHED", "TURN_TIMED_OUT", "GENERATION_FAILED", "NO_IMAGE_RETURNED"].includes(error.code);
|
||||
return { code: error.code, message, retryable };
|
||||
}
|
||||
if (/Timeout|net::ERR_|Target page, context or browser has been closed/i.test(message)) return { code: "BROWSER_ERROR", message, retryable: true };
|
||||
if (/Executable doesn't exist|ProcessSingleton|SingletonLock|profile.*in use/i.test(message)) return { code: "SERVER_NOT_CONFIGURED", message, retryable: false };
|
||||
return { code: "GENERATION_FAILED", message, retryable: false };
|
||||
}
|
||||
+25
-3
@@ -8,7 +8,7 @@ import {
|
||||
attachReferences, Diagnostics, downloadImage, imageSources, isLoggedIn, openNewChat, sendMessage, waitForGeneratedImage, waitForTurnComplete,
|
||||
} from "./client.js";
|
||||
import { loadChatGptConfig, type ChatGptConfig } from "./config.js";
|
||||
import { ImageGenerationError, TurnTimedOut } from "./errors.js";
|
||||
import { ImageGenerationError, IN_SERVER_RETRY_CODES, isBrowserCrash, toJobError, TurnTimedOut } from "./errors.js";
|
||||
import { buildImageRequest } from "./prompts.js";
|
||||
|
||||
export const MIN_IMAGE_BYTES = 20_000;
|
||||
@@ -32,10 +32,9 @@ export class ChatGptImageProvider implements ImageProvider {
|
||||
async generateImages(generationId: string, request: ImageRequest): Promise<StoredOutput[]> {
|
||||
const outputs: StoredOutput[] = [];
|
||||
try {
|
||||
const page = await this.browser.page();
|
||||
for (let index = 0; index < request.imageCount; index += 1) {
|
||||
const started = Date.now();
|
||||
const image = await this.generateOne(page, request);
|
||||
const image = await this.generateWithRetries(generationId, index, request);
|
||||
outputs.push(await storeImage(generationId, index, image));
|
||||
audit("chatgpt_image_generated", { generationId, index, sizeBytes: image.length, durationMs: Date.now() - started });
|
||||
}
|
||||
@@ -67,6 +66,24 @@ export class ChatGptImageProvider implements ImageProvider {
|
||||
await this.browser.close();
|
||||
}
|
||||
|
||||
/** Transient failures get another attempt in a fresh chat; limits, logins and refusals do not. */
|
||||
private async generateWithRetries(generationId: string, index: number, request: ImageRequest): Promise<Buffer> {
|
||||
for (let attempt = 1; ; attempt += 1) {
|
||||
try {
|
||||
return await this.generateOne(await this.browser.page(), request);
|
||||
} catch (error) {
|
||||
if (attempt > this.config.retries || !isRetryableInServer(error)) {
|
||||
if (attempt > 1 && error instanceof Error) error.message += ` (after ${attempt} attempts)`;
|
||||
throw error;
|
||||
}
|
||||
const delayMs = this.config.retryDelayMs * attempt;
|
||||
audit("chatgpt_attempt_failed", { generationId, index, attempt, code: toJobError(error).code, retryInMs: delayMs });
|
||||
if (isBrowserCrash(error)) await this.browser.close();
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async generateOne(page: Page, request: ImageRequest): Promise<Buffer> {
|
||||
await openNewChat(page, this.config.url, this.diagnostics);
|
||||
const baseline = await imageSources(page);
|
||||
@@ -85,3 +102,8 @@ export class ChatGptImageProvider implements ImageProvider {
|
||||
return image;
|
||||
}
|
||||
}
|
||||
|
||||
export function isRetryableInServer(error: unknown): boolean {
|
||||
const { code } = toJobError(error);
|
||||
return IN_SERVER_RETRY_CODES.has(code) && (error instanceof ImageGenerationError || code === "BROWSER_ERROR");
|
||||
}
|
||||
+3
-12
@@ -1,12 +1,14 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import type { NormalizedArguments } from "./arguments.js";
|
||||
import { ImageGenerationError, SessionNotReady, UsageLimitReached } from "./chatgpt/errors.js";
|
||||
import { SessionNotReady, toJobError, UsageLimitReached } from "./chatgpt/errors.js";
|
||||
import type { ImageProvider } from "./chatgpt/provider.js";
|
||||
import { audit, auditError } from "./log.js";
|
||||
import { generationWasPurged, loadPersistedJob, loadPersistedJobs, outputExists, persistCompletedJob, purgeGeneration } from "./media.js";
|
||||
import type { GenerationJob, InlineReferenceImage, JobError, ReferenceImage } from "./types.js";
|
||||
|
||||
export { toJobError };
|
||||
|
||||
export interface JobManagerOptions {
|
||||
minIntervalMs: number;
|
||||
maxIntervalMs: number;
|
||||
@@ -271,14 +273,3 @@ function circuitError(circuit: Circuit): JobError {
|
||||
? { code: "USAGE_LIMIT_REACHED", message: "ChatGPT usage limit reached; generation paused", retryable: true, retryAfter: new Date(circuit.until).toISOString() }
|
||||
: { code: "SESSION_NOT_READY", message: "The ChatGPT profile is not logged in; an operator must run `npm run login`", retryable: false, retryAfter: new Date(circuit.until).toISOString() };
|
||||
}
|
||||
|
||||
export function toJobError(error: unknown): JobError {
|
||||
const message = (error instanceof Error ? error.message : String(error)).slice(0, 2000);
|
||||
if (error instanceof ImageGenerationError) {
|
||||
const retryable = ["USAGE_LIMIT_REACHED", "TURN_TIMED_OUT", "GENERATION_FAILED", "NO_IMAGE_RETURNED"].includes(error.code);
|
||||
return { code: error.code, message, retryable };
|
||||
}
|
||||
if (/Timeout|net::ERR_|Target page, context or browser has been closed/i.test(message)) return { code: "BROWSER_ERROR", message, retryable: true };
|
||||
if (/Executable doesn't exist|ProcessSingleton|SingletonLock|profile.*in use/i.test(message)) return { code: "SERVER_NOT_CONFIGURED", message, retryable: false };
|
||||
return { code: "GENERATION_FAILED", message, retryable: false };
|
||||
}
|
||||
@@ -411,3 +411,27 @@ describe("outputPayload", () => {
|
||||
assert.equal(inline.base64, png.toString("base64"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("in-server retries", async () => {
|
||||
const { isRetryableInServer } = await import("../src/chatgpt/provider.js");
|
||||
const { loadChatGptConfig } = await import("../src/chatgpt/config.js");
|
||||
|
||||
it("retries transient failures only", () => {
|
||||
assert.equal(isRetryableInServer(new TurnTimedOut("slow")), true);
|
||||
assert.equal(isRetryableInServer(new ImageGenerationError("x", "UI_CHANGED")), true);
|
||||
assert.equal(isRetryableInServer(new ImageGenerationError("x", "NO_IMAGE_RETURNED")), true);
|
||||
assert.equal(isRetryableInServer(new ImageGenerationError("something went wrong")), true);
|
||||
assert.equal(isRetryableInServer(new Error("page.goto: Timeout 60000ms exceeded")), true);
|
||||
assert.equal(isRetryableInServer(new UsageLimitReached("limit")), false);
|
||||
assert.equal(isRetryableInServer(new SessionNotReady()), false);
|
||||
assert.equal(isRetryableInServer(new ContentPolicyBlocked("no")), false);
|
||||
assert.equal(isRetryableInServer(new Error("unexpected bug")), false);
|
||||
});
|
||||
|
||||
it("reads retry configuration", () => {
|
||||
assert.equal(loadChatGptConfig({}).retries, 2);
|
||||
assert.equal(loadChatGptConfig({ CHATGPT_RETRIES: "0" }).retries, 0);
|
||||
assert.equal(loadChatGptConfig({ CHATGPT_RETRIES: "4" }).retries, 4);
|
||||
assert.equal(loadChatGptConfig({ CHATGPT_RETRY_DELAY_SECONDS: "5" }).retryDelayMs, 5000);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user