> 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/ch18-streaming-and-block-replies/18.4-telegram-draft-streaming.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 18.4 Telegram Draft Streaming

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

***

In the previous sections, we discussed the generic streaming architecture and block splitting algorithm. However, these mechanisms ultimately need to be implemented in specific channels—the "real-time typing" effect users see on Telegram is implemented by a subsystem called **Telegram Draft Streaming**.

Telegram Bot API doesn't natively support "update message while generating" functionality. OpenClaw leverages the `sendMessageDraft` API endpoint to simulate real-time typing by continuously sending "drafts." This section will analyze the implementation of this mechanism in detail, as well as the two different update strategies: partial mode and block mode.

***

## 18.4.1 Implementation of `sendMessageDraft`

### Core Abstraction of Draft Streaming

The core of Telegram draft streaming is the `createTelegramDraftStream` factory function, located in `src/telegram/draft-stream.ts`. It accepts a set of parameters and returns a `TelegramDraftStream` object that exposes only three methods:

```typescript
// src/telegram/draft-stream.ts
export type TelegramDraftStream = {
  update: (text: string) => void;   // Update draft content
  flush: () => Promise<void>;       // Force flush buffer
  stop: () => void;                 // Stop draft stream
};
```

This is a typical **minimal interface design**—callers only need to care about three operations without understanding throttling, conflict detection, length limits, and other internal details.

### Key Constants and Parameters

The factory function solidifies the following parameters when creating:

| Parameter    | Default    | Description                                                       |
| ------------ | ---------- | ----------------------------------------------------------------- |
| `maxChars`   | 4096       | Telegram message length limit                                     |
| `throttleMs` | 300ms      | Send throttle interval (minimum 50ms)                             |
| `draftId`    | Message ID | Associated original message identifier, positive non-zero integer |
| `chatId`     | —          | Target conversation ID                                            |

```typescript
// src/telegram/draft-stream.ts
const TELEGRAM_DRAFT_MAX_CHARS = 4096;
const DEFAULT_THROTTLE_MS = 300;

const maxChars = Math.min(params.maxChars ?? TELEGRAM_DRAFT_MAX_CHARS, TELEGRAM_DRAFT_MAX_CHARS);
const throttleMs = Math.max(50, params.throttleMs ?? DEFAULT_THROTTLE_MS);
const rawDraftId = Number.isFinite(params.draftId) ? Math.trunc(params.draftId) : 1;
const draftId = rawDraftId === 0 ? 1 : Math.abs(rawDraftId);
```

Note the defensive handling of `draftId`: truncate to integer, ensure non-zero, take absolute value. This is because Telegram API has strict format requirements for draft IDs.

### Internal State Machine

The draft stream internally maintains 5 state variables, forming an implicit **finite state machine**:

```
┌──────────────────────────────────────────┐
│            Draft Stream State            │
├──────────────────────────────────────────┤
│  lastSentText  : string  = ""           │  ← For deduplication: last actually sent text
│  lastSentAt    : number  = 0            │  ← For throttling: timestamp of last send
│  pendingText   : string  = ""           │  ← For buffering: latest text waiting to send
│  inFlight      : boolean = false        │  ← For mutual exclusion: whether request is in progress
│  stopped       : boolean = false        │  ← For termination: whether stopped
└──────────────────────────────────────────┘
```

> **Sidebar: Finite State Machine (FSM)**
>
> A finite state machine is a mathematical model that describes system behavior using a finite number of states and transitions between them. Here, although there's no explicit `enum State { ... }`, the combination of these boolean and string variables implicitly defines all possible states the draft stream can be in. For example, when `stopped=true`, any `update()` call is a no-op; when `inFlight=true`, a new `flush()` only schedules the next send rather than executing immediately.

### Send Logic: `sendDraft`

The internal `sendDraft` function is responsible for actual API calls:

```typescript
// src/telegram/draft-stream.ts (simplified)
const sendDraft = async (text: string) => {
  if (stopped) return;
  const trimmed = text.trimEnd();
  if (!trimmed) return;

  // Oversized → stop permanently—don't send truncated or failure version
  if (trimmed.length > maxChars) {
    stopped = true;
    params.warn?.(`draft length ${trimmed.length} > ${maxChars}`);
    return;
  }

  // Deduplication: same as last send → skip
  if (trimmed === lastSentText) return;

  lastSentText = trimmed;
  lastSentAt = Date.now();
  try {
    await params.api.sendMessageDraft(chatId, draftId, trimmed, threadParams);
  } catch (err) {
    stopped = true;  // API failure → stop permanently, no retry
    params.warn?.(`draft stream failed: ${err instanceof Error ? err.message : String(err)}`);
  }
};
```

There are two noteworthy design decisions here:

1. **Oversized → Stop**: When text exceeds 4096 characters, we don't attempt to truncate and send, but stop the entire draft stream. This is because truncation might break Markdown structure (like unclosed code blocks), resulting in worse user experience than "no update."
2. **Failure → Stop**: API call failure also stops permanently without retry. This avoids continuously generating failed requests when network is unstable. The final reply still reaches via the normal message sending channel; draft streaming is just a bonus preview feature.

