Repository navigation
feat(channels): a channel framework with twelve providers - #778
Merged
Merged
Conversation
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
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.
Collaborator
Author
Follow-up: residual per-line coverageThe framework and seven of the twelve providers are at zero uncovered lines Classes and how to close them:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this changes
channels/used to be two hand-written bridges (Feishu, DingTalk), each with itsown 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 notplatform-specific:
across conversations, backpressure instead of unbounded memory, and a newer
message supersedes a running turn instead of racing it
is an ordinary message
ReplySink, with progressive outputwhere the platform can edit, buffered output where it cannot, tool activity
folded into a visible note, and a failed turn explained
proactive send survives a rate limit or a restart
signatures, an inbound webhook server, and text splitting that never breaks a
character or a half-written code fence
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> | sendare handled before thebridge starts, so diagnostics work with no bridge running, and
--durablehandsa message to the queue.
Verification
cargo test -p future-channel --all-targets— 1366 lib tests + 15 binarytests, including subprocess tests for the process-global paths.
cargo fmt -p future-channel --checkandcargo clippy -p future-channel --all-targets -- -D warningson the pinned1.97 toolchain (the Homebrew clippy 1.96 reports a false positive in
feishu_rest.rs).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
bridge::Inbound, callsProviderCtx::handle, and sends text. It neverchunks, throttles, retries, deduplicates or checks policy — the bridge does,
and the contract (
docs/guide/channels-provider-contract.md) says so.Notifywoke only the waitersparked at that instant, and a channel has two waits in sequence (the session,
then the reconnect backoff), so the second one hung.
Shutdownkeeps a flagnext to the notification, and its
notified()is a hand-written future so aselect!can poll the same wait again after it completed.reserves the generation and publishes it only once the message is queued;
otherwise
Fullwould supersede the running turn and then drop itsreplacement, leaving the conversation unanswered.
question an operator asks, so a transition is written as it happens; counters
ride the periodic flush.
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)
lib.rsinspect_errclosures around the self-bridged channels: those runs only return on shutdown or task abort, and neither evaluates the closure.lib.rs,outbox.rsChannelDefinition::ensure_usable), and the tests assert that the planned/implemented lists still partition the registry.bridge/queue.rsevict_idle, kept so the loop terminates if its invariant is ever broken.transport/webhook.rsaccept()cannot be made to fail from inside the process. The neighbouring 400/413/431 paths are covered.providers/cli.rschannels/src/{feishu,dingtalk}/andgrpc_client.rshave a small number ofpre-existing uncovered lines on
main; this PR does not change them.