@agent-native/core 0.15.10 → 0.15.12
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.
- package/dist/a2a/server.d.ts +1 -0
- package/dist/a2a/server.d.ts.map +1 -1
- package/dist/a2a/server.js +25 -13
- package/dist/a2a/server.js.map +1 -1
- package/dist/a2a/types.d.ts +8 -0
- package/dist/a2a/types.d.ts.map +1 -1
- package/dist/a2a/types.js +0 -1
- package/dist/a2a/types.js.map +1 -1
- package/dist/action.d.ts +15 -0
- package/dist/action.d.ts.map +1 -1
- package/dist/action.js +6 -0
- package/dist/action.js.map +1 -1
- package/dist/agent/production-agent.d.ts +3 -0
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/agent-web/config.d.ts +41 -0
- package/dist/agent-web/config.d.ts.map +1 -0
- package/dist/agent-web/config.js +162 -0
- package/dist/agent-web/config.js.map +1 -0
- package/dist/agent-web/generator.d.ts +95 -0
- package/dist/agent-web/generator.d.ts.map +1 -0
- package/dist/agent-web/generator.js +270 -0
- package/dist/agent-web/generator.js.map +1 -0
- package/dist/agent-web/index.d.ts +3 -0
- package/dist/agent-web/index.d.ts.map +1 -0
- package/dist/agent-web/index.js +3 -0
- package/dist/agent-web/index.js.map +1 -0
- package/dist/cli/audit-agent-web.d.ts +2 -0
- package/dist/cli/audit-agent-web.d.ts.map +1 -0
- package/dist/cli/audit-agent-web.js +201 -0
- package/dist/cli/audit-agent-web.js.map +1 -0
- package/dist/cli/index.js +17 -0
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/migrate.d.ts +10 -0
- package/dist/cli/migrate.d.ts.map +1 -0
- package/dist/cli/migrate.js +78 -0
- package/dist/cli/migrate.js.map +1 -0
- package/dist/cli/templates-meta.d.ts.map +1 -1
- package/dist/cli/templates-meta.js +12 -0
- package/dist/cli/templates-meta.js.map +1 -1
- package/dist/client/settings/SettingsPanel.d.ts.map +1 -1
- package/dist/client/settings/SettingsPanel.js +6 -5
- package/dist/client/settings/SettingsPanel.js.map +1 -1
- package/dist/client/settings/useBuilderStatus.d.ts.map +1 -1
- package/dist/client/settings/useBuilderStatus.js +79 -37
- package/dist/client/settings/useBuilderStatus.js.map +1 -1
- package/dist/client/settings/useBuilderStatus.spec.js +84 -6
- package/dist/client/settings/useBuilderStatus.spec.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +2 -0
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/credential-provider.d.ts.map +1 -1
- package/dist/server/credential-provider.js +4 -2
- package/dist/server/credential-provider.js.map +1 -1
- package/dist/vite/agent-web-plugin.d.ts +17 -0
- package/dist/vite/agent-web-plugin.d.ts.map +1 -0
- package/dist/vite/agent-web-plugin.js +48 -0
- package/dist/vite/agent-web-plugin.js.map +1 -0
- package/dist/vite/index.d.ts +1 -0
- package/dist/vite/index.d.ts.map +1 -1
- package/dist/vite/index.js +1 -0
- package/dist/vite/index.js.map +1 -1
- package/docs/content/agent-web-surfaces.md +143 -0
- package/docs/content/migration-workbench.md +110 -0
- package/package.json +2 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useBuilderStatus.d.ts","sourceRoot":"","sources":["../../../src/client/settings/useBuilderStatus.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,OAAO,CAAC;IACpB,cAAc,EAAE,OAAO,CAAC;IACxB;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,gBAAgB,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,WAAW,GAAG,KAAK,CAAC;IACxD,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;I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AC3E;AAED,MAAM,WAAW,kBAAkB;IACjC,UAAU,EAAE,OAAO,CAAC;IACpB;;;;OAIG;IACH,UAAU,EAAE,OAAO,CAAC;IACpB;;;;OAIG;IACH,cAAc,EAAE,OAAO,CAAC;IACxB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,UAAU,EAAE,OAAO,CAAC;IACpB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB;;;;;;;OAOG;IACH,gBAAgB,EAAE,OAAO,CAAC;IAC1B,oFAAoF;IACpF,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB;AAgJD,MAAM,WAAW,8BAA8B;IAC7C,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,wBAAgB,uBAAuB,CAAC,EACtC,GAAG,EACH,MAA0B,EAC1B,QAAgC,GACjC,GAAE,8BAAmC,GAAG,MAAM,GAAG,IAAI,CAkCrD;AAED,wBAAgB,qBAAqB,CACnC,IAAI,GAAE,yBAA8B,GACnC,kBAAkB,CAwapB"}
|
|
@@ -49,6 +49,9 @@ export function useBuilderStatus() {
|
|
|
49
49
|
}
|
|
50
50
|
const POLL_INTERVAL_MS = 2000;
|
|
51
51
|
const POLL_TIMEOUT_MS = 5 * 60 * 1000;
|
|
52
|
+
const POPUP_CLOSED_CONFIRMATION_GRACE_MS = 5000;
|
|
53
|
+
const CALLBACK_SUCCESS_STATUS_RETRY_MS = 500;
|
|
54
|
+
const CALLBACK_SUCCESS_STATUS_RETRIES = 10;
|
|
52
55
|
const BUILDER_CONNECT_PARAM = "_an_connect";
|
|
53
56
|
const BUILDER_STATE_PARAM = "_an_state";
|
|
54
57
|
const STATUS_CONNECT_URL_TTL_MS = 9 * 60 * 1000;
|
|
@@ -94,13 +97,9 @@ function isCurrentConnectError(error, startedAt) {
|
|
|
94
97
|
return typeof error.at !== "number" || error.at >= startedAt - 1000;
|
|
95
98
|
}
|
|
96
99
|
function showBuilderConnectPopupPlaceholder(opened) {
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
catch {
|
|
101
|
-
// Best effort only. We still hold the WindowProxy so the parent can
|
|
102
|
-
// navigate the blank popup after refreshing the signed connect URL.
|
|
103
|
-
}
|
|
100
|
+
// Keep opener attached: the Builder callback uses postMessage to notify the
|
|
101
|
+
// settings tab that the popup completed. We still hold the WindowProxy so the
|
|
102
|
+
// parent can navigate the blank popup after refreshing the signed connect URL.
|
|
104
103
|
try {
|
|
105
104
|
opened.document.title = "Opening Builder.io";
|
|
106
105
|
opened.document.body.style.margin = "0";
|
|
@@ -140,6 +139,19 @@ function notifyAgentEngineConfiguredChanged(source) {
|
|
|
140
139
|
detail: { source },
|
|
141
140
|
}));
|
|
142
141
|
}
|
|
142
|
+
function delay(ms) {
|
|
143
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
144
|
+
}
|
|
145
|
+
function isPopupClosed(opened) {
|
|
146
|
+
if (!opened)
|
|
147
|
+
return false;
|
|
148
|
+
try {
|
|
149
|
+
return opened.closed === true;
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
143
155
|
function isTrustedBuilderConnectMessageOrigin(origin) {
|
|
144
156
|
if (typeof window !== "undefined" && origin === window.location.origin) {
|
|
145
157
|
return true;
|
|
@@ -320,6 +332,8 @@ export function useBuilderConnectFlow(opts = {}) {
|
|
|
320
332
|
const start = useCallback(() => {
|
|
321
333
|
stopPoll();
|
|
322
334
|
const started = Date.now();
|
|
335
|
+
let openedPopup = null;
|
|
336
|
+
let popupClosedAt = null;
|
|
323
337
|
connectStartedAtRef.current = started;
|
|
324
338
|
setConnecting(true);
|
|
325
339
|
setError(null);
|
|
@@ -330,41 +344,25 @@ export function useBuilderConnectFlow(opts = {}) {
|
|
|
330
344
|
const cachedFreshUrl = isFreshSignedConnectUrl(statusConnectUrl, statusConnectUrlAtRef.current)
|
|
331
345
|
? statusConnectUrl
|
|
332
346
|
: null;
|
|
333
|
-
// popupUrl
|
|
334
|
-
//
|
|
335
|
-
//
|
|
336
|
-
//
|
|
337
|
-
// about:blank refresh-in-popup path doesn't exist); on web, fall
|
|
338
|
-
// through to the refresh-in-popup branch so a stale prop URL doesn't
|
|
339
|
-
// open an expired popup.
|
|
347
|
+
// popupUrl props and statusConnectUrl are signed URLs minted before the
|
|
348
|
+
// click. In web browsers, always refresh inside an about:blank popup so a
|
|
349
|
+
// server/package restart cannot leave the user with a stale signed state.
|
|
350
|
+
// Desktop keeps the direct path because the Electron shell owns the popup.
|
|
340
351
|
const signedPropUrl = hasSignedConnectToken(popupUrl) ? popupUrl : null;
|
|
341
352
|
const signedCliPropUrl = hasSignedCallbackState(popupUrl) ? popupUrl : null;
|
|
342
353
|
const fallbackUrl = new URL(agentNativePath("/_agent-native/builder/connect"), origin).href;
|
|
343
|
-
const hasDirectSignedUrl = Boolean(cachedFreshUrl);
|
|
344
354
|
const directUrl = cachedFreshUrl ?? signedCliPropUrl ?? signedPropUrl ?? fallbackUrl;
|
|
345
355
|
if (isAgentNativeDesktop()) {
|
|
346
356
|
const opened = openBuilderConnectPopup({
|
|
347
357
|
url: directUrl,
|
|
348
358
|
source: trackingSource,
|
|
349
359
|
});
|
|
360
|
+
openedPopup = opened;
|
|
350
361
|
if (!opened) {
|
|
351
362
|
// Agent Native Desktop handles the popup in Electron and reports
|
|
352
363
|
// null to the embedded webview, so null is not a blocker here.
|
|
353
364
|
}
|
|
354
365
|
}
|
|
355
|
-
else if (hasDirectSignedUrl) {
|
|
356
|
-
const opened = openBuilderConnectPopup({
|
|
357
|
-
url: directUrl,
|
|
358
|
-
source: trackingSource,
|
|
359
|
-
features: "width=600,height=700",
|
|
360
|
-
});
|
|
361
|
-
if (!opened) {
|
|
362
|
-
connectStartedAtRef.current = null;
|
|
363
|
-
setConnecting(false);
|
|
364
|
-
setError("Couldn't open Builder. Allow popups and try again.");
|
|
365
|
-
return;
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
366
|
else {
|
|
369
367
|
const opened = openBuilderConnectPopup({
|
|
370
368
|
url: "about:blank",
|
|
@@ -377,6 +375,7 @@ export function useBuilderConnectFlow(opts = {}) {
|
|
|
377
375
|
setError("Couldn't open Builder. Allow popups and try again.");
|
|
378
376
|
return;
|
|
379
377
|
}
|
|
378
|
+
openedPopup = opened;
|
|
380
379
|
showBuilderConnectPopupPlaceholder(opened);
|
|
381
380
|
void (async () => {
|
|
382
381
|
const s = await fetchStatus();
|
|
@@ -399,13 +398,7 @@ export function useBuilderConnectFlow(opts = {}) {
|
|
|
399
398
|
statusConnectUrlAtRef.current = nextConnectUrl ? Date.now() : null;
|
|
400
399
|
setOrgName(s.orgName ?? null);
|
|
401
400
|
}
|
|
402
|
-
const freshUrl =
|
|
403
|
-
? s.cliAuthUrl
|
|
404
|
-
: null) ??
|
|
405
|
-
(s?.connectUrl && hasSignedConnectToken(s.connectUrl)
|
|
406
|
-
? s.connectUrl
|
|
407
|
-
: null) ??
|
|
408
|
-
cachedFreshUrl;
|
|
401
|
+
const freshUrl = s?.cliAuthUrl ?? s?.connectUrl ?? null;
|
|
409
402
|
if (!freshUrl) {
|
|
410
403
|
try {
|
|
411
404
|
opened.close();
|
|
@@ -463,6 +456,21 @@ export function useBuilderConnectFlow(opts = {}) {
|
|
|
463
456
|
setConnecting(false);
|
|
464
457
|
setError(`Couldn't save Builder credentials: ${s.connectError.message}. Try again or contact support.`);
|
|
465
458
|
}
|
|
459
|
+
else if (isPopupClosed(openedPopup)) {
|
|
460
|
+
popupClosedAt ??= Date.now();
|
|
461
|
+
if (Date.now() - popupClosedAt > POPUP_CLOSED_CONFIRMATION_GRACE_MS) {
|
|
462
|
+
stopPoll();
|
|
463
|
+
connectStartedAtRef.current = null;
|
|
464
|
+
setConnecting(false);
|
|
465
|
+
trackEvent("builder connect failed", {
|
|
466
|
+
feature: "builder",
|
|
467
|
+
stage: "client",
|
|
468
|
+
reason: "popup_closed_without_status",
|
|
469
|
+
source: trackingSource,
|
|
470
|
+
});
|
|
471
|
+
setError("Builder finished, but this workspace couldn't confirm the saved credentials. Refresh this page or try Connect Builder.io again.");
|
|
472
|
+
}
|
|
473
|
+
}
|
|
466
474
|
else if (Date.now() - started > POLL_TIMEOUT_MS) {
|
|
467
475
|
stopPoll();
|
|
468
476
|
connectStartedAtRef.current = null;
|
|
@@ -494,9 +502,43 @@ export function useBuilderConnectFlow(opts = {}) {
|
|
|
494
502
|
setError(`Couldn't save Builder credentials: ${message}.`);
|
|
495
503
|
};
|
|
496
504
|
const handleSuccess = async () => {
|
|
497
|
-
|
|
498
|
-
|
|
505
|
+
let s = null;
|
|
506
|
+
for (let i = 0; i < CALLBACK_SUCCESS_STATUS_RETRIES; i += 1) {
|
|
507
|
+
s = await fetchStatus();
|
|
508
|
+
if (!mountedRef.current)
|
|
509
|
+
return;
|
|
510
|
+
if (s?.configured ||
|
|
511
|
+
isCurrentConnectError(s?.connectError, connectStartedAtRef.current)) {
|
|
512
|
+
break;
|
|
513
|
+
}
|
|
514
|
+
if (i < CALLBACK_SUCCESS_STATUS_RETRIES - 1) {
|
|
515
|
+
await delay(CALLBACK_SUCCESS_STATUS_RETRY_MS);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
if (!mountedRef.current)
|
|
499
519
|
return;
|
|
520
|
+
if (!s?.configured) {
|
|
521
|
+
const connectError = isCurrentConnectError(s?.connectError, connectStartedAtRef.current)
|
|
522
|
+
? s?.connectError
|
|
523
|
+
: null;
|
|
524
|
+
stopPoll();
|
|
525
|
+
setHasFetchedStatus(true);
|
|
526
|
+
if (s) {
|
|
527
|
+
setConfigured(false);
|
|
528
|
+
setEnvManaged(!!s.envManaged);
|
|
529
|
+
setBuilderEnabled(!!s.builderEnabled);
|
|
530
|
+
const nextConnectUrl = s.cliAuthUrl ?? s.connectUrl ?? null;
|
|
531
|
+
setStatusConnectUrl(nextConnectUrl);
|
|
532
|
+
statusConnectUrlAtRef.current = nextConnectUrl ? Date.now() : null;
|
|
533
|
+
setOrgName(s.orgName ?? null);
|
|
534
|
+
}
|
|
535
|
+
connectStartedAtRef.current = null;
|
|
536
|
+
setConnecting(false);
|
|
537
|
+
setError(connectError
|
|
538
|
+
? `Couldn't save Builder credentials: ${connectError.message}. Try again or contact support.`
|
|
539
|
+
: "Builder finished, but this workspace couldn't confirm the saved credentials. Refresh this page or try Connect Builder.io again.");
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
500
542
|
stopPoll();
|
|
501
543
|
setHasFetchedStatus(true);
|
|
502
544
|
setConfigured(true);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useBuilderStatus.js","sourceRoot":"","sources":["../../../src/client/settings/useBuilderStatus.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAqC7C;;;GAGG;AACH,MAAM,UAAU,gBAAgB;IAC9B,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,QAAQ,CAAuB,IAAI,CAAC,CAAC;IACjE,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;IAE7C,MAAM,WAAW,GAAG,WAAW,CAAC,KAAK,IAAI,EAAE;QACzC,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,eAAe,CAAC,+BAA+B,CAAC,CAAC,CAAC;YAC1E,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;gBACZ,SAAS,CAAC,IAAI,CAAC,CAAC;gBAChB,OAAO;YACT,CAAC;YACD,SAAS,CAA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KAAK,EAAE,CAAC;YACjB,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACjD,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC,CAAC;IAE5B,OAAO;QACL,UAAU;QACV,UAAU;QACV,cAAc;QACd,OAAO;QACP,UAAU;QACV,KAAK;QACL,gBAAgB;QAChB,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import { agentNativePath } from \"../api-path.js\";\nimport { useState, useEffect, useCallback, useRef } from \"react\";\nimport { getCallbackOrigin } from \"../frame.js\";\nimport { trackEvent } from \"../analytics.js\";\n\nexport interface BuilderStatus {\n configured: boolean;\n builderEnabled: boolean;\n /**\n * True when `BUILDER_PRIVATE_KEY` is set at the deploy level. This is a\n * fallback credential; per-user/org Builder connections are still allowed\n * and take precedence for that request.\n */\n envManaged?: boolean;\n credentialSource?: \"user\" | \"org\" | \"workspace\" | \"env\";\n connectUrl: string;\n cliAuthUrl?: string;\n appHost: string;\n apiHost: string;\n branchProjectIdConfigured?: boolean;\n branchProjectId?: string;\n publicKeyConfigured: boolean;\n privateKeyConfigured: boolean;\n userId?: string;\n orgName?: string;\n orgKind?: string;\n /**\n * Set when the OAuth callback ran but failed to persist credentials.\n * Surfaced as a one-shot row by the server so the connect-flow polling\n * can stop with a clear message instead of timing out at 5min.\n */\n connectError?: { message: string; at: number };\n /**\n * Set when the currently effective Builder credential was rejected by\n * Builder's API. Unlike connectError, this describes the old credential pair\n * and should not abort a new reconnect attempt while the popup is open.\n */\n authError?: { message: string; at: number };\n}\n\n/**\n * Fetches Builder connection status from /_agent-native/builder/status.\n * Re-fetches on window focus to detect post-redirect state changes.\n */\nexport function useBuilderStatus() {\n const [status, setStatus] = useState<BuilderStatus | null>(null);\n const [loading, setLoading] = useState(true);\n\n const fetchStatus = useCallback(async () => {\n try {\n const res = await fetch(agentNativePath(\"/_agent-native/builder/status\"));\n if (!res.ok) {\n setStatus(null);\n return;\n }\n setStatus(await res.json());\n } catch {\n setStatus(null);\n } finally {\n setLoading(false);\n }\n }, []);\n\n useEffect(() => {\n fetchStatus();\n\n function onFocus() {\n fetchStatus();\n }\n function onVisibility() {\n if (document.visibilityState === \"visible\") fetchStatus();\n }\n window.addEventListener(\"focus\", onFocus);\n document.addEventListener(\"visibilitychange\", onVisibility);\n // Engine connect/disconnect actions (e.g. the Builder disconnect button)\n // dispatch this event so dependent cards refresh without a full reload.\n window.addEventListener(\"agent-engine:configured-changed\", fetchStatus);\n return () => {\n window.removeEventListener(\"focus\", onFocus);\n document.removeEventListener(\"visibilitychange\", onVisibility);\n window.removeEventListener(\n \"agent-engine:configured-changed\",\n fetchStatus,\n );\n };\n }, [fetchStatus]);\n\n return { status, loading, refetch: fetchStatus };\n}\n\n// ─── useBuilderConnectFlow ──────────────────────────────────────────────────\n//\n// Shared state machine for the \"open Builder CLI-auth popup + poll\n// /builder/status until credentials land\" interaction. Replaces three\n// near-duplicate inline implementations: `BuilderCliAuthMethod` in\n// OnboardingPanel, `ConnectBuilderCard`, and `BuilderConnectCta` in\n// AssistantChat. Each consumer supplies its own popup URL / completion\n// behavior; the hook owns the polling + timeout + focus refresh.\n//\n// `popupUrl` is what we pass to `window.open`. The default\n// `/_agent-native/builder/connect` is a server-side 302 to the real\n// cli-auth URL — using it keeps the click handler synchronous so popup\n// blockers don't downgrade the open to same-tab navigation. Pass an\n// explicit `popupUrl` (e.g. the already-computed cli-auth URL) if your\n// caller already has it in hand.\n\nexport interface BuilderConnectFlowOptions {\n /** URL to synchronously open on start(). Defaults to the 302 shortcut. */\n popupUrl?: string;\n /** Low-cardinality label for the UI surface that opened Builder connect. */\n trackingSource?: string;\n /** Invoked after the status poll first sees `configured: true`. */\n onConnected?: (state: { orgName: string | null }) => void | Promise<void>;\n}\n\nexport interface BuilderConnectFlow {\n configured: boolean;\n /**\n * True when the deploy has BUILDER_PRIVATE_KEY set as a fallback. Connect\n * is still available so users can override the fallback with their own\n * Builder account.\n */\n envManaged: boolean;\n /**\n * True when the server has a Builder branch project configured for this\n * request. When false, the card surfaces a waitlist CTA instead of a Send\n * button.\n */\n builderEnabled: boolean;\n orgName: string | null;\n connecting: boolean;\n error: string | null;\n /**\n * True once the first `/builder/status` fetch has completed (successfully\n * or not). Consumers that accept an `initialConfigured` prop (e.g. agent\n * tool-call results rendered with server-side state) should treat\n * `configured`/`orgName` as authoritative only once this flips true —\n * otherwise the hook's starting `false` defaults would cause a flash\n * back to \"Connect Builder\" on first paint.\n */\n hasFetchedStatus: boolean;\n /** Open the popup and begin polling. Must be called from a user-gesture handler. */\n start: () => void;\n}\n\nconst POLL_INTERVAL_MS = 2000;\nconst POLL_TIMEOUT_MS = 5 * 60 * 1000;\nconst BUILDER_CONNECT_PARAM = \"_an_connect\";\nconst BUILDER_STATE_PARAM = \"_an_state\";\nconst STATUS_CONNECT_URL_TTL_MS = 9 * 60 * 1000;\n\nfunction isAgentNativeDesktop() {\n if (typeof navigator === \"undefined\") return false;\n return /AgentNativeDesktop/i.test(navigator.userAgent || \"\");\n}\n\nfunction hasSignedConnectToken(url: string | null | undefined): boolean {\n if (!url || typeof window === \"undefined\") return false;\n try {\n return new URL(url, window.location.origin).searchParams.has(\n BUILDER_CONNECT_PARAM,\n );\n } catch {\n return false;\n }\n}\n\nfunction hasSignedCallbackState(url: string | null | undefined): boolean {\n if (!url || typeof window === \"undefined\") return false;\n try {\n const parsed = new URL(url, window.location.origin);\n const redirectUrl = parsed.searchParams.get(\"redirect_url\");\n if (!redirectUrl) return false;\n return new URL(redirectUrl).searchParams.has(BUILDER_STATE_PARAM);\n } catch {\n return false;\n }\n}\n\nfunction isFreshSignedConnectUrl(\n url: string | null,\n fetchedAt: number | null,\n): url is string {\n return (\n (hasSignedConnectToken(url) || hasSignedCallbackState(url)) &&\n typeof fetchedAt === \"number\" &&\n Date.now() - fetchedAt < STATUS_CONNECT_URL_TTL_MS\n );\n}\n\nfunction isCurrentConnectError(\n error: { message: string; at: number } | undefined,\n startedAt: number | null,\n): error is { message: string; at: number } {\n if (!error?.message) return false;\n if (!startedAt) return true;\n return typeof error.at !== \"number\" || error.at >= startedAt - 1000;\n}\n\nfunction showBuilderConnectPopupPlaceholder(opened: Window) {\n try {\n opened.opener = null;\n } catch {\n // Best effort only. We still hold the WindowProxy so the parent can\n // navigate the blank popup after refreshing the signed connect URL.\n }\n try {\n opened.document.title = \"Opening Builder.io\";\n opened.document.body.style.margin = \"0\";\n opened.document.body.style.background = \"#111\";\n opened.document.body.style.color = \"#ddd\";\n opened.document.body.style.fontFamily =\n '-apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif';\n opened.document.body.style.display = \"flex\";\n opened.document.body.style.alignItems = \"center\";\n opened.document.body.style.justifyContent = \"center\";\n opened.document.body.style.height = \"100vh\";\n opened.document.body.textContent = \"Opening Builder.io...\";\n } catch {\n // Popup may already be cross-origin or browser may block document writes.\n }\n}\n\nfunction navigateBuilderConnectPopup(opened: Window, url: string): boolean {\n try {\n opened.location.href = url;\n return true;\n } catch {\n try {\n opened.close();\n } catch {\n // Ignore close failures.\n }\n return false;\n }\n}\n\nfunction notifyAgentEngineConfiguredChanged(source: string) {\n if (typeof window === \"undefined\") return;\n window.dispatchEvent(\n new CustomEvent(\"agent-engine:configured-changed\", {\n detail: { source },\n }),\n );\n}\n\nfunction isTrustedBuilderConnectMessageOrigin(origin: string): boolean {\n if (typeof window !== \"undefined\" && origin === window.location.origin) {\n return true;\n }\n try {\n const hostname = new URL(origin).hostname.toLowerCase();\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"builder.io\" ||\n hostname.endsWith(\".builder.io\") ||\n hostname === \"builder.my\" ||\n hostname.endsWith(\".builder.my\") ||\n hostname === \"builderio.xyz\" ||\n hostname.endsWith(\".builderio.xyz\") ||\n hostname === \"builderio.dev\" ||\n hostname.endsWith(\".builderio.dev\") ||\n hostname === \"builder.codes\" ||\n hostname.endsWith(\".builder.codes\") ||\n hostname === \"agent-native.com\" ||\n hostname.endsWith(\".agent-native.com\")\n );\n } catch {\n return false;\n }\n}\n\nexport interface OpenBuilderConnectPopupOptions {\n url?: string;\n source?: string;\n features?: string;\n}\n\nexport function openBuilderConnectPopup({\n url,\n source = \"builder_connect\",\n features = \"noopener,noreferrer\",\n}: OpenBuilderConnectPopupOptions = {}): Window | null {\n if (typeof window === \"undefined\") return null;\n const origin = getCallbackOrigin() || window.location.origin;\n const href =\n url ??\n new URL(agentNativePath(\"/_agent-native/builder/connect\"), origin).href;\n const connectUrlKind = url ? \"provided\" : \"default\";\n trackEvent(\"builder connect clicked\", {\n feature: \"builder\",\n stage: \"client\",\n source,\n connect_url_kind: connectUrlKind,\n });\n try {\n const opened = window.open(href, \"_blank\", features);\n if (!opened && !/AgentNativeDesktop/i.test(navigator.userAgent || \"\")) {\n trackEvent(\"builder connect popup blocked\", {\n feature: \"builder\",\n stage: \"client\",\n source,\n connect_url_kind: connectUrlKind,\n });\n }\n return opened;\n } catch {\n trackEvent(\"builder connect failed\", {\n feature: \"builder\",\n stage: \"client\",\n reason: \"popup_open_exception\",\n source,\n connect_url_kind: connectUrlKind,\n });\n return null;\n }\n}\n\nexport function useBuilderConnectFlow(\n opts: BuilderConnectFlowOptions = {},\n): BuilderConnectFlow {\n const {\n popupUrl,\n trackingSource = \"builder_connect_flow\",\n onConnected,\n } = opts;\n const [configured, setConfigured] = useState(false);\n const [envManaged, setEnvManaged] = useState(false);\n const [builderEnabled, setBuilderEnabled] = useState(false);\n const [orgName, setOrgName] = useState<string | null>(null);\n const [connecting, setConnecting] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [hasFetchedStatus, setHasFetchedStatus] = useState(false);\n const [statusConnectUrl, setStatusConnectUrl] = useState<string | null>(null);\n // When statusConnectUrl was last fetched. The server signs the embedded\n // _an_connect token with a 10-minute TTL; using an older URL fails the\n // cross-origin popup gate. Track freshness so start() can either use a\n // still-good direct URL (desktop) or refresh a new one inside the popup\n // gesture path (browser/editor embeds).\n const statusConnectUrlAtRef = useRef<number | null>(null);\n const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);\n const connectStartedAtRef = useRef<number | null>(null);\n const mountedRef = useRef(true);\n const notifiedConnectedRef = useRef(false);\n // Keep onConnected in a ref so start() doesn't need to re-create when the\n // caller passes an inline arrow function.\n const onConnectedRef = useRef(onConnected);\n onConnectedRef.current = onConnected;\n\n const stopPoll = useCallback(() => {\n if (pollRef.current) {\n clearInterval(pollRef.current);\n pollRef.current = null;\n }\n }, []);\n\n const fetchStatus = useCallback(async () => {\n const origin = getCallbackOrigin() || window.location.origin;\n try {\n const r = await fetch(\n new URL(agentNativePath(\"/_agent-native/builder/status\"), origin).href,\n );\n if (!r.ok) return null;\n return (await r.json()) as {\n configured: boolean;\n envManaged?: boolean;\n builderEnabled?: boolean;\n orgName?: string | null;\n connectUrl?: string;\n cliAuthUrl?: string;\n credentialSource?: \"user\" | \"org\" | \"workspace\" | \"env\";\n connectError?: { message: string; at: number };\n authError?: { message: string; at: number };\n };\n } catch {\n return null;\n }\n }, []);\n\n // Initial fetch + focus/visibility refresh so if the user completed the\n // flow in another tab (or a downgraded same-tab nav) we notice it. Also\n // listen for `agent-engine:configured-changed` so a Disconnect click in\n // Settings propagates to any connect-CTA cards rendered elsewhere in\n // the app without waiting for the next focus event.\n useEffect(() => {\n mountedRef.current = true;\n let cancelled = false;\n const refresh = async () => {\n const s = await fetchStatus();\n if (cancelled || !mountedRef.current) return;\n // Flip `hasFetchedStatus` even when the fetch failed — the caller's\n // \"use initial props until the hook has an answer\" pattern wants to\n // stop waiting after we've tried, regardless of network outcome.\n setHasFetchedStatus(true);\n if (!s) return;\n setConfigured(!!s.configured);\n setEnvManaged(!!s.envManaged);\n setBuilderEnabled(!!s.builderEnabled);\n const nextConnectUrl = s.cliAuthUrl ?? s.connectUrl ?? null;\n setStatusConnectUrl(nextConnectUrl);\n statusConnectUrlAtRef.current = nextConnectUrl ? Date.now() : null;\n const org = s.orgName ?? null;\n setOrgName(org);\n if (s.configured) {\n connectStartedAtRef.current = null;\n }\n if (s.configured && !notifiedConnectedRef.current) {\n notifiedConnectedRef.current = true;\n notifyAgentEngineConfiguredChanged(\"builder-status\");\n try {\n await onConnectedRef.current?.({ orgName: org });\n } catch {\n // The caller's callback is a UI convenience; status is already set.\n }\n } else if (!s.configured) {\n notifiedConnectedRef.current = false;\n }\n // Surface persisted auth-failure messages on idle refreshes, but don't\n // let an old rejected credential abort a new reconnect popup while the\n // user is still choosing a Builder space.\n const activeConnectStartedAt = connectStartedAtRef.current;\n if (isCurrentConnectError(s.connectError, activeConnectStartedAt)) {\n setError(s.connectError.message);\n } else if (!activeConnectStartedAt && s.authError?.message) {\n setError(s.authError.message);\n } else if (s.configured) {\n setError(null);\n }\n };\n refresh();\n const onVisible = () => {\n if (document.visibilityState === \"visible\") refresh();\n };\n window.addEventListener(\"focus\", refresh);\n document.addEventListener(\"visibilitychange\", onVisible);\n window.addEventListener(\"agent-engine:configured-changed\", refresh);\n return () => {\n cancelled = true;\n mountedRef.current = false;\n window.removeEventListener(\"focus\", refresh);\n document.removeEventListener(\"visibilitychange\", onVisible);\n window.removeEventListener(\"agent-engine:configured-changed\", refresh);\n stopPoll();\n };\n }, [fetchStatus, stopPoll]);\n\n const start = useCallback(() => {\n stopPoll();\n const started = Date.now();\n connectStartedAtRef.current = started;\n setConnecting(true);\n setError(null);\n\n // Open SYNCHRONOUSLY inside the caller's click handler — any await\n // before window.open lets the user-gesture token expire, which causes\n // popup blockers to block entirely or fall back to same-tab navigation.\n const origin = getCallbackOrigin() || window.location.origin;\n const cachedFreshUrl = isFreshSignedConnectUrl(\n statusConnectUrl,\n statusConnectUrlAtRef.current,\n )\n ? statusConnectUrl\n : null;\n // popupUrl prop (e.g. from a chat ConnectBuilderCard) may be a signed\n // URL that was minted minutes-to-days ago — we don't have a mint\n // timestamp for it, so we can't be sure it's still within the signed\n // TTL. Use it as a *direct* popup URL only for desktop (where the\n // about:blank refresh-in-popup path doesn't exist); on web, fall\n // through to the refresh-in-popup branch so a stale prop URL doesn't\n // open an expired popup.\n const signedPropUrl = hasSignedConnectToken(popupUrl) ? popupUrl : null;\n const signedCliPropUrl = hasSignedCallbackState(popupUrl) ? popupUrl : null;\n const fallbackUrl = new URL(\n agentNativePath(\"/_agent-native/builder/connect\"),\n origin,\n ).href;\n const hasDirectSignedUrl = Boolean(cachedFreshUrl);\n const directUrl =\n cachedFreshUrl ?? signedCliPropUrl ?? signedPropUrl ?? fallbackUrl;\n\n if (isAgentNativeDesktop()) {\n const opened = openBuilderConnectPopup({\n url: directUrl,\n source: trackingSource,\n });\n if (!opened) {\n // Agent Native Desktop handles the popup in Electron and reports\n // null to the embedded webview, so null is not a blocker here.\n }\n } else if (hasDirectSignedUrl) {\n const opened = openBuilderConnectPopup({\n url: directUrl,\n source: trackingSource,\n features: \"width=600,height=700\",\n });\n if (!opened) {\n connectStartedAtRef.current = null;\n setConnecting(false);\n setError(\"Couldn't open Builder. Allow popups and try again.\");\n return;\n }\n } else {\n const opened = openBuilderConnectPopup({\n url: \"about:blank\",\n source: trackingSource,\n features: \"width=600,height=700\",\n });\n if (!opened) {\n connectStartedAtRef.current = null;\n setConnecting(false);\n setError(\"Couldn't open Builder. Allow popups and try again.\");\n return;\n }\n showBuilderConnectPopupPlaceholder(opened);\n void (async () => {\n const s = await fetchStatus();\n if (!mountedRef.current) {\n try {\n opened.close();\n } catch {\n // Ignore close failures.\n }\n return;\n }\n if (s) {\n setHasFetchedStatus(true);\n setConfigured(!!s.configured);\n setEnvManaged(!!s.envManaged);\n setBuilderEnabled(!!s.builderEnabled);\n const nextConnectUrl = s.cliAuthUrl ?? s.connectUrl ?? null;\n setStatusConnectUrl(nextConnectUrl);\n statusConnectUrlAtRef.current = nextConnectUrl ? Date.now() : null;\n setOrgName(s.orgName ?? null);\n }\n\n const freshUrl =\n (s?.cliAuthUrl && hasSignedCallbackState(s.cliAuthUrl)\n ? s.cliAuthUrl\n : null) ??\n (s?.connectUrl && hasSignedConnectToken(s.connectUrl)\n ? s.connectUrl\n : null) ??\n cachedFreshUrl;\n if (!freshUrl) {\n try {\n opened.close();\n } catch {\n // Ignore close failures.\n }\n stopPoll();\n connectStartedAtRef.current = null;\n setConnecting(false);\n setError(\n \"Couldn't start Builder connect. Refresh this page and try again.\",\n );\n return;\n }\n if (!navigateBuilderConnectPopup(opened, freshUrl)) {\n stopPoll();\n connectStartedAtRef.current = null;\n setConnecting(false);\n setError(\n \"Couldn't navigate the Builder popup. Allow popups and try again.\",\n );\n }\n })();\n }\n\n pollRef.current = setInterval(async () => {\n const s = await fetchStatus();\n if (!mountedRef.current) {\n stopPoll();\n return;\n }\n if (s?.configured) {\n stopPoll();\n setConfigured(true);\n setEnvManaged(!!s.envManaged);\n setBuilderEnabled(!!s.builderEnabled);\n const nextConnectUrl = s.cliAuthUrl ?? s.connectUrl ?? null;\n setStatusConnectUrl(nextConnectUrl);\n statusConnectUrlAtRef.current = nextConnectUrl ? Date.now() : null;\n const org = s.orgName ?? null;\n setOrgName(org);\n setConnecting(false);\n connectStartedAtRef.current = null;\n notifiedConnectedRef.current = true;\n notifyAgentEngineConfiguredChanged(\"builder-connect\");\n try {\n await onConnectedRef.current?.({ orgName: org });\n } catch {\n // Consumer's callback failed; we've already flipped the UI state\n // to connected. Swallow so we don't re-arm the flow.\n }\n } else if (isCurrentConnectError(s?.connectError, started)) {\n // OAuth callback ran but writeBuilderCredentials threw — surface the\n // real error instead of letting the user wait 5 minutes for timeout.\n stopPoll();\n connectStartedAtRef.current = null;\n setConnecting(false);\n setError(\n `Couldn't save Builder credentials: ${s.connectError.message}. Try again or contact support.`,\n );\n } else if (Date.now() - started > POLL_TIMEOUT_MS) {\n stopPoll();\n connectStartedAtRef.current = null;\n setConnecting(false);\n trackEvent(\"builder connect failed\", {\n feature: \"builder\",\n stage: \"client\",\n reason: \"timeout\",\n source: trackingSource,\n });\n setError(\n \"Didn't hear back from Builder in 5 minutes. Allow popups and try again.\",\n );\n }\n }, POLL_INTERVAL_MS);\n }, [fetchStatus, popupUrl, statusConnectUrl, stopPoll, trackingSource]);\n\n // Popup-side fast path: the callback page broadcasts a message so we stop\n // polling immediately rather than waiting for the next 2s tick.\n //\n // We listen on BroadcastChannel (same-origin, works with noopener popups)\n // AND on window.message (legacy path for environments without BC or for\n // popups that still have opener access). Both paths are safe to have open\n // simultaneously \\u2014 the first one to fire wins and the error is deduplicated\n // by the stopPoll() call which is idempotent.\n useEffect(() => {\n let channel: BroadcastChannel | null = null;\n const handleError = (message: string) => {\n stopPoll();\n connectStartedAtRef.current = null;\n setConnecting(false);\n setError(`Couldn't save Builder credentials: ${message}.`);\n };\n const handleSuccess = async () => {\n const s = await fetchStatus();\n if (!mountedRef.current || !s?.configured) return;\n stopPoll();\n setHasFetchedStatus(true);\n setConfigured(true);\n setEnvManaged(!!s.envManaged);\n setBuilderEnabled(!!s.builderEnabled);\n const nextConnectUrl = s.cliAuthUrl ?? s.connectUrl ?? null;\n setStatusConnectUrl(nextConnectUrl);\n statusConnectUrlAtRef.current = nextConnectUrl ? Date.now() : null;\n const org = s.orgName ?? null;\n setOrgName(org);\n setConnecting(false);\n connectStartedAtRef.current = null;\n notifiedConnectedRef.current = true;\n notifyAgentEngineConfiguredChanged(\"builder-connect-message\");\n try {\n await onConnectedRef.current?.({ orgName: org });\n } catch {\n // The caller's callback is a UI convenience; status is already set.\n }\n };\n\n try {\n channel = new BroadcastChannel(`builder-connect:${window.location.host}`);\n channel.onmessage = (e: MessageEvent) => {\n const data = e.data as { type?: string; message?: string } | undefined;\n if (data?.type === \"builder-connect-success\") {\n void handleSuccess();\n return;\n }\n if (data?.type === \"builder-connect-error\") {\n if (typeof data.message !== \"string\" || !data.message) return;\n handleError(data.message);\n }\n };\n } catch {\n // BroadcastChannel not available (rare) \\u2014 fall through to postMessage.\n }\n\n const handler = (e: MessageEvent) => {\n if (!isTrustedBuilderConnectMessageOrigin(e.origin)) return;\n const data = e.data as { type?: string; message?: string } | undefined;\n if (data?.type === \"builder-connect-success\") {\n void handleSuccess();\n return;\n }\n if (data?.type === \"builder-connect-error\") {\n if (typeof data.message !== \"string\" || !data.message) return;\n handleError(data.message);\n }\n };\n window.addEventListener(\"message\", handler);\n\n return () => {\n channel?.close();\n window.removeEventListener(\"message\", handler);\n };\n }, [fetchStatus, stopPoll]);\n\n return {\n configured,\n envManaged,\n builderEnabled,\n orgName,\n connecting,\n error,\n hasFetchedStatus,\n start,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"useBuilderStatus.js","sourceRoot":"","sources":["../../../src/client/settings/useBuilderStatus.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AACjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAqC7C;;;GAGG;AACH,MAAM,UAAU,gBAAgB;IAC9B,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,QAAQ,CAAuB,IAAI,CAAC,CAAC;IACjE,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;IAE7C,MAAM,WAAW,GAAG,WAAW,CAAC,KAAK,IAAI,EAAE;QACzC,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,eAAe,CAAC,+BAA+B,CAAC,CAAC,CAAC;YAC1E,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;gBACZ,SAAS,CAAC,IAAI,CAAC,CAAC;gBAChB,OAAO;YACT,CAAC;YACD,SAAS,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;QAC9B,CAAC;QAAC,MAAM,CAAC;YACP,SAAS,CAAC,IAAI,CAAC,CAAC;QACl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,KAAK,yBAAyB,EAAE,CAAC;gBAC7C,KAAK,aAAa,EAAE,CAAC;gBACrB,OAAO;YACT,CAAC;YACD,IAAI,IAAI,EAAE,IAAI,KAAK,uBAAuB,EAAE,CAAC;gBAC3C,IAAI,OAAO,IAAI,CAAC,OAAO,KAAK,QAAQ,IAAI,CAAC,IAAI,CAAC,OAAO;oBAAE,OAAO;gBAC9D,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YAC5B,CAAC;QACH,CAAC,CAAC;QACF,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAE5C,OAAO,GAAG,EAAE;YACV,OAAO,EAAE,KAAK,EAAE,CAAC;YACjB,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACjD,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC,CAAC;IAE5B,OAAO;QACL,UAAU;QACV,UAAU;QACV,cAAc;QACd,OAAO;QACP,UAAU;QACV,KAAK;QACL,gBAAgB;QAChB,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import { agentNativePath } from \"../api-path.js\";\nimport { useState, useEffect, useCallback, useRef } from \"react\";\nimport { getCallbackOrigin } from \"../frame.js\";\nimport { trackEvent } from \"../analytics.js\";\n\nexport interface BuilderStatus {\n configured: boolean;\n builderEnabled: boolean;\n /**\n * True when `BUILDER_PRIVATE_KEY` is set at the deploy level. This is a\n * fallback credential; per-user/org Builder connections are still allowed\n * and take precedence for that request.\n */\n envManaged?: boolean;\n credentialSource?: \"user\" | \"org\" | \"workspace\" | \"env\";\n connectUrl: string;\n cliAuthUrl?: string;\n appHost: string;\n apiHost: string;\n branchProjectIdConfigured?: boolean;\n branchProjectId?: string;\n publicKeyConfigured: boolean;\n privateKeyConfigured: boolean;\n userId?: string;\n orgName?: string;\n orgKind?: string;\n /**\n * Set when the OAuth callback ran but failed to persist credentials.\n * Surfaced as a one-shot row by the server so the connect-flow polling\n * can stop with a clear message instead of timing out at 5min.\n */\n connectError?: { message: string; at: number };\n /**\n * Set when the currently effective Builder credential was rejected by\n * Builder's API. Unlike connectError, this describes the old credential pair\n * and should not abort a new reconnect attempt while the popup is open.\n */\n authError?: { message: string; at: number };\n}\n\n/**\n * Fetches Builder connection status from /_agent-native/builder/status.\n * Re-fetches on window focus to detect post-redirect state changes.\n */\nexport function useBuilderStatus() {\n const [status, setStatus] = useState<BuilderStatus | null>(null);\n const [loading, setLoading] = useState(true);\n\n const fetchStatus = useCallback(async () => {\n try {\n const res = await fetch(agentNativePath(\"/_agent-native/builder/status\"));\n if (!res.ok) {\n setStatus(null);\n return;\n }\n setStatus(await res.json());\n } catch {\n setStatus(null);\n } finally {\n setLoading(false);\n }\n }, []);\n\n useEffect(() => {\n fetchStatus();\n\n function onFocus() {\n fetchStatus();\n }\n function onVisibility() {\n if (document.visibilityState === \"visible\") fetchStatus();\n }\n window.addEventListener(\"focus\", onFocus);\n document.addEventListener(\"visibilitychange\", onVisibility);\n // Engine connect/disconnect actions (e.g. the Builder disconnect button)\n // dispatch this event so dependent cards refresh without a full reload.\n window.addEventListener(\"agent-engine:configured-changed\", fetchStatus);\n return () => {\n window.removeEventListener(\"focus\", onFocus);\n document.removeEventListener(\"visibilitychange\", onVisibility);\n window.removeEventListener(\n \"agent-engine:configured-changed\",\n fetchStatus,\n );\n };\n }, [fetchStatus]);\n\n return { status, loading, refetch: fetchStatus };\n}\n\n// ─── useBuilderConnectFlow ──────────────────────────────────────────────────\n//\n// Shared state machine for the \"open Builder CLI-auth popup + poll\n// /builder/status until credentials land\" interaction. Replaces three\n// near-duplicate inline implementations: `BuilderCliAuthMethod` in\n// OnboardingPanel, `ConnectBuilderCard`, and `BuilderConnectCta` in\n// AssistantChat. Each consumer supplies its own popup URL / completion\n// behavior; the hook owns the polling + timeout + focus refresh.\n//\n// `popupUrl` is what we pass to `window.open`. The default\n// `/_agent-native/builder/connect` is a server-side 302 to the real\n// cli-auth URL — using it keeps the click handler synchronous so popup\n// blockers don't downgrade the open to same-tab navigation. Pass an\n// explicit `popupUrl` (e.g. the already-computed cli-auth URL) if your\n// caller already has it in hand.\n\nexport interface BuilderConnectFlowOptions {\n /** URL to synchronously open on start(). Defaults to the 302 shortcut. */\n popupUrl?: string;\n /** Low-cardinality label for the UI surface that opened Builder connect. */\n trackingSource?: string;\n /** Invoked after the status poll first sees `configured: true`. */\n onConnected?: (state: { orgName: string | null }) => void | Promise<void>;\n}\n\nexport interface BuilderConnectFlow {\n configured: boolean;\n /**\n * True when the deploy has BUILDER_PRIVATE_KEY set as a fallback. Connect\n * is still available so users can override the fallback with their own\n * Builder account.\n */\n envManaged: boolean;\n /**\n * True when the server has a Builder branch project configured for this\n * request. When false, the card surfaces a waitlist CTA instead of a Send\n * button.\n */\n builderEnabled: boolean;\n orgName: string | null;\n connecting: boolean;\n error: string | null;\n /**\n * True once the first `/builder/status` fetch has completed (successfully\n * or not). Consumers that accept an `initialConfigured` prop (e.g. agent\n * tool-call results rendered with server-side state) should treat\n * `configured`/`orgName` as authoritative only once this flips true —\n * otherwise the hook's starting `false` defaults would cause a flash\n * back to \"Connect Builder\" on first paint.\n */\n hasFetchedStatus: boolean;\n /** Open the popup and begin polling. Must be called from a user-gesture handler. */\n start: () => void;\n}\n\nconst POLL_INTERVAL_MS = 2000;\nconst POLL_TIMEOUT_MS = 5 * 60 * 1000;\nconst POPUP_CLOSED_CONFIRMATION_GRACE_MS = 5000;\nconst CALLBACK_SUCCESS_STATUS_RETRY_MS = 500;\nconst CALLBACK_SUCCESS_STATUS_RETRIES = 10;\nconst BUILDER_CONNECT_PARAM = \"_an_connect\";\nconst BUILDER_STATE_PARAM = \"_an_state\";\nconst STATUS_CONNECT_URL_TTL_MS = 9 * 60 * 1000;\n\nfunction isAgentNativeDesktop() {\n if (typeof navigator === \"undefined\") return false;\n return /AgentNativeDesktop/i.test(navigator.userAgent || \"\");\n}\n\nfunction hasSignedConnectToken(url: string | null | undefined): boolean {\n if (!url || typeof window === \"undefined\") return false;\n try {\n return new URL(url, window.location.origin).searchParams.has(\n BUILDER_CONNECT_PARAM,\n );\n } catch {\n return false;\n }\n}\n\nfunction hasSignedCallbackState(url: string | null | undefined): boolean {\n if (!url || typeof window === \"undefined\") return false;\n try {\n const parsed = new URL(url, window.location.origin);\n const redirectUrl = parsed.searchParams.get(\"redirect_url\");\n if (!redirectUrl) return false;\n return new URL(redirectUrl).searchParams.has(BUILDER_STATE_PARAM);\n } catch {\n return false;\n }\n}\n\nfunction isFreshSignedConnectUrl(\n url: string | null,\n fetchedAt: number | null,\n): url is string {\n return (\n (hasSignedConnectToken(url) || hasSignedCallbackState(url)) &&\n typeof fetchedAt === \"number\" &&\n Date.now() - fetchedAt < STATUS_CONNECT_URL_TTL_MS\n );\n}\n\nfunction isCurrentConnectError(\n error: { message: string; at: number } | undefined,\n startedAt: number | null,\n): error is { message: string; at: number } {\n if (!error?.message) return false;\n if (!startedAt) return true;\n return typeof error.at !== \"number\" || error.at >= startedAt - 1000;\n}\n\nfunction showBuilderConnectPopupPlaceholder(opened: Window) {\n // Keep opener attached: the Builder callback uses postMessage to notify the\n // settings tab that the popup completed. We still hold the WindowProxy so the\n // parent can navigate the blank popup after refreshing the signed connect URL.\n try {\n opened.document.title = \"Opening Builder.io\";\n opened.document.body.style.margin = \"0\";\n opened.document.body.style.background = \"#111\";\n opened.document.body.style.color = \"#ddd\";\n opened.document.body.style.fontFamily =\n '-apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif';\n opened.document.body.style.display = \"flex\";\n opened.document.body.style.alignItems = \"center\";\n opened.document.body.style.justifyContent = \"center\";\n opened.document.body.style.height = \"100vh\";\n opened.document.body.textContent = \"Opening Builder.io...\";\n } catch {\n // Popup may already be cross-origin or browser may block document writes.\n }\n}\n\nfunction navigateBuilderConnectPopup(opened: Window, url: string): boolean {\n try {\n opened.location.href = url;\n return true;\n } catch {\n try {\n opened.close();\n } catch {\n // Ignore close failures.\n }\n return false;\n }\n}\n\nfunction notifyAgentEngineConfiguredChanged(source: string) {\n if (typeof window === \"undefined\") return;\n window.dispatchEvent(\n new CustomEvent(\"agent-engine:configured-changed\", {\n detail: { source },\n }),\n );\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction isPopupClosed(opened: Window | null): boolean {\n if (!opened) return false;\n try {\n return opened.closed === true;\n } catch {\n return false;\n }\n}\n\nfunction isTrustedBuilderConnectMessageOrigin(origin: string): boolean {\n if (typeof window !== \"undefined\" && origin === window.location.origin) {\n return true;\n }\n try {\n const hostname = new URL(origin).hostname.toLowerCase();\n return (\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"::1\" ||\n hostname === \"builder.io\" ||\n hostname.endsWith(\".builder.io\") ||\n hostname === \"builder.my\" ||\n hostname.endsWith(\".builder.my\") ||\n hostname === \"builderio.xyz\" ||\n hostname.endsWith(\".builderio.xyz\") ||\n hostname === \"builderio.dev\" ||\n hostname.endsWith(\".builderio.dev\") ||\n hostname === \"builder.codes\" ||\n hostname.endsWith(\".builder.codes\") ||\n hostname === \"agent-native.com\" ||\n hostname.endsWith(\".agent-native.com\")\n );\n } catch {\n return false;\n }\n}\n\nexport interface OpenBuilderConnectPopupOptions {\n url?: string;\n source?: string;\n features?: string;\n}\n\nexport function openBuilderConnectPopup({\n url,\n source = \"builder_connect\",\n features = \"noopener,noreferrer\",\n}: OpenBuilderConnectPopupOptions = {}): Window | null {\n if (typeof window === \"undefined\") return null;\n const origin = getCallbackOrigin() || window.location.origin;\n const href =\n url ??\n new URL(agentNativePath(\"/_agent-native/builder/connect\"), origin).href;\n const connectUrlKind = url ? \"provided\" : \"default\";\n trackEvent(\"builder connect clicked\", {\n feature: \"builder\",\n stage: \"client\",\n source,\n connect_url_kind: connectUrlKind,\n });\n try {\n const opened = window.open(href, \"_blank\", features);\n if (!opened && !/AgentNativeDesktop/i.test(navigator.userAgent || \"\")) {\n trackEvent(\"builder connect popup blocked\", {\n feature: \"builder\",\n stage: \"client\",\n source,\n connect_url_kind: connectUrlKind,\n });\n }\n return opened;\n } catch {\n trackEvent(\"builder connect failed\", {\n feature: \"builder\",\n stage: \"client\",\n reason: \"popup_open_exception\",\n source,\n connect_url_kind: connectUrlKind,\n });\n return null;\n }\n}\n\nexport function useBuilderConnectFlow(\n opts: BuilderConnectFlowOptions = {},\n): BuilderConnectFlow {\n const {\n popupUrl,\n trackingSource = \"builder_connect_flow\",\n onConnected,\n } = opts;\n const [configured, setConfigured] = useState(false);\n const [envManaged, setEnvManaged] = useState(false);\n const [builderEnabled, setBuilderEnabled] = useState(false);\n const [orgName, setOrgName] = useState<string | null>(null);\n const [connecting, setConnecting] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [hasFetchedStatus, setHasFetchedStatus] = useState(false);\n const [statusConnectUrl, setStatusConnectUrl] = useState<string | null>(null);\n // When statusConnectUrl was last fetched. The server signs the embedded\n // _an_connect token with a 10-minute TTL; using an older URL fails the\n // cross-origin popup gate. Track freshness so start() can either use a\n // still-good direct URL (desktop) or refresh a new one inside the popup\n // gesture path (browser/editor embeds).\n const statusConnectUrlAtRef = useRef<number | null>(null);\n const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);\n const connectStartedAtRef = useRef<number | null>(null);\n const mountedRef = useRef(true);\n const notifiedConnectedRef = useRef(false);\n // Keep onConnected in a ref so start() doesn't need to re-create when the\n // caller passes an inline arrow function.\n const onConnectedRef = useRef(onConnected);\n onConnectedRef.current = onConnected;\n\n const stopPoll = useCallback(() => {\n if (pollRef.current) {\n clearInterval(pollRef.current);\n pollRef.current = null;\n }\n }, []);\n\n const fetchStatus = useCallback(async () => {\n const origin = getCallbackOrigin() || window.location.origin;\n try {\n const r = await fetch(\n new URL(agentNativePath(\"/_agent-native/builder/status\"), origin).href,\n );\n if (!r.ok) return null;\n return (await r.json()) as {\n configured: boolean;\n envManaged?: boolean;\n builderEnabled?: boolean;\n orgName?: string | null;\n connectUrl?: string;\n cliAuthUrl?: string;\n credentialSource?: \"user\" | \"org\" | \"workspace\" | \"env\";\n connectError?: { message: string; at: number };\n authError?: { message: string; at: number };\n };\n } catch {\n return null;\n }\n }, []);\n\n // Initial fetch + focus/visibility refresh so if the user completed the\n // flow in another tab (or a downgraded same-tab nav) we notice it. Also\n // listen for `agent-engine:configured-changed` so a Disconnect click in\n // Settings propagates to any connect-CTA cards rendered elsewhere in\n // the app without waiting for the next focus event.\n useEffect(() => {\n mountedRef.current = true;\n let cancelled = false;\n const refresh = async () => {\n const s = await fetchStatus();\n if (cancelled || !mountedRef.current) return;\n // Flip `hasFetchedStatus` even when the fetch failed — the caller's\n // \"use initial props until the hook has an answer\" pattern wants to\n // stop waiting after we've tried, regardless of network outcome.\n setHasFetchedStatus(true);\n if (!s) return;\n setConfigured(!!s.configured);\n setEnvManaged(!!s.envManaged);\n setBuilderEnabled(!!s.builderEnabled);\n const nextConnectUrl = s.cliAuthUrl ?? s.connectUrl ?? null;\n setStatusConnectUrl(nextConnectUrl);\n statusConnectUrlAtRef.current = nextConnectUrl ? Date.now() : null;\n const org = s.orgName ?? null;\n setOrgName(org);\n if (s.configured) {\n connectStartedAtRef.current = null;\n }\n if (s.configured && !notifiedConnectedRef.current) {\n notifiedConnectedRef.current = true;\n notifyAgentEngineConfiguredChanged(\"builder-status\");\n try {\n await onConnectedRef.current?.({ orgName: org });\n } catch {\n // The caller's callback is a UI convenience; status is already set.\n }\n } else if (!s.configured) {\n notifiedConnectedRef.current = false;\n }\n // Surface persisted auth-failure messages on idle refreshes, but don't\n // let an old rejected credential abort a new reconnect popup while the\n // user is still choosing a Builder space.\n const activeConnectStartedAt = connectStartedAtRef.current;\n if (isCurrentConnectError(s.connectError, activeConnectStartedAt)) {\n setError(s.connectError.message);\n } else if (!activeConnectStartedAt && s.authError?.message) {\n setError(s.authError.message);\n } else if (s.configured) {\n setError(null);\n }\n };\n refresh();\n const onVisible = () => {\n if (document.visibilityState === \"visible\") refresh();\n };\n window.addEventListener(\"focus\", refresh);\n document.addEventListener(\"visibilitychange\", onVisible);\n window.addEventListener(\"agent-engine:configured-changed\", refresh);\n return () => {\n cancelled = true;\n mountedRef.current = false;\n window.removeEventListener(\"focus\", refresh);\n document.removeEventListener(\"visibilitychange\", onVisible);\n window.removeEventListener(\"agent-engine:configured-changed\", refresh);\n stopPoll();\n };\n }, [fetchStatus, stopPoll]);\n\n const start = useCallback(() => {\n stopPoll();\n const started = Date.now();\n let openedPopup: Window | null = null;\n let popupClosedAt: number | null = null;\n connectStartedAtRef.current = started;\n setConnecting(true);\n setError(null);\n\n // Open SYNCHRONOUSLY inside the caller's click handler — any await\n // before window.open lets the user-gesture token expire, which causes\n // popup blockers to block entirely or fall back to same-tab navigation.\n const origin = getCallbackOrigin() || window.location.origin;\n const cachedFreshUrl = isFreshSignedConnectUrl(\n statusConnectUrl,\n statusConnectUrlAtRef.current,\n )\n ? statusConnectUrl\n : null;\n // popupUrl props and statusConnectUrl are signed URLs minted before the\n // click. In web browsers, always refresh inside an about:blank popup so a\n // server/package restart cannot leave the user with a stale signed state.\n // Desktop keeps the direct path because the Electron shell owns the popup.\n const signedPropUrl = hasSignedConnectToken(popupUrl) ? popupUrl : null;\n const signedCliPropUrl = hasSignedCallbackState(popupUrl) ? popupUrl : null;\n const fallbackUrl = new URL(\n agentNativePath(\"/_agent-native/builder/connect\"),\n origin,\n ).href;\n const directUrl =\n cachedFreshUrl ?? signedCliPropUrl ?? signedPropUrl ?? fallbackUrl;\n\n if (isAgentNativeDesktop()) {\n const opened = openBuilderConnectPopup({\n url: directUrl,\n source: trackingSource,\n });\n openedPopup = opened;\n if (!opened) {\n // Agent Native Desktop handles the popup in Electron and reports\n // null to the embedded webview, so null is not a blocker here.\n }\n } else {\n const opened = openBuilderConnectPopup({\n url: \"about:blank\",\n source: trackingSource,\n features: \"width=600,height=700\",\n });\n if (!opened) {\n connectStartedAtRef.current = null;\n setConnecting(false);\n setError(\"Couldn't open Builder. Allow popups and try again.\");\n return;\n }\n openedPopup = opened;\n showBuilderConnectPopupPlaceholder(opened);\n void (async () => {\n const s = await fetchStatus();\n if (!mountedRef.current) {\n try {\n opened.close();\n } catch {\n // Ignore close failures.\n }\n return;\n }\n if (s) {\n setHasFetchedStatus(true);\n setConfigured(!!s.configured);\n setEnvManaged(!!s.envManaged);\n setBuilderEnabled(!!s.builderEnabled);\n const nextConnectUrl = s.cliAuthUrl ?? s.connectUrl ?? null;\n setStatusConnectUrl(nextConnectUrl);\n statusConnectUrlAtRef.current = nextConnectUrl ? Date.now() : null;\n setOrgName(s.orgName ?? null);\n }\n\n const freshUrl = s?.cliAuthUrl ?? s?.connectUrl ?? null;\n if (!freshUrl) {\n try {\n opened.close();\n } catch {\n // Ignore close failures.\n }\n stopPoll();\n connectStartedAtRef.current = null;\n setConnecting(false);\n setError(\n \"Couldn't start Builder connect. Refresh this page and try again.\",\n );\n return;\n }\n if (!navigateBuilderConnectPopup(opened, freshUrl)) {\n stopPoll();\n connectStartedAtRef.current = null;\n setConnecting(false);\n setError(\n \"Couldn't navigate the Builder popup. Allow popups and try again.\",\n );\n }\n })();\n }\n\n pollRef.current = setInterval(async () => {\n const s = await fetchStatus();\n if (!mountedRef.current) {\n stopPoll();\n return;\n }\n if (s?.configured) {\n stopPoll();\n setConfigured(true);\n setEnvManaged(!!s.envManaged);\n setBuilderEnabled(!!s.builderEnabled);\n const nextConnectUrl = s.cliAuthUrl ?? s.connectUrl ?? null;\n setStatusConnectUrl(nextConnectUrl);\n statusConnectUrlAtRef.current = nextConnectUrl ? Date.now() : null;\n const org = s.orgName ?? null;\n setOrgName(org);\n setConnecting(false);\n connectStartedAtRef.current = null;\n notifiedConnectedRef.current = true;\n notifyAgentEngineConfiguredChanged(\"builder-connect\");\n try {\n await onConnectedRef.current?.({ orgName: org });\n } catch {\n // Consumer's callback failed; we've already flipped the UI state\n // to connected. Swallow so we don't re-arm the flow.\n }\n } else if (isCurrentConnectError(s?.connectError, started)) {\n // OAuth callback ran but writeBuilderCredentials threw — surface the\n // real error instead of letting the user wait 5 minutes for timeout.\n stopPoll();\n connectStartedAtRef.current = null;\n setConnecting(false);\n setError(\n `Couldn't save Builder credentials: ${s.connectError.message}. Try again or contact support.`,\n );\n } else if (isPopupClosed(openedPopup)) {\n popupClosedAt ??= Date.now();\n if (Date.now() - popupClosedAt > POPUP_CLOSED_CONFIRMATION_GRACE_MS) {\n stopPoll();\n connectStartedAtRef.current = null;\n setConnecting(false);\n trackEvent(\"builder connect failed\", {\n feature: \"builder\",\n stage: \"client\",\n reason: \"popup_closed_without_status\",\n source: trackingSource,\n });\n setError(\n \"Builder finished, but this workspace couldn't confirm the saved credentials. Refresh this page or try Connect Builder.io again.\",\n );\n }\n } else if (Date.now() - started > POLL_TIMEOUT_MS) {\n stopPoll();\n connectStartedAtRef.current = null;\n setConnecting(false);\n trackEvent(\"builder connect failed\", {\n feature: \"builder\",\n stage: \"client\",\n reason: \"timeout\",\n source: trackingSource,\n });\n setError(\n \"Didn't hear back from Builder in 5 minutes. Allow popups and try again.\",\n );\n }\n }, POLL_INTERVAL_MS);\n }, [fetchStatus, popupUrl, statusConnectUrl, stopPoll, trackingSource]);\n\n // Popup-side fast path: the callback page broadcasts a message so we stop\n // polling immediately rather than waiting for the next 2s tick.\n //\n // We listen on BroadcastChannel (same-origin, works with noopener popups)\n // AND on window.message (legacy path for environments without BC or for\n // popups that still have opener access). Both paths are safe to have open\n // simultaneously \\u2014 the first one to fire wins and the error is deduplicated\n // by the stopPoll() call which is idempotent.\n useEffect(() => {\n let channel: BroadcastChannel | null = null;\n const handleError = (message: string) => {\n stopPoll();\n connectStartedAtRef.current = null;\n setConnecting(false);\n setError(`Couldn't save Builder credentials: ${message}.`);\n };\n const handleSuccess = async () => {\n let s: Awaited<ReturnType<typeof fetchStatus>> = null;\n for (let i = 0; i < CALLBACK_SUCCESS_STATUS_RETRIES; i += 1) {\n s = await fetchStatus();\n if (!mountedRef.current) return;\n if (\n s?.configured ||\n isCurrentConnectError(s?.connectError, connectStartedAtRef.current)\n ) {\n break;\n }\n if (i < CALLBACK_SUCCESS_STATUS_RETRIES - 1) {\n await delay(CALLBACK_SUCCESS_STATUS_RETRY_MS);\n }\n }\n if (!mountedRef.current) return;\n if (!s?.configured) {\n const connectError = isCurrentConnectError(\n s?.connectError,\n connectStartedAtRef.current,\n )\n ? s?.connectError\n : null;\n stopPoll();\n setHasFetchedStatus(true);\n if (s) {\n setConfigured(false);\n setEnvManaged(!!s.envManaged);\n setBuilderEnabled(!!s.builderEnabled);\n const nextConnectUrl = s.cliAuthUrl ?? s.connectUrl ?? null;\n setStatusConnectUrl(nextConnectUrl);\n statusConnectUrlAtRef.current = nextConnectUrl ? Date.now() : null;\n setOrgName(s.orgName ?? null);\n }\n connectStartedAtRef.current = null;\n setConnecting(false);\n setError(\n connectError\n ? `Couldn't save Builder credentials: ${connectError.message}. Try again or contact support.`\n : \"Builder finished, but this workspace couldn't confirm the saved credentials. Refresh this page or try Connect Builder.io again.\",\n );\n return;\n }\n stopPoll();\n setHasFetchedStatus(true);\n setConfigured(true);\n setEnvManaged(!!s.envManaged);\n setBuilderEnabled(!!s.builderEnabled);\n const nextConnectUrl = s.cliAuthUrl ?? s.connectUrl ?? null;\n setStatusConnectUrl(nextConnectUrl);\n statusConnectUrlAtRef.current = nextConnectUrl ? Date.now() : null;\n const org = s.orgName ?? null;\n setOrgName(org);\n setConnecting(false);\n connectStartedAtRef.current = null;\n notifiedConnectedRef.current = true;\n notifyAgentEngineConfiguredChanged(\"builder-connect-message\");\n try {\n await onConnectedRef.current?.({ orgName: org });\n } catch {\n // The caller's callback is a UI convenience; status is already set.\n }\n };\n\n try {\n channel = new BroadcastChannel(`builder-connect:${window.location.host}`);\n channel.onmessage = (e: MessageEvent) => {\n const data = e.data as { type?: string; message?: string } | undefined;\n if (data?.type === \"builder-connect-success\") {\n void handleSuccess();\n return;\n }\n if (data?.type === \"builder-connect-error\") {\n if (typeof data.message !== \"string\" || !data.message) return;\n handleError(data.message);\n }\n };\n } catch {\n // BroadcastChannel not available (rare) \\u2014 fall through to postMessage.\n }\n\n const handler = (e: MessageEvent) => {\n if (!isTrustedBuilderConnectMessageOrigin(e.origin)) return;\n const data = e.data as { type?: string; message?: string } | undefined;\n if (data?.type === \"builder-connect-success\") {\n void handleSuccess();\n return;\n }\n if (data?.type === \"builder-connect-error\") {\n if (typeof data.message !== \"string\" || !data.message) return;\n handleError(data.message);\n }\n };\n window.addEventListener(\"message\", handler);\n\n return () => {\n channel?.close();\n window.removeEventListener(\"message\", handler);\n };\n }, [fetchStatus, stopPoll]);\n\n return {\n configured,\n envManaged,\n builderEnabled,\n orgName,\n connecting,\n error,\n hasFetchedStatus,\n start,\n };\n}\n"]}
|
|
@@ -63,7 +63,7 @@ describe("useBuilderConnectFlow", () => {
|
|
|
63
63
|
vi.useRealTimers();
|
|
64
64
|
vi.unstubAllGlobals();
|
|
65
65
|
});
|
|
66
|
-
it("opens
|
|
66
|
+
it("opens a blank web popup and navigates to a freshly fetched cli-auth URL", async () => {
|
|
67
67
|
setUserAgent("Mozilla/5.0 Chrome/140.0");
|
|
68
68
|
const popup = createPopupStub();
|
|
69
69
|
openSpy.mockReturnValue(popup);
|
|
@@ -74,9 +74,11 @@ describe("useBuilderConnectFlow", () => {
|
|
|
74
74
|
});
|
|
75
75
|
await act(async () => {
|
|
76
76
|
container.querySelector("button")?.click();
|
|
77
|
+
await Promise.resolve();
|
|
78
|
+
await Promise.resolve();
|
|
77
79
|
});
|
|
78
|
-
expect(openSpy).toHaveBeenCalledWith(
|
|
79
|
-
expect(popup.location.href).toBe(
|
|
80
|
+
expect(openSpy).toHaveBeenCalledWith("about:blank", "_blank", "width=600,height=700");
|
|
81
|
+
expect(popup.location.href).toBe(signedCliAuthUrl);
|
|
80
82
|
expect(container.textContent).not.toContain("Popup blocked");
|
|
81
83
|
});
|
|
82
84
|
it("refreshes an un-timestamped signed prop URL before navigating web popups", async () => {
|
|
@@ -155,6 +157,79 @@ describe("useBuilderConnectFlow", () => {
|
|
|
155
157
|
});
|
|
156
158
|
expect(container.textContent).toContain("configured");
|
|
157
159
|
});
|
|
160
|
+
it("clears the spinner when the callback succeeds but status never confirms credentials", async () => {
|
|
161
|
+
vi.useFakeTimers();
|
|
162
|
+
vi.setSystemTime(new Date("2026-05-14T12:00:00.000Z"));
|
|
163
|
+
setUserAgent("Mozilla/5.0 Chrome/140.0");
|
|
164
|
+
const popup = createPopupStub();
|
|
165
|
+
openSpy.mockReturnValue(popup);
|
|
166
|
+
vi.mocked(fetch).mockImplementation(async () => jsonResponse({
|
|
167
|
+
configured: false,
|
|
168
|
+
envManaged: false,
|
|
169
|
+
builderEnabled: true,
|
|
170
|
+
orgName: null,
|
|
171
|
+
cliAuthUrl: signedCliAuthUrl,
|
|
172
|
+
connectUrl: "http://localhost:3000/_agent-native/builder/connect?_an_connect=signed",
|
|
173
|
+
appHost: "https://builder.io",
|
|
174
|
+
apiHost: "https://api.builder.io",
|
|
175
|
+
publicKeyConfigured: false,
|
|
176
|
+
privateKeyConfigured: false,
|
|
177
|
+
}));
|
|
178
|
+
await act(async () => {
|
|
179
|
+
root.render(_jsx(BuilderConnectProbe, {}));
|
|
180
|
+
await Promise.resolve();
|
|
181
|
+
});
|
|
182
|
+
await act(async () => {
|
|
183
|
+
container.querySelector("button")?.click();
|
|
184
|
+
await Promise.resolve();
|
|
185
|
+
await Promise.resolve();
|
|
186
|
+
});
|
|
187
|
+
expect(container.textContent).toContain("not-configured connecting");
|
|
188
|
+
await act(async () => {
|
|
189
|
+
window.dispatchEvent(new MessageEvent("message", {
|
|
190
|
+
origin: "https://agent-workspace.builder.io",
|
|
191
|
+
data: { type: "builder-connect-success" },
|
|
192
|
+
}));
|
|
193
|
+
await vi.advanceTimersByTimeAsync(5000);
|
|
194
|
+
});
|
|
195
|
+
expect(container.textContent).toContain("not-configured idle");
|
|
196
|
+
expect(container.textContent).toContain("couldn't confirm");
|
|
197
|
+
});
|
|
198
|
+
it("clears the spinner when the popup closes before status confirms credentials", async () => {
|
|
199
|
+
vi.useFakeTimers();
|
|
200
|
+
vi.setSystemTime(new Date("2026-05-14T12:00:00.000Z"));
|
|
201
|
+
setUserAgent("Mozilla/5.0 Chrome/140.0");
|
|
202
|
+
const popup = createPopupStub();
|
|
203
|
+
openSpy.mockReturnValue(popup);
|
|
204
|
+
vi.mocked(fetch).mockImplementation(async () => jsonResponse({
|
|
205
|
+
configured: false,
|
|
206
|
+
envManaged: false,
|
|
207
|
+
builderEnabled: true,
|
|
208
|
+
orgName: null,
|
|
209
|
+
cliAuthUrl: signedCliAuthUrl,
|
|
210
|
+
connectUrl: "http://localhost:3000/_agent-native/builder/connect?_an_connect=signed",
|
|
211
|
+
appHost: "https://builder.io",
|
|
212
|
+
apiHost: "https://api.builder.io",
|
|
213
|
+
publicKeyConfigured: false,
|
|
214
|
+
privateKeyConfigured: false,
|
|
215
|
+
}));
|
|
216
|
+
await act(async () => {
|
|
217
|
+
root.render(_jsx(BuilderConnectProbe, {}));
|
|
218
|
+
await Promise.resolve();
|
|
219
|
+
});
|
|
220
|
+
await act(async () => {
|
|
221
|
+
container.querySelector("button")?.click();
|
|
222
|
+
await Promise.resolve();
|
|
223
|
+
await Promise.resolve();
|
|
224
|
+
});
|
|
225
|
+
expect(container.textContent).toContain("not-configured connecting");
|
|
226
|
+
popup.closed = true;
|
|
227
|
+
await act(async () => {
|
|
228
|
+
await vi.advanceTimersByTimeAsync(8000);
|
|
229
|
+
});
|
|
230
|
+
expect(container.textContent).toContain("not-configured idle");
|
|
231
|
+
expect(container.textContent).toContain("couldn't confirm");
|
|
232
|
+
});
|
|
158
233
|
it("does not replace the desktop webview when Electron reports a handled popup as null", async () => {
|
|
159
234
|
setUserAgent("Mozilla/5.0 Electron/41.2.2 AgentNativeDesktop/0.1.7");
|
|
160
235
|
await act(async () => {
|
|
@@ -174,7 +249,7 @@ describe("useBuilderConnectFlow", () => {
|
|
|
174
249
|
const popup = createPopupStub();
|
|
175
250
|
openSpy.mockReturnValue(popup);
|
|
176
251
|
const signedConnectUrl = "http://localhost:3000/_agent-native/builder/connect?_an_connect=signed";
|
|
177
|
-
vi.mocked(fetch).
|
|
252
|
+
vi.mocked(fetch).mockImplementation(async () => jsonResponse({
|
|
178
253
|
configured: false,
|
|
179
254
|
envManaged: true,
|
|
180
255
|
builderEnabled: true,
|
|
@@ -196,8 +271,11 @@ describe("useBuilderConnectFlow", () => {
|
|
|
196
271
|
expect(container.textContent).toContain("Private key does not match spaceId");
|
|
197
272
|
await act(async () => {
|
|
198
273
|
container.querySelector("button")?.click();
|
|
274
|
+
await Promise.resolve();
|
|
275
|
+
await Promise.resolve();
|
|
199
276
|
});
|
|
200
|
-
expect(openSpy).toHaveBeenCalledWith(
|
|
277
|
+
expect(openSpy).toHaveBeenCalledWith("about:blank", "_blank", "width=600,height=700");
|
|
278
|
+
expect(popup.location.href).toBe(signedConnectUrl);
|
|
201
279
|
expect(container.textContent).toContain("not-configured connecting");
|
|
202
280
|
expect(container.textContent).not.toContain("Private key does not match spaceId");
|
|
203
281
|
await act(async () => {
|
|
@@ -213,7 +291,7 @@ describe("useBuilderConnectFlow", () => {
|
|
|
213
291
|
const popup = createPopupStub();
|
|
214
292
|
openSpy.mockReturnValue(popup);
|
|
215
293
|
const signedConnectUrl = "http://localhost:3000/_agent-native/builder/connect?_an_connect=signed";
|
|
216
|
-
vi.mocked(fetch).
|
|
294
|
+
vi.mocked(fetch).mockImplementation(async () => jsonResponse({
|
|
217
295
|
configured: false,
|
|
218
296
|
envManaged: false,
|
|
219
297
|
builderEnabled: true,
|