Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 12 additions & 19 deletions apps/radio/src/components/radio/index.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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)) {
Expand Down
95 changes: 95 additions & 0 deletions apps/radio/src/lib/mode-lifecycle-boot.test.ts
Original file line number Diff line number Diff line change
@@ -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();
}
});
});
26 changes: 26 additions & 0 deletions apps/radio/src/lib/mode-lifecycle-boot.ts
Original file line number Diff line number Diff line change
@@ -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<Pick<ModeLifecycleRequests, "synchronizeMode">>
): Promise<void> {
let synchronizeMode: ModeLifecycleRequests["synchronizeMode"];
try {
({ synchronizeMode } = await loadRequests());
} catch (error) {
captureError(error, {
operation: "loadModeLifecycle",
surface: "ui",
tags: { mode },
});
throw error;
}
await synchronizeMode(mode);
}
39 changes: 39 additions & 0 deletions packages/error/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
66 changes: 62 additions & 4 deletions packages/error/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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;
Expand Down
Loading