# How Ego-Lite Handles Session Invalidation and Reattachment

> Discover how ego-lite manages CDP session invalidation and reattachment with its ensureSession helper. It automatically detects stale sessions and re-attaches to browser targets.

- Repository: [CitroLabs/ego-lite](https://github.com/citrolabs/ego-lite)
- Tags: internals
- Published: 2026-08-24

---

**Ego-lite centralizes Chrome DevTools Protocol (CDP) session management in the `ensureSession()` helper, which automatically detects stale sessions, clears invalid `sessionId` values from state, and transparently re-attaches to the browser target whenever "Target closed" or "Session not found" errors occur.**

Ego-lite, an open-source browser automation framework from citrolabs/ego-lite, provides resilient automation by abstracting away the fragility of CDP connections. Understanding how ego-lite handles session invalidation and reattachment is critical for building reliable agent scripts that survive page navigations, tab closures, and unexpected browser disconnects.

## The Centralized Session Manager in browser-runtime.ts

The architecture revolves around the `ensureSession()` async function exported from [`package/ego-browser/src/browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/browser-runtime.ts). This utility serves as the single entry point for all CDP interactions, ensuring that no driver module ever operates with a stale session reference.

### Detecting Invalid Sessions

Every CDP message passes through `ensureSession()`. If the underlying `ego.sendCDPMessage` throws an exception indicating the session is no longer valid—such as **"Target closed"** or **"Session not found"**—the error propagates to the central handler. The helper inspects error signatures to distinguish between transient network failures and fundamental session invalidation.

### Automatic Re-attachment Logic

Upon detecting an invalid session, `ensureSession()` immediately **clears the stale `sessionId`** from the singleton store in [`src/state.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/state.ts), invokes `ego.attachSession()` to negotiate a fresh CDP connection with the current page target, and updates the cached reference. This process is transparent to calling code; the helper simply returns a valid session identifier, masking the recovery operation from higher-level drivers.

## Session Caching and TTL Strategy

When `ensureSession()` first creates a session, it stores the resulting `sessionId` in [`src/state.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/state.ts). To balance performance against reliability, the runtime maintains a short **TTL of 2 seconds**, allowing immediate reuse of valid sessions while preventing prolonged dependence on ephemeral connections. If a cached session exceeds this threshold or fails validation, the runtime discards it and initiates a fresh attachment.

## Uniform Retry Logic Across Driver Modules

The reattachment mechanism is not isolated to navigation operations. According to the ego-lite source code, every driver module relies on `ensureSession()`:

- **Navigation driver** ([`package/ego-browser/src/driver/nav.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/driver/nav.ts)): Re-attaches after page loads invalidate previous targets.
- **Observe driver** ([`package/ego-browser/src/driver/observe.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/driver/observe.ts)): Maintains DOM observation across session renewals.
- **Screencast driver** ([`package/ego-browser/src/driver/screencast.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/driver/screencast.ts)): Recovers streaming sessions without frame drops.

Because each driver invokes `ensureSession()` prior to transmitting CDP commands, the automatic retry logic applies uniformly across the entire API surface. When a session expires mid-script, the subsequent driver call triggers re-attachment and retries the original operation automatically.

## Practical Implementation Example

The following example demonstrates how ego-lite abstracts session management. Even if the CDP session becomes invalid between navigation and interaction, the script executes without manual intervention:

```javascript
// Agent script survives implicit session invalidation
await nav('https://example.com');        // Initial attachment
// ... session becomes invalid due to navigation ...
await click('button#submit');            // Automatic re-attachment occurs here

```

Behind the scenes, the runtime executes logic similar to this simplified TypeScript implementation from [`package/ego-browser/src/browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/browser-runtime.ts):

```typescript
export async function ensureSession(): Promise<string> {
  if (state.sessionId && stillValid(state.sessionId)) {
    return state.sessionId;               // Return cached session
  }
  // Clear invalid reference and re-attach
  state.sessionId = null;
  const fresh = await ego.attachSession();
  state.sessionId = fresh.sessionId;
  return fresh.sessionId;
}

```

## Summary

- **Centralized management**: All CDP interactions flow through `ensureSession()` in [`package/ego-browser/src/browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/browser-runtime.ts), eliminating duplicate session handling logic across drivers.
- **Automatic recovery**: The runtime catches "Target closed" and "Session not found" errors, immediately clearing stale `sessionId` values from [`src/state.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/state.ts) and re-attaching via `ego.attachSession()`.
- **Short TTL strategy**: A 2-second session cache minimizes attachment overhead while ensuring rapid detection of invalid connections.
- **Transparent operation**: Driver modules in [`src/driver/nav.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/driver/nav.ts), [`observe.ts`](https://github.com/citrolabs/ego-lite/blob/main/observe.ts), and [`screencast.ts`](https://github.com/citrolabs/ego-lite/blob/main/screencast.ts) inherit resilient session management without explicit error handling code.

## Frequently Asked Questions

### What triggers session invalidation in ego-lite?

CDP sessions become invalid when the attached browser target closes, navigates to a new page that destroys the previous execution context, or when the browser process terminates the DevTools connection. Ego-lite detects these conditions when `ego.sendCDPMessage` returns "Target closed" or "Session not found" errors inside `ensureSession()`.

### How long does ego-lite cache a CDP session before re-attaching?

According to the source code in [`package/ego-browser/src/browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/browser-runtime.ts), ego-lite maintains a **2-second TTL** (time-to-live) for cached sessions. This short duration ensures the runtime quickly detects stale connections while avoiding excessive re-attachment overhead during rapid successive calls.

### Do I need to handle session reattachment manually in my agent scripts?

No. The `ensureSession()` helper handles reattachment transparently. When you call high-level APIs like `nav()`, `click()`, or `snapshot()`, these functions internally invoke `ensureSession()`, which automatically re-attaches if the current session is invalid and retries the operation.

### Which driver modules benefit from automatic session reattachment?

All driver modules benefit uniformly. The navigation driver ([`package/ego-browser/src/driver/nav.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/driver/nav.ts)), observe driver ([`package/ego-browser/src/driver/observe.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/driver/observe.ts)), and screencast driver ([`package/ego-browser/src/driver/screencast.ts`](https://github.com/citrolabs/ego-lite/blob/main/package/ego-browser/src/driver/screencast.ts)) all invoke `ensureSession()` before transmitting CDP messages, ensuring consistent resilience across navigation, DOM observation, and screen recording operations.