Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(daemon): reconcile in-flight task and workspace state on WS reconnect (#4718)

xiawiie93028d303b48
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index eeb41812cf..90455396c6 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -175,6 +175,12 @@ type Daemon struct {
wsHBMu sync.RWMutex // guards wsHBLastAck
wsHBLastAck map[string]time.Time // runtime_id -> last successful WS heartbeat ack timestamp
+ // reconcile fans out a "re-check server state now" signal to subscribers
+ // (watchTaskCancellation, workspaceSyncLoop) so the WS connect/reconnect
+ // path can shrink the 5s / 30s reconciliation gap to sub-second. See
+ // reconcile.go and runTaskWakeupConnection.
+ reconcile *reconcileBroadcaster
+
// runtimeGoneMu guards runtimeGoneInflight, reregisterNextAttempt, and
// reregisterLastCompletedAt. The state lets heartbeat / poller / WS-ack
// handlers converge on a single recovery path when they each detect that a
@@ -264,6 +270,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {
reregisterNextAttempt: make(map[string]time.Time),
reregisterLastCompletedAt: make(map[string]time.Time),
cancelPollInterval: 5 * time.Second,
+ reconcile: newReconcileBroadcaster(),
}
d.runner = taskRunnerFunc(d.runTask)
d.runUpdateFn = d.runUpdate
@@ -1684,19 +1691,35 @@ func (d *Daemon) tryRenewToken(ctx context.Context) {
}
// workspaceSyncLoop periodically fetches the user's workspaces from the API
-// and registers runtimes for any new ones.
+// and registers runtimes for any new ones. A WS connect/reconnect broadcast
+// triggers an immediate sync so runtime/repo changes the server applied during
+// the WS gap are picked up sub-second instead of after the next 30s tick.
func (d *Daemon) workspaceSyncLoop(ctx context.Context) {
ticker := time.NewTicker(DefaultWorkspaceSyncInterval)
defer ticker.Stop()
+ var reconcileCh <-chan struct{}
+ if d.reconcile != nil {
+ reconcileCh = d.reconcile.notify()
+ }
+
+ sync := func() {
+ if err := d.syncWorkspacesFromAPI(ctx); err != nil {
+ d.logger.Debug("workspace sync failed", "error", err)
+ }
+ }
+
for {
select {
case <-ctx.Done():
return
- case <-ticker.C:
- if err := d.syncWorkspacesFromAPI(ctx); err != nil {
- d.logger.Debug("workspace sync failed", "error", err)
+ case <-reconcileCh:
+ if d.reconcile != nil {
+ reconcileCh = d.reconcile.notify()
}
+ sync()
+ case <-ticker.C:
+ sync()
}
}
}
@@ -2753,25 +2776,48 @@ func shouldInterruptAgent(status string, err error) bool {
// so callers should pass the runCtx that was set up around the agent run.
func (d *Daemon) watchTaskCancellation(ctx context.Context, taskID string, pollInterval time.Duration, taskLog *slog.Logger) <-chan struct{} {
cancelled := make(chan struct{})
+ // Subscribe to the reconcile broadcaster before launching the inner
+ // goroutine. A WS reconnect that fires between the goroutine starting
+ // and its first notify() call would otherwise be dropped; the ticker
+ // still bounds the worst case, but the whole point of the broadcast is
+ // to avoid waiting on that ticker.
+ var reconcileCh <-chan struct{}
+ if d.reconcile != nil {
+ reconcileCh = d.reconcile.notify()
+ }
go func() {
ticker := time.NewTicker(pollInterval)
defer ticker.Stop()
+ check := func() bool {
+ status, err := d.client.GetTaskStatus(ctx, taskID)
+ if !shouldInterruptAgent(status, err) {
+ return false
+ }
+ if err != nil {
+ taskLog.Info("task gone server-side, interrupting agent", "error", err)
+ } else {
+ taskLog.Info("task reached terminal state server-side, interrupting agent", "status", status)
+ }
+ close(cancelled)
+ return true
+ }
for {
select {
case <-ctx.Done():
return
- case <-ticker.C:
- status, err := d.client.GetTaskStatus(ctx, taskID)
- if !shouldInterruptAgent(status, err) {
- continue
+ case <-reconcileCh:
+ // Refresh the subscription before issuing the request so a
+ // second broadcast that overlaps GetTaskStatus is not lost.
+ if d.reconcile != nil {
+ reconcileCh = d.reconcile.notify()
}
- if err != nil {
- taskLog.Info("task gone server-side, interrupting agent", "error", err)
- } else {
- taskLog.Info("task reached terminal state server-side, interrupting agent", "status", status)
+ if check() {
+ return
+ }
+ case <-ticker.C:
+ if check() {
+ return
}
- close(cancelled)
- return
}
}
}()
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index fde3e042bf..3128f9ac5e 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"io"
"log/slog"
"net/http"
@@ -2335,3 +2336,378 @@ func TestHandleTask_ReportsUsageWhenCancelledByPoll(t *testing.T) {
t.Fatalf("usage reported before poll-status (order: %v) — poll-status must come first", order)
}
}
+
+// TestWatchTaskCancellation_ReconcileBroadcastTriggersImmediateCheck pins the
+// fix for #4665. The 5s ticker in watchTaskCancellation is too coarse to catch
+// a server-side cancellation that landed during a WS disconnect: without the
+// reconcile broadcast, a reconnect followed by an immediate status flip is
+// invisible until the next tick fires. The test sets the ticker to a long
+// interval (so a tick would fail the test) and asserts the watcher reacts to
+// reconcile.broadcast() sub-second.
+func TestWatchTaskCancellation_ReconcileBroadcastTriggersImmediateCheck(t *testing.T) {
+ t.Parallel()
+
+ var status atomic.Value
+ status.Store("running")
+ var calls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.HasSuffix(r.URL.Path, "/status") {
+ http.NotFound(w, r)
+ return
+ }
+ calls.Add(1)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"status":"` + status.Load().(string) + `"}`))
+ }))
+ t.Cleanup(srv.Close)
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.Default(),
+ reconcile: newReconcileBroadcaster(),
+ }
+ d.reconcile.minBroadcastInterval = 0 // tight timing under test
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+
+ // 30s ticker: if the watcher only reacts to its own ticker the test will
+ // time out at 2s, which is exactly the failure we want to catch.
+ cancelled := d.watchTaskCancellation(ctx, "task-reconcile", 30*time.Second, slog.Default())
+
+ // Simulate the gap: status flips during the WS disconnect.
+ status.Store("cancelled")
+
+ // And then the WS reconnects — broadcast must be heard.
+ if !d.reconcile.broadcast() {
+ t.Fatal("broadcast() returned false; expected first broadcast to fire")
+ }
+
+ select {
+ case <-cancelled:
+ // Expected: reconcile woke the watcher, it called GetTaskStatus,
+ // saw cancelled, and closed the channel.
+ case <-time.After(2 * time.Second):
+ t.Fatalf("watchTaskCancellation did not react to reconcile broadcast within 2s (calls=%d)", calls.Load())
+ }
+
+ if calls.Load() == 0 {
+ t.Fatal("GetTaskStatus was never called — reconcile path did not fire")
+ }
+}
+
+// TestWatchTaskCancellation_ReconcileWithRunningTaskStaysAlive ensures the
+// reconcile path does not falsely interrupt a still-running task. The watcher
+// must call GetTaskStatus on broadcast, see status=running, and continue.
+func TestWatchTaskCancellation_ReconcileWithRunningTaskStaysAlive(t *testing.T) {
+ t.Parallel()
+
+ var calls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"status":"running"}`))
+ }))
+ t.Cleanup(srv.Close)
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.Default(),
+ reconcile: newReconcileBroadcaster(),
+ }
+ d.reconcile.minBroadcastInterval = 0
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+
+ cancelled := d.watchTaskCancellation(ctx, "task-still-running", 30*time.Second, slog.Default())
+
+ // Three broadcasts back-to-back: watcher should call GetTaskStatus at
+ // least once and NOT close the cancelled channel.
+ for i := 0; i < 3; i++ {
+ d.reconcile.broadcast()
+ time.Sleep(20 * time.Millisecond)
+ }
+
+ select {
+ case <-cancelled:
+ t.Fatal("watchTaskCancellation closed cancelled channel for a running task")
+ case <-time.After(200 * time.Millisecond):
+ // Expected: still running.
+ }
+
+ if calls.Load() == 0 {
+ t.Fatal("reconcile broadcasts did not result in any GetTaskStatus call")
+ }
+}
+
+// TestWorkspaceSyncLoop_ReconcileBroadcastTriggersImmediateSync pins that the
+// 30s workspace sync ticker is also short-circuited by reconcile broadcasts.
+// Without this, runtime/repo changes the server made during a WS disconnect
+// stay invisible to the daemon for up to 30 seconds.
+func TestWorkspaceSyncLoop_ReconcileBroadcastTriggersImmediateSync(t *testing.T) {
+ t.Parallel()
+
+ var calls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/workspaces" {
+ http.NotFound(w, r)
+ return
+ }
+ calls.Add(1)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"workspaces":[]}`))
+ }))
+ t.Cleanup(srv.Close)
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.Default(),
+ workspaces: make(map[string]*workspaceState),
+ reconcile: newReconcileBroadcaster(),
+ }
+ d.reconcile.minBroadcastInterval = 0
+
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+
+ loopDone := make(chan struct{})
+ go func() {
+ defer close(loopDone)
+ d.workspaceSyncLoop(ctx)
+ }()
+
+ // Two broadcasts spaced apart. workspaceSyncLoop should re-acquire its
+ // subscription after the first wake and react to the second too.
+ d.reconcile.broadcast()
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) && calls.Load() < 1 {
+ time.Sleep(20 * time.Millisecond)
+ }
+ if calls.Load() < 1 {
+ cancel()
+ <-loopDone
+ t.Fatal("workspaceSyncLoop did not react to first reconcile broadcast within 2s")
+ }
+
+ d.reconcile.broadcast()
+ deadline = time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) && calls.Load() < 2 {
+ time.Sleep(20 * time.Millisecond)
+ }
+ if calls.Load() < 2 {
+ cancel()
+ <-loopDone
+ t.Fatalf("workspaceSyncLoop did not react to second reconcile broadcast within 2s (calls=%d)", calls.Load())
+ }
+
+ cancel()
+ select {
+ case <-loopDone:
+ case <-time.After(time.Second):
+ t.Fatal("workspaceSyncLoop did not return after ctx cancel")
+ }
+}
+
+// TestWorkspaceSyncLoop_ReplaysBroadcastFromBeforeStart pins the daemon-
+// startup race fix: broadcast() that fired while no one was subscribed
+// MUST still wake the loop on its first subscription. Without the
+// reconcile broadcaster's replay slot, this race manifests in production
+// when the WS connects (and broadcasts) before workspaceSyncLoop has
+// finished its first notify() call.
+func TestWorkspaceSyncLoop_ReplaysBroadcastFromBeforeStart(t *testing.T) {
+ t.Parallel()
+
+ var calls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/workspaces" {
+ http.NotFound(w, r)
+ return
+ }
+ calls.Add(1)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"workspaces":[]}`))
+ }))
+ t.Cleanup(srv.Close)
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.Default(),
+ workspaces: make(map[string]*workspaceState),
+ reconcile: newReconcileBroadcaster(),
+ }
+ d.reconcile.minBroadcastInterval = 0
+
+ // Broadcast BEFORE the loop subscribes — the level-triggered replay slot
+ // must hold the event for the loop's first notify().
+ if !d.reconcile.broadcast() {
+ t.Fatal("seed broadcast suppressed")
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+
+ loopDone := make(chan struct{})
+ go func() {
+ defer close(loopDone)
+ d.workspaceSyncLoop(ctx)
+ }()
+
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) && calls.Load() < 1 {
+ time.Sleep(10 * time.Millisecond)
+ }
+ if calls.Load() < 1 {
+ cancel()
+ <-loopDone
+ t.Fatal("workspaceSyncLoop did not replay broadcast issued before its start")
+ }
+
+ cancel()
+ <-loopDone
+}
+
+// TestWatchTaskCancellation_BroadcastWakesAllConcurrentWatchers ensures the
+// fix scales: a single WS reconnect that fires broadcast() must drive every
+// in-flight task's watcher to re-check the server. Without fan-out, a busy
+// daemon with N tasks would still hit a wall of sequential 5s gaps.
+func TestWatchTaskCancellation_BroadcastWakesAllConcurrentWatchers(t *testing.T) {
+ t.Parallel()
+
+ var status atomic.Value
+ status.Store("running")
+ var totalCalls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.HasSuffix(r.URL.Path, "/status") {
+ http.NotFound(w, r)
+ return
+ }
+ totalCalls.Add(1)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"status":"` + status.Load().(string) + `"}`))
+ }))
+ t.Cleanup(srv.Close)
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.Default(),
+ reconcile: newReconcileBroadcaster(),
+ }
+ d.reconcile.minBroadcastInterval = 0
+
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+
+ const watchers = 8
+ chans := make([]<-chan struct{}, watchers)
+ for i := 0; i < watchers; i++ {
+ // 30s ticker: only the broadcast path can satisfy the assertion.
+ chans[i] = d.watchTaskCancellation(ctx, fmt.Sprintf("task-%d", i), 30*time.Second, slog.Default())
+ }
+
+ // Server state flips during the WS gap; broadcast lands the news to
+ // every watcher at once.
+ status.Store("cancelled")
+ if !d.reconcile.broadcast() {
+ t.Fatal("broadcast suppressed")
+ }
+
+ deadline := time.After(3 * time.Second)
+ for i, ch := range chans {
+ select {
+ case <-ch:
+ case <-deadline:
+ t.Fatalf("watcher %d did not react to broadcast (totalCalls=%d, woke=%d)", i, totalCalls.Load(), i)
+ }
+ }
+}
+
+// TestWatchTaskCancellation_ReconcileDoesNotPanicAfterCtxCancel ensures
+// teardown order is safe: even if a broadcast arrives after ctx is cancelled,
+// the watcher must exit cleanly without panic or double-close of cancelled.
+func TestWatchTaskCancellation_ReconcileDoesNotPanicAfterCtxCancel(t *testing.T) {
+ t.Parallel()
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"status":"running"}`))
+ }))
+ t.Cleanup(srv.Close)
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.Default(),
+ reconcile: newReconcileBroadcaster(),
+ }
+ d.reconcile.minBroadcastInterval = 0
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancelled := d.watchTaskCancellation(ctx, "task-ctx-cancelled", 30*time.Second, slog.Default())
+
+ cancel()
+ // Give the watcher a beat to observe ctx.Done() and exit.
+ time.Sleep(50 * time.Millisecond)
+
+ // Broadcast after cancel — must not panic and must not unblock the
+ // cancelled channel (the task was not interrupted server-side).
+ for i := 0; i < 5; i++ {
+ d.reconcile.broadcast()
+ }
+
+ select {
+ case <-cancelled:
+ t.Fatal("cancelled channel was closed after ctx cancel; server still reported running")
+ case <-time.After(150 * time.Millisecond):
+ // Expected: nothing happened.
+ }
+}
+
+// TestWatchTaskCancellation_ReconcileRunningKeepsTickerAlive proves that a
+// reconcile broadcast that sees status=running does not disturb the ticker;
+// a subsequent ticker fire still detects a later cancellation.
+func TestWatchTaskCancellation_ReconcileRunningKeepsTickerAlive(t *testing.T) {
+ t.Parallel()
+
+ var status atomic.Value
+ status.Store("running")
+ var calls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.HasSuffix(r.URL.Path, "/status") {
+ http.NotFound(w, r)
+ return
+ }
+ calls.Add(1)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"status":"` + status.Load().(string) + `"}`))
+ }))
+ t.Cleanup(srv.Close)
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.Default(),
+ reconcile: newReconcileBroadcaster(),
+ }
+ d.reconcile.minBroadcastInterval = 0
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+
+ // Short ticker so the test stays fast.
+ cancelled := d.watchTaskCancellation(ctx, "task-runs-then-cancelled", 50*time.Millisecond, slog.Default())
+
+ // First broadcast: server still reports running — watcher must NOT
+ // close cancelled.
+ if !d.reconcile.broadcast() {
+ t.Fatal("first broadcast suppressed")
+ }
+ select {
+ case <-cancelled:
+ t.Fatal("watcher closed cancelled on a running task")
+ case <-time.After(100 * time.Millisecond):
+ }
+
+ // Now flip status — ticker should pick it up within ~50ms.
+ status.Store("cancelled")
+ select {
+ case <-cancelled:
+ case <-time.After(2 * time.Second):
+ t.Fatalf("ticker did not detect cancellation after broadcast-running path (calls=%d)", calls.Load())
+ }
+}
diff --git a/server/internal/daemon/reconcile.go b/server/internal/daemon/reconcile.go
new file mode 100644
index 0000000000..3bf2c18b60
--- /dev/null
+++ b/server/internal/daemon/reconcile.go
@@ -0,0 +1,98 @@
+package daemon
+
+import (
+ "sync"
+ "time"
+)
+
+// reconcileBroadcaster fans out a "reconcile now" signal to any number of
+// listeners using the close-and-replace channel pattern. Subscribers call
+// notify() to obtain a snapshot channel that closes on the next broadcast;
+// after waking, a subscriber re-acquires a fresh snapshot via notify() to
+// receive the next signal.
+//
+// The broadcaster exists because some daemon loops run on coarse tickers
+// (task-cancellation polling at 5s, workspace sync at 30s). When the daemon's
+// WS connection drops and reconnects, anything the server changed during the
+// gap is invisible to those loops until their next tick fires. broadcast()
+// lets the WS connect path nudge every waiter to re-check immediately,
+// without disturbing the ticker cadence.
+//
+// The broadcaster is edge-triggered with one-slot replay: if broadcast()
+// fires while nobody is subscribed, the next notify() call returns an
+// already-closed channel so the late subscriber observes the missed event
+// exactly once. This closes the daemon-startup race where workspaceSyncLoop
+// (or another late subscriber) parks on its ticker just after a broadcast
+// landed during the WS connect, and would otherwise wait a full ticker
+// period to learn about it.
+//
+// broadcast() debounces back-to-back calls inside minBroadcastInterval so a
+// flapping WS connection cannot translate a network blip into a stampede of
+// GetTaskStatus / ListWorkspaces requests. The interval is intentionally
+// short: a real reconnect still converts quickly, but ten reconnects in a
+// second collapse into one immediate fan-out plus, at most, one follow-up
+// after the interval elapses.
+type reconcileBroadcaster struct {
+ mu sync.Mutex
+ ch chan struct{}
+ pending bool
+ lastBroadcast time.Time
+ minBroadcastInterval time.Duration
+ // now is injected in tests to make the debounce window deterministic;
+ // production code uses time.Now.
+ now func() time.Time
+}
+
+func newReconcileBroadcaster() *reconcileBroadcaster {
+ return &reconcileBroadcaster{
+ ch: make(chan struct{}),
+ minBroadcastInterval: time.Second,
+ now: time.Now,
+ }
+}
+
+// notify returns a channel that closes on the next broadcast. Subscribers
+// should call notify() again after waking to receive the next signal — the
+// returned channel is single-shot.
+//
+// If a broadcast arrived while there were no subscribers, the channel
+// returned by the next notify() call is already closed. The replay flag is
+// cleared by that call: a second concurrent late subscriber does NOT see
+// the same replayed event. Callers that need broadcast delivery to every
+// goroutine must subscribe before the broadcast happens.
+func (b *reconcileBroadcaster) notify() <-chan struct{} {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if b.pending {
+ // Replay the missed broadcast exactly once: hand back a fresh,
+ // already-closed channel without disturbing b.ch for real
+ // subscribers, and clear pending so the next notify() resumes
+ // edge-triggered behaviour.
+ b.pending = false
+ replay := make(chan struct{})
+ close(replay)
+ return replay
+ }
+ return b.ch
+}
+
+// broadcast wakes every current subscriber, then installs a fresh channel
+// for future subscribers. If there are no current subscribers, a one-slot
+// replay flag is set so the next notify() observes the missed event once.
+//
+// Calls within minBroadcastInterval of the previous broadcast are dropped;
+// the function reports whether the signal fired so callers can log
+// debug-level traces of suppressed broadcasts.
+func (b *reconcileBroadcaster) broadcast() bool {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ now := b.now()
+ if !b.lastBroadcast.IsZero() && now.Sub(b.lastBroadcast) < b.minBroadcastInterval {
+ return false
+ }
+ b.lastBroadcast = now
+ b.pending = true
+ close(b.ch)
+ b.ch = make(chan struct{})
+ return true
+}
diff --git a/server/internal/daemon/reconcile_test.go b/server/internal/daemon/reconcile_test.go
new file mode 100644
index 0000000000..2ae15dfe61
--- /dev/null
+++ b/server/internal/daemon/reconcile_test.go
@@ -0,0 +1,241 @@
+package daemon
+
+import (
+ "sync"
+ "testing"
+ "time"
+)
+
+// TestReconcileBroadcaster_FansOutToManySubscribers pins the close-and-replace
+// fan-out: every subscriber registered before broadcast wakes from its
+// snapshot channel.
+func TestReconcileBroadcaster_FansOutToManySubscribers(t *testing.T) {
+ b := newReconcileBroadcaster()
+ b.minBroadcastInterval = 0 // disable debounce for this test
+
+ const subs = 16
+ var wg sync.WaitGroup
+ wg.Add(subs)
+ wokeUp := make(chan struct{}, subs)
+ for i := 0; i < subs; i++ {
+ ch := b.notify()
+ go func() {
+ defer wg.Done()
+ <-ch
+ wokeUp <- struct{}{}
+ }()
+ }
+
+ // Give subscribers a moment to park on <-ch.
+ time.Sleep(20 * time.Millisecond)
+
+ if !b.broadcast() {
+ t.Fatalf("broadcast() = false, want true")
+ }
+
+ done := make(chan struct{})
+ go func() {
+ wg.Wait()
+ close(done)
+ }()
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatalf("only %d/%d subscribers woke up", len(wokeUp), subs)
+ }
+}
+
+// TestReconcileBroadcaster_ReplaysMissedBroadcastToFirstLateSubscriber pins
+// the level-triggered safety net: if a broadcast fires while no one is
+// subscribed, the next notify() returns an already-closed channel so the
+// late subscriber observes the missed event exactly once. This closes the
+// daemon-startup race where a sync loop subscribes a beat after the WS
+// connect broadcast.
+func TestReconcileBroadcaster_ReplaysMissedBroadcastToFirstLateSubscriber(t *testing.T) {
+ b := newReconcileBroadcaster()
+ b.minBroadcastInterval = 0
+
+ // No subscribers yet — fire.
+ if !b.broadcast() {
+ t.Fatalf("broadcast() = false, want true")
+ }
+
+ // First late subscriber must see the replay.
+ first := b.notify()
+ select {
+ case <-first:
+ case <-time.After(time.Second):
+ t.Fatalf("first late subscriber did not receive replayed broadcast")
+ }
+
+ // Second late subscriber must NOT see the same replay; it should park.
+ second := b.notify()
+ select {
+ case <-second:
+ t.Fatalf("second late subscriber received a stale replay; should be fresh")
+ case <-time.After(50 * time.Millisecond):
+ // Expected: parked.
+ }
+}
+
+// TestReconcileBroadcaster_ReplayPersistsAcrossSubscriberDelay pins that an
+// unobserved pending replay is preserved indefinitely until the first
+// notify() consumes it.
+func TestReconcileBroadcaster_ReplayPersistsAcrossSubscriberDelay(t *testing.T) {
+ b := newReconcileBroadcaster()
+ b.minBroadcastInterval = 0
+
+ b.broadcast()
+ time.Sleep(100 * time.Millisecond)
+
+ ch := b.notify()
+ select {
+ case <-ch:
+ case <-time.After(time.Second):
+ t.Fatalf("pending replay was lost after 100ms delay")
+ }
+}
+
+// TestReconcileBroadcaster_DebouncesFlappingReconnects pins the safety
+// property that a flapping WS cannot translate ten reconnects per second
+// into ten fan-out broadcasts. The clock is injected so the debounce
+// window is deterministic.
+func TestReconcileBroadcaster_DebouncesFlappingReconnects(t *testing.T) {
+ b := newReconcileBroadcaster()
+ b.minBroadcastInterval = time.Second
+ var nowVal time.Time
+ b.now = func() time.Time { return nowVal }
+
+ nowVal = time.Unix(1_700_000_000, 0)
+ if !b.broadcast() {
+ t.Fatalf("first broadcast suppressed")
+ }
+
+ // Ten back-to-back calls within 900ms — all suppressed.
+ for i := 0; i < 10; i++ {
+ nowVal = nowVal.Add(90 * time.Millisecond)
+ if b.broadcast() {
+ t.Fatalf("broadcast at +%dms not debounced", (i+1)*90)
+ }
+ }
+
+ // Cross the threshold — next broadcast fires.
+ nowVal = nowVal.Add(time.Second)
+ if !b.broadcast() {
+ t.Fatalf("broadcast past debounce window suppressed")
+ }
+}
+
+// TestReconcileBroadcaster_DebounceBoundaryIsExact pins the exact comparison
+// (strict less-than): a call landing at exactly minBroadcastInterval after
+// the previous broadcast must succeed, not be suppressed.
+func TestReconcileBroadcaster_DebounceBoundaryIsExact(t *testing.T) {
+ b := newReconcileBroadcaster()
+ b.minBroadcastInterval = time.Second
+ var nowVal time.Time
+ b.now = func() time.Time { return nowVal }
+
+ nowVal = time.Unix(1_700_000_000, 0)
+ if !b.broadcast() {
+ t.Fatal("first broadcast suppressed")
+ }
+
+ // Exactly at the interval — must fire (>= boundary is allowed).
+ nowVal = nowVal.Add(time.Second)
+ if !b.broadcast() {
+ t.Fatal("broadcast at exact debounce boundary was suppressed")
+ }
+
+ // Just below the next boundary — must be suppressed.
+ nowVal = nowVal.Add(999 * time.Millisecond)
+ if b.broadcast() {
+ t.Fatal("broadcast at boundary-minus-1ms was not suppressed")
+ }
+}
+
+// TestReconcileBroadcaster_ReSubscribesEachWake pins the edge-triggered
+// contract for ACTIVE subscribers: after the first wake, the same channel
+// stays closed; the subscriber must call notify() again to receive future
+// broadcasts.
+func TestReconcileBroadcaster_ReSubscribesEachWake(t *testing.T) {
+ b := newReconcileBroadcaster()
+ b.minBroadcastInterval = 0
+
+ ch1 := b.notify()
+ b.broadcast()
+ select {
+ case <-ch1:
+ case <-time.After(time.Second):
+ t.Fatalf("first wake did not arrive on ch1")
+ }
+
+ // ch1 is now closed; broadcasting again must not panic.
+ b.broadcast()
+ select {
+ case <-ch1:
+ // Already closed — still drains cleanly.
+ default:
+ t.Fatalf("ch1 should remain closed after second broadcast")
+ }
+}
+
+// TestReconcileBroadcaster_ConcurrentBroadcastAndNotify exercises the lock
+// boundary: heavy concurrent notify/broadcast traffic must not panic, dead-
+// lock, or fail under the race detector. Run with `go test -race`.
+func TestReconcileBroadcaster_ConcurrentBroadcastAndNotify(t *testing.T) {
+ b := newReconcileBroadcaster()
+ b.minBroadcastInterval = 0
+
+ stop := make(chan struct{})
+ var wg sync.WaitGroup
+
+ // 8 subscribers in tight loops.
+ for i := 0; i < 8; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ }
+ ch := b.notify()
+ select {
+ case <-ch:
+ case <-stop:
+ return
+ }
+ }
+ }()
+ }
+
+ // 4 broadcasters in tight loops.
+ for i := 0; i < 4; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ }
+ b.broadcast()
+ }
+ }()
+ }
+
+ time.Sleep(200 * time.Millisecond)
+ close(stop)
+
+ // Bound the join — if anything deadlocks we want a clear failure rather
+ // than a hung test.
+ done := make(chan struct{})
+ go func() { wg.Wait(); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("concurrent broadcast/notify did not converge after stop")
+ }
+}
diff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.go
index f3de25b057..46d10aa71b 100644
--- a/server/internal/daemon/wakeup.go
+++ b/server/internal/daemon/wakeup.go
@@ -124,6 +124,16 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strin
d.logger.Info("task wakeup websocket connected", "runtimes", len(runtimeIDs))
signalTaskWakeup(taskWakeups, "")
+ // signalTaskWakeup only wakes idle ClaimTask pollers. In-flight tasks and
+ // the workspace sync loop park on coarse tickers (5s and 30s) that do not
+ // observe the wakeup channel, so anything the server changed during the
+ // WS gap — task cancellation, runtime/repo updates — stays invisible to
+ // them until the next tick. The reconcile broadcaster nudges those loops
+ // to re-check immediately. broadcast() debounces back-to-back calls so a
+ // flapping connection cannot fan out into a request stampede.
+ if d.reconcile != nil {
+ d.reconcile.broadcast()
+ }
// Serialize all writes through a single channel: the gorilla/websocket
// Conn does not allow concurrent WriteMessage calls, and the heartbeat