### Throttle Scheduling: `update` and `schedule`

The `update` method is the most frequently called entry point:

```typescript
// src/telegram/draft-stream.ts (simplified)
const update = (text: string) => {
  if (stopped) return;
  pendingText = text;    // Always overwrite, keep only latest

  if (inFlight) {        // Request in flight, queue up
    schedule();
    return;
  }
  if (!timer && Date.now() - lastSentAt >= throttleMs) {
    void flush();        // Throttle window passed, send immediately
    return;
  }
  schedule();            // Otherwise schedule delayed send
};

const schedule = () => {
  if (timer) return;     // Already scheduled, don't duplicate
  const delay = Math.max(0, throttleMs - (Date.now() - lastSentAt));
  timer = setTimeout(() => { void flush(); }, delay);
};
```

The key design here is **"overwrite buffering"**: `pendingText` is always overwritten with the latest text, not appended. This means if 10 `update` calls arrive within a 300ms throttle window, only the last one's text is sent. This is exactly the correct semantics for draft streaming—users only need to see the latest typing progress.

The scheduling flow can be summarized in the diagram:

```
update("Hello")
    │
    ▼
pendingText = "Hello"
    │
    ├─ inFlight? ──────yes──→ schedule() → wait for current request
    │                                       │
    │                                       ▼
    │                                   flush() → sendDraft()
    │
    ├─ Throttle window passed? ──yes──→ flush() → sendDraft("Hello")
    │
    └─ Otherwise ──────────────→ schedule()
                                   │
                                   ▼
                               setTimeout(flush, delay)
                                   │
                                   ▼
                               flush() → sendDraft("Hello")
```

### Flush and Concurrency Protection: `flush`

The `flush` method is the core executor of throttle scheduling:

```typescript
// src/telegram/draft-stream.ts (simplified)
const flush = async () => {
  if (timer) { clearTimeout(timer); timer = undefined; }

  if (inFlight) {        // Prevent concurrent sends
    schedule();          // Defer to next round
    return;
  }

  const text = pendingText;
  const trimmed = text.trim();
  if (!trimmed) {
    pendingText = "";
    if (pendingText) schedule();  // Race condition check
    return;
  }

  pendingText = "";
  inFlight = true;
  try {
    await sendDraft(text);
  } finally {
    inFlight = false;
  }

  if (pendingText) schedule();   // New data arrived during send
};
```

The `inFlight` flag acts as a **single-element mutex**: at most one `sendDraft` executes at any time. If `flush` is called when a request is in flight, it doesn't block waiting, but schedules the next round. This ensures:

* No parallel API calls competing
* No blocking via `await` causing caller to hang
* Automatic handling of accumulated updates after request completes

***

## 18.4.2 partial Mode vs block Mode

Draft streaming has two update strategies: **partial mode** and **block mode**. They correspond to different text sources and update methods.

### Mode Selection

In `bot-message-dispatch.ts`, the mode is determined by the `streamMode` configuration:

```typescript
// src/telegram/bot-message-dispatch.ts (simplified)
const draftStream = canStreamDraft
  ? createTelegramDraftStream({ api: bot.api, chatId, draftId: msg.message_id, ... })
  : undefined;

// block mode requires creating an additional BlockChunker
const draftChunking = draftStream && streamMode === "block"
  ? resolveTelegramDraftStreamingChunking(cfg, route.accountId)
  : undefined;
const draftChunker = draftChunking ? new EmbeddedBlockChunker(draftChunking) : undefined;
```

The differences between modes can be summarized in the table:

| Feature          | partial Mode                                           | block Mode                                        |
| ---------------- | ------------------------------------------------------ | ------------------------------------------------- |
| Text source      | `onPartialReply` callback (streaming incremental text) | `onPartialReply` callback + BlockChunker chunking |
| Update method    | Direct replacement of entire draft                     | Incremental append, segmented via BlockChunker    |
| Update frequency | After each token output                                | By paragraph/code block boundary                  |
| User experience  | Character-by-character appearance, like "typewriter"   | Paragraph-by-paragraph appearance, cleaner        |
| Use case         | Short conversations, immediate feedback                | Long text generation, structured output           |

### partial Mode Data Flow

In partial mode, the data flow is very direct:

```typescript
// src/telegram/bot-message-dispatch.ts (simplified)
const updateDraftFromPartial = (text?: string) => {
  if (!draftStream || !text) return;
  if (text === lastPartialText) return;

  if (streamMode === "partial") {
    lastPartialText = text;
    draftStream.update(text);      // Update draft directly with complete text
    return;
  }
  // ...block mode logic below...
};
```

In partial mode, each time `onPartialReply` callback is received:

1. Complete generated text is passed directly to `draftStream.update()`
2. Draft stream internally throttles and sends to Telegram API
3. Users see text grow character-by-character in the conversation

Data flow diagram:

