Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(connectors): complete native Pipedream authorization in the browser (#8178)

Eric Hayes9f3c5e8b8f56
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index c2a88c4cd0..388abda723 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -66,6 +66,17 @@ Then trigger the interaction and read `window.__inst.log`. `'1,2,3' → '' → '
## Development Patterns
+### Pipedream native authorization
+
+Keep native Pipedream consent in the system browser: the desktop navigation
+plugin redirects external popups and breaks the embedded iframe's return path.
+`pipedream-connect.html` is a separate Vite entry, served at
+`/app/pipedream-connect.html`, without a Macro browser login. The Connect token
+and one-time state travel only in its URL fragment, which the page removes on
+load. Its **Return to Macro** link is consumed by the Tauri navigation bridge
+without changing the active route. Backend registration still verifies account
+ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.
+
### General
- Disable GraphQL cache sessions and clear login hints on confirmed auth 401s,
even with retained user data; preserve session state on transient failures.
diff --git a/apps/web/pipedream-connect.html b/apps/web/pipedream-connect.html
new file mode 100644
index 0000000000..25cc2fbb59
--- /dev/null
+++ b/apps/web/pipedream-connect.html
@@ -0,0 +1,22 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="referrer" content="no-referrer" />
+ <title>Connect to Macro</title>
+ <style>
+ :root { color-scheme: light dark; font-family: system-ui, sans-serif; }
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; }
+ main { max-width: 30rem; margin: 2rem; line-height: 1.6; }
+ a { display: block; margin-top: 1rem; }
+ </style>
+ </head>
+ <body>
+ <main id="connect" aria-live="polite"></main>
+ <script type="module">
+ import { mountPipedreamBrowserConnect } from '/src/lib/core/pipedream/connect-browser.ts';
+ mountPipedreamBrowserConnect(document.getElementById('connect'));
+ </script>
+ </body>
+</html>
diff --git a/apps/web/src/lib/core/auth/logout.ts b/apps/web/src/lib/core/auth/logout.ts
index 8ed8c9f855..39e5173b39 100644
--- a/apps/web/src/lib/core/auth/logout.ts
+++ b/apps/web/src/lib/core/auth/logout.ts
@@ -1,6 +1,7 @@
import { clearMcpAuthAttempts } from '@app/features/settings/mcp-auth-attempt';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { SERVER_HOSTS } from '@core/constant/servers';
+import { clearPipedreamCallbacks } from '@core/pipedream/connect-callback';
import { syncLoginStorage } from '@core/util/cookies';
import { isTauri } from '@core/util/platform';
import { clearPostLoginRedirect } from '@core/util/postLoginRedirect';
@@ -45,6 +46,7 @@ const unauthenticatedUserInfo: UserInfoData = {
};
export async function clearLocalAuthSession() {
+ clearPipedreamCallbacks();
document.cookie =
'login=false; expires=Thu, 01 Jan 1970 00:00:00 UTC; max-age=0; path=/; SameSite=Lax';
syncLoginStorage(false);
diff --git a/apps/web/src/lib/core/pipedream/connect-browser.test.ts b/apps/web/src/lib/core/pipedream/connect-browser.test.ts
new file mode 100644
index 0000000000..07d94b6ae8
--- /dev/null
+++ b/apps/web/src/lib/core/pipedream/connect-browser.test.ts
@@ -0,0 +1,65 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { mountPipedreamBrowserConnect } from './connect-browser';
+
+afterEach(() => {
+ document.body.innerHTML = '';
+ history.replaceState(null, '', '/');
+});
+
+describe('browser connection handoff', () => {
+ it.each(['success', 'close'])(
+ 'returns %s to the waiting native session',
+ (type) => {
+ history.replaceState(
+ null,
+ '',
+ '/pipedream-connect.html#token=fixture&app=linear&state=nonce'
+ );
+ const root = document.createElement('main');
+ document.body.appendChild(root);
+ mountPipedreamBrowserConnect(root);
+ expect(location.hash).toBe('');
+ const iframe = document.querySelector('iframe')!;
+ expect(new URL(iframe.src).searchParams.get('token')).toBe('fixture');
+ window.dispatchEvent(
+ new MessageEvent('message', {
+ origin: 'https://pipedream.com',
+ source: window,
+ data: { type, authProvisionId: 'apn_test' },
+ })
+ );
+ expect(root.querySelector('a')).toBeNull();
+ window.dispatchEvent(
+ new MessageEvent('message', {
+ origin: 'https://pipedream.com',
+ source: iframe.contentWindow,
+ data: { type, authProvisionId: 'apn_test' },
+ })
+ );
+ const callback = new URL(root.querySelector('a')!.href);
+ expect(callback.protocol).toBe('macro:');
+ expect(callback.pathname).toBe('/pipedream-connect-callback');
+ expect(callback.searchParams.get('state')).toBe('nonce');
+ expect(callback.searchParams.get('outcome')).toBe(
+ type === 'success' ? 'success' : 'closed'
+ );
+ expect(callback.searchParams.get('account_id')).toBe(
+ type === 'success' ? 'apn_test' : null
+ );
+ expect(callback.href).not.toContain('fixture');
+ expect(document.querySelector('iframe')).toBeNull();
+ }
+ );
+
+ it('does not open consent without the complete handoff', () => {
+ history.replaceState(
+ null,
+ '',
+ '/pipedream-connect.html#token=fixture&app=linear'
+ );
+ mountPipedreamBrowserConnect(document.body);
+ expect(document.querySelector('iframe')).toBeNull();
+ expect(document.body.textContent).toContain('Start again in Macro');
+ expect(location.hash).toBe('');
+ });
+});
diff --git a/apps/web/src/lib/core/pipedream/connect-browser.ts b/apps/web/src/lib/core/pipedream/connect-browser.ts
new file mode 100644
index 0000000000..8220296400
--- /dev/null
+++ b/apps/web/src/lib/core/pipedream/connect-browser.ts
@@ -0,0 +1,42 @@
+import { PIPEDREAM_CALLBACK_PATH } from './connect-callback';
+import { openPipedreamConnectUI } from './connect-ui';
+
+/** Standalone browser handoff; no Macro browser login is needed. */
+export function mountPipedreamBrowserConnect(root: HTMLElement) {
+ const params = new URLSearchParams(window.location.hash.slice(1));
+ history.replaceState(null, '', window.location.pathname);
+ const token = params.get('token');
+ const app = params.get('app');
+ const state = params.get('state');
+ if (!token || !app || !state) {
+ root.textContent =
+ 'This connection link has expired. Start again in Macro.';
+ return;
+ }
+ root.textContent = 'Connect your account to continue.';
+ const ui = openPipedreamConnectUI({
+ token,
+ app,
+ onEvent: (event) => {
+ // Pipedream displays recoverable errors inside its own UI.
+ if (event.type === 'error') return;
+ ui.close();
+ const callback = new URL(`macro://${PIPEDREAM_CALLBACK_PATH}`);
+ callback.searchParams.set('state', state);
+ callback.searchParams.set(
+ 'outcome',
+ event.type === 'success' ? 'success' : 'closed'
+ );
+ if (event.type === 'success')
+ callback.searchParams.set('account_id', event.accountId);
+ root.textContent =
+ event.type === 'success'
+ ? 'Authorization finished. Return to Macro to save your connection.'
+ : 'Connection canceled. Return to Macro to continue.';
+ const link = document.createElement('a');
+ link.href = callback.href;
+ link.textContent = 'Return to Macro';
+ root.appendChild(link);
+ },
+ });
+}
diff --git a/apps/web/src/lib/core/pipedream/connect-callback.test.ts b/apps/web/src/lib/core/pipedream/connect-callback.test.ts
new file mode 100644
index 0000000000..b54fc05a7f
--- /dev/null
+++ b/apps/web/src/lib/core/pipedream/connect-callback.test.ts
@@ -0,0 +1,60 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ clearPipedreamCallbacks,
+ handlePipedreamCallback,
+ PIPEDREAM_CALLBACK_PATH,
+ registerPipedreamCallback,
+} from './connect-callback';
+
+afterEach(clearPipedreamCallbacks);
+
+describe('native Pipedream return', () => {
+ it('accepts a matching success exactly once and leaves other attempts pending', () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ const { state } = registerPipedreamCallback(first);
+ registerPipedreamCallback(second);
+ const query = `state=${state}&outcome=success&account_id=apn_test`;
+ expect(handlePipedreamCallback('/settings', query)).toBe(false);
+ handlePipedreamCallback(
+ PIPEDREAM_CALLBACK_PATH,
+ query.replace(state, 'foreign')
+ );
+ handlePipedreamCallback(
+ PIPEDREAM_CALLBACK_PATH,
+ `state=${state}&outcome=success`
+ );
+ expect(first).not.toHaveBeenCalled();
+ expect(handlePipedreamCallback(PIPEDREAM_CALLBACK_PATH, query)).toBe(true);
+ handlePipedreamCallback(PIPEDREAM_CALLBACK_PATH, query);
+ expect(first).toHaveBeenCalledExactlyOnceWith({
+ type: 'success',
+ accountId: 'apn_test',
+ });
+ expect(second).not.toHaveBeenCalled();
+ });
+
+ it('consumes canceled and expired callbacks without accepting late success', () => {
+ const onEvent = vi.fn();
+ const { state, remove } = registerPipedreamCallback(onEvent);
+ remove();
+ expect(
+ handlePipedreamCallback(
+ PIPEDREAM_CALLBACK_PATH,
+ `state=${state}&outcome=success&account_id=apn_test`
+ )
+ ).toBe(true);
+ expect(onEvent).not.toHaveBeenCalled();
+ });
+
+ it('closes pending flows on logout and ignores their eventual return', () => {
+ const onEvent = vi.fn();
+ const { state } = registerPipedreamCallback(onEvent);
+ clearPipedreamCallbacks();
+ handlePipedreamCallback(
+ PIPEDREAM_CALLBACK_PATH,
+ `state=${state}&outcome=success&account_id=apn_test`
+ );
+ expect(onEvent).toHaveBeenCalledExactlyOnceWith({ type: 'close' });
+ });
+});
diff --git a/apps/web/src/lib/core/pipedream/connect-callback.ts b/apps/web/src/lib/core/pipedream/connect-callback.ts
new file mode 100644
index 0000000000..9bc9af41a1
--- /dev/null
+++ b/apps/web/src/lib/core/pipedream/connect-callback.ts
@@ -0,0 +1,40 @@
+import type { PipedreamConnectEvent } from './connect-ui';
+
+export const PIPEDREAM_CALLBACK_PATH = '/pipedream-connect-callback';
+
+// One-use callbacks belong to a live native session, never persisted storage.
+const pending = new Map<string, (event: PipedreamConnectEvent) => void>();
+
+export function registerPipedreamCallback(
+ onEvent: (event: PipedreamConnectEvent) => void
+) {
+ const state = crypto.randomUUID();
+ pending.set(state, onEvent);
+ return { state, remove: () => pending.delete(state) };
+}
+
+/** Consume even stale callbacks so they never replace the user's current route. */
+export function handlePipedreamCallback(path: string, query: string): boolean {
+ if (path !== PIPEDREAM_CALLBACK_PATH) return false;
+ const params = new URLSearchParams(query);
+ const state = params.get('state') ?? '';
+ const callback = pending.get(state);
+ if (!callback) return true;
+ const accountId = params.get('account_id');
+ const outcome = params.get('outcome');
+ if (outcome !== 'closed' && !(outcome === 'success' && accountId))
+ return true;
+ pending.delete(state);
+ callback(
+ outcome === 'success' && accountId
+ ? { type: 'success', accountId }
+ : { type: 'close' }
+ );
+ return true;
+}
+
+export function clearPipedreamCallbacks() {
+ const callbacks = [...pending.values()];
+ pending.clear();
+ for (const callback of callbacks) callback({ type: 'close' });
+}
diff --git a/apps/web/src/lib/core/pipedream/connect-native.test.tsx b/apps/web/src/lib/core/pipedream/connect-native.test.tsx
new file mode 100644
index 0000000000..26968de0eb
--- /dev/null
+++ b/apps/web/src/lib/core/pipedream/connect-native.test.tsx
@@ -0,0 +1,80 @@
+import { fireEvent, screen } from '@solidjs/testing-library';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ clearPipedreamCallbacks,
+ handlePipedreamCallback,
+ PIPEDREAM_CALLBACK_PATH,
+} from './connect-callback';
+import { openNativePipedreamConnectUI } from './connect-native';
+
+const mocks = vi.hoisted(() => ({
+ open: vi.fn(async (_command: string, _args: { url: string }) => {}),
+}));
+vi.mock('@tauri-apps/api/core', () => ({ invoke: mocks.open }));
+vi.mock('@core/util/webOrigin', () => ({
+ getWebOrigin: () => 'https://dev.macro.com',
+}));
+
+beforeEach(() => vi.stubGlobal('scrollTo', vi.fn()));
+
+afterEach(() => {
+ clearPipedreamCallbacks();
+ vi.clearAllMocks();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('native browser connection dialog', () => {
+ it('opens the browser without a native iframe and allows cancellation and retry', () => {
+ const onEvent = vi.fn();
+ openNativePipedreamConnectUI({ token: 'fixture', app: 'linear', onEvent });
+ expect(document.querySelector('iframe')).toBeNull();
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ expect(mocks.open.mock.calls[0][0]).toBe('plugin:opener|open_url');
+ const url = new URL(mocks.open.mock.calls[0][1].url);
+ expect(url.origin + url.pathname).toBe(
+ 'https://dev.macro.com/app/pipedream-connect.html'
+ );
+ expect(url.search).toBe('');
+ const params = new URLSearchParams(url.hash.slice(1));
+ expect(params.get('token')).toBe('fixture');
+ fireEvent.click(screen.getByRole('button', { name: 'Open browser again' }));
+ expect(mocks.open).toHaveBeenLastCalledWith('plugin:opener|open_url', {
+ url: url.href,
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ handlePipedreamCallback(
+ PIPEDREAM_CALLBACK_PATH,
+ `state=${params.get('state')}&outcome=success&account_id=apn_test`
+ );
+ expect(onEvent).toHaveBeenCalledExactlyOnceWith({ type: 'close' });
+ openNativePipedreamConnectUI({ token: 'retry', app: 'linear', onEvent });
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ });
+
+ it('closes the dialog when consent returns and releases the callback', () => {
+ const onEvent = vi.fn();
+ openNativePipedreamConnectUI({ token: 'fixture', app: 'linear', onEvent });
+ const state = new URLSearchParams(
+ new URL(mocks.open.mock.calls[0][1].url).hash.slice(1)
+ ).get('state');
+ const query = `state=${state}&outcome=success&account_id=apn_test`;
+ handlePipedreamCallback(PIPEDREAM_CALLBACK_PATH, query);
+ handlePipedreamCallback(PIPEDREAM_CALLBACK_PATH, query);
+ expect(onEvent).toHaveBeenCalledExactlyOnceWith({
+ type: 'success',
+ accountId: 'apn_test',
+ });
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+
+ it('releases an abandoned attempt after ten minutes', () => {
+ vi.useFakeTimers();
+ const onEvent = vi.fn();
+ openNativePipedreamConnectUI({ token: 'fixture', app: 'linear', onEvent });
+ vi.advanceTimersByTime(10 * 60 * 1000);
+ expect(onEvent).toHaveBeenCalledExactlyOnceWith({ type: 'close' });
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+});
diff --git a/apps/web/src/lib/core/pipedream/connect-native.tsx b/apps/web/src/lib/core/pipedream/connect-native.tsx
new file mode 100644
index 0000000000..9a55c9cef6
--- /dev/null
+++ b/apps/web/src/lib/core/pipedream/connect-native.tsx
@@ -0,0 +1,84 @@
+import { fireAndForget } from '@core/util/fireAndForget';
+import { getWebOrigin } from '@core/util/webOrigin';
+import { invoke } from '@tauri-apps/api/core';
+import { Button } from '@ui/components/Button';
+import { Dialog } from '@ui/components/Dialog';
+import { ResultAsync } from 'neverthrow';
+import { createSignal, Show } from 'solid-js';
+import { render } from 'solid-js/web';
+import { registerPipedreamCallback } from './connect-callback';
+import type { openPipedreamConnectUI, PipedreamConnectUI } from './connect-ui';
+
+/** Run consent in a browser: native popup interception breaks iframe OAuth. */
+export function openNativePipedreamConnectUI(
+ options: Parameters<typeof openPipedreamConnectUI>[0]
+): PipedreamConnectUI {
+ const host = document.createElement('div');
+ (options.container ?? document.body).appendChild(host);
+ const callback = registerPipedreamCallback((event) => {
+ close();
+ options.onEvent(event);
+ });
+ const url = new URL('/app/pipedream-connect.html', getWebOrigin());
+ // Fragments never reach the host's access logs or Referer headers.
+ url.hash = new URLSearchParams({
+ token: options.token,
+ app: options.app,
+ state: callback.state,
+ }).toString();
+ const cancel = () => {
+ close();
+ options.onEvent({ type: 'close' });
+ };
+ const timer = setTimeout(cancel, 10 * 60 * 1000);
+ let closed = false;
+ const [openFailed, setOpenFailed] = createSignal(false);
+ const launch = async () => {
+ // This hosted /app page must bypass Macro's ordinary in-app link routing.
+ const result = await ResultAsync.fromPromise(
+ invoke('plugin:opener|open_url', { url: url.href }),
+ () => undefined
+ );
+ if (!closed) setOpenFailed(result.isErr());
+ };
+ const dispose = render(
+ () => (
+ <Dialog open onOpenChange={(open) => !open && cancel()}>
+ <div class="flex flex-col gap-4 p-6 bg-panel text-ink rounded-lg">
+ <Dialog.Title>Finish connecting in your browser</Dialog.Title>
+ <Dialog.Description>
+ Authorize the connection, then choose Return to Macro. If you closed
+ the browser tab, cancel and try again.
+ </Dialog.Description>
+ <Show when={openFailed()}>
+ <p role="alert">
+ Could not open your browser. Try again or cancel.
+ </p>
+ </Show>
+ <div class="flex gap-2">
+ <Button
+ variant="outline"
+ onClick={() => fireAndForget(launch(), 'pipedream-connect-open')}
+ >
+ Open browser again
+ </Button>
+ <Button variant="ghost" onClick={cancel}>
+ Cancel
+ </Button>
+ </div>
+ </div>
+ </Dialog>
+ ),
+ host
+ );
+ function close() {
+ if (closed) return;
+ closed = true;
+ clearTimeout(timer);
+ callback.remove();
+ dispose();
+ host.remove();
+ }
+ fireAndForget(launch(), 'pipedream-connect-open');
+ return { close };
+}
diff --git a/apps/web/src/lib/queries/pipedream-connectors.test.ts b/apps/web/src/lib/queries/pipedream-connectors.test.ts
index a5fc2befc9..66d8f5a0f1 100644
--- a/apps/web/src/lib/queries/pipedream-connectors.test.ts
+++ b/apps/web/src/lib/queries/pipedream-connectors.test.ts
@@ -1,3 +1,4 @@
+import type { openPipedreamConnectUI } from '@core/pipedream/connect-ui';
import { ok } from 'neverthrow';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -7,6 +8,13 @@ const mocks = vi.hoisted(() => ({
complete: vi.fn(),
setData: vi.fn(),
invalidate: vi.fn(async () => {}),
+ native: false,
+ openNative: vi.fn(),
+ userId: 'user-one',
+}));
+vi.mock('@core/util/platform', () => ({ isTauri: () => mocks.native }));
+vi.mock('@core/pipedream/connect-native', () => ({
+ openNativePipedreamConnectUI: mocks.openNative,
}));
vi.mock('@core/pipedream/connect-ui', () => ({
openPipedreamConnectUI: mocks.open,
@@ -15,6 +23,7 @@ vi.mock('@queries/client', () => ({
queryClient: {
setQueryData: mocks.setData,
invalidateQueries: mocks.invalidate,
+ getQueryData: () => ({ id: mocks.userId }),
},
}));
vi.mock('@service-cognition/client', () => ({
@@ -29,17 +38,67 @@ import { connectPipedreamApp } from './pipedream-connectors';
beforeEach(() => {
vi.clearAllMocks();
+ mocks.native = false;
+ mocks.userId = 'user-one';
mocks.open.mockImplementation(() => ({ close: mocks.close }));
+ mocks.openNative.mockImplementation(() => ({ close: mocks.close }));
});
-async function connect() {
- const pending = connectPipedreamApp({ appSlug: 'linear' });
- await vi.waitFor(() => expect(mocks.open).toHaveBeenCalledOnce());
- const event = mocks.open.mock.calls[0][0].onEvent;
- return { pending, event };
+async function connect(native = false) {
+ mocks.native = native;
+ const opened =
+ Promise.withResolvers<Parameters<typeof openPipedreamConnectUI>[0]>();
+ (native ? mocks.openNative : mocks.open).mockImplementation((options) => {
+ opened.resolve(options);
+ return { close: mocks.close };
+ });
+ const pending = connectPipedreamApp({
+ appSlug: 'linear',
+ serverName: 'Linear',
+ });
+ const { onEvent } = await opened.promise;
+ return { pending, event: onEvent };
}
describe('verified Pipedream connection completion', () => {
+ it('does not attach a browser result after the user changes accounts', async () => {
+ const { pending, event } = await connect();
+ mocks.userId = 'user-two';
+ event({ type: 'success', accountId: 'apn_test' });
+ expect(await pending).toBe('closed');
+ expect(mocks.complete).not.toHaveBeenCalled();
+ });
+
+ it('does not populate another account cache when registration finishes late', async () => {
+ let complete!: (value: { app_slug: string; enabled: boolean }) => void;
+ mocks.complete.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ complete = (connection) => resolve(ok(connection));
+ })
+ );
+ const { pending, event } = await connect();
+ event({ type: 'success', accountId: 'apn_test' });
+ mocks.userId = 'user-two';
+ complete({ app_slug: 'linear', enabled: true });
+ expect(await pending).toBe('closed');
+ expect(mocks.setData).not.toHaveBeenCalled();
+ });
+ it('opens native consent in the browser and verifies the returned account before success', async () => {
+ mocks.complete.mockResolvedValue(ok({ app_slug: 'linear', enabled: true }));
+ const { pending, event } = await connect(true);
+ expect(mocks.open).not.toHaveBeenCalled();
+ expect(mocks.complete).not.toHaveBeenCalled();
+ event({
+ type: 'success',
+ accountId: 'apn_test',
+ });
+ expect(await pending).toBe('connected');
+ expect(mocks.complete).toHaveBeenCalledExactlyOnceWith({
+ account_id: 'apn_test',
+ server_name: 'Linear',
+ });
+ });
it('reports success only after the requested enabled connection is registered', async () => {
mocks.complete.mockResolvedValue(ok({ app_slug: 'linear', enabled: true }));
const { pending, event } = await connect();
diff --git a/apps/web/src/lib/queries/pipedream-connectors.ts b/apps/web/src/lib/queries/pipedream-connectors.ts
index f2d8aa446b..58639147aa 100644
--- a/apps/web/src/lib/queries/pipedream-connectors.ts
+++ b/apps/web/src/lib/queries/pipedream-connectors.ts
@@ -1,7 +1,11 @@
import { openPipedreamConnectUI } from '@core/pipedream/connect-ui';
import { pipedreamSlugsMatch } from '@core/pipedream/slugs';
import { fireAndForget } from '@core/util/fireAndForget';
+import { isTauri } from '@core/util/platform';
import { ThrownResultError, throwOnErr } from '@core/util/result';
+import { type Span, Telemetry } from '@macro-inc/observability';
+import { authKeys } from '@queries/auth/keys';
+import type { UserInfoData } from '@queries/auth/user-info';
import { queryClient } from '@queries/client';
import { queryReadyGate } from '@queries/gate';
import {
@@ -195,7 +199,8 @@ let pipedreamUnsupported = false;
*
* Mints a Connect token (Pipedream owns the consent flow, credential
* storage, and refresh), opens the hosted Connect UI in a fullscreen
- * iframe, and — once the user authorizes — registers the resulting account
+ * iframe on web or in the system browser on native, and — once the user
+ * authorizes — registers the resulting account
* with our backend, which verifies ownership against Pipedream before
* storing it.
*
@@ -212,9 +217,33 @@ export async function connectPipedreamApp(args: {
/** Where the Connect iframe mounts; see `openPipedreamConnectUI`. */
container?: HTMLElement;
}): Promise<PipedreamConnectOutcome> {
+ return Telemetry.span('pipedream.connect', async (span) => {
+ span.setAttr('connector.app_slug', args.appSlug);
+ span.setAttr('connector.native', isTauri());
+ try {
+ const outcome = await connectPipedreamAccount(args, span);
+ span.setAttr('connector.outcome', outcome);
+ return outcome;
+ } catch (error) {
+ // Do not copy third-party errors or Connect URLs into telemetry.
+ span.error('Pipedream connection failed');
+ throw error;
+ }
+ });
+}
+
+async function connectPipedreamAccount(
+ args: Parameters<typeof connectPipedreamApp>[0],
+ span: Span
+): Promise<PipedreamConnectOutcome> {
if (pipedreamUnsupported) return 'unsupported';
- const token = await cognitionApiServiceClient.createPipedreamToken();
+ const currentUserId = () =>
+ queryClient.getQueryData<UserInfoData>(authKeys.userInfo.queryKey)?.id;
+ const userId = currentUserId();
+ const token = await span.span('pipedream.token', async () =>
+ cognitionApiServiceClient.createPipedreamToken()
+ );
if (token.isErr()) {
if (token.error.some((e) => e.code === PIPEDREAM_DISABLED)) {
pipedreamUnsupported = true;
@@ -223,27 +252,46 @@ export async function connectPipedreamApp(args: {
throw new ThrownResultError(token.error);
}
+ const openConnectUI = isTauri()
+ ? (await import('@core/pipedream/connect-native'))
+ .openNativePipedreamConnectUI
+ : openPipedreamConnectUI;
+ if (currentUserId() !== userId) return 'closed';
+ const consent = span.span('pipedream.consent');
return await new Promise<PipedreamConnectOutcome>((resolve, reject) => {
let settled = false;
- const ui = openPipedreamConnectUI({
+ const ui = openConnectUI({
token: token.value.token,
app: args.appSlug,
container: args.container,
onEvent: (event) => {
if (event.type === 'success' && !settled) {
settled = true;
+ consent.end();
fireAndForget(
(async () => {
try {
- const connection = await throwOnErr(
+ if (currentUserId() !== userId) {
+ resolve('closed');
+ return;
+ }
+ const connection = await span.span(
+ 'pipedream.register',
async () =>
- await cognitionApiServiceClient.completePipedreamConnection(
- {
- account_id: event.accountId,
- server_name: args.serverName,
- }
+ throwOnErr(
+ async () =>
+ await cognitionApiServiceClient.completePipedreamConnection(
+ {
+ account_id: event.accountId,
+ server_name: args.serverName,
+ }
+ )
)
);
+ if (currentUserId() !== userId) {
+ resolve('closed');
+ return;
+ }
if (
!pipedreamSlugsMatch(connection.app_slug, args.appSlug) ||
!connection.enabled
@@ -267,11 +315,12 @@ export async function connectPipedreamApp(args: {
);
} else if (event.type === 'close' && !settled) {
settled = true;
+ consent.end();
resolve('closed');
}
// 'error' events are shown inside the Connect UI itself; the user
// can retry there or close, so they don't settle the promise.
},
});
- });
+ }).finally(() => consent.end());
}
diff --git a/apps/web/src/lib/tauri/navigation.test.ts b/apps/web/src/lib/tauri/navigation.test.ts
index d40f502aea..3614e88c91 100644
--- a/apps/web/src/lib/tauri/navigation.test.ts
+++ b/apps/web/src/lib/tauri/navigation.test.ts
@@ -24,6 +24,7 @@ vi.mock('./macroLinkInterceptor', () => ({
registerMacroLinkInterceptor: () => () => {},
}));
+import { registerPipedreamCallback } from '@core/pipedream/connect-callback';
import { useTauriNavigationEffect } from './navigation';
let dispose: (() => void) | undefined;
@@ -46,6 +47,32 @@ beforeEach(() => {
afterEach(() => dispose?.());
describe('native link session routing', () => {
+ it('completes a connector callback without navigating away from the active chat', () => {
+ const onEvent = vi.fn();
+ const { state } = registerPipedreamCallback(onEvent);
+ receive({
+ payload: {
+ path: '/pipedream-connect-callback',
+ query: `state=${state}&outcome=success&account_id=apn_test`,
+ },
+ });
+ expect(onEvent).toHaveBeenCalledExactlyOnceWith({
+ type: 'success',
+ accountId: 'apn_test',
+ });
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ expect(mocks.setPostLoginRedirect).not.toHaveBeenCalled();
+ });
+
+ it('ignores stale connector callbacks without routing to a missing page', () => {
+ receive({
+ payload: {
+ path: '/pipedream-connect-callback',
+ query: 'state=expired&outcome=closed',
+ },
+ });
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
it('preserves query parameters on Android root links', () => {
receive({
payload: { path: '/', query: 'subscriptionSuccess=true&type=pro' },
diff --git a/apps/web/src/lib/tauri/navigation.ts b/apps/web/src/lib/tauri/navigation.ts
index 9ec57c5a42..f1d910ea2a 100644
--- a/apps/web/src/lib/tauri/navigation.ts
+++ b/apps/web/src/lib/tauri/navigation.ts
@@ -1,3 +1,4 @@
+import { handlePipedreamCallback } from '@core/pipedream/connect-callback';
import { getNativeMobilePlatform } from '@core/util/platform';
import { setPostLoginRedirect } from '@core/util/postLoginRedirect';
import { Telemetry } from '@macro-inc/observability';
@@ -25,6 +26,7 @@ export function useTauriNavigationEffect() {
async function inner() {
unsubscribe = await listen<NavigateEvent>('navigate', (ev) => {
+ if (handlePipedreamCallback(ev.payload.path, ev.payload.query)) return;
const path = ev.payload.query
? `${ev.payload.path}?${ev.payload.query}`
: ev.payload.path;
diff --git a/apps/web/vite.base.ts b/apps/web/vite.base.ts
index a7ce1b0807..ee4d3cbe7a 100644
--- a/apps/web/vite.base.ts
+++ b/apps/web/vite.base.ts
@@ -368,6 +368,7 @@ export const createAppViteConfig = (): UserConfigFn => {
rollupOptions: {
input: {
app: resolve(__dirname, 'index.html'),
+ pipedreamConnect: resolve(__dirname, 'pipedream-connect.html'),
},
// KaTeX and PDF.js are now reachable through lazy boundaries. Let
// Rollup place them naturally; forcing lazy code into named chunks
diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.md
index a71abb2e51..2e0f5752f2 100644
--- a/docs/agent-guide/ai-chat.md
+++ b/docs/agent-guide/ai-chat.md
@@ -22,7 +22,10 @@ tool list. Expand the discovery row to see the results. An app name alone does
not establish that the requested action is supported.
For a suitable unconnected app, the assistant offers **Connect <app>**. Clicking
-it opens the hosted authorization flow over the agent transcript. After the
+it opens the hosted authorization flow over the agent transcript on web. In
+native apps, consent opens in the system browser; choose **Return to Macro**
+after authorization. The waiting dialog also offers **Cancel**, and callbacks
+from canceled or expired attempts cannot resume the agent. After the
backend verifies and registers the connection, the agent session sends a visible
continuation message in the same conversation. Before that message reaches the
agent, the harness hands the live session its permitted connector servers again
diff --git a/docs/agent-guide/media/pipedream/browser-return.png b/docs/agent-guide/media/pipedream/browser-return.png
new file mode 100644
index 0000000000..cda4746e1e
Binary files /dev/null and b/docs/agent-guide/media/pipedream/browser-return.png differ
diff --git a/docs/agent-guide/media/pipedream/native-waiting.png b/docs/agent-guide/media/pipedream/native-waiting.png
new file mode 100644
index 0000000000..58b8943a54
Binary files /dev/null and b/docs/agent-guide/media/pipedream/native-waiting.png differ
diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.md
index a291ff7e5f..47ead37acc 100644
--- a/docs/agent-guide/settings.md
+++ b/docs/agent-guide/settings.md
@@ -434,12 +434,19 @@ Profile, Behavior, Runtime, Connections, Channels, Share. Connections is a radio
connected) or `Specific apps`, which reveals a `Search connectors` box over the whole
Pipedream catalog (results are `option` rows; picking one adds it) and a row per picked app
with a connected / not-connected dot for the *current viewer* plus an inline `Connect`
-that opens the Pipedream Connect flow inside the page. Unconnected picks never block
+that opens the Pipedream Connect flow inside the web page. Native apps open
+consent in the system browser; choose **Return to Macro** after authorization
+to save the connection in the waiting app. Unconnected picks never block
saving; each teammate connects their own account. An agent session that calls a picked
but unconnected app gets a tool result saying so, and the agent's reply renders a
`Connect <app>` chip that opens Agents → Connections for that app. The same page
is also available as Settings → Agent connections.
+Reference captures from an isolated browser fixture: [native waiting dialog](media/pipedream/native-waiting.png)
+and [browser return page](media/pipedream/browser-return.png). The fixture uses
+the real UI and iframe messaging with simulated provider consent and native IPC;
+it does not exercise a real provider account or the operating system's app launch.
+
To change an agent's picture, open `Edit <name>`, choose an image with `Upload`,
wait for `Uploading…` to finish, then click `Save changes`. Images up to 16 MB
are uploaded to image storage; Save stays disabled during the upload. A failed