> ## Documentation Index
> Fetch the complete documentation index at: https://klipy.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# How does Klipy's connection layer work under the hood?

> How Klipy's Nylas and Unipile connections handle OAuth, grant expiry, reconnects, disconnect cascades, and per-inbox limits.

This page explains the mechanism behind a Klipy connection. It covers how a grant gets created, how Klipy notices a broken one, what disconnecting deletes, and how the per-inbox limit gets enforced. It covers Nylas (email and calendar) and Unipile (LinkedIn, WhatsApp, Telegram).

## Two providers, one grant model

Klipy has no single "connections" table. Every connected account lands in one of three tables: `nylasGrants`, `sharedNylasGrants`, or `unipileGrants`. A thin `channels` facade domain wraps all three behind one discriminated `ChannelRef` — `{kind: "email" | "email_shared" | "linkedin" | "whatsapp" | "telegram", grantId}` — so downstream code never needs to know which provider a channel came from (`convex/domains/channels/lib/channelRef.lib.ts:12-19`).

The facade owns no rows of its own — it reacts to grant events from the two provider integrations.

## Making a connection

Nylas (Gmail, Outlook) and Unipile (LinkedIn, WhatsApp, Telegram) use different OAuth mechanics:

* **Nylas** uses OAuth2 PKCE. A Convex action calls `nylas.auth.urlForOAuth2PKCE` to get an authorization URL and a code-verifier secret. The secret is stored in a cookie, and the callback route exchanges the returned code for a grant with `nylas.auth.exchangeCodeForToken` (`convex/components/nylas/grant/actions/connectEmailForGrant.ts:47-53`; `app/api/nylas/connect/route.tsx:23-33`; `convex/components/nylas/grant/actions/oauth2Callback.ts:61-75`).
* **Unipile** issues a hosted-auth link instead of running its own OAuth dance. Klipy calls Unipile's `POST /api/v1/hosted/accounts/link` endpoint and gets back a URL that expires in 15 minutes (`convex/components/unipile/account/connect.ts:52`; `convex/components/unipile/account/adapters/hostedAuth.lib.ts:44-70`). The user finishes authentication inside Unipile's own hosted flow, and Unipile calls Klipy back on a webhook rather than a redirect (`convex/components/unipile/webhook/onAccountCreated.ts`).

Before either flow starts, Klipy checks that the org's subscription record has `status: "active"`. Every plan, including free, gets this status on signup, so the check only blocks a genuinely lapsed or ended subscription (`convex/components/nylas/grant/actions/connectEmailForGrant.ts:40-42`; `convex/components/unipile/account/connect.ts:41-49`). A free-tier subscription is created with `status: "active"` from the start (`convex/domains/subscriptions/adapters/reconcileOrgBillingChain.ts:119-124`).

Klipy also shows a provider-specific verification checklist before redirecting. For Google, it tells the user to confirm the URL starts with `accounts.google.com` and the app is certified under "Vire Technology Solutions Limited". For Microsoft, the checklist names `login.microsoftonline.com`. For WhatsApp, it tells the user the linked session will show as "Ubuntu", since Unipile runs that session inside a virtual machine (`app/(auth)/oauth/nylas/connect/(components)/pre-connection-render.tsx:68-92`; `app/(auth)/oauth/social/connect/(components)/pre-connection-render.tsx:73-93`).

## The inbox-limit gate

A second, separate check runs once the provider hands back a real account: does the org have room for one more inbox. `canConnect` resolves the org's tier limit and its current usage, then compares them (`convex/domains/channels/lib/canConnect.lib.ts:35-45`).

The limit comes from `getInboxLimit`, keyed on the subscription's `type`:

| Subscription | Inbox limit |
| - | - |
| `free` | 2 |
| `subscription`, `status: "active"` | Unlimited |
| `subscription`, not active | 2 |
| `lifetime`, tier 1 | 1 (or `managedInboxQuantity` override) |
| `lifetime`, tier 2 | 3 (or `managedInboxQuantity` override) |
| `lifetime`, tier 3 | 10 (or `managedInboxQuantity` override) |
| No subscription record found | 2 (fallback) |

(`convex/domains/subscriptions/utils/getInboxLimit.lib.ts:11-30`.)

