Skip to content

feat(channels): a channel framework with twelve providers - #778

Merged
huichen merged 24 commits into
mainfrom
feat/channels-multiplatform
Sep 22, 2026
Merged

huichen merged 24 commits into
mainfrom
feat/channels-multiplatform

Conversation

@huichen

@huichen huichen commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

What this changes

channels/ used to be two hand-written bridges (Feishu, DingTalk), each with its
own copy of the same pipeline. This turns it into a channel framework plus a
family of providers, and adds eleven channels on top of it.

The bridge (channels/src/bridge/) now owns everything that is not
platform-specific:

  • a normalized inbound message (conversation, sender, thread, media, addressing)
  • freshness and duplicate filtering, so a reconnect does not replay a backlog
  • the DM / group / mention access policy shared with the Feishu bridge
  • conversation → agent session mapping, thread-aware
  • a bounded per-conversation mailbox: in-order within a conversation, concurrent
    across conversations, backpressure instead of unbounded memory, and a newer
    message supersedes a running turn instead of racing it
  • chat-based approvals: a bare yes/no answers a parked request, anything longer
    is an ordinary message
  • the prompt → stream → reply loop behind a ReplySink, with progressive output
    where the platform can edit, buffered output where it cannot, tool activity
    folded into a visible note, and a failed turn explained
  • a durable outbound queue with backoff and permanent-error classification, so a
    proactive send survives a rate limit or a restart
  • transport helpers: retrying HTTP, reconnecting websocket, constant-time webhook
    signatures, an inbound webhook server, and text splitting that never breaks a
    character or a half-written code fence
  • a status snapshot the CLI reads without talking to a running bridge

Eleven providers implement the contract, so a new IM is one file:

Telegram, Slack, Discord, Mattermost, Signal, WhatsApp (Cloud API), QQ, Linq,
iMessage (macOS), IRC, Email (IMAP + SMTP), plus the Terminal channel used as the
reference implementation. Each declares its real limits (Slack counts UTF-16
units, IRC counts bytes including the protocol overhead), its capabilities and
its maturity; each has tests for its dialect and its error classification.

future channel list | status | test <id> | send are handled before the
bridge starts, so diagnostics work with no bridge running, and --durable hands
a message to the queue.

Verification

  • cargo test -p future-channel --all-targets — 1366 lib tests + 15 binary
    tests, including subprocess tests for the process-global paths.
  • cargo fmt -p future-channel --check and
    cargo clippy -p future-channel --all-targets -- -D warnings on the pinned
    1.97 toolchain (the Homebrew clippy 1.96 reports a false positive in
    feishu_rest.rs).
  • Per-line coverage (lcov DA:n,0): zero uncovered lines in the bridge,
    transport, CLI, outbound queue, status and seven of the eleven providers. The
    remaining lines are either still being closed in follow-up commits or are the
    exemptions listed below — no line was deleted or weakened to satisfy the
    measurement.

Design points worth a reviewer's attention

  1. Providers hold platform knowledge only. A provider parses events into
    bridge::Inbound, calls ProviderCtx::handle, and sends text. It never
    chunks, throttles, retries, deduplicates or checks policy — the bridge does,
    and the contract (docs/guide/channels-provider-contract.md) says so.
  2. A level-triggered shutdown signal. A bare Notify woke only the waiters
    parked at that instant, and a channel has two waits in sequence (the session,
    then the reconnect backoff), so the second one hung. Shutdown keeps a flag
    next to the notification, and its notified() is a hand-written future so a
    select! can poll the same wait again after it completed.
  3. A rejected message does not stop the turn that is running. The mailbox
    reserves the generation and publishes it only once the message is queued;
    otherwise Full would supersede the running turn and then drop its
    replacement, leaving the conversation unanswered.
  4. State transitions publish immediately; counters do not. "Is it up?" is the
    question an operator asks, so a transition is written as it happens; counters
    ride the periodic flush.
  5. The outbound queue keeps a message it cannot build. A channel that is
    misconfigured today may be fixed tomorrow, so the entry keeps its place and
    its attempt budget instead of being dropped.

