diff --git a/apps/radio/src/components/radio/index.tsx b/apps/radio/src/components/radio/index.tsx index 9fcf50fd2..1cb6c13c1 100644 --- a/apps/radio/src/components/radio/index.tsx +++ b/apps/radio/src/components/radio/index.tsx @@ -1,9 +1,9 @@ -import { captureError } from "@avoid.quest/error"; import { Suspense, useEffect } from "react"; import { LazyBoundary, lazyWithRetry } from "@/components/lazy-recovery"; import type { Radio } from "@/lib/audio"; import { useEnabledRadios } from "@/lib/hooks/use-radios"; import { usePlayerModeState } from "@/lib/hooks/use-settings"; +import { runModeLifecycleSynchronization } from "@/lib/mode-lifecycle-boot"; import type { PlayerMode } from "@/lib/normalize-player-mode"; import { useModeTransitionSnapshot } from "@/lib/use-mode-transition-snapshot"; import { RadioLoadingSkeleton } from "./radio-loading-skeleton"; @@ -46,24 +46,17 @@ export function Radios() { if (!hasSettings) { return; } - import("@/lib/mode-lifecycle-requests") - .then( - ({ modeLifecycleRequests }) => - // A legacy mode ("multiple", or one another tab wrote) runs as its - // replacement. Committing that could fail on the same stale record - // the settings step could not rewrite and roll the mode back. - modeLifecycleRequests.synchronizeMode(mode), - (error) => { - captureError(error, { - operation: "loadModeLifecycle", - surface: "ui", - }); - throw error; - } - ) - .catch((error) => { - console.error("[radio] Failed to synchronize playback mode:", error); - }); + // A legacy mode ("multiple", or one another tab wrote) runs as its + // replacement. Committing that could fail on the same stale record + // the settings step could not rewrite and roll the mode back. + runModeLifecycleSynchronization(mode, async () => { + const { modeLifecycleRequests } = await import( + "@/lib/mode-lifecycle-requests" + ); + return modeLifecycleRequests; + }).catch((error: unknown) => { + console.error("[radio] Failed to synchronize playback mode:", error); + }); }, [mode, hasSettings]); if (!(radiosQuery.isReady && isReady)) { diff --git a/apps/radio/src/lib/mode-lifecycle-boot.test.ts b/apps/radio/src/lib/mode-lifecycle-boot.test.ts new file mode 100644 index 000000000..17318b8e1 --- /dev/null +++ b/apps/radio/src/lib/mode-lifecycle-boot.test.ts @@ -0,0 +1,95 @@ +import { beforeEach, describe, expect, mock, spyOn, test } from "bun:test"; +// biome-ignore lint/performance/noNamespaceImport: spy on captureError without replacing the module graph +import * as errorSdk from "@avoid.quest/error"; +import { + type PlaybackSessionId, + playbackSessionsCollection, +} from "@/lib/collections/playback-sessions"; +import { runModeLifecycleSynchronization } from "./mode-lifecycle-boot"; +import { createModeLifecycleRequests } from "./mode-lifecycle-requests"; + +async function resetPlaybackSessions() { + await playbackSessionsCollection.stateWhenReady(); + for (const sessionId of Array.from(playbackSessionsCollection.state.keys())) { + playbackSessionsCollection.delete(sessionId); + } +} + +function insertPlaybackSession(id: PlaybackSessionId) { + playbackSessionsCollection.insert({ + activeChannelId: null, + channels: [], + crossfadePosition: 0.5, + headphoneVolume: 1, + id, + masterVolume: 1, + }); +} + +beforeEach(async () => { + await resetPlaybackSessions(); +}); + +describe("runModeLifecycleSynchronization", () => { + test("tags mode when the lifecycle module fails to load", async () => { + const capture = spyOn(errorSdk, "captureError").mockReturnValue(undefined); + const rejection = "synthetic-lifecycle-import-rejection"; + try { + await expect( + runModeLifecycleSynchronization("dj", () => Promise.reject(rejection)) + ).rejects.toBe(rejection); + expect(capture).toHaveBeenCalledTimes(1); + expect(capture).toHaveBeenCalledWith( + rejection, + expect.objectContaining({ + operation: "loadModeLifecycle", + surface: "ui", + tags: { mode: "dj" }, + }) + ); + } finally { + capture.mockRestore(); + } + }); + + test("lets synchronizeMode own reporting for a synthetic activation rejection", async () => { + insertPlaybackSession("node"); + const failure = new Error("Synthetic synchronizeMode activation failure"); + const capture = spyOn(errorSdk, "captureError").mockReturnValue(undefined); + const requests = createModeLifecycleRequests({ + getCurrentSettings: () => null, + manager: { + activateInitialMode: () => Promise.reject(failure), + getSnapshot: () => ({ + currentMode: null, + error: null, + phase: "inactive", + requestedMode: null, + }), + subscribe: () => () => undefined, + switchTo: mock(async () => undefined), + whenSettled: mock(async () => undefined), + }, + }); + + try { + await expect( + runModeLifecycleSynchronization("node", async () => requests) + ).rejects.toBe(failure); + expect(capture).toHaveBeenCalledTimes(1); + expect(capture).toHaveBeenCalledWith( + failure, + expect.objectContaining({ + operation: "synchronizeMode", + surface: "ui", + tags: { mode: "node" }, + }) + ); + expect(capture.mock.calls[0]?.[1]?.operation).not.toBe( + "loadModeLifecycle" + ); + } finally { + capture.mockRestore(); + } + }); +}); diff --git a/apps/radio/src/lib/mode-lifecycle-boot.ts b/apps/radio/src/lib/mode-lifecycle-boot.ts new file mode 100644 index 000000000..67c183825 --- /dev/null +++ b/apps/radio/src/lib/mode-lifecycle-boot.ts @@ -0,0 +1,26 @@ +import { captureError } from "@avoid.quest/error"; +import type { PlaybackSessionId } from "@/lib/collections/playback-sessions"; +import type { ModeLifecycleRequests } from "./mode-lifecycle-requests"; + +/** + * Loads mode-lifecycle requests (usually via dynamic import) then synchronizes. + * Import failures are reported as `loadModeLifecycle`; synchronizeMode owns its + * own failure reporting. + */ +export async function runModeLifecycleSynchronization( + mode: PlaybackSessionId, + loadRequests: () => Promise> +): Promise { + let synchronizeMode: ModeLifecycleRequests["synchronizeMode"]; + try { + ({ synchronizeMode } = await loadRequests()); + } catch (error) { + captureError(error, { + operation: "loadModeLifecycle", + surface: "ui", + tags: { mode }, + }); + throw error; + } + await synchronizeMode(mode); +} diff --git a/packages/error/src/index.test.ts b/packages/error/src/index.test.ts index 3ae3e7b5a..0556e49f9 100644 --- a/packages/error/src/index.test.ts +++ b/packages/error/src/index.test.ts @@ -155,6 +155,45 @@ describe("reporting policy", () => { ]); }); + // RADIO-26: non-Error rejections were wrapped as AppError and reported as the + // generic safe message only, so Sentry never showed the original cause. + test("reports a non-Error rejection as a reportable Error that keeps the cause", () => { + const rejection = "synthetic-mode-lifecycle-chunk-rejection"; + expect( + captureError(rejection, { + operation: "loadModeLifecycle", + surface: "ui", + tags: { mode: "node" }, + }) + ).toBe(EVENT_ID); + expect(captureException).toHaveBeenCalledTimes(1); + const [reported, hint] = captureException.mock.calls[0] ?? []; + expect(reported).toBeInstanceOf(Error); + expect(reported).not.toBeInstanceOf(AppError); + expect((reported as Error).message).toBe(rejection); + expect((reported as Error).cause).toBe(rejection); + expect(hint).toEqual({ data: { appError: expect.any(AppError) } }); + expect(capturedScope?.tags).toMatchObject({ + error_code: "UNEXPECTED_ERROR", + mode: "node", + operation: "loadModeLifecycle", + }); + expect(PRIVATE_DATA.test((reported as Error).message)).toBe(false); + }); + + test("does not put object rejection bodies into the reportable Error message", () => { + const rejection = { + message: "session=private-token", + url: "https://example.test/stream?secret=1", + }; + captureError(rejection, { operation: "loadModeLifecycle", surface: "ui" }); + const [reported] = captureException.mock.calls[0] ?? []; + expect(reported).toBeInstanceOf(Error); + expect((reported as Error).message).toBe("Object"); + expect((reported as Error).cause).toBe(rejection); + expect(PRIVATE_DATA.test((reported as Error).message)).toBe(false); + }); + test.each(["validation", "auth", "rate_limit", "dependency"] as const)( "does not emit expected %s errors", (category) => { diff --git a/packages/error/src/index.ts b/packages/error/src/index.ts index cdbde06c4..037390cd7 100644 --- a/packages/error/src/index.ts +++ b/packages/error/src/index.ts @@ -306,6 +306,62 @@ function asStringTagValue(value: string | number | boolean): string { return String(value); } +const MAX_UNKNOWN_REJECTION_MESSAGE = 200; + +/** Sentry-facing summary only. Never JSON-serialize arbitrary objects. */ +function describeUnknownRejection(value: unknown): string { + if (typeof value === "string") { + const trimmed = value.trim(); + if (!trimmed) { + return "Empty string rejection"; + } + return trimmed.length > MAX_UNKNOWN_REJECTION_MESSAGE + ? `${trimmed.slice(0, MAX_UNKNOWN_REJECTION_MESSAGE)}…` + : trimmed; + } + if ( + typeof value === "number" || + typeof value === "boolean" || + typeof value === "bigint" + ) { + return String(value); + } + if (typeof value === "symbol") { + return value.description ? `Symbol(${value.description})` : "Symbol()"; + } + if (typeof value === "function") { + return `Function(${value.name || "anonymous"})`; + } + if (value === null) { + return "null"; + } + if (typeof value === "object") { + const name = value.constructor?.name; + return name && name !== "Object" ? `Object(${name})` : "Object"; + } + return "unknown"; +} + +function toReportableException(appError: AppError): { + exception: Error; + withAppErrorHint: boolean; +} { + if (appError.cause instanceof Error) { + return { exception: appError.cause, withAppErrorHint: true }; + } + if (appError.cause !== undefined && appError.cause !== null) { + // Non-Error rejections used to report only the generic AppError safe + // message (RADIO-26). Promote a typed Error so the event value is useful + // while keeping the original value on `cause` for local debugging. + const promoted = new Error(describeUnknownRejection(appError.cause), { + cause: appError.cause, + }); + promoted.name = "NonErrorRejection"; + return { exception: promoted, withAppErrorHint: true }; + } + return { exception: appError, withAppErrorHint: false }; +} + function resolveCaptureError(error: unknown): AppError { return toAppError(error, { category: "unknown", @@ -383,10 +439,12 @@ export function captureError( // Keep native same-cause dedupe and LinkedErrors' original exception. // The hint carries the authoritative wrapper policy only to beforeSend. - eventId = - appError.cause instanceof Error - ? Sentry.captureException(appError.cause, { data: { appError } }) - : Sentry.captureException(appError); + const reportable = toReportableException(appError); + eventId = reportable.withAppErrorHint + ? Sentry.captureException(reportable.exception, { + data: { appError }, + }) + : Sentry.captureException(reportable.exception); }); return eventId;