Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): send referrer for brainrot youtube embeds to fix error 153 (#87694)

Joe Martin7b2ff56fb4bc
diff --git a/products/desktop/apps/code/src/main/index.ts b/products/desktop/apps/code/src/main/index.ts
index b1cb31f1aac9..ae32ffa93253 100644
--- a/products/desktop/apps/code/src/main/index.ts
+++ b/products/desktop/apps/code/src/main/index.ts
@@ -104,6 +104,7 @@ import { isMacosPackagedUnsafeBundleLocation } from "./utils/macos-packaged-inst
import { installMainFetchLogging } from "./utils/network-fetch-logger";
import { installRendererNetworkLogging } from "./utils/network-webrequest-logger";
import { createWindow, onMainWindowClosed } from "./window";
+import { installYoutubeEmbedReferrer } from "./youtube-embed-referrer";
type FileWatcherEventsByKind = {
[K in FileWatcherEvent["kind"]]: Extract<FileWatcherEvent, { kind: K }>;
@@ -368,6 +369,7 @@ app.whenReady().then(async () => {
session.fromPartition("persist:main").webRequest,
container.get<DevNetworkService>(DEV_NETWORK_SERVICE),
);
+ installYoutubeEmbedReferrer(session.fromPartition("persist:main").webRequest);
createWindow();
setupQuickAsk();
// The hidden quick-ask panel must not keep the app alive after the main
diff --git a/products/desktop/apps/code/src/main/youtube-embed-referrer.test.ts b/products/desktop/apps/code/src/main/youtube-embed-referrer.test.ts
new file mode 100644
index 000000000000..440aed3d9c20
--- /dev/null
+++ b/products/desktop/apps/code/src/main/youtube-embed-referrer.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+import {
+ withYoutubeEmbedReferrer,
+ YOUTUBE_EMBED_REFERRER,
+} from "./youtube-embed-referrer";
+
+describe("withYoutubeEmbedReferrer", () => {
+ it("adds a Referer when the request has none", () => {
+ const rewritten = withYoutubeEmbedReferrer({ Accept: "text/html" });
+ expect(rewritten).toEqual({
+ Accept: "text/html",
+ Referer: YOUTUBE_EMBED_REFERRER,
+ });
+ });
+
+ it.each([
+ ["Referer", "http://localhost:5173/"],
+ ["referer", "http://localhost:5173/"],
+ ])(
+ "keeps an existing %s header untouched",
+ (headerName, existingReferrer) => {
+ const rewritten = withYoutubeEmbedReferrer({
+ [headerName]: existingReferrer,
+ });
+ expect(rewritten).toBeNull();
+ },
+ );
+});
diff --git a/products/desktop/apps/code/src/main/youtube-embed-referrer.ts b/products/desktop/apps/code/src/main/youtube-embed-referrer.ts
new file mode 100644
index 000000000000..4bd72e164b75
--- /dev/null
+++ b/products/desktop/apps/code/src/main/youtube-embed-referrer.ts
@@ -0,0 +1,52 @@
+// The packaged renderer is loaded from a file:// URL, and Chromium never
+// sends a Referer header from file:// documents. YouTube rejects
+// referrer-less embed requests with player error 153 ("Video player
+// configuration error"), which breaks the Brainrot cell in production while
+// dev (served from the Vite http origin) keeps working. Injecting a Referer
+// for embed traffic gives YouTube the referrer information it requires.
+
+interface BeforeSendHeadersDetails {
+ requestHeaders: Record<string, string>;
+}
+
+interface BeforeSendHeadersResponse {
+ requestHeaders?: Record<string, string>;
+}
+
+export interface HeaderRewritingWebRequest {
+ onBeforeSendHeaders(
+ filter: { urls: string[] },
+ listener: (
+ details: BeforeSendHeadersDetails,
+ callback: (response: BeforeSendHeadersResponse) => void,
+ ) => void,
+ ): void;
+}
+
+export const YOUTUBE_EMBED_REFERRER = "https://posthog.com/";
+
+// Only the embed document itself needs the rewrite: subresources requested
+// from inside the iframe already carry the iframe's https origin as referrer.
+const YOUTUBE_EMBED_URL_PATTERNS = ["https://www.youtube-nocookie.com/*"];
+
+export function withYoutubeEmbedReferrer(
+ requestHeaders: Record<string, string>,
+): Record<string, string> | null {
+ const hasReferer = Object.keys(requestHeaders).some(
+ (name) => name.toLowerCase() === "referer",
+ );
+ if (hasReferer) return null;
+ return { ...requestHeaders, Referer: YOUTUBE_EMBED_REFERRER };
+}
+
+export function installYoutubeEmbedReferrer(
+ webRequest: HeaderRewritingWebRequest,
+): void {
+ webRequest.onBeforeSendHeaders(
+ { urls: YOUTUBE_EMBED_URL_PATTERNS },
+ (details, callback) => {
+ const rewritten = withYoutubeEmbedReferrer(details.requestHeaders);
+ callback(rewritten ? { requestHeaders: rewritten } : {});
+ },
+ );
+}
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index 0a38616b53c0..cf8a6de39571 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -327,6 +327,17 @@ export interface BrainrotActivatedProperties {
filled_cells: number;
}
+export interface BrainrotPlayerErrorProperties {
+ /** YouTube player error code (e.g. 153), or null when the widget went silent. */
+ error_code: number | null;
+ /**
+ * "player_error" when the embed reported an onError message;
+ * "no_widget_messages" when the widget sent nothing after loading, which
+ * usually means the player failed before the postMessage API came up.
+ */
+ reason: "player_error" | "no_widget_messages";
+}
+
// Settings events
export interface SettingChangedProperties {
setting_name: string;
@@ -1418,6 +1429,7 @@ export const ANALYTICS_EVENTS = {
COMMAND_CENTER_VIEWED: "Command center viewed",
COMMAND_CENTER_CANVAS_VIEWED: "Command center canvas viewed",
BRAINROT_ACTIVATED: "Brainrot activated",
+ BRAINROT_PLAYER_ERROR: "Brainrot player error",
POSTHOG_WEB_OPENED: "PostHog web opened",
SIDEBAR_NAV_ITEM_CLICKED: "Sidebar nav item clicked",
SIDEBAR_CUSTOMIZED: "Sidebar customized",
@@ -1610,6 +1622,7 @@ export type EventPropertyMap = {
[ANALYTICS_EVENTS.COMMAND_CENTER_VIEWED]: never;
[ANALYTICS_EVENTS.COMMAND_CENTER_CANVAS_VIEWED]: CommandCenterCanvasViewedProperties;
[ANALYTICS_EVENTS.BRAINROT_ACTIVATED]: BrainrotActivatedProperties;
+ [ANALYTICS_EVENTS.BRAINROT_PLAYER_ERROR]: BrainrotPlayerErrorProperties;
[ANALYTICS_EVENTS.POSTHOG_WEB_OPENED]: never;
[ANALYTICS_EVENTS.SIDEBAR_NAV_ITEM_CLICKED]: SidebarNavItemClickedProperties;
[ANALYTICS_EVENTS.SIDEBAR_CUSTOMIZED]: SidebarCustomizedProperties;
diff --git a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterPanel.tsx b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterPanel.tsx
index b230cc54bb26..a2cf0eeb2d48 100644
--- a/products/desktop/packages/ui/src/features/command-center/components/CommandCenterPanel.tsx
+++ b/products/desktop/packages/ui/src/features/command-center/components/CommandCenterPanel.tsx
@@ -239,9 +239,15 @@ const BRAINROT_PLAYLIST_IDS = [
"PLSzOLzwLMqSM",
];
const BRAINROT_EMBED_ORIGIN = "https://www.youtube-nocookie.com";
+// Player errors like 153 arrive as onError messages, but the widget can stay
+// silent when the embed document itself fails to load or boot. Silence after
+// load is the only renderer-visible signal of that failure.
+const BRAINROT_WIDGET_SILENCE_TIMEOUT_MS = 15_000;
function brainrotEmbedUrl(playlistId: string): string {
- return `${BRAINROT_EMBED_ORIGIN}/embed/videoseries?list=${playlistId}&enablejsapi=1&autoplay=1&mute=1&playsinline=1&rel=0`;
+ // loop=1 duplicates the setLoop postMessage call, so looping survives when
+ // the widget's postMessage channel is unavailable.
+ return `${BRAINROT_EMBED_ORIGIN}/embed/videoseries?list=${playlistId}&enablejsapi=1&autoplay=1&mute=1&playsinline=1&rel=0&loop=1`;
}
function pickBrainrotEmbedUrl(): string {
@@ -256,6 +262,8 @@ function BrainrotCell({ cellIndex }: { cellIndex: number }) {
const clearCell = useCommandCenterStore((s) => s.clearCell);
const iframeRef = useRef<HTMLIFrameElement>(null);
const randomizedRef = useRef(false);
+ const errorTrackedRef = useRef(false);
+ const silenceTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [loading, setLoading] = useState(true);
// Lazy initializer so the playlist choice is made once per mount.
const [embedUrl] = useState(pickBrainrotEmbedUrl);
@@ -276,13 +284,31 @@ function BrainrotCell({ cellIndex }: { cellIndex: number }) {
if (event.origin !== BRAINROT_EMBED_ORIGIN) return;
if (event.source !== iframeRef.current?.contentWindow) return;
if (typeof event.data !== "string") return;
- let message: { info?: { playlist?: unknown } };
+ let message: { event?: unknown; info?: unknown };
try {
message = JSON.parse(event.data);
} catch {
return;
}
- const playlist = message.info?.playlist;
+ if (silenceTimeoutRef.current) {
+ clearTimeout(silenceTimeoutRef.current);
+ silenceTimeoutRef.current = null;
+ }
+ if (message.event === "onError" && !errorTrackedRef.current) {
+ errorTrackedRef.current = true;
+ const code =
+ typeof message.info === "number"
+ ? message.info
+ : Number(message.info);
+ track(ANALYTICS_EVENTS.BRAINROT_PLAYER_ERROR, {
+ error_code: Number.isFinite(code) ? code : null,
+ reason: "player_error",
+ });
+ }
+ const playlist =
+ typeof message.info === "object" && message.info !== null
+ ? (message.info as { playlist?: unknown }).playlist
+ : undefined;
if (
randomizedRef.current ||
!Array.isArray(playlist) ||
@@ -297,7 +323,13 @@ function BrainrotCell({ cellIndex }: { cellIndex: number }) {
postToPlayer("setLoop", [true]);
};
window.addEventListener("message", onMessage);
- return () => window.removeEventListener("message", onMessage);
+ return () => {
+ window.removeEventListener("message", onMessage);
+ if (silenceTimeoutRef.current) {
+ clearTimeout(silenceTimeoutRef.current);
+ silenceTimeoutRef.current = null;
+ }
+ };
}, [postToPlayer]);
const handleLoad = useCallback(() => {
@@ -310,6 +342,16 @@ function BrainrotCell({ cellIndex }: { cellIndex: number }) {
}),
BRAINROT_EMBED_ORIGIN,
);
+ if (silenceTimeoutRef.current) {
+ clearTimeout(silenceTimeoutRef.current);
+ }
+ silenceTimeoutRef.current = setTimeout(() => {
+ silenceTimeoutRef.current = null;
+ track(ANALYTICS_EVENTS.BRAINROT_PLAYER_ERROR, {
+ error_code: null,
+ reason: "no_widget_messages",
+ });
+ }, BRAINROT_WIDGET_SILENCE_TIMEOUT_MS);
}, [cellIndex]);
return (