Exempted lines (with reasons, not omissions)

File Lines Why it cannot be reached
lib.rs 4 The inspect_err closures around the self-bridged channels: those runs only return on shutdown or task abort, and neither evaluates the closure.
lib.rs, outbox.rs 8 The "enabled but not implemented" guard: every channel in this build is implemented. The decision itself is unit-tested (ChannelDefinition::ensure_usable), and the tests assert that the planned/implemented lists still partition the registry.
bridge/queue.rs 2 Defensive returns in evict_idle, kept so the loop terminates if its invariant is ever broken.
transport/webhook.rs 3 A bound listener's accept() cannot be made to fail from inside the process. The neighbouring 400/413/431 paths are covered.
providers/cli.rs 3 A read error on fd 0 cannot be provoked without taking over the test runner's stdin.

channels/src/{feishu,dingtalk}/ and grpc_client.rs have a small number of
pre-existing uncovered lines on main; this PR does not change them.

Every channel used to re-implement the same pipeline. This extracts it, so a
new IM is one file instead of a new bridge.

The bridge (channels/src/bridge) owns: a normalized inbound envelope, stale and
duplicate filtering, DM/group/mention access policy, conversation → agent
session mapping, a bounded per-conversation queue with generation-based
supersede, routing a chat answer back to a parked approval request, and the
prompt → stream → reply loop behind a ReplySink abstraction. The default sink
streams progressively on platforms that can edit a message, buffers otherwise,
folds tool activity into a visible note, and explains a failed turn.

Supporting pieces: a durable outbound delivery queue with backoff and permanent
error classification, transport helpers (retrying HTTP, reconnecting websocket,
constant-time webhook signatures, an inbound webhook server, text splitting that
never breaks a character or a code fence), and a status snapshot the CLI can
read without talking to the running bridge.

channels/src/providers holds the channel contract and a registry that declares
each channel's identity, capabilities, limits and maturity. Twelve channels are
registered; the Terminal channel is implemented as the reference for how thin a
provider can be, and the rest declare their intended configuration and refuse to
start until implemented. Feishu and DingTalk keep their own bridges and are
declared so the CLI and docs still describe the whole product.

Access policy and the conversation → session store move up from the Feishu
module unchanged, so every channel shares one implementation.
… rejects

The per-conversation mailbox is bounded, and a full mailbox already rejects the
overflow. It also bumped the conversation generation first, so a rejected
message stopped the turn that was running and then dropped its replacement —
leaving the conversation with no answer at all. Reserve the generation, publish
it only after the message is actually queued, and check the generation in the
worker as before.

Also expose response headers on the shared HTTP helper: a platform's rate-limit
bucket and request-id metadata live in headers, and a provider that has to reach
around the helper to read them is worse off than one that gets them from it.
`future channel list | status | test | send` are handled before the bridge
starts, so they answer whether or not one is running and never come up as a
side effect of asking a question.

* `list` prints each channel's maturity, capabilities, message limit, external
  requirements and whether the configured file enables it.
* `status` reads the snapshot the bridge publishes plus the outbound queue, so a
  missing or stale snapshot is itself the answer ("not running"), and a
  configured-but-unbuildable channel is named rather than silently absent.
* `test <channel>` builds one channel from configuration and makes a real
  request; it works on a channel that is not enabled yet.
* `send` is the outbound path that belongs to no conversation — a cron note, a
  loop gate notification, an "tell me when it is done". `--durable` queues it
  first, and the bridge retries the queue on a timer, so a rate limit or a
  restart cannot lose it.

`ChannelConfig::load_for_read` backs the read-only commands: no first-run
template is written, and a missing or broken file degrades to defaults with a
note instead of failing the command.
Raises the new framework code to per-line coverage (lcov DA:0 = 0) rather than
relying on a summary percentage.

The bulk of this is tests, plus the seams they needed:

