@mastra/playground-ui 72.0.0-alpha.0 → 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.
Files changed (47) hide show
  1. package/dist/{combobox-Db8NtklU.js → combobox-BCB51kuy.js} +58 -12
  2. package/dist/combobox-BCB51kuy.js.map +1 -0
  3. package/dist/{combobox-Cg-KVjdt.cjs → combobox-CtEvUaJc.cjs} +58 -12
  4. package/dist/combobox-CtEvUaJc.cjs.map +1 -0
  5. package/dist/components/Combobox.cjs.js +1 -1
  6. package/dist/components/Combobox.es.js +1 -1
  7. package/dist/components/DataList.cjs.js +1 -1
  8. package/dist/components/DataList.es.js +1 -1
  9. package/dist/components/PropertyFilter.cjs.js +1 -1
  10. package/dist/components/PropertyFilter.es.js +1 -1
  11. package/dist/domains/agents/agent-combobox.cjs.js +1 -1
  12. package/dist/domains/agents/agent-combobox.es.js +1 -1
  13. package/dist/domains/chat/tools/connect-prompt-tool.cjs.js +112 -76
  14. package/dist/domains/chat/tools/connect-prompt-tool.cjs.js.map +1 -1
  15. package/dist/domains/chat/tools/connect-prompt-tool.es.js +113 -77
  16. package/dist/domains/chat/tools/connect-prompt-tool.es.js.map +1 -1
  17. package/dist/domains/connect/use-user-connect.cjs.js +1 -0
  18. package/dist/domains/connect/use-user-connect.cjs.js.map +1 -1
  19. package/dist/domains/connect/use-user-connect.es.js +1 -0
  20. package/dist/domains/connect/use-user-connect.es.js.map +1 -1
  21. package/dist/domains/datasets/components/dataset-combobox.cjs.js +1 -1
  22. package/dist/domains/datasets/components/dataset-combobox.es.js +1 -1
  23. package/dist/domains/datasets/components/dataset-detail/dataset-tags-editor.cjs.js +1 -1
  24. package/dist/domains/datasets/components/dataset-detail/dataset-tags-editor.es.js +1 -1
  25. package/dist/domains/datasets/components/dataset-versions.cjs.js +1 -1
  26. package/dist/domains/datasets/components/dataset-versions.es.js +1 -1
  27. package/dist/domains/datasets/components/experiment-trigger/scorer-selector.cjs.js +1 -1
  28. package/dist/domains/datasets/components/experiment-trigger/scorer-selector.es.js +1 -1
  29. package/dist/domains/experiments/components/experiment-results-tag-picker.cjs.js +1 -1
  30. package/dist/domains/experiments/components/experiment-results-tag-picker.es.js +1 -1
  31. package/dist/domains/prompt-blocks/prompt-block-version-combobox.cjs.js +1 -1
  32. package/dist/domains/prompt-blocks/prompt-block-version-combobox.es.js +1 -1
  33. package/dist/domains/scores/components/span-scoring.cjs.js +1 -1
  34. package/dist/domains/scores/components/span-scoring.es.js +1 -1
  35. package/dist/domains/traces/components/trace-columns-menu.cjs.js +1 -1
  36. package/dist/domains/traces/components/trace-columns-menu.es.js +1 -1
  37. package/dist/domains/workflows/components/workflow-combobox.cjs.js +1 -1
  38. package/dist/domains/workflows/components/workflow-combobox.es.js +1 -1
  39. package/dist/layout/tabbed-container.cjs.js +1 -1
  40. package/dist/layout/tabbed-container.es.js +1 -1
  41. package/dist/{tabbed-container-DiHt3VX3.js → tabbed-container-CRPiA3RI.js} +2 -2
  42. package/dist/{tabbed-container-DiHt3VX3.js.map → tabbed-container-CRPiA3RI.js.map} +1 -1
  43. package/dist/{tabbed-container-DbgPRklc.cjs → tabbed-container-DLntsyso.cjs} +2 -2
  44. package/dist/{tabbed-container-DbgPRklc.cjs.map → tabbed-container-DLntsyso.cjs.map} +1 -1
  45. package/package.json +7 -7
  46. package/dist/combobox-Cg-KVjdt.cjs.map +0 -1
  47. package/dist/combobox-Db8NtklU.js.map +0 -1
