Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix(messages): configure Gmail OAuth in UI

[._.]/ Adam Eivy0f5555ef53b8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index baae169502..2054b21436 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -26,6 +26,10 @@
- **[issue-3267] Removed the unmount guard from the shared async-action hook, along with the test that could never fail.** The guard existed to avoid a "state update on an unmounted component" warning React stopped emitting in version 18, so its only remaining effect was to skip a no-op — while being the exact shape that froze every button backed by the hook under StrictMode. Its regression test asserted that the vanished warning never appeared, which stayed green even with the guard deleted; it now unmounts mid-request and asserts the action still resolves with its value.
- **[issue-3250] Stabilize Music Video project-selection tests under CI load.** Project-selection coverage now waits for the requested project to be available before opening its board, preventing intermittent false failures.
+## Messages
+
+- **Gmail can now be fully connected from Messages Config.** The page can create or accept Google OAuth credentials, returns to Messages after authorization, and labels an enabled Gmail account as pending until its Gmail permission is actually ready.
+
## Music Video
- **[issue-3245] Synced Music Video projects now use each machine's own render backends.** Image and video backend pins no longer overwrite a peer's locally usable choices, while shared model and pacing settings continue to sync.
diff --git a/client/src/components/messages/ConfigTab.jsx b/client/src/components/messages/ConfigTab.jsx
index 5f1b156e6b..e2476b3185 100644
--- a/client/src/components/messages/ConfigTab.jsx
+++ b/client/src/components/messages/ConfigTab.jsx
@@ -1,5 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
-import { Plus, Trash2, RefreshCw, Mail, Globe, MessageSquare, Save, ExternalLink, User } from 'lucide-react';
+import { useSearchParams } from 'react-router-dom';
+import { Plus, Trash2, RefreshCw, Mail, Globe, MessageSquare, Save, ExternalLink, User, Key, Monitor, Wand2 } from 'lucide-react';
import toast from '../ui/Toast';
import { formatDateTime } from '../../utils/formatters';
import * as api from '../../services/api';
@@ -49,7 +50,10 @@ export default function ConfigTab({ accounts, setAccounts }) {
// Google OAuth status for Gmail accounts
const [googleAuth, setGoogleAuth] = useState(null);
+ const [oauthForm, setOauthForm] = useState({ clientId: '', clientSecret: '' });
+ const [savingOAuth, setSavingOAuth] = useState(false);
const [reauthorizing, setReauthorizing] = useState(false);
+ const [autoConfigStep, setAutoConfigStep] = useState(null);
// AI config
const [config, setConfig] = useState(null);
@@ -98,20 +102,76 @@ export default function ConfigTab({ accounts, setAccounts }) {
// Check Google OAuth status when Gmail accounts exist
const hasGmailAccount = accounts.some(a => a.type === 'gmail');
+ const gmailAuthorized = Boolean(googleAuth?.hasTokens && !googleAuth?.needsScopeUpgrade);
+ const fetchGoogleAuth = useCallback(() => {
+ api.getGoogleAuthStatus()
+ .then(setGoogleAuth)
+ .catch(err => console.warn(`⚠️ Failed to load Google auth status: ${err.message}`));
+ }, []);
+
useEffect(() => {
- if (hasGmailAccount) {
- api.getGoogleAuthStatus().then(setGoogleAuth).catch(err => console.warn(`⚠️ Failed to load Google auth status: ${err.message}`));
- }
- }, [hasGmailAccount]);
+ if (hasGmailAccount) fetchGoogleAuth();
+ }, [fetchGoogleAuth, hasGmailAccount]);
+
+ // Google redirects back to the surface that started authorization. Surface a
+ // callback failure once, then remove it so reloads do not repeat the toast.
+ const [searchParams, setSearchParams] = useSearchParams();
+ const oauthError = searchParams.get('oauthError');
+ useEffect(() => {
+ if (!oauthError) return;
+ toast.error(`Google OAuth failed: ${oauthError}`);
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ next.delete('oauthError');
+ return next;
+ }, { replace: true });
+ }, [oauthError, setSearchParams]);
const handleReauthorize = () => {
setReauthorizing(true);
- api.getGoogleAuthUrl({ silent: true })
- .then(({ url }) => { window.open(url, '_blank'); })
+ api.getGoogleAuthUrl({ returnTo: 'messages', silent: true })
+ .then(({ url }) => {
+ window.open(url, '_blank');
+ toast.success('Complete authorization in the opened browser tab');
+ })
.catch(() => toast.error('Failed to get auth URL'))
.finally(() => setReauthorizing(false));
};
+ const handleSaveOAuthCredentials = async () => {
+ if (!oauthForm.clientId || !oauthForm.clientSecret) {
+ return toast.error('Both Client ID and Client Secret are required');
+ }
+ setSavingOAuth(true);
+ const saved = await api.saveGoogleAuthCredentials(oauthForm, { silent: true }).catch(() => null);
+ setSavingOAuth(false);
+ if (!saved) return toast.error('Failed to save credentials');
+ toast.success('OAuth credentials saved');
+ fetchGoogleAuth();
+ handleReauthorize();
+ };
+
+ const handleAutoConfigStart = async () => {
+ const result = await api.startGoogleAutoConfig({ silent: true }).catch(() => null);
+ if (!result || result.error) return toast.error(result?.error || 'Failed to open browser');
+ setAutoConfigStep('login');
+ toast.success('Google Cloud Console opened in PortOS browser');
+ };
+
+ const handleAutoConfigContinue = async () => {
+ setAutoConfigStep('running');
+ const email = accounts.find(a => a.type === 'gmail')?.email || '';
+ const result = await api.runGoogleAutoConfig(email, { silent: true }).catch(() => null);
+ if (!result || result.error) {
+ setAutoConfigStep('login');
+ return toast.error(result?.error || 'Automated setup failed. Try manual setup instead.');
+ }
+ setAutoConfigStep('done');
+ fetchGoogleAuth();
+ toast.success('Google OAuth setup complete');
+ handleReauthorize();
+ };
+
const handleEnableGmailApi = () => {
api.enableGmailApi({ silent: true })
.then(r => toast.success(r.message))
@@ -243,35 +303,129 @@ export default function ConfigTab({ accounts, setAccounts }) {
<div className="p-4 mb-4 bg-port-card border border-port-border rounded-lg space-y-3">
<h3 className="text-sm font-medium text-white">Gmail Setup</h3>
<div className="space-y-2">
- <div className="flex items-center justify-between">
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div className="flex items-center gap-2 text-sm">
- <span className={`w-2 h-2 rounded-full ${googleAuth?.hasTokens ? 'bg-port-success' : 'bg-port-error'}`} />
- <span className="text-gray-300">Google OAuth</span>
+ <span className={`w-2 h-2 rounded-full ${gmailAuthorized ? 'bg-port-success' : 'bg-port-warning'}`} />
+ <span className="text-gray-300">
+ {gmailAuthorized
+ ? 'Google OAuth authorized'
+ : googleAuth?.hasTokens
+ ? 'Google OAuth needs Gmail permission'
+ : googleAuth?.hasCredentials
+ ? 'Google OAuth authorization pending'
+ : 'Google OAuth setup required'}
+ </span>
</div>
- {googleAuth?.hasTokens ? (
- <button
- onClick={handleReauthorize}
- className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-gray-400 hover:text-white transition-colors"
- title="Re-authorize to update permissions"
- >
- <RefreshCw size={12} />
- Re-authorize
- </button>
- ) : (
+ {googleAuth?.hasCredentials && (
<button
onClick={handleReauthorize}
disabled={reauthorizing}
- className="flex items-center gap-1.5 px-3 py-1.5 bg-port-warning/20 text-port-warning text-xs rounded-lg hover:bg-port-warning/30 transition-colors disabled:opacity-50"
+ className={`flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg transition-colors disabled:opacity-50 ${
+ gmailAuthorized
+ ? 'text-gray-400 hover:text-white'
+ : 'bg-port-warning/20 text-port-warning hover:bg-port-warning/30'
+ }`}
+ title={gmailAuthorized ? 'Re-authorize to update permissions' : 'Authorize Gmail with Google'}
>
- <ExternalLink size={14} />
- Authorize
+ {gmailAuthorized ? <RefreshCw size={12} /> : <ExternalLink size={14} />}
+ {gmailAuthorized ? 'Re-authorize' : 'Authorize'}
</button>
)}
</div>
+
+ {!googleAuth?.hasCredentials && (
+ <div className="space-y-3 rounded-lg border border-port-border bg-port-bg/50 p-3">
+ <p className="text-xs text-gray-500">
+ PortOS needs a Google Cloud OAuth client before it can ask for access to Gmail.
+ </p>
+
+ {!autoConfigStep ? (
+ <button
+ onClick={handleAutoConfigStart}
+ className="flex w-full items-center justify-center gap-1.5 rounded border border-port-accent/20 bg-port-accent/10 px-3 py-2 text-xs text-port-accent hover:bg-port-accent/20"
+ >
+ <Monitor size={14} />
+ Set up with PortOS Browser
+ </button>
+ ) : autoConfigStep === 'running' ? (
+ <div className="flex items-center gap-2 rounded border border-port-border bg-port-bg/80 p-3">
+ <RefreshCw size={14} className="shrink-0 animate-spin text-port-accent" />
+ <p className="text-xs text-gray-400">
+ Enabling Google APIs, configuring OAuth consent, and creating credentials. This may take up to a minute.
+ </p>
+ </div>
+ ) : autoConfigStep === 'login' ? (
+ <div className="space-y-2 rounded border border-port-border bg-port-bg/80 p-3">
+ <div className="flex items-center gap-1.5 text-xs font-medium text-port-accent">
+ <Monitor size={12} />
+ Google Cloud Console is open in the PortOS browser
+ </div>
+ <div className="space-y-1 text-xs text-gray-400">
+ <p>1. Log in to your Google account if needed.</p>
+ <p>2. Select or create a Google Cloud project.</p>
+ <p>3. Click Continue and PortOS will finish the setup.</p>
+ </div>
+ <div className="flex gap-2 pt-1">
+ <button
+ onClick={handleAutoConfigContinue}
+ className="flex items-center gap-1 rounded bg-port-accent px-3 py-1.5 text-xs text-white hover:bg-port-accent/80"
+ >
+ <Wand2 size={12} /> Continue
+ </button>
+ <button
+ onClick={() => setAutoConfigStep(null)}
+ className="rounded bg-port-border px-3 py-1.5 text-xs text-gray-400 hover:text-white"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ ) : (
+ <div className="flex items-center gap-1.5 p-2 text-xs text-port-success">
+ <Key size={12} />
+ Setup complete. Finish authorization in the opened tab.
+ </div>
+ )}
+
+ <details className="text-xs text-gray-600">
+ <summary className="cursor-pointer font-medium text-gray-400 hover:text-white">
+ Manual setup (paste credentials)
+ </summary>
+ <div className="mt-2 space-y-2">
+ <FormField label="Google OAuth Client ID" labelClassName="block text-xs text-gray-400 mb-1">
+ <input
+ type="text"
+ value={oauthForm.clientId}
+ onChange={e => setOauthForm(f => ({ ...f, clientId: e.target.value }))}
+ placeholder="123456789-abc.apps.googleusercontent.com"
+ className="w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-xs text-white placeholder-gray-600"
+ />
+ </FormField>
+ <FormField label="Google OAuth Client Secret" labelClassName="block text-xs text-gray-400 mb-1">
+ <input
+ type="password"
+ value={oauthForm.clientSecret}
+ onChange={e => setOauthForm(f => ({ ...f, clientSecret: e.target.value }))}
+ placeholder="GOCSPX-..."
+ className="w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-xs text-white placeholder-gray-600"
+ />
+ </FormField>
+ <button
+ onClick={handleSaveOAuthCredentials}
+ disabled={savingOAuth || !oauthForm.clientId || !oauthForm.clientSecret}
+ className="flex items-center gap-1 rounded bg-port-accent px-2.5 py-1.5 text-xs text-white hover:bg-port-accent/80 disabled:opacity-50"
+ >
+ {savingOAuth ? 'Saving...' : 'Save & Authorize'}
+ </button>
+ </div>
+ </details>
+ </div>
+ )}
+
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 text-sm">
<span className="w-2 h-2 rounded-full bg-gray-500" />
- <span className="text-gray-300">Gmail API enabled</span>
+ <span className="text-gray-300">Gmail API</span>
</div>
<button
onClick={handleEnableGmailApi}
@@ -284,8 +438,8 @@ export default function ConfigTab({ accounts, setAccounts }) {
</div>
</div>
<p className="text-xs text-gray-500">
- Gmail requires: 1) Gmail API enabled in Google Cloud Console, 2) Google OAuth authorized with Gmail scopes.
- If sync fails with "API not enabled", click "Enable in Console" above.
+ Gmail requires the Gmail API in Google Cloud and Google OAuth permission. Guided setup handles both;
+ manual setup can use "Enable in Console" to verify the API.
</p>
</div>
)}
@@ -350,6 +504,7 @@ export default function ConfigTab({ accounts, setAccounts }) {
<div className="space-y-2">
{accounts.map((account) => {
const Icon = TYPE_ICONS[account.type] || Mail;
+ const isPendingAuthorization = account.type === 'gmail' && account.enabled && !gmailAuthorized;
return (
<div
key={account.id}
@@ -387,12 +542,15 @@ export default function ConfigTab({ accounts, setAccounts }) {
<button
onClick={() => handleToggle(account)}
className={`px-2 py-1 rounded text-xs transition-colors ${
- account.enabled
+ isPendingAuthorization
+ ? 'bg-port-warning/20 text-port-warning'
+ : account.enabled
? 'bg-port-success/20 text-port-success'
: 'bg-gray-700 text-gray-400'
}`}
+ title={isPendingAuthorization ? 'Account is enabled but waiting for Google authorization' : undefined}
>
- {account.enabled ? 'Enabled' : 'Disabled'}
+ {isPendingAuthorization ? 'Pending authorization' : account.enabled ? 'Enabled' : 'Disabled'}
</button>
<button
onClick={() => handleClearCache(account.id)}
diff --git a/client/src/components/messages/ConfigTab.test.jsx b/client/src/components/messages/ConfigTab.test.jsx
new file mode 100644
index 0000000000..82e5b3e7c8
--- /dev/null
+++ b/client/src/components/messages/ConfigTab.test.jsx
@@ -0,0 +1,108 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+
+const api = vi.hoisted(() => ({
+ getGoogleAuthStatus: vi.fn(),
+ getGoogleAuthUrl: vi.fn(),
+ getSettings: vi.fn(),
+ runGoogleAutoConfig: vi.fn(),
+ saveGoogleAuthCredentials: vi.fn(),
+ startGoogleAutoConfig: vi.fn(),
+}));
+const toast = vi.hoisted(() => Object.assign(vi.fn(), {
+ error: vi.fn(),
+ success: vi.fn(),
+}));
+const providerModels = vi.hoisted(() => ({
+ availableModels: [],
+ loading: false,
+ providers: [],
+ selectedModel: '',
+ selectedProviderId: '',
+ setSelectedModel: vi.fn(),
+ setSelectedProviderId: vi.fn(),
+}));
+
+vi.mock('../../services/api', () => api);
+vi.mock('../ui/Toast', () => ({ default: toast }));
+vi.mock('../../hooks/useProviderModels', () => ({ default: () => providerModels }));
+
+const ConfigTab = (await import('./ConfigTab')).default;
+
+const gmailAccount = {
+ id: '11111111-1111-1111-1111-111111111111',
+ name: 'Personal',
+ type: 'gmail',
+ email: '[email protected]',
+ enabled: true,
+ syncConfig: { ingestSent: true },
+};
+
+function renderConfig() {
+ return render(
+ <MemoryRouter initialEntries={['/messages/config']}>
+ <ConfigTab accounts={[gmailAccount]} setAccounts={vi.fn()} />
+ </MemoryRouter>,
+ );
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.getSettings.mockResolvedValue({ messages: {} });
+ api.getGoogleAuthUrl.mockResolvedValue({ url: 'https://accounts.google.com/o/oauth2/auth?state=messages' });
+ api.saveGoogleAuthCredentials.mockResolvedValue({ clientId: 'client-id' });
+ vi.spyOn(window, 'open').mockImplementation(() => null);
+});
+
+describe('Messages Gmail OAuth setup', () => {
+ it('accepts OAuth credentials in Messages and starts authorization there', async () => {
+ api.getGoogleAuthStatus.mockResolvedValue({
+ hasCredentials: false,
+ hasTokens: false,
+ needsScopeUpgrade: true,
+ });
+ renderConfig();
+
+ expect(await screen.findByText('Google OAuth setup required')).toBeInTheDocument();
+ fireEvent.click(screen.getByText('Manual setup (paste credentials)'));
+ fireEvent.change(screen.getByLabelText('Google OAuth Client ID'), { target: { value: 'client-id' } });
+ fireEvent.change(screen.getByLabelText('Google OAuth Client Secret'), { target: { value: 'client-secret' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save & Authorize' }));
+
+ await waitFor(() => expect(api.saveGoogleAuthCredentials).toHaveBeenCalledWith(
+ { clientId: 'client-id', clientSecret: 'client-secret' },
+ { silent: true },
+ ));
+ await waitFor(() => expect(api.getGoogleAuthUrl).toHaveBeenCalledWith({ returnTo: 'messages', silent: true }));
+ expect(window.open).toHaveBeenCalledWith(
+ 'https://accounts.google.com/o/oauth2/auth?state=messages',
+ '_blank',
+ );
+ });
+
+ it('shows an enabled Gmail account as pending until Gmail OAuth is authorized', async () => {
+ api.getGoogleAuthStatus.mockResolvedValue({
+ hasCredentials: true,
+ hasTokens: false,
+ needsScopeUpgrade: true,
+ });
+ renderConfig();
+
+ expect(await screen.findByText('Google OAuth authorization pending')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Pending authorization' })).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Enabled' })).not.toBeInTheDocument();
+ });
+
+ it('keeps the account pending when existing Google tokens lack the Gmail scope', async () => {
+ api.getGoogleAuthStatus.mockResolvedValue({
+ hasCredentials: true,
+ hasTokens: true,
+ needsScopeUpgrade: true,
+ });
+ renderConfig();
+
+ expect(await screen.findByText('Google OAuth needs Gmail permission')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Pending authorization' })).toBeInTheDocument();
+ });
+});
diff --git a/client/src/services/apiCalendar.js b/client/src/services/apiCalendar.js
index 11b280bd54..e5edc2970e 100644
--- a/client/src/services/apiCalendar.js
+++ b/client/src/services/apiCalendar.js
@@ -19,7 +19,10 @@ export const mcpSyncGoogleCalendar = (accountId) => request(`/calendar/sync/${ac
export const mcpDiscoverCalendars = (accountId) => request(`/calendar/sync/${accountId}/discover`, { method: 'POST' });
export const getGoogleAuthStatus = () => request('/calendar/google/auth/status');
export const saveGoogleAuthCredentials = (data, options = {}) => request('/calendar/google/auth/credentials', { method: 'POST', body: JSON.stringify(data), ...options });
-export const getGoogleAuthUrl = (options = {}) => request('/calendar/google/auth/url', options);
+export const getGoogleAuthUrl = ({ returnTo, ...options } = {}) => {
+ const query = returnTo ? `?returnTo=${encodeURIComponent(returnTo)}` : '';
+ return request(`/calendar/google/auth/url${query}`, options);
+};
export const clearGoogleAuth = () => request('/calendar/google/auth/clear', { method: 'POST' });
export const apiSyncGoogleCalendar = (accountId) => request(`/calendar/sync/${accountId}/api`, { method: 'POST' });
export const apiDiscoverCalendars = (accountId) => request(`/calendar/sync/${accountId}/discover-api`, { method: 'POST' });
diff --git a/server/routes/calendar.js b/server/routes/calendar.js
index c553bc3f62..3ca2e3829b 100644
--- a/server/routes/calendar.js
+++ b/server/routes/calendar.js
@@ -234,7 +234,11 @@ router.post('/google/auth/credentials', asyncHandler(async (req, res) => {
}));
router.get('/google/auth/url', asyncHandler(async (req, res) => {
- const result = await googleAuth.getAuthUrl();
+ const { returnTo } = validateRequest(
+ z.object({ returnTo: z.enum(['calendar', 'messages']).optional().default('calendar') }),
+ req.query
+ );
+ const result = await googleAuth.getAuthUrl(returnTo);
res.json(result);
}));
@@ -242,9 +246,10 @@ router.get('/google/oauth/callback', asyncHandler(async (req, res) => {
// This endpoint is hit by a BROWSER redirect from Google, not by the SPA —
// render every outcome as a redirect to the config page (which toasts the
// oauthError param) instead of the JSON envelope the middleware would send.
+ const configPath = req.query.state === 'messages' ? '/messages/config' : '/calendar/config';
const configUrl = (error) => error
- ? `/calendar/config?oauthError=${encodeURIComponent(error)}`
- : '/calendar/config';
+ ? `${configPath}?oauthError=${encodeURIComponent(error)}`
+ : configPath;
const code = req.query.code;
if (!code) return res.redirect(configUrl('Missing authorization code'));
const error = await googleAuth.handleCallback(code).then(() => null)
diff --git a/server/routes/calendar.test.js b/server/routes/calendar.test.js
index 035abd1e2b..097a63d878 100644
--- a/server/routes/calendar.test.js
+++ b/server/routes/calendar.test.js
@@ -77,6 +77,7 @@ describe('Calendar Routes — normalized error handling', () => {
// The OAuth callback redirects the BROWSER here — echo the query so tests
// can assert what landed (fetch follows redirects by default).
app.get('/calendar/config', (req, res) => res.json({ landed: true, oauthError: req.query.oauthError ?? null }));
+ app.get('/messages/config', (req, res) => res.json({ landed: true, destination: 'messages', oauthError: req.query.oauthError ?? null }));
vi.clearAllMocks();
});
@@ -154,6 +155,16 @@ describe('Calendar Routes — normalized error handling', () => {
expect(response.status).toBe(200);
expect(response.body.url).toMatch(/^https:\/\/accounts\.google\.com/);
+ expect(googleAuth.getAuthUrl).toHaveBeenCalledWith('calendar');
+ });
+
+ it('GET /google/auth/url preserves a Messages return target', async () => {
+ googleAuth.getAuthUrl.mockResolvedValue({ url: 'https://accounts.google.com/o/oauth2/auth?state=messages' });
+
+ const response = await request(app).get('/api/calendar/google/auth/url?returnTo=messages');
+
+ expect(response.status).toBe(200);
+ expect(googleAuth.getAuthUrl).toHaveBeenCalledWith('messages');
});
});
@@ -167,6 +178,15 @@ describe('Calendar Routes — normalized error handling', () => {
expect(googleAuth.handleCallback).toHaveBeenCalledWith('ok');
});
+ it('returns to Messages when authorization started there', async () => {
+ googleAuth.handleCallback.mockResolvedValue({ success: true });
+
+ const response = await request(app).get('/api/calendar/google/oauth/callback?code=ok&state=messages');
+
+ expect(response.body).toEqual({ landed: true, destination: 'messages', oauthError: null });
+ expect(googleAuth.handleCallback).toHaveBeenCalledWith('ok');
+ });
+
it('redirects with oauthError when the code is missing', async () => {
const response = await request(app).get('/api/calendar/google/oauth/callback');
diff --git a/server/services/googleAuth.js b/server/services/googleAuth.js
index b96ca97f1f..9554e8512f 100644
--- a/server/services/googleAuth.js
+++ b/server/services/googleAuth.js
@@ -63,7 +63,7 @@ function createOAuth2Client(credentials) {
);
}
-export async function getAuthUrl() {
+export async function getAuthUrl(returnTo = 'calendar') {
const credentials = await getCredentials();
if (!credentials) throw new ServerError('No Google OAuth credentials configured', { status: 400 });
@@ -71,7 +71,11 @@ export async function getAuthUrl() {
const url = client.generateAuthUrl({
access_type: 'offline',
prompt: 'consent',
- scope: SCOPES
+ scope: SCOPES,
+ // The callback is shared by Calendar and Messages. Keep the return target
+ // in Google's round trip so authorization started in Messages lands back
+ // on the Messages config tab.
+ state: returnTo === 'messages' ? 'messages' : 'calendar'
});
return { url };
}