@mastra/playground-ui 72.0.0-alpha.1 → 72.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,6 +9,7 @@ const require_data_list = require("../../../data-list-BXe_ULaL.cjs");
9
9
  const require_Notice = require("../../../Notice-CS_aUxIi.cjs");
10
10
  const require_Txt = require("../../../Txt-_00wWxTd.cjs");
11
11
  const require_icons_central_IconCheckmark2Medium = require("../../../icons/central/IconCheckmark2Medium.cjs.js");
12
+ const require_icons_central_IconCrossMedium = require("../../../icons/central/IconCrossMedium.cjs.js");
12
13
  const require_icons_Icon = require("../../../icons/Icon.cjs.js");
13
14
  const require_domains_chat_tools_connect_prompt_tool_id = require("./connect-prompt-tool-id.cjs.js");
14
15
  let react = require("react");
@@ -31,16 +32,25 @@ function connectPromptFor({ toolName, toolCallId, output, metadata }) {
31
32
  }
32
33
  /** The resume tool's schema accepts; longer failure reasons are cut to fit. */
33
34
  var MAX_RESUME_ERROR_LENGTH = 500;
35
+ /** What the agent is told when the user cancels the prompt. */
36
+ var CONNECT_PROMPT_CANCELLED_ERROR = "The user cancelled connecting.";
37
+ /** Marks the user cancelling the prompt as the outcome the call was resumed with. */
38
+ var CANCELLED = Symbol("cancelled");
34
39
  /**
35
- * What to resume the paused call with: the settled flow, or a failure when the
36
- * connect session couldn't even be created (e.g. the connection limit).
40
+ * What to resume the paused call with: the user cancelling, the settled flow,
41
+ * or a failure when the connect session couldn't even be created (e.g. the
42
+ * connection limit).
37
43
  */
38
- function connectPromptResumeFor(payload, settled, createError) {
44
+ function connectPromptResumeFor(payload, cancelled, settled, createError) {
39
45
  const failed = (provider, error) => ({
40
46
  provider,
41
47
  status: "failed",
42
48
  error: error.slice(0, MAX_RESUME_ERROR_LENGTH)
43
49
  });
50
+ if (cancelled) {
51
+ const provider = payload.requestedProvider ?? payload.providers[0]?.id;
52
+ return provider ? failed(provider, CONNECT_PROMPT_CANCELLED_ERROR) : void 0;
53
+ }
44
54
  if (createError) {
45
55
  const provider = payload.requestedProvider ?? payload.providers[0]?.id;
46
56
  return provider ? failed(provider, createError.message) : void 0;
@@ -81,23 +91,26 @@ var ConnectPromptTool = ({ toolName, toolCallId, output, metadata, readOnly = fa
81
91
  });
82
92
  };
83
93
  var ConnectPromptCard = ({ toolCallId, payload, paused, readOnly }) => {
84
- const { pending, connect, connectedProviders, isCreating, createError, settled } = require_domains_connect_use_user_connect.usePendingConnect();
94
+ const { pending, connect, cancel, connectedProviders, isCreating, createError, settled } = require_domains_connect_use_user_connect.usePendingConnect();
85
95
  const { approveToolcall, isRunning, toolCallApprovals } = require_domains_chat_context_tool_call_context.useToolCall();
96
+ const [cancelled, setCancelled] = (0, react.useState)(false);
86
97
  const resumedRef = (0, react.useRef)(null);
87
98
  const alreadyResumed = toolCallApprovals[toolCallId] !== void 0;
99
+ const canCancel = !readOnly && paused && !alreadyResumed && !cancelled;
88
100
  const errorMessage = createError?.message ?? (settled?.status === "failed" ? settled.message ?? "The connection was not completed. Try connecting again." : null);
89
101
  (0, react.useEffect)(() => {
90
102
  if (readOnly || !paused || alreadyResumed || isRunning) return;
91
- const outcome = createError ?? settled;
103
+ const outcome = cancelled ? CANCELLED : createError ?? settled;
92
104
  if (!outcome || resumedRef.current === outcome) return;
93
105
  resumedRef.current = outcome;
94
- const resume = connectPromptResumeFor(payload, settled, createError);
106
+ const resume = connectPromptResumeFor(payload, cancelled, settled, createError);
95
107
  if (resume) approveToolcall(toolCallId, resume);
96
108
  }, [
97
109
  readOnly,
98
110
  paused,
99
111
  alreadyResumed,
100
112
  isRunning,
113
+ cancelled,
101
114
  settled,
102
115
  createError,
103
116
  payload,
@@ -107,79 +120,102 @@ var ConnectPromptCard = ({ toolCallId, payload, paused, readOnly }) => {
107
120
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
108
121
  "aria-label": "Connect an account",
109
122
  className: "my-2 space-y-3",
110
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(require_data_list.DataList, {
111
- columns: "minmax(0, 1fr)",
112
- fit: "container",
113
- scrollable: false,
114
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_data_list.DataList.Subheader, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Txt.Txt, {
115
- as: "h4",
116
- variant: "subheading",
117
- tone: "ink",
118
- children: "Connect an account"
119
- }) }), payload.providers.map((provider) => {
120
- const isConnected = provider.connected || connectedProviders.has(provider.id);
121
- const isPending = pending?.provider === provider.id;
122
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_data_list.DataList.RowStatic, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_data_list.DataList.Cell, {
123
- className: "col-span-full py-2",
124
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
125
- className: "flex flex-wrap items-center justify-between gap-3",
126
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
127
- className: "flex min-w-0 flex-1 items-center gap-2",
128
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_domains_connect_provider_logo.ProviderLogo, { logoUrl: provider.logoUrl }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Txt.Txt, {
129
- as: "span",
130
- variant: "body-sm",
131
- tone: "ink",
132
- className: "truncate",
133
- children: provider.displayName ?? provider.id
134
- })]
135
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
136
- className: "flex flex-wrap items-center gap-3",
137
- children: [
138
- isPending ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Txt.Txt, {
123
+ children: [
124
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(require_data_list.DataList, {
125
+ columns: "minmax(0, 1fr)",
126
+ fit: "container",
127
+ scrollable: false,
128
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(require_data_list.DataList.Subheader, {
129
+ className: "flex items-center justify-between gap-3",
130
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Txt.Txt, {
131
+ as: "h4",
132
+ variant: "subheading",
133
+ tone: "ink",
134
+ children: "Connect an account"
135
+ }), canCancel ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Button.Button, {
136
+ variant: "ghost",
137
+ size: "icon-sm",
138
+ "aria-label": "Cancel",
139
+ tooltip: "Cancel",
140
+ onClick: () => {
141
+ cancel();
142
+ setCancelled(true);
143
+ },
144
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_icons_central_IconCrossMedium.IconCrossMedium, { "aria-hidden": true })
145
+ }) : null]
146
+ }), payload.providers.map((provider) => {
147
+ const isConnected = provider.connected || connectedProviders.has(provider.id);
148
+ const isPending = pending?.provider === provider.id;
149
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_data_list.DataList.RowStatic, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_data_list.DataList.Cell, {
150
+ className: "col-span-full py-2",
151
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
152
+ className: "flex flex-wrap items-center justify-between gap-3",
153
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
154
+ className: "flex min-w-0 flex-1 items-center gap-2",
155
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_domains_connect_provider_logo.ProviderLogo, { logoUrl: provider.logoUrl }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Txt.Txt, {
139
156
  as: "span",
140
157
  variant: "body-sm",
141
- tone: "muted",
142
- role: "status",
143
- children: "Waiting for authorization…"
144
- }) : null,
145
- isPending && pending?.fallbackUrl ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
146
- href: pending.fallbackUrl,
147
- target: "_blank",
148
- rel: "noreferrer",
149
- className: "text-ui-md underline underline-offset-2",
150
- children: "Open the connect window"
151
- }) : null,
152
- isConnected ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(require_Txt.Txt, {
153
- as: "span",
154
- variant: "body-sm",
155
- tone: "muted",
156
- className: "flex min-w-24 items-center justify-center gap-1",
157
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_icons_Icon.Icon, {
158
+ tone: "ink",
159
+ className: "truncate",
160
+ children: provider.displayName ?? provider.id
161
+ })]
162
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
163
+ className: "flex flex-wrap items-center gap-3",
164
+ children: [
165
+ isPending ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Txt.Txt, {
166
+ as: "span",
167
+ variant: "body-sm",
168
+ tone: "muted",
169
+ role: "status",
170
+ children: "Waiting for authorization…"
171
+ }) : null,
172
+ isPending && pending?.fallbackUrl ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
173
+ href: pending.fallbackUrl,
174
+ target: "_blank",
175
+ rel: "noreferrer",
176
+ className: "text-ui-md underline underline-offset-2",
177
+ children: "Open the connect window"
178
+ }) : null,
179
+ isConnected ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(require_Txt.Txt, {
180
+ as: "span",
181
+ variant: "body-sm",
182
+ tone: "muted",
183
+ className: "flex min-w-24 items-center justify-center gap-1",
184
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_icons_Icon.Icon, {
185
+ size: "sm",
186
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_icons_central_IconCheckmark2Medium.IconCheckmark2Medium, { "aria-hidden": true })
187
+ }), "Connected"]
188
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Button.Button, {
189
+ variant: "primary",
158
190
  size: "sm",
159
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_icons_central_IconCheckmark2Medium.IconCheckmark2Medium, { "aria-hidden": true })
160
- }), "Connected"]
161
- }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Button.Button, {
162
- variant: "primary",
163
- size: "sm",
164
- className: "min-w-24",
165
- disabled: readOnly || isCreating,
166
- loading: isPending,
167
- onClick: () => connect(provider),
168
- children: "Connect"
169
- })
170
- ]
171
- })]
172
- })
173
- }) }, provider.id);
174
- })]
175
- }), errorMessage ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
176
- role: "alert",
177
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Notice.Notice, {
178
- variant: "destructive",
179
- title: "Couldn't connect",
180
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Notice.Notice.Message, { children: errorMessage })
181
- })
182
- }) : null]
191
+ className: "min-w-24",
192
+ disabled: readOnly || isCreating,
193
+ loading: isPending,
194
+ onClick: () => connect(provider),
195
+ children: "Connect"
196
+ })
197
+ ]
198
+ })]
199
+ })
200
+ }) }, provider.id);
201
+ })]
202
+ }),
203
+ cancelled && isRunning && !alreadyResumed ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Txt.Txt, {
204
+ as: "p",
205
+ variant: "body-sm",
206
+ tone: "muted",
207
+ role: "status",
208
+ children: "Cancelled. The agent continues once its current response finishes."
209
+ }) : null,
210
+ errorMessage ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
211
+ role: "alert",
212
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Notice.Notice, {
213
+ variant: "destructive",
214
+ title: "Couldn't connect",
215
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_Notice.Notice.Message, { children: errorMessage })
216
+ })
217
+ }) : null
218
+ ]
183
219
  });
184
220
  };
185
221
  exports.CONNECT_PROMPT_TOOL_NAME = require_domains_chat_tools_connect_prompt_tool_id.CONNECT_PROMPT_TOOL_NAME;