* `cli_cmd` splits reporting from I/O: each command builds a typed report
  (`ListReport` / `StatusReport` / `SendReport`) that a test can assert, and
  rendering and stdin reading stay at the process entry point.
* `Outbox::deliver_entry` takes an already-built sender, so the success,
  transient-failure and permanent-failure paths are testable without a
  platform; `DrainSummary::record` replaces the duplicated classification arms.
* `ws::supervise_with` takes an explicit health window, so the backoff reset is
  tested without waiting a minute (`supervise` keeps the documented 60s).
* The bridge gains an end-to-end test against a mock agent: prompt, stream,
  reply, session reuse, image input, supersede, approval answer, backpressure
  and the unreachable-agent path all run through the real pipeline.
* Small fixes the tests found: shutdown signals in tests use `notify_one`
  (a `notify_waiters` between waits is lost), the starter publishes a state for
  the self-bridged channels so an off channel reads `disabled` instead of
  nothing, and `ProviderCtx::approvals()` exposes approval state to providers.

Also adds `scripts/chan-cov.sh` (`--check FILE...` gates one file) and
`scripts/chan-missed.py` so a worker can measure its own file without judging a
peer's.
Clears the last per-line gaps in the framework code the previous commit left
open, plus the lints the pinned clippy reports:

* the per-conversation table's eviction is now testable through
  `Conversations::with_idle_timeout`, so both the idle-eviction branch and the
  fallback that protects a busy conversation are asserted; a test also proves an
  evicted conversation's worker exits instead of lingering.
* the reply sink drops its second emptiness check (compose trims, and `chunk`
  never returns nothing for a non-blank body), and a whitespace-only update is
  covered as a real case: the sink posts nothing.
* the mock HTTP harness now self-tests its rate-limit route, which is how a
  provider test emulates a `Retry-After` response.
* test gates are released (and the tasks given a moment to finish) so a runner
  body is not left pending mid-await; shutdown signals in tests use
  `notify_one`, since a `notify_waiters` fired between waits is lost.
Verify the provider reference against the provider sources instead of the
plan: maturity per channel (cli live; the rest preview or planned), the
keys each config block really reads (webhook bind address/path, allowlists,
api_base/api_version test seams, IRC's password and idle ping, Signal's
receive timeout and optional uuid), the declared capabilities, the
diagnostics and runtime files, and a known-limitations section listing what
is not live-verified.

Every shared-behaviour bullet now names the module it comes from, and the
diagnostics section matches what `future channel list|status|test|send`
actually print and accept.
…nent

The queue classifies by matching the platform error text against a
conservative phrase list, so a permanent failure phrased outside it is
retried to exhaustion before being parked. Say that where the durable
queue is described, in both languages.
The contract for adding a channel lived next to the code
(`channels/src/providers/INTERFACE.md`), which the documentation checker reports
as a markdown file outside `docs/`, and it mixed the durable contract with
instructions that only applied to the parallel work that produced it.

The durable half is now a bilingual page under `docs/guide/`, written for the
next contributor: the two provider traits, where the inbound/outbound boundary
sits and why, configuration, error classification, what to test, the
platform-documentation ground rules, and the per-file coverage gate
(`scripts/chan-cov.sh --check`). The parallel-checkout notes are reduced to the
two rules a contributor still needs: never run a tree-wide git operation in a
shared checkout, and a peer's half-written file is not your defect.
The contract now lives in `docs/guide/channels-provider-contract.md` (bilingual);
the file next to the providers is removed so the documentation checker has
nothing outside `docs/` to report, and `providers/mod.rs` documents the path in
its module comment.
Several channel providers are written in one checkout, and a per-file coverage
gate invites each worker to run an instrumented build. Run concurrently they
thrash the CPU, and a test binary was observed getting SIGKILLed mid-run, which
makes the resulting numbers worthless.

