@burdenoff/microfe-botmanor 2026.1123.2 → 2026.1123.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/hooks/internal/workspaceGateway.d.ts +6 -8
- package/dist/botlit/hooks/internal/workspaceGateway.js +32 -27
- package/dist/botlit/hooks/internal/workspaceGateway.js.map +1 -1
- package/dist/botlit/hooks/useBots.js +64 -62
- package/dist/botlit/hooks/useBots.js.map +1 -1
- package/dist/botlit/hooks/useLLMProviders.js +1 -0
- package/dist/botlit/hooks/useLLMProviders.js.map +1 -1
- package/dist/botlit/hooks/useMCPServers.js +5 -1
- package/dist/botlit/hooks/useMCPServers.js.map +1 -1
- package/dist/generated/wspace-operations.d.ts +96 -0
- package/dist/generated/wspace-operations.js +146 -116
- package/dist/generated/wspace-operations.js.map +1 -1
- package/dist/generated/wspace-types.d.ts +22716 -1548
- package/dist/generated/wspace-types.js.map +1 -1
- package/package.json +1 -1
|
@@ -14,14 +14,10 @@ export interface QueryResult<T> {
|
|
|
14
14
|
export interface PaginatedQueryResult<T> extends QueryResult<T> {
|
|
15
15
|
/** True while the next page is being appended. */
|
|
16
16
|
loadingMore: boolean;
|
|
17
|
-
/**
|
|
18
|
-
* True when the most recent page came back full, i.e. another page may
|
|
19
|
-
* exist. False before the first page resolves and once a short page
|
|
20
|
-
* (or an empty one) marks the end of the list.
|
|
21
|
-
*/
|
|
17
|
+
/** True when the latest page has a continuation. */
|
|
22
18
|
hasMore: boolean;
|
|
23
19
|
/**
|
|
24
|
-
* Fetches the next page
|
|
20
|
+
* Fetches the next page at its continuation offset and appends it.
|
|
25
21
|
* No-op while a fetch is in flight or when `hasMore` is false.
|
|
26
22
|
*/
|
|
27
23
|
loadMore: () => Promise<void>;
|
|
@@ -64,6 +60,8 @@ export interface WorkspacePaginatedQueryOptions<TData, TRow, TResult> {
|
|
|
64
60
|
pageSize: number;
|
|
65
61
|
/** Extracts the raw row list from a page payload; missing data yields []. */
|
|
66
62
|
extractRows: (data: TData | undefined) => TRow[] | undefined;
|
|
63
|
+
/** Server continuation for envelope APIs. Null marks the final page. */
|
|
64
|
+
extractNextOffset?: (data: TData | undefined) => number | null;
|
|
67
65
|
/** Projects the ACCUMULATED raw rows onto the record shape the UI consumes. */
|
|
68
66
|
select: (rows: TRow[]) => TResult;
|
|
69
67
|
/** Value held while disabled or before the first successful read. */
|
|
@@ -77,8 +75,8 @@ export interface WorkspacePaginatedQueryOptions<TData, TRow, TResult> {
|
|
|
77
75
|
* Offset-paginated variant of `useWorkspaceQuery` for unbounded lists.
|
|
78
76
|
*
|
|
79
77
|
* `refetch()` restarts at offset 0 and REPLACES the accumulated rows;
|
|
80
|
-
* `loadMore()` fetches the next page and appends it.
|
|
81
|
-
*
|
|
78
|
+
* `loadMore()` fetches the next page and appends it. Envelope APIs set the
|
|
79
|
+
* continuation explicitly. On legacy array APIs a short page ends the list.
|
|
82
80
|
* `select` runs over the accumulated raw rows, so client-side narrowing
|
|
83
81
|
* (e.g. executions search) sees every loaded page, not just the last one.
|
|
84
82
|
*/
|
|
@@ -58,11 +58,13 @@ function f(e) {
|
|
|
58
58
|
}
|
|
59
59
|
var p = [];
|
|
60
60
|
function m(e) {
|
|
61
|
-
let { document: t, variables: i, pageSize: s, enabled: l, errorMessage: f } = e, m = c(), h = d(e.select), g = d(e.extractRows),
|
|
62
|
-
|
|
63
|
-
}, [h]),
|
|
64
|
-
|
|
65
|
-
|
|
61
|
+
let { document: t, variables: i, pageSize: s, enabled: l, errorMessage: f } = e, m = c(), h = d(e.select), g = d(e.extractRows), _ = d(e.extractNextOffset), [v, y] = o([]), b = a([]), [x, S] = o(e.fallback), [C, w] = o(!1), [T, E] = o(!1), [D, O] = o(null), k = a(null), A = a(!1), [j, M] = o(), N = a(0), P = n((e) => {
|
|
62
|
+
b.current = e, y(e), S(h.current(e));
|
|
63
|
+
}, [h]), F = n(async (e, n) => {
|
|
64
|
+
if (n && A.current) return;
|
|
65
|
+
A.current = !0;
|
|
66
|
+
let r = n ? N.current : ++N.current, a = () => r === N.current;
|
|
67
|
+
n ? E(!0) : (w(!0), E(!1)), M(void 0);
|
|
66
68
|
try {
|
|
67
69
|
let r = await m.query({
|
|
68
70
|
query: t,
|
|
@@ -78,12 +80,13 @@ function m(e) {
|
|
|
78
80
|
if (!a()) return;
|
|
79
81
|
let o = r.error;
|
|
80
82
|
if (o != null) throw u(o, f);
|
|
81
|
-
let c =
|
|
82
|
-
|
|
83
|
+
let c = r.data ?? void 0, l = g.current(c) ?? [], d = _.current, p = d ? d(c) : l.length < s ? null : e + l.length;
|
|
84
|
+
if (p !== null && (!Number.isSafeInteger(p) || p <= e)) throw Error(f);
|
|
85
|
+
P(n ? [...b.current, ...l] : l), k.current = p, O(p);
|
|
83
86
|
} catch (e) {
|
|
84
|
-
a() &&
|
|
87
|
+
a() && M(u(e, f));
|
|
85
88
|
} finally {
|
|
86
|
-
a() && (n ?
|
|
89
|
+
a() && (A.current = !1, n ? E(!1) : w(!1));
|
|
87
90
|
}
|
|
88
91
|
}, [
|
|
89
92
|
m,
|
|
@@ -92,30 +95,32 @@ function m(e) {
|
|
|
92
95
|
s,
|
|
93
96
|
f,
|
|
94
97
|
g,
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
+
_,
|
|
99
|
+
P
|
|
100
|
+
]), I = n(async () => {
|
|
101
|
+
l ? await F(0, !1) : (++N.current, A.current = !1, P(p), w(!1), E(!1), k.current = null, O(null), M(void 0));
|
|
98
102
|
}, [
|
|
99
103
|
l,
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
]),
|
|
103
|
-
l && !
|
|
104
|
+
F,
|
|
105
|
+
P
|
|
106
|
+
]), L = n(async () => {
|
|
107
|
+
l && !C && D !== null && D === k.current && await F(D, !0);
|
|
104
108
|
}, [
|
|
105
109
|
l,
|
|
106
|
-
|
|
107
|
-
|
|
110
|
+
C,
|
|
111
|
+
D,
|
|
112
|
+
F
|
|
108
113
|
]);
|
|
109
114
|
return r(() => {
|
|
110
|
-
|
|
111
|
-
}, [
|
|
112
|
-
data:
|
|
113
|
-
loading:
|
|
114
|
-
loadingMore:
|
|
115
|
-
hasMore:
|
|
116
|
-
error:
|
|
117
|
-
refetch:
|
|
118
|
-
loadMore:
|
|
115
|
+
I();
|
|
116
|
+
}, [I]), {
|
|
117
|
+
data: x,
|
|
118
|
+
loading: C,
|
|
119
|
+
loadingMore: T,
|
|
120
|
+
hasMore: D !== null,
|
|
121
|
+
error: j,
|
|
122
|
+
refetch: I,
|
|
123
|
+
loadMore: L
|
|
119
124
|
};
|
|
120
125
|
}
|
|
121
126
|
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","rows","setRows","rowsRef","loadingMore","setLoadingMore","exhausted","setExhausted","generationRef","replaceRows","next","fetchPage","generation","append","isCurrent","pageSize","pageRows","loadMore","useWorkspaceAllPagesQuery","hasMore","useWorkspaceMutation","variablesRef","state","setState","input","selected","mutationError","failure"],"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 while the next page is being appended. */\n loadingMore: boolean;\n /**\n * True when the most recent page came back full, i.e. another page may\n * exist. False before the first page resolves and once a short page\n * (or an empty one) marks the end of the list.\n */\n hasMore: boolean;\n /**\n * Fetches the next page (current row count as 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 */\nfunction 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 /** 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. A page that returns\n * fewer rows than `pageSize` marks the list exhausted (`hasMore` false).\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\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 [exhausted, setExhausted] = useState(true);\n const [error, setError] = useState<Error | undefined>();\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 const generation = append ? generationRef.current : ++generationRef.current;\n const isCurrent = () => generation === generationRef.current;\n if (append) 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 setError(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 pageRows = extractRowsRef.current(result.data ?? undefined) ?? [];\n replaceRows(append ? [...rowsRef.current, ...pageRows] : pageRows);\n setExhausted(pageRows.length < pageSize);\n } catch (queryError) {\n if (isCurrent()) setError(toError(queryError, errorMessage));\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 if (append) setLoadingMore(false);\n else setLoading(false);\n }\n }\n },\n [client, document, variables, pageSize, errorMessage, extractRowsRef, replaceRows]\n );\n\n const refetch = useCallback(async () => {\n if (!enabled) {\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 setExhausted(true);\n setError(undefined);\n return;\n }\n await fetchPage(0, false);\n }, [enabled, fetchPage, replaceRows]);\n\n const loadMore = useCallback(async () => {\n if (!enabled || exhausted) return;\n await fetchPage(rowsRef.current.length, true);\n }, [enabled, exhausted, fetchPage]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, loadingMore, hasMore: !exhausted, error, refetch, loadMore };\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;AA2CA,SAASC,EAAQ,GAAgB,GAAgC;CAC/D,IAAMC,IAAUC,EAA6BC,CAAK;CAOlD,OANIF,IAGS,MAAMA,GAAS,EAAE,SAAM,CAAC,IAEjCE,aAAiB,QAAcA,IACxB,MAAMC,GAAiB,EAAE,SAAM,CAAC;AAC7C;AAGA,SAASC,EAAa,GAAmC;CACvD,IAAMC,IAAMC,EAAOC,CAAK;CAIxB,OAHAC,QAAsB;EACpB,EAAI,UAAUD;CAChB,GAAG,CAACA,CAAK,CAAC,GACHF;AACT;AAsBA,SAAgBI,EACd,GACsB;CACtB,IAAM,EAAE,aAAU,cAAW,YAAS,oBAAiBC,GACjDC,IAAShB,EAAmB,GAC5BiB,IAAYR,EAAUM,EAAQ,MAAM,GACpCG,IAAcT,EAAUM,EAAQ,QAAQ,GAExC,CAACI,GAAMC,KAAWC,EAAkBN,EAAQ,QAAQ,GACpD,CAACO,GAASC,KAAcF,EAAS,EAAK,GACtC,CAACG,GAAOC,KAAYJ,EAA4B,GAEhDK,IAAUC,EAAY,YAAY;EACtC,IAAI,CAACC,GAEH,AADAR,EAAQF,EAAY,OAAO,GAC3BO,EAAS,KAAA,CAAS;OAIpB;GACA,AADAF,EAAW,EAAI,GACfE,EAAS,KAAA,CAAS;GAClB,I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AAO,KAAA;GAAU,CAAC,GACtDA;EACT,SAASC,GAAe;GACtB,IAAMC,IAAU7D,EAAQ4D,GAAehC,CAAY;GAEnD,MADA6B,EAAS;IAAE,MAAM,KAAA;IAAW,SAAS;IAAO,OAAOI;GAAQ,CAAC,GACtDA;EACR;CACF,GACA;EAACjD;EAAQc;EAAUE;EAAcf;EAAW0C;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","generationRef","replaceRows","next","fetchPage","append","generation","isCurrent","pageSize","payload","pageRows","extractNextOffset","continuation","offset","loadMore","useWorkspaceAllPagesQuery","hasMore","useWorkspaceMutation","variablesRef","state","setState","input","selected","mutationError","failure"],"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 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 */\nfunction 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 [error, setError] = useState<Error | undefined>();\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 setError(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()) setError(toError(queryError, errorMessage));\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 setError(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 { data, loading, loadingMore, hasMore: nextOffset !== null, error, refetch, loadMore };\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;AAuCA,SAASC,EAAQ,GAAgB,GAAgC;CAC/D,IAAMC,IAAUC,EAA6BC,CAAK;CAOlD,OANIF,IAGS,MAAMA,GAAS,EAAE,SAAM,CAAC,IAEjCE,aAAiB,QAAcA,IACxB,MAAMC,GAAiB,EAAE,SAAM,CAAC;AAC7C;AAGA,SAASC,EAAa,GAAmC;CACvD,IAAMC,IAAMC,EAAOC,CAAK;CAIxB,OAHAC,QAAsB;EACpB,EAAI,UAAUD;CAChB,GAAG,CAACA,CAAK,CAAC,GACHF;AACT;AAsBA,SAAgBI,EAC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-1,11 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
1
|
+
import { ListBotAppsPageDocument as e } from "../../generated/wspace-operations.js";
|
|
2
|
+
import { useBotlit as t } from "../providers/BotlitProvider.js";
|
|
3
|
+
import { buildMutationInput as n, fieldsOf as r } from "./internal/mutationInput.js";
|
|
4
|
+
import { useWorkspaceAllPagesQuery as i, useWorkspacePaginatedQuery as a, useWorkspaceQuery as o } from "./internal/workspaceGateway.js";
|
|
5
|
+
import { useCallback as s, useEffect as c, useMemo as l, useState as u } from "react";
|
|
6
|
+
import { gql as d } from "@apollo/client";
|
|
7
|
+
import { useGatewayClient as f } from "@burdenoff/fe-libs/shared/graphql";
|
|
7
8
|
// src/botlit/hooks/useBots.ts
|
|
8
|
-
var
|
|
9
|
+
var p = d`
|
|
9
10
|
query ListBotApps($filters: BotAppFilterInput, $pagination: PaginationInput) {
|
|
10
11
|
listBotApps(filters: $filters, pagination: $pagination) {
|
|
11
12
|
id
|
|
@@ -32,7 +33,7 @@ var f = u`
|
|
|
32
33
|
workspaceId
|
|
33
34
|
}
|
|
34
35
|
}
|
|
35
|
-
`,
|
|
36
|
+
`, m = d`
|
|
36
37
|
query GetBotApp($id: ID!) {
|
|
37
38
|
getBotApp(id: $id) {
|
|
38
39
|
id
|
|
@@ -59,7 +60,7 @@ var f = u`
|
|
|
59
60
|
workspaceId
|
|
60
61
|
}
|
|
61
62
|
}
|
|
62
|
-
`,
|
|
63
|
+
`, h = d`
|
|
63
64
|
mutation CreateBotApp($input: CreateBotAppInput!) {
|
|
64
65
|
createBotApp(input: $input) {
|
|
65
66
|
id
|
|
@@ -80,7 +81,7 @@ var f = u`
|
|
|
80
81
|
workspaceId
|
|
81
82
|
}
|
|
82
83
|
}
|
|
83
|
-
`,
|
|
84
|
+
`, g = d`
|
|
84
85
|
mutation UpdateBotApp($id: ID!, $input: UpdateBotAppInput!) {
|
|
85
86
|
updateBotApp(id: $id, input: $input) {
|
|
86
87
|
id
|
|
@@ -103,11 +104,11 @@ var f = u`
|
|
|
103
104
|
workspaceId
|
|
104
105
|
}
|
|
105
106
|
}
|
|
106
|
-
`,
|
|
107
|
+
`, _ = d`
|
|
107
108
|
mutation DeleteBotApp($id: ID!) {
|
|
108
109
|
deleteBotApp(id: $id)
|
|
109
110
|
}
|
|
110
|
-
`,
|
|
111
|
+
`, v = 100, y = [], b = r({
|
|
111
112
|
bucketId: !0,
|
|
112
113
|
context: !0,
|
|
113
114
|
defaultAgentId: !0,
|
|
@@ -126,10 +127,10 @@ var f = u`
|
|
|
126
127
|
welcomeMessage: !0,
|
|
127
128
|
workflowId: !0
|
|
128
129
|
});
|
|
129
|
-
function
|
|
130
|
+
function x(e) {
|
|
130
131
|
return e;
|
|
131
132
|
}
|
|
132
|
-
function
|
|
133
|
+
function S(e, t) {
|
|
133
134
|
if (e || t) return {
|
|
134
135
|
workspaceId: e,
|
|
135
136
|
search: t?.search,
|
|
@@ -138,33 +139,34 @@ function x(e, t) {
|
|
|
138
139
|
bucketId: t?.bucketId
|
|
139
140
|
};
|
|
140
141
|
}
|
|
141
|
-
function
|
|
142
|
-
let { workspaceId:
|
|
143
|
-
return
|
|
144
|
-
document:
|
|
145
|
-
variables:
|
|
146
|
-
pageSize:
|
|
147
|
-
extractRows: (e) => e?.
|
|
142
|
+
function C(n) {
|
|
143
|
+
let { workspaceId: r } = t(), i = l(() => ({ filters: S(r, n) }), [n, r]);
|
|
144
|
+
return a({
|
|
145
|
+
document: e,
|
|
146
|
+
variables: i,
|
|
147
|
+
pageSize: v,
|
|
148
|
+
extractRows: (e) => e?.listBotAppsPage.items ?? [],
|
|
149
|
+
extractNextOffset: (e) => e?.listBotAppsPage.nextOffset ?? null,
|
|
148
150
|
select: (e) => e,
|
|
149
|
-
fallback:
|
|
150
|
-
enabled: !!
|
|
151
|
+
fallback: y,
|
|
152
|
+
enabled: !!r,
|
|
151
153
|
errorMessage: "Failed to load bots"
|
|
152
154
|
});
|
|
153
155
|
}
|
|
154
|
-
function
|
|
155
|
-
let { workspaceId:
|
|
156
|
-
return
|
|
157
|
-
document:
|
|
156
|
+
function w() {
|
|
157
|
+
let { workspaceId: e } = t(), n = l(() => ({ filters: S(e) }), [e]);
|
|
158
|
+
return i({
|
|
159
|
+
document: p,
|
|
158
160
|
variables: n,
|
|
159
|
-
pageSize:
|
|
161
|
+
pageSize: v,
|
|
160
162
|
extractRows: (e) => e?.listBotApps ?? [],
|
|
161
163
|
select: (e) => e,
|
|
162
|
-
fallback:
|
|
163
|
-
enabled: !!
|
|
164
|
+
fallback: y,
|
|
165
|
+
enabled: !!e,
|
|
164
166
|
errorMessage: "Failed to load bots"
|
|
165
167
|
});
|
|
166
168
|
}
|
|
167
|
-
var
|
|
169
|
+
var T = d`
|
|
168
170
|
query GetBotAppCounts {
|
|
169
171
|
getBotAppCounts {
|
|
170
172
|
total
|
|
@@ -175,53 +177,53 @@ var w = u`
|
|
|
175
177
|
}
|
|
176
178
|
}
|
|
177
179
|
`;
|
|
178
|
-
function
|
|
179
|
-
let { workspaceId: n } =
|
|
180
|
-
return
|
|
181
|
-
document:
|
|
180
|
+
function E(e = !0) {
|
|
181
|
+
let { workspaceId: n } = t(), r = l(() => ({}), []);
|
|
182
|
+
return o({
|
|
183
|
+
document: T,
|
|
182
184
|
variables: r,
|
|
183
185
|
select: (e) => e?.getBotAppCounts ?? null,
|
|
184
186
|
fallback: null,
|
|
185
|
-
enabled:
|
|
187
|
+
enabled: e && !!n,
|
|
186
188
|
errorMessage: "Failed to load bot counts"
|
|
187
189
|
});
|
|
188
190
|
}
|
|
189
|
-
function
|
|
190
|
-
let t =
|
|
191
|
+
function D(e) {
|
|
192
|
+
let t = x(f("workspace")), [n, r] = u(null), [i, a] = u(!!e), [o, l] = u(), d = s(async () => {
|
|
191
193
|
if (!e) r(null), a(!1);
|
|
192
194
|
else {
|
|
193
|
-
a(!0),
|
|
195
|
+
a(!0), l(void 0);
|
|
194
196
|
try {
|
|
195
197
|
let n = await t.query({
|
|
196
|
-
query:
|
|
198
|
+
query: m,
|
|
197
199
|
variables: { id: e },
|
|
198
200
|
fetchPolicy: "network-only"
|
|
199
201
|
}), i = n.error;
|
|
200
202
|
if (i != null) throw i instanceof Error ? i : /* @__PURE__ */ Error("Failed to load bot");
|
|
201
203
|
r(n.data?.getBotApp ?? null);
|
|
202
204
|
} catch (e) {
|
|
203
|
-
r(null),
|
|
205
|
+
r(null), l(e instanceof Error ? e : /* @__PURE__ */ Error("Failed to load bot"));
|
|
204
206
|
} finally {
|
|
205
207
|
a(!1);
|
|
206
208
|
}
|
|
207
209
|
}
|
|
208
210
|
}, [e, t]);
|
|
209
|
-
return
|
|
210
|
-
|
|
211
|
-
}, [
|
|
211
|
+
return c(() => {
|
|
212
|
+
d();
|
|
213
|
+
}, [d]), {
|
|
212
214
|
data: n,
|
|
213
215
|
loading: i,
|
|
214
|
-
error:
|
|
215
|
-
refetch:
|
|
216
|
+
error: o,
|
|
217
|
+
refetch: d
|
|
216
218
|
};
|
|
217
219
|
}
|
|
218
|
-
function
|
|
219
|
-
let e =
|
|
220
|
+
function O() {
|
|
221
|
+
let e = x(f("workspace")), [t, n] = u({
|
|
220
222
|
data: void 0,
|
|
221
223
|
loading: !1,
|
|
222
224
|
error: void 0
|
|
223
225
|
});
|
|
224
|
-
return [
|
|
226
|
+
return [s(async (t) => {
|
|
225
227
|
n({
|
|
226
228
|
data: void 0,
|
|
227
229
|
loading: !0,
|
|
@@ -229,7 +231,7 @@ function D() {
|
|
|
229
231
|
});
|
|
230
232
|
try {
|
|
231
233
|
let r = (await e.mutate({
|
|
232
|
-
mutation:
|
|
234
|
+
mutation: h,
|
|
233
235
|
variables: { input: t }
|
|
234
236
|
})).data?.createBotApp;
|
|
235
237
|
if (!r) throw Error("Failed to create bot");
|
|
@@ -248,13 +250,13 @@ function D() {
|
|
|
248
250
|
}
|
|
249
251
|
}, [e]), t];
|
|
250
252
|
}
|
|
251
|
-
function
|
|
252
|
-
let e =
|
|
253
|
+
function k() {
|
|
254
|
+
let e = x(f("workspace")), [t, r] = u({
|
|
253
255
|
data: void 0,
|
|
254
256
|
loading: !1,
|
|
255
257
|
error: void 0
|
|
256
258
|
});
|
|
257
|
-
return [
|
|
259
|
+
return [s(async ({ botId: t, input: i }) => {
|
|
258
260
|
r({
|
|
259
261
|
data: void 0,
|
|
260
262
|
loading: !0,
|
|
@@ -262,10 +264,10 @@ function O() {
|
|
|
262
264
|
});
|
|
263
265
|
try {
|
|
264
266
|
let a = (await e.mutate({
|
|
265
|
-
mutation:
|
|
267
|
+
mutation: g,
|
|
266
268
|
variables: {
|
|
267
|
-
id:
|
|
268
|
-
input:
|
|
269
|
+
id: t,
|
|
270
|
+
input: n(i, b)
|
|
269
271
|
}
|
|
270
272
|
})).data?.updateBotApp;
|
|
271
273
|
if (!a) throw Error("Failed to update bot");
|
|
@@ -282,15 +284,15 @@ function O() {
|
|
|
282
284
|
error: t
|
|
283
285
|
}), t;
|
|
284
286
|
}
|
|
285
|
-
}, [e]),
|
|
287
|
+
}, [e]), t];
|
|
286
288
|
}
|
|
287
|
-
function
|
|
288
|
-
let e =
|
|
289
|
+
function A() {
|
|
290
|
+
let e = x(f("workspace")), [t, n] = u({
|
|
289
291
|
data: void 0,
|
|
290
292
|
loading: !1,
|
|
291
293
|
error: void 0
|
|
292
294
|
});
|
|
293
|
-
return [
|
|
295
|
+
return [s(async (t) => {
|
|
294
296
|
n({
|
|
295
297
|
data: void 0,
|
|
296
298
|
loading: !0,
|
|
@@ -298,7 +300,7 @@ function k() {
|
|
|
298
300
|
});
|
|
299
301
|
try {
|
|
300
302
|
let r = (await e.mutate({
|
|
301
|
-
mutation:
|
|
303
|
+
mutation: _,
|
|
302
304
|
variables: { id: t }
|
|
303
305
|
})).data?.deleteBotApp ?? !1;
|
|
304
306
|
return n({
|
|
@@ -316,6 +318,6 @@ function k() {
|
|
|
316
318
|
}
|
|
317
319
|
}, [e]), t];
|
|
318
320
|
}
|
|
319
|
-
export {
|
|
321
|
+
export { w as useAllBots, D as useBot, E as useBotAppCounts, C as useBots, O as useCreateBot, A as useDeleteBot, k as useUpdateBot };
|
|
320
322
|
|
|
321
323
|
//# sourceMappingURL=useBots.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useBots.js","names":["LIST_BOT_APPS_DOCUMENT","GET_BOT_APP_DOCUMENT","CREATE_BOT_APP_DOCUMENT","UPDATE_BOT_APP_DOCUMENT","DELETE_BOT_APP_DOCUMENT","LIST_PAGE_SIZE","NO_BOTS","UPDATE_BOT_APP_FIELDS","fieldsOf","getWorkspaceClient","client","buildBotFilter","workspaceId","filter","useBots","useBotlit","variables","useMemo","useWorkspacePaginatedQuery","data","rows","useAllBots","useWorkspaceAllPagesQuery","GET_BOT_APP_COUNTS_DOCUMENT","useBotAppCounts","useWorkspaceQuery","enabled","useBot","useGatewayClient","setData","useState","loading","setLoading","botId","error","setError","refetch","useCallback","result","operationError","queryError","useEffect","useCreateBot","state","setState","createdBot","mutationError","useUpdateBot","updatedBot","buildMutationInput","input","useDeleteBot","deleted"],"sources":["../../../src/botlit/hooks/useBots.ts"],"sourcesContent":["import { gql, type ApolloClient } from '@apollo/client';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\n\nimport type { UpdateBotAppInput } from '../../generated/wspace-types';\nimport { useBotlit } from '../providers/BotlitProvider';\nimport type { BaseFilter } from '../types';\nimport { buildMutationInput, fieldsOf, type GraphQLInput } from './internal/mutationInput';\nimport {\n useWorkspaceAllPagesQuery,\n useWorkspacePaginatedQuery,\n useWorkspaceQuery,\n type PaginatedQueryResult,\n type QueryResult,\n} from './internal/workspaceGateway';\n\nconst LIST_BOT_APPS_DOCUMENT = gql`\n query ListBotApps($filters: BotAppFilterInput, $pagination: PaginationInput) {\n listBotApps(filters: $filters, pagination: $pagination) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n welcomeMessage\n fallbackMessage\n workflowId\n executionCount\n lastExecutedAt\n tagIds\n tags\n createdAt\n updatedAt\n createdById\n updatedById\n workspaceId\n }\n }\n`;\n\nconst GET_BOT_APP_DOCUMENT = gql`\n query GetBotApp($id: ID!) {\n getBotApp(id: $id) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n welcomeMessage\n fallbackMessage\n workflowId\n executionCount\n lastExecutedAt\n tagIds\n tags\n createdAt\n updatedAt\n createdById\n updatedById\n workspaceId\n }\n }\n`;\n\nconst CREATE_BOT_APP_DOCUMENT = gql`\n mutation CreateBotApp($input: CreateBotAppInput!) {\n createBotApp(input: $input) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n workflowId\n tagIds\n tags\n createdAt\n updatedAt\n workspaceId\n }\n }\n`;\n\nconst UPDATE_BOT_APP_DOCUMENT = gql`\n mutation UpdateBotApp($id: ID!, $input: UpdateBotAppInput!) {\n updateBotApp(id: $id, input: $input) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n welcomeMessage\n fallbackMessage\n workflowId\n tagIds\n tags\n updatedAt\n updatedById\n workspaceId\n }\n }\n`;\n\nconst DELETE_BOT_APP_DOCUMENT = gql`\n mutation DeleteBotApp($id: ID!) {\n deleteBotApp(id: $id)\n }\n`;\n\ntype WorkspaceClient = ApolloClient;\n\nexport interface BotAppRecord {\n id: string;\n name: string;\n slug: string;\n description?: string | null;\n icon?: string | null;\n type: string;\n status: string;\n visibility?: string | null;\n routingStrategy?: string | null;\n defaultAgentId?: string | null;\n welcomeMessage?: string | null;\n fallbackMessage?: string | null;\n /** Bound FluidGrids workflow definition id — the bot's designed behaviour. */\n workflowId?: string | null;\n executionCount?: number | null;\n lastExecutedAt?: string | null;\n tagIds?: string[] | null;\n /** Entity-owned universal tag records (JSON). */\n tags?: unknown;\n createdAt?: string | null;\n updatedAt?: string | null;\n createdById?: string | null;\n updatedById?: string | null;\n workspaceId?: string | null;\n}\n\ninterface ListBotAppsData {\n listBotApps: BotAppRecord[];\n}\n\nconst LIST_PAGE_SIZE = 100;\nconst NO_BOTS: BotAppRecord[] = [];\n\ninterface GetBotAppData {\n getBotApp: BotAppRecord | null;\n}\n\ninterface CreateBotAppData {\n createBotApp: BotAppRecord;\n}\n\ninterface UpdateBotAppData {\n updateBotApp: BotAppRecord;\n}\n\ninterface DeleteBotAppData {\n deleteBotApp: boolean;\n}\n\ninterface BotMutationState<T> {\n data: T | undefined;\n loading: boolean;\n error: Error | undefined;\n}\n\ninterface CreateBotInput {\n workspaceId: string;\n name: string;\n slug?: string;\n type: string;\n routingStrategy?: string;\n visibility?: string;\n description?: string;\n icon?: string;\n}\n\ninterface UpdateBotInput {\n botId: string;\n input: GraphQLInput<UpdateBotAppInput>;\n}\n\nconst UPDATE_BOT_APP_FIELDS = fieldsOf<UpdateBotAppInput>({\n bucketId: true,\n context: true,\n defaultAgentId: true,\n description: true,\n fallbackMessage: true,\n icon: true,\n metadata: true,\n name: true,\n routingStrategy: true,\n slug: true,\n status: true,\n tagIds: true,\n tags: true,\n type: true,\n visibility: true,\n welcomeMessage: true,\n workflowId: true,\n});\n\nfunction getWorkspaceClient(client: unknown): WorkspaceClient {\n return client as WorkspaceClient;\n}\n\nfunction buildBotFilter(\n workspaceId: string | undefined,\n filter?: BaseFilter\n): Record<string, unknown> | undefined {\n if (!workspaceId && !filter) return undefined;\n\n return {\n workspaceId,\n search: filter?.search,\n status: filter?.status?.[0],\n visibility: filter?.visibility?.[0],\n bucketId: filter?.bucketId,\n };\n}\n\nexport const botKeys = {\n all: ['bots'] as const,\n lists: () => [...botKeys.all, 'list'] as const,\n list: (filter?: BaseFilter) => [...botKeys.lists(), filter] as const,\n details: () => [...botKeys.all, 'detail'] as const,\n detail: (id: string) => [...botKeys.details(), id] as const,\n};\n\nexport function useBots(filter?: BaseFilter): PaginatedQueryResult<BotAppRecord[]> {\n const { workspaceId } = useBotlit();\n\n const variables = useMemo(\n () => ({ filters: buildBotFilter(workspaceId, filter) }),\n [filter, workspaceId]\n );\n\n return useWorkspacePaginatedQuery<ListBotAppsData, BotAppRecord, BotAppRecord[]>({\n document: LIST_BOT_APPS_DOCUMENT,\n variables,\n pageSize: LIST_PAGE_SIZE,\n extractRows: (data) => data?.listBotApps ?? [],\n select: (rows) => rows,\n fallback: NO_BOTS,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load bots',\n });\n}\n\n/**\n * Every bot of the workspace, all pages. For pickers that must offer each bot\n * (a route can point at any of them), where `useBots` stops at one page.\n */\nexport function useAllBots(): QueryResult<BotAppRecord[]> {\n const { workspaceId } = useBotlit();\n const variables = useMemo(() => ({ filters: buildBotFilter(workspaceId) }), [workspaceId]);\n\n return useWorkspaceAllPagesQuery<ListBotAppsData, BotAppRecord, BotAppRecord[]>({\n document: LIST_BOT_APPS_DOCUMENT,\n variables,\n pageSize: LIST_PAGE_SIZE,\n extractRows: (data) => data?.listBotApps ?? [],\n select: (rows) => rows,\n fallback: NO_BOTS,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load bots',\n });\n}\n\n/**\n * Exact bot counts by status for the workspace (BOFF-12426). Unlike `useBots`\n * this is not capped at one page, so it is the source for dashboard totals.\n * `total` counts every status; the dashboard shows `total - archived`.\n */\nexport interface BotAppCounts {\n total: number;\n draft: number;\n active: number;\n paused: number;\n archived: number;\n}\n\ninterface BotAppCountsData {\n getBotAppCounts?: BotAppCounts | null;\n}\n\nconst GET_BOT_APP_COUNTS_DOCUMENT = gql`\n query GetBotAppCounts {\n getBotAppCounts {\n total\n draft\n active\n paused\n archived\n }\n }\n`;\n\nexport function useBotAppCounts(enabled = true): QueryResult<BotAppCounts | null> {\n const { workspaceId } = useBotlit();\n const variables = useMemo(() => ({}), []);\n\n return useWorkspaceQuery<BotAppCountsData, BotAppCounts | null>({\n document: GET_BOT_APP_COUNTS_DOCUMENT,\n variables,\n select: (data) => data?.getBotAppCounts ?? null,\n fallback: null,\n enabled: enabled && Boolean(workspaceId),\n errorMessage: 'Failed to load bot counts',\n });\n}\n\nexport function useBot(botId: string | undefined) {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [data, setData] = useState<BotAppRecord | null>(null);\n // Loading from the first render when there is a bot to read, so a page that\n // depends on the bot never acts on \"no bot yet\" for the frame before the read.\n const [loading, setLoading] = useState(Boolean(botId));\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!botId) {\n setData(null);\n setLoading(false);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<GetBotAppData>({\n query: GET_BOT_APP_DOCUMENT,\n variables: { id: botId },\n fetchPolicy: 'network-only',\n });\n // Apollo v4 resolves (not rejects) with `result.error` set on GraphQL errors.\n // Without this a FORBIDDEN read looked like \"bot not found\" (BOFF-12436).\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw operationError instanceof Error ? operationError : new Error('Failed to load bot');\n }\n setData(result.data?.getBotApp ?? null);\n } catch (queryError) {\n setData(null);\n setError(queryError instanceof Error ? queryError : new Error('Failed to load bot'));\n } finally {\n setLoading(false);\n }\n }, [botId, client]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nexport function useCreateBot() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<BotMutationState<BotAppRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const createBot = useCallback(\n async (input: CreateBotInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<CreateBotAppData>({\n mutation: CREATE_BOT_APP_DOCUMENT,\n variables: { input },\n });\n\n const createdBot = result.data?.createBotApp;\n if (!createdBot) {\n throw new Error('Failed to create bot');\n }\n\n setState({ data: createdBot, loading: false, error: undefined });\n return createdBot;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to create bot');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [createBot, state] as const;\n}\n\nexport function useUpdateBot() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<BotMutationState<BotAppRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const updateBot = useCallback(\n async ({ botId, input }: UpdateBotInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<UpdateBotAppData>({\n mutation: UPDATE_BOT_APP_DOCUMENT,\n variables: { id: botId, input: buildMutationInput(input, UPDATE_BOT_APP_FIELDS) },\n });\n\n const updatedBot = result.data?.updateBotApp;\n if (!updatedBot) {\n throw new Error('Failed to update bot');\n }\n\n setState({ data: updatedBot, loading: false, error: undefined });\n return updatedBot;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to update bot');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [updateBot, state] as const;\n}\n\nexport function useDeleteBot() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<BotMutationState<boolean>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const deleteBot = useCallback(\n async (botId: string) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<DeleteBotAppData>({\n mutation: DELETE_BOT_APP_DOCUMENT,\n variables: { id: botId },\n });\n\n const deleted = result.data?.deleteBotApp ?? false;\n setState({ data: deleted, loading: false, error: undefined });\n return deleted;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to delete bot');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [deleteBot, state] as const;\n}\n"],"mappings":";;;;;;;AAgBA,IAAMA,IAAyB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6B5BC,IAAuB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;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AY,SAAS;IAAO,OAAO,KAAA;GAAU,CAAC,GACxDA;EACT,SAASF,GAAe;GACtB,IAAMZ,IACJY,aAAyB,QAAQA,IAAgB,gBAAI,MAAM,sBAAsB;GAEnF,MADAF,EAAS;IAAE,MAAM,KAAA;IAAW,SAAS;IAAO;GAAM,CAAC,GAC7CV;EACR;CACF,GACA,CAACxB,CAAM,CAGD,GAAWiC,CAAK;AAC1B;AAEA,SAAgBQ,IAAe;CAC7B,IAAMzC,IAASD,EAAmBmB,EAAiB,WAAW,CAAC,GACzD,CAACe,GAAOC,KAAYd,EAAoC;EAC5D,MAAM,KAAA;EACN,SAAS;EACT,OAAO,KAAA;CACT,CAAC;CAwBD,OAAO,CAtBWO,EAChB,OAAO,MAAkB;EACvB,EAAS;GAAE,MAAM,KAAA;GAAW,SAAS;GAAM,OAAO,KAAA;EAAU,CAAC;EAC7D,IAAI;GAMF,IAAMe,KAAU,MALK1C,EAAO,OAAyB;IACnD,UAAUN;IACV,WAAW,EAAE,IAAI6B,EAAM;GACzB,CAAC,EAAA,CAEsB,MAAM,gBAAgB;GAE7C,OADAW,EAAS;IAAE,MAAMQ;IAAS,SAAS;IAAO,OAAO,KAAA;GAAU,CAAC,GACrDA;EACT,SAASN,GAAe;GACtB,IAAMZ,IACJY,aAAyB,QAAQA,IAAgB,gBAAI,MAAM,sBAAsB;GAEnF,MADAF,EAAS;IAAE,MAAM,KAAA;IAAW,SAAS;IAAO;GAAM,CAAC,GAC7CV;EACR;CACF,GACA,CAACxB,CAAM,CAGD,GAAWiC,CAAK;AAC1B"}
|
|
1
|
+
{"version":3,"file":"useBots.js","names":["LIST_BOT_APPS_DOCUMENT","GET_BOT_APP_DOCUMENT","CREATE_BOT_APP_DOCUMENT","UPDATE_BOT_APP_DOCUMENT","DELETE_BOT_APP_DOCUMENT","LIST_PAGE_SIZE","NO_BOTS","UPDATE_BOT_APP_FIELDS","fieldsOf","getWorkspaceClient","client","buildBotFilter","workspaceId","filter","useBots","useBotlit","variables","useMemo","useWorkspacePaginatedQuery","ListBotAppsPageDocument","data","rows","useAllBots","useWorkspaceAllPagesQuery","GET_BOT_APP_COUNTS_DOCUMENT","useBotAppCounts","useWorkspaceQuery","enabled","useBot","useGatewayClient","setData","useState","loading","setLoading","botId","error","setError","refetch","useCallback","result","operationError","queryError","useEffect","useCreateBot","state","setState","createdBot","mutationError","useUpdateBot","updatedBot","buildMutationInput","input","useDeleteBot","deleted"],"sources":["../../../src/botlit/hooks/useBots.ts"],"sourcesContent":["import { gql, type ApolloClient } from '@apollo/client';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\n\nimport {\n ListBotAppsPageDocument,\n type ListBotAppsPageQuery,\n} from '../../generated/wspace-operations';\nimport type { UpdateBotAppInput } from '../../generated/wspace-types';\nimport { useBotlit } from '../providers/BotlitProvider';\nimport type { BaseFilter } from '../types';\nimport { buildMutationInput, fieldsOf, type GraphQLInput } from './internal/mutationInput';\nimport {\n useWorkspaceAllPagesQuery,\n useWorkspacePaginatedQuery,\n useWorkspaceQuery,\n type PaginatedQueryResult,\n type QueryResult,\n} from './internal/workspaceGateway';\n\nconst LIST_BOT_APPS_DOCUMENT = gql`\n query ListBotApps($filters: BotAppFilterInput, $pagination: PaginationInput) {\n listBotApps(filters: $filters, pagination: $pagination) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n welcomeMessage\n fallbackMessage\n workflowId\n executionCount\n lastExecutedAt\n tagIds\n tags\n createdAt\n updatedAt\n createdById\n updatedById\n workspaceId\n }\n }\n`;\n\nconst GET_BOT_APP_DOCUMENT = gql`\n query GetBotApp($id: ID!) {\n getBotApp(id: $id) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n welcomeMessage\n fallbackMessage\n workflowId\n executionCount\n lastExecutedAt\n tagIds\n tags\n createdAt\n updatedAt\n createdById\n updatedById\n workspaceId\n }\n }\n`;\n\nconst CREATE_BOT_APP_DOCUMENT = gql`\n mutation CreateBotApp($input: CreateBotAppInput!) {\n createBotApp(input: $input) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n workflowId\n tagIds\n tags\n createdAt\n updatedAt\n workspaceId\n }\n }\n`;\n\nconst UPDATE_BOT_APP_DOCUMENT = gql`\n mutation UpdateBotApp($id: ID!, $input: UpdateBotAppInput!) {\n updateBotApp(id: $id, input: $input) {\n id\n name\n slug\n description\n icon\n type\n status\n visibility\n routingStrategy\n defaultAgentId\n welcomeMessage\n fallbackMessage\n workflowId\n tagIds\n tags\n updatedAt\n updatedById\n workspaceId\n }\n }\n`;\n\nconst DELETE_BOT_APP_DOCUMENT = gql`\n mutation DeleteBotApp($id: ID!) {\n deleteBotApp(id: $id)\n }\n`;\n\ntype WorkspaceClient = ApolloClient;\n\nexport interface BotAppRecord {\n id: string;\n name: string;\n slug: string;\n description?: string | null;\n icon?: string | null;\n type: string;\n status: string;\n visibility?: string | null;\n routingStrategy?: string | null;\n defaultAgentId?: string | null;\n welcomeMessage?: string | null;\n fallbackMessage?: string | null;\n /** Bound FluidGrids workflow definition id — the bot's designed behaviour. */\n workflowId?: string | null;\n executionCount?: number | null;\n lastExecutedAt?: string | null;\n tagIds?: string[] | null;\n /** Entity-owned universal tag records (JSON). */\n tags?: unknown;\n createdAt?: string | null;\n updatedAt?: string | null;\n createdById?: string | null;\n updatedById?: string | null;\n workspaceId?: string | null;\n}\n\ninterface ListBotAppsData {\n listBotApps: BotAppRecord[];\n}\n\nconst LIST_PAGE_SIZE = 100;\nconst NO_BOTS: BotAppRecord[] = [];\n\ninterface GetBotAppData {\n getBotApp: BotAppRecord | null;\n}\n\ninterface CreateBotAppData {\n createBotApp: BotAppRecord;\n}\n\ninterface UpdateBotAppData {\n updateBotApp: BotAppRecord;\n}\n\ninterface DeleteBotAppData {\n deleteBotApp: boolean;\n}\n\ninterface BotMutationState<T> {\n data: T | undefined;\n loading: boolean;\n error: Error | undefined;\n}\n\ninterface CreateBotInput {\n workspaceId: string;\n name: string;\n slug?: string;\n type: string;\n routingStrategy?: string;\n visibility?: string;\n description?: string;\n icon?: string;\n}\n\ninterface UpdateBotInput {\n botId: string;\n input: GraphQLInput<UpdateBotAppInput>;\n}\n\nconst UPDATE_BOT_APP_FIELDS = fieldsOf<UpdateBotAppInput>({\n bucketId: true,\n context: true,\n defaultAgentId: true,\n description: true,\n fallbackMessage: true,\n icon: true,\n metadata: true,\n name: true,\n routingStrategy: true,\n slug: true,\n status: true,\n tagIds: true,\n tags: true,\n type: true,\n visibility: true,\n welcomeMessage: true,\n workflowId: true,\n});\n\nfunction getWorkspaceClient(client: unknown): WorkspaceClient {\n return client as WorkspaceClient;\n}\n\nfunction buildBotFilter(\n workspaceId: string | undefined,\n filter?: BaseFilter\n): Record<string, unknown> | undefined {\n if (!workspaceId && !filter) return undefined;\n\n return {\n workspaceId,\n search: filter?.search,\n status: filter?.status?.[0],\n visibility: filter?.visibility?.[0],\n bucketId: filter?.bucketId,\n };\n}\n\nexport const botKeys = {\n all: ['bots'] as const,\n lists: () => [...botKeys.all, 'list'] as const,\n list: (filter?: BaseFilter) => [...botKeys.lists(), filter] as const,\n details: () => [...botKeys.all, 'detail'] as const,\n detail: (id: string) => [...botKeys.details(), id] as const,\n};\n\nexport function useBots(filter?: BaseFilter): PaginatedQueryResult<BotAppRecord[]> {\n const { workspaceId } = useBotlit();\n\n const variables = useMemo(\n () => ({ filters: buildBotFilter(workspaceId, filter) }),\n [filter, workspaceId]\n );\n\n return useWorkspacePaginatedQuery<ListBotAppsPageQuery, BotAppRecord, BotAppRecord[]>({\n document: ListBotAppsPageDocument,\n variables,\n pageSize: LIST_PAGE_SIZE,\n extractRows: (data) => data?.listBotAppsPage.items ?? [],\n extractNextOffset: (data) => data?.listBotAppsPage.nextOffset ?? null,\n select: (rows) => rows,\n fallback: NO_BOTS,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load bots',\n });\n}\n\n/**\n * Every bot of the workspace, all pages. For pickers that must offer each bot\n * (a route can point at any of them), where `useBots` stops at one page.\n */\nexport function useAllBots(): QueryResult<BotAppRecord[]> {\n const { workspaceId } = useBotlit();\n const variables = useMemo(() => ({ filters: buildBotFilter(workspaceId) }), [workspaceId]);\n\n return useWorkspaceAllPagesQuery<ListBotAppsData, BotAppRecord, BotAppRecord[]>({\n document: LIST_BOT_APPS_DOCUMENT,\n variables,\n pageSize: LIST_PAGE_SIZE,\n extractRows: (data) => data?.listBotApps ?? [],\n select: (rows) => rows,\n fallback: NO_BOTS,\n enabled: Boolean(workspaceId),\n errorMessage: 'Failed to load bots',\n });\n}\n\n/**\n * Exact bot counts by status for the workspace (BOFF-12426). Unlike `useBots`\n * this is not capped at one page, so it is the source for dashboard totals.\n * `total` counts every status; the dashboard shows `total - archived`.\n */\nexport interface BotAppCounts {\n total: number;\n draft: number;\n active: number;\n paused: number;\n archived: number;\n}\n\ninterface BotAppCountsData {\n getBotAppCounts?: BotAppCounts | null;\n}\n\nconst GET_BOT_APP_COUNTS_DOCUMENT = gql`\n query GetBotAppCounts {\n getBotAppCounts {\n total\n draft\n active\n paused\n archived\n }\n }\n`;\n\nexport function useBotAppCounts(enabled = true): QueryResult<BotAppCounts | null> {\n const { workspaceId } = useBotlit();\n const variables = useMemo(() => ({}), []);\n\n return useWorkspaceQuery<BotAppCountsData, BotAppCounts | null>({\n document: GET_BOT_APP_COUNTS_DOCUMENT,\n variables,\n select: (data) => data?.getBotAppCounts ?? null,\n fallback: null,\n enabled: enabled && Boolean(workspaceId),\n errorMessage: 'Failed to load bot counts',\n });\n}\n\nexport function useBot(botId: string | undefined) {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [data, setData] = useState<BotAppRecord | null>(null);\n // Loading from the first render when there is a bot to read, so a page that\n // depends on the bot never acts on \"no bot yet\" for the frame before the read.\n const [loading, setLoading] = useState(Boolean(botId));\n const [error, setError] = useState<Error | undefined>();\n\n const refetch = useCallback(async () => {\n if (!botId) {\n setData(null);\n setLoading(false);\n return;\n }\n\n setLoading(true);\n setError(undefined);\n try {\n const result = await client.query<GetBotAppData>({\n query: GET_BOT_APP_DOCUMENT,\n variables: { id: botId },\n fetchPolicy: 'network-only',\n });\n // Apollo v4 resolves (not rejects) with `result.error` set on GraphQL errors.\n // Without this a FORBIDDEN read looked like \"bot not found\" (BOFF-12436).\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) {\n throw operationError instanceof Error ? operationError : new Error('Failed to load bot');\n }\n setData(result.data?.getBotApp ?? null);\n } catch (queryError) {\n setData(null);\n setError(queryError instanceof Error ? queryError : new Error('Failed to load bot'));\n } finally {\n setLoading(false);\n }\n }, [botId, client]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\nexport function useCreateBot() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<BotMutationState<BotAppRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const createBot = useCallback(\n async (input: CreateBotInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<CreateBotAppData>({\n mutation: CREATE_BOT_APP_DOCUMENT,\n variables: { input },\n });\n\n const createdBot = result.data?.createBotApp;\n if (!createdBot) {\n throw new Error('Failed to create bot');\n }\n\n setState({ data: createdBot, loading: false, error: undefined });\n return createdBot;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to create bot');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [createBot, state] as const;\n}\n\nexport function useUpdateBot() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<BotMutationState<BotAppRecord>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const updateBot = useCallback(\n async ({ botId, input }: UpdateBotInput) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<UpdateBotAppData>({\n mutation: UPDATE_BOT_APP_DOCUMENT,\n variables: { id: botId, input: buildMutationInput(input, UPDATE_BOT_APP_FIELDS) },\n });\n\n const updatedBot = result.data?.updateBotApp;\n if (!updatedBot) {\n throw new Error('Failed to update bot');\n }\n\n setState({ data: updatedBot, loading: false, error: undefined });\n return updatedBot;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to update bot');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [updateBot, state] as const;\n}\n\nexport function useDeleteBot() {\n const client = getWorkspaceClient(useGatewayClient('workspace'));\n const [state, setState] = useState<BotMutationState<boolean>>({\n data: undefined,\n loading: false,\n error: undefined,\n });\n\n const deleteBot = useCallback(\n async (botId: string) => {\n setState({ data: undefined, loading: true, error: undefined });\n try {\n const result = await client.mutate<DeleteBotAppData>({\n mutation: DELETE_BOT_APP_DOCUMENT,\n variables: { id: botId },\n });\n\n const deleted = result.data?.deleteBotApp ?? false;\n setState({ data: deleted, loading: false, error: undefined });\n return deleted;\n } catch (mutationError) {\n const error =\n mutationError instanceof Error ? mutationError : new Error('Failed to delete bot');\n setState({ data: undefined, loading: false, error });\n throw error;\n }\n },\n [client]\n );\n\n return [deleteBot, state] as const;\n}\n"],"mappings":";;;;;;;;AAoBA,IAAMA,IAAyB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6B5BC,IAAuB,CAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6B1BC,IAA0B,CAAG;;;;;;;;;;;;;;;;;;;;;GAuB7BC,IAA0B,CAAG;;;;;;;;;;;;;;;;;;;;;;;GAyB7BC,IAA0B,CAAG;;;;GAuC7BC,IAAiB,KACjBC,IAA0B,CAAC,GAwC3BC,IAAwBC,EAA4B;CACxD,UAAU;CACV,SAAS;CACT,gBAAgB;CAChB,aAAa;CACb,iBAAiB;CACjB,MAAM;CACN,UAAU;CACV,MAAM;CACN,iBAAiB;CACjB,MAAM;CACN,QAAQ;CACR,QAAQ;CACR,MA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