Skip to content

Commit f1ba2bc

Browse files
1220moritzclaude
andcommitted
fix(api): check Zoo Gateway cancellation before auth and during error notifications
- A pre-aborted signal rejects with an AbortError before the session check, so a cancel wins over a missing session. - The gateway error notification can wait for the user. Race it against the request signal, so an abort or timeout still settles at once with an AbortError. - Tests: no model lookup on a pre-aborted signal (with and without a session), an ordinary lookup failure is kept while the signal is live, a timeout during the SDK call, an abort while a notification waits, and removal of the same listener after success, failure, and abort. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 521f329 commit f1ba2bc

2 files changed

Lines changed: 81 additions & 12 deletions

File tree

‎src/api/providers/__tests__/zoo-gateway.spec.ts‎

Lines changed: 65 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -555,15 +555,67 @@ describe("ZooGatewayHandler", () => {
555555
expect(mockCreate.mock.calls[0][1]).toEqual({})
556556
})
557557

558-
it("rejects with an AbortError and sends no request when the signal is pre-aborted", async () => {
558+
it.each([
559+
["with a session", mockOptions],
560+
["without a session", { zooGatewayModelId: "anthropic/claude-sonnet-4" }],
561+
])(
562+
"rejects a pre-aborted signal with an AbortError, %s, before model lookup",
563+
async (_label, options: ApiHandlerOptions) => {
564+
const { getModels } = await import("../fetchers/modelCache")
565+
const handler = new ZooGatewayHandler(options)
566+
const caller = new AbortController()
567+
caller.abort()
568+
569+
await expect(handler.completePrompt("Test", { abortSignal: caller.signal })).rejects.toMatchObject({
570+
name: "AbortError",
571+
})
572+
expect(getModels).not.toHaveBeenCalled()
573+
expect(mockCreate).not.toHaveBeenCalled()
574+
},
575+
)
576+
577+
it("keeps an ordinary model lookup failure while the caller signal is live", async () => {
578+
const { getModels, refreshModels } = await import("../fetchers/modelCache")
579+
const lookupFailure = new Error("model catalog unavailable")
580+
vitest.mocked(getModels).mockRejectedValue(lookupFailure)
581+
vitest.mocked(refreshModels).mockRejectedValue(lookupFailure)
582+
const handler = new ZooGatewayHandler(mockOptions)
583+
584+
await expect(handler.completePrompt("Test", { abortSignal: new AbortController().signal })).rejects.toBe(
585+
lookupFailure,
586+
)
587+
})
588+
589+
it("rejects with an AbortError when the timeout alone expires during the SDK call", async () => {
590+
const handler = new ZooGatewayHandler(mockOptions)
591+
let sdkSignal: AbortSignal | undefined
592+
mockCreate.mockImplementation((_params: unknown, requestOptions: { signal?: AbortSignal }) => {
593+
sdkSignal = requestOptions.signal
594+
return new Promise(() => {})
595+
})
596+
597+
await expect(handler.completePrompt("Test", { timeoutMs: 20 })).rejects.toMatchObject({
598+
name: "AbortError",
599+
message: "The Zoo Gateway request was aborted",
600+
})
601+
expect(sdkSignal?.aborted).toBe(true)
602+
expect(showErrorMessage).not.toHaveBeenCalled()
603+
})
604+
605+
it("settles on abort while a gateway error notification waits for the user", async () => {
559606
const handler = new ZooGatewayHandler(mockOptions)
560607
const caller = new AbortController()
608+
mockCreate.mockRejectedValue(makeApiError(402))
609+
showErrorMessage.mockImplementation(() => new Promise(() => {}))
610+
611+
const pending = handler.completePrompt("Test", { abortSignal: caller.signal })
612+
await vitest.waitFor(() => expect(showErrorMessage).toHaveBeenCalled())
561613
caller.abort()
562614

563-
await expect(handler.completePrompt("Test", { abortSignal: caller.signal })).rejects.toMatchObject({
615+
await expect(pending).rejects.toMatchObject({
564616
name: "AbortError",
617+
message: "The Zoo Gateway request was aborted",
565618
})
566-
expect(mockCreate).not.toHaveBeenCalled()
567619
})
568620

569621
it("rejects with an AbortError when the timeout alone expires during model lookup", async () => {
@@ -649,13 +701,21 @@ describe("ZooGatewayHandler", () => {
649701
await expect(pending).rejects.toMatchObject({ name: "AbortError" })
650702
})
651703

652-
it("removes the same abort listener from the caller's signal that it added", async () => {
704+
it.each([
705+
["a completed request", () => {}],
706+
["a failed request", () => mockCreate.mockRejectedValue(new Error("upstream failure"))],
707+
["a request aborted mid-flight", () => mockCreate.mockImplementation(() => new Promise(() => {}))],
708+
])("removes the same abort listener from the caller's signal after %s", async (_label, setup) => {
709+
setup()
653710
const handler = new ZooGatewayHandler(mockOptions)
654711
const caller = new AbortController()
655712
const addListener = vitest.spyOn(caller.signal, "addEventListener")
656713
const removeListener = vitest.spyOn(caller.signal, "removeEventListener")
657714

658-
await handler.completePrompt("Test", { abortSignal: caller.signal })
715+
const pending = handler.completePrompt("Test", { abortSignal: caller.signal }).catch(() => undefined)
716+
await vitest.waitFor(() => expect(mockCreate).toHaveBeenCalled())
717+
caller.abort()
718+
await pending
659719

660720
const abortListeners = addListener.mock.calls.filter(([type]) => type === "abort")
661721
expect(abortListeners).toHaveLength(1)

‎src/api/providers/zoo-gateway.ts‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -307,8 +307,6 @@ export class ZooGatewayHandler extends RouterProvider implements SingleCompletio
307307
}
308308

309309
async completePrompt(prompt: string, options?: CompletePromptOptions): Promise<string> {
310-
this.ensureAuthenticated()
311-
312310
// Same abort-signal contract as the other providers (see requesty.ts): the SDK gets a
313311
// per-request signal bridged from the caller's signal, so its abort listener does not stay on
314312
// the caller's long-lived signal. The `finally` below detaches the bridge on every exit path.
@@ -318,7 +316,9 @@ export class ZooGatewayHandler extends RouterProvider implements SingleCompletio
318316
const requestAbortSignal = mergeAbortSignalAndTimeout(bridgedCallerSignal, options?.timeoutMs)
319317

320318
try {
319+
// A cancel that came first wins over every other failure, also a missing session.
321320
throwIfAborted(requestAbortSignal)
321+
this.ensureAuthenticated()
322322

323323
let model: Awaited<ReturnType<ZooGatewayHandler["fetchModel"]>>
324324
try {
@@ -364,12 +364,21 @@ export class ZooGatewayHandler extends RouterProvider implements SingleCompletio
364364
throw createAbortError(ZOO_GATEWAY_PROVIDER_NAME)
365365
}
366366
try {
367-
await surfaceGatewayApiError(error)
367+
// The notification can wait for the user. A cancel or timeout must still settle at once.
368+
const surfacing = surfaceGatewayApiError(error)
369+
await (requestAbortSignal
370+
? rejectOnAbort(surfacing, requestAbortSignal, ZOO_GATEWAY_PROVIDER_NAME)
371+
: surfacing)
368372
} catch (surfaceError) {
369-
console.error(
370-
"Failed to surface Zoo Gateway error:",
371-
surfaceError instanceof Error ? surfaceError.message : surfaceError,
372-
)
373+
if (!requestAbortSignal?.aborted) {
374+
console.error(
375+
"Failed to surface Zoo Gateway error:",
376+
surfaceError instanceof Error ? surfaceError.message : surfaceError,
377+
)
378+
}
379+
}
380+
if (requestAbortSignal?.aborted) {
381+
throw createAbortError(ZOO_GATEWAY_PROVIDER_NAME)
373382
}
374383
if (error instanceof Error) {
375384
throw new Error(`Zoo Gateway completion error: ${error.message}`)

0 commit comments

Comments
 (0)