diff --git a/packages/hyperion-autologging/src/ALSurfaceHierarchy.ts b/packages/hyperion-autologging/src/ALSurfaceHierarchy.ts index fb8cfa6f..eecb60bd 100644 --- a/packages/hyperion-autologging/src/ALSurfaceHierarchy.ts +++ b/packages/hyperion-autologging/src/ALSurfaceHierarchy.ts @@ -53,6 +53,9 @@ export abstract class ALSurfaceHierarchyNode< } removeChild(child: Child): boolean { + if (this.children.get(child.surfaceName) !== child) { + return false; + } return this.children.delete(child.surfaceName); } diff --git a/packages/hyperion-autologging/test/ALSurfaceHierarchy.test.ts b/packages/hyperion-autologging/test/ALSurfaceHierarchy.test.ts index ed5153f4..13a8e709 100644 --- a/packages/hyperion-autologging/test/ALSurfaceHierarchy.test.ts +++ b/packages/hyperion-autologging/test/ALSurfaceHierarchy.test.ts @@ -19,7 +19,7 @@ class TestSurfaceNode extends ALSurfaceHierarchyNode { } describe('ALSurfaceHierarchyNode', () => { - test('uses name-keyed Map replacement and removal semantics', () => { + test('does not remove a replacement through a stale child instance', () => { const root = new TestSurfaceNode('root', null, null); const first = new TestSurfaceNode('child', '/first', root); const second = new TestSurfaceNode('child', '/second', root); @@ -29,7 +29,9 @@ describe('ALSurfaceHierarchyNode', () => { expect(root.getChild('child')).toBe(second); expect(root.getChildren()).toEqual([second]); - expect(root.removeChild(first)).toBe(true); + expect(root.removeChild(first)).toBe(false); + expect(root.getChild('child')).toBe(second); + expect(root.removeChild(second)).toBe(true); expect(root.getChild('child')).toBeNull(); }); diff --git a/packages/hyperion-react-native/README.md b/packages/hyperion-react-native/README.md index b149d72b..53ec25cb 100644 --- a/packages/hyperion-react-native/README.md +++ b/packages/hyperion-react-native/README.md @@ -116,6 +116,13 @@ portable hierarchy contracts live in `hyperion-autologging`; mobile nodes have no DOM element and return a shared frozen empty collection from `getElements()`. App lifecycle is injected structurally through `reactNativeAppLifecycle({ AppState })`, so the portable runtime has no eager `react-native` dependency. +Set `transientInactiveMs` to a positive duration to suppress non-active +transitions that return to active before that duration elapses. It defaults to +zero, which dispatches every transition immediately. + +`AutoLogging.init()` accepts a positive, finite `sessionTimeoutMs` for mobile +in-memory session rotation. The default remains 30 minutes; invalid values use +that default. ## Compatibility setup diff --git a/packages/hyperion-react-native/src/ALAppLifecycle.ts b/packages/hyperion-react-native/src/ALAppLifecycle.ts index dbffa545..54b0fc33 100644 --- a/packages/hyperion-react-native/src/ALAppLifecycle.ts +++ b/packages/hyperion-react-native/src/ALAppLifecycle.ts @@ -17,15 +17,30 @@ export type { ALAppStateListener } from './IReactNative'; export const REACT_NATIVE_APP_LIFECYCLE_PLUGIN = 'react-native-app-lifecycle'; +interface PendingAppStateTransition { + state: AppStateStatus; + readonly previousState: AppStateStatus; + readonly timestamp: number; + readonly timer: ReturnType; +} + export class ALAppLifecycle implements ALAppLifecycleEnvironment { private currentState: AppStateStatus | null = null; private readonly listeners = new Set(); + private pendingTransition: PendingAppStateTransition | null = null; private subscription: { remove(): void } | null = null; + private readonly transientInactiveMs: number; constructor( private readonly appState: ReactNativeAppState, - private readonly now: () => number - ) {} + private readonly now: () => number, + transientInactiveMs = 0 + ) { + this.transientInactiveMs = + Number.isFinite(transientInactiveMs) && transientInactiveMs > 0 + ? transientInactiveMs + : 0; + } getCurrentState(): AppStateStatus | null { return this.currentState; @@ -40,32 +55,91 @@ export class ALAppLifecycle implements ALAppLifecycleEnvironment { if (this.subscription != null) return; this.currentState = this.appState.currentState; this.subscription = this.appState.addEventListener('change', (state) => { - const previousState = this.currentState; - this.currentState = state; const timestamp = this.now(); - const listenerCount = this.listeners.size; - let visited = 0; - for (const listener of this.listeners) { - if (visited++ >= listenerCount) break; - try { - listener(state, previousState, timestamp); - } catch { - // One lifecycle capability must not block the others or AppState. + const pendingTransition = this.pendingTransition; + if (pendingTransition != null) { + if (state === 'active') { + this.clearPendingTransition(); + if ( + timestamp - pendingTransition.timestamp >= + this.transientInactiveMs + ) { + this.dispatch( + pendingTransition.state, + pendingTransition.previousState, + pendingTransition.timestamp + ); + if (this.subscription != null) { + this.dispatch(state, pendingTransition.state, timestamp); + } + } + } else { + pendingTransition.state = state; } + return; } + if ( + this.transientInactiveMs > 0 && + this.currentState === 'active' && + state !== 'active' + ) { + const transition: PendingAppStateTransition = { + state, + previousState: this.currentState, + timestamp, + timer: setTimeout(() => { + if (this.pendingTransition !== transition) return; + this.pendingTransition = null; + this.dispatch( + transition.state, + transition.previousState, + transition.timestamp + ); + }, this.transientInactiveMs), + }; + this.pendingTransition = transition; + return; + } + this.dispatch(state, this.currentState, timestamp); }); } dispose(): void { + this.clearPendingTransition(); this.subscription?.remove(); this.subscription = null; this.currentState = null; this.listeners.clear(); } + + private clearPendingTransition(): void { + if (this.pendingTransition == null) return; + clearTimeout(this.pendingTransition.timer); + this.pendingTransition = null; + } + + private dispatch( + state: AppStateStatus, + previousState: AppStateStatus | null, + timestamp: number + ): void { + this.currentState = state; + const listenerCount = this.listeners.size; + let visited = 0; + for (const listener of this.listeners) { + if (visited++ >= listenerCount) break; + try { + listener(state, previousState, timestamp); + } catch { + // One lifecycle capability must not block the others or AppState. + } + } + } } export interface ReactNativeAppLifecycleOptions { readonly AppState: ReactNativeAppState; + readonly transientInactiveMs?: number; } export function reactNativeAppLifecycle< @@ -78,7 +152,11 @@ export function reactNativeAppLifecycle< if (appState == null) { throw new Error('React Native app lifecycle requires AppState.'); } - const lifecycle = new ALAppLifecycle(appState, context.now); + const lifecycle = new ALAppLifecycle( + appState, + context.now, + options.transientInactiveMs + ); context.installAppLifecycle(lifecycle); return { start() { diff --git a/packages/hyperion-react-native/src/ALCompatibility.ts b/packages/hyperion-react-native/src/ALCompatibility.ts index ad545808..f97b9afa 100644 --- a/packages/hyperion-react-native/src/ALCompatibility.ts +++ b/packages/hyperion-react-native/src/ALCompatibility.ts @@ -54,6 +54,7 @@ export interface CompatibilityInitOptions readonly props?: LegacyComponentPropsOptions | null; readonly componentProps?: LegacyComponentPropsOptions | null; readonly features?: ALFeatureConfig; + readonly sessionTimeoutMs?: number; } export function createReactNativePlugins( diff --git a/packages/hyperion-react-native/src/ALInstrumentedElement.ts b/packages/hyperion-react-native/src/ALInstrumentedElement.ts index 197d801b..e95f59bd 100644 --- a/packages/hyperion-react-native/src/ALInstrumentedElement.ts +++ b/packages/hyperion-react-native/src/ALInstrumentedElement.ts @@ -341,12 +341,12 @@ function invokeRootInstrumentedHandler( } return handler.apply(receiver, args); } + recordActivityWithoutAffectingHandler(state); try { emitUIEvent(state, snapshot, eventType, propName, eventValue); } catch { // Logging failures must not affect the application handler. } - recordActivityWithoutAffectingHandler(state); return handler.apply(receiver, args); } diff --git a/packages/hyperion-react-native/src/ALPluginAutoLogging.ts b/packages/hyperion-react-native/src/ALPluginAutoLogging.ts index 214a4f32..7cbfbefd 100644 --- a/packages/hyperion-react-native/src/ALPluginAutoLogging.ts +++ b/packages/hyperion-react-native/src/ALPluginAutoLogging.ts @@ -6,10 +6,7 @@ import type { BaseChannelEventType } from 'hyperion-channel/src/Channel'; import type { AutoLoggingChannel } from 'hyperion-autologging/src/ALChannel'; -import { - clearActiveRuntimeContext, - setActiveRuntimeContext, -} from './ALActiveRuntime'; +import { clearActiveRuntimeContext } from './ALActiveRuntime'; import { createReactNativeRuntime, type ALReactNativePlugin, @@ -23,6 +20,7 @@ export interface PluginInitOptions< > { readonly channel: AutoLoggingChannel; readonly plugins: readonly ALReactNativePlugin[]; + readonly sessionTimeoutMs?: number; } type InitializationState = @@ -47,7 +45,6 @@ export function init< options as unknown as ALReactNativeRuntimeOptions ); activeRuntime = runtime; - setActiveRuntimeContext(runtime.context); initializationState = 'initialized'; return true; } catch (error) { diff --git a/packages/hyperion-react-native/src/ALRuntime.ts b/packages/hyperion-react-native/src/ALRuntime.ts index 0fdb8a56..0a758032 100644 --- a/packages/hyperion-react-native/src/ALRuntime.ts +++ b/packages/hyperion-react-native/src/ALRuntime.ts @@ -13,6 +13,10 @@ import type { import { createALEventFactory } from 'hyperion-autologging/src/ALEventFactory'; import type { ALManagedPlugin } from 'hyperion-autologging/src/ALPlugin'; import { ALPluginRuntime } from 'hyperion-autologging/src/ALPluginRuntime'; +import { + clearActiveRuntimeContext, + setActiveRuntimeContext, +} from './ALActiveRuntime'; import type { ALAppLifecycleEnvironment } from './IReactNative'; import { ALReactNativeSession } from './ALSession'; import type { ALLoggableEvent, SurfaceMetadataValue } from './ALTypes'; @@ -35,6 +39,7 @@ export interface ALReactNativeRuntimeOptions< readonly channel: AutoLoggingChannel; readonly plugins: readonly ALReactNativePlugin[]; readonly now?: () => number; + readonly sessionTimeoutMs?: number; } export interface ALReactNativeRuntime { @@ -44,20 +49,16 @@ export interface ALReactNativeRuntime { dispose(): boolean; } -function createRuntimeContext(now: () => number): ALReactNativeRuntimeContext { - const session = new ALReactNativeSession(now); - const factory = createALEventFactory({ +function createRuntimeContext( + now: () => number, + sessionTimeoutMs?: number +): ALReactNativeRuntimeContext { + const session = new ALReactNativeSession(now, sessionTimeoutMs); + const eventFactory = createALEventFactory({ now, nextEventIndex: () => session.nextEventIndex(), getBaseMetadata: () => ({}), }); - const eventFactory: ALEventFactory = { - createEvent(options?: ALCreateEventOptions) { - const eventTimestamp = options?.eventTimestamp ?? now(); - session.getSessionId(eventTimestamp); - return factory.createEvent({ ...options, eventTimestamp }); - }, - }; let appLifecycle: ALAppLifecycleEnvironment | null = null; return { eventFactory, @@ -79,9 +80,19 @@ function createRuntimeContext(now: () => number): ALReactNativeRuntimeContext { export function createReactNativeRuntime( options: ALReactNativeRuntimeOptions ): ALReactNativeRuntime { - const context = createRuntimeContext(options.now ?? Date.now); + const context = createRuntimeContext( + options.now ?? Date.now, + options.sessionTimeoutMs + ); const runtime = new ALPluginRuntime(options.channel, context); - runtime.initialize(options.plugins); + // Startup events may have subscribers that read the active session context. + setActiveRuntimeContext(context); + try { + runtime.initialize(options.plugins); + } catch (error) { + clearActiveRuntimeContext(context); + throw error; + } return { channel: options.channel, context, diff --git a/packages/hyperion-react-native/src/ALScreen.ts b/packages/hyperion-react-native/src/ALScreen.ts index ad465f29..1797c33e 100644 --- a/packages/hyperion-react-native/src/ALScreen.ts +++ b/packages/hyperion-react-native/src/ALScreen.ts @@ -85,8 +85,8 @@ export function setCurrentScreen( const previousScreen = runtime.currentScreen; const screenId = context.session.rotateScreenId(); runtime.currentScreen = { name: explicitName, screenId }; + context.session.recordActivity(); if (!runtime.publishTransitions) { - context.session.recordActivity(); return true; } const event = { @@ -101,7 +101,6 @@ export function setCurrentScreen( 'al_screen_transition_event', event as ALScreenTransitionEventData ); - context.session.recordActivity(); return true; } diff --git a/packages/hyperion-react-native/src/ALSession.ts b/packages/hyperion-react-native/src/ALSession.ts index 171946c9..30e2f1e3 100644 --- a/packages/hyperion-react-native/src/ALSession.ts +++ b/packages/hyperion-react-native/src/ALSession.ts @@ -25,20 +25,20 @@ export class ALReactNativeSession { private screenId = generateId(); private lastActivityTime: number; private eventIndex = 0; + private readonly sessionTimeoutMs: number; constructor( private readonly now: () => number = Date.now, - private readonly sessionTimeoutMs = DEFAULT_SESSION_TIMEOUT_MS + sessionTimeoutMs = DEFAULT_SESSION_TIMEOUT_MS ) { + this.sessionTimeoutMs = + Number.isFinite(sessionTimeoutMs) && sessionTimeoutMs > 0 + ? sessionTimeoutMs + : DEFAULT_SESSION_TIMEOUT_MS; this.lastActivityTime = now(); } - getSessionId(timestamp = this.now()): string { - if (timestamp - this.lastActivityTime > this.sessionTimeoutMs) { - this.sessionId = generateId(); - this.eventIndex = 0; - this.lastActivityTime = timestamp; - } + getSessionId(): string { return this.sessionId; } @@ -56,6 +56,9 @@ export class ALReactNativeSession { } recordActivity(timestamp = this.now()): void { + if (timestamp - this.lastActivityTime > this.sessionTimeoutMs) { + this.sessionId = generateId(); + } this.lastActivityTime = timestamp; } diff --git a/packages/hyperion-react-native/src/AutoLogging.ts b/packages/hyperion-react-native/src/AutoLogging.ts index 635177d0..48fd292b 100644 --- a/packages/hyperion-react-native/src/AutoLogging.ts +++ b/packages/hyperion-react-native/src/AutoLogging.ts @@ -33,6 +33,7 @@ export function init< return initPlugins({ channel: options.channel as AutoLoggingChannel, plugins: createReactNativePlugins(options), + sessionTimeoutMs: options.sessionTimeoutMs, }); } diff --git a/packages/hyperion-react-native/test/ALLifecycle.test.ts b/packages/hyperion-react-native/test/ALLifecycle.test.ts index cdd1ff85..a893160e 100644 --- a/packages/hyperion-react-native/test/ALLifecycle.test.ts +++ b/packages/hyperion-react-native/test/ALLifecycle.test.ts @@ -11,11 +11,13 @@ import TestRenderer, { act } from 'react-test-renderer'; import { createAutoLoggingChannel } from 'hyperion-autologging/src/ALChannel'; import { ALHeartbeatType } from 'hyperion-autologging/src/ALHeartbeatType'; import { + ALAppLifecycle, reactNativeAppLifecycle, type ReactNativeAppLifecycleOptions, } from '../src/ALAppLifecycle'; import { reactNativeAppStateEvents } from '../src/ALAppStateEvents'; import { reactNativeHeartbeat } from '../src/ALHeartbeat'; +import type { ALReactNativeRuntimeContext } from '../src/ALRuntime'; import { reactNativeUIEvents } from '../src/ALUIEvents'; import type { ALAppStateEventData, @@ -79,6 +81,27 @@ function createFakeLifecycle( return { AppState }; } +interface ObservedAppStateTransition { + readonly state: AppStateStatus; + readonly previousState: AppStateStatus | null; + readonly timestamp: number; +} + +function observeLifecycle(transientInactiveMs = 0) { + const fake = createFakeLifecycle('active'); + const transitions: ObservedAppStateTransition[] = []; + const lifecycle = new ALAppLifecycle( + fake.AppState, + Date.now, + transientInactiveMs + ); + lifecycle.addListener((state, previousState, timestamp) => { + transitions.push({ state, previousState, timestamp }); + }); + lifecycle.start(); + return { fake, lifecycle, transitions }; +} + describe('React Native lifecycle plugins', () => { const originalConsoleError = console.error; @@ -97,6 +120,162 @@ describe('React Native lifecycle plugins', () => { jest.restoreAllMocks(); }); + test('dispatches every AppState change immediately by default', () => { + const { fake, lifecycle, transitions } = observeLifecycle(); + const backgroundTimestamp = Date.now(); + + fake.AppState.transition('background'); + jest.advanceTimersByTime(10); + fake.AppState.transition('inactive'); + + expect(transitions).toEqual([ + { + state: 'background', + previousState: 'active', + timestamp: backgroundTimestamp, + }, + { + state: 'inactive', + previousState: 'background', + timestamp: backgroundTimestamp + 10, + }, + ]); + expect(lifecycle.getCurrentState()).toBe('inactive'); + lifecycle.dispose(); + }); + + test('suppresses a transient return to active', () => { + const { fake, lifecycle, transitions } = observeLifecycle(1_000); + + fake.AppState.transition('background'); + expect(lifecycle.getCurrentState()).toBe('active'); + jest.advanceTimersByTime(100); + fake.AppState.transition('active'); + jest.advanceTimersByTime(1_000); + + expect(transitions).toEqual([]); + expect(lifecycle.getCurrentState()).toBe('active'); + expect(jest.getTimerCount()).toBe(0); + lifecycle.dispose(); + }); + + test('dispatches an elapsed hold with its original timestamp', () => { + const { fake, lifecycle, transitions } = observeLifecycle(1_000); + const backgroundTimestamp = Date.now(); + + fake.AppState.transition('background'); + jest.advanceTimersByTime(1_000); + + expect(transitions).toEqual([ + { + state: 'background', + previousState: 'active', + timestamp: backgroundTimestamp, + }, + ]); + expect(lifecycle.getCurrentState()).toBe('background'); + + jest.advanceTimersByTime(10); + fake.AppState.transition('active'); + expect(transitions[1]).toEqual({ + state: 'active', + previousState: 'background', + timestamp: backgroundTimestamp + 1_010, + }); + lifecycle.dispose(); + }); + + test('dispatches an elapsed hold when the timer was paused', () => { + const { fake, lifecycle, transitions } = observeLifecycle(1_000); + const backgroundTimestamp = Date.now(); + + fake.AppState.transition('background'); + jest.setSystemTime(backgroundTimestamp + 5_000); + fake.AppState.transition('active'); + + expect(transitions).toEqual([ + { + state: 'background', + previousState: 'active', + timestamp: backgroundTimestamp, + }, + { + state: 'active', + previousState: 'background', + timestamp: backgroundTimestamp + 5_000, + }, + ]); + expect(lifecycle.getCurrentState()).toBe('active'); + expect(jest.getTimerCount()).toBe(0); + lifecycle.dispose(); + }); + + test('coalesces held non-active states into the latest state', () => { + const { fake, lifecycle, transitions } = observeLifecycle(1_000); + const inactiveTimestamp = Date.now(); + + fake.AppState.transition('inactive'); + jest.advanceTimersByTime(100); + fake.AppState.transition('background'); + jest.advanceTimersByTime(900); + + expect(transitions).toEqual([ + { + state: 'background', + previousState: 'active', + timestamp: inactiveTimestamp, + }, + ]); + expect(lifecycle.getCurrentState()).toBe('background'); + lifecycle.dispose(); + }); + + test('discards a held transition during disposal', () => { + const { fake, lifecycle, transitions } = observeLifecycle(1_000); + + fake.AppState.transition('background'); + lifecycle.dispose(); + jest.advanceTimersByTime(1_000); + + expect(transitions).toEqual([]); + expect(lifecycle.getCurrentState()).toBeNull(); + expect(fake.AppState.removeCalls).toBe(1); + expect(jest.getTimerCount()).toBe(0); + }); + + test('hides a transient bounce from heartbeat and app-state plugins', () => { + const fake = createFakeLifecycle('active'); + const channel = createAutoLoggingChannel(); + const heartbeats: ALHeartbeatEventData[] = []; + const appStates: ALAppStateEventData[] = []; + channel.addListener('al_heartbeat_event', (event) => + heartbeats.push(event) + ); + channel.addListener('al_app_state_event', (event) => appStates.push(event)); + AutoLogging.init({ + channel, + plugins: [ + reactNativeAppLifecycle({ + ...fake, + transientInactiveMs: 1_000, + }), + reactNativeHeartbeat({ heartbeatInterval: 10_000 }), + reactNativeAppStateEvents(), + ], + }); + + fake.AppState.transition('background'); + jest.advanceTimersByTime(100); + fake.AppState.transition('active'); + jest.advanceTimersByTime(1_000); + + expect(heartbeats.map((event) => event.heartbeatType)).toEqual([ + ALHeartbeatType.START, + ]); + expect(appStates).toEqual([]); + expect(jest.getTimerCount()).toBe(1); + }); + test('shares one AppState subscription across heartbeat and app-state events', () => { const fake = createFakeLifecycle('active'); const channel = createAutoLoggingChannel(); @@ -254,6 +433,51 @@ describe('React Native lifecycle plugins', () => { act(() => mountedRenderer.unmount()); }); + test('does not rotate or extend sessions from scheduled heartbeats', () => { + const fake = createFakeLifecycle('active'); + const channel = createAutoLoggingChannel(); + const heartbeats: ALHeartbeatEventData[] = []; + const sessionIds: string[] = []; + let runtimeContext: ALReactNativeRuntimeContext | null = null; + channel.addListener('al_heartbeat_event', (event) => { + heartbeats.push(event); + if (runtimeContext != null) { + sessionIds.push(runtimeContext.session.getSessionId()); + } + }); + AutoLogging.init({ + channel, + plugins: [ + { + name: 'session-probe', + install(_channel, context) { + runtimeContext = context; + }, + }, + reactNativeAppLifecycle(fake), + reactNativeHeartbeat({ + heartbeatInterval: 30_000, + maxUserInactivityDuration: 120_000, + }), + ], + sessionTimeoutMs: 60_000, + }); + + jest.advanceTimersByTime(180_000); + + expect(heartbeats.map((event) => event.heartbeatType)).toEqual([ + ALHeartbeatType.START, + ALHeartbeatType.SCHEDULED, + ALHeartbeatType.SCHEDULED, + ALHeartbeatType.SCHEDULED, + ALHeartbeatType.SCHEDULED, + ]); + expect(heartbeats.map((event) => event.eventIndex)).toEqual([ + 0, 1, 2, 3, 4, + ]); + expect(new Set(sessionIds).size).toBe(1); + }); + test('keeps repeated initialization idempotent', () => { const first = createFakeLifecycle('active'); const second = createFakeLifecycle('active'); diff --git a/packages/hyperion-react-native/test/ALRuntime.test.ts b/packages/hyperion-react-native/test/ALRuntime.test.ts index 2d534441..93660eb4 100644 --- a/packages/hyperion-react-native/test/ALRuntime.test.ts +++ b/packages/hyperion-react-native/test/ALRuntime.test.ts @@ -7,12 +7,54 @@ 'use strict'; import { createAutoLoggingChannel } from 'hyperion-autologging/src/ALChannel'; -import type { ALReactNativePlugin } from '../src/ALRuntime'; +import { ALHeartbeatType } from 'hyperion-autologging/src/ALHeartbeatType'; +import { reactNativeAppLifecycle } from '../src/ALAppLifecycle'; +import { reactNativeHeartbeat } from '../src/ALHeartbeat'; +import type { + ALReactNativePlugin, + ALReactNativeRuntimeContext, +} from '../src/ALRuntime'; +import { + getAppInstanceId, + getSessionId, + getWebSessionId, +} from '../src/ALSessionPublic'; import type { ALReactNativeEventMap } from '../src/ALTypes'; import * as AutoLogging from '../src/AutoLogging'; +import type { ReactNativeAppState } from '../src/IReactNative'; + +function initializeSession( + sessionTimeoutMs?: number +): ALReactNativeRuntimeContext { + const channel = createAutoLoggingChannel(); + let capturedContext: ALReactNativeRuntimeContext | null = null; + AutoLogging.init({ + channel, + plugins: [ + { + name: 'session-probe', + install(_channel, context) { + capturedContext = context; + }, + }, + ], + sessionTimeoutMs, + }); + if (capturedContext == null) { + throw new Error('Expected the runtime context to be installed.'); + } + return capturedContext; +} describe('React Native plugin runtime', () => { - afterEach(() => AutoLogging.dispose()); + beforeEach(() => { + jest.useFakeTimers({ now: 1_700_000_000_000 }); + }); + + afterEach(() => { + AutoLogging.dispose(); + jest.useRealTimers(); + }); test('uses the application channel and starts only after every install', () => { const calls: string[] = []; @@ -49,10 +91,60 @@ describe('React Native plugin runtime', () => { expect(calls.slice(-2)).toEqual(['dispose:second', 'dispose:first']); }); + test('publishes session context before startup events', () => { + const subscriberErrors: unknown[] = []; + const channel = createAutoLoggingChannel((error) => + subscriberErrors.push(error) + ); + const AppState: ReactNativeAppState = { + currentState: 'active', + addEventListener: () => ({ remove: () => undefined }), + }; + const records: { + readonly appInstanceId: string; + readonly heartbeatType: ALHeartbeatType; + readonly initialized: boolean; + readonly sessionId: string; + readonly webSessionId: string; + }[] = []; + channel.addListener('al_heartbeat_event', (event) => { + records.push({ + appInstanceId: getAppInstanceId(), + heartbeatType: event.heartbeatType, + initialized: AutoLogging.isInitialized(), + sessionId: getSessionId(), + webSessionId: getWebSessionId(), + }); + }); + + expect( + AutoLogging.init({ + channel, + plugins: [ + reactNativeAppLifecycle({ AppState }), + reactNativeHeartbeat(), + ], + }) + ).toBe(true); + + expect(subscriberErrors).toEqual([]); + expect(records).toHaveLength(1); + expect(records[0]).toEqual({ + appInstanceId: expect.stringMatching(/^[0-9a-z]{6}$/), + heartbeatType: ALHeartbeatType.START, + initialized: false, + sessionId: expect.stringMatching(/^[0-9a-z]{6}$/), + webSessionId: expect.stringMatching( + /^[0-9a-z]{6}:[0-9a-z]{6}:[0-9a-z]{6}$/ + ), + }); + }); + test('rolls back failures and permits a corrected retry', () => { const channel = createAutoLoggingChannel(); const dispose = jest.fn(); const failure = new Error('installation failed'); + let failedSessionId: string | undefined; expect(() => AutoLogging.init({ @@ -61,7 +153,8 @@ describe('React Native plugin runtime', () => { { name: 'first', install: () => ({ dispose }) }, { name: 'failure', - install() { + install(_channel, context) { + failedSessionId = context.session.getSessionId(); throw failure; }, }, @@ -70,7 +163,11 @@ describe('React Native plugin runtime', () => { ).toThrow(failure); expect(dispose).toHaveBeenCalledTimes(1); expect(AutoLogging.isInitialized()).toBe(false); + expect(() => getSessionId()).toThrow( + 'React Native AutoLogging is not initialized.' + ); expect(AutoLogging.init({ channel, plugins: [] })).toBe(true); + expect(getSessionId()).not.toBe(failedSessionId); }); test('creates contiguous events through one runtime event factory', () => { @@ -114,4 +211,70 @@ describe('React Native plugin runtime', () => { expect(nestedResult).toBe(false); expect(AutoLogging.isInitialized()).toBe(true); }); + + test('keeps the default session timeout at thirty minutes', () => { + const context = initializeSession(); + const start = Date.now(); + const initialSessionId = context.session.getSessionId(); + + jest.setSystemTime(start + 29 * 60_000); + expect(context.session.getSessionId()).toBe(initialSessionId); + jest.setSystemTime(start + 31 * 60_000); + context.session.recordActivity(); + expect(context.session.getSessionId()).not.toBe(initialSessionId); + }); + + test('rotates a custom-timeout session only on activity', () => { + const context = initializeSession(60_000); + const start = Date.now(); + const initialSessionId = context.session.getSessionId(); + + expect( + context.eventFactory.createEvent({ eventTimestamp: start }).eventIndex + ).toBe(0); + context.session.recordActivity(start + 59_000); + expect(context.session.getSessionId()).toBe(initialSessionId); + expect( + context.eventFactory.createEvent({ eventTimestamp: start + 120_001 }) + .eventIndex + ).toBe(1); + expect(context.session.getSessionId()).toBe(initialSessionId); + + context.session.recordActivity(start + 120_001); + expect(context.session.getSessionId()).not.toBe(initialSessionId); + expect( + context.eventFactory.createEvent({ eventTimestamp: start + 120_001 }) + .eventIndex + ).toBe(2); + }); + + test('keeps non-activity events in the current session at the timeout boundary', () => { + const context = initializeSession(60_000); + const start = Date.now(); + const initialSessionId = context.session.getSessionId(); + + const boundaryEvent = context.eventFactory.createEvent({ + eventTimestamp: start + 60_000, + }); + jest.setSystemTime(start + 60_001); + + expect(boundaryEvent.eventIndex).toBe(0); + expect(context.session.getSessionId()).toBe(initialSessionId); + expect(context.eventFactory.createEvent().eventIndex).toBe(1); + }); + + test.each([0, -1, Number.NaN])( + 'uses the default session timeout for invalid value %s', + (sessionTimeoutMs) => { + const context = initializeSession(sessionTimeoutMs); + const start = Date.now(); + const initialSessionId = context.session.getSessionId(); + + context.session.recordActivity(start + 29 * 60_000); + expect(context.session.getSessionId()).toBe(initialSessionId); + context.session.recordActivity(start + 60 * 60_000); + expect(context.session.getSessionId()).not.toBe(initialSessionId); + AutoLogging.dispose(); + } + ); }); diff --git a/packages/hyperion-react-native/test/ALScreenSession.test.ts b/packages/hyperion-react-native/test/ALScreenSession.test.ts index 717ab8dc..ca0995b1 100644 --- a/packages/hyperion-react-native/test/ALScreenSession.test.ts +++ b/packages/hyperion-react-native/test/ALScreenSession.test.ts @@ -7,7 +7,10 @@ 'use strict'; import { createAutoLoggingChannel } from 'hyperion-autologging/src/ALChannel'; -import type { ALReactNativePlugin } from '../src/ALRuntime'; +import type { + ALReactNativePlugin, + ALReactNativeRuntimeContext, +} from '../src/ALRuntime'; import { getCurrentScreen, reactNativeScreens, @@ -87,7 +90,45 @@ describe('React Native session and screen state', () => { ); }); - test('resets contiguous indexes when the in-memory session expires', () => { + test('starts a new session before publishing a screen transition after inactivity', () => { + const channel = createAutoLoggingChannel(); + const events: ALScreenTransitionEventData[] = []; + const publishedSessionIds: string[] = []; + let runtimeContext: ALReactNativeRuntimeContext | null = null; + channel.addListener('al_screen_transition_event', (event) => { + events.push(event); + if (runtimeContext != null) { + publishedSessionIds.push(runtimeContext.session.getSessionId()); + } + }); + AutoLogging.init({ + channel, + plugins: [ + { + name: 'session-probe', + install(_channel, context) { + runtimeContext = context; + }, + }, + reactNativeScreens(), + ], + sessionTimeoutMs: 60_000, + }); + if (runtimeContext == null) { + throw new Error('Expected the runtime context to be installed.'); + } + const initialSessionId = runtimeContext.session.getSessionId(); + + jest.advanceTimersByTime(61_000); + expect(setCurrentScreen('After inactivity')).toBe(true); + + expect(events).toHaveLength(1); + expect(events[0].eventIndex).toBe(0); + expect(publishedSessionIds).toHaveLength(1); + expect(publishedSessionIds[0]).not.toBe(initialSessionId); + }); + + test('keeps contiguous indexes when the in-memory session expires', () => { const channel = createAutoLoggingChannel(); const indexes: number[] = []; const timestamps = [ @@ -96,7 +137,8 @@ describe('React Native session and screen state', () => { const plugin: ALReactNativePlugin = { name: 'session-probe', install(_channel, context) { - for (const eventTimestamp of timestamps) { + for (const [index, eventTimestamp] of timestamps.entries()) { + if (index === 2) context.session.recordActivity(eventTimestamp); indexes.push( context.eventFactory.createEvent({ eventTimestamp }).eventIndex ); @@ -105,7 +147,7 @@ describe('React Native session and screen state', () => { }; AutoLogging.init({ channel, plugins: [plugin] }); - expect(indexes).toEqual([0, 1, 0]); + expect(indexes).toEqual([0, 1, 2]); }); test('allows later plugins to publish a screen during managed startup', () => { diff --git a/packages/hyperion-react-native/test/ALSurface.test.ts b/packages/hyperion-react-native/test/ALSurface.test.ts index 2f0c18ab..e62b2373 100644 --- a/packages/hyperion-react-native/test/ALSurface.test.ts +++ b/packages/hyperion-react-native/test/ALSurface.test.ts @@ -16,6 +16,12 @@ import { useSurface, type ALSurfaceDataNode, } from '../src/ALSurface'; +import { + ALSurfaceDataNode as SurfaceDataNode, + registerSurfaceData, + unregisterSurfaceData, +} from '../src/ALSurfaceData'; +import type { ALReactNativeRuntimeContext } from '../src/ALRuntime'; import type { ALReactNativeEventMap, ALSurfaceMutationEventData, @@ -152,6 +158,66 @@ describe('React Native surfaces plugin', () => { } }); + test('links lifecycle events across a session rotation without reusing indexes', async () => { + const channel = createAutoLoggingChannel(); + const events: ALSurfaceMutationEventData[] = []; + const publishedSessionIds: string[] = []; + let runtimeContext: ALReactNativeRuntimeContext | null = null; + channel.addListener('al_surface_mutation_event', (event) => { + events.push(event); + if (runtimeContext != null) { + publishedSessionIds.push(runtimeContext.session.getSessionId()); + } + }); + AutoLogging.init({ + channel, + plugins: [ + { + name: 'session-probe', + install(_channel, context) { + runtimeContext = context; + }, + }, + reactNativeSurfaces(), + ], + sessionTimeoutMs: 60_000, + }); + + let renderer: TestRenderer.ReactTestRenderer | undefined; + await act(async () => { + renderer = TestRenderer.create( + React.createElement(ALSurface, { name: 'cross-session' }, 'content') + ); + await Promise.resolve(); + }); + if (runtimeContext == null || renderer == null) { + throw new Error('Expected the runtime and surface to be installed.'); + } + const mountSessionId = runtimeContext.session.getSessionId(); + runtimeContext.session.recordActivity(Date.now() + 61_000); + expect(runtimeContext.session.getSessionId()).not.toBe(mountSessionId); + + await act(async () => { + renderer?.unmount(); + await Promise.resolve(); + }); + + expect(events).toHaveLength(2); + expect(events[0]).toEqual( + expect.objectContaining({ event: 'mount_component', eventIndex: 0 }) + ); + expect(events[1]).toEqual( + expect.objectContaining({ + event: 'unmount_component', + eventIndex: 1, + relatedEventIndex: events[0].eventIndex, + }) + ); + expect(new Set(events.map((event) => event.eventIndex)).size).toBe(2); + expect(publishedSessionIds).toHaveLength(2); + expect(publishedSessionIds[0]).not.toBe(publishedSessionIds[1]); + }); + test('keeps hierarchy available while mutation publishing is disabled', async () => { const channel = createAutoLoggingChannel(); const listener = jest.fn(); @@ -227,4 +293,50 @@ describe('React Native surfaces plugin', () => { }); consoleError.mockRestore(); }); + + test('keeps a replacement registered when the stale surface unmounts', () => { + const consoleError = jest + .spyOn(console, 'error') + .mockImplementation(() => undefined); + const parent = ALSurfaceData.root; + const createSurface = ( + name: string, + path: string, + surfaceParent: typeof parent | SurfaceDataNode = parent + ) => { + return new SurfaceDataNode({ + name, + path, + interactivePath: path, + depth: + surfaceParent instanceof SurfaceDataNode + ? surfaceParent.depth + 1 + : 1, + parent: surfaceParent, + nonInteractive: false, + metadata: {}, + interactiveMetadata: {}, + uiEventMetadata: {}, + }); + }; + const stale = createSurface('home', 'home'); + const replacement = createSurface('home', 'home'); + + registerSurfaceData(stale); + registerSurfaceData(replacement); + unregisterSurfaceData(stale); + + expect(parent.getChild('home')).toBe(replacement); + expect(ALSurfaceData.get('home')).toBe(replacement); + + const child = createSurface('details', 'home/details', replacement); + registerSurfaceData(child); + expect(replacement.getChild('details')).toBe(child); + expect(ALSurfaceData.get('home/details')).toBe(child); + expect(consoleError).toHaveBeenCalledTimes(1); + expect(consoleError).toHaveBeenCalledWith( + 'Duplicate AutoLogging surface name "home" under "root".' + ); + consoleError.mockRestore(); + }); }); diff --git a/packages/hyperion-react-native/test/ALUIEvents.test.ts b/packages/hyperion-react-native/test/ALUIEvents.test.ts index 81ff11fe..8ae9ae60 100644 --- a/packages/hyperion-react-native/test/ALUIEvents.test.ts +++ b/packages/hyperion-react-native/test/ALUIEvents.test.ts @@ -8,6 +8,7 @@ import React, { Suspense } from 'react'; import TestRenderer, { act } from 'react-test-renderer'; import { createAutoLoggingChannel } from 'hyperion-autologging/src/ALChannel'; import * as AutoLogging from '../src/AutoLogging'; +import type { ALReactNativeRuntimeContext } from '../src/ALRuntime'; import { reactNativeSurfaces, ALSurface } from '../src/ALSurface'; import { reactNativeUIEvents } from '../src/ALUIEvents'; import type { ALReactNativeEventMap, ALUIEventData } from '../src/ALTypes'; @@ -132,6 +133,56 @@ describe('React Native automatic UI event plugin', () => { act(() => renderer.unmount()); }); + test('starts a new session before publishing the first interaction after inactivity', () => { + jest.useFakeTimers({ now: 1_700_000_000_000 }); + const channel = createAutoLoggingChannel(); + const events: ALUIEventData[] = []; + const publishedSessionIds: string[] = []; + let runtimeContext: ALReactNativeRuntimeContext | null = null; + channel.addListener('al_ui_event', (event) => { + events.push(event); + if (runtimeContext != null) { + publishedSessionIds.push(runtimeContext.session.getSessionId()); + } + }); + AutoLogging.init({ + channel, + plugins: [ + { + name: 'session-probe', + install(_channel, context) { + runtimeContext = context; + }, + }, + reactNativeUIEvents(), + ], + sessionTimeoutMs: 60_000, + }); + if (runtimeContext == null) { + throw new Error('Expected the runtime context to be installed.'); + } + const initialSessionId = runtimeContext.session.getSessionId(); + const applicationHandler = jest.fn(); + const renderer = mount( + jsx(InstrumentedControl, { + accessibilityLabel: 'Resume activity', + onPress: applicationHandler, + }) + ); + + jest.advanceTimersByTime(61_000); + renderer.root + .findByType('instrumented-control') + .props.onPress(createNativeEvent()); + + expect(applicationHandler).toHaveBeenCalledTimes(1); + expect(events).toHaveLength(1); + expect(events[0].eventIndex).toBe(0); + expect(publishedSessionIds).toHaveLength(1); + expect(publishedSessionIds[0]).not.toBe(initialSessionId); + act(() => renderer.unmount()); + }); + test('logs a native interaction once when parent and child forward the same handler', () => { const channel = createAutoLoggingChannel(); const events: ALUIEventData[] = [];