Gmail connection and sync
Learn about the restricted Matrix Gmail pilot, Google authorization, connection choice, AI data use, retained copies, deletion and rollout requirements.
Maintained by the Matrix OS team. Product instructions are updated with the supported workflow.
Matrix-owned Gmail authorization lets Matrix call Google's Gmail API directly. You sign in with Google and approve access; you need no API keys or developer credentials. This connects your mailbox to Matrix and is separate from signing in to your Matrix account.
Rollout requires platform setup
This connection is not yet enabled for general use. It requires a runtime release with direct Gmail support, a configured Matrix Google OAuth client, and the Google verification required for public access. An unavailable connection does not mean you need to supply your own credentials.
Connecting your account
Once enabled, open Settings > Connect Apps, select Gmail, and choose Connect or Add account. Sign in to the intended Google account and review the Google consent screen. If the browser is not signed in to Matrix, first complete the Matrix browser sign-in; this can be needed when opening the link from Electron Desktop or Native Mobile. Matrix checks the initiating owner before redirecting to Google. Matrix binds the resulting credential to the exact Matrix owner and Gmail account that completed authorization. Label work and personal accounts clearly and select the intended connection for each task.
Existing Pipedream accounts remain usable. They do not automatically become Matrix-owned connections: reconnect Gmail explicitly to authorize the new path. Check which account an app or bot is bound to before replacing a connection. Saved sources must be rebound deliberately when their selected connection is removed or replaced; they must not silently switch to another mailbox.
Requests through a Matrix-owned Gmail connection go directly to Google and do not execute through Pipedream's Connect proxy. This does not cancel a Pipedream subscription or remove charges from existing Pipedream accounts or other apps. Google still applies its API quotas and account restrictions.
Internal pilot and connection choice
Invited testers can choose Connect with Matrix (internal preview) or Connect with Pipedream when adding Gmail. The choices use separate consent flows. Other users continue connecting through Pipedream. The available choices come from the server; the app does not infer staff membership from an email domain.
You can keep a connection through each method for the same mailbox. Each Gmail account shows a Matrix or Pipedream connection-method badge independently of its editable account label and email address. Older client/server combinations may show Method unavailable; an account name does not establish its method. Give accounts distinct labels, such as “Work” and “Personal”, and select the intended connection in each task. To verify the pilot, compare read-only results from both connections against the same synthetic messages. Matrix never silently retries a send through the other connection; comparing sends by repeating them can send two messages. Approve each test write deliberately.
Google's Testing audience requires explicitly listed Google accounts, with up to 100 test users. Gmail test authorizations expire after seven days, including refresh tokens, so testers must reconnect periodically. Workspace administrator restrictions can also prevent consent. See Google's audience and testing rules. An internal Matrix pilot does not by itself qualify the Google project for Google's organization-only Internal audience or production approval.
Operators configure GMAIL_OAUTH_INTERNAL_CLERK_IDS as a comma-separated list
of up to 100 unique immutable Clerk user IDs. An empty list denies all direct
Gmail access even when the feature switch is enabled. Keep real account IDs and
Google test email addresses in private operations records. For the Cloud Run
workflow, put the ID list in the masked repository secret of the same name;
never commit it to public configuration. Adding someone requires both Matrix
pilot eligibility and Google test access. Removing someone from the pilot blocks
direct consent and mailbox actions while retaining disconnect and account deletion.
Access and approvals
Matrix requests gmail.modify for the existing
read, search, send, and label actions. Google classifies this as a restricted
scope. Matrix does not request https://mail.google.com/, which permits
immediate permanent deletion. See Google's scope reference.
Google consent grants Matrix access to the mailbox. Each bot's read and write permissions still restrict what that bot can do. Sending mail, creating labels, and changing message labels remain write actions subject to the existing approval rules. Connecting Gmail does not grant a bot unrestricted access or approve future writes in advance.
The Gmail action reference lists the available
actions. modify_message can archive a message by removing INBOX or mark it
read by removing UNREAD. Matrix rejects TRASH label changes and does not
expose permanent deletion. send_email retains its plain-text interface;
sending attachments is outside this action.
get_attachment retrieves complete attachments up to 1 MiB decoded on
runtime releases that expose it. Larger or malformed attachments fail rather
than returning a truncated success. In bot workflows, attachments are staged in
that bot's workspace and returned as file references, rather than putting binary
contents into the model's conversation. Retained Gmail attachments have a cap
of 16 files and 16 MiB per bot workspace; remove retained files to free slots.
These downloads do not enable uploads
from a phone or computer; native device connections and uploads are deferred.
Google data and AI tasks
A requested Gmail action can retrieve account metadata, message headers and bodies, labels, history records and attachments. An AI task that reads or summarizes this material makes it available to the model provider or user-configured agent handling that task. The recipient depends on the selected model, credentials and harness configuration. Pipedream processes calls made through a Pipedream connection; a Matrix-owned direct connection calls Google without that proxy. Both methods can return data to your Matrix workspace and the agent carrying out your request.
If you enable Jev email triage, bounded message text and headers also pass through Matrix's funded relay and Cloudflare AI Gateway for classification with the Typesafe Jev model. That is an additional processing path to review; choosing a provider for your agent conversation does not remove it.
Optional ordinary chat-usage analytics is a separate feature, off by default. It excludes Gmail-derived, mixed and unknown-origin context, including saved or resumed conversations carrying that context. Shared and imported chats are also excluded. The selected Matrix classifier processes only sampled ordinary chat text through Cloudflare Workers AI and retains tags and usage metadata, rather than raw classifier text, in the owner's workspace database for reports covering up to 30 days. Expired metadata is hidden from reports and periodically removed while the configured analytics service runs. It uses Matrix AI credits after a separate in-app disclosure and opt-in. Coverage is limited to Matrix Chat and Bots using Matrix's model broker on that computer; external coding-agent harnesses are not covered. Task labels are estimates and missing usage measurements remain unknown. Stopping analytics retains existing facts until expiry or deletion; deleting analytics also disables collection. Neither action recalls content already sent or deletes separate provider records.
Google data is subject to Google's Workspace data policy, including Limited Use. It must serve the visible, consented feature and cannot be sold, used for advertising or used to train general-purpose AI models. Provider processing terms and settings must support that restriction. There is no blanket no-training assurance for every configurable provider or custom agent. Direct Gmail remains restricted while these controls and verification are prepared. Use synthetic test data during pilot qualification, and do not send real mailbox data to an unreviewed model provider or agent configuration.
Processing consent and provider choice
The pilot is being prepared for both Matrix-managed AI and owner-provided API providers. An API key is a separate billing source from a consumer ChatGPT or native coding-agent subscription. Connecting Gmail or an AI account does not grant processing consent. A successful connection or available model list does not qualify that provider for Google data.
Before the pilot can collect Google data for an AI task, it must match the selected account, credential generation, endpoint, model and adapter to a current reviewed processing profile. The normal task flow then shows the recipient, purpose and retention disclosure and requests affirmative owner approval before collection. An expired, revoked or changed profile or credential blocks use; Matrix must not silently switch providers, accounts or billing sources. Unknown or unsupported routes remain unavailable for Google data.
For Cloudflare-hosted Workers AI standard inference, Cloudflare describes transient content processing and no model training. Stateful features, enabled logs or caches, operational metadata and security or legal exceptions have different handling. Matrix's qualified request controls suppress payload logging and caching; they do not turn every Cloudflare route or owner-provided account into a reviewed processor. See Cloudflare's data usage policy.
The reviewed profile states the retention for registered task copies. Removing processing permission blocks subsequent processing and starts the registered copy-cleanup workflow; pending cleanup is not confirmed deletion. Disconnect, retained-copy deletion and provider deletion remain separate operations described below. The staff pilot still requires exact-build live validation before wider use; these disclosures do not assert Google or CASA approval.
Matrix marks integration tool results as untrusted external data and warns the agent not to follow instructions embedded in them. Bot attachments are returned as workspace file references with bounded reads. These protections reduce prompt injection risk; they do not guarantee that malicious email can never influence an agent. Review the selected account, recipients and proposed writes before approval. An email's instructions do not authorize another tool action or permission change.
See the Privacy Policy for Google data use, recipients, human access, retention and deletion, alongside the general AI provider and workspace terms.
Manage and delete Gmail data
Google authorization, the Matrix connection and retained copies are separate:
- Stop a task to stop its subsequent work. Data already sent to a model provider cannot be recalled by stopping it or changing providers.
- Disconnect the exact Gmail account in Settings > Connect Apps, or ask the agent to disconnect that named connection. A successful direct disconnect revokes the Google grant and removes Matrix's stored credential record. If disconnect fails, retry or contact support; a failed request is not proof that revocation completed. You can also review and remove access in your Google Account connections.
- Remove saved copies separately. Disconnecting does not delete copies
already stored in a conversation, agent session, generated output, bot
workspace or saved app import. For an installed app's retained source, ask the
owner agent to use
delete_imported_datafor the exact app and source; this deletes that local source and its saved pages. Remove downloaded attachments and generated files through workspace file controls. Deleting a visible chat alone should not be treated as proof that every underlying agent session or exported file was erased. - Request help with complete deletion. Email support@matrix-os.com from your Matrix account email. Identify the Gmail connection and whether you want selected retained data, a workspace or your full account deleted. Do not include passwords, OAuth tokens or private message contents. We verify ownership and explain any retained records or provider deletion steps. Account/workspace deletion and residual backups follow the Privacy Policy.
These Matrix cleanup actions do not delete messages held by Google. Deleting a saved import does not disconnect Gmail or remove copies made elsewhere. Copies already transferred to a model provider, a user-configured agent or another service follow that provider's retention and deletion process as well. Revoking one Matrix connection does not disconnect a separate Pipedream authorization.
Reading changes without rereading the mailbox
list_history reads changes after a previously saved startHistoryId string.
Each call returns one page, with 1–500 results when maxResults is specified.
Keep Gmail history IDs as strings throughout storage and requests: converting
them to JavaScript numbers can lose precision.
An app or worker that maintains its own mailbox view should:
- Fetch a bounded initial set of messages appropriate to its purpose and save a corresponding mailbox history ID. Record the query and coverage so this is not presented as a complete archive.
- Call
list_historywith the saved ID. Fetch only the changed messages needed by the app, applying label changes and deletions to its saved view. - Pass
nextPageTokenunchanged with the same starting ID and filters until all pages have been consumed. Set explicit page, item, byte, and time limits for the refresh operation. - Advance the checkpoint only after all pages and their updates succeed. Keep the prior checkpoint on malformed pages, failed reads, or limit exhaustion. Show partial progress and the last successful refresh time separately.
If Google returns HTTP 404 for an expired history ID, the direct Gmail action
returns HTTP 409 with code: "gmail_history_expired" and
resync_required: true. This is not an empty successful history response.
Rebuild the app's bounded baseline, reconcile its saved view, and establish a new
checkpoint after that replacement completes. Gmail does not guarantee a fixed
history retention window. See Google's synchronization guide.
The direct transport combines identical reads only while they are in progress for the same owner and account. It has no completed-response cache. Connecting Gmail does not start background imports, a mailbox rescan, or a watch scheduler. Durable cursor orchestration and a user-facing mailbox view remain the app or worker's responsibility.
Where a runtime provides saved connected-data imports, saved pages contain previously retrieved data, not a live view of the mailbox. Check the job status and coverage: a refresh timestamp alone does not prove that every message or every page has been imported. A partial initial import can retain pages already read. An incomplete replacement must retain the previous saved view and must not be advertised as fresh or complete. The last completed bounded refresh describes only the selected source and its filters.
Google watch support: future worker requirements
Gmail's watch API can notify a backend when a mailbox changes. This release does
not register watches or run a watch scheduler. A future implementation needs
Google Cloud Pub/Sub, a topic in the same project used for Gmail API requests,
Gmail's publish permission, authenticated delivery, durable owner/account
binding, and bounded history processing.
Google requires watch renewal at least every seven days and recommends daily renewal. Notifications carry a history ID rather than message contents, and can be delayed or dropped. A worker must reconcile history periodically and recover expired cursors instead of treating notification delivery as a complete mailbox sync. See Google's push guide.
Platform operator setup
These steps belong to the Matrix platform operator. Customers do not create Google projects or provide OAuth client secrets.
Inspect the existing Google project, enabled APIs, consent configuration, and
OAuth clients before creating another client. Enable the Gmail API in the chosen
project. Configure Google Auth Platform branding, audience, and data access for
gmail.modify, then create or reuse a Web application OAuth client.
Register this exact production redirect URI:
https://app.matrix-os.com/api/integrations/gmail/oauth/callbackThe callback configured in Matrix must exactly match the registered URI. The flow requests offline access and uses one-use expiring state with PKCE. An authenticated launcher checks the initiating owner and binds the callback to that browser with an HttpOnly, Secure, SameSite=Lax cookie. Offline access allows server-side token refresh; users may still need to reconnect when Google revokes access. See Google's web-server OAuth guide.
Configure these server-only settings through the deployment's secret management:
GMAIL_OAUTH_CLIENT_ID: the registered web application's client ID.GMAIL_OAUTH_CLIENT_SECRET: its client secret.GMAIL_OAUTH_CALLBACK_URL: the exact registered callback above.GMAIL_CREDENTIAL_ENCRYPTION_KEY: a dedicated 32-byte key encoded as base64 or hex. Retain it securely so stored credentials remain decryptable.GMAIL_OAUTH_INTERNAL_CLERK_IDS: private bounded list of internal pilot account IDs; empty denies native access.GMAIL_OAUTH_ENABLED=true: enable only after the client, database, and encryption configuration are ready and the intended audience can authorize.
Credentials are encrypted with AES-GCM and bound to owner and account in the platform's PostgreSQL store. Tokens and client secrets must never be committed to a repository, printed in logs, or copied into customer workspaces.
For the platform's Cloud Run workflow, set the non-secret repository variables
for enablement, client ID, and callback URL. Store the client secret in
gmail-oauth-client-secret and the encryption key in
gmail-credential-encryption-key. Pin their positive numeric versions with
GMAIL_OAUTH_CLIENT_SECRET_VERSION and
GMAIL_CREDENTIAL_ENCRYPTION_KEY_VERSION; each defaults to 1. A configured
deployment checks that both versions are enabled and that the runtime service
account has Secret Manager access. A disabled deployment with complete client
metadata retains both secret bindings for disconnect and account-deletion
cleanup. Keep the callback equal to the deployment's HTTPS platform origin plus
/api/integrations/gmail/oauth/callback.
Disabling Gmail after rollout
The .env.example leaves the Gmail client ID, callback URL, client secret, and
encryption key blank, with the feature disabled. Unconfigured, disabled
deployments keep existing behavior unchanged.
Once Matrix-owned Gmail credentials have been stored, set
GMAIL_OAUTH_ENABLED=false to disable the feature, but retain the complete
configuration for the same Google OAuth client: its client ID, callback URL,
client secret, and the encryption key used for those stored credentials. Keep
both Secret Manager bindings and their configured versions available to the
runtime service account. Do not clear individual fields or substitute another
client or encryption key as a rollback step; incomplete configuration is
rejected.
Disabling the feature blocks new consent and direct Gmail API calls. The retained configuration lets disconnect and account deletion decrypt stored credentials and revoke their Google grants before removing the local credential records. These cleanup paths do not enable normal Gmail actions while the feature is off. Keep the complete configuration available while stored credentials still need disconnect or account-deletion cleanup.
Broad public rollout requires restricted-scope verification and the applicable CASA security assessment for server access to restricted Gmail data. Prepare the verified domains, accurate consent branding, public privacy policy describing Google data use, scope justification, and an actual authorization and scope-use demonstration. Google data-access review requires published branding and the requested submission material; Google's review then determines the required assurance level and assessment steps. A security assessment is a later verification step, not proof of prior Google approval. Keep Matrix pilot eligibility restricted independently of Google's publishing status. Testing access is not evidence of production approval. Follow Google's restricted-scope verification requirements.
Before enabling public access, verify consent, account selection, token refresh, disconnect, denied permissions, and history recovery using the configured deployment. Reconfirm the exact selected account and bot permissions after a reconnection.
How is this guide?
Connect Apps
Connect services such as Granola, Gmail, Google Calendar, GitHub, Slack, Discord, and X to Matrix OS, with scoped permissions and explicit approvals.
Apps
Use built-in Matrix OS apps and ask your agent to create new tools for your work. Learn how apps run and how to inspect the results they produce.