@@ -1 +1 @@
1
- {"version":3,"file":"connect-prompt-tool.cjs.js","names":["isConnectPromptPayload","toolInteraction","usePendingConnect","useToolCall","useRef","DataList","Txt","ProviderLogo","Icon","IconCheckmark2Medium","Button","Notice"],"sources":["../../../../src/domains/chat/tools/connect-prompt-tool.tsx"],"sourcesContent":["import { useEffect, useRef } from 'react';\nimport type { MessageMetadata } from '../messages/message-metadata';\nimport { toolInteraction } from './tool-card-kind';\nimport { useToolCall } from '@/domains/chat/context/tool-call-context';\nimport type { ConnectPromptPayload, ConnectPromptResume, SettledConnect } from '@/domains/connect';\nimport { isConnectPromptPayload, ProviderLogo, usePendingConnect } from '@/domains/connect';\nimport { Button } from '@/ds/components/Button';\nimport { DataList } from '@/ds/components/DataList';\nimport { Notice } from '@/ds/components/Notice';\nimport { Txt } from '@/ds/components/Txt';\nimport { IconCheckmark2Medium } from '@/ds/icons/central/IconCheckmark2Medium';\nimport { Icon } from '@/ds/icons/Icon';\n\nexport { CONNECT_PROMPT_TOOL_NAME } from './connect-prompt-tool-id';\n\nexport interface ConnectPromptToolProps {\n toolName: string;\n toolCallId: string;\n output: unknown;\n metadata?: MessageMetadata;\n /** Historical rendering: show the card but suppress the connect action. */\n readOnly?: boolean;\n}\n\n/**\n * The prompt this card renders: the finished call's result, or the payload\n * the run paused with while it waits for the user to connect.\n */\nfunction connectPromptFor({\n toolName,\n toolCallId,\n output,\n metadata,\n}: Pick<ConnectPromptToolProps, 'toolName' | 'toolCallId' | 'output' | 'metadata'>):\n | { payload: ConnectPromptPayload; paused: boolean }\n | undefined {\n if (isConnectPromptPayload(output)) return { payload: output, paused: false };\n const suspendPayload = toolInteraction(metadata, toolName, toolCallId).suspended?.suspendPayload;\n if (isConnectPromptPayload(suspendPayload)) return { payload: suspendPayload, paused: true };\n return undefined;\n}\n\n/** The resume tool's schema accepts; longer failure reasons are cut to fit. */\nconst MAX_RESUME_ERROR_LENGTH = 500;\n\n/**\n * What to resume the paused call with: the settled flow, or a failure when the\n * connect session couldn't even be created (e.g. the connection limit).\n */\nfunction connectPromptResumeFor(\n payload: ConnectPromptPayload,\n settled: SettledConnect | null,\n createError: Error | null,\n): ConnectPromptResume | undefined {\n const failed = (provider: string, error: string): ConnectPromptResume => ({\n provider,\n status: 'failed',\n error: error.slice(0, MAX_RESUME_ERROR_LENGTH),\n });\n if (createError) {\n const provider = payload.requestedProvider ?? payload.providers[0]?.id;\n return provider ? failed(provider, createError.message) : undefined;\n }\n if (!settled) return undefined;\n if (settled.status === 'active') return { provider: settled.provider, status: 'active' };\n return failed(settled.provider, settled.message ?? 'The connection was not completed.');\n}\n\n/**\n * Chat card for the built-in `request_connection` tool: the agent surfaces it\n * when provider tools are unavailable because the caller has no connection.\n * Each provider row offers a Connect action that creates a connect session on\n * the mounted `/connect` routes, drives the OAuth flow in a popup through the\n * server's launch gate (which verifies this browser owns the pending session\n * before redirecting to the vendor), and polls until the connection settles.\n *\n * The tool pauses the agent run while the card is up. Once the connection\n * settles, the card resumes the paused call with the outcome — connected, or\n * the reason it failed — so the agent continues from the tool's result rather\n * than a chat message.\n */\nexport const ConnectPromptTool = ({\n toolName,\n toolCallId,\n output,\n metadata,\n readOnly = false,\n}: ConnectPromptToolProps) => {\n const prompt = connectPromptFor({ toolName, toolCallId, output, metadata });\n if (!prompt) return null;\n return (\n <ConnectPromptCard toolCallId={toolCallId} payload={prompt.payload} paused={prompt.paused} readOnly={readOnly} />\n );\n};\n\ninterface ConnectPromptCardProps {\n toolCallId: string;\n payload: ConnectPromptPayload;\n /** The run is waiting on this call, so an activation resumes it. */\n paused: boolean;\n readOnly: boolean;\n}\n\nconst ConnectPromptCard = ({ toolCallId, payload, paused, readOnly }: ConnectPromptCardProps) => {\n const { pending, connect, connectedProviders, isCreating, createError, settled } = usePendingConnect();\n const { approveToolcall, isRunning, toolCallApprovals } = useToolCall();\n // The outcome (settled flow or session-creation error) this call was resumed with.\n const resumedRef = useRef<SettledConnect | Error | null>(null);\n const alreadyResumed = toolCallApprovals[toolCallId] !== undefined;\n\n const errorMessage =\n createError?.message ??\n (settled?.status === 'failed'\n ? (settled.message ?? 'The connection was not completed. Try connecting again.')\n : null);\n\n // Resume once per outcome, success or failure, so the agent sees what\n // happened in the tool result. A run that is still streaming can't be\n // resumed yet, so an outcome that lands mid-run waits for it to stop.\n useEffect(() => {\n if (readOnly || !paused || alreadyResumed || isRunning) return;\n const outcome = createError ?? settled;\n if (!outcome || resumedRef.current === outcome) return;\n resumedRef.current = outcome;\n const resume = connectPromptResumeFor(payload, settled, createError);\n if (resume) approveToolcall(toolCallId, resume);\n }, [readOnly, paused, alreadyResumed, isRunning, settled, createError, payload, approveToolcall, toolCallId]);\n\n return (\n <section aria-label=\"Connect an account\" className=\"my-2 space-y-3\">\n <DataList columns=\"minmax(0, 1fr)\" fit=\"container\" scrollable={false}>\n <DataList.Subheader>\n <Txt as=\"h4\" variant=\"subheading\" tone=\"ink\">\n Connect an account\n </Txt>\n </DataList.Subheader>\n {payload.providers.map(provider => {\n const isConnected = provider.connected || connectedProviders.has(provider.id);\n const isPending = pending?.provider === provider.id;\n return (\n <DataList.RowStatic key={provider.id}>\n <DataList.Cell className=\"col-span-full py-2\">\n <div className=\"flex flex-wrap items-center justify-between gap-3\">\n <div className=\"flex min-w-0 flex-1 items-center gap-2\">\n <ProviderLogo logoUrl={provider.logoUrl} />\n <Txt as=\"span\" variant=\"body-sm\" tone=\"ink\" className=\"truncate\">\n {provider.displayName ?? provider.id}\n </Txt>\n </div>\n <div className=\"flex flex-wrap items-center gap-3\">\n {isPending ? (\n <Txt as=\"span\" variant=\"body-sm\" tone=\"muted\" role=\"status\">\n Waiting for authorization…\n </Txt>\n ) : null}\n {isPending && pending?.fallbackUrl ? (\n <a\n href={pending.fallbackUrl}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"text-ui-md underline underline-offset-2\"\n >\n Open the connect window\n </a>\n ) : null}\n {isConnected ? (\n <Txt\n as=\"span\"\n variant=\"body-sm\"\n tone=\"muted\"\n className=\"flex min-w-24 items-center justify-center gap-1\"\n >\n <Icon size=\"sm\">\n <IconCheckmark2Medium aria-hidden />\n </Icon>\n Connected\n </Txt>\n ) : (\n <Button\n variant=\"primary\"\n size=\"sm\"\n className=\"min-w-24\"\n disabled={readOnly || isCreating}\n loading={isPending}\n onClick={() => connect(provider)}\n >\n Connect\n </Button>\n )}\n </div>\n </div>\n </DataList.Cell>\n </DataList.RowStatic>\n );\n })}\n </DataList>\n {errorMessage ? (\n <div role=\"alert\">\n <Notice variant=\"destructive\" title=\"Couldn't connect\">\n <Notice.Message>{errorMessage}</Notice.Message>\n </Notice>\n </div>\n ) : null}\n </section>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,SAAS,iBAAiB,EACxB,UACA,YACA,QACA,YAGY;CACZ,IAAIA,8BAAAA,uBAAuB,MAAM,GAAG,OAAO;EAAE,SAAS;EAAQ,QAAQ;CAAM;CAC5E,MAAM,iBAAiBC,0CAAAA,gBAAgB,UAAU,UAAU,UAAU,CAAC,CAAC,WAAW;CAClF,IAAID,8BAAAA,uBAAuB,cAAc,GAAG,OAAO;EAAE,SAAS;EAAgB,QAAQ;CAAK;AAE7F;;AAGA,IAAM,0BAA0B;;;;;AAMhC,SAAS,uBACP,SACA,SACA,aACiC;CACjC,MAAM,UAAU,UAAkB,WAAwC;EACxE;EACA,QAAQ;EACR,OAAO,MAAM,MAAM,GAAG,uBAAuB;CAC/C;CACA,IAAI,aAAa;EACf,MAAM,WAAW,QAAQ,qBAAqB,QAAQ,UAAU,EAAE,EAAE;EACpE,OAAO,WAAW,OAAO,UAAU,YAAY,OAAO,IAAI,KAAA;CAC5D;CACA,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,IAAI,QAAQ,WAAW,UAAU,OAAO;EAAE,UAAU,QAAQ;EAAU,QAAQ;CAAS;CACvF,OAAO,OAAO,QAAQ,UAAU,QAAQ,WAAW,mCAAmC;AACxF;;;;;;;;;;;;;;AAeA,IAAa,qBAAqB,EAChC,UACA,YACA,QACA,UACA,WAAW,YACiB;CAC5B,MAAM,SAAS,iBAAiB;EAAE;EAAU;EAAY;EAAQ;CAAS,CAAC;CAC1E,IAAI,CAAC,QAAQ,OAAO;CACpB,OACE,iBAAA,GAAA,kBAAA,IAAA,CAAC,mBAAD;EAA+B;EAAY,SAAS,OAAO;EAAS,QA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,MAAK;SACL,WAAU;SACV,UAAU,YAAY;SACtB,SAAS;SACT,eAAe,QAAQ,QAAQ;SAChC,UAAA;QAEO,CAAA;OAEP;MACF,CAAA,CAAA;;IACQ,CAAA,EACG,GApDK,SAAS,EAoDd;GAExB,CAAC,CACO;EACT,CAAA,GAAA,eACC,iBAAA,GAAA,kBAAA,IAAA,CAAC,OAAD;GAAK,MAAK;GACR,UAAA,iBAAA,GAAA,kBAAA,IAAA,CAACC,eAAAA,QAAD;IAAQ,SAAQ;IAAc,OAAM;IAClC,UAAA,iBAAA,GAAA,kBAAA,IAAA,CAACA,eAAAA,OAAO,SAAR,EAAA,UAAiB,aAA6B,CAAA;GACxC,CAAA;EACL,CAAA,IACH,IACG;;AAEb"}
1
+ {"version":3,"file":"connect-prompt-tool.cjs.js","names":["isConnectPromptPayload","toolInteraction","usePendingConnect","useToolCall","useState","useRef","DataList","Txt","Button","IconCrossMedium","ProviderLogo","Icon","IconCheckmark2Medium","Notice"],"sources":["../../../../src/domains/chat/tools/connect-prompt-tool.tsx"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\nimport type { MessageMetadata } from '../messages/message-metadata';\nimport { toolInteraction } from './tool-card-kind';\nimport { useToolCall } from '@/domains/chat/context/tool-call-context';\nimport type { ConnectPromptPayload, ConnectPromptResume, SettledConnect } from '@/domains/connect';\nimport { isConnectPromptPayload, ProviderLogo, usePendingConnect } from '@/domains/connect';\nimport { Button } from '@/ds/components/Button';\nimport { DataList } from '@/ds/components/DataList';\nimport { Notice } from '@/ds/components/Notice';\nimport { Txt } from '@/ds/components/Txt';\nimport { IconCheckmark2Medium } from '@/ds/icons/central/IconCheckmark2Medium';\nimport { IconCrossMedium } from '@/ds/icons/central/IconCrossMedium';\nimport { Icon } from '@/ds/icons/Icon';\n\nexport { CONNECT_PROMPT_TOOL_NAME } from './connect-prompt-tool-id';\n\nexport interface ConnectPromptToolProps {\n toolName: string;\n toolCallId: string;\n output: unknown;\n metadata?: MessageMetadata;\n /** Historical rendering: show the card but suppress the connect action. */\n readOnly?: boolean;\n}\n\n/**\n * The prompt this card renders: the finished call's result, or the payload\n * the run paused with while it waits for the user to connect.\n */\nfunction connectPromptFor({\n toolName,\n toolCallId,\n output,\n metadata,\n}: Pick<ConnectPromptToolProps, 'toolName' | 'toolCallId' | 'output' | 'metadata'>):\n | { payload: ConnectPromptPayload; paused: boolean }\n | undefined {\n if (isConnectPromptPayload(output)) return { payload: output, paused: false };\n const suspendPayload = toolInteraction(metadata, toolName, toolCallId).suspended?.suspendPayload;\n if (isConnectPromptPayload(suspendPayload)) return { payload: suspendPayload, paused: true };\n return undefined;\n}\n\n/** The resume tool's schema accepts; longer failure reasons are cut to fit. */\nconst MAX_RESUME_ERROR_LENGTH = 500;\n\n/** What the agent is told when the user cancels the prompt. */\nconst CONNECT_PROMPT_CANCELLED_ERROR = 'The user cancelled connecting.';\n\n/** Marks the user cancelling the prompt as the outcome the call was resumed with. */\nconst CANCELLED = Symbol('cancelled');\n\n/**\n * What to resume the paused call with: the user cancelling, the settled flow,\n * or a failure when the connect session couldn't even be created (e.g. the\n * connection limit).\n */\nfunction connectPromptResumeFor(\n payload: ConnectPromptPayload,\n cancelled: boolean,\n settled: SettledConnect | null,\n createError: Error | null,\n): ConnectPromptResume | undefined {\n const failed = (provider: string, error: string): ConnectPromptResume => ({\n provider,\n status: 'failed',\n error: error.slice(0, MAX_RESUME_ERROR_LENGTH),\n });\n if (cancelled) {\n const provider = payload.requestedProvider ?? payload.providers[0]?.id;\n return provider ? failed(provider, CONNECT_PROMPT_CANCELLED_ERROR) : undefined;\n }\n if (createError) {\n const provider = payload.requestedProvider ?? payload.providers[0]?.id;\n return provider ? failed(provider, createError.message) : undefined;\n }\n if (!settled) return undefined;\n if (settled.status === 'active') return { provider: settled.provider, status: 'active' };\n return failed(settled.provider, settled.message ?? 'The connection was not completed.');\n}\n\n/**\n * Chat card for the built-in `request_connection` tool: the agent surfaces it\n * when provider tools are unavailable because the caller has no connection.\n * Each provider row offers a Connect action that creates a connect session on\n * the mounted `/connect` routes, drives the OAuth flow in a popup through the\n * server's launch gate (which verifies this browser owns the pending session\n * before redirecting to the vendor), and polls until the connection settles.\n *\n * The tool pauses the agent run while the card is up. Once the connection\n * settles, the card resumes the paused call with the outcome — connected, or\n * the reason it failed — so the agent continues from the tool's result rather\n * than a chat message.\n */\nexport const ConnectPromptTool = ({\n toolName,\n toolCallId,\n output,\n metadata,\n readOnly = false,\n}: ConnectPromptToolProps) => {\n const prompt = connectPromptFor({ toolName, toolCallId, output, metadata });\n if (!prompt) return null;\n return (\n <ConnectPromptCard toolCallId={toolCallId} payload={prompt.payload} paused={prompt.paused} readOnly={readOnly} />\n );\n};\n\ninterface ConnectPromptCardProps {\n toolCallId: string;\n payload: ConnectPromptPayload;\n /** The run is waiting on this call, so an activation resumes it. */\n paused: boolean;\n readOnly: boolean;\n}\n\nconst ConnectPromptCard = ({ toolCallId, payload, paused, readOnly }: ConnectPromptCardProps) => {\n const { pending, connect, cancel, connectedProviders, isCreating, createError, settled } = usePendingConnect();\n const { approveToolcall, isRunning, toolCallApprovals } = useToolCall();\n const [cancelled, setCancelled] = useState(false);\n // The outcome (cancel, settled flow or session-creation error) this call was resumed with.\n const resumedRef = useRef<typeof CANCELLED | SettledConnect | Error | null>(null);\n const alreadyResumed = toolCallApprovals[toolCallId] !== undefined;\n // A paused call holds the run until it is resumed, so the user can always back out of it.\n const canCancel = !readOnly && paused && !alreadyResumed && !cancelled;\n\n const errorMessage =\n createError?.message ??\n (settled?.status === 'failed'\n ? (settled.message ?? 'The connection was not completed. Try connecting again.')\n : null);\n\n // Resume once per outcome, success or failure, so the agent sees what\n // happened in the tool result. A run that is still streaming can't be\n // resumed yet, so an outcome that lands mid-run waits for it to stop.\n useEffect(() => {\n if (readOnly || !paused || alreadyResumed || isRunning) return;\n const outcome = cancelled ? CANCELLED : (createError ?? settled);\n if (!outcome || resumedRef.current === outcome) return;\n resumedRef.current = outcome;\n const resume = connectPromptResumeFor(payload, cancelled, settled, createError);\n if (resume) approveToolcall(toolCallId, resume);\n }, [\n readOnly,\n paused,\n alreadyResumed,\n isRunning,\n cancelled,\n settled,\n createError,\n payload,\n approveToolcall,\n toolCallId,\n ]);\n\n return (\n <section aria-label=\"Connect an account\" className=\"my-2 space-y-3\">\n <DataList columns=\"minmax(0, 1fr)\" fit=\"container\" scrollable={false}>\n <DataList.Subheader className=\"flex items-center justify-between gap-3\">\n <Txt as=\"h4\" variant=\"subheading\" tone=\"ink\">\n Connect an account\n </Txt>\n {canCancel ? (\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Cancel\"\n tooltip=\"Cancel\"\n onClick={() => {\n cancel();\n setCancelled(true);\n }}\n >\n <IconCrossMedium aria-hidden />\n </Button>\n ) : null}\n </DataList.Subheader>\n {payload.providers.map(provider => {\n const isConnected = provider.connected || connectedProviders.has(provider.id);\n const isPending = pending?.provider === provider.id;\n return (\n <DataList.RowStatic key={provider.id}>\n <DataList.Cell className=\"col-span-full py-2\">\n <div className=\"flex flex-wrap items-center justify-between gap-3\">\n <div className=\"flex min-w-0 flex-1 items-center gap-2\">\n <ProviderLogo logoUrl={provider.logoUrl} />\n <Txt as=\"span\" variant=\"body-sm\" tone=\"ink\" className=\"truncate\">\n {provider.displayName ?? provider.id}\n </Txt>\n </div>\n <div className=\"flex flex-wrap items-center gap-3\">\n {isPending ? (\n <Txt as=\"span\" variant=\"body-sm\" tone=\"muted\" role=\"status\">\n Waiting for authorization…\n </Txt>\n ) : null}\n {isPending && pending?.fallbackUrl ? (\n <a\n href={pending.fallbackUrl}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"text-ui-md underline underline-offset-2\"\n >\n Open the connect window\n </a>\n ) : null}\n {isConnected ? (\n <Txt\n as=\"span\"\n variant=\"body-sm\"\n tone=\"muted\"\n className=\"flex min-w-24 items-center justify-center gap-1\"\n >\n <Icon size=\"sm\">\n <IconCheckmark2Medium aria-hidden />\n </Icon>\n Connected\n </Txt>\n ) : (\n <Button\n variant=\"primary\"\n size=\"sm\"\n className=\"min-w-24\"\n disabled={readOnly || isCreating}\n loading={isPending}\n onClick={() => connect(provider)}\n >\n Connect\n </Button>\n )}\n </div>\n </div>\n </DataList.Cell>\n </DataList.RowStatic>\n );\n })}\n </DataList>\n {cancelled && isRunning && !alreadyResumed ? (\n <Txt as=\"p\" variant=\"body-sm\" tone=\"muted\" role=\"status\">\n Cancelled. The agent continues once its current response finishes.\n </Txt>\n ) : null}\n {errorMessage ? (\n <div role=\"alert\">\n <Notice variant=\"destructive\" title=\"Couldn't connect\">\n <Notice.Message>{errorMessage}</Notice.Message>\n </Notice>\n </div>\n ) : null}\n </section>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6BA,SAAS,iBAAiB,EACxB,UACA,YACA,QACA,YAGY;CACZ,IAAIA,8BAAAA,uBAAuB,MAAM,GAAG,OAAO;EAAE,SAAS;EAAQ,QAAQ;CAAM;CAC5E,MAAM,iBAAiBC,0CAAAA,gBAAgB,UAAU,UAAU,UAAU,CAAC,CAAC,WAAW;CAClF,IAAID,8BAAAA,uBAAuB,cAAc,GAAG,OAAO;EAAE,SAAS;EAAgB,QAAQ;CAAK;AAE7F;;AAGA,IAAM,0BAA0B;;AAGhC,IAAM,iCAAiC;;AAGvC,IAAM,YAAY,OAAO,WAAW;;;;;;AAOpC,SAAS,uBACP,SACA,WACA,SACA,aACiC;CACjC,MAAM,UAAU,UAAkB,WAAwC;EACxE;EACA,QAAQ;EACR,OAAO,MAAM,MAAM,GAAG,uBAAuB;CAC/C;CACA,IAAI,WAAW;EACb,MAAM,WAAW,QAAQ,qBAAqB,QAAQ,UAAU,EAAE,EAAE;EACpE,OAAO,WAAW,OAAO,UAAU,8BAA8B,IAAI,KAAA;CACvE;CACA,IAAI,aAAa;EACf,MAAM,WAAW,QAAQ,qBAAqB,QAAQ,UAAU,EAAE,EAAE;EACpE,OAAO,WAAW,OAAO,UAAU,YAAY,OAAO,IAAI,KAAA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MAAK;IACR,UAAA,iBAAA,GAAA,kBAAA,IAAA,CAACM,eAAAA,QAAD;KAAQ,SAAQ;KAAc,OAAM;KAClC,UAAA,iBAAA,GAAA,kBAAA,IAAA,CAACA,eAAAA,OAAO,SAAR,EAAA,UAAiB,aAA6B,CAAA;IACxC,CAAA;GACL,CAAA,IACH;EACG;;AAEb"}
@@ -8,9 +8,10 @@ import { t as DataList } from "../../../data-list-BV-YCOhk.js";
8
8
  import { t as Notice } from "../../../Notice-BdfIyUok.js";
9
9
  import { t as Txt } from "../../../Txt-5efBsb2p.js";
10
10
  import { IconCheckmark2Medium } from "../../../icons/central/IconCheckmark2Medium.es.js";
11
+ import { IconCrossMedium } from "../../../icons/central/IconCrossMedium.es.js";
11
12
  import { Icon } from "../../../icons/Icon.es.js";
12
13
  import { CONNECT_PROMPT_TOOL_NAME } from "./connect-prompt-tool-id.es.js";
13
- import { useEffect, useRef } from "react";
14
+ import { useEffect, useRef, useState } from "react";
14
15
  import { jsx, jsxs } from "react/jsx-runtime";
15
16
  // src/domains/chat/tools/connect-prompt-tool.tsx
16
17
  /**
@@ -30,16 +31,25 @@ function connectPromptFor({ toolName, toolCallId, output, metadata }) {
30
31
  }
31
32
  /** The resume tool's schema accepts; longer failure reasons are cut to fit. */
32
33
  var MAX_RESUME_ERROR_LENGTH = 500;
34
+ /** What the agent is told when the user cancels the prompt. */
35
+ var CONNECT_PROMPT_CANCELLED_ERROR = "The user cancelled connecting.";
36
+ /** Marks the user cancelling the prompt as the outcome the call was resumed with. */
37
+ var CANCELLED = Symbol("cancelled");
33
38
  /**
34
- * What to resume the paused call with: the settled flow, or a failure when the
35
- * connect session couldn't even be created (e.g. the connection limit).
39
+ * What to resume the paused call with: the user cancelling, the settled flow,
40
+ * or a failure when the connect session couldn't even be created (e.g. the
41
+ * connection limit).
36
42
  */
37
- function connectPromptResumeFor(payload, settled, createError) {
43
+ function connectPromptResumeFor(payload, cancelled, settled, createError) {
38
44
  const failed = (provider, error) => ({
39
45
  provider,
40
46
  status: "failed",
41
47
  error: error.slice(0, MAX_RESUME_ERROR_LENGTH)
42
48
  });
49
+ if (cancelled) {
50
+ const provider = payload.requestedProvider ?? payload.providers[0]?.id;
51
+ return provider ? failed(provider, CONNECT_PROMPT_CANCELLED_ERROR) : void 0;
52
+ }
43
53
  if (createError) {
44
54
  const provider = payload.requestedProvider ?? payload.providers[0]?.id;
45
55
  return provider ? failed(provider, createError.message) : void 0;
@@ -80,23 +90,26 @@ var ConnectPromptTool = ({ toolName, toolCallId, output, metadata, readOnly = fa
80
90
  });
81
91
  };
82
92
  var ConnectPromptCard = ({ toolCallId, payload, paused, readOnly }) => {
83
- const { pending, connect, connectedProviders, isCreating, createError, settled } = usePendingConnect();
93
+ const { pending, connect, cancel, connectedProviders, isCreating, createError, settled } = usePendingConnect();
84
94
  const { approveToolcall, isRunning, toolCallApprovals } = useToolCall();
95
+ const [cancelled, setCancelled] = useState(false);
85
96
  const resumedRef = useRef(null);
86
97
  const alreadyResumed = toolCallApprovals[toolCallId] !== void 0;
98
+ const canCancel = !readOnly && paused && !alreadyResumed && !cancelled;
87
99
  const errorMessage = createError?.message ?? (settled?.status === "failed" ? settled.message ?? "The connection was not completed. Try connecting again." : null);
88
100
  useEffect(() => {
89
101
  if (readOnly || !paused || alreadyResumed || isRunning) return;
90
- const outcome = createError ?? settled;
102
+ const outcome = cancelled ? CANCELLED : createError ?? settled;
91
103
  if (!outcome || resumedRef.current === outcome) return;
92
104
  resumedRef.current = outcome;
93
- const resume = connectPromptResumeFor(payload, settled, createError);
105
+ const resume = connectPromptResumeFor(payload, cancelled, settled, createError);
94
106
  if (resume) approveToolcall(toolCallId, resume);
95
107
  }, [
96
108
  readOnly,
97
109
  paused,
98
110
  alreadyResumed,
99
111
  isRunning,
112
+ cancelled,
100
113
  settled,
101
114
  createError,
102
115
  payload,
@@ -106,79 +119,102 @@ var ConnectPromptCard = ({ toolCallId, payload, paused, readOnly }) => {
106
119
  return /* @__PURE__ */ jsxs("section", {
107
120
  "aria-label": "Connect an account",
108
121
  className: "my-2 space-y-3",
109
- children: [/* @__PURE__ */ jsxs(DataList, {
110
- columns: "minmax(0, 1fr)",
111
- fit: "container",
112
- scrollable: false,
113
- children: [/* @__PURE__ */ jsx(DataList.Subheader, { children: /* @__PURE__ */ jsx(Txt, {
114
- as: "h4",
115
- variant: "subheading",
116
- tone: "ink",
117
- children: "Connect an account"
118
- }) }), payload.providers.map((provider) => {
119
- const isConnected = provider.connected || connectedProviders.has(provider.id);
120
- const isPending = pending?.provider === provider.id;
121
- return /* @__PURE__ */ jsx(DataList.RowStatic, { children: /* @__PURE__ */ jsx(DataList.Cell, {
122
- className: "col-span-full py-2",
123
- children: /* @__PURE__ */ jsxs("div", {
124
- className: "flex flex-wrap items-center justify-between gap-3",
125
- children: [/* @__PURE__ */ jsxs("div", {
126
- className: "flex min-w-0 flex-1 items-center gap-2",
127
- children: [/* @__PURE__ */ jsx(ProviderLogo, { logoUrl: provider.logoUrl }), /* @__PURE__ */ jsx(Txt, {
128
- as: "span",
129
- variant: "body-sm",
130
- tone: "ink",
131
- className: "truncate",
132
- children: provider.displayName ?? provider.id
133
- })]
134
- }), /* @__PURE__ */ jsxs("div", {
135
- className: "flex flex-wrap items-center gap-3",
136
- children: [
137
- isPending ? /* @__PURE__ */ jsx(Txt, {
122
+ children: [
123
+ /* @__PURE__ */ jsxs(DataList, {
124
+ columns: "minmax(0, 1fr)",
125
+ fit: "container",
126
+ scrollable: false,
127
+ children: [/* @__PURE__ */ jsxs(DataList.Subheader, {
128
+ className: "flex items-center justify-between gap-3",
129
+ children: [/* @__PURE__ */ jsx(Txt, {
130
+ as: "h4",
131
+ variant: "subheading",
132
+ tone: "ink",
133
+ children: "Connect an account"
134
+ }), canCancel ? /* @__PURE__ */ jsx(Button, {
135
+ variant: "ghost",
136
+ size: "icon-sm",
137
+ "aria-label": "Cancel",
138
+ tooltip: "Cancel",
139
+ onClick: () => {
140
+ cancel();
141
+ setCancelled(true);
142
+ },
143
+ children: /* @__PURE__ */ jsx(IconCrossMedium, { "aria-hidden": true })
144
+ }) : null]
145
+ }), payload.providers.map((provider) => {
146
+ const isConnected = provider.connected || connectedProviders.has(provider.id);
147
+ const isPending = pending?.provider === provider.id;
148
+ return /* @__PURE__ */ jsx(DataList.RowStatic, { children: /* @__PURE__ */ jsx(DataList.Cell, {
149
+ className: "col-span-full py-2",
150
+ children: /* @__PURE__ */ jsxs("div", {
151
+ className: "flex flex-wrap items-center justify-between gap-3",
152
+ children: [/* @__PURE__ */ jsxs("div", {
153
+ className: "flex min-w-0 flex-1 items-center gap-2",
154
+ children: [/* @__PURE__ */ jsx(ProviderLogo, { logoUrl: provider.logoUrl }), /* @__PURE__ */ jsx(Txt, {
138
155
  as: "span",
139
156
  variant: "body-sm",
140
- tone: "muted",
141
- role: "status",
142
- children: "Waiting for authorization…"
143
- }) : null,
144
- isPending && pending?.fallbackUrl ? /* @__PURE__ */ jsx("a", {
145
- href: pending.fallbackUrl,
146
- target: "_blank",
147
- rel: "noreferrer",
148
- className: "text-ui-md underline underline-offset-2",
149
- children: "Open the connect window"
150
- }) : null,
151
- isConnected ? /* @__PURE__ */ jsxs(Txt, {
152
- as: "span",
153
- variant: "body-sm",
154
- tone: "muted",
155
- className: "flex min-w-24 items-center justify-center gap-1",
156
- children: [/* @__PURE__ */ jsx(Icon, {
157
+ tone: "ink",
158
+ className: "truncate",
159
+ children: provider.displayName ?? provider.id
160
+ })]
161
+ }), /* @__PURE__ */ jsxs("div", {
162
+ className: "flex flex-wrap items-center gap-3",
163
+ children: [
164
+ isPending ? /* @__PURE__ */ jsx(Txt, {
165
+ as: "span",
166
+ variant: "body-sm",
167
+ tone: "muted",
168
+ role: "status",
169
+ children: "Waiting for authorization…"
170
+ }) : null,
171
+ isPending && pending?.fallbackUrl ? /* @__PURE__ */ jsx("a", {
172
+ href: pending.fallbackUrl,
173
+ target: "_blank",
174
+ rel: "noreferrer",
175
+ className: "text-ui-md underline underline-offset-2",
176
+ children: "Open the connect window"
177
+ }) : null,
178
+ isConnected ? /* @__PURE__ */ jsxs(Txt, {
179
+ as: "span",
180
+ variant: "body-sm",
181
+ tone: "muted",
182
+ className: "flex min-w-24 items-center justify-center gap-1",
183
+ children: [/* @__PURE__ */ jsx(Icon, {
184
+ size: "sm",
185
+ children: /* @__PURE__ */ jsx(IconCheckmark2Medium, { "aria-hidden": true })
186
+ }), "Connected"]
187
+ }) : /* @__PURE__ */ jsx(Button, {
188
+ variant: "primary",
157
189
  size: "sm",
158
- children: /* @__PURE__ */ jsx(IconCheckmark2Medium, { "aria-hidden": true })
159
- }), "Connected"]
160
- }) : /* @__PURE__ */ jsx(Button, {
161
- variant: "primary",
162
- size: "sm",
163
- className: "min-w-24",
164
- disabled: readOnly || isCreating,
165
- loading: isPending,
166
- onClick: () => connect(provider),
167
- children: "Connect"
168
- })
169
- ]
170
- })]
171
- })
172
- }) }, provider.id);
173
- })]
174
- }), errorMessage ? /* @__PURE__ */ jsx("div", {
175
- role: "alert",
176
- children: /* @__PURE__ */ jsx(Notice, {
177
- variant: "destructive",
178
- title: "Couldn't connect",
179
- children: /* @__PURE__ */ jsx(Notice.Message, { children: errorMessage })
180
- })
181
- }) : null]
190
+ className: "min-w-24",
191
+ disabled: readOnly || isCreating,
192
+ loading: isPending,
193
+ onClick: () => connect(provider),
194
+ children: "Connect"
195
+ })
196
+ ]
197
+ })]
198
+ })
199
+ }) }, provider.id);
200
+ })]
201
+ }),
202
+ cancelled && isRunning && !alreadyResumed ? /* @__PURE__ */ jsx(Txt, {
203
+ as: "p",
204
+ variant: "body-sm",
205
+ tone: "muted",
206
+ role: "status",
207
+ children: "Cancelled. The agent continues once its current response finishes."
208
+ }) : null,
209
+ errorMessage ? /* @__PURE__ */ jsx("div", {
210
+ role: "alert",
211
+ children: /* @__PURE__ */ jsx(Notice, {
212
+ variant: "destructive",
213
+ title: "Couldn't connect",
214
+ children: /* @__PURE__ */ jsx(Notice.Message, { children: errorMessage })
215
+ })
216
+ }) : null
217
+ ]
182
218
  });
183
219
  };
184
220
  export { CONNECT_PROMPT_TOOL_NAME, ConnectPromptTool };
@@ -1 +1 @@
1
- {"version":3,"file":"connect-prompt-tool.es.js","names":[],"sources":["../../../../src/domains/chat/tools/connect-prompt-tool.tsx"],"sourcesContent":["import { useEffect, useRef } from 'react';\nimport type { MessageMetadata } from '../messages/message-metadata';\nimport { toolInteraction } from './tool-card-kind';\nimport { useToolCall } from '@/domains/chat/context/tool-call-context';\nimport type { ConnectPromptPayload, ConnectPromptResume, SettledConnect } from '@/domains/connect';\nimport { isConnectPromptPayload, ProviderLogo, usePendingConnect } from '@/domains/connect';\nimport { Button } from '@/ds/components/Button';\nimport { DataList } from '@/ds/components/DataList';\nimport { Notice } from '@/ds/components/Notice';\nimport { Txt } from '@/ds/components/Txt';\nimport { IconCheckmark2Medium } from '@/ds/icons/central/IconCheckmark2Medium';\nimport { Icon } from '@/ds/icons/Icon';\n\nexport { CONNECT_PROMPT_TOOL_NAME } from './connect-prompt-tool-id';\n\nexport interface ConnectPromptToolProps {\n toolName: string;\n toolCallId: string;\n output: unknown;\n metadata?: MessageMetadata;\n /** Historical rendering: show the card but suppress the connect action. */\n readOnly?: boolean;\n}\n\n/**\n * The prompt this card renders: the finished call's result, or the payload\n * the run paused with while it waits for the user to connect.\n */\nfunction connectPromptFor({\n toolName,\n toolCallId,\n output,\n metadata,\n}: Pick<ConnectPromptToolProps, 'toolName' | 'toolCallId' | 'output' | 'metadata'>):\n | { payload: ConnectPromptPayload; paused: boolean }\n | undefined {\n if (isConnectPromptPayload(output)) return { payload: output, paused: false };\n const suspendPayload = toolInteraction(metadata, toolName, toolCallId).suspended?.suspendPayload;\n if (isConnectPromptPayload(suspendPayload)) return { payload: suspendPayload, paused: true };\n return undefined;\n}\n\n/** The resume tool's schema accepts; longer failure reasons are cut to fit. */\nconst MAX_RESUME_ERROR_LENGTH = 500;\n\n/**\n * What to resume the paused call with: the settled flow, or a failure when the\n * connect session couldn't even be created (e.g. the connection limit).\n */\nfunction connectPromptResumeFor(\n payload: ConnectPromptPayload,\n settled: SettledConnect | null,\n createError: Error | null,\n): ConnectPromptResume | undefined {\n const failed = (provider: string, error: string): ConnectPromptResume => ({\n provider,\n status: 'failed',\n error: error.slice(0, MAX_RESUME_ERROR_LENGTH),\n });\n if (createError) {\n const provider = payload.requestedProvider ?? payload.providers[0]?.id;\n return provider ? failed(provider, createError.message) : undefined;\n }\n if (!settled) return undefined;\n if (settled.status === 'active') return { provider: settled.provider, status: 'active' };\n return failed(settled.provider, settled.message ?? 'The connection was not completed.');\n}\n\n/**\n * Chat card for the built-in `request_connection` tool: the agent surfaces it\n * when provider tools are unavailable because the caller has no connection.\n * Each provider row offers a Connect action that creates a connect session on\n * the mounted `/connect` routes, drives the OAuth flow in a popup through the\n * server's launch gate (which verifies this browser owns the pending session\n * before redirecting to the vendor), and polls until the connection settles.\n *\n * The tool pauses the agent run while the card is up. Once the connection\n * settles, the card resumes the paused call with the outcome — connected, or\n * the reason it failed — so the agent continues from the tool's result rather\n * than a chat message.\n */\nexport const ConnectPromptTool = ({\n toolName,\n toolCallId,\n output,\n metadata,\n readOnly = false,\n}: ConnectPromptToolProps) => {\n const prompt = connectPromptFor({ toolName, toolCallId, output, metadata });\n if (!prompt) return null;\n return (\n <ConnectPromptCard toolCallId={toolCallId} payload={prompt.payload} paused={prompt.paused} readOnly={readOnly} />\n );\n};\n\ninterface ConnectPromptCardProps {\n toolCallId: string;\n payload: ConnectPromptPayload;\n /** The run is waiting on this call, so an activation resumes it. */\n paused: boolean;\n readOnly: boolean;\n}\n\nconst ConnectPromptCard = ({ toolCallId, payload, paused, readOnly }: ConnectPromptCardProps) => {\n const { pending, connect, connectedProviders, isCreating, createError, settled } = usePendingConnect();\n const { approveToolcall, isRunning, toolCallApprovals } = useToolCall();\n // The outcome (settled flow or session-creation error) this call was resumed with.\n const resumedRef = useRef<SettledConnect | Error | null>(null);\n const alreadyResumed = toolCallApprovals[toolCallId] !== undefined;\n\n const errorMessage =\n createError?.message ??\n (settled?.status === 'failed'\n ? (settled.message ?? 'The connection was not completed. Try connecting again.')\n : null);\n\n // Resume once per outcome, success or failure, so the agent sees what\n // happened in the tool result. A run that is still streaming can't be\n // resumed yet, so an outcome that lands mid-run waits for it to stop.\n useEffect(() => {\n if (readOnly || !paused || alreadyResumed || isRunning) return;\n const outcome = createError ?? settled;\n if (!outcome || resumedRef.current === outcome) return;\n resumedRef.current = outcome;\n const resume = connectPromptResumeFor(payload, settled, createError);\n if (resume) approveToolcall(toolCallId, resume);\n }, [readOnly, paused, alreadyResumed, isRunning, settled, createError, payload, approveToolcall, toolCallId]);\n\n return (\n <section aria-label=\"Connect an account\" className=\"my-2 space-y-3\">\n <DataList columns=\"minmax(0, 1fr)\" fit=\"container\" scrollable={false}>\n <DataList.Subheader>\n <Txt as=\"h4\" variant=\"subheading\" tone=\"ink\">\n Connect an account\n </Txt>\n </DataList.Subheader>\n {payload.providers.map(provider => {\n const isConnected = provider.connected || connectedProviders.has(provider.id);\n const isPending = pending?.provider === provider.id;\n return (\n <DataList.RowStatic key={provider.id}>\n <DataList.Cell className=\"col-span-full py-2\">\n <div className=\"flex flex-wrap items-center justify-between gap-3\">\n <div className=\"flex min-w-0 flex-1 items-center gap-2\">\n <ProviderLogo logoUrl={provider.logoUrl} />\n <Txt as=\"span\" variant=\"body-sm\" tone=\"ink\" className=\"truncate\">\n {provider.displayName ?? provider.id}\n </Txt>\n </div>\n <div className=\"flex flex-wrap items-center gap-3\">\n {isPending ? (\n <Txt as=\"span\" variant=\"body-sm\" tone=\"muted\" role=\"status\">\n Waiting for authorization…\n </Txt>\n ) : null}\n {isPending && pending?.fallbackUrl ? (\n <a\n href={pending.fallbackUrl}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"text-ui-md underline underline-offset-2\"\n >\n Open the connect window\n </a>\n ) : null}\n {isConnected ? (\n <Txt\n as=\"span\"\n variant=\"body-sm\"\n tone=\"muted\"\n className=\"flex min-w-24 items-center justify-center gap-1\"\n >\n <Icon size=\"sm\">\n <IconCheckmark2Medium aria-hidden />\n </Icon>\n Connected\n </Txt>\n ) : (\n <Button\n variant=\"primary\"\n size=\"sm\"\n className=\"min-w-24\"\n disabled={readOnly || isCreating}\n loading={isPending}\n onClick={() => connect(provider)}\n >\n Connect\n </Button>\n )}\n </div>\n </div>\n </DataList.Cell>\n </DataList.RowStatic>\n );\n })}\n </DataList>\n {errorMessage ? (\n <div role=\"alert\">\n <Notice variant=\"destructive\" title=\"Couldn't connect\">\n <Notice.Message>{errorMessage}</Notice.Message>\n </Notice>\n </div>\n ) : null}\n </section>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA4BA,SAAS,iBAAiB,EACxB,UACA,YACA,QACA,YAGY;CACZ,IAAI,uBAAuB,MAAM,GAAG,OAAO;EAAE,SAAS;EAAQ,QAAQ;CAAM;CAC5E,MAAM,iBAAiB,gBAAgB,UAAU,UAAU,UAAU,CAAC,CAAC,WAAW;CAClF,IAAI,uBAAuB,cAAc,GAAG,OAAO;EAAE,SAAS;EAAgB,QAAQ;CAAK;AAE7F;;AAGA,IAAM,0BAA0B;;;;;AAMhC,SAAS,uBACP,SACA,SACA,aACiC;CACjC,MAAM,UAAU,UAAkB,WAAwC;EACxE;EACA,QAAQ;EACR,OAAO,MAAM,MAAM,GAAG,uBAAuB;CAC/C;CACA,IAAI,aAAa;EACf,MAAM,WAAW,QAAQ,qBAAqB,QAAQ,UAAU,EAAE,EAAE;EACpE,OAAO,WAAW,OAAO,UAAU,YAAY,OAAO,IAAI,KAAA;CAC5D;CACA,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,IAAI,QAAQ,WAAW,UAAU,OAAO;EAAE,UAAU,QAAQ;EAAU,QAAQ;CAAS;CACvF,OAAO,OAAO,QAAQ,UAAU,QAAQ,WAAW,mCAAmC;AACxF;;;;;;;;;;;;;;AAeA,IAAa,qBAAqB,EAChC,UACA,YACA,QACA,UACA,WAAW,YACiB;CAC5B,MAAM,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tsx"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\nimport type { MessageMetadata } from '../messages/message-metadata';\nimport { toolInteraction } from './tool-card-kind';\nimport { useToolCall } from '@/domains/chat/context/tool-call-context';\nimport type { ConnectPromptPayload, ConnectPromptResume, SettledConnect } from '@/domains/connect';\nimport { isConnectPromptPayload, ProviderLogo, usePendingConnect } from '@/domains/connect';\nimport { Button } from '@/ds/components/Button';\nimport { DataList } from '@/ds/components/DataList';\nimport { Notice } from '@/ds/components/Notice';\nimport { Txt } from '@/ds/components/Txt';\nimport { IconCheckmark2Medium } from '@/ds/icons/central/IconCheckmark2Medium';\nimport { IconCrossMedium } from '@/ds/icons/central/IconCrossMedium';\nimport { Icon } from '@/ds/icons/Icon';\n\nexport { CONNECT_PROMPT_TOOL_NAME } from './connect-prompt-tool-id';\n\nexport interface ConnectPromptToolProps {\n toolName: string;\n toolCallId: string;\n output: unknown;\n metadata?: MessageMetadata;\n /** Historical rendering: show the card but suppress the connect action. */\n readOnly?: boolean;\n}\n\n/**\n * The prompt this card renders: the finished call's result, or the payload\n * the run paused with while it waits for the user to connect.\n */\nfunction connectPromptFor({\n toolName,\n toolCallId,\n output,\n metadata,\n}: Pick<ConnectPromptToolProps, 'toolName' | 'toolCallId' | 'output' | 'metadata'>):\n | { payload: ConnectPromptPayload; paused: boolean }\n | undefined {\n if (isConnectPromptPayload(output)) return { payload: output, paused: false };\n const suspendPayload = toolInteraction(metadata, toolName, toolCallId).suspended?.suspendPayload;\n if (isConnectPromptPayload(suspendPayload)) return { payload: suspendPayload, paused: true };\n return undefined;\n}\n\n/** The resume tool's schema accepts; longer failure reasons are cut to fit. */\nconst MAX_RESUME_ERROR_LENGTH = 500;\n\n/** What the agent is told when the user cancels the prompt. */\nconst CONNECT_PROMPT_CANCELLED_ERROR = 'The user cancelled connecting.';\n\n/** Marks the user cancelling the prompt as the outcome the call was resumed with. */\nconst CANCELLED = Symbol('cancelled');\n\n/**\n * What to resume the paused call with: the user cancelling, the settled flow,\n * or a failure when the connect session couldn't even be created (e.g. the\n * connection limit).\n */\nfunction connectPromptResumeFor(\n payload: ConnectPromptPayload,\n cancelled: boolean,\n settled: SettledConnect | null,\n createError: Error | null,\n): ConnectPromptResume | undefined {\n const failed = (provider: string, error: string): ConnectPromptResume => ({\n provider,\n status: 'failed',\n error: error.slice(0, MAX_RESUME_ERROR_LENGTH),\n });\n if (cancelled) {\n const provider = payload.requestedProvider ?? payload.providers[0]?.id;\n return provider ? failed(provider, CONNECT_PROMPT_CANCELLED_ERROR) : undefined;\n }\n if (createError) {\n const provider = payload.requestedProvider ?? payload.providers[0]?.id;\n return provider ? failed(provider, createError.message) : undefined;\n }\n if (!settled) return undefined;\n if (settled.status === 'active') return { provider: settled.provider, status: 'active' };\n return failed(settled.provider, settled.message ?? 'The connection was not completed.');\n}\n\n/**\n * Chat card for the built-in `request_connection` tool: the agent surfaces it\n * when provider tools are unavailable because the caller has no connection.\n * Each provider row offers a Connect action that creates a connect session on\n * the mounted `/connect` routes, drives the OAuth flow in a popup through the\n * server's launch gate (which verifies this browser owns the pending session\n * before redirecting to the vendor), and polls until the connection settles.\n *\n * The tool pauses the agent run while the card is up. Once the connection\n * settles, the card resumes the paused call with the outcome — connected, or\n * the reason it failed — so the agent continues from the tool's result rather\n * than a chat message.\n */\nexport const ConnectPromptTool = ({\n toolName,\n toolCallId,\n output,\n metadata,\n readOnly = false,\n}: ConnectPromptToolProps) => {\n const prompt = connectPromptFor({ toolName, toolCallId, output, metadata });\n if (!prompt) return null;\n return (\n <ConnectPromptCard toolCallId={toolCallId} payload={prompt.payload} paused={prompt.paused} readOnly={readOnly} />\n );\n};\n\ninterface ConnectPromptCardProps {\n toolCallId: string;\n payload: ConnectPromptPayload;\n /** The run is waiting on this call, so an activation resumes it. */\n paused: boolean;\n readOnly: boolean;\n}\n\nconst ConnectPromptCard = ({ toolCallId, payload, paused, readOnly }: ConnectPromptCardProps) => {\n const { pending, connect, cancel, connectedProviders, isCreating, createError, settled } = usePendingConnect();\n const { approveToolcall, isRunning, toolCallApprovals } = useToolCall();\n const [cancelled, setCancelled] = useState(false);\n // The outcome (cancel, settled flow or session-creation error) this call was resumed with.\n const resumedRef = useRef<typeof CANCELLED | SettledConnect | Error | null>(null);\n const alreadyResumed = toolCallApprovals[toolCallId] !== undefined;\n // A paused call holds the run until it is resumed, so the user can always back out of it.\n const canCancel = !readOnly && paused && !alreadyResumed && !cancelled;\n\n const errorMessage =\n createError?.message ??\n (settled?.status === 'failed'\n ? (settled.message ?? 'The connection was not completed. Try connecting again.')\n : null);\n\n // Resume once per outcome, success or failure, so the agent sees what\n // happened in the tool result. A run that is still streaming can't be\n // resumed yet, so an outcome that lands mid-run waits for it to stop.\n useEffect(() => {\n if (readOnly || !paused || alreadyResumed || isRunning) return;\n const outcome = cancelled ? CANCELLED : (createError ?? settled);\n if (!outcome || resumedRef.current === outcome) return;\n resumedRef.current = outcome;\n const resume = connectPromptResumeFor(payload, cancelled, settled, createError);\n if (resume) approveToolcall(toolCallId, resume);\n }, [\n readOnly,\n paused,\n alreadyResumed,\n isRunning,\n cancelled,\n settled,\n createError,\n payload,\n approveToolcall,\n toolCallId,\n ]);\n\n return (\n <section aria-label=\"Connect an account\" className=\"my-2 space-y-3\">\n <DataList columns=\"minmax(0, 1fr)\" fit=\"container\" scrollable={false}>\n <DataList.Subheader className=\"flex items-center justify-between gap-3\">\n <Txt as=\"h4\" variant=\"subheading\" tone=\"ink\">\n Connect an account\n </Txt>\n {canCancel ? (\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label=\"Cancel\"\n tooltip=\"Cancel\"\n onClick={() => {\n cancel();\n setCancelled(true);\n }}\n >\n <IconCrossMedium aria-hidden />\n </Button>\n ) : null}\n </DataList.Subheader>\n {payload.providers.map(provider => {\n const isConnected = provider.connected || connectedProviders.has(provider.id);\n const isPending = pending?.provider === provider.id;\n return (\n <DataList.RowStatic key={provider.id}>\n <DataList.Cell className=\"col-span-full py-2\">\n <div className=\"flex flex-wrap items-center justify-between gap-3\">\n <div className=\"flex min-w-0 flex-1 items-center gap-2\">\n <ProviderLogo logoUrl={provider.logoUrl} />\n <Txt as=\"span\" variant=\"body-sm\" tone=\"ink\" className=\"truncate\">\n {provider.displayName ?? provider.id}\n </Txt>\n </div>\n <div className=\"flex flex-wrap items-center gap-3\">\n {isPending ? (\n <Txt as=\"span\" variant=\"body-sm\" tone=\"muted\" role=\"status\">\n Waiting for authorization…\n </Txt>\n ) : null}\n {isPending && pending?.fallbackUrl ? (\n <a\n href={pending.fallbackUrl}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"text-ui-md underline underline-offset-2\"\n >\n Open the connect window\n </a>\n ) : null}\n {isConnected ? (\n <Txt\n as=\"span\"\n variant=\"body-sm\"\n tone=\"muted\"\n className=\"flex min-w-24 items-center justify-center gap-1\"\n >\n <Icon size=\"sm\">\n <IconCheckmark2Medium aria-hidden />\n </Icon>\n Connected\n </Txt>\n ) : (\n <Button\n variant=\"primary\"\n size=\"sm\"\n className=\"min-w-24\"\n disabled={readOnly || isCreating}\n loading={isPending}\n onClick={() => connect(provider)}\n >\n Connect\n </Button>\n )}\n </div>\n </div>\n </DataList.Cell>\n </DataList.RowStatic>\n );\n })}\n </DataList>\n {cancelled && isRunning && !alreadyResumed ? (\n <Txt as=\"p\" variant=\"body-sm\" tone=\"muted\" role=\"status\">\n Cancelled. The agent continues once its current response finishes.\n </Txt>\n ) : null}\n {errorMessage ? (\n <div role=\"alert\">\n <Notice variant=\"destructive\" title=\"Couldn't connect\">\n <Notice.Message>{errorMessage}</Notice.Message>\n </Notice>\n </div>\n ) : null}\n </section>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA6BA,SAAS,iBAAiB,EACxB,UACA,YACA,QACA,YAGY;CACZ,IAAI,uBAAuB,MAAM,GAAG,OAAO;EAAE,SAAS;EAAQ,QAAQ;CAAM;CAC5E,MAAM,iBAAiB,gBAAgB,UAAU,UAAU,UAAU,CAAC,CAAC,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  cancel: (0, react.useCallback)(() => {
375
375
  headlessRef.current?.close();
376
376
  headlessRef.current = null;
377
+ popupRef.current?.close();
377
378
  popupRef.current = null;
378
379
  pendingRef.current = null;
379
380
  setPending(null);
@@ -1 +1 @@
1
- {"version":3,"file":"use-user-connect.cjs.js","names":["useMastraClient","useCallback","useQuery","useMutation","useQueryClient","useState","useRef","splitHeadlessAuthValues","headlessAuthFields","startHeadlessAuth","HeadlessAuthError","supportsHeadlessAuth","headlessAuthRequiresForm"],"sources":["../../../src/domains/connect/use-user-connect.ts"],"sourcesContent":["import { useMastraClient } from '@mastra/react';\nimport type { QueryClient } from '@tanstack/react-query';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nimport {\n HeadlessAuthError,\n headlessAuthFields,\n headlessAuthRequiresForm,\n splitHeadlessAuthValues,\n startHeadlessAuth,\n supportsHeadlessAuth,\n} from './headless-connect';\nimport type { HeadlessAuthHandle } from './headless-connect';\nimport type {\n UserConnectErrorBody,\n UserConnectLaunchTokenResponse,\n UserConnectProvider,\n UserConnectProvidersResponse,\n UserConnectSessionResponse,\n UserConnectionStatusResponse,\n UserConnectionsResponse,\n} from './types';\n\n/** Default mount prefix of `userConnectRoutes()` on the dev server. */\nexport const CONNECT_BASE_PATH = '/connect';\n\nexport class UserConnectRequestError extends Error {\n status: number;\n code: string | null;\n\n constructor(status: number, code: string | null, message: string) {\n super(message);\n this.name = 'UserConnectRequestError';\n this.status = status;\n this.code = code;\n }\n}\n\ntype ConnectFetch = <T>(path: string, init?: RequestInit) => Promise<T>;\n\n/**\n * Fetches against the dev server's mounted connect routes. Custom `apiRoutes`\n * live outside the `/api` prefix, so this goes around the SDK while reusing\n * its base URL, auth headers, credentials mode, and refresh-aware fetch.\n */\nfunction useConnectFetch(): ConnectFetch {\n const client = useMastraClient();\n const { baseUrl, headers, credentials, fetch: customFetch } = client.options;\n\n return useCallback<ConnectFetch>(\n async (path, init) => {\n const fetchFn = customFetch ?? fetch;\n const response = await fetchFn(`${baseUrl}${CONNECT_BASE_PATH}${path}`, {\n ...init,\n headers: { ...headers, ...init?.headers },\n credentials,\n });\n if (!response.ok) {\n let code: string | null = null;\n let message = `Request failed with status ${response.status}`;\n try {\n const body = (await response.json()) as Partial<UserConnectErrorBody>;\n if (body?.error) {\n code = body.error.code ?? null;\n message = body.error.message ?? message;\n }\n } catch {\n // Non-JSON error body (e.g. a plain 404 for unmounted routes).\n }\n throw new UserConnectRequestError(response.status, code, message);\n }\n if (response.status === 204) return undefined as never;\n return (await response.json()) as never;\n },\n [baseUrl, headers, credentials, customFetch],\n );\n}\n\n/**\n * Resolves a server-relative launch-gate path (returned by the session route\n * as `launchUrl`) against the SDK's base URL for top-level popup navigation.\n * The launch route is authenticated by the browser's session cookie — the\n * server re-verifies that this browser owns the pending session before\n * redirecting into the vendor OAuth flow.\n */\nexport function useConnectLaunchHref(): (launchUrl: string) => string {\n const client = useMastraClient();\n const { baseUrl } = client.options;\n return useCallback((launchUrl: string) => (baseUrl ? `${baseUrl}${launchUrl}` : launchUrl), [baseUrl]);\n}\n\n/**\n * Redeems the launch gate for a headless session token (`Accept:\n * application/json`) instead of following its hosted 302. The gate runs the\n * same ownership assertion in both modes; a `null` token means the server\n * could not extract one and the caller falls back to the hosted popup.\n */\nfunction useRedeemLaunchToken(): (launchUrl: string) => Promise<UserConnectLaunchTokenResponse> {\n const client = useMastraClient();\n const { baseUrl, headers, credentials, fetch: customFetch } = client.options;\n\n return useCallback(\n async launchUrl => {\n const fetchFn = customFetch ?? fetch;\n // `launchUrl` is the full server-relative gate path (it already carries\n // the connect mount prefix), so it resolves against the bare base URL.\n const response = await fetchFn(`${baseUrl ?? ''}${launchUrl}`, {\n headers: { ...headers, accept: 'application/json' },\n credentials,\n });\n if (!response.ok) {\n throw new UserConnectRequestError(response.status, null, `Request failed with status ${response.status}`);\n }\n return (await response.json()) as UserConnectLaunchTokenResponse;\n },\n [baseUrl, headers, credentials, customFetch],\n );\n}\n\nexport type ConnectSurface =\n | { status: 'ready'; providers: UserConnectProvidersResponse['providers'] }\n | { status: 'not-mounted' }\n | { status: 'unauthenticated' };\n\n/**\n * Capability detection for the end-user connect surface: probes\n * `GET /connect/providers` and distinguishes a working surface from the two\n * setup gaps (routes not mounted → 404, no end-user identity → 401).\n */\nexport function useConnectSurface() {\n const connectFetch = useConnectFetch();\n\n return useQuery<ConnectSurface, UserConnectRequestError>({\n queryKey: ['user-connect', 'surface'],\n retry: false,\n queryFn: async () => {\n try {\n const body = await connectFetch<UserConnectProvidersResponse>('/providers');\n return { status: 'ready', providers: body.providers };\n } catch (error) {\n if (error instanceof UserConnectRequestError) {\n if (error.status === 404) return { status: 'not-mounted' };\n if (error.status === 401) return { status: 'unauthenticated' };\n }\n throw error;\n }\n },\n });\n}\n\nconst connectionsQueryKey = ['user-connect', 'connections'] as const;\n\n/**\n * A connection that activates or goes away changes which tools resolve for\n * this user, so the connection list and every agent / tool listing are\n * refetched. The server drops its cached tool snapshot when it reports the\n * change, so the refetch already sees the new tools.\n */\nfunction invalidateAfterConnectionChange(queryClient: QueryClient) {\n return Promise.all(\n [connectionsQueryKey, ['agent'], ['agents'], ['tools']].map(async queryKey => {\n // A first fetch still in flight would otherwise be reused by the\n // invalidation, and its pre-change answer would land as fresh data.\n await queryClient.cancelQueries({ queryKey });\n await queryClient.invalidateQueries({ queryKey });\n }),\n );\n}\n\n/** Lists the caller's visible connections (global + their own). */\nexport function useUserConnections({ enabled }: { enabled: boolean }) {\n const connectFetch = useConnectFetch();\n\n return useQuery<UserConnectionsResponse['connections'], UserConnectRequestError>({\n queryKey: connectionsQueryKey,\n enabled,\n retry: false,\n queryFn: async () => {\n const body = await connectFetch<UserConnectionsResponse>('/connections');\n return body.connections;\n },\n });\n}\n\n/** Creates a connect session for a provider; the caller drives the popup. */\nexport function useCreateConnectSession() {\n const connectFetch = useConnectFetch();\n\n return useMutation<UserConnectSessionResponse, UserConnectRequestError, { provider: string }>({\n mutationFn: ({ provider }) =>\n connectFetch<UserConnectSessionResponse>(`/${encodeURIComponent(provider)}/sessions`, { method: 'POST' }),\n });\n}\n\n/** 2s interval with a 5 minute cap, mirroring the hosted connect page. */\nconst STATUS_POLL_INTERVAL_MS = 2_000;\nconst STATUS_MAX_POLLS = 150;\n\n/**\n * Polls a pending connection until it leaves `pending`. A 404 counts as still\n * pending — the platform row may not be visible until the provider handshake\n * lands. Polling stops once the status settles (or after the 5 minute cap);\n * the connections list is refreshed when it does.\n */\nexport function useConnectionStatus({ connectionId }: { connectionId: string | null }) {\n const connectFetch = useConnectFetch();\n const queryClient = useQueryClient();\n\n return useQuery<UserConnectionStatusResponse, UserConnectRequestError>({\n queryKey: ['user-connect', 'connection-status', connectionId],\n enabled: connectionId !== null,\n retry: false,\n refetchInterval: query => {\n const status = query.state.data?.status;\n if (status !== undefined && status !== 'pending') return false;\n if (query.state.dataUpdateCount >= STATUS_MAX_POLLS) return false;\n return STATUS_POLL_INTERVAL_MS;\n },\n queryFn: async () => {\n let status: UserConnectionStatusResponse;\n try {\n status = await connectFetch<UserConnectionStatusResponse>(\n `/connections/${encodeURIComponent(connectionId ?? '')}/status`,\n );\n } catch (error) {\n if (error instanceof UserConnectRequestError && error.status === 404) {\n return { id: connectionId ?? '', status: 'pending', scope: 'user' };\n }\n throw error;\n }\n if (status.status !== 'pending') {\n void invalidateAfterConnectionChange(queryClient);\n }\n return status;\n },\n });\n}\n\nexport interface PendingConnect {\n provider: string;\n connectionId: string;\n /**\n * `headless` — the Nango SDK drives the provider's own consent popup (or no\n * popup at all for collected credentials). `hosted` — a popup navigated\n * through the launch gate's 302 into the hosted connect page.\n */\n mode: 'headless' | 'hosted';\n /** Shown when the popup was blocked so the user can finish the flow manually. */\n fallbackUrl: string | null;\n}\n\n/**\n * What a caller passes to `connect()`: the provider's id plus the auth shape\n * when known. Callers that only know the id (older payloads) always get the\n * hosted flow.\n */\nexport type ConnectTarget = Pick<UserConnectProvider, 'id'> &\n Partial<Pick<UserConnectProvider, 'authType' | 'authFields'>>;\n\n/**\n * Grace period after the vendor popup closes before an unsettled flow is\n * abandoned — the activation webhook often lands a few seconds after the\n * vendor window closes itself.\n */\nconst POPUP_CLOSE_GRACE_MS = 15_000;\n/** Wall-clock cap matching the status poll's 5 minute budget. */\nconst PENDING_TIMEOUT_MS = STATUS_POLL_INTERVAL_MS * STATUS_MAX_POLLS;\n\nexport interface UsePendingConnectOptions {\n /** Overrides for the abandonment timings (primarily for tests). */\n popupCloseGraceMs?: number;\n pendingTimeoutMs?: number;\n}\n\n/**\n * Outcome of the most recently settled flow: `active` when the connection\n * activated, `failed` for everything else (non-active settle, poll failure,\n * abandoned popup, poll budget). Cleared when a new flow starts.\n */\nexport interface SettledConnect {\n provider: string;\n status: 'active' | 'failed';\n /** Human-readable failure detail (blocked popup, closed window, rejected credentials). */\n message?: string;\n}\n\n/** Window features for the hosted connect popup. */\nconst POPUP_FEATURES = 'popup,width=600,height=720';\n\n/**\n * Drives one add-connection flow end to end. Providers whose auth the browser\n * can complete headlessly go through the launch gate's JSON redemption: the\n * released session token keys the Nango SDK, which opens the provider's own\n * consent popup (or submits collected credentials with no popup). Everything\n * else gets the hosted flow — a popup opened synchronously in the click\n * gesture (so popup blockers allow it) and navigated through the launch\n * gate's 302. Either way the connection status is polled until it settles.\n * The pending state always resolves — on settle, on a poll or auth failure,\n * when the popup closes without settling (after a grace period), or at the\n * poll budget — so the Connect action is never stuck disabled.\n */\nexport function usePendingConnect(options: UsePendingConnectOptions = {}) {\n const { popupCloseGraceMs = POPUP_CLOSE_GRACE_MS, pendingTimeoutMs = PENDING_TIMEOUT_MS } = options;\n const session = useCreateConnectSession();\n const resolveLaunchHref = useConnectLaunchHref();\n const redeemLaunchToken = useRedeemLaunchToken();\n const [pending, setPending] = useState<PendingConnect | null>(null);\n const [settled, setSettled] = useState<SettledConnect | null>(null);\n const [connectedProviders, setConnectedProviders] = useState<ReadonlySet<string>>(new Set());\n const popupRef = useRef<Pick<Window, 'closed'> | null>(null);\n const headlessRef = useRef<HeadlessAuthHandle | null>(null);\n // Mirrors `pending` for async guards (the SDK promise settles outside the\n // render cycle); written directly at every transition so a cancel is never\n // raced by a trailing rejection.\n const pendingRef = useRef<PendingConnect | null>(null);\n const status = useConnectionStatus({ connectionId: pending?.connectionId ?? null });\n\n useEffect(() => {\n pendingRef.current = pending;\n }, [pending]);\n\n // Close the provider popup if the surface unmounts mid-flow.\n useEffect(\n () => () => {\n headlessRef.current?.close();\n headlessRef.current = null;\n },\n [],\n );\n\n // Settle only on a status response for the connection currently pending —\n // a stale result from a previous flow must not clear or mark a newer one.\n const statusData = status.data;\n useEffect(() => {\n if (!pending || statusData === undefined) return;\n if (statusData.id !== pending.connectionId || statusData.status === 'pending') return;\n const { provider } = pending;\n if (statusData.status === 'active') {\n setConnectedProviders(previous => (previous.has(provider) ? previous : new Set([...previous, provider])));\n }\n // The provider window closes itself on active settles; drop the handle so\n // a trailing SDK rejection cannot re-settle this flow.\n headlessRef.current = null;\n pendingRef.current = null;\n setSettled({ provider, status: statusData.status === 'active' ? 'active' : 'failed' });\n setPending(null);\n }, [pending, statusData]);\n\n // A failed poll hands the Connect action back instead of leaving it stuck.\n useEffect(() => {\n if (!status.isError || !pending) return;\n // The ref is cleared before close() so the rejection it triggers no-ops.\n pendingRef.current = null;\n headlessRef.current?.close();\n headlessRef.current = null;\n setSettled({ provider: pending.provider, status: 'failed' });\n setPending(null);\n }, [status.isError, pending]);\n\n // Abandonment: the popup closed without the flow settling (grace period for\n // the trailing webhook) or the poll budget ran out.\n useEffect(() => {\n if (!pending) return;\n const startedAt = Date.now();\n let closedAt: number | null = null;\n const tickMs = Math.min(1_000, popupCloseGraceMs);\n const timer = window.setInterval(() => {\n if (popupRef.current?.closed) closedAt ??= Date.now();\n const abandoned = closedAt !== null && Date.now() - closedAt >= popupCloseGraceMs;\n const timedOut = Date.now() - startedAt >= pendingTimeoutMs;\n if (abandoned || timedOut) {\n // The ref is cleared before close() so the rejection it triggers no-ops.\n pendingRef.current = null;\n headlessRef.current?.close();\n headlessRef.current = null;\n setSettled({ provider: pending.provider, status: 'failed' });\n setPending(null);\n }\n }, tickMs);\n return () => window.clearInterval(timer);\n }, [pending, popupCloseGraceMs, pendingTimeoutMs]);\n\n const beginHeadless = useCallback(\n async (provider: ConnectTarget, created: UserConnectSessionResponse, values?: Record<string, string>) => {\n let sessionToken: string | null = null;\n try {\n sessionToken = (await redeemLaunchToken(created.launchUrl)).sessionToken;\n } catch {\n // Redemption failure (older platform, transient error) is not fatal —\n // the hosted flow below still works through the gate's 302.\n }\n if (!sessionToken) {\n // Opened after an await, so a blocker may stop it; the fallback link\n // in the pending state covers that.\n const launchHref = resolveLaunchHref(created.launchUrl);\n const popup = window.open(launchHref, 'mastra-connect', POPUP_FEATURES);\n popupRef.current = popup;\n const next: PendingConnect = {\n provider: provider.id,\n connectionId: created.connectionId,\n mode: 'hosted',\n fallbackUrl: popup ? null : launchHref,\n };\n pendingRef.current = next;\n setPending(next);\n return;\n }\n\n const split = values ? splitHeadlessAuthValues(headlessAuthFields(provider), values) : {};\n const handle = startHeadlessAuth({\n sessionToken,\n apiBaseUrl: created.apiBaseUrl,\n integrationId: created.integrationId,\n authType: provider.authType,\n credentials: split.credentials,\n params: split.params,\n });\n headlessRef.current = handle;\n const next: PendingConnect = {\n provider: provider.id,\n connectionId: created.connectionId,\n mode: 'headless',\n fallbackUrl: null,\n };\n pendingRef.current = next;\n setPending(next);\n // Success needs no action here — the activation webhook lands on the\n // platform and the status poll settles the flow. Failures settle it now.\n handle.result.catch((error: unknown) => {\n if (pendingRef.current?.connectionId !== created.connectionId) return;\n headlessRef.current = null;\n pendingRef.current = null;\n const message = error instanceof HeadlessAuthError ? error.message : 'Could not authorize this connection.';\n setSettled({ provider: provider.id, status: 'failed', message });\n setPending(null);\n });\n },\n [redeemLaunchToken, resolveLaunchHref],\n );\n\n const connect = useCallback(\n (provider: ConnectTarget, values?: Record<string, string>) => {\n setSettled(null);\n headlessRef.current?.close();\n headlessRef.current = null;\n\n // Headless needs both the capability and the inputs: a caller without a\n // form (no `values`) can only run flows whose fields are all optional —\n // anything else falls back to the hosted page, which renders the form.\n const headless =\n supportsHeadlessAuth(provider.authType, provider.authFields) &&\n (values !== undefined || !headlessAuthRequiresForm(provider));\n // Hosted flows open the popup synchronously in the click gesture so\n // popup blockers allow it; headless flows never navigate to a hosted\n // page, so no window opens here.\n const popup = headless ? null : window.open('', 'mastra-connect', POPUP_FEATURES);\n popupRef.current = popup;\n session.mutate(\n { provider: provider.id },\n {\n onSuccess: created => {\n if (headless) {\n void beginHeadless(provider, created, values);\n return;\n }\n // The popup enters OAuth through the server's launch gate, which\n // verifies this browser owns the pending session before\n // redirecting — the raw vendor URL never reaches the page.\n const launchHref = resolveLaunchHref(created.launchUrl);\n if (popup) {\n popup.location.href = launchHref;\n }\n const next: PendingConnect = {\n provider: provider.id,\n connectionId: created.connectionId,\n mode: 'hosted',\n fallbackUrl: popup ? null : launchHref,\n };\n pendingRef.current = next;\n setPending(next);\n },\n onError: () => {\n popup?.close();\n popupRef.current = null;\n },\n },\n );\n },\n [session, resolveLaunchHref, beginHeadless],\n );\n\n /** Abandons the in-flight flow: closes the provider window, hands the Connect action back. */\n const cancel = useCallback(() => {\n headlessRef.current?.close();\n headlessRef.current = null;\n popupRef.current = null;\n pendingRef.current = null;\n setPending(null);\n setSettled(null);\n }, []);\n\n return {\n pending,\n connect,\n cancel,\n /** Outcome of the most recently settled flow; null while none settled or a flow is in progress. */\n settled,\n /** Providers whose connection settled `active` during this hook's lifetime. */\n connectedProviders,\n isCreating: session.isPending,\n createError: session.isError ? session.error : null,\n };\n}\n\n/** Disconnects one of the caller's own connections. */\nexport function useDisconnectUserConnection() {\n const connectFetch = useConnectFetch();\n const queryClient = useQueryClient();\n\n return useMutation<void, UserConnectRequestError, { connectionId: string }>({\n mutationFn: ({ connectionId }) =>\n connectFetch<void>(`/connections/${encodeURIComponent(connectionId)}`, { method: 'DELETE' }),\n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B,UAAU,SAAS,MAAM;MAC5C;KACF;KAIA,MAAM,aAAa,kBAAkB,QAAQ,SAAS;KACtD,IAAI,OACF,MAAM,SAAS,OAAO;KAExB,MAAM,OAAuB;MAC3B,UAAU,SAAS;MACnB,cAAc,QAAQ;MACtB,MAAM;MACN,aAAa,QAAQ,OAAO;KAC9B;KACA,WAAW,UAAU;KACrB,WAAW,IAAI;IACjB;IACA,eAAe;KACb,OAAO,MAAM;KACb,SAAS,UAAU;IACrB;GACF,CACF;EACF,GACA;GAAC;GAAS;GAAmB;EAAa,CAe1C;EACA,SAAA,GAZaX,MAAAA,YAAAA,OAAkB;GAC/B,YAAY,SAAS,MAAM;GAC3B,YAAY,UAAU;GACtB,SAAS,UAAU;GACnB,WAAW,UAAU;GACrB,WAAW,IAAI;GACf,WAAW,IAAI;EACjB,GAAG,CAAC,CAKF;;EAEA;;EAEA;EACA,YAAY,QAAQ;EACpB,aAAa,QAAQ,UAAU,QAAQ,QAAQ;CACjD;AACF;;AAGA,SAAgB,8BAA8B;CAC5C,MAAM,eAAe,gBAAgB;CACrC,MAAM,eAAA,GAAcG,sBAAAA,eAAAA,CAAe;CAEnC,QAAA,GAAOD,sBAAAA,YAAAA,CAAqE;EAC1E,aAAa,EAAE,mBACb,aAAmB,gBAAgB,mBAAmB,YAAY,KAAK,EAAE,QAAQ,SAAS,CAAC;EAC7F,iBAAiB,gCAAgC,WAAW;CAC9D,CAAC;AACH"}
1
+ {"version":3,"file":"use-user-connect.cjs.js","names":["useMastraClient","useCallback","useQuery","useMutation","useQueryClient","useState","useRef","splitHeadlessAuthValues","headlessAuthFields","startHeadlessAuth","HeadlessAuthError","supportsHeadlessAuth","headlessAuthRequiresForm"],"sources":["../../../src/domains/connect/use-user-connect.ts"],"sourcesContent":["import { useMastraClient } from '@mastra/react';\nimport type { QueryClient } from '@tanstack/react-query';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nimport {\n HeadlessAuthError,\n headlessAuthFields,\n headlessAuthRequiresForm,\n splitHeadlessAuthValues,\n startHeadlessAuth,\n supportsHeadlessAuth,\n} from './headless-connect';\nimport type { HeadlessAuthHandle } from './headless-connect';\nimport type {\n UserConnectErrorBody,\n UserConnectLaunchTokenResponse,\n UserConnectProvider,\n UserConnectProvidersResponse,\n UserConnectSessionResponse,\n UserConnectionStatusResponse,\n UserConnectionsResponse,\n} from './types';\n\n/** Default mount prefix of `userConnectRoutes()` on the dev server. */\nexport const CONNECT_BASE_PATH = '/connect';\n\nexport class UserConnectRequestError extends Error {\n status: number;\n code: string | null;\n\n constructor(status: number, code: string | null, message: string) {\n super(message);\n this.name = 'UserConnectRequestError';\n this.status = status;\n this.code = code;\n }\n}\n\ntype ConnectFetch = <T>(path: string, init?: RequestInit) => Promise<T>;\n\n/**\n * Fetches against the dev server's mounted connect routes. Custom `apiRoutes`\n * live outside the `/api` prefix, so this goes around the SDK while reusing\n * its base URL, auth headers, credentials mode, and refresh-aware fetch.\n */\nfunction useConnectFetch(): ConnectFetch {\n const client = useMastraClient();\n const { baseUrl, headers, credentials, fetch: customFetch } = client.options;\n\n return useCallback<ConnectFetch>(\n async (path, init) => {\n const fetchFn = customFetch ?? fetch;\n const response = await fetchFn(`${baseUrl}${CONNECT_BASE_PATH}${path}`, {\n ...init,\n headers: { ...headers, ...init?.headers },\n credentials,\n });\n if (!response.ok) {\n let code: string | null = null;\n let message = `Request failed with status ${response.status}`;\n try {\n const body = (await response.json()) as Partial<UserConnectErrorBody>;\n if (body?.error) {\n code = body.error.code ?? null;\n message = body.error.message ?? message;\n }\n } catch {\n // Non-JSON error body (e.g. a plain 404 for unmounted routes).\n }\n throw new UserConnectRequestError(response.status, code, message);\n }\n if (response.status === 204) return undefined as never;\n return (await response.json()) as never;\n },\n [baseUrl, headers, credentials, customFetch],\n );\n}\n\n/**\n * Resolves a server-relative launch-gate path (returned by the session route\n * as `launchUrl`) against the SDK's base URL for top-level popup navigation.\n * The launch route is authenticated by the browser's session cookie — the\n * server re-verifies that this browser owns the pending session before\n * redirecting into the vendor OAuth flow.\n */\nexport function useConnectLaunchHref(): (launchUrl: string) => string {\n const client = useMastraClient();\n const { baseUrl } = client.options;\n return useCallback((launchUrl: string) => (baseUrl ? `${baseUrl}${launchUrl}` : launchUrl), [baseUrl]);\n}\n\n/**\n * Redeems the launch gate for a headless session token (`Accept:\n * application/json`) instead of following its hosted 302. The gate runs the\n * same ownership assertion in both modes; a `null` token means the server\n * could not extract one and the caller falls back to the hosted popup.\n */\nfunction useRedeemLaunchToken(): (launchUrl: string) => Promise<UserConnectLaunchTokenResponse> {\n const client = useMastraClient();\n const { baseUrl, headers, credentials, fetch: customFetch } = client.options;\n\n return useCallback(\n async launchUrl => {\n const fetchFn = customFetch ?? fetch;\n // `launchUrl` is the full server-relative gate path (it already carries\n // the connect mount prefix), so it resolves against the bare base URL.\n const response = await fetchFn(`${baseUrl ?? ''}${launchUrl}`, {\n headers: { ...headers, accept: 'application/json' },\n credentials,\n });\n if (!response.ok) {\n throw new UserConnectRequestError(response.status, null, `Request failed with status ${response.status}`);\n }\n return (await response.json()) as UserConnectLaunchTokenResponse;\n },\n [baseUrl, headers, credentials, customFetch],\n );\n}\n\nexport type ConnectSurface =\n | { status: 'ready'; providers: UserConnectProvidersResponse['providers'] }\n | { status: 'not-mounted' }\n | { status: 'unauthenticated' };\n\n/**\n * Capability detection for the end-user connect surface: probes\n * `GET /connect/providers` and distinguishes a working surface from the two\n * setup gaps (routes not mounted → 404, no end-user identity → 401).\n */\nexport function useConnectSurface() {\n const connectFetch = useConnectFetch();\n\n return useQuery<ConnectSurface, UserConnectRequestError>({\n queryKey: ['user-connect', 'surface'],\n retry: false,\n queryFn: async () => {\n try {\n const body = await connectFetch<UserConnectProvidersResponse>('/providers');\n return { status: 'ready', providers: body.providers };\n } catch (error) {\n if (error instanceof UserConnectRequestError) {\n if (error.status === 404) return { status: 'not-mounted' };\n if (error.status === 401) return { status: 'unauthenticated' };\n }\n throw error;\n }\n },\n });\n}\n\nconst connectionsQueryKey = ['user-connect', 'connections'] as const;\n\n/**\n * A connection that activates or goes away changes which tools resolve for\n * this user, so the connection list and every agent / tool listing are\n * refetched. The server drops its cached tool snapshot when it reports the\n * change, so the refetch already sees the new tools.\n */\nfunction invalidateAfterConnectionChange(queryClient: QueryClient) {\n return Promise.all(\n [connectionsQueryKey, ['agent'], ['agents'], ['tools']].map(async queryKey => {\n // A first fetch still in flight would otherwise be reused by the\n // invalidation, and its pre-change answer would land as fresh data.\n await queryClient.cancelQueries({ queryKey });\n await queryClient.invalidateQueries({ queryKey });\n }),\n );\n}\n\n/** Lists the caller's visible connections (global + their own). */\nexport function useUserConnections({ enabled }: { enabled: boolean }) {\n const connectFetch = useConnectFetch();\n\n return useQuery<UserConnectionsResponse['connections'], UserConnectRequestError>({\n queryKey: connectionsQueryKey,\n enabled,\n retry: false,\n queryFn: async () => {\n const body = await connectFetch<UserConnectionsResponse>('/connections');\n return body.connections;\n },\n });\n}\n\n/** Creates a connect session for a provider; the caller drives the popup. */\nexport function useCreateConnectSession() {\n const connectFetch = useConnectFetch();\n\n return useMutation<UserConnectSessionResponse, UserConnectRequestError, { provider: string }>({\n mutationFn: ({ provider }) =>\n connectFetch<UserConnectSessionResponse>(`/${encodeURIComponent(provider)}/sessions`, { method: 'POST' }),\n });\n}\n\n/** 2s interval with a 5 minute cap, mirroring the hosted connect page. */\nconst STATUS_POLL_INTERVAL_MS = 2_000;\nconst STATUS_MAX_POLLS = 150;\n\n/**\n * Polls a pending connection until it leaves `pending`. A 404 counts as still\n * pending — the platform row may not be visible until the provider handshake\n * lands. Polling stops once the status settles (or after the 5 minute cap);\n * the connections list is refreshed when it does.\n */\nexport function useConnectionStatus({ connectionId }: { connectionId: string | null }) {\n const connectFetch = useConnectFetch();\n const queryClient = useQueryClient();\n\n return useQuery<UserConnectionStatusResponse, UserConnectRequestError>({\n queryKey: ['user-connect', 'connection-status', connectionId],\n enabled: connectionId !== null,\n retry: false,\n refetchInterval: query => {\n const status = query.state.data?.status;\n if (status !== undefined && status !== 'pending') return false;\n if (query.state.dataUpdateCount >= STATUS_MAX_POLLS) return false;\n return STATUS_POLL_INTERVAL_MS;\n },\n queryFn: async () => {\n let status: UserConnectionStatusResponse;\n try {\n status = await connectFetch<UserConnectionStatusResponse>(\n `/connections/${encodeURIComponent(connectionId ?? '')}/status`,\n );\n } catch (error) {\n if (error instanceof UserConnectRequestError && error.status === 404) {\n return { id: connectionId ?? '', status: 'pending', scope: 'user' };\n }\n throw error;\n }\n if (status.status !== 'pending') {\n void invalidateAfterConnectionChange(queryClient);\n }\n return status;\n },\n });\n}\n\nexport interface PendingConnect {\n provider: string;\n connectionId: string;\n /**\n * `headless` — the Nango SDK drives the provider's own consent popup (or no\n * popup at all for collected credentials). `hosted` — a popup navigated\n * through the launch gate's 302 into the hosted connect page.\n */\n mode: 'headless' | 'hosted';\n /** Shown when the popup was blocked so the user can finish the flow manually. */\n fallbackUrl: string | null;\n}\n\n/**\n * What a caller passes to `connect()`: the provider's id plus the auth shape\n * when known. Callers that only know the id (older payloads) always get the\n * hosted flow.\n */\nexport type ConnectTarget = Pick<UserConnectProvider, 'id'> &\n Partial<Pick<UserConnectProvider, 'authType' | 'authFields'>>;\n\n/**\n * Grace period after the vendor popup closes before an unsettled flow is\n * abandoned — the activation webhook often lands a few seconds after the\n * vendor window closes itself.\n */\nconst POPUP_CLOSE_GRACE_MS = 15_000;\n/** Wall-clock cap matching the status poll's 5 minute budget. */\nconst PENDING_TIMEOUT_MS = STATUS_POLL_INTERVAL_MS * STATUS_MAX_POLLS;\n\nexport interface UsePendingConnectOptions {\n /** Overrides for the abandonment timings (primarily for tests). */\n popupCloseGraceMs?: number;\n pendingTimeoutMs?: number;\n}\n\n/**\n * Outcome of the most recently settled flow: `active` when the connection\n * activated, `failed` for everything else (non-active settle, poll failure,\n * abandoned popup, poll budget). Cleared when a new flow starts.\n */\nexport interface SettledConnect {\n provider: string;\n status: 'active' | 'failed';\n /** Human-readable failure detail (blocked popup, closed window, rejected credentials). */\n message?: string;\n}\n\n/** Window features for the hosted connect popup. */\nconst POPUP_FEATURES = 'popup,width=600,height=720';\n\n/**\n * Drives one add-connection flow end to end. Providers whose auth the browser\n * can complete headlessly go through the launch gate's JSON redemption: the\n * released session token keys the Nango SDK, which opens the provider's own\n * consent popup (or submits collected credentials with no popup). Everything\n * else gets the hosted flow — a popup opened synchronously in the click\n * gesture (so popup blockers allow it) and navigated through the launch\n * gate's 302. Either way the connection status is polled until it settles.\n * The pending state always resolves — on settle, on a poll or auth failure,\n * when the popup closes without settling (after a grace period), or at the\n * poll budget — so the Connect action is never stuck disabled.\n */\nexport function usePendingConnect(options: UsePendingConnectOptions = {}) {\n const { popupCloseGraceMs = POPUP_CLOSE_GRACE_MS, pendingTimeoutMs = PENDING_TIMEOUT_MS } = options;\n const session = useCreateConnectSession();\n const resolveLaunchHref = useConnectLaunchHref();\n const redeemLaunchToken = useRedeemLaunchToken();\n const [pending, setPending] = useState<PendingConnect | null>(null);\n const [settled, setSettled] = useState<SettledConnect | null>(null);\n const [connectedProviders, setConnectedProviders] = useState<ReadonlySet<string>>(new Set());\n const popupRef = useRef<Pick<Window, 'closed' | 'close'> | null>(null);\n const headlessRef = useRef<HeadlessAuthHandle | null>(null);\n // Mirrors `pending` for async guards (the SDK promise settles outside the\n // render cycle); written directly at every transition so a cancel is never\n // raced by a trailing rejection.\n const pendingRef = useRef<PendingConnect | null>(null);\n const status = useConnectionStatus({ connectionId: pending?.connectionId ?? null });\n\n useEffect(() => {\n pendingRef.current = pending;\n }, [pending]);\n\n // Close the provider popup if the surface unmounts mid-flow.\n useEffect(\n () => () => {\n headlessRef.current?.close();\n headlessRef.current = null;\n },\n [],\n );\n\n // Settle only on a status response for the connection currently pending —\n // a stale result from a previous flow must not clear or mark a newer one.\n const statusData = status.data;\n useEffect(() => {\n if (!pending || statusData === undefined) return;\n if (statusData.id !== pending.connectionId || statusData.status === 'pending') return;\n const { provider } = pending;\n if (statusData.status === 'active') {\n setConnectedProviders(previous => (previous.has(provider) ? previous : new Set([...previous, provider])));\n }\n // The provider window closes itself on active settles; drop the handle so\n // a trailing SDK rejection cannot re-settle this flow.\n headlessRef.current = null;\n pendingRef.current = null;\n setSettled({ provider, status: statusData.status === 'active' ? 'active' : 'failed' });\n setPending(null);\n }, [pending, statusData]);\n\n // A failed poll hands the Connect action back instead of leaving it stuck.\n useEffect(() => {\n if (!status.isError || !pending) return;\n // The ref is cleared before close() so the rejection it triggers no-ops.\n pendingRef.current = null;\n headlessRef.current?.close();\n headlessRef.current = null;\n setSettled({ provider: pending.provider, status: 'failed' });\n setPending(null);\n }, [status.isError, pending]);\n\n // Abandonment: the popup closed without the flow settling (grace period for\n // the trailing webhook) or the poll budget ran out.\n useEffect(() => {\n if (!pending) return;\n const startedAt = Date.now();\n let closedAt: number | null = null;\n const tickMs = Math.min(1_000, popupCloseGraceMs);\n const timer = window.setInterval(() => {\n if (popupRef.current?.closed) closedAt ??= Date.now();\n const abandoned = closedAt !== null && Date.now() - closedAt >= popupCloseGraceMs;\n const timedOut = Date.now() - startedAt >= pendingTimeoutMs;\n if (abandoned || timedOut) {\n // The ref is cleared before close() so the rejection it triggers no-ops.\n pendingRef.current = null;\n headlessRef.current?.close();\n headlessRef.current = null;\n setSettled({ provider: pending.provider, status: 'failed' });\n setPending(null);\n }\n }, tickMs);\n return () => window.clearInterval(timer);\n }, [pending, popupCloseGraceMs, pendingTimeoutMs]);\n\n const beginHeadless = useCallback(\n async (provider: ConnectTarget, created: UserConnectSessionResponse, values?: Record<string, string>) => {\n let sessionToken: string | null = null;\n try {\n sessionToken = (await redeemLaunchToken(created.launchUrl)).sessionToken;\n } catch {\n // Redemption failure (older platform, transient error) is not fatal —\n // the hosted flow below still works through the gate's 302.\n }\n if (!sessionToken) {\n // Opened after an await, so a blocker may stop it; the fallback link\n // in the pending state covers that.\n const launchHref = resolveLaunchHref(created.launchUrl);\n const popup = window.open(launchHref, 'mastra-connect', POPUP_FEATURES);\n popupRef.current = popup;\n const next: PendingConnect = {\n provider: provider.id,\n connectionId: created.connectionId,\n mode: 'hosted',\n fallbackUrl: popup ? null : launchHref,\n };\n pendingRef.current = next;\n setPending(next);\n return;\n }\n\n const split = values ? splitHeadlessAuthValues(headlessAuthFields(provider), values) : {};\n const handle = startHeadlessAuth({\n sessionToken,\n apiBaseUrl: created.apiBaseUrl,\n integrationId: created.integrationId,\n authType: provider.authType,\n credentials: split.credentials,\n params: split.params,\n });\n headlessRef.current = handle;\n const next: PendingConnect = {\n provider: provider.id,\n connectionId: created.connectionId,\n mode: 'headless',\n fallbackUrl: null,\n };\n pendingRef.current = next;\n setPending(next);\n // Success needs no action here — the activation webhook lands on the\n // platform and the status poll settles the flow. Failures settle it now.\n handle.result.catch((error: unknown) => {\n if (pendingRef.current?.connectionId !== created.connectionId) return;\n headlessRef.current = null;\n pendingRef.current = null;\n const message = error instanceof HeadlessAuthError ? error.message : 'Could not authorize this connection.';\n setSettled({ provider: provider.id, status: 'failed', message });\n setPending(null);\n });\n },\n [redeemLaunchToken, resolveLaunchHref],\n );\n\n const connect = useCallback(\n (provider: ConnectTarget, values?: Record<string, string>) => {\n setSettled(null);\n headlessRef.current?.close();\n headlessRef.current = null;\n\n // Headless needs both the capability and the inputs: a caller without a\n // form (no `values`) can only run flows whose fields are all optional —\n // anything else falls back to the hosted page, which renders the form.\n const headless =\n supportsHeadlessAuth(provider.authType, provider.authFields) &&\n (values !== undefined || !headlessAuthRequiresForm(provider));\n // Hosted flows open the popup synchronously in the click gesture so\n // popup blockers allow it; headless flows never navigate to a hosted\n // page, so no window opens here.\n const popup = headless ? null : window.open('', 'mastra-connect', POPUP_FEATURES);\n popupRef.current = popup;\n session.mutate(\n { provider: provider.id },\n {\n onSuccess: created => {\n if (headless) {\n void beginHeadless(provider, created, values);\n return;\n }\n // The popup enters OAuth through the server's launch gate, which\n // verifies this browser owns the pending session before\n // redirecting — the raw vendor URL never reaches the page.\n const launchHref = resolveLaunchHref(created.launchUrl);\n if (popup) {\n popup.location.href = launchHref;\n }\n const next: PendingConnect = {\n provider: provider.id,\n connectionId: created.connectionId,\n mode: 'hosted',\n fallbackUrl: popup ? null : launchHref,\n };\n pendingRef.current = next;\n setPending(next);\n },\n onError: () => {\n popup?.close();\n popupRef.current = null;\n },\n },\n );\n },\n [session, resolveLaunchHref, beginHeadless],\n );\n\n /** Abandons the in-flight flow: closes the provider window, hands the Connect action back. */\n const cancel = useCallback(() => {\n headlessRef.current?.close();\n headlessRef.current = null;\n popupRef.current?.close();\n popupRef.current = null;\n pendingRef.current = null;\n setPending(null);\n setSettled(null);\n }, []);\n\n return {\n pending,\n connect,\n cancel,\n /** Outcome of the most recently settled flow; null while none settled or a flow is in progress. */\n settled,\n /** Providers whose connection settled `active` during this hook's lifetime. */\n connectedProviders,\n isCreating: session.isPending,\n createError: session.isError ? session.error : null,\n };\n}\n\n/** Disconnects one of the caller's own connections. */\nexport function useDisconnectUserConnection() {\n const connectFetch = useConnectFetch();\n const queryClient = useQueryClient();\n\n return useMutation<void, UserConnectRequestError, { connectionId: string }>({\n mutationFn: ({ connectionId }) =>\n connectFetch<void>(`/connections/${encodeURIComponent(connectionId)}`, { method: 'DELETE' }),\n onSuccess: () => invalidateAfterConnectionChange(queryClient),\n });\n}\n"],"mappings":";;;;;;;AAyBA,IAAa,oBAAoB;AAEjC,IAAa,0BAAb,cAA6C,MAAM;CACjD;CACA;CAEA,YAAY,QAAgB,MAAqB,SAAiB;EAChE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,OAAO;CACd;AACF;;;;;;AASA,SAAS,kBAAgC;CAEvC,MAAM,EAAE,SAAS,SAAS,aAAa,OAAO,iBAAA,GAD/BA,cAAAA,gBAAAA,CAC+C,CAAA,CAAO;CAErE,QAAA,GAAOC,MAAAA,YAAAA,CACL,OAAO,MAAM,SAAS;EAEpB,MAAM,WAAW,OADD,eAAe,MAAA,CACA,GAAG,UAAU,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AAS,UAAU;GACnB,WAAW,UAAU;GACrB,WAAW,IAAI;GACf,WAAW,IAAI;EACjB,GAAG,CAAC,CAKF;;EAEA;;EAEA;EACA,YAAY,QAAQ;EACpB,aAAa,QAAQ,UAAU,QAAQ,QAAQ;CACjD;AACF;;AAGA,SAAgB,8BAA8B;CAC5C,MAAM,eAAe,gBAAgB;CACrC,MAAM,eAAA,GAAcG,sBAAAA,eAAAA,CAAe;CAEnC,QAAA,GAAOD,sBAAAA,YAAAA,CAAqE;EAC1E,aAAa,EAAE,mBACb,aAAmB,gBAAgB,mBAAmB,YAAY,KAAK,EAAE,QAAQ,SAAS,CAAC;EAC7F,iBAAiB,gCAAgC,WAAW;CAC9D,CAAC;AACH"}
@@ -373,6 +373,7 @@ function usePendingConnect(options = {}) {
373
373
  cancel: useCallback(() => {
374
374
  headlessRef.current?.close();
375
375
  headlessRef.current = null;
376
+ popupRef.current?.close();
376
377
  popupRef.current = null;
377
378
  pendingRef.current = null;
378
379
  setPending(null);
@@ -1 +1 @@
1
- {"version":3,"file":"use-user-connect.es.js","names":[],"sources":["../../../src/domains/connect/use-user-connect.ts"],"sourcesContent":["import { useMastraClient } from '@mastra/react';\nimport type { QueryClient } from '@tanstack/react-query';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nimport {\n HeadlessAuthError,\n headlessAuthFields,\n headlessAuthRequiresForm,\n splitHeadlessAuthValues,\n startHeadlessAuth,\n supportsHeadlessAuth,\n} from './headless-connect';\nimport type { HeadlessAuthHandle } from './headless-connect';\nimport type {\n UserConnectErrorBody,\n UserConnectLaunchTokenResponse,\n UserConnectProvider,\n UserConnectProvidersResponse,\n UserConnectSessionResponse,\n UserConnectionStatusResponse,\n UserConnectionsResponse,\n} from './types';\n\n/** Default mount prefix of `userConnectRoutes()` on the dev server. */\nexport const CONNECT_BASE_PATH = '/connect';\n\nexport class UserConnectRequestError extends Error {\n status: number;\n code: string | null;\n\n constructor(status: number, code: string | null, message: string) {\n super(message);\n this.name = 'UserConnectRequestError';\n this.status = status;\n this.code = code;\n }\n}\n\ntype ConnectFetch = <T>(path: string, init?: RequestInit) => Promise<T>;\n\n/**\n * Fetches against the dev server's mounted connect routes. Custom `apiRoutes`\n * live outside the `/api` prefix, so this goes around the SDK while reusing\n * its base URL, auth headers, credentials mode, and refresh-aware fetch.\n */\nfunction useConnectFetch(): ConnectFetch {\n const client = useMastraClient();\n const { baseUrl, headers, credentials, fetch: customFetch } = client.options;\n\n return useCallback<ConnectFetch>(\n async (path, init) => {\n const fetchFn = customFetch ?? fetch;\n const response = await fetchFn(`${baseUrl}${CONNECT_BASE_PATH}${path}`, {\n ...init,\n headers: { ...headers, ...init?.headers },\n credentials,\n });\n if (!response.ok) {\n let code: string | null = null;\n let message = `Request failed with status ${response.status}`;\n try {\n const body = (await response.json()) as Partial<UserConnectErrorBody>;\n if (body?.error) {\n code = body.error.code ?? null;\n message = body.error.message ?? message;\n }\n } catch {\n // Non-JSON error body (e.g. a plain 404 for unmounted routes).\n }\n throw new UserConnectRequestError(response.status, code, message);\n }\n if (response.status === 204) return undefined as never;\n return (await response.json()) as never;\n },\n [baseUrl, headers, credentials, customFetch],\n );\n}\n\n/**\n * Resolves a server-relative launch-gate path (returned by the session route\n * as `launchUrl`) against the SDK's base URL for top-level popup navigation.\n * The launch route is authenticated by the browser's session cookie — the\n * server re-verifies that this browser owns the pending session before\n * redirecting into the vendor OAuth flow.\n */\nexport function useConnectLaunchHref(): (launchUrl: string) => string {\n const client = useMastraClient();\n const { baseUrl } = client.options;\n return useCallback((launchUrl: string) => (baseUrl ? `${baseUrl}${launchUrl}` : launchUrl), [baseUrl]);\n}\n\n/**\n * Redeems the launch gate for a headless session token (`Accept:\n * application/json`) instead of following its hosted 302. The gate runs the\n * same ownership assertion in both modes; a `null` token means the server\n * could not extract one and the caller falls back to the hosted popup.\n */\nfunction useRedeemLaunchToken(): (launchUrl: string) => Promise<UserConnectLaunchTokenResponse> {\n const client = useMastraClient();\n const { baseUrl, headers, credentials, fetch: customFetch } = client.options;\n\n return useCallback(\n async launchUrl => {\n const fetchFn = customFetch ?? fetch;\n // `launchUrl` is the full server-relative gate path (it already carries\n // the connect mount prefix), so it resolves against the bare base URL.\n const response = await fetchFn(`${baseUrl ?? ''}${launchUrl}`, {\n headers: { ...headers, accept: 'application/json' },\n credentials,\n });\n if (!response.ok) {\n throw new UserConnectRequestError(response.status, null, `Request failed with status ${response.status}`);\n }\n return (await response.json()) as UserConnectLaunchTokenResponse;\n },\n [baseUrl, headers, credentials, customFetch],\n );\n}\n\nexport type ConnectSurface =\n | { status: 'ready'; providers: UserConnectProvidersResponse['providers'] }\n | { status: 'not-mounted' }\n | { status: 'unauthenticated' };\n\n/**\n * Capability detection for the end-user connect surface: probes\n * `GET /connect/providers` and distinguishes a working surface from the two\n * setup gaps (routes not mounted → 404, no end-user identity → 401).\n */\nexport function useConnectSurface() {\n const connectFetch = useConnectFetch();\n\n return useQuery<ConnectSurface, UserConnectRequestError>({\n queryKey: ['user-connect', 'surface'],\n retry: false,\n queryFn: async () => {\n try {\n const body = await connectFetch<UserConnectProvidersResponse>('/providers');\n return { status: 'ready', providers: body.providers };\n } catch (error) {\n if (error instanceof UserConnectRequestError) {\n if (error.status === 404) return { status: 'not-mounted' };\n if (error.status === 401) return { status: 'unauthenticated' };\n }\n throw error;\n }\n },\n });\n}\n\nconst connectionsQueryKey = ['user-connect', 'connections'] as const;\n\n/**\n * A connection that activates or goes away changes which tools resolve for\n * this user, so the connection list and every agent / tool listing are\n * refetched. The server drops its cached tool snapshot when it reports the\n * change, so the refetch already sees the new tools.\n */\nfunction invalidateAfterConnectionChange(queryClient: QueryClient) {\n return Promise.all(\n [connectionsQueryKey, ['agent'], ['agents'], ['tools']].map(async queryKey => {\n // A first fetch still in flight would otherwise be reused by the\n // invalidation, and its pre-change answer would land as fresh data.\n await queryClient.cancelQueries({ queryKey });\n await queryClient.invalidateQueries({ queryKey });\n }),\n );\n}\n\n/** Lists the caller's visible connections (global + their own). */\nexport function useUserConnections({ enabled }: { enabled: boolean }) {\n const connectFetch = useConnectFetch();\n\n return useQuery<UserConnectionsResponse['connections'], UserConnectRequestError>({\n queryKey: connectionsQueryKey,\n enabled,\n retry: false,\n queryFn: async () => {\n const body = await connectFetch<UserConnectionsResponse>('/connections');\n return body.connections;\n },\n });\n}\n\n/** Creates a connect session for a provider; the caller drives the popup. */\nexport function useCreateConnectSession() {\n const connectFetch = useConnectFetch();\n\n return useMutation<UserConnectSessionResponse, UserConnectRequestError, { provider: string }>({\n mutationFn: ({ provider }) =>\n connectFetch<UserConnectSessionResponse>(`/${encodeURIComponent(provider)}/sessions`, { method: 'POST' }),\n });\n}\n\n/** 2s interval with a 5 minute cap, mirroring the hosted connect page. */\nconst STATUS_POLL_INTERVAL_MS = 2_000;\nconst STATUS_MAX_POLLS = 150;\n\n/**\n * Polls a pending connection until it leaves `pending`. A 404 counts as still\n * pending — the platform row may not be visible until the provider handshake\n * lands. Polling stops once the status settles (or after the 5 minute cap);\n * the connections list is refreshed when it does.\n */\nexport function useConnectionStatus({ connectionId }: { connectionId: string | null }) {\n const connectFetch = useConnectFetch();\n const queryClient = useQueryClient();\n\n return useQuery<UserConnectionStatusResponse, UserConnectRequestError>({\n queryKey: ['user-connect', 'connection-status', connectionId],\n enabled: connectionId !== null,\n retry: false,\n refetchInterval: query => {\n const status = query.state.data?.status;\n if (status !== undefined && status !== 'pending') return false;\n if (query.state.dataUpdateCount >= STATUS_MAX_POLLS) return false;\n return STATUS_POLL_INTERVAL_MS;\n },\n queryFn: async () => {\n let status: UserConnectionStatusResponse;\n try {\n status = await connectFetch<UserConnectionStatusResponse>(\n `/connections/${encodeURIComponent(connectionId ?? '')}/status`,\n );\n } catch (error) {\n if (error instanceof UserConnectRequestError && error.status === 404) {\n return { id: connectionId ?? '', status: 'pending', scope: 'user' };\n }\n throw error;\n }\n if (status.status !== 'pending') {\n void invalidateAfterConnectionChange(queryClient);\n }\n return status;\n },\n });\n}\n\nexport interface PendingConnect {\n provider: string;\n connectionId: string;\n /**\n * `headless` — the Nango SDK drives the provider's own consent popup (or no\n * popup at all for collected credentials). `hosted` — a popup navigated\n * through the launch gate's 302 into the hosted connect page.\n */\n mode: 'headless' | 'hosted';\n /** Shown when the popup was blocked so the user can finish the flow manually. */\n fallbackUrl: string | null;\n}\n\n/**\n * What a caller passes to `connect()`: the provider's id plus the auth shape\n * when known. Callers that only know the id (older payloads) always get the\n * hosted flow.\n */\nexport type ConnectTarget = Pick<UserConnectProvider, 'id'> &\n Partial<Pick<UserConnectProvider, 'authType' | 'authFields'>>;\n\n/**\n * Grace period after the vendor popup closes before an unsettled flow is\n * abandoned — the activation webhook often lands a few seconds after the\n * vendor window closes itself.\n */\nconst POPUP_CLOSE_GRACE_MS = 15_000;\n/** Wall-clock cap matching the status poll's 5 minute budget. */\nconst PENDING_TIMEOUT_MS = STATUS_POLL_INTERVAL_MS * STATUS_MAX_POLLS;\n\nexport interface UsePendingConnectOptions {\n /** Overrides for the abandonment timings (primarily for tests). */\n popupCloseGraceMs?: number;\n pendingTimeoutMs?: number;\n}\n\n/**\n * Outcome of the most recently settled flow: `active` when the connection\n * activated, `failed` for everything else (non-active settle, poll failure,\n * abandoned popup, poll budget). Cleared when a new flow starts.\n */\nexport interface SettledConnect {\n provider: string;\n status: 'active' | 'failed';\n /** Human-readable failure detail (blocked popup, closed window, rejected credentials). */\n message?: string;\n}\n\n/** Window features for the hosted connect popup. */\nconst POPUP_FEATURES = 'popup,width=600,height=720';\n\n/**\n * Drives one add-connection flow end to end. Providers whose auth the browser\n * can complete headlessly go through the launch gate's JSON redemption: the\n * released session token keys the Nango SDK, which opens the provider's own\n * consent popup (or submits collected credentials with no popup). Everything\n * else gets the hosted flow — a popup opened synchronously in the click\n * gesture (so popup blockers allow it) and navigated through the launch\n * gate's 302. Either way the connection status is polled until it settles.\n * The pending state always resolves — on settle, on a poll or auth failure,\n * when the popup closes without settling (after a grace period), or at the\n * poll budget — so the Connect action is never stuck disabled.\n */\nexport function usePendingConnect(options: UsePendingConnectOptions = {}) {\n const { popupCloseGraceMs = POPUP_CLOSE_GRACE_MS, pendingTimeoutMs = PENDING_TIMEOUT_MS } = options;\n const session = useCreateConnectSession();\n const resolveLaunchHref = useConnectLaunchHref();\n const redeemLaunchToken = useRedeemLaunchToken();\n const [pending, setPending] = useState<PendingConnect | null>(null);\n const [settled, setSettled] = useState<SettledConnect | null>(null);\n const [connectedProviders, setConnectedProviders] = useState<ReadonlySet<string>>(new Set());\n const popupRef = useRef<Pick<Window, 'closed'> | null>(null);\n const headlessRef = useRef<HeadlessAuthHandle | null>(null);\n // Mirrors `pending` for async guards (the SDK promise settles outside the\n // render cycle); written directly at every transition so a cancel is never\n // raced by a trailing rejection.\n const pendingRef = useRef<PendingConnect | null>(null);\n const status = useConnectionStatus({ connectionId: pending?.connectionId ?? null });\n\n useEffect(() => {\n pendingRef.current = pending;\n }, [pending]);\n\n // Close the provider popup if the surface unmounts mid-flow.\n useEffect(\n () => () => {\n headlessRef.current?.close();\n headlessRef.current = null;\n },\n [],\n );\n\n // Settle only on a status response for the connection currently pending —\n // a stale result from a previous flow must not clear or mark a newer one.\n const statusData = status.data;\n useEffect(() => {\n if (!pending || statusData === undefined) return;\n if (statusData.id !== pending.connectionId || statusData.status === 'pending') return;\n const { provider } = pending;\n if (statusData.status === 'active') {\n setConnectedProviders(previous => (previous.has(provider) ? previous : new Set([...previous, provider])));\n }\n // The provider window closes itself on active settles; drop the handle so\n // a trailing SDK rejection cannot re-settle this flow.\n headlessRef.current = null;\n pendingRef.current = null;\n setSettled({ provider, status: statusData.status === 'active' ? 'active' : 'failed' });\n setPending(null);\n }, [pending, statusData]);\n\n // A failed poll hands the Connect action back instead of leaving it stuck.\n useEffect(() => {\n if (!status.isError || !pending) return;\n // The ref is cleared before close() so the rejection it triggers no-ops.\n pendingRef.current = null;\n headlessRef.current?.close();\n headlessRef.current = null;\n setSettled({ provider: pending.provider, status: 'failed' });\n setPending(null);\n }, [status.isError, pending]);\n\n // Abandonment: the popup closed without the flow settling (grace period for\n // the trailing webhook) or the poll budget ran out.\n useEffect(() => {\n if (!pending) return;\n const startedAt = Date.now();\n let closedAt: number | null = null;\n const tickMs = Math.min(1_000, popupCloseGraceMs);\n const timer = window.setInterval(() => {\n if (popupRef.current?.closed) closedAt ??= Date.now();\n const abandoned = closedAt !== null && Date.now() - closedAt >= popupCloseGraceMs;\n const timedOut = Date.now() - startedAt >= pendingTimeoutMs;\n if (abandoned || timedOut) {\n // The ref is cleared before close() so the rejection it triggers no-ops.\n pendingRef.current = null;\n headlessRef.current?.close();\n headlessRef.current = null;\n setSettled({ provider: pending.provider, status: 'failed' });\n setPending(null);\n }\n }, tickMs);\n return () => window.clearInterval(timer);\n }, [pending, popupCloseGraceMs, pendingTimeoutMs]);\n\n const beginHeadless = useCallback(\n async (provider: ConnectTarget, created: UserConnectSessionResponse, values?: Record<string, string>) => {\n let sessionToken: string | null = null;\n try {\n sessionToken = (await redeemLaunchToken(created.launchUrl)).sessionToken;\n } catch {\n // Redemption failure (older platform, transient error) is not fatal —\n // the hosted flow below still works through the gate's 302.\n }\n if (!sessionToken) {\n // Opened after an await, so a blocker may stop it; the fallback link\n // in the pending state covers that.\n const launchHref = resolveLaunchHref(created.launchUrl);\n const popup = window.open(launchHref, 'mastra-connect', POPUP_FEATURES);\n popupRef.current = popup;\n const next: PendingConnect = {\n provider: provider.id,\n connectionId: created.connectionId,\n mode: 'hosted',\n fallbackUrl: popup ? null : launchHref,\n };\n pendingRef.current = next;\n setPending(next);\n return;\n }\n\n const split = values ? splitHeadlessAuthValues(headlessAuthFields(provider), values) : {};\n const handle = startHeadlessAuth({\n sessionToken,\n apiBaseUrl: created.apiBaseUrl,\n integrationId: created.integrationId,\n authType: provider.authType,\n credentials: split.credentials,\n params: split.params,\n });\n headlessRef.current = handle;\n const next: PendingConnect = {\n provider: provider.id,\n connectionId: created.connectionId,\n mode: 'headless',\n fallbackUrl: null,\n };\n pendingRef.current = next;\n setPending(next);\n // Success needs no action here — the activation webhook lands on the\n // platform and the status poll settles the flow. Failures settle it now.\n handle.result.catch((error: unknown) => {\n if (pendingRef.current?.connectionId !== created.connectionId) return;\n headlessRef.current = null;\n pendingRef.current = null;\n const message = error instanceof HeadlessAuthError ? error.message : 'Could not authorize this connection.';\n setSettled({ provider: provider.id, status: 'failed', message });\n setPending(null);\n });\n },\n [redeemLaunchToken, resolveLaunchHref],\n );\n\n const connect = useCallback(\n (provider: ConnectTarget, values?: Record<string, string>) => {\n setSettled(null);\n headlessRef.current?.close();\n headlessRef.current = null;\n\n // Headless needs both the capability and the inputs: a caller without a\n // form (no `values`) can only run flows whose fields are all optional —\n // anything else falls back to the hosted page, which renders the form.\n const headless =\n supportsHeadlessAuth(provider.authType, provider.authFields) &&\n (values !== undefined || !headlessAuthRequiresForm(provider));\n // Hosted flows open the popup synchronously in the click gesture so\n // popup blockers allow it; headless flows never navigate to a hosted\n // page, so no window opens here.\n const popup = headless ? null : window.open('', 'mastra-connect', POPUP_FEATURES);\n popupRef.current = popup;\n session.mutate(\n { provider: provider.id },\n {\n onSuccess: created => {\n if (headless) {\n void beginHeadless(provider, created, values);\n return;\n }\n // The popup enters OAuth through the server's launch gate, which\n // verifies this browser owns the pending session before\n // redirecting — the raw vendor URL never reaches the page.\n const launchHref = resolveLaunchHref(created.launchUrl);\n if (popup) {\n popup.location.href = launchHref;\n }\n const next: PendingConnect = {\n provider: provider.id,\n connectionId: created.connectionId,\n mode: 'hosted',\n fallbackUrl: popup ? null : launchHref,\n };\n pendingRef.current = next;\n setPending(next);\n },\n onError: () => {\n popup?.close();\n popupRef.current = null;\n },\n },\n );\n },\n [session, resolveLaunchHref, beginHeadless],\n );\n\n /** Abandons the in-flight flow: closes the provider window, hands the Connect action back. */\n const cancel = useCallback(() => {\n headlessRef.current?.close();\n headlessRef.current = null;\n popupRef.current = null;\n pendingRef.current = null;\n setPending(null);\n setSettled(null);\n }, []);\n\n return {\n pending,\n connect,\n cancel,\n /** Outcome of the most recently settled flow; null while none settled or a flow is in progress. */\n settled,\n /** Providers whose connection settled `active` during this hook's lifetime. */\n connectedProviders,\n isCreating: session.isPending,\n createError: session.isError ? session.error : null,\n };\n}\n\n/** Disconnects one of the caller's own connections. */\nexport function useDisconnectUserConnection() {\n const connectFetch = useConnectFetch();\n const queryClient = useQueryClient();\n\n return useMutation<void, UserConnectRequestError, { connectionId: string }>({\n mutationFn: ({ connectionId }) =>\n connectFetch<void>(`/connections/${encodeURIComponent(connectionId)}`, { method: 'DELETE' }),\n onSuccess: () => invalidateAfterConnectionChange(queryClient),\n });\n}\n"],"mappings":";;;;;;AAyBA,IAAa,oBAAoB;AAEjC,IAAa,0BAAb,cAA6C,MAAM;CACjD;CACA;CAEA,YAAY,QAAgB,MAAqB,SAAiB;EAChE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,OAAO;CACd;AACF;;;;;;AASA,SAAS,kBAAgC;CAEvC,MAAM,EAAE,SAAS,SAAS,aAAa,OAAO,gBAD/B,gBAC+C,CAAA,CAAO;CAErE,OAAO,YACL,OAAO,MAAM,SAAS;EAEpB,MAAM,WAAW,OADD,eAAe,MAAA,CACA,GAAG,UAAU,oBAAoB,QAAQ;GACtE,GAAG;GACH,SAAS;IAAE,GAAG;IAAS,GAAG,MAAM;GAAQ;GACxC;EACF,CAAC;EACD,IAAI,CAAC,SAAS,IAAI;GAChB,IAAI,OAAsB;GAC1B,IAAI,UAAU,8BAA8B,SAAS;GACrD,IAAI;IACF,MAAM,OAAQ,MAAM,SAAS,KAAK;IAClC,IAAI,MAAM,OAAO;KACf,OAAO,KAAK,MAAM,QAAQ;KAC1B,UAAU,KAAK,MAAM,WAAW;IAClC;GACF,QAAQ,CAER;GACA,MAAM,IAAI,wBAAwB,SAAS,QAAQ,MAAM,OAAO;EAClE;EACA,IAAI,SAAS,WAAW,KAAK,OAAO,KAAA;EACpC,OAAQ,MAAM,SAA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ACrB,WAAW,IAAI;IACjB;IACA,eAAe;KACb,OAAO,MAAM;KACb,SAAS,UAAU;IACrB;GACF,CACF;EACF,GACA;GAAC;GAAS;GAAmB;EAAa,CAe1C;EACA,QAZa,kBAAkB;GAC/B,YAAY,SAAS,MAAM;GAC3B,YAAY,UAAU;GACtB,SAAS,UAAU;GACnB,WAAW,UAAU;GACrB,WAAW,IAAI;GACf,WAAW,IAAI;EACjB,GAAG,CAAC,CAKF;;EAEA;;EAEA;EACA,YAAY,QAAQ;EACpB,aAAa,QAAQ,UAAU,QAAQ,QAAQ;CACjD;AACF;;AAGA,SAAgB,8BAA8B;CAC5C,MAAM,eAAe,gBAAgB;CACrC,MAAM,cAAc,eAAe;CAEnC,OAAO,YAAqE;EAC1E,aAAa,EAAE,mBACb,aAAmB,gBAAgB,mBAAmB,YAAY,KAAK,EAAE,QAAQ,SAAS,CAAC;EAC7F,iBAAiB,gCAAgC,WAAW;CAC9D,CAAC;AACH"}
1
+ {"version":3,"file":"use-user-connect.es.js","names":[],"sources":["../../../src/domains/connect/use-user-connect.ts"],"sourcesContent":["import { useMastraClient } from '@mastra/react';\nimport type { QueryClient } from '@tanstack/react-query';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nimport {\n HeadlessAuthError,\n headlessAuthFields,\n headlessAuthRequiresForm,\n splitHeadlessAuthValues,\n startHeadlessAuth,\n supportsHeadlessAuth,\n} from './headless-connect';\nimport type { HeadlessAuthHandle } from './headless-connect';\nimport type {\n UserConnectErrorBody,\n UserConnectLaunchTokenResponse,\n UserConnectProvider,\n UserConnectProvidersResponse,\n UserConnectSessionResponse,\n UserConnectionStatusResponse,\n UserConnectionsResponse,\n} from './types';\n\n/** Default mount prefix of `userConnectRoutes()` on the dev server. */\nexport const CONNECT_BASE_PATH = '/connect';\n\nexport class UserConnectRequestError extends Error {\n status: number;\n code: string | null;\n\n constructor(status: number, code: string | null, message: string) {\n super(message);\n this.name = 'UserConnectRequestError';\n this.status = status;\n this.code = code;\n }\n}\n\ntype ConnectFetch = <T>(path: string, init?: RequestInit) => Promise<T>;\n\n/**\n * Fetches against the dev server's mounted connect routes. Custom `apiRoutes`\n * live outside the `/api` prefix, so this goes around the SDK while reusing\n * its base URL, auth headers, credentials mode, and refresh-aware fetch.\n */\nfunction useConnectFetch(): ConnectFetch {\n const client = useMastraClient();\n const { baseUrl, headers, credentials, fetch: customFetch } = client.options;\n\n return useCallback<ConnectFetch>(\n async (path, init) => {\n const fetchFn = customFetch ?? fetch;\n const response = await fetchFn(`${baseUrl}${CONNECT_BASE_PATH}${path}`, {\n ...init,\n headers: { ...headers, ...init?.headers },\n credentials,\n });\n if (!response.ok) {\n let code: string | null = null;\n let message = `Request failed with status ${response.status}`;\n try {\n const body = (await response.json()) as Partial<UserConnectErrorBody>;\n if (body?.error) {\n code = body.error.code ?? null;\n message = body.error.message ?? message;\n }\n } catch {\n // Non-JSON error body (e.g. a plain 404 for unmounted routes).\n }\n throw new UserConnectRequestError(response.status, code, message);\n }\n if (response.status === 204) return undefined as never;\n return (await response.json()) as never;\n },\n [baseUrl, headers, credentials, customFetch],\n );\n}\n\n/**\n * Resolves a server-relative launch-gate path (returned by the session route\n * as `launchUrl`) against the SDK's base URL for top-level popup navigation.\n * The launch route is authenticated by the browser's session cookie — the\n * server re-verifies that this browser owns the pending session before\n * redirecting into the vendor OAuth flow.\n */\nexport function useConnectLaunchHref(): (launchUrl: string) => string {\n const client = useMastraClient();\n const { baseUrl } = client.options;\n return useCallback((launchUrl: string) => (baseUrl ? `${baseUrl}${launchUrl}` : launchUrl), [baseUrl]);\n}\n\n/**\n * Redeems the launch gate for a headless session token (`Accept:\n * application/json`) instead of following its hosted 302. The gate runs the\n * same ownership assertion in both modes; a `null` token means the server\n * could not extract one and the caller falls back to the hosted popup.\n */\nfunction useRedeemLaunchToken(): (launchUrl: string) => Promise<UserConnectLaunchTokenResponse> {\n const client = useMastraClient();\n const { baseUrl, headers, credentials, fetch: customFetch } = client.options;\n\n return useCallback(\n async launchUrl => {\n const fetchFn = customFetch ?? fetch;\n // `launchUrl` is the full server-relative gate path (it already carries\n // the connect mount prefix), so it resolves against the bare base URL.\n const response = await fetchFn(`${baseUrl ?? ''}${launchUrl}`, {\n headers: { ...headers, accept: 'application/json' },\n credentials,\n });\n if (!response.ok) {\n throw new UserConnectRequestError(response.status, null, `Request failed with status ${response.status}`);\n }\n return (await response.json()) as UserConnectLaunchTokenResponse;\n },\n [baseUrl, headers, credentials, customFetch],\n );\n}\n\nexport type ConnectSurface =\n | { status: 'ready'; providers: UserConnectProvidersResponse['providers'] }\n | { status: 'not-mounted' }\n | { status: 'unauthenticated' };\n\n/**\n * Capability detection for the end-user connect surface: probes\n * `GET /connect/providers` and distinguishes a working surface from the two\n * setup gaps (routes not mounted → 404, no end-user identity → 401).\n */\nexport function useConnectSurface() {\n const connectFetch = useConnectFetch();\n\n return useQuery<ConnectSurface, UserConnectRequestError>({\n queryKey: ['user-connect', 'surface'],\n retry: false,\n queryFn: async () => {\n try {\n const body = await connectFetch<UserConnectProvidersResponse>('/providers');\n return { status: 'ready', providers: body.providers };\n } catch (error) {\n if (error instanceof UserConnectRequestError) {\n if (error.status === 404) return { status: 'not-mounted' };\n if (error.status === 401) return { status: 'unauthenticated' };\n }\n throw error;\n }\n },\n });\n}\n\nconst connectionsQueryKey = ['user-connect', 'connections'] as const;\n\n/**\n * A connection that activates or goes away changes which tools resolve for\n * this user, so the connection list and every agent / tool listing are\n * refetched. The server drops its cached tool snapshot when it reports the\n * change, so the refetch already sees the new tools.\n */\nfunction invalidateAfterConnectionChange(queryClient: QueryClient) {\n return Promise.all(\n [connectionsQueryKey, ['agent'], ['agents'], ['tools']].map(async queryKey => {\n // A first fetch still in flight would otherwise be reused by the\n // invalidation, and its pre-change answer would land as fresh data.\n await queryClient.cancelQueries({ queryKey });\n await queryClient.invalidateQueries({ queryKey });\n }),\n );\n}\n\n/** Lists the caller's visible connections (global + their own). */\nexport function useUserConnections({ enabled }: { enabled: boolean }) {\n const connectFetch = useConnectFetch();\n\n return useQuery<UserConnectionsResponse['connections'], UserConnectRequestError>({\n queryKey: connectionsQueryKey,\n enabled,\n retry: false,\n queryFn: async () => {\n const body = await connectFetch<UserConnectionsResponse>('/connections');\n return body.connections;\n },\n });\n}\n\n/** Creates a connect session for a provider; the caller drives the popup. */\nexport function useCreateConnectSession() {\n const connectFetch = useConnectFetch();\n\n return useMutation<UserConnectSessionResponse, UserConnectRequestError, { provider: string }>({\n mutationFn: ({ provider }) =>\n connectFetch<UserConnectSessionResponse>(`/${encodeURIComponent(provider)}/sessions`, { method: 'POST' }),\n });\n}\n\n/** 2s interval with a 5 minute cap, mirroring the hosted connect page. */\nconst STATUS_POLL_INTERVAL_MS = 2_000;\nconst STATUS_MAX_POLLS = 150;\n\n/**\n * Polls a pending connection until it leaves `pending`. A 404 counts as still\n * pending — the platform row may not be visible until the provider handshake\n * lands. Polling stops once the status settles (or after the 5 minute cap);\n * the connections list is refreshed when it does.\n */\nexport function useConnectionStatus({ connectionId }: { connectionId: string | null }) {\n const connectFetch = useConnectFetch();\n const queryClient = useQueryClient();\n\n return useQuery<UserConnectionStatusResponse, UserConnectRequestError>({\n queryKey: ['user-connect', 'connection-status', connectionId],\n enabled: connectionId !== null,\n retry: false,\n refetchInterval: query => {\n const status = query.state.data?.status;\n if (status !== undefined && status !== 'pending') return false;\n if (query.state.dataUpdateCount >= STATUS_MAX_POLLS) return false;\n return STATUS_POLL_INTERVAL_MS;\n },\n queryFn: async () => {\n let status: UserConnectionStatusResponse;\n try {\n status = await connectFetch<UserConnectionStatusResponse>(\n `/connections/${encodeURIComponent(connectionId ?? '')}/status`,\n );\n } catch (error) {\n if (error instanceof UserConnectRequestError && error.status === 404) {\n return { id: connectionId ?? '', status: 'pending', scope: 'user' };\n }\n throw error;\n }\n if (status.status !== 'pending') {\n void invalidateAfterConnectionChange(queryClient);\n }\n return status;\n },\n });\n}\n\nexport interface PendingConnect {\n provider: string;\n connectionId: string;\n /**\n * `headless` — the Nango SDK drives the provider's own consent popup (or no\n * popup at all for collected credentials). `hosted` — a popup navigated\n * through the launch gate's 302 into the hosted connect page.\n */\n mode: 'headless' | 'hosted';\n /** Shown when the popup was blocked so the user can finish the flow manually. */\n fallbackUrl: string | null;\n}\n\n/**\n * What a caller passes to `connect()`: the provider's id plus the auth shape\n * when known. Callers that only know the id (older payloads) always get the\n * hosted flow.\n */\nexport type ConnectTarget = Pick<UserConnectProvider, 'id'> &\n Partial<Pick<UserConnectProvider, 'authType' | 'authFields'>>;\n\n/**\n * Grace period after the vendor popup closes before an unsettled flow is\n * abandoned — the activation webhook often lands a few seconds after the\n * vendor window closes itself.\n */\nconst POPUP_CLOSE_GRACE_MS = 15_000;\n/** Wall-clock cap matching the status poll's 5 minute budget. */\nconst PENDING_TIMEOUT_MS = STATUS_POLL_INTERVAL_MS * STATUS_MAX_POLLS;\n\nexport interface UsePendingConnectOptions {\n /** Overrides for the abandonment timings (primarily for tests). */\n popupCloseGraceMs?: number;\n pendingTimeoutMs?: number;\n}\n\n/**\n * Outcome of the most recently settled flow: `active` when the connection\n * activated, `failed` for everything else (non-active settle, poll failure,\n * abandoned popup, poll budget). Cleared when a new flow starts.\n */\nexport interface SettledConnect {\n provider: string;\n status: 'active' | 'failed';\n /** Human-readable failure detail (blocked popup, closed window, rejected credentials). */\n message?: string;\n}\n\n/** Window features for the hosted connect popup. */\nconst POPUP_FEATURES = 'popup,width=600,height=720';\n\n/**\n * Drives one add-connection flow end to end. Providers whose auth the browser\n * can complete headlessly go through the launch gate's JSON redemption: the\n * released session token keys the Nango SDK, which opens the provider's own\n * consent popup (or submits collected credentials with no popup). Everything\n * else gets the hosted flow — a popup opened synchronously in the click\n * gesture (so popup blockers allow it) and navigated through the launch\n * gate's 302. Either way the connection status is polled until it settles.\n * The pending state always resolves — on settle, on a poll or auth failure,\n * when the popup closes without settling (after a grace period), or at the\n * poll budget — so the Connect action is never stuck disabled.\n */\nexport function usePendingConnect(options: UsePendingConnectOptions = {}) {\n const { popupCloseGraceMs = POPUP_CLOSE_GRACE_MS, pendingTimeoutMs = PENDING_TIMEOUT_MS } = options;\n const session = useCreateConnectSession();\n const resolveLaunchHref = useConnectLaunchHref();\n const redeemLaunchToken = useRedeemLaunchToken();\n const [pending, setPending] = useState<PendingConnect | null>(null);\n const [settled, setSettled] = useState<SettledConnect | null>(null);\n const [connectedProviders, setConnectedProviders] = useState<ReadonlySet<string>>(new Set());\n const popupRef = useRef<Pick<Window, 'closed' | 'close'> | null>(null);\n const headlessRef = useRef<HeadlessAuthHandle | null>(null);\n // Mirrors `pending` for async guards (the SDK promise settles outside the\n // render cycle); written directly at every transition so a cancel is never\n // raced by a trailing rejection.\n const pendingRef = useRef<PendingConnect | null>(null);\n const status = useConnectionStatus({ connectionId: pending?.connectionId ?? null });\n\n useEffect(() => {\n pendingRef.current = pending;\n }, [pending]);\n\n // Close the provider popup if the surface unmounts mid-flow.\n useEffect(\n () => () => {\n headlessRef.current?.close();\n headlessRef.current = null;\n },\n [],\n );\n\n // Settle only on a status response for the connection currently pending —\n // a stale result from a previous flow must not clear or mark a newer one.\n const statusData = status.data;\n useEffect(() => {\n if (!pending || statusData === undefined) return;\n if (statusData.id !== pending.connectionId || statusData.status === 'pending') return;\n const { provider } = pending;\n if (statusData.status === 'active') {\n setConnectedProviders(previous => (previous.has(provider) ? previous : new Set([...previous, provider])));\n }\n // The provider window closes itself on active settles; drop the handle so\n // a trailing SDK rejection cannot re-settle this flow.\n headlessRef.current = null;\n pendingRef.current = null;\n setSettled({ provider, status: statusData.status === 'active' ? 'active' : 'failed' });\n setPending(null);\n }, [pending, statusData]);\n\n // A failed poll hands the Connect action back instead of leaving it stuck.\n useEffect(() => {\n if (!status.isError || !pending) return;\n // The ref is cleared before close() so the rejection it triggers no-ops.\n pendingRef.current = null;\n headlessRef.current?.close();\n headlessRef.current = null;\n setSettled({ provider: pending.provider, status: 'failed' });\n setPending(null);\n }, [status.isError, pending]);\n\n // Abandonment: the popup closed without the flow settling (grace period for\n // the trailing webhook) or the poll budget ran out.\n useEffect(() => {\n if (!pending) return;\n const startedAt = Date.now();\n let closedAt: number | null = null;\n const tickMs = Math.min(1_000, popupCloseGraceMs);\n const timer = window.setInterval(() => {\n if (popupRef.current?.closed) closedAt ??= Date.now();\n const abandoned = closedAt !== null && Date.now() - closedAt >= popupCloseGraceMs;\n const timedOut = Date.now() - startedAt >= pendingTimeoutMs;\n if (abandoned || timedOut) {\n // The ref is cleared before close() so the rejection it triggers no-ops.\n pendingRef.current = null;\n headlessRef.current?.close();\n headlessRef.current = null;\n setSettled({ provider: pending.provider, status: 'failed' });\n setPending(null);\n }\n }, tickMs);\n return () => window.clearInterval(timer);\n }, [pending, popupCloseGraceMs, pendingTimeoutMs]);\n\n const beginHeadless = useCallback(\n async (provider: ConnectTarget, created: UserConnectSessionResponse, values?: Record<string, string>) => {\n let sessionToken: string | null = null;\n try {\n sessionToken = (await redeemLaunchToken(created.launchUrl)).sessionToken;\n } catch {\n // Redemption failure (older platform, transient error) is not fatal —\n // the hosted flow below still works through the gate's 302.\n }\n if (!sessionToken) {\n // Opened after an await, so a blocker may stop it; the fallback link\n // in the pending state covers that.\n const launchHref = resolveLaunchHref(created.launchUrl);\n const popup = window.open(launchHref, 'mastra-connect', POPUP_FEATURES);\n popupRef.current = popup;\n const next: PendingConnect = {\n provider: provider.id,\n connectionId: created.connectionId,\n mode: 'hosted',\n fallbackUrl: popup ? null : launchHref,\n };\n pendingRef.current = next;\n setPending(next);\n return;\n }\n\n const split = values ? splitHeadlessAuthValues(headlessAuthFields(provider), values) : {};\n const handle = startHeadlessAuth({\n sessionToken,\n apiBaseUrl: created.apiBaseUrl,\n integrationId: created.integrationId,\n authType: provider.authType,\n credentials: split.credentials,\n params: split.params,\n });\n headlessRef.current = handle;\n const next: PendingConnect = {\n provider: provider.id,\n connectionId: created.connectionId,\n mode: 'headless',\n fallbackUrl: null,\n };\n pendingRef.current = next;\n setPending(next);\n // Success needs no action here — the activation webhook lands on the\n // platform and the status poll settles the flow. Failures settle it now.\n handle.result.catch((error: unknown) => {\n if (pendingRef.current?.connectionId !== created.connectionId) return;\n headlessRef.current = null;\n pendingRef.current = null;\n const message = error instanceof HeadlessAuthError ? error.message : 'Could not authorize this connection.';\n setSettled({ provider: provider.id, status: 'failed', message });\n setPending(null);\n });\n },\n [redeemLaunchToken, resolveLaunchHref],\n );\n\n const connect = useCallback(\n (provider: ConnectTarget, values?: Record<string, string>) => {\n setSettled(null);\n headlessRef.current?.close();\n headlessRef.current = null;\n\n // Headless needs both the capability and the inputs: a caller without a\n // form (no `values`) can only run flows whose fields are all optional —\n // anything else falls back to the hosted page, which renders the form.\n const headless =\n supportsHeadlessAuth(provider.authType, provider.authFields) &&\n (values !== undefined || !headlessAuthRequiresForm(provider));\n // Hosted flows open the popup synchronously in the click gesture so\n // popup blockers allow it; headless flows never navigate to a hosted\n // page, so no window opens here.\n const popup = headless ? null : window.open('', 'mastra-connect', POPUP_FEATURES);\n popupRef.current = popup;\n session.mutate(\n { provider: provider.id },\n {\n onSuccess: created => {\n if (headless) {\n void beginHeadless(provider, created, values);\n return;\n }\n // The popup enters OAuth through the server's launch gate, which\n // verifies this browser owns the pending session before\n // redirecting — the raw vendor URL never reaches the page.\n const launchHref = resolveLaunchHref(created.launchUrl);\n if (popup) {\n popup.location.href = launchHref;\n }\n const next: PendingConnect = {\n provider: provider.id,\n connectionId: created.connectionId,\n mode: 'hosted',\n fallbackUrl: popup ? null : launchHref,\n };\n pendingRef.current = next;\n setPending(next);\n },\n onError: () => {\n popup?.close();\n popupRef.current = null;\n },\n },\n );\n },\n [session, resolveLaunchHref, beginHeadless],\n );\n\n /** Abandons the in-flight flow: closes the provider window, hands the Connect action back. */\n const cancel = useCallback(() => {\n headlessRef.current?.close();\n headlessRef.current = null;\n popupRef.current?.close();\n popupRef.current = null;\n pendingRef.current = null;\n setPending(null);\n setSettled(null);\n }, []);\n\n return {\n pending,\n connect,\n cancel,\n /** Outcome of the most recently settled flow; null while none settled or a flow is in progress. */\n settled,\n /** Providers whose connection settled `active` during this hook's lifetime. */\n connectedProviders,\n isCreating: session.isPending,\n createError: session.isError ? session.error : null,\n };\n}\n\n/** Disconnects one of the caller's own connections. */\nexport function useDisconnectUserConnection() {\n const connectFetch = useConnectFetch();\n const queryClient = useQueryClient();\n\n return useMutation<void, UserConnectRequestError, { connectionId: string }>({\n mutationFn: ({ connectionId }) =>\n connectFetch<void>(`/connections/${encodeURIComponent(connectionId)}`, { method: 'DELETE' }),\n onSuccess: () => invalidateAfterConnectionChange(queryClient),\n });\n}\n"],"mappings":";;;;;;AAyBA,IAAa,oBAAoB;AAEjC,IAAa,0BAAb,cAA6C,MAAM;CACjD;CACA;CAEA,YAAY,QAAgB,MAAqB,SAAiB;EAChE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,OAAO;CACd;AACF;;;;;;AASA,SAAS,kBAAgC;CAEvC,MAAM,EAAE,SAAS,SAAS,aAAa,OAAO,gBAD/B,gBAC+C,CAAA,CAAO;CAErE,OAAO,YACL,OAAO,MAAM,SAAS;EAEpB,MAAM,WAAW,OADD,eAAe,MAAA,CACA,GAAG,UAAU,oBAAoB,QAAQ;GACtE,GAAG;GACH,SAAS;IAAE,GAAG;IAAS,GAAG,MAAM;GAAQ;GACxC;EACF,CAAC;EACD,IAAI,CAAC,SAAS,IAAI;GAChB,IAAI,OAAsB;GAC1B,IAAI,UAAU,8BAA8B,SAAS;GACrD,IAAI;IACF,MAAM,OAAQ,MAAM,SAAS,KAAK;IAClC,IAAI,MAAM,OAAO;KACf,OAAO,KAAK,MAAM,QAAQ;KAC1B,UAAU,KAAK,MAAM,WAAW;IAClC;GACF,QAAQ,CAER;GACA,MAAM,IAAI,wBAAwB,SAAS,QAAQ,MAAM,OAAO;EAClE;EACA,IAAI,SAAS,WAAW,KAAK,OAAO,KAAA;EACpC,OAAQ,MAAM,SAAS,KAAK;CAC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I;IACjB;IACA,eAAe;KACb,OAAO,MAAM;KACb,SAAS,UAAU;IACrB;GACF,CACF;EACF,GACA;GAAC;GAAS;GAAmB;EAAa,CAgB1C;EACA,QAba,kBAAkB;GAC/B,YAAY,SAAS,MAAM;GAC3B,YAAY,UAAU;GACtB,SAAS,SAAS,MAAM;GACxB,SAAS,UAAU;GACnB,WAAW,UAAU;GACrB,WAAW,IAAI;GACf,WAAW,IAAI;EACjB,GAAG,CAAC,CAKF;;EAEA;;EAEA;EACA,YAAY,QAAQ;EACpB,aAAa,QAAQ,UAAU,QAAQ,QAAQ;CACjD;AACF;;AAGA,SAAgB,8BAA8B;CAC5C,MAAM,eAAe,gBAAgB;CACrC,MAAM,cAAc,eAAe;CAEnC,OAAO,YAAqE;EAC1E,aAAa,EAAE,mBACb,aAAmB,gBAAgB,mBAAmB,YAAY,KAAK,EAAE,QAAQ,SAAS,CAAC;EAC7F,iBAAiB,gCAAgC,WAAW;CAC9D,CAAC;AACH"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mastra/playground-ui",
3
3
  "type": "module",
4
- "version": "72.0.0-alpha.1",
4
+ "version": "72.0.0-alpha.2",
5
5
  "description": "Mastra Playground components",
6
6
  "sideEffects": [
7
7
  "**/*.css"