From 457fa8b6b2f6ddfd318c5022a7289083e544b2b1 Mon Sep 17 00:00:00 2001 From: David Lechner Date: Sun, 25 Jan 2026 20:23:00 +0000 Subject: [PATCH] usb/sagas: Fix command response race condition Fix a race condition where a response to a USB command could be missed if it arrives before the USB transferOut() call returns. This is done by using a channel to buffer incoming responses. Fixes: https://github.com/pybricks/support/issues/2467 --- src/usb/sagas.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/usb/sagas.ts b/src/usb/sagas.ts index 570df488..eb9a1c96 100644 --- a/src/usb/sagas.ts +++ b/src/usb/sagas.ts @@ -454,6 +454,12 @@ function* handleUsbConnectPybricks(hotPlugDevice?: USBDevice): Generator { writeCommand.matches(a), ); + // Response may come before request returns, so we need to buffer them + // in a channel to avoid missing responses. + const responseChannel = yield* actionChannel( + usbDidReceivePybricksMessageResponse, + ); + for (;;) { const action = yield* take(chan); @@ -525,7 +531,7 @@ function* handleUsbConnectPybricks(hotPlugDevice?: USBDevice): Generator { } const { response, timeout } = yield* race({ - response: take(usbDidReceivePybricksMessageResponse), + response: take(responseChannel), timeout: delay(1000), });