mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 03:31:44 +01:00
fix(ui): bundle connector, toolbar, empty-state and agent roster fixes (#18716)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Operators use connector setup, collection headers, empty states, and agent lists to manage that work. > - Provider redirects replace the setup page, and collection controls use different sizes. > - Agent selection inserts a bar above the list. The row link highlights only part of the row. > - This pull request keeps sign-in in a separate window and applies the Tasks control sizes to collection and audit headers. > - It also reuses artifact artwork for empty collections and gives agent selection a fixed action card. > - These changes preserve the operator's place and keep controls and rows stable. ## Linked Issues or Issue Description **What happened?** Connector sign-in replaced the current page. Inline collection controls had different heights. Projects and Artifacts used small placeholder empty states. Agent selection moved the list, hover covered only the identity cell, and chat/status shared that cell without matching headings. **Expected behavior** Provider sign-in opens in a new tab or window. Collection controls match Tasks. Empty collections use the large artifact graphics. Agent actions float above the page while rows remain aligned. **Steps to reproduce** Start connector sign-in from a page or dialog. Compare collection and Audit headers. Open an empty Projects or Artifacts collection. Select an agent, then hover across its row. Related public work: #13584 covers an earlier connector new-tab implementation, including same-page fallbacks that this bundle does not use. #8528 covers Tasks toggle sizing. #17742 covers scoped agent Audit sections. This bundle does not change server callback or audit authorization contracts. ## What Changed - Reserve a separate authorization window during the click. Use validated sign-in URLs, retain a new-tab fallback, and close blank windows after failed requests. Store Cloud reauthentication state in the destination window. - Use the Tasks 44px control foundation for shared collection headers and Audit, Costs, Timeline, Secrets, Teams, Gateways, and agent skill controls. - Use a large artifact stack with an off-white Paperclip image with a dark icon for Projects and artifact Tasks empty states. Use one matching artifact for other types. Set 20px gaps and use the label “Create project”. Action hover and keyboard focus animate the artwork. - Portal agent bulk actions to a fixed card 48px above the bottom safe area. Use quintic entry/exit motion and respect reduced motion. Retain card contents during exit. - Give chat and status separate cells, add a Status heading, use the MessagesSquare chat action with a hover tooltip, and highlight the entire row. - Add linked agent chips and a manager picker to the agent profile. Block self and descendant manager choices. Keep the name crown and custom title inline during edits. - Update design guidance, the connection maps, regression tests, and empty-state Storybook fixtures. ## Verification - Final commit `a41a6c6494a839deaaec1ef7cc50c90078ab6381`: all 55 checks passed, three skipped. [Canonical CI run](https://github.com/paperclipai/paperclip/actions/runs/41999792769) includes all eight browser shards and all server/runner/workspace groups. Greptile: 5/5, zero unresolved review findings. - Workspace typecheck/build passed. Local UI suite passed 11,006 tests in 880 files, plus 542 CLI tests. Subsequent connector callback changes passed all 245 AppsConnect tests, UI typecheck, token gates, and query-error policy checks. Manager cache/error regressions passed four tests. Map checks passed. - Local connector browser suite: 20 passed. All six chat integration shards: 1,931 passed. Workspace B groups passed; database tests passed 313 cases across 72 files with one worker. - Browser preview verified agent manager changes, overview links, inline name/title geometry, empty-state colors, row actions and the chat tooltip. Live provider consent and post-deployment feature verification remain separate from these fixtures. - Preserved failures: ten bulk-roster tests initially missed the portaled action card; their selectors were fixed and all twelve roster tests passed. A nested fixture selected pnpm 11 and removed local dependencies; the local shim now pins pnpm 9. Embedded PostgreSQL native links were restored. A Python 3.9 fixture failure passed all 19 tests with the current runtime. Concurrent local database startup failures passed on the one-worker rerun. - The broad local serialized server run passed 3,791 tests with one scheduling assertion failure, which passed in isolation. The local general-server run reproduced a native recovery provider/model fixture failure and has not completed. These server sources are unchanged by this bundle; all final canonical CI server shards passed. This is not a claim that every broad local run passed. - [Earlier CI run](https://github.com/paperclipai/paperclip/actions/runs/41995119880) failed a browser test during cleanup when heartbeat-run cancellation hit a PostgreSQL lock timeout. All final browser shards passed without weakening that test. - Review follow-ups cover Slack popup/fallback recovery, a single artwork hover transform, shared manager error rendering, detached standalone OAuth windows, and verified task-bound callbacks in both hosts. ## Risks - Browser popup policy and provider callback behavior can affect sign-in completion. The original setup page stays open; blocked windows have an explicit recovery path. - Shared toolbar styles affect several surfaces. Menu content remains in its existing portals; canonical label tabs and search clear buttons retain their own geometry. - No schema, server, API authorization, or migration change. - Required CI and review are complete. Deployment provenance and hosted feature verification are checked separately after merge. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, repository tools, test execution, and browser inspection. The exact model ID and context-window size were not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run relevant tests locally and they pass (broader local exceptions are recorded above) - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
beb73381ca
commit
56517dda6c
60 files changed
+1123
-325
No files matched your search
@@ -1,3 +1,5 @@
|
||||
import { connectionIntentsApi } from "@/api/connection-intents";
|
||||
import { readOAuthWindowOutcome } from "@/lib/oauthWindowOutcome";
|
||||
import { bindAccount } from "@/lib/account-scope";
|
||||
import { StepHeader } from "./ConnectionSetupHeader";
|
||||
import { GoogleWorkspaceServicesDialog } from "./GoogleWorkspaceServices";
|
||||
@@ -83,7 +85,6 @@ import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useCopyAction } from "@/lib/use-copy-action";
|
||||
import { resolveAuthorizationTarget } from "@/lib/authorizationUrl";
|
||||
import { navigateTopLevel } from "@/lib/browserNavigation";
|
||||
import { prepareOAuthNavigation, savePendingCloudHandoff } from "@/lib/oauthHandoff";
|
||||
import { redactUrlSecrets } from "@/lib/redact-url-secrets";
|
||||
import { askFirstCatalogEntryIdsFor } from "./connection-defaults";
|
||||
@@ -833,19 +834,16 @@ function StandardConnectionSetupFlow({
|
||||
const [unavailableReconnectId, setUnavailableReconnectId] = useState<string | null>(null);
|
||||
|
||||
const reserveOAuthPopup = useCallback(() => {
|
||||
if (host !== "dialog" || oauthPopupRef.current?.closed === false) return;
|
||||
oauthPopupRef.current = window.open(
|
||||
"about:blank",
|
||||
"paperclip-connection-oauth",
|
||||
"popup,width=720,height=760,resizable=yes,scrollbars=yes",
|
||||
);
|
||||
}, [host]);
|
||||
if (oauthPopupRef.current?.closed === false) return;
|
||||
try {
|
||||
oauthPopupRef.current = window.open("about:blank", "_blank", "popup,width=720,height=760,resizable=yes,scrollbars=yes");
|
||||
// Task-bound setup can resume in either host and needs its existing
|
||||
// origin-checked callback. Standalone flows verify saved state instead.
|
||||
if (oauthPopupRef.current && !connectionIntentId) oauthPopupRef.current.opener = null;
|
||||
} catch { oauthPopupRef.current = null; }
|
||||
}, [connectionIntentId]);
|
||||
|
||||
const openAuthorization = useCallback((url: string) => {
|
||||
if (host !== "dialog") {
|
||||
navigateTopLevel(url);
|
||||
return;
|
||||
}
|
||||
setAuthorizationFallbackUrl(url);
|
||||
const popup = oauthPopupRef.current;
|
||||
if (!popup || popup.closed) {
|
||||
@@ -868,7 +866,7 @@ function StandardConnectionSetupFlow({
|
||||
}, [onPhaseChange]);
|
||||
|
||||
useEffect(() => {
|
||||
if (host !== "dialog" || oauthPhase !== "redirecting") return;
|
||||
if (oauthPhase !== "redirecting") return;
|
||||
const timer = window.setInterval(() => {
|
||||
if (!oauthPopupRef.current?.closed) return;
|
||||
setOAuthPhase("error");
|
||||
@@ -888,7 +886,7 @@ function StandardConnectionSetupFlow({
|
||||
try {
|
||||
const target = await prepareOAuthNavigation(start, { signal: controller.signal });
|
||||
if (target.kind === "reauthentication") {
|
||||
const destination = host === "dialog" ? oauthPopupRef.current : window;
|
||||
const destination = oauthPopupRef.current;
|
||||
if (!destination || destination.closed || !start.handoff) {
|
||||
throw new Error("Paperclip couldn’t preserve this sign-in while refreshing your account.");
|
||||
}
|
||||
@@ -899,8 +897,11 @@ function StandardConnectionSetupFlow({
|
||||
setOAuthPhase("redirecting");
|
||||
}
|
||||
openAuthorization(target.url);
|
||||
if (target.kind === "reauthentication") setAuthorizationFallbackUrl(null);
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) return;
|
||||
oauthPopupRef.current?.close();
|
||||
oauthPopupRef.current = null;
|
||||
setOAuthPhase("error");
|
||||
setOAuthError(describeError(error).body);
|
||||
onPhaseChange?.("needs_retry");
|
||||
@@ -912,13 +913,27 @@ function StandardConnectionSetupFlow({
|
||||
useEffect(() => () => oauthHandoffAbortRef.current?.abort(), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (host !== "dialog" || !connectionIntentId) return;
|
||||
const receiveOAuthOutcome = (event: MessageEvent) => {
|
||||
if (!connectionIntentId) return;
|
||||
let disposed = false;
|
||||
const receiveOAuthOutcome = async (event: MessageEvent) => {
|
||||
const outcome = readConnectionIntentOAuthOutcome(event, window.location.origin, connectionIntentId);
|
||||
if (outcome === "connected") {
|
||||
setOAuthPhase("entry");
|
||||
setAuthorizationFallbackUrl(null);
|
||||
onComplete?.({ resolvedByCallback: true });
|
||||
if (onComplete) onComplete({ resolvedByCallback: true });
|
||||
else if (host === "page") {
|
||||
const account = bindAccount(queryClient);
|
||||
try {
|
||||
const verified = await connectionIntentsApi.setupOptions(connectionIntentId);
|
||||
if (disposed || !account.isCurrentScope()) return;
|
||||
if (verified.interaction.status !== "accepted") throw new Error("Authorization has not been confirmed yet. Try again.");
|
||||
navigate(`/issues/${verified.interaction.issueId}`);
|
||||
} catch (error) {
|
||||
if (disposed || !account.isCurrentScope()) return;
|
||||
setOAuthPhase("error");
|
||||
setOAuthError(describeError(error).body);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (outcome === "declined") {
|
||||
@@ -932,42 +947,43 @@ function StandardConnectionSetupFlow({
|
||||
setOAuthError("Authorization did not complete. Try again when you’re ready.");
|
||||
};
|
||||
window.addEventListener("message", receiveOAuthOutcome);
|
||||
return () => window.removeEventListener("message", receiveOAuthOutcome);
|
||||
}, [connectionIntentId, host, onComplete, onOAuthDeclined]);
|
||||
return () => { disposed = true; window.removeEventListener("message", receiveOAuthOutcome); };
|
||||
}, [connectionIntentId, host, onComplete, onOAuthDeclined, navigate, queryClient, selectedCompanyId]);
|
||||
|
||||
// Standalone dialog hosts have no task interaction to receive a callback.
|
||||
// Wait for this popup to return to our origin, then verify durable state via
|
||||
// the API. Provider-window contents never determine the saved connection.
|
||||
useEffect(() => {
|
||||
if (host !== "dialog" || connectionIntentId || !dialogOAuthConnectionId) return;
|
||||
if (connectionIntentId || !dialogOAuthConnectionId) return;
|
||||
let cancelled = false;
|
||||
let checking = false;
|
||||
const timer = window.setInterval(async () => {
|
||||
if (checking || cancelled) return;
|
||||
const popup = oauthPopupRef.current;
|
||||
if (!popup || popup.closed) {
|
||||
// Native fallback links have no Window handle; leave their saved flow available.
|
||||
if (!popup) return;
|
||||
if (popup.closed) {
|
||||
setDialogOAuthConnectionId(null);
|
||||
setOAuthPhase("error");
|
||||
setOAuthError("The sign-in window closed. Try again to finish connecting GitHub.");
|
||||
setOAuthError("The sign-in window closed. Try again to finish connecting.");
|
||||
return;
|
||||
}
|
||||
let returned: URL;
|
||||
try { returned = new URL(popup.location.href); } catch { return; }
|
||||
if (returned.origin !== window.location.origin || !returned.pathname.includes(dialogOAuthConnectionId)) return;
|
||||
if (returned.searchParams.has("oauth")) {
|
||||
const outcome = readOAuthWindowOutcome(popup, dialogOAuthConnectionId);
|
||||
if (outcome === "waiting") return;
|
||||
if (outcome !== "connected") {
|
||||
setDialogOAuthConnectionId(null);
|
||||
setOAuthPhase("error");
|
||||
setOAuthError("Authorization did not complete. Finish setup in the sign-in window or try again.");
|
||||
return;
|
||||
}
|
||||
if (returned.searchParams.get("success") !== "1") return;
|
||||
checking = true;
|
||||
try {
|
||||
const connection = await toolsApi.getConnection(dialogOAuthConnectionId);
|
||||
if (!cancelled && connection.status === "active") {
|
||||
setDialogOAuthConnectionId(null);
|
||||
popup.close();
|
||||
onComplete?.({ connectionId: connection.id });
|
||||
if (onComplete) onComplete({ connectionId: connection.id });
|
||||
else navigate(`/apps/${connection.id}/permissions`);
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
@@ -1161,18 +1177,14 @@ function StandardConnectionSetupFlow({
|
||||
setConnectorEnrollmentError(target.message);
|
||||
return;
|
||||
}
|
||||
if (host === "dialog") {
|
||||
setEnrollmentAuthorizationUrl(target.url);
|
||||
const popup = oauthPopupRef.current;
|
||||
if (popup && !popup.closed) {
|
||||
popup.location.assign(target.url);
|
||||
popup.focus();
|
||||
} else {
|
||||
setConnectorEnrollmentError("Open authorization in a new tab to continue.");
|
||||
}
|
||||
return;
|
||||
setEnrollmentAuthorizationUrl(target.url);
|
||||
const popup = oauthPopupRef.current;
|
||||
if (popup && !popup.closed) {
|
||||
popup.location.assign(target.url);
|
||||
popup.focus();
|
||||
} else {
|
||||
setConnectorEnrollmentError("Open authorization in a new tab to continue.");
|
||||
}
|
||||
navigateTopLevel(target.url);
|
||||
}, [host, closeEnrollmentPopup]);
|
||||
useEffect(() => {
|
||||
if (!enrollmentAuthorizationUrl || connectorEnrollmentQuery.data?.status !== "active") return;
|
||||
@@ -1387,6 +1399,8 @@ function StandardConnectionSetupFlow({
|
||||
},
|
||||
onSuccess: (start) => void prepareAndOpenOAuth(start),
|
||||
onError: (error) => {
|
||||
oauthPopupRef.current?.close();
|
||||
oauthPopupRef.current = null;
|
||||
const details = error instanceof ApiError && error.body && typeof error.body === "object"
|
||||
? (error.body as { details?: { code?: unknown } }).details
|
||||
: null;
|
||||
@@ -1407,14 +1421,14 @@ function StandardConnectionSetupFlow({
|
||||
setWorkspaceConsent(() => () => {
|
||||
onPhaseChange?.("authorizing");
|
||||
reserveOAuthPopup();
|
||||
if (host === "dialog" && !connectionIntentId) setDialogOAuthConnectionId(connection.id);
|
||||
if (!connectionIntentId) setDialogOAuthConnectionId(connection.id);
|
||||
mutateOAuthStart(connection);
|
||||
});
|
||||
return;
|
||||
}
|
||||
onPhaseChange?.("authorizing");
|
||||
reserveOAuthPopup();
|
||||
if (host === "dialog" && !connectionIntentId) setDialogOAuthConnectionId(connection.id);
|
||||
if (!connectionIntentId) setDialogOAuthConnectionId(connection.id);
|
||||
mutateOAuthStart(connection);
|
||||
}, [mutateOAuthStart, onPhaseChange, reserveOAuthPopup, host, connectionIntentId]);
|
||||
|
||||
@@ -1537,32 +1551,25 @@ function StandardConnectionSetupFlow({
|
||||
// operator registers themselves. Keep the draft and ask for it in place
|
||||
// rather than sending them back to the start.
|
||||
if (result.auth.manualClientRequired) {
|
||||
oauthPopupRef.current?.close();
|
||||
oauthPopupRef.current = null;
|
||||
setLinkGuidance(genericConnectGuidance("oauth_manual_client_required", null));
|
||||
setLinkAuthMode("oauth");
|
||||
setLinkAdvancedOpen(true);
|
||||
setGenericOAuthPending(false);
|
||||
return;
|
||||
}
|
||||
if (host === "dialog" || connectionIntentId) {
|
||||
setOAuthPhase("starting");
|
||||
setGenericOAuthPending(!entry);
|
||||
startOAuth(result.connection);
|
||||
return;
|
||||
}
|
||||
setOAuthPhase("starting");
|
||||
setGenericOAuthPending(!entry);
|
||||
const startUrl = result.auth.startUrl?.trim();
|
||||
if (!startUrl) {
|
||||
setOAuthPhase("starting");
|
||||
setGenericOAuthPending(true);
|
||||
startOAuth(result.connection);
|
||||
return;
|
||||
}
|
||||
setGenericOAuthPending(true);
|
||||
void prepareAndOpenOAuth({
|
||||
authorizationUrl: startUrl,
|
||||
handoff: result.auth.handoff,
|
||||
});
|
||||
if (startUrl && !connectionIntentId) {
|
||||
setDialogOAuthConnectionId(result.connectionId);
|
||||
void prepareAndOpenOAuth({ authorizationUrl: startUrl, handoff: result.auth.handoff });
|
||||
} else startOAuth(result.connection);
|
||||
return;
|
||||
}
|
||||
oauthPopupRef.current?.close();
|
||||
oauthPopupRef.current = null;
|
||||
setLinkGuidance(null);
|
||||
setConnectResult(result);
|
||||
const defaults: Record<string, boolean> = {};
|
||||
@@ -1572,6 +1579,8 @@ function StandardConnectionSetupFlow({
|
||||
finishMutation.mutate({ result, enabled: defaults });
|
||||
},
|
||||
onError: (error) => {
|
||||
oauthPopupRef.current?.close();
|
||||
oauthPopupRef.current = null;
|
||||
const details = error instanceof ApiError && error.body && typeof error.body === "object"
|
||||
? (error.body as { details?: { code?: unknown } }).details
|
||||
: null;
|
||||
@@ -1623,11 +1632,11 @@ function StandardConnectionSetupFlow({
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (method?.auth === "oauth") {
|
||||
if (method?.auth === "oauth" || (!connectEntry && !zapierSource && (linkAuthMode === "auto" || linkAuthMode === "oauth"))) {
|
||||
reserveOAuthPopup();
|
||||
}
|
||||
mutateConnect(entryOverride);
|
||||
}, [connectionMethodKey, entry, identityConnection, mutateConnect, reserveOAuthPopup]);
|
||||
}, [connectionMethodKey, entry, identityConnection, linkAuthMode, zapierSource, mutateConnect, reserveOAuthPopup]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!requestedAppKey || galleryQuery.isLoading || !galleryQuery.data) return;
|
||||
@@ -2791,7 +2800,7 @@ function StandardConnectionSetupFlow({
|
||||
onBack={backToGallery}
|
||||
onConnect={() => {
|
||||
setLinkGuidance(null);
|
||||
connectMutation.mutate(undefined);
|
||||
connectApp();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -2803,7 +2812,7 @@ function StandardConnectionSetupFlow({
|
||||
submitting={connectMutation.isPending}
|
||||
defaults={connectionDefaults}
|
||||
onBack={backToGallery}
|
||||
onConnect={() => connectMutation.mutate(undefined)}
|
||||
onConnect={() => connectApp()}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { bindAccount } from "@/lib/account-scope";
|
||||
import { connectionIntentsApi } from "@/api/connection-intents";
|
||||
import { ConnectionInstructionsEditor } from "../ConnectionInstructions";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
@@ -14,7 +16,7 @@ import { useCompany } from "@/context/CompanyContext";
|
||||
import { findAggregatorApp } from "@paperclipai/shared/aggregator-app-catalog";
|
||||
import { useNavigate, useSearchParams } from "@/lib/router";
|
||||
import { resolveAuthorizationTarget } from "@/lib/authorizationUrl";
|
||||
import { navigateTopLevel } from "@/lib/browserNavigation";
|
||||
import { readOAuthWindowOutcome } from "@/lib/oauthWindowOutcome";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { RemoteMcpConnectionSetup } from "./RemoteMcpConnectionSetup";
|
||||
import { remoteMcpProviders, type RemoteMcpProviderId } from "./providers";
|
||||
@@ -90,21 +92,34 @@ export function RemoteMcpProductionSetup({ providerId, connection, host = "page"
|
||||
try { sessionStorage.setItem(accessDraftKey, JSON.stringify({ grantKind: state.grantKind, allAgents: state.allAgents, agentIds: state.agentIds })); } catch { /* Storage can be disabled. */ }
|
||||
}, [connection, accessDraftKey, state.grantKind, state.allAgents, state.agentIds]);
|
||||
useEffect(() => {
|
||||
if (host !== "dialog" || !interactionId) return;
|
||||
const receive = (event: MessageEvent) => {
|
||||
if (!interactionId) return;
|
||||
let disposed = false;
|
||||
const receive = async (event: MessageEvent) => {
|
||||
const outcome = readConnectionIntentOAuthOutcome(event, window.location.origin, interactionId);
|
||||
if (!outcome) return;
|
||||
if (outcome === "connected") {
|
||||
// The host verifies durable acceptance; a postMessage is never proof.
|
||||
onComplete?.({ resolvedByCallback: true });
|
||||
if (onComplete) onComplete({ resolvedByCallback: true });
|
||||
else if (host === "page") {
|
||||
const account = bindAccount(queries);
|
||||
try {
|
||||
const verified = await connectionIntentsApi.setupOptions(interactionId);
|
||||
if (disposed || !account.isCurrentScope()) return;
|
||||
if (verified.interaction.status !== "accepted") throw new Error("Authorization has not been confirmed yet. Try again.");
|
||||
navigate(`/issues/${verified.interaction.issueId}`);
|
||||
} catch {
|
||||
if (disposed || !account.isCurrentScope()) return;
|
||||
setState((s) => ({ ...s, connectStatus: "oauth_failed" }));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
setState((s) => ({ ...s, connectStatus: outcome === "declined" ? "cancelled" : "oauth_failed" }));
|
||||
onPhaseChange?.("needs_retry");
|
||||
}
|
||||
};
|
||||
window.addEventListener("message", receive);
|
||||
return () => window.removeEventListener("message", receive);
|
||||
}, [host, interactionId, onComplete, onPhaseChange]);
|
||||
return () => { disposed = true; window.removeEventListener("message", receive); };
|
||||
}, [host, interactionId, onComplete, onPhaseChange, navigate, queries, selectedCompanyId]);
|
||||
const edit = (patch: Partial<RemoteMcpSetupState>) => setState((s) => ({ ...s, ...patch }));
|
||||
const finish = async (id: string) => {
|
||||
try { sessionStorage.removeItem(accessDraftKey); } catch { /* Storage can be disabled. */ }
|
||||
@@ -128,6 +143,40 @@ export function RemoteMcpProductionSetup({ providerId, connection, host = "page"
|
||||
} else if (isAppAggregator(providerId)) navigate("/apps");
|
||||
else navigate(`/apps/${id}/permissions`);
|
||||
};
|
||||
useEffect(() => {
|
||||
if (state.connectStatus !== "sign_in" || !savedConnection.current) return;
|
||||
const id = savedConnection.current.id;
|
||||
let cancelled = false;
|
||||
let checking = false;
|
||||
const check = async () => {
|
||||
if (checking || cancelled) return;
|
||||
// Reconnect can begin with an already-active row. Wait for this attempt’s callback.
|
||||
const outcome = readOAuthWindowOutcome(popup.current, id);
|
||||
if (outcome === "waiting") return;
|
||||
if (outcome !== "connected") {
|
||||
popup.current?.close();
|
||||
popup.current = null;
|
||||
setState((s) => ({ ...s, connectStatus: outcome === "failed" ? "oauth_failed" : "cancelled" }));
|
||||
onPhaseChange?.("needs_retry");
|
||||
return;
|
||||
}
|
||||
if (interactionId) return; // The intent callback and host own durable acceptance.
|
||||
checking = true;
|
||||
try {
|
||||
const saved = await toolsApi.getConnection(id);
|
||||
if (!cancelled && saved.status === "active") {
|
||||
cancelled = true;
|
||||
popup.current?.close();
|
||||
popup.current = null;
|
||||
await finish(id);
|
||||
}
|
||||
} catch { /* Keep the saved sign-in and allow a later focus or poll to retry. */ }
|
||||
finally { checking = false; }
|
||||
};
|
||||
const timer = window.setInterval(() => void check(), 2000);
|
||||
window.addEventListener("focus", check);
|
||||
return () => { cancelled = true; window.clearInterval(timer); window.removeEventListener("focus", check); };
|
||||
}, [state.connectStatus, interactionId]);
|
||||
const submit = async (saveDraft = false) => {
|
||||
if (busy.current || !selectedCompanyId || !instructionsValid || (connection && !installs.data)) return;
|
||||
try {
|
||||
@@ -136,9 +185,11 @@ export function RemoteMcpProductionSetup({ providerId, connection, host = "page"
|
||||
} catch { edit({ connectStatus: "invalid_url" }); return; }
|
||||
// Reserve the window while handling the click so popup blockers do not
|
||||
// discard the later OAuth response. URL/token-only providers never need it.
|
||||
if (!saveDraft && host === "dialog" && state.auth === "auto" && (!popup.current || popup.current.closed)) {
|
||||
if (!saveDraft && state.auth === "auto" && (!popup.current || popup.current.closed)) {
|
||||
try {
|
||||
popup.current = window.open("about:blank", "paperclip-connection-oauth", "popup,width=720,height=760,resizable=yes,scrollbars=yes");
|
||||
popup.current = window.open("about:blank", "_blank", "popup,width=720,height=760,resizable=yes,scrollbars=yes");
|
||||
// Task-bound callbacks must work in both page and dialog hosts.
|
||||
if (popup.current && !interactionId) popup.current.opener = null;
|
||||
} catch { popup.current = null; }
|
||||
}
|
||||
busy.current = true;
|
||||
@@ -190,11 +241,9 @@ export function RemoteMcpProductionSetup({ providerId, connection, host = "page"
|
||||
authorizationUrl.current = target.url;
|
||||
edit({ connectStatus: "sign_in", token: "", headers: [] });
|
||||
try {
|
||||
if (host === "dialog") {
|
||||
if (!popup.current || popup.current.closed) throw new Error("Sign-in window unavailable");
|
||||
popup.current.location.assign(target.url);
|
||||
popup.current.focus();
|
||||
} else navigateTopLevel(target.url);
|
||||
if (!popup.current || popup.current.closed) throw new Error("Sign-in window unavailable");
|
||||
popup.current.location.assign(target.url);
|
||||
popup.current.focus();
|
||||
} catch {
|
||||
// The connection and OAuth session already exist. Preserve them and
|
||||
// let the native sign-in link recover a blocked browser handoff.
|
||||
|
||||
Reference in new issue
Block a user