Skip to content

Self-improving AI Employees for everyone

fix: Fix Google OAuth token mismatch, add Google status to broadcaster, add gmail polling trigger

trohitg6854e89785a3
diff --git a/CLAUDE.md b/CLAUDE.md
index 2545ee3f..438b734f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -364,7 +364,7 @@ class CacheEntry(SQLModel, table=True):
## Codebase Summary
- **Hybrid architecture**: Node.js + Python + React TypeScript
-- **108 implemented workflow nodes** with clean service separation (6 AI models + 3 AI agents/memory + 13 specialized agents + 11 skills + 3 dedicated tools + 9 dual-purpose tools + 16 Android + 3 WhatsApp + 4 Twitter + 2 Social + 3 Location + 3 Code + 6 Utility + 6 Document + 2 Chat + 2 Scheduler + 1 Workflow + 26 Google Workspace + 1 Apify + 3 Search)
+- **89 implemented workflow nodes** with clean service separation (6 AI models + 3 AI agents/memory + 13 specialized agents + 11 skills + 3 dedicated tools + 9 dual-purpose tools + 16 Android + 3 WhatsApp + 4 Twitter + 2 Social + 3 Location + 3 Code + 6 Utility + 6 Document + 2 Chat + 2 Scheduler + 1 Workflow + 7 Google Workspace + 1 Apify + 3 Search)
- **WebSocket-First Architecture**: WebSocket as primary frontend-backend communication (87 message handlers)
- **Recent optimizations**: REST APIs replaced with WebSocket, AI endpoints migrated to Python, Android automation integrated
@@ -394,12 +394,7 @@ The project was completely refactored from schema-based node definitions to expl
- `src/nodeDefinitions/searchNodes.ts` - Search API nodes (braveSearch, serperSearch, perplexitySearch)
- `src/nodeDefinitions/androidServiceNodes.ts` - 16 Android service nodes (monitoring, apps, automation, sensors, media)
- `src/nodeDefinitions/locationNodes.ts` - Google Maps and location services
-- `src/nodeDefinitions/gmailNodes.ts` - Gmail integration (4 nodes)
-- `src/nodeDefinitions/calendarNodes.ts` - Google Calendar integration (4 nodes)
-- `src/nodeDefinitions/driveNodes.ts` - Google Drive integration (4 nodes)
-- `src/nodeDefinitions/sheetsNodes.ts` - Google Sheets integration (3 nodes)
-- `src/nodeDefinitions/tasksNodes.ts` - Google Tasks integration (5 nodes)
-- `src/nodeDefinitions/contactsNodes.ts` - Google Contacts integration (6 nodes)
+- `src/nodeDefinitions/googleWorkspaceNodes.ts` - All Google Workspace nodes (7 consolidated nodes)
- `src/nodeDefinitions/whatsappNodes.ts` - WhatsApp messaging integration (3 nodes)
- `src/nodeDefinitions/twitterNodes.ts` - Twitter/X integration (4 nodes: send, search, user, receive)
- `src/nodeDefinitions/socialNodes.ts` - Unified social messaging nodes (socialReceive, socialSend)
@@ -973,46 +968,19 @@ TWITTER_CLIENT_SECRET=your_client_secret
TWITTER_REDIRECT_URI=http://localhost:3010/api/twitter/callback
```
-### Google Workspace Nodes (26 nodes)
-Unified Google Workspace integration supporting Gmail, Calendar, Drive, Sheets, Tasks, and Contacts. All services share a single OAuth connection with combined scopes. All nodes are execution-ready with Run button in parameter panel.
-
-#### Gmail Nodes (4 nodes)
-- **gmailSend**: **Dual-purpose node** - Send emails with attachments. Works as workflow node OR AI Agent tool.
-- **gmailSearch**: **Dual-purpose node** - Search emails using Gmail query syntax.
-- **gmailRead**: **Dual-purpose node** - Read email content by message ID.
-- **gmailReceive**: Event-driven trigger for incoming emails.
-
-#### Calendar Nodes (4 nodes)
-- **calendarCreate**: **Dual-purpose node** - Create calendar events with title, time, description, attendees, location.
-- **calendarList**: **Dual-purpose node** - List events in date range with filtering.
-- **calendarUpdate**: **Dual-purpose node** - Update existing events.
-- **calendarDelete**: **Dual-purpose node** - Delete events by ID.
-
-#### Drive Nodes (4 nodes)
-- **driveUpload**: **Dual-purpose node** - Upload files from URL or path.
-- **driveDownload**: **Dual-purpose node** - Download files by ID.
-- **driveList**: **Dual-purpose node** - List files in folder with query.
-- **driveShare**: **Dual-purpose node** - Share files with users.
-
-#### Sheets Nodes (3 nodes)
-- **sheetsRead**: **Dual-purpose node** - Read data from spreadsheet range.
-- **sheetsWrite**: **Dual-purpose node** - Write data to specific range.
-- **sheetsAppend**: **Dual-purpose node** - Append rows to sheet.
-
-#### Tasks Nodes (5 nodes)
-- **tasksCreate**: **Dual-purpose node** - Create tasks with title, notes, due date.
-- **tasksList**: **Dual-purpose node** - List tasks with filters.
-- **tasksComplete**: **Dual-purpose node** - Mark task as complete.
-- **tasksUpdate**: **Dual-purpose node** - Update existing task.
-- **tasksDelete**: **Dual-purpose node** - Delete task by ID.
-
-#### Contacts Nodes (6 nodes)
-- **contactsCreate**: **Dual-purpose node** - Create contact with name, email, phone.
-- **contactsList**: **Dual-purpose node** - List contacts with pagination.
-- **contactsSearch**: **Dual-purpose node** - Search contacts by query.
-- **contactsGet**: **Dual-purpose node** - Get contact details by resource name.
-- **contactsUpdate**: **Dual-purpose node** - Update existing contact.
-- **contactsDelete**: **Dual-purpose node** - Delete contact.
+### Google Workspace Nodes (7 nodes)
+Consolidated Google Workspace integration with 6 unified operation-based nodes + 1 polling trigger. Each service node uses an `operation` parameter to select the action (e.g., gmail with operation: send/search/read). All services share a single OAuth connection with combined scopes.
+
+#### Consolidated Service Nodes (6 nodes)
+- **gmail**: **Dual-purpose node** - Operations: `send`, `search`, `read`. Handler: `handle_google_gmail()` dispatcher.
+- **calendar**: **Dual-purpose node** - Operations: `create`, `list`, `update`, `delete`.
+- **drive**: **Dual-purpose node** - Operations: `upload`, `download`, `list`, `share`.
+- **sheets**: **Dual-purpose node** - Operations: `read`, `write`, `append`.
+- **tasks**: **Dual-purpose node** - Operations: `create`, `list`, `complete`, `update`, `delete`.
+- **contacts**: **Dual-purpose node** - Operations: `create`, `list`, `search`, `get`, `update`, `delete`.
+
+#### Trigger Nodes (1 node)
+- **gmailReceive**: Polling-based trigger for incoming emails. Polls Gmail API at configurable interval (10-3600s). Parameters: `filter_query` (default: `is:unread`), `label_filter` (default: `INBOX`), `mark_as_read`, `poll_interval` (default: 60s). In deployment mode, uses `setup_polling_trigger` with baseline detection to avoid triggering on existing emails.
#### Google Workspace OAuth 2.0 Authentication
Authentication is handled via OAuth 2.0 flow in the Credentials Modal:
@@ -1053,10 +1021,11 @@ GOOGLE_WORKSPACE_SCOPES = [
**Key Files:**
| File | Description |
|------|-------------|
-| `server/services/google_oauth.py` | Unified OAuth 2.0 implementation |
+| `server/services/google_oauth.py` | OAuth 2.0 flow (authorization URL, token exchange) |
+| `server/services/handlers/google_auth.py` | Shared credential helper (`get_google_credentials()`) used by all 6 handlers |
| `server/config/google_apis.json` | API endpoints and scopes config |
| `server/routers/google.py` | OAuth callback and status endpoints |
-| `server/services/handlers/gmail.py` | Gmail handlers |
+| `server/services/handlers/gmail.py` | Gmail handlers + `handle_gmail_receive` polling trigger |
| `server/services/handlers/calendar.py` | Calendar handlers |
| `server/services/handlers/drive.py` | Drive handlers |
| `server/services/handlers/sheets.py` | Sheets handlers |
@@ -1064,23 +1033,26 @@ GOOGLE_WORKSPACE_SCOPES = [
| `server/services/handlers/contacts.py` | Contacts handlers |
| `server/models/database.py` | `GoogleConnection` model |
| `server/skills/productivity_agent/` | Google Workspace skills for AI agents |
-| `client/src/nodeDefinitions/gmailNodes.ts` | Gmail node definitions |
-| `client/src/nodeDefinitions/calendarNodes.ts` | Calendar node definitions |
-| `client/src/nodeDefinitions/driveNodes.ts` | Drive node definitions |
-| `client/src/nodeDefinitions/sheetsNodes.ts` | Sheets node definitions |
-| `client/src/nodeDefinitions/tasksNodes.ts` | Tasks node definitions |
-| `client/src/nodeDefinitions/contactsNodes.ts` | Contacts node definitions |
+| `client/src/nodeDefinitions/googleWorkspaceNodes.ts` | All 7 Google node definitions (consolidated) |
| `client/src/assets/icons/google/` | Official Google service SVG icons (n8n pattern) |
| `client/src/components/CredentialsModal.tsx` | Google Workspace panel |
-**Token Storage (Unified `google_*` prefix):**
-| Token Key | Description |
-|-----------|-------------|
-| `google_client_id` | OAuth 2.0 Client ID |
-| `google_client_secret` | OAuth 2.0 Client Secret |
-| `google_access_token` | Access token for API calls |
-| `google_refresh_token` | Refresh token for token renewal |
-| `google_user_info` | Connected user email and name |
+**Token Storage (Two Separate Systems):**
+
+Client ID and Secret are stored as API keys (user enters manually):
+| Key | Storage Method | Description |
+|-----|---------------|-------------|
+| `google_client_id` | `auth_service.get_api_key()` / `EncryptedAPIKey` table | OAuth 2.0 Client ID |
+| `google_client_secret` | `auth_service.get_api_key()` / `EncryptedAPIKey` table | OAuth 2.0 Client Secret |
+
+Access and refresh tokens are stored via OAuth system (after Google login):
+| Field | Storage Method | Description |
+|-------|---------------|-------------|
+| `access_token` | `auth_service.get_oauth_tokens("google")` / `EncryptedOAuthToken` table | Access token for API calls |
+| `refresh_token` | `auth_service.get_oauth_tokens("google")` / `EncryptedOAuthToken` table | Refresh token for renewal |
+| `email`, `name` | `auth_service.get_oauth_tokens("google")` / `EncryptedOAuthToken` table | Connected user info |
+
+**IMPORTANT**: All handlers use `get_google_credentials()` from `google_auth.py`, which reads tokens via `get_oauth_tokens()`. Never use `get_api_key("google_access_token")` — that reads from the wrong table.
**AI Agent Skills (productivity_agent folder):**
| Skill | Tools | Description |
@@ -4435,6 +4407,36 @@ await broadcaster.send_custom_event('task_completed', {
event_waiter.dispatch('email_received', email_data)
```
+### Polling Triggers (Gmail, Twitter)
+
+Some triggers require active API polling instead of waiting for externally dispatched events. These use `setup_polling_trigger` in `TriggerManager` instead of `setup_event_trigger`.
+
+**Architecture:**
+```
+setup_polling_trigger() → broadcasts "waiting" status
+ ↓
+ poller task: runs poll_coroutine(queue, is_running_fn)
+ ↓ ↓
+ polls API at interval → enqueues new items to asyncio.Queue
+ ↓
+ processor task: reads queue → calls on_event → spawns execution run
+```
+
+**Key differences from event triggers:**
+- Event triggers: `event_waiter.register()` + `wait_for_event()` (push-based)
+- Polling triggers: Custom poll coroutine + `asyncio.Queue` (pull-based)
+
+**Routing** (`server/services/deployment/manager.py`):
+```python
+if node_type in POLLING_TRIGGER_TYPES: # gmailReceive, twitterReceive
+ poll_coroutine = self._create_poll_coroutine(node_type, node_id, params)
+ await trigger_manager.setup_polling_trigger(...)
+```
+
+**Constants** (`server/constants.py`):
+- `POLLING_TRIGGER_TYPES`: `frozenset(['gmailReceive', 'twitterReceive'])`
+- These are also in `WORKFLOW_TRIGGER_TYPES` for trigger node detection
+
### Key Design Decisions
- **No Timeout**: Trigger nodes wait indefinitely; users cancel via Cancel button
@@ -4442,6 +4444,7 @@ await broadcaster.send_custom_event('task_completed', {
- **Generic Architecture**: Same execution flow for all trigger types via registry
- **Filter Functions**: Each trigger type builds its own filter from node parameters
- **asyncio.Future**: Simpler than asyncio.Event for single-value resolution
+- **Polling triggers**: Use asyncio.Queue + dedicated poll coroutine for APIs without push support
## Real-time Status WebSocket System
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index 2b3f0155..d2b179cf 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -34,6 +34,7 @@ import { DOCUMENT_NODE_TYPES } from './nodeDefinitions/documentNodes';
import { SEARCH_NODE_TYPES } from './nodeDefinitions/searchNodes';
import { SOCIAL_NODE_TYPES } from './nodeDefinitions/socialNodes';
import { APIFY_NODE_TYPES } from './nodeDefinitions/apifyNodes';
+import { GOOGLE_WORKSPACE_NODE_TYPES } from './nodeDefinitions/googleWorkspaceNodes';
import ParameterPanel from './ParameterPanel';
import LocationParameterPanel from './components/LocationParameterPanel';
import { useAppStore } from './store/useAppStore';
@@ -96,11 +97,8 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {
} else if (type === 'twitterSend' || type === 'twitterSearch' || type === 'twitterUser') {
// Twitter action nodes use SquareNode (twitterReceive is a trigger)
types[type] = SquareNode;
- } else if (type === 'gmailSend' || type === 'gmailSearch' || type === 'gmailRead') {
- // Gmail action nodes use SquareNode (gmailReceive is a trigger)
- types[type] = SquareNode;
- } else if (type.startsWith('calendar') || type.startsWith('drive') || type.startsWith('sheets') || type.startsWith('tasks') || type.startsWith('contacts')) {
- // Google Workspace nodes (Calendar, Drive, Sheets, Tasks, Contacts) use SquareNode
+ } else if (GOOGLE_WORKSPACE_NODE_TYPES.includes(type)) {
+ // Google Workspace nodes (gmail, gmailReceive, calendar, drive, sheets, tasks, contacts)
types[type] = SquareNode;
} else if (ANDROID_SERVICE_NODE_TYPES.includes(type)) {
// Android service nodes use SquareNode component
@@ -672,8 +670,8 @@ const DashboardContent: React.FC = () => {
if (!currentWorkflow) return;
// Check if there's at least one trigger node (workflow entry points)
- // Trigger types: start, cronScheduler, webhookTrigger, whatsappReceive, twitterReceive, workflowTrigger, chatTrigger, taskTrigger
- const triggerTypes = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'twitterReceive', 'workflowTrigger', 'chatTrigger', 'taskTrigger'];
+ // Trigger types: start, cronScheduler, webhookTrigger, whatsappReceive, twitterReceive, gmailReceive, workflowTrigger, chatTrigger, taskTrigger
+ const triggerTypes = ['start', 'cronScheduler', 'webhookTrigger', 'whatsappReceive', 'twitterReceive', 'gmailReceive', 'workflowTrigger', 'chatTrigger', 'taskTrigger'];
const hasTriggerNode = nodes.some(node => triggerTypes.includes(node.type || ''));
if (!hasTriggerNode) {
alert('No trigger node found in workflow.\n\nAdd a trigger node (Cron Scheduler, WhatsApp Receive, Webhook, Chat Trigger, etc.) to begin deployment.');
diff --git a/client/src/components/CredentialsModal.tsx b/client/src/components/CredentialsModal.tsx
index 6982ba6c..daac9c95 100644
--- a/client/src/components/CredentialsModal.tsx
+++ b/client/src/components/CredentialsModal.tsx
@@ -19,7 +19,7 @@ import QRCodeDisplay from './ui/QRCodeDisplay';
import ApiKeyInput from './ui/ApiKeyInput';
import { useApiKeys, ProviderDefaults, ProviderUsageSummary, APIUsageSummary } from '../hooks/useApiKeys';
import { useAppTheme } from '../hooks/useAppTheme';
-import { useWhatsAppStatus, useAndroidStatus, useTwitterStatus, useGmailStatus, useWebSocket, RateLimitConfig, RateLimitStats } from '../contexts/WebSocketContext';
+import { useWhatsAppStatus, useAndroidStatus, useTwitterStatus, useGoogleStatus, useWebSocket, RateLimitConfig, RateLimitStats } from '../contexts/WebSocketContext';
import { useWhatsApp } from '../hooks/useWhatsApp';
import {
OpenAIIcon, ClaudeIcon, GeminiIcon, GroqIcon, OpenRouterIcon, CerebrasIcon,
@@ -185,7 +185,7 @@ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey,
const whatsappStatus = useWhatsAppStatus();
const androidStatus = useAndroidStatus();
const twitterStatus = useTwitterStatus();
- const gmailStatus = useGmailStatus();
+ const googleStatus = useGoogleStatus();
// Tag style helper - consistent theming for status tags
@@ -392,7 +392,7 @@ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey,
return { connected: twitterStatus.connected, label: twitterStatus.connected ? `@${twitterStatus.username}` : 'Not Connected' };
}
if (item.panelType === 'gmail') {
- return { connected: gmailStatus.connected, label: gmailStatus.connected ? gmailStatus.email : 'Not Connected' };
+ return { connected: googleStatus.connected, label: googleStatus.connected ? googleStatus.email : 'Not Connected' };
}
return null;
};
@@ -1725,8 +1725,8 @@ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey,
}}
>
<Descriptions.Item label="Status">
- <Tag style={getTagStyle(gmailStatus.connected ? 'success' : 'error')}>
- {gmailStatus.connected ? 'Connected' : 'Not Connected'}
+ <Tag style={getTagStyle(googleStatus.connected ? 'success' : 'error')}>
+ {googleStatus.connected ? 'Connected' : 'Not Connected'}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="API Credentials">
@@ -1734,22 +1734,22 @@ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey,
{gmailCredentialsStored === null ? 'Checking...' : gmailCredentialsStored ? 'Configured' : 'Not configured'}
</Tag>
</Descriptions.Item>
- {gmailStatus.connected && gmailStatus.email && (
+ {googleStatus.connected && googleStatus.email && (
<Descriptions.Item label="Account">
<Space>
- {gmailStatus.profile_image_url && (
+ {googleStatus.profile_image_url && (
<img
- src={gmailStatus.profile_image_url}
- alt={gmailStatus.email}
+ src={googleStatus.profile_image_url}
+ alt={googleStatus.email}
style={{ width: 24, height: 24, borderRadius: '50%' }}
/>
)}
- <span style={{ fontFamily: theme.fontFamily.mono, fontSize: theme.fontSize.sm }}>{gmailStatus.email}</span>
- {gmailStatus.name && <span style={{ color: theme.colors.textSecondary }}>({gmailStatus.name})</span>}
+ <span style={{ fontFamily: theme.fontFamily.mono, fontSize: theme.fontSize.sm }}>{googleStatus.email}</span>
+ {googleStatus.name && <span style={{ color: theme.colors.textSecondary }}>({googleStatus.name})</span>}
</Space>
</Descriptions.Item>
)}
- {gmailStatus.connected && (
+ {googleStatus.connected && (
<Descriptions.Item label="Services">
<Space wrap size={[4, 4]}>
<Tag style={{ backgroundColor: `${theme.dracula.green}15`, borderColor: `${theme.dracula.green}40`, color: theme.dracula.green }}>Gmail</Tag>
@@ -1764,7 +1764,7 @@ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey,
</Descriptions>
{/* API Credentials Input - Only show if not connected */}
- {!gmailStatus.connected && (
+ {!googleStatus.connected && (
<div style={{ marginBottom: theme.spacing.xl }}>
<label style={{
display: 'block',
@@ -1848,7 +1848,7 @@ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey,
color: theme.colors.textSecondary,
lineHeight: 1.5,
}}>
- {gmailStatus.connected ? (
+ {googleStatus.connected ? (
<>Your Google Workspace account is connected. You can now use Gmail, Calendar, Drive, Sheets, Tasks, and Contacts nodes in your workflows.</>
) : gmailCredentialsStored ? (
<>Click Login with Google to authorize. A browser window will open for authentication.</>
@@ -1866,7 +1866,7 @@ const { validateApiKey, saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey,
paddingTop: theme.spacing.md,
borderTop: `1px solid ${theme.colors.border}`,
}}>
- {!gmailStatus.connected ? (
+ {!googleStatus.connected ? (
<Button
onClick={handleGmailLogin}
loading={gmailLoading === 'login'}
diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsx
index 6967f4e1..eaac9700 100644
--- a/client/src/components/parameterPanel/InputSection.tsx
+++ b/client/src/components/parameterPanel/InputSection.tsx
@@ -277,35 +277,30 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
profile_image_url: 'string',
verified: 'boolean'
},
- // Gmail node output schemas
+ // Google Workspace consolidated node output schemas
+ // Gmail (operation: send, search, read)
gmail: {
+ operation: 'string',
message_id: 'string',
thread_id: 'string',
+ from: 'string',
to: 'string',
+ cc: 'string',
subject: 'string',
- label_ids: 'array'
- },
- gmailSearch: {
- messages: [{
- message_id: 'string',
- thread_id: 'string',
- from: 'string',
- to: 'string',
- subject: 'string',
- date: 'string',
- snippet: 'string',
- labels: 'array'
- }],
- count: 'number',
- query: 'string',
- result_size_estimate: 'number'
+ date: 'string',
+ snippet: 'string',
+ body: 'string',
+ labels: 'array',
+ attachments: 'array',
+ messages: 'array',
+ count: 'number'
},
- gmailRead: {
+ // Gmail Receive trigger
+ gmailReceive: {
message_id: 'string',
thread_id: 'string',
from: 'string',
to: 'string',
- cc: 'string',
subject: 'string',
date: 'string',
snippet: 'string',
@@ -313,8 +308,9 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
labels: 'array',
attachments: 'array'
},
- // Google Calendar
- calendarCreate: {
+ // Google Calendar (operation: create, list, update, delete)
+ calendar: {
+ operation: 'string',
event_id: 'string',
title: 'string',
start: 'string',
@@ -322,119 +318,58 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
description: 'string',
location: 'string',
html_link: 'string',
- status: 'string'
- },
- calendarList: {
+ status: 'string',
events: 'array',
- count: 'number'
- },
- calendarUpdate: {
- event_id: 'string',
- title: 'string',
- start: 'string',
- end: 'string',
- updated: 'string'
- },
- calendarDelete: {
- deleted: 'boolean',
- event_id: 'string'
+ count: 'number',
+ deleted: 'boolean'
},
- // Google Drive
- driveUpload: {
+ // Google Drive (operation: upload, download, list, share)
+ drive: {
+ operation: 'string',
file_id: 'string',
name: 'string',
mime_type: 'string',
web_view_link: 'string',
web_content_link: 'string',
- size: 'number'
- },
- driveDownload: {
- file_id: 'string',
- name: 'string',
+ size: 'number',
content: 'string',
- mime_type: 'string',
- size: 'number'
- },
- driveList: {
files: 'array',
count: 'number',
- next_page_token: 'string'
- },
- driveShare: {
- file_id: 'string',
+ next_page_token: 'string',
permission_id: 'string',
role: 'string',
email: 'string'
},
- // Google Sheets
- sheetsRead: {
+ // Google Sheets (operation: read, write, append)
+ sheets: {
+ operation: 'string',
values: 'array',
range: 'string',
rows: 'number',
columns: 'number',
- major_dimension: 'string'
- },
- sheetsWrite: {
- updated_range: 'string',
- updated_rows: 'number',
- updated_columns: 'number',
- updated_cells: 'number'
- },
- sheetsAppend: {
+ major_dimension: 'string',
updated_range: 'string',
updated_rows: 'number',
updated_columns: 'number',
updated_cells: 'number',
table_range: 'string'
},
- // Google Tasks
- tasksCreate: {
+ // Google Tasks (operation: create, list, complete, update, delete)
+ tasks: {
+ operation: 'string',
task_id: 'string',
title: 'string',
notes: 'string',
due: 'string',
- status: 'string'
- },
- tasksList: {
- tasks: 'array',
- count: 'number'
- },
- tasksComplete: {
- task_id: 'string',
- title: 'string',
status: 'string',
- completed: 'string'
- },
- tasksUpdate: {
- task_id: 'string',
- title: 'string',
- notes: 'string',
- due: 'string',
- status: 'string'
- },
- tasksDelete: {
- deleted: 'boolean',
- task_id: 'string'
- },
- // Google Contacts (People API)
- contactsCreate: {
- resource_name: 'string',
- display_name: 'string',
- email: 'string',
- phone: 'string',
- company: 'string'
- },
- contactsList: {
- contacts: 'array',
+ completed: 'string',
+ tasks: 'array',
count: 'number',
- total_people: 'number',
- next_page_token: 'string'
+ deleted: 'boolean'
},
- contactsSearch: {
- contacts: 'array',
- count: 'number'
- },
- contactsGet: {
+ // Google Contacts (operation: create, list, search, get, update, delete)
+ contacts: {
+ operation: 'string',
resource_name: 'string',
display_name: 'string',
given_name: 'string',
@@ -442,17 +377,12 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
email: 'string',
phone: 'string',
company: 'string',
- job_title: 'string'
- },
- contactsUpdate: {
- resource_name: 'string',
- display_name: 'string',
- email: 'string',
- phone: 'string'
- },
- contactsDelete: {
- deleted: 'boolean',
- resource_name: 'string'
+ job_title: 'string',
+ contacts: 'array',
+ count: 'number',
+ total_people: 'number',
+ next_page_token: 'string',
+ deleted: 'boolean'
},
httpRequest: {
status: 'number',
@@ -729,19 +659,10 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
const isTaskTrigger = nodeType === 'taskTrigger';
const isSocialReceive = nodeType === 'socialReceive';
const isSocialSend = nodeType === 'socialSend';
- const isGmailSend = nodeType === 'gmailSend';
- const isGmailSearch = nodeType === 'gmailSearch';
- const isGmailRead = nodeType === 'gmailRead';
const isSearchNode = nodeType === 'braveSearch' || nodeType === 'serperSearch' || nodeType === 'perplexitySearch';
- // Google Workspace nodes detection
- const googleWorkspaceNodeTypes = [
- 'calendarCreate', 'calendarList', 'calendarUpdate', 'calendarDelete',
- 'driveUpload', 'driveDownload', 'driveList', 'driveShare',
- 'sheetsRead', 'sheetsWrite', 'sheetsAppend',
- 'tasksCreate', 'tasksList', 'tasksComplete', 'tasksUpdate', 'tasksDelete',
- 'contactsCreate', 'contactsList', 'contactsSearch', 'contactsGet', 'contactsUpdate', 'contactsDelete'
- ];
+ // Google Workspace consolidated nodes detection
+ const googleWorkspaceNodeTypes = ['gmail', 'gmailReceive', 'calendar', 'drive', 'sheets', 'tasks', 'contacts'];
const isGoogleWorkspaceNode = googleWorkspaceNodeTypes.includes(nodeType);
// Document processing node detection
@@ -782,9 +703,6 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =
isFile ? sampleSchemas.file :
isWhatsAppDb ? sampleSchemas.whatsappDb :
isWhatsApp ? sampleSchemas.whatsapp :
- isGmailSend ? sampleSchemas.gmail :
- isGmailSearch ? sampleSchemas.gmailSearch :
- isGmailRead ? sampleSchemas.gmailRead :
isWebhook ? sampleSchemas.webhook :
isHttpRequest ? sampleSchemas.httpRequest :
isCodeExecutor ? sampleSchemas.python :
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index c22eac08..78d331a3 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -100,7 +100,7 @@ export interface TwitterStatus {
verified?: boolean;
}
-export interface GmailStatus {
+export interface GoogleStatus {
connected: boolean;
email: string | null;
name?: string;
@@ -221,7 +221,7 @@ interface WebSocketContextValue {
setAndroidStatus: React.Dispatch<React.SetStateAction<AndroidStatus>>;
whatsappStatus: WhatsAppStatus;
twitterStatus: TwitterStatus;
- gmailStatus: GmailStatus;
+ googleStatus: GoogleStatus;
whatsappMessages: WhatsAppMessage[]; // History of received messages
lastWhatsAppMessage: WhatsAppMessage | null; // Most recent message
apiKeyStatuses: Record<string, ApiKeyStatus>;
@@ -350,7 +350,7 @@ const defaultTwitterStatus: TwitterStatus = {
user_id: null,
};
-const defaultGmailStatus: GmailStatus = {
+const defaultGoogleStatus: GoogleStatus = {
connected: false,
email: null,
};
@@ -389,7 +389,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
const [androidStatus, setAndroidStatus] = useState<AndroidStatus>(defaultAndroidStatus);
const [whatsappStatus, setWhatsappStatus] = useState<WhatsAppStatus>(defaultWhatsAppStatus);
const [twitterStatus, setTwitterStatus] = useState<TwitterStatus>(defaultTwitterStatus);
- const [gmailStatus, setGmailStatus] = useState<GmailStatus>(defaultGmailStatus);
+ const [googleStatus, setGoogleStatus] = useState<GoogleStatus>(defaultGoogleStatus);
const [whatsappMessages, setWhatsappMessages] = useState<WhatsAppMessage[]>([]);
const [lastWhatsAppMessage, setLastWhatsAppMessage] = useState<WhatsAppMessage | null>(null);
const [apiKeyStatuses, setApiKeyStatuses] = useState<Record<string, ApiKeyStatus>>({});
@@ -505,7 +505,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
if (data.android) setAndroidStatus(data.android);
if (data.whatsapp) setWhatsappStatus(data.whatsapp);
if (data.twitter) setTwitterStatus(data.twitter);
- if (data.gmail) setGmailStatus(data.gmail);
+ if (data.google) setGoogleStatus(data.google);
if (data.api_keys) setApiKeyStatuses(data.api_keys);
// Node statuses from initial_status - group by workflow_id (n8n pattern)
if (data.nodes) {
@@ -576,7 +576,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
case 'google_oauth_complete':
// Handle Google Workspace OAuth completion broadcast from backend
if (data?.success) {
- setGmailStatus({
+ setGoogleStatus({
connected: true,
email: data.email || null,
name: data.name,
@@ -585,6 +585,17 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
break;
+ case 'google_status':
+ // Handle Google Workspace status update (refresh, logout)
+ if (data) {
+ setGoogleStatus({
+ connected: data.connected || false,
+ email: data.email || null,
+ name: data.name,
+ });
+ }
+ break;
+
case 'whatsapp_message_received':
// Handle incoming WhatsApp message from Go service
if (data) {
@@ -2042,7 +2053,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
setAndroidStatus,
whatsappStatus,
twitterStatus,
- gmailStatus,
+ googleStatus,
whatsappMessages,
lastWhatsAppMessage,
apiKeyStatuses,
@@ -2182,10 +2193,10 @@ export const useTwitterStatus = (): TwitterStatus => {
return twitterStatus;
};
-// Hook specifically for Gmail status
-export const useGmailStatus = (): GmailStatus => {
- const { gmailStatus } = useWebSocket();
- return gmailStatus;
+// Hook specifically for Google Workspace status
+export const useGoogleStatus = (): GoogleStatus => {
+ const { googleStatus } = useWebSocket();
+ return googleStatus;
};
// Hook specifically for deployment status
diff --git a/client/src/services/executionService.ts b/client/src/services/executionService.ts
index d79dc31c..b757ee7a 100644
--- a/client/src/services/executionService.ts
+++ b/client/src/services/executionService.ts
@@ -6,12 +6,7 @@ import { UTILITY_NODE_TYPES } from '../nodeDefinitions/utilityNodes';
import { DOCUMENT_NODE_TYPES } from '../nodeDefinitions/documentNodes';
import { SPECIALIZED_AGENT_TYPES } from '../nodeDefinitions/specializedAgentNodes';
import { TWITTER_NODE_TYPES } from '../nodeDefinitions/twitterNodes';
-import { GMAIL_NODE_TYPES } from '../nodeDefinitions/gmailNodes';
-import { CALENDAR_NODE_TYPES } from '../nodeDefinitions/calendarNodes';
-import { DRIVE_NODE_TYPES } from '../nodeDefinitions/driveNodes';
-import { SHEETS_NODE_TYPES } from '../nodeDefinitions/sheetsNodes';
-import { TASKS_NODE_TYPES } from '../nodeDefinitions/tasksNodes';
-import { CONTACTS_NODE_TYPES } from '../nodeDefinitions/contactsNodes';
+import { GOOGLE_WORKSPACE_NODE_TYPES } from '../nodeDefinitions/googleWorkspaceNodes';
import { APIFY_NODE_TYPES } from '../nodeDefinitions/apifyNodes';
import { SEARCH_NODE_TYPES } from '../nodeDefinitions/searchNodes';
import { Node, Edge } from 'reactflow';
@@ -235,13 +230,8 @@ export class ExecutionService {
...DOCUMENT_NODE_TYPES,
// Twitter/X Nodes
...TWITTER_NODE_TYPES,
- // Google Workspace Nodes
- ...GMAIL_NODE_TYPES,
- ...CALENDAR_NODE_TYPES,
- ...DRIVE_NODE_TYPES,
- ...SHEETS_NODE_TYPES,
- ...TASKS_NODE_TYPES,
- ...CONTACTS_NODE_TYPES,
+ // Google Workspace Nodes (consolidated)
+ ...GOOGLE_WORKSPACE_NODE_TYPES,
// Apify web scraping
...APIFY_NODE_TYPES,
// Search API nodes
diff --git a/server/constants.py b/server/constants.py
index 9c529940..2c8ab260 100644
--- a/server/constants.py
+++ b/server/constants.py
@@ -252,6 +252,18 @@ EVENT_TRIGGER_TYPES: FrozenSet[str] = frozenset([
# Legacy alias for backwards compatibility
TRIGGER_TYPES: FrozenSet[str] = EVENT_TRIGGER_TYPES
+# =============================================================================
+# POLLING TRIGGER TYPES (require active API polling in deployment mode)
+# =============================================================================
+
+# Polling triggers need to actively poll an external API for new data,
+# unlike push-based triggers (WhatsApp, Webhook) that receive events externally.
+# In deployment mode, these get a dedicated polling loop instead of event_waiter.
+POLLING_TRIGGER_TYPES: FrozenSet[str] = frozenset([
+ 'gmailReceive',
+ 'twitterReceive',
+])
+
# =============================================================================
# ALL TRIGGER NODE TYPES (starting points for workflow graphs)
# =============================================================================
@@ -269,6 +281,8 @@ WORKFLOW_TRIGGER_TYPES: FrozenSet[str] = frozenset([
'workflowTrigger',
'chatTrigger',
'taskTrigger',
+ 'twitterReceive',
+ 'gmailReceive',
])
# =============================================================================
diff --git a/server/routers/google.py b/server/routers/google.py
index ed302405..64e53743 100644
--- a/server/routers/google.py
+++ b/server/routers/google.py
@@ -154,9 +154,14 @@ async def google_oauth_callback(
)
logger.info(f"Google OAuth successful for {email}")
- # Broadcast completion event
+ # Update persistent status and broadcast completion event
from services.status_broadcaster import get_status_broadcaster
broadcaster = get_status_broadcaster()
+ broadcaster._status["google"] = {
+ "connected": True,
+ "email": email,
+ "name": name,
+ }
await broadcaster.broadcast({
"type": "google_oauth_complete",
"data": {"success": True, "email": email, "name": name, "mode": mode, "customer_id": customer_id},
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index 38cf82d5..332d2caa 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -1255,35 +1255,30 @@ async def handle_google_oauth_status(data: Dict[str, Any], websocket: WebSocket)
Check Google Workspace OAuth connection status.
Returns connection status and user info if connected.
+ Also updates broadcaster status so all clients stay in sync.
"""
from services.google_oauth import GoogleOAuth
+ from services.status_broadcaster import get_status_broadcaster
auth_service = container.auth_service()
- settings = container.settings()
+ broadcaster = get_status_broadcaster()
- access_token = await auth_service.get_api_key("google_access_token")
+ tokens = await auth_service.get_oauth_tokens("google", customer_id="owner")
- if not access_token:
- return {
- "connected": False,
- "email": None,
- "name": None,
- }
+ if not tokens or not tokens.get("access_token"):
+ status = {"connected": False, "email": None, "name": None}
+ broadcaster._status["google"] = status
+ return status
- user_info_str = await auth_service.get_api_key("google_user_info")
- email, name = None, None
- if user_info_str:
- parts = user_info_str.split(":", 1)
- email = parts[0] if parts else None
- name = parts[1] if len(parts) > 1 else None
+ email = tokens.get("email")
+ name = tokens.get("name")
+ refresh_token = tokens.get("refresh_token")
- # Verify token is valid by checking if we can build service
+ # Try to refresh token proactively
try:
client_id = await auth_service.get_api_key("google_client_id") or ""
client_secret = await auth_service.get_api_key("google_client_secret") or ""
- refresh_token = await auth_service.get_api_key("google_refresh_token")
- # Try to refresh if needed
if refresh_token and client_id and client_secret:
refreshed = GoogleOAuth.refresh_credentials(
refresh_token=refresh_token,
@@ -1291,26 +1286,28 @@ async def handle_google_oauth_status(data: Dict[str, Any], websocket: WebSocket)
client_secret=client_secret,
)
if refreshed.get("success") and refreshed.get("access_token"):
- await auth_service.store_api_key(
- provider="google_access_token",
- api_key=refreshed["access_token"],
- models=[],
- session_id="default"
+ await auth_service.store_oauth_tokens(
+ provider="google",
+ access_token=refreshed["access_token"],
+ refresh_token=refresh_token,
+ email=email,
+ name=name,
+ customer_id="owner",
)
- return {
- "connected": True,
- "email": email,
- "name": name,
- }
+ status = {"connected": True, "email": email, "name": name}
+ broadcaster._status["google"] = status
+ # Broadcast so all connected clients update
+ await broadcaster.broadcast({
+ "type": "google_status",
+ "data": status,
+ })
+ return status
except Exception as e:
logger.warning(f"Google token validation failed: {e}")
- return {
- "connected": False,
- "email": None,
- "name": None,
- "error": str(e),
- }
+ status = {"connected": False, "email": None, "name": None, "error": str(e)}
+ broadcaster._status["google"] = {"connected": False, "email": None, "name": None}
+ return status
@ws_handler()
@@ -1318,11 +1315,19 @@ async def handle_google_logout(data: Dict[str, Any], websocket: WebSocket) -> Di
"""
Disconnect Google Workspace by clearing stored credentials.
"""
+ from services.status_broadcaster import get_status_broadcaster
+
auth_service = container.auth_service()
+ broadcaster = get_status_broadcaster()
+
+ await auth_service.remove_oauth_tokens("google", customer_id="owner")
- await auth_service.remove_api_key("google_access_token")
- await auth_service.remove_api_key("google_refresh_token")
- await auth_service.remove_api_key("google_user_info")
+ # Clear broadcaster status and notify all clients
+ broadcaster._status["google"] = {"connected": False, "email": None, "name": None}
+ await broadcaster.broadcast({
+ "type": "google_status",
+ "data": {"connected": False, "email": None, "name": None},
+ })
return {"success": True, "message": "Google Workspace disconnected"}
diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.py
index 39aa18b2..d83a66c6 100644
--- a/server/services/deployment/manager.py
+++ b/server/services/deployment/manager.py
@@ -13,7 +13,7 @@ from datetime import datetime
from typing import Dict, Any, List, Optional, Callable, TYPE_CHECKING
from core.logging import get_logger
-from constants import WORKFLOW_TRIGGER_TYPES
+from constants import WORKFLOW_TRIGGER_TYPES, POLLING_TRIGGER_TYPES
from services import event_waiter
from .state import DeploymentState, TriggerInfo
from .triggers import TriggerManager
@@ -418,6 +418,18 @@ class DeploymentManager:
if not trigger_manager:
raise RuntimeError(f"No trigger manager for workflow {workflow_id}")
+ # Polling triggers need active API polling instead of event_waiter
+ if node_type in POLLING_TRIGGER_TYPES:
+ poll_coroutine = self._create_poll_coroutine(node_type, node_id, params)
+ if poll_coroutine:
+ await trigger_manager.setup_polling_trigger(
+ node_id, node_type, params, poll_coroutine, on_event,
+ self._broadcaster, workflow_id=workflow_id
+ )
+ return TriggerInfo(node_id, node_type)
+ # Fall through to event_waiter if no polling implementation available
+ logger.warning("No polling implementation for trigger", node_type=node_type)
+
await trigger_manager.setup_event_trigger(
node_id, node_type, params, on_event, self._broadcaster,
workflow_id=workflow_id
@@ -649,6 +661,104 @@ class DeploymentManager:
# HELPERS
# =========================================================================
+ # =========================================================================
+ # POLLING TRIGGER FACTORIES
+ # =========================================================================
+
+ def _create_poll_coroutine(self, node_type: str, node_id: str,
+ params: Dict[str, Any]) -> Optional[Callable]:
+ """Create a polling coroutine for polling-based triggers.
+
+ Returns an async function(queue, is_running_fn) or None if not supported.
+ """
+ if node_type == 'gmailReceive':
+ return self._create_gmail_poll_coroutine(node_id, params)
+ elif node_type == 'twitterReceive':
+ logger.warning("Twitter polling trigger not yet implemented for deployment")
+ return None
+ return None
+
+ def _create_gmail_poll_coroutine(self, node_id: str,
+ params: Dict[str, Any]) -> Callable:
+ """Create Gmail API polling coroutine for deployment mode.
+
+ Polls Gmail API at configured intervals for new emails matching the filter.
+ Establishes a baseline of existing emails to avoid triggering on old messages.
+ """
+ async def poll(queue: asyncio.Queue, is_running_fn: Callable):
+ from services.handlers.gmail import (
+ _get_gmail_service, _poll_gmail_ids,
+ _fetch_email_details, _mark_email_as_read
+ )
+
+ # Authenticate with Gmail API
+ service = await _get_gmail_service(params, {})
+
+ poll_interval = max(10, min(3600, params.get('poll_interval', 60)))
+ filter_query = params.get('filter_query', 'is:unread')
+ label_filter = params.get('label_filter', 'INBOX')
+ mark_as_read = params.get('mark_as_read', False)
+
+ # Build Gmail query
+ query = filter_query
+ if label_filter and label_filter != 'all':
+ query = f"label:{label_filter} {query}"
+
+ logger.info("Gmail poller starting",
+ node_id=node_id, query=query,
+ poll_interval=poll_interval)
+
+ # Establish baseline (avoid triggering on existing emails)
+ seen_ids: set = set()
+ try:
+ baseline = await _poll_gmail_ids(service, query)
+ seen_ids.update(baseline)
+ logger.info("Gmail poller baseline established",
+ node_id=node_id, count=len(seen_ids))
+ except Exception as e:
+ logger.warning("Gmail poller baseline failed",
+ node_id=node_id, error=str(e))
+
+ # Poll loop
+ poll_count = 0
+ while is_running_fn():
+ await asyncio.sleep(poll_interval)
+ if not is_running_fn():
+ break
+
+ poll_count += 1
+ try:
+ current_ids = await _poll_gmail_ids(service, query)
+ new_ids = current_ids - seen_ids
+ logger.debug("Gmail poll cycle",
+ node_id=node_id, cycle=poll_count,
+ current=len(current_ids),
+ seen=len(seen_ids),
+ new=len(new_ids))
+
+ for msg_id in new_ids:
+ seen_ids.add(msg_id)
+ email_data = await _fetch_email_details(service, msg_id)
+
+ if mark_as_read:
+ try:
+ await _mark_email_as_read(service, msg_id)
+ except Exception:
+ pass
+
+ await queue.put(email_data)
+ logger.info("Gmail poller: new email queued",
+ node_id=node_id,
+ subject=email_data.get('subject', ''))
+
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ logger.error("Gmail poll error",
+ node_id=node_id, error=str(e))
+
+ return poll
+
async def _load_settings(self):
"""Load deployment settings from database."""
try:
diff --git a/server/services/deployment/triggers.py b/server/services/deployment/triggers.py
index 2369aa4d..3b9f64a0 100644
--- a/server/services/deployment/triggers.py
+++ b/server/services/deployment/triggers.py
@@ -185,6 +185,100 @@ class TriggerManager:
task = asyncio.create_task(combined())
self._active_listeners[node_id] = task
+ async def setup_polling_trigger(self, node_id: str, node_type: str,
+ parameters: Dict[str, Any],
+ poll_coroutine: Callable,
+ on_event: Callable[[Dict], Any],
+ broadcaster: Any,
+ workflow_id: Optional[str] = None) -> None:
+ """Setup a polling-based trigger with queue-based sequential processing.
+
+ Unlike event triggers that wait for externally dispatched events via
+ event_waiter, polling triggers actively poll an API for new data.
+ Used for Gmail, Twitter, and other APIs that require polling.
+
+ Args:
+ node_id: The trigger node ID
+ node_type: Type of trigger (gmailReceive, twitterReceive, etc.)
+ parameters: Node parameters for filtering
+ poll_coroutine: Async function(queue, is_running_fn) that polls and enqueues events
+ on_event: Callback when event is received
+ broadcaster: Status broadcaster for real-time updates
+ workflow_id: Workflow ID for scoped status updates
+ """
+ event_queue: asyncio.Queue = asyncio.Queue()
+ is_executing = False
+
+ # Broadcast initial "waiting" status immediately
+ config = event_waiter.get_trigger_config(node_type)
+ display_name = config.display_name if config else node_type
+ await broadcaster.update_node_status(node_id, "waiting", {
+ "message": f"Waiting for {display_name} (polling)...",
+ "is_processing": False
+ }, workflow_id=workflow_id)
+
+ async def poller():
+ """Run the polling coroutine to collect events."""
+ try:
+ await poll_coroutine(event_queue, lambda: self._is_running)
+ except asyncio.CancelledError:
+ pass
+ except Exception as e:
+ logger.error("Polling trigger fatal error", node_id=node_id, error=str(e))
+
+ async def processor():
+ """Process events from queue sequentially."""
+ nonlocal is_executing
+ while self._is_running:
+ try:
+ try:
+ event_data = await asyncio.wait_for(event_queue.get(), timeout=1.0)
+ except asyncio.TimeoutError:
+ continue
+
+ is_executing = True
+ config = event_waiter.get_trigger_config(node_type)
+
+ await broadcaster.update_node_status(node_id, "idle", {
+ "message": "Graph executing...",
+ "is_processing": True
+ }, workflow_id=workflow_id)
+
+ try:
+ await on_event(event_data)
+ except Exception as e:
+ logger.error("Polling trigger execution error", node_id=node_id, error=str(e))
+
+ is_executing = False
+
+ queue_size = event_queue.qsize()
+ name = config.display_name if config else node_type
+ msg = f"Waiting for {name} (polling)..." if queue_size == 0 else f"Processing next... ({queue_size} queued)"
+ await broadcaster.update_node_status(node_id, "waiting", {
+ "message": msg,
+ "queue_size": queue_size,
+ "is_processing": False
+ }, workflow_id=workflow_id)
+
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ logger.error("Polling trigger processor error", node_id=node_id, error=str(e))
+ is_executing = False
+
+ async def combined():
+ poller_task = asyncio.create_task(poller())
+ processor_task = asyncio.create_task(processor())
+ try:
+ await asyncio.gather(poller_task, processor_task)
+ except asyncio.CancelledError:
+ poller_task.cancel()
+ processor_task.cancel()
+ await asyncio.gather(poller_task, processor_task, return_exceptions=True)
+
+ task = asyncio.create_task(combined())
+ self._active_listeners[node_id] = task
+
async def teardown_all_listeners(self) -> int:
"""Cancel all event listeners."""
count = 0
diff --git a/server/services/event_waiter.py b/server/services/event_waiter.py
index 0366987f..c1e4fc1f 100644
--- a/server/services/event_waiter.py
+++ b/server/services/event_waiter.py
@@ -115,8 +115,12 @@ TRIGGER_REGISTRY: Dict[str, TriggerConfig] = {
event_type='twitter_event_received',
display_name='Twitter Event'
),
+ 'gmailReceive': TriggerConfig(
+ node_type='gmailReceive',
+ event_type='gmail_email_received',
+ display_name='Gmail Email'
+ ),
# Future triggers - just add to registry:
- # 'emailTrigger': TriggerConfig('emailTrigger', 'email_received', 'Email'),
# 'mqttTrigger': TriggerConfig('mqttTrigger', 'mqtt_message', 'MQTT Message'),
# 'telegramTrigger': TriggerConfig('telegramTrigger', 'telegram_message', 'Telegram'),
}
@@ -387,6 +391,31 @@ def build_twitter_filter(params: Dict) -> Callable[[Dict], bool]:
return matches
+def build_gmail_filter(params: Dict) -> Callable[[Dict], bool]:
+ """Build filter function for Gmail email events.
+
+ Filters by label to ensure the event matches the trigger's label filter.
+ The filter_query is applied at the Gmail API level during polling,
+ so this filter only checks labels for events dispatched via event_waiter.
+
+ Args:
+ params: Node parameters with 'label_filter' field
+
+ Returns:
+ Filter function that checks if event labels match
+ """
+ label_filter = params.get('label_filter', 'INBOX')
+
+ def matches(data: Dict) -> bool:
+ if label_filter and label_filter != 'all':
+ labels = data.get('labels', [])
+ if label_filter not in labels:
+ return False
+ return True
+
+ return matches
+
+
# Registry of filter builders per trigger type
FILTER_BUILDERS: Dict[str, Callable[[Dict], Callable[[Dict], bool]]] = {
'whatsappReceive': build_whatsapp_filter,
@@ -394,6 +423,7 @@ FILTER_BUILDERS: Dict[str, Callable[[Dict], Callable[[Dict], bool]]] = {
'chatTrigger': build_chat_filter,
'taskTrigger': build_task_completed_filter,
'twitterReceive': build_twitter_filter,
+ 'gmailReceive': build_gmail_filter,
}
diff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.py
index ff3c3ec0..c7850ad7 100644
--- a/server/services/handlers/__init__.py
+++ b/server/services/handlers/__init__.py
@@ -81,7 +81,7 @@ from .twitter import (
)
# Google Workspace handlers (consolidated)
-from .gmail import handle_google_gmail
+from .gmail import handle_google_gmail, handle_gmail_receive
from .calendar import handle_google_calendar
from .drive import handle_google_drive
from .sheets import handle_google_sheets
@@ -156,6 +156,7 @@ __all__ = [
'handle_twitter_user',
# Google Workspace (consolidated)
'handle_google_gmail',
+ 'handle_gmail_receive',
'handle_google_calendar',
'handle_google_drive',
'handle_google_sheets',
diff --git a/server/services/handlers/calendar.py b/server/services/handlers/calendar.py
index 7470e735..6de6f974 100644
--- a/server/services/handlers/calendar.py
+++ b/server/services/handlers/calendar.py
@@ -8,10 +8,10 @@ import time
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional
-from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from core.logging import get_logger
+from services.handlers.google_auth import get_google_credentials
from services.pricing import get_pricing_service
logger = get_logger(__name__)
@@ -54,53 +54,8 @@ async def _get_calendar_service(
parameters: Dict[str, Any],
context: Dict[str, Any]
):
- """Get authenticated Google Calendar service.
-
- Supports two modes:
- - Owner mode: Uses tokens from auth_service (Credentials Modal)
- - Customer mode: Uses tokens from google_connections table
- """
- from core.container import container
-
- account_mode = parameters.get('account_mode', 'owner')
-
- if account_mode == 'customer':
- customer_id = parameters.get('customer_id')
- if not customer_id:
- raise ValueError("customer_id required for customer mode")
-
- db = container.database()
- connection = await db.get_google_connection(customer_id)
- if not connection:
- raise ValueError(f"No Google connection for customer: {customer_id}")
-
- if not connection.is_active:
- raise ValueError(f"Google connection inactive for customer: {customer_id}")
-
- access_token = connection.access_token
- refresh_token = connection.refresh_token
-
- await db.update_google_last_used(customer_id)
-
- else:
- auth_service = container.auth_service()
- access_token = await auth_service.get_api_key("google_access_token")
- refresh_token = await auth_service.get_api_key("google_refresh_token")
-
- if not access_token:
- raise ValueError("Google not connected. Please authenticate via Credentials.")
-
- auth_service = container.auth_service()
- client_id = await auth_service.get_api_key("google_client_id") or ""
- client_secret = await auth_service.get_api_key("google_client_secret") or ""
-
- creds = Credentials(
- token=access_token,
- refresh_token=refresh_token,
- token_uri="https://oauth2.googleapis.com/token",
- client_id=client_id,
- client_secret=client_secret,
- )
+ """Get authenticated Google Calendar service."""
+ creds = await get_google_credentials(parameters, context)
def build_service():
return build("calendar", "v3", credentials=creds)
diff --git a/server/services/handlers/contacts.py b/server/services/handlers/contacts.py
index 012a696e..55c31a45 100644
--- a/server/services/handlers/contacts.py
+++ b/server/services/handlers/contacts.py
@@ -7,10 +7,10 @@ import asyncio
import time
from typing import Any, Dict, List
-from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from core.logging import get_logger
+from services.handlers.google_auth import get_google_credentials
from services.pricing import get_pricing_service
logger = get_logger(__name__)
@@ -54,55 +54,13 @@ async def _get_people_service(
context: Dict[str, Any]
):
"""Get authenticated Google People (Contacts) service."""
- from core.container import container
-
- account_mode = parameters.get('account_mode', 'owner')
-
- if account_mode == 'customer':
- customer_id = parameters.get('customer_id')
- if not customer_id:
- raise ValueError("customer_id required for customer mode")
-
- db = container.database()
- connection = await db.get_google_connection(customer_id)
- if not connection:
- raise ValueError(f"No Google connection for customer: {customer_id}")
-
- if not connection.is_active:
- raise ValueError(f"Google connection inactive for customer: {customer_id}")
-
- access_token = connection.access_token
- refresh_token = connection.refresh_token
-
- await db.update_google_last_used(customer_id)
-
- else:
- auth_service = container.auth_service()
- access_token = await auth_service.get_api_key("google_access_token")
- refresh_token = await auth_service.get_api_key("google_refresh_token")
-
- if not access_token:
- raise ValueError("Google not connected. Please authenticate via Credentials.")
-
- auth_service = container.auth_service()
- client_id = await auth_service.get_api_key("google_client_id") or ""
- client_secret = await auth_service.get_api_key("google_client_secret") or ""
-
- creds = Credentials(
- token=access_token,
- refresh_token=refresh_token,
- token_uri="https://oauth2.googleapis.com/token",
- client_id=client_id,
- client_secret=client_secret,
- )
+ creds = await get_google_credentials(parameters, context)
def build_service():
return build("people", "v1", credentials=creds)
loop = asyncio.get_event_loop()
- service = await loop.run_in_executor(None, build_service)
-
- return service
+ return await loop.run_in_executor(None, build_service)
def _format_contact(person: Dict[str, Any]) -> Dict[str, Any]:
diff --git a/server/services/handlers/drive.py b/server/services/handlers/drive.py
index 80882ea3..2fa7731a 100644
--- a/server/services/handlers/drive.py
+++ b/server/services/handlers/drive.py
@@ -9,11 +9,11 @@ import time
from typing import Any, Dict, Optional
import httpx
-from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseUpload, MediaIoBaseDownload
from core.logging import get_logger
+from services.handlers.google_auth import get_google_credentials
from services.pricing import get_pricing_service
logger = get_logger(__name__)
@@ -56,61 +56,14 @@ async def _get_drive_service(
parameters: Dict[str, Any],
context: Dict[str, Any]
):
- """Get authenticated Google Drive service.
-
- Supports two modes:
- - Owner mode: Uses tokens from auth_service (Credentials Modal)
- - Customer mode: Uses tokens from google_connections table
- """
- from core.container import container
-
- account_mode = parameters.get('account_mode', 'owner')
-
- if account_mode == 'customer':
- customer_id = parameters.get('customer_id')
- if not customer_id:
- raise ValueError("customer_id required for customer mode")
-
- db = container.database()
- connection = await db.get_google_connection(customer_id)
- if not connection:
- raise ValueError(f"No Google connection for customer: {customer_id}")
-
- if not connection.is_active:
- raise ValueError(f"Google connection inactive for customer: {customer_id}")
-
- access_token = connection.access_token
- refresh_token = connection.refresh_token
-
- await db.update_google_last_used(customer_id)
-
- else:
- auth_service = container.auth_service()
- access_token = await auth_service.get_api_key("google_access_token")
- refresh_token = await auth_service.get_api_key("google_refresh_token")
-
- if not access_token:
- raise ValueError("Google not connected. Please authenticate via Credentials.")
-
- auth_service = container.auth_service()
- client_id = await auth_service.get_api_key("google_client_id") or ""
- client_secret = await auth_service.get_api_key("google_client_secret") or ""
-
- creds = Credentials(
- token=access_token,
- refresh_token=refresh_token,
- token_uri="https://oauth2.googleapis.com/token",
- client_id=client_id,
- client_secret=client_secret,
- )
+ """Get authenticated Google Drive service."""
+ creds = await get_google_credentials(parameters, context)
def build_service():
return build("drive", "v3", credentials=creds)
loop = asyncio.get_event_loop()
- service = await loop.run_in_executor(None, build_service)
-
- return service
+ return await loop.run_in_executor(None, build_service)
async def handle_drive_upload(
diff --git a/server/services/handlers/gmail.py b/server/services/handlers/gmail.py
index 1c17934f..9ba9755c 100644
--- a/server/services/handlers/gmail.py
+++ b/server/services/handlers/gmail.py
@@ -3,14 +3,15 @@
import asyncio
import base64
import time
+from datetime import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
-from typing import Dict, Any
+from typing import Dict, Any, Set
-from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from core.logging import get_logger
+from services.handlers.google_auth import get_google_credentials
from services.pricing import get_pricing_service
logger = get_logger(__name__)
@@ -63,68 +64,14 @@ async def _get_gmail_service(
parameters: Dict[str, Any],
context: Dict[str, Any]
):
- """Get authenticated Gmail service.
-
- Supports two modes:
- - Owner mode: Uses tokens from auth_service (Credentials Modal)
- - Customer mode: Uses tokens from google_connections table
-
- Args:
- parameters: Node parameters (may include account_mode, customer_id)
- context: Execution context
-
- Returns:
- Gmail API service object
- """
- from core.container import container
-
- account_mode = parameters.get('account_mode', 'owner')
-
- if account_mode == 'customer':
- customer_id = parameters.get('customer_id')
- if not customer_id:
- raise ValueError("customer_id required for customer mode")
-
- db = container.database()
- connection = await db.get_google_connection(customer_id)
- if not connection:
- raise ValueError(f"No Google connection for customer: {customer_id}")
-
- if not connection.is_active:
- raise ValueError(f"Google connection inactive for customer: {customer_id}")
-
- access_token = connection.access_token
- refresh_token = connection.refresh_token
-
- await db.update_google_last_used(customer_id)
-
- else:
- auth_service = container.auth_service()
- access_token = await auth_service.get_api_key("google_access_token")
- refresh_token = await auth_service.get_api_key("google_refresh_token")
-
- if not access_token:
- raise ValueError("Google Workspace not connected. Please authenticate via Credentials.")
-
- auth_service = container.auth_service()
- client_id = await auth_service.get_api_key("google_client_id") or ""
- client_secret = await auth_service.get_api_key("google_client_secret") or ""
-
- creds = Credentials(
- token=access_token,
- refresh_token=refresh_token,
- token_uri="https://oauth2.googleapis.com/token",
- client_id=client_id,
- client_secret=client_secret,
- )
+ """Get authenticated Gmail service."""
+ creds = await get_google_credentials(parameters, context)
def build_service():
return build("gmail", "v1", credentials=creds)
loop = asyncio.get_event_loop()
- service = await loop.run_in_executor(None, build_service)
-
- return service
+ return await loop.run_in_executor(None, build_service)
async def handle_gmail_send(
@@ -416,6 +363,199 @@ def _extract_attachments(payload: Dict[str, Any]) -> list:
return attachments
+# ============================================================================
+# GMAIL RECEIVE - Polling-based trigger
+# ============================================================================
+
+async def _poll_gmail_ids(service, query: str, max_results: int = 20) -> Set[str]:
+ """Poll Gmail API for message IDs matching query.
+
+ Args:
+ service: Authenticated Gmail API service
+ query: Gmail search query string
+ max_results: Maximum messages to fetch
+
+ Returns:
+ Set of message IDs
+ """
+ def list_messages():
+ return service.users().messages().list(
+ userId='me',
+ q=query,
+ maxResults=max_results
+ ).execute()
+
+ loop = asyncio.get_event_loop()
+ result = await loop.run_in_executor(None, list_messages)
+ messages = result.get('messages', [])
+ return {m.get('id') for m in messages if m.get('id')}
+
+
+async def _fetch_email_details(service, message_id: str) -> Dict[str, Any]:
+ """Fetch full email details for a message ID.
+
+ Args:
+ service: Authenticated Gmail API service
+ message_id: Gmail message ID
+
+ Returns:
+ Formatted email data dict
+ """
+ def get_message():
+ return service.users().messages().get(
+ userId='me',
+ id=message_id,
+ format='full',
+ metadataHeaders=['From', 'To', 'Subject', 'Date', 'Cc', 'Bcc']
+ ).execute()
+
+ loop = asyncio.get_event_loop()
+ result = await loop.run_in_executor(None, get_message)
+ return _format_message(result, include_body=True)
+
+
+async def _mark_email_as_read(service, message_id: str) -> None:
+ """Mark email as read by removing UNREAD label.
+
+ Args:
+ service: Authenticated Gmail API service
+ message_id: Gmail message ID
+ """
+ def modify_message():
+ return service.users().messages().modify(
+ userId='me',
+ id=message_id,
+ body={'removeLabelIds': ['UNREAD']}
+ ).execute()
+
+ loop = asyncio.get_event_loop()
+ await loop.run_in_executor(None, modify_message)
+
+
+async def handle_gmail_receive(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any]
+) -> Dict[str, Any]:
+ """Handle Gmail Receive trigger - polls Gmail API for new emails.
+
+ Unlike push-based triggers (WhatsApp, Webhook), Gmail requires polling.
+ This handler:
+ 1. Authenticates with Gmail API using stored OAuth tokens
+ 2. Establishes a baseline of existing email IDs
+ 3. Polls at the configured interval for new emails
+ 4. Returns when a new email is found matching the filter
+ 5. Dispatches event via event_waiter for deployment mode listeners
+
+ Parameters:
+ filter_query: Gmail search query (default: 'is:unread')
+ label_filter: Label to filter by (default: 'INBOX')
+ mark_as_read: Mark processed emails as read (default: False)
+ poll_interval: Seconds between polls (default: 60, range: 30-3600)
+ """
+ from services.status_broadcaster import get_status_broadcaster
+ start_time = time.time()
+
+ try:
+ service = await _get_gmail_service(parameters, context)
+
+ poll_interval = max(10, min(3600, parameters.get('poll_interval', 60)))
+ filter_query = parameters.get('filter_query', 'is:unread')
+ label_filter = parameters.get('label_filter', 'INBOX')
+ mark_as_read = parameters.get('mark_as_read', False)
+
+ # Build Gmail query with label filter
+ query = filter_query
+ if label_filter and label_filter != 'all':
+ query = f"label:{label_filter} {query}"
+
+ # Broadcast waiting status
+ broadcaster = get_status_broadcaster()
+ workflow_id = context.get('workflow_id')
+ await broadcaster.update_node_status(node_id, "waiting", {
+ "message": f"Waiting for Gmail email (polling every {poll_interval}s)...",
+ "event_type": "gmail_email_received",
+ }, workflow_id=workflow_id)
+
+ # Get current email IDs to establish baseline (avoid triggering on existing emails)
+ seen_ids: Set[str] = set()
+ try:
+ baseline = await _poll_gmail_ids(service, query)
+ seen_ids.update(baseline)
+ logger.info(f"[GmailReceive] Baseline: {len(seen_ids)} existing emails for query '{query}'")
+ except Exception as e:
+ logger.warning(f"[GmailReceive] Baseline fetch failed (will treat all as new): {e}")
+
+ # Poll loop - check for new emails at configured interval
+ while True:
+ await asyncio.sleep(poll_interval)
+
+ try:
+ current_ids = await _poll_gmail_ids(service, query)
+ new_ids = current_ids - seen_ids
+
+ if new_ids:
+ # Found new email(s) - process the first one
+ newest_id = next(iter(new_ids))
+ seen_ids.update(new_ids)
+
+ # Fetch full message details
+ email_data = await _fetch_email_details(service, newest_id)
+
+ # Mark as read if configured
+ if mark_as_read:
+ try:
+ await _mark_email_as_read(service, newest_id)
+ except Exception as e:
+ logger.warning(f"[GmailReceive] Failed to mark as read: {e}")
+
+ # Track usage
+ session_id = context.get('session_id', 'default')
+ await _track_gmail_usage(node_id, 'receive', 1, workflow_id, session_id)
+
+ # Also dispatch event for deployment mode listeners
+ from services import event_waiter
+ event_waiter.dispatch('gmail_email_received', email_data)
+
+ logger.info(f"[GmailReceive] New email found: {email_data.get('subject', 'no subject')}")
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": node_type,
+ "result": email_data,
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ except asyncio.CancelledError:
+ raise # Re-raise to outer handler
+ except Exception as e:
+ logger.error(f"[GmailReceive] Poll error (will retry): {e}")
+
+ except asyncio.CancelledError:
+ logger.info(f"[GmailReceive] Cancelled by user: node_id={node_id}")
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": "Cancelled by user",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+ except Exception as e:
+ logger.error(f"[GmailReceive] Error: {e}")
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": str(e),
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat()
+ }
+
+
# ============================================================================
# CONSOLIDATED DISPATCHER
# ============================================================================
diff --git a/server/services/handlers/google_auth.py b/server/services/handlers/google_auth.py
new file mode 100644
index 00000000..93f093af
--- /dev/null
+++ b/server/services/handlers/google_auth.py
@@ -0,0 +1,142 @@
+"""Shared Google OAuth helper for all Google Workspace handlers.
+
+Provides centralized token retrieval, credential building, and proactive
+token refresh with persistence. All Google handler files (gmail, calendar,
+drive, sheets, tasks, contacts) should use get_google_credentials() instead
+of duplicating auth logic.
+"""
+
+import asyncio
+from typing import Any, Dict
+
+from google.oauth2.credentials import Credentials
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+
+async def get_google_credentials(
+ parameters: Dict[str, Any],
+ context: Dict[str, Any],
+) -> Credentials:
+ """Get authenticated Google OAuth credentials.
+
+ Supports two modes:
+ - Owner mode: Uses tokens from auth_service OAuth store (Credentials Modal)
+ - Customer mode: Uses tokens from google_connections table
+
+ After building credentials, proactively attempts a token refresh if a
+ refresh_token is available and persists the new access_token back to the
+ database so subsequent calls don't need to re-refresh.
+
+ Args:
+ parameters: Node parameters (may include account_mode, customer_id)
+ context: Execution context
+
+ Returns:
+ google.oauth2.credentials.Credentials ready for API use
+ """
+ from core.container import container
+
+ account_mode = parameters.get('account_mode', 'owner')
+ customer_id = "owner"
+
+ if account_mode == 'customer':
+ customer_id = parameters.get('customer_id')
+ if not customer_id:
+ raise ValueError("customer_id required for customer mode")
+
+ db = container.database()
+ connection = await db.get_google_connection(customer_id)
+ if not connection:
+ raise ValueError(f"No Google connection for customer: {customer_id}")
+
+ if not connection.is_active:
+ raise ValueError(f"Google connection inactive for customer: {customer_id}")
+
+ access_token = connection.access_token
+ refresh_token = connection.refresh_token
+
+ await db.update_google_last_used(customer_id)
+
+ else:
+ auth_service = container.auth_service()
+ tokens = await auth_service.get_oauth_tokens("google", customer_id="owner")
+
+ if not tokens or not tokens.get("access_token"):
+ raise ValueError(
+ "Google Workspace not connected. Please authenticate via Credentials."
+ )
+
+ access_token = tokens["access_token"]
+ refresh_token = tokens.get("refresh_token")
+
+ auth_service = container.auth_service()
+ client_id = await auth_service.get_api_key("google_client_id") or ""
+ client_secret = await auth_service.get_api_key("google_client_secret") or ""
+
+ creds = Credentials(
+ token=access_token,
+ refresh_token=refresh_token,
+ token_uri="https://oauth2.googleapis.com/token",
+ client_id=client_id,
+ client_secret=client_secret,
+ )
+
+ # Proactively refresh if the token is expired and we have a refresh_token.
+ # The google-auth library marks tokens expired when expiry is set and passed,
+ # but since we don't store expiry, we rely on the Credentials object's
+ # built-in auto-refresh during API calls. This proactive refresh is a
+ # best-effort optimization that persists the new token to the DB.
+ if refresh_token and client_id and client_secret:
+ try:
+ await _try_refresh_and_persist(
+ creds, auth_service, customer_id, account_mode
+ )
+ except Exception as e:
+ # Non-fatal: the Credentials object will auto-refresh on 401 anyway
+ logger.debug(f"Proactive token refresh skipped: {e}")
+
+ return creds
+
+
+async def _try_refresh_and_persist(
+ creds: Credentials,
+ auth_service,
+ customer_id: str,
+ account_mode: str,
+) -> None:
+ """Attempt to refresh credentials and persist the new token.
+
+ Only refreshes if the token appears expired (expired flag or no expiry set
+ meaning we can't tell -- in that case we skip proactive refresh and let
+ the google-auth library handle it lazily on 401).
+ """
+ from google.auth.transport.requests import Request
+
+ if not creds.expired and creds.valid:
+ return
+
+ # Token might be expired or expiry unknown -- try refresh
+ def do_refresh():
+ creds.refresh(Request())
+
+ loop = asyncio.get_event_loop()
+ await loop.run_in_executor(None, do_refresh)
+
+ if not creds.token:
+ return
+
+ # Persist refreshed token back to the correct store
+ if account_mode == 'owner':
+ tokens = await auth_service.get_oauth_tokens("google", customer_id="owner")
+ await auth_service.store_oauth_tokens(
+ provider="google",
+ access_token=creds.token,
+ refresh_token=creds.refresh_token or "",
+ email=tokens.get("email") if tokens else None,
+ name=tokens.get("name") if tokens else None,
+ customer_id="owner",
+ )
+ logger.debug("Proactively refreshed and persisted Google access token")
diff --git a/server/services/handlers/sheets.py b/server/services/handlers/sheets.py
index ec6e1e52..045ef9aa 100644
--- a/server/services/handlers/sheets.py
+++ b/server/services/handlers/sheets.py
@@ -7,10 +7,10 @@ import asyncio
import time
from typing import Any, Dict, List
-from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from core.logging import get_logger
+from services.handlers.google_auth import get_google_credentials
from services.pricing import get_pricing_service
logger = get_logger(__name__)
@@ -54,55 +54,13 @@ async def _get_sheets_service(
context: Dict[str, Any]
):
"""Get authenticated Google Sheets service."""
- from core.container import container
-
- account_mode = parameters.get('account_mode', 'owner')
-
- if account_mode == 'customer':
- customer_id = parameters.get('customer_id')
- if not customer_id:
- raise ValueError("customer_id required for customer mode")
-
- db = container.database()
- connection = await db.get_google_connection(customer_id)
- if not connection:
- raise ValueError(f"No Google connection for customer: {customer_id}")
-
- if not connection.is_active:
- raise ValueError(f"Google connection inactive for customer: {customer_id}")
-
- access_token = connection.access_token
- refresh_token = connection.refresh_token
-
- await db.update_google_last_used(customer_id)
-
- else:
- auth_service = container.auth_service()
- access_token = await auth_service.get_api_key("google_access_token")
- refresh_token = await auth_service.get_api_key("google_refresh_token")
-
- if not access_token:
- raise ValueError("Google not connected. Please authenticate via Credentials.")
-
- auth_service = container.auth_service()
- client_id = await auth_service.get_api_key("google_client_id") or ""
- client_secret = await auth_service.get_api_key("google_client_secret") or ""
-
- creds = Credentials(
- token=access_token,
- refresh_token=refresh_token,
- token_uri="https://oauth2.googleapis.com/token",
- client_id=client_id,
- client_secret=client_secret,
- )
+ creds = await get_google_credentials(parameters, context)
def build_service():
return build("sheets", "v4", credentials=creds)
loop = asyncio.get_event_loop()
- service = await loop.run_in_executor(None, build_service)
-
- return service
+ return await loop.run_in_executor(None, build_service)
async def handle_sheets_read(
diff --git a/server/services/handlers/tasks.py b/server/services/handlers/tasks.py
index e868e767..2de94a35 100644
--- a/server/services/handlers/tasks.py
+++ b/server/services/handlers/tasks.py
@@ -7,10 +7,10 @@ import asyncio
import time
from typing import Any, Dict
-from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from core.logging import get_logger
+from services.handlers.google_auth import get_google_credentials
from services.pricing import get_pricing_service
logger = get_logger(__name__)
@@ -54,55 +54,13 @@ async def _get_tasks_service(
context: Dict[str, Any]
):
"""Get authenticated Google Tasks service."""
- from core.container import container
-
- account_mode = parameters.get('account_mode', 'owner')
-
- if account_mode == 'customer':
- customer_id = parameters.get('customer_id')
- if not customer_id:
- raise ValueError("customer_id required for customer mode")
-
- db = container.database()
- connection = await db.get_google_connection(customer_id)
- if not connection:
- raise ValueError(f"No Google connection for customer: {customer_id}")
-
- if not connection.is_active:
- raise ValueError(f"Google connection inactive for customer: {customer_id}")
-
- access_token = connection.access_token
- refresh_token = connection.refresh_token
-
- await db.update_google_last_used(customer_id)
-
- else:
- auth_service = container.auth_service()
- access_token = await auth_service.get_api_key("google_access_token")
- refresh_token = await auth_service.get_api_key("google_refresh_token")
-
- if not access_token:
- raise ValueError("Google not connected. Please authenticate via Credentials.")
-
- auth_service = container.auth_service()
- client_id = await auth_service.get_api_key("google_client_id") or ""
- client_secret = await auth_service.get_api_key("google_client_secret") or ""
-
- creds = Credentials(
- token=access_token,
- refresh_token=refresh_token,
- token_uri="https://oauth2.googleapis.com/token",
- client_id=client_id,
- client_secret=client_secret,
- )
+ creds = await get_google_credentials(parameters, context)
def build_service():
return build("tasks", "v1", credentials=creds)
loop = asyncio.get_event_loop()
- service = await loop.run_in_executor(None, build_service)
-
- return service
+ return await loop.run_in_executor(None, build_service)
async def handle_tasks_create(
diff --git a/server/services/node_executor.py b/server/services/node_executor.py
index 2bde8665..5b322a2d 100644
--- a/server/services/node_executor.py
+++ b/server/services/node_executor.py
@@ -41,7 +41,7 @@ from services.handlers import (
)
from services.handlers.apify import handle_apify_actor
# Consolidated Google Workspace handlers (6 services with operation dispatchers)
-from services.handlers.gmail import handle_google_gmail
+from services.handlers.gmail import handle_google_gmail, handle_gmail_receive
from services.handlers.calendar import handle_google_calendar
from services.handlers.drive import handle_google_drive
from services.handlers.sheets import handle_google_sheets
@@ -149,8 +149,8 @@ class NodeExecutor:
'twitterSearch': handle_twitter_search,
'twitterUser': handle_twitter_user,
# Google Workspace (consolidated with operation dispatchers)
- # Note: gmailReceive is a trigger node, handled by event_waiter
'gmail': handle_google_gmail,
+ 'gmailReceive': handle_gmail_receive, # Polling-based trigger (custom handler)
'calendar': handle_google_calendar,
'drive': handle_google_drive,
'sheets': handle_google_sheets,
diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.py
index ba0570e3..0baecf0c 100644
--- a/server/services/status_broadcaster.py
+++ b/server/services/status_broadcaster.py
@@ -48,6 +48,11 @@ class StatusBroadcaster:
"name": None,
"profile_image_url": None
},
+ "google": {
+ "connected": False,
+ "email": None,
+ "name": None,
+ },
"api_keys": {}, # provider -> validation status
"nodes": {}, # node_id -> node status
"variables": {}, # variable_name -> value
@@ -83,6 +88,9 @@ class StatusBroadcaster:
# Fetch Twitter status from stored OAuth tokens
await self._refresh_twitter_status()
+ # Fetch Google Workspace status from stored OAuth tokens
+ await self._refresh_google_status()
+
# Auto-reconnect Android relay if there's a stored session
await self._auto_reconnect_android_relay()
@@ -288,6 +296,33 @@ class StatusBroadcaster:
except Exception as e:
logger.debug(f"[StatusBroadcaster] Could not refresh Twitter status: {e}")
+ async def _refresh_google_status(self):
+ """Fetch Google Workspace status from stored OAuth tokens.
+
+ Called on client connect to check if user is authenticated with Google.
+ """
+ try:
+ from core.container import container
+ auth_service = container.auth_service()
+
+ tokens = await auth_service.get_oauth_tokens("google", customer_id="owner")
+ if not tokens or not tokens.get("access_token"):
+ self._status["google"] = {
+ "connected": False,
+ "email": None,
+ "name": None,
+ }
+ return
+
+ self._status["google"] = {
+ "connected": True,
+ "email": tokens.get("email"),
+ "name": tokens.get("name"),
+ }
+ logger.debug(f"[StatusBroadcaster] Google status: connected as {tokens.get('email')}")
+ except Exception as e:
+ logger.debug(f"[StatusBroadcaster] Could not refresh Google status: {e}")
+
async def _auto_reconnect_android_relay(self):
"""Auto-reconnect to Android relay if there's a stored pairing session.