Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(realtime): guard WS frames without a string type + drop benign ResizeObserver noise (MUL-3418) (#4304)
Naiyuan Qing9eaea31892f5
diff --git a/packages/core/analytics/benign-exceptions.test.ts b/packages/core/analytics/benign-exceptions.test.tsnew file mode 100644index 0000000000..75a4ce2a98--- /dev/null+++ b/packages/core/analytics/benign-exceptions.test.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from "vitest";+import { isBenignException } from "./benign-exceptions";++describe("isBenignException", () => {+ it("drops ResizeObserver loop errors via $exception_list value", () => {+ expect(+ isBenignException({+ $exception_list: [+ {+ type: "Error",+ value: "ResizeObserver loop completed with undelivered notifications.",+ },+ ],+ }),+ ).toBe(true);+ });++ it("drops the older 'loop limit exceeded' phrasing", () => {+ expect(+ isBenignException({+ $exception_list: [+ { type: "Error", value: "ResizeObserver loop limit exceeded" },+ ],+ }),+ ).toBe(true);+ });++ it("drops when the signal is on the top-level $exception_message", () => {+ expect(+ isBenignException({+ $exception_message: "ResizeObserver loop limit exceeded",+ }),+ ).toBe(true);+ });++ it("matches case-insensitively", () => {+ expect(+ isBenignException({ $exception_message: "resizeobserver LOOP limit exceeded" }),+ ).toBe(true);+ });++ it("keeps real errors", () => {+ expect(+ isBenignException({+ $exception_list: [+ {+ type: "TypeError",+ value: "Cannot read properties of undefined (reading 'split')",+ },+ ],+ }),+ ).toBe(false);+ });++ it("does not match an unrelated mention of ResizeObserver", () => {+ // Only the benign "loop" phrasing is silenced; a genuine bug in+ // ResizeObserver usage must still be reported.+ expect(+ isBenignException({+ $exception_message: "ResizeObserver is not defined",+ }),+ ).toBe(false);+ });++ it("fails open on missing or malformed properties", () => {+ expect(isBenignException(undefined)).toBe(false);+ expect(isBenignException({})).toBe(false);+ expect(isBenignException({ $exception_list: "not-an-array" })).toBe(false);+ expect(isBenignException({ $exception_list: [null, 42, {}] })).toBe(false);+ expect(isBenignException({ $exception_message: 123 })).toBe(false);+ });+});diff --git a/packages/core/analytics/benign-exceptions.ts b/packages/core/analytics/benign-exceptions.tsnew file mode 100644index 0000000000..247b4b0542--- /dev/null+++ b/packages/core/analytics/benign-exceptions.ts@@ -0,0 +1,52 @@+// Known-benign browser exceptions that are pure noise in `$exception`+// telemetry. These are dropped ENTIRELY in `before_send` (not merely deduped by+// exception-dedupe.ts) — they carry no actionable signal, the browser+// self-recovers, and at scale they dominate the error stream, drowning real+// failures and burning the billed event budget.+//+// ResizeObserver "loop ..." errors are the canonical case: the spec fires them+// when observation callbacks don't settle within a single animation frame. The+// browser resumes delivery on the next frame, so nothing actually breaks. Every+// app that uses ResizeObserver (directly or via a UI library) emits them. The+// CSSWG explicitly considers them benign — see w3c/csswg-drafts#5023. Across+// Chrome versions the message is either "ResizeObserver loop limit exceeded"+// (older) or "ResizeObserver loop completed with undelivered notifications"+// (newer); both contain "ResizeObserver loop".+//+// The bar for adding a pattern here is high: it must be a benign,+// self-recovering error with no actionable signal. A real bug must never be+// silenced — when unsure, leave it to the dedupe fuse, which only caps repeats.++const BENIGN_MESSAGE_PATTERNS: RegExp[] = [/ResizeObserver loop/i];++/**+ * Whether this `$exception` event is known-benign browser noise that should be+ * dropped entirely. Reads the message from the (pre-redaction) event+ * properties — the matched messages carry no PII, so reading them raw is safe,+ * and matching before redaction avoids any chance of a scrub mangling the+ * signal. Never throws: any unexpected shape returns `false` (keep the event),+ * the fail-open direction `before_send` requires.+ */+export function isBenignException(+ properties: Record<string, unknown> | undefined,+): boolean {+ if (!properties || typeof properties !== "object") return false;++ const messages: unknown[] = [properties.$exception_message];+ const list = properties.$exception_list;+ if (Array.isArray(list)) {+ for (const entry of list) {+ if (entry && typeof entry === "object" && "value" in entry) {+ messages.push((entry as { value: unknown }).value);+ }+ }+ }++ for (const message of messages) {+ if (typeof message !== "string") continue;+ for (const pattern of BENIGN_MESSAGE_PATTERNS) {+ if (pattern.test(message)) return true;+ }+ }+ return false;+}diff --git a/packages/core/analytics/index.ts b/packages/core/analytics/index.tsindex 1d1cc6c2e7..b6901fe736 100644--- a/packages/core/analytics/index.ts+++ b/packages/core/analytics/index.ts@@ -15,6 +15,7 @@import posthog from "posthog-js";import { redactExceptionProperties } from "./redact-exception";import { shouldDropException } from "./exception-dedupe";+import { isBenignException } from "./benign-exceptions";export const EVENT_SCHEMA_VERSION = 2;@@ -166,6 +167,11 @@ export function initAnalytics(config: AnalyticsConfig | null | undefined): boolecapture_exceptions: true,before_send: (event) => {if (event && event.event === "$exception") {+ // Drop known-benign browser noise (e.g. ResizeObserver loop) entirely+ // — checked on the raw message before redaction. These dominate the+ // stream and carry no signal, so they skip both redaction and the+ // dedupe fuse. See benign-exceptions.ts.+ if (isBenignException(event.properties)) return null;redactExceptionProperties(event.properties);if (shouldDropException(event.properties)) return null;}diff --git a/packages/core/api/ws-client.test.ts b/packages/core/api/ws-client.test.tsindex 80f5d39e8a..2817cb47ba 100644--- a/packages/core/api/ws-client.test.ts+++ b/packages/core/api/ws-client.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { WSClient } from "./ws-client";+import type { WSMessage } from "../types/events";// Capture URL passed to WebSocket so we can assert the connect-time// query string. We don't simulate the full WS lifecycle here — only the@@ -128,6 +129,57 @@ describe("WSClient", () => {);});+ it("drops frames without a string type without throwing, and keeps dispatching", () => {+ // Regression for MUL-3418: a frame whose parsed JSON lacks a string `type`+ // (an out-of-protocol frame, or a bare JSON primitive) used to throw an+ // uncaught TypeError out of onmessage via `msg.type.split(...)` in a+ // downstream onAny handler, flooding `$exception` telemetry.+ const logger = {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ };+ const ws = new WSClient("ws://example.test/ws", { logger });++ // A downstream consumer that assumes a string type, exactly like the+ // realtime sync's onAny dispatcher.+ const anyHandler = vi.fn((msg: WSMessage) => msg.type.split(":")[0]);+ ws.onAny(anyHandler);+ const issueHandler = vi.fn();+ ws.on("issue:updated", issueHandler);+ ws.connect();++ const badFrames = [+ JSON.stringify({ payload: {} }), // object, no type+ "42", // bare number+ "true", // bare bool+ "[]", // array+ ];+ for (const data of badFrames) {+ expect(() => {+ FakeWebSocket.lastInstance!.onmessage?.({ data });+ }).not.toThrow();+ }++ // Bad frames never reached any handler.+ expect(anyHandler).not.toHaveBeenCalled();+ expect(issueHandler).not.toHaveBeenCalled();++ // A valid frame after the bad ones still dispatches normally.+ FakeWebSocket.lastInstance!.onmessage?.({+ data: JSON.stringify({ type: "issue:updated", payload: { id: "i-1" } }),+ });+ expect(issueHandler).toHaveBeenCalledWith({ id: "i-1" }, undefined, undefined);+ expect(anyHandler).toHaveBeenCalledTimes(1);++ // The drop is logged at most once per connection despite four bad frames.+ expect(logger.warn).toHaveBeenCalledTimes(1);+ expect(logger.warn.mock.calls[0]?.[0]).toBe(+ "ws: dropping frame without a string type",+ );+ });+it("passes actor_id and actor_type to event handlers", () => {const ws = new WSClient("ws://example.test/ws");ws.setAuth("tok", "acme");diff --git a/packages/core/api/ws-client.ts b/packages/core/api/ws-client.tsindex cc3d08e035..447df46b12 100644--- a/packages/core/api/ws-client.ts+++ b/packages/core/api/ws-client.ts@@ -34,6 +34,10 @@ export class WSClient {private handlers = new Map<WSEventType, Set<EventHandler>>();private reconnectTimer: ReturnType<typeof setTimeout> | null = null;private hasConnectedBefore = false;+ // One-shot per connection. A non-conforming frame can repeat hundreds of+ // times per session, so we log the first drop and suppress the rest. Reset+ // on each connect() so a fresh connection logs once again.+ private badFrameLogged = false;private onReconnectCallbacks = new Set<() => void>();private anyHandlers = new Set<(msg: WSMessage) => void>();private logger: Logger;@@ -58,6 +62,7 @@ export class WSClient {}connect() {+ this.badFrameLogged = false;const url = new URL(this.baseUrl);// Token is never sent as a URL query parameter — it would be logged by// proxies, CDNs, and browser history. In cookie mode the HttpOnly cookie@@ -96,6 +101,25 @@ export class WSClient {);return;}+ // Trust boundary: a frame must be an object carrying a string `type`.+ // The server protocol guarantees this for every frame, but a+ // non-conforming frame — an out-of-protocol frame injected by a proxy /+ // browser extension, or a bare JSON primitive — must degrade to a no-op+ // here. Without this guard every downstream consumer (the onAny+ // dispatcher and every ws.on subscriber) runs against a bad shape;+ // `msg.type.split(...)` in the realtime sync threw an uncaught TypeError+ // out of onmessage and surfaced as a flood of global `$exception` events+ // (MUL-3418). Validate once at the boundary, trust the shape downstream.+ if (!msg || typeof (msg as { type?: unknown }).type !== "string") {+ if (!this.badFrameLogged) {+ this.badFrameLogged = true;+ this.logger.warn(+ "ws: dropping frame without a string type",+ summarizeUnparseable(event.data),+ );+ }+ return;+ }if ((msg as any).type === "auth_ack") {this.onAuthenticated();return;