Usage is counted per organization, not per user. It pools every grant kind together — personal Nylas grants, shared Nylas grants, and Unipile grants all count against the same number (`convex/domains/channels/primitives/count.ts:16-31`).

The two providers enforce this gate at different points. Nylas checks it inside the OAuth callback, right before writing the grant. It skips the check entirely when the callback is only refreshing an existing grant, so a reconnect can never hit the limit (`convex/components/nylas/grant/actions/oauth2Callback.ts:48-56`). Unipile checks it inside the `account.created` webhook handler, after the user has already finished hosted auth with the provider (`convex/components/unipile/webhook/onAccountCreated.ts:64-70`).

## Noticing a broken connection

Nylas and Unipile grants track health differently.

A Nylas grant carries a `state` of `valid`, `expired`, or `invalid`. On the transition to `expired`, Klipy schedules a reconnect email, throttled to once every 24 hours per grant. A transition to `invalid` instead logs a blocking error and pauses the channel's tracking rows. No duplicate email fires, since the import path that produces `invalid` already surfaces reconnect UI inline (`convex/domains/nylasGrants/triggers/onGrantStateChanged.ts:10,35-96,98-135`).

A Unipile grant carries a `status` of `OK`, `CREDENTIALS`, `ERROR`, `STOPPED`, or `CONNECTING`, normalized from Unipile's raw values by a single mapping function (`convex/components/unipile/_shared/mapAccountStatus.lib.ts:33-47`). A transition into `CREDENTIALS` or `ERROR` schedules the same kind of throttled reconnect email, also capped at once per 24 hours (`convex/domains/unipileGrants/triggers/onGrantStatusChanged.ts:11,29,51-55`).

Both webhook paths are authenticated differently. Nylas signs its webhook body, and Klipy verifies it with an HMAC-SHA256 digest compared in constant time before trusting the payload (`convex/components/nylas/webhook/verify.ts:33-50`). Unipile's account webhook carries no signature. Instead, it echoes back the `org|user` identifier Klipy embedded in the hosted-auth link when it created it. Klipy trusts that string alone as the account's owner (`convex/http.ts:1208-1229`; `convex/components/unipile/account/connect.ts:52`).

## The settle check, and a 15-minute staleness rule

Unipile only fires a status webhook when a status changes, so one dropped delivery can leave a grant stuck in `CONNECTING` indefinitely. Klipy runs a self-rescheduling "settle check" after every new connect and reconnect. It re-reads the account straight from Unipile. If still `CONNECTING`, it reschedules itself — at 60 seconds, then 3, 10, and 30 minutes, then 2 and 6 hours. After that chain, it gives up and marks the grant `ERROR` (`convex/components/unipile/account/settleGrant.ts:23-29,81,178-201`).

Independently of that chain, the UI treats any grant stuck in `CONNECTING` for more than 15 minutes as errored. This happens even before the settle check exhausts its retries. A user never has to wait out the full backoff to see a working reconnect button (`lib/unipile-grants.ts:9,29-32,48-51`).

## Reconnecting without a new grant

Reconnecting re-authenticates an existing grant rather than creating a new one. For Nylas, the reconnect control appears only to an org admin, only when the grant's state is `invalid`, and only for a non-shared inbox. Clicking it reopens the same OAuth popup used to connect (`app/settings/channels/components/email-accounts.tsx:252-262`).

For Unipile, the control appears whenever the grant is errored. Clicking it requests a fresh hosted-auth link scoped to the same `accountId`, valid for one hour instead of 15 minutes (`app/settings/channels/components/social-accounts.tsx:274-283`; `convex/components/unipile/account/reconnect.ts:71-77`). If the underlying Unipile account was removed on the provider's side, the reconnect link request comes back empty. Klipy then tells the user to disconnect and reconnect from scratch instead (`convex/components/unipile/account/reconnect.ts:100-113`; `app/api/social/reconnect/route.tsx:27-36`).

## Disconnecting, and what it deletes

Disconnecting requires typing the exact account email (Nylas) or account name (Unipile) before the button enables. This is deliberate friction in front of a destructive, cascading action (`app/settings/channels/components/email-accounts.tsx:387-399`; `app/settings/channels/components/social-accounts.tsx:388-403`).

