diff --git a/server/Turtle.js b/server/Turtle.js index 4356608..798b6a4 100644 --- a/server/Turtle.js +++ b/server/Turtle.js @@ -290,6 +290,8 @@ export class Turtle extends EventEmitter { */ async _runStateLoop() { const state = this._state; + let consecutiveErrors = 0; + const MAX_CONSECUTIVE_ERRORS = 5; try { const generator = state.act(); @@ -299,9 +301,23 @@ export class Turtle extends EventEmitter { if (this._state !== state) { return; // State changed, stop this generator } + // Reset error counter on successful iteration + consecutiveErrors = 0; } } catch (error) { - if (this._state === state) { + if (this._state !== state) return; + + consecutiveErrors++; + const isTimeout = error.message?.includes('timed out'); + + if (isTimeout && consecutiveErrors < MAX_CONSECUTIVE_ERRORS) { + console.warn(`[Turtle ${this.id}] Timeout in ${state.name} (${consecutiveErrors}/${MAX_CONSECUTIVE_ERRORS}), retrying...`); + // Wait a bit then restart the state loop + await new Promise(r => setTimeout(r, 2000)); + if (this._state === state) { + this._runStateLoop(); // Restart the loop with the same state + } + } else { console.error(`[Turtle ${this.id}] State error in ${state.name}:`, error.message); this.setState('idle'); }