openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(channels): clear stale OAuth Connecting badges across auth modes (#2128)

Open sanil-23 opened this issue 6 months ago • 2 comments

Summary

  • Centralises OAuth deep-link → channel-badge transitions behind a new useOAuthConnectionListener hook so every channel panel handles both oauth:success and oauth:error consistently.
  • Adds a clearOtherPendingForChannel reducer so starting a connect flow on one auth mode drops any sibling auth mode that's still mid-connecting on the same channel.
  • Wires DiscordConfig and TelegramConfig onto 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):

  • DiscordConfig had a per-component oauth:success listener but no oauth:error listener — failed OAuth attempts never transitioned the badge out of connecting.
  • TelegramConfig had neither — completed and failed OAuth attempts left the badge pinned.
  • Both panels set connecting on the chosen auth mode but never cancelled any sibling auth mode that was already pending. Triggering a second OAuth method on Discord (OAuth Sign-in then Login with OpenHuman, or the reverse) left both methods badged Connecting simultaneously.

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:

  1. Mount useOAuthConnectionListener({ channel: <name>, authMode: 'oauth' }) at the top of the component (replacing the bespoke effect on Discord; net-new on Telegram).
  2. Dispatch clearOtherPendingForChannel at the start of handleConnect before setting their own auth mode to connecting.

Tradeoffs

  • The cancellation transition is disconnected, not a new cancelled state. Adding a dedicated state would expand the ChannelConnectionStatus union 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:coverage locally 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 #NNN in the ## Related section — 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 — channelConnections slice 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 own channels:oauth-listener debug 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 push pre-push hook (app:lint:commands-tokens)
  • error: lint:commands-tokens requires ripgrep — rg not installed on the dev environment
  • impact: zero — the check greps a directory I did not modify (src/components/commands/). Pushed with --no-verify per 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 connecting when the OAuth flow completes or fails, and starting a new method cancels the previous method's connecting row.
  • User-visible effect: the reported bug (multiple methods stuck on Connecting simultaneously, Telegram OAuth never clearing) goes away. No new UI elements; only badge state transitions are affected.

Parity Contract

  • Legacy behavior preserved: existing connected and error transitions are unchanged; disconnectChannelConnection, upsertChannelConnection, setChannelConnectionStatus are all untouched. The Discord oauth:success path 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) or provider (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.

Review Change Stack

sanil-23 avatar May 19 '26 21:05 sanil-23

📝 Walkthrough

Walkthrough

Centralizes OAuth event bridging into Redux via a new useOAuthConnectionListener hook, adds clearOtherPendingForChannel to cancel sibling connecting auth modes, and integrates both into Discord and Telegram connect flows.

Changes

OAuth connection lifecycle and state management

Layer / File(s) Summary
clearOtherPendingForChannel reducer and tests
app/src/store/channelConnectionsSlice.ts, app/src/store/__tests__/channelConnectionsSlice.test.ts
Redux 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.tsx
Hook 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.tsx
Discord 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.tsx
Telegram 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

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

working

Poem

🐰 I hopped through events, ears on the wire,
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 19 '26 21:05 coderabbitai[bot]

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 at cargo metadata during Swatinem/rust-cache post-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-cov for core ran for 9m24s, then failed in the post-job cache step with System.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.

sanil-23 avatar May 19 '26 22:05 sanil-23

@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). No GitHubConfig.tsx / GitLabConfig.tsx anywhere.
  • 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 the channelConnections code path this PR's hook is bound to.
  • The shared useOAuthConnectionListener is the right shape for any future GitHubConfig.tsx / GitLabConfig.tsx if 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.

sanil-23 avatar May 20 '26 14:05 sanil-23

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 💚

senamakel avatar May 20 '26 21:05 senamakel