impact-chatbot 2.3.102 → 2.4.0

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/index.cjs.js CHANGED
@@ -38,6 +38,8 @@ var agGridColumnFormatter = require('core/Utils/agGridV36/columnFormatter');
38
38
  var CoreChart = require('core/Utils/core-charts');
39
39
  var makeStyles = require('@mui/styles/makeStyles');
40
40
  var ChevronRightIcon$1 = require('@mui/icons-material/ChevronRight');
41
+ var DescriptionOutlinedIcon = require('@mui/icons-material/DescriptionOutlined');
42
+ var OpenInNewIcon = require('@mui/icons-material/OpenInNew');
41
43
  var FormatListBulletedOutlinedIcon = require('@mui/icons-material/FormatListBulletedOutlined');
42
44
  var PsychologyOutlinedIcon = require('@mui/icons-material/PsychologyOutlined');
43
45
  var colours$1 = require('core/Styles/colours');
@@ -46,6 +48,13 @@ var RangePicker = require('core/commonComponents/dateRangePicker');
46
48
  var NoFilterSetSavedIcon = require('core/coreAssets/chatbot/noFilterSetSaved.svg');
47
49
  var CoreComponentScreen = require('core/commonComponents/coreComponentScreen');
48
50
  var utils$1 = require('core/commonComponents/coreComponentScreen/utils');
51
+ var reactDom = require('react-dom');
52
+ var VisibilityOutlinedIcon = require('@mui/icons-material/VisibilityOutlined');
53
+ var OpenInFullIcon = require('@mui/icons-material/OpenInFull');
54
+ var CloseFullscreenIcon = require('@mui/icons-material/CloseFullscreen');
55
+ var CloseIcon = require('@mui/icons-material/Close');
56
+ var ExpandMoreIcon = require('@mui/icons-material/ExpandMore');
57
+ var ArrowForwardIcon = require('@mui/icons-material/ArrowForward');
49
58
  var utils$2 = require('core/Utils/utils');
50
59
 
51
60
  function _interopNamespaceDefault(e) {
@@ -307,6 +316,21 @@ const getTableRecords = async (payload, baseUrl, tableName) => {
307
316
  return null;
308
317
  }
309
318
  };
319
+ /** A read for a generated surface (frame protocol iui:query): the agent runs one read tool as the signed-in
320
+ * user and answers {rows, total}. */
321
+ const postUiQuery = async (payload, baseUrl) => {
322
+ try {
323
+ return axiosInstance({
324
+ url: `${baseUrl}/chatbot/agent/ui-query`,
325
+ method: 'POST',
326
+ data: payload,
327
+ });
328
+ }
329
+ catch (error) {
330
+ console.error('postUiQuery error:', error);
331
+ return null;
332
+ }
333
+ };
310
334
  const getTableRecordsByUrl = async (payload, url) => {
311
335
  try {
312
336
  return axiosInstance({
@@ -863,6 +887,17 @@ const parseResponse = (data, type, agentId = "", currentMode = "", disableTimeAn
863
887
  bodyType: "html",
864
888
  bodyText: { content: data?.data?.content || "" },
865
889
  };
890
+ case "allocation_plan_card":
891
+ return {
892
+ ...data,
893
+ timeStamp: timeString,
894
+ userType: "bot",
895
+ userName: userName,
896
+ headerTitle: "",
897
+ noShowHeaderTitle: true,
898
+ bodyType: "allocation_plan_card",
899
+ bodyText: data?.data || data,
900
+ };
866
901
  case "image":
867
902
  return {
868
903
  ...data,
@@ -890,6 +925,18 @@ const parseResponse = (data, type, agentId = "", currentMode = "", disableTimeAn
890
925
  thinkingResponse: utilityObject?.thinkingResponse,
891
926
  enableLikes: true
892
927
  };
928
+ case "surface_frame":
929
+ // A generated UI surface drawn by the UI service's renderer page (Impact UI 5), which SurfaceFrameContent embeds
930
+ return {
931
+ ...data,
932
+ agentId: agentId,
933
+ timeStamp: timeString,
934
+ userType: "bot",
935
+ userName: userName,
936
+ headerTitle: data?.data?.surface?.title || "",
937
+ bodyType: "surface_frame",
938
+ bodyText: data?.data,
939
+ };
893
940
  default:
894
941
  return null;
895
942
  }
@@ -2421,6 +2468,10 @@ const useAgentFlow = (dateFormat, chatDataRef, currentMode, setShowChatPlacehold
2421
2468
  answer_mode: data?.answerMode || "auto",
2422
2469
  ...(!isEmpty(utilityObjectData?.additionalArgs) ? utilityObjectData.additionalArgs : {}),
2423
2470
  };
2471
+ if (data?.uiContext && typeof data.uiContext === "object") {
2472
+ // a follow-up asked from a generated surface: which surface, and its input values
2473
+ payload.ui_context = data.uiContext;
2474
+ }
2424
2475
  // Handle @ filter mentions - user_explicit_input contains filter values
2425
2476
  if (!isEmpty(data?.userExplicitInput)) {
2426
2477
  payload.user_explicit_input = data?.userExplicitInput;
@@ -5568,6 +5619,73 @@ const QuestionsContent = ({ bodyText, props }) => {
5568
5619
  }) }));
5569
5620
  };
5570
5621
 
5622
+ /**
5623
+ * One widget per generated surface in a stream: the agent may send a surface more than once (a placeholder
5624
+ * while it is composed, `status: "pending"`, version 0; then the surface, version 1; or its withdrawal), and
5625
+ * frame protocol 1 replaces a surface by its id (agent-ui-service-ssr docs/chat-frame-widget.md, rule 4).
5626
+ * No imports: the stream reader (AxiosEventSource) uses it too. Ported from core's smartBot
5627
+ * (insideinsight/core feat/iui-surface, e386f8f0).
5628
+ */
5629
+ /** A surface's version; one when it gives none. */
5630
+ const surfaceVersion = (surface) => (Number.isFinite(surface?.version) ? surface.version : 1);
5631
+ const surfaceIdOf = (widget) => (widget?.type === "surface_frame" ? widget?.data?.surface?.id : undefined);
5632
+ /** A stream's widgets with these added: a surface_frame widget whose surface the list already holds replaces
5633
+ * it in place (a lower version is dropped); any other widget is added at the end. */
5634
+ const mergeSurfaceWidgets = (previous, incoming) => {
5635
+ const merged = Array.isArray(previous) ? previous.slice() : previous ? [previous] : [];
5636
+ for (const widget of Array.isArray(incoming) ? incoming : [incoming]) {
5637
+ const id = surfaceIdOf(widget);
5638
+ const at = id === undefined ? -1 : merged.findIndex((w) => surfaceIdOf(w) === id);
5639
+ if (at < 0)
5640
+ merged.push(widget);
5641
+ else if (surfaceVersion(widget.data.surface) >= surfaceVersion(merged[at].data.surface))
5642
+ merged[at] = widget;
5643
+ }
5644
+ return merged;
5645
+ };
5646
+ /*
5647
+ * Across the chat's messages (one page per surface): a surface revised in a later turn is shown, newest
5648
+ * version, where that turn put it; each earlier widget of it collapses to a line. Every SurfaceFrameContent
5649
+ * says which version it shows; a widget whose surface another widget shows in a higher version collapses.
5650
+ * Placeholders and withdrawn surfaces take no part. Equal versions (the same surface drawn in two places)
5651
+ * both show.
5652
+ */
5653
+ const shownVersions = new Map(); // surface id -> Map(widget token -> version)
5654
+ const watchers = new Set();
5655
+ let lastToken = 0;
5656
+ /** A token for one widget. */
5657
+ const surfaceToken = () => {
5658
+ lastToken += 1;
5659
+ return lastToken;
5660
+ };
5661
+ const notify = () => watchers.forEach((watch) => watch());
5662
+ /** This widget shows `version` of surface `id`. */
5663
+ const showSurface = (id, token, version) => {
5664
+ if (!shownVersions.has(id))
5665
+ shownVersions.set(id, new Map());
5666
+ shownVersions.get(id).set(token, version);
5667
+ notify();
5668
+ };
5669
+ /** This widget no longer shows surface `id`. */
5670
+ const hideSurface = (id, token) => {
5671
+ const versions = shownVersions.get(id);
5672
+ if (!versions)
5673
+ return;
5674
+ versions.delete(token);
5675
+ if (versions.size === 0)
5676
+ shownVersions.delete(id);
5677
+ notify();
5678
+ };
5679
+ /** Whether another widget shows surface `id` in a version higher than `version`. */
5680
+ const newerShown = (id, version) => [...(shownVersions.get(id)?.values() ?? [])].some((v) => v > version);
5681
+ /** Calls `watch` whenever a widget starts or stops showing a surface; returns the unsubscribe. */
5682
+ const watchSurfaces = (watch) => {
5683
+ watchers.add(watch);
5684
+ return () => {
5685
+ watchers.delete(watch);
5686
+ };
5687
+ };
5688
+
5571
5689
  // Utility: check whether a string is a likely complete JSON value
