Repository navigation
feat(telemetry): add msSinceLastUiInteraction to sampled state writes - #47490
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
The interaction throttle can suppress trusted activity after the system clock moves backward, leaving the activity signal stale until wall time catches up.
1 open issue
What changed in this PR
Extends the last-activity telemetry introduced in #47455 with time since the last trusted UI interaction, helping analysts interpret sampled state writes independently of auto-lock settings.
Changes:
- Captures trusted pointer and keyboard events, throttled to one report per second per UI surface.
- Records interaction timestamps in background session storage so they survive UI closure and service-worker restarts.
- Adds
state.write.ms_since_ui_interactionto sampled telemetry, with unit coverage across the reporting path.
| File | Description |
|---|---|
ui/store/actions.ts |
Adds best-effort forwarding of UI interactions to the background. |
ui/store/actions.test.js |
Tests forwarding and swallowed background errors. |
ui/pages/routes/routes.component.tsx |
Mounts the interaction reporter independently of auto-lock. |
ui/hooks/useUiInteractionReporter.ts |
Captures and throttles trusted interaction events. |
ui/hooks/useUiInteractionReporter.test.ts |
Tests throttling, event filtering, and listener cleanup. |
shared/lib/telemetry/state-write-reporter.ts |
Includes interaction elapsed time in sampled telemetry. |
shared/lib/telemetry/state-write-reporter.test.ts |
Tests inclusion and omission of the new attribute. |
shared/lib/telemetry/last-activity.ts |
Records, persists, restores, and exposes interaction timestamps. |
shared/lib/telemetry/last-activity.test.ts |
Tests persistence, UI closure, and hydration behavior. |
app/scripts/controllers/app-state-controller.ts |
Exposes the background interaction-recording method. |
app/scripts/controllers/app-state-controller.test.ts |
Tests delegation to last-activity tracking. |
app/scripts/controllers/app-state-controller-method-action-types.ts |
Defines and registers the messenger action type. |
Review effort: Balanced
Builds ready [9eba56a]
⚡ Performance Benchmarks (Total: 🟢 8 pass · 🟡 3 warn · 🔴 2 fail)
Bundle Size Diffs [🚨 Warning! Bundle size has increased!]
|
|
CLA Signature Action: All authors have signed the CLA. You may need to manually re-run the blocking PR check if it doesn't pass in a few minutes. |
Co-authored-by: Cursor <cursoragent@cursor.com>
9eba56a to
90a8c6f
Compare
Builds ready [90a8c6f]
⚡ Performance Benchmarks (Total: 🟢 4 pass · 🟡 5 warn · 🔴 4 fail)
Bundle Size Diffs [🚨 Warning! Bundle size has increased!]
|
MajorLift
left a comment
There was a problem hiding this comment.
Sentry span volume from the new interaction reports. The inline change keeps msSinceLastUiInteraction as it is and drops the spans these reports add: up to about 1M a month in the production metamask project, by the estimate below.
How the estimate was made
Production metamask, 2026-10-29 to 2026-11-05 (transactions by name, rpc.handler spans):
| Transactions | Users | |
|---|---|---|
Background RPC: setLastActiveTime |
1,344 | 833 |
Background RPC: messengerCall |
158,079 | |
State Persist |
89,331 | |
All rpc.handler spans |
3,424,090 | 73,343 |
setLastActiveTime goes through the same wrapper gate with the same one-second throttle, and fires on every input this hook forwards except pen, but only for users with auto-lock on, which is off by default. Scaling it to every user with a sampled background call gives 1,344 × 73,343 / 833 ≈ 118,000 sampled calls a week, each sent as two single-span transactions.
That adds up to 75% to that week's messengerCall bucket, and about 236,000 transactions in all, more than twice the State Persist writes the new field labels. It's an upper bound, and it assumes users with auto-lock on interact about as often as everyone else.
| > { | ||
| return async () => { | ||
| try { | ||
| await submitRequestToBackground('AppStateController:recordUiInteraction'); |
There was a problem hiding this comment.
Sending this call without trace context keeps the timestamp and stops sampled clicks from becoming Sentry transactions.
A click or keypress forwarded while a UI span is active carries that span's context to the background. When the call passes the shared 0.5% wrapper gate, it becomes two single-span transactions in that trace, Background RPC: messengerCall and Messenger Call: AppStateController:recordUiInteraction. The background continues the trace as sampled, so tracesSampler's per-name rates never apply, and sentry.wrapperSampleRate can lower this only by lowering every background-call span with it.
Nothing runs under this call in the background, so dropping the context loses no nested span, and msSinceLastUiInteraction still reaches State Persist.
The helper runs the callback inside a void wrapper because Sentry keeps the forked scope until a returned promise settles. Returning the promise from withActiveSpan would hide the active span from other UI work until the background replies, which the second test catches.
Here's a diff if it helps:
diff --git a/shared/lib/trace.ts b/shared/lib/trace.ts
index 8c4e5687937..6a80fd7a805 100644
--- a/shared/lib/trace.ts
+++ b/shared/lib/trace.ts
@@ -565,6 +565,30 @@ export function getSerializedTraceContext():
}
}
+/**
+ * Run the callback with no active span, so a `submitRequestToBackground` call
+ * inside it carries no trace context and the background emits no wrapper spans
+ * for it. The callback runs inside a void wrapper because Sentry keeps the
+ * forked scope until a returned promise settles, which would hide the active
+ * span from unrelated UI work in the meantime.
+ *
+ * @param callback - Code whose background calls should not join the active trace.
+ * @returns The callback's return value.
+ */
+export function withoutTraceContext<ReturnValue>(
+ callback: () => ReturnValue,
+): ReturnValue {
+ const withActiveSpan = globalThis.sentry?.withActiveSpan;
+ if (!withActiveSpan) {
+ return callback();
+ }
+ let result: ReturnValue | undefined;
+ withActiveSpan(null, () => {
+ result = callback();
+ });
+ return result as ReturnValue;
+}
+
/**
* Extract trace context appended by submitRequestToBackground from RPC params.
* Returns the clean params (without trace context) and the trace context if present.
diff --git a/ui/store/actions.test.js b/ui/store/actions.test.js
index 25e726db32d..d1004e019d5 100644
--- a/ui/store/actions.test.js
+++ b/ui/store/actions.test.js
@@ -13,6 +13,7 @@ import { TransactionStatus } from '@metamask/transaction-controller';
import { NotificationServicesController } from '@metamask/notification-services-controller';
import { BACKUPANDSYNC_FEATURES } from '@metamask/profile-sync-controller/user-storage';
import { SubscriptionUserEvent } from '@metamask/subscription-controller';
+import * as Sentry from '@sentry/browser';
// TODO: Remove restricted import
// eslint-disable-next-line import-x/no-restricted-paths
import enLocale from '../../app/_locales/en/messages.json';
@@ -6639,5 +6640,50 @@ describe('Actions', () => {
store.dispatch(actions.recordUiInteraction()),
).resolves.toBeUndefined();
});
+
+ describe('while a UI span is active', () => {
+ beforeEach(() => {
+ globalThis.sentry = { ...Sentry };
+ });
+
+ afterEach(() => {
+ globalThis.sentry = undefined;
+ });
+
+ it('sends no trace context', async () => {
+ const store = mockStore();
+ const messengerCallStub = sinon.stub().resolves();
+ setBackgroundConnection({ messengerCall: messengerCallStub });
+
+ await Sentry.startSpan({ name: 'ui' }, () =>
+ store.dispatch(actions.recordUiInteraction()),
+ );
+
+ expect(
+ messengerCallStub.calledOnceWithExactly(
+ 'AppStateController:recordUiInteraction',
+ [],
+ ),
+ ).toBe(true);
+ });
+
+ it('keeps the span active while the call is pending', async () => {
+ const store = mockStore();
+ let resolveCall;
+ setBackgroundConnection({
+ messengerCall: () =>
+ new Promise((resolve) => {
+ resolveCall = resolve;
+ }),
+ });
+
+ await Sentry.startSpan({ name: 'ui' }, async (span) => {
+ const pending = store.dispatch(actions.recordUiInteraction());
+ expect(Sentry.getActiveSpan()).toBe(span);
+ resolveCall();
+ await pending;
+ });
+ });
+ });
});
});
diff --git a/ui/store/actions.ts b/ui/store/actions.ts
index 636b90e5da8..24acd8c1276 100644
--- a/ui/store/actions.ts
+++ b/ui/store/actions.ts
@@ -198,6 +198,7 @@ import {
TraceName,
TraceOperation,
TraceRequest,
+ withoutTraceContext,
} from '../../shared/lib/trace';
import type { SerializedTraceContext } from '../../shared/lib/trace';
import { SortCriteria } from '../components/app/assets/util/sort';
@@ -5757,7 +5758,9 @@ export function recordUiInteraction(): ThunkAction<
> {
return async () => {
try {
- await submitRequestToBackground('AppStateController:recordUiInteraction');
+ await withoutTraceContext(() =>
+ submitRequestToBackground('AppStateController:recordUiInteraction'),
+ );
} catch {
// Telemetry must not surface background failures in the UI.
}There was a problem hiding this comment.
Good catch, it's updated in this commit: 1d66f4e
Co-authored-by: Cursor <cursoragent@cursor.com>
Builds ready [1d66f4e]
⚡ Performance Benchmarks (Total: 🟢 6 pass · 🟡 4 warn · 🔴 3 fail)
Bundle Size Diffs [🚨 Warning! Bundle size has increased!]
|
|
|
No release label on PR. Adding release label release-13.58.0 on PR, as PR was added to branch 13.58.0 when release was cut. |




Description
Stacked on #47455 (
feat/telemetry-last-activity-state-writes).Adds the ADR 0068 Option C
msSinceLastUiInteractionsignal to sampled State Persist writes.Trusted
pointerdownandkeydownevents in MetaMask UI surfaces are throttled to once per second and forwarded to the background through a newAppStateController:recordUiInteractionmessenger action. The background stampslastUiInteractionAtinstorage.sessionand sampled writes exposestate.write.ms_since_ui_interaction.It's on purpose that this path is separate from
setLastActiveTime, which only runs while auto-lock is enabled and uses a broader idle-timer event set.Changelog
CHANGELOG entry: null
Related issues
Fixes:
Manual testing steps
ms_since_ui_interactionproperty is now added tostate.writemetdata of State Persist traces in Sentry.Pre-merge author checklist
Pre-merge reviewer checklist
Made with Cursor
Note
Low Risk
Observability-only changes with throttled listeners, ignored failures, and no auth or persistence logic changes beyond existing session last-activity fields.
Reviewed by Cursor Bugbot for commit 1d66f4e. Bugbot is set up for automated code reviews on this repo. Configure here.