Skip to content
Open
4 changes: 2 additions & 2 deletions .agents/skills/exceptionless-javascript/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ Read only the references needed for the request. Start with the runtime for setu

## Rules

- Use `Exceptionless.startup(...)` once during app startup. `startup()` with no args is used later by lifecycle plugins to resume timers/queue processing.
- Use `Exceptionless.startup(...)` once during app startup. The first call that leaves a valid API key configures the client, including when `config.apiKey` was set beforehand and `startup()` gets no arguments; later calls only resume timers and queue processing, and configuration passed to them is ignored with a warning.
- Use the singleton from the platform package when automatic capture matters. Create `ExceptionlessClient` manually only for custom pipelines or tests.
- For React Native or Expo apps, use `@exceptionless/react-native`; do not substitute `@exceptionless/browser` or `@exceptionless/react`.
- In Expo, add `@exceptionless/react-native/expo-plugin` when native iOS crash reporting is expected. Expo Go can report JavaScript errors but cannot load the native crash reporter.
- `submitException` and `createException` take an `Error`. For unknown caught values, use exported `toError(value)` when available.
- `markAsCritical()` marks the event critical; `markAsCritical(false)` leaves tags unchanged.
- `config.serverUrl` also sets `configServerUrl` and `heartbeatServerUrl`; assign custom endpoint overrides after setting `serverUrl`.
- Use lowercase log levels in new snippets: `"trace"`, `"debug"`, `"info"`, `"warn"`, `"error"`, `"fatal"`, `"off"`.
- For short-lived Node/serverless work, call `await Exceptionless.processQueue()` after critical submissions.
- For short-lived Node/serverless work, call `await Exceptionless.processQueue()` after critical submissions. If a send is already in progress, it waits for that send to finish.

