Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
Revert "fix: gzip daemon claim responses (#4259)" (#4307)
LinYushene1c6754304ac
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 779e9679fa..3ba8cb455a 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -101,20 +101,6 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analyticsreturn r}-func daemonJSONCompressor() func(http.Handler) http.Handler {- compress := chimw.Compress(5, "application/json")- return func(next http.Handler) http.Handler {- compressed := compress(next)- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {- next.ServeHTTP(w, r)- return- }- compressed.ServeHTTP(w, r)- })- }-}-type RouterOptions struct {HTTPMetrics *obsmetrics.HTTPMetricsBusinessMetrics *obsmetrics.BusinessMetrics@@ -508,7 +494,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Daemon API routes (require daemon token or valid user token)r.Route("/api/daemon", func(r chi.Router) {r.Use(middleware.DaemonAuth(queries, patCache, daemonTokenCache, cloudPATVerifier))- r.Use(daemonJSONCompressor())r.Post("/register", h.DaemonRegister)r.Post("/deregister", h.DaemonDeregister)diff --git a/server/cmd/server/router_compression_test.go b/server/cmd/server/router_compression_test.godeleted file mode 100644index e8116fcb59..0000000000--- a/server/cmd/server/router_compression_test.go+++ /dev/null@@ -1,92 +0,0 @@-package main--import (- "compress/gzip"- "io"- "net/http"- "net/http/httptest"- "strings"- "testing"-- "github.com/go-chi/chi/v5"-)--func TestDaemonJSONCompressorGzipsJSONWhenAccepted(t *testing.T) {- router := chi.NewRouter()- router.Use(daemonJSONCompressor())- router.Get("/api/daemon/test", func(w http.ResponseWriter, r *http.Request) {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusOK)- w.Write([]byte(`{"payload":"` + strings.Repeat("x", 256) + `"}`))- })-- rec := httptest.NewRecorder()- req := httptest.NewRequest(http.MethodGet, "/api/daemon/test", nil)- req.Header.Set("Accept-Encoding", "gzip")- router.ServeHTTP(rec, req)-- if got := rec.Header().Get("Content-Encoding"); got != "gzip" {- t.Fatalf("Content-Encoding = %q, want gzip", got)- }- if got := rec.Header().Get("Vary"); got != "Accept-Encoding" {- t.Fatalf("Vary = %q, want Accept-Encoding", got)- }-- zr, err := gzip.NewReader(rec.Body)- if err != nil {- t.Fatalf("open gzip body: %v", err)- }- defer zr.Close()- body, err := io.ReadAll(zr)- if err != nil {- t.Fatalf("read gzip body: %v", err)- }- if !strings.Contains(string(body), `"payload":"xxx`) {- t.Fatalf("decoded body missing payload: %s", string(body))- }-}--func TestDaemonJSONCompressorLeavesPlainJSONWhenGzipNotAccepted(t *testing.T) {- router := chi.NewRouter()- router.Use(daemonJSONCompressor())- router.Get("/api/daemon/test", func(w http.ResponseWriter, r *http.Request) {- w.Header().Set("Content-Type", "application/json")- w.Write([]byte(`{"task":null}`))- })-- rec := httptest.NewRecorder()- req := httptest.NewRequest(http.MethodGet, "/api/daemon/test", nil)- router.ServeHTTP(rec, req)-- if got := rec.Header().Get("Content-Encoding"); got != "" {- t.Fatalf("Content-Encoding = %q, want empty", got)- }- if got := rec.Body.String(); got != `{"task":null}` {- t.Fatalf("body = %q, want plain JSON", got)- }-}--func TestDaemonJSONCompressorSkipsWebsocketUpgrade(t *testing.T) {- router := chi.NewRouter()- router.Use(daemonJSONCompressor())- router.Get("/api/daemon/ws", func(w http.ResponseWriter, r *http.Request) {- if got := r.Header.Get("Upgrade"); got != "websocket" {- t.Fatalf("Upgrade header = %q, want websocket", got)- }- w.WriteHeader(http.StatusSwitchingProtocols)- })-- rec := httptest.NewRecorder()- req := httptest.NewRequest(http.MethodGet, "/api/daemon/ws", nil)- req.Header.Set("Accept-Encoding", "gzip")- req.Header.Set("Connection", "Upgrade")- req.Header.Set("Upgrade", "websocket")- router.ServeHTTP(rec, req)-- if got := rec.Header().Get("Content-Encoding"); got != "" {- t.Fatalf("Content-Encoding = %q, want empty for websocket upgrade", got)- }- if rec.Code != http.StatusSwitchingProtocols {- t.Fatalf("status = %d, want %d", rec.Code, http.StatusSwitchingProtocols)- }-}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 78775541b2..e593868339 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1135,7 +1135,7 @@ func logHeartbeatEndpointSlow(runtimeID, outcome, authPath string, start time.Ti// logClaimEndpointSlow emits one structured log when the /tasks/claim endpoint// exceeds 500ms, splitting auth / claim / response-build phases so the prod// tail can be diagnosed without flooding logs at normal poll rates.-func logClaimEndpointSlow(runtimeID, outcome string, start time.Time, authMs, claimMs, buildMs int64, payloadBytes, agentSkillCount, builtinSkillCount, skillPayloadBytes int) {+func logClaimEndpointSlow(runtimeID, outcome string, start time.Time, authMs, claimMs, buildMs int64) {totalMs := time.Since(start).Milliseconds()if totalMs < 500 {return@@ -1147,10 +1147,6 @@ func logClaimEndpointSlow(runtimeID, outcome string, start time.Time, authMs, cl"auth_ms", authMs,"claim_ms", claimMs,"build_ms", buildMs,- "payload_bytes", payloadBytes,- "agent_skill_count", agentSkillCount,- "builtin_skill_count", builtinSkillCount,- "skill_payload_bytes", skillPayloadBytes,)}@@ -1163,10 +1159,6 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {var (outcome = "unauth"authMs, claimMs, buildMs int64- payloadBytes int- agentSkillCount int- builtinSkillCount int- skillPayloadBytes intbuildStart time.Time)defer func() {@@ -1176,7 +1168,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {if !buildStart.IsZero() {buildMs = time.Since(buildStart).Milliseconds()}- logClaimEndpointSlow(runtimeID, outcome, start, authMs, claimMs, buildMs, payloadBytes, agentSkillCount, builtinSkillCount, skillPayloadBytes)+ logClaimEndpointSlow(runtimeID, outcome, start, authMs, claimMs, buildMs)}()// Verify the caller owns this runtime's workspace. The runtime's@@ -1202,7 +1194,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {if task == nil {slog.Debug("no task to claim", "runtime_id", runtimeID)- payloadBytes, _ = writeMeasuredJSON(w, http.StatusOK, map[string]any{"task": nil})+ writeJSON(w, http.StatusOK, map[string]any{"task": nil})outcome = "no_task"return}@@ -1217,10 +1209,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {// names carry a "multica-" prefix so their on-disk slugs never collide// with a user-authored workspace skill (see writeSkillFiles).skills := h.TaskService.LoadAgentSkills(r.Context(), task.AgentID)- agentSkillCount = len(skills)- builtinSkills := h.TaskService.BuiltinSkills()- builtinSkillCount = len(builtinSkills)- skills = append(skills, builtinSkills...)+ skills = append(skills, h.TaskService.BuiltinSkills()...)var customEnv map[string]stringif agent.CustomEnv != nil {if err := json.Unmarshal(agent.CustomEnv, &customEnv); err != nil {@@ -1811,12 +1800,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {resp.AuthToken = tokenStrslog.Info("task claimed by runtime", "task_id", uuidToString(task.ID), "runtime_id", runtimeID, "agent_id", uuidToString(task.AgentID), "prior_session", resp.PriorSessionID)- if resp.Agent != nil && len(resp.Agent.Skills) > 0 {- if skillPayload, err := json.Marshal(resp.Agent.Skills); err == nil {- skillPayloadBytes = len(skillPayload)- }- }- payloadBytes, _ = writeMeasuredJSON(w, http.StatusOK, map[string]any{"task": resp})+ writeJSON(w, http.StatusOK, map[string]any{"task": resp})}// trailingUserMessages returns the run of user messages after the lastdiff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex d41c746b12..cffbc82a9a 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -6,7 +6,6 @@ import ("encoding/json""errors""fmt"- "log/slog""net/http""net/http/httptest""strings"@@ -23,29 +22,6 @@ import ("github.com/multica-ai/multica/server/pkg/protocol")-func TestLogClaimEndpointSlowIncludesPayloadFields(t *testing.T) {- var logs bytes.Buffer- prev := slog.Default()- slog.SetDefault(slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelInfo})))- t.Cleanup(func() { slog.SetDefault(prev) })-- logClaimEndpointSlow("runtime-1", "claimed", time.Now().Add(-600*time.Millisecond), 10, 20, 30, 4096, 2, 8, 3072)-- got := logs.String()- for _, want := range []string{- "msg=\"claim_endpoint slow\"",- "runtime_id=runtime-1",- "payload_bytes=4096",- "agent_skill_count=2",- "builtin_skill_count=8",- "skill_payload_bytes=3072",- } {- if !strings.Contains(got, want) {- t.Fatalf("slow claim log missing %q in %s", want, got)- }- }-}-// slowProbeLocalSkillListStore wraps a LocalSkillListStore but blocks inside// HasPending until the provided context is cancelled. PopPending delegates// to the underlying store. Used to verify that a stalled probe cannot wedgediff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 40f8092383..dd66ad51ba 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -230,21 +230,6 @@ func writeJSON(w http.ResponseWriter, status int, v any) {json.NewEncoder(w).Encode(v)}-func writeMeasuredJSON(w http.ResponseWriter, status int, v any) (int, error) {- body, err := json.Marshal(v)- if err != nil {- writeError(w, http.StatusInternalServerError, "failed to encode response")- return 0, err- }- body = append(body, '\n')- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(status)- if _, err := w.Write(body); err != nil {- return len(body), err- }- return len(body), nil-}-func writeError(w http.ResponseWriter, status int, msg string) {writeJSON(w, status, map[string]string{"error": msg})}