> 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/ch20-core-channel-implementations/20.6-source-deep-dive-three-connections-two-streaming-modes.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 20.6 Source Deep Dive: Three Connection Models, Two Streaming Modes

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

***

§20.1–20.5 covered each core channel individually. This section compares them horizontally: **how three fundamentally different connection models each stay alive**, and **what separates the two "generate as you send" strategies**.

## 20.6.1 Three Platforms, Three Fates

### Telegram = HTTP long polling

grammY plus `@grammyjs/runner`. `TelegramPollingSession` (`src/telegram/polling-session.ts:34`) wraps the getUpdates loop in a **self-healing state machine with exponential backoff (2s→30s, factor 1.8, 25% jitter)**.

Three details show real craft:

**A watchdog: no getUpdates for 90 seconds forces a restart**

```ts
// src/telegram/polling-session.ts:201
const watchdog = setInterval(() => {
  if (this.opts.abortSignal?.aborted) return;
  const elapsed = Date.now() - lastGetUpdatesAt;
  if (elapsed > POLL_STALL_THRESHOLD_MS && runner.isRunning()) {
    stalledRestart = true;
    this.opts.log(`[telegram] Polling stall detected (no getUpdates for ${...}); forcing restart.`);
    void stopRunner();
  }
}, POLL_WATCHDOG_INTERVAL_MS);
```

**How `lastGetUpdatesAt` is sampled is the clever part**: instead of adding a separate heartbeat, it attaches a **transformer middleware** to grammY's API client and stamps the timestamp whenever a `getUpdates` call passes through (`:167-172`).

> **The probe parasitizes normal traffic at zero cost.**
>
> A general technique: **the most reliable signal that a loop is alive is the traffic the loop itself generates, not a separate heartbeat.** A separate heartbeat can be alive while the business loop is dead.

**409 conflict self-healing**

Two instances polling simultaneously triggers Telegram's 409. The code treats it as "there may be a leftover webhook," resets the `#webhookCleared` flag, and **calls `deleteWebhook` before polling on the next round** (`:236-239`).

Meanwhile `bot.ts:109-112`'s comment explains why fetch is wrapped to inject an abort signal: **if an in-flight getUpdates isn't cut off at shutdown, it hangs for 30 seconds and the next instance immediately hits a 409.**

Read together they tell one story: a problem of *shutdown not being clean* manifests at the next startup as a completely unrelated error code.

**Offset persistence**

`updateOffset.lastUpdateId` is written to disk so restarts don't reconsume; after reconnecting it first calls `getUpdates({offset: last+1, limit: 1})` to confirm the offset (`:151-161`).

### Discord = WebSocket Gateway

@buape/carbon. **Connection management is the thinnest of the three**:

`waitForDiscordGatewayStop` (`src/discord/monitor.gateway.ts:20`) only attaches to the gateway's error event and the abort signal; **reconnection is left to the underlying library**. A `shouldStopOnError` hook decides which errors (invalid token, missing intent) warrant stopping entirely.

> Compared with Telegram's pile of keepalive code, Discord does almost nothing here. **Not because Discord is simpler, but because its SDK already handles reconnection.**
>
> A practical rule: **before integrating a platform, find out what the SDK already does for you.** Adding a layer where the SDK already acts usually just manufactures races.

### WhatsApp = Baileys impersonating a client

**The most fragile of the three** — credentials expire and sessions get kicked.

`src/web/reconnect.ts:12` defines a backoff similar to Telegram's but with a `maxAttempts: 12` ceiling, paired with a 60-second heartbeat (`DEFAULT_HEARTBEAT_SECONDS`). **When reconnection fails it marks the state offline and waits for a human to scan a QR code.**

Having a ceiling is right: a WhatsApp disconnect usually means the session is invalid, and **infinite retrying is both useless and potentially risk-flagged**.

The inbound side additionally has the `monitor-inbox` family handling media path capture and allowFrom filtering.

### One shared layer: inbound debounce

Every channel shares `src/channels/inbound-debounce-policy.ts` plus per-channel implementations (§14.5.1).

Telegram additionally sets a longer merge window for **forward bursts** (`bot-handlers.ts:229-233`) — forwarding often splits text and media into adjacent updates, and the default window would cut them apart.

## 20.6.2 Two Streaming Modes: block vs. draft

The two are easy to confuse, so start by separating them:

|                      | **block streaming**                                                      | **draft streaming**                                                          |
| -------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------- |
| Form                 | Output is sent as **separate messages**, one natural paragraph at a time | Send **one** preview message and **edit it in place** as generation proceeds |
| Platform requirement | None                                                                     | **A cheap message-edit API**                                                 |
| Supported channels   | Most                                                                     | **Only Telegram and Discord**                                                |
| Feel                 | Like several messages in a row                                           | Like someone typing                                                          |

### block streaming's coalescing parameters

A channel declares support via the `blockStreaming: true` capability and controls granularity with coalescing parameters — the dock's `blockStreamingCoalesceDefaults`:

| Channel                  | minChars | idleMs |
| ------------------------ | -------- | ------ |
| Discord / Slack / Signal | 1500     | 1000   |
| IRC                      | 300      | 1000   |

(`dock.ts:93-95, 368-370`)

**Blocks below minChars accumulate; after idleMs of silence they're sent together.**

IRC's 300 is noticeably smaller — because its per-message limit is only 350 characters, so accumulating to 1500 would require splitting into five messages anyway.

### draft streaming's shared throttling core

Telegram and Discord each have their own implementation, but they **share one throttling core**, `createDraftStreamLoop` (`src/channels/draft-stream-loop.ts:10`):

```ts
// src/channels/draft-stream-loop.ts:20 (excerpt)
const flush = async () => {
  while (!params.isStopped()) {
    if (inFlightPromise) { await inFlightPromise; continue; }  // single-flight
    const text = pendingText;                                   // take only the latest snapshot
    if (!text.trim()) { pendingText = ""; return; }
    pendingText = "";
    const current = params.sendOrEditStreamMessage(text).finally(...);
    inFlightPromise = current;
    const sent = await current;
    if (sent === false) { pendingText = text; return; }          // roll back on failure
    lastSentAt = Date.now();
    if (!pendingText) return;
  }
};
```

Under a hundred lines, doing three things:

| Mechanism                                       | Effect                                                                     |
| ----------------------------------------------- | -------------------------------------------------------------------------- |
| **Single-flight promise**                       | Only one edit in flight at a time, or the platform rate-limits or reorders |
| **Pending text keeps only the latest snapshot** | A classic last-write-wins coalescer, naturally resistant to edit storms    |
| **Periodic flush on `throttleMs`**              | Controls edit frequency                                                    |

On failure `pendingText = text` rolls back, and the next flush retries.

Layered on top, `createFinalizableDraftLifecycle` (`src/channels/draft-stream-controls.ts:118`) unifies lifecycle semantics:

```
stop         final flush
clear        delete the preview message
stopForClear wait for in-flight requests to land, then delete
```

**Each channel only has to implement two primitives: `sendOrEditStreamMessage` and `deleteMessage`.**

> This is the draft streaming described in §44.5.3. Recall the key point there: **"latest snapshot rather than delta" is the crucial choice** — shipping state over an unreliable channel is far more robust with snapshots than with deltas.

## 20.6.3 How the Two Channels Diverge on the Same Core

This part best illustrates how platform differences seep into implementations.

### Discord's version: straightforward

`src/discord/draft-stream.ts`:

* POST creates the first message and records its id; everything after is a PATCH edit;
* **Exceeding the 2000-character hard limit stops streaming** (`:53-58`), leaving the final reply to normal chunking;
* `minInitialChars` accumulates before sending the first message — the reason is in the comment: **the first screen of a push notification shouldn't be half a sentence**;
* Throttle: 1200 ms.

That `minInitialChars` rationale is very practical: Discord pushes the beginning of a new message to the phone's notification bar. If the first edit contains only "I", the user gets a one-character notification.

### Telegram's version: an order of magnitude more complex

`src/telegram/draft-stream.ts` supports **dual transports**:

```ts
// src/telegram/draft-stream.ts:109-124
const prefersDraftTransport =
  requestedPreviewTransport === "draft" ? true
  : requestedPreviewTransport === "message" ? false
  : params.thread?.scope === "dm";           // default to the draft transport in DMs
const resolvedDraftApi = prefersDraftTransport
  ? resolveSendMessageDraftApi(params.api) : undefined;
```

`sendMessageDraft` is a newer Bot API capability that renders streaming text **into the draft area above the recipient's input box** without producing a real message.

On clients and chat types that don't support it, the code **falls back automatically to `sendMessage` + `editMessageText`** by matching an **error-message regex** (`DRAFT_METHOD_UNAVAILABLE_RE`).

