Skip to content

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

Go

feat(daemon): add WebSocket heartbeat with HTTP fallback

Bohan Jiang286ecf04b172
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index e4a0e98b6e..987483ea8e 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -118,6 +118,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
daemonTokenCache := auth.NewDaemonTokenCache(rdb)
h.PATCache = patCache
h.DaemonTokenCache = daemonTokenCache
+
+ // Wire WS heartbeat after stores are finalized so the WS path uses the
+ // same (possibly Redis-backed) stores as the HTTP path.
+ daemonHub.SetHeartbeatHandler(h.HandleDaemonWSHeartbeat)
health := newServerHealth(pool)
r := chi.NewRouter()
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 5953936e51..3ca3c1f493 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -11,6 +11,8 @@ import (
"runtime"
"strings"
"time"
+
+ "github.com/multica-ai/multica/server/pkg/protocol"
)
// requestError is returned by postJSON/getJSON when the server responds with an error status.
@@ -214,36 +216,16 @@ func (c *Client) GetTaskStatus(ctx context.Context, taskID string) (string, erro
return resp.Status, nil
}
-// HeartbeatResponse contains the server's response to a heartbeat, including any pending actions.
-type HeartbeatResponse struct {
- Status string `json:"status"`
- PendingUpdate *PendingUpdate `json:"pending_update,omitempty"`
- PendingModelList *PendingModelList `json:"pending_model_list,omitempty"`
- PendingLocalSkills *PendingLocalSkills `json:"pending_local_skills,omitempty"`
- PendingLocalSkillImport *PendingLocalSkillImport `json:"pending_local_skill_import,omitempty"`
-}
-
-// PendingUpdate represents a CLI update request from the server.
-type PendingUpdate struct {
- ID string `json:"id"`
- TargetVersion string `json:"target_version"`
-}
-
-// PendingModelList represents a request to enumerate supported models.
-type PendingModelList struct {
- ID string `json:"id"`
-}
-
-// PendingLocalSkills represents a request to enumerate runtime local skills.
-type PendingLocalSkills struct {
- ID string `json:"id"`
-}
-
-// PendingLocalSkillImport represents a request to import a runtime local skill.
-type PendingLocalSkillImport struct {
- ID string `json:"id"`
- SkillKey string `json:"skill_key"`
-}
+// HeartbeatResponse, PendingUpdate, etc. alias the wire types so HTTP and WS
+// heartbeat paths share a single type and a single decoder shape. Aliases
+// (rather than wrappers) keep call sites unchanged.
+type (
+ HeartbeatResponse = protocol.DaemonHeartbeatAckPayload
+ PendingUpdate = protocol.DaemonHeartbeatPendingUpdate
+ PendingModelList = protocol.DaemonHeartbeatPendingModelList
+ PendingLocalSkills = protocol.DaemonHeartbeatPendingLocalSkills
+ PendingLocalSkillImport = protocol.DaemonHeartbeatPendingLocalSkillImport
+)
func (c *Client) SendHeartbeat(ctx context.Context, runtimeID string) (*HeartbeatResponse, error) {
var resp HeartbeatResponse
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index ba7a14750b..7767f96991 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -50,6 +50,9 @@ type Daemon struct {
versionsMu sync.RWMutex // guards agentVersions
agentVersions map[string]string // provider -> detected CLI version (set during registration)
+ wsHBMu sync.RWMutex // guards wsHBLastAck
+ wsHBLastAck map[string]time.Time // runtime_id -> last successful WS heartbeat ack timestamp
+
cancelFunc context.CancelFunc // set by Run(); called by triggerRestart
restartBinary string // non-empty after a successful update; path to the new binary
updating atomic.Bool // prevents concurrent update attempts
@@ -72,6 +75,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {
runtimeIndex: make(map[string]Runtime),
runtimeSetCh: make(chan struct{}, 1),
agentVersions: make(map[string]string),
+ wsHBLastAck: make(map[string]time.Time),
}
}
@@ -108,6 +112,52 @@ func (d *Daemon) drainRuntimeSetChanged() {
}
}
+// wsHeartbeatFreshness defines how long a WS heartbeat ack is considered
+// "fresh enough" to suppress the HTTP heartbeat for that runtime. The window
+// is 2× HeartbeatInterval so a single dropped WS ack still keeps HTTP
+// suppressed, but two missed acks (~30s of WS silence) re-enable HTTP — well
+// inside the server-side 45s offline threshold.
+func (d *Daemon) wsHeartbeatFreshness() time.Duration {
+ if d.cfg.HeartbeatInterval <= 0 {
+ return 30 * time.Second
+ }
+ return 2 * d.cfg.HeartbeatInterval
+}
+
+// recordWSHeartbeatAck stamps the runtime as having received a fresh WS
+// heartbeat ack from the server. Called by the WS read pump.
+func (d *Daemon) recordWSHeartbeatAck(runtimeID string) {
+ if runtimeID == "" {
+ return
+ }
+ d.wsHBMu.Lock()
+ d.wsHBLastAck[runtimeID] = time.Now()
+ d.wsHBMu.Unlock()
+}
+
+// wsHeartbeatRecentlyAcked reports whether the runtime received a WS
+// heartbeat ack inside the freshness window. The HTTP heartbeat loop uses
+// this to skip duplicate work when WS is already keeping the runtime alive.
+func (d *Daemon) wsHeartbeatRecentlyAcked(runtimeID string) bool {
+ d.wsHBMu.RLock()
+ last, ok := d.wsHBLastAck[runtimeID]
+ d.wsHBMu.RUnlock()
+ if !ok {
+ return false
+ }
+ return time.Since(last) < d.wsHeartbeatFreshness()
+}
+
+// clearWSHeartbeatAcks drops all WS heartbeat freshness records. Called on
+// WS disconnect so HTTP heartbeats resume on the next tick.
+func (d *Daemon) clearWSHeartbeatAcks() {
+ d.wsHBMu.Lock()
+ for k := range d.wsHBLastAck {
+ delete(d.wsHBLastAck, k)
+ }
+ d.wsHBMu.Unlock()
+}
+
// Run starts the daemon: resolves auth, registers runtimes, then polls for tasks.
func (d *Daemon) Run(ctx context.Context) error {
// Wrap context so handleUpdate can cancel the daemon for restart.
@@ -519,45 +569,54 @@ func (d *Daemon) heartbeatLoop(ctx context.Context) {
return
case <-ticker.C:
for _, rid := range d.allRuntimeIDs() {
+ // Skip HTTP heartbeat for runtimes that successfully acked
+ // a recent WebSocket heartbeat. The WS path keeps last_seen_at
+ // fresh and delivers actions, so the HTTP write would be a
+ // duplicate DB update. If the WS heartbeat goes silent the
+ // freshness window expires and HTTP resumes automatically on
+ // the next tick — that is the fallback the WS path relies on.
+ if d.wsHeartbeatRecentlyAcked(rid) {
+ continue
+ }
resp, err := d.client.SendHeartbeat(ctx, rid)
if err != nil {
d.logger.Warn("heartbeat failed", "runtime_id", rid, "error", err)
continue
}
-
- // Handle pending update requests.
- if resp.PendingUpdate != nil {
- go d.handleUpdate(ctx, rid, resp.PendingUpdate)
- }
-
- // Handle pending model-list requests.
- if resp.PendingModelList != nil {
- rt := d.findRuntime(rid)
- if rt != nil {
- go d.handleModelList(ctx, *rt, resp.PendingModelList.ID)
- }
- }
-
- // Handle pending runtime-local-skill inventory requests.
- if resp.PendingLocalSkills != nil {
- rt := d.findRuntime(rid)
- if rt != nil {
- go d.handleLocalSkillList(ctx, *rt, resp.PendingLocalSkills.ID)
- }
- }
-
- // Handle pending runtime-local-skill import requests.
- if resp.PendingLocalSkillImport != nil {
- rt := d.findRuntime(rid)
- if rt != nil {
- go d.handleLocalSkillImport(ctx, *rt, *resp.PendingLocalSkillImport)
- }
- }
+ d.handleHeartbeatActions(ctx, rid, resp)
}
}
}
}
+// handleHeartbeatActions dispatches the pending-action set returned by either
+// transport (HTTP POST /api/daemon/heartbeat or WS daemon:heartbeat_ack).
+// Each action is dispatched in its own goroutine so a slow handler cannot
+// block subsequent heartbeats.
+func (d *Daemon) handleHeartbeatActions(ctx context.Context, runtimeID string, resp *HeartbeatResponse) {
+ if resp == nil {
+ return
+ }
+ if resp.PendingUpdate != nil {
+ go d.handleUpdate(ctx, runtimeID, resp.PendingUpdate)
+ }
+ if resp.PendingModelList != nil {
+ if rt := d.findRuntime(runtimeID); rt != nil {
+ go d.handleModelList(ctx, *rt, resp.PendingModelList.ID)
+ }
+ }
+ if resp.PendingLocalSkills != nil {
+ if rt := d.findRuntime(runtimeID); rt != nil {
+ go d.handleLocalSkillList(ctx, *rt, resp.PendingLocalSkills.ID)
+ }
+ }
+ if resp.PendingLocalSkillImport != nil {
+ if rt := d.findRuntime(runtimeID); rt != nil {
+ go d.handleLocalSkillImport(ctx, *rt, *resp.PendingLocalSkillImport)
+ }
+ }
+}
+
// handleModelList resolves the provider's supported models (via static
// catalog or by shelling out to the agent CLI) and reports the result
// back to the server. Model discovery failures are reported as empty
diff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.go
index 9ab2c58fb1..efb51161c6 100644
--- a/server/internal/daemon/wakeup.go
+++ b/server/internal/daemon/wakeup.go
@@ -92,15 +92,49 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strin
return err
}
defer conn.Close()
+ // HTTP heartbeats resume the moment WS detaches so the freshness window
+ // from a previous connection cannot keep them silenced past disconnect.
+ defer d.clearWSHeartbeatAcks()
d.logger.Info("task wakeup websocket connected", "runtimes", len(runtimeIDs))
signalTaskWakeup(taskWakeups)
+ // Serialize all writes through a single channel: the gorilla/websocket
+ // Conn does not allow concurrent WriteMessage calls, and the heartbeat
+ // sender now coexists with future server-initiated writes.
+ writes := make(chan []byte, 8)
+ writerDone := make(chan struct{})
+ go d.runWSWriter(conn, writes, writerDone)
+
+ heartbeatCtx, cancelHeartbeat := context.WithCancel(ctx)
+ hbDone := make(chan struct{})
+ go func() {
+ defer close(hbDone)
+ d.runWSHeartbeatSender(heartbeatCtx, runtimeIDs, writes)
+ }()
+
errCh := make(chan error, 1)
go func() {
errCh <- d.readTaskWakeupMessages(conn, taskWakeups)
}()
+ // Defer cleanup must shut goroutines down in this order:
+ // 1. cancel the heartbeat sender's ctx
+ // 2. wait for the sender to actually return — only then is it safe
+ // to close the writes channel without a "send on closed channel"
+ // panic from sendWSHeartbeats
+ // 3. close writes; the writer drains and exits
+ // 4. wait for the writer to finish so it doesn't outlive the conn
+ //
+ // LIFO defer order would close writes before the sender stops, so the
+ // teardown is folded into a single deferred function instead.
+ defer func() {
+ cancelHeartbeat()
+ <-hbDone
+ close(writes)
+ <-writerDone
+ }()
+
select {
case <-ctx.Done():
return ctx.Err()
@@ -111,6 +145,82 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strin
}
}
+// runWSWriter funnels writes from the heartbeat sender (and any future
+// daemon-initiated message) into a single goroutine. gorilla/websocket
+// requires that all WriteMessage calls happen from the same goroutine.
+func (d *Daemon) runWSWriter(conn *websocket.Conn, writes <-chan []byte, done chan<- struct{}) {
+ defer close(done)
+ for frame := range writes {
+ conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
+ if err := conn.WriteMessage(websocket.TextMessage, frame); err != nil {
+ d.logger.Debug("task wakeup websocket write failed", "error", err)
+ conn.Close()
+ // Drain remaining frames so the producers don't block forever
+ // while waiting for runTaskWakeupConnection to close the channel.
+ for range writes {
+ }
+ return
+ }
+ }
+}
+
+// runWSHeartbeatSender emits a daemon:heartbeat per runtime every
+// HeartbeatInterval. The first batch fires immediately so the server learns
+// the connection identity without waiting a full interval. Frames are queued
+// to the writer; if the queue is full the heartbeat is dropped (the
+// freshness window is short enough that one missed beat just means HTTP will
+// pick it up next tick).
+func (d *Daemon) runWSHeartbeatSender(ctx context.Context, runtimeIDs []string, writes chan<- []byte) {
+ d.sendWSHeartbeats(ctx, runtimeIDs, writes)
+ interval := d.cfg.HeartbeatInterval
+ if interval <= 0 {
+ interval = 15 * time.Second
+ }
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ d.sendWSHeartbeats(ctx, runtimeIDs, writes)
+ }
+ }
+}
+
+func (d *Daemon) sendWSHeartbeats(ctx context.Context, runtimeIDs []string, writes chan<- []byte) {
+ for _, rid := range runtimeIDs {
+ if ctx.Err() != nil {
+ return
+ }
+ frame, err := json.Marshal(protocol.Message{
+ Type: protocol.EventDaemonHeartbeat,
+ Payload: marshalRaw(protocol.DaemonHeartbeatRequestPayload{RuntimeID: rid}),
+ })
+ if err != nil {
+ d.logger.Debug("ws heartbeat marshal failed", "error", err, "runtime_id", rid)
+ continue
+ }
+ select {
+ case writes <- frame:
+ case <-ctx.Done():
+ return
+ default:
+ // Writer is backed up; drop this beat. HTTP heartbeat will resume
+ // on its next tick once the freshness window expires.
+ d.logger.Debug("ws heartbeat dropped: writer backlog", "runtime_id", rid)
+ }
+ }
+}
+
+func marshalRaw(v any) json.RawMessage {
+ data, err := json.Marshal(v)
+ if err != nil {
+ return nil
+ }
+ return data
+}
+
func (d *Daemon) readTaskWakeupMessages(conn *websocket.Conn, taskWakeups chan<- struct{}) error {
conn.SetReadLimit(64 * 1024)
for {
@@ -123,20 +233,31 @@ func (d *Daemon) readTaskWakeupMessages(conn *websocket.Conn, taskWakeups chan<-
d.logger.Debug("task wakeup websocket invalid message", "error", err)
continue
}
- if msg.Type != protocol.EventDaemonTaskAvailable {
- continue
- }
- var payload protocol.TaskAvailablePayload
- if len(msg.Payload) > 0 {
- if err := json.Unmarshal(msg.Payload, &payload); err != nil {
- d.logger.Debug("task wakeup websocket invalid payload", "error", err)
+ switch msg.Type {
+ case protocol.EventDaemonTaskAvailable:
+ var payload protocol.TaskAvailablePayload
+ if len(msg.Payload) > 0 {
+ if err := json.Unmarshal(msg.Payload, &payload); err != nil {
+ d.logger.Debug("task wakeup websocket invalid payload", "error", err)
+ continue
+ }
+ }
+ if payload.RuntimeID != "" {
+ d.logger.Debug("task wakeup received", "runtime_id", payload.RuntimeID, "task_id", payload.TaskID)
+ }
+ signalTaskWakeup(taskWakeups)
+ case protocol.EventDaemonHeartbeatAck:
+ var ack HeartbeatResponse
+ if err := json.Unmarshal(msg.Payload, &ack); err != nil {
+ d.logger.Debug("ws heartbeat ack invalid payload", "error", err)
continue
}
+ if ack.RuntimeID == "" {
+ continue
+ }
+ d.recordWSHeartbeatAck(ack.RuntimeID)
+ d.handleHeartbeatActions(context.Background(), ack.RuntimeID, &ack)
}
- if payload.RuntimeID != "" {
- d.logger.Debug("task wakeup received", "runtime_id", payload.RuntimeID, "task_id", payload.TaskID)
- }
- signalTaskWakeup(taskWakeups)
}
}
diff --git a/server/internal/daemon/wakeup_test.go b/server/internal/daemon/wakeup_test.go
index ce9960fc0b..c7ff957330 100644
--- a/server/internal/daemon/wakeup_test.go
+++ b/server/internal/daemon/wakeup_test.go
@@ -1,6 +1,10 @@
package daemon
-import "testing"
+import (
+ "log/slog"
+ "testing"
+ "time"
+)
func TestTaskWakeupURL(t *testing.T) {
tests := []struct {
@@ -41,3 +45,33 @@ func TestTaskWakeupURL(t *testing.T) {
})
}
}
+
+// TestWSHeartbeatFreshnessSuppressesHTTP pins the WS-vs-HTTP coordination:
+// once a runtime acked over WS within the freshness window the HTTP
+// heartbeat loop must skip it to avoid duplicate DB writes.
+func TestWSHeartbeatFreshnessSuppressesHTTP(t *testing.T) {
+ d := New(Config{HeartbeatInterval: 15 * time.Second}, slog.Default())
+
+ if d.wsHeartbeatRecentlyAcked("runtime-1") {
+ t.Fatalf("expected unrecorded runtime to be stale")
+ }
+
+ d.recordWSHeartbeatAck("runtime-1")
+ if !d.wsHeartbeatRecentlyAcked("runtime-1") {
+ t.Fatalf("expected just-acked runtime to be fresh")
+ }
+
+ // Force the entry past the freshness window.
+ d.wsHBMu.Lock()
+ d.wsHBLastAck["runtime-1"] = time.Now().Add(-d.wsHeartbeatFreshness() - time.Second)
+ d.wsHBMu.Unlock()
+ if d.wsHeartbeatRecentlyAcked("runtime-1") {
+ t.Fatalf("expected aged runtime to be stale (HTTP heartbeat must resume)")
+ }
+
+ d.recordWSHeartbeatAck("runtime-2")
+ d.clearWSHeartbeatAcks()
+ if d.wsHeartbeatRecentlyAcked("runtime-2") {
+ t.Fatalf("expected clearWSHeartbeatAcks to drop all entries")
+ }
+}
diff --git a/server/internal/daemonws/hub.go b/server/internal/daemonws/hub.go
index eeecdacc4b..4496a6f86d 100644
--- a/server/internal/daemonws/hub.go
+++ b/server/internal/daemonws/hub.go
@@ -1,6 +1,7 @@
package daemonws
import (
+ "context"
"encoding/json"
"log/slog"
"net/http"
@@ -64,6 +65,12 @@ func (c *client) markSeen(eventID string) bool {
return true
}
+// HeartbeatHandler processes a daemon:heartbeat frame. It must verify that
+// runtimeID is one of identity.RuntimeIDs (the connection's authenticated
+// scope) and return the ack payload to send back. Returning an error skips
+// the ack and is logged at debug level.
+type HeartbeatHandler func(ctx context.Context, identity ClientIdentity, runtimeID string) (*protocol.DaemonHeartbeatAckPayload, error)
+
// Hub keeps daemon WebSocket connections indexed by runtime ID. Messages are
// best-effort wakeup hints; the daemon still uses HTTP claim for correctness.
type Hub struct {
@@ -72,6 +79,9 @@ type Hub struct {
mu sync.RWMutex
clients map[*client]bool
byRuntime map[string]map[*client]bool
+
+ hbMu sync.RWMutex
+ onHeartbeat HeartbeatHandler
}
func NewHub() *Hub {
@@ -89,6 +99,26 @@ func NewHub() *Hub {
}
}
+// SetHeartbeatHandler installs the callback used for daemon:heartbeat frames.
+// Wiring is done after handler construction because the handler depends on
+// DB queries that aren't available when the hub is built. A nil handler
+// disables WS heartbeat processing — daemons fall back to HTTP heartbeat
+// transparently because their fallback timer fires whenever no ack arrives.
+func (h *Hub) SetHeartbeatHandler(fn HeartbeatHandler) {
+ if h == nil {
+ return
+ }
+ h.hbMu.Lock()
+ h.onHeartbeat = fn
+ h.hbMu.Unlock()
+}
+
+func (h *Hub) heartbeatHandler() HeartbeatHandler {
+ h.hbMu.RLock()
+ defer h.hbMu.RUnlock()
+ return h.onHeartbeat
+}
+
func (h *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request, identity ClientIdentity) {
if len(identity.RuntimeIDs) == 0 {
http.Error(w, `{"error":"runtime_ids required"}`, http.StatusBadRequest)
@@ -315,9 +345,78 @@ func (c *client) handleFrame(raw []byte) {
slog.Debug("daemon websocket invalid frame", "error", err, "daemon_id", c.identity.DaemonID)
return
}
- // The phase-one daemon channel is server-push only. Inbound frames are
- // drained so control frames and close handling work, but app messages are
- // intentionally ignored for forward compatibility.
+ switch msg.Type {
+ case protocol.EventDaemonHeartbeat:
+ c.handleHeartbeatFrame(msg.Payload)
+ default:
+ // Unknown app messages are intentionally ignored for forward
+ // compatibility with future daemon → server message types.
+ }
+}
+
+// handleHeartbeatFrame processes an inbound daemon:heartbeat from the daemon,
+// invokes the hub's handler, and writes back a daemon:heartbeat_ack.
+func (c *client) handleHeartbeatFrame(raw json.RawMessage) {
+ handler := c.hub.heartbeatHandler()
+ if handler == nil {
+ // Server doesn't have a heartbeat handler wired — daemon will time
+ // out waiting for an ack and fall back to HTTP heartbeat.
+ return
+ }
+
+ var payload protocol.DaemonHeartbeatRequestPayload
+ if err := json.Unmarshal(raw, &payload); err != nil {
+ slog.Debug("daemon websocket heartbeat invalid payload", "error", err, "daemon_id", c.identity.DaemonID)
+ return
+ }
+ if payload.RuntimeID == "" {
+ slog.Debug("daemon websocket heartbeat missing runtime_id", "daemon_id", c.identity.DaemonID)
+ return
+ }
+ if _, ok := c.runtimes[payload.RuntimeID]; !ok {
+ // The connection authenticated for a fixed runtime set; reject any
+ // heartbeat for a runtime the client did not register for.
+ slog.Warn("daemon websocket heartbeat for unauthorized runtime",
+ "daemon_id", c.identity.DaemonID,
+ "runtime_id", payload.RuntimeID)
+ return
+ }
+
+ // Intentionally do NOT wrap this ctx with WithTimeout. The handler
+ // reaches LocalSkill{List,Import}Store.PopPending, whose Redis Lua
+ // claim script has side effects (ZREM + SET-running) that cannot be
+ // safely un-run if the client cancels mid-script — the same invariant
+ // that keeps the HTTP heartbeat from putting a per-call timeout on
+ // PopPending. The natural bound is the read pump's lifetime (the conn
+ // closes if the daemon goes away) plus Redis's own server-side limits.
+ ack, err := handler(context.Background(), c.identity, payload.RuntimeID)
+ if err != nil {
+ slog.Warn("daemon websocket heartbeat handler failed",
+ "error", err,
+ "daemon_id", c.identity.DaemonID,
+ "runtime_id", payload.RuntimeID)
+ return
+ }
+ if ack == nil {
+ return
+ }
+ frame, err := json.Marshal(protocol.Message{
+ Type: protocol.EventDaemonHeartbeatAck,
+ Payload: mustMarshalRaw(ack),
+ })
+ if err != nil {
+ slog.Debug("daemon websocket heartbeat ack marshal failed", "error", err)
+ return
+ }
+ select {
+ case c.send <- frame:
+ default:
+ // Send buffer is full — slow client. Don't block the read pump; the
+ // next writePump tick or notifyFrame eviction will clean up.
+ slog.Debug("daemon websocket heartbeat ack dropped: send buffer full",
+ "daemon_id", c.identity.DaemonID,
+ "runtime_id", payload.RuntimeID)
+ }
}
func (c *client) writePump() {
diff --git a/server/internal/daemonws/hub_test.go b/server/internal/daemonws/hub_test.go
index c522c87232..8f66351d4c 100644
--- a/server/internal/daemonws/hub_test.go
+++ b/server/internal/daemonws/hub_test.go
@@ -1,10 +1,12 @@
package daemonws
import (
+ "context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
+ "sync/atomic"
"testing"
"time"
@@ -139,6 +141,197 @@ func TestRelayNotifierDedupsLocalRedisLoopback(t *testing.T) {
}
}
+// TestHeartbeatRoundTrip pins the WS heartbeat contract: a daemon:heartbeat
+// frame invokes the registered HeartbeatHandler with the runtime ID, and the
+// hub serializes the returned ack as a daemon:heartbeat_ack on the wire.
+func TestHeartbeatRoundTrip(t *testing.T) {
+ M.Reset()
+ defer M.Reset()
+
+ hub := NewHub()
+ var calls atomic.Int32
+ hub.SetHeartbeatHandler(func(_ context.Context, identity ClientIdentity, runtimeID string) (*protocol.DaemonHeartbeatAckPayload, error) {
+ calls.Add(1)
+ if identity.WorkspaceID != "ws-1" {
+ t.Errorf("identity workspace = %q, want ws-1", identity.WorkspaceID)
+ }
+ return &protocol.DaemonHeartbeatAckPayload{
+ RuntimeID: runtimeID,
+ Status: "ok",
+ PendingUpdate: &protocol.DaemonHeartbeatPendingUpdate{
+ ID: "update-1",
+ TargetVersion: "0.1.99",
+ },
+ }, nil
+ })
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hub.HandleWebSocket(w, r, ClientIdentity{
+ WorkspaceID: "ws-1",
+ RuntimeIDs: []string{"runtime-1"},
+ })
+ }))
+ defer server.Close()
+
+ wsURL := "ws" + strings.TrimPrefix(server.URL, "http")
+ conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
+ if err != nil {
+ t.Fatalf("Dial: %v", err)
+ }
+ defer conn.Close()
+
+ hbFrame, err := json.Marshal(protocol.Message{
+ Type: protocol.EventDaemonHeartbeat,
+ Payload: mustMarshalRaw(protocol.DaemonHeartbeatRequestPayload{RuntimeID: "runtime-1"}),
+ })
+ if err != nil {
+ t.Fatalf("marshal heartbeat: %v", err)
+ }
+ if err := conn.WriteMessage(websocket.TextMessage, hbFrame); err != nil {
+ t.Fatalf("WriteMessage: %v", err)
+ }
+
+ if err := conn.SetReadDeadline(time.Now().Add(time.Second)); err != nil {
+ t.Fatalf("SetReadDeadline: %v", err)
+ }
+ _, raw, err := conn.ReadMessage()
+ if err != nil {
+ t.Fatalf("ReadMessage: %v", err)
+ }
+
+ var msg protocol.Message
+ if err := json.Unmarshal(raw, &msg); err != nil {
+ t.Fatalf("unmarshal ack envelope: %v", err)
+ }
+ if msg.Type != protocol.EventDaemonHeartbeatAck {
+ t.Fatalf("ack type = %q, want %q", msg.Type, protocol.EventDaemonHeartbeatAck)
+ }
+ var ack protocol.DaemonHeartbeatAckPayload
+ if err := json.Unmarshal(msg.Payload, &ack); err != nil {
+ t.Fatalf("unmarshal ack payload: %v", err)
+ }
+ if ack.RuntimeID != "runtime-1" {
+ t.Fatalf("ack runtime_id = %q, want runtime-1", ack.RuntimeID)
+ }
+ if ack.PendingUpdate == nil || ack.PendingUpdate.ID != "update-1" {
+ t.Fatalf("ack pending_update = %+v, want update-1", ack.PendingUpdate)
+ }
+ if got := calls.Load(); got != 1 {
+ t.Fatalf("HeartbeatHandler invocations = %d, want 1", got)
+ }
+}
+
+// TestHeartbeatHandlerCtxNotTimeBounded pins the PopPending invariant: the
+// hub must not wrap the handler ctx with a short WithTimeout, otherwise the
+// Redis Lua claim script can be cancelled mid-flight after its side effects
+// have already landed. We assert by stalling the handler past any timeout
+// the hub might be tempted to add and verifying the ack still arrives.
+func TestHeartbeatHandlerCtxNotTimeBounded(t *testing.T) {
+ M.Reset()
+ defer M.Reset()
+
+ hub := NewHub()
+ const stall = 250 * time.Millisecond
+ hub.SetHeartbeatHandler(func(ctx context.Context, _ ClientIdentity, runtimeID string) (*protocol.DaemonHeartbeatAckPayload, error) {
+ select {
+ case <-time.After(stall):
+ case <-ctx.Done():
+ t.Errorf("handler ctx was cancelled (deadline=%v) — PopPending invariant violated", ctx.Err())
+ return nil, ctx.Err()
+ }
+ if _, ok := ctx.Deadline(); ok {
+ t.Errorf("handler ctx must not carry a deadline; PopPending side effects cannot be safely un-run")
+ }
+ return &protocol.DaemonHeartbeatAckPayload{RuntimeID: runtimeID, Status: "ok"}, nil
+ })
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hub.HandleWebSocket(w, r, ClientIdentity{RuntimeIDs: []string{"runtime-1"}})
+ }))
+ defer server.Close()
+
+ wsURL := "ws" + strings.TrimPrefix(server.URL, "http")
+ conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
+ if err != nil {
+ t.Fatalf("Dial: %v", err)
+ }
+ defer conn.Close()
+
+ hbFrame, err := json.Marshal(protocol.Message{
+ Type: protocol.EventDaemonHeartbeat,
+ Payload: mustMarshalRaw(protocol.DaemonHeartbeatRequestPayload{RuntimeID: "runtime-1"}),
+ })
+ if err != nil {
+ t.Fatalf("marshal heartbeat: %v", err)
+ }
+ if err := conn.WriteMessage(websocket.TextMessage, hbFrame); err != nil {
+ t.Fatalf("WriteMessage: %v", err)
+ }
+
+ if err := conn.SetReadDeadline(time.Now().Add(stall + 2*time.Second)); err != nil {
+ t.Fatalf("SetReadDeadline: %v", err)
+ }
+ _, raw, err := conn.ReadMessage()
+ if err != nil {
+ t.Fatalf("ReadMessage: %v", err)
+ }
+ var msg protocol.Message
+ if err := json.Unmarshal(raw, &msg); err != nil {
+ t.Fatalf("unmarshal ack: %v", err)
+ }
+ if msg.Type != protocol.EventDaemonHeartbeatAck {
+ t.Fatalf("ack type = %q, want %q", msg.Type, protocol.EventDaemonHeartbeatAck)
+ }
+}
+
+// TestHeartbeatRejectsUnauthorizedRuntime verifies that a heartbeat for a
+// runtime outside the connection's authenticated set is dropped silently —
+// no handler call, no ack frame.
+func TestHeartbeatRejectsUnauthorizedRuntime(t *testing.T) {
+ M.Reset()
+ defer M.Reset()
+
+ hub := NewHub()
+ var called atomic.Bool
+ hub.SetHeartbeatHandler(func(context.Context, ClientIdentity, string) (*protocol.DaemonHeartbeatAckPayload, error) {
+ called.Store(true)
+ return &protocol.DaemonHeartbeatAckPayload{Status: "ok"}, nil
+ })
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hub.HandleWebSocket(w, r, ClientIdentity{RuntimeIDs: []string{"runtime-1"}})
+ }))
+ defer server.Close()
+
+ wsURL := "ws" + strings.TrimPrefix(server.URL, "http")
+ conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
+ if err != nil {
+ t.Fatalf("Dial: %v", err)
+ }
+ defer conn.Close()
+
+ hbFrame, err := json.Marshal(protocol.Message{
+ Type: protocol.EventDaemonHeartbeat,
+ Payload: mustMarshalRaw(protocol.DaemonHeartbeatRequestPayload{RuntimeID: "runtime-other"}),
+ })
+ if err != nil {
+ t.Fatalf("marshal heartbeat: %v", err)
+ }
+ if err := conn.WriteMessage(websocket.TextMessage, hbFrame); err != nil {
+ t.Fatalf("WriteMessage: %v", err)
+ }
+
+ if err := conn.SetReadDeadline(time.Now().Add(150 * time.Millisecond)); err != nil {
+ t.Fatalf("SetReadDeadline: %v", err)
+ }
+ if _, _, err := conn.ReadMessage(); err == nil {
+ t.Fatalf("expected no ack for unauthorized runtime, got message")
+ }
+ if called.Load() {
+ t.Fatalf("HeartbeatHandler invoked for unauthorized runtime")
+ }
+}
+
func attachDaemonTestClient(hub *Hub, runtimeID string) *client {
c := &client{
send: make(chan []byte, 2),
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index cca9ec3600..d338cf0469 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -17,8 +17,10 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/daemonws"
"github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
"github.com/multica-ai/multica/server/pkg/redact"
@@ -574,90 +576,159 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {
}
authMs = time.Since(start).Milliseconds()
- updateStart := time.Now()
- _, updateErr := h.Queries.UpdateAgentRuntimeHeartbeat(r.Context(), rt.ID)
- updateMs = time.Since(updateStart).Milliseconds()
- if updateErr != nil {
+ ack, m, err := h.processHeartbeat(r.Context(), rt)
+ updateMs = m.UpdateMs
+ probeSkillsMs = m.ProbeSkillsMs
+ popSkillsMs = m.PopSkillsMs
+ probeImportMs = m.ProbeImportMs
+ popImportMs = m.PopImportMs
+ probeSkillsTimedOut = m.ProbeSkillsTimedOut
+ probeImportTimedOut = m.ProbeImportTimedOut
+ if err != nil {
outcome = "error_update"
writeError(w, http.StatusInternalServerError, "heartbeat failed")
return
}
- slog.Debug("daemon heartbeat", "runtime_id", req.RuntimeID)
+ outcome = "ok"
+ // Preserve the existing HTTP response shape: the runtime_id field is new
+ // in the WS path and would be redundant noise on the HTTP path where the
+ // caller already knows which runtime it asked about.
+ resp := map[string]any{"status": ack.Status}
+ if ack.PendingUpdate != nil {
+ resp["pending_update"] = ack.PendingUpdate
+ }
+ if ack.PendingModelList != nil {
+ resp["pending_model_list"] = ack.PendingModelList
+ }
+ if ack.PendingLocalSkills != nil {
+ resp["pending_local_skills"] = ack.PendingLocalSkills
+ }
+ if ack.PendingLocalSkillImport != nil {
+ resp["pending_local_skill_import"] = ack.PendingLocalSkillImport
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
- resp := map[string]any{"status": "ok"}
+// HandleDaemonWSHeartbeat is the daemonws.HeartbeatHandler entry point: it
+// resolves the runtime, verifies the connection's workspace owns it, and
+// returns the ack payload. It is the WebSocket-side mirror of DaemonHeartbeat.
+//
+// Workspace authorization is re-checked on every heartbeat instead of trusted
+// from the upgrade-time check because runtime ownership can change (e.g. a
+// runtime is reassigned to another workspace mid-connection).
+func (h *Handler) HandleDaemonWSHeartbeat(ctx context.Context, identity daemonws.ClientIdentity, runtimeID string) (*protocol.DaemonHeartbeatAckPayload, error) {
+ runtimeUUID, err := util.ParseUUID(runtimeID)
+ if err != nil {
+ return nil, fmt.Errorf("invalid runtime_id: %w", err)
+ }
+ rt, err := h.Queries.GetAgentRuntime(ctx, runtimeUUID)
+ if err != nil {
+ return nil, fmt.Errorf("runtime not found: %w", err)
+ }
+ if identity.WorkspaceID != "" && identity.WorkspaceID != uuidToString(rt.WorkspaceID) {
+ return nil, fmt.Errorf("runtime not in connection workspace")
+ }
+ ack, _, err := h.processHeartbeat(ctx, rt)
+ return ack, err
+}
+
+// heartbeatMetrics carries per-stage timings out of processHeartbeat so the
+// HTTP slow-log can stay structured. The WS path discards them.
+type heartbeatMetrics struct {
+ UpdateMs, ProbeSkillsMs, PopSkillsMs, ProbeImportMs, PopImportMs int64
+ ProbeSkillsTimedOut, ProbeImportTimedOut bool
+}
+
+// processHeartbeat does the work shared by HTTP POST /api/daemon/heartbeat and
+// the WebSocket daemon:heartbeat path: bumps last_seen_at and pulls any
+// pending actions queued for the runtime. Auth and request decoding live in
+// the caller because they differ between transports.
+func (h *Handler) processHeartbeat(ctx context.Context, rt db.AgentRuntime) (*protocol.DaemonHeartbeatAckPayload, heartbeatMetrics, error) {
+ var m heartbeatMetrics
+ runtimeID := uuidToString(rt.ID)
+
+ updateStart := time.Now()
+ _, updateErr := h.Queries.UpdateAgentRuntimeHeartbeat(ctx, rt.ID)
+ m.UpdateMs = time.Since(updateStart).Milliseconds()
+ if updateErr != nil {
+ return nil, m, updateErr
+ }
- // Check for pending update requests for this runtime.
- if pending := h.UpdateStore.PopPending(req.RuntimeID); pending != nil {
- resp["pending_update"] = map[string]string{
- "id": pending.ID,
- "target_version": pending.TargetVersion,
+ slog.Debug("daemon heartbeat", "runtime_id", runtimeID)
+
+ ack := &protocol.DaemonHeartbeatAckPayload{
+ RuntimeID: runtimeID,
+ Status: "ok",
+ }
+
+ if pending := h.UpdateStore.PopPending(runtimeID); pending != nil {
+ ack.PendingUpdate = &protocol.DaemonHeartbeatPendingUpdate{
+ ID: pending.ID,
+ TargetVersion: pending.TargetVersion,
}
}
- // Check for pending model-list requests for this runtime.
- if pending := h.ModelListStore.PopPending(req.RuntimeID); pending != nil {
- resp["pending_model_list"] = map[string]string{"id": pending.ID}
+ if pending := h.ModelListStore.PopPending(runtimeID); pending != nil {
+ ack.PendingModelList = &protocol.DaemonHeartbeatPendingModelList{ID: pending.ID}
}
// Probe then claim the local-skill list queue. The probe is bounded so a
// slow shared store cannot stall the heartbeat on empty-queue ticks; the
- // claim runs unbounded (it inherits only r.Context()) because its Lua
- // side effects cannot be safely aborted mid-script.
+ // claim runs unbounded (it inherits only ctx) because its Lua side
+ // effects cannot be safely aborted mid-script.
probeSkillsStart := time.Now()
- probeSkillsCtx, cancelProbeSkills := context.WithTimeout(r.Context(), heartbeatHasPendingTimeout)
- hasSkills, probeErr := h.LocalSkillListStore.HasPending(probeSkillsCtx, req.RuntimeID)
+ probeSkillsCtx, cancelProbeSkills := context.WithTimeout(ctx, heartbeatHasPendingTimeout)
+ hasSkills, probeErr := h.LocalSkillListStore.HasPending(probeSkillsCtx, runtimeID)
cancelProbeSkills()
- probeSkillsMs = time.Since(probeSkillsStart).Milliseconds()
+ m.ProbeSkillsMs = time.Since(probeSkillsStart).Milliseconds()
switch {
case probeErr == nil && hasSkills:
popStart := time.Now()
- pendingSkills, popErr := h.LocalSkillListStore.PopPending(r.Context(), req.RuntimeID)
- popSkillsMs = time.Since(popStart).Milliseconds()
+ pendingSkills, popErr := h.LocalSkillListStore.PopPending(ctx, runtimeID)
+ m.PopSkillsMs = time.Since(popStart).Milliseconds()
if popErr != nil {
- slog.Warn("local skill list PopPending failed", "error", popErr, "runtime_id", req.RuntimeID)
+ slog.Warn("local skill list PopPending failed", "error", popErr, "runtime_id", runtimeID)
} else if pendingSkills != nil {
- resp["pending_local_skills"] = map[string]string{"id": pendingSkills.ID}
+ ack.PendingLocalSkills = &protocol.DaemonHeartbeatPendingLocalSkills{ID: pendingSkills.ID}
}
case probeErr != nil:
if errors.Is(probeErr, context.DeadlineExceeded) || errors.Is(probeErr, context.Canceled) {
- probeSkillsTimedOut = true
- slog.Warn("local skill list HasPending timed out", "runtime_id", req.RuntimeID, "elapsed_ms", probeSkillsMs)
+ m.ProbeSkillsTimedOut = true
+ slog.Warn("local skill list HasPending timed out", "runtime_id", runtimeID, "elapsed_ms", m.ProbeSkillsMs)
} else {
- slog.Warn("local skill list HasPending failed", "error", probeErr, "runtime_id", req.RuntimeID)
+ slog.Warn("local skill list HasPending failed", "error", probeErr, "runtime_id", runtimeID)
}
}
- // Same probe-then-claim pattern for the import queue.
probeImportStart := time.Now()
- probeImportCtx, cancelProbeImport := context.WithTimeout(r.Context(), heartbeatHasPendingTimeout)
- hasImport, probeErr := h.LocalSkillImportStore.HasPending(probeImportCtx, req.RuntimeID)
+ probeImportCtx, cancelProbeImport := context.WithTimeout(ctx, heartbeatHasPendingTimeout)
+ hasImport, probeErr := h.LocalSkillImportStore.HasPending(probeImportCtx, runtimeID)
cancelProbeImport()
- probeImportMs = time.Since(probeImportStart).Milliseconds()
+ m.ProbeImportMs = time.Since(probeImportStart).Milliseconds()
switch {
case probeErr == nil && hasImport:
popStart := time.Now()
- pendingImport, popErr := h.LocalSkillImportStore.PopPending(r.Context(), req.RuntimeID)
- popImportMs = time.Since(popStart).Milliseconds()
+ pendingImport, popErr := h.LocalSkillImportStore.PopPending(ctx, runtimeID)
+ m.PopImportMs = time.Since(popStart).Milliseconds()
if popErr != nil {
- slog.Warn("local skill import PopPending failed", "error", popErr, "runtime_id", req.RuntimeID)
+ slog.Warn("local skill import PopPending failed", "error", popErr, "runtime_id", runtimeID)
} else if pendingImport != nil {
- resp["pending_local_skill_import"] = map[string]string{
- "id": pendingImport.ID,
- "skill_key": pendingImport.SkillKey,
+ ack.PendingLocalSkillImport = &protocol.DaemonHeartbeatPendingLocalSkillImport{
+ ID: pendingImport.ID,
+ SkillKey: pendingImport.SkillKey,
}
}
case probeErr != nil:
if errors.Is(probeErr, context.DeadlineExceeded) || errors.Is(probeErr, context.Canceled) {
- probeImportTimedOut = true
- slog.Warn("local skill import HasPending timed out", "runtime_id", req.RuntimeID, "elapsed_ms", probeImportMs)
+ m.ProbeImportTimedOut = true
+ slog.Warn("local skill import HasPending timed out", "runtime_id", runtimeID, "elapsed_ms", m.ProbeImportMs)
} else {
- slog.Warn("local skill import HasPending failed", "error", probeErr, "runtime_id", req.RuntimeID)
+ slog.Warn("local skill import HasPending failed", "error", probeErr, "runtime_id", runtimeID)
}
}
- outcome = "ok"
- writeJSON(w, http.StatusOK, resp)
+ return ack, m, nil
}
// logHeartbeatEndpointSlow emits one structured log when /api/daemon/heartbeat
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index 47810746e7..d52c4284db 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -99,6 +99,7 @@ const (
// Daemon events
EventDaemonHeartbeat = "daemon:heartbeat"
+ EventDaemonHeartbeatAck = "daemon:heartbeat_ack"
EventDaemonRegister = "daemon:register"
EventDaemonTaskAvailable = "daemon:task_available"
)
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index d98d01456b..4381aaadf6 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -87,9 +87,47 @@ type ChatSessionReadPayload struct {
ChatSessionID string `json:"chat_session_id"`
}
-// HeartbeatPayload is sent periodically from daemon to server.
-type HeartbeatPayload struct {
- DaemonID string `json:"daemon_id"`
- AgentID string `json:"agent_id"`
- CurrentTasks int `json:"current_tasks"`
+// DaemonHeartbeatRequestPayload is sent from daemon to server over WebSocket
+// to update last_seen_at and pull pending actions for a single runtime.
+// Mirrors the body of POST /api/daemon/heartbeat so both transports share
+// identical semantics.
+type DaemonHeartbeatRequestPayload struct {
+ RuntimeID string `json:"runtime_id"`
+}
+
+// DaemonHeartbeatAckPayload is the server's reply to DaemonHeartbeatRequestPayload.
+// JSON shape mirrors the HTTP heartbeat response so daemon code can decode either.
+type DaemonHeartbeatAckPayload struct {
+ RuntimeID string `json:"runtime_id"`
+ Status string `json:"status"`
+ PendingUpdate *DaemonHeartbeatPendingUpdate `json:"pending_update,omitempty"`
+ PendingModelList *DaemonHeartbeatPendingModelList `json:"pending_model_list,omitempty"`
+ PendingLocalSkills *DaemonHeartbeatPendingLocalSkills `json:"pending_local_skills,omitempty"`
+ PendingLocalSkillImport *DaemonHeartbeatPendingLocalSkillImport `json:"pending_local_skill_import,omitempty"`
+}
+
+// DaemonHeartbeatPendingUpdate describes a CLI-update action the daemon
+// should run for the runtime.
+type DaemonHeartbeatPendingUpdate struct {
+ ID string `json:"id"`
+ TargetVersion string `json:"target_version"`
+}
+
+// DaemonHeartbeatPendingModelList describes a request for the daemon to
+// enumerate the runtime's supported models.
+type DaemonHeartbeatPendingModelList struct {
+ ID string `json:"id"`
+}
+
+// DaemonHeartbeatPendingLocalSkills describes a request for the runtime's
+// local-skill inventory.
+type DaemonHeartbeatPendingLocalSkills struct {
+ ID string `json:"id"`
+}
+
+// DaemonHeartbeatPendingLocalSkillImport describes a request to import a
+// specific runtime local skill.
+type DaemonHeartbeatPendingLocalSkillImport struct {
+ ID string `json:"id"`
+ SkillKey string `json:"skill_key"`
}