5572
5690
  const isLikelyCompleteJson = (message) => {
5573
5691
  try {
@@ -5775,10 +5893,8 @@ const sseevent = (message, messageToStoreRef) => {
5775
5893
  let previousWidgetData = lodash.isArray(messageToStoreRef.current.appendedData)
5776
5894
  ? messageToStoreRef.current.appendedData
5777
5895
  : [messageToStoreRef.current.appendedData];
5778
- messageToStoreRef.current.appendedData = [
5779
- ...previousWidgetData,
5780
- ...finalWidgetData,
5781
- ];
5896
+ // a surface sent again (placeholder, then the surface) replaces its widget in place
5897
+ messageToStoreRef.current.appendedData = mergeSurfaceWidgets(previousWidgetData, finalWidgetData);
5782
5898
  messageToStoreRef.current.sessionId = parsedData.session_id;
5783
5899
  messageToStoreRef.current.uniqueChatId = parsedData?.chat_id
5784
5900
  ? parsedData.chat_id
@@ -5818,10 +5934,8 @@ const sseevent = (message, messageToStoreRef) => {
5818
5934
  let previousWidgetData = lodash.isArray(messageToStoreRef.current.appendedData)
5819
5935
  ? messageToStoreRef.current.appendedData
5820
5936
  : [messageToStoreRef.current.appendedData];
5821
- messageToStoreRef.current.appendedData = [
5822
- ...previousWidgetData,
5823
- ...finalWidgetData,
5824
- ];
5937
+ // a surface sent again (placeholder, then the surface) replaces its widget in place
5938
+ messageToStoreRef.current.appendedData = mergeSurfaceWidgets(previousWidgetData, finalWidgetData);
5825
5939
  messageToStoreRef.current.additionalArgs = parsedData?.additional_args
5826
5940
  ? parsedData.additional_args
5827
5941
  : {};
@@ -8012,6 +8126,183 @@ const ImageContent = ({ bodyText }) => {
8012
8126
  } })), caption && (jsxRuntime.jsx("div", { children: jsxRuntime.jsx(TextRenderer, { text: caption }) }))] }));
8013
8127
  };
8014
8128
 
8129
+ const SUBMIT = { buttons: [{ label: "Submit", variant: "primary" }] };
8130
+ /** A follow-up's limits: longer ones are ignored. */
8131
+ const PROMPT_TEXT_MAX = 1000;
8132
+ const PROMPT_CONTEXT_MAX = 16000;
8133
+ /** The window event the chat listens to for a follow-up asked from a surface. */
8134
+ const PROMPT_EVENT = "iris:prompt";
8135
+ /** The source a surface names for this temp table, if it names it: the only tables its page may ask pages
8136
+ * of, and the endpoint address the agent gave (the page's own copy of the source is not trusted for it). */
8137
+ const sourceOf = (surface, table) => Object.values(surface?.data || {}).map((entry) => entry?.source).find((source) => typeof source?.table === "string" && source.table === table);
8138
+ /** Whether the surface binds this tool: the only tools its page may ask to read again. */
8139
+ const bindsTool = (surface, tool) => typeof tool === "string" && tool !== "rows" && Object.values(surface?.data || {}).some((entry) => entry?.tool === tool);
8140
+ const baseUrl = () => sessionStorage.getItem("stepForm_baseUrl") || "";
8141
+ /** One page of a source, from the agent's paging endpoint (its pages hold at most 10 rows): at the address
8142
+ * the agent gave, as TableContent does with temp_table_url, else under the stream's base URL. `search`: a
8143
+ * filter Control over the kept rows (catalog 0.3), each `{field, value}` an exact match the endpoint applies. */
8144
+ const pageOf = async ({ source, page, pageSize, sort, search }) => {
8145
+ const payload = {
8146
+ limit: { page, page_size: pageSize },
8147
+ search: (Array.isArray(search) ? search : [])
8148
+ .filter((s) => s && typeof s.field === "string" && s.value !== undefined && s.value !== null)
8149
+ .slice(0, 5)
8150
+ .map((s) => ({ column: s.field, pattern: String(s.value), search_type: "equals" })),
8151
+ sort: (Array.isArray(sort) ? sort : []).map((s) => ({ column: s.field, order: s.order === "desc" ? "desc" : "asc" })),
8152
+ };
8153
+ const response = source.url
8154
+ ? await getTableRecordsByUrl(payload, source.url)
8155
+ : await getTableRecords(payload, baseUrl(), source.table);
8156
+ const rows = response?.data?.data;
8157
+ const total = response?.data?.total_count;
8158
+ if (!Array.isArray(rows) || !Number.isFinite(total))
8159
+ throw new Error("no rows");
8160
+ return { rows, total };
8161
+ };
8162
+ /** A read tool the surface binds, run again by the agent with these arguments. */
8163
+ const readOf = async ({ surface, tool, args }) => {
8164
+ const response = await postUiQuery({ surface, tool, args: args && typeof args === "object" ? args : {} }, baseUrl());
8165
+ const rows = response?.data?.rows;
8166
+ const total = response?.data?.total;
8167
+ if (!Array.isArray(rows) || !Number.isFinite(total))
8168
+ throw new Error(response?.data?.error || "no rows");
8169
+ return { rows, total };
8170
+ };
8171
+ /** The page's origin, for http(s) addresses only; anything else is refused. */
8172
+ const frameOrigin = (src) => {
8173
+ try {
8174
+ const url = new URL(src, window.location.href);
8175
+ return url.protocol === "https:" || url.protocol === "http:" ? url.origin : null;
8176
+ }
8177
+ catch {
8178
+ return null;
8179
+ }
8180
+ };
8181
+ /** A follow-up within the limits, or null. */
8182
+ const promptOf = (data, surfaceId) => {
8183
+ const text = typeof data?.text === "string" ? data.text.trim() : "";
8184
+ const context = data?.context && typeof data.context === "object" ? { ...data.context, surface: surfaceId } : { surface: surfaceId };
8185
+ let size = Infinity;
8186
+ try {
8187
+ size = JSON.stringify(context).length;
8188
+ }
8189
+ catch {
8190
+ // a context that cannot be sent is not sent
8191
+ }
8192
+ if (!text || text.length > PROMPT_TEXT_MAX || size > PROMPT_CONTEXT_MAX)
8193
+ return null;
8194
+ return { text, uiContext: context };
8195
+ };
8196
+ const SurfaceFrameContent = ({ frame, isFormDisabled = false, messageIndex = 0 }) => {
8197
+ const dispatch = reactRedux.useDispatch();
8198
+ const chatbotContext = reactRedux.useSelector((state) => state.smartBotReducer.chatbotContext);
8199
+ const contextRef = React.useRef(chatbotContext);
8200
+ contextRef.current = chatbotContext;
8201
+ const iframeRef = React.useRef(null);
8202
+ const ready = React.useRef(false);
8203
+ const [height, setHeight] = React.useState(120);
8204
+ const [form, setForm] = React.useState({ values: {}, inputs: [], missing: [] });
8205
+ const formRef = React.useRef(form);
8206
+ formRef.current = form;
8207
+ const src = frame?.src;
8208
+ const incoming = frame?.surface;
8209
+ // the surface shown: a newer version of the same surface replaces it, a lower one is ignored
8210
+ const [surface, setSurface] = React.useState(incoming);
8211
+ React.useEffect(() => {
8212
+ if (incoming && (!surface || incoming.id !== surface.id || surfaceVersion(incoming) >= surfaceVersion(surface)))
8213
+ setSurface(incoming);
8214
+ }, [incoming]); // eslint-disable-line react-hooks/exhaustive-deps
8215
+ const origin = React.useMemo(() => frameOrigin(src), [src]);
8216
+ const ask = surface?.mode === "ask";
8217
+ // which version of its surface each widget shows, across the chat's messages
8218
+ const token = React.useRef(null);
8219
+ if (token.current === null)
8220
+ token.current = surfaceToken();
8221
+ const [, setShownChange] = React.useState(0);
8222
+ React.useEffect(() => watchSurfaces(() => setShownChange((n) => n + 1)), []);
8223
+ React.useEffect(() => {
8224
+ if (!surface?.id || surface.status === "pending" || surface.status === "withdrawn")
8225
+ return undefined;
8226
+ showSurface(surface.id, token.current, surfaceVersion(surface));
8227
+ return () => hideSurface(surface.id, token.current);
8228
+ }, [surface?.id, surface?.version, surface?.status]); // eslint-disable-line react-hooks/exhaustive-deps
8229
+ const send = (target, values) => target?.postMessage({ type: "iui:surface", surface, values, disabled: Boolean(isFormDisabled), query: true, ...(ask ? { submit: false } : {}) }, origin);
8230
+ React.useEffect(() => {
8231
+ if (!origin || !surface)
8232
+ return undefined;
8233
+ const onMessage = (event) => {
8234
+ const target = iframeRef.current?.contentWindow;
8235
+ if (!target || event.source !== target || event.origin !== origin)
8236
+ return;
8237
+ const data = event.data || {};
8238
+ // every message but iui:ready and iui:height names its surface: this widget answers for its own only
8239
+ const own = data.surface === undefined || data.surface === surface.id;
8240
+ if (data.type === "iui:ready") {
8241
+ ready.current = true;
8242
+ send(target, undefined);
8243
+ }
8244
+ else if (data.type === "iui:height" && Number.isFinite(data.height))
8245
+ setHeight(Math.max(40, Math.ceil(data.height)));
8246
+ else if (data.type === "iui:query" && own) {
8247
+ const reply = (body) => target.postMessage({ type: "iui:data", surface: surface.id, id: data.id, ...body }, origin);
8248
+ const args = data.args || {};
8249
+ if (data.tool === "rows") {
8250
+ const source = sourceOf(surface, args.source?.table);
8251
+ if (!source)
8252
+ reply({ error: "not a table of this answer" });
8253
+ else
8254
+ pageOf({ ...args, source }).then(reply, () => reply({ error: "the rows could not be loaded" }));
8255
+ }
8256
+ else if (bindsTool(surface, data.tool)) {
8257
+ readOf({ surface: surface.id, tool: data.tool, args }).then(reply, () => reply({ error: "the data could not be loaded" }));
8258
+ }
8259
+ else
8260
+ reply({ error: "not a tool of this answer" });
8261
+ }
8262
+ else if (data.type === "iui:prompt" && data.surface === surface.id) {
8263
+ const prompt = promptOf(data, surface.id);
8264
+ if (prompt)
8265
+ window.dispatchEvent(new CustomEvent(PROMPT_EVENT, { detail: prompt }));
8266
+ }
8267
+ else if (data.type === "iui:change" && ask && own) {
8268
+ const values = data.values || {};
8269
+ setForm({ values, inputs: Array.isArray(data.inputs) ? data.inputs : Object.keys(values), missing: Array.isArray(data.missing) ? data.missing : [] });
8270
+ // as this chat's own inputs record their values, for the step form's Submit (ButtonContent)
8271
+ const context = { ...contextRef.current };
8272
+ for (const [name, value] of Object.entries(values)) {
8273
+ const empty = value === "" || value === null || value === undefined || (Array.isArray(value) && value.length === 0);
8274
+ context[name] = { ...context[name], [name]: value, updated: !empty };
8275
+ }
8276
+ dispatch(smartBotActions.setChatbotContext(context));
8277
+ // only what was filled in: ButtonContent sends a persisted value even when it is empty
8278
+ const filled = Object.entries(values).filter(([name]) => context[name].updated);
8279
+ dispatch(smartBotActions.setPersistedFormValues(Object.fromEntries(filled.map(([name, value]) => [`${messageIndex}_${name}`, value]))));
8280
+ }
8281
+ // anything else: a message type this chat does not know, ignored
8282
+ };
8283
+ window.addEventListener("message", onMessage);
8284
+ return () => window.removeEventListener("message", onMessage);
8285
+ }, [origin, surface, isFormDisabled, ask, messageIndex]); // eslint-disable-line react-hooks/exhaustive-deps
8286
+ // a newer version of the surface goes into the page that shows it
8287
+ React.useEffect(() => {
8288
+ if (ready.current)
8289
+ send(iframeRef.current?.contentWindow, undefined);
8290
+ }, [surface]); // eslint-disable-line react-hooks/exhaustive-deps
8291
+ // a submitted form is posted again, disabled, with what was filled in
8292
+ React.useEffect(() => {
8293
+ if (isFormDisabled && ask)
8294
+ send(iframeRef.current?.contentWindow, formRef.current.values);
8295
+ }, [isFormDisabled]); // eslint-disable-line react-hooks/exhaustive-deps
8296
+ // a surface that will not come after all (its composition failed): nothing to draw
8297
+ if (!origin || !surface || surface.status === "withdrawn")
8298
+ return null;
8299
+ // a later message shows this surface revised: one line here, the surface there
8300
+ if (newerShown(surface.id, surfaceVersion(surface))) {
8301
+ return (jsxRuntime.jsx(material.Box, { "data-iui-host": "surface-frame", "data-iui-superseded": surface.id, my: 1, sx: { fontSize: 13, color: "text.secondary" }, children: `Revised below${surface.title ? `: ${surface.title}` : ""}.` }));
8302
+ }
8303
+ return (jsxRuntime.jsxs(material.Box, { "data-iui-host": "surface-frame", my: 1, children: [jsxRuntime.jsx("iframe", { ref: iframeRef, src: src, title: surface.title || "Generated answer", sandbox: "allow-scripts allow-same-origin", referrerPolicy: "no-referrer", style: { width: "100%", height, border: 0, display: "block" } }), ask ? (jsxRuntime.jsx(ButtonContent, { bodyText: SUBMIT, isFormDisabled: isFormDisabled, isStepFormSubmit: true, isFormValid: form.inputs.length > 0 && form.missing.length === 0, formParamNames: form.inputs, messageIndex: messageIndex })) : null] }));
8304
+ };
8305
+
8015
8306
  // Key used to persist timeout state in sessionStorage (survives component remounts from tab switches)