```
Model output delta
    │
    ▼
handleMessageUpdate
    │ Concatenate to deltaBuffer
    ▼
stripBlockTags + parseReplyDirectives
    │ Cleaned complete text
    ▼
onPartialReply({ text })
    │
    ▼
updateDraftFromPartial(text)
    │ streamMode === "partial"
    ▼
draftStream.update(text)
    │ Throttle (300ms)
    ▼
sendMessageDraft(chatId, draftId, text)
    │
    ▼
User sees real-time preview in Telegram
```

### block Mode Data Flow

Block mode is more complex—it inserts an independent `EmbeddedBlockChunker` before the draft stream (note this is a **different instance** from the blockChunker at the subscribe layer):

```typescript
// src/telegram/bot-message-dispatch.ts (simplified)
const updateDraftFromPartial = (text?: string) => {
  if (!draftStream || !text) return;
  if (text === lastPartialText) return;

  // block mode
  let delta = text;
  if (text.startsWith(lastPartialText)) {
    delta = text.slice(lastPartialText.length);  // Extract delta
  } else {
    // Non-monotonic stream (stream buffer reset), start over
    draftChunker?.reset();
    draftText = "";
  }
  lastPartialText = text;
  if (!delta) return;

  if (!draftChunker) {
    // No chunker → degrade to partial mode
    draftText = text;
    draftStream.update(draftText);
    return;
  }

  // Feed delta to chunker, output by paragraph boundary
  draftChunker.append(delta);
  draftChunker.drain({
    force: false,
    emit: (chunk) => {
      draftText += chunk;
      draftStream.update(draftText);
    },
  });
};
```

The core difference in block mode is:

1. **Delta Extraction**: Calculate delta from complete text (if text grows monotonically, just take the difference)
2. **BlockChunker Buffering**: Delta enters chunker first, only released when paragraph boundary is encountered
3. **Draft Append**: Released chunks are appended to `draftText`, then draft is updated

This means users in block mode don't see character-by-character appearance, but see text "pop out" paragraph by paragraph—cleaner and better for long text.

### Non-Monotonic Stream Handling

Note the special handling for "non-monotonic streams" in the code:

```typescript
if (text.startsWith(lastPartialText)) {
  delta = text.slice(lastPartialText.length);
} else {
  // Non-monotonic: reset state
  draftChunker?.reset();
  draftText = "";
}
```

> **Sidebar: Monotonic Stream**
>
> In streaming systems, if each frame of data is a "prefix extension" of the previous frame (i.e., new text is old text plus an increment), we call this stream monotonic. OpenClaw's model output is typically monotonic—each `text_delta` appends to existing text. But monotonicity can be broken in some cases:
>
> * After context compaction retry, model regenerates
> * Anomalous behavior from certain model providers
>
> When non-monotonicity is detected, all incremental state must be reset and draft reconstruction starts from scratch.

### Draft Stream Lifecycle

The lifecycle of draft stream throughout the reply handling process is as follows:

```
User sends message
    │
    ▼
canStreamDraft? ──no──→ Don't use draft stream
    │ yes
    ▼
createTelegramDraftStream()
    │
    ▼
┌─────────────────────────────┐
│  Streaming generation phase │
│  onPartialReply → update()  │  ← Called repeatedly
│  onPartialReply → update()  │
│  ...                        │
└─────────────────────────────┘
    │
    ▼
Final reply ready to send
    │
    ▼
flushDraft()                     ← Flush remaining buffer
    │
    ▼
draftStream.stop()               ← Stop draft stream
    │
    ▼
deliverReplies()                 ← Send formal messages
```

Note that **draft streaming is only enabled in private chats**:

```typescript
const canStreamDraft =
  streamMode !== "off" &&
  isPrivateChat &&                    // Private chat only
  typeof draftThreadId === "number" &&
  (await resolveBotTopicsEnabled(primaryCtx));
```

This is because draft updates in group chats might generate excessive notification noise, affecting other users. Additionally, when draft is enabled, block streaming at the subscribe layer is **disabled** (`disableBlockStreaming = true`) to avoid conflicts between the two streaming mechanisms:

```typescript
const disableBlockStreaming =
  Boolean(draftStream) ||    // If draft stream exists, disable block streaming
  (typeof telegramCfg.blockStreaming === "boolean" ? !telegramCfg.blockStreaming : undefined);
```

***

## Section Summary

1. **Telegram draft streaming** implements "real-time typing" effect via `sendMessageDraft` API, a channel-specific layer independent of the generic streaming architecture.
2. **Core design** uses overwrite buffering + time throttling + single-element mutex, ensuring API calls are neither too frequent nor concurrent.
3. **Oversized → Stop, Failure → Stop** strategy prioritizes system stability—drafts are just previews, final replies reach via normal channel.
4. **partial mode** passes complete text directly to draft stream, suitable for "typewriter" effect in short conversations.
5. **block mode** inserts independent BlockChunker before draft stream, updates draft by paragraph boundary, suitable for structured output in long text.
6. Draft streaming is only enabled in **private chats** and automatically **disables** block streaming at subscribe layer to avoid conflicts between the two mechanisms.
