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:
dasemuandClaude Opus 5.5 committed 2026-10-07 17:24:05 +02:00
1 parent d751acfe63
commit f7e7148135
7 files changed
+83 -15

No files matched your search

+4
View File
@@ -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,
+21
View File
@@ -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
View File
@@ -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
View File
@@ -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 };
}