8016
8307
  const STEP_FORM_TIMEOUT_KEY = "__stepFormTimedOut";
8017
8308
  /**
@@ -8439,11 +8730,17 @@ const StepFormContent = ({ formData, messageIndex = 0, isFormDisabled = false, s
8439
8730
  case "radio":
8440
8731
  return jsxRuntime.jsx(RadioContent, { bodyText: parsedData.bodyText, isFormDisabled: formFieldsDisabled, messageIndex: messageIndex }, key);
8441
8732
  case "button":
8733
+ // A form in the renderer page has its Submit drawn by SurfaceFrameContent, which knows the page's inputs
8734
+ if (formData.some((item) => item?.type === "surface_frame"))
8735
+ return null;
8442
8736
  return jsxRuntime.jsx(ButtonContent, { bodyText: parsedData.bodyText, isFormDisabled: isFormDisabled || isFormSubmitted || isTimedOut, isStepFormSubmit: true, isFormValid: requiredFieldsFilled && checkboxGroupsValid, formParamNames: formParamNames, messageIndex: messageIndex }, key);
8443
8737
  case "input":
8444
8738
  return jsxRuntime.jsx(InputContent, { bodyText: parsedData.bodyText, isFormDisabled: formFieldsDisabled, messageIndex: messageIndex }, key);
8445
8739
  case "image":
8446
8740
  return jsxRuntime.jsx(ImageContent, { bodyText: parsedData.bodyText }, key);
8741
+ case "surface_frame":
8742
+ // The whole form in the renderer page; the widget draws this form's Submit (its inputs are in the page)
8743
+ return jsxRuntime.jsx(SurfaceFrameContent, { frame: parsedData.bodyText, isFormDisabled: isFormDisabled || isFormSubmitted || isTimedOut, messageIndex: messageIndex }, parsedData.bodyText?.surface?.id || key);
8447
8744
  default:
8448
8745
  return null;
8449
8746
  }
@@ -8960,6 +9257,479 @@ const Steps$1 = ({ steps, setSteps, done, setTabValue, setDone, finalStepDone, s
8960
9257
  }, children: jsxRuntime.jsx(ProgressBarItem$1, { question: "Thinking", questionSteps: [{ header: "", sub_header: "", step_status: "not-completed" }], isLast: true, classes: classes, formData: null, isFormDisabled: isFormDisabled }) }))] }));
8961
9258
  };
8962
9259
 
9260
+ const useAllocationPanelStyles = styles.makeStyles((theme) => ({
9261
+ // AllocationPlanCard styles (inside chatbot)
9262
+ planCard: {
9263
+ border: "1.5px solid #e2e8f0",
9264
+ borderRadius: "14px",
9265
+ padding: "14px 16px",
9266
+ display: "flex",
9267
+ alignItems: "center",
9268
+ gap: "14px",
9269
+ cursor: "pointer",
9270
+ position: "relative",
9271
+ overflow: "hidden",
9272
+ transition: "border-color 0.25s ease, box-shadow 0.25s ease, background 0.25s ease",
9273
+ background: "#fafbff",
9274
+ "&:hover": {
9275
+ borderColor: "#b4beff",
9276
+ boxShadow: "0 2px 12px rgba(66, 89, 238, 0.10)",
9277
+ background: "linear-gradient(135deg, #f5f7ff 0%, #eef1ff 60%, #e8ecff 100%)",
9278
+ },
9279
+ },
9280
+ planCardIcon: {
9281
+ width: "48px",
9282
+ height: "48px",
9283
+ borderRadius: "12px",
9284
+ background: "linear-gradient(135deg, #e8edff 0%, #dbe1ff 100%)",
9285
+ display: "flex",
9286
+ alignItems: "center",
9287
+ justifyContent: "center",
9288
+ flexShrink: 0,
9289
+ "& svg": {
9290
+ color: "#4259EE",
9291
+ fontSize: "22px",
9292
+ },
9293
+ },
9294
+ planCardContent: {
9295
+ flex: 1,
9296
+ minWidth: 0,
9297
+ },
9298
+ planCardTitle: {
9299
+ fontSize: "14px",
9300
+ fontWeight: 700,
9301
+ color: "#1e293b",
9302
+ lineHeight: 1.4,
9303
+ marginBottom: "4px",
9304
+ },
9305
+ planCardLinks: {
9306
+ display: "flex",
9307
+ alignItems: "center",
9308
+ gap: "4px",
9309
+ flexWrap: "wrap",
9310
+ fontSize: "13px",
9311
+ color: "#64748b",
9312
+ },
9313
+ planCardLink: {
9314
+ color: "#64748b",
9315
+ cursor: "pointer",
9316
+ textDecoration: "none",
9317
+ transition: "color 0.2s ease",
9318
+ "&:hover": {
9319
+ color: "#4259EE",
9320
+ },
9321
+ },
9322
+ planCardLinkSeparator: {
9323
+ color: "#94a3b8",
9324
+ margin: "0 3px",
9325
+ },
9326
+ planCardOpenIcon: {
9327
+ flexShrink: 0,
9328
+ color: "#94a3b8",
9329
+ fontSize: "20px !important",
9330
+ padding: "6px",
9331
+ borderRadius: "8px",
9332
+ border: "1px solid #e2e8f0",
9333
+ background: "#ffffff",
9334
+ transition: "border-color 0.25s ease, color 0.25s ease",
9335
+ "$planCard:hover &": {
9336
+ borderColor: "#b4beff",
9337
+ color: "#4259EE",
9338
+ },
9339
+ },
9340
+
9341
+ // PanelHeader styles
9342
+ panelHeader: {
9343
+ display: "flex",
9344
+ alignItems: "center",
9345
+ justifyContent: "space-between",
9346
+ padding: "16px",
9347
+ borderBottom: "1px solid #f0f0f0",
9348
+ flexShrink: 0,
9349
+ },
9350
+ panelHeaderLeft: {
9351
+ display: "flex",
9352
+ alignItems: "center",
9353
+ gap: "8px",
9354
+ flex: 1,
9355
+ minWidth: 0,
9356
+ },
9357
+ panelHeaderIcon: {
9358
+ color: "#666",
9359
+ fontSize: "20px",
9360
+ cursor: "pointer",
9361
+ },
9362
+ panelTitle: {
9363
+ fontSize: "14px",
9364
+ fontWeight: 600,
9365
+ color: "#1a1a1a",
9366
+ lineHeight: 1.4,
9367
+ overflow: "hidden",
9368
+ textOverflow: "ellipsis",
9369
+ whiteSpace: "nowrap",
9370
+ },
9371
+ panelHeaderActions: {
9372
+ display: "flex",
9373
+ alignItems: "center",
9374
+ gap: "6px",
9375
+ flexShrink: 0,
9376
+ },
9377
+ panelHeaderActionBtn: {
9378
+ width: "28px !important",
9379
+ height: "28px !important",
9380
+ borderRadius: "8px !important",
9381
+ background: "#f1f5f9 !important",
9382
+ color: "#475569 !important",
9383
+ padding: "0 !important",
9384
+ "&:hover": {
9385
+ background: "#e2e8f0 !important",
9386
+ color: "#1e293b !important",
9387
+ },
9388
+ },
9389
+
9390
+ // ReportSummaryCard styles
9391
+ reportSummaryCard: {
9392
+ border: "1px solid #f0c36d",
9393
+ borderRadius: "8px",
9394
+ padding: "14px",
9395
+ margin: "16px 0",
9396
+ background: "#fffdf5",
9397
+ },
9398
+ reportBadge: {
9399
+ display: "inline-block",
9400
+ fontSize: "11px",
9401
+ fontWeight: 500,
9402
+ padding: "3px 8px",
9403
+ borderRadius: "4px",
9404
+ marginBottom: "8px",
9405
+ border: "1px solid #f0c36d",
9406
+ color: "#8b6914",
9407
+ background: "transparent",
9408
+ },
9409
+ reportDescription: {
9410
+ fontSize: "12px",
9411
+ lineHeight: 1.6,
9412
+ color: "#333",
9413
+ marginBottom: "10px",
9414
+ },
9415
+ baselinePlanRow: {
9416
+ fontSize: "12px",
9417
+ color: "#666",
9418
+ display: "flex",
9419
+ alignItems: "center",
9420
+ gap: "4px",
9421
+ },
9422
+ baselinePlanLink: {
9423
+ color: "#2563eb",
9424
+ textDecoration: "underline",
9425
+ cursor: "pointer",
9426
+ wordBreak: "break-all",
9427
+ },
9428
+
9429
+ // PanelSection (Accordion) styles
9430
+ sectionAccordion: {
9431
+ boxShadow: "none !important",
9432
+ border: "none !important",
9433
+ borderRadius: "12px !important",
9434
+ marginBottom: "10px !important",
9435
+ background: "#f8fafc !important",
9436
+ "&:before": {
9437
+ display: "none !important",
9438
+ content: "none !important",
9439
+ background: "none !important",
9440
+ width: "0 !important",
9441
+ height: "0 !important",
9442
+ },
9443
+ "&.Mui-expanded": {
9444
+ margin: "0 0 10px 0 !important",
9445
+ background: "#ffffff !important",
9446
+ boxShadow: "0 1px 8px rgba(0, 0, 0, 0.06) !important",
9447
+ border: "1px solid #e2e8f0 !important",
9448
+ },
9449
+ },
9450
+ sectionSummary: {
9451
+ minHeight: "48px !important",
9452
+ padding: "0 16px !important",
9453
+ border: "none !important",
9454
+ flexDirection: "row-reverse !important",
9455
+ gap: "10px",
9456
+ "&:before": {
9457
+ display: "none !important",
9458
+ content: "none !important",
9459
+ background: "none !important",
9460
+ width: "0 !important",
9461
+ height: "0 !important",
9462
+ },
9463
+ "& .MuiAccordionSummary-content": {
9464
+ margin: "12px 0 !important",
9465
+ },
9466
+ "& .MuiAccordionSummary-expandIconWrapper": {
9467
+ color: "#64748b",
9468
+ transform: "rotate(-90deg)",
9469
+ padding: "0 !important",
9470
+ marginRight: "0 !important",
9471
+ "&.Mui-expanded": {
9472
+ transform: "rotate(0deg)",
9473
+ },
9474
+ },
9475
+ },
9476
+ sectionTitle: {
9477
+ fontSize: "14px",
9478
+ fontWeight: 600,
9479
+ color: "#1e293b",
9480
+ },
9481
+ sectionDetails: {
9482
+ padding: "0 16px 16px !important",
9483
+ border: "none !important",
9484
+ "&:before": {
9485
+ display: "none !important",
9486
+ content: "none !important",
9487
+ background: "none !important",
9488
+ width: "0 !important",
9489
+ height: "0 !important",
9490
+ },
9491
+ },
9492
+
9493
+ // StructuredComparison styles
9494
+ comparisonSubtitle: {
9495
+ fontSize: "12px",
9496
+ color: "#666",
9497
+ marginBottom: "12px",
9498
+ lineHeight: 1.5,
9499
+ },
9500
+ scenarioLabel: {
9501
+ fontSize: "12px",
9502
+ fontWeight: 500,
9503
+ color: "#1a1a1a",
9504
+ padding: "8px 12px",
9505
+ background: "#f8f9fa",
9506
+ borderRadius: "6px",
9507
+ marginBottom: "12px",
9508
+ },
9509
+ comparisonCard: {
9510
+ background: "#f8f9fa",
9511
+ borderRadius: "8px",
9512
+ padding: "12px",
9513
+ marginBottom: "10px",
9514
+ },
9515
+ comparisonParamRow: {
9516
+ display: "flex",
9517
+ alignItems: "center",
9518
+ gap: "8px",
9519
+ marginBottom: "10px",
9520
+ },
9521
+ comparisonParamName: {
9522
+ fontSize: "13px",
9523
+ fontWeight: 600,
9524
+ color: "#1a1a1a",
9525
+ },
9526
+ comparisonTag: {
9527
+ display: "inline-block",
9528
+ fontSize: "10px",
9529
+ fontWeight: 500,
9530
+ padding: "2px 6px",
9531
+ borderRadius: "4px",
9532
+ color: "#2563eb",
9533
+ border: "1px solid #bfdbfe",
9534
+ background: "#eff6ff",
9535
+ },
9536
+ comparisonValues: {
9537
+ display: "flex",
9538
+ alignItems: "center",
9539
+ gap: "8px",
9540
+ },
9541
+ comparisonValueBox: {
9542
+ flex: 1,
9543
+ background: theme.palette.common.white,
9544
+ borderRadius: "6px",
9545
+ padding: "8px 10px",
9546
+ border: "1px solid #e8e8e8",
9547
+ },
9548
+ comparisonValueLabel: {
9549
+ fontSize: "10px",
9550
+ color: "#999",
9551
+ marginBottom: "2px",
9552
+ },
9553
+ comparisonValueText: {
9554
+ fontSize: "12px",
9555
+ fontWeight: 600,
9556
+ color: "#1a1a1a",
9557
+ },
9558
+ comparisonArrow: {
9559
+ color: "#999",
9560
+ fontSize: "16px",
9561
+ flexShrink: 0,
9562
+ },
9563
+
9564
+ // Panel-specific HTML content wrapper (font size/line-height for panel context)
9565
+ panelHtmlContainer: {
9566
+ fontSize: "12px",
9567
+ lineHeight: 1.6,
9568
+ },
9569
+
9570
+ // Slide-in keyframes for panel entry
9571
+ "@keyframes panelSlideIn": {
9572
+ "0%": {
9573
+ transform: "translateX(100%)",
9574
+ opacity: 0,
9575
+ },
9576
+ "100%": {
9577
+ transform: "translateX(0)",
9578
+ opacity: 1,
9579
+ },
9580
+ },
9581
+ // AllocationDetailPanel container (portaled)
9582
+ panelContainer: {
9583
+ position: "fixed",
9584
+ top: 56,
9585
+ right: 0,
9586
+ width: "calc(50vw - 32px)",
9587
+ maxWidth: "520px",
9588
+ height: "calc(100vh - 56px)",
9589
+ zIndex: 99999,
9590
+ display: "flex",
9591
+ flexDirection: "column",
9592
+ background: "#ffffff",
9593
+ boxShadow: "-4px 0 16px rgba(0, 0, 0, 0.15)",
9594
+ borderLeft: "1px solid #e8e8e8",
9595
+ borderRadius: "12px 0 0 12px",
9596
+ overflow: "hidden",
9597
+ animation: "$panelSlideIn 0.3s ease forwards",
9598
+ transition: "width 0.3s ease, max-width 0.3s ease, border-radius 0.3s ease",
9599
+ },
9600
+ // Expanded / maximized panel — covers the chatbot area too
9601
+ panelExpanded: {
9602
+ width: "calc(100vw - 4rem)",
9603
+ maxWidth: "calc(100vw - 4rem)",
9604
+ borderRadius: "0",
9605
+ },
9606
+ panelScrollBody: {
9607
+ flex: 1,
9608
+ overflowY: "auto",
9609
+ padding: "0 16px 24px",
9610
+ },
9611
+
9612
+ // Footer
9613
+ panelFooter: {
9614
+ display: "flex",
9615
+ justifyContent: "flex-end",
9616
+ alignItems: "center",
9617
+ gap: "10px",
9618
+ padding: "12px 16px",
9619
+ borderTop: "1px solid #e2e8f0",
9620
+ background: "#ffffff",
9621
+ flexShrink: 0,
9622
+ position: "relative",
9623
+ },
9624
+ footerBtnOutlined: {
9625
+ display: "inline-flex",
9626
+ alignItems: "center",
9627
+ justifyContent: "center",
9628
+ height: "32px",
9629
+ padding: "0 12px",
9630
+ fontSize: "14px",
9631
+ fontWeight: 600,
9632
+ fontFamily: "Manrope, sans-serif",
9633
+ lineHeight: 1,
9634
+ borderRadius: "8px",
9635
+ border: "1px solid #d1d5db",
9636
+ background: "#ffffff",
9637
+ color: "#1e293b",
9638
+ cursor: "pointer",
9639
+ textTransform: "none",
9640
+ },
9641
+ footerBtnPrimary: {
9642
+ display: "inline-flex",
9643
+ alignItems: "center",
9644
+ justifyContent: "center",
9645
+ height: "32px",
9646
+ padding: "0 12px",
9647
+ fontSize: "14px",
9648
+ fontWeight: 600,
9649
+ fontFamily: "Manrope, sans-serif",
9650
+ lineHeight: 1,
9651
+ borderRadius: "8px",
9652
+ border: "1px solid #4259EE",
9653
+ background: "#4259EE",
9654
+ color: "#ffffff",
9655
+ cursor: "pointer",
9656
+ textTransform: "none",
9657
+ },
9658
+
9659
+ // Footer options popover
9660
+ optionsCard: {
9661
+ position: "absolute",
9662
+ bottom: "100%",
9663
+ right: 0,
9664
+ marginBottom: "8px",
9665
+ background: "#ffffff",
9666
+ borderRadius: "12px",
9667
+ boxShadow: "0 4px 20px rgba(0, 0, 0, 0.12)",
9668
+ border: "1px solid #e2e8f0",
9669
+ padding: "8px",
9670
+ minWidth: "280px",
9671
+ zIndex: 1,
9672
+ },
9673
+ optionRow: {
9674
+ display: "flex",
9675
+ alignItems: "center",
9676
+ gap: "10px",
9677
+ padding: "10px 12px",
9678
+ borderRadius: "8px",
9679
+ cursor: "pointer",
9680
+ fontSize: "13px",
9681
+ fontWeight: 500,
9682
+ color: "#1e293b",
9683
+ background: "#f8fafc",
9684
+ marginBottom: "4px",
9685
+ border: "none",
9686
+ width: "100%",
9687
+ textAlign: "left",
9688
+ fontFamily: "Manrope, sans-serif",
9689
+ "&:hover": {
9690
+ background: "#eef2ff",
9691
+ },
9692
+ "&:last-child": {
9693
+ marginBottom: 0,
9694
+ },
9695
+ },
9696
+ optionIcon: {
9697
+ color: "#6366f1",
9698
+ fontSize: "16px",
9699
+ },
9700
+ }));
9701
+
9702
+ const AllocationPlanCard = ({ bodyText }) => {
9703
+ const classes = useAllocationPanelStyles();
9704
+ const title = bodyText?.title || "Allocation Plan";
9705
+ const links = bodyText?.links || [];
9706
+ const panelData = bodyText?.panel_data || null;
9707
+ const handleCardClick = (target) => {
9708
+ if (!panelData)
9709
+ return;
9710
+ const openPanel = () => {
9711
+ window.dispatchEvent(new CustomEvent("openAllocationDetailPanel", {
9712
+ detail: { panelData, activeSection: target || null },
9713
+ }));
9714
+ };
9715
+ // Check if the chatbot is in a collapsed/minimized state by looking for
9716
+ // the "Expand chatbot" button (present only when collapsed)
9717
+ const expandBtn = document.querySelector('button[aria-label="Expand chatbot"]');
9718
+ if (expandBtn) {
9719
+ // Maximize first, then open the panel after chatbot finishes expanding
9720
+ window.dispatchEvent(new CustomEvent("smartBotMaximize"));
9721
+ setTimeout(openPanel, 350);
9722
+ }
9723
+ else {
9724
+ openPanel();
9725
+ }
9726
+ };
9727
+ return (jsxRuntime.jsxs("div", { className: classes.planCard, onClick: () => handleCardClick(links[0]?.target), children: [jsxRuntime.jsx("div", { className: classes.planCardIcon, children: jsxRuntime.jsx(DescriptionOutlinedIcon, {}) }), jsxRuntime.jsxs("div", { className: classes.planCardContent, children: [jsxRuntime.jsx("div", { className: classes.planCardTitle, children: title }), jsxRuntime.jsx("div", { className: classes.planCardLinks, children: links.map((link, index) => (jsxRuntime.jsxs("span", { children: [index > 0 && (jsxRuntime.jsx("span", { className: classes.planCardLinkSeparator, children: "\u00B7" })), jsxRuntime.jsx("span", { className: classes.planCardLink, onClick: (e) => {
9728
+ e.stopPropagation();
9729
+ handleCardClick(link.target);
9730
+ }, children: link.label })] }, link.target || index))) })] }), jsxRuntime.jsx(OpenInNewIcon, { className: classes.planCardOpenIcon })] }));
9731
+ };
9732
+
8963
9733
  const renderWidgetItem = (item, index, isFormDisabled) => {
8964
9734
  try {
8965
9735
  const parsedData = parseResponse(item, item.type, "", "", true);
@@ -8996,6 +9766,10 @@ const renderWidgetItem = (item, index, isFormDisabled) => {
8996
9766
  return jsxRuntime.jsx(DateRangePickerContent, { bodyText: parsedData.bodyText, isFormDisabled: isFormDisabled }, key);
8997
9767
  case "html":
8998
9768
  return jsxRuntime.jsx(HtmlContent, { bodyText: parsedData.bodyText }, key);
9769
+ case "surface_frame":
9770
+ return jsxRuntime.jsx(SurfaceFrameContent, { frame: parsedData.bodyText }, parsedData.bodyText?.surface?.id || key);
9771
+ case "allocation_plan_card":
9772
+ return jsxRuntime.jsx(AllocationPlanCard, { bodyText: parsedData.bodyText }, key);
8999
9773
  default:
9000
9774
  return null;
9001
9775
  }
@@ -9867,7 +10641,8 @@ const StreamedContent = ({ botData, botProps }) => {
9867
10641
  const widgetItems = isArray(data.widget_data)
9868
10642
  ? data.widget_data
9869
10643
  : [data.widget_data];
9870
- setStreamingWidgetData((prev) => [...prev, ...widgetItems]);
10644
+ // a surface sent again (placeholder, then the surface) replaces its widget in place
10645
+ setStreamingWidgetData((prev) => mergeSurfaceWidgets(prev, widgetItems));
9871
10646
  }
9872
10647
  else if (data.message !== "[DONE]") {
9873
10648
  if (!thinkingDoneRef?.current && currentMode === "agent") {
@@ -11037,6 +11812,8 @@ const TabularContent = ({ steps: initialSteps, currentTabValue, children, questi
11037
11812
  return jsxRuntime.jsx(TableContent, { bodyText: parsedData.bodyText }, parsedData.bodyText?.table_name || key);
11038
11813
  case "graph":
11039
11814
  return jsxRuntime.jsx(GraphContent, { bodyText: parsedData.bodyText }, key);
11815
+ case "surface_frame":
11816
+ return jsxRuntime.jsx(SurfaceFrameContent, { frame: parsedData.bodyText }, parsedData.bodyText?.surface?.id || key);
11040
11817
  case "radio":
11041
11818
  return jsxRuntime.jsx(RadioContent, { bodyText: parsedData.bodyText, isFormDisabled: isFormDisabled }, key);
11042
11819
  case "checkbox":
@@ -11116,7 +11893,8 @@ const TabularContent = ({ steps: initialSteps, currentTabValue, children, questi
11116
11893
  }
11117
11894
  });
11118
11895
  if (newWidgets.length > 0) {
11119
- setWidgetContent((prev) => [...prev, ...newWidgets]);
11896
+ // a surface sent again (placeholder, then the surface) replaces its widget in place
11897
+ setWidgetContent((prev) => mergeSurfaceWidgets(prev, newWidgets));
11120
11898
  }
11121
11899
  return;
11122
11900
  }
@@ -11247,7 +12025,7 @@ const TabularContent = ({ steps: initialSteps, currentTabValue, children, questi
11247
12025
  let newQuestions = [...questionsRef.current];
11248
12026
  let newQuestionsStepsMap = lodash.cloneDeep(questionsStepsMapRef.current);
11249
12027
  let newStepFormDataMap = lodash.cloneDeep(stepFormDataMapRef.current);
11250
- const newWidgets = [];
12028
+ let newWidgets = [];
11251
12029
  chunks.forEach((data) => {
11252
12030
  if (data.status === "questions") {
11253
12031
  const incomingQuestions = data.widget_data?.[0]?.questions || [];
@@ -11344,10 +12122,8 @@ const TabularContent = ({ steps: initialSteps, currentTabValue, children, questi
11344
12122
  }
11345
12123
  if (data.status === "widget") {
11346
12124
  const widgetItems = isArray$1(data.widget_data) ? data.widget_data : [data.widget_data];
11347
- widgetItems.forEach((item) => {
11348
- if (item)
11349
- newWidgets.push(item);
11350
- });
12125
+ // a surface sent again (placeholder, then the surface) replaces its widget in place
12126
+ newWidgets = mergeSurfaceWidgets(newWidgets, widgetItems.filter(Boolean));
11351
12127
  }
11352
12128
  if (data.status === "content" && data.message) {
11353
12129
  newWidgets.push({ type: "text", response: data.message });
@@ -11474,6 +12250,10 @@ const CombinedContent = ({ botData, props }) => {
11474
12250
  return jsxRuntime.jsx(ImageContent, { bodyText: parsedData.bodyText }, key);
11475
12251
  case "html":
11476
12252
  return jsxRuntime.jsx(HtmlContent, { bodyText: parsedData.bodyText }, key);
12253
+ case "surface_frame":
12254
+ return jsxRuntime.jsx(SurfaceFrameContent, { frame: parsedData.bodyText }, parsedData.bodyText?.surface?.id || key);
12255
+ case "allocation_plan_card":
12256
+ return jsxRuntime.jsx(AllocationPlanCard, { bodyText: parsedData.bodyText }, key);
11477
12257
  default:
11478
12258
  return null;
11479
12259
  }
@@ -11552,6 +12332,8 @@ const BotMessage = ({ botData, state, handleLikeDislike, props }) => {
11552
12332
  return jsxRuntime.jsx(TableContent, { bodyText: botData.bodyText });
11553
12333
  case "graph":
11554
12334
  return jsxRuntime.jsx(GraphContent, { bodyText: botData.bodyText });
12335
+ case "surface_frame":
12336
+ return jsxRuntime.jsx(SurfaceFrameContent, { frame: botData.bodyText });
11555
12337
  case "slider":
11556
12338
  return jsxRuntime.jsx(SliderContent, { bodyText: botData.bodyText, isFormDisabled: botData.isFormDisabled, messageIndex: botData.messageIndex });
11557
12339
  case "select":
@@ -11574,6 +12356,8 @@ const BotMessage = ({ botData, state, handleLikeDislike, props }) => {
11574
12356
  return jsxRuntime.jsx(ImageContent, { bodyText: botData.bodyText });
11575
12357
  case "html":
11576
12358
  return jsxRuntime.jsx(HtmlContent, { bodyText: botData.bodyText });
12359
+ case "allocation_plan_card":
12360
+ return jsxRuntime.jsx(AllocationPlanCard, { bodyText: botData.bodyText });
11577
12361
  case "combined":
11578
12362
  return jsxRuntime.jsx(CombinedContent, { botData: botData, props: props });
11579
12363
  case "dynamic":
@@ -15706,6 +16490,146 @@ const MinimizedChatWidget = ({ onExpand }) => {
15706
16490
  return (jsxRuntime.jsxs("div", { className: classes.widgetContainer, onClick: handleExpandClick, children: [jsxRuntime.jsxs("div", { className: classes.widgetHeader, children: [jsxRuntime.jsxs("div", { className: classes.headerLeft, children: [jsxRuntime.jsx("div", { className: !isCompleted ? classes.headerIconLogoSpin : classes.headerIconLogo, children: jsxRuntime.jsx(SvgMimimizedIconLogo, {}) }), jsxRuntime.jsx("span", { className: classes.headerText, children: isCompleted ? "Action completed" : actionLabel }), !isCompleted && (jsxRuntime.jsx("div", { className: classes.warningIcon, children: jsxRuntime.jsx(SvgStepError, {}) }))] }), jsxRuntime.jsx("button", { className: classes.minimizeBtn, onClick: handleMinimizeClick, "aria-label": "Minimize", children: jsxRuntime.jsx(SvgMinimizeDashIcon, {}) })] }), jsxRuntime.jsx("div", { className: classes.widgetContent, children: jsxRuntime.jsxs("div", { className: stepStatus === "step_form" ? classes.innerContentStepForm : classes.innerContent, children: [jsxRuntime.jsxs("div", { className: classes.innerFirstRow, children: [jsxRuntime.jsx("span", { className: classes.stepHeaderText, title: stepHeader, children: stepHeader }), jsxRuntime.jsx("button", { className: classes.expandBtn, onClick: handleExpandClick, "aria-label": "Expand chatbot", children: jsxRuntime.jsx(SvgExpandFullscreenIcon, {}) })] }), stepSubHeader && (jsxRuntime.jsxs("div", { className: classes.innerSecondRow, children: [jsxRuntime.jsxs("div", { className: stepStatus === "step_form" ? classes.subHeaderPillStepForm : classes.subHeaderPill, children: [stepStatus === "step_form" ? (jsxRuntime.jsx("div", { className: classes.exclamationIcon, children: jsxRuntime.jsx(SvgExclamationIcon, {}) })) : !isCompleted && (jsxRuntime.jsx("div", { className: classes.loaderIcon, children: jsxRuntime.jsx(SvgLoadingCircle, {}) })), jsxRuntime.jsx("span", { className: classes.subHeaderText, title: stepSubHeader, children: stepSubHeader })] }), elapsedTime && (jsxRuntime.jsx("span", { className: classes.timeText, children: elapsedTime }))] }))] }) })] }));
15707
16491
  };
15708
16492
 
16493
+ const PanelHeader = ({ title, actions = {}, onClose, isExpanded, onToggleExpand }) => {
16494
+ const classes = useAllocationPanelStyles();
16495
+ return (jsxRuntime.jsxs("div", { className: classes.panelHeader, children: [jsxRuntime.jsxs("div", { className: classes.panelHeaderLeft, children: [actions.preview && (jsxRuntime.jsx(VisibilityOutlinedIcon, { className: classes.panelHeaderIcon })), jsxRuntime.jsx("span", { className: classes.panelTitle, title: title, children: title })] }), jsxRuntime.jsxs("div", { className: classes.panelHeaderActions, children: [actions.expand_fullscreen && (jsxRuntime.jsx(material.IconButton, { className: classes.panelHeaderActionBtn, size: "small", onClick: onToggleExpand, children: isExpanded ? (jsxRuntime.jsx(CloseFullscreenIcon, { sx: { fontSize: 16 } })) : (jsxRuntime.jsx(OpenInFullIcon, { sx: { fontSize: 16 } })) })), jsxRuntime.jsx(material.IconButton, { className: classes.panelHeaderActionBtn, size: "small", onClick: onClose, children: jsxRuntime.jsx(CloseIcon, { sx: { fontSize: 16 } }) })] })] }));
16496
+ };
16497
+
16498
+ const ReportSummaryCard = ({ reportSummary }) => {
16499
+ const classes = useAllocationPanelStyles();
16500
+ if (!reportSummary)
16501
+ return null;
16502
+ const { badge, description, baseline_plan } = reportSummary;
16503
+ return (jsxRuntime.jsxs("div", { className: classes.reportSummaryCard, children: [badge && (jsxRuntime.jsx("span", { className: classes.reportBadge, children: badge.label })), description && (jsxRuntime.jsx("div", { className: classes.reportDescription, children: description })), baseline_plan && (jsxRuntime.jsxs("div", { className: classes.baselinePlanRow, children: [jsxRuntime.jsxs("span", { children: [baseline_plan.label, ":"] }), baseline_plan.link_url ? (jsxRuntime.jsx("span", { className: classes.baselinePlanLink, onClick: () => {
16504
+ if (baseline_plan.link_url) {
16505
+ window.open(baseline_plan.link_url, "_blank");
16506
+ }
16507
+ }, children: baseline_plan.value })) : (jsxRuntime.jsx("span", { children: baseline_plan.value }))] }))] }));
16508
+ };
16509
+
16510
+ const StructuredComparison = ({ content }) => {
16511
+ const classes = useAllocationPanelStyles();
16512
+ if (!content)
16513
+ return null;
16514
+ const { subtitle, scenario_groups = [] } = content;
16515
+ return (jsxRuntime.jsxs("div", { children: [subtitle && (jsxRuntime.jsx("div", { className: classes.comparisonSubtitle, children: subtitle })), scenario_groups.map((group, groupIndex) => (jsxRuntime.jsxs("div", { children: [jsxRuntime.jsx("div", { className: classes.scenarioLabel, children: group.scenario_label }), (group.comparisons || []).map((comparison, compIndex) => (jsxRuntime.jsxs("div", { className: classes.comparisonCard, children: [jsxRuntime.jsxs("div", { className: classes.comparisonParamRow, children: [jsxRuntime.jsx("span", { className: classes.comparisonParamName, children: comparison.parameter_name }), (comparison.tags || []).map((tag, tagIndex) => (jsxRuntime.jsx("span", { className: classes.comparisonTag, children: tag.label }, `tag-${tagIndex}`)))] }), jsxRuntime.jsxs("div", { className: classes.comparisonValues, children: [jsxRuntime.jsxs("div", { className: classes.comparisonValueBox, children: [jsxRuntime.jsx("div", { className: classes.comparisonValueLabel, children: comparison.baseline?.label }), jsxRuntime.jsx("div", { className: classes.comparisonValueText, children: comparison.baseline?.value })] }), jsxRuntime.jsx(ArrowForwardIcon, { className: classes.comparisonArrow }), jsxRuntime.jsxs("div", { className: classes.comparisonValueBox, children: [jsxRuntime.jsx("div", { className: classes.comparisonValueLabel, children: comparison.new_value?.label }), jsxRuntime.jsx("div", { className: classes.comparisonValueText, children: comparison.new_value?.value })] })] })] }, `comp-${groupIndex}-${compIndex}`)))] }, `group-${groupIndex}`)))] }));
16516
+ };
16517
+
16518
+ const PanelSection = ({ section }) => {
16519
+ const classes = useAllocationPanelStyles();
16520
+ if (!section)
16521
+ return null;
16522
+ const renderContent = () => {
16523
+ switch (section.content_type) {
16524
+ case "html":
16525
+ case "custom_html":
16526
+ return (jsxRuntime.jsx("div", { className: classes.panelHtmlContainer, children: jsxRuntime.jsx(HtmlContent, { bodyText: { content: section.content } }) }));
16527
+ case "structured":
16528
+ return jsxRuntime.jsx(StructuredComparison, { content: section.content });
16529
+ default:
16530
+ return null;
16531
+ }
16532
+ };
16533
+ return (jsxRuntime.jsxs(material.Accordion, { defaultExpanded: section.default_expanded, className: classes.sectionAccordion, disableGutters: true, children: [jsxRuntime.jsx(material.AccordionSummary, { expandIcon: jsxRuntime.jsx(ExpandMoreIcon, {}), className: classes.sectionSummary, children: jsxRuntime.jsx("span", { className: classes.sectionTitle, children: section.title }) }), jsxRuntime.jsx(material.AccordionDetails, { className: classes.sectionDetails, children: renderContent() })] }));
16534
+ };
16535
+
16536
+ const shiftChatbot = (panelEl) => {
16537
+ const chatbot = document.querySelector(".chatbot-component-container");
16538
+ if (!chatbot)
16539
+ return;
16540
+ const panelWidth = panelEl ? panelEl.offsetWidth : 0;
16541
+ const currentLeft = parseFloat(chatbot.style.left) || 0;
16542
+ chatbot.dataset.origLeft = chatbot.style.left;
16543
+ chatbot.style.transition = "left 0.3s ease";
16544
+ chatbot.style.left = (currentLeft - panelWidth) + "px";
16545
+ };
16546
+ const restoreChatbot = () => {
16547
+ const chatbot = document.querySelector(".chatbot-component-container");
16548
+ if (!chatbot)
16549
+ return;
16550
+ if (chatbot.dataset.origLeft) {
16551
+ chatbot.style.transition = "left 0.3s ease";
16552
+ chatbot.style.left = chatbot.dataset.origLeft;
16553
+ delete chatbot.dataset.origLeft;
16554
+ // Clean up transition after animation completes
16555
+ const onEnd = () => {
16556
+ chatbot.style.transition = "";
16557
+ chatbot.removeEventListener("transitionend", onEnd);
16558
+ };
16559
+ chatbot.addEventListener("transitionend", onEnd);
16560
+ }
16561
+ };
16562
+ const AllocationDetailPanel = () => {
16563
+ const classes = useAllocationPanelStyles();
16564
+ const [panelData, setPanelData] = React.useState(null);
16565
+ const [activeFooterAction, setActiveFooterAction] = React.useState(null);
16566
+ const [isExpanded, setIsExpanded] = React.useState(false);
16567
+ const panelRef = React.useRef(null);
16568
+ const handleOpen = React.useCallback((e) => {
16569
+ const { panelData: data } = e.detail || {};
16570
+ if (data) {
16571
+ setPanelData(data);
16572
+ }
16573
+ }, []);
16574
+ const handleClose = React.useCallback(() => {
16575
+ restoreChatbot();
16576
+ setPanelData(null);
16577
+ setIsExpanded(false);
16578
+ }, []);
16579
+ React.useEffect(() => {
16580
+ window.addEventListener("openAllocationDetailPanel", handleOpen);
16581
+ window.addEventListener("closeAllocationDetailPanel", handleClose);
16582
+ return () => {
16583
+ window.removeEventListener("openAllocationDetailPanel", handleOpen);
16584
+ window.removeEventListener("closeAllocationDetailPanel", handleClose);
16585
+ };
16586
+ }, [handleOpen, handleClose]);
16587
+ // Shift the chatbot once the panel has rendered
16588
+ React.useEffect(() => {
16589
+ if (panelData && panelRef.current) {
16590
+ // Use requestAnimationFrame to ensure the panel is laid out
16591
+ requestAnimationFrame(() => {
16592
+ shiftChatbot(panelRef.current);
16593
+ });
16594
+ }
16595
+ }, [panelData]);
16596
+ // Listen for direct clicks on the impact-ui collapse button
16597
+ React.useEffect(() => {
16598
+ if (!panelData)
16599
+ return;
16600
+ const collapseBtn = document.querySelector('button[aria-label="Collapse chatbot"]');
16601
+ if (!collapseBtn)
16602
+ return;
16603
+ const onCollapse = () => handleClose();
16604
+ collapseBtn.addEventListener("click", onCollapse);
16605
+ return () => collapseBtn.removeEventListener("click", onCollapse);
16606
+ }, [panelData, handleClose]);
16607
+ if (!panelData)
16608
+ return null;
16609
+ const footerActions = panelData.footer_actions || [
16610
+ { label: "Purge", variant: "outlined", action: "purge", options: [] },
16611
+ { label: "Finalize Plan", variant: "primary", action: "finalize", options: [] },
16612
+ ];
16613
+ const handleOptionClick = (option) => {
16614
+ setActiveFooterAction(null);
16615
+ window.dispatchEvent(new CustomEvent("allocationPanelAction", {
16616
+ detail: { value: option.value, label: option.label },
16617
+ }));
16618
+ };
16619
+ const handleFooterBtnClick = (btn) => {
16620
+ if (btn.options && btn.options.length > 0) {
16621
+ setActiveFooterAction(activeFooterAction === btn.action ? null : btn.action);
16622
+ }
16623
+ else {
16624
+ console.log("[AllocationPanel] footer action:", btn.action);
16625
+ }
16626
+ };
16627
+ const panel = (jsxRuntime.jsxs("div", { ref: panelRef, className: `${classes.panelContainer} ${isExpanded ? classes.panelExpanded : ""}`, "data-testid": "allocation-detail-panel", children: [jsxRuntime.jsx(PanelHeader, { title: panelData.title, actions: panelData.actions || {}, onClose: handleClose, isExpanded: isExpanded, onToggleExpand: () => setIsExpanded((prev) => !prev) }), jsxRuntime.jsxs("div", { className: classes.panelScrollBody, children: [jsxRuntime.jsx(ReportSummaryCard, { reportSummary: panelData.report_summary }), (panelData.sections || []).map((section) => (jsxRuntime.jsx(PanelSection, { section: section }, section.id)))] }), jsxRuntime.jsxs("div", { className: classes.panelFooter, children: [activeFooterAction && (jsxRuntime.jsx("div", { className: classes.optionsCard, children: footerActions
16628
+ .find((a) => a.action === activeFooterAction)
16629
+ ?.options?.map((opt, idx) => (jsxRuntime.jsxs("button", { className: classes.optionRow, onClick: () => handleOptionClick(opt), children: [jsxRuntime.jsx("span", { className: classes.optionIcon, children: "\u2606" }), opt.label] }, idx))) })), footerActions.map((btn, idx) => (jsxRuntime.jsx("button", { className: btn.variant === "primary" ? classes.footerBtnPrimary : classes.footerBtnOutlined, onClick: () => handleFooterBtnClick(btn), children: btn.label }, idx)))] })] }));
16630
+ return reactDom.createPortal(panel, document.body);
16631
+ };
16632
+
15709
16633
  const SmartBot = (props) => {
15710
16634
  const { userName, partialClose, setPartialClose, forceOpen, customBaseUrl = "", displayQuestions, questions = [] } = props;
15711
16635
  const { showModal, setShowModal, minimizedMode, setMinimizedMode, userInput, setUserInput, position, setPosition, flowType, setFlowType, screenName, setScreenName, questionIndex, setQuestionIndex, currentAppLink, setCurrentAppLink, loader, setLoader, enableRefreshAction, setEnableRefreshAction, refreshLoader, setRefreshLoader, chatDataState, setChatDataState, showExtendedContent, setShowExtendedContent, currentMode, setCurrentMode, selectedModule, setSelectedModule, isCardVisible, setIsCardVisible, templateData, setTemplateData, showAlert, setShowAlert, grabPositionRef, chatDataRef, chatBodyRef, minimizedBtnRef, chatDataScreenLinkRef, navigate, location, dispatch, globalClasses, classes, dateFormat, filterReducerState, activeConversationId, setActiveConversationId, isModuleChanged, setIsModuleChanged, showChatPlaceholder, setShowChatPlaceholder, currentAgentId, setCurrentAgentId, baseUrl = customBaseUrl, setBaseUrl, currentSessionId, setCurrentSessionId, notificationData, agentTaskCompleted, setAgentTaskCompleted, customChatConfig, setCustomChatConfig, setMiddleWareFunction, chatBotInfoRef, chatDataInfoRef, initValue, setInitValue, sessionId, setSessionId, thinkingContent, setThinkingContent, isThinking, setIsThinking, chatId, setChatId, isStop, setIsStop, functionsRef, functionsState, setFunctionsState, thinkingHeaderMessage, setThinkingHeaderMessage, legacyAgentScreen, setLegacyAgentScreen, uniqueChatId, setUniqueChatId, fieldNumber, setFieldNumber, thinkingContext, isModalOpen, setIsModalOpen, utilityList, setUtilityList, isUploadModalOpen, setIsUploadModalOpen, isRefreshTriggered, setIsRefreshTriggered, additionalArgs, setAdditionalArgs, showSavedFilters, setShowSavedFilters, navSessionId, setNavSessionId, renameOpen, setRenameOpen, renameTargetId, setRenameTargetId, renameValue, setRenameValue, deleteOpen, setDeleteOpen, deleteTargetId, setDeleteTargetId, } = useChatState();
@@ -15833,6 +16757,7 @@ const SmartBot = (props) => {
15833
16757
  // Minimize the chat window when the user follows an in-app link from a bot response
15834
16758
  const handleMinimizeRequest = () => {
15835
16759
  setPartialClose(true);
16760
+ window.dispatchEvent(new CustomEvent("closeAllocationDetailPanel"));
15836
16761
  };
15837
16762
  window.addEventListener("stepFormStreamStart", handleStepFormStreamStart);
15838
16763
  window.addEventListener("stepFormStreamEnd", handleStepFormStreamEnd);
@@ -16491,7 +17416,7 @@ const SmartBot = (props) => {
16491
17416
  fetchLegacyAgentInfo(); //Disabled temporarily since this was causing issue on homepage first render
16492
17417
  }
16493
17418
  }, [location]);
16494
- const handleSendMessage = async (userInput, userExplicitInput = {}, textWithColumnNames = "") => {
17419
+ const handleSendMessage = async (userInput, userExplicitInput = {}, textWithColumnNames = "", uiContext = null) => {
16495
17420
  try {
16496
17421
  // if (localStorage.getItem("isStreaming") === "true") {
16497
17422
  // displaySnackMessages(
@@ -16555,6 +17480,7 @@ const SmartBot = (props) => {
16555
17480
  userExplicitInput: userExplicitInput,
16556
17481
  textWithColumnNames: textWithColumnNames,
16557
17482
  answerMode: answerMode,
17483
+ ...(uiContext ? { uiContext } : {}),
16558
17484
  };
16559
17485
  // if(!isEmpty(userInput)) {
16560
17486
  // Clear the previous response's completed state so the incoming
@@ -16604,12 +17530,25 @@ const SmartBot = (props) => {
16604
17530
  sessionStorage.removeItem("stepForm_chatId");
16605
17531
  // dispatch(setChatbotContext({}));
16606
17532
  setUserInput(params?.text);
16607
- handleSendMessage(params?.text, params?.userExplicitInput, params?.textWithColumnNames);
17533
+ handleSendMessage(params?.text, params?.userExplicitInput, params?.textWithColumnNames, params?.uiContext);
16608
17534
  }
16609
17535
  catch (error) {
16610
17536
  console.error("onSendIconClick error", error);
16611
17537
  }
16612
17538
  };
17539
+ // A follow-up asked from a generated surface (SurfaceFrameContent's "iris:prompt"): sent as the user's next
17540
+ // message, with the surface's context as ui_context. Not while a turn runs or a form waits for its Submit.
17541
+ const surfacePromptRef = React.useRef(null);
17542
+ surfacePromptRef.current = (detail) => {
17543
+ if (!detail?.text || isStop || !lodash.isEmpty(chatbotContext))
17544
+ return;
17545
+ onSendIconClick({ text: detail.text, uiContext: detail.uiContext });
17546
+ };
17547
+ React.useEffect(() => {
17548
+ const onSurfacePrompt = (event) => surfacePromptRef.current?.(event.detail);
17549
+ window.addEventListener("iris:prompt", onSurfacePrompt);
17550
+ return () => window.removeEventListener("iris:prompt", onSurfacePrompt);
17551
+ }, []);
16613
17552
  const onStopIconClick = (params) => {
16614
17553
  try {
16615
17554
  setIsStop(false);
@@ -16843,9 +17782,35 @@ const SmartBot = (props) => {
16843
17782
  if (!root)
16844
17783
  return;
16845
17784
  const collapseBtn = root.querySelector('button[aria-label="Collapse chatbot"]');
16846
- if (collapseBtn)
17785
+ if (collapseBtn) {
16847
17786
  collapseBtn.click();
17787
+ window.dispatchEvent(new CustomEvent("closeAllocationDetailPanel"));
17788
+ }
16848
17789
  }, []);
17790
+ // Expand the chatbot to its full docked view by programmatically clicking
17791
+ // impact-ui's "Expand chatbot" button. Used when the allocation panel opens
17792
+ // from minimized state.
17793
+ const expandChatBotIfCollapsed = React.useCallback(() => {
17794
+ setShowModal(true);
17795
+ setPartialClose(false);
17796
+ // Use a short delay so the chatbot DOM renders before we look for the button
17797
+ setTimeout(() => {
17798
+ const root = smartBotWrapperRef.current;
17799
+ if (!root)
17800
+ return;
17801
+ const expandBtn = root.querySelector('button[aria-label="Expand chatbot"]');
17802
+ if (expandBtn) {
17803
+ expandBtn.click();
17804
+ }
17805
+ }, 100);
17806
+ }, []);
17807
+ // Listen for smartBotMaximize events (e.g. from allocation plan card)
17808
+ React.useEffect(() => {
17809
+ window.addEventListener("smartBotMaximize", expandChatBotIfCollapsed);
17810
+ return () => {
17811
+ window.removeEventListener("smartBotMaximize", expandChatBotIfCollapsed);
17812
+ };
17813
+ }, [expandChatBotIfCollapsed]);
16849
17814
  // Auto-collapse to draggable mode when the user interacts outside the bot.
16850
17815
  React.useEffect(() => {
16851
17816
  const handleOutsideInteraction = (e) => {
@@ -16867,6 +17832,9 @@ const SmartBot = (props) => {
16867
17832
  // Ignore clicks inside the expanded table modal portal
16868
17833
  if (e.target.closest?.(".test-modal"))
16869
17834
  return;
17835
+ // Ignore clicks inside the allocation detail panel
17836
+ if (e.target.closest?.('[data-testid="allocation-detail-panel"]'))
17837
+ return;
16870
17838
  collapseChatBotIfExpanded();
16871
17839
  };
16872
17840
  document.addEventListener("mousedown", handleOutsideInteraction, true);
@@ -16993,6 +17961,7 @@ const SmartBot = (props) => {
16993
17961
  dispatch(smartBotActions.setMinimizedStreamData(null));
16994
17962
  }
16995
17963
  setPartialClose(true);
17964
+ window.dispatchEvent(new CustomEvent("closeAllocationDetailPanel"));
16996
17965
  }
16997
17966
  },
16998
17967
  // assistantChats={assistantChats}
@@ -17023,7 +17992,8 @@ const SmartBot = (props) => {
17023
17992
  setChatBotWidth(params);
17024
17993
  }, onMinimiseChatBot: () => {
17025
17994
  setPartialClose(true);
17026
- } })] })] }));
17995
+ window.dispatchEvent(new CustomEvent("closeAllocationDetailPanel"));
17996
+ } })] }), jsxRuntime.jsx(AllocationDetailPanel, {})] }));
17027
17997
  };
17028
17998
 
17029
17999
  exports.default = SmartBot;