feat(cli): add telegram channel adapter, scoped config, and diagnostics (replacement)
Summary
- rebased on latest
upstream/dev - squashed replacement history for Telegram adapter path
- includes scoped bridge config + diagnostics + Telegram adapter behavior
Supersedes
- #110
Depends on
- #114 (core replacement)
Notes
- Replacement branch:
feat/telegram-channel-adapter-v2
Summary by CodeRabbit
-
New Features
- Added a Channel Bridge for bi-directional Telegram sessions with webhook and polling modes, CLI bridge commands, daemon auto-start, and runtime config overlay.
-
Bug Fixes
- Improved KV conflict/retry resilience and safer webhook/token validation and error recovery.
-
Tests
- Broad new test coverage for adapters, worker, KV flows, overlays, CLI, and startup/shutdown edge cases.
-
Documentation
- Added Channel Bridge docs, Telegram guide, and UAT checklist; README index updated.
-
UI/Diagnostics
- Doctor enhancements: webhook validation, port parsing, secret redaction, and exit-code handling.
@coderabbitai review
@greptile review
[!NOTE]
Reviews paused
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
- [ ] βΆοΈ Resume reviews
- [ ] π Trigger review
Walkthrough
Adds a Channel Bridge subsystem: provider-agnostic worker runtime, Telegram adapter and webhook relay, server KV transport and cache-backed binding store, scoped account config and overlays, CLI and daemon wiring, diagnostics/redaction utilities, extensive tests, and documentation including a Telegram guide and README "Channel Integrations" entry.
Changes
| Cohort / File(s) | Summary |
|---|---|
Core worker & runtime apps/cli/src/channels/core/channelBridgeWorker.ts, apps/cli/src/channels/core/channelBridgeWorker.test.ts, apps/cli/src/channels/startChannelBridgeWorker.ts, apps/cli/src/channels/startChannelBridgeWorker.test.ts, apps/cli/src/channels/startChannelBridgeWorker.startupFailure.test.ts |
Adds a provider-agnostic channel bridge worker, tick loop, slash-command parsing/handling, per-session runtime caching, lifecycle start/stop orchestration, public worker APIs and extensive unit/integration tests. |
Telegram adapter & webhook relay apps/cli/src/channels/telegram/telegramAdapter.ts, apps/cli/src/channels/telegram/telegramAdapter.test.ts, apps/cli/src/channels/telegram/telegramWebhookRelay.ts, apps/cli/src/channels/telegram/telegramWebhookRelay.test.ts |
Implements Telegram API client, polling/webhook adapter with inbound normalization, ack/queue semantics, outbound truncation/error handling, secure loopback Fastify webhook relay, and tests. |
Server KV, binding store & concurrency apps/cli/src/channels/channelBridgeServerKv.ts, apps/cli/src/channels/channelBridgeServerKv.test.ts, apps/cli/src/channels/channelBindingStore.server.ts, apps/cli/src/channels/channelBindingStore.server.test.ts |
Adds ChannelBridge KV client/types, base64 payload handling, schema parsing/validation, optimistic read/mutate with version-mismatch errors, and a cache-backed server binding store with optimistic retries and comprehensive tests. |
Scoped/account config & overlay apps/cli/src/channels/channelBridgeAccountConfig.ts, apps/cli/src/channels/channelBridgeAccountConfig.test.ts, apps/cli/src/channels/channelBridgeServerConfigOverlay.ts, apps/cli/src/channels/channelBridgeServerConfigOverlay.test.ts |
Implements scoped Telegram bridge config read/upsert/remove, split local/shared updates, pruning of empty nodes, and overlay helper to merge server KV config into settings; includes tests. |
Runtime config resolution apps/cli/src/channels/channelBridgeConfig.ts, apps/cli/src/channels/channelBridgeConfig.test.ts |
Adds layered runtime config resolver merging env/global/server/account scopes with parsing, bounds checking, host/port rules, secret extraction, and tests. |
CLI command surface & dispatch apps/cli/src/cli/commands/bridge.ts, apps/cli/src/cli/commands/bridge.test.ts, apps/cli/src/cli/commandRegistry.ts, apps/cli/src/cli/dispatch.ts, apps/cli/src/cli/dispatch.tmuxDisallowed.test.ts |
Adds bridge CLI (list/set/clear) with validation, transactional server-KV vs local secret updates and rollback, registry wiring, tmux disallowed checks update, and tests. |
Daemon integration & test harness apps/cli/src/daemon/startDaemon.ts, apps/cli/src/daemon/startDaemon.automation.integration.test.ts |
Wires best-effort channel bridge startup into daemon bootstrap, overlays server KV into settings, manages lifecycle and shutdown timeouts, and exposes test harness hooks/mocks. |
Diagnostics, persistence types & UI apps/cli/src/persistence.ts, apps/cli/src/ui/doctor.ts, apps/cli/src/ui/doctor.test.ts |
Adds channelBridge settings type, webhook validation and strict port parsing, redaction helpers for channelBridge secrets, runtime overlay diagnostics and exit-code control, and tests. |
Documentation & README README.md, docs/README.md, docs/channel-bridge.md, docs/channel-bridge-uat.md, docs/telegram-channel-bridge.md |
Adds Channel Bridge docs, UAT checklist, Telegram guide, and README index entries including a "Channel Integrations" subsection linking the Telegram guide. |
Misc & broad tests apps/cli/src/channels/.../*.test.ts, apps/cli/src/cli/.../*.test.ts (multiple new/updated test files) |
Large suite of unit and integration tests added across adapters, KV, store, worker, CLI, webhook relay, and runtime covering many success and error scenarios. |
Sequence Diagram(s)
sequenceDiagram
participant Adapter as Telegram Adapter
participant Worker as Channel Bridge Worker
participant Store as Binding Store
participant KV as Server KV
participant Session as Session Service
rect rgba(0, 100, 200, 0.5)
Note over Worker: Tick begins
Adapter->>Worker: pullInboundMessages()
Worker->>Worker: deduplicateInbound()
alt Slash command (attach/session)
Worker->>Store: upsertBinding(conversationβsession)
Store->>KV: write(binding)
else User message
Worker->>Store: getBinding(conversation)
Store->>KV: read(binding)
Worker->>Session: forwardUserMessage(sessionId, text)
Session-->>Worker: responseRows
Worker->>Adapter: sendMessage(conversation, agentText)
Adapter-->>Worker: deliveryAck
Worker->>Store: updateLastForwardedSeq(binding)
Store->>KV: write(binding.lastForwardedSeq)
end
end
Estimated code review effort
π― 5 (Critical) | β±οΈ ~120 minutes
π₯ Pre-merge checks | β 1 | β 2
β Failed checks (1 warning, 1 inconclusive)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | β οΈ Warning | Docstring coverage is 3.70% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
| Description check | β Inconclusive | The description is sparse and vague, lacking required template sections (Why, How to test, Checklist). While it mentions rebasing and squashing, it does not clearly explain the problem being solved or provide testing instructions. | Complete the PR description by filling in Why (problem/issue it solves), How to test (step-by-step verification), and Checklist sections per the repository template to improve clarity and reviewability. |
β Passed checks (1 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | β Passed | The PR title clearly and concisely describes the main additions: a Telegram channel adapter, scoped configuration management, and diagnostic improvements, which aligns with the substantial code additions across multiple modules. |
βοΈ Tip: You can configure your own custom pre-merge checks in the settings.
β¨ Finishing Touches
π§ͺ Generate unit tests (beta)
- [ ] Create PR with unit tests
[!WARNING]
Review ran into problems
π₯ Problems
Git: Failed to clone repository. Please run the
@coderabbitai full reviewcommand to re-trigger a full review. If the issue persists, setpath_filtersto include or exclude specific files.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
Review triggered. Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.β
Actions performed
@coderabbitai review
Review triggered. Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.β
Actions performed
Greptile Summary
This PR adds a full Telegram Channel Bridge to the Happier CLI: a provider-agnostic bridge worker (channelBridgeWorker.ts), a Telegram adapter with both polling and webhook modes, a scoped settings/KV config system, happier bridge CLI commands, daemon integration, and enhanced happier doctor diagnostics. It supersedes #110 and depends on #114.
The implementation is substantial (~12k lines added) and has received extensive prior review. Many hard correctness issues β permanent-delivery cursor stalls, reply-guard hardening, surrogate-safe truncation, typed error contracts, loopback validation at every write path, and daemon shutdown races β were addressed across multiple fix commits.
Three issues remain unaddressed:
-
Dead parameters and
messageIdtype-contract mismatch increateStableBridgeLocalId(startChannelBridgeWorker.ts:52):sessionIdandtextare declared in the parameter object but never contribute to the hash; more critically,messageIdis typed?: string(matching theChannelBridgeDepsinterface) but throws at runtime when absent, creating a hidden contract violation that TypeScript cannot catch. -
Settings-level webhook token not validated for the allowed character set (
channelBridgeConfig.ts:216):settingsWebhookSecretis resolved throughreadTrimmedString(non-empty check only), while the env-var path usesreadWebhookSecretToken(full pattern validation). A malformed token insettings.jsonsilently causes a webhook startup failure and polling-mode fallback at daemon start. -
No operator warning when
resolveSessionRuntimereturnsnull(startChannelBridgeWorker.ts:290): when a bound session becomes inaccessible, outbound forwarding stalls silently with no log output β unlike the analogousstore.getBindingfailure path which both notifies the user in-channel and emits a warning.
Confidence Score: 2/5
- PR has solid core bridge implementation but carries three unaddressed issues: type-contract violation in localId generation, silent operational stall with no diagnostics, and inconsistent webhook token validation creating config confusion.
- Score of 2/5 reflects that the PR is functionally sound for polling-mode operation and has been well-hardened through multiple review rounds. However, three issues from the prior review cycle remain unaddressed: (1) dead parameters and type-contract mismatch in
createStableBridgeLocalIdcreate developer confusion and hidden runtime constraints; (2)resolveSessionRuntimereturning null silently stalls outbound forwarding with no operator visibility into why; (3) settings-derived webhook token validation is inconsistent with env-var validation, making it easy to misconfigure when editing settings.json directly. None are critical regressions, but they represent observable gaps in type safety, operational diagnostics, and config validation consistency that should be resolved before merge. - apps/cli/src/channels/startChannelBridgeWorker.ts (dead parameters, missing warning on session null), apps/cli/src/channels/channelBridgeConfig.ts (settings webhook token validation gap)
Last reviewed commit: 74ae08b
Addressed the latest review items in commit 8514428b.
Highlights:
- Added explicit
senderIdin Telegram inbound parsing. - Hardened webhook relay with explicit header secret token requirement and loopback-only host validation.
- Prevented tick-only scoped updates from materializing empty provider trees.
- Switched plain-session outbound transcript reads to bypass decryption path.
- Reordered bridge CLI persistence so shared KV writes happen before local settings updates.
- Added strict empty
--bot-tokenvalidation. - Hardened doctor redaction for global/server/account provider scopes and exported strict webhook port parsing.
- Clarified UAT/doc behavior for webhook
401vs404outcomes and refreshed bridge docs/index links.
Targeted regression tests passed locally:
- 10 files, 130 tests passed.
@coderabbitai review
@greptile review
@cdenneen Thanks for the detailed summary of the changes in commit 8514428b! The hardening across webhook relay, doctor redaction, and scoped config persistence all sound like meaningful improvements. Triggering a fresh incremental review now to check the latest commit.
π§ Learnings used
Learnt from: cdenneen
Repo: happier-dev/happier PR: 110
File: apps/cli/src/channels/telegram/telegramAdapter.test.ts:17-41
Timestamp: 2026-03-04T15:25:08.440Z
Learning: In apps/cli/src/channels/telegram/telegramAdapter.test.ts, the TelegramApiClient (getMe, getUpdates, sendMessage) is intentionally stubbed with vi.fn mocks. This is an accepted exception to the no-mocking guideline because TelegramApiClient is a true third-party API system boundary requiring external credentials/network. End-to-end Telegram transport validation is tracked separately as an integration suite to avoid CI flakiness.
β Actions performed
Review triggered.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
Added a follow-up fix in commit 1714afaa to address daemon startup coupling feedback.
Change:
- Moved channel bridge bootstrap into its own best-effort async task so machine registration/sync setup is no longer blocked by bridge startup awaits.
Validation rerun after this patch:
startDaemon.automation.integration.test.tsbridge.test.tsstartChannelBridgeWorker.test.tstelegramWebhookRelay.test.tschannelBindingStore.server.test.tsdoctor.test.tsdispatch.tmuxDisallowed.test.ts
All passed.
@coderabbitai review
@greptile review
@cdenneen Thanks for the follow-up fix! Decoupling the channel bridge bootstrap into a best-effort async task is the right approach β machine registration and sync setup are on the critical startup path (per the daemon lifecycle requirements), so removing the blocking awaits from bridge initialization prevents any bridge startup latency or failure from delaying core daemon readiness. Triggering an incremental review of commit 1714afaa now.
π§ Learnings used
Learnt from: CR
Repo: happier-dev/happier PR: 0
File: apps/cli/src/daemon/CLAUDE.md:0-0
Timestamp: 2026-02-16T05:35:08.653Z
Learning: Applies to apps/cli/src/daemon/src/daemon/**/*.ts : Daemon startup registration must send REST POST /v1/machines request with machine ID, encrypted metadata (base64), and encrypted daemonState (base64); server response includes metadataVersion and daemonStateVersion for independent versioning
Learnt from: CR
Repo: happier-dev/happier PR: 0
File: apps/cli/src/daemon/CLAUDE.md:0-0
Timestamp: 2026-02-16T05:35:08.653Z
Learning: Applies to apps/cli/src/daemon/src/daemon/startDaemon.ts : Daemon startup must call `authAndSetupMachineIfNeeded()` to ensure credentials exist before proceeding
Learnt from: CR
Repo: happier-dev/happier PR: 0
File: apps/cli/src/daemon/CLAUDE.md:0-0
Timestamp: 2026-02-16T05:35:08.653Z
Learning: Applies to apps/cli/src/daemon/src/daemon/**/*.ts : Daemon WebSocket connection must establish persistent connection to backend via `ApiMachineClient` and register RPC handlers: `spawn-happy-session`, `stop-session`, `requestShutdown`
Learnt from: CR
Repo: happier-dev/happier PR: 0
File: apps/cli/src/daemon/CLAUDE.md:0-0
Timestamp: 2026-02-16T05:35:08.653Z
Learning: Applies to apps/cli/src/daemon/src/**/*.ts : New Happier process spawned by daemon must call `notifyDaemonSessionStarted()` to POST to daemon's `/session-started` endpoint to report itself and receive `happySessionId`
Learnt from: CR
Repo: happier-dev/happier PR: 0
File: apps/cli/src/daemon/CLAUDE.md:0-0
Timestamp: 2026-02-16T05:35:08.653Z
Learning: Applies to apps/cli/src/daemon/src/daemon/**/*.ts : Daemon state updates via WebSocket must emit 'machine-update-state' with machineId, encrypted daemonState (base64), and expectedVersion; server response includes version-mismatch handling with current state
Learnt from: CR
Repo: happier-dev/happier PR: 0
File: apps/cli/src/daemon/CLAUDE.md:0-0
Timestamp: 2026-02-16T05:35:08.653Z
Learning: Applies to apps/cli/src/daemon/src/daemon/**/*.ts : On daemon version mismatch detection, spawn new daemon via `spawnHappyCLI(['daemon', 'start'])`, which will see old daemon.state.json version mismatch and call `stopDaemon()` to kill old daemon via HTTP `/stop` with SIGKILL fallback
Learnt from: CR
Repo: happier-dev/happier PR: 0
File: apps/cli/src/daemon/CLAUDE.md:0-0
Timestamp: 2026-02-16T05:35:08.653Z
Learning: Applies to apps/cli/src/daemon/src/daemon/**/*.ts : ApiMachineClient WebSocket communication must handle bidirectional messages: daemon to server (machine-alive, machine-update-metadata, machine-update-state), server to daemon (rpc-request with spawn-happy-session, stop-session, requestShutdown); all data encrypted with TweetNaCl
Learnt from: CR
Repo: happier-dev/happier PR: 0
File: apps/cli/src/daemon/CLAUDE.md:0-0
Timestamp: 2026-02-16T05:35:08.653Z
Learning: Applies to apps/cli/src/daemon/src/daemon/**/*.ts : Daemon-spawned sessions initiated via RPC `spawn-happy-session` must: create directory if needed, spawn detached Happier process with `--happy-starting-mode remote --started-by daemon`, add to `pidToTrackedSession` map, set up 10-second awaiter for session webhook
Learnt from: CR
Repo: happier-dev/happier PR: 0
File: apps/cli/src/daemon/CLAUDE.md:0-0
Timestamp: 2026-02-16T05:35:08.653Z
Learning: Applies to apps/cli/src/daemon/src/{index,daemon/startDaemon}.ts : Daemon lifecycle: Receive `daemon start` command in `src/index.ts`, spawn detached process via `spawnHappyCLI(['daemon', 'start-sync'], { detached: true })`, which calls `startDaemon()` from `src/daemon/startDaemon.ts`
Learnt from: CR
Repo: happier-dev/happier PR: 0
File: apps/cli/src/daemon/CLAUDE.md:0-0
Timestamp: 2026-02-16T05:35:08.653Z
Learning: Applies to apps/cli/src/daemon/src/index.ts : CLI startup must check if machine ID exists in settings; if not, create ID locally only (do NOT create machine on server); CLI does not manage machine details; all API and schema live in daemon subpackage
Learnt from: cdenneen
Repo: happier-dev/happier PR: 110
File: apps/cli/src/channels/telegram/telegramAdapter.test.ts:17-41
Timestamp: 2026-03-04T15:25:08.440Z
Learning: In apps/cli/src/channels/telegram/telegramAdapter.test.ts, the TelegramApiClient (getMe, getUpdates, sendMessage) is intentionally stubbed with vi.fn mocks. This is an accepted exception to the no-mocking guideline because TelegramApiClient is a true third-party API system boundary requiring external credentials/network. End-to-end Telegram transport validation is tracked separately as an integration suite to avoid CI flakiness.
β Actions performed
Review triggered.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
Addressed the latest Greptile findings in commit a2647541 and resolved the corresponding threads.
Summary:
- Added queue-overflow warning/counter for Telegram webhook update eviction.
- Hardened
HAPPIER_CHANNEL_BRIDGE_IO_TIMEOUT_MSparsing to strict numeric input. - Added regression coverage for the overflow warning behavior.
@coderabbitai review
@greptile review
@cdenneen Thanks for the follow-up commit! The additions sound well-targeted:
- Queue-overflow warning and eviction counter for the Telegram webhook update queue adds important observability for back-pressure scenarios.
- Strict numeric parsing for
HAPPIER_CHANNEL_BRIDGE_IO_TIMEOUT_MScloses the gap where non-numeric env var values could silently produceNaN-based timeouts. - Regression coverage for the overflow warning behavior ensures that path stays tested going forward.
Triggering an incremental review of commit a2647541 now.
π§ Learnings used
Learnt from: cdenneen
Repo: happier-dev/happier PR: 110
File: apps/cli/src/channels/telegram/telegramAdapter.test.ts:17-41
Timestamp: 2026-03-04T15:25:08.440Z
Learning: In apps/cli/src/channels/telegram/telegramAdapter.test.ts, the TelegramApiClient (getMe, getUpdates, sendMessage) is intentionally stubbed with vi.fn mocks. This is an accepted exception to the no-mocking guideline because TelegramApiClient is a true third-party API system boundary requiring external credentials/network. End-to-end Telegram transport validation is tracked separately as an integration suite to avoid CI flakiness.
β Actions performed
Review triggered.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
Addressed all current open threads in commit a54e4b54 and resolved each thread with per-item notes.
Highlights:
- Hardened chat-id parsing + env-empty behavior to avoid accidental allow-all widening.
- Added deferred adapter ack flow for inbound webhook draining.
- Hardened persisted bindings parsing (required cursor/timestamp fields).
- Added write-time webhook host validation + expanded tmux command guard.
- Mitigated oversized Telegram outbound message stalling.
- Closed daemon bridge startup/shutdown race and added integration coverage.
- Updated UAT clean-state documentation.
@coderabbitai review
@cdenneen Thanks for the comprehensive summary! The changes in commit a54e4b54 look well-targeted across several important areas:
- Chat-id parsing + env-empty hardening β closing the accidental allow-all widening is a critical security fix.
- Deferred adapter ack flow β properly sequencing inbound webhook draining avoids premature acknowledgment.
- Persisted bindings parsing β requiring cursor/timestamp fields prevents silent partial-state hydration.
- Write-time webhook host validation + tmux guard β good defense-in-depth additions.
- Oversized Telegram outbound mitigation β prevents a stall on large payloads from blocking the bridge.
- Daemon bridge startup/shutdown race + integration coverage β closing that race with test coverage is the right approach.
- UAT clean-state docs β keeping the UAT guide accurate for multi-machine scenarios is important for reproducibility.
Triggering an incremental review of commit a54e4b54 now.
π§ Learnings used
Learnt from: cdenneen
Repo: happier-dev/happier PR: 110
File: apps/cli/src/channels/telegram/telegramAdapter.test.ts:17-41
Timestamp: 2026-03-04T15:25:08.440Z
Learning: In apps/cli/src/channels/telegram/telegramAdapter.test.ts, the TelegramApiClient (getMe, getUpdates, sendMessage) is intentionally stubbed with vi.fn mocks. This is an accepted exception to the no-mocking guideline because TelegramApiClient is a true third-party API system boundary requiring external credentials/network. End-to-end Telegram transport validation is tracked separately as an integration suite to avoid CI flakiness.
β Actions performed
Review triggered.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
@greptile review
Addressed the latest unresolved feedback in signed commits \ and :\n- doctor webhook diagnostics now flag non-loopback hosts and strict invalid ports\n- bridge KV keys are now scoped by server+account\n- malformed non-empty allowedChatIds payloads now fail closed\n- webhook relay now rejects non-finite ports and logs onUpdate failures\n- telegram bridge docs now clarify the single-secret limitation/security tradeoff\n\n@coderabbitai review