> 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/ch13-session-management/13.6-source-deep-dive-two-tier-lanes-and-queue-semantics.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 13.6 Source Deep Dive: Two-Tier Lanes and Three Queueing Semantics

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~272,000 tokens, Output \~14,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

This is the most worthwhile stretch of source in the book.

OpenClaw faces concurrency on two levels:

* **Across sessions**: many chats arriving at once — parallelism is allowed, but there must be a master valve;
* **Within a session**: consecutive messages from one chat must be strictly serial, or the transcript corrupts and tools trample each other.

And "serial" isn't enough — users interject while the agent is working, and *wait your turn* is often not what they meant.

## 13.6.1 The Foundation: Lane-Based In-Process FIFO

`src/process/command-queue.ts` is the **only execution queue in the system**. Pure Promises, no external dependencies.

The structure is simple: one FIFO per lane plus a concurrency cap (`:43-50`), and a `pump` loop that pulls tasks whenever active count is below `maxConcurrent` (`:92-144`).

Default concurrency:

| Lane         | Cap |
| ------------ | --- |
| default lane | 1   |
| `main`       | 4   |
| `subagent`   | 8   |

Agent runs enqueue in a **nested pair**:

```ts
// src/agents/pi-embedded-runner/run.ts:258-275 (excerpt)
const sessionLane = resolveSessionLane(params.sessionKey?.trim() || params.sessionId);
const globalLane = resolveGlobalLane(params.lane);
// ...
return enqueueSession(() =>
    enqueueGlobal(async () => {
      // the real model call and tool loop
    }),
);
```

Unpacked:

```
outer  session:<key> lane (concurrency 1)
        ↓ guarantees one run at a time per session
inner  global lane (main, concurrency 4)
        ↓ caps total concurrent model calls process-wide
      the actual model call
```

**The outer layer is the "session lock" — except it isn't a lock, it's a queue.**

That distinction matters: locks require thinking about fairness, timeouts, and deadlock; queues are naturally fair (FIFO), naturally observable (`getQueueSize` *is* your load metric), and naturally deadlock-free.

cron and subagents use their own lanes, so **background work never blocks human conversation**.

### A practical zombie-task defense

`resetAllLanes` (`:244-259`) uses a **generation counter** to handle SIGUSR1 hot restarts:

```
hot restart → generation++
   ↓
completion callbacks from old tasks are ignored on generation mismatch
queued-but-not-started tasks are preserved and still run
```

So after a restart, in-flight stragglers can't write results into the new state, while work still waiting in line isn't thrown away.

## 13.6.2 The Decision: What to Do When a Run Is Active

Lanes solve *queue and execute*, but there's a finer question at the experience level: **the previous message is still running — is this new one an interjection, a follow-up, or an interrupt?**

Queue mode decides. Resolution precedence (`src/auto-reply/reply/queue/settings.ts:39-44`):

```
inline /queue xxx  >  session-level persistent setting  >  channel config  >  global config  >  default collect
```

The adjudication happens at the top of `runReplyAgent` (`src/auto-reply/reply/agent-runner.ts:197-223`):

```ts
// src/auto-reply/reply/agent-runner.ts:197-223
if (shouldSteer && isStreaming) {
    const steered = queueEmbeddedPiMessage(followupRun.run.sessionId, followupRun.prompt);
    if (steered && !shouldFollowup) {
      await touchActiveSessionEntry();
      typing.cleanup();
      return undefined;      // steer succeeded; this turn ends here
    }
}
const activeRunQueueAction = resolveActiveRunQueueAction({
    isActive, isHeartbeat, shouldFollowup, queueMode: resolvedQueue.mode,
});
if (activeRunQueueAction === "drop") { ... }              // heartbeat hitting an active run: dropped
if (activeRunQueueAction === "enqueue-followup") {
    enqueueFollowupRun(queueKey, followupRun, resolvedQueue);
    // ...
    return undefined;
}
```

