Skip to content

feat(chatbridge): inbound chat bridge core with a Telegram long-poll transport (#5, part 1 of 3) - #456

Open
Shiv9993 wants to merge 1 commit into
BaaRai:mainfrom
Shiv9993:feat/chat-bridge-core
Open

Shiv9993 wants to merge 1 commit into
BaaRai:mainfrom
Shiv9993:feat/chat-bridge-core

Conversation

@Shiv9993

@Shiv9993 Shiv9993 commented Nov 21, 2026 •

Copy link
Copy Markdown

Part 1 of 3 for #5, as agreed in the issue: the bridge core, the Telegram long-poll adapter, the chat allowlist, settings and the migration, with tests. Task commands with main-agent routing (PR 2) and approval buttons with a one-time nonce and expiry (PR 3) build on this one.

Problem

ARTEX can push findings to Telegram, but an operator cannot talk back: there is no inbound path from a chat app.

Behaviour change

  • New chatbridge package. It is transport-agnostic: a Transport interface plus a Router that owns every chat-app-independent rule.
    • Allowlist: only listed chat IDs are served. Any other chat gets one refusal that names its chat ID, then silence. The memory of refused chats is bounded.
    • Stale updates: anything older than two minutes is dropped, so a backlog queued while ARTEX was down is never executed.
    • Senders: bot senders and commands addressed to another bot (/cmd@other_bot) are ignored.
    • Commands: /help and /whoami for now. PR 2 adds the task commands.
  • Telegram transport.
    • Uses getUpdates long polling, so ARTEX opens no inbound port. Replies go out through plain-text sendMessage, cut to the Bot API limit, and getMe identifies the bot.
    • It reuses notify's dial guard and cross-host redirect refusal through three small exported wrappers in notify/http.go, so both directions share one guard.
    • Errors never contain the token: transport errors are reduced to scheme and host.
  • Storage (migration 0015, chat_bridges, one row per kind).
    • config is sealed at rest (added to secretColumns) and masked in the API using the notification-channel convention.
    • Changing base_url requires entering the token again.
    • The update cursor is committed before a batch is acted on, so a crash loses a batch rather than running it twice. It only moves forward.
    • The cursor is written only for the config_version the poller read, so a poll that was running under a replaced token can never move the new bot's cursor. A token change clears the cursor in the same statement that saves the token.
  • Server.
    • server.New starts one loop per transport. Each loop re-reads its row every round, and saving the form interrupts the poll in flight, so token, allowlist and on/off changes apply without a restart.
    • Errors back off exponentially, and Telegram's retry_after is honoured.
    • Logs use the [tgbot] tag and never include message text.
  • API: GET /api/chat-bridges, PUT /api/chat-bridges/{kind}, POST /api/chat-bridges/{kind}/test. The test route checks the token and sends no message.
  • Web: a System → Chat bot page with live status, token, allowlist, optional API URL and a test-connection button, plus zh-CN and tr strings.
  • Docs: docs/chat-bridge.md. The README lists the token among the encrypted secrets.

A bridge may run with an empty allowlist. It then serves no chat and only sends the one-time refusal naming the chat ID, which is how an operator learns the ID to add. I first refused to enable a bridge with an empty allowlist, but the live test below showed that makes the first setup impossible without a placeholder ID. Only listed chats are ever served either way.

What I tested

Automated (local PostgreSQL 16, ARTEX_PG_DSN set, so the DB tests ran rather than skipped):

  • go test ./chatbridge
    • router rules: allowlist, refuse-once-then-silence, bounded refusal memory, stale updates, bot senders, @other_bot commands
    • Telegram adapter against a fake Bot API server: polling cursor and request body, plain-text truncation, 401, 409 and 429 handling, cancelling a long poll
    • no token in any error, including a dial failure
    • config masking and the base_url/token rule
  • go test ./db: full suite. Includes the new TestChatBridgeSaveSealedAndOffset (sealed at rest, forward-only cursor, version-guarded cursor, reset on token change) and the migration tests with 0015 added.
  • go test ./server -run TestChatBridge
    • the poller step with a fake transport: allowlisted, refused and stale updates; cursor committed; a batch polled under a replaced config is dropped; empty allowlist serves nobody; disable
    • backoff and retry_after
    • the API end to end: masking, the token never in responses, chat ID validation, base_url change refused with a masked token, cursor reset on token change
  • go test ./notify, go vet ./...
  • Web:
    • npm run test:i18n passes.
    • biome check is clean on the new page and the sidebar.
    • tsc --noEmit passes.
    • The static build (NEXT_EXPORT=1 next build) includes /system/chat-bridge.

Live, with a real Telegram bot against a locally built binary (-tags embedui):

  • Test connection resolved the bot, and the status went Online.
  • With an empty allowlist, a message from my phone got the refusal naming my chat ID, and a second message got silence.
  • After I added the ID, /help and /whoami answered. Changing the allowlist and switching the bot on applied with no restart.
  • After a server restart the bot reconnected on its own.
  • The server log contained no token and no /bot… URL, and chat_bridges.config was sealed in the database.

Note on the full suite: I ran go test ./... on Windows. 27 tests in agent, evidence and server fail there because of Windows-only causes: \ in paths, no Python on PATH, and fsync on a directory returning "Access is denied". The same 27 fail on an untouched main checkout. None of them touches this change. I have not run the suite on Linux, so CI is the authoritative run.

@Shiv9993
Shiv9993 force-pushed the feat/chat-bridge-core branch 3 times, most recently from c7b34b7 to 24bebcf Compare November 21, 2026 19:14
…transport

First part of BaaRai#5: the transport-agnostic bridge core, the Telegram
adapter, the mandatory chat allowlist, storage, API and settings page.
Task commands, main-agent routing and remote approvals follow in
separate PRs on top of this one.

- chatbridge: Transport interface and Router. The router enforces the
  allowlist (an unknown chat gets one refusal naming its chat ID, then
  silence, bounded memory), drops updates older than two minutes so a
  backlog is never executed, ignores bot senders and commands addressed
  to another bot, and dispatches commands (/help, /whoami for now).
- Telegram transport: getUpdates long polling (no inbound port),
  plain-text sendMessage truncated to the Bot API limit, getMe for the
  identity. It reuses notify's dial guard and redirect policy through
  small exported wrappers, and its errors never carry the token.
- Storage: migration 0015 adds chat_bridges, one row per kind. config
  is sealed at rest (added to secretColumns) and masked in the API with
  the notification-channel convention. The update cursor is committed
  before a batch is acted on, only moves forward, and is written only
  for the config_version the poller read, so a poll of a replaced token
  can never move the new bot's cursor. A token change clears it.
- Server: one loop per transport started by server.New; it re-reads its
  row each round and Reload interrupts a poll in flight, so saving the
  form applies without a restart. Exponential backoff on errors, honours
  Telegram's retry_after, logs under [tgbot] without message text.
- API: GET /api/chat-bridges, PUT /api/chat-bridges/{kind},
  POST /api/chat-bridges/{kind}/test. A bridge may run with an empty
  allowlist: it then serves no chat and only sends the one-time refusal
  naming the chat ID, which is how an operator finds the ID to add.
- Web: System -> Chat bot page with live status, zh-CN and tr strings.
- Docs: docs/chat-bridge.md; README lists the token among stored secrets.

The migration test lists 0015; the pre-0012 test rolls it back with the
others and it re-applies (the migration is idempotent).

Co-authored-by: krad <[email protected]>
@Shiv9993
Shiv9993 force-pushed the feat/chat-bridge-core branch from 24bebcf to 58bafdb Compare November 24, 2026 09:59
@Shiv9993

Copy link
Copy Markdown
Author

@BaaRai rebased on current main (0c64c39); the conflicts are resolved and the PR merges cleanly again.

  • 0014 is now taken by 0014_bedrock_gateway_profiles.sql, so the chat bridge migration is renumbered to 0015_chat_bridges.sql. The migration test lists it, and the pre-0012 test keeps your version >= 12 rollback (the migration is idempotent, so it re-applies).
  • db/secrets.go keeps the new colLLMHeaders and adds colChatBridgeConfig beside colNotifConfig. The README secrets lists keep the gateway-headers wording.
  • tr.json / zh-CN.json: your current files plus the 19 chat bot strings.

No functional change to the bridge. Re-ran on the rebased commit: go build ./..., go vet ./..., go test ./chatbridge ./notify ./db (full db suite on PostgreSQL 16) and go test ./server -run TestChatBridge. On the web side: npm run test:i18n, tsc --noEmit, biome check on the changed files, and the static build.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant