@agent-native/core 0.77.16 → 0.77.18
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/corpus/README.md +1 -1
- package/corpus/core/CHANGELOG.md +19 -0
- package/corpus/core/package.json +1 -1
- package/corpus/core/src/agent/production-agent.ts +21 -5
- package/corpus/core/src/client/AgentPanel.tsx +4 -0
- package/corpus/core/src/client/org/OrgSwitcher.tsx +4 -0
- package/corpus/core/src/client/use-db-sync.ts +19 -2
- package/corpus/core/src/server/auth-marketing.ts +15 -0
- package/corpus/core/src/server/onboarding-html.ts +47 -1
- package/corpus/templates/analytics/.agents/skills/dashboard-management/SKILL.md +76 -0
- package/corpus/templates/analytics/actions/update-dashboard.ts +1 -0
- package/corpus/templates/analytics/app/components/dashboard/SqlChart.tsx +13 -2
- package/corpus/templates/analytics/app/i18n-data.ts +10 -0
- package/corpus/templates/analytics/app/lib/sql-query.ts +97 -21
- package/corpus/templates/analytics/app/pages/adhoc/sql-dashboard/SqlChartCard.tsx +22 -1
- package/corpus/templates/analytics/app/root.tsx +15 -6
- package/corpus/templates/analytics/changelog/2026-06-25-dashboard-charts-no-longer-refresh-in-the-background-during-.md +6 -0
- package/corpus/templates/analytics/changelog/2026-06-25-first-party-dashboards-use-indexed-event-dates-for-faster-da.md +6 -0
- package/corpus/templates/analytics/changelog/2026-06-25-retention-and-active-user-dashboard-panels-now-count-account.md +6 -0
- package/corpus/templates/analytics/seeds/dashboards/agent-native-templates-first-party.json +58 -58
- package/corpus/templates/analytics/server/db/schema.ts +2 -0
- package/corpus/templates/analytics/server/handlers/sql-query.ts +1 -1
- package/corpus/templates/analytics/server/lib/dashboard-catalog.ts +1 -1
- package/corpus/templates/analytics/server/lib/first-party-analytics.ts +16 -6
- package/corpus/templates/analytics/server/lib/first-party-metric-catalog.ts +88 -56
- package/corpus/templates/analytics/server/plugins/db.ts +73 -0
- package/corpus/templates/clips/AGENTS.md +5 -0
- package/corpus/templates/clips/changelog/2026-06-25-github-issue-and-pull-request-pages-can-now-preview-playable.md +6 -0
- package/corpus/templates/clips/chrome-extension/PERMISSIONS.md +8 -2
- package/corpus/templates/clips/chrome-extension/public/manifest.json +14 -2
- package/corpus/templates/clips/chrome-extension/src/github-preview-content.ts +233 -0
- package/corpus/templates/clips/chrome-extension/src/github-preview.html +12 -0
- package/corpus/templates/clips/chrome-extension/src/github-preview.ts +414 -0
- package/corpus/templates/clips/chrome-extension/vite.config.ts +5 -0
- package/corpus/templates/mail/actions/archive-email.ts +13 -3
- package/corpus/templates/mail/app/hooks/use-emails.ts +5 -2
- package/corpus/templates/mail/changelog/2026-06-25-archive-failures-now-explain-when-gmail-needs-reconnecting-p.md +6 -0
- package/corpus/templates/mail/shared/archive-errors.ts +137 -0
- package/corpus/templates/plan/changelog/2026-06-25-hosted-signup-now-shows-how-to-switch-visual-plan-to-local-files.md +6 -0
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +19 -5
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/client/AgentPanel.d.ts.map +1 -1
- package/dist/client/AgentPanel.js +2 -1
- package/dist/client/AgentPanel.js.map +1 -1
- package/dist/client/org/OrgSwitcher.d.ts.map +1 -1
- package/dist/client/org/OrgSwitcher.js +3 -1
- package/dist/client/org/OrgSwitcher.js.map +1 -1
- package/dist/client/use-db-sync.d.ts +9 -0
- package/dist/client/use-db-sync.d.ts.map +1 -1
- package/dist/client/use-db-sync.js +8 -1
- package/dist/client/use-db-sync.js.map +1 -1
- package/dist/file-upload/actions/upload-image.d.ts +2 -2
- package/dist/notifications/routes.d.ts +2 -2
- package/dist/observability/routes.d.ts +6 -6
- package/dist/server/auth-marketing.d.ts +4 -0
- package/dist/server/auth-marketing.d.ts.map +1 -1
- package/dist/server/auth-marketing.js +9 -0
- package/dist/server/auth-marketing.js.map +1 -1
- package/dist/server/onboarding-html.d.ts.map +1 -1
- package/dist/server/onboarding-html.js +46 -1
- package/dist/server/onboarding-html.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OrgSwitcher.d.ts","sourceRoot":"","sources":["../../../src/client/org/OrgSwitcher.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"OrgSwitcher.d.ts","sourceRoot":"","sources":["../../../src/client/org/OrgSwitcher.tsx"],"names":[],"mappings":"AA0DA,MAAM,WAAW,gBAAgB;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,2EAA2E;IAC3E,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,6EAA6E;IAC7E,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B;AA6MD;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,EAC1B,SAAS,EACT,cAAc,EACd,YAAY,EACZ,YAAiD,GAClD,EAAE,gBAAgB,sCA2blB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import * as PopoverPrimitive from "@radix-ui/react-popover";
|
|
3
|
-
import { IconApps, IconArrowUpRight, IconBrain, IconBrandJira, IconBrush, IconBuilding, IconCalendar, IconCalendarTime, IconChartBar, IconCheck, IconChevronRight, IconClipboardList, IconCode, IconContract, IconFileText, IconLoader2, IconLogout, IconMail, IconMessageCircle, IconMicrophone, IconNote, IconPhone, IconPhoto, IconPlus, IconPresentation, IconScreenShare, IconSelector, IconSettings, IconStack2, IconUser, IconUserPlus, IconUsers, IconVideo, IconWorld, } from "@tabler/icons-react";
|
|
3
|
+
import { IconApps, IconArrowUpRight, IconBrain, IconBrandJira, IconBrush, IconBuilding, IconCalendar, IconCalendarTime, IconChartBar, IconCheck, IconChevronRight, IconClipboardList, IconCode, IconContract, IconFileText, IconLayoutBoard, IconLoader2, IconLogout, IconMail, IconMessageCircle, IconMicrophone, IconNote, IconPhone, IconPhoto, IconPlus, IconPresentation, IconRoute, IconScreenShare, IconSelector, IconSettings, IconStack2, IconUser, IconUserPlus, IconUsers, IconVideo, IconWorld, } from "@tabler/icons-react";
|
|
4
4
|
import { useState } from "react";
|
|
5
5
|
import { useNavigate } from "react-router";
|
|
6
6
|
import { agentNativePath } from "../api-path.js";
|
|
@@ -28,6 +28,7 @@ const APP_ICON_MAP = {
|
|
|
28
28
|
Mail: IconMail,
|
|
29
29
|
CalendarDays: IconCalendar,
|
|
30
30
|
FileText: IconFileText,
|
|
31
|
+
LayoutBoard: IconLayoutBoard,
|
|
31
32
|
BarChart2: IconChartBar,
|
|
32
33
|
GalleryHorizontal: IconPresentation,
|
|
33
34
|
Video: IconVideo,
|
|
@@ -37,6 +38,7 @@ const APP_ICON_MAP = {
|
|
|
37
38
|
Code: IconCode,
|
|
38
39
|
Contract: IconContract,
|
|
39
40
|
MessageCircle: IconMessageCircle,
|
|
41
|
+
Route: IconRoute,
|
|
40
42
|
ScreenShare: IconScreenShare,
|
|
41
43
|
Brush: IconBrush,
|
|
42
44
|
Brain: IconBrain,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OrgSwitcher.js","sourceRoot":"","sources":["../../../src/client/org/OrgSwitcher.tsx"],"names":[],"mappings":";AAAA,OAAO,KAAK,gBAAgB,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EACL,QAAQ,EACR,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,SAAS,EACT,YAAY,EACZ,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,QAAQ,EACR,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,UAAU,EACV,QAAQ,EACR,iBAAiB,EACjB,cAAc,EACd,QAAQ,EACR,SAAS,EACT,SAAS,EACT,QAAQ,EACR,gBAAgB,EAChB,eAAe,EACf,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,QAA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GAA8G,uBAGjH,EACT,iBACE,IAAI,EAAC,QAAQ,EACb,QAAQ,EAAE,YAAY,CAAC,SAAS,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,EACvD,SAAS,EAAC,yKAAyK,YAElL,YAAY,CAAC,SAAS,CAAC,CAAC,CAAC,CACxB,KAAC,WAAW,IAAC,SAAS,EAAC,sBAAsB,GAAG,CACjD,CAAC,CAAC,CAAC,CACF,aAAa,CACd,GACM,IACL,IACD,CACR,IACwB,GACH,IACJ,CACzB,CAAC;AACJ,CAAC","sourcesContent":["import * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport {\n IconApps,\n IconArrowUpRight,\n IconBrain,\n IconBrandJira,\n IconBrush,\n IconBuilding,\n IconCalendar,\n IconCalendarTime,\n IconChartBar,\n IconCheck,\n IconChevronRight,\n IconClipboardList,\n IconCode,\n IconContract,\n IconFileText,\n IconLoader2,\n IconLogout,\n IconMail,\n IconMessageCircle,\n IconMicrophone,\n IconNote,\n IconPhone,\n IconPhoto,\n IconPlus,\n IconPresentation,\n IconScreenShare,\n IconSelector,\n IconSettings,\n IconStack2,\n IconUser,\n IconUserPlus,\n IconUsers,\n IconVideo,\n IconWorld,\n} from \"@tabler/icons-react\";\nimport { useState } from \"react\";\nimport { useNavigate } from \"react-router\";\n\nimport { agentNativePath } from \"../api-path.js\";\nimport {\n useOrg,\n useSwitchOrg,\n useCreateOrg,\n useInviteMember,\n useAcceptInvitation,\n useJoinByDomain,\n} from \"./hooks.js\";\nimport {\n ORG_SWITCHER_MAX_APP_LINKS,\n useOrgSwitcherAppLinks,\n visibleOrgAppLinks,\n type OrgSwitcherAppLink,\n} from \"./workspace-app-links.js\";\n\nexport interface OrgSwitcherProps {\n className?: string;\n /** Hide entirely when the user only belongs to one org. Default: false. */\n hideWhenSingle?: boolean;\n /** Keep the switcher's button height reserved while org state is loading. */\n reserveSpace?: boolean;\n /**\n * Path to navigate to when the user clicks \"Organization settings\".\n * Defaults to `/team`, the standard organization-management route. Templates\n * with an established org surface can pass their own path; pass `null` to\n * only open the in-sidebar settings panel.\n */\n settingsPath?: string | null;\n}\n\nfunction personalLabelFromEmail(email: string | null | undefined): string {\n if (!email) return \"Personal\";\n const local = email.split(\"@\")[0] ?? email;\n const cleaned = local.replace(/[._-]+/g, \" \").trim();\n if (!cleaned) return \"Personal\";\n return cleaned\n .split(\" \")\n .filter(Boolean)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(\" \");\n}\n\ntype Mode = \"list\" | \"create\" | \"invite\";\n\nconst POPOVER_CONTENT_CLASS =\n \"z-50 min-w-[14rem] rounded-md border border-border bg-popover py-1 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2\";\n\nconst ITEM_CLASS =\n \"flex w-full items-center gap-2 px-2.5 py-1.5 text-xs text-foreground hover:bg-accent focus-visible:bg-accent focus:outline-none disabled:opacity-50 disabled:pointer-events-none\";\n\nconst SECTION_LABEL_CLASS =\n \"px-2.5 pt-1 pb-0.5 text-[10px] uppercase tracking-wide text-muted-foreground\";\n\nconst APP_SUBMENU_CONTENT_CLASS =\n \"z-50 w-72 rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2\";\n\nconst DEFAULT_ORGANIZATION_SETTINGS_PATH = \"/team\";\n\nconst APP_ICON_MAP: Record<string, typeof IconApps> = {\n Mail: IconMail,\n CalendarDays: IconCalendar,\n FileText: IconFileText,\n BarChart2: IconChartBar,\n GalleryHorizontal: IconPresentation,\n Video: IconVideo,\n BrandJira: IconBrandJira,\n ClipboardList: IconClipboardList,\n Users: IconUsers,\n Code: IconCode,\n Contract: IconContract,\n MessageCircle: IconMessageCircle,\n ScreenShare: IconScreenShare,\n Brush: IconBrush,\n Brain: IconBrain,\n Phone: IconPhone,\n Note: IconNote,\n Microphone: IconMicrophone,\n CalendarTime: IconCalendarTime,\n Globe: IconWorld,\n Photo: IconPhoto,\n};\n\nfunction appMenuIcon(app: OrgSwitcherAppLink): typeof IconApps {\n if (app.icon) return APP_ICON_MAP[app.icon] ?? IconStack2;\n return app.isDispatch ? IconMessageCircle : IconStack2;\n}\n\nfunction organizationSettingsPath(path: string): string {\n return `${path.replace(/#.*$/, \"\")}#workspace-settings`;\n}\n\nfunction AppMenuLink({\n app,\n onNavigate,\n}: {\n app: OrgSwitcherAppLink;\n onNavigate: () => void;\n}) {\n const Icon = appMenuIcon(app);\n return (\n <a\n href={app.href}\n onClick={onNavigate}\n className={`flex items-center gap-2 rounded-sm px-2.5 py-2 text-xs outline-none hover:bg-accent focus:bg-accent ${\n app.isDispatch ? \"border border-primary/20 bg-primary/5\" : \"\"\n }`}\n >\n <span\n className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-md ${\n app.isDispatch\n ? \"bg-primary text-primary-foreground\"\n : \"bg-muted text-muted-foreground\"\n }`}\n >\n <Icon className=\"h-3.5 w-3.5\" />\n </span>\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate font-medium text-foreground\">\n {app.name}\n </span>\n <span className=\"block truncate text-[11px] text-muted-foreground\">\n {app.isDispatch\n ? \"Main hub\"\n : app.status === \"pending\"\n ? \"Building\"\n : \"Open app\"}\n </span>\n </span>\n <IconArrowUpRight className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n </a>\n );\n}\n\nfunction AppsSubmenu({\n apps,\n isWorkspace,\n isLoading,\n dispatchHref,\n dispatchAllAppsHref,\n onNavigate,\n}: {\n apps: OrgSwitcherAppLink[];\n isWorkspace: boolean;\n isLoading: boolean;\n dispatchHref: string;\n dispatchAllAppsHref: string;\n onNavigate: () => void;\n}) {\n const { links, overflowCount } = visibleOrgAppLinks(apps);\n const visibleDispatchApp = links.find((app) => app.isDispatch);\n const dispatchApp =\n visibleDispatchApp ??\n ({\n id: \"dispatch\",\n name: \"Dispatch\",\n href: dispatchHref,\n isDispatch: true,\n status: \"ready\",\n } satisfies OrgSwitcherAppLink);\n const visibleNonDispatch = links\n .filter((app) => !app.isDispatch)\n .slice(0, visibleDispatchApp ? undefined : ORG_SWITCHER_MAX_APP_LINKS - 1);\n const shownCount = (dispatchApp ? 1 : 0) + visibleNonDispatch.length;\n const remainingCount = Math.max(overflowCount, apps.length - shownCount);\n\n return (\n <PopoverPrimitive.Root>\n <PopoverPrimitive.Trigger asChild>\n <button type=\"button\" className={`${ITEM_CLASS} cursor-pointer`}>\n <IconApps className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"flex-1 text-start\">Apps</span>\n <span className=\"text-[11px] text-muted-foreground\">\n {isLoading ? (\n <IconLoader2 className=\"h-3 w-3 animate-spin\" />\n ) : (\n apps.length\n )}\n </span>\n <IconChevronRight className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground rtl:-scale-x-100\" />\n </button>\n </PopoverPrimitive.Trigger>\n <PopoverPrimitive.Portal>\n <PopoverPrimitive.Content\n side=\"right\"\n align=\"start\"\n sideOffset={8}\n collisionPadding={12}\n className={APP_SUBMENU_CONTENT_CLASS}\n >\n <div className=\"px-2.5 py-1.5\">\n <div className=\"text-[10px] uppercase tracking-wide text-muted-foreground\">\n {isWorkspace ? \"Workspace apps\" : \"Default apps\"}\n </div>\n <div className=\"mt-0.5 text-[11px] text-muted-foreground\">\n {isWorkspace\n ? \"Dispatch is the workspace hub.\"\n : \"Dispatch is the home base.\"}\n </div>\n </div>\n\n <AppMenuLink app={dispatchApp} onNavigate={onNavigate} />\n\n {visibleNonDispatch.length > 0 && (\n <div className=\"my-1 h-px bg-border\" />\n )}\n {visibleNonDispatch.map((app) => (\n <AppMenuLink key={app.id} app={app} onNavigate={onNavigate} />\n ))}\n\n {remainingCount > 0 && (\n <>\n <div className=\"my-1 h-px bg-border\" />\n <a\n href={dispatchAllAppsHref}\n onClick={onNavigate}\n className=\"flex items-center gap-2 rounded-sm px-2.5 py-1.5 text-xs text-foreground outline-none hover:bg-accent focus:bg-accent\"\n >\n <IconMessageCircle className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"flex-1\">\n {`View ${remainingCount} more in Dispatch`}\n </span>\n <IconArrowUpRight className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n </a>\n </>\n )}\n </PopoverPrimitive.Content>\n </PopoverPrimitive.Portal>\n </PopoverPrimitive.Root>\n );\n}\n\n/**\n * Compact org switcher button. Shows the active org (or \"Personal\" when the\n * user has none); opens a popover with the user's other orgs, pending\n * invitations, inline forms to create a new org / invite a teammate, and a\n * sign-out item. Renders nothing in dev / no-auth mode.\n */\nexport function OrgSwitcher({\n className,\n hideWhenSingle,\n reserveSpace,\n settingsPath = DEFAULT_ORGANIZATION_SETTINGS_PATH,\n}: OrgSwitcherProps) {\n const { data: org, isLoading } = useOrg();\n const switchOrg = useSwitchOrg();\n const createOrg = useCreateOrg();\n const inviteMember = useInviteMember();\n const acceptInvitation = useAcceptInvitation();\n const joinByDomain = useJoinByDomain();\n const navigate = useNavigate();\n const [open, setOpen] = useState(false);\n const [mode, setMode] = useState<Mode>(\"list\");\n const [newName, setNewName] = useState(\"\");\n const [inviteEmail, setInviteEmail] = useState(\"\");\n const [signingOut, setSigningOut] = useState(false);\n const [joiningOrgId, setJoiningOrgId] = useState<string | null>(null);\n const appLinks = useOrgSwitcherAppLinks(open);\n\n const handleOpenChange = (next: boolean) => {\n setOpen(next);\n if (!next) {\n setMode(\"list\");\n setNewName(\"\");\n setInviteEmail(\"\");\n }\n };\n\n const handleSignOut = async () => {\n if (signingOut) return;\n setSigningOut(true);\n try {\n await fetch(agentNativePath(\"/_agent-native/auth/logout\"), {\n method: \"POST\",\n credentials: \"include\",\n });\n } catch {\n /* fall through to reload — server may already have cleared the cookie */\n }\n window.location.reload();\n };\n\n if (!org) {\n return reserveSpace && isLoading ? (\n <div aria-hidden=\"true\" className={`h-8 ${className ?? \"\"}`} />\n ) : null;\n }\n\n const orgs = org.orgs ?? [];\n const pendingInvitations = org.pendingInvitations ?? [];\n const domainMatches = org.domainMatches ?? [];\n const orgCount = orgs.length;\n const hasAny =\n orgCount > 0 || pendingInvitations.length > 0 || domainMatches.length > 0;\n if (!hasAny && !org.email) {\n return reserveSpace ? (\n <div aria-hidden=\"true\" className={`h-8 ${className ?? \"\"}`} />\n ) : null;\n }\n if (\n hideWhenSingle &&\n orgCount < 2 &&\n pendingInvitations.length === 0 &&\n domainMatches.length === 0\n ) {\n return reserveSpace ? (\n <div aria-hidden=\"true\" className={`h-8 ${className ?? \"\"}`} />\n ) : null;\n }\n\n const canInvite =\n !!org.orgId && (org.role === \"owner\" || org.role === \"admin\");\n\n const personalLabel = personalLabelFromEmail(org.email);\n const inOrg = !!org.orgId;\n const buttonLabel = org.orgName ?? \"Personal\";\n const ButtonIcon = inOrg ? IconBuilding : IconUser;\n const organizationSettingsHref = settingsPath\n ? organizationSettingsPath(settingsPath)\n : null;\n\n return (\n <PopoverPrimitive.Root open={open} onOpenChange={handleOpenChange}>\n <PopoverPrimitive.Trigger asChild>\n <button\n type=\"button\"\n className={`flex w-full items-center gap-2 rounded-md border border-border/50 px-2.5 py-1.5 text-xs font-medium text-muted-foreground hover:bg-accent/50 hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring cursor-pointer ${className ?? \"\"}`}\n >\n <ButtonIcon className=\"h-3.5 w-3.5 shrink-0\" />\n <span className=\"truncate flex-1 text-start\">{buttonLabel}</span>\n <IconSelector className=\"h-3 w-3 shrink-0 opacity-50\" />\n </button>\n </PopoverPrimitive.Trigger>\n <PopoverPrimitive.Portal>\n <PopoverPrimitive.Content\n side=\"top\"\n align=\"start\"\n sideOffset={6}\n collisionPadding={12}\n className={POPOVER_CONTENT_CLASS}\n onOpenAutoFocus={(e) => {\n // Don't auto-focus the first item — feels heavy on a switcher.\n if (mode === \"list\") e.preventDefault();\n }}\n >\n {mode === \"list\" && (\n <>\n {!inOrg && (\n <div\n className=\"flex w-full items-center gap-2 px-2.5 py-1.5 text-xs text-muted-foreground\"\n aria-disabled=\"true\"\n >\n <IconUser className=\"h-3.5 w-3.5 shrink-0\" />\n <span className=\"truncate flex-1 text-start\">\n Personal ({personalLabel})\n </span>\n </div>\n )}\n {orgs.length > 0 && (\n <div className={SECTION_LABEL_CLASS}>Organizations</div>\n )}\n {orgs.map((o) => (\n <button\n key={o.orgId}\n type=\"button\"\n onClick={async () => {\n if (o.orgId === org.orgId) {\n setOpen(false);\n return;\n }\n try {\n await switchOrg.mutateAsync(o.orgId);\n setOpen(false);\n } catch {\n /* error surfaced via switchOrg.error */\n }\n }}\n disabled={switchOrg.isPending}\n className={`${ITEM_CLASS} cursor-pointer`}\n >\n <IconBuilding className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"truncate flex-1 text-start\">\n {o.orgName}\n </span>\n {o.orgId === org.orgId && (\n <IconCheck className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n )}\n </button>\n ))}\n\n {pendingInvitations.length > 0 && (\n <>\n {orgs.length > 0 && <div className=\"my-1 h-px bg-border\" />}\n <div className={SECTION_LABEL_CLASS}>Invitations</div>\n {pendingInvitations.map((inv) => (\n <div\n key={inv.id}\n className=\"flex items-center gap-2 px-2.5 py-1.5 text-xs\"\n >\n <IconBuilding className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"truncate flex-1 text-foreground\">\n {inv.orgName}\n </span>\n <button\n type=\"button\"\n onClick={async () => {\n try {\n await acceptInvitation.mutateAsync(inv.id);\n setOpen(false);\n } catch {\n /* error surfaced via acceptInvitation.error */\n }\n }}\n disabled={acceptInvitation.isPending}\n className=\"rounded px-1.5 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/10 disabled:opacity-50 cursor-pointer\"\n >\n {acceptInvitation.isPending ? (\n <IconLoader2 className=\"h-3 w-3 animate-spin\" />\n ) : (\n \"Join\"\n )}\n </button>\n </div>\n ))}\n </>\n )}\n\n {domainMatches.length > 0 && (\n <>\n {(orgs.length > 0 || pendingInvitations.length > 0) && (\n <div className=\"my-1 h-px bg-border\" />\n )}\n <div className={SECTION_LABEL_CLASS}>Join your team</div>\n {domainMatches.map((match) => {\n const isJoining =\n joinByDomain.isPending && joiningOrgId === match.orgId;\n return (\n <div\n key={match.orgId}\n className=\"flex items-center gap-2 px-2.5 py-1.5 text-xs\"\n >\n <IconBuilding className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"truncate flex-1 text-foreground\">\n {match.orgName}\n </span>\n <button\n type=\"button\"\n onClick={async () => {\n setJoiningOrgId(match.orgId);\n try {\n await joinByDomain.mutateAsync(match.orgId);\n setOpen(false);\n } catch {\n /* error surfaced via joinByDomain.error */\n } finally {\n setJoiningOrgId(null);\n }\n }}\n disabled={joinByDomain.isPending}\n className=\"rounded px-1.5 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/10 disabled:opacity-50 cursor-pointer\"\n >\n {isJoining ? (\n <IconLoader2 className=\"h-3 w-3 animate-spin\" />\n ) : (\n \"Join\"\n )}\n </button>\n </div>\n );\n })}\n </>\n )}\n\n <div className=\"my-1 h-px bg-border\" />\n <AppsSubmenu\n apps={appLinks.apps}\n isWorkspace={appLinks.isWorkspace}\n isLoading={appLinks.isLoading}\n dispatchHref={appLinks.dispatchHref}\n dispatchAllAppsHref={appLinks.dispatchAllAppsHref}\n onNavigate={() => setOpen(false)}\n />\n {inOrg && (\n <button\n type=\"button\"\n onClick={() => {\n setOpen(false);\n window.dispatchEvent(new CustomEvent(\"agent-panel:open\"));\n window.dispatchEvent(\n new CustomEvent(\"agent-panel:open-settings\", {\n detail: { section: \"workspace-settings\" },\n }),\n );\n if (organizationSettingsHref) {\n navigate(organizationSettingsHref);\n }\n }}\n className={`${ITEM_CLASS} cursor-pointer`}\n >\n <IconSettings className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"flex-1 text-start\">\n Organization settings\n </span>\n </button>\n )}\n <button\n type=\"button\"\n onClick={() => {\n // Clear any leftover input from a prior session — otherwise\n // the create form re-opens prefilled with the just-created\n // org's name and looks like a create dialog for the new org.\n setNewName(\"\");\n setMode(\"create\");\n }}\n className={`${ITEM_CLASS} cursor-pointer`}\n >\n <IconPlus className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"flex-1 text-start\">Create organization</span>\n </button>\n {canInvite && (\n <button\n type=\"button\"\n onClick={() => {\n setInviteEmail(\"\");\n setMode(\"invite\");\n }}\n className={`${ITEM_CLASS} cursor-pointer`}\n >\n <IconUserPlus className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"flex-1 text-start\">Invite member</span>\n </button>\n )}\n\n <div className=\"my-1 h-px bg-border\" />\n <button\n type=\"button\"\n onClick={handleSignOut}\n disabled={signingOut}\n className={`${ITEM_CLASS} cursor-pointer`}\n >\n {signingOut ? (\n <IconLoader2 className=\"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground\" />\n ) : (\n <IconLogout className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground rtl:-scale-x-100\" />\n )}\n <span className=\"flex-1 text-start\">\n Sign out\n {org.email ? (\n <span className=\"ms-1 text-muted-foreground\">\n ({org.email})\n </span>\n ) : null}\n </span>\n </button>\n\n {(switchOrg.error ||\n acceptInvitation.error ||\n joinByDomain.error) && (\n <div className=\"px-2.5 pt-1 text-[11px] text-destructive\">\n {\n (\n (switchOrg.error ||\n acceptInvitation.error ||\n joinByDomain.error) as Error\n ).message\n }\n </div>\n )}\n </>\n )}\n\n {mode === \"create\" && (\n <form\n onSubmit={async (e) => {\n e.preventDefault();\n const name = newName.trim();\n if (!name) return;\n try {\n await createOrg.mutateAsync(name);\n handleOpenChange(false);\n } catch {\n /* error surfaced via createOrg.error */\n }\n }}\n className=\"px-2 py-1.5\"\n >\n <div className=\"px-0.5 pb-1 text-[10px] uppercase tracking-wide text-muted-foreground\">\n New organization\n </div>\n <input\n autoFocus\n value={newName}\n onChange={(e) => setNewName(e.target.value)}\n placeholder=\"Organization name\"\n disabled={createOrg.isPending}\n className=\"w-full rounded-md border border-input bg-background px-2 py-1.5 text-xs outline-none focus:ring-2 focus:ring-ring disabled:opacity-50\"\n />\n {createOrg.error && (\n <div className=\"pt-1 text-[11px] text-destructive\">\n {(createOrg.error as Error).message}\n </div>\n )}\n <div className=\"flex items-center gap-1.5 pt-1.5\">\n <button\n type=\"button\"\n onClick={() => setMode(\"list\")}\n disabled={createOrg.isPending}\n className=\"flex-1 rounded-md px-2 py-1 text-xs text-muted-foreground hover:bg-accent disabled:opacity-50 cursor-pointer\"\n >\n Cancel\n </button>\n <button\n type=\"submit\"\n disabled={createOrg.isPending || !newName.trim()}\n className=\"flex flex-1 items-center justify-center rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50 cursor-pointer\"\n >\n {createOrg.isPending ? (\n <IconLoader2 className=\"h-3 w-3 animate-spin\" />\n ) : (\n \"Create\"\n )}\n </button>\n </div>\n </form>\n )}\n\n {mode === \"invite\" && (\n <form\n onSubmit={async (e) => {\n e.preventDefault();\n const email = inviteEmail.trim();\n if (!email) return;\n try {\n await inviteMember.mutateAsync(email);\n setInviteEmail(\"\");\n setMode(\"list\");\n } catch {\n /* error surfaced via inviteMember.error */\n }\n }}\n className=\"px-2 py-1.5\"\n >\n <div className=\"px-0.5 pb-1 text-[10px] uppercase tracking-wide text-muted-foreground\">\n Invite to {org.orgName}\n </div>\n <input\n autoFocus\n type=\"email\"\n value={inviteEmail}\n onChange={(e) => setInviteEmail(e.target.value)}\n placeholder=\"teammate@company.com\"\n disabled={inviteMember.isPending}\n className=\"w-full rounded-md border border-input bg-background px-2 py-1.5 text-xs outline-none focus:ring-2 focus:ring-ring disabled:opacity-50\"\n />\n {inviteMember.error && (\n <div className=\"pt-1 text-[11px] text-destructive\">\n {(inviteMember.error as Error).message}\n </div>\n )}\n <div className=\"flex items-center gap-1.5 pt-1.5\">\n <button\n type=\"button\"\n onClick={() => setMode(\"list\")}\n disabled={inviteMember.isPending}\n className=\"flex-1 rounded-md px-2 py-1 text-xs text-muted-foreground hover:bg-accent disabled:opacity-50 cursor-pointer\"\n >\n Cancel\n </button>\n <button\n type=\"submit\"\n disabled={inviteMember.isPending || !inviteEmail.trim()}\n className=\"flex flex-1 items-center justify-center rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50 cursor-pointer\"\n >\n {inviteMember.isPending ? (\n <IconLoader2 className=\"h-3 w-3 animate-spin\" />\n ) : (\n \"Send invite\"\n )}\n </button>\n </div>\n </form>\n )}\n </PopoverPrimitive.Content>\n </PopoverPrimitive.Portal>\n </PopoverPrimitive.Root>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"OrgSwitcher.js","sourceRoot":"","sources":["../../../src/client/org/OrgSwitcher.tsx"],"names":[],"mappings":";AAAA,OAAO,KAAK,gBAAgB,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EACL,QAAQ,EACR,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,SAAS,EACT,YAAY,EACZ,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,QAAQ,EACR,YAAY,EACZ,YAAY,EACZ,eAAe,EACf,WAAW,EACX,UAAU,EACV,QAAQ,EACR,iBAAiB,EACjB,cAAc,EACd,QAAQ,EACR,SAAS,EACT,SAAS,EACT,QAAQ,EACR,gBAAgB,EAChB,SAAS,EACT,eA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G,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,EAC9B,QAAQ,EAAE,YAAY,CAAC,SAAS,EAChC,SAAS,EAAC,8GAA8G,uBAGjH,EACT,iBACE,IAAI,EAAC,QAAQ,EACb,QAAQ,EAAE,YAAY,CAAC,SAAS,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,EACvD,SAAS,EAAC,yKAAyK,YAElL,YAAY,CAAC,SAAS,CAAC,CAAC,CAAC,CACxB,KAAC,WAAW,IAAC,SAAS,EAAC,sBAAsB,GAAG,CACjD,CAAC,CAAC,CAAC,CACF,aAAa,CACd,GACM,IACL,IACD,CACR,IACwB,GACH,IACJ,CACzB,CAAC;AACJ,CAAC","sourcesContent":["import * as PopoverPrimitive from \"@radix-ui/react-popover\";\nimport {\n IconApps,\n IconArrowUpRight,\n IconBrain,\n IconBrandJira,\n IconBrush,\n IconBuilding,\n IconCalendar,\n IconCalendarTime,\n IconChartBar,\n IconCheck,\n IconChevronRight,\n IconClipboardList,\n IconCode,\n IconContract,\n IconFileText,\n IconLayoutBoard,\n IconLoader2,\n IconLogout,\n IconMail,\n IconMessageCircle,\n IconMicrophone,\n IconNote,\n IconPhone,\n IconPhoto,\n IconPlus,\n IconPresentation,\n IconRoute,\n IconScreenShare,\n IconSelector,\n IconSettings,\n IconStack2,\n IconUser,\n IconUserPlus,\n IconUsers,\n IconVideo,\n IconWorld,\n} from \"@tabler/icons-react\";\nimport { useState } from \"react\";\nimport { useNavigate } from \"react-router\";\n\nimport { agentNativePath } from \"../api-path.js\";\nimport {\n useOrg,\n useSwitchOrg,\n useCreateOrg,\n useInviteMember,\n useAcceptInvitation,\n useJoinByDomain,\n} from \"./hooks.js\";\nimport {\n ORG_SWITCHER_MAX_APP_LINKS,\n useOrgSwitcherAppLinks,\n visibleOrgAppLinks,\n type OrgSwitcherAppLink,\n} from \"./workspace-app-links.js\";\n\nexport interface OrgSwitcherProps {\n className?: string;\n /** Hide entirely when the user only belongs to one org. Default: false. */\n hideWhenSingle?: boolean;\n /** Keep the switcher's button height reserved while org state is loading. */\n reserveSpace?: boolean;\n /**\n * Path to navigate to when the user clicks \"Organization settings\".\n * Defaults to `/team`, the standard organization-management route. Templates\n * with an established org surface can pass their own path; pass `null` to\n * only open the in-sidebar settings panel.\n */\n settingsPath?: string | null;\n}\n\nfunction personalLabelFromEmail(email: string | null | undefined): string {\n if (!email) return \"Personal\";\n const local = email.split(\"@\")[0] ?? email;\n const cleaned = local.replace(/[._-]+/g, \" \").trim();\n if (!cleaned) return \"Personal\";\n return cleaned\n .split(\" \")\n .filter(Boolean)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(\" \");\n}\n\ntype Mode = \"list\" | \"create\" | \"invite\";\n\nconst POPOVER_CONTENT_CLASS =\n \"z-50 min-w-[14rem] rounded-md border border-border bg-popover py-1 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2\";\n\nconst ITEM_CLASS =\n \"flex w-full items-center gap-2 px-2.5 py-1.5 text-xs text-foreground hover:bg-accent focus-visible:bg-accent focus:outline-none disabled:opacity-50 disabled:pointer-events-none\";\n\nconst SECTION_LABEL_CLASS =\n \"px-2.5 pt-1 pb-0.5 text-[10px] uppercase tracking-wide text-muted-foreground\";\n\nconst APP_SUBMENU_CONTENT_CLASS =\n \"z-50 w-72 rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2\";\n\nconst DEFAULT_ORGANIZATION_SETTINGS_PATH = \"/team\";\n\nconst APP_ICON_MAP: Record<string, typeof IconApps> = {\n Mail: IconMail,\n CalendarDays: IconCalendar,\n FileText: IconFileText,\n LayoutBoard: IconLayoutBoard,\n BarChart2: IconChartBar,\n GalleryHorizontal: IconPresentation,\n Video: IconVideo,\n BrandJira: IconBrandJira,\n ClipboardList: IconClipboardList,\n Users: IconUsers,\n Code: IconCode,\n Contract: IconContract,\n MessageCircle: IconMessageCircle,\n Route: IconRoute,\n ScreenShare: IconScreenShare,\n Brush: IconBrush,\n Brain: IconBrain,\n Phone: IconPhone,\n Note: IconNote,\n Microphone: IconMicrophone,\n CalendarTime: IconCalendarTime,\n Globe: IconWorld,\n Photo: IconPhoto,\n};\n\nfunction appMenuIcon(app: OrgSwitcherAppLink): typeof IconApps {\n if (app.icon) return APP_ICON_MAP[app.icon] ?? IconStack2;\n return app.isDispatch ? IconMessageCircle : IconStack2;\n}\n\nfunction organizationSettingsPath(path: string): string {\n return `${path.replace(/#.*$/, \"\")}#workspace-settings`;\n}\n\nfunction AppMenuLink({\n app,\n onNavigate,\n}: {\n app: OrgSwitcherAppLink;\n onNavigate: () => void;\n}) {\n const Icon = appMenuIcon(app);\n return (\n <a\n href={app.href}\n onClick={onNavigate}\n className={`flex items-center gap-2 rounded-sm px-2.5 py-2 text-xs outline-none hover:bg-accent focus:bg-accent ${\n app.isDispatch ? \"border border-primary/20 bg-primary/5\" : \"\"\n }`}\n >\n <span\n className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-md ${\n app.isDispatch\n ? \"bg-primary text-primary-foreground\"\n : \"bg-muted text-muted-foreground\"\n }`}\n >\n <Icon className=\"h-3.5 w-3.5\" />\n </span>\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate font-medium text-foreground\">\n {app.name}\n </span>\n <span className=\"block truncate text-[11px] text-muted-foreground\">\n {app.isDispatch\n ? \"Main hub\"\n : app.status === \"pending\"\n ? \"Building\"\n : \"Open app\"}\n </span>\n </span>\n <IconArrowUpRight className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n </a>\n );\n}\n\nfunction AppsSubmenu({\n apps,\n isWorkspace,\n isLoading,\n dispatchHref,\n dispatchAllAppsHref,\n onNavigate,\n}: {\n apps: OrgSwitcherAppLink[];\n isWorkspace: boolean;\n isLoading: boolean;\n dispatchHref: string;\n dispatchAllAppsHref: string;\n onNavigate: () => void;\n}) {\n const { links, overflowCount } = visibleOrgAppLinks(apps);\n const visibleDispatchApp = links.find((app) => app.isDispatch);\n const dispatchApp =\n visibleDispatchApp ??\n ({\n id: \"dispatch\",\n name: \"Dispatch\",\n href: dispatchHref,\n isDispatch: true,\n status: \"ready\",\n } satisfies OrgSwitcherAppLink);\n const visibleNonDispatch = links\n .filter((app) => !app.isDispatch)\n .slice(0, visibleDispatchApp ? undefined : ORG_SWITCHER_MAX_APP_LINKS - 1);\n const shownCount = (dispatchApp ? 1 : 0) + visibleNonDispatch.length;\n const remainingCount = Math.max(overflowCount, apps.length - shownCount);\n\n return (\n <PopoverPrimitive.Root>\n <PopoverPrimitive.Trigger asChild>\n <button type=\"button\" className={`${ITEM_CLASS} cursor-pointer`}>\n <IconApps className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"flex-1 text-start\">Apps</span>\n <span className=\"text-[11px] text-muted-foreground\">\n {isLoading ? (\n <IconLoader2 className=\"h-3 w-3 animate-spin\" />\n ) : (\n apps.length\n )}\n </span>\n <IconChevronRight className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground rtl:-scale-x-100\" />\n </button>\n </PopoverPrimitive.Trigger>\n <PopoverPrimitive.Portal>\n <PopoverPrimitive.Content\n side=\"right\"\n align=\"start\"\n sideOffset={8}\n collisionPadding={12}\n className={APP_SUBMENU_CONTENT_CLASS}\n >\n <div className=\"px-2.5 py-1.5\">\n <div className=\"text-[10px] uppercase tracking-wide text-muted-foreground\">\n {isWorkspace ? \"Workspace apps\" : \"Default apps\"}\n </div>\n <div className=\"mt-0.5 text-[11px] text-muted-foreground\">\n {isWorkspace\n ? \"Dispatch is the workspace hub.\"\n : \"Dispatch is the home base.\"}\n </div>\n </div>\n\n <AppMenuLink app={dispatchApp} onNavigate={onNavigate} />\n\n {visibleNonDispatch.length > 0 && (\n <div className=\"my-1 h-px bg-border\" />\n )}\n {visibleNonDispatch.map((app) => (\n <AppMenuLink key={app.id} app={app} onNavigate={onNavigate} />\n ))}\n\n {remainingCount > 0 && (\n <>\n <div className=\"my-1 h-px bg-border\" />\n <a\n href={dispatchAllAppsHref}\n onClick={onNavigate}\n className=\"flex items-center gap-2 rounded-sm px-2.5 py-1.5 text-xs text-foreground outline-none hover:bg-accent focus:bg-accent\"\n >\n <IconMessageCircle className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"flex-1\">\n {`View ${remainingCount} more in Dispatch`}\n </span>\n <IconArrowUpRight className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n </a>\n </>\n )}\n </PopoverPrimitive.Content>\n </PopoverPrimitive.Portal>\n </PopoverPrimitive.Root>\n );\n}\n\n/**\n * Compact org switcher button. Shows the active org (or \"Personal\" when the\n * user has none); opens a popover with the user's other orgs, pending\n * invitations, inline forms to create a new org / invite a teammate, and a\n * sign-out item. Renders nothing in dev / no-auth mode.\n */\nexport function OrgSwitcher({\n className,\n hideWhenSingle,\n reserveSpace,\n settingsPath = DEFAULT_ORGANIZATION_SETTINGS_PATH,\n}: OrgSwitcherProps) {\n const { data: org, isLoading } = useOrg();\n const switchOrg = useSwitchOrg();\n const createOrg = useCreateOrg();\n const inviteMember = useInviteMember();\n const acceptInvitation = useAcceptInvitation();\n const joinByDomain = useJoinByDomain();\n const navigate = useNavigate();\n const [open, setOpen] = useState(false);\n const [mode, setMode] = useState<Mode>(\"list\");\n const [newName, setNewName] = useState(\"\");\n const [inviteEmail, setInviteEmail] = useState(\"\");\n const [signingOut, setSigningOut] = useState(false);\n const [joiningOrgId, setJoiningOrgId] = useState<string | null>(null);\n const appLinks = useOrgSwitcherAppLinks(open);\n\n const handleOpenChange = (next: boolean) => {\n setOpen(next);\n if (!next) {\n setMode(\"list\");\n setNewName(\"\");\n setInviteEmail(\"\");\n }\n };\n\n const handleSignOut = async () => {\n if (signingOut) return;\n setSigningOut(true);\n try {\n await fetch(agentNativePath(\"/_agent-native/auth/logout\"), {\n method: \"POST\",\n credentials: \"include\",\n });\n } catch {\n /* fall through to reload — server may already have cleared the cookie */\n }\n window.location.reload();\n };\n\n if (!org) {\n return reserveSpace && isLoading ? (\n <div aria-hidden=\"true\" className={`h-8 ${className ?? \"\"}`} />\n ) : null;\n }\n\n const orgs = org.orgs ?? [];\n const pendingInvitations = org.pendingInvitations ?? [];\n const domainMatches = org.domainMatches ?? [];\n const orgCount = orgs.length;\n const hasAny =\n orgCount > 0 || pendingInvitations.length > 0 || domainMatches.length > 0;\n if (!hasAny && !org.email) {\n return reserveSpace ? (\n <div aria-hidden=\"true\" className={`h-8 ${className ?? \"\"}`} />\n ) : null;\n }\n if (\n hideWhenSingle &&\n orgCount < 2 &&\n pendingInvitations.length === 0 &&\n domainMatches.length === 0\n ) {\n return reserveSpace ? (\n <div aria-hidden=\"true\" className={`h-8 ${className ?? \"\"}`} />\n ) : null;\n }\n\n const canInvite =\n !!org.orgId && (org.role === \"owner\" || org.role === \"admin\");\n\n const personalLabel = personalLabelFromEmail(org.email);\n const inOrg = !!org.orgId;\n const buttonLabel = org.orgName ?? \"Personal\";\n const ButtonIcon = inOrg ? IconBuilding : IconUser;\n const organizationSettingsHref = settingsPath\n ? organizationSettingsPath(settingsPath)\n : null;\n\n return (\n <PopoverPrimitive.Root open={open} onOpenChange={handleOpenChange}>\n <PopoverPrimitive.Trigger asChild>\n <button\n type=\"button\"\n className={`flex w-full items-center gap-2 rounded-md border border-border/50 px-2.5 py-1.5 text-xs font-medium text-muted-foreground hover:bg-accent/50 hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring cursor-pointer ${className ?? \"\"}`}\n >\n <ButtonIcon className=\"h-3.5 w-3.5 shrink-0\" />\n <span className=\"truncate flex-1 text-start\">{buttonLabel}</span>\n <IconSelector className=\"h-3 w-3 shrink-0 opacity-50\" />\n </button>\n </PopoverPrimitive.Trigger>\n <PopoverPrimitive.Portal>\n <PopoverPrimitive.Content\n side=\"top\"\n align=\"start\"\n sideOffset={6}\n collisionPadding={12}\n className={POPOVER_CONTENT_CLASS}\n onOpenAutoFocus={(e) => {\n // Don't auto-focus the first item — feels heavy on a switcher.\n if (mode === \"list\") e.preventDefault();\n }}\n >\n {mode === \"list\" && (\n <>\n {!inOrg && (\n <div\n className=\"flex w-full items-center gap-2 px-2.5 py-1.5 text-xs text-muted-foreground\"\n aria-disabled=\"true\"\n >\n <IconUser className=\"h-3.5 w-3.5 shrink-0\" />\n <span className=\"truncate flex-1 text-start\">\n Personal ({personalLabel})\n </span>\n </div>\n )}\n {orgs.length > 0 && (\n <div className={SECTION_LABEL_CLASS}>Organizations</div>\n )}\n {orgs.map((o) => (\n <button\n key={o.orgId}\n type=\"button\"\n onClick={async () => {\n if (o.orgId === org.orgId) {\n setOpen(false);\n return;\n }\n try {\n await switchOrg.mutateAsync(o.orgId);\n setOpen(false);\n } catch {\n /* error surfaced via switchOrg.error */\n }\n }}\n disabled={switchOrg.isPending}\n className={`${ITEM_CLASS} cursor-pointer`}\n >\n <IconBuilding className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"truncate flex-1 text-start\">\n {o.orgName}\n </span>\n {o.orgId === org.orgId && (\n <IconCheck className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n )}\n </button>\n ))}\n\n {pendingInvitations.length > 0 && (\n <>\n {orgs.length > 0 && <div className=\"my-1 h-px bg-border\" />}\n <div className={SECTION_LABEL_CLASS}>Invitations</div>\n {pendingInvitations.map((inv) => (\n <div\n key={inv.id}\n className=\"flex items-center gap-2 px-2.5 py-1.5 text-xs\"\n >\n <IconBuilding className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"truncate flex-1 text-foreground\">\n {inv.orgName}\n </span>\n <button\n type=\"button\"\n onClick={async () => {\n try {\n await acceptInvitation.mutateAsync(inv.id);\n setOpen(false);\n } catch {\n /* error surfaced via acceptInvitation.error */\n }\n }}\n disabled={acceptInvitation.isPending}\n className=\"rounded px-1.5 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/10 disabled:opacity-50 cursor-pointer\"\n >\n {acceptInvitation.isPending ? (\n <IconLoader2 className=\"h-3 w-3 animate-spin\" />\n ) : (\n \"Join\"\n )}\n </button>\n </div>\n ))}\n </>\n )}\n\n {domainMatches.length > 0 && (\n <>\n {(orgs.length > 0 || pendingInvitations.length > 0) && (\n <div className=\"my-1 h-px bg-border\" />\n )}\n <div className={SECTION_LABEL_CLASS}>Join your team</div>\n {domainMatches.map((match) => {\n const isJoining =\n joinByDomain.isPending && joiningOrgId === match.orgId;\n return (\n <div\n key={match.orgId}\n className=\"flex items-center gap-2 px-2.5 py-1.5 text-xs\"\n >\n <IconBuilding className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"truncate flex-1 text-foreground\">\n {match.orgName}\n </span>\n <button\n type=\"button\"\n onClick={async () => {\n setJoiningOrgId(match.orgId);\n try {\n await joinByDomain.mutateAsync(match.orgId);\n setOpen(false);\n } catch {\n /* error surfaced via joinByDomain.error */\n } finally {\n setJoiningOrgId(null);\n }\n }}\n disabled={joinByDomain.isPending}\n className=\"rounded px-1.5 py-0.5 text-[11px] font-medium text-primary hover:bg-primary/10 disabled:opacity-50 cursor-pointer\"\n >\n {isJoining ? (\n <IconLoader2 className=\"h-3 w-3 animate-spin\" />\n ) : (\n \"Join\"\n )}\n </button>\n </div>\n );\n })}\n </>\n )}\n\n <div className=\"my-1 h-px bg-border\" />\n <AppsSubmenu\n apps={appLinks.apps}\n isWorkspace={appLinks.isWorkspace}\n isLoading={appLinks.isLoading}\n dispatchHref={appLinks.dispatchHref}\n dispatchAllAppsHref={appLinks.dispatchAllAppsHref}\n onNavigate={() => setOpen(false)}\n />\n {inOrg && (\n <button\n type=\"button\"\n onClick={() => {\n setOpen(false);\n window.dispatchEvent(new CustomEvent(\"agent-panel:open\"));\n window.dispatchEvent(\n new CustomEvent(\"agent-panel:open-settings\", {\n detail: { section: \"workspace-settings\" },\n }),\n );\n if (organizationSettingsHref) {\n navigate(organizationSettingsHref);\n }\n }}\n className={`${ITEM_CLASS} cursor-pointer`}\n >\n <IconSettings className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"flex-1 text-start\">\n Organization settings\n </span>\n </button>\n )}\n <button\n type=\"button\"\n onClick={() => {\n // Clear any leftover input from a prior session — otherwise\n // the create form re-opens prefilled with the just-created\n // org's name and looks like a create dialog for the new org.\n setNewName(\"\");\n setMode(\"create\");\n }}\n className={`${ITEM_CLASS} cursor-pointer`}\n >\n <IconPlus className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"flex-1 text-start\">Create organization</span>\n </button>\n {canInvite && (\n <button\n type=\"button\"\n onClick={() => {\n setInviteEmail(\"\");\n setMode(\"invite\");\n }}\n className={`${ITEM_CLASS} cursor-pointer`}\n >\n <IconUserPlus className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"flex-1 text-start\">Invite member</span>\n </button>\n )}\n\n <div className=\"my-1 h-px bg-border\" />\n <button\n type=\"button\"\n onClick={handleSignOut}\n disabled={signingOut}\n className={`${ITEM_CLASS} cursor-pointer`}\n >\n {signingOut ? (\n <IconLoader2 className=\"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground\" />\n ) : (\n <IconLogout className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground rtl:-scale-x-100\" />\n )}\n <span className=\"flex-1 text-start\">\n Sign out\n {org.email ? (\n <span className=\"ms-1 text-muted-foreground\">\n ({org.email})\n </span>\n ) : null}\n </span>\n </button>\n\n {(switchOrg.error ||\n acceptInvitation.error ||\n joinByDomain.error) && (\n <div className=\"px-2.5 pt-1 text-[11px] text-destructive\">\n {\n (\n (switchOrg.error ||\n acceptInvitation.error ||\n joinByDomain.error) as Error\n ).message\n }\n </div>\n )}\n </>\n )}\n\n {mode === \"create\" && (\n <form\n onSubmit={async (e) => {\n e.preventDefault();\n const name = newName.trim();\n if (!name) return;\n try {\n await createOrg.mutateAsync(name);\n handleOpenChange(false);\n } catch {\n /* error surfaced via createOrg.error */\n }\n }}\n className=\"px-2 py-1.5\"\n >\n <div className=\"px-0.5 pb-1 text-[10px] uppercase tracking-wide text-muted-foreground\">\n New organization\n </div>\n <input\n autoFocus\n value={newName}\n onChange={(e) => setNewName(e.target.value)}\n placeholder=\"Organization name\"\n disabled={createOrg.isPending}\n className=\"w-full rounded-md border border-input bg-background px-2 py-1.5 text-xs outline-none focus:ring-2 focus:ring-ring disabled:opacity-50\"\n />\n {createOrg.error && (\n <div className=\"pt-1 text-[11px] text-destructive\">\n {(createOrg.error as Error).message}\n </div>\n )}\n <div className=\"flex items-center gap-1.5 pt-1.5\">\n <button\n type=\"button\"\n onClick={() => setMode(\"list\")}\n disabled={createOrg.isPending}\n className=\"flex-1 rounded-md px-2 py-1 text-xs text-muted-foreground hover:bg-accent disabled:opacity-50 cursor-pointer\"\n >\n Cancel\n </button>\n <button\n type=\"submit\"\n disabled={createOrg.isPending || !newName.trim()}\n className=\"flex flex-1 items-center justify-center rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50 cursor-pointer\"\n >\n {createOrg.isPending ? (\n <IconLoader2 className=\"h-3 w-3 animate-spin\" />\n ) : (\n \"Create\"\n )}\n </button>\n </div>\n </form>\n )}\n\n {mode === \"invite\" && (\n <form\n onSubmit={async (e) => {\n e.preventDefault();\n const email = inviteEmail.trim();\n if (!email) return;\n try {\n await inviteMember.mutateAsync(email);\n setInviteEmail(\"\");\n setMode(\"list\");\n } catch {\n /* error surfaced via inviteMember.error */\n }\n }}\n className=\"px-2 py-1.5\"\n >\n <div className=\"px-0.5 pb-1 text-[10px] uppercase tracking-wide text-muted-foreground\">\n Invite to {org.orgName}\n </div>\n <input\n autoFocus\n type=\"email\"\n value={inviteEmail}\n onChange={(e) => setInviteEmail(e.target.value)}\n placeholder=\"teammate@company.com\"\n disabled={inviteMember.isPending}\n className=\"w-full rounded-md border border-input bg-background px-2 py-1.5 text-xs outline-none focus:ring-2 focus:ring-ring disabled:opacity-50\"\n />\n {inviteMember.error && (\n <div className=\"pt-1 text-[11px] text-destructive\">\n {(inviteMember.error as Error).message}\n </div>\n )}\n <div className=\"flex items-center gap-1.5 pt-1.5\">\n <button\n type=\"button\"\n onClick={() => setMode(\"list\")}\n disabled={inviteMember.isPending}\n className=\"flex-1 rounded-md px-2 py-1 text-xs text-muted-foreground hover:bg-accent disabled:opacity-50 cursor-pointer\"\n >\n Cancel\n </button>\n <button\n type=\"submit\"\n disabled={inviteMember.isPending || !inviteEmail.trim()}\n className=\"flex flex-1 items-center justify-center rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50 cursor-pointer\"\n >\n {inviteMember.isPending ? (\n <IconLoader2 className=\"h-3 w-3 animate-spin\" />\n ) : (\n \"Send invite\"\n )}\n </button>\n </div>\n </form>\n )}\n </PopoverPrimitive.Content>\n </PopoverPrimitive.Portal>\n </PopoverPrimitive.Root>\n );\n}\n"]}
|
|
@@ -1,6 +1,10 @@
|
|
|
1
|
+
interface Query {
|
|
2
|
+
queryKey: readonly unknown[];
|
|
3
|
+
}
|
|
1
4
|
interface QueryClient {
|
|
2
5
|
invalidateQueries(opts?: {
|
|
3
6
|
queryKey?: string[];
|
|
7
|
+
predicate?: (query: Query) => boolean;
|
|
4
8
|
}): void;
|
|
5
9
|
}
|
|
6
10
|
/** @internal */
|
|
@@ -31,6 +35,10 @@ export declare function _resetSyncTransportRegistryForTests(): void;
|
|
|
31
35
|
* @param options.ignoreSource - Skip events whose `requestSource` matches this
|
|
32
36
|
* value. Use a per-tab ID so the UI ignores its own writes while still
|
|
33
37
|
* picking up changes from other tabs, agents, and scripts.
|
|
38
|
+
* @param options.actionInvalidatePredicate - Optional filter for the broad
|
|
39
|
+
* compatibility invalidate triggered by `action` events. Use this to keep
|
|
40
|
+
* expensive active queries on explicit-refresh semantics while still letting
|
|
41
|
+
* normal source-versioned queries react through `useChangeVersion`.
|
|
34
42
|
*/
|
|
35
43
|
export declare function useDbSync(options?: {
|
|
36
44
|
queryClient?: QueryClient;
|
|
@@ -44,6 +52,7 @@ export declare function useDbSync(options?: {
|
|
|
44
52
|
fallbackInterval?: number;
|
|
45
53
|
pauseWhenHidden?: boolean;
|
|
46
54
|
ignoreSource?: string;
|
|
55
|
+
actionInvalidatePredicate?: (query: Query) => boolean;
|
|
47
56
|
}): void;
|
|
48
57
|
/** @deprecated Use useDbSync instead */
|
|
49
58
|
export declare const useFileWatcher: typeof useDbSync;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-db-sync.d.ts","sourceRoot":"","sources":["../../src/client/use-db-sync.ts"],"names":[],"mappings":"AAUA,UAAU,WAAW;IACnB,iBAAiB,CAAC,IAAI,CAAC,EAAE;
|
|
1
|
+
{"version":3,"file":"use-db-sync.d.ts","sourceRoot":"","sources":["../../src/client/use-db-sync.ts"],"names":[],"mappings":"AAUA,UAAU,KAAK;IACb,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAC;CAC9B;AAED,UAAU,WAAW;IACnB,iBAAiB,CAAC,IAAI,CAAC,EAAE;QACvB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;QACpB,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,OAAO,CAAC;KACvC,GAAG,IAAI,CAAC;CACV;AAkbD,gBAAgB;AAChB,wBAAgB,mCAAmC,IAAI,IAAI,CAE1D;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,SAAS,CACvB,OAAO,GAAE;IACP,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IACxB,sCAAsC;IACtC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,IAAI,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,yBAAyB,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,OAAO,CAAC;CAClD,GACL,IAAI,CAsJN;AAED,wCAAwC;AACxC,eAAO,MAAM,cAAc,kBAAY,CAAC;AAExC;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE;IACP,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,eAAe,CAAC,EAAE,OAAO,CAAC;CACtB,GACL,MAAM,CAuDR"}
|
|
@@ -370,6 +370,10 @@ export function _resetSyncTransportRegistryForTests() {
|
|
|
370
370
|
* @param options.ignoreSource - Skip events whose `requestSource` matches this
|
|
371
371
|
* value. Use a per-tab ID so the UI ignores its own writes while still
|
|
372
372
|
* picking up changes from other tabs, agents, and scripts.
|
|
373
|
+
* @param options.actionInvalidatePredicate - Optional filter for the broad
|
|
374
|
+
* compatibility invalidate triggered by `action` events. Use this to keep
|
|
375
|
+
* expensive active queries on explicit-refresh semantics while still letting
|
|
376
|
+
* normal source-versioned queries react through `useChangeVersion`.
|
|
373
377
|
*/
|
|
374
378
|
export function useDbSync(options = {}) {
|
|
375
379
|
const { queryClient, pollUrl = agentNativePath(options.eventsUrl ?? "/_agent-native/poll"), sseUrl = resolveSseUrl(options.sseUrl), interval = 2000, fallbackInterval = Math.max(options.fallbackInterval ?? SSE_FALLBACK_INTERVAL_MS, interval), pauseWhenHidden = true, } = options;
|
|
@@ -377,6 +381,8 @@ export function useDbSync(options = {}) {
|
|
|
377
381
|
onEventRef.current = options.onEvent;
|
|
378
382
|
const ignoreSourceRef = useRef(options.ignoreSource);
|
|
379
383
|
ignoreSourceRef.current = options.ignoreSource;
|
|
384
|
+
const actionInvalidatePredicateRef = useRef(options.actionInvalidatePredicate);
|
|
385
|
+
actionInvalidatePredicateRef.current = options.actionInvalidatePredicate;
|
|
380
386
|
useEffect(() => {
|
|
381
387
|
const id = Symbol("useDbSync");
|
|
382
388
|
// Per-subscriber version cursor: tracks which events have already been
|
|
@@ -412,7 +418,8 @@ export function useDbSync(options = {}) {
|
|
|
412
418
|
// signal, so refresh active queries broadly as a compatibility
|
|
413
419
|
// safety net. Other event sources stay targeted to avoid request
|
|
414
420
|
// storms from noisy domain-specific writes.
|
|
415
|
-
|
|
421
|
+
const predicate = actionInvalidatePredicateRef.current;
|
|
422
|
+
queryClient.invalidateQueries(predicate ? { predicate } : undefined);
|
|
416
423
|
}
|
|
417
424
|
// Framework-level invalidate: a small, fixed list of query-key
|
|
418
425
|
// prefixes the framework's own hooks/components use (action results,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-db-sync.js","sourceRoot":"","sources":["../../src/client/use-db-sync.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEpD,OAAO,EAAE,8BAA8B,EAAE,MAAM,8BAA8B,CAAC;AAC9E,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EACL,+BAA+B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oBAAoB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACxD,SAAS,CAAC,GAAG,CAAC,EAAE,EAAE;YAChB,QAAQ;YACR,eAAe;YACf,QAAQ;YACR,gBAAgB;SACjB,CAAC,CAAC;QAEH,OAAO,GAAG,EAAE;YACV,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACrB,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC,IAAI,EAAE,CAAC;gBACnC,gBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;YACpC,CAAC;QACH,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,gBAAgB,EAAE,eAAe,CAAC,CAAC,CAAC;IAEnE,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import { useEffect, useRef, useState } from \"react\";\n\nimport { ensureDemoModeFetchInterceptor } from \"../demo/fetch-interceptor.js\";\nimport { agentNativePath } from \"./api-path.js\";\nimport {\n ensureEmbedAuthFetchInterceptor,\n isEmbedAuthActive,\n} from \"./embed-auth.js\";\nimport { bumpChangeVersion } from \"./use-change-version.js\";\n\ninterface QueryClient {\n invalidateQueries(opts?: { queryKey?: string[] }): void;\n}\n\nconst POLL_ABORT_MIN_MS = 10_000;\nconst SSE_FALLBACK_INTERVAL_MS = 15_000;\nconst POLL_AUTH_FAILURE_COOLDOWN_MS = 60_000;\n\nclass HttpStatusError extends Error {\n status: number;\n\n constructor(status: number) {\n super(\"HTTP \" + status);\n this.status = status;\n }\n}\n\ntype SyncEvent = {\n version?: number;\n source?: string;\n type?: string;\n key?: string;\n requestSource?: string;\n [k: string]: unknown;\n};\n\ntype PollResponse = {\n version: number;\n events: SyncEvent[];\n};\n\n/** Callback delivered to each transport subscriber for every batch of events. */\ntype EventSubscriber = (\n events: SyncEvent[],\n version: number | undefined,\n) => void;\n\nfunction getPollAbortMs(interval: number): number {\n return Math.max(POLL_ABORT_MIN_MS, interval * 4);\n}\n\nfunction isDocumentHidden(): boolean {\n return (\n typeof document !== \"undefined\" && document.visibilityState === \"hidden\"\n );\n}\n\nfunction resolveSseUrl(sseUrl: string | false | undefined): string | false {\n if (sseUrl === false) return false;\n if (isEmbedAuthActive()) return false;\n return agentNativePath(sseUrl ?? \"/_agent-native/events\");\n}\n\nfunction normalizeEventPayload(payload: unknown): SyncEvent[] {\n if (!payload || typeof payload !== \"object\") return [];\n const record = payload as { type?: unknown; events?: unknown };\n if (record.type === \"batch\" && Array.isArray(record.events)) {\n return record.events.filter(\n (event): event is SyncEvent => !!event && typeof event === \"object\",\n );\n }\n if (Array.isArray(record.events)) {\n return record.events.filter(\n (event): event is SyncEvent => !!event && typeof event === \"object\",\n );\n }\n return [payload as SyncEvent];\n}\n\nfunction isAuthFailure(error: unknown): boolean {\n return (\n !!error &&\n typeof error === \"object\" &&\n \"status\" in error &&\n ((error as { status?: unknown }).status === 401 ||\n (error as { status?: unknown }).status === 403)\n );\n}\n\nasync function fetchPollJson<T>(\n pollUrl: string,\n since: number,\n interval: number,\n): Promise<T> {\n const controller =\n typeof AbortController === \"undefined\" ? null : new AbortController();\n const timeout = controller\n ? setTimeout(() => controller.abort(), getPollAbortMs(interval))\n : null;\n\n try {\n const res = await fetch(\n `${pollUrl}?since=${since}`,\n controller ? { signal: controller.signal } : undefined,\n );\n if (!res.ok) throw new HttpStatusError(res.status);\n // Await the json before the finally so a body-stream abort doesn't\n // produce a dangling promise that escapes as an unhandled rejection.\n return await res.json();\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Shared SSE + poll transport\n//\n// One SyncTransport per (pollUrl, sseUrl) pair is held in a module-level\n// registry. Both `useDbSync` and `useScreenRefreshKey` subscribe to it, so a\n// single browser tab opens exactly ONE SSE connection and ONE poll loop\n// regardless of how many hook instances are mounted.\n//\n// Lifecycle: the transport starts when the first subscriber joins and shuts\n// down when the last subscriber leaves. This makes it safe to SSR and to\n// mount/unmount hooks independently.\n// ---------------------------------------------------------------------------\n\ninterface TransportSubscription {\n onEvents: EventSubscriber;\n /**\n * Whether this subscriber wants the transport to pause when the tab is\n * hidden. The transport pauses only when ALL subscribers request it — any\n * subscriber with `pauseWhenHidden: false` keeps the connection alive.\n */\n pauseWhenHidden: boolean;\n /**\n * Requested poll interval in ms. The transport uses the minimum across all\n * subscribers so the most-frequent caller is satisfied.\n */\n interval: number;\n /** Requested fallback interval while SSE is connected. */\n fallbackInterval: number;\n}\n\nclass SyncTransport {\n private subscribers = new Map<symbol, TransportSubscription>();\n private versionRef = 0;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private stopped = false;\n private inFlight = false;\n private eventSource: EventSource | null = null;\n private sseConnected = false;\n private authFailureUntil = 0;\n\n constructor(\n private readonly pollUrl: string,\n private readonly sseUrl: string | false,\n ) {}\n\n // -------------------------------------------------------------------------\n // Subscriber management\n // -------------------------------------------------------------------------\n\n add(id: symbol, sub: TransportSubscription): void {\n const wasEmpty = this.subscribers.size === 0;\n this.subscribers.set(id, sub);\n if (wasEmpty) {\n this.stopped = false;\n this.start();\n }\n }\n\n remove(id: symbol): void {\n this.subscribers.delete(id);\n if (this.subscribers.size === 0) {\n this.teardown();\n } else {\n // Recalculate poll interval in case the leaving subscriber was the\n // fastest caller; reschedule with the updated cadence.\n this.reschedule();\n }\n }\n\n // -------------------------------------------------------------------------\n // Derived settings (aggregate over active subscribers)\n // -------------------------------------------------------------------------\n\n private get effectivePauseWhenHidden(): boolean {\n // Pause only if every subscriber has opted in.\n for (const sub of this.subscribers.values()) {\n if (!sub.pauseWhenHidden) return false;\n }\n return true;\n }\n\n private get effectiveInterval(): number {\n let min = Infinity;\n for (const sub of this.subscribers.values()) {\n if (sub.interval < min) min = sub.interval;\n }\n return isFinite(min) ? min : 2000;\n }\n\n private get effectiveFallbackInterval(): number {\n let min = Infinity;\n for (const sub of this.subscribers.values()) {\n if (sub.fallbackInterval < min) min = sub.fallbackInterval;\n }\n return isFinite(min) ? min : SSE_FALLBACK_INTERVAL_MS;\n }\n\n // -------------------------------------------------------------------------\n // Event fan-out\n // -------------------------------------------------------------------------\n\n private fan(events: SyncEvent[], version: number | undefined): void {\n for (const sub of this.subscribers.values()) {\n sub.onEvents(events, version);\n }\n }\n\n // -------------------------------------------------------------------------\n // SSE + poll loop (mirrors the original per-hook logic exactly)\n // -------------------------------------------------------------------------\n\n private authFailureDelayMs(): number {\n return Math.max(0, this.authFailureUntil - Date.now());\n }\n\n private schedulePoll(): void {\n if (this.stopped) return;\n if (this.effectivePauseWhenHidden && isDocumentHidden()) return;\n if (this.timer) clearTimeout(this.timer);\n const authDelay = this.authFailureDelayMs();\n if (authDelay > 0) {\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.poll();\n }, authDelay);\n return;\n }\n this.timer = setTimeout(\n () => {\n this.timer = null;\n void this.poll();\n },\n this.sseConnected\n ? this.effectiveFallbackInterval\n : this.effectiveInterval,\n );\n }\n\n private reschedule(): void {\n // Only need to act if a timer is already pending; next natural tick will\n // pick up the new effective interval otherwise.\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n this.schedulePoll();\n }\n }\n\n private closeEvents(): void {\n if (!this.eventSource) return;\n this.eventSource.close();\n this.eventSource = null;\n this.sseConnected = false;\n }\n\n private connectEvents(): void {\n if (\n this.stopped ||\n !this.sseUrl ||\n this.eventSource ||\n typeof EventSource === \"undefined\" ||\n (this.effectivePauseWhenHidden && isDocumentHidden())\n ) {\n return;\n }\n\n const source = new EventSource(this.sseUrl);\n this.eventSource = source;\n source.onopen = () => {\n this.sseConnected = true;\n this.schedulePoll();\n };\n source.onerror = () => {\n this.sseConnected = false;\n // When the browser gives up permanently (HTTP error → readyState\n // CLOSED), it won't auto-reconnect. Drop the ref so a later\n // connectEvents() (on focus/visibility) can establish a fresh stream;\n // otherwise the non-null closed `eventSource` blocks reconnection and\n // we'd be stuck on polling-only forever.\n if (source.readyState === EventSource.CLOSED) {\n this.eventSource = null;\n }\n this.schedulePoll();\n };\n source.onmessage = (message) => {\n try {\n const payload = JSON.parse(message.data);\n const events = normalizeEventPayload(payload);\n const version =\n typeof payload?.version === \"number\" ? payload.version : undefined;\n this.applyVersion(events, version);\n this.fan(events, version);\n } catch {\n // Ignore malformed SSE frames; polling is the safety net.\n }\n };\n }\n\n /**\n * Advance the transport's shared version cursor. Subscribers receive the\n * raw events and decide independently which ones are \"fresh\" relative to\n * their own cursor, but the transport-level cursor ensures the poll\n * `?since=` parameter always advances.\n */\n private applyVersion(events: SyncEvent[], version: number | undefined): void {\n let max = typeof version === \"number\" ? version : 0;\n for (const evt of events) {\n const v = typeof evt.version === \"number\" ? evt.version : 0;\n if (v > max) max = v;\n }\n if (max > this.versionRef) this.versionRef = max;\n }\n\n private async poll(): Promise<void> {\n if (this.stopped || this.inFlight) return;\n this.inFlight = true;\n try {\n const data = await fetchPollJson<PollResponse>(\n this.pollUrl,\n this.versionRef,\n this.effectiveInterval,\n );\n if (this.stopped) return;\n const events = data.events ?? [];\n this.applyVersion(events, data.version);\n this.fan(events, data.version);\n } catch (err) {\n if (this.stopped) return;\n if (isAuthFailure(err)) {\n this.authFailureUntil = Date.now() + POLL_AUTH_FAILURE_COOLDOWN_MS;\n this.closeEvents();\n }\n // Network error — will retry on next interval.\n } finally {\n this.inFlight = false;\n this.schedulePoll();\n }\n }\n\n private pollNow(): void {\n if (this.effectivePauseWhenHidden && isDocumentHidden()) return;\n if (this.authFailureDelayMs() > 0) {\n this.schedulePoll();\n return;\n }\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n this.connectEvents();\n void this.poll();\n }\n\n private handleVisibilityChange = (): void => {\n if (document.visibilityState === \"visible\") {\n this.connectEvents();\n this.pollNow();\n } else if (this.effectivePauseWhenHidden) {\n this.closeEvents();\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n };\n\n private handleFocus = (): void => {\n this.pollNow();\n };\n\n private start(): void {\n // Universal demo-mode redaction for the UI. Idempotent + browser-only +\n // a no-op until demo mode is on. Lives here because every template root\n // already mounts useDbSync, so this needs zero per-template wiring.\n ensureEmbedAuthFetchInterceptor();\n ensureDemoModeFetchInterceptor();\n\n if (!this.effectivePauseWhenHidden || !isDocumentHidden()) {\n this.connectEvents();\n void this.poll();\n }\n window.addEventListener(\"focus\", this.handleFocus);\n document.addEventListener(\"visibilitychange\", this.handleVisibilityChange);\n }\n\n private teardown(): void {\n this.stopped = true;\n this.closeEvents();\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n window.removeEventListener(\"focus\", this.handleFocus);\n document.removeEventListener(\n \"visibilitychange\",\n this.handleVisibilityChange,\n );\n }\n}\n\n/**\n * Registry of active transports keyed by \"<pollUrl>\\0<sseUrl>\".\n * Module-level singleton: survives React render cycles, shared across all\n * hook instances in the same browser tab.\n */\nconst transportRegistry = new Map<string, SyncTransport>();\n\nfunction getOrCreateTransport(\n pollUrl: string,\n sseUrl: string | false,\n): SyncTransport {\n const key = `${pollUrl}\\0${String(sseUrl)}`;\n let transport = transportRegistry.get(key);\n if (!transport) {\n transport = new SyncTransport(pollUrl, sseUrl);\n transportRegistry.set(key, transport);\n }\n return transport;\n}\n\n/** Remove a transport from the registry once torn down (last subscriber left). */\nfunction releaseTransport(pollUrl: string, sseUrl: string | false): void {\n const key = `${pollUrl}\\0${String(sseUrl)}`;\n // Leave the entry in place: SSE/poll is already stopped inside the class;\n // the next subscriber will re-start it via `add()`. Clearing the map entry\n // prevents any dangling reference from the old SyncTransport instance.\n transportRegistry.delete(key);\n}\n\n// ---------------------------------------------------------------------------\n// Internal test helper — reset transport registry between tests.\n// ---------------------------------------------------------------------------\n/** @internal */\nexport function _resetSyncTransportRegistryForTests(): void {\n transportRegistry.clear();\n}\n\n/**\n * Hook that listens to /_agent-native/events for DB change events and\n * invalidates react-query caches when changes are detected. Falls back to\n * /_agent-native/poll so cross-process/serverless writes still show up.\n *\n * Works in all deployment environments (serverless, edge, long-lived server).\n * SSE is the fast path; polling is the safety net.\n *\n * @param options.queryClient - The react-query QueryClient instance\n * @param options.queryKeys - **Deprecated and ignored.** The hook uses\n * framework-owned fixed prefixes plus per-source change counters instead of\n * caller-supplied key lists. Kept in the type signature for backward\n * compatibility — existing call sites that still pass this option keep\n * working but the value has no effect.\n * @param options.pollUrl - Poll endpoint URL. Default: \"/_agent-native/poll\"\n * @param options.sseUrl - SSE endpoint URL. Default: \"/_agent-native/events\".\n * Pass false to disable SSE and use polling only.\n * @param options.onEvent - Optional callback for each change event\n * @param options.interval - Poll interval in ms. Default: 2000\n * @param options.fallbackInterval - Poll interval while SSE is connected.\n * Default: 15000\n * @param options.pauseWhenHidden - Pause polling while the tab is hidden.\n * Default: true\n * @param options.ignoreSource - Skip events whose `requestSource` matches this\n * value. Use a per-tab ID so the UI ignores its own writes while still\n * picking up changes from other tabs, agents, and scripts.\n */\nexport function useDbSync(\n options: {\n queryClient?: QueryClient;\n queryKeys?: string[];\n pollUrl?: string;\n sseUrl?: string | false;\n /** @deprecated Use pollUrl instead */\n eventsUrl?: string;\n onEvent?: (data: any) => void;\n interval?: number;\n fallbackInterval?: number;\n pauseWhenHidden?: boolean;\n ignoreSource?: string;\n } = {},\n): void {\n const {\n queryClient,\n pollUrl = agentNativePath(options.eventsUrl ?? \"/_agent-native/poll\"),\n sseUrl = resolveSseUrl(options.sseUrl),\n interval = 2000,\n fallbackInterval = Math.max(\n options.fallbackInterval ?? SSE_FALLBACK_INTERVAL_MS,\n interval,\n ),\n pauseWhenHidden = true,\n } = options;\n\n const onEventRef = useRef(options.onEvent);\n onEventRef.current = options.onEvent;\n\n const ignoreSourceRef = useRef(options.ignoreSource);\n ignoreSourceRef.current = options.ignoreSource;\n\n useEffect(() => {\n const id = Symbol(\"useDbSync\");\n // Per-subscriber version cursor: tracks which events have already been\n // processed by THIS subscriber so stale poll re-deliveries are ignored.\n let subscriberVersion = 0;\n\n function hasAppStateEvent(events: SyncEvent[], key: string): boolean {\n return events.some(\n (event) =>\n event.source === \"app-state\" &&\n (event.key === key ||\n event.key === \"*\" ||\n (typeof event.key === \"string\" && event.key.startsWith(`${key}:`))),\n );\n }\n\n function invalidateForEvents(events: SyncEvent[]) {\n const ignore = ignoreSourceRef.current;\n const relevant = ignore\n ? events.filter((e) => e.requestSource !== ignore)\n : events;\n\n // Bump per-source change counters. Components that read these via\n // `useChangeVersion(source)` and fold the value into a React Query\n // queryKey get a targeted refetch — no whole-cache invalidate, no\n // request storm. See `use-change-version.ts` for the contract.\n for (const evt of relevant) {\n const src = typeof evt.source === \"string\" ? evt.source : \"\";\n const ver = typeof evt.version === \"number\" ? evt.version : 0;\n if (src && ver > 0) bumpChangeVersion(src, ver);\n }\n\n if (relevant.length > 0 && queryClient) {\n const hasActionEvent = relevant.some((evt) => evt.source === \"action\");\n if (hasActionEvent) {\n // Custom apps frequently start with raw `useQuery` calls before\n // graduating to `useActionQuery` or source-versioned query keys.\n // A successful mutating action is the core \"agent changed app data\"\n // signal, so refresh active queries broadly as a compatibility\n // safety net. Other event sources stay targeted to avoid request\n // storms from noisy domain-specific writes.\n queryClient.invalidateQueries();\n }\n\n // Framework-level invalidate: a small, fixed list of query-key\n // prefixes the framework's own hooks/components use (action results,\n // extension state, application-state, the agent's `set-url` channel,\n // etc.). Templates' own data queries do NOT live here — they react\n // through `useChangeVersion(source)` in their query keys instead, so\n // a single change event doesn't fan out into \"refetch everything\".\n queryClient.invalidateQueries({ queryKey: [\"action\"] });\n queryClient.invalidateQueries({ queryKey: [\"extension\"] });\n queryClient.invalidateQueries({ queryKey: [\"extensions\"] });\n queryClient.invalidateQueries({ queryKey: [\"extension-slots\"] });\n queryClient.invalidateQueries({ queryKey: [\"slot-installs\"] });\n queryClient.invalidateQueries({ queryKey: [\"slot-available\"] });\n queryClient.invalidateQueries({ queryKey: [\"tool\"] });\n queryClient.invalidateQueries({ queryKey: [\"tools\"] });\n queryClient.invalidateQueries({ queryKey: [\"app-state\"] });\n if (hasAppStateEvent(relevant, \"navigate\")) {\n queryClient.invalidateQueries({ queryKey: [\"navigate-command\"] });\n }\n if (hasAppStateEvent(relevant, \"show-questions\")) {\n queryClient.invalidateQueries({ queryKey: [\"show-questions\"] });\n }\n if (hasAppStateEvent(relevant, \"__set_url__\")) {\n queryClient.invalidateQueries({ queryKey: [\"__set_url__\"] });\n }\n }\n\n // Always forward all events to onEvent — templates can layer surgical\n // logic on top (e.g. ignore their own writes via requestSource, or\n // invalidate inactive queries for a specific source).\n for (const evt of events) {\n onEventRef.current?.(evt);\n }\n }\n\n function onEvents(events: SyncEvent[], version: number | undefined): void {\n const freshEvents = events.filter((event) => {\n const v = typeof event.version === \"number\" ? event.version : 0;\n return v === 0 || v > subscriberVersion;\n });\n\n if (freshEvents.length > 0) {\n invalidateForEvents(freshEvents);\n }\n\n const maxEventVersion = freshEvents.reduce(\n (max, event) =>\n Math.max(max, typeof event.version === \"number\" ? event.version : 0),\n 0,\n );\n subscriberVersion = Math.max(\n subscriberVersion,\n version ?? 0,\n maxEventVersion,\n );\n }\n\n const transport = getOrCreateTransport(pollUrl, sseUrl);\n transport.add(id, {\n onEvents,\n pauseWhenHidden,\n interval,\n fallbackInterval,\n });\n\n return () => {\n transport.remove(id);\n // If the registry still holds this transport, and the transport is now\n // empty, evict it so the next mount gets a fresh instance rather than a\n // stopped-but-still-registered one (the registry entry being cleared by\n // releaseTransport is the signal to rebuild state).\n if (!transport[\"subscribers\"].size) {\n releaseTransport(pollUrl, sseUrl);\n }\n };\n }, [\n pollUrl,\n sseUrl,\n queryClient,\n interval,\n fallbackInterval,\n pauseWhenHidden,\n ]);\n}\n\n/** @deprecated Use useDbSync instead */\nexport const useFileWatcher = useDbSync;\n\n/**\n * Subscribe to `refresh-screen` events from the agent. Returns an integer\n * that increments every time the agent invokes the framework's `refresh-screen`\n * tool. Apply it as a React `key` on the main content wrapper (the part\n * OUTSIDE the agent chat sidebar) so that region remounts and re-fetches its\n * data while the chat, sidebar, and any other persistent chrome keep their\n * in-flight state.\n *\n * Usage in a template's root:\n *\n * const screenKey = useScreenRefreshKey();\n * return (\n * <AppLayout>\n * <div key={screenKey}>\n * <Outlet />\n * </div>\n * </AppLayout>\n * );\n */\nexport function useScreenRefreshKey(\n options: {\n pollUrl?: string;\n sseUrl?: string | false;\n interval?: number;\n fallbackInterval?: number;\n pauseWhenHidden?: boolean;\n } = {},\n): number {\n const {\n pollUrl = agentNativePath(options.pollUrl ?? \"/_agent-native/poll\"),\n sseUrl = resolveSseUrl(options.sseUrl),\n interval = 2000,\n fallbackInterval = Math.max(\n options.fallbackInterval ?? SSE_FALLBACK_INTERVAL_MS,\n interval,\n ),\n pauseWhenHidden = true,\n } = options;\n const [key, setKey] = useState(0);\n\n useEffect(() => {\n const id = Symbol(\"useScreenRefreshKey\");\n // Per-subscriber version cursor (same freshness logic as useDbSync).\n let subscriberVersion = 0;\n\n function onEvents(events: SyncEvent[], version: number | undefined): void {\n const freshEvents = events.filter((event) => {\n const v = typeof event.version === \"number\" ? event.version : 0;\n return v === 0 || v > subscriberVersion;\n });\n if (freshEvents.some((e) => e.source === \"screen-refresh\")) {\n setKey((k) => k + 1);\n }\n const maxEventVersion = freshEvents.reduce(\n (max, event) =>\n Math.max(max, typeof event.version === \"number\" ? event.version : 0),\n 0,\n );\n subscriberVersion = Math.max(\n subscriberVersion,\n version ?? 0,\n maxEventVersion,\n );\n }\n\n const transport = getOrCreateTransport(pollUrl, sseUrl);\n transport.add(id, {\n onEvents,\n pauseWhenHidden,\n interval,\n fallbackInterval,\n });\n\n return () => {\n transport.remove(id);\n if (!transport[\"subscribers\"].size) {\n releaseTransport(pollUrl, sseUrl);\n }\n };\n }, [pollUrl, sseUrl, interval, fallbackInterval, pauseWhenHidden]);\n\n return key;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"use-db-sync.js","sourceRoot":"","sources":["../../src/client/use-db-sync.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEpD,OAAO,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Ae,GAAG,WAAW,CAAC,MAAM,CACxC,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CACb,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,EACtE,CAAC,CACF,CAAC;YACF,iBAAiB,GAAG,IAAI,CAAC,GAAG,CAC1B,iBAAiB,EACjB,OAAO,IAAI,CAAC,EACZ,eAAe,CAChB,CAAC;QACJ,CAAC;QAED,MAAM,SAAS,GAAG,oBAAoB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACxD,SAAS,CAAC,GAAG,CAAC,EAAE,EAAE;YAChB,QAAQ;YACR,eAAe;YACf,QAAQ;YACR,gBAAgB;SACjB,CAAC,CAAC;QAEH,OAAO,GAAG,EAAE;YACV,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACrB,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC,IAAI,EAAE,CAAC;gBACnC,gBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;YACpC,CAAC;QACH,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,gBAAgB,EAAE,eAAe,CAAC,CAAC,CAAC;IAEnE,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import { useEffect, useRef, useState } from \"react\";\n\nimport { ensureDemoModeFetchInterceptor } from \"../demo/fetch-interceptor.js\";\nimport { agentNativePath } from \"./api-path.js\";\nimport {\n ensureEmbedAuthFetchInterceptor,\n isEmbedAuthActive,\n} from \"./embed-auth.js\";\nimport { bumpChangeVersion } from \"./use-change-version.js\";\n\ninterface Query {\n queryKey: readonly unknown[];\n}\n\ninterface QueryClient {\n invalidateQueries(opts?: {\n queryKey?: string[];\n predicate?: (query: Query) => boolean;\n }): void;\n}\n\nconst POLL_ABORT_MIN_MS = 10_000;\nconst SSE_FALLBACK_INTERVAL_MS = 15_000;\nconst POLL_AUTH_FAILURE_COOLDOWN_MS = 60_000;\n\nclass HttpStatusError extends Error {\n status: number;\n\n constructor(status: number) {\n super(\"HTTP \" + status);\n this.status = status;\n }\n}\n\ntype SyncEvent = {\n version?: number;\n source?: string;\n type?: string;\n key?: string;\n requestSource?: string;\n [k: string]: unknown;\n};\n\ntype PollResponse = {\n version: number;\n events: SyncEvent[];\n};\n\n/** Callback delivered to each transport subscriber for every batch of events. */\ntype EventSubscriber = (\n events: SyncEvent[],\n version: number | undefined,\n) => void;\n\nfunction getPollAbortMs(interval: number): number {\n return Math.max(POLL_ABORT_MIN_MS, interval * 4);\n}\n\nfunction isDocumentHidden(): boolean {\n return (\n typeof document !== \"undefined\" && document.visibilityState === \"hidden\"\n );\n}\n\nfunction resolveSseUrl(sseUrl: string | false | undefined): string | false {\n if (sseUrl === false) return false;\n if (isEmbedAuthActive()) return false;\n return agentNativePath(sseUrl ?? \"/_agent-native/events\");\n}\n\nfunction normalizeEventPayload(payload: unknown): SyncEvent[] {\n if (!payload || typeof payload !== \"object\") return [];\n const record = payload as { type?: unknown; events?: unknown };\n if (record.type === \"batch\" && Array.isArray(record.events)) {\n return record.events.filter(\n (event): event is SyncEvent => !!event && typeof event === \"object\",\n );\n }\n if (Array.isArray(record.events)) {\n return record.events.filter(\n (event): event is SyncEvent => !!event && typeof event === \"object\",\n );\n }\n return [payload as SyncEvent];\n}\n\nfunction isAuthFailure(error: unknown): boolean {\n return (\n !!error &&\n typeof error === \"object\" &&\n \"status\" in error &&\n ((error as { status?: unknown }).status === 401 ||\n (error as { status?: unknown }).status === 403)\n );\n}\n\nasync function fetchPollJson<T>(\n pollUrl: string,\n since: number,\n interval: number,\n): Promise<T> {\n const controller =\n typeof AbortController === \"undefined\" ? null : new AbortController();\n const timeout = controller\n ? setTimeout(() => controller.abort(), getPollAbortMs(interval))\n : null;\n\n try {\n const res = await fetch(\n `${pollUrl}?since=${since}`,\n controller ? { signal: controller.signal } : undefined,\n );\n if (!res.ok) throw new HttpStatusError(res.status);\n // Await the json before the finally so a body-stream abort doesn't\n // produce a dangling promise that escapes as an unhandled rejection.\n return await res.json();\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Shared SSE + poll transport\n//\n// One SyncTransport per (pollUrl, sseUrl) pair is held in a module-level\n// registry. Both `useDbSync` and `useScreenRefreshKey` subscribe to it, so a\n// single browser tab opens exactly ONE SSE connection and ONE poll loop\n// regardless of how many hook instances are mounted.\n//\n// Lifecycle: the transport starts when the first subscriber joins and shuts\n// down when the last subscriber leaves. This makes it safe to SSR and to\n// mount/unmount hooks independently.\n// ---------------------------------------------------------------------------\n\ninterface TransportSubscription {\n onEvents: EventSubscriber;\n /**\n * Whether this subscriber wants the transport to pause when the tab is\n * hidden. The transport pauses only when ALL subscribers request it — any\n * subscriber with `pauseWhenHidden: false` keeps the connection alive.\n */\n pauseWhenHidden: boolean;\n /**\n * Requested poll interval in ms. The transport uses the minimum across all\n * subscribers so the most-frequent caller is satisfied.\n */\n interval: number;\n /** Requested fallback interval while SSE is connected. */\n fallbackInterval: number;\n}\n\nclass SyncTransport {\n private subscribers = new Map<symbol, TransportSubscription>();\n private versionRef = 0;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private stopped = false;\n private inFlight = false;\n private eventSource: EventSource | null = null;\n private sseConnected = false;\n private authFailureUntil = 0;\n\n constructor(\n private readonly pollUrl: string,\n private readonly sseUrl: string | false,\n ) {}\n\n // -------------------------------------------------------------------------\n // Subscriber management\n // -------------------------------------------------------------------------\n\n add(id: symbol, sub: TransportSubscription): void {\n const wasEmpty = this.subscribers.size === 0;\n this.subscribers.set(id, sub);\n if (wasEmpty) {\n this.stopped = false;\n this.start();\n }\n }\n\n remove(id: symbol): void {\n this.subscribers.delete(id);\n if (this.subscribers.size === 0) {\n this.teardown();\n } else {\n // Recalculate poll interval in case the leaving subscriber was the\n // fastest caller; reschedule with the updated cadence.\n this.reschedule();\n }\n }\n\n // -------------------------------------------------------------------------\n // Derived settings (aggregate over active subscribers)\n // -------------------------------------------------------------------------\n\n private get effectivePauseWhenHidden(): boolean {\n // Pause only if every subscriber has opted in.\n for (const sub of this.subscribers.values()) {\n if (!sub.pauseWhenHidden) return false;\n }\n return true;\n }\n\n private get effectiveInterval(): number {\n let min = Infinity;\n for (const sub of this.subscribers.values()) {\n if (sub.interval < min) min = sub.interval;\n }\n return isFinite(min) ? min : 2000;\n }\n\n private get effectiveFallbackInterval(): number {\n let min = Infinity;\n for (const sub of this.subscribers.values()) {\n if (sub.fallbackInterval < min) min = sub.fallbackInterval;\n }\n return isFinite(min) ? min : SSE_FALLBACK_INTERVAL_MS;\n }\n\n // -------------------------------------------------------------------------\n // Event fan-out\n // -------------------------------------------------------------------------\n\n private fan(events: SyncEvent[], version: number | undefined): void {\n for (const sub of this.subscribers.values()) {\n sub.onEvents(events, version);\n }\n }\n\n // -------------------------------------------------------------------------\n // SSE + poll loop (mirrors the original per-hook logic exactly)\n // -------------------------------------------------------------------------\n\n private authFailureDelayMs(): number {\n return Math.max(0, this.authFailureUntil - Date.now());\n }\n\n private schedulePoll(): void {\n if (this.stopped) return;\n if (this.effectivePauseWhenHidden && isDocumentHidden()) return;\n if (this.timer) clearTimeout(this.timer);\n const authDelay = this.authFailureDelayMs();\n if (authDelay > 0) {\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.poll();\n }, authDelay);\n return;\n }\n this.timer = setTimeout(\n () => {\n this.timer = null;\n void this.poll();\n },\n this.sseConnected\n ? this.effectiveFallbackInterval\n : this.effectiveInterval,\n );\n }\n\n private reschedule(): void {\n // Only need to act if a timer is already pending; next natural tick will\n // pick up the new effective interval otherwise.\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n this.schedulePoll();\n }\n }\n\n private closeEvents(): void {\n if (!this.eventSource) return;\n this.eventSource.close();\n this.eventSource = null;\n this.sseConnected = false;\n }\n\n private connectEvents(): void {\n if (\n this.stopped ||\n !this.sseUrl ||\n this.eventSource ||\n typeof EventSource === \"undefined\" ||\n (this.effectivePauseWhenHidden && isDocumentHidden())\n ) {\n return;\n }\n\n const source = new EventSource(this.sseUrl);\n this.eventSource = source;\n source.onopen = () => {\n this.sseConnected = true;\n this.schedulePoll();\n };\n source.onerror = () => {\n this.sseConnected = false;\n // When the browser gives up permanently (HTTP error → readyState\n // CLOSED), it won't auto-reconnect. Drop the ref so a later\n // connectEvents() (on focus/visibility) can establish a fresh stream;\n // otherwise the non-null closed `eventSource` blocks reconnection and\n // we'd be stuck on polling-only forever.\n if (source.readyState === EventSource.CLOSED) {\n this.eventSource = null;\n }\n this.schedulePoll();\n };\n source.onmessage = (message) => {\n try {\n const payload = JSON.parse(message.data);\n const events = normalizeEventPayload(payload);\n const version =\n typeof payload?.version === \"number\" ? payload.version : undefined;\n this.applyVersion(events, version);\n this.fan(events, version);\n } catch {\n // Ignore malformed SSE frames; polling is the safety net.\n }\n };\n }\n\n /**\n * Advance the transport's shared version cursor. Subscribers receive the\n * raw events and decide independently which ones are \"fresh\" relative to\n * their own cursor, but the transport-level cursor ensures the poll\n * `?since=` parameter always advances.\n */\n private applyVersion(events: SyncEvent[], version: number | undefined): void {\n let max = typeof version === \"number\" ? version : 0;\n for (const evt of events) {\n const v = typeof evt.version === \"number\" ? evt.version : 0;\n if (v > max) max = v;\n }\n if (max > this.versionRef) this.versionRef = max;\n }\n\n private async poll(): Promise<void> {\n if (this.stopped || this.inFlight) return;\n this.inFlight = true;\n try {\n const data = await fetchPollJson<PollResponse>(\n this.pollUrl,\n this.versionRef,\n this.effectiveInterval,\n );\n if (this.stopped) return;\n const events = data.events ?? [];\n this.applyVersion(events, data.version);\n this.fan(events, data.version);\n } catch (err) {\n if (this.stopped) return;\n if (isAuthFailure(err)) {\n this.authFailureUntil = Date.now() + POLL_AUTH_FAILURE_COOLDOWN_MS;\n this.closeEvents();\n }\n // Network error — will retry on next interval.\n } finally {\n this.inFlight = false;\n this.schedulePoll();\n }\n }\n\n private pollNow(): void {\n if (this.effectivePauseWhenHidden && isDocumentHidden()) return;\n if (this.authFailureDelayMs() > 0) {\n this.schedulePoll();\n return;\n }\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n this.connectEvents();\n void this.poll();\n }\n\n private handleVisibilityChange = (): void => {\n if (document.visibilityState === \"visible\") {\n this.connectEvents();\n this.pollNow();\n } else if (this.effectivePauseWhenHidden) {\n this.closeEvents();\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n };\n\n private handleFocus = (): void => {\n this.pollNow();\n };\n\n private start(): void {\n // Universal demo-mode redaction for the UI. Idempotent + browser-only +\n // a no-op until demo mode is on. Lives here because every template root\n // already mounts useDbSync, so this needs zero per-template wiring.\n ensureEmbedAuthFetchInterceptor();\n ensureDemoModeFetchInterceptor();\n\n if (!this.effectivePauseWhenHidden || !isDocumentHidden()) {\n this.connectEvents();\n void this.poll();\n }\n window.addEventListener(\"focus\", this.handleFocus);\n document.addEventListener(\"visibilitychange\", this.handleVisibilityChange);\n }\n\n private teardown(): void {\n this.stopped = true;\n this.closeEvents();\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n window.removeEventListener(\"focus\", this.handleFocus);\n document.removeEventListener(\n \"visibilitychange\",\n this.handleVisibilityChange,\n );\n }\n}\n\n/**\n * Registry of active transports keyed by \"<pollUrl>\\0<sseUrl>\".\n * Module-level singleton: survives React render cycles, shared across all\n * hook instances in the same browser tab.\n */\nconst transportRegistry = new Map<string, SyncTransport>();\n\nfunction getOrCreateTransport(\n pollUrl: string,\n sseUrl: string | false,\n): SyncTransport {\n const key = `${pollUrl}\\0${String(sseUrl)}`;\n let transport = transportRegistry.get(key);\n if (!transport) {\n transport = new SyncTransport(pollUrl, sseUrl);\n transportRegistry.set(key, transport);\n }\n return transport;\n}\n\n/** Remove a transport from the registry once torn down (last subscriber left). */\nfunction releaseTransport(pollUrl: string, sseUrl: string | false): void {\n const key = `${pollUrl}\\0${String(sseUrl)}`;\n // Leave the entry in place: SSE/poll is already stopped inside the class;\n // the next subscriber will re-start it via `add()`. Clearing the map entry\n // prevents any dangling reference from the old SyncTransport instance.\n transportRegistry.delete(key);\n}\n\n// ---------------------------------------------------------------------------\n// Internal test helper — reset transport registry between tests.\n// ---------------------------------------------------------------------------\n/** @internal */\nexport function _resetSyncTransportRegistryForTests(): void {\n transportRegistry.clear();\n}\n\n/**\n * Hook that listens to /_agent-native/events for DB change events and\n * invalidates react-query caches when changes are detected. Falls back to\n * /_agent-native/poll so cross-process/serverless writes still show up.\n *\n * Works in all deployment environments (serverless, edge, long-lived server).\n * SSE is the fast path; polling is the safety net.\n *\n * @param options.queryClient - The react-query QueryClient instance\n * @param options.queryKeys - **Deprecated and ignored.** The hook uses\n * framework-owned fixed prefixes plus per-source change counters instead of\n * caller-supplied key lists. Kept in the type signature for backward\n * compatibility — existing call sites that still pass this option keep\n * working but the value has no effect.\n * @param options.pollUrl - Poll endpoint URL. Default: \"/_agent-native/poll\"\n * @param options.sseUrl - SSE endpoint URL. Default: \"/_agent-native/events\".\n * Pass false to disable SSE and use polling only.\n * @param options.onEvent - Optional callback for each change event\n * @param options.interval - Poll interval in ms. Default: 2000\n * @param options.fallbackInterval - Poll interval while SSE is connected.\n * Default: 15000\n * @param options.pauseWhenHidden - Pause polling while the tab is hidden.\n * Default: true\n * @param options.ignoreSource - Skip events whose `requestSource` matches this\n * value. Use a per-tab ID so the UI ignores its own writes while still\n * picking up changes from other tabs, agents, and scripts.\n * @param options.actionInvalidatePredicate - Optional filter for the broad\n * compatibility invalidate triggered by `action` events. Use this to keep\n * expensive active queries on explicit-refresh semantics while still letting\n * normal source-versioned queries react through `useChangeVersion`.\n */\nexport function useDbSync(\n options: {\n queryClient?: QueryClient;\n queryKeys?: string[];\n pollUrl?: string;\n sseUrl?: string | false;\n /** @deprecated Use pollUrl instead */\n eventsUrl?: string;\n onEvent?: (data: any) => void;\n interval?: number;\n fallbackInterval?: number;\n pauseWhenHidden?: boolean;\n ignoreSource?: string;\n actionInvalidatePredicate?: (query: Query) => boolean;\n } = {},\n): void {\n const {\n queryClient,\n pollUrl = agentNativePath(options.eventsUrl ?? \"/_agent-native/poll\"),\n sseUrl = resolveSseUrl(options.sseUrl),\n interval = 2000,\n fallbackInterval = Math.max(\n options.fallbackInterval ?? SSE_FALLBACK_INTERVAL_MS,\n interval,\n ),\n pauseWhenHidden = true,\n } = options;\n\n const onEventRef = useRef(options.onEvent);\n onEventRef.current = options.onEvent;\n\n const ignoreSourceRef = useRef(options.ignoreSource);\n ignoreSourceRef.current = options.ignoreSource;\n const actionInvalidatePredicateRef = useRef(\n options.actionInvalidatePredicate,\n );\n actionInvalidatePredicateRef.current = options.actionInvalidatePredicate;\n\n useEffect(() => {\n const id = Symbol(\"useDbSync\");\n // Per-subscriber version cursor: tracks which events have already been\n // processed by THIS subscriber so stale poll re-deliveries are ignored.\n let subscriberVersion = 0;\n\n function hasAppStateEvent(events: SyncEvent[], key: string): boolean {\n return events.some(\n (event) =>\n event.source === \"app-state\" &&\n (event.key === key ||\n event.key === \"*\" ||\n (typeof event.key === \"string\" && event.key.startsWith(`${key}:`))),\n );\n }\n\n function invalidateForEvents(events: SyncEvent[]) {\n const ignore = ignoreSourceRef.current;\n const relevant = ignore\n ? events.filter((e) => e.requestSource !== ignore)\n : events;\n\n // Bump per-source change counters. Components that read these via\n // `useChangeVersion(source)` and fold the value into a React Query\n // queryKey get a targeted refetch — no whole-cache invalidate, no\n // request storm. See `use-change-version.ts` for the contract.\n for (const evt of relevant) {\n const src = typeof evt.source === \"string\" ? evt.source : \"\";\n const ver = typeof evt.version === \"number\" ? evt.version : 0;\n if (src && ver > 0) bumpChangeVersion(src, ver);\n }\n\n if (relevant.length > 0 && queryClient) {\n const hasActionEvent = relevant.some((evt) => evt.source === \"action\");\n if (hasActionEvent) {\n // Custom apps frequently start with raw `useQuery` calls before\n // graduating to `useActionQuery` or source-versioned query keys.\n // A successful mutating action is the core \"agent changed app data\"\n // signal, so refresh active queries broadly as a compatibility\n // safety net. Other event sources stay targeted to avoid request\n // storms from noisy domain-specific writes.\n const predicate = actionInvalidatePredicateRef.current;\n queryClient.invalidateQueries(predicate ? { predicate } : undefined);\n }\n\n // Framework-level invalidate: a small, fixed list of query-key\n // prefixes the framework's own hooks/components use (action results,\n // extension state, application-state, the agent's `set-url` channel,\n // etc.). Templates' own data queries do NOT live here — they react\n // through `useChangeVersion(source)` in their query keys instead, so\n // a single change event doesn't fan out into \"refetch everything\".\n queryClient.invalidateQueries({ queryKey: [\"action\"] });\n queryClient.invalidateQueries({ queryKey: [\"extension\"] });\n queryClient.invalidateQueries({ queryKey: [\"extensions\"] });\n queryClient.invalidateQueries({ queryKey: [\"extension-slots\"] });\n queryClient.invalidateQueries({ queryKey: [\"slot-installs\"] });\n queryClient.invalidateQueries({ queryKey: [\"slot-available\"] });\n queryClient.invalidateQueries({ queryKey: [\"tool\"] });\n queryClient.invalidateQueries({ queryKey: [\"tools\"] });\n queryClient.invalidateQueries({ queryKey: [\"app-state\"] });\n if (hasAppStateEvent(relevant, \"navigate\")) {\n queryClient.invalidateQueries({ queryKey: [\"navigate-command\"] });\n }\n if (hasAppStateEvent(relevant, \"show-questions\")) {\n queryClient.invalidateQueries({ queryKey: [\"show-questions\"] });\n }\n if (hasAppStateEvent(relevant, \"__set_url__\")) {\n queryClient.invalidateQueries({ queryKey: [\"__set_url__\"] });\n }\n }\n\n // Always forward all events to onEvent — templates can layer surgical\n // logic on top (e.g. ignore their own writes via requestSource, or\n // invalidate inactive queries for a specific source).\n for (const evt of events) {\n onEventRef.current?.(evt);\n }\n }\n\n function onEvents(events: SyncEvent[], version: number | undefined): void {\n const freshEvents = events.filter((event) => {\n const v = typeof event.version === \"number\" ? event.version : 0;\n return v === 0 || v > subscriberVersion;\n });\n\n if (freshEvents.length > 0) {\n invalidateForEvents(freshEvents);\n }\n\n const maxEventVersion = freshEvents.reduce(\n (max, event) =>\n Math.max(max, typeof event.version === \"number\" ? event.version : 0),\n 0,\n );\n subscriberVersion = Math.max(\n subscriberVersion,\n version ?? 0,\n maxEventVersion,\n );\n }\n\n const transport = getOrCreateTransport(pollUrl, sseUrl);\n transport.add(id, {\n onEvents,\n pauseWhenHidden,\n interval,\n fallbackInterval,\n });\n\n return () => {\n transport.remove(id);\n // If the registry still holds this transport, and the transport is now\n // empty, evict it so the next mount gets a fresh instance rather than a\n // stopped-but-still-registered one (the registry entry being cleared by\n // releaseTransport is the signal to rebuild state).\n if (!transport[\"subscribers\"].size) {\n releaseTransport(pollUrl, sseUrl);\n }\n };\n }, [\n pollUrl,\n sseUrl,\n queryClient,\n interval,\n fallbackInterval,\n pauseWhenHidden,\n ]);\n}\n\n/** @deprecated Use useDbSync instead */\nexport const useFileWatcher = useDbSync;\n\n/**\n * Subscribe to `refresh-screen` events from the agent. Returns an integer\n * that increments every time the agent invokes the framework's `refresh-screen`\n * tool. Apply it as a React `key` on the main content wrapper (the part\n * OUTSIDE the agent chat sidebar) so that region remounts and re-fetches its\n * data while the chat, sidebar, and any other persistent chrome keep their\n * in-flight state.\n *\n * Usage in a template's root:\n *\n * const screenKey = useScreenRefreshKey();\n * return (\n * <AppLayout>\n * <div key={screenKey}>\n * <Outlet />\n * </div>\n * </AppLayout>\n * );\n */\nexport function useScreenRefreshKey(\n options: {\n pollUrl?: string;\n sseUrl?: string | false;\n interval?: number;\n fallbackInterval?: number;\n pauseWhenHidden?: boolean;\n } = {},\n): number {\n const {\n pollUrl = agentNativePath(options.pollUrl ?? \"/_agent-native/poll\"),\n sseUrl = resolveSseUrl(options.sseUrl),\n interval = 2000,\n fallbackInterval = Math.max(\n options.fallbackInterval ?? SSE_FALLBACK_INTERVAL_MS,\n interval,\n ),\n pauseWhenHidden = true,\n } = options;\n const [key, setKey] = useState(0);\n\n useEffect(() => {\n const id = Symbol(\"useScreenRefreshKey\");\n // Per-subscriber version cursor (same freshness logic as useDbSync).\n let subscriberVersion = 0;\n\n function onEvents(events: SyncEvent[], version: number | undefined): void {\n const freshEvents = events.filter((event) => {\n const v = typeof event.version === \"number\" ? event.version : 0;\n return v === 0 || v > subscriberVersion;\n });\n if (freshEvents.some((e) => e.source === \"screen-refresh\")) {\n setKey((k) => k + 1);\n }\n const maxEventVersion = freshEvents.reduce(\n (max, event) =>\n Math.max(max, typeof event.version === \"number\" ? event.version : 0),\n 0,\n );\n subscriberVersion = Math.max(\n subscriberVersion,\n version ?? 0,\n maxEventVersion,\n );\n }\n\n const transport = getOrCreateTransport(pollUrl, sseUrl);\n transport.add(id, {\n onEvents,\n pauseWhenHidden,\n interval,\n fallbackInterval,\n });\n\n return () => {\n transport.remove(id);\n if (!transport[\"subscribers\"].size) {\n releaseTransport(pollUrl, sseUrl);\n }\n };\n }, [pollUrl, sseUrl, interval, fallbackInterval, pauseWhenHidden]);\n\n return key;\n}\n"]}
|
|
@@ -3,18 +3,18 @@ declare const _default: import("../../action.js").ActionDefinition<{
|
|
|
3
3
|
url?: string;
|
|
4
4
|
filename?: string;
|
|
5
5
|
}, {
|
|
6
|
-
id?: undefined;
|
|
7
6
|
error: string;
|
|
8
7
|
configured?: undefined;
|
|
9
8
|
connectPath?: undefined;
|
|
10
9
|
url?: undefined;
|
|
10
|
+
id?: undefined;
|
|
11
11
|
provider?: undefined;
|
|
12
12
|
} | {
|
|
13
|
-
id?: undefined;
|
|
14
13
|
error: string;
|
|
15
14
|
configured: boolean;
|
|
16
15
|
connectPath: string;
|
|
17
16
|
url?: undefined;
|
|
17
|
+
id?: undefined;
|
|
18
18
|
provider?: undefined;
|
|
19
19
|
} | {
|
|
20
20
|
error?: undefined;
|
|
@@ -13,13 +13,13 @@
|
|
|
13
13
|
export declare function createNotificationsHandler(): import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<"" | import("./types.js").Notification[] | {
|
|
14
14
|
count: number;
|
|
15
15
|
updated?: undefined;
|
|
16
|
-
error?: undefined;
|
|
17
16
|
ok?: undefined;
|
|
17
|
+
error?: undefined;
|
|
18
18
|
} | {
|
|
19
19
|
count?: undefined;
|
|
20
20
|
updated: number;
|
|
21
|
-
error?: undefined;
|
|
22
21
|
ok?: undefined;
|
|
22
|
+
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
count?: undefined;
|
|
25
25
|
updated?: undefined;
|
|
@@ -43,26 +43,26 @@ export declare function createObservabilityHandler(): import("h3").EventHandlerW
|
|
|
43
43
|
} | {
|
|
44
44
|
summary: import("./types.js").TraceSummary;
|
|
45
45
|
spans: import("./types.js").TraceSpan[];
|
|
46
|
-
id?: undefined;
|
|
47
|
-
error?: undefined;
|
|
48
46
|
ok?: undefined;
|
|
47
|
+
error?: undefined;
|
|
48
|
+
id?: undefined;
|
|
49
49
|
} | {
|
|
50
50
|
summary?: undefined;
|
|
51
51
|
spans?: undefined;
|
|
52
52
|
id: string;
|
|
53
|
-
error?: undefined;
|
|
54
53
|
ok?: undefined;
|
|
54
|
+
error?: undefined;
|
|
55
55
|
} | {
|
|
56
56
|
summary?: undefined;
|
|
57
57
|
spans?: undefined;
|
|
58
|
-
id?: undefined;
|
|
59
58
|
error: any;
|
|
60
59
|
ok?: undefined;
|
|
60
|
+
id?: undefined;
|
|
61
61
|
} | {
|
|
62
62
|
summary?: undefined;
|
|
63
63
|
spans?: undefined;
|
|
64
|
-
id?: undefined;
|
|
65
|
-
error?: undefined;
|
|
66
64
|
ok: boolean;
|
|
65
|
+
error?: undefined;
|
|
66
|
+
id?: undefined;
|
|
67
67
|
}>>;
|
|
68
68
|
//# sourceMappingURL=routes.d.ts.map
|
|
@@ -4,6 +4,10 @@ export interface AuthMarketingContent {
|
|
|
4
4
|
description?: string;
|
|
5
5
|
features?: string[];
|
|
6
6
|
runLocalCommand?: string;
|
|
7
|
+
signupLocalModeNote?: {
|
|
8
|
+
text: string;
|
|
9
|
+
command: string;
|
|
10
|
+
};
|
|
7
11
|
}
|
|
8
12
|
export interface ResolveBuiltInAuthMarketingOptions {
|
|
9
13
|
requestHost?: string;
|