Skip to content

Commit 135d720

Browse files
committed
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
1 parent 2fd6f39 commit 135d720

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

index.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,13 @@ class Replicate {
145145
async run(ref, options, progress) {
146146
const { wait = { mode: "block" }, signal, ...data } = options;
147147

148+
// Throw immediately if signal is already aborted
149+
if (signal?.aborted) {
150+
const error = new Error("Aborted");
151+
error.name = "AbortError";
152+
throw error;
153+
}
154+
148155
const identifier = ModelVersionIdentifier.parse(ref);
149156

150157
let prediction;
@@ -191,7 +198,10 @@ class Replicate {
191198
}
192199

193200
if (signal && signal.aborted) {
194-
prediction = await this.predictions.cancel(prediction.id);
201+
await this.predictions.cancel(prediction.id).catch(() => {});
202+
const error = new Error("Aborted");
203+
error.name = "AbortError";
204+
throw error;
195205
}
196206

197207
// Call progress callback with the completed prediction object

0 commit comments

Comments
 (0)