@burdenoff/microfe-botmanor 2026.1203.2 → 2026.1203.4
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/BotmanorRootInner.js +38 -41
- package/dist/botlit/BotmanorRootInner.js.map +1 -1
- package/dist/botlit/components/DashboardUsagePanel.js +2 -2
- package/dist/botlit/components/DashboardUsagePanel.js.map +1 -1
- package/dist/botlit/providers/WorkspaceFlagScope.d.ts +7 -0
- package/dist/botlit/providers/WorkspaceFlagScope.js +17 -0
- package/dist/botlit/providers/WorkspaceFlagScope.js.map +1 -0
- package/dist/botlit/providers/workspaceFlagKeys.d.ts +18 -0
- package/dist/botlit/providers/workspaceFlagKeys.js +8 -0
- package/dist/botlit/providers/workspaceFlagKeys.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -1
- package/dist/utils/pageContext.d.ts +50 -0
- package/dist/utils/pageContext.js +191 -0
- package/dist/utils/pageContext.js.map +1 -0
- package/package.json +1 -1
|
@@ -1,71 +1,68 @@
|
|
|
1
1
|
import { BotlitProvider as e } from "./providers/BotlitProvider.js";
|
|
2
2
|
import { QuotaGuard as t } from "./providers/QuotaGuard.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
3
|
+
import { WorkspaceFlagScope as n } from "./providers/WorkspaceFlagScope.js";
|
|
4
|
+
import { BotlitRoutes as r } from "./BotlitRoutes.js";
|
|
5
|
+
import { RouteLoader as i } from "./components/RouteLoader.js";
|
|
6
|
+
import { useTr as a } from "../shared/hooks/useTr.js";
|
|
7
|
+
import { WorkspaceRequired as o } from "./components/WorkspaceRequired.js";
|
|
8
|
+
import { ConfirmActionBridge as s } from "./utils/confirmAction.js";
|
|
9
|
+
import { BOTMANOR_TOUR_PRODUCT_ID as c, botmanorTourRoutes as l } from "./tours/tourRoutes.js";
|
|
10
|
+
import { useEffect as u, useState as d } from "react";
|
|
11
|
+
import { jsx as f, jsxs as p } from "react/jsx-runtime";
|
|
12
|
+
import { useGatewayClient as m } from "@burdenoff/fe-libs/shared/graphql";
|
|
13
|
+
import { ApolloProvider as h } from "@apollo/client/react";
|
|
14
|
+
import { QueryClient as g, QueryClientProvider as _ } from "@tanstack/react-query";
|
|
15
|
+
import { registerTourRouteCatalog as v } from "@burdenoff/fe-libs/shared/tours";
|
|
16
|
+
import { ErrorBoundary as y } from "@burdenoff/fe-libs/shared/components";
|
|
17
17
|
// src/botlit/BotmanorRootInner.tsx
|
|
18
|
-
var b = 1e4, x = 2e3, S = new
|
|
18
|
+
var b = 1e4, x = 2e3, S = new g({ defaultOptions: { queries: {
|
|
19
19
|
staleTime: 3e5,
|
|
20
20
|
retry: 1
|
|
21
|
-
} } }), C = (
|
|
22
|
-
let C =
|
|
23
|
-
if (
|
|
21
|
+
} } }), C = (g) => {
|
|
22
|
+
let C = a(), w = m("workspace"), T = !!w, [E, D] = d(!1), [O, k] = d(!1);
|
|
23
|
+
if (u(() => v(c, l(g.basePath)), [g.basePath]), u(() => {
|
|
24
24
|
if (T) return;
|
|
25
25
|
let e = setTimeout(() => {
|
|
26
26
|
D(!0);
|
|
27
27
|
}, b);
|
|
28
28
|
return () => clearTimeout(e);
|
|
29
|
-
}, [T]),
|
|
30
|
-
if (
|
|
29
|
+
}, [T]), u(() => {
|
|
30
|
+
if (g.workspaceId) return;
|
|
31
31
|
let e = setTimeout(() => k(!0), x);
|
|
32
32
|
return () => clearTimeout(e);
|
|
33
|
-
}, [
|
|
34
|
-
basePath:
|
|
35
|
-
navigate:
|
|
36
|
-
}) : /* @__PURE__ */
|
|
37
|
-
if (!T) return E ? /* @__PURE__ */
|
|
33
|
+
}, [g.workspaceId]), !g.workspaceId) return O ? /* @__PURE__ */ f(o, {
|
|
34
|
+
basePath: g.basePath,
|
|
35
|
+
navigate: g.navigate
|
|
36
|
+
}) : /* @__PURE__ */ f(i, { label: C("botlit.root.loadingWorkspace", "Loading your workspace…") });
|
|
37
|
+
if (!T) return E ? /* @__PURE__ */ f("div", {
|
|
38
38
|
className: "flex h-full min-h-[200px] w-full items-center justify-center p-6",
|
|
39
|
-
children: /* @__PURE__ */
|
|
39
|
+
children: /* @__PURE__ */ p("div", {
|
|
40
40
|
className: "text-center",
|
|
41
|
-
children: [/* @__PURE__ */
|
|
41
|
+
children: [/* @__PURE__ */ f("p", {
|
|
42
42
|
className: "mb-4 text-sm text-text-secondary",
|
|
43
43
|
children: C("botlit.root.connectError", "BotManor could not connect to the gateway. Please refresh the page or check your configuration.")
|
|
44
|
-
}), /* @__PURE__ */
|
|
44
|
+
}), /* @__PURE__ */ f("button", {
|
|
45
45
|
type: "button",
|
|
46
46
|
onClick: () => window.location.reload(),
|
|
47
47
|
className: "rounded-md bg-action-primary-bg px-4 py-2 text-sm font-medium text-action-primary-text transition-colors hover:bg-action-primary-bg-hover",
|
|
48
48
|
children: C("botlit.root.reload", "Reload Page")
|
|
49
49
|
})]
|
|
50
50
|
})
|
|
51
|
-
}) : /* @__PURE__ */
|
|
52
|
-
let A = !!
|
|
53
|
-
...
|
|
54
|
-
children: /* @__PURE__ */
|
|
51
|
+
}) : /* @__PURE__ */ f(i, {});
|
|
52
|
+
let A = !!g.basePath, j = /* @__PURE__ */ f(e, {
|
|
53
|
+
...g,
|
|
54
|
+
children: /* @__PURE__ */ f(t, { children: /* @__PURE__ */ f(r, {}) })
|
|
55
55
|
});
|
|
56
|
-
return /* @__PURE__ */
|
|
57
|
-
fallback: /* @__PURE__ */
|
|
56
|
+
return /* @__PURE__ */ p(y, {
|
|
57
|
+
fallback: /* @__PURE__ */ f("div", {
|
|
58
58
|
className: "p-6 text-center text-text-secondary",
|
|
59
59
|
children: C("botlit.root.loadFailed", "Something went wrong loading BotManor. Please refresh the page.")
|
|
60
60
|
}),
|
|
61
|
-
children: [/* @__PURE__ */
|
|
62
|
-
workspaceId:
|
|
63
|
-
|
|
64
|
-
flagKeys: ["botmanor.stewards"],
|
|
65
|
-
defaultEnabled: !0,
|
|
66
|
-
children: /* @__PURE__ */ d(g, {
|
|
61
|
+
children: [/* @__PURE__ */ f(s, {}), /* @__PURE__ */ f(n, {
|
|
62
|
+
workspaceId: g.workspaceId,
|
|
63
|
+
children: /* @__PURE__ */ f(_, {
|
|
67
64
|
client: S,
|
|
68
|
-
children: A ? j : /* @__PURE__ */
|
|
65
|
+
children: A ? j : /* @__PURE__ */ f(h, {
|
|
69
66
|
client: w,
|
|
70
67
|
children: j
|
|
71
68
|
})
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BotmanorRootInner.js","names":["CLIENT_READY_TIMEOUT_MS","WORKSPACE_SETTLE_MS","queryClient","QueryClient","BotmanorRootInner","tr","useTr","workspaceClient","useGatewayClient","clientReady","clientTimedOut","setClientTimedOut","useState","workspaceSettled","setWorkspaceSettled","useEffect","registerTourRouteCatalog","BOTMANOR_TOUR_PRODUCT_ID","botmanorTourRoutes","props","timer","WorkspaceRequired","RouteLoader","isIntegrated","content","BotlitProvider","QuotaGuard","BotlitRoutes","ErrorBoundary","ConfirmActionBridge","
|
|
1
|
+
{"version":3,"file":"BotmanorRootInner.js","names":["CLIENT_READY_TIMEOUT_MS","WORKSPACE_SETTLE_MS","queryClient","QueryClient","BotmanorRootInner","tr","useTr","workspaceClient","useGatewayClient","clientReady","clientTimedOut","setClientTimedOut","useState","workspaceSettled","setWorkspaceSettled","useEffect","registerTourRouteCatalog","BOTMANOR_TOUR_PRODUCT_ID","botmanorTourRoutes","props","timer","WorkspaceRequired","RouteLoader","isIntegrated","content","BotlitProvider","QuotaGuard","BotlitRoutes","ErrorBoundary","ConfirmActionBridge","WorkspaceFlagScope","QueryClientProvider","ApolloProvider"],"sources":["../../src/botlit/BotmanorRootInner.tsx"],"sourcesContent":["/**\n * BotManor Root — implementation\n * @module botlit\n *\n * Product pages live behind this lazy boundary. Workflow routes and SDK\n * lifecycle are owned by the app-shell WorkflowsRoot, shared with every host.\n */\n\nimport type { FC } from 'react';\nimport { useEffect, useState } from 'react';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\nimport { ApolloProvider } from '@apollo/client/react';\nimport { ErrorBoundary } from '@burdenoff/fe-libs/shared/components';\nimport { BotlitProvider } from './providers/BotlitProvider';\nimport { QuotaGuard } from './providers/QuotaGuard';\nimport { WorkspaceFlagScope } from './providers/WorkspaceFlagScope';\nimport { BotlitRoutes } from './BotlitRoutes';\nimport { RouteLoader } from './components/RouteLoader';\nimport { useTr } from '../shared/hooks/useTr';\nimport { WorkspaceRequired } from './components/WorkspaceRequired';\nimport { ConfirmActionBridge } from './utils/confirmAction';\nimport type { BotmanorRootProps } from './types';\n\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { registerTourRouteCatalog } from '@burdenoff/fe-libs/shared/tours';\nimport { BOTMANOR_TOUR_PRODUCT_ID, botmanorTourRoutes } from './tours/tourRoutes';\n\n/** How long to wait for the shell's gateway clients before showing an error. */\nconst CLIENT_READY_TIMEOUT_MS = 10_000;\n\n/**\n * How long to keep showing the loading skeleton before concluding that the\n * shell really has no active workspace.\n *\n * The shell resolves org/workspace asynchronously and passes `workspaceId=\"\"`\n * until it lands, which is indistinguishable from \"this user has no\n * workspace\". Without this settle window the guided zero state would flash on\n * every cold load — a get-started screen appearing and vanishing reads as a\n * broken page, which is exactly what this component exists to avoid.\n */\nconst WORKSPACE_SETTLE_MS = 2_000;\n\n// Create a query client for this microfrontend\nconst queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 5 * 60 * 1000,\n retry: 1,\n },\n },\n});\n\nexport const BotmanorRootInner: FC<BotmanorRootProps> = (props) => {\n // NOTE: Navigation is now handled by the shell's NavRegistration.tsx\n // The shell manages all product submenu items in a centralized way\n\n // Product operations use the shell's authenticated workspace gateway client.\n const tr = useTr();\n const workspaceClient = useGatewayClient('workspace');\n const clientReady = Boolean(workspaceClient);\n const [clientTimedOut, setClientTimedOut] = useState(false);\n const [workspaceSettled, setWorkspaceSettled] = useState(false);\n\n // Name each BotManor screen for product tours (BOFF-15482). Without this the\n // shell resolves every screen under the mount path to one pageId.\n useEffect(\n () => registerTourRouteCatalog(BOTMANOR_TOUR_PRODUCT_ID, botmanorTourRoutes(props.basePath)),\n [props.basePath]\n );\n\n // Timeout fallback: if gateway clients are never provided (test env, shell\n // misconfiguration, auth failure before hydration), show an error rather than\n // spinning indefinitely.\n useEffect(() => {\n if (clientReady) return;\n const timer = setTimeout(() => {\n setClientTimedOut(true);\n }, CLIENT_READY_TIMEOUT_MS);\n return () => clearTimeout(timer);\n }, [clientReady]);\n\n // Give the shell a bounded window to resolve the active workspace before the\n // guided zero state is allowed to render. Cancelled the moment a workspace\n // arrives — a workspace that is already present never starts the timer.\n useEffect(() => {\n if (props.workspaceId) return;\n const timer = setTimeout(() => setWorkspaceSettled(true), WORKSPACE_SETTLE_MS);\n return () => clearTimeout(timer);\n }, [props.workspaceId]);\n\n // Without a workspace every BotManor query is unscoped and every write is\n // rejected — guide the user instead of rendering empty lists. Until the\n // settle window elapses we cannot tell \"still resolving\" from \"none\", so we\n // keep the same skeleton the shell was already showing.\n if (!props.workspaceId) {\n if (!workspaceSettled) {\n return <RouteLoader label={tr('botlit.root.loadingWorkspace', 'Loading your workspace…')} />;\n }\n return <WorkspaceRequired basePath={props.basePath} navigate={props.navigate} />;\n }\n\n // Don't render until clients are ready (same pattern as microfe-bigconsole)\n if (!clientReady) {\n if (clientTimedOut) {\n return (\n <div className=\"flex h-full min-h-[200px] w-full items-center justify-center p-6\">\n <div className=\"text-center\">\n <p className=\"mb-4 text-sm text-text-secondary\">\n {tr(\n 'botlit.root.connectError',\n 'BotManor could not connect to the gateway. Please refresh the page or check your configuration.'\n )}\n </p>\n <button\n type=\"button\"\n onClick={() => window.location.reload()}\n className=\"rounded-md bg-action-primary-bg px-4 py-2 text-sm font-medium text-action-primary-text transition-colors hover:bg-action-primary-bg-hover\"\n >\n {tr('botlit.root.reload', 'Reload Page')}\n </button>\n </div>\n </div>\n );\n }\n // Same skeleton as the lazy-chunk fallback, so the content region never\n // switches loading idioms between first paint and the page rendering.\n return <RouteLoader />;\n }\n\n const isIntegrated = !!props.basePath;\n\n const content = (\n <BotlitProvider {...props}>\n {/* Every metered mutation that hits a plan limit opens one translated dialog. */}\n <QuotaGuard>\n <BotlitRoutes />\n </QuotaGuard>\n </BotlitProvider>\n );\n\n return (\n <ErrorBoundary\n fallback={\n <div className=\"p-6 text-center text-text-secondary\">\n {tr(\n 'botlit.root.loadFailed',\n 'Something went wrong loading BotManor. Please refresh the page.'\n )}\n </div>\n }\n >\n {/* Every confirmAction asks through fe-libs' useConfirm (BOFF-16859). */}\n <ConfirmActionBridge />\n {/* One flag evaluation per workspace: reuses the shell's provider when it\n already covers this workspace (BOFF-18147). */}\n <WorkspaceFlagScope workspaceId={props.workspaceId}>\n <QueryClientProvider client={queryClient}>\n {isIntegrated ? (\n content\n ) : (\n <ApolloProvider client={workspaceClient}>{content}</ApolloProvider>\n )}\n </QueryClientProvider>\n </WorkspaceFlagScope>\n </ErrorBoundary>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,IAAMA,IAA0B,KAY1BC,IAAsB,KAGtBC,IAAc,IAAIC,EAAY,EAClC,gBAAgB,EACd,SAAS;CACP,WAAW;CACX,OAAO;AACT,EACF,EACF,CAAC,GAEYC,KAA4C,MAAU;CAKjE,IAAMC,IAAKC,EAAM,GACXC,IAAkBC,EAAiB,WAAW,GAC9CC,IAAc,EAAQF,GACtB,CAACG,GAAgBC,KAAqBC,EAAS,EAAK,GACpD,CAACC,GAAkBC,KAAuBF,EAAS,EAAK;CAiC9D,IA7BAG,QACQC,EAAyBC,GAA0BC,EAAmBC,EAAM,QAAQ,CAAC,GAC3F,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A,kBAACY,GAAD;IAAqB,QAAQ7B;IAC1B,UAAAqB,IACCC,IAEA,kBAACQ,GAAD;KAAgB,QAAQzB;KAAkB,UAAAiB;IAAwB,CAAA;GAEjD,CAAA;EACH,CAAA,CACP;;AAEnB"}
|
|
@@ -103,13 +103,13 @@ var N = ({ label: e, value: t, icon: i, hint: a }) => /* @__PURE__ */ b("li", {
|
|
|
103
103
|
hint: k("botlit.dashboard.usage.failed", "{{count}} failed", { count: h(R.failureCount) })
|
|
104
104
|
}),
|
|
105
105
|
/* @__PURE__ */ b(N, {
|
|
106
|
-
label: k("botlit.dashboard.usage.
|
|
106
|
+
label: k("botlit.dashboard.usage.byoCost", "BYO provider spend"),
|
|
107
107
|
value: I.loading || R.totalCost === null ? "—" : p(R.totalCost),
|
|
108
108
|
icon: /* @__PURE__ */ b(E, {
|
|
109
109
|
className: "h-5 w-5",
|
|
110
110
|
"aria-hidden": "true"
|
|
111
111
|
}),
|
|
112
|
-
hint: k("botlit.dashboard.usage.
|
|
112
|
+
hint: k("botlit.dashboard.usage.byoCostHint", "{{count}} tokens · informational (billed by your provider; platform AI credits are metered separately)", { count: g(R.totalTokens) })
|
|
113
113
|
}),
|
|
114
114
|
/* @__PURE__ */ b(N, {
|
|
115
115
|
label: k("botlit.dashboard.usage.avgLatency", "Avg latency"),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DashboardUsagePanel.js","names":["_Fragment","Fragment$1","TOP_AGENTS","HEALTH_WARN_RATE","healthOf","finishedRuns","successRate","topAgents","rows","row","b","a","limit","Kpi","Card","CardContent","icon","label","hint","value","DashboardUsagePanel","t","useTr","useBotlit","days","setDays","useState","daily","useDailyUsageStats","agents","DailyUsageDimension","DailyUsageInterval","totals","useMemo","sumUsage","byDay","index","windowDays","date","maxRuns","day","leaders","health","healthLabel","ErrorState","formatNumber","Activity","formatRate","CheckCircle2","formatCurrency","DollarSign","formatTokens","formatDuration","Timer","CardHeader","CardTitle","runs","failed","height","failedShare","AlertTriangle","Link","getPath","Trophy"],"sources":["../../../src/botlit/components/DashboardUsagePanel.tsx"],"sourcesContent":["/**\n * Dashboard usage panel (BOFF-15360 package E).\n * @module botlit/components\n *\n * Workspace runs, success rate, cost and latency over the last 7 or 30 days,\n * a per-day run chart, the busiest agents and a health summary. Every number\n * comes from `getDailyUsageStats`, counted by the service over the whole\n * window — never from rows the browser loaded.\n */\n\nimport { useMemo, useState, type FC, type ReactNode } from 'react';\nimport { Link } from 'react-router';\nimport { Activity, AlertTriangle, CheckCircle2, DollarSign, Timer, Trophy } from 'lucide-react';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { useBotlit } from '../providers/BotlitProvider';\nimport { Card, CardContent, CardHeader, CardTitle } from './Card';\nimport { ErrorState } from './ErrorState';\nimport {\n DailyUsageDimension,\n DailyUsageInterval,\n sumUsage,\n useDailyUsageStats,\n windowDays,\n type DailyUsageRecord,\n} from '../hooks/useUsageStats';\nimport { formatRate } from './RunStatsCard';\nimport {\n formatCurrency,\n formatDuration,\n formatNumber,\n formatTokens,\n MISSING_VALUE,\n} from '../utils/formatters';\n\nconst TOP_AGENTS = 5;\n/** Below this success rate over finished runs the workspace is flagged. */\nconst HEALTH_WARN_RATE = 0.9;\n\ntype Health = 'idle' | 'healthy' | 'degraded';\n\nexport function healthOf(successRate: number | null, finishedRuns: number): Health {\n if (finishedRuns === 0 || successRate === null) return 'idle';\n return successRate >= HEALTH_WARN_RATE ? 'healthy' : 'degraded';\n}\n\n/** Rank agents by runs over the window (the service already sums the window). */\nexport function topAgents(\n rows: readonly DailyUsageRecord[],\n limit = TOP_AGENTS\n): DailyUsageRecord[] {\n return [...rows]\n .filter((row) => row.agentId)\n .sort((a, b) => b.executionCount - a.executionCount)\n .slice(0, limit);\n}\n\nconst Kpi: FC<{ label: string; value: string; icon: ReactNode; hint?: string }> = ({\n label,\n value,\n icon,\n hint,\n}) => (\n <li>\n <Card treatment=\"metric\">\n <CardContent className=\"pt-6\">\n <div className=\"flex items-center gap-4\">\n <div className=\"rounded-lg bg-[var(--color-accent-soft)] p-3 text-text-primary\">\n {icon}\n </div>\n <div className=\"flex flex-col-reverse\">\n <p className=\"text-sm text-text-secondary\">\n {label}\n {hint ? <span className=\"block text-xs\">{hint}</span> : null}\n </p>\n <p className=\"text-2xl font-bold tabular-nums text-text-primary\">{value}</p>\n </div>\n </div>\n </CardContent>\n </Card>\n </li>\n);\n\nexport const DashboardUsagePanel: FC = () => {\n const t = useTr();\n const { getPath } = useBotlit();\n const [days, setDays] = useState(30);\n\n const daily = useDailyUsageStats({ days });\n const agents = useDailyUsageStats({\n days,\n dimension: DailyUsageDimension.Agent,\n interval: DailyUsageInterval.Window,\n });\n\n const totals = useMemo(() => sumUsage(daily.data), [daily.data]);\n const byDay = useMemo(() => {\n const index = new Map(daily.data.map((row) => [row.date, row]));\n return windowDays(days).map((date) => ({ date, row: index.get(date) }));\n }, [daily.data, days]);\n const maxRuns = Math.max(1, ...byDay.map((day) => day.row?.executionCount ?? 0));\n const leaders = useMemo(() => topAgents(agents.data), [agents.data]);\n const health = healthOf(totals.successRate, totals.successCount + totals.failureCount);\n\n const healthLabel =\n health === 'healthy'\n ? t('botlit.dashboard.usage.health.healthy', 'Healthy')\n : health === 'degraded'\n ? t('botlit.dashboard.usage.health.degraded', 'Needs attention')\n : t('botlit.dashboard.usage.health.idle', 'No finished runs');\n\n return (\n <section\n aria-labelledby=\"botmanor-usage-heading\"\n className=\"space-y-4\"\n data-testid=\"dashboard-usage-panel\"\n >\n <div className=\"flex flex-wrap items-center justify-between gap-2\">\n <h2 id=\"botmanor-usage-heading\" className=\"text-lg font-semibold text-text-primary\">\n {t('botlit.dashboard.usage.title', 'Runs and health')}\n </h2>\n <div\n role=\"group\"\n aria-label={t('botlit.runStats.rangeLabel', 'Period')}\n className=\"flex gap-1\"\n >\n {[7, 30].map((value) => (\n <button\n key={value}\n type=\"button\"\n aria-pressed={days === value}\n onClick={() => setDays(value)}\n className={`rounded-md border px-2 py-1 text-xs transition-colors ${\n days === value\n ? 'border-border-strong bg-accent text-text-primary'\n : 'border-border-seam text-text-secondary hover:border-border-strong'\n }`}\n >\n {value === 7\n ? t('botlit.runStats.range.7d', '7 days')\n : t('botlit.runStats.range.30d', '30 days')}\n </button>\n ))}\n </div>\n </div>\n\n {daily.error ? (\n <ErrorState\n resource={t('botlit.dashboard.usage.resource', 'usage statistics')}\n error={daily.error}\n onRetry={() => void daily.refetch()}\n />\n ) : (\n <>\n <ul className=\"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4\">\n <Kpi\n label={t('botlit.dashboard.usage.runs', 'Runs')}\n value={daily.loading ? MISSING_VALUE : formatNumber(totals.executionCount)}\n icon={<Activity className=\"h-5 w-5\" aria-hidden=\"true\" />}\n hint={\n totals.inProgressCount > 0\n ? t('botlit.dashboard.usage.inProgress', '{{count}} in progress', {\n count: formatNumber(totals.inProgressCount),\n })\n : undefined\n }\n />\n <Kpi\n label={t('botlit.dashboard.usage.successRate', 'Success rate')}\n value={daily.loading ? MISSING_VALUE : formatRate(totals.successRate)}\n icon={<CheckCircle2 className=\"h-5 w-5\" aria-hidden=\"true\" />}\n hint={t('botlit.dashboard.usage.failed', '{{count}} failed', {\n count: formatNumber(totals.failureCount),\n })}\n />\n <Kpi\n label={t('botlit.dashboard.usage.cost', 'Cost')}\n value={\n daily.loading || totals.totalCost === null\n ? MISSING_VALUE\n : formatCurrency(totals.totalCost)\n }\n icon={<DollarSign className=\"h-5 w-5\" aria-hidden=\"true\" />}\n hint={t('botlit.dashboard.usage.tokens', '{{count}} tokens', {\n count: formatTokens(totals.totalTokens),\n })}\n />\n <Kpi\n label={t('botlit.dashboard.usage.avgLatency', 'Avg latency')}\n value={\n daily.loading || totals.avgDurationMs === null\n ? MISSING_VALUE\n : formatDuration(Math.round(totals.avgDurationMs))\n }\n icon={<Timer className=\"h-5 w-5\" aria-hidden=\"true\" />}\n />\n </ul>\n\n <div className=\"grid grid-cols-1 gap-6 lg:grid-cols-3\">\n <Card treatment=\"insight\" className=\"lg:col-span-2\">\n <CardHeader>\n <CardTitle as=\"h3\">\n {t('botlit.dashboard.usage.perDay', 'Runs per day (UTC)')}\n </CardTitle>\n </CardHeader>\n <CardContent>\n <div\n className=\"flex h-32 items-end gap-0.5\"\n role=\"img\"\n aria-label={t(\n 'botlit.dashboard.usage.chartLabel',\n '{{count}} runs over the last {{days}} days',\n { count: formatNumber(totals.executionCount), days: String(days) }\n )}\n >\n {byDay.map(({ date, row }) => {\n const runs = row?.executionCount ?? 0;\n const failed = row?.failureCount ?? 0;\n const height = `${(runs / maxRuns) * 100}%`;\n const failedShare = runs > 0 ? `${(failed / runs) * 100}%` : '0%';\n return (\n <div\n key={date}\n className=\"flex h-full flex-1 flex-col justify-end\"\n title={t(\n 'botlit.dashboard.usage.dayTitle',\n '{{date}}: {{runs}} runs, {{failed}} failed',\n {\n date,\n runs: formatNumber(runs),\n failed: formatNumber(failed),\n }\n )}\n >\n <div\n className=\"flex w-full flex-col overflow-hidden rounded-sm bg-[var(--color-chart-1)]\"\n style={{ height }}\n >\n <div\n className=\"w-full bg-status-error-text\"\n style={{ height: failedShare }}\n />\n </div>\n </div>\n );\n })}\n </div>\n <div className=\"mt-2 flex justify-between text-xs text-text-secondary\">\n <span>{byDay[0]?.date}</span>\n <span>{byDay[byDay.length - 1]?.date}</span>\n </div>\n </CardContent>\n </Card>\n\n <Card treatment=\"insight\">\n <CardHeader>\n <CardTitle as=\"h3\" className=\"flex items-center gap-2\">\n {health === 'degraded' ? (\n <AlertTriangle className=\"h-4 w-4 text-status-error-text\" aria-hidden=\"true\" />\n ) : (\n <CheckCircle2 className=\"h-4 w-4 text-status-success-text\" aria-hidden=\"true\" />\n )}\n {t('botlit.dashboard.usage.healthTitle', 'Health')}\n </CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-2 text-sm\">\n <p className=\"font-medium text-text-primary\" data-testid=\"dashboard-health\">\n {healthLabel}\n </p>\n <p className=\"text-text-secondary\">\n {t(\n 'botlit.dashboard.usage.healthDetail',\n '{{succeeded}} succeeded, {{failed}} failed or timed out, {{open}} in progress.',\n {\n succeeded: formatNumber(totals.successCount),\n failed: formatNumber(totals.failureCount),\n open: formatNumber(totals.inProgressCount),\n }\n )}\n </p>\n <Link\n to={getPath('executions')}\n className=\"inline-block text-text-primary underline underline-offset-2\"\n >\n {t('botlit.dashboard.usage.viewExecutions', 'View executions')}\n </Link>\n </CardContent>\n </Card>\n </div>\n\n <Card treatment=\"insight\">\n <CardHeader>\n <CardTitle as=\"h3\" className=\"flex items-center gap-2\">\n <Trophy className=\"h-4 w-4\" aria-hidden=\"true\" />\n {t('botlit.dashboard.usage.topAgents', 'Top agents')}\n </CardTitle>\n </CardHeader>\n <CardContent>\n {agents.error ? (\n <ErrorState\n resource={t('botlit.dashboard.usage.resourceAgents', 'agent usage')}\n error={agents.error}\n onRetry={() => void agents.refetch()}\n />\n ) : leaders.length === 0 ? (\n <p className=\"text-sm text-text-secondary\">\n {agents.loading\n ? t('botlit.common.loading', 'Loading')\n : t('botlit.dashboard.usage.noAgentRuns', 'No agent runs in this period.')}\n </p>\n ) : (\n <table className=\"w-full text-sm\">\n <thead>\n <tr className=\"text-left text-text-secondary\">\n <th className=\"py-1 font-normal\">\n {t('botlit.dashboard.usage.agent', 'Agent')}\n </th>\n <th className=\"py-1 text-right font-normal\">\n {t('botlit.dashboard.usage.runs', 'Runs')}\n </th>\n <th className=\"py-1 text-right font-normal\">\n {t('botlit.dashboard.usage.successRate', 'Success rate')}\n </th>\n <th className=\"hidden py-1 text-right font-normal sm:table-cell\">\n {t('botlit.dashboard.usage.cost', 'Cost')}\n </th>\n <th className=\"hidden py-1 text-right font-normal sm:table-cell\">\n {t('botlit.dashboard.usage.avgLatency', 'Avg latency')}\n </th>\n </tr>\n </thead>\n <tbody>\n {leaders.map((row) => (\n <tr key={row.agentId} className=\"border-t border-border-seam\">\n <td className=\"py-2\">\n <Link\n to={getPath(`agents/${row.agentId}`)}\n className=\"font-medium text-text-primary hover:underline\"\n >\n {row.agentName ??\n t('botlit.dashboard.usage.deletedAgent', 'Deleted agent')}\n </Link>\n </td>\n <td className=\"py-2 text-right tabular-nums\">\n {formatNumber(row.executionCount)}\n </td>\n <td className=\"py-2 text-right tabular-nums\">\n {formatRate(row.successRate)}\n </td>\n <td className=\"hidden py-2 text-right tabular-nums sm:table-cell\">\n {row.totalCost === null ? MISSING_VALUE : formatCurrency(row.totalCost)}\n </td>\n <td className=\"hidden py-2 text-right tabular-nums sm:table-cell\">\n {row.avgDurationMs === null\n ? MISSING_VALUE\n : formatDuration(Math.round(row.avgDurationMs))}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n )}\n </CardContent>\n </Card>\n </>\n )}\n </section>\n );\n};\n"],"mappings":";;;;;;;;;;;;;AAkCA,IAAME,IAAa,GAEbC,IAAmB;AAIzB,SAAgBC,EAAS,GAA4B,GAA8B;CAEjF,OADIC,MAAiB,KAAKC,MAAgB,OAAa,SAChDA,KAAeH,IAAmB,YAAY;AACvD;AAGA,SAAgBI,EACd,GACA,IAAQL,GACY;CACpB,OAAO,CAAC,GAAGM,CAAI,CAAC,CACb,QAAQ,MAAQC,EAAI,OAAO,CAAC,CAC5B,MAAM,GAAG,MAAMC,EAAE,iBAAiBC,EAAE,cAAc,CAAC,CACnD,MAAM,GAAGC,CAAK;AACnB;AAEA,IAAMC,KAA6E,EACjF,UACA,UACA,SACA,cAEA,kBAAC,MAAD,EAAA,UACE,kBAACC,GAAD;CAAM,WAAU;CACd,UAAA,kBAACC,GAAD;EAAa,WAAU;EACrB,UAAA,kBAAC,OAAD;GAAK,WAAU;GAAf,UAAA,CACE,kBAAC,OAAD;IAAK,WAAU;IACZ,UAAAC;GACE,CAAA,GACL,kBAAC,OAAD;IAAK,WAAU;IAAf,UAAA,CACE,kBAAC,KAAD;KAAG,WAAU;KAAb,UAAA,CACGC,GACAC,IAAO,kBAAC,QAAD;MAAM,WAAU;MAAiB,UAAAA;KAAW,CAAA,IAAI,IACvD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QACX,UAAAwB,EAAapC,EAAI,cAAc;OAC9B,CAAA;OACJ,kBAAC,MAAD;QAAI,WAAU;QACX,UAAAsC,EAAWtC,EAAI,WAAW;OACzB,CAAA;OACJ,kBAAC,MAAD;QAAI,WAAU;QACX,UAAAA,EAAI,cAAc,OAAA,MAAuBwC,EAAexC,EAAI,SAAS;OACpE,CAAA;OACJ,kBAAC,MAAD;QAAI,WAAU;QACX,UAAAA,EAAI,kBAAkB,OAAA,MAEnB2C,EAAe,KAAK,MAAM3C,EAAI,aAAa,CAAC;OAC9C,CAAA;MACF;KAxBK,GAAAA,EAAI,OAwBT,CACL,EACI,CAAA,CACF;IAEE,CAAA,EAAA,CAAA,CACT;;EACN,EAAA,CAAA,CAEG;;AAEb"}
|
|
1
|
+
{"version":3,"file":"DashboardUsagePanel.js","names":["_Fragment","Fragment$1","TOP_AGENTS","HEALTH_WARN_RATE","healthOf","finishedRuns","successRate","topAgents","rows","row","b","a","limit","Kpi","Card","CardContent","icon","label","hint","value","DashboardUsagePanel","t","useTr","useBotlit","days","setDays","useState","daily","useDailyUsageStats","agents","DailyUsageDimension","DailyUsageInterval","totals","useMemo","sumUsage","byDay","index","windowDays","date","maxRuns","day","leaders","health","healthLabel","ErrorState","formatNumber","Activity","formatRate","CheckCircle2","formatCurrency","DollarSign","formatTokens","formatDuration","Timer","CardHeader","CardTitle","runs","failed","height","failedShare","AlertTriangle","Link","getPath","Trophy"],"sources":["../../../src/botlit/components/DashboardUsagePanel.tsx"],"sourcesContent":["/**\n * Dashboard usage panel (BOFF-15360 package E).\n * @module botlit/components\n *\n * Workspace runs, success rate, cost and latency over the last 7 or 30 days,\n * a per-day run chart, the busiest agents and a health summary. Every number\n * comes from `getDailyUsageStats`, counted by the service over the whole\n * window — never from rows the browser loaded.\n */\n\nimport { useMemo, useState, type FC, type ReactNode } from 'react';\nimport { Link } from 'react-router';\nimport { Activity, AlertTriangle, CheckCircle2, DollarSign, Timer, Trophy } from 'lucide-react';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { useBotlit } from '../providers/BotlitProvider';\nimport { Card, CardContent, CardHeader, CardTitle } from './Card';\nimport { ErrorState } from './ErrorState';\nimport {\n DailyUsageDimension,\n DailyUsageInterval,\n sumUsage,\n useDailyUsageStats,\n windowDays,\n type DailyUsageRecord,\n} from '../hooks/useUsageStats';\nimport { formatRate } from './RunStatsCard';\nimport {\n formatCurrency,\n formatDuration,\n formatNumber,\n formatTokens,\n MISSING_VALUE,\n} from '../utils/formatters';\n\nconst TOP_AGENTS = 5;\n/** Below this success rate over finished runs the workspace is flagged. */\nconst HEALTH_WARN_RATE = 0.9;\n\ntype Health = 'idle' | 'healthy' | 'degraded';\n\nexport function healthOf(successRate: number | null, finishedRuns: number): Health {\n if (finishedRuns === 0 || successRate === null) return 'idle';\n return successRate >= HEALTH_WARN_RATE ? 'healthy' : 'degraded';\n}\n\n/** Rank agents by runs over the window (the service already sums the window). */\nexport function topAgents(\n rows: readonly DailyUsageRecord[],\n limit = TOP_AGENTS\n): DailyUsageRecord[] {\n return [...rows]\n .filter((row) => row.agentId)\n .sort((a, b) => b.executionCount - a.executionCount)\n .slice(0, limit);\n}\n\nconst Kpi: FC<{ label: string; value: string; icon: ReactNode; hint?: string }> = ({\n label,\n value,\n icon,\n hint,\n}) => (\n <li>\n <Card treatment=\"metric\">\n <CardContent className=\"pt-6\">\n <div className=\"flex items-center gap-4\">\n <div className=\"rounded-lg bg-[var(--color-accent-soft)] p-3 text-text-primary\">\n {icon}\n </div>\n <div className=\"flex flex-col-reverse\">\n <p className=\"text-sm text-text-secondary\">\n {label}\n {hint ? <span className=\"block text-xs\">{hint}</span> : null}\n </p>\n <p className=\"text-2xl font-bold tabular-nums text-text-primary\">{value}</p>\n </div>\n </div>\n </CardContent>\n </Card>\n </li>\n);\n\nexport const DashboardUsagePanel: FC = () => {\n const t = useTr();\n const { getPath } = useBotlit();\n const [days, setDays] = useState(30);\n\n const daily = useDailyUsageStats({ days });\n const agents = useDailyUsageStats({\n days,\n dimension: DailyUsageDimension.Agent,\n interval: DailyUsageInterval.Window,\n });\n\n const totals = useMemo(() => sumUsage(daily.data), [daily.data]);\n const byDay = useMemo(() => {\n const index = new Map(daily.data.map((row) => [row.date, row]));\n return windowDays(days).map((date) => ({ date, row: index.get(date) }));\n }, [daily.data, days]);\n const maxRuns = Math.max(1, ...byDay.map((day) => day.row?.executionCount ?? 0));\n const leaders = useMemo(() => topAgents(agents.data), [agents.data]);\n const health = healthOf(totals.successRate, totals.successCount + totals.failureCount);\n\n const healthLabel =\n health === 'healthy'\n ? t('botlit.dashboard.usage.health.healthy', 'Healthy')\n : health === 'degraded'\n ? t('botlit.dashboard.usage.health.degraded', 'Needs attention')\n : t('botlit.dashboard.usage.health.idle', 'No finished runs');\n\n return (\n <section\n aria-labelledby=\"botmanor-usage-heading\"\n className=\"space-y-4\"\n data-testid=\"dashboard-usage-panel\"\n >\n <div className=\"flex flex-wrap items-center justify-between gap-2\">\n <h2 id=\"botmanor-usage-heading\" className=\"text-lg font-semibold text-text-primary\">\n {t('botlit.dashboard.usage.title', 'Runs and health')}\n </h2>\n <div\n role=\"group\"\n aria-label={t('botlit.runStats.rangeLabel', 'Period')}\n className=\"flex gap-1\"\n >\n {[7, 30].map((value) => (\n <button\n key={value}\n type=\"button\"\n aria-pressed={days === value}\n onClick={() => setDays(value)}\n className={`rounded-md border px-2 py-1 text-xs transition-colors ${\n days === value\n ? 'border-border-strong bg-accent text-text-primary'\n : 'border-border-seam text-text-secondary hover:border-border-strong'\n }`}\n >\n {value === 7\n ? t('botlit.runStats.range.7d', '7 days')\n : t('botlit.runStats.range.30d', '30 days')}\n </button>\n ))}\n </div>\n </div>\n\n {daily.error ? (\n <ErrorState\n resource={t('botlit.dashboard.usage.resource', 'usage statistics')}\n error={daily.error}\n onRetry={() => void daily.refetch()}\n />\n ) : (\n <>\n <ul className=\"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4\">\n <Kpi\n label={t('botlit.dashboard.usage.runs', 'Runs')}\n value={daily.loading ? MISSING_VALUE : formatNumber(totals.executionCount)}\n icon={<Activity className=\"h-5 w-5\" aria-hidden=\"true\" />}\n hint={\n totals.inProgressCount > 0\n ? t('botlit.dashboard.usage.inProgress', '{{count}} in progress', {\n count: formatNumber(totals.inProgressCount),\n })\n : undefined\n }\n />\n <Kpi\n label={t('botlit.dashboard.usage.successRate', 'Success rate')}\n value={daily.loading ? MISSING_VALUE : formatRate(totals.successRate)}\n icon={<CheckCircle2 className=\"h-5 w-5\" aria-hidden=\"true\" />}\n hint={t('botlit.dashboard.usage.failed', '{{count}} failed', {\n count: formatNumber(totals.failureCount),\n })}\n />\n <Kpi\n label={t('botlit.dashboard.usage.byoCost', 'BYO provider spend')}\n value={\n daily.loading || totals.totalCost === null\n ? MISSING_VALUE\n : formatCurrency(totals.totalCost)\n }\n icon={<DollarSign className=\"h-5 w-5\" aria-hidden=\"true\" />}\n hint={t(\n 'botlit.dashboard.usage.byoCostHint',\n '{{count}} tokens · informational (billed by your provider; platform AI credits are metered separately)',\n {\n count: formatTokens(totals.totalTokens),\n }\n )}\n />\n <Kpi\n label={t('botlit.dashboard.usage.avgLatency', 'Avg latency')}\n value={\n daily.loading || totals.avgDurationMs === null\n ? MISSING_VALUE\n : formatDuration(Math.round(totals.avgDurationMs))\n }\n icon={<Timer className=\"h-5 w-5\" aria-hidden=\"true\" />}\n />\n </ul>\n\n <div className=\"grid grid-cols-1 gap-6 lg:grid-cols-3\">\n <Card treatment=\"insight\" className=\"lg:col-span-2\">\n <CardHeader>\n <CardTitle as=\"h3\">\n {t('botlit.dashboard.usage.perDay', 'Runs per day (UTC)')}\n </CardTitle>\n </CardHeader>\n <CardContent>\n <div\n className=\"flex h-32 items-end gap-0.5\"\n role=\"img\"\n aria-label={t(\n 'botlit.dashboard.usage.chartLabel',\n '{{count}} runs over the last {{days}} days',\n { count: formatNumber(totals.executionCount), days: String(days) }\n )}\n >\n {byDay.map(({ date, row }) => {\n const runs = row?.executionCount ?? 0;\n const failed = row?.failureCount ?? 0;\n const height = `${(runs / maxRuns) * 100}%`;\n const failedShare = runs > 0 ? `${(failed / runs) * 100}%` : '0%';\n return (\n <div\n key={date}\n className=\"flex h-full flex-1 flex-col justify-end\"\n title={t(\n 'botlit.dashboard.usage.dayTitle',\n '{{date}}: {{runs}} runs, {{failed}} failed',\n {\n date,\n runs: formatNumber(runs),\n failed: formatNumber(failed),\n }\n )}\n >\n <div\n className=\"flex w-full flex-col overflow-hidden rounded-sm bg-[var(--color-chart-1)]\"\n style={{ height }}\n >\n <div\n className=\"w-full bg-status-error-text\"\n style={{ height: failedShare }}\n />\n </div>\n </div>\n );\n })}\n </div>\n <div className=\"mt-2 flex justify-between text-xs text-text-secondary\">\n <span>{byDay[0]?.date}</span>\n <span>{byDay[byDay.length - 1]?.date}</span>\n </div>\n </CardContent>\n </Card>\n\n <Card treatment=\"insight\">\n <CardHeader>\n <CardTitle as=\"h3\" className=\"flex items-center gap-2\">\n {health === 'degraded' ? (\n <AlertTriangle className=\"h-4 w-4 text-status-error-text\" aria-hidden=\"true\" />\n ) : (\n <CheckCircle2 className=\"h-4 w-4 text-status-success-text\" aria-hidden=\"true\" />\n )}\n {t('botlit.dashboard.usage.healthTitle', 'Health')}\n </CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-2 text-sm\">\n <p className=\"font-medium text-text-primary\" data-testid=\"dashboard-health\">\n {healthLabel}\n </p>\n <p className=\"text-text-secondary\">\n {t(\n 'botlit.dashboard.usage.healthDetail',\n '{{succeeded}} succeeded, {{failed}} failed or timed out, {{open}} in progress.',\n {\n succeeded: formatNumber(totals.successCount),\n failed: formatNumber(totals.failureCount),\n open: formatNumber(totals.inProgressCount),\n }\n )}\n </p>\n <Link\n to={getPath('executions')}\n className=\"inline-block text-text-primary underline underline-offset-2\"\n >\n {t('botlit.dashboard.usage.viewExecutions', 'View executions')}\n </Link>\n </CardContent>\n </Card>\n </div>\n\n <Card treatment=\"insight\">\n <CardHeader>\n <CardTitle as=\"h3\" className=\"flex items-center gap-2\">\n <Trophy className=\"h-4 w-4\" aria-hidden=\"true\" />\n {t('botlit.dashboard.usage.topAgents', 'Top agents')}\n </CardTitle>\n </CardHeader>\n <CardContent>\n {agents.error ? (\n <ErrorState\n resource={t('botlit.dashboard.usage.resourceAgents', 'agent usage')}\n error={agents.error}\n onRetry={() => void agents.refetch()}\n />\n ) : leaders.length === 0 ? (\n <p className=\"text-sm text-text-secondary\">\n {agents.loading\n ? t('botlit.common.loading', 'Loading')\n : t('botlit.dashboard.usage.noAgentRuns', 'No agent runs in this period.')}\n </p>\n ) : (\n <table className=\"w-full text-sm\">\n <thead>\n <tr className=\"text-left text-text-secondary\">\n <th className=\"py-1 font-normal\">\n {t('botlit.dashboard.usage.agent', 'Agent')}\n </th>\n <th className=\"py-1 text-right font-normal\">\n {t('botlit.dashboard.usage.runs', 'Runs')}\n </th>\n <th className=\"py-1 text-right font-normal\">\n {t('botlit.dashboard.usage.successRate', 'Success rate')}\n </th>\n <th className=\"hidden py-1 text-right font-normal sm:table-cell\">\n {t('botlit.dashboard.usage.cost', 'Cost')}\n </th>\n <th className=\"hidden py-1 text-right font-normal sm:table-cell\">\n {t('botlit.dashboard.usage.avgLatency', 'Avg latency')}\n </th>\n </tr>\n </thead>\n <tbody>\n {leaders.map((row) => (\n <tr key={row.agentId} className=\"border-t border-border-seam\">\n <td className=\"py-2\">\n <Link\n to={getPath(`agents/${row.agentId}`)}\n className=\"font-medium text-text-primary hover:underline\"\n >\n {row.agentName ??\n t('botlit.dashboard.usage.deletedAgent', 'Deleted agent')}\n </Link>\n </td>\n <td className=\"py-2 text-right tabular-nums\">\n {formatNumber(row.executionCount)}\n </td>\n <td className=\"py-2 text-right tabular-nums\">\n {formatRate(row.successRate)}\n </td>\n <td className=\"hidden py-2 text-right tabular-nums sm:table-cell\">\n {row.totalCost === null ? MISSING_VALUE : formatCurrency(row.totalCost)}\n </td>\n <td className=\"hidden py-2 text-right tabular-nums sm:table-cell\">\n {row.avgDurationMs === null\n ? MISSING_VALUE\n : formatDuration(Math.round(row.avgDurationMs))}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n )}\n </CardContent>\n </Card>\n </>\n )}\n </section>\n );\n};\n"],"mappings":";;;;;;;;;;;;;AAkCA,IAAME,IAAa,GAEbC,IAAmB;AAIzB,SAAgBC,EAAS,GAA4B,GAA8B;CAEjF,OADIC,MAAiB,KAAKC,MAAgB,OAAa,SAChDA,KAAeH,IAAmB,YAAY;AACvD;AAGA,SAAgBI,EACd,GACA,IAAQL,GACY;CACpB,OAAO,CAAC,GAAGM,CAAI,CAAC,CACb,QAAQ,MAAQC,EAAI,OAAO,CAAC,CAC5B,MAAM,GAAG,MAAMC,EAAE,iBAAiBC,EAAE,cAAc,CAAC,CACnD,MAAM,GAAGC,CAAK;AACnB;AAEA,IAAMC,KAA6E,EACjF,UACA,UACA,SACA,cAEA,kBAAC,MAAD,EAAA,UACE,kBAACC,GAAD;CAAM,WAAU;CACd,UAAA,kBAACC,GAAD;EAAa,WAAU;EACrB,UAAA,kBAAC,OAAD;GAAK,WAAU;GAAf,UAAA,CACE,kBAAC,OAAD;IAAK,WAAU;IACZ,UAAAC;GACE,CAAA,GACL,kBAAC,OAAD;IAAK,WAAU;IAAf,UAAA,CACE,kBAAC,KAAD;KAAG,WAAU;KAAb,UAAA,CACGC,GACAC,IAAO,kBAAC,QAAD;MAAM,WAAU;MAAiB,UAAAA;KAAW,CAAA,IAAI,IACvD;IACH,CAAA,GAAA,kBAAC,KAAD;KAAG,WAAU;KAAqD,UAAAC;IAAS,CAAA,CACxE;GACF,CAAA,CAAA;;CACM,CAAA;AACT,CAAA,EACJ,CAAA,GAGOC,UAAgC;CAC3C,IAAMC,IAAIC,EAAM,GACV,EAAE,eAAYC,EAAU,GACxB,CAACC,GAAMC,KAAWC,EAAS,EAAE,GAE7BC,IAAQC,EAAmB,EAAE,QAAK,CAAC,GACnCC,IAASD,EAAmB;EAChC;EACA,WAAWE,EAAoB;E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AAa,CAAC;OAC9C,CAAA;MACF;KAxBK,GAAAA,EAAI,OAwBT,CACL,EACI,CAAA,CACF;IAEE,CAAA,EAAA,CAAA,CACT;;EACN,EAAA,CAAA,CAEG;;AAEb"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { FC, ReactNode } from 'react';
|
|
2
|
+
export interface WorkspaceFlagScopeProps {
|
|
3
|
+
/** The page's workspace; empty or null while the shell is still resolving it. */
|
|
4
|
+
workspaceId: string | null | undefined;
|
|
5
|
+
children: ReactNode;
|
|
6
|
+
}
|
|
7
|
+
export declare const WorkspaceFlagScope: FC<WorkspaceFlagScopeProps>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { BOTMANOR_FLAG_KEYS as e, enclosingProviderCoversWorkspace as t } from "./workspaceFlagKeys.js";
|
|
2
|
+
import { Fragment as n, jsx as r } from "react/jsx-runtime";
|
|
3
|
+
import { FeatureFlagProvider as i, useOptionalFeatureFlags as a } from "@burdenoff/fe-libs/shared/feature-flags";
|
|
4
|
+
// src/botlit/providers/WorkspaceFlagScope.tsx
|
|
5
|
+
var o = ({ workspaceId: o, children: s }) => {
|
|
6
|
+
let c = a();
|
|
7
|
+
return t(c?.workspaceId, o) ? /* @__PURE__ */ r(n, { children: s }) : /* @__PURE__ */ r(i, {
|
|
8
|
+
workspaceId: o || null,
|
|
9
|
+
gateway: "global",
|
|
10
|
+
flagKeys: e,
|
|
11
|
+
defaultEnabled: !0,
|
|
12
|
+
children: s
|
|
13
|
+
});
|
|
14
|
+
};
|
|
15
|
+
export { o as WorkspaceFlagScope };
|
|
16
|
+
|
|
17
|
+
//# sourceMappingURL=WorkspaceFlagScope.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"WorkspaceFlagScope.js","names":["_Fragment","WorkspaceFlagScope","enclosing","useOptionalFeatureFlags","enclosingProviderCoversWorkspace","workspaceId","Fragment","FeatureFlagProvider","BOTMANOR_FLAG_KEYS"],"sources":["../../../src/botlit/providers/WorkspaceFlagScope.tsx"],"sourcesContent":["/**\n * Feature flags for BotManor's pages, evaluated once per workspace.\n * @module botlit\n *\n * BotManor's only flag today is `botmanor.stewards`. The BotManor app shell\n * already evaluates every flag for the active workspace in its own\n * FeatureFlagProvider (botmanor-app `WorkspaceFeatureFlags`, BOFF-16146), and\n * this module used to mount a second provider underneath it that asked again\n * for `botmanor.stewards` alone. Every signed-in BotManor page therefore sent\n * `EvaluateFeatureFlags` twice for the same workspace (BOFF-18147).\n *\n * When an enclosing provider already evaluates flags for the same workspace,\n * this scope reuses it and sends nothing. A host that mounts no provider, or\n * one with no workspace or a different workspace, still gets BotManor's own\n * provider, so `useFeatureFlag('botmanor.stewards')` keeps answering for the\n * page's workspace in every host.\n */\n\nimport type { FC, ReactNode } from 'react';\nimport {\n FeatureFlagProvider,\n useOptionalFeatureFlags,\n} from '@burdenoff/fe-libs/shared/feature-flags';\nimport { BOTMANOR_FLAG_KEYS, enclosingProviderCoversWorkspace } from './workspaceFlagKeys';\n\nexport interface WorkspaceFlagScopeProps {\n /** The page's workspace; empty or null while the shell is still resolving it. */\n workspaceId: string | null | undefined;\n children: ReactNode;\n}\n\nexport const WorkspaceFlagScope: FC<WorkspaceFlagScopeProps> = ({ workspaceId, children }) => {\n const enclosing = useOptionalFeatureFlags();\n\n if (enclosingProviderCoversWorkspace(enclosing?.workspaceId, workspaceId)) {\n return <>{children}</>;\n }\n\n return (\n <FeatureFlagProvider\n workspaceId={workspaceId || null}\n gateway=\"global\"\n flagKeys={BOTMANOR_FLAG_KEYS}\n defaultEnabled={true}\n >\n {children}\n </FeatureFlagProvider>\n );\n};\n"],"mappings":";;;;AA+BA,IAAaC,KAAmD,EAAE,gBAAa,kBAAe;CAC5F,IAAMC,IAAYC,EAAwB;CAM1C,OAJIC,EAAiCF,GAAW,aAAaG,CAAW,IAC/D,kBAAAL,GAAA,EAAG,YAAW,CAAA,IAIrB,kBAACO,GAAD;EACE,aAAaF,KAAe;EAC5B,SAAQ;EACR,UAAUG;EACV,gBAAgB;EAEf;CACkB,CAAA;AAEzB"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flag keys and the reuse rule behind WorkspaceFlagScope (BOFF-18147).
|
|
3
|
+
* @module botlit
|
|
4
|
+
*
|
|
5
|
+
* Kept out of the component file so Fast Refresh can preserve the scope's
|
|
6
|
+
* state (react-doctor `only-export-components`).
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* The flags BotManor's pages read. A module constant on purpose: the provider
|
|
10
|
+
* re-runs its fetch whenever this array changes identity, so an inline literal
|
|
11
|
+
* would evaluate the flags again on every render of the module root.
|
|
12
|
+
*/
|
|
13
|
+
export declare const BOTMANOR_FLAG_KEYS: string[];
|
|
14
|
+
/**
|
|
15
|
+
* `true` when the enclosing flag provider already evaluates flags for
|
|
16
|
+
* `workspaceId`, so a nested provider would only repeat its request.
|
|
17
|
+
*/
|
|
18
|
+
export declare function enclosingProviderCoversWorkspace(enclosingWorkspaceId: string | null | undefined, workspaceId: string | null | undefined): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"workspaceFlagKeys.js","names":["BOTMANOR_FLAG_KEYS","enclosingProviderCoversWorkspace","enclosingWorkspaceId","workspaceId"],"sources":["../../../src/botlit/providers/workspaceFlagKeys.ts"],"sourcesContent":["/**\n * Flag keys and the reuse rule behind WorkspaceFlagScope (BOFF-18147).\n * @module botlit\n *\n * Kept out of the component file so Fast Refresh can preserve the scope's\n * state (react-doctor `only-export-components`).\n */\n\n/**\n * The flags BotManor's pages read. A module constant on purpose: the provider\n * re-runs its fetch whenever this array changes identity, so an inline literal\n * would evaluate the flags again on every render of the module root.\n */\nexport const BOTMANOR_FLAG_KEYS: string[] = ['botmanor.stewards'];\n\n/**\n * `true` when the enclosing flag provider already evaluates flags for\n * `workspaceId`, so a nested provider would only repeat its request.\n */\nexport function enclosingProviderCoversWorkspace(\n enclosingWorkspaceId: string | null | undefined,\n workspaceId: string | null | undefined\n): boolean {\n return Boolean(enclosingWorkspaceId) && enclosingWorkspaceId === workspaceId;\n}\n"],"mappings":";AAaA,IAAaA,IAA+B,CAAC,mBAAmB;AAMhE,SAAgBC,EACd,GACA,GACS;CACT,OAAO,EAAQC,KAAyBA,MAAyBC;AACnE"}
|
package/dist/index.d.ts
CHANGED
|
@@ -3,3 +3,4 @@
|
|
|
3
3
|
* @module @burdenoff/microfe-botmanor
|
|
4
4
|
*/
|
|
5
5
|
export * from './botlit';
|
|
6
|
+
export { describeCurrentPage, gatherPageContext, isBotmanorChatRoute, resolveBotmanorEntityContext, type BotmanorEntityContext, type BotmanorEntityType, type BotmanorPageContext, } from './utils/pageContext';
|
package/dist/index.js
CHANGED
|
@@ -10,4 +10,5 @@ import { cn as S } from "./botlit/utils/cn.js";
|
|
|
10
10
|
import { formatDate as C, formatRelativeTime as w } from "./botlit/utils/formatters.js";
|
|
11
11
|
import { BOTMANOR_TOUR_ANCHORS as T, BOTMANOR_TOUR_MODULE_ID as E, BOTMANOR_TOUR_PRODUCT_ID as D, BOTMANOR_TOUR_ROUTES as O, botmanorTourRoutes as k, resolveBotmanorTourPageId as A } from "./botlit/tours/tourRoutes.js";
|
|
12
12
|
import "./botlit/index.js";
|
|
13
|
-
|
|
13
|
+
import { describeCurrentPage as j, gatherPageContext as M, isBotmanorChatRoute as N, resolveBotmanorEntityContext as P } from "./utils/pageContext.js";
|
|
14
|
+
export { T as BOTMANOR_TOUR_ANCHORS, E as BOTMANOR_TOUR_MODULE_ID, D as BOTMANOR_TOUR_PRODUCT_ID, O as BOTMANOR_TOUR_ROUTES, t as BotlitProvider, e as BotmanorRoot, k as botmanorTourRoutes, S as cn, j as describeCurrentPage, C as formatDate, w as formatRelativeTime, M as gatherPageContext, N as isBotmanorChatRoute, P as resolveBotmanorEntityContext, A as resolveBotmanorTourPageId, l as useAgent, u as useAgents, i as useBot, n as useBotlit, r as useBotlitStore, a as useBots, v as useConfigureLLMProvider, d as useCreateAgent, o as useCreateBot, m as useCreateKnowledgeBase, b as useCreateMCPServer, f as useDeleteAgent, s as useDeleteBot, h as useKnowledgeBase, g as useKnowledgeBases, _ as useKnowledgeDocuments, y as useLLMProviders, x as useMCPServers, p as useUpdateAgent, c as useUpdateBot };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BotManor pageContext builder for the shared AI Assistant (BOFF-3788).
|
|
3
|
+
*
|
|
4
|
+
* Emits strictly the agent's allow-listed keys (`currentUrl`, `currentPage`,
|
|
5
|
+
* `entityType`, `entityId`, `platform`, `version`, `viewportSize`). Never
|
|
6
|
+
* emits `activeUrl`, `userAgent`, `timestamp`, or secrets.
|
|
7
|
+
*/
|
|
8
|
+
export type BotmanorEntityType = 'botApp' | 'agent' | 'knowledgeBase' | 'retrievalProfile' | 'mcpConnection' | 'a2aAgent' | 'channelConnector' | 'policy' | 'skill' | 'promptTemplate' | 'execution' | 'bucket' | 'storePackage';
|
|
9
|
+
export type BotmanorEntityContext = {
|
|
10
|
+
entityType: BotmanorEntityType | null;
|
|
11
|
+
entityId: string | null;
|
|
12
|
+
currentPage: string;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Type alias (not interface) so it remains assignable to fe-libs' `PageContext`
|
|
16
|
+
* index signature without TS2322.
|
|
17
|
+
*/
|
|
18
|
+
export type BotmanorPageContext = {
|
|
19
|
+
currentUrl: string;
|
|
20
|
+
currentPage: string;
|
|
21
|
+
entityType?: BotmanorEntityType;
|
|
22
|
+
entityId?: string;
|
|
23
|
+
platform: 'web';
|
|
24
|
+
version: string;
|
|
25
|
+
viewportSize: string;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* True when the user is on BotManor's own agent chat surface, where the
|
|
29
|
+
* floating platform Assistant FAB should stay out of the composer's way.
|
|
30
|
+
*/
|
|
31
|
+
export declare function isBotmanorChatRoute(pathname: string): boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Resolve a BotManor route into its innermost entity (`entityType`, `entityId`)
|
|
34
|
+
* and a concise `currentPage` label. Nested routes resolve the innermost entity
|
|
35
|
+
* (e.g. `/botmanor/bots/:botId/agents/:agentId` -> `agent` / `:agentId`).
|
|
36
|
+
*/
|
|
37
|
+
export declare function resolveBotmanorEntityContext(pathname: string): BotmanorEntityContext;
|
|
38
|
+
/** Human-readable label for the Assistant panel header ("Context: ..."). */
|
|
39
|
+
export declare function describeCurrentPage(pathname?: string): string | null;
|
|
40
|
+
/**
|
|
41
|
+
* Gather the allow-listed `PageContext` sent with every AI Assistant turn.
|
|
42
|
+
* Emits ONLY: `currentUrl`, `currentPage`, optional `entityType` & `entityId`,
|
|
43
|
+
* `platform`, `version`, `viewportSize`.
|
|
44
|
+
*/
|
|
45
|
+
export declare function gatherPageContext(override?: {
|
|
46
|
+
href?: string;
|
|
47
|
+
pathname?: string;
|
|
48
|
+
innerWidth?: number;
|
|
49
|
+
innerHeight?: number;
|
|
50
|
+
}): BotmanorPageContext;
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// src/utils/pageContext.ts
|
|
2
|
+
var e = /* @__PURE__ */ new Set([
|
|
3
|
+
"new",
|
|
4
|
+
"register",
|
|
5
|
+
"routes",
|
|
6
|
+
"approvals",
|
|
7
|
+
"installed",
|
|
8
|
+
"publish"
|
|
9
|
+
]);
|
|
10
|
+
function t(e) {
|
|
11
|
+
try {
|
|
12
|
+
return decodeURIComponent(e);
|
|
13
|
+
} catch {
|
|
14
|
+
return e;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function n(e) {
|
|
18
|
+
let t = e.split(/[?#]/)[0] || "/", n = (t.length > 1 ? t.replace(/\/+$/, "") : t).replace(/^\/(?:botmanor|botlit)(?=\/|$)/, "");
|
|
19
|
+
return n === "" ? "/" : n;
|
|
20
|
+
}
|
|
21
|
+
function r(e) {
|
|
22
|
+
let t = n(e);
|
|
23
|
+
return t === "/chat" || /^\/chat\/[^/]+$/.test(t) || /^\/agents\/[^/]+\/chat$/.test(t) || /^\/bots\/[^/]+\/agents\/[^/]+\/chat$/.test(t);
|
|
24
|
+
}
|
|
25
|
+
function i(r) {
|
|
26
|
+
let i = n(r), a = i.match(/^\/bots\/([^/]+)\/agents\/([^/]+)(?:\/(edit|chat|test))?$/);
|
|
27
|
+
if (a && !e.has(a[2])) {
|
|
28
|
+
let e = t(a[1]), n = t(a[2]), r = a[3];
|
|
29
|
+
return {
|
|
30
|
+
entityType: "agent",
|
|
31
|
+
entityId: n,
|
|
32
|
+
currentPage: `${r === "edit" ? "Edit Bot Agent" : r === "chat" ? "Bot Agent Chat" : "Bot Agent Detail"} (bot:${e})`
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
let o = i.match(/^\/bots\/([^/]+)\/knowledge\/([^/]+)$/);
|
|
36
|
+
if (o && !e.has(o[2])) {
|
|
37
|
+
let e = t(o[1]);
|
|
38
|
+
return {
|
|
39
|
+
entityType: "knowledgeBase",
|
|
40
|
+
entityId: t(o[2]),
|
|
41
|
+
currentPage: `Bot Knowledge Base (bot:${e})`
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
let s = i.match(/^\/store\/package\/(.+)$/);
|
|
45
|
+
if (s && s[1]) return {
|
|
46
|
+
entityType: "storePackage",
|
|
47
|
+
entityId: t(s[1]),
|
|
48
|
+
currentPage: "Store Package Detail"
|
|
49
|
+
};
|
|
50
|
+
for (let { regex: n, entityType: r, pageLabel: a } of [
|
|
51
|
+
{
|
|
52
|
+
regex: /^\/bots\/([^/]+)(?:\/(?:edit|agents|knowledge))?$/,
|
|
53
|
+
entityType: "botApp",
|
|
54
|
+
pageLabel: "Bot Detail"
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
regex: /^\/agents\/([^/]+)(?:\/(?:edit|test|chat))?$/,
|
|
58
|
+
entityType: "agent",
|
|
59
|
+
pageLabel: "Agent Detail"
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
regex: /^\/chat\/([^/]+)$/,
|
|
63
|
+
entityType: "agent",
|
|
64
|
+
pageLabel: "Agent Chat"
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
regex: /^\/knowledge\/([^/]+)$/,
|
|
68
|
+
entityType: "knowledgeBase",
|
|
69
|
+
pageLabel: "Knowledge Base Detail"
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
regex: /^\/retrieval-profiles\/([^/]+)$/,
|
|
73
|
+
entityType: "retrievalProfile",
|
|
74
|
+
pageLabel: "Retrieval Profile Detail"
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
regex: /^\/mcp\/([^/]+)$/,
|
|
78
|
+
entityType: "mcpConnection",
|
|
79
|
+
pageLabel: "MCP Server Detail"
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
regex: /^\/a2a\/([^/]+)$/,
|
|
83
|
+
entityType: "a2aAgent",
|
|
84
|
+
pageLabel: "A2A Agent Detail"
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
regex: /^\/channels\/([^/]+)$/,
|
|
88
|
+
entityType: "channelConnector",
|
|
89
|
+
pageLabel: "Channel Detail"
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
regex: /^\/policies\/([^/]+)$/,
|
|
93
|
+
entityType: "policy",
|
|
94
|
+
pageLabel: "Policy Detail"
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
regex: /^\/skills\/([^/]+)$/,
|
|
98
|
+
entityType: "skill",
|
|
99
|
+
pageLabel: "Skill Detail"
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
regex: /^\/prompt-templates\/([^/]+)$/,
|
|
103
|
+
entityType: "promptTemplate",
|
|
104
|
+
pageLabel: "Prompt Template Detail"
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
regex: /^\/executions\/([^/]+)$/,
|
|
108
|
+
entityType: "execution",
|
|
109
|
+
pageLabel: "Execution Detail"
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
regex: /^\/buckets\/([^/]+)$/,
|
|
113
|
+
entityType: "bucket",
|
|
114
|
+
pageLabel: "Bucket Detail"
|
|
115
|
+
}
|
|
116
|
+
]) {
|
|
117
|
+
let o = i.match(n);
|
|
118
|
+
if (o && o[1] && !e.has(o[1])) return {
|
|
119
|
+
entityType: r,
|
|
120
|
+
entityId: t(o[1]),
|
|
121
|
+
currentPage: a
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
for (let [e, t] of [
|
|
125
|
+
[/^\/$/, "Dashboard"],
|
|
126
|
+
[/^\/bots\/new$/, "New Bot"],
|
|
127
|
+
[/^\/bots$/, "Bots"],
|
|
128
|
+
[/^\/agents\/new$/, "New Agent"],
|
|
129
|
+
[/^\/agents\/approvals$/, "Agent Approvals"],
|
|
130
|
+
[/^\/agents$/, "Agents"],
|
|
131
|
+
[/^\/approvals$/, "Tool Approvals"],
|
|
132
|
+
[/^\/knowledge\/new$/, "New Knowledge Base"],
|
|
133
|
+
[/^\/knowledge$/, "Knowledge Bases"],
|
|
134
|
+
[/^\/retrieval-profiles\/new$/, "New Retrieval Profile"],
|
|
135
|
+
[/^\/retrieval-profiles$/, "Retrieval Profiles"],
|
|
136
|
+
[/^\/mcp\/new$/, "New MCP Server"],
|
|
137
|
+
[/^\/mcp$/, "MCP Servers"],
|
|
138
|
+
[/^\/a2a\/register$/, "Register A2A Agent"],
|
|
139
|
+
[/^\/a2a$/, "A2A Registry"],
|
|
140
|
+
[/^\/channels\/new$/, "New Channel"],
|
|
141
|
+
[/^\/channels\/routes$/, "Channel Routes"],
|
|
142
|
+
[/^\/channels$/, "Channels"],
|
|
143
|
+
[/^\/policies\/new$/, "New Policy"],
|
|
144
|
+
[/^\/policies$/, "Policies"],
|
|
145
|
+
[/^\/skills\/new$/, "New Skill"],
|
|
146
|
+
[/^\/skills$/, "Skills"],
|
|
147
|
+
[/^\/prompt-templates\/new$/, "New Prompt Template"],
|
|
148
|
+
[/^\/prompt-templates$/, "Prompt Templates"],
|
|
149
|
+
[/^\/prompts$/, "Prompt Studio"],
|
|
150
|
+
[/^\/executions$/, "Executions"],
|
|
151
|
+
[/^\/ai$/, "AI Operations"],
|
|
152
|
+
[/^\/handoffs$/, "Human Handoffs"],
|
|
153
|
+
[/^\/buckets\/new$/, "New Bucket"],
|
|
154
|
+
[/^\/buckets$/, "Buckets"],
|
|
155
|
+
[/^\/store\/installed$/, "Installed Packages"],
|
|
156
|
+
[/^\/store\/publish$/, "Publish to Store"],
|
|
157
|
+
[/^\/store$/, "Store"],
|
|
158
|
+
[/^\/chat$/, "Bot Chat"],
|
|
159
|
+
[/^\/settings$/, "BotManor Settings"]
|
|
160
|
+
]) if (e.test(i)) return {
|
|
161
|
+
entityType: null,
|
|
162
|
+
entityId: null,
|
|
163
|
+
currentPage: t
|
|
164
|
+
};
|
|
165
|
+
return {
|
|
166
|
+
entityType: null,
|
|
167
|
+
entityId: null,
|
|
168
|
+
currentPage: "BotManor"
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function a(e) {
|
|
172
|
+
let t = e ?? (typeof window < "u" ? window.location.pathname : null);
|
|
173
|
+
return t ? i(t).currentPage : null;
|
|
174
|
+
}
|
|
175
|
+
function o(e) {
|
|
176
|
+
let t = e?.pathname ?? (typeof window < "u" ? window.location.pathname : "/"), n = e?.href ?? (typeof window < "u" ? window.location.href : ""), r = `${e?.innerWidth ?? (typeof window < "u" ? window.innerWidth : 0)}x${e?.innerHeight ?? (typeof window < "u" ? window.innerHeight : 0)}`, a = i(t);
|
|
177
|
+
return {
|
|
178
|
+
currentUrl: n,
|
|
179
|
+
currentPage: a.currentPage,
|
|
180
|
+
...a.entityType && a.entityId ? {
|
|
181
|
+
entityType: a.entityType,
|
|
182
|
+
entityId: a.entityId
|
|
183
|
+
} : {},
|
|
184
|
+
platform: "web",
|
|
185
|
+
version: "1.0.0",
|
|
186
|
+
viewportSize: r
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
export { a as describeCurrentPage, o as gatherPageContext, r as isBotmanorChatRoute, i as resolveBotmanorEntityContext };
|
|
190
|
+
|
|
191
|
+
//# sourceMappingURL=pageContext.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pageContext.js","names":["RESERVED_SEGMENTS","decodeSegment","raw","stripProductPrefix","clean","pathname","stripped","isBotmanorChatRoute","sub","resolveBotmanorEntityContext","botAgentMatch","botId","agentId","leaf","botKbMatch","storePkgMatch","match","regex","pageLabel","pattern","label","describeCurrentPage","path","gatherPageContext","override","currentUrl","viewportSize","resolved"],"sources":["../../src/utils/pageContext.ts"],"sourcesContent":["/**\n * BotManor pageContext builder for the shared AI Assistant (BOFF-3788).\n *\n * Emits strictly the agent's allow-listed keys (`currentUrl`, `currentPage`,\n * `entityType`, `entityId`, `platform`, `version`, `viewportSize`). Never\n * emits `activeUrl`, `userAgent`, `timestamp`, or secrets.\n */\n\nexport type BotmanorEntityType =\n | 'botApp'\n | 'agent'\n | 'knowledgeBase'\n | 'retrievalProfile'\n | 'mcpConnection'\n | 'a2aAgent'\n | 'channelConnector'\n | 'policy'\n | 'skill'\n | 'promptTemplate'\n | 'execution'\n | 'bucket'\n | 'storePackage';\n\nexport type BotmanorEntityContext = {\n entityType: BotmanorEntityType | null;\n entityId: string | null;\n currentPage: string;\n};\n\n/**\n * Type alias (not interface) so it remains assignable to fe-libs' `PageContext`\n * index signature without TS2322.\n */\nexport type BotmanorPageContext = {\n currentUrl: string;\n currentPage: string;\n entityType?: BotmanorEntityType;\n entityId?: string;\n platform: 'web';\n version: string;\n viewportSize: string;\n};\n\nconst RESERVED_SEGMENTS = new Set([\n 'new',\n 'register',\n 'routes',\n 'approvals',\n 'installed',\n 'publish',\n]);\n\nfunction decodeSegment(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n}\n\n/**\n * Strip the `/botmanor` or legacy `/botlit` mount prefix and normalize trailing slashes.\n */\nfunction stripProductPrefix(pathname: string): string {\n const clean = pathname.split(/[?#]/)[0] || '/';\n const withoutTrailing = clean.length > 1 ? clean.replace(/\\/+$/, '') : clean;\n const stripped = withoutTrailing.replace(/^\\/(?:botmanor|botlit)(?=\\/|$)/, '');\n return stripped === '' ? '/' : stripped;\n}\n\n/**\n * True when the user is on BotManor's own agent chat surface, where the\n * floating platform Assistant FAB should stay out of the composer's way.\n */\nexport function isBotmanorChatRoute(pathname: string): boolean {\n const sub = stripProductPrefix(pathname);\n return (\n sub === '/chat' ||\n /^\\/chat\\/[^/]+$/.test(sub) ||\n /^\\/agents\\/[^/]+\\/chat$/.test(sub) ||\n /^\\/bots\\/[^/]+\\/agents\\/[^/]+\\/chat$/.test(sub)\n );\n}\n\n/**\n * Resolve a BotManor route into its innermost entity (`entityType`, `entityId`)\n * and a concise `currentPage` label. Nested routes resolve the innermost entity\n * (e.g. `/botmanor/bots/:botId/agents/:agentId` -> `agent` / `:agentId`).\n */\nexport function resolveBotmanorEntityContext(pathname: string): BotmanorEntityContext {\n const sub = stripProductPrefix(pathname);\n\n // Nested routes first so innermost entity always wins.\n const botAgentMatch = sub.match(/^\\/bots\\/([^/]+)\\/agents\\/([^/]+)(?:\\/(edit|chat|test))?$/);\n if (botAgentMatch && !RESERVED_SEGMENTS.has(botAgentMatch[2])) {\n const botId = decodeSegment(botAgentMatch[1]);\n const agentId = decodeSegment(botAgentMatch[2]);\n const leaf = botAgentMatch[3];\n const pageLabel =\n leaf === 'edit' ? 'Edit Bot Agent' : leaf === 'chat' ? 'Bot Agent Chat' : 'Bot Agent Detail';\n return {\n entityType: 'agent',\n entityId: agentId,\n currentPage: `${pageLabel} (bot:${botId})`,\n };\n }\n\n const botKbMatch = sub.match(/^\\/bots\\/([^/]+)\\/knowledge\\/([^/]+)$/);\n if (botKbMatch && !RESERVED_SEGMENTS.has(botKbMatch[2])) {\n const botId = decodeSegment(botKbMatch[1]);\n return {\n entityType: 'knowledgeBase',\n entityId: decodeSegment(botKbMatch[2]),\n currentPage: `Bot Knowledge Base (bot:${botId})`,\n };\n }\n\n const storePkgMatch = sub.match(/^\\/store\\/package\\/(.+)$/);\n if (storePkgMatch && storePkgMatch[1]) {\n return {\n entityType: 'storePackage',\n entityId: decodeSegment(storePkgMatch[1]),\n currentPage: 'Store Package Detail',\n };\n }\n\n const directPatterns: ReadonlyArray<{\n regex: RegExp;\n entityType: BotmanorEntityType;\n pageLabel: string;\n }> = [\n {\n regex: /^\\/bots\\/([^/]+)(?:\\/(?:edit|agents|knowledge))?$/,\n entityType: 'botApp',\n pageLabel: 'Bot Detail',\n },\n {\n regex: /^\\/agents\\/([^/]+)(?:\\/(?:edit|test|chat))?$/,\n entityType: 'agent',\n pageLabel: 'Agent Detail',\n },\n { regex: /^\\/chat\\/([^/]+)$/, entityType: 'agent', pageLabel: 'Agent Chat' },\n {\n regex: /^\\/knowledge\\/([^/]+)$/,\n entityType: 'knowledgeBase',\n pageLabel: 'Knowledge Base Detail',\n },\n {\n regex: /^\\/retrieval-profiles\\/([^/]+)$/,\n entityType: 'retrievalProfile',\n pageLabel: 'Retrieval Profile Detail',\n },\n { regex: /^\\/mcp\\/([^/]+)$/, entityType: 'mcpConnection', pageLabel: 'MCP Server Detail' },\n { regex: /^\\/a2a\\/([^/]+)$/, entityType: 'a2aAgent', pageLabel: 'A2A Agent Detail' },\n { regex: /^\\/channels\\/([^/]+)$/, entityType: 'channelConnector', pageLabel: 'Channel Detail' },\n { regex: /^\\/policies\\/([^/]+)$/, entityType: 'policy', pageLabel: 'Policy Detail' },\n { regex: /^\\/skills\\/([^/]+)$/, entityType: 'skill', pageLabel: 'Skill Detail' },\n {\n regex: /^\\/prompt-templates\\/([^/]+)$/,\n entityType: 'promptTemplate',\n pageLabel: 'Prompt Template Detail',\n },\n { regex: /^\\/executions\\/([^/]+)$/, entityType: 'execution', pageLabel: 'Execution Detail' },\n { regex: /^\\/buckets\\/([^/]+)$/, entityType: 'bucket', pageLabel: 'Bucket Detail' },\n ];\n\n for (const { regex, entityType, pageLabel } of directPatterns) {\n const match = sub.match(regex);\n if (match && match[1] && !RESERVED_SEGMENTS.has(match[1])) {\n return {\n entityType,\n entityId: decodeSegment(match[1]),\n currentPage: pageLabel,\n };\n }\n }\n\n const staticPages: ReadonlyArray<[RegExp, string]> = [\n [/^\\/$/, 'Dashboard'],\n [/^\\/bots\\/new$/, 'New Bot'],\n [/^\\/bots$/, 'Bots'],\n [/^\\/agents\\/new$/, 'New Agent'],\n [/^\\/agents\\/approvals$/, 'Agent Approvals'],\n [/^\\/agents$/, 'Agents'],\n [/^\\/approvals$/, 'Tool Approvals'],\n [/^\\/knowledge\\/new$/, 'New Knowledge Base'],\n [/^\\/knowledge$/, 'Knowledge Bases'],\n [/^\\/retrieval-profiles\\/new$/, 'New Retrieval Profile'],\n [/^\\/retrieval-profiles$/, 'Retrieval Profiles'],\n [/^\\/mcp\\/new$/, 'New MCP Server'],\n [/^\\/mcp$/, 'MCP Servers'],\n [/^\\/a2a\\/register$/, 'Register A2A Agent'],\n [/^\\/a2a$/, 'A2A Registry'],\n [/^\\/channels\\/new$/, 'New Channel'],\n [/^\\/channels\\/routes$/, 'Channel Routes'],\n [/^\\/channels$/, 'Channels'],\n [/^\\/policies\\/new$/, 'New Policy'],\n [/^\\/policies$/, 'Policies'],\n [/^\\/skills\\/new$/, 'New Skill'],\n [/^\\/skills$/, 'Skills'],\n [/^\\/prompt-templates\\/new$/, 'New Prompt Template'],\n [/^\\/prompt-templates$/, 'Prompt Templates'],\n [/^\\/prompts$/, 'Prompt Studio'],\n [/^\\/executions$/, 'Executions'],\n [/^\\/ai$/, 'AI Operations'],\n [/^\\/handoffs$/, 'Human Handoffs'],\n [/^\\/buckets\\/new$/, 'New Bucket'],\n [/^\\/buckets$/, 'Buckets'],\n [/^\\/store\\/installed$/, 'Installed Packages'],\n [/^\\/store\\/publish$/, 'Publish to Store'],\n [/^\\/store$/, 'Store'],\n [/^\\/chat$/, 'Bot Chat'],\n [/^\\/settings$/, 'BotManor Settings'],\n ];\n\n for (const [pattern, label] of staticPages) {\n if (pattern.test(sub)) {\n return { entityType: null, entityId: null, currentPage: label };\n }\n }\n\n return { entityType: null, entityId: null, currentPage: 'BotManor' };\n}\n\n/** Human-readable label for the Assistant panel header (\"Context: ...\"). */\nexport function describeCurrentPage(pathname?: string): string | null {\n const path = pathname ?? (typeof window !== 'undefined' ? window.location.pathname : null);\n if (!path) return null;\n return resolveBotmanorEntityContext(path).currentPage;\n}\n\n/**\n * Gather the allow-listed `PageContext` sent with every AI Assistant turn.\n * Emits ONLY: `currentUrl`, `currentPage`, optional `entityType` & `entityId`,\n * `platform`, `version`, `viewportSize`.\n */\nexport function gatherPageContext(override?: {\n href?: string;\n pathname?: string;\n innerWidth?: number;\n innerHeight?: number;\n}): BotmanorPageContext {\n const pathname =\n override?.pathname ?? (typeof window !== 'undefined' ? window.location.pathname : '/');\n const currentUrl = override?.href ?? (typeof window !== 'undefined' ? window.location.href : '');\n const width = override?.innerWidth ?? (typeof window !== 'undefined' ? window.innerWidth : 0);\n const height = override?.innerHeight ?? (typeof window !== 'undefined' ? window.innerHeight : 0);\n const viewportSize = `${width}x${height}`;\n const resolved = resolveBotmanorEntityContext(pathname);\n\n return {\n currentUrl,\n currentPage: resolved.currentPage,\n ...(resolved.entityType && resolved.entityId\n ? { entityType: resolved.entityType, entityId: resolved.entityId }\n : {}),\n platform: 'web',\n version: '1.0.0',\n viewportSize,\n };\n}\n"],"mappings":";AA2CA,IAAMA,oBAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAASC,EAAc,GAAqB;CAC1C,IAAI;EACF,OAAO,mBAAmBC,CAAG;CAC/B,QAAQ;EACN,OAAOA;CACT;AACF;AAKA,SAASC,EAAmB,GAA0B;CACpD,IAAMC,IAAQC,EAAS,MAAM,MAAM,CAAC,CAAC,MAAM,KAErCC,KADkBF,EAAM,SAAS,IAAIA,EAAM,QAAQ,QAAQ,EAAE,IAAIA,EAAA,CACtC,QAAQ,kCAAk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