Skip to content

Commit d5db073

Browse files
committed
0.2.10: hardening
1 parent a22c5a1 commit d5db073

24 files changed

Lines changed: 1874 additions & 335 deletions

AGENTS.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
- Keep comments and user-facing docs in English unless the surrounding file already follows another convention
5858
- Each project `.ts` file should start with a short multi-line responsibility header comment that explains the file boundary to future maintainers
5959
- Name extracted `/lib` modules and mirrored `/tests` suites by bare domain when the repository already supplies the Telegram scope; prefer `api.ts`, `queue.ts`, `updates.ts`, and `queue.test.ts` over redundant `telegram-*` filename prefixes
60-
- Prefer targeted edits, keeping `index.ts` as the orchestration layer and moving reusable logic into flat `/lib` domain modules when a subsystem becomes large enough to earn extraction; current extracted domains include queueing/runtime decisions, preview streaming, replies, polling, updates, attachments, registration and lifecycle-hook binding, Telegram API/config support, turn-building, media extraction, setup, rendering, status rendering, menu/model-resolution/UI support, and model-switch support
60+
- Prefer targeted edits, keeping `index.ts` as the orchestration layer and moving reusable logic into flat `/lib` domain modules when a subsystem becomes large enough to earn extraction; current extracted domains include queueing/runtime decisions, preview streaming, replies, polling, updates, attachments, registration and lifecycle-hook binding, Telegram API/config support, Telegram Bot API transport types, command parsing/action routing, turn-building, media extraction/media-group coalescing, setup, rendering, status rendering, menu/model-resolution/UI support, and model-switch support
6161
- Keep preview appearance logic in the rendering domain and preview transport/lifecycle logic in the preview domain so richer streaming strategies can evolve without entangling Telegram delivery state with Markdown formatting rules
6262

6363
## 7. Operational Conventions

CHANGELOG.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,17 @@
22

33
## Current
44

5+
- `[Turns]` Preserved existing attachment-path blocks and aborted-turn history context when a still-queued Telegram message is edited. Impact: caption edits no longer make queued prompts lose their downloaded file references or prior-message context.
6+
- `[Polling]` Persisted Telegram long-poll offsets only after each update is handled successfully. Impact: a handler failure no longer marks an unprocessed Telegram update as consumed, reducing the chance of silently dropping inbound messages.
7+
- `[Telegram API]` Added HTTP-status-aware Bot API response parsing, malformed-success handling, retry/backoff for 429 and 5xx Bot API responses, streaming Telegram downloads with size-limit checks, file-backed multipart upload blobs, partial-download cleanup on limit failures, startup cleanup for stale Telegram temp files, and UUID-based sanitized temp filenames. Impact: Telegram transport failures now report clearer status/description details, transient Telegram throttling/server failures get retried automatically, oversized inbound files are rejected before or during download, outbound multipart sends avoid preloading files into memory, partial and stale temp files are removed, and downloaded files are less prone to timestamp collisions or unsafe local names.
8+
- `[Rendering]` Escaped generated HTML attributes separately, sanitized code-fence language classes, and chunked raw HTML-mode output below Telegram length limits with balanced tag reopening across raw HTML chunks. Impact: generated Telegram HTML is harder to malformed through link or fence metadata and long raw-HTML replies no longer exceed Telegram's message size limit or break active tags across chunk boundaries.
9+
- `[Preview]` Serialized overlapping preview flushes through a single in-flight flush chain. Impact: rapid streaming updates no longer allow concurrent Telegram edit calls to overwrite newer preview text with stale snapshots.
10+
- `[Polling]` Added a bounded poisoned-update policy for repeatedly failing Telegram updates. Impact: one malformed or consistently failing update can no longer stall the long-poll loop forever; after the retry threshold, the bridge records and advances past it.
11+
- `[Menu]` Added short-lived model-menu input caching plus TTL/LRU cleanup for stored inline menu state. Impact: repeated `/status` and `/model` interactions do less settings/model-registry work, while old Telegram inline keyboards expire predictably instead of accumulating for the whole session.
12+
- `[Updates]` Routed Telegram `edited_message` updates separately from new messages and applied edits to matching queued turns. Impact: editing a still-queued Telegram message updates the pending prompt instead of enqueueing a duplicate turn.
13+
- `[Refactor]` Moved shared Telegram Bot API transport shapes out of `index.ts` into `lib/types.ts`. Impact: the entrypoint is smaller and future runtime extraction can reuse one type boundary instead of keeping local duplicate interfaces.
14+
- `[Refactor]` Moved Telegram media-group debounce and pending-group removal into the existing media domain with mirrored tests. Impact: album coalescing and reaction/delete cleanup are easier to validate without reading the full extension entrypoint, while avoiding an unnecessary extra domain file.
15+
- `[Refactor]` Extracted Telegram slash-command parsing and command-action routing into `lib/commands.ts` with mirrored tests, and moved queued-turn text replacement for edited messages into the turn domain. Impact: command normalization/execution planning and queued edit mutations are reusable, while the entrypoint keeps less local runtime state logic.
516
- `[Rendering]` Hardened link rendering so absolute links stay clickable, markdown-heavy link labels reduce to plain clickable labels, tooltip titles are ignored safely, balanced-parenthesis URLs stay intact, and unsupported link forms degrade without broken anchors. Impact: Telegram replies now keep more links usable while avoiding malformed output for relative, reference-style, or footnote-like link syntax.
617
- `[Preview]` Evolved rich streaming from first-chunk snapshots to stable-block previews with a conservative plain tail fallback, while preserving original blank-line spacing between rendered blocks and keeping headings visually separated from following blocks. Impact: closed top-level Markdown blocks now stream as rich Telegram HTML before finalization, incomplete fences, quotes, lists, and other trailing work remain readable without producing broken rich formatting, preview/final block spacing no longer collapses extra empty lines, and headings no longer visually merge into following code blocks when source Markdown omits a blank line.
718
- `[Refactor]` Split preview concerns so runtime transport and finalization live in the preview domain while preview snapshot derivation lives in the rendering domain. Impact: rich streaming can evolve independently from final reply delivery while keeping preview appearance decisions closer to the Telegram renderer.