> Using an error-message regex for capability detection isn't elegant, but with no capability-query endpoint in the Bot API it's the only workable approach. **Note that it degrades in a safe direction** — a failed probe falls back to the old method, so functionality is never lost.

That brings a set of unique lifecycle actions:

| Action                   | Purpose                                                                                                           |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------- |
| `materialize()` (`:381`) | On finalize, **promote the draft into a real message** and clear the draft area                                   |
| `forceNewMessage()`      | Handle "segment rotation" (finalize the previous segment, start the next as a new message)                        |
| `onSupersededPreview`    | Absorb the race where "the send response arrives late and this side has already moved to a new generation"        |
| `sendMayHaveLanded()`    | Mark the **grey state** of "sent, but unknown whether it succeeded" for the layer above to decide about resending |

**`sendMayHaveLanded` deserves its own note.**

When a network request times out, you don't know whether the server received it. A binary state (success/failure) can't express that — reporting success may lose the message, reporting failure may duplicate it.

Introducing a third state hands the decision to the layer that understands the context better.

> **In distributed systems, "I don't know" is a state that must be modeled.** Collapsing it into success or failure means making a guess on someone else's behalf.

The 4096-character hard limit likewise stops streaming (`:271-279`).

### Throttle parameter choices

| Channel  | Throttle                |
| -------- | ----------------------- |
| Telegram | 1000 ms                 |
| Discord  | 1200 ms                 |
| Floor    | 250 ms across the board |

**More headroom than most platforms' edit rate limits — better a slightly chunky preview than a 429.**

## 20.6.4 Cross-Channel Comparison

| Channel                  | Form                         | Connection                    | chatTypes                   | Chunk limit | Streaming                                         | Notable capabilities                                                |
| ------------------------ | ---------------------------- | ----------------------------- | --------------------------- | ----------- | ------------------------------------------------- | ------------------------------------------------------------------- |
| **Telegram**             | Built-in (609-line shell)    | Bot API long polling (grammY) | direct/group/channel/thread | 4000        | **draft stream, dual transport** + blockStreaming | Native commands, forum topics, inline buttons                       |
| **Discord**              | Built-in (639-line shell)    | WS Gateway (Carbon)           | direct/channel/thread       | **2000**    | draft stream (edit) + coalesce 1500/1000          | polls, threads, PluralKit, component UI                             |
| **WhatsApp**             | Built-in (496-line shell)    | Baileys web protocol + QR     | direct/group                | 4000        | **Final reply only** (no edit streaming)          | polls, reactions, self-chat default                                 |
| **Slack**                | Built-in (497-line shell)    | Socket Mode (Bolt)            | direct/channel/thread       | 4000        | coalesce 1500/1000                                | Native commands, per-account thread replyToMode                     |
| **Signal**               | Built-in (346-line shell)    | signal-cli REST               | direct/group                | 4000        | coalesce 1500/1000                                | E164-normalized allowlist                                           |
| **iMessage** (legacy)    | Built-in (341-line shell)    | imsg CLI (macOS)              | direct/group                | 4000        | —                                                 | Superseded by BlueBubbles                                           |
| **IRC**                  | Built-in                     | IRC socket                    | direct/group                | **350**     | blockStreaming, coalesce 300/1000                 | Case-insensitive channel allowlist                                  |
| **Google Chat**          | Built-in                     | HTTP webhook                  | direct/group/thread         | 4000        | blockStreaming                                    | Workspace app                                                       |
| **LINE**                 | Built-in                     | Messaging API webhook         | direct/group                | **5000**    | blockStreaming                                    | Flex templates, rich menu                                           |
| **BlueBubbles**          | Plugin (7,101 lines)         | BlueBubbles server REST       | direct/group                | —           | —                                                 | **edit/unsend/effects/group admin — the widest capability surface** |
| **Matrix**               | Plugin (7,558 lines)         | Matrix protocol               | direct/group/thread         | —           | —                                                 | polls, E2E rooms                                                    |
| **Mattermost**           | Plugin (7,524 lines)         | Bot API + WS                  | direct/channel/group/thread | 4000        | coalesce 1500/1000                                | Native slash command callback routing                               |
| **MS Teams**             | Plugin (7,879 lines)         | Bot Framework                 | direct/channel/thread       | —           | —                                                 | polls, enterprise compliance                                        |
| **Feishu**               | Plugin (12,286 lines)        | WS long connection            | direct/channel              | —           | —                                                 | Card messages, edit                                                 |
| **Nostr**                | Plugin (3,446 lines)         | NIP-04 relays                 | **direct only**             | —           | —                                                 | Decentralized DMs (MVP, no media)                                   |
| **Twitch**               | Plugin (3,130 lines)         | IRC connection                | **group only**              | —           | —                                                 | Live-chat shaped                                                    |
| **Zalo / Zalo personal** | Plugin (2,665 / 4,842 lines) | Bot API / QR login            | direct/group                | 2000        | blockStreaming                                    | Dual forms for the Vietnamese market                                |