**The adjudicating function `resolveActiveRunQueueAction` (`queue-policy.ts:5-21`) is only 15 lines**, yet it's the fork point for all three semantics:

| Condition                       | Action                                      |
| ------------------------------- | ------------------------------------------- |
| No active run                   | Run immediately                             |
| Heartbeat hitting an active run | **Drop** — a heartbeat isn't worth queueing |
| steer / followup / collect      | Enter the followup queue                    |

### What happens when steer fails

`steer` has three rejection conditions (`src/agents/pi-embedded-runner/runs.ts:21-38`) — the run isn't in a streaming phase, compaction is in progress, and so on.

On failure it **falls back naturally to the followup path**, matching the documented promise. That's good degradation design: the user doesn't need to know why steering didn't take, and the message isn't lost.

### interrupt is handled earlier

`interrupt` (a legacy mode) is handled back at `get-reply-run.ts:447-451`: **clear the session lane outright and abort the current run**.

It's blunter than steer — steer says "let the current run know you said something new," interrupt says "throw the current run away."

## 13.6.3 The Followup Queue: collect Merging and Overflow Summaries

Followup queues are kept per session key (`FOLLOWUP_QUEUES`, `queue/state.ts:21`):

| Parameter       | Default     |
| --------------- | ----------- |
| debounce        | 1000 ms     |
| capacity        | 20          |
| overflow policy | `summarize` |

Enqueueing performs **three levels of deduplication** (`queue/enqueue.ts:51-96`): a global 5-minute message-ID cache, in-queue message IDs, and optionally identical prompts.

### The heart of collect mode

Draining happens in `scheduleFollowupDrain` (`queue/drain.ts:66-173`):

```ts
// src/auto-reply/reply/queue/drain.ts:104-129 (excerpt)
const items = queue.items.slice();
const summary = previewQueueSummaryPrompt({ state: queue, noun: "message" });
const run = items.at(-1)?.run ?? queue.lastRun;
// ...
const prompt = buildCollectPrompt({
    title: "[Queued messages while agent was busy]",
    items, summary,
    renderItem: (item, idx) => `---\nQueued #${idx + 1}\n${item.prompt}`.trim(),
});
await runFollowup({ prompt, run, enqueuedAt: Date.now(), ...routing });
queue.items.splice(0, items.length);
```

Four behaviors matter:

**1. Merge after debounce.** `waitForQueueDebounce` waits for one quiet second before acting — so "go on", "go on", "keep going" doesn't fire three runs. Then all backlog is stitched into one numbered prompt and **consumed in a single agent turn**.

Note the `run` parameter takes the **last** item's configuration (model, thinking level, etc.) — what the user said most recently represents their current intent.

**2. Cross-channel protection.**

If queued messages come from different channels or threads, **collect degrades to running them one at a time** (`hasCrossChannelItems`, `:86-99`).

The comment notes: **"once a drain has mixed channels, never collect again."**

The reason is that merging destroys the per-item return routing — three messages from Telegram, Discord, and Slack merged into one prompt: where does the single reply go?

**3. Overflow summaries: losing data is acceptable; losing awareness is not.**

At capacity, the `summarize` policy **doesn't just discard**. It collects the first line of each dropped message into `summaryLines`, then synthesizes a "these messages got squeezed out while you were busy" note so the model knows.

Worth remembering on its own: **when a system must drop data, it should at minimum tell downstream that something was dropped.** Silent loss leaves the model (and the user) reasoning on a false completeness assumption.

**4. Self-healing restart.**

Draining deletes the queue when empty. But if new messages arrived during the race window, `kickFollowupDrainIfIdle` (`:24-31`, `enqueue.ts:90-94`) restarts the drain using a cached callback.

That mechanism is the residue of fixing a "messages stuck in the queue with nobody servicing them" race.

### The followup execution path

`createFollowupRunner` (`followup-runner.ts:37-359`) **bypasses the inbound dispatcher**, going straight to `runWithModelFallback → runEmbeddedPiAgent`, and replies via `routeReply` back to the `originatingChannel` / `To` / `ThreadId` recorded at enqueue time.

One elegant scheduling detail: **when the main run finishes, `finalizeWithFollowup` (`agent-runner-helpers.ts:53-60`) calls `scheduleFollowupDrain` on the way out.**

In other words — **the main turn's completion&#x20;*****is*****&#x20;the starting gun for the followup queue. No separate scheduler needed.**

## 13.6.4 Six Queue Modes at a Glance

The default is `collect` (`queue/settings.ts:7-9`):

| Mode                 | With an active run                                                   | Underlying action                         | Typical use                                      |
| -------------------- | -------------------------------------------------------------------- | ----------------------------------------- | ------------------------------------------------ |
| `steer`              | Inject into the current run; falls back to followup if not streaming | `queueEmbeddedPiMessage`                  | "Wait — write it in Chinese"                     |
| `followup`           | Queue; run one at a time after the current run                       | `enqueueFollowupRun` → drain              | Adding tasks                                     |
| `collect`            | Queue; **merge into one turn** after debounce                        | `buildCollectPrompt`                      | Fragment bursts (**default**)                    |
| `steer-backlog`      | Steer first, **then also** keep a followup copy                      | Both                                      | Want immediate influence *and* a complete answer |
| `interrupt` (legacy) | Clear the lane + abort the current run                               | `clearCommandLane` + `abortEmbeddedPiRun` | Old "latest wins" behavior                       |
| `queue` (legacy)     | Same as `steer`                                                      | —                                         | Compatibility alias                              |

> **A known problem with `steer-backlog`** (§45.2): the same message both injects into the current run and triggers a followup, and the docs themselves admit it **"looks like a duplicate reply"** in streaming UIs. This kind of semantics **can only be constrained by documentation, not by the type system**, and the user-confusion cost isn't small.

## 13.6.5 The Typing Indicator: Where Three Execution Paths Converge

A UI detail that turns out to validate the whole concurrency model.

`createTypingController` (`get-reply.ts:117-124`) **starts at enqueue time** — the user immediately sees "typing…" even while the run is still waiting in a lane.

Stopping requires **both signals**:

```
markRunComplete    (model finished)
markDispatchIdle   (outbound chain drained)
        ↓ both received
      stop typing
