iddo 6f2ea80060
Fix race between stopping and starting the receive thread (#2142)
* Fix race between stopping and starting the receive thread

When the last receive handler was removed, receiveThread was cleared
before the thread had stopped. A handler added in that window, e.g. by
a client reconnecting to the daemon in on-connection receive mode,
started a second receive thread. While the stop request for the old
thread was still set, each new thread ended immediately and started the
next one. When the old thread ended, it cleared the reference to the
newer thread and started yet another one, leaving two receive loops on
the same websocket. The unreferenced loop was never stopped and kept
receiving and acknowledging messages after all clients had gone.

Keep receiveThread set until the receive thread has finished and only
let the thread itself clear it. Its end block already starts a new
receive thread if handlers were added in the meantime. Clear a stop
request right before a new receive loop is started instead of when a
loop ends, so it can neither be cleared by another loop nor stop a
later one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add test for adding a receive handler while the receive thread stops

The receive loop is replaced by a fake one that can be held while it
stops, so the test doesn't connect to the server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: iddo <917594+iddo@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 16:28:42 +02:00
..