From 135d720ab081be34debe6f82c73758bb624bcefb Mon Sep 17 00:00:00 2001 From: Charlie Tonneslan Date: Tue, 17 Mar 2026 18:19:49 -0400 Subject: [PATCH] fix: respect AbortSignal in run() - throw on pre-aborted and mid-poll abort run() ignores AbortSignal in two ways: 1. If signal is already aborted before calling run(), the prediction starts anyway instead of throwing immediately 2. If signal becomes aborted during polling, run() cancels the prediction but returns the result instead of throwing AbortError Now checks signal.aborted before starting the prediction and throws AbortError after cancellation instead of silently returning output. The cancel call is wrapped in catch to handle cases where the prediction already completed on Replicate's servers. Fixes #370 --- index.js | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 3fc14dd..fbd6bcd 100644 --- a/index.js +++ b/index.js @@ -145,6 +145,13 @@ class Replicate { async run(ref, options, progress) { const { wait = { mode: "block" }, signal, ...data } = options; + // Throw immediately if signal is already aborted + if (signal?.aborted) { + const error = new Error("Aborted"); + error.name = "AbortError"; + throw error; + } + const identifier = ModelVersionIdentifier.parse(ref); let prediction; @@ -191,7 +198,10 @@ class Replicate { } if (signal && signal.aborted) { - prediction = await this.predictions.cancel(prediction.id); + await this.predictions.cancel(prediction.id).catch(() => {}); + const error = new Error("Aborted"); + error.name = "AbortError"; + throw error; } // Call progress callback with the completed prediction object