fix: remove duplicate WebSocket event subscriptions (#667)

* fix: remove duplicate WebSocket event subscriptions for messages and session state

* fix: remove unused broadcastRecorder.all method

* fix: address review comments — replace tautological test with subscription count guard

* fix: update test comments per review feedback

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
This commit is contained in:
João Salavisa
2026-04-21 01:04:43 +01:00
committed by GitHub
parent 2d1a868107
commit 5bb10190c2
3 changed files with 147 additions and 139 deletions
-111
View File
@@ -309,117 +309,6 @@ func appendSessionModelsMessage(sessionID string, session *models.TaskSession, l
return result
}
// newMessageAddedHandler returns an event bus handler that broadcasts message.added events
// to WebSocket subscribers.
func newMessageAddedHandler(gateway *gateways.Gateway, log *logger.Logger) func(context.Context, *bus.Event) error {
return func(ctx context.Context, event *bus.Event) error {
data, ok := event.Data.(map[string]interface{})
if !ok {
return nil
}
taskSessionID, _ := data["session_id"].(string)
taskID, _ := data["task_id"].(string)
if taskSessionID == "" {
return nil
}
payload := map[string]interface{}{
"task_id": taskID,
"session_id": taskSessionID,
"message_id": data["message_id"],
"author_type": data["author_type"],
"author_id": data["author_id"],
"content": data["content"],
"type": data["type"],
"requests_input": data["requests_input"],
"created_at": data["created_at"],
}
if metadata, ok := data["metadata"]; ok && metadata != nil {
payload["metadata"] = metadata
}
notification, err := ws.NewNotification(ws.ActionSessionMessageAdded, payload)
if err != nil {
log.Error("Failed to create message.added notification", zap.Error(err))
return nil
}
gateway.Hub.BroadcastToSession(taskSessionID, notification)
return nil
}
}
// newMessageUpdatedHandler returns an event bus handler that broadcasts message.updated events
// to WebSocket subscribers.
func newMessageUpdatedHandler(gateway *gateways.Gateway, log *logger.Logger) func(context.Context, *bus.Event) error {
return func(ctx context.Context, event *bus.Event) error {
data, ok := event.Data.(map[string]interface{})
if !ok {
return nil
}
taskSessionID, _ := data["session_id"].(string)
taskID, _ := data["task_id"].(string)
if taskSessionID == "" {
log.Warn("message.updated event has no session_id, skipping")
return nil
}
payload := map[string]interface{}{
"message_id": data["message_id"],
"session_id": taskSessionID,
"task_id": taskID,
"author_type": data["author_type"],
"author_id": data["author_id"],
"content": data["content"],
"type": data["type"],
"requests_input": data["requests_input"],
"created_at": data["created_at"],
}
if metadata, ok := data["metadata"]; ok && metadata != nil {
payload["metadata"] = metadata
}
notification, err := ws.NewNotification(ws.ActionSessionMessageUpdated, payload)
if err != nil {
log.Error("Failed to create message.updated notification", zap.Error(err))
return nil
}
gateway.Hub.BroadcastToSession(taskSessionID, notification)
return nil
}
}
// newSessionStateChangedHandler returns an event bus handler that broadcasts
// task_session.state_changed events to WebSocket subscribers.
func newSessionStateChangedHandler(gateway *gateways.Gateway, log *logger.Logger) func(context.Context, *bus.Event) error {
return func(ctx context.Context, event *bus.Event) error {
data, ok := event.Data.(map[string]interface{})
if !ok {
return nil
}
taskSessionID, _ := data["session_id"].(string)
if taskSessionID == "" {
return nil
}
notification, err := ws.NewNotification(ws.ActionSessionStateChanged, data)
if err != nil {
log.Error("Failed to create task_session.state_changed notification", zap.Error(err))
return nil
}
gateway.Hub.BroadcastToSession(taskSessionID, notification)
return nil
}
}
// newGitHubTaskPRUpdatedHandler returns an event bus handler that broadcasts
// github.task_pr.updated events to all WebSocket clients.
func newGitHubTaskPRUpdatedHandler(gateway *gateways.Gateway, log *logger.Logger) func(context.Context, *bus.Event) error {
return func(_ context.Context, event *bus.Event) error {
notification, err := ws.NewNotification(ws.ActionGitHubTaskPRUpdated, event.Data)
if err != nil {
log.Error("Failed to create github.task_pr.updated notification", zap.Error(err))
return nil
}
gateway.Hub.Broadcast(notification)
return nil
}
}
// routeParams holds all dependencies needed for HTTP and WebSocket route registration.
type routeParams struct {
router *gin.Engine
-28
View File
@@ -408,8 +408,6 @@ func startGatewayAndServe(
services.Task.StartAutoArchiveLoop(ctx)
subscribeEventBusHandlers(eventBus, gateway, log)
// ============================================
// HTTP SERVER
// ============================================
@@ -499,32 +497,6 @@ func buildHTTPServer(
}
}
// subscribeEventBusHandlers subscribes WebSocket broadcast handlers to the event bus.
func subscribeEventBusHandlers(eventBus bus.EventBus, gateway *gateways.Gateway, log *logger.Logger) {
if _, err := eventBus.Subscribe(events.MessageAdded, newMessageAddedHandler(gateway, log)); err != nil {
log.Error("Failed to subscribe to message.added events", zap.Error(err))
} else {
log.Debug("Subscribed to message.added events for WebSocket broadcasting")
}
if _, err := eventBus.Subscribe(events.MessageUpdated, newMessageUpdatedHandler(gateway, log)); err != nil {
log.Error("Failed to subscribe to message.updated events", zap.Error(err))
} else {
log.Debug("Subscribed to message.updated events for WebSocket broadcasting")
}
if _, err := eventBus.Subscribe(events.TaskSessionStateChanged, newSessionStateChangedHandler(gateway, log)); err != nil {
log.Error("Failed to subscribe to task_session.state_changed events", zap.Error(err))
} else {
log.Debug("Subscribed to task_session.state_changed events for WebSocket broadcasting")
}
// GitHub task-PR update broadcasts
if _, err := eventBus.Subscribe(events.GitHubTaskPRUpdated, newGitHubTaskPRUpdatedHandler(gateway, log)); err != nil {
log.Error("Failed to subscribe to github.task_pr.updated events", zap.Error(err))
} else {
log.Debug("Subscribed to github.task_pr.updated events for WebSocket broadcasting")
}
}
// awaitShutdown waits for an OS signal then performs graceful shutdown.
func awaitShutdown(
server *http.Server,
@@ -0,0 +1,147 @@
package websocket
import (
"context"
"encoding/json"
"testing"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/internal/events"
"github.com/kandev/kandev/internal/events/bus"
)
func testLogger() *logger.Logger {
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
return log
}
// TestTaskEventBroadcaster_NoDuplicateSubscriptions verifies that
// RegisterTaskNotifications creates exactly one subscription per event type.
//
// The old code had a second subscription system (subscribeEventBusHandlers in
// cmd/kandev/helpers.go) that subscribed to the same four events, causing
// duplicate broadcasts. This test counts the broadcaster's internal
// subscriptions directly to guard against re-introducing duplicates.
func TestTaskEventBroadcaster_NoDuplicateSubscriptions(t *testing.T) {
log := testLogger()
eventBus := bus.NewMemoryEventBus(log)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := NewHub(nil, log)
go hub.Run(ctx)
b := RegisterTaskNotifications(ctx, eventBus, hub, log)
// Count how many b.subscribe() calls are in RegisterTaskNotifications.
// Each call creates exactly one subscription. If any event is subscribed
// twice, this count will increase and the test will fail.
//
// Update this number when adding or removing event subscriptions in
// RegisterTaskNotifications — it is intentionally exact.
const wantSubscriptions = 46
if got := len(b.subscriptions); got != wantSubscriptions {
t.Errorf("RegisterTaskNotifications created %d subscriptions, want %d — "+
"did an event get subscribed twice?", got, wantSubscriptions)
}
// Verify no event subject appears more than once by publishing each of
// the 4 previously-duplicated events and counting hub broadcasts.
// We use a fresh event bus per sub-test so each has exactly
// 1 broadcaster subscription + 1 counter subscription.
for _, subject := range []string{
events.MessageAdded,
events.MessageUpdated,
events.TaskSessionStateChanged,
events.GitHubTaskPRUpdated,
} {
subject := subject
t.Run(subject, func(t *testing.T) {
perEventBus := bus.NewMemoryEventBus(log)
perHub := NewHub(nil, log)
go perHub.Run(ctx)
_ = RegisterTaskNotifications(ctx, perEventBus, perHub, log)
var count int
_, _ = perEventBus.Subscribe(subject, func(_ context.Context, _ *bus.Event) error {
count++
return nil
})
data := map[string]interface{}{
"session_id": "s1", "task_id": "t1",
}
evt := bus.NewEvent(subject, "test", data)
_ = perEventBus.Publish(context.Background(), subject, evt)
// This verifies that publishing one event reaches our handler exactly
// once. Duplicate-subscription detection is handled by the
// len(b.subscriptions) guard above; these sub-tests cover event
// delivery correctness for the four previously-duplicated subjects.
if count != 1 {
t.Errorf("counter handler fired %d times, want 1", count)
}
})
}
}
// TestTaskEventBroadcaster_PreservesAllFields verifies that event data passes through the
// event bus unmodified — the broadcaster receives the same object that was published,
// including fields like turn_id, raw_content, and updated_at that the old
// subscribeEventBusHandlers used to strip before constructing a new payload manually.
func TestTaskEventBroadcaster_PreservesAllFields(t *testing.T) {
log := testLogger()
eventBus := bus.NewMemoryEventBus(log)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
hub := NewHub(nil, log)
go hub.Run(ctx)
// Subscribe a handler before the broadcaster to capture what data
// the event bus delivers — the broadcaster receives the same object.
var captured interface{}
_, _ = eventBus.Subscribe(events.MessageAdded, func(_ context.Context, ev *bus.Event) error {
captured = ev.Data
return nil
})
_ = RegisterTaskNotifications(ctx, eventBus, hub, log)
original := map[string]interface{}{
"session_id": "s1",
"task_id": "t1",
"message_id": "m1",
"content": "hello world",
"raw_content": "raw hello world",
"turn_id": "turn-abc",
"author_type": "agent",
"author_id": "claude",
"type": "text",
"created_at": "2026-04-20T00:00:00Z",
"updated_at": "2026-04-20T00:01:00Z",
"metadata": map[string]interface{}{"key": "value"},
}
evt := bus.NewEvent(events.MessageAdded, "test", original)
_ = eventBus.Publish(context.Background(), events.MessageAdded, evt)
capturedMap, ok := captured.(map[string]interface{})
if !ok {
t.Fatalf("captured data is not map[string]interface{}, got %T", captured)
}
// Verify fields that the old handler used to strip are still present.
for _, field := range []string{"turn_id", "raw_content", "updated_at"} {
if _, exists := capturedMap[field]; !exists {
t.Errorf("field %q was stripped from event data", field)
}
}
origJSON, _ := json.Marshal(original)
capturedJSON, _ := json.Marshal(capturedMap)
if string(origJSON) != string(capturedJSON) {
t.Errorf("event data was modified\noriginal: %s\ncaptured: %s", origJSON, capturedJSON)
}
}