fix(channels): clear stale OAuth Connecting badges across auth modes (#2128)
Summary
- Centralises OAuth deep-link → channel-badge transitions behind a new
useOAuthConnectionListenerhook so every channel panel handles bothoauth:successandoauth:errorconsistently. - Adds a
clearOtherPendingForChannelreducer so starting a connect flow on one auth mode drops any sibling auth mode that's still mid-connectingon the same channel. - Wires
DiscordConfigandTelegramConfigonto the shared hook; future channels with an OAuth auth mode inherit correct pending-state transitions automatically. - Covers the new reducer (4 cases) and hook (8 cases) with Vitest.
Problem
OAuth badges on the channel connection panels could get pinned at
Connecting indefinitely (issue #2128):
DiscordConfighad a per-componentoauth:successlistener but nooauth:errorlistener — failed OAuth attempts never transitioned the badge out ofconnecting.TelegramConfighad neither — completed and failed OAuth attempts left the badge pinned.- Both panels set
connectingon the chosen auth mode but never cancelled any sibling auth mode that was already pending. Triggering a second OAuth method on Discord (OAuth Sign-inthenLogin with OpenHuman, or the reverse) left both methods badgedConnectingsimultaneously.
This is the exact repro from the issue. The same shape was visible across
GitHub/GitLab style multi-method panels because the underlying state model
(channelConnections, keyed by (channel, authMode)) had no notion of
mutual exclusion.
Solution
Shared listener hook —
app/src/hooks/useOAuthConnectionListener.ts
subscribes to both oauth:success and oauth:error window events
(dispatched from utils/desktopDeepLinkListener.ts), filters by toolkit /
provider case-insensitively, and dispatches the matching slice action.
Per-channel panels mount it once with { channel, authMode }; cleanup on
unmount is deterministic. New channels with an OAuth auth mode inherit the
behaviour without copying any logic.
Pending-state cancellation reducer — clearOtherPendingForChannel({ channel, exceptAuthMode }) in channelConnectionsSlice.ts walks the auth-mode map
for one channel and transitions every connecting row (except the
exception) to disconnected with lastError: undefined. Cancelled rows go
to disconnected rather than error so the UI doesn't surface a misleading
failure — the user explicitly switched methods, they didn't experience an
error.
Per-panel wiring — DiscordConfig and TelegramConfig each:
- Mount
useOAuthConnectionListener({ channel: <name>, authMode: 'oauth' })at the top of the component (replacing the bespoke effect on Discord; net-new on Telegram). - Dispatch
clearOtherPendingForChannelat the start ofhandleConnectbefore setting their own auth mode toconnecting.
Tradeoffs
- The cancellation transition is
disconnected, not a newcancelledstate. Adding a dedicated state would expand theChannelConnectionStatusunion across many call sites for marginal UX value. - The deep-link CustomEvent payload (
{ integrationId, toolkit }for success,{ provider, errorCode, message }for error) is unchanged, so no symmetric change in the Tauri-side handler is needed.
Submission Checklist
- [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy — 12 new Vitest cases (4 reducer + 8 hook) covering success, error, mismatched channel, mismatched provider, missing error message, custom capabilities, unsubscribe on unmount, and three sibling-cancellation shapes.
- [x] Diff coverage ≥ 80% — frontend-only change;
pnpm test:coveragelocally over the new files reaches 100% on changed lines (every branch in the hook + reducer is exercised by the suite). - [x] Coverage matrix updated —
N/A: behaviour-only fix on existing surfaces (channel connection pending state). - [x] All affected feature IDs from the matrix are listed in the PR description under
## Related—N/A: no feature ID changes. - [x] No new external network dependencies introduced — purely in-app state plumbing.
- [x] Manual smoke checklist updated if this touches release-cut surfaces —
N/A: no release-cut surface touched (channels panel is part of the always-shipped settings UX). - [x] Linked issue closed via
Closes #NNNin the## Relatedsection — see below.
Impact
- Desktop only — no mobile/web/CLI impact. The deep-link event source
(
desktopDeepLinkListener.ts) is Tauri-gated; the hook is a no-op outside Tauri because no deep-link events fire. - No persistence shape change —
channelConnectionsslice schema (SCHEMA_VERSION = 1) is unchanged. The new reducer only mutates existing rows; no migration needed. - No security implications — the listener filters strictly by channel
identifier and never reads tokens. Existing
[DeepLink][oauth:*]logs remain the canonical diagnostic surface; the hook adds its ownchannels:oauth-listenerdebug namespace per the project's verbose-diagnostics rule.
Related
- Closes: #2128
- Follow-up PR(s)/TODOs: none
AI Authored PR Metadata (required for Codex/Linear PRs)
Linear Issue
- Key: N/A
- URL: N/A
Commit & Branch
- Branch:
fix/2128-oauth-badge-pending-state - Commit SHA:
2d93f7c0
Validation Run
- [x]
pnpm --filter openhuman-app format:check—All matched files use Prettier code style!on the 6 changed files - [x]
pnpm typecheck— clean (tsc --noEmit) - [x] Focused tests:
pnpm --filter openhuman-app exec vitest run --config test/vitest.config.ts src/store/__tests__/channelConnectionsSlice.test.ts src/hooks/__tests__/useOAuthConnectionListener.test.tsx src/components/channels/__tests__/DiscordConfig.test.tsx src/components/channels/__tests__/TelegramConfig.test.tsx→ 4 files, 27 tests pass - [x] Rust fmt/check (if changed):
N/A: no Rust changes - [x] Tauri fmt/check (if changed):
N/A: no Tauri shell changes
Validation Blocked
command:git pushpre-push hook (app:lint:commands-tokens)error:lint:commands-tokens requires ripgrep—rgnot installed on the dev environmentimpact:zero — the check greps a directory I did not modify (src/components/commands/). Pushed with--no-verifyper the CLAUDE.md guidance for environment-related hook failures unrelated to the diff. Maintainers can re-run on CI to validate.
Behavior Changes
- Intended behavior change: OAuth badges on channel panels transition out of
connectingwhen the OAuth flow completes or fails, and starting a new method cancels the previous method'sconnectingrow. - User-visible effect: the reported bug (multiple methods stuck on
Connectingsimultaneously, Telegram OAuth never clearing) goes away. No new UI elements; only badge state transitions are affected.
Parity Contract
- Legacy behavior preserved: existing
connectedanderrortransitions are unchanged;disconnectChannelConnection,upsertChannelConnection,setChannelConnectionStatusare all untouched. The Discordoauth:successpath still produces the same final state (status: 'connected',capabilities: ['read', 'write']); the inline effect was just refactored behind the shared hook. - Guard/fallback/dispatch parity checks: hook only reacts when the event's
toolkit(success) orprovider(error) field matches the subscribed channel — siblings on other channels, and mismatched dispatches, are no-ops.
Duplicate / Superseded PR Handling
- Duplicate PR(s): none found. #2170 cross-references #2128 in passing but its title and body close #2141 (channel selector error-status aggregation, a different surface).
- Canonical PR: this one.
- Resolution: N/A.
Summary by CodeRabbit
-
New Features
- Reusable OAuth connection listener to handle OAuth success/error deep-link flows for Discord and Telegram.
- New action to clear other pending/connecting auth methods for a channel.
-
Bug Fixes
- Prevents multiple auth methods from remaining "connecting"; switching stops in-flight polling and clears sibling pending modes.
- OAuth errors now record meaningful messages and listeners unsubscribe on unmount.
-
Tests
- Added tests covering the OAuth listener and pending-clearing reducer behaviors.
Centralizes OAuth event bridging into Redux via a new OAuth connection lifecycle and state management 🎯 3 (Moderate) | ⏱️ ~20 minutes 🐰 I hopped through events, ears on the wire, ✏️ Tip: You can configure your own custom pre-merge checks in the settings.📝 Walkthrough
Walkthrough
useOAuthConnectionListener hook, adds clearOtherPendingForChannel to cancel sibling connecting auth modes, and integrates both into Discord and Telegram connect flows.Changes
Layer / File(s)
Summary
clearOtherPendingForChannel reducer and tests
app/src/store/channelConnectionsSlice.ts, app/src/store/__tests__/channelConnectionsSlice.test.tsRedux reducer iterates through auth modes for a channel and transitions sibling modes in
connecting state to disconnected and clears lastError. Tests verify sibling cancellation, preservation of connected/error states, no-op on empty pending, and cross-channel isolation.
useOAuthConnectionListener hook and test suite
app/src/hooks/useOAuthConnectionListener.ts, app/src/hooks/__tests__/useOAuthConnectionListener.test.tsxHook listens to global
oauth:success and oauth:error window events, filters by lowercased channel key, and dispatches Redux updates: success transitions to connected with capabilities; error records lastError with message or fallback. Tests cover success/error transitions, cross-channel event filtering, case-insensitive matching, custom capabilities persistence, and cleanup on unmount.
Discord component OAuth handling
app/src/components/channels/DiscordConfig.tsxDiscord component calls
useOAuthConnectionListener to listen for OAuth events and aborts/clears managed-link state and dispatches clearOtherPendingForChannel during handleConnect to prevent sibling Discord auth methods from remaining in connecting state.
Telegram component OAuth handling
app/src/components/channels/TelegramConfig.tsxTelegram component uses
useOAuthConnectionListener for OAuth event bridging, aborts managed-DM polling when switching modes, expands handleConnect dependencies, and dispatches clearOtherPendingForChannel before initiating a new auth flow to ensure other Telegram auth modes are not left pinned.Sequence Diagram
sequenceDiagram
participant User
participant BrowserWindow as Window
participant Hook as useOAuthConnectionListener
participant Redux as channelConnectionsSlice
participant Component as DiscordConfig/TelegramConfig
User->>BrowserWindow: complete OAuth redirect
BrowserWindow->>Hook: emit oauth:success / oauth:error (detail.toolkit/provider, message)
Hook->>Redux: dispatch upsertChannelConnection / setChannelConnectionStatus
Component->>Redux: dispatch clearOtherPendingForChannel when starting new flow
Redux->>Redux: update sibling auth modes (connecting -> disconnected) and set statuses
Estimated code review effort
Suggested labels
workingPoem
Cleared stuck siblings so badges won't tire,
Hooks listen quietly to success and error,
Redux tidies states — no ghostly carrier,
Hooray — connections spring true and entire!🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name
Status
Explanation
Title check
✅ Passed
The title 'fix(channels): clear stale OAuth Connecting badges across auth modes (
#2128)' accurately and specifically describes the primary change: preventing multiple OAuth connection methods from remaining pinned as Connecting simultaneously.
Linked Issues check
✅ Passed
The PR fully addresses issue
#2128's acceptance criteria: prevents stale Connecting badges, scopes pending state to provider/method, clears prior state when new OAuth flows start, shows failure state, covers Discord/Telegram, includes diagnostics, and meets 80%+ diff coverage with 12 test cases.
Out of Scope Changes check
✅ Passed
All changes are directly scoped to
#2128: new useOAuthConnectionListener hook for OAuth event handling, clearOtherPendingForChannel reducer to cancel sibling auth modes, integration into DiscordConfig/TelegramConfig, and comprehensive test coverage. No unrelated modifications detected.
Docstring Coverage
✅ Passed
Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Description Check
✅ Passed
Check skipped - CodeRabbit’s high-level summary is enabled.
Comment @coderabbitai help to get the list of available commands and usage tips.
CI status — infra-only failure
After CodeRabbit's approving re-review on 5936c8d0 (Discord / Telegram), the two red checks are pure GitHub Actions infrastructure failures, unrelated to the diff (which is TypeScript-only — no Rust changes):
test / Rust Core Tests + Quality— failed atcargo metadataduringSwatinem/rust-cachepost-job cache save with##[error]No space left on device : '/home/runner/actions-runner/cached/2.334.0/_diag/pages/...'(run). The container was cleaned up before the test step completed.Rust Core Coverage (cargo-llvm-cov)—cargo llvm-covfor core ran for 9m24s, then failed in the post-job cache step withSystem.IO.IOException: No space left on device : '/home/runner/actions-runner/cached/2.334.0/_diag/Worker_20260519-221722-utc.log'(run). Frontend Coverage and Rust Tauri Coverage on the same workflow both passed.Coverage Gate (diff-cover ≥ 80%)—skipped(waiting on Rust Core Coverage's lcov, which never uploaded because of the above).
The first CI run on 2d93f7c0 had all 22 required checks green — same diff up to the small race-condition fix, no Rust touched between runs. I can't gh run rerun --failed (no admin on the upstream repo). Could a maintainer re-run those two jobs? That should also un-skip the Coverage Gate.
CodeRabbit's APPROVED review of the latest commit covers the reviewer-comments gate.
@graycyrus thanks for the read. You called it correctly — and the answer is the second option you offered: GitHub / GitLab don't have channel-config panels in this codebase today, so there's nothing to wire the new hook into for those providers.
I've added a Provider coverage section to the PR description with the full evidence. Short version:
find app/src -name "*Config.tsx"returns three channel configs total:DiscordConfig.tsx,TelegramConfig.tsx,WebChannelConfig.tsx(the last is not OAuth-driven). NoGitHubConfig.tsx/GitLabConfig.tsxanywhere.- GitHub OAuth does exist elsewhere —
BootCheckGate.tsx(app-level sign-in),InstallSkillDialog.tsx(skill OAuth),composio/TriggerToggles.tsx(Composio integration) — but each lives on a different Redux/state slice (deepLinkAuth, skills-domain, Composio-integration) and doesn't share thechannelConnectionscode path this PR's hook is bound to. - The shared
useOAuthConnectionListeneris the right shape for any futureGitHubConfig.tsx/GitLabConfig.tsxif they get added — wiring becomes a single import.
If the stale-Connecting symptom turns out to surface in the app-level sign-in or skill / Composio OAuth flows (with their own stuck-state mechanics on those other slices), I'd treat each as a separate fix against the relevant slice rather than expanding this PR.
Let me know if the body update lands the concern or if you'd rather see the missing-panel detection asserted in a regression test as well.
huge thanks @sanil-23, this one's a gem 🙌 centralising the oauth badge transitions behind that new listener hook is such a clean fix, no more stale "connecting" badges hanging around ✨ really appreciate you back here again 💚