Session Caching Mechanism with 2s TTL and Auto Re‑attach in Ego‑Lite
Ego‑Lite caches Chrome DevTools Protocol (CDP) sessions for exactly 2 seconds to eliminate connection overhead and automatically re‑attaches to the browser when sessions terminate, ensuring seamless automation without manual reconnection logic.
The citrolabs/ego-lite browser runtime implements an intelligent session management layer that balances performance with reliability. By maintaining a 2‑second TTL cache for CDP sessions and providing automatic re‑attachment capabilities, the framework eliminates the latency of repeated session creation while gracefully handling browser crashes or unexpected disconnections.
How the 2‑Second Session Cache Works
The caching mechanism operates transparently behind high‑level helpers, storing active CDP sessions in memory with strict time‑based invalidation.
Cache Lookup and Reuse
When automation code requests a browser interaction, the runtime invokes the ensureSession helper defined in src/browser-runtime.ts. This utility first checks the internal cache for an existing session younger than 2 seconds. If a fresh session exists, it is reused immediately, bypassing the expensive CDP handshake and target attachment process. This optimization is critical for sequential operations like navigation chains or element interactions that occur within rapid succession.
TTL Expiry and Invalidation
After 2 seconds, the cached entry is automatically considered stale. Any subsequent call to ensureSession detects the expired TTL and discards the old session, triggering the creation of a new CDP connection. This short window prevents resource exhaustion from dangling sessions while maintaining performance for typical multi‑step automation workflows that complete within the time window.
Automatic Re‑attachment on Connection Loss
When the underlying browser tab crashes, closes, or the CDP connection drops, the runtime executes a transparent recovery sequence without throwing errors to the calling script.
Detection and Recovery Flow
The runtime monitors connection health through event listeners registered in src/browser-runtime.ts. Upon detecting a disconnection, the system emits a sessionLost event managed by the global mutable state in src/state.ts. Immediately following detection, ensureSession creates a new CDP session, updates the cache, and resumes the pending operation. This re‑attachment flow ensures that navigation commands in src/driver/nav.ts always execute against a valid session, even if the original browser context disappeared mid‑command.
Implementation Architecture
The session caching system spans three core modules:
-
src/browser-runtime.ts– Contains theensureSessionhelper that encapsulates the 2‑second TTL cache logic and automatic re‑attachment flow. This file manages the core CDP transport layer and handles session lifecycle transitions. -
src/state.ts– Stores the active session reference and event emitters. This global state module tracks the timestamp of the last cached session and broadcastssessionLostevents when connectivity issues arise. -
src/driver/nav.ts– The navigation driver that relies on the session cache for all page transitions. Every navigation call implicitly invokesensureSession, guaranteeing that commands execute against valid, non‑expired connections.
Practical Usage Examples
These patterns demonstrate how the caching and re‑attachment mechanisms operate in practice.
Automatic Session Handling
High‑level helpers automatically manage the cache lifecycle. No explicit session handling is required for standard operations:
// navigate and click helpers internally call ensureSession
await navigate('https://example.com');
await click('@5'); // Cached session reused if within 2s TTL
Bypassing the Cache
To force a fresh CDP session regardless of cache state, use the forceNew parameter:
import { ensureSession } from 'ego-browser';
// Creates new session even if cached session is still valid
await ensureSession({ forceNew: true });
Manual Re‑attachment Handling
For debugging or custom recovery logic, listen to session loss events and manually trigger re‑attachment:
import { state } from 'ego-browser';
state.on('sessionLost', async () => {
console.log('Session lost – re‑attaching...');
await ensureSession(); // Re‑creates and caches fresh session
});
Summary
- 2‑second TTL cache in
src/browser-runtime.tseliminates redundant CDP session creation overhead for rapid sequential operations. - Automatic re‑attachment detects connection loss via event listeners and transparently recreates sessions without interrupting automation flows.
ensureSessionserves as the central gateway for session acquisition, handling both cache validation and recovery logic.- Global state management in
src/state.tstracks session health and emitssessionLostevents for recovery hooks. - Zero configuration required – navigation and interaction helpers in
src/driver/nav.tsandsrc/helpers.tsleverage caching automatically.
Frequently Asked Questions
What triggers the 2s TTL countdown in Ego‑Lite?
The countdown begins when a new CDP session is created and cached in src/browser-runtime.ts. Each call to ensureSession checks the timestamp of the cached entry; if more than 2 seconds have elapsed, the entry is discarded and a new session is negotiated.
How does Ego‑Lite detect a lost CDP session?
The runtime monitors the CDP transport layer for disconnected or crashed events. When detected, it emits a sessionLost event through the global state module in src/state.ts, triggering the automatic re‑attachment sequence in ensureSession.
Can I disable automatic re‑attachment?
There is no configuration flag to disable re‑attachment, as it is fundamental to the runtime's reliability guarantees. However, you can intercept the recovery process by listening to the sessionLost event and implementing custom logic before or instead of the automatic re‑attachment.
Where is the session state stored between operations?
Active session references and timestamps are stored in the global mutable runtime state defined in src/state.ts. This state persists for the duration of the Node.js process, allowing ensureSession to retrieve cached connections across multiple helper invocations.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →