> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch38-monitoring-and-troubleshooting/38.2-presence-tracking.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 38.2 Presence Tracking

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~260k tokens, Output \~5k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In a multi-device environment, users need to know which devices are connected and what their status is. OpenClaw's **System Presence** mechanism records information about all connected devices and synchronizes it in real-time to all clients.

## 38.2.1 Presence Data Structure

Each online device corresponds to a `SystemPresence` record (`src/infra/system-presence.ts`):

```typescript
export type SystemPresence = {
  host?: string;              // Hostname
  ip?: string;                // IP address
  version?: string;           // OpenClaw version
  platform?: string;          // Platform info (e.g., "macos 15.2")
  deviceFamily?: string;      // Device family (Mac / Linux / Windows)
  modelIdentifier?: string;   // Hardware model (e.g., "Mac16,10")
  lastInputSeconds?: number;  // Last input time (seconds ago)
  mode?: string;              // Running mode (gateway / node / cli)
  reason?: string;            // Connection reason (self / heartbeat / connect)
  deviceId?: string;          // Device unique identifier
  roles?: string[];           // Role list (operator / node)
  scopes?: string[];          // Permission scopes
  instanceId?: string;        // Instance UUID
  text: string;               // Human-readable summary text
  ts: number;                 // Last update timestamp
};
```

### Self Presence Initialization

When the Gateway starts, it immediately calls `initSelfPresence()` to register itself:

```typescript
function initSelfPresence() {
  const host = os.hostname();
  const ip = resolvePrimaryIPv4();     // Prefer en0/eth0, fallback to other interfaces
  const version = process.env.OPENCLAW_VERSION ?? "unknown";
  const modelIdentifier = (() => {
    if (os.platform() === "darwin") {
      return spawnSync("sysctl", ["-n", "hw.model"]).stdout.trim();
    }
    return os.arch();
  })();
  // Register to Presence Map
  entries.set(host.toLowerCase(), {
    host, ip, version, platform, deviceFamily, modelIdentifier,
    mode: "gateway", reason: "self",
    text: `Gateway: ${host} (${ip}) · app ${version} · mode gateway · reason self`,
    ts: Date.now(),
  });
}
```

Note the use of synchronous `spawnSync("sysctl", ...)` here—this is because `initSelfPresence()` is executed during module loading (top-level call), at which point asynchronous APIs would add unnecessary complexity. Moreover, `sysctl` execution typically takes less than 1 millisecond.

## 38.2.2 Presence Storage and Expiration

Presence data is stored in a module-level `Map<string, SystemPresence>`:

```typescript
const entries = new Map<string, SystemPresence>();
const TTL_MS = 5 * 60 * 1000;  // 5 minute expiration
const MAX_ENTRIES = 200;         // Maximum 200 records
```

`listSystemPresence()` performs two cleanup operations before returning data:

1. **TTL expiration cleanup**: Delete records that haven't been updated for more than 5 minutes
2. **Capacity limit**: If the number of records exceeds 200, sort by timestamp and delete the oldest records (LRU strategy)

```typescript
export function listSystemPresence(): SystemPresence[] {
  ensureSelfPresence();
  const now = Date.now();
  // Remove expired records
  for (const [k, v] of entries) {
    if (now - v.ts > TTL_MS) entries.delete(k);
  }
  // LRU eviction
  if (entries.size > MAX_ENTRIES) {
    const sorted = [...entries.entries()].toSorted((a, b) => a[1].ts - b[1].ts);
    const toDrop = entries.size - MAX_ENTRIES;
    for (let i = 0; i < toDrop; i++) entries.delete(sorted[i][0]);
  }
  touchSelfPresence();   // Refresh self timestamp
  return [...entries.values()].toSorted((a, b) => b.ts - a.ts);
}
```

> **Sidebar**: LRU (Least Recently Used) is a cache eviction strategy. When the cache is full, it prioritizes evicting the data that has not been accessed for the longest time. The Presence Map here is essentially an LRU cache—when capacity is exceeded, it deletes records with the smallest `ts` (least recently updated).

## 38.2.3 Presence Update

When a client (CLI, macOS application, iOS/Android node) connects or sends a heartbeat, the Gateway calls `updateSystemPresence()` to update Presence:

```typescript
export function updateSystemPresence(payload: SystemPresencePayload): SystemPresenceUpdate {
  ensureSelfPresence();
  const parsed = parsePresence(payload.text);
  // Key selection priority: deviceId > instanceId > host > ip > text prefix
  const key = normalizePresenceKey(payload.deviceId)
    || normalizePresenceKey(payload.instanceId)
    || normalizePresenceKey(parsed.host)
    || parsed.ip
    || parsed.text.slice(0, 64);
  
  const existing = entries.get(key) ?? {};
  const merged = {
    ...existing,
    ...parsed,
    host: payload.host ?? parsed.host ?? existing.host,
    // ... merge logic for other fields
    roles: mergeStringList(existing.roles, payload.roles),
    ts: Date.now(),
  };
  entries.set(key, merged);
  
  // Return change summary
  return { key, previous: existing, next: merged, changes, changedKeys };
}
```

The merge strategy follows a "new value first" principle: `payload` (latest client data) > `parsed` (data parsed from text) > `existing` (existing record). Role and scope lists use set merging (`mergeStringList`) to avoid duplicates.

### Text Parsing

The Presence data sent by clients contains a human-readable `text` field with the format:

```
Node: myhost (192.168.1.10) · app 1.2.3 · last input 42s ago · mode node · reason heartbeat
```

`parsePresence()` uses regular expressions to extract structured fields from this text, which is a compatibility design—even if the client only sends the `text` field without structured data, the Gateway can parse out key information.

## 38.2.4 Presence Version and Broadcast

Presence changes trigger version number increment and real-time broadcast:

```typescript
let presenceVersion = 1;

export function incrementPresenceVersion(): number {
  presenceVersion += 1;
  return presenceVersion;
}
```

The Gateway broadcasts Presence updates at the following times:

1. **When a new client connects**
2. **When a client disconnects**
3. **When a heartbeat updates**
4. **When a device is paired/unpaired**

After receiving a Presence update, clients (such as the Web console) can display the online device list in real-time, typing indicators, and other UI elements.

## 38.2.5 Typing Indicators

> **Sidebar**: Typing indicators are a common feature in instant messaging—when the other party is typing a message, it displays a "typing..." prompt. In OpenClaw, the meaning of typing indicators is broader: it not only includes the user typing, but also the Agent "thinking" (calling the LLM API) and outputting streaming responses.

OpenClaw's typing indicators are implemented through the Presence system. When the Agent starts processing a user message, the Gateway broadcasts a `mode` change to all clients:

```
mode: "idle"     → Idle
mode: "thinking" → AI is thinking
mode: "writing"  → Streaming output
mode: "tool"     → Executing tool call
```

The Web console and native clients listen to these mode changes to display corresponding UI states (such as three-dot animation, progress indicators, etc.).

***

## Section Summary

1. **SystemPresence** records detailed information about each connected device: hostname, IP, platform, hardware model, running mode, version, etc. The Gateway automatically registers itself when it starts.
2. **TTL + LRU** dual mechanism controls the lifecycle of Presence data: automatic cleanup after 5 minutes of expiration, eviction of the oldest records when exceeding 200 entries.
3. **Presence update** uses a "new value first" merge strategy, with Key selection supporting multi-level fallback of deviceId, instanceId, and host, ensuring that records for the same device are not duplicated.
4. **Version number broadcast** allows clients to perceive Presence changes with minimal overhead—only need to compare a single integer to determine whether to fetch the latest data.
5. **Typing indicators** are implemented based on the `mode` field of Presence, covering four states: idle/thinking/writing/tool.