```

How each path supplies them:

| Path          | How the signals arrive                                                                               |
| ------------- | ---------------------------------------------------------------------------------------------------- |
| Main path     | The dispatcher's onIdle callback (`reply-dispatcher.ts:222-227`)                                     |
| Followup path | **Bypasses the dispatcher**, so `followup-runner.ts:347-357`'s finally block **emits both manually** |
| Backstop      | `agent-runner.ts:713-723` keeps a "calling twice is harmless" guard                                  |

The comment on the followup path says it outright: without this, **Telegram's typing indicator spins until its TTL expires.**

> **This is the easiest extension trap in the module**: any new outbound path that bypasses the dispatcher must remember to close out typing itself. It's one of the "contract by discipline" reuse points from §45.2 — the type system can't help, only review can.

## 13.6.6 Session Storage: The Pipeline's Persistence Face

`src/sessions/` plus `src/config/sessions.ts` form the persistence layer that nearly every gate reads or writes.

### The session store (`sessions.json`, one directory per agent)

A dictionary of `SessionEntry` keyed by session key, holding:

* sessionId, transcript file path
* **Session-level overrides**: model, thinking level, verbose, queue mode
* Group activation state (`groupActivationNeedsSystemIntro`)
* Fallback notification state (§14.5.7)
* Cumulative token usage

`runReplyAgent` writes this turn's usage, model used, and system prompt report back on the way out via `persistRunSessionUsage` (`agent-runner.ts:468-479`).

### The transcript

`~/.openclaw/agents/<agentId>/sessions/<sessionId>.jsonl`, the complete conversation record, appended by the embedded runner while holding a write lock.

**The session lane's concurrency of 1 is the first line of defense for transcript integrity.**

### Session reset: new ID, same key

On `/new` or an unrecoverable error (compaction failure, role-ordering conflict), `resetSession` (`agent-runner.ts:261-331`):

```
generate a new sessionId + transcript path
clear systemSent, model overrides, and other run-scoped fields
the session key stays the same  ← the key point
```

**An unchanged session key means the routing layer notices nothing at all** — upstream doesn't need to know the session was reset. Old files are cleaned up on demand.

That's a clean layering: **routing knows keys, storage knows ids.**

### Input provenance

`InputProvenance` (`src/sessions/input-provenance.ts`) travels with `FollowupRun.run` all the way into the runner (`queue/types.ts:81`), tagging whether this input came from **a user, cron, or a system event** — used downstream for auditing and prompt layering.

### Three small modules that complete the semantics

| Module                 | Role                                                                                                                                                                                                     |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `send-policy.ts`       | The deny interception in §14.5.4 comes from `resolveSendPolicy`                                                                                                                                          |
| `transcript-events.ts` | Broadcasts transcript changes to the console UI (a 29-line thin event layer)                                                                                                                             |
| `session-key-utils.ts` | Key parsing and classification (`isCronSessionKey` / `isSubagentSessionKey` / `getSubagentDepth`, `:61-95`) — lane naming, heartbeat targeting, and subagent depth limits all depend on these predicates |

## 13.6.7 What This Design Costs

Listed in §45.2; here are the details.

**Everything is in process memory.** The followup queue, debounce buffers, and lane state all live in memory. **A process crash loses every queued message.**

What that buys is zero dependencies and zero operations. For a single-machine personal assistant it's the right trade, but horizontal scaling or high-reliability scenarios would need a rewrite.

**Hidden waiting in the two-tier lanes.** After queueing in a session lane you queue again in the global lane. In the extreme (main concurrency 4, dozens of active sessions) **wait times stack** — and the only visibility today is a "queued for …ms" line in verbose logs. **There's no "N people ahead of you" feedback for the user.**

**collect merging amplifies single-point failure.** Once 20 messages are merged into one prompt, a failed run (timeout, model error) fails **all 20 together**. The catch at `drain.ts:161-164` only logs and waits for the next enqueue to retry — **there is no split-and-replay mechanism**.

**The configuration cascade is deep.** Inline directive > session > channel > plugin default > global > hard-coded default, with separate cascades for queue and debounce. Flexible — but diagnosing "why didn't this message get merged?" means opening at least four files.

***

## Section Summary

1. **`src/process/command-queue.ts` is the system's only execution queue** — pure Promises, no external dependencies; `session lane(1) ⊂ global lane(N)` nested, with cron and subagents on separate lanes.
2. **The session lock isn't a lock, it's a queue** — naturally fair, naturally observable, naturally deadlock-free; `resetAllLanes` uses a generation counter to prevent zombie tasks after hot restarts.
3. **A 15-line `resolveActiveRunQueueAction` is the fork point for all three semantics**; steer failure falls back naturally to followup, and a heartbeat hitting an active run is dropped outright.
4. **Four key collect behaviors**: merge after debounce (config taken from the last item), **degrade to one-at-a-time across channels** (merging destroys return routing), **overflow `summarize`** (losing data is acceptable; losing awareness is not), and self-healing restart against a stuck-queue race.
5. **The main turn's completion is the starting gun for the followup queue** — no separate scheduler.
6. **The typing indicator requires both "model finished" and "outbound drained"**; the followup path bypasses the dispatcher and emits both manually — **any new dispatcher-bypassing outbound path must close out typing itself**, the module's easiest extension trap.
7. **Session reset uses a new ID and the same key**, so the routing layer notices nothing — routing knows keys, storage knows ids: clean layering.
8. **Four costs**: all state in memory (crash loses the queue), stacked two-tier wait with no user-visible feedback, collect merging amplifying single-point failure (no split replay), and a configuration cascade deep enough to make diagnosis painful.