> [!WARNING]
>
> Klipy never disconnects an account until you type its email or name to confirm.

Removing a non-shared Nylas grant schedules seven cascades (`convex/domains/nylasGrants/triggers/onGrantRemoved.ts:33-86`):

* Delete its agent drafts
* Delete its draft styles
* Delete its import jobs
* Nullify the grant reference on its meetings
* Nullify the grant reference on its interactions
* Destroy its meeting links
* Remove it from the channel registry

Removing a Unipile grant schedules six cascades (`convex/domains/unipileGrants/triggers/onGrantRemoved.ts:21-79`):

* Delete its social interactions
* Delete its social drafts
* Nullify the grant reference on its interactions
* Delete its chat signals
* Delete its email draft styles
* Remove it from the channel registry

Shared Nylas inboxes skip this cascade entirely — the code only runs it when `!shared`. Disconnecting a shared inbox orphans its data instead of deleting it (`convex/domains/nylasGrants/triggers/onGrantRemoved.ts:19-31`).

## The first sync after connecting

Connecting a personal email account does not start a historical import immediately. The grant-created trigger instead schedules a fallback "kick" 3 minutes later. This way, an explicit consent decision the user makes in that window — scan now, or later — is never silently overridden (`convex/v3/core/object/nylasImportJobs/internals.ts:14-29`).

When the onboarding import does run, it pulls roughly the last 90 days of mail — a `"3_months"` time range. It caps at 500 threads total, regardless of how much history fits in that window (`convex/v3/core/object/nylasImportJobs/internals.ts:81-86`; `convex/applications/importers/emails/importWorkflow.ts:64,430-441`). This fallback only fires for users still inside their onboarding window. So connecting a second inbox later, as an established customer, never re-triggers a bulk backfill (`convex/domains/nylasGrants/triggers/onGrantCreated.ts:127-158`).

## Limits worth knowing

| Behavior | Limit |
| - | - |
| Inbox limit, free plan | 2, pooled across email and social grants org-wide |
| Inbox limit, active paid subscription | Unlimited |
| Inbox limit, lifetime tiers 1 / 2 / 3 | 1 / 3 / 10, unless overridden per user |
| Unipile connect-link expiry | 15 minutes |
| Unipile reconnect-link expiry | 1 hour |
| Unipile settle-check backoff | 60s, 3m, 10m, 30m, 2h, 6h, then marked `ERROR` |
| Unipile stale-`CONNECTING` threshold (UI) | 15 minutes |
| Reconnect-email throttle (both providers) | Once per 24 hours per grant |
| Onboarding import consent grace period | 3 minutes |
| Onboarding import window / thread cap | \~90 days / 500 threads |

## What Klipy stores and sends

Nylas is the pipe for Gmail and Outlook. Email messages, threads, calendar events, and availability come in; sends, drafts, and booking events go out over the same grant. Nylas webhook payloads carry only the event and object identifiers needed to look up the corresponding data. Klipy verifies each with the HMAC signature described above before acting on it (`convex/components/nylas/webhook/verify.ts:33-50`).

Unipile is the pipe for LinkedIn, WhatsApp, and Telegram. Chats, message previews, and, for LinkedIn, profile data come in; social sends go out over the same grant.

Both integrations are scoped to a single grant per connected account; nothing about one connected account's data is readable through another account's grant.

## What this does not do

Klipy does not run a background poll to check whether a connection is still healthy. Every state or status transition described above is reactive. It fires from a provider webhook, or from the settle check's own self-scheduled re-read — never from a health-check cron (`convex/domains/nylasGrants/triggers/onGrantStateChanged.ts`; `convex/components/unipile/account/settleGrant.ts`). A stale connection is surfaced only when the provider tells Klipy about it, or the next time a read against that grant fails.

## Related guides

> [card] [How do my connections work in Klipy?](https://klipy.ai/docs/get-started/your-connections.md)
>
> The channels overview: what each connection unlocks and where to connect it.

> [card] [How do I connect email and calendar?](https://klipy.ai/docs/get-started/connecting-email-calendar.md)
>
> Step-by-step Gmail and Outlook setup.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.