feat(connections): connect services from native task feeds (#13058)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use connections to reach external services.
> - A fresh native task can have no service tools installed.
> - The agent needs a way to discover services and ask the responsible
person for access.
> - This pull request brings the existing connection-intent flow into
native task execution.
> - The person can connect from the task, and the agent can continue
with updated tools.

## Linked Issues or Issue Description

**Subsystem affected**

Native runner tool authority, connection intents, task interactions, and
shared connection setup.

**Problem or motivation**

A task that needs an unconnected service cannot finish its work. Leaving
the task to configure access also loses context. A resolved request must
survive a restart and resume the correct agent once.

**Proposed solution**

Expose connection discovery and access requests as server-owned native
tools. Render a durable task card and use the shared setup dialog.
Persist outcome delivery and start a fresh provider session after access
is ready.

**Alternatives considered**

Sending the person to the Connections page adds navigation and does not
solve continuation. Polling for authorization consumes runs and can
create duplicate requests.

**Roadmap alignment**

This extends the existing connection-intent runtime and setup
experience. It reuses the shared access model and the native runner.

Related: #12345, #12347. The service-slug fix in #12906 is related but
separate. Companion evaluation PR:
https://github.com/paperclipai/paperclip-evals/pull/21.

## What Changed

- Expose `connections_search` and `connection_request` with server-bound
company, task, agent, and responsible user. Preserve the legacy entry
points.
- Discover catalog services and authorized custom connections. Check
installation, identity, health, and executable permissions before
reporting ready.
- Keep pending cards through ordinary messages. Reuse requests and
retire stale ownership. Put Connect at the right of Not now.
- Reuse the shared setup flow in a task dialog. Keep access additive and
default to the requesting agent. Recover from cancelled or blocked OAuth
windows with a new-tab fallback.
- Persist outcome delivery with an idempotent wake key. Resume in a
fresh session and recheck ownership before dispatch.
- Add native browser fixtures, offline Storybook states, server
contracts, and evaluation fixtures. Update guidance and documentation.

## Verification

- `pnpm build`: passed after replaying the change on current master.
- `pnpm -r typecheck`: passed.
- `pnpm check:token-gates`: passed.
- `pnpm --filter @paperclipai/ui build-storybook`: passed.
- New continuation-policy regression cases: 16 passed.
- Docker-backed PostgreSQL regressions passed for requester-only OAuth
access, assignment-only expiry, terminal expiry, and credential-free
setup metadata.
- Shared setup and task-card UI tests: 121 passed, including configured
MCP reconnect URL recovery and preserving user edits across refetch.
- Storybook browser checks: all 119 passed on the latest reconnect fix.
- `pnpm test:run`: 4,734 tests passed in the first server group, but
embedded PostgreSQL startup failures and resulting cleanup errors
prevented a complete local pass. All Linux CI lanes passed on the latest
reviewed commit. One external-object route test returned an unexplained
500 on the first run; it passed twice locally and the failed shard
passed on retry without code changes.
- Earlier feature-checkout evidence: three deterministic native browser
journeys passed, including restart delivery and an actual fixture tool
result. Legacy scripted coverage also passed. All 59 added stories were
inspected in light and dark themes.
- Live Notion testing recorded successful provider reads. The manual
test used a local-trusted instance. It does not prove
authenticated/cloud deployment or every provider journey.
- Native browser rerun reached the embedded PostgreSQL startup limit
before bootstrap, so the latest checkout’s full native browser journey
remains unverified. Both OAuth page/task regression cases passed against
isolated Docker-backed PostgreSQL 17. They verify no premature task
access, requester-only completion, additive retries, and reconnect
preservation.
- Applied both new migrations twice to isolated PostgreSQL 17. Foreign
keys remained intact, duplicate active delivery keys were rejected, and
failed delivery records did not block retries.

Reviewer path: start a fresh test drive, enable the native runner, use
an agent that can perform work directly, and ask it to summarize a
Notion page. Connect from the card, then verify the resumed provider
call and source-linked answer. The default test-drive CEO is instructed
to delegate, so it can introduce an unrelated hiring step.

## Risks

- Two additive migrations create durable deliveries and a partial unique
wake index. They are idempotent. The wake index can require a
maintenance window on large tables because migrations run in a
transaction.
- OAuth and continuation cross asynchronous boundaries. Tests cover
ownership changes, retries, additive access, and restart delivery; live
provider behavior still varies.
- The latest requester-scope fix has not yet been exercised through live
OAuth. GitHub, API-key, authenticated-user, and all recovery journeys
are not claimed as verified.

## Model Used

OpenAI GPT-6-based Codex assisted with implementation, tests, and review
using tools and code execution. The runtime does not expose the exact
model version, context window, or reasoning setting. Live evaluation
used `gpt-5.6-luna`; manual native testing used `gpt-5.6-sol`.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used and disclosed unavailable runtime
details
- [x] I have checked ROADMAP.md and confirmed this extends existing
connection work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have described the issue in-PR following the feature issue
template
- [x] I have not referenced internal or instance-local Paperclip issues
or links
- [x] My branch name describes the change and contains no internal
ticket id
- [ ] I have run all required tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation
- [x] I have considered and documented risks
- [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:
DottaandPaperclip authored and GitHub committed 2026-09-08 15:55:26 -05:00
1 parent 5128b4f323
commit e095b84dab
67 files changed
+88330 -327

No files matched your search

@@ -132,10 +132,10 @@ describe("IssueThreadInteractionCard", () => {
});
expect(host.querySelector('[data-testid="connection-intent-actions"]')).toBeTruthy();
expect(host.textContent).toContain("Connect / Use existing");
expect(host.textContent).toContain("Connect");
expect(host.textContent).toContain("Not now");
const loadButton = Array.from(host.querySelectorAll("button")).find((button) =>
button.textContent?.includes("Connect / Use existing"),
button.textContent?.trim() === "Connect",
);
await act(async () => {
loadButton?.click();
@@ -159,7 +159,7 @@ describe("IssueThreadInteractionCard", () => {
});
expect(host.querySelector('[data-testid="connection-intent-waiting"]')).toBeTruthy();
expect(host.textContent).not.toContain("Connect / Use existing");
expect(Array.from(host.querySelectorAll("button")).map((button) => button.textContent?.trim())).not.toContain("Connect");
expect(host.textContent).not.toContain("Not now");
});
@@ -1438,7 +1438,7 @@ describe("IssueThreadInteractionCard connection-intent card", () => {
});
expect(host.querySelector('[data-testid="connection-intent-actions"]')).not.toBeNull();
const labels = Array.from(host.querySelectorAll("button")).map((button) => button.textContent?.trim());
expect(labels).toContain("Connect / Use existing");
expect(labels).toContain("Connect");
expect(labels).toContain("Not now");
expect(host.textContent).toContain("Access is added only for this agent");
});
+10
View File
@@ -1091,6 +1091,16 @@ describe("TaskChatThread runtime transcript selection", () => {
},
);
it("does not show a completed-response notice for a redundant cancelled continuation", () => {
render(<TaskChatThread comments={[]} onAdd={async () => {}} linkedRuns={[{
runId: "connection-continuation-skipped", status: "cancelled", errorCode: "issue_not_in_progress", startedAt: null,
agentId: "agent-1", agentName: "Runner", adapterType: "paperclip_runner",
createdAt: "2026-09-07T18:00:00.000Z", finishedAt: "2026-09-07T18:00:01.000Z",
}]} />);
expect(container.textContent).not.toContain("The runner returned no user-facing response.");
expect(container.textContent).not.toContain("Run completed");
});
it("does not treat a progress comment as the final response of a failed native run", () => {
nativeTranscriptState.transcriptByRun.set("native-progress-failed", [
{
+8
View File
@@ -1402,6 +1402,13 @@ export function TaskChatThread(props: TaskChatThreadProps) {
});
}
if (entries.length === 0) {
// A queued continuation cancelled after the task was completed or parked
// never produced a provider turn. Keep its record in the run log without
// presenting it as a completed chat response.
if (source.status === "cancelled" && meta?.errorCode === "issue_not_in_progress") {
settledRunIds.add(source.id);
continue;
}
if (sourceIsPaperclipRunner && sourceYielded) {
settledRunIds.add(source.id);
continue;
@@ -2081,6 +2088,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
.filter(
(interaction) =>
interaction.status === "pending" &&
interaction.kind !== "connection_intent" &&
!shouldHideInteractionCard(interaction),
)
.sort((left, right) => toMs(right.createdAt) - toMs(left.createdAt));
@@ -43,7 +43,7 @@ export function TaskChatInteractionCard({
interaction.result?.expirationReason === "superseded_by_newer_interaction";
if (shouldHideInteractionCard(interaction) && !isSupersededQuestionReceipt)
return null;
if (presentation === "timeline" && interaction.status === "pending") {
if (presentation === "timeline" && interaction.status === "pending" && interaction.kind !== "connection_intent") {
const isPlanReview =
interaction.kind === "request_confirmation" &&
Boolean(interaction.sourceRunId) &&
@@ -144,7 +144,7 @@ function renderBody(
function button(label: string) {
return Array.from(document.body.querySelectorAll("button")).find(
(candidate) => candidate.textContent?.trim() === label,
(candidate) => candidate.textContent?.trim() === label || (label === "Connect / Use existing" && candidate.textContent?.trim() === "Connect"),
) as HTMLButtonElement | undefined;
}
@@ -175,7 +175,7 @@ afterEach(async () => {
describe("ConnectionIntentInteractionBody states and audience", () => {
it.each([
[pendingConnectionIntentInteraction, "Connect / Use existing"],
[pendingConnectionIntentInteraction, "Connect"],
[
{
...pendingConnectionIntentInteraction,
@@ -184,7 +184,7 @@ describe("ConnectionIntentInteractionBody states and audience", () => {
phase: "authorizing",
},
},
"Authorizing…",
"Continue setup",
],
[retryConnectionIntentInteraction, "Try again"],
[connectedConnectionIntentInteraction, "Notion connected"],
@@ -1,4 +1,4 @@
import { useCallback, useRef, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
CheckCircle2,
@@ -88,10 +88,19 @@ export function ConnectionIntentInteractionBody({
const setupQuery = useQuery({
queryKey: ["connection-intent", interaction.id, "setup-options"],
queryFn: () => connectionIntentsApi.setupOptions(interaction.id),
enabled: open && isAddressee && isPending,
refetchInterval: open && isPending ? 2_000 : false,
enabled: isAddressee && isPending,
refetchInterval: isPending && (open || interaction.payload.phase === "authorizing") ? 2_000 : false,
});
useEffect(() => {
const current = setupQuery.data?.interaction;
if (current && current.status !== "pending" && isPending) {
void invalidateTask(current);
setOpen(false);
returnFocusToCard();
}
}, [setupQuery.data?.interaction, isPending]);
const completeMutation = useMutation({
mutationFn: (connectionId: string) =>
connectionIntentsApi.complete(interaction.id, connectionId),
@@ -123,7 +132,10 @@ export function ConnectionIntentInteractionBody({
const finishNewConnection = async (completion: ConnectionSetupCompletion) => {
if (completion.resolvedByCallback) {
await invalidateTask();
// A browser message cannot establish authorization. Read the durable result.
const verified = await setupQuery.refetch();
if (verified.data?.interaction.status !== "accepted") return;
await invalidateTask(verified.data.interaction);
setOpen(false);
returnFocusToCard();
return;
@@ -154,7 +166,7 @@ export function ConnectionIntentInteractionBody({
: "Connection request expired",
body:
resultOutcome === "superseded"
? "A newer run requested this connection. Use the latest card instead."
? "This request was replaced. Use the latest connection card instead."
: "This request is no longer active.",
}
: null;
@@ -247,20 +259,28 @@ export function ConnectionIntentInteractionBody({
</p>
) : null}
<div className="mt-4 flex flex-wrap gap-2">
<div className="mt-4 flex flex-wrap justify-end gap-2">
<Button
type="button"
variant="ghost"
disabled={declineMutation.isPending || authorizing}
onClick={() => declineMutation.mutate()}
>
Not now
</Button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button type="button" disabled={authorizing}>
<Button type="button">
{authorizing ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Plug className="h-4 w-4" />
)}
{authorizing
? "Authorizing…"
? "Continue setup"
: needsRetry
? "Try again"
: "Connect / Use existing"}
: setupQuery.data?.existingConnections.length ? "Connect / Use existing" : "Connect"}
</Button>
</DialogTrigger>
<DialogContent
@@ -304,7 +324,8 @@ export function ConnectionIntentInteractionBody({
) : setupQuery.data ? (
<ConnectionSetupFlow
host="dialog"
serviceSlug={interaction.payload.serviceSlug}
serviceSlug={interaction.payload.serviceSlug.startsWith("connection:") ? undefined : interaction.payload.serviceSlug}
configuredConnection={interaction.payload.serviceSlug.startsWith("connection:") ? setupQuery.data.existingConnections[0] : undefined}
requestedAgentId={setupQuery.data.requestedAgentId}
interactionId={interaction.id}
existingConnections={setupQuery.data.existingConnections}
@@ -321,14 +342,6 @@ export function ConnectionIntentInteractionBody({
) : null}
</DialogContent>
</Dialog>
<Button
type="button"
variant="ghost"
disabled={declineMutation.isPending || authorizing}
onClick={() => declineMutation.mutate()}
>
Not now
</Button>
</div>
{completeMutation.isError ||
@@ -20,6 +20,7 @@ import type {
Agent,
AppDefinition,
ConnectionGrantKind,
ConnectionIntentSetupConnection,
ConnectionMethodDef,
ConnectToolAppResult,
FieldDef,
@@ -315,7 +316,8 @@ const ZAPIER_STEP_LABELS = ["Access", "Add MCP URL"];
* it. Personal-only methods still stay personal, and reconnects preserve their
* original identity through the explicit reconnect hint.
*/
function defaultGrantKindFor(method: ConnectionMethodDef | null): ConnectionGrantKind {
function defaultGrantKindFor(method: ConnectionMethodDef | null, preferPersonal = false): ConnectionGrantKind {
if (preferPersonal && method?.auth !== "none" && (!method?.grantKinds || method.grantKinds.includes("user"))) return "user";
if (method?.grantKinds?.length === 1) return method.grantKinds[0]!;
if (method?.grantKinds && !method.grantKinds.includes("organization")) return method.grantKinds[0]!;
return "organization";
@@ -476,7 +478,8 @@ export interface ConnectionSetupFlowProps {
requestedAgentId?: string;
interactionId?: string;
forceNewConnection?: boolean;
existingConnections?: ToolConnection[];
existingConnections?: ConnectionIntentSetupConnection[];
configuredConnection?: ConnectionIntentSetupConnection;
onUseExisting?: (connectionId: string) => Promise<void>;
onComplete?: (result: ConnectionSetupCompletion) => void;
onOAuthDeclined?: () => void;
@@ -499,6 +502,7 @@ export function ConnectionSetupFlow({
interactionId,
forceNewConnection = false,
existingConnections = [],
configuredConnection,
onUseExisting,
onComplete,
onOAuthDeclined,
@@ -528,7 +532,7 @@ export function ConnectionSetupFlow({
const oauthCallbackCode = searchParams.get("code");
const githubInstallationUrl = githubRecoveryUrl(searchParams.get("installation_url"));
const githubManagementUrl = githubRecoveryUrl(searchParams.get("management_url"));
const reconnectConnectionId = searchParams.get("reconnect")?.trim() || null;
const reconnectConnectionId = configuredConnection?.id ?? (searchParams.get("reconnect")?.trim() || null);
const reconnectGrantKindHint: ConnectionGrantKind | null = searchParams.get("identity") === "user"
? "user"
: searchParams.get("identity") === "organization"
@@ -546,7 +550,7 @@ export function ConnectionSetupFlow({
const routeAppKey = resolveAppsConnectRouteKey({ serviceSlug, appKey, sourceSlug });
const zapierSource = (serviceSlug ?? sourceSlug ?? appKey) === "zapier";
const requestedAppKey = zapierSource ? undefined : routeAppKey;
const byo = host === "page" && (byoOnly || searchParams.get("byo") === "1");
const byo = Boolean(configuredConnection) || (host === "page" && (byoOnly || searchParams.get("byo") === "1"));
const [restoredEnrollmentAccess] = useState<EnrollmentAccessState | null>(() =>
host === "page"
&& searchParams.get("cloud_connector") === "enrolled"
@@ -561,8 +565,8 @@ export function ConnectionSetupFlow({
const rawLink = searchParams.get("link")?.trim() ?? "";
return {
link: /^https?:\/\//i.test(rawLink) ? rawLink : "",
name: searchParams.get("name")?.trim() ?? "",
applicationId: searchParams.get("applicationId")?.trim() || undefined,
name: configuredConnection?.name ?? searchParams.get("name")?.trim() ?? "",
applicationId: configuredConnection?.applicationId ?? (searchParams.get("applicationId")?.trim() || undefined),
};
});
@@ -609,7 +613,7 @@ export function ConnectionSetupFlow({
* backwards through the wizard.
*/
const [grantKind, setGrantKind] = useState<ConnectionGrantKind>(
restoredEnrollmentAccess?.grantKind ?? reconnectGrantKindHint ?? "organization",
restoredEnrollmentAccess?.grantKind ?? reconnectGrantKindHint ?? (requestedAgentId ? "user" : "organization"),
);
const [installChoice, setInstallChoice] = useState<"specific" | "all">(
restoredEnrollmentAccess?.installChoice ?? (requestedAgentId ? "specific" : "all"),
@@ -633,6 +637,7 @@ export function ConnectionSetupFlow({
const [hydratedResumeConnectionId, setHydratedResumeConnectionId] = useState<string | null>(null);
const oauthPopupRef = useRef<Window | null>(null);
const [dialogOAuthConnectionId, setDialogOAuthConnectionId] = useState<string | null>(null);
const [authorizationFallbackUrl, setAuthorizationFallbackUrl] = useState<string | null>(null);
const oauthHandoffAbortRef = useRef<AbortController | null>(null);
const [showConnectionChoice, setShowConnectionChoice] = useState(
existingConnections.length > 0 && Boolean(onUseExisting),
@@ -655,10 +660,11 @@ export function ConnectionSetupFlow({
navigateTopLevel(url);
return;
}
setAuthorizationFallbackUrl(url);
const popup = oauthPopupRef.current;
if (!popup || popup.closed) {
setOAuthPhase("error");
setOAuthError("Paperclip couldn’t open the sign-in window. Allow popups for this site and try again.");
setOAuthError("Paperclip couldn’t open the sign-in window. Open sign-in in a new tab to continue.");
onPhaseChange?.("needs_retry");
return;
}
@@ -666,6 +672,27 @@ export function ConnectionSetupFlow({
popup.focus();
}, [host, onPhaseChange]);
const openAuthorizationTab = useCallback(() => {
// Let a real link own navigation. Some embedded browsers return a window
// proxy from window.open without opening a usable authorization tab.
oauthPopupRef.current = null;
setOAuthError(null);
setOAuthPhase("redirecting");
onPhaseChange?.("authorizing");
}, [onPhaseChange]);
useEffect(() => {
if (host !== "dialog" || oauthPhase !== "redirecting") return;
const timer = window.setInterval(() => {
if (!oauthPopupRef.current?.closed) return;
setOAuthPhase("error");
setOAuthError("The sign-in window closed. If authorization did not finish, try again.");
setAuthorizationFallbackUrl(null);
onPhaseChange?.("needs_retry");
}, 1_000);
return () => window.clearInterval(timer);
}, [host, oauthPhase, onPhaseChange]);
const prepareAndOpenOAuth = useCallback(async (
start: Pick<ToolOAuthStartResult, "authorizationUrl" | "handoff">,
) => {
@@ -703,11 +730,15 @@ export function ConnectionSetupFlow({
const receiveOAuthOutcome = (event: MessageEvent) => {
const outcome = readConnectionIntentOAuthOutcome(event, window.location.origin, connectionIntentId);
if (outcome === "connected") {
setOAuthPhase("entry");
setAuthorizationFallbackUrl(null);
onComplete?.({ resolvedByCallback: true });
return;
}
if (outcome === "declined") {
onOAuthDeclined?.();
setOAuthPhase("error");
setOAuthError("Authorization was cancelled. You can try again.");
onPhaseChange?.("needs_retry");
return;
}
if (outcome !== "failed") return;
@@ -817,7 +848,7 @@ export function ConnectionSetupFlow({
setConnectResult(null);
setInstallAgentIds(new Set(requestedAgentId ? [requestedAgentId] : []));
setInstallChoice(requestedAgentId ? "specific" : "all");
setGrantKind(reconnectGrantKind ?? defaultGrantKindFor(initialMethod));
setGrantKind(reconnectGrantKind ?? defaultGrantKindFor(initialMethod, Boolean(requestedAgentId)));
setStep("access");
navigate(
credentialSource === "vercel_connect"
@@ -957,6 +988,20 @@ export function ConnectionSetupFlow({
: null,
[connectionsQuery.data, reconnectConnectionId],
);
const seededReconnectEndpoint = useRef<string | null>(null);
useEffect(() => {
// Task choices contain selection metadata only. Load the endpoint through
// the existing authorized connection query, once, without overwriting edits.
if (!configuredConnection || !connectionsQuery.isFetchedAfterMount || !reconnectConnection
|| seededReconnectEndpoint.current === reconnectConnection.id) return;
const endpoint = reconnectConnection.config?.url
?? reconnectConnection.transportConfig?.url
?? reconnectConnection.transportConfig?.serverUrl
?? reconnectConnection.config?.serverUrl;
if (typeof endpoint !== "string" || !/^https?:\/\//i.test(endpoint)) return;
seededReconnectEndpoint.current = reconnectConnection.id;
setLinkUrl((current) => current || endpoint);
}, [configuredConnection, connectionsQuery.isFetchedAfterMount, reconnectConnection]);
const reconnectApplication = useMemo(
() => reconnectConnection
? (applicationsQuery.data?.applications ?? []).find(
@@ -1073,11 +1118,14 @@ export function ConnectionSetupFlow({
* apply the same selection.
*/
const applyAccessInstalls = async (connectionId: string) => {
// The task completion endpoint adds the requester atomically with resolution.
if (requestedAgentId) return;
const dedicatedIdentity = (fixedGrantKind ?? grantKind) === "agent";
const installState = !dedicatedIdentity && installChoice === "all"
? { onAll: true, agentIds: new Set<string>() }
: { onAll: false, agentIds: installAgentIds };
await toolsApi.putConnectionInstalls(connectionId, installPayload(selectedCompanyId!, installState));
const desired = installPayload(selectedCompanyId!, installState);
await toolsApi.putConnectionInstalls(connectionId, desired);
};
const effectiveGrantKind = fixedGrantKind ?? grantKind;
@@ -1119,7 +1167,7 @@ export function ConnectionSetupFlow({
? configValues
: undefined,
applicationId: prefill.applicationId,
...(resumeConnectionId ? { resumeConnectionId } : {}),
...(resumeConnectionId ? { resumeConnectionId } : reconnectConnectionId ? { reconnectConnectionId } : {}),
...(requestedGrantKind !== "organization" ? { grantKind: requestedGrantKind } : {}),
...(requestedGrantKind === "agent" ? { subjectAgentId: [...installAgentIds][0] } : {}),
});
@@ -1140,6 +1188,7 @@ export function ConnectionSetupFlow({
);
result = await toolsApi.connectApp(selectedCompanyId!, {
...genericPayload,
...(reconnectConnectionId ? { reconnectConnectionId } : {}),
// Zapier issues a credential-bearing URL, so its branded setup keeps
// the compact pasted-URL step. It is still a curated app, though: the
// gallery identity must reach the server or Browse can only see a
@@ -1349,7 +1398,7 @@ export function ConnectionSetupFlow({
const matchingEnrollmentAccess = restoredEnrollmentAccess?.companyId === selectedCompanyId
? restoredEnrollmentAccess
: null;
setGrantKind(reconnectGrantKind ?? matchingEnrollmentAccess?.grantKind ?? defaultGrantKindFor(initialMethod));
setGrantKind(reconnectGrantKind ?? matchingEnrollmentAccess?.grantKind ?? defaultGrantKindFor(initialMethod, Boolean(requestedAgentId)));
setInstallAgentIds(new Set(
matchingEnrollmentAccess?.agentIds ?? (requestedAgentId ? [requestedAgentId] : []),
));
@@ -1521,6 +1570,7 @@ export function ConnectionSetupFlow({
enabledCatalogEntryIds: enabledIds,
askFirstCatalogEntryIds: askFirstIds,
access: selection,
...(requestedAgentId ? { preserveExistingAccess: true } : {}),
});
await applyAccessInstalls(connected.connectionId);
return finished;
@@ -1724,7 +1774,7 @@ export function ConnectionSetupFlow({
) : null}
<div className="mt-5 flex flex-wrap gap-2">
<Button type="button" variant="outline" onClick={() => setShowConnectionChoice(false)}>
Connect new
{configuredConnection ? "Review connection setup" : "Connect new"}
</Button>
{onCancel ? <Button type="button" variant="ghost" onClick={onCancel}>Cancel</Button> : null}
</div>
@@ -1770,6 +1820,8 @@ export function ConnectionSetupFlow({
managementUrl: githubManagementUrl,
} : undefined}
authorizationHost={authorizationHost}
authorizationUrl={authorizationFallbackUrl}
onOpenAuthorization={openAuthorizationTab}
onRetry={async () => {
setOAuthError(null);
setOAuthPhase("starting");
@@ -1857,6 +1909,8 @@ export function ConnectionSetupFlow({
phase={oauthPhase}
error={oauthError}
authorizationHost={authorizationHost}
authorizationUrl={authorizationFallbackUrl}
onOpenAuthorization={openAuthorizationTab}
onRetry={() => {
setOAuthError(null);
const connection = connectResult?.connection;
@@ -1969,6 +2023,7 @@ export function ConnectionSetupFlow({
{step === "gallery" && (
<GalleryStep
loading={galleryQuery.isLoading}
initialLink={linkUrl}
apps={credentialSourceApps}
vercelConnect={vercelConnectMode}
vercelConnectAvailability={galleryQuery.data?.credentialSources?.vercelConnect ?? null}
@@ -1987,9 +2042,9 @@ export function ConnectionSetupFlow({
setCredentials({});
setGoogleSheetsLinks("");
setGoogleSheetsError(null);
setInstallAgentIds(new Set());
setInstallChoice("all");
setGrantKind(reconnectGrantKind ?? "organization");
setInstallAgentIds(new Set(requestedAgentId ? [requestedAgentId] : []));
setInstallChoice(requestedAgentId ? "specific" : "all");
setGrantKind(reconnectGrantKind ?? (requestedAgentId ? "user" : "organization"));
setStep("access");
}}
/>
@@ -2058,6 +2113,7 @@ export function ConnectionSetupFlow({
) : step === "key" && entry ? (
<KeyStep
entry={entry}
error={connectMutation.isError ? (connectMutation.error instanceof Error ? connectMutation.error.message : "Please check your key and try again.") : null}
values={credentials}
onChange={setCredentials}
oauthClientId={curatedOAuthClientId}
@@ -2072,7 +2128,7 @@ export function ConnectionSetupFlow({
onMethodChange={(nextMethod) => {
setConnectionMethodKey(nextMethod?.key ?? "");
if (!reconnectGrantKind) {
setGrantKind(defaultGrantKindFor(nextMethod));
setGrantKind(defaultGrantKindFor(nextMethod, Boolean(requestedAgentId)));
}
setCredentials({});
setCuratedOAuthClientId("");
@@ -2223,7 +2279,7 @@ export function ConnectionSetupFlow({
)}
{step === "success" && (
<SuccessStep
<ConnectionSetupCompletionScreen
appName={appName}
logoUrl={entry?.branding.logoUrl}
darkLogoUrl={entry?.branding.darkLogoUrl}
@@ -2307,7 +2363,9 @@ export function OAuthConnectStateScreen({
error,
recoveryActions,
authorizationHost,
authorizationUrl,
onRetry,
onOpenAuthorization,
onBack,
onCancel,
}: {
@@ -2326,6 +2384,9 @@ export function OAuthConnectStateScreen({
* they are being handed to (PAP-17099).
*/
authorizationHost?: string | null;
/** Already validated by prepareOAuthNavigation; used for a native browser link. */
authorizationUrl?: string | null;
onOpenAuthorization?: () => void;
onRetry: () => void;
onBack: () => void;
onCancel: () => void;
@@ -2419,6 +2480,7 @@ export function OAuthConnectStateScreen({
{phase === "redirecting" ? `Opening ${serverName}…` : "Preparing…"}
</Button>
)}
{authorizationUrl ? <Button variant="outline" asChild><a href={authorizationUrl} target="_blank" rel="noopener noreferrer" onClick={onOpenAuthorization}>Open sign-in in a new tab</a></Button> : null}
<Button type="button" variant="ghost" onClick={onBack}>Back</Button>
</div>
</div>
@@ -2480,6 +2542,7 @@ function ZapierConnectStep({
function GalleryStep({
loading,
initialLink = "",
apps,
byo = false,
byoOnly = false,
@@ -2490,6 +2553,7 @@ function GalleryStep({
onUseLink,
}: {
loading: boolean;
initialLink?: string;
apps: AppDefinition[];
/** Entered via the "Connect your own MCP server" card (PAP-12371, Finding C): focus the link path. */
byo?: boolean;
@@ -2507,7 +2571,11 @@ function GalleryStep({
onUseLink: (link: string) => void;
}) {
const [search, setSearch] = useState("");
const [linkInput, setLinkInput] = useState("");
const [linkInput, setLinkInput] = useState(initialLink);
const linkInputEdited = useRef(false);
useEffect(() => {
if (!linkInputEdited.current) setLinkInput(initialLink);
}, [initialLink]);
const [linkError, setLinkError] = useState<string | null>(null);
const linkSectionRef = useRef<HTMLDivElement>(null);
const linkInputRef = useRef<HTMLInputElement>(null);
@@ -2707,6 +2775,7 @@ function GalleryStep({
aria-label="MCP server URL"
value={linkInput}
onChange={(e) => {
linkInputEdited.current = true;
setLinkInput(e.target.value);
setLinkError(null);
}}
@@ -3068,6 +3137,7 @@ function SegmentedOption({
function KeyStep({
entry,
error,
values,
onChange,
oauthClientId,
@@ -3090,6 +3160,7 @@ function KeyStep({
onConnect,
}: {
entry: AppDefinition;
error?: string | null;
values: Record<string, string>;
onChange: (next: Record<string, string>) => void;
oauthClientId: string;
@@ -3377,6 +3448,8 @@ function KeyStep({
</div>
) : null}
{error ? <div role="alert"><InlineBanner tone="danger">{error}</InlineBanner></div> : null}
{standardConfigFields.map((field) => (
<MethodConfigField
key={field.key}
@@ -3440,6 +3513,7 @@ function KeyStep({
</label>
<Input
type="password"
aria-label={credentialFieldLabel(entry.name, field.label, fields.length)}
autoComplete="off"
value={values[field.configPath] ?? ""}
onChange={(e) => onChange({ ...values, [field.configPath]: e.target.value })}
@@ -3978,7 +4052,7 @@ function Radio({ selected }: { selected: boolean }) {
);
}
function SuccessStep({
export function ConnectionSetupCompletionScreen({
appName,
logoUrl,
darkLogoUrl,
+3
View File
@@ -2144,6 +2144,9 @@ export function DesignGuide() {
The task card is the dialog host for the shared connection setup flow. Provider forms,
validation, OAuth, access selection, and completion come from the same feature module as
the full-page Apps setup; this card owns only audience, dialog, and task refresh behavior.
Pending connections stay in the timeline beside a usable composer. The independently
addressable Connections/In-task connections stories cover access, OAuth recovery, narrow
layouts, completion, and historical outcomes.
</p>
<div className="grid gap-4 xl:grid-cols-3">
<IssueThreadInteractionCard
+43 -1
View File
@@ -310,6 +310,44 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {
expect(document.activeElement).toBe(urlInput);
});
it.each(["config-url", "transport-url", "transport-serverUrl"] as const)("reloads a generic task reconnect endpoint from %s with selection-only card metadata", async (source) => {
const endpoint = "https://archive.example.test/mcp";
const choice = { id: "conn-archive", applicationId: "app-archive", name: "Archive", status: "active" as const, enabled: true };
listApplicationsMock.mockResolvedValue({ applications: [{ id: choice.applicationId, name: "Archive", applicationKey: "archive", type: "mcp_http" }] });
listConnectionsMock.mockResolvedValue({ connections: [{
...choice, companyId: "company-1", transport: "mcp_remote", authKind: "none", credentialPolicy: "shared", credentialSource: "paperclip_vault",
config: source === "config-url" ? { url: endpoint } : {},
transportConfig: source === "transport-url" ? { url: endpoint } : source === "transport-serverUrl" ? { serverUrl: endpoint } : {},
}] });
await render(undefined, false, <ConnectionSetupFlow host="dialog" configuredConnection={choice} requestedAgentId="agent-1" />);
const input = container.querySelector<HTMLInputElement>('input[aria-label="MCP server URL"]');
expect(input?.value).toBe(endpoint);
expect(listConnectionsMock).toHaveBeenCalledWith("company-1");
await act(async () => { buttonByText("Continue")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); });
await flushReact();
await passAccessStep();
await act(async () => { buttonByText("Check link")?.dispatchEvent(new MouseEvent("click", { bubbles: true })); });
await flushReact();
expect(connectAppMock).toHaveBeenCalledWith("company-1", expect.objectContaining({
link: endpoint, reconnectConnectionId: choice.id,
}));
});
it("preserves an edited task reconnect endpoint after refreshing connection data", async () => {
const choice = { id: "conn-archive", applicationId: "app-archive", name: "Archive", status: "active" as const, enabled: true };
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
listApplicationsMock.mockResolvedValue({ applications: [{ id: choice.applicationId, name: "Archive", applicationKey: "archive", type: "mcp_http" }] });
listConnectionsMock.mockResolvedValue({ connections: [{ ...choice, companyId: "company-1", transport: "mcp_remote", authKind: "none", credentialPolicy: "shared", credentialSource: "paperclip_vault", config: { url: "https://archive.example.test/mcp" } }] });
await render(client, false, <ConnectionSetupFlow host="dialog" configuredConnection={choice} requestedAgentId="agent-1" />);
const input = container.querySelector<HTMLInputElement>('input[aria-label="MCP server URL"]');
expect(input?.value).toBe("https://archive.example.test/mcp");
await act(async () => setInputValue(input!, "https://edited.example.test/mcp"));
listConnectionsMock.mockResolvedValue({ connections: [{ ...choice, companyId: "company-1", transport: "mcp_remote", authKind: "none", credentialPolicy: "shared", credentialSource: "paperclip_vault", config: { url: "https://refreshed.example.test/mcp" } }] });
await act(async () => { await client.invalidateQueries(); });
await flushReact();
expect(container.querySelector<HTMLInputElement>('input[aria-label="MCP server URL"]')?.value).toBe("https://edited.example.test/mcp");
});
it("an unrecognized URL routes to a minimal frame with the URL and key choice", async () => {
await render();
await gotoLinkFrame(container, "https://www.example.com/actions");
@@ -1491,9 +1529,13 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {
await flushReact();
await flushReact();
expect(container.textContent).toContain("Allow popups for this site and try again");
expect(container.textContent).toContain("Open sign-in in a new tab to continue");
expect(container.textContent).toContain("Try again");
expect(onPhaseChange).toHaveBeenCalledWith("needs_retry");
const fallback = container.querySelector<HTMLAnchorElement>('a[target="_blank"]');
expect(fallback?.textContent).toBe("Open sign-in in a new tab");
expect(fallback?.href).toContain("https://mcp.notion.com/authorize");
expect(fallback?.rel).toBe("noopener noreferrer");
openSpy.mockRestore();
await act(async () => dialogRoot.unmount());