README.md

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22

33
![pi-telegram screenshot](screenshot.png)
44

5-
Better Telegram DM bridge for pi.
6-
75
This repository is an actively maintained fork of [`badlogic/pi-telegram`](https://github.com/badlogic/pi-telegram). It started from upstream commit [`cb34008460b6c1ca036d92322f69d87f626be0fc`](https://github.com/badlogic/pi-telegram/commit/cb34008460b6c1ca036d92322f69d87f626be0fc) and has since diverged substantially.
86

97
## Start Here
@@ -90,30 +88,35 @@ Once paired, simply chat with your bot in Telegram. All text, images, and files
9088
- `👍` moves a waiting turn into the priority block. Removing `👍` sends it back to its normal queue position, and adding `👍` again gives it a fresh priority position.
9189
- `👎` removes a waiting turn from the queue. Telegram Bot API does not expose ordinary DM message-deletion events through the polling path used here, so queue removal is bound to the dislike reaction.
9290
- For media groups, a reaction on any message in the group applies to the whole queued turn.
93-
- Inbound images, albums, and files are downloaded to `~/.pi/agent/tmp/telegram`, local file paths are included in the prompt, and inbound images are forwarded to pi as image inputs.
91+
- If you edit a Telegram message while it is still waiting in the queue, the queued turn is updated instead of creating a duplicate prompt. Edits after a turn has already started may not affect the active run.
92+
- Inbound images, albums, and files are saved to `~/.pi/agent/tmp/telegram`, local file paths are included in the prompt, and inbound images are forwarded to pi as image inputs.
9493
- Queue reactions depend on Telegram delivering `message_reaction` updates for your bot and chat type.
9594

9695
### Requesting Files
9796

9897
If you ask pi for a file or generated artifact (e.g., _"generate a shell script and attach it"_), pi will call the `telegram_attach` tool, and the extension will send the file alongside its next Telegram reply.
9998

100-
Examples:
101-
102-
- `summarize this image`
103-
- `generate a shell script and attach it`
104-
10599
## Streaming
106100

107101
The extension streams assistant previews back to Telegram while pi is generating.
108102

109103
Rich previews are sent through editable messages because Telegram drafts are text-only. Closed top-level Markdown blocks can appear with formatting before the answer finishes, while the still-growing tail remains conservative and readable until the preview is replaced with the fully rendered Telegram HTML reply.
110104

105+
## Status bar
106+
107+
The pi status bar shows queued Telegram turns as compact previews, for example:
108+
109+
```text
110+
+3: [⬆ write a shell script…, summarize this image…, 📎 2 attachments]
111+
```
112+
111113
## Notes
112114

113115
- Only one pi session should be connected to the bot at a time
114116
- Replies are sent as normal Telegram messages, not quote-replies
115-
- Long replies are split below Telegram's 4096 character limit
117+
- Long replies are split below Telegram's 4096 character limit without intentionally breaking Telegram HTML formatting
116118
- Outbound files are sent via `telegram_attach`
119+
- Temporary inbound Telegram files are cleaned up on later session starts
117120

118121
## License
119122

docs/architecture.md

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,16 @@ Naming rule: because the repository already scopes this codebase to Telegram, ex
1919

2020
Current runtime areas include:
2121

22-
- Telegram API types and local bridge state in `index.ts`
22+
- Telegram Bot API transport shape types in `/lib/types.ts`, with local bridge state still composed in `index.ts`
2323
- Queueing and queue-runtime helpers in `/lib/queue.ts`
2424
- Preview transport-selection, preview-finalization, and preview-runtime helpers in `/lib/preview.ts`
2525
- Reply-transport and rendered-message delivery helpers in `/lib/replies.ts`
2626
- Preview appearance and snapshot derivation stay in `/lib/rendering.ts`, while `/lib/preview.ts` owns transport and lifecycle decisions, so richer preview strategies can evolve without entangling Markdown formatting with Telegram delivery state
2727
- Polling request, stop-condition, and long-poll loop helpers in `/lib/polling.ts`
2828
- Telegram API/config helpers and lazy bot-token client wrappers in `/lib/api.ts`
2929
- Telegram turn-building helpers in `/lib/turns.ts`
30-
- Telegram media/text extraction helpers in `/lib/media.ts`
30+
- Telegram media/text extraction, file-info normalization, and media-group debounce helpers in `/lib/media.ts`
31+
- Telegram slash-command parsing and command-action routing helpers in `/lib/commands.ts`
3132
- Telegram updates extraction, authorization, flow, execution-planning, direct execute-from-update routing, and runtime helpers in `/lib/updates.ts`
3233
- Telegram attachment queueing and delivery helpers in `/lib/attachments.ts`
3334
- Telegram tool, command, and lifecycle-hook registration helpers in `/lib/registration.ts`
@@ -55,11 +56,13 @@ Because `ctx.ui.input()` only exposes placeholder text, the bridge uses `ctx.ui.
5556
### Inbound Path
5657

5758
1. Telegram updates are polled through `getUpdates`
58-
2. The bridge filters to the paired private user
59-
3. Media groups are coalesced into a single Telegram turn when needed
60-
4. Files are downloaded into `~/.pi/agent/tmp/telegram`
61-
5. A `PendingTelegramTurn` is created and queued locally
62-
6. The queue dispatcher sends the turn into pi only when dispatch is safe
59+
2. Each update offset is persisted only after the update handler succeeds; repeated handler failures are bounded so one poisoned update cannot stall polling forever
60+
3. The bridge filters to the paired private user
61+
4. Media groups are coalesced into a single Telegram turn when needed
62+
5. Files are streamed into `~/.pi/agent/tmp/telegram` with size-limit checks, partial-download cleanup on failures, and stale temp cleanup on session start
63+
6. A `PendingTelegramTurn` is created and queued locally
64+
7. Telegram `edited_message` updates are routed separately and update a matching queued turn when the original message has not been dispatched yet
65+
8. The queue dispatcher sends the turn into pi only when dispatch is safe
6366

6467
### Queue Safety Model
6568

@@ -96,13 +99,13 @@ Key rules:
9699

97100
- Rich text should render cleanly in Telegram chats
98101
- Real code blocks must remain literal and escaped
99-
- Supported absolute HTTP(S) and mailto links should stay clickable, while unsupported link forms such as unresolved references, footnotes, or relative links without a known base should degrade safely instead of producing broken Telegram anchors
102+
- Supported absolute HTTP(S) and mailto links should stay clickable, with generated HTML attributes escaped separately from text content, while unsupported link forms such as unresolved references, footnotes, or relative links without a known base should degrade safely instead of producing broken Telegram anchors
100103
- Markdown tables should keep their internal separators but drop the outer left and right borders when rendered as monospace blocks so narrow Telegram clients keep more usable width
101104
- Unordered Markdown lists should render with a monospace `-` marker and ordered Markdown lists should render with monospace numeric markers so list indentation stays more predictable on narrow Telegram clients
102105
- Real Markdown task-list items should render with checkbox markers, while standalone `[x]` and `[ ]` prose should stay literal instead of being reinterpreted as checklists
103106
- Nested Markdown quotes should flatten into one Telegram blockquote with added non-breaking-space indentation because Telegram does not render nested blockquotes reliably
104107
- Original blank-line spacing between Markdown blocks should stay intact in both preview and final rendering instead of being collapsed to one generic block separator, while headings should still keep readable separation from following blocks such as code fences even when source Markdown omits a blank line
105-
- Long replies must be split below Telegram's 4096-character limit
108+
- Long replies, including raw HTML-mode replies used by interactive/status flows, must be split below Telegram's 4096-character limit
106109
- Chunking should avoid breaking HTML structure where possible
107110
- Preview rendering uses stable top-level Markdown blocks for rich Telegram HTML and appends the still-growing tail conservatively as readable plain text so the preview stays valid even when the answer is incomplete
108111

@@ -116,11 +119,12 @@ Preferred order:
116119

117120
1. Re-render the current Markdown buffer into a preview snapshot that renders closed top-level blocks as rich Telegram HTML and keeps the unstable tail conservative and readable
118121
2. Send or update that preview through `sendMessage` plus `editMessageText`, because `sendMessageDraft` is text-only for rich previews
119-
3. Replace the preview with the final rendered reply when generation ends
122+
3. Serialize overlapping preview flushes so older Telegram edit calls cannot race newer streamed snapshots
123+
4. Replace the preview with the final rendered reply when generation ends
120124

121125
Draft streaming can remain as a plain-text fallback path, but rich Telegram previews are driven through editable messages and stable-block snapshot selection.
122126

123-
Outbound files are sent only after the active Telegram turn completes and must be staged through the `telegram_attach` tool.
127+
Outbound files are sent only after the active Telegram turn completes, must be staged through the `telegram_attach` tool, and use file-backed multipart blobs so large sends do not require preloading whole files into memory.
124128

125129
## Interactive Controls
126130

@@ -129,7 +133,7 @@ The bridge exposes Telegram-side session controls in addition to regular chat fo
129133
Current operator controls include:
130134

131135
- `/status` for model, usage, cost, and context visibility, queued as a high-priority control item when needed
132-
- Inline status buttons for model and thinking adjustments, applying idle selections immediately while still respecting busy-run restart rules
136+
- Inline status buttons for model and thinking adjustments, applying idle selections immediately while still respecting busy-run restart rules; model-menu inputs are cached briefly and stored inline-menu states are pruned by TTL/LRU so old keyboards expire predictably
133137
- `/model` for interactive model selection, queued as a high-priority control item when needed and supporting in-flight restart of the active Telegram-owned run on a newly selected model
134138
- `/compact` for Telegram-triggered pi session compaction when the bridge is idle
135139
- Queue reactions using `👍` and `👎`, with `👎` acting as the canonical queue-removal path because ordinary Telegram DM message deletions are not exposed through the Bot API polling path this bridge uses

0 commit comments

Comments
 (0)