Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-4775: fix(daemon): negotiate websocket RPC support
texjarvisf2c4b2cf5097
diff --git a/server/internal/daemon/daemon_legacy_fallback_test.go b/server/internal/daemon/daemon_legacy_fallback_test.goindex 2ce98324cf..b0e54dd2ab 100644--- a/server/internal/daemon/daemon_legacy_fallback_test.go+++ b/server/internal/daemon/daemon_legacy_fallback_test.go@@ -95,12 +95,13 @@ func TestClaimTasksWSFirst_NoDoubleClaimOnDetach(t *testing.T) {// disconnect leaves a genuinely uncertain outcome (the server may commit).var mu sync.Mutexvar item *wsOutbound- d.wsRPC.attach(func(frame []byte) (*wsOutbound, error) {+ generation := d.wsRPC.attach(func(frame []byte) (*wsOutbound, error) {mu.Lock()defer mu.Unlock()item = &wsOutbound{data: frame}return item, nil})+ d.wsRPC.markRPCV1Supported(generation)done := make(chan struct{})var tasks []*Task@@ -131,3 +132,44 @@ func TestClaimTasksWSFirst_NoDoubleClaimOnDetach(t *testing.T) {t.Fatalf("HTTP fallback claimed %d times after an uncertain WS claim; must be 0 to avoid double-claim", httpClaims.Load())}}++// TestClaimTasksWSFirst_ReconnectToOldServerSkipsWSRPC pins compatibility when+// a daemon moves from an rpc-v1 server to an older server. The replacement+// connection must not inherit the first connection's negotiated capability;+// old servers ignore unknown WS frames, so claims must use HTTP until a fresh+// heartbeat ack explicitly advertises server support.+func TestClaimTasksWSFirst_ReconnectToOldServerSkipsWSRPC(t *testing.T) {+ var httpClaims, wsClaims atomic.Int64+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if strings.Contains(r.URL.Path, "/claim") {+ httpClaims.Add(1)+ }+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"tasks":[{"id":"http-t","runtime_id":"rt1","agent":{"name":"a"}}]}`))+ }))+ defer srv.Close()++ d := New(Config{ServerBaseURL: srv.URL, MaxConcurrentTasks: 4}, slog.New(slog.NewTextHandler(noopWriter{}, nil)))+ previousGeneration := d.wsRPC.attach(func(frame []byte) (*wsOutbound, error) {+ return &wsOutbound{data: frame}, nil+ })+ d.wsRPC.markRPCV1Supported(previousGeneration)+ d.wsRPC.attach(func(frame []byte) (*wsOutbound, error) {+ wsClaims.Add(1)+ return &wsOutbound{data: frame}, nil+ })++ tasks, err := d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 1)+ if err != nil {+ t.Fatalf("ClaimTasksWSFirst: %v", err)+ }+ if len(tasks) != 1 || tasks[0].ID != "http-t" {+ t.Fatalf("tasks = %#v, want HTTP task", tasks)+ }+ if wsClaims.Load() != 0 {+ t.Fatalf("WS claims = %d without rpc-v1 advertisement, want 0", wsClaims.Load())+ }+ if httpClaims.Load() != 1 {+ t.Fatalf("HTTP claims = %d, want 1", httpClaims.Load())+ }+}diff --git a/server/internal/daemon/runtime_gone_test.go b/server/internal/daemon/runtime_gone_test.goindex 0d479b0744..842b1b2f1e 100644--- a/server/internal/daemon/runtime_gone_test.go+++ b/server/internal/daemon/runtime_gone_test.go@@ -312,13 +312,21 @@ func TestHandleWSHeartbeatAck_NormalAckRecordsFreshness(t *testing.T) {t.Parallel()d := freshDaemon("")- d.handleWSHeartbeatAck(context.Background(), &HeartbeatResponse{- RuntimeID: "rt-1",- Status: "ok",+ d.wsRPC = newWSRPCClient(wsRPCResponseGrace)+ generation := d.wsRPC.attach(func(frame []byte) (*wsOutbound, error) {+ return &wsOutbound{data: frame}, nil})+ d.handleWSHeartbeatAckForConnection(context.Background(), &HeartbeatResponse{+ RuntimeID: "rt-1",+ Status: "ok",+ ServerCapabilities: []string{"rpc-v1"},+ }, generation)if !d.wsHeartbeatRecentlyAcked("rt-1") {t.Fatalf("normal ack should record WS freshness for rt-1")}+ if !d.wsRPC.supportsRPCV1() {+ t.Fatal("rpc-v1 heartbeat acknowledgement should enable WS RPC")+ }}func TestHandleWSHeartbeatAck_EmptyAckIgnored(t *testing.T) {diff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.goindex 8e5a6f9c5c..f31a7924b7 100644--- a/server/internal/daemon/wakeup.go+++ b/server/internal/daemon/wakeup.go@@ -166,7 +166,7 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strin// close(writes), and the sender holds sendMu across its non-blocking send.var sendMu sync.MutexsendClosed := false- d.wsRPC.attach(func(frame []byte) (*wsOutbound, error) {+ wsRPCGeneration := d.wsRPC.attach(func(frame []byte) (*wsOutbound, error) {sendMu.Lock()defer sendMu.Unlock()if sendClosed {@@ -193,7 +193,7 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strinerrCh := make(chan error, 1)go func() {- errCh <- d.readTaskWakeupMessages(conn, taskWakeups)+ errCh <- d.readTaskWakeupMessagesForConnection(conn, taskWakeups, wsRPCGeneration)}()// Defer cleanup must shut goroutines down in this order:@@ -334,6 +334,10 @@ func marshalRaw(v any) json.RawMessage {// handleRuntimeGone uses the daemon root context for its register call, so// this function can safely pass any caller context here.func (d *Daemon) handleWSHeartbeatAck(ctx context.Context, ack *HeartbeatResponse) {+ d.handleWSHeartbeatAckForConnection(ctx, ack, d.wsRPC.currentGeneration())+}++func (d *Daemon) handleWSHeartbeatAckForConnection(ctx context.Context, ack *HeartbeatResponse, wsRPCGeneration uint64) {if ack == nil || ack.RuntimeID == "" {return}@@ -341,11 +345,21 @@ func (d *Daemon) handleWSHeartbeatAck(ctx context.Context, ack *HeartbeatResponsgo d.handleRuntimeGone(ack.RuntimeID)return}+ for _, capability := range ack.ServerCapabilities {+ if capability == protocol.DaemonCapabilityRPCV1 {+ d.wsRPC.markRPCV1Supported(wsRPCGeneration)+ break+ }+ }d.recordWSHeartbeatAck(ack.RuntimeID)d.handleHeartbeatActions(ctx, ack.RuntimeID, ack)}func (d *Daemon) readTaskWakeupMessages(conn *websocket.Conn, taskWakeups chan<- taskWakeup) error {+ return d.readTaskWakeupMessagesForConnection(conn, taskWakeups, d.wsRPC.currentGeneration())+}++func (d *Daemon) readTaskWakeupMessagesForConnection(conn *websocket.Conn, taskWakeups chan<- taskWakeup, wsRPCGeneration uint64) error {d.configureTaskWakeupReadLiveness(conn)for {_, raw, err := conn.ReadMessage()@@ -394,7 +408,7 @@ func (d *Daemon) readTaskWakeupMessages(conn *websocket.Conn, taskWakeups chan<-d.logger.Debug("ws heartbeat ack invalid payload", "error", err)continue}- d.handleWSHeartbeatAck(context.Background(), &ack)+ d.handleWSHeartbeatAckForConnection(context.Background(), &ack, wsRPCGeneration)case protocol.EventDaemonRPCResponse:var resp protocol.RPCResponsePayloadif err := json.Unmarshal(msg.Payload, &resp); err != nil {diff --git a/server/internal/daemon/wsrpc.go b/server/internal/daemon/wsrpc.goindex afed826ed1..e35bf77763 100644--- a/server/internal/daemon/wsrpc.go+++ b/server/internal/daemon/wsrpc.go@@ -83,6 +83,11 @@ type wsRPCClient struct {mu sync.Mutexpending map[string]chan protocol.RPCResponsePayloadsendFrame func([]byte) (*wsOutbound, error)+ // rpcV1Supported belongs to the currently attached connection. attach+ // clears it before exposing a replacement sender so a claim that races a+ // reconnect can never carry negotiation state across connections.+ rpcV1Supported bool+ generation uint64// grace is added to a call's server-side timeout budget to get how long the// daemon waits for the response, so a claim that committed just before the// server deadline still reports back before the daemon gives up (MUL-4257).@@ -96,38 +101,82 @@ func newWSRPCClient(grace time.Duration) *wsRPCClient {}}-// attach binds a live connection's frame writer. Passing nil detaches (on-// disconnect), after which Call fails fast until the next attach. Any pending-// requests are failed so their callers fall back to HTTP immediately.-func (c *wsRPCClient) attach(sendFrame func([]byte) (*wsOutbound, error)) {+// attach binds a live connection's frame writer and clears the previous+// connection's negotiated capability. Passing nil detaches (on disconnect),+// after which Call fails fast until the next attach and rpc-v1 heartbeat ack.+// Any pending requests are failed so their callers fall back to HTTP+// immediately.+func (c *wsRPCClient) attach(sendFrame func([]byte) (*wsOutbound, error)) uint64 {c.mu.Lock()+ c.generation+++ c.rpcV1Supported = falsec.sendFrame = sendFrame- if sendFrame == nil {- for id, ch := range c.pending {- close(ch)- delete(c.pending, id)- }+ for id, ch := range c.pending {+ close(ch)+ delete(c.pending, id)}+ generation := c.generationc.mu.Unlock()+ return generation+}++// markRPCV1Supported records explicit server support for the currently+// attached connection. Heartbeat acks received without a live sender cannot+// enable a future connection.+func (c *wsRPCClient) markRPCV1Supported(generation uint64) {+ if c == nil {+ return+ }+ c.mu.Lock()+ if c.sendFrame != nil && c.generation == generation {+ c.rpcV1Supported = true+ }+ c.mu.Unlock()+}++func (c *wsRPCClient) currentGeneration() uint64 {+ if c == nil {+ return 0+ }+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.generation}-// connected reports whether a live connection is attached.-func (c *wsRPCClient) connected() bool {+// supportsRPCV1 reports whether the live connection explicitly negotiated+// rpc-v1. Call repeats this check while capturing the sender under the same+// mutex, so this method is only a fast-path hint and cannot authorize a send by+// itself.+func (c *wsRPCClient) supportsRPCV1() bool {if c == nil {return false}c.mu.Lock()defer c.mu.Unlock()- return c.sendFrame != nil+ return c.sendFrame != nil && c.rpcV1Supported}-// Call issues an RPC and blocks until the response, the per-request timeout, or-// ctx cancellation. reqBody is marshaled into the request envelope; on a 2xx+// Call issues an RPC on any attached connection. Transport-level tests and+// callers that have their own negotiation contract use this directly.+func (c *wsRPCClient) Call(ctx context.Context, method string, serverTimeout time.Duration, reqBody, respBody any) (int, error) {+ return c.call(ctx, method, serverTimeout, reqBody, respBody, false)+}++// CallIfRPCV1Supported issues an RPC only when the currently attached+// connection explicitly negotiated rpc-v1. The capability check and sender+// capture happen under the same mutex, so a reconnect cannot redirect a call+// authorized by the previous connection onto its replacement.+func (c *wsRPCClient) CallIfRPCV1Supported(ctx context.Context, method string, serverTimeout time.Duration, reqBody, respBody any) (int, error) {+ return c.call(ctx, method, serverTimeout, reqBody, respBody, true)+}++// call blocks until the response, the per-request timeout, or ctx+// cancellation. reqBody is marshaled into the request envelope; on a 2xx// response respBody (if non-nil) is unmarshaled from the response body. It// returns the response status (0 when the call never reached the server) so the-// caller can distinguish transport failure (→ HTTP fallback) from a server-side-// error.-func (c *wsRPCClient) Call(ctx context.Context, method string, serverTimeout time.Duration, reqBody, respBody any) (int, error) {+// caller can distinguish transport failure (→ HTTP fallback) from a+// server-side error.+func (c *wsRPCClient) call(ctx context.Context, method string, serverTimeout time.Duration, reqBody, respBody any, requireRPCV1 bool) (int, error) {if c == nil {return 0, errWSRPCUnavailable}@@ -155,7 +204,7 @@ func (c *wsRPCClient) Call(ctx context.Context, method string, serverTimeout timch := make(chan protocol.RPCResponsePayload, 1)c.mu.Lock()- if c.sendFrame == nil {+ if c.sendFrame == nil || (requireRPCV1 && !c.rpcV1Supported) {c.mu.Unlock()return 0, errWSRPCUnavailable}@@ -266,13 +315,13 @@ func (d *Daemon) ClaimTasksWSFirst(ctx context.Context, daemonID string, runtimeif d.batchClaimUnsupported.Load() {return d.client.claimTasksLegacy(ctx, runtimeIDs, maxTasks)}- if d.wsRPC.connected() {+ if d.wsRPC.supportsRPCV1() {var resp struct {Tasks []*Task `json:"tasks"`}// batchClaimRequestTimeout is the server-side execution budget; the// daemon waits that plus the client's grace margin for the response.- _, err := d.wsRPC.Call(ctx, "tasks.claim", batchClaimRequestTimeout, map[string]any{+ _, err := d.wsRPC.CallIfRPCV1Supported(ctx, "tasks.claim", batchClaimRequestTimeout, map[string]any{"daemon_id": daemonID,"runtime_ids": runtimeIDs,"max_tasks": maxTasks,diff --git a/server/internal/daemon/wsrpc_test.go b/server/internal/daemon/wsrpc_test.goindex 8edf6a365f..87f39280d1 100644--- a/server/internal/daemon/wsrpc_test.go+++ b/server/internal/daemon/wsrpc_test.go@@ -36,7 +36,6 @@ func TestWSRPCClient_CallRoundTrip(t *testing.T) {})return &wsOutbound{data: frame}, nil})-var resp struct {Tasks []struct {ID string `json:"id"`@@ -60,6 +59,40 @@ func TestWSRPCClient_Unavailable(t *testing.T) {}}+// TestWSRPCClient_ReattachRequiresFreshNegotiation pins capability state to a+// specific connection. A replacement sender must remain unavailable until a+// heartbeat ack from that connection explicitly advertises rpc-v1.+func TestWSRPCClient_ReattachRequiresFreshNegotiation(t *testing.T) {+ c := newWSRPCClient(time.Second)+ firstGeneration := c.attach(func(frame []byte) (*wsOutbound, error) {+ return &wsOutbound{data: frame}, nil+ })+ c.markRPCV1Supported(firstGeneration)+ if !c.supportsRPCV1() {+ t.Fatal("first connection should support rpc-v1 after negotiation")+ }++ newConnectionCalls := 0+ secondGeneration := c.attach(func(frame []byte) (*wsOutbound, error) {+ newConnectionCalls+++ return &wsOutbound{data: frame}, nil+ })+ c.markRPCV1Supported(firstGeneration) // delayed ack from the replaced connection+ if c.supportsRPCV1() {+ t.Fatal("replacement connection inherited rpc-v1 support from a stale ack")+ }+ if _, err := c.CallIfRPCV1Supported(context.Background(), "tasks.claim", 0, nil, nil); !errors.Is(err, errWSRPCUnavailable) {+ t.Fatalf("CallIfRPCV1Supported error = %v, want errWSRPCUnavailable before fresh negotiation", err)+ }+ if newConnectionCalls != 0 {+ t.Fatalf("replacement connection received %d RPC calls before negotiation, want 0", newConnectionCalls)+ }+ c.markRPCV1Supported(secondGeneration)+ if !c.supportsRPCV1() {+ t.Fatal("replacement connection did not accept its own rpc-v1 acknowledgement")+ }+}+// TestWSRPCClient_Timeout: no response arrives within the per-request timeout.func TestWSRPCClient_Timeout(t *testing.T) {c := newWSRPCClient(50 * time.Millisecond)diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex ed993aebc9..dea82f6ce1 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1101,8 +1101,9 @@ func (h *Handler) processHeartbeat(ctx context.Context, rt db.AgentRuntime, suppslog.Debug("daemon heartbeat", "runtime_id", runtimeID)ack := &protocol.DaemonHeartbeatAckPayload{- RuntimeID: runtimeID,- Status: "ok",+ RuntimeID: runtimeID,+ Status: "ok",+ ServerCapabilities: []string{protocol.DaemonCapabilityRPCV1},}probeUpdateCtx, cancelProbeUpdate := context.WithTimeout(ctx, heartbeatHasPendingTimeout)diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex e29b5c0735..8378ecc88f 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -249,6 +249,8 @@ type DaemonHeartbeatRequestPayload struct {// DaemonHeartbeatAckPayload is the server's reply to DaemonHeartbeatRequestPayload.// JSON shape mirrors the HTTP heartbeat response so daemon code can decode either.+// ServerCapabilities is explicit server-to-daemon protocol negotiation. A+// daemon must not infer support from its own advertised client capabilities.//// RuntimeGone is the WebSocket replacement for the HTTP 404 "runtime not found"// response. When the server discovers the runtime row was deleted (UI delete,@@ -260,6 +262,7 @@ type DaemonHeartbeatRequestPayload struct {type DaemonHeartbeatAckPayload struct {RuntimeID string `json:"runtime_id"`Status string `json:"status"`+ ServerCapabilities []string `json:"server_capabilities,omitempty"`RuntimeGone bool `json:"runtime_gone,omitempty"`PendingUpdate *DaemonHeartbeatPendingUpdate `json:"pending_update,omitempty"`PendingModelList *DaemonHeartbeatPendingModelList `json:"pending_model_list,omitempty"`