## Integrator Guidance

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ await Exceptionless.startup((config) => {
- `heartbeatInterval` defaults to 60000ms. Values below 30000ms are reset to 60000ms.
- `useSessionIdManagement` adds `SessionIdManagementPlugin`, which creates a session id and links later events to it.

Session lifetime in the browser and React Native:

- `startup()` sends a session start once. Resuming after a hidden tab continues the same session (and its heartbeats) unless the client was suspended for more than 5 minutes, after which the server has closed the session and a new one starts. Overlapping startups share the automatic session start. If a plugin cancels it, a later startup can retry.
- The browser ends the session on `pagehide` and starts a new one if the page is restored from the back/forward cache. React Native ends it when the app goes to the background and starts a new one when it becomes active.

Disable heartbeat traffic while still using session events:

```js
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/BrowserExceptionlessClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { BrowserRequestInfoPlugin } from "./plugins/BrowserRequestInfoPlugin.js"
export class BrowserExceptionlessClient extends ExceptionlessClient {
public async startup(configurationOrApiKey?: ((config: Configuration) => void) | string): Promise<void> {
const config = this.config;
if (configurationOrApiKey && !this._initialized) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure why we had this check that we removed wasn't sure if was for double init

@ejsmith ejsmith Dec 2, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It wasn't a double-init guard. _initialized already covers that, and addPlugin skips a plugin whose name is already registered. The check only skipped registering the browser plugins when startup() was called with no arguments, for example a no-arg startup() after config.apiKey = ..., which then ran without global error capture. The test "should configure browser plugins when startup is called without arguments" covers it.

if (!this._initialized) {
config.useLocalStorage();
Comment on lines +13 to 14

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve explicitly configured storage on argumentless startup

When a browser client is configured beforehand with a custom config.services.storage and then started with startup(), this newly entered block calls useLocalStorage(), which replaces that service whenever browser localStorage exists. Previously, argumentless startup retained the configured storage. With usePersistedQueueStorage enabled, persisted events in the custom backend are consequently not loaded, and subsequent events are written to a different backend. Install the platform storage default only when storage has not already been explicitly configured; the new argumentless initialization path in NodeExceptionlessClient has the same overwrite problem.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.


config.addPlugin(new BrowserGlobalHandlerPlugin());
Expand Down
10 changes: 9 additions & 1 deletion packages/browser/src/plugins/BrowserLifeCyclePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,22 @@ export class BrowserLifeCyclePlugin implements IEventPlugin {

this._client = context.client;

globalThis.addEventListener("beforeunload", () => {
// pagehide fires reliably on mobile and doesn't stop the page from entering the back/forward cache, unlike beforeunload.
globalThis.addEventListener("pagehide", () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

beforeunload fires before pagehide and gives more time for submission.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I kept pagehide on purpose:

  • Mobile: beforeunload often doesn't fire on mobile (iOS Safari, or Android when the app is backgrounded or killed). pagehide does.
  • Back/forward cache: a beforeunload listener can keep the page out of the bfcache (Firefox, for example).
  • Cancelled navigation: beforeunload also fires when another handler cancels the navigation ("Leave site?" → Stay). We would then end a session that is still active.
  • Timing: the earlier start isn't lost. The order is beforeunload → visibilitychange (hidden) → pagehide, and the existing visibilitychange handler already suspends and starts the queue send there. Only the session end waits for pagehide.
  • Delivery: the request survives because it uses keepalive (added in Make queued event delivery reliable #221), not because it starts a few ms earlier.

If you still want beforeunload, I can add it alongside pagehide. That brings back the cancelled-navigation false session end.

if (this._client?.config.sessionsEnabled) {
void this._client?.submitSessionEnd();
}

void this._client?.suspend();
});

// A page restored from the back/forward cache starts a new session.
globalThis.addEventListener("pageshow", (event: PageTransitionEvent) => {
if (event.persisted) {
void this._client?.startup();
}
});

document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
void this._client?.startup();
Expand Down
18 changes: 18 additions & 0 deletions packages/browser/test/BrowserExceptionlessClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,22 @@ describe("BrowserExceptionlessClient", () => {
await client.suspend();
}
});

test("should configure browser plugins when startup is called without arguments", async () => {
const client = new BrowserExceptionlessClient();
client.config.apiKey = "UNIT_TEST_API_KEY";
client.config.updateSettingsWhenIdleInterval = -1;

await client.startup();

try {
const pluginNames = client.config.plugins.map((plugin) => plugin.name);

expect(pluginNames).toContain("BrowserGlobalHandlerPlugin");
expect(pluginNames).toContain("BrowserErrorPlugin");
expect(pluginNames).not.toContain("SimpleErrorPlugin");
} finally {
await client.suspend();
}
});
});
65 changes: 65 additions & 0 deletions packages/browser/test/plugins/BrowserLifeCyclePlugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { afterEach, describe, expect, test, vi } from "vitest";

import { ExceptionlessClient } from "@exceptionless/core";

import { BrowserLifeCyclePlugin } from "../../src/plugins/BrowserLifeCyclePlugin.js";

describe("BrowserLifeCyclePlugin", () => {
afterEach(() => {
vi.restoreAllMocks();
});

async function startPlugin() {
const listeners = new Map<string, EventListener>();
vi.spyOn(globalThis, "addEventListener").mockImplementation((type: string, listener: EventListenerOrEventListenerObject) => {
listeners.set(type, listener as EventListener);
});

const client = new ExceptionlessClient();
client.config.sessionsEnabled = true;
const suspend = vi.spyOn(client, "suspend").mockResolvedValue();
const startup = vi.spyOn(client, "startup").mockResolvedValue();
const submitSessionEnd = vi.spyOn(client, "submitSessionEnd").mockResolvedValue();

await new BrowserLifeCyclePlugin().startup({
client,
log: client.config.services.log
});

return {
listeners,
suspend,
startup,
submitSessionEnd
};
}

test("ends the session and flushes on pagehide instead of beforeunload", async () => {
const { listeners, suspend, submitSessionEnd } = await startPlugin();

expect(listeners.has("beforeunload")).toBe(false);
listeners.get("pagehide")?.(new Event("pagehide"));

expect(submitSessionEnd).toHaveBeenCalledTimes(1);
expect(suspend).toHaveBeenCalledTimes(1);
});

test("resumes when the page is restored from the back/forward cache", async () => {
const { listeners, startup } = await startPlugin();
const pageshow = listeners.get("pageshow");

pageshow?.(
Object.assign(new Event("pageshow"), {
persisted: false
})
);
expect(startup).not.toHaveBeenCalled();

pageshow?.(
Object.assign(new Event("pageshow"), {
persisted: true
})
);
expect(startup).toHaveBeenCalledTimes(1);
});
});
58 changes: 48 additions & 10 deletions packages/core/src/ExceptionlessClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,31 +12,47 @@ import { allowProcessToExitWithoutWaitingForTimerOrInterval } from "./Utils.js";
export class ExceptionlessClient {
private _intervalId: ReturnType<typeof setInterval> | undefined;
private _timeoutId: ReturnType<typeof setTimeout> | undefined;
private _sessionActive = false;
private _startingSession: Promise<EventPluginContext> | undefined;
private _suspendedAt: number | undefined;
/** The server closes sessions that have had no activity for this long. */
private readonly SESSION_INACTIVE_PERIOD = 5 * 60 * 1000;
protected _initialized = false;

public constructor(public config: Configuration = new Configuration()) {}

/** Resume background submission, resume any timers. */
/**
* Starts the client, or resumes background submission and timers after `suspend()`.
* The first call that leaves the client with a valid API key configures it; later calls only resume it.
*/
public async startup(configurationOrApiKey?: ((config: Configuration) => void) | string): Promise<void> {
if (configurationOrApiKey && !this._initialized) {
this._initialized = true;

const startingUp = !this._initialized;
if (startingUp) {
if (typeof configurationOrApiKey === "string") {
this.config.apiKey = configurationOrApiKey;
} else {
} else if (configurationOrApiKey) {
configurationOrApiKey(this.config);
}

if (!this.config.isValid) {
// Stay uninitialized so a later startup() call can still configure the client.
this.config.services.log.warn("Exceptionless is not configured and will not process events.");
return;
}

this._initialized = true;
this.config.services.queue.onEventsPosted(() => Promise.resolve(this.updateSettingsTimer()));
await SettingsManager.applySavedServerSettings(this.config);
} else if (configurationOrApiKey) {
this.config.services.log.warn("Exceptionless has already been started; the configuration passed to startup() was ignored.");
}

if (!this.config.isValid) {
this.config.services.log.warn("Exceptionless is not configured and will not process events.");
return;
}

this.updateSettingsTimer(!!configurationOrApiKey);
this.updateSettingsTimer(startingUp);
await EventPluginManager.startup(new PluginContext(this));

const { queue } = this.config.services;
Expand All @@ -46,13 +62,26 @@ export class ExceptionlessClient {
await queue.process();
}

if (this.config.sessionsEnabled) {
await this.submitSessionStart();
// Resuming (for example, when a hidden tab becomes visible) continues the current session unless the
// server will already have closed it for inactivity.
const suspendedAt = this._suspendedAt;
this._suspendedAt = undefined;
const sessionExpired = suspendedAt !== undefined && Date.now() - suspendedAt > this.SESSION_INACTIVE_PERIOD;
if (sessionExpired) {
this._sessionActive = false;
}

if (this.config.sessionsEnabled && !this._sessionActive) {
this._startingSession ??= this.submitSessionStart().finally(() => {
this._startingSession = undefined;
});
await this._startingSession;
}
}

/** Submit events, pause any timers and go into low power mode. */
public async suspend(): Promise<void> {
this._suspendedAt ??= Date.now();
await EventPluginManager.suspend(new PluginContext(this));
const { queue } = this.config.services;
await queue.suspend();
Expand Down Expand Up @@ -172,13 +201,22 @@ export class ExceptionlessClient {
return this.createEvent().setType("session");
}

public submitSessionStart(): Promise<EventPluginContext> {
return this.createSessionStart().submit();
public async submitSessionStart(): Promise<EventPluginContext> {
const context = await this.createSessionStart().submit();
if (!context.cancelled) {
this._sessionActive = true;
}

return context;
}

public async submitSessionEnd(sessionIdOrUserId?: string): Promise<void> {
const { currentSessionIdentifier, enabled, isValid, services } = this.config;
const sessionId = sessionIdOrUserId || currentSessionIdentifier;
if (!sessionIdOrUserId || sessionIdOrUserId === currentSessionIdentifier) {
this._sessionActive = false;
}

if (sessionId && enabled && isValid) {
services.log.info(`Submitting session end: ${sessionId}`);
await services.submissionClient.submitHeartbeat(sessionId, true);
Expand Down
57 changes: 50 additions & 7 deletions packages/core/src/configuration/Configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,8 @@ export class Configuration {
* The list of plugins that will be used in this configuration.
*/
public get plugins(): IEventPlugin[] {
return this._plugins.sort((p1: IEventPlugin, p2: IEventPlugin) => {
// Sort a copy: callers iterate this list while plugins may add or remove plugins.
return [...this._plugins].sort((p1: IEventPlugin, p2: IEventPlugin) => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sort mutates but js is single threaded (browsers) so how would there ever be an issue with this? Did we ever hit an issue with this with node??

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a threading problem, and I have no report of it in the wild. The getter sorted _plugins in place and returned the live array. A caller iterating config.plugins (EventPluginManager awaits each plugin inside the loop) while a plugin calls removePlugin/addPlugin mutates the array it is iterating, so the next plugin gets skipped. The test "removing a plugin while iterating does not skip the next plugin" shows it synchronously. Returning a sorted copy costs a few plugins' worth of allocation. If you'd rather not carry it, I can revert it.

if (p1 == null && p2 == null) {
return 0;
}
Expand Down Expand Up @@ -521,16 +522,58 @@ export class Configuration {
}
}

private originalSettings?: Record<string, string>;
/** Local values of settings the server has overridden, restored when the server stops sending them. */
private _overriddenLocalSettings: Record<string, string> = {};
/** The server settings that were applied last. */
private _appliedServerSettings: Record<string, string> = {};

public applyServerSettings(serverSettings: ServerSettings): void {
if (!this.originalSettings) {
this.originalSettings = JSON.parse(JSON.stringify(this.settings)) as Record<string, string>;
this.services.log.trace(`Applying saved settings: v${serverSettings?.version}`);

const received: Record<string, string> = {};
const value: unknown = serverSettings?.settings;
if (value && typeof value === "object") {
for (const [key, setting] of Object.entries(value)) {
if (typeof setting === "string") {
received[key] = setting;
} else {
this.services.log.warn(`Ignoring server setting "${key}": expected a string value`);
}
}
}

// Settings still holding the value the server last sent are server-owned: drop them (restoring any local value they
// replaced) so settings the server no longer sends are removed. Anything else, including local changes made after
// startup, is kept.
const settings: Record<string, string> = {
...this.settings
};
Comment thread
ejsmith marked this conversation as resolved.
Resolved
for (const [key, setting] of Object.entries(this._appliedServerSettings)) {
if (settings[key] !== setting) {
delete this._overriddenLocalSettings[key];
continue;
}

if (key in this._overriddenLocalSettings) {
settings[key] = this._overriddenLocalSettings[key];
delete this._overriddenLocalSettings[key];
} else {
delete settings[key];
}
}

for (const [key, setting] of Object.entries(received)) {
// Server-owned keys were removed above, so any remaining value is local, even if it equals the server value.
if (key in settings) {
this._overriddenLocalSettings[key] = settings[key];
}

settings[key] = setting;
}

this.services.log.trace(`Applying saved settings: v${serverSettings.version}`);
this.settings = Object.assign(this.originalSettings, serverSettings.settings);
this.settingsVersion = serverSettings.version;
this._appliedServerSettings = received;
this.settings = settings;
this.settingsVersion = typeof serverSettings?.version === "number" ? serverSettings.version : 0;
this.notifySubscribers();
}

Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/configuration/SettingsManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class ServerSettings {

export class SettingsManager {
private static readonly SettingsKey: string = "settings";
private static _isUpdatingSettings = false;
private static readonly _updatingConfigurations = new WeakSet<Configuration>();

public static async applySavedServerSettings(config: Configuration): Promise<void> {
if (!config?.isValid) {
Expand All @@ -23,11 +23,11 @@ export class SettingsManager {
}

public static async updateSettings(config: Configuration): Promise<void> {
if (!config?.enabled || this._isUpdatingSettings) {
if (!config?.enabled || this._updatingConfigurations.has(config)) {
return;
}

this._isUpdatingSettings = true;
this._updatingConfigurations.add(config);
const { log, storage, submissionClient } = config.services;

try {
Expand Down Expand Up @@ -58,7 +58,7 @@ export class SettingsManager {
} catch (ex) {
log.error(`Error updating settings: ${ex instanceof Error ? ex.message : ex + ""}`);
} finally {
this._isUpdatingSettings = false;
this._updatingConfigurations.delete(config);
}
}

Expand Down
Loading
Loading