### Three horizontal observations

**1. `chatTypes` is the first variable in capability negotiation.**

Twitch has only group, Nostr only direct, Discord has no group (GroupDM is a separate switch). **The shared layer uses this to trim session key shapes and policy surfaces** — DM-related config is meaningless for a group-only channel.

**2. draft stream exists only on Telegram and Discord.**

**The barrier isn't the framework, it's the platform** — you need a cheap message-edit API. Other channels use blockStreaming (separate messages) or send only the final reply.

**3. Capability ceilings are often set by third-party bridges.**

In the iMessage ecosystem, the official CLI bridge can only send and receive; **the BlueBubbles server unlocks edit/unsend/effects** — which is why the docs mark it as the recommended path.

> Practically useful for integrators: **when an official API is limited, a community bridge's capability surface may far exceed it.** Don't judge a platform's integrability from official documentation alone.

## 20.6.5 Two Rough Edges

**1. draft stream stops dead at the limit.**

Past 4096 / 2000 characters, Telegram and Discord **simply stop updating the preview** and wait for the final chunked reply.

The user sees typing "freeze" mid-sentence — a perceptual discontinuity.

> A smoother approach (a scrolling preview window, or materialize + rotate on reaching the limit) **already has its foundation in Telegram's `forceNewMessage`**; it just hasn't been wired to the over-limit case. A road built but not yet opened.

**2. Group policy semantics drift across channels.**

The same `groupPolicy` setting constrains **different dimensions** depending on the channel:

| Channel  | `groupPolicy` applies to           |
| -------- | ---------------------------------- |
| Discord  | guild + channel allowlist          |
| WhatsApp | **senders** within a group         |
| IRC      | Case-insensitive **channel names** |

The docs explain it, but it **remains a frequent source of misconfiguration** (already in §45.2).

The root cause is that the platforms' organizational structures genuinely differ — Discord has three levels (server/channel/thread), WhatsApp has only groups. Covering both with one config key necessarily compromises somewhere.

***

## Section Summary

1. **Telegram (long polling) has the thickest keepalive**: exponential backoff (2s→30s + 25% jitter) + a **90-second watchdog** (the probe **parasitizes normal getUpdates traffic** via transformer middleware rather than a separate heartbeat) + 409 self-healing (deleteWebhook first) + offset persistence.
2. **Discord (WS) has the thinnest connection management** — reconnection is the SDK's job. **Find out what the SDK already does before integrating**; adding a layer where it already acts manufactures races.
3. **WhatsApp (Baileys) is the most fragile**, with a `maxAttempts: 12` backoff ceiling — a disconnect usually means an invalid session, so **infinite retrying is both useless and potentially risk-flagged**.
4. **block vs. draft streaming**: the former sends separate messages (coalesced by minChars/idleMs; IRC uses 300 because of its 350-character limit); the latter edits one in place (**the barrier is whether the platform has a cheap edit API** — only Telegram and Discord).
5. **`createDraftStreamLoop` implements single-flight + latest snapshot + throttling in under a hundred lines**; each channel implements only `sendOrEditStreamMessage` and `deleteMessage`.
6. **Telegram's dual transport** (`sendMessageDraft` draft area / message editing) falls back via error regex; its unique `materialize` / `forceNewMessage` / `onSupersededPreview` / **`sendMayHaveLanded`** — **"I don't know" is a third state that must be modeled in distributed systems**.
7. **Throttles keep headroom** (Telegram 1000 ms, Discord 1200 ms, 250 ms floor) — better a chunky preview than a 429.
8. **Three horizontal observations**: `chatTypes` is the first capability-negotiation variable; draft streaming's barrier is the platform not the framework; **capability ceilings are often set by third-party bridges** (BlueBubbles unlocks edit/unsend/effects beyond the official iMessage CLI).
9. **Two rough edges**: draft stream stopping at the limit creates a perceptual discontinuity (`forceNewMessage` is the unused foundation for fixing it), and **`groupPolicy` constrains different dimensions on different channels**, driving frequent misconfiguration.
