mirror of
https://github.com/Untrivial-ai/agent-orchestrator.git
synced 2026-11-23 16:21:31 +08:00
fix: preserve Sentry error messages and split issue groups (#8892)
This commit is contained in:
1 parent
7c65ce3cfc
commit
1f1362995b
13 files changed
+301
-86
No files matched your search
@@ -4,7 +4,7 @@ import type { IpcMain, IpcMainInvokeEvent } from "electron";
|
||||
// Electron main's handled failures (daemon start and exit, auto-update, IPC
|
||||
// handlers, hung windows) used to reach only the console and PostHog. This
|
||||
// module is the single path from those sites to the consented Sentry
|
||||
// transport. Only fixed categories and reasons cross it; error text never does.
|
||||
// transport. Error messages are scrubbed by the transport before sending.
|
||||
|
||||
export const MAIN_ERROR_CATEGORIES = ["daemon", "update", "ipc", "window", "acp_runtime", "side_chat"] as const;
|
||||
export type MainErrorCategory = (typeof MAIN_ERROR_CATEGORIES)[number];
|
||||
@@ -27,7 +27,7 @@ export type MainErrorReason = (typeof MAIN_ERROR_REASONS)[number];
|
||||
export type MainErrorCapture = {
|
||||
category: MainErrorCategory;
|
||||
reason: MainErrorReason;
|
||||
// Only the error's standard type is used.
|
||||
// The transport extracts the error type and a scrubbed message.
|
||||
error?: unknown;
|
||||
// A short fixed detail such as "signal:SIGKILL" or "code:1".
|
||||
detail?: string;
|
||||
|
||||
@@ -114,7 +114,7 @@ describe("Electron main Sentry configuration", () => {
|
||||
message: "Electron main daemon failure (exited)",
|
||||
fingerprint: ["electron", "handled", "daemon", "exited", "electron-main"],
|
||||
tags: { surface: "electron-main", kind: "handled", category: "daemon", reason: "exited", detail: "signal:SIGKILL" },
|
||||
exception: { values: [{ type: "TypeError", value: "" }] },
|
||||
exception: { values: [{ type: "TypeError", value: "Electron main daemon failure (exited)" }] },
|
||||
});
|
||||
const second = beforeSend(sdk.captureEvent.mock.calls[1]?.[0] as ErrorEvent);
|
||||
expect(second?.tags).not.toHaveProperty("detail");
|
||||
@@ -126,7 +126,7 @@ describe("Electron main Sentry configuration", () => {
|
||||
const beforeSend = sdk.init.mock.calls[0]?.[0].beforeSend as (event: ErrorEvent) => ErrorEvent | null;
|
||||
transport.captureMain?.({ category: "side_chat", reason: "recovery", error: new TypeError("private-session /Users/private token=secret"), detail: "private-project" });
|
||||
const event = beforeSend(sdk.captureEvent.mock.calls[0][0]);
|
||||
expect(event).toMatchObject({ message: "Electron main side_chat failure (recovery)", tags: { category: "side_chat", reason: "recovery" }, exception: { values: [{ type: "TypeError", value: "" }] } });
|
||||
expect(event).toMatchObject({ message: "Electron main side_chat failure (recovery)", tags: { category: "side_chat", reason: "recovery" }, exception: { values: [{ type: "TypeError", value: "Electron main side_chat failure (recovery)" }] } });
|
||||
expect(JSON.stringify(event)).not.toMatch(/private|Users|secret/);
|
||||
});
|
||||
|
||||
@@ -534,7 +534,7 @@ describe("sanitizeRendererCapture", () => {
|
||||
consentGeneration: "generation-1",
|
||||
kind: "exception",
|
||||
level: "error",
|
||||
message: "failed [redacted-path] at [redacted-url] and [redacted-path]",
|
||||
message: "",
|
||||
tags: {
|
||||
operation: "GET [redacted-url]",
|
||||
category: "[redacted-url]",
|
||||
@@ -550,11 +550,11 @@ describe("sanitizeRendererCapture", () => {
|
||||
expect(sanitizeRendererCapture({ ...base, kind: "trace" })).toBeNull();
|
||||
expect(sanitizeRendererCapture({ ...base, level: "debug" })).toBeNull();
|
||||
expect(sanitizeRendererCapture({ ...base, kind: "exception", exception: { type: "ProjectError", frames: [] } })).toBeNull();
|
||||
expect(sanitizeRendererCapture({ ...base, kind: "exception", exception: { type: "TypeError", frames: [{ function: "loadProject", filename: "/Users/alice/private-repo" }] } })).toBeNull();
|
||||
expect(sanitizeRendererCapture({ ...base, kind: "exception", exception: { type: "TypeError", frames: [{ function: "loadProject", filename: "assets/../private.js" }] } })).toBeNull();
|
||||
expect(sanitizeRendererCapture({ ...base, kind: "exception", exception: { type: "TypeError", frames: [{ function: "private-repo" }] } })).toBeNull();
|
||||
expect(sanitizeRendererCapture({ ...base, kind: "exception", exception: { type: "TypeError", frames: [{ function: "loadProject", filename: "/Users/alice/private-repo" }] } })?.exception?.frames).toEqual([]);
|
||||
expect(sanitizeRendererCapture({ ...base, kind: "exception", exception: { type: "TypeError", frames: [{ function: "loadProject", filename: "assets/../private.js" }] } })?.exception?.frames).toEqual([]);
|
||||
expect(sanitizeRendererCapture({ ...base, kind: "exception", exception: { type: "TypeError", frames: [{ function: "<anonymous>", lineno: 5 }] } })?.exception?.frames).toEqual([{ function: "renderer_frame", lineno: 5 }]);
|
||||
for (const colno of [0, -1, 10_000_001, 1.5, "private", null]) {
|
||||
expect(sanitizeRendererCapture({ ...base, kind: "exception", exception: { type: "TypeError", frames: [{ function: "privateProject", colno }] } })).toBeNull();
|
||||
expect(sanitizeRendererCapture({ ...base, kind: "exception", exception: { type: "TypeError", frames: [{ function: "privateProject", colno }] } })?.exception?.frames).toEqual([]);
|
||||
}
|
||||
expect(sanitizeRendererCapture({ ...base, kind: "exception", exception: { type: "TypeError", frames: [{ function: "privateProject", filename: "assets/app-A1B2C3D4.js", lineno: 5, colno: 138_000 }] } })?.exception?.frames).toEqual([{ function: "renderer_frame", filename: "assets/app-A1B2C3D4.js", lineno: 5, colno: 138_000 }]);
|
||||
});
|
||||
@@ -612,17 +612,17 @@ describe("Electron main error sampling and budget", () => {
|
||||
it("titles an anonymous renderer frame by bundle file and line and keeps its debug ID", async () => {
|
||||
const debugId = "8a1f4c2e-1b3d-4e5f-9a6b-7c8d9e0f1a2b";
|
||||
const transport = await initMainSentry("1.0.0", dataDir, "/tmp/ao-electron-test");
|
||||
transport.capture({ consentGeneration: "generation-1", kind: "exception", message: "private", level: "error", exception: { type: "TypeError", frames: [{ function: "renderer_frame", filename: "assets/useSessionWorkspaceFiles-BjAotn5p.js", lineno: 123, colno: 45, debug_id: debugId }] } });
|
||||
transport.capture({ consentGeneration: "generation-1", kind: "exception", message: "private", level: "error", exception: { type: "TypeError", frames: [{ function: "<anonymous>", filename: "/home/alice/private.js" }, { function: "Object.a [as then]", filename: "assets/useSessionWorkspaceFiles-BjAotn5p.js", lineno: 123, colno: 45, debug_id: debugId }] } });
|
||||
const sent = sdk.captureEvent.mock.calls[0]?.[0] as ErrorEvent;
|
||||
expect(sent.debug_meta?.images).toEqual([{ type: "sourcemap", code_file: "app://renderer/assets/useSessionWorkspaceFiles-BjAotn5p.js", debug_id: debugId }]);
|
||||
const event = beforeSendOf()(sent);
|
||||
expect(event?.message).toBe("Renderer TypeError in assets/useSessionWorkspaceFiles:123:45 (unknown)");
|
||||
// Sentry applies source maps only to javascript or node events.
|
||||
expect(event?.platform).toBe("javascript");
|
||||
expect(event?.exception?.values?.[0]?.value).toBe("");
|
||||
expect(event?.exception?.values?.[0]?.value).toBe("Renderer TypeError in assets/useSessionWorkspaceFiles:123:45 (unknown)");
|
||||
expect(event?.exception?.values?.[0]?.stacktrace?.frames?.[0]).toMatchObject({ abs_path: "app://renderer/assets/useSessionWorkspaceFiles-BjAotn5p.js", lineno: 123, colno: 45 });
|
||||
expect(event?.debug_meta?.images).toEqual([{ type: "sourcemap", code_file: "app://renderer/assets/useSessionWorkspaceFiles-BjAotn5p.js", debug_id: debugId }]);
|
||||
expect(sanitizeRendererCapture({ consentGeneration: "g", kind: "exception", message: "m", exception: { type: "Error", frames: [{ function: "renderer_frame", filename: "assets/x-BjAotn5p.js", debug_id: "not-a-uuid" }] } })).toBeNull();
|
||||
expect(sanitizeRendererCapture({ consentGeneration: "g", kind: "exception", message: "m", exception: { type: "Error", frames: [{ function: "renderer_frame", filename: "assets/x-BjAotn5p.js", debug_id: "not-a-uuid" }] } })?.exception?.frames).toEqual([{ function: "renderer_frame", filename: "assets/x-BjAotn5p.js" }]);
|
||||
});
|
||||
|
||||
it("maps main bundle frames and debug images to app URLs without install paths", async () => {
|
||||
@@ -669,3 +669,35 @@ describe("Electron main error sampling and budget", () => {
|
||||
expect(beforeSendOf()(mainError("other"))).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("uses scrubbed renderer exception text for titles and grouping", async () => {
|
||||
const transport = await initMainSentry("1.0.0", dataDir, "/tmp/ao-electron-test");
|
||||
const beforeSend = sdk.init.mock.calls[0]?.[0].beforeSend as (event: ErrorEvent) => ErrorEvent | null;
|
||||
const send = (message: string) => {
|
||||
transport.capture({ consentGeneration: "g", kind: "exception", message,
|
||||
tags: { category: "render_crash" },
|
||||
exception: { type: "TypeError", frames: [] },
|
||||
});
|
||||
return beforeSend(sdk.captureEvent.mock.calls.at(-1)?.[0] as ErrorEvent);
|
||||
};
|
||||
const first = send("HTTP error 500: /etc/private http://localhost:8080/token alice@example.test '0xdeadbeef'");
|
||||
const same = send("HTTP error 503: ~/private http://127.0.0.1/x bob@example.test '12345678-1234-1234-1234-123456789abc'");
|
||||
const other = send("Cannot read properties of undefined (reading 'id')");
|
||||
expect(first?.exception?.values?.[0]?.value).toBe("HTTP error 500 (in unknown, render_crash)");
|
||||
expect(same?.fingerprint).toEqual(first?.fingerprint);
|
||||
expect(other?.fingerprint).not.toEqual(first?.fingerprint);
|
||||
expect(other?.exception?.values?.[0]?.value).toBe("Cannot read properties of undefined (reading 'id') (in unknown, render_crash)");
|
||||
expect(send("/home/alice/private.txt")?.exception?.values?.[0]?.value).toBe("Renderer TypeError in unknown (render_crash)");
|
||||
});
|
||||
|
||||
it("uses scrubbed messages for handled and SDK-originated main errors", async () => {
|
||||
const transport = await initMainSentry("1.0.0", dataDir, "/tmp/ao-electron-test");
|
||||
const beforeSend = sdk.init.mock.calls[0]?.[0].beforeSend as (event: ErrorEvent) => ErrorEvent | null;
|
||||
const value = "ENOENT: no such file or directory, open '/var/projects/alice/private'";
|
||||
transport.captureMain?.({ category: "ipc", reason: "handler", detail: "channel:project:read", error: new Error(value) });
|
||||
const handled = beforeSend(sdk.captureEvent.mock.calls[0][0]);
|
||||
expect(handled?.exception?.values?.[0]?.value).toBe("ENOENT: no such file or directory, open [redacted] (in channel:project:read, ipc/handler)");
|
||||
expect(handled?.fingerprint?.at(-1)).toBe("enoent: no such file or directory, open [redacted]");
|
||||
const uncaught = beforeSend({ type: undefined, exception: { values: [{ type: "Error", value }] } });
|
||||
expect(uncaught?.exception?.values?.[0]?.value).toBe("ENOENT: no such file or directory, open [redacted] (in unknown, main_error)");
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { RendererTelemetryCapture } from "../shared/telemetry-policy";
|
||||
import { DEFAULT_ELECTRON_SENTRY_DSN, isPublishedSentryBuild, SAFE_APP_ASSET, SAFE_FUNCTION, safeSentryExceptionType, safeSentryFunctionName, sentryEnvironment } from "../shared/sentry-config";
|
||||
import { scrubSentryMessage, sentryExceptionValue, sentryMessageFingerprint } from "../../../packages/shared/telemetry/sentry-message";
|
||||
import { loadOrCreateTelemetryInstallId } from "../shared/telemetry";
|
||||
import type { DesktopTelemetryTransport } from "./desktop-telemetry-controller";
|
||||
import { isSafeMainErrorDetail, MAIN_ERROR_CATEGORIES, MAIN_ERROR_REASONS, sanitizeMainErrorCapture, type MainErrorCapture } from "./main-error-capture";
|
||||
@@ -99,15 +100,15 @@ const CAPTURE_LEVELS = new Set<NonNullable<RendererTelemetryCapture["level"]>>([
|
||||
const LOCAL_URL = /(?:\bfile:\/\/\/\S+|\bapp:\/\/renderer\/\S+|\bhttps?:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?\S*)/gi;
|
||||
const HOME_PATH = /\/(?:Users|home)\/[^\s"']+/g;
|
||||
const WIN_PATH = /[A-Za-z]:\\[^\s"']+|\\\\[^\s"']+/g;
|
||||
const SAFE_CATEGORIES = new Set(["agent_runtime", "http_5xx", "integration", "native_crash", "onboarding", "render_crash", "update"]);
|
||||
const SAFE_CATEGORIES = new Set(["renderer_exception", "renderer_rejection", "agent_runtime", "http_5xx", "integration", "native_crash", "onboarding", "render_crash", "update"]);
|
||||
const MAIN_CATEGORIES = new Set<string>(MAIN_ERROR_CATEGORIES);
|
||||
const MAIN_REASONS = new Set<string>(MAIN_ERROR_REASONS);
|
||||
const SAFE_CODES = new Set([
|
||||
"AGENT_RESUME_FAILED", "CHAT_DELIVERY_FAILED", "CONVERSATION_READ_FAILED",
|
||||
"INTERNAL_ERROR", "ORCHESTRATOR_SPAWN_FAILED", "REPORT_CREATE_FAILED",
|
||||
"REPORT_LIST_FAILED", "REVIEW_OPERATION_FAILED", "WORKSPACE_GIT_READ_FAILED",
|
||||
"REPORT_LIST_FAILED", "REVIEW_OPERATION_FAILED", "WORKSPACE_GIT_READ_FAILED", "WINDOW_ERROR", "UNHANDLED_REJECTION", "RENDERER_SCRIPT_LOAD_FAILED",
|
||||
]);
|
||||
const SAFE_OPERATIONS = new Set(["query", "mutation", "route", "react_render", "open_orchestrator", "xterm_init"]);
|
||||
const SAFE_OPERATIONS = new Set(["query", "mutation", "route", "react_render", "open_orchestrator", "xterm_init", "session_view", "lazy_chunk"]);
|
||||
// Flows a renderer event can be tagged with while they show.
|
||||
const SAFE_FLOWS = new Set(["onboarding"]);
|
||||
|
||||
@@ -218,6 +219,7 @@ function scrubMainSentryEvent(event: Sentry.ErrorEvent, installId: string, versi
|
||||
};
|
||||
}
|
||||
const exceptionType = safeSentryExceptionType(event.exception?.values?.[0]?.type);
|
||||
const errorMessage = scrubSentryMessage(event.exception?.values?.[0]?.value ?? event.message);
|
||||
const frames = event.exception?.values?.flatMap((value) => value.stacktrace?.frames ?? [])
|
||||
.filter((frame) => frame.in_app !== false && typeof frame.function === "string" && frame.function.length <= 128 && SAFE_FUNCTION.test(frame.function))
|
||||
.slice(-8)
|
||||
@@ -248,38 +250,39 @@ function scrubMainSentryEvent(event: Sentry.ErrorEvent, installId: string, versi
|
||||
timestamp: event.timestamp,
|
||||
level: event.level === "fatal" || event.level === "error" || event.level === "warning" ? event.level : "error",
|
||||
message: title,
|
||||
fingerprint: ["electron", kind, renderer ? rendererLabel : processReason ?? safeCode, exceptionType, topFunction, renderer ? "renderer" : "electron-main"],
|
||||
fingerprint: ["electron", kind, renderer ? rendererLabel : processReason ?? safeCode, exceptionType, topFunction, renderer ? "renderer" : "electron-main", ...sentryMessageFingerprint(errorMessage)],
|
||||
tags: { surface: renderer ? "renderer" : "electron-main", kind, ...(renderer ? { category: safeCategory, code: safeCode, ...(safeOperation ? { operation: safeOperation } : {}), ...(safeFlow ? { flow: safeFlow } : {}) } : {}), ...(processReason ? { reason: processReason } : {}) },
|
||||
user: { id: installId },
|
||||
release: version,
|
||||
environment,
|
||||
exception: { values: [{ type: exceptionType, value: "", ...(frames?.length ? { stacktrace: { frames } } : {}) }] },
|
||||
exception: { values: [{ type: exceptionType, value: sentryExceptionValue(errorMessage, title, topFunction, renderer ? rendererLabel : processReason ?? kind), ...(frames?.length ? { stacktrace: { frames } } : {}) }] },
|
||||
...(debugImages.length ? { debug_meta: { images: debugImages } } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
// A handled main-process failure reported through captureMainError. Its title
|
||||
// and grouping come only from the fixed category and reason.
|
||||
// A handled main-process failure reported through captureMainError.
|
||||
function scrubMainHandledEvent(event: Sentry.ErrorEvent, installId: string, version: string, environment: string): Sentry.ErrorEvent | null {
|
||||
const category = event.tags?.["ao.category"];
|
||||
const reason = event.tags?.["ao.reason"];
|
||||
if (typeof category !== "string" || !MAIN_CATEGORIES.has(category) || typeof reason !== "string" || !MAIN_REASONS.has(reason)) return null;
|
||||
const detail = event.tags?.["ao.detail"];
|
||||
const title = `Electron main ${category} failure (${reason})`;
|
||||
const exceptionType = safeSentryExceptionType(event.exception?.values?.[0]?.type);
|
||||
const errorMessage = scrubSentryMessage(event.exception?.values?.[0]?.value ?? event.message);
|
||||
return {
|
||||
type: undefined,
|
||||
platform: "node",
|
||||
event_id: event.event_id,
|
||||
timestamp: event.timestamp,
|
||||
level: event.level === "fatal" || event.level === "warning" ? event.level : "error",
|
||||
message: `Electron main ${category} failure (${reason})`,
|
||||
// IPC failures group per channel; everything else per category and reason.
|
||||
fingerprint: ["electron", "handled", category, reason, ...(category === "ipc" && isSafeMainErrorDetail(detail) ? [detail] : []), "electron-main"],
|
||||
message: title,
|
||||
// Keep the IPC channel when known.
|
||||
fingerprint: ["electron", "handled", category, reason, ...(category === "ipc" && isSafeMainErrorDetail(detail) ? [detail] : []), "electron-main", ...sentryMessageFingerprint(errorMessage)],
|
||||
tags: { surface: "electron-main", kind: "handled", category, reason, ...(isSafeMainErrorDetail(detail) ? { detail } : {}) },
|
||||
user: { id: installId },
|
||||
release: version,
|
||||
environment,
|
||||
exception: { values: [{ type: exceptionType, value: "" }] },
|
||||
exception: { values: [{ type: exceptionType, value: sentryExceptionValue(errorMessage, title, category === "ipc" && isSafeMainErrorDetail(detail) ? detail : "electron-main", `${category}/${reason}`) }] },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -353,7 +356,7 @@ export async function initMainSentry(version: string, dataDir: string, cacheRoot
|
||||
Sentry.captureEvent({
|
||||
message: "Renderer error",
|
||||
level: safe.level ?? "error",
|
||||
...(safe.exception ? { exception: { values: [{ type: safe.exception.type, value: "", stacktrace: { frames: safe.exception.frames.map(({ debug_id: _debugId, ...frame }) => ({ ...frame, in_app: true })) } }] } } : {}),
|
||||
...(safe.exception ? { exception: { values: [{ type: safe.exception.type, value: safe.message, stacktrace: { frames: safe.exception.frames.map(({ debug_id: _debugId, ...frame }) => ({ ...frame, in_app: true })) } }] } } : {}),
|
||||
...(debugImages.length ? { debug_meta: { images: debugImages } } : {}),
|
||||
tags: {
|
||||
"ao.origin": "renderer",
|
||||
@@ -373,7 +376,7 @@ export async function initMainSentry(version: string, dataDir: string, cacheRoot
|
||||
Sentry.captureEvent({
|
||||
message: "Electron main handled error",
|
||||
level: "error",
|
||||
exception: { values: [{ type: errorTypeOf(safe.error), value: "" }] },
|
||||
exception: { values: [{ type: errorTypeOf(safe.error), value: scrubSentryMessage(safe.error instanceof Error ? safe.error.message : undefined) }] },
|
||||
tags: {
|
||||
"ao.origin": "main_handled",
|
||||
"ao.category": safe.category,
|
||||
@@ -416,20 +419,19 @@ export function sanitizeRendererCapture(request: unknown): RendererTelemetryCapt
|
||||
const value = input.exception as Record<string, unknown>;
|
||||
if (Object.keys(value).some((key) => key !== "type" && key !== "frames")) return null;
|
||||
if (typeof value.type !== "string" || safeSentryExceptionType(value.type) !== value.type) return null;
|
||||
if (!Array.isArray(value.frames) || value.frames.length > 8) return null;
|
||||
if (!Array.isArray(value.frames) || value.frames.length > 64) return null;
|
||||
const frames: NonNullable<RendererTelemetryCapture["exception"]>["frames"] = [];
|
||||
for (const frame of value.frames) {
|
||||
if (!frame || typeof frame !== "object" || Array.isArray(frame)) return null;
|
||||
if (!frame || typeof frame !== "object" || Array.isArray(frame)) continue;
|
||||
const entry = frame as Record<string, unknown>;
|
||||
if (Object.keys(entry).some((key) => key !== "function" && key !== "filename" && key !== "lineno" && key !== "colno" && key !== "debug_id")) return null;
|
||||
if (typeof entry.function !== "string" || entry.function.length > 128 || !SAFE_FUNCTION.test(entry.function)) return null;
|
||||
if (entry.filename !== undefined && (typeof entry.filename !== "string" || !SAFE_APP_ASSET.test(entry.filename))) return null;
|
||||
if (entry.lineno !== undefined && (typeof entry.lineno !== "number" || !Number.isSafeInteger(entry.lineno) || entry.lineno < 1 || entry.lineno > 1_000_000)) return null;
|
||||
if (entry.debug_id !== undefined && (typeof entry.debug_id !== "string" || !DEBUG_ID.test(entry.debug_id) || entry.filename === undefined)) return null;
|
||||
if (entry.colno !== undefined && (typeof entry.colno !== "number" || !Number.isSafeInteger(entry.colno) || entry.colno < 1 || entry.colno > 10_000_000)) return null;
|
||||
frames.push({ function: safeSentryFunctionName(entry.function, "renderer_frame"), ...(entry.filename === undefined ? {} : { filename: entry.filename as string }), ...(entry.lineno === undefined ? {} : { lineno: entry.lineno as number }), ...(entry.colno === undefined ? {} : { colno: entry.colno as number }), ...(entry.debug_id === undefined ? {} : { debug_id: (entry.debug_id as string).toLowerCase() }) });
|
||||
if (Object.keys(entry).some((key) => key !== "function" && key !== "filename" && key !== "lineno" && key !== "colno" && key !== "debug_id")) continue;
|
||||
if (entry.filename !== undefined && (typeof entry.filename !== "string" || !SAFE_APP_ASSET.test(entry.filename))) continue;
|
||||
if (entry.lineno !== undefined && (typeof entry.lineno !== "number" || !Number.isSafeInteger(entry.lineno) || entry.lineno < 1 || entry.lineno > 1_000_000)) continue;
|
||||
if (entry.colno !== undefined && (typeof entry.colno !== "number" || !Number.isSafeInteger(entry.colno) || entry.colno < 1 || entry.colno > 10_000_000)) continue;
|
||||
const debugId = entry.filename !== undefined && typeof entry.debug_id === "string" && DEBUG_ID.test(entry.debug_id) ? entry.debug_id.toLowerCase() : undefined;
|
||||
frames.push({ function: safeSentryFunctionName(entry.function, "renderer_frame"), ...(entry.filename === undefined ? {} : { filename: entry.filename as string }), ...(entry.lineno === undefined ? {} : { lineno: entry.lineno as number }), ...(entry.colno === undefined ? {} : { colno: entry.colno as number }), ...(debugId ? { debug_id: debugId } : {}) });
|
||||
}
|
||||
exception = { type: value.type, frames };
|
||||
exception = { type: value.type, frames: frames.slice(-8) };
|
||||
}
|
||||
|
||||
let tags: Record<string, string> | undefined;
|
||||
@@ -447,7 +449,7 @@ export function sanitizeRendererCapture(request: unknown): RendererTelemetryCapt
|
||||
return {
|
||||
consentGeneration: input.consentGeneration,
|
||||
kind: input.kind as RendererTelemetryCapture["kind"],
|
||||
message: scrubTelemetryText(input.message),
|
||||
message: input.kind === "exception" && !EXPECTED_NOISE.test(input.message) ? scrubSentryMessage(input.message) : scrubTelemetryText(input.message),
|
||||
...(input.level === undefined ? {} : { level: input.level as NonNullable<RendererTelemetryCapture["level"]> }),
|
||||
...(tags === undefined ? {} : { tags }),
|
||||
...(exception === undefined ? {} : { exception }),
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { sanitizeRendererCapture } from "./main/sentry-main";
|
||||
import { DesktopTelemetryController } from "./main/desktop-telemetry-controller";
|
||||
import type { RendererTelemetryCapture, TelemetryPolicyView } from "./shared/telemetry-policy";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ invoke: vi.fn(), listeners: new Map<string, (...args: unknown[]) => void>() }));
|
||||
vi.mock("@sentry/electron/main", () => ({}));
|
||||
vi.mock("electron", () => ({
|
||||
contextBridge: {
|
||||
exposeInMainWorld: (key: string, value: unknown) => Object.defineProperty(window, key, { value, configurable: true }),
|
||||
@@ -37,7 +39,7 @@ async function setup(enabled: boolean) {
|
||||
await controller.initialize();
|
||||
let resolvePolicy!: (view: TelemetryPolicyView) => void;
|
||||
const policy = new Promise<TelemetryPolicyView>((resolve) => { resolvePolicy = resolve; });
|
||||
mocks.invoke.mockImplementation(async (channel: string, input: RendererTelemetryCapture) => channel === "telemetry:getPolicy" ? policy : channel === "telemetry:capture" ? controller.capture(input) : null);
|
||||
mocks.invoke.mockImplementation(async (channel: string, input: RendererTelemetryCapture) => channel === "telemetry:getPolicy" ? policy : channel === "telemetry:capture" ? controller.capture(sanitizeRendererCapture(input)!) : null);
|
||||
await import("./preload");
|
||||
return { controller, capture, resolvePolicy };
|
||||
}
|
||||
@@ -54,7 +56,7 @@ it("captures an entry-module failure before the renderer runs, using main-owned
|
||||
expect(mocks.invoke).toHaveBeenCalledWith("telemetry:getPolicy");
|
||||
resolvePolicy(controller.snapshot());
|
||||
await vi.waitFor(() => expect(capture).toHaveBeenCalledOnce());
|
||||
expect(capture.mock.calls[0][0]).toMatchObject({ consentGeneration: "generation-1", kind: "exception", message: "Renderer startup error", exception: { type: "TypeError" } });
|
||||
expect(capture.mock.calls[0][0]).toMatchObject({ consentGeneration: "generation-1", kind: "exception", message: "", tags: { category: "renderer_exception", code: "WINDOW_ERROR" }, exception: { type: "TypeError" } });
|
||||
expect(JSON.stringify(capture.mock.calls)).not.toMatch(/private|token|project|Users/);
|
||||
// Runtime and preload use one listener. Re-observing the same early error
|
||||
// through another boundary cannot send it a second time.
|
||||
@@ -103,3 +105,27 @@ it("does not let a late initial policy response replace a newer opt-out broadcas
|
||||
await vi.waitFor(() => expect(mocks.invoke).toHaveBeenCalledWith("telemetry:capture", expect.objectContaining({ consentGeneration: disabled.consentGeneration })));
|
||||
expect(capture).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
it("keeps an early rejection's minified frame and debug ID", async () => {
|
||||
const { controller, capture, resolvePolicy } = await setup(true);
|
||||
const filename = "assets/index-A1B2C3D4.js";
|
||||
const debugId = "8a1f4c2e-1b3d-4e5f-9a6b-7c8d9e0f1a2b";
|
||||
vi.stubGlobal("_sentryDebugIds", { [`Error\n at app://renderer/${filename}:1:2`]: debugId });
|
||||
try {
|
||||
const error = new TypeError("Cannot read properties of undefined (reading 'id')");
|
||||
error.stack = `TypeError: ${error.message}\n at a (app://renderer/${filename}:17:99)`;
|
||||
const rejection = new Event("unhandledrejection");
|
||||
Object.defineProperty(rejection, "reason", { value: error });
|
||||
window.dispatchEvent(rejection);
|
||||
resolvePolicy(controller.snapshot());
|
||||
await vi.waitFor(() => expect(capture).toHaveBeenCalledOnce());
|
||||
expect(capture.mock.calls[0][0]).toMatchObject({
|
||||
message: error.message,
|
||||
tags: { category: "renderer_rejection", code: "UNHANDLED_REJECTION" },
|
||||
exception: { type: "TypeError", frames: [{ function: "renderer_frame", filename, lineno: 17, colno: 99, debug_id: debugId }] },
|
||||
});
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
@@ -77,6 +77,20 @@ it("keeps anonymous minified frames and their chunk debug IDs", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the browser location and error type when no error object or stack is available", () => {
|
||||
const event = new ErrorEvent("error", {
|
||||
message: "Uncaught TypeError: Cannot read properties of undefined (reading 'id')",
|
||||
filename: "app://renderer/assets/index-A1B2C3D4.js?private=query",
|
||||
lineno: 42,
|
||||
colno: 9,
|
||||
});
|
||||
captureExceptionToSentry(undefined, { category: "renderer_exception", code: "WINDOW_ERROR" }, event);
|
||||
expect(capture).toHaveBeenCalledWith(expect.objectContaining({
|
||||
message: "Cannot read properties of undefined (reading 'id')",
|
||||
exception: { type: "TypeError", frames: [{ function: "renderer_frame", filename: "assets/index-A1B2C3D4.js", lineno: 42, colno: 9 }] },
|
||||
}));
|
||||
});
|
||||
|
||||
it("reports a broken onboarding action as an error titled by action and reason", () => {
|
||||
captureOnboardingFailureToSentry("gh_install", "install_failed", "gh");
|
||||
expect(capture).toHaveBeenCalledWith({
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// the latest main-owned generation before forwarding to Electron main.
|
||||
import { classifyError, type ClassifyInput, type Triage } from "../../shared/observability";
|
||||
import { SAFE_APP_ASSET, SAFE_FUNCTION, safeSentryExceptionType, safeSentryFunctionName } from "../../shared/sentry-config";
|
||||
import { scrubSentryMessage } from "../../../../packages/shared/telemetry/sentry-message";
|
||||
import { onboardingFailureCode, ONBOARDING_SENTRY_REASONS, type OnboardingAction, type OnboardingFailureReason } from "../../shared/onboarding-failures";
|
||||
import { aoBridge } from "./bridge";
|
||||
import { onboardingSentryFlow } from "./onboarding-flow";
|
||||
@@ -35,7 +36,7 @@ function debugIdsByAsset(): Map<string, string> {
|
||||
const ids = (globalThis as { _sentryDebugIds?: Record<string, string> })._sentryDebugIds;
|
||||
const byAsset = new Map<string, string>();
|
||||
for (const [stack, id] of Object.entries(ids ?? {})) {
|
||||
const asset = /app:\/\/renderer\/(assets\/[^\s:)]+)/.exec(stack)?.[1];
|
||||
const asset = /app:\/\/renderer\/(assets\/[^\s:)?#]+)/.exec(stack)?.[1];
|
||||
if (asset && SAFE_APP_ASSET.test(asset)) byAsset.set(asset, id);
|
||||
}
|
||||
return byAsset;
|
||||
@@ -45,17 +46,17 @@ function debugIdsByAsset(): Map<string, string> {
|
||||
// kept when the location is an app asset. Function text crosses only when it is
|
||||
// an allowlisted name; anything else becomes "renderer_frame", and Electron
|
||||
// main titles the event by bundle file and line instead.
|
||||
function safeRendererFrames(error: unknown): RendererFrame[] {
|
||||
if (!(error instanceof Error) || !error.stack) return [];
|
||||
function safeRendererFrames(error: unknown, event?: ErrorEvent): RendererFrame[] {
|
||||
const frames: RendererFrame[] = [];
|
||||
const debugIds = debugIdsByAsset();
|
||||
for (const line of error.stack.split("\n")) {
|
||||
const match = /^\s*at\s+(?:(.+?)\s+\((\S+)\)|(\S+))\s*$/.exec(line);
|
||||
const stack = (error instanceof Error || error instanceof DOMException) && typeof error.stack === "string" ? error.stack : "";
|
||||
for (const line of stack.split("\n")) {
|
||||
const match = /^\s*at\s+(?:(.+?)\s+\((\S+)\)|((?:async )?\S+))\s*$/.exec(line);
|
||||
if (!match) continue;
|
||||
const name = match[1]?.replace(/^(?:async|new)\s+/, "");
|
||||
const location = match[2] ?? match[3];
|
||||
const location = (match[2] ?? match[3]).replace(/^async\s+/, "");
|
||||
if (!location.startsWith("app://renderer/") && !/^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?\//.test(location)) continue;
|
||||
const source = location.replace(/:\d+:\d+$/, "");
|
||||
const source = location.replace(/:\d+:\d+$/, "").split(/[?#]/, 1)[0];
|
||||
const appPath = source.startsWith("app://renderer/") ? source.slice("app://renderer/".length) : undefined;
|
||||
const filename = appPath && SAFE_APP_ASSET.test(appPath) ? appPath : undefined;
|
||||
const debugId = filename ? debugIds.get(filename) : undefined;
|
||||
@@ -66,17 +67,31 @@ function safeRendererFrames(error: unknown): RendererFrame[] {
|
||||
frames.push({ function: fn, ...(filename ? { filename } : {}), ...(lineno && Number.isSafeInteger(lineno) && lineno <= 1_000_000 ? { lineno } : {}), ...(colno && Number.isSafeInteger(colno) && colno <= 10_000_000 ? { colno } : {}), ...(debugId ? { debug_id: debugId } : {}) });
|
||||
if (frames.length === 8) break;
|
||||
}
|
||||
if (!frames.length && event?.filename?.startsWith("app://renderer/")) {
|
||||
const filename = event.filename.slice("app://renderer/".length).split(/[?#]/, 1)[0];
|
||||
if (SAFE_APP_ASSET.test(filename)) {
|
||||
const debugId = debugIds.get(filename);
|
||||
frames.push({ function: "renderer_frame", filename,
|
||||
...(Number.isSafeInteger(event.lineno) && event.lineno > 0 && event.lineno <= 1_000_000 ? { lineno: event.lineno } : {}),
|
||||
...(Number.isSafeInteger(event.colno) && event.colno > 0 && event.colno <= 10_000_000 ? { colno: event.colno } : {}),
|
||||
...(debugId ? { debug_id: debugId } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
return frames.reverse();
|
||||
}
|
||||
|
||||
export function captureExceptionToSentry(error: unknown, meta: CaptureMeta = {}): void {
|
||||
export function captureExceptionToSentry(error: unknown, meta: CaptureMeta = {}, event?: ErrorEvent): void {
|
||||
const triage = classifyError(meta);
|
||||
const isError = error instanceof Error || error instanceof DOMException;
|
||||
const message = isError ? error.message : event?.message ?? error;
|
||||
const type = isError ? error.name : typeof message === "string" ? /^(?:Uncaught(?: \(in promise\))? )?(\w+): /.exec(message)?.[1] : undefined;
|
||||
forwardCapture({
|
||||
kind: triage.report ? "exception" : "breadcrumb",
|
||||
message: "Renderer error",
|
||||
message: scrubSentryMessage(message) || "Renderer error",
|
||||
level: triage.level,
|
||||
tags: tagsFor(meta, triage),
|
||||
...(triage.report ? { exception: { type: safeSentryExceptionType((error as Error)?.name), frames: safeRendererFrames(error) } } : {}),
|
||||
...(triage.report ? { exception: { type: safeSentryExceptionType(type), frames: safeRendererFrames(error, event) } } : {}),
|
||||
});
|
||||
}
|
||||
export function captureApiErrorToSentry(operation: string, category: string, status?: number, code?: string, requestId?: string): void {
|
||||
|
||||
@@ -793,16 +793,6 @@ export function startDailyActiveHeartbeat({
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeException(reason: unknown): Error {
|
||||
if (reason instanceof Error) return reason;
|
||||
if (typeof reason === "string") return new Error(reason);
|
||||
try {
|
||||
return new Error(JSON.stringify(reason));
|
||||
} catch {
|
||||
return new Error("Unknown renderer exception");
|
||||
}
|
||||
}
|
||||
|
||||
function routeSurface(pathname: string): string {
|
||||
if (pathname === "/") return "home";
|
||||
if (/^\/settings(?:\/|$)/.test(pathname)) return "global_settings";
|
||||
@@ -1422,7 +1412,7 @@ export async function sanitizeRendererExceptionProperties(
|
||||
export function bindRendererErrorHandlers() {
|
||||
if (errorHandlersBound) return;
|
||||
errorHandlersBound = true;
|
||||
installRendererErrorHandlers((error, source) => { void captureRendererException(error, { source, unhandled: true }); });
|
||||
installRendererErrorHandlers((error, source, event) => { void captureRendererException(error, { source, unhandled: true }, event); });
|
||||
}
|
||||
|
||||
type PostHogClient = typeof posthogModule;
|
||||
@@ -1689,7 +1679,7 @@ export async function captureRendererEvent(event: string, properties?: Record<st
|
||||
}
|
||||
}
|
||||
|
||||
export async function captureRendererException(error: unknown, properties?: Record<string, unknown>): Promise<void> {
|
||||
export async function captureRendererException(error: unknown, properties?: Record<string, unknown>, event?: ErrorEvent): Promise<void> {
|
||||
if (!reserveException(error)) return;
|
||||
try {
|
||||
await initTelemetry();
|
||||
@@ -1701,11 +1691,16 @@ export async function captureRendererException(error: unknown, properties?: Reco
|
||||
// Electron main samples and budgets it per install on the final scrubbed
|
||||
// fingerprint. Renderer exceptions no longer enter the PostHog path.
|
||||
const source = typeof properties?.source === "string" ? properties.source : undefined;
|
||||
captureExceptionToSentry(normalizeException(error), {
|
||||
category: source === "react-error-boundary" ? "render_crash" : undefined,
|
||||
captureExceptionToSentry(error, {
|
||||
category: source === "react-error-boundary" || source === "route-error" ? "render_crash"
|
||||
: source === "window-error" || source === "script-load" ? "renderer_exception"
|
||||
: source === "unhandledrejection" ? "renderer_rejection" : undefined,
|
||||
code: source === "window-error" ? "WINDOW_ERROR"
|
||||
: source === "script-load" ? "RENDERER_SCRIPT_LOAD_FAILED"
|
||||
: source === "unhandledrejection" ? "UNHANDLED_REJECTION" : undefined,
|
||||
operation: typeof properties?.operation === "string" ? properties.operation : undefined,
|
||||
unhandled: properties?.unhandled === true,
|
||||
});
|
||||
}, event);
|
||||
}
|
||||
|
||||
export async function addRendererExceptionStep(message: string, properties?: Record<string, unknown>): Promise<void> {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { RendererTelemetryCaptureInput } from "./telemetry-policy";
|
||||
|
||||
type Handler = (error: unknown, source: "window-error" | "unhandledrejection") => void;
|
||||
type Source = "window-error" | "unhandledrejection" | "script-load";
|
||||
type Handler = (error: unknown, source: Source, event?: ErrorEvent) => void;
|
||||
type State = { capture?: Handler; early: WeakSet<object> };
|
||||
type ErrorWindow = Window & {
|
||||
__aoRendererErrors?: State;
|
||||
@@ -18,15 +19,17 @@ export function installRendererErrorHandlers(capture?: Handler): void {
|
||||
const state: State = { capture, early: new WeakSet() };
|
||||
root.__aoRendererErrors = state;
|
||||
const budgets = new Map<string, { minute: number; day: number; minuteCount: number; dayCount: number }>();
|
||||
const report = (error: unknown, source: "window-error" | "unhandledrejection", event?: ErrorEvent) => {
|
||||
const report = (error: unknown, source: Source, event?: ErrorEvent) => {
|
||||
try {
|
||||
if (state.capture) { state.capture(error, source); return; }
|
||||
if (state.capture) { state.capture(error, source, event); return; }
|
||||
if (!root.ao?.telemetry) return;
|
||||
const object = error !== null && typeof error === "object" ? error : undefined;
|
||||
if (object && state.early.has(object)) return;
|
||||
if ((error instanceof Error || error instanceof DOMException) && error.name === "AbortError") return;
|
||||
const types = new Set(["Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "AggregateError", "DOMException"]);
|
||||
const name = error instanceof Error && types.has(error.name) ? error.name : "Error";
|
||||
const message = (error instanceof Error || error instanceof DOMException ? error.message : typeof error === "string" ? error : event?.message) ?? "";
|
||||
const type = error instanceof Error || error instanceof DOMException ? error.name : /^(?:Uncaught )?(\w+): /.exec(message)?.[1];
|
||||
const name = type && types.has(type) ? type : "Error";
|
||||
const location = event?.filename?.replace(/^app:\/\/renderer\//, "");
|
||||
const filename = location && /^assets\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,80}-[A-Za-z0-9_-]{8,16}\.(?:js|mjs)$/.test(location) ? location : undefined;
|
||||
const line = event?.lineno, column = event?.colno;
|
||||
@@ -41,15 +44,41 @@ export function installRendererErrorHandlers(capture?: Handler): void {
|
||||
if (budget.minuteCount >= 5 || budget.dayCount >= 200) return;
|
||||
budget.minuteCount++; budget.dayCount++; budgets.set(key, budget);
|
||||
if (object) state.early.add(object);
|
||||
// This runs before the renderer module can parse stacks. Extract only
|
||||
// packaged asset coordinates and look up their injected debug IDs.
|
||||
const ids = (root as Window & { _sentryDebugIds?: Record<string, string> })._sentryDebugIds;
|
||||
const assets = new Map<string, string>();
|
||||
for (const [stack, id] of Object.entries(ids ?? {})) {
|
||||
const asset = /app:\/\/renderer\/(assets\/[^\s:)?#]+)/.exec(stack)?.[1];
|
||||
if (asset) assets.set(asset, id);
|
||||
}
|
||||
const frames = [];
|
||||
const stack = error instanceof Error && typeof error.stack === "string" ? error.stack : "";
|
||||
for (const frame of stack.split("\n")) {
|
||||
const match = /^\s*at\s+(?:.*?\()?app:\/\/renderer\/(assets\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,80}-[A-Za-z0-9_-]{8,16}\.(?:js|mjs))(?:[?#][^\s)]*)?:(\d+):(\d+)\)?$/.exec(frame);
|
||||
if (!match) continue;
|
||||
const [, filename, line, column] = match;
|
||||
const lineno = Number(line), colno = Number(column);
|
||||
if (lineno < 1 || lineno > 1_000_000 || colno < 1 || colno > 10_000_000) continue;
|
||||
const debugId = assets.get(filename);
|
||||
frames.push({ function: "renderer_frame", filename, lineno, colno, ...(debugId ? { debug_id: debugId } : {}) });
|
||||
if (frames.length === 8) break;
|
||||
}
|
||||
if (!frames.length && (filename || lineno)) {
|
||||
const debugId = filename && assets.get(filename);
|
||||
frames.push({ function: "renderer_frame", ...(filename ? { filename } : {}), ...(lineno ? { lineno } : {}), ...(colno ? { colno } : {}), ...(debugId ? { debug_id: debugId } : {}) });
|
||||
}
|
||||
void root.ao.telemetry.capture({
|
||||
kind: "exception", message: "Renderer startup error", level: "error",
|
||||
exception: { type: name, frames: filename || lineno ? [{ function: "renderer_frame", ...(filename ? { filename } : {}), ...(lineno ? { lineno } : {}), ...(colno ? { colno } : {}) }] : [] },
|
||||
kind: "exception", message: message.length <= 4096 ? message : "", level: "error",
|
||||
tags: { category: source === "unhandledrejection" ? "renderer_rejection" : "renderer_exception",
|
||||
code: source === "unhandledrejection" ? "UNHANDLED_REJECTION" : source === "script-load" ? "RENDERER_SCRIPT_LOAD_FAILED" : "WINDOW_ERROR" },
|
||||
exception: { type: name, frames: frames.reverse() },
|
||||
}).catch(() => undefined);
|
||||
} catch { /* reporting must not become another uncaught error */ }
|
||||
};
|
||||
window.addEventListener("error", (event: Event) => {
|
||||
if (event instanceof ErrorEvent) report(event.error ?? new Error("Renderer startup error"), "window-error", event);
|
||||
else if (event.target instanceof HTMLScriptElement) report(new Error("Renderer script load failed"), "window-error");
|
||||
if (event instanceof ErrorEvent) report(event.error ?? event.message, "window-error", event);
|
||||
else if (event.target instanceof HTMLScriptElement) report(new Error("Renderer script load failed"), "script-load");
|
||||
}, true);
|
||||
window.addEventListener("unhandledrejection", (event) => report(event.reason, "unhandledrejection"));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { DEFAULT_DAEMON_SENTRY_DSN, daemonSentryDsn, isPublishedSentryBuild } from "./sentry-config";
|
||||
import { DEFAULT_DAEMON_SENTRY_DSN, daemonSentryDsn, isPublishedSentryBuild, safeSentryExceptionType } from "./sentry-config";
|
||||
|
||||
import { scrubSentryMessage, sentryExceptionValue } from "../../../packages/shared/telemetry/sentry-message";
|
||||
|
||||
beforeEach(() => { vi.stubEnv("AO_PUBLISHED_BUILD", "1"); });
|
||||
afterEach(() => { vi.unstubAllEnvs(); });
|
||||
@@ -41,3 +43,29 @@ describe("published Sentry builds", () => {
|
||||
expect(isPublishedSentryBuild("0.13.0", false)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Sentry exception fields", () => {
|
||||
it("keeps registered names and rejects arbitrary custom names", () => {
|
||||
expect(safeSentryExceptionType("WorkspaceRequestError")).toBe("WorkspaceRequestError");
|
||||
expect(safeSentryExceptionType("PrivateProjectError")).toBe("Error");
|
||||
});
|
||||
|
||||
it("rebuilds known error formats without copying paths, tokens or file contents", () => {
|
||||
expect(scrubSentryMessage("ENOENT: no such file or directory, open '/var/private/token'")).toBe("ENOENT: no such file or directory, open [redacted]");
|
||||
expect(scrubSentryMessage("Unexpected token 's', secret source file contents")).toBe("Unexpected token");
|
||||
expect(scrubSentryMessage("Cannot read properties of undefined (reading 'private@example.test')")).toBe("Cannot read properties of undefined (reading '[redacted]')");
|
||||
expect(scrubSentryMessage("Please summarize the following private prompt")).toBe("");
|
||||
expect(scrubSentryMessage("token=private")).toBe("");
|
||||
});
|
||||
|
||||
it("keeps chunk failures through repeated scrubbing", () => {
|
||||
const message = scrubSentryMessage("Loading chunk 123 failed: http://localhost:8080/private");
|
||||
expect(message).toBe("Loading chunk failed");
|
||||
expect(scrubSentryMessage(message)).toBe(message);
|
||||
});
|
||||
|
||||
it("caps the complete exception value including its location", () => {
|
||||
expect(sentryExceptionValue("Invalid array length", "Fallback", "x".repeat(180), "render_crash").length).toBe(200);
|
||||
expect(sentryExceptionValue("", "Fallback", "unknown", "other")).toBe("Fallback");
|
||||
});
|
||||
});
|
||||
@@ -38,13 +38,7 @@ export function safeSentryFunctionName(value: unknown, fallback: string): string
|
||||
return typeof value === "string" && SAFE_FUNCTION_NAMES.has(value) ? value : fallback;
|
||||
}
|
||||
|
||||
const SAFE_EXCEPTION_TYPES = new Set([
|
||||
"Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "AggregateError", "DOMException",
|
||||
]);
|
||||
|
||||
export function safeSentryExceptionType(value: unknown): string {
|
||||
return typeof value === "string" && SAFE_EXCEPTION_TYPES.has(value) ? value : "Error";
|
||||
}
|
||||
export { safeSentryExceptionType } from "../../../packages/shared/telemetry/sentry-message";
|
||||
|
||||
// Keep this version mapping aligned with sentryEnvironment in the Go daemon.
|
||||
export function sentryEnvironment(version: string): "unknown" | "nightly" | "development" | "stable" {
|
||||
|
||||
@@ -107,11 +107,28 @@ describe("mobile Sentry consent and payload", () => {
|
||||
] } }] },
|
||||
});
|
||||
expect(clean).toMatchObject({ message: "Mobile error", user: { id }, exception: { values: [{
|
||||
type: "MobileError", value: "Mobile error", stacktrace: { frames: [{ function: "mobile_frame", lineno: 42 }, { function: "mobile_frame" }] },
|
||||
type: "Error", value: "Mobile error", stacktrace: { frames: [{ function: "mobile_frame", lineno: 42 }, { function: "mobile_frame" }] },
|
||||
}] } });
|
||||
expect(JSON.stringify(clean)).not.toMatch(/private|secret|raw-account|repo/);
|
||||
});
|
||||
|
||||
it("keeps the scrubbed message and groups normalized variants", async () => {
|
||||
const sentry = await import("./sentry");
|
||||
sentry.setMobileSentryConsent(true);
|
||||
await sentry.initMobileSentry();
|
||||
sentry.captureMobileException(new TypeError("Invalid array length"), { category: "render_crash" });
|
||||
const clean = (value: string) => sentry.sanitizeMobileSentryEvent({
|
||||
type: undefined,
|
||||
tags: sdk.captureException.mock.calls[0]?.[1]?.tags,
|
||||
exception: { values: [{ type: "TypeError", value }] },
|
||||
});
|
||||
const first = clean("HTTP error 500: /etc/private http://localhost:8080/x alice@example.test");
|
||||
expect(first?.exception?.values).toMatchObject([{ type: "TypeError", value: "HTTP error 500 (in mobile, render_crash)" }]);
|
||||
expect(clean("HTTP error 502: '12345678-1234-1234-1234-123456789abc'")?.fingerprint).toEqual(first?.fingerprint);
|
||||
expect(clean("Invalid array length")?.fingerprint).not.toEqual(first?.fingerprint);
|
||||
expect(clean("/home/alice/private")?.exception?.values?.[0]?.value).toBe("Mobile error");
|
||||
});
|
||||
|
||||
it("does not initialize after opt-out wins an in-flight SDK import", async () => {
|
||||
let releaseImport = () => {};
|
||||
sdk.importGate = new Promise<void>((resolve) => { releaseImport = resolve; });
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ErrorEvent, StackFrame } from "@sentry/react-native";
|
||||
import { classifyError, type ClassifyInput } from "./observability";
|
||||
import { safeSentryExceptionType, scrubSentryMessage, sentryExceptionValue, sentryMessageFingerprint } from "../../shared/telemetry/sentry-message";
|
||||
import { DEFAULT_SENTRY_DSN } from "./sentry-config";
|
||||
|
||||
const SAFE_CATEGORIES = new Set(["native_crash", "render_crash", "http_5xx", "http_4xx", "offline", "timeout"]);
|
||||
@@ -40,11 +41,19 @@ export function sanitizeMobileSentryEvent(event: ErrorEvent): ErrorEvent | null
|
||||
const severity = typeof event.tags?.["ao.severity"] === "string" && /^P[0-3]$/.test(event.tags["ao.severity"])
|
||||
? event.tags["ao.severity"] : undefined;
|
||||
const title = event.message === "Mobile API error" ? "Mobile API error" : "Mobile error";
|
||||
const values = event.exception?.values?.map((value) => ({
|
||||
type: "MobileError",
|
||||
value: "Mobile error",
|
||||
stacktrace: value.stacktrace?.frames ? { frames: value.stacktrace.frames.map(safeFrame) } : undefined,
|
||||
}));
|
||||
const exceptions = event.exception?.values ?? [];
|
||||
const messages = exceptions.map((value) => scrubSentryMessage(value.value));
|
||||
const values = exceptions.map((value, index) => {
|
||||
const frames = value.stacktrace?.frames?.map(safeFrame);
|
||||
const top = frames?.at(-1);
|
||||
const location = top?.lineno ? `mobile:${top.lineno}` : "mobile";
|
||||
return {
|
||||
type: safeSentryExceptionType(value.type),
|
||||
value: sentryExceptionValue(messages[index], title, location, category),
|
||||
stacktrace: frames ? { frames } : undefined,
|
||||
};
|
||||
});
|
||||
const primary = values.at(-1);
|
||||
const clean: ErrorEvent = {
|
||||
type: undefined,
|
||||
event_id: event.event_id,
|
||||
@@ -61,7 +70,7 @@ export function sanitizeMobileSentryEvent(event: ErrorEvent): ErrorEvent | null
|
||||
...(severity ? { "ao.severity": severity } : {}),
|
||||
...(daemonVersion && /^\d+\.\d+\.\d+(?:[.-][A-Za-z0-9.]+)?$/.test(daemonVersion) ? { "ao.daemon_version": daemonVersion } : {}),
|
||||
},
|
||||
fingerprint: ["mobile", title, category],
|
||||
fingerprint: ["mobile", title, category, ...(primary ? [primary.type] : []), ...sentryMessageFingerprint(messages.at(-1) ?? "")],
|
||||
user: pairedInstallId ? { id: pairedInstallId } : undefined,
|
||||
};
|
||||
if (clean.event_id) allowedEventIds.add(clean.event_id);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// Error text can contain arbitrary application data. Rebuild known error
|
||||
// formats from fixed text and bounded arguments before sending or grouping.
|
||||
export function scrubSentryMessage(value: unknown): string {
|
||||
if (typeof value !== "string" || value.length > 4096 || /[\r\n]/.test(value)) return "";
|
||||
const message = value.trim().replace(/^(?:Uncaught(?: \(in promise\))? )?(?:TypeError|ReferenceError|SyntaxError|RangeError|Error): /, "");
|
||||
const property = /^Cannot (read|set) properties of (undefined|null) \((reading|setting) '[^']*'\)$/.exec(message);
|
||||
if (property) {
|
||||
const key = /'(id|length|name|map|value)'\)$/.exec(message)?.[1];
|
||||
return `Cannot ${property[1]} properties of ${property[2]} (${property[3]} '${key ?? "[redacted]"}')`;
|
||||
}
|
||||
const system = /^(ENOENT: no such file or directory|EACCES: permission denied|EPERM: operation not permitted|EISDIR: illegal operation on a directory|ENOTDIR: not a directory), (open|stat|lstat|scandir|readlink|unlink|mkdir|rename)(?: .+)?$/.exec(message);
|
||||
if (system) return `${system[1]}, ${system[2]} [redacted]`;
|
||||
const network = /^(Failed to fetch(?! dynamically imported module)|Network request failed|Load failed|Connection refused)(?:[: .].*)?$/.exec(message);
|
||||
if (network) return network[1];
|
||||
const http = /^(?:HTTP (?:error )?|Request failed with status code )([45]\d\d)(?:\b.*)?$/.exec(message);
|
||||
if (http) return `HTTP error ${http[1]}`;
|
||||
const chunk = /^(Failed to fetch dynamically imported module|Importing a module script failed|Loading chunk(?: [\w-]+)? failed)(?:[: .].*)?$/.exec(message);
|
||||
if (chunk) return chunk[1].startsWith("Loading chunk ") ? "Loading chunk failed" : chunk[1];
|
||||
if (/^.{1,256} is not a (?:function|constructor)$/.test(message)) {
|
||||
return message.endsWith("function") ? "Value is not a function" : "Value is not a constructor";
|
||||
}
|
||||
if (/^.{1,256} is not defined$/.test(message)) return "Reference is not defined";
|
||||
const syntax = /^Unexpected (token|identifier)\b/.exec(message);
|
||||
if (syntax) return `Unexpected ${syntax[1]}`;
|
||||
if (/^(?:JSON Parse error: )?Unexpected end of (?:JSON )?input$/.test(message)) return message;
|
||||
return /^(?:Maximum call stack size exceeded|Invalid array length|Invalid time value|Cannot convert undefined or null to object|Renderer script load failed)$/.test(message) ? message : "";
|
||||
}
|
||||
|
||||
export function sentryMessageFingerprint(message: string): string[] {
|
||||
if (!message) return [];
|
||||
return [message.toLowerCase()
|
||||
.replace(/'[^']*'/g, "'?'")
|
||||
.replace(/\b(?:[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}|(?:0x)?[a-f0-9]{8,})\b/gi, "?")
|
||||
.replace(/\d+/g, "?")];
|
||||
}
|
||||
|
||||
export function sentryExceptionValue(message: string, title: string, location: string, label: string): string {
|
||||
if (!message) return title.slice(0, 200);
|
||||
const suffix = ` (in ${location}, ${label})`.slice(0, 199);
|
||||
return message.slice(0, 200 - suffix.length) + suffix;
|
||||
}
|
||||
|
||||
const SAFE_EXCEPTION_TYPES = new Set([
|
||||
"Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "AggregateError", "DOMException",
|
||||
"ApiError", "ArtifactTextTooLargeError", "ArtifactTooLargeError", "AuthStoreUnreadableError",
|
||||
"BrowserProfileStoreError", "CloudAuthError", "CloudCpAuthError", "CloudCpError", "CloudError",
|
||||
"CloudShareError", "EndpointRefreshError", "FolderPushError", "GitHubDaemonError",
|
||||
"IncompatibleHostVersionError", "IncompatibleRemoteVersionError", "LocalAuthError",
|
||||
"OrchestratorSpawnError", "TaskCreateError", "WorkspaceRequestError",
|
||||
]);
|
||||
|
||||
export function safeSentryExceptionType(value: unknown): string {
|
||||
return typeof value === "string" && SAFE_EXCEPTION_TYPES.has(value) ? value : "Error";
|
||||
}
|
||||
Reference in new issue
Block a user