The script now takes an exclusive lock and waits its turn, printing one line the
first time it has to wait. `--check FILE...` keeps judging only the files it is
given, so a peer's in-flight file still cannot fail someone else's gate.
`notify_waiters` only wakes tasks parked on the signal at that moment. A channel
supervisor whose session was running registers its wait *after* the signal, so it
waited forever for a second one (and `Started::stop` then aborted it, masking the
hang). Storing a permit as well means the next registration completes
immediately.
A measurement killed outright (SIGKILL skips the trap) left the lock directory
behind, which would block every other worker until the wait timeout. The lock now
records its owner's pid and is reclaimed when that process is gone.
A lock created before the pid file existed (or by a run killed before writing
it) had no owner to check, so it blocked every worker until the wait timeout.
Such a lock is now reclaimed once nothing has touched it for a minute.
* `ChannelDefinition::ensure_usable` replaces two copies of the
  "channel is not implemented" message, so the starter, the diagnostics and the
  outbound queue cannot drift apart — and the decision is unit-testable without
  a channel that happens to be unimplemented.
* Diagnostics that were only evaluated with a tracing subscriber installed are
  built as a plain message first, so the line is a statement the tests reach and
  the macro takes one argument.
* New tests: a superseded turn updates the published counter, a turn that cannot
  start reports a failure and leaves the bridge routable, an approval answer the
  agent rejects is kept retryable, a configured-but-not-buildable channel is
  refused with its reason, and a status write failure is reported.
* Tests that iterated the now-empty `planned()` set (every channel is
  implemented) assert the invariant over the whole registry instead, and the
  test doubles' own methods are called so a silent no-op cannot hide a gap.
Three test suites were hanging on shutdown, and the cause was shared: a channel
has two waits in sequence — the session that is streaming, then the supervisor's
reconnect backoff — and the second one registers *after* the first was woken by
the signal. A bare `Notify` wakes only the waiters parked at that instant (or
leaves a single permit), so the second wait never completed. In production
`Started::stop` then aborted the task, which hid the hang; a caller that awaited
the channel task instead of aborting it would have waited forever.

`Shutdown` keeps a flag next to the notification, so a wait started after the
signal returns immediately, and every later wait does too. Providers see the same
call they already used (`ctx.shutdown().notified()`, `ws::supervise(...)`), so
only the type changed; the internal bot bridge and the webhook server take it as
well, and `Shutdown::notified` is a hand-written future so that a `select!` which
picked another branch can poll the same wait again instead of panicking.

The Feishu, DingTalk, Mattermost, Slack, IRC and Email test suites now shut down
promptly instead of timing out.
…gaps

A state change is the part of the snapshot an operator reads to answer "is it
up?", so it is now written out as it happens; counters stay on the periodic
flush. That also makes a channel's reported state observable as soon as it
connects, which is what a provider test wants to assert.

Alongside: tests for a provider that fails to start (reported, then retried), an
unwritable snapshot path (reported, never fatal), reading a proactive send body
from stdin, and both terminal callbacks on the test sinks. Tests that walked the
now-empty planned subset assert the partition of the registry instead, and the
remaining diagnostics are built as plain messages so the line is reachable.
Every registered channel is now implemented, so the macro that declared a
planned provider had no callers; the helper it wrapped stays, and the contract
points at it. Also flattens the subcommand dispatch, builds the missing-publish
diagnostic as a plain message, and hoists two test-macro arguments so the lines
are reachable. The suite is green (1366 lib + 15 binary tests) and the pinned
clippy is clean for these files.
…xemptions

Adds tests for the reachable remainder: a channel data directory that cannot be
created, a snapshot the flusher cannot write, two thinking deltas inside one
throttle window, an image whose inbox path is blocked, and a client that resets
the connection mid-response. Removes a test whose busy-wait handshake read
starved the client on a current-thread runtime (it hung the instrumented suite,
and the exact handshake-level EOF it wanted cannot be produced by the harness,
whose close is an abortive reset).

Also drops a dead panic arm from an assertion and asserts the published-channel
count instead, so the measurement has no unavoidable ghosts.

