@burdenoff/microfe-botmanor 2026.1203.4 → 2026.1203.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/botlit/BotlitRoutes.js +0 -1
- package/dist/botlit/BotlitRoutes.js.map +1 -1
- package/dist/botlit/components/A2ACardVerificationCard.js +0 -1
- package/dist/botlit/components/A2ACardVerificationCard.js.map +1 -1
- package/dist/botlit/components/AgentA2APanel.js +20 -21
- package/dist/botlit/components/AgentA2APanel.js.map +1 -1
- package/dist/botlit/components/AgentApprovalPanel.js +22 -23
- package/dist/botlit/components/AgentApprovalPanel.js.map +1 -1
- package/dist/botlit/components/AgentBindingsPanel.js +66 -68
- package/dist/botlit/components/AgentBindingsPanel.js.map +1 -1
- package/dist/botlit/components/AiOperationsPanel.js +34 -35
- package/dist/botlit/components/AiOperationsPanel.js.map +1 -1
- package/dist/botlit/components/BotAgentsPanel.js +59 -60
- package/dist/botlit/components/BotAgentsPanel.js.map +1 -1
- package/dist/botlit/components/BotVersionHistoryPanel.js +19 -20
- package/dist/botlit/components/BotVersionHistoryPanel.js.map +1 -1
- package/dist/botlit/components/BucketDialogs.js +0 -1
- package/dist/botlit/components/BucketDialogs.js.map +1 -1
- package/dist/botlit/components/ChannelRoutesPanel.js +82 -84
- package/dist/botlit/components/ChannelRoutesPanel.js.map +1 -1
- package/dist/botlit/components/CreateChannelRouteDialog.js +4 -5
- package/dist/botlit/components/CreateChannelRouteDialog.js.map +1 -1
- package/dist/botlit/components/DescribeBotDialog.js +0 -1
- package/dist/botlit/components/DescribeBotDialog.js.map +1 -1
- package/dist/botlit/components/GettingStartedChecklist.js +9 -10
- package/dist/botlit/components/GettingStartedChecklist.js.map +1 -1
- package/dist/botlit/components/HandoffConfigPanel.js +0 -1
- package/dist/botlit/components/HandoffConfigPanel.js.map +1 -1
- package/dist/botlit/components/RetentionStatusPanel.js +10 -12
- package/dist/botlit/components/RetentionStatusPanel.js.map +1 -1
- package/dist/botlit/components/StewardApprovalsInbox.js +201 -212
- package/dist/botlit/components/StewardApprovalsInbox.js.map +1 -1
- package/dist/botlit/components/StoreOwnPackagesCard.js +21 -22
- package/dist/botlit/components/StoreOwnPackagesCard.js.map +1 -1
- package/dist/botlit/components/StorePackageDraftCard.js +38 -39
- package/dist/botlit/components/StorePackageDraftCard.js.map +1 -1
- package/dist/botlit/components/StorePolicyBundleCard.js +27 -29
- package/dist/botlit/components/StorePolicyBundleCard.js.map +1 -1
- package/dist/botlit/components/StoreSubmissionsCard.js +64 -65
- package/dist/botlit/components/StoreSubmissionsCard.js.map +1 -1
- package/dist/botlit/components/VersionHistoryPanel.js +18 -19
- package/dist/botlit/components/VersionHistoryPanel.js.map +1 -1
- package/dist/botlit/hooks/internal/workspaceGateway.d.ts +6 -0
- package/dist/botlit/hooks/internal/workspaceGateway.js +40 -40
- package/dist/botlit/hooks/internal/workspaceGateway.js.map +1 -1
- package/dist/botlit/hooks/useChannels.js +2 -0
- package/dist/botlit/hooks/useChannels.js.map +1 -1
- package/dist/botlit/hooks/useToolApprovals.d.ts +8 -3
- package/dist/botlit/hooks/useToolApprovals.js +68 -73
- package/dist/botlit/hooks/useToolApprovals.js.map +1 -1
- package/dist/botlit/pages/A2AAgentDetailPage.js +331 -332
- package/dist/botlit/pages/A2AAgentDetailPage.js.map +1 -1
- package/dist/botlit/pages/A2ARegistryPage.js +39 -41
- package/dist/botlit/pages/A2ARegistryPage.js.map +1 -1
- package/dist/botlit/pages/AgentApprovalsPage.js +24 -25
- package/dist/botlit/pages/AgentApprovalsPage.js.map +1 -1
- package/dist/botlit/pages/AgentBuilderPage.js +470 -471
- package/dist/botlit/pages/AgentBuilderPage.js.map +1 -1
- package/dist/botlit/pages/AgentDetailPage.js +68 -69
- package/dist/botlit/pages/AgentDetailPage.js.map +1 -1
- package/dist/botlit/pages/AgentsListPage.js +277 -278
- package/dist/botlit/pages/AgentsListPage.js.map +1 -1
- package/dist/botlit/pages/AiOperationsPage.js +44 -46
- package/dist/botlit/pages/AiOperationsPage.js.map +1 -1
- package/dist/botlit/pages/BotChannelsTab.js +354 -356
- package/dist/botlit/pages/BotChannelsTab.js.map +1 -1
- package/dist/botlit/pages/BotDetailPage.js +138 -139
- package/dist/botlit/pages/BotDetailPage.js.map +1 -1
- package/dist/botlit/pages/BotWorkflowTab.js +23 -24
- package/dist/botlit/pages/BotWorkflowTab.js.map +1 -1
- package/dist/botlit/pages/BotsListPage.js +32 -33
- package/dist/botlit/pages/BotsListPage.js.map +1 -1
- package/dist/botlit/pages/BucketDetailPage.js +110 -112
- package/dist/botlit/pages/BucketDetailPage.js.map +1 -1
- package/dist/botlit/pages/BucketsPage.js +115 -117
- package/dist/botlit/pages/BucketsPage.js.map +1 -1
- package/dist/botlit/pages/ChannelDetailPage.js +105 -107
- package/dist/botlit/pages/ChannelDetailPage.js.map +1 -1
- package/dist/botlit/pages/ChannelsPage.js +38 -40
- package/dist/botlit/pages/ChannelsPage.js.map +1 -1
- package/dist/botlit/pages/DashboardPage.js +26 -27
- package/dist/botlit/pages/DashboardPage.js.map +1 -1
- package/dist/botlit/pages/ExecutionDetailPage.js +70 -71
- package/dist/botlit/pages/ExecutionDetailPage.js.map +1 -1
- package/dist/botlit/pages/ExecutionsPage.js +219 -220
- package/dist/botlit/pages/ExecutionsPage.js.map +1 -1
- package/dist/botlit/pages/HandoffsPage.js +208 -210
- package/dist/botlit/pages/HandoffsPage.js.map +1 -1
- package/dist/botlit/pages/InstalledPackagesPage.js +179 -181
- package/dist/botlit/pages/InstalledPackagesPage.js.map +1 -1
- package/dist/botlit/pages/KnowledgeBaseDetailPage.js +194 -195
- package/dist/botlit/pages/KnowledgeBaseDetailPage.js.map +1 -1
- package/dist/botlit/pages/KnowledgeBasesPage.js +38 -39
- package/dist/botlit/pages/KnowledgeBasesPage.js.map +1 -1
- package/dist/botlit/pages/MCPServerDetailPage.js +178 -180
- package/dist/botlit/pages/MCPServerDetailPage.js.map +1 -1
- package/dist/botlit/pages/MCPServersPage.js +42 -43
- package/dist/botlit/pages/MCPServersPage.js.map +1 -1
- package/dist/botlit/pages/PoliciesPage.js +77 -78
- package/dist/botlit/pages/PoliciesPage.js.map +1 -1
- package/dist/botlit/pages/PolicyDetailPage.js +517 -519
- package/dist/botlit/pages/PolicyDetailPage.js.map +1 -1
- package/dist/botlit/pages/PromptStudioPage.js +81 -83
- package/dist/botlit/pages/PromptStudioPage.js.map +1 -1
- package/dist/botlit/pages/PromptTemplateDetailPage.js +137 -139
- package/dist/botlit/pages/PromptTemplateDetailPage.js.map +1 -1
- package/dist/botlit/pages/PromptTemplatesPage.js +28 -30
- package/dist/botlit/pages/PromptTemplatesPage.js.map +1 -1
- package/dist/botlit/pages/RetrievalProfileDetailPage.js +64 -65
- package/dist/botlit/pages/RetrievalProfileDetailPage.js.map +1 -1
- package/dist/botlit/pages/RetrievalProfilesPage.js +59 -60
- package/dist/botlit/pages/RetrievalProfilesPage.js.map +1 -1
- package/dist/botlit/pages/SettingsPage.js +30 -31
- package/dist/botlit/pages/SettingsPage.js.map +1 -1
- package/dist/botlit/pages/SkillDetailPage.js +205 -207
- package/dist/botlit/pages/SkillDetailPage.js.map +1 -1
- package/dist/botlit/pages/SkillsPage.js +68 -69
- package/dist/botlit/pages/SkillsPage.js.map +1 -1
- package/dist/botlit/pages/StorePackageDetailPage.js +39 -41
- package/dist/botlit/pages/StorePackageDetailPage.js.map +1 -1
- package/dist/botlit/pages/StorePage.js +169 -171
- package/dist/botlit/pages/StorePage.js.map +1 -1
- package/dist/botlit/pages/ToolApprovalsPage.js +61 -62
- package/dist/botlit/pages/ToolApprovalsPage.js.map +1 -1
- package/dist/generated/global-types.d.ts +540 -171
- package/dist/generated/global-types.js.map +1 -1
- package/dist/generated/wspace-operations.d.ts +38 -4
- package/dist/generated/wspace-operations.js.map +1 -1
- package/dist/generated/wspace-types.d.ts +9539 -686
- package/dist/generated/wspace-types.js.map +1 -1
- package/dist/index.js +0 -1
- package/package.json +4 -1
- package/dist/botlit/hooks/index.js +0 -21
- package/dist/botlit/index.js +0 -12
- package/dist/botlit/permissions/index.js +0 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VersionHistoryPanel.js","names":["versionStatusVariant","status","VersionHistoryPanel","t","useTr","versions","useAgentVersions","agentId","publishAgentVersion","publishState","usePublishAgentVersion","rollbackAgentVersion","rollbackState","useRollbackAgentVersion","publishOpen","setPublishOpen","useState","changelogDraft","setChangelogDraft","rollbackTarget","setRollbackTarget","handlePublish","draftVersionId","published","toast","refetch","onChanged","err","handleRollback","restored","Card","CardHeader","CardTitle","History","CardDescription","loading","error","appendError","BotmanorPermissionGate","BOTMANOR_PERMISSIONS","Button","Rocket","CardContent","ErrorState","isCurrent","version","currentVersionId","canRollback","Badge","CheckCircle2","formatRelativeTime","RotateCcw","loadMore","LoadMore","hasMore","Dialog","DialogContent","DialogHeader","DialogTitle","DialogDescription","Textarea","DialogFooter","AlertDialog","open","AlertDialogContent","AlertDialogHeader","AlertDialogTitle","AlertDialogDescription","AlertDialogFooter","AlertDialogCancel","AlertDialogAction"],"sources":["../../../src/botlit/components/VersionHistoryPanel.tsx"],"sourcesContent":["/**\n * Version History Panel (BOFF-4381)\n * @module botlit/components\n *\n * Real, discoverable UI for agent versioning: shows the full version\n * history (draft/published/historical), lets a workspace admin publish the\n * current draft with a changelog, and roll back to any prior published\n * version with a confirmation step.\n */\n\nimport { useState, type FC } from 'react';\nimport { History, Rocket, RotateCcw, CheckCircle2 } from 'lucide-react';\nimport { toast } from 'sonner';\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n Textarea,\n} from '@burdenoff/fe-libs/ui';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { Card, CardContent, CardHeader, CardTitle, CardDescription } from './Card';\nimport { Button } from './Button';\nimport { Badge } from './Badge';\nimport { ErrorState } from './ErrorState';\nimport { LoadMore } from './LoadMore';\nimport {\n useAgentVersions,\n usePublishAgentVersion,\n useRollbackAgentVersion,\n type AgentVersionRecord,\n} from '../hooks/useAgents';\nimport { formatRelativeTime } from '../utils/formatters';\nimport { BOTMANOR_PERMISSIONS, BotmanorPermissionGate } from '../permissions';\n\ninterface VersionHistoryPanelProps {\n agentId: string;\n /** The agent's current draft version id (if any) — enables the Publish action. */\n draftVersionId?: string | null;\n /** The agent's current live (published) version id — hidden from the rollback list. */\n currentVersionId?: string | null;\n /** Called after a successful publish or rollback so the caller can refetch the agent itself. */\n onChanged?: () => void;\n}\n\nfunction versionStatusVariant(\n status: AgentVersionRecord['status']\n): 'secondary' | 'success' | 'outline' {\n if (status === 'DRAFT') return 'secondary';\n if (status === 'PUBLISHED') return 'success';\n return 'outline';\n}\n\nexport const VersionHistoryPanel: FC<VersionHistoryPanelProps> = ({\n agentId,\n draftVersionId,\n currentVersionId,\n onChanged,\n}) => {\n const t = useTr();\n\n const {\n data: versions,\n loading,\n error,\n appendError,\n refetch,\n hasMore,\n loadingMore,\n loadMore,\n } = useAgentVersions(agentId);\n const [publishAgentVersion, publishState] = usePublishAgentVersion();\n const [rollbackAgentVersion, rollbackState] = useRollbackAgentVersion();\n\n const [publishOpen, setPublishOpen] = useState(false);\n const [changelogDraft, setChangelogDraft] = useState('');\n const [rollbackTarget, setRollbackTarget] = useState<AgentVersionRecord | null>(null);\n\n const handlePublish = async (): Promise<void> => {\n if (!draftVersionId) return;\n try {\n const published = await publishAgentVersion({\n agentId,\n versionId: draftVersionId,\n changelog: changelogDraft,\n });\n toast.success(\n `${t('botlit.agentDetail.versions.publishSuccessPrefix', 'Published version')} ${published.version}`\n );\n setPublishOpen(false);\n setChangelogDraft('');\n await refetch();\n onChanged?.();\n } catch (err: unknown) {\n toast.error(\n err instanceof Error\n ? err.message\n : t('botlit.agentDetail.versions.publishError', 'Failed to publish version')\n );\n }\n };\n\n const handleRollback = async (): Promise<void> => {\n if (!rollbackTarget) return;\n try {\n const restored = await rollbackAgentVersion({ agentId, targetVersionId: rollbackTarget.id });\n toast.success(\n `${t('botlit.agentDetail.versions.rollbackSuccessPrefix', 'Rolled back to version')} ${rollbackTarget.version} (${t('botlit.agentDetail.versions.rollbackSuccessSuffix', 'now')} ${restored.version})`\n );\n setRollbackTarget(null);\n await refetch();\n onChanged?.();\n } catch (err: unknown) {\n toast.error(\n err instanceof Error\n ? err.message\n : t('botlit.agentDetail.versions.rollbackError', 'Failed to roll back agent version')\n );\n }\n };\n\n return (\n <div className=\"space-y-6\">\n <Card>\n <CardHeader className=\"flex flex-row items-start justify-between gap-4\">\n <div>\n <CardTitle className=\"flex items-center gap-2\">\n <History size={18} />\n {t('botlit.agentDetail.versions.title', 'Version History')}\n </CardTitle>\n <CardDescription>\n {t(\n 'botlit.agentDetail.versions.description',\n 'Every published configuration change, with a diff-able changelog. Publish the current draft or roll back to any prior version.'\n )}\n </CardDescription>\n </div>\n {draftVersionId && !loading && (!error || appendError) && (\n <BotmanorPermissionGate permission={BOTMANOR_PERMISSIONS.AGENT_PUBLISH}>\n <Button leftIcon={<Rocket size={16} />} onClick={() => setPublishOpen(true)}>\n {t('botlit.agentDetail.versions.publishDraft', 'Publish Draft')}\n </Button>\n </BotmanorPermissionGate>\n )}\n </CardHeader>\n <CardContent>\n {loading ? (\n <div className=\"h-32 bg-bg-sunken motion-safe:animate-vc-shimmer rounded-lg\" />\n ) : error && !appendError ? (\n <ErrorState\n resource={t('botlit.agentDetail.versions.resource', 'agent versions')}\n error={error}\n onRetry={() => void refetch()}\n />\n ) : versions.length === 0 ? (\n <p className=\"text-text-secondary\">\n {t('botlit.agentDetail.versions.empty', 'No version history yet.')}\n </p>\n ) : (\n <ul className=\"space-y-3\">\n {versions.map((version) => {\n const isCurrent = version.id === currentVersionId;\n const canRollback = version.status !== 'DRAFT' && !isCurrent;\n return (\n <li\n key={version.id}\n className=\"flex items-start justify-between gap-4 p-4 border border-border-subtle rounded-lg\"\n >\n <div className=\"space-y-1 min-w-0\">\n <div className=\"flex items-center gap-2 flex-wrap\">\n <span className=\"font-mono font-medium\">v{version.version}</span>\n <Badge variant={versionStatusVariant(version.status)}>\n {version.status}\n </Badge>\n {isCurrent && (\n <Badge variant=\"outline\" className=\"flex items-center gap-1\">\n <CheckCircle2 size={12} />\n {t('botlit.agentDetail.versions.liveNow', 'Live now')}\n </Badge>\n )}\n </div>\n <p className=\"text-sm text-text-secondary break-words\">\n {version.changelog ||\n t('botlit.agentDetail.versions.noChangelog', 'No description')}\n </p>\n <p className=\"text-xs text-text-secondary\">\n {version.status === 'DRAFT'\n ? `${t('botlit.agentDetail.versions.updated', 'Updated')} ${formatRelativeTime(version.createdAt)}`\n : `${t('botlit.agentDetail.versions.published', 'Published')} ${formatRelativeTime(version.publishedAt ?? version.createdAt)}`}\n </p>\n </div>\n {canRollback && (\n <BotmanorPermissionGate permission={BOTMANOR_PERMISSIONS.AGENT_ROLLBACK}>\n <Button\n variant=\"outline\"\n size=\"sm\"\n leftIcon={<RotateCcw size={14} />}\n onClick={() => setRollbackTarget(version)}\n >\n {t('botlit.agentDetail.versions.rollback', 'Roll back')}\n </Button>\n </BotmanorPermissionGate>\n )}\n </li>\n );\n })}\n </ul>\n )}\n {error && appendError && (\n <ErrorState\n resource={t('botlit.agentDetail.versions.moreResource', 'more agent versions')}\n error={error}\n onRetry={() => void loadMore()}\n />\n )}\n <LoadMore\n hasMore={hasMore && !error && !loading}\n loadingMore={loadingMore}\n onLoadMore={() => void loadMore()}\n loadedCount={versions.length}\n />\n </CardContent>\n </Card>\n\n {/* Publish dialog */}\n <Dialog open={publishOpen} onOpenChange={setPublishOpen}>\n <DialogContent>\n <DialogHeader>\n <DialogTitle>\n {t('botlit.agentDetail.versions.publishDialog.title', 'Publish this version')}\n </DialogTitle>\n <DialogDescription>\n {t(\n 'botlit.agentDetail.versions.publishDialog.description',\n \"This makes the draft's prompt, model, tools, and policy settings live for the agent. Describe what changed.\"\n )}\n </DialogDescription>\n </DialogHeader>\n <Textarea\n value={changelogDraft}\n onChange={(e) => setChangelogDraft(e.target.value)}\n placeholder={t(\n 'botlit.agentDetail.versions.publishDialog.placeholder',\n 'e.g. Tightened the system prompt and switched to gpt-4o'\n )}\n rows={4}\n />\n <DialogFooter>\n <Button variant=\"outline\" onClick={() => setPublishOpen(false)}>\n {t('botlit.common.cancel', 'Cancel')}\n </Button>\n <Button isLoading={publishState.loading} onClick={() => void handlePublish()}>\n {t('botlit.agentDetail.versions.publishDialog.confirm', 'Publish')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n\n {/* Rollback confirmation */}\n <AlertDialog\n open={rollbackTarget !== null}\n onOpenChange={(open) => !open && setRollbackTarget(null)}\n >\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>\n {t('botlit.agentDetail.versions.rollbackDialog.title', 'Roll back to this version?')}\n </AlertDialogTitle>\n <AlertDialogDescription>\n {rollbackTarget &&\n `${t('botlit.agentDetail.versions.rollbackDialog.descriptionPrefix', 'This immediately restores the agent to version')} ${rollbackTarget.version}${t('botlit.agentDetail.versions.rollbackDialog.descriptionSuffix', '. The current live config is kept in history and can be restored the same way.')}`}\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel onClick={() => setRollbackTarget(null)}>\n {t('botlit.common.cancel', 'Cancel')}\n </AlertDialogCancel>\n <AlertDialogAction\n disabled={rollbackState.loading}\n onClick={() => void handleRollback()}\n >\n {t('botlit.agentDetail.versions.rollbackDialog.confirm', 'Roll back')}\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAuDA,SAASA,EACP,GACqC;CAGrC,OAFIC,MAAW,UAAgB,cAC3BA,MAAW,cAAoB,YAC5B;AACT;AAEA,IAAaC,KAAqD,EAChE,YACA,mBACA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atusVariant","status","VersionHistoryPanel","t","useTr","versions","useAgentVersions","agentId","publishAgentVersion","publishState","usePublishAgentVersion","rollbackAgentVersion","rollbackState","useRollbackAgentVersion","publishOpen","setPublishOpen","useState","changelogDraft","setChangelogDraft","rollbackTarget","setRollbackTarget","handlePublish","draftVersionId","published","toast","refetch","onChanged","err","handleRollback","restored","Card","CardHeader","CardTitle","History","CardDescription","loading","error","appendError","BotmanorPermissionGate","BOTMANOR_PERMISSIONS","Button","Rocket","CardContent","ErrorState","isCurrent","version","currentVersionId","canRollback","Badge","CheckCircle2","formatRelativeTime","RotateCcw","loadMore","LoadMore","hasMore","Dialog","DialogContent","DialogHeader","DialogTitle","DialogDescription","Textarea","DialogFooter","AlertDialog","open","AlertDialogContent","AlertDialogHeader","AlertDialogTitle","AlertDialogDescription","AlertDialogFooter","AlertDialogCancel","AlertDialogAction"],"sources":["../../../src/botlit/components/VersionHistoryPanel.tsx"],"sourcesContent":["/**\n * Version History Panel (BOFF-4381)\n * @module botlit/components\n *\n * Real, discoverable UI for agent versioning: shows the full version\n * history (draft/published/historical), lets a workspace admin publish the\n * current draft with a changelog, and roll back to any prior published\n * version with a confirmation step.\n */\n\nimport { useState, type FC } from 'react';\nimport { History, Rocket, RotateCcw, CheckCircle2 } from 'lucide-react';\nimport { toast } from 'sonner';\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n Textarea,\n} from '@burdenoff/fe-libs/ui';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { Card, CardContent, CardHeader, CardTitle, CardDescription } from './Card';\nimport { Button } from './Button';\nimport { Badge } from './Badge';\nimport { ErrorState } from './ErrorState';\nimport { LoadMore } from './LoadMore';\nimport {\n useAgentVersions,\n usePublishAgentVersion,\n useRollbackAgentVersion,\n type AgentVersionRecord,\n} from '../hooks/useAgents';\nimport { formatRelativeTime } from '../utils/formatters';\nimport { BOTMANOR_PERMISSIONS, BotmanorPermissionGate } from '../permissions';\n\ninterface VersionHistoryPanelProps {\n agentId: string;\n /** The agent's current draft version id (if any) — enables the Publish action. */\n draftVersionId?: string | null;\n /** The agent's current live (published) version id — hidden from the rollback list. */\n currentVersionId?: string | null;\n /** Called after a successful publish or rollback so the caller can refetch the agent itself. */\n onChanged?: () => void;\n}\n\nfunction versionStatusVariant(\n status: AgentVersionRecord['status']\n): 'secondary' | 'success' | 'outline' {\n if (status === 'DRAFT') return 'secondary';\n if (status === 'PUBLISHED') return 'success';\n return 'outline';\n}\n\nexport const VersionHistoryPanel: FC<VersionHistoryPanelProps> = ({\n agentId,\n draftVersionId,\n currentVersionId,\n onChanged,\n}) => {\n const t = useTr();\n\n const {\n data: versions,\n loading,\n error,\n appendError,\n refetch,\n hasMore,\n loadingMore,\n loadMore,\n } = useAgentVersions(agentId);\n const [publishAgentVersion, publishState] = usePublishAgentVersion();\n const [rollbackAgentVersion, rollbackState] = useRollbackAgentVersion();\n\n const [publishOpen, setPublishOpen] = useState(false);\n const [changelogDraft, setChangelogDraft] = useState('');\n const [rollbackTarget, setRollbackTarget] = useState<AgentVersionRecord | null>(null);\n\n const handlePublish = async (): Promise<void> => {\n if (!draftVersionId) return;\n try {\n const published = await publishAgentVersion({\n agentId,\n versionId: draftVersionId,\n changelog: changelogDraft,\n });\n toast.success(\n `${t('botlit.agentDetail.versions.publishSuccessPrefix', 'Published version')} ${published.version}`\n );\n setPublishOpen(false);\n setChangelogDraft('');\n await refetch();\n onChanged?.();\n } catch (err: unknown) {\n toast.error(\n err instanceof Error\n ? err.message\n : t('botlit.agentDetail.versions.publishError', 'Failed to publish version')\n );\n }\n };\n\n const handleRollback = async (): Promise<void> => {\n if (!rollbackTarget) return;\n try {\n const restored = await rollbackAgentVersion({ agentId, targetVersionId: rollbackTarget.id });\n toast.success(\n `${t('botlit.agentDetail.versions.rollbackSuccessPrefix', 'Rolled back to version')} ${rollbackTarget.version} (${t('botlit.agentDetail.versions.rollbackSuccessSuffix', 'now')} ${restored.version})`\n );\n setRollbackTarget(null);\n await refetch();\n onChanged?.();\n } catch (err: unknown) {\n toast.error(\n err instanceof Error\n ? err.message\n : t('botlit.agentDetail.versions.rollbackError', 'Failed to roll back agent version')\n );\n }\n };\n\n return (\n <div className=\"space-y-6\">\n <Card>\n <CardHeader className=\"flex flex-row items-start justify-between gap-4\">\n <div>\n <CardTitle className=\"flex items-center gap-2\">\n <History size={18} />\n {t('botlit.agentDetail.versions.title', 'Version History')}\n </CardTitle>\n <CardDescription>\n {t(\n 'botlit.agentDetail.versions.description',\n 'Every published configuration change, with a diff-able changelog. Publish the current draft or roll back to any prior version.'\n )}\n </CardDescription>\n </div>\n {draftVersionId && !loading && (!error || appendError) && (\n <BotmanorPermissionGate permission={BOTMANOR_PERMISSIONS.AGENT_PUBLISH}>\n <Button leftIcon={<Rocket size={16} />} onClick={() => setPublishOpen(true)}>\n {t('botlit.agentDetail.versions.publishDraft', 'Publish Draft')}\n </Button>\n </BotmanorPermissionGate>\n )}\n </CardHeader>\n <CardContent>\n {loading ? (\n <div className=\"h-32 bg-bg-sunken motion-safe:animate-vc-shimmer rounded-lg\" />\n ) : error && !appendError ? (\n <ErrorState\n resource={t('botlit.agentDetail.versions.resource', 'agent versions')}\n error={error}\n onRetry={() => void refetch()}\n />\n ) : versions.length === 0 ? (\n <p className=\"text-text-secondary\">\n {t('botlit.agentDetail.versions.empty', 'No version history yet.')}\n </p>\n ) : (\n <ul className=\"space-y-3\">\n {versions.map((version) => {\n const isCurrent = version.id === currentVersionId;\n const canRollback = version.status !== 'DRAFT' && !isCurrent;\n return (\n <li\n key={version.id}\n className=\"flex items-start justify-between gap-4 p-4 border border-border-subtle rounded-lg\"\n >\n <div className=\"space-y-1 min-w-0\">\n <div className=\"flex items-center gap-2 flex-wrap\">\n <span className=\"font-mono font-medium\">v{version.version}</span>\n <Badge variant={versionStatusVariant(version.status)}>\n {version.status}\n </Badge>\n {isCurrent && (\n <Badge variant=\"outline\" className=\"flex items-center gap-1\">\n <CheckCircle2 size={12} />\n {t('botlit.agentDetail.versions.liveNow', 'Live now')}\n </Badge>\n )}\n </div>\n <p className=\"text-sm text-text-secondary break-words\">\n {version.changelog ||\n t('botlit.agentDetail.versions.noChangelog', 'No description')}\n </p>\n <p className=\"text-xs text-text-secondary\">\n {version.status === 'DRAFT'\n ? `${t('botlit.agentDetail.versions.updated', 'Updated')} ${formatRelativeTime(version.createdAt)}`\n : `${t('botlit.agentDetail.versions.published', 'Published')} ${formatRelativeTime(version.publishedAt ?? version.createdAt)}`}\n </p>\n </div>\n {canRollback && (\n <BotmanorPermissionGate permission={BOTMANOR_PERMISSIONS.AGENT_ROLLBACK}>\n <Button\n variant=\"outline\"\n size=\"sm\"\n leftIcon={<RotateCcw size={14} />}\n onClick={() => setRollbackTarget(version)}\n >\n {t('botlit.agentDetail.versions.rollback', 'Roll back')}\n </Button>\n </BotmanorPermissionGate>\n )}\n </li>\n );\n })}\n </ul>\n )}\n {error && appendError && (\n <ErrorState\n resource={t('botlit.agentDetail.versions.moreResource', 'more agent versions')}\n error={error}\n onRetry={() => void loadMore()}\n />\n )}\n <LoadMore\n hasMore={hasMore && !error && !loading}\n loadingMore={loadingMore}\n onLoadMore={() => void loadMore()}\n loadedCount={versions.length}\n />\n </CardContent>\n </Card>\n\n {/* Publish dialog */}\n <Dialog open={publishOpen} onOpenChange={setPublishOpen}>\n <DialogContent>\n <DialogHeader>\n <DialogTitle>\n {t('botlit.agentDetail.versions.publishDialog.title', 'Publish this version')}\n </DialogTitle>\n <DialogDescription>\n {t(\n 'botlit.agentDetail.versions.publishDialog.description',\n \"This makes the draft's prompt, model, tools, and policy settings live for the agent. Describe what changed.\"\n )}\n </DialogDescription>\n </DialogHeader>\n <Textarea\n value={changelogDraft}\n onChange={(e) => setChangelogDraft(e.target.value)}\n placeholder={t(\n 'botlit.agentDetail.versions.publishDialog.placeholder',\n 'e.g. Tightened the system prompt and switched to gpt-4o'\n )}\n rows={4}\n />\n <DialogFooter>\n <Button variant=\"outline\" onClick={() => setPublishOpen(false)}>\n {t('botlit.common.cancel', 'Cancel')}\n </Button>\n <Button isLoading={publishState.loading} onClick={() => void handlePublish()}>\n {t('botlit.agentDetail.versions.publishDialog.confirm', 'Publish')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n\n {/* Rollback confirmation */}\n <AlertDialog\n open={rollbackTarget !== null}\n onOpenChange={(open) => !open && setRollbackTarget(null)}\n >\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>\n {t('botlit.agentDetail.versions.rollbackDialog.title', 'Roll back to this version?')}\n </AlertDialogTitle>\n <AlertDialogDescription>\n {rollbackTarget &&\n `${t('botlit.agentDetail.versions.rollbackDialog.descriptionPrefix', 'This immediately restores the agent to version')} ${rollbackTarget.version}${t('botlit.agentDetail.versions.rollbackDialog.descriptionSuffix', '. The current live config is kept in history and can be restored the same way.')}`}\n </AlertDialogDescription>\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel onClick={() => setRollbackTarget(null)}>\n {t('botlit.common.cancel', 'Cancel')}\n </AlertDialogCancel>\n <AlertDialogAction\n disabled={rollbackState.loading}\n onClick={() => void handleRollback()}\n >\n {t('botlit.agentDetail.versions.rollbackDialog.confirm', 'Roll back')}\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAuDA,SAASA,EACP,GACqC;CAGrC,OAFIC,MAAW,UAAgB,cAC3BA,MAAW,cAAoB,YAC5B;AACT;AAEA,IAAaC,KAAqD,EAChE,YACA,mBACA,qBACA,mBACI;CACJ,IAAMC,IAAIC,EAAM,GAEV,EACJ,MAAMC,GACN,YACA,UACA,gBACA,YACA,YACA,gBACA,gBACEC,EAAiBC,CAAO,GACtB,CAACC,GAAqBC,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,EAAE,OAAO,KAAK;MACjD,aAAaf,EACX,yDACA,yDACF;MACA,MAAM;KACP,CAAA;KACD,kBAAC0D,IAAD,EAAA,UAAA,CACE,kBAACrB,GAAD;MAAQ,SAAQ;MAAU,eAAezB,EAAe,EAAK;MAC1D,UAAAZ,EAAE,wBAAwB,QAAQ;KAC7B,CAAA,GACR,kBAACqC,GAAD;MAAQ,WAAW/B,EAAa;MAAS,eAAe,KAAKY,EAAc;MACxE,UAAAlB,EAAE,qDAAqD,SAAS;KAC3D,CAAA,CACI,EAAA,CAAA;IACD,EAAA,CAAA;GACT,CAAA;GAGR,kBAAC2D,IAAD;IACE,MAAM3C,MAAmB;IACzB,eAAe,MAAS,CAAC4C,KAAQ3C,EAAkB,IAAI;IAEvD,UAAA,kBAAC4C,GAAD,EAAA,UAAA,CACE,kBAACC,IAAD,EAAA,UAAA,CACE,kBAACC,IAAD,EAAA,UACG/D,EAAE,oDAAoD,4BAA4B,EACnE,CAAA,GAClB,kBAACgE,GAAD,EAAA,UACGhD,KACC,GAAGhB,EAAE,gEAAgE,gDAAgD,EAAE,GAAGgB,EAAe,UAAUhB,EAAE,gEAAgE,gFAAgF,IACjR,CAAA,CACP,EAAA,CAAA,GACnB,kBAACiE,GAAD,EAAA,UAAA,CACE,kBAACC,GAAD;KAAmB,eAAejD,EAAkB,IAAI;KACrD,UAAAjB,EAAE,wBAAwB,QAAQ;IAClB,CAAA,GACnB,kBAACmE,GAAD;KACE,UAAU1D,GAAc;KACxB,eAAe,KAAKgB,GAAe;KAElC,UAAAzB,EAAE,sDAAsD,WAAW;IACnD,CAAA,CACF,EAAA,CAAA,CACD,EAAA,CAAA;GACT,CAAA;EACV;;AAET"}
|
|
@@ -84,6 +84,12 @@ export interface WorkspacePaginatedQueryOptions<TData, TRow, TResult> {
|
|
|
84
84
|
enabled: boolean;
|
|
85
85
|
/** Used when the thrown value is not an Error. */
|
|
86
86
|
errorMessage: string;
|
|
87
|
+
/**
|
|
88
|
+
* When true, `loading` is already true on the first render of an enabled
|
|
89
|
+
* query, so a page does not flash its empty state before the first read
|
|
90
|
+
* starts. Defaults to false.
|
|
91
|
+
*/
|
|
92
|
+
loadingBeforeFirstRead?: boolean;
|
|
87
93
|
}
|
|
88
94
|
/**
|
|
89
95
|
* Offset-paginated variant of `useWorkspaceQuery` for unbounded lists.
|
|
@@ -58,15 +58,15 @@ function f(e) {
|
|
|
58
58
|
}
|
|
59
59
|
var p = [];
|
|
60
60
|
function m(e) {
|
|
61
|
-
let { document: t, variables: i, pageSize: s, enabled:
|
|
62
|
-
|
|
63
|
-
}, [
|
|
64
|
-
if (n &&
|
|
65
|
-
|
|
66
|
-
let r = n ?
|
|
67
|
-
n ?
|
|
61
|
+
let { document: t, variables: i, pageSize: s, enabled: f, errorMessage: m } = e, h = c(), g = d(e.select), _ = d(e.extractRows), v = d(e.extractNextOffset), [y, b] = o([]), x = a([]), [S, C] = o(e.fallback), [w, T] = o(!!e.loadingBeforeFirstRead && f), [E, D] = o(!1), [O, k] = o(null), A = a(null), j = a(!1), [M, N] = o(), P = a(0), F = n((e) => {
|
|
62
|
+
x.current = e, b(e), C(g.current(e));
|
|
63
|
+
}, [g]), I = n(async (e, n) => {
|
|
64
|
+
if (n && j.current) return;
|
|
65
|
+
j.current = !0;
|
|
66
|
+
let r = n ? P.current : ++P.current, a = () => r === P.current;
|
|
67
|
+
n ? D(!0) : (T(!0), D(!1)), N(void 0);
|
|
68
68
|
try {
|
|
69
|
-
let r = await
|
|
69
|
+
let r = await h.query({
|
|
70
70
|
query: t,
|
|
71
71
|
variables: {
|
|
72
72
|
...i,
|
|
@@ -79,52 +79,52 @@ function m(e) {
|
|
|
79
79
|
});
|
|
80
80
|
if (!a()) return;
|
|
81
81
|
let o = r.error;
|
|
82
|
-
if (o != null) throw u(o,
|
|
83
|
-
let c = r.data ?? void 0, l =
|
|
84
|
-
if (
|
|
85
|
-
|
|
82
|
+
if (o != null) throw u(o, m);
|
|
83
|
+
let c = r.data ?? void 0, l = _.current(c) ?? [], d = v.current, f = d ? d(c) : l.length < s ? null : e + l.length;
|
|
84
|
+
if (f !== null && (!Number.isSafeInteger(f) || f <= e)) throw Error(m);
|
|
85
|
+
F(n ? [...x.current, ...l] : l), A.current = f, k(f);
|
|
86
86
|
} catch (e) {
|
|
87
|
-
a() &&
|
|
88
|
-
error: u(e,
|
|
87
|
+
a() && N({
|
|
88
|
+
error: u(e, m),
|
|
89
89
|
append: n
|
|
90
90
|
});
|
|
91
91
|
} finally {
|
|
92
|
-
a() && (
|
|
92
|
+
a() && (j.current = !1, n ? D(!1) : T(!1));
|
|
93
93
|
}
|
|
94
94
|
}, [
|
|
95
|
-
|
|
95
|
+
h,
|
|
96
96
|
t,
|
|
97
97
|
i,
|
|
98
98
|
s,
|
|
99
|
-
|
|
100
|
-
g,
|
|
99
|
+
m,
|
|
101
100
|
_,
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
l ? await F(0, !1) : (++N.current, A.current = !1, P(p), w(!1), E(!1), k.current = null, O(null), M(void 0));
|
|
105
|
-
}, [
|
|
106
|
-
l,
|
|
107
|
-
F,
|
|
108
|
-
P
|
|
101
|
+
v,
|
|
102
|
+
F
|
|
109
103
|
]), L = n(async () => {
|
|
110
|
-
|
|
104
|
+
f ? await I(0, !1) : (++P.current, j.current = !1, F(p), T(!1), D(!1), A.current = null, k(null), N(void 0));
|
|
111
105
|
}, [
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
D,
|
|
106
|
+
f,
|
|
107
|
+
I,
|
|
115
108
|
F
|
|
116
|
-
])
|
|
109
|
+
]), R = n(async () => {
|
|
110
|
+
f && !w && O !== null && O === A.current && await I(O, !0);
|
|
111
|
+
}, [
|
|
112
|
+
f,
|
|
113
|
+
w,
|
|
114
|
+
O,
|
|
115
|
+
I
|
|
116
|
+
]), z = l();
|
|
117
117
|
return r(() => {
|
|
118
|
-
|
|
119
|
-
}, [
|
|
120
|
-
data:
|
|
121
|
-
loading:
|
|
122
|
-
loadingMore:
|
|
123
|
-
hasMore:
|
|
124
|
-
error:
|
|
125
|
-
appendError:
|
|
126
|
-
refetch:
|
|
127
|
-
loadMore:
|
|
118
|
+
L();
|
|
119
|
+
}, [L, z]), {
|
|
120
|
+
data: S,
|
|
121
|
+
loading: w,
|
|
122
|
+
loadingMore: E,
|
|
123
|
+
hasMore: O !== null,
|
|
124
|
+
error: M?.error,
|
|
125
|
+
appendError: M?.append ?? !1,
|
|
126
|
+
refetch: L,
|
|
127
|
+
loadMore: R
|
|
128
128
|
};
|
|
129
129
|
}
|
|
130
130
|
function h(e) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspaceGateway.js","names":["useWorkspaceClient","useGatewayClient","useWorkspaceId","useBotlit","toError","message","extractGraphqlFailureMessage","cause","fallbackMessage","useLatest","ref","useRef","value","useLayoutEffect","useWorkspaceQuery","options","client","selectRef","fallbackRef","data","setData","useState","loading","setLoading","error","setError","refetch","useCallback","enabled","result","document","operationError","errorMessage","queryError","variables","useEffect","NO_ROWS","useWorkspacePaginatedQuery","extractRowsRef","extractNextOffsetRef","rows","setRows","rowsRef","loadingMore","setLoadingMore","nextOffset","setNextOffset","nextOffsetRef","fetchInFlightRef","failure","setFailure","generationRef","replaceRows","next","fetchPage","append","generation","isCurrent","pageSize","payload","pageRows","extractNextOffset","continuation","offset","loadMore","useWorkspaceAllPagesQuery","hasMore","useWorkspaceMutation","variablesRef","state","setState","input","selected","mutationError"],"sources":["../../../../src/botlit/hooks/internal/workspaceGateway.ts"],"sourcesContent":["/**\n * Workspace gateway hook primitives\n * @module botlit/hooks/internal\n *\n * Every BotManor hook talks to the workspace public gateway through the Apollo\n * client the shell installs (`useGatewayClient('workspace')`) — never through a\n * client of its own. These primitives capture the exact shape used by the\n * reference hooks (`useAgents`, `useBots`): `network-only` reads, an explicit\n * `Error` in state rather than a thrown promise, and a `refetch` the caller can\n * run after a mutation.\n */\n\nimport type { ApolloClient, DocumentNode } from '@apollo/client';\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\n\nimport { useBotlit } from '../../providers/BotlitProvider';\nimport { extractGraphqlFailureMessage } from '../../utils/errors';\n\nexport type WorkspaceClient = ApolloClient;\n\n/** Apollo client for the workspace gateway, provided by the host shell. */\nexport function useWorkspaceClient(): WorkspaceClient {\n return useGatewayClient('workspace');\n}\n\n/** Current workspace id from the BotManor context (undefined until the shell resolves it). */\nexport function useWorkspaceId(): string | undefined {\n return useBotlit().workspaceId;\n}\n\nexport interface QueryResult<T> {\n data: T;\n loading: boolean;\n /** Set only when the request FAILED. An empty `data` with no `error` means \"no records yet\". */\n error: Error | undefined;\n refetch: () => Promise<void>;\n}\n\nexport interface PaginatedQueryResult<T> extends QueryResult<T> {\n /** True when the most recent request failed while appending a page. */\n appendError: boolean;\n /** True while the next page is being appended. */\n loadingMore: boolean;\n /** True when the latest page has a continuation. */\n hasMore: boolean;\n /**\n * Fetches the next page at its continuation offset and appends it.\n * No-op while a fetch is in flight or when `hasMore` is false.\n */\n loadMore: () => Promise<void>;\n}\n\nexport interface MutationState<T> {\n data: T | undefined;\n loading: boolean;\n error: Error | undefined;\n}\n\n/**\n * Normalises any mutation failure to an Error with the server's\n * user-actionable message where one exists.\n *\n * Apollo Client v4 does not reject with a plain Error: failures arrive as\n * `{ networkError }` / `{ graphQLErrors }` objects, and the batched fetch\n * layer attaches the structured GraphQL errors as `.errors` on the\n * networkError. `extractGraphqlFailureMessage` unwraps all of those; only\n * when nothing user-actionable is present do we fall back to the hook's\n * generic `errorMessage`.\n */\nexport function toError(cause: unknown, fallbackMessage: string): Error {\n const message = extractGraphqlFailureMessage(cause);\n if (message) {\n // Preserve the original rejection on the chain so error monitoring can\n // still reach the structured GraphQL errors (extensions.code, requestId…).\n return new Error(message, { cause });\n }\n if (cause instanceof Error) return cause;\n return new Error(fallbackMessage, { cause });\n}\n\n/** Keeps a mutable ref pointing at the latest value without re-running effects. */\nfunction useLatest<T>(value: T): { readonly current: T } {\n const ref = useRef(value);\n useLayoutEffect(() => {\n ref.current = value;\n }, [value]);\n return ref;\n}\n\nexport interface WorkspaceQueryOptions<TData, TResult> {\n /** Generated GraphQL document (see `src/generated/wspace-operations.ts`). */\n document: DocumentNode;\n /** Must be referentially stable — memoize at the call site. */\n variables: Record<string, unknown> | undefined;\n /** Projects the raw payload onto the record shape the UI consumes. */\n select: (data: TData | undefined) => TResult;\n /** Value held while disabled or before the first successful read. */\n fallback: TResult;\n /** When false the request is skipped (e.g. no workspace id / no entity id yet). */\n enabled: boolean;\n /** Used when the thrown value is not an Error. */\n errorMessage: string;\n}\n\n/**\n * Reads from the workspace gateway and keeps `{ data, loading, error, refetch }`\n * in sync. `error` is reserved for real failures so callers can tell an empty\n * collection apart from a failed request.\n */\nexport function useWorkspaceQuery<TData, TResult>(\n options: WorkspaceQueryOptions<TData, TResult>\n): QueryResult<TResult> {\n const { document, variables, enabled, errorMessage } = options;\n const client = useWorkspaceClient();\n const selectRef = useLatest(options.select);\n const fallbackRef = useLatest(options.fallback);\n\n const [data, setData] = useState<TResult>(options.fallback);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!enabled) {\n setData(fallbackRef.current);\n setError(undefined);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<TData>({\n query: document,\n variables,\n fetchPolicy: 'network-only',\n });\n // Apollo v4 resolves (not rejects) with `result.error` set on GraphQL\n // errors — same handling as useWorkspaceMutation.\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw toError(operationError, errorMessage);\n }\n setData(selectRef.current(result.data ?? undefined));\n } catch (queryError) {\n setData(fallbackRef.current);\n setError(toError(queryError, errorMessage));\n } finally {\n setLoading(false);\n }\n // fallbackRef/selectRef are stable refs by construction\n }, [client, document, variables, enabled, errorMessage, fallbackRef, selectRef]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\n/** Shared empty page, so a disabled paginated query keeps one stable value. */\nconst NO_ROWS: never[] = [];\n\nexport interface WorkspacePaginatedQueryOptions<TData, TRow, TResult> {\n /** Generated GraphQL document (see `src/generated/wspace-operations.ts`). */\n document: DocumentNode;\n /**\n * Base variables (filters, ids, …) WITHOUT `pagination` — the hook adds\n * `{ limit: pageSize, offset }` per fetch. Must be referentially stable;\n * a new identity resets the accumulation back to page one.\n */\n variables: Record<string, unknown> | undefined;\n /** Page size for each fetch. */\n pageSize: number;\n /** Extracts the raw row list from a page payload; missing data yields []. */\n extractRows: (data: TData | undefined) => TRow[] | undefined;\n /** Server continuation for envelope APIs. Null marks the final page. */\n extractNextOffset?: (data: TData | undefined) => number | null;\n /** Projects the ACCUMULATED raw rows onto the record shape the UI consumes. */\n select: (rows: TRow[]) => TResult;\n /** Value held while disabled or before the first successful read. */\n fallback: TResult;\n /** When false the request is skipped (e.g. no workspace id yet). */\n enabled: boolean;\n /** Used when the thrown value is not an Error. */\n errorMessage: string;\n}\n\n/**\n * Offset-paginated variant of `useWorkspaceQuery` for unbounded lists.\n *\n * `refetch()` restarts at offset 0 and REPLACES the accumulated rows;\n * `loadMore()` fetches the next page and appends it. Envelope APIs set the\n * continuation explicitly. On legacy array APIs a short page ends the list.\n * `select` runs over the accumulated raw rows, so client-side narrowing\n * (e.g. executions search) sees every loaded page, not just the last one.\n */\nexport function useWorkspacePaginatedQuery<TData, TRow, TResult>(\n options: WorkspacePaginatedQueryOptions<TData, TRow, TResult>\n): PaginatedQueryResult<TResult> {\n const { document, variables, pageSize, enabled, errorMessage } = options;\n const client = useWorkspaceClient();\n const selectRef = useLatest(options.select);\n const extractRowsRef = useLatest(options.extractRows);\n const extractNextOffsetRef = useLatest(options.extractNextOffset);\n\n const [rows, setRows] = useState<TRow[]>([]);\n const rowsRef = useRef<TRow[]>([]);\n const [data, setData] = useState<TResult>(options.fallback);\n const [loading, setLoading] = useState(false);\n const [loadingMore, setLoadingMore] = useState(false);\n const [nextOffset, setNextOffset] = useState<number | null>(null);\n const nextOffsetRef = useRef<number | null>(null);\n const fetchInFlightRef = useRef(false);\n const [failure, setFailure] = useState<{ error: Error; append: boolean }>();\n // Bumped by every page-one read: a page from a superseded read (e.g. a\n // workspace switch mid-paging) must not touch the newer read's state.\n const generationRef = useRef(0);\n\n const replaceRows = useCallback(\n (next: TRow[]) => {\n rowsRef.current = next;\n setRows(next);\n setData(selectRef.current(next));\n },\n [selectRef]\n );\n\n const fetchPage = useCallback(\n async (offset: number, append: boolean) => {\n if (append && fetchInFlightRef.current) return;\n fetchInFlightRef.current = true;\n const generation = append ? generationRef.current : ++generationRef.current;\n const isCurrent = () => generation === generationRef.current;\n if (append) {\n setLoadingMore(true);\n } else {\n setLoading(true);\n // A new page-one read supersedes any in-flight append; that append\n // no longer owns `loadingMore` and will not clear it.\n setLoadingMore(false);\n }\n setFailure(undefined);\n try {\n const result = await client.query<TData>({\n query: document,\n variables: { ...variables, pagination: { limit: pageSize, offset } },\n fetchPolicy: 'network-only',\n });\n if (!isCurrent()) return;\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw toError(operationError, errorMessage);\n }\n const payload = result.data ?? undefined;\n const pageRows = extractRowsRef.current(payload) ?? [];\n const extractNextOffset = extractNextOffsetRef.current;\n const continuation = extractNextOffset\n ? extractNextOffset(payload)\n : pageRows.length < pageSize\n ? null\n : offset + pageRows.length;\n if (\n continuation !== null &&\n (!Number.isSafeInteger(continuation) || continuation <= offset)\n ) {\n throw new Error(errorMessage);\n }\n replaceRows(append ? [...rowsRef.current, ...pageRows] : pageRows);\n nextOffsetRef.current = continuation;\n setNextOffset(continuation);\n } catch (queryError) {\n if (isCurrent()) setFailure({ error: toError(queryError, errorMessage), append });\n } finally {\n // Only the current read owns the flags: a superseded append must not\n // clear a newer read's `loadingMore` (that would start a duplicate\n // append at the same offset).\n if (isCurrent()) {\n fetchInFlightRef.current = false;\n if (append) setLoadingMore(false);\n else setLoading(false);\n }\n }\n },\n [\n client,\n document,\n variables,\n pageSize,\n errorMessage,\n extractRowsRef,\n extractNextOffsetRef,\n replaceRows,\n ]\n );\n\n const refetch = useCallback(async () => {\n if (!enabled) {\n ++generationRef.current;\n fetchInFlightRef.current = false;\n // The same empty list every time: a disabled query must not change state, or a\n // caller whose client identity changes per render would refetch forever.\n replaceRows(NO_ROWS);\n setLoading(false);\n setLoadingMore(false);\n nextOffsetRef.current = null;\n setNextOffset(null);\n setFailure(undefined);\n return;\n }\n await fetchPage(0, false);\n }, [enabled, fetchPage, replaceRows]);\n\n const loadMore = useCallback(async () => {\n if (!enabled || loading || nextOffset === null) return;\n // A page can resolve before React publishes the new continuation.\n if (nextOffset !== nextOffsetRef.current) return;\n await fetchPage(nextOffset, true);\n }, [enabled, loading, nextOffset, fetchPage]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return {\n data,\n loading,\n loadingMore,\n hasMore: nextOffset !== null,\n error: failure?.error,\n appendError: failure?.append ?? false,\n refetch,\n loadMore,\n };\n}\n\n/**\n * Every page of an offset-paginated list (BOFF-15360), for callers that must\n * see the whole list at once (pickers, \"already configured\" checks).\n * `loading` holds until the last page has arrived; a failed page stops paging\n * and sets `error`. `refetch` restarts from page one.\n */\nexport function useWorkspaceAllPagesQuery<TData, TRow, TResult>(\n options: WorkspacePaginatedQueryOptions<TData, TRow, TResult>\n): QueryResult<TResult> {\n const { data, loading, loadingMore, hasMore, error, refetch, loadMore } =\n useWorkspacePaginatedQuery(options);\n\n useEffect(() => {\n if (hasMore && !loading && !loadingMore && !error) void loadMore();\n }, [hasMore, loading, loadingMore, error, loadMore]);\n\n return { data, loading: loading || loadingMore || (hasMore && !error), error, refetch };\n}\n\nexport interface WorkspaceMutationOptions<TData, TInput, TResult> {\n /** Generated GraphQL document (see `src/generated/wspace-operations.ts`). */\n document: DocumentNode;\n /** Maps the caller's input onto GraphQL variables. */\n variables: (input: TInput) => Record<string, unknown>;\n /** Projects the raw payload onto the record shape the UI consumes. */\n select: (data: TData | undefined) => TResult | undefined;\n /** Thrown (and stored) when the payload is missing or the request fails. */\n errorMessage: string;\n}\n\n/**\n * Writes to the workspace gateway. Returns the `[mutate, state]` tuple used by\n * the reference hooks. `mutate` REJECTS on failure so callers cannot mistake a\n * failed write for a successful one.\n */\nexport function useWorkspaceMutation<TData, TInput, TResult>(\n options: WorkspaceMutationOptions<TData, TInput, TResult>\n): readonly [(input: TInput) => Promise<TResult>, MutationState<TResult>] {\n const { document, errorMessage } = options;\n const client = useWorkspaceClient();\n const variablesRef = useLatest(options.variables);\n const selectRef = useLatest(options.select);\n\n const [state, setState] = useState<MutationState<TResult>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const mutate = useCallback(\n async (input: TInput): Promise<TResult> => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<TData>({\n mutation: document,\n variables: variablesRef.current(input),\n });\n // Apollo v4 does not reject on GraphQL errors by default: the mutation\n // RESOLVES with `data` undefined and the failure on `result.error`\n // (CombinedGraphQLErrors / networkError). Surface it like a rejection\n // so callers see the server's field-level message, not the fallback.\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw toError(operationError, errorMessage);\n }\n const selected = selectRef.current(result.data ?? undefined);\n if (selected === undefined) {\n throw new Error(errorMessage);\n }\n setState({ data: selected, loading: false, error: undefined });\n return selected;\n } catch (mutationError) {\n const failure = toError(mutationError, errorMessage);\n setState({ data: undefined, loading: false, error: failure });\n throw failure;\n }\n },\n [client, document, errorMessage, selectRef, variablesRef]\n );\n\n return [mutate, state] as const;\n}\n"],"mappings":";;;;;AAsBA,SAAgBA,IAAsC;CACpD,OAAOC,EAAiB,WAAW;AACrC;AAGA,SAAgBC,IAAqC;CACnD,OAAOC,EAAU,CAAC,CAAC;AACrB;AAyCA,SAAgBC,EAAQ,GAAgB,GAAgC;CACtE,IAAMC,IAAUC,EAA6BC,CAAK;CAOlD,OANIF,IAGS,MAAMA,GAAS,EAAE,SAAM,CAAC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;IAAU,SAAS;IAAO,OAAO,KAAA;GAAU,CAAC,GACtDA;EACT,SAASC,GAAe;GACtB,IAAMxB,IAAU7C,EAAQqE,GAAezC,CAAY;GAEnD,MADAsC,EAAS;IAAE,MAAM,KAAA;IAAW,SAAS;IAAO,OAAOrB;GAAQ,CAAC,GACtDA;EACR;CACF,GACA;EAACjC;EAAQc;EAAUE;EAAcf;EAAWmD;CAAY,CAGlD,GAAQC,CAAK;AACvB"}
|
|
1
|
+
{"version":3,"file":"workspaceGateway.js","names":["useWorkspaceClient","useGatewayClient","useWorkspaceId","useBotlit","toError","message","extractGraphqlFailureMessage","cause","fallbackMessage","useLatest","ref","useRef","value","useLayoutEffect","useWorkspaceQuery","options","client","selectRef","fallbackRef","data","setData","useState","loading","setLoading","error","setError","refetch","useCallback","enabled","result","document","operationError","errorMessage","queryError","variables","useEffect","NO_ROWS","useWorkspacePaginatedQuery","extractRowsRef","extractNextOffsetRef","rows","setRows","rowsRef","loadingMore","setLoadingMore","nextOffset","setNextOffset","nextOffsetRef","fetchInFlightRef","failure","setFailure","generationRef","replaceRows","next","fetchPage","append","generation","isCurrent","pageSize","payload","pageRows","extractNextOffset","continuation","offset","loadMore","workspaceId","useWorkspaceAllPagesQuery","hasMore","useWorkspaceMutation","variablesRef","state","setState","input","selected","mutationError"],"sources":["../../../../src/botlit/hooks/internal/workspaceGateway.ts"],"sourcesContent":["/**\n * Workspace gateway hook primitives\n * @module botlit/hooks/internal\n *\n * Every BotManor hook talks to the workspace public gateway through the Apollo\n * client the shell installs (`useGatewayClient('workspace')`) — never through a\n * client of its own. These primitives capture the exact shape used by the\n * reference hooks (`useAgents`, `useBots`): `network-only` reads, an explicit\n * `Error` in state rather than a thrown promise, and a `refetch` the caller can\n * run after a mutation.\n */\n\nimport type { ApolloClient, DocumentNode } from '@apollo/client';\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\n\nimport { useBotlit } from '../../providers/BotlitProvider';\nimport { extractGraphqlFailureMessage } from '../../utils/errors';\n\nexport type WorkspaceClient = ApolloClient;\n\n/** Apollo client for the workspace gateway, provided by the host shell. */\nexport function useWorkspaceClient(): WorkspaceClient {\n return useGatewayClient('workspace');\n}\n\n/** Current workspace id from the BotManor context (undefined until the shell resolves it). */\nexport function useWorkspaceId(): string | undefined {\n return useBotlit().workspaceId;\n}\n\nexport interface QueryResult<T> {\n data: T;\n loading: boolean;\n /** Set only when the request FAILED. An empty `data` with no `error` means \"no records yet\". */\n error: Error | undefined;\n refetch: () => Promise<void>;\n}\n\nexport interface PaginatedQueryResult<T> extends QueryResult<T> {\n /** True when the most recent request failed while appending a page. */\n appendError: boolean;\n /** True while the next page is being appended. */\n loadingMore: boolean;\n /** True when the latest page has a continuation. */\n hasMore: boolean;\n /**\n * Fetches the next page at its continuation offset and appends it.\n * No-op while a fetch is in flight or when `hasMore` is false.\n */\n loadMore: () => Promise<void>;\n}\n\nexport interface MutationState<T> {\n data: T | undefined;\n loading: boolean;\n error: Error | undefined;\n}\n\n/**\n * Normalises any mutation failure to an Error with the server's\n * user-actionable message where one exists.\n *\n * Apollo Client v4 does not reject with a plain Error: failures arrive as\n * `{ networkError }` / `{ graphQLErrors }` objects, and the batched fetch\n * layer attaches the structured GraphQL errors as `.errors` on the\n * networkError. `extractGraphqlFailureMessage` unwraps all of those; only\n * when nothing user-actionable is present do we fall back to the hook's\n * generic `errorMessage`.\n */\nexport function toError(cause: unknown, fallbackMessage: string): Error {\n const message = extractGraphqlFailureMessage(cause);\n if (message) {\n // Preserve the original rejection on the chain so error monitoring can\n // still reach the structured GraphQL errors (extensions.code, requestId…).\n return new Error(message, { cause });\n }\n if (cause instanceof Error) return cause;\n return new Error(fallbackMessage, { cause });\n}\n\n/** Keeps a mutable ref pointing at the latest value without re-running effects. */\nfunction useLatest<T>(value: T): { readonly current: T } {\n const ref = useRef(value);\n useLayoutEffect(() => {\n ref.current = value;\n }, [value]);\n return ref;\n}\n\nexport interface WorkspaceQueryOptions<TData, TResult> {\n /** Generated GraphQL document (see `src/generated/wspace-operations.ts`). */\n document: DocumentNode;\n /** Must be referentially stable — memoize at the call site. */\n variables: Record<string, unknown> | undefined;\n /** Projects the raw payload onto the record shape the UI consumes. */\n select: (data: TData | undefined) => TResult;\n /** Value held while disabled or before the first successful read. */\n fallback: TResult;\n /** When false the request is skipped (e.g. no workspace id / no entity id yet). */\n enabled: boolean;\n /** Used when the thrown value is not an Error. */\n errorMessage: string;\n}\n\n/**\n * Reads from the workspace gateway and keeps `{ data, loading, error, refetch }`\n * in sync. `error` is reserved for real failures so callers can tell an empty\n * collection apart from a failed request.\n */\nexport function useWorkspaceQuery<TData, TResult>(\n options: WorkspaceQueryOptions<TData, TResult>\n): QueryResult<TResult> {\n const { document, variables, enabled, errorMessage } = options;\n const client = useWorkspaceClient();\n const selectRef = useLatest(options.select);\n const fallbackRef = useLatest(options.fallback);\n\n const [data, setData] = useState<TResult>(options.fallback);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!enabled) {\n setData(fallbackRef.current);\n setError(undefined);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<TData>({\n query: document,\n variables,\n fetchPolicy: 'network-only',\n });\n // Apollo v4 resolves (not rejects) with `result.error` set on GraphQL\n // errors — same handling as useWorkspaceMutation.\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw toError(operationError, errorMessage);\n }\n setData(selectRef.current(result.data ?? undefined));\n } catch (queryError) {\n setData(fallbackRef.current);\n setError(toError(queryError, errorMessage));\n } finally {\n setLoading(false);\n }\n // fallbackRef/selectRef are stable refs by construction\n }, [client, document, variables, enabled, errorMessage, fallbackRef, selectRef]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\n/** Shared empty page, so a disabled paginated query keeps one stable value. */\nconst NO_ROWS: never[] = [];\n\nexport interface WorkspacePaginatedQueryOptions<TData, TRow, TResult> {\n /** Generated GraphQL document (see `src/generated/wspace-operations.ts`). */\n document: DocumentNode;\n /**\n * Base variables (filters, ids, …) WITHOUT `pagination` — the hook adds\n * `{ limit: pageSize, offset }` per fetch. Must be referentially stable;\n * a new identity resets the accumulation back to page one.\n */\n variables: Record<string, unknown> | undefined;\n /** Page size for each fetch. */\n pageSize: number;\n /** Extracts the raw row list from a page payload; missing data yields []. */\n extractRows: (data: TData | undefined) => TRow[] | undefined;\n /** Server continuation for envelope APIs. Null marks the final page. */\n extractNextOffset?: (data: TData | undefined) => number | null;\n /** Projects the ACCUMULATED raw rows onto the record shape the UI consumes. */\n select: (rows: TRow[]) => TResult;\n /** Value held while disabled or before the first successful read. */\n fallback: TResult;\n /** When false the request is skipped (e.g. no workspace id yet). */\n enabled: boolean;\n /** Used when the thrown value is not an Error. */\n errorMessage: string;\n /**\n * When true, `loading` is already true on the first render of an enabled\n * query, so a page does not flash its empty state before the first read\n * starts. Defaults to false.\n */\n loadingBeforeFirstRead?: boolean;\n}\n\n/**\n * Offset-paginated variant of `useWorkspaceQuery` for unbounded lists.\n *\n * `refetch()` restarts at offset 0 and REPLACES the accumulated rows;\n * `loadMore()` fetches the next page and appends it. Envelope APIs set the\n * continuation explicitly. On legacy array APIs a short page ends the list.\n * `select` runs over the accumulated raw rows, so client-side narrowing\n * (e.g. executions search) sees every loaded page, not just the last one.\n */\nexport function useWorkspacePaginatedQuery<TData, TRow, TResult>(\n options: WorkspacePaginatedQueryOptions<TData, TRow, TResult>\n): PaginatedQueryResult<TResult> {\n const { document, variables, pageSize, enabled, errorMessage } = options;\n const client = useWorkspaceClient();\n const selectRef = useLatest(options.select);\n const extractRowsRef = useLatest(options.extractRows);\n const extractNextOffsetRef = useLatest(options.extractNextOffset);\n\n const [rows, setRows] = useState<TRow[]>([]);\n const rowsRef = useRef<TRow[]>([]);\n const [data, setData] = useState<TResult>(options.fallback);\n const [loading, setLoading] = useState(Boolean(options.loadingBeforeFirstRead) && enabled);\n const [loadingMore, setLoadingMore] = useState(false);\n const [nextOffset, setNextOffset] = useState<number | null>(null);\n const nextOffsetRef = useRef<number | null>(null);\n const fetchInFlightRef = useRef(false);\n const [failure, setFailure] = useState<{ error: Error; append: boolean }>();\n // Bumped by every page-one read: a page from a superseded read (e.g. a\n // workspace switch mid-paging) must not touch the newer read's state.\n const generationRef = useRef(0);\n\n const replaceRows = useCallback(\n (next: TRow[]) => {\n rowsRef.current = next;\n setRows(next);\n setData(selectRef.current(next));\n },\n [selectRef]\n );\n\n const fetchPage = useCallback(\n async (offset: number, append: boolean) => {\n if (append && fetchInFlightRef.current) return;\n fetchInFlightRef.current = true;\n const generation = append ? generationRef.current : ++generationRef.current;\n const isCurrent = () => generation === generationRef.current;\n if (append) {\n setLoadingMore(true);\n } else {\n setLoading(true);\n // A new page-one read supersedes any in-flight append; that append\n // no longer owns `loadingMore` and will not clear it.\n setLoadingMore(false);\n }\n setFailure(undefined);\n try {\n const result = await client.query<TData>({\n query: document,\n variables: { ...variables, pagination: { limit: pageSize, offset } },\n fetchPolicy: 'network-only',\n });\n if (!isCurrent()) return;\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw toError(operationError, errorMessage);\n }\n const payload = result.data ?? undefined;\n const pageRows = extractRowsRef.current(payload) ?? [];\n const extractNextOffset = extractNextOffsetRef.current;\n const continuation = extractNextOffset\n ? extractNextOffset(payload)\n : pageRows.length < pageSize\n ? null\n : offset + pageRows.length;\n if (\n continuation !== null &&\n (!Number.isSafeInteger(continuation) || continuation <= offset)\n ) {\n throw new Error(errorMessage);\n }\n replaceRows(append ? [...rowsRef.current, ...pageRows] : pageRows);\n nextOffsetRef.current = continuation;\n setNextOffset(continuation);\n } catch (queryError) {\n if (isCurrent()) setFailure({ error: toError(queryError, errorMessage), append });\n } finally {\n // Only the current read owns the flags: a superseded append must not\n // clear a newer read's `loadingMore` (that would start a duplicate\n // append at the same offset).\n if (isCurrent()) {\n fetchInFlightRef.current = false;\n if (append) setLoadingMore(false);\n else setLoading(false);\n }\n }\n },\n [\n client,\n document,\n variables,\n pageSize,\n errorMessage,\n extractRowsRef,\n extractNextOffsetRef,\n replaceRows,\n ]\n );\n\n const refetch = useCallback(async () => {\n if (!enabled) {\n ++generationRef.current;\n fetchInFlightRef.current = false;\n // The same empty list every time: a disabled query must not change state, or a\n // caller whose client identity changes per render would refetch forever.\n replaceRows(NO_ROWS);\n setLoading(false);\n setLoadingMore(false);\n nextOffsetRef.current = null;\n setNextOffset(null);\n setFailure(undefined);\n return;\n }\n await fetchPage(0, false);\n }, [enabled, fetchPage, replaceRows]);\n\n const loadMore = useCallback(async () => {\n if (!enabled || loading || nextOffset === null) return;\n // A page can resolve before React publishes the new continuation.\n if (nextOffset !== nextOffsetRef.current) return;\n await fetchPage(nextOffset, true);\n }, [enabled, loading, nextOffset, fetchPage]);\n\n // The workspace travels in the gateway token, not always in `variables`.\n // A switch between two workspaces must start again from page one, or the\n // previous workspace's rows stay on screen and the next page is read at\n // the old offset (BOFF-18147).\n const workspaceId = useWorkspaceId();\n useEffect(() => {\n void refetch();\n }, [refetch, workspaceId]);\n\n return {\n data,\n loading,\n loadingMore,\n hasMore: nextOffset !== null,\n error: failure?.error,\n appendError: failure?.append ?? false,\n refetch,\n loadMore,\n };\n}\n\n/**\n * Every page of an offset-paginated list (BOFF-15360), for callers that must\n * see the whole list at once (pickers, \"already configured\" checks).\n * `loading` holds until the last page has arrived; a failed page stops paging\n * and sets `error`. `refetch` restarts from page one.\n */\nexport function useWorkspaceAllPagesQuery<TData, TRow, TResult>(\n options: WorkspacePaginatedQueryOptions<TData, TRow, TResult>\n): QueryResult<TResult> {\n const { data, loading, loadingMore, hasMore, error, refetch, loadMore } =\n useWorkspacePaginatedQuery(options);\n\n useEffect(() => {\n if (hasMore && !loading && !loadingMore && !error) void loadMore();\n }, [hasMore, loading, loadingMore, error, loadMore]);\n\n return { data, loading: loading || loadingMore || (hasMore && !error), error, refetch };\n}\n\nexport interface WorkspaceMutationOptions<TData, TInput, TResult> {\n /** Generated GraphQL document (see `src/generated/wspace-operations.ts`). */\n document: DocumentNode;\n /** Maps the caller's input onto GraphQL variables. */\n variables: (input: TInput) => Record<string, unknown>;\n /** Projects the raw payload onto the record shape the UI consumes. */\n select: (data: TData | undefined) => TResult | undefined;\n /** Thrown (and stored) when the payload is missing or the request fails. */\n errorMessage: string;\n}\n\n/**\n * Writes to the workspace gateway. Returns the `[mutate, state]` tuple used by\n * the reference hooks. `mutate` REJECTS on failure so callers cannot mistake a\n * failed write for a successful one.\n */\nexport function useWorkspaceMutation<TData, TInput, TResult>(\n options: WorkspaceMutationOptions<TData, TInput, TResult>\n): readonly [(input: TInput) => Promise<TResult>, MutationState<TResult>] {\n const { document, errorMessage } = options;\n const client = useWorkspaceClient();\n const variablesRef = useLatest(options.variables);\n const selectRef = useLatest(options.select);\n\n const [state, setState] = useState<MutationState<TResult>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const mutate = useCallback(\n async (input: TInput): Promise<TResult> => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<TData>({\n mutation: document,\n variables: variablesRef.current(input),\n });\n // Apollo v4 does not reject on GraphQL errors by default: the mutation\n // RESOLVES with `data` undefined and the failure on `result.error`\n // (CombinedGraphQLErrors / networkError). Surface it like a rejection\n // so callers see the server's field-level message, not the fallback.\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw toError(operationError, errorMessage);\n }\n const selected = selectRef.current(result.data ?? undefined);\n if (selected === undefined) {\n throw new Error(errorMessage);\n }\n setState({ data: selected, loading: false, error: undefined });\n return selected;\n } catch (mutationError) {\n const failure = toError(mutationError, errorMessage);\n setState({ data: undefined, loading: false, error: failure });\n throw failure;\n }\n },\n [client, document, errorMessage, selectRef, variablesRef]\n );\n\n return [mutate, state] as const;\n}\n"],"mappings":";;;;;AAsBA,SAAgBA,IAAsC;CACpD,OAAOC,EAAiB,WAAW;AACrC;AAGA,SA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KzC,IAAkBF,EAA+B;GACvD,IAAIE,KAAkB,MACpB,MAAM3B,EAAQ2B,GAAgBC,CAAY;GAE5C,IAAMyC,IAAWxD,EAAU,QAAQY,EAAO,QAAQ,KAAA,CAAS;GAC3D,IAAI4C,MAAa,KAAA,GACf,MAAU,MAAMzC,CAAY;GAG9B,OADAuC,EAAS;IAAE,MAAME;IAAU,SAAS;IAAO,OAAO,KAAA;GAAU,CAAC,GACtDA;EACT,SAASC,GAAe;GACtB,IAAMzB,IAAU7C,EAAQsE,GAAe1C,CAAY;GAEnD,MADAuC,EAAS;IAAE,MAAM,KAAA;IAAW,SAAS;IAAO,OAAOtB;GAAQ,CAAC,GACtDA;EACR;CACF,GACA;EAACjC;EAAQc;EAAUE;EAAcf;EAAWoD;CAAY,CAGlD,GAAQC,CAAK;AACvB"}
|
|
@@ -5,6 +5,7 @@ import { useCallback as v, useMemo as y } from "react";
|
|
|
5
5
|
// src/botlit/hooks/useChannels.ts
|
|
6
6
|
var b = 100, x = d({
|
|
7
7
|
bucketId: !0,
|
|
8
|
+
channelId: !0,
|
|
8
9
|
credentialsRefId: !0,
|
|
9
10
|
defaultPolicyBindings: !0,
|
|
10
11
|
description: !0,
|
|
@@ -17,6 +18,7 @@ var b = 100, x = d({
|
|
|
17
18
|
workspaceId: !0
|
|
18
19
|
}), S = d({
|
|
19
20
|
bucketId: !0,
|
|
21
|
+
channelId: !0,
|
|
20
22
|
credentialsRefId: !0,
|
|
21
23
|
defaultPolicyBindings: !0,
|
|
22
24
|
description: !0,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useChannels.js","names":["LIST_LIMIT","CREATE_CONNECTOR_FIELDS","fieldsOf","UPDATE_CONNECTOR_FIELDS","CREATE_ROUTE_FIELDS","UPDATE_ROUTE_FIELDS","NO_CONNECTORS","NO_ROUTES","selectConnectorRows","rows","selectRouteRows","selectConnectors","data","selectConnectorsNextOffset","selectRoutesNextOffset","selectConnector","routeMetadataString","value","route","key","useChannelConnectors","workspaceId","useWorkspaceId","search","filter","type","status","bucketId","variables","useMemo","useWorkspacePaginatedQuery","ListBotmanorChannelConnectorsPageDocument","useChannelConnector","connectorId","useWorkspaceQuery","GetChannelConnectorDocument","useAllChannelConnectors","useWorkspaceAllPagesQuery","useFindChannelConnector","client","useWorkspaceClient","useCallback","offset","result","operationError","match","connector","channelId","nextOffset","useCreateChannelConnector","buildMutationInput","input","useWorkspaceMutation","CreateChannelConnectorDocument","useUpdateChannelConnector","UpdateChannelConnectorDocument","useDeleteChannelConnector","DeleteChannelConnectorDocument","useChannelRoutes","isActive","ListBotmanorChannelRoutesPageDocument","useAllChannelRoutes","NO_OVERVIEW","useChannelOverview","ChannelOverviewDocument","useBotChannelRoutes","botId","useCreateChannelRoute","CreateChannelRouteDocument","useUpdateChannelRoute","UpdateChannelRouteDocument","routeId","useDeleteChannelRoute","DeleteChannelRouteDocument"],"sources":["../../../src/botlit/hooks/useChannels.ts"],"sourcesContent":["/**\n * Channels Hooks\n * @module botlit/hooks\n *\n * Backed by the live `listChannelConnectors` / `listChannelRoutes` operations\n * (and their get/create/update/delete counterparts) on wspace-botlit-svc.\n *\n * Connectors are the platform integrations (Slack, web widget, webhook…).\n * Routes bind a location on a connector to a bot app.\n */\n\nimport { useCallback, useMemo } from 'react';\nimport {\n ChannelOverviewDocument,\n CreateChannelConnectorDocument,\n CreateChannelRouteDocument,\n DeleteChannelConnectorDocument,\n DeleteChannelRouteDocument,\n GetChannelConnectorDocument,\n GetChannelRouteDocument,\n ListBotmanorChannelConnectorsPageDocument,\n ListBotmanorChannelRoutesPageDocument,\n UpdateChannelConnectorDocument,\n UpdateChannelRouteDocument,\n type ChannelOverviewQuery,\n type CreateChannelConnectorMutation,\n type CreateChannelRouteMutation,\n type DeleteChannelConnectorMutation,\n type DeleteChannelRouteMutation,\n type GetChannelConnectorQuery,\n type GetChannelRouteQuery,\n type ListBotmanorChannelConnectorsPageQuery,\n type ListBotmanorChannelRoutesPageQuery,\n type UpdateChannelConnectorMutation,\n type UpdateChannelRouteMutation,\n} from '../../generated/wspace-operations';\nimport type {\n CreateChannelConnectorInput,\n CreateChannelRouteInput,\n UpdateChannelConnectorInput,\n UpdateChannelRouteInput,\n} from '../../generated/wspace-types';\nimport type { ChannelFilter } from '../types';\nimport { buildMutationInput, fieldsOf, type GraphQLInput } from './internal/mutationInput';\nimport {\n useWorkspaceClient,\n useWorkspaceId,\n useWorkspaceMutation,\n useWorkspaceQuery,\n useWorkspaceAllPagesQuery,\n useWorkspacePaginatedQuery,\n type PaginatedQueryResult,\n type QueryResult,\n} from './internal/workspaceGateway';\n\nconst LIST_LIMIT = 100;\n\nexport interface ChannelConnectorRecord {\n id: string;\n name: string;\n type: string;\n status: string;\n visibility: string;\n description?: string | null;\n bucketId?: string | null;\n credentialsRefId?: string | null;\n defaultPolicyBindings?: Record<string, unknown> | null;\n metadata?: Record<string, unknown> | null;\n /** Inbound messages no live route answered (BOFF-12566). */\n unroutedMessageCount: number;\n lastUnroutedAt?: string | null;\n revision: number;\n tags: string[];\n createdAt: string;\n updatedAt: string;\n createdById: string;\n updatedById: string;\n workspaceId: string;\n}\n\nexport interface ChannelRouteRecord {\n id: string;\n appId: string;\n connectorId: string;\n locationId: string;\n /** An inactive route is ignored by inbound routing (BOFF-12566). */\n isActive: boolean;\n metadata?: Record<string, unknown> | null;\n revision: number;\n createdAt: string;\n updatedAt: string;\n workspaceId: string;\n}\n\n/** `CreateChannelConnectorInput` minus the `workspaceId` the hook supplies. */\nexport type CreateChannelConnectorVariables = Omit<\n GraphQLInput<CreateChannelConnectorInput>,\n 'workspaceId'\n>;\n\nexport interface UpdateChannelConnectorVariables {\n connectorId: string;\n input: GraphQLInput<UpdateChannelConnectorInput>;\n}\n\n/**\n * Route fields channel routing never applies. They are deprecated in the\n * schema and the service refuses a value (BOFF-12567), so they are never sent.\n */\ntype UnappliedRouteField = 'policyBindings' | 'formatPolicyId' | 'routingOverrides';\ntype SupportedCreateRouteInput = Omit<CreateChannelRouteInput, UnappliedRouteField>;\ntype SupportedUpdateRouteInput = Omit<UpdateChannelRouteInput, UnappliedRouteField>;\n\n/** `CreateChannelRouteInput` minus the `workspaceId` the hook supplies. */\nexport type CreateChannelRouteVariables = Omit<\n GraphQLInput<SupportedCreateRouteInput>,\n 'workspaceId'\n>;\n\nexport interface UpdateChannelRouteVariables {\n routeId: string;\n input: GraphQLInput<SupportedUpdateRouteInput>;\n}\n\nconst CREATE_CONNECTOR_FIELDS = fieldsOf<CreateChannelConnectorInput>({\n bucketId: true,\n credentialsRefId: true,\n defaultPolicyBindings: true,\n description: true,\n metadata: true,\n name: true,\n status: true,\n tags: true,\n type: true,\n visibility: true,\n workspaceId: true,\n});\n\nconst UPDATE_CONNECTOR_FIELDS = fieldsOf<UpdateChannelConnectorInput>({\n bucketId: true,\n credentialsRefId: true,\n defaultPolicyBindings: true,\n description: true,\n metadata: true,\n name: true,\n status: true,\n tags: true,\n visibility: true,\n});\n\nconst CREATE_ROUTE_FIELDS = fieldsOf<SupportedCreateRouteInput>({\n appId: true,\n connectorId: true,\n isActive: true,\n locationId: true,\n metadata: true,\n workspaceId: true,\n});\n\nconst UPDATE_ROUTE_FIELDS = fieldsOf<SupportedUpdateRouteInput>({\n appId: true,\n isActive: true,\n locationId: true,\n metadata: true,\n});\n\nconst NO_CONNECTORS: ChannelConnectorRecord[] = [];\nconst NO_ROUTES: ChannelRouteRecord[] = [];\n\nconst selectConnectorRows = (rows: ChannelConnectorRecord[]): ChannelConnectorRecord[] => rows;\nconst selectRouteRows = (rows: ChannelRouteRecord[]): ChannelRouteRecord[] => rows;\n\nfunction selectConnectors(\n data: ListBotmanorChannelConnectorsPageQuery | undefined\n): ChannelConnectorRecord[] {\n return data?.listBotmanorChannelConnectorsPage.items ?? NO_CONNECTORS;\n}\n\nfunction selectConnectorsNextOffset(\n data: ListBotmanorChannelConnectorsPageQuery | undefined\n): number | null {\n return data?.listBotmanorChannelConnectorsPage.nextOffset ?? null;\n}\n\nfunction selectRoutesNextOffset(\n data: ListBotmanorChannelRoutesPageQuery | undefined\n): number | null {\n return data?.listBotmanorChannelRoutesPage.nextOffset ?? null;\n}\n\nfunction selectConnector(\n data: GetChannelConnectorQuery | undefined\n): ChannelConnectorRecord | null {\n return data?.getChannelConnector ?? null;\n}\n\nfunction selectRoute(data: GetChannelRouteQuery | undefined): ChannelRouteRecord | null {\n return data?.getChannelRoute ?? null;\n}\n\n/** Reads a display label the UI stashed on the route's free-form metadata. */\nexport function routeMetadataString(\n route: Pick<ChannelRouteRecord, 'metadata'>,\n key: string\n): string | undefined {\n const value = route.metadata?.[key];\n return typeof value === 'string' ? value : undefined;\n}\n\nexport const channelKeys = {\n all: ['channels'] as const,\n connectors: () => [...channelKeys.all, 'connectors'] as const,\n connectorList: (filter?: ChannelFilter) => [...channelKeys.connectors(), 'list', filter] as const,\n connectorDetail: (id: string) => [...channelKeys.connectors(), 'detail', id] as const,\n routes: () => [...channelKeys.all, 'routes'] as const,\n routeList: (connectorId?: string) => [...channelKeys.routes(), 'list', connectorId] as const,\n routeDetail: (id: string) => [...channelKeys.routes(), 'detail', id] as const,\n};\n\n// ============================================================================\n// Connectors\n// ============================================================================\n\n/**\n * Connectors of the workspace, one page at a time (BOFF-12569): `loadMore`\n * reaches every row past the first page. Search, type, status and bucket\n * filters are applied by the service.\n */\nexport function useChannelConnectors(\n filter?: ChannelFilter\n): PaginatedQueryResult<ChannelConnectorRecord[]> {\n const workspaceId = useWorkspaceId();\n const search = filter?.search;\n const type = filter?.type?.[0];\n const status = filter?.status?.[0];\n const bucketId = filter?.bucketId;\n\n const variables = useMemo(\n () => ({\n filters: {\n workspaceId,\n search: search || undefined,\n type,\n status,\n bucketId,\n },\n }),\n [workspaceId, search, type, status, bucketId]\n );\n\n return useWorkspacePaginatedQuery<\n ListBotmanorChannelConnectorsPageQuery,\n ChannelConnectorRecord,\n ChannelConnectorRecord[]\n >({\n document: ListBotmanorChannelConnectorsPageDocument,\n variables,\n pageSize: LIST_LIMIT,\n extractRows: selectConnectors,\n extractNextOffset: selectConnectorsNextOffset,\n select: selectConnectorRows,\n fallback: NO_CONNECTORS,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load channel connectors',\n });\n}\n\nexport function useChannelConnector(\n connectorId: string | undefined\n): QueryResult<ChannelConnectorRecord | null> {\n const variables = useMemo(() => ({ id: connectorId ?? '' }), [connectorId]);\n\n return useWorkspaceQuery<GetChannelConnectorQuery, ChannelConnectorRecord | null>({\n document: GetChannelConnectorDocument,\n variables,\n select: selectConnector,\n fallback: null,\n enabled: Boolean(connectorId),\n errorMessage: 'Failed to load channel connector',\n });\n}\n\n/**\n * Every connector of the workspace, all pages (BOFF-15360). For pickers that\n * must offer each connector: `useChannelConnectors` stops at the first page.\n */\nexport function useAllChannelConnectors(): QueryResult<ChannelConnectorRecord[]> {\n const workspaceId = useWorkspaceId();\n const variables = useMemo(() => ({ filters: { workspaceId } }), [workspaceId]);\n\n return useWorkspaceAllPagesQuery<\n ListBotmanorChannelConnectorsPageQuery,\n ChannelConnectorRecord,\n ChannelConnectorRecord[]\n >({\n document: ListBotmanorChannelConnectorsPageDocument,\n variables,\n pageSize: LIST_LIMIT,\n extractRows: selectConnectors,\n extractNextOffset: selectConnectorsNextOffset,\n select: selectConnectorRows,\n fallback: NO_CONNECTORS,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load channel connectors',\n });\n}\n\n/**\n * Looks up whether this workspace already has a connector naming a global\n * channel. Resolves to the connector, null when there is none, and rejects\n * when the lookup itself fails (the answer is then unknown).\n */\nexport function useFindChannelConnector(): (\n channelId: string\n) => Promise<ChannelConnectorRecord | null> {\n const client = useWorkspaceClient();\n const workspaceId = useWorkspaceId();\n\n return useCallback(\n async (channelId: string) => {\n // Every page: a match beyond the first page must still be found, or a\n // duplicate connector would be created for the same channel.\n for (let offset: number | null = 0; offset !== null;) {\n const result = await client.query<ListBotmanorChannelConnectorsPageQuery>({\n query: ListBotmanorChannelConnectorsPageDocument,\n variables: { filters: { workspaceId }, pagination: { limit: LIST_LIMIT, offset } },\n fetchPolicy: 'network-only',\n });\n // Apollo v4 resolves with `error` set on GraphQL errors.\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) throw operationError;\n const page = selectConnectors(result.data ?? undefined);\n const match = page.find((connector) => connector.credentialsRefId === channelId);\n if (match) return match;\n const nextOffset = selectConnectorsNextOffset(result.data ?? undefined);\n if (nextOffset === null || !Number.isSafeInteger(nextOffset) || nextOffset <= offset) {\n return null;\n }\n offset = nextOffset;\n }\n return null;\n },\n [client, workspaceId]\n );\n}\n\nexport function useCreateChannelConnector() {\n const workspaceId = useWorkspaceId();\n\n const variables = useCallback(\n (input: CreateChannelConnectorVariables) => ({\n input: buildMutationInput({ ...input, workspaceId }, CREATE_CONNECTOR_FIELDS),\n }),\n [workspaceId]\n );\n\n return useWorkspaceMutation<\n CreateChannelConnectorMutation,\n CreateChannelConnectorVariables,\n ChannelConnectorRecord\n >({\n document: CreateChannelConnectorDocument,\n variables,\n select: (data) => data?.createChannelConnector,\n errorMessage: 'Failed to create channel connector',\n });\n}\n\nexport function useUpdateChannelConnector() {\n return useWorkspaceMutation<\n UpdateChannelConnectorMutation,\n UpdateChannelConnectorVariables,\n ChannelConnectorRecord\n >({\n document: UpdateChannelConnectorDocument,\n variables: ({ connectorId, input }) => ({\n id: connectorId,\n input: buildMutationInput(input, UPDATE_CONNECTOR_FIELDS),\n }),\n select: (data) => data?.updateChannelConnector,\n errorMessage: 'Failed to update channel connector',\n });\n}\n\nexport function useDeleteChannelConnector() {\n return useWorkspaceMutation<DeleteChannelConnectorMutation, string, boolean>({\n document: DeleteChannelConnectorDocument,\n variables: (connectorId) => ({ id: connectorId }),\n select: (data) => data?.deleteChannelConnector,\n errorMessage: 'Failed to delete channel connector',\n });\n}\n\n// ============================================================================\n// Routes\n// ============================================================================\n\nexport interface ChannelRouteListFilter {\n connectorId?: string;\n /** Only routes that are on (true) or off (false); all when undefined. */\n isActive?: boolean;\n}\n\n/**\n * Routes of the workspace (optionally of one connector), one page at a time\n * (BOFF-12569): `loadMore` reaches every row past the first page.\n */\nexport function useChannelRoutes(\n filter?: ChannelRouteListFilter\n): PaginatedQueryResult<ChannelRouteRecord[]> {\n const workspaceId = useWorkspaceId();\n const connectorId = filter?.connectorId;\n const isActive = filter?.isActive;\n\n const variables = useMemo(\n () => ({\n filters: { workspaceId, connectorId: connectorId || undefined, isActive },\n }),\n [workspaceId, connectorId, isActive]\n );\n\n return useWorkspacePaginatedQuery<\n ListBotmanorChannelRoutesPageQuery,\n ChannelRouteRecord,\n ChannelRouteRecord[]\n >({\n document: ListBotmanorChannelRoutesPageDocument,\n variables,\n pageSize: LIST_LIMIT,\n extractRows: (result) => result?.listBotmanorChannelRoutesPage.items ?? NO_ROUTES,\n extractNextOffset: selectRoutesNextOffset,\n select: selectRouteRows,\n fallback: NO_ROUTES,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load channel routes',\n });\n}\n\n/**\n * Every route of the workspace (or of one connector), all pages. For derived\n * figures that must not stop at the first page, such as route counts.\n */\nexport function useAllChannelRoutes(connectorId?: string): QueryResult<ChannelRouteRecord[]> {\n const workspaceId = useWorkspaceId();\n const variables = useMemo(\n () => ({ filters: { workspaceId, connectorId: connectorId || undefined } }),\n [workspaceId, connectorId]\n );\n\n return useWorkspaceAllPagesQuery<\n ListBotmanorChannelRoutesPageQuery,\n ChannelRouteRecord,\n ChannelRouteRecord[]\n >({\n document: ListBotmanorChannelRoutesPageDocument,\n variables,\n pageSize: LIST_LIMIT,\n extractRows: (result) => result?.listBotmanorChannelRoutesPage.items ?? NO_ROUTES,\n extractNextOffset: selectRoutesNextOffset,\n select: selectRouteRows,\n fallback: NO_ROUTES,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load channel routes',\n });\n}\n\nexport interface ChannelOverview {\n connectorCount: number;\n activeConnectorCount: number;\n routeCount: number;\n activeRouteCount: number;\n unroutedMessageCount: number;\n}\n\nconst NO_OVERVIEW: ChannelOverview | null = null;\n\n/**\n * The workspace's real channel totals from the service (BOFF-12569), so tab\n * counts and \"Active routes\" never depend on how many rows were loaded.\n */\nexport function useChannelOverview(): QueryResult<ChannelOverview | null> {\n const workspaceId = useWorkspaceId();\n const variables = useMemo(() => ({ workspaceId }), [workspaceId]);\n\n return useWorkspaceQuery<ChannelOverviewQuery, ChannelOverview | null>({\n document: ChannelOverviewDocument,\n variables,\n select: (data) => data?.channelOverview ?? null,\n fallback: NO_OVERVIEW,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load channel totals',\n });\n}\n\n/** Routes bound to a specific bot app (Bot Detail → Channels tab). */\n/**\n * Every route of one bot, all pages: the Channels tab derives which\n * connectors are already routed from it, so a later page must not be missed.\n */\nexport function useBotChannelRoutes(botId: string | undefined): QueryResult<ChannelRouteRecord[]> {\n const workspaceId = useWorkspaceId();\n\n const variables = useMemo(\n () => ({ filters: { workspaceId, appId: botId } }),\n [workspaceId, botId]\n );\n\n return useWorkspaceAllPagesQuery<\n ListBotmanorChannelRoutesPageQuery,\n ChannelRouteRecord,\n ChannelRouteRecord[]\n >({\n document: ListBotmanorChannelRoutesPageDocument,\n variables,\n pageSize: LIST_LIMIT,\n extractRows: (result) => result?.listBotmanorChannelRoutesPage.items ?? NO_ROUTES,\n extractNextOffset: selectRoutesNextOffset,\n select: selectRouteRows,\n fallback: NO_ROUTES,\n enabled: Boolean(workspaceId) && Boolean(botId),\n errorMessage: 'Failed to load channel routes for this bot',\n });\n}\n\nexport function useChannelRoute(\n routeId: string | undefined\n): QueryResult<ChannelRouteRecord | null> {\n const variables = useMemo(() => ({ id: routeId ?? '' }), [routeId]);\n\n return useWorkspaceQuery<GetChannelRouteQuery, ChannelRouteRecord | null>({\n document: GetChannelRouteDocument,\n variables,\n select: selectRoute,\n fallback: null,\n enabled: Boolean(routeId),\n errorMessage: 'Failed to load channel route',\n });\n}\n\nexport function useCreateChannelRoute() {\n const workspaceId = useWorkspaceId();\n\n const variables = useCallback(\n (input: CreateChannelRouteVariables) => ({\n input: buildMutationInput({ ...input, workspaceId }, CREATE_ROUTE_FIELDS),\n }),\n [workspaceId]\n );\n\n return useWorkspaceMutation<\n CreateChannelRouteMutation,\n CreateChannelRouteVariables,\n ChannelRouteRecord\n >({\n document: CreateChannelRouteDocument,\n variables,\n select: (data) => data?.createChannelRoute,\n errorMessage: 'Failed to create channel route',\n });\n}\n\nexport function useUpdateChannelRoute() {\n return useWorkspaceMutation<\n UpdateChannelRouteMutation,\n UpdateChannelRouteVariables,\n ChannelRouteRecord\n >({\n document: UpdateChannelRouteDocument,\n variables: ({ routeId, input }) => ({\n id: routeId,\n input: buildMutationInput(input, UPDATE_ROUTE_FIELDS),\n }),\n select: (data) => data?.updateChannelRoute,\n errorMessage: 'Failed to update channel route',\n });\n}\n\nexport function useDeleteChannelRoute() {\n return useWorkspaceMutation<DeleteChannelRouteMutation, string, boolean>({\n document: DeleteChannelRouteDocument,\n variables: (routeId) => ({ id: routeId }),\n select: (data) => data?.deleteChannelRoute,\n errorMessage: 'Failed to delete channel route',\n });\n}\n"],"mappings":";;;;;AAuDA,IAAMA,IAAa,KAqEbC,IAA0BC,EAAsC;CACpE,UAAU;CACV,kBAAkB;CAClB,uBAAuB;CACvB,aAAa;CACb,UAAU;CACV,MAAM;CACN,QAAQ;CACR,MAAM;CACN,MAAM;CACN,YAAY;CACZ,aAAa;AACf,CAAC,GAEKC,IAA0BD,EAAsC;CACpE,UAAU;CACV,kBAAkB;CAClB,uBAAuB;CACvB,aAAa;CACb,UAAU;CACV,MAAM;CACN,QAAQ;CACR,MAAM;CACN,YAAY;AACd,CAAC,GAEKE,IAAsBF,EAAoC;CAC9D,OAAO;CACP,aAAa;CACb,UAAU;CACV,YAAY;CACZ,UAAU;CACV,aAAa;AACf,CAAC,GAEKG,IAAsBH,EAAoC;CAC9D,OAAO;CACP,UAAU;CACV,YAAY;CACZ,UAAU;AACZ,CAAC,GAEKI,IAA0C,CAAC,GAC3CC,IAAkC,CAAC,GAEn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,EAAoB,GAA8D;CAChG,IAAM5C,IAAcC,EAAe,GAE7BM,IAAYC,SACT,EAAE,SAAS;EAAE;EAAa,OAAOqC;CAAM,EAAE,IAChD,CAAC7C,GAAa6C,CAAK,CACrB;CAEA,OAAO7B,EAIL;EACA,UAAUuB;EACV;EACA,UAAU5D;EACV,cAAc,MAAW2C,GAAQ,8BAA8B,SAASpC;EACxE,mBAAmBO;EACnB,QAAQJ;EACR,UAAUH;EACV,SAAS,EAAQc,KAAgB,EAAQ6C;EACzC,cAAc;CAChB,CAAC;AACH;AAiBA,SAAgBC,IAAwB;CACtC,IAAM9C,IAAcC,EAAe,GAE7BM,IAAYa,GACf,OAAwC,EACvC,OAAOS,EAAmB;EAAE,GAAGC;EAAO;CAAY,GAAG/C,CAAmB,EAC1E,IACA,CAACiB,CAAW,CACd;CAEA,OAAO+B,EAIL;EACA,UAAUgB;EACV;EACA,SAAS,MAASxD,GAAM;EACxB,cAAc;CAChB,CAAC;AACH;AAEA,SAAgByD,IAAwB;CACtC,OAAOjB,EAIL;EACA,UAAUkB;EACV,YAAY,EAAE,YAAS,gBAAa;GAClC,IAAIC;GACJ,OAAOrB,EAAmBC,GAAO9C,CAAmB;EACtD;EACA,SAAS,MAASO,GAAM;EACxB,cAAc;CAChB,CAAC;AACH;AAEA,SAAgB4D,IAAwB;CACtC,OAAOpB,EAAkE;EACvE,UAAUqB;EACV,YAAY,OAAa,EAAE,IAAIF,EAAQ;EACvC,SAAS,MAAS3D,GAAM;EACxB,cAAc;CAChB,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"useChannels.js","names":["LIST_LIMIT","CREATE_CONNECTOR_FIELDS","fieldsOf","UPDATE_CONNECTOR_FIELDS","CREATE_ROUTE_FIELDS","UPDATE_ROUTE_FIELDS","NO_CONNECTORS","NO_ROUTES","selectConnectorRows","rows","selectRouteRows","selectConnectors","data","selectConnectorsNextOffset","selectRoutesNextOffset","selectConnector","routeMetadataString","value","route","key","useChannelConnectors","workspaceId","useWorkspaceId","search","filter","type","status","bucketId","variables","useMemo","useWorkspacePaginatedQuery","ListBotmanorChannelConnectorsPageDocument","useChannelConnector","connectorId","useWorkspaceQuery","GetChannelConnectorDocument","useAllChannelConnectors","useWorkspaceAllPagesQuery","useFindChannelConnector","client","useWorkspaceClient","useCallback","offset","result","operationError","match","connector","channelId","nextOffset","useCreateChannelConnector","buildMutationInput","input","useWorkspaceMutation","CreateChannelConnectorDocument","useUpdateChannelConnector","UpdateChannelConnectorDocument","useDeleteChannelConnector","DeleteChannelConnectorDocument","useChannelRoutes","isActive","ListBotmanorChannelRoutesPageDocument","useAllChannelRoutes","NO_OVERVIEW","useChannelOverview","ChannelOverviewDocument","useBotChannelRoutes","botId","useCreateChannelRoute","CreateChannelRouteDocument","useUpdateChannelRoute","UpdateChannelRouteDocument","routeId","useDeleteChannelRoute","DeleteChannelRouteDocument"],"sources":["../../../src/botlit/hooks/useChannels.ts"],"sourcesContent":["/**\n * Channels Hooks\n * @module botlit/hooks\n *\n * Backed by the live `listChannelConnectors` / `listChannelRoutes` operations\n * (and their get/create/update/delete counterparts) on wspace-botlit-svc.\n *\n * Connectors are the platform integrations (Slack, web widget, webhook…).\n * Routes bind a location on a connector to a bot app.\n */\n\nimport { useCallback, useMemo } from 'react';\nimport {\n ChannelOverviewDocument,\n CreateChannelConnectorDocument,\n CreateChannelRouteDocument,\n DeleteChannelConnectorDocument,\n DeleteChannelRouteDocument,\n GetChannelConnectorDocument,\n GetChannelRouteDocument,\n ListBotmanorChannelConnectorsPageDocument,\n ListBotmanorChannelRoutesPageDocument,\n UpdateChannelConnectorDocument,\n UpdateChannelRouteDocument,\n type ChannelOverviewQuery,\n type CreateChannelConnectorMutation,\n type CreateChannelRouteMutation,\n type DeleteChannelConnectorMutation,\n type DeleteChannelRouteMutation,\n type GetChannelConnectorQuery,\n type GetChannelRouteQuery,\n type ListBotmanorChannelConnectorsPageQuery,\n type ListBotmanorChannelRoutesPageQuery,\n type UpdateChannelConnectorMutation,\n type UpdateChannelRouteMutation,\n} from '../../generated/wspace-operations';\nimport type {\n CreateChannelConnectorInput,\n CreateChannelRouteInput,\n UpdateChannelConnectorInput,\n UpdateChannelRouteInput,\n} from '../../generated/wspace-types';\nimport type { ChannelFilter } from '../types';\nimport { buildMutationInput, fieldsOf, type GraphQLInput } from './internal/mutationInput';\nimport {\n useWorkspaceClient,\n useWorkspaceId,\n useWorkspaceMutation,\n useWorkspaceQuery,\n useWorkspaceAllPagesQuery,\n useWorkspacePaginatedQuery,\n type PaginatedQueryResult,\n type QueryResult,\n} from './internal/workspaceGateway';\n\nconst LIST_LIMIT = 100;\n\nexport interface ChannelConnectorRecord {\n id: string;\n name: string;\n type: string;\n status: string;\n visibility: string;\n description?: string | null;\n bucketId?: string | null;\n credentialsRefId?: string | null;\n defaultPolicyBindings?: Record<string, unknown> | null;\n metadata?: Record<string, unknown> | null;\n /** Inbound messages no live route answered (BOFF-12566). */\n unroutedMessageCount: number;\n lastUnroutedAt?: string | null;\n revision: number;\n tags: string[];\n createdAt: string;\n updatedAt: string;\n createdById: string;\n updatedById: string;\n workspaceId: string;\n}\n\nexport interface ChannelRouteRecord {\n id: string;\n appId: string;\n connectorId: string;\n locationId: string;\n /** An inactive route is ignored by inbound routing (BOFF-12566). */\n isActive: boolean;\n metadata?: Record<string, unknown> | null;\n revision: number;\n createdAt: string;\n updatedAt: string;\n workspaceId: string;\n}\n\n/** `CreateChannelConnectorInput` minus the `workspaceId` the hook supplies. */\nexport type CreateChannelConnectorVariables = Omit<\n GraphQLInput<CreateChannelConnectorInput>,\n 'workspaceId'\n>;\n\nexport interface UpdateChannelConnectorVariables {\n connectorId: string;\n input: GraphQLInput<UpdateChannelConnectorInput>;\n}\n\n/**\n * Route fields channel routing never applies. They are deprecated in the\n * schema and the service refuses a value (BOFF-12567), so they are never sent.\n */\ntype UnappliedRouteField = 'policyBindings' | 'formatPolicyId' | 'routingOverrides';\ntype SupportedCreateRouteInput = Omit<CreateChannelRouteInput, UnappliedRouteField>;\ntype SupportedUpdateRouteInput = Omit<UpdateChannelRouteInput, UnappliedRouteField>;\n\n/** `CreateChannelRouteInput` minus the `workspaceId` the hook supplies. */\nexport type CreateChannelRouteVariables = Omit<\n GraphQLInput<SupportedCreateRouteInput>,\n 'workspaceId'\n>;\n\nexport interface UpdateChannelRouteVariables {\n routeId: string;\n input: GraphQLInput<SupportedUpdateRouteInput>;\n}\n\nconst CREATE_CONNECTOR_FIELDS = fieldsOf<CreateChannelConnectorInput>({\n bucketId: true,\n channelId: true,\n credentialsRefId: true,\n defaultPolicyBindings: true,\n description: true,\n metadata: true,\n name: true,\n status: true,\n tags: true,\n type: true,\n visibility: true,\n workspaceId: true,\n});\n\nconst UPDATE_CONNECTOR_FIELDS = fieldsOf<UpdateChannelConnectorInput>({\n bucketId: true,\n channelId: true,\n credentialsRefId: true,\n defaultPolicyBindings: true,\n description: true,\n metadata: true,\n name: true,\n status: true,\n tags: true,\n visibility: true,\n});\n\nconst CREATE_ROUTE_FIELDS = fieldsOf<SupportedCreateRouteInput>({\n appId: true,\n connectorId: true,\n isActive: true,\n locationId: true,\n metadata: true,\n workspaceId: true,\n});\n\nconst UPDATE_ROUTE_FIELDS = fieldsOf<SupportedUpdateRouteInput>({\n appId: true,\n isActive: true,\n locationId: true,\n metadata: true,\n});\n\nconst NO_CONNECTORS: ChannelConnectorRecord[] = [];\nconst NO_ROUTES: ChannelRouteRecord[] = [];\n\nconst selectConnectorRows = (rows: ChannelConnectorRecord[]): ChannelConnectorRecord[] => rows;\nconst selectRouteRows = (rows: ChannelRouteRecord[]): ChannelRouteRecord[] => rows;\n\nfunction selectConnectors(\n data: ListBotmanorChannelConnectorsPageQuery | undefined\n): ChannelConnectorRecord[] {\n return data?.listBotmanorChannelConnectorsPage.items ?? NO_CONNECTORS;\n}\n\nfunction selectConnectorsNextOffset(\n data: ListBotmanorChannelConnectorsPageQuery | undefined\n): number | null {\n return data?.listBotmanorChannelConnectorsPage.nextOffset ?? null;\n}\n\nfunction selectRoutesNextOffset(\n data: ListBotmanorChannelRoutesPageQuery | undefined\n): number | null {\n return data?.listBotmanorChannelRoutesPage.nextOffset ?? null;\n}\n\nfunction selectConnector(\n data: GetChannelConnectorQuery | undefined\n): ChannelConnectorRecord | null {\n return data?.getChannelConnector ?? null;\n}\n\nfunction selectRoute(data: GetChannelRouteQuery | undefined): ChannelRouteRecord | null {\n return data?.getChannelRoute ?? null;\n}\n\n/** Reads a display label the UI stashed on the route's free-form metadata. */\nexport function routeMetadataString(\n route: Pick<ChannelRouteRecord, 'metadata'>,\n key: string\n): string | undefined {\n const value = route.metadata?.[key];\n return typeof value === 'string' ? value : undefined;\n}\n\nexport const channelKeys = {\n all: ['channels'] as const,\n connectors: () => [...channelKeys.all, 'connectors'] as const,\n connectorList: (filter?: ChannelFilter) => [...channelKeys.connectors(), 'list', filter] as const,\n connectorDetail: (id: string) => [...channelKeys.connectors(), 'detail', id] as const,\n routes: () => [...channelKeys.all, 'routes'] as const,\n routeList: (connectorId?: string) => [...channelKeys.routes(), 'list', connectorId] as const,\n routeDetail: (id: string) => [...channelKeys.routes(), 'detail', id] as const,\n};\n\n// ============================================================================\n// Connectors\n// ============================================================================\n\n/**\n * Connectors of the workspace, one page at a time (BOFF-12569): `loadMore`\n * reaches every row past the first page. Search, type, status and bucket\n * filters are applied by the service.\n */\nexport function useChannelConnectors(\n filter?: ChannelFilter\n): PaginatedQueryResult<ChannelConnectorRecord[]> {\n const workspaceId = useWorkspaceId();\n const search = filter?.search;\n const type = filter?.type?.[0];\n const status = filter?.status?.[0];\n const bucketId = filter?.bucketId;\n\n const variables = useMemo(\n () => ({\n filters: {\n workspaceId,\n search: search || undefined,\n type,\n status,\n bucketId,\n },\n }),\n [workspaceId, search, type, status, bucketId]\n );\n\n return useWorkspacePaginatedQuery<\n ListBotmanorChannelConnectorsPageQuery,\n ChannelConnectorRecord,\n ChannelConnectorRecord[]\n >({\n document: ListBotmanorChannelConnectorsPageDocument,\n variables,\n pageSize: LIST_LIMIT,\n extractRows: selectConnectors,\n extractNextOffset: selectConnectorsNextOffset,\n select: selectConnectorRows,\n fallback: NO_CONNECTORS,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load channel connectors',\n });\n}\n\nexport function useChannelConnector(\n connectorId: string | undefined\n): QueryResult<ChannelConnectorRecord | null> {\n const variables = useMemo(() => ({ id: connectorId ?? '' }), [connectorId]);\n\n return useWorkspaceQuery<GetChannelConnectorQuery, ChannelConnectorRecord | null>({\n document: GetChannelConnectorDocument,\n variables,\n select: selectConnector,\n fallback: null,\n enabled: Boolean(connectorId),\n errorMessage: 'Failed to load channel connector',\n });\n}\n\n/**\n * Every connector of the workspace, all pages (BOFF-15360). For pickers that\n * must offer each connector: `useChannelConnectors` stops at the first page.\n */\nexport function useAllChannelConnectors(): QueryResult<ChannelConnectorRecord[]> {\n const workspaceId = useWorkspaceId();\n const variables = useMemo(() => ({ filters: { workspaceId } }), [workspaceId]);\n\n return useWorkspaceAllPagesQuery<\n ListBotmanorChannelConnectorsPageQuery,\n ChannelConnectorRecord,\n ChannelConnectorRecord[]\n >({\n document: ListBotmanorChannelConnectorsPageDocument,\n variables,\n pageSize: LIST_LIMIT,\n extractRows: selectConnectors,\n extractNextOffset: selectConnectorsNextOffset,\n select: selectConnectorRows,\n fallback: NO_CONNECTORS,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load channel connectors',\n });\n}\n\n/**\n * Looks up whether this workspace already has a connector naming a global\n * channel. Resolves to the connector, null when there is none, and rejects\n * when the lookup itself fails (the answer is then unknown).\n */\nexport function useFindChannelConnector(): (\n channelId: string\n) => Promise<ChannelConnectorRecord | null> {\n const client = useWorkspaceClient();\n const workspaceId = useWorkspaceId();\n\n return useCallback(\n async (channelId: string) => {\n // Every page: a match beyond the first page must still be found, or a\n // duplicate connector would be created for the same channel.\n for (let offset: number | null = 0; offset !== null;) {\n const result = await client.query<ListBotmanorChannelConnectorsPageQuery>({\n query: ListBotmanorChannelConnectorsPageDocument,\n variables: { filters: { workspaceId }, pagination: { limit: LIST_LIMIT, offset } },\n fetchPolicy: 'network-only',\n });\n // Apollo v4 resolves with `error` set on GraphQL errors.\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) throw operationError;\n const page = selectConnectors(result.data ?? undefined);\n const match = page.find((connector) => connector.credentialsRefId === channelId);\n if (match) return match;\n const nextOffset = selectConnectorsNextOffset(result.data ?? undefined);\n if (nextOffset === null || !Number.isSafeInteger(nextOffset) || nextOffset <= offset) {\n return null;\n }\n offset = nextOffset;\n }\n return null;\n },\n [client, workspaceId]\n );\n}\n\nexport function useCreateChannelConnector() {\n const workspaceId = useWorkspaceId();\n\n const variables = useCallback(\n (input: CreateChannelConnectorVariables) => ({\n input: buildMutationInput({ ...input, workspaceId }, CREATE_CONNECTOR_FIELDS),\n }),\n [workspaceId]\n );\n\n return useWorkspaceMutation<\n CreateChannelConnectorMutation,\n CreateChannelConnectorVariables,\n ChannelConnectorRecord\n >({\n document: CreateChannelConnectorDocument,\n variables,\n select: (data) => data?.createChannelConnector,\n errorMessage: 'Failed to create channel connector',\n });\n}\n\nexport function useUpdateChannelConnector() {\n return useWorkspaceMutation<\n UpdateChannelConnectorMutation,\n UpdateChannelConnectorVariables,\n ChannelConnectorRecord\n >({\n document: UpdateChannelConnectorDocument,\n variables: ({ connectorId, input }) => ({\n id: connectorId,\n input: buildMutationInput(input, UPDATE_CONNECTOR_FIELDS),\n }),\n select: (data) => data?.updateChannelConnector,\n errorMessage: 'Failed to update channel connector',\n });\n}\n\nexport function useDeleteChannelConnector() {\n return useWorkspaceMutation<DeleteChannelConnectorMutation, string, boolean>({\n document: DeleteChannelConnectorDocument,\n variables: (connectorId) => ({ id: connectorId }),\n select: (data) => data?.deleteChannelConnector,\n errorMessage: 'Failed to delete channel connector',\n });\n}\n\n// ============================================================================\n// Routes\n// ============================================================================\n\nexport interface ChannelRouteListFilter {\n connectorId?: string;\n /** Only routes that are on (true) or off (false); all when undefined. */\n isActive?: boolean;\n}\n\n/**\n * Routes of the workspace (optionally of one connector), one page at a time\n * (BOFF-12569): `loadMore` reaches every row past the first page.\n */\nexport function useChannelRoutes(\n filter?: ChannelRouteListFilter\n): PaginatedQueryResult<ChannelRouteRecord[]> {\n const workspaceId = useWorkspaceId();\n const connectorId = filter?.connectorId;\n const isActive = filter?.isActive;\n\n const variables = useMemo(\n () => ({\n filters: { workspaceId, connectorId: connectorId || undefined, isActive },\n }),\n [workspaceId, connectorId, isActive]\n );\n\n return useWorkspacePaginatedQuery<\n ListBotmanorChannelRoutesPageQuery,\n ChannelRouteRecord,\n ChannelRouteRecord[]\n >({\n document: ListBotmanorChannelRoutesPageDocument,\n variables,\n pageSize: LIST_LIMIT,\n extractRows: (result) => result?.listBotmanorChannelRoutesPage.items ?? NO_ROUTES,\n extractNextOffset: selectRoutesNextOffset,\n select: selectRouteRows,\n fallback: NO_ROUTES,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load channel routes',\n });\n}\n\n/**\n * Every route of the workspace (or of one connector), all pages. For derived\n * figures that must not stop at the first page, such as route counts.\n */\nexport function useAllChannelRoutes(connectorId?: string): QueryResult<ChannelRouteRecord[]> {\n const workspaceId = useWorkspaceId();\n const variables = useMemo(\n () => ({ filters: { workspaceId, connectorId: connectorId || undefined } }),\n [workspaceId, connectorId]\n );\n\n return useWorkspaceAllPagesQuery<\n ListBotmanorChannelRoutesPageQuery,\n ChannelRouteRecord,\n ChannelRouteRecord[]\n >({\n document: ListBotmanorChannelRoutesPageDocument,\n variables,\n pageSize: LIST_LIMIT,\n extractRows: (result) => result?.listBotmanorChannelRoutesPage.items ?? NO_ROUTES,\n extractNextOffset: selectRoutesNextOffset,\n select: selectRouteRows,\n fallback: NO_ROUTES,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load channel routes',\n });\n}\n\nexport interface ChannelOverview {\n connectorCount: number;\n activeConnectorCount: number;\n routeCount: number;\n activeRouteCount: number;\n unroutedMessageCount: number;\n}\n\nconst NO_OVERVIEW: ChannelOverview | null = null;\n\n/**\n * The workspace's real channel totals from the service (BOFF-12569), so tab\n * counts and \"Active routes\" never depend on how many rows were loaded.\n */\nexport function useChannelOverview(): QueryResult<ChannelOverview | null> {\n const workspaceId = useWorkspaceId();\n const variables = useMemo(() => ({ workspaceId }), [workspaceId]);\n\n return useWorkspaceQuery<ChannelOverviewQuery, ChannelOverview | null>({\n document: ChannelOverviewDocument,\n variables,\n select: (data) => data?.channelOverview ?? null,\n fallback: NO_OVERVIEW,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load channel totals',\n });\n}\n\n/** Routes bound to a specific bot app (Bot Detail → Channels tab). */\n/**\n * Every route of one bot, all pages: the Channels tab derives which\n * connectors are already routed from it, so a later page must not be missed.\n */\nexport function useBotChannelRoutes(botId: string | undefined): QueryResult<ChannelRouteRecord[]> {\n const workspaceId = useWorkspaceId();\n\n const variables = useMemo(\n () => ({ filters: { workspaceId, appId: botId } }),\n [workspaceId, botId]\n );\n\n return useWorkspaceAllPagesQuery<\n ListBotmanorChannelRoutesPageQuery,\n ChannelRouteRecord,\n ChannelRouteRecord[]\n >({\n document: ListBotmanorChannelRoutesPageDocument,\n variables,\n pageSize: LIST_LIMIT,\n extractRows: (result) => result?.listBotmanorChannelRoutesPage.items ?? NO_ROUTES,\n extractNextOffset: selectRoutesNextOffset,\n select: selectRouteRows,\n fallback: NO_ROUTES,\n enabled: Boolean(workspaceId) && Boolean(botId),\n errorMessage: 'Failed to load channel routes for this bot',\n });\n}\n\nexport function useChannelRoute(\n routeId: string | undefined\n): QueryResult<ChannelRouteRecord | null> {\n const variables = useMemo(() => ({ id: routeId ?? '' }), [routeId]);\n\n return useWorkspaceQuery<GetChannelRouteQuery, ChannelRouteRecord | null>({\n document: GetChannelRouteDocument,\n variables,\n select: selectRoute,\n fallback: null,\n enabled: Boolean(routeId),\n errorMessage: 'Failed to load channel route',\n });\n}\n\nexport function useCreateChannelRoute() {\n const workspaceId = useWorkspaceId();\n\n const variables = useCallback(\n (input: CreateChannelRouteVariables) => ({\n input: buildMutationInput({ ...input, workspaceId }, CREATE_ROUTE_FIELDS),\n }),\n [workspaceId]\n );\n\n return useWorkspaceMutation<\n CreateChannelRouteMutation,\n CreateChannelRouteVariables,\n ChannelRouteRecord\n >({\n document: CreateChannelRouteDocument,\n variables,\n select: (data) => data?.createChannelRoute,\n errorMessage: 'Failed to create channel route',\n });\n}\n\nexport function useUpdateChannelRoute() {\n return useWorkspaceMutation<\n UpdateChannelRouteMutation,\n UpdateChannelRouteVariables,\n ChannelRouteRecord\n >({\n document: UpdateChannelRouteDocument,\n variables: ({ routeId, input }) => ({\n id: routeId,\n input: buildMutationInput(input, UPDATE_ROUTE_FIELDS),\n }),\n select: (data) => data?.updateChannelRoute,\n errorMessage: 'Failed to update channel route',\n });\n}\n\nexport function useDeleteChannelRoute() {\n return useWorkspaceMutation<DeleteChannelRouteMutation, string, boolean>({\n document: DeleteChannelRouteDocument,\n variables: (routeId) => ({ id: routeId }),\n select: (data) => data?.deleteChannelRoute,\n errorMessage: 'Failed to delete channel route',\n });\n}\n"],"mappings":";;;;;AAuDA,IAAMA,IAAa,KAqEbC,IAA0BC,EAAsC;CACpE,UAAU;CACV,WAAW;CACX,kBAAkB;CAClB,uBAAuB;CACvB,aAAa;CACb,UAAU;CACV,MAAM;CACN,QAAQ;CACR,MAAM;CACN,MAAM;CACN,YAAY;CACZ,aAAa;AACf,CAAC,GAEKC,IAA0BD,EAAsC;CACpE,UAAU;CACV,WAAW;CACX,kBAAkB;CAClB,uBAAuB;CACvB,aAAa;CACb,UAAU;CACV,MAAM;CACN,QAAQ;CACR,MAAM;CACN,YAAY;AACd,CAAC,GAEKE,IAAsBF,EAAoC;CAC9D,OAAO;CACP,aAAa;CACb,UAAU;CACV,YAAY;CACZ,UAAU;CACV,aAAa;AACf,CAAC,GAEKG,IAAsBH,EAAoC;CAC9D,OAAO;CACP,UAAU;CACV,YAAY;CACZ,UAAU;AACZ,CAAC,GAEKI,IAA0C,CAAC,G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CAAC;AACH;AAOA,SAAgB4C,EAAoB,GAA8D;CAChG,IAAM5C,IAAcC,EAAe,GAE7BM,IAAYC,SACT,EAAE,SAAS;EAAE;EAAa,OAAOqC;CAAM,EAAE,IAChD,CAAC7C,GAAa6C,CAAK,CACrB;CAEA,OAAO7B,EAIL;EACA,UAAUuB;EACV;EACA,UAAU5D;EACV,cAAc,MAAW2C,GAAQ,8BAA8B,SAASpC;EACxE,mBAAmBO;EACnB,QAAQJ;EACR,UAAUH;EACV,SAAS,EAAQc,KAAgB,EAAQ6C;EACzC,cAAc;CAChB,CAAC;AACH;AAiBA,SAAgBC,IAAwB;CACtC,IAAM9C,IAAcC,EAAe,GAE7BM,IAAYa,GACf,OAAwC,EACvC,OAAOS,EAAmB;EAAE,GAAGC;EAAO;CAAY,GAAG/C,CAAmB,EAC1E,IACA,CAACiB,CAAW,CACd;CAEA,OAAO+B,EAIL;EACA,UAAUgB;EACV;EACA,SAAS,MAASxD,GAAM;EACxB,cAAc;CAChB,CAAC;AACH;AAEA,SAAgByD,IAAwB;CACtC,OAAOjB,EAIL;EACA,UAAUkB;EACV,YAAY,EAAE,YAAS,gBAAa;GAClC,IAAIC;GACJ,OAAOrB,EAAmBC,GAAO9C,CAAmB;EACtD;EACA,SAAS,MAASO,GAAM;EACxB,cAAc;CAChB,CAAC;AACH;AAEA,SAAgB4D,IAAwB;CACtC,OAAOpB,EAAkE;EACvE,UAAUqB;EACV,YAAY,OAAa,EAAE,IAAIF,EAAQ;EACvC,SAAS,MAAS3D,GAAM;EACxB,cAAc;CAChB,CAAC;AACH"}
|
|
@@ -11,11 +11,10 @@ export interface ToolApprovalFilter {
|
|
|
11
11
|
mine?: boolean;
|
|
12
12
|
}
|
|
13
13
|
export interface ToolApprovalListOptions {
|
|
14
|
-
/** Page size; the inbox raises it to load more. */
|
|
15
|
-
limit?: number;
|
|
16
14
|
/** When false the query is not sent and the result stays empty. */
|
|
17
15
|
enabled?: boolean;
|
|
18
16
|
}
|
|
17
|
+
/** Rows per page; the service accepts at most 100 (BOFF-18147). */
|
|
19
18
|
export declare const TOOL_APPROVALS_PAGE_SIZE = 50;
|
|
20
19
|
/** The filter input the service takes; empty values are left out. */
|
|
21
20
|
export declare function toFilterInput(filter: ToolApprovalFilter): Record<string, unknown>;
|
|
@@ -63,12 +62,18 @@ export interface ToolApprovalRecord {
|
|
|
63
62
|
/** Set for calls that always go to a person (password, payment, one-time code, external message). */
|
|
64
63
|
fixedDefault?: string | null;
|
|
65
64
|
}
|
|
66
|
-
/**
|
|
65
|
+
/**
|
|
66
|
+
* Tool approval requests in the workspace, newest first, one page at a time.
|
|
67
|
+
* `loadMore` appends the next page; `hasMore` is the server's continuation.
|
|
68
|
+
*/
|
|
67
69
|
export declare function useToolApprovals(filter: ToolApprovalFilter, options?: ToolApprovalListOptions): {
|
|
68
70
|
data: ToolApprovalRecord[];
|
|
69
71
|
loading: boolean;
|
|
72
|
+
loadingMore: boolean;
|
|
73
|
+
hasMore: boolean;
|
|
70
74
|
error: Error | undefined;
|
|
71
75
|
refetch: () => Promise<void>;
|
|
76
|
+
loadMore: () => Promise<void>;
|
|
72
77
|
};
|
|
73
78
|
/** Approve or deny a pending tool call. */
|
|
74
79
|
export declare function useDecideToolApproval(): {
|