@@ -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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AAK;SAAQ,MAAK;SAAS,UAAA;QAEvD,CAAA,IACH;QACH,aAAa,SAAS,cACrB,oBAAC,KAAD;SACE,MAAM,QAAQ;SACd,QAAO;SACP,KAAI;SACJ,WAAU;SACX,UAAA;QAEE,CAAA,IACD;QACH,cACC,qBAAC,KAAD;SACE,IAAG;SACH,SAAQ;SACR,MAAK;SACL,WAAU;SAJZ,UAAA,CAME,oBAAC,MAAD;UAAM,MAAK;UACT,UAAA,oBAAC,sBAAD,EAAsB,eAAA,KAAa,CAAA;SAC/B,CAAA,GAAC,WAEJ;QAEL,CAAA,IAAA,oBAAC,QAAD;SACE,SAAQ;SACR,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,oBAAC,OAAD;GAAK,MAAK;GACR,UAAA,oBAAC,QAAD;IAAQ,SAAQ;IAAc,OAAM;IAClC,UAAA,oBAAC,OAAO,SAAR,EAAA,UAAiB,aAA6B,CAAA;GACxC,CAAA;EACL,CAAA,IACH,IACG;;AAEb"}
1
+ {"version":3,"file":"connect-prompt-tool.es.js","names":[],"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,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;;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,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;UACE,MAAM,QAAQ;UACd,QAAO;UACP,KAAI;UACJ,WAAU;UACX,UAAA;SAEE,CAAA,IACD;SACH,cACC,qBAAC,KAAD;UACE,IAAG;UACH,SAAQ;UACR,MAAK;UACL,WAAU;UAJZ,UAAA,CAME,oBAAC,MAAD;WAAM,MAAK;WACT,UAAA,oBAAC,sBAAD,EAAsB,eAAA,KAAa,CAAA;UAC/B,CAAA,GAAC,WAEJ;SAEL,CAAA,IAAA,oBAAC,QAAD;UACE,SAAQ;UACR,MAAK;UACL,WAAU;UACV,UAAU,YAAY;UACtB,SAAS;UACT,eAAe,QAAQ,QAAQ;UAChC,UAAA;SAEO,CAAA;QAEP;OACF,CAAA,CAAA;;KACQ,CAAA,EACG,GApDK,SAAS,EAoDd;IAExB,CAAC,CACO;;GACT,aAAa,aAAa,CAAC,iBAC1B,oBAAC,KAAD;IAAK,IAAG;IAAI,SAAQ;IAAU,MAAK;IAAQ,MAAK;IAAS,UAAA;GAEpD,CAAA,IACH;GACH,eACC,oBAAC,OAAD;IAAK,MAAK;IACR,UAAA,oBAAC,QAAD;KAAQ,SAAQ;KAAc,OAAM;KAClC,UAAA,oBAAC,OAAO,SAAR,EAAA,UAAiB,aAA6B,CAAA;IACxC,CAAA;GACL,CAAA,IACH;EACG;;AAEb"}
@@ -374,6 +374,7 @@ function usePendingConnect(options = {}) {
374
374
  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 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,YAAA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B;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,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;E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AS,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(queryCl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;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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B,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,6 +1,6 @@
1
1
  "use client";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const require_combobox = require("../../../combobox-Cg-KVjdt.cjs");
3
+ const require_combobox = require("../../../combobox-CtEvUaJc.cjs");
4
4
  const require_lib_framework = require("../../../lib/framework.cjs.js");
5
5
  const require_toast_api = require("../../../toast-api-OXZMucsU.cjs");
6
6
  let react = require("react");
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { t as Combobox } from "../../../combobox-Db8NtklU.js";
2
+ import { t as Combobox } from "../../../combobox-BCB51kuy.js";
3
3
  import { useLinkComponent } from "../../../lib/framework.es.js";
4
4
  import { t as toast } from "../../../toast-api-C7oY0pJy.js";
5
5
  import { useEffect } from "react";
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_domains_datasets_components_datasets_list_helpers = require("../datasets-list/helpers.cjs.js");
3
3
  const require_domains_observability_components_computed_tag = require("../../../observability/components/computed-tag.cjs.js");
4
- const require_combobox = require("../../../../combobox-Cg-KVjdt.cjs");
4
+ const require_combobox = require("../../../../combobox-CtEvUaJc.cjs");
5
5
  const require_icons_central_IconCheckmark2Medium = require("../../../../icons/central/IconCheckmark2Medium.cjs.js");
6
6
  const require_icons_central_IconCrossMedium = require("../../../../icons/central/IconCrossMedium.cjs.js");
7
7
  const require_toast_api = require("../../../../toast-api-OXZMucsU.cjs");
@@ -1,6 +1,6 @@
1
1
  import { getAllDatasetTags } from "../datasets-list/helpers.es.js";
2
2
  import { ComputedTag } from "../../../observability/components/computed-tag.es.js";
3
- import { t as Combobox } from "../../../../combobox-Db8NtklU.js";
3
+ import { t as Combobox } from "../../../../combobox-BCB51kuy.js";
4
4
  import { IconCheckmark2Medium } from "../../../../icons/central/IconCheckmark2Medium.es.js";
5
5
  import { IconCrossMedium } from "../../../../icons/central/IconCrossMedium.es.js";
6
6
  import { t as toast } from "../../../../toast-api-C7oY0pJy.js";
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const require_combobox = require("../../../combobox-Cg-KVjdt.cjs");
3
+ const require_combobox = require("../../../combobox-CtEvUaJc.cjs");
4
4
  const require_utils_date_format = require("../../../utils/date-format.cjs.js");
5
5
  let react = require("react");
6
6
  let react_jsx_runtime = require("react/jsx-runtime");
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { t as Combobox } from "../../../combobox-Db8NtklU.js";
2
+ import { t as Combobox } from "../../../combobox-BCB51kuy.js";
3
3
  import { formatDate } from "../../../utils/date-format.es.js";
4
4
  import { useEffect } from "react";
5
5
  import { jsx } from "react/jsx-runtime";
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_combobox = require("../../../../combobox-Cg-KVjdt.cjs");
2
+ const require_combobox = require("../../../../combobox-CtEvUaJc.cjs");
3
3
  const require_components_Field = require("../../../../components/Field.cjs.js");
4
4
  let react_jsx_runtime = require("react/jsx-runtime");
5
5
  let _mastra_react_hooks_scores = require("@mastra/react/hooks/scores");
@@ -1,5 +1,5 @@
1
1
  import { useScorers } from "../../../scores/hooks.es.js";
2
- import { t as Combobox } from "../../../../combobox-Db8NtklU.js";
2
+ import { t as Combobox } from "../../../../combobox-BCB51kuy.js";
3
3
  import { Field, FieldDescription, FieldLabel } from "../../../../components/Field.es.js";
4
4
  import { jsx, jsxs } from "react/jsx-runtime";
5
5
  // src/domains/datasets/components/experiment-trigger/scorer-selector.tsx
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const require_combobox = require("../../../combobox-Cg-KVjdt.cjs");
3
+ const require_combobox = require("../../../combobox-CtEvUaJc.cjs");
4
4
  const require_icons_central_IconCheckmark2Medium = require("../../../icons/central/IconCheckmark2Medium.cjs.js");
5
5
  let react = require("react");
6
6
  let react_jsx_runtime = require("react/jsx-runtime");
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { t as Combobox } from "../../../combobox-Db8NtklU.js";
2
+ import { t as Combobox } from "../../../combobox-BCB51kuy.js";
3
3
  import { IconCheckmark2Medium } from "../../../icons/central/IconCheckmark2Medium.es.js";
4
4
  import { useMemo, useState } from "react";
5
5
  import { jsx } from "react/jsx-runtime";
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_Badge = require("../../Badge-DqaMg7Gy.cjs");
3
- const require_combobox = require("../../combobox-Cg-KVjdt.cjs");
3
+ const require_combobox = require("../../combobox-CtEvUaJc.cjs");
4
4
  const require_utils_date_format = require("../../utils/date-format.cjs.js");
5
5
  let react_jsx_runtime = require("react/jsx-runtime");
6
6
  let _mastra_react_hooks_prompt_blocks = require("@mastra/react/hooks/prompt-blocks");
@@ -1,5 +1,5 @@
1
1
  import { t as Badge } from "../../Badge-C7NnqmMx.js";
2
- import { t as Combobox } from "../../combobox-Db8NtklU.js";
2
+ import { t as Combobox } from "../../combobox-BCB51kuy.js";
3
3
  import { formatDate } from "../../utils/date-format.es.js";
4
4
  import { jsx } from "react/jsx-runtime";
5
5
  import { usePromptBlockVersions } from "@mastra/react/hooks/prompt-blocks";
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_combobox = require("../../../combobox-Cg-KVjdt.cjs");
2
+ const require_combobox = require("../../../combobox-CtEvUaJc.cjs");
3
3
  const require_Dialog = require("../../../Dialog-DKOLz3KE.cjs");
4
4
  const require_Notice = require("../../../Notice-CS_aUxIi.cjs");
5
5
  const require_components_Text = require("../../../components/Text.cjs.js");
@@ -1,4 +1,4 @@
1
- import { t as Combobox } from "../../../combobox-Db8NtklU.js";
1
+ import { t as Combobox } from "../../../combobox-BCB51kuy.js";
2
2
  import { n as DialogBody, o as DialogDescription, p as DialogAction, r as DialogCancel, s as DialogFooter } from "../../../Dialog-CybqopCT.js";
3
3
  import { t as Notice } from "../../../Notice-BdfIyUok.js";
4
4
  import { TextAndIcon } from "../../../components/Text.es.js";
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_domains_traces_trace_list_columns = require("../trace-list-columns.cjs.js");
3
- const require_combobox = require("../../../combobox-Cg-KVjdt.cjs");
3
+ const require_combobox = require("../../../combobox-CtEvUaJc.cjs");
4
4
  const require_Dialog = require("../../../Dialog-DKOLz3KE.cjs");
5
5
  const require_dropdown_menu = require("../../../dropdown-menu-CbrBOOgZ.cjs");
6
6
  const require_components_Field = require("../../../components/Field.cjs.js");
@@ -1,5 +1,5 @@
1
1
  import { TRACE_COLUMN_CATALOGS, TRACE_CUSTOM_COLUMN_FIELDS, TRACE_CUSTOM_COLUMN_LABELS, TRACE_USAGE_COLUMNS } from "../trace-list-columns.es.js";
2
- import { t as Combobox } from "../../../combobox-Db8NtklU.js";
2
+ import { t as Combobox } from "../../../combobox-BCB51kuy.js";
3
3
  import { a as DialogContent, c as DialogHeader, d as DialogTitle, n as DialogBody, o as DialogDescription, p as DialogAction, r as DialogCancel, s as DialogFooter, t as Dialog } from "../../../Dialog-CybqopCT.js";
4
4
  import { t as DropdownMenu } from "../../../dropdown-menu-C9U8z4q0.js";
5
5
  import { Field, FieldError, FieldLabel } from "../../../components/Field.es.js";
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_combobox = require("../../../combobox-Cg-KVjdt.cjs");
2
+ const require_combobox = require("../../../combobox-CtEvUaJc.cjs");
3
3
  const require_lib_framework = require("../../../lib/framework.cjs.js");
4
4
  const require_toast_api = require("../../../toast-api-OXZMucsU.cjs");
5
5
  let react = require("react");
@@ -1,4 +1,4 @@
1
- import { t as Combobox } from "../../../combobox-Db8NtklU.js";
1
+ import { t as Combobox } from "../../../combobox-BCB51kuy.js";
2
2
  import { useLinkComponent } from "../../../lib/framework.es.js";
3
3
  import { t as toast } from "../../../toast-api-C7oY0pJy.js";
4
4
  import { useEffect } from "react";
@@ -1,3 +1,3 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_tabbed_container = require("../tabbed-container-DbgPRklc.cjs");
2
+ const require_tabbed_container = require("../tabbed-container-DLntsyso.cjs");
3
3
  exports.TabbedContainer = require_tabbed_container.TabbedContainer;
@@ -1 +1 @@
1
- export { t as TabbedContainer } from "../tabbed-container-DiHt3VX3.js";
1
+ export { t as TabbedContainer } from "../tabbed-container-CRPiA3RI.js";
@@ -1,4 +1,4 @@
1
- import { t as Combobox } from "./combobox-Db8NtklU.js";
1
+ import { t as Combobox } from "./combobox-BCB51kuy.js";
2
2
  import { t as DataList } from "./data-list-BV-YCOhk.js";
3
3
  import { SearchInput } from "./components/SearchInput.es.js";
4
4
  import { t as TabContent } from "./tabs-content-Clwuqe7C.js";
@@ -127,4 +127,4 @@ var TabbedContainer = Object.assign(TabbedContainerRoot, {
127
127
  });
128
128
  export { TabbedContainer as t };
129
129
 
130
- //# sourceMappingURL=tabbed-container-DiHt3VX3.js.map
130
+ //# sourceMappingURL=tabbed-container-CRPiA3RI.js.map