The per-line exemptions that remain are recorded in
coverage/chan/acceptance-record.md with the reason each line cannot be reached.
Provider-side coverage for the frames and failures a platform can produce but a
happy-path test never does: a non-JSON frame, a socket whose write half is gone
before the next ack/pong, a webhook bind that has to be observed from inside the
task, an attachment whose download fails, a missing database permission for the
macOS channel, and a QQ gateway frame the parser ignores.

Also silences three lints the pinned clippy reports: a complex slot type in the
Slack test hook is named, the two unused harness bindings are marked, and the
Slack tests state why a guard is held across awaits (they serialize on a
process-global hook).
@huichen
huichen enabled auto-merge (squash) September 22, 2026 13:29
Two Linux-only build errors that a macOS checkout cannot see, because the code
that triggers them is inside `cfg(not(target_os = "macos"))`:

- the bridge imports (ChatKind, Inbound, SenderRef) are used only by the
  macOS-gated implementation, so they are now imported under that cfg;
- the unsupported-platform test calls `expect_err` on a sender result, whose Ok
  side is a trait object with no Debug — the Ok side is mapped away first.

The pinned clippy with `--all-targets -D warnings` is green again.
The unsupported-platform test module is compiled only off macOS, and it names
 through  — which no longer reaches that type now that the
parent import is macOS-gated. It imports what it uses itself.
The test asserted that the *default* 127.0.0.1:8787 is unavailable because a
local service held it on the machine it was written on. On a clean machine the
port is free, the bind succeeds, and the run loop never returns — which is how it
failed in CI. It now binds its own port, keeps the listener, and points the
provider at that address, so the failure path is tested deterministically.
@huichen
huichen merged commit b287f5e into main Sep 22, 2026
22 of 24 checks passed
@huichen
huichen deleted the feat/channels-multiplatform branch September 22, 2026 13:59
@huichen

huichen commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up: residual per-line coverage

The framework and seven of the twelve providers are at zero uncovered lines
(lcov DA:n,0). This is what remains, measured on the merge commit
(bash scripts/chan-cov.sh, pinned toolchain, self-serialising lock):

providers/slack.rs       11  lines 738, 768, 798, 799, 800, 804, 913, 944, 945, 946, 986
providers/mattermost.rs   5  lines 529, 554, 575, 576, 577
providers/imessage.rs     2  lines 278, 387
providers/qq.rs           1  line  626
lib.rs                   15  the exemptions below
providers/cli.rs          3  the stdin read-error arm
transport/webhook.rs      3  the accept() error arm
bridge/queue.rs           2  defensive returns in evict_idle
outbox.rs                 1  the "not implemented" guard

Classes and how to close them:

  1. Tracing arguments (798-800, 804, 575-577 and similar): the macro's
    arguments are only evaluated when a subscriber is installed, so the line stays
    uncovered even when the branch runs. Build the message with format! first and
    pass one variable to the macro — that is how the bridge's own diagnostics were
    fixed.
  2. Unparseable frame / failed download (mattermost 575-577, slack 798-804):
    point a mock at a text frame that is not JSON, and a file URL that returns an
    error. Both are ordinary inputs the provider is expected to survive.
  3. Write to a socket whose peer is gone (slack 768, mattermost 529/554):
    close the mock's side first, then let the session write without an intervening
    read.
  4. The webhook test hook (slack 913, 944-946, 986): either a test arms it, or
    the hook is dead scaffolding and should be deleted in favour of asserting the
    bound address directly.
  5. imessage.rs 278 is the non-macOS unsupported path, which cannot run on
    macOS; imessage.rs 387, qq.rs 626 and the lib.rs,
    providers/cli.rs, transport/webhook.rs, bridge/queue.rs and outbox.rs
    lines are the documented exemptions (a run that only returns on abort, a guard
    for a maturity no channel declares, an fd the test runner owns, a listener
    whose accept cannot be made to fail, and two defensive returns).

scripts/chan-cov.sh --check <file>... judges only the files named, so the
follow-up can be split per file without a peer's in-flight file failing someone
else's gate.

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